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
hubme/WorkHelperApp
app/src/main/java/com/king/app/workhelper/location/LocationManager.kt
1
2768
package com.king.app.workhelper.location import android.Manifest import android.content.Context import android.content.pm.PackageManager import android.location.Criteria import android.location.Location import android.location.LocationManager import androidx.annotation.RequiresPermission import androidx.core.app.ActivityCompat fun isProviderEnabled(context: Context): Boolean { val locationManager = context.getSystemService(Context.LOCATION_SERVICE) as LocationManager return locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) } @RequiresPermission(anyOf = [Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION]) private fun getLastKnownLocation(context: Context): Location? { if (checkPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) && checkPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION)) { return null } // 为获取地理位置信息时设置查询条件 是按GPS定位还是network定位 val bestProvider: String? = getProvider(context) if (bestProvider.isNullOrBlank()) { return null } val locationManager = context.getSystemService(Context.LOCATION_SERVICE) as LocationManager return locationManager.getLastKnownLocation(bestProvider) } private fun checkPermission(context: Context, permission: String): Boolean { return ActivityCompat.checkSelfPermission(context, permission) != PackageManager.PERMISSION_GRANTED } /** * 定位查询条件 * 返回查询条件 ,获取目前设备状态下,最适合的定位方式 */ private fun getProvider(context: Context): String? { SomeSingleton.getInstance(context) // 构建位置查询条件 val criteria = Criteria() // 设置定位精确度 Criteria.ACCURACY_COARSE比较粗略,Criteria.ACCURACY_FINE则比较精细 //Criteria.ACCURACY_FINE,当使用该值时,在建筑物当中,可能定位不了,建议在对定位要求并不是很高的时候用Criteria.ACCURACY_COARSE,避免定位失败 // 查询精度:高 criteria.accuracy = Criteria.ACCURACY_FINE // 设置是否要求速度 criteria.isSpeedRequired = false // 是否查询海拨:否 criteria.isAltitudeRequired = false // 是否查询方位角 : 否 criteria.isBearingRequired = false // 是否允许付费:是 criteria.isCostAllowed = false // 电量要求:低 criteria.powerRequirement = Criteria.POWER_LOW val locationManager = context.getSystemService(Context.LOCATION_SERVICE) as LocationManager // 返回最合适的符合条件的provider,第2个参数为true说明 , 如果只有一个provider是有效的,则返回当前provider return locationManager.getBestProvider(criteria, true) }
apache-2.0
dc03276401c75a226745de9c98789535
37.145161
115
0.77665
3.973109
false
false
false
false
cfig/Android_boot_image_editor
bbootimg/src/main/kotlin/avb/desc/ChainPartitionDescriptor.kt
1
4538
// Copyright 2021 [email protected] // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package avb.desc import avb.AVBInfo import cfig.Avb import cfig.helper.Helper import cfig.helper.Dumpling import cc.cfig.io.Struct import java.io.File import java.io.InputStream import java.security.MessageDigest import org.slf4j.LoggerFactory class ChainPartitionDescriptor( var rollback_index_location: Int = 0, var partition_name_len: Int = 0, var public_key_len: Int = 0, var partition_name: String = "", var pubkey: ByteArray = byteArrayOf(), var pubkey_sha1: String = "" ) : Descriptor(TAG, 0, 0) { override fun encode(): ByteArray { this.partition_name_len = this.partition_name.length this.public_key_len = this.pubkey.size this.num_bytes_following = SIZE + this.partition_name_len + this.public_key_len - 16 val nbf_with_padding = Helper.round_to_multiple(this.num_bytes_following, 8).toULong() val padding_size = nbf_with_padding - this.num_bytes_following.toUInt() val desc = Struct(FORMAT_STRING + "${RESERVED}x").pack( TAG, nbf_with_padding, this.rollback_index_location, this.partition_name.length.toUInt(), this.public_key_len, null) val padding = Struct("${padding_size}x").pack(null) return Helper.join(desc, this.partition_name.toByteArray(), this.pubkey, padding) } companion object { const val TAG: Long = 4L const val RESERVED = 64 const val SIZE = 28L + RESERVED const val FORMAT_STRING = "!2Q3L" private val log = LoggerFactory.getLogger(ChainPartitionDescriptor::class.java) } constructor(data: InputStream, seq: Int = 0) : this() { if (SIZE - RESERVED != Struct(FORMAT_STRING).calcSize().toLong()) { throw RuntimeException("ChainPartitionDescriptor size check failed") } this.sequence = seq val info = Struct(FORMAT_STRING + "${RESERVED}s").unpack(data) this.tag = (info[0] as ULong).toLong() this.num_bytes_following = (info[1] as ULong).toLong() this.rollback_index_location = (info[2] as UInt).toInt() this.partition_name_len = (info[3] as UInt).toInt() this.public_key_len = (info[4] as UInt).toInt() val expectedSize = Helper.round_to_multiple(SIZE - 16 + this.partition_name_len + this.public_key_len, 8) if (this.tag != TAG || this.num_bytes_following != expectedSize) { throw IllegalArgumentException("Given data does not look like a chain/delegation descriptor") } val info2 = Struct("${this.partition_name_len}s${this.public_key_len}b").unpack(data) this.partition_name = info2[0] as String this.pubkey = info2[1] as ByteArray val md = MessageDigest.getInstance("SHA1").let { it.update(this.pubkey) it.digest() } this.pubkey_sha1 = Helper.toHexString(md) } fun verify(image_files: List<String>, parent: String = ""): Array<Any> { val ret: Array<Any> = arrayOf(false, "file not found") for (item in image_files) { if (File(item).exists()) { val subAi = AVBInfo.parseFrom(Dumpling(item)) if (pubkey.contentEquals(subAi.auxBlob!!.pubkey!!.pubkey)) { log.info("VERIFY($parent): public key matches, PASS") return Avb.verify(subAi, Dumpling(item), parent) } else { log.info("VERIFY($parent): public key mismatch, FAIL") ret[1] = "public key mismatch" return ret } } } log.info("VERIFY($parent): " + ret[1] as String + "... FAIL") return ret } override fun toString(): String { return "ChainPartitionDescriptor(partition=${this.partition_name}, pubkey=${this.pubkey.contentToString()}" } }
apache-2.0
a8e8a187a0a0ae7614e08f5fc538b975
41.411215
115
0.620978
3.984197
false
false
false
false
Ruben-Sten/TeXiFy-IDEA
src/nl/hannahsten/texifyidea/lang/BibtexDefaultEntryType.kt
1
20776
package nl.hannahsten.texifyidea.lang import nl.hannahsten.texifyidea.lang.BibtexDefaultEntryField.* import nl.hannahsten.texifyidea.lang.LatexPackage.Companion.BIBLATEX import java.util.* import kotlin.collections.HashMap /** * All entry types in bibtex and biblatex. * * @author Hannah Schellekens */ enum class BibtexDefaultEntryType( override val token: String, override val description: String, override val required: Array<BibtexEntryField>, override val optional: Array<BibtexEntryField>, override val dependency: LatexPackage = LatexPackage.DEFAULT ) : BibtexEntryType { // Regular entry types. ARTICLE( "article", "An article from a journal or magazine.", arrayOf(AUTHOR, TITLE, JOURNAL, YEAR), arrayOf(NUMBER, PAGES, MONTH, NOTE, VOLUME, KEY) ), BOOK( "book", "A book with an explicit publisher.", arrayOf(AUTHOR, TITLE, PUBLISHER, YEAR), arrayOf(EDITION, VOLUME, NUMBER, SERIES, ADDRESS, EDITION, MONTH, NOTE, KEY) ), BOOKLET( "booklet", "A work that is printed and bound, but without a named publisher or sponsoring institution.", arrayOf(TITLE), arrayOf(AUTHOR, HOWPUBLISHED, ADDRESS, MONTH, YEAR, NOTE, KEY) ), CONFERENCE( "conference", "The same as inproceedings, included for Scribe compatibility.", arrayOf(AUTHOR, TITLE, BOOKTITLE, YEAR), arrayOf(EDITOR, VOLUME, NUMBER, SERIES, PAGES, ADDRESS, MONTH, ORGANISATION, PUBLISHER, NOTE, KEY) ), INBOOK( "inbook", "A part of a book, usually untitled. May be a chapter (or section, etc.) and/or a range of pages.", arrayOf(AUTHOR, TITLE, PAGES, PUBLISHER, YEAR), arrayOf(EDITOR, CHAPTER, VOLUME, NUMBER, SERIES, TYPE, ADDRESS, EDITION, MONTH, NOTE, KEY) ), INCOLLECTION( "incollection", "A part of a book having its own title.", arrayOf(AUTHOR, TITLE, BOOKTITLE, PUBLISHER, YEAR), arrayOf(EDITOR, VOLUME, NUMBER, SERIES, TYPE, CHAPTER, PAGES, ADDRESS, EDITION, MONTH, NOTE, KEY) ), INPROCEEDINGS( "inproceedings", "An article in a conference proceedings.", arrayOf(AUTHOR, TITLE, BOOKTITLE, YEAR), arrayOf(EDITOR, VOLUME, NUMBER, SERIES, PAGES, ADDRESS, MONTH, ORGANISATION, PUBLISHER, NOTE, KEY) ), MANUAL( "manual", "Technical documentation.", arrayOf(TITLE), arrayOf(AUTHOR, ORGANISATION, ADDRESS, EDITION, MONTH, YEAR, NOTE, KEY) ), MASTERTHESIS( "masterthesis", "A Master's thesis.", arrayOf(AUTHOR, TITLE, SCHOOL, YEAR), arrayOf(TYPE, ADDRESS, MONTH, NOTE, KEY) ), MISC( "misc", "For use when nothing else fits.", emptyArray(), arrayOf(AUTHOR, TITLE, HOWPUBLISHED, MONTH, YEAR, NOTE, KEY) ), PHDTHESIS( "phdthesis", "A Ph.D. thesis.", arrayOf(AUTHOR, TITLE, SCHOOL, YEAR), arrayOf(TYPE, ADDRESS, MONTH, NOTE, KEY) ), PROCEEDINGS( "proceedings", "The proceedings of a conference.", arrayOf(TITLE, YEAR), arrayOf(EDITOR, VOLUME, NUMBER, SERIES, ADDRESS, MONTH, PUBLISHER, ORGANISATION, NOTE, KEY) ), TECHREPORT( "techreport", "A report published by a school or other institution, usually numbered within a series.", arrayOf(AUTHOR, TITLE, INSTITUTION, YEAR), arrayOf(TYPE, NUMBER, ADDRESS, MONTH, NOTE, KEY) ), UNPUBLISHED( "unpublished", "A document having an author and title, but not formally published.", arrayOf(AUTHOR, TITLE, NOTE), arrayOf(MONTH, YEAR, KEY) ), // Special entries STRING( "string", "Define a string to be used later on in the bibliography", emptyArray(), emptyArray() ), PREAMBLE( "preamble", "You can define some LaTeX commands that will be included in the .bbl file generated by BibTex using the preamble", emptyArray(), emptyArray() ), // BibLaTeX entries. Source: biblatex docs BIBLATEX_ARTICLE( "article", "An article in a journal, magazine, newspaper, or other periodical which forms a self-contained unit with its own title.", arrayOf(AUTHOR, TITLE, JOURNALTITLE, DATE), arrayOf(TRANSLATOR, ANNOTATOR, COMMENTATOR, SUBTITLE, TITLEADDON, EDITOR, EDITORA, EDITORB, EDITORC, JOURNALSUBTITLE, ISSUETITLE, ISSUESUBTITLE, LANGUAGE, ORIGLANGUAGE, SERIES, VOLUME, NUMBER, EID, ISSUE, MONTH, PAGES, VERSION, NOTE, ISSN, ADDENDUM, PUBSTATE, DOI, EPRINT, EPRINTCLASS, EPRINTTYPE, URL, URLDATE), BIBLATEX ), BIBLATEX_BOOK( "book", "A single-volume book with one or more authors where the authors share credit for the work as a whole.", arrayOf(AUTHOR, TITLE, DATE), arrayOf(EDITOR, EDITORA, EDITORB, EDITORC, TRANSLATOR, ANNOTATOR, COMMENTATOR, INTRODUCTION, FOREWORD, AFTERWORD, SUBTITLE, TITLEADDON, MAINTITLE, MAINSUBTITLE, MAINTITLEADDON, LANGUAGE, ORIGLANGUAGE, VOLUME, PART, EDITION, VOLUMES, SERIES, NUMBER, NOTE, PUBLISHER, LOCATION, ISBN, CHAPTER, PAGES, PAGETOTAL, ADDENDUM, PUBSTATE, DOI, EPRINT, EPRINTCLASS, EPRINTTYPE, URL, URLDATE), BIBLATEX ), MVBOOK( "mvbook", "A multi-volume @book.", arrayOf(AUTHOR, TITLE, DATE), arrayOf(EDITOR, EDITORA, EDITORB, EDITORC, TRANSLATOR, ANNOTATOR, COMMENTATOR, INTRODUCTION, FOREWORD, AFTERWORD, SUBTITLE, TITLEADDON, LANGUAGE, ORIGLANGUAGE, EDITION, VOLUMES, SERIES, NUMBER, NOTE, PUBLISHER, LOCATION, ISBN, PAGETOTAL, ADDENDUM, PUBSTATE, DOI, EPRINT, EPRINTCLASS, EPRINTTYPE, URL, URLDATE), BIBLATEX ), BIBLATEX_INBOOK( "inbook", "A part of a book which forms a self-contained unit with its own title.", arrayOf(AUTHOR, TITLE, BOOKTITLE, DATE), arrayOf(BOOKAUTHOR, EDITOR, EDITORA, EDITORB, EDITORC, TRANSLATOR, ANNOTATOR, COMMENTATOR, INTRODUCTION, FOREWORD, AFTERWORD, SUBTITLE, TITLEADDON, MAINTITLE, MAINSUBTITLE, MAINTITLEADDON, BOOKSUBTITLE, BOOKTITLEADDON, LANGUAGE, ORIGLANGUAGE, VOLUME, PART, EDITION, VOLUMES, SERIES, NUMBER, NOTE, PUBLISHER, LOCATION, ISBN, CHAPTER, PAGES, ADDENDUM, PUBSTATE, DOI, EPRINT, EPRINTCLASS, EPRINTTYPE, URL, URLDATE), BIBLATEX ), BOOKINBOOK( "bookinbook", "This type is similar to @inbook but intended for works originally published as a\n" + "stand-alone book.", arrayOf(AUTHOR, TITLE, BOOKTITLE, DATE), arrayOf(BOOKAUTHOR, EDITOR, EDITORA, EDITORB, EDITORC, TRANSLATOR, ANNOTATOR, COMMENTATOR, INTRODUCTION, FOREWORD, AFTERWORD, SUBTITLE, TITLEADDON, MAINTITLE, MAINSUBTITLE, MAINTITLEADDON, BOOKSUBTITLE, BOOKTITLEADDON, LANGUAGE, ORIGLANGUAGE, VOLUME, PART, EDITION, VOLUMES, SERIES, NUMBER, NOTE, PUBLISHER, LOCATION, ISBN, CHAPTER, PAGES, ADDENDUM, PUBSTATE, DOI, EPRINT, EPRINTCLASS, EPRINTTYPE, URL, URLDATE), BIBLATEX ), SUPPBOOK( "suppbook", "Supplemental material in a @book. This type is closely related to the @inbook entry type.", arrayOf(AUTHOR, TITLE, BOOKTITLE, DATE), arrayOf(BOOKAUTHOR, EDITOR, EDITORA, EDITORB, EDITORC, TRANSLATOR, ANNOTATOR, COMMENTATOR, INTRODUCTION, FOREWORD, AFTERWORD, SUBTITLE, TITLEADDON, MAINTITLE, MAINSUBTITLE, MAINTITLEADDON, BOOKSUBTITLE, BOOKTITLEADDON, LANGUAGE, ORIGLANGUAGE, VOLUME, PART, EDITION, VOLUMES, SERIES, NUMBER, NOTE, PUBLISHER, LOCATION, ISBN, CHAPTER, PAGES, ADDENDUM, PUBSTATE, DOI, EPRINT, EPRINTCLASS, EPRINTTYPE, URL, URLDATE), BIBLATEX ), BIBLATEX_BOOKLET( "booklet", "A book-like work without a format publisher or sponsoring insitution.", arrayOf(AUTHOR, TITLE, DATE), arrayOf(EDITOR, SUBTITLE, TITLEADDON, LANGUAGE, HOWPUBLISHED, TYPE, NOTE, LOCATION, CHAPTER, PAGES, PAGETOTAL, ADDENDUM, PUBSTATE, DOI, EPRINT, EPRINTCLASS, EPRINTTYPE, URL, URLDATE), BIBLATEX ), COLLECTION( "collection", "A single-volume collection with multiple, self-contained contributions by distinct authors which have their own title.", arrayOf(EDITOR, TITLE, DATE), arrayOf(EDITORA, EDITORB, EDITORC, TRANSLATOR, ANNOTATOR, COMMENTATOR, INTRODUCTION, FOREWORD, AFTERWORD, SUBTITLE, TITLEADDON, MAINTITLE, MAINSUBTITLE, MAINTITLEADDON, LANGUAGE, ORIGLANGUAGE, VOLUME, PART, EDITION, VOLUMES, SERIES, NUMBER, NOTE, PUBLISHER, LOCATION, ISBN, CHAPTER, PAGES, PAGETOTAL, ADDENDUM, PUBSTATE, DOI, EPRINT, EPRINTCLASS, EPRINTTYPE, URL, URLDATE), BIBLATEX ), MVCOLLECTION( "mvcollection", "A multi-volume @collection.", arrayOf(EDITOR, TITLE, DATE), arrayOf(YEAR, EDITORA, EDITORB, EDITORC, TRANSLATOR, ANNOTATOR, COMMENTATOR, INTRODUCTION, FOREWORD, AFTERWORD, SUBTITLE, TITLEADDON, LANGUAGE, ORIGLANGUAGE, EDITION, VOLUMES, SERIES, NUMBER, NOTE, PUBLISHER, LOCATION, ISBN, PAGETOTAL, ADDENDUM, PUBSTATE, DOI, EPRINT, EPRINTCLASS, EPRINTTYPE, URL, URLDATE), BIBLATEX ), BIBLATEX_INCOLLECTION( "incollection", "A contribution to a collection which forms a self-contained unit with a distinct author and title.", arrayOf(AUTHOR, TITLE, BOOKTITLE, DATE), arrayOf(YEAR, EDITOR, EDITORA, EDITORB, EDITORC, TRANSLATOR, ANNOTATOR, COMMENTATOR, INTRODUCTION, FOREWORD, AFTERWORD, SUBTITLE, TITLEADDON, MAINTITLE, MAINSUBTITLE, MAINTITLEADDON, BOOKSUBTITLE, BOOKTITLEADDON, LANGUAGE, ORIGLANGUAGE, VOLUME, PART, EDITION, VOLUMES, SERIES, NUMBER, NOTE, PUBLISHER, LOCATION, ISBN, CHAPTER, PAGES, ADDENDUM, PUBSTATE, DOI, EPRINT, EPRINTCLASS, EPRINTTYPE, URL, URLDATE), BIBLATEX ), BIBLATEX_SUPPCOLLECTION( "suppcollection", "Supplemental material in a @collection. This type is similar to @suppbook but related to the @collection entry type. ", arrayOf(AUTHOR, TITLE, BOOKTITLE, DATE), arrayOf(YEAR, EDITOR, EDITORA, EDITORB, EDITORC, TRANSLATOR, ANNOTATOR, COMMENTATOR, INTRODUCTION, FOREWORD, AFTERWORD, SUBTITLE, TITLEADDON, MAINTITLE, MAINSUBTITLE, MAINTITLEADDON, BOOKSUBTITLE, BOOKTITLEADDON, LANGUAGE, ORIGLANGUAGE, VOLUME, PART, EDITION, VOLUMES, SERIES, NUMBER, NOTE, PUBLISHER, LOCATION, ISBN, CHAPTER, PAGES, ADDENDUM, PUBSTATE, DOI, EPRINT, EPRINTCLASS, EPRINTTYPE, URL, URLDATE), BIBLATEX ), DATASET( "dataset", "A data set or a similar collection of (mostly) raw data.", arrayOf(AUTHOR, TITLE, DATE), arrayOf(YEAR, SUBTITLE, TITLEADDON, LANGUAGE, EDITION, TYPE, SERIES, NUMBER, VERSION, NOTE, ORGANISATION, PUBLISHER, LOCATION, ADDENDUM, PUBSTATE, DOI, EPRINT, EPRINTCLASS, EPRINTTYPE, URL, URLDATE), BIBLATEX ), BIBLATEX_MANUAL( "manual", "Technical or other documentation.", arrayOf(TITLE, DATE), arrayOf(AUTHOR, EDITOR, YEAR, SUBTITLE, TITLEADDON, LANGUAGE, EDITION, TYPE, SERIES, NUMBER, VERSION, NOTE, ORGANISATION, PUBLISHER, LOCATION, ISBN, CHAPTER, PAGES, PAGETOTAL, ADDENDUM, PUBSTATE, DOI, EPRINT, EPRINTCLASS, EPRINTTYPE, URL, URLDATE), BIBLATEX ), BIBLATEX_MISC( "misc", "A fallback type for entries which do not fit into any other category.", arrayOf(TITLE, DATE), arrayOf(AUTHOR, EDITOR, YEAR, SUBTITLE, TITLEADDON, LANGUAGE, HOWPUBLISHED, TYPE, VERSION, NOTE, ORGANISATION, LOCATION, MONTH, ADDENDUM, PUBSTATE, DOI, EPRINT, EPRINTCLASS, EPRINTTYPE, URL, URLDATE), BIBLATEX ), ONLINE( "online", "A website.", arrayOf(AUTHOR, TITLE, DATE, URL), arrayOf(SUBTITLE, TITLEADDON, LANGUAGE, VERSION, NOTE, ORGANISATION, ADDENDUM, PUBSTATE, EPRINTCLASS, EPRINTTYPE, URLDATE), BIBLATEX ), PATENT( "patent", "A patent or patent request.", arrayOf(AUTHOR, TITLE, NUMBER, DATE), arrayOf(YEAR, HOLDER, SUBTITLE, TITLEADDON, TYPE, VERSION, LOCATION, NOTE, MONTH, ADDENDUM, PUBSTATE, DOI, EPRINT, EPRINTCLASS, EPRINTTYPE, URL, URLDATE), BIBLATEX ), PERIODICAL( "periodical", "A complete issue of a periodical.", arrayOf(EDITOR, TITLE, DATE), arrayOf(YEAR, EDITORA, EDITORB, EDITORC, SUBTITLE, ISSUETITLE, ISSUESUBTITLE, LANGUAGE, SERIES, VOLUME, NUMBER, ISSUE, MONTH, NOTE, ISSN, ADDENDUM, PUBSTATE, DOI, EPRINT, EPRINTCLASS, EPRINTTYPE, URL, URLDATE), BIBLATEX ), SUPPPERIODICAL( "suppperiodical", "Supplemental material in a @periodical. This type is similar to @suppbook but related to the @periodical entry type.", arrayOf(EDITOR, TITLE, DATE), arrayOf(YEAR, EDITORA, EDITORB, EDITORC, SUBTITLE, ISSUETITLE, ISSUESUBTITLE, LANGUAGE, SERIES, VOLUME, NUMBER, ISSUE, MONTH, NOTE, ISSN, ADDENDUM, PUBSTATE, DOI, EPRINT, EPRINTCLASS, EPRINTTYPE, URL, URLDATE), BIBLATEX ), BIBLATEX_PROCEEDINGS( "proceedings", "A single-volume conference proceedings.", arrayOf(TITLE, DATE), arrayOf(YEAR, EDITOR, SUBTITLE, TITLEADDON, MAINTITLE, MAINSUBTITLE, MAINTITLEADDON, EVENTTITLE, EVENTTITLEADDON, EVENTDATE, VENUE, LANGUAGE, VOLUME, PART, VOLUMES, SERIES, NUMBER, NOTE, ORGANISATION, PUBLISHER, LOCATION, MONTH, ISBN, CHAPTER, PAGES, PAGETOTAL, ADDENDUM, PUBSTATE, DOI, EPRINT, EPRINTCLASS, EPRINTTYPE, URL, URLDATE), BIBLATEX ), MVPROCEEDINGS( "mvproceedings", "A multi-volume @proceedings entry.", arrayOf(TITLE, DATE), arrayOf(YEAR, EDITOR, SUBTITLE, TITLEADDON, EVENTTITLE, EVENTTITLEADDON, EVENTDATE, VENUE, LANGUAGE, VOLUMES, SERIES, NUMBER, NOTE, ORGANISATION, PUBLISHER, LOCATION, MONTH, ISBN, PAGETOTAL, ADDENDUM, PUBSTATE, DOI, EPRINT, EPRINTCLASS, EPRINTTYPE, URL, URLDATE), BIBLATEX ), BIBLATEX_INPROCEEDINGS( "inproceedings", "An article in a conference proceedings.", arrayOf(AUTHOR, TITLE, BOOKTITLE, DATE), arrayOf(EDITOR, SUBTITLE, TITLEADDON, MAINTITLE, MAINSUBTITLE, MAINTITLEADDON, BOOKSUBTITLE, BOOKTITLEADDON, EVENTTITLE, EVENTTITLEADDON, EVENTDATE, VENUE, LANGUAGE, VOLUME, PART, VOLUMES, SERIES, NUMBER, NOTE, ORGANISATION, PUBLISHER, LOCATION, MONTH, ISBN, CHAPTER, PAGES, ADDENDUM, PUBSTATE, DOI, EPRINT, EPRINTCLASS, EPRINTTYPE, URL, URLDATE), BIBLATEX ), REFERENCE( "reference", "A single-volume work of reference such as an encyclopedia or a dictionary. This is a\n" + "more specific variant of the generic @collection entry type", arrayOf(EDITOR, TITLE, DATE), arrayOf(EDITORA, EDITORB, EDITORC, TRANSLATOR, ANNOTATOR, COMMENTATOR, INTRODUCTION, FOREWORD, AFTERWORD, SUBTITLE, TITLEADDON, MAINTITLE, MAINSUBTITLE, MAINTITLEADDON, LANGUAGE, ORIGLANGUAGE, VOLUME, PART, EDITION, VOLUMES, SERIES, NUMBER, NOTE, PUBLISHER, LOCATION, ISBN, CHAPTER, PAGES, PAGETOTAL, ADDENDUM, PUBSTATE, DOI, EPRINT, EPRINTCLASS, EPRINTTYPE, URL, URLDATE), BIBLATEX ), MVREFERENCE( "mvreference", "A multi-volume @reference entry. ", arrayOf(EDITOR, TITLE, DATE), arrayOf(YEAR, EDITORA, EDITORB, EDITORC, TRANSLATOR, ANNOTATOR, COMMENTATOR, INTRODUCTION, FOREWORD, AFTERWORD, SUBTITLE, TITLEADDON, LANGUAGE, ORIGLANGUAGE, EDITION, VOLUMES, SERIES, NUMBER, NOTE, PUBLISHER, LOCATION, ISBN, PAGETOTAL, ADDENDUM, PUBSTATE, DOI, EPRINT, EPRINTCLASS, EPRINTTYPE, URL, URLDATE), BIBLATEX ), INREFERENCE( "inreference", "An article in a work of reference.", arrayOf(EDITOR, TITLE, DATE), arrayOf(YEAR, EDITORA, EDITORB, EDITORC, TRANSLATOR, ANNOTATOR, COMMENTATOR, INTRODUCTION, FOREWORD, AFTERWORD, SUBTITLE, TITLEADDON, LANGUAGE, ORIGLANGUAGE, EDITION, VOLUMES, SERIES, NUMBER, NOTE, PUBLISHER, LOCATION, ISBN, PAGETOTAL, ADDENDUM, PUBSTATE, DOI, EPRINT, EPRINTCLASS, EPRINTTYPE, URL, URLDATE), BIBLATEX ), REPORT( "report", "A technical report, research report, or white paper published by a university or other institution.", arrayOf(AUTHOR, TITLE, TYPE, INSTITUTION, DATE), arrayOf(YEAR, SUBTITLE, TITLEADDON, LANGUAGE, NUMBER, VERSION, NOTE, LOCATION, MONTH, ISRN, CHAPTER, PAGES, PAGETOTAL, ADDENDUM, PUBSTATE, DOI, EPRINT, EPRINTCLASS, EPRINTTYPE, URL, URLDATE), BIBLATEX ), SOFTWARE( "software", "Computer software. The standard styles will treat this entry type as an alias for\n" + "@misc.", arrayOf(TITLE, DATE), arrayOf(AUTHOR, EDITOR, YEAR, SUBTITLE, TITLEADDON, LANGUAGE, HOWPUBLISHED, TYPE, VERSION, NOTE, ORGANISATION, LOCATION, MONTH, ADDENDUM, PUBSTATE, DOI, EPRINT, EPRINTCLASS, EPRINTTYPE, URL, URLDATE), BIBLATEX ), BIBLATEX_THESIS( "thesis", "A thesis written for an educational institution to satisfy the requirements for a degree.", arrayOf(AUTHOR, TITLE, TYPE, INSTITUTION, DATE), arrayOf(YEAR, SUBTITLE, TITLEADDON, LANGUAGE, NOTE, LOCATION, MONTH, ISBN, CHAPTER, PAGES, PAGETOTAL, ADDENDUM, PUBSTATE, DOI, EPRINT, EPRINTCLASS, EPRINTTYPE, URL, URLDATE), BIBLATEX ), BIBLATEX_UNPUBLISHED( "unpublished", "A work with an author and a title which has not been formally published.", arrayOf(AUTHOR, TITLE, DATE), arrayOf(SUBTITLE, TITLEADDON, TYPE, EVENTTITLE, EVENTTITLEADDON, EVENTDATE, VENUE, LANGUAGE, HOWPUBLISHED, NOTE, LOCATION, ISBN, MONTH, ADDENDUM, PUBSTATE, URL, URLDATE), BIBLATEX ), BIBLATEX_CONFERENCE( "conference", "A legacy alias for @inproceedings.", arrayOf(AUTHOR, TITLE, BOOKTITLE, DATE), arrayOf(EDITOR, SUBTITLE, TITLEADDON, MAINTITLE, MAINSUBTITLE, MAINTITLEADDON, BOOKSUBTITLE, BOOKTITLEADDON, EVENTTITLE, EVENTTITLEADDON, EVENTDATE, VENUE, LANGUAGE, VOLUME, PART, VOLUMES, SERIES, NUMBER, NOTE, ORGANISATION, PUBLISHER, LOCATION, MONTH, ISBN, CHAPTER, PAGES, ADDENDUM, PUBSTATE, DOI, EPRINT, EPRINTCLASS, EPRINTTYPE, URL, URLDATE), BIBLATEX ), ELECTRONIC( "electronic", "An alias for @online.", arrayOf(AUTHOR, TITLE, DATE, URL), arrayOf(SUBTITLE, TITLEADDON, LANGUAGE, VERSION, NOTE, ORGANISATION, ADDENDUM, PUBSTATE, EPRINTCLASS, EPRINTTYPE, URLDATE), BIBLATEX ), MASTERSTHESIS( "mastersthesis", "Similar to @thesis except that the type field is optional and defaults to the\n" + "localised term ‘Master’s thesis’. You may still use the type field to override that.", arrayOf(AUTHOR, TITLE, INSTITUTION, DATE), arrayOf(YEAR, SUBTITLE, TITLEADDON, LANGUAGE, NOTE, LOCATION, MONTH, ISBN, CHAPTER, PAGES, PAGETOTAL, ADDENDUM, PUBSTATE, DOI, EPRINT, EPRINTCLASS, EPRINTTYPE, URL, URLDATE, TYPE), BIBLATEX ), BIBLATEX_PHDTHESIS( "phdthesis", "Similar to @thesis except that the type field is optional and defaults to the\n" + "localised term ‘PhD thesis’. You may still use the type field to override that.", arrayOf(AUTHOR, TITLE, INSTITUTION, DATE), arrayOf(YEAR, SUBTITLE, TITLEADDON, LANGUAGE, NOTE, LOCATION, MONTH, ISBN, CHAPTER, PAGES, PAGETOTAL, ADDENDUM, PUBSTATE, DOI, EPRINT, EPRINTCLASS, EPRINTTYPE, URL, URLDATE, TYPE), BIBLATEX ), BIBLATEX_TECHREPORT( "techreport", "Similar to @report except that the type field is optional and defaults to the\n" + "localised term ‘technical report’. You may still use the type field to override that.", arrayOf(AUTHOR, TITLE, TYPE, INSTITUTION, DATE), arrayOf(YEAR, SUBTITLE, TITLEADDON, LANGUAGE, NUMBER, VERSION, NOTE, LOCATION, MONTH, ISRN, CHAPTER, PAGES, PAGETOTAL, ADDENDUM, PUBSTATE, DOI, EPRINT, EPRINTCLASS, EPRINTTYPE, URL, URLDATE), BIBLATEX ), WWW( "www", "An alias for @online, provided for jurabib compatibility.", arrayOf(AUTHOR, TITLE, DATE, URL), arrayOf(SUBTITLE, TITLEADDON, LANGUAGE, VERSION, NOTE, ORGANISATION, ADDENDUM, PUBSTATE, EPRINTCLASS, EPRINTTYPE, URLDATE), BIBLATEX ), ; companion object { private val lookup: MutableMap<String, BibtexEntryType> = HashMap() init { for (entry in values()) { lookup[entry.token] = entry } } @JvmStatic operator fun get(token: String): BibtexEntryType? { var trimmedToken = token.lowercase(Locale.getDefault()) if (token.startsWith("@")) { trimmedToken = token.substring(1) } return lookup[trimmedToken] } } }
mit
667b83d2e6a62299ca0b5fd68e0931ab
52.651163
420
0.675224
3.685126
false
false
false
false
AgileVentures/MetPlus_resumeCruncher
core/src/test/kotlin/org/metplus/cruncher/rating/CrunchResumeProcessTest.kt
1
5383
package org.metplus.cruncher.rating import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Test import org.metplus.cruncher.resume.FileInputStreamFake import org.metplus.cruncher.resume.Resume import org.metplus.cruncher.resume.ResumeFile import org.metplus.cruncher.resume.ResumeFileRepository import org.metplus.cruncher.resume.ResumeFileRepositoryFake import org.metplus.cruncher.resume.ResumeRepository import org.metplus.cruncher.resume.ResumeRepositoryFake class CrunchResumeProcessTest { private lateinit var cruncher: CrunchResumeProcess private lateinit var cruncherImpl: CruncherStub private lateinit var resumeRepository: ResumeRepository private lateinit var resumeFileRepository: ResumeFileRepository @BeforeEach fun setup() { cruncherImpl = CruncherStub() val allCrunchers = CruncherList(listOf(cruncherImpl)) resumeRepository = ResumeRepositoryFake() resumeFileRepository = ResumeFileRepositoryFake() cruncher = CrunchResumeProcess( allCrunchers = allCrunchers, resumeRepository = resumeRepository, resumeFileRepository = resumeFileRepository ) } @Test fun `When no resumes need to be processed, starts and stops without calling the cruncher`() { cruncher.start() cruncher.stop() cruncher.join() } @Test fun `When one resume need to be processed, it gets crunched`() { val resume = resumeRepository.save( Resume( filename = "some-file-name.pdf", userId = "some-user-id", fileType = "pdf", cruncherData = mutableMapOf()) ) resumeFileRepository.save(ResumeFile( filename = "some-file-name.pdf", userId = "some-user-id", fileStream = FileInputStreamFake("Some text in the file") )) cruncherImpl.crunchReturn = mutableListOf(CruncherMetaData( metaData = mutableMapOf("some-key" to 10.0) )) cruncher.start() cruncher.addWork(resume) cruncher.stop() cruncher.join() assertThat(cruncherImpl.crunchWasCalledWith.size).isEqualTo(1) assertThat(cruncherImpl.crunchWasCalledWith.first()).contains("Some text in the file") val cruncherResume = resumeRepository.getByUserId("some-user-id")!! assertThat(cruncherResume.cruncherData["some-cruncher"]!!.metaData["some-key"]).isEqualTo(10.0) } @Test fun `when 2 resumes are added, it process both of them`() { val resumeUser1 = resumeRepository.save( Resume( filename = "some-file-name.pdf", userId = "some-user-id", fileType = "pdf", cruncherData = mutableMapOf()) ) resumeFileRepository.save(ResumeFile( filename = "some-file-name.pdf", userId = "some-user-id", fileStream = FileInputStreamFake("Some text in the file") )) cruncherImpl.crunchReturn.add(CruncherMetaData( metaData = mutableMapOf("some-key" to 10.0))) val resumeUser2 = resumeRepository.save( Resume( filename = "some-other-file-name.pdf", userId = "some-other-user-id", fileType = "pdf", cruncherData = mutableMapOf("some-cruncher" to CruncherMetaData(mutableMapOf("the-key" to 99.0)))) ) resumeFileRepository.save(ResumeFile( filename = "some-file-name.pdf", userId = "some-other-user-id", fileStream = FileInputStreamFake("Some other text in the file") )) cruncherImpl.crunchReturn.add(CruncherMetaData( metaData = mutableMapOf("some-other-key" to 9.0))) cruncher.start() cruncher.addWork(resumeUser1) cruncher.addWork(resumeUser2) cruncher.stop() cruncher.join() assertThat(cruncherImpl.crunchWasCalledWith.size).isEqualTo(2) assertThat(cruncherImpl.crunchWasCalledWith.first()).contains("Some text in the file") assertThat(cruncherImpl.crunchWasCalledWith[1]).contains("Some other text in the file") val cruncherResumeUser1 = resumeRepository.getByUserId("some-user-id")!! assertThat(cruncherResumeUser1.cruncherData["some-cruncher"]!!.metaData["some-key"]).isEqualTo(10.0) val cruncherResumeUser2 = resumeRepository.getByUserId("some-other-user-id")!! assertThat(cruncherResumeUser2.cruncherData["some-cruncher"]!!.metaData["some-other-key"]).isEqualTo(9.0) } @Test fun `When resume need to be processed but cannot find file, starts and stops without calling the cruncher`() { val resumeUser1 = resumeRepository.save( Resume( filename = "some-file-name.pdf", userId = "some-user-id", fileType = "pdf", cruncherData = mapOf()) ) cruncher.start() cruncher.addWork(resumeUser1) cruncher.stop() cruncher.join() } }
gpl-3.0
4059ffe12dbb24ae5b8de8d332df1f18
39.171642
122
0.619915
4.832136
false
false
false
false
natanieljr/droidmate
project/pcComponents/exploration/src/main/kotlin/org/droidmate/exploration/modelFeatures/reporter/playback/TraceDumpMF.kt
1
1499
package org.droidmate.exploration.modelFeatures.reporter.playback import org.droidmate.exploration.ExplorationContext import org.droidmate.exploration.strategy.playback.Playback import java.nio.file.Path /** * Report to print the state of each playback action, as well as the action which was taken */ class TraceDump @JvmOverloads constructor(reportDir: Path, resourceDir: Path, playbackStrategy: Playback, fileName: String = "dump.txt") : PlaybackReportMF(reportDir, resourceDir, playbackStrategy, fileName) { override suspend fun safeWriteApkReport(context: ExplorationContext<*, *, *>, apkReportDir: Path, resourceDir: Path) { // val reportSubDir = getPlaybackReportDir(apkReportDir) val sb = StringBuilder() val header = "TraceNr\tActionNr\tRequested\tReproduced\tExplorationAction\n" sb.append(header) TODO("use ModelFeature with own dump method if the current model does not have sufficient data") // playbackStrategy.traces.forEachIndexed { traceNr, trace -> // trace.getTraceCopy().forEachIndexed { actionNr, traceData -> // sb.append("$traceNr\t$actionNr\t${traceData.requested}\t${traceData.explored}\t${traceData.action}\n") // } // } // val reportFile = reportSubDir.resolve(fileName) // Files.write(reportFile, sb.toString().toByteArray()) } override fun reset() { // Do nothing } }
gpl-3.0
74e8cc7969652ab2752cd311ff30793a
40.666667
145
0.677118
4.234463
false
false
false
false
googlecodelabs/kotlin-coroutines
advanced-coroutines-codelab/sunflower/src/main/java/com/example/android/advancedcoroutines/Plant.kt
1
1153
/* * Copyright 2018 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.android.advancedcoroutines import androidx.room.ColumnInfo import androidx.room.Entity import androidx.room.PrimaryKey @Entity(tableName = "plants") data class Plant( @PrimaryKey @ColumnInfo(name = "id") val plantId: String, val name: String, val description: String, val growZoneNumber: Int, val wateringInterval: Int = 7, // how often the plant should be watered, in days val imageUrl: String = "" ) { override fun toString() = name } inline class GrowZone(val number: Int) val NoGrowZone = GrowZone(-1)
apache-2.0
b0f0bc9519c09db200b2ea1185ac724d
30.189189
84
0.732003
4.017422
false
false
false
false
nemerosa/ontrack
ontrack-extension-test/src/main/kotlin/net/nemerosa/ontrack/extension/test/TestPropertyType.kt
1
2105
package net.nemerosa.ontrack.extension.test import com.fasterxml.jackson.databind.JsonNode import net.nemerosa.ontrack.extension.support.AbstractPropertyType import net.nemerosa.ontrack.model.form.Form import net.nemerosa.ontrack.model.form.Text import net.nemerosa.ontrack.model.security.ProjectEdit import net.nemerosa.ontrack.model.security.SecurityService import net.nemerosa.ontrack.model.structure.ProjectEntity import net.nemerosa.ontrack.model.structure.ProjectEntityType import org.springframework.beans.factory.annotation.Autowired import org.springframework.stereotype.Component import java.util.* import java.util.function.Function @Component class TestPropertyType @Autowired constructor(extensionFeature: TestFeature) : AbstractPropertyType<TestProperty>(extensionFeature) { override fun getName(): String = "Test" override fun getDescription(): String = "Associates a text with the entity" override fun getSupportedEntityTypes(): Set<ProjectEntityType> = EnumSet.allOf(ProjectEntityType::class.java) override fun canEdit(entity: ProjectEntity, securityService: SecurityService): Boolean = securityService.isProjectFunctionGranted(entity, ProjectEdit::class.java) override fun canView(entity: ProjectEntity, securityService: SecurityService): Boolean = true override fun getEditionForm(entity: ProjectEntity, value: TestProperty?): Form = Form.create() .with( Text.of("value") .label("My value") .length(20) .value(value?.value) ) override fun fromClient(node: JsonNode): TestProperty = fromStorage(node) override fun fromStorage(node: JsonNode): TestProperty = AbstractPropertyType.parse(node, TestProperty::class.java) override fun replaceValue(value: TestProperty, replacementFunction: Function<String, String>): TestProperty = TestProperty( replacementFunction.apply(value.value) ) }
mit
82e486a0739d197b926040e736af6262
41.959184
113
0.712589
5.047962
false
true
false
false
d9n/intellij-rust
src/main/kotlin/org/rust/lang/core/types/ty/TyPrimitive.kt
1
3937
package org.rust.lang.core.types.ty import com.intellij.openapi.project.Project import com.intellij.psi.PsiElement import org.rust.lang.core.psi.* import org.rust.lang.core.psi.ext.hasColonColon import org.rust.lang.core.psi.ext.sizeExpr /** * These are "atomic" ty (not type constructors, singletons). * * Definition intentionally differs from the reference: we don't treat * tuples or arrays as primitive. */ interface TyPrimitive : Ty { override fun canUnifyWith(other: Ty, project: Project, mapping: TypeMapping?): Boolean = this == other companion object { fun fromPath(path: RsPath): TyPrimitive? { if (path.hasColonColon) return null if (path.parent !is RsBaseType) return null val name = path.referenceName val integerKind = TyInteger.Kind.values().find { it.name == name } if (integerKind != null) return TyInteger(integerKind) val floatKind = TyFloat.Kind.values().find { it.name == name } if (floatKind != null) return TyFloat(floatKind) return when (name) { "bool" -> TyBool "char" -> TyChar "str" -> TyStr else -> null } } } } object TyBool : TyPrimitive { override fun toString(): String = "bool" } object TyChar : TyPrimitive { override fun toString(): String = "char" } object TyUnit : TyPrimitive { override fun toString(): String = "()" } object TyStr : TyPrimitive { override fun toString(): String = "str" } interface TyNumeric : TyPrimitive { val isKindWeak: Boolean override fun canUnifyWith(other: Ty, project: Project, mapping: MutableMap<TyTypeParameter, Ty>?): Boolean = this == other || javaClass == other.javaClass && (other as TyNumeric).isKindWeak } class TyInteger(val kind: Kind, override val isKindWeak: Boolean = false) : TyNumeric { companion object { fun fromLiteral(literal: PsiElement): TyInteger { val kind = Kind.values().find { literal.text.endsWith(it.name) } ?: inferKind(literal) return TyInteger(kind ?: DEFAULT_KIND, kind == null) } /** * Tries to infer the kind of an unsuffixed integer literal by its context. * Fall back to the default kind if can't infer. */ private fun inferKind(literal: PsiElement): Kind? { val expr = literal.parent as? RsLitExpr ?: return null return when { expr.isArraySize -> Kind.usize expr.isEnumVariantDiscriminant -> Kind.isize else -> null } } private val RsLitExpr.isArraySize: Boolean get() = (parent as? RsArrayExpr)?.sizeExpr == this private val RsLitExpr.isEnumVariantDiscriminant: Boolean get() = parent is RsVariantDiscriminant val DEFAULT_KIND = Kind.i32 } enum class Kind { u8, u16, u32, u64, u128, usize, i8, i16, i32, i64, i128, isize } // Ignore `isKindWeak` for the purposes of equality override fun equals(other: Any?): Boolean = other is TyInteger && other.kind == kind override fun hashCode(): Int = kind.hashCode() override fun toString(): String = kind.toString() } class TyFloat(val kind: Kind, override val isKindWeak: Boolean = false) : TyNumeric { companion object { fun fromLiteral(literal: PsiElement): TyFloat { val kind = Kind.values().find { literal.text.endsWith(it.name) } return TyFloat(kind ?: DEFAULT_KIND, kind == null) } val DEFAULT_KIND = Kind.f64 } enum class Kind { f32, f64 } // Ignore `isKindWeak` for the purposes of equality override fun equals(other: Any?): Boolean = other is TyFloat && other.kind == kind override fun hashCode(): Int = kind.hashCode() override fun toString(): String = kind.toString() }
mit
1ff7cf4562269fea2e17189228ceb09e
31.270492
110
0.624333
4.284004
false
false
false
false
nextcloud/android
app/src/androidTest/java/com/nextcloud/client/jobs/ContactsBackupIT.kt
1
3267
/* * Nextcloud Android client application * * @author Tobias Kaminsky * Copyright (C) 2020 Tobias Kaminsky * Copyright (C) 2020 Nextcloud GmbH * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero 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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package com.nextcloud.client.jobs import android.Manifest import androidx.test.rule.GrantPermissionRule import androidx.work.WorkManager import com.nextcloud.client.core.ClockImpl import com.owncloud.android.AbstractIT import com.owncloud.android.AbstractOnServerIT import com.owncloud.android.R import com.owncloud.android.datamodel.OCFile import com.owncloud.android.operations.DownloadFileOperation import ezvcard.Ezvcard import ezvcard.VCard import junit.framework.Assert.assertEquals import junit.framework.Assert.assertTrue import org.junit.Rule import org.junit.Test import java.io.File class ContactsBackupIT : AbstractOnServerIT() { val workmanager = WorkManager.getInstance(targetContext) private val backgroundJobManager = BackgroundJobManagerImpl(workmanager, ClockImpl()) @get:Rule val writeContactsRule = GrantPermissionRule.grant(Manifest.permission.WRITE_CONTACTS) @get:Rule val readContactsRule = GrantPermissionRule.grant(Manifest.permission.READ_CONTACTS) private val vcard: String = "vcard.vcf" @Test fun importExport() { val intArray = IntArray(1) intArray[0] = 0 // import file to local contacts backgroundJobManager.startImmediateContactsImport(null, null, getFile(vcard).absolutePath, intArray) shortSleep() // export contact backgroundJobManager.startImmediateContactsBackup(user) longSleep() val backupFolder: String = targetContext.resources.getString(R.string.contacts_backup_folder) + OCFile.PATH_SEPARATOR refreshFolder("/") longSleep() refreshFolder(backupFolder) longSleep() val backupOCFile = storageManager.getFolderContent( storageManager.getFileByDecryptedRemotePath(backupFolder), false )[0] assertTrue(DownloadFileOperation(user, backupOCFile, AbstractIT.targetContext).execute(client).isSuccess) val backupFile = File(backupOCFile.storagePath) // verify same val originalCards: ArrayList<VCard> = ArrayList() originalCards.addAll(Ezvcard.parse(getFile(vcard)).all()) val backupCards: ArrayList<VCard> = ArrayList() backupCards.addAll(Ezvcard.parse(backupFile).all()) assertEquals(originalCards.size, backupCards.size) assertEquals(originalCards[0].formattedName.toString(), backupCards[0].formattedName.toString()) } }
gpl-2.0
e0fb5cb29a48716fc672842aeca788c8
33.03125
113
0.739822
4.562849
false
false
false
false
DemonWav/IntelliJBukkitSupport
src/main/kotlin/platform/mcp/actions/CopyAtAction.kt
1
2459
/* * Minecraft Dev for IntelliJ * * https://minecraftdev.org * * Copyright (c) 2021 minecraft-dev * * MIT License */ package com.demonwav.mcdev.platform.mcp.actions import com.demonwav.mcdev.platform.mcp.srg.McpSrgMap import com.demonwav.mcdev.util.ActionData import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.editor.Editor import com.intellij.psi.PsiClass import com.intellij.psi.PsiElement import com.intellij.psi.PsiField import com.intellij.psi.PsiMethod import java.awt.Toolkit import java.awt.datatransfer.StringSelection class CopyAtAction : SrgActionBase() { override fun withSrgTarget(parent: PsiElement, srgMap: McpSrgMap, e: AnActionEvent, data: ActionData) { when (parent) { is PsiField -> { val containing = parent.containingClass ?: return showBalloon("No SRG name found", e) val classSrg = srgMap.getSrgClass(containing) ?: return showBalloon("No SRG name found", e) val srg = srgMap.getSrgField(parent) ?: return showBalloon("No SRG name found", e) copyToClipboard( data.editor, data.element, classSrg + " " + srg.name + " # " + parent.name ) } is PsiMethod -> { val containing = parent.containingClass ?: return showBalloon("No SRG name found", e) val classSrg = srgMap.getSrgClass(containing) ?: return showBalloon("No SRG name found", e) val srg = srgMap.getSrgMethod(parent) ?: return showBalloon("No SRG name found", e) copyToClipboard( data.editor, data.element, classSrg + " " + srg.name + srg.descriptor + " # " + parent.name ) } is PsiClass -> { val classMcpToSrg = srgMap.getSrgClass(parent) ?: return showBalloon("No SRG name found", e) copyToClipboard(data.editor, data.element, classMcpToSrg) } else -> showBalloon("Not a valid element", e) } } private fun copyToClipboard(editor: Editor, element: PsiElement, text: String) { val stringSelection = StringSelection(text) val clpbrd = Toolkit.getDefaultToolkit().systemClipboard clpbrd.setContents(stringSelection, null) showSuccessBalloon(editor, element, "Copied $text") } }
mit
a0e2f2fa134194f7ee93f491e16d4962
39.311475
108
0.619357
4.438628
false
false
false
false
VoxelGamesLib/VoxelGamesLibv2
games/tixtax/src/main/kotlin/com/voxelgameslib/tixtax/tixtaxPhase.kt
1
932
package com.voxelgameslib.tixtax import com.voxelgameslib.kvgl.* import com.voxelgameslib.voxelgameslib.GameConstants import com.voxelgameslib.voxelgameslib.feature.features.GameModeFeature import com.voxelgameslib.voxelgameslib.feature.features.MapFeature import com.voxelgameslib.voxelgameslib.feature.features.SpawnFeature import com.voxelgameslib.voxelgameslib.feature.features.TeamFeature import com.voxelgameslib.voxelgameslib.phase.TimedPhase class tixtaxPhase : TimedPhase() { override fun init() { name = "tixtaxPhase" ticks = 2 * 60 * GameConstants.TPS super.init() allowJoin = false allowSpectate = true addFeature<MapFeature> { shouldUnload = true } addFeature<SpawnFeature> { isRespawn = false } addFeature<GameModeFeature>() addFeature<tixtaxFeature>() addFeature<TeamFeature>() } }
mit
b3e0b60b0f6114fb506ec7649c84ef91
27.242424
71
0.7103
3.915966
false
false
false
false
soywiz/korge
@old/korge-samples/jvm/src/commonMain/kotlin/Sample1.kt
1
3074
import com.soywiz.korge.* import com.soywiz.korge.input.* import com.soywiz.korge.view.* import com.soywiz.korim.bitmap.* import com.soywiz.korim.color.* import com.soywiz.korim.format.* import com.soywiz.korio.file.std.* import kotlin.jvm.* object Sample1 { @JvmStatic fun main(args: Array<String>) = Korge(title = "Sample1") { //waveEffectView { //colorMatrixEffectView(ColorMatrixEffectView.GRAYSCALE_MATRIX) { //convolute3EffectView(Convolute3EffectView.KERNEL_EDGE_DETECTION) { /* blurEffectView(radius = 1.0) { convolute3EffectView(Convolute3EffectView.KERNEL_GAUSSIAN_BLUR) { //convolute3EffectView(Convolute3EffectView.KERNEL_BOX_BLUR) { swizzleColorsEffectView("bgra") { x = 100.0 y = 100.0 image(Bitmap32(100, 100) { x, y -> RGBA(156 + x, 156 + y, 0, 255) }) //solidRect(100, 100, Colors.RED) } //} } }.apply { tween(this::radius[10.0], time = 5.seconds) } */ //val mfilter = ColorMatrixFilter(ColorMatrixFilter.GRAYSCALE_MATRIX, 0.0) //val mfilter = WaveFilter() //val mfilter = Convolute3Filter(Convolute3Filter.KERNEL_GAUSSIAN_BLUR) solidRect(640, 480, Colors.ALICEBLUE) image(resourcesVfs["a.png"].readBitmap()) { position(50, 50) } image(Bitmap32(100, 100) { x, y -> RGBA(156 + x, 156 + y, 0, 255) }) { x = 100.0 y = 100.0 //filter = ComposedFilter(SwizzleColorsFilter("bgra"), SwizzleColorsFilter("bgra")) //filter = ComposedFilter( // SwizzleColorsFilter("bgra"), // Convolute3Filter(Convolute3Filter.KERNEL_GAUSSIAN_BLUR), // Convolute3Filter(Convolute3Filter.KERNEL_EDGE_DETECTION) //) //filter = ComposedFilter(mfilter, Convolute3Filter(Convolute3Filter.KERNEL_GAUSSIAN_BLUR)) alpha = 1.0 //filter = mfilter //filter = WaveFilter() }.apply { //mfilter.amplitudeY = 6 //mfilter.amplitudeX = 0 //mfilter.time = 0.5 //tween(mfilter::time[0.0, 10.0], time = 10.seconds) //tween(mfilter::blendRatio[0.0, 1.0], time = 4.seconds) onClick { try { //LaunchReview.launch("com.google.android.apps.maps") //println(Camera.getPicture(Camera.Info())) AdMob.banner.prepare() AdMob.banner.show() //AdMob.rewardvideo.prepare() //AdMob.rewardvideo.show() } catch (e: Throwable) { alert("$e") } } } //val bmp = SolidRect(100, 100, Colors.RED).renderToBitmap(views) //val bmp = view.renderToBitmap(views) //bmp.writeTo("/tmp/demo.png".uniVfs, defaultImageFormats) //println(bmp) } }
apache-2.0
2e2bef81b76a485e49068cfe557c4ba8
38.410256
103
0.543266
3.856964
false
false
false
false
cashapp/sqldelight
sqldelight-gradle-plugin/src/main/kotlin/app/cash/sqldelight/gradle/squash/MigrationSquashTask.kt
1
4480
package app.cash.sqldelight.gradle.squash import app.cash.sqldelight.VERSION import app.cash.sqldelight.core.SqlDelightCompilationUnit import app.cash.sqldelight.core.SqlDelightDatabaseProperties import app.cash.sqldelight.core.SqlDelightEnvironment import app.cash.sqldelight.core.lang.MigrationLanguage import app.cash.sqldelight.core.psi.SqlDelightImportStmtList import app.cash.sqldelight.dialect.api.SqlDelightDialect import app.cash.sqldelight.gradle.SqlDelightCompilationUnitImpl import app.cash.sqldelight.gradle.SqlDelightDatabasePropertiesImpl import app.cash.sqldelight.gradle.SqlDelightWorkerTask import com.alecstrong.sql.psi.core.SqlFileBase import com.intellij.psi.PsiFileFactory import org.gradle.api.file.FileTree import org.gradle.api.provider.Property import org.gradle.api.tasks.CacheableTask import org.gradle.api.tasks.Input import org.gradle.api.tasks.InputFiles import org.gradle.api.tasks.Nested import org.gradle.api.tasks.PathSensitive import org.gradle.api.tasks.PathSensitivity import org.gradle.api.tasks.SkipWhenEmpty import org.gradle.api.tasks.TaskAction import org.gradle.workers.WorkAction import org.gradle.workers.WorkParameters import java.io.File import java.util.ServiceLoader @CacheableTask abstract class MigrationSquashTask : SqlDelightWorkerTask() { @Suppress("unused") // Required to invalidate the task on version updates. @Input val pluginVersion = VERSION @Input val projectName: Property<String> = project.objects.property(String::class.java) @Nested lateinit var properties: SqlDelightDatabasePropertiesImpl @Nested lateinit var compilationUnit: SqlDelightCompilationUnitImpl @TaskAction fun generateSquashedMigrationFile() { workQueue().submit(GenerateMigration::class.java) { it.moduleName.set(projectName) it.properties.set(properties) it.compilationUnit.set(compilationUnit) } } @InputFiles @SkipWhenEmpty @PathSensitive(PathSensitivity.RELATIVE) override fun getSource(): FileTree { return super.getSource() } interface GenerateSchemaWorkParameters : WorkParameters { val moduleName: Property<String> val properties: Property<SqlDelightDatabaseProperties> val compilationUnit: Property<SqlDelightCompilationUnit> } abstract class GenerateMigration : WorkAction<GenerateSchemaWorkParameters> { private val sourceFolders: List<File> get() = parameters.compilationUnit.get().sourceFolders.map { it.folder } override fun execute() { val properties = parameters.properties.get() val environment = SqlDelightEnvironment( sourceFolders = sourceFolders.filter { it.exists() }, dependencyFolders = emptyList(), moduleName = parameters.moduleName.get(), properties = properties, verifyMigrations = false, compilationUnit = parameters.compilationUnit.get(), dialect = ServiceLoader.load(SqlDelightDialect::class.java).single(), ) val fileFromText = { text: String -> PsiFileFactory.getInstance(environment.project).createFileFromText(MigrationLanguage, text) as SqlFileBase } val ansiSquasher = AnsiSqlMigrationSquasher(fileFromText) val squasher = environment.dialect.migrationSquasher(ansiSquasher) ansiSquasher.squasher = squasher // For recursion to ensure the dialect squasher gets called. val imports = linkedSetOf<String>() var newMigrations = fileFromText("") // Generate the new files. var topVersion = 0 lateinit var migrationDirectory: File environment.forMigrationFiles { migrationFile -> if (migrationFile.version > topVersion) { topVersion = migrationFile.version migrationDirectory = File(migrationFile.virtualFile!!.parent.path) } val migrations = migrationFile.sqlStmtList?.children ?.filterIsInstance<SqlDelightImportStmtList>()?.single() migrations?.importStmtList?.forEach { imports.add(it.javaType.text) } migrationFile.sqlStmtList?.stmtList?.forEach { newMigrations = fileFromText(squasher.squish(it, into = newMigrations)) } } var text = newMigrations.text if (imports.isNotEmpty()) { text = """ |${imports.joinToString(separator = "\n", transform = { "import $it;" })} | |$text """.trimMargin() } File(migrationDirectory, "_$topVersion.sqm").writeText(text) } } }
apache-2.0
58cefacf145e31932526ac4d6f586778
34.555556
114
0.740625
4.6138
false
false
false
false
martin-nordberg/KatyDOM
Katydid-VDOM-JS/src/main/kotlin/o/katydid/vdom/builders/KatydidPhrasingContentBuilder.kt
1
153261
// // (C) Copyright 2017-2019 Martin E. Nordberg III // Apache 2.0 License // package o.katydid.vdom.builders import o.katydid.vdom.builders.media.KatydidMediaPhrasingContentBuilder import o.katydid.vdom.builders.miscellaneous.KatydidOptGroupContentBuilder import o.katydid.vdom.builders.miscellaneous.KatydidSelectContentBuilder import o.katydid.vdom.builders.miscellaneous.KatydidTextContentBuilder import o.katydid.vdom.builders.objects.KatydidObjectPhrasingContentBuilder import o.katydid.vdom.builders.ruby.KatydidRubyContentBuilder import o.katydid.vdom.types.* import x.katydid.vdom.types.KatyDateTime import x.katydid.vdom.types.KatyTime //--------------------------------------------------------------------------------------------------------------------- /** * Virtual DOM builder for the case of HTML "phrasing content". */ @Suppress("unused") interface KatydidPhrasingContentBuilder<in Msg> : KatydidEmbeddedContentBuilder<Msg> { /** * Adds an `<a>` element with its attributes as the next child of the element under construction. * @param selector the "selector" for the element, e.g. "#myid.my-class.my-other-class". * @param key a non-DOM key for this Katydid element that is unique among all the siblings of this element. * @param accesskey a string specifying the HTML accesskey value. * @param contenteditable whether the element has editable content. * @param dir the left-to-right direction of text inside this element. * @param download non-empty to download the resource with that file name instead of opening in the browser. * @param draggable controls whether or not the element is draggable. * @param hidden true if the element is to be hidden. * @param href the URL linked to. * @param hreflang the language of the document linked to. * @param lang the language of text within this element. * @param rel the relationship of the document to the linked document. * @param rev the relationship of the linked document to this document. * @param spellcheck whether the element is subject to spell checking. * @param style a string containing CSS for this element. * @param tabindex the tab index for the element. * @param target the window or browsing context to open the link in. * @param title a tool tip for the element. * @param translate whether to translate text within this element. * @param type the type of the linked resource. * @param defineContent a DSL-style lambda that builds the child nodes of the new element. */ fun a( selector: String? = null, key: Any? = null, accesskey: Char? = null, contenteditable: Boolean? = null, dir: EDirection? = null, download: String? = null, draggable: Boolean? = null, hidden: Boolean? = null, href: String? = null, hreflang: String? = null, lang: String? = null, rel: Iterable<EAnchorHtmlLinkType>? = null, rev: Iterable<EAnchorHtmlLinkType>? = null, spellcheck: Boolean? = null, style: String? = null, tabindex: Int? = null, target: String? = null, title: String? = null, translate: Boolean? = null, type: String? = null, defineContent: KatydidPhrasingContentBuilder<Msg>.() -> Unit ) /** * Adds an `<abbr>` element with its attributes as the next child of the element under construction. * @param selector the "selector" for the element, e.g. "#myid.my-class.my-other-class". * @param key a non-DOM key for this Katydid element that is unique among all the siblings of this element. * @param accesskey a string specifying the HTML accesskey value. * @param contenteditable whether the element has editable content. * @param dir the left-to-right direction of text inside this element. * @param draggable controls whether or not the element is draggable. * @param hidden true if the element is to be hidden. * @param lang the language of text within this element. * @param spellcheck whether the element is subject to spell checking. * @param style a string containing CSS for this element. * @param tabindex the tab index for the element. * @param title a tool tip for the element. * @param translate whether to translate text within this element. * @param defineContent a DSL-style lambda that builds the child nodes of the new element. */ fun abbr( selector: String? = null, key: Any? = null, accesskey: Char? = null, contenteditable: Boolean? = null, dir: EDirection? = null, draggable: Boolean? = null, hidden: Boolean? = null, lang: String? = null, spellcheck: Boolean? = null, style: String? = null, tabindex: Int? = null, title: String? = null, translate: Boolean? = null, defineContent: KatydidPhrasingContentBuilder<Msg>.() -> Unit ) /** * Adds an `<area>` element with its attributes as the next child of the element under construction. * @param selector the "selector" for the element, e.g. "#myid.my-class.my-other-class". * @param key a non-DOM key for this Katydid element that is unique among all the siblings of this element. * @param accesskey a string specifying the HTML accesskey value. * @param alt - Replacement text for use when images are not available * @param contenteditable whether the element has editable content. * @param coords - Coordinates for the shape to be created in an image map * @param dir the left-to-right direction of text inside this element. * @param draggable controls whether or not the element is draggable. * @param download - Whether to download the resource instead of navigating to it, and its file name if so * @param hidden true if the element is to be hidden. * @param href - Address of the hyperlink * @param hreflang - Language of the linked resource * @param lang the language of text within this element. * @param referrerpolicy - Referrer policy for fetches initiated by the element * @param rel - Relationship of this document (or subsection/topic) to the destination resource * @param shape - The kind of shape to be created in an image map * @param spellcheck whether the element is subject to spell checking. * @param style a string containing CSS for this element. * @param tabindex the tab index for the element. * @param target - browsing context for hyperlink navigation * @param title a tool tip for the element. * @param translate whether to translate text within this element. * @param type - Hint for the type of the referenced resource * @param defineAttributes a DSL-style lambda that sets additional attributes of the new element. */ fun area( selector: String? = null, key: Any? = null, accesskey: Char? = null, alt: String? = null, contenteditable: Boolean? = null, coords: String? = null, dir: EDirection? = null, download: String? = null, draggable: Boolean? = null, hidden: Boolean? = null, href: String? = null, hreflang: String? = null, lang: String? = null, referrerpolicy: EReferrerPolicy? = null, rel: EAnchorHtmlLinkType? = null, spellcheck: Boolean? = null, shape: EAreaShape? = null, style: String? = null, tabindex: Int? = null, target: String? = null, title: String? = null, translate: Boolean? = null, type: String? = null, defineAttributes: KatydidAttributesContentBuilder<Msg>.() -> Unit ) /** * Adds an `<audio>` element with its attributes as the next child of the element under construction. * @param selector the "selector" for the element, e.g. "#myid.my-class.my-other-class". * @param key a non-DOM key for this Katydid element that is unique among all the siblings of this element. * @param accesskey a string specifying the HTML accesskey value. * @param autoplay hint that the media resource can be started automatically when the page is loaded. * @param contenteditable whether the element has editable content. * @param controls show user agent controls * @param crossorigin how the element handles crossorigin requests. * @param dir the left-to-right direction of text inside this element. * @param draggable controls whether or not the element is draggable. * @param hidden true if the element is to be hidden. * @param lang the language of text within this element. * @param loop whether to loop the media resource. * @param muted whether to mute the media resource by default. * @param preload hints how much buffering the media resource will likely need. * @param spellcheck whether the element is subject to spell checking. * @param src address of the resource. * @param style a string containing CSS for this element. * @param tabindex the tab index for the element. * @param title a tool tip for the element. * @param translate whether to translate text within this element. * @param contentType parameter to indicate what kind of transparent content is needed. * @param defineContent a DSL-style lambda that builds child elements of the new element. */ fun audio( selector: String? = null, key: Any? = null, accesskey: Char? = null, autoplay: Boolean? = null, contenteditable: Boolean? = null, controls: Boolean? = null, crossorigin: ECorsSetting? = null, dir: EDirection? = null, draggable: Boolean? = null, hidden: Boolean? = null, lang: String? = null, loop: Boolean? = null, muted: Boolean? = null, preload: EPreloadHint? = null, spellcheck: Boolean? = null, src: String? = null, style: String? = null, tabindex: Int? = null, title: String? = null, translate: Boolean? = null, contentType: PhrasingContent, defineContent: KatydidMediaPhrasingContentBuilder<Msg>.() -> Unit ) /** * Adds a `<b>` element with its attributes as the next child of the element under construction. * @param selector the "selector" for the element, e.g. "#myid.my-class.my-other-class". * @param key a non-DOM key for this Katydid element that is unique among all the siblings of this element. * @param accesskey a string specifying the HTML accesskey value. * @param contenteditable whether the element has editable content. * @param dir the left-to-right direction of text inside this element. * @param draggable controls whether or not the element is draggable. * @param hidden true if the element is to be hidden. * @param lang the language of text within this element. * @param spellcheck whether the element is subject to spell checking. * @param style a string containing CSS for this element. * @param tabindex the tab index for the element. * @param title a tool tip for the element. * @param translate whether to translate text within this element. * @param defineContent a DSL-style lambda that builds the child nodes of the new element. */ fun b( selector: String? = null, key: Any? = null, accesskey: Char? = null, contenteditable: Boolean? = null, dir: EDirection? = null, draggable: Boolean? = null, hidden: Boolean? = null, lang: String? = null, spellcheck: Boolean? = null, style: String? = null, tabindex: Int? = null, title: String? = null, translate: Boolean? = null, defineContent: KatydidPhrasingContentBuilder<Msg>.() -> Unit ) /** * Adds a `<bdi>` element with its attributes as the next child of the element under construction. * @param selector the "selector" for the element, e.g. "#myid.my-class.my-other-class". * @param key a non-DOM key for this Katydid element that is unique among all the siblings of this element. * @param accesskey a string specifying the HTML accesskey value. * @param contenteditable whether the element has editable content. * @param dir the left-to-right direction of text inside this element. * @param draggable controls whether or not the element is draggable. * @param hidden true if the element is to be hidden. * @param lang the language of text within this element. * @param spellcheck whether the element is subject to spell checking. * @param style a string containing CSS for this element. * @param tabindex the tab index for the element. * @param title a tool tip for the element. * @param translate whether to translate text within this element. * @param defineContent a DSL-style lambda that builds the child nodes of the new element. */ fun bdi( selector: String? = null, key: Any? = null, accesskey: Char? = null, contenteditable: Boolean? = null, dir: EDirection, draggable: Boolean? = null, hidden: Boolean? = null, lang: String? = null, spellcheck: Boolean? = null, style: String? = null, tabindex: Int? = null, title: String? = null, translate: Boolean? = null, defineContent: KatydidPhrasingContentBuilder<Msg>.() -> Unit ) /** * Adds a `<bdo>` element with its attributes as the next child of the element under construction. * @param selector the "selector" for the element, e.g. "#myid.my-class.my-other-class". * @param key a non-DOM key for this Katydid element that is unique among all the siblings of this element. * @param accesskey a string specifying the HTML accesskey value. * @param contenteditable whether the element has editable content. * @param dir the left-to-right direction of text inside this element. * @param draggable controls whether or not the element is draggable. * @param hidden true if the element is to be hidden. * @param lang the language of text within this element. * @param spellcheck whether the element is subject to spell checking. * @param style a string containing CSS for this element. * @param tabindex the tab index for the element. * @param title a tool tip for the element. * @param translate whether to translate text within this element. * @param defineContent a DSL-style lambda that builds the child nodes of the new element. */ fun bdo( selector: String? = null, key: Any? = null, accesskey: Char? = null, contenteditable: Boolean? = null, dir: EDirection, draggable: Boolean? = null, hidden: Boolean? = null, lang: String? = null, spellcheck: Boolean? = null, style: String? = null, tabindex: Int? = null, title: String? = null, translate: Boolean? = null, defineContent: KatydidPhrasingContentBuilder<Msg>.() -> Unit ) /** * Adds a `<br>` (line break) element as the next child of the element under construction. * @param selector the "selector" for the element, e.g. "#myid.my-class.my-other-class". * @param key a non-DOM key for this Katydid element that is unique among all the siblings of this element. * @param accesskey a string specifying the HTML accesskey value. * @param contenteditable whether the element has editable content. * @param dir the left-to-right direction of text inside this element. * @param draggable controls whether or not the element is draggable. * @param hidden true if the element is to be hidden. * @param lang the language of text within this element. * @param spellcheck whether the element is subject to spell checking. * @param style a string containing CSS for this element. * @param tabindex the tab index for the element. * @param title a tool tip for the element. * @param translate whether to translate text within this element. * @param defineAttributes a DSL-style lambda that adds any nonstandard attributes to the new element. */ fun br( selector: String? = null, key: Any? = null, accesskey: Char? = null, contenteditable: Boolean? = null, dir: EDirection? = null, draggable: Boolean? = null, hidden: Boolean? = null, lang: String? = null, spellcheck: Boolean? = null, style: String? = null, tabindex: Int? = null, title: String? = null, translate: Boolean? = null, defineAttributes: KatydidAttributesContentBuilder<Msg>.() -> Unit ) /** * Adds a `<button>` element with given attributes as the next child of the element under construction. * @param selector the "selector" for the element, e.g. "#myid.my-class.my-other-class". * @param key a non-DOM key for this Katydid element that is unique among all the siblings of this element. * @param accesskey a string specifying the HTML accesskey value. * @param autofocus true to make the element the focused control in the browser. * @param contenteditable whether the element has editable content. * @param dir the left-to-right direction of text inside this element. * @param draggable controls whether or not the element is draggable. * @param disabled true to make the element disabled in the browser display. * @param form the form acted upon by this button. * @param formaction the URL to use for form submission. * @param formenctype the encoding type to be used for form data submitted by this button. * @param formmethod the choice of GET or POST for submitting the form's data. * @param formnovalidate true to skip form field validation when this button is clicked. * @param formtarget the target window (browser context) for form submission * @param hidden true if the element is to be hidden. * @param lang the language of text within this element. * @param name the name of this button as a form field. * @param spellcheck whether the element is subject to spell checking. * @param style a string containing CSS for this element. * @param tabindex the tab index for the element. * @param title a tool tip for the element. * @param translate whether to translate text within this element. * @param type the type of button. * @param value the value of the button for form field submission. * @param defineContent a DSL-style lambda that builds the child nodes of the new element. */ fun button( selector: String? = null, key: Any? = null, accesskey: Char? = null, autofocus: Boolean? = null, contenteditable: Boolean? = null, dir: EDirection? = null, disabled: Boolean? = null, draggable: Boolean? = null, form: String? = null, formaction: String? = null, formenctype: EFormEncodingType? = null, formmethod: EFormSubmissionMethod? = null, formnovalidate: Boolean? = null, formtarget: String? = null, hidden: Boolean? = null, lang: String? = null, name: String? = null, spellcheck: Boolean? = null, style: String? = null, tabindex: Int? = null, title: String? = null, translate: Boolean? = null, type: EButtonType? = EButtonType.button, value: String? = null, defineContent: KatydidPhrasingContentBuilder<Msg>.() -> Unit ) /** * Adds a `<canvas>` element with its attributes as the next child of the element under construction. * @param selector the "selector" for the element, e.g. "#myid.my-class.my-other-class". * @param key a non-DOM key for this Katydid element that is unique among all the siblings of this element. * @param accesskey a string specifying the HTML accesskey value. * @param contenteditable whether the element has editable content. * @param dir the left-to-right direction of text inside this element. * @param draggable controls whether or not the element is draggable. * @param height vertical dimension. * @param hidden true if the element is to be hidden. * @param lang the language of text within this element. * @param spellcheck whether the element is subject to spell checking. * @param style a string containing CSS for this element. * @param tabindex the tab index for the element. * @param title a tool tip for the element. * @param translate whether to translate text within this element. * @param width horizontal dimension. * @param contentType flag to explicitly specify content type to support content transparency. * @param defineContent a DSL-style lambda that builds the content of the new element. */ fun canvas( selector: String? = null, key: Any? = null, accesskey: Char? = null, contenteditable: Boolean? = null, dir: EDirection? = null, draggable: Boolean? = null, height: Int? = null, hidden: Boolean? = null, lang: String? = null, spellcheck: Boolean? = null, style: String? = null, tabindex: Int? = null, title: String? = null, translate: Boolean? = null, width: Int? = null, contentType: PhrasingContent = PhrasingContent, defineContent: KatydidPhrasingContentBuilder<Msg>.() -> Unit ) /** * Adds a `<cite>` element with its attributes as the next child of the element under construction. * @param selector the "selector" for the element, e.g. "#myid.my-class.my-other-class". * @param key a non-DOM key for this Katydid element that is unique among all the siblings of this element. * @param accesskey a string specifying the HTML accesskey value. * @param contenteditable whether the element has editable content. * @param dir the left-to-right direction of text inside this element. * @param draggable controls whether or not the element is draggable. * @param hidden true if the element is to be hidden. * @param lang the language of text within this element. * @param spellcheck whether the element is subject to spell checking. * @param style a string containing CSS for this element. * @param tabindex the tab index for the element. * @param title a tool tip for the element. * @param translate whether to translate text within this element. * @param defineContent a DSL-style lambda that builds the child nodes of the new element. */ fun cite( selector: String? = null, key: Any? = null, accesskey: Char? = null, contenteditable: Boolean? = null, dir: EDirection? = null, draggable: Boolean? = null, hidden: Boolean? = null, lang: String? = null, spellcheck: Boolean? = null, style: String? = null, tabindex: Int? = null, title: String? = null, translate: Boolean? = null, defineContent: KatydidPhrasingContentBuilder<Msg>.() -> Unit ) /** * Adds a `<code>` element with its attributes as the next child of the element under construction. * @param selector the "selector" for the element, e.g. "#myid.my-class.my-other-class". * @param key a non-DOM key for this Katydid element that is unique among all the siblings of this element. * @param accesskey a string specifying the HTML accesskey value. * @param contenteditable whether the element has editable content. * @param dir the left-to-right direction of text inside this element. * @param draggable controls whether or not the element is draggable. * @param hidden true if the element is to be hidden. * @param lang the language of text within this element. * @param spellcheck whether the element is subject to spell checking. * @param style a string containing CSS for this element. * @param tabindex the tab index for the element. * @param title a tool tip for the element. * @param translate whether to translate text within this element. * @param defineContent a DSL-style lambda that builds the child nodes of the new element. */ fun code( selector: String? = null, key: Any? = null, accesskey: Char? = null, contenteditable: Boolean? = null, dir: EDirection? = null, draggable: Boolean? = null, hidden: Boolean? = null, lang: String? = null, spellcheck: Boolean? = null, style: String? = null, tabindex: Int? = null, title: String? = null, translate: Boolean? = null, defineContent: KatydidPhrasingContentBuilder<Msg>.() -> Unit ) /** * Adds a comment node as the next child of the element under construction. * @param nodeValue the text within the comment. * @param key unique key for this comment within its parent node. */ fun comment( nodeValue: String, key: Any? = null ) /** * Adds a `<data>` element with its attributes as the next child of the element under construction. * @param selector the "selector" for the element, e.g. "#myid.my-class.my-other-class". * @param key a non-DOM key for this Katydid element that is unique among all the siblings of this element. * @param accesskey a string specifying the HTML accesskey value. * @param contenteditable whether the element has editable content. * @param dir the left-to-right direction of text inside this element. * @param draggable controls whether or not the element is draggable. * @param hidden true if the element is to be hidden. * @param lang the language of text within this element. * @param spellcheck whether the element is subject to spell checking. * @param style a string containing CSS for this element. * @param tabindex the tab index for the element. * @param title a tool tip for the element. * @param translate whether to translate text within this element. * @param value the value of the data element. * @param defineContent a DSL-style lambda that builds the child nodes of the new element. */ fun data( selector: String? = null, key: Any? = null, accesskey: Char? = null, contenteditable: Boolean? = null, dir: EDirection? = null, draggable: Boolean? = null, hidden: Boolean? = null, lang: String? = null, spellcheck: Boolean? = null, style: String? = null, tabindex: Int? = null, title: String? = null, translate: Boolean? = null, value: String, defineContent: KatydidPhrasingContentBuilder<Msg>.() -> Unit ) /** * Adds a `<datalist>` element with its attributes as the next child of the element under construction. * View the specification: https://www.w3.org/TR/html5/sec-forms.html#the-datalist-element. * @param selector the "selector" for the element, e.g. "#myid.my-class.my-other-class". * @param key a non-DOM key for this Katydid element that is unique among all the siblings of this element. * @param accesskey a string specifying the HTML accesskey value. * @param contenteditable whether the element has editable content. * @param dir the left-to-right direction of text inside this element. * @param draggable controls whether or not the element is draggable. * @param hidden true if the element is to be hidden. * @param lang the language of text within this element. * @param spellcheck whether the element is subject to spell checking. * @param style a string containing CSS for this element. * @param tabindex the tab index for the element. * @param title a tool tip for the element. * @param translate whether to translate text within this element. * @param defineContent a DSL-style lambda that builds the child nodes of the new element (<option> elements). */ fun datalist( selector: String? = null, key: Any? = null, accesskey: Char? = null, contenteditable: Boolean? = null, dir: EDirection? = null, draggable: Boolean? = null, hidden: Boolean? = null, lang: String? = null, spellcheck: Boolean? = null, style: String? = null, tabindex: Int? = null, title: String? = null, translate: Boolean? = null, defineContent: KatydidOptGroupContentBuilder<Msg>.() -> Unit ) /** * Adds a `<datalist>` element with its attributes as the next child of the element under construction. * View the specification: https://www.w3.org/TR/html5/sec-forms.html#the-datalist-element. * @param selector the "selector" for the element, e.g. "#myid.my-class.my-other-class". * @param key a non-DOM key for this Katydid element that is unique among all the siblings of this element. * @param accesskey a string specifying the HTML accesskey value. * @param contenteditable whether the element has editable content. * @param dir the left-to-right direction of text inside this element. * @param draggable controls whether or not the element is draggable. * @param hidden true if the element is to be hidden. * @param lang the language of text within this element. * @param spellcheck whether the element is subject to spell checking. * @param style a string containing CSS for this element. * @param tabindex the tab index for the element. * @param title a tool tip for the element. * @param translate whether to translate text within this element. * @param contentType flag to turn on phrasing content instead of <option> element content. * @param defineContent a DSL-style lambda that builds the child nodes of the new element (<option> elements). */ fun datalist( selector: String? = null, key: Any? = null, accesskey: Char? = null, contenteditable: Boolean? = null, dir: EDirection? = null, draggable: Boolean? = null, hidden: Boolean? = null, lang: String? = null, spellcheck: Boolean? = null, style: String? = null, tabindex: Int? = null, title: String? = null, translate: Boolean? = null, contentType: PhrasingContent, defineContent: KatydidPhrasingContentBuilder<Msg>.() -> Unit ) /** * Adds a `<del>` element with its attributes as the next child of the element under construction. * @param selector the "selector" for the element, e.g. "#myid.my-class.my-other-class". * @param key a non-DOM key for this Katydid element that is unique among all the siblings of this element. * @param accesskey a string specifying the HTML accesskey value. * @param cite a URL describing the change. * @param contenteditable whether the element has editable content. * @param datetime when the edit was made. * @param dir the left-to-right direction of text inside this element. * @param draggable controls whether or not the element is draggable. * @param hidden true if the element is to be hidden. * @param lang the language of text within this element. * @param spellcheck whether the element is subject to spell checking. * @param style a string containing CSS for this element. * @param tabindex the tab index for the element. * @param title a tool tip for the element. * @param translate whether to translate text within this element. * @param defineContent a DSL-style lambda that builds the child nodes of the new element. */ fun del( selector: String? = null, key: Any? = null, accesskey: Char? = null, cite: String? = null, contenteditable: Boolean? = null, datetime: KatyDateTime? = null, dir: EDirection? = null, draggable: Boolean? = null, hidden: Boolean? = null, lang: String? = null, spellcheck: Boolean? = null, style: String? = null, tabindex: Int? = null, title: String? = null, translate: Boolean? = null, defineContent: KatydidPhrasingContentBuilder<Msg>.() -> Unit ) /** * Adds a `<dfn>` element with its attributes as the next child of the element under construction. * @param selector the "selector" for the element, e.g. "#myid.my-class.my-other-class". * @param key a non-DOM key for this Katydid element that is unique among all the siblings of this element. * @param accesskey a string specifying the HTML accesskey value. * @param contenteditable whether the element has editable content. * @param dir the left-to-right direction of text inside this element. * @param draggable controls whether or not the element is draggable. * @param hidden true if the element is to be hidden. * @param lang the language of text within this element. * @param spellcheck whether the element is subject to spell checking. * @param style a string containing CSS for this element. * @param tabindex the tab index for the element. * @param title a tool tip for the element. * @param translate whether to translate text within this element. * @param defineContent a DSL-style lambda that builds the child nodes of the new element. */ fun dfn( selector: String? = null, key: Any? = null, accesskey: Char? = null, contenteditable: Boolean? = null, dir: EDirection? = null, draggable: Boolean? = null, hidden: Boolean? = null, lang: String? = null, spellcheck: Boolean? = null, style: String? = null, tabindex: Int? = null, title: String? = null, translate: Boolean? = null, defineContent: KatydidPhrasingContentBuilder<Msg>.() -> Unit ) /** * Adds an `<em>` element with its attributes as the next child of the element under construction. * @param selector the "selector" for the element, e.g. "#myid.my-class.my-other-class". * @param key a non-DOM key for this Katydid element that is unique among all the siblings of this element. * @param accesskey a string specifying the HTML accesskey value. * @param contenteditable whether the element has editable content. * @param dir the left-to-right direction of text inside this element. * @param draggable controls whether or not the element is draggable. * @param hidden true if the element is to be hidden. * @param lang the language of text within this element. * @param spellcheck whether the element is subject to spell checking. * @param style a string containing CSS for this element. * @param tabindex the tab index for the element. * @param title a tool tip for the element. * @param translate whether to translate text within this element. * @param defineContent a DSL-style lambda that builds the child nodes of the new element. */ fun em( selector: String? = null, key: Any? = null, accesskey: Char? = null, contenteditable: Boolean? = null, dir: EDirection? = null, draggable: Boolean? = null, hidden: Boolean? = null, lang: String? = null, spellcheck: Boolean? = null, style: String? = null, tabindex: Int? = null, title: String? = null, translate: Boolean? = null, defineContent: KatydidPhrasingContentBuilder<Msg>.() -> Unit ) /** * Adds an `<i>` element with its attributes as the next child of the element under construction. * @param selector the "selector" for the element, e.g. "#myid.my-class.my-other-class". * @param key a non-DOM key for this Katydid element that is unique among all the siblings of this element. * @param accesskey a string specifying the HTML accesskey value. * @param contenteditable whether the element has editable content. * @param dir the left-to-right direction of text inside this element. * @param draggable controls whether or not the element is draggable. * @param hidden true if the element is to be hidden. * @param lang the language of text within this element. * @param spellcheck whether the element is subject to spell checking. * @param style a string containing CSS for this element. * @param tabindex the tab index for the element. * @param title a tool tip for the element. * @param translate whether to translate text within this element. * @param defineContent a DSL-style lambda that builds the child nodes of the new element. */ fun i( selector: String? = null, key: Any? = null, accesskey: Char? = null, contenteditable: Boolean? = null, dir: EDirection? = null, draggable: Boolean? = null, hidden: Boolean? = null, lang: String? = null, spellcheck: Boolean? = null, style: String? = null, tabindex: Int? = null, title: String? = null, translate: Boolean? = null, defineContent: KatydidPhrasingContentBuilder<Msg>.() -> Unit ) /** * Adds an `<input type="button">` element with given attributes as the next child of the element under construction. * @param selector the "selector" for the element, e.g. "#myid.my-class.my-other-class". * @param key a non-DOM key for this Katydid element that is unique among all the siblings of this element. * @param accesskey a string specifying the HTML accesskey value. * @param contenteditable whether the element has editable content. * @param dir the left-to-right direction of text inside this element. * @param disabled whether this field is disabled for user interaction. * @param draggable controls whether or not the element is draggable. * @param form the ID of the form this field is part of. * @param hidden true if the element is to be hidden. * @param lang the language of text within this element. * @param name the name of this field for form submissions. * @param spellcheck whether the element is subject to spell checking. * @param style a string containing CSS for this element. * @param tabindex the tab index for the element. * @param title a tool tip for the element. * @param translate whether to translate text within this element. * @param value the field value to submit if this button is pressed. * @param defineAttributes a DSL-style lambda that adds any nonstandard attributes to the new element. */ fun inputButton( selector: String? = null, key: Any? = null, accesskey: Char? = null, contenteditable: Boolean? = null, dir: EDirection? = null, disabled: Boolean? = null, draggable: Boolean? = null, form: String? = null, hidden: Boolean? = null, lang: String? = null, name: String? = null, spellcheck: Boolean? = null, style: String? = null, tabindex: Int? = null, title: String? = null, translate: Boolean? = null, value: String? = null, defineAttributes: KatydidAttributesContentBuilder<Msg>.() -> Unit ) /** * Adds an `<input type="checkbox">` element with given attributes as the next child of the element under construction. * @param selector the "selector" for the element, e.g. "#myid.my-class.my-other-class". * @param key a non-DOM key for this Katydid element that is unique among all the siblings of this element. * @param accesskey a string specifying the HTML accesskey value. * @param autofocus true if the field is to automatically receive the keyboard focus. * @param checked true if the checkbox is checked. * @param contenteditable whether the element has editable content. * @param dir the left-to-right direction of text inside this element. * @param disabled whether this field is disabled for user interaction. * @param draggable controls whether or not the element is draggable. * @param form the ID of the form this field is part of. * @param hidden true if the element is to be hidden. * @param lang the language of text within this element. * @param name the name of this field for form submissions. * @param required true if the checkbox must be checkedfor the form to validate. * @param spellcheck whether the element is subject to spell checking. * @param style a string containing CSS for this element. * @param tabindex the tab index for the element. * @param title a tool tip for the element. * @param translate whether to translate text within this element. * @param value the value of the field when the chekbox is checked. * @param defineAttributes a DSL-style lambda that adds any nonstandard attributes to the new element. */ fun inputCheckbox( selector: String? = null, key: Any? = null, accesskey: Char? = null, autofocus: Boolean? = null, checked: Boolean? = null, contenteditable: Boolean? = null, dir: EDirection? = null, disabled: Boolean? = null, draggable: Boolean? = null, form: String? = null, hidden: Boolean? = null, lang: String? = null, name: String? = null, required: Boolean? = null, spellcheck: Boolean? = null, style: String? = null, tabindex: Int? = null, title: String? = null, translate: Boolean? = null, value: String? = null, defineAttributes: KatydidAttributesContentBuilder<Msg>.() -> Unit ) /** * Adds an `<input type="color">` element with given attributes as the next child of the element under construction. * @param selector the "selector" for the element, e.g. "#myid.my-class.my-other-class". * @param key a non-DOM key for this Katydid element that is unique among all the siblings of this element. * @param accesskey a string specifying the HTML accesskey value. * @param autocomplete a hint describing the value that can be prefilled into this field by a browser. * @param autofocus true if the field is to automatically receive keyboard focus. * @param contenteditable whether the element has editable content. * @param dir the left-to-right direction of text inside this element. * @param disabled whether this field is disabled for user interaction. * @param draggable controls whether or not the element is draggable. * @param form the ID of the form this field is part of. * @param hidden true if the element is to be hidden. * @param lang the language of text within this element. * @param list the ID of a datalist of colors. * @param name the name of this field for form submissions. * @param spellcheck whether the element is subject to spell checking. * @param style a string containing CSS for this element. * @param tabindex the tab index for the element. * @param title a tool tip for the element. * @param translate whether to translate text within this element. * @param value a valid lower case color name. * @param defineAttributes a DSL-style lambda that adds any nonstandard attributes to the new element. */ fun inputColor( selector: String? = null, key: Any? = null, accesskey: Char? = null, autocomplete: String? = null, autofocus: Boolean? = null, contenteditable: Boolean? = null, dir: EDirection? = null, disabled: Boolean? = null, draggable: Boolean? = null, form: String? = null, hidden: Boolean? = null, lang: String? = null, list: String? = null, name: String? = null, spellcheck: Boolean? = null, style: String? = null, tabindex: Int? = null, title: String? = null, translate: Boolean? = null, value: String? = null, defineAttributes: KatydidAttributesContentBuilder<Msg>.() -> Unit ) /** * Adds an `<input type="date">` element with given attributes as the next child of the element under construction. * @param selector the "selector" for the element, e.g. "#myid.my-class.my-other-class". * @param key a non-DOM key for this Katydid element that is unique among all the siblings of this element. * @param accesskey a string specifying the HTML accesskey value. * @param autocomplete a hint describing the value that can be prefilled into this field by a browser. * @param autofocus true if the field is to automatically receive keyboard focus. * @param contenteditable whether the element has editable content. * @param dir the left-to-right direction of text inside this element. * @param disabled whether this field is disabled for user interaction. * @param draggable controls whether or not the element is draggable. * @param form the ID of the form this field is part of. * @param hidden true if the element is to be hidden. * @param lang the language of text within this element. * @param list a list of values to pick from. * @param max the latest date allowed to be chosen. * @param min the earliest date allowed to be chosen. * @param name the name of this field for form submissions. * @param readonly true if the date field is displayed but not editable by the user. * @param required true if the field may not be left blank in a valid form submission. * @param spellcheck whether the element is subject to spell checking. * @param step the step value for incrementing or decrementing the date in steps. * @param style a string containing CSS for this element. * @param tabindex the tab index for the element. * @param title a tool tip for the element. * @param translate whether to translate text within this element. * @param value the value of the field. * @param defineAttributes a DSL-style lambda that adds any nonstandard attributes to the new element. */ fun inputDate( selector: String? = null, key: Any? = null, accesskey: Char? = null, autocomplete: String? = null, autofocus: Boolean? = null, contenteditable: Boolean? = null, dir: EDirection? = null, disabled: Boolean? = null, draggable: Boolean? = null, form: String? = null, hidden: Boolean? = null, lang: String? = null, list: String? = null, max: String? = null, min: String? = null, name: String? = null, readonly: Boolean? = null, required: Boolean? = null, spellcheck: Boolean? = null, step: String? = null, style: String? = null, tabindex: Int? = null, title: String? = null, translate: Boolean? = null, value: String? = null, defineAttributes: KatydidAttributesContentBuilder<Msg>.() -> Unit ) /** * Adds an `<input type="datetime-local">` element with given attributes as the next child of the element under construction. * @param selector the "selector" for the element, e.g. "#myid.my-class.my-other-class". * @param key a non-DOM key for this Katydid element that is unique among all the siblings of this element. * @param accesskey a string specifying the HTML accesskey value. * @param autocomplete a hint describing the value that can be prefilled into this field by a browser. * @param autofocus true if the field is to automatically receive keyboard focus. * @param contenteditable whether the element has editable content. * @param dir the left-to-right direction of text inside this element. * @param disabled whether this field is disabled for user interaction. * @param draggable controls whether or not the element is draggable. * @param form the ID of the form this field is part of. * @param hidden true if the element is to be hidden. * @param lang the language of text within this element. * @param list a list of values to pick from. * @param max the latest date allowed to be chosen. * @param min the earliest date allowed to be chosen. * @param name the name of this field for form submissions. * @param readonly true if the date field is displayed but not editable by the user. * @param required true if the field may not be left blank in a valid form submission. * @param spellcheck whether the element is subject to spell checking. * @param step the step value for incrementing or decrementing the date in steps. * @param style a string containing CSS for this element. * @param tabindex the tab index for the element. * @param title a tool tip for the element. * @param translate whether to translate text within this element. * @param value the value of the field. * @param defineAttributes a DSL-style lambda that adds any nonstandard attributes to the new element. */ fun inputDateTimeLocal( selector: String? = null, key: Any? = null, accesskey: Char? = null, autocomplete: String? = null, autofocus: Boolean? = null, contenteditable: Boolean? = null, dir: EDirection? = null, disabled: Boolean? = null, draggable: Boolean? = null, form: String? = null, hidden: Boolean? = null, lang: String? = null, list: String? = null, max: String? = null, min: String? = null, name: String? = null, readonly: Boolean? = null, required: Boolean? = null, spellcheck: Boolean? = null, step: String? = null, style: String? = null, tabindex: Int? = null, title: String? = null, translate: Boolean? = null, value: String? = null, defineAttributes: KatydidAttributesContentBuilder<Msg>.() -> Unit ) /** * Adds an input type="email" element with given attributes as the next child of the element under construction. * @param selector the "selector" for the element, e.g. "#myid.my-class.my-other-class". * @param key a non-DOM key for this Katydid element that is unique among all the siblings of this element. * @param accesskey a string specifying the HTML accesskey value. * @param autocomplete a hint describing the value that can be prefilled into this field by a browser. * @param autofocus true if the field is to automatically receive keyboard focus. * @param contenteditable whether the element has editable content. * @param dir the left-to-right direction of text inside this element. * @param disabled whether this field is disabled for user interaction. * @param draggable controls whether or not the element is draggable. * @param form the ID of the form this field is part of. * @param hidden true if the element is to be hidden. * @param lang the language of text within this element. * @param name the name of this field for form submissions. * @param spellcheck whether the element is subject to spell checking. * @param style a string containing CSS for this element. * @param tabindex the tab index for the element. * @param title a tool tip for the element. * @param translate whether to translate text within this element. * @param defineAttributes a DSL-style lambda that adds any nonstandard attributes to the new element. */ fun inputEmail( selector: String? = null, key: Any? = null, accesskey: Char? = null, autocomplete: String? = null, autofocus: Boolean? = null, contenteditable: Boolean? = null, dir: EDirection? = null, disabled: Boolean? = null, draggable: Boolean? = null, form: String? = null, hidden: Boolean? = null, lang: String? = null, list: String? = null, maxlength: Int? = null, minlength: Int? = null, multiple: Boolean? = null, name: String? = null, pattern: String? = null, placeholder: String? = null, readonly: Boolean? = null, required: Boolean? = null, size: Int? = null, spellcheck: Boolean? = null, style: String? = null, tabindex: Int? = null, title: String? = null, translate: Boolean? = null, value: String? = null, defineAttributes: KatydidAttributesContentBuilder<Msg>.() -> Unit ) /** * Adds an `<input type="file">` element with given attributes as the next child of the element under construction. * @param selector the "selector" for the element, e.g. "#myid.my-class.my-other-class". * @param key a non-DOM key for this Katydid element that is unique among all the siblings of this element. * @param accept a string describing the type of files that can be uploaded. * @param accesskey a string specifying the HTML accesskey value. * @param autofocus true if the field is to automatically receive keyboard focus. * @param contenteditable whether the element has editable content. * @param dir the left-to-right direction of text inside this element. * @param disabled whether this field is disabled for user interaction. * @param draggable controls whether or not the element is draggable. * @param form the ID of the form this field is part of. * @param hidden true if the element is to be hidden. * @param lang the language of text within this element. * @param multiple true to allow multiple files to be uploaded; otherwise only one file can be uploaded. * @param name the name of this field for form submissions. * @param required true to indicate that a file must be uploaded for the form to validate. * @param spellcheck whether the element is subject to spell checking. * @param style a string containing CSS for this element. * @param tabindex the tab index for the element. * @param title a tool tip for the element. * @param translate whether to translate text within this element. * @param value the file name that has been uplaoded. * @param defineAttributes a DSL-style lambda that adds any nonstandard attributes to the new element. */ fun inputFile( selector: String? = null, key: Any? = null, accept: String? = null, accesskey: Char? = null, autofocus: Boolean? = null, contenteditable: Boolean? = null, dir: EDirection? = null, disabled: Boolean? = null, draggable: Boolean? = null, form: String? = null, hidden: Boolean? = null, lang: String? = null, multiple: Boolean? = null, name: String? = null, required: Boolean? = null, spellcheck: Boolean? = null, style: String? = null, tabindex: Int? = null, title: String? = null, translate: Boolean? = null, value: String? = null, defineAttributes: KatydidAttributesContentBuilder<Msg>.() -> Unit ) /** * Adds an `<input type="hidden">` element with given attributes as the next child of the element under construction. * @param selector the "selector" for the element, e.g. "#myid.my-class.my-other-class". * @param key a non-DOM key for this Katydid element that is unique among all the siblings of this element. * @param accesskey a string specifying the HTML accesskey value. * @param contenteditable whether the element has editable content. * @param dir the left-to-right direction of text inside this element. * @param disabled whether this field is disabled for user interaction. * @param draggable controls whether or not the element is draggable. * @param form the ID of the form this field is part of. * @param hidden true if the element is to be hidden. * @param lang the language of text within this element. * @param name the name of this field for form submissions. * @param spellcheck whether the element is subject to spell checking. * @param style a string containing CSS for this element. * @param tabindex the tab index for the element. * @param title a tool tip for the element. * @param translate whether to translate text within this element. * @param value the value of the hidden field. * @param defineAttributes a DSL-style lambda that adds any nonstandard attributes to the new element. */ fun inputHidden( selector: String? = null, key: Any? = null, accesskey: Char? = null, contenteditable: Boolean? = null, dir: EDirection? = null, disabled: Boolean? = null, draggable: Boolean? = null, form: String? = null, hidden: Boolean? = null, lang: String? = null, name: String? = null, spellcheck: Boolean? = null, style: String? = null, tabindex: Int? = null, title: String? = null, translate: Boolean? = null, value: String? = null, defineAttributes: KatydidAttributesContentBuilder<Msg>.() -> Unit ) /** * Adds an `<input type="image">` element with given attributes as the next child of the element under construction. * @param selector the "selector" for the element, e.g. "#myid.my-class.my-other-class". * @param key a non-DOM key for this Katydid element that is unique among all the siblings of this element. * @param accesskey a string specifying the HTML accesskey value. * @param alt text to be displayed as an alternative to the image. * @param contenteditable whether the element has editable content. * @param dir the left-to-right direction of text inside this element. * @param disabled whether this field is disabled for user interaction. * @param draggable controls whether or not the element is draggable. * @param form the ID of the form this field is part of. * @param formaction the URL to use for form submission. * @param formenctype the encoding type to be used for form data submitted by this button. * @param formmethod the choice of GET or POST for submitting the form's data. * @param formnovalidate true to skip form field validation when this button is clicked. * @param formtarget the target window (browser context) for form submission * @param height the height of the image in pixels. * @param hidden true if the element is to be hidden. * @param lang the language of text within this element. * @param name the name of this field for form submissions. * @param spellcheck whether the element is subject to spell checking. * @param src a URL from which to retrieve the image. * @param style a string containing CSS for this element. * @param tabindex the tab index for the element. * @param title a tool tip for the element. * @param translate whether to translate text within this element. * @param defineAttributes a DSL-style lambda that adds any nonstandard attributes to the new element. */ fun inputImageButton( selector: String? = null, key: Any? = null, accesskey: Char? = null, alt: String? = null, contenteditable: Boolean? = null, dir: EDirection? = null, disabled: Boolean? = null, draggable: Boolean? = null, form: String? = null, formaction: String? = null, formenctype: EFormEncodingType? = null, formmethod: EFormSubmissionMethod? = null, formnovalidate: Boolean? = null, formtarget: String? = null, height: Int? = null, hidden: Boolean? = null, lang: String? = null, name: String? = null, spellcheck: Boolean? = null, src: String, style: String? = null, tabindex: Int? = null, title: String? = null, translate: Boolean? = null, width: Int? = null, defineAttributes: KatydidAttributesContentBuilder<Msg>.() -> Unit ) /** * Adds an `<input type="month">` element with given attributes as the next child of the element under construction. * @param selector the "selector" for the element, e.g. "#myid.my-class.my-other-class". * @param key a non-DOM key for this Katydid element that is unique among all the siblings of this element. * @param accesskey a string specifying the HTML accesskey value. * @param autocomplete a hint describing the value that can be prefilled into this field by a browser. * @param autofocus true if the field is to automatically receive keyboard focus. * @param contenteditable whether the element has editable content. * @param dir the left-to-right direction of text inside this element. * @param disabled whether this field is disabled for user interaction. * @param draggable controls whether or not the element is draggable. * @param form the ID of the form this field is part of. * @param hidden true if the element is to be hidden. * @param lang the language of text within this element. * @param list a list of values to pick from. * @param max the latest month allowed to be chosen. * @param min the earliest month allowed to be chosen. * @param name the name of this field for form submissions. * @param readonly true if the month field is displayed but not editable by the user. * @param required true if the field may not be left blank in a valid form submission. * @param spellcheck whether the element is subject to spell checking. * @param step the step value for incrementing or decrementing the date in steps. * @param style a string containing CSS for this element. * @param tabindex the tab index for the element. * @param title a tool tip for the element. * @param translate whether to translate text within this element. * @param value the value for this field. * @param defineAttributes a DSL-style lambda that adds any nonstandard attributes to the new element. */ fun inputMonth( selector: String? = null, key: Any? = null, accesskey: Char? = null, autocomplete: String? = null, autofocus: Boolean? = null, contenteditable: Boolean? = null, dir: EDirection? = null, disabled: Boolean? = null, draggable: Boolean? = null, form: String? = null, hidden: Boolean? = null, lang: String? = null, list: String? = null, max: String? = null, min: String? = null, name: String? = null, readonly: Boolean? = null, required: Boolean? = null, spellcheck: Boolean? = null, step: String? = null, style: String? = null, tabindex: Int? = null, title: String? = null, translate: Boolean? = null, value: String? = null, defineAttributes: KatydidAttributesContentBuilder<Msg>.() -> Unit ) /** * Adds an `<input type="number">` element with given attributes as the next child of the element under construction. * @param selector the "selector" for the element, e.g. "#myid.my-class.my-other-class". * @param key a non-DOM key for this Katydid element that is unique among all the siblings of this element. * @param accesskey a string specifying the HTML accesskey value. * @param autocomplete a hint describing the value that can be prefilled into this field by a browser. * @param autofocus true if the field is to automatically receive keyboard focus. * @param contenteditable whether the element has editable content. * @param dir the left-to-right direction of text inside this element. * @param disabled whether this field is disabled for user interaction. * @param draggable controls whether or not the element is draggable. * @param form the ID of the form this field is part of. * @param hidden true if the element is to be hidden. * @param lang the language of text within this element. * @param list a list of values to pick from. * @param max the largest number allowed to be chosen. * @param min the smallest number allowed to be chosen. * @param name the name of this field for form submissions. * @param placeholder text to show in the field when it has no user-entered value. * @param readonly true if the field is displayed but not editable by the user. * @param required true if the field may not be left blank in a valid form submission. * @param spellcheck whether the element is subject to spell checking. * @param step the increment or decrement to apply to the value when editing it in steps. * @param style a string containing CSS for this element. * @param tabindex the tab index for the element. * @param title a tool tip for the element. * @param translate whether to translate text within this element. * @param value the value of the field. * @param defineAttributes a DSL-style lambda that adds any nonstandard attributes to the new element. */ fun inputNumber( selector: String? = null, key: Any? = null, accesskey: Char? = null, autocomplete: String? = null, autofocus: Boolean? = null, contenteditable: Boolean? = null, dir: EDirection? = null, disabled: Boolean? = null, draggable: Boolean? = null, form: String? = null, hidden: Boolean? = null, lang: String? = null, list: String? = null, max: Double? = null, min: Double? = null, name: String? = null, placeholder: String? = null, readonly: Boolean? = null, required: Boolean? = null, spellcheck: Boolean? = null, step: Double? = null, style: String? = null, tabindex: Int? = null, title: String? = null, translate: Boolean? = null, value: Double? = null, defineAttributes: KatydidAttributesContentBuilder<Msg>.() -> Unit ) /** * Adds an `<input type="number">` element with given attributes as the next child of the element under construction. * @param selector the "selector" for the element, e.g. "#myid.my-class.my-other-class". * @param key a non-DOM key for this Katydid element that is unique among all the siblings of this element. * @param accesskey a string specifying the HTML accesskey value. * @param autocomplete a hint describing the value that can be prefilled into this field by a browser. * @param autofocus true if the field is to automatically receive keyboard focus. * @param contenteditable whether the element has editable content. * @param dir the left-to-right direction of text inside this element. * @param disabled whether this field is disabled for user interaction. * @param draggable controls whether or not the element is draggable. * @param form the ID of the form this field is part of. * @param hidden true if the element is to be hidden. * @param lang the language of text within this element. * @param list a list of values to pick from. * @param max the largest number allowed to be chosen. * @param min the smallest number allowed to be chosen. * @param name the name of this field for form submissions. * @param placeholder text to show in the field when it has no user-entered value. * @param readonly true if the field is displayed but not editable by the user. * @param required true if the field may not be left blank in a valid form submission. * @param spellcheck whether the element is subject to spell checking. * @param step the increment or decrement to apply to the value when editing it in steps. * @param style a string containing CSS for this element. * @param tabindex the tab index for the element. * @param title a tool tip for the element. * @param translate whether to translate text within this element. * @param value the value of the field. * @param defineAttributes a DSL-style lambda that adds any nonstandard attributes to the new element. */ fun inputNumber( selector: String? = null, key: Any? = null, accesskey: Char? = null, autocomplete: String? = null, autofocus: Boolean? = null, contenteditable: Boolean? = null, dir: EDirection? = null, disabled: Boolean? = null, draggable: Boolean? = null, form: String? = null, hidden: Boolean? = null, lang: String? = null, list: String? = null, max: Int? = null, min: Int? = null, name: String? = null, placeholder: String? = null, readonly: Boolean? = null, required: Boolean? = null, spellcheck: Boolean? = null, step: Int? = null, style: String? = null, tabindex: Int? = null, title: String? = null, translate: Boolean? = null, value: Int? = null, defineAttributes: KatydidAttributesContentBuilder<Msg>.() -> Unit ) /** * Adds an `<input type="password">` element with given attributes as the next child of the element under construction. * @param selector the "selector" for the element, e.g. "#myid.my-class.my-other-class". * @param key a non-DOM key for this Katydid element that is unique among all the siblings of this element. * @param accesskey a string specifying the HTML accesskey value. * @param autocomplete a hint describing the value that can be prefilled into this field by a browser. * @param autofocus true if the field is to automatically receive keyboard focus. * @param contenteditable whether the element has editable content. * @param dir the left-to-right direction of text inside this element. * @param disabled whether this field is disabled for user interaction. * @param draggable controls whether or not the element is draggable. * @param form the ID of the form this field is part of. * @param hidden true if the element is to be hidden. * @param lang the language of text within this element. * @param maxlength the maximum length of text that may be entered for the form to validate. * @param minlength the minimum length of text that must be entered for the form to validate. * @param name the name of this field for form submissions. * @param pattern a regular expression for validating this field. * @param placeholder text to display in the field when its value is empty. * @param readonly true if the field is displayed but may not be edited by a user. * @param required true if the filed must have a value for the form to validate. * @param size the number of visible characters in the field. * @param spellcheck whether the element is subject to spell checking. * @param style a string containing CSS for this element. * @param tabindex the tab index for the element. * @param title a tool tip for the element. * @param translate whether to translate text within this element. * @param value the value of the field. * @param defineAttributes a DSL-style lambda that adds any nonstandard attributes to the new element. */ fun inputPassword( selector: String? = null, key: Any? = null, accesskey: Char? = null, autocomplete: String? = null, autofocus: Boolean? = null, contenteditable: Boolean? = null, dir: EDirection? = null, disabled: Boolean? = null, draggable: Boolean? = null, form: String? = null, hidden: Boolean? = null, lang: String? = null, maxlength: Int? = null, minlength: Int? = null, name: String? = null, pattern: String? = null, placeholder: String? = null, readonly: Boolean? = null, required: Boolean? = null, size: Int? = null, spellcheck: Boolean? = null, style: String? = null, tabindex: Int? = null, title: String? = null, translate: Boolean? = null, value: String? = null, defineAttributes: KatydidAttributesContentBuilder<Msg>.() -> Unit ) /** * Adds an `<input type="radio">` element with given attributes as the next child of the element under construction. * @param selector the "selector" for the element, e.g. "#myid.my-class.my-other-class". * @param key a non-DOM key for this Katydid element that is unique among all the siblings of this element. * @param accesskey a string specifying the HTML accesskey value. * @param autofocus true if the field is to automatically receive keyboard focus. * @param checked whether the button is checked. * @param contenteditable whether the element has editable content. * @param dir the left-to-right direction of text inside this element. * @param disabled whether this field is disabled for user interaction. * @param draggable controls whether or not the element is draggable. * @param form the ID of the form this field is part of. * @param hidden true if the element is to be hidden. * @param lang the language of text within this element. * @param name the name of this field for form submissions. * @param required true if the radio button group must have one button checked for valid form submission. * @param spellcheck whether the element is subject to spell checking. * @param style a string containing CSS for this element. * @param tabindex the tab index for the element. * @param title a tool tip for the element. * @param translate whether to translate text within this element. * @param defineAttributes a DSL-style lambda that adds any nonstandard attributes to the new element. */ fun inputRadioButton( selector: String? = null, key: Any? = null, accesskey: Char? = null, autofocus: Boolean? = null, checked: Boolean? = null, contenteditable: Boolean? = null, dir: EDirection? = null, disabled: Boolean? = null, draggable: Boolean? = null, form: String? = null, hidden: Boolean? = null, lang: String? = null, name: String? = null, required: Boolean? = null, spellcheck: Boolean? = null, style: String? = null, tabindex: Int? = null, title: String? = null, translate: Boolean? = null, value: String? = null, defineAttributes: KatydidAttributesContentBuilder<Msg>.() -> Unit ) /** * Adds an `<input type="range">` element with given attributes as the next child of the element under construction. * @param selector the "selector" for the element, e.g. "#myid.my-class.my-other-class". * @param key a non-DOM key for this Katydid element that is unique among all the siblings of this element. * @param accesskey a string specifying the HTML accesskey value. * @param autocomplete a hint describing the value that can be prefilled into this field by a browser. * @param autofocus true if the field is to automatically receive keyboard focus. * @param contenteditable whether the element has editable content. * @param dir the left-to-right direction of text inside this element. * @param disabled whether this field is disabled for user interaction. * @param draggable controls whether or not the element is draggable. * @param form the ID of the form this field is part of. * @param hidden true if the element is to be hidden. * @param lang the language of text within this element. * @param list a list of labeled values for the range. * @param max the maximum value for the range. * @param min the minimum value for the range. * @param name the name of this field for form submissions. * @param spellcheck whether the element is subject to spell checking. * @param step the increment for stepping the ranged value. * @param style a string containing CSS for this element. * @param tabindex the tab index for the element. * @param title a tool tip for the element. * @param translate whether to translate text within this element. * @param value the current value for the range field. * @param defineAttributes a DSL-style lambda that adds any nonstandard attributes to the new element. */ fun <T : Number> inputRange( selector: String? = null, key: Any? = null, accesskey: Char? = null, autocomplete: String? = null, autofocus: Boolean? = null, contenteditable: Boolean? = null, dir: EDirection? = null, disabled: Boolean? = null, draggable: Boolean? = null, form: String? = null, hidden: Boolean? = null, lang: String? = null, list: String? = null, max: T? = null, min: T? = null, name: String? = null, spellcheck: Boolean? = null, step: String? = null, style: String? = null, tabindex: Int? = null, title: String? = null, translate: Boolean? = null, value: T? = null, defineAttributes: KatydidAttributesContentBuilder<Msg>.() -> Unit ) /** * Adds an `<input type="reset">` element with given attributes as the next child of the element under construction. * @param selector the "selector" for the element, e.g. "#myid.my-class.my-other-class". * @param key a non-DOM key for this Katydid element that is unique among all the siblings of this element. * @param accesskey a string specifying the HTML accesskey value. * @param contenteditable whether the element has editable content. * @param dir the left-to-right direction of text inside this element. * @param disabled whether this field is disabled for user interaction. * @param draggable controls whether or not the element is draggable. * @param form the ID of the form this field is part of. * @param hidden true if the element is to be hidden. * @param lang the language of text within this element. * @param name the name of this field for form submissions. * @param spellcheck whether the element is subject to spell checking. * @param style a string containing CSS for this element. * @param tabindex the tab index for the element. * @param title a tool tip for the element. * @param translate whether to translate text within this element. * @param value the label to show on the button. * @param defineAttributes a DSL-style lambda that adds any nonstandard attributes to the new element. */ fun inputResetButton( selector: String? = null, key: Any? = null, accesskey: Char? = null, contenteditable: Boolean? = null, dir: EDirection? = null, disabled: Boolean? = null, draggable: Boolean? = null, form: String? = null, hidden: Boolean? = null, lang: String? = null, name: String? = null, spellcheck: Boolean? = null, style: String? = null, tabindex: Int? = null, title: String? = null, translate: Boolean? = null, value: String? = null, defineAttributes: KatydidAttributesContentBuilder<Msg>.() -> Unit ) /** * Adds an `<input type="search">` element with given attributes as the next child of the element under construction. * @param selector the "selector" for the element, e.g. "#myid.my-class.my-other-class". * @param key a non-DOM key for this Katydid element that is unique among all the siblings of this element. * @param accesskey a string specifying the HTML accesskey value. * @param autocomplete a hint describing the value that can be prefilled into this field by a browser. * @param autofocus true if the field is to automatically receive keyboard focus. * @param contenteditable whether the element has editable content. * @param dir the left-to-right direction of text inside this element. * @param dirname the name of a parameter holding the directionality when submitting the form. * @param disabled whether this field is disabled for user interaction. * @param draggable controls whether or not the element is draggable. * @param form the ID of the form this field is part of. * @param hidden true if the element is to be hidden. * @param lang the language of text within this element. * @param list a list of labeled values for the search field. * @param maxlength the maximum length of text that may be entered for the form to validate. * @param minlength the minimum length of text that must be entered for the form to validate. * @param name the name of this field for form submissions. * @param pattern a regular expression for validating this field. * @param placeholder text to display in the field when its value is empty. * @param readonly true if the field is displayed but may not be edited by a user. * @param required true if the filed must have a value for the form to validate. * @param size the number of visible characters in the field. * @param spellcheck whether the element is subject to spell checking. * @param style a string containing CSS for this element. * @param tabindex the tab index for the element. * @param title a tool tip for the element. * @param translate whether to translate text within this element. * @param value the value of the field. * @param defineAttributes a DSL-style lambda that adds any nonstandard attributes to the new element. */ fun inputSearch( selector: String? = null, key: Any? = null, accesskey: Char? = null, autocomplete: String? = null, autofocus: Boolean? = null, contenteditable: Boolean? = null, dir: EDirection? = null, dirname: String? = null, disabled: Boolean? = null, draggable: Boolean? = null, form: String? = null, hidden: Boolean? = null, lang: String? = null, list: String? = null, maxlength: Int? = null, minlength: Int? = null, name: String? = null, pattern: String? = null, placeholder: String? = null, readonly: Boolean? = null, required: Boolean? = null, size: Int? = null, spellcheck: Boolean? = null, style: String? = null, tabindex: Int? = null, title: String? = null, translate: Boolean? = null, value: String? = null, defineAttributes: KatydidAttributesContentBuilder<Msg>.() -> Unit ) /** * Adds an `<input type="submit">` element with given attributes as the next child of the element under construction. * @param selector the "selector" for the element, e.g. "#myid.my-class.my-other-class". * @param key a non-DOM key for this Katydid element that is unique among all the siblings of this element. * @param accesskey a string specifying the HTML accesskey value. * @param contenteditable whether the element has editable content. * @param dir the left-to-right direction of text inside this element. * @param disabled whether this field is disabled for user interaction. * @param draggable controls whether or not the element is draggable. * @param form the ID of the form this field is part of. * @param formaction the URL to use for form submission. * @param formenctype the encoding type to be used for form data submitted by this button. * @param formmethod the choice of GET or POST for submitting the form's data. * @param formnovalidate true to skip form field validation when this button is clicked. * @param formtarget the target window (browser context) for form submission * @param hidden true if the element is to be hidden. * @param lang the language of text within this element. * @param name the name of this field for form submissions. * @param spellcheck whether the element is subject to spell checking. * @param style a string containing CSS for this element. * @param tabindex the tab index for the element. * @param title a tool tip for the element. * @param translate whether to translate text within this element. * @param value the value of the field corresponding to the button when the form is submitted. * @param defineAttributes a DSL-style lambda that adds any nonstandard attributes to the new element. */ fun inputSubmitButton( selector: String? = null, key: Any? = null, accesskey: Char? = null, contenteditable: Boolean? = null, dir: EDirection? = null, disabled: Boolean? = null, draggable: Boolean? = null, form: String? = null, formaction: String? = null, formenctype: EFormEncodingType? = null, formmethod: EFormSubmissionMethod? = null, formnovalidate: Boolean? = null, formtarget: String? = null, hidden: Boolean? = null, lang: String? = null, name: String? = null, spellcheck: Boolean? = null, style: String? = null, tabindex: Int? = null, title: String? = null, translate: Boolean? = null, value: String? = null, defineAttributes: KatydidAttributesContentBuilder<Msg>.() -> Unit ) /** * Adds an `<input type="tel">` element with given attributes as the next child of the element under construction. * @param selector the "selector" for the element, e.g. "#myid.my-class.my-other-class". * @param key a non-DOM key for this Katydid element that is unique among all the siblings of this element. * @param accesskey a string specifying the HTML accesskey value. * @param autocomplete a hint describing the value that can be prefilled into this field by a browser. * @param autofocus true if the field is to automatically receive keyboard focus. * @param contenteditable whether the element has editable content. * @param dir the left-to-right direction of text inside this element. * @param disabled whether this field is disabled for user interaction. * @param draggable controls whether or not the element is draggable. * @param form the ID of the form this field is part of. * @param hidden true if the element is to be hidden. * @param lang the language of text within this element. * @param list a list of labeled values for the field. * @param maxlength the maximum length of text that may be entered for the form to validate. * @param minlength the minimum length of text that must be entered for the form to validate. * @param name the name of this field for form submissions. * @param pattern a regular expression for validating this field. * @param placeholder text to display in the field when its value is empty. * @param readonly true if the field is displayed but may not be edited by a user. * @param required true if the filed must have a value for the form to validate. * @param size the number of visible characters in the field. * @param spellcheck whether the element is subject to spell checking. * @param style a string containing CSS for this element. * @param tabindex the tab index for the element. * @param title a tool tip for the element. * @param translate whether to translate text within this element. * @param value the value of this field. * @param defineAttributes a DSL-style lambda that adds any nonstandard attributes to the new element. */ fun inputTelephone( selector: String? = null, key: Any? = null, accesskey: Char? = null, autocomplete: String? = null, autofocus: Boolean? = null, contenteditable: Boolean? = null, dir: EDirection? = null, disabled: Boolean? = null, draggable: Boolean? = null, form: String? = null, hidden: Boolean? = null, lang: String? = null, list: String? = null, maxlength: Int? = null, minlength: Int? = null, name: String? = null, pattern: String? = null, placeholder: String? = null, readonly: Boolean? = null, required: Boolean? = null, size: Int? = null, spellcheck: Boolean? = null, style: String? = null, tabindex: Int? = null, title: String? = null, translate: Boolean? = null, value: String? = null, defineAttributes: KatydidAttributesContentBuilder<Msg>.() -> Unit ) /** * Adds an `<input type="text"> element with given attributes as the next child of the element under construction. * @param selector the "selector" for the element, e.g. "#myid.my-class.my-other-class". * @param key a non-DOM key for this Katydid element that is unique among all the siblings of this element. * @param accesskey a string specifying the HTML accesskey value. * @param autocomplete a hint describing the value that can be prefilled into this field by a browser. * @param autofocus true if the field is to automatically receive keyboard focus. * @param contenteditable whether the element has editable content. * @param dir the left-to-right direction of text inside this element. * @param dirname the name of a parameter holding the directionality when submitting the form. * @param disabled whether this field is disabled for user interaction. * @param draggable controls whether or not the element is draggable. * @param form the ID of the form this field is part of. * @param hidden true if the element is to be hidden. * @param lang the language of text within this element. * @param list a list of labeled values for the field. * @param maxlength the maximum length of text that may be entered for the form to validate. * @param minlength the minimum length of text that must be entered for the form to validate. * @param name the name of this field for form submissions. * @param pattern a regular expression for validating this field. * @param placeholder text to display in the field when its value is empty. * @param readonly true if the field is displayed but may not be edited by a user. * @param required true if the filed must have a value for the form to validate. * @param size the number of visible characters in the field. * @param spellcheck whether the element is subject to spell checking. * @param style a string containing CSS for this element. * @param tabindex the tab index for the element. * @param title a tool tip for the element. * @param translate whether to translate text within this element. * @param value the current value of the field. * @param defineAttributes a DSL-style lambda that adds any nonstandard attributes to the new element. */ fun inputText( selector: String? = null, key: Any? = null, accesskey: Char? = null, autocomplete: String? = null, autofocus: Boolean? = null, contenteditable: Boolean? = null, dir: EDirection? = null, dirname: String? = null, disabled: Boolean? = null, draggable: Boolean? = null, form: String? = null, hidden: Boolean? = null, lang: String? = null, list: String? = null, maxlength: Int? = null, minlength: Int? = null, name: String? = null, pattern: String? = null, placeholder: String? = null, readonly: Boolean? = null, required: Boolean? = null, size: Int? = null, spellcheck: Boolean? = null, style: String? = null, tabindex: Int? = null, title: String? = null, translate: Boolean? = null, value: String? = null, defineAttributes: KatydidAttributesContentBuilder<Msg>.() -> Unit ) /** * Adds an input type="time" element with given attributes as the next child of the element under construction. * @param selector the "selector" for the element, e.g. "#myid.my-class.my-other-class". * @param key a non-DOM key for this Katydid element that is unique among all the siblings of this element. * @param accesskey a string specifying the HTML accesskey value. * @param autocomplete a hint describing the value that can be prefilled into this field by a browser. * @param autofocus true if the field is to automatically receive keyboard focus. * @param contenteditable whether the element has editable content. * @param dir the left-to-right direction of text inside this element. * @param disabled whether this field is disabled for user interaction. * @param draggable controls whether or not the element is draggable. * @param form the ID of the form this field is part of. * @param hidden true if the element is to be hidden. * @param lang the language of text within this element. * @param list a list of labeled values for the field. * @param max the maximum value for the field. * @param min the minimum value for the field. * @param name the name of this field for form submissions. * @param readonly true if the field is displayed but may not be edited by a user. * @param required true if the filed must have a value for the form to validate. * @param spellcheck whether the element is subject to spell checking. * @param step the number of seconds to increment or decrement the time with a stepping UI. * @param style a string containing CSS for this element. * @param tabindex the tab index for the element. * @param title a tool tip for the element. * @param translate whether to translate text within this element. * @param value the current value of the field. * @param defineAttributes a DSL-style lambda that adds any nonstandard attributes to the new element. */ fun inputTime( selector: String? = null, key: Any? = null, accesskey: Char? = null, autocomplete: String? = null, autofocus: Boolean? = null, contenteditable: Boolean? = null, dir: EDirection? = null, disabled: Boolean? = null, draggable: Boolean? = null, form: String? = null, hidden: Boolean? = null, lang: String? = null, list: String? = null, max: String? = null, min: String? = null, name: String? = null, readonly: Boolean? = null, required: Boolean? = null, spellcheck: Boolean? = null, step: String? = null, style: String? = null, tabindex: Int? = null, title: String? = null, translate: Boolean? = null, value: KatyTime? = null, defineAttributes: KatydidAttributesContentBuilder<Msg>.() -> Unit ) /** * Adds an input type="url" element with given attributes as the next child of the element under construction. * @param selector the "selector" for the element, e.g. "#myid.my-class.my-other-class". * @param key a non-DOM key for this Katydid element that is unique among all the siblings of this element. * @param accesskey a string specifying the HTML accesskey value. * @param autocomplete a hint describing the value that can be prefilled into this field by a browser. * @param autofocus true if the field is to automatically receive keyboard focus. * @param contenteditable whether the element has editable content. * @param dir the left-to-right direction of text inside this element. * @param disabled whether this field is disabled for user interaction. * @param draggable controls whether or not the element is draggable. * @param form the ID of the form this field is part of. * @param hidden true if the element is to be hidden. * @param lang the language of text within this element. * @param name the name of this field for form submissions. * @param spellcheck whether the element is subject to spell checking. * @param style a string containing CSS for this element. * @param tabindex the tab index for the element. * @param title a tool tip for the element. * @param translate whether to translate text within this element. * @param defineAttributes a DSL-style lambda that adds any nonstandard attributes to the new element. */ fun inputUrl( selector: String? = null, key: Any? = null, accesskey: Char? = null, autocomplete: String? = null, autofocus: Boolean? = null, contenteditable: Boolean? = null, dir: EDirection? = null, disabled: Boolean? = null, draggable: Boolean? = null, form: String? = null, hidden: Boolean? = null, lang: String? = null, list: String? = null, maxlength: Int? = null, minlength: Int? = null, name: String? = null, pattern: String? = null, placeholder: String? = null, readonly: Boolean? = null, required: Boolean? = null, size: Int? = null, spellcheck: Boolean? = null, style: String? = null, tabindex: Int? = null, title: String? = null, translate: Boolean? = null, value: String? = null, defineAttributes: KatydidAttributesContentBuilder<Msg>.() -> Unit ) /** * Adds an input type="week" element with given attributes as the next child of the element under construction. * @param selector the "selector" for the element, e.g. "#myid.my-class.my-other-class". * @param key a non-DOM key for this Katydid element that is unique among all the siblings of this element. * @param accesskey a string specifying the HTML accesskey value. * @param autocomplete a hint describing the value that can be prefilled into this field by a browser. * @param autofocus true if the field is to automatically receive keyboard focus. * @param contenteditable whether the element has editable content. * @param dir the left-to-right direction of text inside this element. * @param disabled whether this field is disabled for user interaction. * @param draggable controls whether or not the element is draggable. * @param form the ID of the form this field is part of. * @param hidden true if the element is to be hidden. * @param lang the language of text within this element. * @param name the name of this field for form submissions. * @param spellcheck whether the element is subject to spell checking. * @param style a string containing CSS for this element. * @param tabindex the tab index for the element. * @param title a tool tip for the element. * @param translate whether to translate text within this element. * @param defineAttributes a DSL-style lambda that adds any nonstandard attributes to the new element. */ fun inputWeek( selector: String? = null, key: Any? = null, accesskey: Char? = null, autocomplete: String? = null, autofocus: Boolean? = null, contenteditable: Boolean? = null, dir: EDirection? = null, disabled: Boolean? = null, draggable: Boolean? = null, form: String? = null, hidden: Boolean? = null, lang: String? = null, list: String? = null, max: String? = null, min: String? = null, name: String? = null, readonly: Boolean? = null, required: Boolean? = null, spellcheck: Boolean? = null, step: String? = null, style: String? = null, tabindex: Int? = null, title: String? = null, translate: Boolean? = null, value: String? = null, defineAttributes: KatydidAttributesContentBuilder<Msg>.() -> Unit ) /** * Adds an `<ins>` element with its attributes as the next child of the element under construction. * @param selector the "selector" for the element, e.g. "#myid.my-class.my-other-class". * @param key a non-DOM key for this Katydid element that is unique among all the siblings of this element. * @param accesskey a string specifying the HTML accesskey value. * @param cite a URL describing the change. * @param contenteditable whether the element has editable content. * @param datetime when the edit was made. * @param dir the left-to-right direction of text inside this element. * @param draggable controls whether or not the element is draggable. * @param hidden true if the element is to be hidden. * @param lang the language of text within this element. * @param spellcheck whether the element is subject to spell checking. * @param style a string containing CSS for this element. * @param tabindex the tab index for the element. * @param title a tool tip for the element. * @param translate whether to translate text within this element. * @param defineContent a DSL-style lambda that builds the child nodes of the new element. */ fun ins( selector: String? = null, key: Any? = null, accesskey: Char? = null, cite: String? = null, contenteditable: Boolean? = null, datetime: KatyDateTime? = null, dir: EDirection? = null, draggable: Boolean? = null, hidden: Boolean? = null, lang: String? = null, spellcheck: Boolean? = null, style: String? = null, tabindex: Int? = null, title: String? = null, translate: Boolean? = null, defineContent: KatydidPhrasingContentBuilder<Msg>.() -> Unit ) /** * Adds a kbd element with its attributes as the next child of the element under construction. * @param selector the "selector" for the element, e.g. "#myid.my-class.my-other-class". * @param key a non-DOM key for this Katydid element that is unique among all the siblings of this element. * @param accesskey a string specifying the HTML accesskey value. * @param contenteditable whether the element has editable content. * @param dir the left-to-right direction of text inside this element. * @param draggable controls whether or not the element is draggable. * @param hidden true if the element is to be hidden. * @param lang the language of text within this element. * @param spellcheck whether the element is subject to spell checking. * @param style a string containing CSS for this element. * @param tabindex the tab index for the element. * @param title a tool tip for the element. * @param translate whether to translate text within this element. * @param defineContent a DSL-style lambda that builds the child nodes of the new element. */ fun kbd( selector: String? = null, key: Any? = null, accesskey: Char? = null, contenteditable: Boolean? = null, dir: EDirection? = null, draggable: Boolean? = null, hidden: Boolean? = null, lang: String? = null, spellcheck: Boolean? = null, style: String? = null, tabindex: Int? = null, title: String? = null, translate: Boolean? = null, defineContent: KatydidPhrasingContentBuilder<Msg>.() -> Unit ) /** * Adds a label element with its attributes as the next child of the element under construction. * Note: If key is not specified, the `for` attribute will be used as the key. * @param selector the "selector" for the element, e.g. "#myid.my-class.my-other-class". * @param key a non-DOM key for this Katydid element that is unique among all the siblings of this element. * @param accesskey a string specifying the HTML accesskey value. * @param contenteditable whether the element has editable content. * @param dir the left-to-right direction of text inside this element. * @param draggable controls whether or not the element is draggable. * @param hidden true if the element is to be hidden. * @param lang the language of text within this element. * @param spellcheck whether the element is subject to spell checking. * @param style a string containing CSS for this element. * @param tabindex the tab index for the element. * @param title a tool tip for the element. * @param translate whether to translate text within this element. * @param defineContent a DSL-style lambda that builds the child nodes of the new element. */ fun label( selector: String? = null, key: Any? = null, accesskey: Char? = null, contenteditable: Boolean? = null, dir: EDirection? = null, draggable: Boolean? = null, `for`: String? = null, hidden: Boolean? = null, lang: String? = null, spellcheck: Boolean? = null, style: String? = null, tabindex: Int? = null, title: String? = null, translate: Boolean? = null, defineContent: KatydidPhrasingContentBuilder<Msg>.() -> Unit ) /** * Adds a map element with its attributes as the next child of the element under construction. * @param selector the "selector" for the element, e.g. "#myid.my-class.my-other-class". * @param key a non-DOM key for this Katydid element that is unique among all the siblings of this element. * @param accesskey a string specifying the HTML accesskey value. * @param contenteditable whether the element has editable content. * @param dir the left-to-right direction of text inside this element. * @param draggable controls whether or not the element is draggable. * @param hidden true if the element is to be hidden. * @param lang the language of text within this element. * @param name the name of the image map to reference from an img usemap attribute. * @param spellcheck whether the element is subject to spell checking. * @param style a string containing CSS for this element. * @param tabindex the tab index for the element. * @param title a tool tip for the element. * @param translate whether to translate text within this element. * @param defineContent a DSL-style lambda that builds the child nodes of the new element. */ fun map( selector: String? = null, key: Any? = null, accesskey: Char? = null, contenteditable: Boolean? = null, dir: EDirection? = null, draggable: Boolean? = null, hidden: Boolean? = null, lang: String? = null, name: String? = null, spellcheck: Boolean? = null, style: String? = null, tabindex: Int? = null, title: String? = null, translate: Boolean? = null, defineContent: KatydidPhrasingContentBuilder<Msg>.() -> Unit ) /** * Adds a mark element with its attributes as the next child of the element under construction. * @param selector the "selector" for the element, e.g. "#myid.my-class.my-other-class". * @param key a non-DOM key for this Katydid element that is unique among all the siblings of this element. * @param accesskey a string specifying the HTML accesskey value. * @param contenteditable whether the element has editable content. * @param dir the left-to-right direction of text inside this element. * @param draggable controls whether or not the element is draggable. * @param hidden true if the element is to be hidden. * @param lang the language of text within this element. * @param spellcheck whether the element is subject to spell checking. * @param style a string containing CSS for this element. * @param tabindex the tab index for the element. * @param title a tool tip for the element. * @param translate whether to translate text within this element. * @param defineContent a DSL-style lambda that builds the child nodes of the new element. */ fun mark( selector: String? = null, key: Any? = null, accesskey: Char? = null, contenteditable: Boolean? = null, dir: EDirection? = null, draggable: Boolean? = null, hidden: Boolean? = null, lang: String? = null, spellcheck: Boolean? = null, style: String? = null, tabindex: Int? = null, title: String? = null, translate: Boolean? = null, defineContent: KatydidPhrasingContentBuilder<Msg>.() -> Unit ) /** * Adds a meter element with its attributes as the next child of the element under construction. Meter readings * are floating point numbers * @param selector the "selector" for the element, e.g. "#myid.my-class.my-other-class". * @param key a non-DOM key for this Katydid element that is unique among all the siblings of this element. * @param accesskey a string specifying the HTML accesskey value. * @param contenteditable whether the element has editable content. * @param dir the left-to-right direction of text inside this element. * @param draggable controls whether or not the element is draggable. * @param hidden true if the element is to be hidden. * @param high the highest recorded reading for the meter. * @param lang the language of text within this element. * @param low the lowest recorded reading for the meter. * @param max the maximum of the meter's range. * @param min the minimum of the meter's range. * @param optimum the optimum reading for the measured value. * @param spellcheck whether the element is subject to spell checking. * @param style a string containing CSS for this element. * @param tabindex the tab index for the element. * @param title a tool tip for the element. * @param translate whether to translate text within this element. * @param value the current value of the meter. * @param defineContent a DSL-style lambda that builds the child nodes of the new element. */ fun meter( selector: String? = null, key: Any? = null, accesskey: Char? = null, contenteditable: Boolean? = null, dir: EDirection? = null, draggable: Boolean? = null, hidden: Boolean? = null, high: Double? = null, lang: String? = null, low: Double? = null, max: Double? = null, min: Double? = null, optimum: Double? = null, spellcheck: Boolean? = null, style: String? = null, tabindex: Int? = null, title: String? = null, translate: Boolean? = null, value: Double, defineContent: KatydidPhrasingContentBuilder<Msg>.() -> Unit ) /** * Adds a meter element with its attributes as the next child of the element under construction. Meter readings * are integers. * @param selector the "selector" for the element, e.g. "#myid.my-class.my-other-class". * @param key a non-DOM key for this Katydid element that is unique among all the siblings of this element. * @param accesskey a string specifying the HTML accesskey value. * @param contenteditable whether the element has editable content. * @param dir the left-to-right direction of text inside this element. * @param draggable controls whether or not the element is draggable. * @param hidden true if the element is to be hidden. * @param high the highest recorded reading for the meter. * @param lang the language of text within this element. * @param low the lowest recorded reading for the meter. * @param max the maximum of the meter's range. * @param min the minimum of the meter's range. * @param optimum the optimum reading for the measured value. * @param spellcheck whether the element is subject to spell checking. * @param style a string containing CSS for this element. * @param tabindex the tab index for the element. * @param title a tool tip for the element. * @param translate whether to translate text within this element. * @param value the current value of the meter. * @param defineContent a DSL-style lambda that builds the child nodes of the new element. */ fun meter( selector: String? = null, key: Any? = null, accesskey: Char? = null, contenteditable: Boolean? = null, dir: EDirection? = null, draggable: Boolean? = null, hidden: Boolean? = null, high: Int? = null, lang: String? = null, low: Int? = null, max: Int, min: Int? = null, optimum: Int? = null, spellcheck: Boolean? = null, style: String? = null, tabindex: Int? = null, title: String? = null, translate: Boolean? = null, value: Int, defineContent: KatydidPhrasingContentBuilder<Msg>.() -> Unit ) /** * Adds an `<object>` element with its attributes as the next child of the element under construction. * @param selector the "selector" for the element, e.g. "#myid.my-class.my-other-class". * @param key a non-DOM key for this Katydid element that is unique among all the siblings of this element. * @param accesskey a string specifying the HTML accesskey value. * @param contenteditable whether the element has editable content. * @param data the address of the resource. * @param dir the left-to-right direction of text inside this element. * @param draggable controls whether or not the element is draggable. * @param form associates the control with a form element. * @param height the vertical dimension. * @param hidden true if the element is to be hidden. * @param lang the language of text within this element. * @param name the name of the nested browsing context. * @param spellcheck whether the element is subject to spell checking. * @param style a string containing CSS for this element. * @param tabindex the tab index for the element. * @param title a tool tip for the element. * @param translate whether to translate text within this element. * @param type the MIME type of the embedded resource. * @param typemustmatch whether the type attribute and the Content-Type value need to match for the resource to be used. * @param width the horizontal dimension. * @param contentType flag to explicitly specify content type to support content transparency. * @param defineContent a DSL-style lambda that builds any custom attributes of the new element. */ fun `object`( selector: String? = null, key: Any? = null, accesskey: Char? = null, contenteditable: Boolean? = null, data: String? = null, dir: EDirection? = null, draggable: Boolean? = null, form: String? = null, height: Int? = null, hidden: Boolean? = null, lang: String? = null, name: String? = null, spellcheck: Boolean? = null, style: String? = null, tabindex: Int? = null, title: String? = null, translate: Boolean? = null, type: MimeType? = null, typemustmatch: Boolean? = null, width: Int? = null, contentType: PhrasingContent, defineContent: KatydidObjectPhrasingContentBuilder<Msg>.() -> Unit ) /** * Adds an output element with given attributes as the next child of the element under construction. * @param selector the "selector" for the element, e.g. "#myid.my-class.my-other-class". * @param key a non-DOM key for this Katydid element that is unique among all the siblings of this element. * @param accesskey a string specifying the HTML accesskey value. * @param contenteditable whether the element has editable content. * @param dir the left-to-right direction of text inside this element. * @param draggable controls whether or not the element is draggable. * @param hidden true if the element is to be hidden. * @param lang the language of text within this element. * @param name the name of this field for form submissions. * @param spellcheck whether the element is subject to spell checking. * @param style a string containing CSS for this element. * @param tabindex the tab index for the element. * @param title a tool tip for the element. * @param translate whether to translate text within this element. * @param defineContent a DSL-style lambda that builds the child nodes of the new element. */ fun output( selector: String? = null, key: Any? = null, accesskey: Char? = null, contenteditable: Boolean? = null, dir: EDirection? = null, disabled: Boolean? = null, draggable: Boolean? = null, `for`: String? = null, form: String? = null, hidden: Boolean? = null, lang: String? = null, name: String? = null, spellcheck: Boolean? = null, style: String? = null, tabindex: Int? = null, title: String? = null, translate: Boolean? = null, defineContent: KatydidPhrasingContentBuilder<Msg>.() -> Unit ) /** * Adds a `<progress>` element with its attributes as the next child of the element under construction. * @param selector the "selector" for the element, e.g. "#myid.my-class.my-other-class". * @param key a non-DOM key for this Katydid element that is unique among all the siblings of this element. * @param accesskey a string specifying the HTML accesskey value. * @param contenteditable whether the element has editable content. * @param dir the left-to-right direction of text inside this element. * @param draggable controls whether or not the element is draggable. * @param hidden true if the element is to be hidden. * @param lang the language of text within this element. * @param max the upper limit for the progress value. * @param spellcheck whether the element is subject to spell checking. * @param style a string containing CSS for this element. * @param tabindex the tab index for the element. * @param title a tool tip for the element. * @param translate whether to translate text within this element. * @param value the current degree of progress. * @param defineContent a DSL-style lambda that builds the child nodes of the new element. */ fun progress( selector: String? = null, key: Any? = null, accesskey: Char? = null, contenteditable: Boolean? = null, dir: EDirection? = null, draggable: Boolean? = null, hidden: Boolean? = null, lang: String? = null, max: Double? = null, spellcheck: Boolean? = null, style: String? = null, tabindex: Int? = null, title: String? = null, translate: Boolean? = null, value: Double? = null, defineContent: KatydidPhrasingContentBuilder<Msg>.() -> Unit ) /** * Adds a `<progress>` element with its attributes as the next child of the element under construction. * @param selector the "selector" for the element, e.g. "#myid.my-class.my-other-class". * @param key a non-DOM key for this Katydid element that is unique among all the siblings of this element. * @param accesskey a string specifying the HTML accesskey value. * @param contenteditable whether the element has editable content. * @param dir the left-to-right direction of text inside this element. * @param draggable controls whether or not the element is draggable. * @param hidden true if the element is to be hidden. * @param lang the language of text within this element. * @param max the upper limit for the progress value. * @param spellcheck whether the element is subject to spell checking. * @param style a string containing CSS for this element. * @param tabindex the tab index for the element. * @param title a tool tip for the element. * @param translate whether to translate text within this element. * @param value the current degree of progress. * @param defineContent a DSL-style lambda that builds the child nodes of the new element. */ fun progress( selector: String? = null, key: Any? = null, accesskey: Char? = null, contenteditable: Boolean? = null, dir: EDirection? = null, draggable: Boolean? = null, hidden: Boolean? = null, lang: String? = null, max: Int, spellcheck: Boolean? = null, style: String? = null, tabindex: Int? = null, title: String? = null, translate: Boolean? = null, value: Int? = null, defineContent: KatydidPhrasingContentBuilder<Msg>.() -> Unit ) /** * Adds a q element with its attributes as the next child of the element under construction. * @param selector the "selector" for the element, e.g. "#myid.my-class.my-other-class". * @param key a non-DOM key for this Katydid element that is unique among all the siblings of this element. * @param accesskey a string specifying the HTML accesskey value. * @param contenteditable whether the element has editable content. * @param dir the left-to-right direction of text inside this element. * @param draggable controls whether or not the element is draggable. * @param hidden true if the element is to be hidden. * @param lang the language of text within this element. * @param spellcheck whether the element is subject to spell checking. * @param style a string containing CSS for this element. * @param tabindex the tab index for the element. * @param title a tool tip for the element. * @param translate whether to translate text within this element. * @param defineContent a DSL-style lambda that builds the child nodes of the new element. */ fun q( selector: String? = null, key: Any? = null, accesskey: Char? = null, contenteditable: Boolean? = null, dir: EDirection? = null, draggable: Boolean? = null, hidden: Boolean? = null, lang: String? = null, spellcheck: Boolean? = null, style: String? = null, tabindex: Int? = null, title: String? = null, translate: Boolean? = null, defineContent: KatydidPhrasingContentBuilder<Msg>.() -> Unit ) /** * Adds a ruby element with its attributes as the next child of the element under construction. * @param selector the "selector" for the element, e.g. "#myid.my-class.my-other-class". * @param key a non-DOM key for this Katydid element that is unique among all the siblings of this element. * @param accesskey a string specifying the HTML accesskey value. * @param contenteditable whether the element has editable content. * @param dir the left-to-right direction of text inside this element. * @param draggable controls whether or not the element is draggable. * @param hidden true if the element is to be hidden. * @param lang the language of text within this element. * @param spellcheck whether the element is subject to spell checking. * @param style a string containing CSS for this element. * @param tabindex the tab index for the element. * @param title a tool tip for the element. * @param translate whether to translate text within this element. * @param defineContent a DSL-style lambda that builds the child nodes of the new element. */ fun ruby( selector: String? = null, key: Any? = null, accesskey: Char? = null, contenteditable: Boolean? = null, dir: EDirection? = null, draggable: Boolean? = null, hidden: Boolean? = null, lang: String? = null, spellcheck: Boolean? = null, style: String? = null, tabindex: Int? = null, title: String? = null, translate: Boolean? = null, defineContent: KatydidRubyContentBuilder<Msg>.() -> Unit ) /** * Adds an s element with its attributes as the next child of the element under construction. * @param selector the "selector" for the element, e.g. "#myid.my-class.my-other-class". * @param key a non-DOM key for this Katydid element that is unique among all the siblings of this element. * @param accesskey a string specifying the HTML accesskey value. * @param contenteditable whether the element has editable content. * @param dir the left-to-right direction of text inside this element. * @param draggable controls whether or not the element is draggable. * @param hidden true if the element is to be hidden. * @param lang the language of text within this element. * @param spellcheck whether the element is subject to spell checking. * @param style a string containing CSS for this element. * @param tabindex the tab index for the element. * @param title a tool tip for the element. * @param translate whether to translate text within this element. * @param defineContent a DSL-style lambda that builds the child nodes of the new element. */ fun s( selector: String? = null, key: Any? = null, accesskey: Char? = null, contenteditable: Boolean? = null, dir: EDirection? = null, draggable: Boolean? = null, hidden: Boolean? = null, lang: String? = null, spellcheck: Boolean? = null, style: String? = null, tabindex: Int? = null, title: String? = null, translate: Boolean? = null, defineContent: KatydidPhrasingContentBuilder<Msg>.() -> Unit ) /** * Adds a samp element with its attributes as the next child of the element under construction. * @param selector the "selector" for the element, e.g. "#myid.my-class.my-other-class". * @param key a non-DOM key for this Katydid element that is unique among all the siblings of this element. * @param accesskey a string specifying the HTML accesskey value. * @param contenteditable whether the element has editable content. * @param dir the left-to-right direction of text inside this element. * @param draggable controls whether or not the element is draggable. * @param hidden true if the element is to be hidden. * @param lang the language of text within this element. * @param spellcheck whether the element is subject to spell checking. * @param style a string containing CSS for this element. * @param tabindex the tab index for the element. * @param title a tool tip for the element. * @param translate whether to translate text within this element. * @param defineContent a DSL-style lambda that builds the child nodes of the new element. */ fun samp( selector: String? = null, key: Any? = null, accesskey: Char? = null, contenteditable: Boolean? = null, dir: EDirection? = null, draggable: Boolean? = null, hidden: Boolean? = null, lang: String? = null, spellcheck: Boolean? = null, style: String? = null, tabindex: Int? = null, title: String? = null, translate: Boolean? = null, defineContent: KatydidPhrasingContentBuilder<Msg>.() -> Unit ) /** * Adds a select element with its attributes as the next child of the element under construction. * @param selector the "selector" for the element, e.g. "#myid.my-class.my-other-class". * @param key a non-DOM key for this Katydid element that is unique among all the siblings of this element. * @param accesskey a string specifying the HTML accesskey value. * @param autocomplete a hint describing the value that can be prefilled into this field by a browser. * @param autofocus true if the field is to automatically receive keyboard focus. * @param contenteditable whether the element has editable content. * @param dir the left-to-right direction of text inside this element. * @param draggable controls whether or not the element is draggable. * @param hidden true if the element is to be hidden. * @param lang the language of text within this element. * @param name the name of this field for form submissions. * @param spellcheck whether the element is subject to spell checking. * @param style a string containing CSS for this element. * @param tabindex the tab index for the element. * @param title a tool tip for the element. * @param translate whether to translate text within this element. * @param defineContent a DSL-style lambda that builds the child nodes of the new element. */ fun select( selector: String? = null, key: Any? = null, accesskey: Char? = null, autocomplete: String? = null, autofocus: Boolean? = null, contenteditable: Boolean? = null, dir: EDirection? = null, disabled: Boolean? = null, draggable: Boolean? = null, form: String? = null, hidden: Boolean? = null, lang: String? = null, multiple: Boolean? = null, name: String? = null, required: Boolean? = null, size: Int? = null, spellcheck: Boolean? = null, style: String? = null, tabindex: Int? = null, title: String? = null, translate: Boolean? = null, value: String? = null, defineContent: KatydidSelectContentBuilder<Msg>.() -> Unit ) /** * Adds a small element with its attributes as the next child of the element under construction. * @param selector the "selector" for the element, e.g. "#myid.my-class.my-other-class". * @param key a non-DOM key for this Katydid element that is unique among all the siblings of this element. * @param accesskey a string specifying the HTML accesskey value. * @param contenteditable whether the element has editable content. * @param dir the left-to-right direction of text inside this element. * @param draggable controls whether or not the element is draggable. * @param hidden true if the element is to be hidden. * @param lang the language of text within this element. * @param spellcheck whether the element is subject to spell checking. * @param style a string containing CSS for this element. * @param tabindex the tab index for the element. * @param title a tool tip for the element. * @param translate whether to translate text within this element. * @param defineContent a DSL-style lambda that builds the child nodes of the new element. */ fun small( selector: String? = null, key: Any? = null, accesskey: Char? = null, contenteditable: Boolean? = null, dir: EDirection? = null, draggable: Boolean? = null, hidden: Boolean? = null, lang: String? = null, spellcheck: Boolean? = null, style: String? = null, tabindex: Int? = null, title: String? = null, translate: Boolean? = null, defineContent: KatydidPhrasingContentBuilder<Msg>.() -> Unit ) /** * Adds a span element with its attributes as the next child of the element under construction. * @param selector the "selector" for the element, e.g. "#myid.my-class.my-other-class". * @param key a non-DOM key for this Katydid element that is unique among all the siblings of this element. * @param accesskey a string specifying the HTML accesskey value. * @param contenteditable whether the element has editable content. * @param dir the left-to-right direction of text inside this element. * @param draggable controls whether or not the element is draggable. * @param hidden true if the element is to be hidden. * @param lang the language of text within this element. * @param spellcheck whether the element is subject to spell checking. * @param style a string containing CSS for this element. * @param tabindex the tab index for the element. * @param title a tool tip for the element. * @param translate whether to translate text within this element. * @param defineContent a DSL-style lambda that builds the child nodes of the new element. */ fun span( selector: String? = null, key: Any? = null, accesskey: Char? = null, contenteditable: Boolean? = null, dir: EDirection? = null, draggable: Boolean? = null, hidden: Boolean? = null, lang: String? = null, spellcheck: Boolean? = null, style: String? = null, tabindex: Int? = null, title: String? = null, translate: Boolean? = null, defineContent: KatydidPhrasingContentBuilder<Msg>.() -> Unit ) /** * Adds a strong element with its attributes as the next child of the element under construction. * @param selector the "selector" for the element, e.g. "#myid.my-class.my-other-class". * @param key a non-DOM key for this Katydid element that is unique among all the siblings of this element. * @param accesskey a string specifying the HTML accesskey value. * @param contenteditable whether the element has editable content. * @param dir the left-to-right direction of text inside this element. * @param draggable controls whether or not the element is draggable. * @param hidden true if the element is to be hidden. * @param lang the language of text within this element. * @param spellcheck whether the element is subject to spell checking. * @param style a string containing CSS for this element. * @param tabindex the tab index for the element. * @param title a tool tip for the element. * @param translate whether to translate text within this element. * @param defineContent a DSL-style lambda that builds the child nodes of the new element. */ fun strong( selector: String? = null, key: Any? = null, accesskey: Char? = null, contenteditable: Boolean? = null, dir: EDirection? = null, draggable: Boolean? = null, hidden: Boolean? = null, lang: String? = null, spellcheck: Boolean? = null, style: String? = null, tabindex: Int? = null, title: String? = null, translate: Boolean? = null, defineContent: KatydidPhrasingContentBuilder<Msg>.() -> Unit ) /** * Adds a sub element with its attributes as the next child of the element under construction. * @param selector the "selector" for the element, e.g. "#myid.my-class.my-other-class". * @param key a non-DOM key for this Katydid element that is unique among all the siblings of this element. * @param accesskey a string specifying the HTML accesskey value. * @param contenteditable whether the element has editable content. * @param dir the left-to-right direction of text inside this element. * @param draggable controls whether or not the element is draggable. * @param hidden true if the element is to be hidden. * @param lang the language of text within this element. * @param spellcheck whether the element is subject to spell checking. * @param style a string containing CSS for this element. * @param tabindex the tab index for the element. * @param title a tool tip for the element. * @param translate whether to translate text within this element. * @param defineContent a DSL-style lambda that builds the child nodes of the new element. */ fun sub( selector: String? = null, key: Any? = null, accesskey: Char? = null, contenteditable: Boolean? = null, dir: EDirection? = null, draggable: Boolean? = null, hidden: Boolean? = null, lang: String? = null, spellcheck: Boolean? = null, style: String? = null, tabindex: Int? = null, title: String? = null, translate: Boolean? = null, defineContent: KatydidPhrasingContentBuilder<Msg>.() -> Unit ) /** * Adds a sup element with its attributes as the next child of the element under construction. * @param selector the "selector" for the element, e.g. "#myid.my-class.my-other-class". * @param key a non-DOM key for this Katydid element that is unique among all the siblings of this element. * @param accesskey a string specifying the HTML accesskey value. * @param contenteditable whether the element has editable content. * @param dir the left-to-right direction of text inside this element. * @param draggable controls whether or not the element is draggable. * @param hidden true if the element is to be hidden. * @param lang the language of text within this element. * @param spellcheck whether the element is subject to spell checking. * @param style a string containing CSS for this element. * @param tabindex the tab index for the element. * @param title a tool tip for the element. * @param translate whether to translate text within this element. * @param defineContent a DSL-style lambda that builds the child nodes of the new element. */ fun sup( selector: String? = null, key: Any? = null, accesskey: Char? = null, contenteditable: Boolean? = null, dir: EDirection? = null, draggable: Boolean? = null, hidden: Boolean? = null, lang: String? = null, spellcheck: Boolean? = null, style: String? = null, tabindex: Int? = null, title: String? = null, translate: Boolean? = null, defineContent: KatydidPhrasingContentBuilder<Msg>.() -> Unit ) /** * Adds a text node as the next child of the element under construction. * @param nodeValue the text within the node. */ fun text( nodeValue: String, key: Any? = null ) /** * Allows using +"some text" for text content. */ operator fun String.unaryPlus() { [email protected](this) } /** * Adds a textarea element with given attributes as the next child of the element under construction. * @param selector the "selector" for the element, e.g. "#myid.my-class.my-other-class". * @param key a non-DOM key for this Katydid element that is unique among all the siblings of this element. * @param accesskey a string specifying the HTML accesskey value. * @param autocomplete a hint describing the value that can be prefilled into this field by a browser. * @param autofocus true if the field is to automatically receive keyboard focus. * @param contenteditable whether the element has editable content. * @param dir the left-to-right direction of text inside this element. * @param draggable controls whether or not the element is draggable. * @param hidden true if the element is to be hidden. * @param lang the language of text within this element. * @param name the name of this field for form submissions. * @param spellcheck whether the element is subject to spell checking. * @param style a string containing CSS for this element. * @param tabindex the tab index for the element. * @param title a tool tip for the element. * @param translate whether to translate text within this element. * @param defineContent a DSL-style lambda that builds the child nodes of the new element. */ fun textarea( selector: String? = null, key: Any? = null, accesskey: Char? = null, autocomplete: String? = null, autofocus: Boolean? = null, cols: Int? = null, contenteditable: Boolean? = null, dir: EDirection? = null, dirname: String? = null, disabled: Boolean? = null, draggable: Boolean? = null, form: String? = null, hidden: Boolean? = null, lang: String? = null, maxlength: Int? = null, minlength: Int? = null, name: String? = null, placeholder: String? = null, readonly: Boolean? = null, required: Boolean? = null, rows: Int? = null, spellcheck: Boolean? = null, style: String? = null, tabindex: Int? = null, title: String? = null, translate: Boolean? = null, wrap: EWrapType? = null, defineContent: KatydidTextContentBuilder<Msg>.() -> Unit ) /** * Adds a `<time>` element with text content as the next child of the element under construction. * @param selector the "selector" for the element, e.g. "#myid.my-class.my-other-class". * @param key a non-DOM key for this Katydid element that is unique among all the siblings of this element. * @param accesskey a string specifying the HTML accesskey value. * @param contenteditable whether the element has editable content. * @param dir the left-to-right direction of text inside this element. * @param draggable controls whether or not the element is draggable. * @param hidden true if the element is to be hidden. * @param lang the language of text within this element. * @param spellcheck whether the element is subject to spell checking. * @param style a string containing CSS for this element. * @param tabindex the tab index for the element. * @param title a tool tip for the element. * @param translate whether to translate text within this element. * @param defineContent a DSL-style lambda that builds the child nodes of the new element. */ fun time( selector: String? = null, key: Any? = null, accesskey: Char? = null, contenteditable: Boolean? = null, dir: EDirection? = null, draggable: Boolean? = null, hidden: Boolean? = null, lang: String? = null, spellcheck: Boolean? = null, style: String? = null, tabindex: Int? = null, title: String? = null, translate: Boolean? = null, defineContent: KatydidTextContentBuilder<Msg>.() -> Unit ) /** * Adds a `<time>` element with datetime attribute as the next child of the element under construction. * @param selector the "selector" for the element, e.g. "#myid.my-class.my-other-class". * @param key a non-DOM key for this Katydid element that is unique among all the siblings of this element. * @param accesskey a string specifying the HTML accesskey value. * @param contenteditable whether the element has editable content. * @param dir the left-to-right direction of text inside this element. * @param draggable controls whether or not the element is draggable. * @param hidden true if the element is to be hidden. * @param lang the language of text within this element. * @param spellcheck whether the element is subject to spell checking. * @param style a string containing CSS for this element. * @param tabindex the tab index for the element. * @param title a tool tip for the element. * @param translate whether to translate text within this element. * @param defineContent a DSL-style lambda that builds the child nodes of the new element. */ fun time( selector: String? = null, key: Any? = null, accesskey: Char? = null, contenteditable: Boolean? = null, datetime: KatyDateTime, dir: EDirection? = null, draggable: Boolean? = null, hidden: Boolean? = null, lang: String? = null, spellcheck: Boolean? = null, style: String? = null, tabindex: Int? = null, title: String? = null, translate: Boolean? = null, defineContent: KatydidPhrasingContentBuilder<Msg>.() -> Unit ) /** * Adds a `<u>` element with its attributes as the next child of the element under construction. * @param selector the "selector" for the element, e.g. "#myid.my-class.my-other-class". * @param key a non-DOM key for this Katydid element that is unique among all the siblings of this element. * @param accesskey a string specifying the HTML accesskey value. * @param contenteditable whether the element has editable content. * @param dir the left-to-right direction of text inside this element. * @param draggable controls whether or not the element is draggable. * @param hidden true if the element is to be hidden. * @param lang the language of text within this element. * @param spellcheck whether the element is subject to spell checking. * @param style a string containing CSS for this element. * @param tabindex the tab index for the element. * @param title a tool tip for the element. * @param translate whether to translate text within this element. * @param defineContent a DSL-style lambda that builds the child nodes of the new element. */ fun u( selector: String? = null, key: Any? = null, accesskey: Char? = null, contenteditable: Boolean? = null, dir: EDirection? = null, draggable: Boolean? = null, hidden: Boolean? = null, lang: String? = null, spellcheck: Boolean? = null, style: String? = null, tabindex: Int? = null, title: String? = null, translate: Boolean? = null, defineContent: KatydidPhrasingContentBuilder<Msg>.() -> Unit ) /** * Adds a var element with its attributes as the next child of the element under construction. * @param selector the "selector" for the element, e.g. "#myid.my-class.my-other-class". * @param key a non-DOM key for this Katydid element that is unique among all the siblings of this element. * @param accesskey a string specifying the HTML accesskey value. * @param contenteditable whether the element has editable content. * @param dir the left-to-right direction of text inside this element. * @param draggable controls whether or not the element is draggable. * @param hidden true if the element is to be hidden. * @param lang the language of text within this element. * @param spellcheck whether the element is subject to spell checking. * @param style a string containing CSS for this element. * @param tabindex the tab index for the element. * @param title a tool tip for the element. * @param translate whether to translate text within this element. * @param defineContent a DSL-style lambda that builds the child nodes of the new element. */ fun `var`( selector: String? = null, key: Any? = null, accesskey: Char? = null, contenteditable: Boolean? = null, dir: EDirection? = null, draggable: Boolean? = null, hidden: Boolean? = null, lang: String? = null, spellcheck: Boolean? = null, style: String? = null, tabindex: Int? = null, title: String? = null, translate: Boolean? = null, defineContent: KatydidPhrasingContentBuilder<Msg>.() -> Unit ) /** * Adds a `<video>` element with its attributes as the next child of the element under construction. * @param selector the "selector" for the element, e.g. "#myid.my-class.my-other-class". * @param key a non-DOM key for this Katydid element that is unique among all the siblings of this element. * @param accesskey a string specifying the HTML accesskey value. * @param autoplay hint that the media resource can be started automatically when the page is loaded. * @param contenteditable whether the element has editable content. * @param controls show user agent controls * @param crossorigin how the element handles crossorigin requests. * @param dir the left-to-right direction of text inside this element. * @param draggable controls whether or not the element is draggable. * @param height vertical dimension. * @param hidden true if the element is to be hidden. * @param lang the language of text within this element. * @param loop whether to loop the media resource. * @param muted whether to mute the media resource by default. * @param poster poster frame to show prior to video playback. * @param preload hints how much buffering the media resource will likely need. * @param spellcheck whether the element is subject to spell checking. * @param src address of the resource. * @param style a string containing CSS for this element. * @param tabindex the tab index for the element. * @param title a tool tip for the element. * @param translate whether to translate text within this element. * @param width horizontal dimension. * @param contentType flag to explicitly specify content type to support content transparency. * @param defineContent a DSL-style lambda that builds any custom attributes of the new element. */ fun video( selector: String? = null, key: Any? = null, accesskey: Char? = null, autoplay: Boolean? = null, contenteditable: Boolean? = null, controls: Boolean? = null, crossorigin: ECorsSetting? = null, dir: EDirection? = null, draggable: Boolean? = null, height: Int? = null, hidden: Boolean? = null, lang: String? = null, loop: Boolean? = null, muted: Boolean? = null, poster: String? = null, preload: EPreloadHint? = null, spellcheck: Boolean? = null, src: String? = null, style: String? = null, tabindex: Int? = null, title: String? = null, translate: Boolean? = null, width: Int? = null, contentType: PhrasingContent, defineContent: KatydidMediaPhrasingContentBuilder<Msg>.() -> Unit ) /** * Adds a wbr element as the next child of the element under construction. * @param selector the "selector" for the element, e.g. "#myid.my-class.my-other-class". * @param key a non-DOM key for this Katydid element that is unique among all the siblings of this element. * @param accesskey a string specifying the HTML accesskey value. * @param contenteditable whether the element has editable content. * @param dir the left-to-right direction of text inside this element. * @param draggable controls whether or not the element is draggable. * @param hidden true if the element is to be hidden. * @param lang the language of text within this element. * @param spellcheck whether the element is subject to spell checking. * @param style a string containing CSS for this element. * @param tabindex the tab index for the element. * @param title a tool tip for the element. * @param translate whether to translate text within this element. * @param defineAttributes a DSL-style lambda that adds any nonstandard attributes to the new element. */ fun wbr( selector: String? = null, key: Any? = null, accesskey: Char? = null, contenteditable: Boolean? = null, dir: EDirection? = null, draggable: Boolean? = null, hidden: Boolean? = null, lang: String? = null, spellcheck: Boolean? = null, style: String? = null, tabindex: Int? = null, title: String? = null, translate: Boolean? = null, defineAttributes: KatydidAttributesContentBuilder<Msg>.() -> Unit ) } //---------------------------------------------------------------------------------------------------------------------
apache-2.0
680799d30572a3ce8f4eb112ad411a39
48.454985
129
0.65718
4.487877
false
false
false
false
Ribesg/anko
dsl/static/src/common/Async.kt
1
4422
/* * Copyright 2015 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.anko import android.app.Activity import android.app.Fragment import android.content.Context import android.os.Handler import android.os.Looper import org.jetbrains.anko.internals.AnkoInternals.NoBinding import java.lang.ref.WeakReference import java.util.concurrent.ExecutorService import java.util.concurrent.Executors import java.util.concurrent.Future // Fragment.uiThread() has a different argument list (because of inline) @NoBinding fun Context.onUiThread(f: Context.() -> Unit) { if (ContextHelper.mainThread == Thread.currentThread()) f() else ContextHelper.handler.post { f() } } @NoBinding inline fun Fragment.onUiThread(crossinline f: () -> Unit) { activity?.onUiThread { f() } } class AnkoAsyncContext<T>(val weakRef: WeakReference<T>) fun <T> AnkoAsyncContext<T>.uiThread(f: (T) -> Unit) { val ref = weakRef.get() ?: return if (ContextHelper.mainThread == Thread.currentThread()) { f(ref) } else { ContextHelper.handler.post { f(ref) } } } fun <T: Activity> AnkoAsyncContext<T>.activityUiThread(f: (T) -> Unit) { val activity = weakRef.get() ?: return if (activity.isFinishing) return activity.runOnUiThread { f(activity) } } fun <T: Activity> AnkoAsyncContext<T>.activityUiThreadWithContext(f: Context.(T) -> Unit) { val activity = weakRef.get() ?: return if (activity.isFinishing) return activity.runOnUiThread { activity.f(activity) } } @JvmName("activityContextUiThread") fun <T: Activity> AnkoAsyncContext<AnkoContext<T>>.activityUiThread(f: (T) -> Unit) { val activity = weakRef.get()?.owner ?: return if (activity.isFinishing) return activity.runOnUiThread { f(activity) } } @JvmName("activityContextUiThreadWithContext") fun <T: Activity> AnkoAsyncContext<AnkoContext<T>>.activityUiThreadWithContext(f: Context.(T) -> Unit) { val activity = weakRef.get()?.owner ?: return if (activity.isFinishing) return activity.runOnUiThread { activity.f(activity) } } fun <T: Fragment> AnkoAsyncContext<T>.fragmentUiThread(f: (T) -> Unit) { val fragment = weakRef.get() ?: return if (fragment.isDetached) return val activity = fragment.activity ?: return activity.runOnUiThread { f(fragment) } } fun <T: Fragment> AnkoAsyncContext<T>.fragmentUiThreadWithContext(f: Context.(T) -> Unit) { val fragment = weakRef.get() ?: return if (fragment.isDetached) return val activity = fragment.activity ?: return activity.runOnUiThread { activity.f(fragment) } } fun <T> T.async(task: AnkoAsyncContext<T>.() -> Unit): Future<Unit> { val context = AnkoAsyncContext(WeakReference(this)) return BackgroundExecutor.submit { context.task() } } fun <T> T.async(executorService: ExecutorService, task: AnkoAsyncContext<T>.() -> Unit): Future<Unit> { val context = AnkoAsyncContext(WeakReference(this)) return executorService.submit<Unit> { context.task() } } fun <T, R> T.asyncResult(task: AnkoAsyncContext<T>.() -> R): Future<R> { val context = AnkoAsyncContext(WeakReference(this)) return BackgroundExecutor.submit { context.task() } } fun <T, R> T.asyncResult(executorService: ExecutorService, task: AnkoAsyncContext<T>.() -> R): Future<R> { val context = AnkoAsyncContext(WeakReference(this)) return executorService.submit<R> { context.task() } } internal object BackgroundExecutor { var executor: ExecutorService = Executors.newScheduledThreadPool(2 * Runtime.getRuntime().availableProcessors()) fun execute(task: () -> Unit): Future<Unit> { return executor.submit<Unit> { task() } } fun <T> submit(task: () -> T): Future<T> { return executor.submit(task) } } private object ContextHelper { val handler = Handler(Looper.getMainLooper()) val mainThread = Looper.getMainLooper().thread }
apache-2.0
c065821f13c21882bdb99705e77b73f8
33.554688
106
0.7128
4.012704
false
false
false
false
Pixelhash/SignColors
src/main/kotlin/de/codehat/signcolors/database/MysqlDatabase.kt
1
800
package de.codehat.signcolors.database import de.codehat.signcolors.database.abstraction.Database class MysqlDatabase(connectionString: String): Database(connectionString) { companion object { // Pattern is HOSTNAME -> PORT -> DATABASE -> USER -> PASSWORD private const val MYSQL_JDBC_CONNECTION_STRING = "jdbc:mysql://%s:%s/%s?user=%s&password=%s&useSSL=false&autoReconnect=true" fun createConnectionString(hostname: String, port: Int, database: String, user: String, password: String): String { return String.format(MYSQL_JDBC_CONNECTION_STRING, hostname, port, database, user, password) } } }
gpl-3.0
2e0db5bbf381731f3ec28c670f35bacc
31
81
0.58125
4.678363
false
false
false
false
Ribesg/anko
dsl/testData/functional/sdk19/ViewTest.kt
2
47638
object `$$Anko$Factories$Sdk19View` { val MEDIA_ROUTE_BUTTON = { ctx: Context -> android.app.MediaRouteButton(ctx) } val GESTURE_OVERLAY_VIEW = { ctx: Context -> android.gesture.GestureOverlayView(ctx) } val EXTRACT_EDIT_TEXT = { ctx: Context -> android.inputmethodservice.ExtractEditText(ctx) } val G_L_SURFACE_VIEW = { ctx: Context -> android.opengl.GLSurfaceView(ctx) } val SURFACE_VIEW = { ctx: Context -> android.view.SurfaceView(ctx) } val TEXTURE_VIEW = { ctx: Context -> android.view.TextureView(ctx) } val VIEW = { ctx: Context -> android.view.View(ctx) } val VIEW_STUB = { ctx: Context -> android.view.ViewStub(ctx) } val ADAPTER_VIEW_FLIPPER = { ctx: Context -> android.widget.AdapterViewFlipper(ctx) } val ANALOG_CLOCK = { ctx: Context -> android.widget.AnalogClock(ctx) } val AUTO_COMPLETE_TEXT_VIEW = { ctx: Context -> android.widget.AutoCompleteTextView(ctx) } val BUTTON = { ctx: Context -> android.widget.Button(ctx) } val CALENDAR_VIEW = { ctx: Context -> android.widget.CalendarView(ctx) } val CHECK_BOX = { ctx: Context -> android.widget.CheckBox(ctx) } val CHECKED_TEXT_VIEW = { ctx: Context -> android.widget.CheckedTextView(ctx) } val CHRONOMETER = { ctx: Context -> android.widget.Chronometer(ctx) } val DATE_PICKER = { ctx: Context -> android.widget.DatePicker(ctx) } val DIALER_FILTER = { ctx: Context -> android.widget.DialerFilter(ctx) } val DIGITAL_CLOCK = { ctx: Context -> android.widget.DigitalClock(ctx) } val EDIT_TEXT = { ctx: Context -> android.widget.EditText(ctx) } val EXPANDABLE_LIST_VIEW = { ctx: Context -> android.widget.ExpandableListView(ctx) } val IMAGE_BUTTON = { ctx: Context -> android.widget.ImageButton(ctx) } val IMAGE_VIEW = { ctx: Context -> android.widget.ImageView(ctx) } val LIST_VIEW = { ctx: Context -> android.widget.ListView(ctx) } val MULTI_AUTO_COMPLETE_TEXT_VIEW = { ctx: Context -> android.widget.MultiAutoCompleteTextView(ctx) } val NUMBER_PICKER = { ctx: Context -> android.widget.NumberPicker(ctx) } val PROGRESS_BAR = { ctx: Context -> android.widget.ProgressBar(ctx) } val QUICK_CONTACT_BADGE = { ctx: Context -> android.widget.QuickContactBadge(ctx) } val RADIO_BUTTON = { ctx: Context -> android.widget.RadioButton(ctx) } val RATING_BAR = { ctx: Context -> android.widget.RatingBar(ctx) } val SEARCH_VIEW = { ctx: Context -> android.widget.SearchView(ctx) } val SEEK_BAR = { ctx: Context -> android.widget.SeekBar(ctx) } val SLIDING_DRAWER = { ctx: Context -> android.widget.SlidingDrawer(ctx, null) } val SPACE = { ctx: Context -> android.widget.Space(ctx) } val SPINNER = { ctx: Context -> android.widget.Spinner(ctx) } val STACK_VIEW = { ctx: Context -> android.widget.StackView(ctx) } val SWITCH = { ctx: Context -> android.widget.Switch(ctx) } val TAB_HOST = { ctx: Context -> android.widget.TabHost(ctx) } val TAB_WIDGET = { ctx: Context -> android.widget.TabWidget(ctx) } val TEXT_CLOCK = { ctx: Context -> android.widget.TextClock(ctx) } val TEXT_VIEW = { ctx: Context -> android.widget.TextView(ctx) } val TIME_PICKER = { ctx: Context -> android.widget.TimePicker(ctx) } val TOGGLE_BUTTON = { ctx: Context -> android.widget.ToggleButton(ctx) } val TWO_LINE_LIST_ITEM = { ctx: Context -> android.widget.TwoLineListItem(ctx) } val VIDEO_VIEW = { ctx: Context -> android.widget.VideoView(ctx) } val VIEW_FLIPPER = { ctx: Context -> android.widget.ViewFlipper(ctx) } val ZOOM_BUTTON = { ctx: Context -> android.widget.ZoomButton(ctx) } val ZOOM_CONTROLS = { ctx: Context -> android.widget.ZoomControls(ctx) } } inline fun ViewManager.mediaRouteButton(): android.app.MediaRouteButton = mediaRouteButton({}) inline fun ViewManager.mediaRouteButton(init: android.app.MediaRouteButton.() -> Unit): android.app.MediaRouteButton { return ankoView(`$$Anko$Factories$Sdk19View`.MEDIA_ROUTE_BUTTON) { init() } } inline fun ViewManager.gestureOverlayView(): android.gesture.GestureOverlayView = gestureOverlayView({}) inline fun ViewManager.gestureOverlayView(init: android.gesture.GestureOverlayView.() -> Unit): android.gesture.GestureOverlayView { return ankoView(`$$Anko$Factories$Sdk19View`.GESTURE_OVERLAY_VIEW) { init() } } inline fun Context.gestureOverlayView(): android.gesture.GestureOverlayView = gestureOverlayView({}) inline fun Context.gestureOverlayView(init: android.gesture.GestureOverlayView.() -> Unit): android.gesture.GestureOverlayView { return ankoView(`$$Anko$Factories$Sdk19View`.GESTURE_OVERLAY_VIEW) { init() } } inline fun Activity.gestureOverlayView(): android.gesture.GestureOverlayView = gestureOverlayView({}) inline fun Activity.gestureOverlayView(init: android.gesture.GestureOverlayView.() -> Unit): android.gesture.GestureOverlayView { return ankoView(`$$Anko$Factories$Sdk19View`.GESTURE_OVERLAY_VIEW) { init() } } inline fun ViewManager.extractEditText(): android.inputmethodservice.ExtractEditText = extractEditText({}) inline fun ViewManager.extractEditText(init: android.inputmethodservice.ExtractEditText.() -> Unit): android.inputmethodservice.ExtractEditText { return ankoView(`$$Anko$Factories$Sdk19View`.EXTRACT_EDIT_TEXT) { init() } } inline fun ViewManager.gLSurfaceView(): android.opengl.GLSurfaceView = gLSurfaceView({}) inline fun ViewManager.gLSurfaceView(init: android.opengl.GLSurfaceView.() -> Unit): android.opengl.GLSurfaceView { return ankoView(`$$Anko$Factories$Sdk19View`.G_L_SURFACE_VIEW) { init() } } inline fun ViewManager.surfaceView(): android.view.SurfaceView = surfaceView({}) inline fun ViewManager.surfaceView(init: android.view.SurfaceView.() -> Unit): android.view.SurfaceView { return ankoView(`$$Anko$Factories$Sdk19View`.SURFACE_VIEW) { init() } } inline fun ViewManager.textureView(): android.view.TextureView = textureView({}) inline fun ViewManager.textureView(init: android.view.TextureView.() -> Unit): android.view.TextureView { return ankoView(`$$Anko$Factories$Sdk19View`.TEXTURE_VIEW) { init() } } inline fun ViewManager.view(): android.view.View = view({}) inline fun ViewManager.view(init: android.view.View.() -> Unit): android.view.View { return ankoView(`$$Anko$Factories$Sdk19View`.VIEW) { init() } } inline fun ViewManager.viewStub(): android.view.ViewStub = viewStub({}) inline fun ViewManager.viewStub(init: android.view.ViewStub.() -> Unit): android.view.ViewStub { return ankoView(`$$Anko$Factories$Sdk19View`.VIEW_STUB) { init() } } inline fun ViewManager.adapterViewFlipper(): android.widget.AdapterViewFlipper = adapterViewFlipper({}) inline fun ViewManager.adapterViewFlipper(init: android.widget.AdapterViewFlipper.() -> Unit): android.widget.AdapterViewFlipper { return ankoView(`$$Anko$Factories$Sdk19View`.ADAPTER_VIEW_FLIPPER) { init() } } inline fun Context.adapterViewFlipper(): android.widget.AdapterViewFlipper = adapterViewFlipper({}) inline fun Context.adapterViewFlipper(init: android.widget.AdapterViewFlipper.() -> Unit): android.widget.AdapterViewFlipper { return ankoView(`$$Anko$Factories$Sdk19View`.ADAPTER_VIEW_FLIPPER) { init() } } inline fun Activity.adapterViewFlipper(): android.widget.AdapterViewFlipper = adapterViewFlipper({}) inline fun Activity.adapterViewFlipper(init: android.widget.AdapterViewFlipper.() -> Unit): android.widget.AdapterViewFlipper { return ankoView(`$$Anko$Factories$Sdk19View`.ADAPTER_VIEW_FLIPPER) { init() } } inline fun ViewManager.analogClock(): android.widget.AnalogClock = analogClock({}) inline fun ViewManager.analogClock(init: android.widget.AnalogClock.() -> Unit): android.widget.AnalogClock { return ankoView(`$$Anko$Factories$Sdk19View`.ANALOG_CLOCK) { init() } } inline fun ViewManager.autoCompleteTextView(): android.widget.AutoCompleteTextView = autoCompleteTextView({}) inline fun ViewManager.autoCompleteTextView(init: android.widget.AutoCompleteTextView.() -> Unit): android.widget.AutoCompleteTextView { return ankoView(`$$Anko$Factories$Sdk19View`.AUTO_COMPLETE_TEXT_VIEW) { init() } } inline fun ViewManager.button(): android.widget.Button = button({}) inline fun ViewManager.button(init: android.widget.Button.() -> Unit): android.widget.Button { return ankoView(`$$Anko$Factories$Sdk19View`.BUTTON) { init() } } inline fun ViewManager.button(text: CharSequence?): android.widget.Button { return ankoView(`$$Anko$Factories$Sdk19View`.BUTTON) { setText(text) } } inline fun ViewManager.button(text: CharSequence?, init: android.widget.Button.() -> Unit): android.widget.Button { return ankoView(`$$Anko$Factories$Sdk19View`.BUTTON) { init() setText(text) } } inline fun ViewManager.button(text: Int): android.widget.Button { return ankoView(`$$Anko$Factories$Sdk19View`.BUTTON) { setText(text) } } inline fun ViewManager.button(text: Int, init: android.widget.Button.() -> Unit): android.widget.Button { return ankoView(`$$Anko$Factories$Sdk19View`.BUTTON) { init() setText(text) } } inline fun ViewManager.calendarView(): android.widget.CalendarView = calendarView({}) inline fun ViewManager.calendarView(init: android.widget.CalendarView.() -> Unit): android.widget.CalendarView { return ankoView(`$$Anko$Factories$Sdk19View`.CALENDAR_VIEW) { init() } } inline fun Context.calendarView(): android.widget.CalendarView = calendarView({}) inline fun Context.calendarView(init: android.widget.CalendarView.() -> Unit): android.widget.CalendarView { return ankoView(`$$Anko$Factories$Sdk19View`.CALENDAR_VIEW) { init() } } inline fun Activity.calendarView(): android.widget.CalendarView = calendarView({}) inline fun Activity.calendarView(init: android.widget.CalendarView.() -> Unit): android.widget.CalendarView { return ankoView(`$$Anko$Factories$Sdk19View`.CALENDAR_VIEW) { init() } } inline fun ViewManager.checkBox(): android.widget.CheckBox = checkBox({}) inline fun ViewManager.checkBox(init: android.widget.CheckBox.() -> Unit): android.widget.CheckBox { return ankoView(`$$Anko$Factories$Sdk19View`.CHECK_BOX) { init() } } inline fun ViewManager.checkBox(text: CharSequence?): android.widget.CheckBox { return ankoView(`$$Anko$Factories$Sdk19View`.CHECK_BOX) { setText(text) } } inline fun ViewManager.checkBox(text: CharSequence?, init: android.widget.CheckBox.() -> Unit): android.widget.CheckBox { return ankoView(`$$Anko$Factories$Sdk19View`.CHECK_BOX) { init() setText(text) } } inline fun ViewManager.checkBox(text: Int): android.widget.CheckBox { return ankoView(`$$Anko$Factories$Sdk19View`.CHECK_BOX) { setText(text) } } inline fun ViewManager.checkBox(text: Int, init: android.widget.CheckBox.() -> Unit): android.widget.CheckBox { return ankoView(`$$Anko$Factories$Sdk19View`.CHECK_BOX) { init() setText(text) } } inline fun ViewManager.checkBox(text: CharSequence?, checked: Boolean): android.widget.CheckBox { return ankoView(`$$Anko$Factories$Sdk19View`.CHECK_BOX) { setText(text) setChecked(checked) } } inline fun ViewManager.checkBox(text: CharSequence?, checked: Boolean, init: android.widget.CheckBox.() -> Unit): android.widget.CheckBox { return ankoView(`$$Anko$Factories$Sdk19View`.CHECK_BOX) { init() setText(text) setChecked(checked) } } inline fun ViewManager.checkBox(text: Int, checked: Boolean): android.widget.CheckBox { return ankoView(`$$Anko$Factories$Sdk19View`.CHECK_BOX) { setText(text) setChecked(checked) } } inline fun ViewManager.checkBox(text: Int, checked: Boolean, init: android.widget.CheckBox.() -> Unit): android.widget.CheckBox { return ankoView(`$$Anko$Factories$Sdk19View`.CHECK_BOX) { init() setText(text) setChecked(checked) } } inline fun ViewManager.checkedTextView(): android.widget.CheckedTextView = checkedTextView({}) inline fun ViewManager.checkedTextView(init: android.widget.CheckedTextView.() -> Unit): android.widget.CheckedTextView { return ankoView(`$$Anko$Factories$Sdk19View`.CHECKED_TEXT_VIEW) { init() } } inline fun ViewManager.chronometer(): android.widget.Chronometer = chronometer({}) inline fun ViewManager.chronometer(init: android.widget.Chronometer.() -> Unit): android.widget.Chronometer { return ankoView(`$$Anko$Factories$Sdk19View`.CHRONOMETER) { init() } } inline fun ViewManager.datePicker(): android.widget.DatePicker = datePicker({}) inline fun ViewManager.datePicker(init: android.widget.DatePicker.() -> Unit): android.widget.DatePicker { return ankoView(`$$Anko$Factories$Sdk19View`.DATE_PICKER) { init() } } inline fun Context.datePicker(): android.widget.DatePicker = datePicker({}) inline fun Context.datePicker(init: android.widget.DatePicker.() -> Unit): android.widget.DatePicker { return ankoView(`$$Anko$Factories$Sdk19View`.DATE_PICKER) { init() } } inline fun Activity.datePicker(): android.widget.DatePicker = datePicker({}) inline fun Activity.datePicker(init: android.widget.DatePicker.() -> Unit): android.widget.DatePicker { return ankoView(`$$Anko$Factories$Sdk19View`.DATE_PICKER) { init() } } inline fun ViewManager.dialerFilter(): android.widget.DialerFilter = dialerFilter({}) inline fun ViewManager.dialerFilter(init: android.widget.DialerFilter.() -> Unit): android.widget.DialerFilter { return ankoView(`$$Anko$Factories$Sdk19View`.DIALER_FILTER) { init() } } inline fun Context.dialerFilter(): android.widget.DialerFilter = dialerFilter({}) inline fun Context.dialerFilter(init: android.widget.DialerFilter.() -> Unit): android.widget.DialerFilter { return ankoView(`$$Anko$Factories$Sdk19View`.DIALER_FILTER) { init() } } inline fun Activity.dialerFilter(): android.widget.DialerFilter = dialerFilter({}) inline fun Activity.dialerFilter(init: android.widget.DialerFilter.() -> Unit): android.widget.DialerFilter { return ankoView(`$$Anko$Factories$Sdk19View`.DIALER_FILTER) { init() } } inline fun ViewManager.digitalClock(): android.widget.DigitalClock = digitalClock({}) inline fun ViewManager.digitalClock(init: android.widget.DigitalClock.() -> Unit): android.widget.DigitalClock { return ankoView(`$$Anko$Factories$Sdk19View`.DIGITAL_CLOCK) { init() } } inline fun ViewManager.editText(): android.widget.EditText = editText({}) inline fun ViewManager.editText(init: android.widget.EditText.() -> Unit): android.widget.EditText { return ankoView(`$$Anko$Factories$Sdk19View`.EDIT_TEXT) { init() } } inline fun ViewManager.editText(text: CharSequence?): android.widget.EditText { return ankoView(`$$Anko$Factories$Sdk19View`.EDIT_TEXT) { setText(text) } } inline fun ViewManager.editText(text: CharSequence?, init: android.widget.EditText.() -> Unit): android.widget.EditText { return ankoView(`$$Anko$Factories$Sdk19View`.EDIT_TEXT) { init() setText(text) } } inline fun ViewManager.editText(text: Int): android.widget.EditText { return ankoView(`$$Anko$Factories$Sdk19View`.EDIT_TEXT) { setText(text) } } inline fun ViewManager.editText(text: Int, init: android.widget.EditText.() -> Unit): android.widget.EditText { return ankoView(`$$Anko$Factories$Sdk19View`.EDIT_TEXT) { init() setText(text) } } inline fun ViewManager.expandableListView(): android.widget.ExpandableListView = expandableListView({}) inline fun ViewManager.expandableListView(init: android.widget.ExpandableListView.() -> Unit): android.widget.ExpandableListView { return ankoView(`$$Anko$Factories$Sdk19View`.EXPANDABLE_LIST_VIEW) { init() } } inline fun Context.expandableListView(): android.widget.ExpandableListView = expandableListView({}) inline fun Context.expandableListView(init: android.widget.ExpandableListView.() -> Unit): android.widget.ExpandableListView { return ankoView(`$$Anko$Factories$Sdk19View`.EXPANDABLE_LIST_VIEW) { init() } } inline fun Activity.expandableListView(): android.widget.ExpandableListView = expandableListView({}) inline fun Activity.expandableListView(init: android.widget.ExpandableListView.() -> Unit): android.widget.ExpandableListView { return ankoView(`$$Anko$Factories$Sdk19View`.EXPANDABLE_LIST_VIEW) { init() } } inline fun ViewManager.imageButton(): android.widget.ImageButton = imageButton({}) inline fun ViewManager.imageButton(init: android.widget.ImageButton.() -> Unit): android.widget.ImageButton { return ankoView(`$$Anko$Factories$Sdk19View`.IMAGE_BUTTON) { init() } } inline fun ViewManager.imageButton(imageDrawable: android.graphics.drawable.Drawable?): android.widget.ImageButton { return ankoView(`$$Anko$Factories$Sdk19View`.IMAGE_BUTTON) { setImageDrawable(imageDrawable) } } inline fun ViewManager.imageButton(imageDrawable: android.graphics.drawable.Drawable?, init: android.widget.ImageButton.() -> Unit): android.widget.ImageButton { return ankoView(`$$Anko$Factories$Sdk19View`.IMAGE_BUTTON) { init() setImageDrawable(imageDrawable) } } inline fun ViewManager.imageButton(imageResource: Int): android.widget.ImageButton { return ankoView(`$$Anko$Factories$Sdk19View`.IMAGE_BUTTON) { setImageResource(imageResource) } } inline fun ViewManager.imageButton(imageResource: Int, init: android.widget.ImageButton.() -> Unit): android.widget.ImageButton { return ankoView(`$$Anko$Factories$Sdk19View`.IMAGE_BUTTON) { init() setImageResource(imageResource) } } inline fun ViewManager.imageView(): android.widget.ImageView = imageView({}) inline fun ViewManager.imageView(init: android.widget.ImageView.() -> Unit): android.widget.ImageView { return ankoView(`$$Anko$Factories$Sdk19View`.IMAGE_VIEW) { init() } } inline fun ViewManager.imageView(imageDrawable: android.graphics.drawable.Drawable?): android.widget.ImageView { return ankoView(`$$Anko$Factories$Sdk19View`.IMAGE_VIEW) { setImageDrawable(imageDrawable) } } inline fun ViewManager.imageView(imageDrawable: android.graphics.drawable.Drawable?, init: android.widget.ImageView.() -> Unit): android.widget.ImageView { return ankoView(`$$Anko$Factories$Sdk19View`.IMAGE_VIEW) { init() setImageDrawable(imageDrawable) } } inline fun ViewManager.imageView(imageResource: Int): android.widget.ImageView { return ankoView(`$$Anko$Factories$Sdk19View`.IMAGE_VIEW) { setImageResource(imageResource) } } inline fun ViewManager.imageView(imageResource: Int, init: android.widget.ImageView.() -> Unit): android.widget.ImageView { return ankoView(`$$Anko$Factories$Sdk19View`.IMAGE_VIEW) { init() setImageResource(imageResource) } } inline fun ViewManager.listView(): android.widget.ListView = listView({}) inline fun ViewManager.listView(init: android.widget.ListView.() -> Unit): android.widget.ListView { return ankoView(`$$Anko$Factories$Sdk19View`.LIST_VIEW) { init() } } inline fun Context.listView(): android.widget.ListView = listView({}) inline fun Context.listView(init: android.widget.ListView.() -> Unit): android.widget.ListView { return ankoView(`$$Anko$Factories$Sdk19View`.LIST_VIEW) { init() } } inline fun Activity.listView(): android.widget.ListView = listView({}) inline fun Activity.listView(init: android.widget.ListView.() -> Unit): android.widget.ListView { return ankoView(`$$Anko$Factories$Sdk19View`.LIST_VIEW) { init() } } inline fun ViewManager.multiAutoCompleteTextView(): android.widget.MultiAutoCompleteTextView = multiAutoCompleteTextView({}) inline fun ViewManager.multiAutoCompleteTextView(init: android.widget.MultiAutoCompleteTextView.() -> Unit): android.widget.MultiAutoCompleteTextView { return ankoView(`$$Anko$Factories$Sdk19View`.MULTI_AUTO_COMPLETE_TEXT_VIEW) { init() } } inline fun ViewManager.numberPicker(): android.widget.NumberPicker = numberPicker({}) inline fun ViewManager.numberPicker(init: android.widget.NumberPicker.() -> Unit): android.widget.NumberPicker { return ankoView(`$$Anko$Factories$Sdk19View`.NUMBER_PICKER) { init() } } inline fun Context.numberPicker(): android.widget.NumberPicker = numberPicker({}) inline fun Context.numberPicker(init: android.widget.NumberPicker.() -> Unit): android.widget.NumberPicker { return ankoView(`$$Anko$Factories$Sdk19View`.NUMBER_PICKER) { init() } } inline fun Activity.numberPicker(): android.widget.NumberPicker = numberPicker({}) inline fun Activity.numberPicker(init: android.widget.NumberPicker.() -> Unit): android.widget.NumberPicker { return ankoView(`$$Anko$Factories$Sdk19View`.NUMBER_PICKER) { init() } } inline fun ViewManager.progressBar(): android.widget.ProgressBar = progressBar({}) inline fun ViewManager.progressBar(init: android.widget.ProgressBar.() -> Unit): android.widget.ProgressBar { return ankoView(`$$Anko$Factories$Sdk19View`.PROGRESS_BAR) { init() } } inline fun ViewManager.quickContactBadge(): android.widget.QuickContactBadge = quickContactBadge({}) inline fun ViewManager.quickContactBadge(init: android.widget.QuickContactBadge.() -> Unit): android.widget.QuickContactBadge { return ankoView(`$$Anko$Factories$Sdk19View`.QUICK_CONTACT_BADGE) { init() } } inline fun ViewManager.radioButton(): android.widget.RadioButton = radioButton({}) inline fun ViewManager.radioButton(init: android.widget.RadioButton.() -> Unit): android.widget.RadioButton { return ankoView(`$$Anko$Factories$Sdk19View`.RADIO_BUTTON) { init() } } inline fun ViewManager.ratingBar(): android.widget.RatingBar = ratingBar({}) inline fun ViewManager.ratingBar(init: android.widget.RatingBar.() -> Unit): android.widget.RatingBar { return ankoView(`$$Anko$Factories$Sdk19View`.RATING_BAR) { init() } } inline fun ViewManager.searchView(): android.widget.SearchView = searchView({}) inline fun ViewManager.searchView(init: android.widget.SearchView.() -> Unit): android.widget.SearchView { return ankoView(`$$Anko$Factories$Sdk19View`.SEARCH_VIEW) { init() } } inline fun Context.searchView(): android.widget.SearchView = searchView({}) inline fun Context.searchView(init: android.widget.SearchView.() -> Unit): android.widget.SearchView { return ankoView(`$$Anko$Factories$Sdk19View`.SEARCH_VIEW) { init() } } inline fun Activity.searchView(): android.widget.SearchView = searchView({}) inline fun Activity.searchView(init: android.widget.SearchView.() -> Unit): android.widget.SearchView { return ankoView(`$$Anko$Factories$Sdk19View`.SEARCH_VIEW) { init() } } inline fun ViewManager.seekBar(): android.widget.SeekBar = seekBar({}) inline fun ViewManager.seekBar(init: android.widget.SeekBar.() -> Unit): android.widget.SeekBar { return ankoView(`$$Anko$Factories$Sdk19View`.SEEK_BAR) { init() } } inline fun ViewManager.slidingDrawer(): android.widget.SlidingDrawer = slidingDrawer({}) inline fun ViewManager.slidingDrawer(init: android.widget.SlidingDrawer.() -> Unit): android.widget.SlidingDrawer { return ankoView(`$$Anko$Factories$Sdk19View`.SLIDING_DRAWER) { init() } } inline fun Context.slidingDrawer(): android.widget.SlidingDrawer = slidingDrawer({}) inline fun Context.slidingDrawer(init: android.widget.SlidingDrawer.() -> Unit): android.widget.SlidingDrawer { return ankoView(`$$Anko$Factories$Sdk19View`.SLIDING_DRAWER) { init() } } inline fun Activity.slidingDrawer(): android.widget.SlidingDrawer = slidingDrawer({}) inline fun Activity.slidingDrawer(init: android.widget.SlidingDrawer.() -> Unit): android.widget.SlidingDrawer { return ankoView(`$$Anko$Factories$Sdk19View`.SLIDING_DRAWER) { init() } } inline fun ViewManager.space(): android.widget.Space = space({}) inline fun ViewManager.space(init: android.widget.Space.() -> Unit): android.widget.Space { return ankoView(`$$Anko$Factories$Sdk19View`.SPACE) { init() } } inline fun ViewManager.spinner(): android.widget.Spinner = spinner({}) inline fun ViewManager.spinner(init: android.widget.Spinner.() -> Unit): android.widget.Spinner { return ankoView(`$$Anko$Factories$Sdk19View`.SPINNER) { init() } } inline fun Context.spinner(): android.widget.Spinner = spinner({}) inline fun Context.spinner(init: android.widget.Spinner.() -> Unit): android.widget.Spinner { return ankoView(`$$Anko$Factories$Sdk19View`.SPINNER) { init() } } inline fun Activity.spinner(): android.widget.Spinner = spinner({}) inline fun Activity.spinner(init: android.widget.Spinner.() -> Unit): android.widget.Spinner { return ankoView(`$$Anko$Factories$Sdk19View`.SPINNER) { init() } } inline fun ViewManager.stackView(): android.widget.StackView = stackView({}) inline fun ViewManager.stackView(init: android.widget.StackView.() -> Unit): android.widget.StackView { return ankoView(`$$Anko$Factories$Sdk19View`.STACK_VIEW) { init() } } inline fun Context.stackView(): android.widget.StackView = stackView({}) inline fun Context.stackView(init: android.widget.StackView.() -> Unit): android.widget.StackView { return ankoView(`$$Anko$Factories$Sdk19View`.STACK_VIEW) { init() } } inline fun Activity.stackView(): android.widget.StackView = stackView({}) inline fun Activity.stackView(init: android.widget.StackView.() -> Unit): android.widget.StackView { return ankoView(`$$Anko$Factories$Sdk19View`.STACK_VIEW) { init() } } inline fun ViewManager.switch(): android.widget.Switch = switch({}) inline fun ViewManager.switch(init: android.widget.Switch.() -> Unit): android.widget.Switch { return ankoView(`$$Anko$Factories$Sdk19View`.SWITCH) { init() } } inline fun ViewManager.tabHost(): android.widget.TabHost = tabHost({}) inline fun ViewManager.tabHost(init: android.widget.TabHost.() -> Unit): android.widget.TabHost { return ankoView(`$$Anko$Factories$Sdk19View`.TAB_HOST) { init() } } inline fun Context.tabHost(): android.widget.TabHost = tabHost({}) inline fun Context.tabHost(init: android.widget.TabHost.() -> Unit): android.widget.TabHost { return ankoView(`$$Anko$Factories$Sdk19View`.TAB_HOST) { init() } } inline fun Activity.tabHost(): android.widget.TabHost = tabHost({}) inline fun Activity.tabHost(init: android.widget.TabHost.() -> Unit): android.widget.TabHost { return ankoView(`$$Anko$Factories$Sdk19View`.TAB_HOST) { init() } } inline fun ViewManager.tabWidget(): android.widget.TabWidget = tabWidget({}) inline fun ViewManager.tabWidget(init: android.widget.TabWidget.() -> Unit): android.widget.TabWidget { return ankoView(`$$Anko$Factories$Sdk19View`.TAB_WIDGET) { init() } } inline fun Context.tabWidget(): android.widget.TabWidget = tabWidget({}) inline fun Context.tabWidget(init: android.widget.TabWidget.() -> Unit): android.widget.TabWidget { return ankoView(`$$Anko$Factories$Sdk19View`.TAB_WIDGET) { init() } } inline fun Activity.tabWidget(): android.widget.TabWidget = tabWidget({}) inline fun Activity.tabWidget(init: android.widget.TabWidget.() -> Unit): android.widget.TabWidget { return ankoView(`$$Anko$Factories$Sdk19View`.TAB_WIDGET) { init() } } inline fun ViewManager.textClock(): android.widget.TextClock = textClock({}) inline fun ViewManager.textClock(init: android.widget.TextClock.() -> Unit): android.widget.TextClock { return ankoView(`$$Anko$Factories$Sdk19View`.TEXT_CLOCK) { init() } } inline fun ViewManager.textView(): android.widget.TextView = textView({}) inline fun ViewManager.textView(init: android.widget.TextView.() -> Unit): android.widget.TextView { return ankoView(`$$Anko$Factories$Sdk19View`.TEXT_VIEW) { init() } } inline fun ViewManager.textView(text: CharSequence?): android.widget.TextView { return ankoView(`$$Anko$Factories$Sdk19View`.TEXT_VIEW) { setText(text) } } inline fun ViewManager.textView(text: CharSequence?, init: android.widget.TextView.() -> Unit): android.widget.TextView { return ankoView(`$$Anko$Factories$Sdk19View`.TEXT_VIEW) { init() setText(text) } } inline fun ViewManager.textView(text: Int): android.widget.TextView { return ankoView(`$$Anko$Factories$Sdk19View`.TEXT_VIEW) { setText(text) } } inline fun ViewManager.textView(text: Int, init: android.widget.TextView.() -> Unit): android.widget.TextView { return ankoView(`$$Anko$Factories$Sdk19View`.TEXT_VIEW) { init() setText(text) } } inline fun ViewManager.timePicker(): android.widget.TimePicker = timePicker({}) inline fun ViewManager.timePicker(init: android.widget.TimePicker.() -> Unit): android.widget.TimePicker { return ankoView(`$$Anko$Factories$Sdk19View`.TIME_PICKER) { init() } } inline fun Context.timePicker(): android.widget.TimePicker = timePicker({}) inline fun Context.timePicker(init: android.widget.TimePicker.() -> Unit): android.widget.TimePicker { return ankoView(`$$Anko$Factories$Sdk19View`.TIME_PICKER) { init() } } inline fun Activity.timePicker(): android.widget.TimePicker = timePicker({}) inline fun Activity.timePicker(init: android.widget.TimePicker.() -> Unit): android.widget.TimePicker { return ankoView(`$$Anko$Factories$Sdk19View`.TIME_PICKER) { init() } } inline fun ViewManager.toggleButton(): android.widget.ToggleButton = toggleButton({}) inline fun ViewManager.toggleButton(init: android.widget.ToggleButton.() -> Unit): android.widget.ToggleButton { return ankoView(`$$Anko$Factories$Sdk19View`.TOGGLE_BUTTON) { init() } } inline fun ViewManager.twoLineListItem(): android.widget.TwoLineListItem = twoLineListItem({}) inline fun ViewManager.twoLineListItem(init: android.widget.TwoLineListItem.() -> Unit): android.widget.TwoLineListItem { return ankoView(`$$Anko$Factories$Sdk19View`.TWO_LINE_LIST_ITEM) { init() } } inline fun Context.twoLineListItem(): android.widget.TwoLineListItem = twoLineListItem({}) inline fun Context.twoLineListItem(init: android.widget.TwoLineListItem.() -> Unit): android.widget.TwoLineListItem { return ankoView(`$$Anko$Factories$Sdk19View`.TWO_LINE_LIST_ITEM) { init() } } inline fun Activity.twoLineListItem(): android.widget.TwoLineListItem = twoLineListItem({}) inline fun Activity.twoLineListItem(init: android.widget.TwoLineListItem.() -> Unit): android.widget.TwoLineListItem { return ankoView(`$$Anko$Factories$Sdk19View`.TWO_LINE_LIST_ITEM) { init() } } inline fun ViewManager.videoView(): android.widget.VideoView = videoView({}) inline fun ViewManager.videoView(init: android.widget.VideoView.() -> Unit): android.widget.VideoView { return ankoView(`$$Anko$Factories$Sdk19View`.VIDEO_VIEW) { init() } } inline fun ViewManager.viewFlipper(): android.widget.ViewFlipper = viewFlipper({}) inline fun ViewManager.viewFlipper(init: android.widget.ViewFlipper.() -> Unit): android.widget.ViewFlipper { return ankoView(`$$Anko$Factories$Sdk19View`.VIEW_FLIPPER) { init() } } inline fun Context.viewFlipper(): android.widget.ViewFlipper = viewFlipper({}) inline fun Context.viewFlipper(init: android.widget.ViewFlipper.() -> Unit): android.widget.ViewFlipper { return ankoView(`$$Anko$Factories$Sdk19View`.VIEW_FLIPPER) { init() } } inline fun Activity.viewFlipper(): android.widget.ViewFlipper = viewFlipper({}) inline fun Activity.viewFlipper(init: android.widget.ViewFlipper.() -> Unit): android.widget.ViewFlipper { return ankoView(`$$Anko$Factories$Sdk19View`.VIEW_FLIPPER) { init() } } inline fun ViewManager.zoomButton(): android.widget.ZoomButton = zoomButton({}) inline fun ViewManager.zoomButton(init: android.widget.ZoomButton.() -> Unit): android.widget.ZoomButton { return ankoView(`$$Anko$Factories$Sdk19View`.ZOOM_BUTTON) { init() } } inline fun ViewManager.zoomControls(): android.widget.ZoomControls = zoomControls({}) inline fun ViewManager.zoomControls(init: android.widget.ZoomControls.() -> Unit): android.widget.ZoomControls { return ankoView(`$$Anko$Factories$Sdk19View`.ZOOM_CONTROLS) { init() } } inline fun Context.zoomControls(): android.widget.ZoomControls = zoomControls({}) inline fun Context.zoomControls(init: android.widget.ZoomControls.() -> Unit): android.widget.ZoomControls { return ankoView(`$$Anko$Factories$Sdk19View`.ZOOM_CONTROLS) { init() } } inline fun Activity.zoomControls(): android.widget.ZoomControls = zoomControls({}) inline fun Activity.zoomControls(init: android.widget.ZoomControls.() -> Unit): android.widget.ZoomControls { return ankoView(`$$Anko$Factories$Sdk19View`.ZOOM_CONTROLS) { init() } } object `$$Anko$Factories$Sdk19ViewGroup` { val APP_WIDGET_HOST_VIEW = { ctx: Context -> _AppWidgetHostView(ctx) } val WEB_VIEW = { ctx: Context -> _WebView(ctx) } val ABSOLUTE_LAYOUT = { ctx: Context -> _AbsoluteLayout(ctx) } val FRAME_LAYOUT = { ctx: Context -> _FrameLayout(ctx) } val GALLERY = { ctx: Context -> _Gallery(ctx) } val GRID_LAYOUT = { ctx: Context -> _GridLayout(ctx) } val GRID_VIEW = { ctx: Context -> _GridView(ctx) } val HORIZONTAL_SCROLL_VIEW = { ctx: Context -> _HorizontalScrollView(ctx) } val IMAGE_SWITCHER = { ctx: Context -> _ImageSwitcher(ctx) } val LINEAR_LAYOUT = { ctx: Context -> _LinearLayout(ctx) } val RADIO_GROUP = { ctx: Context -> _RadioGroup(ctx) } val RELATIVE_LAYOUT = { ctx: Context -> _RelativeLayout(ctx) } val SCROLL_VIEW = { ctx: Context -> _ScrollView(ctx) } val TABLE_LAYOUT = { ctx: Context -> _TableLayout(ctx) } val TABLE_ROW = { ctx: Context -> _TableRow(ctx) } val TEXT_SWITCHER = { ctx: Context -> _TextSwitcher(ctx) } val VIEW_ANIMATOR = { ctx: Context -> _ViewAnimator(ctx) } val VIEW_SWITCHER = { ctx: Context -> _ViewSwitcher(ctx) } } inline fun ViewManager.appWidgetHostView(): android.appwidget.AppWidgetHostView = appWidgetHostView({}) inline fun ViewManager.appWidgetHostView(init: _AppWidgetHostView.() -> Unit): android.appwidget.AppWidgetHostView { return ankoView(`$$Anko$Factories$Sdk19ViewGroup`.APP_WIDGET_HOST_VIEW) { init() } } inline fun Context.appWidgetHostView(): android.appwidget.AppWidgetHostView = appWidgetHostView({}) inline fun Context.appWidgetHostView(init: _AppWidgetHostView.() -> Unit): android.appwidget.AppWidgetHostView { return ankoView(`$$Anko$Factories$Sdk19ViewGroup`.APP_WIDGET_HOST_VIEW) { init() } } inline fun Activity.appWidgetHostView(): android.appwidget.AppWidgetHostView = appWidgetHostView({}) inline fun Activity.appWidgetHostView(init: _AppWidgetHostView.() -> Unit): android.appwidget.AppWidgetHostView { return ankoView(`$$Anko$Factories$Sdk19ViewGroup`.APP_WIDGET_HOST_VIEW) { init() } } inline fun ViewManager.webView(): android.webkit.WebView = webView({}) inline fun ViewManager.webView(init: _WebView.() -> Unit): android.webkit.WebView { return ankoView(`$$Anko$Factories$Sdk19ViewGroup`.WEB_VIEW) { init() } } inline fun Context.webView(): android.webkit.WebView = webView({}) inline fun Context.webView(init: _WebView.() -> Unit): android.webkit.WebView { return ankoView(`$$Anko$Factories$Sdk19ViewGroup`.WEB_VIEW) { init() } } inline fun Activity.webView(): android.webkit.WebView = webView({}) inline fun Activity.webView(init: _WebView.() -> Unit): android.webkit.WebView { return ankoView(`$$Anko$Factories$Sdk19ViewGroup`.WEB_VIEW) { init() } } inline fun ViewManager.absoluteLayout(): android.widget.AbsoluteLayout = absoluteLayout({}) inline fun ViewManager.absoluteLayout(init: _AbsoluteLayout.() -> Unit): android.widget.AbsoluteLayout { return ankoView(`$$Anko$Factories$Sdk19ViewGroup`.ABSOLUTE_LAYOUT) { init() } } inline fun Context.absoluteLayout(): android.widget.AbsoluteLayout = absoluteLayout({}) inline fun Context.absoluteLayout(init: _AbsoluteLayout.() -> Unit): android.widget.AbsoluteLayout { return ankoView(`$$Anko$Factories$Sdk19ViewGroup`.ABSOLUTE_LAYOUT) { init() } } inline fun Activity.absoluteLayout(): android.widget.AbsoluteLayout = absoluteLayout({}) inline fun Activity.absoluteLayout(init: _AbsoluteLayout.() -> Unit): android.widget.AbsoluteLayout { return ankoView(`$$Anko$Factories$Sdk19ViewGroup`.ABSOLUTE_LAYOUT) { init() } } inline fun ViewManager.frameLayout(): android.widget.FrameLayout = frameLayout({}) inline fun ViewManager.frameLayout(init: _FrameLayout.() -> Unit): android.widget.FrameLayout { return ankoView(`$$Anko$Factories$Sdk19ViewGroup`.FRAME_LAYOUT) { init() } } inline fun Context.frameLayout(): android.widget.FrameLayout = frameLayout({}) inline fun Context.frameLayout(init: _FrameLayout.() -> Unit): android.widget.FrameLayout { return ankoView(`$$Anko$Factories$Sdk19ViewGroup`.FRAME_LAYOUT) { init() } } inline fun Activity.frameLayout(): android.widget.FrameLayout = frameLayout({}) inline fun Activity.frameLayout(init: _FrameLayout.() -> Unit): android.widget.FrameLayout { return ankoView(`$$Anko$Factories$Sdk19ViewGroup`.FRAME_LAYOUT) { init() } } inline fun ViewManager.gallery(): android.widget.Gallery = gallery({}) inline fun ViewManager.gallery(init: _Gallery.() -> Unit): android.widget.Gallery { return ankoView(`$$Anko$Factories$Sdk19ViewGroup`.GALLERY) { init() } } inline fun Context.gallery(): android.widget.Gallery = gallery({}) inline fun Context.gallery(init: _Gallery.() -> Unit): android.widget.Gallery { return ankoView(`$$Anko$Factories$Sdk19ViewGroup`.GALLERY) { init() } } inline fun Activity.gallery(): android.widget.Gallery = gallery({}) inline fun Activity.gallery(init: _Gallery.() -> Unit): android.widget.Gallery { return ankoView(`$$Anko$Factories$Sdk19ViewGroup`.GALLERY) { init() } } inline fun ViewManager.gridLayout(): android.widget.GridLayout = gridLayout({}) inline fun ViewManager.gridLayout(init: _GridLayout.() -> Unit): android.widget.GridLayout { return ankoView(`$$Anko$Factories$Sdk19ViewGroup`.GRID_LAYOUT) { init() } } inline fun Context.gridLayout(): android.widget.GridLayout = gridLayout({}) inline fun Context.gridLayout(init: _GridLayout.() -> Unit): android.widget.GridLayout { return ankoView(`$$Anko$Factories$Sdk19ViewGroup`.GRID_LAYOUT) { init() } } inline fun Activity.gridLayout(): android.widget.GridLayout = gridLayout({}) inline fun Activity.gridLayout(init: _GridLayout.() -> Unit): android.widget.GridLayout { return ankoView(`$$Anko$Factories$Sdk19ViewGroup`.GRID_LAYOUT) { init() } } inline fun ViewManager.gridView(): android.widget.GridView = gridView({}) inline fun ViewManager.gridView(init: _GridView.() -> Unit): android.widget.GridView { return ankoView(`$$Anko$Factories$Sdk19ViewGroup`.GRID_VIEW) { init() } } inline fun Context.gridView(): android.widget.GridView = gridView({}) inline fun Context.gridView(init: _GridView.() -> Unit): android.widget.GridView { return ankoView(`$$Anko$Factories$Sdk19ViewGroup`.GRID_VIEW) { init() } } inline fun Activity.gridView(): android.widget.GridView = gridView({}) inline fun Activity.gridView(init: _GridView.() -> Unit): android.widget.GridView { return ankoView(`$$Anko$Factories$Sdk19ViewGroup`.GRID_VIEW) { init() } } inline fun ViewManager.horizontalScrollView(): android.widget.HorizontalScrollView = horizontalScrollView({}) inline fun ViewManager.horizontalScrollView(init: _HorizontalScrollView.() -> Unit): android.widget.HorizontalScrollView { return ankoView(`$$Anko$Factories$Sdk19ViewGroup`.HORIZONTAL_SCROLL_VIEW) { init() } } inline fun Context.horizontalScrollView(): android.widget.HorizontalScrollView = horizontalScrollView({}) inline fun Context.horizontalScrollView(init: _HorizontalScrollView.() -> Unit): android.widget.HorizontalScrollView { return ankoView(`$$Anko$Factories$Sdk19ViewGroup`.HORIZONTAL_SCROLL_VIEW) { init() } } inline fun Activity.horizontalScrollView(): android.widget.HorizontalScrollView = horizontalScrollView({}) inline fun Activity.horizontalScrollView(init: _HorizontalScrollView.() -> Unit): android.widget.HorizontalScrollView { return ankoView(`$$Anko$Factories$Sdk19ViewGroup`.HORIZONTAL_SCROLL_VIEW) { init() } } inline fun ViewManager.imageSwitcher(): android.widget.ImageSwitcher = imageSwitcher({}) inline fun ViewManager.imageSwitcher(init: _ImageSwitcher.() -> Unit): android.widget.ImageSwitcher { return ankoView(`$$Anko$Factories$Sdk19ViewGroup`.IMAGE_SWITCHER) { init() } } inline fun Context.imageSwitcher(): android.widget.ImageSwitcher = imageSwitcher({}) inline fun Context.imageSwitcher(init: _ImageSwitcher.() -> Unit): android.widget.ImageSwitcher { return ankoView(`$$Anko$Factories$Sdk19ViewGroup`.IMAGE_SWITCHER) { init() } } inline fun Activity.imageSwitcher(): android.widget.ImageSwitcher = imageSwitcher({}) inline fun Activity.imageSwitcher(init: _ImageSwitcher.() -> Unit): android.widget.ImageSwitcher { return ankoView(`$$Anko$Factories$Sdk19ViewGroup`.IMAGE_SWITCHER) { init() } } inline fun ViewManager.linearLayout(): android.widget.LinearLayout = linearLayout({}) inline fun ViewManager.linearLayout(init: _LinearLayout.() -> Unit): android.widget.LinearLayout { return ankoView(`$$Anko$Factories$Sdk19ViewGroup`.LINEAR_LAYOUT) { init() } } inline fun Context.linearLayout(): android.widget.LinearLayout = linearLayout({}) inline fun Context.linearLayout(init: _LinearLayout.() -> Unit): android.widget.LinearLayout { return ankoView(`$$Anko$Factories$Sdk19ViewGroup`.LINEAR_LAYOUT) { init() } } inline fun Activity.linearLayout(): android.widget.LinearLayout = linearLayout({}) inline fun Activity.linearLayout(init: _LinearLayout.() -> Unit): android.widget.LinearLayout { return ankoView(`$$Anko$Factories$Sdk19ViewGroup`.LINEAR_LAYOUT) { init() } } inline fun ViewManager.radioGroup(): android.widget.RadioGroup = radioGroup({}) inline fun ViewManager.radioGroup(init: _RadioGroup.() -> Unit): android.widget.RadioGroup { return ankoView(`$$Anko$Factories$Sdk19ViewGroup`.RADIO_GROUP) { init() } } inline fun Context.radioGroup(): android.widget.RadioGroup = radioGroup({}) inline fun Context.radioGroup(init: _RadioGroup.() -> Unit): android.widget.RadioGroup { return ankoView(`$$Anko$Factories$Sdk19ViewGroup`.RADIO_GROUP) { init() } } inline fun Activity.radioGroup(): android.widget.RadioGroup = radioGroup({}) inline fun Activity.radioGroup(init: _RadioGroup.() -> Unit): android.widget.RadioGroup { return ankoView(`$$Anko$Factories$Sdk19ViewGroup`.RADIO_GROUP) { init() } } inline fun ViewManager.relativeLayout(): android.widget.RelativeLayout = relativeLayout({}) inline fun ViewManager.relativeLayout(init: _RelativeLayout.() -> Unit): android.widget.RelativeLayout { return ankoView(`$$Anko$Factories$Sdk19ViewGroup`.RELATIVE_LAYOUT) { init() } } inline fun Context.relativeLayout(): android.widget.RelativeLayout = relativeLayout({}) inline fun Context.relativeLayout(init: _RelativeLayout.() -> Unit): android.widget.RelativeLayout { return ankoView(`$$Anko$Factories$Sdk19ViewGroup`.RELATIVE_LAYOUT) { init() } } inline fun Activity.relativeLayout(): android.widget.RelativeLayout = relativeLayout({}) inline fun Activity.relativeLayout(init: _RelativeLayout.() -> Unit): android.widget.RelativeLayout { return ankoView(`$$Anko$Factories$Sdk19ViewGroup`.RELATIVE_LAYOUT) { init() } } inline fun ViewManager.scrollView(): android.widget.ScrollView = scrollView({}) inline fun ViewManager.scrollView(init: _ScrollView.() -> Unit): android.widget.ScrollView { return ankoView(`$$Anko$Factories$Sdk19ViewGroup`.SCROLL_VIEW) { init() } } inline fun Context.scrollView(): android.widget.ScrollView = scrollView({}) inline fun Context.scrollView(init: _ScrollView.() -> Unit): android.widget.ScrollView { return ankoView(`$$Anko$Factories$Sdk19ViewGroup`.SCROLL_VIEW) { init() } } inline fun Activity.scrollView(): android.widget.ScrollView = scrollView({}) inline fun Activity.scrollView(init: _ScrollView.() -> Unit): android.widget.ScrollView { return ankoView(`$$Anko$Factories$Sdk19ViewGroup`.SCROLL_VIEW) { init() } } inline fun ViewManager.tableLayout(): android.widget.TableLayout = tableLayout({}) inline fun ViewManager.tableLayout(init: _TableLayout.() -> Unit): android.widget.TableLayout { return ankoView(`$$Anko$Factories$Sdk19ViewGroup`.TABLE_LAYOUT) { init() } } inline fun Context.tableLayout(): android.widget.TableLayout = tableLayout({}) inline fun Context.tableLayout(init: _TableLayout.() -> Unit): android.widget.TableLayout { return ankoView(`$$Anko$Factories$Sdk19ViewGroup`.TABLE_LAYOUT) { init() } } inline fun Activity.tableLayout(): android.widget.TableLayout = tableLayout({}) inline fun Activity.tableLayout(init: _TableLayout.() -> Unit): android.widget.TableLayout { return ankoView(`$$Anko$Factories$Sdk19ViewGroup`.TABLE_LAYOUT) { init() } } inline fun ViewManager.tableRow(): android.widget.TableRow = tableRow({}) inline fun ViewManager.tableRow(init: _TableRow.() -> Unit): android.widget.TableRow { return ankoView(`$$Anko$Factories$Sdk19ViewGroup`.TABLE_ROW) { init() } } inline fun Context.tableRow(): android.widget.TableRow = tableRow({}) inline fun Context.tableRow(init: _TableRow.() -> Unit): android.widget.TableRow { return ankoView(`$$Anko$Factories$Sdk19ViewGroup`.TABLE_ROW) { init() } } inline fun Activity.tableRow(): android.widget.TableRow = tableRow({}) inline fun Activity.tableRow(init: _TableRow.() -> Unit): android.widget.TableRow { return ankoView(`$$Anko$Factories$Sdk19ViewGroup`.TABLE_ROW) { init() } } inline fun ViewManager.textSwitcher(): android.widget.TextSwitcher = textSwitcher({}) inline fun ViewManager.textSwitcher(init: _TextSwitcher.() -> Unit): android.widget.TextSwitcher { return ankoView(`$$Anko$Factories$Sdk19ViewGroup`.TEXT_SWITCHER) { init() } } inline fun Context.textSwitcher(): android.widget.TextSwitcher = textSwitcher({}) inline fun Context.textSwitcher(init: _TextSwitcher.() -> Unit): android.widget.TextSwitcher { return ankoView(`$$Anko$Factories$Sdk19ViewGroup`.TEXT_SWITCHER) { init() } } inline fun Activity.textSwitcher(): android.widget.TextSwitcher = textSwitcher({}) inline fun Activity.textSwitcher(init: _TextSwitcher.() -> Unit): android.widget.TextSwitcher { return ankoView(`$$Anko$Factories$Sdk19ViewGroup`.TEXT_SWITCHER) { init() } } inline fun ViewManager.viewAnimator(): android.widget.ViewAnimator = viewAnimator({}) inline fun ViewManager.viewAnimator(init: _ViewAnimator.() -> Unit): android.widget.ViewAnimator { return ankoView(`$$Anko$Factories$Sdk19ViewGroup`.VIEW_ANIMATOR) { init() } } inline fun Context.viewAnimator(): android.widget.ViewAnimator = viewAnimator({}) inline fun Context.viewAnimator(init: _ViewAnimator.() -> Unit): android.widget.ViewAnimator { return ankoView(`$$Anko$Factories$Sdk19ViewGroup`.VIEW_ANIMATOR) { init() } } inline fun Activity.viewAnimator(): android.widget.ViewAnimator = viewAnimator({}) inline fun Activity.viewAnimator(init: _ViewAnimator.() -> Unit): android.widget.ViewAnimator { return ankoView(`$$Anko$Factories$Sdk19ViewGroup`.VIEW_ANIMATOR) { init() } } inline fun ViewManager.viewSwitcher(): android.widget.ViewSwitcher = viewSwitcher({}) inline fun ViewManager.viewSwitcher(init: _ViewSwitcher.() -> Unit): android.widget.ViewSwitcher { return ankoView(`$$Anko$Factories$Sdk19ViewGroup`.VIEW_SWITCHER) { init() } } inline fun Context.viewSwitcher(): android.widget.ViewSwitcher = viewSwitcher({}) inline fun Context.viewSwitcher(init: _ViewSwitcher.() -> Unit): android.widget.ViewSwitcher { return ankoView(`$$Anko$Factories$Sdk19ViewGroup`.VIEW_SWITCHER) { init() } } inline fun Activity.viewSwitcher(): android.widget.ViewSwitcher = viewSwitcher({}) inline fun Activity.viewSwitcher(init: _ViewSwitcher.() -> Unit): android.widget.ViewSwitcher { return ankoView(`$$Anko$Factories$Sdk19ViewGroup`.VIEW_SWITCHER) { init() } }
apache-2.0
d66777feade4ea50562bb5c65fcb3a77
50.060021
161
0.736723
4.235995
false
false
false
false
vondear/RxTools
RxUI/src/main/java/com/tamsiree/rxui/view/loadingview/sprite/CircleLayoutContainer.kt
1
1105
package com.tamsiree.rxui.view.loadingview.sprite import android.graphics.Canvas import android.graphics.Rect /** * @author tamsiree */ abstract class CircleLayoutContainer : SpriteContainer() { override fun drawChild(canvas: Canvas) { for (i in 0 until childCount) { val sprite = getChildAt(i) val count = canvas.save() canvas.rotate(i * 360 / childCount.toFloat(), bounds.centerX().toFloat(), bounds.centerY().toFloat()) sprite!!.draw(canvas) canvas.restoreToCount(count) } } override fun onBoundsChange(bounds: Rect) { var bounds = bounds super.onBoundsChange(bounds) bounds = clipSquare(bounds) val radius = (bounds.width() * Math.PI / 3.6f / childCount).toInt() val left = bounds.centerX() - radius val right = bounds.centerX() + radius for (i in 0 until childCount) { val sprite = getChildAt(i) sprite!!.setDrawBounds0(left, bounds.top, right, bounds.top + radius * 2) } } }
apache-2.0
37e30580a166913641a4d4066e75beda
31.529412
85
0.591855
4.437751
false
false
false
false
AromaTech/banana-data-operations
src/test/java/tech/aroma/data/sql/SQLUserRepositoryIT.kt
3
5215
package tech.aroma.data.sql /* * Copyright 2017 RedRoma, 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. */ import com.natpryce.hamkrest.assertion.assertThat import com.natpryce.hamkrest.hasElement import com.natpryce.hamkrest.isEmpty import org.apache.thrift.TException import org.junit.After import org.junit.Assert.assertEquals import org.junit.Before import org.junit.BeforeClass import org.junit.Test import org.junit.runner.RunWith import org.springframework.jdbc.core.JdbcOperations import tech.aroma.data.sql.serializers.UserSerializer import tech.aroma.thrift.User import tech.aroma.thrift.exceptions.UserDoesNotExistException import tech.aroma.thrift.generators.UserGenerators.users import tech.sirwellington.alchemy.generator.StringGenerators.Companion.alphabeticStrings import tech.sirwellington.alchemy.generator.one import tech.sirwellington.alchemy.test.junit.ThrowableAssertion.assertThrows import tech.sirwellington.alchemy.test.junit.runners.AlchemyTestRunner import kotlin.test.assertFalse import kotlin.test.assertTrue @RunWith(AlchemyTestRunner::class) class SQLUserRepositoryIT { private companion object { @JvmStatic lateinit var database: JdbcOperations @JvmStatic @BeforeClass fun setupClass() { database = TestingResources.connectToDatabase() } } private val serializer = UserSerializer() private lateinit var user: User private lateinit var userId: String private lateinit var instance: SQLUserRepository @Before fun setup() { instance = SQLUserRepository(database, serializer) user = one(users()) userId = user.userId } @After fun cleanUp() { try { instance.deleteUser(userId) } catch (ex: TException) { println("Could not delete user $userId | ${ex.message}") } } @Test fun testSave() { instance.saveUser(user) assertTrue { instance.containsUser(userId) } } @Test fun testGetUser() { instance.saveUser(user) assertTrue { instance.containsUser(userId) } val result = instance.getUser(userId) assertEquals(user, result) } @Test fun testGetUserWhenNoUser() { assertThrows { instance.getUser(userId) }.isInstanceOf(UserDoesNotExistException::class.java) } @Test fun testDeleteUser() { instance.saveUser(user) assertTrue { instance.containsUser(userId) } instance.deleteUser(userId) assertFalse { instance.containsUser(userId) } } @Test fun testDeleteUserWhenNoUser() { assertFalse { instance.containsUser(userId) } instance.deleteUser(userId) assertFalse { instance.containsUser(userId) } } @Test fun testContainsUser() { assertFalse { instance.containsUser(userId) } instance.saveUser(user) assertTrue { instance.containsUser(userId) } instance.deleteUser(userId) assertFalse { instance.containsUser(userId) } } @Test fun testGetUserByEmail() { instance.saveUser(user) val email = user.email val result = instance.getUserByEmail(email) assertEquals(user, result) } @Test fun testGetUserByEmailWhenNotExists() { val email = user.email assertFalse { instance.containsUser(userId) } assertThrows { instance.getUserByEmail(email) } } @Test fun testGetUserByGithub() { val github = one(alphabeticStrings()) user.githubProfile = github instance.saveUser(user) assertTrue { instance.containsUser(userId) } val result = instance.findByGithubProfile(github) assertEquals(user, result) } fun testGetUserByGithubWhenNotExists() { val github = one(alphabeticStrings()) assertThrows { instance.findByGithubProfile(github) } .isInstanceOf(UserDoesNotExistException::class.java) } @Test fun testGetRecentlyCreatedUsers() { instance.saveUser(user) val recent = instance.recentlyCreatedUsers assertThat(recent, hasElement(user)) } @Test fun testGetRecentlyCreatedWhenRemoved() { instance.saveUser(user) instance.deleteUser(userId) val recent = instance.recentlyCreatedUsers assertThat(recent, !hasElement(user)) } @Test fun testGetRecentlyCreatedUsersWhenNone() { val recent = instance.recentlyCreatedUsers assertThat(recent, isEmpty) } }
apache-2.0
2f8bf15aa79fc56f7d80a2908b0f5076
23.373832
88
0.67325
4.610964
false
true
false
false
AndroidX/androidx
compose/material/material/integration-tests/material-catalog/src/main/java/androidx/compose/material/catalog/library/model/Themes.kt
3
4925
/* * Copyright 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.material.catalog.library.model import androidx.compose.foundation.shape.CornerBasedShape import androidx.compose.foundation.shape.CutCornerShape import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.runtime.saveable.Saver import androidx.compose.ui.graphics.Color import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.unit.Dp data class Theme( val primaryColor: ThemeColor = ThemeColor.Purple, val secondaryColor: ThemeColor = ThemeColor.Teal, val fontFamily: ThemeFontFamily = ThemeFontFamily.Default, val shapeCornerFamily: ThemeShapeCornerFamily = ThemeShapeCornerFamily.Rounded, val smallShapeCornerSize: Int = 4, val mediumShapeCornerSize: Int = 4, val largeShapeCornerSize: Int = 0 ) val DefaultTheme = Theme() enum class ThemeColor { Blue, Brown, Green, Indigo, Orange, Pink, Purple, Red, Teal, Yellow } fun ThemeColor.getColor(darkTheme: Boolean): Color = when (this) { ThemeColor.Blue -> if (!darkTheme) Color(0xFF2196F3) else Color(0xFF90CAF9) ThemeColor.Brown -> if (!darkTheme) Color(0xFF795548) else Color(0xFFBCAAA4) ThemeColor.Green -> if (!darkTheme) Color(0xFF43A047) else Color(0xFFA5D6A7) ThemeColor.Indigo -> if (!darkTheme) Color(0xFF3F51B5) else Color(0xFFC5CAE9) ThemeColor.Orange -> if (!darkTheme) Color(0xFFE65100) else Color(0xFFFFB74D) ThemeColor.Pink -> if (!darkTheme) Color(0xFFE91E63) else Color(0xFFF48FB1) ThemeColor.Purple -> if (!darkTheme) Color(0xFF6200EE) else Color(0xFFBB86FC) ThemeColor.Red -> if (!darkTheme) Color(0xFFB00020) else Color(0xFFCF6679) ThemeColor.Teal -> if (!darkTheme) Color(0xFF03DAC6) else Color(0xFF03DAC6) ThemeColor.Yellow -> if (!darkTheme) Color(0xFFFFEB3B) else Color(0xFFFFF59D) } enum class ThemeFontFamily(val label: String) { Default("Default"), SansSerif("Sans serif"), Serif("Serif"), Monospace("Monospace"), Cursive("Cursive") } fun ThemeFontFamily.getFontFamily(): FontFamily = when (this) { ThemeFontFamily.Default -> FontFamily.Default ThemeFontFamily.SansSerif -> FontFamily.SansSerif ThemeFontFamily.Serif -> FontFamily.Serif ThemeFontFamily.Monospace -> FontFamily.Monospace ThemeFontFamily.Cursive -> FontFamily.Cursive } enum class ThemeShapeCornerFamily(val label: String) { Rounded("Rounded"), Cut("Cut") } fun ThemeShapeCornerFamily.getShape(size: Dp): CornerBasedShape = when (this) { ThemeShapeCornerFamily.Rounded -> RoundedCornerShape(size = size) ThemeShapeCornerFamily.Cut -> CutCornerShape(size = size) } val ThemeSaver = Saver<Theme, Map<String, Int>>( save = { theme -> mapOf( PrimaryColorKey to theme.primaryColor.ordinal, SecondaryColorKey to theme.secondaryColor.ordinal, FontFamilyKey to theme.fontFamily.ordinal, ShapeCornerFamilyKey to theme.shapeCornerFamily.ordinal, SmallShapeCornerSizeKey to theme.smallShapeCornerSize, MediumShapeCornerSizeKey to theme.mediumShapeCornerSize, LargeShapeCornerSizeKey to theme.largeShapeCornerSize ) }, restore = { map -> Theme( primaryColor = ThemeColor.values()[map[PrimaryColorKey]!!], secondaryColor = ThemeColor.values()[map[SecondaryColorKey]!!], fontFamily = ThemeFontFamily.values()[map[FontFamilyKey]!!], shapeCornerFamily = ThemeShapeCornerFamily.values()[map[ShapeCornerFamilyKey]!!], smallShapeCornerSize = map[SmallShapeCornerSizeKey]!!, mediumShapeCornerSize = map[MediumShapeCornerSizeKey]!!, largeShapeCornerSize = map[LargeShapeCornerSizeKey]!! ) } ) const val MaxSmallShapeCornerSize = 16 const val MaxMediumShapeCornerSize = 32 const val MaxLargeShapeCornerSize = 48 private const val PrimaryColorKey = "primaryColor" private const val SecondaryColorKey = "secondaryColor" private const val FontFamilyKey = "fontFamily" private const val ShapeCornerFamilyKey = "shapeCornerFamily" private const val SmallShapeCornerSizeKey = "smallShapeCornerSize" private const val MediumShapeCornerSizeKey = "mediumShapeCornerSize" private const val LargeShapeCornerSizeKey = "largeShapeCornerSize"
apache-2.0
4541dd74fb9055fcbabd0632feb30d6c
38.087302
93
0.736853
3.987854
false
false
false
false
exponent/exponent
android/versioned-abis/expoview-abi44_0_0/src/main/java/abi44_0_0/expo/modules/barcodescanner/BarCodeScannerView.kt
2
5765
package abi44_0_0.expo.modules.barcodescanner import android.content.Context import android.hardware.SensorManager import android.view.OrientationEventListener import android.view.View import android.view.ViewGroup import android.view.WindowManager import abi44_0_0.expo.modules.barcodescanner.BarCodeScannedEvent.Companion.obtain import abi44_0_0.expo.modules.barcodescanner.utils.mapX import abi44_0_0.expo.modules.barcodescanner.utils.mapY import abi44_0_0.expo.modules.core.ModuleRegistryDelegate import abi44_0_0.expo.modules.core.interfaces.services.EventEmitter import abi44_0_0.expo.modules.interfaces.barcodescanner.BarCodeScannerResult import abi44_0_0.expo.modules.interfaces.barcodescanner.BarCodeScannerSettings import kotlin.math.roundToInt class BarCodeScannerView( private val viewContext: Context, private val moduleRegistryDelegate: ModuleRegistryDelegate ) : ViewGroup(viewContext) { private val orientationListener = object : OrientationEventListener( viewContext, SensorManager.SENSOR_DELAY_NORMAL ) { override fun onOrientationChanged(orientation: Int) { if (setActualDeviceOrientation(viewContext)) { layoutViewFinder() } } }.apply { if (canDetectOrientation()) enable() else disable() } private inline fun <reified T> moduleRegistry() = moduleRegistryDelegate.getFromModuleRegistry<T>() private lateinit var viewFinder: BarCodeScannerViewFinder private var actualDeviceOrientation = -1 private var leftPadding = 0 private var topPadding = 0 private var type = 0 override fun onDetachedFromWindow() { super.onDetachedFromWindow() orientationListener.disable() } override fun onLayout(changed: Boolean, left: Int, top: Int, right: Int, bottom: Int) { layoutViewFinder(left, top, right, bottom) } override fun onViewAdded(child: View) { if (viewFinder == child) return // remove and read view to make sure it is in the back. // @TODO figure out why there was a z order issue in the first place and fix accordingly. removeView(viewFinder) addView(viewFinder, 0) } fun onBarCodeScanned(barCode: BarCodeScannerResult) { val emitter: EventEmitter by moduleRegistry() transformBarCodeScannerResultToViewCoordinates(barCode) val event = obtain(id, barCode, displayDensity) emitter.emit(id, event) } private val displayDensity: Float get() = resources.displayMetrics.density private fun transformBarCodeScannerResultToViewCoordinates(barCode: BarCodeScannerResult) { val cornerPoints = barCode.cornerPoints val previewWidth = width - leftPadding * 2 val previewHeight = height - topPadding * 2 // fix for problem with rotation when front camera is in use if (type == ExpoBarCodeScanner.CAMERA_TYPE_FRONT && getDeviceOrientation(viewContext) % 2 == 0) { cornerPoints.mapY { barCode.referenceImageHeight - cornerPoints[it] } } if (type == ExpoBarCodeScanner.CAMERA_TYPE_FRONT && getDeviceOrientation(viewContext) % 2 != 0) { cornerPoints.mapX { barCode.referenceImageWidth - cornerPoints[it] } } // end of fix cornerPoints.mapX { (cornerPoints[it] * previewWidth / barCode.referenceImageWidth.toFloat() + leftPadding) .roundToInt() } cornerPoints.mapY { (cornerPoints[it] * previewHeight / barCode.referenceImageHeight.toFloat() + topPadding) .roundToInt() } barCode.referenceImageHeight = height barCode.referenceImageWidth = width barCode.cornerPoints = cornerPoints } fun setCameraType(cameraType: Int) { type = cameraType if (!::viewFinder.isInitialized) { viewFinder = BarCodeScannerViewFinder( viewContext, cameraType, this, moduleRegistryDelegate ) addView(viewFinder) } else { viewFinder.setCameraType(cameraType) ExpoBarCodeScanner.instance.adjustPreviewLayout(cameraType) } } fun setBarCodeScannerSettings(settings: BarCodeScannerSettings?) { viewFinder.setBarCodeScannerSettings(settings) } private fun setActualDeviceOrientation(context: Context): Boolean { val innerActualDeviceOrientation = getDeviceOrientation(context) return if (actualDeviceOrientation != innerActualDeviceOrientation) { actualDeviceOrientation = innerActualDeviceOrientation ExpoBarCodeScanner.instance.actualDeviceOrientation = actualDeviceOrientation true } else { false } } private fun getDeviceOrientation(context: Context) = (context.getSystemService(Context.WINDOW_SERVICE) as WindowManager).defaultDisplay.rotation fun layoutViewFinder() { layoutViewFinder(left, top, right, bottom) } private fun layoutViewFinder(left: Int, top: Int, right: Int, bottom: Int) { if (!::viewFinder.isInitialized) { return } val width = (right - left).toFloat() val height = (bottom - top).toFloat() val viewfinderWidth: Int val viewfinderHeight: Int val ratio = viewFinder.ratio // Just fill the given space if (ratio * height < width) { viewfinderWidth = (ratio * height).toInt() viewfinderHeight = height.toInt() } else { viewfinderHeight = (width / ratio).toInt() viewfinderWidth = width.toInt() } val viewFinderPaddingX = ((width - viewfinderWidth) / 2).toInt() val viewFinderPaddingY = ((height - viewfinderHeight) / 2).toInt() leftPadding = viewFinderPaddingX topPadding = viewFinderPaddingY viewFinder.layout(viewFinderPaddingX, viewFinderPaddingY, viewFinderPaddingX + viewfinderWidth, viewFinderPaddingY + viewfinderHeight) postInvalidate(left, top, right, bottom) } init { ExpoBarCodeScanner.createInstance(getDeviceOrientation(viewContext)) } }
bsd-3-clause
8139668286cda689f6de68197aa2de16
34.152439
138
0.73582
4.49688
false
false
false
false
Jonatino/JOGL2D
src/main/kotlin/org/anglur/joglext/jogl2d/shape/impl/LineIterator.kt
1
4005
/* * Copyright 2016 Jonathan Beaudoin <https://github.com/Jonatino> * * 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.anglur.joglext.jogl2d.shape.impl import java.awt.geom.AffineTransform import java.awt.geom.Line2D import java.awt.geom.PathIterator import java.util.* /** * Created by Jonathan on 9/30/2016. */ object LineIterator : PathIterator { private lateinit var line: Line2D private var affine: AffineTransform? = null private var index: Int = 0 fun set(line: Line2D, affine: AffineTransform?) = apply { this.index = 0 this.line = line this.affine = affine } /** * Return the winding rule for determining the insideness of the * path. * @see #WIND_EVEN_ODD * @see #WIND_NON_ZERO */ override fun getWindingRule() = PathIterator.WIND_NON_ZERO /** * Tests if there are more points to read. * @return true if there are more points to read */ override fun isDone() = index > 1 /** * Moves the iterator to the next segment of the path forwards * along the primary direction of traversal as long as there are * more points in that direction. */ override fun next() { index++ } /** * Returns the coordinates and type of the current path segment in * the iteration. * The return value is the path segment type: * SEG_MOVETO, SEG_LINETO, SEG_QUADTO, SEG_CUBICTO, or SEG_CLOSE. * A float array of length 6 must be passed in and may be used to * store the coordinates of the point(s). * Each point is stored as a pair of float x,y coordinates. * SEG_MOVETO and SEG_LINETO types will return one point, * SEG_QUADTO will return two points, * SEG_CUBICTO will return 3 points * and SEG_CLOSE will not return any points. * @see #SEG_MOVETO * @see #SEG_LINETO * @see #SEG_QUADTO * @see #SEG_CUBICTO * @see #SEG_CLOSE */ override fun currentSegment(coords: FloatArray): Int { if (isDone) { throw NoSuchElementException("line iterator out of bounds") } val type: Int if (index === 0) { coords[0] = line.x1.toFloat() coords[1] = line.y1.toFloat() type = PathIterator.SEG_MOVETO } else { coords[0] = line.x2.toFloat() coords[1] = line.y2.toFloat() type = PathIterator.SEG_LINETO } affine?.transform(coords, 0, coords, 0, 1) return type } /** * Returns the coordinates and type of the current path segment in * the iteration. * The return value is the path segment type: * SEG_MOVETO, SEG_LINETO, SEG_QUADTO, SEG_CUBICTO, or SEG_CLOSE. * A double array of length 6 must be passed in and may be used to * store the coordinates of the point(s). * Each point is stored as a pair of double x,y coordinates. * SEG_MOVETO and SEG_LINETO types will return one point, * SEG_QUADTO will return two points, * SEG_CUBICTO will return 3 points * and SEG_CLOSE will not return any points. * @see #SEG_MOVETO * @see #SEG_LINETO * @see #SEG_QUADTO * @see #SEG_CUBICTO * @see #SEG_CLOSE */ override fun currentSegment(coords: DoubleArray): Int { if (isDone) { throw NoSuchElementException("line iterator out of bounds") } val type: Int if (index === 0) { coords[0] = line.x1 coords[1] = line.y1 type = PathIterator.SEG_MOVETO } else { coords[0] = line.x2 coords[1] = line.y2 type = PathIterator.SEG_LINETO } affine?.transform(coords, 0, coords, 0, 1) return type } operator fun invoke(line: Line2D, affine: AffineTransform? = null) = set(line, affine) }
apache-2.0
dfa9fc2ac7e32f5670ec10bcc7607208
27.411348
87
0.683146
3.272059
false
false
false
false
scenerygraphics/SciView
src/main/kotlin/sc/iview/commands/view/ToggleInspector.kt
1
2188
/*- * #%L * Scenery-backed 3D visualization package for ImageJ. * %% * Copyright (C) 2016 - 2021 SciView developers. * %% * 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. * * 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 HOLDERS 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. * #L% */ package sc.iview.commands.view import org.scijava.command.Command import org.scijava.plugin.Menu import org.scijava.plugin.Parameter import org.scijava.plugin.Plugin import sc.iview.SciView import sc.iview.commands.MenuWeights.VIEW import sc.iview.commands.MenuWeights.VIEW_TOGGLE_INSPECTOR /** * Command that displays a [SwingNodePropertyEditor] window. * * @author Curtis Rueden */ @Plugin(type = Command::class, initializer = "initValues", menuRoot = "SciView", menu = [Menu(label = "View", weight = VIEW), Menu(label = "Toggle Inspector", weight = VIEW_TOGGLE_INSPECTOR)]) class ToggleInspector : Command { @Parameter private lateinit var sciView: SciView override fun run() { sciView.toggleInspectorWindow() } }
bsd-2-clause
456f0b85a79f0f624a7d9ad6ff1f5a55
41.096154
192
0.755484
4.248544
false
false
false
false
androidx/androidx
camera/integration-tests/uiwidgetstestapp/src/main/java/androidx/camera/integration/uiwidgets/compose/ui/ComposeCameraApp.kt
3
2534
/* * Copyright 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.camera.integration.uiwidgets.compose.ui import androidx.camera.integration.uiwidgets.compose.ui.navigation.ComposeCameraNavHost import androidx.camera.integration.uiwidgets.compose.ui.navigation.ComposeCameraScreen import androidx.camera.integration.uiwidgets.compose.ui.screen.components.ComposeCameraScreenTabRow import androidx.camera.view.PreviewView import androidx.compose.foundation.layout.padding import androidx.compose.material.MaterialTheme import androidx.compose.material.Scaffold import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.navigation.compose.currentBackStackEntryAsState import androidx.navigation.compose.rememberNavController // Provides callback when StreamState changes in a ComposeCameraScreen @Composable fun ComposeCameraApp( onStreamStateChange: (ComposeCameraScreen, PreviewView.StreamState) -> Unit = { _, _ -> } ) { MaterialTheme { val allScreens = ComposeCameraScreen.values().toList() val navController = rememberNavController() val backstackEntry = navController.currentBackStackEntryAsState() val currentScreen = ComposeCameraScreen.fromRoute( route = backstackEntry.value?.destination?.route, defaultRoute = ComposeCameraScreen.ImageCapture ) Scaffold( topBar = { ComposeCameraScreenTabRow( allScreens = allScreens, onTabSelected = { screen -> navController.navigate(screen.name) }, currentScreen = currentScreen ) } ) { innerPadding -> ComposeCameraNavHost( navController = navController, modifier = Modifier.padding(innerPadding), onStreamStateChange = onStreamStateChange ) } } }
apache-2.0
d142cf38b3da9e1d5edd3d801dbe91da
39.222222
99
0.705998
5.160896
false
false
false
false
androidx/androidx
wear/compose/compose-material/src/commonMain/kotlin/androidx/wear/compose/material/CurvedText.kt
3
9176
/* * Copyright 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.wear.compose.material import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.takeOrElse import androidx.compose.ui.text.TextStyle 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.style.TextOverflow import androidx.compose.ui.unit.TextUnit import androidx.wear.compose.foundation.CurvedDirection import androidx.wear.compose.foundation.CurvedLayout import androidx.wear.compose.foundation.CurvedModifier import androidx.wear.compose.foundation.CurvedScope import androidx.wear.compose.foundation.CurvedTextStyle import androidx.wear.compose.foundation.basicCurvedText import androidx.wear.compose.foundation.curvedRow /** * CurvedText is a component allowing developers to easily write curved text following * the curvature a circle (usually at the edge of a circular screen). * CurvedText can be only created within the CurvedLayout to ensure the best experience, like being * able to specify to positioning. * * The default [style] uses the [LocalTextStyle] provided by the [MaterialTheme] / components, * converting it to a [CurvedTextStyle]. Note that not all parameters are used by [curvedText]. * * If you are setting your own style, you may want to consider first retrieving [LocalTextStyle], * and using [TextStyle.copy] to keep any theme defined attributes, only modifying the specific * attributes you want to override, then convert to [CurvedTextStyle] * * For ease of use, commonly used parameters from [CurvedTextStyle] are also present here. The * order of precedence is as follows: * - If a parameter is explicitly set here (i.e, it is _not_ `null` or [TextUnit.Unspecified]), * then this parameter will always be used. * - If a parameter is _not_ set, (`null` or [TextUnit.Unspecified]), then the corresponding value * from [style] will be used instead. * * Additionally, for [color], if [color] is not set, and [style] does not have a color, then * [LocalContentColor] will be used with an alpha of [LocalContentAlpha]- this allows this * [curvedText] or element containing this [curvedText] to adapt to different background colors and * still maintain contrast and accessibility. * * For samples explicitly specifying style see: * @sample androidx.wear.compose.material.samples.CurvedTextDemo * * For examples using CompositionLocal to specify the style, see: * @sample androidx.wear.compose.material.samples.CurvedTextProviderDemo * * For more information, see the * [Curved Text](https://developer.android.com/training/wearables/compose/curved-text) * guide. * * @param text The text to display * @param modifier The [CurvedModifier] to apply to this curved text. * @param background The background color for the text. * @param color [Color] to apply to the text. If [Color.Unspecified], and [style] has no color set, * this will be [LocalContentColor]. * @param fontSize The size of glyphs to use when painting the text. See [TextStyle.fontSize]. * @param fontFamily The font family to be used when rendering the text. * @param fontWeight The thickness of the glyphs, in a range of [1, 1000]. see [FontWeight] * @param fontStyle The typeface variant to use when drawing the letters (e.g. italic). * @param fontSynthesis Whether to synthesize font weight and/or style when the requested weight * or style cannot be found in the provided font family. * @param style Specifies the style to use. * @param angularDirection Specify if the text is laid out clockwise or anti-clockwise, and if * those needs to be reversed in a Rtl layout. * If not specified, it will be inherited from the enclosing [curvedRow] or [CurvedLayout] * See [CurvedDirection.Angular]. * @param overflow How visual overflow should be handled. */ public fun CurvedScope.curvedText( text: String, modifier: CurvedModifier = CurvedModifier, background: Color = Color.Unspecified, color: Color = Color.Unspecified, fontSize: TextUnit = TextUnit.Unspecified, fontFamily: FontFamily? = null, fontWeight: FontWeight? = null, fontStyle: FontStyle? = null, fontSynthesis: FontSynthesis? = null, style: CurvedTextStyle? = null, angularDirection: CurvedDirection.Angular? = null, overflow: TextOverflow = TextOverflow.Clip, ) = basicCurvedText(text, modifier, angularDirection, overflow) { val baseStyle = style ?: CurvedTextStyle(LocalTextStyle.current) val textColor = color.takeOrElse { baseStyle.color.takeOrElse { LocalContentColor.current.copy(alpha = LocalContentAlpha.current) } } baseStyle.merge( CurvedTextStyle( color = textColor, fontSize = fontSize, fontFamily = fontFamily, fontWeight = fontWeight, fontStyle = fontStyle, fontSynthesis = fontSynthesis, background = background ) ) } /** * CurvedText is a component allowing developers to easily write curved text following * the curvature a circle (usually at the edge of a circular screen). * CurvedText can be only created within the CurvedLayout to ensure the best experience, like being * able to specify to positioning. * * The default [style] uses the [LocalTextStyle] provided by the [MaterialTheme] / components, * converting it to a [CurvedTextStyle]. Note that not all parameters are used by [curvedText]. * * If you are setting your own style, you may want to consider first retrieving [LocalTextStyle], * and using [TextStyle.copy] to keep any theme defined attributes, only modifying the specific * attributes you want to override, then convert to [CurvedTextStyle] * * For ease of use, commonly used parameters from [CurvedTextStyle] are also present here. The * order of precedence is as follows: * - If a parameter is explicitly set here (i.e, it is _not_ `null` or [TextUnit.Unspecified]), * then this parameter will always be used. * - If a parameter is _not_ set, (`null` or [TextUnit.Unspecified]), then the corresponding value * from [style] will be used instead. * * Additionally, for [color], if [color] is not set, and [style] does not have a color, then * [LocalContentColor] will be used with an alpha of [LocalContentAlpha]- this allows this * [curvedText] or element containing this [curvedText] to adapt to different background colors and * still maintain contrast and accessibility. * * @sample androidx.wear.compose.material.samples.CurvedTextDemo * * For more information, see the * [Curved Text](https://developer.android.com/training/wearables/compose/curved-text) * guide. * * @param text The text to display * @param modifier The [CurvedModifier] to apply to this curved text. * @param background The background color for the text. * @param color [Color] to apply to the text. If [Color.Unspecified], and [style] has no color set, * this will be [LocalContentColor]. * @param fontSize The size of glyphs to use when painting the text. See [TextStyle.fontSize]. * @param style Specifies the style to use. * @param angularDirection Specify if the text is laid out clockwise or anti-clockwise, and if * those needs to be reversed in a Rtl layout. * If not specified, it will be inherited from the enclosing [curvedRow] or [CurvedLayout] * See [CurvedDirection.Angular]. * @param overflow How visual overflow should be handled. */ @Deprecated("This overload is provided for backwards compatibility with Compose for " + "Wear OS 1.0. A newer overload is available with additional font parameters.", level = DeprecationLevel.HIDDEN) public fun CurvedScope.curvedText( text: String, modifier: CurvedModifier = CurvedModifier, background: Color = Color.Unspecified, color: Color = Color.Unspecified, fontSize: TextUnit = TextUnit.Unspecified, style: CurvedTextStyle? = null, angularDirection: CurvedDirection.Angular? = null, overflow: TextOverflow = TextOverflow.Clip, ) = basicCurvedText(text, modifier, angularDirection, overflow) { val baseStyle = style ?: CurvedTextStyle(LocalTextStyle.current) val textColor = color.takeOrElse { baseStyle.color.takeOrElse { LocalContentColor.current.copy(alpha = LocalContentAlpha.current) } } baseStyle.merge( CurvedTextStyle( color = textColor, fontSize = fontSize, background = background ) ) }
apache-2.0
515ba88a23f0603c102e2335fa0c9e08
46.796875
99
0.742916
4.386233
false
false
false
false
androidx/androidx
room/room-compiler/src/main/kotlin/androidx/room/vo/EmbeddedField.kt
3
1347
/* * Copyright (C) 2017 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.room.vo import androidx.room.compiler.processing.XNullability /** * Used when a field is embedded inside an Entity or Pojo. */ // used in cache matching, must stay as a data class or implement equals data class EmbeddedField( val field: Field, val prefix: String = "", val parent: EmbeddedField? ) { val getter by lazy { field.getter } val setter by lazy { field.setter } val nonNull = field.type.nullability == XNullability.NONNULL lateinit var pojo: Pojo val mRootParent: EmbeddedField by lazy { parent?.mRootParent ?: this } fun isNonNullRecursively(): Boolean { return field.nonNull && (parent == null || parent.isNonNullRecursively()) } }
apache-2.0
3bbffecc459cbefa53b76dd9039402b1
31.853659
81
0.709725
4.222571
false
false
false
false
bsmr-java/lwjgl3
modules/templates/src/main/kotlin/org/lwjgl/opengles/templates/EXT_window_rectangles.kt
1
4465
/* * Copyright LWJGL. All rights reserved. * License terms: https://www.lwjgl.org/license */ package org.lwjgl.opengles.templates import org.lwjgl.generator.* import org.lwjgl.opengles.* val EXT_window_rectangles = "EXTWindowRectangles".nativeClassGLES("EXT_window_rectangles", postfix = EXT) { documentation = """ Native bindings to the $registryLink extension. This extension provides additional orthogonally aligned "window rectangles" specified in window-space coordinates that restrict rasterization of all primitive types (geometry, images, paths) and framebuffer clears. When rendering to the framebuffer of an on-screen window, these window rectangles are ignored so these window rectangles apply to rendering to non-zero framebuffer objects only. From zero to an implementation-dependent limit (specified by #MAX_WINDOW_RECTANGLES_EXT) number of window rectangles can be operational at once. When one or more window rectangles are active, rasterized fragments can either survive if the fragment is within any of the operational window rectangles (#INCLUSIVE_EXT mode) or be rejected if the fragment is within any of the operational window rectangles (#EXCLUSIVE_EXT mode). These window rectangles operate orthogonally to the existing scissor test functionality. This extension has specification language for both OpenGL and ES so {@code EXT_window_rectangles} can be implemented and advertised for either or both API contexts. Requires ${GLES30.link} or ${EXT_multiview_draw_buffers.link}. """ val Modes = IntConstant( "Accepted by the {@code mode} parameter of #WindowRectanglesEXT().", "INCLUSIVE_EXT"..0x8F10, "EXCLUSIVE_EXT"..0x8F11 ).javaDocLinks IntConstant( """ Accepted by the {@code pname} parameter of GetIntegeri_v, GetInteger64i_v, GetBooleani_v, GetFloati_v, GetDoublei_v, GetIntegerIndexedvEXT, GetFloatIndexedvEXT, GetDoubleIndexedvEXT, GetBooleanIndexedvEXT, and GetIntegeri_vEXT. """, "WINDOW_RECTANGLE_EXT"..0x8F12 ) IntConstant( "Accepted by the {@code pname} parameter of GetBooleanv, GetIntegerv, GetInteger64v, GetFloatv, and GetDoublev.", "WINDOW_RECTANGLE_MODE_EXT"..0x8F13, "MAX_WINDOW_RECTANGLES_EXT"..0x8F14, "NUM_WINDOW_RECTANGLES_EXT"..0x8F15 ) void( "WindowRectanglesEXT", """ Sets the active window rectangles. When the {@code WindowRectanglesEXT} command is processed without error, the i<sup>th</sup> window rectangle box is set to the corresponding four parameters for values of {@code i} less then {@code n}. For values of {@code i} greater than {@code n}, each window rectangle box is set to (0,0,0,0). Each four elements corresponds to the i<sup>th</sup> window rectangle indicating a box of pixels specified with window-space coordinates. Each window rectangle box {@code i} has a lower-left origin at {@code (x_i,y_i)} and upper-right corner at {@code (x_i+w_i,y_i+h_i)}. The #INVALID_VALUE error is generated if any element {@code w_i} or {@code h_i}, corresponding to each box's respective width and height, is negative. Each rasterized or cleared fragment with a window-space position {@code (xw,yw)} is within the i<sup>th</sup> window rectangle box when both of these equations are satisfied for all {@code i} less than {@code n}: ${codeBlock(""" x_i <= xw < x_i+w_i y_i <= yw < y_i+h_i""")} When the window rectangles mode is #INCLUSIVE_EXT mode and the bound framebuffer object is non-zero, a fragment passes the window rectangles test if the fragment's window-space position is within at least one of the current {@code n} active window rectangles; otherwise the window rectangles test fails and the fragment is discarded. When the window rectangles mode is #EXCLUSIVE_EXT mode and the bound framebuffer object is non-zero, a fragment fails the window rectangles test and is discarded if the fragment's window-space position is within at least one of the current {@code n} active window rectangles; otherwise the window rectangles test passes and the fragment passes the window rectangles test. When the bound framebuffer object is zero, the window rectangles test always passes. """, GLenum.IN("mode", "the rectangle mode", Modes), AutoSize(4, "box")..GLsizei.IN("count", "the number of active window rectangles. Must be between zero and the value of #MAX_WINDOW_RECTANGLES_EXT."), nullable..const..GLint_p.IN("box", "an array of {@code 4*count} window rectangle coordinates") ) }
bsd-3-clause
46ffe1ab2be8b7264d9fae7ef7325131
48.622222
153
0.757223
3.961846
false
true
false
false
noemus/kotlin-eclipse
kotlin-eclipse-ui/src/org/jetbrains/kotlin/ui/editors/codeassist/KotlinCompletionProcessor.kt
1
12410
/******************************************************************************* * Copyright 2000-2014 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *******************************************************************************/ package org.jetbrains.kotlin.ui.editors.codeassist import com.intellij.psi.PsiElement import com.intellij.psi.PsiFile import com.intellij.psi.util.PsiTreeUtil import org.eclipse.jdt.core.IJavaProject import org.eclipse.jdt.internal.ui.JavaPlugin import org.eclipse.jdt.internal.ui.JavaPluginImages import org.eclipse.jdt.internal.ui.viewsupport.JavaElementImageProvider import org.eclipse.jface.text.IRegion import org.eclipse.jface.text.ITextViewer import org.eclipse.jface.text.Region import org.eclipse.jface.text.contentassist.ContentAssistEvent import org.eclipse.jface.text.contentassist.ContentAssistant import org.eclipse.jface.text.contentassist.ICompletionListener import org.eclipse.jface.text.contentassist.ICompletionProposal import org.eclipse.jface.text.contentassist.ICompletionProposalSorter import org.eclipse.jface.text.contentassist.IContentAssistProcessor import org.eclipse.jface.text.contentassist.IContextInformation import org.eclipse.jface.text.contentassist.IContextInformationValidator import org.eclipse.jface.text.templates.TemplateContext import org.eclipse.jface.text.templates.TemplateProposal import org.jetbrains.kotlin.descriptors.ClassDescriptor import org.jetbrains.kotlin.descriptors.DeclarationDescriptor import org.jetbrains.kotlin.eclipse.ui.utils.KotlinImageProvider import org.jetbrains.kotlin.idea.util.CallTypeAndReceiver import org.jetbrains.kotlin.name.Name import org.jetbrains.kotlin.psi.KtExpression import org.jetbrains.kotlin.psi.KtSimpleNameExpression import org.jetbrains.kotlin.renderer.DescriptorRenderer import org.jetbrains.kotlin.resolve.DescriptorUtils import org.jetbrains.kotlin.ui.editors.KotlinEditor import org.jetbrains.kotlin.ui.editors.completion.KotlinCompletionUtils import org.jetbrains.kotlin.ui.editors.templates.KotlinApplicableTemplateContext import org.jetbrains.kotlin.ui.editors.templates.KotlinDocumentTemplateContext import org.jetbrains.kotlin.ui.editors.templates.KotlinTemplateManager import org.jetbrains.kotlin.core.model.runJob import java.util.Comparator import org.eclipse.core.runtime.jobs.Job import org.eclipse.core.runtime.Status class KotlinCompletionProcessor( private val editor: KotlinEditor, private val assistant: ContentAssistant? = null, private val needSorting: Boolean = false) : IContentAssistProcessor, ICompletionListener { companion object { private val VALID_PROPOSALS_CHARS = charArrayOf() private val VALID_INFO_CHARS = charArrayOf('(', ',') } private val kotlinParameterValidator by lazy { KotlinParameterListValidator(editor) } override fun computeCompletionProposals(viewer: ITextViewer, offset: Int): Array<ICompletionProposal> { if (assistant != null) { configureContentAssistant(assistant) } val generatedProposals = generateCompletionProposals(viewer, offset).let { if (needSorting) sortProposals(it) else it } return generatedProposals.toTypedArray() } private fun sortProposals(proposals: List<ICompletionProposal>): List<ICompletionProposal> { return proposals.sortedWith(object : Comparator<ICompletionProposal> { override fun compare(o1: ICompletionProposal, o2: ICompletionProposal): Int { return KotlinCompletionSorter.compare(o1, o2) } }) } private fun configureContentAssistant(contentAssistant: ContentAssistant) { contentAssistant.setEmptyMessage("No Default Proposals") contentAssistant.setSorter(KotlinCompletionSorter) } private fun generateCompletionProposals(viewer: ITextViewer, offset: Int): List<ICompletionProposal> { val (identifierPart, identifierStart) = getIdentifierInfo(viewer.document, offset) val psiElement = KotlinCompletionUtils.getPsiElement(editor, identifierStart) val simpleNameExpression = PsiTreeUtil.getParentOfType(psiElement, KtSimpleNameExpression::class.java) val proposals = arrayListOf<ICompletionProposal>().apply { if (simpleNameExpression != null) { addAll(collectCompletionProposals(generateBasicCompletionProposals(identifierPart, simpleNameExpression), identifierPart)) if (identifierPart.isNotBlank()) { addAll(generateNonImportedCompletionProposals(identifierPart, simpleNameExpression, editor.javaProject!!)) } } if (psiElement != null) { addAll(generateKeywordProposals(identifierPart, psiElement)) addAll(generateTemplateProposals(psiElement.containingFile, viewer, offset, identifierPart)) } Status.OK_STATUS } return proposals } private fun generateNonImportedCompletionProposals( identifierPart: String, expression: KtSimpleNameExpression, javaProject: IJavaProject): List<KotlinCompletionProposal> { val file = editor.eclipseFile ?: return emptyList() val ktFile = editor.parsedFile ?: return emptyList() return lookupNonImportedTypes(expression, identifierPart, ktFile, javaProject).map { val imageDescriptor = JavaElementImageProvider.getTypeImageDescriptor(false, false, it.modifiers, false) val image = JavaPlugin.getImageDescriptorRegistry().get(imageDescriptor) KotlinImportCompletionProposal(it, image, file, identifierPart) } } private fun generateBasicCompletionProposals(identifierPart: String, expression: KtSimpleNameExpression): Collection<DeclarationDescriptor> { val file = editor.eclipseFile if (file == null) { throw IllegalStateException("Failed to retrieve IFile from editor $editor") } val nameFilter: (Name) -> Boolean = { name -> KotlinCompletionUtils.applicableNameFor(identifierPart, name) } return KotlinCompletionUtils.getReferenceVariants(expression, nameFilter, file, identifierPart) } private fun collectCompletionProposals(descriptors: Collection<DeclarationDescriptor>, part: String): List<KotlinCompletionProposal> { return descriptors.map { descriptor -> val completion = descriptor.name.identifier val image = KotlinImageProvider.getImage(descriptor) val presentableString = DescriptorRenderer.ONLY_NAMES_WITH_SHORT_TYPES.render(descriptor) val containmentPresentableString = if (descriptor is ClassDescriptor) { val fqName = DescriptorUtils.getFqName(descriptor) if (fqName.isRoot) "<root>" else fqName.parent().asString() } else { null } val proposal = KotlinCompletionProposal( completion, image, presentableString, containmentPresentableString, null, completion, part) withKotlinInsertHandler(descriptor, proposal, part) } } private fun generateTemplateProposals( psiFile: PsiFile, viewer: ITextViewer, offset: Int, identifierPart: String): List<ICompletionProposal> { val contextTypeIds = KotlinApplicableTemplateContext.getApplicableContextTypeIds(viewer, psiFile, offset - identifierPart.length) val region = Region(offset - identifierPart.length, identifierPart.length) val templateIcon = JavaPluginImages.get(JavaPluginImages.IMG_OBJS_TEMPLATE) val templates = KotlinApplicableTemplateContext.getTemplatesByContextTypeIds(contextTypeIds) return templates .filter { it.name.startsWith(identifierPart) } .map { val templateContext = createTemplateContext(region, it.contextTypeId) TemplateProposal(it, templateContext, region, templateIcon) } } private fun createTemplateContext(region: IRegion, contextTypeID: String): TemplateContext { return KotlinDocumentTemplateContext( KotlinTemplateManager.INSTANCE.getContextTypeRegistry().getContextType(contextTypeID), editor, region.getOffset(), region.getLength()) } private fun generateKeywordProposals(identifierPart: String, expression: PsiElement): List<KotlinCompletionProposal> { val callTypeAndReceiver = if (expression is KtSimpleNameExpression) CallTypeAndReceiver.detect(expression) else null return arrayListOf<String>().apply { KeywordCompletion.complete(expression, identifierPart, true) { keywordProposal -> if (!KotlinCompletionUtils.applicableNameFor(identifierPart, keywordProposal)) return@complete when (keywordProposal) { "break", "continue" -> { if (expression is KtSimpleNameExpression) { addAll(breakOrContinueExpressionItems(expression, keywordProposal)) } } "class" -> { if (callTypeAndReceiver !is CallTypeAndReceiver.CALLABLE_REFERENCE) { add(keywordProposal) } } "this", "return" -> { if (expression is KtExpression) { add(keywordProposal) } } else -> add(keywordProposal) } } }.map { KotlinKeywordCompletionProposal(it, identifierPart) } } override fun computeContextInformation(viewer: ITextViewer?, offset: Int): Array<IContextInformation> { return KotlinFunctionParameterInfoAssist.computeContextInformation(editor, offset) } override fun getCompletionProposalAutoActivationCharacters(): CharArray = VALID_PROPOSALS_CHARS override fun getContextInformationAutoActivationCharacters(): CharArray = VALID_INFO_CHARS override fun getErrorMessage(): String? = "" override fun getContextInformationValidator(): IContextInformationValidator = kotlinParameterValidator override fun assistSessionStarted(event: ContentAssistEvent?) { } override fun assistSessionEnded(event: ContentAssistEvent?) { } override fun selectionChanged(proposal: ICompletionProposal?, smartToggle: Boolean) { } } private object KotlinCompletionSorter : ICompletionProposalSorter { override fun compare(p1: ICompletionProposal, p2: ICompletionProposal): Int { val relevance2 = p2.relevance() val relevance1 = p1.relevance() return if (relevance2 > relevance1) { 1 } else if (relevance2 < relevance1) { -1 } else { p1.sortString().compareTo(p2.sortString(), ignoreCase = true) } } private fun ICompletionProposal.sortString(): String { return if (this is KotlinCompletionProposal) this.replacementString else this.displayString } private fun ICompletionProposal.relevance(): Int { return if (this is KotlinCompletionProposal) this.getRelevance() else 0 } }
apache-2.0
2f304a5ba636811809c44b4278a1c64d
44.966667
145
0.670185
5.301153
false
false
false
false
minecraft-dev/MinecraftDev
src/main/kotlin/util/class-utils.kt
1
9934
/* * Minecraft Dev for IntelliJ * * https://minecraftdev.org * * Copyright (c) 2022 minecraft-dev * * MIT License */ package com.demonwav.mcdev.util import com.intellij.codeInsight.daemon.impl.quickfix.AddMethodFix import com.intellij.navigation.AnonymousElementProvider import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import com.intellij.psi.CommonClassNames import com.intellij.psi.JavaPsiFacade import com.intellij.psi.PsiClass import com.intellij.psi.PsiClassType import com.intellij.psi.PsiElement import com.intellij.psi.PsiField import com.intellij.psi.PsiFile import com.intellij.psi.PsiInvalidElementAccessException import com.intellij.psi.PsiJavaFile import com.intellij.psi.PsiMethod import com.intellij.psi.PsiParameterList import com.intellij.psi.PsiPrimitiveType import com.intellij.psi.PsiTypeParameter import com.intellij.psi.search.GlobalSearchScope val PsiClass.packageName get() = (containingFile as? PsiJavaFile)?.packageName // Type val PsiClassType.fullQualifiedName get() = resolve()?.fullQualifiedName // this can be null if the type import is missing // Class val PsiClass.outerQualifiedName get() = if (containingClass == null) qualifiedName else null val PsiClass.fullQualifiedName get(): String? { return try { outerQualifiedName ?: buildQualifiedName(StringBuilder()).toString() } catch (e: ClassNameResolutionFailedException) { null } } @Throws(ClassNameResolutionFailedException::class) private fun PsiClass.buildQualifiedName(builder: StringBuilder): StringBuilder { if (this is PsiTypeParameter) { throw ClassNameResolutionFailedException() } buildInnerName(builder, PsiClass::outerQualifiedName) return builder } private val PsiClass.outerShortName get() = if (containingClass == null) name else null val PsiClass.shortName: String? get() { if (this is PsiTypeParameter) { return null } outerShortName?.let { return it } return try { val builder = StringBuilder() buildInnerName(builder, PsiClass::outerShortName, '.') return builder.toString() } catch (e: ClassNameResolutionFailedException) { null } } @Throws(ClassNameResolutionFailedException::class) inline fun PsiClass.buildInnerName(builder: StringBuilder, getName: (PsiClass) -> String?, separator: Char = '$') { var currentClass: PsiClass = this var parentClass: PsiClass? var name: String? val list = ArrayList<String>() do { parentClass = currentClass.containingClass if (parentClass != null) { // Add named inner class list.add(currentClass.name ?: throw ClassNameResolutionFailedException()) } else { parentClass = currentClass.parent.findContainingClass() ?: throw ClassNameResolutionFailedException() // Add index of anonymous class to list list.add(parentClass.getAnonymousIndex(currentClass).toString()) } currentClass = parentClass name = getName(currentClass) } while (name == null) // Append name of outer class builder.append(name) // Append names for all inner classes for (i in list.lastIndex downTo 0) { builder.append(separator).append(list[i]) } } fun findQualifiedClass(fullQualifiedName: String, context: PsiElement): PsiClass? { return findQualifiedClass(context.project, fullQualifiedName, context.resolveScope) } fun findQualifiedClass( project: Project, fullQualifiedName: String, scope: GlobalSearchScope = GlobalSearchScope.allScope(project) ): PsiClass? { return findQualifiedClass(fullQualifiedName) { name -> JavaPsiFacade.getInstance(project).findClass(name, scope) } } fun findQualifiedClass( fullQualifiedName: String, outerResolver: (String) -> PsiClass? ): PsiClass? { var innerPos = fullQualifiedName.indexOf('$') if (innerPos == -1) { return outerResolver(fullQualifiedName) } var currentClass = outerResolver(fullQualifiedName.substring(0, innerPos)) ?: return null var outerPos: Int while (true) { outerPos = innerPos + 1 innerPos = fullQualifiedName.indexOf('$', outerPos) if (innerPos == -1) { return currentClass.findInnerClass(fullQualifiedName.substring(outerPos)) } else { currentClass = currentClass.findInnerClass(fullQualifiedName.substring(outerPos, innerPos)) ?: return null } } } private fun PsiClass.findInnerClass(name: String): PsiClass? { val anonymousIndex = name.toIntOrNull() return if (anonymousIndex == null) { // Named inner class findInnerClassByName(name, false) } else { if (anonymousIndex > 0 && anonymousIndex <= anonymousElements.size) { anonymousElements[anonymousIndex - 1] as PsiClass } else { null } } } @Throws(ClassNameResolutionFailedException::class) fun PsiElement.getAnonymousIndex(anonymousElement: PsiElement): Int? { // Attempt to find name for anonymous class for ((i, element) in anonymousElements.withIndex()) { if (element equivalentTo anonymousElement) { return i + 1 } } throw ClassNameResolutionFailedException("Failed to determine anonymous class for $anonymousElement") } val PsiElement.anonymousElements: Array<PsiElement> get() { for (provider in AnonymousElementProvider.EP_NAME.extensionList) { val elements = provider.getAnonymousElements(this) if (elements.isNotEmpty()) { return elements } } return emptyArray() } // Inheritance fun PsiClass.extendsOrImplements(qualifiedClassName: String): Boolean { val aClass = JavaPsiFacade.getInstance(project).findClass(qualifiedClassName, resolveScope) ?: return false return equivalentTo(aClass) || this.isInheritor(aClass, true) } fun PsiClass.addImplements(qualifiedClassName: String) { if (interfaces.any { it.qualifiedName == qualifiedClassName }) { return } val project = project val listenerClass = JavaPsiFacade.getInstance(project).findClass(qualifiedClassName, resolveScope) ?: return val elementFactory = JavaPsiFacade.getElementFactory(project) val element = elementFactory.createClassReferenceElement(listenerClass) val referenceList = implementsList if (referenceList != null) { referenceList.add(element) } else { add(elementFactory.createReferenceList(arrayOf(element))) } } // Member /** * Adds the given method to this class, or its copy. Returns the method actually added */ fun PsiClass.addMethod(template: PsiMethod): PsiMethod? { var theNewMethod: PsiMethod? = null object : AddMethodFix(template, this) { override fun postAddAction(file: PsiFile, editor: Editor?, newMethod: PsiMethod?) { theNewMethod = newMethod super.postAddAction(file, editor, newMethod) } }.applyFix() return theNewMethod } fun PsiClass.findMatchingMethod( pattern: PsiMethod, checkBases: Boolean, name: String = pattern.name, constructor: Boolean = pattern.isConstructor ): PsiMethod? { return findMethodsByName(name, checkBases).firstOrNull { it.isMatchingMethod(pattern, constructor) } } fun PsiClass.findMatchingMethods( pattern: PsiMethod, checkBases: Boolean, name: String = pattern.name, constructor: Boolean = pattern.isConstructor ): List<PsiMethod> { return findMethodsByName(name, checkBases).filter { it.isMatchingMethod(pattern, constructor) } } inline fun PsiClass.findMatchingMethods( pattern: PsiMethod, checkBases: Boolean, name: String, func: (PsiMethod) -> Unit ) { for (method in findMethodsByName(name, checkBases)) { if (method.isMatchingMethod(pattern)) { func(method) } } } fun PsiMethod.isMatchingMethod(pattern: PsiMethod, constructor: Boolean = pattern.isConstructor): Boolean { return this.isConstructor == constructor && areReallyOnlyParametersErasureEqual(this.parameterList, pattern.parameterList) && (this.isConstructor || constructor || this.returnType.isErasureEquivalentTo(pattern.returnType)) } fun PsiClass.findMatchingField(pattern: PsiField, checkBases: Boolean, name: String = pattern.name): PsiField? { return try { findFieldByName(name, checkBases)?.takeIf { it.isMatchingField(pattern) } } catch (e: PsiInvalidElementAccessException) { null } } fun PsiField.isMatchingField(pattern: PsiField): Boolean { return type.isErasureEquivalentTo(pattern.type) } private fun areReallyOnlyParametersErasureEqual( parameterList1: PsiParameterList, parameterList2: PsiParameterList ): Boolean { // Similar to MethodSignatureUtil.areParametersErasureEqual, but doesn't check method name if (parameterList1.parametersCount != parameterList2.parametersCount) { return false } val parameters1 = parameterList1.parameters val parameters2 = parameterList2.parameters for (i in parameters1.indices) { val type1 = parameters1[i].type val type2 = parameters2[i].type if (type1 is PsiPrimitiveType && (type2 !is PsiPrimitiveType || type1 != type2)) { return false } if (!type1.isErasureEquivalentTo(type2)) { return false } } return true } fun PsiClass.isJavaOptional(): Boolean = this.qualifiedName == CommonClassNames.JAVA_UTIL_OPTIONAL fun PsiClassType.isJavaOptional(): Boolean = this.fullQualifiedName == CommonClassNames.JAVA_UTIL_OPTIONAL class ClassNameResolutionFailedException : Exception { constructor() : super() constructor(message: String) : super(message) }
mit
1758ad8aa29a1e86723b3a9b1d78be5b
30.636943
118
0.701933
4.71924
false
false
false
false
andstatus/andstatus
app/src/main/kotlin/org/andstatus/app/lang/SelectableEnumList.kt
1
2771
/* * Copyright (c) 2017 yvolk (Yuri Volkov), http://yurivolkov.com * * 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.andstatus.app.lang import android.content.Context import android.widget.ArrayAdapter import java.util.* /** * @author [email protected] */ class SelectableEnumList<E> private constructor(clazz: Class<E>) where E : Enum<E>, E : SelectableEnum { private val list: MutableList<E> = ArrayList() fun getList(): MutableList<E> { return list } /** * @return -1 if the item is not found in the list */ fun getIndex(other: SelectableEnum?): Int { for (index in list.indices) { val selectableEnum: SelectableEnum = list[index] if (selectableEnum == other) { return index } } return -1 } /** * @return the first element if not found */ operator fun get(index: Int): E { return list[if (index >= 0 && index < list.size) index else 0] } fun getDialogTitleResId(): Int { return list[0].getDialogTitleResId() } fun getSpinnerArrayAdapter(context: Context): ArrayAdapter<CharSequence?> { val spinnerArrayAdapter = ArrayAdapter( context, android.R.layout.simple_spinner_item, getTitles(context)) spinnerArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item) return spinnerArrayAdapter } private fun getTitles(context: Context?): MutableList<CharSequence?> { val titles: MutableList<CharSequence?> = ArrayList() for (selectableEnum in list) { titles.add(selectableEnum.title(context)) } return titles } companion object { fun <E> newInstance(clazz: Class<E>): SelectableEnumList<E> where E : Enum<E>, E : SelectableEnum { return SelectableEnumList(clazz) } } init { require(SelectableEnum::class.java.isAssignableFrom(clazz)) { "Class '" + clazz.name + "' doesn't implement SelectableEnum" } for (value in EnumSet.allOf(clazz)) { if (value?.isSelectable() == true) { list.add(value) } } } }
apache-2.0
6d67caa73925866375e26461a990df43
30.850575
107
0.630458
4.356918
false
false
false
false
andstatus/andstatus
app/src/main/kotlin/org/andstatus/app/net/http/HttpConnectionOAuthJavaNet.kt
1
11637
/* * Copyright (C) 2014 yvolk (Yuri Volkov), http://yurivolkov.com * * 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.andstatus.app.net.http import android.content.ContentResolver import io.vavr.control.Try import oauth.signpost.OAuthConsumer import oauth.signpost.OAuthProvider import oauth.signpost.basic.DefaultOAuthConsumer import oauth.signpost.basic.DefaultOAuthProvider import org.andstatus.app.context.MyContextHolder import org.andstatus.app.context.MyPreferences import org.andstatus.app.data.DbUtils.closeSilently import org.andstatus.app.data.MyContentType.Companion.uri2MimeType import org.andstatus.app.net.social.ApiRoutineEnum import org.andstatus.app.util.MyLog import org.andstatus.app.util.MyStringBuilder import org.apache.commons.lang3.tuple.ImmutablePair import org.json.JSONObject import java.io.BufferedOutputStream import java.io.OutputStreamWriter import java.io.Writer import java.net.HttpURLConnection import java.net.URL import java.nio.charset.StandardCharsets import java.util.* open class HttpConnectionOAuthJavaNet : HttpConnectionOAuth() { /** * Partially borrowed from the "Impeller" code ! */ override fun registerClient(): Try<Unit> { val uri = getApiUri(ApiRoutineEnum.OAUTH_REGISTER_CLIENT) val logmsg: MyStringBuilder = MyStringBuilder.of("registerClient; for " + data.originUrl + "; URL='" + uri + "'") MyLog.v(this) { logmsg.toString() } data.oauthClientKeys?.clear() var writer: Writer? = null try { val endpoint = URL(uri.toString()) val conn = endpoint.openConnection() as HttpURLConnection val params: MutableMap<String, String> = HashMap() params["type"] = "client_associate" params["application_type"] = "native" params["redirect_uris"] = HttpConnectionInterface.CALLBACK_URI.toString() params["client_name"] = HttpConnectionInterface.USER_AGENT params["application_name"] = HttpConnectionInterface.USER_AGENT val requestBody = HttpConnectionUtils.encode(params) conn.doOutput = true conn.doInput = true writer = OutputStreamWriter(conn.outputStream, StandardCharsets.UTF_8) writer.write(requestBody) writer.close() HttpRequest.of(ApiRoutineEnum.OAUTH_REGISTER_CLIENT, uri) .withConnectionData(data) .let { request -> val result: HttpReadResult = request.newResult() setStatusCodeAndHeaders(result, conn) if (result.isStatusOk()) { result.readStream("") { conn.inputStream } val jso = JSONObject(result.strResponse) val consumerKey = jso.getString("client_id") val consumerSecret = jso.getString("client_secret") data.oauthClientKeys?.setConsumerKeyAndSecret(consumerKey, consumerSecret) } else { result.readStream("") { conn.errorStream } logmsg.atNewLine("Server returned an error response", result.strResponse) logmsg.atNewLine("Response message from server", conn.responseMessage) MyLog.i(this, logmsg.toString()) } result.toTryResult() } } catch (e: Exception) { logmsg.withComma("Exception", e.message) MyLog.i(this, logmsg.toString(), e) } finally { closeSilently(writer) } if (data.oauthClientKeys?.areKeysPresent() == true) { MyLog.v(this) { "Completed $logmsg" } } else { return Try.failure(ConnectionException.fromStatusCodeAndHost(StatusCode.NO_CREDENTIALS_FOR_HOST, "Failed to obtain client keys for host; $logmsg", data.originUrl)) } return Try.success(null) } override fun getProvider(): OAuthProvider? { val provider: OAuthProvider provider = DefaultOAuthProvider( getApiUri(ApiRoutineEnum.OAUTH_REQUEST_TOKEN).toString(), getApiUri(ApiRoutineEnum.OAUTH_ACCESS_TOKEN).toString(), getApiUri(ApiRoutineEnum.OAUTH_AUTHORIZE).toString()) provider.setOAuth10a(true) return provider } override fun postRequest(result: HttpReadResult): HttpReadResult { try { val conn = result.requiredUrl("PostOAuth")?.openConnection() as HttpURLConnection? ?: return result conn.doOutput = true conn.doInput = true conn.requestMethod = "POST" conn.readTimeout = MyPreferences.getConnectionTimeoutMs() conn.connectTimeout = MyPreferences.getConnectionTimeoutMs() try { if (result.request.mediaUri.isPresent) { writeMedia(conn, result.request) } else { result.request.postParams.ifPresent { params: JSONObject -> try { writeJson(conn, result.request, params) } catch (e: Exception) { result.setException(e) } } } } catch (e: Exception) { result.setException(e) } setStatusCodeAndHeaders(result, conn) when (result.statusCode) { StatusCode.OK -> result.readStream("") { conn.inputStream } else -> { result.readStream("") { conn.errorStream } result.setException(result.getExceptionFromJsonErrorResponse()) } } } catch (e: Exception) { result.setException(e) } return result } /** This method is not legacy HTTP */ private fun writeMedia(conn: HttpURLConnection, request: HttpRequest) { val contentResolver: ContentResolver = MyContextHolder.myContextHolder.getNow().context.contentResolver val mediaUri = request.mediaUri.get() conn.setChunkedStreamingMode(0) conn.setRequestProperty("Content-Type", uri2MimeType(contentResolver, mediaUri)) signConnection(conn, getConsumer(), false) contentResolver.openInputStream(mediaUri)?.use { inputStream -> val buffer = ByteArray(16384) BufferedOutputStream(conn.outputStream).use { out -> var length: Int while (inputStream.read(buffer).also { length = it } != -1) { out.write(buffer, 0, length) } } } } private fun writeJson(conn: HttpURLConnection, request: HttpRequest, formParams: JSONObject) { conn.setRequestProperty("Content-Type", data.jsonContentType(request.apiRoutine)) signConnection(conn, getConsumer(), false) conn.outputStream.use { os -> OutputStreamWriter(os, UTF_8).use { writer -> writer.write(formParams.toString()) } } } override fun getConsumer(): OAuthConsumer { val consumer: OAuthConsumer = DefaultOAuthConsumer( data.oauthClientKeys?.getConsumerKey(), data.oauthClientKeys?.getConsumerSecret()) if (credentialsPresent) { consumer.setTokenWithSecret(userToken, userSecret) } return consumer } override fun getRequest(result: HttpReadResult): HttpReadResult { var connCopy: HttpURLConnection? = null try { val consumer = getConsumer() var redirected = false var stop: Boolean do { connCopy = result.requiredUrl("GetOAuth")?.openConnection() as HttpURLConnection? ?: return result val conn = connCopy conn.readTimeout = MyPreferences.getConnectionTimeoutMs() conn.connectTimeout = MyPreferences.getConnectionTimeoutMs() data.optOriginContentType().ifPresent { value: String -> conn.addRequestProperty("Accept", value) } conn.instanceFollowRedirects = false if (result.authenticate()) { signConnection(conn, consumer, redirected) } conn.connect() setStatusCodeAndHeaders(result, conn) when (result.statusCode) { StatusCode.OK -> { result.readStream("") { conn.inputStream } stop = true } StatusCode.MOVED -> { redirected = true stop = onMoved(result) } else -> { result.readStream("") { conn.errorStream } stop = result.noMoreHttpRetries() } } closeSilently(conn) } while (!stop) } catch (e: Exception) { result.setException(e) } finally { closeSilently(connCopy) } return result } protected open fun signConnection(conn: HttpURLConnection, consumer: OAuthConsumer, redirected: Boolean) { val originUrl = data.originUrl val urlForUserToken = data.urlForUserToken if (!credentialsPresent || originUrl == null || urlForUserToken == null) { return } try { if (originUrl.host == urlForUserToken.host) { consumer.sign(conn) } else { // See http://tools.ietf.org/html/draft-prodromou-dialback-00 if (redirected) { consumer.setTokenWithSecret("", "") consumer.sign(conn) } else { conn.setRequestProperty("Authorization", "Dialback") conn.setRequestProperty("host", urlForUserToken.host) conn.setRequestProperty("token", userToken) MyLog.v(this) { ("Dialback authorization at " + originUrl + "; urlForUserToken=" + urlForUserToken + "; token=" + userToken) } consumer.sign(conn) } } } catch (e: Exception) { throw ConnectionException(e) } } companion object { private val UTF_8: String = "UTF-8" fun setStatusCodeAndHeaders(result: HttpReadResult, conn: HttpURLConnection) { result.setStatusCodeInt(conn.responseCode) try { result.setHeaders( conn.headerFields.entries.stream().flatMap { entry -> entry.value.stream() .map { value: String -> ImmutablePair(entry.key, value) } }, {it.key}, {it.value}) } catch (ignored: Exception) { // ignore } } } }
apache-2.0
b1fc2343076ecc78e333a211342f87ae
42.1
123
0.579015
5.090551
false
false
false
false
codehz/container
app/src/main/java/one/codehz/container/behavior/ScrollAwareFABBehavior.kt
1
1638
package one.codehz.container.behavior import android.content.Context import android.support.design.widget.BottomNavigationView import android.support.design.widget.CoordinatorLayout import android.support.design.widget.FloatingActionButton import android.util.AttributeSet import android.view.View import one.codehz.container.MainActivity @Suppress("unused") class ScrollAwareFABBehavior(context: Context, attrs: AttributeSet) : FloatingActionButton.Behavior(context, attrs) { override fun layoutDependsOn(parent: CoordinatorLayout?, child: FloatingActionButton, dependency: View) = when (dependency) { is BottomNavigationView -> true else -> false } override fun onDependentViewChanged(parent: CoordinatorLayout, child: FloatingActionButton, dependency: View): Boolean { if ((dependency.context as? MainActivity)?.isTransition ?: false) { if (child.visibility == View.VISIBLE) child.visibility = View.GONE return false } return when (dependency) { is BottomNavigationView -> { with(child) { val enabled = (dependency.context as MainActivity).currentFragment.canBeFloatingActionTarget when { visibility == View.VISIBLE && (dependency.translationY > dependency.height / 2 || !enabled) -> hide() visibility != View.VISIBLE && dependency.translationY == 0f && enabled -> show() } } true } else -> super.onDependentViewChanged(parent, child, dependency) } } }
gpl-3.0
3eaf3b2ded1eb7e29ec0d335f0c6f490
43.297297
129
0.659951
5.370492
false
false
false
false
inorichi/tachiyomi-extensions
src/ru/mangaonlinebiz/src/eu/kanade/tachiyomi/extension/ru/mangaonlinebiz/MangaOnlineBiz.kt
1
9730
package eu.kanade.tachiyomi.extension.ru.mangaonlinebiz import com.github.salomonbrys.kotson.float import com.github.salomonbrys.kotson.forEach import com.github.salomonbrys.kotson.string import com.google.gson.JsonObject import com.google.gson.JsonParser import eu.kanade.tachiyomi.network.GET import eu.kanade.tachiyomi.source.model.Filter import eu.kanade.tachiyomi.source.model.FilterList import eu.kanade.tachiyomi.source.model.MangasPage import eu.kanade.tachiyomi.source.model.Page import eu.kanade.tachiyomi.source.model.SChapter import eu.kanade.tachiyomi.source.model.SManga import eu.kanade.tachiyomi.source.online.ParsedHttpSource import okhttp3.Headers import okhttp3.Request import okhttp3.Response import org.jsoup.nodes.Document import org.jsoup.nodes.Element import java.text.SimpleDateFormat import java.util.Locale class MangaOnlineBiz : ParsedHttpSource() { override val name = "MangaOnlineBiz" override val baseUrl = "https://manga-online.biz" override val lang = "ru" override val supportsLatest = true private val userAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.163 Safari/537.36" override fun headersBuilder(): Headers.Builder = Headers.Builder() .add("User-Agent", userAgent) .add("Referer", baseUrl) override fun popularMangaRequest(page: Int): Request = GET("$baseUrl/genre/all/page/$page", headers) override fun latestUpdatesRequest(page: Int): Request = GET("$baseUrl/genre/all/order/new/page/$page") override fun searchMangaRequest(page: Int, query: String, filters: FilterList): Request { val url = if (query.isNotBlank()) { "$baseUrl/search-ajax/?query=$query" } else { var ret = String() (if (filters.isEmpty()) getFilterList() else filters).forEach { filter -> when (filter) { is GenreList -> { ret = "$baseUrl/genre/${filter.values[filter.state].id}/page/$page" } } } ret } return GET(url, headers) } override fun popularMangaSelector() = "a.genre" override fun latestUpdatesSelector() = popularMangaSelector() override fun searchMangaParse(response: Response): MangasPage { if (!response.request.url.toString().contains("search-ajax")) { return popularMangaParse(response) } val jsonData = response.body!!.string() val json = JsonParser().parse(jsonData).asJsonObject val results = json.getAsJsonArray("results") val mangas = mutableListOf<SManga>() results.forEach { val element = it.asJsonObject val manga = SManga.create() manga.setUrlWithoutDomain(element.get("url").string) manga.title = element.get("title").string.split("/").first() val image = element.get("image").string if (image.startsWith("http")) { manga.thumbnail_url = image } else { manga.thumbnail_url = baseUrl + image } mangas.add(manga) } return MangasPage(mangas, false) } override fun popularMangaFromElement(element: Element): SManga { val manga = SManga.create() manga.thumbnail_url = element.select("img").first().attr("src") manga.setUrlWithoutDomain(element.attr("href")) element.select("div.content").first().let { manga.title = it.text().split("/").first() } return manga } override fun latestUpdatesFromElement(element: Element): SManga = popularMangaFromElement(element) override fun searchMangaFromElement(element: Element): SManga = throw Exception("Not Used") override fun popularMangaNextPageSelector() = "a.button.next" override fun latestUpdatesNextPageSelector() = popularMangaNextPageSelector() override fun searchMangaNextPageSelector() = throw Exception("Not Used") override fun mangaDetailsParse(document: Document): SManga { val infoElement = document.select(".items .item").first() val manga = SManga.create() manga.genre = infoElement.select("a.label").joinToString { it.text() } manga.description = infoElement.select(".description").text() manga.thumbnail_url = infoElement.select("img").first().attr("src") if (infoElement.text().contains("Перевод: закончен")) { manga.status = SManga.COMPLETED } else if (infoElement.text().contains("Перевод: продолжается")) { manga.status = SManga.ONGOING } return manga } override fun chapterListParse(response: Response): List<SChapter> { val html = response.body!!.string() val jsonData = html.split("App.Collection.MangaChapter(").last().split("]);").first() + "]" val mangaName = html.split("mangaName: '").last().split("' });").first() val json = JsonParser().parse(jsonData).asJsonArray val chapterList = mutableListOf<SChapter>() json.forEach { chapterList.add(chapterFromElement(mangaName, it.asJsonObject)) } return chapterList } override fun chapterListSelector(): String = throw Exception("Not Used") private fun chapterFromElement(mangaName: String, element: JsonObject): SChapter { val chapter = SChapter.create() chapter.setUrlWithoutDomain("/$mangaName/${element.get("volume").string}/${element.get("number").string})/1") chapter.name = "Том ${element.get("volume").string} - Глава ${element.get("number").string} ${element.get("title").string}" chapter.chapter_number = element.get("number").float chapter.date_upload = SimpleDateFormat("yyyy-MM-dd", Locale.US).parse(element.get("date").string)?.time ?: 0L return chapter } override fun pageListParse(response: Response): List<Page> { val html = response.body!!.string() val jsonData = html.split("new App.Router.Chapter(").last().split("});").first() + "}" val json = JsonParser().parse(jsonData).asJsonObject val cdnUrl = json.get("srcBaseUrl").string val pages = json.get("pages").asJsonObject val resPages = mutableListOf<Page>() pages.forEach { page, jsonElement -> resPages.add(Page(page.toInt(), imageUrl = "$cdnUrl/${jsonElement.asJsonObject.get("src").string}")) } return resPages } private class Genre(name: String, val id: String) : Filter.CheckBox(name) { override fun toString(): String { return name } } private class GenreList(genres: Array<Genre>) : Filter.Select<Genre>("Genres", genres, 0) override fun getFilterList() = FilterList( GenreList(getGenreList()) ) /* [...document.querySelectorAll(".categories .item")] * .map(el => `Genre("${el.textContent.trim()}", "${el.getAttribute('href')}")`).join(',\n') * on https://manga-online.biz/genre/all/ */ private fun getGenreList() = arrayOf( Genre("Все", "all"), Genre("Боевик", "boevik"), Genre("Боевые искусства", "boevye_iskusstva"), Genre("Вампиры", "vampiry"), Genre("Гарем", "garem"), Genre("Гендерная интрига", "gendernaya_intriga"), Genre("Героическое фэнтези", "geroicheskoe_fehntezi"), Genre("Детектив", "detektiv"), Genre("Дзёсэй", "dzyosehj"), Genre("Додзинси", "dodzinsi"), Genre("Драма", "drama"), Genre("Игра", "igra"), Genre("История", "istoriya"), Genre("Меха", "mekha"), Genre("Мистика", "mistika"), Genre("Научная фантастика", "nauchnaya_fantastika"), Genre("Повседневность", "povsednevnost"), Genre("Постапокалиптика", "postapokaliptika"), Genre("Приключения", "priklyucheniya"), Genre("Психология", "psihologiya"), Genre("Романтика", "romantika"), Genre("Самурайский боевик", "samurajskij_boevik"), Genre("Сверхъестественное", "sverhestestvennoe"), Genre("Сёдзё", "syodzyo"), Genre("Сёдзё-ай", "syodzyo-aj"), Genre("Сёнэн", "syonen"), Genre("Спорт", "sport"), Genre("Сэйнэн", "sejnen"), Genre("Трагедия", "tragediya"), Genre("Триллер", "triller"), Genre("Ужасы", "uzhasy"), Genre("Фантастика", "fantastika"), Genre("Фэнтези", "fentezi"), Genre("Школа", "shkola"), Genre("Этти", "etti"), Genre("Юри", "yuri"), Genre("Военный", "voennyj"), Genre("Жосей", "zhosej"), Genre("Магия", "magiya"), Genre("Полиция", "policiya"), Genre("Смена пола", "smena-pola"), Genre("Супер сила", "super-sila"), Genre("Эччи", "echchi"), Genre("Яой", "yaoj"), Genre("Сёнэн-ай", "syonen-aj") ) override fun imageUrlParse(document: Document) = throw Exception("Not Used") override fun searchMangaSelector(): String = throw Exception("Not Used") override fun chapterFromElement(element: Element): SChapter = throw Exception("Not Used") override fun pageListParse(document: Document): List<Page> = throw Exception("Not Used") }
apache-2.0
a36a0e51c84498e414d80d6f217e7f85
38.508475
145
0.629558
4.057441
false
false
false
false
java-opengl-labs/learn-OpenGL
src/main/kotlin/learnOpenGL/a_gettingStarted/1.2 hello window clear.kt
1
1738
package learnOpenGL.a_gettingStarted /** * Created by GBarbieri on 24.04.2017. */ import glm_.vec4.Vec4 import gln.glClearColor import gln.glViewport import org.lwjgl.glfw.GLFW.GLFW_KEY_ESCAPE import org.lwjgl.opengl.GL import org.lwjgl.opengl.GL11.GL_COLOR_BUFFER_BIT import org.lwjgl.opengl.GL11.glClear import uno.glfw.GlfwWindow import uno.glfw.glfw fun main(args: Array<String>) { with(HelloWindowClear()) { run() end() } } private class HelloWindowClear { val window = initWindow("Hello Window Clear") fun run() { // render loop while (window.open) { // input window.processInput() // render glClearColor(clearColor) glClear(GL_COLOR_BUFFER_BIT) // glfw: swap buffers and poll IO events (keys pressed/released, mouse moved etc.) window.swapAndPoll() } } fun end() = window.end() /** process all input: query GLFW whether relevant keys are pressed/released this frame and react accordingly */ private fun GlfwWindow.processInput() { if (pressed(GLFW_KEY_ESCAPE)) close = true } } fun initWindow(title: String): GlfwWindow { with(glfw) { init() windowHint { context.version = "3.3" profile = "core" } } return GlfwWindow(windowSize, title).apply { makeContextCurrent() show() framebufferSizeCallback = { size -> glViewport(size) } }.also { GL.createCapabilities() } } val clearColor = Vec4(0.2f, 0.3f, 0.3f, 1f) fun GlfwWindow.end() { destroy() glfw.terminate() } fun GlfwWindow.swapAndPoll() { swapBuffers() glfw.pollEvents() }
mit
1f7190043ecbe5ea46c7307cfe037b0c
21.294872
118
0.613924
3.803063
false
false
false
false
ThomasVadeSmileLee/cyls
src/main/kotlin/com/github/salomonbrys/kotson/Element.kt
1
4351
package com.github.salomonbrys.kotson import com.google.gson.Gson import com.google.gson.JsonArray import com.google.gson.JsonElement import com.google.gson.JsonNull import com.google.gson.JsonObject import com.google.gson.JsonSerializationContext import java.math.BigDecimal import java.math.BigInteger import java.util.* private fun <T : Any> JsonElement?._nullOr(getNotNull: JsonElement.() -> T): T? = if (this == null || isJsonNull) null else getNotNull() val JsonElement.string: String get() = asString val JsonElement?.nullString: String? get() = _nullOr { string } val JsonElement.bool: Boolean get() = asBoolean val JsonElement?.nullBool: Boolean? get() = _nullOr { bool } val JsonElement.byte: Byte get() = asByte val JsonElement?.nullByte: Byte? get() = _nullOr { byte } val JsonElement.char: Char get() = asCharacter val JsonElement?.nullChar: Char? get() = _nullOr { char } val JsonElement.short: Short get() = asShort val JsonElement?.nullShort: Short? get() = _nullOr { short } val JsonElement.int: Int get() = asInt val JsonElement?.nullInt: Int? get() = _nullOr { int } val JsonElement.long: Long get() = asLong val JsonElement?.nullLong: Long? get() = _nullOr { long } val JsonElement.float: Float get() = asFloat val JsonElement?.nullFloat: Float? get() = _nullOr { float } val JsonElement.double: Double get() = asDouble val JsonElement?.nullDouble: Double? get() = _nullOr { double } val JsonElement.number: Number get() = asNumber val JsonElement?.nullNumber: Number? get() = _nullOr { number } val JsonElement.bigInteger: BigInteger get() = asBigInteger val JsonElement?.nullBigInteger: BigInteger? get() = _nullOr { bigInteger } val JsonElement.bigDecimal: BigDecimal get() = asBigDecimal val JsonElement?.nullBigDecimal: BigDecimal? get() = _nullOr { bigDecimal } val JsonElement.array: JsonArray get() = asJsonArray val JsonElement?.nullArray: JsonArray? get() = _nullOr { array } val JsonElement.obj: JsonObject get() = asJsonObject val JsonElement?.nullObj: JsonObject? get() = _nullOr { obj } inline fun <reified T : Any> JsonElement.castTo(): T = Gson().fromJson(this, typeToken<T>()) inline fun <reified T : Any> JsonElement.getObject(key: String): T = Gson().fromJson(get(key), typeToken<T>()) inline fun <reified T : Any> JsonElement.getObject(index: Int): T = Gson().fromJson(get(index), typeToken<T>()) val jsonNull: JsonNull = JsonNull.INSTANCE operator fun JsonElement.get(key: String): JsonElement = obj.getNotNull(key) operator fun JsonElement.get(index: Int): JsonElement = array.get(index) fun JsonObject.getNotNull(key: String): JsonElement = get(key) ?: throw NoSuchElementException("'$key' is not found") operator fun JsonObject.contains(key: String): Boolean = has(key) fun JsonObject.isEmpty(): Boolean = entrySet().isEmpty() fun JsonObject.isNotEmpty(): Boolean = entrySet().isNotEmpty() fun JsonObject.keys(): Collection<String> = entrySet().map { it.key } fun JsonObject.forEach(operation: (String, JsonElement) -> Unit) = entrySet().forEach { operation(it.key, it.value) } fun JsonObject.toMap(): Map<String, JsonElement> = entrySet().associateBy({ it.key }, { it.value }) fun JsonObject.addProperty(property: String, value: JsonElement?) = add(property, value) fun JsonObject.addProperty(property: String, value: Any?, context: JsonSerializationContext) = add(property, context.serialize(value)) fun JsonObject.addPropertyIfNotNull(property: String, value: String?) = value?.let { addProperty(property, value) } fun JsonObject.addPropertyIfNotNull(property: String, value: Char?) = value?.let { addProperty(property, value) } fun JsonObject.addPropertyIfNotNull(property: String, value: Boolean?) = value?.let { addProperty(property, value) } fun JsonObject.addPropertyIfNotNull(property: String, value: Number?) = value?.let { addProperty(property, value) } fun JsonObject.addPropertyIfNotNull(property: String, value: JsonElement?) = value?.let { addProperty(property, value) } fun JsonObject.addPropertyIfNotNull(property: String, value: Any?, context: JsonSerializationContext) = value?.let { addProperty(property, value, context) } fun JsonObject.getAsJsonArrayOrNull(key: String) = get(key) as? JsonArray operator fun JsonArray.contains(value: Any): Boolean = contains(value.toJsonElement()) fun JsonArray.getAsJsonObject(index: Int) = get(index) as JsonObject
mit
669ce51c258678bfdafe6563a5d8b28b
47.344444
156
0.748564
3.874443
false
false
false
false
lydia-schiff/hella-renderscript
coolalgebralydiathanks/src/main/java/cat/the/lydia/coolalgebralydiathanks/implementation/RsColorCubeRenderer.kt
1
1020
package cat.the.lydia.coolalgebralydiathanks.implementation import android.renderscript.RenderScript import cat.the.lydia.coolalgebralydiathanks.ColorCube import cat.the.lydia.coolalgebralydiathanks.rs.RsFriend import com.lydiaschiff.hella.renderer.Lut3dRsRenderer class RsColorCubeRenderer(private var colorCube : ColorCube) : Lut3dRsRenderer(ColorCube.N) { private var cubeUpdate = false // explicit no-arg constructor for use with camera constructor() : this(ColorCube.identity) override fun onFirstDraw(rs: RenderScript) { RsFriend.copyColorCubeToLutAlloc(colorCube, lutAlloc) } @Synchronized fun setColorCube(cube: ColorCube) { if (this.colorCube != cube) { this.colorCube = cube cubeUpdate = true } } override fun onUpdate() { if (cubeUpdate) { RsFriend.copyColorCubeToLutAlloc(colorCube, lutAlloc) cubeUpdate = false } } override val name = "Lut3dRenderer Cool Algebra!" }
mit
26b57d7b9a060703a3901aaf0cb89c05
28.142857
93
0.702941
4.214876
false
false
false
false
btimofeev/UniPatcher
app/src/main/java/org/emunix/unipatcher/patcher/BPS.kt
1
7029
/* Copyright (c) 2016, 2018, 2020, 2021 Boris Timofeev This file is part of UniPatcher. UniPatcher 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. UniPatcher 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 UniPatcher. If not, see <http://www.gnu.org/licenses/>. */ package org.emunix.unipatcher.patcher import org.emunix.unipatcher.R import org.emunix.unipatcher.utils.FileUtils import org.emunix.unipatcher.helpers.ResourceProvider import java.io.File import java.io.FileInputStream import java.io.IOException import java.util.zip.CRC32 class BPS( patch: File, rom: File, output: File, resourceProvider: ResourceProvider, fileUtils: FileUtils, ) : Patcher(patch, rom, output, resourceProvider, fileUtils) { @Throws(PatchException::class, IOException::class) override fun apply(ignoreChecksum: Boolean) { if (patchFile.length() < 19) { throw PatchException(resourceProvider.getString(R.string.notify_error_patch_corrupted)) } if (!checkMagic(patchFile)) throw PatchException(resourceProvider.getString(R.string.notify_error_not_bps_patch)) val patch = fileUtils.readFileToByteArray(patchFile) val crc = readBpsCrc(patch) if (crc.patchFile != crc.realPatch) throw PatchException(resourceProvider.getString(R.string.notify_error_patch_corrupted)) if (!ignoreChecksum) { val realRomCrc = fileUtils.checksumCRC32(romFile) if (realRomCrc != crc.inputFile) { throw PatchException(resourceProvider.getString(R.string.notify_error_rom_not_compatible_with_patch)) } } var patchPos = 4 var decoded: Pair<Int, Int> // decode rom size decoded = decode(patch, patchPos) patchPos = decoded.component2() val rom = fileUtils.readFileToByteArray(romFile) // decode output size decoded = decode(patch, patchPos) val outputSize = decoded.component1() if (outputSize > Int.MAX_VALUE) throw PatchException("The output file is too large.") if (outputSize < 0) throw PatchException(resourceProvider.getString(R.string.notify_error_patch_corrupted)) patchPos = decoded.component2() val output = ByteArray(outputSize) var outputPos = 0 // decode metadata size and skip decoded = decode(patch, patchPos) val metadataSize = decoded.component1() patchPos = decoded.component2() + metadataSize var romRelOffset = 0 var outRelOffset = 0 var offset: Int var length: Int var mode: Byte while (patchPos < patch.size - 12) { decoded = decode(patch, patchPos) length = decoded.component1() patchPos = decoded.component2() mode = (length and 3).toByte() length = (length shr 2) + 1 when (mode) { SOURCE_READ -> { System.arraycopy(rom, outputPos, output, outputPos, length) outputPos += length } TARGET_READ -> { System.arraycopy(patch, patchPos, output, outputPos, length) patchPos += length outputPos += length } SOURCE_COPY, TARGET_COPY -> { decoded = decode(patch, patchPos) offset = decoded.component1() patchPos = decoded.component2() offset = (if (offset and 1 == 1) -1 else 1) * (offset shr 1) if (mode == SOURCE_COPY) { romRelOffset += offset System.arraycopy(rom, romRelOffset, output, outputPos, length) romRelOffset += length outputPos += length } else { outRelOffset += offset while (length-- > 0) output[outputPos++] = output[outRelOffset++] } } } } fileUtils.writeByteArrayToFile(outputFile, output) if (!ignoreChecksum) { val realOutCrc = fileUtils.checksumCRC32(outputFile) if (realOutCrc != crc.outputFile) throw PatchException(resourceProvider.getString(R.string.notify_error_wrong_checksum_after_patching)) } } private fun decode(array: ByteArray, pos: Int): Pair<Int, Int> { if (pos < 0) throw PatchException(resourceProvider.getString(R.string.notify_error_patch_corrupted)) var newPos = pos var offset = 0 var shift = 1 var x: Int while (true) { x = array[newPos++].toInt() offset += (x and 0x7f) * shift if (x and 0x80 != 0) break shift = shift shl 7 offset += shift } return Pair(offset, newPos) } private fun readBpsCrc(array: ByteArray): BpsCrc { var x: Int val crc = CRC32() crc.update(array, 0, array.size - 4) val realPatchCrc = crc.value var index = array.size - 12 if (index < 0) throw PatchException(resourceProvider.getString(R.string.notify_error_patch_corrupted)) var inputCrc: Long = 0 for (i in 0..3) { x = array[index++].toInt() and 0xFF inputCrc += x.toLong() shl (i * 8) } var outputCrc: Long = 0 for (i in 0..3) { x = array[index++].toInt() and 0xFF outputCrc += x.toLong() shl (i * 8) } var patchCrc: Long = 0 for (i in 0..3) { x = array[index++].toInt() and 0xFF patchCrc += x.toLong() shl (i * 8) } return BpsCrc(inputCrc, outputCrc, patchCrc, realPatchCrc) } private data class BpsCrc(val inputFile: Long, val outputFile: Long, val patchFile: Long, val realPatch: Long) companion object { private val MAGIC_NUMBER = byteArrayOf(0x42, 0x50, 0x53, 0x31) // "BPS1" private const val SOURCE_READ: Byte = 0 private const val TARGET_READ: Byte = 1 private const val SOURCE_COPY: Byte = 2 private const val TARGET_COPY: Byte = 3 @Throws(IOException::class) fun checkMagic(f: File): Boolean { val buffer = ByteArray(4) FileInputStream(f).use { it.read(buffer) } return buffer.contentEquals(MAGIC_NUMBER) } } }
gpl-3.0
d979cd084201b0e4143507d01bea519d
33.625616
117
0.584863
4.365839
false
false
false
false
HabitRPG/habitica-android
Habitica/src/main/java/com/habitrpg/android/habitica/helpers/notifications/HabiticaFirebaseMessagingService.kt
1
1586
package com.habitrpg.android.habitica.helpers.notifications import com.google.firebase.messaging.FirebaseMessaging import com.google.firebase.messaging.FirebaseMessagingService import com.google.firebase.messaging.RemoteMessage import com.habitrpg.android.habitica.HabiticaBaseApplication import com.habitrpg.android.habitica.components.UserComponent import javax.inject.Inject class HabiticaFirebaseMessagingService : FirebaseMessagingService() { private val userComponent: UserComponent? get() = HabiticaBaseApplication.userComponent @Inject internal lateinit var pushNotificationManager: PushNotificationManager override fun onMessageReceived(remoteMessage: RemoteMessage) { userComponent?.inject(this) if (this::pushNotificationManager.isInitialized) { pushNotificationManager.displayNotification(remoteMessage) if (remoteMessage.data["identifier"]?.contains(PushNotificationManager.WON_CHALLENGE_PUSH_NOTIFICATION_KEY) == true) { // userRepository.retrieveUser(true).subscribe({}, ExceptionHandler.rx()) } } } override fun onNewToken(s: String) { super.onNewToken(s) userComponent?.inject(this) FirebaseMessaging.getInstance().token.addOnCompleteListener { task -> val refreshedToken = task.result if (refreshedToken != null && this::pushNotificationManager.isInitialized) { pushNotificationManager.refreshedToken = refreshedToken } } } }
gpl-3.0
7809323470f9635899cf240edc7d9a86
38.666667
130
0.713745
5.584507
false
false
false
false
bstarke/elastic-maintenance
src/main/java/net/starkenberg/logging/elastic/ConfigProps.kt
1
420
package net.starkenberg.logging.elastic import org.springframework.boot.context.properties.ConfigurationProperties import java.util.* /** * @author Brad Starkenberg */ @ConfigurationProperties(prefix = "app.repo.log") class ConfigProps { var days: Int = 0 var host: String? = null var port: Int = 0 var indexPrefixs: List<String> = ArrayList() var indexDateFormat: String? = null }
apache-2.0
b487051ccac0011990184180fbbe6914
24.375
74
0.7
3.716814
false
true
false
false
Cypher121/discordplayer
src/main/kotlin/coffee/cypher/discordplayer/model/MusicFile.kt
1
1676
package coffee.cypher.discordplayer.model import org.mapdb.DataInput2 import org.mapdb.DataOutput2 data class MusicFile(val index: Int, val artist: String?, val name: String?, val path: String) { override fun toString(): String { if (artist == null && name == null) { return "$index: $path" } else { return "$index: ${artist ?: "Unknown Artist"} - ${name ?: "Unknown Track"} ($path)" } } object Serializer : org.mapdb.Serializer<MusicFile> { override fun serialize(out: DataOutput2, value: MusicFile) { val artist = value.artist val name = value.name val path = value.path val index = value.index out.writeInt(index) if (artist != null) { out.writeBoolean(true) out.writeUTF(artist) } else { out.writeBoolean(false) } if (name != null) { out.writeBoolean(true) out.writeUTF(name) } else { out.writeBoolean(false) } out.writeUTF(path) } override fun deserialize(input: DataInput2, available: Int): MusicFile { val index = input.readInt() val artist = if (input.readBoolean()) { input.readUTF() } else { null } val name = if (input.readBoolean()) { input.readUTF() } else { null } val path = input.readUTF() return MusicFile(index, artist, name, path) } } }
mit
c6f192f7b520048dfa9a0f4269fa9853
26.048387
96
0.492243
4.707865
false
false
false
false
dhleong/ideavim
src/com/maddyhome/idea/vim/action/motion/select/SelectEnableCharacterModeAction.kt
1
2377
/* * 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/>. */ package com.maddyhome.idea.vim.action.motion.select import com.intellij.openapi.actionSystem.DataContext import com.intellij.openapi.editor.Editor import com.maddyhome.idea.vim.VimPlugin import com.maddyhome.idea.vim.action.VimCommandAction import com.maddyhome.idea.vim.command.Command import com.maddyhome.idea.vim.command.CommandState import com.maddyhome.idea.vim.command.MappingMode import com.maddyhome.idea.vim.group.visual.vimSetSystemSelectionSilently import com.maddyhome.idea.vim.handler.VimActionHandler import com.maddyhome.idea.vim.helper.EditorHelper import com.maddyhome.idea.vim.helper.vimLastColumn import javax.swing.KeyStroke /** * @author Alex Plate */ class SelectEnableCharacterModeAction : VimCommandAction() { override fun makeActionHandler(): VimActionHandler = object : VimActionHandler.SingleExecution() { override fun execute(editor: Editor, context: DataContext, cmd: Command): Boolean { editor.caretModel.runForEachCaret { caret -> val lineEnd = EditorHelper.getLineEndForOffset(editor, caret.offset) caret.run { vimSetSystemSelectionSilently(offset, (offset + 1).coerceAtMost(lineEnd)) moveToOffset((offset + 1).coerceAtMost(lineEnd)) vimLastColumn = visualPosition.column } } return VimPlugin.getVisualMotion().enterSelectMode(editor, CommandState.SubMode.VISUAL_CHARACTER) } } override val mappingModes: MutableSet<MappingMode> = MappingMode.N override val keyStrokesSet: Set<List<KeyStroke>> = parseKeysSet("gh") override val type: Command.Type = Command.Type.OTHER_READONLY }
gpl-2.0
a24b28fbdb3ecfc0d282bc277d2533eb
40
103
0.766933
4.369485
false
false
false
false
kapil93/CircularLayoutManager
circular-layout-manager/src/main/java/com/kapil/circularlayoutmanager/CircularLayoutManager.kt
1
25340
package com.kapil.circularlayoutmanager import android.content.Context import android.content.res.TypedArray import android.graphics.PointF import android.os.Bundle import android.os.Parcelable import android.util.AttributeSet import android.util.DisplayMetrics import android.util.Log import android.view.View import androidx.recyclerview.widget.LinearSmoothScroller import androidx.recyclerview.widget.RecyclerView import androidx.recyclerview.widget.RecyclerView.SCROLL_STATE_IDLE import androidx.recyclerview.widget.RecyclerView.SmoothScroller.ScrollVectorProvider import kotlin.math.abs import kotlin.math.sqrt /** * This is a custom layout manager for recycler view which displays list items in a circular or * elliptical fashion. * * @see <a href="https://github.com/kapil93/Circular-Layout-Manager">Github Page</a> */ open class CircularLayoutManager : RecyclerView.LayoutManager, ScrollVectorProvider { companion object { private val TAG = CircularLayoutManager::class.simpleName private const val FILL_START_POSITION = "FILL_START_POSITION" private const val FIRST_CHILD_TOP_OFFSET = "FIRST_CHILD_TOP_OFFSET" private const val MILLIS_PER_INCH_FAST = 25f private const val MILLIS_PER_INCH_SLOW = 200f } private val xRadius: Float private val yRadius: Float private val xCenter: Float // The two fields below are the only parameters needed to define the scroll state. // They together define the placement of the first child view in the layout. private var fillStartPosition = 0 private var firstChildTopOffset = 0 private var isFirstChildParametersProgrammaticallyUpdated = false /** * Needed only for the stabilization feature. Value assigned and updated on every call to [fill]. * * Not sure whether holding a reference of [RecyclerView.Recycler] will create any problems. * * @see stabilize * @see couldChildBeBroughtDownToCenter * @see couldChildBeBroughtUpToCenter */ private lateinit var mRecycler: RecyclerView.Recycler /** * This constructor is called by the [RecyclerView] when the name of this layout manager is * passed as an XML attribute to the recycler view. * * For the purpose of instantiating this layout manager, radius and xCenter OR xRadius, yRadius * and xCenter should also be passed as XML attributes to the same recycler view depending on * whether a circular or an elliptical layout manager is desired respectively. */ constructor( context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0, defStyleRes: Int = 0 ) { val a = context.obtainStyledAttributes( attrs, R.styleable.RecyclerView, defStyleAttr, defStyleRes ) when { areAttrsForCircleAvailable(a) -> { xRadius = a.getDimension(R.styleable.RecyclerView_radius, 0f) yRadius = a.getDimension(R.styleable.RecyclerView_radius, 0f) xCenter = a.getDimension(R.styleable.RecyclerView_xCenter, 0f) } areAttrsForEllipseAvailable(a) -> { xRadius = a.getDimension(R.styleable.RecyclerView_xRadius, 0f) yRadius = a.getDimension(R.styleable.RecyclerView_yRadius, 0f) xCenter = a.getDimension(R.styleable.RecyclerView_xCenter, 0f) } else -> { throw InstantiationException( "All the necessary attributes need to be supplied. " + "For circle: radius and xCenter OR For ellipse: xRadius, yRadius and xCenter" ) } } scalingFactor = a.getFloat(R.styleable.RecyclerView_scalingFactor, 0f) shouldIgnoreHeaderAndFooterMargins = a.getBoolean( R.styleable.RecyclerView_shouldIgnoreHeaderAndFooterMargins, false ) shouldCenterIfProgrammaticallyScrolled = a.getBoolean( R.styleable.RecyclerView_shouldCenterIfProgrammaticallyScrolled, true ) isAutoStabilizationEnabled = a.getBoolean( R.styleable.RecyclerView_isAutoStabilizationEnabled, true ) a.recycle() } /** * Creates a circular layout manager. * * Calls the constructor for ellipse as circle is also an ellipse. * * @param radius Radius of the imaginary circle in dp. * @param centerX X-coordinate of center of the imaginary circle in dp. */ constructor(radius: Float, centerX: Float) : this(radius, radius, centerX) /** * Creates an elliptical layout manager. * * @param xRadius Radius of the imaginary ellipse along X-axis in dp. * @param yRadius Radius of the imaginary ellipse along Y-axis in dp. * @param xCenter X-coordinate of center of the imaginary ellipse in dp. */ constructor(xRadius: Float, yRadius: Float, xCenter: Float) { this.xRadius = xRadius this.yRadius = yRadius this.xCenter = xCenter } /** * Header and Footer item margins are by default taken into consideration while calculating the * left offset. Setting this value to true would ignore the top decoration margin for first * adapter item and bottom decoration margin for last adapter item. */ var shouldIgnoreHeaderAndFooterMargins = false /** * Scaling factor determines the amount by which an item would be shrunk when it moves away from * the center. * * It is supposed to take float values between 0 to infinity. * * Set this value to 0.0 if no scaling is desired. */ var scalingFactor = 0f /** * This value determines whether the call to [RecyclerView.scrollToPosition] and in turn the * call to [CircularLayoutManager.scrollToPosition] or the call to * [RecyclerView.smoothScrollToPosition] and in turn the call to * [CircularLayoutManager.smoothScrollToPosition] makes the view, associated with position * passed, to appear in the center or not. * * This field has NO relevance when user action is involved in scrolling. * * When set to false, the view associated with the position passed to the method appears at * the top. */ var shouldCenterIfProgrammaticallyScrolled = true /** * Enables or disables auto stabilization feature. Manual call to [stabilize] is always possible. * * Some tuning of the top and bottom item offsets (decorations) of the first and last adapter * items might be required to get the desired over scroll effect when auto stabilization is * enabled. * * @see stabilize */ var isAutoStabilizationEnabled = true override fun generateDefaultLayoutParams() = RecyclerView.LayoutParams( RecyclerView.LayoutParams.WRAP_CONTENT, RecyclerView.LayoutParams.WRAP_CONTENT ) override fun onLayoutChildren(recycler: RecyclerView.Recycler, state: RecyclerView.State) { adjustGapsIfProgrammaticallyScrolled(recycler) fill(recycler) } override fun onLayoutCompleted(state: RecyclerView.State?) { super.onLayoutCompleted(state) if (isAutoStabilizationEnabled) stabilize() } override fun canScrollVertically() = true override fun scrollVerticallyBy( dy: Int, recycler: RecyclerView.Recycler, state: RecyclerView.State ): Int { if (childCount == 0) return 0 val scrolled = determineActualScroll(dy) offsetChildrenVertical(-scrolled) calculateFirstChildPlacement(recycler) fill(recycler) return scrolled } override fun scrollToPosition(position: Int) { if (position in 0 until itemCount) { fillStartPosition = position firstChildTopOffset = 0 isFirstChildParametersProgrammaticallyUpdated = true requestLayout() } else { Log.e(TAG, "scrollToPosition: Index: $position, Size: $itemCount") } } override fun smoothScrollToPosition( recyclerView: RecyclerView, state: RecyclerView.State, position: Int ) { if (position in 0 until itemCount) { startSmoothScroll( recyclerView.context, position, MILLIS_PER_INCH_FAST, shouldCenterIfProgrammaticallyScrolled ) } else { Log.e(TAG, "smoothScrollToPosition: Index: $position, Size: $itemCount") } } override fun onScrollStateChanged(state: Int) { super.onScrollStateChanged(state) if (isAutoStabilizationEnabled && state == SCROLL_STATE_IDLE) stabilize() } override fun computeScrollVectorForPosition(targetPosition: Int) = PointF(0f, (targetPosition - fillStartPosition).toFloat()) // The three methods below are mainly overridden for accessibility. More specifically, to enable // scrolling while using TalkBack. override fun computeVerticalScrollOffset(state: RecyclerView.State) = getPosition(getChildAt(0)!!) override fun computeVerticalScrollExtent(state: RecyclerView.State) = getPosition(getChildAt(childCount - 1)!!) - getPosition(getChildAt(0)!!) + 1 override fun computeVerticalScrollRange(state: RecyclerView.State) = itemCount override fun onAdapterChanged( oldAdapter: RecyclerView.Adapter<*>?, newAdapter: RecyclerView.Adapter<*>? ) { super.onAdapterChanged(oldAdapter, newAdapter) removeAllViews() clearScrollState() } override fun onSaveInstanceState(): Parcelable = Bundle().apply { putInt(FILL_START_POSITION, fillStartPosition) putInt(FIRST_CHILD_TOP_OFFSET, firstChildTopOffset) } override fun onRestoreInstanceState(state: Parcelable?) { (state as? Bundle)?.let { fillStartPosition = it.getInt(FILL_START_POSITION) firstChildTopOffset = it.getInt(FIRST_CHILD_TOP_OFFSET) } } /** * This method is responsible to actually layout the child views based on the data obtained from * the recycler and the layout manager. * * Steps: * 1. Detaches and scraps all the attached views * 2. Adds, measures, scales (if needed) and lays out all the relevant child views. It starts * based on the values [fillStartPosition] and [firstChildTopOffset] and stops when there is * no more space left to fill * 3. Recycles the leftover views (if any) in the scrap list[RecyclerView.Recycler.getScrapList] */ private fun fill(recycler: RecyclerView.Recycler) { if (itemCount == 0) { removeAndRecycleAllViews(recycler) return } mRecycler = recycler var tmpOffset = firstChildTopOffset detachAndScrapAttachedViews(recycler) for (position in fillStartPosition until itemCount) { val child = recycler.getViewForPosition(position) addView(child) measureChildWithMargins(child, 0, 0) val childWidth = getDecoratedMeasuredWidth(child) val childHeight = getDecoratedMeasuredHeight(child) val left = calculateLeftOffset(position, child, childHeight, tmpOffset) val top = tmpOffset layoutDecoratedWithMargins(child, left, top, left + childWidth, top + childHeight) scaleChild(child) tmpOffset += childHeight if (tmpOffset > height) break } recycler.scrapList.toList().forEach { recycler.recycleView(it.itemView) } } /** * Calculates [fillStartPosition] and [firstChildTopOffset] to prepare for the fill usually * after the child views have moved. * * @see scrollVerticallyBy */ private fun calculateFirstChildPlacement(recycler: RecyclerView.Recycler) { // Find first visible view for (i in 0 until childCount) { val tmpChild = getChildAt(i)!! if (getDecoratedBottom(tmpChild) > 0) { firstChildTopOffset = getDecoratedTop(tmpChild) fillStartPosition = getPosition(tmpChild) break } } // Find position from which filling of gap should be started while (firstChildTopOffset > 0) { fillStartPosition -= 1 if (fillStartPosition < 0) { clearScrollState() break } else { val tmpChild = recycler.getViewForPosition(fillStartPosition) measureChildWithMargins(tmpChild, 0, 0) firstChildTopOffset -= getDecoratedMeasuredHeight(tmpChild) } } } /** * Scales the width and height of a child view depending on it's vertical positioning relative * to the horizontal axis of the ellipse. * * @param child Child View to be scaled. * * @see scalingFactor */ private fun scaleChild(child: View) { val y = (child.top + child.bottom) / 2 val scale = 1 - (scalingFactor * (abs((height / 2f) - y) / (height - child.height))) child.pivotX = 0f child.pivotY = child.height / 2f child.scaleX = scale child.scaleY = scale } /** * @see shouldIgnoreHeaderAndFooterMargins */ private fun calculateLeftOffset(position: Int, child: View, childHeight: Int, tmpOffset: Int) = if (shouldIgnoreHeaderAndFooterMargins) { when (position) { 0 -> calculateEllipseXFromY( tmpOffset + getTopDecorationHeight(child) + ((childHeight - getTopDecorationHeight(child)) / 2) ) itemCount - 1 -> calculateEllipseXFromY( tmpOffset + ((childHeight - getBottomDecorationHeight(child)) / 2) ) else -> calculateEllipseXFromY(tmpOffset + (childHeight / 2)) } } else calculateEllipseXFromY(tmpOffset + (childHeight / 2)) /** * This method calculates the x-coordinate of an ellipse based on the y-coordinate provided. * * This method is only relevant in the context of the specific use case of this class. * * Note: y-coordinate supplied is allowed to be an illegal value which may out of bounds with * respect to the imaginary ellipse. */ private fun calculateEllipseXFromY(y: Int): Int { val yCenter = height / 2f val amount = (1 - (y - yCenter) * (y - yCenter) / (yRadius * yRadius)) * (xRadius * xRadius).toDouble() return if (amount >= 0) (sqrt(amount) + xCenter).toInt() else (-sqrt(-amount) + xCenter).toInt() } /** * This method is responsible to determine the amount by which the child views should be offset * as a response to user scroll. It introduces boundary conditions and prevents the child views * from being over-scrolled. */ private fun determineActualScroll(dy: Int): Int { val firstChild = getChildAt(0)!! val lastChild = getChildAt(childCount - 1)!! return when { (dy < 0 && getPosition(firstChild) == 0 && getDecoratedTop(firstChild) - dy > 0) -> getDecoratedTop(firstChild) (dy > 0 && getPosition(lastChild) == itemCount - 1 && getDecoratedBottom(lastChild) - dy < height) -> getDecoratedBottom(lastChild) - height else -> dy } } /** * The fields [fillStartPosition] and [firstChildTopOffset] are never set arbitrarily. They are * always updated based on some user action like in [scrollVerticallyBy]. There is no scope for * any gaps in the layout if these values are only updated as a response to scrollVerticallyBy. * * @see determineActualScroll * * But in [scrollToPosition] these values can be indirectly set programmatically which may * result in some gaps specially when views with first and last adapter positions are involved. * * This method adjusts fillStartPosition and firstChildTopOffset to eliminate potential gaps. */ private fun adjustGapsIfProgrammaticallyScrolled(recycler: RecyclerView.Recycler) { if (isFirstChildParametersProgrammaticallyUpdated) { if (shouldCenterIfProgrammaticallyScrolled) { // If shouldCenterAfterScrollToPosition is true, readjust fillStartPosition // Also, ensure there is no gap at the top val centerChild = recycler.getViewForPosition(fillStartPosition) measureChildWithMargins(centerChild, 0, 0) var topGap = (height / 2) - (getDecoratedMeasuredHeight(centerChild) / 2) for (position in (fillStartPosition - 1) downTo 0) { val tmpChild = recycler.getViewForPosition(position) measureChildWithMargins(tmpChild, 0, 0) topGap -= getDecoratedMeasuredHeight(tmpChild) if (topGap <= 0) { fillStartPosition = position firstChildTopOffset = topGap break } } if (topGap > 0) clearScrollState() } // Ensure there is no gap at the bottom var bottomGap = height for (position in (itemCount - 1) downTo 0) { val tmpChild = recycler.getViewForPosition(position) measureChildWithMargins(tmpChild, 0, 0) bottomGap -= getDecoratedMeasuredHeight(tmpChild) if (bottomGap <= 0) { if ((position < fillStartPosition) || (position == fillStartPosition && bottomGap > firstChildTopOffset)) { fillStartPosition = position firstChildTopOffset = bottomGap } break } } if (bottomGap > 0) clearScrollState() isFirstChildParametersProgrammaticallyUpdated = false } } private fun startSmoothScroll( context: Context, targetPosition: Int, millisPerInch: Float, shouldCenter: Boolean ) { object : LinearSmoothScroller(context) { override fun calculateDtToFit( viewStart: Int, viewEnd: Int, boxStart: Int, boxEnd: Int, snapPreference: Int ): Int { return if (shouldCenter) { ((boxStart + boxEnd) / 2) - ((viewStart + viewEnd) / 2) } else { super.calculateDtToFit(viewStart, viewEnd, boxStart, boxEnd, snapPreference) } } override fun calculateSpeedPerPixel(displayMetrics: DisplayMetrics) = millisPerInch / displayMetrics.densityDpi }.apply { this.targetPosition = targetPosition startSmoothScroll(this) } } /** * Clears the scroll state. * * In other words, the next call to [fill] will result in the layout starting from the adapter * position 0. */ private fun clearScrollState() { fillStartPosition = 0 firstChildTopOffset = 0 } private fun areAttrsForCircleAvailable(a: TypedArray) = a.hasValue(R.styleable.RecyclerView_radius) && a.hasValue(R.styleable.RecyclerView_xCenter) private fun areAttrsForEllipseAvailable(a: TypedArray) = a.hasValue(R.styleable.RecyclerView_xRadius) && a.hasValue(R.styleable.RecyclerView_yRadius) && a.hasValue(R.styleable.RecyclerView_xCenter) private fun couldChildBeBroughtDownToCenter(nearestChildIndex: Int): Boolean { val nearestChildPosition = getPosition(getChildAt(nearestChildIndex)!!) var topGap = height / 2 for (i in 0 until nearestChildPosition) { val child = mRecycler.getViewForPosition(i) measureChildWithMargins(child, 0, 0) topGap -= getDecoratedMeasuredHeight(child) if (topGap <= 0) return true } val nearestChild = mRecycler.getViewForPosition(nearestChildPosition) measureChildWithMargins(nearestChild, 0, 0) topGap -= getDecoratedMeasuredHeight(nearestChild) / 2 return topGap <= 0 } private fun couldChildBeBroughtUpToCenter(nearestChildIndex: Int): Boolean { val nearestChildPosition = getPosition(getChildAt(nearestChildIndex)!!) var bottomGap = height / 2 for (i in (itemCount - 1) downTo (nearestChildPosition + 1)) { val child = mRecycler.getViewForPosition(i) measureChildWithMargins(child, 0, 0) bottomGap -= getDecoratedMeasuredHeight(child) if (bottomGap <= 0) return true } val nearestChild = mRecycler.getViewForPosition(nearestChildPosition) measureChildWithMargins(nearestChild, 0, 0) bottomGap -= getDecoratedMeasuredHeight(nearestChild) / 2 return bottomGap <= 0 } /** * This method is responsible for detecting the view nearest to the vertical center of the * layout and centering it. * * This method is called only after a user scroll or fling ends and after layout completion. * These automatic calls could be enabled or disabled by [isAutoStabilizationEnabled]. * * This For programmatic scrolls, [scrollToPosition] and [smoothScrollToPosition] is supported. * The centering behaviour can be controlled by the field [shouldCenterIfProgrammaticallyScrolled]. * * When scrolling is externally and programmatically triggered through methods like * [RecyclerView.scrollBy], there is no clean way of knowing whether the scrolling has stopped * or not with certainty. Therefore, this method should be called in such cases whenever * stabilization is necessary even when isAutoStabilizationEnabled is set to true. Ideally it * should be called when the scroll state is IDLE. * * The distance between the center of the layout and the center of the view would keep on * decreasing as we traverse downwards from the top child towards the center of the layout. If * at any moment the distance is greater than the previous distance, it means that we are now * moving away from center, so we ignore this greater distance and break out of the loop as the * child with the least distance from the center of the layout should be the previous child. * * The above logic is used to find the nearest child from vertical center and the current * distance which separates them. After that, it is checked whether movement in either direction * is possible or not. */ fun stabilize() { if (childCount == 0 || isSmoothScrolling) return var minDistance = Int.MAX_VALUE var nearestChildIndex = 0 val yCenter = height / 2 for (i in 0 until childCount) { val child = getChildAt(i)!! val y = (getDecoratedTop(child) + getDecoratedBottom(child)) / 2 if (abs(y - yCenter) < abs(minDistance)) { nearestChildIndex = i minDistance = y - yCenter } else break } var isStabilizationPossible = false if (minDistance < 0) { // Child is above the center if (couldChildBeBroughtDownToCenter(nearestChildIndex)) { isStabilizationPossible = true } else { if (nearestChildIndex + 1 < childCount) { // Here an assumption is made that the child views would approximately be of the // same height and the next nearest child to center would be below the center. if (couldChildBeBroughtUpToCenter(nearestChildIndex + 1)) { nearestChildIndex++ isStabilizationPossible = true } } } } else if (minDistance > 0) { // Child is below the center if (couldChildBeBroughtUpToCenter(nearestChildIndex)) { isStabilizationPossible = true } else { // This condition should always be true. But is checked just for safety. if (nearestChildIndex - 1 >= 0) { // Here an assumption is made that the child views would approximately be of the // same height and the next nearest child to center would be above the center. if (couldChildBeBroughtDownToCenter(nearestChildIndex - 1)) { nearestChildIndex-- isStabilizationPossible = true } } } } if (isStabilizationPossible) startSmoothScroll( getChildAt(nearestChildIndex)!!.context, getPosition(getChildAt(nearestChildIndex)!!), MILLIS_PER_INCH_SLOW, true ) } }
mit
5ff0ccf7e1da1d7a8e873be44f9a0e38
39.22381
127
0.635083
4.959875
false
false
false
false
apollostack/apollo-android
apollo-compiler/src/test/kotlin/com/apollographql/apollo3/compiler/TestUtils.kt
1
3831
package com.apollographql.apollo3.compiler import com.apollographql.apollo3.graphql.ast.Schema import com.apollographql.apollo3.compiler.introspection.IntrospectionSchema import com.apollographql.apollo3.compiler.introspection.toSchema import com.apollographql.apollo3.graphql.ast.GraphQLParser import com.google.common.truth.Truth.assertThat import java.io.File import java.lang.Exception internal object TestUtils { internal fun shouldUpdateTestFixtures(): Boolean { return when (System.getProperty("updateTestFixtures")?.trim()) { "on", "true", "1" -> true else -> false } } internal fun shouldUpdateMeasurements(): Boolean { return when (System.getProperty("updateTestFixtures")?.trim()) { "on", "true", "1" -> true else -> false } } internal fun checkTestFixture(actual: File, expected: File) { val actualText = actual.readText() val expectedText = expected.readText() if (actualText != expectedText) { if (shouldUpdateTestFixtures()) { expected.writeText(actualText) } else { throw Exception("""generatedFile content doesn't match the expectedFile content. |If you changed the compiler recently, you need to update the testFixtures. |Run the tests with `-DupdateTestFixtures=true` to do so. |diff ${expected.path} ${actual.path}""".trimMargin()) } } } /** * This allows to run a specific test from the command line by using something like: * * ./gradlew :apollo-compiler:test -testFilter="fragments_with_type_condition" --tests '*Codegen*' */ fun testFilterMatches(value: String): Boolean { val testFilter = System.getProperty("testFilter") ?: return true return Regex(testFilter).containsMatchIn(value) } fun testParametersForGraphQLFilesIn(path: String): Collection<Array<Any>> { return File(path) .walk() .toList() .filter { it.isFile } .filter { it.extension == "graphql" } .filter { testFilterMatches(it.name) } .sortedBy { it.name } .map { arrayOf(it.nameWithoutExtension, it) } } private fun File.replaceExtension(newExtension: String): File { return File(parentFile, "$nameWithoutExtension.$newExtension") } private fun findSchema(parent: File, nameWithoutExtension: String): Schema? { val schema = File(parent, "$nameWithoutExtension.sdl") .takeIf { it.exists() } ?.let { GraphQLParser.parseSchema(it) } if (schema != null) { return schema } return File(parent, "$nameWithoutExtension.json") .takeIf { it.exists() } ?.let { IntrospectionSchema(it).toSchema() } } /** * run the block and checks the result against the .expected file * * @param block: the callback to produce the result. [checkExpected] will try to find a schema * for [graphQLFile] by either looking for a schema with the same name or testing the first * schema.[json|sdl|graphqls] in the hierarchy */ fun checkExpected(graphQLFile: File, block: (Schema?) -> String) { var schema = findSchema(graphQLFile.parentFile, graphQLFile.nameWithoutExtension) if (schema == null) { var parent = graphQLFile.parentFile while (parent.name != "test") { schema = findSchema(parent, "schema") if (schema != null) { break } parent = parent.parentFile } } val actual = block(schema) val expectedFile = File(graphQLFile.parent, graphQLFile.nameWithoutExtension + ".expected") val expected = try { expectedFile.readText() } catch (e: Exception) { null } if (shouldUpdateTestFixtures()) { expectedFile.writeText(actual) } else { assertThat(actual).isEqualTo(expected) } } }
mit
7400c98646289cfd15e8c5c4e49575b9
30.925
100
0.659619
4.403448
false
true
false
false
apollostack/apollo-android
composite/integration-tests-kotlin/src/commonTest/kotlin/com/apollographql/apollo3/integration/test/normalized/OptimisticCacheTest.kt
1
16204
package com.apollographql.apollo3.integration.test.normalized import com.apollographql.apollo3.ApolloClient import com.apollographql.apollo3.ApolloRequest import com.apollographql.apollo3.api.Optional import com.apollographql.apollo3.cache.normalized.ApolloStore import com.apollographql.apollo3.cache.normalized.MemoryCacheFactory import com.apollographql.apollo3.integration.IdFieldCacheKeyResolver import com.apollographql.apollo3.integration.enqueue import com.apollographql.apollo3.mockserver.MockServer import com.apollographql.apollo3.integration.normalizer.HeroAndFriendsNamesQuery import com.apollographql.apollo3.integration.normalizer.HeroAndFriendsNamesWithIDsQuery import com.apollographql.apollo3.integration.normalizer.HeroNameWithIdQuery import com.apollographql.apollo3.integration.normalizer.ReviewsByEpisodeQuery import com.apollographql.apollo3.integration.normalizer.UpdateReviewMutation import com.apollographql.apollo3.integration.normalizer.type.ColorInput import com.apollographql.apollo3.integration.normalizer.type.Episode import com.apollographql.apollo3.integration.normalizer.type.ReviewInput import com.apollographql.apollo3.integration.readResource import com.apollographql.apollo3.integration.receiveOrTimeout import com.apollographql.apollo3.interceptor.cache.FetchPolicy import com.apollographql.apollo3.interceptor.cache.watch import com.apollographql.apollo3.interceptor.cache.withFetchPolicy import com.apollographql.apollo3.interceptor.cache.withOptimiticUpdates import com.apollographql.apollo3.interceptor.cache.withRefetchPolicy import com.apollographql.apollo3.interceptor.cache.withStore import com.apollographql.apollo3.testing.runWithMainLoop import com.benasher44.uuid.uuid4 import kotlinx.coroutines.channels.Channel import kotlinx.coroutines.flow.collect import kotlinx.coroutines.launch import kotlin.test.BeforeTest import kotlin.test.Test import com.apollographql.apollo3.integration.assertEquals2 as assertEquals class OptimisticCacheTest { private lateinit var mockServer: MockServer private lateinit var apolloClient: ApolloClient private lateinit var store: ApolloStore @BeforeTest fun setUp() { store = ApolloStore(MemoryCacheFactory(maxSizeBytes = Int.MAX_VALUE), IdFieldCacheKeyResolver) mockServer = MockServer() apolloClient = ApolloClient(mockServer.url()).withStore(store) } /** * Write the updates programmatically, make sure they are seen, * roll them back, make sure we're back to the initial state */ @Test fun programmaticOptimiticUpdates() = runWithMainLoop { val query = HeroAndFriendsNamesQuery(Episode.JEDI) mockServer.enqueue(readResource("HeroAndFriendsNameResponse.json")) apolloClient.query(ApolloRequest(query).withFetchPolicy(FetchPolicy.NetworkOnly)) val mutationId = uuid4() val data = HeroAndFriendsNamesQuery.Data(HeroAndFriendsNamesQuery.Data.Hero( "R222-D222", listOf( HeroAndFriendsNamesQuery.Data.Hero.Friend( "SuperMan" ), HeroAndFriendsNamesQuery.Data.Hero.Friend( "Batman" ) ) )) store.writeOptimisticUpdates( operation = query, operationData = data, mutationId = mutationId, publish = true) var response = apolloClient.query(ApolloRequest(query).withFetchPolicy(FetchPolicy.CacheOnly)) assertEquals(response.data?.hero?.name, "R222-D222") assertEquals(response.data?.hero?.friends?.size, 2) assertEquals(response.data?.hero?.friends?.get(0)?.name, "SuperMan") assertEquals(response.data?.hero?.friends?.get(1)?.name, "Batman") store.rollbackOptimisticUpdates(mutationId, false) response = apolloClient.query(ApolloRequest(query).withFetchPolicy(FetchPolicy.CacheOnly)) assertEquals(response.data?.hero?.name, "R2-D2") assertEquals(response.data?.hero?.friends?.size, 3) assertEquals(response.data?.hero?.friends?.get(0)?.name, "Luke Skywalker") assertEquals(response.data?.hero?.friends?.get(1)?.name, "Han Solo") assertEquals(response.data?.hero?.friends?.get(2)?.name, "Leia Organa") } /** * A more complex scenario where we stack optimistic updates */ @Test fun two_optimistic_two_rollback() = runWithMainLoop { val query1 = HeroAndFriendsNamesWithIDsQuery(Episode.JEDI) val mutationId1 = uuid4() // execute query1 from the network mockServer.enqueue(readResource("HeroAndFriendsNameWithIdsResponse.json")) apolloClient.query(ApolloRequest(query1).withFetchPolicy(FetchPolicy.NetworkOnly)) // now write some optimistic updates for query1 val data1 = HeroAndFriendsNamesWithIDsQuery.Data( HeroAndFriendsNamesWithIDsQuery.Data.Hero( "2001", "R222-D222", listOf( HeroAndFriendsNamesWithIDsQuery.Data.Hero.Friend( "1000", "SuperMan" ), HeroAndFriendsNamesWithIDsQuery.Data.Hero.Friend( "1003", "Batman" ) ) ) ) store.writeOptimisticUpdates( operation = query1, operationData = data1, mutationId = mutationId1, publish = true) // check if query1 see optimistic updates var response1 = apolloClient.query(ApolloRequest(query1).withFetchPolicy(FetchPolicy.CacheOnly)) assertEquals(response1.data?.hero?.id, "2001") assertEquals(response1.data?.hero?.name, "R222-D222") assertEquals(response1.data?.hero?.friends?.size, 2) assertEquals(response1.data?.hero?.friends?.get(0)?.id, "1000") assertEquals(response1.data?.hero?.friends?.get(0)?.name, "SuperMan") assertEquals(response1.data?.hero?.friends?.get(1)?.id, "1003") assertEquals(response1.data?.hero?.friends?.get(1)?.name, "Batman") // execute query2 val query2 = HeroNameWithIdQuery() val mutationId2 = uuid4() mockServer.enqueue(readResource("HeroNameWithIdResponse.json")) apolloClient.query(query2) // write optimistic data2 val data2 = HeroNameWithIdQuery.Data(HeroNameWithIdQuery.Data.Hero( "1000", "Beast" )) store.writeOptimisticUpdates( operation = query2, operationData = data2, mutationId = mutationId2, publish = true) // check if query1 sees data2 response1 = apolloClient.query(ApolloRequest(query1).withFetchPolicy(FetchPolicy.CacheOnly)) assertEquals(response1.data?.hero?.id, "2001") assertEquals(response1.data?.hero?.name, "R222-D222") assertEquals(response1.data?.hero?.friends?.size, 2) assertEquals(response1.data?.hero?.friends?.get(0)?.id, "1000") assertEquals(response1.data?.hero?.friends?.get(0)?.name, "Beast") assertEquals(response1.data?.hero?.friends?.get(1)?.id, "1003") assertEquals(response1.data?.hero?.friends?.get(1)?.name, "Batman") // check if query2 sees data2 var response2 = apolloClient.query(ApolloRequest(query2).withFetchPolicy(FetchPolicy.CacheOnly)) assertEquals(response2.data?.hero?.id, "1000") assertEquals(response2.data?.hero?.name, "Beast") // rollback data1 store.rollbackOptimisticUpdates(mutationId1, false) // check if query2 sees the rollback response1 = apolloClient.query(ApolloRequest(query1).withFetchPolicy(FetchPolicy.CacheOnly)) assertEquals(response1.data?.hero?.id, "2001") assertEquals(response1.data?.hero?.name, "R2-D2") assertEquals(response1.data?.hero?.friends?.size, 3) assertEquals(response1.data?.hero?.friends?.get(0)?.id, "1000") assertEquals(response1.data?.hero?.friends?.get(0)?.name, "Beast") assertEquals(response1.data?.hero?.friends?.get(1)?.id, "1002") assertEquals(response1.data?.hero?.friends?.get(1)?.name, "Han Solo") assertEquals(response1.data?.hero?.friends?.get(2)?.id, "1003") assertEquals(response1.data?.hero?.friends?.get(2)?.name, "Leia Organa") // check if query2 see the latest optimistic updates response2 = apolloClient.query(ApolloRequest(query2).withFetchPolicy(FetchPolicy.CacheOnly)) assertEquals(response2.data?.hero?.id, "1000") assertEquals(response2.data?.hero?.name, "Beast") // rollback query2 optimistic updates store.rollbackOptimisticUpdates(mutationId2, false) // check if query2 see the latest optimistic updates response2 = apolloClient.query(ApolloRequest(query2).withFetchPolicy(FetchPolicy.CacheOnly)) assertEquals(response2.data?.hero?.id, "1000") assertEquals(response2.data?.hero?.name, "SuperMan") } @Test fun mutation_and_query_watcher() = runWithMainLoop { mockServer.enqueue(readResource("ReviewsEmpireEpisodeResponse.json")) val channel = Channel<ReviewsByEpisodeQuery.Data?>() val job = launch { apolloClient.watch( ApolloRequest(ReviewsByEpisodeQuery(Episode.EMPIRE)) .withFetchPolicy(FetchPolicy.NetworkOnly) .withRefetchPolicy(FetchPolicy.CacheOnly) ).collect { channel.send(it.data) } } var watcherData = channel.receive() // before mutation and optimistic updates assertEquals(watcherData?.reviews?.size, 3) assertEquals(watcherData?.reviews?.get(0)?.id, "empireReview1") assertEquals(watcherData?.reviews?.get(0)?.stars, 1) assertEquals(watcherData?.reviews?.get(0)?.commentary, "Boring") assertEquals(watcherData?.reviews?.get(1)?.id, "empireReview2") assertEquals(watcherData?.reviews?.get(1)?.stars, 2) assertEquals(watcherData?.reviews?.get(1)?.commentary, "So-so") assertEquals(watcherData?.reviews?.get(2)?.id, "empireReview3") assertEquals(watcherData?.reviews?.get(2)?.stars, 5) assertEquals(watcherData?.reviews?.get(2)?.commentary, "Amazing") mockServer.enqueue(readResource("UpdateReviewResponse.json")) val updateReviewMutation = UpdateReviewMutation( "empireReview2", ReviewInput( commentary = Optional.Present("Not Bad"), stars = 4, favoriteColor = ColorInput() ) ) apolloClient.mutate( ApolloRequest(updateReviewMutation).withOptimiticUpdates( UpdateReviewMutation.Data( UpdateReviewMutation.Data.UpdateReview( "empireReview2", 5, "Great" ) ) ) ) // optimistic updates watcherData = channel.receive() assertEquals(watcherData?.reviews?.size, 3) assertEquals(watcherData?.reviews?.get(0)?.id, "empireReview1") assertEquals(watcherData?.reviews?.get(0)?.stars, 1) assertEquals(watcherData?.reviews?.get(0)?.commentary, "Boring") assertEquals(watcherData?.reviews?.get(1)?.id, "empireReview2") assertEquals(watcherData?.reviews?.get(1)?.stars, 5) assertEquals(watcherData?.reviews?.get(1)?.commentary, "Great") assertEquals(watcherData?.reviews?.get(2)?.id, "empireReview3") assertEquals(watcherData?.reviews?.get(2)?.stars, 5) assertEquals(watcherData?.reviews?.get(2)?.commentary, "Amazing") // after mutation with rolled back optimistic updates watcherData = channel.receiveOrTimeout() assertEquals(watcherData?.reviews?.size, 3) assertEquals(watcherData?.reviews?.get(0)?.id, "empireReview1") assertEquals(watcherData?.reviews?.get(0)?.stars, 1) assertEquals(watcherData?.reviews?.get(0)?.commentary, "Boring") assertEquals(watcherData?.reviews?.get(1)?.id, "empireReview2") assertEquals(watcherData?.reviews?.get(1)?.stars, 4) assertEquals(watcherData?.reviews?.get(1)?.commentary, "Not Bad") assertEquals(watcherData?.reviews?.get(2)?.id, "empireReview3") assertEquals(watcherData?.reviews?.get(2)?.stars, 5) assertEquals(watcherData?.reviews?.get(2)?.commentary, "Amazing") job.cancel() } @Test @Throws(Exception::class) fun two_optimistic_reverse_rollback_order() = runWithMainLoop { val query1 = HeroAndFriendsNamesWithIDsQuery(Episode.JEDI) val mutationId1 = uuid4() val query2 = HeroNameWithIdQuery() val mutationId2 = uuid4() mockServer.enqueue(readResource("HeroAndFriendsNameWithIdsResponse.json")) apolloClient.query(query1) mockServer.enqueue(readResource("HeroNameWithIdResponse.json")) apolloClient.query(query2) val data1 = HeroAndFriendsNamesWithIDsQuery.Data( HeroAndFriendsNamesWithIDsQuery.Data.Hero( "2001", "R222-D222", listOf( HeroAndFriendsNamesWithIDsQuery.Data.Hero.Friend( "1000", "Robocop" ), HeroAndFriendsNamesWithIDsQuery.Data.Hero.Friend( "1003", "Batman" ) ) ) ) store.writeOptimisticUpdates( operation = query1, operationData = data1, mutationId = mutationId1, publish = true) val data2 = HeroNameWithIdQuery.Data(HeroNameWithIdQuery.Data.Hero( "1000", "Spiderman" )) store.writeOptimisticUpdates( operation = query2, operationData = data2, mutationId = mutationId2, publish = true) // check if query1 see optimistic updates var response1 = apolloClient.query(ApolloRequest(query1).withFetchPolicy(FetchPolicy.CacheOnly)) assertEquals(response1.data?.hero?.id, "2001") assertEquals(response1.data?.hero?.name, "R222-D222") assertEquals(response1.data?.hero?.friends?.size, 2) assertEquals(response1.data?.hero?.friends?.get(0)?.id, "1000") assertEquals(response1.data?.hero?.friends?.get(0)?.name, "Spiderman") assertEquals(response1.data?.hero?.friends?.get(1)?.id, "1003") assertEquals(response1.data?.hero?.friends?.get(1)?.name, "Batman") // check if query2 see the latest optimistic updates var response2 = apolloClient.query(ApolloRequest(query2).withFetchPolicy(FetchPolicy.CacheOnly)) assertEquals(response2.data?.hero?.id, "1000") assertEquals(response2.data?.hero?.name, "Spiderman") // rollback query2 optimistic updates store.rollbackOptimisticUpdates(mutationId2, false) // check if query1 see the latest optimistic updates response1 = apolloClient.query(ApolloRequest(query1).withFetchPolicy(FetchPolicy.CacheOnly)) assertEquals(response1.data?.hero?.id, "2001") assertEquals(response1.data?.hero?.name, "R222-D222") assertEquals(response1.data?.hero?.friends?.size, 2) assertEquals(response1.data?.hero?.friends?.get(0)?.id, "1000") assertEquals(response1.data?.hero?.friends?.get(0)?.name, "Robocop") assertEquals(response1.data?.hero?.friends?.get(1)?.id, "1003") assertEquals(response1.data?.hero?.friends?.get(1)?.name, "Batman") // check if query2 see the latest optimistic updates response2 = apolloClient.query(ApolloRequest(query2).withFetchPolicy(FetchPolicy.CacheOnly)) assertEquals(response2.data?.hero?.id, "1000") assertEquals(response2.data?.hero?.name, "Robocop") // rollback query1 optimistic updates store.rollbackOptimisticUpdates(mutationId1, false) // check if query1 see the latest non-optimistic updates response1 = apolloClient.query(ApolloRequest(query1).withFetchPolicy(FetchPolicy.CacheOnly)) assertEquals(response1.data?.hero?.id, "2001") assertEquals(response1.data?.hero?.name, "R2-D2") assertEquals(response1.data?.hero?.friends?.size, 3) assertEquals(response1.data?.hero?.friends?.get(0)?.id, "1000") assertEquals(response1.data?.hero?.friends?.get(0)?.name, "SuperMan") assertEquals(response1.data?.hero?.friends?.get(1)?.id, "1002") assertEquals(response1.data?.hero?.friends?.get(1)?.name, "Han Solo") assertEquals(response1.data?.hero?.friends?.get(2)?.id, "1003") assertEquals(response1.data?.hero?.friends?.get(2)?.name, "Leia Organa") // check if query2 see the latest non-optimistic updates response2 = apolloClient.query(ApolloRequest(query2).withFetchPolicy(FetchPolicy.CacheOnly)) assertEquals(response2.data?.hero?.id, "1000") assertEquals(response2.data?.hero?.name, "SuperMan") } }
mit
5996469f0ba384425c5fc33692f2748e
41.530184
100
0.709578
4.043923
false
false
false
false
k9mail/k-9
app/storage/src/test/java/com/fsck/k9/storage/messages/SaveMessageOperationsTest.kt
2
21691
package com.fsck.k9.storage.messages import com.fsck.k9.K9 import com.fsck.k9.mail.Address import com.fsck.k9.mail.Flag import com.fsck.k9.mail.Message import com.fsck.k9.mail.MessageDownloadState import com.fsck.k9.mail.Multipart import com.fsck.k9.mail.Part import com.fsck.k9.mail.buildMessage import com.fsck.k9.mailstore.SaveMessageData import com.fsck.k9.mailstore.StorageManager import com.fsck.k9.message.extractors.BasicPartInfoExtractor import com.fsck.k9.message.extractors.PreviewResult import com.fsck.k9.storage.RobolectricTest import com.google.common.truth.Truth.assertThat import java.io.ByteArrayOutputStream import java.util.Stack import org.junit.After import org.junit.Test import org.mockito.kotlin.anyOrNull import org.mockito.kotlin.doReturn import org.mockito.kotlin.eq import org.mockito.kotlin.mock private const val ACCOUNT_UUID = "00000000-0000-4000-0000-000000000000" class SaveMessageOperationsTest : RobolectricTest() { private val messagePartDirectory = createRandomTempDirectory() private val sqliteDatabase = createDatabase() private val storageManager = mock<StorageManager> { on { getAttachmentDirectory(eq(ACCOUNT_UUID), anyOrNull()) } doReturn messagePartDirectory } private val lockableDatabase = createLockableDatabaseMock(sqliteDatabase) private val attachmentFileManager = AttachmentFileManager(storageManager, ACCOUNT_UUID) private val basicPartInfoExtractor = BasicPartInfoExtractor() private val threadMessageOperations = ThreadMessageOperations() private val saveMessageOperations = SaveMessageOperations( lockableDatabase, attachmentFileManager, basicPartInfoExtractor, threadMessageOperations ) @After fun tearDown() { messagePartDirectory.deleteRecursively() } @Test fun `save message with text_plain body`() { val messageData = buildMessage { header("Subject", "Test Message") header("From", "[email protected]") header("To", "Bob <[email protected]>") header("Cc", "<[email protected]>") header("Date", "Mon, 12 Apr 2021 03:42:00 +0200") header("Message-ID", "<[email protected]>") textBody("Text") }.apply { setFlag(Flag.FLAGGED, true) setFlag(Flag.SEEN, true) setFlag(Flag.ANSWERED, true) setFlag(Flag.FORWARDED, true) }.toSaveMessageData( previewResult = PreviewResult.text("Preview") ) saveMessageOperations.saveRemoteMessage(folderId = 1, messageServerId = "uid1", messageData) val messages = sqliteDatabase.readMessages() assertThat(messages).hasSize(1) val message = messages.first() with(message) { assertThat(deleted).isEqualTo(0) assertThat(folderId).isEqualTo(1) assertThat(uid).isEqualTo("uid1") assertThat(subject).isEqualTo("Test Message") assertThat(date).isEqualTo(1618191720000L) assertThat(internalDate).isEqualTo(1618191720000L) assertThat(flags).isEqualTo("X_DOWNLOADED_FULL") assertThat(senderList).isEqualTo("[email protected]") assertThat(toList).isEqualTo(Address.pack(Address.parse("Bob <[email protected]>"))) assertThat(ccList).isEqualTo("[email protected]") assertThat(bccList).isEqualTo("") assertThat(replyToList).isEqualTo("") assertThat(attachmentCount).isEqualTo(0) assertThat(messageId).isEqualTo("<[email protected]>") assertThat(previewType).isEqualTo("text") assertThat(preview).isEqualTo("Preview") assertThat(mimeType).isEqualTo("text/plain") assertThat(empty).isEqualTo(0) assertThat(read).isEqualTo(1) assertThat(flagged).isEqualTo(1) assertThat(answered).isEqualTo(1) assertThat(forwarded).isEqualTo(1) assertThat(encryptionType).isNull() } val messageParts = sqliteDatabase.readMessageParts() assertThat(messageParts).hasSize(1) val messagePart = messageParts.first() with(messagePart) { assertThat(type).isEqualTo(MessagePartType.UNKNOWN) assertThat(root).isEqualTo(messagePart.id) assertThat(parent).isEqualTo(-1) assertThat(seq).isEqualTo(0) assertThat(mimeType).isEqualTo("text/plain") assertThat(displayName).isEqualTo("noname.txt") assertThat(header?.toString(Charsets.UTF_8)).isEqualTo(messageData.message.header()) assertThat(encoding).isEqualTo("quoted-printable") assertThat(charset).isNull() assertThat(dataLocation).isEqualTo(DataLocation.IN_DATABASE) assertThat(decodedBodySize).isEqualTo(4) assertThat(data?.toString(Charsets.UTF_8)).isEqualTo("Text") assertThat(preamble).isNull() assertThat(epilogue).isNull() assertThat(boundary).isNull() assertThat(contentId).isNull() assertThat(serverExtra).isNull() } val threads = sqliteDatabase.readThreads() assertThat(threads).hasSize(1) val thread = threads.first() with(thread) { assertThat(messageId).isEqualTo(message.id) assertThat(root).isEqualTo(id) assertThat(parent).isNull() } } @Test fun `save message with multipart body`() { val messageData = buildMessage { multipart("alternative") { bodyPart("text/plain") { textBody("plain") } bodyPart("text/html") { textBody("html") } } }.toSaveMessageData() saveMessageOperations.saveRemoteMessage(folderId = 1, messageServerId = "uid1", messageData) val messages = sqliteDatabase.readMessages() assertThat(messages).hasSize(1) val messageParts = sqliteDatabase.readMessageParts() assertThat(messageParts).hasSize(3) val rootMessagePart = messageParts.first { it.seq == 0 } with(rootMessagePart) { assertThat(type).isEqualTo(MessagePartType.UNKNOWN) assertThat(root).isEqualTo(id) assertThat(parent).isEqualTo(-1) assertThat(mimeType).isEqualTo("multipart/alternative") assertThat(displayName).isNull() assertThat(header?.toString(Charsets.UTF_8)).isEqualTo(messageData.message.header()) assertThat(encoding).isNull() assertThat(charset).isNull() assertThat(dataLocation).isEqualTo(DataLocation.CHILD_PART_CONTAINS_DATA) assertThat(decodedBodySize).isNull() assertThat(data).isNull() assertThat(preamble).isNull() assertThat(epilogue).isNull() assertThat(boundary).isEqualTo(messageData.message.boundary()) assertThat(contentId).isNull() assertThat(serverExtra).isNull() } val textPlainMessagePart = messageParts.first { it.seq == 1 } with(textPlainMessagePart) { assertThat(type).isEqualTo(MessagePartType.UNKNOWN) assertThat(root).isEqualTo(rootMessagePart.id) assertThat(parent).isEqualTo(rootMessagePart.id) assertThat(mimeType).isEqualTo("text/plain") assertThat(displayName).isEqualTo("noname.txt") assertThat(header).isNotNull() assertThat(encoding).isEqualTo("quoted-printable") assertThat(charset).isNull() assertThat(dataLocation).isEqualTo(DataLocation.IN_DATABASE) assertThat(decodedBodySize).isEqualTo(5) assertThat(data?.toString(Charsets.UTF_8)).isEqualTo("plain") assertThat(preamble).isNull() assertThat(epilogue).isNull() assertThat(boundary).isNull() assertThat(contentId).isNull() assertThat(serverExtra).isNull() } val textHtmlMessagePart = messageParts.first { it.seq == 2 } with(textHtmlMessagePart) { assertThat(type).isEqualTo(MessagePartType.UNKNOWN) assertThat(root).isEqualTo(rootMessagePart.id) assertThat(parent).isEqualTo(rootMessagePart.id) assertThat(mimeType).isEqualTo("text/html") assertThat(displayName).isEqualTo("noname.html") assertThat(header).isNotNull() assertThat(encoding).isEqualTo("quoted-printable") assertThat(charset).isNull() assertThat(dataLocation).isEqualTo(DataLocation.IN_DATABASE) assertThat(decodedBodySize).isEqualTo(4) assertThat(data?.toString(Charsets.UTF_8)).isEqualTo("html") assertThat(preamble).isNull() assertThat(epilogue).isNull() assertThat(boundary).isNull() assertThat(contentId).isNull() assertThat(serverExtra).isNull() } } @Test fun `save message into existing thread`() { val messageId1 = sqliteDatabase.createMessage( folderId = 1, empty = true, messageIdHeader = "<[email protected]>" ) val messageId2 = sqliteDatabase.createMessage( folderId = 1, empty = true, messageIdHeader = "<[email protected]>" ) val messageId3 = sqliteDatabase.createMessage( folderId = 1, empty = false, messageIdHeader = "<[email protected]>" ) val threadId1 = sqliteDatabase.createThread(messageId1) val threadId2 = sqliteDatabase.createThread(messageId2, root = threadId1, parent = threadId1) val threadId3 = sqliteDatabase.createThread(messageId3, root = threadId1, parent = threadId2) val messageData = buildMessage { header("Message-ID", "<[email protected]>") header("In-Reply-To", "<[email protected]>") textBody() }.toSaveMessageData() saveMessageOperations.saveRemoteMessage(folderId = 1, messageServerId = "uid1", messageData) val threads = sqliteDatabase.readThreads() assertThat(threads).hasSize(3) assertThat(threads.first { it.id == threadId1 }).isEqualTo( ThreadEntry( id = threadId1, messageId = messageId1, root = threadId1, parent = null ) ) assertThat(threads.first { it.id == threadId2 }).isEqualTo( ThreadEntry( id = threadId2, messageId = messageId2, root = threadId1, parent = threadId1 ) ) assertThat(threads.first { it.id == threadId3 }).isEqualTo( ThreadEntry( id = threadId3, messageId = messageId3, root = threadId1, parent = threadId2 ) ) } @Test fun `save message with references header should create empty messages`() { val messageData = buildMessage { header("Message-ID", "<[email protected]>") header("In-Reply-To", "<[email protected]>") header("References", "<[email protected]> <[email protected]>") textBody() }.toSaveMessageData() saveMessageOperations.saveRemoteMessage(folderId = 1, messageServerId = "uid1", messageData) val messages = sqliteDatabase.readMessages() assertThat(messages).hasSize(3) val threads = sqliteDatabase.readThreads() assertThat(threads).hasSize(3) val thread1 = threads.first { it.id == it.root } val message1 = messages.first { it.id == thread1.messageId } assertThat(message1.empty).isEqualTo(1) val thread2 = threads.first { it.parent == thread1.id } val message2 = messages.first { it.id == thread2.messageId } assertThat(message2.empty).isEqualTo(1) val thread3 = threads.first { it.parent == thread2.id } val message3 = messages.first { it.id == thread3.messageId } assertThat(message3.empty).isEqualTo(0) assertThat(message3.uid).isEqualTo("uid1") } @Test fun `save message with server ID already existing in MessageStore should replace that message`() { val existingMessageData = buildMessage { multipart("alternative") { bodyPart("text/plain") { textBody("plain") } bodyPart("text/html") { textBody("html") } } }.toSaveMessageData() saveMessageOperations.saveRemoteMessage(folderId = 1, messageServerId = "uid1", existingMessageData) val messageData = buildMessage { textBody("new") }.toSaveMessageData() saveMessageOperations.saveRemoteMessage(folderId = 1, messageServerId = "uid1", messageData) val messages = sqliteDatabase.readMessages() assertThat(messages).hasSize(1) val messageParts = sqliteDatabase.readMessageParts() assertThat(messageParts).hasSize(1) val messagePart = messageParts.first() with(messagePart) { assertThat(type).isEqualTo(MessagePartType.UNKNOWN) assertThat(root).isEqualTo(messagePart.id) assertThat(parent).isEqualTo(-1) assertThat(mimeType).isEqualTo("text/plain") assertThat(displayName).isEqualTo("noname.txt") assertThat(header).isNotNull() assertThat(encoding).isEqualTo("quoted-printable") assertThat(charset).isNull() assertThat(dataLocation).isEqualTo(DataLocation.IN_DATABASE) assertThat(decodedBodySize).isEqualTo(3) assertThat(data?.toString(Charsets.UTF_8)).isEqualTo("new") assertThat(preamble).isNull() assertThat(epilogue).isNull() assertThat(boundary).isNull() assertThat(contentId).isNull() assertThat(serverExtra).isNull() } val threads = sqliteDatabase.readThreads() assertThat(threads).hasSize(1) val thread = threads.first() val message = messages.first() assertThat(thread.root).isEqualTo(thread.id) assertThat(thread.parent).isNull() assertThat(thread.messageId).isEqualTo(message.id) } @Test fun `save local message`() { val messageData = buildMessage { textBody("local") }.toSaveMessageData( subject = "Provided subject", date = 1618191720000L, internalDate = 1618191720000L, previewResult = PreviewResult.text("Preview") ) val newMessageId = saveMessageOperations.saveLocalMessage(folderId = 1, messageData, existingMessageId = null) val messages = sqliteDatabase.readMessages() assertThat(messages).hasSize(1) val message = messages.first() with(message) { assertThat(id).isEqualTo(newMessageId) assertThat(deleted).isEqualTo(0) assertThat(folderId).isEqualTo(1) assertThat(uid).startsWith(K9.LOCAL_UID_PREFIX) assertThat(subject).isEqualTo("Provided subject") assertThat(date).isEqualTo(1618191720000L) assertThat(internalDate).isEqualTo(1618191720000L) assertThat(flags).isEqualTo("X_DOWNLOADED_FULL") assertThat(senderList).isEqualTo("") assertThat(toList).isEqualTo("") assertThat(ccList).isEqualTo("") assertThat(bccList).isEqualTo("") assertThat(replyToList).isEqualTo("") assertThat(attachmentCount).isEqualTo(0) assertThat(messageId).isNull() assertThat(previewType).isEqualTo("text") assertThat(preview).isEqualTo("Preview") assertThat(mimeType).isEqualTo("text/plain") assertThat(empty).isEqualTo(0) assertThat(read).isEqualTo(0) assertThat(flagged).isEqualTo(0) assertThat(answered).isEqualTo(0) assertThat(forwarded).isEqualTo(0) assertThat(encryptionType).isNull() } val messageParts = sqliteDatabase.readMessageParts() assertThat(messageParts).hasSize(1) val messagePart = messageParts.first() with(messagePart) { assertThat(type).isEqualTo(MessagePartType.UNKNOWN) assertThat(root).isEqualTo(messagePart.id) assertThat(parent).isEqualTo(-1) assertThat(mimeType).isEqualTo("text/plain") assertThat(displayName).isEqualTo("noname.txt") assertThat(header).isNotNull() assertThat(encoding).isEqualTo("quoted-printable") assertThat(charset).isNull() assertThat(dataLocation).isEqualTo(DataLocation.IN_DATABASE) assertThat(decodedBodySize).isEqualTo(5) assertThat(data?.toString(Charsets.UTF_8)).isEqualTo("local") assertThat(preamble).isNull() assertThat(epilogue).isNull() assertThat(boundary).isNull() assertThat(contentId).isNull() assertThat(serverExtra).isNull() } val threads = sqliteDatabase.readThreads() assertThat(threads).hasSize(1) val thread = threads.first() assertThat(thread.root).isEqualTo(thread.id) assertThat(thread.parent).isNull() assertThat(thread.messageId).isEqualTo(message.id) } @Test fun `replace local message`() { val existingMessageData = buildMessage { multipart("alternative") { bodyPart("text/plain") { textBody("plain") } bodyPart("text/html") { textBody("html") } } }.toSaveMessageData() val existingMessageId = saveMessageOperations.saveLocalMessage( folderId = 1, existingMessageData, existingMessageId = null ) val messageData = buildMessage { textBody("new") }.toSaveMessageData() val newMessageId = saveMessageOperations.saveLocalMessage(folderId = 1, messageData, existingMessageId) val messages = sqliteDatabase.readMessages() assertThat(messages).hasSize(1) assertThat(messages.first().id).isEqualTo(newMessageId) val messageParts = sqliteDatabase.readMessageParts() assertThat(messageParts).hasSize(1) val messagePart = messageParts.first() with(messagePart) { assertThat(type).isEqualTo(MessagePartType.UNKNOWN) assertThat(root).isEqualTo(messagePart.id) assertThat(parent).isEqualTo(-1) assertThat(mimeType).isEqualTo("text/plain") assertThat(displayName).isEqualTo("noname.txt") assertThat(header).isNotNull() assertThat(encoding).isEqualTo("quoted-printable") assertThat(charset).isNull() assertThat(dataLocation).isEqualTo(DataLocation.IN_DATABASE) assertThat(decodedBodySize).isEqualTo(3) assertThat(data?.toString(Charsets.UTF_8)).isEqualTo("new") assertThat(preamble).isNull() assertThat(epilogue).isNull() assertThat(boundary).isNull() assertThat(contentId).isNull() assertThat(serverExtra).isNull() } val threads = sqliteDatabase.readThreads() assertThat(threads).hasSize(1) val thread = threads.first() val message = messages.first() assertThat(thread.root).isEqualTo(thread.id) assertThat(thread.parent).isNull() assertThat(thread.messageId).isEqualTo(message.id) } private fun Message.toSaveMessageData( subject: String? = getSubject(), date: Long = sentDate?.time ?: System.currentTimeMillis(), internalDate: Long = date, downloadState: MessageDownloadState = getDownloadState(), attachmentCount: Int = 0, previewResult: PreviewResult = PreviewResult.none(), textForSearchIndex: String? = null, encryptionType: String? = null ): SaveMessageData { return SaveMessageData( message = this, subject, date, internalDate, downloadState, attachmentCount, previewResult, textForSearchIndex, encryptionType ) } private fun Message.getDownloadState(): MessageDownloadState { if (body == null) return MessageDownloadState.ENVELOPE val stack = Stack<Part>() stack.push(this) while (stack.isNotEmpty()) { val part = stack.pop() when (val body = part.body) { null -> return MessageDownloadState.PARTIAL is Multipart -> { for (i in 0 until body.count) { stack.push(body.getBodyPart(i)) } } } } return MessageDownloadState.FULL } private fun Message.header(): String { val outputStream = ByteArrayOutputStream() writeHeaderTo(outputStream) return outputStream.toString("UTF-8") } private fun Message.boundary(): String? = (body as Multipart).boundary }
apache-2.0
c79fb70d7d43b3d2b66b5fdc61dddc51
38.366606
118
0.620396
4.948893
false
false
false
false
Maccimo/intellij-community
platform/workspaceModel/storage/src/com/intellij/workspaceModel/storage/impl/Entities.kt
1
25442
// 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.storage.impl import com.intellij.util.ReflectionUtil import com.intellij.workspaceModel.storage.* import com.intellij.workspaceModel.storage.impl.indices.VirtualFileIndex import com.intellij.workspaceModel.storage.impl.indices.WorkspaceMutableIndex import com.intellij.workspaceModel.storage.url.VirtualFileUrl import kotlin.reflect.KClass /** * For creating a new entity, you should perform the following steps: * * - Choose the name of the entity, e.g. MyModuleEntity * - Create [WorkspaceEntity] representation: * - The entity should inherit [WorkspaceEntityBase] * - Properties (not references to other entities) should be listed in a primary constructor as val's * - If the entity has PersistentId, the entity should extend [WorkspaceEntityWithPersistentId] * - If the entity has references to other entities, they should be implement using property delegation objects listed in [com.intellij.workspaceModel.storage.impl.references] package. * E.g. [OneToMany] or [ManyToOne.NotNull] * * Example: * * ```kotlin * class MyModuleEntity(val name: String) : WorkspaceEntityBase(), WorkspaceEntityWithPersistentId { * * val childModule: MyModuleEntity? by OneToOneParent.Nullable(MyModuleEntity::class.java, true) * * fun persistentId = NameId(name) * } * ``` * * The above entity describes an entity with `name` property, persistent id and the reference to "ChildModule" * * This object will be used by users and it's returned by methods like `resolve`, `entities` and so on. * * ------------------------------------------------------------------------------------------------------------------------------- * * - Create EntityData representation: * - Entity data should have the name ${entityName}Data. E.g. MyModuleEntityData. * - Entity data should inherit [WorkspaceEntityData] * - Properties (not references to other entities) should be listed in the body as lateinit var's or with default value (null, 0, false). * - If the entity has PersistentId, the Entity data should extend [WorkspaceEntityData.WithCalculablePersistentId] * - References to other entities should not be listed in entity data. * * - If the entity contains soft references to other entities (persistent id to other entities), entity data should extend SoftLinkable * interface and implement the required methods. Check out the [FacetEntityData] implementation, but keep in mind the this might * be more complicated like in [ModuleEntityData]. * - Entity data should implement [WorkspaceEntityData.createEntity] method. This method should return an instance of * [WorkspaceEntity]. This instance should be passed to [addMetaData] after creation! * E.g.: * * override fun createEntity(snapshot: WorkspaceEntityStorage): ModuleEntity = ModuleEntity(name, type, dependencies).also { * addMetaData(it, snapshot) * } * * Example: * * ```kotlin * class MyModuleEntityData : WorkspaceEntityData.WithCalculablePersistentId<MyModuleEntity>() { * lateinit var name: String * * override fun persistentId(): NameId = NameId(name) * * override fun createEntity(snapshot: WorkspaceEntityStorage): MyModuleEntity = MyModuleEntity(name).also { * addMetaData(it, snapshot) * } * } * ``` * * This is an internal representation of WorkspaceEntity. It's not passed to users. * * ------------------------------------------------------------------------------------------------------------------------------- * * - Create [ModifiableWorkspaceEntity] representation: * - The name should be: Modifiable${entityName}. E.g. ModifiableMyModuleEntity * - This should be inherited from [ModifiableWorkspaceEntityBase] * - Properties (not references to other entities) should be listed in the body as delegation to [EntityDataDelegation()] * - References to other entities should be listed as in [WorkspaceEntity], but with corresponding modifiable delegates * * Example: * * ```kotlin * class ModifiableMyModuleEntity : ModifiableWorkspaceEntityBase<MyModuleEntity>() { * var name: String by EntityDataDelegation() * * var childModule: MyModuleEntity? by MutableOneToOneParent.NotNull(MyModuleEntity::class.java, MyModuleEntity::class.java, true) * } * ``` */ abstract class WorkspaceEntityBase : ReferableWorkspaceEntity, Any() { override lateinit var entitySource: EntitySource internal set var id: EntityId = 0 lateinit var snapshot: EntityStorage abstract fun connectionIdList(): List<ConnectionId> override fun <R : WorkspaceEntity> referrers(entityClass: Class<R>, propertyName: String): Sequence<R> { val mySnapshot = snapshot as AbstractEntityStorage return getReferences(mySnapshot, entityClass) } internal fun <R : WorkspaceEntity> getReferences( mySnapshot: AbstractEntityStorage, entityClass: Class<R> ): Sequence<R> { var connectionId = mySnapshot.refs.findConnectionId(getEntityInterface(), entityClass) if (connectionId != null) { return when (connectionId.connectionType) { ConnectionId.ConnectionType.ONE_TO_MANY -> mySnapshot.extractOneToManyChildren(connectionId, id) ConnectionId.ConnectionType.ONE_TO_ONE -> mySnapshot.extractOneToOneChild<R>(connectionId, id) ?.let { sequenceOf(it) } ?: emptySequence() ConnectionId.ConnectionType.ONE_TO_ABSTRACT_MANY -> mySnapshot.extractOneToAbstractManyChildren( connectionId, id.asParent() ) ConnectionId.ConnectionType.ABSTRACT_ONE_TO_ONE -> /*mySnapshot.extractAbstractOneToOneChild<R>(connectionId, id.asParent())?.let { sequenceOf(it) } ?: */emptySequence() } } connectionId = mySnapshot.refs.findConnectionId(entityClass, getEntityInterface()) if (connectionId != null) { return when (connectionId.connectionType) { ConnectionId.ConnectionType.ONE_TO_MANY -> mySnapshot.extractOneToManyParent<R>(connectionId, id)?.let { sequenceOf(it) } ?: emptySequence() ConnectionId.ConnectionType.ONE_TO_ONE -> mySnapshot.extractOneToOneParent<R>(connectionId, id) ?.let { sequenceOf(it) } ?: emptySequence() ConnectionId.ConnectionType.ONE_TO_ABSTRACT_MANY -> mySnapshot.extractOneToAbstractManyParent<R>( connectionId, id.asChild() ) ?.let { sequenceOf(it) } ?: emptySequence() ConnectionId.ConnectionType.ABSTRACT_ONE_TO_ONE -> /*mySnapshot.extractAbstractOneToOneChild<R>(connectionId, id.asParent())?.let { sequenceOf(it) } ?: */emptySequence() } } return emptySequence() } override fun <E : WorkspaceEntity> createReference(): EntityReference<E> { return EntityReferenceImpl(this.id) } override fun getEntityInterface(): Class<out WorkspaceEntity> = id.clazz.findWorkspaceEntity() override fun toString(): String = id.asString() override fun equals(other: Any?): Boolean { if (this === other) return true if (other !is WorkspaceEntityBase) return false if (id != other.id) return false if ((this.snapshot as AbstractEntityStorage).entityDataById(id) !== (other.snapshot as AbstractEntityStorage).entityDataById(other.id) ) return false return true } override fun hashCode(): Int = id.hashCode() } data class EntityLink( val isThisFieldChild: Boolean, val connectionId: ConnectionId, ) val EntityLink.remote: EntityLink get() = EntityLink(!this.isThisFieldChild, connectionId) abstract class ModifiableWorkspaceEntityBase<T : WorkspaceEntity> : WorkspaceEntityBase(), ModifiableWorkspaceEntity<T>, ModifiableReferableWorkspaceEntity { /** * In case any of two referred entities is not added to diff, the reference between entities will be stored in this field */ val entityLinks: MutableMap<EntityLink, Any?> = HashMap() internal lateinit var original: WorkspaceEntityData<T> var diff: MutableEntityStorage? = null val modifiable: ThreadLocal<Boolean> = ThreadLocal.withInitial { false } val changedProperty: MutableSet<String> = mutableSetOf() override fun linkExternalEntity(entityClass: KClass<out WorkspaceEntity>, isThisFieldChild: Boolean, entities: List<WorkspaceEntity?>) { val foundConnectionId = findConnectionId(entityClass, entities) if (foundConnectionId == null) return // If the diff is empty, we should link entities using the internal map // If it's not, we should add entity to store and update indexes val myDiff = diff if (myDiff != null) { //if (foundConnectionId.parentClass == getEntityClass().toClassId()) { if (isThisFieldChild) { // Branch for case `this` entity is a parent if (foundConnectionId.connectionType == ConnectionId.ConnectionType.ONE_TO_MANY || foundConnectionId.connectionType == ConnectionId.ConnectionType.ONE_TO_ABSTRACT_MANY) { // One - to - many connection for (item in entities) { if (item != null && item is ModifiableWorkspaceEntityBase<*> && item.diff == null) { @Suppress("KotlinConstantConditions") item.entityLinks[EntityLink(!isThisFieldChild, foundConnectionId)] = this myDiff.addEntity(item) } } myDiff.updateOneToManyChildrenOfParent(foundConnectionId, this, entities.filterNotNull()) } else { // One - to -one connection val item = entities.single() if (item != null && item is ModifiableWorkspaceEntityBase<*> && item.diff == null) { @Suppress("KotlinConstantConditions") item.entityLinks[EntityLink(!isThisFieldChild, foundConnectionId)] = this myDiff.addEntity(item) } myDiff.updateOneToOneChildOfParent(foundConnectionId, this, item) } } else { // Branch for case `this` entity is a child if (foundConnectionId.connectionType == ConnectionId.ConnectionType.ONE_TO_MANY || foundConnectionId.connectionType == ConnectionId.ConnectionType.ONE_TO_ABSTRACT_MANY) { // One - to - many connection val item = entities.single() if (item != null && item is ModifiableWorkspaceEntityBase<*> && item.diff == null) { @Suppress("KotlinConstantConditions", "UNCHECKED_CAST") item.entityLinks[EntityLink(!isThisFieldChild, foundConnectionId)] = (item.entityLinks[EntityLink(!isThisFieldChild, foundConnectionId)] as? List<Any> ?: emptyList()) + this myDiff.addEntity(item) } myDiff.updateOneToManyParentOfChild(foundConnectionId, this, item) } else { // One - to -one connection val item = entities.single() if (item != null && item is ModifiableWorkspaceEntityBase<*> && item.diff == null) { @Suppress("KotlinConstantConditions") item.entityLinks[EntityLink(!isThisFieldChild, foundConnectionId)] = this myDiff.addEntity(item) } myDiff.updateOneToOneParentOfChild(foundConnectionId, this, item) } } } else { //if (foundConnectionId.parentClass == getEntityClass().toClassId()) { if (isThisFieldChild) { // Branch for case `this` entity is a parent if (foundConnectionId.connectionType == ConnectionId.ConnectionType.ONE_TO_MANY || foundConnectionId.connectionType == ConnectionId.ConnectionType.ONE_TO_ABSTRACT_MANY) { // One - to - many connection @Suppress("KotlinConstantConditions") this.entityLinks[EntityLink(isThisFieldChild, foundConnectionId)] = entities for (item in entities) { if (item != null && item is ModifiableWorkspaceEntityBase<*>) { @Suppress("KotlinConstantConditions") item.entityLinks[EntityLink(!isThisFieldChild, foundConnectionId)] = this } } } else { // One - to -one connection val item = entities.single() @Suppress("KotlinConstantConditions") this.entityLinks[EntityLink(isThisFieldChild, foundConnectionId)] = item if (item != null && item is ModifiableWorkspaceEntityBase<*>) { @Suppress("KotlinConstantConditions") item.entityLinks[EntityLink(!isThisFieldChild, foundConnectionId)] = this } } } else { // Branch for case `this` entity is a child if (foundConnectionId.connectionType == ConnectionId.ConnectionType.ONE_TO_MANY || foundConnectionId.connectionType == ConnectionId.ConnectionType.ONE_TO_ABSTRACT_MANY) { // One - to - many connection val item = entities.single() @Suppress("KotlinConstantConditions") this.entityLinks[EntityLink(isThisFieldChild, foundConnectionId)] = item if (item != null && item is ModifiableWorkspaceEntityBase<*>) { @Suppress("KotlinConstantConditions", "UNCHECKED_CAST") item.entityLinks[EntityLink(!isThisFieldChild, foundConnectionId)] = (item.entityLinks[EntityLink(!isThisFieldChild, foundConnectionId)] as? List<Any> ?: emptyList()) + this } } else { // One - to -one connection val item = entities.single() @Suppress("KotlinConstantConditions") this.entityLinks[EntityLink(isThisFieldChild, foundConnectionId)] = item if (item != null && item is ModifiableWorkspaceEntityBase<*>) { @Suppress("KotlinConstantConditions") item.entityLinks[EntityLink(!isThisFieldChild, foundConnectionId)] = this } } } } } private fun findConnectionId(entityClass: KClass<out WorkspaceEntity>, entity: List<WorkspaceEntity?>): ConnectionId? { val someEntity = entity.filterNotNull().firstOrNull() return if (someEntity != null) { val firstClass = this.getEntityClass() (someEntity as WorkspaceEntityBase).connectionIdList().single { it.parentClass == firstClass.toClassId() && it.childClass == entityClass.java.toClassId() || it.childClass == firstClass.toClassId() && it.parentClass == entityClass.java.toClassId() } } else { val firstClass = this.getEntityClass() entityLinks.keys.asSequence().map { it.connectionId }.singleOrNull { it.parentClass == firstClass.toClassId() && it.childClass == entityClass.java.toClassId() || it.childClass == firstClass.toClassId() && it.parentClass == entityClass.java.toClassId() } } } override fun <R : WorkspaceEntity> referrers(entityClass: Class<R>, propertyName: String): Sequence<R> { val myDiff = diff val entitiesFromDiff = if (myDiff != null) { getReferences(myDiff as AbstractEntityStorage, entityClass) } else emptySequence() val entityClassId = entityClass.toClassId() val thisClassId = getEntityClass().toClassId() val res = entityLinks.entries.singleOrNull { it.key.connectionId.parentClass == entityClassId && it.key.connectionId.childClass == thisClassId || it.key.connectionId.parentClass == thisClassId && it.key.connectionId.childClass == entityClassId }?.value return entitiesFromDiff + if (res == null) { emptySequence() } else { if (res is List<*>) { @Suppress("UNCHECKED_CAST") res.asSequence() as Sequence<R> } else { @Suppress("UNCHECKED_CAST") sequenceOf(res as R) } } } inline fun allowModifications(action: () -> Unit) { modifiable.set(true) try { action() } finally { modifiable.remove() } } protected fun checkModificationAllowed() { if (diff != null && !modifiable.get()) { throw IllegalStateException("Modifications are allowed inside `modifyEntity` method only!") } } abstract fun getEntityClass(): Class<T> open fun applyToBuilder(builder: MutableEntityStorage) { throw NotImplementedError() } fun processLinkedEntities(builder: MutableEntityStorage) { val parentKeysToRemove = ArrayList<EntityLink>() for ((key, entity) in HashMap(entityLinks)) { if (key.isThisFieldChild) { processLinkedChildEntity(entity, builder, key.connectionId) } else { processLinkedParentEntity(entity, builder, key, parentKeysToRemove) } } for (key in parentKeysToRemove) { val data = entityLinks[key] if (data != null) { if (data is List<*>) { error("Cannot have parent lists") } else if (data is ModifiableWorkspaceEntityBase<*>) { val remoteData = data.entityLinks[key.remote] if (remoteData != null) { if (remoteData is List<*>) { data.entityLinks[key.remote] = remoteData.filterNot { it === this } } else { data.entityLinks.remove(key.remote) } } this.entityLinks.remove(key) } } } } private fun processLinkedParentEntity(entity: Any?, builder: MutableEntityStorage, entityLink: EntityLink, parentKeysToRemove: ArrayList<EntityLink>) { if (entity is List<*>) { error("Cannot have parent lists") } else if (entity is WorkspaceEntity) { if (entity is ModifiableWorkspaceEntityBase<*> && entity.diff == null) { builder.addEntity(entity) } applyParentRef(entityLink.connectionId, entity) parentKeysToRemove.add(entityLink) } } private fun processLinkedChildEntity(entity: Any?, builder: MutableEntityStorage, connectionId: ConnectionId) { if (entity is List<*>) { for (item in entity) { if (item is ModifiableWorkspaceEntityBase<*>) { builder.addEntity(item) } @Suppress("UNCHECKED_CAST") entity as List<WorkspaceEntity> val withBuilder_entity = entity.filter { it is ModifiableWorkspaceEntityBase<*> && it.diff != null } applyRef(connectionId, withBuilder_entity) } } else if (entity is WorkspaceEntity) { builder.addEntity(entity) applyRef(connectionId, entity) } } open fun getEntityData(): WorkspaceEntityData<T> { val actualEntityData = (diff as MutableEntityStorageImpl).entityDataById(id) ?: error("Requested entity data doesn't exist at entity family") @Suppress("UNCHECKED_CAST") return actualEntityData as WorkspaceEntityData<T> } // For generated entities fun addToBuilder() { val builder = diff as MutableEntityStorageImpl builder.putEntity(this) } // For generated entities private fun applyRef(connectionId: ConnectionId, child: WorkspaceEntity) { val builder = diff as MutableEntityStorageImpl when (connectionId.connectionType) { ConnectionId.ConnectionType.ONE_TO_ONE -> builder.updateOneToOneChildOfParent(connectionId, this, child) ConnectionId.ConnectionType.ABSTRACT_ONE_TO_ONE -> builder.updateOneToAbstractOneChildOfParent(connectionId, this, child) else -> error("Unexpected branch") } } private fun applyRef(connectionId: ConnectionId, children: List<WorkspaceEntity>) { val builder = diff as MutableEntityStorageImpl when (connectionId.connectionType) { ConnectionId.ConnectionType.ONE_TO_MANY -> builder.updateOneToManyChildrenOfParent(connectionId, this, children) ConnectionId.ConnectionType.ONE_TO_ABSTRACT_MANY -> builder.updateOneToAbstractManyChildrenOfParent(connectionId, this, children.asSequence()) else -> error("Unexpected branch") } } private fun applyParentRef(connectionId: ConnectionId, parent: WorkspaceEntity) { val builder = diff as MutableEntityStorageImpl when (connectionId.connectionType) { ConnectionId.ConnectionType.ONE_TO_ONE -> builder.updateOneToOneParentOfChild(connectionId, this, parent) ConnectionId.ConnectionType.ABSTRACT_ONE_TO_ONE -> builder.updateOneToAbstractOneParentOfChild(connectionId, this, parent) ConnectionId.ConnectionType.ONE_TO_MANY -> builder.updateOneToManyParentOfChild(connectionId, this, parent) ConnectionId.ConnectionType.ONE_TO_ABSTRACT_MANY -> builder.updateOneToAbstractManyParentOfChild(connectionId, this, parent) } } fun existsInBuilder(builder: MutableEntityStorage): Boolean { builder as MutableEntityStorageImpl val entityData = getEntityData() return builder.entityDataById(entityData.createEntityId()) != null } // For generated entities fun index(entity: WorkspaceEntity, propertyName: String, virtualFileUrl: VirtualFileUrl?) { val builder = diff as MutableEntityStorageImpl builder.getMutableVirtualFileUrlIndex().index(entity, propertyName, virtualFileUrl) } // For generated entities fun index(entity: WorkspaceEntity, propertyName: String, virtualFileUrls: Set<VirtualFileUrl>) { val builder = diff as MutableEntityStorageImpl (builder.getMutableVirtualFileUrlIndex() as VirtualFileIndex.MutableVirtualFileIndex).index((entity as WorkspaceEntityBase).id, propertyName, virtualFileUrls) } // For generated entities fun indexJarDirectories(entity: WorkspaceEntity, virtualFileUrls: Set<VirtualFileUrl>) { val builder = diff as MutableEntityStorageImpl (builder.getMutableVirtualFileUrlIndex() as VirtualFileIndex.MutableVirtualFileIndex).indexJarDirectories( (entity as WorkspaceEntityBase).id, virtualFileUrls) } } interface SoftLinkable { fun getLinks(): Set<PersistentEntityId<*>> fun index(index: WorkspaceMutableIndex<PersistentEntityId<*>>) fun updateLinksIndex(prev: Set<PersistentEntityId<*>>, index: WorkspaceMutableIndex<PersistentEntityId<*>>) fun updateLink(oldLink: PersistentEntityId<*>, newLink: PersistentEntityId<*>): Boolean } abstract class WorkspaceEntityData<E : WorkspaceEntity> : Cloneable, SerializableEntityData { lateinit var entitySource: EntitySource var id: Int = -1 fun isEntitySourceInitialized(): Boolean = ::entitySource.isInitialized fun createEntityId(): EntityId = createEntityId(id, getEntityInterface().toClassId()) abstract fun createEntity(snapshot: EntityStorage): E abstract fun wrapAsModifiable(diff: MutableEntityStorage): ModifiableWorkspaceEntity<E> abstract fun getEntityInterface(): Class<out WorkspaceEntity> @Suppress("UNCHECKED_CAST") public override fun clone(): WorkspaceEntityData<E> = super.clone() as WorkspaceEntityData<E> override fun equals(other: Any?): Boolean { if (other == null) return false if (this::class != other::class) return false return ReflectionUtil.collectFields(this.javaClass).filterNot { it.name == WorkspaceEntityData<*>::id.name } .onEach { it.isAccessible = true } .all { it.get(this) == it.get(other) } } open fun equalsIgnoringEntitySource(other: Any?): Boolean { if (other == null) return false if (this::class != other::class) return false return ReflectionUtil.collectFields(this.javaClass) .filterNot { it.name == WorkspaceEntityData<*>::id.name } .filterNot { it.name == WorkspaceEntityData<*>::entitySource.name } .onEach { it.isAccessible = true } .all { it.get(this) == it.get(other) } } override fun hashCode(): Int { return ReflectionUtil.collectFields(this.javaClass).filterNot { it.name == WorkspaceEntityData<*>::id.name } .onEach { it.isAccessible = true } .mapNotNull { it.get(this)?.hashCode() } .fold(31) { acc, i -> acc * 17 + i } } override fun toString(): String { val fields = ReflectionUtil.collectFields(this.javaClass).toList().onEach { it.isAccessible = true } .joinToString(separator = ", ") { f -> "${f.name}=${f.get(this)}" } return "${this::class.simpleName}($fields, id=${this.id})" } /** * Temporally solution. * Get persistent Id without creating of TypedEntity. Should be in sync with TypedEntityWithPersistentId. * But it doesn't everywhere. E.g. FacetEntity where we should resolve module before creating persistent id. */ abstract class WithCalculablePersistentId<E : WorkspaceEntity> : WorkspaceEntityData<E>() { abstract fun persistentId(): PersistentEntityId<*> } } fun WorkspaceEntityData<*>.persistentId(): PersistentEntityId<*>? = when (this) { is WorkspaceEntityData.WithCalculablePersistentId -> this.persistentId() else -> null } /** * This interface is a solution for checking consistency of some entities that can't be checked automatically * * For example, we can mark LibraryPropertiesEntityData with this interface and check that entity source of properties is the same as * entity source of the library itself. * * Interface should be applied to *entity data*. * * [assertConsistency] method is called during [MutableEntityStorageImpl.assertConsistency]. */ interface WithAssertableConsistency { fun assertConsistency(storage: EntityStorage) }
apache-2.0
e30b0e0c6f468e0d427422e3deeb6e5c
42.492308
259
0.680292
5.156465
false
false
false
false
Hexworks/zircon
zircon.core/src/commonMain/kotlin/org/hexworks/zircon/api/builder/component/IconBuilder.kt
1
1532
package org.hexworks.zircon.api.builder.component import org.hexworks.cobalt.databinding.api.extension.toProperty import org.hexworks.cobalt.databinding.api.property.Property import org.hexworks.zircon.api.component.Icon import org.hexworks.zircon.api.component.builder.base.BaseComponentBuilder import org.hexworks.zircon.api.data.Tile import org.hexworks.zircon.internal.component.impl.DefaultIcon import org.hexworks.zircon.internal.component.renderer.DefaultIconRenderer import org.hexworks.zircon.internal.dsl.ZirconDsl import kotlin.jvm.JvmStatic @Suppress("UNCHECKED_CAST") @ZirconDsl class IconBuilder private constructor() : BaseComponentBuilder<Icon, IconBuilder>( initialRenderer = DefaultIconRenderer() ) { var iconProperty: Property<Tile> = Tile.empty().toProperty() var iconTile: Tile get() = iconProperty.value set(value) { iconProperty.value = value } fun withIcon(icon: Tile) = also { this.iconTile = icon } fun withIconProperty(iconProperty: Property<Tile>) = also { this.iconProperty = iconProperty } override fun build(): Icon { return DefaultIcon( componentMetadata = createMetadata(), renderingStrategy = createRenderingStrategy(), iconProperty = iconProperty ).attachListeners() } override fun createCopy() = newBuilder().withProps(props.copy()).withIcon(iconTile) companion object { @JvmStatic fun newBuilder() = IconBuilder() } }
apache-2.0
ed31ca17bdfd367d3f6a1a872004b8be
30.265306
87
0.71671
4.44058
false
false
false
false
Hexworks/zircon
zircon.core/src/commonMain/kotlin/org/hexworks/zircon/internal/util/TextBuffer.kt
1
2574
package org.hexworks.zircon.internal.util import org.hexworks.zircon.api.data.Position import org.hexworks.zircon.api.data.Size import org.hexworks.zircon.platform.util.SystemUtils import kotlin.math.min @Suppress("unused") class TextBuffer(text: String) { private val currentText = mutableListOf<StringBuilder>() init { setText(text) } fun getBoundingBoxSize() = Size.create(currentText.map { it.length }.maxOrNull() ?: 0, currentText.size) fun getText() = currentText.joinToString(SystemUtils.getLineSeparator()) { it.toString() } fun getSize() = currentText.size fun getRowOrNull(row: Int): StringBuilder? = if (row < currentText.size && row >= 0) { currentText[row] } else { null } fun getCharAtOrNull(position: Position): Char? = if (position.y >= currentText.size || currentText[position.y].length <= position.x) { null } else { currentText[position.y][position.x] } fun getTextSection(position: Position, size: Size): List<String> { val fromRow = position.y val toRow = min(currentText.size - 1, fromRow + size.height - 1) val fromCol = position.x return if (requestedRowsHaveNoIntersectionWithBuffer(fromRow, toRow)) { listOf() } else { var rowIdx = fromRow val list = mutableListOf<String>() do { val row = currentText[rowIdx] val toCol = min(fromCol + size.width, row.length) list.add( if (requestedColsHaveNoIntersectionWithBuffer(fromCol, toCol, row)) { "" } else { row.substring(fromCol, toCol) } ) rowIdx++ } while (rowIdx <= toRow) list } } fun setText(text: String) { currentText.clear() currentText.addAll(text.split(SystemUtils.getLineSeparator()).map { StringBuilder(it) }) } fun deleteRowAt(rowIdx: Int) { currentText.removeAt(rowIdx) } fun addNewRowAt(rowIdx: Int) { currentText.add(rowIdx, StringBuilder()) } private fun requestedRowsHaveNoIntersectionWithBuffer(fromRow: Int, toRow: Int) = toRow < fromRow || fromRow >= currentText.size private fun requestedColsHaveNoIntersectionWithBuffer(fromCol: Int, toCol: Int, row: StringBuilder) = toCol <= fromCol || fromCol >= row.length }
apache-2.0
2ad7e27dfbeb59022278da80391615a2
30.012048
108
0.589355
4.247525
false
false
false
false
hpost/kommon
app/src/main/java/cc/femto/kommon/ui/recyclerview/DividerItemDecoration.kt
1
3376
package cc.femto.kommon.ui.recyclerview import android.content.Context import android.graphics.Canvas import android.graphics.Rect import android.graphics.drawable.Drawable import android.support.v4.view.ViewCompat import android.support.v7.widget.LinearLayoutManager import android.support.v7.widget.RecyclerView import android.view.View class DividerItemDecoration(context: Context, orientation: Int, paddingStart: Float, private val rtl: Boolean) : RecyclerView.ItemDecoration() { companion object { private val ATTRS = intArrayOf(android.R.attr.listDivider) val HORIZONTAL_LIST = LinearLayoutManager.HORIZONTAL val VERTICAL_LIST = LinearLayoutManager.VERTICAL } private val divider: Drawable private var orientation: Int = 0 private var paddingStart: Float = 0.toFloat() init { val a = context.obtainStyledAttributes(ATTRS) divider = a.getDrawable(0) a.recycle() setOrientation(orientation) setPaddingStart(paddingStart) } fun setOrientation(orientation: Int) { if (orientation != HORIZONTAL_LIST && orientation != VERTICAL_LIST) { throw IllegalArgumentException("invalid orientation") } this.orientation = orientation } fun setPaddingStart(paddingStart: Float) { if (paddingStart < 0) { throw IllegalArgumentException("paddingStart < 0") } this.paddingStart = paddingStart } override fun onDraw(c: Canvas, parent: RecyclerView, state: RecyclerView.State?) { if (orientation == VERTICAL_LIST) { drawVertical(c, parent) } else { drawHorizontal(c, parent) } } fun drawVertical(c: Canvas, parent: RecyclerView) { val left = (parent.paddingLeft + if (rtl) 0 else paddingStart.toInt()).toInt() val right = (parent.width - parent.paddingRight + if (rtl) paddingStart.toInt() else 0).toInt() val childCount = parent.childCount for (i in 0 until childCount) { val child = parent.getChildAt(i) val params = child.layoutParams as RecyclerView.LayoutParams val top = child.bottom + params.bottomMargin + Math.round(ViewCompat.getTranslationY(child)) val bottom = top + divider.intrinsicHeight divider.setBounds(left, top, right, bottom) divider.draw(c) } } fun drawHorizontal(c: Canvas, parent: RecyclerView) { val top = parent.paddingTop val bottom = parent.height - parent.paddingBottom val childCount = parent.childCount for (i in 0 until childCount) { val child = parent.getChildAt(i) val params = child.layoutParams as RecyclerView.LayoutParams val left = child.right + params.rightMargin + Math.round(ViewCompat.getTranslationX(child)) val right = left + divider.intrinsicHeight divider.setBounds(left, top, right, bottom) divider.draw(c) } } override fun getItemOffsets(outRect: Rect, view: View, parent: RecyclerView, state: RecyclerView.State?) { if (orientation == VERTICAL_LIST) { outRect.set(0, 0, 0, divider.intrinsicHeight) } else { outRect.set(0, 0, divider.intrinsicWidth, 0) } } }
apache-2.0
530b8900f93974ae1f3444c8314bad20
35.301075
144
0.648697
4.775106
false
false
false
false
DiUS/pact-jvm
core/model/src/main/kotlin/au/com/dius/pact/core/model/generators/Generator.kt
1
14490
package au.com.dius.pact.core.model.generators import com.github.michaelbull.result.getOr import au.com.dius.pact.core.model.PactSpecVersion import au.com.dius.pact.core.support.Json import au.com.dius.pact.core.support.expressions.DataType import au.com.dius.pact.core.support.expressions.ExpressionParser.containsExpressions import au.com.dius.pact.core.support.expressions.ExpressionParser.parseExpression import au.com.dius.pact.core.support.expressions.MapValueResolver import au.com.dius.pact.core.support.json.JsonValue import com.mifmif.common.regex.Generex import mu.KotlinLogging import org.apache.commons.lang3.RandomStringUtils import org.apache.commons.lang3.RandomUtils import java.math.BigDecimal import java.time.OffsetDateTime import java.time.ZoneId import java.time.format.DateTimeFormatter import java.util.UUID import java.util.concurrent.ThreadLocalRandom import kotlin.reflect.full.companionObject import kotlin.reflect.full.companionObjectInstance import kotlin.reflect.full.declaredMemberFunctions private val logger = KotlinLogging.logger {} const val DEFAULT_GENERATOR_PACKAGE = "au.com.dius.pact.core.model.generators" /** * Looks up the generator class in the configured generator packages. By default it will look for generators in * au.com.dius.pact.model.generators package, but this can be extended by adding a comma separated list to the * pact.generators.packages system property. The generator class name needs to be <Type>Generator. */ fun lookupGenerator(generatorJson: JsonValue.Object): Generator? { var generator: Generator? = null try { val generatorClass = findGeneratorClass(Json.toString(generatorJson["type"])).kotlin val fromJson = when { generatorClass.companionObject != null -> generatorClass.companionObjectInstance to generatorClass.companionObject?.declaredMemberFunctions?.find { it.name == "fromJson" } generatorClass.objectInstance != null -> generatorClass.objectInstance to generatorClass.declaredMemberFunctions.find { it.name == "fromJson" } else -> null } if (fromJson?.second != null) { generator = fromJson.second!!.call(fromJson.first, generatorJson) as Generator? } else { logger.warn { "Could not invoke generator class 'fromJson' for generator config '$generatorJson'" } } } catch (e: ClassNotFoundException) { logger.warn(e) { "Could not find generator class for generator config '$generatorJson'" } } return generator } fun findGeneratorClass(generatorType: String): Class<*> { val generatorPackages = System.getProperty("pact.generators.packages") return when { generatorPackages.isNullOrBlank() -> Class.forName("$DEFAULT_GENERATOR_PACKAGE.${generatorType}Generator") else -> { val packages = generatorPackages.split(",").map { it.trim() } + DEFAULT_GENERATOR_PACKAGE var generatorClass: Class<*>? = null packages.find { try { generatorClass = Class.forName("$it.${generatorType}Generator") true } catch (_: ClassNotFoundException) { false } } generatorClass ?: throw ClassNotFoundException("No generator found for type '$generatorType'") } } } /** * Interface that all Generators need to implement */ interface Generator { fun generate(context: Map<String, Any?>): Any? fun toMap(pactSpecVersion: PactSpecVersion): Map<String, Any> fun correspondsToMode(mode: GeneratorTestMode): Boolean = true } /** * Generates a random integer between a min and max value */ data class RandomIntGenerator(val min: Int, val max: Int) : Generator { override fun toMap(pactSpecVersion: PactSpecVersion): Map<String, Any> { return mapOf("type" to "RandomInt", "min" to min, "max" to max) } override fun generate(context: Map<String, Any?>): Any { return RandomUtils.nextInt(min, max) } companion object { fun fromJson(json: JsonValue.Object): RandomIntGenerator { val min = if (json["min"].isNumber) { json["min"].asNumber().toInt() } else { logger.warn { "Ignoring invalid value for min: '${json["min"]}'" } 0 } val max = if (json["max"].isNumber) { json["max"].asNumber().toInt() } else { logger.warn { "Ignoring invalid value for max: '${json["max"]}'" } Int.MAX_VALUE } return RandomIntGenerator(min, max) } } } /** * Generates a random big decimal value with the provided number of digits */ data class RandomDecimalGenerator(val digits: Int) : Generator { override fun toMap(pactSpecVersion: PactSpecVersion): Map<String, Any> { return mapOf("type" to "RandomDecimal", "digits" to digits) } override fun generate(context: Map<String, Any?>): Any { return when { digits < 1 -> throw UnsupportedOperationException("RandomDecimalGenerator digits must be > 0, got $digits") digits == 1 -> BigDecimal(RandomUtils.nextInt(0, 9)) digits == 2 -> BigDecimal("${RandomUtils.nextInt(0, 9)}.${RandomUtils.nextInt(0, 9)}") else -> { val sampleDigits = RandomStringUtils.randomNumeric(digits + 1) val pos = RandomUtils.nextInt(1, digits - 1) val selectedDigits = if (sampleDigits.startsWith("00")) { RandomUtils.nextInt(1, 9).toString() + sampleDigits.substring(1, digits) } else if (pos != 1 && sampleDigits.startsWith('0')) { sampleDigits.substring(1) } else { sampleDigits.substring(0, digits) } val generated = "${selectedDigits.substring(0, pos)}.${selectedDigits.substring(pos)}" logger.trace { "RandomDecimalGenerator: sampleDigits=[$sampleDigits], pos=$pos, selectedDigits=[$selectedDigits], " + "generated=[$generated]" } BigDecimal(generated) } } } companion object { fun fromJson(json: JsonValue.Object): RandomDecimalGenerator { val digits = if (json["digits"].isNumber) { json["digits"].asNumber().toInt() } else { logger.warn { "Ignoring invalid value for digits: '${json["digits"]}'" } 10 } return RandomDecimalGenerator(digits) } } } /** * Generates a random hexadecimal value of the given number of digits */ data class RandomHexadecimalGenerator(val digits: Int) : Generator { override fun toMap(pactSpecVersion: PactSpecVersion): Map<String, Any> { return mapOf("type" to "RandomHexadecimal", "digits" to digits) } override fun generate(context: Map<String, Any?>): Any = RandomStringUtils.random(digits, "0123456789abcdef") companion object { fun fromJson(json: JsonValue.Object): RandomHexadecimalGenerator { val digits = if (json["digits"].isNumber) { json["digits"].asNumber().toInt() } else { logger.warn { "Ignoring invalid value for digits: '${json["digits"]}'" } 10 } return RandomHexadecimalGenerator(digits) } } } /** * Generates a random alphanumeric string of the provided length */ data class RandomStringGenerator(val size: Int = 20) : Generator { override fun toMap(pactSpecVersion: PactSpecVersion): Map<String, Any> { return mapOf("type" to "RandomString", "size" to size) } override fun generate(context: Map<String, Any?>): Any { return RandomStringUtils.randomAlphanumeric(size) } companion object { fun fromJson(json: JsonValue.Object): RandomStringGenerator { val size = if (json["size"].isNumber) { json["size"].asNumber().toInt() } else { logger.warn { "Ignoring invalid value for size: '${json["size"]}'" } 10 } return RandomStringGenerator(size) } } } /** * Generates a random string from the provided regular expression */ data class RegexGenerator(val regex: String) : Generator { override fun toMap(pactSpecVersion: PactSpecVersion): Map<String, Any> { return mapOf("type" to "Regex", "regex" to regex) } override fun generate(context: Map<String, Any?>): Any = Generex(regex).random() companion object { fun fromJson(json: JsonValue.Object) = RegexGenerator(Json.toString(json["regex"])) } } /** * Generates a random UUID */ object UuidGenerator : Generator { override fun toMap(pactSpecVersion: PactSpecVersion): Map<String, Any> { return mapOf("type" to "Uuid") } override fun generate(context: Map<String, Any?>): Any { return UUID.randomUUID().toString() } @Suppress("UNUSED_PARAMETER") fun fromJson(json: JsonValue.Object): UuidGenerator { return UuidGenerator } } /** * Generates a date value for the provided format. If no format is provided, ISO date format is used. If an expression * is given, it will be evaluated to generate the date, otherwise 'today' will be used */ data class DateGenerator @JvmOverloads constructor( val format: String? = null, val expression: String? = null ) : Generator { override fun toMap(pactSpecVersion: PactSpecVersion): Map<String, Any> { val map = mutableMapOf("type" to "Date") if (!format.isNullOrEmpty()) { map["format"] = this.format } if (!expression.isNullOrEmpty()) { map["expression"] = this.expression } return map } override fun generate(context: Map<String, Any?>): Any { val base = if (context.containsKey("baseDate")) context["baseDate"] as OffsetDateTime else OffsetDateTime.now() val date = DateExpression.executeDateExpression(base, expression).getOr { base } return if (!format.isNullOrEmpty()) { date.format(DateTimeFormatter.ofPattern(format)) } else { date.toString() } } companion object { fun fromJson(json: JsonValue.Object): DateGenerator { val format = if (json["format"].isString) json["format"].asString() else null val expression = if (json["expression"].isString) json["expression"].asString() else null return DateGenerator(format, expression) } } } /** * Generates a time value for the provided format. If no format is provided, ISO time format is used. If an expression * is given, it will be evaluated to generate the time, otherwise 'now' will be used */ data class TimeGenerator @JvmOverloads constructor( val format: String? = null, val expression: String? = null ) : Generator { override fun toMap(pactSpecVersion: PactSpecVersion): Map<String, Any> { val map = mutableMapOf("type" to "Time") if (!format.isNullOrEmpty()) { map["format"] = this.format } if (!expression.isNullOrEmpty()) { map["expression"] = this.expression } return map } override fun generate(context: Map<String, Any?>): Any { val base = if (context.containsKey("baseTime")) context["baseTime"] as OffsetDateTime else OffsetDateTime.now() val time = TimeExpression.executeTimeExpression(base, expression).getOr { base } return if (!format.isNullOrEmpty()) { time.format(DateTimeFormatter.ofPattern(format)) } else { time.toString() } } companion object { fun fromJson(json: JsonValue.Object): TimeGenerator { val format = if (json["format"].isString) json["format"].asString() else null val expression = if (json["expression"].isString) json["expression"].asString() else null return TimeGenerator(format, expression) } } } /** * Generates a datetime value for the provided format. If no format is provided, ISO format is used. If an expression * is given, it will be evaluated to generate the datetime, otherwise 'now' will be used */ data class DateTimeGenerator @JvmOverloads constructor( val format: String? = null, val expression: String? = null ) : Generator { override fun toMap(pactSpecVersion: PactSpecVersion): Map<String, Any> { val map = mutableMapOf("type" to "DateTime") if (!format.isNullOrEmpty()) { map["format"] = this.format } if (!expression.isNullOrEmpty()) { map["expression"] = this.expression } return map } override fun generate(context: Map<String, Any?>): Any { val base = if (context.containsKey("baseDateTime")) context["baseDateTime"] as OffsetDateTime else OffsetDateTime.now() val datetime = DateTimeExpression.executeExpression(base, expression).getOr { base } return if (!format.isNullOrEmpty()) { datetime.toZonedDateTime().format(DateTimeFormatter.ofPattern(format).withZone(ZoneId.systemDefault())) } else { datetime.toString() } } companion object { fun fromJson(json: JsonValue.Object): DateTimeGenerator { val format = if (json["format"].isString) json["format"].asString() else null val expression = if (json["expression"].isString) json["expression"].asString() else null return DateTimeGenerator(format, expression) } } } /** * Generates a random boolean value */ @SuppressWarnings("EqualsWithHashCodeExist") object RandomBooleanGenerator : Generator { override fun toMap(pactSpecVersion: PactSpecVersion): Map<String, Any> { return mapOf("type" to "RandomBoolean") } override fun generate(context: Map<String, Any?>): Any { return ThreadLocalRandom.current().nextBoolean() } override fun equals(other: Any?) = other is RandomBooleanGenerator @Suppress("UNUSED_PARAMETER") fun fromJson(json: JsonValue.Object): RandomBooleanGenerator { return RandomBooleanGenerator } } /** * Generates a value that is looked up from the provider state context */ data class ProviderStateGenerator @JvmOverloads constructor ( val expression: String, val type: DataType = DataType.RAW ) : Generator { override fun toMap(pactSpecVersion: PactSpecVersion): Map<String, Any> { return mapOf("type" to "ProviderState", "expression" to expression, "dataType" to type.name) } override fun generate(context: Map<String, Any?>): Any? { return when (val providerState = context["providerState"]) { is Map<*, *> -> { val map = providerState as Map<String, Any> if (containsExpressions(expression)) { parseExpression(expression, type, MapValueResolver(map)) } else { map[expression] } } else -> null } } override fun correspondsToMode(mode: GeneratorTestMode) = mode == GeneratorTestMode.Provider companion object { fun fromJson(json: JsonValue.Object) = ProviderStateGenerator( Json.toString(json["expression"]), if (json.has("dataType")) DataType.valueOf(Json.toString(json["dataType"])) else DataType.RAW ) } }
apache-2.0
3b9d66efeeeb95cd5cbdf35ba97293b9
33.665072
118
0.688406
4.3125
false
false
false
false
DiUS/pact-jvm
core/model/src/main/kotlin/au/com/dius/pact/core/model/FeatureToggles.kt
1
1134
package au.com.dius.pact.core.model enum class Feature(val featureKey: String) { UseMatchValuesMatcher("pact.feature.matchers.useMatchValuesMatcher") } object FeatureToggles { private var features = mutableMapOf<String, Any>() init { reset() } @JvmStatic fun toggleFeature(name: String, value: Boolean) { features[name] = value } @JvmStatic fun toggleFeature(feature: Feature, value: Boolean) = toggleFeature(feature.featureKey, value) @JvmStatic fun isFeatureSet(name: String) = features[name] != null && features[name] is Boolean && features[name] as Boolean @JvmStatic fun isFeatureSet(feature: Feature) = isFeatureSet(feature.featureKey) @JvmStatic fun reset() { features = default() } @JvmStatic fun default(): MutableMap<String, Any> = mutableMapOf(Feature.UseMatchValuesMatcher.featureKey to false) @JvmStatic fun features() = features.toMap() @JvmStatic fun updatedToggles(): Map<String, Any> { val defaultFeatures = default() return features.filter { !defaultFeatures.containsKey(it.key) || defaultFeatures[it.key] != it.value } } }
apache-2.0
4283a0f9cbfa85aaa3357acaf9b47be1
22.625
106
0.708113
3.870307
false
false
false
false
mdaniel/intellij-community
plugins/kotlin/uast/uast-kotlin-base/src/org/jetbrains/uast/kotlin/expressions/KotlinStringTemplateUPolyadicExpression.kt
3
2493
// 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.uast.kotlin import com.intellij.psi.PsiLanguageInjectionHost import org.jetbrains.annotations.ApiStatus import org.jetbrains.kotlin.psi.KtCallExpression import org.jetbrains.kotlin.psi.KtDotQualifiedExpression import org.jetbrains.kotlin.psi.KtStringTemplateExpression import org.jetbrains.kotlin.utils.addToStdlib.safeAs import org.jetbrains.uast.* import org.jetbrains.uast.expressions.UInjectionHost @ApiStatus.Internal class KotlinStringTemplateUPolyadicExpression( override val sourcePsi: KtStringTemplateExpression, givenParent: UElement? ) : KotlinAbstractUExpression(givenParent), UPolyadicExpression, KotlinUElementWithType, KotlinEvaluatableUElement, UInjectionHost { override val operands: List<UExpression> by lz { sourcePsi.entries.map { baseResolveProviderService.baseKotlinConverter.convertStringTemplateEntry( it, this, DEFAULT_EXPRESSION_TYPES_LIST )!! }.takeIf { it.isNotEmpty() } ?: listOf(KotlinStringULiteralExpression(sourcePsi, this, "")) } override val operator = UastBinaryOperator.PLUS override val psiLanguageInjectionHost: PsiLanguageInjectionHost get() = sourcePsi override val isString: Boolean get() = true override fun asRenderString(): String = if (operands.isEmpty()) "\"\"" else super<UPolyadicExpression>.asRenderString() override fun asLogString(): String = if (operands.isEmpty()) "UPolyadicExpression (value = \"\")" else super.asLogString() override fun getStringRoomExpression(): UExpression { val uParent = this.uastParent as? UExpression ?: return this val dotQualifiedExpression = uParent.sourcePsi as? KtDotQualifiedExpression if (dotQualifiedExpression != null) { val callExpression = dotQualifiedExpression.selectorExpression.safeAs<KtCallExpression>() ?: return this val resolvedFunctionName = baseResolveProviderService.resolvedFunctionName(callExpression) if (resolvedFunctionName == "trimIndent" || resolvedFunctionName == "trimMargin") return uParent } if (uParent is UPolyadicExpression && uParent.operator == UastBinaryOperator.PLUS) return uParent return super.getStringRoomExpression() } }
apache-2.0
dba987612b57fa0710ad853eff44b0d4
46.037736
158
0.736863
5.678815
false
false
false
false
mdaniel/intellij-community
plugins/kotlin/fir/src/org/jetbrains/kotlin/idea/completion/lookups/TailTextProvider.kt
1
2600
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.completion.lookups import org.jetbrains.kotlin.analysis.api.KtAnalysisSession import org.jetbrains.kotlin.analysis.api.symbols.KtCallableSymbol import org.jetbrains.kotlin.analysis.api.symbols.KtClassLikeSymbol import org.jetbrains.kotlin.analysis.api.symbols.KtFunctionSymbol import org.jetbrains.kotlin.analysis.api.types.KtFunctionalType import org.jetbrains.kotlin.analysis.api.types.KtSubstitutor import org.jetbrains.kotlin.idea.completion.KotlinIdeaCompletionBundle import org.jetbrains.kotlin.idea.completion.lookups.CompletionShortNamesRenderer.renderFunctionParameters import org.jetbrains.kotlin.name.FqName internal object TailTextProvider { fun KtAnalysisSession.getTailText(symbol: KtCallableSymbol, substitutor: KtSubstitutor): String = buildString { if (symbol is KtFunctionSymbol) { if (insertLambdaBraces(symbol)) { append(" {...}") } else { append(renderFunctionParameters(symbol, substitutor)) } } symbol.callableIdIfNonLocal ?.takeIf { it.className == null } ?.let { callableId -> append(" (") append(callableId.packageName.asStringForTailText()) append(")") } symbol.receiverType?.let { receiverType -> val renderedType = receiverType.render(CompletionShortNamesRenderer.TYPE_RENDERING_OPTIONS) append(KotlinIdeaCompletionBundle.message("presentation.tail.for.0", renderedType)) } } fun KtAnalysisSession.getTailText(symbol: KtClassLikeSymbol): String = buildString { symbol.classIdIfNonLocal?.let { classId -> append(" (") append(classId.asSingleFqName().parent().asStringForTailText()) append(")") } } private fun FqName.asStringForTailText(): String = if (isRoot) "<root>" else asString() fun KtAnalysisSession.insertLambdaBraces(symbol: KtFunctionSymbol): Boolean { val singleParam = symbol.valueParameters.singleOrNull() return singleParam != null && !singleParam.hasDefaultValue && singleParam.returnType is KtFunctionalType } fun KtAnalysisSession.insertLambdaBraces(symbol: KtFunctionalType): Boolean { val singleParam = symbol.parameterTypes.singleOrNull() return singleParam != null && singleParam is KtFunctionalType } }
apache-2.0
573d2139fd7258ec3230311b50445840
42.35
158
0.704615
5.220884
false
false
false
false
hermantai/samples
kotlin/kotlin-and-android-development-featuring-jetpack/chapter-9/code-to-copy/standings/StandingsAdapter.kt
1
4562
package dev.mfazio.abl.standings import android.view.LayoutInflater import android.view.ViewGroup import androidx.recyclerview.widget.DiffUtil import androidx.recyclerview.widget.ListAdapter import androidx.recyclerview.widget.RecyclerView import dev.mfazio.abl.databinding.StandingsHeaderBinding import dev.mfazio.abl.databinding.StandingsTeamItemBinding import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import java.lang.ClassCastException class StandingsAdapter : ListAdapter<StandingsListItem, RecyclerView.ViewHolder>(StandingsDiffCallback()) { fun addHeadersAndBuildStandings(uiTeamStandings: List<UITeamStanding>) = CoroutineScope( Dispatchers.Default ).launch { val items = uiTeamStandings .sortedWith(compareBy({ it.teamStanding.division }, { -it.teamStanding.wins })) .groupBy { it.teamStanding.division } .map { (division, teams) -> listOf(StandingsListItem.Header(division)) + teams.map { team -> StandingsListItem.TeamItem(team) } }.flatten() withContext(Dispatchers.Main) { submitList(items) } } override fun getItemViewType(position: Int) = when (getItem(position)) { is StandingsListItem.Header -> STANDINGS_ITEM_VIEW_TYPE_HEADER is StandingsListItem.TeamItem -> STANDINGS_ITEM_VIEW_TYPE_TEAM } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) = when (viewType) { STANDINGS_ITEM_VIEW_TYPE_HEADER -> StandingsListHeaderViewHolder.from(parent) STANDINGS_ITEM_VIEW_TYPE_TEAM -> StandingsListTeamViewHolder.from(parent) else -> throw ClassCastException("Unknown view type [$viewType]") } override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) { when (holder) { is StandingsListTeamViewHolder -> { (getItem(position) as? StandingsListItem.TeamItem)?.let { teamItem -> holder.bind(teamItem) } } is StandingsListHeaderViewHolder -> { (getItem(position) as? StandingsListItem.Header)?.let { teamItem -> holder.bind(teamItem) } } } } class StandingsListTeamViewHolder(private val binding: StandingsTeamItemBinding) : RecyclerView.ViewHolder(binding.root) { fun bind(standingsTeamItem: StandingsListItem.TeamItem) { binding.uiTeamStanding = standingsTeamItem.uiTeamStanding //TODO: Uncomment this code when you're ready. /*binding.clickListener = View.OnClickListener { view -> val action = NavGraphDirections.actionGoToTeam( standingsTeamItem.uiTeamStanding.teamId, standingsTeamItem.uiTeamStanding.teamName ) view.findNavController().navigate(action) }*/ } companion object { fun from(parent: ViewGroup): RecyclerView.ViewHolder { val inflater = LayoutInflater.from(parent.context) val binding = StandingsTeamItemBinding.inflate(inflater, parent, false) return StandingsListTeamViewHolder(binding) } } } class StandingsListHeaderViewHolder(private val binding: StandingsHeaderBinding) : RecyclerView.ViewHolder(binding.root) { fun bind(standingsHeaderItem: StandingsListItem.Header) { binding.divisionName = standingsHeaderItem.division.name } companion object { fun from(parent: ViewGroup): RecyclerView.ViewHolder { val inflater = LayoutInflater.from(parent.context) val binding = StandingsHeaderBinding.inflate(inflater, parent, false) return StandingsListHeaderViewHolder(binding) } } } companion object { private const val STANDINGS_ITEM_VIEW_TYPE_HEADER = 0 private const val STANDINGS_ITEM_VIEW_TYPE_TEAM = 1 } } class StandingsDiffCallback : DiffUtil.ItemCallback<StandingsListItem>() { override fun areItemsTheSame(oldItem: StandingsListItem, newItem: StandingsListItem) = oldItem == newItem override fun areContentsTheSame( oldItem: StandingsListItem, newItem: StandingsListItem ) = oldItem.id == newItem.id }
apache-2.0
4f4a0a7980529ee16495e2ce3e5d0aff
38.327586
92
0.657168
4.942579
false
false
false
false
TheCoinTosser/Kotlin-Koans---Solutions
src/v_builders/n40BuildersHowItWorks.kt
2
1988
package v_builders.builders import util.questions.Answer import util.questions.Answer.* fun todoTask40(): Nothing = TODO( """ Task 40. Look at the questions below and give your answers: change 'insertAnswerHere()' in task40's map to your choice (a, b or c). All the constants are imported via 'util.questions.Answer.*', so they can be accessed by name. """ ) fun insertAnswerHere(): Nothing = todoTask40() fun task40() = linkedMapOf<Int, Answer>( /* 1. In the Kotlin code tr { td { text("Product") } td { text("Popularity") } } 'td' is: a. special built-in syntactic construct b. function declaration c. function invocation */ 1 to Answer.c, /* 2. In the Kotlin code tr (color = "yellow") { td { text("Product") } td { text("Popularity") } } 'color' is: a. new variable declaration b. argument name c. argument value */ 2 to Answer.b, /* 3. The block { text("Product") } from the previous question is: a. block inside built-in syntax construction 'td' b. function literal (or "lambda") c. something mysterious */ 3 to Answer.b, /* 4. For the code tr (color = "yellow") { this.td { text("Product") } td { text("Popularity") } } which of the following is true: a. this code doesn't compile b. 'this' refers to an instance of an outer class c. 'this' refers to a receiver parameter TR of the function literal: tr (color = "yellow") { [email protected] { text("Product") } } */ 4 to Answer.c )
mit
a253a6168db48cf4468a2edb59b3967e
21.590909
102
0.485915
4.447427
false
false
false
false
thaapasa/jalkametri-android
app/src/main/java/fi/tuska/jalkametri/gui/DrinkSizeSelector.kt
1
8987
package fi.tuska.jalkametri.gui import android.view.View import android.view.View.OnClickListener import android.widget.AdapterView import android.widget.AdapterView.OnItemSelectedListener import android.widget.CheckBox import android.widget.EditText import android.widget.Spinner import fi.tuska.jalkametri.Common import fi.tuska.jalkametri.R import fi.tuska.jalkametri.activity.JalkametriActivity import fi.tuska.jalkametri.dao.DrinkSizes import fi.tuska.jalkametri.data.DrinkSize import fi.tuska.jalkametri.db.DBAdapter import fi.tuska.jalkametri.db.DrinkLibraryDB import fi.tuska.jalkametri.util.Converter import fi.tuska.jalkametri.util.LogUtil import fi.tuska.jalkametri.util.NumberUtil import java.util.Locale class DrinkSizeSelector( private val parent: JalkametriActivity, db: DBAdapter, private val selectorShown: Boolean, private val sizeIconEditorShown: Boolean, initialSelection: DrinkSize?) { private val locale: Locale = parent.prefs.locale private val sizeLib: DrinkSizes = DrinkLibraryDB(db).drinkSizes private val initial = initialSelection ?: sizeLib.defaultSize private var sizeEdit = parent.findViewById(R.id.size_edit) as EditText private var sizeNameEdit = parent.findViewById(R.id.size_name_edit) as EditText private var sizeIcon: IconView? = null private var spinnerSelection: DrinkSize? = null private var selectedDrinkSize: DrinkSize? = null /** * Selection spinner for pre-existing size entries. This can be missing * from the edit form and therefore be null; this class is prepared to * handle that. In this case the pre-selection functionality is not * enabled. */ private var sizeSelectionSpinner: Spinner? = parent.findViewById(R.id.size_selector) as Spinner? /** * Adapter for the spinner; this will be null if the spinner is null, see * the comments for the spinner. */ private var sizeSelectionAdapter: TextIconSpinnerAdapter<DrinkSize>? = null /** * A CheckBox for checking whether a custom size can be entered. This * class is prepared for a null value for this control; i.e., it can be * missing from the edit form. In this case, custom editing is always * enabled. */ private var modifySizeCheckbox: CheckBox? = parent.findViewById(R.id.modify_size) as CheckBox? private val modifyCheckBoxSelectListener = OnClickListener { modifySizeCheckbox?.isChecked = true } init { if (!selectorShown) { // Hide the entire size selector LogUtil.e(TAG, "Hiding size selector -- TODO: REMOVE THIS!") //View selectorArea = parent.findViewById(R.id.size_selection_area); //AssertionUtils.INSTANCE.expect(selectorArea != null); //selectorArea.setVisibility(View.GONE); } else { if (sizeIconEditorShown) { // Show the size icon editor // View sizeArea = parent.findViewById(R.id.size_icon_area); // sizeArea.setVisibility(View.VISIBLE); val sIcon = parent.findViewById(R.id.size_icon) as IconView? sizeIcon = sIcon sIcon?.setOnClickListener { // Select an icon if (isCustomSizeEditingEnabled) { val dialog = IconPickerDialog.createDialog { icon -> // Update icon LogUtil.d(TAG, "Selecting icon %s", icon.icon) sIcon.icon = icon } JalkametriActivity.showCustomDialog(parent, dialog) } } } } // Modify size modifySizeCheckbox?.isChecked = false updateSizeEditorEnabling() if (selectorShown) { modifySizeCheckbox?.setOnCheckedChangeListener { _, _ -> updateSizeEditorEnabling() } } // Size selection spinner if (sizeSelectionSpinner != null) { populateSizeSelectionSpinner(initial) } // Set size name/size edit clicking to toggle modification // checkbox sizeNameEdit.setOnClickListener(modifyCheckBoxSelectListener) sizeEdit.setOnClickListener(modifyCheckBoxSelectListener) setDrinkSize(initial, true) if (selectorShown) { sizeSelectionSpinner?.onItemSelectedListener = object : OnItemSelectedListener { override fun onItemSelected(adapter: AdapterView<*>, view: View?, position: Int, id: Long) { sizeSelectionAdapter?.getItem(position)?.let { size -> spinnerSelection.let { if (it == null || it != size) { LogUtil.d(TAG, "DrinkSize item %s selected", size) spinnerSelection = size setSizeSelected(size) } } } } override fun onNothingSelected(adapter: AdapterView<*>) {} } } } // Custom size selected // Create a new size based on the entered data // Return the selected drink val drinkSize: DrinkSize? get() { return if (isCustomSizeEditingEnabled) { val name = sizeNameEdit.text.toString() val volume = NumberUtil.readDouble(sizeEdit.text.toString(), locale) DrinkSize(name, volume, currentlySelectedIcon) } else { selectedDrinkSize } } // If there is no modification button on the form, then it is assumed // that the size editing is enabled private val isCustomSizeEditingEnabled: Boolean get() = modifySizeCheckbox?.isChecked ?: true private val currentlySelectedIcon: String get() = if (sizeIconEditorShown) sizeIcon?.icon?.icon ?: Common.DEFAULT_ICON_NAME else Common.DEFAULT_ICON_NAME /** * Sets the given size. */ fun setDrinkSize(size: DrinkSize, addIfMissing: Boolean) { this.selectedDrinkSize = size if (sizeSelectionAdapter == null) { // No size selection db, so just set the custom edit forms. populateCustomEditors(size) return } // Find the selection from the sizeSelectionAdapter val pos = sizeSelectionAdapter!!.findItem(size) if (pos != -1) { // Size was found from the size list sizeSelectionSpinner?.setSelection(pos) // Not a custom item, set the text to the text editors modifySizeCheckbox?.isChecked = false spinnerSelection = size } else { // Size was not found, so this is a custom size // Select first element from the spinner if (sizeSelectionAdapter?.itemCount ?: 0 > 0) { sizeSelectionSpinner?.setSelection(0) spinnerSelection = sizeSelectionAdapter?.getItem(0) } else { spinnerSelection = null } modifySizeCheckbox?.isChecked = true } // Update the text editors sizeNameEdit.setText(size.name) sizeEdit.setText(NumberUtil.toString(size.volume, parent.resources)) if (sizeIconEditorShown) sizeIcon?.setIcon(size.icon) } private fun populateCustomEditors(size: DrinkSize) { sizeNameEdit.setText(size.name) sizeEdit.setText(NumberUtil.toString(size.volume, parent.resources)) if (sizeIconEditorShown) sizeIcon?.setIcon(size.icon) } private fun setSizeSelected(size: DrinkSize) { selectedDrinkSize = size sizeEdit.setText(NumberUtil.toString(size.volume, parent.resources)) sizeNameEdit.setText(size.name) modifySizeCheckbox?.isChecked = false if (sizeIconEditorShown) { sizeIcon?.setIcon(size.icon) } updateSizeEditorEnabling() } private fun updateSizeEditorEnabling() { val controlsEnabled = isCustomSizeEditingEnabled sizeNameEdit.isEnabled = controlsEnabled sizeEdit.isEnabled = controlsEnabled if (sizeIconEditorShown) { sizeIcon?.isEnabled = controlsEnabled } } /** * Must only be called when the spinner is present on the edit form. */ private fun populateSizeSelectionSpinner(initialSize: DrinkSize) { val sizes = sizeLib.allSizes sizeSelectionAdapter = TextIconSpinnerAdapter(parent, sizes, Converter { it.getIconText(parent.resources) }, Converter { it.icon }) sizeSelectionSpinner?.adapter = sizeSelectionAdapter } companion object { private val TAG = "DrinkSizeSelector" } }
mit
b91509a56c4ded2126a1793da52828d2
36.136364
100
0.619673
4.727512
false
false
false
false
GunoH/intellij-community
platform/platform-impl/src/com/intellij/openapi/fileEditor/impl/HTMLFileEditor.kt
8
5648
// 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.fileEditor.impl import com.intellij.CommonBundle import com.intellij.ide.BrowserUtil import com.intellij.ide.IdeBundle import com.intellij.ide.plugins.MultiPanel import com.intellij.openapi.application.IdeUrlTrackingParametersProvider import com.intellij.openapi.application.invokeLater import com.intellij.openapi.editor.EditorBundle import com.intellij.openapi.fileEditor.FileEditor import com.intellij.openapi.fileEditor.FileEditorState import com.intellij.openapi.project.Project import com.intellij.openapi.util.ActionCallback import com.intellij.openapi.util.NlsSafe import com.intellij.openapi.util.UserDataHolderBase import com.intellij.openapi.util.registry.Registry import com.intellij.openapi.vfs.VirtualFile import com.intellij.openapi.wm.StatusBar import com.intellij.testFramework.LightVirtualFile import com.intellij.ui.components.JBLoadingPanel import com.intellij.ui.jcef.JBCefBrowserBase.ErrorPage import com.intellij.ui.jcef.JCEFHtmlPanel import com.intellij.util.Alarm import com.intellij.util.AlarmFactory import com.intellij.util.ui.UIUtil import org.cef.browser.CefBrowser import org.cef.browser.CefFrame import org.cef.handler.* import org.cef.network.CefRequest import java.awt.BorderLayout import java.beans.PropertyChangeListener import java.util.concurrent.atomic.AtomicBoolean import javax.swing.JComponent internal class HTMLFileEditor(private val project: Project, private val file: LightVirtualFile, url: String) : UserDataHolderBase(), FileEditor { private val loadingPanel = JBLoadingPanel(BorderLayout(), this) private val contentPanel = JCEFHtmlPanel(true, null, null) private val alarm = AlarmFactory.getInstance().create(Alarm.ThreadToUse.SWING_THREAD, this) private val initial = AtomicBoolean(true) private val navigating = AtomicBoolean(false) private val multiPanel = object : MultiPanel() { override fun create(key: Int): JComponent = when (key) { LOADING_KEY -> loadingPanel CONTENT_KEY -> contentPanel.component else -> throw IllegalArgumentException("Unknown key: ${key}") } override fun select(key: Int, now: Boolean): ActionCallback { val callback = super.select(key, now) if (key == CONTENT_KEY) { UIUtil.invokeLaterIfNeeded { contentPanel.component.requestFocusInWindow() } } return callback } } init { loadingPanel.setLoadingText(CommonBundle.getLoadingTreeNodeText()) contentPanel.jbCefClient.addLoadHandler(object : CefLoadHandlerAdapter() { override fun onLoadingStateChange(browser: CefBrowser, isLoading: Boolean, canGoBack: Boolean, canGoForward: Boolean) { if (initial.get()) { if (isLoading) { invokeLater { loadingPanel.startLoading() multiPanel.select(LOADING_KEY, true) } } else { alarm.cancelAllRequests() initial.set(false) invokeLater { loadingPanel.stopLoading() multiPanel.select(CONTENT_KEY, true) } } } } }, contentPanel.cefBrowser) contentPanel.jbCefClient.addRequestHandler(object : CefRequestHandlerAdapter() { override fun onBeforeBrowse(browser: CefBrowser, frame: CefFrame, request: CefRequest, userGesture: Boolean, isRedirect: Boolean): Boolean = if (userGesture) { navigating.set(true); browse(request.url); true } else false }, contentPanel.cefBrowser) contentPanel.jbCefClient.addLifeSpanHandler(object : CefLifeSpanHandlerAdapter() { override fun onBeforePopup(browser: CefBrowser, frame: CefFrame, targetUrl: String, targetFrameName: String?): Boolean { browse(targetUrl) return true } }, contentPanel.cefBrowser) contentPanel.jbCefClient.addDisplayHandler(object : CefDisplayHandlerAdapter() { override fun onStatusMessage(browser: CefBrowser, text: @NlsSafe String) = StatusBar.Info.set(text, project) }, contentPanel.cefBrowser) contentPanel.setErrorPage { errorCode, errorText, failedUrl -> if (errorCode == CefLoadHandler.ErrorCode.ERR_ABORTED && navigating.getAndSet(false)) null else ErrorPage.DEFAULT.create(errorCode, errorText, failedUrl) } multiPanel.select(CONTENT_KEY, true) if (url.isNotEmpty()) { if (file.content.isEmpty()) { file.setContent(this, EditorBundle.message("message.html.editor.timeout"), false) } alarm.addRequest({ contentPanel.loadHTML(file.content.toString()) }, Registry.intValue("html.editor.timeout", 10000)) contentPanel.loadURL(url) } else { contentPanel.loadHTML(file.content.toString()) } } private fun browse(url: String) = BrowserUtil.browse(IdeUrlTrackingParametersProvider.getInstance().augmentUrl(url)) override fun getComponent(): JComponent = multiPanel override fun getPreferredFocusedComponent(): JComponent = multiPanel override fun getName(): String = IdeBundle.message("tab.title.html.preview") override fun setState(state: FileEditorState) { } override fun isModified(): Boolean = false override fun isValid(): Boolean = true override fun addPropertyChangeListener(listener: PropertyChangeListener) { } override fun removePropertyChangeListener(listener: PropertyChangeListener) { } override fun dispose() { } override fun getFile(): VirtualFile = file private companion object { private const val LOADING_KEY = 1 private const val CONTENT_KEY = 0 } }
apache-2.0
55470e93d52f15b3828aa8e39bb31de1
39.633094
146
0.7392
4.569579
false
false
false
false
GunoH/intellij-community
plugins/kotlin/jvm/src/org/jetbrains/kotlin/idea/scratch/ScratchFileAutoRunner.kt
4
3175
// 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.scratch import com.intellij.openapi.Disposable import com.intellij.openapi.components.service import com.intellij.openapi.editor.event.DocumentEvent import com.intellij.openapi.editor.event.DocumentListener import com.intellij.openapi.fileEditor.FileDocumentManager import com.intellij.openapi.fileEditor.FileEditorManager import com.intellij.openapi.fileEditor.TextEditor import com.intellij.openapi.project.Project import com.intellij.openapi.util.Disposer import com.intellij.openapi.vfs.VirtualFile import com.intellij.util.Alarm import org.jetbrains.kotlin.idea.scratch.actions.RunScratchAction import org.jetbrains.kotlin.idea.scratch.actions.RunScratchFromHereAction import org.jetbrains.kotlin.idea.scratch.actions.ScratchCompilationSupport import org.jetbrains.kotlin.idea.scratch.ui.findScratchFileEditorWithPreview class ScratchFileAutoRunner(private val project: Project) : DocumentListener, Disposable { companion object { fun addListener(project: Project, editor: TextEditor) { if (editor.getScratchFile() != null) { editor.editor.document.addDocumentListener(getInstance(project)) Disposer.register(editor, Disposable { editor.editor.document.removeDocumentListener(getInstance(project)) }) } } private fun getInstance(project: Project): ScratchFileAutoRunner = project.service() const val AUTO_RUN_DELAY_IN_SECONDS = 2 } private val myAlarm = Alarm(Alarm.ThreadToUse.POOLED_THREAD, this) override fun documentChanged(event: DocumentEvent) { val file = FileDocumentManager.getInstance().getFile(event.document) ?: return if (project.isDisposed) return val scratchFile = getScratchFile(file, project) ?: return if (!scratchFile.options.isInteractiveMode) return if (event.newFragment.isNotBlank()) { runScratch(scratchFile) } } private fun runScratch(scratchFile: ScratchFile) { myAlarm.cancelAllRequests() if (ScratchCompilationSupport.isInProgress(scratchFile) && !scratchFile.options.isRepl) { ScratchCompilationSupport.forceStop() } myAlarm.addRequest( { scratchFile.ktScratchFile?.takeIf { it.isValid && !scratchFile.hasErrors() }?.let { if (scratchFile.options.isRepl) { RunScratchFromHereAction.doAction(scratchFile) } else { RunScratchAction.doAction(scratchFile, true) } } }, AUTO_RUN_DELAY_IN_SECONDS * 1000, true ) } private fun getScratchFile(file: VirtualFile, project: Project): ScratchFile? { val editor = FileEditorManager.getInstance(project).getSelectedEditor(file) as? TextEditor return editor?.findScratchFileEditorWithPreview()?.scratchFile } override fun dispose() { } }
apache-2.0
dd10693dbfe8afcc5bfdb171740edd9a
38.7
158
0.699213
4.892142
false
false
false
false
yole/jitwatch-intellij
src/main/java/InlineAnalyzer.kt
1
4732
package ru.yole.jitwatch import org.adoptopenjdk.jitwatch.core.JITWatchConstants.* import org.adoptopenjdk.jitwatch.journal.AbstractJournalVisitable import org.adoptopenjdk.jitwatch.journal.JournalUtil import org.adoptopenjdk.jitwatch.model.IMetaMember import org.adoptopenjdk.jitwatch.model.IParseDictionary import org.adoptopenjdk.jitwatch.model.IReadOnlyJITDataModel import org.adoptopenjdk.jitwatch.model.Tag import org.adoptopenjdk.jitwatch.treevisitor.ITreeVisitable import org.adoptopenjdk.jitwatch.util.ParseUtil class InlineFailureInfo(val callSite: IMetaMember, val bci: Int, val callee: IMetaMember, val calleeSize: Int, val calleeInvocationCount: Int?, val reason: String) class InlineCallSite(val member: IMetaMember, val bci: Int) class InlineFailureGroup(val callee: IMetaMember, val calleeSize: Int, val calleeInvocationCount: Int?, val reasons: Set<String>, val callSites: List<InlineCallSite>) class InlineAnalyzer(val model: IReadOnlyJITDataModel, val filter: (IMetaMember) -> Boolean) : ITreeVisitable { private val _failures = mutableListOf<InlineFailureInfo>() val failureGroups: List<InlineFailureGroup> by lazy { val map = _failures .filter { it.reason != "not inlineable" && it.reason != "no static binding" } .groupBy { it.callee } map.map { InlineFailureGroup(it.key, it.value.first().calleeSize, it.value.first().calleeInvocationCount, it.value.mapTo(mutableSetOf<String>()) { failure -> failure.reason }, it.value.map { failure -> InlineCallSite(failure.callSite, failure.bci) }) }.sortedByDescending { it.callSites.size } } val failures: List<InlineFailureInfo> get() = _failures override fun visit(mm: IMetaMember?) { if (mm == null || !mm.isCompiled) return JournalUtil.visitParseTagsOfLastTask(mm.journal, InlineJournalVisitor(model, mm, _failures, filter)) } override fun reset() { } private class InlineJournalVisitor(val model: IReadOnlyJITDataModel, val callSite: IMetaMember, val failures: MutableList<InlineFailureInfo>, val filter: (IMetaMember) -> Boolean) : AbstractJournalVisitable() { override fun visitTag(toVisit: Tag, parseDictionary: IParseDictionary) { processParseTag(toVisit, parseDictionary) } private fun processParseTag(toVisit: Tag, parseDictionary: IParseDictionary, bci: Int? = null) { var methodID: String? = null var currentBCI : Int = 0 for (child in toVisit.children) { val tagName = child.name val tagAttrs = child.attributes when (tagName) { TAG_METHOD -> methodID = tagAttrs[ATTR_ID] TAG_BC -> { val newBCI = tagAttrs[ATTR_BCI] if (newBCI != null) { currentBCI = newBCI.toInt() } } TAG_CALL -> methodID = tagAttrs[ATTR_METHOD] TAG_INLINE_FAIL -> { val reason = tagAttrs[ATTR_REASON] val method = parseDictionary.getMethod(methodID) val metaMember = ParseUtil.lookupMember(methodID, parseDictionary, model) if (metaMember != null && filter(metaMember)) { failures.add(InlineFailureInfo(callSite, bci ?: currentBCI, metaMember, method?.attributes?.get(ATTR_BYTES)?.toInt() ?: -1, method?.attributes?.get(ATTR_IICOUNT)?.toInt(), reason?.replace("&lt;", "<")?.replace("&gt;", ">") ?: "Unknown")) } methodID = null } TAG_PARSE -> { processParseTag(child, parseDictionary, bci ?: currentBCI) } TAG_PHASE -> { val phaseName = tagAttrs[ATTR_NAME] if (S_PARSE_HIR == phaseName) { visitTag(child, parseDictionary) } } else -> handleOther(child) } } } } }
apache-2.0
be5843a7ac6168b1cf42dc3534fa722f
40.508772
111
0.53973
4.863309
false
false
false
false
OnyxDevTools/onyx-database-parent
onyx-remote-driver/src/main/kotlin/com/onyx/network/SSLSocketChannel.kt
1
8245
package com.onyx.network import com.onyx.extension.common.delay import javax.net.ssl.SSLEngineResult import java.io.IOException import java.nio.ByteBuffer import java.nio.ByteOrder import java.nio.channels.ByteChannel import javax.net.ssl.SSLEngineResult.HandshakeStatus import javax.net.ssl.SSLEngine import java.nio.channels.SocketChannel import java.util.concurrent.TimeUnit import javax.net.ssl.SSLContext /** * This class wraps a socket channel and applies a ssl engine to wrap the transport data using SSL * * @since 2.0.0 Refactored so that the SSL logic is out of the networking classes */ class SSLSocketChannel(private val channel: SocketChannel, sslContext: SSLContext, useClientMode:Boolean = true) : ByteChannel { private var sslEngine: SSLEngine? = null private var cipherOut: ByteBuffer? = null private var cipherIn: ByteBuffer? = null private var plainIn: ByteBuffer? = null private var plainOut: ByteBuffer? = null init { sslEngine = sslContext.createSSLEngine() sslEngine!!.useClientMode = useClientMode createBuffers() doHandshake() } /** * Override is open. Just determines if the channel is open */ override fun isOpen(): Boolean = channel.isOpen /** * Perform handshake. I recommend looking up how ssl engine wrapping and unwrapping / handshake works cause, its a mess. * Security through obfuscation!! * */ private fun doHandshake() { sslEngine!!.beginHandshake() var iteration = 0 var handshakeStatus = sslEngine!!.handshakeStatus while (handshakeStatus != HandshakeStatus.FINISHED && handshakeStatus != HandshakeStatus.NOT_HANDSHAKING) { when (handshakeStatus) { SSLEngineResult.HandshakeStatus.NEED_TASK -> handshakeStatus = runDelegatedTasks() SSLEngineResult.HandshakeStatus.NEED_UNWRAP -> { handshakeStatus = unwrap(null) plainIn!!.clear() } SSLEngineResult.HandshakeStatus.NEED_WRAP -> handshakeStatus = wrap(plainOut) else -> { } } delay(2, TimeUnit.MILLISECONDS) iteration++ if(iteration > MAX_HANDSHAKE_ITERATIONS) { this.close() break } } plainIn!!.clear() plainOut!!.clear() } /** * Run handshake tasks */ private fun runDelegatedTasks(): HandshakeStatus { var runnable: Runnable? do { runnable = sslEngine!!.delegatedTask runnable?.run() } while (runnable != null) return sslEngine!!.handshakeStatus } /** * Unwrap data from a channel and put into buffer */ private fun unwrap(buffer: ByteBuffer?): HandshakeStatus { var handshakeStatus = sslEngine!!.handshakeStatus if (channel.read(cipherIn) < 0) { throw IOException("Failed to establish SSL socket connection.") } cipherIn!!.flip() var status: SSLEngineResult.Status? do { status = sslEngine!!.unwrap(cipherIn, plainIn).status when (status) { SSLEngineResult.Status.OK -> { plainIn!!.flip() copyBuffer(plainIn, buffer) plainIn!!.compact() handshakeStatus = runDelegatedTasks() } SSLEngineResult.Status.BUFFER_OVERFLOW -> { plainIn!!.flip() val appSize = sslEngine!!.session.applicationBufferSize val newAppSize = appSize + plainIn!!.remaining() if (newAppSize > appSize * 2) throw IOException("Failed to enlarge application input buffer ") val newPlainIn = ByteBuffer.allocateDirect(newAppSize).order(ByteOrder.BIG_ENDIAN) newPlainIn.put(plainIn) plainIn = newPlainIn } SSLEngineResult.Status.BUFFER_UNDERFLOW -> { val curNetSize = cipherIn!!.capacity() val netSize = sslEngine!!.session.packetBufferSize if (netSize > curNetSize) { val newCipherIn = ByteBuffer.allocateDirect(netSize).order(ByteOrder.BIG_ENDIAN) newCipherIn.put(cipherIn) cipherIn = newCipherIn } else { cipherIn!!.compact() } return handshakeStatus } else -> throw IOException("Unexpected status $status") } } while (cipherIn!!.hasRemaining()) cipherIn!!.compact() return handshakeStatus } /** * Wrap byte buffer and write it to a channel */ private fun wrap(buffer: ByteBuffer?): HandshakeStatus { var handshakeStatus = sslEngine!!.handshakeStatus val status = sslEngine!!.wrap(buffer, cipherOut).status when (status) { SSLEngineResult.Status.OK -> { handshakeStatus = runDelegatedTasks() cipherOut!!.flip() channel.write(cipherOut) cipherOut!!.clear() } SSLEngineResult.Status.BUFFER_OVERFLOW -> { val curNetSize = cipherOut!!.capacity() val netSize = sslEngine!!.session.packetBufferSize if (curNetSize >= netSize || buffer!!.capacity() > netSize) { throw IOException("Failed to enlarge network buffer") } cipherOut = ByteBuffer.allocateDirect(netSize).order(ByteOrder.BIG_ENDIAN) } else -> throw IOException("Unexpected status $status") } return handshakeStatus } /** * Initial allocation of a buffer */ private fun createBuffers() { val session = sslEngine!!.session val appBufferSize = session.applicationBufferSize val netBufferSize = session.packetBufferSize plainOut = ByteBuffer.allocateDirect(appBufferSize).order(ByteOrder.BIG_ENDIAN) plainIn = ByteBuffer.allocateDirect(appBufferSize).order(ByteOrder.BIG_ENDIAN) cipherOut = ByteBuffer.allocateDirect(netBufferSize).order(ByteOrder.BIG_ENDIAN) cipherIn = ByteBuffer.allocateDirect(netBufferSize).order(ByteOrder.BIG_ENDIAN) } /** * Read from a channel and Unwrap SSL data */ override fun read(dst: ByteBuffer): Int { val toRead = dst.remaining() plainIn!!.flip() if (plainIn!!.remaining() >= toRead) { copyBuffer(plainIn, dst) plainIn!!.compact() } else { dst.put(plainIn) do { plainIn!!.clear() unwrap(dst) } while (dst.remaining() > 0) } return toRead } /** * SSL Wrap a buffer and write it to socket channel */ override fun write(src: ByteBuffer): Int { val toWrite = src.remaining() while (src.remaining() > 0) { wrap(src) } return toWrite } /** * Close channel */ override fun close() { plainOut!!.clear() sslEngine!!.closeOutbound() while (!sslEngine!!.isOutboundDone) { sslEngine!!.wrap(plainOut, cipherOut) while (cipherOut!!.hasRemaining()) { val num = channel.write(cipherOut) if (num == -1) { break } } } channel.close() } companion object { const val MAX_HANDSHAKE_ITERATIONS = 5000 /** * Helper method to copy a buffer */ internal fun copyBuffer(from: ByteBuffer?, to: ByteBuffer?): Int { if (from == null || to == null) return 0 var i = 0 while (to.remaining() > 0 && from.remaining() > 0) { to.put(from.get()) i++ } return i } } }
agpl-3.0
3df7acf8cc9d3ce31aa0966206011e38
32.25
128
0.56034
5.140274
false
false
false
false
GunoH/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/ConverKClassToClassFix.kt
3
2775
// 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.codeInsight.intention.HighPriorityAction import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import org.jetbrains.kotlin.builtins.KotlinBuiltIns import org.jetbrains.kotlin.descriptors.ClassDescriptor import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.caches.resolve.resolveImportReference import org.jetbrains.kotlin.idea.base.psi.replaced import org.jetbrains.kotlin.idea.codeinsight.api.classic.quickfixes.KotlinQuickFixAction import org.jetbrains.kotlin.psi.KtExpression import org.jetbrains.kotlin.psi.KtFile import org.jetbrains.kotlin.psi.KtPsiFactory import org.jetbrains.kotlin.psi.createExpressionByPattern import org.jetbrains.kotlin.types.KotlinType import org.jetbrains.kotlin.types.KotlinTypeFactory import org.jetbrains.kotlin.types.TypeAttributes import org.jetbrains.kotlin.types.TypeProjectionImpl import org.jetbrains.kotlin.types.typeUtil.isSubtypeOf class ConvertKClassToClassFix(element: KtExpression) : KotlinQuickFixAction<KtExpression>(element), HighPriorityAction { override fun getText() = familyName override fun getFamilyName() = KotlinBundle.message("convert.from.class.to.kclass") override fun invoke(project: Project, editor: Editor?, file: KtFile) { val element = element ?: return val expressionToInsert = KtPsiFactory(file).createExpressionByPattern("$0.java", element) element.replaced(expressionToInsert) } companion object { fun create(file: KtFile, expectedType: KotlinType, expressionType: KotlinType, diagnosticElement: KtExpression): ConvertKClassToClassFix?{ val expressionClassDescriptor = expressionType.constructor.declarationDescriptor as? ClassDescriptor ?: return null if (!KotlinBuiltIns.isKClass(expressionClassDescriptor) || !expectedType.isJClass()) return null val expressionTypeArgument = expressionType.arguments.firstOrNull()?.type ?: return null val javaLangClassDescriptor = file.resolveImportReference(JAVA_LANG_CLASS_FQ_NAME) .singleOrNull() as? ClassDescriptor ?: return null val javaLangClassType = KotlinTypeFactory.simpleNotNullType( TypeAttributes.Empty, javaLangClassDescriptor, listOf(TypeProjectionImpl(expressionTypeArgument)) ) if (javaLangClassType.isSubtypeOf(expectedType)) { return ConvertKClassToClassFix(diagnosticElement) } return null } } }
apache-2.0
d31efaae7c6982a79a2bc4bc10af52da
52.384615
158
0.766126
5.12939
false
false
false
false
jk1/intellij-community
platform/script-debugger/backend/src/debugger/values/ValueType.kt
2
1334
/* * 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.debugger.values private val VALUE_TYPES = ValueType.values() /** * Don't forget to update NashornDebuggerSupport.ValueType and DebuggerSupport.ts respectively also */ enum class ValueType { OBJECT, NUMBER, STRING, FUNCTION, BOOLEAN, ARRAY, NODE, UNDEFINED, NULL, SYMBOL; /** * Returns whether `type` corresponds to a JsObject. Note that while 'null' is an object * in JavaScript world, here for API consistency it has bogus type [.NULL] and is * not a [ObjectValue] */ val isObjectType: Boolean get() = this == OBJECT || this == ARRAY || this == FUNCTION || this == NODE companion object { fun fromIndex(index: Int): ValueType = VALUE_TYPES.get(index) } }
apache-2.0
2b918b1da2393f4b9c3f504155380ee9
26.8125
99
0.709145
4.042424
false
false
false
false
g1144146/sds_for_kotlin
src/main/kotlin/sds/util/AccessFlag.kt
1
3915
package sds.util object AccessFlag { private val PUBLIC: Pair<Int, String> = 0x0001 to "public " private val PRIVATE: Pair<Int, String> = 0x0002 to "private " private val PROTECTED: Pair<Int, String> = 0x0004 to "protected " private val STATIC: Pair<Int, String> = 0x0008 to "static " private val FINAL: Pair<Int, String> = 0x0010 to "final " private val SYNCHRONIZED: Pair<Int, String> = 0x0020 to "synchronized " private val VOLATILE: Pair<Int, String> = 0x0040 to "volatile " private val TRANSIENT: Pair<Int, String> = 0x0080 to "transient " private val NATIVE: Pair<Int, String> = 0x0100 to "native " private val INTERFACE: Pair<Int, String> = 0x0200 to "interface " private val ABSTRACT: Pair<Int, String> = 0x0400 to "abstract " private val STRICT: Pair<Int, String> = 0x0800 to "strictfp " private val SYNTHETIC: Pair<Int, String> = 0x1000 to "synthetic " private val ANNOTATION: Pair<Int, String> = 0x2000 to "@interface " private val ENUM: Pair<Int, String> = 0x4000 to "enum " private val SUPER: Int = 0x0020 private val BRIDGE: Int = 0x0040 private val VARARGS: Int = 0x0080 private val CLASS: Int = PUBLIC.first or FINAL.first or SUPER or INTERFACE.first or ABSTRACT.first or SYNTHETIC.first or ANNOTATION.first or ENUM.first private val FIELD: Int = PUBLIC.first or PRIVATE.first or PROTECTED.first or STATIC.first or FINAL.first or VOLATILE.first or TRANSIENT.first or SYNTHETIC.first or ENUM.first private val METHOD: Int = PUBLIC.first or PRIVATE.first or PROTECTED.first or STATIC.first or FINAL.first or SYNCHRONIZED.first or BRIDGE or VARARGS or NATIVE.first or ABSTRACT.first or STRICT.first or SYNTHETIC.first private val NESTED: Int = PUBLIC.first or PRIVATE.first or PROTECTED.first or STATIC.first or FINAL.first or INTERFACE.first or ABSTRACT.first or SYNTHETIC.first or ANNOTATION.first or ENUM.first private val LOCAL: Int = FINAL.first fun get(flag: Int, type: String): String = when { type == "class" && checkOr(flag, CLASS) -> getClassFlag(flag) type == "field" && checkOr(flag, FIELD) -> getFieldFlag(flag) type == "method" && checkOr(flag, METHOD) -> getMethodFlag(flag) type == "nested" && checkOr(flag, NESTED) -> getClassFlag(flag) type == "local" && checkOr(flag, LOCAL) -> getLocalFlag(flag) else -> throw IllegalArgumentException() } private fun getClassFlag(flag: Int): String = build(flag, PUBLIC, STATIC, FINAL, SYNTHETIC, ABSTRACT) + when { checkAnd(flag, ANNOTATION.first) -> ANNOTATION.second checkAnd(flag, ENUM.first) -> ENUM.second checkAnd(flag, INTERFACE.first) -> INTERFACE.second else -> "class " } private fun getFieldFlag(flag: Int): String = build(flag, PUBLIC, PRIVATE, PROTECTED, STATIC, FINAL, VOLATILE, TRANSIENT, SYNTHETIC, ENUM) private fun getMethodFlag(flag: Int): String = build(flag, PUBLIC, PRIVATE, PROTECTED, STATIC, FINAL, SYNCHRONIZED, NATIVE, ABSTRACT, STRICT, SYNTHETIC) private fun getLocalFlag(flag: Int): String = if(checkAnd(flag, FINAL.first)) "final " else "" private fun build(target: Int, vararg flags: Pair<Int, String>): String = flags.filter { checkAnd(target, it.first) } .map { it.second } .reduce { flag1: String, flag2: String -> flag1 + flag2 } private fun checkAnd(target: Int, flag: Int): Boolean = (target and flag) == flag private fun checkOr(target: Int, flag: Int): Boolean = (target or flag) == flag }
apache-2.0
777d2b714c9adb1c66bff7e7c8dc36da
64.266667
120
0.627075
3.942598
false
false
false
false
emoji-gen/Emoji-Android
app/src/main/java/moe/pine/emoji/components/setting/SettingTeamListComponent.kt
1
1874
package moe.pine.emoji.components.setting import android.os.Bundle import android.support.v4.app.Fragment import com.squareup.otto.Subscribe import io.realm.Realm import io.realm.Sort import kotlinx.android.synthetic.main.fragment_setting_team_list.* import moe.pine.emoji.adapter.setting.SettingTeamListAdapter import moe.pine.emoji.model.event.TeamAddedEvent import moe.pine.emoji.model.event.TeamDeleteEvent import moe.pine.emoji.model.realm.SlackTeam import moe.pine.emoji.util.eventBus /** * Component for setting team list * Created by pine on May 14, 2017. */ class SettingTeamListComponent( val fragment: Fragment ) { private lateinit var realm: Realm private val teams: List<SlackTeam> get() = this.realm.where(SlackTeam::class.java).findAllSorted("team", Sort.ASCENDING) fun onActivityCreated(savedInstanceState: Bundle?) { this.realm = Realm.getDefaultInstance() this.eventBus.register(this) val adapter = SettingTeamListAdapter(this.fragment.context!!) this.fragment.list_view_setting.adapter = adapter this.update() } fun onDestroyView() { this.eventBus.unregister(this) this.realm.close() } @Subscribe fun onTeamDelete(event: TeamDeleteEvent) { this.removeTeam(event.domain) this.update() } @Subscribe fun onTeamAdded(event: TeamAddedEvent) { this.update() } private fun update() { val adapter = this.fragment.list_view_setting.adapter as SettingTeamListAdapter adapter.replaceAll(this.teams) } private fun removeTeam(domain: String) { val team: SlackTeam? = this.realm.where(SlackTeam::class.java) .equalTo("team", domain) .findFirst() team ?: return this.realm.executeTransaction { team.deleteFromRealm() } } }
mit
3720739db6e89a7eeeaa70ffd810a7af
26.985075
93
0.692636
4.082789
false
false
false
false
mdanielwork/intellij-community
java/idea-ui/src/com/intellij/jarRepository/ExternalAnnotationsRepositoryResolver.kt
1
5429
// 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.jarRepository import com.intellij.codeInsight.ExternalAnnotationsArtifactsResolver import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.application.invokeAndWaitIfNeed import com.intellij.openapi.application.runWriteAction import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.project.Project import com.intellij.openapi.roots.AnnotationOrderRootType import com.intellij.openapi.roots.impl.libraries.LibraryEx import com.intellij.openapi.roots.libraries.Library import com.intellij.openapi.roots.libraries.ui.OrderRoot import com.intellij.openapi.roots.ui.configuration.libraryEditor.ExistingLibraryEditor import org.jetbrains.concurrency.AsyncPromise import org.jetbrains.concurrency.Promise import org.jetbrains.idea.maven.aether.ArtifactKind import org.jetbrains.idea.maven.utils.library.RepositoryLibraryProperties import org.jetbrains.jps.model.library.JpsMavenRepositoryLibraryDescriptor /** * Resolve external annotations from Maven repositories. * Delegates actual resolution to [JarRepositoryManager] */ class ExternalAnnotationsRepositoryResolver : ExternalAnnotationsArtifactsResolver { companion object { val LOG = Logger.getInstance(ExternalAnnotationsRepositoryResolver::class.java) } override fun resolve(project: Project, library: Library, mavenId: String?): Library { var mavenLibDescriptor = extractDescriptor(mavenId, library, false) ?: return library var roots = JarRepositoryManager .loadDependenciesSync(project, mavenLibDescriptor, setOf(ArtifactKind.ANNOTATIONS), null, null) as MutableList<OrderRoot>? if (roots == null || roots.isEmpty()) { mavenLibDescriptor = extractDescriptor(mavenId, library, true) ?: return library roots = JarRepositoryManager .loadDependenciesSync(project, mavenLibDescriptor, setOf(ArtifactKind.ANNOTATIONS), null, null) as MutableList<OrderRoot>? } invokeAndWaitIfNeed { updateLibrary(roots, mavenLibDescriptor, library) } return library } override fun resolveAsync(project: Project, library: Library, mavenId: String?): Promise<Library> { val mavenLibDescriptor = extractDescriptor(mavenId, library, false) ?: return Promise.resolve(library) return JarRepositoryManager.loadDependenciesAsync(project, mavenLibDescriptor, setOf(ArtifactKind.ANNOTATIONS), null, null) .thenAsync { roots -> val resolvedRoots = Promise.resolve(roots) if (roots?.isEmpty() == false) { resolvedRoots } else { val patchedDescriptor = extractDescriptor(mavenId, library, true) ?: return@thenAsync resolvedRoots JarRepositoryManager.loadDependenciesAsync(project, patchedDescriptor, setOf(ArtifactKind.ANNOTATIONS), null, null) } }.thenAsync { roots -> val promise = AsyncPromise<Library>() ApplicationManager.getApplication().invokeLater { updateLibrary(roots, mavenLibDescriptor, library) promise.setResult(library) } promise } } private fun updateLibrary(roots: MutableList<OrderRoot>?, mavenLibDescriptor: JpsMavenRepositoryLibraryDescriptor, library: Library) { if (roots == null || roots.isEmpty()) { LOG.info("No annotations found for [$mavenLibDescriptor]") } else { runWriteAction { LOG.debug("Found ${roots.size} external annotations for ${library.name}") val editor = ExistingLibraryEditor(library, null) val type = AnnotationOrderRootType.getInstance() editor.getUrls(type).forEach { editor.removeRoot(it, type) } editor.addRoots(roots) editor.commit() } } } private fun extractDescriptor(mavenId: String?, library: Library, patched: Boolean): JpsMavenRepositoryLibraryDescriptor? = when { mavenId != null -> JpsMavenRepositoryLibraryDescriptor( if (patched) patchArtifactId(mavenId) else mavenId, false, emptyList() ) library is LibraryEx -> (library.properties as? RepositoryLibraryProperties) ?.run { JpsMavenRepositoryLibraryDescriptor(groupId, if (patched) "$artifactId-annotations" else artifactId, version) } else -> null } private fun patchArtifactId(mavenId: String): String { val components = mavenId.split(':', limit = 3) if (components.size < 3) { return mavenId } return "${components[0]}:${components[1]}-annotations:${components[2]}" } }
apache-2.0
eb8cd1e4be52adf05e26ec715cfdf303
41.748031
140
0.631608
5.579651
false
false
false
false
dahlstrom-g/intellij-community
plugins/kotlin/j2k/new/tests/testData/inference/mutability/listOfMutableList.kt
13
549
import java.util.ArrayList fun a() { val list: /*T4@*/List</*T3@*/MutableList</*T2@*/Int>> = ArrayList</*T1@*/MutableList</*T0@*/Int>>()/*ArrayList<T1@MutableList<T0@Int>>*/ list/*T4@MutableList<T3@MutableList<T2@Int>>*/.get(0/*LIT*/)/*T3@MutableList<T2@Int>*/.add(1/*LIT*/) } //T2 := T0 due to 'INITIALIZER' //T3 := T1 due to 'INITIALIZER' //T2 := T2 due to 'RECEIVER_PARAMETER' //T3 := T3 due to 'RECEIVER_PARAMETER' //T4 <: UPPER due to 'RECEIVER_PARAMETER' //T2 := T2 due to 'RECEIVER_PARAMETER' //T3 := LOWER due to 'USE_AS_RECEIVER'
apache-2.0
f13711ee014a0c1b7a2f8afe32ce8587
38.214286
140
0.639344
2.758794
false
false
false
false
anibyl/slounik
main/src/main/java/org/anibyl/slounik/data/ArticlesInfo.kt
1
694
package org.anibyl.slounik.data /** * Represents article information. * Contains articles and connected information. * @author Usievaład Kimajeŭ * @created 29.04.2015 */ class ArticlesInfo { enum class Status { SUCCESS, IN_PROCESS, FAILURE } var articles: List<Article>? = null private set var status: Status? = null internal set constructor(articles: List<Article>?, status: Status) { this.articles = articles this.status = status } constructor(articles: List<Article>?) { this.articles = articles if (articles == null) { status = Status.FAILURE } else { status = Status.SUCCESS } } constructor(status: Status) { this.status = status } }
gpl-3.0
24885c87e9348f1795dea90d91c0c209
15.878049
56
0.686416
3.218605
false
false
false
false
dahlstrom-g/intellij-community
java/java-analysis-impl/src/com/intellij/codeInspection/apiUsage/ApiUsageUastVisitor.kt
2
17462
// 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.codeInspection.apiUsage import com.intellij.lang.java.JavaLanguage import com.intellij.psi.* import com.intellij.psi.util.PsiTreeUtil import com.intellij.psi.util.PsiUtil import com.intellij.uast.UastVisitorAdapter import com.intellij.util.castSafelyTo import org.jetbrains.annotations.ApiStatus import org.jetbrains.uast.* import org.jetbrains.uast.visitor.AbstractUastNonRecursiveVisitor /** * Non-recursive UAST visitor that detects usages of APIs in source code of UAST-supporting languages * and reports them via [ApiUsageProcessor] interface. */ @ApiStatus.Experimental open class ApiUsageUastVisitor(private val apiUsageProcessor: ApiUsageProcessor) : AbstractUastNonRecursiveVisitor() { companion object { @JvmStatic fun createPsiElementVisitor(apiUsageProcessor: ApiUsageProcessor): PsiElementVisitor = UastVisitorAdapter(ApiUsageUastVisitor(apiUsageProcessor), true) } override fun visitSimpleNameReferenceExpression(node: USimpleNameReferenceExpression): Boolean { if (maybeProcessReferenceInsideImportStatement(node)) { return true } if (maybeProcessJavaModuleReference(node)) { return true } if (isMethodReferenceOfCallExpression(node) || isNewArrayClassReference(node) || isMethodReferenceOfCallableReferenceExpression(node) || isSelectorOfQualifiedReference(node) ) { return true } if (isSuperOrThisCall(node)) { return true } val resolved = node.resolve() if (resolved is PsiMethod) { if (isClassReferenceInConstructorInvocation(node) || isClassReferenceInKotlinSuperClassConstructor(node)) { /* Suppose a code: ``` object : SomeClass(42) { } or new SomeClass(42) ``` with USimpleNameReferenceExpression pointing to `SomeClass`. We want ApiUsageProcessor to notice two events: 1) reference to `SomeClass` and 2) reference to `SomeClass(int)` constructor. But Kotlin UAST resolves this simple reference to the PSI constructor of the class SomeClass. So we resolve it manually to the class because the constructor will be handled separately in "visitObjectLiteralExpression" or "visitCallExpression". */ val resolvedClass = resolved.containingClass if (resolvedClass != null) { apiUsageProcessor.processReference(node, resolvedClass, null) } return true } } if (resolved is PsiModifierListOwner) { apiUsageProcessor.processReference(node, resolved, null) return true } return true } override fun visitQualifiedReferenceExpression(node: UQualifiedReferenceExpression): Boolean { if (maybeProcessReferenceInsideImportStatement(node)) { return true } if (node.sourcePsi is PsiMethodCallExpression || node.selector is UCallExpression) { //UAST for Java produces UQualifiedReferenceExpression for both PsiMethodCallExpression and PsiReferenceExpression inside it //UAST for Kotlin produces UQualifiedReferenceExpression with UCallExpression as selector return true } var resolved = node.resolve() if (resolved == null) { resolved = node.selector.tryResolve() } if (resolved is PsiModifierListOwner) { apiUsageProcessor.processReference(node.selector, resolved, node.receiver) } return true } private fun isKotlin(node: UElement): Boolean { val sourcePsi = node.sourcePsi ?: return false return sourcePsi.language.id.contains("kotlin", true) } override fun visitCallableReferenceExpression(node: UCallableReferenceExpression): Boolean { /* * KT-31181: Kotlin UAST: UCallableReferenceExpression.referenceNameElement is always null. */ fun workaroundKotlinGetReferenceNameElement(node: UCallableReferenceExpression): UElement? { if (isKotlin(node)) { val sourcePsi = node.sourcePsi if (sourcePsi != null) { val children = sourcePsi.children if (children.size == 2) { return children[1].toUElement() } } } return null } val resolve = node.resolve() if (resolve is PsiModifierListOwner) { val sourceNode = node.referenceNameElement ?: workaroundKotlinGetReferenceNameElement(node) ?: node apiUsageProcessor.processReference(sourceNode, resolve, node.qualifierExpression) //todo support this for other JVM languages val javaMethodReference = node.sourcePsi as? PsiMethodReferenceExpression if (javaMethodReference != null) { //a reference to the functional interface will be added by compiler val resolved = PsiUtil.resolveGenericsClassInType(javaMethodReference.functionalInterfaceType).element if (resolved != null) { apiUsageProcessor.processReference(node, resolved, null) } } } return true } override fun visitCallExpression(node: UCallExpression): Boolean { if (node.sourcePsi is PsiExpressionStatement) { //UAST for Java generates UCallExpression for PsiExpressionStatement and PsiMethodCallExpression inside it. return true } val psiMethod = node.resolve() val sourceNode = node.methodIdentifier ?: node.classReference?.referenceNameElement ?: node.classReference ?: node if (psiMethod != null) { val containingClass = psiMethod.containingClass if (psiMethod.isConstructor) { if (containingClass != null) { apiUsageProcessor.processConstructorInvocation(sourceNode, containingClass, psiMethod, null) } } else { apiUsageProcessor.processReference(sourceNode, psiMethod, node.receiver) } return true } if (node.kind == UastCallKind.CONSTRUCTOR_CALL) { //Java does not resolve constructor for subclass constructor's "super()" statement // if the superclass has the default constructor, which is not declared in source code and lacks PsiMethod. val superClass = node.getContainingUClass()?.javaPsi?.superClass ?: return true apiUsageProcessor.processConstructorInvocation(sourceNode, superClass, null, null) return true } val classReference = node.classReference if (classReference != null) { val resolvedClass = classReference.resolve() as? PsiClass if (resolvedClass != null) { if (node.kind == UastCallKind.CONSTRUCTOR_CALL) { val emptyConstructor = resolvedClass.constructors.find { it.parameterList.isEmpty } apiUsageProcessor.processConstructorInvocation(sourceNode, resolvedClass, emptyConstructor, null) } else { apiUsageProcessor.processReference(sourceNode, resolvedClass, node.receiver) } } return true } return true } override fun visitObjectLiteralExpression(node: UObjectLiteralExpression): Boolean { val psiMethod = node.resolve() val sourceNode = node.methodIdentifier ?: node.classReference?.referenceNameElement ?: node.classReference ?: node.declaration.uastSuperTypes.firstOrNull() ?: node if (psiMethod != null) { val containingClass = psiMethod.containingClass if (psiMethod.isConstructor) { if (containingClass != null) { apiUsageProcessor.processConstructorInvocation(sourceNode, containingClass, psiMethod, node.declaration) } } } else { maybeProcessImplicitConstructorInvocationAtSubclassDeclaration(sourceNode, node.declaration) } return true } override fun visitElement(node: UElement): Boolean { if (node is UNamedExpression) { //IDEA-209279: UAstVisitor lacks a hook for UNamedExpression //KT-30522: Kotlin does not generate UNamedExpression for annotation's parameters. processNamedExpression(node) return true } return super.visitElement(node) } override fun visitClass(node: UClass): Boolean { val uastAnchor = node.uastAnchor if (uastAnchor == null || node is UAnonymousClass || node.javaPsi is PsiTypeParameter) { return true } maybeProcessImplicitConstructorInvocationAtSubclassDeclaration(uastAnchor, node) return true } override fun visitMethod(node: UMethod): Boolean { if (node.isConstructor) { checkImplicitCallOfSuperEmptyConstructor(node) } else { checkMethodOverriding(node) } return true } override fun visitLambdaExpression(node: ULambdaExpression): Boolean { val explicitClassReference = (node.uastParent as? UCallExpression)?.classReference if (explicitClassReference == null) { //a reference to the functional interface will be added by compiler val resolved = PsiUtil.resolveGenericsClassInType(node.functionalInterfaceType).element if (resolved != null) { apiUsageProcessor.processReference(node, resolved, null) } } return true } private fun maybeProcessJavaModuleReference(node: UElement): Boolean { val sourcePsi = node.sourcePsi if (sourcePsi is PsiJavaModuleReferenceElement) { val reference = sourcePsi.reference val target = reference?.resolve() if (target != null) { apiUsageProcessor.processJavaModuleReference(reference, target) } return true } return false } private fun maybeProcessReferenceInsideImportStatement(node: UReferenceExpression): Boolean { if (isInsideImportStatement(node)) { val parentingQualifier = node.castSafelyTo<USimpleNameReferenceExpression>()?.uastParent.castSafelyTo<UQualifiedReferenceExpression>() if (node != parentingQualifier?.selector) { val resolved = node.resolve() as? PsiModifierListOwner if (resolved != null) { apiUsageProcessor.processImportReference(node.referenceNameElement ?: node, resolved) } } return true } return false } private fun isInsideImportStatement(node: UElement): Boolean { val sourcePsi = node.sourcePsi if (sourcePsi != null && sourcePsi.language == JavaLanguage.INSTANCE) { return PsiTreeUtil.getParentOfType(sourcePsi, PsiImportStatementBase::class.java) != null } return sourcePsi.findContaining(UImportStatement::class.java) != null } private fun maybeProcessImplicitConstructorInvocationAtSubclassDeclaration(sourceNode: UElement, subclassDeclaration: UClass) { val instantiatedClass = subclassDeclaration.javaPsi.superClass ?: return val subclassHasExplicitConstructor = subclassDeclaration.methods.any { it.isConstructor } val emptyConstructor = instantiatedClass.constructors.find { it.parameterList.isEmpty } if (subclassDeclaration is UAnonymousClass || !subclassHasExplicitConstructor) { apiUsageProcessor.processConstructorInvocation(sourceNode, instantiatedClass, emptyConstructor, subclassDeclaration) } } private fun processNamedExpression(node: UNamedExpression) { val sourcePsi = node.sourcePsi val annotationMethod = sourcePsi?.reference?.resolve() as? PsiAnnotationMethod if (annotationMethod != null) { val sourceNode = (sourcePsi as? PsiNameValuePair)?.nameIdentifier?.toUElement() ?: node apiUsageProcessor.processReference(sourceNode, annotationMethod, null) } } protected fun checkImplicitCallOfSuperEmptyConstructor(constructor: UMethod) { val containingUClass = constructor.getContainingUClass() ?: return val superClass = containingUClass.javaPsi.superClass ?: return val uastBody = constructor.uastBody val uastAnchor = constructor.uastAnchor if (uastAnchor != null && isImplicitCallOfSuperEmptyConstructorFromSubclassConstructorBody(uastBody)) { val emptyConstructor = superClass.constructors.find { it.parameterList.isEmpty } apiUsageProcessor.processConstructorInvocation(uastAnchor, superClass, emptyConstructor, null) } } private fun isImplicitCallOfSuperEmptyConstructorFromSubclassConstructorBody(constructorBody: UExpression?): Boolean { if (constructorBody == null || constructorBody is UBlockExpression && constructorBody.expressions.isEmpty()) { //Empty constructor body => implicit super() call. return true } val firstExpression = (constructorBody as? UBlockExpression)?.expressions?.firstOrNull() ?: constructorBody if (firstExpression !is UCallExpression) { //First expression is not super() => the super() is implicit. return true } if (firstExpression.valueArgumentCount > 0) { //Invocation of non-empty super(args) constructor. return false } val methodName = firstExpression.methodIdentifier?.name ?: firstExpression.methodName return methodName != "super" && methodName != "this" } private fun checkMethodOverriding(node: UMethod) { val method = node.javaPsi val superMethods = method.findSuperMethods(true) for (superMethod in superMethods) { apiUsageProcessor.processMethodOverriding(node, superMethod) } } /** * UAST for Kotlin generates UAST tree with "UnknownKotlinExpression (CONSTRUCTOR_CALLEE)" for the following expressions: * 1) an object literal expression: `object : BaseClass() { ... }` * 2) a super class constructor invocation `class Derived : BaseClass(42) { ... }` * * * ``` * UObjectLiteralExpression * UnknownKotlinExpression (CONSTRUCTOR_CALLEE) * UTypeReferenceExpression (BaseClass) * USimpleNameReferenceExpression (BaseClass) * ``` * * and * * ``` * UCallExpression (kind = CONSTRUCTOR_CALL) * UnknownKotlinExpression (CONSTRUCTOR_CALLEE) * UTypeReferenceExpression (BaseClass) * USimpleNameReferenceExpression (BaseClass) * ``` * * This method checks if the given simple reference points to the `BaseClass` part, * which is treated by Kotlin UAST as a reference to `BaseClass'` constructor, not to the `BaseClass` itself. */ private fun isClassReferenceInKotlinSuperClassConstructor(expression: USimpleNameReferenceExpression): Boolean { val parent1 = expression.uastParent val parent2 = parent1?.uastParent val parent3 = parent2?.uastParent return parent1 is UTypeReferenceExpression && parent2 != null && parent2.asLogString().contains("CONSTRUCTOR_CALLEE") && (parent3 is UObjectLiteralExpression || parent3 is UCallExpression && parent3.kind == UastCallKind.CONSTRUCTOR_CALL) } private fun isSelectorOfQualifiedReference(expression: USimpleNameReferenceExpression): Boolean { val qualifiedReference = expression.uastParent as? UQualifiedReferenceExpression ?: return false return haveSameSourceElement(expression, qualifiedReference.selector) } private fun isNewArrayClassReference(simpleReference: USimpleNameReferenceExpression): Boolean { val callExpression = simpleReference.uastParent as? UCallExpression ?: return false return callExpression.kind == UastCallKind.NEW_ARRAY_WITH_DIMENSIONS } private fun isSuperOrThisCall(simpleReference: USimpleNameReferenceExpression): Boolean { val callExpression = simpleReference.uastParent as? UCallExpression ?: return false return callExpression.kind == UastCallKind.CONSTRUCTOR_CALL && (callExpression.methodIdentifier?.name == "super" || callExpression.methodIdentifier?.name == "this") } private fun isClassReferenceInConstructorInvocation(simpleReference: USimpleNameReferenceExpression): Boolean { if (isSuperOrThisCall(simpleReference)) { return false } val callExpression = simpleReference.uastParent as? UCallExpression ?: return false if (callExpression.kind != UastCallKind.CONSTRUCTOR_CALL) { return false } val classReferenceNameElement = callExpression.classReference?.referenceNameElement if (classReferenceNameElement != null) { return haveSameSourceElement(classReferenceNameElement, simpleReference.referenceNameElement) } return callExpression.resolve()?.name == simpleReference.resolvedName } private fun isMethodReferenceOfCallExpression(expression: USimpleNameReferenceExpression): Boolean { val callExpression = expression.uastParent as? UCallExpression ?: return false if (callExpression.kind != UastCallKind.METHOD_CALL) { return false } val expressionNameElement = expression.referenceNameElement val methodIdentifier = callExpression.methodIdentifier return methodIdentifier != null && haveSameSourceElement(expressionNameElement, methodIdentifier) } private fun isMethodReferenceOfCallableReferenceExpression(expression: USimpleNameReferenceExpression): Boolean { val callableReferenceExpression = expression.uastParent as? UCallableReferenceExpression ?: return false if (haveSameSourceElement(callableReferenceExpression.referenceNameElement, expression)) { return true } return expression.identifier == callableReferenceExpression.callableName } private fun haveSameSourceElement(element1: UElement?, element2: UElement?): Boolean { if (element1 == null || element2 == null) return false val sourcePsi1 = element1.sourcePsi return sourcePsi1 != null && sourcePsi1 == element2.sourcePsi } }
apache-2.0
9baa764bb1bfa4b5d15e5bacf28fcf3a
40.186321
140
0.725518
5.712136
false
false
false
false
dahlstrom-g/intellij-community
plugins/hg4idea/src/org/zmlx/hg4idea/provider/HgCloneDialogComponent.kt
8
2222
// 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.zmlx.hg4idea.provider import com.intellij.dvcs.ui.CloneDvcsValidationUtils import com.intellij.dvcs.ui.DvcsCloneDialogComponent import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.project.Project import com.intellij.openapi.vcs.CheckoutProvider import com.intellij.openapi.vcs.VcsBundle import com.intellij.openapi.vcs.VcsNotifier import com.intellij.openapi.vcs.ui.cloneDialog.VcsCloneDialogComponentStateListener import org.zmlx.hg4idea.HgNotificationIdsHolder.Companion.CLONE_DESTINATION_ERROR import org.zmlx.hg4idea.HgRememberedInputs import org.zmlx.hg4idea.util.HgUtil import java.nio.file.Paths class HgCloneDialogComponent(project: Project, dialogStateListener: VcsCloneDialogComponentStateListener) : DvcsCloneDialogComponent(project, HgUtil.DOT_HG, HgRememberedInputs.getInstance(), dialogStateListener) { private val LOG = Logger.getInstance(HgCloneDialogComponent::class.java) override fun doClone(listener: CheckoutProvider.Listener) { val validationInfo = CloneDvcsValidationUtils.createDestination(getDirectory()) if (validationInfo != null) { LOG.error("Unable to create destination directory", validationInfo.message) VcsNotifier.getInstance(project).notifyError(CLONE_DESTINATION_ERROR, VcsBundle.message("clone.dialog.clone.failed.error"), VcsBundle.message("clone.dialog.unable.create.destination.error")) return } val directory = Paths.get(getDirectory()).fileName.toString() val url = getUrl() val parent = Paths.get(getDirectory()).toAbsolutePath().parent.toAbsolutePath().toString() HgCheckoutProvider.doClone(project, listener, directory, url, parent) rememberedInputs.addUrl(url) rememberedInputs.cloneParentDir = parent } override fun onComponentSelected(dialogStateListener: VcsCloneDialogComponentStateListener) { updateOkActionState(dialogStateListener) } }
apache-2.0
7ad93ef0a5d7c4788d8335a9e2cc8f94
47.326087
140
0.743924
4.638831
false
false
false
false
tateisu/SubwayTooter
app/src/main/java/jp/juggler/subwaytooter/actmain/ActMainQuickPost.kt
1
5093
package jp.juggler.subwaytooter.actmain import android.text.InputType import android.view.View import android.view.inputmethod.EditorInfo import android.widget.TextView import androidx.core.view.GravityCompat import jp.juggler.subwaytooter.ActMain import jp.juggler.subwaytooter.App1 import jp.juggler.subwaytooter.R import jp.juggler.subwaytooter.Styler import jp.juggler.subwaytooter.actpost.CompletionHelper import jp.juggler.subwaytooter.api.entity.TootVisibility import jp.juggler.subwaytooter.dialog.pickAccount import jp.juggler.subwaytooter.pref.PrefB import jp.juggler.subwaytooter.table.SavedAccount import jp.juggler.subwaytooter.util.PostImpl import jp.juggler.subwaytooter.util.PostResult import jp.juggler.util.hideKeyboard import jp.juggler.util.launchAndShowError import jp.juggler.util.launchMain import org.jetbrains.anko.imageResource // 簡易投稿入力のテキスト val ActMain.quickPostText: String get() = etQuickPost.text.toString() fun ActMain.initUIQuickPost() { etQuickPost.typeface = ActMain.timelineFont if (!PrefB.bpQuickPostBar(pref)) { llQuickPostBar.visibility = View.GONE } if (PrefB.bpDontUseActionButtonWithQuickPostBar(pref)) { etQuickPost.inputType = InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_FLAG_MULTI_LINE etQuickPost.imeOptions = EditorInfo.IME_ACTION_NONE // 最後に指定する必要がある? etQuickPost.maxLines = 5 etQuickPost.isVerticalScrollBarEnabled = true etQuickPost.isScrollbarFadingEnabled = false } else { etQuickPost.inputType = InputType.TYPE_CLASS_TEXT etQuickPost.imeOptions = EditorInfo.IME_ACTION_SEND etQuickPost.setOnEditorActionListener(TextView.OnEditorActionListener { _, actionId, _ -> if (actionId == EditorInfo.IME_ACTION_SEND) { btnQuickToot.performClick() return@OnEditorActionListener true } false }) // 最後に指定する必要がある? etQuickPost.maxLines = 1 } completionHelper.attachEditText( llFormRoot, etQuickPost, true, object : CompletionHelper.Callback2 { override fun onTextUpdate() {} override fun canOpenPopup(): Boolean { return !drawer.isDrawerOpen(GravityCompat.START) } }) showQuickPostVisibility() } fun ActMain.showQuickPostVisibility() { btnQuickPostMenu.imageResource = when (val resId = Styler.getVisibilityIconId(false, quickPostVisibility)) { R.drawable.ic_question -> R.drawable.ic_description else -> resId } } fun ActMain.toggleQuickPostMenu() { dlgQuickTootMenu.toggle() } fun ActMain.performQuickPost(account: SavedAccount?) { if (account == null) { val a = if (tabletViews != null && !PrefB.bpQuickTootOmitAccountSelection(pref)) { // タブレットモードでオプションが無効なら // 簡易投稿は常にアカウント選択する null } else { currentPostTarget } if (a != null && !a.isPseudo) { performQuickPost(a) } else { // アカウントを選択してやり直し launchMain { pickAccount( bAllowPseudo = false, bAuto = true, message = getString(R.string.account_picker_toot) )?.let { performQuickPost(it) } } } return } etQuickPost.hideKeyboard() launchAndShowError { val postResult = PostImpl( activity = this@performQuickPost, account = account, content = etQuickPost.text.toString().trim { it <= ' ' }, spoilerText = null, visibilityArg = when (quickPostVisibility) { TootVisibility.AccountSetting -> account.visibility else -> quickPostVisibility }, bNSFW = false, inReplyToId = null, attachmentListArg = null, enqueteItemsArg = null, pollType = null, pollExpireSeconds = 0, pollHideTotals = false, pollMultipleChoice = false, scheduledAt = 0L, scheduledId = null, redraftStatusId = null, editStatusId = null, emojiMapCustom = App1.custom_emoji_lister.getMapNonBlocking(account), useQuoteToot = false, lang = account.lang, ).runSuspend() if (postResult is PostResult.Normal) { etQuickPost.setText("") postedAcct = postResult.targetAccount.acct postedStatusId = postResult.status.id postedReplyId = postResult.status.in_reply_to_id postedRedraftId = null refreshAfterPost() } } }
apache-2.0
73d6824e0503bced8173a3ae8074c71f
31.705479
97
0.614306
4.40161
false
false
false
false
awsdocs/aws-doc-sdk-examples
kotlin/services/comprehend/src/main/kotlin/com/kotlin/comprehend/DetectKeyPhrases.kt
1
1821
// snippet-sourcedescription:[DetectKeyPhrases.kt demonstrates how to detect key phrases.] // snippet-keyword:[AWS SDK for Kotlin] // snippet-service:[Amazon Comprehend] /* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. SPDX-License-Identifier: Apache-2.0 */ package com.kotlin.comprehend // snippet-start:[comprehend.kotlin.detect_keyphrases.import] import aws.sdk.kotlin.services.comprehend.ComprehendClient import aws.sdk.kotlin.services.comprehend.model.DetectKeyPhrasesRequest import aws.sdk.kotlin.services.comprehend.model.LanguageCode // snippet-end:[comprehend.kotlin.detect_keyphrases.import] /** Before running this Kotlin code example, set up your development environment, including your credentials. For more information, see the following documentation topic: https://docs.aws.amazon.com/sdk-for-kotlin/latest/developer-guide/setup.html */ suspend fun main() { val text = "Amazon.com, Inc. is located in Seattle, WA and was founded July 5th, 1994 by Jeff Bezos, allowing customers to buy everything from books to blenders. Seattle is north of Portland and south of Vancouver, BC. Other notable Seattle - based companies are Starbucks and Boeing." detectAllKeyPhrases(text) } // snippet-start:[comprehend.kotlin.detect_keyphrases.main] suspend fun detectAllKeyPhrases(textVal: String) { val request = DetectKeyPhrasesRequest { text = textVal languageCode = LanguageCode.fromValue("en") } ComprehendClient { region = "us-east-1" }.use { comClient -> val response = comClient.detectKeyPhrases(request) response.keyPhrases?.forEach { phrase -> println("Key phrase text is ${phrase.text}") } } } // snippet-end:[comprehend.kotlin.detect_keyphrases.main]
apache-2.0
878d3d2f1b95def19fa27acab3a4714a
37.586957
289
0.732565
3.833684
false
false
false
false
JoelMarcey/buck
src/com/facebook/buck/jvm/kotlin/plugin/ClassUsageRecorder.kt
1
5059
/* * Copyright (c) Facebook, Inc. and its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.facebook.buck.jvm.kotlin.plugin import com.intellij.openapi.project.Project import com.intellij.psi.search.GlobalSearchScope import kotlin.reflect.jvm.internal.impl.load.java.sources.JavaSourceElement import org.jetbrains.kotlin.descriptors.CallableDescriptor import org.jetbrains.kotlin.descriptors.ClassDescriptor import org.jetbrains.kotlin.descriptors.DeclarationDescriptor import org.jetbrains.kotlin.descriptors.ModuleDescriptor import org.jetbrains.kotlin.descriptors.ValueDescriptor import org.jetbrains.kotlin.load.java.JavaClassFinder import org.jetbrains.kotlin.load.java.structure.JavaClass import org.jetbrains.kotlin.load.java.structure.classId import org.jetbrains.kotlin.load.java.structure.impl.VirtualFileBoundJavaClass import org.jetbrains.kotlin.load.kotlin.JvmPackagePartSource import org.jetbrains.kotlin.load.kotlin.KotlinJvmBinarySourceElement import org.jetbrains.kotlin.load.kotlin.VirtualFileFinder import org.jetbrains.kotlin.load.kotlin.getSourceElement import org.jetbrains.kotlin.name.ClassId import org.jetbrains.kotlin.name.FqName import org.jetbrains.kotlin.resolve.descriptorUtil.classId import org.jetbrains.kotlin.resolve.jvm.KotlinJavaPsiFacade import org.jetbrains.kotlin.serialization.deserialization.descriptors.DescriptorWithContainerSource import org.jetbrains.kotlin.types.KotlinType private const val JAR_FILE_SEPARATOR = "!/" class ClassUsageRecorder(project: Project, module: ModuleDescriptor) { private val searchScope = GlobalSearchScope.allScope(project) private val psiFacade = KotlinJavaPsiFacade.getInstance(project) private val fileFinder = VirtualFileFinder.getInstance(project, module) private val seen = mutableSetOf<KotlinType>() private val results = mutableMapOf<String, MutableMap<String, Int>>() fun getUsage(): Map<String, MutableMap<String, Int>> = HashMap(results) fun recordClass(fqName: FqName) { if (!fqName.isRoot) { recordClass(ClassId.topLevel(fqName)) } } fun recordClass(type: KotlinType?) { type?.run { /** * This is done not only for optimisation. The main reason is to avoid endless recursion when * a class depends on itself (e.g. `class Foo : Comparable<Foo>` or an annotation is used on * itself like [java.lang.annotation.Target]) */ if (!seen.add(this)) return constructor.declarationDescriptor?.let(::recordClass) arguments.forEach { if (!it.isStarProjection) { recordClass(it.type) } } } } fun recordClass(descriptor: DeclarationDescriptor) { val source = getSourceElement(descriptor) when { source is JvmPackagePartSource -> { source.knownJvmBinaryClass?.location?.let(::addFile) } source is KotlinJvmBinarySourceElement -> { addFile(source.binaryClass.location) } source is JavaSourceElement && source.javaElement is VirtualFileBoundJavaClass -> { (source.javaElement as VirtualFileBoundJavaClass).virtualFile?.path?.let(::addFile) } descriptor is DescriptorWithContainerSource && descriptor.containerSource is JvmPackagePartSource -> { (descriptor.containerSource as JvmPackagePartSource).knownJvmBinaryClass?.location?.let( ::addFile) } } descriptor.annotations.forEach { recordClass(it.type) } when (descriptor) { is ClassDescriptor -> { descriptor.classId?.let(::recordClass) } is ValueDescriptor -> { recordClass(descriptor.type) } is CallableDescriptor -> { descriptor.valueParameters.forEach { recordClass(it) } descriptor.typeParameters.forEach { recordClass(it) } descriptor.returnType?.let(::recordClass) } } } private fun recordClass(classId: ClassId) { fileFinder.findVirtualFileWithHeader(classId)?.path?.let(::addFile) psiFacade.findClass(JavaClassFinder.Request(classId), searchScope)?.let(::recordSupertypes) } private fun recordSupertypes(javaClass: JavaClass) { javaClass.supertypes.forEach { (it.classifier as? JavaClass)?.classId?.let(::recordClass) } } private fun addFile(path: String) { if (path.contains(JAR_FILE_SEPARATOR)) { val (jarPath, classPath) = path.split(JAR_FILE_SEPARATOR) val occurrences = results.computeIfAbsent(jarPath) { mutableMapOf() } occurrences.compute(classPath) { _, count -> count ?: 0 + 1 } } } }
apache-2.0
7f6e254843ec055f2cd718c23c40d921
37.618321
99
0.738881
4.453345
false
false
false
false
zbeboy/ISY
src/main/java/top/zbeboy/isy/service/graduate/design/GraduationDesignArchivesServiceImpl.kt
1
45922
package top.zbeboy.isy.service.graduate.design import org.jooq.* import org.springframework.beans.factory.annotation.Autowired import org.springframework.stereotype.Service import org.springframework.transaction.annotation.Propagation import org.springframework.transaction.annotation.Transactional import org.springframework.util.ObjectUtils import org.springframework.util.StringUtils import top.zbeboy.isy.domain.Tables.* import top.zbeboy.isy.domain.tables.pojos.GraduationDesignArchives import top.zbeboy.isy.domain.tables.records.GraduationDesignArchivesRecord import top.zbeboy.isy.service.plugin.DataTablesPlugin import top.zbeboy.isy.service.util.SQLQueryUtils import top.zbeboy.isy.web.bean.graduate.design.archives.GraduationDesignArchivesBean import top.zbeboy.isy.web.util.DataTablesUtils import java.util.* /** * Created by zbeboy 2018-02-08 . **/ @Service("graduationDesignArchivesService") @Transactional(propagation = Propagation.SUPPORTS, readOnly = true) open class GraduationDesignArchivesServiceImpl @Autowired constructor(dslContext: DSLContext) : DataTablesPlugin<GraduationDesignArchivesBean>(), GraduationDesignArchivesService { private val create: DSLContext = dslContext override fun findByGraduationDesignPresubjectId(graduationDesignPresubjectId: String): GraduationDesignArchivesRecord { return create.selectFrom(GRADUATION_DESIGN_ARCHIVES) .where(GRADUATION_DESIGN_ARCHIVES.GRADUATION_DESIGN_PRESUBJECT_ID.eq(graduationDesignPresubjectId)) .fetchOne() } override fun findByArchiveNumber(archiveNumber: String): GraduationDesignArchivesRecord { return create.selectFrom(GRADUATION_DESIGN_ARCHIVES) .where(GRADUATION_DESIGN_ARCHIVES.ARCHIVE_NUMBER.eq(archiveNumber)) .fetchOne() } override fun findAllByPage(dataTablesUtils: DataTablesUtils<GraduationDesignArchivesBean>, graduateArchivesBean: GraduationDesignArchivesBean): List<GraduationDesignArchivesBean> { val graduateArchivesBeans = ArrayList<GraduationDesignArchivesBean>() val records: Result<Record> var a = searchCondition(dataTablesUtils) a = otherCondition(a, graduateArchivesBean) records = if (ObjectUtils.isEmpty(a)) { val selectJoinStep = create.select() .from(GRADUATION_DESIGN_TEACHER) .join(GRADUATION_DESIGN_TUTOR) .on(GRADUATION_DESIGN_TEACHER.GRADUATION_DESIGN_TEACHER_ID.eq(GRADUATION_DESIGN_TUTOR.GRADUATION_DESIGN_TEACHER_ID)) .join(GRADUATION_DESIGN_PRESUBJECT) .on(GRADUATION_DESIGN_TUTOR.STUDENT_ID.eq(GRADUATION_DESIGN_PRESUBJECT.STUDENT_ID)) .join(DEFENSE_ARRANGEMENT) .on(DEFENSE_ARRANGEMENT.GRADUATION_DESIGN_RELEASE_ID.eq(GRADUATION_DESIGN_TEACHER.GRADUATION_DESIGN_RELEASE_ID)) .join(DEFENSE_GROUP) .on(DEFENSE_GROUP.DEFENSE_ARRANGEMENT_ID.eq(DEFENSE_ARRANGEMENT.DEFENSE_ARRANGEMENT_ID)) .join(DEFENSE_ORDER) .on(DEFENSE_ORDER.DEFENSE_GROUP_ID.eq(DEFENSE_GROUP.DEFENSE_GROUP_ID).and(GRADUATION_DESIGN_TUTOR.STUDENT_ID.eq(DEFENSE_ORDER.STUDENT_ID))) .leftJoin(SCORE_TYPE) .on(DEFENSE_ORDER.SCORE_TYPE_ID.eq(SCORE_TYPE.SCORE_TYPE_ID)) .join(STAFF) .on(GRADUATION_DESIGN_TEACHER.STAFF_ID.eq(STAFF.STAFF_ID)) .leftJoin(ACADEMIC_TITLE) .on(STAFF.ACADEMIC_TITLE_ID.eq(ACADEMIC_TITLE.ACADEMIC_TITLE_ID)) .join(GRADUATION_DESIGN_DECLARE) .on(GRADUATION_DESIGN_PRESUBJECT.GRADUATION_DESIGN_PRESUBJECT_ID.eq(GRADUATION_DESIGN_DECLARE.GRADUATION_DESIGN_PRESUBJECT_ID)) .leftJoin(GRADUATION_DESIGN_SUBJECT_TYPE) .on(GRADUATION_DESIGN_DECLARE.SUBJECT_TYPE_ID.eq(GRADUATION_DESIGN_SUBJECT_TYPE.SUBJECT_TYPE_ID)) .leftJoin(GRADUATION_DESIGN_SUBJECT_ORIGIN_TYPE) .on(GRADUATION_DESIGN_DECLARE.ORIGIN_TYPE_ID.eq(GRADUATION_DESIGN_SUBJECT_ORIGIN_TYPE.ORIGIN_TYPE_ID)) .leftJoin(GRADUATION_DESIGN_ARCHIVES) .on(GRADUATION_DESIGN_PRESUBJECT.GRADUATION_DESIGN_PRESUBJECT_ID.eq(GRADUATION_DESIGN_ARCHIVES.GRADUATION_DESIGN_PRESUBJECT_ID)) .join(GRADUATION_DESIGN_DECLARE_DATA) .on(GRADUATION_DESIGN_PRESUBJECT.GRADUATION_DESIGN_RELEASE_ID.eq(GRADUATION_DESIGN_DECLARE_DATA.GRADUATION_DESIGN_RELEASE_ID)) .join(GRADUATION_DESIGN_RELEASE) .on(GRADUATION_DESIGN_PRESUBJECT.GRADUATION_DESIGN_RELEASE_ID.eq(GRADUATION_DESIGN_RELEASE.GRADUATION_DESIGN_RELEASE_ID)) .join(SCIENCE) .on(GRADUATION_DESIGN_RELEASE.SCIENCE_ID.eq(SCIENCE.SCIENCE_ID)) .join(DEPARTMENT) .on(SCIENCE.DEPARTMENT_ID.eq(DEPARTMENT.DEPARTMENT_ID)) .join(COLLEGE) .on(DEPARTMENT.COLLEGE_ID.eq(COLLEGE.COLLEGE_ID)) sortCondition(dataTablesUtils, null, selectJoinStep, DataTablesPlugin.JOIN_TYPE) pagination(dataTablesUtils, null, selectJoinStep, DataTablesPlugin.JOIN_TYPE) selectJoinStep.fetch() } else { val selectConditionStep = create.select() .from(GRADUATION_DESIGN_TEACHER) .join(GRADUATION_DESIGN_TUTOR) .on(GRADUATION_DESIGN_TEACHER.GRADUATION_DESIGN_TEACHER_ID.eq(GRADUATION_DESIGN_TUTOR.GRADUATION_DESIGN_TEACHER_ID)) .join(GRADUATION_DESIGN_PRESUBJECT) .on(GRADUATION_DESIGN_TUTOR.STUDENT_ID.eq(GRADUATION_DESIGN_PRESUBJECT.STUDENT_ID).and(GRADUATION_DESIGN_PRESUBJECT.GRADUATION_DESIGN_RELEASE_ID.eq(graduateArchivesBean.graduationDesignReleaseId))) .join(DEFENSE_ARRANGEMENT) .on(DEFENSE_ARRANGEMENT.GRADUATION_DESIGN_RELEASE_ID.eq(GRADUATION_DESIGN_TEACHER.GRADUATION_DESIGN_RELEASE_ID)) .join(DEFENSE_GROUP) .on(DEFENSE_GROUP.DEFENSE_ARRANGEMENT_ID.eq(DEFENSE_ARRANGEMENT.DEFENSE_ARRANGEMENT_ID)) .join(DEFENSE_ORDER) .on(DEFENSE_ORDER.DEFENSE_GROUP_ID.eq(DEFENSE_GROUP.DEFENSE_GROUP_ID).and(GRADUATION_DESIGN_TUTOR.STUDENT_ID.eq(DEFENSE_ORDER.STUDENT_ID))) .leftJoin(SCORE_TYPE) .on(DEFENSE_ORDER.SCORE_TYPE_ID.eq(SCORE_TYPE.SCORE_TYPE_ID)) .join(STAFF) .on(GRADUATION_DESIGN_TEACHER.STAFF_ID.eq(STAFF.STAFF_ID)) .leftJoin(ACADEMIC_TITLE) .on(STAFF.ACADEMIC_TITLE_ID.eq(ACADEMIC_TITLE.ACADEMIC_TITLE_ID)) .join(GRADUATION_DESIGN_DECLARE) .on(GRADUATION_DESIGN_PRESUBJECT.GRADUATION_DESIGN_PRESUBJECT_ID.eq(GRADUATION_DESIGN_DECLARE.GRADUATION_DESIGN_PRESUBJECT_ID)) .leftJoin(GRADUATION_DESIGN_SUBJECT_TYPE) .on(GRADUATION_DESIGN_DECLARE.SUBJECT_TYPE_ID.eq(GRADUATION_DESIGN_SUBJECT_TYPE.SUBJECT_TYPE_ID)) .leftJoin(GRADUATION_DESIGN_SUBJECT_ORIGIN_TYPE) .on(GRADUATION_DESIGN_DECLARE.ORIGIN_TYPE_ID.eq(GRADUATION_DESIGN_SUBJECT_ORIGIN_TYPE.ORIGIN_TYPE_ID)) .leftJoin(GRADUATION_DESIGN_ARCHIVES) .on(GRADUATION_DESIGN_PRESUBJECT.GRADUATION_DESIGN_PRESUBJECT_ID.eq(GRADUATION_DESIGN_ARCHIVES.GRADUATION_DESIGN_PRESUBJECT_ID)) .join(GRADUATION_DESIGN_DECLARE_DATA) .on(GRADUATION_DESIGN_PRESUBJECT.GRADUATION_DESIGN_RELEASE_ID.eq(GRADUATION_DESIGN_DECLARE_DATA.GRADUATION_DESIGN_RELEASE_ID)) .join(GRADUATION_DESIGN_RELEASE) .on(GRADUATION_DESIGN_PRESUBJECT.GRADUATION_DESIGN_RELEASE_ID.eq(GRADUATION_DESIGN_RELEASE.GRADUATION_DESIGN_RELEASE_ID)) .join(SCIENCE) .on(GRADUATION_DESIGN_RELEASE.SCIENCE_ID.eq(SCIENCE.SCIENCE_ID)) .join(DEPARTMENT) .on(SCIENCE.DEPARTMENT_ID.eq(DEPARTMENT.DEPARTMENT_ID)) .join(COLLEGE) .on(DEPARTMENT.COLLEGE_ID.eq(COLLEGE.COLLEGE_ID)) .where(a) sortCondition(dataTablesUtils, selectConditionStep, null, DataTablesPlugin.CONDITION_TYPE) pagination(dataTablesUtils, selectConditionStep, null, DataTablesPlugin.CONDITION_TYPE) selectConditionStep.fetch() } buildData(records, graduateArchivesBeans) return graduateArchivesBeans } override fun countAll(graduateArchivesBean: GraduationDesignArchivesBean): Int { val count: Record1<Int> val a = otherCondition(null, graduateArchivesBean) count = if (ObjectUtils.isEmpty(a)) { create.selectCount() .from(GRADUATION_DESIGN_TEACHER) .join(GRADUATION_DESIGN_TUTOR) .on(GRADUATION_DESIGN_TEACHER.GRADUATION_DESIGN_TEACHER_ID.eq(GRADUATION_DESIGN_TUTOR.GRADUATION_DESIGN_TEACHER_ID)) .join(GRADUATION_DESIGN_PRESUBJECT) .on(GRADUATION_DESIGN_TUTOR.STUDENT_ID.eq(GRADUATION_DESIGN_PRESUBJECT.STUDENT_ID)) .join(DEFENSE_ARRANGEMENT) .on(DEFENSE_ARRANGEMENT.GRADUATION_DESIGN_RELEASE_ID.eq(GRADUATION_DESIGN_TEACHER.GRADUATION_DESIGN_RELEASE_ID)) .join(DEFENSE_GROUP) .on(DEFENSE_GROUP.DEFENSE_ARRANGEMENT_ID.eq(DEFENSE_ARRANGEMENT.DEFENSE_ARRANGEMENT_ID)) .join(DEFENSE_ORDER) .on(DEFENSE_ORDER.DEFENSE_GROUP_ID.eq(DEFENSE_GROUP.DEFENSE_GROUP_ID).and(GRADUATION_DESIGN_TUTOR.STUDENT_ID.eq(DEFENSE_ORDER.STUDENT_ID))) .leftJoin(SCORE_TYPE) .on(DEFENSE_ORDER.SCORE_TYPE_ID.eq(SCORE_TYPE.SCORE_TYPE_ID)) .join(STAFF) .on(GRADUATION_DESIGN_TEACHER.STAFF_ID.eq(STAFF.STAFF_ID)) .leftJoin(ACADEMIC_TITLE) .on(STAFF.ACADEMIC_TITLE_ID.eq(ACADEMIC_TITLE.ACADEMIC_TITLE_ID)) .join(GRADUATION_DESIGN_DECLARE) .on(GRADUATION_DESIGN_PRESUBJECT.GRADUATION_DESIGN_PRESUBJECT_ID.eq(GRADUATION_DESIGN_DECLARE.GRADUATION_DESIGN_PRESUBJECT_ID)) .leftJoin(GRADUATION_DESIGN_SUBJECT_TYPE) .on(GRADUATION_DESIGN_DECLARE.SUBJECT_TYPE_ID.eq(GRADUATION_DESIGN_SUBJECT_TYPE.SUBJECT_TYPE_ID)) .leftJoin(GRADUATION_DESIGN_SUBJECT_ORIGIN_TYPE) .on(GRADUATION_DESIGN_DECLARE.ORIGIN_TYPE_ID.eq(GRADUATION_DESIGN_SUBJECT_ORIGIN_TYPE.ORIGIN_TYPE_ID)) .leftJoin(GRADUATION_DESIGN_ARCHIVES) .on(GRADUATION_DESIGN_PRESUBJECT.GRADUATION_DESIGN_PRESUBJECT_ID.eq(GRADUATION_DESIGN_ARCHIVES.GRADUATION_DESIGN_PRESUBJECT_ID)) .join(GRADUATION_DESIGN_DECLARE_DATA) .on(GRADUATION_DESIGN_PRESUBJECT.GRADUATION_DESIGN_RELEASE_ID.eq(GRADUATION_DESIGN_DECLARE_DATA.GRADUATION_DESIGN_RELEASE_ID)) .join(GRADUATION_DESIGN_RELEASE) .on(GRADUATION_DESIGN_PRESUBJECT.GRADUATION_DESIGN_RELEASE_ID.eq(GRADUATION_DESIGN_RELEASE.GRADUATION_DESIGN_RELEASE_ID)) .join(SCIENCE) .on(GRADUATION_DESIGN_RELEASE.SCIENCE_ID.eq(SCIENCE.SCIENCE_ID)) .join(DEPARTMENT) .on(SCIENCE.DEPARTMENT_ID.eq(DEPARTMENT.DEPARTMENT_ID)) .join(COLLEGE) .on(DEPARTMENT.COLLEGE_ID.eq(COLLEGE.COLLEGE_ID)) .fetchOne() } else { create.selectCount() .from(GRADUATION_DESIGN_TEACHER) .join(GRADUATION_DESIGN_TUTOR) .on(GRADUATION_DESIGN_TEACHER.GRADUATION_DESIGN_TEACHER_ID.eq(GRADUATION_DESIGN_TUTOR.GRADUATION_DESIGN_TEACHER_ID)) .join(GRADUATION_DESIGN_PRESUBJECT) .on(GRADUATION_DESIGN_TUTOR.STUDENT_ID.eq(GRADUATION_DESIGN_PRESUBJECT.STUDENT_ID).and(GRADUATION_DESIGN_PRESUBJECT.GRADUATION_DESIGN_RELEASE_ID.eq(graduateArchivesBean.graduationDesignReleaseId))) .join(DEFENSE_ARRANGEMENT) .on(DEFENSE_ARRANGEMENT.GRADUATION_DESIGN_RELEASE_ID.eq(GRADUATION_DESIGN_TEACHER.GRADUATION_DESIGN_RELEASE_ID)) .join(DEFENSE_GROUP) .on(DEFENSE_GROUP.DEFENSE_ARRANGEMENT_ID.eq(DEFENSE_ARRANGEMENT.DEFENSE_ARRANGEMENT_ID)) .join(DEFENSE_ORDER) .on(DEFENSE_ORDER.DEFENSE_GROUP_ID.eq(DEFENSE_GROUP.DEFENSE_GROUP_ID).and(GRADUATION_DESIGN_TUTOR.STUDENT_ID.eq(DEFENSE_ORDER.STUDENT_ID))) .leftJoin(SCORE_TYPE) .on(DEFENSE_ORDER.SCORE_TYPE_ID.eq(SCORE_TYPE.SCORE_TYPE_ID)) .join(STAFF) .on(GRADUATION_DESIGN_TEACHER.STAFF_ID.eq(STAFF.STAFF_ID)) .leftJoin(ACADEMIC_TITLE) .on(STAFF.ACADEMIC_TITLE_ID.eq(ACADEMIC_TITLE.ACADEMIC_TITLE_ID)) .join(GRADUATION_DESIGN_DECLARE) .on(GRADUATION_DESIGN_PRESUBJECT.GRADUATION_DESIGN_PRESUBJECT_ID.eq(GRADUATION_DESIGN_DECLARE.GRADUATION_DESIGN_PRESUBJECT_ID)) .leftJoin(GRADUATION_DESIGN_SUBJECT_TYPE) .on(GRADUATION_DESIGN_DECLARE.SUBJECT_TYPE_ID.eq(GRADUATION_DESIGN_SUBJECT_TYPE.SUBJECT_TYPE_ID)) .leftJoin(GRADUATION_DESIGN_SUBJECT_ORIGIN_TYPE) .on(GRADUATION_DESIGN_DECLARE.ORIGIN_TYPE_ID.eq(GRADUATION_DESIGN_SUBJECT_ORIGIN_TYPE.ORIGIN_TYPE_ID)) .leftJoin(GRADUATION_DESIGN_ARCHIVES) .on(GRADUATION_DESIGN_PRESUBJECT.GRADUATION_DESIGN_PRESUBJECT_ID.eq(GRADUATION_DESIGN_ARCHIVES.GRADUATION_DESIGN_PRESUBJECT_ID)) .join(GRADUATION_DESIGN_DECLARE_DATA) .on(GRADUATION_DESIGN_PRESUBJECT.GRADUATION_DESIGN_RELEASE_ID.eq(GRADUATION_DESIGN_DECLARE_DATA.GRADUATION_DESIGN_RELEASE_ID)) .join(GRADUATION_DESIGN_RELEASE) .on(GRADUATION_DESIGN_PRESUBJECT.GRADUATION_DESIGN_RELEASE_ID.eq(GRADUATION_DESIGN_RELEASE.GRADUATION_DESIGN_RELEASE_ID)) .join(SCIENCE) .on(GRADUATION_DESIGN_RELEASE.SCIENCE_ID.eq(SCIENCE.SCIENCE_ID)) .join(DEPARTMENT) .on(SCIENCE.DEPARTMENT_ID.eq(DEPARTMENT.DEPARTMENT_ID)) .join(COLLEGE) .on(DEPARTMENT.COLLEGE_ID.eq(COLLEGE.COLLEGE_ID)) .where(a) .fetchOne() } return count.value1() } override fun countByCondition(dataTablesUtils: DataTablesUtils<GraduationDesignArchivesBean>, graduateArchivesBean: GraduationDesignArchivesBean): Int { val count: Record1<Int> var a = searchCondition(dataTablesUtils) a = otherCondition(a, graduateArchivesBean) count = if (ObjectUtils.isEmpty(a)) { val selectJoinStep = create.selectCount() .from(GRADUATION_DESIGN_TEACHER) .join(GRADUATION_DESIGN_TUTOR) .on(GRADUATION_DESIGN_TEACHER.GRADUATION_DESIGN_TEACHER_ID.eq(GRADUATION_DESIGN_TUTOR.GRADUATION_DESIGN_TEACHER_ID)) .join(GRADUATION_DESIGN_PRESUBJECT) .on(GRADUATION_DESIGN_TUTOR.STUDENT_ID.eq(GRADUATION_DESIGN_PRESUBJECT.STUDENT_ID)) .join(DEFENSE_ARRANGEMENT) .on(DEFENSE_ARRANGEMENT.GRADUATION_DESIGN_RELEASE_ID.eq(GRADUATION_DESIGN_TEACHER.GRADUATION_DESIGN_RELEASE_ID)) .join(DEFENSE_GROUP) .on(DEFENSE_GROUP.DEFENSE_ARRANGEMENT_ID.eq(DEFENSE_ARRANGEMENT.DEFENSE_ARRANGEMENT_ID)) .join(DEFENSE_ORDER) .on(DEFENSE_ORDER.DEFENSE_GROUP_ID.eq(DEFENSE_GROUP.DEFENSE_GROUP_ID).and(GRADUATION_DESIGN_TUTOR.STUDENT_ID.eq(DEFENSE_ORDER.STUDENT_ID))) .leftJoin(SCORE_TYPE) .on(DEFENSE_ORDER.SCORE_TYPE_ID.eq(SCORE_TYPE.SCORE_TYPE_ID)) .join(STAFF) .on(GRADUATION_DESIGN_TEACHER.STAFF_ID.eq(STAFF.STAFF_ID)) .leftJoin(ACADEMIC_TITLE) .on(STAFF.ACADEMIC_TITLE_ID.eq(ACADEMIC_TITLE.ACADEMIC_TITLE_ID)) .join(GRADUATION_DESIGN_DECLARE) .on(GRADUATION_DESIGN_PRESUBJECT.GRADUATION_DESIGN_PRESUBJECT_ID.eq(GRADUATION_DESIGN_DECLARE.GRADUATION_DESIGN_PRESUBJECT_ID)) .leftJoin(GRADUATION_DESIGN_SUBJECT_TYPE) .on(GRADUATION_DESIGN_DECLARE.SUBJECT_TYPE_ID.eq(GRADUATION_DESIGN_SUBJECT_TYPE.SUBJECT_TYPE_ID)) .leftJoin(GRADUATION_DESIGN_SUBJECT_ORIGIN_TYPE) .on(GRADUATION_DESIGN_DECLARE.ORIGIN_TYPE_ID.eq(GRADUATION_DESIGN_SUBJECT_ORIGIN_TYPE.ORIGIN_TYPE_ID)) .leftJoin(GRADUATION_DESIGN_ARCHIVES) .on(GRADUATION_DESIGN_PRESUBJECT.GRADUATION_DESIGN_PRESUBJECT_ID.eq(GRADUATION_DESIGN_ARCHIVES.GRADUATION_DESIGN_PRESUBJECT_ID)) .join(GRADUATION_DESIGN_DECLARE_DATA) .on(GRADUATION_DESIGN_PRESUBJECT.GRADUATION_DESIGN_RELEASE_ID.eq(GRADUATION_DESIGN_DECLARE_DATA.GRADUATION_DESIGN_RELEASE_ID)) .join(GRADUATION_DESIGN_RELEASE) .on(GRADUATION_DESIGN_PRESUBJECT.GRADUATION_DESIGN_RELEASE_ID.eq(GRADUATION_DESIGN_RELEASE.GRADUATION_DESIGN_RELEASE_ID)) .join(SCIENCE) .on(GRADUATION_DESIGN_RELEASE.SCIENCE_ID.eq(SCIENCE.SCIENCE_ID)) .join(DEPARTMENT) .on(SCIENCE.DEPARTMENT_ID.eq(DEPARTMENT.DEPARTMENT_ID)) .join(COLLEGE) .on(DEPARTMENT.COLLEGE_ID.eq(COLLEGE.COLLEGE_ID)) selectJoinStep.fetchOne() } else { val selectConditionStep = create.selectCount() .from(GRADUATION_DESIGN_TEACHER) .join(GRADUATION_DESIGN_TUTOR) .on(GRADUATION_DESIGN_TEACHER.GRADUATION_DESIGN_TEACHER_ID.eq(GRADUATION_DESIGN_TUTOR.GRADUATION_DESIGN_TEACHER_ID)) .join(GRADUATION_DESIGN_PRESUBJECT) .on(GRADUATION_DESIGN_TUTOR.STUDENT_ID.eq(GRADUATION_DESIGN_PRESUBJECT.STUDENT_ID).and(GRADUATION_DESIGN_PRESUBJECT.GRADUATION_DESIGN_RELEASE_ID.eq(graduateArchivesBean.graduationDesignReleaseId))) .join(DEFENSE_ARRANGEMENT) .on(DEFENSE_ARRANGEMENT.GRADUATION_DESIGN_RELEASE_ID.eq(GRADUATION_DESIGN_TEACHER.GRADUATION_DESIGN_RELEASE_ID)) .join(DEFENSE_GROUP) .on(DEFENSE_GROUP.DEFENSE_ARRANGEMENT_ID.eq(DEFENSE_ARRANGEMENT.DEFENSE_ARRANGEMENT_ID)) .join(DEFENSE_ORDER) .on(DEFENSE_ORDER.DEFENSE_GROUP_ID.eq(DEFENSE_GROUP.DEFENSE_GROUP_ID).and(GRADUATION_DESIGN_TUTOR.STUDENT_ID.eq(DEFENSE_ORDER.STUDENT_ID))) .leftJoin(SCORE_TYPE) .on(DEFENSE_ORDER.SCORE_TYPE_ID.eq(SCORE_TYPE.SCORE_TYPE_ID)) .join(STAFF) .on(GRADUATION_DESIGN_TEACHER.STAFF_ID.eq(STAFF.STAFF_ID)) .leftJoin(ACADEMIC_TITLE) .on(STAFF.ACADEMIC_TITLE_ID.eq(ACADEMIC_TITLE.ACADEMIC_TITLE_ID)) .join(GRADUATION_DESIGN_DECLARE) .on(GRADUATION_DESIGN_PRESUBJECT.GRADUATION_DESIGN_PRESUBJECT_ID.eq(GRADUATION_DESIGN_DECLARE.GRADUATION_DESIGN_PRESUBJECT_ID)) .leftJoin(GRADUATION_DESIGN_SUBJECT_TYPE) .on(GRADUATION_DESIGN_DECLARE.SUBJECT_TYPE_ID.eq(GRADUATION_DESIGN_SUBJECT_TYPE.SUBJECT_TYPE_ID)) .leftJoin(GRADUATION_DESIGN_SUBJECT_ORIGIN_TYPE) .on(GRADUATION_DESIGN_DECLARE.ORIGIN_TYPE_ID.eq(GRADUATION_DESIGN_SUBJECT_ORIGIN_TYPE.ORIGIN_TYPE_ID)) .leftJoin(GRADUATION_DESIGN_ARCHIVES) .on(GRADUATION_DESIGN_PRESUBJECT.GRADUATION_DESIGN_PRESUBJECT_ID.eq(GRADUATION_DESIGN_ARCHIVES.GRADUATION_DESIGN_PRESUBJECT_ID)) .join(GRADUATION_DESIGN_DECLARE_DATA) .on(GRADUATION_DESIGN_PRESUBJECT.GRADUATION_DESIGN_RELEASE_ID.eq(GRADUATION_DESIGN_DECLARE_DATA.GRADUATION_DESIGN_RELEASE_ID)) .join(GRADUATION_DESIGN_RELEASE) .on(GRADUATION_DESIGN_PRESUBJECT.GRADUATION_DESIGN_RELEASE_ID.eq(GRADUATION_DESIGN_RELEASE.GRADUATION_DESIGN_RELEASE_ID)) .join(SCIENCE) .on(GRADUATION_DESIGN_RELEASE.SCIENCE_ID.eq(SCIENCE.SCIENCE_ID)) .join(DEPARTMENT) .on(SCIENCE.DEPARTMENT_ID.eq(DEPARTMENT.DEPARTMENT_ID)) .join(COLLEGE) .on(DEPARTMENT.COLLEGE_ID.eq(COLLEGE.COLLEGE_ID)) .where(a) selectConditionStep.fetchOne() } return count.value1() } override fun exportData(dataTablesUtils: DataTablesUtils<GraduationDesignArchivesBean>, graduationDesignArchivesBean: GraduationDesignArchivesBean): List<GraduationDesignArchivesBean> { val graduationDesignArchivesBeans = ArrayList<GraduationDesignArchivesBean>() val records: Result<Record> var a = searchCondition(dataTablesUtils) a = otherCondition(a, graduationDesignArchivesBean) records = if (ObjectUtils.isEmpty(a)) { val selectJoinStep = create.select() .from(GRADUATION_DESIGN_TEACHER) .join(GRADUATION_DESIGN_TUTOR) .on(GRADUATION_DESIGN_TEACHER.GRADUATION_DESIGN_TEACHER_ID.eq(GRADUATION_DESIGN_TUTOR.GRADUATION_DESIGN_TEACHER_ID)) .join(GRADUATION_DESIGN_PRESUBJECT) .on(GRADUATION_DESIGN_TUTOR.STUDENT_ID.eq(GRADUATION_DESIGN_PRESUBJECT.STUDENT_ID)) .join(DEFENSE_ARRANGEMENT) .on(DEFENSE_ARRANGEMENT.GRADUATION_DESIGN_RELEASE_ID.eq(GRADUATION_DESIGN_TEACHER.GRADUATION_DESIGN_RELEASE_ID)) .join(DEFENSE_GROUP) .on(DEFENSE_GROUP.DEFENSE_ARRANGEMENT_ID.eq(DEFENSE_ARRANGEMENT.DEFENSE_ARRANGEMENT_ID)) .join(DEFENSE_ORDER) .on(DEFENSE_ORDER.DEFENSE_GROUP_ID.eq(DEFENSE_GROUP.DEFENSE_GROUP_ID).and(GRADUATION_DESIGN_TUTOR.STUDENT_ID.eq(DEFENSE_ORDER.STUDENT_ID))) .leftJoin(SCORE_TYPE) .on(DEFENSE_ORDER.SCORE_TYPE_ID.eq(SCORE_TYPE.SCORE_TYPE_ID)) .join(STAFF) .on(GRADUATION_DESIGN_TEACHER.STAFF_ID.eq(STAFF.STAFF_ID)) .leftJoin(ACADEMIC_TITLE) .on(STAFF.ACADEMIC_TITLE_ID.eq(ACADEMIC_TITLE.ACADEMIC_TITLE_ID)) .join(GRADUATION_DESIGN_DECLARE) .on(GRADUATION_DESIGN_PRESUBJECT.GRADUATION_DESIGN_PRESUBJECT_ID.eq(GRADUATION_DESIGN_DECLARE.GRADUATION_DESIGN_PRESUBJECT_ID)) .leftJoin(GRADUATION_DESIGN_SUBJECT_TYPE) .on(GRADUATION_DESIGN_DECLARE.SUBJECT_TYPE_ID.eq(GRADUATION_DESIGN_SUBJECT_TYPE.SUBJECT_TYPE_ID)) .leftJoin(GRADUATION_DESIGN_SUBJECT_ORIGIN_TYPE) .on(GRADUATION_DESIGN_DECLARE.ORIGIN_TYPE_ID.eq(GRADUATION_DESIGN_SUBJECT_ORIGIN_TYPE.ORIGIN_TYPE_ID)) .leftJoin(GRADUATION_DESIGN_ARCHIVES) .on(GRADUATION_DESIGN_PRESUBJECT.GRADUATION_DESIGN_PRESUBJECT_ID.eq(GRADUATION_DESIGN_ARCHIVES.GRADUATION_DESIGN_PRESUBJECT_ID)) .join(GRADUATION_DESIGN_DECLARE_DATA) .on(GRADUATION_DESIGN_PRESUBJECT.GRADUATION_DESIGN_RELEASE_ID.eq(GRADUATION_DESIGN_DECLARE_DATA.GRADUATION_DESIGN_RELEASE_ID)) .join(GRADUATION_DESIGN_RELEASE) .on(GRADUATION_DESIGN_PRESUBJECT.GRADUATION_DESIGN_RELEASE_ID.eq(GRADUATION_DESIGN_RELEASE.GRADUATION_DESIGN_RELEASE_ID)) .join(SCIENCE) .on(GRADUATION_DESIGN_RELEASE.SCIENCE_ID.eq(SCIENCE.SCIENCE_ID)) .join(DEPARTMENT) .on(SCIENCE.DEPARTMENT_ID.eq(DEPARTMENT.DEPARTMENT_ID)) .join(COLLEGE) .on(DEPARTMENT.COLLEGE_ID.eq(COLLEGE.COLLEGE_ID)) selectJoinStep.fetch() } else { val selectConditionStep = create.select() .from(GRADUATION_DESIGN_TEACHER) .join(GRADUATION_DESIGN_TUTOR) .on(GRADUATION_DESIGN_TEACHER.GRADUATION_DESIGN_TEACHER_ID.eq(GRADUATION_DESIGN_TUTOR.GRADUATION_DESIGN_TEACHER_ID)) .join(GRADUATION_DESIGN_PRESUBJECT) .on(GRADUATION_DESIGN_TUTOR.STUDENT_ID.eq(GRADUATION_DESIGN_PRESUBJECT.STUDENT_ID).and(GRADUATION_DESIGN_PRESUBJECT.GRADUATION_DESIGN_RELEASE_ID.eq(graduationDesignArchivesBean.graduationDesignReleaseId))) .join(DEFENSE_ARRANGEMENT) .on(DEFENSE_ARRANGEMENT.GRADUATION_DESIGN_RELEASE_ID.eq(GRADUATION_DESIGN_TEACHER.GRADUATION_DESIGN_RELEASE_ID)) .join(DEFENSE_GROUP) .on(DEFENSE_GROUP.DEFENSE_ARRANGEMENT_ID.eq(DEFENSE_ARRANGEMENT.DEFENSE_ARRANGEMENT_ID)) .join(DEFENSE_ORDER) .on(DEFENSE_ORDER.DEFENSE_GROUP_ID.eq(DEFENSE_GROUP.DEFENSE_GROUP_ID).and(GRADUATION_DESIGN_TUTOR.STUDENT_ID.eq(DEFENSE_ORDER.STUDENT_ID))) .leftJoin(SCORE_TYPE) .on(DEFENSE_ORDER.SCORE_TYPE_ID.eq(SCORE_TYPE.SCORE_TYPE_ID)) .join(STAFF) .on(GRADUATION_DESIGN_TEACHER.STAFF_ID.eq(STAFF.STAFF_ID)) .leftJoin(ACADEMIC_TITLE) .on(STAFF.ACADEMIC_TITLE_ID.eq(ACADEMIC_TITLE.ACADEMIC_TITLE_ID)) .join(GRADUATION_DESIGN_DECLARE) .on(GRADUATION_DESIGN_PRESUBJECT.GRADUATION_DESIGN_PRESUBJECT_ID.eq(GRADUATION_DESIGN_DECLARE.GRADUATION_DESIGN_PRESUBJECT_ID)) .leftJoin(GRADUATION_DESIGN_SUBJECT_TYPE) .on(GRADUATION_DESIGN_DECLARE.SUBJECT_TYPE_ID.eq(GRADUATION_DESIGN_SUBJECT_TYPE.SUBJECT_TYPE_ID)) .leftJoin(GRADUATION_DESIGN_SUBJECT_ORIGIN_TYPE) .on(GRADUATION_DESIGN_DECLARE.ORIGIN_TYPE_ID.eq(GRADUATION_DESIGN_SUBJECT_ORIGIN_TYPE.ORIGIN_TYPE_ID)) .leftJoin(GRADUATION_DESIGN_ARCHIVES) .on(GRADUATION_DESIGN_PRESUBJECT.GRADUATION_DESIGN_PRESUBJECT_ID.eq(GRADUATION_DESIGN_ARCHIVES.GRADUATION_DESIGN_PRESUBJECT_ID)) .join(GRADUATION_DESIGN_DECLARE_DATA) .on(GRADUATION_DESIGN_PRESUBJECT.GRADUATION_DESIGN_RELEASE_ID.eq(GRADUATION_DESIGN_DECLARE_DATA.GRADUATION_DESIGN_RELEASE_ID)) .join(GRADUATION_DESIGN_RELEASE) .on(GRADUATION_DESIGN_PRESUBJECT.GRADUATION_DESIGN_RELEASE_ID.eq(GRADUATION_DESIGN_RELEASE.GRADUATION_DESIGN_RELEASE_ID)) .join(SCIENCE) .on(GRADUATION_DESIGN_RELEASE.SCIENCE_ID.eq(SCIENCE.SCIENCE_ID)) .join(DEPARTMENT) .on(SCIENCE.DEPARTMENT_ID.eq(DEPARTMENT.DEPARTMENT_ID)) .join(COLLEGE) .on(DEPARTMENT.COLLEGE_ID.eq(COLLEGE.COLLEGE_ID)) .where(a) selectConditionStep.fetch() } buildData(records, graduationDesignArchivesBeans) return graduationDesignArchivesBeans } @Transactional(propagation = Propagation.REQUIRED, readOnly = false) override fun saveAndIgnore(graduationDesignArchives: GraduationDesignArchives) { create.insertInto(GRADUATION_DESIGN_ARCHIVES, GRADUATION_DESIGN_ARCHIVES.GRADUATION_DESIGN_PRESUBJECT_ID, GRADUATION_DESIGN_ARCHIVES.IS_EXCELLENT, GRADUATION_DESIGN_ARCHIVES.ARCHIVE_NUMBER, GRADUATION_DESIGN_ARCHIVES.NOTE) .values(graduationDesignArchives.graduationDesignPresubjectId, graduationDesignArchives.isExcellent, graduationDesignArchives.archiveNumber, graduationDesignArchives.note) .onDuplicateKeyIgnore() .execute() } @Transactional(propagation = Propagation.REQUIRED, readOnly = false) override fun save(graduationDesignArchives: GraduationDesignArchives) { create.insertInto(GRADUATION_DESIGN_ARCHIVES) .set(GRADUATION_DESIGN_ARCHIVES.GRADUATION_DESIGN_PRESUBJECT_ID, graduationDesignArchives.graduationDesignPresubjectId) .set(GRADUATION_DESIGN_ARCHIVES.ARCHIVE_NUMBER, graduationDesignArchives.archiveNumber) .set(GRADUATION_DESIGN_ARCHIVES.IS_EXCELLENT, graduationDesignArchives.isExcellent) .set(GRADUATION_DESIGN_ARCHIVES.NOTE, graduationDesignArchives.note) .execute() } override fun update(graduationDesignArchives: GraduationDesignArchives) { create.update(GRADUATION_DESIGN_ARCHIVES) .set(GRADUATION_DESIGN_ARCHIVES.IS_EXCELLENT, graduationDesignArchives.isExcellent) .set(GRADUATION_DESIGN_ARCHIVES.NOTE, graduationDesignArchives.note) .set(GRADUATION_DESIGN_ARCHIVES.ARCHIVE_NUMBER, graduationDesignArchives.archiveNumber) .where(GRADUATION_DESIGN_ARCHIVES.GRADUATION_DESIGN_PRESUBJECT_ID.eq(graduationDesignArchives.graduationDesignPresubjectId)) .execute() } /** * 其它条件 * * @param graduateArchivesBean 条件 * @return 条件 */ fun otherCondition(a: Condition?, graduateArchivesBean: GraduationDesignArchivesBean): Condition? { var tempCondition = a if (!ObjectUtils.isEmpty(graduateArchivesBean)) { if (StringUtils.hasLength(graduateArchivesBean.graduationDesignReleaseId)) { tempCondition = if (!ObjectUtils.isEmpty(tempCondition)) { tempCondition!!.and(GRADUATION_DESIGN_TEACHER.GRADUATION_DESIGN_RELEASE_ID.eq(graduateArchivesBean.graduationDesignReleaseId)) } else { GRADUATION_DESIGN_TEACHER.GRADUATION_DESIGN_RELEASE_ID.eq(graduateArchivesBean.graduationDesignReleaseId) } } } return tempCondition } private fun buildData(records: Result<Record>, graduateArchivesBeans: MutableList<GraduationDesignArchivesBean>) { for (r in records) { val graduateArchivesBean = GraduationDesignArchivesBean() graduateArchivesBean.graduationDesignReleaseId = r.getValue(GRADUATION_DESIGN_RELEASE.GRADUATION_DESIGN_RELEASE_ID) graduateArchivesBean.collegeName = r.getValue(COLLEGE.COLLEGE_NAME) graduateArchivesBean.collegeCode = r.getValue(COLLEGE.COLLEGE_CODE) graduateArchivesBean.scienceName = r.getValue(SCIENCE.SCIENCE_NAME) graduateArchivesBean.scienceCode = r.getValue(SCIENCE.SCIENCE_CODE) graduateArchivesBean.graduationDate = r.getValue(GRADUATION_DESIGN_DECLARE_DATA.GRADUATION_DATE) graduateArchivesBean.staffName = r.getValue(GRADUATION_DESIGN_TEACHER.STAFF_REAL_NAME) graduateArchivesBean.staffNumber = r.getValue(STAFF.STAFF_NUMBER) graduateArchivesBean.academicTitleName = r.getValue(ACADEMIC_TITLE.ACADEMIC_TITLE_NAME) graduateArchivesBean.assistantTeacher = r.getValue(GRADUATION_DESIGN_DECLARE.ASSISTANT_TEACHER) graduateArchivesBean.assistantTeacherAcademic = r.getValue(GRADUATION_DESIGN_DECLARE.ASSISTANT_TEACHER_ACADEMIC) graduateArchivesBean.assistantTeacherNumber = r.getValue(GRADUATION_DESIGN_DECLARE.ASSISTANT_TEACHER_NUMBER) graduateArchivesBean.presubjectTitle = r.getValue(GRADUATION_DESIGN_PRESUBJECT.PRESUBJECT_TITLE) graduateArchivesBean.subjectTypeName = r.getValue(GRADUATION_DESIGN_SUBJECT_TYPE.SUBJECT_TYPE_NAME) graduateArchivesBean.originTypeName = r.getValue(GRADUATION_DESIGN_SUBJECT_ORIGIN_TYPE.ORIGIN_TYPE_NAME) graduateArchivesBean.studentName = r.getValue(DEFENSE_ORDER.STUDENT_NAME) graduateArchivesBean.studentNumber = r.getValue(DEFENSE_ORDER.STUDENT_NUMBER) graduateArchivesBean.scoreTypeName = r.getValue(SCORE_TYPE.SCORE_TYPE_NAME) graduateArchivesBean.graduationDesignPresubjectId = r.getValue(GRADUATION_DESIGN_PRESUBJECT.GRADUATION_DESIGN_PRESUBJECT_ID) graduateArchivesBean.isExcellent = r.getValue(GRADUATION_DESIGN_ARCHIVES.IS_EXCELLENT) graduateArchivesBean.archiveNumber = r.getValue(GRADUATION_DESIGN_ARCHIVES.ARCHIVE_NUMBER) graduateArchivesBean.note = r.getValue(GRADUATION_DESIGN_ARCHIVES.NOTE) graduateArchivesBeans.add(graduateArchivesBean) } } /** * 数据全局搜索条件 * * @param dataTablesUtils datatables工具类 * @return 搜索条件 */ override fun searchCondition(dataTablesUtils: DataTablesUtils<GraduationDesignArchivesBean>): Condition? { var a: Condition? = null val search = dataTablesUtils.search if (!ObjectUtils.isEmpty(search)) { val studentName = StringUtils.trimWhitespace(search!!.getString("studentName")) val studentNumber = StringUtils.trimWhitespace(search.getString("studentNumber")) val staffName = StringUtils.trimWhitespace(search.getString("staffName")) val staffNumber = StringUtils.trimWhitespace(search.getString("staffNumber")) if (StringUtils.hasLength(studentName)) { a = DEFENSE_ORDER.STUDENT_NAME.like(SQLQueryUtils.likeAllParam(studentName)) } if (StringUtils.hasLength(studentNumber)) { a = if (ObjectUtils.isEmpty(a)) { DEFENSE_ORDER.STUDENT_NUMBER.like(SQLQueryUtils.likeAllParam(studentNumber)) } else { a!!.and(DEFENSE_ORDER.STUDENT_NUMBER.like(SQLQueryUtils.likeAllParam(studentNumber))) } } if (StringUtils.hasLength(staffName)) { a = if (ObjectUtils.isEmpty(a)) { GRADUATION_DESIGN_TEACHER.STAFF_REAL_NAME.like(SQLQueryUtils.likeAllParam(staffName)) } else { a!!.and(GRADUATION_DESIGN_TEACHER.STAFF_REAL_NAME.like(SQLQueryUtils.likeAllParam(staffName))) } } if (StringUtils.hasLength(staffNumber)) { a = if (ObjectUtils.isEmpty(a)) { STAFF.STAFF_NUMBER.like(SQLQueryUtils.likeAllParam(staffNumber)) } else { a!!.and(STAFF.STAFF_NUMBER.like(SQLQueryUtils.likeAllParam(staffNumber))) } } } return a } /** * 数据排序 * * @param dataTablesUtils datatables工具类 * @param selectConditionStep 条件 */ override fun sortCondition(dataTablesUtils: DataTablesUtils<GraduationDesignArchivesBean>, selectConditionStep: SelectConditionStep<Record>?, selectJoinStep: SelectJoinStep<Record>?, type: Int) { val orderColumnName = dataTablesUtils.orderColumnName val orderDir = dataTablesUtils.orderDir val isAsc = "asc".equals(orderDir, ignoreCase = true) var sortField: Array<SortField<*>?>? = null if (StringUtils.hasLength(orderColumnName)) { if ("college_name".equals(orderColumnName!!, ignoreCase = true)) { sortField = arrayOfNulls(2) if (isAsc) { sortField[0] = COLLEGE.COLLEGE_NAME.asc() sortField[1] = DEFENSE_ORDER.DEFENSE_ORDER_ID.asc() } else { sortField[0] = COLLEGE.COLLEGE_NAME.desc() sortField[1] = DEFENSE_ORDER.DEFENSE_ORDER_ID.desc() } } if ("college_code".equals(orderColumnName, ignoreCase = true)) { sortField = arrayOfNulls(2) if (isAsc) { sortField[0] = COLLEGE.COLLEGE_CODE.asc() sortField[1] = DEFENSE_ORDER.DEFENSE_ORDER_ID.asc() } else { sortField[0] = COLLEGE.COLLEGE_CODE.desc() sortField[1] = DEFENSE_ORDER.DEFENSE_ORDER_ID.desc() } } if ("science_name".equals(orderColumnName, ignoreCase = true)) { sortField = arrayOfNulls(2) if (isAsc) { sortField[0] = SCIENCE.SCIENCE_NAME.asc() sortField[1] = DEFENSE_ORDER.DEFENSE_ORDER_ID.asc() } else { sortField[0] = SCIENCE.SCIENCE_NAME.desc() sortField[1] = DEFENSE_ORDER.DEFENSE_ORDER_ID.desc() } } if ("science_code".equals(orderColumnName, ignoreCase = true)) { sortField = arrayOfNulls(2) if (isAsc) { sortField[0] = SCIENCE.SCIENCE_CODE.asc() sortField[1] = DEFENSE_ORDER.DEFENSE_ORDER_ID.asc() } else { sortField[0] = SCIENCE.SCIENCE_CODE.desc() sortField[1] = DEFENSE_ORDER.DEFENSE_ORDER_ID.desc() } } if ("graduation_date".equals(orderColumnName, ignoreCase = true)) { sortField = arrayOfNulls(2) if (isAsc) { sortField[0] = GRADUATION_DESIGN_DECLARE_DATA.GRADUATION_DATE.asc() sortField[1] = DEFENSE_ORDER.DEFENSE_ORDER_ID.asc() } else { sortField[0] = GRADUATION_DESIGN_DECLARE_DATA.GRADUATION_DATE.desc() sortField[1] = DEFENSE_ORDER.DEFENSE_ORDER_ID.desc() } } if ("staff_name".equals(orderColumnName, ignoreCase = true)) { sortField = arrayOfNulls(2) if (isAsc) { sortField[0] = GRADUATION_DESIGN_TEACHER.STAFF_REAL_NAME.asc() sortField[1] = DEFENSE_ORDER.DEFENSE_ORDER_ID.asc() } else { sortField[0] = GRADUATION_DESIGN_TEACHER.STAFF_REAL_NAME.desc() sortField[1] = DEFENSE_ORDER.DEFENSE_ORDER_ID.desc() } } if ("staff_number".equals(orderColumnName, ignoreCase = true)) { sortField = arrayOfNulls(2) if (isAsc) { sortField[0] = STAFF.STAFF_NUMBER.asc() sortField[1] = DEFENSE_ORDER.DEFENSE_ORDER_ID.asc() } else { sortField[0] = STAFF.STAFF_NUMBER.desc() sortField[1] = DEFENSE_ORDER.DEFENSE_ORDER_ID.desc() } } if ("academic_title_name".equals(orderColumnName, ignoreCase = true)) { sortField = arrayOfNulls(2) if (isAsc) { sortField[0] = ACADEMIC_TITLE.ACADEMIC_TITLE_NAME.asc() sortField[1] = DEFENSE_ORDER.DEFENSE_ORDER_ID.asc() } else { sortField[0] = ACADEMIC_TITLE.ACADEMIC_TITLE_NAME.desc() sortField[1] = DEFENSE_ORDER.DEFENSE_ORDER_ID.desc() } } if ("assistant_teacher".equals(orderColumnName, ignoreCase = true)) { sortField = arrayOfNulls(2) if (isAsc) { sortField[0] = GRADUATION_DESIGN_DECLARE.ASSISTANT_TEACHER.asc() sortField[1] = DEFENSE_ORDER.DEFENSE_ORDER_ID.asc() } else { sortField[0] = GRADUATION_DESIGN_DECLARE.ASSISTANT_TEACHER.desc() sortField[1] = DEFENSE_ORDER.DEFENSE_ORDER_ID.desc() } } if ("assistant_teacher_number".equals(orderColumnName, ignoreCase = true)) { sortField = arrayOfNulls(2) if (isAsc) { sortField[0] = GRADUATION_DESIGN_DECLARE.ASSISTANT_TEACHER_NUMBER.asc() sortField[1] = DEFENSE_ORDER.DEFENSE_ORDER_ID.asc() } else { sortField[0] = GRADUATION_DESIGN_DECLARE.ASSISTANT_TEACHER_NUMBER.desc() sortField[1] = DEFENSE_ORDER.DEFENSE_ORDER_ID.desc() } } if ("assistant_teacher_academic".equals(orderColumnName, ignoreCase = true)) { sortField = arrayOfNulls(2) if (isAsc) { sortField[0] = GRADUATION_DESIGN_DECLARE.ASSISTANT_TEACHER_ACADEMIC.asc() sortField[1] = DEFENSE_ORDER.DEFENSE_ORDER_ID.asc() } else { sortField[0] = GRADUATION_DESIGN_DECLARE.ASSISTANT_TEACHER_ACADEMIC.desc() sortField[1] = DEFENSE_ORDER.DEFENSE_ORDER_ID.desc() } } if ("presubject_title".equals(orderColumnName, ignoreCase = true)) { sortField = arrayOfNulls(2) if (isAsc) { sortField[0] = GRADUATION_DESIGN_PRESUBJECT.PRESUBJECT_TITLE.asc() sortField[1] = DEFENSE_ORDER.DEFENSE_ORDER_ID.asc() } else { sortField[0] = GRADUATION_DESIGN_PRESUBJECT.PRESUBJECT_TITLE.desc() sortField[1] = DEFENSE_ORDER.DEFENSE_ORDER_ID.desc() } } if ("subject_type_name".equals(orderColumnName, ignoreCase = true)) { sortField = arrayOfNulls(2) if (isAsc) { sortField[0] = GRADUATION_DESIGN_SUBJECT_TYPE.SUBJECT_TYPE_NAME.asc() sortField[1] = DEFENSE_ORDER.DEFENSE_ORDER_ID.asc() } else { sortField[0] = GRADUATION_DESIGN_SUBJECT_TYPE.SUBJECT_TYPE_NAME.desc() sortField[1] = DEFENSE_ORDER.DEFENSE_ORDER_ID.desc() } } if ("origin_type_name".equals(orderColumnName, ignoreCase = true)) { sortField = arrayOfNulls(2) if (isAsc) { sortField[0] = GRADUATION_DESIGN_SUBJECT_ORIGIN_TYPE.ORIGIN_TYPE_NAME.asc() sortField[1] = DEFENSE_ORDER.DEFENSE_ORDER_ID.asc() } else { sortField[0] = GRADUATION_DESIGN_SUBJECT_ORIGIN_TYPE.ORIGIN_TYPE_NAME.desc() sortField[1] = DEFENSE_ORDER.DEFENSE_ORDER_ID.desc() } } if ("student_number".equals(orderColumnName, ignoreCase = true)) { sortField = arrayOfNulls(1) if (isAsc) { sortField[0] = DEFENSE_ORDER.STUDENT_NUMBER.asc() } else { sortField[0] = DEFENSE_ORDER.STUDENT_NUMBER.desc() } } if ("student_name".equals(orderColumnName, ignoreCase = true)) { sortField = arrayOfNulls(2) if (isAsc) { sortField[0] = DEFENSE_ORDER.STUDENT_NAME.asc() sortField[1] = DEFENSE_ORDER.DEFENSE_ORDER_ID.asc() } else { sortField[0] = DEFENSE_ORDER.STUDENT_NAME.desc() sortField[1] = DEFENSE_ORDER.DEFENSE_ORDER_ID.desc() } } if ("score_type_name".equals(orderColumnName, ignoreCase = true)) { sortField = arrayOfNulls(2) if (isAsc) { sortField[0] = SCORE_TYPE.SCORE_TYPE_NAME.asc() sortField[1] = DEFENSE_ORDER.DEFENSE_ORDER_ID.asc() } else { sortField[0] = SCORE_TYPE.SCORE_TYPE_NAME.desc() sortField[1] = DEFENSE_ORDER.DEFENSE_ORDER_ID.desc() } } if ("is_excellent".equals(orderColumnName, ignoreCase = true)) { sortField = arrayOfNulls(2) if (isAsc) { sortField[0] = GRADUATION_DESIGN_ARCHIVES.IS_EXCELLENT.asc() sortField[1] = DEFENSE_ORDER.DEFENSE_ORDER_ID.asc() } else { sortField[0] = GRADUATION_DESIGN_ARCHIVES.IS_EXCELLENT.desc() sortField[1] = DEFENSE_ORDER.DEFENSE_ORDER_ID.desc() } } if ("archive_number".equals(orderColumnName, ignoreCase = true)) { sortField = arrayOfNulls(1) if (isAsc) { sortField[0] = GRADUATION_DESIGN_ARCHIVES.ARCHIVE_NUMBER.asc() } else { sortField[0] = GRADUATION_DESIGN_ARCHIVES.ARCHIVE_NUMBER.desc() } } if ("note".equals(orderColumnName, ignoreCase = true)) { sortField = arrayOfNulls(2) if (isAsc) { sortField[0] = GRADUATION_DESIGN_ARCHIVES.NOTE.asc() sortField[1] = DEFENSE_ORDER.DEFENSE_ORDER_ID.asc() } else { sortField[0] = GRADUATION_DESIGN_ARCHIVES.NOTE.desc() sortField[1] = DEFENSE_ORDER.DEFENSE_ORDER_ID.desc() } } } sortToFinish(selectConditionStep, selectJoinStep, type, *sortField!!) } }
mit
0b2faabd7bbee5da7cbaabb8d8c76d37
60.145333
225
0.612914
4.261896
false
false
false
false
BreakOutEvent/breakout-backend
src/main/java/backend/model/payment/TeamEntryFeeInvoice.kt
1
1937
package backend.model.payment import backend.exceptions.DomainException import backend.model.event.Team import org.javamoney.moneta.Money import javax.persistence.Entity import javax.persistence.FetchType.LAZY import javax.persistence.OneToOne @Entity class TeamEntryFeeInvoice : Invoice { @OneToOne(fetch = LAZY) var team: Team? = null private constructor() : super() constructor(team: Team, amount: Money) : super(amount) { this.team = team this.team!!.invoice = this } override fun checkPaymentEligability(payment: Payment) { val isAdminOrSepa = payment is AdminPayment || payment is SepaPayment if (exeedsTotalAmount(payment)) throw DomainException("This payment is not eligable because the total necessary amount of $amount would be exeeded") if (!isAdminOrSepa) throw DomainException("Currently only payments via admins or sepa can be added to team invoices") } private fun exeedsTotalAmount(payment: Payment): Boolean { val after = payment.amount.add(this.amountOfCurrentPayments()) return after > this.amount } private fun isFullAmount(money: Money): Boolean { return money.isEqualTo(amount) } override fun generatePurposeOfTransfer(): String { val teamId = this.team?.id ?: throw DomainException("Can't generate purposeOfTransfer for unsaved team without id") val eventId = this.team?.event?.id ?: throw DomainException("Can't generate purposeOfTransfer for team without event") val invoiceId = this.id ?: throw DomainException("Can't generate purposeOfTransfer for unsaved invoice without id") this.purposeOfTransferCode = generateRandomPurposeOfTransferCode() this.purposeOfTransfer = "$purposeOfTransferCode-BREAKOUT$eventId-TEAM$teamId-INVOICE$invoiceId-ENTRYFREE" return this.purposeOfTransfer!! } }
agpl-3.0
e4284316d3eedb9b77a842857e739f43
36.980392
156
0.713474
4.65625
false
false
false
false
google/intellij-community
plugins/kotlin/j2k/post-processing/src/org/jetbrains/kotlin/idea/j2k/post/processing/postProcessing/processings/diagnosticBasedProcessings.kt
2
4661
// 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.j2k.post.processing.postProcessing.processings import com.intellij.psi.PsiElement import com.intellij.psi.search.LocalSearchScope import com.intellij.psi.search.searches.ReferencesSearch import org.jetbrains.kotlin.diagnostics.DiagnosticWithParameters2 import org.jetbrains.kotlin.diagnostics.Errors import org.jetbrains.kotlin.idea.caches.resolve.analyze import org.jetbrains.kotlin.idea.intentions.branchedTransformations.isNullExpression import org.jetbrains.kotlin.idea.quickfix.NumberConversionFix import org.jetbrains.kotlin.idea.quickfix.RemoveUselessCastFix import org.jetbrains.kotlin.idea.references.mainReference import org.jetbrains.kotlin.idea.j2k.post.processing.postProcessing.diagnosticBasedProcessing import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode import org.jetbrains.kotlin.types.KotlinType import org.jetbrains.kotlin.types.isNullable import org.jetbrains.kotlin.types.typeUtil.isNothing import org.jetbrains.kotlin.types.typeUtil.isSignedOrUnsignedNumberType import org.jetbrains.kotlin.types.typeUtil.isSubtypeOf import org.jetbrains.kotlin.types.typeUtil.makeNotNullable internal val fixValToVarDiagnosticBasedProcessing = diagnosticBasedProcessing( Errors.VAL_REASSIGNMENT, Errors.CAPTURED_VAL_INITIALIZATION, Errors.CAPTURED_MEMBER_VAL_INITIALIZATION ) { element: KtSimpleNameExpression, _ -> val property = element.mainReference.resolve() as? KtProperty ?: return@diagnosticBasedProcessing if (!property.isVar) { property.valOrVarKeyword.replace(KtPsiFactory(element.project).createVarKeyword()) } } internal val fixTypeMismatchDiagnosticBasedProcessing = diagnosticBasedProcessing(Errors.TYPE_MISMATCH) { element: PsiElement, diagnostic -> @Suppress("UNCHECKED_CAST") val diagnosticWithParameters = diagnostic as? DiagnosticWithParameters2<KtExpression, KotlinType, KotlinType> ?: return@diagnosticBasedProcessing val expectedType = diagnosticWithParameters.a val realType = diagnosticWithParameters.b when { realType.makeNotNullable().isSubtypeOf(expectedType.makeNotNullable()) && realType.isNullable() && !expectedType.isNullable() -> { val factory = KtPsiFactory(element) element.replace(factory.createExpressionByPattern("($0)!!", element.text)) } element is KtExpression && realType.isSignedOrUnsignedNumberType() && expectedType.isSignedOrUnsignedNumberType() -> { val fix = NumberConversionFix(element, realType, expectedType, disableIfAvailable = null) fix.invoke(element.project, null, element.containingFile) } element is KtLambdaExpression && expectedType.isNothing() -> { for (valueParameter in element.valueParameters) { valueParameter.typeReference?.delete() valueParameter.colon?.delete() } } } } internal val removeUselessCastDiagnosticBasedProcessing = diagnosticBasedProcessing<KtBinaryExpressionWithTypeRHS>(Errors.USELESS_CAST) { element, _ -> if (element.left.isNullExpression()) return@diagnosticBasedProcessing val expression = RemoveUselessCastFix.invoke(element) val variable = expression.parent as? KtProperty if (variable != null && expression == variable.initializer && variable.isLocal) { val ref = ReferencesSearch.search(variable, LocalSearchScope(variable.containingFile)).findAll().singleOrNull() if (ref != null && ref.element is KtSimpleNameExpression) { ref.element.replace(expression) variable.delete() } } } internal val removeUnnecessaryNotNullAssertionDiagnosticBasedProcessing = diagnosticBasedProcessing<KtSimpleNameExpression>(Errors.UNNECESSARY_NOT_NULL_ASSERTION) { element, _ -> val exclExclExpr = element.parent as KtUnaryExpression val baseExpression = exclExclExpr.baseExpression ?: return@diagnosticBasedProcessing val context = baseExpression.analyze(BodyResolveMode.PARTIAL_WITH_DIAGNOSTICS) if (context.diagnostics.forElement(element).any { it.factory == Errors.UNNECESSARY_NOT_NULL_ASSERTION }) { exclExclExpr.replace(baseExpression) } }
apache-2.0
fd14723bcb63ce6235e6d4de7268947d
50.8
123
0.720017
5.278596
false
false
false
false
breandan/idear
src/main/java/com/darkprograms/speech/recognizer/vad/AbstractVAD.kt
2
6924
package com.darkprograms.speech.recognizer.vad import com.darkprograms.speech.microphone.* import java.io.* import javax.sound.sampled.AudioInputStream abstract class AbstractVAD : VoiceActivityDetector, Runnable { protected lateinit var audio: AudioInputStream var mic: MicrophoneAnalyzer? = null private var listener: VoiceActivityListener? = null private var state: VoiceActivityDetector.VadState = VoiceActivityDetector.VadState.INITIALISING private var thread: Thread? = null private var maxSpeechMs: Int = 0 private var maxSpeechWindows: Int = 0 var silenceCount: Int = 0 var speechCount: Int = 0 private var offset: Int = 0 private var bufferSize: Int = 0 private var outBuffer: ByteArrayOutputStream? = null // TODO: optionally provide PipedInputStream to support streaming recogntion on Google override fun detectVoiceActivity(mic: MicrophoneAnalyzer, listener: VoiceActivityListener) { detectVoiceActivity(mic, MAX_SPEECH_MILLIS, listener) } /** Initialise the VAD and start a thread */ override fun detectVoiceActivity(mic: MicrophoneAnalyzer, maxSpeechMs: Int, listener: VoiceActivityListener) { this.listener = listener this.maxSpeechMs = maxSpeechMs maxSpeechWindows = maxSpeechMs / WINDOW_MILLIS state = VoiceActivityDetector.VadState.LISTENING if (this.mic != null) { if (this.mic === mic) { // re-open the same mic if (mic.state == Microphone.CaptureState.CLOSED) { mic.open() } return } else { // swap mics this.audio = mic.captureAudioToStream() this.mic!!.close() } } else { this.audio = mic.captureAudioToStream() } this.mic = mic if (thread == null || !thread!!.isAlive) { thread = Thread(this, "JARVIS-VAD") thread!!.start() } } override fun pause() { state = VoiceActivityDetector.VadState.PAUSED mic!!.close() } override fun setVoiceActivityListener(listener: VoiceActivityListener) { this.listener = listener } override fun terminate() { state = VoiceActivityDetector.VadState.CLOSED mic!!.close() thread!!.interrupt() } /** * Continuously reads "windows" of audio into a buffer and delegates to [.sampleForSpeech] * and [.incrementSpeechCounter]. * [.emitVoiceActivity] will be called when an utterance has been captured. */ override fun run() { val bytesToRead = mic!!.getNumOfBytes(WINDOW_SECONDS) val audioData = ByteArray(bytesToRead) bufferSize = maxSpeechMs * this.mic!!.getNumOfBytes(0.001) silenceCount = 0 speechCount = 0 offset = 0 outBuffer = ByteArrayOutputStream(bufferSize) state = VoiceActivityDetector.VadState.LISTENING while (state !== VoiceActivityDetector.VadState.CLOSED) { try { val bytesRead = this.audio.read(audioData, 0, bytesToRead) if (bytesRead > 0) { val speechDetected = sampleForSpeech(audioData) incrementSpeechCounter(speechDetected, bytesRead, audioData) } } catch (e: Exception) { e.printStackTrace() state = VoiceActivityDetector.VadState.CLOSED return } } } /** * Executed from within the VAD thread * @param audioData * @return */ protected abstract fun sampleForSpeech(audioData: ByteArray): Boolean protected fun incrementSpeechCounter(speechDetected: Boolean, bytesRead: Int, audioData: ByteArray) { var updatedBytesRead = bytesRead if (speechDetected) { speechCount++ // Ignore speech runs less than 5 successive frames. if (state !== VoiceActivityDetector.VadState.DETECTED_SPEECH && speechCount >= IGNORE_SPEECH_WINDOWS) { state = VoiceActivityDetector.VadState.DETECTED_SPEECH silenceCount = 0 } if (offset + updatedBytesRead < bufferSize) { outBuffer!!.write(audioData, 0, updatedBytesRead) offset += updatedBytesRead if (speechCount >= maxSpeechWindows) { println("in theory, this should be handled by the following end of buffer handler") emitVoiceActivity(outBuffer) } } else { println("Reached the end of the buffer! Send what we've captured so far") updatedBytesRead = bufferSize - offset outBuffer!!.write(audioData, 0, updatedBytesRead) emitVoiceActivity(outBuffer) } } else { // silence silenceCount++ // Ignore silence runs less than 10 successive frames. if (state === VoiceActivityDetector.VadState.DETECTED_SPEECH && silenceCount >= IGNORE_SILENCE_WINDOWS) { if (silenceCount >= MAX_SILENCE_WINDOWS && speechCount >= MIN_SPEECH_WINDOWS) { println("We have silence after a chunk of speech worth processing") emitVoiceActivity(outBuffer) } else { state = VoiceActivityDetector.VadState.DETECTED_SILENCE_AFTER_SPEECH } speechCount = 0 } } } protected fun emitVoiceActivity(outBuffer: ByteArrayOutputStream?) { listener!!.onVoiceActivity(createVoiceActivityStream(outBuffer)) outBuffer!!.reset() offset = 0 state = VoiceActivityDetector.VadState.LISTENING } protected fun createVoiceActivityStream(outBuffer: ByteArrayOutputStream?): AudioInputStream { println("speech: " + mic!!.audioFormat.frameSize * mic!!.getNumOfFrames(outBuffer!!.size())) return AudioInputStream(ByteArrayInputStream(outBuffer.toByteArray()), audio.format, mic!!.getNumOfFrames(outBuffer.size()).toLong()) } companion object { private val WINDOW_MILLIS = 16 private val IGNORE_SILENCE_WINDOWS = 10 private val IGNORE_SPEECH_WINDOWS = 5 /** maximum ms between words */ private val MAX_SILENCE_MILLIS = 4 /** minimum duration of speech to recognise */ private val MIN_SPEECH_MILLIS = 200 private val WINDOW_SECONDS = WINDOW_MILLIS.toDouble() / 1000 /** Google does not allow recordings over 1 minute, but 10 seconds should be ample */ private val MAX_SPEECH_MILLIS = 10000 private val MAX_SILENCE_WINDOWS = MAX_SILENCE_MILLIS / WINDOW_MILLIS private val MIN_SPEECH_WINDOWS = MIN_SPEECH_MILLIS / WINDOW_MILLIS } }
apache-2.0
173afa92671d7c323fcedcc729dd9256
36.836066
141
0.61684
4.795014
false
false
false
false
google/intellij-community
platform/util-ex/src/com/intellij/util/Plow.kt
1
3943
// 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.util import com.intellij.openapi.progress.ProgressManager import com.intellij.util.containers.ContainerUtil /** * A Processor + Flow, or the Poor man's Flow: a reactive-stream-like wrapper around [Processor]. * * Instead of creating the [Processor] manually - create a [Plow] and work with the Processor inside a lambda. * If your method accepts the processor it is the good idea to return a [Plow] instead to avoid the "return value in parameter" semantic * * Itself [Plow] is stateless and ["Cold"](https://projectreactor.io/docs/core/3.3.9.RELEASE/reference/index.html#reactor.hotCold), * meaning that the same instance of [Plow] could be reused several times (by reevaluating the sources), * but depending on the idempotence of the [producingFunction] this contract could be violated, * so to be careful, and it is better to obtain the new [Plow] instance each time. */ class Plow<T> private constructor(private val producingFunction: (Processor<T>) -> Boolean) { @Suppress("UNCHECKED_CAST") fun processWith(processor: Processor<in T>): Boolean = producingFunction(processor as Processor<T>) fun <P : Processor<T>> processTo(processor: P): P = processor.apply { producingFunction(this) } fun findAny(): T? = processTo(CommonProcessors.FindFirstProcessor()).foundValue fun find(test: (T) -> Boolean): T? = processTo(object : CommonProcessors.FindFirstProcessor<T>() { override fun accept(t: T): Boolean = test(t) }).foundValue fun <C : MutableCollection<T>> collectTo(coll: C): C = coll.apply { processTo(CommonProcessors.CollectProcessor(this)) } fun toList(): List<T> = ContainerUtil.unmodifiableOrEmptyList(collectTo(SmartList())) fun toSet(): Set<T> = ContainerUtil.unmodifiableOrEmptySet(collectTo(HashSet())) fun toArray(array: Array<T>): Array<T> = processTo(CommonProcessors.CollectProcessor()).toArray(array) fun <R> transform(transformation: (Processor<R>) -> (Processor<T>)): Plow<R> = Plow { pr -> producingFunction(transformation(pr)) } fun <R> map(mapping: (T) -> R): Plow<R> = transform { pr -> Processor { v -> pr.process(mapping(v)) } } fun <R> mapNotNull(mapping: (T) -> R?): Plow<R> = transform { pr -> Processor { v -> mapping(v)?.let { pr.process(it) } ?: true } } fun filter(test: (T) -> Boolean): Plow<T> = transform { pr -> Processor { v -> !test(v) || pr.process(v) } } fun <R> mapToProcessor(mapping: (T, Processor<R>) -> Boolean): Plow<R> = Plow { rProcessor -> producingFunction(Processor { t -> mapping(t, rProcessor) }) } fun <R> flatMap(mapping: (T) -> Plow<R>): Plow<R> = mapToProcessor { t, processor -> mapping(t).processWith(processor) } fun <R> flatMapSeq(mapping: (T) -> Sequence<R>): Plow<R> = mapToProcessor { t, processor -> mapping(t).all { processor.process(it) } } fun cancellable(): Plow<T> = transform { pr -> Processor { v -> ProgressManager.checkCanceled();pr.process(v) } } fun limit(n: Int): Plow<T> { var processedCount = 0 return transform { pr -> Processor { processedCount++ processedCount <= n && pr.process(it) } } } companion object { @JvmStatic fun <T> empty(): Plow<T> = of { true } @JvmStatic fun <T> of(processorCall: (Processor<T>) -> Boolean): Plow<T> = Plow(processorCall) @JvmStatic @JvmName("ofArray") fun <T> Array<T>.toPlow(): Plow<T> = Plow { pr -> all { pr.process(it) } } @JvmStatic @JvmName("ofIterable") fun <T> Iterable<T>.toPlow(): Plow<T> = Plow { pr -> all { pr.process(it) } } @JvmStatic @JvmName("ofSequence") fun <T> Sequence<T>.toPlow(): Plow<T> = Plow { pr -> all { pr.process(it) } } @JvmStatic fun <T> concat(vararg plows: Plow<T>): Plow<T> = of { pr -> plows.all { it.processWith(pr) } } } }
apache-2.0
3116a569e86c3e3e6322733a90ac976a
42.340659
140
0.670555
3.627415
false
false
false
false
google/intellij-community
plugins/kotlin/base/project-structure/src/org/jetbrains/kotlin/idea/base/projectStructure/moduleInfo/NotUnderContentRootModuleInfo.kt
4
1809
// 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.base.projectStructure.moduleInfo import com.intellij.openapi.project.Project import com.intellij.psi.search.GlobalSearchScope import org.jetbrains.kotlin.analyzer.NonSourceModuleInfoBase import org.jetbrains.kotlin.idea.base.projectStructure.KotlinBaseProjectStructureBundle import org.jetbrains.kotlin.idea.base.projectStructure.compositeAnalysis.findAnalyzerServices import org.jetbrains.kotlin.name.Name import org.jetbrains.kotlin.platform.TargetPlatform import org.jetbrains.kotlin.platform.jvm.JvmPlatforms import org.jetbrains.kotlin.resolve.PlatformDependentAnalyzerServices import org.jetbrains.kotlin.idea.caches.project.NotUnderContentRootModuleInfo as OldNotUnderContentRootModuleInfo object NotUnderContentRootModuleInfo : OldNotUnderContentRootModuleInfo(), IdeaModuleInfo, NonSourceModuleInfoBase { override val moduleOrigin: ModuleOrigin get() = ModuleOrigin.OTHER override val name: Name = Name.special("<special module for files not under source root>") override val displayedName: String get() = KotlinBaseProjectStructureBundle.message("special.module.for.files.not.under.source.root") override val project: Project? get() = null override val contentScope: GlobalSearchScope get() = GlobalSearchScope.EMPTY_SCOPE //TODO: (module refactoring) dependency on runtime can be of use here override fun dependencies(): List<IdeaModuleInfo> = listOf(this) override val platform: TargetPlatform get() = JvmPlatforms.defaultJvmPlatform override val analyzerServices: PlatformDependentAnalyzerServices get() = platform.single().findAnalyzerServices() }
apache-2.0
748367d4ea25580e92caba3f086a0a70
46.631579
120
0.804312
5.081461
false
false
false
false
JetBrains/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/callableBuilder/CallableBuilder.kt
1
63090
// 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.quickfix.createFromUsage.callableBuilder import com.intellij.codeInsight.daemon.impl.quickfix.CreateFromUsageUtils import com.intellij.codeInsight.intention.preview.IntentionPreviewUtils import com.intellij.codeInsight.navigation.NavigationUtil import com.intellij.codeInsight.template.* import com.intellij.codeInsight.template.impl.TemplateImpl import com.intellij.codeInsight.template.impl.TemplateManagerImpl import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.application.runWriteAction import com.intellij.openapi.editor.Editor import com.intellij.openapi.editor.ScrollType import com.intellij.openapi.fileEditor.FileEditorManager import com.intellij.openapi.fileEditor.OpenFileDescriptor import com.intellij.openapi.ui.DialogWrapper import com.intellij.openapi.util.UnfairTextRange import com.intellij.psi.* import com.intellij.psi.codeStyle.CodeStyleManager import com.intellij.psi.codeStyle.JavaCodeStyleManager import com.intellij.psi.util.PsiTreeUtil import org.jetbrains.kotlin.builtins.KotlinBuiltIns import org.jetbrains.kotlin.builtins.functions.FunctionClassDescriptor import org.jetbrains.kotlin.cfg.pseudocode.Pseudocode import org.jetbrains.kotlin.cfg.pseudocode.getContainingPseudocode import org.jetbrains.kotlin.descriptors.* import org.jetbrains.kotlin.descriptors.annotations.Annotations import org.jetbrains.kotlin.descriptors.impl.MutablePackageFragmentDescriptor import org.jetbrains.kotlin.descriptors.impl.SimpleFunctionDescriptorImpl import org.jetbrains.kotlin.descriptors.impl.TypeParameterDescriptorImpl import org.jetbrains.kotlin.idea.FrontendInternals import org.jetbrains.kotlin.idea.base.fe10.codeInsight.newDeclaration.Fe10KotlinNameSuggester import org.jetbrains.kotlin.idea.base.psi.copied import org.jetbrains.kotlin.idea.base.psi.isMultiLine import org.jetbrains.kotlin.idea.base.psi.replaced import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.caches.resolve.analyzeWithAllCompilerChecks import org.jetbrains.kotlin.idea.caches.resolve.analyzeWithContent import org.jetbrains.kotlin.idea.caches.resolve.getResolutionFacade import org.jetbrains.kotlin.idea.caches.resolve.resolveToDescriptorIfAny import org.jetbrains.kotlin.idea.caches.resolve.util.getJavaClassDescriptor import org.jetbrains.kotlin.idea.core.* import org.jetbrains.kotlin.idea.imports.importableFqName import org.jetbrains.kotlin.idea.quickfix.createFromUsage.createClass.ClassKind import org.jetbrains.kotlin.idea.refactoring.* import org.jetbrains.kotlin.idea.resolve.frontendService import org.jetbrains.kotlin.idea.util.DialogWithEditor import org.jetbrains.kotlin.idea.util.IdeDescriptorRenderers import org.jetbrains.kotlin.idea.util.application.executeWriteCommand import org.jetbrains.kotlin.idea.util.application.isUnitTestMode import org.jetbrains.kotlin.idea.util.application.withPsiAttachment import org.jetbrains.kotlin.idea.util.getDefaultInitializer import org.jetbrains.kotlin.incremental.components.NoLookupLocation import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.load.java.descriptors.JavaClassDescriptor import org.jetbrains.kotlin.name.FqName import org.jetbrains.kotlin.name.Name import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.* import org.jetbrains.kotlin.psi.typeRefHelpers.setReceiverTypeReference import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.DescriptorToSourceUtils import org.jetbrains.kotlin.resolve.descriptorUtil.getSuperClassOrAny import org.jetbrains.kotlin.resolve.scopes.HierarchicalScope import org.jetbrains.kotlin.resolve.scopes.LexicalScopeImpl import org.jetbrains.kotlin.resolve.scopes.LexicalScopeKind import org.jetbrains.kotlin.resolve.scopes.utils.findClassifier import org.jetbrains.kotlin.resolve.scopes.utils.memberScopeAsImportingScope import org.jetbrains.kotlin.types.KotlinType import org.jetbrains.kotlin.types.TypeProjectionImpl import org.jetbrains.kotlin.types.TypeUtils import org.jetbrains.kotlin.types.Variance import org.jetbrains.kotlin.types.checker.KotlinTypeChecker import org.jetbrains.kotlin.types.typeUtil.isAnyOrNullableAny import org.jetbrains.kotlin.types.typeUtil.isSubtypeOf import org.jetbrains.kotlin.types.typeUtil.isUnit import org.jetbrains.kotlin.types.typeUtil.makeNullable import org.jetbrains.kotlin.utils.KotlinExceptionWithAttachments import org.jetbrains.kotlin.utils.addToStdlib.firstIsInstanceOrNull import java.util.* import kotlin.math.max /** * Represents a single choice for a type (e.g. parameter type or return type). */ class TypeCandidate(val theType: KotlinType, scope: HierarchicalScope? = null) { val typeParameters: Array<TypeParameterDescriptor> var renderedTypes: List<String> = emptyList() private set var renderedTypeParameters: List<RenderedTypeParameter>? = null private set fun render(typeParameterNameMap: Map<TypeParameterDescriptor, String>, fakeFunction: FunctionDescriptor?) { renderedTypes = theType.renderShort(typeParameterNameMap) renderedTypeParameters = typeParameters.map { RenderedTypeParameter(it, it.containingDeclaration == fakeFunction, typeParameterNameMap.getValue(it)) } } init { val typeParametersInType = theType.getTypeParameters() if (scope == null) { typeParameters = typeParametersInType.toTypedArray() renderedTypes = theType.renderShort(Collections.emptyMap()) } else { typeParameters = getTypeParameterNamesNotInScope(typeParametersInType, scope).toTypedArray() } } override fun toString() = theType.toString() } data class RenderedTypeParameter( val typeParameter: TypeParameterDescriptor, val fake: Boolean, val text: String ) fun List<TypeCandidate>.getTypeByRenderedType(renderedTypes: List<String>): KotlinType? = firstOrNull { it.renderedTypes == renderedTypes }?.theType class CallableBuilderConfiguration( val callableInfos: List<CallableInfo>, val originalElement: KtElement, val currentFile: KtFile = originalElement.containingKtFile, val currentEditor: Editor? = null, val isExtension: Boolean = false, val enableSubstitutions: Boolean = true ) sealed class CallablePlacement { class WithReceiver(val receiverTypeCandidate: TypeCandidate) : CallablePlacement() class NoReceiver(val containingElement: PsiElement) : CallablePlacement() } class CallableBuilder(val config: CallableBuilderConfiguration) { private var finished: Boolean = false val currentFileContext = config.currentFile.analyzeWithContent() private lateinit var _currentFileModule: ModuleDescriptor val currentFileModule: ModuleDescriptor get() { if (!_currentFileModule.isValid) { updateCurrentModule() } return _currentFileModule } init { updateCurrentModule() } val pseudocode: Pseudocode? by lazy { config.originalElement.getContainingPseudocode(currentFileContext) } private val typeCandidates = HashMap<TypeInfo, List<TypeCandidate>>() var placement: CallablePlacement? = null private val elementsToShorten = ArrayList<KtElement>() private fun updateCurrentModule() { _currentFileModule = config.currentFile.analyzeWithAllCompilerChecks().moduleDescriptor } fun computeTypeCandidates(typeInfo: TypeInfo): List<TypeCandidate> = typeCandidates.getOrPut(typeInfo) { typeInfo.getPossibleTypes(this).map { TypeCandidate(it) } } private fun computeTypeCandidates( typeInfo: TypeInfo, substitutions: List<KotlinTypeSubstitution>, scope: HierarchicalScope ): List<TypeCandidate> { if (!typeInfo.substitutionsAllowed) return computeTypeCandidates(typeInfo) return typeCandidates.getOrPut(typeInfo) { val types = typeInfo.getPossibleTypes(this).asReversed() // We have to use semantic equality here data class EqWrapper(val _type: KotlinType) { override fun equals(other: Any?) = this === other || other is EqWrapper && KotlinTypeChecker.DEFAULT.equalTypes(_type, other._type) override fun hashCode() = 0 // no good way to compute hashCode() that would agree with our equals() } val newTypes = LinkedHashSet(types.map(::EqWrapper)) for (substitution in substitutions) { // each substitution can be applied or not, so we offer all options val toAdd = newTypes.map { it._type.substitute(substitution, typeInfo.variance) } // substitution.byType are type arguments, but they cannot already occur in the type before substitution val toRemove = newTypes.filter { substitution.byType in it._type } newTypes.addAll(toAdd.map(::EqWrapper)) newTypes.removeAll(toRemove) } if (newTypes.isEmpty()) { newTypes.add(EqWrapper(currentFileModule.builtIns.anyType)) } newTypes.map { TypeCandidate(it._type, scope) }.asReversed() } } private fun buildNext(iterator: Iterator<CallableInfo>) { if (iterator.hasNext()) { val context = Context(iterator.next()) val action: () -> Unit = { context.buildAndRunTemplate { buildNext(iterator) } } if (IntentionPreviewUtils.isPreviewElement(config.currentFile)) { action() } else { runWriteAction(action) ApplicationManager.getApplication().invokeLater { context.showDialogIfNeeded() } } } else { val action: () -> Unit = { ShortenReferences.DEFAULT.process(elementsToShorten) } if (IntentionPreviewUtils.isPreviewElement(config.currentFile)) { action() } else { runWriteAction(action) } } } fun build(onFinish: () -> Unit = {}) { try { assert(config.currentEditor != null) { "Can't run build() without editor" } check(!finished) { "Current builder has already finished" } buildNext(config.callableInfos.iterator()) } finally { finished = true onFinish() } } private inner class Context(val callableInfo: CallableInfo) { val skipReturnType: Boolean val ktFileToEdit: KtFile val containingFileEditor: Editor val containingElement: PsiElement val dialogWithEditor: DialogWithEditor? val receiverClassDescriptor: ClassifierDescriptor? val typeParameterNameMap: Map<TypeParameterDescriptor, String> val receiverTypeCandidate: TypeCandidate? val mandatoryTypeParametersAsCandidates: List<TypeCandidate> val substitutions: List<KotlinTypeSubstitution> var finished: Boolean = false init { // gather relevant information val placement = placement var nullableReceiver = false when (placement) { is CallablePlacement.NoReceiver -> { containingElement = placement.containingElement receiverClassDescriptor = with(placement.containingElement) { when (this) { is KtClassOrObject -> currentFileContext[BindingContext.CLASS, this] is PsiClass -> getJavaClassDescriptor() else -> null } } } is CallablePlacement.WithReceiver -> { val theType = placement.receiverTypeCandidate.theType nullableReceiver = theType.isMarkedNullable receiverClassDescriptor = theType.constructor.declarationDescriptor val classDeclaration = receiverClassDescriptor?.let { DescriptorToSourceUtils.getSourceFromDescriptor(it) } containingElement = if (!config.isExtension && classDeclaration != null) classDeclaration else config.currentFile } else -> throw IllegalArgumentException("Placement wan't initialized") } val receiverType = receiverClassDescriptor?.defaultType?.let { if (nullableReceiver) it.makeNullable() else it } val project = config.currentFile.project if (containingElement.containingFile != config.currentFile) { NavigationUtil.activateFileWithPsiElement(containingElement) } dialogWithEditor = if (containingElement is KtElement) { ktFileToEdit = containingElement.containingKtFile containingFileEditor = if (ktFileToEdit != config.currentFile) { FileEditorManager.getInstance(project).selectedTextEditor!! } else { config.currentEditor!! } null } else { val dialog = object : DialogWithEditor(project, KotlinBundle.message("fix.create.from.usage.dialog.title"), "") { override fun doOKAction() { project.executeWriteCommand(KotlinBundle.message("premature.end.of.template")) { TemplateManagerImpl.getTemplateState(editor)?.gotoEnd(false) } super.doOKAction() } } containingFileEditor = dialog.editor with(containingFileEditor.settings) { additionalColumnsCount = config.currentEditor!!.settings.getRightMargin(project) additionalLinesCount = 5 } ktFileToEdit = PsiDocumentManager.getInstance(project).getPsiFile(containingFileEditor.document) as KtFile ktFileToEdit.analysisContext = config.currentFile dialog } val scope = getDeclarationScope() receiverTypeCandidate = receiverType?.let { TypeCandidate(it, scope) } val fakeFunction: FunctionDescriptor? // figure out type substitutions for type parameters val substitutionMap = LinkedHashMap<KotlinType, KotlinType>() if (config.enableSubstitutions) { collectSubstitutionsForReceiverTypeParameters(receiverType, substitutionMap) val typeArgumentsForFakeFunction = callableInfo.typeParameterInfos .map { val typeCandidates = computeTypeCandidates(it) assert(typeCandidates.size == 1) { "Ambiguous type candidates for type parameter $it: $typeCandidates" } typeCandidates.first().theType } .subtract(substitutionMap.keys) fakeFunction = createFakeFunctionDescriptor(scope, typeArgumentsForFakeFunction.size) collectSubstitutionsForCallableTypeParameters(fakeFunction, typeArgumentsForFakeFunction, substitutionMap) mandatoryTypeParametersAsCandidates = listOfNotNull(receiverTypeCandidate) + typeArgumentsForFakeFunction.map { TypeCandidate(substitutionMap[it]!!, scope) } } else { fakeFunction = null mandatoryTypeParametersAsCandidates = Collections.emptyList() } substitutions = substitutionMap.map { KotlinTypeSubstitution(it.key, it.value) } callableInfo.parameterInfos.forEach { computeTypeCandidates(it.typeInfo, substitutions, scope) } val returnTypeCandidate = computeTypeCandidates(callableInfo.returnTypeInfo, substitutions, scope).singleOrNull() skipReturnType = when (callableInfo.kind) { CallableKind.FUNCTION -> returnTypeCandidate?.theType?.isUnit() ?: false CallableKind.CLASS_WITH_PRIMARY_CONSTRUCTOR -> callableInfo.returnTypeInfo == TypeInfo.Empty || returnTypeCandidate?.theType?.isAnyOrNullableAny() ?: false CallableKind.CONSTRUCTOR -> true CallableKind.PROPERTY -> containingElement is KtBlockExpression } // figure out type parameter renames to avoid conflicts typeParameterNameMap = getTypeParameterRenames(scope) callableInfo.parameterInfos.forEach { renderTypeCandidates(it.typeInfo, typeParameterNameMap, fakeFunction) } if (!skipReturnType) { renderTypeCandidates(callableInfo.returnTypeInfo, typeParameterNameMap, fakeFunction) } receiverTypeCandidate?.render(typeParameterNameMap, fakeFunction) mandatoryTypeParametersAsCandidates.forEach { it.render(typeParameterNameMap, fakeFunction) } } private fun getDeclarationScope(): HierarchicalScope { if (config.isExtension || receiverClassDescriptor == null) { return currentFileModule.getPackage(config.currentFile.packageFqName).memberScope.memberScopeAsImportingScope() } if (receiverClassDescriptor is ClassDescriptorWithResolutionScopes) { return receiverClassDescriptor.scopeForMemberDeclarationResolution } assert(receiverClassDescriptor is JavaClassDescriptor) { "Unexpected receiver class: $receiverClassDescriptor" } val projections = ((receiverClassDescriptor as JavaClassDescriptor).declaredTypeParameters) .map { TypeProjectionImpl(it.defaultType) } val memberScope = receiverClassDescriptor.getMemberScope(projections) return LexicalScopeImpl( memberScope.memberScopeAsImportingScope(), receiverClassDescriptor, false, null, emptyList(), LexicalScopeKind.SYNTHETIC ) { receiverClassDescriptor.typeConstructor.parameters.forEach { addClassifierDescriptor(it) } } } private fun collectSubstitutionsForReceiverTypeParameters( receiverType: KotlinType?, result: MutableMap<KotlinType, KotlinType> ) { if (placement is CallablePlacement.NoReceiver) return val classTypeParameters = receiverType?.arguments ?: Collections.emptyList() val ownerTypeArguments = (placement as? CallablePlacement.WithReceiver)?.receiverTypeCandidate?.theType?.arguments ?: Collections.emptyList() assert(ownerTypeArguments.size == classTypeParameters.size) ownerTypeArguments.zip(classTypeParameters).forEach { result[it.first.type] = it.second.type } } private fun collectSubstitutionsForCallableTypeParameters( fakeFunction: FunctionDescriptor, typeArguments: Set<KotlinType>, result: MutableMap<KotlinType, KotlinType> ) { for ((typeArgument, typeParameter) in typeArguments.zip(fakeFunction.typeParameters)) { result[typeArgument] = typeParameter.defaultType } } @OptIn(FrontendInternals::class) private fun createFakeFunctionDescriptor(scope: HierarchicalScope, typeParameterCount: Int): FunctionDescriptor { val fakeFunction = SimpleFunctionDescriptorImpl.create( MutablePackageFragmentDescriptor(currentFileModule, FqName("fake")), Annotations.EMPTY, Name.identifier("fake"), CallableMemberDescriptor.Kind.SYNTHESIZED, SourceElement.NO_SOURCE ) val validator = CollectingNameValidator { scope.findClassifier(Name.identifier(it), NoLookupLocation.FROM_IDE) == null } val parameterNames = Fe10KotlinNameSuggester.suggestNamesForTypeParameters(typeParameterCount, validator) val typeParameters = (0 until typeParameterCount).map { TypeParameterDescriptorImpl.createWithDefaultBound( fakeFunction, Annotations.EMPTY, false, Variance.INVARIANT, Name.identifier(parameterNames[it]), it, ktFileToEdit.getResolutionFacade().frontendService() ) } return fakeFunction.initialize( null, null, emptyList(), typeParameters, Collections.emptyList(), null, null, DescriptorVisibilities.INTERNAL ) } private fun renderTypeCandidates( typeInfo: TypeInfo, typeParameterNameMap: Map<TypeParameterDescriptor, String>, fakeFunction: FunctionDescriptor? ) { typeCandidates[typeInfo]?.forEach { it.render(typeParameterNameMap, fakeFunction) } } private fun isInsideInnerOrLocalClass(): Boolean { val classOrObject = containingElement.getNonStrictParentOfType<KtClassOrObject>() return classOrObject is KtClass && (classOrObject.isInner() || classOrObject.isLocal) } private fun createDeclarationSkeleton(): KtNamedDeclaration { with(config) { val assignmentToReplace = if (containingElement is KtBlockExpression && (callableInfo as? PropertyInfo)?.writable == true) { originalElement as KtBinaryExpression } else null val pointerOfAssignmentToReplace = assignmentToReplace?.createSmartPointer() val ownerTypeString = if (isExtension) { val renderedType = receiverTypeCandidate!!.renderedTypes.first() val isFunctionType = receiverTypeCandidate.theType.constructor.declarationDescriptor is FunctionClassDescriptor if (isFunctionType) "($renderedType)." else "$renderedType." } else "" val classKind = (callableInfo as? ClassWithPrimaryConstructorInfo)?.classInfo?.kind fun renderParamList(): String { val prefix = if (classKind == ClassKind.ANNOTATION_CLASS) "val " else "" val list = callableInfo.parameterInfos.indices.joinToString(", ") { i -> "${prefix}p$i: Any" } return if (callableInfo.parameterInfos.isNotEmpty() || callableInfo.kind == CallableKind.FUNCTION || callableInfo.kind == CallableKind.CONSTRUCTOR ) "($list)" else list } val paramList = when (callableInfo.kind) { CallableKind.FUNCTION, CallableKind.CLASS_WITH_PRIMARY_CONSTRUCTOR, CallableKind.CONSTRUCTOR -> renderParamList() CallableKind.PROPERTY -> "" } val returnTypeString = if (skipReturnType || assignmentToReplace != null) "" else ": Any" val header = "$ownerTypeString${callableInfo.name.quoteIfNeeded()}$paramList$returnTypeString" val psiFactory = KtPsiFactory(currentFile.project) val modifiers = buildString { val modifierList = callableInfo.modifierList?.copied() ?: psiFactory.createEmptyModifierList() val visibilityKeyword = modifierList.visibilityModifierType() if (visibilityKeyword == null) { val defaultVisibility = if (callableInfo.isAbstract) "" else if (containingElement is KtClassOrObject && !(containingElement is KtClass && containingElement.isInterface()) && containingElement.isAncestor(config.originalElement) && callableInfo.kind != CallableKind.CONSTRUCTOR ) "private " else if (isExtension) "private " else "" append(defaultVisibility) } // TODO: Get rid of isAbstract if (callableInfo.isAbstract && containingElement is KtClass && !containingElement.isInterface() && !modifierList.hasModifier(KtTokens.ABSTRACT_KEYWORD) ) { modifierList.appendModifier(KtTokens.ABSTRACT_KEYWORD) } val text = modifierList.normalize().text if (text.isNotEmpty()) { append("$text ") } } val isExpectClassMember by lazy { containingElement is KtClassOrObject && containingElement.resolveToDescriptorIfAny()?.isExpect ?: false } val declaration: KtNamedDeclaration = when (callableInfo.kind) { CallableKind.FUNCTION, CallableKind.CONSTRUCTOR -> { val body = when { callableInfo is ConstructorInfo -> if (callableInfo.withBody) "{\n\n}" else "" callableInfo.isAbstract -> "" containingElement is KtClass && containingElement.hasModifier(KtTokens.EXTERNAL_KEYWORD) -> "" containingElement is KtObjectDeclaration && containingElement.hasModifier(KtTokens.EXTERNAL_KEYWORD) -> "" containingElement is KtObjectDeclaration && containingElement.isCompanion() && containingElement.parent.parent is KtClass && (containingElement.parent.parent as KtClass).hasModifier(KtTokens.EXTERNAL_KEYWORD) -> "" isExpectClassMember -> "" else -> "{\n\n}" } @Suppress("USELESS_CAST") // KT-10755 when { callableInfo is FunctionInfo -> psiFactory.createFunction("${modifiers}fun<> $header $body") as KtNamedDeclaration (callableInfo as ConstructorInfo).isPrimary -> { val constructorText = if (modifiers.isNotEmpty()) "${modifiers}constructor$paramList" else paramList psiFactory.createPrimaryConstructor(constructorText) as KtNamedDeclaration } else -> psiFactory.createSecondaryConstructor("${modifiers}constructor$paramList $body") as KtNamedDeclaration } } CallableKind.CLASS_WITH_PRIMARY_CONSTRUCTOR -> { val classWithPrimaryConstructorInfo = callableInfo as ClassWithPrimaryConstructorInfo with(classWithPrimaryConstructorInfo.classInfo) { val classBody = when (kind) { ClassKind.ANNOTATION_CLASS, ClassKind.ENUM_ENTRY -> "" else -> "{\n\n}" } val safeName = name.quoteIfNeeded() when (kind) { ClassKind.ENUM_ENTRY -> { val targetParent = applicableParents.singleOrNull() if (!(targetParent is KtClass && targetParent.isEnum())) { throw KotlinExceptionWithAttachments("Enum class expected: ${targetParent?.let { it::class.java }}") .withPsiAttachment("targetParent", targetParent) } val hasParameters = targetParent.primaryConstructorParameters.isNotEmpty() psiFactory.createEnumEntry("$safeName${if (hasParameters) "()" else " "}") } else -> { val openMod = if (open && kind != ClassKind.INTERFACE) "open " else "" val innerMod = if (inner || isInsideInnerOrLocalClass()) "inner " else "" val typeParamList = when (kind) { ClassKind.PLAIN_CLASS, ClassKind.INTERFACE -> "<>" else -> "" } val ctor = classWithPrimaryConstructorInfo.primaryConstructorVisibility?.name?.let { " $it constructor" } ?: "" psiFactory.createDeclaration<KtClassOrObject>( "$openMod$innerMod${kind.keyword} $safeName$typeParamList$ctor$paramList$returnTypeString $classBody" ) } } } } CallableKind.PROPERTY -> { val isVar = (callableInfo as PropertyInfo).writable val const = if (callableInfo.isConst) "const " else "" val valVar = if (isVar) "var" else "val" val accessors = if (isExtension && !isExpectClassMember) { buildString { append("\nget() {}") if (isVar) { append("\nset() {}") } } } else "" psiFactory.createProperty("$modifiers$const$valVar<> $header$accessors") } } if (callableInfo is PropertyInfo) { callableInfo.annotations.forEach { declaration.addAnnotationEntry(it) } } if (callableInfo is ConstructorInfo) { callableInfo.annotations.forEach { declaration.addAnnotationEntry(it) } } val newInitializer = pointerOfAssignmentToReplace?.element if (newInitializer != null) { (declaration as KtProperty).initializer = newInitializer.right return newInitializer.replace(declaration) as KtCallableDeclaration } val container = if (containingElement is KtClass && callableInfo.isForCompanion) { containingElement.getOrCreateCompanionObject() } else containingElement val declarationInPlace = placeDeclarationInContainer(declaration, container, config.originalElement, ktFileToEdit) if (declarationInPlace is KtSecondaryConstructor) { val containingClass = declarationInPlace.containingClassOrObject!! val primaryConstructorParameters = containingClass.primaryConstructorParameters if (primaryConstructorParameters.isNotEmpty()) { declarationInPlace.replaceImplicitDelegationCallWithExplicit(true) } else if ((receiverClassDescriptor as ClassDescriptor).getSuperClassOrAny().constructors .all { it.valueParameters.isNotEmpty() } ) { declarationInPlace.replaceImplicitDelegationCallWithExplicit(false) } if (declarationInPlace.valueParameters.size > primaryConstructorParameters.size) { val hasCompatibleTypes = primaryConstructorParameters.zip(callableInfo.parameterInfos).all { (primary, secondary) -> val primaryType = currentFileContext[BindingContext.TYPE, primary.typeReference] ?: return@all false val secondaryType = computeTypeCandidates(secondary.typeInfo).firstOrNull()?.theType ?: return@all false secondaryType.isSubtypeOf(primaryType) } if (hasCompatibleTypes) { val delegationCallArgumentList = declarationInPlace.getDelegationCall().valueArgumentList primaryConstructorParameters.forEach { val name = it.name if (name != null) delegationCallArgumentList?.addArgument(psiFactory.createArgument(name)) } } } } return declarationInPlace } } private fun getTypeParameterRenames(scope: HierarchicalScope): Map<TypeParameterDescriptor, String> { val allTypeParametersNotInScope = LinkedHashSet<TypeParameterDescriptor>() mandatoryTypeParametersAsCandidates.asSequence() .plus(callableInfo.parameterInfos.asSequence().flatMap { typeCandidates[it.typeInfo]!!.asSequence() }) .flatMap { it.typeParameters.asSequence() } .toCollection(allTypeParametersNotInScope) if (!skipReturnType) { computeTypeCandidates(callableInfo.returnTypeInfo).asSequence().flatMapTo(allTypeParametersNotInScope) { it.typeParameters.asSequence() } } val validator = CollectingNameValidator { scope.findClassifier(Name.identifier(it), NoLookupLocation.FROM_IDE) == null } val typeParameterNames = allTypeParametersNotInScope.map { Fe10KotlinNameSuggester.suggestNameByName(it.name.asString(), validator) } return allTypeParametersNotInScope.zip(typeParameterNames).toMap() } private fun setupTypeReferencesForShortening( declaration: KtNamedDeclaration, parameterTypeExpressions: List<TypeExpression> ) { if (config.isExtension) { val receiverTypeText = receiverTypeCandidate!!.theType.renderLong(typeParameterNameMap).first() val replacingTypeRef = KtPsiFactory(declaration.project).createType(receiverTypeText) (declaration as KtCallableDeclaration).setReceiverTypeReference(replacingTypeRef)!! } val returnTypeRefs = declaration.getReturnTypeReferences() if (returnTypeRefs.isNotEmpty()) { val returnType = typeCandidates[callableInfo.returnTypeInfo]!!.getTypeByRenderedType( returnTypeRefs.map { it.text } ) if (returnType != null) { // user selected a given type replaceWithLongerName(returnTypeRefs, returnType) } } val valueParameters = declaration.getValueParameters() val parameterIndicesToShorten = ArrayList<Int>() assert(valueParameters.size == parameterTypeExpressions.size) for ((i, parameter) in valueParameters.asSequence().withIndex()) { val parameterTypeRef = parameter.typeReference if (parameterTypeRef != null) { val parameterType = parameterTypeExpressions[i].typeCandidates.getTypeByRenderedType( listOf(parameterTypeRef.text) ) if (parameterType != null) { replaceWithLongerName(listOf(parameterTypeRef), parameterType) parameterIndicesToShorten.add(i) } } } } private fun postprocessDeclaration(declaration: KtNamedDeclaration) { if (callableInfo is PropertyInfo && callableInfo.isLateinitPreferred) { if (declaration.containingClassOrObject == null) return val propertyDescriptor = declaration.resolveToDescriptorIfAny() as? PropertyDescriptor ?: return val returnType = propertyDescriptor.returnType ?: return if (TypeUtils.isNullableType(returnType) || KotlinBuiltIns.isPrimitiveType(returnType)) return declaration.addModifier(KtTokens.LATEINIT_KEYWORD) } if (callableInfo.isAbstract) { val containingClass = declaration.containingClassOrObject if (containingClass is KtClass && containingClass.isInterface()) { declaration.removeModifier(KtTokens.ABSTRACT_KEYWORD) } } } private fun setupDeclarationBody(func: KtDeclarationWithBody) { if (func !is KtNamedFunction && func !is KtPropertyAccessor) return if (skipReturnType && callableInfo is FunctionInfo && callableInfo.preferEmptyBody) return val oldBody = func.bodyExpression ?: return val bodyText = getFunctionBodyTextFromTemplate( func.project, TemplateKind.FUNCTION, if (callableInfo.name.isNotEmpty()) callableInfo.name else null, if (skipReturnType) "Unit" else (func as? KtFunction)?.typeReference?.text ?: "", receiverClassDescriptor?.importableFqName ?: receiverClassDescriptor?.name?.let { FqName.topLevel(it) } ) oldBody.replace(KtPsiFactory(func.project).createBlock(bodyText)) } private fun setupCallTypeArguments(callElement: KtCallElement, typeParameters: List<TypeParameterDescriptor>) { val oldTypeArgumentList = callElement.typeArgumentList ?: return val renderedTypeArgs = typeParameters.map { typeParameter -> val type = substitutions.first { it.byType.constructor.declarationDescriptor == typeParameter }.forType IdeDescriptorRenderers.SOURCE_CODE.renderType(type) } if (renderedTypeArgs.isEmpty()) { oldTypeArgumentList.delete() } else { val psiFactory = KtPsiFactory(callElement.project) oldTypeArgumentList.replace(psiFactory.createTypeArguments(renderedTypeArgs.joinToString(", ", "<", ">"))) elementsToShorten.add(callElement.typeArgumentList!!) } } private fun setupReturnTypeTemplate(builder: TemplateBuilder, declaration: KtNamedDeclaration): TypeExpression? { val candidates = typeCandidates[callableInfo.returnTypeInfo]!! if (candidates.isEmpty()) return null val elementToReplace: KtElement? val expression: TypeExpression = when (declaration) { is KtCallableDeclaration -> { elementToReplace = declaration.typeReference TypeExpression.ForTypeReference(candidates) } is KtClassOrObject -> { elementToReplace = declaration.superTypeListEntries.firstOrNull() TypeExpression.ForDelegationSpecifier(candidates) } else -> throw KotlinExceptionWithAttachments("Unexpected declaration kind: ${declaration::class.java}") .withPsiAttachment("declaration", declaration) } if (elementToReplace == null) return null if (candidates.size == 1) { builder.replaceElement(elementToReplace, (expression.calculateResult(null) as TextResult).text) return null } builder.replaceElement(elementToReplace, expression) return expression } private fun setupValVarTemplate(builder: TemplateBuilder, property: KtProperty) { if (!(callableInfo as PropertyInfo).writable) { builder.replaceElement(property.valOrVarKeyword, ValVarExpression) } } private fun setupTypeParameterListTemplate( builder: TemplateBuilderImpl, declaration: KtNamedDeclaration ): TypeParameterListExpression? { when (declaration) { is KtObjectDeclaration -> return null !is KtTypeParameterListOwner -> { throw KotlinExceptionWithAttachments("Unexpected declaration kind: ${declaration::class.java}") .withPsiAttachment("declaration", declaration) } } val typeParameterList = (declaration as KtTypeParameterListOwner).typeParameterList ?: return null val typeParameterMap = HashMap<String, List<RenderedTypeParameter>>() val mandatoryTypeParameters = ArrayList<RenderedTypeParameter>() //receiverTypeCandidate?.let { mandatoryTypeParameters.addAll(it.renderedTypeParameters!!) } mandatoryTypeParametersAsCandidates.asSequence().flatMapTo(mandatoryTypeParameters) { it.renderedTypeParameters!!.asSequence() } callableInfo.parameterInfos.asSequence() .flatMap { typeCandidates[it.typeInfo]!!.asSequence() } .forEach { typeParameterMap[it.renderedTypes.first()] = it.renderedTypeParameters!! } if (declaration.getReturnTypeReference() != null) { typeCandidates[callableInfo.returnTypeInfo]!!.forEach { typeParameterMap[it.renderedTypes.first()] = it.renderedTypeParameters!! } } val expression = TypeParameterListExpression( mandatoryTypeParameters, typeParameterMap, callableInfo.kind != CallableKind.CLASS_WITH_PRIMARY_CONSTRUCTOR ) val leftSpace = typeParameterList.prevSibling as? PsiWhiteSpace val rangeStart = leftSpace?.startOffset ?: typeParameterList.startOffset val offset = typeParameterList.startOffset val range = UnfairTextRange(rangeStart - offset, typeParameterList.endOffset - offset) builder.replaceElement(typeParameterList, range, "TYPE_PARAMETER_LIST", expression, false) return expression } private fun setupParameterTypeTemplates(builder: TemplateBuilder, parameterList: List<KtParameter>): List<TypeExpression> { assert(parameterList.size == callableInfo.parameterInfos.size) val typeParameters = ArrayList<TypeExpression>() for ((parameter, ktParameter) in callableInfo.parameterInfos.zip(parameterList)) { val parameterTypeExpression = TypeExpression.ForTypeReference(typeCandidates[parameter.typeInfo]!!) val parameterTypeRef = ktParameter.typeReference!! builder.replaceElement(parameterTypeRef, parameterTypeExpression) // add parameter name to the template val possibleNamesFromExpression = parameter.typeInfo.getPossibleNamesFromExpression(currentFileContext) val possibleNames = arrayOf(*parameter.nameSuggestions.toTypedArray(), *possibleNamesFromExpression) // figure out suggested names for each type option val parameterTypeToNamesMap = HashMap<String, Array<String>>() typeCandidates[parameter.typeInfo]!!.forEach { typeCandidate -> val suggestedNames = Fe10KotlinNameSuggester.suggestNamesByType(typeCandidate.theType, { true }) parameterTypeToNamesMap[typeCandidate.renderedTypes.first()] = suggestedNames.toTypedArray() } // add expression to builder val parameterNameExpression = ParameterNameExpression(possibleNames, parameterTypeToNamesMap) val parameterNameIdentifier = ktParameter.nameIdentifier!! builder.replaceElement(parameterNameIdentifier, parameterNameExpression) typeParameters.add(parameterTypeExpression) } return typeParameters } private fun replaceWithLongerName(typeRefs: List<KtTypeReference>, theType: KotlinType) { val psiFactory = KtPsiFactory(ktFileToEdit.project) val fullyQualifiedReceiverTypeRefs = theType.renderLong(typeParameterNameMap).map { psiFactory.createType(it) } (typeRefs zip fullyQualifiedReceiverTypeRefs).forEach { (shortRef, longRef) -> shortRef.replace(longRef) } } private fun transformToJavaMemberIfApplicable(declaration: KtNamedDeclaration): Boolean { fun convertToJava(targetClass: PsiClass): PsiMember? { val psiFactory = KtPsiFactory(declaration.project) psiFactory.createPackageDirectiveIfNeeded(config.currentFile.packageFqName)?.let { declaration.containingFile.addBefore(it, null) } val adjustedDeclaration = when (declaration) { is KtNamedFunction, is KtProperty -> { val klass = psiFactory.createClass("class Foo {}") klass.body!!.add(declaration) (declaration.replace(klass) as KtClass).body!!.declarations.first() } else -> declaration } return when (adjustedDeclaration) { is KtNamedFunction, is KtSecondaryConstructor -> { createJavaMethod(adjustedDeclaration as KtFunction, targetClass) } is KtProperty -> { createJavaField(adjustedDeclaration, targetClass) } is KtClass -> { createJavaClass(adjustedDeclaration, targetClass) } else -> null } } if (config.isExtension || receiverClassDescriptor !is JavaClassDescriptor) return false val targetClass = DescriptorToSourceUtils.getSourceFromDescriptor(receiverClassDescriptor) as? PsiClass if (targetClass == null || !targetClass.canRefactor()) return false val project = declaration.project val newJavaMember = convertToJava(targetClass) ?: return false val modifierList = newJavaMember.modifierList!! if (newJavaMember is PsiMethod || newJavaMember is PsiClass) { modifierList.setModifierProperty(PsiModifier.FINAL, false) } val needStatic = when (callableInfo) { is ClassWithPrimaryConstructorInfo -> with(callableInfo.classInfo) { !inner && kind != ClassKind.ENUM_ENTRY && kind != ClassKind.ENUM_CLASS } else -> callableInfo.receiverTypeInfo.staticContextRequired } modifierList.setModifierProperty(PsiModifier.STATIC, needStatic) JavaCodeStyleManager.getInstance(project).shortenClassReferences(newJavaMember) val descriptor = OpenFileDescriptor(project, targetClass.containingFile.virtualFile) val targetEditor = FileEditorManager.getInstance(project).openTextEditor(descriptor, true)!! targetEditor.selectionModel.removeSelection() when (newJavaMember) { is PsiMethod -> CreateFromUsageUtils.setupEditor(newJavaMember, targetEditor) is PsiField -> targetEditor.caretModel.moveToOffset(newJavaMember.endOffset - 1) is PsiClass -> { val constructor = newJavaMember.constructors.firstOrNull() val superStatement = constructor?.body?.statements?.firstOrNull() as? PsiExpressionStatement val superCall = superStatement?.expression as? PsiMethodCallExpression if (superCall != null) { val lParen = superCall.argumentList.firstChild targetEditor.caretModel.moveToOffset(lParen.endOffset) } else { targetEditor.caretModel.moveToOffset(newJavaMember.nameIdentifier?.startOffset ?: newJavaMember.startOffset) } } } targetEditor.scrollingModel.scrollToCaret(ScrollType.RELATIVE) return true } private fun setupEditor(declaration: KtNamedDeclaration) { if (declaration is KtProperty && !declaration.hasInitializer() && containingElement is KtBlockExpression) { val psiFactory = KtPsiFactory(declaration.project) val defaultValueType = typeCandidates[callableInfo.returnTypeInfo]!!.firstOrNull()?.theType val defaultValue = defaultValueType?.getDefaultInitializer() ?: "null" val initializer = declaration.setInitializer(psiFactory.createExpression(defaultValue))!! val range = initializer.textRange containingFileEditor.selectionModel.setSelection(range.startOffset, range.endOffset) containingFileEditor.caretModel.moveToOffset(range.endOffset) return } if (declaration is KtSecondaryConstructor && !declaration.hasImplicitDelegationCall()) { containingFileEditor.caretModel.moveToOffset(declaration.getDelegationCall().valueArgumentList!!.startOffset + 1) return } setupEditorSelection(containingFileEditor, declaration) } // build templates fun buildAndRunTemplate(onFinish: () -> Unit) { val declarationSkeleton = createDeclarationSkeleton() val project = declarationSkeleton.project val declarationPointer = SmartPointerManager.getInstance(project).createSmartPsiElementPointer(declarationSkeleton) // build templates val documentManager = PsiDocumentManager.getInstance(project) val document = containingFileEditor.document documentManager.commitDocument(document) documentManager.doPostponedOperationsAndUnblockDocument(document) val caretModel = containingFileEditor.caretModel caretModel.moveToOffset(ktFileToEdit.node.startOffset) val declaration = declarationPointer.element ?: return val declarationMarker = document.createRangeMarker(declaration.textRange) val builder = TemplateBuilderImpl(ktFileToEdit) if (declaration is KtProperty) { setupValVarTemplate(builder, declaration) } if (!skipReturnType) { setupReturnTypeTemplate(builder, declaration) } val parameterTypeExpressions = setupParameterTypeTemplates(builder, declaration.getValueParameters()) // add a segment for the parameter list // Note: because TemplateBuilderImpl does not have a replaceElement overload that takes in both a TextRange and alwaysStopAt, we // need to create the segment first and then hack the Expression into the template later. We use this template to update the type // parameter list as the user makes selections in the parameter types, and we need alwaysStopAt to be false so the user can't tab to // it. val expression = setupTypeParameterListTemplate(builder, declaration) documentManager.doPostponedOperationsAndUnblockDocument(document) // the template built by TemplateBuilderImpl is ordered by element position, but we want types to be first, so hack it val templateImpl = builder.buildInlineTemplate() as TemplateImpl val variables = templateImpl.variables!! if (variables.isNotEmpty()) { val typeParametersVar = if (expression != null) variables.removeAt(0) else null for (i in callableInfo.parameterInfos.indices) { Collections.swap(variables, i * 2, i * 2 + 1) } typeParametersVar?.let { variables.add(it) } } // TODO: Disabled shortening names because it causes some tests fail. Refactor code to use automatic reference shortening templateImpl.isToShortenLongNames = false // run the template TemplateManager.getInstance(project).startTemplate(containingFileEditor, templateImpl, object : TemplateEditingAdapter() { private fun finishTemplate(brokenOff: Boolean) { try { documentManager.commitDocument(document) dialogWithEditor?.close(DialogWrapper.OK_EXIT_CODE) if (brokenOff && !isUnitTestMode()) return // file templates val newDeclaration = PsiTreeUtil.findElementOfClassAtOffset( ktFileToEdit, declarationMarker.startOffset, declaration::class.java, false ) ?: return if (IntentionPreviewUtils.isPreviewElement(config.currentFile)) return runWriteAction { postprocessDeclaration(newDeclaration) // file templates if (newDeclaration is KtNamedFunction || newDeclaration is KtSecondaryConstructor) { setupDeclarationBody(newDeclaration as KtFunction) } if (newDeclaration is KtProperty) { newDeclaration.getter?.let { setupDeclarationBody(it) } if (callableInfo is PropertyInfo && callableInfo.initializer != null) { newDeclaration.initializer = callableInfo.initializer } } val callElement = config.originalElement as? KtCallElement if (callElement != null) { setupCallTypeArguments(callElement, expression?.currentTypeParameters ?: Collections.emptyList()) } CodeStyleManager.getInstance(project).reformat(newDeclaration) // change short type names to fully qualified ones (to be shortened below) if (newDeclaration.getValueParameters().size == parameterTypeExpressions.size) { setupTypeReferencesForShortening(newDeclaration, parameterTypeExpressions) } if (!transformToJavaMemberIfApplicable(newDeclaration)) { elementsToShorten.add(newDeclaration) setupEditor(newDeclaration) } } } finally { declarationMarker.dispose() finished = true onFinish() } } override fun templateCancelled(template: Template?) { finishTemplate(true) } override fun templateFinished(template: Template, brokenOff: Boolean) { finishTemplate(brokenOff) } }) } fun showDialogIfNeeded() { if (!isUnitTestMode() && dialogWithEditor != null && !finished) { dialogWithEditor.show() } } } } // TODO: Simplify and use formatter as much as possible @Suppress("UNCHECKED_CAST") internal fun <D : KtNamedDeclaration> placeDeclarationInContainer( declaration: D, container: PsiElement, anchor: PsiElement, fileToEdit: KtFile = container.containingFile as KtFile ): D { val psiFactory = KtPsiFactory(container.project) val newLine = psiFactory.createNewLine() fun calcNecessaryEmptyLines(decl: KtDeclaration, after: Boolean): Int { var lineBreaksPresent = 0 var neighbor: PsiElement? = null siblingsLoop@ for (sibling in decl.siblings(forward = after, withItself = false)) { when (sibling) { is PsiWhiteSpace -> lineBreaksPresent += (sibling.text ?: "").count { it == '\n' } else -> { neighbor = sibling break@siblingsLoop } } } val neighborType = neighbor?.node?.elementType val lineBreaksNeeded = when { neighborType == KtTokens.LBRACE || neighborType == KtTokens.RBRACE -> 1 neighbor is KtDeclaration && (neighbor !is KtProperty || decl !is KtProperty) -> 2 else -> 1 } return max(lineBreaksNeeded - lineBreaksPresent, 0) } val actualContainer = (container as? KtClassOrObject)?.getOrCreateBody() ?: container fun addDeclarationToClassOrObject( classOrObject: KtClassOrObject, declaration: KtNamedDeclaration ): KtNamedDeclaration { val classBody = classOrObject.getOrCreateBody() return if (declaration is KtNamedFunction) { val neighbor = PsiTreeUtil.skipSiblingsBackward( classBody.rBrace ?: classBody.lastChild!!, PsiWhiteSpace::class.java ) classBody.addAfter(declaration, neighbor) as KtNamedDeclaration } else classBody.addAfter(declaration, classBody.lBrace!!) as KtNamedDeclaration } fun addNextToOriginalElementContainer(addBefore: Boolean): D { val sibling = anchor.parentsWithSelf.first { it.parent == actualContainer } return if (addBefore || PsiTreeUtil.hasErrorElements(sibling)) { actualContainer.addBefore(declaration, sibling) } else { actualContainer.addAfter(declaration, sibling) } as D } val declarationInPlace = when { declaration is KtPrimaryConstructor -> { (container as KtClass).createPrimaryConstructorIfAbsent().replaced(declaration) } declaration is KtProperty && container !is KtBlockExpression -> { val sibling = actualContainer.getChildOfType<KtProperty>() ?: when (actualContainer) { is KtClassBody -> actualContainer.declarations.firstOrNull() ?: actualContainer.rBrace is KtFile -> actualContainer.declarations.first() else -> null } sibling?.let { actualContainer.addBefore(declaration, it) as D } ?: fileToEdit.add(declaration) as D } actualContainer.isAncestor(anchor, true) -> { val insertToBlock = container is KtBlockExpression if (insertToBlock) { val parent = container.parent if (parent is KtFunctionLiteral) { if (!parent.isMultiLine()) { parent.addBefore(newLine, container) parent.addAfter(newLine, container) } } } addNextToOriginalElementContainer(insertToBlock || declaration is KtTypeAlias) } container is KtFile -> container.add(declaration) as D container is PsiClass -> { if (declaration is KtSecondaryConstructor) { val wrappingClass = psiFactory.createClass("class ${container.name} {\n}") addDeclarationToClassOrObject(wrappingClass, declaration) (fileToEdit.add(wrappingClass) as KtClass).declarations.first() as D } else { fileToEdit.add(declaration) as D } } container is KtClassOrObject -> { var sibling: PsiElement? = container.declarations.lastOrNull { it::class == declaration::class } if (sibling == null && declaration is KtProperty) { sibling = container.body?.lBrace } insertMembersAfterAndReformat(null, container, declaration, sibling) } else -> throw KotlinExceptionWithAttachments("Invalid containing element: ${container::class.java}") .withPsiAttachment("container", container) } when (declaration) { is KtEnumEntry -> { val prevEnumEntry = declarationInPlace.siblings(forward = false, withItself = false).firstIsInstanceOrNull<KtEnumEntry>() if (prevEnumEntry != null) { if ((prevEnumEntry.prevSibling as? PsiWhiteSpace)?.text?.contains('\n') == true) { declarationInPlace.parent.addBefore(psiFactory.createNewLine(), declarationInPlace) } val comma = psiFactory.createComma() if (prevEnumEntry.allChildren.any { it.node.elementType == KtTokens.COMMA }) { declarationInPlace.add(comma) } else { prevEnumEntry.add(comma) } val semicolon = prevEnumEntry.allChildren.firstOrNull { it.node?.elementType == KtTokens.SEMICOLON } if (semicolon != null) { (semicolon.prevSibling as? PsiWhiteSpace)?.text?.let { declarationInPlace.add(psiFactory.createWhiteSpace(it)) } declarationInPlace.add(psiFactory.createSemicolon()) semicolon.delete() } } } !is KtPrimaryConstructor -> { val parent = declarationInPlace.parent calcNecessaryEmptyLines(declarationInPlace, false).let { if (it > 0) parent.addBefore(psiFactory.createNewLine(it), declarationInPlace) } calcNecessaryEmptyLines(declarationInPlace, true).let { if (it > 0) parent.addAfter(psiFactory.createNewLine(it), declarationInPlace) } } } return declarationInPlace } fun KtNamedDeclaration.getReturnTypeReference() = getReturnTypeReferences().singleOrNull() internal fun KtNamedDeclaration.getReturnTypeReferences(): List<KtTypeReference> { return when (this) { is KtCallableDeclaration -> listOfNotNull(typeReference) is KtClassOrObject -> superTypeListEntries.mapNotNull { it.typeReference } else -> throw AssertionError("Unexpected declaration kind: $text") } } fun CallableBuilderConfiguration.createBuilder(): CallableBuilder = CallableBuilder(this)
apache-2.0
732c4724ab963e17eb237c102044b8d3
49.593424
144
0.617752
6.500773
false
false
false
false
nielsutrecht/adventofcode
src/main/kotlin/com/nibado/projects/advent/y2019/Day04.kt
1
717
package com.nibado.projects.advent.y2019 import com.nibado.projects.advent.Day object Day04 : Day { private val range = (108457 .. 562041).map { it.toString().map {c -> c.toInt() } } private fun doesNotDecrease(password: List<Int>) = (0..4).none { password[it] > password[it + 1] } private fun hasSameTwo(password: List<Int>) = (0..4).any { password[it] == password[it + 1] } private fun hasGroupOfTwoB(password: List<Int>) = ('0'.toInt() .. '9'.toInt()).any { password.lastIndexOf(it) - password.indexOf(it) == 1 } override fun part1() = range.filter(::doesNotDecrease).filter(::hasSameTwo).count() override fun part2() = range.filter(::doesNotDecrease).filter(::hasGroupOfTwoB).count() }
mit
76fdf65b25f2cc01e32d6f0c42145aec
50.285714
143
0.672245
3.319444
false
false
false
false
allotria/intellij-community
plugins/ide-features-trainer/src/training/learn/lesson/general/GotoActionLesson.kt
2
5591
// 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 training.learn.lesson.general import com.intellij.ide.actions.AboutPopup import com.intellij.ide.actions.searcheverywhere.SearchEverywhereUI import com.intellij.ide.util.gotoByName.GotoActionModel import com.intellij.idea.ActionsBundle import com.intellij.openapi.editor.actions.ToggleShowLineNumbersGloballyAction import com.intellij.openapi.editor.ex.EditorSettingsExternalizable import com.intellij.openapi.editor.impl.EditorComponentImpl import com.intellij.openapi.util.SystemInfo import com.intellij.util.ui.UIUtil import org.fest.swing.driver.ComponentDriver import training.dsl.* import training.learn.LearnBundle import training.learn.LessonsBundle import training.learn.course.KLesson import java.awt.Component import java.awt.event.KeyEvent import javax.swing.JPanel class GotoActionLesson(private val sample: LessonSample, private val firstLesson: Boolean = false) : KLesson("Actions", LessonsBundle.message("goto.action.lesson.name")) { companion object { private const val FIND_ACTION_WORKAROUND: String = "https://intellij-support.jetbrains.com/hc/en-us/articles/360005137400-Cmd-Shift-A-hotkey-opens-Terminal-with-apropos-search-instead-of-the-Find-Action-dialog" } override val lessonContent: LessonContext.() -> Unit get() = { prepareSample(sample) task("GotoAction") { text(LessonsBundle.message("goto.action.use.find.action.1", LessonUtil.actionName(it), action(it))) if (SystemInfo.isMacOSMojave) { text(LessonsBundle.message("goto.action.mac.workaround", LessonUtil.actionName(it), FIND_ACTION_WORKAROUND)) } text(LessonsBundle.message("goto.action.use.find.action.2", LessonUtil.actionName("SearchEverywhere"), LessonUtil.rawKeyStroke(KeyEvent.VK_SHIFT))) stateCheck { checkInsideSearchEverywhere() } test { actions(it) } } actionTask("About") { showWarningIfSearchPopupClosed() LessonsBundle.message("goto.action.invoke.about.action", LessonUtil.actionName(it).toLowerCase(), LessonUtil.rawEnter()) } task { text(LessonsBundle.message("goto.action.to.return.to.the.editor", action("EditorEscape"))) var aboutHasBeenFocused = false stateCheck { aboutHasBeenFocused = aboutHasBeenFocused || focusOwner is AboutPopup.PopupPanel aboutHasBeenFocused && focusOwner is EditorComponentImpl } test { ideFrame { waitComponent(JPanel::class.java, "InfoSurface") // Note 1: it is editor from test IDE fixture // Note 2: In order to pass this task without interference with later task I need to firstly focus lesson // and only then press Escape ComponentDriver<Component>(robot).focusAndWaitForFocusGain(editor.contentComponent) invokeActionViaShortcut("ESCAPE") } } } task("GotoAction") { text(LessonsBundle.message("goto.action.invoke.again", action(it), LessonUtil.rawKeyStroke(KeyEvent.VK_SHIFT))) stateCheck { checkInsideSearchEverywhere() } test { actions(it) } } val showLineNumbersName = ActionsBundle.message("action.EditorGutterToggleGlobalLineNumbers.text") task(LearnBundle.message("show.line.number.prefix.to.show.first")) { text(LessonsBundle.message("goto.action.show.line.numbers.request", strong(it), strong(showLineNumbersName))) triggerByListItemAndHighlight { item -> val matchedValue = item as? GotoActionModel.MatchedValue val actionWrapper = matchedValue?.value as? GotoActionModel.ActionWrapper val action = actionWrapper?.action action is ToggleShowLineNumbersGloballyAction } restoreState { !checkInsideSearchEverywhere() } test { waitComponent(SearchEverywhereUI::class.java) type(it) } } val lineNumbersShown = isLineNumbersShown() task { text(LessonsBundle.message("goto.action.first.lines.toggle", if (lineNumbersShown) 0 else 1)) stateCheck { isLineNumbersShown() == !lineNumbersShown } showWarningIfSearchPopupClosed() test { ideFrame { jList(showLineNumbersName).item(showLineNumbersName).click() } } } task { text(LessonsBundle.message("goto.action.second.lines.toggle", if (lineNumbersShown) 0 else 1)) stateCheck { isLineNumbersShown() == lineNumbersShown } showWarningIfSearchPopupClosed() test { ideFrame { jList(showLineNumbersName).item(showLineNumbersName).click() } } } if (firstLesson) { firstLessonCompletedMessage() } } private fun TaskRuntimeContext.checkInsideSearchEverywhere(): Boolean { return UIUtil.getParentOfType(SearchEverywhereUI::class.java, focusOwner) != null } private fun TaskContext.showWarningIfSearchPopupClosed() { showWarning(LessonsBundle.message("goto.action.popup.closed.warning.message", action("GotoAction"), LessonUtil.rawKeyStroke(KeyEvent.VK_SHIFT))) { !checkInsideSearchEverywhere() } } private fun isLineNumbersShown() = EditorSettingsExternalizable.getInstance().isLineNumbersShown }
apache-2.0
86cd0a9c8458b994faf72b039710098e
40.422222
214
0.685745
4.790917
false
true
false
false
leafclick/intellij-community
plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/sam/ClosureToSamConverter.kt
1
1807
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.plugins.groovy.lang.sam import com.intellij.psi.PsiClassType import com.intellij.psi.PsiType import org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElement import org.jetbrains.plugins.groovy.lang.psi.impl.statements.expressions.ConversionResult import org.jetbrains.plugins.groovy.lang.psi.impl.statements.expressions.TypesUtil import org.jetbrains.plugins.groovy.lang.psi.typeEnhancers.GrTypeConverter import org.jetbrains.plugins.groovy.lang.psi.typeEnhancers.GrTypeConverter.Position.* import org.jetbrains.plugins.groovy.lang.psi.util.GroovyCommonClassNames.GROOVY_LANG_CLOSURE import org.jetbrains.plugins.groovy.lang.typing.GroovyClosureType class ClosureToSamConverter : GrTypeConverter() { private val myPositions = setOf(ASSIGNMENT, RETURN_VALUE, METHOD_PARAMETER) override fun isApplicableTo(position: Position): Boolean = position in myPositions override fun isConvertible(targetType: PsiType, actualType: PsiType, position: Position, context: GroovyPsiElement): ConversionResult? { if (targetType !is PsiClassType || actualType !is GroovyClosureType && !TypesUtil.isClassType(actualType, GROOVY_LANG_CLOSURE)) return null if (!isSamConversionAllowed(context)) return null val result = targetType.resolveGenerics() val targetClass = result.element ?: return null val targetFqn = targetClass.qualifiedName ?: return null // anonymous classes has no fqn if (targetFqn == GROOVY_LANG_CLOSURE) return null findSingleAbstractSignature(targetClass) ?: return null return ConversionResult.OK } }
apache-2.0
58ebd342e811beaecba0194377a70cc0
46.552632
140
0.763143
4.681347
false
false
false
false
aconsuegra/algorithms-playground
src/main/kotlin/me/consuegra/algorithms/KSumLinkedLists.kt
1
2017
package me.consuegra.algorithms import me.consuegra.datastructure.KListNode /** * You have two numbers represented by a linked list, where each node represents a single digit. The digits are * stored in reverse1 order, such as the 1's digit is at the head of the list. Write a function that adds the two * numbers and return the sum as a linked list. * <p> * Example * INPUT: 7->1->6 + 5->9->2 * OUTPUT: 2->1->9 */ class KSumLinkedLists { fun sum(param1: KListNode<Int>?, param2: KListNode<Int>?): KListNode<Int>? { var result: KListNode<Int>? = null var list1 = param1 var list2 = param2 var acc = 0 while (list1 != null || list2 != null) { val list1Data = list1?.data ?: 0 val list2Data = list2?.data ?: 0 val sum = acc.plus(list1Data).plus(list2Data) if (sum >= 10) { acc = 1 result = add(result, sum % 10) } else { acc = 0 result = add(result, sum) } list1 = list1?.next list2 = list2?.next } return if (acc == 1) add(result, acc) else result } private fun add(result: KListNode<Int>?, value: Int): KListNode<Int> { return result?.append(value) ?: KListNode(data = value) } fun sumRec(list1: KListNode<Int>?, list2: KListNode<Int>?): KListNode<Int>? = sumRec(list1, list2, 0) private fun sumRec(list1: KListNode<Int>?, list2: KListNode<Int>?, carry: Int): KListNode<Int>? { if (list1 == null && list2 == null && carry == 0) { return null } val list1Data = list1?.data ?: 0 val list2Data = list2?.data ?: 0 val sum = carry.plus(list1Data).plus(list2Data) val result = KListNode(sum % 10) if (list1 != null || list2 != null) { val more = sumRec(list1?.next, list2?.next, if (sum >= 10) 1 else 0) result.next = more } return result } }
mit
10f95ec52e6af6cd188211011c6e0c72
30.515625
113
0.556272
3.694139
false
false
false
false
JuliusKunze/kotlin-native
backend.native/tests/external/codegen/boxInline/tryCatchFinally/tryCatchFinally.kt
2
2205
// IGNORE_BACKEND: NATIVE // FILE: 1.kt // WITH_RUNTIME class My(val value: Int) inline fun <T, R> T.performWithFinally(job: (T)-> R, finally: (T) -> R) : R { try { return job(this) } finally { return finally(this) } } inline fun <T, R> T.performWithFailFinally(job: (T)-> R, failJob : (e: RuntimeException, T) -> R, finally: (T) -> R) : R { try { return job(this) } catch (e: RuntimeException) { return failJob(e, this) } finally { return finally(this) } } inline fun String.toInt2() : Int = java.lang.Integer.parseInt(this) // FILE: 2.kt fun test1(): Int { var res = My(111).performWithFinally<My, Int>( { 1 }, { it.value }) return res } fun test11(): Int { var result = -1; val res = My(111).performWithFinally<My, Int>( { try { result = it.value throw RuntimeException("1") } catch (e: RuntimeException) { ++result throw RuntimeException("2") } }, { ++result }) return res } fun test2(): Int { var res = My(111).performWithFinally<My, Int>( { throw RuntimeException("1") }, { it.value }) return res } fun test3(): Int { try { var result = -1; val res = My(111).performWithFailFinally<My, Int>( { result = it.value; throw RuntimeException("-1") }, { e, z -> ++result throw RuntimeException("-2") }, { ++result }) return res } catch (e: RuntimeException) { return e.message?.toInt()!! } } fun box(): String { if (test1() != 111) return "test1: ${test1()}" if (test11() != 113) return "test11: ${test11()}" if (test2() != 111) return "test2: ${test2()}" if (test3() != 113) return "test3: ${test3()}" return "OK" }
apache-2.0
ce09db554253a8bf1e075b71d0da8906
20.831683
122
0.438549
3.9375
false
true
false
false
blokadaorg/blokada
android5/app/src/main/java/ui/stats/StatsConverter.kt
1
1976
/* * This file is part of Blokada. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. * * Copyright © 2022 Blocka AB. All rights reserved. * * @author Karol Gusak ([email protected]) */ package ui.stats import model.Activity import model.HistoryEntry import model.HistoryEntryType import repository.Repos import service.EnvironmentService import utils.toBlockaDate import java.util.* fun convertActivity(activity: List<Activity>): List<HistoryEntry> { val act = activity.map { HistoryEntry( name = it.domain_name, type = convertType(it), time = convertDate(it.timestamp), requests = 1, device = it.device_name, pack = getPack(it) ) } // Group by name + type return act.groupBy { it.type to it.name }.map { // Assuming items are ordered by most recent first val item = it.value.first() HistoryEntry( name = item.name, type = item.type, time = item.time, requests = it.value.count(), device = item.device, pack = item.pack ) } } private fun convertType(a: Activity): HistoryEntryType { return when { a.action == "block" && a.list == EnvironmentService.deviceTag -> HistoryEntryType.blocked_denied a.action == "allow" && a.list == EnvironmentService.deviceTag -> HistoryEntryType.passed_allowed a.action == "block" -> HistoryEntryType.blocked else -> HistoryEntryType.passed } } private fun convertDate(timestamp: String): Date { return timestamp.toBlockaDate() } private fun getPack(it: Activity): String? { // TODO: quite hacky if (it.list == EnvironmentService.deviceTag) return it.list return Repos.packs.getPackNameForBlocklist(it.list) }
mpl-2.0
faa2d70d4462f0c54b07d104a2eea248
28.492537
104
0.639494
4.014228
false
false
false
false
FirebaseExtended/mlkit-material-android
app/src/main/java/com/google/firebase/ml/md/kotlin/productsearch/ProductAdapter.kt
1
2650
/* * Copyright 2019 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.firebase.ml.md.kotlin.productsearch import android.text.TextUtils import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ImageView import android.widget.TextView import androidx.recyclerview.widget.RecyclerView import androidx.recyclerview.widget.RecyclerView.Adapter import com.google.firebase.ml.md.R import com.google.firebase.ml.md.kotlin.productsearch.ProductAdapter.ProductViewHolder /** Presents the list of product items from cloud product search. */ class ProductAdapter(private val productList: List<Product>) : Adapter<ProductViewHolder>() { class ProductViewHolder private constructor(view: View) : RecyclerView.ViewHolder(view) { private val imageView: ImageView = view.findViewById(R.id.product_image) private val titleView: TextView = view.findViewById(R.id.product_title) private val subtitleView: TextView = view.findViewById(R.id.product_subtitle) private val imageSize: Int = view.resources.getDimensionPixelOffset(R.dimen.product_item_image_size) fun bindProduct(product: Product) { imageView.setImageDrawable(null) if (!TextUtils.isEmpty(product.imageUrl)) { ImageDownloadTask(imageView, imageSize).execute(product.imageUrl) } else { imageView.setImageResource(R.drawable.logo_google_cloud) } titleView.text = product.title subtitleView.text = product.subtitle } companion object { fun create(parent: ViewGroup) = ProductViewHolder(LayoutInflater.from(parent.context).inflate(R.layout.product_item, parent, false)) } } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ProductViewHolder = ProductViewHolder.create(parent) override fun onBindViewHolder(holder: ProductViewHolder, position: Int) { holder.bindProduct(productList[position]) } override fun getItemCount(): Int = productList.size }
apache-2.0
7b0628f4ffdd679bf89b45ca845801fc
39.769231
116
0.727547
4.592721
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/jvm-debugger/core/src/org/jetbrains/kotlin/idea/debugger/stepping/filter/KotlinStepOverFilter.kt
2
3268
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.debugger.stepping.filter import com.intellij.debugger.engine.DebugProcess.JAVA_STRATUM import com.intellij.debugger.engine.DebugProcessImpl import com.intellij.debugger.engine.MethodFilter import com.intellij.debugger.engine.SuspendContextImpl import com.intellij.openapi.project.Project import com.intellij.util.Range import com.sun.jdi.Location import com.sun.jdi.StackFrame import org.jetbrains.kotlin.codegen.inline.isFakeLocalVariableForInline import org.jetbrains.kotlin.idea.debugger.DebuggerUtils.isKotlinFakeLineNumber import org.jetbrains.kotlin.idea.debugger.safeLineNumber import org.jetbrains.kotlin.idea.debugger.safeMethod import org.jetbrains.kotlin.idea.debugger.safeVariables import org.jetbrains.kotlin.idea.debugger.stepping.KotlinMethodFilter @Suppress("EqualsOrHashCode") data class StepOverCallerInfo(val declaringType: String, val methodName: String?, val methodSignature: String?) { companion object { fun from(location: Location): StepOverCallerInfo { val method = location.safeMethod() val declaringType = location.declaringType().name() val methodName = method?.name() val methodSignature = method?.signature() return StepOverCallerInfo(declaringType, methodName, methodSignature) } } } data class LocationToken(val lineNumber: Int, val inlineVariables: List<String>) { companion object { fun from(stackFrame: StackFrame): LocationToken { val location = stackFrame.location() val lineNumber = location.safeLineNumber(JAVA_STRATUM) val methodVariables = ArrayList<String>(0) for (variable in location.safeMethod()?.safeVariables() ?: emptyList()) { val name = variable.name() if (variable.isVisible(stackFrame) && isFakeLocalVariableForInline(name)) { methodVariables += name } } return LocationToken(lineNumber, methodVariables) } } } class KotlinStepOverFilter( val project: Project, private val tokensToSkip: Set<LocationToken>, private val callerInfo: StepOverCallerInfo ) : KotlinMethodFilter { override fun locationMatches(context: SuspendContextImpl, location: Location): Boolean { // Never stop on compiler generated fake line numbers. if (isKotlinFakeLineNumber(location)) return false val stackFrame = context.frameProxy?.stackFrame ?: return true val token = LocationToken.from(stackFrame) val callerInfo = StepOverCallerInfo.from(location) if (callerInfo.methodName != null && callerInfo.methodSignature != null && this.callerInfo == callerInfo) { return token.lineNumber >= 0 && token !in tokensToSkip } else { return true } } override fun locationMatches(process: DebugProcessImpl, location: Location): Boolean { throw IllegalStateException("Should not be called from Kotlin hint") } override fun getCallingExpressionLines(): Range<Int>? = null }
apache-2.0
c730934721b951acbd7ea8e3a586d8bc
41.441558
158
0.71634
4.798825
false
false
false
false
smmribeiro/intellij-community
platform/collaboration-tools/src/com/intellij/collaboration/ui/codereview/comment/RoundedPanel.kt
2
2101
// 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.collaboration.ui.codereview.comment import com.intellij.openapi.editor.colors.EditorColors import com.intellij.openapi.editor.colors.EditorColorsManager import com.intellij.util.ui.GraphicsUtil import com.intellij.util.ui.JBInsets import java.awt.* import java.awt.event.ComponentAdapter import java.awt.event.ComponentEvent import java.awt.geom.RoundRectangle2D import javax.swing.JComponent import javax.swing.JPanel fun wrapComponentUsingRoundedPanel(component: JComponent): JComponent { val wrapper = RoundedPanel(BorderLayout()) wrapper.add(component) component.addComponentListener(object : ComponentAdapter() { override fun componentResized(e: ComponentEvent?) = wrapper.dispatchEvent(ComponentEvent(component, ComponentEvent.COMPONENT_RESIZED)) }) return wrapper } private class RoundedPanel(layout: LayoutManager?) : JPanel(layout) { private var borderLineColor: Color? = null init { isOpaque = false cursor = Cursor.getDefaultCursor() updateColors() } override fun updateUI() { super.updateUI() updateColors() } private fun updateColors() { val scheme = EditorColorsManager.getInstance().globalScheme background = scheme.defaultBackground borderLineColor = scheme.getColor(EditorColors.TEARLINE_COLOR) } override fun paintComponent(g: Graphics) { GraphicsUtil.setupRoundedBorderAntialiasing(g) val g2 = g as Graphics2D val rect = Rectangle(size) JBInsets.removeFrom(rect, insets) // 2.25 scale is a @#$!% so we adjust sizes manually val rectangle2d = RoundRectangle2D.Float(rect.x.toFloat() + 0.5f, rect.y.toFloat() + 0.5f, rect.width.toFloat() - 1f, rect.height.toFloat() - 1f, 10f, 10f) g2.color = background g2.fill(rectangle2d) borderLineColor?.let { g2.color = borderLineColor g2.draw(rectangle2d) } } }
apache-2.0
6283c5ef43bfbf44e9fca6bfbcac42fb
32.887097
140
0.717277
4.296524
false
false
false
false
FuturemanGaming/FutureBot-Discord
src/main/kotlin/com/futuremangaming/futurebot/command/help/Helpers.kt
1
1716
/* * Copyright 2014-2017 FuturemanGaming * * 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.futuremangaming.futurebot.command.help import com.futuremangaming.futurebot.internal.CommandManagement import gnu.trove.map.hash.TLongObjectHashMap import net.dv8tion.jda.core.JDA import net.dv8tion.jda.core.entities.TextChannel class Helpers(val management: CommandManagement) { internal val helpers = TLongObjectHashMap<HelpView>() val adapter = HelpAdapter(this) fun register(api: JDA) { if (adapter !in api.registeredListeners) api.addEventListener(adapter) } fun shutdown(api: JDA) { api.removeEventListener(adapter) helpers.forEachValue(HelpView::destroy) } fun display(channel: TextChannel, matching: () -> String) { val helper = of(channel) helper.show(management, matching) } fun display(channel: TextChannel) { val helper = of(channel) helper.show(management, new = true) } fun of(channel: TextChannel): HelpView { if (channel.idLong !in helpers) helpers.put(channel.idLong, HelpView(channel)) return helpers[channel.idLong]!! } }
apache-2.0
1b68c5e3c6521674924117e6b0cfc064
29.642857
75
0.702214
4.095465
false
false
false
false
mdaniel/intellij-community
platform/collaboration-tools/src/com/intellij/collaboration/ui/codereview/InlineIconButton.kt
1
5394
// 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.intellij.collaboration.ui.codereview import com.intellij.ide.HelpTooltip import com.intellij.openapi.actionSystem.ShortcutSet import com.intellij.openapi.keymap.KeymapUtil import com.intellij.openapi.util.Disposer import com.intellij.openapi.util.IconLoader import com.intellij.openapi.util.NlsContexts import com.intellij.util.ui.BaseButtonBehavior import com.intellij.util.ui.JBInsets import com.intellij.util.ui.update.Activatable import com.intellij.util.ui.update.UiNotifyConnector import java.awt.* import java.awt.event.* import java.beans.PropertyChangeEvent import java.beans.PropertyChangeListener import javax.swing.Icon import javax.swing.JComponent import javax.swing.plaf.ComponentUI import kotlin.properties.Delegates.observable class InlineIconButton(icon: Icon, hoveredIcon: Icon? = null, disabledIcon: Icon? = null, @NlsContexts.Tooltip val tooltip: String? = null, var shortcut: ShortcutSet? = null) : JComponent() { var actionListener: ActionListener? by observable(null) { _, old, new -> firePropertyChange(ACTION_LISTENER_PROPERTY, old, new) } var icon by observable(icon) { _, old, new -> firePropertyChange(ICON_PROPERTY, old, new) } var hoveredIcon by observable(hoveredIcon) { _, old, new -> firePropertyChange(HOVERED_ICON_PROPERTY, old, new) } var disabledIcon by observable(disabledIcon) { _, old, new -> firePropertyChange(DISABLED_ICON_PROPERTY, old, new) } init { setUI(InlineIconButtonUI()) } private class InlineIconButtonUI : ComponentUI() { private var buttonBehavior: BaseButtonBehavior? = null private var tooltipConnector: UiNotifyConnector? = null private var spaceKeyListener: KeyListener? = null private var propertyListener: PropertyChangeListener? = null override fun paint(g: Graphics, c: JComponent) { c as InlineIconButton val icon = getCurrentIcon(c) val g2 = g.create() as Graphics2D try { val r = Rectangle(c.getSize()) JBInsets.removeFrom(r, c.insets) g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON) g2.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_NORMALIZE) g2.translate(r.x, r.y) icon.paintIcon(c, g2, 0, 0) } finally { g2.dispose() } } override fun getMinimumSize(c: JComponent): Dimension { return getPreferredSize(c) } override fun getPreferredSize(c: JComponent): Dimension { val icon = (c as InlineIconButton).icon val size = Dimension(icon.iconWidth, icon.iconHeight) JBInsets.addTo(size, c.insets) return size } override fun getMaximumSize(c: JComponent): Dimension { return getPreferredSize(c) } private fun getCurrentIcon(c: InlineIconButton): Icon { if (!c.isEnabled) return c.disabledIcon ?: IconLoader.getDisabledIcon(c.icon) if (buttonBehavior?.isHovered == true || c.hasFocus()) return c.hoveredIcon ?: c.icon return c.icon } override fun installUI(c: JComponent) { c as InlineIconButton buttonBehavior = object : BaseButtonBehavior(c) { override fun execute(e: MouseEvent) { if (c.isEnabled) { c.actionListener?.actionPerformed(ActionEvent(e, ActionEvent.ACTION_PERFORMED, "execute", e.modifiers)) } } } spaceKeyListener = object : KeyAdapter() { override fun keyReleased(e: KeyEvent) { if (c.isEnabled && !e.isConsumed && e.modifiers == 0 && e.keyCode == KeyEvent.VK_SPACE) { c.actionListener?.actionPerformed(ActionEvent(e, ActionEvent.ACTION_PERFORMED, "execute", e.modifiers)) e.consume() return } } } c.addKeyListener(spaceKeyListener) tooltipConnector = UiNotifyConnector(c, object : Activatable { override fun showNotify() { if (c.tooltip != null) { HelpTooltip() .setTitle(c.tooltip) .setShortcut(c.shortcut?.let { KeymapUtil.getFirstKeyboardShortcutText(it) }) .installOn(c) } } override fun hideNotify() { HelpTooltip.dispose(c) } }) propertyListener = PropertyChangeListener { c.revalidate() c.repaint() } c.addPropertyChangeListener(propertyListener) c.isOpaque = false c.isFocusable = true c.cursor = Cursor.getPredefinedCursor(Cursor.HAND_CURSOR) } override fun uninstallUI(c: JComponent) { tooltipConnector?.let { Disposer.dispose(it) } tooltipConnector = null spaceKeyListener?.let { c.removeKeyListener(it) } propertyListener?.let { c.removePropertyChangeListener(it) } propertyListener = null spaceKeyListener = null buttonBehavior = null HelpTooltip.dispose(c) } } companion object { val ACTION_LISTENER_PROPERTY = "action_listener" val ICON_PROPERTY = "icon" val HOVERED_ICON_PROPERTY = "hovered_icon" val DISABLED_ICON_PROPERTY = "disabled_icon" } }
apache-2.0
ce4e66929a1a4e3ba369864f41ba1bb2
31.896341
140
0.664813
4.424938
false
false
false
false
mdaniel/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/inline/AbstractKotlinDeclarationInlineProcessor.kt
1
2772
// 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.inline import com.intellij.java.refactoring.JavaRefactoringBundle import com.intellij.lang.findUsages.DescriptiveNameUtil import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import com.intellij.refactoring.BaseRefactoringProcessor import com.intellij.refactoring.RefactoringBundle import com.intellij.usageView.UsageInfo import com.intellij.usageView.UsageViewBundle import com.intellij.usageView.UsageViewDescriptor import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.search.codeUsageScopeRestrictedToProject import org.jetbrains.kotlin.psi.KtDeclaration import org.jetbrains.kotlin.psi.KtNamedFunction import org.jetbrains.kotlin.psi.KtProperty import org.jetbrains.kotlin.psi.KtTypeAlias abstract class AbstractKotlinDeclarationInlineProcessor<TElement : KtDeclaration>( protected val declaration: TElement, protected val editor: Editor?, project: Project, ) : BaseRefactoringProcessor(project, declaration.codeUsageScopeRestrictedToProject(), null) { protected val kind = when (declaration) { is KtNamedFunction -> if (declaration.name != null) KotlinBundle.message("text.function") else KotlinBundle.message("text.anonymous.function") is KtProperty -> if (declaration.isLocal) KotlinBundle.message("text.local.variable") else KotlinBundle.message("text.local.property") is KtTypeAlias -> KotlinBundle.message("text.type.alias") else -> KotlinBundle.message("text.declaration") } override fun getCommandName(): String = KotlinBundle.message( "text.inlining.0.1", kind, DescriptiveNameUtil.getDescriptiveName(declaration) ) override fun createUsageViewDescriptor(usages: Array<out UsageInfo>): UsageViewDescriptor = object : UsageViewDescriptor { override fun getCommentReferencesText(usagesCount: Int, filesCount: Int) = RefactoringBundle.message( "comments.elements.header", UsageViewBundle.getOccurencesString(usagesCount, filesCount), ) override fun getCodeReferencesText(usagesCount: Int, filesCount: Int) = JavaRefactoringBundle.message( "invocations.to.be.inlined", UsageViewBundle.getReferencesString(usagesCount, filesCount), ) override fun getElements() = arrayOf<KtDeclaration>(declaration) override fun getProcessedElementsHeader() = KotlinBundle.message("text.0.to.inline", kind.capitalize()) } }
apache-2.0
908f3f899dbd3118c0e30793383540b5
43.015873
158
0.750361
4.871705
false
false
false
false
tsagi/JekyllForAndroid
app/src/main/java/com/jchanghong/ActivityCategoryPick.kt
2
3463
package com.jchanghong import android.app.Activity import android.content.Context import android.content.Intent import android.graphics.Color import android.graphics.drawable.GradientDrawable import android.os.Bundle import android.support.v7.app.AppCompatActivity import android.support.v7.widget.Toolbar import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.* import com.jchanghong.data.DatabaseManager import com.jchanghong.model.Category import com.jchanghong.utils.Tools class ActivityCategoryPick : AppCompatActivity() { lateinit private var adapterListCategory: AdapterListCategory override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_category_pick) initToolbar() adapterListCategory = AdapterListCategory(this, DatabaseManager.allCategory) val listView = findViewById(R.id.paired_devices) as ListView listView.adapter = adapterListCategory listView.onItemClickListener = AdapterView.OnItemClickListener({ _, _, i, _ -> sendIntentResult(adapterListCategory.getItem(i) as Category) }) } private fun initToolbar() { val toolbar = findViewById(R.id.toolbar) as Toolbar setSupportActionBar(toolbar) val actionBar = supportActionBar actionBar?.setDisplayHomeAsUpEnabled(false) actionBar?.setHomeButtonEnabled(false) actionBar?.setTitle(R.string.title_activity_pick_category) } private fun sendIntentResult(category: Category) { // send extra object val intent = Intent() intent.putExtra(EXTRA_OBJ, category) // Set result and finish this Activity setResult(Activity.RESULT_OK, intent) finish() } private inner class AdapterListCategory(private val ctx: Context, private val items: List<Category>) : BaseAdapter() { override fun getCount(): Int { return items.size } override fun getItem(position: Int): Any { return items[position] } override fun getItemId(position: Int): Long { return position.toLong() } override fun getView(position: Int, convertView: View?, parent: ViewGroup): View { var convertView = convertView val obj = getItem(position) as Category val holder: ViewHolder if (convertView == null) { holder = ViewHolder() convertView = LayoutInflater.from(ctx).inflate(R.layout.row_category_simple, parent, false) holder.image = convertView.findViewById<View>(R.id.image) as ImageView holder.name = convertView.findViewById<View>(R.id.name) as TextView convertView.tag = holder } else { holder = convertView.tag as ViewHolder } holder.image?.setImageResource(Tools.StringToResId(obj.icon, ctx)) (holder.image?.background as GradientDrawable).setColor(Color.parseColor(obj.color)) holder.name?.text = obj.name return convertView!! } private inner class ViewHolder { internal var image: ImageView? = null internal var name: TextView? = null } } companion object { /** Return Intent extra */ var EXTRA_OBJ = "com.jchanghong.EXTRA_OBJ" } }
gpl-2.0
2e9b48865a1adf3c10451797ce19ae7c
33.287129
150
0.668207
4.968436
false
false
false
false
siosio/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/kdoc/KDocMissingDocumentationInspection.kt
1
4022
// 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.kdoc import com.intellij.codeInsight.FileModificationService import com.intellij.codeInspection.LocalQuickFix import com.intellij.codeInspection.ProblemDescriptor import com.intellij.codeInspection.ProblemsHolder import com.intellij.openapi.editor.EditorModificationUtil import com.intellij.openapi.project.Project import com.intellij.psi.PsiElementVisitor import com.siyeh.ig.psiutils.TestUtils import org.jetbrains.kotlin.descriptors.DeclarationDescriptorWithVisibility import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.idea.caches.resolve.resolveToDescriptorIfAny import org.jetbrains.kotlin.idea.codeInsight.DescriptorToSourceUtilsIde import org.jetbrains.kotlin.idea.core.unblockDocument import org.jetbrains.kotlin.idea.inspections.AbstractKotlinInspection import org.jetbrains.kotlin.idea.inspections.describe import org.jetbrains.kotlin.idea.inspections.findExistingEditor import org.jetbrains.kotlin.idea.kdoc.KDocElementFactory import org.jetbrains.kotlin.idea.kdoc.findKDoc import org.jetbrains.kotlin.kdoc.psi.impl.KDocSection import org.jetbrains.kotlin.psi.KtNamedDeclaration import org.jetbrains.kotlin.psi.namedDeclarationVisitor import org.jetbrains.kotlin.psi.psiUtil.endOffset import org.jetbrains.kotlin.psi.psiUtil.getChildOfType import org.jetbrains.kotlin.psi.psiUtil.getParentOfType import org.jetbrains.kotlin.resolve.descriptorUtil.isEffectivelyPublicApi class KDocMissingDocumentationInspection : AbstractKotlinInspection() { override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean): PsiElementVisitor = namedDeclarationVisitor { element -> if (TestUtils.isInTestSourceContent(element)) { return@namedDeclarationVisitor } val nameIdentifier = element.nameIdentifier if (nameIdentifier != null) { if (element.findKDoc { DescriptorToSourceUtilsIde.getAnyDeclaration(element.project, it) } == null) { val descriptor = element.resolveToDescriptorIfAny() as? DeclarationDescriptorWithVisibility ?: return@namedDeclarationVisitor if (descriptor.isEffectivelyPublicApi) { val message = element.describe()?.let { KotlinBundle.message("0.is.missing.documentation", it) } ?: KotlinBundle.message("missing.documentation") holder.registerProblem(nameIdentifier, message, AddDocumentationFix()) } } } } class AddDocumentationFix : LocalQuickFix { override fun getName(): String = KotlinBundle.message("add.documentation.fix.text") override fun getFamilyName(): String = name override fun applyFix(project: Project, descriptor: ProblemDescriptor) { if (!FileModificationService.getInstance().preparePsiElementForWrite(descriptor.psiElement)) return val declaration = descriptor.psiElement.getParentOfType<KtNamedDeclaration>(true) ?: throw IllegalStateException("Can't find declaration") declaration.addBefore(KDocElementFactory(project).createKDocFromText("/**\n*\n*/\n"), declaration.firstChild) val editor = descriptor.psiElement.findExistingEditor() ?: return // If we just add whitespace // /** // *[HERE] // it will be erased by formatter, so following code adds it right way and moves caret then editor.unblockDocument() val section = declaration.firstChild.getChildOfType<KDocSection>() ?: return val asterisk = section.firstChild editor.caretModel.moveToOffset(asterisk.endOffset) EditorModificationUtil.insertStringAtCaret(editor, " ") } } }
apache-2.0
d7a3a51ce33eaae9f69b69a27176730c
49.275
158
0.730482
5.405914
false
false
false
false
siosio/intellij-community
platform/workspaceModel/jps/src/com/intellij/workspaceModel/ide/impl/jps/serialization/JpsLibraryEntitiesSerializer.kt
1
14449
// 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.jps.serialization import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.util.JDOMUtil import com.intellij.util.containers.ConcurrentFactoryMap import com.intellij.workspaceModel.ide.JpsFileEntitySource import com.intellij.workspaceModel.ide.JpsImportedEntitySource import com.intellij.workspaceModel.ide.JpsProjectConfigLocation import com.intellij.workspaceModel.ide.impl.JpsEntitySourceFactory import com.intellij.workspaceModel.ide.impl.legacyBridge.library.LibraryNameGenerator import com.intellij.workspaceModel.storage.* import com.intellij.workspaceModel.storage.bridgeEntities.* import com.intellij.workspaceModel.storage.impl.EntityDataDelegation import com.intellij.workspaceModel.storage.impl.ModifiableWorkspaceEntityBase import com.intellij.workspaceModel.storage.impl.WorkspaceEntityBase import com.intellij.workspaceModel.storage.impl.WorkspaceEntityData import com.intellij.workspaceModel.storage.impl.references.MutableOneToOneChild import com.intellij.workspaceModel.storage.impl.references.OneToOneChild import com.intellij.workspaceModel.storage.url.VirtualFileUrl import com.intellij.workspaceModel.storage.url.VirtualFileUrlManager import org.jdom.Element import org.jetbrains.jps.model.serialization.JDomSerializationUtil import org.jetbrains.jps.model.serialization.SerializationConstants import org.jetbrains.jps.model.serialization.java.JpsJavaModelSerializerExtension import org.jetbrains.jps.model.serialization.library.JpsLibraryTableSerializer.* import org.jetbrains.jps.model.serialization.module.JpsModuleRootModelSerializer internal class JpsLibrariesDirectorySerializerFactory(override val directoryUrl: String) : JpsDirectoryEntitiesSerializerFactory<LibraryEntity> { override val componentName: String get() = LIBRARY_TABLE_COMPONENT_NAME override fun getDefaultFileName(entity: LibraryEntity): String { return entity.name } override val entityClass: Class<LibraryEntity> get() = LibraryEntity::class.java override val entityFilter: (LibraryEntity) -> Boolean get() = { it.tableId == LibraryTableId.ProjectLibraryTableId } override fun createSerializer(fileUrl: String, entitySource: JpsFileEntitySource.FileInDirectory, virtualFileManager: VirtualFileUrlManager): JpsFileEntitiesSerializer<LibraryEntity> { return JpsLibraryEntitiesSerializer(virtualFileManager.fromUrl(fileUrl), entitySource, LibraryTableId.ProjectLibraryTableId) } override fun changeEntitySourcesToDirectoryBasedFormat(builder: WorkspaceEntityStorageBuilder, configLocation: JpsProjectConfigLocation) { builder.entities(LibraryEntity::class.java).forEach { if (it.tableId == LibraryTableId.ProjectLibraryTableId) { builder.changeSource(it, JpsEntitySourceFactory.createJpsEntitySourceForProjectLibrary(configLocation)) } } builder.entities(LibraryPropertiesEntity::class.java).forEach { if (it.library.tableId == LibraryTableId.ProjectLibraryTableId) { builder.changeSource(it, it.library.entitySource) } } } } private const val LIBRARY_TABLE_COMPONENT_NAME = "libraryTable" internal class JpsLibrariesFileSerializer(entitySource: JpsFileEntitySource.ExactFile, libraryTableId: LibraryTableId) : JpsLibraryEntitiesSerializer(entitySource.file, entitySource, libraryTableId), JpsFileEntityTypeSerializer<LibraryEntity> { override val isExternalStorage: Boolean get() = false override val entityFilter: (LibraryEntity) -> Boolean get() = { it.tableId == libraryTableId && (it.entitySource as? JpsImportedEntitySource)?.storedExternally != true } override fun deleteObsoleteFile(fileUrl: String, writer: JpsFileContentWriter) { writer.saveComponent(fileUrl, LIBRARY_TABLE_COMPONENT_NAME, null) } } internal class JpsLibrariesExternalFileSerializer(private val externalFile: JpsFileEntitySource.ExactFile, private val internalLibrariesDirUrl: VirtualFileUrl) : JpsLibraryEntitiesSerializer(externalFile.file, externalFile, LibraryTableId.ProjectLibraryTableId), JpsFileEntityTypeSerializer<LibraryEntity> { override val isExternalStorage: Boolean get() = true override val entityFilter: (LibraryEntity) -> Boolean get() = { it.tableId == LibraryTableId.ProjectLibraryTableId && (it.entitySource as? JpsImportedEntitySource)?.storedExternally == true } override fun createEntitySource(libraryTag: Element): EntitySource? { val externalSystemId = libraryTag.getAttributeValue(SerializationConstants.EXTERNAL_SYSTEM_ID_ATTRIBUTE) ?: return null val internalEntitySource = JpsFileEntitySource.FileInDirectory(internalLibrariesDirUrl, externalFile.projectLocation) return JpsImportedEntitySource(internalEntitySource, externalSystemId, true) } override fun getExternalSystemId(libraryEntity: LibraryEntity): String? { val source = libraryEntity.entitySource return (source as? JpsImportedEntitySource)?.externalSystemId } override fun deleteObsoleteFile(fileUrl: String, writer: JpsFileContentWriter) { writer.saveComponent(fileUrl, LIBRARY_TABLE_COMPONENT_NAME, null) } } internal open class JpsLibraryEntitiesSerializer(override val fileUrl: VirtualFileUrl, override val internalEntitySource: JpsFileEntitySource, protected val libraryTableId: LibraryTableId) : JpsFileEntitiesSerializer<LibraryEntity> { open val isExternalStorage: Boolean get() = false override val mainEntityClass: Class<LibraryEntity> get() = LibraryEntity::class.java override fun loadEntities(builder: WorkspaceEntityStorageBuilder, reader: JpsFileContentReader, errorReporter: ErrorReporter, virtualFileManager: VirtualFileUrlManager) { val libraryTableTag = reader.loadComponent(fileUrl.url, LIBRARY_TABLE_COMPONENT_NAME) ?: return for (libraryTag in libraryTableTag.getChildren(LIBRARY_TAG)) { val source = createEntitySource(libraryTag) ?: continue val name = libraryTag.getAttributeValueStrict(JpsModuleRootModelSerializer.NAME_ATTRIBUTE) val libraryId = LibraryId(name, libraryTableId) val existingLibraryEntity = builder.resolve(libraryId) if (existingLibraryEntity != null) { logger<JpsLibraryEntitiesSerializer>().error("""Error during entities loading |Entity with this library id already exists. |Library id: $libraryId |fileUrl: ${fileUrl.presentableUrl} |library table id: $libraryTableId |internal entity source: $internalEntitySource """.trimMargin()) } loadLibrary(name, libraryTag, libraryTableId, builder, source, virtualFileManager, isExternalStorage) } } protected open fun createEntitySource(libraryTag: Element): EntitySource? = internalEntitySource override fun saveEntities(mainEntities: Collection<LibraryEntity>, entities: Map<Class<out WorkspaceEntity>, List<WorkspaceEntity>>, storage: WorkspaceEntityStorage, writer: JpsFileContentWriter) { if (mainEntities.isEmpty()) return val componentTag = JDomSerializationUtil.createComponentElement(LIBRARY_TABLE_COMPONENT_NAME) mainEntities.sortedBy { it.name }.forEach { componentTag.addContent(saveLibrary(it, getExternalSystemId(it), isExternalStorage)) } writer.saveComponent(fileUrl.url, LIBRARY_TABLE_COMPONENT_NAME, componentTag) } protected open fun getExternalSystemId(libraryEntity: LibraryEntity): String? { return libraryEntity.externalSystemId?.externalSystemId } override fun toString(): String = "${javaClass.simpleName.substringAfterLast('.')}($fileUrl)" } private const val DEFAULT_JAR_DIRECTORY_TYPE = "CLASSES" internal fun loadLibrary(name: String, libraryElement: Element, libraryTableId: LibraryTableId, builder: WorkspaceEntityStorageBuilder, source: EntitySource, virtualFileManager: VirtualFileUrlManager, isExternalStorage: Boolean): LibraryEntity { val roots = ArrayList<LibraryRoot>() val excludedRoots = ArrayList<VirtualFileUrl>() val jarDirectories = libraryElement.getChildren(JAR_DIRECTORY_TAG).associateBy( { Pair(it.getAttributeValue(JpsModuleRootModelSerializer.TYPE_ATTRIBUTE) ?: DEFAULT_JAR_DIRECTORY_TYPE, it.getAttributeValueStrict(JpsModuleRootModelSerializer.URL_ATTRIBUTE)) }, { if (it.getAttributeValue(RECURSIVE_ATTRIBUTE)?.toBoolean() == true) LibraryRoot.InclusionOptions.ARCHIVES_UNDER_ROOT_RECURSIVELY else LibraryRoot.InclusionOptions.ARCHIVES_UNDER_ROOT } ) val type = libraryElement.getAttributeValue("type") var properties: String? = null for (childElement in libraryElement.children) { when (childElement.name) { "excluded" -> excludedRoots.addAll( childElement.getChildren(JpsJavaModelSerializerExtension.ROOT_TAG) .map { it.getAttributeValueStrict(JpsModuleRootModelSerializer.URL_ATTRIBUTE) } .map { virtualFileManager.fromUrl(it) } ) PROPERTIES_TAG -> { properties = JDOMUtil.write(childElement) } JAR_DIRECTORY_TAG -> { } else -> { val rootType = childElement.name for (rootTag in childElement.getChildren(JpsJavaModelSerializerExtension.ROOT_TAG)) { val url = rootTag.getAttributeValueStrict(JpsModuleRootModelSerializer.URL_ATTRIBUTE) val inclusionOptions = jarDirectories[Pair(rootType, url)] ?: LibraryRoot.InclusionOptions.ROOT_ITSELF roots.add(LibraryRoot(virtualFileManager.fromUrl(url), libraryRootTypes[rootType]!!, inclusionOptions)) } } } } val libraryEntity = builder.addLibraryEntity(name, libraryTableId, roots, excludedRoots, source) if (type != null) { builder.addLibraryPropertiesEntity(libraryEntity, type, properties) } val externalSystemId = libraryElement.getAttributeValue(SerializationConstants.EXTERNAL_SYSTEM_ID_IN_INTERNAL_STORAGE_ATTRIBUTE) if (externalSystemId != null && !isExternalStorage) { builder.addEntity(ModifiableLibraryExternalSystemIdEntity::class.java, source) { this.externalSystemId = externalSystemId library = libraryEntity } } return libraryEntity } private val libraryRootTypes = ConcurrentFactoryMap.createMap<String, LibraryRootTypeId> { LibraryRootTypeId(it) } internal fun saveLibrary(library: LibraryEntity, externalSystemId: String?, isExternalStorage: Boolean): Element { val libraryTag = Element(LIBRARY_TAG) val legacyName = LibraryNameGenerator.getLegacyLibraryName(library.persistentId()) if (legacyName != null) { libraryTag.setAttribute(NAME_ATTRIBUTE, legacyName) } val customProperties = library.getCustomProperties() if (customProperties != null) { libraryTag.setAttribute(TYPE_ATTRIBUTE, customProperties.libraryType) val propertiesXmlTag = customProperties.propertiesXmlTag if (propertiesXmlTag != null) { libraryTag.addContent(JDOMUtil.load(propertiesXmlTag)) } } if (externalSystemId != null) { val attributeName = if (isExternalStorage) SerializationConstants.EXTERNAL_SYSTEM_ID_ATTRIBUTE else SerializationConstants.EXTERNAL_SYSTEM_ID_IN_INTERNAL_STORAGE_ATTRIBUTE libraryTag.setAttribute(attributeName, externalSystemId) } val rootsMap = library.roots.groupByTo(HashMap()) { it.type } ROOT_TYPES_TO_WRITE_EMPTY_TAG.forEach { rootsMap.putIfAbsent(it, ArrayList()) } val jarDirectoriesTags = ArrayList<Element>() rootsMap.entries.sortedWith(compareBy(String.CASE_INSENSITIVE_ORDER) {it.key.name}).forEach { (rootType, roots) -> val rootTypeTag = Element(rootType.name) roots.forEach { rootTypeTag.addContent(Element(ROOT_TAG).setAttribute(JpsModuleRootModelSerializer.URL_ATTRIBUTE, it.url.url)) } roots.sortedWith(compareBy(String.CASE_INSENSITIVE_ORDER) {it.url.url}).forEach { if (it.inclusionOptions != LibraryRoot.InclusionOptions.ROOT_ITSELF) { val jarDirectoryTag = Element(JAR_DIRECTORY_TAG) jarDirectoryTag.setAttribute(JpsModuleRootModelSerializer.URL_ATTRIBUTE, it.url.url) jarDirectoryTag.setAttribute(RECURSIVE_ATTRIBUTE, (it.inclusionOptions == LibraryRoot.InclusionOptions.ARCHIVES_UNDER_ROOT_RECURSIVELY).toString()) if (rootType.name != DEFAULT_JAR_DIRECTORY_TYPE) { jarDirectoryTag.setAttribute(TYPE_ATTRIBUTE, rootType.name) } jarDirectoriesTags.add(jarDirectoryTag) } } libraryTag.addContent(rootTypeTag) } val excludedRoots = library.excludedRoots if (excludedRoots.isNotEmpty()) { val excludedTag = Element("excluded") excludedRoots.forEach { excludedTag.addContent(Element(ROOT_TAG).setAttribute(JpsModuleRootModelSerializer.URL_ATTRIBUTE, it.url)) } libraryTag.addContent(excludedTag) } jarDirectoriesTags.forEach { libraryTag.addContent(it) } return libraryTag } private val ROOT_TYPES_TO_WRITE_EMPTY_TAG = listOf("CLASSES", "SOURCES", "JAVADOC").map { libraryRootTypes[it]!! } /** * This property indicates that external-system-id attribute should be stored in library configuration file to avoid unnecessary modifications */ @Suppress("unused") internal class LibraryExternalSystemIdEntityData : WorkspaceEntityData<LibraryExternalSystemIdEntity>() { lateinit var externalSystemId: String override fun createEntity(snapshot: WorkspaceEntityStorage): LibraryExternalSystemIdEntity { return LibraryExternalSystemIdEntity(externalSystemId).also { addMetaData(it, snapshot) } } } internal class LibraryExternalSystemIdEntity( val externalSystemId: String ) : WorkspaceEntityBase() { val library: LibraryEntity by OneToOneChild.NotNull(LibraryEntity::class.java) } internal class ModifiableLibraryExternalSystemIdEntity : ModifiableWorkspaceEntityBase<LibraryExternalSystemIdEntity>() { var externalSystemId: String by EntityDataDelegation() var library: LibraryEntity by MutableOneToOneChild.NotNull(LibraryExternalSystemIdEntity::class.java, LibraryEntity::class.java) } private val LibraryEntity.externalSystemId get() = referrers(LibraryExternalSystemIdEntity::library).firstOrNull()
apache-2.0
eb5784416ca4cdc3c643aa616f6a2cde
48.146259
155
0.768911
5.39343
false
false
false
false
siosio/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/AddWhenRemainingBranchesFix.kt
1
4993
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.quickfix import com.intellij.codeInsight.intention.IntentionAction import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import com.intellij.psi.PsiWhiteSpace import org.jetbrains.kotlin.cfg.* import org.jetbrains.kotlin.descriptors.ClassDescriptor import org.jetbrains.kotlin.descriptors.ClassKind import org.jetbrains.kotlin.diagnostics.Diagnostic import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.idea.caches.resolve.analyze import org.jetbrains.kotlin.idea.core.ShortenReferences import org.jetbrains.kotlin.idea.core.quoteIfNeeded import org.jetbrains.kotlin.idea.intentions.ImportAllMembersIntention import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.getNonStrictParentOfType import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameSafe import org.jetbrains.kotlin.utils.addToStdlib.firstNotNullResult class AddWhenRemainingBranchesFix( expression: KtWhenExpression, val withImport: Boolean = false ) : KotlinQuickFixAction<KtWhenExpression>(expression) { override fun getFamilyName() = text override fun getText(): String { if (withImport) { return KotlinBundle.message("fix.add.remaining.branches.with.star.import") } else { return KotlinBundle.message("fix.add.remaining.branches") } } override fun isAvailable(project: Project, editor: Editor?, file: KtFile): Boolean { return isAvailable(element) } override fun invoke(project: Project, editor: Editor?, file: KtFile) { addRemainingBranches(element, withImport) } companion object : KotlinIntentionActionsFactory() { private fun KtWhenExpression.hasEnumSubject(): Boolean { val subject = subjectExpression ?: return false val descriptor = subject.analyze().getType(subject)?.constructor?.declarationDescriptor ?: return false return (descriptor as? ClassDescriptor)?.kind == ClassKind.ENUM_CLASS } override fun doCreateActions(diagnostic: Diagnostic): List<IntentionAction> { val whenExpression = diagnostic.psiElement.getNonStrictParentOfType<KtWhenExpression>() ?: return emptyList() val actions = mutableListOf(AddWhenRemainingBranchesFix(whenExpression)) if (whenExpression.hasEnumSubject()) { actions += AddWhenRemainingBranchesFix(whenExpression, withImport = true) } return actions } fun isAvailable(element: KtWhenExpression?): Boolean { if (element == null) return false return element.closeBrace != null && with(WhenChecker.getMissingCases(element, element.analyze())) { isNotEmpty() && !hasUnknown } } fun addRemainingBranches(element: KtWhenExpression?, withImport: Boolean = false) { if (element == null) return val missingCases = WhenChecker.getMissingCases(element, element.analyze()) val whenCloseBrace = element.closeBrace ?: throw AssertionError("isAvailable should check if close brace exist") val elseBranch = element.entries.find { it.isElse } val psiFactory = KtPsiFactory(element) (whenCloseBrace.prevSibling as? PsiWhiteSpace)?.replace(psiFactory.createNewLine()) for (case in missingCases) { val branchConditionText = when (case) { UnknownMissingCase, NullMissingCase, is BooleanMissingCase, is ConditionTypeIsExpectMissingCase -> case.branchConditionText is ClassMissingCase -> if (case.classIsSingleton) { "" } else { "is " } + case.descriptor.fqNameSafe.quoteIfNeeded().asString() } val entry = psiFactory.createWhenEntry("$branchConditionText -> TODO()") if (elseBranch != null) { element.addBefore(entry, elseBranch) } else { element.addBefore(entry, whenCloseBrace) } } ShortenReferences.DEFAULT.process(element) if (withImport) { importAllEntries(element) } } private fun importAllEntries(element: KtWhenExpression) { with(ImportAllMembersIntention) { element.entries .map { it.conditions.toList() } .flatten() .firstNotNullResult { (it as? KtWhenConditionWithExpression)?.expression as? KtDotQualifiedExpression }?.importReceiverMembers() } } } }
apache-2.0
772629443c035cda477a5f8448e38a3d
43.185841
158
0.651112
5.468784
false
false
false
false
siosio/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/ReformatInspection.kt
1
3611
// 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.codeInsight.actions.VcsFacade import com.intellij.codeInspection.* import com.intellij.codeInspection.ex.ProblemDescriptorImpl import com.intellij.codeInspection.ui.SingleCheckboxOptionsPanel import com.intellij.openapi.project.Project import com.intellij.psi.PsiFile import com.intellij.psi.PsiWhiteSpace import com.intellij.psi.codeStyle.CodeStyleManager import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.idea.formatter.FormattingChange import org.jetbrains.kotlin.idea.formatter.FormattingChange.ReplaceWhiteSpace import org.jetbrains.kotlin.idea.formatter.FormattingChange.ShiftIndentInsideRange import org.jetbrains.kotlin.idea.formatter.collectFormattingChanges import org.jetbrains.kotlin.idea.util.ProjectRootsUtil import org.jetbrains.kotlin.psi.KtFile import javax.swing.JComponent class ReformatInspection(@JvmField var processChangedFilesOnly: Boolean = false) : LocalInspectionTool() { override fun checkFile(file: PsiFile, manager: InspectionManager, isOnTheFly: Boolean): Array<out ProblemDescriptor>? = checkFile(file, isOnTheFly)?.toTypedArray() private fun checkFile(file: PsiFile, isOnTheFly: Boolean): List<ProblemDescriptor>? { if (file !is KtFile || !file.isWritable || !ProjectRootsUtil.isInProjectSource(file)) { return null } if (processChangedFilesOnly && !VcsFacade.getInstance().hasChanges(file)) { return null } val changes = collectFormattingChanges(file) if (changes.isEmpty()) return null val elements = changes.asSequence().map { val rangeOffset = when (it) { is ShiftIndentInsideRange -> it.range.startOffset is ReplaceWhiteSpace -> it.textRange.startOffset } val leaf = file.findElementAt(rangeOffset) ?: return@map null if (!leaf.isValid) return@map null if (leaf is PsiWhiteSpace && isEmptyLineReformat(leaf, it)) return@map null leaf }.filterNotNull().toList() return elements.map { ProblemDescriptorImpl( it, it, KotlinBundle.message("file.is.not.properly.formatted"), arrayOf(ReformatQuickFix), ProblemHighlightType.GENERIC_ERROR_OR_WARNING, false, null, isOnTheFly ) } } override fun createOptionsPanel(): JComponent = SingleCheckboxOptionsPanel( KotlinBundle.message("apply.only.to.modified.files.for.projects.under.a.version.control"), this, "processChangedFilesOnly", ) private fun isEmptyLineReformat(whitespace: PsiWhiteSpace, change: FormattingChange): Boolean { if (change !is ReplaceWhiteSpace) return false val beforeText = whitespace.text val afterText = change.whiteSpace return beforeText.count { it == '\n' } == afterText.count { it == '\n' } && beforeText.substringAfterLast('\n') == afterText.substringAfterLast('\n') } private object ReformatQuickFix : LocalQuickFix { override fun getFamilyName(): String = KotlinBundle.message("reformat.quick.fix.family.name") override fun applyFix(project: Project, descriptor: ProblemDescriptor) { CodeStyleManager.getInstance(project).reformat(descriptor.psiElement.containingFile) } } }
apache-2.0
53574d77f8532d99a447fa345de8b941
42
158
0.705345
4.973829
false
false
false
false
dkrivoruchko/ScreenStream
app/src/main/kotlin/info/dvkr/screenstream/ui/fragment/SettingsInterfaceFragment.kt
1
11917
package info.dvkr.screenstream.ui.fragment import android.content.ActivityNotFoundException import android.content.Intent import android.graphics.Color import android.net.Uri import android.os.Build import android.os.Bundle import android.view.View import androidx.appcompat.app.AppCompatDelegate import androidx.core.content.ContextCompat import androidx.fragment.app.Fragment import androidx.lifecycle.lifecycleScope import androidx.window.layout.WindowMetricsCalculator import com.afollestad.materialdialogs.LayoutMode import com.afollestad.materialdialogs.MaterialDialog import com.afollestad.materialdialogs.bottomsheets.BottomSheet import com.afollestad.materialdialogs.bottomsheets.setPeekHeight import com.afollestad.materialdialogs.color.ColorPalette import com.afollestad.materialdialogs.color.colorChooser import com.afollestad.materialdialogs.lifecycle.lifecycleOwner import com.afollestad.materialdialogs.list.listItemsSingleChoice import com.elvishew.xlog.XLog import info.dvkr.screenstream.R import info.dvkr.screenstream.common.getLog import info.dvkr.screenstream.common.settings.AppSettings import info.dvkr.screenstream.databinding.FragmentSettingsInterfaceBinding import info.dvkr.screenstream.mjpeg.settings.MjpegSettings import info.dvkr.screenstream.service.helper.NotificationHelper import info.dvkr.screenstream.ui.viewBinding import kotlinx.coroutines.flow.first import kotlinx.coroutines.flow.launchIn import kotlinx.coroutines.flow.onEach import org.koin.android.ext.android.inject class SettingsInterfaceFragment : Fragment(R.layout.fragment_settings_interface) { private val notificationHelper: NotificationHelper by inject() private val appSettings: AppSettings by inject() private val mjpegSettings: MjpegSettings by inject() private val nightModeList = if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.P) listOf( 0 to AppCompatDelegate.MODE_NIGHT_YES, 1 to AppCompatDelegate.MODE_NIGHT_AUTO_BATTERY, 2 to AppCompatDelegate.MODE_NIGHT_NO ) else listOf( 0 to AppCompatDelegate.MODE_NIGHT_YES, 1 to AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM, 2 to AppCompatDelegate.MODE_NIGHT_NO ) private val nightModeOptions by lazy { if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.P) resources.getStringArray(R.array.pref_night_mode_options_api21_28).asList() else resources.getStringArray(R.array.pref_night_mode_options_api29).asList() } private val binding by viewBinding { fragment -> FragmentSettingsInterfaceBinding.bind(fragment.requireView()) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) // Interface - Locale if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { binding.clFragmentSettingsLocale.setOnClickListener { try { startActivity( Intent(android.provider.Settings.ACTION_APP_LOCALE_SETTINGS) .setData(Uri.fromParts("package", requireContext().packageName, null)) ) } catch (ignore: ActivityNotFoundException) { } } } else { // TODO Maybe add for API < 33 https://developer.android.com/about/versions/13/features/app-languages binding.clFragmentSettingsLocale.visibility = View.GONE binding.vFragmentSettingsLocale.visibility = View.GONE } // Interface - Night mode viewLifecycleOwner.lifecycleScope.launchWhenCreated { appSettings.nightModeFlow.onEach { mode -> val index = nightModeList.first { it.second == mode }.first binding.tvFragmentSettingsNightModeSummary.text = nightModeOptions[index] }.launchIn(this) } binding.clFragmentSettingsNightMode.setOnClickListener { viewLifecycleOwner.lifecycleScope.launchWhenCreated { val nightMode = appSettings.nightModeFlow.first() val indexOld = nightModeList.first { it.second == nightMode }.first MaterialDialog(requireActivity(), BottomSheet(LayoutMode.WRAP_CONTENT)).show { adjustPeekHeight() lifecycleOwner(viewLifecycleOwner) title(R.string.pref_night_mode) icon(R.drawable.ic_settings_night_mode_24dp) listItemsSingleChoice(items = nightModeOptions, initialSelection = indexOld) { _, index, _ -> val newNightMode = nightModeList.firstOrNull { item -> item.first == index }?.second ?: throw IllegalArgumentException("Unknown night mode index") viewLifecycleOwner.lifecycleScope.launchWhenCreated { appSettings.setNightMode(newNightMode) } } positiveButton(android.R.string.ok) negativeButton(android.R.string.cancel) } } } // Interface - Device notification settings if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { binding.clFragmentSettingsNotification.setOnClickListener { try { startActivity(notificationHelper.getNotificationSettingsIntent()) } catch (ignore: ActivityNotFoundException) { } } } else { binding.clFragmentSettingsNotification.visibility = View.GONE binding.vFragmentSettingsNotification.visibility = View.GONE } // Interface - Keep awake viewLifecycleOwner.lifecycleScope.launchWhenCreated { binding.cbFragmentSettingsKeepAwake.isChecked = appSettings.keepAwakeFlow.first() } binding.cbFragmentSettingsKeepAwake.setOnClickListener { viewLifecycleOwner.lifecycleScope.launchWhenCreated { appSettings.setKeepAwake(binding.cbFragmentSettingsKeepAwake.isChecked) } } binding.clFragmentSettingsKeepAwake.setOnClickListener { binding.cbFragmentSettingsKeepAwake.performClick() } // Interface - Stop on sleep viewLifecycleOwner.lifecycleScope.launchWhenCreated { binding.cbFragmentSettingsStopOnSleep.isChecked = appSettings.stopOnSleepFlow.first() } binding.cbFragmentSettingsStopOnSleep.setOnClickListener { viewLifecycleOwner.lifecycleScope.launchWhenCreated { appSettings.setStopOnSleep(binding.cbFragmentSettingsStopOnSleep.isChecked) } } binding.clFragmentSettingsStopOnSleep.setOnClickListener { binding.cbFragmentSettingsStopOnSleep.performClick() } // Interface - StartService on boot viewLifecycleOwner.lifecycleScope.launchWhenCreated { binding.cbFragmentSettingsStartOnBoot.isChecked = appSettings.startOnBootFlow.first() } binding.cbFragmentSettingsStartOnBoot.setOnClickListener { viewLifecycleOwner.lifecycleScope.launchWhenCreated { appSettings.setStartOnBoot(binding.cbFragmentSettingsStartOnBoot.isChecked) } } binding.clFragmentSettingsStartOnBoot.setOnClickListener { binding.cbFragmentSettingsStartOnBoot.performClick() } // Interface - Auto start stop viewLifecycleOwner.lifecycleScope.launchWhenCreated { binding.cbFragmentSettingsAutoStartStop.isChecked = appSettings.autoStartStopFlow.first() } binding.cbFragmentSettingsAutoStartStop.setOnClickListener { viewLifecycleOwner.lifecycleScope.launchWhenCreated { appSettings.setAutoStartStop(binding.cbFragmentSettingsAutoStartStop.isChecked) } } binding.clFragmentSettingsAutoStartStop.setOnClickListener { binding.cbFragmentSettingsAutoStartStop.performClick() } // Interface - Notify slow connections viewLifecycleOwner.lifecycleScope.launchWhenCreated { binding.cbFragmentSettingsNotifySlowConnections.isChecked = mjpegSettings.notifySlowConnectionsFlow.first() } binding.cbFragmentSettingsNotifySlowConnections.setOnClickListener { viewLifecycleOwner.lifecycleScope.launchWhenCreated { mjpegSettings.setNotifySlowConnections(binding.cbFragmentSettingsNotifySlowConnections.isChecked) } } binding.clFragmentSettingsNotifySlowConnections.setOnClickListener { binding.cbFragmentSettingsNotifySlowConnections.performClick() } // Interface - Web page Image buttons viewLifecycleOwner.lifecycleScope.launchWhenCreated { binding.cbFragmentSettingsHtmlButtons.isChecked = mjpegSettings.htmlEnableButtonsFlow.first() } binding.cbFragmentSettingsHtmlButtons.setOnClickListener { viewLifecycleOwner.lifecycleScope.launchWhenCreated { mjpegSettings.setHtmlEnableButtons(binding.cbFragmentSettingsHtmlButtons.isChecked) } } binding.clFragmentSettingsHtmlButtons.setOnClickListener { binding.cbFragmentSettingsHtmlButtons.performClick() } // Interface - Web page show "Press START on device" viewLifecycleOwner.lifecycleScope.launchWhenCreated { binding.cbFragmentSettingsHtmlPressStart.isChecked = mjpegSettings.htmlShowPressStartFlow.first() } binding.cbFragmentSettingsHtmlPressStart.setOnClickListener { viewLifecycleOwner.lifecycleScope.launchWhenCreated { mjpegSettings.setHtmlShowPressStart(binding.cbFragmentSettingsHtmlPressStart.isChecked) } } binding.clFragmentSettingsHtmlPressStart.setOnClickListener { binding.cbFragmentSettingsHtmlPressStart.performClick() } // Interface - Web page HTML Back color viewLifecycleOwner.lifecycleScope.launchWhenCreated { mjpegSettings.htmlBackColorFlow.onEach { binding.vFragmentSettingsHtmlBackColor.color = it binding.vFragmentSettingsHtmlBackColor.border = ContextCompat.getColor(requireContext(), R.color.textColorPrimary) }.launchIn(this) } binding.clFragmentSettingsHtmlBackColor.setOnClickListener { viewLifecycleOwner.lifecycleScope.launchWhenCreated { val htmlBackColor = mjpegSettings.htmlBackColorFlow.first() MaterialDialog(requireActivity()).show { lifecycleOwner(viewLifecycleOwner) title(R.string.pref_html_back_color_title) icon(R.drawable.ic_settings_html_back_color_24dp) colorChooser( colors = ColorPalette.Primary + Color.parseColor("#000000"), initialSelection = htmlBackColor, allowCustomArgb = true ) { _, color -> if (htmlBackColor != color) viewLifecycleOwner.lifecycleScope.launchWhenCreated { mjpegSettings.setHtmlBackColor(color) } } positiveButton(android.R.string.ok) negativeButton(android.R.string.cancel) } } } } override fun onStart() { super.onStart() XLog.d(getLog("onStart")) } override fun onStop() { XLog.d(getLog("onStop")) super.onStop() } private fun MaterialDialog.adjustPeekHeight(): MaterialDialog { val metrics = WindowMetricsCalculator.getOrCreate().computeCurrentWindowMetrics(requireActivity()) val heightDp = metrics.bounds.height() / resources.displayMetrics.density if (heightDp < 480f) setPeekHeight(metrics.bounds.height()) return this } }
mit
215add72f163ce24b0fa7e92c7366d3d
47.447154
141
0.689687
5.762573
false
false
false
false
BijoySingh/Quick-Note-Android
base/src/main/java/com/maubis/scarlet/base/settings/sheet/ThemeColorPickerBottomSheet.kt
1
6872
package com.maubis.scarlet.base.settings.sheet import android.app.Dialog import android.graphics.Color import androidx.appcompat.app.AppCompatActivity import com.facebook.litho.ClickEvent import com.facebook.litho.Column import com.facebook.litho.Component import com.facebook.litho.ComponentContext import com.facebook.litho.Row import com.facebook.litho.annotations.LayoutSpec import com.facebook.litho.annotations.OnCreateLayout import com.facebook.litho.annotations.OnEvent import com.facebook.litho.annotations.Prop import com.facebook.yoga.YogaAlign import com.facebook.yoga.YogaEdge import com.maubis.scarlet.base.MainActivityActions import com.maubis.scarlet.base.R import com.maubis.scarlet.base.config.ApplicationBase.Companion.sAppTheme import com.maubis.scarlet.base.main.sheets.InstallProUpsellBottomSheet import com.maubis.scarlet.base.support.sheets.LithoBottomSheet import com.maubis.scarlet.base.support.sheets.LithoOptionsItem import com.maubis.scarlet.base.support.sheets.OptionItemLayout import com.maubis.scarlet.base.support.sheets.getLithoBottomSheetTitle import com.maubis.scarlet.base.support.sheets.openSheet import com.maubis.scarlet.base.support.specs.BottomSheetBar import com.maubis.scarlet.base.support.specs.EmptySpec import com.maubis.scarlet.base.support.specs.RoundIcon import com.maubis.scarlet.base.support.ui.Theme import com.maubis.scarlet.base.support.ui.ThemeManager.Companion.getThemeFromStore import com.maubis.scarlet.base.support.ui.ThemedActivity import com.maubis.scarlet.base.support.ui.sThemeDarkenNoteColor import com.maubis.scarlet.base.support.ui.sThemeIsAutomatic import com.maubis.scarlet.base.support.ui.setThemeFromSystem import com.maubis.scarlet.base.support.utils.FlavorUtils import com.maubis.scarlet.base.support.utils.OsVersionUtils @LayoutSpec object ThemeColorPickerItemSpec { @OnCreateLayout fun onCreate( context: ComponentContext, @Prop theme: Theme, @Prop isDisabled: Boolean, @Prop isSelected: Boolean): Component { val icon = RoundIcon.create(context) .showBorder(true) .iconSizeDip(64f) .iconPaddingDip(16f) .onClick { } .flexGrow(1f) .isClickDisabled(true) .alpha(if (isDisabled) 0.3f else 1f) when (isSelected) { true -> icon.iconRes(R.drawable.ic_done_white_48dp) .bgColorRes(R.color.colorAccent) .iconColor(Color.WHITE) false -> icon.iconRes(R.drawable.icon_realtime_markdown) .bgColorRes(theme.background) .iconColorRes(theme.primaryText) } val row = Row.create(context) .widthPercent(100f) .alignItems(YogaAlign.CENTER) .child(icon) row.clickHandler(ThemeColorPickerItem.onItemClick(context)) return row.build() } @OnEvent(ClickEvent::class) fun onItemClick( context: ComponentContext, @Prop theme: Theme, @Prop isDisabled: Boolean, @Prop onThemeSelected: (Theme) -> Unit) { if (isDisabled) { openSheet(context.androidContext as ThemedActivity, InstallProUpsellBottomSheet()) return } onThemeSelected(theme) } } class ThemeColorPickerBottomSheet : LithoBottomSheet() { var onThemeChange: (Theme) -> Unit = {} override fun getComponent(componentContext: ComponentContext, dialog: Dialog): Component { val column = Column.create(componentContext) .widthPercent(100f) .paddingDip(YogaEdge.VERTICAL, 8f) .paddingDip(YogaEdge.HORIZONTAL, 20f) .child( getLithoBottomSheetTitle(componentContext) .textRes(R.string.theme_page_title) .marginDip(YogaEdge.HORIZONTAL, 0f)) if (OsVersionUtils.canUseSystemTheme()) { column.child( OptionItemLayout.create(componentContext) .option( LithoOptionsItem( title = R.string.theme_use_system_theme, subtitle = R.string.theme_use_system_theme_details, icon = R.drawable.ic_action_color, listener = {}, isSelectable = true, selected = sThemeIsAutomatic, actionIcon = if (FlavorUtils.isLite()) R.drawable.ic_rating else 0 )) .onClick { val context = componentContext.androidContext as AppCompatActivity if (FlavorUtils.isLite()) { openSheet(context, InstallProUpsellBottomSheet()) return@onClick } sThemeIsAutomatic = !sThemeIsAutomatic if (sThemeIsAutomatic) { setThemeFromSystem(context) onThemeChange(sAppTheme.get()) } reset(context, dialog) }) } if (sAppTheme.isNightTheme()) { column.child( OptionItemLayout.create(componentContext) .option( LithoOptionsItem( title = R.string.theme_dark_notes, subtitle = R.string.theme_dark_notes_details, icon = R.drawable.night_mode_white_48dp, listener = {}, isSelectable = true, selected = sThemeDarkenNoteColor, actionIcon = if (FlavorUtils.isLite()) R.drawable.ic_rating else 0 )) .onClick { val context = componentContext.androidContext as AppCompatActivity if (FlavorUtils.isLite()) { openSheet(context, InstallProUpsellBottomSheet()) return@onClick } sThemeDarkenNoteColor = !sThemeDarkenNoteColor context.startActivity(MainActivityActions.COLOR_PICKER.intent(context)) context.finish() }) } if (!sThemeIsAutomatic) { var flex: Row.Builder? = null Theme.values().forEachIndexed { index, theme -> if (index % 4 == 0) { column.child(flex) flex = Row.create(componentContext) .widthPercent(100f) .alignItems(YogaAlign.CENTER) .paddingDip(YogaEdge.VERTICAL, 12f) } val disabled = when { !FlavorUtils.isLite() -> false theme == Theme.DARK || theme == Theme.LIGHT -> false else -> true } flex?.child( ThemeColorPickerItem.create(componentContext) .theme(theme) .isDisabled(disabled) .isSelected(theme.name == getThemeFromStore().name) .onThemeSelected { newTheme -> onThemeChange(newTheme) } .flexGrow(1f)) } column.child(flex) } column.child(EmptySpec.create(componentContext).widthPercent(100f).heightDip(24f)) column.child(BottomSheetBar.create(componentContext) .primaryActionRes(R.string.import_export_layout_exporting_done) .onPrimaryClick { dismiss() }.paddingDip(YogaEdge.VERTICAL, 8f)) return column.build() } }
gpl-3.0
20c8d7271e9d6c60522597d454092dcc
34.979058
92
0.66851
4.289638
false
false
false
false
androidx/androidx
datastore/datastore-sampleapp/src/main/java/com/example/datastoresampleapp/KotlinSerializationActivity.kt
3
4600
/* * Copyright 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.datastoresampleapp import android.os.Bundle import android.os.StrictMode import android.util.Log import android.widget.Button import android.widget.TextView import androidx.appcompat.app.AppCompatActivity import androidx.datastore.core.CorruptionException import androidx.datastore.core.DataStore import androidx.datastore.core.DataStoreFactory import androidx.datastore.core.Serializer import androidx.lifecycle.lifecycleScope import kotlinx.coroutines.flow.catch import kotlinx.coroutines.flow.collect import kotlinx.coroutines.flow.distinctUntilChanged import kotlinx.coroutines.flow.map import kotlinx.coroutines.launch import kotlinx.serialization.Serializable import kotlinx.serialization.SerializationException import kotlinx.serialization.decodeFromString import kotlinx.serialization.encodeToString import kotlinx.serialization.json.Json import java.io.File import java.io.IOException import java.io.InputStream import java.io.OutputStream @OptIn(kotlinx.coroutines.ExperimentalCoroutinesApi::class) class KotlinSerializationActivity : AppCompatActivity() { private val TAG = "SerializationActivity" private val PROTO_STORE_FILE_NAME = "kotlin_serialization_test_file.json" private val settingsStore: DataStore<MySettings> by lazy { DataStoreFactory.create( serializer = MySettingsSerializer ) { File(applicationContext.filesDir, PROTO_STORE_FILE_NAME) } } override fun onCreate(savedInstanceState: Bundle?) { // Strict mode allows us to check that no writes or reads are blocking the UI thread. StrictMode.setThreadPolicy( StrictMode.ThreadPolicy.Builder() .detectDiskReads() .detectDiskWrites() .penaltyDeath() .build() ) super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) setUpProtoDataStoreUi() } private fun setUpProtoDataStoreUi() { findViewById<Button>(R.id.counter_dec).setOnClickListener { lifecycleScope.launch { settingsStore.updateData { currentSettings -> currentSettings.copy( count = currentSettings.count - 1 ) } } } findViewById<Button>(R.id.counter_inc).setOnClickListener { lifecycleScope.launch { settingsStore.updateData { currentSettings -> currentSettings.copy( count = currentSettings.count + 1 ) } } } lifecycleScope.launch { settingsStore.data .catch { e -> if (e is IOException) { Log.e(TAG, "Error reading preferences.", e) emit(MySettings()) } else { throw e } } .map { it.count } .distinctUntilChanged() .collect { counterValue -> findViewById<TextView>(R.id.counter_text_view).text = counterValue.toString() } } } } @Serializable data class MySettings(val count: Int = 0) @OptIn(kotlinx.serialization.ExperimentalSerializationApi::class) object MySettingsSerializer : Serializer<MySettings> { override val defaultValue: MySettings get() = MySettings() override suspend fun readFrom(input: InputStream): MySettings { try { return Json.decodeFromString<MySettings>(input.readBytes().decodeToString()) } catch (serialization: SerializationException) { throw CorruptionException("Unable to read Json", serialization) } } override suspend fun writeTo(t: MySettings, output: OutputStream) { output.write(Json.encodeToString(t).encodeToByteArray()) } }
apache-2.0
0b51cad4e9f723eeb6560d2239b04e7c
33.335821
93
0.655435
5.099778
false
false
false
false
Akkyen/LootChest
src/main/java/de/mydevtime/sponge/plugin/lootchest/commands/SetRandom_CMD.kt
1
1810
package de.mydevtime.sponge.plugin.lootchest.commands import de.mydevtime.sponge.plugin.lootchest.data.Constant import de.mydevtime.sponge.plugin.lootchest.data.RandomData import org.spongepowered.api.command.CommandException import org.spongepowered.api.command.CommandResult import org.spongepowered.api.command.CommandSource import org.spongepowered.api.command.args.CommandContext import org.spongepowered.api.command.source.CommandBlockSource import org.spongepowered.api.command.source.ConsoleSource import org.spongepowered.api.command.spec.CommandExecutor import org.spongepowered.api.entity.living.player.Player class SetRandom_CMD() : CommandExecutor { override fun execute(p0: CommandSource?, p1: CommandContext?): CommandResult { if (p0 == null || p1 == null) { throw NullPointerException("CommandSource or CommandContext or both are null!") } if (p0 is ConsoleSource) { throw CommandException(Constant.ERROR_CMD_CONSOLE) } if (p0 is CommandBlockSource) { throw CommandException(Constant.ERROR_CMD_COMMANDBLOCK) } p1.checkPermission(p0, Constant.PERMISSION_CMD_SETRANDOM) if (p1.hasAny("-help")) { p0.sendMessage(Constant.HELP_CMD_SETRANDOM) return CommandResult.success() } if (p1.hasAny("<Mode>") && p1.hasAny("<Amount>") && p1.hasAny("<Reuse>") && p1.hasAny("<AllowAir>")) { val mode: Int = p1.getOne<Int>("<Mode>").get() val amount: Int = p1.getOne<Int>("<Amount>").get() val reuse: Boolean = p1.getOne<Boolean>("<Reuse>").get() val allowAir: Boolean = p1.getOne<Boolean>("<AllowAir>").get() Constant.MAP_PLAYER_RANDOMDATA.put(p0 as Player, RandomData(mode, amount, reuse, allowAir)) p0.sendMessage(Constant.MSG_CMD_PUNCH) return CommandResult.success() } throw CommandException(Constant.ERROR_CMD_NOARGS) } }
apache-2.0
354ff498ccc3d23d39d550c635b65214
30.224138
102
0.748066
3.447619
false
false
false
false