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
stuartcarnie/toml-plugin
src/main/kotlin/org/toml/lang/colorscheme/TomlColors.kt
1
1066
package org.toml.lang.colorscheme import com.intellij.openapi.editor.DefaultLanguageHighlighterColors import com.intellij.openapi.editor.colors.TextAttributesKey object TomlColors { private fun r(id: String, attrKey: TextAttributesKey) = TextAttributesKey.createTextAttributesKey(id, attrKey) val KEY = r("org.toml.KEY", DefaultLanguageHighlighterColors.KEYWORD) val STRING = r("org.toml.STRING", DefaultLanguageHighlighterColors.STRING) val NUMBER = r("org.toml.NUMBER", DefaultLanguageHighlighterColors.NUMBER) val BOOLEAN = r("org.toml.BOOLEAN", DefaultLanguageHighlighterColors.PREDEFINED_SYMBOL) val DATE = r("org.toml.DATE", DefaultLanguageHighlighterColors.PREDEFINED_SYMBOL) val LINE_COMMENT = r("org.toml.LINE_COMMENT", DefaultLanguageHighlighterColors.LINE_COMMENT) val BRACKETS = r("org.toml.BRACKETS", DefaultLanguageHighlighterColors.BRACKETS) val BRACES = r("org.toml.BRACES", DefaultLanguageHighlighterColors.BRACES) val COMMA = r("org.toml.COMMA", DefaultLanguageHighlighterColors.COMMA) }
mit
3b004e24fe9ab66ecdcfb42681a0ebf2
43.416667
96
0.780488
4.737778
false
false
false
false
djkovrik/YapTalker
app/src/main/java/com/sedsoftware/yaptalker/presentation/custom/glide/OkHttpProgressResponseBody.kt
1
1710
package com.sedsoftware.yaptalker.presentation.custom.glide import com.sedsoftware.yaptalker.presentation.extensions.orZero import okhttp3.HttpUrl import okhttp3.MediaType import okhttp3.ResponseBody import okio.Buffer import okio.BufferedSource import okio.ForwardingSource import okio.Okio import okio.Source import java.io.IOException class OkHttpProgressResponseBody( private val url: HttpUrl, private val responseBody: ResponseBody?, private val progressListener: ResponseProgressListener? ) : ResponseBody() { private var bufferedSource: BufferedSource? = null override fun contentLength(): Long = responseBody?.contentLength().orZero() override fun contentType(): MediaType? = responseBody?.contentType() override fun source(): BufferedSource? { if (bufferedSource == null) { bufferedSource = Okio.buffer(source(responseBody?.source())) } return bufferedSource } @Suppress("NULLABILITY_MISMATCH_BASED_ON_JAVA_ANNOTATIONS") private fun source(source: Source?): Source = object : ForwardingSource(source) { var totalBytesRead = 0L @Throws(IOException::class) override fun read(sink: Buffer, byteCount: Long): Long { val bytesRead = super.read(sink, byteCount) val fullLength = responseBody?.contentLength().orZero() if (bytesRead == -1L) { totalBytesRead = fullLength } else { totalBytesRead += bytesRead } progressListener?.update(url, totalBytesRead, fullLength) return bytesRead } } }
apache-2.0
96cc007104ba96af26d995047b8a853a
30.666667
73
0.653216
5.44586
false
false
false
false
androidx/androidx
room/room-compiler/src/test/test-data/kotlinCodeGen/relations.kt
3
12580
import android.database.Cursor import androidx.room.RoomDatabase import androidx.room.RoomSQLiteQuery import androidx.room.RoomSQLiteQuery.Companion.acquire import androidx.room.util.appendPlaceholders import androidx.room.util.getColumnIndex import androidx.room.util.getColumnIndexOrThrow import androidx.room.util.newStringBuilder import androidx.room.util.query import androidx.room.util.recursiveFetchHashMap import java.lang.Class import java.lang.StringBuilder import java.util.ArrayList import java.util.HashMap import javax.`annotation`.processing.Generated import kotlin.Int import kotlin.Long import kotlin.String import kotlin.Suppress import kotlin.Unit import kotlin.collections.List import kotlin.collections.Set import kotlin.jvm.JvmStatic @Generated(value = ["androidx.room.RoomProcessor"]) @Suppress(names = ["UNCHECKED_CAST", "DEPRECATION"]) public class MyDao_Impl( __db: RoomDatabase, ) : MyDao { private val __db: RoomDatabase init { this.__db = __db } public override fun getSongsWithArtist(): SongWithArtist { val _sql: String = "SELECT * FROM Song" val _statement: RoomSQLiteQuery = acquire(_sql, 0) __db.assertNotSuspendingTransaction() val _cursor: Cursor = query(__db, _statement, true, null) try { val _cursorIndexOfSongId: Int = getColumnIndexOrThrow(_cursor, "songId") val _cursorIndexOfArtistKey: Int = getColumnIndexOrThrow(_cursor, "artistKey") val _collectionArtist: HashMap<Long, Artist?> = HashMap<Long, Artist?>() while (_cursor.moveToNext()) { val _tmpKey: Long _tmpKey = _cursor.getLong(_cursorIndexOfArtistKey) _collectionArtist.put(_tmpKey, null) } _cursor.moveToPosition(-1) __fetchRelationshipArtistAsArtist(_collectionArtist) val _result: SongWithArtist if (_cursor.moveToFirst()) { val _tmpSong: Song val _tmpSongId: Long _tmpSongId = _cursor.getLong(_cursorIndexOfSongId) val _tmpArtistKey: Long _tmpArtistKey = _cursor.getLong(_cursorIndexOfArtistKey) _tmpSong = Song(_tmpSongId,_tmpArtistKey) val _tmpArtist: Artist? val _tmpKey_1: Long _tmpKey_1 = _cursor.getLong(_cursorIndexOfArtistKey) _tmpArtist = _collectionArtist.get(_tmpKey_1) if (_tmpArtist == null) { error("Missing relationship item.") } _result = SongWithArtist(_tmpSong,_tmpArtist) } else { error("Cursor was empty, but expected a single item.") } return _result } finally { _cursor.close() _statement.release() } } public override fun getArtistAndSongs(): ArtistAndSongs { val _sql: String = "SELECT * FROM Artist" val _statement: RoomSQLiteQuery = acquire(_sql, 0) __db.assertNotSuspendingTransaction() val _cursor: Cursor = query(__db, _statement, true, null) try { val _cursorIndexOfArtistId: Int = getColumnIndexOrThrow(_cursor, "artistId") val _collectionSongs: HashMap<Long, ArrayList<Song>> = HashMap<Long, ArrayList<Song>>() while (_cursor.moveToNext()) { val _tmpKey: Long _tmpKey = _cursor.getLong(_cursorIndexOfArtistId) if (!_collectionSongs.containsKey(_tmpKey)) { _collectionSongs.put(_tmpKey, ArrayList<Song>()) } } _cursor.moveToPosition(-1) __fetchRelationshipSongAsSong(_collectionSongs) val _result: ArtistAndSongs if (_cursor.moveToFirst()) { val _tmpArtist: Artist val _tmpArtistId: Long _tmpArtistId = _cursor.getLong(_cursorIndexOfArtistId) _tmpArtist = Artist(_tmpArtistId) val _tmpSongsCollection: ArrayList<Song> val _tmpKey_1: Long _tmpKey_1 = _cursor.getLong(_cursorIndexOfArtistId) _tmpSongsCollection = _collectionSongs.getValue(_tmpKey_1) _result = ArtistAndSongs(_tmpArtist,_tmpSongsCollection) } else { error("Cursor was empty, but expected a single item.") } return _result } finally { _cursor.close() _statement.release() } } public override fun getPlaylistAndSongs(): PlaylistAndSongs { val _sql: String = "SELECT * FROM Playlist" val _statement: RoomSQLiteQuery = acquire(_sql, 0) __db.assertNotSuspendingTransaction() val _cursor: Cursor = query(__db, _statement, true, null) try { val _cursorIndexOfPlaylistId: Int = getColumnIndexOrThrow(_cursor, "playlistId") val _collectionSongs: HashMap<Long, ArrayList<Song>> = HashMap<Long, ArrayList<Song>>() while (_cursor.moveToNext()) { val _tmpKey: Long _tmpKey = _cursor.getLong(_cursorIndexOfPlaylistId) if (!_collectionSongs.containsKey(_tmpKey)) { _collectionSongs.put(_tmpKey, ArrayList<Song>()) } } _cursor.moveToPosition(-1) __fetchRelationshipSongAsSong_1(_collectionSongs) val _result: PlaylistAndSongs if (_cursor.moveToFirst()) { val _tmpPlaylist: Playlist val _tmpPlaylistId: Long _tmpPlaylistId = _cursor.getLong(_cursorIndexOfPlaylistId) _tmpPlaylist = Playlist(_tmpPlaylistId) val _tmpSongsCollection: ArrayList<Song> val _tmpKey_1: Long _tmpKey_1 = _cursor.getLong(_cursorIndexOfPlaylistId) _tmpSongsCollection = _collectionSongs.getValue(_tmpKey_1) _result = PlaylistAndSongs(_tmpPlaylist,_tmpSongsCollection) } else { error("Cursor was empty, but expected a single item.") } return _result } finally { _cursor.close() _statement.release() } } private fun __fetchRelationshipArtistAsArtist(_map: HashMap<Long, Artist?>): Unit { val __mapKeySet: Set<Long> = _map.keys if (__mapKeySet.isEmpty()) { return } if (_map.size > RoomDatabase.MAX_BIND_PARAMETER_CNT) { recursiveFetchHashMap(_map, false) { __fetchRelationshipArtistAsArtist(it) } return } val _stringBuilder: StringBuilder = newStringBuilder() _stringBuilder.append("SELECT `artistId` FROM `Artist` WHERE `artistId` IN (") val _inputSize: Int = __mapKeySet.size appendPlaceholders(_stringBuilder, _inputSize) _stringBuilder.append(")") val _sql: String = _stringBuilder.toString() val _argCount: Int = 0 + _inputSize val _stmt: RoomSQLiteQuery = acquire(_sql, _argCount) var _argIndex: Int = 1 for (_item: Long in __mapKeySet) { _stmt.bindLong(_argIndex, _item) _argIndex++ } val _cursor: Cursor = query(__db, _stmt, false, null) try { val _itemKeyIndex: Int = getColumnIndex(_cursor, "artistId") if (_itemKeyIndex == -1) { return } val _cursorIndexOfArtistId: Int = 0 while (_cursor.moveToNext()) { val _tmpKey: Long _tmpKey = _cursor.getLong(_itemKeyIndex) if (_map.containsKey(_tmpKey)) { val _item_1: Artist val _tmpArtistId: Long _tmpArtistId = _cursor.getLong(_cursorIndexOfArtistId) _item_1 = Artist(_tmpArtistId) _map.put(_tmpKey, _item_1) } } } finally { _cursor.close() } } private fun __fetchRelationshipSongAsSong(_map: HashMap<Long, ArrayList<Song>>): Unit { val __mapKeySet: Set<Long> = _map.keys if (__mapKeySet.isEmpty()) { return } if (_map.size > RoomDatabase.MAX_BIND_PARAMETER_CNT) { recursiveFetchHashMap(_map, true) { __fetchRelationshipSongAsSong(it) } return } val _stringBuilder: StringBuilder = newStringBuilder() _stringBuilder.append("SELECT `songId`,`artistKey` FROM `Song` WHERE `artistKey` IN (") val _inputSize: Int = __mapKeySet.size appendPlaceholders(_stringBuilder, _inputSize) _stringBuilder.append(")") val _sql: String = _stringBuilder.toString() val _argCount: Int = 0 + _inputSize val _stmt: RoomSQLiteQuery = acquire(_sql, _argCount) var _argIndex: Int = 1 for (_item: Long in __mapKeySet) { _stmt.bindLong(_argIndex, _item) _argIndex++ } val _cursor: Cursor = query(__db, _stmt, false, null) try { val _itemKeyIndex: Int = getColumnIndex(_cursor, "artistKey") if (_itemKeyIndex == -1) { return } val _cursorIndexOfSongId: Int = 0 val _cursorIndexOfArtistKey: Int = 1 while (_cursor.moveToNext()) { val _tmpKey: Long _tmpKey = _cursor.getLong(_itemKeyIndex) val _tmpRelation: ArrayList<Song>? = _map.get(_tmpKey) if (_tmpRelation != null) { val _item_1: Song val _tmpSongId: Long _tmpSongId = _cursor.getLong(_cursorIndexOfSongId) val _tmpArtistKey: Long _tmpArtistKey = _cursor.getLong(_cursorIndexOfArtistKey) _item_1 = Song(_tmpSongId,_tmpArtistKey) _tmpRelation.add(_item_1) } } } finally { _cursor.close() } } private fun __fetchRelationshipSongAsSong_1(_map: HashMap<Long, ArrayList<Song>>): Unit { val __mapKeySet: Set<Long> = _map.keys if (__mapKeySet.isEmpty()) { return } if (_map.size > RoomDatabase.MAX_BIND_PARAMETER_CNT) { recursiveFetchHashMap(_map, true) { __fetchRelationshipSongAsSong_1(it) } return } val _stringBuilder: StringBuilder = newStringBuilder() _stringBuilder.append("SELECT `Song`.`songId` AS `songId`,`Song`.`artistKey` AS `artistKey`,_junction.`playlistKey` FROM `PlaylistSongXRef` AS _junction INNER JOIN `Song` ON (_junction.`songKey` = `Song`.`songId`) WHERE _junction.`playlistKey` IN (") val _inputSize: Int = __mapKeySet.size appendPlaceholders(_stringBuilder, _inputSize) _stringBuilder.append(")") val _sql: String = _stringBuilder.toString() val _argCount: Int = 0 + _inputSize val _stmt: RoomSQLiteQuery = acquire(_sql, _argCount) var _argIndex: Int = 1 for (_item: Long in __mapKeySet) { _stmt.bindLong(_argIndex, _item) _argIndex++ } val _cursor: Cursor = query(__db, _stmt, false, null) try { // _junction.playlistKey val _itemKeyIndex: Int = 2 if (_itemKeyIndex == -1) { return } val _cursorIndexOfSongId: Int = 0 val _cursorIndexOfArtistKey: Int = 1 while (_cursor.moveToNext()) { val _tmpKey: Long _tmpKey = _cursor.getLong(_itemKeyIndex) val _tmpRelation: ArrayList<Song>? = _map.get(_tmpKey) if (_tmpRelation != null) { val _item_1: Song val _tmpSongId: Long _tmpSongId = _cursor.getLong(_cursorIndexOfSongId) val _tmpArtistKey: Long _tmpArtistKey = _cursor.getLong(_cursorIndexOfArtistKey) _item_1 = Song(_tmpSongId,_tmpArtistKey) _tmpRelation.add(_item_1) } } } finally { _cursor.close() } } public companion object { @JvmStatic public fun getRequiredConverters(): List<Class<*>> = emptyList() } }
apache-2.0
c1f19c17e7d887b5af5a84df3e548580
39.980456
258
0.558188
4.596273
false
false
false
false
androidx/androidx
health/connect/connect-client/src/main/java/androidx/health/connect/client/records/HipCircumferenceRecord.kt
3
2456
/* * Copyright (C) 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.health.connect.client.records import androidx.annotation.RestrictTo import androidx.health.connect.client.records.metadata.Metadata import androidx.health.connect.client.units.Length import androidx.health.connect.client.units.meters import java.time.Instant import java.time.ZoneOffset /** Captures the user's hip circumference. */ @RestrictTo(RestrictTo.Scope.LIBRARY) public class HipCircumferenceRecord( override val time: Instant, override val zoneOffset: ZoneOffset?, /** Circumference in [Length] unit. Required field. Valid range: 0-10 meters. */ public val circumference: Length, override val metadata: Metadata = Metadata.EMPTY, ) : InstantaneousRecord { init { circumference.requireNotLess(other = circumference.zero(), name = "circumference") circumference.requireNotMore(other = MAX_CIRCUMFERENCE, name = "circumference") } /* * Generated by the IDE: Code -> Generate -> "equals() and hashCode()". */ override fun equals(other: Any?): Boolean { if (this === other) return true if (other !is HipCircumferenceRecord) return false if (circumference != other.circumference) return false if (time != other.time) return false if (zoneOffset != other.zoneOffset) return false if (metadata != other.metadata) return false return true } /* * Generated by the IDE: Code -> Generate -> "equals() and hashCode()". */ override fun hashCode(): Int { var result = circumference.hashCode() result = 31 * result + time.hashCode() result = 31 * result + (zoneOffset?.hashCode() ?: 0) result = 31 * result + metadata.hashCode() return result } private companion object { private val MAX_CIRCUMFERENCE = 10.meters } }
apache-2.0
33b3f706b0d14900b0fefe46ded9d59e
34.594203
90
0.691368
4.263889
false
false
false
false
androidx/androidx
room/room-compiler/src/main/kotlin/androidx/room/solver/query/result/ImmutableMapQueryResultAdapter.kt
3
1970
/* * 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.room.solver.query.result import androidx.room.compiler.codegen.XCodeBlock import androidx.room.compiler.processing.XType import androidx.room.ext.GuavaTypeNames import androidx.room.parser.ParsedQuery import androidx.room.processor.Context import androidx.room.solver.CodeGenScope class ImmutableMapQueryResultAdapter( context: Context, parsedQuery: ParsedQuery, override val keyTypeArg: XType, override val valueTypeArg: XType, private val resultAdapter: QueryResultAdapter ) : MultimapQueryResultAdapter(context, parsedQuery, resultAdapter.rowAdapters) { override fun convert(outVarName: String, cursorVarName: String, scope: CodeGenScope) { scope.builder.apply { val mapVarName = scope.getTmpVar("_mapResult") resultAdapter.convert(mapVarName, cursorVarName, scope) addLocalVariable( name = outVarName, typeName = GuavaTypeNames.IMMUTABLE_MAP.parametrizedBy( keyTypeArg.asTypeName(), valueTypeArg.asTypeName() ), assignExpr = XCodeBlock.of( language = language, format = "%T.copyOf(%L)", GuavaTypeNames.IMMUTABLE_MAP, mapVarName ), ) } } }
apache-2.0
91552f76b08fbd8bdfce05372ff39eac
36.903846
90
0.674619
4.793187
false
false
false
false
mikrobi/TransitTracker_android
app/src/main/java/de/jakobclass/transittracker/services/vehicles/VehicleService.kt
1
4105
package de.jakobclass.transittracker.services.vehicles import android.os.Handler import android.os.Looper import com.google.android.gms.maps.model.LatLngBounds import de.jakobclass.transittracker.models.Position import de.jakobclass.transittracker.models.Vehicle import de.jakobclass.transittracker.models.VehicleType import de.jakobclass.transittracker.network.Api import de.jakobclass.transittracker.services.asRequestParameters import java.lang.ref.WeakReference import java.util.* interface VehicleServiceDelegate { fun vehicleServiceDidAddVehicles(vehicles: Collection<Vehicle>) fun vehicleServiceDidRemoveVehicles(vehicles: Collection<Vehicle>) } class VehicleService : VehicleParsingTaskDelegate { var boundingBox: LatLngBounds? = null set(value) { field = value startPeriodicFetchRunnable() } var delegate: VehicleServiceDelegate? get() = delegateReference.get() set(value) { delegateReference = WeakReference<VehicleServiceDelegate>(value) } val positionUpdateIntervalInMS: Int = 2000 override val vehicles: Map<String, Vehicle> get() = _vehicles var vehicleTypesCode: Int = 0 private var activeVehicleParsingTask: VehicleParsingTask? = null private var delegateReference = WeakReference<VehicleServiceDelegate>(null) private val fetchIntervalInMS: Int = 20000 private var fetchRunnable: Runnable? = null private val mainThreadHandler = Handler(Looper.getMainLooper()) private var positionUpdateRunnable: Runnable? = null private var _vehicles = mutableMapOf<String, Vehicle>() private fun startPeriodicFetchRunnable() { mainThreadHandler.removeCallbacks(fetchRunnable) fetchRunnable = Runnable { fetchVehicles() mainThreadHandler.postDelayed(fetchRunnable!!, fetchIntervalInMS.toLong()) } fetchRunnable!!.run() } private fun fetchVehicles() { boundingBox?.let { var parameters = it.asRequestParameters() parameters["look_productclass"] = vehicleTypesCode parameters["look_json"] = "yes" parameters["tpl"] = "trains2json2" parameters["performLocating"] = 1 parameters["look_nv"] = "zugposmode|2|interval|$fetchIntervalInMS|intervalstep|$positionUpdateIntervalInMS|" Api.requestJSONObject(parameters) { data -> activeVehicleParsingTask?.cancel(false) activeVehicleParsingTask = VehicleParsingTask(this) activeVehicleParsingTask!!.execute(data) } } } private fun startPeriodicPositionUpdateRunnable() { mainThreadHandler.removeCallbacks(positionUpdateRunnable) positionUpdateRunnable = Runnable { updateVehiclePositions() mainThreadHandler.postDelayed(positionUpdateRunnable!!, positionUpdateIntervalInMS.toLong()) } positionUpdateRunnable!!.run() } private fun updateVehiclePositions() { for (vehicle in vehicles.values) { vehicle.updatePosition() } } override fun addOrUpdateVehiclesAndPositions(vehiclesAndPositions: Map<Vehicle, LinkedList<Position>>) { var addedVehicles = mutableSetOf<Vehicle>() var updatedVehicles = mutableSetOf<Vehicle>() for ((vehicle, positions) in vehiclesAndPositions) { vehicle.predictedPositions = positions if (_vehicles.containsKey(vehicle.vehicleId)) { updatedVehicles.add(vehicle) } else { _vehicles[vehicle.vehicleId] = vehicle addedVehicles.add(vehicle) } } val removedVehicles = _vehicles.values.toSet().subtract(addedVehicles).subtract(updatedVehicles) for (vehicle in removedVehicles) { _vehicles.remove(vehicle.vehicleId) } delegate?.vehicleServiceDidAddVehicles(addedVehicles) delegate?.vehicleServiceDidRemoveVehicles(removedVehicles) startPeriodicPositionUpdateRunnable() } }
gpl-3.0
e4b422d71ee110583ec872b121a35191
38.480769
120
0.690865
4.933894
false
false
false
false
slegrand45/todomvc
examples/kotlin-react/src/components/TodoList.kt
4
2114
package components import kotlinx.html.js.onDoubleClickFunction import model.Todo import model.TodoFilter import react.* import react.dom.li import react.dom.ul class TodoList : RComponent<TodoList.Props, TodoList.State>() { override fun componentWillMount() { setState { editingIdx = -1 } } override fun RBuilder.render() { console.log("TodoList render") ul(classes = "todo-list") { val filter = props.filter props.todos.filter { todo -> filter.filter(todo) }.forEachIndexed { idx, todo -> val isEditing = idx == state.editingIdx val classes = when { todo.completed -> "completed" isEditing -> "editing" else -> "" } li(classes = classes) { attrs.onDoubleClickFunction = { setState { editingIdx = idx } } todoItem( todo = todo, editing = isEditing, endEditing = ::endEditing, removeTodo = { props.removeTodo(todo) }, updateTodo = { title, completed -> props.updateTodo(todo.copy(title = title, completed = completed)) } ) } } } } private fun endEditing() { setState { editingIdx = -1 } } class Props(var removeTodo: (Todo) -> Unit, var updateTodo: (Todo) -> Unit, var todos: List<Todo>, var filter: TodoFilter) : RProps class State(var editingIdx: Int) : RState } fun RBuilder.todoList(removeTodo: (Todo) -> Unit, updateTodo: (Todo) -> Unit, todos: List<Todo>, filter: TodoFilter) = child(TodoList::class) { attrs.todos = todos attrs.removeTodo = removeTodo attrs.updateTodo = updateTodo attrs.filter = filter }
mit
0d7cec6c807c0420f236c41644b39bca
27.972603
143
0.486755
5.009479
false
false
false
false
kenrube/Fantlab-client
app/src/main/kotlin/ru/fantlab/android/ui/modules/plans/pubplans/PubplansPresenter.kt
2
3551
package ru.fantlab.android.ui.modules.plans.pubplans import android.view.View import io.reactivex.Single import io.reactivex.functions.Consumer import ru.fantlab.android.data.dao.model.Pubplans import ru.fantlab.android.data.dao.response.PubplansResponse import ru.fantlab.android.helper.FantlabHelper import ru.fantlab.android.provider.rest.DataManager import ru.fantlab.android.provider.rest.PubplansSortOption import ru.fantlab.android.provider.rest.getPubplansPath import ru.fantlab.android.provider.storage.DbProvider import ru.fantlab.android.ui.base.mvp.presenter.BasePresenter class PubplansPresenter : BasePresenter<PubplansMvp.View>(), PubplansMvp.Presenter { private var page: Int = 1 private var sort: FantlabHelper.PubplansSort<PubplansSortOption, Int, Int> = FantlabHelper.PubplansSort(PubplansSortOption.BY_CORRECT, 0, 0) private var previousTotal: Int = 0 private var lastPage: Int = Integer.MAX_VALUE var publishers: List<Pubplans.Publisher> = arrayListOf() override fun onCallApi(page: Int, parameter: Int?): Boolean { if (page == 1) { lastPage = Integer.MAX_VALUE sendToView { it.getLoadMore().reset() } } setCurrentPage(page) if (page > lastPage || lastPage == 0) { sendToView { it.hideProgress() } return false } getPubplans(page, false) return true } override fun getPubplans(page: Int, force: Boolean) { makeRestCall( getPubplansInternal(page, force).toObservable(), Consumer { (response, totalCount, lastPage) -> this.lastPage = lastPage sendToView { with(it) { onNotifyAdapter(response, page) } } } ) } private fun getPubplansInternal(page: Int, force: Boolean) = getPubplansFromServer(page) .onErrorResumeNext { throwable -> if (page == 1 && !force) { getPubplansFromDb(page) } else { throw throwable } } private fun getPubplansFromServer(page: Int): Single<Triple<ArrayList<Pubplans.Object>, Int, Int>> = DataManager.getPubplans(page, sort.sortBy.value, sort.filterLang, sort.filterPublisher) .map { getPubplans(it) } private fun getPubplansFromDb(page: Int): Single<Triple<ArrayList<Pubplans.Object>, Int, Int>> = DbProvider.mainDatabase .responseDao() .get(getPubplansPath(page, sort.sortBy.value, sort.filterLang, sort.filterPublisher)) .map { it.response } .map { PubplansResponse.Deserializer().deserialize(it) } .map { getPubplans(it) } private fun getPubplans(response: PubplansResponse): Triple<ArrayList<Pubplans.Object>, Int, Int> { publishers = response.publisherList return Triple(response.editions.items, response.editions.totalCount, response.editions.last) } override fun setCurrentSort(sortBy: PubplansSortOption?, filterLang: String?, filterPublisher: String?) { sort.sortBy = sortBy ?: sort.sortBy sort.filterLang = filterLang?.toInt() ?: sort.filterLang sort.filterPublisher = filterPublisher?.toInt() ?: sort.filterPublisher getPubplans(1, true) } override fun getCurrentSort() = sort override fun onItemClick(position: Int, v: View?, item: Pubplans.Object) { sendToView { it.onItemClicked(item) } } override fun onItemLongClick(position: Int, v: View?, item: Pubplans.Object) { sendToView { it.onItemLongClicked(position, v, item) } } override fun getCurrentPage(): Int = page override fun getPreviousTotal(): Int = previousTotal override fun setCurrentPage(page: Int) { this.page = page } override fun setPreviousTotal(previousTotal: Int) { this.previousTotal = previousTotal } }
gpl-3.0
066e11dc2007951708aef00bdf180e4f
32.196262
141
0.736412
3.484789
false
false
false
false
sebastiansokolowski/AuctionHunter---Allegro
server/src/main/kotlin/com/sebastiansokolowski/auctionhunter/allegro_api/AllegroAuthClient.kt
1
1992
package com.sebastiansokolowski.auctionhunter.allegro_api import com.sebastiansokolowski.auctionhunter.allegro_api.response.AuthResponse import com.sebastiansokolowski.auctionhunter.allegro_api.response.RefreshTokenResponse import okhttp3.OkHttpClient import okhttp3.logging.HttpLoggingInterceptor import retrofit2.Call import retrofit2.Retrofit import retrofit2.converter.gson.GsonConverterFactory import java.util.* class AllegroAuthClient(private val clientId: String, private val clientSecret: String) { private lateinit var allegroAuthService: AllegroAuthService fun auth(): Call<AuthResponse> { val allegroAuthService = getAllegroAuthService() return allegroAuthService.auth(getAuthorizationHeader(), "client_credentials") } fun refresh(token: String): Call<RefreshTokenResponse> { val allegroAuthService = getAllegroAuthService() return allegroAuthService.refreshToken(getAuthorizationHeader(), "refresh_token", token) } private fun getAuthorizationHeader(): String { val credential = "$clientId:$clientSecret" return "Basic " + String(Base64.getEncoder().encode(credential.toByteArray())) } private fun getAllegroAuthService(): AllegroAuthService { if (!::allegroAuthService.isInitialized) { val retrofit = Retrofit.Builder() .baseUrl(AllegroAuthService.baseUrl) .addConverterFactory(GsonConverterFactory.create()) .client(getOkHttpClient()) .build() allegroAuthService = retrofit.create(AllegroAuthService::class.java) } return allegroAuthService } private fun getOkHttpClient(): OkHttpClient { val httpLoggingInterceptor = HttpLoggingInterceptor() httpLoggingInterceptor.level = HttpLoggingInterceptor.Level.NONE return OkHttpClient.Builder() .addInterceptor(httpLoggingInterceptor) .build() } }
apache-2.0
e8d8e1a9cd665eef34a1cd1200155e0f
36.603774
96
0.716867
4.918519
false
false
false
false
fredyw/leetcode
src/main/kotlin/leetcode/Problem2239.kt
1
543
package leetcode import kotlin.math.abs import kotlin.math.max /** * https://leetcode.com/problems/find-closest-number-to-zero/ */ class Problem2239 { fun findClosestNumber(nums: IntArray): Int { var answer = Int.MIN_VALUE var min = Int.MAX_VALUE for (num in nums) { if (abs(num - 0) < min) { min = abs(num - 0) answer = num } else if (abs(num - 0) == min) { answer = max(answer, num) } } return answer } }
mit
2bb3caa42527792047a61018f9fe8dfe
22.608696
61
0.510129
3.668919
false
false
false
false
StepicOrg/stepic-android
app/src/main/java/org/stepic/droid/adaptive/ui/custom/morphing/MorphingView.kt
2
2795
package org.stepic.droid.adaptive.ui.custom.morphing import android.content.Context import android.graphics.drawable.GradientDrawable import android.util.AttributeSet import android.util.TypedValue import android.widget.FrameLayout import android.widget.TextView import org.stepic.droid.util.KotlinUtil.setIfNot class MorphingView @JvmOverloads constructor(context: Context, attributeSet: AttributeSet? = null, defStyleAttr: Int = 0) : FrameLayout(context, attributeSet, defStyleAttr) { val drawableWrapper = GradientDrawableWrapper(GradientDrawable()) var nestedTextView: TextView? = null init { background = drawableWrapper.drawable } fun setGradientDrawableParams(color: Int, cornerRadius: Float) { drawableWrapper.drawable.shape = GradientDrawable.RECTANGLE drawableWrapper.color = color drawableWrapper.cornerRadius = cornerRadius } fun morph(params: MorphParams) { setIfNot(drawableWrapper::cornerRadius::set, params.cornerRadius, -1f) setIfNot(drawableWrapper::color::set, params.backgroundColor, -1) val lParams = this.layoutParams as MarginLayoutParams setIfNot(lParams::width::set, params.width, -1) setIfNot(lParams::height::set, params.height, -1) setIfNot(lParams::leftMargin::set, params.marginLeft, -1) setIfNot(lParams::topMargin::set, params.marginTop, -1) setIfNot(lParams::rightMargin::set, params.marginRight, -1) setIfNot(lParams::bottomMargin::set, params.marginBottom, -1) layoutParams = lParams nestedTextView?.let { if (params.text != null) it.text = params.text setIfNot({ nestedTextView?.setTextSize(TypedValue.COMPLEX_UNIT_PX, it) }, params.textSize, -1f) } } fun getMorphParams(): MorphParams { val lParams = layoutParams as MarginLayoutParams return MorphParams( drawableWrapper.cornerRadius, drawableWrapper.color, width, height, lParams.leftMargin, lParams.topMargin, lParams.rightMargin, lParams.bottomMargin, nestedTextView?.text?.toString() ?: "", nestedTextView?.textSize ?: -1f ) } val initialMorphParams by lazy { getMorphParams() } data class MorphParams( val cornerRadius: Float = -1f, val backgroundColor: Int = -1, val width: Int = -1, val height: Int = -1, val marginLeft: Int = -1, val marginTop: Int = -1, val marginRight: Int = -1, val marginBottom: Int = -1, val text: String? = null, val textSize: Float = -1f ) }
apache-2.0
6e9f0b1ed67ca44b88b51931b19f2abd
29.391304
141
0.63864
4.544715
false
false
false
false
NerdNumber9/TachiyomiEH
app/src/main/java/eu/kanade/tachiyomi/ui/catalogue/global_search/CatalogueSearchAdapter.kt
1
2745
package eu.kanade.tachiyomi.ui.catalogue.global_search import android.os.Bundle import android.os.Parcelable import android.support.v7.widget.RecyclerView import android.util.SparseArray import eu.davidea.flexibleadapter.FlexibleAdapter import eu.kanade.tachiyomi.source.CatalogueSource /** * Adapter that holds the search cards. * * @param controller instance of [CatalogueSearchController]. */ class CatalogueSearchAdapter(val controller: CatalogueSearchController) : FlexibleAdapter<CatalogueSearchItem>(null, controller, true) { /** * Listen for more button clicks. */ val moreClickListener: OnMoreClickListener = controller /** * Bundle where the view state of the holders is saved. */ private var bundle = Bundle() override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int, payloads: List<Any?>) { super.onBindViewHolder(holder, position, payloads) restoreHolderState(holder) } override fun onViewRecycled(holder: RecyclerView.ViewHolder) { super.onViewRecycled(holder) saveHolderState(holder, bundle) } override fun onSaveInstanceState(outState: Bundle) { val holdersBundle = Bundle() allBoundViewHolders.forEach { saveHolderState(it, holdersBundle) } outState.putBundle(HOLDER_BUNDLE_KEY, holdersBundle) super.onSaveInstanceState(outState) } override fun onRestoreInstanceState(savedInstanceState: Bundle) { super.onRestoreInstanceState(savedInstanceState) bundle = savedInstanceState.getBundle(HOLDER_BUNDLE_KEY) } /** * Saves the view state of the given holder. * * @param holder The holder to save. * @param outState The bundle where the state is saved. */ private fun saveHolderState(holder: RecyclerView.ViewHolder, outState: Bundle) { val key = "holder_${holder.adapterPosition}" val holderState = SparseArray<Parcelable>() holder.itemView.saveHierarchyState(holderState) outState.putSparseParcelableArray(key, holderState) } /** * Restores the view state of the given holder. * * @param holder The holder to restore. */ private fun restoreHolderState(holder: RecyclerView.ViewHolder) { val key = "holder_${holder.adapterPosition}" val holderState = bundle.getSparseParcelableArray<Parcelable>(key) if (holderState != null) { holder.itemView.restoreHierarchyState(holderState) bundle.remove(key) } } interface OnMoreClickListener { fun onMoreClick(source: CatalogueSource) } private companion object { const val HOLDER_BUNDLE_KEY = "holder_bundle" } }
apache-2.0
809d0188bf7cda994b5680f2d3c67115
31.690476
105
0.699818
4.832746
false
false
false
false
Tait4198/hi_pixiv
app/src/main/java/info/hzvtc/hipixiv/data/AppKV.kt
1
1358
package info.hzvtc.hipixiv.data import android.os.Build import info.hzvtc.hipixiv.util.AppUtil class AppKV{ companion object { val CONTENT_TYPE_KEY = "Content-Type" val CONTENT_TYPE = "application/x-www-form-urlencoded" val CONTENT_TYPE_UTF8 = "application/x-www-form-urlencoded;charset=UTF-8" val ACCEPT_LANGUAGE_KEY = "Accept-Language" val ACCEPT_LANGUAGE = AppUtil.getLocalLanguage() val P_APP_VERSION_KEY = "App-Version" val P_APP_VERSION = "5.0.63" val APP_OS_VERSION_KEY = "App-OS-Version" val APP_OS_VERSION = Build.VERSION.RELEASE!! val APP_OS_KEY = "App-OS" val APP_OS = "android" val USER_AGENT_KEY = "User-Agent" val USER_AGENT = "PixivAndroidApp/" + P_APP_VERSION + " (Android " + APP_OS_VERSION + "; " + Build.MODEL + ")" val ACCEPT_ENCODING_KEY = "Accept-Encoding" val ACCEPT_ENCODING_GZIP = "gzip" val ACCEPT_ENCODING_IDE = "identity" val REFERER_KEY = "Referer" val REFERER = "https://app-api.pixiv.net/" val CLIENT_ID = "MOBrBDS8blbauoSck0ZfDbtuzpyT" val CLIENT_SECRET = "lsACyCD94FhDUtGTXi3QzcFE2uU1hqtDaKeqrdwj" val GRANT_TYPE_PASSWORD = "password" val GRANT_TYPE_REFRESH = "refresh_token" val DEVICE_TOKEN = "pixiv" } }
mit
e218bd46ec250c8ffee087bbbb228485
32.121951
81
0.623711
3.296117
false
false
false
false
exponentjs/exponent
packages/expo-dev-menu/android/src/main/java/expo/modules/devmenu/modules/internals/DevMenuInternalMenuControllerModule.kt
2
6413
package expo.modules.devmenu.modules.internals import android.content.ClipData import android.content.ClipboardManager import android.content.Context import android.content.pm.PackageManager import com.facebook.react.bridge.Arguments import com.facebook.react.bridge.Promise import com.facebook.react.bridge.ReactContext import com.facebook.react.bridge.ReadableMap import com.facebook.react.devsupport.DevInternalSettings import expo.modules.devmenu.devtools.DevMenuDevToolsDelegate import expo.modules.devmenu.modules.DevMenuInternalMenuControllerModuleInterface import expo.modules.devmenu.modules.DevMenuManagerProvider import kotlinx.coroutines.launch class DevMenuInternalMenuControllerModule(private val reactContext: ReactContext) : DevMenuInternalMenuControllerModuleInterface { private val devMenuManger by lazy { reactContext .getNativeModule(DevMenuManagerProvider::class.java)!! .getDevMenuManager() } private val devMenuSettings by lazy { devMenuManger.getSettings()!! } override fun dispatchCallableAsync(callableId: String?, args: ReadableMap?, promise: Promise) { if (callableId == null) { promise.reject("ERR_DEVMENU_ACTION_FAILED", "Callable ID not provided.") return } devMenuManger.dispatchCallable(callableId, args) promise.resolve(null) } override fun hideMenu() { devMenuManger.hideMenu() } override fun setOnboardingFinished(finished: Boolean) { devMenuSettings.isOnboardingFinished = finished } override fun getSettingsAsync(promise: Promise) = promise.resolve(devMenuSettings.serialize()) override fun setSettingsAsync(settings: ReadableMap, promise: Promise) { if (settings.hasKey("motionGestureEnabled")) { devMenuSettings.motionGestureEnabled = settings.getBoolean("motionGestureEnabled") } if (settings.hasKey("keyCommandsEnabled")) { devMenuSettings.keyCommandsEnabled = settings.getBoolean("keyCommandsEnabled") } if (settings.hasKey("showsAtLaunch")) { devMenuSettings.showsAtLaunch = settings.getBoolean("showsAtLaunch") } if (settings.hasKey("touchGestureEnabled")) { devMenuSettings.touchGestureEnabled = settings.getBoolean("touchGestureEnabled") } promise.resolve(null) } override fun openDevMenuFromReactNative() { devMenuManger.getSession()?.reactInstanceManager?.devSupportManager?.let { devMenuManger.closeMenu() it.devSupportEnabled = true it.showDevOptionsDialog() } } override fun onScreenChangeAsync(currentScreen: String?, promise: Promise) { devMenuManger.setCurrentScreen(currentScreen) promise.resolve(null) } override fun fetchDataSourceAsync(id: String?, promise: Promise) { if (id == null) { promise.reject("ERR_DEVMENU_FETCH_FAILED", "DataSource ID not provided.") return } devMenuManger.coroutineScope.launch { val data = devMenuManger.fetchDataSource(id) val result = Arguments.fromList(data.map { it.serialize() }) promise.resolve(result) } } override fun getDevSettingsAsync(promise: Promise) { val reactInstanceManager = devMenuManger.getSession()?.reactInstanceManager val map = Arguments.createMap() if (reactInstanceManager != null) { val devDelegate = DevMenuDevToolsDelegate(devMenuManger, reactInstanceManager) val devSettings = devDelegate.devSettings val devInternalSettings = (devSettings as? DevInternalSettings) map.apply { if (devInternalSettings != null) { putBoolean("isDebuggingRemotely", devSettings.isRemoteJSDebugEnabled) putBoolean("isElementInspectorShown", devSettings.isElementInspectorEnabled) putBoolean("isHotLoadingEnabled", devSettings.isHotModuleReplacementEnabled) putBoolean("isPerfMonitorShown", devSettings.isFpsDebugEnabled) } } } promise.resolve(map) } override fun getBuildInfoAsync(promise: Promise) { val map = Arguments.createMap() val packageManager = reactContext.packageManager val packageName = reactContext.packageName val packageInfo = packageManager.getPackageInfo(packageName, 0) var appVersion = packageInfo.versionName val applicationInfo = packageManager.getApplicationInfo(packageName, PackageManager.GET_META_DATA) var appName = packageManager.getApplicationLabel(applicationInfo).toString() val runtimeVersion = getMetadataValue("expo.modules.updates.EXPO_RUNTIME_VERSION") val sdkVersion = getMetadataValue("expo.modules.updates.EXPO_SDK_VERSION") var appIcon = getApplicationIconUri() var hostUrl = reactContext.sourceURL val manifest = devMenuManger.getSession()?.appInfo if (manifest != null) { if (manifest.get("appName") != null) { appName = manifest.get("appName") as String } if (manifest.get("appVersion") != null) { appVersion = manifest.get("appVersion") as String } if (manifest.get("hostUrl") != null) { hostUrl = manifest.get("hostUrl") as String } } map.apply { putString("appVersion", appVersion) putString("appName", appName) putString("appIcon", appIcon) putString("runtimeVersion", runtimeVersion) putString("sdkVersion", sdkVersion) putString("hostUrl", hostUrl) } promise.resolve(map) } override fun copyToClipboardAsync(content: String, promise: Promise) { val clipboard = reactContext.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager val clip = ClipData.newPlainText(null, content) clipboard.setPrimaryClip(clip) promise.resolve(null) } private fun getMetadataValue(key: String): String { val packageManager = reactContext.packageManager val packageName = reactContext.packageName val applicationInfo = packageManager.getApplicationInfo(packageName, PackageManager.GET_META_DATA) return applicationInfo.metaData?.get(key)?.toString() ?: "" } private fun getApplicationIconUri(): String { var appIcon = "" val packageManager = reactContext.packageManager val packageName = reactContext.packageName val applicationInfo = packageManager.getApplicationInfo(packageName, 0) if (applicationInfo.icon != null) { appIcon = "" + applicationInfo.icon } // TODO - figure out how to get resId for AdaptiveIconDrawable icons return appIcon } }
bsd-3-clause
3453513749f2f0b463aa65ab3392d5e1
33.853261
102
0.736629
4.785821
false
false
false
false
cdarras/clamav-client
src/main/kotlin/xyz/capybara/clamav/commands/scan/InStream.kt
1
1954
package xyz.capybara.clamav.commands.scan import xyz.capybara.clamav.commands.scan.result.ScanResult import xyz.capybara.clamav.CommunicationException import java.io.IOException import java.io.InputStream import java.net.InetSocketAddress import java.nio.Buffer import java.nio.ByteBuffer import java.nio.ByteOrder import java.nio.channels.SocketChannel internal class InStream(private val inputStream: InputStream) : ScanCommand() { override val commandString get() = "INSTREAM" override val format get() = CommandFormat.NULL_CHAR override fun send(server: InetSocketAddress): ScanResult { try { SocketChannel.open(server).use { it.write(rawCommand) // ByteBuffer order must be big-endian ( == network byte order) // It is, by default, but it doesn't hurt to set it anyway val length = ByteBuffer.allocate(4).order(ByteOrder.BIG_ENDIAN) val data = ByteArray(CHUNK_SIZE) var chunkSize = CHUNK_SIZE while (chunkSize != -1) { chunkSize = inputStream.read(data) if (chunkSize > 0) { (length as Buffer).clear() (length.putInt(chunkSize) as Buffer).flip() // The format of the chunk is: '<length><data>' it.write(length) it.write(ByteBuffer.wrap(data, 0, chunkSize)) } } (length as Buffer).clear() // Terminate the stream by sending a zero-length chunk (length.putInt(0) as Buffer).flip() it.write(length) return readResponse(it) } } catch (e: IOException) { throw CommunicationException(e) } } companion object { private const val CHUNK_SIZE = 2048 } }
mit
821fb3662c482878fb37f79d88bbeaef
33.280702
79
0.57216
4.64133
false
false
false
false
Adventech/sabbath-school-android-2
common/core/src/main/java/com/cryart/sabbathschool/core/extensions/view/ViewBindingUtils.kt
1
2928
/* * Copyright (c) 2021. Adventech <[email protected]> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.cryart.sabbathschool.core.extensions.view import android.view.LayoutInflater import android.view.View import androidx.appcompat.app.AppCompatActivity import androidx.fragment.app.Fragment import androidx.lifecycle.DefaultLifecycleObserver import androidx.lifecycle.Lifecycle import androidx.lifecycle.LifecycleOwner import androidx.viewbinding.ViewBinding import kotlin.properties.ReadOnlyProperty import kotlin.reflect.KProperty inline fun <T : ViewBinding> AppCompatActivity.viewBinding( crossinline bindingInflater: (LayoutInflater) -> T ): Lazy<T> { return lazy(LazyThreadSafetyMode.NONE) { bindingInflater(layoutInflater) } } fun <T : ViewBinding> Fragment.viewBinding( viewBindingFactory: (View) -> T ): FragmentViewBindingDelegate<T> { return FragmentViewBindingDelegate(this, viewBindingFactory) } class FragmentViewBindingDelegate<T : ViewBinding>( private val fragment: Fragment, private val viewBindingFactory: (View) -> T ) : ReadOnlyProperty<Fragment, T> { private var binding: T? = null init { fragment.lifecycle.addObserver(object : DefaultLifecycleObserver { override fun onDestroy(owner: LifecycleOwner) { binding = null } }) } override fun getValue(thisRef: Fragment, property: KProperty<*>): T { if (binding != null) { return checkNotNull(binding) } val lifecycle = fragment.viewLifecycleOwner.lifecycle if (!lifecycle.currentState.isAtLeast(Lifecycle.State.INITIALIZED)) { throw IllegalStateException("Could not retrieve a view binding when the fragment is not initialized.") } return viewBindingFactory(thisRef.requireView()) .also { binding = it } } }
mit
0c5a0195f4212f8c4494954e83f7e0a8
36.063291
114
0.734631
4.831683
false
false
false
false
JohnnyShieh/Gank
app/src/main/kotlin/com/johnny/gank/widget/BallSpinFadeLoadingIndicator.kt
1
3423
package com.johnny.gank.widget /* * Copyright (C) 2016 Johnny Shieh 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. */ import android.animation.Animator import android.animation.ValueAnimator import android.graphics.Canvas import android.graphics.Paint /** * description * * @author Johnny Shieh ([email protected]) * @version 1.0 */ class BallSpinFadeLoadingIndicator : BaseLoadingIndicator() { private val scaleFloats = arrayOf( SCALE, SCALE, SCALE, SCALE, SCALE, SCALE, SCALE, SCALE) private val alphas = arrayListOf( ALPHA, ALPHA, ALPHA, ALPHA, ALPHA, ALPHA, ALPHA, ALPHA) override fun draw(canvas: Canvas, paint: Paint) { val radius = getWidth() / 10 for (i in 1..7) { canvas.save() val point = circleAt(getWidth(), getHeight(), (getWidth() / 2 - radius).toFloat(), i * (Math.PI / 4)) canvas.translate(point.x, point.y) canvas.scale(scaleFloats[i], scaleFloats[i]) paint.alpha = alphas[i] canvas.drawCircle(0f, 0f, radius.toFloat(), paint) canvas.restore() } } /** * 圆O的圆心为(a,b),半径为R,点A与到X轴的为角α. *则点A的坐标为(a+R*cosα,b+R*sinα) */ private fun circleAt(width: Int, height: Int, radius: Float, angle: Double): Point{ val x = (width / 2 + radius * (Math.cos(angle))).toFloat() val y = (height / 2 + radius * (Math.sin(angle))).toFloat() return Point(x, y) } override fun createAnimation(): List<Animator> { val animators = mutableListOf<Animator>() val delays = arrayOf(0, 120, 240, 360, 480, 600, 720, 780, 840) for (i in 1..7) { val scaleAnim = ValueAnimator.ofFloat(1f, 0.4f, 1f) scaleAnim.duration = 1000 scaleAnim.repeatCount = -1 scaleAnim.startDelay = delays[i].toLong() scaleAnim.addUpdateListener { animation -> scaleFloats[i] = animation.animatedValue as Float postInvalidate() } scaleAnim.start() val alphaAnim = ValueAnimator.ofInt(255, 77, 255) alphaAnim.duration = 1000 alphaAnim.repeatCount = -1 alphaAnim.startDelay = delays[i].toLong() alphaAnim.addUpdateListener { animation -> alphas[i] = animation.animatedValue as Int } alphaAnim.start() animators.add(scaleAnim) animators.add(alphaAnim) } return animators } data class Point(val x: Float, val y: Float) companion object { const val SCALE = 1f const val ALPHA = 255 } }
apache-2.0
6f916e6505fe0ccc856522705c9e47ea
29.709091
113
0.582889
4.114495
false
false
false
false
fcostaa/kotlin-rxjava-android
feature/detail/src/main/kotlin/com/github/felipehjcosta/marvelapp/detail/presentation/CharacterDetailViewModelInputOutput.kt
1
2035
package com.github.felipehjcosta.marvelapp.detail.presentation import com.felipecosta.rxaction.RxAction import com.felipecosta.rxaction.RxCommand import com.github.felipehjcosta.marvelapp.base.character.data.pojo.Character import com.github.felipehjcosta.marvelapp.detail.datamodel.DetailDataModel import io.reactivex.Observable import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.schedulers.Schedulers import javax.inject.Inject class CharacterDetailViewModelInputOutput @Inject constructor( private val characterId: Int, private val dataModel: DetailDataModel ) : CharacterDetailViewModel(), CharacterDetailViewModelInput, CharacterDetailViewModelOutput { override val input: CharacterDetailViewModelInput = this override val output: CharacterDetailViewModelOutput = this private val asyncLoadCharacterAction: RxAction<Any, Character> = RxAction { dataModel.character(characterId) .subscribeOn(Schedulers.newThread()) .observeOn(AndroidSchedulers.mainThread()) } override val characterCommand: RxCommand<Any> get() = asyncLoadCharacterAction private val characterObservable: Observable<Character> = asyncLoadCharacterAction.elements.share() override val name: Observable<String> get() = characterObservable.map { it.name } override val description: Observable<String> get() = characterObservable.map { it.description } override val thumbnailUrl: Observable<String> get() = characterObservable.map { it.thumbnail.url } override val comicsCount: Observable<Int> get() = characterObservable.map { it.comics.items.count() } override val eventsCount: Observable<Int> get() = characterObservable.map { it.events.items.count() } override val seriesCount: Observable<Int> get() = characterObservable.map { it.series.items.count() } override val storiesCount: Observable<Int> get() = characterObservable.map { it.stories.items.count() } }
mit
82d501a762e5680e7057369a3df09b85
37.396226
95
0.755283
4.710648
false
false
false
false
ligi/PassAndroid
android/src/main/java/org/ligi/passandroid/ui/UnzipPassController.kt
1
6449
package org.ligi.passandroid.ui import android.content.Context import android.graphics.Bitmap import android.graphics.BitmapFactory import android.graphics.pdf.PdfRenderer import android.os.Build import android.os.ParcelFileDescriptor import net.lingala.zip4j.ZipFile import net.lingala.zip4j.exception.ZipException import okio.buffer import okio.source import org.json.JSONObject import org.koin.core.component.KoinComponent import org.koin.core.component.inject import org.ligi.passandroid.Tracker import org.ligi.passandroid.functions.createPassForImageImport import org.ligi.passandroid.functions.createPassForPDFImport import org.ligi.passandroid.functions.readJSONSafely import org.ligi.passandroid.model.InputStreamWithSource import org.ligi.passandroid.model.PassStore import org.ligi.passandroid.model.Settings import timber.log.Timber import java.io.File import java.io.FileOutputStream import java.util.* object UnzipPassController : KoinComponent { val tracker :Tracker by inject() val settings : Settings by inject() interface SuccessCallback { fun call(uuid: String) } interface FailCallback { fun fail(reason: String) } fun processInputStream(spec: InputStreamUnzipControllerSpec) { try { val tempFile = File.createTempFile("ins", "pass") spec.inputStreamWithSource.inputStream.copyTo(FileOutputStream(tempFile)) processFile(FileUnzipControllerSpec(tempFile.absolutePath, spec)) tempFile.delete() } catch (e: Exception) { tracker.trackException("problem processing InputStream", e, false) spec.failCallback?.fail("problem with temp file: $e") } } private fun processFile(spec: FileUnzipControllerSpec) { var uuid = UUID.randomUUID().toString() val path = File(spec.context.cacheDir, "temp/$uuid") path.mkdirs() if (!path.exists()) { spec.failCallback?.fail("Problem creating the temp dir: $path") return } File(path, "source.obj").bufferedWriter().write(spec.source) try { val zipFile = ZipFile(spec.zipFileString) zipFile.extractAll(path.absolutePath) } catch (e: ZipException) { e.printStackTrace() } val manifestFile = File(path, "manifest.json") val espassFile = File(path, "main.json") val manifestJSON: JSONObject when { manifestFile.exists() -> try { val readToString = manifestFile.bufferedReader().readText() manifestJSON = readJSONSafely(readToString)!! uuid = manifestJSON.getString("pass.json") } catch (e: Exception) { spec.failCallback?.fail("Problem with manifest.json: $e") return } espassFile.exists() -> try { val readToString = espassFile.bufferedReader().readText() manifestJSON = readJSONSafely(readToString)!! uuid = manifestJSON.getString("id") } catch (e: Exception) { spec.failCallback?.fail("Problem with manifest.json: $e") return } else -> { val bitmap = BitmapFactory.decodeFile(spec.zipFileString) val resources = spec.context.resources if (bitmap != null) { val imagePass = createPassForImageImport(resources) val pathForID = spec.passStore.getPathForID(imagePass.id) pathForID.mkdirs() File(spec.zipFileString).copyTo(File(pathForID, "strip.png")) spec.passStore.save(imagePass) spec.passStore.classifier.moveToTopic(imagePass, "new") spec.onSuccessCallback?.call(imagePass.id) return } if (Build.VERSION.SDK_INT >= 21) { try { val file = File(spec.zipFileString) val readUtf8 = file.source().buffer().readUtf8(4) if (readUtf8 == "%PDF") { val open = ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY) val pdfRenderer = PdfRenderer(open) val page = pdfRenderer.openPage(0) val ratio = page.height.toFloat() / page.width val widthPixels = resources.displayMetrics.widthPixels val createBitmap = Bitmap.createBitmap(widthPixels, (widthPixels * ratio).toInt(), Bitmap.Config.ARGB_8888) page.render(createBitmap, null, null, PdfRenderer.Page.RENDER_MODE_FOR_DISPLAY) val imagePass = createPassForPDFImport(resources) val pathForID = spec.passStore.getPathForID(imagePass.id) pathForID.mkdirs() createBitmap.compress(Bitmap.CompressFormat.PNG, 100, FileOutputStream(File(pathForID, "strip.png"))) spec.passStore.save(imagePass) spec.passStore.classifier.moveToTopic(imagePass, "new") spec.onSuccessCallback?.call(imagePass.id) return } } catch (e: Exception) { e.printStackTrace() } } spec.failCallback?.fail("Pass is not espass or pkpass format :-(") return } } spec.targetPath.mkdirs() val renamedFile = File(spec.targetPath, uuid) if (spec.overwrite && renamedFile.exists()) { renamedFile.deleteRecursively() } if (!renamedFile.exists()) { path.renameTo(renamedFile) } else { Timber.i("Pass with same ID exists") } spec.onSuccessCallback?.call(uuid) } class InputStreamUnzipControllerSpec(internal val inputStreamWithSource: InputStreamWithSource, context: Context, passStore: PassStore, onSuccessCallback: SuccessCallback?, failCallback: FailCallback?) : UnzipControllerSpec(context, passStore, onSuccessCallback, failCallback, settings) }
gpl-3.0
567ae5e4c8af460438475f3fa37c345c
37.159763
191
0.59296
4.949348
false
false
false
false
wordpress-mobile/WordPress-Android
WordPress/src/main/java/org/wordpress/android/ui/deeplinks/DeepLinkingIntentReceiverViewModel.kt
1
7928
package org.wordpress.android.ui.deeplinks import android.net.Uri import android.os.Bundle import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.CoroutineDispatcher import org.wordpress.android.analytics.AnalyticsTracker.Stat.DEEP_LINKED import org.wordpress.android.fluxc.store.AccountStore import org.wordpress.android.modules.UI_THREAD import org.wordpress.android.ui.deeplinks.DeepLinkEntryPoint.WEB_LINKS import org.wordpress.android.ui.deeplinks.DeepLinkNavigator.NavigateAction import org.wordpress.android.ui.deeplinks.DeepLinkNavigator.NavigateAction.LoginForResult import org.wordpress.android.ui.deeplinks.DeepLinkNavigator.NavigateAction.OpenInBrowser import org.wordpress.android.ui.deeplinks.DeepLinkNavigator.NavigateAction.OpenJetpackForDeepLink import org.wordpress.android.ui.deeplinks.DeepLinkNavigator.NavigateAction.OpenLoginPrologue import org.wordpress.android.ui.deeplinks.DeepLinkNavigator.NavigateAction.ShowSignInFlow import org.wordpress.android.ui.deeplinks.handlers.DeepLinkHandlers import org.wordpress.android.ui.deeplinks.handlers.ServerTrackingHandler import org.wordpress.android.util.UriWrapper import org.wordpress.android.util.analytics.AnalyticsUtilsWrapper import org.wordpress.android.viewmodel.Event import org.wordpress.android.viewmodel.ScopedViewModel import javax.inject.Inject import javax.inject.Named @HiltViewModel @Suppress("LongParameterList", "TooManyFunctions") class DeepLinkingIntentReceiverViewModel @Inject constructor( @Named(UI_THREAD) private val uiDispatcher: CoroutineDispatcher, private val deepLinkHandlers: DeepLinkHandlers, private val deepLinkUriUtils: DeepLinkUriUtils, private val accountStore: AccountStore, private val serverTrackingHandler: ServerTrackingHandler, private val deepLinkTrackingUtils: DeepLinkTrackingUtils, private val analyticsUtilsWrapper: AnalyticsUtilsWrapper, private val openWebLinksWithJetpackHelper: DeepLinkOpenWebLinksWithJetpackHelper ) : ScopedViewModel(uiDispatcher) { private val _navigateAction = MutableLiveData<Event<NavigateAction>>() val navigateAction = _navigateAction as LiveData<Event<NavigateAction>> private val _finish = MutableLiveData<Event<Unit>>() val finish = _finish as LiveData<Event<Unit>> private val _showOpenWebLinksWithJetpackOverlay = MutableLiveData<Event<Unit>>() val showOpenWebLinksWithJetpackOverlay = _showOpenWebLinksWithJetpackOverlay as LiveData<Event<Unit>> val toast = deepLinkHandlers.toast private var action: String? = null private var uriWrapper: UriWrapper? = null private var deepLinkEntryPoint = DeepLinkEntryPoint.DEFAULT fun start( action: String?, data: UriWrapper?, entryPoint: DeepLinkEntryPoint, savedInstanceState: Bundle?) { extractSavedInstanceStateIfNeeded(savedInstanceState) applyFromArgsIfNeeded(action, data, entryPoint, savedInstanceState != null) val requestHandled = checkAndShowOpenWebLinksWithJetpackOverlayIfNeeded() if (!requestHandled) handleRequest() } fun handleRequest() { uriWrapper?.let { uri -> if (!handleUrl(uri, action)) { trackWithDeepLinkDataAndFinish() } }?:trackWithDeepLinkDataAndFinish() } private fun trackWithDeepLinkDataAndFinish() { action?.let { analyticsUtilsWrapper.trackWithDeepLinkData( DEEP_LINKED, it,uriWrapper?.host ?: "", uriWrapper?.uri ) } _finish.value = Event(Unit) } fun onSuccessfulLogin() { uriWrapper?.let { handleUrl(it) } } fun writeToBundle(outState: Bundle) { uriWrapper?.let { outState.putParcelable(URI_KEY, it.uri) } outState.putString(DEEP_LINK_ENTRY_POINT_KEY, deepLinkEntryPoint.name) } fun forwardDeepLinkToJetpack() { uriWrapper?.let { if (openWebLinksWithJetpackHelper.handleOpenWebLinksWithJetpack()) { _navigateAction.value = Event(OpenJetpackForDeepLink(action = action, uri = it)) } else { handleRequest() } }?: handleRequest() } /** * Handles the following URLs * `wordpress.com/post...` * `wordpress.com/stats...` * `public-api.wordpress.com/mbar` * and builds the navigation action based on them */ private fun handleUrl(uriWrapper: UriWrapper, action: String? = null): Boolean { return buildNavigateAction(uriWrapper)?.also { if (action != null) { deepLinkTrackingUtils.track(action, it, uriWrapper) } if (loginIsUnnecessary(it)) { _navigateAction.value = Event(it) } else { _navigateAction.value = Event(LoginForResult) } } != null } private fun loginIsUnnecessary(action: NavigateAction): Boolean { return accountStore.hasAccessToken() || action is OpenInBrowser || action is ShowSignInFlow || action is OpenLoginPrologue } private fun buildNavigateAction(uri: UriWrapper, rootUri: UriWrapper = uri): NavigateAction? { return when { deepLinkUriUtils.isTrackingUrl(uri) -> getRedirectUriAndBuildNavigateAction(uri, rootUri) ?.also { // The new URL was build so we need to hit the original `mbar` tracking URL serverTrackingHandler.request(uri) } ?: OpenInBrowser(rootUri.copy(REGULAR_TRACKING_PATH)) deepLinkUriUtils.isWpLoginUrl(uri) -> getRedirectUriAndBuildNavigateAction(uri, rootUri) else -> deepLinkHandlers.buildNavigateAction(uri) } } private fun getRedirectUriAndBuildNavigateAction(uri: UriWrapper, rootUri: UriWrapper): NavigateAction? { return deepLinkUriUtils.getRedirectUri(uri)?.let { buildNavigateAction(it, rootUri) } } private fun extractSavedInstanceStateIfNeeded(savedInstanceState: Bundle?) { savedInstanceState?.let { val uri: Uri? = savedInstanceState.getParcelable(URI_KEY) uriWrapper = uri?.let { UriWrapper(it) } deepLinkEntryPoint = DeepLinkEntryPoint.valueOf( savedInstanceState.getString(DEEP_LINK_ENTRY_POINT_KEY, DeepLinkEntryPoint.DEFAULT.name)) } } private fun applyFromArgsIfNeeded( actionValue: String?, uriValue: UriWrapper?, deepLinkEntryPointValue: DeepLinkEntryPoint, hasSavedInstanceState: Boolean ) { if (hasSavedInstanceState) return action = actionValue uriWrapper = uriValue deepLinkEntryPoint = deepLinkEntryPointValue } private fun checkAndShowOpenWebLinksWithJetpackOverlayIfNeeded() : Boolean { return if (deepLinkEntryPoint == WEB_LINKS && accountStore.hasAccessToken() && // Already logged in openWebLinksWithJetpackHelper.shouldShowDeepLinkOpenWebLinksWithJetpackOverlay()) { openWebLinksWithJetpackHelper.onOverlayShown() _showOpenWebLinksWithJetpackOverlay.value = Event(Unit) true } else { false } } override fun onCleared() { serverTrackingHandler.clear() uriWrapper = null super.onCleared() } companion object { const val HOST_WORDPRESS_COM = "wordpress.com" const val APPLINK_SCHEME = "wordpress://" const val SITE_DOMAIN = "domain" private const val REGULAR_TRACKING_PATH = "bar" private const val URI_KEY = "uri_key" private const val DEEP_LINK_ENTRY_POINT_KEY = "deep_link_entry_point_key" } }
gpl-2.0
fdf187449081db18f2f95b59c64118a7
39.243655
115
0.693113
4.979899
false
false
false
false
KotlinNLP/SimpleDNN
src/main/kotlin/com/kotlinnlp/simplednn/core/layers/models/merge/biaffine/BiaffineBackwardHelper.kt
1
4998
/* Copyright 2016-present The KotlinNLP Authors. All Rights Reserved. * * 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 http://mozilla.org/MPL/2.0/. * ------------------------------------------------------------------*/ package com.kotlinnlp.simplednn.core.layers.models.merge.biaffine import com.kotlinnlp.simplednn.core.arrays.ParamsArray import com.kotlinnlp.simplednn.core.layers.helpers.BackwardHelper import com.kotlinnlp.simplednn.core.optimizer.ParamsErrorsList import com.kotlinnlp.simplednn.simplemath.ndarray.* import com.kotlinnlp.simplednn.simplemath.ndarray.dense.DenseNDArray import com.kotlinnlp.simplednn.simplemath.ndarray.dense.DenseNDArrayFactory import com.kotlinnlp.simplednn.simplemath.ndarray.sparsebinary.SparseBinaryNDArray /** * The helper which executes the backward on a [BiaffineLayer]. * * @property layer the layer in which the backward is executed */ internal class BiaffineBackwardHelper<InputNDArrayType : NDArray<InputNDArrayType>>( override val layer: BiaffineLayer<InputNDArrayType> ) : BackwardHelper<InputNDArrayType>(layer) { /** * Executes the backward calculating the errors of the parameters and eventually of the input through the SGD * algorithm, starting from the preset errors of the output array. * * @param propagateToInput whether to propagate the errors to the input array */ override fun execBackward(propagateToInput: Boolean) { this.layer.applyOutputActivationDeriv() val gwx1: List<DenseNDArray> = this.getWX1ArraysGradients() this.assignParamsGradients(wx1Errors = gwx1) if (propagateToInput) { this.assignLayerGradients(wx1Errors = gwx1) } } /** * */ private fun getWX1ArraysGradients(): List<DenseNDArray> { // TODO: actually the wx errors are Sparse if the input is SparseBinary: calculations should be optimized val x2: InputNDArrayType = this.layer.inputArray2.values val gy: DenseNDArray = this.layer.outputArray.errors return List( size = this.layer.params.outputSize, init = { i -> val gwxi: Double = gy[i] when (x2) { is DenseNDArray -> x2.prod(gwxi) is SparseBinaryNDArray -> { // TODO: actually the wx arrays are sparse, replace with the commented code to optimize further calculations val tmpArray = DenseNDArrayFactory.zeros(shape = x2.shape) val mask: NDArrayMask = x2.mask for (k in 0 until mask.dim1.size) { tmpArray[mask.dim1[k], mask.dim2[k]] = gwxi } tmpArray // val zeros = DenseNDArrayFactory.zeros(shape = x2.shape) // val mask: NDArrayMask = x2.mask // SparseNDArrayFactory.arrayOf( // activeIndicesValues = List( // size = mask.dim1.size, // init = { k -> SparseEntry(Indices(mask.dim1[k], mask.dim2[k]), gwi) } // ), // shape = x2.shape // ) } else -> throw RuntimeException("Invalid input type") } } ) } /** * */ private fun assignParamsGradients(wx1Errors: List<DenseNDArray>) { // TODO: actually the wx errors are Sparse if the input is SparseBinary: calculations should be optimized val x1: InputNDArrayType = this.layer.inputArray1.values val x1T : InputNDArrayType = x1.t val x2: InputNDArrayType = this.layer.inputArray2.values val gy: DenseNDArray = this.layer.outputArray.errors val gwArrays: ParamsErrorsList = this.layer.params.w.map { it.errors } val gw1: NDArray<*> = this.layer.params.w1.errors.values val gw2: NDArray<*> = this.layer.params.w2.errors.values val gb: NDArray<*> = this.layer.params.b.errors.values gwArrays.forEachIndexed { i, gwArray -> val gwi: DenseNDArray = gwArray.values as DenseNDArray val gwx1i: DenseNDArray = wx1Errors[i] gwi.assignDot(gwx1i, x1T) } gw1.assignDot(gy, x1T) gw2.assignDot(gy, x2.t) gb.assignValues(gy) } /** * */ private fun assignLayerGradients(wx1Errors: List<DenseNDArray>) { // TODO: actually the wx errors are Sparse if the input is SparseBinary: calculations should be optimized val w1: DenseNDArray = this.layer.params.w1.values val w2: DenseNDArray = this.layer.params.w2.values val wArrays: List<ParamsArray> = this.layer.params.w val gy: DenseNDArray = this.layer.outputArray.errors val gyT: DenseNDArray = gy.t this.layer.inputArray1.assignErrorsByDotT(gyT, w1) this.layer.inputArray2.assignErrorsByDotT(gyT, w2) wx1Errors.forEachIndexed { i, wx1Error -> val wi: DenseNDArray = wArrays[i].values val wx1i: DenseNDArray = this.layer.wx1Arrays[i] this.layer.inputArray1.errors.assignSum(wx1Error.t.dot(wi)) this.layer.inputArray2.errors.assignSum(wx1i.prod(gy[i])) } } }
mpl-2.0
1fe284ed7a50223df7cebfd19111b990
34.7
120
0.679272
3.944751
false
false
false
false
Turbo87/intellij-rust
src/main/kotlin/org/rust/lang/core/psi/impl/mixin/RustItemImplMixin.kt
1
1262
package org.rust.lang.core.psi.impl.mixin import com.intellij.lang.ASTNode import com.intellij.navigation.ItemPresentation import com.intellij.psi.stubs.IStubElementType import org.rust.lang.core.psi.RustItem import org.rust.lang.core.psi.RustNamedElement import org.rust.lang.core.psi.impl.RustStubbedNamedElementImpl import org.rust.lang.core.stubs.RustItemStub import javax.swing.Icon public abstract class RustItemImplMixin : RustStubbedNamedElementImpl<RustItemStub> , RustItem { constructor(node: ASTNode) : super(node) constructor(stub: RustItemStub, nodeType: IStubElementType<*, *>) : super(stub, nodeType) override val boundElements: Collection<RustNamedElement> get() = listOf(this) override fun getPresentation(): ItemPresentation = object : ItemPresentation { override fun getLocationString(): String? = "(in ${containingFile.name})" override fun getIcon(unused: Boolean): Icon? = [email protected](0) override fun getPresentableText(): String? = name } } val RustItem.isPublic: Boolean get() = vis != null fun RustItem.hasAttribute(name: String): Boolean = outerAttrList.any { it.metaItem?.identifier?.text.equals(name) }
mit
6946b6361ac5a77dc09a70f5e080e91d
32.210526
93
0.731379
4.33677
false
false
false
false
wordpress-mobile/WordPress-Android
WordPress/src/test/java/org/wordpress/android/ui/stats/refresh/lists/sections/insights/usecases/AnnualStatsMapperTest.kt
1
5572
package org.wordpress.android.ui.stats.refresh.lists.sections.insights.usecases import org.assertj.core.api.Assertions.assertThat import org.junit.Before import org.junit.Test import org.junit.runner.RunWith import org.mockito.Mock import org.mockito.junit.MockitoJUnitRunner import org.mockito.kotlin.any import org.mockito.kotlin.eq import org.mockito.kotlin.whenever import org.wordpress.android.R import org.wordpress.android.anyNullable import org.wordpress.android.fluxc.model.stats.YearsInsightsModel.YearInsights import org.wordpress.android.ui.stats.refresh.lists.sections.BlockListItem import org.wordpress.android.ui.stats.refresh.lists.sections.BlockListItem.ListItemWithIcon import org.wordpress.android.ui.stats.refresh.lists.sections.BlockListItem.QuickScanItem import org.wordpress.android.ui.stats.refresh.lists.sections.BlockListItem.Type.LIST_ITEM_WITH_ICON import org.wordpress.android.ui.stats.refresh.lists.sections.BlockListItem.Type.QUICK_SCAN_ITEM import org.wordpress.android.ui.stats.refresh.utils.ContentDescriptionHelper import org.wordpress.android.ui.stats.refresh.utils.StatsUtils @RunWith(MockitoJUnitRunner::class) class AnnualStatsMapperTest { @Mock lateinit var contentDescriptionHelper: ContentDescriptionHelper @Mock lateinit var statsUtils: StatsUtils private lateinit var annualStatsMapper: AnnualStatsMapper private val contentDescription = "title, views" @Before fun setUp() { annualStatsMapper = AnnualStatsMapper(contentDescriptionHelper, statsUtils) whenever(contentDescriptionHelper.buildContentDescription( any(), any<String>() ) ).thenReturn(contentDescription) whenever( statsUtils.toFormattedString( any<Int>(), any() ) ).then { (it.arguments[0] as Int).toString() } whenever( statsUtils.toFormattedString( anyNullable<Double>(), any() ) ).then { (it.arguments[0] as Double).toString() } whenever( statsUtils.toFormattedString( anyNullable<Double>(), any(), eq("0") ) ).then { (it.arguments[0] as Double).toString() } } @Test fun `maps year insights for the card`() { val mappedYear = YearInsights( 2.567, 1.5, 578.1, 536.0, 155, 89, 746, 12, 237, "2019" ) val result = annualStatsMapper.mapYearInBlock(mappedYear) assertThat(result).hasSize(4) assertQuickScanItem(result[0], R.string.stats_insights_year, "2019", R.string.stats_insights_posts, "12") assertQuickScanItem( result[1], R.string.stats_insights_total_comments, "155", R.string.stats_insights_average_comments, "2.567" ) assertQuickScanItem( result[2], R.string.stats_insights_total_likes, "746", R.string.stats_insights_average_likes, "578.1" ) assertQuickScanItem( result[3], R.string.stats_insights_total_words, "237", R.string.stats_insights_average_words, "536.0" ) } @Test fun `maps year insights for the view all`() { val mappedYear = YearInsights( 2.567, 1.5, 578.1, 53.3, 155, 89, 746, 12, 247, "2019" ) val result = annualStatsMapper.mapYearInViewAll(mappedYear) assertThat(result).hasSize(7) assertListItem(result[0], R.string.stats_insights_posts, "12") assertListItem(result[1], R.string.stats_insights_total_comments, "155") assertListItem(result[2], R.string.stats_insights_average_comments, "2.567") assertListItem(result[3], R.string.stats_insights_total_likes, "746") assertListItem(result[4], R.string.stats_insights_average_likes, "578.1") assertListItem(result[5], R.string.stats_insights_total_words, "247") assertListItem(result[6], R.string.stats_insights_average_words, "53.3") } private fun assertQuickScanItem( blockListItem: BlockListItem, startLabel: Int, startValue: String, endLabel: Int, endValue: String ) { assertThat(blockListItem.type).isEqualTo(QUICK_SCAN_ITEM) val item = blockListItem as QuickScanItem assertThat(item.startColumn.label).isEqualTo(startLabel) assertThat(item.startColumn.value).isEqualTo(startValue) assertThat(item.endColumn.label).isEqualTo(endLabel) assertThat(item.endColumn.value).isEqualTo(endValue) } private fun assertListItem( blockListItem: BlockListItem, label: Int, value: String ) { assertThat(blockListItem.type).isEqualTo(LIST_ITEM_WITH_ICON) val item = blockListItem as ListItemWithIcon assertThat(item.textResource).isEqualTo(label) assertThat(item.value).isEqualTo(value) assertThat(item.contentDescription).isEqualTo(contentDescription) } }
gpl-2.0
a4c54acba12b0805914b246f9bf87652
36.395973
113
0.608579
4.4576
false
false
false
false
ingokegel/intellij-community
tools/ideTestingFramework/intellij.tools.ide.starter/src/com/intellij/ide/starter/process/processUtils.kt
2
9454
package com.intellij.ide.starter.process import com.intellij.ide.starter.di.di import com.intellij.ide.starter.path.GlobalPaths import com.intellij.ide.starter.process.exec.ExecOutputRedirect import com.intellij.ide.starter.process.exec.ProcessExecutor import com.intellij.ide.starter.system.SystemInfo import com.intellij.ide.starter.utils.catchAll import com.intellij.ide.starter.utils.logOutput import org.kodein.di.direct import org.kodein.di.instance import java.nio.file.Path import kotlin.io.path.isRegularFile import kotlin.time.Duration.Companion.minutes import kotlin.time.Duration.Companion.seconds // TODO: consider using https://github.com/oshi/oshi for acquiring process info /** * TeamCity may not kill processes started during the build (TW-69045). * They stay alive and consume resources after tests. * This lead to OOM and other errors during tests, for example, * IDEA-256265: shared-indexes tests on Linux suspiciously fail with 137 (killed by OOM) */ fun killOutdatedProcessesOnUnix(commandsToSearch: Iterable<String> = listOf("/perf-startup/")) { if (SystemInfo.isWindows) { logOutput("Current system is Windows. No logic for analysis of outdated processes is yet implemented.") return } val processes = arrayListOf<ProcessMetaInfo>() if (SystemInfo.isLinux) catchAll { processes += dumpListOfProcessesOnLinux() } else catchAll { processes += dumpListOfProcessesOnMacOS() } val processIdsToKill = processes.filter { process -> commandsToSearch.any { process.command.contains(it) } }.map { it.pid } logOutput("These Unix processes must be killed before the next test run: [$processIdsToKill]") for (pid in processIdsToKill) { catchAll { killProcessOnUnix(pid) } } } fun dumpListOfProcessesOnMacOS(): List<MacOsProcessMetaInfo> { check(SystemInfo.isMac) val stdoutRedirect = ExecOutputRedirect.ToString() ProcessExecutor("ps", di.direct.instance<GlobalPaths>().testsDirectory, timeout = 1.minutes, args = listOf("ps", "-ax"), stdoutRedirect = stdoutRedirect ).start() val processLines = stdoutRedirect.read().lines().drop(1).map { it.trim() }.filterNot { it.isBlank() } //PID TTY TIME CMD // 1 ?? 0:43.67 /sbin/launchd val processes = arrayListOf<MacOsProcessMetaInfo>() for (line in processLines) { var rest = line fun nextString(): String { val result = rest.substringBefore(" ").trim() rest = rest.substringAfter(" ").dropWhile { it == ' ' } return result } val pid = nextString().toInt() nextString() //TTY nextString() //TIME val command = rest processes += MacOsProcessMetaInfo(pid, command) } return processes } fun dumpListOfProcessesOnLinux(): List<LinuxProcessMetaInfo> { check(SystemInfo.isLinux) val stdoutRedirect = ExecOutputRedirect.ToString() ProcessExecutor("ps", di.direct.instance<GlobalPaths>().testsDirectory, timeout = 1.minutes, args = listOf("ps", "-aux"), stdoutRedirect = stdoutRedirect ).start() val processLines = stdoutRedirect.read().lines().drop(1).map { it.trim() }.filterNot { it.isBlank() } //USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND //root 823 0.0 0.0 1576524 8128 ? Ssl дек01 0:08 /usr/bin/containerd val processes = arrayListOf<LinuxProcessMetaInfo>() for (line in processLines) { var rest = line fun nextString(): String { val result = rest.substringBefore(" ").trim() rest = rest.substringAfter(" ").dropWhile { it == ' ' } return result } nextString() //user val pid = nextString().toInt() nextString() //cpu nextString() //mem val vsz = nextString().toInt() val rss = nextString().toInt() nextString() //tty nextString() //stat nextString() //start nextString() //time val command = rest processes += LinuxProcessMetaInfo(pid, vsz, rss, command) } return processes } private fun killProcessOnUnix(pid: Int) { check(SystemInfo.isUnix) logOutput("Killing process $pid") ProcessExecutor( "kill-process-$pid", di.direct.instance<GlobalPaths>().testsDirectory, timeout = 1.minutes, args = listOf("kill", "-9", pid.toString()), stdoutRedirect = ExecOutputRedirect.ToStdOut("[kill-$pid-out]"), stderrRedirect = ExecOutputRedirect.ToStdOut("[kill-$pid-err]") ).start() } /** * Workaround for IDEA-251643. * On Linux we run IDE using `xvfb-run` tool wrapper. * Thus we must guess the original java process ID for capturing the thread dumps. * TODO: try to use java.lang.ProcessHandle to get the parent process ID. */ fun getJavaProcessId(javaHome: Path, workDir: Path, originalProcessId: Long, originalProcess: Process): Long { if (!SystemInfo.isLinux) { return originalProcessId } logOutput("Guessing java process ID on Linux (pid of the java process wrapper - $originalProcessId)") val stdout = ExecOutputRedirect.ToString() val stderr = ExecOutputRedirect.ToString() ProcessExecutor( "jcmd-run", workDir, timeout = 1.minutes, args = listOf(javaHome.resolve("bin/jcmd").toAbsolutePath().toString()), stdoutRedirect = stdout, stderrRedirect = stderr ).start() val mergedOutput = stdout.read() + "\n" + stderr.read() val candidates = arrayListOf<Long>() val candidatesFromProcessHandle = arrayListOf<Long>() logOutput("List all java processes IDs:") for (line in mergedOutput.lines().map { it.trim() }.filterNot { it.isEmpty() }) { logOutput(line) /* An example of a process line: 1578401 com.intellij.idea.Main /home/sergey.patrikeev/Documents/intellij/out/perf-startup/tests/IU-211.1852/ijx-jdk-empty/verify-shared-index/temp/projects/idea-startup-performance-project-test-03/idea-startup-performance-project-test-03 An example from TC: intellij project: 81413 com.intellij.idea.Main /opt/teamcity-agent/work/71b862de01f59e23 another project: 84318 com.intellij.idea.Main /opt/teamcity-agent/temp/buildTmp/startupPerformanceTests5985285665047908961/perf-startup/tests/IU-installer-from-file/spring_boot/indexing_oldProjectModel/projects/projects/spring-boot-master/spring-boot-master An example from TC TestsDynamicBundledPluginsStableLinux 1879942 com.intellij.idea.Main /opt/teamcity-agent/temp/buildTmp/startupPerformanceTests4436006118811351792/perf-startup/cache/projects/unpacked/javaproject_1.0.0/java-design-patterns-master */ //TODO(Monitor case /opt/teamcity-agent/work/) val pid = line.substringBefore(" ", "").toLongOrNull() ?: continue if (line.contains("com.intellij.idea.Main") && (line.contains("/perf-startup/tests/") || line.contains( "/perf-startup/cache/") || line.contains("/opt/teamcity-agent/work/"))) { candidates.add(pid) } } originalProcess.toHandle().descendants().forEach { desc -> if (desc.info().command().get().contains("java")) { logOutput("Candidate from ProcessHandle process: ${desc.pid()}") logOutput("command: ${desc.info().command()}") candidatesFromProcessHandle.add(desc.pid()) } } if (candidates.isEmpty() && candidatesFromProcessHandle.isNotEmpty()) { logOutput("Candidates from jcmd are missing, will be used first one from ProcessHandle instead: " + candidatesFromProcessHandle.first()) candidates.add(candidatesFromProcessHandle.first()) } if (candidates.isNotEmpty()) { logOutput("Found the following java process ID candidates: " + candidates.joinToString()) if (originalProcessId in candidates) { return originalProcessId } return candidates.first() } else { return originalProcessId } } fun collectJavaThreadDump( javaHome: Path, workDir: Path, javaProcessId: Long, dumpFile: Path, includeStdout: Boolean = true ) { val ext = if (SystemInfo.isWindows) ".exe" else "" val jstackPath = listOf( javaHome.resolve("bin/jstack$ext"), javaHome.parent.resolve("bin/jstack$ext") ).map { it.toAbsolutePath() }.firstOrNull { it.isRegularFile() } ?: error("Failed to locate jstack under $javaHome") val command = listOf(jstackPath.toAbsolutePath().toString(), "-l", javaProcessId.toString()) ProcessExecutor( "jstack", workDir, timeout = 1.minutes, args = command, stdoutRedirect = ExecOutputRedirect.ToFile(dumpFile.toFile()), stderrRedirect = ExecOutputRedirect.ToStdOut("[jstack-err]") ).start() if (includeStdout) { logOutput("jstack output:\n${dumpFile.toFile().readLines().joinToString("\n")}") } } fun destroyGradleDaemonProcessIfExists() { val stdout = ExecOutputRedirect.ToString() ProcessExecutor( "get jps process", workDir = null, timeout = 30.seconds, args = listOf("jps", "-l"), stdoutRedirect = stdout ).start() logOutput("List of java processes: " + stdout.read()) if (stdout.read().contains("GradleDaemon")) { val readLines = stdout.read().split('\n') readLines.forEach { if (it.contains("GradleDaemon")) { logOutput("Killing GradleDaemon process") val processId = it.split(" ").first().toLong() // get up-to date process list on every iteration ProcessHandle.allProcesses() .filter { ph -> ph.isAlive && ph.pid() == processId } .forEach { ph -> ph.destroy() } } } } }
apache-2.0
8208b8ba6676380ed5d525515aef837f
35.210728
244
0.69199
4.130682
false
true
false
false
mdaniel/intellij-community
plugins/kotlin/frontend-independent/src/org/jetbrains/kotlin/idea/quickfix/AddToStringFix.kt
1
1823
// 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.LowPriorityAction import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.base.psi.replaced import org.jetbrains.kotlin.idea.codeinsight.api.classic.quickfixes.KotlinPsiOnlyQuickFixAction import org.jetbrains.kotlin.idea.inspections.KotlinUniversalQuickFix 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.psi.psiUtil.endOffset class AddToStringFix(element: KtExpression, private val useSafeCallOperator: Boolean) : KotlinPsiOnlyQuickFixAction<KtExpression>(element), KotlinUniversalQuickFix, LowPriorityAction { override fun getFamilyName() = KotlinBundle.message("fix.add.tostring.call.family") override fun getText(): String { return when (useSafeCallOperator) { true -> KotlinBundle.message("fix.add.tostring.call.text.safe") false -> KotlinBundle.message("fix.add.tostring.call.text") } } override fun invoke(project: Project, editor: Editor?, file: KtFile) { val element = element ?: return val pattern = if (useSafeCallOperator) "$0?.toString()" else "$0.toString()" val expressionToInsert = KtPsiFactory(file).createExpressionByPattern(pattern, element) val newExpression = element.replaced(expressionToInsert) editor?.caretModel?.moveToOffset(newExpression.endOffset) } }
apache-2.0
9eb9bb31ac343aae8155239ca278c35b
49.666667
158
0.77729
4.468137
false
false
false
false
mdaniel/intellij-community
plugins/kotlin/idea/tests/testData/codeInsight/codeVision/ClassPropertyUsages.kt
12
397
// MODE: usages <# block [ 1 Usage] #> interface SomeClass { <# block [ 3 Usages] #> var someProperty = "initialized" fun someFun() = "it's " + someProperty // <== (1): reference from expression } fun main() { val instance = object: SomeClass {} val someString = instance.someProperty // <== (2): getter call instance.someProperty = "anotherValue" // <== (3): setter call
apache-2.0
42c6172a90fec49ddc59ad4978a1d33f
29.615385
80
0.619647
3.854369
false
false
false
false
Major-/Vicis
modern/src/main/kotlin/rs/emulate/modern/codec/Container.kt
1
3967
package rs.emulate.modern.codec import com.google.common.collect.Iterators import io.netty.buffer.ByteBuf import io.netty.buffer.Unpooled import rs.emulate.util.compression.* import rs.emulate.util.crypto.xtea.XteaKey import rs.emulate.util.crypto.xtea.xteaDecrypt import rs.emulate.util.crypto.xtea.xteaEncrypt class Container(val compression: CompressionType, buffer: ByteBuf) { var buffer = buffer get() = field.slice() /* returns an immutable buffer */ fun write(key: XteaKey = XteaKey.NONE): ByteBuf { val buf = Unpooled.buffer() buf.writeByte(compression.id) val data = when (compression) { CompressionType.NONE -> buffer.slice() CompressionType.BZIP2 -> buffer.slice().bzip2() CompressionType.GZIP -> buffer.slice().gzip() CompressionType.LZMA -> buffer.slice().lzma() } buf.writeInt(data.readableBytes()) val start = buf.writerIndex() if (compression !== CompressionType.NONE) { buf.writeInt(buffer.readableBytes()) } buf.writeBytes(data) if (!key.isZero) { val end = buf.writerIndex() buf.xteaEncrypt(start, end, key) } return buf.asReadOnly() } companion object { /* accepts any buffer, returns a Container that contains an immutable buffer */ fun ByteBuf.readContainer(key: XteaKey = XteaKey.NONE): Container { var buf = this val compressionOrdinal = buf.readUnsignedByte().toInt() val compression = checkNotNull(CompressionType[compressionOrdinal]) { "Invalid compression type $compressionOrdinal." } val length = buf.readInt() var origBuf: ByteBuf? = null if (!key.isZero) { origBuf = buf buf = buf.copy() val start = buf.readerIndex() val end = if (compression === CompressionType.NONE) { start + length } else { start + length + Int.SIZE_BYTES } buf.xteaDecrypt(start, end, key) } val uncompressedLength = if (compression === CompressionType.NONE) { length } else { origBuf?.skipBytes(Int.SIZE_BYTES) buf.readInt() } var data = if (key.isZero && compression === CompressionType.NONE) { buf.readBytes(length) } else { /* * If the container is encrypted, we can use readSlice() as we are already operating on a copy. * If the container is compressed, we can use readSlice() as the decompression functions create a copy. */ buf.readSlice(length) } origBuf?.skipBytes(length) data = when (compression) { CompressionType.NONE -> data CompressionType.BZIP2 -> data.bunzip2(uncompressedLength) CompressionType.GZIP -> data.gunzip(uncompressedLength) CompressionType.LZMA -> data.unlzma(uncompressedLength) } return Container(compression, data.asReadOnly()) } /* accepts any buffer, returns an immutable buffer */ fun pack(buffer: ByteBuf, key: XteaKey = XteaKey.NONE): ByteBuf { val it = Iterators.forArray(*CompressionType.values()) var type = it.next() var container = Container(type, buffer).write(key) while (it.hasNext()) { type = it.next() val tempContainer = Container(type, buffer).write(key) if (tempContainer.readableBytes() < container.readableBytes()) { container = tempContainer } } return container } } }
isc
27743d6dcfd602e45179bbab56cf15eb
31.252033
119
0.558609
4.879459
false
false
false
false
gdg-belfast/bookmark
app/src/main/java/com/joocy/bookmark/BookmarkAdapter.kt
1
3201
package com.joocy.bookmark import android.content.Context import android.content.Intent import android.support.v7.widget.RecyclerView import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.TextView import com.joocy.bookmark.data.BookmarkRepositoryListener import com.joocy.bookmark.data.BookmarkRepository import com.joocy.bookmark.model.Bookmark /** * BookmarkAdapter is the class responsible for telling the Recyclerview on the main activity * how to display bookmarks. It sits between the Recyclerview component and the data source * as well as providing the view holder that the Recyclerview uses to actually display the * bookmarks. * * When the Recyclerview is displayed, it will ask the adapter how many items there are to * display (by calling getItemCount()), and ask the adapter to create a viewholder (the callback * onCreateViewHolder(ViewGroup?, int) will be called). Then, for every item that the Recyclerview * needs to display, it will call the onBindViewHolder(ViewHolder?, int) method so that the * adapter can bind the data at the position requested to the viewholder supplied. */ class BookmarkAdapter(val context: Context, val dataservice: BookmarkRepository): RecyclerView.Adapter<BookmarkViewholder>(),BookmarkRepositoryListener { override fun getItemCount(): Int = dataservice.count() override fun onBindViewHolder(holder: BookmarkViewholder?, position: Int) { Log.d("BookmarkAdapter", "Displaying bookmark at position " + position.toString()) val bookmarks = dataservice.getAllBookmarks() holder?.displayBookmark(bookmarks[position]) } override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): BookmarkViewholder { Log.d("BookmarkAdapter", "Creating view holder") val view = LayoutInflater.from(parent?.context).inflate(R.layout.layout_bookmark_item, parent, false) return BookmarkViewholder(context, view) } override fun onRepositoryUpdate() { notifyDataSetChanged() } } /** * BookmarkViewholder is a wrapper around the view used by the RecyclerView to display * a line in the list. The ViewHolder is responsible for taking a Bookmark and binding * its members to the components in the view. */ class BookmarkViewholder(context: Context, view: View): RecyclerView.ViewHolder(view) { val bookmarkName: TextView val bookmarkUrl: TextView val bookmarkRow: View init { bookmarkName = view.findViewById<TextView>(R.id.bookmarkName) bookmarkUrl = view.findViewById<TextView>(R.id.bookmarkURL) bookmarkRow = view.findViewById<View>(R.id.bookmarkRow) bookmarkRow.setOnClickListener { _ -> val intent = Intent(BookmarkListActivity.ACTION_DISPLAY_BOOKMARK) intent.putExtra("bookmark", Bookmark(bookmarkUrl.text.toString(), bookmarkName.text.toString())) context.startActivity(intent) } } fun displayBookmark(bookmark: Bookmark) { Log.d("BookmarkViewHolder", "Displaying bookmark") bookmarkName.setText(bookmark.name) bookmarkUrl.setText(bookmark.url) } }
bsd-3-clause
82da72ae4b02fd86804bf1f6632b9414
39.531646
151
0.747579
4.51481
false
false
false
false
Major-/Vicis
common/src/main/kotlin/rs/emulate/common/config/npc/MovementAnimationSet.kt
1
1963
package rs.emulate.common.config.npc import io.netty.buffer.ByteBuf /** * A wrapper class containing four movement animations used by an npc. * * @param walking The walking animation id. * @param halfTurn The half turn animation id. * @param clockwiseQuarterTurn The clockwise quarter turn animation id. * @param anticlockwiseQuarterTurn The anticlockwise quarter turn animation id. */ data class MovementAnimationSet( val walking: Int, val halfTurn: Int, val clockwiseQuarterTurn: Int, val anticlockwiseQuarterTurn: Int ) { init { require(walking >= -1 && halfTurn >= -1 && clockwiseQuarterTurn >= -1 && anticlockwiseQuarterTurn >= -1) { "Specified animation ids must be greater than or equal to -1." } } companion object { /** * The empty MovementAnimationSet instance, to be used as the default value. */ val EMPTY = MovementAnimationSet(-1, -1, -1, -1) /** * Decodes a MovementAnimationSet from the specified [ByteBuf]. */ fun decode(buffer: ByteBuf): MovementAnimationSet { val walking = buffer.readUnsignedShort() val halfTurn = buffer.readUnsignedShort() val clockwiseQuarterTurn = buffer.readUnsignedShort() val anticlockwiseQuarterTurn = buffer.readUnsignedShort() return MovementAnimationSet( walking, halfTurn, clockwiseQuarterTurn, anticlockwiseQuarterTurn ) } /** * Encodes the specified [MovementAnimationSet] into the specified [ByteBuf]. */ fun encode(buffer: ByteBuf, set: MovementAnimationSet): ByteBuf { return buffer.writeShort(set.walking) .writeShort(set.halfTurn) .writeShort(set.clockwiseQuarterTurn) .writeShort(set.anticlockwiseQuarterTurn) } } }
isc
7fead26bae6cae6719bae7df3dd224b2
31.180328
114
0.625064
4.684964
false
false
false
false
Major-/Vicis
legacy/src/main/kotlin/rs/emulate/legacy/widget/type/InventoryWidget.kt
1
3576
package rs.emulate.legacy.widget.type import io.netty.buffer.ByteBuf import io.netty.buffer.Unpooled import rs.emulate.legacy.widget.Widget import rs.emulate.legacy.widget.WidgetGroup import rs.emulate.legacy.widget.WidgetGroup.INVENTORY import rs.emulate.legacy.widget.WidgetOption import rs.emulate.legacy.widget.script.LegacyClientScript import rs.emulate.util.Point import rs.emulate.util.writeAsciiString /** * Contains properties used by [WidgetGroup.INVENTORY]. * * @param id The id of the TextWidget. * @param parent The parent id of the TextWidget. * @param optionType The [WidgetOption] of the TextWidget. * @param content The content type of the TextWidget. * @param width The width of the TextWidget, in pixels. * @param height The width of the TextWidget, in pixels. * @param alpha The alpha of the TextWidget, in pixels. * @param hover The hover id of the TextWidget. * @param scripts The [List] of [LegacyClientScript]s. * @param option The [Option] of the InventoryWidget. * @param hoverText The hover text of the InventoryWidget. * @param swappable Whether or not items in the inventory are swappable. * @param usable Whether or not the items in the inventory are usable. * @param replace Whether or not items in the inventory are replaced (instead of swapped). * @param padding The [Point] containing the padding for the sprites. * @param sprites The [List] of sprite names. * @param spritePoints The List of Points for the sprites. * @param actions The List of menu actions. */ class InventoryWidget( id: Int, parent: Int?, optionType: WidgetOption, content: Int, width: Int, height: Int, alpha: Int, hover: Int?, scripts: List<LegacyClientScript>, option: Option?, hoverText: String?, private val swappable: Boolean, private val usable: Boolean, private val replace: Boolean, private val padding: Point, private val sprites: List<String?>, private val spritePoints: List<Point>, private val actions: List<String> ) : Widget(id, parent, INVENTORY, optionType, content, width, height, alpha, hover, scripts, option, hoverText) { init { require(sprites.size == spritePoints.size) { "Sprite names and Points must have an equal size." } } public override fun encodeBespoke(): ByteBuf { var size = actions.map(String::length).sum() + actions.size size += sprites.map { name -> (name?.length ?: 0) + 2 * java.lang.Short.BYTES + java.lang.Byte.BYTES }.sum() val action = Unpooled.buffer(size) actions.forEach { action.writeAsciiString(it) } size = sprites.map { name -> (name?.length ?: 0) + 2 * java.lang.Short.BYTES + java.lang.Byte.BYTES }.sum() val sprite = Unpooled.buffer(size) for (index in sprites.indices) { val name = sprites[index] sprite.writeBoolean(name != null) if (name != null) { val point = spritePoints[index] sprite.writeShort(point.x).writeShort(point.y) sprite.writeAsciiString(name) } } val buffer = Unpooled.buffer(6 * java.lang.Byte.BYTES + action.readableBytes() + sprite.readableBytes()) // TODO use composite buffer buffer.writeBoolean(swappable) buffer.writeBoolean(actions.isEmpty()) buffer.writeBoolean(usable) buffer.writeBoolean(replace) buffer.writeByte(padding.x).writeByte(padding.y) buffer.writeBytes(sprite) buffer.writeBytes(action) return buffer } }
isc
9691572dd90e5981e73fe046d721e9c4
38.296703
113
0.685123
4.040678
false
false
false
false
GunoH/intellij-community
plugins/kotlin/base/facet/src/org/jetbrains/kotlin/idea/facet/KotlinFacetModificationTracker.kt
2
2344
// 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.facet import com.intellij.openapi.Disposable import com.intellij.openapi.components.service import com.intellij.openapi.project.Project import com.intellij.openapi.util.SimpleModificationTracker import com.intellij.workspaceModel.ide.WorkspaceModelChangeListener import com.intellij.workspaceModel.ide.WorkspaceModelTopics import com.intellij.workspaceModel.storage.VersionedStorageChange import com.intellij.workspaceModel.storage.bridgeEntities.FacetEntity import com.intellij.workspaceModel.storage.bridgeEntities.ModuleEntity import org.jetbrains.kotlin.idea.base.util.caching.oldEntity import org.jetbrains.kotlin.idea.base.util.caching.newEntity class KotlinFacetModificationTracker(project: Project) : SimpleModificationTracker(), WorkspaceModelChangeListener, Disposable { init { project.messageBus.connect(this).subscribe(WorkspaceModelTopics.CHANGED, this) } override fun changed(event: VersionedStorageChange) { val moduleChanges = event.getChanges(ModuleEntity::class.java) val facetChanges = event.getChanges(FacetEntity::class.java) if (moduleChanges.isEmpty() && facetChanges.isEmpty()) return for (facetChange in facetChanges) { val kotlinFacetEntity = facetChange.oldEntity()?.takeIf { it.isKotlinFacet() } ?: facetChange.newEntity() ?.takeIf { it.isKotlinFacet() } if (kotlinFacetEntity != null) { incModificationCount() return } } for (moduleChange in moduleChanges) { val kotlinModuleEntity = moduleChange.oldEntity()?.takeIf { it.facets.any { facet -> facet.isKotlinFacet() } } ?: moduleChange.newEntity() ?.takeIf { it.facets.any { facet -> facet.isKotlinFacet() } } if (kotlinModuleEntity != null) { incModificationCount() return } } } override fun dispose() = Unit companion object { fun FacetEntity.isKotlinFacet() = name == KotlinFacetType.NAME @JvmStatic fun getInstance(project: Project): KotlinFacetModificationTracker = project.service() } }
apache-2.0
1880d9487a6fe5eefa2ab761fb9f0319
40.857143
129
0.703072
5.04086
false
false
false
false
GunoH/intellij-community
platform/workspaceModel/storage/src/com/intellij/workspaceModel/storage/bridgeEntities/module.kt
1
8599
// 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.bridgeEntities import com.intellij.workspaceModel.storage.* import com.intellij.workspaceModel.storage.impl.containers.toMutableWorkspaceList import com.intellij.workspaceModel.storage.url.VirtualFileUrl import org.jetbrains.deft.ObjBuilder import org.jetbrains.deft.Type import org.jetbrains.deft.annotations.Child import com.intellij.workspaceModel.storage.EntitySource import com.intellij.workspaceModel.storage.GeneratedCodeApiVersion import com.intellij.workspaceModel.storage.MutableEntityStorage import com.intellij.workspaceModel.storage.WorkspaceEntity interface ModuleEntity : WorkspaceEntityWithSymbolicId { val name: String val type: String? val dependencies: List<ModuleDependencyItem> val contentRoots: List<@Child ContentRootEntity> @Child val customImlData: ModuleCustomImlDataEntity? @Child val groupPath: ModuleGroupPathEntity? @Child val javaSettings: JavaModuleSettingsEntity? @Child val exModuleOptions: ExternalSystemModuleOptionsEntity? val facets: List<@Child FacetEntity> override val symbolicId: ModuleId get() = ModuleId(name) //region generated code @GeneratedCodeApiVersion(1) interface Builder : ModuleEntity, WorkspaceEntity.Builder<ModuleEntity>, ObjBuilder<ModuleEntity> { override var entitySource: EntitySource override var name: String override var type: String? override var dependencies: MutableList<ModuleDependencyItem> override var contentRoots: List<ContentRootEntity> override var customImlData: ModuleCustomImlDataEntity? override var groupPath: ModuleGroupPathEntity? override var javaSettings: JavaModuleSettingsEntity? override var exModuleOptions: ExternalSystemModuleOptionsEntity? override var facets: List<FacetEntity> } companion object : Type<ModuleEntity, Builder>() { operator fun invoke(name: String, dependencies: List<ModuleDependencyItem>, entitySource: EntitySource, init: (Builder.() -> Unit)? = null): ModuleEntity { val builder = builder() builder.name = name builder.dependencies = dependencies.toMutableWorkspaceList() builder.entitySource = entitySource init?.invoke(builder) return builder } } //endregion } //region generated code fun MutableEntityStorage.modifyEntity(entity: ModuleEntity, modification: ModuleEntity.Builder.() -> Unit) = modifyEntity( ModuleEntity.Builder::class.java, entity, modification) var ModuleEntity.Builder.facetOrder: @Child FacetsOrderEntity? by WorkspaceEntity.extension() var ModuleEntity.Builder.sourceRoots: List<SourceRootEntity> by WorkspaceEntity.extension() //endregion interface ModuleCustomImlDataEntity : WorkspaceEntity { val module: ModuleEntity val rootManagerTagCustomData: String? val customModuleOptions: Map<String, String> //region generated code @GeneratedCodeApiVersion(1) interface Builder : ModuleCustomImlDataEntity, WorkspaceEntity.Builder<ModuleCustomImlDataEntity>, ObjBuilder<ModuleCustomImlDataEntity> { override var entitySource: EntitySource override var module: ModuleEntity override var rootManagerTagCustomData: String? override var customModuleOptions: Map<String, String> } companion object : Type<ModuleCustomImlDataEntity, Builder>() { operator fun invoke(customModuleOptions: Map<String, String>, entitySource: EntitySource, init: (Builder.() -> Unit)? = null): ModuleCustomImlDataEntity { val builder = builder() builder.customModuleOptions = customModuleOptions builder.entitySource = entitySource init?.invoke(builder) return builder } } //endregion } //region generated code fun MutableEntityStorage.modifyEntity(entity: ModuleCustomImlDataEntity, modification: ModuleCustomImlDataEntity.Builder.() -> Unit) = modifyEntity( ModuleCustomImlDataEntity.Builder::class.java, entity, modification) //endregion interface ModuleGroupPathEntity : WorkspaceEntity { val module: ModuleEntity val path: List<String> //region generated code @GeneratedCodeApiVersion(1) interface Builder : ModuleGroupPathEntity, WorkspaceEntity.Builder<ModuleGroupPathEntity>, ObjBuilder<ModuleGroupPathEntity> { override var entitySource: EntitySource override var module: ModuleEntity override var path: MutableList<String> } companion object : Type<ModuleGroupPathEntity, Builder>() { operator fun invoke(path: List<String>, entitySource: EntitySource, init: (Builder.() -> Unit)? = null): ModuleGroupPathEntity { val builder = builder() builder.path = path.toMutableWorkspaceList() builder.entitySource = entitySource init?.invoke(builder) return builder } } //endregion } //region generated code fun MutableEntityStorage.modifyEntity(entity: ModuleGroupPathEntity, modification: ModuleGroupPathEntity.Builder.() -> Unit) = modifyEntity( ModuleGroupPathEntity.Builder::class.java, entity, modification) //endregion interface JavaModuleSettingsEntity: WorkspaceEntity { val module: ModuleEntity val inheritedCompilerOutput: Boolean val excludeOutput: Boolean val compilerOutput: VirtualFileUrl? val compilerOutputForTests: VirtualFileUrl? val languageLevelId: String? //region generated code @GeneratedCodeApiVersion(1) interface Builder : JavaModuleSettingsEntity, WorkspaceEntity.Builder<JavaModuleSettingsEntity>, ObjBuilder<JavaModuleSettingsEntity> { override var entitySource: EntitySource override var module: ModuleEntity override var inheritedCompilerOutput: Boolean override var excludeOutput: Boolean override var compilerOutput: VirtualFileUrl? override var compilerOutputForTests: VirtualFileUrl? override var languageLevelId: String? } companion object : Type<JavaModuleSettingsEntity, Builder>() { operator fun invoke(inheritedCompilerOutput: Boolean, excludeOutput: Boolean, entitySource: EntitySource, init: (Builder.() -> Unit)? = null): JavaModuleSettingsEntity { val builder = builder() builder.inheritedCompilerOutput = inheritedCompilerOutput builder.excludeOutput = excludeOutput builder.entitySource = entitySource init?.invoke(builder) return builder } } //endregion } //region generated code fun MutableEntityStorage.modifyEntity(entity: JavaModuleSettingsEntity, modification: JavaModuleSettingsEntity.Builder.() -> Unit) = modifyEntity( JavaModuleSettingsEntity.Builder::class.java, entity, modification) //endregion interface ExternalSystemModuleOptionsEntity: WorkspaceEntity { val module: ModuleEntity val externalSystem: String? val externalSystemModuleVersion: String? val linkedProjectPath: String? val linkedProjectId: String? val rootProjectPath: String? val externalSystemModuleGroup: String? val externalSystemModuleType: String? //region generated code @GeneratedCodeApiVersion(1) interface Builder : ExternalSystemModuleOptionsEntity, WorkspaceEntity.Builder<ExternalSystemModuleOptionsEntity>, ObjBuilder<ExternalSystemModuleOptionsEntity> { override var entitySource: EntitySource override var module: ModuleEntity override var externalSystem: String? override var externalSystemModuleVersion: String? override var linkedProjectPath: String? override var linkedProjectId: String? override var rootProjectPath: String? override var externalSystemModuleGroup: String? override var externalSystemModuleType: String? } companion object : Type<ExternalSystemModuleOptionsEntity, Builder>() { operator fun invoke(entitySource: EntitySource, init: (Builder.() -> Unit)? = null): ExternalSystemModuleOptionsEntity { val builder = builder() builder.entitySource = entitySource init?.invoke(builder) return builder } } //endregion } //region generated code fun MutableEntityStorage.modifyEntity(entity: ExternalSystemModuleOptionsEntity, modification: ExternalSystemModuleOptionsEntity.Builder.() -> Unit) = modifyEntity( ExternalSystemModuleOptionsEntity.Builder::class.java, entity, modification) //endregion
apache-2.0
c48c5c2880ff3a0aa1e813a4582c2a49
37.217778
164
0.750785
5.975678
false
false
false
false
GunoH/intellij-community
platform/util/ui/src/com/intellij/util/ui/ExtendableHTMLViewFactory.kt
3
11782
// 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.util.ui import com.intellij.openapi.diagnostic.thisLogger import com.intellij.openapi.util.IconLoader import com.intellij.openapi.util.text.HtmlChunk import com.intellij.ui.scale.JBUIScale import com.intellij.util.text.nullize import com.intellij.util.ui.html.HiDpiScalingImageView import java.awt.* import java.awt.image.BufferedImage import java.io.ByteArrayInputStream import java.io.IOException import java.util.* import javax.imageio.ImageIO import javax.swing.Icon import javax.swing.SizeRequirements import javax.swing.text.* import javax.swing.text.Position.Bias import javax.swing.text.html.HTML import javax.swing.text.html.HTMLEditorKit import javax.swing.text.html.HTMLEditorKit.HTMLFactory import javax.swing.text.html.ImageView import javax.swing.text.html.ParagraphView import kotlin.math.max /** * Pluggable [HTMLFactory] which allows overriding and adding functionality to [HTMLFactory] without using inheritance */ class ExtendableHTMLViewFactory internal constructor( private val extensions: List<(Element, View) -> View?>, private val base: ViewFactory = HTMLEditorKit().viewFactory ) : HTMLFactory() { internal constructor(vararg extensions: (Element, View) -> View?) : this(extensions.asList()) internal constructor(vararg extensions: Extension) : this(extensions.asList()) override fun create(elem: Element): View { val defaultView = base.create(elem) for (extension in extensions) { val view = extension(elem, defaultView) if (view != null && view !== defaultView) return view } return defaultView } companion object { @JvmField val DEFAULT_EXTENSIONS = listOf(Extensions.ICONS, Extensions.BASE64_IMAGES, Extensions.HIDPI_IMAGES) @JvmField val DEFAULT = ExtendableHTMLViewFactory(DEFAULT_EXTENSIONS) private val DEFAULT_EXTENSIONS_WORD_WRAP = DEFAULT_EXTENSIONS + Extensions.WORD_WRAP @JvmField val DEFAULT_WORD_WRAP = ExtendableHTMLViewFactory(DEFAULT_EXTENSIONS_WORD_WRAP) } @FunctionalInterface interface Extension : (Element, View) -> View? /** * Collection of most popular features */ object Extensions { /** * Render icons from the provided map * * Syntax is `<icon src='MAP_KEY'>` */ @JvmStatic fun icons(preLoaded: Map<String, Icon> = emptyMap()): Extension = if (preLoaded.isEmpty()) ICONS else IconsExtension(preLoaded) /** * Render icons provided by [existingIconsProvider] * * Syntax is `<icon src='KEY'>` */ @JvmStatic fun icons(existingIconsProvider: (key: String) -> Icon?): Extension = IconsExtension(existingIconsProvider) /** * Render icons provided by [htmlChunk] * * Syntax is `<icon src='KEY'>` */ @JvmStatic fun icons(htmlChunk: HtmlChunk): Extension = IconsExtension { htmlChunk.findIcon(it) } /** * Render icons from IJ icon classes * * Syntax is `<icon src='FQN_FOR_ICON'>` */ @JvmField val ICONS: Extension = IconsExtension(emptyMap()) /** * Render base64 encoded images * * Syntax is `<img src='data:image/png;base64,ENCODED_IMAGE_HERE'>` */ @JvmField val BASE64_IMAGES: Extension = Base64ImagesExtension() /** * Wrap words that are too long, for example: A_TEST_TABLE_SINGLE_ROW_UPDATE_AUTOCOMMIT_A_FIK */ @JvmField val WORD_WRAP: Extension = WordWrapExtension() /** * Renders images with proper scaling according to sysScale */ @JvmField val HIDPI_IMAGES: Extension = HiDpiImagesExtension() private class IconsExtension(private val existingIconsProvider: (key: String) -> Icon?) : Extension { constructor(preloadedIcons: Map<String, Icon>) : this(preloadedIconsProvider(preloadedIcons)) override fun invoke(elem: Element, defaultView: View): View? { if (StyleConstants.IconElementName != elem.name) return null val src = elem.attributes.getAttribute(HTML.Attribute.SRC) as? String ?: return null val icon = getIcon(src) ?: return null return JBIconView(elem, icon) } private fun getIcon(src: String): Icon? { val existingIcon = existingIconsProvider(src) if (existingIcon != null) return existingIcon return IconLoader.findIcon(src, ExtendableHTMLViewFactory::class.java, true, false) } /** * @see [javax.swing.text.IconView] */ private class JBIconView(elem: Element, private val icon: Icon) : View(elem) { override fun getPreferredSpan(axis: Int): Float { return when (axis) { X_AXIS -> icon.iconWidth.toFloat() Y_AXIS -> icon.iconHeight.toFloat() else -> throw IllegalArgumentException("Invalid axis: $axis") } } override fun getAlignment(axis: Int): Float { // 12 is a "standard" font height which has user scale of 1 if (axis == Y_AXIS) return JBUIScale.scale(12) / icon.iconHeight.toFloat() return super.getAlignment(axis) } override fun getToolTipText(x: Float, y: Float, allocation: Shape): String? { return (element.attributes.getAttribute(HTML.Attribute.ALT) as? String)?.nullize(true) } override fun paint(g: Graphics, allocation: Shape) { val g2d = g as Graphics2D val savedComposite = g2d.composite g2d.composite = AlphaComposite.SrcOver // support transparency icon.paintIcon(null, g, allocation.bounds.x, allocation.bounds.y) g2d.composite = savedComposite } @Throws(BadLocationException::class) override fun modelToView(pos: Int, a: Shape, b: Bias): Shape { val p0 = startOffset val p1 = endOffset if (pos in p0..p1) { val r = a.bounds if (pos == p1) { r.x += r.width } r.width = 0 return r } throw BadLocationException("$pos not in range $p0,$p1", pos) } override fun viewToModel(x: Float, y: Float, a: Shape, bias: Array<Bias>): Int { val alloc = a as Rectangle if (x < alloc.x + alloc.width / 2f) { bias[0] = Bias.Forward return startOffset } bias[0] = Bias.Backward return endOffset } } companion object { private fun preloadedIconsProvider(preloadedIcons: Map<String, Icon>) = { key: String -> preloadedIcons[key] } } } private class Base64ImagesExtension : Extension { override fun invoke(elem: Element, defaultView: View): View? { if ("img" != elem.name) return null val src = (elem.attributes.getAttribute(HTML.Attribute.SRC) as? String)?.takeIf { // example: "data:image/png;base64,ENCODED_IMAGE_HERE" it.startsWith("data:image") && it.contains("base64") } ?: return null val encodedImage = src.split(',').takeIf { it.size == 2 }?.get(1) ?: return null try { val image = ByteArrayInputStream(Base64.getDecoder().decode(encodedImage)).use(ImageIO::read) ?: return null return BufferedImageView(elem, image) } catch (e: java.lang.IllegalArgumentException) { thisLogger().debug(e) } catch (e: IOException) { thisLogger().debug(e) } return null } private class BufferedImageView(elem: Element, private val bufferedImage: BufferedImage) : View(elem) { private val width: Int private val height: Int private val border: Int private val vAlign: Float init { val width = getIntAttr(HTML.Attribute.WIDTH, -1) val height = getIntAttr(HTML.Attribute.HEIGHT, -1) val aspectRatio: Int = bufferedImage.width / bufferedImage.height if (width < 0 && height < 0) { this.width = bufferedImage.width this.height = bufferedImage.height } else if (width < 0) { this.width = height * aspectRatio this.height = height } else if (height < 0) { this.width = width this.height = width / aspectRatio } else { this.width = width this.height = height } border = getIntAttr(HTML.Attribute.BORDER, DEFAULT_BORDER) var alignment = elem.attributes.getAttribute(HTML.Attribute.ALIGN) var vAlign = 1.0f if (alignment != null) { alignment = alignment.toString() if ("top" == alignment) { vAlign = 0f } else if ("middle" == alignment) { vAlign = .5f } } this.vAlign = vAlign } private fun getIntAttr(name: HTML.Attribute, defaultValue: Int): Int { val attr = element.attributes if (!attr.isDefined(name)) return defaultValue val value = attr.getAttribute(name) as? String ?: return defaultValue return try { max(0, value.toInt()) } catch (x: NumberFormatException) { defaultValue } } override fun getPreferredSpan(axis: Int): Float { return when (axis) { X_AXIS -> (width + 2 * border).toFloat() Y_AXIS -> (height + 2 * border).toFloat() else -> throw IllegalArgumentException("Invalid axis: $axis") } } override fun getToolTipText(x: Float, y: Float, allocation: Shape) = super.getElement().attributes.getAttribute(HTML.Attribute.ALT) as? String override fun paint(g: Graphics, a: Shape) { val bounds = a.bounds g.drawImage(bufferedImage, bounds.x + border, bounds.y + border, width, height, null) } override fun modelToView(pos: Int, a: Shape, b: Bias): Shape? { val p0 = startOffset val p1 = endOffset if (pos in p0..p1) { val r = a.bounds if (pos == p1) { r.x += r.width } r.width = 0 return r } return null } override fun viewToModel(x: Float, y: Float, a: Shape, bias: Array<Bias>): Int { val alloc = a as Rectangle if (x < alloc.x + alloc.width) { bias[0] = Bias.Forward return startOffset } bias[0] = Bias.Backward return endOffset } override fun getAlignment(axis: Int): Float = if (axis == Y_AXIS) vAlign else super.getAlignment(axis) companion object { private const val DEFAULT_BORDER = 0 } } } } private class WordWrapExtension : Extension { override fun invoke(elem: Element, defaultView: View): View? { if (defaultView !is ParagraphView) return null return object : ParagraphView(elem) { override fun calculateMinorAxisRequirements(axis: Int, requirements: SizeRequirements?): SizeRequirements = (requirements ?: SizeRequirements()).apply { minimum = layoutPool.getMinimumSpan(axis).toInt() preferred = max(minimum, layoutPool.getPreferredSpan(axis).toInt()) maximum = Int.MAX_VALUE alignment = 0.5f } } } } } private class HiDpiImagesExtension : ExtendableHTMLViewFactory.Extension { override fun invoke(elem: Element, defaultView: View): View? { if (defaultView !is ImageView) return null return HiDpiScalingImageView(elem) } }
apache-2.0
0f9ae7a3dc9c0ee3e4101157c5967190
32.474432
131
0.615091
4.325257
false
false
false
false
AsamK/TextSecure
app/src/main/java/org/thoughtcrime/securesms/conversation/ConversationItemSelection.kt
1
3500
package org.thoughtcrime.securesms.conversation import android.graphics.Bitmap import android.graphics.Path import android.view.ViewGroup import androidx.core.graphics.applyCanvas import androidx.core.graphics.createBitmap import androidx.core.graphics.withClip import androidx.core.graphics.withTranslation import androidx.core.view.children import androidx.recyclerview.widget.RecyclerView import org.signal.core.util.DimensionUnit import org.thoughtcrime.securesms.database.model.MessageRecord import org.thoughtcrime.securesms.util.hasNoBubble object ConversationItemSelection { @JvmStatic fun snapshotView( conversationItem: ConversationItem, list: RecyclerView, messageRecord: MessageRecord, videoBitmap: Bitmap?, ): Bitmap { val isOutgoing = messageRecord.isOutgoing val hasNoBubble = messageRecord.hasNoBubble(conversationItem.context) return snapshotMessage( conversationItem = conversationItem, list = list, videoBitmap = videoBitmap, drawConversationItem = !isOutgoing || hasNoBubble, hasReaction = messageRecord.reactions.isNotEmpty(), ) } private fun snapshotMessage( conversationItem: ConversationItem, list: RecyclerView, videoBitmap: Bitmap?, drawConversationItem: Boolean, hasReaction: Boolean, ): Bitmap { val bodyBubble = conversationItem.bodyBubble val reactionsView = conversationItem.reactionsView val originalScale = bodyBubble.scaleX bodyBubble.scaleX = 1.0f bodyBubble.scaleY = 1.0f val projections = conversationItem.getColorizerProjections(list) val path = Path() val xTranslation = -conversationItem.x - bodyBubble.x val yTranslation = -conversationItem.y - bodyBubble.y val mp4Projection = conversationItem.getGiphyMp4PlayableProjection(list) var scaledVideoBitmap = videoBitmap if (videoBitmap != null) { scaledVideoBitmap = Bitmap.createScaledBitmap( videoBitmap, (videoBitmap.width / originalScale).toInt(), (videoBitmap.height / originalScale).toInt(), true ) mp4Projection.translateX(xTranslation) mp4Projection.translateY(yTranslation) mp4Projection.applyToPath(path) } projections.use { it.forEach { p -> p.translateX(xTranslation) p.translateY(yTranslation) p.applyToPath(path) } } conversationItem.destroyAllDrawingCaches() var bitmapHeight = bodyBubble.height if (hasReaction) { bitmapHeight += (reactionsView.height - DimensionUnit.DP.toPixels(4f)).toInt() } return createBitmap(bodyBubble.width, bitmapHeight).applyCanvas { if (drawConversationItem) { bodyBubble.draw(this) } withClip(path) { withTranslation(x = xTranslation, y = yTranslation) { list.draw(this) if (scaledVideoBitmap != null) { drawBitmap(scaledVideoBitmap, mp4Projection.x - xTranslation, mp4Projection.y - yTranslation, null) } } } withTranslation( x = reactionsView.x - bodyBubble.x, y = reactionsView.y - bodyBubble.y ) { reactionsView.draw(this) } }.also { mp4Projection.release() bodyBubble.scaleX = originalScale bodyBubble.scaleY = originalScale } } } private fun ViewGroup.destroyAllDrawingCaches() { children.forEach { it.destroyDrawingCache() if (it is ViewGroup) { it.destroyAllDrawingCaches() } } }
gpl-3.0
cd71e684275a31aceea3d161981d557a
27.225806
111
0.705143
4.447268
false
false
false
false
RoyaAoki/Megumin
mobile/src/main/java/com/sqrtf/megumin/PlayerActivity.kt
1
9551
package com.sqrtf.megumin import android.app.Activity import android.content.Context import android.content.Intent import android.net.Uri import android.os.Build import android.os.Bundle import android.os.Handler import android.text.TextUtils import android.util.Log import android.view.KeyEvent import android.view.View import android.widget.SeekBar import android.widget.TextView import android.widget.Toast import com.google.android.exoplayer2.extractor.DefaultExtractorsFactory import com.google.android.exoplayer2.source.ExtractorMediaSource import com.google.android.exoplayer2.upstream.DefaultDataSourceFactory import com.google.android.exoplayer2.util.Util import com.sqrtf.common.activity.BaseActivity import com.sqrtf.common.api.ApiHelper import com.sqrtf.common.player.MeguminExoPlayer import com.sqrtf.common.view.CheckableImageButton import com.sqrtf.common.view.FastForwardBar import kotlin.math.min class PlayerActivity : BaseActivity() { val playerController by lazy { findViewById<View>(R.id.play_controller) } val playerView by lazy { findViewById<MeguminExoPlayer>(R.id.player_content) } val root by lazy { findViewById<View>(R.id.root) } val mHidePart2Runnable = Runnable { playerView.systemUiVisibility = View.SYSTEM_UI_FLAG_LOW_PROFILE or View.SYSTEM_UI_FLAG_FULLSCREEN or View.SYSTEM_UI_FLAG_LAYOUT_STABLE or View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY or View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION or View.SYSTEM_UI_FLAG_HIDE_NAVIGATION } val mShowPart2Runnable = Runnable { supportActionBar?.show() } val mHideHandler = Handler() var lastPlayWhenReady = false var controllerVisibility = View.VISIBLE companion object { fun intent(context: Context, url: String, id: String, id2: String): Intent { val intent = Intent(context, PlayerActivity::class.java) intent.putExtra(INTENT_KEY_URL, url) intent.putExtra(RESULT_KEY_ID, id) intent.putExtra(RESULT_KEY_ID_2, id2) return intent } private val INTENT_KEY_URL = "INTENT_KEY_URL" private val UI_ANIMATION_DELAY = 100 val RESULT_KEY_ID = "PlayerActivity:RESULT_KEY_ID" val RESULT_KEY_ID_2 = "PlayerActivity:RESULT_KEY_ID_2" val RESULT_KEY_POSITION = "PlayerActivity:RESULT_KEY_POSITION" val RESULT_KEY_DURATION = "PlayerActivity:RESULT_KEY_DURATION" } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_player) supportActionBar?.setDisplayHomeAsUpEnabled(true) // playerView.postDelayed({ // requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE // }, 1000) // requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE // requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_LOCKED val url = intent.getStringExtra(INTENT_KEY_URL) if (TextUtils.isEmpty(url)) throw IllegalArgumentException("Required url") val fixedUrl = Uri.encode(ApiHelper.fixHttpUrl(url), "@#&=*+-_.,:!?()/~'%") Log.i(this.localClassName, "playing:" + fixedUrl) checkMultiWindowMode() findViewById<View>(R.id.play_close).setOnClickListener { finish() } (findViewById<FastForwardBar>(R.id.fast_forward_bar)).callback = object : FastForwardBar.FastForwardEventCallback { override fun onFastForward(range: Int) { playerView.seekOffsetTo(range * 1000) } override fun onClick(view: View) { playerView.performClick() } } playerView.setControllerView( MeguminExoPlayer.ControllerViews( playerController, findViewById<CheckableImageButton>(R.id.play_button), findViewById<CheckableImageButton?>(R.id.play_screen), findViewById<SeekBar>(R.id.play_progress), findViewById<TextView>(R.id.play_position), findViewById<TextView>(R.id.play_duration))) playerView.setControllerCallback(object : MeguminExoPlayer.ControllerCallback { override fun onControllerVisibilityChange(visible: Boolean) { if (visible) { showController() } else { hideController() } } }) val dataSourceFactory = DefaultDataSourceFactory(this, Util.getUserAgent(this, BuildConfig.APPLICATION_ID)) val extractorsFactory = DefaultExtractorsFactory() val videoSource = ExtractorMediaSource(Uri.parse(fixedUrl), dataSourceFactory, extractorsFactory, null, null) playerView.setSource(videoSource) playerView.setPlayWhenReady(true) lastPlayWhenReady = true } private fun checkMultiWindowMode() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { root.fitsSystemWindows = isInMultiWindowMode } } override fun onBackPressed() { if (!packageManager.hasSystemFeature("android.hardware.touchscreen") && controllerVisibility == View.VISIBLE) { playerView.dismissController() } else { super.onBackPressed() } // finish() } override fun onPostCreate(savedInstanceState: Bundle?) { super.onPostCreate(savedInstanceState) } override fun onStart() { super.onStart() playerView.setPlayWhenReady(lastPlayWhenReady) playerView.showController() } override fun onStop() { super.onStop() lastPlayWhenReady = playerView.getPlayWhenReady() playerView.setPlayWhenReady(false) } override fun onMultiWindowModeChanged(isInMultiWindowMode: Boolean) { super.onMultiWindowModeChanged(isInMultiWindowMode) checkMultiWindowMode() } override fun onDestroy() { super.onDestroy() playerView.setPlayWhenReady(false) playerView.release() } override fun finish() { val resultCode = if (playerView.player.currentPosition > 0) Activity.RESULT_OK else Activity.RESULT_CANCELED val i = intent i.putExtra(RESULT_KEY_POSITION, playerView.player.currentPosition) i.putExtra(RESULT_KEY_DURATION, playerView.player.duration) setResult(resultCode, i) super.finish() } private fun hideController() { supportActionBar?.hide() controllerVisibility = View.INVISIBLE mHideHandler.removeCallbacks(mShowPart2Runnable) mHideHandler.postDelayed(mHidePart2Runnable, UI_ANIMATION_DELAY.toLong()) } private fun showController() { playerView.systemUiVisibility = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN or View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION or View.SYSTEM_UI_FLAG_LAYOUT_STABLE controllerVisibility = View.VISIBLE mHideHandler.removeCallbacks(mHidePart2Runnable) mHideHandler.postDelayed(mShowPart2Runnable, UI_ANIMATION_DELAY.toLong()) } private var pressTimes = 0 private var keyPressingCode = Int.MIN_VALUE private val keyPressingRunnable = Runnable { if (keyPressingCode < 0) { return@Runnable } pressTimes += 1 onKeyboardSeekUpdate(pressTimes) checkNext() } private fun checkNext() { mHideHandler.postDelayed(keyPressingRunnable, 400) } override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean { if (controllerVisibility != View.INVISIBLE) return super.onKeyDown(keyCode, event) if (keyPressingCode == keyCode) return true when (keyCode) { KeyEvent.KEYCODE_DPAD_RIGHT, KeyEvent.KEYCODE_DPAD_LEFT -> { if (keyPressingCode != keyCode) { pressTimes = 1 keyPressingCode = keyCode onKeyboardSeekUpdate(pressTimes) mHideHandler.removeCallbacks(keyPressingRunnable) checkNext() } return true } } return super.onKeyDown(keyCode, event) } override fun onKeyUp(keyCode: Int, event: KeyEvent?): Boolean { if (keyPressingCode > 0 && keyCode == keyPressingCode) { onKeyboardSeekUpdate(pressTimes, true) keyPressingCode = Int.MIN_VALUE return true } if (controllerVisibility == View.INVISIBLE && (keyCode == KeyEvent.KEYCODE_DPAD_CENTER || keyCode == KeyEvent.KEYCODE_ENTER)){ playerView.showController() } return super.onKeyUp(keyCode, event) } val mToast by lazy { Toast.makeText(this, "", Toast.LENGTH_SHORT) } private fun onKeyboardSeekUpdate(times: Int, isFinish: Boolean = false) { val isForward = keyPressingCode == KeyEvent.KEYCODE_DPAD_RIGHT val s = if (times <= 3) times * 5 else 3 * 5 + (times - 3) * 15 mToast.setText(getString(if (isForward) R.string.toast_forward else R.string.toast_backward).format(s)) mToast.show() if (isFinish) { playerView.seekOffsetTo(s * (if (isForward) 1000 else -1000)) mToast.cancel() } } }
mit
33e86f4b50ad4396eca6cd0898248113
34.906015
123
0.644749
4.688758
false
false
false
false
ktorio/ktor
ktor-http/ktor-http-cio/common/src/io/ktor/http/cio/HttpParser.kt
1
9304
/* * Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ package io.ktor.http.cio import io.ktor.http.* import io.ktor.http.cio.internals.* import io.ktor.utils.io.* /** * An HTTP parser exception */ public class ParserException(message: String) : IllegalStateException(message) private const val HTTP_LINE_LIMIT = 8192 private const val HTTP_STATUS_CODE_MIN_RANGE = 100 private const val HTTP_STATUS_CODE_MAX_RANGE = 999 private val hostForbiddenSymbols = setOf('/', '?', '#', '@') /** * Parse an HTTP request line and headers */ public suspend fun parseRequest(input: ByteReadChannel): Request? { val builder = CharArrayBuilder() val range = MutableRange(0, 0) try { while (true) { if (!input.readUTF8LineTo(builder, HTTP_LINE_LIMIT)) return null range.end = builder.length if (range.start == range.end) continue val method = parseHttpMethod(builder, range) val uri = parseUri(builder, range) val version = parseVersion(builder, range) skipSpaces(builder, range) if (range.start != range.end) { throw ParserException("Extra characters in request line: ${builder.substring(range.start, range.end)}") } if (uri.isEmpty()) throw ParserException("URI is not specified") if (version.isEmpty()) throw ParserException("HTTP version is not specified") val headers = parseHeaders(input, builder, range) ?: return null return Request(method, uri, version, headers, builder) } } catch (t: Throwable) { builder.release() throw t } } /** * Parse an HTTP response status line and headers */ public suspend fun parseResponse(input: ByteReadChannel): Response? { val builder = CharArrayBuilder() val range = MutableRange(0, 0) try { if (!input.readUTF8LineTo(builder, HTTP_LINE_LIMIT)) return null range.end = builder.length val version = parseVersion(builder, range) val statusCode = parseStatusCode(builder, range) skipSpaces(builder, range) val statusText = builder.subSequence(range.start, range.end) range.start = range.end val headers = parseHeaders(input, builder, range) ?: HttpHeadersMap(builder) return Response(version, statusCode, statusText, headers, builder) } catch (t: Throwable) { builder.release() throw t } } /** * Parse http headers. Not applicable to request and response status lines. */ public suspend fun parseHeaders(input: ByteReadChannel): HttpHeadersMap { val builder = CharArrayBuilder() return parseHeaders(input, builder) ?: HttpHeadersMap(builder) } /** * Parse HTTP headers. Not applicable to request and response status lines. */ internal suspend fun parseHeaders( input: ByteReadChannel, builder: CharArrayBuilder, range: MutableRange = MutableRange(0, 0) ): HttpHeadersMap? { val headers = HttpHeadersMap(builder) try { while (true) { if (!input.readUTF8LineTo(builder, HTTP_LINE_LIMIT)) { headers.release() return null } range.end = builder.length val rangeLength = range.end - range.start if (rangeLength == 0) break if (rangeLength >= HTTP_LINE_LIMIT) error("Header line length limit exceeded") val nameStart = range.start val nameEnd = parseHeaderName(builder, range) val nameHash = builder.hashCodeLowerCase(nameStart, nameEnd) val headerEnd = range.end parseHeaderValue(builder, range) val valueStart = range.start val valueEnd = range.end val valueHash = builder.hashCodeLowerCase(valueStart, valueEnd) range.start = headerEnd headers.put(nameHash, valueHash, nameStart, nameEnd, valueStart, valueEnd) } val host = headers[HttpHeaders.Host] if (host != null) { validateHostHeader(host) } return headers } catch (t: Throwable) { headers.release() throw t } } private fun validateHostHeader(host: CharSequence) { if (host.endsWith(":")) { throw ParserException("Host header with ':' should contains port: $host") } if (host.any { hostForbiddenSymbols.contains(it) }) { throw ParserException("Host cannot contain any of the following symbols: $hostForbiddenSymbols") } } private fun parseHttpMethod(text: CharSequence, range: MutableRange): HttpMethod { skipSpaces(text, range) val exact = DefaultHttpMethods.search(text, range.start, range.end) { ch, _ -> ch == ' ' }.singleOrNull() if (exact != null) { range.start += exact.value.length return exact } return parseHttpMethodFull(text, range) } private fun parseHttpMethodFull(text: CharSequence, range: MutableRange): HttpMethod { return HttpMethod(nextToken(text, range).toString()) } private fun parseUri(text: CharSequence, range: MutableRange): CharSequence { skipSpaces(text, range) val start = range.start val spaceOrEnd = findSpaceOrEnd(text, range) val length = spaceOrEnd - start if (length <= 0) return "" if (length == 1 && text[start] == '/') { range.start = spaceOrEnd return "/" } val s = text.subSequence(start, spaceOrEnd) range.start = spaceOrEnd return s } private val versions = AsciiCharTree.build(listOf("HTTP/1.0", "HTTP/1.1")) private fun parseVersion(text: CharSequence, range: MutableRange): CharSequence { skipSpaces(text, range) check(range.start < range.end) { "Failed to parse version: $text" } val exact = versions.search(text, range.start, range.end) { ch, _ -> ch == ' ' }.singleOrNull() if (exact != null) { range.start += exact.length return exact } unsupportedHttpVersion(nextToken(text, range)) } private fun parseStatusCode(text: CharSequence, range: MutableRange): Int { skipSpaces(text, range) var status = 0 var newStart = range.end for (idx in range.start until range.end) { val ch = text[idx] if (ch == ' ') { if (statusOutOfRange(status)) { throw ParserException("Status-code must be 3-digit. Status received: $status.") } newStart = idx break } else if (ch in '0'..'9') { status = status * 10 + (ch - '0') } else { val code = text.substring(range.start, findSpaceOrEnd(text, range)) throw NumberFormatException("Illegal digit $ch in status code $code") } } range.start = newStart return status } private fun statusOutOfRange(code: Int) = code < HTTP_STATUS_CODE_MIN_RANGE || code > HTTP_STATUS_CODE_MAX_RANGE /** * Returns index of the next character after the last header name character, * range.start is modified to point to the next character after colon. */ internal fun parseHeaderName(text: CharArrayBuilder, range: MutableRange): Int { var index = range.start val end = range.end while (index < end) { val ch = text[index] if (ch == ':' && index != range.start) { range.start = index + 1 return index } if (isDelimiter(ch)) { parseHeaderNameFailed(text, index, range.start, ch) } index++ } noColonFound(text, range) } private fun parseHeaderNameFailed(text: CharArrayBuilder, index: Int, start: Int, ch: Char): Nothing { if (ch == ':') { throw ParserException("Empty header names are not allowed as per RFC7230.") } if (index == start) { throw ParserException( "Multiline headers via line folding is not supported " + "since it is deprecated as per RFC7230." ) } characterIsNotAllowed(text, ch) } internal fun parseHeaderValue(text: CharArrayBuilder, range: MutableRange) { val start = range.start val end = range.end var index = start index = skipSpacesAndHorizontalTabs(text, index, end) if (index >= end) { range.start = end return } val valueStart = index var valueLastIndex = index while (index < end) { when (val ch = text[index]) { HTAB, ' ' -> { } '\r', '\n' -> characterIsNotAllowed(text, ch) else -> valueLastIndex = index } index++ } range.start = valueStart range.end = valueLastIndex + 1 } private fun noColonFound(text: CharSequence, range: MutableRange): Nothing { throw ParserException("No colon in HTTP header in ${text.substring(range.start, range.end)} in builder: \n$text") } private fun characterIsNotAllowed(text: CharSequence, ch: Char): Nothing = throw ParserException("Character with code ${(ch.code and 0xff)} is not allowed in header names, \n$text") private fun isDelimiter(ch: Char): Boolean { return ch <= ' ' || ch in "\"(),/:;<=>?@[\\]{}" } private fun unsupportedHttpVersion(result: CharSequence): Nothing { throw ParserException("Unsupported HTTP version: $result") }
apache-2.0
110b1289d1565684204d0eabdcfce377
29.504918
119
0.630267
4.238724
false
false
false
false
ktorio/ktor
ktor-client/ktor-client-plugins/ktor-client-json/ktor-client-serialization/common/src/io/ktor/client/plugins/kotlinx/serializer/KotlinxSerializer.kt
1
3603
/* * Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ @file:Suppress("DEPRECATION") package io.ktor.client.plugins.kotlinx.serializer import io.ktor.client.plugins.json.* import io.ktor.http.* import io.ktor.http.content.* import io.ktor.util.reflect.* import io.ktor.utils.io.core.* import kotlinx.serialization.* import kotlinx.serialization.builtins.* import kotlinx.serialization.json.* import kotlinx.serialization.modules.* /** * A [JsonSerializer] implemented for kotlinx [Serializable] classes. */ @Deprecated( "Please use ContentNegotiation plugin and its converters: https://ktor.io/docs/migrating-2.html#serialization-client" // ktlint-disable max-line-length ) public class KotlinxSerializer( private val json: Json = DefaultJson ) : JsonSerializer { override fun write(data: Any, contentType: ContentType): OutgoingContent { @Suppress("UNCHECKED_CAST") return TextContent(writeContent(data), contentType) } internal fun writeContent(data: Any): String = json.encodeToString(buildSerializer(data, json.serializersModule), data) @OptIn(InternalSerializationApi::class, ExperimentalSerializationApi::class) override fun read(type: TypeInfo, body: Input): Any { val text = body.readText() val deserializationStrategy = json.serializersModule.getContextual(type.type) val mapper = deserializationStrategy ?: (type.kotlinType?.let { serializer(it) } ?: type.type.serializer()) return json.decodeFromString(mapper, text)!! } public companion object { /** * Default [Json] configuration for [KotlinxSerializer]. */ public val DefaultJson: Json = Json { isLenient = false ignoreUnknownKeys = false allowSpecialFloatingPointValues = true useArrayPolymorphism = false } } } @Suppress("UNCHECKED_CAST") private fun buildSerializer(value: Any, module: SerializersModule): KSerializer<Any> = when (value) { is JsonElement -> JsonElement.serializer() is List<*> -> ListSerializer(value.elementSerializer(module)) is Array<*> -> value.firstOrNull()?.let { buildSerializer(it, module) } ?: ListSerializer(String.serializer()) is Set<*> -> SetSerializer(value.elementSerializer(module)) is Map<*, *> -> { val keySerializer = value.keys.elementSerializer(module) val valueSerializer = value.values.elementSerializer(module) MapSerializer(keySerializer, valueSerializer) } else -> { @OptIn(InternalSerializationApi::class, ExperimentalSerializationApi::class) module.getContextual(value::class) ?: value::class.serializer() } } as KSerializer<Any> @OptIn(ExperimentalSerializationApi::class) private fun Collection<*>.elementSerializer(module: SerializersModule): KSerializer<*> { val serializers: List<KSerializer<*>> = filterNotNull().map { buildSerializer(it, module) }.distinctBy { it.descriptor.serialName } if (serializers.size > 1) { error( "Serializing collections of different element types is not yet supported. " + "Selected serializers: ${serializers.map { it.descriptor.serialName }}" ) } val selected = serializers.singleOrNull() ?: String.serializer() if (selected.descriptor.isNullable) { return selected } @Suppress("UNCHECKED_CAST") selected as KSerializer<Any> if (any { it == null }) { return selected.nullable } return selected }
apache-2.0
61877a1e94a2df2914e370e8f54be465
34.673267
155
0.693589
4.537783
false
false
false
false
prolificinteractive/simcoe-android
simcoe/src/main/java/com/prolificinteractive/simcoe/Tracker.kt
1
2168
package com.prolificinteractive.simcoe import com.prolificinteractive.simcoe.trackers.AnalyticsTracking import java.util.ArrayList /** * A recorder for SimcoeEvents. * @param outputOption The output options. * @param errorOption The error options. */ class Tracker @JvmOverloads constructor( var outputOption: OutputOptions = OutputOptions.VERBOSE, var errorOption: ErrorHandlingOption = ErrorHandlingOption.DEFAULT, vararg outputs: Output) { constructor() : this(outputs = ConsoleOutput()) private val outputSources = outputs companion object { const private val ANALYTICS_PROVIDER_NAME = "Analytics" const private val ANALYTICS_ERROR = "** ANALYTICS ERROR **" } /** * Records the event. * * @param event The event to record. * @throws Exception The exception thrown when ErrorHandlingOption.STRICT is used. */ internal fun track(event: Event) { val successfulProviders = ArrayList<AnalyticsTracking>() for (writeEvent in event.writeEvents) { if (!writeEvent.trackingResult.isError) { successfulProviders.add(writeEvent.provider) } else { handleError(writeEvent.provider.providerName(), writeEvent.trackingResult.errorMessage) return } } write(event.description, successfulProviders) } @Throws(SimcoeException::class) private fun handleError(name: String, errorMessage: String?) { when (errorOption) { ErrorHandlingOption.DEFAULT -> { val errorFormatted = String.format("%s => %s", name + (errorMessage ?: "Unknown errorMessage")) outputSources.writeOut(ANALYTICS_ERROR, errorFormatted) } ErrorHandlingOption.SUPPRESS -> { } ErrorHandlingOption.STRICT -> throw SimcoeException(errorMessage) } } private fun write(description: String, providers: List<AnalyticsTracking>) { when (outputOption) { OutputOptions.NONE -> return OutputOptions.VERBOSE -> providers.forEach { outputSources.writeOut(it.providerName(), description) } OutputOptions.SIMPLE -> outputSources.writeOut(ANALYTICS_PROVIDER_NAME, description) } } }
mit
6e989ca3f6b26c2b7e96797ee4ccdd68
29.535211
95
0.700185
4.415479
false
false
false
false
onnerby/musikcube
src/musikdroid/app/src/main/java/io/casey/musikcube/remote/ui/shared/mixin/PlaybackMixin.kt
2
2448
package io.casey.musikcube.remote.ui.shared.mixin import android.content.Context import android.content.SharedPreferences import android.os.Bundle import android.view.KeyEvent import io.casey.musikcube.remote.Application import io.casey.musikcube.remote.framework.MixinBase import io.casey.musikcube.remote.service.playback.IPlaybackService import io.casey.musikcube.remote.service.playback.PlaybackServiceFactory import io.casey.musikcube.remote.ui.settings.constants.Prefs class PlaybackMixin(var listener: (() -> Unit)? = { }): MixinBase() { private lateinit var prefs: SharedPreferences private val context = Application.instance var service: IPlaybackService = PlaybackServiceFactory.instance(context) private set override fun onCreate(bundle: Bundle) { super.onCreate(bundle) prefs = context.getSharedPreferences(Prefs.NAME, Context.MODE_PRIVATE) connect() } override fun onPause() { super.onPause() disconnect() } override fun onResume() { super.onResume() reload() } fun connectAll() { connect(PlaybackServiceFactory.streaming(context)) connect(PlaybackServiceFactory.remote(context)) } fun reload() { if (active) { disconnect() connect() } } fun onKeyDown(keyCode: Int): Boolean { if (!streaming) { if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN) { service.volumeDown() return true } else if (keyCode == KeyEvent.KEYCODE_VOLUME_UP) { service.volumeUp() return true } } return false } val streaming: Boolean get() { return prefs.getBoolean( Prefs.Key.STREAMING_PLAYBACK, Prefs.Default.STREAMING_PLAYBACK) } private fun connect() { service = PlaybackServiceFactory.instance(context) connect(service) } private fun disconnect() { disconnect(service) } private fun connect(service: IPlaybackService) { val listener = this.listener if (listener != null) { service.connect(listener) } } private fun disconnect(service: IPlaybackService) { val listener = this.listener if (listener != null) { service.disconnect(listener) } } }
bsd-3-clause
30bfbd62b57a4cf089f32e907deb0b34
25.912088
78
0.620098
4.80943
false
false
false
false
android/project-replicator
plugin/src/main/kotlin/com/android/gradle/replicator/CombineModuleInfoTask.kt
1
5141
/* * Copyright (C) 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.gradle.replicator import com.android.gradle.replicator.model.Serializer import com.android.gradle.replicator.model.internal.DefaultProjectInfo import com.android.gradle.replicator.model.toAnonymized import org.gradle.api.Action import org.gradle.api.DefaultTask import org.gradle.api.Project import org.gradle.api.artifacts.Configuration import org.gradle.api.attributes.Attribute import org.gradle.api.file.ConfigurableFileCollection import org.gradle.api.file.RegularFileProperty import org.gradle.api.provider.ListProperty import org.gradle.api.tasks.* abstract class CombineModuleInfoTask : DefaultTask() { @get:InputFiles @get:PathSensitive(PathSensitivity.NONE) abstract val subModules: ConfigurableFileCollection // optional module info if root project is also a module with plugins applied @get:InputFile @get:PathSensitive(PathSensitivity.NONE) @get:Optional abstract val localModuleInfo: RegularFileProperty @get:Input abstract val properties: ListProperty<String> @get:OutputFile abstract val outputStructure: RegularFileProperty @get:OutputFile abstract val outputMapping: RegularFileProperty @TaskAction fun action() { val serializer = Serializer.instance() val projectInfo = DefaultProjectInfo( gradleVersion = project.gradle.gradleVersion, agpVersion = findAgpVersion(), kotlinVersion = findKotlinVersion(), rootModule = serializer.deserializeModule(localModuleInfo.get().asFile), subModules = this.subModules.map { serializer.deserializeModule(it) }, gradleProperties = properties.get() ) // Remove PII val anonymizedInfo = projectInfo.toAnonymized() val structureFile = outputStructure.get().asFile structureFile.writeText(Serializer.instance().serialize(anonymizedInfo.projectInfo)) println("Structure written at: $structureFile") // write mapping file val mappingFile = outputMapping.get().asFile mappingFile.writeText(anonymizedInfo.mapping.entries.map { "${it.key} -> ${it.value}" }.joinToString(separator = "\n")) println("Mapping written at: $mappingFile") } class ConfigAction(private val project: Project, private val structureConfig: Configuration) : Action<CombineModuleInfoTask> { @Suppress("UnstableApiUsage") override fun execute(task: CombineModuleInfoTask) { task.outputStructure.set(project.layout.buildDirectory.file("project-structure.json")) task.outputStructure.disallowChanges() task.outputMapping.set(project.layout.buildDirectory.file("project-mapping.txt")) task.outputMapping.disallowChanges() task.subModules.from(structureConfig .incoming .artifactView { config -> config.attributes { container -> container.attribute<String>( Attribute.of("artifactType", String::class.java), ARTIFACT_TYPE_MODULE_INFO) } } .artifacts .artifactFiles) task.subModules.disallowChanges() // handle properties val propertyMap = project.extensions.extraProperties.properties for (entry in propertyMap.entries) { if ((entry.key.startsWith("android.") && entry.key != "android.agp.version.check.performed") || entry.key.startsWith("org.gradle.") ) { task.properties.add("${entry.key}=${entry.value}") } } task.properties.disallowChanges() } } private fun findAgpVersion(): String { for (config in project.buildscript.configurations) { for (dep in config.allDependencies) { if (dep.group == "com.android.tools.build" && dep.name == "gradle") return dep.version!! } } return "n/a" } private fun findKotlinVersion(): String { for (config in project.buildscript.configurations) { for (dep in config.allDependencies) { if (dep.group == "org.jetbrains.kotlin" && dep.name == "kotlin-gradle-plugin") return dep.version!! } } return "n/a" } }
apache-2.0
43c5f32a9e0011eaca08f817b78c6635
36.801471
127
0.645789
4.914914
false
true
false
false
dbrant/apps-android-wikipedia
app/src/main/java/org/wikipedia/util/TransitionUtil.kt
1
970
package org.wikipedia.util import android.content.Context import android.view.View import android.widget.ImageView import android.widget.TextView import androidx.core.util.Pair import org.wikipedia.settings.Prefs object TransitionUtil { @JvmStatic fun getSharedElements(context: Context, vararg views: View): Array<Pair<View, String>> { val shareElements: MutableList<Pair<View, String>> = mutableListOf() views.forEach { if (it is TextView && it.text.isNotEmpty()) { shareElements.add(Pair(it, it.transitionName)) } if (it is ImageView && it.visibility == View.VISIBLE && (it.parent as View).visibility == View.VISIBLE && !DimenUtil.isLandscape(context) && Prefs.isImageDownloadEnabled()) { shareElements.add(Pair(it, it.transitionName)) } } return shareElements.toTypedArray() } }
apache-2.0
61a4ee83bf57cc18ffe3fd813d9d68a7
33.642857
92
0.628866
4.553991
false
false
false
false
McMoonLakeDev/MoonLake
API/src/main/kotlin/com/mcmoonlake/api/dsl/DSLItemBuilder.kt
1
19730
/* * Copyright (C) 2016-Present The MoonLake ([email protected]) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ @file:JvmName("DSLItemBuilder") package com.mcmoonlake.api.dsl import com.mcmoonlake.api.attribute.AttributeItemModifier import com.mcmoonlake.api.attribute.AttributeType import com.mcmoonlake.api.attribute.Operation import com.mcmoonlake.api.attribute.Slot import com.mcmoonlake.api.chat.ChatComponent import com.mcmoonlake.api.effect.EffectBase import com.mcmoonlake.api.effect.EffectCustom import com.mcmoonlake.api.effect.EffectType import com.mcmoonlake.api.item.Enchantment import com.mcmoonlake.api.item.Generation import com.mcmoonlake.api.item.ItemBuilder import com.mcmoonlake.api.item.Pattern import com.mcmoonlake.api.nbt.NBTBase import com.mcmoonlake.api.nbt.NBTCompound import com.mcmoonlake.api.nbt.NBTList import org.bukkit.Color import org.bukkit.FireworkEffect import org.bukkit.Material import org.bukkit.entity.Entity import org.bukkit.entity.EntityType import org.bukkit.inventory.ItemFlag import org.bukkit.inventory.ItemStack import java.util.* /** * # If call the property getter, it returns the empty object. * * * Indicates that this property is only for the function setter. * * 指示此属性仅适用于函数设置器. */ @Target(AnnotationTarget.PROPERTY) @Retention(AnnotationRetention.RUNTIME) annotation class DSLItemBuilderSetterOnly @DslMarker annotation class DSLItemBuilderMarker @DSLItemBuilderMarker class DSLItemBuilderScope(itemStack: ItemStack) { private val builder = ItemBuilder.of(itemStack) private inline fun <T> ItemBuilder.apply(value: T?, block: ItemBuilder.(T) -> Unit) = if(value != null) block(this, value) else {} /** * nbt tag */ fun getTagCompound(key: String, block: (target: NBTCompound) -> Unit) { builder.getTagCompound(key, block) } fun getTagCompoundOrDefault(key: String, block: (target: NBTCompound) -> Unit) { builder.getTagCompoundOrDefault(key, block) } fun getTagCompoundOrNull(key: String, block: (target: NBTCompound?) -> Unit) { builder.getTagCompoundOrNull(key, block) } fun <T> getTagList(key: String, block: (target: NBTList<T>) -> Unit) { builder.getTagList(key, block) } fun <T> getTagListOrDefault(key: String, block: (target: NBTList<T>) -> Unit) { builder.getTagListOrDefault(key, block) } fun <T> getTagListOrNull(key: String, block: (target: NBTList<T>?) -> Unit) { builder.getTagListOrNull(key, block) } fun removeTag(key: String) { builder.removeTag(key) } fun removeTagIf(key: String, predicate: (NBTBase<*>) -> Boolean) { builder.removeTagIf(key, predicate) } /** * general meta * @see org.bukkit.inventory.meta.ItemMeta */ var displayName: String? set(value) = builder.apply(value) { setDisplayName(it) } get() { var value: String? = null builder.getDisplayName { _, displayName -> value = displayName } return value } var localizedName: String? set(value) = builder.apply(value) { setLocalizedName(it) } get() { var value: String? = null builder.getLocalizedName { _, localizedName -> value = localizedName } return value } var lore: List<String>? set(value) = builder.apply(value) { setLore(it) } get() { var value: List<String>? = null builder.getLore { _, lore -> value = lore } return value } @DSLItemBuilderSetterOnly var addLore: Array<String> set(value) = builder.apply(value) { addLore(*it) } get() = emptyArray() fun clearLore() { builder.clearLore() } var enchant: Map<Enchantment, Int>? set(value) = builder.apply(value) { clearEnchant(); it.forEach { addEnchant(it.key, it.value) } } get() { var value: Map<Enchantment, Int>? = null builder.getEnchant { _, ench -> value = ench } return value } @DSLItemBuilderSetterOnly var addEnchants: Array<Pair<Enchantment, Int>> set(value) = builder.apply(value) { it.forEach { addEnchant(it.first, it.second) } } get() = emptyArray() class EnchantScope { var enchant: Enchantment? = null var level: Int? = null } fun addEnchant(block: EnchantScope.() -> Unit) = builder.apply(DSLItemBuilderScope.EnchantScope().apply(block)) { val enchant = it.enchant val level = it.level if(enchant != null && level != null) builder.addEnchant(enchant, level) } fun clearEnchant() { builder.clearEnchant() } var flag: Collection<ItemFlag>? set(value) = builder.apply(value) { clearFlag(); addFlag(it) } get() { var value: Collection<ItemFlag>? = null builder.getFlag { _, flag -> value = flag?.toList() } return value } @DSLItemBuilderSetterOnly var addFlag: Array<ItemFlag> set(value) = builder.apply(value) { addFlag(*it) } get() = emptyArray() @DSLItemBuilderSetterOnly var removeFlag: Array<ItemFlag>? set(value) = builder.apply(value) { removeFlag(*it) } get() = emptyArray() var isUnbreakable: Boolean? set(value) = builder.apply(value) { setUnbreakable(it) } get() { var value: Boolean? = null builder.isUnbreakable { _, unbreakable -> value = unbreakable } return value } var attributes: Set<AttributeItemModifier>? set(value) = builder.apply(value) { it.forEach { addAttribute(it.type, it.operation, it.slot, it.amount, it.uuid) } } get() { var value: Set<AttributeItemModifier>? = null builder.getAttribute { _, attribute -> value = attribute } return value } @DSLItemBuilderMarker class AttributeScope { var type: AttributeType? = null var name: String? = null var operation: Operation? = null var slot: Slot? = null var amount: Double? = null var uuid: UUID = UUID.randomUUID() } fun addAttribute(block: DSLItemBuilderScope.AttributeScope.() -> Unit) = builder.apply(DSLItemBuilderScope.AttributeScope().apply(block)) { val type = it.type val operation = it.operation val amount = it.amount if(type != null && operation != null && amount != null) addAttribute(type, it.name ?: type.name, operation, it.slot, amount, it.uuid) } fun clearAttribute() { builder.clearAttribute() } var canDestroy: Array<Material>? set(value) = builder.apply(value) { setCanDestroy(*it) } get() { var value: Array<Material>? = null builder.getCanDestroy { _, canDestroy -> value = canDestroy?.toTypedArray() } return value } @DSLItemBuilderSetterOnly var addCanDestroy: Array<Material> set(value) = builder.apply(value) { addCanDestroy(*it) } get() = emptyArray() fun clearCanDestroy() { builder.clearCanDestroy() } var canPlaceOn: Array<Material>? set(value) = builder.apply(value) { setCanPlaceOn(*it) } get() { var value: Array<Material>? = null builder.getCanPlaceOn { _, canPlaceOn -> value = canPlaceOn?.toTypedArray() } return value } @DSLItemBuilderSetterOnly var addCanPlaceOn: Array<Material> set(value) = builder.apply(value) { addCanPlaceOn(*it) } get() = emptyArray() fun clearCanPlaceOn() { builder.clearCanPlaceOn() } var repairCost: Int? set(value) = builder.apply(value) { setRepairCost(it) } get() { var value: Int? = null builder.getRepairCost { _, repairCost -> value = repairCost } return value } /** * leather armor meta * @see org.bukkit.inventory.meta.LeatherArmorMeta */ var leatherColor: Color? set(value) = builder.apply(value) { setLeatherColor(it) } get() { var value: Color? = null builder.getLeatherColor { _, color -> value = color } return value } /** * book meta * @see org.bukkit.inventory.meta.BookMeta */ var bookTitle: String? set(value) = builder.apply(value) { setBookTitle(it) } get() { var value: String? = null builder.getBookTitle { _, title -> value = title } return value } var bookAuthor: String? set(value) = builder.apply(value) { setBookAuthor(it) } get() { var value: String? = null builder.getBookAuthor { _, author -> value = author } return value } var bookGeneration: Generation? set(value) = builder.apply(value) { setBookGeneration(it) } get() { var value: Generation? = null builder.getBookGeneration { _, generation -> value = generation } return value } var bookPages: Collection<String>? set(value) = builder.apply(value) { setBookPages(it) } get() { var value: Collection<String>? = null builder.getBookPages { _, pages -> value = pages } return value } @DSLItemBuilderSetterOnly var addBookPages: Array<String> set(value) = builder.apply(value) { addBookPages(*it) } get() = emptyArray() @DSLItemBuilderSetterOnly var addBookPageComponents: Array<ChatComponent> set(value) = builder.apply(value) { addBookPages(*it) } get() = emptyArray() fun clearBookPages() { builder.clearBookPages() } /** * enchantment storage meta * @see org.bukkit.inventory.meta.EnchantmentStorageMeta */ var storedEnchant: Map<Enchantment, Int>? set(value) = builder.apply(value) { clearStoredEnchant(); it.forEach { addStoredEnchant(it.key, it.value) } } get() { var value: Map<Enchantment, Int>? = null builder.getStoredEnchant { _, ench -> value = ench } return value } @DSLItemBuilderSetterOnly var addStoredEnchants: Array<Pair<Enchantment, Int>> set(value) = builder.apply(value) { it.forEach { addStoredEnchant(it.first, it.second) } } get() = emptyArray() fun addStoredEnchant(block: EnchantScope.() -> Unit) = builder.apply(DSLItemBuilderScope.EnchantScope().apply(block)) { val enchant = it.enchant val level = it.level if(enchant != null && level != null) builder.addStoredEnchant(enchant, level) } fun clearStoredEnchant() { builder.clearStoredEnchant() } /** * skull meta * @see org.bukkit.inventory.meta.SkullMeta */ var skullOwner: String? set(value) = builder.apply(value) { setSkullOwner(it) } get() { var value: String? = null builder.getSkullOwner { _, owner -> value = owner } return value } var skullTexture: String? set(value) = builder.apply(value) { setSkullTexture(it) } get() { var value0: String? = null builder.getSkullTexture { _, value -> value0 = value } return value0 } /** * spawn egg meta * @see org.bukkit.inventory.meta.SpawnEggMeta */ var spawnEggType: EntityType? set(value) = builder.apply(value) { setSpawnEggType(it) } get() { var value: EntityType? = null builder.getSpawnEggType { _, type -> value = type } return value } @DSLItemBuilderSetterOnly var spawnEggEntity: Entity? set(value) = builder.apply(value) { setSpawnEggType(it) } get() = null /** * map meta * @see org.bukkit.inventory.meta.MapMeta */ var isMapScaling: Boolean? set(value) = builder.apply(value) { setMapScaling(it) } get() { var value = false builder.getMapScaling { _, scaling -> value = scaling } return value } var mapLocationName: String? set(value) = builder.apply(value) { setMapLocationName(it) } get() { var value: String? = null builder.getMapLocationName { _, locationName -> value = locationName } return value } var mapColor: Color? set(value) = builder.apply(value) { setMapColor(it) } get() { var value: Color? = null builder.getMapColor { _, color -> value = color } return value } /** * potion meta * @see org.bukkit.inventory.meta.PotionMeta */ var potionColor: Color? set(value) = builder.apply(value) { setPotionColor(it) } get() { var value: Color? = null builder.getPotionColor { _, color -> value = color } return value } var potionBase: EffectBase? set(value) = builder.apply(value) { setPotionBase(it) } get() { var value: EffectBase? = null builder.getPotionBase { _, base -> value = base } return value } var potionEffect: Collection<EffectCustom>? set(value) = builder.apply(value) { setPotionEffect(it) } get() { var value: Collection<EffectCustom>? = null builder.getPotionEffect { _, effect -> value = effect } return value } @DSLItemBuilderSetterOnly var addPotionEffect: Array<EffectCustom> set(value) = builder.apply(value) { addPotionEffect(*it) } get() = emptyArray() @DSLItemBuilderMarker class PotionEffectScope { var type: EffectType? = null var duration: Int? = null var amplifier: Int? = null var ambient: Boolean = true var particle: Boolean = true var color: Color? = null } fun addPotionEffect(block: DSLItemBuilderScope.PotionEffectScope.() -> Unit) = builder.apply(DSLItemBuilderScope.PotionEffectScope().apply(block)) { val type = it.type val duration = it.duration val amplifier = it.amplifier if(type != null && duration != null && amplifier != null) addPotionEffect(type, duration, amplifier, it.ambient, it.particle, it.color) } fun clearPotionEffect() { builder.clearPotionEffect() } /** * firework charge * @see org.bukkit.inventory.meta.FireworkEffectMeta */ var fireworkCharge: FireworkEffect? set(value) = builder.apply(value) { setFireworkCharge(it) } get() { var value: FireworkEffect? = null builder.getFireworkCharge { _, effect -> value = effect } return value } fun setFireworkCharge(block: DSLItemBuilderScope.FireworkEffectScope.() -> Unit) = builder.apply(DSLItemBuilderScope.FireworkEffectScope().apply(block)) { val type = it.type if(type != null) { val effect = FireworkEffect.builder() .with(type) .flicker(it.flicker ?: false) .trail(it.trail ?: false) .withColor(*it.colors ?: arrayOf()) .withFade(*it.fadeColors ?: arrayOf()) fireworkCharge = effect.build() } } /** * firework meta * @see org.bukkit.inventory.meta.FireworkMeta */ var fireworkEffect: Collection<FireworkEffect>? set(value) = builder.apply(value) { setFireworkEffect(it) } get() { var value: Collection<FireworkEffect>? = null builder.getFireworkEffect { _, effect -> value = effect } return value } @DSLItemBuilderSetterOnly var addFireworkEffect: Array<FireworkEffect> set(value) = builder.apply(value) { addFireworkEffect(*it) } get() = emptyArray() @DSLItemBuilderMarker class FireworkEffectScope { var type: FireworkEffect.Type? = null var flicker: Boolean? = null var trail: Boolean? = null var colors: Array<Color>? = null var fadeColors: Array<Color>? = null } fun addFirework(block: DSLItemBuilderScope.FireworkEffectScope.() -> Unit) = builder.apply(DSLItemBuilderScope.FireworkEffectScope().apply(block)) { val type = it.type if(type != null) { val effect = FireworkEffect.builder() .with(type) .flicker(it.flicker ?: false) .trail(it.trail ?: false) .withColor(*it.colors ?: arrayOf()) .withFade(*it.fadeColors ?: arrayOf()) addFireworkEffect(effect.build()) } } fun clearFireworkEffect() { builder.clearFireworkEffect() } var fireworkPower: Int? set(value) = builder.apply(value) { setFireworkPower(it) } get() { var value: Int? = null builder.getFireworkPower { _, power -> value = power } return value } /** * banner meta * @see org.bukkit.inventory.meta.BannerMeta */ var bannerPattern: Collection<Pattern>? set(value) = builder.apply(value) { setBannerPattern(it) } get() { var value: Collection<Pattern>? = null builder.getBannerPattern { _, pattern -> value = pattern } return value } @DSLItemBuilderSetterOnly var addBannerPattern: Array<Pattern>? set(value) = builder.apply(value) { it.forEach { addBannerPattern(it) } } get() = emptyArray() fun clearBannerPattern() { builder.clearBannerPattern() } /** * knowledge book meta * @see org.bukkit.inventory.meta.KnowledgeBookMeta */ var knowledgeBookRecipes: List<Material>? set(value) = builder.apply(value) { setKnowledgeBookRecipes(it) } get() { var value: List<Material>? = null builder.getKnowledgeBookRecipes { _, recipes -> value = recipes } return value } @DSLItemBuilderSetterOnly var addKnowledgeBookRecipes: Array<Material> set(value) = builder.apply(value) { addKnowledgeBookRecipes(*it) } get() = emptyArray() /** * * Not recommended for external calls. * * @see [buildItemBuilder] */ fun get(): ItemBuilder = builder } inline fun ItemStack.buildItemBuilder(block: DSLItemBuilderScope.() -> Unit): ItemBuilder = DSLItemBuilderScope(this).also(block).get() @JvmOverloads inline fun Material.buildItemBuilder(amount: Int = 1, durability: Int = 0, block: DSLItemBuilderScope.() -> Unit): ItemBuilder = DSLItemBuilderScope(ItemStack(this, amount, durability.toShort())).also(block).get()
gpl-3.0
7bfd882063531e49cdc8244885a098ab
31.565289
126
0.600548
4.18746
false
false
false
false
dahlstrom-g/intellij-community
plugins/gradle/testSources/org/jetbrains/plugins/gradle/importing/UnsupportedGradleImportingTest.kt
7
1808
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.plugins.gradle.importing import com.intellij.util.lang.JavaVersion import org.gradle.util.GradleVersion import org.jetbrains.plugins.gradle.tooling.VersionMatcherRule import org.junit.Test import org.junit.runners.Parameterized class UnsupportedGradleImportingTest : BuildViewMessagesImportingTestCase() { @Test fun testSyncMessages() { importProject("") val expectedExecutionTree: String when { currentGradleVersion < GradleVersion.version("2.6") -> expectedExecutionTree = "-\n" + " -failed\n" + " Unsupported Gradle" currentGradleVersion < GradleVersion.version("3.0") -> expectedExecutionTree = "-\n" + " -finished\n" + " Gradle ${currentGradleVersion.version} support can be dropped in the next release" else -> expectedExecutionTree = "-\n" + " finished" } assertSyncViewTreeEquals(expectedExecutionTree) } override fun assumeTestJavaRuntime(javaRuntimeVersion: JavaVersion) { // run on all Java Runtime } companion object { private val OLD_GRADLE_VERSIONS = arrayOf( arrayOf("0.9"), /*..., */arrayOf("0.9.2"), arrayOf("1.0"), /*arrayOf("1.1"), arrayOf("1.2"), ..., */arrayOf("1.12"), arrayOf("2.0"), /*arrayOf("2.1"), arrayOf("2.2"), ..., */arrayOf("2.5"), arrayOf("2.6"), arrayOf("2.14.1")) /** * Run the test against very old not-supported Gradle versions also */ @Parameterized.Parameters(name = "with Gradle-{0}") @JvmStatic fun tests(): Array<out Array<String>> { return OLD_GRADLE_VERSIONS + VersionMatcherRule.SUPPORTED_GRADLE_VERSIONS } } }
apache-2.0
dd50ac188a9a239fcea3fa7078b52ae6
34.45098
120
0.658186
4.081264
false
true
false
false
ngthtung2805/dalatlaptop
app/src/main/java/com/tungnui/abccomputer/api/ServiceGenerator.kt
1
1572
package com.tungnui.abccomputer.api import android.text.TextUtils import com.google.gson.GsonBuilder import com.jakewharton.retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory import okhttp3.Credentials import okhttp3.OkHttpClient import retrofit2.Retrofit import retrofit2.converter.gson.GsonConverterFactory /** * Created by thanh on 22/09/2017. */ object ServiceGenerator { val API_BASE_URL ="https://abccomputer.tungnui.com" val CONSUMER_KEY ="ck_9c06a645be257c36f5b8545064559caf7d7eab05" val CONSUMER_SECRET = "cs_eba612121c821ba1fb8c3ba50692a27c204a0226" private val httpClient = OkHttpClient.Builder() private val json = GsonBuilder().setLenient().create() private val builder = Retrofit.Builder() .baseUrl(API_BASE_URL) .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) .addConverterFactory(GsonConverterFactory.create(json)) private var retrofit = builder.build() fun <S> createService(serviceClass: Class<S>): S = createService(serviceClass, Credentials.basic(CONSUMER_KEY, CONSUMER_SECRET)) fun <S> createService(serviceClass: Class<S>, authToken: String): S { if (!TextUtils.isEmpty(authToken)) { val interceptor = AuthenticationInterceptor(authToken) if (!httpClient.interceptors().contains(interceptor)) { httpClient.addInterceptor(interceptor) builder.client(httpClient.build()) retrofit = builder.build() } } return retrofit.create(serviceClass) } }
mit
a1c13c9859267e30f07421ba3f05d48f
38.325
87
0.713104
4.295082
false
false
false
false
DreierF/MyTargets
shared/src/main/java/de/dreier/mytargets/shared/targets/models/WAVegas3Spot.kt
1
1304
/* * Copyright (C) 2018 Florian Dreier * * This file is part of MyTargets. * * MyTargets is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 * as published by the Free Software Foundation. * * MyTargets is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. */ package de.dreier.mytargets.shared.targets.models import android.graphics.PointF import de.dreier.mytargets.shared.R import de.dreier.mytargets.shared.models.Dimension import de.dreier.mytargets.shared.models.Dimension.Unit.CENTIMETER class WAVegas3Spot : WA5Ring( id = ID, nameRes = R.string.vegas_3_spot, diameters = listOf( Dimension(40f, CENTIMETER), Dimension(60f, CENTIMETER) ) ) { init { faceRadius = 0.48f facePositions = listOf( PointF(-0.52f, 0.5f), PointF(0.0f, -0.5f), PointF(0.52f, 0.5f) ) } override val singleSpotTargetId: Long get() = WA5Ring.ID companion object { private const val ID = 4L } }
gpl-2.0
43fe18b5061d4a100e25ddc21734eed8
26.744681
68
0.652607
3.835294
false
false
false
false
sachil/Essence
app/src/main/java/xyz/sachil/essence/fragment/vh/PlainTextDataViewHolder.kt
1
866
package xyz.sachil.essence.fragment.vh import androidx.recyclerview.widget.RecyclerView import xyz.sachil.essence.databinding.RecyclerItemPlainTextBinding import xyz.sachil.essence.model.net.bean.TypeData class PlainTextDataViewHolder(private val viewBinding: RecyclerItemPlainTextBinding) : RecyclerView.ViewHolder(viewBinding.root) { companion object { const val ITEM_TYPE_PLAIN_TEXT = 0x03 } fun bindView(typeData: TypeData) { viewBinding.title.text = typeData.title.replace("\n", "") viewBinding.author.text = typeData.author viewBinding.publishDate.text = typeData.publishedDate.subSequence(0, 10) viewBinding.description.text = typeData.description.replace("\n", "") viewBinding.viewCounts.text = "${typeData.viewCounts}" viewBinding.likeCounts.text = "${typeData.likeCounts}" } }
apache-2.0
0fee76c11b0813eed8ed05e1a38363db
38.409091
86
0.740185
4.26601
false
false
false
false
nibarius/opera-park-android
app/src/main/java/se/barsk/park/storage/Database.kt
1
5270
package se.barsk.park.storage import android.content.ContentValues import android.content.Context import android.database.sqlite.SQLiteDatabase import se.barsk.park.R import se.barsk.park.datatypes.OwnCar /** * Class for handling all the interactions with the database storage. */ class Database(context: Context, dbName: String = context.getString(R.string.parked_cars_database_name)) { private val dbHelper = ParkDbHelper(context, dbName) fun fetchAllCars(): MutableList<OwnCar> { val projection: Array<String> = arrayOf( ParkContract.CarCollectionTable.COLUMN_NAME_REGNO, ParkContract.CarCollectionTable.COLUMN_NAME_OWNER, ParkContract.CarCollectionTable.COLUMN_NAME_NICKNAME, ParkContract.CarCollectionTable.COLUMN_NAME_UUID ) val sortOrder = ParkContract.CarCollectionTable.COLUMN_NAME_POSITION + " ASC" val db = dbHelper.readableDatabase val cursor = db.query( ParkContract.CarCollectionTable.TABLE_NAME, projection, null, // No where clause null, // No where clause args null, // No grouping null, // No filtering sortOrder ) val ownCars: MutableList<OwnCar> = mutableListOf() while (cursor.moveToNext()) { var regno = cursor.getString(cursor.getColumnIndexOrThrow(ParkContract.CarCollectionTable.COLUMN_NAME_REGNO)) if (regno.isBlank()) { // In version 2.1 and below it was possible to create a car with only whitespace // in the licence plate number. When doing this the app would crash every time // the user enters the mange cars view making it impossible to fix the licence // plate number. When reading from storage replace blank licence plate numbers // with just a '?' regno = "?" } ownCars.add(OwnCar( regno, cursor.getString(cursor.getColumnIndexOrThrow(ParkContract.CarCollectionTable.COLUMN_NAME_OWNER)), cursor.getString(cursor.getColumnIndexOrThrow(ParkContract.CarCollectionTable.COLUMN_NAME_NICKNAME)), cursor.getString(cursor.getColumnIndexOrThrow(ParkContract.CarCollectionTable.COLUMN_NAME_UUID)) )) } cursor.close() return ownCars } fun insertOrReplace(ownCar: OwnCar, position: Int) { val db = dbHelper.writableDatabase val values = ContentValues() values.put(ParkContract.CarCollectionTable.COLUMN_NAME_POSITION, position) values.put(ParkContract.CarCollectionTable.COLUMN_NAME_REGNO, ownCar.regNo) values.put(ParkContract.CarCollectionTable.COLUMN_NAME_OWNER, ownCar.owner) values.put(ParkContract.CarCollectionTable.COLUMN_NAME_NICKNAME, ownCar.nickName) values.put(ParkContract.CarCollectionTable.COLUMN_NAME_UUID, ownCar.id) db.insertWithOnConflict( ParkContract.CarCollectionTable.TABLE_NAME, null, // no nullColumnHack values, SQLiteDatabase.CONFLICT_REPLACE ) } fun remove(ownCar: OwnCar) { val position = getPosition(ownCar) val db = dbHelper.writableDatabase db.delete( ParkContract.CarCollectionTable.TABLE_NAME, "${ParkContract.CarCollectionTable.COLUMN_NAME_UUID} = ?", arrayOf(ownCar.id) ) decreasePositionsAbove(position) } /** * Returns the position for the given car or Int.MAX_VALUE if the car doesn't exist */ private fun getPosition(ownCar: OwnCar): Int { val projection: Array<String> = arrayOf( ParkContract.CarCollectionTable.COLUMN_NAME_POSITION ) val selection = ParkContract.CarCollectionTable.COLUMN_NAME_UUID + " = ?" val selectionArgs: Array<String> = arrayOf(ownCar.id) val db = dbHelper.readableDatabase val cursor = db.query( ParkContract.CarCollectionTable.TABLE_NAME, projection, selection, selectionArgs, null, // No grouping null, // No filtering null // No sorting ) val pos = if (cursor.moveToFirst()) { cursor.getInt(cursor.getColumnIndexOrThrow(ParkContract.CarCollectionTable.COLUMN_NAME_POSITION)) } else { Int.MAX_VALUE } cursor.close() return pos } /** * Decrease the position by one of all items with higher position than the given position. */ private fun decreasePositionsAbove(position: Int) { val updateSQL = "UPDATE " + ParkContract.CarCollectionTable.TABLE_NAME + " SET " + ParkContract.CarCollectionTable.COLUMN_NAME_POSITION + " = " + ParkContract.CarCollectionTable.COLUMN_NAME_POSITION + " - 1" + " WHERE " + ParkContract.CarCollectionTable.COLUMN_NAME_POSITION + " > " + position val db = dbHelper.writableDatabase db.execSQL(updateSQL) } }
mit
7e368e20c47d614246d08f8036c30a98
40.503937
121
0.624099
4.826007
false
false
false
false
BreakOutEvent/breakout-backend
src/main/java/backend/Teamoverview/ContactWithHeadquarters.kt
1
886
package backend.teamoverview import backend.model.BasicEntity import backend.model.event.Team import backend.model.user.UserAccount import javax.persistence.* @Entity class ContactWithHeadquarters : BasicEntity { enum class Reason { TECHNICAL_PROBLEM, FIVE_HOUR_NOTIFICATION, NEW_TRANSPORT, FINISHED, SICKNESS, EMERGENCY, OTHER } @ManyToOne(fetch = FetchType.LAZY) var team: Team? = null var reason: Reason? = null @Column(columnDefinition = "TEXT") var comment: String? = null @ManyToOne(fetch = FetchType.LAZY) var admin: UserAccount? = null private constructor() : super() constructor(team: Team, reason: Reason, comment: String?, admin: UserAccount) { this.team = team this.reason = reason this.comment = comment this.admin = admin } }
agpl-3.0
83cd994b899198d8ee1695098c52f702
20.609756
83
0.648984
4.140187
false
false
false
false
arnab/adventofcode
src/main/kotlin/aoc2020/day3/Forest.kt
1
1891
package aoc2020.day3 object Forest { /** * Forest is organized as a 2D array where, Y -> 1st dim, X -> 2nd dim. * Each spot can be analyzed with [isOccupied] to see if there is a tree there. */ fun parse(data: String): List<List<Char>> = data.split("\n") .reversed() .map { it.toCharArray().toList() } fun walkAndCount(forest: List<List<Char>>, stepX: Int, stepY: Int) = walkAndCountRecursively( currentTreeCount = 0, currentX = 0, currentY = forest.size -1, stepX, stepY, forest ) private fun walkAndCountRecursively( currentTreeCount: Int, currentX: Int, currentY: Int, stepX: Int, stepY: Int, forest: List<List<Char>> ): Int { val nextGenForest = expandForestIfRequired(currentX, forest) val currentSpot = nextGenForest[currentY][currentX] val nextTreeCount = currentTreeCount + if (currentSpot.isOccupied()) 1 else 0 val nextX = currentX + stepX val nextY = currentY - stepY if (nextY < 0) { // we have passed through the end/bottom of the forest return nextTreeCount } return walkAndCountRecursively( currentTreeCount = nextTreeCount, currentX = nextX, currentY = nextY, stepX, stepY, nextGenForest ) } private fun Char.isOccupied() = this == '#' /** * Expand the forest, by duplicating it along the X-axis (the 2nd dim) for each Y (row), if we are out of the * currently known bounds of the forest (along the X-axis). */ private fun expandForestIfRequired(currentX: Int, forest: List<List<Char>>) = if (currentX < forest[0].size) { forest } else { forest.map { it + it } } }
mit
7593c83e379a5248e533f3bf04d3fc0e
30
113
0.570069
4.128821
false
false
false
false
google/intellij-community
platform/platform-impl/src/com/intellij/ide/plugins/marketplace/MarketplaceRequests.kt
1
20579
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.ide.plugins.marketplace import com.fasterxml.jackson.core.type.TypeReference import com.fasterxml.jackson.databind.ObjectMapper import com.intellij.ide.IdeBundle import com.intellij.ide.plugins.PluginInfoProvider import com.intellij.ide.plugins.PluginNode import com.intellij.ide.plugins.auth.PluginRepositoryAuthService import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.application.PathManager import com.intellij.openapi.application.impl.ApplicationInfoImpl import com.intellij.openapi.components.serviceOrNull import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.extensions.PluginId import com.intellij.openapi.progress.ProgressIndicator import com.intellij.openapi.util.BuildNumber import com.intellij.util.Url import com.intellij.util.Urls import com.intellij.util.concurrency.annotations.RequiresBackgroundThread import com.intellij.util.concurrency.annotations.RequiresReadLockAbsence import com.intellij.util.io.* import com.intellij.util.ui.IoErrorText import org.jetbrains.annotations.ApiStatus import org.jetbrains.annotations.Nls import org.jetbrains.annotations.VisibleForTesting import org.xml.sax.InputSource import org.xml.sax.SAXException import java.io.IOException import java.io.InputStream import java.net.HttpURLConnection import java.net.URLConnection import java.net.UnknownHostException import java.nio.file.Files import java.nio.file.NoSuchFileException import java.nio.file.Path import java.nio.file.Paths import java.util.concurrent.Callable import java.util.concurrent.Future import javax.xml.parsers.ParserConfigurationException import javax.xml.parsers.SAXParserFactory private val LOG = logger<MarketplaceRequests>() private const val FULL_PLUGINS_XML_IDS_FILENAME = "pluginsXMLIds.json" private val objectMapper by lazy { ObjectMapper() } private val pluginManagerUrl by lazy(LazyThreadSafetyMode.PUBLICATION) { ApplicationInfoImpl.getShadowInstance().pluginManagerUrl.trimEnd('/') } private val compatibleUpdateUrl: String get() = "${pluginManagerUrl}/api/search/compatibleUpdates" @ApiStatus.Internal class MarketplaceRequests : PluginInfoProvider { companion object { @JvmStatic fun getInstance(): MarketplaceRequests = PluginInfoProvider.getInstance() as MarketplaceRequests @JvmStatic fun parsePluginList(input: InputStream): List<PluginNode> { try { val handler = RepositoryContentHandler() SAXParserFactory.newDefaultInstance().newSAXParser().parse(InputSource(input), handler) return handler.pluginsList } catch (e: Exception) { when (e) { is ParserConfigurationException, is SAXException, is RuntimeException -> throw IOException(e) else -> throw e } } } @RequiresBackgroundThread @RequiresReadLockAbsence @JvmStatic @JvmOverloads fun loadLastCompatiblePluginDescriptors( pluginIds: Set<PluginId>, buildNumber: BuildNumber? = null, throwExceptions: Boolean = false ): List<PluginNode> { return getLastCompatiblePluginUpdate(pluginIds, buildNumber, throwExceptions) .map { loadPluginDescriptor(it.pluginId, it, null) } } @RequiresBackgroundThread @RequiresReadLockAbsence @JvmStatic @JvmOverloads fun getLastCompatiblePluginUpdate( ids: Set<PluginId>, buildNumber: BuildNumber? = null, throwExceptions: Boolean = false ): List<IdeCompatibleUpdate> { try { if (ids.isEmpty()) { return emptyList() } val data = objectMapper.writeValueAsString(CompatibleUpdateRequest(ids, buildNumber)) return HttpRequests.post(Urls.newFromEncoded(compatibleUpdateUrl).toExternalForm(), HttpRequests.JSON_CONTENT_TYPE).run { productNameAsUserAgent() throwStatusCodeException(throwExceptions) connect { it.write(data) objectMapper.readValue(it.inputStream, object : TypeReference<List<IdeCompatibleUpdate>>() {}) } } } catch (e: Exception) { LOG.infoOrDebug("Can not get compatible updates from Marketplace", e) return emptyList() } } @RequiresBackgroundThread @RequiresReadLockAbsence @JvmStatic @JvmOverloads @Throws(IOException::class) internal fun loadPluginDescriptor( xmlId: String, ideCompatibleUpdate: IdeCompatibleUpdate, indicator: ProgressIndicator? = null, ): PluginNode { val updateMetadataFile = Paths.get(PathManager.getPluginTempPath(), "meta") return readOrUpdateFile( updateMetadataFile.resolve(ideCompatibleUpdate.externalUpdateId + ".json"), "$pluginManagerUrl/files/${ideCompatibleUpdate.externalPluginId}/${ideCompatibleUpdate.externalUpdateId}/meta.json", indicator, IdeBundle.message("progress.downloading.plugins.meta", xmlId) ) { objectMapper.readValue(it, IntellijUpdateMetadata::class.java) }.toPluginNode() } @JvmStatic @JvmName("readOrUpdateFile") @Throws(IOException::class) internal fun <T> readOrUpdateFile( file: Path?, url: String, indicator: ProgressIndicator?, @Nls indicatorMessage: String, parser: (InputStream) -> T ): T { val eTag = if (file == null) null else loadETagForFile(file) return HttpRequests .request(url) .tuner { connection -> if (eTag != null) { connection.setRequestProperty("If-None-Match", eTag) } if (ApplicationManager.getApplication() != null) { serviceOrNull<PluginRepositoryAuthService>() ?.connectionTuner ?.tune(connection) } } .productNameAsUserAgent() .connect { request -> try { indicator?.checkCanceled() val connection = request.connection if (file != null && isNotModified(connection, file)) { return@connect Files.newInputStream(file).use(parser) } if (indicator != null) { indicator.checkCanceled() indicator.text2 = indicatorMessage } if (file == null) { return@connect request.inputStream.use(parser) } synchronized(this) { request.saveToFile(file, indicator) connection.getHeaderField("ETag")?.let { saveETagForFile(file, it) } } return@connect Files.newInputStream(file).use(parser) } catch (e: HttpRequests.HttpStatusException) { LOG.infoWithDebug("Cannot load data from ${url} (statusCode=${e.statusCode})", e) throw e } catch (e: Exception) { LOG.infoWithDebug("Error reading Marketplace file: ${e} (file=${file} URL=${url})", e) if (file != null && LOG.isDebugEnabled) { LOG.debug("File content:\n${runCatching { Files.readString(file) }.getOrElse { IoErrorText.message(e) }}") } throw e } } } } private val IDE_BUILD_FOR_REQUEST = URLUtil.encodeURIComponent(ApplicationInfoImpl.getShadowInstanceImpl().pluginsCompatibleBuild) private val MARKETPLACE_ORGANIZATIONS_URL = Urls.newFromEncoded("${pluginManagerUrl}/api/search/aggregation/organizations") .addParameters(mapOf("build" to IDE_BUILD_FOR_REQUEST)) private val JETBRAINS_PLUGINS_URL = Urls.newFromEncoded( "${pluginManagerUrl}/api/search/plugins?organization=JetBrains&max=1000" ).addParameters(mapOf("build" to IDE_BUILD_FOR_REQUEST)) private val IDE_EXTENSIONS_URL = Urls.newFromEncoded("${pluginManagerUrl}/files/IDE/extensions.json") .addParameters(mapOf("build" to IDE_BUILD_FOR_REQUEST)) private fun createSearchUrl(query: String, count: Int): Url { return Urls.newFromEncoded("$pluginManagerUrl/api/search/plugins?$query&build=$IDE_BUILD_FOR_REQUEST&max=$count") } private fun createFeatureUrl(param: Map<String, String>): Url { return Urls.newFromEncoded("${pluginManagerUrl}/feature/getImplementations").addParameters(param) } @Throws(IOException::class) fun getFeatures(param: Map<String, String>): List<FeatureImpl> { if (param.isEmpty()) { return emptyList() } try { return HttpRequests .request(createFeatureUrl(param)) .throwStatusCodeException(false) .productNameAsUserAgent() .setHeadersViaTuner() .connect { objectMapper.readValue( it.inputStream, object : TypeReference<List<FeatureImpl>>() {} ) } } catch (e: Exception) { LOG.infoOrDebug("Can not get features from Marketplace", e) return emptyList() } } @Throws(IOException::class) internal fun getFeatures( featureType: String, implementationName: String, ): List<FeatureImpl> { val param = mapOf( "featureType" to featureType, "implementationName" to implementationName, "build" to ApplicationInfoImpl.getShadowInstanceImpl().pluginsCompatibleBuild, ) return getFeatures(param) } @RequiresBackgroundThread @JvmOverloads @Throws(IOException::class) fun getMarketplacePlugins(indicator: ProgressIndicator? = null): Set<PluginId> { try { return readOrUpdateFile( Path.of(PathManager.getPluginTempPath(), FULL_PLUGINS_XML_IDS_FILENAME), "${pluginManagerUrl}/files/$FULL_PLUGINS_XML_IDS_FILENAME", indicator, IdeBundle.message("progress.downloading.available.plugins"), ::parseXmlIds, ) } catch (e: UnknownHostException) { LOG.infoOrDebug("Cannot get plugins from Marketplace", e) return emptySet() } } override fun loadPlugins(indicator: ProgressIndicator?): Future<Set<PluginId>> { return ApplicationManager.getApplication().executeOnPooledThread(Callable { try { getMarketplacePlugins(indicator) } catch (e: IOException) { LOG.infoOrDebug("Cannot get plugins from Marketplace", e) emptySet() } }) } override fun loadCachedPlugins(): Set<PluginId>? { val pluginXmlIdsFile = Paths.get(PathManager.getPluginTempPath(), FULL_PLUGINS_XML_IDS_FILENAME) try { if (Files.size(pluginXmlIdsFile) > 0) { return Files.newInputStream(pluginXmlIdsFile).use(::parseXmlIds) } } catch (ignore: IOException) { } return null } @Throws(IOException::class) fun searchPlugins(query: String, count: Int): List<PluginNode> { val marketplaceSearchPluginData = HttpRequests .request(createSearchUrl(query, count)) .setHeadersViaTuner() .throwStatusCodeException(false) .connect { objectMapper.readValue( it.inputStream, object : TypeReference<List<MarketplaceSearchPluginData>>() {} ) } // Marketplace Search Service can produce objects without "externalUpdateId". It means that an update is not in the search index yet. return marketplaceSearchPluginData.filter { it.externalUpdateId != null }.map { it.toPluginNode() } } fun getAllPluginsVendors(): List<String> { try { return HttpRequests .request(MARKETPLACE_ORGANIZATIONS_URL) .setHeadersViaTuner() .productNameAsUserAgent() .throwStatusCodeException(false) .connect { objectMapper.readValue(it.inputStream, AggregationSearchResponse::class.java).aggregations.keys.toList() } } catch (e: Exception) { LOG.infoOrDebug("Can not get organizations from Marketplace", e) return emptyList() } } fun getBrokenPlugins(currentBuild: BuildNumber): Map<PluginId, Set<String>> { val brokenPlugins = try { readOrUpdateFile( Paths.get(PathManager.getPluginTempPath(), "brokenPlugins.json"), "${pluginManagerUrl}/files/brokenPlugins.json", null, "" ) { objectMapper.readValue(it, object : TypeReference<List<MarketplaceBrokenPlugin>>() {}) } } catch (e: Exception) { LOG.infoOrDebug("Can not get broken plugins file from Marketplace", e) return emptyMap() } val brokenPluginsMap = HashMap<PluginId, MutableSet<String>>() brokenPlugins.forEach { record -> try { val parsedOriginalUntil = record.originalUntil?.trim() val parsedOriginalSince = record.originalSince?.trim() if (!parsedOriginalUntil.isNullOrEmpty() && !parsedOriginalSince.isNullOrEmpty()) { val originalUntil = BuildNumber.fromString(parsedOriginalUntil, record.id, null) ?: currentBuild val originalSince = BuildNumber.fromString(parsedOriginalSince, record.id, null) ?: currentBuild val until = BuildNumber.fromString(record.until) ?: currentBuild val since = BuildNumber.fromString(record.since) ?: currentBuild if (currentBuild in originalSince..originalUntil && currentBuild !in since..until) { brokenPluginsMap.computeIfAbsent(PluginId.getId(record.id)) { HashSet() }.add(record.version) } } } catch (e: Exception) { LOG.error("cannot parse ${record}", e) } } return brokenPluginsMap } fun getAllPluginsTags(): List<String> { try { return HttpRequests .request(Urls.newFromEncoded( "${pluginManagerUrl}/api/search/aggregation/tags" ).addParameters(mapOf("build" to IDE_BUILD_FOR_REQUEST))) .setHeadersViaTuner() .productNameAsUserAgent() .throwStatusCodeException(false) .connect { objectMapper.readValue(it.inputStream, AggregationSearchResponse::class.java).aggregations.keys.toList() } } catch (e: Exception) { LOG.infoOrDebug("Can not get tags from Marketplace", e) return emptyList() } } @RequiresBackgroundThread @RequiresReadLockAbsence @JvmOverloads fun loadPluginDetails( pluginNode: PluginNode, indicator: ProgressIndicator? = null, ): PluginNode? { val externalPluginId = pluginNode.externalPluginId ?: return pluginNode val externalUpdateId = pluginNode.externalUpdateId ?: return pluginNode try { return loadPluginDescriptor( pluginNode.pluginId.idString, IdeCompatibleUpdate(externalUpdateId = externalUpdateId, externalPluginId = externalPluginId), indicator, ).apply { // these three fields are not present in `IntellijUpdateMetadata`, but present in `MarketplaceSearchPluginData` rating = pluginNode.rating downloads = pluginNode.downloads date = pluginNode.date } } catch (e: IOException) { LOG.error(e) return null } } @Deprecated("Please use `PluginId`", replaceWith = ReplaceWith("getLastCompatiblePluginUpdate(PluginId.get(id), buildNumber, indicator)")) @ApiStatus.ScheduledForRemoval @RequiresBackgroundThread @RequiresReadLockAbsence @JvmOverloads fun getLastCompatiblePluginUpdate( id: String, buildNumber: BuildNumber? = null, indicator: ProgressIndicator? = null, ): PluginNode? = getLastCompatiblePluginUpdate(PluginId.getId(id), buildNumber, indicator) @RequiresBackgroundThread @RequiresReadLockAbsence @JvmOverloads fun getLastCompatiblePluginUpdate( pluginId: PluginId, buildNumber: BuildNumber? = null, indicator: ProgressIndicator? = null, ): PluginNode? { return getLastCompatiblePluginUpdate(setOf(pluginId), buildNumber).firstOrNull() ?.let { loadPluginDescriptor(pluginId.idString, it, indicator) } } fun getCompatibleUpdateByModule(module: String): PluginId? { try { val data = objectMapper.writeValueAsString(CompatibleUpdateForModuleRequest(module)) return HttpRequests.post( Urls.newFromEncoded(compatibleUpdateUrl).toExternalForm(), HttpRequests.JSON_CONTENT_TYPE, ).productNameAsUserAgent() .throwStatusCodeException(false) .connect { it.write(data) objectMapper.readValue(it.inputStream, object : TypeReference<List<IdeCompatibleUpdate>>() {}) }.firstOrNull() ?.pluginId ?.let { PluginId.getId(it) } } catch (e: Exception) { LOG.infoOrDebug("Can not get compatible update by module from Marketplace", e) return null } } var jetBrainsPluginsIds: Set<String>? = null private set fun loadJetBrainsPluginsIds() { if (jetBrainsPluginsIds != null) { return } try { HttpRequests .request(JETBRAINS_PLUGINS_URL) .productNameAsUserAgent() .setHeadersViaTuner() .throwStatusCodeException(false) .connect { deserializeJetBrainsPluginsIds(it.inputStream) } } catch (e: Exception) { LOG.infoOrDebug("Can not get JetBrains plugins' IDs from Marketplace", e) jetBrainsPluginsIds = null } } @VisibleForTesting fun deserializeJetBrainsPluginsIds(stream: InputStream) { jetBrainsPluginsIds = objectMapper.readValue(stream, object : TypeReference<List<MarketplaceSearchPluginData>>() {}) .asSequence() .map(MarketplaceSearchPluginData::id) .toCollection(HashSet()) } var extensionsForIdes: Map<String, List<String>>? = null private set fun loadExtensionsForIdes() { if (extensionsForIdes != null) { return } try { HttpRequests .request(IDE_EXTENSIONS_URL) .productNameAsUserAgent() .setHeadersViaTuner() .throwStatusCodeException(false) .connect { deserializeExtensionsForIdes(it.inputStream) } } catch (e: Exception) { LOG.infoOrDebug("Can not get supported extensions from Marketplace", e) extensionsForIdes = null } } @VisibleForTesting fun deserializeExtensionsForIdes(stream: InputStream) { extensionsForIdes = objectMapper.readValue(stream, object : TypeReference<Map<String, List<String>>>() {}) } private fun parseXmlIds(input: InputStream) = objectMapper.readValue(input, object : TypeReference<Set<PluginId>>() {}) } /** * NB!: any previous tuners set by {@link RequestBuilder#tuner} will be overwritten by this call */ fun RequestBuilder.setHeadersViaTuner(): RequestBuilder { return ApplicationManager.getApplication() ?.getService(PluginRepositoryAuthService::class.java) ?.connectionTuner ?.let(::tuner) ?: this } private fun loadETagForFile(file: Path): String { val eTagFile = getETagFile(file) try { val lines = Files.readAllLines(eTagFile) if (lines.size == 1) { return lines[0] } LOG.warn("Can't load ETag from '" + eTagFile + "'. Unexpected number of lines: " + lines.size) Files.deleteIfExists(eTagFile) } catch (ignore: NoSuchFileException) { } catch (e: IOException) { LOG.warn("Can't load ETag from '$eTagFile'", e) } return "" } @Suppress("SpellCheckingInspection") private fun getETagFile(file: Path): Path = file.parent.resolve("${file.fileName}.etag") private fun saveETagForFile(file: Path, eTag: String) { val eTagFile = getETagFile(file) try { eTagFile.write(eTag) } catch (e: IOException) { LOG.warn("Can't save ETag to '$eTagFile'", e) } } private fun isNotModified(urlConnection: URLConnection, file: Path?): Boolean { return file != null && file.exists() && Files.size(file) > 0 && urlConnection is HttpURLConnection && urlConnection.responseCode == HttpURLConnection.HTTP_NOT_MODIFIED } private data class CompatibleUpdateRequest( val build: String, val pluginXMLIds: List<String>, ) { @JvmOverloads constructor( pluginIds: Set<PluginId>, buildNumber: BuildNumber? = null, ) : this( ApplicationInfoImpl.orFromPluginsCompatibleBuild(buildNumber), pluginIds.map { it.idString }, ) } private data class CompatibleUpdateForModuleRequest( val module: String, val build: String, ) { @JvmOverloads constructor( module: String, buildNumber: BuildNumber? = null, ) : this( module, ApplicationInfoImpl.orFromPluginsCompatibleBuild(buildNumber), ) } private fun Logger.infoOrDebug( message: String, throwable: Throwable, ) { if (isDebugEnabled) { debug(message, throwable) } else { info("$message: ${throwable.message}") } }
apache-2.0
6061c7510b2dba9049178fdd0b680f48
32.570962
144
0.685359
4.622417
false
false
false
false
google/intellij-community
platform/build-scripts/src/org/jetbrains/intellij/build/BuildPaths.kt
5
1954
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.intellij.build import com.intellij.openapi.util.io.FileUtilRt import org.jetbrains.intellij.build.dependencies.BuildDependenciesCommunityRoot import java.nio.file.Path import kotlin.io.path.pathString /** * All paths are absolute and use '/' as a separator */ abstract class BuildPaths( val communityHomeDir: BuildDependenciesCommunityRoot, val buildOutputDir: Path, /** * All log and debug files should be written to this directory. It will be automatically published to TeamCity artifacts */ val logDir: Path, /** * Path to a base directory of the project which will be compiled */ val projectHome: Path ) { /** * Path to a directory where idea/community Git repository is checked out */ val communityHome: String = FileUtilRt.toSystemIndependentName(communityHomeDir.communityRoot.pathString) /** * Path to a directory where build script will store temporary and resulting files */ val buildOutputRoot: String = FileUtilRt.toSystemIndependentName(buildOutputDir.toString()) /** * Path to a directory where resulting artifacts will be placed */ lateinit var artifacts: String lateinit var artifactDir: Path /** * Path to a directory containing distribution files ('bin', 'lib', 'plugins' directories) common for all operating systems */ var distAllDir: Path = buildOutputDir.resolve("dist.all") fun getDistAll(): String = FileUtilRt.toSystemIndependentName(distAllDir.toString()) /** * Path to a directory where temporary files required for a particular build step can be stored */ val tempDir: Path = buildOutputDir.resolve("temp") /** * Path to a directory where temporary files required for a particular build step can be stored */ val temp: String = FileUtilRt.toSystemIndependentName(tempDir.toString()) }
apache-2.0
5c94edc5d7bb63168e1dfeb6054acb29
33.892857
125
0.748721
4.765854
false
false
false
false
JetBrains/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/ExpandBooleanExpressionIntention.kt
1
2256
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.intentions import com.intellij.openapi.editor.Editor import com.intellij.openapi.util.TextRange import com.intellij.psi.PsiElement import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.caches.resolve.safeAnalyzeNonSourceRootCode import org.jetbrains.kotlin.idea.codeinsight.api.classic.intentions.SelfTargetingRangeIntention import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.startOffset import org.jetbrains.kotlin.psi2ir.deparenthesize import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode import org.jetbrains.kotlin.types.typeUtil.isBoolean class ExpandBooleanExpressionIntention : SelfTargetingRangeIntention<KtExpression>( KtExpression::class.java, KotlinBundle.lazyMessage("expand.boolean.expression.to.if.else") ) { override fun applicabilityRange(element: KtExpression): TextRange? { if (!element.isTargetExpression() || element.parent.isTargetExpression()) return null if (element.deparenthesize() is KtConstantExpression) return null val parent = element.parent if (parent is KtValueArgument || parent is KtParameter || parent is KtStringTemplateEntry) return null val context = element.safeAnalyzeNonSourceRootCode(BodyResolveMode.PARTIAL) if (context[BindingContext.EXPRESSION_TYPE_INFO, element]?.type?.isBoolean() != true) return null return element.textRange } private fun PsiElement.isTargetExpression() = this is KtSimpleNameExpression || this is KtCallExpression || this is KtQualifiedExpression || this is KtOperationExpression || this is KtParenthesizedExpression override fun applyTo(element: KtExpression, editor: Editor?) { val ifExpression = KtPsiFactory(element.project).createExpressionByPattern("if ($0) {\ntrue\n} else {\nfalse\n}", element) val replaced = element.replace(ifExpression) if (replaced != null) { editor?.caretModel?.moveToOffset(replaced.startOffset) } } }
apache-2.0
2f37c5e17bad4f6f83b1f23f4589d88d
52.714286
158
0.772606
4.893709
false
false
false
false
chrislo27/RhythmHeavenRemixEditor2
core/src/main/kotlin/io/github/chrislo27/rhre3/editor/stage/PresentationModeButton.kt
2
1887
package io.github.chrislo27.rhre3.editor.stage import com.badlogic.gdx.graphics.Texture import com.badlogic.gdx.graphics.g2d.TextureRegion import io.github.chrislo27.rhre3.editor.Editor import io.github.chrislo27.rhre3.editor.Tool import io.github.chrislo27.rhre3.screen.EditorScreen import io.github.chrislo27.toolboks.i18n.Localization import io.github.chrislo27.toolboks.registry.AssetRegistry import io.github.chrislo27.toolboks.ui.* class PresentationModeButton(val editor: Editor, val editorStage: EditorStage, palette: UIPalette, parent: UIElement<EditorScreen>, stage: Stage<EditorScreen>) : Button<EditorScreen>(palette, parent, stage) { init { addLabel(ImageLabel(palette, this, stage).apply { this.image = TextureRegion(AssetRegistry.get<Texture>("ui_icon_presentation")) }) } override var tooltipText: String? set(_) {} get() { return Localization["editor.presentationMode.info"] } override fun onLeftClick(xPercent: Float, yPercent: Float) { super.onLeftClick(xPercent, yPercent) val stage = editorStage val visible = !stage.presentationModeStage.visible stage.elements.filterIsInstance<Stage<*>>().forEach { it.visible = !visible } stage.presentationModeStage.visible = visible stage.tapalongStage.visible = false stage.playalongStage.visible = false stage.paneLikeStages.forEach { it.visible = false } stage.buttonBarStage.visible = true stage.messageBarStage.visible = !visible stage.subtitleStage.visible = true if (visible) { editor.currentTool = Tool.SELECTION editor.remix.recomputeCachedData() } stage.updateSelected() editor.updateMessageLabel() } }
gpl-3.0
970157d96cbf92d580182233c943538d
36.019608
98
0.674086
4.569007
false
false
false
false
JetBrains/teamcity-dnx-plugin
plugin-dotnet-server/src/main/kotlin/jetbrains/buildServer/dotnet/DotnetToolTypeAdapter.kt
1
1388
package jetbrains.buildServer.dotnet import jetbrains.buildServer.dotnet.DotnetConstants.INTEGRATION_PACKAGE_TYPE import jetbrains.buildServer.tools.ToolTypeAdapter class DotnetToolTypeAdapter : ToolTypeAdapter() { override fun getType() = DotnetConstants.INTEGRATION_PACKAGE_TYPE override fun getDisplayName() = DotnetConstants.INTEGRATION_PACKAGE_TOOL_TYPE_NAME override fun getDescription(): String? = "Is used in .NET CLI build steps." override fun getShortDisplayName() = DotnetConstants.INTEGRATION_PACKAGE_SHORT_TOOL_TYPE_NAME override fun getTargetFileDisplayName() = DotnetConstants.INTEGRATION_PACKAGE_TARGET_FILE_DISPLAY_NAME override fun isSupportDownload() = true override fun getToolSiteUrl() = "https://github.com/JetBrains/TeamCity.MSBuild.Logger/" override fun getToolLicenseUrl() = "https://github.com/JetBrains/TeamCity.MSBuild.Logger/blob/master/LICENSE" override fun getValidPackageDescription(): String? = "Specify the path to a " + displayName + " (.nupkg).\n" + "<br/>Download <em>${INTEGRATION_PACKAGE_TYPE}.&lt;VERSION&gt;.nupkg</em> from\n" + "<a href=\"https://www.nuget.org/packages/${INTEGRATION_PACKAGE_TYPE}/\" target=\"_blank\" rel=\"noreferrer\">www.nuget.org</a>" companion object { internal val Shared: ToolTypeAdapter = DotnetToolTypeAdapter() } }
apache-2.0
5f28dcfedde9e5bcf1ded99e6606f693
43.806452
144
0.732709
4.244648
false
false
false
false
leafclick/intellij-community
platform/vcs-log/impl/src/com/intellij/vcs/log/ui/frame/VcsLogDiffPreview.kt
1
5350
// 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.vcs.log.ui.frame import com.intellij.diff.impl.DiffRequestProcessor import com.intellij.openapi.Disposable import com.intellij.openapi.application.invokeLater import com.intellij.openapi.fileEditor.FileEditorManager import com.intellij.openapi.project.Project import com.intellij.openapi.ui.Splitter import com.intellij.openapi.util.Disposer import com.intellij.openapi.vcs.changes.DiffPreviewProvider import com.intellij.openapi.vcs.changes.EditorTabPreview import com.intellij.openapi.vcs.changes.PreviewDiffVirtualFile import com.intellij.openapi.wm.IdeFocusManager import com.intellij.openapi.wm.ToolWindowId import com.intellij.openapi.wm.ToolWindowManager import com.intellij.ui.OnePixelSplitter import com.intellij.vcs.log.impl.CommonUiProperties import com.intellij.vcs.log.impl.VcsLogUiProperties import com.intellij.vcs.log.impl.VcsLogUiProperties.PropertiesChangeListener import com.intellij.vcs.log.impl.VcsLogUiProperties.VcsLogUiProperty import org.jetbrains.annotations.NonNls import javax.swing.JComponent fun toggleDiffPreviewOnPropertyChange(uiProperties: VcsLogUiProperties, parent: Disposable, showDiffPreview: (Boolean) -> Unit) { val propertiesChangeListener: PropertiesChangeListener = object : PropertiesChangeListener { override fun <T> onPropertyChanged(property: VcsLogUiProperty<T>) { if (CommonUiProperties.SHOW_DIFF_PREVIEW == property) { showDiffPreview(uiProperties.get(CommonUiProperties.SHOW_DIFF_PREVIEW)) } } } uiProperties.addChangeListener(propertiesChangeListener) Disposer.register(parent, Disposable { uiProperties.removeChangeListener(propertiesChangeListener) }) } abstract class FrameDiffPreview<D : DiffRequestProcessor>(protected val previewDiff: D, uiProperties: VcsLogUiProperties, mainComponent: JComponent, @NonNls splitterProportionKey: String, vertical: Boolean = false, defaultProportion: Float = 0.7f) { private val previewDiffSplitter: Splitter = OnePixelSplitter(vertical, splitterProportionKey, defaultProportion) val mainComponent: JComponent get() = previewDiffSplitter init { previewDiffSplitter.setHonorComponentsMinimumSize(false) previewDiffSplitter.firstComponent = mainComponent toggleDiffPreviewOnPropertyChange(uiProperties, previewDiff, this::showDiffPreview) invokeLater { showDiffPreview(uiProperties.get(CommonUiProperties.SHOW_DIFF_PREVIEW)) } } abstract fun updatePreview(state: Boolean) private fun showDiffPreview(state: Boolean) { previewDiffSplitter.secondComponent = if (state) previewDiff.component else null updatePreview(state) } } abstract class EditorDiffPreview(private val uiProperties: VcsLogUiProperties, private val owner: Disposable) : DiffPreviewProvider { protected fun init(project: Project) { toggleDiffPreviewOnPropertyChange(uiProperties, owner) { state -> if (state) { openPreviewInEditor(project, this, getOwnerComponent()) } else { //'equals' for such files is overridden and means the equality of its owner FileEditorManager.getInstance(project).closeFile(PreviewDiffVirtualFile(this)) } } @Suppress("LeakingThis") addSelectionListener { if (uiProperties.get(CommonUiProperties.SHOW_DIFF_PREVIEW)) { openPreviewInEditor(project, this, getOwnerComponent()) } } } override fun getOwner(): Disposable = owner abstract fun getOwnerComponent(): JComponent abstract fun addSelectionListener(listener: () -> Unit) } class VcsLogEditorDiffPreview(project: Project, uiProperties: VcsLogUiProperties, private val mainFrame: MainFrame) : EditorDiffPreview(uiProperties, mainFrame.changesBrowser) { init { init(project) } override fun createDiffRequestProcessor(): DiffRequestProcessor { val preview = mainFrame.createDiffPreview(true, owner) preview.updatePreview(true) return preview } override fun getEditorTabName(): String { return "Repository Diff" } override fun getOwnerComponent(): JComponent = mainFrame.changesBrowser.preferredFocusedComponent override fun addSelectionListener(listener: () -> Unit) { mainFrame.changesBrowser.viewer.addSelectionListener(Runnable { if (mainFrame.changesBrowser.selectedChanges.isNotEmpty()) { listener() } }, owner) } } private fun openPreviewInEditor(project: Project, diffPreviewProvider: DiffPreviewProvider, componentToFocus: JComponent) { val escapeHandler = Runnable { val toolWindow = ToolWindowManager.getInstance(project).getToolWindow(ToolWindowId.VCS) toolWindow?.activate({ IdeFocusManager.getInstance(project).requestFocus(componentToFocus, true) }, false) } EditorTabPreview.openPreview(project, PreviewDiffVirtualFile(diffPreviewProvider), false, escapeHandler) }
apache-2.0
16271e6437811c1fef3cd0fe2aabc911
40.48062
140
0.73028
5.318091
false
false
false
false
code-helix/slatekit
src/lib/kotlin/slatekit-common/src/main/kotlin/slatekit/common/crypto/HMAC.kt
1
667
package slatekit.common.crypto import java.util.* import javax.crypto.Mac import javax.crypto.spec.SecretKeySpec class HMAC(secret: ByteArray) { val provider = "HmacSHA256" val hasher: javax.crypto.Mac = Mac.getInstance(provider) val key = SecretKeySpec(secret, provider) val base64 = Base64.getUrlEncoder() init { hasher.init(key) } fun sign(content: String): ByteArray { val hash = hasher.doFinal(content.toByteArray(Charsets.UTF_8)) return hash } fun encode(content: String): String { val hash = sign(content) val encoded = base64.encodeToString(hash) return encoded } }
apache-2.0
cde3ed3c088b38c9aa6e39ea4149a02a
23.703704
70
0.667166
4.018072
false
false
false
false
zdary/intellij-community
platform/core-impl/src/com/intellij/ide/plugins/PluginDescriptorLoader.kt
1
33084
// 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. @file:Suppress("ReplaceNegatedIsEmptyWithIsNotEmpty") package com.intellij.ide.plugins import com.intellij.diagnostic.ActivityCategory import com.intellij.diagnostic.StartUpMeasurer import com.intellij.openapi.application.PathManager import com.intellij.openapi.extensions.PluginId import com.intellij.openapi.util.BuildNumber import com.intellij.openapi.util.JDOMUtil import com.intellij.openapi.util.io.FileUtil import com.intellij.openapi.util.text.Strings import com.intellij.util.PlatformUtils import com.intellij.util.io.Decompressor import com.intellij.util.io.URLUtil import com.intellij.util.lang.UrlClassLoader import com.intellij.util.lang.ZipFilePool import org.jdom.Element import org.jetbrains.annotations.ApiStatus import org.jetbrains.annotations.TestOnly import java.io.File import java.io.IOException import java.net.URL import java.nio.file.* import java.util.* import java.util.concurrent.ForkJoinPool import java.util.concurrent.ForkJoinTask import java.util.concurrent.RecursiveAction import java.util.concurrent.RecursiveTask import java.util.function.Supplier @ApiStatus.Internal object PluginDescriptorLoader { fun loadDescriptor(file: Path, isBundled: Boolean, parentContext: DescriptorListLoadingContext): IdeaPluginDescriptorImpl? { return loadDescriptorFromFileOrDir(file = file, pathName = PluginManagerCore.PLUGIN_XML, context = parentContext, pathResolver = PluginXmlPathResolver.DEFAULT_PATH_RESOLVER, isBundled = isBundled, isEssential = false, isDirectory = Files.isDirectory(file)) } internal fun loadForCoreEnv(pluginRoot: Path, fileName: String): IdeaPluginDescriptorImpl? { val pathResolver = PluginXmlPathResolver.DEFAULT_PATH_RESOLVER val parentContext = DescriptorListLoadingContext.createSingleDescriptorContext(DisabledPluginsState.disabledPlugins()) if (Files.isDirectory(pluginRoot)) { return loadDescriptorFromDir(file = pluginRoot, descriptorRelativePath = "${PluginManagerCore.META_INF}$fileName", pluginPath = null, context = parentContext, isBundled = true, isEssential = true, pathResolver = pathResolver) } else { DescriptorLoadingContext().use { context -> return loadDescriptorFromJar(file = pluginRoot, fileName = fileName, pathResolver = pathResolver, context = context, parentContext = parentContext, isBundled = true, isEssential = true, pluginPath = null) } } } private fun loadDescriptorFromDir(file: Path, descriptorRelativePath: String, pluginPath: Path?, context: DescriptorListLoadingContext, isBundled: Boolean, isEssential: Boolean, pathResolver: PathResolver): IdeaPluginDescriptorImpl? { try { val descriptor = IdeaPluginDescriptorImpl(pluginPath ?: file, isBundled) val element = JDOMUtil.load(file.resolve(descriptorRelativePath), context.xmlFactory) descriptor.readExternal(element, pathResolver, context, descriptor, LocalFsDataLoader(file)) return descriptor } catch (e: NoSuchFileException) { return null } catch (e: Throwable) { if (isEssential) { throw e } DescriptorListLoadingContext.LOG.warn("Cannot load ${file.resolve(descriptorRelativePath)}", e) return null } } internal fun loadDescriptorFromJar(file: Path, fileName: String, pathResolver: PathResolver, context: DescriptorLoadingContext, parentContext: DescriptorListLoadingContext, isBundled: Boolean, isEssential: Boolean, pluginPath: Path?): IdeaPluginDescriptorImpl? { val factory = parentContext.xmlFactory try { val element: Element val dataLoader: DataLoader try { val pool = ZipFilePool.POOL if (pool == null) { val fs = context.open(file) val pluginDescriptorFile = fs.getPath("/META-INF/$fileName") element = JDOMUtil.load(pluginDescriptorFile, factory) dataLoader = ZipFsDataLoader(pluginDescriptorFile.root) } else { val resolver = pool.load(file) val data = resolver.loadZipEntry("META-INF/$fileName") ?: return null element = JDOMUtil.load(data, factory) dataLoader = ImmutableZipFileDataLoader(resolver, file, pool) } } catch (ignore: NoSuchFileException) { return null } val descriptor = IdeaPluginDescriptorImpl(pluginPath ?: file, isBundled) if (descriptor.readExternal(element, pathResolver, parentContext, descriptor, dataLoader)) { descriptor.jarFiles = listOf(descriptor.pluginPath) } return descriptor } catch (e: Throwable) { if (isEssential) { throw e } parentContext.result.reportCannotLoad(file, e) } return null } @JvmStatic fun loadDescriptorFromFileOrDir(file: Path, pathName: String, context: DescriptorListLoadingContext, pathResolver: PathResolver, isBundled: Boolean, isEssential: Boolean, isDirectory: Boolean): IdeaPluginDescriptorImpl? { return when { isDirectory -> loadDescriptorFromDirAndNormalize(file = file, pathName = pathName, parentContext = context, isBundled = isBundled, isEssential = isEssential, pathResolver = pathResolver) file.fileName.toString().endsWith(".jar", ignoreCase = true) -> { DescriptorLoadingContext().use { loadingContext -> loadDescriptorFromJar(file = file, fileName = pathName, pathResolver = pathResolver, context = loadingContext, parentContext = context, isBundled = isBundled, isEssential = isEssential, pluginPath = null) } } else -> null } } internal fun loadDescriptorFromDirAndNormalize(file: Path, pathName: String, parentContext: DescriptorListLoadingContext, isBundled: Boolean, isEssential: Boolean, pathResolver: PathResolver): IdeaPluginDescriptorImpl? { val descriptorRelativePath = "${PluginManagerCore.META_INF}$pathName" loadDescriptorFromDir(file = file, descriptorRelativePath = descriptorRelativePath, pluginPath = null, context = parentContext, isBundled = isBundled, isEssential = isEssential, pathResolver = pathResolver)?.let { return it } val pluginJarFiles = ArrayList<Path>() val dirs = ArrayList<Path>() if (!collectPluginDirectoryContents(file, pluginJarFiles, dirs)) { return null } if (!pluginJarFiles.isEmpty()) { val pluginPathResolver = PluginXmlPathResolver(pluginJarFiles) DescriptorLoadingContext().use { loadingContext -> for (jarFile in pluginJarFiles) { loadDescriptorFromJar(file = jarFile, fileName = pathName, pathResolver = pluginPathResolver, context = loadingContext, parentContext = parentContext, isBundled = isBundled, isEssential = isEssential, pluginPath = file)?.let { it.jarFiles = pluginJarFiles return it } } } } var descriptor: IdeaPluginDescriptorImpl? = null for (dir in dirs) { val otherDescriptor = loadDescriptorFromDir(file = dir, descriptorRelativePath = descriptorRelativePath, pluginPath = file, context = parentContext, isBundled = isBundled, isEssential = isEssential, pathResolver = pathResolver) if (otherDescriptor != null) { if (descriptor != null) { DescriptorListLoadingContext.LOG.error("Cannot load $file because two or more plugin.xml detected") return null } descriptor = otherDescriptor } } return descriptor } private fun collectPluginDirectoryContents(file: Path, pluginJarFiles: MutableList<Path>, dirs: MutableList<Path>): Boolean { try { Files.newDirectoryStream(file.resolve("lib")).use { stream -> for (childFile in stream) { if (Files.isDirectory(childFile)) { dirs.add(childFile) } else { val path = childFile.toString() if (path.endsWith(".jar", ignoreCase = true) || path.endsWith(".zip", ignoreCase = true)) { pluginJarFiles.add(childFile) } } } } } catch (e: IOException) { return false } if (!pluginJarFiles.isEmpty()) { putMoreLikelyPluginJarsFirst(file, pluginJarFiles) } return true } /* * Sort the files heuristically to load the plugin jar containing plugin descriptors without extra ZipFile accesses * File name preference: * a) last order for files with resources in name, like resources_en.jar * b) last order for files that have -digit suffix is the name e.g. completion-ranking.jar is before gson-2.8.0.jar or junit-m5.jar * c) jar with name close to plugin's directory name, e.g. kotlin-XXX.jar is before all-open-XXX.jar * d) shorter name, e.g. android.jar is before android-base-common.jar */ private fun putMoreLikelyPluginJarsFirst(pluginDir: Path, filesInLibUnderPluginDir: MutableList<Path>) { val pluginDirName = pluginDir.fileName.toString() filesInLibUnderPluginDir.sortWith(Comparator { o1: Path, o2: Path -> val o2Name = o2.fileName.toString() val o1Name = o1.fileName.toString() val o2StartsWithResources = o2Name.startsWith("resources") val o1StartsWithResources = o1Name.startsWith("resources") if (o2StartsWithResources != o1StartsWithResources) { return@Comparator if (o2StartsWithResources) -1 else 1 } val o2IsVersioned = fileNameIsLikeVersionedLibraryName(o2Name) val o1IsVersioned = fileNameIsLikeVersionedLibraryName(o1Name) if (o2IsVersioned != o1IsVersioned) { return@Comparator if (o2IsVersioned) -1 else 1 } val o2StartsWithNeededName = o2Name.startsWith(pluginDirName, ignoreCase = true) val o1StartsWithNeededName = o1Name.startsWith(pluginDirName, ignoreCase = true) if (o2StartsWithNeededName != o1StartsWithNeededName) { return@Comparator if (o2StartsWithNeededName) 1 else -1 } val o2EndsWithIdea = o2Name.endsWith("-idea.jar") val o1EndsWithIdea = o1Name.endsWith("-idea.jar") if (o2EndsWithIdea != o1EndsWithIdea) { return@Comparator if (o2EndsWithIdea) 1 else -1 } o1Name.length - o2Name.length }) } private fun fileNameIsLikeVersionedLibraryName(name: String): Boolean { val i = name.lastIndexOf('-') if (i == -1) { return false } if (i + 1 < name.length) { val c = name[i + 1] if (Character.isDigit(c)) { return true } else { return (c == 'm' || c == 'M') && i + 2 < name.length && Character.isDigit(name[i + 2]) } } return false } private fun loadDescriptorsFromProperty(result: PluginLoadingResult, context: DescriptorListLoadingContext) { val pathProperty = System.getProperty(PluginManagerCore.PROPERTY_PLUGIN_PATH) ?: return // gradle-intellij-plugin heavily depends on this property in order to have core class loader plugins during tests val useCoreClassLoaderForPluginsFromProperty = java.lang.Boolean.parseBoolean( System.getProperty("idea.use.core.classloader.for.plugin.path")) val t = StringTokenizer(pathProperty, File.pathSeparatorChar.toString() + ",") while (t.hasMoreTokens()) { val s = t.nextToken() loadDescriptor(Paths.get(s), false, context)?.let { // plugins added via property shouldn't be overridden to avoid plugin root detection issues when running external plugin tests result.add(it, /* overrideUseIfCompatible = */true) if (useCoreClassLoaderForPluginsFromProperty) { it.setUseCoreClassLoader() } } } } @JvmStatic fun loadDescriptors(isUnitTestMode: Boolean, isRunningFromSources: Boolean): DescriptorListLoadingContext { var flags = DescriptorListLoadingContext.IGNORE_MISSING_SUB_DESCRIPTOR if (isUnitTestMode) { flags = flags or DescriptorListLoadingContext.IGNORE_MISSING_INCLUDE } if (isUnitTestMode || isRunningFromSources) { flags = flags or DescriptorListLoadingContext.CHECK_OPTIONAL_CONFIG_NAME_UNIQUENESS } val result = PluginManagerCore.createLoadingResult(null) val bundledPluginPath: Path? = if (isUnitTestMode) { null } else if (java.lang.Boolean.getBoolean("idea.use.dev.build.server")) { Paths.get(PathManager.getHomePath(), "out/dev-run", PlatformUtils.getPlatformPrefix(), "plugins") } else { Paths.get(PathManager.getPreInstalledPluginsPath()) } val context = DescriptorListLoadingContext(flags, DisabledPluginsState.disabledPlugins(), result) context.use { loadBundledDescriptorsAndDescriptorsFromDir(context = context, customPluginDir = Paths.get(PathManager.getPluginsPath()), bundledPluginDir = bundledPluginPath, isRunningFromSources = isRunningFromSources) loadDescriptorsFromProperty(result, context) if (isUnitTestMode && result.enabledPluginCount() <= 1) { // we're running in unit test mode, but the classpath doesn't contain any plugins; try to load bundled plugins anyway context.usePluginClassLoader = true ForkJoinPool.commonPool().invoke(LoadDescriptorsFromDirAction(Paths.get(PathManager.getPreInstalledPluginsPath()), context, true)) } } context.result.finishLoading() return context } @JvmStatic fun loadBundledDescriptorsAndDescriptorsFromDir(context: DescriptorListLoadingContext, customPluginDir: Path, bundledPluginDir: Path?, isRunningFromSources: Boolean) { val classLoader = PluginDescriptorLoader::class.java.classLoader val pool = ForkJoinPool.commonPool() var activity = StartUpMeasurer.startActivity("platform plugin collecting", ActivityCategory.DEFAULT) val platformPrefix = System.getProperty(PlatformUtils.PLATFORM_PREFIX_KEY) // should be the only plugin in lib (only for Ultimate and WebStorm for now) val pathResolver = ClassPathXmlPathResolver(classLoader) if ((platformPrefix == null || platformPrefix == PlatformUtils.IDEA_PREFIX || platformPrefix == PlatformUtils.WEB_PREFIX) && (java.lang.Boolean.getBoolean("idea.use.dev.build.server") || !isRunningFromSources)) { val factory = context.xmlFactory val element = JDOMUtil.load(classLoader.getResourceAsStream(PluginManagerCore.PLUGIN_XML_PATH)!!, factory) val descriptor = IdeaPluginDescriptorImpl(Paths.get(PathManager.getLibPath()), true) descriptor.readExternal(element, pathResolver, context, descriptor, object : DataLoader { override val pool: ZipFilePool get() = throw IllegalStateException("must be not called") override fun load(path: String) = throw IllegalStateException("must be not called") override fun toString() = "product classpath" }) descriptor.setUseCoreClassLoader() context.result.add(descriptor, /* overrideUseIfCompatible = */false) } else { val urlsFromClassPath = LinkedHashMap<URL, String>() val platformPluginURL = computePlatformPluginUrlAndCollectPluginUrls(classLoader, urlsFromClassPath, platformPrefix) if (!urlsFromClassPath.isEmpty()) { activity = activity.endAndStart("plugin from classpath loading") pool.invoke(LoadDescriptorsFromClassPathAction(urls = urlsFromClassPath, context = context, platformPluginURL = platformPluginURL, pathResolver = pathResolver)) } } activity = activity.endAndStart("plugin from user dir loading") pool.invoke(LoadDescriptorsFromDirAction(customPluginDir, context, false)) if (bundledPluginDir != null) { activity = activity.endAndStart("plugin from bundled dir loading") pool.invoke(LoadDescriptorsFromDirAction(bundledPluginDir, context, true)) } activity.end() } private fun computePlatformPluginUrlAndCollectPluginUrls(loader: ClassLoader, urls: MutableMap<URL, String>, platformPrefix: String?): URL? { var result: URL? = null if (platformPrefix != null) { val fileName = "${platformPrefix}Plugin.xml" loader.getResource("${PluginManagerCore.META_INF}$fileName")?.let { urls.put(it, fileName) result = it } } collectPluginFilesInClassPath(loader, urls) return result } private fun collectPluginFilesInClassPath(loader: ClassLoader, urls: MutableMap<URL, String>) { try { val enumeration = loader.getResources(PluginManagerCore.PLUGIN_XML_PATH) while (enumeration.hasMoreElements()) { urls.put(enumeration.nextElement(), PluginManagerCore.PLUGIN_XML) } } catch (e: IOException) { DescriptorListLoadingContext.LOG.warn(e) } } /** * Think twice before use and get approve from core team. * * Returns enabled plugins only. */ @ApiStatus.Internal @JvmStatic fun loadUncachedDescriptors(isUnitTestMode: Boolean, isRunningFromSources: Boolean): List<IdeaPluginDescriptorImpl> { return loadDescriptors(isUnitTestMode = isUnitTestMode, isRunningFromSources = isRunningFromSources).result.enabledPlugins } @Throws(IOException::class) @JvmStatic fun loadDescriptorFromArtifact(file: Path, buildNumber: BuildNumber?): IdeaPluginDescriptorImpl? { val context = DescriptorListLoadingContext(DescriptorListLoadingContext.IGNORE_MISSING_SUB_DESCRIPTOR, DisabledPluginsState.disabledPlugins(), PluginManagerCore.createLoadingResult(buildNumber)) var outputDir: Path? = null try { var descriptor = loadDescriptorFromFileOrDir(file = file, pathName = PluginManagerCore.PLUGIN_XML, context = context, pathResolver = PluginXmlPathResolver.DEFAULT_PATH_RESOLVER, isBundled = false, isEssential = false, isDirectory = false) if (descriptor != null || !file.toString().endsWith(".zip")) { return descriptor } outputDir = Files.createTempDirectory("plugin") Decompressor.Zip(file).extract(outputDir!!) try { Files.newDirectoryStream(outputDir).use { stream -> val iterator = stream.iterator() if (iterator.hasNext()) { descriptor = loadDescriptorFromFileOrDir(file = iterator.next(), pathName = PluginManagerCore.PLUGIN_XML, context = context, pathResolver = PluginXmlPathResolver.DEFAULT_PATH_RESOLVER, isBundled = false, isEssential = false, isDirectory = true) } } } catch (ignore: NoSuchFileException) { } return descriptor } finally { outputDir?.let { FileUtil.delete(it) } } } @JvmStatic fun tryLoadFullDescriptor(descriptor: IdeaPluginDescriptorImpl): IdeaPluginDescriptorImpl? { if (!PluginManagerCore.hasDescriptorByIdentity(descriptor) || PluginManagerCore.getLoadedPlugins().contains(descriptor)) { return descriptor } else { return loadDescriptor(file = descriptor.pluginPath, disabledPlugins = emptySet(), isBundled = descriptor.isBundled, pathResolver = createPathResolverForPlugin(descriptor = descriptor, checkPluginJarFiles = false)) } } @JvmStatic fun loadDescriptor(file: Path, disabledPlugins: Set<PluginId?>, isBundled: Boolean, pathResolver: PathResolver): IdeaPluginDescriptorImpl? { DescriptorListLoadingContext.createSingleDescriptorContext(disabledPlugins).use { context -> return loadDescriptorFromFileOrDir(file = file, pathName = PluginManagerCore.PLUGIN_XML, context = context, pathResolver = pathResolver, isBundled = isBundled, isEssential = false, isDirectory = Files.isDirectory(file)) } } fun createPathResolverForPlugin(descriptor: IdeaPluginDescriptorImpl, checkPluginJarFiles: Boolean): PathResolver { if (PluginManagerCore.isRunningFromSources() && descriptor.pluginPath.fileSystem == FileSystems.getDefault() && descriptor.pluginPath.toString().contains("out/classes")) { return ClassPathXmlPathResolver(descriptor.pluginClassLoader) } else if (checkPluginJarFiles) { val pluginJarFiles = ArrayList<Path>() val dirs = ArrayList<Path>() if (collectPluginDirectoryContents(descriptor.pluginPath, pluginJarFiles, dirs)) { return PluginXmlPathResolver(pluginJarFiles) } } return PluginXmlPathResolver.DEFAULT_PATH_RESOLVER } @JvmStatic fun loadFullDescriptor(descriptor: IdeaPluginDescriptorImpl): IdeaPluginDescriptorImpl { // PluginDescriptor fields are cleaned after the plugin is loaded, so we need to reload the descriptor to check if it's dynamic val fullDescriptor = tryLoadFullDescriptor(descriptor) if (fullDescriptor == null) { DescriptorListLoadingContext.LOG.error("Could not load full descriptor for plugin ${descriptor.pluginPath}") return descriptor } else { return fullDescriptor } } @TestOnly @JvmStatic fun testLoadDescriptorsFromClassPath(loader: ClassLoader): List<IdeaPluginDescriptor> { val urlsFromClassPath = LinkedHashMap<URL, String>() collectPluginFilesInClassPath(loader, urlsFromClassPath) val buildNumber = BuildNumber.fromString("2042.42") val context = DescriptorListLoadingContext(0, emptySet(), PluginLoadingResult(emptyMap(), Supplier { buildNumber }, false)) LoadDescriptorsFromClassPathAction(urlsFromClassPath, context, null, ClassPathXmlPathResolver(loader)).compute() context.result.finishLoading() return context.result.enabledPlugins } } private class LoadDescriptorsFromDirAction(private val dir: Path, private val context: DescriptorListLoadingContext, private val isBundled: Boolean) : RecursiveAction() { override fun compute() { val tasks = ArrayList<RecursiveTask<IdeaPluginDescriptorImpl?>>() try { Files.newDirectoryStream(dir).use { dirStream -> for (file in dirStream) { tasks.add(object : RecursiveTask<IdeaPluginDescriptorImpl?>() { override fun compute(): IdeaPluginDescriptorImpl? { if (Files.isDirectory(file)) { return PluginDescriptorLoader.loadDescriptorFromDirAndNormalize(file = file, pathName = PluginManagerCore.PLUGIN_XML, parentContext = context, isBundled = isBundled, isEssential = false, pathResolver = PluginXmlPathResolver.DEFAULT_PATH_RESOLVER) } else if (file.fileName.toString().endsWith(".jar", ignoreCase = true)) { DescriptorLoadingContext().use { loadingContext -> return PluginDescriptorLoader.loadDescriptorFromJar(file = file, fileName = PluginManagerCore.PLUGIN_XML, pathResolver = PluginXmlPathResolver.DEFAULT_PATH_RESOLVER, context = loadingContext, parentContext = context, isBundled = isBundled, isEssential = false, pluginPath = null) } } else { return null } } }) } } } catch (ignore: IOException) { return } ForkJoinTask.invokeAll(tasks) for (task in tasks) { task.rawResult?.let { context.result.add(it, /* overrideUseIfCompatible = */false) } } } } private class LoadDescriptorsFromClassPathAction(private val urls: Map<URL, String>, private val context: DescriptorListLoadingContext, private val platformPluginURL: URL?, private val pathResolver: PathResolver) : RecursiveAction() { public override fun compute() { val tasks = ArrayList<RecursiveTask<IdeaPluginDescriptorImpl?>>(urls.size) for ((url, value) in urls) { tasks.add(object : RecursiveTask<IdeaPluginDescriptorImpl?>() { override fun compute(): IdeaPluginDescriptorImpl? { val isEssential = url == platformPluginURL try { return loadDescriptorFromResource(resource = url, pathName = value, isEssential = isEssential) } catch (e: Throwable) { if (isEssential) { throw e } DescriptorListLoadingContext.LOG.info("Cannot load $url", e) return null } } }) } val result = context.result ForkJoinTask.invokeAll(tasks) val usePluginClassLoader = PluginManagerCore.usePluginClassLoader for (task in tasks) { task.rawResult?.let { if (!usePluginClassLoader) { it.setUseCoreClassLoader() } result.add(it, /* overrideUseIfCompatible = */false) } } } private fun loadDescriptorFromResource(resource: URL, pathName: String, isEssential: Boolean): IdeaPluginDescriptorImpl? { when { URLUtil.FILE_PROTOCOL == resource.protocol -> { val file = Paths.get(Strings.trimEnd(UrlClassLoader.urlToFilePath(resource.path).replace('\\', '/'), pathName)).parent return PluginDescriptorLoader.loadDescriptorFromFileOrDir(file = file, pathName = pathName, context = context, pathResolver = pathResolver, isBundled = true, isEssential = isEssential, isDirectory = Files.isDirectory(file)) } URLUtil.JAR_PROTOCOL == resource.protocol -> { val file = Paths.get(UrlClassLoader.urlToFilePath(resource.path)) val parentFile = file.parent if (parentFile == null || !parentFile.endsWith("lib")) { DescriptorLoadingContext().use { loadingContext -> return PluginDescriptorLoader.loadDescriptorFromJar(file = file, fileName = pathName, pathResolver = pathResolver, context = loadingContext, parentContext = context, isBundled = true, isEssential = isEssential, pluginPath = null) } } else { // Support for unpacked plugins in classpath. E.g. .../community/build/dependencies/build/kotlin/Kotlin/lib/kotlin-plugin.jar DescriptorLoadingContext().use { loadingContext -> val descriptor = PluginDescriptorLoader.loadDescriptorFromJar(file = file, fileName = pathName, pathResolver = pathResolver, context = loadingContext, parentContext = context, isBundled = true, isEssential = isEssential, pluginPath = file.parent.parent) if (descriptor != null) { descriptor.jarFiles = null } return descriptor } } } else -> { return null } } } }
apache-2.0
937b2318e6e5b31347e280e03ec8a70c
45.079387
140
0.560362
6.064895
false
false
false
false
JuliusKunze/kotlin-native
backend.native/tests/external/codegen/box/callableReference/function/genericCallableReferencesWithNullableTypes.kt
2
756
// IGNORE_BACKEND: JS, NATIVE // WITH_RUNTIME // WITH_REFLECT import kotlin.test.assertEquals fun <T, R> foo(x: T): R = TODO() inline fun <reified T, reified R> bar(x: T, y: R, f: (T) -> R, tType: String, rType: String): Pair<T, R?> { assertEquals(tType, T::class.simpleName) assertEquals(rType, R::class.simpleName) return Pair(x, y) } data class Pair<A, B>(val a: A, val b: B) fun box(): String { bar(1, "", ::foo, "Int", "String") val s1: Pair<Int, String?> = bar(1, "", ::foo, "Int", "String") val (a: Int, b: String?) = bar(1, "", ::foo, "Int", "String") val ns: String? = null bar(ns, ns, ::foo, "String", "String") val s2: Pair<Int?, String?> = bar(null, null, ::foo, "Int", "String") return "OK" }
apache-2.0
13480e43406ac193da69661ff45584bc
24.2
107
0.568783
2.73913
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/idea/tests/testData/codeInsight/lineMarker/overrideImplement/FakeOverrideForClasses.kt
8
994
package sample interface <lineMarker descr="*">S</lineMarker><T> { fun <lineMarker descr="<html><body>Is implemented in <br>&nbsp;&nbsp;&nbsp;&nbsp;sample.S2</body></html>">foo</lineMarker>(t: T): T val <lineMarker descr="<html><body>Is implemented in <br/>&nbsp;&nbsp;&nbsp;&nbsp;sample.S2</body></html>">some</lineMarker>: T? get var <lineMarker descr="<html><body>Is implemented in <br/>&nbsp;&nbsp;&nbsp;&nbsp;sample.S2</body></html>">other</lineMarker>: T? get set } open abstract class <lineMarker descr="*">S1</lineMarker> : S<String> class S2 : S1() { override val <lineMarker descr="Implements property in 'S&lt;T&gt;'">some</lineMarker>: String = "S" override var <lineMarker descr="Implements property in 'S&lt;T&gt;'">other</lineMarker>: String? get() = null set(value) {} override fun <lineMarker descr="Implements function in 'S&lt;T&gt;'">foo</lineMarker>(t: String): String { return super<S1>.foo(t) } }
apache-2.0
d398d7fe7099e63bc66bd90e6696a549
38.8
136
0.649899
3.463415
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/structuralsearch/KotlinStructuralSearchUtil.kt
2
2529
// 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.structuralsearch import com.google.common.collect.ImmutableBiMap import com.intellij.psi.PsiComment import com.intellij.psi.tree.IElementType import com.intellij.structuralsearch.impl.matcher.handlers.MatchingHandler import com.intellij.structuralsearch.impl.matcher.handlers.SubstitutionHandler import org.jetbrains.kotlin.descriptors.CallableDescriptor import org.jetbrains.kotlin.descriptors.ClassDescriptor import org.jetbrains.kotlin.descriptors.annotations.Annotations import org.jetbrains.kotlin.idea.caches.resolve.resolveToDescriptorIfAny import org.jetbrains.kotlin.lexer.KtSingleValueToken import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.name.Name import org.jetbrains.kotlin.psi.KtDeclaration import org.jetbrains.kotlin.renderer.DescriptorRenderer import org.jetbrains.kotlin.types.KotlinType import org.jetbrains.kotlin.types.KotlinTypeFactory import org.jetbrains.kotlin.types.expressions.OperatorConventions fun getCommentText(comment: PsiComment): String { return when (comment.tokenType) { KtTokens.EOL_COMMENT -> comment.text.drop(2).trim() KtTokens.BLOCK_COMMENT -> comment.text.drop(2).dropLast(2).trim() else -> "" } } private val BINARY_EXPR_OP_NAMES = ImmutableBiMap.builder<KtSingleValueToken, Name>() .putAll(OperatorConventions.ASSIGNMENT_OPERATIONS) .putAll(OperatorConventions.BINARY_OPERATION_NAMES) .build() fun IElementType.binaryExprOpName(): Name? = BINARY_EXPR_OP_NAMES[this] fun KotlinType.renderNames(): Array<String> = arrayOf( DescriptorRenderer.FQ_NAMES_IN_TYPES.renderType(this), DescriptorRenderer.SHORT_NAMES_IN_TYPES.renderType(this), "$this" ) fun String.removeTypeParameters(): String { if (!this.contains('<') || !this.contains('>')) return this return this.removeRange( this.indexOfFirst { c -> c == '<' }, this.indexOfLast { c -> c == '>' } + 1 ) } val MatchingHandler.withinHierarchyTextFilterSet: Boolean get() = this is SubstitutionHandler && (this.isSubtype || this.isStrictSubtype) fun KtDeclaration.resolveKotlinType(): KotlinType? = (resolveToDescriptorIfAny() as? CallableDescriptor)?.returnType fun ClassDescriptor.toSimpleType(nullable: Boolean = false) = KotlinTypeFactory.simpleType(Annotations.EMPTY, this.typeConstructor, emptyList(), nullable)
apache-2.0
685f1ed5cc78f88a85b7f71ce85e0779
41.881356
158
0.780941
4.308348
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/FloatingPointLiteralPrecisionInspection.kt
5
3962
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.inspections import com.intellij.codeInspection.LocalQuickFix import com.intellij.codeInspection.ProblemDescriptor import com.intellij.codeInspection.ProblemHighlightType import com.intellij.codeInspection.ProblemsHolder import com.intellij.openapi.project.Project import com.intellij.psi.PsiElementVisitor import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.idea.inspections.dfa.getKotlinType import org.jetbrains.kotlin.psi.KtConstantExpression import org.jetbrains.kotlin.psi.KtPsiFactory import org.jetbrains.kotlin.psi.expressionVisitor import org.jetbrains.kotlin.psi.stubs.ConstantValueKind import org.jetbrains.kotlin.psi.stubs.elements.KtConstantExpressionElementType import org.jetbrains.kotlin.types.typeUtil.isFloat import java.math.BigDecimal /** * Highlight floating point literals that exceed precision of the corresponding type. * * Some floating point values can't be represented using IEEE 754 floating point standard. * For example, the literal 9_999_999_999.000001 has the same representation as a Double * as the literal 9_999_999_999.000002. Specifying excess digits hides the fact that * computations use the rounded value instead of the exact constant. * * This inspection highlights floating point constants whose literal representation * requires more precision than the floating point type can provide. * It does not try to detect rounding errors or otherwise check computation results. */ class FloatingPointLiteralPrecisionInspection : AbstractKotlinInspection() { private val FLOAT_LITERAL = KtConstantExpressionElementType.kindToConstantElementType(ConstantValueKind.FLOAT_CONSTANT) private val FORMATTING_CHARACTERS_REGEX = Regex("[_fF]") override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean): PsiElementVisitor { return expressionVisitor { if ((it is KtConstantExpression) && (it.elementType == FLOAT_LITERAL)) { val isFloat = it.getKotlinType()?.isFloat() ?: false val uppercaseSuffix = isFloat && it.text?.endsWith('F') ?: false val literal = it.text?.replace(FORMATTING_CHARACTERS_REGEX, "") ?: return@expressionVisitor try { val parseResult = if (isFloat) literal.toFloat().toString() else literal.toDouble().toString() val roundedValue = BigDecimal(parseResult) val exactValue = BigDecimal(literal) if (exactValue.compareTo(roundedValue) != 0) { val replacementText = if (isFloat) parseResult + if (uppercaseSuffix) "F" else "f" else parseResult holder.registerProblem( it, KotlinBundle.message("floating.point.literal.precision.inspection"), ProblemHighlightType.WEAK_WARNING, FloatingPointLiteralPrecisionQuickFix(replacementText)) } } catch (e: NumberFormatException) { return@expressionVisitor } } } } } private class FloatingPointLiteralPrecisionQuickFix(val replacementText: String) : LocalQuickFix { override fun getName(): String = KotlinBundle.message("replace.with.0", replacementText) override fun getFamilyName(): String = name override fun applyFix(project: Project, descriptor: ProblemDescriptor) { val element = descriptor.psiElement as? KtConstantExpression ?: return element.replace(KtPsiFactory(element).createExpression(replacementText)) } }
apache-2.0
f61eb8c3834d57157310907b4a1a9350
48.525
158
0.688289
5.39782
false
false
false
false
jotomo/AndroidAPS
danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_Notify_Alarm.kt
1
3303
package info.nightscout.androidaps.danars.comm import dagger.android.HasAndroidInjector import info.nightscout.androidaps.danars.R import info.nightscout.androidaps.logging.LTag import info.nightscout.androidaps.plugins.bus.RxBusWrapper import info.nightscout.androidaps.plugins.general.nsclient.NSUpload import info.nightscout.androidaps.plugins.general.overview.events.EventNewNotification import info.nightscout.androidaps.plugins.general.overview.notifications.Notification import info.nightscout.androidaps.danars.encryption.BleEncryption import info.nightscout.androidaps.utils.resources.ResourceHelper import javax.inject.Inject class DanaRS_Packet_Notify_Alarm( injector: HasAndroidInjector ) : DanaRS_Packet(injector) { @Inject lateinit var rxBus: RxBusWrapper @Inject lateinit var resourceHelper: ResourceHelper @Inject lateinit var nsUpload: NSUpload init { type = BleEncryption.DANAR_PACKET__TYPE_NOTIFY opCode = BleEncryption.DANAR_PACKET__OPCODE_NOTIFY__ALARM aapsLogger.debug(LTag.PUMPCOMM, "New message") } override fun handleMessage(data: ByteArray) { val alarmCode = byteArrayToInt(getBytes(data, DATA_START, 1)) var errorString = "" when (alarmCode) { 0x01 -> // Battery 0% Alarm errorString = resourceHelper.gs(R.string.batterydischarged) 0x02 -> // Pump Error errorString = resourceHelper.gs(R.string.pumperror) + " " + alarmCode 0x03 -> // Occlusion errorString = resourceHelper.gs(R.string.occlusion) 0x04 -> // LOW BATTERY errorString = resourceHelper.gs(R.string.pumpshutdown) 0x05 -> // Shutdown errorString = resourceHelper.gs(R.string.lowbattery) 0x06 -> // Basal Compare errorString = resourceHelper.gs(R.string.basalcompare) 0x07, 0xFF -> // Blood sugar measurement alert errorString = resourceHelper.gs(R.string.bloodsugarmeasurementalert) 0x08, 0xFE -> // Remaining insulin level errorString = resourceHelper.gs(R.string.remaininsulinalert) 0x09 -> // Empty Reservoir errorString = resourceHelper.gs(R.string.emptyreservoir) 0x0A -> // Check shaft errorString = resourceHelper.gs(R.string.checkshaft) 0x0B -> // Basal MAX errorString = resourceHelper.gs(R.string.basalmax) 0x0C -> // Daily MAX errorString = resourceHelper.gs(R.string.dailymax) 0xFD -> // Blood sugar check miss alarm errorString = resourceHelper.gs(R.string.missedbolus) } // No error no need to upload anything if (errorString == "") { failed = true aapsLogger.debug(LTag.PUMPCOMM, "Error detected: $errorString") return } val notification = Notification(Notification.USERMESSAGE, errorString, Notification.URGENT) rxBus.send(EventNewNotification(notification)) nsUpload.uploadError(errorString) } override fun getFriendlyName(): String { return "NOTIFY__ALARM" } }
agpl-3.0
46e34ffada770fd696964df9f7dad6ee
44.260274
99
0.648501
4.632539
false
false
false
false
Flank/flank
test_runner/src/main/kotlin/ftl/client/google/UserAuth.kt
1
4275
package ftl.client.google import com.google.auth.oauth2.ClientId import com.google.auth.oauth2.MemoryTokensStorage import com.google.auth.oauth2.UserAuthorizer import com.google.auth.oauth2.UserCredentials import flank.common.dotFlank import ftl.api.LoginState import ftl.config.FtlConstants import ftl.run.exception.FlankGeneralError import io.ktor.server.application.call import io.ktor.server.engine.embeddedServer import io.ktor.server.netty.Netty import io.ktor.server.response.respondText import io.ktor.server.routing.get import io.ktor.server.routing.routing import kotlinx.coroutines.delay import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.emptyFlow import kotlinx.coroutines.flow.flow import kotlinx.coroutines.runBlocking import java.io.File import java.io.FileInputStream import java.io.FileOutputStream import java.io.ObjectInputStream import java.io.ObjectOutputStream import java.net.URI import java.nio.file.Files import java.nio.file.Path import java.nio.file.Paths class UserAuth { companion object { val userToken: Path = if (FtlConstants.useMock) File.createTempFile("test_", ".Token").toPath() else Paths.get(dotFlank.toString(), "UserToken") fun exists() = Files.exists(userToken) fun load(): UserCredentials = readCredentialsOrThrow() private fun readCredentialsOrThrow(): UserCredentials = runCatching { FileInputStream(userToken.toFile()).use { ObjectInputStream(it).readObject() as UserCredentials } }.getOrElse { throwAuthenticationError() } fun throwAuthenticationError(): Nothing { Files.deleteIfExists(userToken) throw FlankGeneralError( "Could not load user authentication, please\n" + " - login again using command: flank auth login\n" + " - or try again to use The Application Default Credentials variable to login" ) } } private var waitingForUserAuth = true private val server = embeddedServer(Netty, 8085) { routing { // 'code' and 'scope' are passed back into the callback as parameters get("/oauth2callback") { authCode = call.parameters["code"] ?: "" call.respondText { "User authorized. Close the browser window." } waitingForUserAuth = false } } } var authCode = "" // https://github.com/bootstraponline/gcloud_cli/blob/40521a6e297830b9f652a9ab4d8002e309b4353a/google-cloud-sdk/platform/gsutil/gslib/utils/system_util.py#L177 private val clientId = ClientId.newBuilder() .setClientId("32555940559.apps.googleusercontent.com") .setClientSecret("ZmssLNjJy2998hD4CTg2ejr2") .build()!! // https://github.com/bootstraponline/gcloud_cli/blob/e4b5e01610abad2e31d8a6edb20b17b2f84c5395/google-cloud-sdk/lib/googlecloudsdk/core/config.py#L167 private val scopes = listOf("https://www.googleapis.com/auth/cloud-platform") private val tokenStore = MemoryTokensStorage() private val authorizer = UserAuthorizer.newBuilder() .setClientId(clientId) .setScopes(scopes) .setTokenStore(tokenStore) .build()!! private val userId = "flank" private val uri: URI = URI.create("http://localhost:8085") fun request(): Flow<LoginState> { if (FtlConstants.useMock) return emptyFlow() return flow { emit(LoginState.LoginStarted(authorizer.getAuthorizationUrl(userId, null, uri))) server.start(wait = false) while (waitingForUserAuth) { runBlocking { delay(1000) } } // trade OAuth2 authorization code for tokens. // // https://developers.google.com/gdata/docs/auth/oauth#NoLibrary authorizer.getAndStoreCredentialsFromCode(userId, authCode, uri) server.stop(0, 0) val userCredential = authorizer.getCredentials(userId) dotFlank.toFile().mkdirs() ObjectOutputStream(FileOutputStream(userToken.toFile())).writeObject(userCredential) emit(LoginState.LoginFinished(userToken.toString())) } } }
apache-2.0
d9621100500ae0d227bfdaed8de52158
34.625
163
0.681637
4.241071
false
false
false
false
fabmax/kool
kool-core/src/jsMain/kotlin/de/fabmax/kool/pipeline/PlatformAttributeProps.kt
1
1378
package de.fabmax.kool.pipeline actual class PlatformAttributeProps actual constructor(attribute: Attribute) { actual val nSlots: Int val attribSize: Int init { when (attribute.type) { GlslType.FLOAT -> { nSlots = 1 attribSize = 1 } GlslType.VEC_2F -> { nSlots = 1 attribSize = 2 } GlslType.VEC_3F -> { nSlots = 1 attribSize = 3 } GlslType.VEC_4F -> { nSlots = 1 attribSize = 4 } GlslType.MAT_2F -> { nSlots = 2 attribSize = 2 } GlslType.MAT_3F -> { nSlots = 3 attribSize = 3 } GlslType.MAT_4F -> { nSlots = 4 attribSize = 4 } GlslType.INT -> { nSlots = 1 attribSize = 1 } GlslType.VEC_2I -> { nSlots = 1 attribSize = 2 } GlslType.VEC_3I -> { nSlots = 1 attribSize = 3 } GlslType.VEC_4I -> { nSlots = 1 attribSize = 4 } } } }
apache-2.0
440a15d8f5ec1e8324be3b5329214b54
23.175439
78
0.354862
4.719178
false
false
false
false
anitawoodruff/habitica-android
Habitica/src/main/java/com/habitrpg/android/habitica/ui/fragments/preferences/PushNotificationsPreferencesFragment.kt
1
4377
package com.habitrpg.android.habitica.ui.fragments.preferences import android.content.SharedPreferences import android.os.Bundle import androidx.preference.CheckBoxPreference import com.habitrpg.android.habitica.HabiticaBaseApplication import com.habitrpg.android.habitica.helpers.RxErrorHandler import com.habitrpg.android.habitica.models.user.User import io.reactivex.functions.Consumer class PushNotificationsPreferencesFragment : BasePreferencesFragment(), SharedPreferences.OnSharedPreferenceChangeListener { private var isInitialSet: Boolean = true private var isSettingUser: Boolean = false override fun onCreate(savedInstanceState: Bundle?) { HabiticaBaseApplication.userComponent?.inject(this) super.onCreate(savedInstanceState) } override fun onResume() { super.onResume() preferenceScreen.sharedPreferences.registerOnSharedPreferenceChangeListener(this) } override fun onPause() { super.onPause() preferenceScreen.sharedPreferences.unregisterOnSharedPreferenceChangeListener(this) } override fun setupPreferences() { /* no-on */ } override fun setUser(user: User?) { super.setUser(user) isSettingUser = !isInitialSet updatePreference("preference_push_you_won_challenge", user?.preferences?.pushNotifications?.wonChallenge) updatePreference("preference_push_received_a_private_message", user?.preferences?.pushNotifications?.newPM) updatePreference("preference_push_gifted_gems", user?.preferences?.pushNotifications?.giftedGems) updatePreference("preference_push_gifted_subscription", user?.preferences?.pushNotifications?.giftedSubscription) updatePreference("preference_push_invited_to_party", user?.preferences?.pushNotifications?.invitedParty) updatePreference("preference_push_invited_to_guild", user?.preferences?.pushNotifications?.invitedGuild) updatePreference("preference_push_your_quest_has_begun", user?.preferences?.pushNotifications?.questStarted) updatePreference("preference_push_invited_to_quest", user?.preferences?.pushNotifications?.invitedQuest) updatePreference("preference_push_important_announcements", user?.preferences?.pushNotifications?.majorUpdates) updatePreference("preference_push_party_activity", user?.preferences?.pushNotifications?.partyActivity) updatePreference("preference_push_party_mention", user?.preferences?.pushNotifications?.mentionParty) updatePreference("preference_push_joined_guild_mention", user?.preferences?.pushNotifications?.mentionJoinedGuild) updatePreference("preference_push_unjoined_guild_mention", user?.preferences?.pushNotifications?.mentionUnjoinedGuild) isSettingUser = false isInitialSet = false } private fun updatePreference(key: String, isChecked: Boolean?) { val preference = (findPreference(key) as? CheckBoxPreference) preference?.isChecked = isChecked == true } override fun onSharedPreferenceChanged(sharedPreferences: SharedPreferences, key: String) { if (isSettingUser) { return } val pathKey = when (key) { "preference_push_you_won_challenge" -> "wonChallenge" "preference_push_received_a_private_message" -> "newPM" "preference_push_gifted_gems" -> "giftedGems" "preference_push_gifted_subscription" -> "giftedSubscription" "preference_push_invited_to_party" -> "invitedParty" "preference_push_invited_to_guild" -> "invitedGuild" "preference_push_your_quest_has_begun" -> "questStarted" "preference_push_invited_to_quest" -> "invitedQuest" "preference_push_important_announcements" -> "majorUpdates" "preference_push_party_activity" -> "partyActivity" "preference_push_party_mention" -> "mentionParty" "preference_push_joined_guild_mention" -> "mentionJoinedGuild" "preference_push_unjoined_guild_mention" -> "mentionUnjoinedGuild" else -> null } if (pathKey != null) { compositeSubscription.add(userRepository.updateUser(user, "preferences.pushNotifications.$pathKey", sharedPreferences.getBoolean(key, false)).subscribe(Consumer { }, RxErrorHandler.handleEmptyError())) } } }
gpl-3.0
f7aee2ed97be0f04efad28a336a23e0b
52.390244
214
0.726297
4.962585
false
false
false
false
ingokegel/intellij-community
plugins/gradle/src/org/jetbrains/plugins/gradle/execution/target/TargetBuildExecuter.kt
10
2347
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.plugins.gradle.execution.target import org.gradle.tooling.BuildAction import org.gradle.tooling.ResultHandler import org.gradle.tooling.events.OperationType import org.gradle.tooling.events.ProgressListener import org.gradle.tooling.internal.consumer.AbstractLongRunningOperation import org.gradle.tooling.internal.consumer.BlockingResultHandler import org.jetbrains.plugins.gradle.tooling.proxy.TargetBuildParameters internal abstract class TargetBuildExecuter<T : AbstractLongRunningOperation<T>, R : Any?>(private val connection: TargetProjectConnection) : AbstractLongRunningOperation<T>(connection.parameters.connectionParameters) { abstract val targetBuildParametersBuilder: TargetBuildParameters.Builder protected open val buildActions: List<BuildAction<*>> = emptyList() override fun addProgressListener(listener: ProgressListener?, vararg operationTypes: OperationType?): T { targetBuildParametersBuilder.withSubscriptions(operationTypes.asIterable().filterNotNull()) return super.addProgressListener(listener, *operationTypes) } override fun addProgressListener(listener: ProgressListener?, eventTypes: MutableSet<OperationType>?): T { eventTypes?.let { targetBuildParametersBuilder.withSubscriptions(it) } return super.addProgressListener(listener, eventTypes) } protected fun runAndGetResult(): R = BlockingResultHandler(Any::class.java).run { runWithHandler(this) @Suppress("UNCHECKED_CAST") result as R } protected fun runWithHandler(handler: ResultHandler<Any?>) { val gradleHome = connection.distribution.gradleHome.maybeGetTargetValue() if (gradleHome != null) { targetBuildParametersBuilder.useInstallation(gradleHome) } val gradleUserHome = connection.parameters.gradleUserHome.maybeGetTargetValue() if (gradleUserHome != null) { targetBuildParametersBuilder.useGradleUserHome(gradleUserHome) } val classPathAssembler = GradleServerClasspathInferer() for (buildAction in buildActions) { classPathAssembler.add(buildAction) } GradleServerRunner(connection, consumerOperationParameters).run(classPathAssembler, targetBuildParametersBuilder, handler) } }
apache-2.0
6248cdea490fc3b42d4ad6e3bd4c71c0
47.916667
141
0.802301
4.741414
false
false
false
false
mdaniel/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/callableBuilder/CallableBuilder.kt
1
62356
// 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.createFromUsage.callableBuilder import com.intellij.codeInsight.daemon.impl.quickfix.CreateFromUsageUtils 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.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.resources.KotlinBundle import org.jetbrains.kotlin.idea.core.CollectingNameValidator 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.replaced 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.base.psi.isMultiLine 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.runWriteAction 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()) runWriteAction { context.buildAndRunTemplate { buildNext(iterator) } } ApplicationManager.getApplication().invokeLater { context.showDialogIfNeeded() } } else { runWriteAction { ShortenReferences.DEFAULT.process(elementsToShorten) } } } 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) 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) } } 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).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).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 { oldTypeArgumentList.replace(KtPsiFactory(callElement).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) 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 defaultValueType = typeCandidates[callableInfo.returnTypeInfo]!!.firstOrNull()?.theType val defaultValue = defaultValueType?.let { it.getDefaultInitializer() } ?: "null" val initializer = declaration.setInitializer(KtPsiFactory(declaration).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 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) 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
fccc7f306ab5008bc5d121b4b5a7b376
49.695935
158
0.618834
6.504224
false
false
false
false
idea4bsd/idea4bsd
platform/projectModel-api/src/org/jetbrains/concurrency/AsyncPromise.kt
1
8236
/* * Copyright 2000-2016 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.concurrency import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.util.Getter import com.intellij.util.Consumer import com.intellij.util.Function import org.jetbrains.concurrency.Promise.State import java.util.* import java.util.concurrent.CountDownLatch import java.util.concurrent.TimeUnit import java.util.concurrent.TimeoutException import java.util.concurrent.atomic.AtomicReference private val LOG = Logger.getInstance(AsyncPromise::class.java) open class AsyncPromise<T> : Promise<T>, Getter<T> { private val doneRef = AtomicReference<Consumer<in T>?>() private val rejectedRef = AtomicReference<Consumer<in Throwable>?>() private val stateRef = AtomicReference(State.PENDING) // result object or error message @Volatile private var result: Any? = null override fun getState() = stateRef.get()!! override fun done(done: Consumer<in T>): Promise<T> { setHandler(doneRef, done, State.FULFILLED) return this } override fun rejected(rejected: Consumer<Throwable>): Promise<T> { setHandler(rejectedRef, rejected, State.REJECTED) return this } @Suppress("UNCHECKED_CAST") override fun get() = if (state == State.FULFILLED) result as T? else null override fun <SUB_RESULT> then(handler: Function<in T, out SUB_RESULT>): Promise<SUB_RESULT> { @Suppress("UNCHECKED_CAST") when (state) { State.PENDING -> { } State.FULFILLED -> return DonePromise<SUB_RESULT>(handler.`fun`(result as T?)) State.REJECTED -> return rejectedPromise(result as Throwable) } val promise = AsyncPromise<SUB_RESULT>() addHandlers(Consumer({ result -> promise.catchError { if (handler is Obsolescent && handler.isObsolete) { promise.cancel() } else { promise.setResult(handler.`fun`(result)) } } }), Consumer({ promise.setError(it) })) return promise } override fun notify(child: AsyncPromise<in T>) { LOG.assertTrue(child !== this) when (state) { State.PENDING -> { addHandlers(Consumer({ child.catchError { child.setResult(it) } }), Consumer({ child.setError(it) })) } State.FULFILLED -> { @Suppress("UNCHECKED_CAST") child.setResult(result as T) } State.REJECTED -> { child.setError((result as Throwable?)!!) } } } override fun <SUB_RESULT> thenAsync(handler: Function<in T, Promise<SUB_RESULT>>): Promise<SUB_RESULT> { @Suppress("UNCHECKED_CAST") when (state) { State.PENDING -> { } State.FULFILLED -> return handler.`fun`(result as T?) State.REJECTED -> return rejectedPromise(result as Throwable) } val promise = AsyncPromise<SUB_RESULT>() val rejectedHandler = Consumer<Throwable>({ promise.setError(it) }) addHandlers(Consumer({ promise.catchError { handler.`fun`(it) .done { promise.catchError { promise.setResult(it) } } .rejected(rejectedHandler) } }), rejectedHandler) return promise } override fun processed(fulfilled: AsyncPromise<in T>): Promise<T> { when (state) { State.PENDING -> { addHandlers(Consumer({ result -> fulfilled.catchError { fulfilled.setResult(result) } }), Consumer({ fulfilled.setError(it) })) } State.FULFILLED -> { @Suppress("UNCHECKED_CAST") fulfilled.setResult(result as T) } State.REJECTED -> { fulfilled.setError((result as Throwable?)!!) } } return this } private fun addHandlers(done: Consumer<T>, rejected: Consumer<Throwable>) { setHandler(doneRef, done, State.FULFILLED) setHandler(rejectedRef, rejected, State.REJECTED) } fun setResult(result: T?) { if (!stateRef.compareAndSet(State.PENDING, State.FULFILLED)) { return } this.result = result val done = doneRef.getAndSet(null) rejectedRef.set(null) if (done != null && !isObsolete(done)) { done.consume(result) } } fun setError(error: String) = setError(createError(error)) fun cancel() { setError(OBSOLETE_ERROR) } open fun setError(error: Throwable): Boolean { if (!stateRef.compareAndSet(State.PENDING, State.REJECTED)) { LOG.errorIfNotMessage(error) return false } result = error val rejected = rejectedRef.getAndSet(null) doneRef.set(null) if (rejected == null) { LOG.errorIfNotMessage(error) } else if (!isObsolete(rejected)) { rejected.consume(error) } return true } override fun processed(processed: Consumer<in T>): Promise<T> { done(processed) rejected { processed.consume(null) } return this } override fun blockingGet(timeout: Int, timeUnit: TimeUnit): T? { val latch = CountDownLatch(1) processed { latch.countDown() } if (!latch.await(timeout.toLong(), timeUnit)) { throw TimeoutException() } @Suppress("UNCHECKED_CAST") if (isRejected) { throw (result as Throwable) } else { return result as T? } } private fun <T> setHandler(ref: AtomicReference<Consumer<in T>?>, newConsumer: Consumer<in T>, targetState: State) { if (isObsolete(newConsumer)) { return } if (state != State.PENDING) { if (state == targetState) { @Suppress("UNCHECKED_CAST") newConsumer.consume(result as T?) } return } while (true) { val oldConsumer = ref.get() val newEffectiveConsumer = when (oldConsumer) { null -> newConsumer is CompoundConsumer<*> -> { @Suppress("UNCHECKED_CAST") val compoundConsumer = oldConsumer as CompoundConsumer<T> var executed = true synchronized(compoundConsumer) { compoundConsumer.consumers?.let { it.add(newConsumer) executed = false } } // clearHandlers was called - just execute newConsumer if (executed) { if (state == targetState) { @Suppress("UNCHECKED_CAST") newConsumer.consume(result as T?) } return } compoundConsumer } else -> CompoundConsumer(oldConsumer, newConsumer) } if (ref.compareAndSet(oldConsumer, newEffectiveConsumer)) { break } } if (state == targetState) { ref.getAndSet(null)?.let { @Suppress("UNCHECKED_CAST") it.consume(result as T?) } } } } private class CompoundConsumer<T>(c1: Consumer<in T>, c2: Consumer<in T>) : Consumer<T> { var consumers: MutableList<Consumer<in T>>? = ArrayList() init { synchronized(this) { consumers!!.add(c1) consumers!!.add(c2) } } override fun consume(t: T) { val list = synchronized(this) { val list = consumers consumers = null list } ?: return for (consumer in list) { if (!isObsolete(consumer)) { consumer.consume(t) } } } } internal fun isObsolete(consumer: Consumer<*>?) = consumer is Obsolescent && consumer.isObsolete inline fun <T> AsyncPromise<*>.catchError(runnable: () -> T): T? { try { return runnable() } catch (e: Throwable) { setError(e) return null } }
apache-2.0
19d4dd34340dfa875ad29a125a3bb7a3
27.305842
135
0.609883
4.45671
false
false
false
false
siosio/intellij-community
plugins/kotlin/idea/tests/testData/intentions/loopToCallChain/smartCasts/smartCastNotBroken4.kt
4
513
// WITH_RUNTIME // INTENTION_TEXT: "Replace with 'map{}.map{}.firstOrNull{}'" // INTENTION_TEXT_2: "Replace with 'asSequence().map{}.map{}.firstOrNull{}'" fun foo(list: List<String>, o: Any) { var result: Any? = "" if (o is CharSequence) { result = null <caret>for (s in list) { val a = s.length + (o as String).capitalize().hashCode() val x = a * o.length if (x > 1000) { result = x break } } } }
apache-2.0
51267b4973e4210f36ba2ba74f436a32
29.235294
76
0.489279
3.828358
false
false
false
false
jwren/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/RemoveExplicitTypeIntention.kt
1
4053
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.intentions import com.intellij.codeInsight.intention.HighPriorityAction import com.intellij.openapi.editor.Editor import com.intellij.openapi.util.TextRange import com.intellij.psi.util.elementType import org.jetbrains.kotlin.KtNodeTypes import org.jetbrains.kotlin.descriptors.FunctionDescriptor import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.idea.caches.resolve.resolveToDescriptorIfAny import org.jetbrains.kotlin.idea.project.languageVersionSettings import org.jetbrains.kotlin.idea.refactoring.addTypeArgumentsIfNeeded import org.jetbrains.kotlin.idea.refactoring.getQualifiedTypeArgumentList import org.jetbrains.kotlin.idea.search.usagesSearch.descriptor import org.jetbrains.kotlin.idea.util.isExplicitTypeReferenceNeededForTypeInference import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.endOffset import org.jetbrains.kotlin.psi.psiUtil.startOffset import org.jetbrains.kotlin.resolve.checkers.ExplicitApiDeclarationChecker import org.jetbrains.kotlin.types.typeUtil.isUnit class RemoveExplicitTypeIntention : SelfTargetingRangeIntention<KtCallableDeclaration>( KtCallableDeclaration::class.java, KotlinBundle.lazyMessage("remove.explicit.type.specification") ), HighPriorityAction { override fun applicabilityRange(element: KtCallableDeclaration): TextRange? = getRange(element) override fun applyTo(element: KtCallableDeclaration, editor: Editor?) = removeExplicitType(element) companion object { fun removeExplicitType(element: KtCallableDeclaration) { val initializer = (element as? KtProperty)?.initializer val typeArgumentList = initializer?.let { getQualifiedTypeArgumentList(it) } element.typeReference = null if (typeArgumentList != null) addTypeArgumentsIfNeeded(initializer, typeArgumentList) } fun isApplicableTo(element: KtCallableDeclaration): Boolean { return getRange(element) != null } fun getRange(element: KtCallableDeclaration): TextRange? { if (element.containingFile is KtCodeFragment) return null val typeReference = element.typeReference ?: return null if (typeReference.annotationEntries.isNotEmpty()) return null if (element is KtParameter) { if (element.isLoopParameter) return element.textRange if (element.isSetterParameter) return typeReference.textRange } if (element !is KtProperty && element !is KtNamedFunction) return null if (element is KtNamedFunction && element.hasBlockBody() && (element.descriptor as? FunctionDescriptor)?.returnType?.isUnit()?.not() != false ) return null val initializer = (element as? KtDeclarationWithInitializer)?.initializer if (element is KtProperty && element.isVar && initializer?.node?.elementType == KtNodeTypes.NULL) return null if (ExplicitApiDeclarationChecker.publicReturnTypeShouldBePresentInApiMode( element, element.languageVersionSettings, element.resolveToDescriptorIfAny() ) ) return null if (element.isExplicitTypeReferenceNeededForTypeInference()) return null return when { initializer != null -> TextRange(element.startOffset, initializer.startOffset - 1) element is KtProperty && element.getter != null -> TextRange(element.startOffset, typeReference.endOffset) element is KtNamedFunction -> TextRange(element.startOffset, typeReference.endOffset) else -> null } } } } internal val KtParameter.isSetterParameter: Boolean get() = (parent.parent as? KtPropertyAccessor)?.isSetter ?: false
apache-2.0
e3c5dc6cccd23f039a366363afc888a2
47.831325
158
0.724895
5.636996
false
false
false
false
androidx/androidx
room/room-compiler-processing/src/main/java/androidx/room/compiler/codegen/XFunSpec.kt
3
6079
/* * 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.room.compiler.codegen import androidx.room.compiler.codegen.java.JavaFunSpec import androidx.room.compiler.codegen.java.toJavaVisibilityModifier import androidx.room.compiler.codegen.kotlin.KotlinFunSpec import androidx.room.compiler.codegen.kotlin.toKotlinVisibilityModifier import androidx.room.compiler.processing.FunSpecHelper import androidx.room.compiler.processing.MethodSpecHelper import androidx.room.compiler.processing.XMethodElement import androidx.room.compiler.processing.XType import com.squareup.javapoet.MethodSpec import com.squareup.kotlinpoet.FunSpec import com.squareup.kotlinpoet.KModifier interface XFunSpec : TargetLanguage { val name: String interface Builder : TargetLanguage { val name: String fun addAnnotation(annotation: XAnnotationSpec) // TODO(b/247247442): Maybe make a XParameterSpec ? fun addParameter( typeName: XTypeName, name: String, annotations: List<XAnnotationSpec> = emptyList() ): Builder fun addCode( code: XCodeBlock ): Builder fun callSuperConstructor(vararg args: XCodeBlock): Builder fun returns(typeName: XTypeName): Builder fun build(): XFunSpec companion object { fun Builder.addStatement(format: String, vararg args: Any?) = addCode( XCodeBlock.builder(language).addStatement(format, *args).build() ) fun Builder.apply( javaMethodBuilder: MethodSpec.Builder.() -> Unit, kotlinFunctionBuilder: FunSpec.Builder.() -> Unit, ): Builder = apply { when (language) { CodeLanguage.JAVA -> { check(this is JavaFunSpec.Builder) this.actual.javaMethodBuilder() } CodeLanguage.KOTLIN -> { check(this is KotlinFunSpec.Builder) this.actual.kotlinFunctionBuilder() } } } } } companion object { fun builder( language: CodeLanguage, name: String, visibility: VisibilityModifier, isOpen: Boolean = false, isOverride: Boolean = false ): Builder { return when (language) { CodeLanguage.JAVA -> { JavaFunSpec.Builder( name, MethodSpec.methodBuilder(name).apply { addModifiers(visibility.toJavaVisibilityModifier()) // TODO(b/247242374) Add nullability annotations for non-private params // if (!isOpen) { // addModifiers(Modifier.FINAL) // } if (isOverride) { addAnnotation(Override::class.java) } } ) } CodeLanguage.KOTLIN -> { KotlinFunSpec.Builder( name, FunSpec.builder(name).apply { addModifiers(visibility.toKotlinVisibilityModifier()) if (isOpen) { addModifiers(KModifier.OPEN) } if (isOverride) { addModifiers(KModifier.OVERRIDE) } } ) } } } fun constructorBuilder( language: CodeLanguage, visibility: VisibilityModifier ): Builder { val name = "<init>" return when (language) { CodeLanguage.JAVA -> { JavaFunSpec.Builder( name, MethodSpec.constructorBuilder().apply { addModifiers(visibility.toJavaVisibilityModifier()) } ) } CodeLanguage.KOTLIN -> { KotlinFunSpec.Builder( name, FunSpec.constructorBuilder().apply { // Workaround for the unreleased fix in // https://github.com/square/kotlinpoet/pull/1342 if (visibility != VisibilityModifier.PUBLIC) { addModifiers(visibility.toKotlinVisibilityModifier()) } } ) } } } fun overridingBuilder( language: CodeLanguage, element: XMethodElement, owner: XType ): Builder { return when (language) { CodeLanguage.JAVA -> JavaFunSpec.Builder( name = element.jvmName, actual = MethodSpecHelper.overridingWithFinalParams(element, owner) ) CodeLanguage.KOTLIN -> KotlinFunSpec.Builder( name = element.name, actual = FunSpecHelper.overriding(element, owner) ) } } } }
apache-2.0
effe7619d9f6ccd29a555fb4901de988
35.190476
99
0.513078
5.995069
false
false
false
false
androidx/androidx
room/room-compiler/src/main/kotlin/androidx/room/processor/UpdateMethodProcessor.kt
3
3024
/* * 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.processor import androidx.room.OnConflictStrategy import androidx.room.Update import androidx.room.compiler.processing.XMethodElement import androidx.room.compiler.processing.XType import androidx.room.vo.UpdateMethod import androidx.room.vo.findFieldByColumnName class UpdateMethodProcessor( baseContext: Context, val containing: XType, val executableElement: XMethodElement ) { val context = baseContext.fork(executableElement) fun process(): UpdateMethod { val delegate = ShortcutMethodProcessor(context, containing, executableElement) val annotation = delegate .extractAnnotation(Update::class, ProcessorErrors.MISSING_UPDATE_ANNOTATION) val onConflict = annotation?.value?.onConflict ?: OnConflictProcessor.INVALID_ON_CONFLICT context.checker.check( onConflict in OnConflictStrategy.NONE..OnConflictStrategy.IGNORE, executableElement, ProcessorErrors.INVALID_ON_CONFLICT_VALUE ) val (entities, params) = delegate.extractParams( targetEntityType = annotation?.getAsType("entity"), missingParamError = ProcessorErrors.UPDATE_MISSING_PARAMS, onValidatePartialEntity = { entity, pojo -> val missingPrimaryKeys = entity.primaryKey.fields.filter { pojo.findFieldByColumnName(it.columnName) == null } context.checker.check( missingPrimaryKeys.isEmpty(), executableElement, ProcessorErrors.missingPrimaryKeysInPartialEntityForUpdate( partialEntityName = pojo.typeName.toString(context.codeLanguage), primaryKeyNames = missingPrimaryKeys.map { it.columnName } ) ) } ) val returnType = delegate.extractReturnType() val methodBinder = delegate.findDeleteOrUpdateMethodBinder(returnType) context.checker.check( methodBinder.adapter != null, executableElement, ProcessorErrors.CANNOT_FIND_UPDATE_RESULT_ADAPTER ) return UpdateMethod( element = delegate.executableElement, entities = entities, onConflictStrategy = onConflict, methodBinder = methodBinder, parameters = params ) } }
apache-2.0
0b204b1c0ab385876cd2be4252df0cbb
37.769231
97
0.675265
5.204819
false
false
false
false
nrizzio/Signal-Android
app/src/main/java/org/thoughtcrime/securesms/conversation/MessageSendType.kt
1
6075
package org.thoughtcrime.securesms.conversation import android.Manifest import android.content.Context import android.os.Parcelable import androidx.annotation.ColorRes import androidx.annotation.DrawableRes import androidx.annotation.StringRes import kotlinx.parcelize.Parcelize import org.signal.core.util.logging.Log import org.thoughtcrime.securesms.R import org.thoughtcrime.securesms.keyvalue.SignalStore import org.thoughtcrime.securesms.util.CharacterCalculator import org.thoughtcrime.securesms.util.MmsCharacterCalculator import org.thoughtcrime.securesms.util.PushCharacterCalculator import org.thoughtcrime.securesms.util.SmsCharacterCalculator import org.thoughtcrime.securesms.util.dualsim.SubscriptionInfoCompat import org.thoughtcrime.securesms.util.dualsim.SubscriptionManagerCompat import java.lang.IllegalArgumentException /** * The kinds of messages you can send, e.g. a plain Signal message, an SMS message, etc. */ @Parcelize sealed class MessageSendType( @StringRes val titleRes: Int, @StringRes val composeHintRes: Int, @DrawableRes val buttonDrawableRes: Int, @DrawableRes val menuDrawableRes: Int, @ColorRes val backgroundColorRes: Int, val transportType: TransportType, val characterCalculator: CharacterCalculator, open val simName: CharSequence? = null, open val simSubscriptionId: Int? = null ) : Parcelable { @get:JvmName("usesSmsTransport") val usesSmsTransport get() = transportType == TransportType.SMS @get:JvmName("usesSignalTransport") val usesSignalTransport get() = transportType == TransportType.SIGNAL fun calculateCharacters(body: String): CharacterCalculator.CharacterState { return characterCalculator.calculateCharacters(body) } fun getSimSubscriptionIdOr(fallback: Int): Int { return simSubscriptionId ?: fallback } open fun getTitle(context: Context): String { return context.getString(titleRes) } /** * A type representing an SMS message, with optional SIM fields for multi-SIM devices. */ @Parcelize data class SmsMessageSendType(override val simName: CharSequence? = null, override val simSubscriptionId: Int? = null) : MessageSendType( titleRes = R.string.ConversationActivity_transport_insecure_sms, composeHintRes = R.string.conversation_activity__type_message_sms_insecure, buttonDrawableRes = R.drawable.ic_send_unlock_24, menuDrawableRes = R.drawable.ic_insecure_24, backgroundColorRes = R.color.core_grey_50, transportType = TransportType.SMS, characterCalculator = SmsCharacterCalculator(), simName = simName, simSubscriptionId = simSubscriptionId ) { override fun getTitle(context: Context): String { return if (simName == null) { super.getTitle(context) } else { context.getString(R.string.ConversationActivity_transport_insecure_sms_with_sim, simName) } } } /** * A type representing an MMS message, with optional SIM fields for multi-SIM devices. */ @Parcelize data class MmsMessageSendType(override val simName: CharSequence? = null, override val simSubscriptionId: Int? = null) : MessageSendType( titleRes = R.string.ConversationActivity_transport_insecure_mms, composeHintRes = R.string.conversation_activity__type_message_mms_insecure, buttonDrawableRes = R.drawable.ic_send_unlock_24, menuDrawableRes = R.drawable.ic_insecure_24, backgroundColorRes = R.color.core_grey_50, transportType = TransportType.SMS, characterCalculator = MmsCharacterCalculator(), simName = simName, simSubscriptionId = simSubscriptionId ) { override fun getTitle(context: Context): String { return if (simName == null) { super.getTitle(context) } else { context.getString(R.string.ConversationActivity_transport_insecure_sms_with_sim, simName) } } } /** * A type representing a basic Signal message. */ @Parcelize object SignalMessageSendType : MessageSendType( titleRes = R.string.ConversationActivity_transport_signal, composeHintRes = R.string.conversation_activity__type_message_push, buttonDrawableRes = R.drawable.ic_send_lock_24, menuDrawableRes = R.drawable.ic_secure_24, backgroundColorRes = R.color.core_ultramarine, transportType = TransportType.SIGNAL, characterCalculator = PushCharacterCalculator() ) enum class TransportType { SIGNAL, SMS } companion object { private val TAG = Log.tag(MessageSendType::class.java) /** * Returns a list of all available [MessageSendType]s. Requires [Manifest.permission.READ_PHONE_STATE] in order to get available * SMS options. */ @JvmStatic fun getAllAvailable(context: Context, isMedia: Boolean = false): List<MessageSendType> { val options: MutableList<MessageSendType> = mutableListOf() options += SignalMessageSendType if (SignalStore.misc().smsExportPhase.allowSmsFeatures()) { try { val subscriptions: Collection<SubscriptionInfoCompat> = SubscriptionManagerCompat(context).activeAndReadySubscriptionInfos if (subscriptions.size < 2) { options += if (isMedia) MmsMessageSendType() else SmsMessageSendType() } else { options += subscriptions.map { if (isMedia) { MmsMessageSendType(simName = it.displayName, simSubscriptionId = it.subscriptionId) } else { SmsMessageSendType(simName = it.displayName, simSubscriptionId = it.subscriptionId) } } } } catch (e: SecurityException) { Log.w(TAG, "Did not have permission to get SMS subscription details!") } } return options } @JvmStatic fun getFirstForTransport(context: Context, isMedia: Boolean, transportType: TransportType): MessageSendType { return getAllAvailable(context, isMedia).firstOrNull { it.transportType == transportType } ?: throw IllegalArgumentException("No options available for desired type $transportType!") } } }
gpl-3.0
21d1c622e3de934a07edeac46c7ed8cc
34.735294
187
0.729218
4.480088
false
false
false
false
androidx/androidx
compose/ui/ui/src/commonMain/kotlin/androidx/compose/ui/semantics/SemanticsModifier.kt
3
6257
/* * Copyright 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.ui.semantics import androidx.compose.ui.Modifier import androidx.compose.ui.platform.AtomicInt import androidx.compose.ui.platform.InspectorInfo import androidx.compose.ui.platform.InspectorValueInfo import androidx.compose.ui.platform.NoInspectorInfo import androidx.compose.ui.platform.debugInspectorInfo import androidx.compose.ui.internal.JvmDefaultWithCompatibility /** * A [Modifier.Element] that adds semantics key/value for use in testing, * accessibility, and similar use cases. */ @JvmDefaultWithCompatibility interface SemanticsModifier : Modifier.Element { @Deprecated( message = "SemanticsModifier.id is now unused and has been set to a fixed value. " + "Retrieve the id from LayoutInfo instead.", replaceWith = ReplaceWith("") ) val id: Int get() = -1 /** * The SemanticsConfiguration holds substantive data, especially a list of key/value pairs * such as (label -> "buttonName"). */ val semanticsConfiguration: SemanticsConfiguration } internal class SemanticsModifierCore( mergeDescendants: Boolean, clearAndSetSemantics: Boolean, properties: (SemanticsPropertyReceiver.() -> Unit), inspectorInfo: InspectorInfo.() -> Unit = NoInspectorInfo ) : SemanticsModifier, InspectorValueInfo(inspectorInfo) { override val semanticsConfiguration: SemanticsConfiguration = SemanticsConfiguration().also { it.isMergingSemanticsOfDescendants = mergeDescendants it.isClearingSemantics = clearAndSetSemantics it.properties() } companion object { private var lastIdentifier = AtomicInt(0) fun generateSemanticsId() = lastIdentifier.addAndGet(1) } override fun equals(other: Any?): Boolean { if (this === other) return true if (other !is SemanticsModifierCore) return false if (semanticsConfiguration != other.semanticsConfiguration) return false return true } override fun hashCode(): Int { return semanticsConfiguration.hashCode() } } /** * Add semantics key/value pairs to the layout node, for use in testing, accessibility, etc. * * The provided lambda receiver scope provides "key = value"-style setters for any * [SemanticsPropertyKey]. Additionally, chaining multiple semantics modifiers is * also a supported style. * * The resulting semantics produce two [SemanticsNode] trees: * * The "unmerged tree" rooted at [SemanticsOwner.unmergedRootSemanticsNode] has one * [SemanticsNode] per layout node which has any [SemanticsModifier] on it. This [SemanticsNode] * contains all the properties set in all the [SemanticsModifier]s on that node. * * The "merged tree" rooted at [SemanticsOwner.rootSemanticsNode] has equal-or-fewer nodes: it * simplifies the structure based on [mergeDescendants] and [clearAndSetSemantics]. For most * purposes (especially accessibility, or the testing of accessibility), the merged semantics * tree should be used. * * @param mergeDescendants Whether the semantic information provided by the owning component and * its descendants should be treated as one logical entity. * Most commonly set on screen-reader-focusable items such as buttons or form fields. * In the merged semantics tree, all descendant nodes (except those themselves marked * [mergeDescendants]) will disappear from the tree, and their properties will get merged * into the parent's configuration (using a merging algorithm that varies based on the type * of property -- for example, text properties will get concatenated, separated by commas). * In the unmerged semantics tree, the node is simply marked with * [SemanticsConfiguration.isMergingSemanticsOfDescendants]. * @param properties properties to add to the semantics. [SemanticsPropertyReceiver] will be * provided in the scope to allow access for common properties and its values. */ fun Modifier.semantics( mergeDescendants: Boolean = false, properties: (SemanticsPropertyReceiver.() -> Unit) ): Modifier = this then SemanticsModifierCore( mergeDescendants = mergeDescendants, clearAndSetSemantics = false, properties = properties, inspectorInfo = debugInspectorInfo { name = "semantics" this.properties["mergeDescendants"] = mergeDescendants this.properties["properties"] = properties } ) /** * Clears the semantics of all the descendant nodes and sets new semantics. * * In the merged semantics tree, this clears the semantic information provided * by the node's descendants (but not those of the layout node itself, if any) and sets * the provided semantics. (In the unmerged tree, the semantics node is marked with * "[SemanticsConfiguration.isClearingSemantics]", but nothing is actually cleared.) * * Compose's default semantics provide baseline usability for screen-readers, but this can be * used to provide a more polished screen-reader experience: for example, clearing the * semantics of a group of tiny buttons, and setting equivalent actions on the card containing them. * * @param properties properties to add to the semantics. [SemanticsPropertyReceiver] will be * provided in the scope to allow access for common properties and its values. */ fun Modifier.clearAndSetSemantics( properties: (SemanticsPropertyReceiver.() -> Unit) ): Modifier = this then SemanticsModifierCore( mergeDescendants = false, clearAndSetSemantics = true, properties = properties, inspectorInfo = debugInspectorInfo { name = "clearAndSetSemantics" this.properties["properties"] = properties } )
apache-2.0
66b30a00ec3a9ff29153f1cf7bcac75d
41.856164
100
0.746524
4.779985
false
true
false
false
nrizzio/Signal-Android
app/src/main/java/org/thoughtcrime/securesms/exporter/flow/ExportSmsFullErrorFragment.kt
1
2116
package org.thoughtcrime.securesms.exporter.flow import android.content.Context import android.os.Bundle import android.view.ContextThemeWrapper import android.view.LayoutInflater import android.view.View import androidx.core.content.ContextCompat import androidx.navigation.fragment.findNavController import androidx.navigation.fragment.navArgs import org.thoughtcrime.securesms.LoggingFragment import org.thoughtcrime.securesms.R import org.thoughtcrime.securesms.SmsExportDirections import org.thoughtcrime.securesms.databinding.ExportSmsFullErrorFragmentBinding import org.thoughtcrime.securesms.util.navigation.safeNavigate /** * Fragment shown when all export messages failed. */ class ExportSmsFullErrorFragment : LoggingFragment(R.layout.export_sms_full_error_fragment) { private val args: ExportSmsFullErrorFragmentArgs by navArgs() override fun onGetLayoutInflater(savedInstanceState: Bundle?): LayoutInflater { val inflater = super.onGetLayoutInflater(savedInstanceState) val contextThemeWrapper: Context = ContextThemeWrapper(requireContext(), R.style.Signal_DayNight) return inflater.cloneInContext(contextThemeWrapper) } @Suppress("UsePropertyAccessSyntax") override fun onViewCreated(view: View, savedInstanceState: Bundle?) { val binding = ExportSmsFullErrorFragmentBinding.bind(view) val exportSuccessCount = args.exportMessageCount - args.exportMessageFailureCount binding.exportCompleteStatus.text = resources.getQuantityString(R.plurals.ExportSmsCompleteFragment__d_of_d_messages_exported, args.exportMessageCount, exportSuccessCount, args.exportMessageCount) binding.retryButton.setOnClickListener { findNavController().safeNavigate(SmsExportDirections.actionDirectToExportYourSmsMessagesFragment()) } binding.pleaseTryAgain.apply { setLinkColor(ContextCompat.getColor(requireContext(), R.color.signal_colorPrimary)) setLearnMoreVisible(true, R.string.ExportSmsPartiallyComplete__contact_us) setOnLinkClickListener { findNavController().safeNavigate(SmsExportDirections.actionDirectToHelpFragment()) } } } }
gpl-3.0
1e466eca10c2acecaebcb7207ec95cd1
47.090909
200
0.82656
4.943925
false
false
false
false
androidx/androidx
constraintlayout/constraintlayout-compose/integration-tests/macrobenchmark-target/src/main/java/androidx/constraintlayout/compose/integration/macrobenchmark/target/newmessage/NewMessage.kt
3
24946
/* * 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. */ @file:OptIn(ExperimentalMotionApi::class) package androidx.compose.integration.macrobenchmark.target.motionlayout.newmessage import androidx.compose.animation.core.tween import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxHeight import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.width import androidx.compose.foundation.shape.RoundedCornerShape import androidx.constraintlayout.compose.integration.macrobenchmark.target.common.components.TestableButton import androidx.compose.material.Button import androidx.compose.material.ExperimentalMaterialApi import androidx.compose.material.Icon import androidx.compose.material.LocalTextStyle import androidx.compose.material.MaterialTheme import androidx.compose.material.OutlinedTextField import androidx.compose.material.Surface import androidx.compose.material.Text import androidx.compose.material.TextField import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Close import androidx.compose.material.icons.filled.Delete import androidx.compose.material.icons.filled.Edit import androidx.compose.material.icons.filled.KeyboardArrowDown import androidx.compose.material.icons.filled.Send import androidx.compose.runtime.Composable import androidx.compose.runtime.remember import androidx.compose.ui.Alignment import androidx.compose.ui.ExperimentalComposeUiApi import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.toArgb import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.layout.layoutId import androidx.compose.ui.platform.LocalFocusManager import androidx.compose.ui.semantics.semantics import androidx.compose.ui.semantics.testTagsAsResourceId import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import androidx.constraintlayout.compose.ConstraintLayout import androidx.constraintlayout.compose.ConstraintSet import androidx.constraintlayout.compose.Dimension import androidx.constraintlayout.compose.ExperimentalMotionApi import androidx.constraintlayout.compose.MotionLayout import androidx.constraintlayout.compose.MotionLayoutScope import androidx.constraintlayout.compose.MotionScene import androidx.constraintlayout.compose.Visibility // Copied from ComposeMail project @Preview @Composable fun NewMotionMessagePreview() { NewMotionMessageWithControls(useDsl = false) } @Preview @Composable fun NewMotionMessagePreviewWithDsl() { NewMotionMessageWithControls(useDsl = true) } @OptIn(ExperimentalComposeUiApi::class, ExperimentalMotionApi::class) @Composable fun NewMotionMessageWithControls( useDsl: Boolean ) { val initialLayout = NewMessageLayout.Full val newMessageState = rememberNewMessageState(initialLayoutState = initialLayout) val motionScene = if (useDsl) { messageMotionSceneDsl(initialState = initialLayout) } else { messageMotionScene(initialState = initialLayout) } Column(Modifier.semantics { testTagsAsResourceId = true }) { Row(horizontalArrangement = Arrangement.spacedBy(10.dp)) { TestableButton( onClick = newMessageState::setToFab, text = "Fab" ) TestableButton( onClick = newMessageState::setToFull, text = "Full" ) TestableButton( onClick = newMessageState::setToMini, text = "Mini" ) } NewMessageButton( modifier = Modifier.fillMaxSize(), motionScene = motionScene, state = newMessageState, ) } } @OptIn(ExperimentalMotionApi::class) @Composable private fun messageMotionSceneDsl(initialState: NewMessageLayout): MotionScene { val startState = remember { initialState } val endState = when (startState) { NewMessageLayout.Fab -> NewMessageLayout.Full NewMessageLayout.Mini -> NewMessageLayout.Fab NewMessageLayout.Full -> NewMessageLayout.Fab } val primary = MaterialTheme.colors.primary val primaryVariant = MaterialTheme.colors.primaryVariant val onPrimary = MaterialTheme.colors.onPrimary val surface = MaterialTheme.colors.surface val onSurface = MaterialTheme.colors.onSurface return MotionScene { val box = createRefFor("box") val minIcon = createRefFor("minIcon") val editClose = createRefFor("editClose") val title = createRefFor("title") val content = createRefFor("content") val fab = constraintSet(NewMessageLayout.Fab.name) { constrain(box) { width = Dimension.value(50.dp) height = Dimension.value(50.dp) end.linkTo(parent.end, 12.dp) bottom.linkTo(parent.bottom, 12.dp) customColor("background", primary) } constrain(minIcon) { width = Dimension.value(40.dp) height = Dimension.value(40.dp) end.linkTo(editClose.start, 8.dp) top.linkTo(editClose.top) customColor("content", onPrimary) } constrain(editClose) { width = Dimension.value(40.dp) height = Dimension.value(40.dp) centerTo(box) customColor("content", onPrimary) } constrain(title) { width = Dimension.fillToConstraints top.linkTo(box.top) bottom.linkTo(editClose.bottom) start.linkTo(box.start, 8.dp) end.linkTo(minIcon.start, 8.dp) customColor("content", onPrimary) visibility = Visibility.Gone } constrain(content) { width = Dimension.fillToConstraints height = Dimension.fillToConstraints start.linkTo(box.start, 8.dp) end.linkTo(box.end, 8.dp) top.linkTo(editClose.bottom, 8.dp) bottom.linkTo(box.bottom, 8.dp) visibility = Visibility.Gone } } val full = constraintSet(NewMessageLayout.Full.name) { constrain(box) { width = Dimension.fillToConstraints height = Dimension.fillToConstraints start.linkTo(parent.start, 12.dp) end.linkTo(parent.end, 12.dp) bottom.linkTo(parent.bottom, 12.dp) top.linkTo(parent.top, 40.dp) customColor("background", surface) } constrain(minIcon) { width = Dimension.value(40.dp) height = Dimension.value(40.dp) end.linkTo(editClose.start, 8.dp) top.linkTo(editClose.top) customColor("content", onSurface) } constrain(editClose) { width = Dimension.value(40.dp) height = Dimension.value(40.dp) end.linkTo(box.end, 4.dp) top.linkTo(box.top, 4.dp) customColor("content", onSurface) } constrain(title) { width = Dimension.fillToConstraints top.linkTo(box.top) bottom.linkTo(editClose.bottom) start.linkTo(box.start, 8.dp) end.linkTo(minIcon.start, 8.dp) customColor("content", onSurface) } constrain(content) { width = Dimension.fillToConstraints height = Dimension.fillToConstraints start.linkTo(box.start, 8.dp) end.linkTo(box.end, 8.dp) top.linkTo(editClose.bottom, 8.dp) bottom.linkTo(box.bottom, 8.dp) } } val mini = constraintSet(NewMessageLayout.Mini.name) { constrain(box) { width = Dimension.value(220.dp) height = Dimension.value(50.dp) end.linkTo(parent.end, 12.dp) bottom.linkTo(parent.bottom, 12.dp) customColor("background", primaryVariant) } constrain(minIcon) { width = Dimension.value(40.dp) height = Dimension.value(40.dp) end.linkTo(editClose.start, 8.dp) top.linkTo(editClose.top) rotationZ = 180f customColor("content", onPrimary) } constrain(editClose) { width = Dimension.value(40.dp) height = Dimension.value(40.dp) end.linkTo(box.end, 4.dp) top.linkTo(box.top, 4.dp) customColor("content", onPrimary) } constrain(title) { width = Dimension.fillToConstraints top.linkTo(box.top) bottom.linkTo(editClose.bottom) start.linkTo(box.start, 8.dp) end.linkTo(minIcon.start, 8.dp) customColor("content", onPrimary) } constrain(content) { width = Dimension.fillToConstraints start.linkTo(box.start, 8.dp) end.linkTo(box.end, 8.dp) top.linkTo(editClose.bottom, 8.dp) bottom.linkTo(box.bottom, 8.dp) visibility = Visibility.Gone } } fun constraintSetFor(layoutState: NewMessageLayout) = when (layoutState) { NewMessageLayout.Full -> full NewMessageLayout.Mini -> mini NewMessageLayout.Fab -> fab } defaultTransition( from = constraintSetFor(startState), to = constraintSetFor(endState) ) } } @OptIn(ExperimentalMotionApi::class) @Composable private fun messageMotionScene(initialState: NewMessageLayout): MotionScene { val startState = remember { initialState } val endState = when (startState) { NewMessageLayout.Fab -> NewMessageLayout.Full NewMessageLayout.Mini -> NewMessageLayout.Fab NewMessageLayout.Full -> NewMessageLayout.Fab } val startStateName = startState.name val endStateName = endState.name val primary = MaterialTheme.colors.primary.toHexString() val primaryVariant = MaterialTheme.colors.primaryVariant.toHexString() val onPrimary = MaterialTheme.colors.onPrimary.toHexString() val surface = MaterialTheme.colors.surface.toHexString() val onSurface = MaterialTheme.colors.onSurface.toHexString() return MotionScene( content = """ { ConstraintSets: { ${NewMessageLayout.Fab.name}: { box: { width: 50, height: 50, end: ['parent', 'end', 12], bottom: ['parent', 'bottom', 12], custom: { background: '#$primary' } }, minIcon: { width: 40, height: 40, end: ['editClose', 'start', 8], top: ['editClose', 'top', 0], visibility: 'gone', custom: { content: '#$onPrimary' } }, editClose: { width: 40, height: 40, centerHorizontally: 'box', centerVertically: 'box', custom: { content: '#$onPrimary' } }, title: { width: 'spread', top: ['box', 'top', 0], bottom: ['editClose', 'bottom', 0], start: ['box', 'start', 8], end: ['minIcon', 'start', 8], custom: { content: '#$onPrimary' } visibility: 'gone' }, content: { width: 'spread', height: 'spread', start: ['box', 'start', 8], end: ['box', 'end', 8], top: ['editClose', 'bottom', 8], bottom: ['box', 'bottom', 8], visibility: 'gone' } }, ${NewMessageLayout.Full.name}: { box: { width: 'spread', height: 'spread', start: ['parent', 'start', 12], end: ['parent', 'end', 12], bottom: ['parent', 'bottom', 12], top: ['parent', 'top', 40], custom: { background: '#$surface' } }, minIcon: { width: 40, height: 40, end: ['editClose', 'start', 8], top: ['editClose', 'top', 0], custom: { content: '#$onSurface' } }, editClose: { width: 40, height: 40, end: ['box', 'end', 4], top: ['box', 'top', 4], custom: { content: '#$onSurface' } }, title: { width: 'spread', top: ['box', 'top', 0], bottom: ['editClose', 'bottom', 0], start: ['box', 'start', 8], end: ['minIcon', 'start', 8], custom: { content: '#$onSurface' } }, content: { width: 'spread', height: 'spread', start: ['box', 'start', 8], end: ['box', 'end', 8], top: ['editClose', 'bottom', 8], bottom: ['box', 'bottom', 8] } }, ${NewMessageLayout.Mini.name}: { box: { width: 180, height: 50, bottom: ['parent', 'bottom', 12], end: ['parent', 'end', 12], custom: { background: '#$primaryVariant' } }, minIcon: { width: 40, height: 40, end: ['editClose', 'start', 8], top: ['editClose', 'top', 0], rotationZ: 180, custom: { content: '#$onPrimary' } }, editClose: { width: 40, height: 40, end: ['box', 'end', 4], top: ['box', 'top', 4], custom: { content: '#$onPrimary' } }, title: { width: 'spread', top: ['box', 'top', 0], bottom: ['editClose', 'bottom', 0], start: ['box', 'start', 8], end: ['minIcon', 'start', 8], custom: { content: '#$onPrimary' } }, content: { width: 'spread', height: 'spread', start: ['box', 'start', 8], end: ['box', 'end', 8], top: ['editClose', 'bottom', 8], bottom: ['box', 'bottom', 8], visibility: 'gone' } } }, Transitions: { default: { from: '$startStateName', to: '$endStateName' } } } """ ) } @OptIn(ExperimentalMotionApi::class) @Composable internal fun MotionLayoutScope.MotionMessageContent( state: NewMessageState ) { val currentState = state.currentState val focusManager = LocalFocusManager.current val dialogName = remember(currentState) { when (currentState) { NewMessageLayout.Mini -> "Draft" else -> "Message" } } Surface( modifier = Modifier.layoutId("box"), color = motionColor(id = "box", name = "background"), elevation = 4.dp, shape = RoundedCornerShape(8.dp) ) {} ColorableIconButton( modifier = Modifier.layoutId("editClose"), imageVector = when (currentState) { NewMessageLayout.Fab -> Icons.Default.Edit else -> Icons.Default.Close }, color = motionColor("editClose", "content"), enabled = true ) { when (currentState) { NewMessageLayout.Fab -> state.setToFull() else -> state.setToFab() } } ColorableIconButton( modifier = Modifier.layoutId("minIcon"), imageVector = Icons.Default.KeyboardArrowDown, color = motionColor("minIcon", "content"), enabled = true ) { when (currentState) { NewMessageLayout.Full -> state.setToMini() else -> state.setToFull() } } CheapText( text = dialogName, modifier = Modifier.layoutId("title"), color = motionColor("title", "content"), style = MaterialTheme.typography.h6 ) MessageWidget(modifier = Modifier.layoutId("content"), onDelete = { focusManager.clearFocus() state.setToFab() }) // MessageWidgetCol( // modifier = Modifier // .layoutId("content") // .padding(start = 4.dp, end = 4.dp, bottom = 4.dp) // ) } @Composable private fun NewMessageButton( modifier: Modifier = Modifier, motionScene: MotionScene, state: NewMessageState ) { val currentStateName = state.currentState.name MotionLayout( motionScene = motionScene, animationSpec = tween(700), constraintSetName = currentStateName, modifier = modifier ) { MotionMessageContent(state = state) } } @OptIn(ExperimentalMaterialApi::class) @Composable internal fun ColorableIconButton( modifier: Modifier, imageVector: ImageVector, color: Color, enabled: Boolean, onClick: () -> Unit ) { Surface( modifier = modifier, color = Color.Transparent, contentColor = color, onClick = onClick, enabled = enabled ) { Icon( imageVector = imageVector, contentDescription = null, modifier = Modifier.fillMaxSize() ) } } // With column @Composable internal fun MessageWidgetCol(modifier: Modifier) { Column( modifier = modifier, verticalArrangement = Arrangement.spacedBy(8.dp), horizontalAlignment = Alignment.CenterHorizontally ) { TextField( modifier = Modifier.fillMaxWidth(), value = "", onValueChange = {}, placeholder = { Text("Recipients") } ) TextField( modifier = Modifier.fillMaxWidth(), value = "", onValueChange = {}, placeholder = { Text("Subject") } ) TextField( modifier = Modifier .fillMaxWidth() .weight(weight = 2.0f, fill = true), value = "", onValueChange = {}, placeholder = { Text("Message") } ) Row( modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween, ) { Button(onClick = { /*TODO*/ }) { Row { Text(text = "Send") Spacer(modifier = Modifier.width(8.dp)) Icon( imageVector = Icons.Default.Send, contentDescription = "Send Mail", ) } } Button(onClick = { /*TODO*/ }) { Icon( imageVector = Icons.Default.Delete, contentDescription = "Delete Draft", ) } } } } // With ConstraintLayout @Preview @Composable private fun MessageWidgetPreview() { MessageWidget(modifier = Modifier.fillMaxSize()) } @Composable internal fun MessageWidget( modifier: Modifier, onDelete: () -> Unit = {} ) { val constraintSet = remember { ConstraintSet( """ { gl1: { type: 'hGuideline', end: 50 }, recipient: { top: ['parent', 'top', 2], width: 'spread', centerHorizontally: 'parent', }, subject: { top: ['recipient', 'bottom', 8], width: 'spread', centerHorizontally: 'parent', }, message: { height: 'spread', width: 'spread', centerHorizontally: 'parent', top: ['subject', 'bottom', 8], bottom: ['gl1', 'bottom', 4], }, delete: { height: 'spread', top: ['gl1', 'bottom', 0], bottom: ['parent', 'bottom', 4], start: ['parent', 'start', 0] }, send: { height: 'spread', top: ['gl1', 'bottom', 0], bottom: ['parent', 'bottom', 4], end: ['parent', 'end', 0] } } """.trimIndent() ) } ConstraintLayout( modifier = modifier.padding(top = 4.dp, start = 8.dp, end = 8.dp, bottom = 0.dp), constraintSet = constraintSet ) { OutlinedTextField( modifier = Modifier.layoutId("recipient"), value = "", onValueChange = {}, label = { CheapText("To") } ) OutlinedTextField( modifier = Modifier.layoutId("subject"), value = "", onValueChange = {}, label = { CheapText("Subject") } ) OutlinedTextField( modifier = Modifier .layoutId("message") .fillMaxHeight(), value = "", onValueChange = {}, label = { CheapText("Message") } ) Button( modifier = Modifier.layoutId("send"), onClick = onDelete // TODO: Do something different for Send onClick ) { Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) { CheapText(text = "Send") Icon( imageVector = Icons.Default.Send, contentDescription = "Send Mail", ) } } Button( modifier = Modifier.layoutId("delete"), onClick = onDelete ) { Icon( imageVector = Icons.Default.Delete, contentDescription = "Delete Draft", ) } } } /** * [Text] Composable constrained to one line for better animation performance. */ @Composable private fun CheapText( text: String, modifier: Modifier = Modifier, color: Color = Color.Unspecified, style: TextStyle = LocalTextStyle.current, overflow: TextOverflow = TextOverflow.Clip ) { Text( text = text, modifier = modifier, color = color, style = style, maxLines = 1, overflow = overflow, ) } private fun Color.toHexString() = toArgb().toUInt().toString(16)
apache-2.0
6cf989e22d79706689838d0e72542558
31.911609
107
0.524132
4.908697
false
false
false
false
androidx/androidx
compose/foundation/foundation/src/commonMain/kotlin/androidx/compose/foundation/pager/PagerState.kt
3
10998
/* * 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.compose.foundation.pager import androidx.compose.animation.core.AnimationSpec import androidx.compose.animation.core.Spring import androidx.compose.animation.core.spring import androidx.compose.foundation.ExperimentalFoundationApi import androidx.compose.foundation.MutatePriority import androidx.compose.foundation.gestures.ScrollScope import androidx.compose.foundation.gestures.ScrollableState import androidx.compose.foundation.gestures.animateScrollBy import androidx.compose.foundation.gestures.snapping.calculateDistanceToDesiredSnapPosition import androidx.compose.foundation.interaction.InteractionSource import androidx.compose.foundation.lazy.LazyListItemInfo import androidx.compose.foundation.lazy.LazyListState import androidx.compose.runtime.Composable import androidx.compose.runtime.derivedStateOf import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.saveable.Saver import androidx.compose.runtime.saveable.listSaver import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.runtime.setValue import androidx.compose.ui.unit.Density import androidx.compose.ui.unit.dp import androidx.compose.ui.util.fastMaxBy import kotlin.math.abs import kotlin.math.roundToInt import kotlin.math.sign /** * Creates and remember a [PagerState] to be used with a [Pager] * * @param initialPage The pager that should be shown first. * @param initialPageOffset The offset of the initial page with respect to the start of the layout. */ @ExperimentalFoundationApi @Composable internal fun rememberPagerState(initialPage: Int = 0, initialPageOffset: Int = 0): PagerState { return rememberSaveable(saver = PagerState.Saver) { PagerState(initialPage = initialPage, initialPageOffset = initialPageOffset) } } /** * The state that can be used to control [VerticalPager] and [HorizontalPager] * @param initialPage The initial page to be displayed * @param initialPageOffset The offset of the initial page with respect to the start of the layout. */ @ExperimentalFoundationApi internal class PagerState( initialPage: Int = 0, initialPageOffset: Int = 0 ) : ScrollableState { internal var snapRemainingScrollOffset by mutableStateOf(0f) internal val lazyListState = LazyListState(initialPage, initialPageOffset) internal var pageSpacing by mutableStateOf(0) internal val pageSize: Int get() = visiblePages.firstOrNull()?.size ?: 0 private val visiblePages: List<LazyListItemInfo> get() = lazyListState.layoutInfo.visibleItemsInfo private val pageAvailableSpace: Int get() = pageSize + pageSpacing /** * How far the current page needs to scroll so the target page is considered to be the next * page. */ private val positionThresholdFraction: Float get() = with(lazyListState.density) { val minThreshold = minOf(DefaultPositionThreshold.toPx(), pageSize / 2f) minThreshold / pageSize.toFloat() } internal val pageCount: Int get() = lazyListState.layoutInfo.totalItemsCount private val closestPageToSnappedPosition: LazyListItemInfo? get() = visiblePages.fastMaxBy { -abs( lazyListState.density.calculateDistanceToDesiredSnapPosition( lazyListState.layoutInfo, it, SnapAlignmentStartToStart ) ) } private val distanceToSnapPosition: Float get() = closestPageToSnappedPosition?.let { lazyListState.density.calculateDistanceToDesiredSnapPosition( lazyListState.layoutInfo, it, SnapAlignmentStartToStart ) } ?: 0f /** * [InteractionSource] that will be used to dispatch drag events when this * list is being dragged. If you want to know whether the fling (or animated scroll) is in * progress, use [isScrollInProgress]. */ val interactionSource: InteractionSource get() = lazyListState.interactionSource /** * The page that sits closest to the snapped position. */ val currentPage: Int by derivedStateOf { closestPageToSnappedPosition?.index ?: 0 } private var animationTargetPage by mutableStateOf(-1) private var settledPageState by mutableStateOf(initialPage) /** * The page that is currently "settled". This is an animation/gesture unaware page in the sense * that it will not be updated while the pages are being scrolled, but rather when the * animation/scroll settles. */ val settledPage: Int by derivedStateOf { if (pageCount == 0) 0 else settledPageState.coerceInPageRange() } /** * The page this [Pager] intends to settle to. * During fling or animated scroll (from [animateScrollToPage] this will represent the page * this pager intends to settle to. When no scroll is ongoing, this will be equal to * [currentPage]. */ val targetPage: Int by derivedStateOf { if (!isScrollInProgress) { currentPage } else if (animationTargetPage != -1) { animationTargetPage } else { val offsetFromFling = snapRemainingScrollOffset val offsetFromScroll = if (abs(currentPageOffset) >= abs(positionThresholdFraction)) { (abs(currentPageOffset) + 1) * pageAvailableSpace * currentPageOffset.sign } else { 0f } val pageDisplacement = (offsetFromFling + offsetFromScroll).roundToInt() / pageAvailableSpace (currentPage + pageDisplacement).coerceInPageRange() } } /** * Indicates how far the current page is to the snapped position, this will vary from * -0.5 (page is offset towards the start of the layout) to 0.5 (page is offset towards the end * of the layout). This is 0.0 if the [currentPage] is in the snapped position. The value will * flip once the current page changes. */ val currentPageOffset: Float by derivedStateOf { val currentPagePositionOffset = closestPageToSnappedPosition?.offset ?: 0 val pageUsedSpace = pageAvailableSpace.toFloat() ((-currentPagePositionOffset) / (pageUsedSpace)).coerceIn( MinPageOffset, MaxPageOffset ) } /** * Scroll (jump immediately) to a given [page] * @param page The destination page to scroll to */ suspend fun scrollToPage(page: Int) { val targetPage = page.coerceInPageRange() val pageOffsetToCorrectPosition = distanceToSnapPosition.toInt() lazyListState.scrollToItem(targetPage, pageOffsetToCorrectPosition) } /** * Scroll animate to a given [page]. If the [page] is too far away from [currentPage] we will * not compose all pages in the way. We will pre-jump to a nearer page, compose and animate * the rest of the pages until [page]. * @param page The destination page to scroll to * @param animationSpec An [AnimationSpec] to move between pages. We'll use a [spring] as the * default animation. */ suspend fun animateScrollToPage( page: Int, animationSpec: AnimationSpec<Float> = spring(stiffness = Spring.StiffnessMediumLow) ) { if (page == currentPage) return var currentPosition = currentPage val targetPage = page.coerceInPageRange() animationTargetPage = targetPage // If our future page is too far off, that is, outside of the current viewport val firstVisiblePageIndex = visiblePages.first().index val lastVisiblePageIndex = visiblePages.last().index if (((page > currentPage && page > lastVisiblePageIndex) || (page < currentPage && page < firstVisiblePageIndex)) && abs(page - currentPage) >= MaxPagesForAnimateScroll ) { val preJumpPosition = if (page > currentPage) { (page - visiblePages.size).coerceAtLeast(currentPosition) } else { page + visiblePages.size.coerceAtMost(currentPosition) } // Pre-jump to 1 viewport away from destination item, if possible scrollToPage(preJumpPosition) currentPosition = preJumpPosition } val targetOffset = targetPage * pageAvailableSpace val currentOffset = currentPosition * pageAvailableSpace val pageOffsetToSnappedPosition = distanceToSnapPosition val displacement = targetOffset - currentOffset + pageOffsetToSnappedPosition lazyListState.animateScrollBy(displacement, animationSpec) animationTargetPage = -1 } override suspend fun scroll( scrollPriority: MutatePriority, block: suspend ScrollScope.() -> Unit ) { lazyListState.scroll(scrollPriority, block) } override fun dispatchRawDelta(delta: Float): Float { return lazyListState.dispatchRawDelta(delta) } override val isScrollInProgress: Boolean get() = lazyListState.isScrollInProgress override val canScrollForward: Boolean get() = lazyListState.canScrollForward override val canScrollBackward: Boolean get() = lazyListState.canScrollBackward private fun Int.coerceInPageRange() = coerceIn(0, pageCount - 1) internal fun updateOnScrollStopped() { settledPageState = currentPage } companion object { /** * To keep current page and current page offset saved */ val Saver: Saver<PagerState, *> = listSaver( save = { listOf( it.closestPageToSnappedPosition?.index ?: 0, it.closestPageToSnappedPosition?.offset ?: 0 ) }, restore = { PagerState( initialPage = it[0], initialPageOffset = it[1] ) } ) } } private const val MinPageOffset = -0.5f private const val MaxPageOffset = 0.5f internal val SnapAlignmentStartToStart: Density.(layoutSize: Float, itemSize: Float) -> Float = { _, _ -> 0f } private val DefaultPositionThreshold = 56.dp private const val MaxPagesForAnimateScroll = 3
apache-2.0
bbca50dd26e7e848a693083e3114861b
37.454545
99
0.684852
4.971971
false
false
false
false
JayyyR/SimpleFragments
library/src/main/java/com/joeracosta/library/activity/SimpleFragment.kt
1
2519
package com.joeracosta.library.activity import android.os.Bundle import android.support.v4.app.Fragment /** * Created by Joe on 8/14/2017. * Simple Fragment. Must be used in a FragmentStackFragment/Activity or FragmentMapFragment/Activity */ abstract class SimpleFragment : Fragment() { private var atForefront: Boolean = false internal fun setAtForefront(atForefront: Boolean) { this.atForefront = atForefront } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) atForefront = savedInstanceState?.getBoolean(FOREFRONT_TAG, atForefront) ?: atForefront if (parentFragment != null) { if (parentFragment !is FragmentStackFragment && parentFragment !is FragmentMapFragment) { throw RuntimeException("A SimpleFragment must have a FragmentStackFragment/Activity or FragmentMapFragment/Activity as a parent!") } } else { if (activity !is FragmentMapActivity && activity !is FragmentStackActivity) { throw RuntimeException("A SimpleFragment must have a FragmentStackFragment/Activity or FragmentMapFragment/Activity as a parent!") } } } override fun onSaveInstanceState(outState: Bundle) { outState.putBoolean(FOREFRONT_TAG, atForefront) super.onSaveInstanceState(outState) } override fun onHiddenChanged(hidden: Boolean) { super.onHiddenChanged(hidden) if (hidden) { atForefront = false onHidden() } else { atForefront = true onShown() } } override fun onStart() { super.onStart() if (atForefront) { //only use onStart for when app is coming back from background onShown() } } override fun onStop() { super.onStop() if (atForefront) { //only use onStop for when app is backgrounding onHidden() } } /** * Called when the fragment is shown on the screen */ open fun onShown() {} /** * Called when the fragment is hidden on the screen */ open fun onHidden() {} /** * Called when back is pressed when using this Fragment in a FragmentMapActivity or FragmentStackActivity * @return whether or not the backpress was handled */ open fun onSimpleBackPressed(): Boolean { return false } } private const val FOREFRONT_TAG = "com.joeracosta.at_forefront_tag"
mit
2c8a3b5f55ff8565972f72710934f7db
27.954023
146
0.645097
4.682156
false
false
false
false
GunoH/intellij-community
platform/vcs-impl/src/com/intellij/openapi/vcs/changes/ui/ChangesTreeCellRenderer.kt
2
4165
// 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.vcs.changes.ui import com.intellij.openapi.actionSystem.ActionManager import com.intellij.ui.CellRendererPanel import com.intellij.util.ui.ThreeStateCheckBox import com.intellij.util.ui.accessibility.AccessibleContextDelegateWithContextMenu import java.awt.* import javax.accessibility.Accessible import javax.accessibility.AccessibleContext import javax.accessibility.AccessibleRole import javax.swing.JTree import javax.swing.tree.TreeCellRenderer open class ChangesTreeCellRenderer(protected val textRenderer: ChangesBrowserNodeRenderer) : CellRendererPanel(), TreeCellRenderer { private val component = ThreeStateCheckBox() init { buildLayout() } private fun buildLayout() { layout = BorderLayout() add(component, BorderLayout.WEST) add(textRenderer, BorderLayout.CENTER) } override fun getTreeCellRendererComponent( tree: JTree, value: Any, selected: Boolean, expanded: Boolean, leaf: Boolean, row: Int, hasFocus: Boolean ): Component { tree as ChangesTree value as ChangesBrowserNode<*> customize(this, selected) textRenderer.apply { isOpaque = false isTransparentIconBackground = true toolTipText = null getTreeCellRendererComponent(tree, value, selected, expanded, leaf, row, hasFocus) } component.apply { background = null isOpaque = false isVisible = tree.isShowCheckboxes && (value is ChangesTree.FixedHeightSampleChangesBrowserNode || // assume checkbox is visible for the sample node tree.isInclusionVisible(value)) if (isVisible) { state = tree.getNodeStatus(value) isEnabled = tree.run { isEnabled && isInclusionEnabled(value) } } } return this } override fun getAccessibleContext(): AccessibleContext { val accessibleComponent = component as? Accessible ?: return super.getAccessibleContext() if (accessibleContext == null) { accessibleContext = object : AccessibleContextDelegateWithContextMenu(accessibleComponent.accessibleContext) { override fun doShowContextMenu() { ActionManager.getInstance().tryToExecute(ActionManager.getInstance().getAction("ShowPopupMenu"), null, null, null, true) } override fun getDelegateParent(): Container? = parent override fun getAccessibleName(): String? { accessibleComponent.accessibleContext.accessibleName = textRenderer.accessibleContext.accessibleName return accessibleComponent.accessibleContext.accessibleName } override fun getAccessibleRole(): AccessibleRole { // Because of a problem with NVDA we have to make this a LABEL, // or otherwise NVDA will read out the entire tree path, causing confusion. return AccessibleRole.LABEL } } } return accessibleContext } /** * In case of New UI background selection painting performs by [com.intellij.ui.tree.ui.DefaultTreeUI.paint], * but in case of expansion popup painting it is necessary to fill the background in renderer. * * [setOpaque] for renderer is set in the tree UI and in [com.intellij.ui.TreeExpandableItemsHandler] * * @see [com.intellij.ui.tree.ui.DefaultTreeUI.setBackground] and its private overloading * @see [com.intellij.ui.TreeExpandableItemsHandler.doPaintTooltipImage] */ final override fun paintComponent(g: Graphics?) { if (isOpaque) { super.paintComponent(g) } } /** * Otherwise incorrect node sizes are cached - see [com.intellij.ui.tree.ui.DefaultTreeUI.createNodeDimensions]. * And [com.intellij.ui.ExpandableItemsHandler] does not work correctly. */ override fun getPreferredSize(): Dimension = layout.preferredLayoutSize(this) override fun getToolTipText(): String? = textRenderer.toolTipText companion object { fun customize(panel: CellRendererPanel, selected: Boolean) { panel.background = null panel.isSelected = selected } } }
apache-2.0
b7720d9964437efe16f877612c3e2ca2
33.716667
132
0.722929
4.928994
false
false
false
false
feelfreelinux/WykopMobilny
app/src/main/kotlin/io/github/feelfreelinux/wykopmobilny/ui/modules/search/links/LinkSearchPresenter.kt
1
2070
package io.github.feelfreelinux.wykopmobilny.ui.modules.search.links import io.github.feelfreelinux.wykopmobilny.api.search.SearchApi import io.github.feelfreelinux.wykopmobilny.base.BasePresenter import io.github.feelfreelinux.wykopmobilny.base.Schedulers import io.github.feelfreelinux.wykopmobilny.models.dataclass.Link import io.github.feelfreelinux.wykopmobilny.ui.fragments.links.LinkActionListener import io.github.feelfreelinux.wykopmobilny.ui.fragments.links.LinksInteractor import io.github.feelfreelinux.wykopmobilny.utils.intoComposite import io.reactivex.Single class LinkSearchPresenter( val schedulers: Schedulers, val searchApi: SearchApi, val linksInteractor: LinksInteractor ) : BasePresenter<LinkSearchView>(), LinkActionListener { var page = 1 fun searchLinks(q: String, shouldRefresh: Boolean) { if (shouldRefresh) page = 1 searchApi.searchLinks(page, q) .subscribeOn(schedulers.backgroundThread()) .observeOn(schedulers.mainThread()) .subscribe({ view?.showSearchEmptyView = (page == 1 && it.isEmpty()) if (it.isNotEmpty()) { page++ view?.addItems(it, shouldRefresh) } else { view?.addItems(it, (page == 1)) view?.disableLoading() } }, { view?.showErrorDialog(it) }) .intoComposite(compositeObservable) } override fun dig(link: Link) = linksInteractor.dig(link).processLinkSingle(link) override fun removeVote(link: Link) = linksInteractor.voteRemove(link).processLinkSingle(link) private fun Single<Link>.processLinkSingle(link: Link) { this .subscribeOn(schedulers.backgroundThread()) .observeOn(schedulers.mainThread()) .subscribe({ view?.updateLink(it) }, { view?.showErrorDialog(it) view?.updateLink(link) }) .intoComposite(compositeObservable) } }
mit
925e6e2da7f2654d0ebfbf24aab3cf2b
38.075472
98
0.653623
4.859155
false
false
false
false
siosio/intellij-community
platform/vcs-impl/src/com/intellij/openapi/vcs/changes/ui/PartiallyExcludedFilesStateHolder.kt
2
6183
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.openapi.vcs.changes.ui import com.intellij.openapi.Disposable import com.intellij.openapi.project.Project import com.intellij.openapi.vcs.ex.ExclusionState import com.intellij.openapi.vcs.ex.LineStatusTracker import com.intellij.openapi.vcs.ex.PartialLocalLineStatusTracker import com.intellij.openapi.vcs.impl.LineStatusTrackerManager import com.intellij.util.concurrency.annotations.RequiresEdt import com.intellij.util.containers.CollectionFactory import com.intellij.util.containers.HashingStrategy import com.intellij.util.ui.update.DisposableUpdate import com.intellij.util.ui.update.MergingUpdateQueue abstract class PartiallyExcludedFilesStateHolder<T>( project: Project, private val hashingStrategy: HashingStrategy<T>? = null ) : Disposable { private fun PartialLocalLineStatusTracker.setExcludedFromCommit(element: T, isExcluded: Boolean) = getChangeListId(element)?.let { setExcludedFromCommit(it, isExcluded) } private fun PartialLocalLineStatusTracker.getExcludedFromCommitState(element: T): ExclusionState = getChangeListId(element)?.let { getExcludedFromCommitState(it) } ?: ExclusionState.NO_CHANGES protected val myUpdateQueue = MergingUpdateQueue(PartiallyExcludedFilesStateHolder::class.java.name, 300, true, MergingUpdateQueue.ANY_COMPONENT, this) private val myIncludedElements: MutableSet<T> = if (hashingStrategy == null) HashSet() else CollectionFactory.createCustomHashingStrategySet(hashingStrategy) private val myTrackerExclusionStates: MutableMap<T, ExclusionState> = if (hashingStrategy == null) HashMap() else CollectionFactory.createCustomHashingStrategyMap(hashingStrategy) init { MyTrackerManagerListener().install(project) } override fun dispose() = Unit protected abstract val trackableElements: Sequence<T> protected abstract fun getChangeListId(element: T): String? protected abstract fun findElementFor(tracker: PartialLocalLineStatusTracker, changeListId: String): T? protected abstract fun findTrackerFor(element: T): PartialLocalLineStatusTracker? private val trackers get() = trackableElements.mapNotNull { element -> findTrackerFor(element)?.let { tracker -> element to tracker } } @RequiresEdt open fun updateExclusionStates() { myTrackerExclusionStates.clear() trackers.forEach { (element, tracker) -> val state = tracker.getExcludedFromCommitState(element) if (state != ExclusionState.NO_CHANGES) myTrackerExclusionStates[element] = state } } fun getExclusionState(element: T): ExclusionState = myTrackerExclusionStates[element] ?: if (element in myIncludedElements) ExclusionState.ALL_INCLUDED else ExclusionState.ALL_EXCLUDED private fun scheduleExclusionStatesUpdate() { myUpdateQueue.queue(DisposableUpdate.createDisposable(myUpdateQueue, "updateExcludedFromCommit") { updateExclusionStates() }) } private inner class MyTrackerListener : PartialLocalLineStatusTracker.ListenerAdapter() { override fun onExcludedFromCommitChange(tracker: PartialLocalLineStatusTracker) = scheduleExclusionStatesUpdate() override fun onChangeListMarkerChange(tracker: PartialLocalLineStatusTracker) = scheduleExclusionStatesUpdate() } private inner class MyTrackerManagerListener : LineStatusTrackerManager.ListenerAdapter() { private val trackerListener = MyTrackerListener() private val disposable get() = this@PartiallyExcludedFilesStateHolder @RequiresEdt fun install(project: Project) { with(LineStatusTrackerManager.getInstanceImpl(project)) { addTrackerListener(this@MyTrackerManagerListener, disposable) getTrackers().filterIsInstance<PartialLocalLineStatusTracker>().forEach { it.addListener(trackerListener, disposable) } } } override fun onTrackerAdded(tracker: LineStatusTracker<*>) { if (tracker !is PartialLocalLineStatusTracker) return tracker.getAffectedChangeListsIds().forEach { changeListId -> findElementFor(tracker, changeListId)?.let { element -> tracker.setExcludedFromCommit(element, element !in myIncludedElements) } } tracker.addListener(trackerListener, disposable) } override fun onTrackerRemoved(tracker: LineStatusTracker<*>) { if (tracker !is PartialLocalLineStatusTracker) return tracker.getAffectedChangeListsIds().forEach { changeListId -> val element = findElementFor(tracker, changeListId) ?: return@forEach myTrackerExclusionStates -= element val exclusionState = tracker.getExcludedFromCommitState(element) if (exclusionState != ExclusionState.NO_CHANGES) { if (exclusionState != ExclusionState.ALL_EXCLUDED) myIncludedElements += element else myIncludedElements -= element } scheduleExclusionStatesUpdate() } } } fun getIncludedSet(): Set<T> { val set: MutableSet<T> = if (hashingStrategy == null) HashSet(myIncludedElements) else CollectionFactory.createCustomHashingStrategySet(hashingStrategy).also { it.addAll(myIncludedElements) } myTrackerExclusionStates.forEach { (element, state) -> if (state == ExclusionState.ALL_EXCLUDED) set -= element else set += element } return set } fun setIncludedElements(elements: Collection<T>) { val set: MutableSet<T> = if (hashingStrategy == null) HashSet(elements) else CollectionFactory.createCustomHashingStrategySet(hashingStrategy).also { it.addAll(elements) } trackers.forEach { (element, tracker) -> tracker.setExcludedFromCommit(element, element !in set) } myIncludedElements.clear() myIncludedElements += elements updateExclusionStates() } fun includeElements(elements: Collection<T>) { elements.forEach { findTrackerFor(it)?.setExcludedFromCommit(it, false) } myIncludedElements += elements updateExclusionStates() } fun excludeElements(elements: Collection<T>) { elements.forEach { findTrackerFor(it)?.setExcludedFromCommit(it, true) } myIncludedElements -= elements updateExclusionStates() } }
apache-2.0
c31e347257bb99753d330acd0329ff83
43.482014
195
0.773734
4.982272
false
false
false
false
K0zka/kerub
src/main/kotlin/com/github/kerubistan/kerub/security/AssetAccessControllerImpl.kt
2
4724
package com.github.kerubistan.kerub.security import com.github.kerubistan.kerub.data.AccountMembershipDao import com.github.kerubistan.kerub.data.AssetDao import com.github.kerubistan.kerub.data.ControllerConfigDao import com.github.kerubistan.kerub.data.ProjectMembershipDao import com.github.kerubistan.kerub.model.Asset import com.github.kerubistan.kerub.model.AssetOwner import com.github.kerubistan.kerub.model.AssetOwnerType import com.github.kerubistan.kerub.model.paging.SearchResultPage import com.github.kerubistan.kerub.model.paging.SortResultPage import io.github.kerubistan.kroki.collections.concat import nl.komponents.kovenant.task import org.apache.shiro.SecurityUtils.getSubject import java.util.UUID class AssetAccessControllerImpl( private val controllerConfigDao: ControllerConfigDao, private val accountMembershipDao: AccountMembershipDao, private val projectMembershipDao: ProjectMembershipDao, private val validator: Validator ) : AssetAccessController { override fun <T : Asset> filter(items: List<T>): List<T> { return if (controllerConfigDao.get().accountsRequired) { val memberships = memberships(getSubject().principal.toString()) items.filter { item -> memberships.any { membership -> item.owner?.ownerId == membership.ownerId && item.owner?.ownerType == membership.ownerType } } } else { items } } override fun <T : Asset> listWithFilter(dao: AssetDao<T>, start: Long, limit: Int, sort: String): SortResultPage<T> { return if (filterNotRequired()) { val list = dao.list(start, limit, sort) SortResultPage( start = start, count = list.size.toLong(), result = list, sortBy = sort, total = dao.count().toLong() ) } else { val owners = memberships(getSubject().principal.toString()) val list = dao.listByOwners( owners = owners, limit = limit, sort = sort, start = start ) SortResultPage( start = start, count = list.size.toLong(), result = list, sortBy = sort, total = dao.count(owners = owners.toSet()).toLong() ) } } internal fun memberships(userName: String) = listOf( task { accountMembershipDao.listByUsername(userName).map { AssetOwner(ownerId = it.groupId, ownerType = AssetOwnerType.account) } }, task { projectMembershipDao.listByUsername(userName).map { AssetOwner(ownerId = it.groupId, ownerType = AssetOwnerType.project) } } ).map { it.get() }.concat() override fun <T : Asset> searchWithFilter( dao: AssetDao<T>, field: String, value: String, start: Long, limit: Int ): SearchResultPage<T> { if (filterNotRequired()) { val list = dao.fieldSearch(field, value, start, limit) return SearchResultPage( count = list.size.toLong(), result = list, searchby = field, start = start, total = dao.count().toLong() ) } else { val assetOwners = memberships(getSubject().principal.toString()).toSet() val results = dao.fieldSearch(assetOwners, field, value, start, limit) return SearchResultPage( count = results.size.toLong(), result = results, searchby = field, start = start, total = results.size.toLong() //TODO ) } } /** * Filtering of assets not required when the user is an administrator * OR account are optional and therefore all users can see all VMs */ private fun filterNotRequired() = getSubject().hasRole(admin) || !controllerConfigDao.get().accountsRequired override fun <T : Asset> doAndCheck(action: () -> T?): T? { val result = action() return if (result == null) { null } else { return checkMembership(result) } } private fun <T : Asset> checkMembership(result: T): T { val owner = result.owner return if (owner == null) { result } else when (owner.ownerType) { AssetOwnerType.account -> doAsAccountMember(owner.ownerId) { result } else -> TODO() } } override fun <T> checkAndDo(asset: Asset, action: () -> T?): T? { val owner = asset.owner validator.validate(asset) val config = controllerConfigDao.get() return if (owner != null) { if (owner.ownerType == AssetOwnerType.account) { doAsAccountMember(owner.ownerId) { action() } } else { TODO("handle projects here") } } else { if (config.accountsRequired) { throw IllegalArgumentException("accounts required") } else { action() } } } override fun <T> doAsAccountMember(accountId: UUID, action: () -> T): T { if (getSubject().hasRole(admin) || accountMembershipDao.isAccountMember(getSubject().principal.toString(), accountId)) { return action() } else { throw SecurityException("No permission") } } }
apache-2.0
03a0745b4ce2ec6c0f44b6c27bb0955f
27.636364
109
0.687765
3.535928
false
false
false
false
dowenliu-xyz/ketcd
ketcd-core/src/main/kotlin/xyz/dowenliu/ketcd/client/EtcdClient.kt
1
7452
package xyz.dowenliu.ketcd.client import io.grpc.ManagedChannel import io.grpc.ManagedChannelBuilder import org.slf4j.LoggerFactory import xyz.dowenliu.ketcd.Endpoint import xyz.dowenliu.ketcd.UsernamePassword import xyz.dowenliu.ketcd.api.AuthGrpc import xyz.dowenliu.ketcd.api.AuthenticateRequest import xyz.dowenliu.ketcd.api.StatusResponse import xyz.dowenliu.ketcd.exception.AuthFailedException import xyz.dowenliu.ketcd.exception.ConnectException import xyz.dowenliu.ketcd.resolver.AbstractEtcdNameResolverFactory import xyz.dowenliu.ketcd.version.EtcdVersion import java.util.concurrent.CountDownLatch import java.util.concurrent.ExecutionException import java.util.concurrent.TimeUnit import java.util.concurrent.atomic.AtomicReference /** * Etcd client. * * create at 2017/4/13 * @author liufl * @since 0.1.0 * * @property channelBuilder Build [ManagedChannel] for stubs used in any gRPC base service this client create. * @property token Etcd server side authentication token. */ class EtcdClient(val channelBuilder: ManagedChannelBuilder<*>, val token: String?) { /** * Companion object of [EtcdClient] */ companion object { /** * Creates new Builder instance. * * @return The instance create. */ @JvmStatic fun newBuilder() = Builder() @Throws(ConnectException::class, AuthFailedException::class) private fun getToken(channel: ManagedChannel, builder: Builder): String? { val usernamePassword = builder.usernamePassword ?: return null try { return authenticate(channel, usernamePassword).token } catch (e: InterruptedException) { throw ConnectException("connect to etcd failed.", e) } catch (e: ExecutionException) { throw AuthFailedException("auth failed as wrong username or password", e) } } private fun authenticate(channel: ManagedChannel, usernamePassword: UsernamePassword) = AuthGrpc.newBlockingStub(channel).authenticate( AuthenticateRequest.newBuilder() .setNameBytes(usernamePassword.username) .setPasswordBytes(usernamePassword.password) .build() ) } internal val knowVersion: AtomicReference<EtcdVersion?> = AtomicReference() init { val detectVersionLatch = CountDownLatch(1) newMaintenanceService().statusMemberAsync(object : ResponseCallback<StatusResponse> { override fun onResponse(response: StatusResponse) { val detectedVersion = EtcdVersion.ofValue(response.version) ?: return synchronized(Companion) { val stored = knowVersion.get() if (stored != null) { if (stored > detectedVersion) { knowVersion.set(detectedVersion) } } else { knowVersion.set(detectedVersion) } } } override fun onError(throwable: Throwable) { LoggerFactory.getLogger(javaClass).warn("Can not detect etcd version when client startup.") } override fun completeCallback() { detectVersionLatch.countDown() } }) detectVersionLatch.await(10, TimeUnit.SECONDS) } /** * Create new EtcdMaintenanceService instance. * * @return A new instance of EtcdMaintenanceService type. */ fun newMaintenanceService(): EtcdMaintenanceService = EtcdMaintenanceServiceImpl(this) /** * Create new EtcdClusterService instance. * * @return A new instance of EtcdClusterService type. */ fun newClusterService(): EtcdClusterService = EtcdClusterServiceImpl(this) /** * Create new EtcdKVService instance. * * @return A new instance of EtcdKVService type. */ fun newKVService(): EtcdKVService = EtcdKVServiceImpl(this) /** * Create new EtcdAuthService instance. * * @return A new instance of EtcdAuthService type. */ fun newAuthService(): EtcdAuthService = EtcdAuthServiceImpl(this) /** * Create new EtcdLeaseService instance. * * @return A new instance of EtcdLeaseService type. */ fun newLeaseService(): EtcdLeaseService = EtcdLeaseServiceImpl(this) /** * Create new EtcdWatchService instance. * * @return A new instance of EtcdWatchService type. */ fun newWatchService(): EtcdWatchService = EtcdWatchServiceImpl(this) /** * Builder to build an EtcdClient instance. */ class Builder internal constructor() { private val _endpoints: MutableList<Endpoint> = mutableListOf() /** * Etcd auth username password info. */ var usernamePassword: UsernamePassword? = null private set /** * NameResolver factory for etcd client. */ var nameResolverFactory: AbstractEtcdNameResolverFactory? = null private set /** * Channel builder. */ var channelBuilder: ManagedChannelBuilder<*>? = null private set /** * The distinct list of endpoints configured for the builder. */ val endpoints: List<Endpoint> get() = _endpoints.distinct().toList() /** * Add etcd server endpoints. * * @param endpoints Etcd endpoints. * @return this builder to train */ fun withEndpoint(vararg endpoints: Endpoint): Builder { _endpoints.addAll(endpoints) return this } /** * Config etcd auth username password info. * * @param usernamePassword etcd auth username password info. * @return this builder to train. */ fun withUsernamePassword(usernamePassword: UsernamePassword?): Builder { this.usernamePassword = usernamePassword return this } /** * Config etcd name resolver factory for etcd client. * * @param nameResolverFactory AbstractEtcdNameResolverFactory instance to use. * @return this builder to train. */ fun withNameResolverFactory(nameResolverFactory: AbstractEtcdNameResolverFactory?): Builder { this.nameResolverFactory = nameResolverFactory return this } /** * Config channel builder. * * @param channelBuilder ManagedChannelBuilder instance to use. * @return this builder to train. */ fun withChannelBuilder(channelBuilder: ManagedChannelBuilder<*>?): Builder { this.channelBuilder = channelBuilder return this } /** * Creates new EtcdClientProvider instance. * * @return The instance create. */ fun build(): EtcdClient { val channelBuilder = channelBuilder ?: defaultChannelBuilder(nameResolverFactory ?: simpleNameResolverFactory(endpoints)) val token = getToken(channelBuilder.build(), this) return EtcdClient(channelBuilder, token) } } }
apache-2.0
39d49accc8dad66812ba4c4f643bf9e9
33.188073
110
0.615674
5.164241
false
false
false
false
vovagrechka/fucking-everything
phizdets/phizdets-idea/src/vgrechka/phizdetsidea/phizdets/projectView/PyTypeShedNode.kt
1
2289
/* * Copyright 2000-2016 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package vgrechka.phizdetsidea.phizdets.projectView import com.intellij.ide.projectView.PresentationData import com.intellij.ide.projectView.ProjectViewNode import com.intellij.ide.projectView.ViewSettings import com.intellij.ide.projectView.impl.nodes.PsiDirectoryNode import com.intellij.openapi.project.Project import com.intellij.openapi.projectRoots.Sdk import com.intellij.openapi.roots.OrderRootType.CLASSES import com.intellij.openapi.vfs.VirtualFile import com.intellij.psi.PsiManager import com.intellij.util.PlatformIcons import vgrechka.phizdetsidea.phizdets.codeInsight.typing.PyTypeShed /** * @author vlan */ class PyTypeShedNode(project: Project?, sdk: Sdk, viewSettings: ViewSettings) : ProjectViewNode<Sdk>(project, sdk, viewSettings) { companion object { fun create(project : Project?, sdk: Sdk, viewSettings: ViewSettings) = if (sdk.rootProvider.getFiles(CLASSES).any { PyTypeShed.isInside(it) }) PyTypeShedNode(project, sdk, viewSettings) else null } override fun getChildren(): MutableCollection<PsiDirectoryNode> { val p = project ?: return mutableListOf() val psiManager = PsiManager.getInstance(p) return value.rootProvider.getFiles(CLASSES) .asSequence() .filter { PyTypeShed.isInside(it) } .map { psiManager.findDirectory(it) } .filterNotNull() .map { PsiDirectoryNode(p, it, settings) } .toMutableList() } override fun contains(file: VirtualFile) = PyTypeShed.isInside(file) override fun update(presentation: PresentationData?) { val p = presentation ?: return p.presentableText = "Typeshed Stubs" p.setIcon(PlatformIcons.LIBRARY_ICON) } }
apache-2.0
94e2c13bcd7bef40dfb47dc99b9adac9
37.166667
130
0.748799
4.278505
false
false
false
false
GunoH/intellij-community
plugins/package-search/src/com/jetbrains/packagesearch/intellij/plugin/ui/toolwindow/models/DataStatus.kt
2
1281
/******************************************************************************* * Copyright 2000-2022 JetBrains s.r.o. and contributors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models internal data class DataStatus( val isSearching: Boolean = false, val isRefreshingData: Boolean = false, val isExecutingOperations: Boolean = false ) { private val isBusy = isRefreshingData || isSearching || isExecutingOperations override fun toString() = "DataStatus(isBusy=$isBusy " + "[isSearching=$isSearching, isRefreshingData=$isRefreshingData, isExecutingOperations=$isExecutingOperations])" }
apache-2.0
2041e533f6cb560ec82d667f7659531e
43.172414
119
0.660422
5.043307
false
false
false
false
GunoH/intellij-community
plugins/github/src/org/jetbrains/plugins/github/pullrequest/data/service/GHPRStateServiceImpl.kt
8
7519
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.plugins.github.pullrequest.data.service import com.intellij.collaboration.async.CompletableFutureUtil.submitIOTask import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.progress.ProcessCanceledException import com.intellij.openapi.progress.ProgressIndicator import com.intellij.openapi.progress.ProgressManager import org.jetbrains.plugins.github.api.* import org.jetbrains.plugins.github.api.data.GHBranchProtectionRules import org.jetbrains.plugins.github.api.data.GHRepositoryPermissionLevel import org.jetbrains.plugins.github.api.data.GithubIssueState import org.jetbrains.plugins.github.api.data.GithubPullRequestMergeMethod import org.jetbrains.plugins.github.pullrequest.GHPRStatisticsCollector import org.jetbrains.plugins.github.pullrequest.data.GHPRIdentifier import org.jetbrains.plugins.github.pullrequest.data.GHPRMergeabilityStateBuilder import org.jetbrains.plugins.github.pullrequest.data.service.GHServiceUtil.logError import java.util.concurrent.CompletableFuture class GHPRStateServiceImpl internal constructor(private val progressManager: ProgressManager, private val securityService: GHPRSecurityService, private val requestExecutor: GithubApiRequestExecutor, private val serverPath: GithubServerPath, private val repoPath: GHRepositoryPath) : GHPRStateService { private val repository = GHRepositoryCoordinates(serverPath, repoPath) override fun loadBranchProtectionRules(progressIndicator: ProgressIndicator, pullRequestId: GHPRIdentifier, baseBranch: String): CompletableFuture<GHBranchProtectionRules?> { if (!securityService.currentUserHasPermissionLevel(GHRepositoryPermissionLevel.WRITE)) return CompletableFuture.completedFuture(null) return progressManager.submitIOTask(progressIndicator) { try { requestExecutor.execute(it, GithubApiRequests.Repos.Branches.getProtection(repository, baseBranch)) } catch (e: Exception) { // assume there are no restrictions if (e !is ProcessCanceledException) LOG.info("Error occurred while loading branch protection rules for $baseBranch", e) null } } } override fun loadMergeabilityState(progressIndicator: ProgressIndicator, pullRequestId: GHPRIdentifier, headRefOid: String, prHtmlUrl: String, baseBranchProtectionRules: GHBranchProtectionRules?) = progressManager.submitIOTask(progressIndicator) { val mergeabilityData = requestExecutor.execute(it, GHGQLRequests.PullRequest.mergeabilityData(repository, pullRequestId.number)) ?: error("Could not find pull request $pullRequestId.number") val builder = GHPRMergeabilityStateBuilder(headRefOid, prHtmlUrl, mergeabilityData) if (baseBranchProtectionRules != null) { builder.withRestrictions(securityService, baseBranchProtectionRules) } builder.build() }.logError(LOG, "Error occurred while loading mergeability state data for PR ${pullRequestId.number}") override fun close(progressIndicator: ProgressIndicator, pullRequestId: GHPRIdentifier) = progressManager.submitIOTask(progressIndicator) { requestExecutor.execute(it, GithubApiRequests.Repos.PullRequests.update(serverPath, repoPath.owner, repoPath.repository, pullRequestId.number, state = GithubIssueState.closed)) return@submitIOTask }.logError(LOG, "Error occurred while closing PR ${pullRequestId.number}") override fun reopen(progressIndicator: ProgressIndicator, pullRequestId: GHPRIdentifier) = progressManager.submitIOTask(progressIndicator) { requestExecutor.execute(it, GithubApiRequests.Repos.PullRequests.update(serverPath, repoPath.owner, repoPath.repository, pullRequestId.number, state = GithubIssueState.open)) return@submitIOTask }.logError(LOG, "Error occurred while reopening PR ${pullRequestId.number}") override fun markReadyForReview(progressIndicator: ProgressIndicator, pullRequestId: GHPRIdentifier) = progressManager.submitIOTask(progressIndicator) { requestExecutor.execute(it, GHGQLRequests.PullRequest.markReadyForReview(repository, pullRequestId.id)) return@submitIOTask }.logError(LOG, "Error occurred while marking PR ${pullRequestId.number} ready fro review") override fun merge(progressIndicator: ProgressIndicator, pullRequestId: GHPRIdentifier, commitMessage: Pair<String, String>, currentHeadRef: String) = progressManager.submitIOTask(progressIndicator) { requestExecutor.execute(it, GithubApiRequests.Repos.PullRequests.merge(serverPath, repoPath, pullRequestId.number, commitMessage.first, commitMessage.second, currentHeadRef)) GHPRStatisticsCollector.logMergedEvent(GithubPullRequestMergeMethod.merge) return@submitIOTask }.logError(LOG, "Error occurred while merging PR ${pullRequestId.number}") override fun rebaseMerge(progressIndicator: ProgressIndicator, pullRequestId: GHPRIdentifier, currentHeadRef: String) = progressManager.submitIOTask(progressIndicator) { requestExecutor.execute(it, GithubApiRequests.Repos.PullRequests.rebaseMerge(serverPath, repoPath, pullRequestId.number, currentHeadRef)) GHPRStatisticsCollector.logMergedEvent(GithubPullRequestMergeMethod.rebase) return@submitIOTask }.logError(LOG, "Error occurred while rebasing PR ${pullRequestId.number}") override fun squashMerge(progressIndicator: ProgressIndicator, pullRequestId: GHPRIdentifier, commitMessage: Pair<String, String>, currentHeadRef: String) = progressManager.submitIOTask(progressIndicator) { requestExecutor.execute(it, GithubApiRequests.Repos.PullRequests.squashMerge(serverPath, repoPath, pullRequestId.number, commitMessage.first, commitMessage.second, currentHeadRef)) GHPRStatisticsCollector.logMergedEvent(GithubPullRequestMergeMethod.squash) return@submitIOTask }.logError(LOG, "Error occurred while squash-merging PR ${pullRequestId.number}") companion object { private val LOG = logger<GHPRStateService>() } }
apache-2.0
eb9e7ca3c430f02dfef9b6a321cd92b2
60.138211
140
0.658997
6.509957
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/idea/tests/test/org/jetbrains/kotlin/idea/codeInsight/Java8OverrideImplementTest.kt
1
2176
// 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.codeInsight import com.intellij.codeInsight.generation.OverrideImplementExploreUtil import com.intellij.codeInsight.generation.OverrideImplementUtil import com.intellij.codeInsight.generation.PsiMethodMember import com.intellij.psi.PsiJavaFile import com.intellij.psi.PsiSubstitutor import com.intellij.psi.util.TypeConversionUtil import org.jetbrains.kotlin.idea.test.IDEA_TEST_DATA_DIR import org.jetbrains.kotlin.idea.test.KotlinWithJdkAndRuntimeLightProjectDescriptor import org.jetbrains.kotlin.idea.util.application.executeWriteCommand import org.jetbrains.kotlin.psi.KtFile import org.junit.internal.runners.JUnit38ClassRunner import org.junit.runner.RunWith import java.io.File @RunWith(JUnit38ClassRunner::class) class Java8OverrideImplementTest : AbstractOverrideImplementTest() { override val testDataDirectory: File get() = IDEA_TEST_DATA_DIR.resolve("codeInsight/overrideImplement/jdk8") override fun getProjectDescriptor() = KotlinWithJdkAndRuntimeLightProjectDescriptor.INSTANCE_FULL_JDK fun testOverrideCollectionStream() = doOverrideFileTest("stream") fun testImplementKotlinInterface() { val file = myFixture.addFileToProject( "A.kt", """interface A<T> { fun <L : T> foo(l : L) }""" ) val superClass = (file as KtFile).classes[0] val javaFile = myFixture.configureByFile(getTestName(true) + ".java") val psiClass = (javaFile as PsiJavaFile).classes[0] val method = superClass.methods[0] val substitutor = TypeConversionUtil.getSuperClassSubstitutor(superClass, psiClass, PsiSubstitutor.EMPTY) val candidates = listOf(PsiMethodMember(method, OverrideImplementExploreUtil.correctSubstitutor(method, substitutor))) myFixture.project.executeWriteCommand("") { OverrideImplementUtil.overrideOrImplementMethodsInRightPlace(myFixture.editor, psiClass, candidates, false, true) } myFixture.checkResultByFile(getTestName(true) + ".after.java") } }
apache-2.0
a2b868f7e8989cd67e8533ba571c1739
45.297872
126
0.769761
4.639659
false
true
false
false
smmribeiro/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/BooleanLiteralArgumentInspection.kt
1
4673
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.inspections import com.intellij.codeInspection.IntentionWrapper import com.intellij.codeInspection.ProblemHighlightType.GENERIC_ERROR_OR_WARNING import com.intellij.codeInspection.ProblemHighlightType.INFORMATION import com.intellij.codeInspection.ProblemsHolder import com.intellij.codeInspection.ui.MultipleCheckboxOptionsPanel import org.jetbrains.kotlin.KtNodeTypes import org.jetbrains.kotlin.descriptors.ClassConstructorDescriptor import org.jetbrains.kotlin.diagnostics.Severity import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.idea.caches.resolve.resolveToCall import org.jetbrains.kotlin.idea.intentions.AddNameToArgumentIntention import org.jetbrains.kotlin.idea.intentions.AddNamesToCallArgumentsIntention import org.jetbrains.kotlin.idea.intentions.AddNamesToFollowingArgumentsIntention import org.jetbrains.kotlin.idea.project.languageVersionSettings import org.jetbrains.kotlin.idea.util.safeAnalyzeNonSourceRootCode import org.jetbrains.kotlin.name.FqName import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameOrNull import javax.swing.JComponent class BooleanLiteralArgumentInspection( @JvmField var reportSingle: Boolean = false ) : AbstractKotlinInspection() { companion object { private val ignoreConstructors = listOf("kotlin.Pair", "kotlin.Triple").map { FqName(it) } } private fun KtExpression.isBooleanLiteral(): Boolean = this is KtConstantExpression && node.elementType == KtNodeTypes.BOOLEAN_CONSTANT private fun KtValueArgument.isUnnamedBooleanLiteral(): Boolean = !isNamed() && getArgumentExpression()?.isBooleanLiteral() == true override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean) = valueArgumentVisitor(fun(argument: KtValueArgument) { if (argument.isNamed()) return val argumentExpression = argument.getArgumentExpression() ?: return if (!argumentExpression.isBooleanLiteral()) return val call = argument.getStrictParentOfType<KtCallExpression>() ?: return val valueArguments = call.valueArguments if (argumentExpression.safeAnalyzeNonSourceRootCode().diagnostics.forElement(argumentExpression).any { it.severity == Severity.ERROR }) return if (AddNameToArgumentIntention.detectNameToAdd(argument, shouldBeLastUnnamed = false) == null) return val resolvedCall = call.resolveToCall() ?: return if ((resolvedCall.resultingDescriptor as? ClassConstructorDescriptor)?.constructedClass?.fqNameOrNull() in ignoreConstructors) { return } if (!resolvedCall.candidateDescriptor.hasStableParameterNames()) return val languageVersionSettings = call.languageVersionSettings if (valueArguments.any { !AddNameToArgumentIntention.argumentMatchedAndCouldBeNamedInCall(it, resolvedCall, languageVersionSettings) } ) return val highlightType = if (reportSingle) { GENERIC_ERROR_OR_WARNING } else { val hasNeighbourUnnamedBoolean = valueArguments.asSequence().windowed(size = 2, step = 1).any { (prev, next) -> prev == argument && next.isUnnamedBooleanLiteral() || next == argument && prev.isUnnamedBooleanLiteral() } if (hasNeighbourUnnamedBoolean) GENERIC_ERROR_OR_WARNING else INFORMATION } val fix = if (argument != valueArguments.lastOrNull { !it.isNamed() }) { if (argument == valueArguments.firstOrNull()) { AddNamesToCallArgumentsIntention() } else { AddNamesToFollowingArgumentsIntention() } } else { AddNameToArgumentIntention() } holder.registerProblemWithoutOfflineInformation( argument, KotlinBundle.message("boolean.literal.argument.without.parameter.name"), isOnTheFly, highlightType, IntentionWrapper(fix) ) }) override fun createOptionsPanel(): JComponent { val panel = MultipleCheckboxOptionsPanel(this) panel.addCheckbox(KotlinBundle.message("report.also.on.call.with.single.boolean.literal.argument"), "reportSingle") return panel } }
apache-2.0
ed5eba2326f9abfc394d23971d3bc5c9
50.922222
158
0.711748
5.478312
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/idea/tests/testData/refactoring/rename/javaGetterToOrdinaryMethod/after/synthesize.kt
13
305
fun synthesize(p: SyntheticProperty) { val v1 = p.foo() p.setSyntheticA(1) p.setSyntheticA(p.foo() + 2) p.setSyntheticA(p.foo().inc()) val syntheticA = p.foo() p.setSyntheticA(syntheticA.inc()) val x = syntheticA val i = p.foo().inc() p.setSyntheticA(i) val y = i }
apache-2.0
3c794116cde292e58eb2b26f72aab586
24.5
38
0.603279
2.877358
false
false
false
false
musichin/ktXML
ktxml/src/main/kotlin/com/github/musichin/ktxml/Element.kt
1
13232
package com.github.musichin.ktxml import java.util.NoSuchElementException interface Element : Content, Iterable<Content> { val namespace: String? val name: String val contents: List<Content> val attributes: List<Attribute> override fun mutable(): MutableElement /** * Returns size of contents in this element */ val size: Int /** * Returns content at specified position */ operator fun get(i: Int): Content operator fun get(name: String): Element /** * Returns string of first text content in contents */ fun text(): String? /** * Returns string of first cdata content in contents */ fun cdata(): String? /** * Returns string of first comment */ fun comment(): String? /** * Returns list of elements which match the specified namespace and name. */ fun elements(namespace: String? = null, name: String? = null): List<Element> /** * Returns list of elements which match the specified name. */ fun elements(name: String? = null): List<Element> /** * Returns first element which match specified namespace and name */ fun element(namespace: String? = null, name: String? = null): Element? /** * Returns first element which match specified name */ fun element(name: String): Element? /** * Returns attribute value of the first match */ fun attribute(namespace: String? = null, name: String? = null): String? /** * Returns attribute value of the first match */ fun attribute(name: String? = null): String? companion object { fun of(name: String): Element = ElementContent(name = name) fun of(namespace: String?, name: String): Element = ElementContent(namespace, name) fun of(namespace: String?, name: String, contents: List<Content>, attributes: List<Attribute>): Element = ElementContent(namespace, name, contents, attributes) } } fun elementOf(name: String) = Element.of(name) fun elementOf(namespace: String?, name: String) = Element.of(namespace, name) fun elementOf(namespace: String?, name: String, contents: List<Content>, attributes: List<Attribute>) = Element.of(namespace, name, contents, attributes) interface MutableElement : Element, MutableContent { override var namespace: String? override var name: String override val contents: MutableList<MutableContent> override val attributes: MutableList<MutableAttribute> override fun immutable(): Element override fun iterator(): Iterator<MutableContent> override fun get(i: Int): MutableContent override fun elements(namespace: String?, name: String?): List<MutableElement> override fun elements(name: String?): List<MutableElement> override fun element(namespace: String?, name: String?): MutableElement? override fun element(name: String): MutableElement? /** * Adds attribute */ fun addAttribute(attribute: Attribute) fun addAttribute(namespace: String? = null, name: String, value: String) fun addAttribute(name: String, value: String) fun addText(text: String) fun addCData(text: String) fun addComment(comment: String) fun addElement(namespace: String? = null, name: String) fun addContent(content: Content) companion object { fun of(name: String): MutableElement = MutableElementContent(name = name) fun of(namespace: String?, name: String): MutableElement = MutableElementContent(namespace, name) fun of( namespace: String?, name: String, contents: MutableList<MutableContent>, attributes: MutableList<MutableAttribute> ): MutableElement = MutableElementContent(namespace, name, contents, attributes) } } fun mutableElementOf(name: String) = MutableElement.of(name) fun mutableElementOf(namespace: String?, name: String) = MutableElement.of(namespace, name) fun mutableElementOf( namespace: String?, name: String, contents: MutableList<MutableContent>, attributes: MutableList<MutableAttribute> ) = MutableElement.of(namespace, name, contents, attributes) open class ElementContent( override val namespace: String? = null, override val name: String, override val contents: List<Content> = listOf(), override val attributes: List<Attribute> = listOf() ) : Element { constructor( name: String, contents: List<Content> = listOf(), attributes: List<Attribute> = listOf() ) : this(null, name, contents, attributes) override fun mutable(): MutableElement = MutableElementContent( namespace, name, contents.map { it.mutable() }.toMutableList(), attributes.map { it.mutable() }.toMutableList() ) override fun iterator() = contents.iterator() fun name() = name fun namespace() = namespace override fun element(namespace: String?, name: String?): Element? = contents.element(namespace, name) override fun element(name: String) = element(null, name) fun element() = element(null, null) fun elements() = contents override fun elements(name: String?): List<Element> = elements(null, name) override fun elements(namespace: String?, name: String?): List<Element> = contents.elements(namespace, name) fun attributes() = attributes override fun attribute(namespace: String?, name: String?) = attributes.find { it.matches(namespace, name) }?.value override fun attribute(name: String?) = attribute(null, name) fun attribute() = attribute(null, null) override fun text(): String? { return (contents.find { it is Text } as? Text)?.text } override fun comment(): String? { return (contents.find { it is Comment } as? Comment)?.comment } override fun cdata(): String? { return (contents.find { it is CData } as? CData)?.text } override val size: Int get() = contents.size override operator fun get(i: Int) = contents[i] override fun get(name: String): Element = element(name) ?: throw NoSuchElementException() override fun hashCode(): Int { var result = (namespace?.hashCode() ?: 0) result = 31 * result + name.hashCode() result = 31 * result + contents.hashCode() result = 31 * result + attributes.hashCode() return result } override fun equals(other: Any?): Boolean { if (other is Element) { return namespace == other.namespace && name == other.name && contents == other.contents && attributes == other.attributes } return super.equals(other) } override fun toString(): String { return "${javaClass.simpleName}(namespace=$namespace, name=$name, contents=$contents, attributes=$attributes)" } } open class MutableElementContent constructor( override var namespace: String? = null, override var name: String, override val contents: MutableList<MutableContent> = mutableListOf(), override val attributes: MutableList<MutableAttribute> = mutableListOf() ) : ElementContent(namespace, name, contents, attributes), MutableElement { override fun immutable(): Element = ElementContent( namespace, name, contents.map { it.immutable() }.toList(), attributes.map { it.immutable() }.toList() ) override fun mutable(): MutableElement = this override fun iterator() = contents.iterator() override fun get(i: Int) = contents[i] override fun get(name: String): MutableElement = element(name) ?: throw NoSuchElementException() override fun elements(namespace: String?, name: String?): List<MutableElement> = contents.elements(namespace, name) override fun elements(name: String?) = elements(null, name) override fun element(namespace: String?, name: String?): MutableElement? = contents.element(namespace, name) override fun element(name: String): MutableElement? = element(null, name) fun name(name: String) { this.name = name } fun namespace(namespace: String?) { this.namespace = namespace } override fun addAttribute(attribute: Attribute) { attributes.add(attribute.mutable()) } override fun addAttribute(namespace: String?, name: String, value: String) = addAttribute(mutableAttributeOf(namespace, name, value)) override fun addAttribute(name: String, value: String) = addAttribute(null, name, value) override fun addContent(content: Content) { contents.add(content.mutable()) } fun addElement(namespace: String? = null, name: String, init: MarkupBuilder.() -> Unit = {}) { addContent(mutableElementOf(namespace, name, init)) } override fun addElement(namespace: String?, name: String) = addElement(namespace, name, {}) fun addElement(name: String) = addElement(null, name, {}) fun addElement(name: String, init: MarkupBuilder.() -> Unit = {}) = addElement(null, name, init) override fun addText(text: String) = addContent(mutableTextOf(text)) override fun addComment(comment: String) = addContent(mutableCommentOf(comment)) override fun addCData(text: String) = addContent(mutableCDataOf(text)) fun remove(attribute: Attribute) { attributes.remove(attribute.mutable()) } fun remove(element: Content) { contents.remove(element.mutable()) } fun clearAttributes() { attributes.clear() } fun clearContent() { contents.clear() } fun clear() { clearAttributes() clearContent() } operator fun String.unaryPlus() = addText(this) } @Suppress("UNCHECKED_CAST") internal fun <T : Element> List<Content>.elements(namespace: String?, name: String?) = filter { it is Element && it.matches(namespace, name) } as List<T> @Suppress("UNCHECKED_CAST") internal fun <T : Element> List<Content>.element(namespace: String?, name: String?) = find { it is Element && it.matches(namespace, name) } as? T open class MarkupBuilder( internal val element: MutableElement, init: MarkupBuilder.() -> Unit = {} ) : Content, MutableContent { override fun mutable(): MutableElement = setNamespace(element) override fun immutable(): Element = mutable().immutable() constructor(name: String, init: MarkupBuilder.() -> Unit = {}) : this(null, name, init) constructor( namespace: String?, name: String, init: MarkupBuilder.() -> Unit = {} ) : this(mutableElementOf(namespace, name), init) init { init() } internal fun setNamespace(attribute: Attribute): Attribute { val result = attribute.mutable() result.namespace = namespace(result.namespace) return result } internal fun <T : Content> setNamespace(content: T): T { if (content is Element) { val result = content.mutable() result.namespace = namespace(result.namespace) content.contents.forEach { setNamespace(it) } content.attributes.forEach { setNamespace(it) } @Suppress("UNCHECKED_CAST") return result as T } return content } internal fun namespace(other: String?): String? { val namespace = element.namespace ?: return other if (other == null) return namespace return other } fun attribute(attribute: Attribute) = element.addAttribute(attribute) fun attribute(namespace: String? = null, name: String, value: String) = attribute(mutableAttributeOf(namespace, name, value)) fun attribute(name: String, value: String) = attribute(null, name, value) fun content(content: Content) = element.addContent(content) fun element(namespace: String?, name: String, init: MarkupBuilder.() -> Unit = {}) = content(mutableElementOf(namespace, name, init)) fun element(name: String, init: MarkupBuilder.() -> Unit = {}) = element(null, name, init) fun text(text: String) = element.addText(text) fun comment(comment: String) = element.addComment(comment) fun cdata(data: String) = element.addCData(data) operator fun String.unaryPlus() = text(this) operator fun Pair<String, String>.unaryPlus() = attribute(first, second) } fun elementOf(name: String, init: MarkupBuilder.() -> Unit = {}) = elementOf(null, name, init) fun elementOf(namespace: String? = null, name: String, init: MarkupBuilder.() -> Unit = {}) = mutableElementOf(namespace, name, init).immutable() fun mutableElementOf(name: String, init: MarkupBuilder.() -> Unit = {}) = mutableElementOf(null, name, init) fun mutableElementOf(namespace: String? = null, name: String, init: MarkupBuilder.() -> Unit = {}) = MarkupBuilder(namespace, name, init).mutable() internal fun Element.matches(namespace: String?, name: String?) = (name == null || this.name == name) && (namespace == null || this.namespace == namespace) internal fun Attribute.matches(namespace: String?, name: String?) = (name == null || this.name == name) && (namespace == null || this.namespace == namespace)
apache-2.0
3706cd11f7806036c8933aa37b1e0dac
31.591133
119
0.660293
4.387268
false
false
false
false
TachiWeb/TachiWeb-Server
Tachiyomi-App/src/main/java/eu/kanade/tachiyomi/data/preference/PreferenceKeys.kt
1
3827
package eu.kanade.tachiyomi.data.preference /** * This class stores the keys for the preferences in the application. */ object PreferenceKeys { const val theme = "pref_theme_key" const val rotation = "pref_rotation_type_key" const val enableTransitions = "pref_enable_transitions_key" const val doubleTapAnimationSpeed = "pref_double_tap_anim_speed" const val showPageNumber = "pref_show_page_number_key" const val fullscreen = "fullscreen" const val keepScreenOn = "pref_keep_screen_on_key" const val customBrightness = "pref_custom_brightness_key" const val customBrightnessValue = "custom_brightness_value" const val colorFilter = "pref_color_filter_key" const val colorFilterValue = "color_filter_value" const val defaultViewer = "pref_default_viewer_key" const val imageScaleType = "pref_image_scale_type_key" const val zoomStart = "pref_zoom_start_key" const val readerTheme = "pref_reader_theme_key" const val cropBorders = "crop_borders" const val cropBordersWebtoon = "crop_borders_webtoon" const val readWithTapping = "reader_tap" const val readWithLongTap = "reader_long_tap" const val readWithVolumeKeys = "reader_volume_keys" const val readWithVolumeKeysInverted = "reader_volume_keys_inverted" const val portraitColumns = "pref_library_columns_portrait_key" const val landscapeColumns = "pref_library_columns_landscape_key" const val updateOnlyNonCompleted = "pref_update_only_non_completed_key" const val autoUpdateTrack = "pref_auto_update_manga_sync_key" const val lastUsedCatalogueSource = "last_catalogue_source" const val lastUsedCategory = "last_used_category" const val catalogueAsList = "pref_display_catalogue_as_list" const val enabledLanguages = "source_languages" const val backupDirectory = "backup_directory" const val downloadsDirectory = "download_directory" const val downloadOnlyOverWifi = "pref_download_only_over_wifi_key" const val numberOfBackups = "backup_slots" const val backupInterval = "backup_interval" const val removeAfterReadSlots = "remove_after_read_slots" const val removeAfterMarkedAsRead = "pref_remove_after_marked_as_read_key" const val libraryUpdateInterval = "pref_library_update_interval_key" const val libraryUpdateRestriction = "library_update_restriction" const val libraryUpdateCategories = "library_update_categories" const val filterDownloaded = "pref_filter_downloaded_key" const val filterUnread = "pref_filter_unread_key" const val filterCompleted = "pref_filter_completed_key" const val librarySortingMode = "library_sorting_mode" const val automaticUpdates = "automatic_updates" const val startScreen = "start_screen" const val downloadNew = "download_new" const val downloadNewCategories = "download_new_categories" const val libraryAsList = "pref_display_library_as_list" const val lang = "app_language" const val defaultCategory = "default_category" const val downloadBadge = "display_download_badge" const val syncId = "sync_id" const val lastSync = "last_sync" const val syncOnLaunch = "pref_sync_on_launch" const val syncInterval = "pref_sync_interval" @Deprecated("Use the preferences of the source") fun sourceUsername(sourceId: Long) = "pref_source_username_$sourceId" @Deprecated("Use the preferences of the source") fun sourcePassword(sourceId: Long) = "pref_source_password_$sourceId" fun sourceSharedPref(sourceId: Long) = "source_$sourceId" fun trackUsername(syncId: Int) = "pref_mangasync_username_$syncId" fun trackPassword(syncId: Int) = "pref_mangasync_password_$syncId" fun trackToken(syncId: Int) = "track_token_$syncId" }
apache-2.0
b620a8375d0a6f9fd5c028565fa726f7
27.992424
78
0.729031
4.075612
false
false
false
false
marverenic/Paper
app/src/main/java/com/marverenic/reader/data/database/sql/LinkTable.kt
1
2208
package com.marverenic.reader.data.database.sql import android.content.ContentValues import android.database.Cursor import android.database.sqlite.SQLiteDatabase import com.marverenic.reader.model.Link import com.marverenic.reader.utils.getString private const val LINK_TABLE_NAME = "links" private const val LINK_ID_COL = "_ID" private const val LINK_HREF_COL = "href" private const val LINK_TYPE_COL = "type" private const val LINK_ARTICLE_ID_COL = "article_ID" private const val CREATE_STATEMENT = """ CREATE TABLE $LINK_TABLE_NAME( $LINK_ID_COL varchar PRIMARY KEY, $LINK_HREF_COL varchar, $LINK_TYPE_COL varchar, $LINK_ARTICLE_ID_COL varchar ); """ data class LinkRow(val link: Link, val articleId: String) { val id: String get() = "$articleId/${link.href}" } class LinkTable(db: SQLiteDatabase) : SqliteTable<LinkRow>(db) { override val tableName = LINK_TABLE_NAME companion object { fun onCreate(db: SQLiteDatabase) { db.execSQL(CREATE_STATEMENT) } } override fun convertToContentValues(row: LinkRow, cv: ContentValues) { cv.put(LINK_ID_COL, row.id) cv.put(LINK_ARTICLE_ID_COL, row.articleId) val link = row.link cv.put(LINK_HREF_COL, link.href) cv.put(LINK_TYPE_COL, link.type) } override fun readValueFromCursor(cursor: Cursor) = LinkRow( link = Link( href = cursor.getString(LINK_HREF_COL), type = cursor.getString(LINK_TYPE_COL) ), articleId = cursor.getString(LINK_ARTICLE_ID_COL) ) fun insert(link: Link, articleId: String) { insert(LinkRow(link, articleId)) } fun insertAll(links: Collection<Link>, articleId: String) { insertAll(links.map { LinkRow(it, articleId) }) } fun findByArticle(articleId: String) = query( selection = "$LINK_ARTICLE_ID_COL = ?", selectionArgs = arrayOf(articleId)) .map(LinkRow::link) }
apache-2.0
d7777f8fd0dc8604c60304ca8fbe9540
29.680556
78
0.593297
3.978378
false
false
false
false
Waboodoo/HTTP-Shortcuts
HTTPShortcuts/app/src/main/kotlin/ch/rmy/android/http_shortcuts/activities/categories/editor/CategoryEditorViewModel.kt
1
7312
package ch.rmy.android.http_shortcuts.activities.categories.editor import android.app.Application import androidx.lifecycle.viewModelScope import ch.rmy.android.framework.utils.localization.StringResLocalizable import ch.rmy.android.framework.viewmodel.BaseViewModel import ch.rmy.android.framework.viewmodel.WithDialog import ch.rmy.android.framework.viewmodel.viewstate.DialogState import ch.rmy.android.http_shortcuts.R import ch.rmy.android.http_shortcuts.activities.categories.editor.models.CategoryBackground import ch.rmy.android.http_shortcuts.dagger.getApplicationComponent import ch.rmy.android.http_shortcuts.data.domains.categories.CategoryId import ch.rmy.android.http_shortcuts.data.domains.categories.CategoryRepository import ch.rmy.android.http_shortcuts.data.enums.CategoryBackgroundType import ch.rmy.android.http_shortcuts.data.enums.CategoryLayoutType import ch.rmy.android.http_shortcuts.data.enums.ShortcutClickBehavior import ch.rmy.android.http_shortcuts.data.models.CategoryModel import ch.rmy.android.http_shortcuts.extensions.createDialogState import ch.rmy.android.http_shortcuts.utils.ColorPickerFactory import ch.rmy.android.http_shortcuts.utils.LauncherShortcutManager import kotlinx.coroutines.CancellationException import kotlinx.coroutines.launch import javax.inject.Inject class CategoryEditorViewModel(application: Application) : BaseViewModel<CategoryEditorViewModel.InitData, CategoryEditorViewState>(application), WithDialog { @Inject lateinit var categoryRepository: CategoryRepository @Inject lateinit var launcherShortcutManager: LauncherShortcutManager @Inject lateinit var colorPickerFactory: ColorPickerFactory init { getApplicationComponent().inject(this) } private lateinit var category: CategoryModel private val isNewCategory get() = initData.categoryId == null override var dialogState: DialogState? get() = currentViewState?.dialogState set(value) { updateViewState { copy(dialogState = value) } } override fun onInitializationStarted(data: InitData) { if (data.categoryId != null) { viewModelScope.launch { try { val category = categoryRepository.getCategory(data.categoryId) [email protected] = category finalizeInitialization() } catch (e: CancellationException) { throw e } catch (e: Exception) { handleInitializationError(e) } } } else { category = CategoryModel() finalizeInitialization() } } private fun handleInitializationError(error: Throwable) { handleUnexpectedError(error) finish() } override fun initViewState() = CategoryEditorViewState( toolbarTitle = StringResLocalizable(if (isNewCategory) R.string.title_create_category else R.string.title_edit_category), categoryName = category.name, categoryLayoutType = category.categoryLayoutType, categoryBackgroundType = category.categoryBackgroundType, categoryClickBehavior = category.clickBehavior, originalCategoryName = category.name, originalCategoryLayoutType = category.categoryLayoutType, originalCategoryBackgroundType = category.categoryBackgroundType, originalCategoryClickBehavior = category.clickBehavior, ) fun onCategoryNameChanged(name: String) { updateViewState { copy(categoryName = name) } } fun onLayoutTypeChanged(categoryLayoutType: CategoryLayoutType) { updateViewState { copy(categoryLayoutType = categoryLayoutType) } } fun onBackgroundChanged(backgroundType: CategoryBackground) { doWithViewState { viewState -> if (backgroundType == CategoryBackground.WALLPAPER && viewState.categoryBackground != CategoryBackground.WALLPAPER) { emitEvent(CategoryEditorEvent.RequestFilePermissionsIfNeeded) } val newCategoryBackgroundType = when (backgroundType) { CategoryBackground.DEFAULT -> CategoryBackgroundType.Default CategoryBackground.COLOR -> CategoryBackgroundType.Color(viewState.backgroundColor) CategoryBackground.WALLPAPER -> CategoryBackgroundType.Wallpaper } updateViewState { copy(categoryBackgroundType = newCategoryBackgroundType) } } } fun onClickBehaviorChanged(clickBehavior: ShortcutClickBehavior?) { updateViewState { copy(categoryClickBehavior = clickBehavior) } } fun onColorButtonClicked() { doWithViewState { viewState -> dialogState = createDialogState("category-color-picker") { colorPickerFactory.createColorPicker( onColorPicked = ::onBackgroundColorSelected, onDismissed = { dialogState?.let(::onDialogDismissed) }, initialColor = viewState.backgroundColor, ) } } } private fun onBackgroundColorSelected(color: Int) { updateViewState { copy(categoryBackgroundType = CategoryBackgroundType.Color(color)) } } fun onSaveButtonClicked() { doWithViewState { viewState -> if (!viewState.hasChanges) { return@doWithViewState } viewModelScope.launch { saveChanges(viewState) finishWithOkResult() } } } private suspend fun saveChanges(viewState: CategoryEditorViewState) { if (isNewCategory) { categoryRepository.createCategory( name = viewState.categoryName, layoutType = viewState.categoryLayoutType, background = viewState.categoryBackgroundType, clickBehavior = viewState.categoryClickBehavior, ) } else { categoryRepository.updateCategory( category.id, name = viewState.categoryName, layoutType = viewState.categoryLayoutType, background = viewState.categoryBackgroundType, clickBehavior = viewState.categoryClickBehavior, ) launcherShortcutManager.updatePinnedCategoryShortcut(category.id, viewState.categoryName) } } fun onBackPressed() { doWithViewState { viewState -> if (viewState.hasChanges) { showDiscardDialog() } else { finish() } } } private fun showDiscardDialog() { dialogState = createDialogState { message(R.string.confirm_discard_changes_message) .positive(R.string.dialog_discard) { onDiscardDialogConfirmed() } .negative(R.string.dialog_cancel) .build() } } private fun onDiscardDialogConfirmed() { finish() } data class InitData(val categoryId: CategoryId?) }
mit
2ae4f94269ae56915dc80c667171d615
35.378109
129
0.656865
5.428359
false
false
false
false
sandy-8925/Checklist
app/src/main/java/org/sanpra/checklist/activity/ChecklistActivity.kt
1
3063
/* * Copyright (C) 2011-2018 Sandeep Raghuraman ([email protected]) This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.sanpra.checklist.activity import android.app.Dialog import android.content.Intent import android.os.Bundle import android.text.Spannable import android.text.SpannableString import android.text.util.Linkify import android.view.Menu import android.view.MenuItem import androidx.appcompat.app.AlertDialog import androidx.appcompat.app.AppCompatActivity import androidx.core.text.util.LinkifyCompat import androidx.databinding.DataBindingUtil import androidx.fragment.app.DialogFragment import com.google.android.gms.oss.licenses.OssLicensesMenuActivity import org.sanpra.checklist.R import org.sanpra.checklist.databinding.ChecklistBinding /** * Main activity, that is displayed when the app is launched. Displays the list of ToDo items. */ class ChecklistActivity : AppCompatActivity() { /** Called when the activity is first created. */ override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val binding = DataBindingUtil.setContentView<ChecklistBinding>(this, R.layout.checklist) setSupportActionBar(binding.toolbar) } override fun onCreateOptionsMenu(menu: Menu?): Boolean { menuInflater.inflate(R.menu.main_menu, menu) return true } override fun onOptionsItemSelected(item: MenuItem): Boolean { when(item.itemId) { R.id.menu_license_info -> { startActivity(Intent(this, OssLicensesMenuActivity::class.java)) return true } R.id.menu_about -> { val aboutDialog = AboutDialog() aboutDialog.show(supportFragmentManager, aboutDialog.TAG) return true } } return super.onOptionsItemSelected(item) } } class AboutDialog : DialogFragment() { internal val TAG : String = "AboutDialog" override fun onCreateDialog(savedInstanceState: Bundle?): Dialog { val message : Spannable = SpannableString(getText(R.string.about_dlg_msg)) LinkifyCompat.addLinks(message, Linkify.WEB_URLS) val builder = AlertDialog.Builder(requireContext()) .setTitle(R.string.about) .setMessage(message) .setPositiveButton(android.R.string.ok, null) return builder.create() } }
gpl-3.0
d48888145bfac26be91f8fe5fd6691d4
35.915663
96
0.704865
4.697853
false
false
false
false
rjhdby/motocitizen
Motocitizen/src/motocitizen/content/accident/AccidentFactory.kt
1
873
package motocitizen.content.accident import motocitizen.dictionary.AccidentStatus import motocitizen.dictionary.Medicine import motocitizen.dictionary.Type import motocitizen.utils.getAccidentLocation import motocitizen.utils.getEnumOr import motocitizen.utils.getTimeFromSeconds import org.json.JSONObject object AccidentFactory { fun make(json: JSONObject): Accident = Accident( id = json.getInt("id"), status = json.getEnumOr("s", AccidentStatus.ACTIVE), type = json.getEnumOr("t", Type.OTHER), medicine = json.getEnumOr("m", Medicine.UNKNOWN), time = json.getTimeFromSeconds(), location = json.getAccidentLocation(), owner = json.getInt("o")) .apply { description = json.getString("d") messagesCount = json.getInt("mc") } }
mit
076f878ba0e28439485eb276fd1fac8c
35.416667
64
0.66323
4.546875
false
false
false
false
seventhroot/elysium
bukkit/rpk-crafting-skill-bukkit/src/main/kotlin/com/rpkit/craftingskill/bukkit/command/craftingskill/CraftingSkillCommand.kt
1
4333
/* * Copyright 2019 Ross Binden * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.rpkit.craftingskill.bukkit.command.craftingskill import com.rpkit.characters.bukkit.character.RPKCharacterProvider import com.rpkit.craftingskill.bukkit.RPKCraftingSkillBukkit import com.rpkit.craftingskill.bukkit.craftingskill.RPKCraftingAction import com.rpkit.craftingskill.bukkit.craftingskill.RPKCraftingSkillProvider import com.rpkit.players.bukkit.profile.RPKMinecraftProfileProvider import org.bukkit.Material import org.bukkit.command.Command import org.bukkit.command.CommandExecutor import org.bukkit.command.CommandSender import org.bukkit.entity.Player class CraftingSkillCommand(private val plugin: RPKCraftingSkillBukkit): CommandExecutor { override fun onCommand(sender: CommandSender, command: Command, label: String, args: Array<out String>): Boolean { if (sender !is Player) { sender.sendMessage(plugin.messages["not-from-console"]) return true } if (!sender.hasPermission("rpkit.craftingskill.command.craftingskill")) { sender.sendMessage(plugin.messages["no-permission-crafting-skill"]) return true } if (args.size < 2) { sender.sendMessage(plugin.messages["crafting-skill-usage"]) return true } val actionName = args[0].toUpperCase() val action = try { RPKCraftingAction.valueOf(actionName.toUpperCase()) } catch (exception: IllegalArgumentException) { sender.sendMessage(plugin.messages["crafting-skill-actions-title"]) RPKCraftingAction.values().forEach { action -> sender.sendMessage(plugin.messages["crafting-skill-actions-item", mapOf( "action" to action.name )]) } return true } val actionConfigSectionName = when (action) { RPKCraftingAction.CRAFT -> "crafting" RPKCraftingAction.SMELT -> "smelting" RPKCraftingAction.MINE -> "mining" } val material = Material.matchMaterial(args.drop(1).joinToString("_").toUpperCase()) if (material == null) { sender.sendMessage(plugin.messages["crafting-skill-invalid-material"]) return true } val minecraftProfileProvider = plugin.core.serviceManager.getServiceProvider(RPKMinecraftProfileProvider::class) val minecraftProfile = minecraftProfileProvider.getMinecraftProfile(sender) if (minecraftProfile == null) { sender.sendMessage(plugin.messages["no-minecraft-profile"]) return true } val characterProvider = plugin.core.serviceManager.getServiceProvider(RPKCharacterProvider::class) val character = characterProvider.getActiveCharacter(minecraftProfile) if (character == null) { sender.sendMessage(plugin.messages["no-character"]) return true } val craftingSkillProvider = plugin.core.serviceManager.getServiceProvider(RPKCraftingSkillProvider::class) val totalExperience = craftingSkillProvider.getCraftingExperience(character, action, material) val maxExperience = plugin.config.getConfigurationSection("$actionConfigSectionName.$material") ?.getKeys(false) ?.map(String::toInt) ?.max() ?: 0 sender.sendMessage(plugin.messages["crafting-skill-valid", mapOf( "action" to action.toString().toLowerCase(), "material" to material.toString().toLowerCase().replace('_', ' '), "total-experience" to totalExperience.toString(), "max-experience" to maxExperience.toString() )]) return true } }
apache-2.0
70bcb2a30328cdb35ea3ee2dd0cae264
44.145833
120
0.676898
5.127811
false
false
false
false
orgzly/orgzly-android
app/src/main/java/com/orgzly/android/ui/util/ActivityUtils.kt
1
5764
package com.orgzly.android.ui.util import android.app.Activity import android.app.PendingIntent import android.content.ComponentName import android.content.Context import android.content.Intent import android.content.res.Configuration import android.net.Uri import android.os.Build import android.util.DisplayMetrics import android.view.* import androidx.appcompat.app.AlertDialog import androidx.appcompat.view.menu.ActionMenuItemView import androidx.appcompat.widget.Toolbar import androidx.core.view.WindowCompat import com.google.android.material.dialog.MaterialAlertDialogBuilder import com.orgzly.BuildConfig import com.orgzly.R import com.orgzly.android.AppIntent import com.orgzly.android.prefs.AppPreferences import com.orgzly.android.ui.main.MainActivity import com.orgzly.android.util.LogUtils object ActivityUtils { private val TAG = ActivityUtils::class.java.name /** * Open "App info" settings, where permissions can be granted. */ fun openAppInfoSettings(activity: Activity) { val intent = Intent(android.provider.Settings.ACTION_APPLICATION_DETAILS_SETTINGS) intent.data = Uri.parse("package:" + BuildConfig.APPLICATION_ID) activity.startActivity(intent) } @JvmStatic fun mainActivityPendingIntent(context: Context, bookId: Long, noteId: Long): PendingIntent { if (BuildConfig.LOG_DEBUG) LogUtils.d(TAG, bookId, noteId) val intent = Intent.makeRestartActivityTask(ComponentName(context, MainActivity::class.java)) intent.putExtra(AppIntent.EXTRA_BOOK_ID, bookId) intent.putExtra(AppIntent.EXTRA_NOTE_ID, noteId) return PendingIntent.getActivity( context, noteId.toInt(), intent, immutable(PendingIntent.FLAG_UPDATE_CURRENT)) } fun keepScreenOnToggle(activity: Activity?, item: MenuItem): AlertDialog? { activity ?: return null if (!isKeepScreenOn(activity)) { return MaterialAlertDialogBuilder(activity) .setTitle(R.string.keep_screen_on) .setMessage(R.string.keep_screen_on_desc) .setPositiveButton(android.R.string.ok) { dialog, _ -> keepScreenOnSet(activity) item.isChecked = true dialog.dismiss() } .setNegativeButton(android.R.string.cancel) { dialog, _ -> dialog.dismiss() } .show() } else { keepScreenOnClear(activity) item.isChecked = false return null } } fun keepScreenOnUpdateMenuItem(activity: Activity?, menu: Menu) { val item = menu.findItem(R.id.keep_screen_on) if (activity != null && item != null) { if (AppPreferences.keepScreenOnMenuItem(activity)) { item.isChecked = isKeepScreenOn(activity) } else { menu.removeItem(item.itemId) } } } fun keepScreenOnClear(activity: Activity?) { activity?.window?.clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON) } private fun keepScreenOnSet(activity: Activity) { activity.window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON) } private fun isKeepScreenOn(activity: Activity): Boolean { val flags = activity.window.attributes.flags return flags and WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON != 0 } fun distributeToolbarItems(activity: Activity?, toolbar: Toolbar) { if (activity != null) { val display = activity.windowManager.defaultDisplay val metrics = DisplayMetrics().also { display.getMetrics(it) } val screenWidth = metrics.widthPixels for (i in 0 until toolbar.childCount) { val childView = toolbar.getChildAt(i) if (childView is ViewGroup) { val innerChildCount = childView.childCount /* * Use 1 less pixel for item width to avoid exception in tests: * Caused by: java.lang.RuntimeException: Action will not be performed because the target view does not match one or more of the following constraints: * at least 90 percent of the view's area is displayed to the user. */ val itemWidth = screenWidth / innerChildCount - 1 for (j in 0 until innerChildCount) { val grandChild = childView.getChildAt(j) if (grandChild is ActionMenuItemView) { grandChild.layoutParams.width = itemWidth } } } } } } @JvmStatic fun immutable(flags: Int): Int { return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { flags or PendingIntent.FLAG_IMMUTABLE } else { flags } } @JvmStatic fun mutable(flags: Int): Int { return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) { flags or PendingIntent.FLAG_MUTABLE } else { flags } } } /** Don't fit decor to system windows only in portrait mode when the bottom toolbar is visible. */ fun Activity.setDecorFitsSystemWindowsForBottomToolbar(visibility: Int) { val orientation = resources.configuration.orientation if (visibility == View.VISIBLE && orientation == Configuration.ORIENTATION_PORTRAIT) { WindowCompat.setDecorFitsSystemWindows(window, false) } else { WindowCompat.setDecorFitsSystemWindows(window, true) } }
gpl-3.0
cdfd544055b1663f66d359fefd0edff5
33.939394
171
0.628036
4.93916
false
false
false
false
EMResearch/EvoMaster
core/src/main/kotlin/org/evomaster/core/search/gene/regex/DisjunctionListRxGene.kt
1
7793
package org.evomaster.core.search.gene.regex import org.evomaster.core.logging.LoggingUtil import org.evomaster.core.output.OutputFormat import org.evomaster.core.search.gene.root.CompositeFixedGene import org.evomaster.core.search.gene.Gene import org.evomaster.core.search.gene.utils.GeneUtils import org.evomaster.core.search.impact.impactinfocollection.regex.DisjunctionListRxGeneImpact import org.evomaster.core.search.service.AdaptiveParameterControl import org.evomaster.core.search.service.Randomness import org.evomaster.core.search.service.mutator.MutationWeightControl import org.evomaster.core.search.service.mutator.genemutation.AdditionalGeneMutationInfo import org.evomaster.core.search.service.mutator.genemutation.SubsetGeneMutationSelectionStrategy import org.slf4j.Logger import org.slf4j.LoggerFactory class DisjunctionListRxGene( val disjunctions: List<DisjunctionRxGene> ) : RxAtom, CompositeFixedGene("disjunction_list", disjunctions) { //FIXME refactor with ChoiceGene var activeDisjunction: Int = 0 companion object{ private const val PROB_NEXT = 0.1 private val log: Logger = LoggerFactory.getLogger(DisjunctionListRxGene::class.java) } override fun isLocallyValid() : Boolean{ return activeDisjunction >= 0 && activeDisjunction < disjunctions.size && getViewOfChildren().all { it.isLocallyValid() } } override fun copyContent(): Gene { val copy = DisjunctionListRxGene(disjunctions.map { it.copy() as DisjunctionRxGene }) copy.activeDisjunction = this.activeDisjunction return copy } override fun isMutable(): Boolean { return disjunctions.size > 1 || disjunctions.any { it.isMutable() } } override fun randomize(randomness: Randomness, tryToForceNewValue: Boolean) { /* randomize content of all disjunctions (since standardMutation can be invoked on another term) */ disjunctions.forEach { it.randomize(randomness,tryToForceNewValue) } /** * randomly choose a new disjunction term */ if (disjunctions.size > 1) { log.trace("random disjunctions of DisjunctionListRxGene") activeDisjunction = randomness.nextInt(0, disjunctions.size-1) } } override fun customShouldApplyShallowMutation( randomness: Randomness, selectionStrategy: SubsetGeneMutationSelectionStrategy, enableAdaptiveGeneMutation: Boolean, additionalGeneMutationInfo: AdditionalGeneMutationInfo? ): Boolean { if(disjunctions.size > 1 && (!disjunctions[activeDisjunction].isMutable() || randomness.nextBoolean(PROB_NEXT))){ //activate the next disjunction return true } return false } override fun mutablePhenotypeChildren(): List<Gene> { return listOf(disjunctions[activeDisjunction]).filter { it.isMutable() } } override fun adaptiveSelectSubsetToMutate(randomness: Randomness, internalGenes: List<Gene>, mwc: MutationWeightControl, additionalGeneMutationInfo: AdditionalGeneMutationInfo): List<Pair<Gene, AdditionalGeneMutationInfo?>> { if (additionalGeneMutationInfo.impact == null || additionalGeneMutationInfo.impact !is DisjunctionListRxGeneImpact) throw IllegalArgumentException("mismatched gene impact") if (!disjunctions.containsAll(internalGenes)) throw IllegalArgumentException("mismatched internal genes") val impacts = internalGenes.map { additionalGeneMutationInfo.impact.disjunctions[disjunctions.indexOf(it)] } val selected = mwc.selectSubGene( candidateGenesToMutate = internalGenes, impacts = impacts, targets = additionalGeneMutationInfo.targets, forceNotEmpty = true, adaptiveWeight = true ) return selected.map { it to additionalGeneMutationInfo.copyFoInnerGene(additionalGeneMutationInfo.impact.disjunctions[disjunctions.indexOf(it)], it) }.toList() } override fun shallowMutate(randomness: Randomness, apc: AdaptiveParameterControl, mwc: MutationWeightControl, selectionStrategy: SubsetGeneMutationSelectionStrategy, enableAdaptiveGeneMutation: Boolean, additionalGeneMutationInfo: AdditionalGeneMutationInfo?): Boolean { // select another disjunction based on impact if (enableAdaptiveGeneMutation || selectionStrategy == SubsetGeneMutationSelectionStrategy.ADAPTIVE_WEIGHT){ additionalGeneMutationInfo?:throw IllegalStateException("") if (additionalGeneMutationInfo.impact != null && additionalGeneMutationInfo.impact is DisjunctionListRxGeneImpact){ val candidates = disjunctions.filterIndexed { index, _ -> index != activeDisjunction } val impacts = candidates.map { additionalGeneMutationInfo.impact.disjunctions[disjunctions.indexOf(it)] } val selected = mwc.selectSubGene( candidateGenesToMutate = candidates, impacts = impacts, targets = additionalGeneMutationInfo.targets, forceNotEmpty = true, adaptiveWeight = true ) activeDisjunction = disjunctions.indexOf(randomness.choose(selected)) return true } //throw IllegalArgumentException("mismatched gene impact") } //activate the next disjunction activeDisjunction = (activeDisjunction + 1) % disjunctions.size return true } override fun getValueAsPrintableString(previousGenes: List<Gene>, mode: GeneUtils.EscapeMode?, targetFormat: OutputFormat?, extraCheck: Boolean): String { if (disjunctions.isEmpty()) { return "" } return disjunctions[activeDisjunction] .getValueAsPrintableString(previousGenes, mode, targetFormat) } override fun copyValueFrom(other: Gene) { if (other !is DisjunctionListRxGene) { throw IllegalArgumentException("Invalid gene type ${other.javaClass}") } //TODO: Man, shall we check the size of [disjunctions] this.activeDisjunction = other.activeDisjunction for (i in 0 until disjunctions.size) { this.disjunctions[i].copyValueFrom(other.disjunctions[i]) } } override fun containsSameValueAs(other: Gene): Boolean { if (other !is DisjunctionListRxGene) { throw IllegalArgumentException("Invalid gene type ${other.javaClass}") } if (this.activeDisjunction != other.activeDisjunction) { return false } return this.disjunctions[activeDisjunction] .containsSameValueAs(other.disjunctions[activeDisjunction]) } override fun mutationWeight(): Double = disjunctions.map { it.mutationWeight() }.sum() + 1 override fun bindValueBasedOn(gene: Gene): Boolean { if (gene is DisjunctionListRxGene && gene.disjunctions.size == disjunctions.size){ var result = true disjunctions.indices.forEach { i-> val r = disjunctions[i].bindValueBasedOn(gene.disjunctions[i]) if (!r) LoggingUtil.uniqueWarn(log, "cannot bind disjunctions (name: ${disjunctions[i].name}) at index $i") result = result && r } activeDisjunction = gene.activeDisjunction return result } LoggingUtil.uniqueWarn(log, "cannot bind DisjunctionListRxGene with ${gene::class.java.simpleName}") return false } }
lgpl-3.0
9d77b104257fef795f52b689dc06e1ba
40.679144
274
0.677531
5.472612
false
false
false
false
Wackalooon/EcoMeter
app/src/main/java/com/wackalooon/ecometer/base/BaseViewModel.kt
1
1556
package com.wackalooon.ecometer.base import androidx.lifecycle.ViewModel import kotlinx.coroutines.* import kotlinx.coroutines.channels.Channel import kotlinx.coroutines.channels.ConflatedBroadcastChannel import kotlinx.coroutines.channels.ReceiveChannel import kotlinx.coroutines.channels.consumeEach import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.collect import kotlin.coroutines.CoroutineContext abstract class BaseViewModel<E : Event, U : Update, S : State>( dispatcher: Dispatcher<E, U>, initialState: S ) : ViewModel(), CoroutineScope { override val coroutineContext: CoroutineContext = SupervisorJob() + Dispatchers.IO private val events = Channel<E>(Channel.CONFLATED) private val updateFlows = Channel<Flow<U>>(Channel.UNLIMITED) private val states = ConflatedBroadcastChannel(initialState) val stateChannel: ReceiveChannel<S> get() = states.openSubscription() val currentState get() = states.value fun offerEvent(event: E) { events.offer(event) } init { launch { events.consumeEach { event -> updateFlows.send(dispatcher.dispatchEvent(event)) } } launch { updateFlows.consumeEach { updates -> updates.collect { update -> states.send(updateState(update)) } } } } protected abstract fun updateState(update: U): S override fun onCleared() { super.onCleared() coroutineContext.cancel() } }
apache-2.0
61270b22a819f2b3ca8c23d079a5fa6c
29.509804
86
0.678663
4.893082
false
false
false
false
fuzhouch/qbranch
core/src/test/kotlin/net/dummydigit/qbranch/ut/mocks/AllPrimitiveTypes.kt
1
1530
// Licensed under the MIT license. See LICENSE file in the project root // for full license information. package net.dummydigit.qbranch.ut.mocks import net.dummydigit.qbranch.* import net.dummydigit.qbranch.annotations.FieldId import net.dummydigit.qbranch.annotations.QBranchGeneratedCode import net.dummydigit.qbranch.generic.StructT import net.dummydigit.qbranch.ut.PrimitiveStruct // A mock class to test primitive types @QBranchGeneratedCode("gbc", "version.mock") open class AllPrimitiveTypes : QBranchSerializable { @FieldId(0) var fieldByte : Byte = 1 @FieldId(1) var fieldShort : Short = 2 @FieldId(2) var fieldInt : Int = 3 @FieldId(3) var fieldLong : Long = 4L @FieldId(4) var fieldUnsignedByte : UnsignedByte = UnsignedByte() @FieldId(5) var fieldUnsignedShort : UnsignedShort = UnsignedShort() @FieldId(6) var fieldUnsignedInt : UnsignedInt = UnsignedInt() @FieldId(7) var fieldUnsignedLong : UnsignedLong = UnsignedLong() @FieldId(8) var fieldByteString : ByteString = ByteString() @FieldId(9) var fieldString : String = "" companion object QTypeDef { class AllPrimitiveTypesT : StructT<AllPrimitiveTypes>() { override val baseClassT = null override fun newInstance() = AllPrimitiveTypes() private val refObj = newInstance() override fun getGenericType() = refObj.javaClass } @JvmStatic fun asQTypeArg() : AllPrimitiveTypesT { return AllPrimitiveTypesT() } } }
mit
eff22eb1dae9a6336f782a945adcc260
36.317073
72
0.70719
4.214876
false
true
false
false