repo_name
stringlengths
7
79
path
stringlengths
8
206
copies
stringclasses
36 values
size
stringlengths
2
6
content
stringlengths
55
523k
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
7.18
99.5
line_max
int64
16
979
alpha_frac
float64
0.3
0.87
ratio
float64
2.01
8.07
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
inorichi/tachiyomi-extensions
multisrc/overrides/madara/yaoitoshokan/src/YaoiToshokan.kt
1
3163
package eu.kanade.tachiyomi.extension.pt.yaoitoshokan import eu.kanade.tachiyomi.annotations.Nsfw import eu.kanade.tachiyomi.lib.ratelimit.RateLimitInterceptor import eu.kanade.tachiyomi.multisrc.madara.Madara import eu.kanade.tachiyomi.source.model.Page import okhttp3.OkHttpClient import org.jsoup.nodes.Document import java.text.SimpleDateFormat import java.util.Locale import java.util.concurrent.TimeUnit @Nsfw class YaoiToshokan : Madara( "Yaoi Toshokan", "https://yaoitoshokan.net", "pt-BR", SimpleDateFormat("dd MMM yyyy", Locale("pt", "BR")) ) { override val client: OkHttpClient = super.client.newBuilder() .addInterceptor(RateLimitInterceptor(1, 1, TimeUnit.SECONDS)) .build() // Page has custom link to scan website. override val popularMangaUrlSelector = "div.post-title a:not([target])" override fun pageListParse(document: Document): List<Page> { return document.select(pageListParseSelector) .mapIndexed { index, element -> // Had to add trim because of white space in source. val imageUrl = element.select("img").attr("data-src").trim() Page(index, document.location(), imageUrl) } } // [...document.querySelectorAll('input[name="genre[]"]')] // .map(x => `Genre("${document.querySelector('label[for=' + x.id + ']').innerHTML.trim()}", "${x.value}")`) // .join(',\n') override fun getGenreList(): List<Genre> = listOf( Genre("Ação", "acao"), Genre("Adulto", "adulto"), Genre("Bara", "bara"), Genre("BDSM", "bdsm"), Genre("Comédia", "comedia"), Genre("Comic", "comic"), Genre("Cotidiano", "cotidiano"), Genre("Crossdress", "gender-bender"), Genre("Doujinshi", "doujinshi"), Genre("Drama", "drama"), Genre("Ecchi", "ecchi"), Genre("Esportes", "esportes"), Genre("Fantasia", "fantasia"), Genre("Fury", "fury"), Genre("Futanari", "futanari"), Genre("Gender Bender", "gender-bender-2"), Genre("Histórico", "historico"), Genre("Horror", "horror"), Genre("Incesto", "incesto"), Genre("Mafia", "mafia"), Genre("Manga", "manga"), Genre("Manhua", "manhua"), Genre("Manhwa", "manhwa"), Genre("Mistério", "misterio"), Genre("Mpreg", "mpreg"), Genre("Omegaverse", "omegaverse"), Genre("One shot", "one-shot"), Genre("Poliamor", "poliamor"), Genre("Psicológico", "psicologico"), Genre("Romance", "romance"), Genre("Salaryman", "salaryman"), Genre("Sci-fi", "sci-fi"), Genre("Seinen", "seinen"), Genre("Shocaton", "shocaton"), Genre("Shoujo", "shoujo"), Genre("Shoujo Ai", "shoujo-ai"), Genre("Shounen", "shounen"), Genre("Shounen Ai", "shounen-ai"), Genre("Smut", "smut"), Genre("Sobrenatural", "sobrenatural"), Genre("Tragédia", "tragedia"), Genre("Vampiros", "vampiros"), Genre("Vida Escolar", "vida-escolar"), Genre("Yaoi", "yaoi") ) }
apache-2.0
739e565b11b2be8959a1735fdf4c0fa2
35.697674
114
0.589354
3.682614
false
false
false
false
Etik-Tak/backend
src/main/kotlin/dk/etiktak/backend/model/product/ProductTag.kt
1
2823
// Copyright (c) 2017, Daniel Andersen ([email protected]) // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // 2. 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. // 3. The name of the author may not 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. /** * Represents a product tag, ex. vegetarian. */ package dk.etiktak.backend.model.product import dk.etiktak.backend.model.BaseModel import dk.etiktak.backend.model.recommendation.ProductTagRecommendation import org.springframework.format.annotation.DateTimeFormat import java.util.* import javax.persistence.* @Entity(name = "product_tags") class ProductTag : BaseModel() { @Id @GeneratedValue(strategy = GenerationType.AUTO) @Column(name = "product_tag_id") var id: Long = 0 @Column(name = "uuid", nullable = false, unique = true) var uuid: String = "" @Column(name = "name") var name: String = "" @ManyToMany(mappedBy = "productTags", fetch = FetchType.LAZY) var products: MutableSet<Product> = HashSet() @OneToMany(mappedBy = "productTag", fetch = FetchType.LAZY) var recommendations: MutableList<ProductTagRecommendation> = ArrayList() @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") var creationTime = Date() @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") var modificationTime = Date() @PreUpdate fun preUpdate() { modificationTime = Date() } @PrePersist fun prePersist() { val now = Date() creationTime = now modificationTime = now } }
bsd-3-clause
2e9c10afaef2e7ba7464706d78f07beb
35.675325
83
0.728303
4.397196
false
false
false
false
PassionateWsj/YH-Android
app/src/main/java/com/intfocus/template/subject/seven/concernlist/ConcernListActivity.kt
1
6019
package com.intfocus.template.subject.seven.concernlist import android.content.Context import android.content.Intent import android.os.Bundle import android.support.v4.content.ContextCompat import android.text.Editable import android.text.TextWatcher import android.view.View import android.view.inputmethod.InputMethodManager import android.widget.TextView import com.intfocus.template.R import com.intfocus.template.constant.Params import com.intfocus.template.constant.ToastColor import com.intfocus.template.model.response.attention.AttentionItem import com.intfocus.template.scanner.BarCodeScannerActivity import com.intfocus.template.subject.seven.listener.ConcernListItemClickListener import com.intfocus.template.ui.BaseActivity import com.intfocus.template.util.ToastUtils import kotlinx.android.synthetic.main.activity_attention_list.* /** * **************************************************** * author jameswong * created on: 17/12/18 上午11:14 * e-mail: [email protected] * name: 关注列表 * desc: 关注/取消关注功能 * **************************************************** */ class ConcernListActivity : BaseActivity(), ConcernListContract.View, ConcernListItemClickListener { companion object { val REQUEST_CODE = 2 val RESPONSE_CODE = 201 } override lateinit var presenter: ConcernListContract.Presenter private lateinit var mItemAdapter: ConcernListItemAdapter var loadConcernedData: Boolean = false override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_attention_list) presenter = ConcernListPresenter(ConcernListModelImpl.getInstance(), this) initAdapter() initData() initListener() } private fun initAdapter() { mItemAdapter = ConcernListItemAdapter(this, this) lv_attention_list_item.adapter = mItemAdapter } private fun initData() { presenter.loadData(loadConcernedData) } private fun initListener() { // 隐藏软键盘 rl_attention_list_layout.setOnTouchListener { _, _ -> hideKeyboard() false } // item 点击监听 lv_attention_list_item.setOnItemClickListener { _, _, _, _ -> hideKeyboard() } // 文本输入框内容监听 ed_attention_list_search.addTextChangedListener(object : TextWatcher { override fun afterTextChanged(p0: Editable?) { presenter.loadData(p0.toString(), loadConcernedData) } override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) { } override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) { } }) } override fun onResultFailure(e: Throwable) { mItemAdapter.clearData() } override fun onResultSuccess(data: List<AttentionItem>) { mItemAdapter.setData(data) } override fun itemClick(pos: Int) { val attentionItem = mItemAdapter.getSelectItem(pos) presenter.concernOrCancelConcern(attentionItem.attention_item_id, attentionItem.attention_item_name) hideKeyboard() } override fun concernOrCancelConcernResult(isConcernSuccess: Boolean) { if (isConcernSuccess) { ToastUtils.show(this, "关注成功", ToastColor.SUCCESS) } else { ToastUtils.show(this, "取消关注成功") } } fun onClick(view: View) { hideKeyboard() when (view.id) { R.id.tv_attention_list_attentioned_btn -> { changeStyle(tv_attention_list_attentioned_btn, tv_attention_list_attention_btn) // rl_attention_list_input_container.visibility = View.GONE loadConcernedData = true presenter.loadData(ed_attention_list_search.text.toString(), loadConcernedData) } R.id.tv_attention_list_attention_btn -> { changeStyle(tv_attention_list_attention_btn, tv_attention_list_attentioned_btn) // rl_attention_list_input_container.visibility = View.VISIBLE loadConcernedData = false presenter.loadData(ed_attention_list_search.text.toString(), loadConcernedData) } R.id.iv_attention_list_scan -> { intent = Intent(this, BarCodeScannerActivity::class.java) Intent.FLAG_ACTIVITY_SINGLE_TOP intent.putExtra(BarCodeScannerActivity.INTENT_FOR_RESULT, true) startActivityForResult(intent, REQUEST_CODE) } } } private fun changeStyle(currentTextView: TextView, standbyTextView: TextView) { currentTextView.setTextColor(ContextCompat.getColor(this, R.color.co10_syr)) currentTextView.background = ContextCompat.getDrawable(this, R.drawable.bg_radius_fill_blue) standbyTextView.setTextColor(ContextCompat.getColor(this, R.color.co3_syr)) standbyTextView.background = ContextCompat.getDrawable(this, R.drawable.bg_radius_sold) } /** * 返回监听 */ fun backPress(v: View) { hideKeyboard() setResult(RESPONSE_CODE) finish() } /** * 隐藏软件盘 */ fun hideKeyboard() { val imm = getSystemService( Context.INPUT_METHOD_SERVICE) as InputMethodManager imm.hideSoftInputFromWindow(this.currentFocus .windowToken, InputMethodManager.HIDE_NOT_ALWAYS) } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) if (requestCode == REQUEST_CODE && resultCode == BarCodeScannerActivity.RESULT_CODE_SCAN) { data?.getStringExtra(Params.CODE_INFO)?.let { ed_attention_list_search.setText(it.toCharArray(), 0, it.length) } } } }
gpl-3.0
4b7664cad6e421f20c79c299382bd0e3
34.638554
108
0.651733
4.410887
false
false
false
false
dhleong/ideavim
test/org/jetbrains/plugins/ideavim/action/change/change/ChangeVisualActionTest.kt
1
6165
/* * IdeaVim - Vim emulator for IDEs based on the IntelliJ platform * Copyright (C) 2003-2019 The IdeaVim authors * * 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 2 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/>. */ @file:Suppress("RemoveCurlyBracesFromTemplate") package org.jetbrains.plugins.ideavim.action.change.change import com.maddyhome.idea.vim.command.CommandState import com.maddyhome.idea.vim.helper.StringHelper.parseKeys import com.maddyhome.idea.vim.helper.VimBehaviorDiffers import org.jetbrains.plugins.ideavim.VimTestCase class ChangeVisualActionTest : VimTestCase() { fun `test multiple line change`() { val keys = parseKeys("VjcHello<esc>") val before = """ ${c}A Discovery I found it in a legendary land all rocks and lavender and tufted grass, where it was settled on some sodden sand hard by the torrent of a mountain pass. """.trimIndent() val after = """ Hello I found it in a legendary land all rocks and lavender and tufted grass, where it was settled on some sodden sand hard by the torrent of a mountain pass. """.trimIndent() doTest(keys, before, after, CommandState.Mode.COMMAND, CommandState.SubMode.NONE) } fun `test multiple line change in text middle`() { val keys = parseKeys("Vjc") val before = """ A Discovery ${c}I found it in a legendary land all rocks and lavender and tufted grass, where it was settled on some sodden sand hard by the torrent of a mountain pass. """.trimIndent() val after = """ A Discovery ${c} where it was settled on some sodden sand hard by the torrent of a mountain pass. """.trimIndent() doTest(keys, before, after, CommandState.Mode.INSERT, CommandState.SubMode.NONE) } @VimBehaviorDiffers(originalVimAfter = """ A Discovery I found it in a legendary land all rocks and lavender and tufted grass, ${c} """) fun `test multiple line change till the end`() { val keys = parseKeys("Vjc") val before = """ A Discovery I found it in a legendary land all rocks and lavender and tufted grass, ${c}where it was settled on some sodden sand hard by the torrent of a mountain pass. """.trimIndent() val after = """ A Discovery I found it in a legendary land all rocks and lavender and tufted grass, ${c} """.trimIndent() doTest(keys, before, after, CommandState.Mode.INSERT, CommandState.SubMode.NONE) } @VimBehaviorDiffers(originalVimAfter = """ A Discovery I found it in a legendary land all rocks and lavender and tufted grass, ${c} """) fun `test multiple line change till the end with two new lines`() { val keys = parseKeys("Vjc") val before = """ A Discovery I found it in a legendary land all rocks and lavender and tufted grass, ${c}where it was settled on some sodden sand hard by the torrent of a mountain pass. """.trimIndent() val after = """ A Discovery I found it in a legendary land all rocks and lavender and tufted grass, ${c} """.trimIndent() doTest(keys, before, after, CommandState.Mode.INSERT, CommandState.SubMode.NONE) } fun `test change with dollar motion`() { val keys = parseKeys("<C-V>3j$", "c", "Hello<Esc>") val before = """ A Discovery I |${c}found it in a legendary land al|l rocks and lavender and tufted grass,[ additional symbols] wh|ere it was settled on some sodden sand ha|rd by the torrent of a mountain pass. """.trimIndent() val after = """ A Discovery I |Hello al|Hello wh|Hello ha|Hello """.trimIndent() doTest(keys, before, after, CommandState.Mode.COMMAND, CommandState.SubMode.NONE) } fun `test replace first line`() { val keys = parseKeys("VcHello<esc>") val before = "${c}A Discovery" val after = "Hello" doTest(keys, before, after, CommandState.Mode.COMMAND, CommandState.SubMode.NONE) } fun `test change visual action`() { typeTextInFile(parseKeys("v2lc", "aaa", "<ESC>"), "abcd${c}ffffff${c}abcde${c}aaaa\n") assertMode(CommandState.Mode.COMMAND) myFixture.checkResult("abcdaa${c}afffaa${c}adeaa${c}aa\n") } // VIM-1379 |CTRL-V| |j| |v_b_c| fun `test change visual block with empty line in the middle`() { doTest(parseKeys("ll", "<C-V>", "ljjc", "_quux_", "<Esc>"), "foo foo\n" + "\n" + "bar bar\n", ("fo_quux_foo\n" + "\n" + "ba_quux_bar\n"), CommandState.Mode.COMMAND, CommandState.SubMode.NONE) } // VIM-1379 |CTRL-V| |j| |v_b_c| fun `test change visual block with shorter line in the middle`() { doTest(parseKeys("ll", "<C-V>", "ljjc", "_quux_", "<Esc>"), "foo foo\n" + "x\n" + "bar bar\n", ("fo_quux_foo\n" + "x\n" + "ba_quux_bar\n"), CommandState.Mode.COMMAND, CommandState.SubMode.NONE) } }
gpl-2.0
58c856f492a0eaeda26f9d98dd29752c
30.141414
85
0.58605
4.363057
false
true
false
false
mgramin/sql-boot
src/main/kotlin/com/github/mgramin/sqlboot/model/resourcetype/impl/sql/SqlResourceType.kt
1
4807
/* * The MIT License (MIT) * <p> * Copyright (c) 2016-2019 Maksim Gramin * <p> * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * <p> * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * <p> * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.github.mgramin.sqlboot.model.resourcetype.impl.sql import com.github.mgramin.sqlboot.model.connection.DbConnection import com.github.mgramin.sqlboot.model.resource.DbResource import com.github.mgramin.sqlboot.model.resource.impl.DbResourceImpl import com.github.mgramin.sqlboot.model.resourcetype.ResourceType import com.github.mgramin.sqlboot.model.uri.Uri import com.github.mgramin.sqlboot.model.uri.impl.DbUri import com.github.mgramin.sqlboot.sql.select.SelectQuery import com.github.mgramin.sqlboot.sql.select.impl.SimpleSelectQuery import com.github.mgramin.sqlboot.sql.select.wrappers.JdbcSelectQuery import com.github.mgramin.sqlboot.sql.select.wrappers.OrderedSelectQuery import com.github.mgramin.sqlboot.sql.select.wrappers.PaginatedSelectQuery import com.github.mgramin.sqlboot.template.generator.impl.GroovyTemplateGenerator import org.apache.commons.lang3.StringUtils.strip import reactor.core.publisher.Flux /** * Created by MGramin on 12.07.2017. */ class SqlResourceType( private val aliases: List<String>, sql: String, private val connections: List<DbConnection> ) : ResourceType { private val simpleSelectQuery = SimpleSelectQuery(GroovyTemplateGenerator(sql)) override fun aliases(): List<String> { return aliases } override fun path(): List<String> { return simpleSelectQuery.columns().keys .filter { v -> v.startsWith("@") } .map { v -> strip(v, "@") } } override fun read(uri: Uri): Flux<DbResource> { val mergeSequential: Flux<Map<String, Any>> = Flux.merge( connections .asSequence() .map { connection -> return@map createQuery(uri, connection).execute(hashMapOf("uri" to uri)) .map<Map<String, Any>?> { val mutableMap = it.toMutableMap() mutableMap["database"] = connection.name() mutableMap } } .toList() ) return mergeSequential .map { o -> val path = o.entries .filter { v -> v.key.startsWith("@") } .map { it.value.toString() } val name = path[path.size - 1] val headers = o.entries .map { strip(it.key, "@") to it.value } .toMap() DbResourceImpl(name, this, DbUri(headers["database"].toString(), this.name(), path), headers) as DbResource } } override fun metaData(): Map<String, String> { val columns = simpleSelectQuery.columns() val newColumns = columns.toMutableMap() newColumns["database"] = """{"label": "Database", "description": "Database name", "visible": true}""" return newColumns } private fun createQuery(uri: Uri, connection: DbConnection): SelectQuery { return JdbcSelectQuery( PaginatedSelectQuery( OrderedSelectQuery( simpleSelectQuery, uri.orderedColumns()), uri, connection.paginationQueryTemplate()), dataSource = connection.getDataSource()) } }
mit
e7dcb16c6aa38d40bc08af4349647dea
42.306306
127
0.603911
4.787849
false
false
false
false
Heiner1/AndroidAPS
danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacketBolusSet24CIRCFArray.kt
1
2038
package info.nightscout.androidaps.danars.comm import dagger.android.HasAndroidInjector import info.nightscout.androidaps.dana.DanaPump import info.nightscout.androidaps.danars.encryption.BleEncryption import info.nightscout.androidaps.interfaces.GlucoseUnit import info.nightscout.androidaps.interfaces.Profile import info.nightscout.shared.logging.LTag import javax.inject.Inject import kotlin.math.round class DanaRSPacketBolusSet24CIRCFArray( injector: HasAndroidInjector, private val profile: Profile? ) : DanaRSPacket(injector) { @Inject lateinit var danaPump: DanaPump init { opCode = BleEncryption.DANAR_PACKET__OPCODE_BOLUS__SET_24_CIR_CF_ARRAY aapsLogger.debug(LTag.PUMPCOMM, "New message") } override fun getRequestParams(): ByteArray { val request = ByteArray(96) profile ?: return request // profile is null only in hash table val cfStart = 24 * 2 for (i in 0..23) { var isf = profile.getIsfMgdlTimeFromMidnight(i * 3600) if (danaPump.units == DanaPump.UNITS_MMOL) { isf = Profile.fromMgdlToUnits(isf, GlucoseUnit.MMOL) isf *= 100 } val ic = profile.getIcTimeFromMidnight(i * 3600) request[2 * i] = (round(ic).toInt() and 0xff).toByte() request[2 * i + 1] = (round(ic).toInt() ushr 8 and 0xff).toByte() request[cfStart + 2 * i] = (round(isf).toInt() and 0xff).toByte() request[cfStart + 2 * i + 1] = (round(isf).toInt() ushr 8 and 0xff).toByte() } return request } override fun handleMessage(data: ByteArray) { val result = intFromBuff(data, 0, 1) @Suppress("LiftReturnOrAssignment") if (result == 0) { aapsLogger.debug(LTag.PUMPCOMM, "Result OK") failed = false } else { aapsLogger.error("Result Error: $result") failed = true } } override val friendlyName: String = "BOLUS__SET_24_CIR_CF_ARRAY" }
agpl-3.0
667ace3f10513a76ce13b9ecd8294f6a
35.410714
88
0.640334
4.125506
false
false
false
false
hurricup/intellij-community
platform/configuration-store-impl/src/SchemeManagerImpl.kt
1
33993
/* * Copyright 2000-2015 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.configurationStore import com.intellij.openapi.application.AccessToken import com.intellij.openapi.application.WriteAction import com.intellij.openapi.application.ex.DecodeDefaultsUtil import com.intellij.openapi.application.runWriteAction import com.intellij.openapi.components.RoamingType import com.intellij.openapi.components.impl.stores.FileStorageCoreUtil import com.intellij.openapi.components.impl.stores.FileStorageCoreUtil.DEFAULT_EXT import com.intellij.openapi.extensions.AbstractExtensionPointBean import com.intellij.openapi.options.* import com.intellij.openapi.project.ProjectBundle import com.intellij.openapi.util.Condition import com.intellij.openapi.util.JDOMUtil import com.intellij.openapi.util.WriteExternalException import com.intellij.openapi.util.io.FileUtil import com.intellij.openapi.util.text.StringUtilRt import com.intellij.openapi.vfs.* import com.intellij.openapi.vfs.newvfs.BulkFileListener import com.intellij.openapi.vfs.newvfs.NewVirtualFile import com.intellij.openapi.vfs.newvfs.events.VFileContentChangeEvent import com.intellij.openapi.vfs.newvfs.events.VFileCreateEvent import com.intellij.openapi.vfs.newvfs.events.VFileDeleteEvent import com.intellij.openapi.vfs.newvfs.events.VFileEvent import com.intellij.util.* import com.intellij.util.containers.ConcurrentList import com.intellij.util.containers.ContainerUtil import com.intellij.util.io.URLUtil import com.intellij.util.messages.MessageBus import com.intellij.util.text.UniqueNameGenerator import gnu.trove.THashSet import org.jdom.Document import org.jdom.Element import org.xmlpull.mxp1.MXParser import org.xmlpull.v1.XmlPullParser import java.io.File import java.io.IOException import java.io.InputStream import java.nio.file.Path import java.util.* import java.util.concurrent.atomic.AtomicBoolean import java.util.concurrent.atomic.AtomicReference import java.util.function.Function class SchemeManagerImpl<T : Scheme, MUTABLE_SCHEME : T>(val fileSpec: String, private val processor: SchemeProcessor<T, MUTABLE_SCHEME>, private val provider: StreamProvider?, private val ioDirectory: Path, val roamingType: RoamingType = RoamingType.DEFAULT, val presentableName: String? = null, private val isUseOldFileNameSanitize: Boolean = false, private val messageBus: MessageBus? = null) : SchemeManager<T>(), SafeWriteRequestor { private val isLoadingSchemes = AtomicBoolean() private val schemesRef = AtomicReference(ContainerUtil.createLockFreeCopyOnWriteList<T>() as ConcurrentList<T>) private val schemes: ConcurrentList<T> get() = schemesRef.get() private val readOnlyExternalizableSchemes = ContainerUtil.newConcurrentMap<String, T>() /** * Schemes can be lazy loaded, so, client should be able to set current scheme by name, not only by instance. */ private @Volatile var currentPendingSchemeName: String? = null private var currentScheme: T? = null private var cachedVirtualDirectory: VirtualFile? = null private val schemeExtension: String private val updateExtension: Boolean private val filesToDelete = ContainerUtil.newConcurrentSet<String>() // scheme could be changed - so, hashcode will be changed - we must use identity hashing strategy private val schemeToInfo = ContainerUtil.newConcurrentMap<T, ExternalInfo>(ContainerUtil.identityStrategy()) private val useVfs = messageBus != null init { if (processor is SchemeExtensionProvider) { schemeExtension = processor.schemeExtension updateExtension = processor.isUpgradeNeeded } else { schemeExtension = FileStorageCoreUtil.DEFAULT_EXT updateExtension = false } if (useVfs && (provider == null || !provider.isApplicable(fileSpec, roamingType))) { try { refreshVirtualDirectoryAndAddListener() } catch (e: Throwable) { LOG.error(e) } } } private inner class SchemeFileTracker() : BulkFileListener.Adapter() { private fun isMy(file: VirtualFile) = isMy(file.nameSequence) private fun isMy(name: CharSequence) = name.endsWith(schemeExtension, ignoreCase = true) && (processor !is LazySchemeProcessor || processor.isSchemeFile(name)) override fun after(events: MutableList<out VFileEvent>) { eventLoop@ for (event in events) { if (event.requestor is SchemeManagerImpl<*, *>) { continue } fun isMyDirectory(parent: VirtualFile) = cachedVirtualDirectory.let { if (it == null) ioDirectory.systemIndependentPath == parent.path else it == parent } when (event) { is VFileContentChangeEvent -> { if (!isMy(event.file) || !isMyDirectory(event.file.parent)) { continue@eventLoop } val oldCurrentScheme = currentScheme findExternalizableSchemeByFileName(event.file.name)?.let { removeScheme(it) processor.onSchemeDeleted(it) } updateCurrentScheme(oldCurrentScheme, readSchemeFromFile(event.file)?.let { processor.initScheme(it) processor.onSchemeAdded(it) it }) } is VFileCreateEvent -> { if (isMy(event.childName)) { if (isMyDirectory(event.parent)) { event.file?.let { schemeCreatedExternally(it) } } } else if (event.file?.isDirectory ?: false) { val dir = virtualDirectory if (event.file == dir) { for (file in dir!!.children) { if (isMy(file)) { schemeCreatedExternally(file) } } } } } is VFileDeleteEvent -> { val oldCurrentScheme = currentScheme if (event.file.isDirectory) { val dir = virtualDirectory if (event.file == dir) { cachedVirtualDirectory = null removeExternalizableSchemes() } } else if (isMy(event.file) && isMyDirectory(event.file.parent)) { val scheme = findExternalizableSchemeByFileName(event.file.name) ?: continue@eventLoop removeScheme(scheme) processor.onSchemeDeleted(scheme) } updateCurrentScheme(oldCurrentScheme) } } } } private fun schemeCreatedExternally(file: VirtualFile) { val readScheme = readSchemeFromFile(file) if (readScheme != null) { processor.initScheme(readScheme) processor.onSchemeAdded(readScheme) } } private fun updateCurrentScheme(oldScheme: T?, newScheme: T? = null) { if (currentScheme != null) { return } if (oldScheme != currentScheme) { val scheme = newScheme ?: schemes.firstOrNull() currentPendingSchemeName = null currentScheme = scheme // must be equals by reference if (oldScheme !== scheme) { processor.onCurrentSchemeSwitched(oldScheme, scheme) } } else if (newScheme != null) { processPendingCurrentSchemeName(newScheme) } } } private fun refreshVirtualDirectoryAndAddListener() { // store refreshes root directory, so, we don't need to use refreshAndFindFile val directory = LocalFileSystem.getInstance().findFileByPath(ioDirectory.systemIndependentPath) ?: return this.cachedVirtualDirectory = directory directory.children if (directory is NewVirtualFile) { directory.markDirty() } directory.refresh(true, false) } override fun loadBundledScheme(resourceName: String, requestor: Any, convertor: ThrowableConvertor<Element, T, Throwable>) { try { val url = if (requestor is AbstractExtensionPointBean) requestor.loaderForClass.getResource(resourceName) else DecodeDefaultsUtil.getDefaults(requestor, resourceName) if (url == null) { LOG.error("Cannot read scheme from $resourceName") return } val element = loadElement(URLUtil.openStream(url)) val scheme = convertor.convert(element) if (processor.isExternalizable(scheme)) { val fileName = PathUtilRt.getFileName(url.path) val extension = getFileExtension(fileName, true) val info = ExternalInfo(fileName.substring(0, fileName.length - extension.length), extension) info.digest = element.digest() info.schemeName = scheme.name val oldInfo = schemeToInfo.put(scheme, info) LOG.assertTrue(oldInfo == null) val oldScheme = readOnlyExternalizableSchemes.put(scheme.name, scheme) if (oldScheme != null) { LOG.warn("Duplicated scheme ${scheme.name} - old: $oldScheme, new $scheme") } } schemes.add(scheme) } catch (e: Throwable) { LOG.error("Cannot read scheme from $resourceName", e) } } private fun getFileExtension(fileName: CharSequence, allowAny: Boolean): String { return if (StringUtilRt.endsWithIgnoreCase(fileName, schemeExtension)) { schemeExtension } else if (StringUtilRt.endsWithIgnoreCase(fileName, DEFAULT_EXT)) { DEFAULT_EXT } else if (allowAny) { PathUtil.getFileExtension(fileName.toString())!! } else { throw IllegalStateException("Scheme file extension $fileName is unknown, must be filtered out") } } override fun loadSchemes(): Collection<T> { if (!isLoadingSchemes.compareAndSet(false, true)) { throw IllegalStateException("loadSchemes is already called") } try { val filesToDelete = THashSet<String>() val oldSchemes = schemes val schemes = oldSchemes.toMutableList() val newSchemesOffset = schemes.size if (provider != null && provider.isApplicable(fileSpec, roamingType)) { provider.processChildren(fileSpec, roamingType, { canRead(it) }) { name, input, readOnly -> catchAndLog(name) { val scheme = loadScheme(name, input, schemes, filesToDelete) if (readOnly && scheme != null) { readOnlyExternalizableSchemes.put(scheme.name, scheme) } } true } } else { ioDirectory.directoryStreamIfExists({ canRead(it.fileName.toString()) }) { for (file in it) { if (file.isDirectory()) { continue } catchAndLog(file.fileName.toString()) { filename -> file.inputStream().use { loadScheme(filename, it, schemes, filesToDelete) } } } } } this.filesToDelete.addAll(filesToDelete) replaceSchemeList(oldSchemes, schemes) @Suppress("UNCHECKED_CAST") for (i in newSchemesOffset..schemes.size - 1) { val scheme = schemes.get(i) as MUTABLE_SCHEME processor.initScheme(scheme) @Suppress("UNCHECKED_CAST") processPendingCurrentSchemeName(scheme) } messageBus?.let { it.connect().subscribe(VirtualFileManager.VFS_CHANGES, SchemeFileTracker()) } return schemes.subList(newSchemesOffset, schemes.size) } finally { isLoadingSchemes.set(false) } } private fun replaceSchemeList(oldList: ConcurrentList<T>, newList: List<T>) { if (!schemesRef.compareAndSet(oldList, ContainerUtil.createLockFreeCopyOnWriteList(newList) as ConcurrentList<T>)) { throw IllegalStateException("Scheme list was modified") } } fun reload() { // we must not remove non-persistent (e.g. predefined) schemes, because we cannot load it (obviously) removeExternalizableSchemes() loadSchemes() } private fun removeExternalizableSchemes() { // todo check is bundled/read-only schemes correctly handled val iterator = schemes.iterator() for (scheme in iterator) { if (processor.getState(scheme) == SchemeState.NON_PERSISTENT) { continue } if (scheme === currentScheme) { currentScheme = null } iterator.remove() @Suppress("UNCHECKED_CAST") processor.onSchemeDeleted(scheme as MUTABLE_SCHEME) } retainExternalInfo() } @Suppress("UNCHECKED_CAST") private fun findExternalizableSchemeByFileName(fileName: String) = schemes.firstOrNull { fileName == "${it.fileName}$schemeExtension" } as MUTABLE_SCHEME? private fun isOverwriteOnLoad(existingScheme: T): Boolean { val info = schemeToInfo.get(existingScheme) // scheme from file with old extension, so, we must ignore it return info != null && schemeExtension != info.fileExtension } private inner class SchemeDataHolderImpl(private val bytes: ByteArray, private val externalInfo: ExternalInfo) : SchemeDataHolder<MUTABLE_SCHEME> { override fun read(): Element = loadElement(bytes.inputStream()) override fun updateDigest(scheme: MUTABLE_SCHEME) { try { externalInfo.digest = (processor.writeScheme(scheme) as Element).digest() } catch (e: WriteExternalException) { LOG.error("Cannot update digest", e) } } } private fun loadScheme(fileName: String, input: InputStream, schemes: MutableList<T>, filesToDelete: MutableSet<String>? = null): MUTABLE_SCHEME? { val extension = getFileExtension(fileName, false) if (filesToDelete != null && filesToDelete.contains(fileName)) { LOG.warn("Scheme file \"$fileName\" is not loaded because marked to delete") return null } val fileNameWithoutExtension = fileName.substring(0, fileName.length - extension.length) fun checkExisting(schemeName: String): Boolean { if (filesToDelete == null) { return true } schemes.firstOrNull({ it.name == schemeName})?.let { existingScheme -> if (readOnlyExternalizableSchemes.get(existingScheme.name) === existingScheme) { // so, bundled scheme is shadowed removeFirstScheme({ it === existingScheme }, schemes, scheduleDelete = false) return true } else if (processor.isExternalizable(existingScheme) && isOverwriteOnLoad(existingScheme)) { removeFirstScheme({ it === existingScheme }, schemes) } else { if (schemeExtension != extension && schemeToInfo.get(existingScheme as Scheme)?.fileNameWithoutExtension == fileNameWithoutExtension) { // 1.oldExt is loading after 1.newExt - we should delete 1.oldExt filesToDelete.add(fileName) } else { // We don't load scheme with duplicated name - if we generate unique name for it, it will be saved then with new name. // It is not what all can expect. Such situation in most cases indicates error on previous level, so, we just warn about it. LOG.warn("Scheme file \"$fileName\" is not loaded because defines duplicated name \"$schemeName\"") } return false } } return true } fun createInfo(schemeName: String, element: Element?): ExternalInfo { val info = ExternalInfo(fileNameWithoutExtension, extension) element?.let { info.digest = it.digest() } info.schemeName = schemeName return info } val duringLoad = filesToDelete != null var scheme: MUTABLE_SCHEME? = null if (processor is LazySchemeProcessor) { val bytes = input.readBytes() val parser = MXParser() parser.setInput(bytes.inputStream().reader()) var eventType = parser.eventType read@ do { when (eventType) { XmlPullParser.START_TAG -> { if (!isUseOldFileNameSanitize || parser.name != "component") { var name: String? = null if (isUseOldFileNameSanitize && parser.name == "profile") { eventType = parser.next() findName@ while (eventType != XmlPullParser.END_DOCUMENT) { when (eventType) { XmlPullParser.START_TAG -> { if (parser.name == "option" && parser.getAttributeValue(null, "name") == "myName") { name = parser.getAttributeValue(null, "value") break@findName } } } eventType = parser.next() } } val attributeProvider = Function<String, String?> { parser.getAttributeValue(null, it) } val schemeName = name ?: processor.getName(attributeProvider) if (!checkExisting(schemeName)) { return null } val externalInfo = createInfo(schemeName, null) val dataHolder = SchemeDataHolderImpl(bytes, externalInfo) scheme = processor.createScheme(dataHolder, schemeName, attributeProvider) schemeToInfo.put(scheme, externalInfo) this.filesToDelete.remove(fileName) break@read } } } eventType = parser.next() } while (eventType != XmlPullParser.END_DOCUMENT) } else { val element = loadElement(input) scheme = (processor as NonLazySchemeProcessor).readScheme(element, duringLoad) ?: return null val schemeName = scheme.name if (!checkExisting(schemeName)) { return null } schemeToInfo.put(scheme, createInfo(schemeName, element)) this.filesToDelete.remove(fileName) } @Suppress("UNCHECKED_CAST") if (duringLoad) { schemes.add(scheme as T) } else { addNewScheme(scheme as T, true) } return scheme } private val T.fileName: String? get() = schemeToInfo.get(this)?.fileNameWithoutExtension fun canRead(name: CharSequence) = (updateExtension && name.endsWith(DEFAULT_EXT, true) || name.endsWith(schemeExtension, true)) && (processor !is LazySchemeProcessor || processor.isSchemeFile(name)) private fun readSchemeFromFile(file: VirtualFile, schemes: MutableList<T> = this.schemes): MUTABLE_SCHEME? { val fileName = file.name if (file.isDirectory || !canRead(fileName)) { return null } catchAndLog(fileName) { return file.inputStream.use { loadScheme(fileName, it, schemes) } } return null } fun save(errors: MutableList<Throwable>) { if (isLoadingSchemes.get()) { LOG.warn("Skip save - schemes are loading") } var hasSchemes = false val nameGenerator = UniqueNameGenerator() val schemesToSave = SmartList<MUTABLE_SCHEME>() for (scheme in schemes) { val state = processor.getState(scheme) if (state == SchemeState.NON_PERSISTENT) { continue } hasSchemes = true if (state != SchemeState.UNCHANGED) { @Suppress("UNCHECKED_CAST") schemesToSave.add(scheme as MUTABLE_SCHEME) } val fileName = scheme.fileName if (fileName != null && !isRenamed(scheme)) { nameGenerator.addExistingName(fileName) } } for (scheme in schemesToSave) { try { saveScheme(scheme, nameGenerator) } catch (e: Throwable) { errors.add(RuntimeException("Cannot save scheme $fileSpec/$scheme", e)) } } val filesToDelete = THashSet(filesToDelete) if (!filesToDelete.isEmpty) { this.filesToDelete.removeAll(filesToDelete) deleteFiles(errors, filesToDelete) // remove empty directory only if some file was deleted - avoid check on each save if (!hasSchemes && (provider == null || !provider.isApplicable(fileSpec, roamingType))) { removeDirectoryIfEmpty(errors) } } } private fun removeDirectoryIfEmpty(errors: MutableList<Throwable>) { ioDirectory.directoryStreamIfExists { for (file in it) { if (!file.isHidden()) { LOG.info("Directory ${ioDirectory.fileName} is not deleted: at least one file ${file.fileName} exists") return@removeDirectoryIfEmpty } } } LOG.info("Remove schemes directory ${ioDirectory.fileName}") cachedVirtualDirectory = null var deleteUsingIo = !useVfs if (!deleteUsingIo) { virtualDirectory?.let { runWriteAction { try { it.delete(this) } catch (e: IOException) { deleteUsingIo = true errors.add(e) } } } } if (deleteUsingIo) { errors.catch { ioDirectory.delete() } } } private fun saveScheme(scheme: MUTABLE_SCHEME, nameGenerator: UniqueNameGenerator) { var externalInfo: ExternalInfo? = schemeToInfo.get(scheme) val currentFileNameWithoutExtension = externalInfo?.fileNameWithoutExtension val parent = processor.writeScheme(scheme) val element = if (parent is Element) parent else (parent as Document).detachRootElement() if (JDOMUtil.isEmpty(element)) { externalInfo?.scheduleDelete() return } var fileNameWithoutExtension = currentFileNameWithoutExtension if (fileNameWithoutExtension == null || isRenamed(scheme)) { fileNameWithoutExtension = nameGenerator.generateUniqueName(FileUtil.sanitizeFileName(scheme.name, isUseOldFileNameSanitize)) } val newDigest = element!!.digest() if (externalInfo != null && currentFileNameWithoutExtension === fileNameWithoutExtension && externalInfo.isDigestEquals(newDigest)) { return } // save only if scheme differs from bundled val bundledScheme = readOnlyExternalizableSchemes.get(scheme.name) if (bundledScheme != null && schemeToInfo.get(bundledScheme)?.isDigestEquals(newDigest) ?: false) { externalInfo?.scheduleDelete() return } // we must check it only here to avoid delete old scheme just because it is empty (old idea save -> new idea delete on open) if (processor is LazySchemeProcessor && processor.isSchemeDefault(scheme, newDigest)) { externalInfo?.scheduleDelete() return } val fileName = fileNameWithoutExtension!! + schemeExtension // file will be overwritten, so, we don't need to delete it filesToDelete.remove(fileName) // stream provider always use LF separator val byteOut = element.toBufferExposingByteArray() var providerPath: String? if (provider != null && provider.enabled) { providerPath = "$fileSpec/$fileName" if (!provider.isApplicable(providerPath, roamingType)) { providerPath = null } } else { providerPath = null } // if another new scheme uses old name of this scheme, so, we must not delete it (as part of rename operation) val renamed = externalInfo != null && fileNameWithoutExtension !== currentFileNameWithoutExtension && nameGenerator.value(currentFileNameWithoutExtension) if (providerPath == null) { if (useVfs) { var file: VirtualFile? = null var dir = virtualDirectory if (dir == null || !dir.isValid) { dir = createDir(ioDirectory, this) cachedVirtualDirectory = dir } if (renamed) { file = dir.findChild(externalInfo!!.fileName) if (file != null) { runWriteAction { file!!.rename(this, fileName) } } } if (file == null) { file = getFile(fileName, dir, this) } runWriteAction { file!!.getOutputStream(this).use { byteOut.writeTo(it) } } } else { if (renamed) { externalInfo!!.scheduleDelete() } ioDirectory.resolve(fileName).write(byteOut.internalBuffer, 0, byteOut.size()) } } else { if (renamed) { externalInfo!!.scheduleDelete() } provider!!.write(providerPath, byteOut.internalBuffer, byteOut.size(), roamingType) } if (externalInfo == null) { externalInfo = ExternalInfo(fileNameWithoutExtension, schemeExtension) schemeToInfo.put(scheme, externalInfo) } else { externalInfo.setFileNameWithoutExtension(fileNameWithoutExtension, schemeExtension) } externalInfo.digest = newDigest externalInfo.schemeName = scheme.name } private fun ExternalInfo.scheduleDelete() { filesToDelete.add(fileName) } private fun isRenamed(scheme: T): Boolean { val info = schemeToInfo.get(scheme) return info != null && scheme.name != info.schemeName } private fun deleteFiles(errors: MutableList<Throwable>, filesToDelete: MutableSet<String>) { if (provider != null && provider.enabled) { val iterator = filesToDelete.iterator() for (name in iterator) { errors.catch { val spec = "$fileSpec/$name" if (provider.isApplicable(spec, roamingType)) { iterator.remove() provider.delete(spec, roamingType) } } } } if (filesToDelete.isEmpty()) { return } if (useVfs) { virtualDirectory?.let { var token: AccessToken? = null try { for (file in it.children) { if (filesToDelete.contains(file.name)) { if (token == null) { token = WriteAction.start() } errors.catch { file.delete(this) } } } } finally { token?.finish() } return } } for (name in filesToDelete) { errors.catch { ioDirectory.resolve(name).delete() } } } private val virtualDirectory: VirtualFile? get() { var result = cachedVirtualDirectory if (result == null) { result = LocalFileSystem.getInstance().findFileByPath(ioDirectory.systemIndependentPath) cachedVirtualDirectory = result } return result } override fun getRootDirectory(): File = ioDirectory.toFile() override fun setSchemes(newSchemes: List<T>, newCurrentScheme: T?, removeCondition: Condition<T>?) { if (removeCondition == null) { schemes.clear() } else { val iterator = schemes.iterator() for (scheme in iterator) { if (removeCondition.value(scheme)) { iterator.remove() } } } schemes.addAll(newSchemes) val oldCurrentScheme = currentScheme retainExternalInfo() if (oldCurrentScheme != newCurrentScheme) { val newScheme: T? if (newCurrentScheme != null) { currentScheme = newCurrentScheme newScheme = newCurrentScheme } else if (oldCurrentScheme != null && !schemes.contains(oldCurrentScheme)) { newScheme = schemes.firstOrNull() currentScheme = newScheme } else { newScheme = null } if (oldCurrentScheme != newScheme) { processor.onCurrentSchemeSwitched(oldCurrentScheme, newScheme) } } } private fun retainExternalInfo() { if (schemeToInfo.isEmpty()) { return } val iterator = schemeToInfo.entries.iterator() l@ for ((scheme, info) in iterator) { if (readOnlyExternalizableSchemes.get(scheme.name) == scheme) { continue } for (s in schemes) { if (s === scheme) { filesToDelete.remove(info.fileName) continue@l } } iterator.remove() info.scheduleDelete() } } override fun addNewScheme(scheme: T, replaceExisting: Boolean) { var toReplace = -1 val schemes = schemes for (i in schemes.indices) { val existing = schemes.get(i) if (existing.name == scheme.name) { if (existing.javaClass != scheme.javaClass) { LOG.warn("'${scheme.name}' ${existing.javaClass.simpleName} replaced with ${scheme.javaClass.simpleName}") } toReplace = i if (replaceExisting && processor.isExternalizable(existing)) { val oldInfo = schemeToInfo.remove(existing) if (oldInfo != null && processor.isExternalizable(scheme) && !schemeToInfo.containsKey(scheme)) { schemeToInfo.put(scheme, oldInfo) } } break } } if (toReplace == -1) { schemes.add(scheme) } else if (replaceExisting || !processor.isExternalizable(scheme)) { schemes.set(toReplace, scheme) } else { (scheme as ExternalizableScheme).renameScheme(UniqueNameGenerator.generateUniqueName(scheme.name, collectExistingNames(schemes))) schemes.add(scheme) } if (processor.isExternalizable(scheme) && filesToDelete.isNotEmpty()) { schemeToInfo.get(scheme)?.let { filesToDelete.remove(it.fileName) } } processPendingCurrentSchemeName(scheme) } private fun collectExistingNames(schemes: Collection<T>): Collection<String> { val result = THashSet<String>(schemes.size) for (scheme in schemes) { result.add(scheme.name) } return result } override fun clearAllSchemes() { for (it in schemeToInfo.values) { it.scheduleDelete() } currentScheme = null schemes.clear() schemeToInfo.clear() } override fun getAllSchemes(): List<T> = Collections.unmodifiableList(schemes) override fun isEmpty() = schemes.isEmpty() override fun findSchemeByName(schemeName: String) = schemes.firstOrNull { it.name == schemeName } override fun setCurrent(scheme: T?, notify: Boolean) { currentPendingSchemeName = null val oldCurrent = currentScheme currentScheme = scheme if (notify && oldCurrent !== scheme) { processor.onCurrentSchemeSwitched(oldCurrent, scheme) } } override fun setCurrentSchemeName(schemeName: String?, notify: Boolean) { currentPendingSchemeName = schemeName val scheme = if (schemeName == null) null else findSchemeByName(schemeName) // don't set current scheme if no scheme by name - pending resolution (see currentSchemeName field comment) if (scheme != null || schemeName == null) { setCurrent(scheme, notify) } } override fun getCurrentScheme() = currentScheme override fun getCurrentSchemeName() = currentScheme?.name ?: currentPendingSchemeName private fun processPendingCurrentSchemeName(newScheme: T) { if (newScheme.name == currentPendingSchemeName) { setCurrent(newScheme, false) } } override fun removeScheme(schemeName: String) = removeFirstScheme({it.name == schemeName}, schemes) override fun removeScheme(scheme: T) { removeFirstScheme({ it == scheme }, schemes) } private fun removeFirstScheme(condition: (T) -> Boolean, schemes: MutableList<T>, scheduleDelete: Boolean = true): T? { val iterator = schemes.iterator() for (scheme in iterator) { if (!condition(scheme)) { continue } if (currentScheme === scheme) { currentScheme = null } iterator.remove() if (scheduleDelete && processor.isExternalizable(scheme)) { schemeToInfo.remove(scheme)?.scheduleDelete() } return scheme } return null } override fun getAllSchemeNames() = schemes.let { if (it.isEmpty()) emptyList() else it.map { it.name } } override fun isMetadataEditable(scheme: T) = !readOnlyExternalizableSchemes.containsKey(scheme.name) private class ExternalInfo(var fileNameWithoutExtension: String, var fileExtension: String?) { // we keep it to detect rename var schemeName: String? = null var digest: ByteArray? = null val fileName: String get() = "$fileNameWithoutExtension$fileExtension" fun setFileNameWithoutExtension(nameWithoutExtension: String, extension: String) { fileNameWithoutExtension = nameWithoutExtension fileExtension = extension } fun isDigestEquals(newDigest: ByteArray) = Arrays.equals(digest, newDigest) override fun toString() = fileName } override fun toString() = fileSpec } private fun ExternalizableScheme.renameScheme(newName: String) { if (newName != name) { name = newName LOG.assertTrue(newName == name) } } private inline fun MutableList<Throwable>.catch(runnable: () -> Unit) { try { runnable() } catch (e: Throwable) { add(e) } } fun createDir(ioDir: Path, requestor: Any): VirtualFile { ioDir.createDirectories() val parentFile = ioDir.parent val parentVirtualFile = (if (parentFile == null) null else VfsUtil.createDirectoryIfMissing(parentFile.systemIndependentPath)) ?: throw IOException(ProjectBundle.message("project.configuration.save.file.not.found", parentFile)) return getFile(ioDir.fileName.toString(), parentVirtualFile, requestor) } fun getFile(fileName: String, parent: VirtualFile, requestor: Any): VirtualFile { return parent.findChild(fileName) ?: runWriteAction { parent.createChildData(requestor, fileName) } } private inline fun catchAndLog(fileName: String, runnable: (fileName: String) -> Unit) { try { runnable(fileName) } catch (e: Throwable) { LOG.error("Cannot read scheme $fileName", e) } }
apache-2.0
3e4e9e654308da2121603a471462981e
32.458661
229
0.646663
4.867268
false
false
false
false
Maccimo/intellij-community
plugins/kotlin/base/plugin/src/org/jetbrains/kotlin/idea/compiler/configuration/KotlinJpsPluginSettings.kt
1
10430
// 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.compiler.configuration import com.intellij.notification.NotificationGroupManager import com.intellij.notification.NotificationType import com.intellij.openapi.components.State import com.intellij.openapi.components.Storage import com.intellij.openapi.components.service import com.intellij.openapi.project.Project import com.intellij.openapi.util.JDOMUtil import com.intellij.openapi.util.NlsContexts import com.intellij.openapi.util.NlsSafe import com.intellij.util.io.exists import com.intellij.util.xmlb.XmlSerializer import org.jetbrains.annotations.Nls import org.jetbrains.kotlin.config.JpsPluginSettings import org.jetbrains.kotlin.config.LanguageVersion import org.jetbrains.kotlin.config.SettingConstants import org.jetbrains.kotlin.config.SettingConstants.KOTLIN_JPS_PLUGIN_SETTINGS_SECTION import org.jetbrains.kotlin.config.toKotlinVersion import org.jetbrains.kotlin.idea.base.plugin.KotlinBasePluginBundle import org.jetbrains.kotlin.idea.util.application.isUnitTestMode import java.nio.file.Path import kotlin.io.path.bufferedReader @State(name = KOTLIN_JPS_PLUGIN_SETTINGS_SECTION, storages = [(Storage(SettingConstants.KOTLIN_COMPILER_SETTINGS_FILE))]) class KotlinJpsPluginSettings(project: Project) : BaseKotlinCompilerSettings<JpsPluginSettings>(project) { override fun createSettings() = JpsPluginSettings() fun setVersion(jpsVersion: String) { if (jpsVersion == settings.version) return update { version = jpsVersion } } fun dropExplicitVersion(): Unit = setVersion("") companion object { // Use bundled by default because this will work even without internet connection @JvmStatic val rawBundledVersion: String get() = bundledVersion.rawVersion // Use stable 1.6.21 for outdated compiler versions in order to work with old LV settings @JvmStatic val fallbackVersionForOutdatedCompiler: String get() = "1.6.21" @JvmStatic val bundledVersion: IdeKotlinVersion get() = KotlinPluginLayout.standaloneCompilerVersion @JvmStatic val jpsMinimumSupportedVersion: KotlinVersion = IdeKotlinVersion.get("1.6.0").kotlinVersion @JvmStatic val jpsMaximumSupportedVersion: KotlinVersion = LanguageVersion.values().last().toKotlinVersion() fun validateSettings(project: Project) { val jpsPluginSettings = project.service<KotlinJpsPluginSettings>() if (!isUnbundledJpsExperimentalFeatureEnabled(project)) { // Delete compiler version in kotlinc.xml when feature flag is off jpsPluginSettings.dropExplicitVersion() return } if (jpsPluginSettings.settings.version.isEmpty() && bundledVersion.buildNumber == null) { // Encourage user to specify desired Kotlin compiler version in project settings for sake of reproducible builds // it's important to trigger `.idea/kotlinc.xml` file creation jpsPluginSettings.setVersion(rawBundledVersion) } } fun jpsVersion(project: Project): String? = getInstance(project)?.settings?.versionWithFallback /** * @see readFromKotlincXmlOrIpr */ @JvmStatic fun getInstance(project: Project): KotlinJpsPluginSettings? = project.takeIf { isUnbundledJpsExperimentalFeatureEnabled(it) }?.service() @JvmStatic fun isUnbundledJpsExperimentalFeatureEnabled(project: Project): Boolean = isUnitTestMode() || !project.isDefault /** * @param jpsVersion version to parse * @param fromFile true if [jpsVersion] come from kotlin.xml * @return error message if [jpsVersion] is not valid */ @Nls fun checkJpsVersion(jpsVersion: String, fromFile: Boolean = false): UnsupportedJpsVersionError? { val parsedKotlinVersion = IdeKotlinVersion.opt(jpsVersion)?.kotlinVersion if (parsedKotlinVersion == null) { return ParsingError( if (fromFile) { KotlinBasePluginBundle.message( "failed.to.parse.kotlin.version.0.from.1", jpsVersion, SettingConstants.KOTLIN_COMPILER_SETTINGS_FILE, ) } else { KotlinBasePluginBundle.message("failed.to.parse.kotlin.version.0", jpsVersion) } ) } if (parsedKotlinVersion < jpsMinimumSupportedVersion) { return OutdatedCompilerVersion(KotlinBasePluginBundle.message( "kotlin.jps.compiler.minimum.supported.version.not.satisfied", jpsMinimumSupportedVersion, jpsVersion, )) } if (parsedKotlinVersion > jpsMaximumSupportedVersion) { return NewCompilerVersion(KotlinBasePluginBundle.message( "kotlin.jps.compiler.maximum.supported.version.not.satisfied", jpsMaximumSupportedVersion, jpsVersion, )) } return null } /** * Replacement for [getInstance] for cases when it's not possible to use [getInstance] (e.g. project isn't yet initialized). * * Please, prefer [getInstance] if possible. */ fun readFromKotlincXmlOrIpr(path: Path) = path.takeIf { it.fileIsNotEmpty() } ?.let { JDOMUtil.load(path) } ?.children ?.singleOrNull { it.getAttributeValue("name") == KotlinJpsPluginSettings::class.java.simpleName } ?.let { xmlElement -> JpsPluginSettings().apply { XmlSerializer.deserializeInto(this, xmlElement) } } fun supportedJpsVersion(project: Project, onUnsupportedVersion: (String) -> Unit): String? { val version = jpsVersion(project) ?: return null return when (val error = checkJpsVersion(version, fromFile = true)) { is OutdatedCompilerVersion -> fallbackVersionForOutdatedCompiler is NewCompilerVersion, is ParsingError -> { onUnsupportedVersion(error.message) null } null -> version } } fun importKotlinJpsVersionFromExternalBuildSystem( project: Project, rawVersion: String, showNotification: Boolean = true, ): Boolean { val instance = getInstance(project) ?: return true if (rawVersion == rawBundledVersion) { instance.setVersion(rawVersion) return true } val error = checkJpsVersion(rawVersion) val version = when (error) { is OutdatedCompilerVersion -> fallbackVersionForOutdatedCompiler is NewCompilerVersion, is ParsingError -> rawBundledVersion null -> rawVersion } if (error != null) { if (showNotification) { showNotificationUnsupportedJpsPluginVersion( project, KotlinBasePluginBundle.message("notification.title.unsupported.kotlin.jps.plugin.version"), KotlinBasePluginBundle.message( "notification.content.bundled.version.0.will.be.used.reason.1", version, error.message ), ) } if (error !is OutdatedCompilerVersion) { instance.dropExplicitVersion() return false } } val ok = shouldImportKotlinJpsPluginVersionFromExternalBuildSystem(IdeKotlinVersion.get(version)) if (ok) { instance.setVersion(version) } else { instance.dropExplicitVersion() } return ok } fun shouldImportKotlinJpsPluginVersionFromExternalBuildSystem(version: IdeKotlinVersion): Boolean { check(jpsMinimumSupportedVersion < IdeKotlinVersion.get("1.7.10").kotlinVersion) { "${::shouldImportKotlinJpsPluginVersionFromExternalBuildSystem.name} makes sense when minimum supported version is lower " + "than 1.7.20. If minimum supported version is already 1.7.20 then you can drop this function." } require(version.kotlinVersion >= jpsMinimumSupportedVersion) { "${version.kotlinVersion} is lower than $jpsMinimumSupportedVersion" } val kt160 = IdeKotlinVersion.get("1.6.0") val kt170 = IdeKotlinVersion.get("1.7.0") // Until 1.6.0 none of unbundled Kotlin JPS artifacts was published to the Maven Central. // In range [1.6.0, 1.7.0] unbundled Kotlin JPS artifacts were published only for release Kotlin versions. return version > kt170 || version >= kt160 && version.isRelease && version.buildNumber == null } } } sealed class UnsupportedJpsVersionError(val message: String) class ParsingError(message: String) : UnsupportedJpsVersionError(message) class OutdatedCompilerVersion(message: String) : UnsupportedJpsVersionError(message) class NewCompilerVersion(message: String) : UnsupportedJpsVersionError(message) @get:NlsSafe val JpsPluginSettings.versionWithFallback: String get() = version.ifEmpty { KotlinJpsPluginSettings.rawBundledVersion } private fun showNotificationUnsupportedJpsPluginVersion( project: Project, @NlsContexts.NotificationTitle title: String, @NlsContexts.NotificationContent content: String, ) { NotificationGroupManager.getInstance() .getNotificationGroup("Kotlin JPS plugin") .createNotification(title, content, NotificationType.WARNING) .setImportant(true) .notify(project) } fun Path.fileIsNotEmpty() = exists() && bufferedReader().use { it.readLine() != null }
apache-2.0
87b2d3261b819fe3d3a455e941aa6705
42.823529
140
0.635954
5.398551
false
false
false
false
k9mail/k-9
app/core/src/main/java/com/fsck/k9/KoinModule.kt
2
1347
package com.fsck.k9 import android.content.Context import com.fsck.k9.helper.Contacts import com.fsck.k9.helper.DefaultTrustedSocketFactory import com.fsck.k9.mail.ssl.LocalKeyStore import com.fsck.k9.mail.ssl.TrustManagerFactory import com.fsck.k9.mail.ssl.TrustedSocketFactory import com.fsck.k9.mailstore.LocalStoreProvider import com.fsck.k9.setup.ServerNameSuggester import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.GlobalScope import org.koin.core.qualifier.named import org.koin.dsl.module val mainModule = module { single<CoroutineScope>(named("AppCoroutineScope")) { GlobalScope } single { Preferences( storagePersister = get(), localStoreProvider = get(), accountPreferenceSerializer = get() ) } single { get<Context>().resources } single { get<Context>().contentResolver } single { LocalStoreProvider() } single { Contacts.getInstance(get()) } single { LocalKeyStore(directoryProvider = get()) } single { TrustManagerFactory.createInstance(get()) } single { LocalKeyStoreManager(get()) } single<TrustedSocketFactory> { DefaultTrustedSocketFactory(get(), get()) } single<Clock> { RealClock() } factory { ServerNameSuggester() } factory { EmailAddressValidator() } factory { ServerSettingsSerializer() } }
apache-2.0
e098b9b331f6f76d3668e2bdaaa0f789
35.405405
78
0.730512
4.289809
false
false
false
false
Maccimo/intellij-community
plugins/kotlin/base/fe10/highlighting/src/org/jetbrains/kotlin/idea/highlighter/KotlinSuppressableWarningProblemGroup.kt
3
7724
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.highlighter import com.intellij.codeInspection.SuppressIntentionAction import com.intellij.codeInspection.SuppressableProblemGroup import com.intellij.openapi.util.NlsSafe import com.intellij.psi.PsiElement import org.jetbrains.kotlin.diagnostics.DiagnosticFactory import org.jetbrains.kotlin.diagnostics.Severity import org.jetbrains.kotlin.idea.base.fe10.highlighting.KotlinBaseFe10HighlightingBundle import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType class KotlinSuppressableWarningProblemGroup(private val diagnosticFactory: DiagnosticFactory<*>) : SuppressableProblemGroup { init { assert(diagnosticFactory.severity == Severity.WARNING) } override fun getProblemName() = diagnosticFactory.name override fun getSuppressActions(element: PsiElement?): Array<SuppressIntentionAction> { return if (element != null) { createSuppressWarningActions(element, diagnosticFactory).toTypedArray() } else { SuppressIntentionAction.EMPTY_ARRAY } } } fun createSuppressWarningActions(element: PsiElement, diagnosticFactory: DiagnosticFactory<*>): List<SuppressIntentionAction> = createSuppressWarningActions(element, diagnosticFactory.severity, diagnosticFactory.name) fun createSuppressWarningActions(element: PsiElement, severity: Severity, suppressionKey: String): List<SuppressIntentionAction> { if (severity != Severity.WARNING) { return emptyList() } val actions = arrayListOf<SuppressIntentionAction>() var current: PsiElement? = element var suppressAtStatementAllowed = true while (current != null) { when { current is KtDeclaration && current !is KtDestructuringDeclaration -> { val declaration = current val kind = DeclarationKindDetector.detect(declaration) if (kind != null) { actions.add(Fe10QuickFixProvider.getInstance(declaration.project).createSuppressFix(declaration, suppressionKey, kind)) } suppressAtStatementAllowed = false } current is KtExpression && suppressAtStatementAllowed -> { // Add suppress action at first statement if (current.parent is KtBlockExpression || current.parent is KtDestructuringDeclaration) { val kind = if (current.parent is KtBlockExpression) KotlinBaseFe10HighlightingBundle.message("declaration.kind.statement") else KotlinBaseFe10HighlightingBundle.message("declaration.kind.initializer") val hostKind = AnnotationHostKind(kind, null, true) actions.add(Fe10QuickFixProvider.getInstance(current.project).createSuppressFix(current, suppressionKey, hostKind)) suppressAtStatementAllowed = false } } current is KtFile -> { val hostKind = AnnotationHostKind(KotlinBaseFe10HighlightingBundle.message("declaration.kind.file"), current.name, true) actions.add(Fe10QuickFixProvider.getInstance(current.project).createSuppressFix(current, suppressionKey, hostKind)) suppressAtStatementAllowed = false } } current = current.parent } return actions } private object DeclarationKindDetector : KtVisitor<AnnotationHostKind?, Unit?>() { fun detect(declaration: KtDeclaration) = declaration.accept(this, null) override fun visitDeclaration(declaration: KtDeclaration, data: Unit?) = null private fun getDeclarationName(declaration: KtDeclaration): @NlsSafe String { return declaration.name ?: KotlinBaseFe10HighlightingBundle.message("declaration.name.anonymous") } override fun visitClass(declaration: KtClass, data: Unit?): AnnotationHostKind { val kind = when { declaration.isInterface() -> KotlinBaseFe10HighlightingBundle.message("declaration.kind.interface") else -> KotlinBaseFe10HighlightingBundle.message("declaration.kind.class") } return AnnotationHostKind(kind, getDeclarationName(declaration), newLineNeeded = true) } override fun visitNamedFunction(declaration: KtNamedFunction, data: Unit?): AnnotationHostKind { val kind = KotlinBaseFe10HighlightingBundle.message("declaration.kind.fun") return AnnotationHostKind(kind, getDeclarationName(declaration), newLineNeeded = true) } override fun visitProperty(declaration: KtProperty, data: Unit?): AnnotationHostKind { val kind = when { declaration.isVar -> KotlinBaseFe10HighlightingBundle.message("declaration.kind.var") else -> KotlinBaseFe10HighlightingBundle.message("declaration.kind.val") } return AnnotationHostKind(kind, getDeclarationName(declaration), newLineNeeded = true) } override fun visitDestructuringDeclaration(declaration: KtDestructuringDeclaration, data: Unit?): AnnotationHostKind { val kind = when { declaration.isVar -> KotlinBaseFe10HighlightingBundle.message("declaration.kind.var") else -> KotlinBaseFe10HighlightingBundle.message("declaration.kind.val") } val name = declaration.entries.joinToString(", ", "(", ")") { it.name!! } return AnnotationHostKind(kind, name, newLineNeeded = true) } override fun visitTypeParameter(declaration: KtTypeParameter, data: Unit?): AnnotationHostKind { val kind = KotlinBaseFe10HighlightingBundle.message("declaration.kind.type.parameter") return AnnotationHostKind(kind, getDeclarationName(declaration), newLineNeeded = false) } override fun visitEnumEntry(declaration: KtEnumEntry, data: Unit?): AnnotationHostKind { val kind = KotlinBaseFe10HighlightingBundle.message("declaration.kind.enum.entry") return AnnotationHostKind(kind, getDeclarationName(declaration), newLineNeeded = true) } override fun visitParameter(declaration: KtParameter, data: Unit?): AnnotationHostKind { val kind = KotlinBaseFe10HighlightingBundle.message("declaration.kind.parameter") return AnnotationHostKind(kind, getDeclarationName(declaration), newLineNeeded = false) } override fun visitSecondaryConstructor(declaration: KtSecondaryConstructor, data: Unit?): AnnotationHostKind { val kind = KotlinBaseFe10HighlightingBundle.message("declaration.kind.secondary.constructor.of") return AnnotationHostKind(kind, getDeclarationName(declaration), newLineNeeded = true) } override fun visitObjectDeclaration(d: KtObjectDeclaration, data: Unit?): AnnotationHostKind? { return when { d.isCompanion() -> { val kind = KotlinBaseFe10HighlightingBundle.message("declaration.kind.companion.object") val name = KotlinBaseFe10HighlightingBundle.message( "declaration.name.0.of.1", d.name.toString(), d.getStrictParentOfType<KtClass>()?.name.toString() ) AnnotationHostKind(kind, name, newLineNeeded = true) } d.parent is KtObjectLiteralExpression -> null else -> { val kind = KotlinBaseFe10HighlightingBundle.message("declaration.kind.object") AnnotationHostKind(kind, getDeclarationName(d), newLineNeeded = true) } } } }
apache-2.0
751b0ccbdd9cdadcafa5b0c07c1f1e1d
47.892405
158
0.701709
5.474132
false
false
false
false
k9mail/k-9
app/ui/legacy/src/main/java/com/fsck/k9/ui/managefolders/ManageFoldersFragment.kt
2
6102
package com.fsck.k9.ui.managefolders 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.widget.SearchView import androidx.core.os.bundleOf import androidx.fragment.app.Fragment import androidx.navigation.fragment.findNavController import androidx.recyclerview.widget.RecyclerView import com.fsck.k9.Account import com.fsck.k9.Preferences import com.fsck.k9.controller.MessagingController import com.fsck.k9.mailstore.DisplayFolder import com.fsck.k9.ui.R import com.fsck.k9.ui.folders.FolderIconProvider import com.fsck.k9.ui.folders.FolderNameFormatter import com.fsck.k9.ui.observeNotNull import com.mikepenz.fastadapter.FastAdapter import com.mikepenz.fastadapter.adapters.ItemAdapter import java.util.Locale import org.koin.android.ext.android.inject import org.koin.androidx.viewmodel.ext.android.viewModel import org.koin.core.parameter.parametersOf class ManageFoldersFragment : Fragment() { private val viewModel: ManageFoldersViewModel by viewModel() private val folderNameFormatter: FolderNameFormatter by inject { parametersOf(requireActivity()) } private val messagingController: MessagingController by inject() private val preferences: Preferences by inject() private val folderIconProvider by lazy { FolderIconProvider(requireActivity().theme) } private lateinit var account: Account private lateinit var itemAdapter: ItemAdapter<FolderListItem> override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setHasOptionsMenu(true) val arguments = arguments ?: error("Missing arguments") val accountUuid = arguments.getString(EXTRA_ACCOUNT) ?: error("Missing argument '$EXTRA_ACCOUNT'") account = preferences.getAccount(accountUuid) ?: error("Missing account: $accountUuid") } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { return inflater.inflate(R.layout.fragment_manage_folders, container, false) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { initializeFolderList() viewModel.getFolders(account).observeNotNull(this) { folders -> updateFolderList(folders) } } private fun initializeFolderList() { itemAdapter = ItemAdapter() itemAdapter.itemFilter.filterPredicate = ::folderListFilter val folderListAdapter = FastAdapter.with(itemAdapter).apply { setHasStableIds(true) onClickListener = { _, _, item: FolderListItem, _ -> openFolderSettings(item.folderId) true } } val recyclerView = requireView().findViewById<RecyclerView>(R.id.folderList) recyclerView.adapter = folderListAdapter } private fun updateFolderList(displayFolders: List<DisplayFolder>) { val folderListItems = displayFolders.map { displayFolder -> val databaseId = displayFolder.folder.id val folderIconResource = folderIconProvider.getFolderIcon(displayFolder.folder.type) val displayName = folderNameFormatter.displayName(displayFolder.folder) FolderListItem(databaseId, folderIconResource, displayName) } itemAdapter.set(folderListItems) } private fun openFolderSettings(folderId: Long) { val folderSettingsArguments = bundleOf( FolderSettingsFragment.EXTRA_ACCOUNT to account.uuid, FolderSettingsFragment.EXTRA_FOLDER_ID to folderId ) findNavController().navigate(R.id.action_manageFoldersScreen_to_folderSettingsScreen, folderSettingsArguments) } override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) { inflater.inflate(R.menu.folder_list_option, menu) configureFolderSearchView(menu) } private fun configureFolderSearchView(menu: Menu) { val folderMenuItem = menu.findItem(R.id.filter_folders) val folderSearchView = folderMenuItem.actionView as SearchView folderSearchView.queryHint = getString(R.string.folder_list_filter_hint) folderSearchView.setOnQueryTextListener(object : SearchView.OnQueryTextListener { override fun onQueryTextSubmit(query: String): Boolean { itemAdapter.filter(query) return true } override fun onQueryTextChange(newText: String): Boolean { itemAdapter.filter(newText) return true } }) } override fun onOptionsItemSelected(item: MenuItem): Boolean { when (item.itemId) { R.id.list_folders -> refreshFolderList() R.id.display_1st_class -> setDisplayMode(Account.FolderMode.FIRST_CLASS) R.id.display_1st_and_2nd_class -> setDisplayMode(Account.FolderMode.FIRST_AND_SECOND_CLASS) R.id.display_not_second_class -> setDisplayMode(Account.FolderMode.NOT_SECOND_CLASS) R.id.display_all -> setDisplayMode(Account.FolderMode.ALL) else -> return super.onOptionsItemSelected(item) } return true } private fun refreshFolderList() { messagingController.refreshFolderList(account) } private fun setDisplayMode(newMode: Account.FolderMode) { account.folderDisplayMode = newMode preferences.saveAccount(account) itemAdapter.filter(null) } private fun folderListFilter(item: FolderListItem, constraint: CharSequence?): Boolean { if (constraint.isNullOrEmpty()) return true val locale = Locale.getDefault() val displayName = item.displayName.lowercase(locale) return constraint.splitToSequence(" ") .filter { it.isNotEmpty() } .map { it.lowercase(locale) } .any { it in displayName } } companion object { const val EXTRA_ACCOUNT = "account" } }
apache-2.0
00602fdb99542736fcbe711a9ff448ad
37.866242
118
0.708948
4.862151
false
false
false
false
michaelkourlas/voipms-sms-client
voipms-sms/src/main/kotlin/net/kourlas/voipms_sms/CustomApplication.kt
1
4646
/* * VoIP.ms SMS * Copyright (C) 2017-2021 Michael Kourlas * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.kourlas.voipms_sms import android.app.Application import android.net.ConnectivityManager import android.os.Build import androidx.appcompat.app.AppCompatDelegate import net.kourlas.voipms_sms.billing.Billing import net.kourlas.voipms_sms.database.Database import net.kourlas.voipms_sms.network.NetworkManager.Companion.getInstance import net.kourlas.voipms_sms.preferences.fragments.AppearancePreferencesFragment import net.kourlas.voipms_sms.preferences.getAppTheme import net.kourlas.voipms_sms.preferences.getSyncInterval import net.kourlas.voipms_sms.preferences.setRawSyncInterval import net.kourlas.voipms_sms.sms.ConversationId import net.kourlas.voipms_sms.sms.workers.SyncWorker import net.kourlas.voipms_sms.utils.subscribeToDidTopics class CustomApplication : Application() { private var conversationsActivitiesVisible = 0 private val conversationActivitiesVisible: MutableMap<ConversationId, Int> = HashMap() fun conversationsActivityVisible(): Boolean { return conversationsActivitiesVisible > 0 } fun conversationsActivityIncrementCount() { conversationsActivitiesVisible++ } fun conversationsActivityDecrementCount() { conversationsActivitiesVisible-- } fun conversationActivityVisible(conversationId: ConversationId): Boolean { val count = conversationActivitiesVisible[conversationId] return count != null && count > 0 } fun conversationActivityIncrementCount( conversationId: ConversationId ) { var count = conversationActivitiesVisible[conversationId] if (count == null) { count = 0 } conversationActivitiesVisible[conversationId] = count + 1 } fun conversationActivityDecrementCount( conversationId: ConversationId ) { var count = conversationActivitiesVisible[conversationId] if (count == null) { count = 0 } conversationActivitiesVisible[conversationId] = count - 1 } override fun onCreate() { super.onCreate() // Create static reference to self. self = this // Limit synchronization interval to 15 minutes. Previous versions // supported a shorter interval. if (getSyncInterval(applicationContext) != 0.0 && getSyncInterval(applicationContext) < (15.0 / (24 * 60)) ) { setRawSyncInterval(applicationContext, "0.01041666666") } // Update theme when (getAppTheme(applicationContext)) { AppearancePreferencesFragment.SYSTEM_DEFAULT -> AppCompatDelegate.setDefaultNightMode( AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM ) AppearancePreferencesFragment.LIGHT -> AppCompatDelegate.setDefaultNightMode( AppCompatDelegate.MODE_NIGHT_NO ) AppearancePreferencesFragment.DARK -> AppCompatDelegate.setDefaultNightMode( AppCompatDelegate.MODE_NIGHT_YES ) } // Register for network callbacks if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { val connectivityManager = getSystemService( CONNECTIVITY_SERVICE ) as ConnectivityManager connectivityManager.registerDefaultNetworkCallback( getInstance() ) } // Open the database. Database.getInstance(applicationContext) // Subscribe to topics for current DIDs. subscribeToDidTopics(applicationContext) // Schedule a database synchronization, if required. SyncWorker.performFullSynchronization( applicationContext, scheduleOnly = true ) // Initialize the billing service. Billing.getInstance(applicationContext) } companion object { private lateinit var self: CustomApplication fun getApplication(): CustomApplication { return self } } }
apache-2.0
053f528e1760374efae2d91323cc817d
32.919708
98
0.68898
5.273553
false
false
false
false
ingokegel/intellij-community
platform/platform-impl/src/com/intellij/openapi/wm/impl/customFrameDecorations/header/toolbar/ToolbarFrameHeader.kt
1
6271
// 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.openapi.wm.impl.customFrameDecorations.header.toolbar import com.intellij.ide.ui.UISettings import com.intellij.ide.ui.UISettingsListener import com.intellij.openapi.util.Disposer import com.intellij.openapi.util.SystemInfo import com.intellij.openapi.wm.IdeFrame import com.intellij.openapi.wm.impl.IdeMenuBar import com.intellij.openapi.wm.impl.ToolbarHolder import com.intellij.openapi.wm.impl.customFrameDecorations.header.FrameHeader import com.intellij.openapi.wm.impl.customFrameDecorations.header.MainFrameCustomHeader import com.intellij.openapi.wm.impl.headertoolbar.MainToolbar import com.intellij.openapi.wm.impl.headertoolbar.isToolbarInHeader import com.intellij.ui.awt.RelativeRectangle import com.intellij.ui.components.panels.NonOpaquePanel import com.intellij.util.ui.GridBag import com.intellij.util.ui.JBUI import com.intellij.util.ui.JBUI.CurrentTheme.CustomFrameDecorations import com.jetbrains.CustomWindowDecoration.MENU_BAR import java.awt.* import java.awt.GridBagConstraints.* import java.awt.event.ComponentAdapter import java.awt.event.ComponentEvent import javax.swing.Box import javax.swing.JComponent import javax.swing.JFrame import javax.swing.JPanel import kotlin.math.roundToInt private enum class ShowMode { MENU, TOOLBAR } internal class ToolbarFrameHeader(frame: JFrame, ideMenu: IdeMenuBar) : FrameHeader(frame), UISettingsListener, ToolbarHolder, MainFrameCustomHeader { private val myMenuBar = ideMenu private val mainMenuButton = MainMenuButton() private var toolbar : MainToolbar? = null private val myToolbarPlaceholder = NonOpaquePanel() private val myHeaderContent = createHeaderContent() private val contentResizeListener = object : ComponentAdapter() { override fun componentResized(e: ComponentEvent?) { updateCustomDecorationHitTestSpots() } } private var mode = ShowMode.MENU init { layout = GridBagLayout() val gb = GridBag().anchor(WEST) updateLayout(UISettings.getInstance()) productIcon.border = JBUI.Borders.empty(V, 0, V, 0) add(productIcon, gb.nextLine().next().anchor(WEST).insetLeft(H)) add(myHeaderContent, gb.next().fillCell().anchor(CENTER).weightx(1.0).weighty(1.0)) val buttonsView = wrap(buttonPanes.getView()) if (SystemInfo.isWindows) buttonsView.border = JBUI.Borders.emptyLeft(8) add(buttonsView, gb.next().anchor(EAST)) setCustomFrameTopBorder({ false }, {true}) Disposer.register(this, mainMenuButton.menuShortcutHandler) } private fun wrap(comp: JComponent) = object : NonOpaquePanel(comp) { override fun getPreferredSize(): Dimension = comp.preferredSize override fun getMinimumSize(): Dimension = comp.preferredSize } override fun updateToolbar() { removeToolbar() val toolbar = MainToolbar() toolbar.init((frame as? IdeFrame)?.project) toolbar.isOpaque = false toolbar.addComponentListener(contentResizeListener) this.toolbar = toolbar myToolbarPlaceholder.add(this.toolbar) myToolbarPlaceholder.revalidate() } override fun removeToolbar() { toolbar?.removeComponentListener(contentResizeListener) myToolbarPlaceholder.removeAll() myToolbarPlaceholder.revalidate() } override fun installListeners() { super.installListeners() mainMenuButton.menuShortcutHandler.registerShortcuts(frame.rootPane) myMenuBar.addComponentListener(contentResizeListener) } override fun uninstallListeners() { super.uninstallListeners() mainMenuButton.menuShortcutHandler.unregisterShortcuts() myMenuBar.removeComponentListener(contentResizeListener) toolbar?.removeComponentListener(contentResizeListener) } override fun updateMenuActions(forceRebuild: Boolean) {} //todo remove override fun getComponent(): JComponent = this override fun uiSettingsChanged(uiSettings: UISettings) { updateLayout(uiSettings) when (mode) { ShowMode.TOOLBAR -> updateToolbar() ShowMode.MENU -> removeToolbar() } } override fun getHitTestSpots(): Sequence<Pair<RelativeRectangle, Int>> { return when (mode) { ShowMode.MENU -> { super.getHitTestSpots() + Pair(getElementRect(myMenuBar) { rect -> val state = frame.extendedState if (state != Frame.MAXIMIZED_VERT && state != Frame.MAXIMIZED_BOTH) { val topGap = (rect.height / 3).toFloat().roundToInt() rect.y += topGap rect.height -= topGap } }, MENU_BAR) } ShowMode.TOOLBAR -> { super.getHitTestSpots() + Pair(getElementRect(mainMenuButton.button), MENU_BAR) + (toolbar?.components?.asSequence()?.filter { it.isVisible }?.map { Pair(getElementRect(it), MENU_BAR) } ?: emptySequence()) } } } override fun getHeaderBackground(active: Boolean) = CustomFrameDecorations.mainToolbarBackground(active) private fun getElementRect(comp: Component, rectProcessor: ((Rectangle) -> Unit)? = null): RelativeRectangle { val rect = Rectangle(comp.size) rectProcessor?.invoke(rect) return RelativeRectangle(comp, rect) } private fun createHeaderContent(): JPanel { val res = NonOpaquePanel(CardLayout()) res.border = JBUI.Borders.empty() val menuPnl = NonOpaquePanel(GridBagLayout()).apply { val gb = GridBag().anchor(WEST).nextLine() add(myMenuBar, gb.next().insetLeft(JBUI.scale(20)).fillCellVertically().weighty(1.0)) add(Box.createHorizontalGlue(), gb.next().weightx(1.0).fillCell()) } val toolbarPnl = NonOpaquePanel(GridBagLayout()).apply { val gb = GridBag().anchor(WEST).nextLine() add(mainMenuButton.button, gb.next().insetLeft(JBUI.scale(20))) add(myToolbarPlaceholder, gb.next().weightx(1.0).fillCellHorizontally().insetLeft(JBUI.scale(16))) } res.add(ShowMode.MENU.name, menuPnl) res.add(ShowMode.TOOLBAR.name, toolbarPnl) return res } private fun updateLayout(settings: UISettings) { mode = if (isToolbarInHeader(settings)) ShowMode.TOOLBAR else ShowMode.MENU val layout = myHeaderContent.layout as CardLayout layout.show(myHeaderContent, mode.name) } }
apache-2.0
ac904e6d906a910ddf76bb06738554ba
35.672515
150
0.741827
4.307005
false
false
false
false
mdaniel/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/AddJvmInlineIntention.kt
2
2013
// 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.intentions import com.intellij.codeInsight.intention.HighPriorityAction import com.intellij.codeInsight.intention.IntentionAction import com.intellij.openapi.editor.Editor import com.intellij.openapi.util.TextRange import org.jetbrains.kotlin.diagnostics.Diagnostic import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.codeinsight.api.classic.intentions.SelfTargetingRangeIntention import org.jetbrains.kotlin.idea.quickfix.KotlinSingleIntentionActionFactory import org.jetbrains.kotlin.idea.util.addAnnotation import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.psi.KtClass import org.jetbrains.kotlin.psi.KtModifierListOwner import org.jetbrains.kotlin.psi.psiUtil.getParentOfType import org.jetbrains.kotlin.resolve.JVM_INLINE_ANNOTATION_FQ_NAME import org.jetbrains.kotlin.resolve.jvm.diagnostics.ErrorsJvm class AddJvmInlineIntention : SelfTargetingRangeIntention<KtClass>( KtClass::class.java, KotlinBundle.lazyMessage("add.jvminline.annotation") ), HighPriorityAction { override fun applyTo(element: KtClass, editor: Editor?) { element.addAnnotation(JVM_INLINE_ANNOTATION_FQ_NAME) } override fun applicabilityRange(element: KtClass): TextRange? { if (!element.isValue()) return null val modifier = element.modifierList?.getModifier(KtTokens.VALUE_KEYWORD) ?: return null return modifier.textRange } companion object : KotlinSingleIntentionActionFactory() { override fun createAction(diagnostic: Diagnostic): IntentionAction? { val valueModifier = ErrorsJvm.VALUE_CLASS_WITHOUT_JVM_INLINE_ANNOTATION.cast(diagnostic) ?: return null if (valueModifier.psiElement.getParentOfType<KtModifierListOwner>(strict = true) == null) return null return AddJvmInlineIntention() } } }
apache-2.0
10c00269e3e2002f231f89284adc3192
45.837209
120
0.789369
4.725352
false
false
false
false
akvo/akvo-rsr-up
android/AkvoRSR/app/src/main/java/org/akvo/rsr/up/worker/SubmitProjectUpdateWorker.kt
1
2342
package org.akvo.rsr.up.worker import android.annotation.SuppressLint import android.content.Context import android.util.Log import androidx.work.Worker import androidx.work.WorkerParameters import androidx.work.workDataOf import org.akvo.rsr.up.util.ConstantUtil import org.akvo.rsr.up.util.SettingsUtil import org.akvo.rsr.up.util.Uploader import org.akvo.rsr.up.util.Uploader.FailedPostException import org.akvo.rsr.up.util.Uploader.UnresolvedPostException class SubmitProjectUpdateWorker(ctx: Context, params: WorkerParameters) : Worker(ctx, params) { @SuppressLint("LongLogTag") override fun doWork(): Result { val projectId = inputData.getString(ConstantUtil.UPDATE_ID_KEY) val appContext = applicationContext val sendImg = SettingsUtil.ReadBoolean(appContext, ConstantUtil.SEND_IMG_SETTING_KEY, true) val user = SettingsUtil.getAuthUser(appContext) if (projectId != null) { try { Uploader.sendUpdate( appContext, projectId, SettingsUtil.host(appContext) + ConstantUtil.POST_UPDATE_URL, // + ConstantUtil.API_KEY_PATTERN, SettingsUtil.host(appContext) + ConstantUtil.VERIFY_UPDATE_PATTERN, sendImg, user ) { sofar, total -> setProgressAsync( workDataOf( ConstantUtil.SOFAR_KEY to sofar, ConstantUtil.TOTAL_KEY to total ) ) } return Result.success() } catch (e: FailedPostException) { return Result.failure(workDataOf(ConstantUtil.SERVICE_ERRMSG_KEY to e.message)) } catch (e: UnresolvedPostException) { return Result.failure( workDataOf( ConstantUtil.SERVICE_ERRMSG_KEY to e.message, ConstantUtil.SERVICE_UNRESOLVED_KEY to true ) ) } catch (e: Exception) { // TODO: show to user Log.e(TAG, "Config problem", e) } } return Result.failure() } companion object { const val TAG = "SubmitProjectUpdateWorker" } }
agpl-3.0
a9f2d7a718b0f036dac05abfb03438e9
38.033333
116
0.584543
4.869023
false
false
false
false
tginsberg/advent-2016-kotlin
src/main/kotlin/com/ginsberg/advent2016/Day03.kt
1
1778
/* * Copyright (c) 2016 by Todd Ginsberg */ package com.ginsberg.advent2016 /** * Advent of Code - Day 3: December 3, 2016 * * From http://adventofcode.com/2016/day/3 * */ class Day03(rawInput: String) { private val inputAsDigits = rawInput.trim().split(Regex("\\s+")).map(String::toInt) /** * In your puzzle input, how many of the listed triangles are possible? */ fun solvePart1(): Int = countValidTriangles(inputByHorizontal()) /** * In your puzzle input, and instead reading by columns, how many of the * listed triangles are possible? */ fun solvePart2(): Int = countValidTriangles(inputByVertical()) // Takes advantage of descending sort of the triplets so we can // just subtract the numbers as a reduction and compare to zero. private fun countValidTriangles(sides: List<List<Int>>): Int = sides.filter { it.reduce { a, b -> a - b } < 0 }.size // Picks out triplets of numbers horizontally private fun inputByHorizontal(): List<List<Int>> = (0..inputAsDigits.size-3 step 3).map { row -> listOf(inputAsDigits[row+0], inputAsDigits[row+1], inputAsDigits[row+2]).sortedDescending() } // Picks out triplets of numbers vertically. Break the input into groups // of nine numbers, and pick out three groups of three. private fun inputByVertical(): List<List<Int>> = (0..inputAsDigits.size-9 step 9).flatMap { group -> (0..2).map { col -> listOf(inputAsDigits[group+col+0], inputAsDigits[group+col+3], inputAsDigits[group+col+6]).sortedDescending() } } }
mit
0bc433187f31ceb5b9f834c256e80633
32.54717
87
0.595613
4.115741
false
false
false
false
GunoH/intellij-community
plugins/markdown/core/src/org/intellij/plugins/markdown/lang/psi/impl/MarkdownLinkText.kt
7
987
package org.intellij.plugins.markdown.lang.psi.impl import com.intellij.extapi.psi.ASTWrapperPsiElement import com.intellij.lang.ASTNode import com.intellij.psi.PsiElement import org.intellij.plugins.markdown.lang.MarkdownTokenTypes import org.intellij.plugins.markdown.lang.psi.MarkdownPsiElement import org.intellij.plugins.markdown.lang.psi.util.children import org.intellij.plugins.markdown.lang.psi.util.hasType import org.jetbrains.annotations.ApiStatus @ApiStatus.Experimental class MarkdownLinkText(node: ASTNode): ASTWrapperPsiElement(node), MarkdownPsiElement { /** * Actual content elements without opening bracket at the start and closing backet at the end. */ val contentElements: Sequence<PsiElement> get() { val openBracket = firstChild?.takeIf { it.hasType(MarkdownTokenTypes.LBRACKET) } val closeBracket = lastChild?.takeIf { it.hasType(MarkdownTokenTypes.RBRACKET) } return children().filterNot { it == openBracket || it == closeBracket } } }
apache-2.0
5804e6f5aebb82ee4e9e98732cd21c29
43.863636
96
0.798379
4.272727
false
false
false
false
GunoH/intellij-community
plugins/kotlin/gradle/gradle-java/tests/test/org/jetbrains/kotlin/idea/codeInsight/gradle/GradleBuildFileHighlightingTest.kt
1
4582
// 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.codeInsight.gradle import com.intellij.openapi.util.registry.Registry import com.intellij.openapi.vfs.VirtualFile import com.intellij.psi.PsiManager import com.intellij.testFramework.runInEdtAndWait import org.jetbrains.kotlin.diagnostics.Severity import org.jetbrains.kotlin.diagnostics.rendering.DefaultErrorMessages import org.jetbrains.kotlin.idea.caches.resolve.analyzeWithContent import org.jetbrains.kotlin.idea.core.script.ScriptConfigurationManager import org.jetbrains.kotlin.idea.core.script.ucache.KOTLIN_SCRIPTS_AS_ENTITIES import com.intellij.openapi.application.runReadAction import org.jetbrains.kotlin.psi.KtFile import org.jetbrains.plugins.gradle.tooling.annotation.TargetVersions import org.jetbrains.plugins.gradle.util.GradleConstants import org.junit.Ignore import org.junit.Rule import org.junit.Test import org.junit.rules.ExternalResource import org.junit.runners.Parameterized abstract class GradleBuildFileHighlightingTest : KotlinGradleImportingTestCase() { companion object { private val GRADLE_VERSION_AND_SCRIPT_FLAG = SUPPORTED_GRADLE_VERSIONS .map { listOf(arrayOf(it, false), arrayOf(it, true)) } .flatten() @JvmStatic @Suppress("ACCIDENTAL_OVERRIDE") @Parameterized.Parameters(name = "{index}: with Gradle-{0}, scriptsAsEntities-{1}") fun testInputData(): List<Array<out Any>> = GRADLE_VERSION_AND_SCRIPT_FLAG } @JvmField @Parameterized.Parameter(1) var scriptsAsEntities: Boolean? = null @JvmField @Rule val setRegistryFlag = RegistryFlagRule() inner class RegistryFlagRule : ExternalResource() { override fun before() { Registry.get(KOTLIN_SCRIPTS_AS_ENTITIES).setValue(scriptsAsEntities!!) } override fun after() { Registry.get(KOTLIN_SCRIPTS_AS_ENTITIES).resetToDefault() } } class KtsInJsProject2114 : GradleBuildFileHighlightingTest() { @TargetVersions("4.8 <=> 6.0") @Test fun testKtsInJsProject() { val buildGradleKts = configureByFiles().findBuildGradleKtsFile() importProjectUsingSingeModulePerGradleProject() checkHighlighting(buildGradleKts) } } class Simple : GradleBuildFileHighlightingTest() { @TargetVersions("5.3+") @Test fun testSimple() { val buildGradleKts = configureByFiles().findBuildGradleKtsFile() importProjectUsingSingeModulePerGradleProject() checkHighlighting(buildGradleKts) } } class ComplexBuildGradleKts : GradleBuildFileHighlightingTest() { @Ignore @TargetVersions("4.8+") @Test fun testComplexBuildGradleKts() { val buildGradleKts = configureByFiles().findBuildGradleKtsFile() importProjectUsingSingeModulePerGradleProject() checkHighlighting(buildGradleKts) } } class JavaLibraryPlugin14 : GradleBuildFileHighlightingTest() { @Test @TargetVersions("6.0.1+") fun testJavaLibraryPlugin() { val buildGradleKts = configureByFiles().findBuildGradleKtsFile() importProject() checkHighlighting(buildGradleKts) } } protected fun List<VirtualFile>.findBuildGradleKtsFile(): VirtualFile { return singleOrNull { it.name == GradleConstants.KOTLIN_DSL_SCRIPT_NAME } ?: error("Couldn't find any build.gradle.kts file") } protected fun checkHighlighting(file: VirtualFile) { runInEdtAndWait { runReadAction { val psiFile = PsiManager.getInstance(myProject).findFile(file) as? KtFile ?: error("Couldn't find psiFile for virtual file: ${file.canonicalPath}") ScriptConfigurationManager.updateScriptDependenciesSynchronously(psiFile) val bindingContext = psiFile.analyzeWithContent() val diagnostics = bindingContext.diagnostics.filter { it.severity == Severity.ERROR } assert(diagnostics.isEmpty()) { val diagnosticLines = diagnostics.joinToString("\n") { DefaultErrorMessages.render(it) } "Diagnostic list should be empty:\n $diagnosticLines" } } } } override fun testDataDirName() = "highlighting" }
apache-2.0
1ce5640cb40ddf1ea58bf2819d4a0a1c
35.086614
158
0.686381
5.035165
false
true
false
false
GunoH/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/AddAnnotationTargetFix.kt
1
10707
// 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 import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import com.intellij.psi.* import com.intellij.psi.search.GlobalSearchScope import com.intellij.psi.search.searches.ReferencesSearch import org.jetbrains.kotlin.asJava.LightClassUtil import org.jetbrains.kotlin.builtins.StandardNames import org.jetbrains.kotlin.descriptors.ClassDescriptor import org.jetbrains.kotlin.descriptors.annotations.AnnotationUseSiteTarget import org.jetbrains.kotlin.descriptors.annotations.KotlinTarget import org.jetbrains.kotlin.diagnostics.Diagnostic import org.jetbrains.kotlin.diagnostics.Errors.WRONG_ANNOTATION_TARGET import org.jetbrains.kotlin.diagnostics.Errors.WRONG_ANNOTATION_TARGET_WITH_USE_SITE_TARGET import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.caches.resolve.analyze import org.jetbrains.kotlin.idea.codeinsight.api.classic.quickfixes.KotlinQuickFixAction import org.jetbrains.kotlin.idea.core.util.runSynchronouslyWithProgressIfEdt import com.intellij.openapi.application.runWriteAction import org.jetbrains.kotlin.idea.util.runOnExpectAndAllActuals import org.jetbrains.kotlin.name.FqName import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.getNonStrictParentOfType import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType import org.jetbrains.kotlin.resolve.AnnotationChecker import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.BindingTraceContext import org.jetbrains.kotlin.resolve.DescriptorToSourceUtils import org.jetbrains.kotlin.resolve.constants.EnumValue import org.jetbrains.kotlin.resolve.constants.TypedArrayValue import org.jetbrains.kotlin.resolve.descriptorUtil.firstArgument import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode import org.jetbrains.kotlin.utils.addToStdlib.safeAs class AddAnnotationTargetFix(annotationEntry: KtAnnotationEntry) : KotlinQuickFixAction<KtAnnotationEntry>(annotationEntry) { override fun getText() = KotlinBundle.message("fix.add.annotation.target") override fun getFamilyName() = text override fun startInWriteAction(): Boolean = false override fun invoke(project: Project, editor: Editor?, file: KtFile) { val annotationEntry = element ?: return val (annotationClass, annotationClassDescriptor) = annotationEntry.toAnnotationClass() ?: return val requiredAnnotationTargets = annotationEntry.getRequiredAnnotationTargets(annotationClass, annotationClassDescriptor, project) if (requiredAnnotationTargets.isEmpty()) return annotationClass.runOnExpectAndAllActuals(useOnSelf = true) { val ktClass = it.safeAs<KtClass>() ?: return@runOnExpectAndAllActuals val psiFactory = KtPsiFactory(annotationEntry) runWriteAction { ktClass.addAnnotationTargets(requiredAnnotationTargets, psiFactory) } } } companion object : KotlinSingleIntentionActionFactory() { private fun KtAnnotationEntry.toAnnotationClass(): Pair<KtClass, ClassDescriptor>? { val context = analyze(BodyResolveMode.PARTIAL) val annotationDescriptor = context[BindingContext.ANNOTATION, this] ?: return null val annotationTypeDescriptor = annotationDescriptor.type.constructor.declarationDescriptor as? ClassDescriptor ?: return null val annotationClass = (DescriptorToSourceUtils.descriptorToDeclaration(annotationTypeDescriptor) as? KtClass)?.takeIf { it.isAnnotation() && it.isWritable } ?: return null return annotationClass to annotationTypeDescriptor } override fun createAction(diagnostic: Diagnostic): KotlinQuickFixAction<KtAnnotationEntry>? { if (diagnostic.factory != WRONG_ANNOTATION_TARGET && diagnostic.factory != WRONG_ANNOTATION_TARGET_WITH_USE_SITE_TARGET) { return null } val entry = diagnostic.psiElement as? KtAnnotationEntry ?: return null val (annotationClass, annotationClassDescriptor) = entry.toAnnotationClass() ?: return null if (entry.getRequiredAnnotationTargets(annotationClass, annotationClassDescriptor, entry.project).isEmpty()) return null return AddAnnotationTargetFix(entry) } } } private fun KtAnnotationEntry.getRequiredAnnotationTargets( annotationClass: KtClass, annotationClassDescriptor: ClassDescriptor, project: Project ): List<KotlinTarget> { val ignoredTargets = if (annotationClassDescriptor.hasRequiresOptInAnnotation()) { listOf(AnnotationTarget.EXPRESSION, AnnotationTarget.FILE, AnnotationTarget.TYPE, AnnotationTarget.TYPE_PARAMETER) .map { it.name } .toSet() } else emptySet() val existingTargets = annotationClassDescriptor.annotations .firstOrNull { it.fqName == StandardNames.FqNames.target } ?.firstArgument() .safeAs<TypedArrayValue>() ?.value ?.mapNotNull { it.safeAs<EnumValue>()?.enumEntryName?.asString() } ?.toSet() .orEmpty() val validTargets = AnnotationTarget.values() .map { it.name } .minus(ignoredTargets) .minus(existingTargets) .toSet() if (validTargets.isEmpty()) return emptyList() val requiredTargets = getActualTargetList() if (requiredTargets.isEmpty()) return emptyList() val searchScope = GlobalSearchScope.allScope(project) return project.runSynchronouslyWithProgressIfEdt(KotlinBundle.message("progress.looking.up.add.annotation.usage"), true) { val otherReferenceRequiredTargets = ReferencesSearch.search(annotationClass, searchScope).mapNotNull { reference -> if (reference.element is KtNameReferenceExpression) { // Kotlin annotation reference.element.getNonStrictParentOfType<KtAnnotationEntry>()?.takeIf { it != this }?.getActualTargetList() } else { // Java annotation (reference.element.parent as? PsiAnnotation)?.getActualTargetList() } }.flatten().toSet() (requiredTargets + otherReferenceRequiredTargets).asSequence() .distinct() .filter { it.name in validTargets } .sorted() .toList() } ?: emptyList() } private fun ClassDescriptor.hasRequiresOptInAnnotation() = annotations.any { it.fqName == FqName("kotlin.RequiresOptIn") } private fun PsiAnnotation.getActualTargetList(): List<KotlinTarget> { val target = when (val annotated = this.parent.parent) { is PsiClass -> KotlinTarget.CLASS is PsiMethod -> when { annotated.isConstructor -> KotlinTarget.CONSTRUCTOR else -> KotlinTarget.FUNCTION } is PsiExpression -> KotlinTarget.EXPRESSION is PsiField -> KotlinTarget.FIELD is PsiLocalVariable -> KotlinTarget.LOCAL_VARIABLE is PsiParameter -> KotlinTarget.VALUE_PARAMETER is PsiTypeParameterList -> KotlinTarget.TYPE is PsiReferenceList -> KotlinTarget.TYPE_PARAMETER else -> null } return listOfNotNull(target) } private fun KtAnnotationEntry.getActualTargetList(): List<KotlinTarget> { val annotatedElement = getStrictParentOfType<KtModifierList>()?.owner as? KtElement ?: getStrictParentOfType<KtAnnotatedExpression>()?.baseExpression ?: getStrictParentOfType<KtFile>() ?: return emptyList() val targetList = AnnotationChecker.getActualTargetList(annotatedElement, null, BindingTraceContext().bindingContext) val useSiteTarget = this.useSiteTarget ?: return targetList.defaultTargets val annotationUseSiteTarget = useSiteTarget.getAnnotationUseSiteTarget() val target = KotlinTarget.USE_SITE_MAPPING[annotationUseSiteTarget] ?: return emptyList() if (annotationUseSiteTarget == AnnotationUseSiteTarget.FIELD) { if (KotlinTarget.MEMBER_PROPERTY !in targetList.defaultTargets && KotlinTarget.TOP_LEVEL_PROPERTY !in targetList.defaultTargets) { return emptyList() } val property = annotatedElement as? KtProperty if (property != null && (LightClassUtil.getLightClassPropertyMethods(property).backingField == null || property.hasDelegate())) { return emptyList() } } else { if (target !in with(targetList) { defaultTargets + canBeSubstituted + onlyWithUseSiteTarget }) { return emptyList() } } return listOf(target) } private fun KtClass.addAnnotationTargets(annotationTargets: List<KotlinTarget>, psiFactory: KtPsiFactory) { val retentionAnnotationName = StandardNames.FqNames.retention.shortName().asString() if (annotationTargets.any { it == KotlinTarget.EXPRESSION }) { val retentionEntry = annotationEntries.firstOrNull { it.typeReference?.text == retentionAnnotationName } val newRetentionEntry = psiFactory.createAnnotationEntry( "@$retentionAnnotationName(${StandardNames.FqNames.annotationRetention.shortName()}.${AnnotationRetention.SOURCE.name})" ) if (retentionEntry == null) { addAnnotationEntry(newRetentionEntry) } else { retentionEntry.replace(newRetentionEntry) } } val targetAnnotationName = StandardNames.FqNames.target.shortName().asString() val targetAnnotationEntry = annotationEntries.find { it.typeReference?.text == targetAnnotationName } ?: run { val text = "@$targetAnnotationName${annotationTargets.toArgumentListString()}" addAnnotationEntry(psiFactory.createAnnotationEntry(text)) return } val valueArgumentList = targetAnnotationEntry.valueArgumentList if (valueArgumentList == null) { val text = annotationTargets.toArgumentListString() targetAnnotationEntry.add(psiFactory.createCallArguments(text)) } else { val arguments = targetAnnotationEntry.valueArguments.mapNotNull { it.getArgumentExpression()?.text } for (target in annotationTargets) { val text = target.asNameString() if (text !in arguments) valueArgumentList.addArgument(psiFactory.createArgument(text)) } } } private fun List<KotlinTarget>.toArgumentListString() = joinToString(separator = ", ", prefix = "(", postfix = ")") { it.asNameString() } private fun KotlinTarget.asNameString() = "${StandardNames.FqNames.annotationTarget.shortName().asString()}.$name"
apache-2.0
48badc18d6009f5ac7009e2e1496401f
47.22973
158
0.73083
5.457187
false
false
false
false
ktorio/ktor
ktor-server/ktor-server-netty/jvm/src/io/ktor/server/netty/cio/RequestBodyHandler.kt
1
6013
/* * 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.server.netty.cio import io.ktor.utils.io.* import io.netty.buffer.* import io.netty.channel.* import io.netty.handler.codec.http.* import io.netty.util.* import kotlinx.coroutines.* import kotlinx.coroutines.channels.Channel import java.lang.Integer.* import kotlin.coroutines.* internal class RequestBodyHandler( val context: ChannelHandlerContext ) : ChannelInboundHandlerAdapter(), CoroutineScope { private val handlerJob = CompletableDeferred<Nothing>() private val queue = Channel<Any>(Channel.UNLIMITED) private object Upgrade override val coroutineContext: CoroutineContext get() = handlerJob private val job = launch(context.executor().asCoroutineDispatcher(), start = CoroutineStart.LAZY) { var current: ByteWriteChannel? = null var upgraded = false try { while (true) { val event = queue.tryReceive().getOrNull() ?: run { current?.flush(); queue.receiveCatching().getOrNull() } ?: break when (event) { is ByteBufHolder -> { val channel = current ?: error("No current channel but received a byte buf") processContent(channel, event) if (!upgraded && event is LastHttpContent) { current.close() current = null } requestMoreEvents() } is ByteBuf -> { val channel = current ?: error("No current channel but received a byte buf") processContent(channel, event) requestMoreEvents() } is ByteWriteChannel -> { current?.close() current = event } is Upgrade -> { upgraded = true } } } } catch (t: Throwable) { queue.close(t) current?.close(t) } finally { current?.close() queue.close() consumeAndReleaseQueue() } } @OptIn(ExperimentalCoroutinesApi::class) fun upgrade(): ByteReadChannel { val result = queue.trySend(Upgrade) if (result.isSuccess) return newChannel() if (queue.isClosedForSend) { throw CancellationException("HTTP pipeline has been terminated.", result.exceptionOrNull()) } throw IllegalStateException( "Unable to start request processing: failed to offer " + "$Upgrade to the HTTP pipeline queue. " + "Queue closed: ${queue.isClosedForSend}" ) } fun newChannel(): ByteReadChannel { val result = ByteChannel() tryOfferChannelOrToken(result) return result } @OptIn(ExperimentalCoroutinesApi::class) private fun tryOfferChannelOrToken(token: Any) { val result = queue.trySend(token) if (result.isSuccess) return if (queue.isClosedForSend) { throw CancellationException("HTTP pipeline has been terminated.", result.exceptionOrNull()) } throw IllegalStateException( "Unable to start request processing: failed to offer " + "$token to the HTTP pipeline queue. " + "Queue closed: ${queue.isClosedForSend}" ) } fun close() { queue.close() } override fun channelRead(context: ChannelHandlerContext, msg: Any?) { when (msg) { is ByteBufHolder -> handleBytesRead(msg) is ByteBuf -> handleBytesRead(msg) else -> context.fireChannelRead(msg) } } private suspend fun processContent(current: ByteWriteChannel, event: ByteBufHolder): Int { try { val buf = event.content() return copy(buf, current) } finally { event.release() } } private suspend fun processContent(current: ByteWriteChannel, buf: ByteBuf): Int { try { return copy(buf, current) } finally { buf.release() } } private fun requestMoreEvents() { context.read() } @OptIn(ExperimentalCoroutinesApi::class) private fun consumeAndReleaseQueue() { while (!queue.isEmpty) { val e = try { queue.tryReceive().getOrNull() } catch (t: Throwable) { null } ?: break when (e) { is ByteChannel -> e.close() is ReferenceCounted -> e.release() else -> { } } } } private suspend fun copy(buf: ByteBuf, dst: ByteWriteChannel): Int { val length = buf.readableBytes() if (length > 0) { val buffer = buf.internalNioBuffer(buf.readerIndex(), length) dst.writeFully(buffer) } return max(length, 0) } private fun handleBytesRead(content: ReferenceCounted) { if (!queue.trySend(content).isSuccess) { content.release() throw IllegalStateException("Unable to process received buffer: queue offer failed") } } @Suppress("OverridingDeprecatedMember") override fun exceptionCaught(ctx: ChannelHandlerContext?, cause: Throwable) { handlerJob.completeExceptionally(cause) queue.close(cause) } override fun handlerRemoved(ctx: ChannelHandlerContext?) { if (queue.close() && job.isCompleted) { consumeAndReleaseQueue() handlerJob.cancel() } } override fun handlerAdded(ctx: ChannelHandlerContext?) { job.start() } }
apache-2.0
364cf45273ae384a9c4235c192b8fa8b
29.994845
118
0.554133
5.288478
false
false
false
false
google/accompanist
sample/src/main/java/com/google/accompanist/sample/swiperefresh/SwipeRefreshCustomIndicatorSample.kt
1
6428
/* * Copyright 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ @file:Suppress("DEPRECATION") package com.google.accompanist.sample.swiperefresh import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.compose.animation.core.FastOutSlowInEasing import androidx.compose.foundation.Image import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.width import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.material.LinearProgressIndicator import androidx.compose.material.MaterialTheme import androidx.compose.material.Scaffold import androidx.compose.material.Text import androidx.compose.material.TopAppBar import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.drawWithCache import androidx.compose.ui.graphics.Brush import androidx.compose.ui.graphics.Color import androidx.compose.ui.platform.LocalDensity import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.dp import com.google.accompanist.sample.AccompanistSampleTheme import com.google.accompanist.sample.R import com.google.accompanist.swiperefresh.SwipeRefresh import com.google.accompanist.swiperefresh.SwipeRefreshState import com.google.accompanist.swiperefresh.rememberSwipeRefreshState import kotlinx.coroutines.delay class SwipeRefreshCustomIndicatorSample : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { AccompanistSampleTheme { Sample() } } } } @Suppress("DEPRECATION") @Composable private fun Sample() { Scaffold( topBar = { TopAppBar( title = { Text(stringResource(R.string.swiperefresh_title_custom)) }, backgroundColor = MaterialTheme.colors.surface, ) }, modifier = Modifier.fillMaxSize() ) { padding -> // Simulate a fake 2-second 'load'. Ideally this 'refreshing' value would // come from a ViewModel or similar var refreshing by remember { mutableStateOf(false) } LaunchedEffect(refreshing) { if (refreshing) { delay(2000) refreshing = false } } SwipeRefresh( state = rememberSwipeRefreshState(isRefreshing = refreshing), onRefresh = { refreshing = true }, indicator = { state, trigger -> GlowIndicator( swipeRefreshState = state, refreshTriggerDistance = trigger ) }, ) { LazyColumn(contentPadding = padding) { items(30) { Row(Modifier.padding(16.dp)) { Image( painter = painterResource(R.drawable.placeholder), contentDescription = null, modifier = Modifier.size(64.dp), ) Spacer(Modifier.width(8.dp)) Text( text = "Text", style = MaterialTheme.typography.subtitle2, modifier = Modifier .weight(1f) .align(Alignment.CenterVertically) ) } } } } } } /** * A custom indicator which displays a glow and progress indicator */ @Composable fun GlowIndicator( swipeRefreshState: SwipeRefreshState, refreshTriggerDistance: Dp, color: Color = MaterialTheme.colors.primary, ) { Box( Modifier .drawWithCache { onDrawBehind { val distance = refreshTriggerDistance.toPx() val progress = (swipeRefreshState.indicatorOffset / distance).coerceIn(0f, 1f) // We draw a translucent glow val brush = Brush.verticalGradient( 0f to color.copy(alpha = 0.45f), 1f to color.copy(alpha = 0f) ) // And fade the glow in/out based on the swipe progress drawRect(brush = brush, alpha = FastOutSlowInEasing.transform(progress)) } } .fillMaxWidth() .height(72.dp) ) { if (swipeRefreshState.isRefreshing) { // If we're refreshing, show an indeterminate progress indicator LinearProgressIndicator(Modifier.fillMaxWidth()) } else { // Otherwise we display a determinate progress indicator with the current swipe progress val trigger = with(LocalDensity.current) { refreshTriggerDistance.toPx() } val progress = (swipeRefreshState.indicatorOffset / trigger).coerceIn(0f, 1f) LinearProgressIndicator( progress = progress, modifier = Modifier.fillMaxWidth(), ) } } }
apache-2.0
b097ba580ce477d7e73cb081871c8736
36.156069
100
0.643279
5.217532
false
false
false
false
armcha/Ribble
app/src/main/kotlin/io/armcha/ribble/presentation/utils/delegates/BundleDelegate.kt
1
1476
package io.armcha.ribble.presentation.utils.delegates import android.os.Bundle import android.os.Parcelable import android.support.v4.app.Fragment import io.armcha.ribble.presentation.utils.extensions.isNull import java.io.Serializable import kotlin.properties.ReadOnlyProperty import kotlin.reflect.KProperty /** * Created by Chatikyan on 30.09.2017. */ inline fun <reified VALUE> bundle() = object : ReadOnlyProperty<Fragment, VALUE> { private var value: VALUE? = null override fun getValue(thisRef: Fragment, property: KProperty<*>): VALUE { if (value.isNull) { value = thisRef.arguments[property.name] as VALUE } return value!! } } inline operator fun <reified V> Bundle.setValue(thisRef: Any?, property: KProperty<*>, value: V): Bundle { put(property.name to thisRef) return this } inline fun <reified V> Bundle.put(pair: Pair<String, V>): Bundle { val value = pair.second val key = pair.first when (value) { is Int -> putInt(key, value) is Long -> putLong(key, value) is String -> putString(key, value) is Parcelable -> putParcelable(key, value) is Serializable -> putSerializable(key, value) else -> throw UnsupportedOperationException("$value type not supported yet!!!") } return this } infix fun String.bundleWith(value: Any?): Bundle { val bundle = Bundle() val key = this bundle.put(key to value) return bundle }
apache-2.0
0cf4030069c9594cd9532be682040dc6
26.849057
106
0.680894
4.1
false
false
false
false
inorichi/mangafeed
app/src/main/java/eu/kanade/tachiyomi/ui/reader/loader/ChapterLoader.kt
2
3623
package eu.kanade.tachiyomi.ui.reader.loader import android.content.Context import eu.kanade.tachiyomi.R import eu.kanade.tachiyomi.data.database.models.Manga import eu.kanade.tachiyomi.data.download.DownloadManager import eu.kanade.tachiyomi.source.LocalSource import eu.kanade.tachiyomi.source.Source import eu.kanade.tachiyomi.source.online.HttpSource import eu.kanade.tachiyomi.ui.reader.model.ReaderChapter import eu.kanade.tachiyomi.util.system.logcat import rx.Completable import rx.Observable import rx.android.schedulers.AndroidSchedulers import rx.schedulers.Schedulers /** * Loader used to retrieve the [PageLoader] for a given chapter. */ class ChapterLoader( private val context: Context, private val downloadManager: DownloadManager, private val manga: Manga, private val source: Source ) { /** * Returns a completable that assigns the page loader and loads the its pages. It just * completes if the chapter is already loaded. */ fun loadChapter(chapter: ReaderChapter): Completable { if (chapterIsReady(chapter)) { return Completable.complete() } return Observable.just(chapter) .doOnNext { chapter.state = ReaderChapter.State.Loading } .observeOn(Schedulers.io()) .flatMap { readerChapter -> logcat { "Loading pages for ${chapter.chapter.name}" } val loader = getPageLoader(readerChapter) chapter.pageLoader = loader loader.getPages().take(1).doOnNext { pages -> pages.forEach { it.chapter = chapter } } } .observeOn(AndroidSchedulers.mainThread()) .doOnError { chapter.state = ReaderChapter.State.Error(it) } .doOnNext { pages -> if (pages.isEmpty()) { throw Exception(context.getString(R.string.page_list_empty_error)) } chapter.state = ReaderChapter.State.Loaded(pages) // If the chapter is partially read, set the starting page to the last the user read // otherwise use the requested page. if (!chapter.chapter.read) { chapter.requestedPage = chapter.chapter.last_page_read } } .toCompletable() } /** * Checks [chapter] to be loaded based on present pages and loader in addition to state. */ private fun chapterIsReady(chapter: ReaderChapter): Boolean { return chapter.state is ReaderChapter.State.Loaded && chapter.pageLoader != null } /** * Returns the page loader to use for this [chapter]. */ private fun getPageLoader(chapter: ReaderChapter): PageLoader { val isDownloaded = downloadManager.isChapterDownloaded(chapter.chapter, manga, true) return when { isDownloaded -> DownloadPageLoader(chapter, manga, source, downloadManager) source is HttpSource -> HttpPageLoader(chapter, source) source is LocalSource -> source.getFormat(chapter.chapter).let { format -> when (format) { is LocalSource.Format.Directory -> DirectoryPageLoader(format.file) is LocalSource.Format.Zip -> ZipPageLoader(format.file) is LocalSource.Format.Rar -> RarPageLoader(format.file) is LocalSource.Format.Epub -> EpubPageLoader(format.file) } } else -> error(context.getString(R.string.loader_not_implemented_error)) } } }
apache-2.0
733e960a1db5ac98b92142d7e10ea4b7
37.956989
100
0.635109
4.850067
false
false
false
false
WilliamHester/Breadit-2
app/app/src/main/java/me/williamhester/reddit/ui/activities/MainActivity.kt
1
2877
package me.williamhester.reddit.ui.activities import android.os.Bundle import androidx.fragment.app.Fragment import androidx.viewpager2.adapter.FragmentStateAdapter import androidx.viewpager2.widget.ViewPager2 import com.google.android.material.bottomnavigation.BottomNavigationView import com.google.common.collect.HashBiMap import me.williamhester.reddit.R import me.williamhester.reddit.ui.fragments.SubmissionFragment import me.williamhester.reddit.ui.fragments.SubredditsFragment /** The main activity */ class MainActivity : BaseActivity() { override val layoutId = R.layout.activity_main private var selectedTab: Int = HOME_POSITION private lateinit var viewPager: ViewPager2 private lateinit var bottomNavigation: BottomNavigationView override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) selectedTab = savedInstanceState?.getInt(SELECTED_TAB, HOME_POSITION) ?: HOME_POSITION viewPager = findViewById(R.id.view_pager) bottomNavigation = findViewById(R.id.bottom_navigation) viewPager.adapter = HomeViewPagerAdapter() viewPager.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() { override fun onPageSelected(position: Int) { bottomNavigation.selectedItemId = POSITION_TO_ID[position]!! } }) bottomNavigation.setOnItemSelectedListener { selectTab(POSITION_TO_ID.inverse()[it.itemId]!!) return@setOnItemSelectedListener true } bottomNavigation.selectedItemId = selectedTab viewPager.currentItem = selectedTab } private fun selectTab(position: Int) { if (selectedTab == position) return selectedTab = position viewPager.currentItem = position } override fun onSaveInstanceState(outState: Bundle) { super.onSaveInstanceState(outState) outState.putInt(SELECTED_TAB, selectedTab) } inner class HomeViewPagerAdapter : FragmentStateAdapter(this) { override fun getItemCount(): Int = 4 override fun createFragment(position: Int): Fragment { return when (position) { SUBREDDIT_LIST_POSITION -> SubredditsFragment() HOME_POSITION -> SubmissionFragment.newInstance() USER_POSITION -> Fragment() // Placeholder SEARCH_POSITION -> Fragment() // Placeholder else -> throw IllegalStateException("Unexpected position") } } } companion object { private const val SELECTED_TAB = "selectedTab" private const val SUBREDDIT_LIST_POSITION = 0 private const val HOME_POSITION = 1 private const val USER_POSITION = 2 private const val SEARCH_POSITION = 3 private val POSITION_TO_ID = HashBiMap.create( mutableMapOf( SUBREDDIT_LIST_POSITION to R.id.subreddit_list, HOME_POSITION to R.id.home, USER_POSITION to R.id.user, SEARCH_POSITION to R.id.search, ) ) } }
apache-2.0
3010d2f14130758ee898bcadb39c187a
31.325843
90
0.737226
4.771144
false
false
false
false
dbrant/apps-android-wikipedia
app/src/main/java/org/wikipedia/views/DrawableItemDecoration.kt
1
2548
package org.wikipedia.views import android.content.Context import android.graphics.Canvas import android.graphics.Rect import android.graphics.drawable.Drawable import android.view.View import androidx.annotation.AttrRes import androidx.appcompat.content.res.AppCompatResources import androidx.recyclerview.widget.RecyclerView import androidx.recyclerview.widget.RecyclerView.ItemDecoration import org.wikipedia.util.ResourceUtil // todo: replace with DividerItemDecoration once it supports headers and footers class DrawableItemDecoration @JvmOverloads constructor(context: Context, @AttrRes id: Int, private val drawStart: Boolean = false, private val drawEnd: Boolean = true) : ItemDecoration() { private val drawable: Drawable = AppCompatResources.getDrawable(context, ResourceUtil.getThemedAttributeId(context, id))!! override fun getItemOffsets(outRect: Rect, view: View, parent: RecyclerView, state: RecyclerView.State) { super.getItemOffsets(outRect, view, parent, state) outRect.top = drawable.intrinsicHeight if (parent.getChildAdapterPosition(view) == state.itemCount - 1) { outRect.bottom = drawable.intrinsicHeight } } override fun onDraw(canvas: Canvas, parent: RecyclerView, state: RecyclerView.State) { super.onDraw(canvas, parent, state) if (parent.childCount == 0) { return } val end = parent.childCount - 1 for (i in (if (drawStart) 0 else 1) until end) { draw(canvas, bounds(parent, parent.getChildAt(i), true)) } if (drawStart || parent.childCount > 1) { draw(canvas, bounds(parent, parent.getChildAt(end), true)) } if (drawEnd) { draw(canvas, bounds(parent, parent.getChildAt(end), false)) } } private fun bounds(parent: RecyclerView, child: View, top: Boolean): Rect { val layoutManager = parent.layoutManager val bounds = Rect() bounds.right = parent.width - parent.paddingRight bounds.left = parent.paddingLeft val height = drawable.intrinsicHeight bounds.top = if (top) layoutManager!!.getDecoratedTop(child) else layoutManager!!.getDecoratedBottom(child) - height bounds.bottom = bounds.top + height return bounds } private fun draw(canvas: Canvas, bounds: Rect) { drawable.bounds = bounds drawable.draw(canvas) } }
apache-2.0
30555835df38a2afd1a09b308613c719
40.770492
126
0.666797
4.834915
false
false
false
false
saffih/ElmDroid
app/src/main/java/saffih/elmdroid/gps/GpsService.kt
1
4173
/* * By Saffi Hartal, 2017. * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package saffih.elmdroid.gps import android.app.Service import android.content.Context import android.content.Intent import android.location.Location import android.os.Message import saffih.elmdroid.StateBase import saffih.elmdroid.gps.child.GpsChild import saffih.elmdroid.service.LocalService import saffih.elmdroid.service.LocalServiceClient import saffih.elmdroid.gps.child.Model as GpsLocalServiceModel import saffih.elmdroid.gps.child.Msg as GpsLocalServiceMsg // bound service class GpsService : Service() { val elm = GpsServiceApp(this) override fun onBind(intent: android.content.Intent): android.os.IBinder? { return elm.onBind(intent) } override fun onCreate() { super.onCreate() elm.onCreate() } override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int { return super.onStartCommand(intent, flags, startId) } override fun onDestroy() { elm.onDestroy() super.onDestroy() } override fun onRebind(intent: Intent?) { super.onRebind(intent) } override fun onUnbind(intent: Intent?): Boolean { return super.onUnbind(intent) } } // an exmaple for local service // app as annonymous inner class class GpsLocalService : LocalService() { private fun handleMSG(cur: saffih.elmdroid.gps.child.Msg) { app.dispatch(cur) } // service loop app val app = object : StateBase<GpsLocalServiceModel, GpsLocalServiceMsg>(this) { val gps = object : GpsChild(this@GpsLocalService) { override fun handleMSG(cur: saffih.elmdroid.gps.child.Msg) { [email protected](cur) } override fun onLocationChanged(location: Location) { broadcast(location) } private fun broadcast(location: Location) { val msg = Message.obtain(null, 0, location) broadcast(msg) } } override fun onCreate() { super.onCreate() gps.onCreate() } override fun onDestroy() { super.onDestroy() gps.onDestroy() } override fun init() = gps.init() override fun update(msg: GpsLocalServiceMsg, model: GpsLocalServiceModel) = gps.update(msg, model) } // delegate to app override fun onCreate() { super.onCreate() app.onCreate() } override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int { return super.onStartCommand(intent, flags, startId) } fun request() = app.dispatch(GpsLocalServiceMsg.requestLocationMsg()) override fun onDestroy() { unregisterAll() app.onDestroy() super.onDestroy() } override fun onRebind(intent: Intent?) { super.onRebind(intent) } override fun onUnbind(intent: Intent?): Boolean { return super.onUnbind(intent) } } // example only class GpsLocalServiceClient(me: Context) : LocalServiceClient<GpsLocalService>(me, localserviceJavaClass = GpsService::class.java) { override fun onReceive(payload: Message?) { payload?.obj as Location } }
apache-2.0
f031a5b05a4144d4b177542896a09921
27.195946
106
0.646777
4.388013
false
false
false
false
dhis2/dhis2-android-sdk
core/src/main/java/org/hisp/dhis/android/core/program/programindicatorengine/internal/ProgramIndicatorItemIdsCollector.kt
1
3639
/* * 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.program.programindicatorengine.internal import org.hisp.dhis.android.core.parser.internal.service.dataitem.DimensionalItemId import org.hisp.dhis.android.core.parser.internal.service.dataitem.DimensionalItemType import org.hisp.dhis.android.core.program.programindicatorengine.internal.ProgramIndicatorParserUtils.assumeProgramAttributeSyntax import org.hisp.dhis.android.core.program.programindicatorengine.internal.ProgramIndicatorParserUtils.assumeStageElementSyntax import org.hisp.dhis.parser.expression.antlr.ExpressionBaseListener import org.hisp.dhis.parser.expression.antlr.ExpressionParser import org.hisp.dhis.parser.expression.antlr.ExpressionParser.A_BRACE import org.hisp.dhis.parser.expression.antlr.ExpressionParser.HASH_BRACE internal class ProgramIndicatorItemIdsCollector : ExpressionBaseListener() { val itemIds: MutableList<DimensionalItemId> = mutableListOf() override fun enterExpr(ctx: ExpressionParser.ExprContext) { if (ctx.it != null) { when (ctx.it.type) { HASH_BRACE -> { assumeStageElementSyntax(ctx) val stageId = ctx.uid0.text val dataElementId = ctx.uid1.text itemIds.add( DimensionalItemId.builder() .dimensionalItemType(DimensionalItemType.TRACKED_ENTITY_DATA_VALUE) .id0(stageId) .id1(dataElementId) .build() ) } A_BRACE -> { assumeProgramAttributeSyntax(ctx) val attributeId = ctx.uid0.text itemIds.add( DimensionalItemId.builder() .dimensionalItemType(DimensionalItemType.TRACKED_ENTITY_ATTRIBUTE) .id0(attributeId) .build() ) } } } } }
bsd-3-clause
83df37f43d379c80d6698b5f80b19720
46.25974
130
0.680956
4.884564
false
false
false
false
mikepenz/FastAdapter
fastadapter-extensions-expandable/src/main/java/com/mikepenz/fastadapter/utils/AdapterUtil.kt
1
3298
package com.mikepenz.fastadapter.utils import com.mikepenz.fastadapter.FastAdapter import com.mikepenz.fastadapter.GenericItem import com.mikepenz.fastadapter.IExpandable import java.util.* /** * Created by mikepenz on 31.12.15. */ object AdapterUtil { /** * Internal method to restore the selection state of subItems * * @param item the parent item * @param selectedItems the list of selectedItems from the savedInstanceState */ @JvmStatic fun <Item> restoreSubItemSelectionStatesForAlternativeStateManagement(item: Item, selectedItems: List<String>?) where Item : GenericItem, Item : IExpandable<*> { if (!item.isExpanded) { val subItems = (item as IExpandable<*>).subItems for (i in subItems.indices) { val subItem = subItems[i] as Item val id = subItem.identifier.toString() if (selectedItems != null && selectedItems.contains(id)) { subItem.isSelected = true } restoreSubItemSelectionStatesForAlternativeStateManagement(subItem, selectedItems) } } } /** * Internal method to find all selections from subItems and sub sub items so we can save those inside our savedInstanceState * * @param item the parent item * @param selections the ArrayList which will be stored in the savedInstanceState */ @JvmStatic fun <Item> findSubItemSelections(item: Item, selections: MutableList<String>) where Item : GenericItem, Item : IExpandable<*> { if (!item.isExpanded) { val subItems = (item as IExpandable<*>).subItems for (i in subItems.indices) { val subItem = subItems[i] as Item val id = subItem.identifier.toString() if (subItem.isSelected) { selections.add(id) } findSubItemSelections(subItem, selections) } } } /** * Gets all items (including sub items) from the FastAdapter * * @param fastAdapter the FastAdapter * @return a list of all items including the whole subItem hierarchy */ @JvmStatic fun <Item> getAllItems(fastAdapter: FastAdapter<Item>): List<Item> where Item : GenericItem, Item : IExpandable<*> { val size = fastAdapter.itemCount val items = ArrayList<Item>(size) for (i in 0 until size) { fastAdapter.getItem(i)?.let { items.add(it) addAllSubItems(it, items) } } return items } /** * Gets all subItems from a given parent item * * @param item the parent from which we add all items * @param items the list in which we add the subItems */ @JvmStatic fun <Item> addAllSubItems(item: Item?, items: MutableList<Item>) where Item : GenericItem, Item : IExpandable<*> { if (item is IExpandable<*> && !item.isExpanded) { val subItems = (item as IExpandable<*>).subItems var subItem: Item for (i in subItems.indices) { subItem = subItems[i] as Item items.add(subItem) addAllSubItems(subItem, items) } } } }
apache-2.0
1ea71b2ce1a8c1cb0c2fdc611e1556bb
36.908046
176
0.60188
4.691323
false
false
false
false
zeapo/Android-Password-Store
app/src/main/java/com/zeapo/pwdstore/pwgen/RandomPasswordGenerator.kt
1
3112
package com.zeapo.pwdstore.pwgen internal object RandomPasswordGenerator { /** * Generates a completely random password. * * @param size length of password to generate * @param pwFlags flag field where set bits indicate conditions the * generated password must meet * <table summary ="bits of flag field"> * <tr><td>Bit</td><td>Condition</td></tr> * <tr><td>0</td><td>include at least one number</td></tr> * <tr><td>1</td><td>include at least one uppercase letter</td></tr> * <tr><td>2</td><td>include at least one symbol</td></tr> * <tr><td>3</td><td>don't include ambiguous characters</td></tr> * <tr><td>4</td><td>don't include vowels</td></tr> * <tr><td>5</td><td>include at least one lowercase</td></tr> </table> * * @return the generated password */ fun rand(size: Int, pwFlags: Int): String { var password: String var cha: Char var i: Int var featureFlags: Int var num: Int var character: String var bank = "" if (pwFlags and PasswordGenerator.DIGITS > 0) { bank += PasswordGenerator.DIGITS_STR } if (pwFlags and PasswordGenerator.UPPERS > 0) { bank += PasswordGenerator.UPPERS_STR } if (pwFlags and PasswordGenerator.LOWERS > 0) { bank += PasswordGenerator.LOWERS_STR } if (pwFlags and PasswordGenerator.SYMBOLS > 0) { bank += PasswordGenerator.SYMBOLS_STR } do { password = "" featureFlags = pwFlags i = 0 while (i < size) { num = RandomNumberGenerator.number(bank.length) cha = bank.toCharArray()[num] character = cha.toString() if (pwFlags and PasswordGenerator.AMBIGUOUS > 0 && PasswordGenerator.AMBIGUOUS_STR.contains(character)) { continue } if (pwFlags and PasswordGenerator.NO_VOWELS > 0 && PasswordGenerator.VOWELS_STR.contains(character)) { continue } password += character i++ if (PasswordGenerator.DIGITS_STR.contains(character)) { featureFlags = featureFlags and PasswordGenerator.DIGITS.inv() } if (PasswordGenerator.UPPERS_STR.contains(character)) { featureFlags = featureFlags and PasswordGenerator.UPPERS.inv() } if (PasswordGenerator.SYMBOLS_STR.contains(character)) { featureFlags = featureFlags and PasswordGenerator.SYMBOLS.inv() } if (PasswordGenerator.LOWERS_STR.contains(character)) { featureFlags = featureFlags and PasswordGenerator.LOWERS.inv() } } } while (featureFlags and (PasswordGenerator.UPPERS or PasswordGenerator.DIGITS or PasswordGenerator.SYMBOLS or PasswordGenerator.LOWERS) > 0) return password } }
gpl-3.0
4e3d987b7c81d9cf0bf18b9e0d2d003f
39.947368
150
0.564267
4.817337
false
false
false
false
sreich/ore-infinium
core/src/com/ore/infinium/systems/server/TileLightingSystem.kt
1
14564
/** MIT License Copyright (c) 2016 Shaun Reich <[email protected]> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.ore.infinium.systems.server import com.artemis.BaseSystem import com.artemis.annotations.Wire import com.artemis.utils.IntBag import com.ore.infinium.OreBlock import com.ore.infinium.OreWorld import com.ore.infinium.components.* import com.ore.infinium.util.* import mu.KLogging @Wire class TileLightingSystem(private val oreWorld: OreWorld) : BaseSystem() { private val mPlayer by mapper<PlayerComponent>() private val mLight by mapper<LightComponent>() private val mItem by mapper<ItemComponent>() private val mSprite by mapper<SpriteComponent>() private val mDevice by mapper<PowerDeviceComponent>() private val serverNetworkSystem by system<ServerNetworkSystem>() private var initialized = false // todo find a good number, this is a complete guess. // this happens when the world is mostly air, stack overflow otherwise val MAX_LIGHTING_DEPTH = 20 companion object : KLogging() { /** * the max number of light levels we have for each tile. * we could do way more, but it'd probably cost more a lot * more calculation wise..which isn't a big deal, but * we might want to use the rest of the byte for something else. * haven't decided what for */ const val MAX_TILE_LIGHT_LEVEL: Byte = 18 } override fun initialize() { val aspectSubscriptionManager = world.aspectSubscriptionManager val subscription = aspectSubscriptionManager.get(allOf(LightComponent::class)) subscription.addSubscriptionListener(LightingEntitySubscriptionListener()) } /** * for first-run initialization, * runs through the entire world tiles and finds and sets light levels * of each tile according to access to sunlight. * * doesn't factor in actual lights, just the global light (sunlight) * * sunlight bleeds through empty walls in the background. * this will not happen underground, because walls cannot * be removed underground. they are a permanent part of the world */ private fun computeWorldTileLighting() { //TODO incorporate sunlight..this is all theoretical approaches. //check if light is greater than sunlight and if so don't touch it.. //sets the flag to indicate it is caused by sunlight //todo max y should be a reasonable base level, not far below ground, just as an optimization step for (y in 0 until 200) { for (x in 0 until oreWorld.worldSize.width) { if (!oreWorld.isBlockSolid(x, y) && oreWorld.blockWallType(x, y) == OreBlock.WallType.Air.oreValue) { oreWorld.setBlockLightLevel(x, y, MAX_TILE_LIGHT_LEVEL) } } } for (y in 0 until 200) { for (x in 0 until oreWorld.worldSize.width) { if (!oreWorld.isBlockSolid(x, y) && oreWorld.blockWallType(x, y) == OreBlock.WallType.Air.oreValue) { val lightLevel = oreWorld.blockLightLevel(x, y) //ambient/sunlight updateTileLighting(x, y, lightLevel) // diamondSunlightFloodFill(x, y, lightLevel) // diamondSunlightFloodFill(x, y, lightLevel) } } } } private fun recomputeLighting(startX: Int, endX: Int, startY: Int, endY: Int) { //todo max y should be a reasonable base level, not far below ground for (y in startY..endY) { for (x in startX..endX) { if (!oreWorld.isBlockSolid(x, y) && oreWorld.blockWallType(x, y) == OreBlock.WallType.Air.oreValue) { oreWorld.setBlockLightLevel(x, y, MAX_TILE_LIGHT_LEVEL) } } } for (y in startY..endY) { for (x in startX..endX) { if (!oreWorld.isBlockSolid(x, y) && oreWorld.blockWallType(x, y) == OreBlock.WallType.Air.oreValue) { val lightLevel = oreWorld.blockLightLevel(x, y) //ambient/sunlight updateTileLighting(x, y, lightLevel) // diamondSunlightFloodFill(x, y, lightLevel) // diamondSunlightFloodFill(x, y, lightLevel) } } } } /** * updates tile lighting for a region */ fun updateTileLighting(x: Int, y: Int, lightLevel: Byte) { diamondSunlightFloodFill(x - 1, y, lightLevel) diamondSunlightFloodFill(x + 1, y, lightLevel) diamondSunlightFloodFill(x, y + 1, lightLevel) diamondSunlightFloodFill(x, y - 1, lightLevel) } fun updateTileLightingRemove(x: Int, y: Int, lightLevel: Byte) { diamondFloodFillLightRemove(x - 1, y, lightLevel) diamondFloodFillLightRemove(x + 1, y, lightLevel) diamondFloodFillLightRemove(x, y + 1, lightLevel) diamondFloodFillLightRemove(x, y - 1, lightLevel) } /** * @param depth current depth the function is going to (so we don't blow out the stack) */ private fun diamondSunlightFloodFill(x: Int, y: Int, lastLightLevel: Byte, firstRun: Boolean = true, depth: Int = 0) { if (oreWorld.blockXSafe(x) != x || oreWorld.blockYSafe(y) != y) { //out of world bounds, abort return } val blockType = oreWorld.blockType(x, y) val wallType = oreWorld.blockWallType(x, y) var lightAttenuation = when { //fixme: this can't be right? 0? what if we change this to 1 too? how does this affect regular lights blockType == OreBlock.BlockType.Air.oreValue && wallType == OreBlock.WallType.Air.oreValue -> 0 //dug-out underground bleeds off, but not as quickly as a solid block blockType == OreBlock.BlockType.Air.oreValue && wallType != OreBlock.WallType.Air.oreValue -> 1 //solid block underground else -> 2 } if (firstRun) { lightAttenuation = 0 } //light bleed off value val newLightLevel = (lastLightLevel - lightAttenuation).toByte() val currentLightLevel = oreWorld.blockLightLevel(x, y) //don't overwrite previous light values that were greater if (newLightLevel <= currentLightLevel) { return } oreWorld.setBlockLightLevel(x, y, newLightLevel) if (depth == MAX_LIGHTING_DEPTH) { return } val newDepth = depth + 1 diamondSunlightFloodFill(x - 1, y, lastLightLevel = newLightLevel, firstRun = false, depth = newDepth) diamondSunlightFloodFill(x + 1, y, lastLightLevel = newLightLevel, firstRun = false, depth = newDepth) diamondSunlightFloodFill(x, y - 1, lastLightLevel = newLightLevel, firstRun = false, depth = newDepth) diamondSunlightFloodFill(x, y + 1, lastLightLevel = newLightLevel, firstRun = false, depth = newDepth) } private fun diamondFloodFillLightRemove(x: Int, y: Int, lastLightLevel: Byte, firstRun: Boolean = true, depth: Int = 0) { if (oreWorld.blockXSafe(x) != x || oreWorld.blockYSafe(y) != y) { //out of world bounds, abort return } //logger.debug {"tiles lighting system - diamondFloodFillLightRemove", "begin, depth: $depth") val blockType = oreWorld.blockType(x, y) val wallType = oreWorld.blockWallType(x, y) //light bleed off value val newLightLevel = 0.toByte() oreWorld.setBlockLightLevel(x, y, newLightLevel) if (depth == 5 + 3 /*MAX_LIGHTING_DEPTH*/) { return } //logger.debug {"tiles lighting system - diamondFloodFillLightRemove", "recursive calls being made, depth: $depth") val newDepth = depth + 1 diamondFloodFillLightRemove(x - 1, y, lastLightLevel = newLightLevel, firstRun = false, depth = newDepth) diamondFloodFillLightRemove(x + 1, y, lastLightLevel = newLightLevel, firstRun = false, depth = newDepth) diamondFloodFillLightRemove(x, y - 1, lastLightLevel = newLightLevel, firstRun = false, depth = newDepth) diamondFloodFillLightRemove(x, y + 1, lastLightLevel = newLightLevel, firstRun = false, depth = newDepth) } override fun processSystem() { if (!initialized) { computeWorldTileLighting() initialized = true } //oreWorld.players().forEach { // val cPlayer = mPlayer.get(it) // val rect = cPlayer.loadedViewport.rect // recomputeLighting(oreWorld.blockXSafe(rect.left.toInt()), oreWorld.blockXSafe(rect.right.toInt()), // oreWorld.blockYSafe(rect.top.toInt()), oreWorld.blockYSafe(rect.bottom.toInt())) //} } /** * occurs when the lighting for this light must be reprocessed. * updates all lighting in the area. * * this must be called for if a light turns on/off, * if a light is placed or created. * * the exception being if a light is removed (deleted from the world) * that is the case that will automatically be handled properly. */ fun updateLightingForLight(entityId: Int, sendUpdate: Boolean = true) { val cItem = mItem.get(entityId) if (cItem.state != ItemComponent.State.InWorldState) { return } //todo this should get the radius of the light i think val cDevice = mDevice.get(entityId) val cLight = mLight.get(entityId) val cSprite = mSprite.get(entityId) val x = cSprite.sprite.x.toInt() val y = cSprite.sprite.y.toInt() val currentLightLevel = oreWorld.blockLightLevel(x, y) //hack: radius actually should be intensity...or something. we could have both? //hack or is what we want to affect, actually attenuation? that would affect the radius.. //hack we need to be sure the lighting calculation functions (updateTileLighting) do not override //hack light of a lower value! //ensure tile where the light is, is at least this well lit up val lightLevel = lightLevelForLight(deviceRunning = cDevice.running, lightRadius = cLight.radius) .coerceAtLeast(currentLightLevel) oreWorld.setBlockLightLevel(x, y, lightLevel) if (lightLevel == 0.toByte()) { // updateTileLightingRemove(x, y, lightLevel) } else { updateTileLighting(x, y, lightLevel) } if (sendUpdate) { serverNetworkSystem.sendBlockRegionInterestedPlayers(left = x - 20, right = x + 20, top = y - 20, bottom = y + 20) } } /** * returns the proper light level for a light, depending on whether it is running or not */ private fun lightLevelForLight(deviceRunning: Boolean, lightRadius: Int): Byte = if (deviceRunning) { lightRadius.toByte() } else { 0.toByte() } inner class LightingEntitySubscriptionListener : OreEntitySubscriptionListener { override fun removed(entities: IntBag) { entities.forEach { entity -> mItem.ifPresent(entity) { if (!oreWorld.isItemPlacedInWorldOpt(entity)) { //ignore ones dropped in the world, or in inventory return } } //turn it off before we update the lighting mDevice.get(entity).running = false val cSprite = mSprite.get(entity) logger.debug { "calculating light removal" } val x = cSprite.sprite.x.toInt() val y = cSprite.sprite.y.toInt() //updateTileLightingRemove(x, y, 0) //wipe the lighting //todo, only do it in sane region for (x2 in 0 until oreWorld.worldSize.width) { for (y2 in 0 until oreWorld.worldSize.height) { oreWorld.setBlockLightLevel(x2, y2, 0) } } // recomputeLighting(startX = x - 100, endX = x + 100, startY = y - 100, endY = y + 100) computeWorldTileLighting() updateAllLightsWithoutSending() // computeWorldTileLighting() // updateLightingForLight(entity) serverNetworkSystem.sendBlockRegionInterestedPlayers(left = x - 100, right = x + 100, top = y - 100, bottom = y + 100) } //fixme //TODO("remove lighting in the area of this light/update that area") } } private fun updateAllLightsWithoutSending() { val lights = oreWorld.getEntitiesWithComponent<LightComponent>().forEach { light -> updateLightingForLight(entityId = light, sendUpdate = false) } } }
mit
f74e51a6fc255a762aede266c947a235
39.681564
123
0.603818
4.381468
false
false
false
false
ThePreviousOne/tachiyomi
app/src/main/java/eu/kanade/tachiyomi/widget/preference/SourceLoginDialog.kt
1
2622
package eu.kanade.tachiyomi.widget.preference import android.os.Bundle import android.view.View import eu.kanade.tachiyomi.R import eu.kanade.tachiyomi.data.source.Source import eu.kanade.tachiyomi.data.source.SourceManager import eu.kanade.tachiyomi.data.source.online.LoginSource import eu.kanade.tachiyomi.util.toast import kotlinx.android.synthetic.main.pref_account_login.view.* import rx.android.schedulers.AndroidSchedulers import rx.schedulers.Schedulers import uy.kohesive.injekt.injectLazy class SourceLoginDialog : LoginDialogPreference() { companion object { fun newInstance(source: Source): LoginDialogPreference { val fragment = SourceLoginDialog() val bundle = Bundle(1) bundle.putInt("key", source.id) fragment.arguments = bundle return fragment } } val sourceManager: SourceManager by injectLazy() lateinit var source: LoginSource override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val sourceId = arguments.getInt("key") source = sourceManager.get(sourceId) as LoginSource } override fun setCredentialsOnView(view: View) = with(view) { dialog_title.text = getString(R.string.login_title, source.toString()) username.setText(preferences.sourceUsername(source)) password.setText(preferences.sourcePassword(source)) } override fun checkLogin() { requestSubscription?.unsubscribe() v?.apply { if (username.text.length == 0 || password.text.length == 0) return login.progress = 1 requestSubscription = source.login(username.text.toString(), password.text.toString()) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe({ logged -> if (logged) { preferences.setSourceCredentials(source, username.text.toString(), password.text.toString()) dialog.dismiss() context.toast(R.string.login_success) } else { preferences.setSourceCredentials(source, "", "") login.progress = -1 } }, { error -> login.progress = -1 login.setText(R.string.unknown_error) }) } } }
apache-2.0
3aa5856334f2aaf253a8e6dfded2b564
33.5
98
0.587719
5.223108
false
false
false
false
DreierF/MyTargets
wearable/src/main/java/de/dreier/mytargets/TargetSelectView.kt
1
6148
/* * Copyright (C) 2018 Florian Dreier * * This file is part of MyTargets. * * MyTargets is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 * as published by the Free Software Foundation. * * MyTargets is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. */ package de.dreier.mytargets import android.content.Context import android.graphics.* import androidx.core.content.ContextCompat import android.util.AttributeSet import android.view.MotionEvent import de.dreier.mytargets.shared.models.Target import de.dreier.mytargets.shared.models.db.Shot import de.dreier.mytargets.shared.utils.Circle import de.dreier.mytargets.shared.utils.EndRenderer import de.dreier.mytargets.shared.views.TargetViewBase class TargetSelectView : TargetViewBase { private var radius: Int = 0 private var chinHeight: Int = 0 private var circleRadius: Double = 0.toDouble() private var circle: Circle? = null private var chinBound: Float = 0.toFloat() private var ambientMode = false private val backspaceBackground = Paint() private val currentlySelectedZone: Int get() = if (currentShotIndex != EndRenderer.NO_SELECTION) { shots[currentShotIndex].scoringRing } else { Shot.NOTHING_SELECTED } override val selectedShotCircleRadius: Int get() = RADIUS_SELECTED constructor(context: Context) : super(context) { init() } constructor(context: Context, attrs: AttributeSet) : super(context, attrs) { init() } constructor(context: Context, attrs: AttributeSet, defStyle: Int) : super(context, attrs, defStyle) { init() } private fun init() { backspaceSymbol.setTint(-0x1) backspaceBackground.color = ContextCompat.getColor(context, R.color.md_wear_green_active_ui_element) backspaceBackground.isAntiAlias = true } internal fun setChinHeight(chinHeight: Int) { this.chinHeight = chinHeight } override fun initWithTarget(target: Target) { super.initWithTarget(target) circle = Circle(density) } override fun onDraw(canvas: Canvas) { // Draw all possible points in a circular val curZone = currentlySelectedZone for (i in 0 until selectableZones.size) { val coordinate = getCircularCoordinates(i) if (i != curZone) { circle!!.draw(canvas, coordinate.x, coordinate.y, selectableZones[i].index, 17, currentShotIndex, null, ambientMode, target) } } if (!ambientMode) { canvas.drawCircle(radius.toFloat(), radius + 30 * density, 20 * density, backspaceBackground) drawBackspaceButton(canvas) } // Draw all points of this end in the center endRenderer.draw(canvas) } private fun getCircularCoordinates(zone: Int): PointF { val degree = Math.toRadians(zone * 360.0 / selectableZones.size.toDouble()) val coordinate = PointF() coordinate.x = (radius + Math.cos(degree) * circleRadius).toFloat() coordinate.y = (radius + Math.sin(degree) * circleRadius).toFloat() if (coordinate.y > chinBound) { coordinate.y = chinBound } return coordinate } override fun getShotCoordinates(shot: Shot): PointF { return getCircularCoordinates(getSelectableZoneIndexFromShot(shot)) } override fun updateLayoutBounds(width: Int, height: Int) { radius = (width / 2.0).toInt() chinBound = height - (chinHeight + 15) * density circleRadius = (radius - 25 * density).toDouble() } override fun getEndRect(): RectF { val endRect = RectF() endRect.left = radius - 45 * density endRect.right = radius + 45 * density endRect.top = (radius / 2).toFloat() endRect.bottom = radius.toFloat() return endRect } override fun getBackspaceButtonBounds(): Rect { val backspaceBounds = Rect() backspaceBounds.left = (radius - 20 * density).toInt() backspaceBounds.right = (radius + 20 * density).toInt() backspaceBounds.top = (radius + 10 * density).toInt() backspaceBounds.bottom = (radius + 50 * density).toInt() return backspaceBounds } override fun getSelectableZonePosition(i: Int): Rect { val coordinate = getCircularCoordinates(i) val rad = if (i == currentlySelectedZone) RADIUS_SELECTED else RADIUS_UNSELECTED val rect = Rect() rect.left = (coordinate.x - rad).toInt() rect.top = (coordinate.y - rad).toInt() rect.right = (coordinate.x + rad).toInt() rect.bottom = (coordinate.y + rad).toInt() return rect } override fun updateShotToPosition(shot: Shot, x: Float, y: Float): Boolean { val zones = selectableZones.size val xDiff = (x - radius).toDouble() val yDiff = (y - radius).toDouble() val perceptionRadius = radius - 50 * density // Select current arrow if (xDiff * xDiff + yDiff * yDiff > perceptionRadius * perceptionRadius) { var degree = Math.toDegrees(Math.atan2(-yDiff, xDiff)) - 180.0 / zones.toDouble() if (degree < 0) { degree += 360.0 } val index = (zones * ((360.0 - degree) / 360.0)).toInt() shot.scoringRing = selectableZones[index].index return true } return false } override fun selectPreviousShots(motionEvent: MotionEvent, x: Float, y: Float): Boolean { return false } fun setAmbientMode(ambientMode: Boolean) { this.ambientMode = ambientMode endRenderer.setAmbientMode(ambientMode) invalidate() } companion object { const val RADIUS_SELECTED = 23 const val RADIUS_UNSELECTED = 17 } }
gpl-2.0
2771ad2fed4e10c44e59fadec25b0766
33.155556
108
0.642648
4.308339
false
false
false
false
bingju328/SelfViewDemo
selfview/src/main/kotlin/selfview/com/selfview/KTWatchView.kt
1
8822
package selfview.com.selfview import android.content.Context import android.graphics.* import android.util.AttributeSet import android.util.TypedValue import android.view.View import java.util.* /** * Created by bingj on 2017/5/30. */ class KTWatchView: View { /** * 默认宽高 * */ private val DEFAUTSIZE: Float = 200f /** * 最终的大小 * */ private var mSize: Int = 200 /** * Paint * */ private lateinit var backCirclePaint: Paint // 整个背景圆 private lateinit var textPaint: Paint // 文字 private lateinit var scaleArcPaint: Paint // 刻度弧 private lateinit var pointPaint: Paint // 中心圆 private lateinit var timePaint: Paint // 时针 private lateinit var minutePaint: Paint // 分针 private lateinit var secondPaint: Paint // 秒针 private var scaleArcRadius: Int = 0 //刻度弧的半径 constructor(context: Context): this(context,null) constructor(context: Context, attrs: AttributeSet?): this(context,attrs,0) constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int): super(context, attrs, defStyleAttr){ initPaint() } fun initPaint(): Unit{ backCirclePaint = Paint() backCirclePaint.isAntiAlias = true backCirclePaint.strokeWidth = 5f backCirclePaint.style = Paint.Style.FILL_AND_STROKE backCirclePaint.color = resources.getColor(R.color.watchBackground) textPaint = Paint() textPaint.isAntiAlias = true textPaint.color = resources.getColor(R.color.whiteback) textPaint.typeface = Typeface.DEFAULT_BOLD scaleArcPaint = Paint() scaleArcPaint.isAntiAlias = true scaleArcPaint.strokeWidth = dp2px(2f) scaleArcPaint.style = Paint.Style.STROKE timePaint = Paint() timePaint.isAntiAlias = true timePaint.style = Paint.Style.STROKE minutePaint = Paint() minutePaint.isAntiAlias = true minutePaint.style = Paint.Style.STROKE secondPaint = Paint() secondPaint.isAntiAlias = true secondPaint.style = Paint.Style.STROKE pointPaint = Paint() pointPaint.isAntiAlias = true pointPaint.style = Paint.Style.FILL_AND_STROKE } override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) { super.onMeasure(widthMeasureSpec, heightMeasureSpec) mSize = Math.max(startMeasure(widthMeasureSpec),startMeasure(heightMeasureSpec)) setMeasuredDimension(mSize,mSize) } private fun startMeasure(mode: Int): Int{ var size: Int = MeasureSpec.getSize(mode) var modeNew: Int = MeasureSpec.getMode(mode) //AT_MOST 表示wrap_content return if (modeNew==MeasureSpec.AT_MOST) dp2px(DEFAUTSIZE).toInt() else size } override fun onDraw(canvas: Canvas?) { //移动画布到中央 canvas!!.translate(mSize/2f,mSize/2f) //画背景圆 drawCircle(canvas) //画背景上的文字 drawText(canvas) // 画表盘 drawPanel(canvas) } private fun drawPanel(canvas: Canvas) { // 画刻度弧 drawScaleArc(canvas) //画时针 drawTime(canvas) //画分针 drawMinute(canvas) // 画秒指针 drawPointer(canvas) drawInPoint(canvas) } private var pointRadius = dp2px(3f) // 中心圆半径 private fun drawInPoint(canvas: Canvas) { canvas.save() pointPaint.color = resources.getColor(R.color.whiteback) canvas.drawCircle(0f, 0f, pointRadius, pointPaint) canvas.restore() } private fun drawPointer(canvas: Canvas) { //先将指针与刻度0位置对齐 canvas.save() canvas.rotate(180f,0f,0f) var angleMille = milleSecond % 360 var angleSecond = currentSecond * 6 % 360 canvas.rotate(angleSecond +angleMille ,0f,0f) secondPaint.style = Paint.Style.FILL_AND_STROKE secondPaint.color = resources.getColor(R.color.secondPointer) secondPaint.strokeWidth = dp2px(0.8f) val timePath: Path = Path() timePath.moveTo(0f,0f) timePath.lineTo(0f,scaleArcRadius - mTikeHeight - dp2px(10f)) timePath.close(); canvas.drawPath(timePath,secondPaint) canvas.restore() } private fun drawMinute(canvas: Canvas) { //先将指针与刻度0位置对齐 canvas.save() canvas.rotate(180f,0f,0f) var angleMinute: Float = currentMinute * 6f % 360 var angleSecond: Float = currentSecond*(6f/60) // Log.i("watchview--","drawMinute-angleMinute--"+angleMinute); // Log.i("watchview--","drawMinute-angleSecond--"+angleSecond); canvas.rotate(angleMinute+angleSecond,0f,0f) minutePaint.style = Paint.Style.FILL_AND_STROKE minutePaint.color = resources.getColor(R.color.minutePointer) minutePaint.strokeWidth = (dp2px(2f)) val timePath: Path = Path() timePath.moveTo(0f,0f) timePath.lineTo(0f,scaleArcRadius - mTikeHeight - dp2px(10f)) timePath.close() canvas.drawPath(timePath,minutePaint) canvas.restore() } private var currentTime: Int = 0 private var currentMinute: Int = 0 private var currentSecond: Float = 0f private var milleSecond: Float = 0f //1/6秒 private fun drawTime(canvas: Canvas) { //先将指针与刻度0位置对齐 canvas.save() canvas.rotate(180f,0f,0f) var angleTime: Int = currentTime * 30 % 360 var angleMinute: Float = (((currentMinute % 60)/60f) * 30f) % 30 canvas.rotate(angleTime+angleMinute,0f,0f) timePaint.style = Paint.Style.FILL_AND_STROKE timePaint.color = resources.getColor(R.color.timePointer) timePaint.strokeWidth = dp2px(3f) val timePath: Path = Path() timePath.moveTo(0f,0f) timePath.lineTo(0f,scaleArcRadius - mTikeHeight - dp2px(30f)) timePath.close() canvas.drawPath(timePath,timePaint) canvas.restore() } private var mTikeCount: Int = 12 //12条该度 private var mTikeHeight: Int = dp2px(15f).toInt()// 长度 private fun drawScaleArc(canvas: Canvas) { scaleArcRadius = mSize/2 canvas.save() scaleArcPaint.color = Color.parseColor("#aaaaaa")//#FFFAFA // 旋转的角度 var mAngle: Float = 360f / mTikeCount for (item: Int in 0..mTikeCount) { //3的倍数画上宽刻度 if (item % 3 == 0) { scaleArcPaint.strokeWidth = dp2px(2f) } else { scaleArcPaint.strokeWidth = dp2px(1f) } canvas.drawLine(0f,-scaleArcRadius+5f, 0f, -scaleArcRadius+mTikeHeight+5f, scaleArcPaint) //旋转画布 canvas.rotate(mAngle, 0f, 0f) } canvas.restore() } private fun drawText(canvas: Canvas) { textPaint.color = Color.WHITE val textUp = "LOBING"; val textDown = "AUTOMATIC"; //表盘上方logo textPaint.textSize = sp2px(12f) textPaint.typeface = Typeface.SERIF //测量字体的宽度 val textWidthUp = textPaint.measureText(textUp) canvas.drawText(textUp, -textWidthUp/2, -mSize/4f, textPaint) //表盘下方字体 textPaint.typeface = Typeface.SANS_SERIF textPaint.textSize = sp2px(8f) var textWidthDown = textPaint.measureText(textDown) canvas.drawText(textDown,-textWidthDown/2,mSize/4f,textPaint) } private fun drawCircle(canvas: Canvas) { // 已将画布移到中心,所以圆心为(0,0) backCirclePaint.color = Color.parseColor("#3A3A3A") //如果不关闭硬件加速,setShadowLayer无效 // backCirclePaint.setShadowLayer(dp2px(5),dp2px(100),dp2px(100),Color.RED) canvas.drawCircle(0f, 0f, mSize /2-dp2px(1f), backCirclePaint) canvas.save() } fun setCurrentTime(currentTime1: Long) { val date: Date = Date(currentTime1) var milliSecond: Float = (currentTime1 % 1000).toFloat() //当前毫秒 currentTime = date.getHours() currentMinute = date.getMinutes() currentSecond = date.getSeconds().toFloat() milleSecond = milliSecond/1000 * 6; //以 1/6秒为单位 postInvalidate() } /** * 将 dp 转换为 px * @param dp * @return */ private fun dp2px(dp: Float): Float{ return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,dp,resources.displayMetrics) } private fun sp2px(dp: Float): Float{ return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP,dp,resources.displayMetrics) } }
apache-2.0
8783c496b7c15fd07ce6793ac5b71405
32.109804
112
0.633855
3.696147
false
false
false
false
gorrotowi/Nothing
Android/Nothing/app/src/main/java/com/gorro/nothing/eggs/GlitchEffect.kt
1
4259
@file:Suppress("MagicNumber") package com.gorro.nothing.eggs import android.app.Activity import android.content.Context import android.graphics.Bitmap import android.graphics.BitmapFactory import android.graphics.Canvas import android.graphics.PixelFormat import android.graphics.drawable.AnimationDrawable import android.graphics.drawable.BitmapDrawable import android.os.Handler import android.os.Looper import android.view.WindowManager import android.view.WindowManager.LayoutParams import android.widget.ImageView import androidx.annotation.Nullable import java.io.ByteArrayOutputStream import java.util.* object GlitchEffect { private val RANDOM = Random() private const val BITMAP_COUNT = 4 private const val JPEG_QUALITY = 33 private const val JPEG_CORRUPTION_COUNT = 5 private const val JPEG_HEADER_SIZE = 100 private const val ANIM_FRAME_DURATION_MAX = 150 private const val ANIM_FRAME_DURATION_MIN = 50 private var sMainHandler: Handler? = null private val mainHandler: Handler get() { if (sMainHandler == null) sMainHandler = Handler(Looper.getMainLooper()) return sMainHandler as Handler } fun showGlitch(activity: Activity) { val bitmap = captureWindow(activity) val corruptedBitmaps = makeCorruptedBitmaps(bitmap, BITMAP_COUNT) showAnimation(activity, corruptedBitmaps) } private fun captureWindow(activity: Activity): Bitmap { val root = activity.window.decorView.rootView val screenshot = Bitmap.createBitmap(root.width, root.height, Bitmap.Config.RGB_565) val canvas = Canvas(screenshot) root.draw(canvas) return screenshot } private fun makeCorruptedBitmaps(bitmap: Bitmap, count: Int): Array<Bitmap?> { val bos = ByteArrayOutputStream(1024) val res = arrayOfNulls<Bitmap>(count) bitmap.compress(Bitmap.CompressFormat.JPEG, JPEG_QUALITY, bos) val data = bos.toByteArray() var i = 0 while (i < count) { val corrupted = getCorruptedArray(data) val decoded = decodeJpg(corrupted) if (decoded != null) { res[i] = decoded i++ } } return res } private fun getCorruptedArray(source: ByteArray): ByteArray { val res = source.clone() for (i in 0 until JPEG_CORRUPTION_COUNT) { val idx = RANDOM.nextInt(res.size - JPEG_HEADER_SIZE) + JPEG_HEADER_SIZE res[idx] = (res[idx] + RANDOM.nextInt(3).toByte()).toByte() } return res } @Nullable private fun decodeJpg(data: ByteArray): Bitmap? { val options = BitmapFactory.Options().also { it.inPreferredConfig = Bitmap.Config.RGB_565 it.inSampleSize = 2 } return BitmapFactory.decodeByteArray(data, 0, data.size, options) } private fun showAnimation(activity: Activity, bitmaps: Array<Bitmap?>) { val windowManager = activity.getSystemService(Context.WINDOW_SERVICE) as WindowManager val layoutParams = LayoutParams(LayoutParams.FIRST_SUB_WINDOW) val decorView = activity.window.decorView layoutParams.width = decorView.width layoutParams.height = decorView.height layoutParams.format = PixelFormat.RGBA_8888 layoutParams.flags = LayoutParams.FLAG_LAYOUT_IN_SCREEN or LayoutParams.FLAG_HARDWARE_ACCELERATED layoutParams.token = decorView.rootView.windowToken val imageView = ImageView(activity) val animationDrawable = AnimationDrawable() animationDrawable.isOneShot = true var totalDuration = 0L val resources = activity.resources for (bitmap in bitmaps) { val duration = RANDOM.nextInt(ANIM_FRAME_DURATION_MAX - ANIM_FRAME_DURATION_MIN) + ANIM_FRAME_DURATION_MIN totalDuration += duration animationDrawable.addFrame(BitmapDrawable(resources, bitmap), duration) } imageView.setImageDrawable(animationDrawable) windowManager.addView(imageView, layoutParams) animationDrawable.start() mainHandler.postDelayed({ windowManager.removeView(imageView) }, totalDuration) } }
apache-2.0
482e8891dcc4f175465d903dafeaec0d
36.690265
118
0.684198
4.6957
false
false
false
false
zanata/zanata-platform
server/services/src/main/java/org/zanata/service/impl/AttributionService.kt
1
4643
package org.zanata.service.impl import org.fedorahosted.openprops.Properties import org.slf4j.Logger import org.slf4j.LoggerFactory import org.zanata.common.DocumentType import org.zanata.common.DocumentType.GETTEXT import org.zanata.common.DocumentType.PROPERTIES import org.zanata.common.DocumentType.PROPERTIES_UTF8 import org.zanata.common.ProjectType import org.zanata.model.HDocument import org.zanata.model.HLocale import org.zanata.model.HSimpleComment import org.zanata.model.HTextFlow import org.zanata.model.po.HPoHeader import org.zanata.model.po.HPoTargetHeader import org.zanata.rest.service.PoUtility.headerToProperties import org.zanata.rest.service.PoUtility.propertiesToHeader import javax.enterprise.context.ApplicationScoped internal const val ATTRIBUTION_KEY = "X-Zanata-MT-Attribution" /** * @author Sean Flanigan <a href="mailto:[email protected]">[email protected]</a> */ @ApplicationScoped class AttributionService { companion object { val log: Logger = LoggerFactory.getLogger(AttributionService::class.java) } fun inferDocumentType(doc: HDocument): DocumentType? { return when (doc.projectIteration.effectiveProjectType) { ProjectType.Gettext, ProjectType.Podir -> GETTEXT ProjectType.Properties -> PROPERTIES ProjectType.Utf8Properties -> PROPERTIES_UTF8 ProjectType.Xml -> DocumentType.XML ProjectType.Xliff -> DocumentType.XLIFF ProjectType.File -> { // null rawDoc is assumed to be gettext val rawDocument = doc.rawDocument ?: return GETTEXT rawDocument.type } // A very old project with no effective project type null -> null } } fun supportsAttribution(doc: HDocument): Boolean = when (inferDocumentType(doc)) { GETTEXT, PROPERTIES, PROPERTIES_UTF8 -> true else -> false } fun addAttribution(doc: HDocument, locale: HLocale, backendId: String) { if (doc.textFlows.isEmpty()) return val attributionMessage = getAttributionMessage(backendId) val docType = inferDocumentType(doc) when (docType) { GETTEXT -> { val poTargetHeader = doc.poTargetHeaders.getOrPut(locale) { HPoTargetHeader().apply { targetLanguage = locale document = doc } } ensureAttributionForGettext(poTargetHeader, attributionMessage) } PROPERTIES, PROPERTIES_UTF8 -> ensureAttributionForProperties(doc.textFlows[0], attributionMessage) null -> throw RuntimeException("null DocumentType for $doc") else -> throw RuntimeException("unexpected DocumentType for $doc") } } internal fun ensureAttributionForGettext(header: HPoTargetHeader, attributionMessage: String) { val props = if (header.entries == null) { Properties() } else { headerToProperties(header.entries) } props.setProperty(ATTRIBUTION_KEY, attributionMessage) header.entries = propertiesToHeader(props) } internal fun ensureAttributionForProperties(textFlow: HTextFlow, attributionMessage: String) { val prefix = "$ATTRIBUTION_KEY:" val attributionLine = "$prefix $attributionMessage" if (textFlow.comment != null) { val oldLines = textFlow.comment.comment.lines() textFlow.comment.comment = ensureLine(oldLines, prefix, attributionLine) } else { textFlow.comment = HSimpleComment(attributionLine) } } private fun ensureLine(lines: List<String>, prefix: String, attributionLine: String): String { val newLines: List<String> = if (lines.find { it.startsWith(prefix) } != null) { lines.map { line -> if (line.startsWith(prefix)) attributionLine else line } } else lines + attributionLine return newLines.joinToString("\n") } fun getAttributionMessage(backendId: String): String { return when (backendId) { "GOOGLE" -> "Translated by Google" "DEV" -> "Pseudo-translated by MT (DEV)" else -> { log.warn("Unexpected MT backendId: {}", backendId) "Translated by MT backendId: $backendId" } } } }
lgpl-2.1
009718068b7b7996ded247d68ec97bd5
36.747967
99
0.625888
4.592483
false
false
false
false
georocket/georocket
src/test/kotlin/io/georocket/output/geojson/GeoJsonMergerTest.kt
1
10641
package io.georocket.output.geojson import io.georocket.coVerify import io.georocket.storage.GeoJsonChunkMeta import io.georocket.util.io.BufferWriteStream import io.vertx.core.Vertx import io.vertx.core.buffer.Buffer import io.vertx.junit5.VertxExtension import io.vertx.junit5.VertxTestContext import io.vertx.kotlin.coroutines.dispatcher import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.launch import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test import org.junit.jupiter.api.extension.ExtendWith /** * Test [GeoJsonMerger] * @author Michel Kraemer */ @ExtendWith(VertxExtension::class) class GeoJsonMergerTest { private fun doMerge( vertx: Vertx, ctx: VertxTestContext, chunks: List<Buffer>, metas: List<GeoJsonChunkMeta>, jsonContents: String, optimistic: Boolean = false ) { val m = GeoJsonMerger(optimistic) val bws = BufferWriteStream() if (!optimistic) { for (meta in metas) { m.init(meta) } } CoroutineScope(vertx.dispatcher()).launch { ctx.coVerify { for ((meta, chunk) in metas.zip(chunks)) { m.merge(chunk, meta, bws) } m.finish(bws) assertThat(bws.buffer.toString("utf-8")).isEqualTo(jsonContents) } ctx.completeNow() } } /** * Test if one geometry is rendered directly */ @Test fun oneGeometry(vertx: Vertx, ctx: VertxTestContext) { val strChunk1 = """{"type":"Polygon"}""" val expected = "{\"type\":\"GeometryCollection\",\"geometries\":[$strChunk1]}" val chunk1 = Buffer.buffer(strChunk1) val cm1 = GeoJsonChunkMeta("Polygon", "geometries") doMerge(vertx, ctx, listOf(chunk1), listOf(cm1), expected) } /** * Test if one geometry can be merged in optimistic mode */ @Test fun oneGeometryOptimistic(vertx: Vertx, ctx: VertxTestContext) { val strChunk1 = """{"type":"Polygon"}""" val expected = """{"type":"FeatureCollection","features":[""" + """{"type":"Feature","geometry":$strChunk1}]}""" val chunk1 = Buffer.buffer(strChunk1) val cm1 = GeoJsonChunkMeta("Polygon", "geometries") doMerge(vertx, ctx, listOf(chunk1), listOf(cm1), expected, true) } /** * Test if one feature is rendered directly */ @Test fun oneFeature(vertx: Vertx, ctx: VertxTestContext) { val strChunk1 = """{"type":"Feature"}""" val expected = """{"type":"FeatureCollection","features":[$strChunk1]}""" val chunk1 = Buffer.buffer(strChunk1) val cm1 = GeoJsonChunkMeta("Feature", "features") doMerge(vertx, ctx, listOf(chunk1), listOf(cm1), expected) doMerge(vertx, ctx, listOf(chunk1), listOf(cm1), expected, true) } /** * Test if two geometries can be merged to a geometry collection */ @Test fun twoGeometries(vertx: Vertx, ctx: VertxTestContext) { val strChunk1 = """{"type":"Polygon"}""" val strChunk2 = """{"type":"Point"}""" val chunk1 = Buffer.buffer(strChunk1) val chunk2 = Buffer.buffer(strChunk2) val cm1 = GeoJsonChunkMeta("Polygon", "geometries") val cm2 = GeoJsonChunkMeta("Point", "geometries") doMerge( vertx, ctx, listOf(chunk1, chunk2), listOf(cm1, cm2), "{\"type\":\"GeometryCollection\",\"geometries\":[$strChunk1,$strChunk2]}" ) } /** * Test if two geometries can be merged in optimistic mode */ @Test fun twoGeometriesOptimistic(vertx: Vertx, ctx: VertxTestContext) { val strChunk1 = """{"type":"Polygon"}""" val strChunk2 = """{"type":"Point"}""" val expected = """{"type":"FeatureCollection","features":[""" + """{"type":"Feature","geometry":$strChunk1},""" + """{"type":"Feature","geometry":$strChunk2}]}""" val chunk1 = Buffer.buffer(strChunk1) val chunk2 = Buffer.buffer(strChunk2) val cm1 = GeoJsonChunkMeta("Polygon", "geometries") val cm2 = GeoJsonChunkMeta("Point", "geometries") doMerge(vertx, ctx, listOf(chunk1, chunk2), listOf(cm1, cm2), expected, true) } /** * Test if three geometries can be merged to a geometry collection */ @Test fun threeGeometries(vertx: Vertx, ctx: VertxTestContext) { val strChunk1 = """{"type":"Polygon"}""" val strChunk2 = """{"type":"Point"}""" val strChunk3 = """{"type":"MultiPoint"}""" val chunk1 = Buffer.buffer(strChunk1) val chunk2 = Buffer.buffer(strChunk2) val chunk3 = Buffer.buffer(strChunk3) val cm1 = GeoJsonChunkMeta("Polygon", "geometries") val cm2 = GeoJsonChunkMeta("Point", "geometries") val cm3 = GeoJsonChunkMeta("MultiPoint", "geometries") doMerge( vertx, ctx, listOf(chunk1, chunk2, chunk3), listOf(cm1, cm2, cm3), """{"type":"GeometryCollection","geometries":[$strChunk1,$strChunk2,$strChunk3]}""" ) } /** * Test if two features can be merged to a feature collection */ @Test fun twoFeatures(vertx: Vertx, ctx: VertxTestContext) { val strChunk1 = """{"type":"Feature"}""" val strChunk2 = """{"type":"Feature","properties":{}}""" val chunk1 = Buffer.buffer(strChunk1) val chunk2 = Buffer.buffer(strChunk2) val cm1 = GeoJsonChunkMeta("Feature", "features") doMerge( vertx, ctx, listOf(chunk1, chunk2), listOf(cm1, cm1), """{"type":"FeatureCollection","features":[$strChunk1,$strChunk2]}""" ) } /** * Test if two features can be merged in optimistic mode */ @Test fun twoFeaturesOptimistic(vertx: Vertx, ctx: VertxTestContext) { val strChunk1 = """{"type":"Feature"}""" val strChunk2 = """{"type":"Feature","properties":{}}""" val chunk1 = Buffer.buffer(strChunk1) val chunk2 = Buffer.buffer(strChunk2) val cm1 = GeoJsonChunkMeta("Feature", "features") doMerge( vertx, ctx, listOf(chunk1, chunk2), listOf(cm1, cm1), """{"type":"FeatureCollection","features":[$strChunk1,$strChunk2]}""", true ) } /** * Test if three features can be merged to a feature collection */ @Test fun threeFeatures(vertx: Vertx, ctx: VertxTestContext) { val strChunk1 = """{"type":"Feature"}""" val strChunk2 = """{"type":"Feature","properties":{}}""" val strChunk3 = """{"type":"Feature","geometry":[]}""" val chunk1 = Buffer.buffer(strChunk1) val chunk2 = Buffer.buffer(strChunk2) val chunk3 = Buffer.buffer(strChunk3) val cm1 = GeoJsonChunkMeta("Feature", "features") doMerge( vertx, ctx, listOf(chunk1, chunk2, chunk3), listOf(cm1, cm1, cm1), """{"type":"FeatureCollection","features":[$strChunk1,$strChunk2,$strChunk3]}""" ) } /** * Test if two geometries and a feature can be merged to a feature collection */ @Test fun geometryAndFeature(vertx: Vertx, ctx: VertxTestContext) { val strChunk1 = """{"type":"Polygon"}""" val strChunk2 = """{"type":"Feature"}""" val chunk1 = Buffer.buffer(strChunk1) val chunk2 = Buffer.buffer(strChunk2) val cm1 = GeoJsonChunkMeta("Polygon", "geometries") val cm2 = GeoJsonChunkMeta("Feature", "features") doMerge( vertx, ctx, listOf(chunk1, chunk2), listOf(cm1, cm2), """{"type":"FeatureCollection","features":[""" + """{"type":"Feature","geometry":$strChunk1},$strChunk2]}""" ) } /** * Test if two geometries and a feature can be merged to a feature collection */ @Test fun featureAndGeometry(vertx: Vertx, ctx: VertxTestContext) { val strChunk1 = """{"type":"Feature"}""" val strChunk2 = """{"type":"Polygon"}""" val chunk1 = Buffer.buffer(strChunk1) val chunk2 = Buffer.buffer(strChunk2) val cm1 = GeoJsonChunkMeta("Feature", "features") val cm2 = GeoJsonChunkMeta("Polygon", "geometries") doMerge( vertx, ctx, listOf(chunk1, chunk2), listOf(cm1, cm2), """{"type":"FeatureCollection","features":[$strChunk1,""" + """{"type":"Feature","geometry":$strChunk2}]}""" ) } /** * Test if two geometries and a feature can be merged to a feature collection */ @Test fun twoGeometriesAndAFeature(vertx: Vertx, ctx: VertxTestContext) { val strChunk1 = """{"type":"Polygon"}""" val strChunk2 = """{"type":"Point"}""" val strChunk3 = """{"type":"Feature"}""" val chunk1 = Buffer.buffer(strChunk1) val chunk2 = Buffer.buffer(strChunk2) val chunk3 = Buffer.buffer(strChunk3) val cm1 = GeoJsonChunkMeta("Polygon", "geometries") val cm2 = GeoJsonChunkMeta("Point", "geometries") val cm3 = GeoJsonChunkMeta("Feature", "features") doMerge( vertx, ctx, listOf(chunk1, chunk2, chunk3), listOf(cm1, cm2, cm3), """{"type":"FeatureCollection","features":[""" + """{"type":"Feature","geometry":$strChunk1},""" + """{"type":"Feature","geometry":$strChunk2},$strChunk3]}""" ) } /** * Test if two geometries and a feature can be merged to a feature collection */ @Test fun twoFeaturesAndAGeometry(vertx: Vertx, ctx: VertxTestContext) { val strChunk1 = """{"type":"Feature"}""" val strChunk2 = """{"type":"Feature","properties":{}}""" val strChunk3 = """{"type":"Point"}""" val chunk1 = Buffer.buffer(strChunk1) val chunk2 = Buffer.buffer(strChunk2) val chunk3 = Buffer.buffer(strChunk3) val cm1 = GeoJsonChunkMeta("Feature", "features") val cm2 = GeoJsonChunkMeta("Point", "geometries") doMerge( vertx, ctx, listOf(chunk1, chunk2, chunk3), listOf(cm1, cm1, cm2), """{"type":"FeatureCollection","features":[$strChunk1,$strChunk2,""" + """{"type":"Feature","geometry":$strChunk3}]}""" ) } /** * Test if the merger succeeds if [GeoJsonMerger.init] has * not been called just often enough */ @Test fun enoughInits(vertx: Vertx, ctx: VertxTestContext) { val strChunk1 = """{"type":"Feature"}""" val strChunk2 = """{"type":"Feature","properties":{}}""" val strChunk3 = """{"type":"Polygon"}""" val chunk1 = Buffer.buffer(strChunk1) val chunk2 = Buffer.buffer(strChunk2) val chunk3 = Buffer.buffer(strChunk3) val cm1 = GeoJsonChunkMeta("Feature", "features") val cm2 = GeoJsonChunkMeta("Polygon", "geometries") val jsonContents = """{"type":"FeatureCollection","features":""" + """[$strChunk1,$strChunk2,{"type":"Feature","geometry":$strChunk3}]}""" val m = GeoJsonMerger(false) val bws = BufferWriteStream() CoroutineScope(vertx.dispatcher()).launch { ctx.coVerify { m.init(cm1) m.init(cm1) m.merge(chunk1, cm1, bws) m.merge(chunk2, cm1, bws) m.merge(chunk3, cm2, bws) m.finish(bws) assertThat(jsonContents).isEqualTo(bws.buffer.toString("utf-8")) } ctx.completeNow() } } }
apache-2.0
72a0477ecb0d6981f4fab840f63905a8
34.352159
89
0.638004
3.731066
false
true
false
false
paplorinc/intellij-community
platform/platform-impl/src/com/intellij/internal/statistic/eventLog/FeatureUsageFileEventLogger.kt
1
2673
/* * 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.internal.statistic.eventLog import com.intellij.openapi.Disposable import com.intellij.util.ConcurrencyUtil import java.io.File import java.util.* open class FeatureUsageFileEventLogger(private val sessionId: String, private val build: String, private val bucket: String, private val recorderVersion: String, private val writer: FeatureUsageEventWriter) : FeatureUsageEventLogger, Disposable { protected val myLogExecutor = ConcurrencyUtil.newSingleThreadExecutor(javaClass.simpleName) private var lastEvent: LogEvent? = null private var lastEventTime: Long = 0 private var lastEventCreatedTime: Long = 0 override fun log(group: FeatureUsageGroup, action: String, isState: Boolean) { log(group, action, Collections.emptyMap(), isState) } override fun log(group: FeatureUsageGroup, action: String, data: Map<String, Any>, isState: Boolean) { val eventTime = System.currentTimeMillis() myLogExecutor.execute(Runnable { val creationTime = System.currentTimeMillis() val event = newLogEvent(sessionId, build, bucket, eventTime, group.id, group.version.toString(), recorderVersion, action, isState) for (datum in data) { event.event.addData(datum.key, datum.value) } log(writer, event, creationTime) }) } private fun log(writer: FeatureUsageEventWriter, event: LogEvent, createdTime: Long) { if (lastEvent != null && event.time - lastEventTime <= 10000 && lastEvent!!.shouldMerge(event)) { lastEventTime = event.time lastEvent!!.event.increment() } else { logLastEvent(writer) lastEvent = event lastEventTime = event.time lastEventCreatedTime = createdTime } } private fun logLastEvent(writer: FeatureUsageEventWriter) { lastEvent?.let { if (it.event.isEventGroup()) { it.event.addData("last", lastEventTime) } it.event.addData("created", lastEventCreatedTime) writer.log(LogEventSerializer.toString(it)) } lastEvent = null } override fun getLogFiles(): List<File> { return writer.getFiles() } override fun cleanup() { writer.cleanup() } override fun dispose() { dispose(writer) } private fun dispose(writer: FeatureUsageEventWriter) { myLogExecutor.execute(Runnable { logLastEvent(writer) }) myLogExecutor.shutdown() } }
apache-2.0
abd0b79869e05ba7ad8eb45ebe5a3c97
32.012346
140
0.67153
4.697715
false
false
false
false
paramsen/noise
sample/src/main/java/com/paramsen/noise/sample/view/FFTSpectogramView.kt
1
5090
package com.paramsen.noise.sample.view import android.content.Context import android.graphics.Canvas import android.graphics.Color import android.graphics.Paint import android.util.AttributeSet import android.util.Log import java.util.ArrayDeque import kotlin.math.pow import kotlin.math.sqrt import kotlin.system.measureTimeMillis /** * @author Pär Amsen 06/2017 */ class FFTSpectogramView(context: Context, attrs: AttributeSet?) : SimpleSurface(context, attrs), FFTView { val TAG = javaClass.simpleName val sec = 10 val hz = 44100 / 4096 val fps = 80 val history = hz * sec var resolution = 512 var minResolution = 64 val ffts = ArrayDeque<FloatArray>() val paintSpectogram: Paint = Paint() val paintText: Paint = textPaint() val paintMsg: Paint = errTextPaint() val bg = Color.rgb(20, 20, 25) val hotThresholds = hashMapOf(512 to 15000, 256 to 15000, 128 to 30000, 64 to 45000) val drawTimes = ArrayDeque<Long>() var msg: Pair<Long, String>? = null var lastAvg = Pair(System.currentTimeMillis(), 0) init { paintSpectogram.color = Color.parseColor("#FF2C00") paintSpectogram.style = Paint.Style.FILL } fun drawTitle(canvas: Canvas) = canvas.drawText("FFT SPECTOGRAM", 16f.px, 24f.px, paintText) fun drawIndicator(canvas: Canvas) { for (i in 0..height) { val f = i / height.toDouble() paintSpectogram.color = Spectogram.color(1.0 - f) canvas.drawRect(0f, i.toFloat(), 10f, i + 1f, paintSpectogram) } } fun drawMsg(canvas: Canvas) { val msg = msg ?: return if (msg.first > System.currentTimeMillis()) { canvas.drawText(msg.second, (width - paintMsg.measureText(msg.second)) / 2, height - 16f.px, paintMsg) } } fun drawSpectogram(canvas: Canvas) { val fftW = width / history.toFloat() val bandWH = height / resolution.toFloat() var x: Float var y: Float var band: FloatArray? val hot = hotThresholds[resolution] ?: 0 for (i in 0 until ffts.size) { synchronized(ffts) { band = ffts.elementAtOrNull(i) } x = width - (fftW * i) for (j in 0 until resolution) { y = height - (bandWH * j) val mag = band?.get(j) ?: .0f paintSpectogram.color = Spectogram.color((mag / hot.toDouble()).coerceAtMost(1.0)) canvas.drawRect(x - fftW, y - bandWH, x, y, paintSpectogram) } } } fun canDrawSpectogram() = resolution >= minResolution fun drawGraphic(canvas: Canvas): Canvas { canvas.drawColor(bg) if (!canDrawSpectogram()) { val msg = "GPU MEM TOO LOW" drawTitle(canvas) canvas.drawText(msg, (width - paintMsg.measureText(msg)) / 2, height - 16f.px, paintMsg) return canvas } // If rendering is causing backpressure [and thus fps drop], lower resolution + show message if (resolution >= minResolution && drawTimes.size >= history / 5 && avgDrawTime() > fps) { synchronized(ffts) { ffts.clear() } drawTimes.clear() resolution /= 2 msg = Pair(System.currentTimeMillis() + 10000, "DOWNSAMPLE DUE TO LOW GPU MEMORY") Log.w(TAG, "Draw hz exceeded 60 (${avgDrawTime()}), downsampled to $resolution") return canvas } drawTimes.addLast(measureTimeMillis { drawSpectogram(canvas) drawIndicator(canvas) drawTitle(canvas) drawMsg(canvas) }) println("===p4: ${drawTimes.last}") while (drawTimes.size > history) drawTimes.removeFirst() return canvas } override fun onFFT(fft: FloatArray) { if (canDrawSpectogram()) { val bands = FloatArray(resolution) var accum: Float var avg = 0f for (i in 0 until resolution) { accum = .0f for (j in 0 until fft.size / resolution step 2) { accum += (sqrt(fft[i * j].toDouble().pow(2.0) + fft[i * j + 1].toDouble().pow(2.0))).toFloat() //magnitudes } accum /= resolution bands[i] = accum avg += accum } avg /= resolution for (i in 0 until resolution) { if (bands[i] < avg / 2) bands[i] * 1000f } synchronized(ffts) { ffts.addFirst(bands) while (ffts.size > history) ffts.removeLast() } } drawSurface(this::drawGraphic) } private fun avgDrawTime(): Int { if (System.currentTimeMillis() - lastAvg.first > 1000) { lastAvg = Pair(System.currentTimeMillis(), if (drawTimes.size > 0) drawTimes.sum().div(drawTimes.size).toInt() else 0) } return lastAvg.second } }
apache-2.0
966a3fbc180a0e1f6035d01bbb0437b9
28.252874
130
0.567106
4.042097
false
false
false
false
paplorinc/intellij-community
uast/uast-common/src/org/jetbrains/uast/expressions/UUnaryExpression.kt
6
2845
/* * Copyright 2000-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.uast import com.intellij.psi.PsiMethod import org.jetbrains.uast.internal.acceptList import org.jetbrains.uast.internal.log import org.jetbrains.uast.visitor.UastTypedVisitor import org.jetbrains.uast.visitor.UastVisitor interface UUnaryExpression : UExpression { /** * Returns the expression operand. */ val operand: UExpression /** * Returns the expression operator. */ val operator: UastOperator /** * Returns the operator identifier. */ val operatorIdentifier: UIdentifier? /** * Resolve the operator method. * * @return the resolved method, or null if the method can't be resolved, or if the expression is not a method call. */ fun resolveOperator(): PsiMethod? override fun accept(visitor: UastVisitor) { if (visitor.visitUnaryExpression(this)) return annotations.acceptList(visitor) operand.accept(visitor) visitor.afterVisitUnaryExpression(this) } override fun <D, R> accept(visitor: UastTypedVisitor<D, R>, data: D): R = visitor.visitUnaryExpression(this, data) } interface UPrefixExpression : UUnaryExpression { override val operator: UastPrefixOperator override fun accept(visitor: UastVisitor) { if (visitor.visitPrefixExpression(this)) return annotations.acceptList(visitor) operand.accept(visitor) visitor.afterVisitPrefixExpression(this) } override fun <D, R> accept(visitor: UastTypedVisitor<D, R>, data: D): R = visitor.visitPrefixExpression(this, data) override fun asLogString(): String = log("operator = $operator") override fun asRenderString(): String = operator.text + operand.asRenderString() } interface UPostfixExpression : UUnaryExpression { override val operator: UastPostfixOperator override fun accept(visitor: UastVisitor) { if (visitor.visitPostfixExpression(this)) return annotations.acceptList(visitor) operand.accept(visitor) visitor.afterVisitPostfixExpression(this) } override fun <D, R> accept(visitor: UastTypedVisitor<D, R>, data: D): R = visitor.visitPostfixExpression(this, data) override fun asLogString(): String = log("operator = $operator") override fun asRenderString(): String = operand.asRenderString() + operator.text }
apache-2.0
fdcc9ebb56b8da7f08e555a6ae648a2c
29.934783
117
0.740949
4.410853
false
false
false
false
JetBrains/intellij-community
plugins/kotlin/code-insight/intentions-k2/src/org/jetbrains/kotlin/idea/k2/codeinsight/intentions/ConvertToStringTemplateIntention.kt
1
9021
// 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.k2.codeinsight.intentions import com.intellij.openapi.editor.Editor import com.intellij.openapi.util.text.StringUtil import com.intellij.psi.util.PsiUtilCore import org.jetbrains.kotlin.analysis.api.KtAllowAnalysisOnEdt import org.jetbrains.kotlin.analysis.api.analyze import org.jetbrains.kotlin.analysis.api.components.KtConstantEvaluationMode import org.jetbrains.kotlin.analysis.api.lifetime.allowAnalysisOnEdt import org.jetbrains.kotlin.analysis.api.symbols.KtCallableSymbol import org.jetbrains.kotlin.analysis.api.symbols.KtNamedClassOrObjectSymbol import org.jetbrains.kotlin.builtins.StandardNames import org.jetbrains.kotlin.idea.base.psi.replaced import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.codeinsight.api.classic.intentions.SelfTargetingOffsetIndependentIntention import org.jetbrains.kotlin.idea.codeinsight.utils.isToString import org.jetbrains.kotlin.idea.references.mainReference import org.jetbrains.kotlin.idea.util.application.runWriteActionIfPhysical import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.types.ConstantValueKind private const val TRIPLE_DOUBLE_QUOTE = "\"\"\"" /** * A class for convert-to-string-template intention. * * Example: "a" + 1 + 'b' + foo + 2.3f + bar -> "a1b${foo}2.3f{bar}" */ open class ConvertToStringTemplateIntention : SelfTargetingOffsetIndependentIntention<KtBinaryExpression>( KtBinaryExpression::class.java, KotlinBundle.lazyMessage("convert.concatenation.to.template") ) { /** * [element] is applicable for this intention if * - it is an expression with only string plus operations, and * - its parent is not an expression with only string plus operations * - which helps us to avoid handling the child multiple times * e.g., for "a" + 'b' + "c", we do not want to visit both 'b' + "c" and "a" + 'b' + "c" since 'b' + "c" will be handled * in "a" + 'b' + "c". */ override fun isApplicableTo(element: KtBinaryExpression): Boolean { if (!isStringPlusExpressionWithoutNewLineInOperands(element)) return false val parent = element.parent if (parent is KtBinaryExpression && isStringPlusExpressionWithoutNewLineInOperands(parent)) return false return true } override fun applyTo(element: KtBinaryExpression, editor: Editor?) { val replacement = buildStringTemplateForBinaryExpression(element) runWriteActionIfPhysical(element) { element.replaced(replacement) } } } /** * Recursively visits all operands of binary [expression] with plus and, * returns true if all operands do not have a new line. Otherwise, returns false. */ private fun hasNoPlusOperandWithNewLine(expression: KtExpression): Boolean { if (expression is KtBinaryExpression && expression.operationToken == KtTokens.PLUS) { val left = expression.left ?: return false val right = expression.right ?: return false return hasNoPlusOperandWithNewLine(left) && hasNoPlusOperandWithNewLine(right) } if (PsiUtilCore.hasErrorElementChild(expression)) return false if (expression.textContains('\n')) return false return true } /** * Returns true if [expression] * - is a binary expression with string plus, and * - has no operand with a new line. */ @OptIn(KtAllowAnalysisOnEdt::class) private fun isStringPlusExpressionWithoutNewLineInOperands(expression: KtBinaryExpression): Boolean { if (expression.operationToken != KtTokens.PLUS) return false if (!hasNoPlusOperandWithNewLine(expression)) return false return allowAnalysisOnEdt { analyze(expression) { if (expression.getKtType()?.isString != true) return@analyze false val plusOperation = expression.operationReference.mainReference.resolveToSymbol() as? KtCallableSymbol val classContainingPlus = plusOperation?.getContainingSymbol() as? KtNamedClassOrObjectSymbol classContainingPlus?.classIdIfNonLocal?.asSingleFqName() == StandardNames.FqNames.string.toSafe() } } } /** * A function to build a string or string template for a single operand of a binary expression. * * @param expr The single operand of a binary expression as an expression. * * Example: * When we convert * "a" + 1 + 'b' + foo + 2.3f + bar -> "a1b${foo}2.3f{bar}" * this function converts `bar` to "${bar}", `2.3f` to "2.3f", ... */ @OptIn(KtAllowAnalysisOnEdt::class) private fun buildStringTemplateForBinaryOperand(expr: KtExpression?, forceBraces: Boolean): String { if (expr == null) return "" val expression = KtPsiUtil.safeDeparenthesize(expr).let { expression -> val dotQualifiedExpression = expression as? KtDotQualifiedExpression when { dotQualifiedExpression != null && allowAnalysisOnEdt { dotQualifiedExpression.isToString() } && dotQualifiedExpression.receiverExpression !is KtSuperExpression -> dotQualifiedExpression.receiverExpression expression is KtLambdaExpression && expression.parent is KtLabeledExpression -> expr else -> expression } } val expressionText = expression.text when (expression) { is KtConstantExpression -> { allowAnalysisOnEdt { analyze(expression) { val constantValue = expression.evaluate(KtConstantEvaluationMode.CONSTANT_EXPRESSION_EVALUATION) ?: return "\${${expressionText}}" val isChar = constantValue.constantValueKind == ConstantValueKind.Char val stringValue = if (isChar) "${constantValue.value}" else constantValue.renderAsKotlinConstant() if (isChar || stringValue == expressionText) { return StringUtil.escapeStringCharacters( stringValue.length, stringValue, if (forceBraces) "\"$" else "\"", StringBuilder() ).toString() } } } } is KtStringTemplateExpression -> { val base = if (expressionText.startsWith(TRIPLE_DOUBLE_QUOTE) && expressionText.endsWith(TRIPLE_DOUBLE_QUOTE)) { val unquoted = expressionText.substring(TRIPLE_DOUBLE_QUOTE.length, expressionText.length - TRIPLE_DOUBLE_QUOTE.length) StringUtil.escapeStringCharacters(unquoted) } else { StringUtil.unquoteString(expressionText) } if (forceBraces) { if (base.endsWith(char = '$')) { return base.dropLast(n = 1) + "\\$" } else { val lastPart = expression.children.lastOrNull() if (lastPart is KtSimpleNameStringTemplateEntry) { return base.dropLast(lastPart.textLength) + "\${" + lastPart.text.drop(n = 1) + "}" } } } return base } is KtNameReferenceExpression -> return "$" + (if (forceBraces) "{$expressionText}" else expressionText) is KtThisExpression -> return "$" + (if (forceBraces || expression.labelQualifier != null) "{$expressionText}" else expressionText) } return "\${$expressionText}" } private fun foldOperandsOfBinaryExpression(left: KtExpression?, right: String, factory: KtPsiFactory): KtStringTemplateExpression { val forceBraces = right.isNotEmpty() && right.first() != '$' && right.first().isJavaIdentifierPart() return if (left is KtBinaryExpression && isStringPlusExpressionWithoutNewLineInOperands(left)) { val leftRight = buildStringTemplateForBinaryOperand(left.right, forceBraces) foldOperandsOfBinaryExpression(left.left, leftRight + right, factory) } else { val leftText = buildStringTemplateForBinaryOperand(left, forceBraces) factory.createExpression("\"$leftText$right\"") as KtStringTemplateExpression } } private fun buildStringTemplateForBinaryExpression(expression: KtBinaryExpression): KtStringTemplateExpression { val rightText = buildStringTemplateForBinaryOperand(expression.right, forceBraces = false) return foldOperandsOfBinaryExpression(expression.left, rightText, KtPsiFactory(expression)) } internal fun canConvertToStringTemplate(expression: KtBinaryExpression): Boolean { if (expression.textContains('\n')) return false val entries = buildStringTemplateForBinaryExpression(expression).entries return entries.none { it is KtBlockStringTemplateEntry } && entries.none { it !is KtLiteralStringTemplateEntry && it !is KtEscapeStringTemplateEntry } && entries.any { it is KtLiteralStringTemplateEntry } }
apache-2.0
683e145ebdeaf8040a5d544dbba63aaf
44.791878
174
0.691276
4.989491
false
false
false
false
youdonghai/intellij-community
platform/credential-store/src/dbV1Convertor.kt
2
5420
/* * Copyright 2000-2016 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.credentialStore import com.intellij.credentialStore.windows.WindowsCryptUtils import com.intellij.ide.ApplicationLoadListener import com.intellij.ide.passwordSafe.impl.providers.ByteArrayWrapper import com.intellij.ide.passwordSafe.impl.providers.EncryptionUtil import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.application.PathManager import com.intellij.openapi.components.ServiceManager import com.intellij.openapi.diagnostic.catchAndLog import com.intellij.openapi.ui.DialogWrapper import com.intellij.openapi.util.SystemInfo import com.intellij.openapi.util.text.StringUtil import com.intellij.util.io.exists import gnu.trove.THashMap import java.nio.file.Paths import java.util.function.Function private val TEST_PASSWORD_VALUE = "test password" internal fun isMasterPasswordValid(password: String, @Suppress("DEPRECATION") db: PasswordDatabase): Boolean { val key = EncryptionUtil.genPasswordKey(password) val value = db.myDatabase.get(ByteArrayWrapper(EncryptionUtil.encryptKey(key, rawTestKey(password)))) if (value != null) { return StringUtil.equals(EncryptionUtil.decryptText(key, value), TEST_PASSWORD_VALUE) } return false } internal fun checkPassAndConvertOldDb(password: String, @Suppress("DEPRECATION") db: PasswordDatabase): Map<CredentialAttributes, Credentials>? { return if (isMasterPasswordValid(password, db)) convertOldDb(password, db) else null } internal fun convertOldDb(@Suppress("DEPRECATION") db: PasswordDatabase): Map<CredentialAttributes, Credentials>? { if (db.myDatabase.size <= 1) { return null } // trying empty password: people who have set up empty password, don't want to get disturbed by the prompt checkPassAndConvertOldDb("", db)?.let { return it } if (SystemInfo.isWindows) { db.myMasterPassword?.let { try { WindowsCryptUtils.unprotect(it).toString(Charsets.UTF_8) } catch (e: Exception) { LOG.warn(e) null } }?.let { checkPassAndConvertOldDb(it, db)?.let { return it } } } if (db.myDatabase.size <= 1) { return null } var result: Map<CredentialAttributes, Credentials>? = null val dialog = MasterPasswordDialog(EnterPasswordComponent(Function { result = checkPassAndConvertOldDb(it, db) result != null })) if (ApplicationManager.getApplication().isUnitTestMode) { dialog.doOKAction() dialog.close(DialogWrapper.OK_EXIT_CODE) } else if (!dialog.showAndGet()) { LOG.warn("User cancelled master password dialog, will be recreated") } return result } internal fun convertOldDb(oldKey: String, @Suppress("DEPRECATION") db: PasswordDatabase): Map<CredentialAttributes, Credentials> { val oldKeyB = EncryptionUtil.genPasswordKey(oldKey) val testKey = ByteArrayWrapper(EncryptionUtil.encryptKey(oldKeyB, rawTestKey(oldKey))) val newDb = THashMap<CredentialAttributes, Credentials>(db.myDatabase.size) for ((key, value) in db.myDatabase) { if (testKey == key) { continue } // in old db we cannot get key value - it is hashed, so, we store it as a base64 encoded in the new DB val attributes = toOldKeyAsIdentity(EncryptionUtil.decryptKey(oldKeyB, key.unwrap())) newDb.put(attributes, Credentials(attributes.userName, EncryptionUtil.decryptText(oldKeyB, value))) } return newDb } private fun rawTestKey(oldKey: String) = EncryptionUtil.hash("com.intellij.ide.passwordSafe.impl.providers.masterKey.MasterKeyPasswordSafe/TEST_PASSWORD:${oldKey}".toByteArray()) internal class PasswordDatabaseConvertor : ApplicationLoadListener { override fun beforeComponentsCreated() { try { val oldDbFile = Paths.get(PathManager.getConfigPath(), "options", "security.xml") if (oldDbFile.exists()) { val settings = ServiceManager.getService(PasswordSafeSettings::class.java) if (settings.providerType == ProviderType.MEMORY_ONLY) { return } @Suppress("DEPRECATION") val oldDb = ServiceManager.getService(PasswordDatabase::class.java) // old db contains at least one test key - skip it if (oldDb.myDatabase.size > 1) { @Suppress("DEPRECATION") val newDb = convertOldDb(ServiceManager.getService<PasswordDatabase>(PasswordDatabase::class.java)) if (newDb != null && newDb.isNotEmpty()) { LOG.catchAndLog { for (factory in CredentialStoreFactory.CREDENTIAL_STORE_FACTORY.extensions) { val store = factory.create() ?: continue copyTo(newDb, store) return } } KeePassCredentialStore(newDb).save() } } } } catch (e: Throwable) { LOG.warn("Cannot check old password safe DB", e) } } }
apache-2.0
840e1cd55edce1852c9f01c1a49ffba7
37.176056
178
0.720664
4.188563
false
true
false
false
apollographql/apollo-android
apollo-compiler/src/main/kotlin/com/apollographql/apollo3/compiler/codegen/kotlin/model/ModelBuilder.kt
1
4049
package com.apollographql.apollo3.compiler.codegen.kotlin.model import com.apollographql.apollo3.compiler.TargetLanguage.KOTLIN_1_5 import com.apollographql.apollo3.compiler.applyIf import com.apollographql.apollo3.compiler.codegen.CodegenLayout.Companion.upperCamelCaseIgnoringNonLetters import com.apollographql.apollo3.compiler.codegen.kotlin.KotlinContext import com.apollographql.apollo3.compiler.codegen.kotlin.adapter.from import com.apollographql.apollo3.compiler.codegen.kotlin.helpers.makeDataClassFromProperties import com.apollographql.apollo3.compiler.codegen.kotlin.helpers.maybeAddDeprecation import com.apollographql.apollo3.compiler.codegen.kotlin.helpers.maybeAddDescription import com.apollographql.apollo3.compiler.decapitalizeFirstLetter import com.apollographql.apollo3.compiler.ir.IrAccessor import com.apollographql.apollo3.compiler.ir.IrFragmentAccessor import com.apollographql.apollo3.compiler.ir.IrModel import com.apollographql.apollo3.compiler.ir.IrSubtypeAccessor import com.squareup.kotlinpoet.ClassName import com.squareup.kotlinpoet.FunSpec import com.squareup.kotlinpoet.KModifier import com.squareup.kotlinpoet.PropertySpec import com.squareup.kotlinpoet.TypeSpec class ModelBuilder( private val context: KotlinContext, private val model: IrModel, private val superClassName: ClassName?, private val path: List<String>, private val hasSubclassesInSamePackage: Boolean, ) { private val nestedBuilders = model.modelGroups.flatMap { it.models.map { ModelBuilder( context = context, model = it, superClassName = null, path = path + model.modelName, hasSubclassesInSamePackage = hasSubclassesInSamePackage, ) } } fun prepare() { context.resolver.registerModel( model.id, ClassName.from(path + model.modelName) ) nestedBuilders.forEach { it.prepare() } } fun build(): TypeSpec { return model.typeSpec() } fun IrModel.typeSpec(): TypeSpec { val properties = properties.filter { !it.hidden }.map { PropertySpec.builder( context.layout.propertyName(it.info.responseName), context.resolver.resolveIrType(it.info.type) ) .applyIf(it.override) { addModifiers(KModifier.OVERRIDE) } .maybeAddDescription(it.info.description) .maybeAddDeprecation(it.info.deprecationReason) .build() } val superInterfaces = implements.map { context.resolver.resolveModel(it) } + listOfNotNull(superClassName) val typeSpecBuilder = if (isInterface) { TypeSpec.interfaceBuilder(modelName) // All interfaces can be sealed except if implementations exist in different packages (not allowed in Kotlin) .applyIf(context.isTargetLanguageVersionAtLeast(KOTLIN_1_5) && hasSubclassesInSamePackage) { addModifiers(KModifier.SEALED) } .addProperties(properties) } else { TypeSpec.classBuilder(modelName) .makeDataClassFromProperties(properties) } val nestedTypes = nestedBuilders.map { it.build() } return typeSpecBuilder .addTypes(nestedTypes) .applyIf(accessors.isNotEmpty()) { addType(companionTypeSpec(this@typeSpec)) } .addSuperinterfaces(superInterfaces) .build() } private fun companionTypeSpec(model: IrModel): TypeSpec { val funSpecs = model.accessors.map { accessor -> FunSpec.builder(accessor.funName()) .receiver(context.resolver.resolveModel(model.id)) .addCode("return this as? %T\n", context.resolver.resolveModel(accessor.returnedModelId)) .build() } return TypeSpec.companionObjectBuilder() .addFunctions(funSpecs) .build() } private fun IrAccessor.funName(): String { return when (this) { is IrFragmentAccessor -> this.fragmentName.decapitalizeFirstLetter() is IrSubtypeAccessor -> { "as${upperCamelCaseIgnoringNonLetters(this.typeSet)}" } } } }
mit
3a38953ae846458317d00119ff09233c
35.151786
119
0.723635
4.429978
false
false
false
false
allotria/intellij-community
platform/indexing-impl/src/com/intellij/psi/stubs/PrebuiltStubs.kt
2
4843
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.psi.stubs import com.google.common.hash.HashCode import com.google.common.hash.Hashing import com.intellij.index.PrebuiltIndexProvider import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.fileTypes.FileTypeExtension import com.intellij.openapi.progress.ProcessCanceledException import com.intellij.openapi.util.Disposer import com.intellij.openapi.util.text.StringUtilRt import com.intellij.util.indexing.FileContent import com.intellij.util.io.DataExternalizer import com.intellij.util.io.DataInputOutputUtil import com.intellij.util.io.KeyDescriptor import com.intellij.util.io.PersistentHashMap import java.io.DataInput import java.io.DataOutput import java.io.File import java.nio.file.Files const val EP_NAME = "com.intellij.filetype.prebuiltStubsProvider" val prebuiltStubsProvider: FileTypeExtension<PrebuiltStubsProvider> = FileTypeExtension<PrebuiltStubsProvider>(EP_NAME) interface PrebuiltStubsProvider { /** * Tries to find stub for [fileContent] in this provider. */ fun findStub(fileContent: FileContent): SerializedStubTree? } class FileContentHashing { private val hashing = Hashing.sha256() fun hashString(fileContent: FileContent): HashCode = hashing.hashBytes(fileContent.content)!! } class HashCodeDescriptor : HashCodeExternalizers(), KeyDescriptor<HashCode> { override fun getHashCode(value: HashCode): Int = value.hashCode() override fun isEqual(val1: HashCode, val2: HashCode): Boolean = val1 == val2 companion object { val instance: HashCodeDescriptor = HashCodeDescriptor() } } open class HashCodeExternalizers : DataExternalizer<HashCode> { override fun save(out: DataOutput, value: HashCode) { val bytes = value.asBytes() DataInputOutputUtil.writeINT(out, bytes.size) out.write(bytes, 0, bytes.size) } override fun read(`in`: DataInput): HashCode { val len = DataInputOutputUtil.readINT(`in`) val bytes = ByteArray(len) `in`.readFully(bytes) return HashCode.fromBytes(bytes) } } class GeneratingFullStubExternalizer : SerializedStubTreeDataExternalizer(SerializationManagerEx.getInstanceEx(), StubForwardIndexExternalizer.createFileLocalExternalizer()) abstract class PrebuiltStubsProviderBase : PrebuiltIndexProvider<SerializedStubTree>(), PrebuiltStubsProvider { private lateinit var mySerializationManager: SerializationManagerImpl protected abstract val stubVersion: Int override val indexName: String get() = SDK_STUBS_STORAGE_NAME override val indexExternalizer: SerializedStubTreeDataExternalizer get() = SerializedStubTreeDataExternalizer(mySerializationManager, StubForwardIndexExternalizer.createFileLocalExternalizer()) companion object { const val PREBUILT_INDICES_PATH_PROPERTY = "prebuilt_indices_path" const val SDK_STUBS_STORAGE_NAME = "sdk-stubs" private val LOG = logger<PrebuiltStubsProviderBase>() } protected open fun getIndexVersion(): Int = -1 override fun openIndexStorage(indexesRoot: File): PersistentHashMap<HashCode, SerializedStubTree>? { val formatFile = indexesRoot.toPath().resolve("$indexName.version") val versionFileText = Files.readAllLines(formatFile) if (versionFileText.size != 2) { LOG.warn("Invalid version file format: \"$versionFileText\" (file=$formatFile)") return null } val stubSerializationVersion = versionFileText[0] val currentSerializationVersion = StringUtilRt.parseInt(stubSerializationVersion, 0) val expected = getIndexVersion() if (expected != -1 && currentSerializationVersion != expected) { LOG.error("Stub serialization version mismatch: $expected, current version is $currentSerializationVersion") return null } val prebuiltIndexVersion = versionFileText[1] if (StringUtilRt.parseInt(prebuiltIndexVersion, 0) != stubVersion) { LOG.error("Prebuilt stubs version mismatch: $prebuiltIndexVersion, current version is $stubVersion") return null } else { mySerializationManager = SerializationManagerImpl(File(indexesRoot, "$indexName.names").toPath(), true) Disposer.register(ApplicationManager.getApplication(), mySerializationManager!!) return super.openIndexStorage(indexesRoot) } } override fun findStub(fileContent: FileContent): SerializedStubTree? { try { return get(fileContent) } catch (e: ProcessCanceledException) { throw e } catch (e: Exception) { dispose() LOG.error("Can't get prebuilt stub tree from ${this.javaClass.name}", e) } return null } }
apache-2.0
f4622983c9e5cf2b2cf0969067b27738
37.133858
195
0.758001
4.711089
false
false
false
false
allotria/intellij-community
platform/lang-impl/src/com/intellij/workspaceModel/ide/impl/legacyBridge/LegacyBridgeProjectLifecycleListener.kt
1
4106
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.workspaceModel.ide.impl.legacyBridge import com.intellij.ide.plugins.PluginManagerCore import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.module.ModuleManager import com.intellij.openapi.module.impl.ExternalModuleListStorage import com.intellij.openapi.project.Project import com.intellij.openapi.project.impl.ProjectServiceContainerCustomizer import com.intellij.openapi.roots.ProjectRootManager import com.intellij.openapi.roots.impl.ModifiableModelCommitterService import com.intellij.openapi.roots.impl.libraries.ProjectLibraryTable import com.intellij.serviceContainer.ComponentManagerImpl import com.intellij.workspaceModel.ide.WorkspaceModel import com.intellij.workspaceModel.ide.WorkspaceModelTopics import com.intellij.workspaceModel.ide.impl.WorkspaceModelImpl import com.intellij.workspaceModel.ide.impl.WorkspaceModelInitialTestContent import com.intellij.workspaceModel.ide.impl.jps.serialization.JpsProjectModelSynchronizer import com.intellij.workspaceModel.ide.impl.legacyBridge.facet.FacetEntityChangeListener import com.intellij.workspaceModel.ide.impl.legacyBridge.watcher.RootsChangeWatcher import com.intellij.workspaceModel.ide.impl.legacyBridge.watcher.VirtualFileUrlWatcher import com.intellij.workspaceModel.ide.impl.legacyBridge.library.ProjectLibraryTableBridgeImpl import com.intellij.workspaceModel.ide.impl.legacyBridge.module.ModuleManagerComponentBridge import com.intellij.workspaceModel.ide.impl.legacyBridge.module.roots.ModifiableModelCommitterServiceBridge import com.intellij.workspaceModel.ide.impl.legacyBridge.project.ProjectRootManagerBridge import org.jetbrains.annotations.ApiStatus import org.picocontainer.MutablePicoContainer @ApiStatus.Internal class LegacyBridgeProjectLifecycleListener : ProjectServiceContainerCustomizer { companion object { private val LOG = logger<LegacyBridgeProjectLifecycleListener>() fun enabled(project: Project) = ModuleManager.getInstance(project) is ModuleManagerComponentBridge } override fun serviceRegistered(project: Project) { val enabled = WorkspaceModel.isEnabled || WorkspaceModelInitialTestContent.peek() != null if (!enabled) { LOG.info("Using legacy project model to open project") return } LOG.info("Using workspace model to open project") val pluginDescriptor = PluginManagerCore.getPlugin(PluginManagerCore.CORE_ID) ?: error("Could not find plugin by id: ${PluginManagerCore.CORE_ID}") val container = project as ComponentManagerImpl container.registerComponent(JpsProjectModelSynchronizer::class.java, JpsProjectModelSynchronizer::class.java, pluginDescriptor, false) container.registerComponent(RootsChangeWatcher::class.java, RootsChangeWatcher::class.java, pluginDescriptor, false) container.registerComponent(VirtualFileUrlWatcher::class.java, VirtualFileUrlWatcher::class.java, pluginDescriptor, false) container.registerComponent(ModuleManager::class.java, ModuleManagerComponentBridge::class.java, pluginDescriptor, true) container.registerComponent(ProjectRootManager::class.java, ProjectRootManagerBridge::class.java, pluginDescriptor, true) (container.picoContainer as MutablePicoContainer).unregisterComponent(ExternalModuleListStorage::class.java) container.registerService(WorkspaceModel::class.java, WorkspaceModelImpl::class.java, pluginDescriptor, false) container.registerService(ProjectLibraryTable::class.java, ProjectLibraryTableBridgeImpl::class.java, pluginDescriptor, true) container.registerService(ModifiableModelCommitterService::class.java, ModifiableModelCommitterServiceBridge::class.java, pluginDescriptor, true) container.registerService(WorkspaceModelTopics::class.java, WorkspaceModelTopics::class.java, pluginDescriptor, false) container.registerService(FacetEntityChangeListener::class.java, FacetEntityChangeListener::class.java, pluginDescriptor, false) } }
apache-2.0
5e4630d94babb87ea11e031f050dceac
62.184615
149
0.840234
5.151819
false
false
false
false
spring-projects/spring-framework
spring-messaging/src/test/kotlin/org/springframework/messaging/rsocket/RSocketClientToServerCoroutinesIntegrationTests.kt
1
8194
/* * Copyright 2002-2020 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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 org.springframework.messaging.rsocket import io.netty.buffer.PooledByteBufAllocator import io.rsocket.core.RSocketServer import io.rsocket.frame.decoder.PayloadDecoder import io.rsocket.transport.netty.server.CloseableChannel import io.rsocket.transport.netty.server.TcpServerTransport import kotlinx.coroutines.delay import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.flow import kotlinx.coroutines.flow.map import org.junit.jupiter.api.AfterAll import org.junit.jupiter.api.BeforeAll import org.junit.jupiter.api.Test import org.springframework.context.annotation.AnnotationConfigApplicationContext import org.springframework.context.annotation.Bean import org.springframework.context.annotation.Configuration import org.springframework.core.codec.CharSequenceEncoder import org.springframework.core.codec.StringDecoder import org.springframework.core.io.buffer.NettyDataBufferFactory import org.springframework.messaging.handler.annotation.MessageExceptionHandler import org.springframework.messaging.handler.annotation.MessageMapping import org.springframework.messaging.rsocket.annotation.support.RSocketMessageHandler import org.springframework.stereotype.Controller import reactor.core.publisher.Flux import reactor.core.publisher.Sinks import reactor.test.StepVerifier import java.time.Duration /** * Coroutines server-side handling of RSocket requests. * * @author Sebastien Deleuze * @author Rossen Stoyanchev */ class RSocketClientToServerCoroutinesIntegrationTests { @Test fun fireAndForget() { Flux.range(1, 3) .concatMap { requester.route("receive").data("Hello $it").send() } .blockLast() StepVerifier.create(context.getBean(ServerController::class.java).fireForgetPayloads.asFlux()) .expectNext("Hello 1") .expectNext("Hello 2") .expectNext("Hello 3") .thenAwait(Duration.ofMillis(50)) .thenCancel() .verify(Duration.ofSeconds(5)) } @Test fun fireAndForgetAsync() { Flux.range(1, 3) .concatMap { i: Int -> requester.route("receive-async").data("Hello $i").send() } .blockLast() StepVerifier.create(context.getBean(ServerController::class.java).fireForgetPayloads.asFlux()) .expectNext("Hello 1") .expectNext("Hello 2") .expectNext("Hello 3") .thenAwait(Duration.ofMillis(50)) .thenCancel() .verify(Duration.ofSeconds(5)) } @Test fun echoAsync() { val result = Flux.range(1, 3).concatMap { i -> requester.route("echo-async").data("Hello " + i!!).retrieveMono(String::class.java) } StepVerifier.create(result) .expectNext("Hello 1 async").expectNext("Hello 2 async").expectNext("Hello 3 async") .expectComplete() .verify(Duration.ofSeconds(5)) } @Test fun echoStream() { val result = requester.route("echo-stream").data("Hello").retrieveFlux(String::class.java) StepVerifier.create(result) .expectNext("Hello 0").expectNextCount(6).expectNext("Hello 7") .thenCancel() .verify(Duration.ofSeconds(5)) } @Test fun echoStreamAsync() { val result = requester.route("echo-stream-async").data("Hello").retrieveFlux(String::class.java) StepVerifier.create(result) .expectNext("Hello 0").expectNextCount(6).expectNext("Hello 7") .thenCancel() .verify(Duration.ofSeconds(5)) } @Test fun echoChannel() { val result = requester.route("echo-channel") .data(Flux.range(1, 10).map { i -> "Hello " + i!! }, String::class.java) .retrieveFlux(String::class.java) StepVerifier.create(result) .expectNext("Hello 1 async").expectNextCount(8).expectNext("Hello 10 async") .thenCancel() // https://github.com/rsocket/rsocket-java/issues/613 .verify(Duration.ofSeconds(5)) } @Test fun unitReturnValue() { val result = requester.route("unit-return-value").data("Hello").retrieveMono(String::class.java) StepVerifier.create(result).expectComplete().verify(Duration.ofSeconds(5)) } @Test fun unitReturnValueFromExceptionHandler() { val result = requester.route("unit-return-value").data("bad").retrieveMono(String::class.java) StepVerifier.create(result).expectComplete().verify(Duration.ofSeconds(5)) } @Test fun handleWithThrownException() { val result = requester.route("thrown-exception").data("a").retrieveMono(String::class.java) StepVerifier.create(result) .expectNext("Invalid input error handled") .expectComplete() .verify(Duration.ofSeconds(5)) } @Controller class ServerController { val fireForgetPayloads = Sinks.many().replay().all<String>() @MessageMapping("receive") fun receive(payload: String) { fireForgetPayloads.tryEmitNext(payload) } @MessageMapping("receive-async") suspend fun receiveAsync(payload: String) { delay(10) fireForgetPayloads.tryEmitNext(payload) } @MessageMapping("echo-async") suspend fun echoAsync(payload: String): String { delay(10) return "$payload async" } @MessageMapping("echo-stream") fun echoStream(payload: String): Flow<String> { var i = 0 return flow { while(true) { delay(10) emit("$payload ${i++}") } } } @MessageMapping("echo-stream-async") suspend fun echoStreamAsync(payload: String): Flow<String> { delay(10) var i = 0 return flow { while(true) { delay(10) emit("$payload ${i++}") } } } @MessageMapping("echo-channel") fun echoChannel(payloads: Flow<String>) = payloads.map { delay(10) "$it async" } @Suppress("UNUSED_PARAMETER") @MessageMapping("thrown-exception") suspend fun handleAndThrow(payload: String): String { delay(10) throw IllegalArgumentException("Invalid input error") } @MessageMapping("unit-return-value") suspend fun unitReturnValue(payload: String) = if (payload != "bad") delay(10) else throw IllegalStateException("bad") @MessageExceptionHandler suspend fun handleException(ex: IllegalArgumentException): String { delay(10) return "${ex.message} handled" } @Suppress("UNUSED_PARAMETER") @MessageExceptionHandler suspend fun handleExceptionWithVoidReturnValue(ex: IllegalStateException) { delay(10) } } @Configuration open class ServerConfig { @Bean open fun controller(): ServerController { return ServerController() } @Bean open fun messageHandler(): RSocketMessageHandler { val handler = RSocketMessageHandler() handler.rSocketStrategies = rsocketStrategies() return handler } @Bean open fun rsocketStrategies(): RSocketStrategies { return RSocketStrategies.builder() .decoder(StringDecoder.allMimeTypes()) .encoder(CharSequenceEncoder.allMimeTypes()) .dataBufferFactory(NettyDataBufferFactory(PooledByteBufAllocator.DEFAULT)) .build() } } companion object { private lateinit var context: AnnotationConfigApplicationContext private lateinit var server: CloseableChannel private lateinit var requester: RSocketRequester @BeforeAll @JvmStatic fun setupOnce() { context = AnnotationConfigApplicationContext(ServerConfig::class.java) server = RSocketServer.create(context.getBean(RSocketMessageHandler::class.java).responder()) .payloadDecoder(PayloadDecoder.ZERO_COPY) .bind(TcpServerTransport.create("localhost", 7000)) .block()!! requester = RSocketRequester.builder() .rsocketConnector { connector -> connector.payloadDecoder(PayloadDecoder.ZERO_COPY) } .rsocketStrategies(context.getBean(RSocketStrategies::class.java)) .tcp("localhost", 7000) } @AfterAll @JvmStatic fun tearDownOnce() { requester.rsocketClient().dispose() server.dispose() } } }
apache-2.0
27b4da1cb2cf590b1755bcbd8fcffc45
28.369176
134
0.735416
3.697653
false
false
false
false
leafclick/intellij-community
platform/script-debugger/debugger-ui/src/VariableView.kt
1
20044
// 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.debugger import com.intellij.icons.AllIcons import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.project.Project import com.intellij.openapi.util.text.StringUtil import com.intellij.pom.Navigatable import com.intellij.psi.PsiElement import com.intellij.psi.PsiReference import com.intellij.util.SmartList import com.intellij.util.ThreeState import com.intellij.xdebugger.XExpression import com.intellij.xdebugger.XSourcePositionWrapper import com.intellij.xdebugger.frame.* import com.intellij.xdebugger.frame.presentation.XKeywordValuePresentation import com.intellij.xdebugger.frame.presentation.XNumericValuePresentation import com.intellij.xdebugger.frame.presentation.XStringValuePresentation import com.intellij.xdebugger.frame.presentation.XValuePresentation import org.jetbrains.concurrency.* import org.jetbrains.debugger.values.* import java.util.* import java.util.concurrent.atomic.AtomicBoolean import java.util.regex.Pattern import javax.swing.Icon fun VariableView(variable: Variable, context: VariableContext): VariableView = VariableView(variable.name, variable, context) class VariableView(override val variableName: String, private val variable: Variable, private val context: VariableContext) : XNamedValue(variableName), VariableContext { @Volatile private var value: Value? = null // lazy computed private var _memberFilter: MemberFilter? = null @Volatile private var remainingChildren: List<Variable>? = null @Volatile private var remainingChildrenOffset: Int = 0 override fun watchableAsEvaluationExpression(): Boolean = context.watchableAsEvaluationExpression() override val viewSupport: DebuggerViewSupport get() = context.viewSupport override val parent: VariableContext = context override val memberFilter: Promise<MemberFilter> get() = context.viewSupport.getMemberFilter(this) override val evaluateContext: EvaluateContext get() = context.evaluateContext override val scope: Scope? get() = context.scope override val vm: Vm? get() = context.vm override fun computePresentation(node: XValueNode, place: XValuePlace) { value = variable.value if (value != null) { computePresentation(value!!, node) return } if (variable !is ObjectProperty || variable.getter == null) { // it is "used" expression (WEB-6779 Debugger/Variables: Automatically show used variables) context.memberFilter.then { evaluateContext.evaluate(it.sourceNameToRaw(variable.name) ?: variable.name) .onSuccess(node) { if (it.wasThrown) { setEvaluatedValue(viewSupport.transformErrorOnGetUsedReferenceValue(it.value, null), null, node) } else { value = it.value computePresentation(it.value, node) } } .onError(node) { setEvaluatedValue(viewSupport.transformErrorOnGetUsedReferenceValue(null, it.message), it.message, node) } } return } node.setPresentation(null, object : XValuePresentation() { override fun renderValue(renderer: XValuePresentation.XValueTextRenderer) { renderer.renderValue("\u2026") } }, false) node.setFullValueEvaluator(object : XFullValueEvaluator(" (invoke getter)") { override fun startEvaluation(callback: XFullValueEvaluator.XFullValueEvaluationCallback) { var valueModifier = variable.valueModifier var nonProtoContext = context while (nonProtoContext is VariableView && nonProtoContext.variableName == PROTOTYPE_PROP) { valueModifier = nonProtoContext.variable.valueModifier nonProtoContext = nonProtoContext.parent } valueModifier!!.evaluateGet(variable, evaluateContext) .onSuccess(node) { callback.evaluated("") setEvaluatedValue(it, null, node) } } }.setShowValuePopup(false)) } private fun setEvaluatedValue(value: Value?, error: String?, node: XValueNode) { if (value == null) { node.setPresentation(AllIcons.Debugger.Db_primitive, null, error ?: "Internal Error", false) } else { this.value = value computePresentation(value, node) } } private fun computePresentation(value: Value, node: XValueNode) { when (value.type) { ValueType.OBJECT, ValueType.NODE -> context.viewSupport.computeObjectPresentation((value as ObjectValue), variable, context, node, icon) ValueType.FUNCTION -> node.setPresentation(icon, ObjectValuePresentation(trimFunctionDescription(value)), true) ValueType.ARRAY -> context.viewSupport.computeArrayPresentation(value, variable, context, node, icon) ValueType.BOOLEAN, ValueType.NULL, ValueType.UNDEFINED -> node.setPresentation(icon, XKeywordValuePresentation(value.valueString!!), false) ValueType.NUMBER, ValueType.BIGINT -> node.setPresentation(icon, createNumberPresentation(value.valueString!!), false) ValueType.STRING -> { node.setPresentation(icon, XStringValuePresentation(value.valueString!!), false) // isTruncated in terms of debugger backend, not in our terms (i.e. sometimes we cannot control truncation), // so, even in case of StringValue, we check value string length if ((value is StringValue && value.isTruncated) || value.valueString!!.length > XValueNode.MAX_VALUE_LENGTH) { node.setFullValueEvaluator(MyFullValueEvaluator(value)) } } else -> node.setPresentation(icon, null, value.valueString!!, true) } } override fun computeChildren(node: XCompositeNode) { node.setAlreadySorted(true) if (value !is ObjectValue) { node.addChildren(XValueChildrenList.EMPTY, true) return } val list = remainingChildren if (list != null) { val to = Math.min(remainingChildrenOffset + XCompositeNode.MAX_CHILDREN_TO_SHOW, list.size) val isLast = to == list.size node.addChildren(createVariablesList(list, remainingChildrenOffset, to, this, _memberFilter), isLast) if (!isLast) { node.tooManyChildren(list.size - to) remainingChildrenOffset += XCompositeNode.MAX_CHILDREN_TO_SHOW } return } val objectValue = value as ObjectValue val hasNamedProperties = objectValue.hasProperties() != ThreeState.NO val hasIndexedProperties = objectValue.hasIndexedProperties() != ThreeState.NO val promises = SmartList<Promise<*>>() val additionalProperties = viewSupport.computeAdditionalObjectProperties(objectValue, variable, this, node) if (additionalProperties != null) { promises.add(additionalProperties) } // we don't support indexed properties if additional properties added - behavior is undefined if object has indexed properties and additional properties also specified if (hasIndexedProperties) { promises.add(computeIndexedProperties(objectValue as ArrayValue, node, !hasNamedProperties && additionalProperties == null)) } if (hasNamedProperties) { // named properties should be added after additional properties if (additionalProperties == null || additionalProperties.state != Promise.State.PENDING) { promises.add(computeNamedProperties(objectValue, node, !hasIndexedProperties && additionalProperties == null)) } else { promises.add(additionalProperties.thenAsync(node) { computeNamedProperties(objectValue, node, true) }) } } if (hasIndexedProperties == hasNamedProperties || additionalProperties != null) { promises.all().processed(node) { node.addChildren(XValueChildrenList.EMPTY, true) } } } abstract class ObsolescentIndexedVariablesConsumer(protected val node: XCompositeNode) : IndexedVariablesConsumer() { override val isObsolete: Boolean get() = node.isObsolete } private fun computeIndexedProperties(value: ArrayValue, node: XCompositeNode, isLastChildren: Boolean): Promise<*> { return value.getIndexedProperties(0, value.length, XCompositeNode.MAX_CHILDREN_TO_SHOW, object : ObsolescentIndexedVariablesConsumer(node) { override fun consumeRanges(ranges: IntArray?) { if (ranges == null) { val groupList = XValueChildrenList() addGroups(value, ::lazyVariablesGroup, groupList, 0, value.length, XCompositeNode.MAX_CHILDREN_TO_SHOW, this@VariableView) node.addChildren(groupList, isLastChildren) } else { addRanges(value, ranges, node, this@VariableView, isLastChildren) } } override fun consumeVariables(variables: List<Variable>) { node.addChildren(createVariablesList(variables, this@VariableView, null), isLastChildren) } }) } private fun computeNamedProperties(value: ObjectValue, node: XCompositeNode, isLastChildren: Boolean) = processVariables(this, value.properties, node) { memberFilter, variables -> _memberFilter = memberFilter if (value.type == ValueType.ARRAY && value !is ArrayValue) { computeArrayRanges(variables, node) return@processVariables } var functionValue = value as? FunctionValue if (functionValue != null && (functionValue.hasScopes() == ThreeState.NO)) { functionValue = null } remainingChildren = processNamedObjectProperties(variables, node, this@VariableView, memberFilter, XCompositeNode.MAX_CHILDREN_TO_SHOW, isLastChildren && functionValue == null) if (remainingChildren != null) { remainingChildrenOffset = XCompositeNode.MAX_CHILDREN_TO_SHOW } if (functionValue != null) { // we pass context as variable context instead of this variable value - we cannot watch function scopes variables, so, this variable name doesn't matter node.addChildren(XValueChildrenList.bottomGroup(FunctionScopesValueGroup(functionValue, context)), isLastChildren && remainingChildren == null) } } private fun computeArrayRanges(properties: List<Variable>, node: XCompositeNode) { val variables = filterAndSort(properties, _memberFilter!!) var count = variables.size val bucketSize = XCompositeNode.MAX_CHILDREN_TO_SHOW if (count <= bucketSize) { node.addChildren(createVariablesList(variables, this, null), true) return } while (count > 0) { if (Character.isDigit(variables.get(count - 1).name[0])) { break } count-- } val groupList = XValueChildrenList() if (count > 0) { addGroups(variables, ::createArrayRangeGroup, groupList, 0, count, bucketSize, this) } var notGroupedVariablesOffset: Int if ((variables.size - count) > bucketSize) { notGroupedVariablesOffset = variables.size while (notGroupedVariablesOffset > 0) { if (!variables.get(notGroupedVariablesOffset - 1).name.startsWith("__")) { break } notGroupedVariablesOffset-- } if (notGroupedVariablesOffset > 0) { addGroups(variables, ::createArrayRangeGroup, groupList, count, notGroupedVariablesOffset, bucketSize, this) } } else { notGroupedVariablesOffset = count } for (i in notGroupedVariablesOffset..variables.size - 1) { val variable = variables.get(i) groupList.add(VariableView(_memberFilter!!.rawNameToSource(variable), variable, this)) } node.addChildren(groupList, true) } private val icon: Icon get() = getIcon(value!!) override fun getModifier(): XValueModifier? { if (!variable.isMutable) { return null } return object : XValueModifier() { override fun getInitialValueEditorText(): String? { if (value!!.type == ValueType.STRING) { val string = value!!.valueString!! val builder = StringBuilder(string.length) builder.append('"') StringUtil.escapeStringCharacters(string.length, string, builder) builder.append('"') return builder.toString() } else { return if (value!!.type.isObjectType) null else value!!.valueString } } override fun setValue(expression: XExpression, callback: XValueModifier.XModificationCallback) { variable.valueModifier!!.setValue(variable, expression.expression, evaluateContext) .onSuccess { value = null callback.valueModified() } .onError { callback.errorOccurred(it.message!!) } } } } fun getValue(): Value? = variable.value override fun canNavigateToSource(): Boolean = value is FunctionValue && value?.valueString?.contains("[native code]") != true || viewSupport.canNavigateToSource(variable, context) override fun computeSourcePosition(navigatable: XNavigatable) { if (value is FunctionValue) { (value as FunctionValue).resolve() .onSuccess { function -> vm!!.scriptManager.getScript(function) .onSuccess { navigatable.setSourcePosition(it?.let { viewSupport.getSourceInfo(null, it, function.openParenLine, function.openParenColumn) }?.let { object : XSourcePositionWrapper(it) { override fun createNavigatable(project: Project): Navigatable { return PsiVisitors.visit(myPosition, project) { _, element, _, _ -> // element will be "open paren", but we should navigate to function name, // we cannot use specific PSI type here (like JSFunction), so, we try to find reference expression (i.e. name expression) var referenceCandidate: PsiElement? = element var psiReference: PsiElement? = null while (true) { referenceCandidate = referenceCandidate?.prevSibling ?: break if (referenceCandidate is PsiReference) { psiReference = referenceCandidate break } } if (psiReference == null) { referenceCandidate = element.parent while (true) { referenceCandidate = referenceCandidate?.prevSibling ?: break if (referenceCandidate is PsiReference) { psiReference = referenceCandidate break } } } (if (psiReference == null) element.navigationElement else psiReference.navigationElement) as? Navigatable } ?: super.createNavigatable(project) } } }) } } } else { viewSupport.computeSourcePosition(variableName, value!!, variable, context, navigatable) } } override fun computeInlineDebuggerData(callback: XInlineDebuggerDataCallback): ThreeState = viewSupport.computeInlineDebuggerData(variableName, variable, context, callback) override fun getEvaluationExpression(): String? { if (!watchableAsEvaluationExpression()) { return null } if (context.variableName == null) return variable.name // top level watch expression, may be call etc. val list = SmartList<String>() addVarName(list, parent, variable.name) var parent: VariableContext? = context while (parent != null && parent.variableName != null) { addVarName(list, parent.parent, parent.variableName!!) parent = parent.parent } return context.viewSupport.propertyNamesToString(list, false) } private fun addVarName(list: SmartList<String>, parent: VariableContext?, name: String) { if (parent == null || parent.variableName != null) list.add(name) else list.addAll(name.split(".").reversed()) } private class MyFullValueEvaluator(private val value: Value) : XFullValueEvaluator(if (value is StringValue) value.length else value.valueString!!.length) { override fun startEvaluation(callback: XFullValueEvaluator.XFullValueEvaluationCallback) { if (value !is StringValue || !value.isTruncated) { callback.evaluated(value.valueString!!) return } val evaluated = AtomicBoolean() value.fullString .onSuccess { if (!callback.isObsolete && evaluated.compareAndSet(false, true)) { callback.evaluated(value.valueString!!) } } .onError { callback.errorOccurred(it.message!!) } } } companion object { fun setObjectPresentation(value: ObjectValue, icon: Icon, node: XValueNode) { node.setPresentation(icon, ObjectValuePresentation(getObjectValueDescription(value)), value.hasProperties() != ThreeState.NO) } fun setArrayPresentation(value: Value, context: VariableContext, icon: Icon, node: XValueNode) { assert(value.type == ValueType.ARRAY) if (value is ArrayValue) { val length = value.length node.setPresentation(icon, ArrayPresentation(length, value.className), length > 0) return } val valueString = value.valueString // only WIP reports normal description if (valueString != null && (valueString.endsWith(")") || valueString.endsWith(']')) && ARRAY_DESCRIPTION_PATTERN.matcher(valueString).find()) { node.setPresentation(icon, null, valueString, true) } else { context.evaluateContext.evaluate("a.length", Collections.singletonMap<String, Any>("a", value), false) .onSuccess(node) { node.setPresentation(icon, null, "Array[${it.value.valueString}]", true) } .onError(node) { logger<VariableView>().error("Failed to evaluate array length: $it") node.setPresentation(icon, null, valueString ?: "Array", true) } } } fun getIcon(value: Value): Icon { val type = value.type return when (type) { ValueType.FUNCTION -> AllIcons.Nodes.Lambda ValueType.ARRAY -> AllIcons.Debugger.Db_array else -> if (type.isObjectType) AllIcons.Debugger.Value else AllIcons.Debugger.Db_primitive } } } } fun getClassName(value: ObjectValue): String { val className = value.className return when { className.isNullOrEmpty() -> "Object" className == "console" -> "Console" else -> className } } fun getObjectValueDescription(value: ObjectValue): String { val description = value.valueString return if (description.isNullOrEmpty()) getClassName(value) else description } internal fun trimFunctionDescription(value: Value): String { return trimFunctionDescription(value.valueString ?: return "") } fun trimFunctionDescription(value: String): String { var endIndex = 0 while (endIndex < value.length && !StringUtil.isLineBreak(value[endIndex])) { endIndex++ } while (endIndex > 0 && Character.isWhitespace(value[endIndex - 1])) { endIndex-- } return value.substring(0, endIndex) } private fun createNumberPresentation(value: String): XValuePresentation { return if (value == PrimitiveValue.NA_N_VALUE || value == PrimitiveValue.INFINITY_VALUE) XKeywordValuePresentation(value) else XNumericValuePresentation(value) } private val ARRAY_DESCRIPTION_PATTERN = Pattern.compile("^[a-zA-Z\\d]+[\\[(]\\d+[\\])]$") private class ArrayPresentation(length: Int, className: String?) : XValuePresentation() { private val length = Integer.toString(length) private val className = if (className.isNullOrEmpty()) "Array" else className override fun renderValue(renderer: XValuePresentation.XValueTextRenderer) { renderer.renderSpecialSymbol(className) renderer.renderSpecialSymbol("[") renderer.renderSpecialSymbol(length) renderer.renderSpecialSymbol("]") } } private const val PROTOTYPE_PROP = "__proto__"
apache-2.0
ef1256011c192250e61bf2b8f130833a
39.251004
181
0.681002
5.152699
false
false
false
false
zdary/intellij-community
plugins/ide-features-trainer/src/training/dsl/impl/TaskContextImpl.kt
2
10758
// 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 training.dsl.impl import com.intellij.codeInsight.daemon.impl.DaemonCodeAnalyzerEx import com.intellij.openapi.application.* import com.intellij.openapi.command.WriteCommandAction import com.intellij.openapi.fileEditor.FileDocumentManager import com.intellij.openapi.fileEditor.FileEditorManager import com.intellij.openapi.fileEditor.OpenFileDescriptor import com.intellij.openapi.project.DumbService import com.intellij.openapi.project.Project import com.intellij.openapi.vfs.VirtualFile import com.intellij.psi.PsiDocumentManager import com.intellij.ui.EditorNotifications import org.fest.swing.exception.ComponentLookupException import org.fest.swing.exception.WaitTimedOutError import org.intellij.lang.annotations.Language import training.dsl.* import training.learn.ActionsRecorder import training.learn.LearnBundle import training.learn.lesson.LessonManager import training.statistic.StatisticBase import java.awt.Component import java.util.concurrent.CompletableFuture import java.util.concurrent.Future import javax.swing.JComponent internal class TaskContextImpl(private val lessonExecutor: LessonExecutor, private val recorder: ActionsRecorder, val taskIndex: Int, private val data: LessonExecutor.TaskData) : TaskContext() { override val project: Project get() = lessonExecutor.project override val taskId = TaskId(taskIndex) private val runtimeContext = TaskRuntimeContext(lessonExecutor, recorder, { lessonExecutor.applyRestore(this) }, { lessonExecutor.getUserVisibleInfo(taskIndex) }) val steps: MutableList<CompletableFuture<Boolean>> = mutableListOf() val testActions: MutableList<Runnable> = mutableListOf() override fun before(preparation: TaskRuntimeContext.() -> Unit) { preparation(runtimeContext) // just call it here } override fun restoreState(restoreId: TaskId?, delayMillis: Int, restoreRequired: TaskRuntimeContext.() -> Boolean) { data.delayMillis = delayMillis val previous = data.shouldRestoreToTask val actualId = restoreId ?: TaskId(taskIndex - 1) data.shouldRestoreToTask = { previous?.let { it() } ?: if (restoreRequired(runtimeContext)) actualId else null } } override fun proposeRestore(restoreCheck: TaskRuntimeContext.() -> RestoreNotification?) { restoreState { // restoreState is used to trigger by any IDE state change and check restore proposal is needed [email protected](needToLog = true, restoreCheck) { LessonManager.instance.setRestoreNotification(it) } return@restoreState false } } private fun checkEditor(): RestoreNotification? { fun restoreNotification(file: VirtualFile) = RestoreNotification(LearnBundle.message("learn.restore.notification.wrong.editor"), LearnBundle.message("learn.restore.get.back.link.text")) { invokeLater { FileEditorManager.getInstance(project).openTextEditor(OpenFileDescriptor(project, file), true) } } val selectedTextEditor = FileEditorManager.getInstance(project).selectedTextEditor ?: return null if (lessonExecutor.lesson.lessonType.isSingleEditor) { if (selectedTextEditor != lessonExecutor.predefinedEditor) { val file = lessonExecutor.predefinedFile ?: return null return restoreNotification(file) } } else { val file = runtimeContext.previous.file ?: return null val currentFile = FileDocumentManager.getInstance().getFile(selectedTextEditor.document) if (file != currentFile) { return restoreNotification(file) } } return null } override fun showWarning(text: String, restoreTaskWhenResolved: Boolean, warningRequired: TaskRuntimeContext.() -> Boolean) { restoreState(taskId, delayMillis = defaultRestoreDelay) { val notificationRequired: TaskRuntimeContext.() -> RestoreNotification? = { if (warningRequired()) RestoreNotification(text) {} else null } val warningResolved = [email protected](needToLog = !restoreTaskWhenResolved, notificationRequired) { LessonManager.instance.setWarningNotification(it) } warningResolved && restoreTaskWhenResolved } } /** * Returns true if already shown notification has been cleared */ private fun checkAndShowNotificationIfNeeded(needToLog: Boolean, notificationRequired: TaskRuntimeContext.() -> RestoreNotification?, setNotification: (RestoreNotification) -> Unit): Boolean { val file = lessonExecutor.virtualFile val proposal = checkEditor() ?: notificationRequired(runtimeContext) if (proposal == null) { if (LessonManager.instance.shownRestoreNotification != null) { LessonManager.instance.clearRestoreMessage() return true } } else { if (proposal.message != LessonManager.instance.shownRestoreNotification?.message) { EditorNotifications.getInstance(runtimeContext.project).updateNotifications(file) setNotification(proposal) if(needToLog) { StatisticBase.logRestorePerformed(lessonExecutor.lesson, lessonExecutor.currentTaskIndex) } } } return false } override fun text(@Language("HTML") text: String, useBalloon: LearningBalloonConfig?) { if (useBalloon == null || useBalloon.duplicateMessage) lessonExecutor.text(text) if (useBalloon != null) { val ui = useBalloon.highlightingComponent ?: runtimeContext.previous.ui as? JComponent ?: return LessonExecutorUtil.showBalloonMessage(text, ui, useBalloon, runtimeContext.actionsRecorder, lessonExecutor.project) } } override fun type(text: String) = before { invokeLater(ModalityState.current()) { WriteCommandAction.runWriteCommandAction(project) { val startOffset = editor.caretModel.offset editor.document.insertString(startOffset, text) editor.caretModel.moveToOffset(startOffset + text.length) } } } override fun runtimeText(callback: RuntimeTextContext.() -> String?) { val runtimeTextContext = RuntimeTextContext(runtimeContext) val text = callback(runtimeTextContext) if (text != null) { lessonExecutor.text(text, runtimeTextContext.removeAfterDone) } } override fun trigger(actionId: String) { addStep(recorder.futureAction(actionId)) } override fun trigger(checkId: (String) -> Boolean) { addStep(recorder.futureAction(checkId)) } override fun triggerStart(actionId: String, checkState: TaskRuntimeContext.() -> Boolean) { addStep(recorder.futureActionOnStart(actionId) { checkState(runtimeContext) }) } override fun triggers(vararg actionIds: String) { addStep(recorder.futureListActions(actionIds.toList())) } override fun <T : Any?> trigger(actionId: String, calculateState: TaskRuntimeContext.() -> T, checkState: TaskRuntimeContext.(T, T) -> Boolean) { // Some checks are needed to be performed in EDT thread // For example, selection information could not be got (for some magic reason) from another thread // Also we need to commit document fun calculateAction() = WriteAction.computeAndWait<T, RuntimeException> { PsiDocumentManager.getInstance(runtimeContext.project).commitDocument(runtimeContext.editor.document) calculateState(runtimeContext) } var state: T? = null addStep(recorder.futureActionAndCheckAround(actionId, { state = calculateAction()}) { state?.let { checkState(runtimeContext, it, calculateAction()) } ?: false }) } override fun stateCheck(checkState: TaskRuntimeContext.() -> Boolean): CompletableFuture<Boolean> { val future = recorder.futureCheck { checkState(runtimeContext) } addStep(future) return future } override fun <T : Any> stateRequired(requiredState: TaskRuntimeContext.() -> T?): Future<T> { val result = CompletableFuture<T>() val future = recorder.futureCheck { val state = requiredState(runtimeContext) if (state != null) { result.complete(state) true } else { false } } addStep(future) return result } override fun addFutureStep(p: DoneStepContext.() -> Unit) { val future: CompletableFuture<Boolean> = CompletableFuture() addStep(future) p.invoke(DoneStepContext(future, runtimeContext)) } override fun addStep(step: CompletableFuture<Boolean>) { steps.add(step) } override fun test(waitEditorToBeReady: Boolean, action: TaskTestContext.() -> Unit) { testActions.add(Runnable { DumbService.getInstance(runtimeContext.project).waitForSmartMode() // This wait implementation is quite ugly, but it works and it is needed in the test mode only. So should be ok for now. if (waitEditorToBeReady) { val psiFile = invokeAndWaitIfNeeded { PsiDocumentManager.getInstance(project).getPsiFile(runtimeContext.editor.document) } ?: return@Runnable var t = 0 val step = 100 while (!runReadAction { DaemonCodeAnalyzerEx.getInstanceEx(project).isErrorAnalyzingFinished(psiFile) }) { Thread.sleep(step.toLong()) t += step if (t > 3000) return@Runnable } } TaskTestContext(runtimeContext).action() }) } @Suppress("OverridingDeprecatedMember") override fun triggerByUiComponentAndHighlight(findAndHighlight: TaskRuntimeContext.() -> (() -> Component)) { val step = CompletableFuture<Boolean>() ApplicationManager.getApplication().executeOnPooledThread { while (true) { if (lessonExecutor.hasBeenStopped) { step.complete(false) break } try { val highlightFunction = findAndHighlight(runtimeContext) invokeLater(ModalityState.any()) { lessonExecutor.foundComponent = highlightFunction() lessonExecutor.rehighlightComponent = highlightFunction step.complete(true) } } catch (e: WaitTimedOutError) { continue } catch (e: ComponentLookupException) { continue } break } } steps.add(step) } }
apache-2.0
411f54bee03806751653719e120fc995
38.701107
149
0.69195
5.050704
false
false
false
false
JuliusKunze/kotlin-native
backend.native/tests/external/codegen/box/mangling/internalOverrideSuperCall.kt
5
361
open class A { internal open val field = "F" internal open fun test(): String = "A" } class Z : A() { override fun test(): String = super.test() override val field = super.field } fun box() : String { val z = Z().test() if (z != "A") return "fail 1: $z" val f = Z().field if (f != "F") return "fail 2: $f" return "OK" }
apache-2.0
6f5a59ceacbce5dfccf6e6dd4a001c9c
16.238095
46
0.529086
3.08547
false
true
false
false
JuliusKunze/kotlin-native
backend.native/tests/external/codegen/box/constructorCall/continueInConstructorArguments.kt
1
704
// TARGET_BACKEND: JVM // WITH_RUNTIME // FILE: test.kt fun box(): String { var count = 0 while (true) { count++ if (count > 1) break Foo( logged("i", if (count == 1) 1 else continue), logged("j", 2) ) } val result = log.toString() if (result != "<clinit>ij<init>") return "Fail: '$result'" return "OK" } // FILE: util.kt val log = StringBuilder() fun <T> logged(msg: String, value: T): T { log.append(msg) return value } // FILE: Foo.kt class Foo(i: Int, j: Int) { init { log.append("<init>") } companion object { init { log.append("<clinit>") } } }
apache-2.0
31604e3893758e7e7a440e2daefac29d
16.625
62
0.485795
3.417476
false
false
false
false
Dmedina88/SSB
generator-ssb/generators/templates/template-normal/app/src/main/kotlin/com/grayherring/temp/base/ui/BaseFragment.kt
1
2461
package <%= appPackage %>.base.ui; import android.arch.lifecycle.LifecycleFragment import android.arch.lifecycle.LifecycleRegistryOwner import android.arch.lifecycle.ViewModelProviders import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import butterknife.ButterKnife import butterknife.Unbinder import <%= appPackage %>.base.util.plusAssign import <%= appPackage %>.di.Injectable import <%= appPackage %>.viewmodel.ViewModelFactory import io.reactivex.disposables.CompositeDisposable import javax.inject.Inject abstract class BaseFragment<V : BaseState, T : BaseViewModel<V>> : LifecycleFragment(), LifecycleRegistryOwner, Injectable { @Inject lateinit var viewModelFactory: ViewModelFactory protected lateinit var viewModel: T protected val disposable = CompositeDisposable() lateinit private var unbinder: Unbinder override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? { val v = inflater!!.inflate(viewLayout(), container, false) unbinder = ButterKnife.bind(this,v) return v } override fun onViewCreated(view: View?, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) //if we are going to bind butterKnife do it here initViewModel() } override fun onDestroyView() { unbinder.unbind() disposable.clear() super.onDestroyView() } //todo this code maybe the same in the fragment and activity maybe abstract? /** * setup for view model and stream */ fun initViewModel() { viewModel = ViewModelProviders.of(activity, viewModelFactory).get(viewModelClass()) viewModel.init() initView(viewModel.lastState) disposable += viewModel.observeState { bindView(it) } setUpEventStream() } /** * if initializing view if you have to */ open fun initView(state: V) {} /** * class needed to get the viewModel */ abstract internal fun viewModelClass(): Class<T> /** * layout id for view */ abstract internal fun viewLayout(): Int /** * hook for handling view updates */ abstract internal fun bindView(state: V) /** * put code that creates events for into the even stream here remember to add to [disposable] */ abstract fun setUpEventStream() override fun onDestroy() { disposable.clear() super.onDestroy() } }
apache-2.0
c9715a57d63d07ac0d50675c6b7d7172
27.616279
124
0.716375
4.834971
false
false
false
false
smmribeiro/intellij-community
platform/built-in-server/src/org/jetbrains/builtInWebServer/DefaultWebServerPathHandler.kt
4
6419
// 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.builtInWebServer import com.intellij.openapi.diagnostic.runAndLogException import com.intellij.openapi.extensions.ExtensionPointName import com.intellij.openapi.project.Project import com.intellij.openapi.util.io.FileUtilRt import com.intellij.openapi.util.io.endsWithName import com.intellij.openapi.util.text.StringUtil import com.intellij.openapi.vfs.VFileProperty import com.intellij.openapi.vfs.VirtualFile import com.intellij.util.PathUtilRt import com.intellij.util.io.* import io.netty.channel.Channel import io.netty.channel.ChannelHandlerContext import io.netty.handler.codec.http.FullHttpRequest import io.netty.handler.codec.http.HttpRequest import io.netty.handler.codec.http.HttpResponseStatus import org.jetbrains.ide.orInSafeMode import org.jetbrains.io.send import java.nio.file.Path import java.nio.file.Paths import java.util.regex.Pattern val chromeVersionFromUserAgent: Pattern = Pattern.compile(" Chrome/([\\d.]+) ") private val WEB_SERVER_FILE_HANDLER_EP_NAME = ExtensionPointName<WebServerFileHandler>("org.jetbrains.webServerFileHandler") private class DefaultWebServerPathHandler : WebServerPathHandler() { override fun process(path: String, project: Project, request: FullHttpRequest, context: ChannelHandlerContext, projectName: String, decodedRawPath: String, isCustomHost: Boolean): Boolean { val channel = context.channel() val isSignedRequest = request.isSignedRequest() val extraHeaders = validateToken(request, channel, isSignedRequest) ?: return true val pathToFileManager = WebServerPathToFileManager.getInstance(project) var pathInfo = pathToFileManager.pathToInfoCache.getIfPresent(path) if (pathInfo == null || !pathInfo.isValid) { pathInfo = pathToFileManager.doFindByRelativePath(path, defaultPathQuery) if (pathInfo == null) { if (FavIconHttpRequestHandler.sendDefaultFavIcon(decodedRawPath, request, context)) { return true } HttpResponseStatus.NOT_FOUND.send(channel, request, extraHeaders = extraHeaders) return true } pathToFileManager.pathToInfoCache.put(path, pathInfo) } var indexUsed = false if (pathInfo.isDirectory()) { var indexVirtualFile: VirtualFile? = null var indexFile: Path? = null if (pathInfo.file == null) { indexFile = findIndexFile(pathInfo.ioFile!!) } else { indexVirtualFile = findIndexFile(pathInfo.file!!) } if (indexFile == null && indexVirtualFile == null) { HttpResponseStatus.NOT_FOUND.send(channel, request, extraHeaders = extraHeaders) return true } // we must redirect only after index file check to not expose directory status if (!endsWithSlash(decodedRawPath)) { redirectToDirectory(request, channel, if (isCustomHost) path else "$projectName/$path", extraHeaders) return true } indexUsed = true pathInfo = PathInfo(indexFile, indexVirtualFile, pathInfo.root, pathInfo.moduleName, pathInfo.isLibrary) pathToFileManager.pathToInfoCache.put(path, pathInfo) } val userAgent = request.userAgent if (!isSignedRequest && userAgent != null && request.isRegularBrowser() && request.origin == null && request.referrer == null) { val matcher = chromeVersionFromUserAgent.matcher(userAgent) if (matcher.find() && StringUtil.compareVersionNumbers(matcher.group(1), "51") < 0 && !canBeAccessedDirectly(pathInfo.name)) { HttpResponseStatus.FORBIDDEN.orInSafeMode(HttpResponseStatus.NOT_FOUND).send(channel, request) return true } } if (!indexUsed && !endsWithName(path, pathInfo.name)) { if (endsWithSlash(decodedRawPath)) { indexUsed = true } else { // FallbackResource feature in action, /login requested, /index.php retrieved, we must not redirect /login to /login/ val parentPath = PathUtilRt.getParentPath(pathInfo.path).takeIf { it.isNotEmpty() } if (parentPath != null && endsWithName(path, PathUtilRt.getFileName(parentPath))) { redirectToDirectory(request, channel, if (isCustomHost) path else "$projectName/$path", extraHeaders) return true } } } if (!checkAccess(pathInfo, channel, request)) { return true } val canonicalPath = if (indexUsed) "$path/${pathInfo.name}" else path for (fileHandler in WEB_SERVER_FILE_HANDLER_EP_NAME.extensionList) { LOG.runAndLogException { if (fileHandler.process(pathInfo, canonicalPath, project, request, channel, if (isCustomHost) null else projectName, extraHeaders)) { return true } } } // we registered as a last handler, so, we should just return 404 and send extra headers HttpResponseStatus.NOT_FOUND.send(channel, request, extraHeaders = extraHeaders) return true } } private fun checkAccess(pathInfo: PathInfo, channel: Channel, request: HttpRequest): Boolean { if (pathInfo.ioFile != null || pathInfo.file!!.isInLocalFileSystem) { val file = pathInfo.ioFile ?: Paths.get(pathInfo.file!!.path) if (file.isDirectory()) { HttpResponseStatus.FORBIDDEN.orInSafeMode(HttpResponseStatus.NOT_FOUND).send(channel, request) return false } else if (!hasAccess(file)) { // we check only file, but all directories in the path because of https://youtrack.jetbrains.com/issue/WEB-21594 HttpResponseStatus.FORBIDDEN.orInSafeMode(HttpResponseStatus.NOT_FOUND).send(channel, request) return false } } else if (pathInfo.file!!.`is`(VFileProperty.HIDDEN)) { HttpResponseStatus.FORBIDDEN.orInSafeMode(HttpResponseStatus.NOT_FOUND).send(channel, request) return false } return true } private fun canBeAccessedDirectly(path: String): Boolean { for (fileHandler in WEB_SERVER_FILE_HANDLER_EP_NAME.extensionList) { for (ext in fileHandler.pageFileExtensions) { if (FileUtilRt.extensionEquals(path, ext)) { return true } } } return false } private fun endsWithSlash(path: String): Boolean = path.getOrNull(path.length - 1) == '/'
apache-2.0
99d1a4e3a6b75cf3e2032783963803d3
39.89172
158
0.706808
4.654822
false
false
false
false
smmribeiro/intellij-community
plugins/github/src/org/jetbrains/plugins/github/pullrequest/ui/timeline/GHPRTimelineMergedStateEvents.kt
12
1224
// 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.github.pullrequest.ui.timeline import org.jetbrains.plugins.github.api.data.pullrequest.GHPullRequestState import org.jetbrains.plugins.github.api.data.pullrequest.timeline.GHPRTimelineEvent class GHPRTimelineMergedStateEvents(initialState: GHPRTimelineEvent.State) : GHPRTimelineMergedEvents<GHPRTimelineEvent.State>(), GHPRTimelineEvent.State { private val inferredOriginalState: GHPullRequestState = when (initialState.newState) { GHPullRequestState.CLOSED -> GHPullRequestState.OPEN GHPullRequestState.MERGED -> GHPullRequestState.OPEN GHPullRequestState.OPEN -> GHPullRequestState.CLOSED } init { add(initialState) } override var newState: GHPullRequestState = initialState.newState private set var lastStateEvent = initialState private set override fun addNonMergedEvent(event: GHPRTimelineEvent.State) { if (newState != GHPullRequestState.MERGED) { newState = event.newState lastStateEvent = event } } override fun hasAnyChanges(): Boolean = newState != inferredOriginalState }
apache-2.0
631aec5791b3fb98c60eff277643bf7a
37.28125
155
0.786765
5.057851
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/move/moveDeclarations/ExtractDeclarationFromCurrentFileIntention.kt
4
7107
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.refactoring.move.moveDeclarations import com.intellij.codeInsight.actions.OptimizeImportsProcessor import com.intellij.codeInsight.intention.LowPriorityAction import com.intellij.codeInsight.navigation.NavigationUtil import com.intellij.openapi.editor.Editor import com.intellij.openapi.fileEditor.FileEditorManager import com.intellij.openapi.project.Project import com.intellij.openapi.util.TextRange import com.intellij.psi.PsiDirectory import com.intellij.psi.PsiFile import com.intellij.refactoring.RefactoringBundle import com.intellij.refactoring.move.MoveCallback import com.intellij.refactoring.util.CommonRefactoringUtil import kotlinx.coroutines.runBlocking import kotlinx.coroutines.withTimeoutOrNull import org.jetbrains.kotlin.descriptors.Modality import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.idea.caches.resolve.resolveToDescriptorIfAny import org.jetbrains.kotlin.idea.core.moveCaret import org.jetbrains.kotlin.idea.intentions.SelfTargetingRangeIntention import org.jetbrains.kotlin.idea.refactoring.createKotlinFile import org.jetbrains.kotlin.idea.refactoring.move.moveDeclarations.ui.MoveKotlinTopLevelDeclarationsDialog import org.jetbrains.kotlin.idea.refactoring.showWithTransaction import org.jetbrains.kotlin.idea.util.application.invokeLater import org.jetbrains.kotlin.idea.util.application.isUnitTestMode import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.name.FqName import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.endOffset import org.jetbrains.kotlin.psi.psiUtil.isAncestor import org.jetbrains.kotlin.psi.psiUtil.startOffset import org.jetbrains.kotlin.resolve.descriptorUtil.getSuperClassNotAny import org.jetbrains.kotlin.resolve.source.getPsi private const val TIMEOUT_FOR_IMPORT_OPTIMIZING_MS: Long = 700L class ExtractDeclarationFromCurrentFileIntention : SelfTargetingRangeIntention<KtClassOrObject>( KtClassOrObject::class.java, KotlinBundle.lazyMessage("intention.extract.declarations.from.file.text") ), LowPriorityAction { private fun KtClassOrObject.tryGetExtraClassesToMove(): List<KtNamedDeclaration>? { val descriptor = resolveToDescriptorIfAny() ?: return null if (descriptor.getSuperClassNotAny()?.modality == Modality.SEALED) return null return descriptor.sealedSubclasses .mapNotNull { it.source.getPsi() as? KtNamedDeclaration } .filterNot { isAncestor(it) } } override fun applicabilityRange(element: KtClassOrObject): TextRange? { element.name ?: return null if (element.parent !is KtFile) return null if (element.hasModifier(KtTokens.PRIVATE_KEYWORD)) return null if (element.containingKtFile.run { declarations.size == 1 || containingDirectory === null }) return null val extraClassesToMove = element.tryGetExtraClassesToMove() ?: return null val startOffset = when (element) { is KtClass -> element.startOffset is KtObjectDeclaration -> element.getObjectKeyword()?.startOffset else -> return null } ?: return null val endOffset = element.nameIdentifier?.endOffset ?: return null setTextGetter( KotlinBundle.lazyMessage( "intention.extract.declarations.from.file.text.details", element.name.toString(), extraClassesToMove.size ) ) return TextRange(startOffset, endOffset) } override fun startInWriteAction() = false override fun applyTo(element: KtClassOrObject, editor: Editor?) { requireNotNull(editor) { "This intention requires an editor" } val file = element.containingKtFile val project = file.project val originalOffset = editor.caretModel.offset - element.startOffset val directory = file.containingDirectory ?: return val packageName = file.packageFqName val targetFileName = "${element.name}.kt" val targetFile = directory.findFile(targetFileName) if (targetFile !== null) { if (isUnitTestMode()) { throw CommonRefactoringUtil.RefactoringErrorHintException(RefactoringBundle.message("file.already.exist", targetFileName)) } // If automatic move is not possible, fall back to full-fledged Move Declarations refactoring runFullFledgedMoveRefactoring(project, element, packageName, directory, targetFile, file) return } val moveTarget = KotlinMoveTargetForDeferredFile(packageName, directory.virtualFile) { createKotlinFile(targetFileName, directory, packageName.asString()) } val moveSource = element.tryGetExtraClassesToMove() ?.let { additionalElements -> MoveSource(additionalElements.toMutableList().also { it.add(0, element) }) } ?: MoveSource(element) val moveCallBack = MoveCallback { val newFile = directory.findFile(targetFileName) as KtFile val newDeclaration = newFile.declarations.first() NavigationUtil.activateFileWithPsiElement(newFile) FileEditorManager.getInstance(project).selectedTextEditor?.moveCaret(newDeclaration.startOffset + originalOffset) runBlocking { withTimeoutOrNull(TIMEOUT_FOR_IMPORT_OPTIMIZING_MS) { OptimizeImportsProcessor(project, file).run() } } } val descriptor = MoveDeclarationsDescriptor( project, moveSource, moveTarget, MoveDeclarationsDelegate.TopLevel, searchInCommentsAndStrings = false, searchInNonCode = false, moveCallback = moveCallBack ) MoveKotlinDeclarationsProcessor(descriptor).run() } private fun runFullFledgedMoveRefactoring( project: Project, element: KtClassOrObject, packageName: FqName, directory: PsiDirectory, targetFile: PsiFile?, file: KtFile ) { invokeLater { val callBack = MoveCallback { runBlocking { withTimeoutOrNull(TIMEOUT_FOR_IMPORT_OPTIMIZING_MS) { OptimizeImportsProcessor(project, file).run() } } } MoveKotlinTopLevelDeclarationsDialog( project, setOf(element), packageName.asString(), directory, targetFile as? KtFile, /* freezeTargets */ false, /* moveToPackage = */ true, /* searchInComments = */ true, /* searchForTextOccurrences = */ true, /* deleteEmptySourceFiles = */ true, /* moveMppDeclarations = */ false, callBack ).showWithTransaction() } } }
apache-2.0
926d7b61c98dfe79834b5afdafd3378a
41.819277
158
0.694245
5.408676
false
false
false
false
kickstarter/android-oss
app/src/main/java/com/kickstarter/models/SurveyResponse.kt
1
3476
package com.kickstarter.models import android.os.Parcelable import kotlinx.parcelize.Parcelize import org.joda.time.DateTime @Parcelize class SurveyResponse private constructor( private val answeredAt: DateTime?, private val id: Long, private val project: Project?, private val urls: Urls? ) : Parcelable { fun answeredAt() = this.answeredAt fun id() = this.id fun project() = this.project fun urls() = this.urls @Parcelize data class Builder( private var answeredAt: DateTime? = null, private var id: Long = 0L, private var project: Project? = null, private var urls: Urls? = null ) : Parcelable { fun answeredAt(answeredAt: DateTime?) = apply { answeredAt?.let { this.answeredAt = it } } fun id(id: Long) = apply { this.id = id ?: 0L } fun project(project: Project?) = apply { this.project = project } fun urls(urls: Urls?) = apply { urls?.let { this.urls = it } } fun build() = SurveyResponse( answeredAt = this.answeredAt, id = id, project = project, urls = this.urls ) } @Parcelize class Urls private constructor( private val web: Web ) : Parcelable { fun web() = this.web @Parcelize data class Builder( private var web: Web = Web.builder().build() ) : Parcelable { fun web(web: Web?) = apply { this.web = web ?: Web.builder().build() } fun build() = Urls( web = web ) } fun toBuilder() = Builder( web = web, ) companion object { @JvmStatic fun builder() = Builder() } override fun equals(obj: Any?): Boolean { var equals = super.equals(obj) if (obj is Urls) { equals = web() == obj.web() } return equals } @Parcelize class Web private constructor( private val survey: String? ) : Parcelable { fun survey() = this.survey @Parcelize data class Builder( private var survey: String? = null ) : Parcelable { fun survey(survey: String?) = apply { this.survey = survey } fun build() = Web( survey = survey ) } fun toBuilder() = Builder( survey = survey ) companion object { @JvmStatic fun builder() = Builder() } override fun equals(obj: Any?): Boolean { var equals = super.equals(obj) if (obj is Web) { equals = survey() == obj.survey() } return equals } } } fun toBuilder() = Builder( answeredAt = answeredAt, id = id, project = project, urls = urls ) override fun equals(obj: Any?): Boolean { var equals = super.equals(obj) if (obj is SurveyResponse) { equals = answeredAt() == obj.answeredAt() && id() == obj.id() && project() == obj.project() && urls() == obj.urls() } return equals } companion object { @JvmStatic fun builder() = Builder() } }
apache-2.0
558fcdb1f3b9a431e5618afa4cec1ea1
25.534351
98
0.490219
4.697297
false
false
false
false
mdaniel/intellij-community
platform/workspaceModel/jps/tests/testSrc/com/intellij/workspaceModel/ide/ModuleBridgesTest.kt
1
35921
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.workspaceModel.ide import com.intellij.ProjectTopics.PROJECT_ROOTS import com.intellij.configurationStore.saveSettings import com.intellij.openapi.application.* import com.intellij.openapi.command.WriteCommandAction import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.module.* import com.intellij.openapi.project.Project import com.intellij.openapi.project.rootManager import com.intellij.openapi.roots.* import com.intellij.openapi.roots.impl.OrderEntryUtil import com.intellij.openapi.roots.libraries.LibraryTablesRegistrar import com.intellij.openapi.util.JDOMUtil import com.intellij.openapi.util.io.FileUtil import com.intellij.openapi.vfs.VfsUtilCore import com.intellij.testFramework.* import com.intellij.testFramework.UsefulTestCase.assertEmpty import com.intellij.testFramework.UsefulTestCase.assertSameElements import com.intellij.util.io.write import com.intellij.util.ui.UIUtil import com.intellij.workspaceModel.ide.impl.JpsEntitySourceFactory import com.intellij.workspaceModel.ide.impl.WorkspaceModelInitialTestContent import com.intellij.workspaceModel.ide.impl.jps.serialization.toConfigLocation import com.intellij.workspaceModel.ide.impl.legacyBridge.module.ModuleManagerBridgeImpl import com.intellij.workspaceModel.ide.impl.legacyBridge.module.ModuleManagerBridgeImpl.Companion.findModuleEntity import com.intellij.workspaceModel.ide.impl.legacyBridge.module.roots.ModuleRootComponentBridge import com.intellij.workspaceModel.ide.impl.toVirtualFileUrl import com.intellij.workspaceModel.ide.legacyBridge.ModuleBridge import com.intellij.workspaceModel.storage.EntityStorageSnapshot import com.intellij.workspaceModel.storage.MutableEntityStorage import com.intellij.workspaceModel.storage.bridgeEntities.addContentRootEntity import com.intellij.workspaceModel.storage.bridgeEntities.addLibraryEntity import com.intellij.workspaceModel.storage.bridgeEntities.addModuleEntity import com.intellij.workspaceModel.storage.bridgeEntities.addSourceRootEntity import com.intellij.workspaceModel.storage.bridgeEntities.api.* import com.intellij.workspaceModel.storage.impl.url.toVirtualFileUrl import com.intellij.workspaceModel.storage.toBuilder import com.intellij.workspaceModel.storage.url.VirtualFileUrlManager import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.runBlocking import kotlinx.coroutines.withContext import org.jetbrains.jps.model.java.LanguageLevel import org.jetbrains.jps.model.module.UnknownSourceRootType import org.jetbrains.jps.model.module.UnknownSourceRootTypeProperties import org.jetbrains.jps.model.serialization.JDomSerializationUtil import org.jetbrains.jps.model.serialization.library.JpsLibraryTableSerializer import org.junit.Assert.* import org.junit.Before import org.junit.Rule import org.junit.Test import java.io.File import java.io.PrintStream import java.nio.file.Files import kotlin.random.Random class ModuleBridgesTest { @Rule @JvmField var application = ApplicationRule() @Rule @JvmField var temporaryDirectoryRule = TemporaryDirectory() @Rule @JvmField var disposableRule = DisposableRule() private lateinit var project: Project private lateinit var virtualFileManager: VirtualFileUrlManager @Before fun prepareProject() { project = createEmptyTestProject(temporaryDirectoryRule, disposableRule) virtualFileManager = VirtualFileUrlManager.getInstance(project) } @Test fun `test that module continues to receive updates after being created in modifiable model`() { WriteCommandAction.runWriteCommandAction(project) { val moduleManager = ModuleManager.getInstance(project) val module = moduleManager.getModifiableModel().let { val m = it.newModule(File(project.basePath, "xxx.iml").path, EmptyModuleType.getInstance().id) as ModuleBridge it.commit() m } assertTrue(moduleManager.modules.contains(module)) assertSame(WorkspaceModel.getInstance(project).entityStorage, module.entityStorage) val contentRootUrl = temporaryDirectoryRule.newPath("contentRoot").toVirtualFileUrl(virtualFileManager) WorkspaceModel.getInstance(project).updateProjectModel { val moduleEntity = it.findModuleEntity(module)!! it.addContentRootEntity(contentRootUrl, emptyList(), emptyList(), moduleEntity) } assertArrayEquals( ModuleRootManager.getInstance(module).contentRootUrls, arrayOf(contentRootUrl.url) ) moduleManager.getModifiableModel().let { it.disposeModule(module) it.commit() } } } @Test fun `test commit module root model in uncommitted module`() = WriteCommandAction.runWriteCommandAction(project) { val moduleManager = ModuleManager.getInstance(project) val modulesModifiableModel = moduleManager.getModifiableModel() try { val m = modulesModifiableModel.newModule(File(project.basePath, "xxx.iml").path, ModuleType.EMPTY.id) as ModuleBridge val rootModel = m.rootManager.modifiableModel val temp = temporaryDirectoryRule.newPath() rootModel.addContentEntry(temp.toVirtualFileUrl(virtualFileManager).url) rootModel.commit() assertArrayEquals(arrayOf(temp.toVirtualFileUrl(virtualFileManager).url), m.rootManager.contentRootUrls) } finally { modulesModifiableModel.dispose() } } @Test fun `test rename module from model`() { val oldModuleName = "oldName" val newModuleName = "newName" val moduleManager = ModuleManager.getInstance(project) val iprFile = File(project.projectFilePath!!) val oldNameFile = File(project.basePath, "$oldModuleName.iml") val newNameFile = File(project.basePath, "$newModuleName.iml") runBlocking { val module = withContext(Dispatchers.EDT) { runWriteAction { val model = moduleManager.getModifiableModel() val module = model.newModule(oldNameFile.path, ModuleType.EMPTY.id) model.commit() module } } saveSettings(project) assertTrue(oldNameFile.exists()) assertTrue(iprFile.readText().contains(oldNameFile.name)) assertEquals(oldModuleName, module.name) withContext(Dispatchers.EDT) { ApplicationManager.getApplication().runWriteAction { val model = moduleManager.getModifiableModel() assertSame(module, model.findModuleByName(oldModuleName)) assertNull(model.getModuleToBeRenamed(oldModuleName)) model.renameModule(module, newModuleName) assertSame(module, model.findModuleByName(oldModuleName)) assertSame(module, model.getModuleToBeRenamed(newModuleName)) assertSame(newModuleName, model.getNewName(module)) model.commit() } } assertNull(moduleManager.findModuleByName(oldModuleName)) assertSame(module, moduleManager.findModuleByName(newModuleName)) assertEquals(newModuleName, module.name) val moduleFilePath = module.moduleFile?.toVirtualFileUrl(virtualFileManager)?.presentableUrl assertNotNull(moduleFilePath) assertEquals(newNameFile, File(moduleFilePath!!)) assertTrue(module.getModuleNioFile().toString().endsWith(newNameFile.name)) saveSettings(project) assertFalse(iprFile.readText().contains(oldNameFile.name)) assertFalse(oldNameFile.exists()) assertTrue(iprFile.readText().contains(newNameFile.name)) assertTrue(newNameFile.exists()) } } @Test fun `test rename module and all dependencies in other modules`() = runBlocking { val checkModuleDependency = { moduleName: String, dependencyModuleName: String -> assertNotNull(WorkspaceModel.getInstance(project).entityStorage.current.entities(ModuleEntity::class.java) .first { it.persistentId.name == moduleName }.dependencies .find { it is ModuleDependencyItem.Exportable.ModuleDependency && it.module.name == dependencyModuleName }) } val antModuleName = "ant" val mavenModuleName = "maven" val gradleModuleName = "gradle" val moduleManager = ModuleManager.getInstance(project) val iprFile = File(project.projectFilePath!!) val antModuleFile = File(project.basePath, "$antModuleName.iml") val mavenModuleFile = File(project.basePath, "$mavenModuleName.iml") val gradleModuleFile = File(project.basePath, "$gradleModuleName.iml") val (antModule, mavenModule) = withContext(Dispatchers.EDT) { runWriteAction { val model = moduleManager.getModifiableModel() val antModule = model.newModule(antModuleFile.path, ModuleType.EMPTY.id) val mavenModule = model.newModule(mavenModuleFile.path, ModuleType.EMPTY.id) model.commit() Pair(antModule, mavenModule) } } ModuleRootModificationUtil.addDependency(mavenModule, antModule) checkModuleDependency(mavenModuleName, antModuleName) saveSettings(project) var fileText = iprFile.readText() assertEquals(2, listOf(antModuleName, mavenModuleName).filter { fileText.contains(it) }.size) assertTrue(antModuleFile.exists()) assertTrue(mavenModuleFile.exists()) assertTrue(mavenModuleFile.readText().contains(antModuleName)) withContext(Dispatchers.EDT) { ApplicationManager.getApplication().runWriteAction { val model = moduleManager.getModifiableModel() model.renameModule(antModule, gradleModuleName) model.commit() } } checkModuleDependency(mavenModuleName, gradleModuleName) saveSettings(project) fileText = iprFile.readText() assertEquals(2, listOf(mavenModuleName, gradleModuleName).filter { fileText.contains(it) }.size) assertFalse(antModuleFile.exists()) assertTrue(gradleModuleFile.exists()) assertTrue(mavenModuleFile.exists()) fileText = mavenModuleFile.readText() assertFalse(fileText.contains(antModuleName)) assertFalse(fileText.contains(antModuleName)) } @Test fun `test remove and add module with the same name`() = WriteCommandAction.runWriteCommandAction(project) { startLog() val moduleManager = ModuleManager.getInstance(project) for (module in moduleManager.modules) { moduleManager.disposeModule(module) } val moduleDirUrl = virtualFileManager.fromPath(project.basePath!!) val projectModel = WorkspaceModel.getInstance(project) projectModel.updateProjectModel { it.addModuleEntity("name", emptyList(), JpsFileEntitySource.FileInDirectory(moduleDirUrl, getJpsProjectConfigLocation(project)!!)) } assertNotNull(moduleManager.findModuleByName("name")) projectModel.updateProjectModel { val moduleEntity = it.entities(ModuleEntity::class.java).single() it.removeEntity(moduleEntity) it.addModuleEntity("name", emptyList(), JpsFileEntitySource.FileInDirectory(moduleDirUrl, getJpsProjectConfigLocation(project)!!)) } assertEquals(1, moduleManager.modules.size) assertNotNull(moduleManager.findModuleByName("name")) val caughtLogs = catchLog() // Trying to assert that a particular warning isn't presented in logs assertFalse("name.iml does not exist" in caughtLogs) } @Test fun `test LibraryEntity is removed after removing module library order entry`() = WriteCommandAction.runWriteCommandAction(project) { val moduleManager = ModuleManager.getInstance(project) val module = moduleManager.getModifiableModel().let { val m = it.newModule(File(project.basePath, "xxx.iml").path, EmptyModuleType.getInstance().id) as ModuleBridge it.commit() m } ModuleRootModificationUtil.addModuleLibrary(module, "xxx-lib", listOf(File(project.basePath, "x.jar").path), emptyList()) val projectModel = WorkspaceModel.getInstance(project) assertEquals( "xxx-lib", projectModel.entityStorage.current.entities(LibraryEntity::class.java).toList().single().name) ModuleRootModificationUtil.updateModel(module) { model -> val orderEntry = model.orderEntries.filterIsInstance<LibraryOrderEntry>().single() model.removeOrderEntry(orderEntry) } assertEmpty(projectModel.entityStorage.current.entities(LibraryEntity::class.java).toList()) } @Test fun `test LibraryEntity is removed after clearing module order entries`() = WriteCommandAction.runWriteCommandAction(project) { val moduleManager = ModuleManager.getInstance(project) val module = moduleManager.getModifiableModel().let { val m = it.newModule(File(project.basePath, "xxx.iml").path, EmptyModuleType.getInstance().id) as ModuleBridge it.commit() m } ModuleRootModificationUtil.addModuleLibrary(module, "xxx-lib", listOf(File(project.basePath, "x.jar").path), emptyList()) val projectModel = WorkspaceModel.getInstance(project) assertEquals( "xxx-lib", projectModel.entityStorage.current.entities(LibraryEntity::class.java).toList().single().name) ModuleRootModificationUtil.updateModel(module) { model -> model.clear() } assertEmpty(projectModel.entityStorage.current.entities(LibraryEntity::class.java).toList()) } @Test fun `test content roots provided`() = WriteCommandAction.runWriteCommandAction(project) { val moduleManager = ModuleManager.getInstance(project) val dir = File(project.basePath, "dir") val moduleDirUrl = virtualFileManager.fromPath(project.basePath!!) val projectModel = WorkspaceModel.getInstance(project) val projectLocation = getJpsProjectConfigLocation(project)!! val virtualFileUrl = dir.toVirtualFileUrl(virtualFileManager) projectModel.updateProjectModel { val moduleEntity = it.addModuleEntity("name", emptyList(), JpsFileEntitySource.FileInDirectory(moduleDirUrl, projectLocation)) val contentRootEntity = it.addContentRootEntity(virtualFileUrl, emptyList(), emptyList(), moduleEntity) it.addSourceRootEntity(contentRootEntity, virtualFileUrl, "", JpsFileEntitySource.FileInDirectory(moduleDirUrl, projectLocation)) } val module = moduleManager.findModuleByName("name") assertNotNull(module) assertArrayEquals( arrayOf(virtualFileUrl.url), ModuleRootManager.getInstance(module!!).contentRootUrls ) val sourceRootUrl = ModuleRootManager.getInstance(module).contentEntries.single() .sourceFolders.single().url assertEquals(virtualFileUrl.url, sourceRootUrl) } @Test fun `test module component serialized into module iml`() = runBlocking { val moduleFile = File(project.basePath, "test.iml") val moduleManager = ModuleManager.getInstance(project) val module = runWriteActionAndWait { moduleManager.newModule (moduleFile.path, ModuleTypeId.JAVA_MODULE) } saveSettings(project) assertNull(JDomSerializationUtil.findComponent(JDOMUtil.load(moduleFile), "XXX")) TestModuleComponent.getInstance(module).testString = "My String" saveSettings(project, forceSavingAllSettings = true) assertEquals( """ <component name="XXX"> <option name="testString" value="My String" /> </component> """.trimIndent(), JDOMUtil.write(JDomSerializationUtil.findComponent(JDOMUtil.load(moduleFile), "XXX")!!) ) } @Test fun `test module extensions`() { TestModuleExtension.commitCalled.set(0) val module = runWriteActionAndWait { ModuleManager.getInstance(project).newModule(File(project.basePath, "test.iml").path, ModuleType.EMPTY.id) } val modifiableModel = ApplicationManager.getApplication().runReadAction<ModifiableRootModel> { ModuleRootManager.getInstance(module).modifiableModel } val moduleExtension = modifiableModel.getModuleExtension(TestModuleExtension::class.java) moduleExtension.languageLevel = LanguageLevel.JDK_1_5 runWriteActionAndWait { modifiableModel.commit() } assertEquals( LanguageLevel.JDK_1_5, ModuleRootManager.getInstance(module).getModuleExtension(TestModuleExtension::class.java).languageLevel ) val modifiableRootModel = ModuleRootManager.getInstance(module).modifiableModel assertEquals(LanguageLevel.JDK_1_5, modifiableRootModel.getModuleExtension(TestModuleExtension::class.java).languageLevel) modifiableRootModel.dispose() assertEquals(1, TestModuleExtension.commitCalled.get()) } @Test fun `test module extension saves correctly if custom options exist`() { val optionValue = "foo" val module = runWriteActionAndWait { ModuleManager.getInstance(project).newModule(File(project.basePath, "test.iml").path, ModuleType.EMPTY.id) } module.setOption(Module.ELEMENT_TYPE, optionValue) val moduleRootManager = ModuleRootManager.getInstance(module) var modifiableModel = moduleRootManager.modifiableModel var moduleExtension = modifiableModel.getModuleExtension(TestModuleExtension::class.java) moduleExtension.languageLevel = LanguageLevel.JDK_1_5 runWriteActionAndWait { modifiableModel.commit() } assertEquals(LanguageLevel.JDK_1_5, moduleRootManager.getModuleExtension(TestModuleExtension::class.java).languageLevel) modifiableModel = moduleRootManager.modifiableModel moduleExtension = modifiableModel.getModuleExtension(TestModuleExtension::class.java) moduleExtension.languageLevel = null runWriteActionAndWait { modifiableModel.commit() } assertEquals(optionValue, module.getOptionValue(Module.ELEMENT_TYPE)) assertNull(moduleRootManager.getModuleExtension(TestModuleExtension::class.java).languageLevel) } @Test fun `test module libraries loaded from cache`() { val builder = MutableEntityStorage.create() val tempDir = temporaryDirectoryRule.newPath() val iprFile = tempDir.resolve("testProject.ipr") val configLocation = toConfigLocation(iprFile, virtualFileManager) val source = JpsFileEntitySource.FileInDirectory(configLocation.baseDirectoryUrl, configLocation) val moduleEntity = builder.addModuleEntity(name = "test", dependencies = emptyList(), source = source) val moduleLibraryEntity = builder.addLibraryEntity( name = "some", tableId = LibraryTableId.ModuleLibraryTableId(moduleEntity.persistentId), roots = listOf(LibraryRoot(tempDir.toVirtualFileUrl(virtualFileManager), LibraryRootTypeId.COMPILED)), excludedRoots = emptyList(), source = source ) builder.modifyEntity(moduleEntity) { dependencies = listOf( ModuleDependencyItem.Exportable.LibraryDependency(moduleLibraryEntity.persistentId, false, ModuleDependencyItem.DependencyScope.COMPILE) ) } WorkspaceModelInitialTestContent.withInitialContent(builder.toSnapshot()) { val project = PlatformTestUtil.loadAndOpenProject(iprFile, disposableRule.disposable) val module = ModuleManager.getInstance(project).findModuleByName("test") val rootManager = ModuleRootManager.getInstance(module!!) val libraries = OrderEntryUtil.getModuleLibraries(rootManager) assertEquals(1, libraries.size) val libraryOrderEntry = rootManager.orderEntries[0] as LibraryOrderEntry assertTrue(libraryOrderEntry.isModuleLevel) assertSame(libraryOrderEntry.library, libraries[0]) assertEquals(JpsLibraryTableSerializer.MODULE_LEVEL, libraryOrderEntry.libraryLevel) assertSameElements(libraryOrderEntry.getUrls(OrderRootType.CLASSES), tempDir.toVirtualFileUrl(virtualFileManager).url) } } @Test fun `test libraries are loaded from cache`() { val builder = MutableEntityStorage.create() val tempDir = temporaryDirectoryRule.newPath() val iprFile = tempDir.resolve("testProject.ipr") val jarUrl = tempDir.resolve("a.jar").toVirtualFileUrl(virtualFileManager) builder.addLibraryEntity( name = "my_lib", tableId = LibraryTableId.ProjectLibraryTableId, roots = listOf(LibraryRoot(jarUrl, LibraryRootTypeId.COMPILED)), excludedRoots = emptyList(), source = JpsEntitySourceFactory.createJpsEntitySourceForProjectLibrary(toConfigLocation(iprFile, virtualFileManager)) ) WorkspaceModelInitialTestContent.withInitialContent(builder.toSnapshot()) { val project = PlatformTestUtil.loadAndOpenProject(iprFile, disposableRule.disposable) val projectLibraryTable = LibraryTablesRegistrar.getInstance().getLibraryTable(project) invokeAndWaitIfNeeded { UIUtil.dispatchAllInvocationEvents() } val library = projectLibraryTable.getLibraryByName("my_lib") assertNotNull(library) assertEquals(JpsLibraryTableSerializer.PROJECT_LEVEL, library!!.table.tableLevel) assertSameElements(library.getUrls(OrderRootType.CLASSES), jarUrl.url) } } @Test fun `test custom source root loading`() { TestCustomRootModelSerializerExtension.registerTestCustomSourceRootType(temporaryDirectoryRule.newPath().toFile(), disposableRule.disposable) val tempDir = temporaryDirectoryRule.newPath() val moduleImlFile = tempDir.resolve("my.iml") Files.createDirectories(moduleImlFile.parent) val url = VfsUtilCore.pathToUrl(moduleImlFile.parent.toString()) moduleImlFile.write(""" <module type="JAVA_MODULE" version="4"> <component name="NewModuleRootManager"> <content url="file://${'$'}MODULE_DIR${'$'}"> <sourceFolder url="file://${'$'}MODULE_DIR${'$'}/root1" type="custom-source-root-type" testString="x y z" /> <sourceFolder url="file://${'$'}MODULE_DIR${'$'}/root2" type="custom-source-root-type" /> </content> </component> </module> """.trimIndent()) WriteCommandAction.runWriteCommandAction(project) { val moduleManager = ModuleManager.getInstance(project) val module = moduleManager.loadModule(moduleImlFile) val contentEntry = ModuleRootManager.getInstance(module).contentEntries.single() assertEquals(2, contentEntry.sourceFolders.size) assertTrue(contentEntry.sourceFolders[0].rootType is TestCustomSourceRootType) assertEquals("x y z", (contentEntry.sourceFolders[0].jpsElement.properties as TestCustomSourceRootProperties).testString) assertTrue(contentEntry.sourceFolders[1].rootType is TestCustomSourceRootType) assertEquals("default properties", (contentEntry.sourceFolders[1].jpsElement.properties as TestCustomSourceRootProperties).testString) val customRoots = WorkspaceModel.getInstance(project).entityStorage.current.entities(CustomSourceRootPropertiesEntity::class.java) .toList() .sortedBy { it.sourceRoot.url.url } assertEquals(1, customRoots.size) assertEquals("<sourceFolder testString=\"x y z\" />", customRoots[0].propertiesXmlTag) assertEquals("$url/root1", customRoots[0].sourceRoot.url.url) assertEquals(TestCustomSourceRootType.TYPE_ID, customRoots[0].sourceRoot.rootType) } } @Test fun `test unknown custom source root type`() { val tempDir = temporaryDirectoryRule.newPath() val moduleImlFile = tempDir.resolve("my.iml") Files.createDirectories(moduleImlFile.parent) moduleImlFile.write(""" <module type="JAVA_MODULE" version="4"> <component name="NewModuleRootManager"> <content url="file://${'$'}MODULE_DIR${'$'}"> <sourceFolder url="file://${'$'}MODULE_DIR${'$'}/root1" type="unsupported-custom-source-root-type" param1="x y z" /> </content> </component> </module> """.trimIndent()) WriteCommandAction.runWriteCommandAction(project) { val moduleManager = ModuleManager.getInstance(project) val module = moduleManager.loadModule(moduleImlFile) val contentEntry = ModuleRootManager.getInstance(module).contentEntries.single() val sourceFolder = contentEntry.sourceFolders.single() assertSame(UnknownSourceRootType.getInstance("unsupported-custom-source-root-type"), sourceFolder.rootType) assertTrue(sourceFolder.jpsElement.properties is UnknownSourceRootTypeProperties<*>) val customRoot = WorkspaceModel.getInstance(project).entityStorage.current.entities(CustomSourceRootPropertiesEntity::class.java) .toList().single() assertEquals("<sourceFolder param1=\"x y z\" />", customRoot.propertiesXmlTag) assertEquals("unsupported-custom-source-root-type", customRoot.sourceRoot.rootType) } } @Test fun `test custom source root saving`() = runBlocking { val tempDir = temporaryDirectoryRule.newPath().toFile() TestCustomRootModelSerializerExtension.registerTestCustomSourceRootType(temporaryDirectoryRule.newPath().toFile(), disposableRule.disposable) val moduleImlFile = File(tempDir, "my.iml") Files.createDirectories(moduleImlFile.parentFile.toPath()) WriteCommandAction.runWriteCommandAction(project) { val moduleManager = ModuleManager.getInstance(project) val module = moduleManager.newModule(moduleImlFile.path, ModuleTypeId.WEB_MODULE) ModuleRootModificationUtil.updateModel(module) { model -> val url = VfsUtilCore.pathToUrl(FileUtil.toSystemIndependentName(tempDir.path)) val contentEntry = model.addContentEntry(url) contentEntry.addSourceFolder("$url/root1", TestCustomSourceRootType.INSTANCE) contentEntry.addSourceFolder("$url/root2", TestCustomSourceRootType.INSTANCE, TestCustomSourceRootProperties("")) contentEntry.addSourceFolder("$url/root3", TestCustomSourceRootType.INSTANCE, TestCustomSourceRootProperties("some data")) contentEntry.addSourceFolder("$url/root4", TestCustomSourceRootType.INSTANCE, TestCustomSourceRootProperties(null)) } } saveSettings(project) val rootManagerComponent = JDomSerializationUtil.findComponent(JDOMUtil.load(moduleImlFile), "NewModuleRootManager")!! assertEquals(""" <content url="file://${'$'}MODULE_DIR${'$'}"> <sourceFolder url="file://${'$'}MODULE_DIR${'$'}/root1" type="custom-source-root-type" testString="default properties" /> <sourceFolder url="file://${'$'}MODULE_DIR${'$'}/root2" type="custom-source-root-type" testString="" /> <sourceFolder url="file://${'$'}MODULE_DIR${'$'}/root3" type="custom-source-root-type" testString="some data" /> <sourceFolder url="file://${'$'}MODULE_DIR${'$'}/root4" type="custom-source-root-type" /> </content> """.trimIndent(), JDOMUtil.write(rootManagerComponent.getChild("content")!!)) } @Test fun `test remove module removes source roots`() = runBlocking { startLog() val moduleName = "build" val antLibraryFolder = "ant-lib" val moduleFile = File(project.basePath, "$moduleName.iml") val module = withContext(Dispatchers.EDT) { runWriteAction { val module = ModuleManager.getInstance(project).getModifiableModel().let { moduleModel -> val module = moduleModel.newModule(moduleFile.path, EmptyModuleType.getInstance().id) as ModuleBridge moduleModel.commit() module } ModuleRootModificationUtil.updateModel(module) { model -> val tempDir = temporaryDirectoryRule.newPath().toFile() val url = VfsUtilCore.pathToUrl(FileUtil.toSystemIndependentName(tempDir.path)) val contentEntry = model.addContentEntry(url) contentEntry.addSourceFolder("$url/$antLibraryFolder", false) } module } } saveSettings(project) withContext(Dispatchers.EDT) { assertTrue(moduleFile.readText().contains(antLibraryFolder)) val entityStore = WorkspaceModel.getInstance(project).entityStorage assertEquals(1, entityStore.current.entities(ContentRootEntity::class.java).count()) assertEquals(1, entityStore.current.entities(JavaSourceRootEntity::class.java).count()) ApplicationManager.getApplication().runWriteAction { ModuleManager.getInstance(project).disposeModule(module) } assertEmpty(entityStore.current.entities(ContentRootEntity::class.java).toList()) assertEmpty(entityStore.current.entities(JavaSourceRootEntity::class.java).toList()) } val caughtLogs = catchLog() // Trying to assert that a particular warning isn't presented in logs assertFalse("name.iml does not exist" in caughtLogs) } @Test fun `test remove content entity removes related source folders`() = WriteCommandAction.runWriteCommandAction(project) { val moduleName = "build" val antLibraryFolder = "ant-lib" val moduleFile = File(project.basePath, "$moduleName.iml") val module = ModuleManager.getInstance(project).getModifiableModel().let { moduleModel -> val module = moduleModel.newModule(moduleFile.path, EmptyModuleType.getInstance().id) as ModuleBridge moduleModel.commit() module } ModuleRootModificationUtil.updateModel(module) { model -> val tempDir = temporaryDirectoryRule.newPath().toFile() val url = VfsUtilCore.pathToUrl(FileUtil.toSystemIndependentName(tempDir.path)) val contentEntry = model.addContentEntry(url) contentEntry.addSourceFolder("$url/$antLibraryFolder", false) } val entityStore = WorkspaceModel.getInstance(project).entityStorage assertEquals(1, entityStore.current.entities(ContentRootEntity::class.java).count()) assertEquals(1, entityStore.current.entities(SourceRootEntity::class.java).count()) ModuleRootModificationUtil.updateModel(module) { model -> val contentEntries = model.contentEntries assertEquals(1, contentEntries.size) model.removeContentEntry(contentEntries[0]) } assertEmpty(entityStore.current.entities(ContentRootEntity::class.java).toList()) assertEmpty(entityStore.current.entities(SourceRootEntity::class.java).toList()) } @Test fun `test disposed module doesn't appear in rootsChanged`() = WriteCommandAction.runWriteCommandAction(project) { val moduleName = "build" val moduleFile = File(project.basePath, "$moduleName.iml") val module = ModuleManager.getInstance(project).getModifiableModel().let { moduleModel -> val module = moduleModel.newModule(moduleFile.path, EmptyModuleType.getInstance().id) as ModuleBridge moduleModel.commit() module } project.messageBus.connect(disposableRule.disposable).subscribe(PROJECT_ROOTS, object : ModuleRootListener { override fun rootsChanged(event: ModuleRootEvent) { val modules = ModuleManager.getInstance(event.project).modules assertEmpty(modules) } }) ModuleManager.getInstance(project).disposeModule(module) } @Test fun `creating module from modifiable model and removing it`() = WriteCommandAction.runWriteCommandAction(project) { val moduleManager = ModuleManager.getInstance(project) as ModuleManagerBridgeImpl moduleManager.getModifiableModel().let { modifiableModel -> modifiableModel.newModule(File(project.basePath, "xxx.iml").path, EmptyModuleType.getInstance().id) as ModuleBridge modifiableModel.commit() } moduleManager.getModifiableModel(WorkspaceModel.getInstance(project).entityStorage.current.toBuilder()).let { modifiableModel -> val existingModule = modifiableModel.modules.single { it.name == "xxx" } modifiableModel.disposeModule(existingModule) val module = modifiableModel.newModule(File(project.basePath, "xxx.iml").path, EmptyModuleType.getInstance().id) as ModuleBridge // No commit // This is an actual code that was broken // It tests that model listener inside of ModuleBridgeImpl correctly converts an instanse of the storage inside of it WorkspaceModel.getInstance(project).updateProjectModel { val moduleEntity: ModuleEntity = it.entities(ModuleEntity::class.java).single() it.removeEntity(moduleEntity) } assertEquals("xxx", module.name) modifiableModel.commit() } } @Test fun `remove module without removing module library`() = WriteCommandAction.runWriteCommandAction(project) { val moduleManager = ModuleManager.getInstance(project) as ModuleManagerBridgeImpl val module = moduleManager.getModifiableModel().let { modifiableModel -> val module = modifiableModel.newModule(File(project.basePath, "xxx.iml").path, EmptyModuleType.getInstance().id) modifiableModel.commit() module as ModuleBridge } val componentBridge = ModuleRootComponentBridge.getInstance(module) val componentModifiableModel = componentBridge.modifiableModel val modifiableModel = componentModifiableModel.moduleLibraryTable.modifiableModel modifiableModel.createLibrary("myNewLibrary") modifiableModel.commit() componentModifiableModel.commit() val currentStore = WorkspaceModel.getInstance(project).entityStorage.current UsefulTestCase.assertOneElement(currentStore.entities(ModuleEntity::class.java).toList()) UsefulTestCase.assertOneElement(currentStore.entities(LibraryEntity::class.java).toList()) WorkspaceModel.getInstance(project).updateProjectModel { val moduleEntity = it.entities(ModuleEntity::class.java).single() it.removeEntity(moduleEntity) } val updatedStore = WorkspaceModel.getInstance(project).entityStorage.current assertEmpty(updatedStore.entities(ModuleEntity::class.java).toList()) assertEmpty(updatedStore.entities(LibraryEntity::class.java).toList()) } @Test fun `readd module`() = WriteCommandAction.runWriteCommandAction(project) { val moduleManager = ModuleManager.getInstance(project) val module = moduleManager.getModifiableModel().let { modifiableModel -> val module = modifiableModel.newModule(File(project.basePath, "xxx.iml").path, EmptyModuleType.getInstance().id) modifiableModel.commit() module as ModuleBridge } val newModule = moduleManager.getModifiableModel().let { modifiableModel -> modifiableModel.disposeModule(module) val newModule = modifiableModel.newModule(File(project.basePath, "xxx.iml").path, EmptyModuleType.getInstance().id) modifiableModel.commit() newModule } WorkspaceModel.getInstance(project).updateProjectModel { builder -> val entity = builder.resolve(ModuleId("xxx"))!! builder.modifyEntity(entity) { this.name = "yyy" } } assertEquals("yyy", newModule.name) } class OutCatcher(printStream: PrintStream) : PrintStream(printStream) { var catcher = "" override fun println(x: String?) { catcher += "$x\n" } } companion object { val log = logger<ModuleBridgesTest>() var logLine = "" val rand = Random(0) fun startLog() { logLine = "Start logging " + rand.nextInt() log.info(logLine) } fun catchLog(): String { return try { val outCatcher = OutCatcher(System.out) System.setOut(outCatcher) TestLoggerFactory.dumpLogToStdout(logLine) outCatcher.catcher } finally { System.setOut(System.out) } } } } internal fun createEmptyTestProject(temporaryDirectory: TemporaryDirectory, disposableRule: DisposableRule): Project { val projectDir = temporaryDirectory.newPath("project") val project = WorkspaceModelInitialTestContent.withInitialContent(EntityStorageSnapshot.empty()) { PlatformTestUtil.loadAndOpenProject(projectDir.resolve("testProject.ipr"), disposableRule.disposable) } return project }
apache-2.0
2c1dd1bc96c97582e0762af7c0198da2
41.409681
154
0.737591
5.222594
false
true
false
false
siosio/intellij-community
plugins/kotlin/j2k/new/src/org/jetbrains/kotlin/nj2k/conversions/SwitchStatementConversion.kt
1
5654
// 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.conversions import com.intellij.psi.PsiElement import com.intellij.psi.controlFlow.ControlFlowFactory import com.intellij.psi.controlFlow.ControlFlowUtil import com.intellij.psi.controlFlow.LocalsOrMyInstanceFieldsControlFlowPolicy import org.jetbrains.kotlin.nj2k.NewJ2kConverterContext import org.jetbrains.kotlin.nj2k.blockStatement import org.jetbrains.kotlin.nj2k.runExpression import org.jetbrains.kotlin.nj2k.tree.* class SwitchStatementConversion(context: NewJ2kConverterContext) : RecursiveApplicableConversionBase(context) { override fun applyToElement(element: JKTreeElement): JKTreeElement { if (element !is JKJavaSwitchStatement) return recurse(element) element.invalidate() element.cases.forEach { case -> case.statements.forEach { it.detach(case) } if (case is JKJavaLabelSwitchCase) { case.label.detach(case) } } val cases = switchCasesToWhenCases(element.cases).moveElseCaseToTheEnd() val whenStatement = JKKtWhenStatement(element.expression, cases) return recurse(whenStatement) } private fun List<JKKtWhenCase>.moveElseCaseToTheEnd(): List<JKKtWhenCase> = sortedBy { it.labels.any { it is JKKtElseWhenLabel } } private fun switchCasesToWhenCases(cases: List<JKJavaSwitchCase>): List<JKKtWhenCase> = if (cases.isEmpty()) emptyList() else { val statements = cases .takeWhileInclusive { it.statements.fallsThrough() } .flatMap { it.statements } .takeWhileInclusive { it.singleListOrBlockStatements().none { isSwitchBreak(it) } } .mapNotNull { statement -> when { statement is JKBlockStatement -> blockStatement( statement.block.statements .takeWhile { !isSwitchBreak(it) } .map { it.copyTreeAndDetach() } ).withFormattingFrom(statement) isSwitchBreak(statement) -> null else -> statement.copyTreeAndDetach() } } val javaLabels = cases .takeWhileInclusive { it.statements.isEmpty() } val statementLabels = javaLabels .filterIsInstance<JKJavaLabelSwitchCase>() .map { JKKtValueWhenLabel(it.label) } val elseLabel = javaLabels .find { it is JKJavaDefaultSwitchCase } ?.let { JKKtElseWhenLabel() } val elseWhenCase = elseLabel?.let { label -> JKKtWhenCase(listOf(label), statements.map { it.copyTreeAndDetach() }.singleBlockOrWrapToRun()) } val mainWhenCase = if (statementLabels.isNotEmpty()) { JKKtWhenCase(statementLabels, statements.singleBlockOrWrapToRun()) } else null listOfNotNull(mainWhenCase) + listOfNotNull(elseWhenCase) + switchCasesToWhenCases(cases.drop(javaLabels.size)) } private fun <T> List<T>.takeWhileInclusive(predicate: (T) -> Boolean): List<T> = takeWhile(predicate) + listOfNotNull(find { !predicate(it) }) private fun List<JKStatement>.singleBlockOrWrapToRun(): JKStatement = singleOrNull() ?: JKBlockStatement( JKBlockImpl(map { statement -> when (statement) { is JKBlockStatement -> JKExpressionStatement( runExpression(statement, symbolProvider) ) else -> statement } }) ) private fun JKStatement.singleListOrBlockStatements(): List<JKStatement> = when (this) { is JKBlockStatement -> block.statements else -> listOf(this) } private fun isSwitchBreak(statement: JKStatement) = statement is JKBreakStatement && statement.label is JKLabelEmpty private fun List<JKStatement>.fallsThrough(): Boolean = all { it.fallsThrough() } private fun JKStatement.fallsThrough(): Boolean = when { this.isThrowStatement() || this is JKBreakStatement || this is JKReturnStatement || this is JKContinueStatement -> false this is JKBlockStatement -> block.statements.fallsThrough() this is JKIfElseStatement || this is JKJavaSwitchStatement || this is JKKtWhenStatement -> psi?.canCompleteNormally() == true else -> true } private fun JKStatement.isThrowStatement(): Boolean = (this as? JKExpressionStatement)?.expression is JKKtThrowExpression private fun PsiElement.canCompleteNormally(): Boolean { val controlFlow = ControlFlowFactory.getInstance(project).getControlFlow(this, LocalsOrMyInstanceFieldsControlFlowPolicy.getInstance()) val startOffset = controlFlow.getStartOffset(this) val endOffset = controlFlow.getEndOffset(this) return startOffset == -1 || endOffset == -1 || ControlFlowUtil.canCompleteNormally(controlFlow, startOffset, endOffset) } }
apache-2.0
9acf956108a7313179d7ca46151c5e85
42.837209
158
0.605412
5.581441
false
false
false
false
siosio/intellij-community
python/src/com/jetbrains/python/packaging/toolwindow/PyPackagingToolWindowPanel.kt
1
16133
// 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 com.jetbrains.python.packaging.toolwindow import com.intellij.icons.AllIcons import com.intellij.ide.BrowserUtil import com.intellij.openapi.actionSystem.* import com.intellij.openapi.actionSystem.impl.ActionButton import com.intellij.openapi.application.ModalityState import com.intellij.openapi.fileChooser.FileChooserDescriptorFactory import com.intellij.openapi.ui.SimpleToolWindowPanel import com.intellij.openapi.ui.TextFieldWithBrowseButton import com.intellij.openapi.ui.popup.JBPopupFactory import com.intellij.openapi.ui.popup.PopupStep import com.intellij.openapi.ui.popup.util.BaseListPopupStep import com.intellij.openapi.util.Disposer import com.intellij.openapi.util.NlsContexts import com.intellij.openapi.util.NlsSafe import com.intellij.openapi.wm.ToolWindow import com.intellij.openapi.wm.ToolWindowManager import com.intellij.openapi.wm.ex.ToolWindowManagerListener import com.intellij.ui.* import com.intellij.ui.components.* import com.intellij.ui.jcef.JCEFHtmlPanel import com.intellij.ui.layout.* import com.intellij.util.Alarm import com.intellij.util.SingleAlarm import com.intellij.util.ui.JBFont import com.intellij.util.ui.JBUI import com.intellij.util.ui.UIUtil import com.jetbrains.python.PyBundle.message import java.awt.* import java.awt.event.ActionEvent import java.awt.event.MouseAdapter import java.awt.event.MouseEvent import javax.swing.* import javax.swing.event.DocumentEvent class PyPackagingToolWindowPanel(service: PyPackagingToolWindowService, toolWindow: ToolWindow) : SimpleToolWindowPanel(false, true) { private val packageNameLabel = JLabel().apply { font = JBFont.h4().asBold(); isVisible = false } private val versionLabel = JLabel().apply { isVisible = false } private val documentationLink = HyperlinkLabel(message("python.toolwindow.packages.documentation.link")).apply { addHyperlinkListener { if (documentationUrl != null) BrowserUtil.browse(documentationUrl!!) } isVisible = false } private val searchTextField: SearchTextField private val searchAlarm: Alarm private val installButton: JBOptionButton private val uninstallAction: JComponent private val progressBar: JProgressBar private val versionSelector: JBComboBoxLabel private val descriptionPanel: JCEFHtmlPanel private var currentPackageInfo: PackageInfo? = null private var documentationUrl: String? = null val packageListPanel: JPanel val tablesView: PyPackagingTablesView val noPackagePanel = JBPanelWithEmptyText().apply { emptyText.text = message("python.toolwindow.packages.description.panel.placeholder") } // layout private var mainPanel: JPanel? = null private var splitter: OnePixelSplitter? = null private val leftPanel: JScrollPane private val rightPanel: JComponent internal var contentVisible: Boolean get() = mainPanel!!.isVisible set(value) { mainPanel!!.isVisible = value } private val latestText: String get() = message("python.toolwindow.packages.latest.version.label") private val fromVcsText: String get() = message("python.toolwindow.packages.add.package.from.vcs") private val fromDiscText: String get() = message("python.toolwindow.packages.add.package.from.disc") init { withEmptyText(message("python.toolwindow.packages.no.interpreter.text")) descriptionPanel = PyPackagingJcefHtmlPanel(service.project) Disposer.register(toolWindow.disposable, descriptionPanel) versionSelector = JBComboBoxLabel().apply { text = latestText isVisible = false addMouseListener(object : MouseAdapter() { override fun mouseClicked(e: MouseEvent?) { val versions = listOf(latestText) + (currentPackageInfo?.availableVersions ?: emptyList()) JBPopupFactory.getInstance().createListPopup( object : BaseListPopupStep<String>(null, versions) { override fun onChosen(@NlsContexts.Label selectedValue: String, finalChoice: Boolean): PopupStep<*>? { [email protected] = selectedValue return FINAL_CHOICE } }, 8).showUnderneathOf(this@apply) } }) } // todo: add options to install with args installButton = JBOptionButton(object : AbstractAction(message("python.toolwindow.packages.install.button")) { override fun actionPerformed(e: ActionEvent?) { val version = if (versionSelector.text == latestText) null else versionSelector.text service.installSelectedPackage(version) } }, null).apply { isVisible = false } val uninstallToolbar = ActionManager.getInstance() .createActionToolbar(ActionPlaces.TOOLWINDOW_CONTENT, DefaultActionGroup(DefaultActionGroup().apply { add(object : AnAction(message("python.toolwindow.packages.delete.package")) { override fun actionPerformed(e: AnActionEvent) { service.deleteSelectedPackage() } }) isPopup = true with(templatePresentation) { putClientProperty(ActionButton.HIDE_DROPDOWN_ICON, true) icon = AllIcons.Actions.More } }), true) uninstallToolbar.setTargetComponent(this) uninstallAction = uninstallToolbar.component progressBar = JProgressBar(JProgressBar.HORIZONTAL).apply { maximumSize.width = 200 minimumSize.width = 200 preferredSize.width = 200 isVisible = false isIndeterminate = true } packageListPanel = JPanel().apply { layout = BoxLayout(this, BoxLayout.Y_AXIS) alignmentX = LEFT_ALIGNMENT background = UIUtil.getListBackground() } tablesView = PyPackagingTablesView(service, packageListPanel) leftPanel = ScrollPaneFactory.createScrollPane(packageListPanel, true) rightPanel = borderPanel { add(borderPanel { border = SideBorder(JBColor.GRAY, SideBorder.BOTTOM) preferredSize = Dimension(preferredSize.width, 50) minimumSize = Dimension(minimumSize.width, 50) maximumSize = Dimension(maximumSize.width, 50) add(boxPanel { add(Box.createHorizontalStrut(10)) add(packageNameLabel) add(Box.createHorizontalStrut(10)) add(documentationLink) }, BorderLayout.WEST) add(boxPanel { alignmentX = Component.RIGHT_ALIGNMENT add(progressBar) add(versionSelector) add(versionLabel) add(installButton) add(uninstallAction) add(Box.createHorizontalStrut(10)) }, BorderLayout.EAST) }, BorderLayout.NORTH) add(descriptionPanel.component, BorderLayout.CENTER) } searchTextField = object : SearchTextField(false) { init { preferredSize = Dimension(250, 30) minimumSize = Dimension(250, 30) maximumSize = Dimension(250, 30) textEditor.border = JBUI.Borders.empty(0, 6, 0, 0) textEditor.isOpaque = true textEditor.emptyText.text = message("python.toolwindow.packages.search.text.placeholder") } override fun onFieldCleared() { service.handleSearch("") } } searchAlarm = SingleAlarm(Runnable { service.handleSearch(searchTextField.text.trim()) }, 500, ModalityState.NON_MODAL, service) searchTextField.addDocumentListener(object : DocumentAdapter() { override fun textChanged(e: DocumentEvent) { searchAlarm.cancelAndRequest() } }) initOrientation(service, true) trackOrientation(service) } private fun initOrientation(service: PyPackagingToolWindowService, horizontal: Boolean) { val second = if (splitter?.secondComponent == rightPanel) rightPanel else noPackagePanel val proportionKey = if (horizontal) HORIZONTAL_SPLITTER_KEY else VERTICAL_SPLITTER_KEY splitter = OnePixelSplitter(!horizontal, proportionKey, 0.3f).apply { firstComponent = leftPanel secondComponent = second } val actionGroup = DefaultActionGroup() actionGroup.add(object : AnAction({ message("python.toolwindow.packages.reload.repositories.action")}, AllIcons.Actions.Refresh) { override fun actionPerformed(e: AnActionEvent) { service.reloadPackages() } }) actionGroup.add(object : AnAction({ message("python.toolwindow.packages.manage.repositories.action") }, AllIcons.General.GearPlain) { override fun actionPerformed(e: AnActionEvent) { service.manageRepositories() } }) val actionToolbar = ActionManager.getInstance().createActionToolbar(ActionPlaces.TOOLWINDOW_CONTENT, actionGroup,true) actionToolbar.setTargetComponent(this) val installFromLocationLink = DropDownLink(message("python.toolwindow.packages.add.package.action"), listOf(fromVcsText, fromDiscText)) { val params = when (it) { fromDiscText -> showInstallFromDiscDialog(service) fromVcsText -> showInstallFromVcsDialog(service) else -> throw IllegalStateException("Unknown operation") } if (params != null) { service.installFromLocation(params.first, params.second) } } mainPanel = borderPanel { val topToolbar = boxPanel { border = SideBorder(UIUtil.getBoundsColor(), SideBorder.BOTTOM) preferredSize = Dimension(preferredSize.width, 30) minimumSize = Dimension(minimumSize.width, 30) maximumSize = Dimension(maximumSize.width, 30) add(searchTextField) actionToolbar.component.maximumSize = Dimension(60, actionToolbar.component.maximumSize.height) add(actionToolbar.component) add(installFromLocationLink) } add(topToolbar, BorderLayout.NORTH) add(splitter!!, BorderLayout.CENTER) } setContent(mainPanel!!) } private fun showInstallFromVcsDialog(service: PyPackagingToolWindowService): Pair<String, Boolean>? { var editable = false var link = "" val systems = arrayOf(message("python.toolwindow.packages.add.package.vcs.git"), message("python.toolwindow.packages.add.package.vcs.svn"), message("python.toolwindow.packages.add.package.vcs.hg"), message("python.toolwindow.packages.add.package.vcs.bzr")) var vcs = systems.first() val panel = panel { row { comboBox<String>(DefaultComboBoxModel(systems), getter = { vcs }, setter = { vcs = it!! }) textField({ link }, { link = it }).growPolicy(GrowPolicy.MEDIUM_TEXT) } row { checkBox(message("python.toolwindow.packages.add.package.as.editable"), { editable }, { editable = it }) } } val shouldInstall = dialog(message("python.toolwindow.packages.add.package.dialog.title"), panel, project = service.project, resizable = true).showAndGet() if (shouldInstall) { val prefix = when (vcs) { message("python.toolwindow.packages.add.package.vcs.git") -> "git+" message("python.toolwindow.packages.add.package.vcs.svn") -> "svn+" message("python.toolwindow.packages.add.package.vcs.hg") -> "hg+" message("python.toolwindow.packages.add.package.vcs.bzr") -> "bzr+" else -> throw IllegalStateException("Unknown VCS") } return Pair(prefix + link, editable) } return null } private fun showInstallFromDiscDialog(service: PyPackagingToolWindowService): Pair<String, Boolean>? { var editable = false val textField = TextFieldWithBrowseButton().apply { addBrowseFolderListener(message("python.toolwindow.packages.add.package.path.selector"), "", service.project, FileChooserDescriptorFactory.createSingleFileOrFolderDescriptor()) } val panel = panel { row { label(message("python.toolwindow.packages.add.package.path")) textField().growPolicy(GrowPolicy.MEDIUM_TEXT) } row { checkBox(message("python.toolwindow.packages.add.package.as.editable"), { editable }, { editable = it }) } } val shouldInstall = dialog(message("python.toolwindow.packages.add.package.dialog.title"), panel, project = service.project, resizable = true).showAndGet() return if (shouldInstall) Pair("file://${textField.text}", editable) else null } private fun trackOrientation(service: PyPackagingToolWindowService) { service.project.messageBus.connect(service).subscribe(ToolWindowManagerListener.TOPIC, object : ToolWindowManagerListener { var myHorizontal = true override fun stateChanged(toolWindowManager: ToolWindowManager) { val toolWindow = toolWindowManager.getToolWindow("Python Packages") if (toolWindow == null || toolWindow.isDisposed) return val isHorizontal = toolWindow.anchor.isHorizontal if (myHorizontal != isHorizontal) { myHorizontal = isHorizontal val content = toolWindow.contentManager.contents.find { it?.component is PyPackagingToolWindowPanel } val panel = content?.component as? PyPackagingToolWindowPanel ?: return panel.initOrientation(service, myHorizontal) } } }) } fun showSearchResult(installed: List<InstalledPackage>, repoData: List<PyPackagesViewData>) { tablesView.showSearchResult(installed, repoData) } fun resetSearch(installed: List<InstalledPackage>, repos: List<PyPackagesViewData>) { tablesView.resetSearch(installed, repos) } fun displaySelectedPackageInfo(packageInfo: PackageInfo) { currentPackageInfo = packageInfo if (splitter?.secondComponent != rightPanel) { splitter!!.secondComponent = rightPanel } descriptionPanel.setHtml(packageInfo.description) documentationUrl = packageInfo.documentationUrl documentationLink.isVisible = documentationUrl != null } fun startProgress() { progressBar.isVisible = true hideInstallableControls() hideInstalledControls() } fun stopProgress() { progressBar.isVisible = false } fun showInstalledControls() { hideInstallableControls() progressBar.isVisible = false versionLabel.isVisible = true uninstallAction.isVisible = true } fun showInstallableControls() { hideInstalledControls() progressBar.isVisible = false versionSelector.isVisible = true versionSelector.text = latestText installButton.isVisible = true } private fun hideInstalledControls() { versionLabel.isVisible = false uninstallAction.isVisible = false } private fun hideInstallableControls() { installButton.isVisible = false versionSelector.isVisible = false } fun packageInstalled(newFiltered: List<InstalledPackage>) { tablesView.packagesAdded(newFiltered) } fun packageDeleted(deletedPackage: DisplayablePackage) { tablesView.packageDeleted(deletedPackage) } fun showHeaderForPackage(selectedPackage: DisplayablePackage) { packageNameLabel.text = selectedPackage.name packageNameLabel.isVisible = true documentationLink.isVisible = false if (selectedPackage is InstalledPackage) { versionLabel.text = selectedPackage.instance.version showInstalledControls() } else { showInstallableControls() } } fun setEmpty() { hideInstalledControls() hideInstallableControls() listOf(packageNameLabel, packageNameLabel, documentationLink).forEach { it.isVisible = false } splitter?.secondComponent = noPackagePanel } companion object { private const val HORIZONTAL_SPLITTER_KEY = "Python.PackagingToolWindow.Horizontal" private const val VERTICAL_SPLITTER_KEY = "Python.PackagingToolWindow.Vertical" val REMOTE_INTERPRETER_TEXT: String get() = message("python.toolwindow.packages.remote.interpreter.placeholder") val REQUEST_FAILED_TEXT: String get() = message("python.toolwindow.packages.request.failed") val NO_DESCRIPTION: String get() = message("python.toolwindow.packages.no.description.placeholder") } }
apache-2.0
a84fbefec60fbeeeaf29175f3801859a
37.232227
159
0.711957
4.897693
false
false
false
false
siosio/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/LateinitVarOverridesLateinitVarInspection.kt
1
1556
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.inspections import com.intellij.codeInspection.ProblemsHolder import org.jetbrains.kotlin.descriptors.PropertyDescriptor import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.idea.caches.resolve.resolveToDescriptorIfAny import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.psi.KtProperty import org.jetbrains.kotlin.psi.classOrObjectRecursiveVisitor class LateinitVarOverridesLateinitVarInspection : AbstractKotlinInspection() { override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean) = classOrObjectRecursiveVisitor(fun(klass) { for (declaration in klass.declarations) { val property = declaration as? KtProperty ?: continue if (!property.hasModifier(KtTokens.OVERRIDE_KEYWORD) || !property.hasModifier(KtTokens.LATEINIT_KEYWORD) || !property.isVar) { continue } val identifier = property.nameIdentifier ?: continue val descriptor = property.resolveToDescriptorIfAny() ?: continue if (descriptor.overriddenDescriptors.any { (it as? PropertyDescriptor)?.let { d -> d.isLateInit && d.isVar } == true }) { holder.registerProblem( identifier, KotlinBundle.message("lateinit.var.overrides.lateinit.var") ) } } }) }
apache-2.0
c765943c04b373b42d199d966726ae60
50.866667
158
0.710154
5.035599
false
false
false
false
androidx/androidx
compose/ui/ui/src/androidMain/kotlin/androidx/compose/ui/platform/AndroidClipboardManager.android.kt
3
17840
/* * Copyright 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.ui.platform import android.content.ClipData import android.content.Context import android.os.Parcel import android.text.Annotation import android.text.SpannableString import android.text.Spanned import android.util.Base64 import androidx.compose.ui.geometry.Offset import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.Shadow import androidx.compose.ui.text.AnnotatedString import androidx.compose.ui.text.SpanStyle import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.text.font.FontStyle import androidx.compose.ui.text.font.FontSynthesis import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.intl.LocaleList import androidx.compose.ui.text.style.BaselineShift import androidx.compose.ui.text.style.TextDecoration import androidx.compose.ui.text.style.TextGeometricTransform import androidx.compose.ui.unit.ExperimentalUnitApi import androidx.compose.ui.unit.TextUnit import androidx.compose.ui.unit.TextUnitType import androidx.compose.ui.util.fastForEach private const val PLAIN_TEXT_LABEL = "plain text" /** * Android implementation for [ClipboardManager]. */ internal class AndroidClipboardManager internal constructor( private val clipboardManager: android.content.ClipboardManager ) : ClipboardManager { internal constructor(context: Context) : this( context.getSystemService(Context.CLIPBOARD_SERVICE) as android.content.ClipboardManager ) override fun setText(annotatedString: AnnotatedString) { clipboardManager.setPrimaryClip( ClipData.newPlainText( PLAIN_TEXT_LABEL, annotatedString.convertToCharSequence() ) ) } override fun getText(): AnnotatedString? { return clipboardManager.primaryClip?.let { primaryClip -> if (primaryClip.itemCount > 0) { // note: text may be null, ensure this is null-safe primaryClip.getItemAt(0)?.text.convertToAnnotatedString() } else { null } } } override fun hasText() = clipboardManager.primaryClipDescription?.hasMimeType("text/*") ?: false } internal fun CharSequence?.convertToAnnotatedString(): AnnotatedString? { if (this == null) return null if (this !is Spanned) { return AnnotatedString(text = toString()) } val annotations = getSpans(0, length, Annotation::class.java) val spanStyleRanges = mutableListOf<AnnotatedString.Range<SpanStyle>>() for (i in 0..annotations.lastIndex) { val span = annotations[i] if (span.key != "androidx.compose.text.SpanStyle") { continue } val start = getSpanStart(span) val end = getSpanEnd(span) val decodeHelper = DecodeHelper(span.value) val spanStyle = decodeHelper.decodeSpanStyle() spanStyleRanges.add(AnnotatedString.Range(spanStyle, start, end)) } return AnnotatedString(text = toString(), spanStyles = spanStyleRanges) } internal fun AnnotatedString.convertToCharSequence(): CharSequence { if (spanStyles.isEmpty()) { return text } val spannableString = SpannableString(text) // Normally a SpanStyle will take less than 100 bytes. However, fontFeatureSettings is a string // and doesn't have a maximum length defined. Here we set tentatively set maxSize to be 1024. val encodeHelper = EncodeHelper() spanStyles.fastForEach { (spanStyle, start, end) -> encodeHelper.apply { reset() encode(spanStyle) } spannableString.setSpan( Annotation("androidx.compose.text.SpanStyle", encodeHelper.encodedString()), start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE ) } return spannableString } /** * A helper class used to encode SpanStyles into bytes. * Each field of SpanStyle is assigned with an ID. And if a field is not null or Unspecified, it * will be encoded. Otherwise, it will simply be omitted to save space. */ internal class EncodeHelper { private var parcel = Parcel.obtain() fun reset() { parcel.recycle() parcel = Parcel.obtain() } fun encodedString(): String { val bytes = parcel.marshall() return Base64.encodeToString(bytes, Base64.DEFAULT) } fun encode(spanStyle: SpanStyle) { if (spanStyle.color != Color.Unspecified) { encode(COLOR_ID) encode(spanStyle.color) } if (spanStyle.fontSize != TextUnit.Unspecified) { encode(FONT_SIZE_ID) encode(spanStyle.fontSize) } spanStyle.fontWeight?.let { encode(FONT_WEIGHT_ID) encode(it) } spanStyle.fontStyle?.let { encode(FONT_STYLE_ID) encode(it) } spanStyle.fontSynthesis?.let { encode(FONT_SYNTHESIS_ID) encode(it) } spanStyle.fontFeatureSettings?.let { encode(FONT_FEATURE_SETTINGS_ID) encode(it) } if (spanStyle.letterSpacing != TextUnit.Unspecified) { encode(LETTER_SPACING_ID) encode(spanStyle.letterSpacing) } spanStyle.baselineShift?.let { encode(BASELINE_SHIFT_ID) encode(it) } spanStyle.textGeometricTransform?.let { encode(TEXT_GEOMETRIC_TRANSFORM_ID) encode(it) } if (spanStyle.background != Color.Unspecified) { encode(BACKGROUND_ID) encode(spanStyle.background) } spanStyle.textDecoration?.let { encode(TEXT_DECORATION_ID) encode(it) } spanStyle.shadow?.let { encode(SHADOW_ID) encode(it) } } fun encode(color: Color) { encode(color.value) } fun encode(textUnit: TextUnit) { val typeCode = when (textUnit.type) { TextUnitType.Unspecified -> UNIT_TYPE_UNSPECIFIED TextUnitType.Sp -> UNIT_TYPE_SP TextUnitType.Em -> UNIT_TYPE_EM else -> UNIT_TYPE_UNSPECIFIED } encode(typeCode) if (textUnit.type != TextUnitType.Unspecified) { encode(textUnit.value) } } fun encode(fontWeight: FontWeight) { encode(fontWeight.weight) } fun encode(fontStyle: FontStyle) { encode( when (fontStyle) { FontStyle.Normal -> FONT_STYLE_NORMAL FontStyle.Italic -> FONT_STYLE_ITALIC else -> FONT_STYLE_NORMAL } ) } fun encode(fontSynthesis: FontSynthesis) { val value = when (fontSynthesis) { FontSynthesis.None -> FONT_SYNTHESIS_NONE FontSynthesis.All -> FONT_SYNTHESIS_ALL FontSynthesis.Weight -> FONT_SYNTHESIS_WEIGHT FontSynthesis.Style -> FONT_SYNTHESIS_STYLE else -> FONT_SYNTHESIS_NONE } encode(value) } fun encode(baselineShift: BaselineShift) { encode(baselineShift.multiplier) } fun encode(textGeometricTransform: TextGeometricTransform) { encode(textGeometricTransform.scaleX) encode(textGeometricTransform.skewX) } fun encode(textDecoration: TextDecoration) { encode(textDecoration.mask) } fun encode(shadow: Shadow) { encode(shadow.color) encode(shadow.offset.x) encode(shadow.offset.y) encode(shadow.blurRadius) } fun encode(byte: Byte) { parcel.writeByte(byte) } fun encode(int: Int) { parcel.writeInt(int) } fun encode(float: Float) { parcel.writeFloat(float) } fun encode(uLong: ULong) { parcel.writeLong(uLong.toLong()) } fun encode(string: String) { parcel.writeString(string) } } /** * The helper class to decode SpanStyle from a string encoded by [EncodeHelper]. */ internal class DecodeHelper(string: String) { private val parcel = Parcel.obtain() init { val bytes = Base64.decode(string, Base64.DEFAULT) parcel.unmarshall(bytes, 0, bytes.size) parcel.setDataPosition(0) } /** Decode a SpanStyle from a string. */ fun decodeSpanStyle(): SpanStyle { val mutableSpanStyle = MutableSpanStyle() while (parcel.dataAvail() > BYTE_SIZE) { when (decodeByte()) { COLOR_ID -> if (dataAvailable() >= COLOR_SIZE) { mutableSpanStyle.color = decodeColor() } else { break } FONT_SIZE_ID -> if (dataAvailable() >= TEXT_UNIT_SIZE) { mutableSpanStyle.fontSize = decodeTextUnit() } else { break } FONT_WEIGHT_ID -> if (dataAvailable() >= FONT_WEIGHT_SIZE) { mutableSpanStyle.fontWeight = decodeFontWeight() } else { break } FONT_STYLE_ID -> if (dataAvailable() >= FONT_STYLE_SIZE) { mutableSpanStyle.fontStyle = decodeFontStyle() } else { break } FONT_SYNTHESIS_ID -> if (dataAvailable() >= FONT_SYNTHESIS_SIZE) { mutableSpanStyle.fontSynthesis = decodeFontSynthesis() } else { break } FONT_FEATURE_SETTINGS_ID -> mutableSpanStyle.fontFeatureSettings = decodeString() LETTER_SPACING_ID -> if (dataAvailable() >= TEXT_UNIT_SIZE) { mutableSpanStyle.letterSpacing = decodeTextUnit() } else { break } BASELINE_SHIFT_ID -> if (dataAvailable() >= BASELINE_SHIFT_SIZE) { mutableSpanStyle.baselineShift = decodeBaselineShift() } else { break } TEXT_GEOMETRIC_TRANSFORM_ID -> if (dataAvailable() >= TEXT_GEOMETRIC_TRANSFORM_SIZE) { mutableSpanStyle.textGeometricTransform = decodeTextGeometricTransform() } else { break } BACKGROUND_ID -> if (dataAvailable() >= COLOR_SIZE) { mutableSpanStyle.background = decodeColor() } else { break } TEXT_DECORATION_ID -> if (dataAvailable() >= TEXT_DECORATION_SIZE) { mutableSpanStyle.textDecoration = decodeTextDecoration() } else { break } SHADOW_ID -> if (dataAvailable() >= SHADOW_SIZE) { mutableSpanStyle.shadow = decodeShadow() } else { break } } } return mutableSpanStyle.toSpanStyle() } fun decodeColor(): Color { return Color(decodeULong()) } @OptIn(ExperimentalUnitApi::class) fun decodeTextUnit(): TextUnit { val type = when (decodeByte()) { UNIT_TYPE_SP -> TextUnitType.Sp UNIT_TYPE_EM -> TextUnitType.Em else -> TextUnitType.Unspecified } if (type == TextUnitType.Unspecified) { return TextUnit.Unspecified } val value = decodeFloat() return TextUnit(value, type) } @OptIn(ExperimentalUnitApi::class) fun decodeFontWeight(): FontWeight { return FontWeight(decodeInt()) } fun decodeFontStyle(): FontStyle { return when (decodeByte()) { FONT_STYLE_NORMAL -> FontStyle.Normal FONT_STYLE_ITALIC -> FontStyle.Italic else -> FontStyle.Normal } } fun decodeFontSynthesis(): FontSynthesis { return when (decodeByte()) { FONT_SYNTHESIS_NONE -> FontSynthesis.None FONT_SYNTHESIS_ALL -> FontSynthesis.All FONT_SYNTHESIS_STYLE -> FontSynthesis.Style FONT_SYNTHESIS_WEIGHT -> FontSynthesis.Weight else -> FontSynthesis.None } } private fun decodeBaselineShift(): BaselineShift { return BaselineShift(decodeFloat()) } private fun decodeTextGeometricTransform(): TextGeometricTransform { return TextGeometricTransform( scaleX = decodeFloat(), skewX = decodeFloat() ) } private fun decodeTextDecoration(): TextDecoration { val mask = decodeInt() val hasLineThrough = mask and TextDecoration.LineThrough.mask != 0 val hasUnderline = mask and TextDecoration.Underline.mask != 0 return if (hasLineThrough && hasUnderline) { TextDecoration.combine(listOf(TextDecoration.LineThrough, TextDecoration.Underline)) } else if (hasLineThrough) { TextDecoration.LineThrough } else if (hasUnderline) { TextDecoration.Underline } else { TextDecoration.None } } private fun decodeShadow(): Shadow { return Shadow( color = decodeColor(), offset = Offset(decodeFloat(), decodeFloat()), blurRadius = decodeFloat() ) } private fun decodeByte(): Byte { return parcel.readByte() } private fun decodeInt(): Int { return parcel.readInt() } private fun decodeULong(): ULong { return parcel.readLong().toULong() } private fun decodeFloat(): Float { return parcel.readFloat() } private fun decodeString(): String? { return parcel.readString() } private fun dataAvailable(): Int { return parcel.dataAvail() } } private class MutableSpanStyle( var color: Color = Color.Unspecified, var fontSize: TextUnit = TextUnit.Unspecified, var fontWeight: FontWeight? = null, var fontStyle: FontStyle? = null, var fontSynthesis: FontSynthesis? = null, var fontFamily: FontFamily? = null, var fontFeatureSettings: String? = null, var letterSpacing: TextUnit = TextUnit.Unspecified, var baselineShift: BaselineShift? = null, var textGeometricTransform: TextGeometricTransform? = null, var localeList: LocaleList? = null, var background: Color = Color.Unspecified, var textDecoration: TextDecoration? = null, var shadow: Shadow? = null ) { fun toSpanStyle(): SpanStyle { return SpanStyle( color = color, fontSize = fontSize, fontWeight = fontWeight, fontStyle = fontStyle, fontSynthesis = fontSynthesis, fontFamily = fontFamily, fontFeatureSettings = fontFeatureSettings, letterSpacing = letterSpacing, baselineShift = baselineShift, textGeometricTransform = textGeometricTransform, localeList = localeList, background = background, textDecoration = textDecoration, shadow = shadow ) } } private const val UNIT_TYPE_UNSPECIFIED: Byte = 0 private const val UNIT_TYPE_SP: Byte = 1 private const val UNIT_TYPE_EM: Byte = 2 private const val FONT_STYLE_NORMAL: Byte = 0 private const val FONT_STYLE_ITALIC: Byte = 1 private const val FONT_SYNTHESIS_NONE: Byte = 0 private const val FONT_SYNTHESIS_ALL: Byte = 1 private const val FONT_SYNTHESIS_WEIGHT: Byte = 2 private const val FONT_SYNTHESIS_STYLE: Byte = 3 private const val COLOR_ID: Byte = 1 private const val FONT_SIZE_ID: Byte = 2 private const val FONT_WEIGHT_ID: Byte = 3 private const val FONT_STYLE_ID: Byte = 4 private const val FONT_SYNTHESIS_ID: Byte = 5 private const val FONT_FEATURE_SETTINGS_ID: Byte = 6 private const val LETTER_SPACING_ID: Byte = 7 private const val BASELINE_SHIFT_ID: Byte = 8 private const val TEXT_GEOMETRIC_TRANSFORM_ID: Byte = 9 private const val BACKGROUND_ID: Byte = 10 private const val TEXT_DECORATION_ID: Byte = 11 private const val SHADOW_ID: Byte = 12 private const val BYTE_SIZE = 1 private const val INT_SIZE = 4 private const val FLOAT_SIZE = 4 private const val LONG_SIZE = 8 private const val COLOR_SIZE = LONG_SIZE private const val TEXT_UNIT_SIZE = BYTE_SIZE + FLOAT_SIZE private const val FONT_WEIGHT_SIZE = INT_SIZE private const val FONT_STYLE_SIZE = BYTE_SIZE private const val FONT_SYNTHESIS_SIZE = BYTE_SIZE private const val BASELINE_SHIFT_SIZE = FLOAT_SIZE private const val TEXT_GEOMETRIC_TRANSFORM_SIZE = FLOAT_SIZE * 2 private const val TEXT_DECORATION_SIZE = INT_SIZE private const val SHADOW_SIZE = COLOR_SIZE + FLOAT_SIZE * 3
apache-2.0
87875d081143c6c551b5361a77b3db90
31.438182
99
0.602242
4.750999
false
false
false
false
androidx/androidx
health/connect/connect-client/src/main/java/androidx/health/connect/client/records/ExerciseRepetitionsRecord.kt
3
7986
/* * Copyright (C) 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.health.connect.client.records import androidx.annotation.IntDef import androidx.annotation.RestrictTo import androidx.health.connect.client.records.metadata.Metadata import java.time.Instant import java.time.ZoneOffset /** Captures the number of repetitions in an exercise set. */ public class ExerciseRepetitionsRecord( override val startTime: Instant, override val startZoneOffset: ZoneOffset?, override val endTime: Instant, override val endZoneOffset: ZoneOffset?, /** Count. Required field. Valid range: 1-1000000. */ public val count: Long, /** Type of exercise being repeated. Required field. */ @property:RepetitionTypes public val type: Int, override val metadata: Metadata = Metadata.EMPTY, ) : IntervalRecord { init { requireNonNegative(value = count, name = "count") count.requireNotMore(other = 1000_000, name = "count") require(startTime.isBefore(endTime)) { "startTime must be before endTime." } } override fun equals(other: Any?): Boolean { if (this === other) return true if (other !is ExerciseRepetitionsRecord) return false if (count != other.count) return false if (type != other.type) return false if (startTime != other.startTime) return false if (startZoneOffset != other.startZoneOffset) return false if (endTime != other.endTime) return false if (endZoneOffset != other.endZoneOffset) return false if (metadata != other.metadata) return false return true } override fun hashCode(): Int { var result = count.hashCode() result = 31 * result + type.hashCode() result = 31 * result + (startZoneOffset?.hashCode() ?: 0) result = 31 * result + endTime.hashCode() result = 31 * result + (endZoneOffset?.hashCode() ?: 0) result = 31 * result + metadata.hashCode() return result } companion object { const val REPETITION_TYPE_UNKNOWN = 0 const val REPETITION_TYPE_ARM_CURL = 1 const val REPETITION_TYPE_BACK_EXTENSION = 2 const val REPETITION_TYPE_BALL_SLAM = 3 const val REPETITION_TYPE_BENCH_PRESS = 4 const val REPETITION_TYPE_BURPEE = 5 const val REPETITION_TYPE_CRUNCH = 6 const val REPETITION_TYPE_DEADLIFT = 7 const val REPETITION_TYPE_DOUBLE_ARM_TRICEPS_EXTENSION = 8 const val REPETITION_TYPE_DUMBBELL_ROW = 9 const val REPETITION_TYPE_FRONT_RAISE = 10 const val REPETITION_TYPE_HIP_THRUST = 11 const val REPETITION_TYPE_HULA_HOOP = 12 const val REPETITION_TYPE_JUMPING_JACK = 13 const val REPETITION_TYPE_JUMP_ROPE = 14 const val REPETITION_TYPE_KETTLEBELL_SWING = 15 const val REPETITION_TYPE_LATERAL_RAISE = 16 const val REPETITION_TYPE_LAT_PULL_DOWN = 17 const val REPETITION_TYPE_LEG_CURL = 18 const val REPETITION_TYPE_LEG_EXTENSION = 19 const val REPETITION_TYPE_LEG_PRESS = 20 const val REPETITION_TYPE_LEG_RAISE = 21 const val REPETITION_TYPE_LUNGE = 22 const val REPETITION_TYPE_MOUNTAIN_CLIMBER = 23 const val REPETITION_TYPE_PLANK = 24 const val REPETITION_TYPE_PULL_UP = 25 const val REPETITION_TYPE_PUNCH = 26 const val REPETITION_TYPE_SHOULDER_PRESS = 27 const val REPETITION_TYPE_SINGLE_ARM_TRICEPS_EXTENSION = 28 const val REPETITION_TYPE_SIT_UP = 29 const val REPETITION_TYPE_SQUAT = 30 @RestrictTo(RestrictTo.Scope.LIBRARY) @JvmField val REPETITION_TYPE_STRING_TO_INT_MAP: Map<String, Int> = mapOf( "arm_curl" to REPETITION_TYPE_ARM_CURL, "back_extension" to REPETITION_TYPE_BACK_EXTENSION, "ball_slam" to REPETITION_TYPE_BALL_SLAM, "bench_press" to REPETITION_TYPE_BENCH_PRESS, "burpee" to REPETITION_TYPE_BURPEE, "crunch" to REPETITION_TYPE_CRUNCH, "deadlift" to REPETITION_TYPE_DEADLIFT, "double_arm_triceps_extension" to REPETITION_TYPE_DOUBLE_ARM_TRICEPS_EXTENSION, "dumbbell_row" to REPETITION_TYPE_DUMBBELL_ROW, "front_raise" to REPETITION_TYPE_FRONT_RAISE, "hip_thrust" to REPETITION_TYPE_HIP_THRUST, "hula_hoop" to REPETITION_TYPE_HULA_HOOP, "jumping_jack" to REPETITION_TYPE_JUMPING_JACK, "jump_rope" to REPETITION_TYPE_JUMP_ROPE, "kettlebell_swing" to REPETITION_TYPE_KETTLEBELL_SWING, "lateral_raise" to REPETITION_TYPE_LATERAL_RAISE, "lat_pull_down" to REPETITION_TYPE_LAT_PULL_DOWN, "leg_curl" to REPETITION_TYPE_LEG_CURL, "leg_extension" to REPETITION_TYPE_LEG_EXTENSION, "leg_press" to REPETITION_TYPE_LEG_PRESS, "leg_raise" to REPETITION_TYPE_LEG_RAISE, "lunge" to REPETITION_TYPE_LUNGE, "mountain_climber" to REPETITION_TYPE_MOUNTAIN_CLIMBER, "plank" to REPETITION_TYPE_PLANK, "pull_up" to REPETITION_TYPE_PULL_UP, "punch" to REPETITION_TYPE_PUNCH, "shoulder_press" to REPETITION_TYPE_SHOULDER_PRESS, "single_arm_triceps_extension" to REPETITION_TYPE_SINGLE_ARM_TRICEPS_EXTENSION, "sit_up" to REPETITION_TYPE_SIT_UP, "squat" to REPETITION_TYPE_SQUAT, ) @RestrictTo(RestrictTo.Scope.LIBRARY) @JvmField val REPETITION_TYPE_INT_TO_STRING_MAP = REPETITION_TYPE_STRING_TO_INT_MAP.entries.associateBy({ it.value }, { it.key }) } /** * Exercise types supported by repetitions. * @suppress */ @Retention(AnnotationRetention.SOURCE) @IntDef( value = [ REPETITION_TYPE_ARM_CURL, REPETITION_TYPE_BACK_EXTENSION, REPETITION_TYPE_BALL_SLAM, REPETITION_TYPE_BENCH_PRESS, REPETITION_TYPE_BURPEE, REPETITION_TYPE_CRUNCH, REPETITION_TYPE_DEADLIFT, REPETITION_TYPE_DOUBLE_ARM_TRICEPS_EXTENSION, REPETITION_TYPE_DUMBBELL_ROW, REPETITION_TYPE_FRONT_RAISE, REPETITION_TYPE_HIP_THRUST, REPETITION_TYPE_HULA_HOOP, REPETITION_TYPE_JUMPING_JACK, REPETITION_TYPE_JUMP_ROPE, REPETITION_TYPE_KETTLEBELL_SWING, REPETITION_TYPE_LATERAL_RAISE, REPETITION_TYPE_LAT_PULL_DOWN, REPETITION_TYPE_LEG_CURL, REPETITION_TYPE_LEG_EXTENSION, REPETITION_TYPE_LEG_PRESS, REPETITION_TYPE_LEG_RAISE, REPETITION_TYPE_LUNGE, REPETITION_TYPE_MOUNTAIN_CLIMBER, REPETITION_TYPE_PLANK, REPETITION_TYPE_PULL_UP, REPETITION_TYPE_PUNCH, REPETITION_TYPE_SHOULDER_PRESS, REPETITION_TYPE_SINGLE_ARM_TRICEPS_EXTENSION, REPETITION_TYPE_SIT_UP, REPETITION_TYPE_SQUAT, ] ) @RestrictTo(RestrictTo.Scope.LIBRARY) annotation class RepetitionTypes }
apache-2.0
c9f85f77800bf477ca1d93e6e891d2b2
42.167568
95
0.622965
4.045593
false
false
false
false
GunoH/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/actions/generate/KotlinGenerateEqualsAndHashcodeAction.kt
1
15324
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.actions.generate import com.intellij.codeInsight.CodeInsightSettings import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import com.intellij.psi.PsiNameIdentifierOwner import com.intellij.util.IncorrectOperationException import org.jetbrains.kotlin.builtins.KotlinBuiltIns import org.jetbrains.kotlin.config.ApiVersion import org.jetbrains.kotlin.config.LanguageFeature import org.jetbrains.kotlin.descriptors.ClassDescriptor import org.jetbrains.kotlin.descriptors.FunctionDescriptor import org.jetbrains.kotlin.descriptors.Modality import org.jetbrains.kotlin.descriptors.VariableDescriptor import org.jetbrains.kotlin.idea.core.CollectingNameValidator import org.jetbrains.kotlin.idea.base.facet.platform.platform import org.jetbrains.kotlin.idea.base.fe10.codeInsight.newDeclaration.Fe10KotlinNameSuggester import org.jetbrains.kotlin.idea.base.projectStructure.languageVersionSettings import org.jetbrains.kotlin.idea.base.psi.isInlineOrValue import org.jetbrains.kotlin.idea.caches.resolve.analyzeWithContent import org.jetbrains.kotlin.idea.codeInsight.DescriptorToSourceUtilsIde import org.jetbrains.kotlin.idea.core.insertMembersAfterAndReformat import org.jetbrains.kotlin.idea.util.IdeDescriptorRenderers import org.jetbrains.kotlin.idea.util.application.isUnitTestMode import com.intellij.openapi.application.runWriteAction import org.jetbrains.kotlin.platform.isCommon import org.jetbrains.kotlin.platform.js.isJs import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.hasExpectModifier import org.jetbrains.kotlin.psi.psiUtil.quoteIfNeeded import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.descriptorUtil.builtIns import org.jetbrains.kotlin.resolve.descriptorUtil.getSuperClassOrAny import org.jetbrains.kotlin.resolve.source.getPsi import org.jetbrains.kotlin.types.TypeUtils import org.jetbrains.kotlin.utils.addIfNotNull import org.jetbrains.kotlin.utils.addToStdlib.lastIsInstanceOrNull import org.jetbrains.kotlin.utils.addToStdlib.safeAs fun ClassDescriptor.findDeclaredEquals(checkSupers: Boolean): FunctionDescriptor? { return findDeclaredFunction("equals", checkSupers) { it.modality != Modality.ABSTRACT && it.valueParameters.singleOrNull()?.type == it.builtIns.nullableAnyType && it.typeParameters.isEmpty() } } fun ClassDescriptor.findDeclaredHashCode(checkSupers: Boolean): FunctionDescriptor? { return findDeclaredFunction("hashCode", checkSupers) { it.modality != Modality.ABSTRACT && it.valueParameters.isEmpty() && it.typeParameters.isEmpty() } } class KotlinGenerateEqualsAndHashcodeAction : KotlinGenerateMemberActionBase<KotlinGenerateEqualsAndHashcodeAction.Info>() { companion object { private val LOG = Logger.getInstance(KotlinGenerateEqualsAndHashcodeAction::class.java) } class Info( val needEquals: Boolean, val needHashCode: Boolean, val classDescriptor: ClassDescriptor, val variablesForEquals: List<VariableDescriptor>, val variablesForHashCode: List<VariableDescriptor> ) override fun isValidForClass(targetClass: KtClassOrObject): Boolean { return targetClass is KtClass && targetClass !is KtEnumEntry && !targetClass.isEnum() && !targetClass.isAnnotation() && !targetClass.isInterface() && !targetClass.isInlineOrValue() } override fun prepareMembersInfo(klass: KtClassOrObject, project: Project, editor: Editor?): Info? { val asClass = klass.safeAs<KtClass>() ?: return null return prepareMembersInfo(asClass, project, true) } fun prepareMembersInfo(klass: KtClass, project: Project, askDetails: Boolean): Info? { val context = klass.analyzeWithContent() val classDescriptor = context.get(BindingContext.CLASS, klass) ?: return null val equalsDescriptor = classDescriptor.findDeclaredEquals(false) val hashCodeDescriptor = classDescriptor.findDeclaredHashCode(false) var needEquals = equalsDescriptor == null var needHashCode = hashCodeDescriptor == null if (!needEquals && !needHashCode && askDetails) { if (!confirmMemberRewrite(klass, equalsDescriptor!!, hashCodeDescriptor!!)) return null runWriteAction { try { equalsDescriptor.source.getPsi()?.delete() hashCodeDescriptor.source.getPsi()?.delete() needEquals = true needHashCode = true } catch (e: IncorrectOperationException) { LOG.error(e) } } } val properties = getPropertiesToUseInGeneratedMember(klass) if (properties.isEmpty() || isUnitTestMode() || !askDetails) { val descriptors = properties.map { context[BindingContext.DECLARATION_TO_DESCRIPTOR, it] as VariableDescriptor } return Info(needEquals, needHashCode, classDescriptor, descriptors, descriptors) } return with(KotlinGenerateEqualsWizard(project, klass, properties, needEquals, needHashCode)) { if (!klass.hasExpectModifier() && !showAndGet()) return null Info(needEquals, needHashCode, classDescriptor, getPropertiesForEquals().map { context[BindingContext.DECLARATION_TO_DESCRIPTOR, it] as VariableDescriptor }, getPropertiesForHashCode().map { context[BindingContext.DECLARATION_TO_DESCRIPTOR, it] as VariableDescriptor }) } } private fun generateClassLiteralsNotEqual(paramName: String, targetClass: KtClassOrObject): String { val defaultExpression = "javaClass != $paramName?.javaClass" if (!targetClass.languageVersionSettings.supportsFeature(LanguageFeature.BoundCallableReferences)) return defaultExpression return when { targetClass.platform.isJs() -> "other == null || this::class.js != $paramName::class.js" targetClass.platform.isCommon() -> "other == null || this::class != $paramName::class" else -> defaultExpression } } private fun generateClassLiteral(targetClass: KtClassOrObject): String { val defaultExpression = "javaClass" if (!targetClass.languageVersionSettings.supportsFeature(LanguageFeature.BoundCallableReferences)) return defaultExpression return when { targetClass.platform.isJs() -> "this::class.js" targetClass.platform.isCommon() -> "this::class" else -> defaultExpression } } private fun isNestedArray(variable: VariableDescriptor) = KotlinBuiltIns.isArrayOrPrimitiveArray(variable.builtIns.getArrayElementType(variable.type)) private fun KtElement.canUseArrayContentFunctions() = languageVersionSettings.apiVersion >= ApiVersion.KOTLIN_1_1 private fun generateArraysEqualsCall( variable: VariableDescriptor, canUseContentFunctions: Boolean, arg1: String, arg2: String ): String { return if (canUseContentFunctions) { val methodName = if (isNestedArray(variable)) "contentDeepEquals" else "contentEquals" "$arg1.$methodName($arg2)" } else { val methodName = if (isNestedArray(variable)) "deepEquals" else "equals" "java.util.Arrays.$methodName($arg1, $arg2)" } } private fun generateArrayHashCodeCall( variable: VariableDescriptor, canUseContentFunctions: Boolean, argument: String ): String { return if (canUseContentFunctions) { val methodName = if (isNestedArray(variable)) "contentDeepHashCode" else "contentHashCode" val dot = if (TypeUtils.isNullableType(variable.type)) "?." else "." "$argument$dot$methodName()" } else { val methodName = if (isNestedArray(variable)) "deepHashCode" else "hashCode" "java.util.Arrays.$methodName($argument)" } } fun generateEquals(project: Project, info: Info, targetClass: KtClassOrObject): KtNamedFunction? { with(info) { if (!needEquals) return null val superEquals = classDescriptor.getSuperClassOrAny().findDeclaredEquals(true)!! val equalsFun = generateFunctionSkeleton(superEquals, targetClass) val paramName = equalsFun.valueParameters.first().name!!.quoteIfNeeded() var typeForCast = IdeDescriptorRenderers.SOURCE_CODE.renderClassifierName(classDescriptor) val typeParams = classDescriptor.declaredTypeParameters if (typeParams.isNotEmpty()) { typeForCast += typeParams.joinToString(prefix = "<", postfix = ">") { "*" } } val useIsCheck = CodeInsightSettings.getInstance().USE_INSTANCEOF_ON_EQUALS_PARAMETER val isNotInstanceCondition = if (useIsCheck) { "$paramName !is $typeForCast" } else { generateClassLiteralsNotEqual(paramName, targetClass) } val bodyText = buildString { append("if (this === $paramName) return true\n") append("if ($isNotInstanceCondition) return false\n") val builtIns = superEquals.builtIns if (!builtIns.isMemberOfAny(superEquals)) { append("if (!super.equals($paramName)) return false\n") } if (variablesForEquals.isNotEmpty()) { if (!useIsCheck) { append("\n$paramName as $typeForCast\n") } append('\n') variablesForEquals.forEach { val isNullable = TypeUtils.isNullableType(it.type) val isArray = KotlinBuiltIns.isArrayOrPrimitiveArray(it.type) val canUseArrayContentFunctions = targetClass.canUseArrayContentFunctions() val propName = (DescriptorToSourceUtilsIde.getAnyDeclaration(project, it) as PsiNameIdentifierOwner).nameIdentifier!!.text val notEquals = when { isArray -> { "!${generateArraysEqualsCall(it, canUseArrayContentFunctions, propName, "$paramName.$propName")}" } else -> { "$propName != $paramName.$propName" } } val equalsCheck = "if ($notEquals) return false\n" if (isArray && isNullable && canUseArrayContentFunctions) { append("if ($propName != null) {\n") append("if ($paramName.$propName == null) return false\n") append(equalsCheck) append("} else if ($paramName.$propName != null) return false\n") } else { append(equalsCheck) } } append('\n') } append("return true") } equalsFun.replaceBody { KtPsiFactory(project).createBlock(bodyText) } return equalsFun } } fun generateHashCode(project: Project, info: Info, targetClass: KtClassOrObject): KtNamedFunction? { fun VariableDescriptor.genVariableHashCode(parenthesesNeeded: Boolean): String { val ref = (DescriptorToSourceUtilsIde.getAnyDeclaration(project, this) as PsiNameIdentifierOwner).nameIdentifier!!.text val isNullable = TypeUtils.isNullableType(type) val builtIns = builtIns val typeClass = type.constructor.declarationDescriptor var text = when { typeClass == builtIns.byte || typeClass == builtIns.short || typeClass == builtIns.int -> ref KotlinBuiltIns.isArrayOrPrimitiveArray(type) -> { val canUseArrayContentFunctions = targetClass.canUseArrayContentFunctions() val shouldWrapInLet = isNullable && !canUseArrayContentFunctions val hashCodeArg = if (shouldWrapInLet) "it" else ref val hashCodeCall = generateArrayHashCodeCall(this, canUseArrayContentFunctions, hashCodeArg) if (shouldWrapInLet) "$ref?.let { $hashCodeCall }" else hashCodeCall } else -> if (isNullable) "$ref?.hashCode()" else "$ref.hashCode()" } if (isNullable) { text += " ?: 0" if (parenthesesNeeded) { text = "($text)" } } return text } with(info) { if (!needHashCode) return null val superHashCode = classDescriptor.getSuperClassOrAny().findDeclaredHashCode(true)!! val hashCodeFun = generateFunctionSkeleton(superHashCode, targetClass) val builtins = superHashCode.builtIns val propertyIterator = variablesForHashCode.iterator() val initialValue = when { !builtins.isMemberOfAny(superHashCode) -> "super.hashCode()" propertyIterator.hasNext() -> propertyIterator.next().genVariableHashCode(false) else -> generateClassLiteral(targetClass) + ".hashCode()" } val bodyText = if (propertyIterator.hasNext()) { val validator = CollectingNameValidator(variablesForEquals.map { it.name.asString().quoteIfNeeded() }) val resultVarName = Fe10KotlinNameSuggester.suggestNameByName("result", validator) StringBuilder().apply { append("var $resultVarName = $initialValue\n") propertyIterator.forEach { append("$resultVarName = 31 * $resultVarName + ${it.genVariableHashCode(true)}\n") } append("return $resultVarName") }.toString() } else "return $initialValue" hashCodeFun.replaceBody { KtPsiFactory(project).createBlock(bodyText) } return hashCodeFun } } override fun generateMembers(project: Project, editor: Editor?, info: Info): List<KtDeclaration> { val targetClass = info.classDescriptor.source.getPsi() as KtClass val prototypes = ArrayList<KtDeclaration>(2) .apply { addIfNotNull(generateEquals(project, info, targetClass)) addIfNotNull(generateHashCode(project, info, targetClass)) } val anchor = with(targetClass.declarations) { lastIsInstanceOrNull<KtNamedFunction>() ?: lastOrNull() } return insertMembersAfterAndReformat(editor, targetClass, prototypes, anchor) } }
apache-2.0
ff1443f6478e883e6b5980935c751d12
45.862385
158
0.644218
5.524153
false
false
false
false
GunoH/intellij-community
python/src/com/jetbrains/python/statistics/PyPackageUsagesCollector.kt
8
3117
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.jetbrains.python.statistics import com.intellij.internal.statistic.beans.MetricEvent import com.intellij.internal.statistic.eventLog.EventLogGroup import com.intellij.internal.statistic.eventLog.events.EventFields import com.intellij.internal.statistic.eventLog.validator.ValidationResultType import com.intellij.internal.statistic.eventLog.validator.rules.EventContext import com.intellij.internal.statistic.eventLog.validator.rules.impl.CustomValidationRule import com.intellij.internal.statistic.service.fus.collectors.ProjectUsagesCollector import com.intellij.openapi.progress.ProgressManager import com.intellij.openapi.project.Project import com.jetbrains.extensions.getSdk import com.jetbrains.python.packaging.PyPIPackageCache import com.jetbrains.python.packaging.PyPackageManager import com.jetbrains.python.statistics.PyPackageVersionUsagesCollector.Companion.PACKAGE_FIELD import com.jetbrains.python.statistics.PyPackageVersionUsagesCollector.Companion.PACKAGE_VERSION_FIELD import com.jetbrains.python.statistics.PyPackageVersionUsagesCollector.Companion.PYTHON_PACKAGE_INSTALLED /** * Reports usages of packages and versions */ class PyPackageVersionUsagesCollector : ProjectUsagesCollector() { override fun getMetrics(project: Project) = getPackages(project) override fun requiresReadAccess(): Boolean = true override fun getGroup(): EventLogGroup = GROUP companion object { private val GROUP = EventLogGroup("python.packages", 3) //full list is stored in metadata, see FUS-1218 for more details val PACKAGE_FIELD = EventFields.String("package", emptyList()) val PACKAGE_VERSION_FIELD = EventFields.StringValidatedByRegexp("package_version", "version") val PYTHON_PACKAGE_INSTALLED = registerPythonSpecificEvent(GROUP, "python_package_installed", PACKAGE_FIELD, PACKAGE_VERSION_FIELD) } } private fun getPackages(project: Project): Set<MetricEvent> { val result = HashSet<MetricEvent>() val pypiPackages = PyPIPackageCache.getInstance() for (module in project.modules) { val sdk = module.getSdk() ?: continue val usageData = getPythonSpecificInfo(sdk) PyPackageManager.getInstance(sdk).getRequirements(module).orEmpty() .filter { pypiPackages.containsPackage(it.name) } .forEach { req -> ProgressManager.checkCanceled() val version = req.versionSpecs.firstOrNull()?.version?.trim() ?: "unknown" val data = ArrayList(usageData) // Not to calculate interpreter on each call data.add(PACKAGE_FIELD.with(req.name)) data.add(PACKAGE_VERSION_FIELD.with(version)) result.add(PYTHON_PACKAGE_INSTALLED.metric(data)) } } return result } class PyPackageUsagesValidationRule : CustomValidationRule() { override fun getRuleId(): String = "python_packages" override fun doValidate(data: String, context: EventContext) = if (PyPIPackageCache.getInstance().containsPackage(data)) ValidationResultType.ACCEPTED else ValidationResultType.REJECTED }
apache-2.0
4f3776012d0c5cba3f0c76f1937eea67
46.969231
135
0.792429
4.543732
false
false
false
false
GunoH/intellij-community
plugins/kotlin/idea/tests/test/org/jetbrains/kotlin/idea/quickfix/CommonIntentionActionsParametersTest.kt
2
7521
// 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 import com.intellij.lang.jvm.actions.* import com.intellij.lang.jvm.types.JvmType import com.intellij.psi.PsiType import com.intellij.testFramework.fixtures.LightPlatformCodeInsightFixtureTestCase import org.jetbrains.kotlin.idea.test.KotlinWithJdkAndRuntimeLightProjectDescriptor import org.jetbrains.uast.UMethod import org.junit.internal.runners.JUnit38ClassRunner import org.junit.runner.RunWith @RunWith(JUnit38ClassRunner::class) class CommonIntentionActionsParametersTest : LightPlatformCodeInsightFixtureTestCase() { override fun getProjectDescriptor() = KotlinWithJdkAndRuntimeLightProjectDescriptor.getInstanceFullJdk() override fun setUp() { super.setUp() myFixture.configureByText("Anno.kt", "annotation class Anno(val i: Int)") myFixture.configureByText("ClassRef.kt", "annotation class ClassRef(val klass: KClass<*>)") myFixture.configureByText("Root.kt", "annotation class Root(val children: Array<Child>") myFixture.configureByText("Child.kt", "annotation class Child(val s: String)") } fun testSetParameters() { myFixture.configureByText( "foo.kt", """ class Foo { fun ba<caret>r() {} } """.trimIndent() ) myFixture.launchAction( createChangeParametersActions( myFixture.atCaret<UMethod>().javaPsi, setMethodParametersRequest( linkedMapOf<String, JvmType>( "i" to PsiType.INT, "file" to PsiType.getTypeByName("java.io.File", project, myFixture.file.resolveScope) ).entries ) ).findWithText("Change method parameters to '(i: Int, file: File)'") ) myFixture.checkResult( """ import java.io.File class Foo { fun bar(i: Int, file: File) {} } """.trimIndent(), true ) } fun testSetConstructorParameters() { myFixture.configureByText( "foo.kt", """ class Foo(<caret>) { } """.trimIndent() ) val action = createChangeParametersActions( myFixture.atCaret<UMethod>().javaPsi, setMethodParametersRequest( linkedMapOf<String, JvmType>( "i" to PsiType.INT, "file" to PsiType.getTypeByName("java.io.File", project, myFixture.file.resolveScope) ).entries ) ).find { it.text.contains("Change signature of Foo") } if (action == null) fail("Change signature intention not found") myFixture.launchAction(action!!) myFixture.checkResult( """ import java.io.File class Foo(i: Int, file: File) { } """.trimIndent(), true ) } fun testAddParameterToTheEnd() { myFixture.configureByText( "foo.kt", """ class Foo { fun ba<caret>r(@Anno(3) a: Int) {} } """.trimIndent() ) runParametersTransformation("Change method parameters to '(a: Int, file: File)'") { currentParameters -> currentParameters + expectedParameter( PsiType.getTypeByName("java.io.File", project, myFixture.file.resolveScope), "file", listOf(annotationRequest("Anno", intAttribute("i", 8))) ) } myFixture.checkResult( """ import java.io.File class Foo { fun bar(@Anno(3) a: Int, @Anno(i = 8) file: File) {} } """.trimIndent(), true ) } fun testAddParameterToTheBeginning() { myFixture.configureByText( "foo.kt", """ class Foo { fun ba<caret>r(@Anno(3) a: Int) {} } """.trimIndent() ) runParametersTransformation("Change method parameters to '(file: File, a: Int)'") { currentParameters -> listOf( expectedParameter( PsiType.getTypeByName("java.io.File", project, myFixture.file.resolveScope), "file", listOf(annotationRequest("Anno", intAttribute("i", 8))) ) ) + currentParameters } myFixture.checkResult( """ import java.io.File class Foo { fun bar(@Anno(i = 8) file: File, @Anno(3) a: Int) {} } """.trimIndent(), true ) } fun testReplaceInTheMiddle() { myFixture.configureByText( "foo.kt", """ class Foo { fun ba<caret>r(@Anno(1) a: Int, @Anno(2) b: Int, @Anno(3) c: Int) {} } """.trimIndent() ) runParametersTransformation("Change method parameters to '(a: Int, file: File, c: Int)'") { currentParameters -> ArrayList<ExpectedParameter>(currentParameters).apply { this[1] = expectedParameter( PsiType.getTypeByName("java.io.File", project, myFixture.file.resolveScope), "file", listOf(annotationRequest("Anno", intAttribute("i", 8))) ) } } myFixture.checkResult( """ import java.io.File class Foo { fun bar(@Anno(1) a: Int, @Anno(i = 8) file: File, @Anno(3) c: Int) {} } """.trimIndent(), true ) } fun testChangeTypeWithComplexAnnotations() { myFixture.configureByText( "foo.kt", """ class Foo { fun ba<caret>r(@Anno(1) @Root([Child("a"), Child("b")]) a: Int) {} } """.trimIndent() ) runParametersTransformation("Change method parameters to '(a: Long)'") { currentParameters -> ArrayList<ExpectedParameter>(currentParameters).apply { this[0] = expectedParameter(PsiType.LONG, this[0].semanticNames.first(), this[0].expectedAnnotations) } } myFixture.checkResult( """ class Foo { fun bar(@Anno(i = 1) @Root(children = [Child(s = "a"), Child(s = "b")]) a: Long) {} } """.trimIndent(), true ) } private fun runParametersTransformation( actionName: String, transformation: (List<ChangeParametersRequest.ExistingParameterWrapper>) -> List<ExpectedParameter> ) { val psiMethod = myFixture.atCaret<UMethod>().javaPsi val currentParameters = psiMethod.parameters.map { ChangeParametersRequest.ExistingParameterWrapper(it) } myFixture.launchAction( createChangeParametersActions( psiMethod, SimpleChangeParametersRequest( transformation(currentParameters) ) ).findWithText(actionName) ) } } private class SimpleChangeParametersRequest(private val list: List<ExpectedParameter>) : ChangeParametersRequest { override fun getExpectedParameters(): List<ExpectedParameter> = list override fun isValid(): Boolean = true }
apache-2.0
9a1c6a65379f3b2f1e11291300fa8b1e
32.136564
158
0.555777
5.024048
false
false
false
false
GunoH/intellij-community
python/src/com/jetbrains/python/codeInsight/mlcompletion/prev2calls/AssignmentVisitor.kt
12
3363
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.jetbrains.python.codeInsight.mlcompletion.prev2calls import com.intellij.codeInsight.completion.CompletionUtilCore import com.intellij.psi.PsiElement import com.jetbrains.python.codeInsight.mlcompletion.PyMlCompletionHelpers import com.jetbrains.python.psi.* class AssignmentVisitor(private val borderOffset: Int, private val scope: PsiElement, private val fullNames: MutableMap<String, String>) : PyRecursiveElementVisitor() { data class QualifierAndReference(val qualifier: String, val reference: String) val arrPrevCalls = ArrayList<QualifierAndReference>() override fun visitPyReferenceExpression(node: PyReferenceExpression) { super.visitPyReferenceExpression(node) if (node.textOffset > borderOffset) return val (resolvedExpression, resolvedPrefix) = getResolvedExpression(node) if (node.parent !is PyCallExpression && CompletionUtilCore.DUMMY_IDENTIFIER_TRIMMED !in resolvedExpression && ("." !in resolvedExpression || resolvedPrefix == resolvedExpression)) return val qualifier = resolvedExpression.substringBeforeLast(".", "") val reference = resolvedExpression.substringAfterLast(".") arrPrevCalls.add(QualifierAndReference(qualifier, reference)) } override fun visitPyWithStatement(node: PyWithStatement) { if (node.textOffset > borderOffset) return node.withItems.filter { it.expression != null && it.target != null }.forEach { fullNames[it.target!!.text] = getResolvedExpression(it.expression).resolvedExpression } super.visitPyWithStatement(node) } override fun visitPyAssignmentStatement(node: PyAssignmentStatement) { if (node.textOffset > borderOffset) return super.visitPyAssignmentStatement(node) node.targetsToValuesMapping.forEach { val left = it.first val right = it.second if (left is PyTargetExpression) { val leftName = PyMlCompletionHelpers.getQualifiedComponents(left).joinToString(".") val rightName = getResolvedExpression(right).resolvedExpression if (rightName.isNotEmpty() && leftName.isNotEmpty()) { fullNames[leftName] = rightName } } } } data class ResolvedExpression(val resolvedExpression: String = "", val resolvedPrefix: String = "") private fun getResolvedExpression(node: PyExpression?): ResolvedExpression { if (node == null) return ResolvedExpression() val components = PyMlCompletionHelpers.getQualifiedComponents(node) for (i in components.indices) { val firstN = i + 1 val prefix = components.take(firstN).joinToString(".") fullNames[prefix]?.let { resolvedPrefix -> val postfix = if (firstN < components.size) components.takeLast(components.size - firstN).joinToString(separator=".", prefix=".") else "" return ResolvedExpression("$resolvedPrefix$postfix", resolvedPrefix) } } return ResolvedExpression(components.joinToString(".")) } override fun visitPyFunction(node: PyFunction) { if (node == scope) super.visitPyFunction(node) } override fun visitPyClass(node: PyClass) { if (node == scope) super.visitPyClass(node) } }
apache-2.0
65530060f717d1046434a9bb34a48e29
40.02439
140
0.72138
4.73662
false
false
false
false
siosio/intellij-community
plugins/github/src/org/jetbrains/plugins/github/pullrequest/comment/ui/GHSubmittableTextFieldModel.kt
1
1330
// 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.github.pullrequest.comment.ui import com.intellij.collaboration.async.CompletableFutureUtil.completionOnEdt import com.intellij.collaboration.async.CompletableFutureUtil.errorOnEdt import com.intellij.collaboration.async.CompletableFutureUtil.successOnEdt import com.intellij.collaboration.ui.codereview.timeline.comment.SubmittableTextFieldModelBase import com.intellij.openapi.project.Project import org.intellij.plugins.markdown.lang.MarkdownLanguage import java.util.concurrent.CompletableFuture open class GHSubmittableTextFieldModel( project: Project, initialText: String, private val submitter: (String) -> CompletableFuture<*> ) : SubmittableTextFieldModelBase(project, initialText, MarkdownLanguage.INSTANCE) { constructor(project: Project, submitter: (String) -> CompletableFuture<*>) : this(project, "", submitter) override fun submit() { if (isBusy) return isBusy = true content.isReadOnly = true submitter(content.text).successOnEdt { content.isReadOnly = false content.clear() }.errorOnEdt { content.isReadOnly = false error = it }.completionOnEdt { isBusy = false } } }
apache-2.0
7e197304895eba724628ba7ea6d82ac1
37.028571
140
0.77594
4.666667
false
false
false
false
jwren/intellij-community
platform/build-scripts/groovy/org/jetbrains/intellij/build/impl/SVGPreBuilder.kt
1
2692
// 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.intellij.build.impl import org.jetbrains.intellij.build.BuildContext import org.jetbrains.intellij.build.BuildOptions import org.jetbrains.intellij.build.impl.TracerManager.spanBuilder import java.nio.file.Files import java.nio.file.Path import java.util.concurrent.ForkJoinTask /* Please do not convert this to direct call of ImageSvgPreCompiler since it brings too much modules to build scripts classpath, and it'll be too slow to compile by jps-bootstrap Please do not call it via constructing special classloader, since external process does not take too much time, and it's much easier to reason about */ object SVGPreBuilder { fun createPrebuildSvgIconsTask(context: BuildContext): ForkJoinTask<*>? { return BuildHelper.createSkippableTask(spanBuilder("prebuild SVG icons"), BuildOptions.SVGICONS_PREBUILD_STEP, context) { val requestBuilder = StringBuilder() // build for all modules - so, icon db will be suitable for any non-bundled plugin for (module in context.project.modules) { requestBuilder.append(context.getModuleOutputDir(module).toString()).append("\n") } val requestFile = context.paths.tempDir.resolve("svg-prebuild-request.txt") Files.createDirectories(requestFile.parent) Files.writeString(requestFile, requestBuilder) val svgToolClasspath = context.getModuleRuntimeClasspath(module = context.findRequiredModule("intellij.platform.images.build"), forTests = false) runSvgTool(context = context, svgToolClasspath = svgToolClasspath, requestFile = requestFile) } } private fun runSvgTool(context: BuildContext, svgToolClasspath: List<String>, requestFile: Path) { val dbDir = context.paths.tempDir.resolve("icons.db.dir") BuildHelper.runJava( context, "org.jetbrains.intellij.build.images.ImageSvgPreCompiler", listOf(dbDir.toString(), requestFile.toString()) + context.getApplicationInfo().svgProductIcons, listOf("-Xmx1024m"), svgToolClasspath ) Files.newDirectoryStream(dbDir).use { dirStream -> var found = false for (file in dirStream) { if (!Files.isRegularFile(file)) { context.messages.error("SVG tool: output must be a regular file: $file") } found = true context.addDistFile(java.util.Map.entry(file, "bin/icons")) } if (!found) { context.messages.error("SVG tool: after running SVG prebuild it must be a least one file at $dbDir") } } } }
apache-2.0
48aa402225935119b91115fcef816f1e
41.746032
133
0.715825
4.334944
false
false
false
false
smmribeiro/intellij-community
plugins/git4idea/src/git4idea/fetch/GitFetchSupportImpl.kt
1
14260
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package git4idea.fetch import com.intellij.dvcs.MultiMessage import com.intellij.dvcs.MultiRootMessage import com.intellij.notification.NotificationType import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.progress.EmptyProgressIndicator import com.intellij.openapi.progress.ProcessCanceledException import com.intellij.openapi.progress.ProgressManager import com.intellij.openapi.progress.util.BackgroundTaskUtil import com.intellij.openapi.project.Project import com.intellij.openapi.util.NlsSafe import com.intellij.openapi.util.registry.Registry import com.intellij.openapi.util.text.HtmlBuilder import com.intellij.openapi.util.text.HtmlChunk import com.intellij.openapi.vcs.VcsException import com.intellij.openapi.vcs.VcsNotifier import com.intellij.openapi.vcs.VcsNotifier.STANDARD_NOTIFICATION import com.intellij.openapi.vcs.changes.actions.VcsStatisticsCollector import com.intellij.util.concurrency.AppExecutorUtil import git4idea.GitNotificationIdsHolder import git4idea.GitUtil.findRemoteByName import git4idea.GitUtil.mention import git4idea.commands.Git import git4idea.commands.GitAuthenticationGate import git4idea.commands.GitAuthenticationListener.GIT_AUTHENTICATION_SUCCESS import git4idea.commands.GitImpl import git4idea.commands.GitRestrictingAuthenticationGate import git4idea.config.GitConfigUtil import git4idea.i18n.GitBundle import git4idea.repo.GitRemote import git4idea.repo.GitRemote.ORIGIN import git4idea.repo.GitRepository import org.jetbrains.annotations.Nls import org.jetbrains.annotations.NonNls import java.util.concurrent.CancellationException import java.util.concurrent.ExecutionException import java.util.concurrent.Future import java.util.concurrent.atomic.AtomicInteger import java.util.regex.Pattern private val LOG = logger<GitFetchSupportImpl>() private val PRUNE_PATTERN = Pattern.compile("\\s*x\\s*\\[deleted\\].*->\\s*(\\S*)") // x [deleted] (none) -> origin/branch private const val MAX_SSH_CONNECTIONS = 10 // by default SSH server has a limit of 10 multiplexed ssh connection internal class GitFetchSupportImpl(private val project: Project) : GitFetchSupport { private val git get() = Git.getInstance() as GitImpl private val progressManager get() = ProgressManager.getInstance() private val fetchQueue = GitRemoteOperationQueueImpl() private val fetchRequestCounter = AtomicInteger() override fun getDefaultRemoteToFetch(repository: GitRepository): GitRemote? { val remotes = repository.remotes return when { remotes.isEmpty() -> null remotes.size == 1 -> remotes.first() else -> { // this emulates behavior of the native `git fetch`: // if current branch doesn't give a hint, then return "origin"; if there is no "origin", don't guess and fail repository.currentBranch?.findTrackedBranch(repository)?.remote ?: findRemoteByName(repository, ORIGIN) } } } override fun fetchDefaultRemote(repositories: Collection<GitRepository>): GitFetchResult { val remotesToFetch = mutableListOf<RemoteRefCoordinates>() for (repository in repositories) { val remote = getDefaultRemoteToFetch(repository) if (remote != null) remotesToFetch.add(RemoteRefCoordinates(repository, remote)) else LOG.info("No remote to fetch found in $repository") } return fetch(remotesToFetch) } override fun fetchAllRemotes(repositories: Collection<GitRepository>): GitFetchResult { val remotesToFetch = mutableListOf<RemoteRefCoordinates>() for (repository in repositories) { if (repository.remotes.isEmpty()) { LOG.info("No remote to fetch found in $repository") } else { for (remote in repository.remotes) { remotesToFetch.add(RemoteRefCoordinates(repository, remote)) } } } return fetch(remotesToFetch) } override fun fetch(repository: GitRepository, remote: GitRemote): GitFetchResult { return fetch(listOf(RemoteRefCoordinates(repository, remote))) } override fun fetch(repository: GitRepository, remote: GitRemote, refspec: @NonNls String): GitFetchResult { return fetch(listOf(RemoteRefCoordinates(repository, remote, refspec))) } private fun fetch(arguments: List<RemoteRefCoordinates>): GitFetchResult { try { fetchRequestCounter.incrementAndGet() return withIndicator { val activity = VcsStatisticsCollector.FETCH_ACTIVITY.started(project) val tasks = fetchInParallel(arguments) val results = waitForFetchTasks(tasks) val mergedResults = mutableMapOf<GitRepository, RepoResult>() val succeedResults = mutableListOf<SingleRemoteResult>() for (result in results) { val res = mergedResults[result.repository] mergedResults[result.repository] = mergeRepoResults(res, result) if (result.success()) succeedResults.add(result) } val successFetchesMap = succeedResults.groupBy({ it.repository }, { it.remote }) if (successFetchesMap.isNotEmpty()) { GitFetchHandler.afterSuccessfulFetch(project, successFetchesMap, progressManager.progressIndicator ?: EmptyProgressIndicator()) } activity.finished() FetchResultImpl(project, VcsNotifier.getInstance(project), mergedResults) } } finally { fetchRequestCounter.decrementAndGet() } } private fun mergeRepoResults(firstResult: RepoResult?, secondResult: SingleRemoteResult): RepoResult { if (firstResult == null) { return RepoResult(mapOf(secondResult.remote to secondResult)) } else { return RepoResult(firstResult.results + (secondResult.remote to secondResult)) } } override fun isFetchRunning() = fetchRequestCounter.get() > 0 private fun fetchInParallel(remotes: List<RemoteRefCoordinates>): List<FetchTask> { val tasks = mutableListOf<FetchTask>() val maxThreads = getMaxThreads(remotes.mapTo(HashSet()) { it.repository }, remotes.size) LOG.debug("Fetching $remotes using $maxThreads threads") val executor = AppExecutorUtil.createBoundedApplicationPoolExecutor("GitFetch pool", maxThreads) val commonIndicator = progressManager.progressIndicator ?: EmptyProgressIndicator() val authenticationGate = GitRestrictingAuthenticationGate() for ((repository, remote, refspec) in remotes) { LOG.debug("Fetching $remote in $repository") val future: Future<SingleRemoteResult> = executor.submit<SingleRemoteResult> { commonIndicator.checkCanceled() lateinit var result: SingleRemoteResult ProgressManager.getInstance().executeProcessUnderProgress({ commonIndicator.checkCanceled() result = fetchQueue.executeForRemote(repository, remote) { doFetch(repository, remote, refspec, authenticationGate) } }, commonIndicator) result } tasks.add(FetchTask(repository, remote, future)) } return tasks } private fun getMaxThreads(repositories: Collection<GitRepository>, numberOfRemotes: Int): Int { val config = Registry.intValue("git.parallel.fetch.threads") val maxThreads = when { config > 0 -> config config == -1 -> Runtime.getRuntime().availableProcessors() config == -2 -> numberOfRemotes config == -3 -> Math.min(numberOfRemotes, Runtime.getRuntime().availableProcessors() * 2) else -> 1 } if (isStoreCredentialsHelperUsed(repositories)) { return 1 } return Math.min(maxThreads, MAX_SSH_CONNECTIONS) } private fun isStoreCredentialsHelperUsed(repositories: Collection<GitRepository>): Boolean { return repositories.any { GitConfigUtil.getValue(project, it.root, "credential.helper").equals("store", ignoreCase = true) } } private fun waitForFetchTasks(tasks: List<FetchTask>): List<SingleRemoteResult> { val results = mutableListOf<SingleRemoteResult>() for (task in tasks) { try { results.add(task.future.get()) } catch (e: CancellationException) { throw ProcessCanceledException(e) } catch (e: InterruptedException) { throw ProcessCanceledException(e) } catch (e: ExecutionException) { if (e.cause is ProcessCanceledException) throw e.cause as ProcessCanceledException results.add(SingleRemoteResult(task.repository, task.remote, e.cause?.message ?: GitBundle.message("error.dialog.title"), emptyList())) LOG.error(e) } } return results } private fun <T> withIndicator(operation: () -> T): T { val indicator = progressManager.progressIndicator val prevText = indicator?.text indicator?.text = GitBundle.message("git.fetch.progress") try { return operation() } finally { indicator?.text = prevText } } private fun doFetch(repository: GitRepository, remote: GitRemote, refspec: String?, authenticationGate: GitAuthenticationGate? = null) : SingleRemoteResult { val recurseSubmodules = "--recurse-submodules=no" val params = if (refspec == null) arrayOf(recurseSubmodules) else arrayOf(refspec, recurseSubmodules) val result = git.fetch(repository, remote, emptyList(), authenticationGate, *params) val pruned = result.output.mapNotNull { getPrunedRef(it) } if (result.success()) { BackgroundTaskUtil.syncPublisher(repository.project, GIT_AUTHENTICATION_SUCCESS).authenticationSucceeded(repository, remote) repository.update() } val error = if (result.success()) null else result.errorOutputAsJoinedString return SingleRemoteResult(repository, remote, error, pruned) } private fun getPrunedRef(line: String): String? { val matcher = PRUNE_PATTERN.matcher(line) return if (matcher.matches()) matcher.group(1) else null } private data class RemoteRefCoordinates(val repository: GitRepository, val remote: GitRemote, val refspec: String? = null) private class FetchTask(val repository: GitRepository, val remote: GitRemote, val future: Future<SingleRemoteResult>) private class RepoResult(val results: Map<GitRemote, SingleRemoteResult>) { fun totallySuccessful() = results.values.all { it.success() } fun error(): @Nls String { val errorMessage = multiRemoteMessage(true) for ((remote, result) in results) { if (result.error != null) errorMessage.append(remote, result.error) } return errorMessage.asString() } fun prunedRefs(): @NlsSafe String { val prunedRefs = multiRemoteMessage(false) for ((remote, result) in results) { if (result.prunedRefs.isNotEmpty()) prunedRefs.append(remote, result.prunedRefs.joinToString("\n")) } return prunedRefs.asString() } /* For simplicity, remote and repository results are merged separately. It means that they are not merged, if two repositories have two remotes, and then fetch succeeds for the first remote in both repos, and fails for the second remote in both repos. Such cases are rare, and can be handled when actual problem is reported. */ private fun multiRemoteMessage(remoteInPrefix: Boolean) = MultiMessage(results.keys, GitRemote::getName, GitRemote::getName, remoteInPrefix) } private class SingleRemoteResult(val repository: GitRepository, val remote: GitRemote, val error: @Nls String?, val prunedRefs: List<String>) { fun success() = error == null } private class FetchResultImpl(val project: Project, val vcsNotifier: VcsNotifier, val results: Map<GitRepository, RepoResult>) : GitFetchResult { private val isFailed = results.values.any { !it.totallySuccessful() } override fun showNotification() { doShowNotification() } override fun showNotificationIfFailed(): Boolean { if (isFailed) doShowNotification(null) return !isFailed } override fun showNotificationIfFailed(title: @Nls String): Boolean { if (isFailed) doShowNotification(title) return !isFailed } private fun doShowNotification(failureTitle: @Nls String? = null) { val type = if (!isFailed) NotificationType.INFORMATION else NotificationType.ERROR val message = buildMessage(failureTitle) val notification = STANDARD_NOTIFICATION.createNotification(message, type) notification.setDisplayId(if (!isFailed) GitNotificationIdsHolder.FETCH_RESULT else GitNotificationIdsHolder.FETCH_RESULT_ERROR) vcsNotifier.notify(notification) } override fun throwExceptionIfFailed() { if (isFailed) throw VcsException(buildMessage(null)) } private fun buildMessage(failureTitle: @Nls String?): @Nls String { val roots = results.keys.map { it.root } val errorMessage = MultiRootMessage(project, roots, true) val prunedRefs = MultiRootMessage(project, roots) val failed = results.filterValues { !it.totallySuccessful() } for ((repo, result) in failed) { errorMessage.append(repo.root, result.error()) } for ((repo, result) in results) { prunedRefs.append(repo.root, result.prunedRefs()) } val sb = HtmlBuilder() if (!isFailed) { sb.append(HtmlChunk.text(GitBundle.message("notification.title.fetch.success")).bold()) } else { sb.append(HtmlChunk.text(failureTitle ?: GitBundle.message("notification.title.fetch.failure")).bold()) if (failed.size != roots.size) { sb.append(mention(failed.keys)) } } appendDetails(sb, errorMessage) appendDetails(sb, prunedRefs) return sb.toString() } private fun appendDetails(sb: HtmlBuilder, details: MultiRootMessage) { val text = details.asString() if (text.isNotEmpty()) { sb.br().append(text) } } } }
apache-2.0
f0d8fab99dd7269def01186f0648cf1e
40.213873
145
0.704769
4.66623
false
false
false
false
smmribeiro/intellij-community
platform/lang-api/src/com/intellij/execution/runToolbar/RunToolbarRunProcess.kt
9
915
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.execution.runToolbar import com.intellij.execution.ExecutionBundle import com.intellij.openapi.wm.ToolWindowId import com.intellij.ui.JBColor class RunToolbarRunProcess : RunToolbarProcess { override val ID: String = ToolWindowId.RUN override val executorId: String = ToolWindowId.RUN override val name: String = ExecutionBundle.message("run.toolbar.running") override val shortName: String = ExecutionBundle.message("run.toolbar.run") override val actionId: String = "RunToolbarRunProcess" override val moreActionSubGroupName: String = "RunToolbarRunMoreActionSubGroupName" override val showInBar: Boolean = true override val pillColor: JBColor = JBColor.namedColor("RunToolbar.Run.activeBackground", JBColor(0xC7FFD1, 0x235423)) }
apache-2.0
bcd827bc0b02da2f5c654d73b0d27f36
44.8
140
0.803279
4.316038
false
false
false
false
tooploox/android-versioning-plugin
src/main/kotlin/versioning/android/DefaultVersionNamingStrategy.kt
1
1201
package versioning.android import versioning.git.Repository import versioning.model.RevisionVersionInfo class DefaultVersionNamingStrategy( repository: Repository ) : VersionNamingStrategy { override val versionCode: Int override val versionName: String init { try { val revisionVersionInfo = RevisionVersionInfo.fromGitDescribe(repository.describe()) val version = revisionVersionInfo.lastVersion versionCode = version.major * 10000 + version.minor * 1000 + version.patch * 100 + revisionVersionInfo.commitsSinceLastTag val versionNameBuilder = StringBuilder() versionNameBuilder.append("${version.major}.${version.minor}.${version.patch}") if (revisionVersionInfo.commitsSinceLastTag > 0) { versionNameBuilder.append("-${revisionVersionInfo.commitsSinceLastTag}") versionNameBuilder.append("-${repository.currentBranchName()}") versionNameBuilder.append("-${revisionVersionInfo.currentRevisionSha!!}") } versionName = versionNameBuilder.toString() } finally { repository.close() } } }
apache-2.0
51da1a8309d973bc1a5d439500daa668
32.361111
134
0.671107
5.746411
false
false
false
false
NlRVANA/Unity
app/src/test/java/com/zwq65/unity/algorithm/unionfind/LeetCode959.kt
1
2233
package com.zwq65.unity.algorithm.unionfind import org.junit.Test /** * ================================================ * <p> * <a href="https://leetcode-cn.com/problems/regions-cut-by-slashes">959. 由斜杠划分区域</a>. * Created by NIRVANA on 2019/7/15. * Contact with <[email protected]> * ================================================ */ class LeetCode959 { @Test fun test() { val array = arrayOf("/\\", "\\/") val number = regionsBySlashes(array) print("number:$number") } private fun regionsBySlashes(grid: Array<String>): Int { val size = grid.size val uf = UF(4 * size * size) for (i in 0 until size) { for (j in 0 until size) { val root = 4 * (size * i + j) val charr = grid[i][j] if (charr != '/') { uf.union(root + 1, root + 0) uf.union(root + 3, root + 2) } if (charr != '\\') { uf.union(root + 1, root + 2) uf.union(root + 3, root + 0) } if (i != size - 1) { // 如果不是最后一行,则向下归并 uf.union(root + 2, (root + 4 * size) + 0) } if (j != size - 1) { // 如果不是最后一列,则向右归并 uf.union(root + 1, (root + 4) + 3) } } } var answer = 0 for (i in 0 until 4 * size * size) { if (i == uf.find(i)) { answer++ } } return answer } class UF(size: Int) { private var parent = IntArray(size) init { //初始化:parent指向本身 for (i in 0 until size) { parent[i] = i } } fun find(x: Int): Int { return if (x == parent[x]) { x } else { parent[x] = find(parent[x]) find(parent[x]) } } fun union(x: Int, y: Int) { parent[find(x)] = parent[find(y)] } } }
apache-2.0
98eedc77c702490bb68b4936b72d194f
24.282353
86
0.375058
3.776801
false
false
false
false
intrigus/jtransc
jtransc-main/test/big/HelloWorldKotlinTest.kt
1
5226
package big import com.jtransc.annotation.JTranscAddHeader import com.jtransc.annotation.JTranscInline import com.jtransc.annotation.JTranscMethodBody import com.jtransc.io.JTranscSyncIO object HelloWorldKotlinTest { @JvmStatic fun main(args: Array<String>) { PSP2.main(args) } } //@JTranscAddHeader(target = "cpp", value = *arrayOf("extern \"C\" {", "#include <psp2/ctrl.h>", "#include <psp2/touch.h>", "#include <psp2/display.h>", "#include <psp2/gxm.h>", "#include <psp2/types.h>", "#include <psp2/moduleinfo.h>", "#include <psp2/kernel/processmgr.h>", "}")) //@JTranscAddLibraries(target = "cpp", value = *arrayOf("c", "SceKernel_stub", "SceDisplay_stub", "SceGxm_stub", "SceCtrl_stub", "SceTouch_stub")) //@JTranscAddFile(target = "cpp", prepend = "draw_include.c", process = true) //@JTranscAddFlags(target = "cpp", value = { // "-Wl,-q" //}) //-lc -lSceKernel_stub -lSceDisplay_stub -lSceGxm_stub -lSceCtrl_stub -lSceTouch_stub @Suppress("unused", "UNUSED_PARAMETER") @JTranscAddHeader(target = "cpp", value = """ void input_read() { } int pad_buttons() { return 0; } void font_draw_string(int x, int y, int color, char *str) { printf("%s\n", str); } void sceKernelExitProcess(int code) {} void sceDisplayWaitVblankStart() { } void init_video() { } void end_video() { } void clear_screen() { } void swap_buffers() { } void draw_pixel(int x, int y, int color) {} void draw_rectangle(int x, int y, int width, int height, int color) { printf("draw_rectangle:%d,%d,%d,%d,%d\n", x, y, width, height, color); } """) object PSP2 { private val WHITE = 0xFFFFFFFF.toInt() private val RED = 0xFF0000FF.toInt() private val PINK = 0xFFFF00FF.toInt() private val YELLOW = 0xFF00FFFF.toInt() private val BLACK = 0xFF000000.toInt() @JvmStatic fun main(args: Array<String>) { val api = Api.create() println("Start!") init_video() println(api.demo()) JTranscSyncIO.impl = object : JTranscSyncIO.Impl(JTranscSyncIO.impl) { @JTranscMethodBody(target = "cpp", value = """ auto str = N::istr3(p0); std::vector<std::string> out; out.push_back(str); out.push_back(std::string("hello")); out.push_back(std::string("world")); return N::strArray(out); """) override external fun list(file: String): Array<String> } println("Start2!") var frame = 0 while (true) { clear_screen() input_read() draw_rectangle(0, 0, 100, 100, RED) draw_rectangle(100, 100, 100, 100, PINK) val str = "PSVITA HELLO WORLD FROM KOTLIN WITH JTRANSC! %d".format(frame) //val str = "PSVITA HELLO WORLD FROM KOTLIN WITH JTRANSC! " + frame font_draw_string(0, 0, YELLOW, str) font_draw_string(1, 1, BLACK, str) if (pad_buttons() and PSP2_CTRL_START != 0) break //frame_end(); swap_buffers() sceDisplayWaitVblankStart() frame++ if (frame >= 10) { break } } end_video() sceKernelExitProcess(0) } @JTranscMethodBody(target = "cpp", value = "::init_video();") @JTranscInline fun init_video() { } @JTranscMethodBody(target = "cpp", value = "::end_video();") @JTranscInline fun end_video() { } @JTranscMethodBody(target = "cpp", value = "::clear_screen();") @JTranscInline fun clear_screen() { } @JTranscMethodBody(target = "cpp", value = "::swap_buffers();") @JTranscInline fun swap_buffers() { } @JTranscMethodBody(target = "cpp", value = "::draw_pixel(p0, p1, p2);") @JTranscInline fun draw_pixel(x: Int, y: Int, color: Int) { } @JTranscMethodBody(target = "cpp", value = "::draw_rectangle(p0, p1, p2, p3, p4);") @JTranscInline fun draw_rectangle(x: Int, y: Int, w: Int, h: Int, color: Int) { println("draw_rectangle:$x,$y,$w,$h,$color") } //static int strLen(SOBJ obj); //static int strCharAt(SOBJ obj, int n); @JTranscMethodBody(target = "cpp", value = "int len = N::strLen(p3); char *temp = (char*)malloc(len + 1); memset(temp, 0, len + 1); for (int n = 0; n < len; n++) temp[n] = N::strCharAt(p3, n); ::font_draw_string(p0, p1, p2, temp); free((void*)temp);") @JTranscInline fun font_draw_string(x: Int, y: Int, color: Int, str: String) { println(str) } @JTranscMethodBody(target = "cpp", value = "::input_read();") @JTranscInline fun input_read() { } @JTranscMethodBody(target = "cpp", value = "::frame_end();") @JTranscInline fun frame_end() { } @JTranscMethodBody(target = "cpp", value = "return ::pad_buttons();") @JTranscInline fun pad_buttons(): Int { return 0 } @JTranscMethodBody(target = "cpp", value = "::sceDisplayWaitVblankStart();") @JTranscInline fun sceDisplayWaitVblankStart() { try { Thread.sleep(20L) } catch (e: InterruptedException) { e.printStackTrace() } } @JTranscMethodBody(target = "cpp", value = "::sceKernelExitProcess(p0);") @JTranscInline fun sceKernelExitProcess(value: Int) { } val PSP2_CTRL_SELECT = 0x000001 val PSP2_CTRL_START = 0x000008 val PSP2_CTRL_UP = 0x000010 val PSP2_CTRL_RIGHT = 0x000020 val PSP2_CTRL_DOWN = 0x000040 val PSP2_CTRL_LEFT = 0x000080 val PSP2_CTRL_LTRIGGER = 0x000100 val PSP2_CTRL_RTRIGGER = 0x000200 val PSP2_CTRL_TRIANGLE = 0x001000 val PSP2_CTRL_CIRCLE = 0x002000 val PSP2_CTRL_CROSS = 0x004000 val PSP2_CTRL_SQUARE = 0x008000 val PSP2_CTRL_ANY = 0x010000 }
apache-2.0
ed5c7f3f04de8ab508aa6c44b7f7a75a
26.946524
281
0.660735
2.840217
false
false
false
false
ZoranPandovski/al-go-rithms
search/binary_search/kotlin/BinarySearch.kt
1
967
class BinarySearch(private val array: IntArray) { //Search for a number in an array fun search(number: Int): Int { return binarySearch(0, array.size - 1, number) } // Returns index of x if it is present in the array, else returns -1 private fun binarySearch(start: Int, end: Int, number: Int): Int { if (start <= end) { val middle = start + (end - start) / 2 if (array[middle] == number) return middle return if (array[middle] > number) binarySearch(start, middle - 1, number) else binarySearch(middle + 1, end, number) } return -1 } } fun main(args: Array<String>) { val searchableArray = BinarySearch(intArrayOf(2, 3, 7, 8, 78, 99, 102, 5555)) val numberToFind = 102 val result = searchableArray.search(numberToFind) if (result == -1) println("Element not present") else println("Element found at index $result") }
cc0-1.0
93e184ceb70c7b4c999ba4d654ed1500
29.25
129
0.602896
3.946939
false
false
false
false
EMResearch/EvoMaster
core/src/main/kotlin/org/evomaster/core/problem/rest/resource/ResourceCluster.kt
1
8597
package org.evomaster.core.problem.rest.resource import org.evomaster.client.java.controller.api.dto.database.operations.DataRowDto import org.evomaster.core.EMConfig import org.evomaster.core.Lazy import org.evomaster.core.database.DbAction import org.evomaster.core.database.DbActionUtils import org.evomaster.core.database.SqlInsertBuilder import org.evomaster.core.database.schema.Table import org.evomaster.core.problem.rest.RestCallAction import org.evomaster.core.problem.rest.RestIndividual import org.evomaster.core.problem.util.inference.SimpleDeriveResourceBinding import org.evomaster.core.search.Action import org.evomaster.core.search.service.Randomness /** * this class is to record the identified resources in the sut, i.e., based on the 'paths' of 'OpenAPI' */ class ResourceCluster { /** * key is resource path * value is an abstract resource */ private val resourceCluster : MutableMap<String, RestResourceNode> = mutableMapOf() /** * key is table name * value is a list of existing data of PKs in DB */ private val dataInDB : MutableMap<String, MutableList<DataRowDto>> = mutableMapOf() /** * key is table name * value is the table */ private val tables : MutableMap<String, Table> = mutableMapOf() /** * init resource nodes based on [actionCluster] and [sqlInsertBuilder] * @param actionCluster specified all actions in the sut * @param sqlInsertBuilder specified the database info * @param config indicates the EM configuration which will be used to init [actionCluster] and [sqlInsertBuilder] * e.g., whether to init derived table for each of resource */ fun initResourceCluster(actionCluster : Map<String, Action>, sqlInsertBuilder: SqlInsertBuilder? = null, config: EMConfig) { if (resourceCluster.isNotEmpty()) return if (sqlInsertBuilder != null) syncDataInDb(sqlInsertBuilder) if(config.extractSqlExecutionInfo) { // reset tables based on table info in [sqlInsertBuilder] sqlInsertBuilder?.extractExistingTables(tables) } actionCluster.values.forEach { u -> if (u is RestCallAction) { val resource = resourceCluster.getOrPut(u.path.toString()) { RestResourceNode( u.path.copy(), initMode = if(config.probOfEnablingResourceDependencyHeuristics > 0.0 && config.doesApplyNameMatching) InitMode.WITH_DERIVED_DEPENDENCY else if(config.doesApplyNameMatching) InitMode.WITH_TOKEN else if (config.probOfEnablingResourceDependencyHeuristics > 0.0) InitMode.WITH_DEPENDENCY else InitMode.NONE, employNLP = config.enableNLPParser) } resource.actions.add(u) } } resourceCluster.values.forEach{it.initAncestors(resourceCluster.values.toList())} resourceCluster.values.forEach{it.init()} } fun reset(){ resourceCluster.clear() dataInDB.clear() tables.clear() } /** * derive related table for each resource node */ fun initRelatedTables(){ resourceCluster.values.forEach { r-> SimpleDeriveResourceBinding.deriveResourceToTable(r, getTableInfo()) } } /** * synchronize the existing data in database based on [sqlInsertBuilder] */ fun syncDataInDb(sqlInsertBuilder: SqlInsertBuilder?){ sqlInsertBuilder?.extractExistingPKs(dataInDB) } /** * @return all resource nodes */ fun getCluster() = resourceCluster.toMap() /** * @return all table info */ fun getTableInfo() = tables.toMap() /** * @return resource node based on the specified [action] * @param nullCheck specified whether to throw an exception when the requested resource does not exist */ fun getResourceNode(action: RestCallAction, nullCheck: Boolean = false) : RestResourceNode? = getResourceNode(action.path.toString(), nullCheck) /** * @return resource node based on the specified [key] * @param key specified the resource node to get * @param nullCheck specified whether to throw an exception when the requested resource does not exist */ fun getResourceNode(key: String, nullCheck: Boolean = false) : RestResourceNode?{ if (!nullCheck) return resourceCluster[key] return resourceCluster[key]?:throw IllegalStateException("cannot find the resource node with $key") } /** * @return existing rows of the table based on the specified [tableName] */ fun getDataInDb(tableName: String) : MutableList<DataRowDto>?{ val found = dataInDB.filterKeys { k-> k.equals(tableName, ignoreCase = true) }.keys if (found.isEmpty()) return null Lazy.assert{found.size == 1} return dataInDB.getValue(found.first()) } /** * @return table class based on specified [name] */ fun getTableByName(name : String) = tables.keys.find { it.equals(name, ignoreCase = true) }?.run { tables[this] } /** * create db actions based on specified tables, i.e., [tables] * @param tables specifies tables * @param sqlInsertBuilder is used to create dbactions * @param previous specifies the previous dbactions * @param doNotCreateDuplicatedAction specifies whether it is allowed to create duplicate db actions * @param isInsertion specifies that db actions are SELECT or INSERT * note that if there does not exist data for the table, we will employ INSERT instead of SELECT * @param randomness is employed to randomize the created actions or select an existing data * @param forceSynDataInDb specified whether to force synchronizing data. By default, we disable it since it is quite time-consuming. * * for instance, set could be A and B, and B refers to A * if [doNotCreateDuplicatedAction], the returned list would be A and B * else the return list would be A, A and B. the additional A is created for B */ fun createSqlAction(tables: List<String>, sqlInsertBuilder: SqlInsertBuilder, previous: List<DbAction>, doNotCreateDuplicatedAction: Boolean, isInsertion: Boolean = true, randomness: Randomness, forceSynDataInDb: Boolean = false, useExtraSqlDbConstraints: Boolean = false ) : MutableList<DbAction>{ val sorted = DbActionUtils.sortTable(tables.mapNotNull { getTableByName(it) }.run { if (doNotCreateDuplicatedAction) this.distinct() else this }) val added = mutableListOf<DbAction>() val preTables = previous.filter { !isInsertion || !it.representExistingData }.map { it.table.name }.toMutableList() if (!isInsertion && sorted.none { t-> (getDataInDb(t.name)?.size?: 0) > 0 }){ if (forceSynDataInDb) syncDataInDb(sqlInsertBuilder) if (sorted.none { t-> (getDataInDb(t.name)?.size?: 0) > 0 }){ return mutableListOf() } } sorted.forEach { t-> if (!doNotCreateDuplicatedAction || preTables.none { p-> p.equals(t.name, ignoreCase = true) }){ val actions = if (!isInsertion){ if ((getDataInDb(t.name)?.size ?: 0) == 0) null else{ val candidates = getDataInDb(t.name)!! val row = randomness.choose(candidates) listOf(sqlInsertBuilder.extractExistingByCols(t.name, row, useExtraSqlDbConstraints)) } } else{ sqlInsertBuilder.createSqlInsertionAction(t.name, useExtraSqlDbConstraints = useExtraSqlDbConstraints) .onEach { a -> a.doInitialize(randomness) } } if (actions != null){ //actions.forEach {it.doInitialize()} added.addAll(actions) preTables.addAll(actions.filter { !isInsertion || !it.representExistingData }.map { it.table.name }) } } } return added } fun doesCoverAll(individual: RestIndividual): Boolean{ return individual.getResourceCalls().map { it.getResolvedKey() }.toSet().size >= resourceCluster.size } }
lgpl-3.0
3d9d4c650ea51a0ba2e9505bd96a6c80
40.138756
153
0.63813
4.734031
false
true
false
false
BlueBoxWare/LibGDXPlugin
src/main/kotlin/com/gmail/blueboxware/libgdxplugin/utils/ColorsUtils.kt
1
8104
package com.gmail.blueboxware.libgdxplugin.utils import com.intellij.openapi.project.Project import com.intellij.psi.* import com.intellij.psi.search.searches.MethodReferencesSearch import com.intellij.psi.search.searches.ReferencesSearch import com.intellij.psi.util.CachedValue import com.siyeh.ig.psiutils.MethodCallUtils import org.jetbrains.kotlin.idea.intentions.callExpression import org.jetbrains.kotlin.idea.search.allScope import org.jetbrains.kotlin.psi.KtCallExpression import org.jetbrains.kotlin.psi.KtDotQualifiedExpression import org.jetbrains.kotlin.psi.KtStringTemplateExpression /* * Copyright 2018 Blue Box Ware * * 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. */ internal fun PsiMethodCallExpression.isColorsGetCall(): Boolean = isColorsCall(false) internal fun KtCallExpression.isColorsGetCall(): Boolean = isColorsCall(false) internal fun PsiMethodCallExpression.isColorsPutCall(): Boolean = isColorsCall(true) internal fun KtCallExpression.isColorsPutCall(): Boolean = isColorsCall(true) private fun PsiMethodCallExpression.isColorsCall(isPut: Boolean): Boolean { val (clazz, method) = resolveCallToStrings() ?: return false val expectedMethodName = if (isPut) "put" else "get" if (clazz == COLORS_CLASS_NAME && method == expectedMethodName) { return true } else if (clazz == OBJECT_MAP_CLASS_NAME && method == expectedMethodName) { MethodCallUtils.getQualifierMethodCall(this)?.resolveCallToStrings()?.let { (clazz2, method2) -> if (clazz2 == COLORS_CLASS_NAME && method2 == "getColors") { return true } } ((methodExpression.qualifierExpression as? PsiReferenceExpression)?.resolve() as? PsiField)?.let { psiField -> if (psiField.containingClass?.qualifiedName == COLORS_CLASS_NAME && psiField.name == "map") { return true } } } return false } internal fun KtCallExpression.isColorsCall(isPut: Boolean): Boolean { val (clazz, method) = resolveCallToStrings() ?: return false val expectedMethodName = if (isPut) "put" else "get" if (clazz == COLORS_CLASS_NAME && method == expectedMethodName) { return true } else if (clazz == OBJECT_MAP_CLASS_NAME && method == expectedMethodName) { ((parent as? KtDotQualifiedExpression)?.receiverExpression as? KtDotQualifiedExpression) ?.resolveCallToStrings() ?.let { (clazz2, method2) -> if (clazz2 == COLORS_CLASS_NAME && method2 == "getColors") { return true } } } return false } internal class ColorsDefinition( nameElement: PsiElement, valueElement: PsiElement ) { private val nameElements = mutableSetOf(nameElement) var valueElement: PsiElement? = valueElement private set fun addNameElement(nameElement: PsiElement?) { nameElement?.let { nameElements.add(it) } valueElement = null } fun nameElements(): Set<PsiElement> = nameElements } private val KEY = key<CachedValue<Map<String, ColorsDefinition?>>>("colorsMap") internal fun Project.getColorsMap(): Map<String, ColorsDefinition?> = getCachedValue(KEY, null) { if (!isLibGDXProject()) { mapOf<String, ColorsDefinition>() } val colorsClasses = psiFacade().findClasses(COLORS_CLASS_NAME, allScope()) val callExpressions = mutableListOf<PsiElement>() // map.put(String, Color) colorsClasses.forEach { clazz -> clazz.findFieldByName("map", false)?.navigationElement?.let { map -> ReferencesSearch.search(map, allScope()).forEach { reference -> reference.element.getParentOfType<PsiMethodCallExpression>()?.let { call -> if (call.resolveMethod()?.name == "put") { callExpressions.add(call) } } } } } // getColors().put(String, Color) val getColorsMethods = colorsClasses.mapNotNull { it.findMethodsByName("getColors", false).firstOrNull() } getColorsMethods.forEach { method -> MethodReferencesSearch.search(method, allScope(), true).forEach { reference -> reference .element .getParentOfType<KtDotQualifiedExpression>() ?.getParentOfType<KtDotQualifiedExpression>() ?.callExpression ?.let { call -> call.resolveCallToStrings()?.let { (_, methodName) -> if (methodName == "put") { callExpressions.add(call) } } } reference .element .getParentOfType<PsiCallExpression>() ?.getParentOfType<PsiCallExpression>() ?.let { call -> if (call.resolveMethod()?.name == "put") { callExpressions.add(call) } } } } // Colors.put(String, Color) val putMethods = colorsClasses.mapNotNull { it.findMethodsByName("put", false).firstOrNull() } putMethods.forEach { method -> ReferencesSearch.search(method, allScope(), true).forEach { reference -> reference.element.getParentOfType<PsiCallExpression>()?.let { callExpressions.add(it) } reference.element.getParentOfType<KtCallExpression>()?.let { callExpressions.add(it) } } } val colors = mutableMapOf<String, ColorsDefinition?>() callExpressions.forEach { callExpression -> val colorName: String = getColorNameFromArgs(callExpression)?.second ?: return@forEach val colorDef = getColorDefFromArgs(callExpression) colors[colorName]?.let { it.addNameElement(colorDef?.first) return@forEach } if (colorDef != null) { colors[colorName] = ColorsDefinition(colorDef.first, colorDef.second) } else { colors[colorName] = null } } colors.toMap() } ?: mapOf() internal fun getColorNameFromArgs(callExpression: PsiElement): Pair<PsiElement, String?>? = (callExpression as? PsiCallExpression)?.let { psiCallExpression -> (psiCallExpression.argumentList?.expressions?.firstOrNull() as? PsiLiteralExpression)?.let { it to it.asString() } } ?: (callExpression as? KtCallExpression)?.let { ktCallExpression -> (ktCallExpression.valueArguments.firstOrNull()?.getArgumentExpression() as? KtStringTemplateExpression)?.let { it to it.asPlainString() } } private fun getColorDefFromArgs(callExpression: PsiElement): Pair<PsiElement, PsiElement>? = (callExpression as? PsiCallExpression)?.let { psiCallExpression -> psiCallExpression.argumentList?.expressions?.let { args -> args.getOrNull(0)?.let { nameElement -> args.getOrNull(1)?.let { valueElement -> nameElement to valueElement } } } } ?: (callExpression as? KtCallExpression)?.let { ktCallExpression -> ktCallExpression.valueArguments.let { args -> args.getOrNull(0)?.getArgumentExpression()?.let { nameElement -> args.getOrNull(1)?.getArgumentExpression()?.let { valueElement -> nameElement to valueElement } } } }
apache-2.0
f85cc1d7e7265b25d9700e6c55f36aaf
32.766667
118
0.628578
4.996301
false
false
false
false
google/private-compute-libraries
java/com/google/android/libraries/pcc/chronicle/analysis/DefaultChronicleContext.kt
1
5663
/* * Copyright 2022 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.libraries.pcc.chronicle.analysis import com.google.android.libraries.pcc.chronicle.api.Connection import com.google.android.libraries.pcc.chronicle.api.ConnectionName import com.google.android.libraries.pcc.chronicle.api.ConnectionProvider import com.google.android.libraries.pcc.chronicle.api.DataTypeDescriptor import com.google.android.libraries.pcc.chronicle.api.DataTypeDescriptorSet import com.google.android.libraries.pcc.chronicle.api.ProcessorNode import com.google.android.libraries.pcc.chronicle.api.error.ConnectionTypeAmbiguity import com.google.android.libraries.pcc.chronicle.util.TypedMap /** * Default implementation of [ChronicleContext] configured and intended to represent the data-flow * characteristics and requirements of Chronicle in the process. */ class DefaultChronicleContext( override val connectionProviders: Set<ConnectionProvider>, override val processorNodes: Set<ProcessorNode>, override val policySet: PolicySet, override val dataTypeDescriptorSet: DataTypeDescriptorSet, override val connectionContext: TypedMap = TypedMap() ) : ChronicleContext { // TODO(b/251295492) these properties can disappear or be renamed. private val connectionProviderByType: Map<Class<out Connection>?, ConnectionProvider> private val connectionProviderByName: Map<ConnectionName<out Connection>, ConnectionProvider> private val dtdByType: Map<Class<out Connection>?, DataTypeDescriptor> private val dtdByConnectionName: Map<ConnectionName<out Connection>, DataTypeDescriptor> // Note: It would be nice to not have to do this much work each time we create a new // ChronicleContextImpl when adding a node. init { val tempProvidersByClass = mutableMapOf<Class<out Connection>?, ConnectionProvider>() val tempProvidersByName = mutableMapOf<ConnectionName<out Connection>, ConnectionProvider>() val tempDtdsByClass = mutableMapOf<Class<out Connection>?, DataTypeDescriptor>() val tempDtdsByName = mutableMapOf<ConnectionName<out Connection>, DataTypeDescriptor>() connectionProviders.forEach { connectionProvider -> val dataType = connectionProvider.dataType dataType.connectionTypes.forEach { ensureNoConnectionAmbiguity(tempProvidersByClass[it], connectionProvider, it.toString()) tempProvidersByClass[it] = connectionProvider tempDtdsByClass[it] = dataType.descriptor } dataType.connectionNames.forEach { ensureNoConnectionAmbiguity(tempProvidersByName[it], connectionProvider, it.toString()) tempProvidersByName[it] = connectionProvider tempDtdsByName[it] = dataType.descriptor } } connectionProviderByType = tempProvidersByClass connectionProviderByName = tempProvidersByName dtdByType = tempDtdsByClass dtdByConnectionName = tempDtdsByName } private fun ensureNoConnectionAmbiguity( existing: ConnectionProvider?, new: ConnectionProvider, connectionTypeAsString: String ) { if (existing != null) { throw ConnectionTypeAmbiguity(connectionTypeAsString, setOf(existing, new)) } } override fun <T : Connection> findConnectionProvider( connectionType: Class<T>? ): ConnectionProvider? = connectionProviderByType[connectionType] override fun <T : Connection> findConnectionProvider( connectionName: ConnectionName<T> ): ConnectionProvider? = connectionProviderByName[connectionName] override fun <T : Connection> findDataType(connectionType: Class<T>?): DataTypeDescriptor? = dtdByType[connectionType] override fun <T : Connection> findDataType( connectionName: ConnectionName<T> ): DataTypeDescriptor? = dtdByConnectionName[connectionName] override fun withNode(node: ProcessorNode): ChronicleContext = DefaultChronicleContext( connectionProviders = connectionProviders, processorNodes = processorNodes + node, policySet = policySet, dataTypeDescriptorSet = dataTypeDescriptorSet, connectionContext = connectionContext ) override fun withConnectionContext(connectionContext: TypedMap): ChronicleContext = DefaultChronicleContext( connectionProviders = connectionProviders, processorNodes = processorNodes, policySet = policySet, dataTypeDescriptorSet = dataTypeDescriptorSet, connectionContext = connectionContext ) override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false other as DefaultChronicleContext if (connectionProviders != other.connectionProviders) return false if (processorNodes != other.processorNodes) return false if (policySet != other.policySet) return false if (connectionContext != other.connectionContext) return false return true } override fun hashCode(): Int { var result = connectionProviders.hashCode() result = 31 * result + processorNodes.hashCode() result = 31 * result + policySet.hashCode() result = 31 * result + connectionContext.hashCode() return result } }
apache-2.0
9de364304fd071b4c0479e33fa5870a0
40.335766
98
0.767261
4.894555
false
false
false
false
soeminnminn/EngMyanDictionary
app/src/main/java/com/s16/view/RecyclerViewArrayAdapter.kt
1
10809
package com.s16.view import android.view.View import android.widget.Filter import android.widget.Filterable import androidx.recyclerview.widget.RecyclerView import java.util.* import kotlin.Comparator import kotlin.collections.ArrayList abstract class RecyclerViewArrayAdapter<VH: RecyclerView.ViewHolder, T>: RecyclerView.Adapter<VH>(), Filterable { /** * Lock used to modify the content of [.mObjects]. Any write operation * performed on the array should be synchronized on this lock. This lock is also * used by the filter (see [.getFilter] to make a synchronized copy of * the original array of data. */ private val mLock = Any() /** * Contains the list of objects that represent the data of this ArrayAdapter. * The content of this list is referred to as "the array" in the documentation. */ private var mObjects: MutableList<T> = mutableListOf() /** * Indicates whether or not [.notifyDataSetChanged] must be called whenever * [.mObjects] is modified. */ private var mNotifyOnChange = true // A copy of the original mObjects array, initialized from and then used instead as soon as // the mFilter ArrayFilter is used. mObjects will then only contain the filtered values. private var mOriginalValues: MutableList<T>? = null private var mFilter: ArrayFilter? = null private var mItemClickListener: OnItemClickListener? = null interface OnItemClickListener { /** * Callback method to be invoked when an item in this RecyclerView has * been clicked. * * @param view The view within the AdapterView that was clicked (this * will be a view provided by the adapter) * @param position The position of the view in the adapter. */ fun onItemClick(view: View, position: Int) } fun setOnItemClickListener(listener: OnItemClickListener) { mItemClickListener = listener } abstract fun onBindViewHolder(holder: VH, item: T) override fun onBindViewHolder(holder: VH, position: Int) { getItem(position)?.let { item -> onBindViewHolder(holder, item) } if (mItemClickListener != null) { holder.itemView.isClickable = true holder.itemView.setOnClickListener { v -> mItemClickListener!!.onItemClick(v, position) } } } /** * Set the new list to be displayed. * * @param collection The new list to be displayed. */ fun submitList(collection: Collection<T>) { synchronized(mLock) { mObjects = ArrayList(collection) mOriginalValues = null } if (mNotifyOnChange) notifyDataSetChanged() } /** * Adds the specified object at the end of the array. * * @param element The object to add at the end of the array. * @throws UnsupportedOperationException if the underlying data collection is immutable */ fun add(element: T) { var index: Int synchronized(mLock) { mOriginalValues?.add(element) ?: mObjects.add(element) index = mOriginalValues?.indexOf(element) ?: mObjects.indexOf(element) } if (index != -1) notifyItemInserted(index) } /** * Adds the specified Collection at the end of the array. * * @param collection The Collection to add at the end of the array. * @throws UnsupportedOperationException if the <tt>addAll</tt> operation * is not supported by this list * @throws ClassCastException if the class of an element of the specified * collection prevents it from being added to this list * @throws NullPointerException if the specified collection contains one * or more null elements and this list does not permit null * elements, or if the specified collection is null * @throws IllegalArgumentException if some property of an element of the * specified collection prevents it from being added to this list */ fun addAll(collection: Collection<T>) { synchronized(mLock) { mOriginalValues?.addAll(collection) ?: mObjects.addAll(collection) } if (mNotifyOnChange) notifyDataSetChanged() } /** * Adds the specified items at the end of the array. * * @param items The items to add at the end of the array. * @throws UnsupportedOperationException if the underlying data collection is immutable */ fun addAll(vararg items: T) { synchronized(mLock) { if (mOriginalValues != null) { mOriginalValues!!.addAll(items) } else { mObjects.addAll(items) } } if (mNotifyOnChange) notifyDataSetChanged() } /** * Inserts the specified object at the specified index in the array. * * @param element The object to insert into the array. * @param index The index at which the object must be inserted. * @throws UnsupportedOperationException if the underlying data collection is immutable */ fun insert(element: T, index: Int) { synchronized(mLock) { if (mOriginalValues != null) { mOriginalValues!!.add(index, element) } else { mObjects.add(index, element) } } notifyItemInserted(index) } /** * Removes the specified object from the array. * * @param element The object to remove. * @throws UnsupportedOperationException if the underlying data collection is immutable */ fun remove(element: T) { var index: Int synchronized(mLock) { index = mOriginalValues?.indexOf(element) ?: mObjects.indexOf(element) mOriginalValues?.remove(element) ?: mObjects.remove(element) } if (index != -1) notifyItemRemoved(index) } /** * Removes a object at the specified [index] from the array. * * @param index The index to remove. */ fun removeAt(index: Int) { synchronized(mLock) { mOriginalValues?.removeAt(index) ?: mObjects.removeAt(index) } notifyItemRemoved(index) } /** * Remove all elements from the list. * * @throws UnsupportedOperationException if the underlying data collection is immutable */ fun clear() { synchronized(mLock) { if (mOriginalValues != null) { mOriginalValues!!.clear() } else { mObjects.clear() } } if (mNotifyOnChange) notifyDataSetChanged() } /** * Sorts the content of this adapter using the specified comparator. * * @param comparator The comparator used to sort the objects contained * in this adapter. */ fun sort(comparator: Comparator<in T>) { synchronized(mLock) { if (mOriginalValues != null) { mOriginalValues!!.sortWith(comparator) } else { mObjects.sortWith(comparator) } } if (mNotifyOnChange) notifyDataSetChanged() } /** * Returns the first element matching the given [predicate], or `null` if no such element was found. */ fun find(predicate: (T) -> Boolean): T? = mObjects.find(predicate) /** * Returns the index of the first occurrence of the specified element in the list, or -1 if the specified * element is not contained in the list. */ fun findIndex(predicate: (T) -> Boolean): Int { val element = mObjects.find(predicate) return if (element != null) mObjects.indexOf(element) else -1 } /** * Control whether methods that change the list ([.add], [.addAll], * [.addAll], [.insert], [.remove], [.clear], * [.sort]) automatically call [.notifyDataSetChanged]. If set to * false, caller must manually call notifyDataSetChanged() to have the changes * reflected in the attached view. * * The default is true, and calling notifyDataSetChanged() * resets the flag to true. * * @param notifyOnChange if true, modifications to the list will * automatically call [ ][.notifyDataSetChanged] */ fun setNotifyOnChange(notifyOnChange: Boolean) { mNotifyOnChange = notifyOnChange } override fun getItemCount(): Int = mObjects.size fun getItems(): List<T> { return mOriginalValues ?: mObjects } fun getItem(position: Int): T? = if (position > -1 && position < mObjects.size) { mObjects[position] } else { null } fun getPosition(element: T): Int = mObjects.indexOf(element) override fun getFilter(): Filter { if (mFilter == null) { mFilter = ArrayFilter() } return mFilter!! } private inner class ArrayFilter: Filter() { override fun performFiltering(prefix: CharSequence?): FilterResults { val results = FilterResults() if (mOriginalValues == null) { synchronized(mLock) { mOriginalValues = ArrayList(mObjects) } } if (prefix == null || prefix.isEmpty()) { val list: ArrayList<T> synchronized(mLock) { list = ArrayList(mOriginalValues!!) } results.values = list results.count = list.size } else { val prefixString = "$prefix".toLowerCase(Locale.getDefault()) val values: ArrayList<T> synchronized(mLock) { values = ArrayList(mOriginalValues!!) } val newValues = values.filter { value -> val valueText = "$value".toLowerCase(Locale.getDefault()) if (valueText.startsWith(prefixString)) { true } else { val words = valueText.split(" ".toRegex()).dropLastWhile { it.isEmpty() } words.indexOfFirst { word -> word.startsWith(prefixString) } > -1 } }.toMutableList() results.values = newValues results.count = newValues.size } return results } @Suppress("UNCHECKED_CAST") override fun publishResults(constraint: CharSequence?, results: FilterResults?) { // noinspection unchecked mObjects = results?.values as MutableList<T> notifyDataSetChanged() } } }
gpl-2.0
9a65b81d56e14458b0deaf8ef0e0430e
32.78125
109
0.596817
4.96281
false
false
false
false
AlexanderDashkov/hpcourse
csc/2015/any/any_1_kotlin/src/ru/bronti/hpcource/hw1/MyThreadPool.kt
4
3770
package ru.bronti.hpcource.hw1 import java.util.LinkedList import java.util.Queue import java.util.concurrent.Callable import java.util.concurrent.ConcurrentLinkedQueue import java.util.concurrent.RejectedExecutionException import java.lang.ThreadGroup import java.util.concurrent.* import java.util.concurrent.atomic.AtomicBoolean public class MyThreadPool(public val size: Int) { public volatile var isShut: Boolean = false set(value) { synchronized(queueMonitor) { synchronized(emptynessMonitor) { $isShut = value emptynessMonitor.notifyAll() queueMonitor.notifyAll() } } } private volatile var isClosed = false private val queueMonitor = Object() private val emptynessMonitor = Object() val queue: Queue<MyFuture<*>> = LinkedList() val pool = Array(size, { MyThread(MyWorker("Worker " + it)) }) init { for (thread in pool) { thread.start() } } public fun submit<V>(task: Callable<V>, name: String = "_noname_"): MyFuture<V>? { if (isClosed) { throw RejectedExecutionException() } val result = MyFuture(task, name, this) synchronized(queueMonitor) { queue.add(result) queueMonitor.notifyAll() } return result } public fun shutdown() { isClosed = true synchronized(emptynessMonitor) { while (!queue.isEmpty() && !isShut) { emptynessMonitor.wait() } } isShut = true } public fun shutdownNow(): List<Callable<*>>? { isClosed = true isShut = true for(t in pool) { t.interrupt() } return queue map { it.getTaskAndCancel() } } inner class MyWorker(val name: String) : Runnable { private fun getTask(mustHave: Boolean): MyFuture<*>? { var task: MyFuture<*>? do { task = synchronized(queueMonitor) { while (queue.isEmpty() && !isShut && mustHave) { try { queueMonitor.wait() } catch (e: InterruptedException) { Thread.currentThread().interrupt() } } synchronized(emptynessMonitor) { emptynessMonitor.notifyAll() queue.poll() } } } while ((task != null) && (task!!.isCancelled())) /*if (task != null) { println(Thread.currentThread().getName() + " caught " + task!!.name) }*/ return task } fun runTask(mustHave: Boolean = true) { if (!isShut) { val task = getTask(mustHave) if (task == null || Thread.currentThread().isInterrupted()) { return } try { //println(name + " captured " + task.name) task.run(Thread.currentThread() as MyThread) println(Thread.currentThread().getName() + " released " + task.name) //println(name + " completed " + task.name) } catch (e: InterruptedException) { println(Thread.currentThread().getName() + " caught IE from " + task.name) //println("thrown exeption by " + task.name) } } } override fun run() { while (!isShut) { Thread.interrupted() runTask() } } } }
gpl-2.0
faeaed560f11493e305a9abf176c5956
30.689076
94
0.497613
5.013298
false
false
false
false
fgsguedes/notes
app/src/main/java/io/guedes/notes/app/note/list/viewmodel/ListNotesViewModel.kt
1
2690
package io.guedes.notes.app.note.list.viewmodel import io.guedes.notes.app.note.list.interactor.ListNotesInteractor import io.guedes.notes.arch.BaseViewModel import io.guedes.notes.domain.model.Note import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.FlowPreview import io.guedes.notes.app.note.list.ListNotesAction as Action import io.guedes.notes.app.note.list.ListNotesNavigation as Navigation import io.guedes.notes.app.note.list.ListNotesResult as Result import io.guedes.notes.app.note.list.ListNotesState as State @FlowPreview @ExperimentalCoroutinesApi class ListNotesViewModel( private val interactor: ListNotesInteractor, dispatcher: CoroutineDispatcher ) : BaseViewModel<Action, Result, State, Navigation>(interactor, dispatcher, State()) { init { interactor.offer(Action.Init) } override fun reduce(state: State, result: Result) = when (result) { is Result.Fetch -> onFetchResult(state, result.notes) is Result.ChangeSorting -> onSortingResult(state, result.descendingSort) is Result.DeleteInProgress -> onDeleteInProgressResult(state, result.noteId) is Result.DeleteCompleted -> onDeleteCompletedResult(state) Result.DeleteCanceled -> onDeleteCanceledResult(state) } fun onCreateNote() { interactor.offer(Action.CreateNote) } fun onNoteCreated() { interactor.offer(Action.NoteCreated) } fun onNoteClick(note: Note) { interactor.offer(Action.EditNote(note)) } fun onUpdateSorting() { interactor.offer(Action.InvertSorting) } fun onItemSwipe(noteId: Long) { interactor.offer(Action.Delete(noteId)) } fun onUndoDelete(noteId: Long) { interactor.offer(Action.UndoDelete(noteId)) } // region Results private fun onFetchResult(state: State, notes: List<Note>) = state.copy(notes = notes.sorted(state.descendingSort)) private fun onSortingResult(state: State, descendingSort: Boolean) = state.copy( notes = state.notes.sorted(descendingSort), descendingSort = descendingSort ) private fun onDeleteInProgressResult(state: State, noteId: Long) = state.copy(deleteInProgress = noteId) private fun onDeleteCompletedResult(state: State) = state.copy(deleteInProgress = 0) private fun onDeleteCanceledResult(state: State) = state.copy(deleteInProgress = 0) // endregion private fun List<Note>.sorted(descendingSort: Boolean): List<Note> = if (descendingSort) sortedByDescending { it.id } else sortedBy { it.id } }
gpl-3.0
eee0c8582e9220bc12dbadd570c7905f
32.625
87
0.719703
4.157651
false
false
false
false
jayrave/falkon
falkon-dao/src/main/kotlin/com/jayrave/falkon/dao/lib/LinkedHashMapBackedDataConsumer.kt
1
2189
package com.jayrave.falkon.dao.lib import com.jayrave.falkon.engine.Type import com.jayrave.falkon.engine.TypedNull import com.jayrave.falkon.mapper.DataConsumer import java.util.* /** * A [DataConsumer] that stores the data in a backing [LinkedHashMap]. Failing to call * [setColumnName] before every #put*() call will result in [RuntimeException] */ internal class LinkedHashMapBackedDataConsumer : DataConsumer { /** * When accessed from outside, this map should be treated as a read-only map */ val map = LinkedHashMap<String, Any>() private var columnName: String? = null fun setColumnName(columnName: String) { this.columnName = columnName } override fun put(short: Short?) { when (short) { null -> putNullTypeInMap(Type.SHORT) else -> putInMap(short) } } override fun put(int: Int?) { when (int) { null -> putNullTypeInMap(Type.INT) else -> putInMap(int) } } override fun put(long: Long?) { when (long) { null -> putNullTypeInMap(Type.LONG) else -> putInMap(long) } } override fun put(float: Float?) { when (float) { null -> putNullTypeInMap(Type.FLOAT) else -> putInMap(float) } } override fun put(double: Double?) { when (double) { null -> putNullTypeInMap(Type.DOUBLE) else -> putInMap(double) } } override fun put(string: String?) { when (string) { null -> putNullTypeInMap(Type.STRING) else -> putInMap(string) } } override fun put(blob: ByteArray?) { when (blob) { null -> putNullTypeInMap(Type.BLOB) else -> putInMap(blob) } } private fun putNullTypeInMap(type: Type) { putInMap(TypedNull(type)) } private fun putInMap(value: Any) { val key = when (columnName) { null -> throw RuntimeException("Calling #put without setting a column name") else -> columnName!! } columnName = null map.put(key, value) } }
apache-2.0
ebe30a826ae9c5090e6642da3e0129a9
24.465116
88
0.574235
4.137996
false
false
false
false
andretietz/retroauth
demo-android/src/main/java/com/andretietz/retroauth/demo/screen/main/MainViewModel.kt
1
2964
package com.andretietz.retroauth.demo.screen.main import androidx.annotation.WorkerThread import androidx.lifecycle.ViewModel import com.andretietz.retroauth.AndroidAccountManagerCredentialStorage import com.andretietz.retroauth.AndroidAccountManagerOwnerStorage import com.andretietz.retroauth.AuthenticationCanceledException import com.andretietz.retroauth.AuthenticationRequiredException import com.andretietz.retroauth.Credentials import com.andretietz.retroauth.demo.api.GithubApi import com.andretietz.retroauth.demo.auth.GithubAuthenticator import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.CoroutineName import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.launch import timber.log.Timber import javax.inject.Inject @HiltViewModel class MainViewModel @Inject constructor( private val api: GithubApi, private val ownerStorage: AndroidAccountManagerOwnerStorage, private val credentialStorage: AndroidAccountManagerCredentialStorage, private val authenticator: GithubAuthenticator ) : ViewModel() { private val _state = MutableStateFlow<MainViewState>(MainViewState.InitialState) private val scope = CoroutineScope(Dispatchers.Default + CoroutineName("ViewModelScope")) val state = _state init { scope.launch { loadRepositories() } } fun addAccount() { scope.launch { val account = ownerStorage.createOwner( authenticator.getCredentialType()) if (account == null) { _state.value = MainViewState.Error(AuthenticationCanceledException()) } else { Timber.d("Logged in: $account") _state.value = MainViewState.InitialState _state.value = MainViewState.LoginSuccess(account) } } } fun loadRepositories() = scope.launch(Dispatchers.IO) { try { _state.value = MainViewState.RepositoryUpdate(api.getRepositories()) } catch (error: AuthenticationRequiredException) { _state.value = MainViewState.InitialState } } fun invalidateTokens() { ownerStorage.getActiveOwner()?.let { account -> val credential = credentialStorage.getCredentials( account, authenticator.getCredentialType()) if (credential == null) { _state.value = MainViewState.Error(AuthenticationCanceledException()) } else { credentialStorage.storeCredentials( account, authenticator.getCredentialType(), Credentials("some-invalid-token", credential.data) ) } } } fun logout() = scope.launch(Dispatchers.Default) { ownerStorage.getActiveOwner()?.let { account -> if (ownerStorage.removeOwner(account)) { _state.value = MainViewState.LogoutSuccess } else { _state.value = MainViewState.Error(UnknownError()) } } } fun getCurrentAccount() = ownerStorage.getActiveOwner() }
apache-2.0
20a0a847ab279f64ddcf8d4263345b17
31.217391
91
0.738529
4.843137
false
false
false
false
nickthecoder/tickle
tickle-editor/src/main/kotlin/uk/co/nickthecoder/tickle/editor/util/ParameterFactory.kt
1
3845
/* Tickle Copyright (C) 2017 Nick Robinson This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package uk.co.nickthecoder.tickle.editor.util import uk.co.nickthecoder.paratask.parameters.ChoiceParameter import uk.co.nickthecoder.paratask.parameters.GroupedChoiceParameter import uk.co.nickthecoder.tickle.Costume import uk.co.nickthecoder.tickle.Pose import uk.co.nickthecoder.tickle.graphics.Texture import uk.co.nickthecoder.tickle.resources.FontResource import uk.co.nickthecoder.tickle.resources.Resources import uk.co.nickthecoder.tickle.sound.Sound fun createTextureParameter(parameterName: String = "texture"): ChoiceParameter<Texture?> { val parameter = ChoiceParameter<Texture?>(name = parameterName, required = true, value = null) Resources.instance.textures.items().forEach { name, texture -> parameter.addChoice(name, texture, name) } return parameter } fun createPoseParameter(parameterName: String = "pose", label: String = "Pose", required: Boolean = true): GroupedChoiceParameter<Pose?> { val choiceParameter = GroupedChoiceParameter<Pose?>(parameterName, label = label, required = required, value = null) if (!required) { choiceParameter.addChoice("", null, "None") } Resources.instance.textures.items().forEach { textureName, texture -> val group = choiceParameter.group(textureName) Resources.instance.poses.items().filter { it.value.texture === texture }.forEach { poseName, pose -> group.choice(poseName, pose, poseName) } } return choiceParameter } fun createFontParameter(parameterName: String = "font", label: String = "Font"): ChoiceParameter<FontResource?> { val choice = ChoiceParameter<FontResource?>(parameterName, label = label, required = true, value = null) Resources.instance.fontResources.items().forEach { name, fontResource -> choice.addChoice(name, fontResource, name) } return choice } fun createCostumeParameter(parameterName: String = "costume", required: Boolean = true, value: Costume? = null): GroupedChoiceParameter<Costume?> { val choiceParameter = GroupedChoiceParameter<Costume?>(parameterName, required = required, value = value) if (!required) { choiceParameter.addChoice("", null, "None") } val defaultGroup = choiceParameter.group("") Resources.instance.costumes.items().filter { it.value.costumeGroup == null }.forEach { costumeName, costume -> defaultGroup.choice(costumeName, costume, costumeName) } Resources.instance.costumeGroups.items().forEach { groupName, costumeGroup -> val group = choiceParameter.group(groupName) costumeGroup.items().forEach { costumeName, costume -> group.choice(costumeName, costume, costumeName) } } return choiceParameter } fun createSoundParameter(parameterName: String = "sound"): ChoiceParameter<Sound?> { val choice = ChoiceParameter<Sound?>(parameterName, required = true, value = null) Resources.instance.sounds.items().forEach { name, sound -> choice.addChoice(name, sound, name) } return choice } fun createNinePatchParameter(parameterName: String = "ninePatch", label: String = "NinePatch") = NinePatchParameter(parameterName, label)
gpl-3.0
de79a4d2c6e1f64a6280f5f2a761b74d
36.330097
147
0.73472
4.384265
false
false
false
false
alexmonthy/lttng-scope
lttng-scope/src/main/kotlin/org/lttng/scope/views/events/EventTable.kt
2
9281
/* * Copyright (C) 2017 EfficiOS Inc., Alexandre Montplaisir <[email protected]> * * All rights reserved. This program and the accompanying materials are * made available under the terms of the Eclipse Public License v1.0 which * accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ package org.lttng.scope.views.events import com.efficios.jabberwocky.common.TimeRange import com.efficios.jabberwocky.context.ViewGroupContext import com.efficios.jabberwocky.project.TraceProject import com.efficios.jabberwocky.trace.event.TraceEvent import com.sun.javafx.scene.control.skin.TableViewSkin import com.sun.javafx.scene.control.skin.VirtualFlow import javafx.application.Platform import javafx.beans.property.ReadOnlyObjectWrapper import javafx.collections.FXCollections import javafx.collections.ListChangeListener import javafx.scene.CacheHint import javafx.scene.Node import javafx.scene.control.TableCell import javafx.scene.control.TableColumn import javafx.scene.control.TableRow import javafx.scene.control.TableView import javafx.scene.layout.BorderPane import javafx.scene.layout.HBox import org.lttng.scope.application.ScopeOptions import org.lttng.scope.project.ProjectFilters import org.lttng.scope.project.ProjectManager import org.lttng.scope.project.filter.EventFilterDefinition import org.lttng.scope.project.filter.getGraphic import org.lttng.scope.views.context.ViewGroupContextManager /** * Table displaying the trace project's trace events. */ class EventTable(private val tableControl: EventTableControl) : BorderPane() { internal val tableView: TableView<TraceEvent> init { /* Setup the table */ val filterIconsCol = FilterColumn() val timestampCol = createTextColumn("Timestamp", 200.0, { ScopeOptions.timestampFormat.tsToString(it.timestamp) }) val traceCol = createTextColumn("Trace", 100.0, { it.trace.name }) val cpuCol = createTextColumn("CPU", 50.0, { it.cpu.toString() }) val typeCol = createTextColumn("Event Type", 200.0, { it.eventName }) val fieldsCol = createTextColumn("Event Fields", 800.0, { event -> event.fields .map { "${it.key}=${it.value}" } .toString() }) tableView = TableView<TraceEvent>().apply { fixedCellSize = 24.0 isCache = true cacheHint = CacheHint.SPEED columns.addAll(filterIconsCol, timestampCol, traceCol, cpuCol, typeCol, fieldsCol) /* Row factory to add the click listener on each row */ setRowFactory { TableRow<TraceEvent>().apply { setOnMouseClicked { this.item?.let { updateSelection(it.timestamp) } } } } } center = tableView right = EventTableScrollToolBar(tableControl) } private fun createTextColumn(headerText: String, initialWidth: Double, provideText: (TraceEvent) -> String): TableColumn<TraceEvent, String> { return TableColumn<TraceEvent, String>(headerText).apply { setCellValueFactory { ReadOnlyObjectWrapper(provideText(it.value)) } isSortable = false prefWidth = initialWidth } } fun clearTable() { tableView.items = FXCollections.emptyObservableList() } fun displayEvents(events: List<TraceEvent>) { tableView.items = FXCollections.observableList(events) } /** * Scroll to the top *of the current event list*. * This method will not load any new events from the trace. */ fun scrollToTop() { Platform.runLater { tableView.scrollTo(0) } } /** * Scroll to the end *of the current event list*. * This method will not load any new events from the trace. */ fun scrollToBottom() { val nbItems = tableView.items.size Platform.runLater { tableView.scrollTo(nbItems - 1) } } fun selectIndex(index: Int) { Platform.runLater { with(tableView) { requestFocus() selectionModel.clearAndSelect(index) focusModel.focus(index) /* * Scroll to the target index, but only if it is out of the current * range shown by the table. */ val visibleRows = getVisibleRowIndices() ?: return@runLater if (index !in visibleRows) { /* Place the target row in the middle of the view. */ scrollTo(maxOf(0, index - visibleRows.count() / 2)) } } } } /** * Refresh the view, as in, keep the same displayed data and selection, * but ask to regenerate the cell contents. */ fun refresh() { tableView.refresh() } /** * Whenever a table row is clicked, the selection in the rest * of the framework should be updated. * * If we end up pointing to a timestamp outside of the current * visible range, also recenter the visible range on that timestamp * (but *only* if it's outside, else don't move the visible range). */ private fun updateSelection(timestamp: Long) { val viewCtx = tableControl.viewContext viewCtx.selectionTimeRange = TimeRange.of(timestamp, timestamp) if (timestamp !in viewCtx.visibleTimeRange) { viewCtx.centerVisibleRangeOn(timestamp) } } /** * Get the start/end range currently shown by the table, in terms of row index. * * If the table is empty then null is returned. */ private fun getVisibleRowIndices(): IntRange? { val flow = (tableView.skin as TableViewSkin<*>).children[1] as VirtualFlow<*> val firstCell = flow.firstVisibleCell ?: return null val lastCell = flow.lastVisibleCell ?: return null return firstCell.index..lastCell.index } } private class FilterColumn : TableColumn<TraceEvent, TraceEvent>(""), ProjectFilters.FilterListener { private inner class FilterCell : TableCell<TraceEvent, TraceEvent>() { private val filterSymbols = mutableMapOf<EventFilterDefinition, Node>() private val node = HBox() init { enabledFilters.addListener(ListChangeListener<EventFilterDefinition> { c -> if (c == null) return@ListChangeListener while (c.next()) { for (removedFilter in c.removed) { filterSymbols.remove(removedFilter)?.let { node.children.remove(it) } } for (addedFilter in c.addedSubList) { val graphic = addedFilter.getGraphic() /* * Whenever a symbol is hidden, we don't want it to count in its * parent's layout calculations (so the HBox "collapses"). */ graphic.managedProperty().bind(graphic.visibleProperty()) filterSymbols.put(addedFilter, graphic) graphic.isVisible = (item != null && addedFilter.predicate.invoke(item)) node.children.add(graphic) } } }) } override fun updateItem(item: TraceEvent?, empty: Boolean) { super.updateItem(item, empty) filterSymbols.forEach { filter, node -> node.isVisible = (item != null && filter.predicate.invoke(item)) } graphic = node } } private val createdFilters = mutableListOf<EventFilterDefinition>() private val enabledFilters = FXCollections.observableArrayList<EventFilterDefinition>() init { ViewGroupContextManager.getCurrent().registerProjectChangeListener(object : ViewGroupContext.ProjectChangeListener(this) { override fun newProjectCb(newProject: TraceProject<*, *>?) { if (newProject != null) { ProjectManager.getProjectState(newProject).filters.registerFilterListener(this@FilterColumn) } else { createdFilters.clear() enabledFilters.clear() } } }) /* The 'register' call returns the current project */ ?.let { ProjectManager.getProjectState(it).filters.registerFilterListener(this) } setCellValueFactory { ReadOnlyObjectWrapper(it.value) } setCellFactory { FilterCell() } isSortable = false prefWidth = 20.0 } override fun filterCreated(filter: EventFilterDefinition) { createdFilters.add(filter) if (filter.isEnabled) { enabledFilters.add(filter) } filter.enabledProperty().addListener { _, _, nowEnabled -> if (nowEnabled) { enabledFilters.add(filter) } else { enabledFilters.remove(filter) } } } override fun filterRemoved(filter: EventFilterDefinition) { createdFilters.remove(filter) enabledFilters.remove(filter) } }
epl-1.0
1f3e088c5ef23ca4df13969b3f9d17f2
36.574899
146
0.622023
4.843946
false
false
false
false
t-yoshi/peca-android
libpeercast/src/main/java/org/peercast/core/lib/rpc/io/JsonRpcException.kt
1
447
package org.peercast.core.lib.rpc.io import java.io.IOException /** * JsonRpcのエラー * @author (c) 2019, T Yoshizawa * @licenses Dual licensed under the MIT or GPL licenses. */ class JsonRpcException internal constructor( message: String, val code: Int = -10000, val id: Int = 0, cause: Throwable? = null, ) : IOException(message, cause) { override fun toString() = "${javaClass.name}: $message ($code, id=$id)" }
gpl-3.0
0a178e948a1ea45bc0267a6b552bb421
22.105263
75
0.669704
3.456693
false
false
false
false
Kotlin/anko
anko/library/static/commons/src/main/java/Custom.kt
2
2218
/* * Copyright 2016 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ @file:Suppress("unused") package org.jetbrains.anko.custom import android.app.Activity import android.content.Context import android.view.View import android.view.ViewManager import org.jetbrains.anko.internals.AnkoInternals inline fun <T : View> ViewManager.ankoView(factory: (ctx: Context) -> T, theme: Int, init: T.() -> Unit): T { val ctx = AnkoInternals.wrapContextIfNeeded(AnkoInternals.getContext(this), theme) val view = factory(ctx) view.init() AnkoInternals.addView(this, view) return view } inline fun <T : View> Context.ankoView(factory: (ctx: Context) -> T, theme: Int, init: T.() -> Unit): T { val ctx = AnkoInternals.wrapContextIfNeeded(this, theme) val view = factory(ctx) view.init() AnkoInternals.addView(this, view) return view } inline fun <T : View> Activity.ankoView(factory: (ctx: Context) -> T, theme: Int, init: T.() -> Unit): T { val ctx = AnkoInternals.wrapContextIfNeeded(this, theme) val view = factory(ctx) view.init() AnkoInternals.addView(this, view) return view } inline fun <reified T : View> ViewManager.customView(theme: Int = 0, init: T.() -> Unit): T = ankoView({ ctx -> AnkoInternals.initiateView(ctx, T::class.java) }, theme) { init() } inline fun <reified T : View> Context.customView(theme: Int = 0, init: T.() -> Unit): T = ankoView({ ctx -> AnkoInternals.initiateView(ctx, T::class.java) }, theme) { init() } inline fun <reified T : View> Activity.customView(theme: Int = 0, init: T.() -> Unit): T = ankoView({ ctx -> AnkoInternals.initiateView(ctx, T::class.java) }, theme) { init() }
apache-2.0
8f7b31e315f56bf9d11fea9cdb063be1
37.258621
109
0.692065
3.684385
false
false
false
false
perenecabuto/CatchCatch
android/app/src/main/java/io/perenecabuto/catchcatch/events/RadarEventHandler.kt
1
2310
package io.perenecabuto.catchcatch.events import android.os.Handler import android.os.Looper import io.perenecabuto.catchcatch.drivers.WebSocketClient import io.perenecabuto.catchcatch.model.FeatureList import io.perenecabuto.catchcatch.model.GameInfo import io.perenecabuto.catchcatch.model.Player import io.perenecabuto.catchcatch.view.HomeActivity import org.json.JSONArray import org.json.JSONObject class RadarEventHandler(override val sock: WebSocketClient, val activity: HomeActivity) : EventHandler { private val looper = Looper.myLooper() private val interval: Long = 20_000 override var running = false override fun onStart() { sock.on(PLAYER_REGISTERED) finish@ { msg: String -> val json = JSONObject(msg) onRegistered(Player(json)) } .on(PLAYER_UPDATED) { onUpdated() } .on(GAME_AROUND) finish@ { msg: String -> val items = JSONArray(msg) onGamesAround(FeatureList(items)) } .on(GAME_STARTED) finish@ { msg: String -> val json = JSONObject(msg) onGameStarted(GameInfo(json)) } .onDisconnect { onDisconnect() } } override fun onStop() { radarStarted = false } private var radarStarted: Boolean = false private fun onUpdated() { if (!radarStarted) { radarStarted = true radar() } } private fun radar() { if (!running) return activity.showInfo("searching for games around...") activity.showRadar() sock.emit("player:request-games") Handler(looper).postDelayed(this::radar, interval) } private fun onGamesAround(games: FeatureList) { activity.showInfo("found ${games.list.size} games near you") activity.showFeatures(games.list) } private fun onGameStarted(info: GameInfo) { activity.showMessage("Game ${info.game} started.\nYour role is: ${info.role}") activity.startGame(info) } private fun onRegistered(p: Player) { activity.player = p activity.showInfo("Connected as ${p.id}") } private fun onDisconnect() { activity.showMessage("Disconnected") } }
gpl-3.0
e59b441b0ade2d8a7b84845225fd0990
29.813333
104
0.624675
4.358491
false
false
false
false
quarck/CalendarNotification
app/src/main/java/com/github/quarck/calnotify/utils/ColorUtils.kt
1
5252
// // Calendar Notifications Plus // Copyright (C) 2016 Sergey Parshin ([email protected]) // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software Foundation, // Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA // package com.github.quarck.calnotify.utils internal const val FULL_ALPHA = 0xff000000.toInt() internal const val CALENDAR_COLOR_FADE_MIN = 1.17; internal const val CALENDAR_COLOR_FADE_MED = 1.3; internal const val CALENDAR_COLOR_FADE_MAX = 1.35; internal const val DARK_FACTOR_1 = 1.2; internal const val DARK_FACTOR_2 = 1.3; internal const val DARK_FACTOR_3 = 1.4; internal const val CHANNELS_ARE_EQUAL_THRESHOLD = 0x10 internal const val RGB_TO_YUV_1_1 = 0.299 internal const val RGB_TO_YUV_1_2 = 0.587 internal const val RGB_TO_YUV_1_3 = 0.114 internal const val RGB_TO_YUV_2_1 = -0.14713 internal const val RGB_TO_YUV_2_2 = -0.28886 internal const val RGB_TO_YUV_2_3 = 0.436 internal const val RGB_TO_YUV_3_1 = 0.615 internal const val RGB_TO_YUV_3_2 = -0.51499 internal const val RGB_TO_YUV_3_3 = -0.10001 internal const val YUV_TO_RGB_1_1 = 1.0 internal const val YUV_TO_RGB_1_2 = 0 internal const val YUV_TO_RGB_1_3 = 1.13983 internal const val YUV_TO_RGB_2_1 = 1.0 internal const val YUV_TO_RGB_2_2 = -0.39465 internal const val YUV_TO_RGB_2_3 = -0.58060 internal const val YUV_TO_RGB_3_1 = 1.0 internal const val YUV_TO_RGB_3_2 = 2.03211 internal const val YUV_TO_RGB_3_3 = 0 internal const val Y_MIN = 16.0 internal const val Y_MAX = 235.0 data class RGB(val r: Int, val g: Int, val b: Int) { constructor(v: Int) : this((v.ushr(16)) and 0xff, (v.ushr(8)) and 0xff, (v.ushr(0)) and 0xff) {} fun toInt() = (FULL_ALPHA or (r shl 16) or (g shl 8) or (b shl 0)) } fun Int.adjustCalendarColor(darker: Boolean = true): Int { var (r, g, b) = RGB(this) val min = Math.min(r, Math.min(g, b)) val max = Math.max(r, Math.max(g, b)) val darkFactor1st = if (darker) DARK_FACTOR_1 else 1.0 val darkFactor2nd = if (darker) DARK_FACTOR_2 else 1.0 val darkFactor3rd = if (darker) DARK_FACTOR_3 else 1.0 if (max - min < CHANNELS_ARE_EQUAL_THRESHOLD) { r = (r / CALENDAR_COLOR_FADE_MED / darkFactor1st).toInt() g = (g / CALENDAR_COLOR_FADE_MED / darkFactor1st).toInt() b = (b / CALENDAR_COLOR_FADE_MED / darkFactor1st).toInt() } else { if (r > g && r > b) { // r = (r / CALENDAR_COLOR_FADE_MIN / darkFactor1st).toInt() if (g > b) { g = (g / CALENDAR_COLOR_FADE_MED / darkFactor3rd).toInt() b = (b / CALENDAR_COLOR_FADE_MAX / darkFactor2nd).toInt() } else { b = (b / CALENDAR_COLOR_FADE_MED / darkFactor3rd).toInt() g = (g / CALENDAR_COLOR_FADE_MAX / darkFactor2nd).toInt() } } else if (g > r && g > b) { // g = (g / CALENDAR_COLOR_FADE_MIN / darkFactor1st).toInt() if (r > b) { r = (r / CALENDAR_COLOR_FADE_MED / darkFactor3rd).toInt() b = (b / CALENDAR_COLOR_FADE_MAX / darkFactor2nd).toInt() } else { b = (b / CALENDAR_COLOR_FADE_MED / darkFactor3rd).toInt() r = (r / CALENDAR_COLOR_FADE_MAX / darkFactor2nd).toInt() } } else { // b > r && b > g b = (b / CALENDAR_COLOR_FADE_MIN / darkFactor1st).toInt() if (r > g) { r = (r / CALENDAR_COLOR_FADE_MED / darkFactor3rd).toInt() g = (g / CALENDAR_COLOR_FADE_MAX / darkFactor2nd).toInt() } else { g = (g / CALENDAR_COLOR_FADE_MED / darkFactor3rd).toInt() r = (r / CALENDAR_COLOR_FADE_MAX / darkFactor2nd).toInt() } } } return RGB(r, g, b).toInt() } fun Int.btnAdjustCalendarColor(darker: Boolean): Int { var (r, g, b) = RGB(this) if (darker) { r = (r / CALENDAR_COLOR_FADE_MED).toInt() g = (g / CALENDAR_COLOR_FADE_MED).toInt() b = (b / CALENDAR_COLOR_FADE_MED).toInt() } else { r = (r / CALENDAR_COLOR_FADE_MIN).toInt() g = (g / CALENDAR_COLOR_FADE_MIN).toInt() b = (b / CALENDAR_COLOR_FADE_MIN).toInt() } return RGB(r, g, b).toInt() } fun Int.scaleColor(value: Float): Int { val (r, g, b) = RGB(this) val newR = Math.max(0, Math.min((r * value).toInt(), 255)) val newG = Math.max(0, Math.min((g * value).toInt(), 255)) val newB = Math.max(0, Math.min((b * value).toInt(), 255)) return RGB(newR, newG, newB).toInt() }
gpl-3.0
1b5f18a72e621be5187eebed45de9efd
34.255034
100
0.596344
3.118765
false
false
false
false
LorittaBot/Loritta
web/spicy-morenitta/src/main/kotlin/LoriDashboard.kt
1
14064
import kotlinx.browser.document import kotlinx.browser.window import kotlinx.html.* import kotlinx.html.dom.append import kotlinx.html.dom.create import kotlinx.html.js.onClickFunction import kotlinx.html.stream.appendHTML import net.perfectdreams.loritta.embededitor.EmbedEditorCrossWindow import net.perfectdreams.loritta.embededitor.EmbedRenderer import net.perfectdreams.loritta.embededitor.data.DiscordMessage import net.perfectdreams.loritta.embededitor.data.crosswindow.* import net.perfectdreams.spicymorenitta.locale import net.perfectdreams.spicymorenitta.utils.TingleModal import net.perfectdreams.spicymorenitta.utils.TingleOptions import net.perfectdreams.spicymorenitta.utils.select import org.w3c.dom.Audio import org.w3c.dom.HTMLDivElement import org.w3c.dom.MessageEvent import utils.AutoSize import utils.autosize import kotlin.js.* external val guildId: String external fun delete(p: dynamic): Boolean = definedExternally object LoriDashboard { var toggleCounter = 1000 val configSavedSfx: Audio by lazy { Audio("${loriUrl}assets/snd/config_saved.mp3") } val configErrorSfx: Audio by lazy { Audio("${loriUrl}assets/snd/config_error.mp3") } val wrapper: JQuery by lazy { jq("#server-configuration") } fun showLoadingBar(text: String? = "Salvando...") { document.select<HTMLDivElement>("#loading-screen").apply { select<HTMLDivElement>(".loading-text").apply { textContent = text } style.opacity = "1" } } fun hideLoadingBar() { document.select<HTMLDivElement>("#loading-screen").apply { style.opacity = "0" } } fun applyBlur(toBeHidden: String, toggle: String, onToggle: (() -> (Boolean))? = null) { jq(toggle).click { val result = onToggle?.invoke() ?: true if (!result) { it.preventDefault() return@click } toggleBlur(toBeHidden, toggle) } toggleBlur(toBeHidden, toggle) } fun toggleBlur(toBeHidden: String, toggle: String) { val hide = jq(toBeHidden) if (jq(toggle).`is`(":checked")) { hide.removeClass("blurSection") hide.addClass("noBlur") } else { hide.removeClass("noBlur") hide.addClass("blurSection") } } fun createToggle(internalName: String, toggleMainText: String, toggleSubText: String?, needsToBeSaved: Boolean, isEnabled: Boolean): Pair<Int, JQuery> { val html = """<div class="toggleable-wrapper"> <div class="information"> $toggleMainText ${ if (toggleSubText != null) "<div class=\"sub-text\">$toggleSubText</div>" else ""} </div> <label class="switch" for="cmn-toggle-$toggleCounter"> <input class="cmn-toggle" type="checkbox" data-internal-name="$internalName" value="true" ${ if (needsToBeSaved) "data-send-on-save=\"true\"" else ""} ${if (isEnabled) "checked" else ""} id="cmn-toggle-$toggleCounter" type="checkbox" /> <div class="slider round"></div> </label> </div> <br style="clear: both" />""" val cnt = toggleCounter toggleCounter++ return Pair(cnt, jq(html)) } fun configureTextChannelSelect(selectChannelDropdown: JQuery, textChannels: List<net.perfectdreams.spicymorenitta.views.dashboard.ServerConfig.TextChannel>, selectedChannelId: Long?) { val optionData = mutableListOf<dynamic>() for (it in textChannels) { val option = object{}.asDynamic() option.id = it.id val text = "<span style=\"font-weight: 600;\">#${it.name}</span>" option.text = text if (!it.canTalk) option.text = "${text} <span class=\"keyword\" style=\"background-color: rgb(231, 76, 60);\">${legacyLocale["DASHBOARD_NoPermission"].replace("!", "")}</span>" if (it.id == selectedChannelId) option.selected = true optionData.add(option) } val options = object{}.asDynamic() options.data = optionData.toTypedArray() options.escapeMarkup = { str: dynamic -> str } selectChannelDropdown.asDynamic().select2( options ) selectChannelDropdown.on("select2:select") { event, a -> val channelId = selectChannelDropdown.`val`() as String val channel = textChannels.firstOrNull { it.id.toString() == channelId } if (channel != null && !channel.canTalk) { event.preventDefault() selectChannelDropdown.asDynamic().select2("close") val modal = TingleModal( TingleOptions( footer = true, cssClass = arrayOf("tingle-modal--overflow") ) ) modal.setContent( jq("<div>").append( jq("<div>") .addClass("category-name") .text(legacyLocale["DASHBOARD_NoPermission"]) ).append(jq("<div>").css("text-align", "center").append( jq("<img>") .attr("src", "https://mrpowergamerbr.com/uploads/2018-06-17_11-19-43.gif") .css("width", "100%") ) ).append(jq("<div>").css("text-align", "center").append( jq("<p>") .text("Atualmente eu não consigo falar no canal que você deseja porque eu não tenho permissão para isto... \uD83D\uDE2D") ).append( jq("<p>") .text("Para eu conseguir falar neste canal, clique com botão direito no canal que você deseja que eu possa falar, vá nas permissões, adicione um permission override para mim e dê permissão para que eu possa ler mensagens e enviar mensagens!") )) .html() ) modal.addFooterBtn("<i class=\"far fa-thumbs-up\"></i> Já arrumei!", "button-discord button-discord-info pure-button button-discord-modal") { modal.close() window.location.reload() } modal.addFooterBtn("<i class=\"fas fa-times\"></i> Fechar", "button-discord pure-button button-discord-modal button-discord-modal-secondary-action") { modal.close() } modal.open() } } } class SUMMARY(consumer: TagConsumer<*>) : HTMLTag("summary", consumer, emptyMap(), inlineTag = true, emptyTag = false), HtmlInlineTag { } fun DETAILS.summary(block: SUMMARY.() -> Unit = {}) { SUMMARY(consumer).visit(block) } fun configureTextArea( jquery: JQuery, markdownPreview: Boolean = false, sendTestMessages: Boolean = false, textChannelSelect: JQuery? = null, showPlaceholders: Boolean = false, placeholders: List<Placeholder> = listOf(), showTemplates: Boolean = false, templates: Map<String, String> = mapOf() ) { val div = jq("<div>") // wrapper .css("position", "relative") val wrapperWithButtons = jq("<div>") .css("display", "flex") .css("gap", "0.5em") .css("flex-wrap", "wrap") .css("justify-content", "space-between") if (showTemplates) { val select = jq("<select>") wrapperWithButtons.append(select) val optionData = mutableListOf<dynamic>() val dummyPlaceholder = object{}.asDynamic() dummyPlaceholder.id = "" dummyPlaceholder.text = "" optionData.add(dummyPlaceholder) for (it in templates) { val option = object{}.asDynamic() option.id = it.key // option.id = it.id val text = it.key option.text = text optionData.add(option) } val options = object{}.asDynamic() options.placeholder = "Sem ideias? Então veja nossos templates!" options.data = optionData.toTypedArray() options.escapeMarkup = { str: dynamic -> str } select.asDynamic().select2( options ) select.on("select2:select") { event, a -> val selected = select.`val`() as String val result = templates[selected] select.asDynamic().select2("close") val modal = TingleModal( TingleOptions( footer = true, cssClass = arrayOf("tingle-modal--overflow") ) ) modal.setContent( StringBuilder().appendHTML(false).div { div(classes = "category-name") { + "Você realmente quer substituir pelo template?" } p { + "Ao aplicar o template, a sua mensagem atual será perdida para sempre! (A não ser se você tenha copiado ela para outro lugar, aí vida que segue né)" } }.toString() ) modal.addFooterBtn("<i class=\"far fa-thumbs-up\"></i> Aplicar", "button-discord button-discord-info pure-button button-discord-modal") { modal.close() jquery.`val`(result) jquery.trigger("input", null) // Para recalcular a preview AutoSize.update(jquery) // E para o AutoSize recalcular o tamanho } modal.addFooterBtn("<i class=\"fas fa-times\"></i> Fechar", "button-discord pure-button button-discord-modal button-discord-modal-secondary-action") { modal.close() } modal.open() } } val newElement = document.create.button(classes = "button-discord button-discord-info pure-button") { i(classes = "fas fa-edit") {} + " ${locale["website.dashboard.advancedEditor"]}" onClickFunction = { val extendedWindow = window.open("https://embeds.loritta.website/")!! window.addEventListener("message", { event -> event as MessageEvent println("Received message ${event.data} from ${event.origin}") // We check for embeds.loritta.website because AdSense can also send messages via postMessage if (event.origin.contains("embeds.loritta.website") && event.source == extendedWindow) { println("Received message from our target source, yay!") val packet = EmbedEditorCrossWindow.communicationJson.decodeFromString(PacketWrapper.serializer(), event.data as String) if (packet.m is ReadyPacket) { println("Is ready packet, current text area is ${jquery.`val`()}") val content = createMessageFromString(jquery.`val`() as String) extendedWindow.postMessage( EmbedEditorCrossWindow.communicationJson.encodeToString( PacketWrapper.serializer(), PacketWrapper( MessageSetupPacket( content, placeholders ) ) ), "*" ) } else if (packet.m is UpdatedMessagePacket) { jquery.`val`((packet.m as UpdatedMessagePacket).content) // Trigger a update jquery.trigger("input", null) // Para recalcular a preview AutoSize.update(jquery) // E para o AutoSize recalcular o tamanho } } }) } } wrapperWithButtons.append(newElement) if (sendTestMessages) { // <button onclick="sendMessage('joinMessage', 'canalJoinId')" class="button-discord button-discord-info pure-button">Test Message</button> val button = jq("<button>") .addClass("button-discord button-discord-info pure-button") .html("<i class=\"fas fa-paper-plane\"></i> ${locale["website.dashboard.testMessage"]}") button.on("click") { event, args -> val textChannelId = if (textChannelSelect != null) { textChannelSelect.`val`() as String } else { null } val json = json( "channelId" to textChannelId, "message" to jquery.`val`(), "sources" to arrayOf("user", "member") ) val dynamic = object{}.asDynamic() dynamic.url = "${loriUrl}api/v1/guilds/$guildId/send-message" dynamic.type = "POST" dynamic.dataType = "json" dynamic.data = JSON.stringify(json) dynamic.success = { data: Json, textStatus: String, event: JQueryXHR -> println(data) } dynamic.error = { event: JQueryXHR, textStatus: String, errorThrown: String -> println("Status: " + event.status) println(event.response) } jQuery.ajax( settings = dynamic ) } wrapperWithButtons.append(button) } wrapperWithButtons.insertBefore(jquery) console.log(div) autosize(jquery) if (showPlaceholders) { println("Displaying placeholders...") // Placeholders são algo mágico, parça val html = StringBuilder().appendHTML(false).div { details(classes = "fancy-details") { summary { + "${locale["loritta.modules.generic.showPlaceholders"]} " i(classes = "fas fa-chevron-down") {} } div(classes = "details-content") { table(classes = "fancy-table") { thead { tr { th { +"Placeholder" } th { +"Significado" } } placeholders.filterNot { it.hidden }.forEach { tr { td { style = "white-space: nowrap;" code(classes = "inline") { + it.name } } td { + (it.description ?: "???") } } } } } } } }.toString() jq(html).insertAfter(jquery) } if (markdownPreview) { val markdownPreview = jq("<div>") .attr("id", jquery.attr("id") + "-markdownpreview") .attr("class", "discord-style") jquery.on("input") { event, args -> val content = jquery.`val`() as String val message = createMessageFromString(content) val renderer = EmbedRenderer(message, placeholders) // Clear the current preview markdownPreview.empty() // And now render the embed! markdownPreview.get()[0].append { div(classes = "theme-light") { renderer.generateMessagePreview(this) } } } markdownPreview.insertAfter( jquery ) } jquery.trigger("input", null) } /** * Creates a (Discord) message from a string. * * If it is a valid JSON, it will be generated via [EmbedRenderer.json], if it is invalid, a object * will be created with the [content] * * @param the input, can be a JSON object as a string or a raw message * @return a [DiscordMessage] */ fun createMessageFromString(content: String): DiscordMessage { return try { val rawMessage = content .replace("\n", "") .replace("\r", "") // Try parsing the current content as JSON if (!(rawMessage.startsWith("{") && rawMessage.endsWith("}"))) // Just to avoid parsing the (probably invalid) JSON throw RuntimeException("Not in a JSON format") EmbedRenderer.json .decodeFromString(DiscordMessage.serializer(), content) } catch (e: Throwable) { // If it fails, probably it is a raw message, so we are going to just create a // DiscordMessage based on that DiscordMessage(content) } } } fun Int.toString(radix: Int): String { val value = this @Suppress("UnsafeCastFromDynamic") return js(code = "value.toString(radix)") }
agpl-3.0
96e0d9e0f3e26678d5c575d18a406d4d
28.197505
252
0.649932
3.523081
false
false
false
false
LorittaBot/Loritta
discord/loritta-bot-common/src/main/kotlin/net/perfectdreams/loritta/morenitta/utils/minecraft/MCUtils.kt
1
2600
package net.perfectdreams.loritta.morenitta.utils.minecraft import com.github.benmanes.caffeine.cache.Caffeine import com.github.kevinsawicki.http.HttpRequest import com.github.salomonbrys.kotson.* import com.google.gson.JsonArray import com.google.gson.JsonParser import net.perfectdreams.loritta.morenitta.LorittaBot.Companion.GSON import net.perfectdreams.loritta.morenitta.utils.extensions.success import java.util.* import java.util.concurrent.TimeUnit /** * Classe de utilidades relacionadas ao Minecraft (como UUID query) */ object MCUtils { val username2uuid = Caffeine.newBuilder().expireAfterWrite(30L, TimeUnit.MINUTES).maximumSize(10000).build<String, String>().asMap() val uuid2profile = Caffeine.newBuilder().expireAfterWrite(5L, TimeUnit.MINUTES).maximumSize(10000).build<String, MCTextures>().asMap() fun getUniqueId(player: String): String? { val lowercase = player.toLowerCase() if (username2uuid.contains(lowercase)) { return username2uuid[lowercase] } if (player.isBlank()) return null val payload = JsonArray() payload.add(player) val connection = HttpRequest.post("https://api.mojang.com/profiles/minecraft") .contentType("application/json") .send(payload.toString()) if (!connection.success()) return null val profile = connection.body() val array = JsonParser.parseString(profile).array array.forEach { username2uuid[it["name"].string.toLowerCase()] = it["id"].string } return username2uuid[lowercase] } fun getUserProfileFromName(username: String): MCTextures? { val uuid = getUniqueId(username) ?: return null return getUserProfile(uuid) } fun getUserProfile(uuid: String): MCTextures? { if (uuid2profile.contains(uuid)) return uuid2profile[uuid] val connection = HttpRequest.get("https://sessionserver.mojang.com/session/minecraft/profile/$uuid") .contentType("application/json") if (!connection.success()) return null val rawJson = connection.body() val profile = JsonParser.parseString(rawJson).obj val textureValue = profile["properties"].array.firstOrNull { it["name"].nullString == "textures" } if (textureValue == null) { uuid2profile[uuid] = null return null } val str = textureValue["value"].string val json = String(Base64.getDecoder().decode(str)) uuid2profile[uuid] = GSON.fromJson(json) return uuid2profile[uuid] } class MCTextures( val timestamp: Long, val profileId: String, val profileName: String, val signatureRequired: Boolean?, val textures: Map<String, TextureValue> ) class TextureValue( val url: String ) }
agpl-3.0
53c5113db1c803b7728e4925f7f68d93
26.967742
135
0.745
3.661972
false
false
false
false
LorittaBot/Loritta
discord/loritta-bot-common/src/test/kotlin/net/perfectdreams/loritta/utils/LoriReplyTest.kt
1
1553
package net.perfectdreams.loritta.morenitta.utils import net.perfectdreams.loritta.morenitta.messages.LorittaReply import io.mockk.every import io.mockk.mockk import net.dv8tion.jda.api.entities.User import net.perfectdreams.loritta.morenitta.platform.discord.legacy.entities.jda.JDAUser import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test class LoriReplyTest { val user = mockk<User>() val userId = "123170274651668480" init { every { user.asMention } returns "<@$userId>" } @Test fun `simple lori reply`() { val loriReply = LorittaReply(message = "Hello World!") assertThat(loriReply.build(JDAUser(user))).isEqualTo(Constants.LEFT_PADDING + " **|** <@123170274651668480> Hello World!") } @Test fun `lori reply with custom prefix`() { val loriReply = LorittaReply(message = "Hello World!", prefix = "<:whatdog:388420518107414528>") assertThat(loriReply.build(JDAUser(user))).isEqualTo("<:whatdog:388420518107414528> **|** <@123170274651668480> Hello World!") } @Test fun `lori reply without mention`() { val loriReply = LorittaReply(message = "Hello World!", mentionUser = false) assertThat(loriReply.build(JDAUser(user))).isEqualTo(Constants.LEFT_PADDING + " **|** Hello World!") } @Test fun `lori reply without mention and with custom prefix`() { val loriReply = LorittaReply(message = "Hello World!", mentionUser = false, prefix = "<:whatdog:388420518107414528>") assertThat(loriReply.build(JDAUser(user))).isEqualTo("<:whatdog:388420518107414528> **|** Hello World!") } }
agpl-3.0
e739ce67420e75c6b087de157efe8b85
32.782609
128
0.739858
3.361472
false
true
false
false
LorittaBot/Loritta
web/embed-editor/embed-editor/src/main/kotlin/net/perfectdreams/loritta/embededitor/editors/EmbedImageEditor.kt
1
1773
package net.perfectdreams.loritta.embededitor.editors import kotlinx.html.classes import kotlinx.html.js.onClickFunction import net.perfectdreams.loritta.embededitor.EmbedEditor import net.perfectdreams.loritta.embededitor.data.DiscordEmbed import net.perfectdreams.loritta.embededitor.utils.lovelyButton object EmbedImageEditor : EditorBase { val isNotNull: ELEMENT_CONFIGURATION = { m, discordMessage, currentElement, renderInfo -> currentElement.classes += "clickable" currentElement.onClickFunction = { imagePopup(discordMessage.embed!!, m) } } val isNull: ELEMENT_CONFIGURATION = { m, discordMessage, currentElement, renderInfo -> lovelyButton( "fas fa-image", "Adicionar Imagem" ) { imagePopup(discordMessage.embed!!, m) } } fun imagePopup(embed: DiscordEmbed, m: EmbedEditor) = genericPopupTextInputWithSaveAndDelete( m, { val realLink = it.ifBlank { null } if (realLink != null) m.activeMessage!!.copy( embed = m.activeMessage!!.embed!!.copy( image = DiscordEmbed.EmbedUrl( realLink ) ) ) else m.activeMessage!!.copy( embed = m.activeMessage!!.embed!!.copy(image = null) ) }, { m.activeMessage!!.copy( embed = m.activeMessage!!.embed!!.copy(image = null) ) }, embed.image?.url ?: "", 6000 ) }
agpl-3.0
54e55c20e7c5f445a8494f6664d37160
33.784314
97
0.522279
5.540625
false
false
false
false
GBenoitG/AndroidTools_NetworkManager
app/src/main/java/com/bendev/networkmanager/data/network/result/NetworkError.kt
1
708
package com.bendev.networkmanager.data.network.result import java.net.ConnectException import java.net.UnknownHostException enum class NetworkError( val code: Int ) { UNAUTHORIZED(401), FORBIDDEN(403), NOT_FOUND(404), NO_CONNECTION(-1), UNKNOWN_ERROR(-2) ; companion object { fun fromCode(code: Int): NetworkError = values().find { it.code == code } ?: UNKNOWN_ERROR fun fromException(e: Exception): NetworkError = when (e) { is UnknownHostException, is ConnectException -> NO_CONNECTION else -> UNKNOWN_ERROR } } override fun toString(): String { return "ErrorType($name=(code: $code))" } }
gpl-3.0
e69a236a33e3954623784b7f8253b20c
23.448276
98
0.627119
4.239521
false
false
false
false
rectangle-dbmi/Realtime-Port-Authority
app/src/main/java/rectangledbmi/com/pittsburghrealtimetracker/predictions/ProcessedPredictions.kt
1
1608
package rectangledbmi.com.pittsburghrealtimetracker.predictions import com.google.android.gms.maps.model.Marker import com.rectanglel.patstatic.patterns.response.Pt import com.rectanglel.patstatic.predictions.PredictionsType import com.rectanglel.patstatic.predictions.PredictionsView import com.rectanglel.patstatic.predictions.response.Prd import com.rectanglel.patstatic.vehicles.response.Vehicle import java.text.SimpleDateFormat import java.util.* import kotlin.IllegalArgumentException /** * * Holds prediction info for the [PredictionsView]. * * Created by epicstar on 10/14/16. * @author Jeremy Jao * @since 78 */ data class ProcessedPredictions(val marker: Marker, private val predictionsType: PredictionsType, private val predictionList: List<Prd>) { val predictions: String by lazy { val dateFormatPrint = "hh:mm a" val dateFormat = SimpleDateFormat(dateFormatPrint, Locale.US) dateFormat.timeZone = TimeZone.getTimeZone("America/New_York") val str = predictionList.joinToString(separator = "\n", transform = { prd -> when (predictionsType) { is Pt -> "${prd.rt} (${prd.vid}): ${dateFormat.format(prd.prdtm)}" is Vehicle -> "(${prd.stpid}) ${prd.stpnm}: ${dateFormat.format(prd.prdtm)}" else -> throw IllegalArgumentException() // this should never happen } }) if (str.isNotEmpty()) str else "No predictions available." } // predictionsType is already in the marker but there's an IllegalStateException if not on main thread when running marker.getTag()... }
gpl-3.0
17041ac7e86d5ce63c66c4a3cd77a11d
43.666667
140
0.717662
3.97037
false
false
false
false
KameLong/AOdia
app/src/main/java/com/kamelong/aodia/SearchSystem/RouteView.kt
1
1539
package com.kamelong.aodia.SearchSystem import com.kamelong.aodia.KLdatabase.RouteStation import com.kamelong.aodia.KLdatabase.Station import java.io.File import android.content.Context import android.util.AttributeSet import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.* import com.kamelong.aodia.KLdatabase.KLdetabase import com.kamelong.aodia.MainActivity import com.kamelong.aodia.R import java.util.jar.Attributes class RouteView(private val activity:MainActivity, private val connect:ConnectLine,routeViewClicked: OnRouteViewClicked) :LinearLayout(activity) { init{ LayoutInflater.from(context).inflate(R.layout.search_route_view, this) this.findViewById<TextView>(R.id.routeName).setText(connect.routeName) this.findViewById<TextView>(R.id.direction).setText(connect.directionName) this.findViewById<Button>(R.id.openTimeTable).setOnClickListener { routeViewClicked.onRouteTimeTableClicked(connect.routeID) } this.findViewById<Button>(R.id.openStationTimeTable).setOnClickListener { routeViewClicked.onStationTimeTableClicked(connect.routeID,connect.direction) } } class ConnectLine{ var routeID:String=""; var direction:Int=0 lateinit var file: File; var routeName:String="" var directionName:String="" var seq=0 } } interface OnRouteViewClicked{ fun onRouteTimeTableClicked(routeID:String) fun onStationTimeTableClicked(routeID:String,direction:Int) }
gpl-3.0
da4e813a06a46248d7e5770ba000df84
36.560976
161
0.779077
3.818859
false
false
false
false
spaceisstrange/ToListen
ToListen/app/src/main/java/io/spaceisstrange/tolisten/ui/adapters/ArtistsAdapter.kt
1
3597
/* * Made with <3 by Fran González (@spaceisstrange) * * 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, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package io.spaceisstrange.tolisten.ui.adapters import android.support.v7.widget.RecyclerView import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import com.bumptech.glide.Glide import io.spaceisstrange.tolisten.R import io.spaceisstrange.tolisten.data.database.Database import io.spaceisstrange.tolisten.data.model.Artist import kotlinx.android.synthetic.main.list_artist_search_item.view.* /** * Adapter for every RecyclerView showing a list of artists */ class ArtistsAdapter(val layoutId: Int = R.layout.list_artist_item) : RecyclerView.Adapter<ArtistsAdapter.ArtistHolder>() { /** * List of artists to show in the adapter */ var artists: List<Artist> = arrayListOf() /** * Method to call when the user presses a holder */ var onClick: ((artist: Artist) -> Unit)? = null /** * Method to call when the checkbox (if any) state changes */ var onCheckboxChange: ((artist: Artist, state: Boolean) -> Unit)? = null override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): ArtistHolder { val view = LayoutInflater.from(parent?.context).inflate(layoutId, parent, false) val holder = ArtistHolder(view) // Call the onClick callback with the selected artist when the view is clicked holder.itemView.setOnClickListener { onClick?.invoke(artists[holder.adapterPosition]) } // Call the onCheckboxChange when the checkbox (if any) is checked or unchecked holder.itemView.artistAdded?.setOnCheckedChangeListener { button, state -> onCheckboxChange?.invoke(artists[holder.adapterPosition], state) } return holder } override fun onBindViewHolder(holder: ArtistHolder?, position: Int) { holder?.bindItem(artists[position]) } override fun getItemCount(): Int { return artists.size } /** * Updates the content of the current artist list */ fun updateArtists(artists: List<Artist>) { this.artists = artists notifyDataSetChanged() } /** * Holder for an artist with a cover image and the artist's name */ class ArtistHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { fun bindItem(artist: Artist) { // Load the artist's cover image (if any) Glide.with(itemView.context) .load(artist.pictureUrl) .placeholder(R.color.cardview_dark_background) .error(R.color.cardview_dark_background) .into(itemView.artistCover) itemView.artistName.text = artist.name // Especial case for the search itemView.artistAdded?.isChecked = Database.artistExists(artist.id) } } }
gpl-3.0
44968563eec9227ff16d29787c2c76e9
34.613861
123
0.682147
4.39072
false
false
false
false
vsch/SmartData
test/src/com/vladsch/smart/SmartVersionedDataTest.kt
1
23107
/* * Copyright (c) 2015-2020 Vladimir Schneider <[email protected]> * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ @file:Suppress("UNUSED_VARIABLE", "UNUSED_ANONYMOUS_PARAMETER", "UNUSED_VALUE", "VARIABLE_WITH_REDUNDANT_INITIALIZER", "ASSIGNED_BUT_NEVER_ACCESSED_VARIABLE") package com.vladsch.smart import org.junit.Assert.* import org.junit.Test class SmartVersionedDataTest { @Test fun test_immutable() { for (i in -10..10) { val v1 = SmartImmutableData(i) assertFalse(v1.isStale) assertFalse(v1.isMutable) assertEquals(i, v1.get()) } } @Test fun test_volatile() { val v1 = SmartVolatileData(0) val v2 = SmartVolatileData(1) assertFalse(v1.isStale) assertFalse(v2.isStale) assertTrue(v1.isMutable) assertTrue(v1.versionSerial < v2.versionSerial) v1.set(5) assertFalse(v1.versionSerial < v2.versionSerial) assertEquals(5, v1.get()) val v1Serial = v1.versionSerial v1.set(5) assertEquals(v1Serial, v1.versionSerial) SmartVersionManager.groupedUpdate(Runnable { v1.set(10) v2.set(11) }) assertEquals(v1.versionSerial, v2.versionSerial) assertEquals(10, v1.get()) assertEquals(11, v2.get()) val v1Version = v1.versionSerial v1.nextVersion() assertEquals(v1Version, v1.versionSerial) val v2Version = v2.versionSerial v2.nextVersion() assertEquals(v2Version, v2.versionSerial) v1.set(2) v2.set(3) assertTrue(v1.versionSerial < v2.versionSerial) SmartVersionManager.groupedUpdate(Runnable { v1.set(4) v2.set(5) }) assertEquals(v1.versionSerial, v2.versionSerial) v1.set(6) v2.set(7) SmartVersionManager.groupedCompute { v1.set(8) v2.set(9) } assertEquals(v1.versionSerial, v2.versionSerial) } @Test fun test_updateDependent() { val v1 = SmartVolatileData(1) val v2 = SmartVolatileData(2) val v3 = SmartVolatileData(3) val vc = SmartDependentData(v3) { v3.get() } val sum: () -> Int = { v1.get() + v2.get() + vc.get() } val sumEq = { v1.get() + v2.get() + v3.get() } val dv = SmartUpdateDependentData(listOf(v1, v2, vc), sum) var dv2 = SmartUpdateDependentData(listOf(vc), sum) val vi = SmartImmutableData(10) val dvn = SmartLatestDependentData(listOf(vi)) assertTrue(dv.isMutable) assertFalse(dv.isStale) v2.set(21) assertTrue(dv.isStale) dv.nextVersion() assertFalse(dv.isStale) assertEquals(sumEq(), dv.get()) assertFalse(dvn.isMutable) assertFalse(dvn.isStale) assertEquals(10, dvn.get()) assertEquals(v1.versionSerial.max(v2.versionSerial, v3.versionSerial), dv.versionSerial) assertEquals(sumEq(), dv.get()) v3.set(31) vc.get() assertEquals(v3.versionSerial, vc.versionSerial) assertEquals(v3.get(), vc.get()) // println("v1: ${v1.versionSerial}, v2: ${v2.versionSerial}, v3: ${v3.versionSerial}, vc: ${vc.versionSerial} : dv: ${dv.versionSerial} ${dv.isStale}") assertTrue(dv.isStale) dv.nextVersion() assertFalse(dv.isStale) assertEquals(v1.versionSerial.max(v2.versionSerial, v3.versionSerial), dv.versionSerial) assertEquals(sumEq(), dv.get()) v3.set(32) assertTrue(dv.isStale) dv.nextVersion() assertFalse(dv.isStale) assertEquals(v1.versionSerial.max(v2.versionSerial, v3.versionSerial), dv.versionSerial) assertEquals(sumEq(), dv.get()) } @Test fun test_dependent() { val v1 = SmartVolatileData(1) val v2 = SmartVolatileData(2) val v3 = SmartVolatileData(3) val vc = SmartDependentData(v3) { v3.get() } val sum = { v1.get() + v2.get() + vc.get() } val sumEq = { v1.get() + v2.get() + v3.get() } val dv = SmartDependentData(listOf(v1, v2, vc), sum) val vi = SmartImmutableData(10) val dvn = SmartIterableData(listOf(vi)) { it -> vi.get() } assertTrue(dv.isMutable) assertFalse(dv.isStale) v2.set(21) dv.get() assertFalse(dv.isStale) assertEquals(sumEq(), dv.get()) assertFalse(dvn.isMutable) assertFalse(dvn.isStale) assertEquals(10, dvn.get()) assertEquals(v1.versionSerial.max(v2.versionSerial, v3.versionSerial), dv.versionSerial) assertEquals(sumEq(), dv.get()) v3.set(31) dv.get() assertEquals(v3.versionSerial, vc.versionSerial) assertEquals(v3.get(), vc.get()) // println("v1: ${v1.versionSerial}, v2: ${v2.versionSerial}, v3: ${v3.versionSerial}, vc: ${vc.versionSerial} : dv: ${dv.versionSerial} ${dv.isStale}") assertFalse(dv.isStale) assertEquals(v1.versionSerial.max(v2.versionSerial, v3.versionSerial), dv.versionSerial) assertEquals(sumEq(), dv.get()) v3.set(32) dv.get() assertFalse(dv.isStale) assertEquals(v1.versionSerial.max(v2.versionSerial, v3.versionSerial), dv.versionSerial) assertEquals(sumEq(), dv.get()) } @Test fun test_dependentIterable() { val v1 = SmartVolatileData(1) val v2 = SmartVolatileData(2) val v3 = SmartVolatileData(3) val vc = SmartDependentData(v3) { v3.get() } val sum = IterableDataComputable<Int> { it.sumBy { it } } val sumEq = { v1.get() + v2.get() + v3.get() } val dv = SmartVectorData(listOf(v1, v2, vc), sum) val vi = SmartImmutableData(10) val dvn = SmartIterableData(listOf(vi)) { it -> vi.get() } assertTrue(dv.isMutable) assertFalse(dv.isStale) v2.set(21) dv.get() assertFalse(dv.isStale) assertEquals(sumEq(), dv.get()) assertFalse(dvn.isMutable) assertFalse(dvn.isStale) assertEquals(10, dvn.get()) assertEquals(v1.versionSerial.max(v2.versionSerial, v3.versionSerial), dv.versionSerial) assertEquals(sumEq(), dv.get()) v3.set(31) dv.get() assertEquals(v3.versionSerial, vc.versionSerial) assertEquals(v3.get(), vc.get()) // println("v1: ${v1.versionSerial}, v2: ${v2.versionSerial}, v3: ${v3.versionSerial}, vc: ${vc.versionSerial} : dv: ${dv.versionSerial} ${dv.isStale}") assertFalse(dv.isStale) assertEquals(v1.versionSerial.max(v2.versionSerial, v3.versionSerial), dv.versionSerial) assertEquals(sumEq(), dv.get()) v3.set(32) dv.get() assertFalse(dv.isStale) assertEquals(v1.versionSerial.max(v2.versionSerial, v3.versionSerial), dv.versionSerial) assertEquals(sumEq(), dv.get()) } @Test fun test_snapshot() { val v1 = SmartImmutableData("v1", 1) val v2 = SmartVolatileData("v2", 2) val vs1 = SmartCachedData("vs1", v1) val vs2 = SmartCachedData("vs2", v2) println("$v1, $v2, $vs1, $vs2") assertFalse(vs1.isMutable) assertFalse(vs1.isStale) assertEquals(v1.versionSerial, vs1.versionSerial) assertEquals(v1.get(), vs1.get()) assertFalse(vs2.isMutable) assertFalse(vs2.isStale) assertEquals(v2.versionSerial, vs2.versionSerial) assertEquals(v2.get(), vs2.get()) v2.set(22) assertFalse(vs2.isMutable) assertTrue(vs2.isStale) assertNotEquals(v2.versionSerial, vs2.versionSerial) assertNotEquals(v2.get(), vs2.get()) } @Test fun test_latest() { val v1 = SmartImmutableData("v1", 1) val v2 = SmartVolatileData("v2", 2) val v3 = SmartVolatileData("v3", 3) var vs: SmartVersionedDataHolder<Int> = v1 vs = SmartLatestDependentData("vs2", listOf(v1, v2, v3)) { println("$v1, $v2, $v3, $vs") } var va: SmartVersionedDataHolder<Int> = v1 va = v3 assertTrue(vs.isMutable) assertFalse(vs.isStale) assertEquals(va.versionSerial, vs.versionSerial) assertEquals(va.get(), vs.get()) v2.set(22) va = v2 vs.get() assertTrue(vs.isMutable) assertFalse(vs.isStale) // println("$v1, $v2, $v3, $vs") assertEquals(va.versionSerial, vs.versionSerial) assertEquals(va.get(), vs.get()) v3.set(33) va = v3 vs.get() assertTrue(vs.isMutable) assertFalse(vs.isStale) // println("$v1, $v2, $v3, $vs") assertEquals(va.versionSerial, vs.versionSerial) assertEquals(va.get(), vs.get()) } @Test fun test_Fun() { val v1 = SmartVolatileData(10.0) val v2 = SmartVolatileData(5.0) val v3 = SmartVolatileData(3.0) val vd = SmartVectorData(listOf(v1, v2, v3)) { val prod = it.fold(1.0) { a, b -> a * b } println(it.fold("product of ") { a, b -> "$a $b" } + " = $prod") prod } var t = vd.get() v2.set(2.0) t = vd.get() v1.set(7.0) t = vd.get() v1.set(7.0) v2.set(7.0) v3.set(7.0) t = vd.get() } @Test fun test_Recursive() { val v1 = SmartVolatileData(10.0) val v2 = SmartVolatileData(5.0) val v3 = SmartVolatileData(3.0) val vd = SmartVectorData<Double>(listOf(v1, v2, v3)) { val prod = it.fold(1.0) { a, b -> a * b } println(it.fold("product of ") { a, b -> "$a $b" } + " = $prod") prod } val vd2 = SmartVectorData<Double>(listOf(v1, v2, v3, vd)) { val sumOf = it.sum() println(it.fold("sum of ") { a, b -> "$a $b" } + " = $sumOf") v3.set(sumOf) sumOf } var t = vd.get() var t2 = vd2.get() v2.set(2.0) t = vd.get() t2 = vd2.get() v1.set(7.0) t = vd.get() t2 = vd2.get() v1.set(7.0) v2.set(7.0) v3.set(7.0) t = vd.get() t2 = vd2.get() } @Test fun test_aliased() { val v1 = SmartImmutableData(1) val v2 = SmartVolatileData(5) val v3 = SmartVolatileData(3) val ad = SmartVersionedDataAlias(v1) var va: SmartVersionedDataHolder<Int> = v1 val vd = SmartVectorData<Int>(listOf(v1, v2, v3, ad)) { val prod = it.fold(1) { a, b -> a * b } println(it.fold("product of ") { a, b -> "$a $b" } + " = $prod") prod } assertTrue(vd.isMutable) va = v1 assertFalse(vd.isStale) assertEquals(va.get(), ad.get()) assertTrue(ad.isMutable) assertTrue(va.versionSerial <= ad.versionSerial) ad.alias = v2 va = v2 vd.get() assertFalse(vd.isStale) assertEquals(va.get(), ad.get()) assertTrue(ad.isMutable) assertTrue(va.versionSerial <= ad.versionSerial) ad.alias = v3 va = v3 vd.get() assertFalse(vd.isStale) assertEquals(va.get(), ad.get()) assertTrue(ad.isMutable) assertTrue(va.versionSerial <= ad.versionSerial) ad.alias = vd va = vd vd.get() assertFalse(vd.isStale) assertEquals(va.get(), ad.get()) assertTrue(ad.isMutable) assertTrue(va.versionSerial <= ad.versionSerial) ad.touchVersionSerial() vd.get() assertFalse(vd.isStale) assertEquals(va.get(), ad.get()) assertTrue(ad.isMutable) assertTrue(va.versionSerial <= ad.versionSerial) } @Test fun test_property() { val v1 = SmartVolatileData("v1", 1) val v2 = SmartVolatileData("v2", 20) val va = SmartVersionedDataAlias("va", v1) val vp = SmartVersionedProperty("vp", 0) assertTrue(vp.isMutable) assertEquals(0, vp.get()) va.set(2) vp.connect(va) assertTrue(vp.isStale) assertEquals(2, vp.get()) vp.set(2) assertTrue(vp.isStale) assertEquals(2, vp.get()) vp.disconnect() assertTrue(vp.isStale) assertEquals(2, vp.get()) vp.set(5) assertTrue(vp.isStale) assertEquals(5, vp.get()) vp.connect(va) assertTrue(vp.isStale) assertEquals(2, vp.get()) va.alias = v2 assertEquals(20, va.get()) assertTrue(vp.isStale) assertEquals(20, vp.get()) println(vp) vp.connectionFinalized() println(vp) assertFalse(vp.isStale) assertEquals(20, vp.get()) va.alias = v1 v1.set(100) assertFalse(vp.isStale) assertEquals(20, vp.get()) v2.set(200) assertTrue(vp.isStale) assertEquals(200, vp.get()) } @Test fun test_propertyArrayDistribute() { val v1 = SmartVolatileData(1) val v2 = SmartVolatileData(20) val v3 = SmartVolatileData(20) val va1 = SmartVersionedDataAlias(v1) val va2 = SmartVersionedDataAlias(v2) val va3 = SmartVersionedDataAlias(v3) var called = 0 var inAggr = false val pa = SmartVersionedPropertyArray<Int>("pa", 3, 0, DataValueComputable { assertFalse(inAggr) try { inAggr = true // print("aggregating: ") // for (n in it) { // print("$n ") // } // println() called++ it.sum() } finally { inAggr = false } }, DataValueComputable { assertFalse(inAggr) try { inAggr = true // println("distributing") called++ DistributingIterator(3, it) } finally { inAggr = false } }) // test as distributing pa.get() assertEquals(0, pa.get()) println("called: $called") // println(pa) for (i in 0..10) { pa.set(i) assertEquals(i, pa.get()) // print("i:$i ") // for (c in 0..2) { // val col = (i / 3) + if (c < (i - (i / 3) * 3)) 1 else 0 // print("[$c] -> $col ") // } // println() for (c in 0..2) { val col = (i / 3) + if (c < (i - (i / 3) * 3)) 1 else 0 assertEquals(col, pa[c].get()) } // println(pa) assertEquals(i, pa.get()) // println(pa) println("called: $called") } // test connected distribution pa.connect(v1) for (i in 0..10) { v1.set(i) assertEquals(i, pa.get()) // print("i:$i ") // for (c in 0..2) { // val col = (i / 3) + if (c < (i - (i / 3) * 3)) 1 else 0 // print("[$c] -> $col ") // } // println() for (c in 0..2) { val col = (i / 3) + if (c < (i - (i / 3) * 3)) 1 else 0 assertEquals(col, pa[c].get()) } // println(pa) assertEquals(i, pa.get()) // println(pa) println("called: $called") } } @Test fun test_propertyArrayAggregate() { val v1 = SmartVolatileData(1) val v2 = SmartVolatileData(20) val v3 = SmartVolatileData(3) val va = SmartVersionedDataAlias(v1) var called = 0 var inAggr = false val pa = SmartVersionedPropertyArray<Int>("pa", 3, 0, DataValueComputable { assertFalse(inAggr) try { inAggr = true // print("aggregating: ") // for (n in it) { // print("$n ") // } // println() called++ it.sum() } finally { inAggr = false } }, DataValueComputable { assertFalse(inAggr) try { inAggr = true // println("distributing") called++ DistributingIterator(3, it) } finally { inAggr = false } }) // test as aggregating pa.get() assertEquals(0, pa.get()) println("called: $called") pa[0].set(1) pa.get() println(pa) assertEquals(1, pa.get()) println("called: $called") pa[1].set(2) assertEquals(3, pa.get()) println("called: $called") pa[2].set(3) assertEquals(6, pa.get()) println("called: $called") for (a in 1..6) { pa[0].set(a) for (b in 1..6) { pa[1].set(b) for (c in 1..6) { pa[2].set(c) assertEquals(a + b + c, pa.get()) } } } // test a connected array property pa[0].connect(v1) pa.get() println(pa) v1.set(10) pa[1].set(20) pa[2].set(30) println("about to value") pa.get() println(pa) assertEquals(60, pa.get()) for (a in 1..6) { v1.set(a) for (b in 1..6) { pa[1].set(b) for (c in 1..6) { pa[2].set(c) assertEquals(a + b + c, pa.get()) } } } pa[1].connect(v2) for (a in 1..6) { v1.set(a) for (b in 1..6) { v2.set(b) for (c in 1..6) { pa[2].set(c) assertEquals(a + b + c, pa.get()) } } } pa[2].connect(v3) for (a in 1..6) { v1.set(a) for (b in 1..6) { v2.set(b) for (c in 1..6) { v3.set(c) assertEquals(a + b + c, pa.get()) } } } println("called: $called") } @Test fun test_propertyArrayDistributor() { val v1 = SmartVolatileData(1) val v2 = SmartVolatileData(20) val v3 = SmartVolatileData(20) val va1 = SmartVersionedDataAlias(v1) val va2 = SmartVersionedDataAlias(v2) val va3 = SmartVersionedDataAlias(v3) val pa = SmartVersionedIntAggregatorDistributor("pa", 3, 0) // test as distributing pa.get() assertEquals(0, pa.get()) // println(pa) for (i in 0..10) { pa.set(i) assertEquals(i, pa.get()) // print("i:$i ") // for (c in 0..2) { // val col = (i / 3) + if (c < (i - (i / 3) * 3)) 1 else 0 // print("[$c] -> $col ") // } // println() for (c in 0..2) { val col = (i / 3) + if (c < (i - (i / 3) * 3)) 1 else 0 assertEquals(col, pa[c].get()) } // println(pa) assertEquals(i, pa.get()) // println(pa) } // test connected distribution pa.connect(v1) for (i in 0..10) { v1.set(i) assertEquals(i, pa.get()) // print("i:$i ") // for (c in 0..2) { // val col = (i / 3) + if (c < (i - (i / 3) * 3)) 1 else 0 // print("[$c] -> $col ") // } // println() for (c in 0..2) { val col = (i / 3) + if (c < (i - (i / 3) * 3)) 1 else 0 assertEquals(col, pa[c].get()) } // println(pa) assertEquals(i, pa.get()) // println(pa) } } @Test fun test_propertyArrayAggregator() { val v1 = SmartVolatileData(1) val v2 = SmartVolatileData(20) val v3 = SmartVolatileData(3) val va = SmartVersionedDataAlias(v1) val pa = SmartVersionedIntAggregatorDistributor("pa", 3, 0) // test as aggregating pa.get() assertEquals(0, pa.get()) pa[0].set(1) pa.get() println(pa) assertEquals(1, pa.get()) pa[1].set(2) assertEquals(3, pa.get()) pa[2].set(3) assertEquals(6, pa.get()) for (a in 1..6) { pa[0].set(a) for (b in 1..6) { pa[1].set(b) for (c in 1..6) { pa[2].set(c) assertEquals(a + b + c, pa.get()) } } } // test a connected array property pa[0].connect(v1) pa.get() println(pa) v1.set(10) pa[1].set(20) pa[2].set(30) println("about to value") pa.get() println(pa) assertEquals(60, pa.get()) for (a in 1..6) { v1.set(a) for (b in 1..6) { pa[1].set(b) for (c in 1..6) { pa[2].set(c) assertEquals(a + b + c, pa.get()) } } } pa[1].connect(v2) for (a in 1..6) { v1.set(a) for (b in 1..6) { v2.set(b) for (c in 1..6) { pa[2].set(c) assertEquals(a + b + c, pa.get()) } } } pa[2].connect(v3) for (a in 1..6) { v1.set(a) for (b in 1..6) { v2.set(b) for (c in 1..6) { v3.set(c) assertEquals(a + b + c, pa.get()) } } } } }
apache-2.0
8e27fc26b6393a259864c99c3c3c2722
27.95614
167
0.495261
3.634319
false
true
false
false
jitsi/jitsi-videobridge
jitsi-media-transform/src/main/kotlin/org/jitsi/nlj/transform/PipelineDsl.kt
1
2728
/* * Copyright @ 2018 - Present, 8x8 Inc * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jitsi.nlj.transform import org.jitsi.nlj.PacketInfo import org.jitsi.nlj.transform.node.ConditionalPacketPath import org.jitsi.nlj.transform.node.DemuxerNode import org.jitsi.nlj.transform.node.ExclusivePathDemuxer import org.jitsi.nlj.transform.node.Node import org.jitsi.nlj.transform.node.TransformerNode import org.jitsi.rtp.Packet // TODO: look into @DslMarker to prevent inner dsl builders from accidentally setting parent // member variables when they overlap fun DemuxerNode.packetPath(b: ConditionalPacketPath.() -> Unit) { this.addPacketPath(ConditionalPacketPath().apply(b)) } class PipelineBuilder { private var head: Node? = null private var tail: Node? = null private fun addNode(node: Node) { if (head == null) { head = node } if (tail is DemuxerNode) { // In the future we could separate 'input/output' nodes from purely // input nodes and use that here? throw Exception("Cannot attach node to a DemuxerNode") } tail?.attach(node) tail = node } fun node(node: Node, condition: () -> Boolean = { true }) { if (condition()) { addNode(node) } } /** * simpleNode allows the caller to pass in a block of code which takes a list of input * [Packet]s and returns a list of output [Packet]s to be forwarded to the next * [Node] */ fun simpleNode(name: String, packetHandler: (PacketInfo) -> PacketInfo?) { val node = object : TransformerNode(name) { override fun transform(packetInfo: PacketInfo): PacketInfo? { return packetHandler.invoke(packetInfo) } override val aggregationKey = this.name override fun trace(f: () -> Unit) = f.invoke() } addNode(node) } fun demux(name: String, block: DemuxerNode.() -> Unit) { val demuxer = ExclusivePathDemuxer(name).apply(block) addNode(demuxer) } fun build(): Node = head!! } fun pipeline(block: PipelineBuilder.() -> Unit): Node = PipelineBuilder().apply(block).build()
apache-2.0
3a713157b01f42b126ad2c2280ac5edf
33.531646
94
0.667155
4.005874
false
false
false
false
emce/smog
app/src/main/java/mobi/cwiklinski/smog/database/AppUriMatcher.kt
1
725
package mobi.cwiklinski.smog.database import android.content.UriMatcher import android.text.TextUtils class AppUriMatcher { public companion object { val PATH_SEPARATOR = "/"; val NUMBER = "#"; val WILDCARD = "*"; val READINGS = 100; val READINGS_ID = 101; } var matcher: UriMatcher = UriMatcher(UriMatcher.NO_MATCH) init { addEndpoint(matcher, READINGS, AppContract.PATH_READINGS); addEndpoint(matcher, READINGS_ID, AppContract.PATH_READINGS, NUMBER); } fun addEndpoint(matcher: UriMatcher, code: Int, vararg pathSegments: String) { matcher.addURI(AppContract.AUTHORITY, TextUtils.join(PATH_SEPARATOR, pathSegments), code); } }
apache-2.0
4e4b99c717672b734165743b77f2979f
28.04
98
0.673103
4.096045
false
false
false
false
Deletescape-Media/Lawnchair
lawnchair/src/app/lawnchair/theme/color/ColorOption.kt
1
2896
package app.lawnchair.theme.color import android.graphics.Color import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.stringResource import app.lawnchair.ui.preferences.components.colorpreference.ColorPreferenceEntry import app.lawnchair.ui.theme.getSystemAccent import app.lawnchair.wallpaper.WallpaperManagerCompat import com.android.launcher3.R import com.android.launcher3.Utilities sealed class ColorOption { abstract val isSupported: Boolean abstract val colorPreferenceEntry: ColorPreferenceEntry<ColorOption> object SystemAccent : ColorOption() { override val isSupported = true override val colorPreferenceEntry = ColorPreferenceEntry<ColorOption>( this, { stringResource(id = R.string.system) }, { LocalContext.current.getSystemAccent(false) }, { LocalContext.current.getSystemAccent(true) } ) override fun toString() = "system_accent" } object WallpaperPrimary : ColorOption() { override val isSupported = Utilities.ATLEAST_O_MR1 override val colorPreferenceEntry = ColorPreferenceEntry<ColorOption>( this, { stringResource(id = R.string.wallpaper) }, { val context = LocalContext.current val wallpaperManager = WallpaperManagerCompat.INSTANCE.get(context) val primaryColor = wallpaperManager.wallpaperColors?.primaryColor primaryColor ?: LawnchairBlue.color } ) override fun toString() = "wallpaper_primary" } class CustomColor(val color: Int) : ColorOption() { override val isSupported = true override val colorPreferenceEntry = ColorPreferenceEntry<ColorOption>( this, { stringResource(id = R.string.custom) }, { color } ) constructor(color: Long) : this(color.toInt()) override fun equals(other: Any?) = other is CustomColor && other.color == color override fun hashCode() = color override fun toString() = "custom|#${String.format("%08x", color)}" } companion object { val LawnchairBlue = CustomColor(0xFF007FFF) fun fromString(stringValue: String) = when (stringValue) { "system_accent" -> SystemAccent "wallpaper_primary" -> WallpaperPrimary else -> instantiateCustomColor(stringValue) } private fun instantiateCustomColor(stringValue: String): ColorOption { try { if (stringValue.startsWith("custom")) { val color = Color.parseColor(stringValue.substring(7)) return CustomColor(color) } } catch (e: IllegalArgumentException) { // ignore } return SystemAccent } } }
gpl-3.0
db68566eb91f0c15d509d141b2478f31
32.674419
87
0.637086
5.045296
false
false
false
false
google/horologist
compose-tools/src/main/java/com/google/android/horologist/compose/tools/a11y/ComposeA11yExtension.kt
1
5488
/* * Copyright 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ @file:OptIn(ExperimentalHorologistPaparazziApi::class) package com.google.android.horologist.compose.tools.a11y import android.view.View import android.view.ViewGroup import androidx.compose.ui.graphics.toAndroidRect import androidx.compose.ui.node.RootForTest import androidx.compose.ui.platform.ComposeView import androidx.compose.ui.platform.ViewRootForTest import androidx.compose.ui.semantics.SemanticsActions import androidx.compose.ui.semantics.SemanticsNode import androidx.compose.ui.semantics.SemanticsProperties import androidx.compose.ui.semantics.getOrNull import app.cash.paparazzi.RenderExtension import com.google.android.horologist.compose.tools.ExperimentalHorologistComposeToolsApi import com.google.android.horologist.paparazzi.ExperimentalHorologistPaparazziApi import com.google.android.horologist.paparazzi.a11y.AccessibilityState /** * Paparazzi Render Extension that collects Accessibility information for Compose * hierarchies. * * Currently captures Content Description, State Description, On Click, Role, Disabled, * Heading, Custom Actions, Text, and Progress. These are saved as AccessibilityState.Element in * the [accessibilityState] list. */ @ExperimentalHorologistComposeToolsApi public class ComposeA11yExtension : RenderExtension { public lateinit var accessibilityState: AccessibilityState private lateinit var rootForTest: RootForTest init { ViewRootForTest.onViewCreatedCallback = { viewRoot -> viewRoot.view.addOnAttachStateChangeListener(object : View.OnAttachStateChangeListener { override fun onViewAttachedToWindow(p0: View) { // Grab the AndroidComposeView using the same hook that createComposeRule uses // Note: It isn't usefully populated at this point. rootForTest = p0 as RootForTest } override fun onViewDetachedFromWindow(p0: View) { } }) } } private fun processAccessibleChildren( p0: SemanticsNode, fn: (AccessibilityState.Element) -> Unit ) { val contentDescription = p0.config.getOrNull(SemanticsProperties.ContentDescription) val stateDescription = p0.config.getOrNull(SemanticsProperties.StateDescription) val onClickLabel = p0.config.getOrNull(SemanticsActions.OnClick)?.label val role = p0.config.getOrNull(SemanticsProperties.Role)?.toString() val disabled = p0.config.getOrNull(SemanticsProperties.Disabled) != null val heading = p0.config.getOrNull(SemanticsProperties.Heading) != null val customActions = p0.config.getOrNull(SemanticsActions.CustomActions) val text = p0.config.getOrNull(SemanticsProperties.Text) val progress = p0.config.getOrNull(SemanticsProperties.ProgressBarRangeInfo) val hasProgressAction = p0.config.getOrNull(SemanticsActions.SetProgress) != null if (contentDescription != null || stateDescription != null || onClickLabel != null || role != null || progress != null || text != null) { val position = p0.boundsInRoot.toAndroidRect() val touchBounds = p0.touchBoundsInRoot.toAndroidRect() fn( AccessibilityState.Element( position, if (touchBounds != position) touchBounds else null, text?.map { it.toString() }, contentDescription, stateDescription, onClickLabel, role, disabled, heading, customActions?.map { AccessibilityState.CustomAction(label = it.label) }, progress?.let { AccessibilityState.Progress(it.current, it.range, it.steps, hasProgressAction) } ) ) } p0.children.forEach { processAccessibleChildren(it, fn) } } override fun renderView(contentView: View): View { val composeView = (contentView as ViewGroup).getChildAt(0) as ComposeView // Capture the accessibility elements during the drawing phase after // measurement and layout has occurred composeView.viewTreeObserver.addOnPreDrawListener { extractAccessibilityState() true } return contentView } private fun extractAccessibilityState() { val rootSemanticsNode = rootForTest.semanticsOwner.rootSemanticsNode val elements = buildList { processAccessibleChildren(rootSemanticsNode) { add(it) } } accessibilityState = AccessibilityState( rootSemanticsNode.size.width, rootSemanticsNode.size.height, elements ) } }
apache-2.0
59fedaf33ccfa0051ffb21b38f95ada7
40.263158
145
0.680029
5.162747
false
true
false
false
tmarsteel/compiler-fiddle
test/compiler/lexer/LexerTest.kt
1
8923
/* * Copyright 2018 Tobias Marstaller * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ package compiler.lexer import io.kotlintest.matchers.* import io.kotlintest.specs.FreeSpec class LexerTest : FreeSpec() {init { val testSource = SimpleSourceDescriptor("test source code") "keywords" - { "default" { val result = Lexer(" module ", testSource).remainingTokens().toList() result.size shouldBe 1 result[0] should beInstanceOf(KeywordToken::class) (result[0] as KeywordToken).keyword shouldBe Keyword.MODULE (result[0] as KeywordToken).sourceText shouldEqual "module" (result[0] as KeywordToken).sourceLocation shouldEqual SourceLocation(testSource, 1, 4) } "should be case insensitive" { val result = Lexer(" MoDulE ", testSource).remainingTokens().toList() result.size should beGreaterThanOrEqualTo(1) result[0] should beInstanceOf(KeywordToken::class) (result[0] as KeywordToken).keyword shouldBe Keyword.MODULE } } "newlines are semantic" { val result = Lexer(" \n \n \n", testSource).remainingTokens().toList() result.size shouldEqual 3 result[0] should beInstanceOf(OperatorToken::class) (result[0] as OperatorToken).operator shouldBe Operator.NEWLINE result[1] shouldEqual result[0] result[2] shouldEqual result[0] } "integers" - { "single digit" { val result = Lexer("7", testSource).remainingTokens().toList() result.size shouldEqual 1 result[0] should beInstanceOf(NumericLiteralToken::class) (result[0] as NumericLiteralToken).stringContent shouldEqual "7" } "multiple digit" { val result = Lexer("21498743", testSource).remainingTokens().toList() result.size shouldEqual 1 result[0] should beInstanceOf(NumericLiteralToken::class) (result[0] as NumericLiteralToken).stringContent shouldEqual "21498743" } } "decimals" - { "simple decimal" { val result = Lexer("312.1232", testSource).remainingTokens().toList() result.size shouldEqual 1 result[0] should beInstanceOf(NumericLiteralToken::class) (result[0] as NumericLiteralToken).stringContent shouldEqual "312.1232" } "without leading digit it's not a decimal" { val result = Lexer(".25", testSource).remainingTokens().toList() result.size should beGreaterThan(1) result[0] shouldNot beInstanceOf(NumericLiteralToken::class) } "invocation on integer literal" { val result = Lexer("312.toLong()", testSource).remainingTokens().toList() result.size should beGreaterThan(3) result[0] should beInstanceOf(NumericLiteralToken::class) (result[0] as NumericLiteralToken).stringContent shouldEqual "312" result[1] should beInstanceOf(OperatorToken::class) (result[1] as OperatorToken).operator shouldBe Operator.DOT result[2] should beInstanceOf(IdentifierToken::class) (result[2] as IdentifierToken).value shouldEqual "toLong" } } "identifiers" - { "identifier stops at space" { val result = Lexer("foo bar", testSource).remainingTokens().toList() result.size shouldBe 2 result[0] should beInstanceOf(IdentifierToken::class) (result[0] as IdentifierToken).value shouldEqual "foo" result[1] should beInstanceOf(IdentifierToken::class) (result[1] as IdentifierToken).value shouldEqual "bar" } "identifier stops at operator" { val result = Lexer("baz*", testSource).remainingTokens().toList() result.size shouldBe 2 result[0] should beInstanceOf(IdentifierToken::class) (result[0] as IdentifierToken).value shouldEqual "baz" result[1] should beInstanceOf(OperatorToken::class) (result[1] as OperatorToken).operator shouldBe Operator.TIMES } "identifier stops at newline" { val result = Lexer("cat\n", testSource).remainingTokens().toList() result.size shouldBe 2 result[0] should beInstanceOf(IdentifierToken::class) (result[0] as IdentifierToken).value shouldEqual "cat" result[1] should beInstanceOf(OperatorToken::class) (result[1] as OperatorToken).operator shouldBe Operator.NEWLINE } } "combo test with code" { val result = Lexer("""module foo fun foobar(val x: Int = 24) = return (142.12)?.toLong() == x """, testSource).remainingTokens().toList() result.size shouldBe 25 result[0] should beInstanceOf(KeywordToken::class) (result[0] as KeywordToken).keyword shouldBe Keyword.MODULE result[1] should beInstanceOf(IdentifierToken::class) (result[1] as IdentifierToken).value shouldEqual "foo" result[2] should beInstanceOf(OperatorToken::class) (result[2] as OperatorToken).operator shouldBe Operator.NEWLINE result[3] should beInstanceOf(KeywordToken::class) (result[3] as KeywordToken).keyword shouldBe Keyword.FUNCTION result[4] should beInstanceOf(IdentifierToken::class) (result[4] as IdentifierToken).value shouldEqual "foobar" result[5] should beInstanceOf(OperatorToken::class) (result[5] as OperatorToken).operator shouldBe Operator.PARANT_OPEN result[6] should beInstanceOf(KeywordToken::class) (result[6] as KeywordToken).keyword shouldBe Keyword.VAL result[7] should beInstanceOf(IdentifierToken::class) (result[7] as IdentifierToken).value shouldEqual "x" result[8] should beInstanceOf(OperatorToken::class) (result[8] as OperatorToken).operator shouldBe Operator.COLON result[9] should beInstanceOf(IdentifierToken::class) (result[9] as IdentifierToken).value shouldEqual "Int" result[10] should beInstanceOf(OperatorToken::class) (result[10] as OperatorToken).operator shouldBe Operator.ASSIGNMENT result[11] should beInstanceOf(NumericLiteralToken::class) (result[11] as NumericLiteralToken).stringContent shouldEqual "24" result[12] should beInstanceOf(OperatorToken::class) (result[12] as OperatorToken).operator shouldBe Operator.PARANT_CLOSE result[13] should beInstanceOf(OperatorToken::class) (result[13] as OperatorToken).operator shouldBe Operator.ASSIGNMENT result[14] should beInstanceOf(KeywordToken::class) (result[14] as KeywordToken).keyword shouldBe Keyword.RETURN result[15] should beInstanceOf(OperatorToken::class) (result[15] as OperatorToken).operator shouldBe Operator.PARANT_OPEN result[16] should beInstanceOf(NumericLiteralToken::class) (result[16] as NumericLiteralToken).stringContent shouldEqual "142.12" result[17] should beInstanceOf(OperatorToken::class) (result[17] as OperatorToken).operator shouldBe Operator.PARANT_CLOSE result[18] should beInstanceOf(OperatorToken::class) (result[18] as OperatorToken).operator shouldBe Operator.SAFEDOT result[19] should beInstanceOf(IdentifierToken::class) (result[19] as IdentifierToken).value shouldEqual "toLong" result[20] should beInstanceOf(OperatorToken::class) (result[20] as OperatorToken).operator shouldBe Operator.PARANT_OPEN result[21] should beInstanceOf(OperatorToken::class) (result[21] as OperatorToken).operator shouldBe Operator.PARANT_CLOSE result[22] should beInstanceOf(OperatorToken::class) (result[22] as OperatorToken).operator shouldBe Operator.EQUALS result[23] should beInstanceOf(IdentifierToken::class) (result[23] as IdentifierToken).value shouldEqual "x" result[24] should beInstanceOf(OperatorToken::class) (result[24] as OperatorToken).operator shouldBe Operator.NEWLINE } }}
lgpl-3.0
2f83276aec1583a696b108c4f08248cd
38.140351
99
0.670178
4.661964
false
true
false
false