repo_name
stringlengths
7
81
path
stringlengths
6
242
copies
stringclasses
53 values
size
stringlengths
2
6
content
stringlengths
73
737k
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
5.44
99.8
line_max
int64
15
977
alpha_frac
float64
0.3
0.91
ratio
float64
2
9.93
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
rock3r/detekt
detekt-core/src/main/kotlin/io/gitlab/arturbosch/detekt/core/processors/ProjectLOCProcessor.kt
1
565
package io.gitlab.arturbosch.detekt.core.processors import io.gitlab.arturbosch.detekt.api.DetektVisitor import org.jetbrains.kotlin.com.intellij.openapi.util.Key import org.jetbrains.kotlin.psi.KtFile class ProjectLOCProcessor : AbstractProcessor() { override val visitor: DetektVisitor = LOCVisitor() override val key = linesKey } class LOCVisitor : DetektVisitor() { override fun visitKtFile(file: KtFile) { val lines = file.text.count { it == '\n' } + 1 file.putUserData(linesKey, lines) } } val linesKey = Key<Int>("loc")
apache-2.0
dc9b50233f7c0f7a72b81713dd559eae
25.904762
57
0.725664
3.791946
false
false
false
false
openMF/self-service-app
app/src/main/java/org/mifos/mobile/models/client/DepositType.kt
1
1370
package org.mifos.mobile.models.client import android.os.Parcelable import com.google.gson.annotations.SerializedName import kotlinx.android.parcel.Parcelize import org.mifos.mobile.api.ApiEndPoints @Parcelize data class DepositType( @SerializedName("id") var id: Int? = null, @SerializedName("code") var code: String, @SerializedName("value") var value: String ) : Parcelable { fun isRecurring(): Boolean { return ServerTypes.RECURRING.id == this.id } fun endpoint(): String { return ServerTypes.fromId(id!!).endpoint } fun serverType(): ServerTypes { return ServerTypes.fromId(id!!) } enum class ServerTypes constructor(val id: Int?, val code: String, val endpoint: String) { SAVINGS(100, "depositAccountType.savingsDeposit", ApiEndPoints.SAVINGS_ACCOUNTS), FIXED(200, "depositAccountType.fixedDeposit", ApiEndPoints.SAVINGS_ACCOUNTS), RECURRING(300, "depositAccountType.recurringDeposit", ApiEndPoints.RECURRING_ACCOUNTS); companion object { fun fromId(id: Int): ServerTypes { for (type in ServerTypes.values()) { if (type.id == id) { return type } } return SAVINGS } } } }
mpl-2.0
fe41bd6d12007e7cfaf3ce2f42c8fcd7
24.867925
95
0.608759
4.644068
false
false
false
false
world-federation-of-advertisers/cross-media-measurement
src/test/kotlin/org/wfanet/measurement/kingdom/service/api/v2alpha/RecurringExchangesServiceTest.kt
1
2123
// Copyright 2021 The Cross-Media Measurement Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // 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.wfanet.measurement.kingdom.service.api.v2alpha import kotlin.test.assertFailsWith import kotlinx.coroutines.runBlocking import org.junit.Test import org.junit.runner.RunWith import org.junit.runners.JUnit4 import org.wfanet.measurement.api.v2alpha.CreateRecurringExchangeRequest import org.wfanet.measurement.api.v2alpha.GetRecurringExchangeRequest import org.wfanet.measurement.api.v2alpha.ListRecurringExchangesRequest import org.wfanet.measurement.api.v2alpha.RetireRecurringExchangeRequest @RunWith(JUnit4::class) class RecurringExchangesServiceTest { val service = RecurringExchangesService() @Test fun createRecurringExchange() = runBlocking<Unit> { assertFailsWith(NotImplementedError::class) { service.createRecurringExchange(CreateRecurringExchangeRequest.getDefaultInstance()) } } @Test fun getRecurringExchange() = runBlocking<Unit> { assertFailsWith(NotImplementedError::class) { service.getRecurringExchange(GetRecurringExchangeRequest.getDefaultInstance()) } } @Test fun listRecurringExchanges() = runBlocking<Unit> { assertFailsWith(NotImplementedError::class) { service.listRecurringExchanges(ListRecurringExchangesRequest.getDefaultInstance()) } } @Test fun retireRecurringExchange() = runBlocking<Unit> { assertFailsWith(NotImplementedError::class) { service.retireRecurringExchange(RetireRecurringExchangeRequest.getDefaultInstance()) } } }
apache-2.0
cdd667881b479c11a0483cdc44e6f855
32.698413
92
0.768252
4.76009
false
true
false
false
RoverPlatform/rover-android
location/src/main/kotlin/io/rover/sdk/location/LocationAssembler.kt
1
15442
@file:JvmName("Location") package io.rover.sdk.location import android.content.Context import android.database.sqlite.SQLiteDatabase import android.database.sqlite.SQLiteOpenHelper import android.location.Geocoder import com.google.android.gms.location.FusedLocationProviderClient import com.google.android.gms.location.GeofencingClient import com.google.android.gms.location.LocationServices import com.google.android.gms.nearby.Nearby import com.google.android.gms.nearby.messages.MessagesClient import io.rover.sdk.core.Rover import io.rover.sdk.core.container.Assembler import io.rover.sdk.core.container.Container import io.rover.sdk.core.container.Resolver import io.rover.sdk.core.container.Scope import io.rover.sdk.core.data.sync.CursorState import io.rover.sdk.core.data.sync.RealPagedSyncParticipant import io.rover.sdk.core.data.sync.SyncCoordinatorInterface import io.rover.sdk.core.data.sync.SyncParticipant import io.rover.sdk.core.events.ContextProvider import io.rover.sdk.core.events.EventQueueServiceInterface import io.rover.sdk.core.permissions.PermissionsNotifierInterface import io.rover.sdk.core.platform.DateFormattingInterface import io.rover.sdk.core.platform.LocalStorage import io.rover.sdk.core.streams.Scheduler import io.rover.sdk.location.events.contextproviders.LocationContextProvider import io.rover.sdk.location.sync.BeaconSyncDecoder import io.rover.sdk.location.sync.BeaconsRepository import io.rover.sdk.location.sync.BeaconsSqlStorage import io.rover.sdk.location.sync.BeaconsSyncResource import io.rover.sdk.location.sync.GeofenceSyncDecoder import io.rover.sdk.location.sync.GeofencesRepository import io.rover.sdk.location.sync.GeofencesSqlStorage import io.rover.sdk.location.sync.GeofencesSyncResource import io.rover.sdk.location.sync.LocationDatabase /** * Location Assembler contains the Rover SDK subsystems for Geofence, Beacon, and location tracking. * * It can automatically use the Google Location services, which you can opt out of by passing false * to the following boolean parameters. You may wish to do this if you want to use a Location SDK * from a vendor other than Google, integrate with your own location implementation, or do not * require the functionality. * * Note: if you use any of the below, then you must complete the Google Play Services setup as per * the SDK documentation (also needed for the Notifications module). */ class LocationAssembler( /** * Automatically use the Google Location Geofence API to monitor for geofence events. * * Note: because of a fixed limit of geofences that may be monitored with the Google Geofence * API, this may introduce conflicts with your own code. In that case, see below. * * Set to false if you do not want Rover to provide this functionality, or if you prefer to * manage the Geofences yourself (see [GoogleGeofenceService]). */ private val automaticGeofenceMonitoring: Boolean = true, /** * Automatically use the Google Nearby Messages API to monitor for Beacons. * * This should not conflict with your own use of Nearby Messages API, so you can leave * [automaticBeaconMonitoring] true even if you are using Google Nearby for your own beacons or * messages. * * Set to false if you do not want Rover to provide this functionality, or if you still prefer * to manage the Beacons yourself (see [GoogleBeaconTrackerService]). */ private val automaticBeaconMonitoring: Boolean = true, /** * Automatically use the Google Location [FusedLocationProviderClient] to track the device and * user's location in the background. This will make more accurate location information * available about your users in the Rover Audience app. * * Note that if you enable either [automaticGeofenceMonitoring] or [automaticBeaconMonitoring] * that the Google Fused Location Provider API will still be used, although location reporting * itself will be disabled as requested. * * This should not conflict with your own use of the Google Fused Location Provider API. * * Set to false if you do not want Rover to provide this functionality, or if you still prefer * to manage the fused location manager yourself. */ private val automaticLocationTracking: Boolean = true ) : Assembler { override fun assemble(container: Container) { container.register( Scope.Singleton, LocationReportingServiceInterface::class.java ) { resolver -> LocationReportingService( resolver.resolveSingletonOrFail(EventQueueServiceInterface::class.java) ) } container.register( Scope.Singleton, SQLiteOpenHelper::class.java, "location" ) { resolver -> LocationDatabase( resolver.resolveSingletonOrFail(Context::class.java), resolver.resolveSingletonOrFail(LocalStorage::class.java) ) } container.register( Scope.Singleton, SQLiteDatabase::class.java, "location" ) { resolver -> resolver.resolveSingletonOrFail(SQLiteOpenHelper::class.java, "location").writableDatabase } container.register( Scope.Singleton, GeofencesSqlStorage::class.java ) { resolver -> GeofencesSqlStorage( resolver.resolveSingletonOrFail( SQLiteDatabase::class.java, "location" ) ) } container.register( Scope.Singleton, Geocoder::class.java ) { resolver -> Geocoder(resolver.resolveSingletonOrFail(Context::class.java)) } container.register( Scope.Singleton, SyncParticipant::class.java, "geofences" ) { resolver -> RealPagedSyncParticipant( GeofencesSyncResource( resolver.resolveSingletonOrFail(GeofencesSqlStorage::class.java) ), GeofenceSyncDecoder(), "io.rover.location.geofencesCursor", resolver.resolveSingletonOrFail(SQLiteOpenHelper::class.java, "location") as CursorState ) } container.register( Scope.Singleton, GeofencesRepository::class.java ) { resolver -> GeofencesRepository( resolver.resolveSingletonOrFail(SyncCoordinatorInterface::class.java), resolver.resolveSingletonOrFail(GeofencesSqlStorage::class.java), resolver.resolveSingletonOrFail(Scheduler::class.java, "io") ) } container.register( Scope.Singleton, BeaconsSqlStorage::class.java ) { resolver -> BeaconsSqlStorage( resolver.resolveSingletonOrFail( SQLiteDatabase::class.java, "location" ) ) } container.register( Scope.Singleton, SyncParticipant::class.java, "beacons" ) { resolver -> RealPagedSyncParticipant( BeaconsSyncResource( resolver.resolveSingletonOrFail(BeaconsSqlStorage::class.java) ), BeaconSyncDecoder(), "io.rover.location.beaconsCursor", resolver.resolveSingletonOrFail(SQLiteOpenHelper::class.java, "location") as CursorState ) } container.register( Scope.Singleton, BeaconsRepository::class.java ) { resolver -> BeaconsRepository( resolver.resolveSingletonOrFail(SyncCoordinatorInterface::class.java), resolver.resolveSingletonOrFail(BeaconsSqlStorage::class.java), resolver.resolveSingletonOrFail(Scheduler::class.java, "io") ) } container.register( Scope.Singleton, ContextProvider::class.java, "location" ) { resolver -> LocationContextProvider( resolver.resolveSingletonOrFail(GoogleBackgroundLocationServiceInterface::class.java) ) } // if automatic location/region tracking, then register our Google-powered services: if (automaticLocationTracking) { container.register( Scope.Singleton, FusedLocationProviderClient::class.java ) { resolver -> LocationServices.getFusedLocationProviderClient( resolver.resolveSingletonOrFail(Context::class.java) ) } container.register( Scope.Singleton, GoogleBackgroundLocationServiceInterface::class.java ) { resolver -> GoogleBackgroundLocationService( resolver.resolveSingletonOrFail( FusedLocationProviderClient::class.java ), resolver.resolveSingletonOrFail(Context::class.java), resolver.resolveSingletonOrFail(PermissionsNotifierInterface::class.java), resolver.resolveSingletonOrFail(LocationReportingServiceInterface::class.java), resolver.resolveSingletonOrFail(Geocoder::class.java), resolver.resolveSingletonOrFail(Scheduler::class.java, "io"), resolver.resolveSingletonOrFail(Scheduler::class.java, "main"), automaticLocationTracking, resolver.resolveSingletonOrFail(LocalStorage::class.java), resolver.resolveSingletonOrFail(DateFormattingInterface::class.java) ) } } if (automaticGeofenceMonitoring) { container.register( Scope.Singleton, GeofencingClient::class.java ) { resolver -> LocationServices.getGeofencingClient( resolver.resolveSingletonOrFail(Context::class.java) ) } container.register( Scope.Singleton, GoogleGeofenceServiceInterface::class.java ) { resolver -> GoogleGeofenceService( resolver.resolveSingletonOrFail(Context::class.java), resolver.resolveSingletonOrFail(LocalStorage::class.java), resolver.resolveSingletonOrFail(GeofencingClient::class.java), resolver.resolveSingletonOrFail(Scheduler::class.java, "main"), resolver.resolveSingletonOrFail(Scheduler::class.java, "io"), resolver.resolveSingletonOrFail( LocationReportingServiceInterface::class.java ), resolver.resolveSingletonOrFail(PermissionsNotifierInterface::class.java), resolver.resolveSingletonOrFail(GeofencesRepository::class.java), resolver.resolveSingletonOrFail(GoogleBackgroundLocationServiceInterface::class.java) ) } container.register( Scope.Singleton, GeofenceServiceInterface::class.java ) { resolver -> resolver.resolveSingletonOrFail(GoogleGeofenceServiceInterface::class.java) } } if (automaticBeaconMonitoring) { container.register( Scope.Singleton, MessagesClient::class.java ) { resolver -> Nearby.getMessagesClient(resolver.resolveSingletonOrFail(Context::class.java)) } container.register( Scope.Singleton, GoogleBeaconTrackerServiceInterface::class.java ) { resolver -> GoogleBeaconTrackerService( resolver.resolveSingletonOrFail(Context::class.java), resolver.resolveSingletonOrFail(MessagesClient::class.java), resolver.resolveSingletonOrFail(BeaconsRepository::class.java), resolver.resolveSingletonOrFail(Scheduler::class.java, "main"), resolver.resolveSingletonOrFail(Scheduler::class.java, "io"), resolver.resolveSingletonOrFail( LocationReportingServiceInterface::class.java ), resolver.resolveSingletonOrFail(PermissionsNotifierInterface::class.java) ) } } } override fun afterAssembly(resolver: Resolver) { if (automaticLocationTracking || automaticBeaconMonitoring || automaticGeofenceMonitoring) { // greedily poke for GoogleBackgroundLocationService to force the DI to evaluate // it and therefore have it start monitoring. resolver.resolveSingletonOrFail(GoogleBackgroundLocationServiceInterface::class.java) } if (automaticGeofenceMonitoring) { resolver.resolveSingletonOrFail( SyncCoordinatorInterface::class.java ).registerParticipant( resolver.resolveSingletonOrFail( SyncParticipant::class.java, "geofences" ) ) resolver.resolveSingletonOrFail(GoogleGeofenceServiceInterface::class.java) } if (automaticBeaconMonitoring) { resolver.resolveSingletonOrFail( SyncCoordinatorInterface::class.java ).registerParticipant( resolver.resolveSingletonOrFail( SyncParticipant::class.java, "beacons" ) ) resolver.resolveSingletonOrFail(GoogleBeaconTrackerServiceInterface::class.java) } if (automaticLocationTracking) { resolver.resolveSingletonOrFail(EventQueueServiceInterface::class.java).addContextProvider( resolver.resolveSingletonOrFail(ContextProvider::class.java, "location") ) } } } @Deprecated("Use .resolve(GoogleBackgroundLocationServiceInterface::class.java)") val Rover.googleBackgroundLocationService: GoogleBackgroundLocationServiceInterface get() = this.resolve(GoogleBackgroundLocationServiceInterface::class.java) ?: throw missingDependencyError("GoogleBackgroundLocationServiceInterface") @Deprecated("Use .resolve(GoogleBeaconTrackerServiceInterface::class.java)") val Rover.googleBeaconTrackerService: GoogleBeaconTrackerServiceInterface get() = this.resolve(GoogleBeaconTrackerServiceInterface::class.java) ?: throw missingDependencyError("GoogleBeaconTrackerServiceInterface") @Deprecated("Use .resolve(GoogleGeofenceServiceInterface::class.java)") val Rover.googleGeofenceService: GoogleGeofenceServiceInterface get() = this.resolve(GoogleGeofenceServiceInterface::class.java) ?: throw missingDependencyError("GoogleGeofenceServiceInterface") private fun missingDependencyError(name: String): Throwable { throw RuntimeException("Dependency not registered: $name. Did you include LocationAssembler() in the assembler list?") }
apache-2.0
1a6e9dcc1afbd0f8abdfaa1e0c7f5a81
41.657459
154
0.649009
5.818387
false
false
false
false
Dimigo-AppClass-Mission/SaveTheEarth
app/src/main/kotlin/me/hyemdooly/sangs/dimigo/app/project/fragment/StatsFragment.kt
1
6017
package me.hyemdooly.sangs.dimigo.app.project.fragment import android.annotation.SuppressLint import android.content.Context import android.content.SharedPreferences import android.graphics.Color import android.os.Bundle import android.support.v4.app.Fragment import android.support.v7.widget.AppCompatSpinner import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ArrayAdapter import android.widget.TextView import lecho.lib.hellocharts.view.LineChartView import me.hyemdooly.sangs.dimigo.app.project.R import lecho.lib.hellocharts.model.* import me.hyemdooly.sangs.dimigo.app.project.database.DataController class StatsFragment : Fragment() { private var rootView: View? = null private var dateFilter: AppCompatSpinner? = null private var timeUsedFilter: AppCompatSpinner? = null private var chart: LineChartView? = null private var usedTimeText: TextView? = null private var unusedTimeText: TextView? = null private var dateFilterListObj: ArrayList<String> = ArrayList() private var timeUsedFilterListObj: ArrayList<String> = ArrayList() private var dataController: DataController? = null private var user: SharedPreferences? = null override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? { rootView = inflater!!.inflate(R.layout.fragment_stats, null, false) dataController = DataController(activity) user = context.getSharedPreferences("User", Context.MODE_PRIVATE) dateFilter = rootView!!.findViewById(R.id.stats_fragment_time_filter) timeUsedFilter = rootView!!.findViewById(R.id.stats_fragment_usedtime_filter) chart = rootView!!.findViewById(R.id.stats_fragment_chart) usedTimeText = rootView!!.findViewById(R.id.stats_fragment_used_time_text) unusedTimeText = rootView!!.findViewById(R.id.stats_fragment_unused_time_text) val dateFilterAdapter = ArrayAdapter<String>(activity, R.layout.item_spinner, dateFilterListObj) val timeUsedFilterAdapter = ArrayAdapter<String>(activity, R.layout.item_spinner, timeUsedFilterListObj) initDateFilter() initTimeUsedFilter() dateFilter!!.adapter = dateFilterAdapter timeUsedFilter!!.adapter = timeUsedFilterAdapter initChart() loadTimeStats() return rootView!! } private fun initDateFilter() { dateFilterListObj.add("์˜ค๋Š˜") dateFilterListObj.add("8์›” 26์ผ") dateFilterListObj.add("8์›” 25์ผ") dateFilterListObj.add("8์›” 24์ผ") } private fun initTimeUsedFilter() { timeUsedFilterListObj.add("์‚ฌ์šฉํ•œ ์‹œ๊ฐ„") timeUsedFilterListObj.add("์‚ฌ์šฉ์•ˆํ•œ ์‹œ๊ฐ„") } private fun initChart() { val axisXValue = ArrayList<AxisValue>() axisXValue.add(AxisValue(1.toFloat()).setLabel("7์‹œ")) axisXValue.add(AxisValue(2.toFloat()).setLabel("10์‹œ")) axisXValue.add(AxisValue(3.toFloat()).setLabel("13์‹œ")) axisXValue.add(AxisValue(4.toFloat()).setLabel("16์‹œ")) axisXValue.add(AxisValue(5.toFloat()).setLabel("19์‹œ")) axisXValue.add(AxisValue(6.toFloat()).setLabel("22์‹œ")) axisXValue.add(AxisValue(7.toFloat()).setLabel("~7์‹œ")) axisXValue.add(AxisValue(8.toFloat()).setLabel("")) val axisXTopValue = ArrayList<AxisValue>() axisXTopValue.add(AxisValue(1.toFloat()).setLabel("0๋ถ„")) axisXTopValue.add(AxisValue(2.toFloat()).setLabel("27๋ถ„")) axisXTopValue.add(AxisValue(3.toFloat()).setLabel("43๋ถ„")) axisXTopValue.add(AxisValue(4.toFloat()).setLabel("47๋ถ„")) axisXTopValue.add(AxisValue(5.toFloat()).setLabel("31๋ถ„")) axisXTopValue.add(AxisValue(6.toFloat()).setLabel("34๋ถ„")) axisXTopValue.add(AxisValue(7.toFloat()).setLabel("37๋ถ„")) axisXTopValue.add(AxisValue(8.toFloat()).setLabel("")) val values = ArrayList<PointValue>() values.add(PointValue(0f, 0f)) values.add(PointValue(1f, 8f)) values.add(PointValue(2f, 27f)) values.add(PointValue(3f, 43f)) values.add(PointValue(4f, 47f)) values.add(PointValue(5f, 31f)) values.add(PointValue(6f, 34f)) values.add(PointValue(7f, 37f)) values.add(PointValue(8f, 50f)) val compareValues = ArrayList<PointValue>() compareValues.add(PointValue(0f, 0f)) compareValues.add(PointValue(1f, 4f)) compareValues.add(PointValue(2f, 13.5f)) compareValues.add(PointValue(3f, 21.5f)) compareValues.add(PointValue(4f, 23.5f)) compareValues.add(PointValue(5f, 15.5f)) compareValues.add(PointValue(6f, 17f)) compareValues.add(PointValue(7f, 18.5f)) compareValues.add(PointValue(8f, 25f)) val line = Line(values).setColor(Color.parseColor("#29C9BD")).setCubic(true).setHasLabelsOnlyForSelected(true).setStrokeWidth(2).setPointRadius(4) val line2 = Line(compareValues).setColor(Color.parseColor("#C0C9CF")).setCubic(true).setHasLabelsOnlyForSelected(true).setStrokeWidth(1).setPointRadius(2) val lines = ArrayList<Line>() lines.add(line) lines.add(line2) val data = LineChartData() data.lines = lines data.axisXBottom = Axis(axisXValue).setHasLines(true).setLineColor(Color.parseColor("#4029C9BD")).setTextColor(Color.parseColor("#29C9BD")) data.axisXTop = Axis(axisXTopValue).setHasLines(false).setTextColor(Color.parseColor("#29C9BD")) chart!!.isZoomEnabled = false chart!!.isInteractive = true chart!!.lineChartData = data } @SuppressLint("SetTextI18n") private fun loadTimeStats() { val usedTime = user!!.getLong("UnTotalTime", 0).toString() val unusedTime = user!!.getLong("TotalTime", 0).div(60).toString() usedTimeText!!.text = usedTime + "๋ถ„" unusedTimeText!!.text = unusedTime + "๋ถ„" } }
gpl-3.0
8cd666a33b97b614276b35404229bdf0
41.485714
162
0.694131
4.141365
false
false
false
false
Vlad-Popa/Filtrin
src/main/java/application/TableMenu.kt
1
3077
/* * Copyright (C) 2015 Vlad Popa * * 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 application import javafx.scene.control.ContextMenu import javafx.scene.control.MenuItem import javafx.scene.control.TableView import javafx.stage.FileChooser import javafx.stage.Stage import org.apache.poi.xssf.usermodel.XSSFWorkbook import org.controlsfx.control.Notifications import java.io.File import java.io.FileOutputStream import java.io.IOException /** * @author Vlad Popa on 9/5/2015. */ class TableMenu : ContextMenu() { private var tableView: TableView<Model>? = null init { val remove = MenuItem("Remove") val export = MenuItem("Export") val normalize = MenuItem("Normalize .pdb") this.items.addAll(remove, export, normalize) remove.setOnAction { event -> val items = tableView!!.selectionModel.selectedItems tableView!!.items.removeAll(items) } val initialDirectory = File(System.getProperty("user.home") + "/Desktop") val extensionFilter: FileChooser.ExtensionFilter extensionFilter = FileChooser.ExtensionFilter("Excel (*.xlsx)", "*.xlsx") val fileChooser = FileChooser() fileChooser.title = "Export As..." fileChooser.initialDirectory = initialDirectory fileChooser.initialFileName = "untitled" fileChooser.extensionFilters.addAll(extensionFilter) export.setOnAction { val file = fileChooser.showSaveDialog(Stage()) if (file != null) { try { FileOutputStream(file).use { fos -> val book = XSSFWorkbook() for (model in tableView!!.selectionModel.selectedItems) { val path = model.file val sheet = book.createSheet(model.name) sheet.createRow(0) val key = model.key } book.write(fos) Notifications.create().title("Export Complete").text("The file was successfully written").showConfirm() } } catch (e: IOException) { Notifications.create().title("Export Failed").text("The file was not successfully written").showConfirm() e.printStackTrace() } } } } fun setTableView(tableView: TableView<Model>) { this.tableView = tableView this.tableView!!.contextMenu = this } }
apache-2.0
65fc0db0734e4a4965c50aa663d9bff1
35.630952
127
0.621059
4.915335
false
false
false
false
clangen/musikcube
src/musikdroid/app/src/main/java/io/casey/musikcube/remote/ui/shared/fragment/TransportFragment.kt
1
9100
package io.casey.musikcube.remote.ui.shared.fragment import android.os.Bundle import android.view.LayoutInflater import android.view.MotionEvent import android.view.View import android.view.ViewGroup import android.widget.TextView import io.casey.musikcube.remote.R import io.casey.musikcube.remote.service.playback.PlaybackState import io.casey.musikcube.remote.ui.home.activity.MainActivity import io.casey.musikcube.remote.ui.navigation.Navigate import io.casey.musikcube.remote.ui.playqueue.fragment.PlayQueueFragment import io.casey.musikcube.remote.ui.shared.extension.dpToPx import io.casey.musikcube.remote.ui.shared.extension.fallback import io.casey.musikcube.remote.ui.shared.extension.getColorCompat import io.casey.musikcube.remote.ui.shared.extension.topOfStack import io.casey.musikcube.remote.ui.shared.mixin.PlaybackMixin import io.casey.musikcube.remote.ui.shared.view.InterceptTouchFrameLayout import me.zhanghai.android.materialprogressbar.MaterialProgressBar import kotlin.math.abs class TransportFragment: BaseFragment() { private lateinit var rootView: View private lateinit var buffering: View private lateinit var title: TextView private lateinit var playPause: TextView private lateinit var progress: MaterialProgressBar private val seekTracker = TouchTracker() private var seekOverride = -1 lateinit var playback: PlaybackMixin private set var modelChangedListener: ((TransportFragment) -> Unit)? = null override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View { this.rootView = inflater.inflate(R.layout.transport_fragment, container, false) progress = this.rootView.findViewById(R.id.progress) bindEventHandlers() rebindUi() return this.rootView } override fun onCreate(savedInstanceState: Bundle?) { playback = mixin(PlaybackMixin(playbackListener)) super.onCreate(savedInstanceState) } override fun onResume() { super.onResume() rebindUi() scheduleUpdateTime() } override fun onPause() { super.onPause() handler.removeCallbacks(updateTimeRunnable) } private fun bindEventHandlers() { this.title = this.rootView.findViewById(R.id.track_title) this.title.isClickable = false this.title.isFocusable = false this.buffering = this.rootView.findViewById(R.id.buffering) val titleBar = this.rootView.findViewById<InterceptTouchFrameLayout>(R.id.title_bar) titleBar?.setOnClickListener { if (!seekTracker.processed && playback.service.state != PlaybackState.Stopped) { appCompatActivity.supportFragmentManager.run { when (topOfStack != PlayQueueFragment.TAG) { true -> Navigate.toPlayQueue( playback.service.queuePosition, appCompatActivity, this@TransportFragment) false -> this.popBackStack() } } } } titleBar?.setOnLongClickListener { if (!seekTracker.processed) { activity?.let { a -> startActivity(MainActivity.getStartIntent(a)) return@setOnLongClickListener true } } false } titleBar?.setOnInterceptTouchEventListener(object: InterceptTouchFrameLayout.OnInterceptTouchEventListener { override fun onInterceptTouchEvent(view: InterceptTouchFrameLayout, event: MotionEvent, disallowIntercept: Boolean): Boolean { return when (event.action) { MotionEvent.ACTION_DOWN, MotionEvent.ACTION_MOVE, MotionEvent.ACTION_CANCEL, MotionEvent.ACTION_UP -> true else -> false } } override fun onTouchEvent(view: InterceptTouchFrameLayout, event: MotionEvent): Boolean { seekTracker.update(event) if (seekTracker.processed) { when (event.action) { MotionEvent.ACTION_MOVE -> { seekOverride = ( seekTracker.lastX.toFloat() / view.width.toFloat() * playback.service.duration.toFloat()).toInt() rebindProgress() } MotionEvent.ACTION_UP -> { if (seekOverride >= 0) { playback.service.seekTo(seekOverride.toDouble()) seekOverride = -1 } } } } view.defaultOnTouchEvent(event) return true } }) this.rootView.findViewById<View>(R.id.button_prev)?.setOnClickListener { playback.service.prev() } this.playPause = this.rootView.findViewById(R.id.button_play_pause) this.playPause.setOnClickListener { if (playback.service.state == PlaybackState.Stopped) { playback.service.playAll() } else { playback.service.pauseOrResume() } } this.rootView.findViewById<View>(R.id.button_next)?.setOnClickListener { playback.service.next() } } private fun rebindProgress() { if (playback.service.state == PlaybackState.Stopped) { progress.progress = 0 progress.secondaryProgress = 0 } else { val buffered = playback.service.bufferedTime.toInt() val total = playback.service.duration.toInt() progress.max = total progress.secondaryProgress = if (buffered >= total) 0 else buffered progress.progress = if (seekTracker.down && seekOverride >= 0) { seekOverride } else { playback.service.currentTime.toInt() } } } private fun rebindUi() { val state = playback.service.state val playing = state == PlaybackState.Playing val buffering = state == PlaybackState.Buffering this.playPause.setText(if (playing || buffering) R.string.button_pause else R.string.button_play) this.buffering.visibility = if (buffering) View.VISIBLE else View.GONE if (state == PlaybackState.Stopped) { title.setTextColor(getColorCompat(R.color.theme_disabled_foreground)) title.setText(R.string.transport_not_playing) } else { val defaultValue = getString(if (buffering) R.string.buffering else R.string.unknown_title) title.text = fallback(playback.service.playingTrack.title, defaultValue) title.setTextColor(getColorCompat(R.color.theme_green)) } rebindProgress() } private fun scheduleUpdateTime() { handler.removeCallbacks(updateTimeRunnable) handler.postDelayed(updateTimeRunnable, 1000L) } private val updateTimeRunnable = Runnable { rebindProgress() scheduleUpdateTime() } private val playbackListener: () -> Unit = { rebindUi() modelChangedListener?.invoke(this@TransportFragment) } private class TouchTracker { var down = false var startX = 0 var startY = 0 var totalDx = 0 var totalDy = 0 var lastX = 0 var lastY = 0 fun reset() { down = false startX = 0 startY = 0 totalDx = 0 totalDy = 0 lastX = 0 lastY = 0 } fun update(ev: MotionEvent) { when (ev.action) { MotionEvent.ACTION_DOWN -> { reset() down = true startX = ev.x.toInt() startY = ev.y.toInt() lastX = startX lastY = startY } MotionEvent.ACTION_MOVE -> { val x = ev.x.toInt() val y = ev.y.toInt() totalDx += abs(lastX - x) totalDy += abs(lastY - y) lastX = x lastY = y } MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> { down = false } } } val processed: Boolean get() { return totalDx >= dpToPx(SEEK_SLOP_PX) } } companion object { const val TAG = "TransportFragment" private const val SEEK_SLOP_PX = 16 fun create(): TransportFragment = TransportFragment() } }
bsd-3-clause
a275e5a8c288202f50df1d5fae629e34
33.210526
138
0.569231
5.281486
false
false
false
false
tasks/tasks
app/src/main/java/org/tasks/caldav/CaldavCalendarSettingsActivity.kt
1
5925
package org.tasks.caldav import android.os.Bundle import androidx.activity.viewModels import androidx.compose.material.FloatingActionButton import androidx.compose.material.Icon import androidx.compose.material.MaterialTheme import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.ui.platform.ComposeView import androidx.compose.ui.res.painterResource import androidx.core.view.isVisible import androidx.lifecycle.lifecycleScope import com.google.android.material.composethemeadapter.MdcTheme import dagger.hilt.android.AndroidEntryPoint import kotlinx.coroutines.launch import org.tasks.R import org.tasks.compose.ListSettingsComposables.PrincipalList import org.tasks.compose.ShareInvite.ShareInviteDialog import org.tasks.data.CaldavAccount import org.tasks.data.CaldavAccount.Companion.SERVER_NEXTCLOUD import org.tasks.data.CaldavAccount.Companion.SERVER_OWNCLOUD import org.tasks.data.CaldavAccount.Companion.SERVER_SABREDAV import org.tasks.data.CaldavAccount.Companion.SERVER_TASKS import org.tasks.data.CaldavCalendar import org.tasks.data.CaldavCalendar.Companion.ACCESS_OWNER import org.tasks.data.PrincipalDao import org.tasks.data.PrincipalWithAccess import javax.inject.Inject @AndroidEntryPoint class CaldavCalendarSettingsActivity : BaseCaldavCalendarSettingsActivity() { @Inject lateinit var principalDao: PrincipalDao private val viewModel: CaldavCalendarViewModel by viewModels() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) viewModel.inFlight.observe(this) { progressView.isVisible = it } viewModel.error.observe(this) { throwable -> throwable?.let { requestFailed(it) viewModel.error.value = null } } viewModel.finish.observe(this) { setResult(RESULT_OK, it) finish() } caldavCalendar?.takeIf { it.id > 0 }?.let { principalDao.getPrincipals(it.id).observe(this) { findViewById<ComposeView>(R.id.people) .apply { isVisible = it.isNotEmpty() } .setContent { MdcTheme { PrincipalList(it, if (canRemovePrincipals) this::onRemove else null) } } } } if (caldavAccount.canShare && (isNew || caldavCalendar?.access == ACCESS_OWNER)) { findViewById<ComposeView>(R.id.fab) .apply { isVisible = true } .setContent { MdcTheme { val openDialog = rememberSaveable { mutableStateOf(false) } ShareInviteDialog( openDialog, email = caldavAccount.serverType != SERVER_OWNCLOUD ) { input -> lifecycleScope.launch { share(input) openDialog.value = false } } FloatingActionButton(onClick = { openDialog.value = true }) { Icon( painter = painterResource(R.drawable.ic_outline_person_add_24), contentDescription = null, tint = MaterialTheme.colors.onPrimary, ) } } } } } private val canRemovePrincipals: Boolean get() = caldavCalendar?.access == ACCESS_OWNER && caldavAccount.canRemovePrincipal private fun onRemove(principal: PrincipalWithAccess) { if (requestInProgress()) { return } dialogBuilder .newDialog(R.string.remove_user) .setMessage(R.string.remove_user_confirmation, principal.name, caldavCalendar?.name) .setNegativeButton(R.string.cancel, null) .setPositiveButton(R.string.ok) { _, _ -> removePrincipal(principal) } .show() } private fun removePrincipal(principal: PrincipalWithAccess) = lifecycleScope.launch { try { viewModel.removeUser(caldavAccount, caldavCalendar!!, principal) } catch (e: Exception) { requestFailed(e) } } override suspend fun createCalendar(caldavAccount: CaldavAccount, name: String, color: Int) { caldavCalendar = viewModel.createCalendar(caldavAccount, name, color, selectedIcon) } override suspend fun updateNameAndColor( account: CaldavAccount, calendar: CaldavCalendar, name: String, color: Int ) { viewModel.updateCalendar(account, calendar, name, color, selectedIcon) } override suspend fun deleteCalendar( caldavAccount: CaldavAccount, caldavCalendar: CaldavCalendar ) { viewModel.deleteCalendar(caldavAccount, caldavCalendar) } private suspend fun share(email: String) { if (isNew) { viewModel.ignoreFinish = true try { save() } finally { viewModel.ignoreFinish = false } } caldavCalendar?.let { viewModel.addUser(caldavAccount, it, email) } } companion object { val CaldavAccount.canRemovePrincipal: Boolean get() = when (serverType) { SERVER_TASKS, SERVER_OWNCLOUD, SERVER_SABREDAV, SERVER_NEXTCLOUD -> true else -> false } val CaldavAccount.canShare: Boolean get() = when (serverType) { SERVER_TASKS, SERVER_OWNCLOUD, SERVER_SABREDAV, SERVER_NEXTCLOUD -> true else -> false } } }
gpl-3.0
6102c263bd57500e9c218f56c8de455d
36.27044
97
0.604388
5.313901
false
false
false
false
dafi/photoshelf
core/src/main/java/com/ternaryop/photoshelf/view/snackbar/SnackbarHolder.kt
1
2042
package com.ternaryop.photoshelf.view.snackbar import android.graphics.Color import android.view.View import android.widget.TextView import androidx.lifecycle.DefaultLifecycleObserver import androidx.lifecycle.LifecycleOwner import com.google.android.material.snackbar.Snackbar open class SnackbarHolder : DefaultLifecycleObserver { private var snackbar: Snackbar? = null var backgroundColor = 0 var textColor = 0 var actionTextColor = 0 init { defaultColors() } open fun show( view: View, t: Throwable?, actionText: String? = null, action: ((View?) -> (Unit))? = null ) = show(build(view, t?.localizedMessage ?: "", actionText, action)) open fun show(snackbar: Snackbar, maxLines: Int = 3) { dismiss() this.snackbar = snackbar val sbView = snackbar.view sbView.setBackgroundColor(backgroundColor) val textView: TextView = sbView.findViewById(com.google.android.material.R.id.snackbar_text) textView.setTextColor(textColor) textView.maxLines = maxLines snackbar.show() resetColors() } open fun build( view: View, title: String?, actionText: String? = null, action: ((View?) -> (Unit))? = null ): Snackbar { val safeTitle = title ?: "" return if (action == null) { Snackbar.make(view, safeTitle, Snackbar.LENGTH_LONG) } else { Snackbar .make(view, safeTitle, Snackbar.LENGTH_INDEFINITE) .setActionTextColor(actionTextColor) .setAction(actionText, action) } } open fun dismiss() { snackbar?.dismiss() snackbar = null } open fun resetColors() = defaultColors() private fun defaultColors() { backgroundColor = Color.parseColor("#90000000") textColor = Color.WHITE actionTextColor = Color.parseColor("#ffdd00") } override fun onDestroy(owner: LifecycleOwner) = dismiss() }
mit
5d43b11ceca34cd019d3b71b81988843
28.171429
100
0.627326
4.6621
false
false
false
false
ken-kentan/student-portal-plus
app/src/main/java/jp/kentan/studentportalplus/data/dao/MyClassDao.kt
1
4052
package jp.kentan.studentportalplus.data.dao import jp.kentan.studentportalplus.data.model.MyClass import jp.kentan.studentportalplus.data.parser.MyClassParser import org.jetbrains.anko.db.* class MyClassDao( private val database: DatabaseOpenHelper ) : BaseDao() { companion object { const val TABLE_NAME = "my_class" val PARSER = MyClassParser() } fun getAll(): List<MyClass> = database.use { select(TABLE_NAME) .orderBy("week") .orderBy("period") .orderBy("user", SqlOrderDirection.DESC) .parseList(PARSER) } fun getSubjectList(): List<String> = database.use { select(TABLE_NAME) .distinct() .column("subject") .parseList(object : RowParser<String> { override fun parseRow(columns: Array<Any?>) = columns[0] as String }) } fun update(data: MyClass) = database.use { update(TABLE_NAME, "hash" to data.hash, "week" to data.week.code, "period" to data.period, "schedule_code" to data.scheduleCode, "credit" to data.credit, "category" to data.category, "subject" to data.subject, "instructor" to data.instructor, "user" to data.isUser, "color" to data.color, "location" to data.location) .whereArgs("_id=${data.id}") .exec() } fun updateAll(list: List<MyClass>) = database.use { transaction { var st = compileStatement("INSERT OR IGNORE INTO $TABLE_NAME VALUES(?,?,?,?,?,?,?,?,?,?,?,?);") // Insert new data list.forEach { st.bindNull(1) st.bindLong(2, it.hash) st.bindLong(3, it.week.code.toLong()) st.bindLong(4, it.period.toLong()) st.bindString(5, it.scheduleCode) st.bindLong(6, it.credit.toLong()) st.bindString(7, it.category) st.bindString(8, it.subject) st.bindString(9, it.instructor) st.bindLong(10, it.isUser.toLong()) st.bindLong(11, it.color.toLong()) st.bindStringOrNull(12, it.location) st.executeInsert() st.clearBindings() } // Delete old data if (list.isNotEmpty()) { val args = StringBuilder("?") for (i in 2..list.size) { args.append(",?") } st = compileStatement("DELETE FROM $TABLE_NAME WHERE user=0 AND hash NOT IN ($args)") list.forEachIndexed { i, d -> st.bindLong(i + 1, d.hash) } st.executeUpdateDelete() } } } fun insert(list: List<MyClass>) = database.use { var count = 0 transaction { val st = compileStatement("INSERT INTO $TABLE_NAME VALUES(?,?,?,?,?,?,?,?,?,?,?,?);") list.forEach { st.bindNull(1) st.bindLong(2, it.hash) st.bindLong(3, it.week.code.toLong()) st.bindLong(4, it.period.toLong()) st.bindString(5, it.scheduleCode) st.bindLong(6, it.credit.toLong()) st.bindString(7, it.category) st.bindString(8, it.subject) st.bindString(9, it.instructor) st.bindLong(10, it.isUser.toLong()) st.bindLong(11, it.color.toLong()) st.bindStringOrNull(12, it.location) st.executeInsert() st.clearBindings() count++ } } return@use count } fun delete(subject: String) = database.use { delete(TABLE_NAME, "subject='${subject.escapeQuery()}' AND user=1") } }
gpl-3.0
fce089382f823c0fab4921e42fea2912
31.95122
107
0.49383
4.492239
false
false
false
false
NextFaze/dev-fun
devfun/src/main/java/com/nextfaze/devfun/error/Dialog.kt
1
11974
package com.nextfaze.devfun.error import android.annotation.SuppressLint import android.app.Dialog import android.content.ClipData import android.content.Context import android.graphics.Color import android.os.Bundle import android.os.Handler import android.os.Parcelable import android.text.SpannableStringBuilder import android.util.AttributeSet import android.view.InflateException import android.view.LayoutInflater import android.view.MotionEvent import android.view.View import android.view.ViewGroup import android.view.ViewGroup.LayoutParams.MATCH_PARENT import android.view.ViewGroup.LayoutParams.WRAP_CONTENT import android.view.Window import android.widget.HorizontalScrollView import android.widget.ScrollView import android.widget.Toast import androidx.constraintlayout.widget.ConstraintLayout import androidx.constraintlayout.widget.ConstraintSet import androidx.fragment.app.FragmentActivity import com.nextfaze.devfun.core.R import com.nextfaze.devfun.core.devFun import com.nextfaze.devfun.internal.android.* import com.nextfaze.devfun.internal.log.* import com.nextfaze.devfun.internal.string.* import kotlinx.android.synthetic.main.df_devfun_error_dialog_fragment.* import java.lang.Math.abs import java.text.SimpleDateFormat internal interface RenderedError : Parcelable { val nanoTime: Long val timeMs: Long val stackTrace: String val title: CharSequence val body: CharSequence val method: CharSequence? var seen: Boolean } internal class ErrorDialogFragment : BaseDialogFragment() { companion object { fun show(activity: FragmentActivity, errors: ArrayList<RenderedError>) = showNow(activity) { ErrorDialogFragment().apply { arguments = Bundle().apply { putParcelableArrayList(ERRORS, errors) } } } } private val log = logger() private val handler = Handler() private val errorHandler by lazy { devFun.get<ErrorHandler>() } private val isInjectModuleMissing by lazy { classExists("dagger.Provides") && !classExists("com.nextfaze.devfun.inject.dagger2.InjectFromDagger2") } private lateinit var errors: List<RenderedError> private var currentErrorIdx: Int = 0 private val currentError get() = errors[abs(currentErrorIdx % errors.size)] override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) errors = arguments!!.getParcelableArrayList<RenderedError>(ERRORS)!!.apply { sortBy { it.nanoTime } } currentErrorIdx = errors.indexOfFirst { !it.seen }.takeIf { it >= 0 } ?: errors.size - 1 setStyle(STYLE_NO_TITLE, 0) } override fun onCreateDialog(savedInstanceState: Bundle?): Dialog = super.onCreateDialog(savedInstanceState).apply { requestWindowFeature(Window.FEATURE_NO_TITLE) } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? = inflater.inflate(R.layout.df_devfun_error_dialog_fragment, container, false) private fun showNextError() { if (currentErrorIdx < errors.size - 1) { currentErrorIdx++ bindCurrentError() } } private fun bindCurrentError() = setCurrentError(currentError) private fun showPreviousError() { if (currentErrorIdx > 0) { currentErrorIdx-- bindCurrentError() } } private fun setCurrentError(error: RenderedError) { with(error) { titleTextView.text = title timeTextView.text = SimpleDateFormat.getDateTimeInstance().format(timeMs) bodyTextView.text = if (isInjectModuleMissing && stackTrace.contains("ConstructableException")) { SpannableStringBuilder().apply { this += body this += "\n" this += color(b("Dagger 2.x detected but dagger-inject module not found. Did you forgot to add "), Color.RED) this += pre("devfun-inject-dagger2") this += color(b(" to your project?"), Color.RED) } } else { body } methodTextView.text = method methodTextView.visibility = if (method.isNullOrBlank()) View.GONE else View.VISIBLE stackTraceTextView.text = stackTrace } prevButton.isEnabled = currentErrorIdx > 0 nextButton.isEnabled = currentErrorIdx < errors.size - 1 errorPosTextView.text = getString(R.string.df_devfun_error_position, currentErrorIdx + 1, errors.size) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { stackTraceTextView.setOnLongClickListener { log.w { "Exception:\n${stackTraceTextView.text}" } it.context.clipboardManager.primaryClip = ClipData.newPlainText("stackTrace", currentError.stackTrace) Toast.makeText(context, "Stacktrace logged and copied to clipboard.", Toast.LENGTH_SHORT).show() true } bindCurrentError() prevButton.setOnClickListener { showPreviousError() } nextButton.setOnClickListener { showNextError() } navButtons?.visibility = if (errors.size > 1) View.VISIBLE else View.GONE clearButton.text = getString(if (errors.size > 1) R.string.df_devfun_clear_all else R.string.df_devfun_clear) clearButton.setOnClickListener { errors.forEach { error -> errorHandler.remove(error.nanoTime) } dismiss() } okButton.setOnClickListener { dismiss() } // love me some nested 2-dimensional scrolling in dialog with constraint layout... errorRootConstraintLayout.addOnLayoutChangeListener { _, _, _, _, _, _, _, _, _ -> fixLayout() } } override fun onPerformDismiss() { errors.forEach { errorHandler.markSeen(it.nanoTime) } } private fun fixLayout() { if (!isResumed) return val rootParent = (errorRootConstraintLayout?.parent as? ViewGroup) ?: return log.t { """Current Sizes: Current root.parent view size: ${rootParent.width}, ${rootParent.height} Current root view size: ${errorRootConstraintLayout.width}, ${errorRootConstraintLayout.height} (minWidth=${errorRootConstraintLayout.minWidth}) Current root view layout params: ${errorRootConstraintLayout.layoutParams.width}, ${errorRootConstraintLayout.layoutParams.height} Current titleTextView size: ${titleTextView.width}, ${titleTextView.height} Current bodyTextView size: ${bodyTextView.width}, ${bodyTextView.height} Current stack trace size: ${stackTraceScrollView.width}, ${stackTraceScrollView.height} """.trimIndent() } fun calculateTargetSize() = Math.min(stackTraceScrollView.width, stackTraceTextView.width) to Math.min(stackTraceScrollView.height, stackTraceTextView.height) val dialogIsMatchParent = dialog?.window?.attributes?.takeIf { it.width == MATCH_PARENT && it.height == MATCH_PARENT } != null val dialogIsWrapContent = dialog?.window?.attributes?.takeIf { it.width == WRAP_CONTENT && it.height == WRAP_CONTENT } != null val constraintsUpdated = (stackTraceScrollView.layoutParams as ConstraintLayout.LayoutParams).let { it.matchConstraintMinWidth != 0 && it.matchConstraintMinHeight != 0 } val viewSizesMatched = run matched@{ val (targetWidth, targetHeight) = calculateTargetSize() log.t { "targetWidth=$targetWidth, targetHeight=$targetHeight" } return@matched targetWidth > 0 && targetHeight > 0 && stackTraceScrollView.width == targetWidth && stackTraceScrollView.height == targetHeight } if (!constraintsUpdated || !viewSizesMatched) { if (!dialogIsMatchParent) { "Set dialog/constraint to match parent...".toastIt() handler.doPost { dialog?.window?.setLayout(MATCH_PARENT, MATCH_PARENT) errorRootConstraintLayout?.layoutParams ?.takeIf { it.width != MATCH_PARENT || it.height != MATCH_PARENT } ?.apply { width = MATCH_PARENT height = MATCH_PARENT } ?.let { errorRootConstraintLayout.layoutParams = it } } } else if (!constraintsUpdated) { "Update constraints...".toastIt() handler.doPost { if (errorRootConstraintLayout == null) return@doPost val (targetWidth, targetHeight) = calculateTargetSize() if (targetWidth > 0 && targetHeight > 0) { log.t { "Update stackTraceScrollView min width/height to ($targetWidth, $targetHeight)" } val constraints = ConstraintSet().apply { clone(errorRootConstraintLayout) constrainWidth(R.id.stackTraceScrollView, targetWidth) constrainMinWidth(R.id.stackTraceScrollView, targetWidth) constrainHeight(R.id.stackTraceScrollView, targetHeight) constrainMinHeight(R.id.stackTraceScrollView, targetHeight) } errorRootConstraintLayout.setConstraintSet(constraints) stackTraceScrollView.requestLayout() errorRootConstraintLayout.layoutParams = errorRootConstraintLayout.layoutParams.apply { width = targetWidth } } } } else { "Wrap constraint layout...".toastIt() handler.doPost { errorRootConstraintLayout?.layoutParams ?.takeIf { it.width != WRAP_CONTENT || it.height != WRAP_CONTENT } ?.apply { width = WRAP_CONTENT height = WRAP_CONTENT } ?.let { errorRootConstraintLayout.layoutParams = it } } } } else if (!dialogIsWrapContent) { "Wrap dialog window...".toastIt() handler.doPost { dialog?.window?.setLayout(WRAP_CONTENT, WRAP_CONTENT) } } } private fun Handler.doPost(body: () -> Unit) { post(body) // postDelayed(body, 5000) } private fun String.toastIt() { log.t { "Step: $this" } // Toast.makeText(context, this, Toast.LENGTH_SHORT).show() } } private const val ERRORS = "ERRORS" /** Our Horizontal-Vertical ScrollView. */ internal class HVScrollView @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0) : ScrollView(context, attrs, defStyleAttr) { private lateinit var hScrollView: HorizontalScrollView override fun onFinishInflate() { super.onFinishInflate() if (childCount <= 0) return if (childCount > 1) throw InflateException("HVScrollView can only have a single child!") val v = getChildAt(0) removeViewAt(0) hScrollView = HorizontalScrollView(context) addView(hScrollView) hScrollView.addView(v) } @SuppressLint("ClickableViewAccessibility") override fun onTouchEvent(event: MotionEvent) = super.onTouchEvent(event) || hScrollView.onTouchEvent(event) } private fun classExists(fqn: String) = try { Class.forName(fqn) true } catch (t: Throwable) { false }
apache-2.0
9cf618282b91e79dc85062e3163400ab
40.867133
164
0.625522
5.291206
false
false
false
false
apollo-rsps/apollo
game/plugin/cmd/test/ItemCommandTests.kt
1
1979
import io.mockk.verify import org.apollo.cache.def.ItemDefinition import org.apollo.game.command.Command import org.apollo.game.model.World import org.apollo.game.model.entity.Player import org.apollo.game.model.entity.setting.PrivilegeLevel import org.apollo.game.plugin.testing.assertions.contains import org.apollo.game.plugin.testing.junit.ApolloTestingExtension import org.apollo.game.plugin.testing.junit.api.annotations.ItemDefinitions import org.apollo.game.plugin.testing.junit.api.annotations.TestMock import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Test import org.junit.jupiter.api.extension.ExtendWith import org.junit.jupiter.params.ParameterizedTest import org.junit.jupiter.params.provider.ValueSource @ExtendWith(ApolloTestingExtension::class) class ItemCommandTests { @TestMock lateinit var world: World @TestMock lateinit var player: Player @Test fun `Defaults to an amount of 1`() { player.privilegeLevel = PrivilegeLevel.ADMINISTRATOR world.commandDispatcher.dispatch(player, Command("item", arrayOf("1"))) assertEquals(1, player.inventory.getAmount(1)) } @Test fun `Adds item of specified amount to inventory`() { player.privilegeLevel = PrivilegeLevel.ADMINISTRATOR world.commandDispatcher.dispatch(player, Command("item", arrayOf("1", "10"))) assertEquals(10, player.inventory.getAmount(1)) } @ParameterizedTest(name = "::item {0}") @ValueSource(strings = ["<garbage>", "1 <garbage>", "<garbage> 1"]) fun `Help message sent on invalid syntax`(args: String) { player.privilegeLevel = PrivilegeLevel.ADMINISTRATOR world.commandDispatcher.dispatch(player, Command("item", args.split(" ").toTypedArray())) verify { player.sendMessage(contains("Invalid syntax")) } } companion object { @ItemDefinitions val items = listOf(ItemDefinition(1)) } }
isc
118f862fd6da0255092914c525f6cf8f
33.736842
97
0.730672
4.378319
false
true
false
false
nemerosa/ontrack
ontrack-extension-indicators/src/test/java/net/nemerosa/ontrack/extension/indicators/ui/graphql/GQLRootQueryIndicatorPortfoliosIT.kt
1
7904
package net.nemerosa.ontrack.extension.indicators.ui.graphql import net.nemerosa.ontrack.common.Time import net.nemerosa.ontrack.extension.indicators.AbstractIndicatorsTestSupport import net.nemerosa.ontrack.extension.indicators.portfolio.IndicatorView import net.nemerosa.ontrack.json.asJson import net.nemerosa.ontrack.test.TestUtils.uid import org.junit.Test import java.util.* import kotlin.test.assertEquals import kotlin.test.assertTrue class GQLRootQueryIndicatorPortfoliosIT : AbstractIndicatorsTestSupport() { @Test fun `Getting a portfolio by ID`() { val portfolio1 = portfolio() @Suppress("UNUSED_VARIABLE") val portfolio2 = portfolio() val data = asAdmin { run( """ query LoadPortfolioOfPortfolios(${'$'}id: String!) { indicatorPortfolios(id: ${'$'}id) { id name } } """, mapOf("id" to portfolio1.id) ) } val portfolios = data["indicatorPortfolios"] assertEquals(1, portfolios.size()) val portfolio = portfolios[0] assertEquals(portfolio1.id, portfolio["id"].asText()) assertEquals(portfolio1.name, portfolio["name"].asText()) } @Test fun `Getting all portfolios`() { val portfolio1 = portfolio() val portfolio2 = portfolio() val data = asAdmin { run( """{ indicatorPortfolios { id name } }""", mapOf("id" to portfolio1.id) ) } val portfolios = data["indicatorPortfolios"] assertTrue(portfolios.any { it["id"].asText() == portfolio1.id }) assertTrue(portfolios.any { it["id"].asText() == portfolio2.id }) } @Test fun `Getting portfolio stats for a view`() { clearPortfolios() val category = category() val type = category.booleanType() val viewId = asAdmin { indicatorViewService.saveIndicatorView( IndicatorView( id = "", name = uid("V"), categories = listOf( category.id ) ) ).id } val label = label() project { labels = listOf(label) indicator(type, false, Time.now()) } val portfolio = portfolio( label = label ) asAdmin { run( """query IndicatorPortfolios( ${'$'}viewId: String ) { indicatorPortfolios(id: "${portfolio.id}") { id name viewStats(id: ${'$'}viewId) { category { id } stats { count avg avgRating } } } }""", mapOf("viewId" to viewId) ).let { data -> assertEquals( mapOf( "indicatorPortfolios" to listOf( mapOf( "id" to portfolio.id, "name" to portfolio.name, "viewStats" to listOf( mapOf( "category" to mapOf( "id" to category.id ), "stats" to mapOf( "count" to 1, "avg" to 0, "avgRating" to "F" ) ) ) ) ) ).asJson(), data ) } } } @Test fun `Getting portfolio stats without a view returns the categories of the portfolio`() { clearPortfolios() val category = category() val type = category.booleanType() val label = label() project { labels = listOf(label) indicator(type, false, Time.now()) } val portfolio = portfolio( label = label, categories = listOf(category) ) asAdmin { run( """query IndicatorPortfolios( ${'$'}viewId: String ) { indicatorPortfolios { id name viewStats(id: ${'$'}viewId) { category { id } stats { count avg avgRating } } } }""", mapOf("viewId" to null) ).let { data -> assertEquals( mapOf( "indicatorPortfolios" to listOf( mapOf( "id" to portfolio.id, "name" to portfolio.name, "viewStats" to listOf( mapOf( "category" to mapOf( "id" to category.id ), "stats" to mapOf( "count" to 1, "avg" to 0, "avgRating" to "F" ) ) ) ) ) ).asJson(), data ) } } } @Test fun `Getting portfolio stats with a non-existent view`() { clearPortfolios() val category = category() val type = category.booleanType() val label = label() project { labels = listOf(label) indicator(type, false, Time.now()) } val portfolio = portfolio( label = label ) asAdmin { run( """query IndicatorPortfolios( ${'$'}viewId: String ) { indicatorPortfolios { id name viewStats(id: ${'$'}viewId) { category { id } stats { count avg avgRating } } } }""", mapOf("viewId" to UUID.randomUUID().toString()) ).let { data -> assertEquals( mapOf( "indicatorPortfolios" to listOf( mapOf( "id" to portfolio.id, "name" to portfolio.name, "viewStats" to null ) ) ).asJson(), data ) } } } }
mit
f2996adb20c2bca4868435fab60c822a
29.635659
92
0.349696
6.664418
false
false
false
false
voghDev/HelloKotlin
app/src/main/java/es/voghdev/hellokotlin/MainActivity.kt
1
2669
/* * Copyright (C) 2017 Olmo Gallegos Hernรกndez. * * 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 es.voghdev.hellokotlin import android.app.Activity import android.content.Context import android.content.Intent import android.os.Bundle import android.support.v7.app.AppCompatActivity import android.util.DisplayMetrics import android.widget.Toast import es.voghdev.hellokotlin.features.user.SomeDetailActivity import kotlinx.android.synthetic.main.activity_main.* import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Job import kotlinx.coroutines.launch import kotlinx.coroutines.withContext class MainActivity : AppCompatActivity(), CoroutineScope { val job = Job() override val coroutineContext = Dispatchers.Main + job override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) button1.setOnClickListener { toast("You wrote: ${editText1.text}") launch { Thread.sleep(2500) withContext(Dispatchers.Main) { val width: Int = screenWidth() val height: Int = screenHeight() toast("Screen size is: $width x $height") } } } button1.setOnLongClickListener { startActivity(Intent(this, SomeDetailActivity::class.java)) true } } override fun onDestroy() { super.onDestroy() job.cancel() } fun Context.screenWidth(): Int { val displayMetrics: DisplayMetrics = DisplayMetrics() (this as Activity).windowManager.defaultDisplay.getMetrics(displayMetrics) return displayMetrics.widthPixels } fun Context.screenHeight(): Int { val displayMetrics: DisplayMetrics = DisplayMetrics() (this as Activity).windowManager.defaultDisplay.getMetrics(displayMetrics) return displayMetrics.heightPixels } fun toast(text: CharSequence, duration: Int = Toast.LENGTH_SHORT) = Toast.makeText(this, text, duration).show() }
apache-2.0
a463f005b659e1a47bef8740c5d32813
31.938272
115
0.696402
4.781362
false
false
false
false
ibaton/3House
mobile/src/main/java/treehou/se/habit/ui/widget/WidgetSetpointFactory.kt
1
3564
package treehou.se.habit.ui.widget import android.content.DialogInterface import android.support.v7.app.AlertDialog import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.NumberPicker import se.treehou.ng.ohcommunicator.connector.models.OHLinkedPage import se.treehou.ng.ohcommunicator.connector.models.OHServer import se.treehou.ng.ohcommunicator.services.IServerHandler import treehou.se.habit.R import treehou.se.habit.ui.adapter.WidgetAdapter import treehou.se.habit.util.getName import treehou.se.habit.util.logging.Logger import javax.inject.Inject class WidgetSetpointFactory @Inject constructor() : WidgetFactory { @Inject lateinit var logger: Logger @Inject lateinit var server: OHServer @Inject lateinit var page: OHLinkedPage @Inject lateinit var serverHandler: IServerHandler override fun createViewHolder(parent: ViewGroup): WidgetAdapter.WidgetViewHolder { val view = LayoutInflater.from(parent.context).inflate(R.layout.widget_setpoint, parent, false) return SwitchWidgetViewHolder(view) } inner class SwitchWidgetViewHolder(view: View) : WidgetBaseHolder(view, server, page) { private val valueView: View = view.findViewById(R.id.widgetValueHolder) override fun bind(itemWidget: WidgetAdapter.WidgetItem) { super.bind(itemWidget) valueView.setOnClickListener { createPickerDialog() } } private fun createPickerDialog() { val minValue = widget.minValue.toFloat() val maxValue = widget.maxValue.toFloat() val stepSize = if (minValue == maxValue || widget.step < 0) 1f else widget.step val stepValues = mutableListOf<String>() var x = minValue while (x <= maxValue) { stepValues.add("%.1f".format(x)) x += stepSize } val dialogView = LayoutInflater.from(context).inflate(R.layout.dialog_numberpicker, null, false) val numberPicker: NumberPicker = dialogView.findViewById(R.id.numberpicker) numberPicker.minValue = 0 numberPicker.maxValue = stepValues.size - 1 numberPicker.displayedValues = stepValues.toTypedArray(); val stateString = widget.item.state var stepIndex = stepValues.binarySearch(stateString, Comparator { t1: String, t2: String -> convertStringValueToFloat(t1).compareTo(convertStringValueToFloat(t2)) }) // Create wrap around if (stepIndex < 0) { stepIndex = (-(stepIndex + 1)) stepIndex = Math.min(stepIndex, stepValues.size - 1) } numberPicker.value = stepIndex AlertDialog.Builder(context) .setTitle(widget.getName()) .setView(dialogView) .setPositiveButton(R.string.ok, object : DialogInterface.OnClickListener { override fun onClick(dialog: DialogInterface?, which: Int) { serverHandler.sendCommand(widget.item.name, stepValues[numberPicker.value]) } }) .setNegativeButton(R.string.cancel, null) .show(); } private fun convertStringValueToFloat(value: String): Float { return value.replace(",", ".").toFloatOrNull() ?: 0f } } companion object { const val TAG = "WidgetSwitchFactory" } }
epl-1.0
9398daf661476cd936f1f24b38f06633
39.05618
108
0.647306
4.991597
false
false
false
false
d9n/intellij-rust
src/main/kotlin/org/rust/ide/commenter/RsCommenter.kt
1
433
package org.rust.ide.commenter import com.intellij.lang.Commenter class RsCommenter : Commenter { override fun getLineCommentPrefix(): String = "//" override fun getBlockCommentPrefix(): String = "/*" override fun getBlockCommentSuffix(): String = "*/" // for nested comments override fun getCommentedBlockCommentPrefix(): String = "*//*" override fun getCommentedBlockCommentSuffix(): String = "*//*" }
mit
b86d84777e82a3496ba12950cd0eb81b
27.866667
66
0.704388
5.034884
false
false
false
false
RedstonerServer/Parcels
src/main/kotlin/io/dico/parcels2/defaultimpl/GlobalPrivilegesManagerImpl.kt
1
1118
@file:Suppress("UNCHECKED_CAST") package io.dico.parcels2.defaultimpl import io.dico.parcels2.* import io.dico.parcels2.util.ext.alsoIfTrue import java.util.Collections class GlobalPrivilegesManagerImpl(val plugin: ParcelsPlugin) : GlobalPrivilegesManager { private val map = mutableMapOf<PlayerProfile, GlobalPrivileges>() override fun get(owner: PlayerProfile.Real): GlobalPrivileges { return map[owner] ?: GlobalPrivilegesImpl(owner).also { map[owner] = it } } private inner class GlobalPrivilegesImpl(override val keyOfOwner: PlayerProfile.Real) : PrivilegesHolder(), GlobalPrivileges { override var privilegeOfStar: Privilege get() = super<GlobalPrivileges>.privilegeOfStar set(value) = run { super<GlobalPrivileges>.privilegeOfStar = value } override fun setRawStoredPrivilege(key: PrivilegeKey, privilege: Privilege): Boolean { return super.setRawStoredPrivilege(key, privilege).alsoIfTrue { plugin.storage.setGlobalPrivilege(keyOfOwner, key, privilege) } } } }
gpl-2.0
0d5e3cd7fbbd8b969262e37504423360
38
130
0.703936
4.7173
false
false
false
false
ReactiveSocket/reactivesocket-tck
rsocket-tck-core/src/main/kotlin/io/rsocket/tck/frame/MetadataPushFrame.kt
1
850
package io.rsocket.tck.frame import io.netty.buffer.* import io.rsocket.tck.frame.shared.* data class MetadataPushFrame( override val header: FrameHeader<MetadataPushFlags>, val metadata: ByteBuf ) : Frame<MetadataPushFlags>(FrameType.METADATA_PUSH) { override fun buffer(allocator: ByteBufAllocator): ByteBuf { val header = headerBuffer(allocator) return allocator.compose(header, metadata) } } fun RawFrame.asMetadataPush(): MetadataPushFrame = typed(FrameType.METADATA_PUSH) { val flags = MetadataPushFlags(metadata = header.flags.value check CommonFlag.Metadata) val metadata = slice() MetadataPushFrame( header = header.withFlags(flags), metadata = metadata ) } data class MetadataPushFlags( val metadata: Boolean ) : TypedFlags({ CommonFlag.Metadata setIf metadata })
apache-2.0
92c841d0fccc3cbd3899c009054297a9
28.310345
90
0.728235
4.207921
false
false
false
false
FFlorien/AmpachePlayer
app/src/main/java/be/florien/anyflow/data/server/AmpacheConnection.kt
1
15881
package be.florien.anyflow.data.server import android.content.SharedPreferences import androidx.lifecycle.MutableLiveData import be.florien.anyflow.UserComponentContainer import be.florien.anyflow.data.TimeOperations import be.florien.anyflow.data.server.exception.NotAnAmpacheUrlException import be.florien.anyflow.data.server.exception.SessionExpiredException import be.florien.anyflow.data.server.exception.WrongFormatServerUrlException import be.florien.anyflow.data.server.exception.WrongIdentificationPairException import be.florien.anyflow.data.server.model.* import be.florien.anyflow.data.user.AuthPersistence import be.florien.anyflow.extension.applyPutLong import be.florien.anyflow.extension.eLog import com.fasterxml.jackson.databind.ObjectMapper import okhttp3.HttpUrl.Companion.toHttpUrl import retrofit2.HttpException import java.lang.IllegalStateException import java.math.BigInteger import java.security.MessageDigest import java.util.* import javax.inject.Inject import javax.inject.Singleton /** * Manager for the ampache API server-side */ @Singleton open class AmpacheConnection @Inject constructor( private var authPersistence: AuthPersistence, private var userComponentContainer: UserComponentContainer, private val sharedPreferences: SharedPreferences ) { companion object { private const val OFFSET_SONG = "songOffset" private const val OFFSET_ARTIST = "artistOffset" private const val OFFSET_ALBUM = "albumOffset" private const val OFFSET_TAG = "tagOffset" private const val OFFSET_PLAYLIST = "playlistOffset" private const val OFFSET_PLAYLIST_SONGS = "playlistSongOffset" private const val RECONNECT_LIMIT = 3 private const val COUNT_SONGS = "SONGS_COUNT" private const val COUNT_ALBUMS = "ALBUMS_COUNT" private const val COUNT_ARTIST = "ARTIST_COUNT" private const val COUNT_PLAYLIST = "PLAYLIST_COUNT" } private var ampacheApi: AmpacheApi = AmpacheApiDisconnected() private val oldestDateForRefresh = TimeOperations.getDateFromMillis(0L) private val itemLimit: Int = 150 private var songOffset: Int = sharedPreferences.getLong(OFFSET_SONG, 0).toInt() private var artistOffset: Int = sharedPreferences.getLong(OFFSET_ARTIST, 0).toInt() private var albumOffset: Int = sharedPreferences.getLong(OFFSET_ALBUM, 0).toInt() private var tagOffset: Int = sharedPreferences.getLong(OFFSET_TAG, 0).toInt() private var playlistOffset: Int = sharedPreferences.getLong(OFFSET_PLAYLIST, 0).toInt() private var reconnectByPing = 0 private var reconnectByUserPassword = 0 private var userComponent get() = userComponentContainer.userComponent set(value) { userComponentContainer.userComponent = value } val connectionStatusUpdater = MutableLiveData(ConnectionStatus.CONNEXION) val songsPercentageUpdater = MutableLiveData(0) val artistsPercentageUpdater = MutableLiveData(0) val albumsPercentageUpdater = MutableLiveData(0) val playlistsPercentageUpdater = MutableLiveData(0) /** * Ampache connection handling */ fun openConnection(serverUrl: String) { val url = try { serverUrl.toHttpUrl() } catch (exception: IllegalArgumentException) { throw WrongFormatServerUrlException( "The provided url was not correctly formed", exception ) } ampacheApi = userComponentContainer.createUserScopeForServer(url.toString()) authPersistence.saveServerInfo(url.toString()) } fun ensureConnection() { if (userComponent == null) { val savedServerUrl = authPersistence.serverUrl.secret if (savedServerUrl.isNotBlank()) { openConnection(savedServerUrl) } } } fun resetReconnectionCount() { reconnectByUserPassword = 0 } /** * API calls : connection */ suspend fun authenticate(user: String, password: String): AmpacheAuthentication { val time = (TimeOperations.getCurrentDate().timeInMillis / 1000).toString() val encoder = MessageDigest.getInstance("SHA-256") encoder.reset() val passwordEncoded = binToHex(encoder.digest(password.toByteArray())).lowercase(Locale.ROOT) encoder.reset() val auth = binToHex(encoder.digest((time + passwordEncoded).toByteArray())).lowercase(Locale.ROOT) connectionStatusUpdater.postValue(ConnectionStatus.CONNEXION) try { val authentication = ampacheApi.authenticate(user = user, auth = auth, time = time) when (authentication.error.code) { 401 -> { connectionStatusUpdater.postValue(ConnectionStatus.WRONG_ID_PAIR) throw WrongIdentificationPairException(authentication.error.error_text) } 0 -> { authPersistence.saveConnectionInfo( user, password, authentication.auth, TimeOperations.getDateFromAmpacheComplete(authentication.session_expire).timeInMillis ) saveDbCount(authentication.songs, authentication.albums, authentication.artists, authentication.playlists) } } connectionStatusUpdater.postValue(ConnectionStatus.CONNECTED) return authentication } catch (exception: HttpException) { connectionStatusUpdater.postValue(ConnectionStatus.WRONG_SERVER_URL) ampacheApi = AmpacheApiDisconnected() throw NotAnAmpacheUrlException("The ampache server couldn't be found at provided url") } catch (exception: Exception) { eLog(exception, "Unknown error while trying to login") throw exception } } suspend fun ping(authToken: String = authPersistence.authToken.secret): AmpachePing { if (authToken.isBlank()) { throw IllegalArgumentException("No token available !") } try { connectionStatusUpdater.postValue(ConnectionStatus.CONNEXION) val ping = ampacheApi.ping(auth = authToken) if (ping.session_expire.isEmpty()) { return ping } saveDbCount(ping.songs, ping.albums, ping.artists, ping.playlists) authPersistence.setNewAuthExpiration(TimeOperations.getDateFromAmpacheComplete(ping.session_expire).timeInMillis) connectionStatusUpdater.postValue(ConnectionStatus.CONNECTED) return ping } catch (exception: Exception) { eLog(exception) throw exception } } suspend fun <T> reconnect(request: suspend () -> T): T { if (!authPersistence.hasConnectionInfo()) { throw SessionExpiredException("Can't reconnect") } else { if (reconnectByPing >= RECONNECT_LIMIT) { reconnectByPing = 0 authPersistence.revokeAuthToken() } return if (authPersistence.authToken.secret.isNotBlank()) { reconnectByPing(request) } else if (authPersistence.user.secret.isNotBlank() && authPersistence.password.secret.isNotBlank()) { reconnectByUsernamePassword(request) } else { throw SessionExpiredException("Can't reconnect") } } } private suspend fun <T> reconnectByPing(request: suspend () -> T): T { reconnectByPing++ val pingResponse = ping(authPersistence.authToken.secret) return if (pingResponse.error.code == 0) { saveDbCount(pingResponse.songs, pingResponse.albums, pingResponse.artists, pingResponse.playlists) request() } else { val authResponse = authenticate(authPersistence.user.secret, authPersistence.password.secret) if (authResponse.error.code == 0) { request() } else { throw SessionExpiredException("Can't reconnect") } } } private suspend fun <T> reconnectByUsernamePassword(request: suspend () -> T): T { reconnectByUserPassword++ val authentication = authenticate(authPersistence.user.secret, authPersistence.password.secret) return if (authentication.error.code == 0) { saveDbCount(authentication.songs, authentication.albums, authentication.artists, authentication.playlists) request() } else { throw SessionExpiredException("Can't reconnect") } } private fun saveDbCount(songs: Int, albums: Int, artists: Int, playlists: Int) { val edit = sharedPreferences.edit() edit.putInt(COUNT_SONGS, songs) edit.putInt(COUNT_ALBUMS, albums) edit.putInt(COUNT_ARTIST, artists) edit.putInt(COUNT_PLAYLIST, playlists) edit.apply() } /** * API calls : data */ suspend fun getSongs(from: Calendar = oldestDateForRefresh): List<AmpacheSong>? { try { val songList = ampacheApi.getSongs( auth = authPersistence.authToken.secret, add = TimeOperations.getAmpacheGetFormatted(from), limit = itemLimit, offset = songOffset ) val totalSongs = sharedPreferences.getInt(COUNT_SONGS, 1) return if (songList.isEmpty()) { songsPercentageUpdater.postValue(-1) sharedPreferences.edit().remove(OFFSET_SONG).apply() null } else { val percentage = (songOffset * 100) / totalSongs songsPercentageUpdater.postValue(percentage) songOffset += songList.size sharedPreferences.applyPutLong(OFFSET_SONG, songOffset.toLong()) songList } } catch (ex: Exception) { eLog(ex) throw ex } } suspend fun getArtists(from: Calendar = oldestDateForRefresh): List<AmpacheArtist>? { try { val artistList = ampacheApi.getArtists( auth = authPersistence.authToken.secret, add = TimeOperations.getAmpacheGetFormatted(from), limit = itemLimit, offset = artistOffset ) val totalArtists = sharedPreferences.getInt(COUNT_ARTIST, 1) if (!artistList.isSuccessful) { val errorBody = artistList.errorBody() if (errorBody != null) { val readValue = ObjectMapper().readValue(errorBody.byteStream(), AmpacheErrorObject::class.java) throw IllegalStateException(readValue.error.error_text) } } val body = artistList.body() ?: throw IllegalArgumentException("No list of artist in the response") return if (body.isEmpty()) { artistsPercentageUpdater.postValue(-1) sharedPreferences.edit().remove(OFFSET_ARTIST).apply() null } else { val percentage = (artistOffset * 100) / totalArtists artistsPercentageUpdater.postValue(percentage) artistOffset += body.size sharedPreferences.applyPutLong(OFFSET_ARTIST, artistOffset.toLong()) body } } catch (ex: Exception) { eLog(ex) throw ex } } suspend fun getAlbums(from: Calendar = oldestDateForRefresh): List<AmpacheAlbum>? { try { val albumList = ampacheApi.getAlbums( auth = authPersistence.authToken.secret, add = TimeOperations.getAmpacheGetFormatted(from), limit = itemLimit, offset = albumOffset ) val totalAlbums = sharedPreferences.getInt(COUNT_ALBUMS, 1) return if (albumList.isEmpty()) { albumsPercentageUpdater.postValue(-1) sharedPreferences.edit().remove(OFFSET_ALBUM).apply() null } else { val percentage = (albumOffset * 100) / totalAlbums albumsPercentageUpdater.postValue(percentage) albumOffset += albumList.size sharedPreferences.applyPutLong(OFFSET_ALBUM, albumOffset.toLong()) albumList } } catch (ex: java.lang.Exception) { eLog(ex) throw ex } } suspend fun getPlaylists(): List<AmpachePlayList>? { // todo these are the new playlists val playlistList = ampacheApi.getPlaylists( auth = authPersistence.authToken.secret, limit = itemLimit, offset = playlistOffset ) val totalPlaylists = sharedPreferences.getInt(COUNT_PLAYLIST, 1) return if (playlistList.isEmpty()) { playlistsPercentageUpdater.postValue(-1) sharedPreferences.edit().remove(OFFSET_PLAYLIST).apply() null } else { val percentage = (playlistOffset * 100) / totalPlaylists playlistsPercentageUpdater.postValue(percentage) playlistOffset += playlistList.size sharedPreferences.applyPutLong(OFFSET_PLAYLIST, playlistOffset.toLong()) playlistList } } suspend fun getTags(from: Calendar = oldestDateForRefresh): List<AmpacheTag>? { val tagList = ampacheApi.getTags( auth = authPersistence.authToken.secret, add = TimeOperations.getAmpacheGetFormatted(from), limit = itemLimit, offset = tagOffset ) return if (tagList.isEmpty()) { sharedPreferences.edit().remove(OFFSET_TAG).apply() null } else { tagOffset += tagList.size sharedPreferences.applyPutLong(OFFSET_TAG, tagOffset.toLong()) tagList } } suspend fun getPlaylistsSongs(playlistToQuery: Long): List<AmpacheSongId>? { val prefName = OFFSET_PLAYLIST_SONGS + playlistToQuery var currentPlaylistOffset = sharedPreferences.getLong(prefName, 0).toInt() val playlistSongList = ampacheApi.getPlaylistSongs( auth = authPersistence.authToken.secret, filter = playlistToQuery.toString(), limit = itemLimit, offset = currentPlaylistOffset ) return if (playlistSongList.isEmpty()) { sharedPreferences.edit().remove(prefName).apply() null } else { currentPlaylistOffset += playlistSongList.size sharedPreferences.applyPutLong(prefName, currentPlaylistOffset.toLong()) playlistSongList } } suspend fun createPlaylist(name: String) { ampacheApi.createPlaylist(auth = authPersistence.authToken.secret, name = name) } suspend fun addSongToPlaylist(songId: Long, playlistId: Long) { ampacheApi.addToPlaylist(auth = authPersistence.authToken.secret, filter = playlistId, songId = songId) } fun getSongUrl(id: Long): String { val serverUrl = authPersistence.serverUrl.secret val token = authPersistence.authToken.secret return "${serverUrl}play/index.php?ssid=$token&oid=$id" } private fun binToHex(data: ByteArray): String = String.format("%0" + data.size * 2 + "X", BigInteger(1, data)) enum class ConnectionStatus { WRONG_SERVER_URL, WRONG_ID_PAIR, CONNEXION, CONNECTED } }
gpl-3.0
c65cea533b50f817596b7067bfed3a08
39.616368
126
0.626472
5.377921
false
false
false
false
REBOOTERS/AndroidAnimationExercise
imitate/src/main/java/com/engineer/imitate/ui/activity/ConstraintLayoutActivity.kt
1
5923
package com.engineer.imitate.ui.activity import android.animation.Animator import android.animation.AnimatorListenerAdapter import android.animation.ValueAnimator import android.graphics.Rect import android.os.Bundle import android.util.Log import android.view.View import android.view.ViewPropertyAnimator import android.view.ViewTreeObserver import android.widget.FrameLayout import android.widget.Toast import androidx.appcompat.app.AppCompatActivity import androidx.recyclerview.widget.LinearLayoutManager import com.engineer.imitate.R import com.engineer.imitate.ui.list.adapter.LargeImageAdapter import com.engineer.imitate.ui.widget.more.DZStickyNavLayouts import com.engineer.imitate.util.hide import com.engineer.imitate.util.show import kotlinx.android.synthetic.main.activity_constraint_layout.* class ConstraintLayoutActivity : AppCompatActivity() { val tag = "ConstraintLayout" private lateinit var layoutParams: FrameLayout.LayoutParams private val globalLayoutListener = object : ViewTreeObserver.OnGlobalLayoutListener { override fun onGlobalLayout() { root_content?.let { val displayRect = Rect() it.getWindowVisibleDisplayFrame(displayRect) Log.e(tag, "${displayRect.top}") Log.e(tag, "${displayRect.right}") Log.e(tag, "${displayRect.bottom}") Log.e(tag, "${displayRect.left}") // scrollView.scrollBy(0, -displayRect.bottom) // layoutParams.height = displayRect.bottom // layoutParams.bottomMargin = 1000 it.layoutParams = layoutParams } } } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_constraint_layout) recyclerView_2.layoutManager = LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false) recyclerView_2.adapter = LargeImageAdapter(getList()) head_home_layout.setOnStartActivity(object : DZStickyNavLayouts.OnStartActivityListener { override fun onStart() { Toast.makeText(this@ConstraintLayoutActivity, "bingo", Toast.LENGTH_SHORT).show() } }) var toggle = false anim.setOnClickListener { if (toggle) { image_alpha.alpha = 0.0f } else { image_alpha.alpha = 1.0f } toggle = !toggle } rotate_anim.setOnClickListener { rotate_anim.rotation = 0f rotateAnim(rotate_anim) } button_2.setOnClickListener { if (button_1.visibility == View.VISIBLE) { button_1.hide() } else { button_1.show() } } } private var rotation: ViewPropertyAnimator? = null private fun rotateAnim(view: View) { rotation = view.animate().rotation(90f).setStartDelay(400).setDuration(600) .setListener(object : AnimatorListenerAdapter() { override fun onAnimationEnd(animation: Animator) { super.onAnimationEnd(animation) rotation = view.animate().rotation(0f).setStartDelay(400).setDuration(600) .setListener(object : AnimatorListenerAdapter() { override fun onAnimationEnd(animation: Animator) { super.onAnimationEnd(animation) rotation = view.animate().rotation(90f).setStartDelay(400).setDuration(600) rotation?.start() } }) rotation?.start() } }) rotation?.start() } // <editor-fold defaultstate="collapsed" desc="prepare datas"> private fun getList(): MutableList<String> { val datas = ArrayList<String>() datas.add("https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1555581149653&di=5912dd2fe4db77ce303569b3e8f34d7b&imgtype=0&src=http%3A%2F%2Fb-ssl.duitang.com%2Fuploads%2Fitem%2F201406%2F08%2F20140608161225_VYVEV.jpeg") datas.add("https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1555581149653&di=5912dd2fe4db77ce303569b3e8f34d7b&imgtype=0&src=http%3A%2F%2Fb-ssl.duitang.com%2Fuploads%2Fitem%2F201406%2F08%2F20140608161225_VYVEV.jpeg") datas.add("https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1555581149653&di=5912dd2fe4db77ce303569b3e8f34d7b&imgtype=0&src=http%3A%2F%2Fb-ssl.duitang.com%2Fuploads%2Fitem%2F201406%2F08%2F20140608161225_VYVEV.jpeg") datas.add("https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1555581149653&di=5912dd2fe4db77ce303569b3e8f34d7b&imgtype=0&src=http%3A%2F%2Fb-ssl.duitang.com%2Fuploads%2Fitem%2F201406%2F08%2F20140608161225_VYVEV.jpeg") datas.add("https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1555581149653&di=5912dd2fe4db77ce303569b3e8f34d7b&imgtype=0&src=http%3A%2F%2Fb-ssl.duitang.com%2Fuploads%2Fitem%2F201406%2F08%2F20140608161225_VYVEV.jpeg") datas.add("https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1555581149653&di=5912dd2fe4db77ce303569b3e8f34d7b&imgtype=0&src=http%3A%2F%2Fb-ssl.duitang.com%2Fuploads%2Fitem%2F201406%2F08%2F20140608161225_VYVEV.jpeg") return datas } // </editor-fold> override fun onResume() { super.onResume() layoutParams = root_content.layoutParams as FrameLayout.LayoutParams root_content.viewTreeObserver.addOnGlobalLayoutListener(globalLayoutListener) } override fun onPause() { super.onPause() root_content.viewTreeObserver.removeOnGlobalLayoutListener(globalLayoutListener) } }
apache-2.0
9e61db586de09a1f1599770f8c30b7c1
46.007937
242
0.665879
4.116053
false
false
false
false
REBOOTERS/AndroidAnimationExercise
imitate/src/test/java/com/engineer/imitate/AndroidContextTest.kt
1
1089
package com.engineer.imitate import android.content.Context import androidx.test.core.app.ApplicationProvider import com.engineer.imitate.util.AppUtils import com.facebook.soloader.SoLoader import org.junit.Assert.* import org.junit.BeforeClass import org.junit.Test import org.junit.runner.RunWith //import org.robolectric.RobolectricTestRunner //import org.robolectric.annotation.Config /** * @author rookie * @since 07-30-2019 */ //@RunWith(RobolectricTestRunner::class) //@Config(sdk = [27],application = ImitateApplication::class) class AndroidContextTest { @Test fun assertContext() { val context = ApplicationProvider.getApplicationContext<Context>() val version = AppUtils.getAppVersion(context) // ๅ•ๅ…ƒๆต‹่ฏ•๏ผŒไนŸๅฏไปฅๆ‰“ๅฐๆ—ฅๅฟ— println("version ==$version") assertEquals("1.0", version) assertEquals("com.engineer.imitate",AppUtils.getAppName(context)) } companion object { @BeforeClass fun setup() { // for Fresco SoLoader.setInTestMode() } } }
apache-2.0
bf05ef40a53d498b23fee57888165339
23.767442
74
0.699531
4.364754
false
true
false
false
DemonWav/IntelliJBukkitSupport
src/main/kotlin/util/editor-utils.kt
1
1507
/* * Minecraft Dev for IntelliJ * * https://minecraftdev.org * * Copyright (c) 2021 minecraft-dev * * MIT License */ package com.demonwav.mcdev.util import com.intellij.ide.util.EditSourceUtil import com.intellij.openapi.editor.Editor import com.intellij.openapi.fileEditor.OpenFileDescriptor import com.intellij.openapi.fileEditor.ex.IdeDocumentHistory import com.intellij.pom.Navigatable import com.intellij.psi.PsiElement import com.intellij.psi.PsiFile import com.intellij.psi.util.PsiTreeUtil fun gotoTargetElement(element: PsiElement, currentEditor: Editor, currentFile: PsiFile) { if (element.containingFile === currentFile) { val offset = element.textOffset val leaf = currentFile.findElementAt(offset) // check that element is really physically inside the file // there are fake elements with custom navigation (e.g. opening URL in browser) that override getContainingFile for various reasons if (leaf != null && PsiTreeUtil.isAncestor(element, leaf, false)) { val project = element.project IdeDocumentHistory.getInstance(project).includeCurrentCommandAsNavigation() OpenFileDescriptor(project, currentFile.viewProvider.virtualFile, offset).navigateIn(currentEditor) return } } val navigatable = if (element is Navigatable) element else EditSourceUtil.getDescriptor(element) if (navigatable != null && navigatable.canNavigate()) { navigatable.navigate(true) } }
mit
501e521526b5f9c1ed66999db5baf35b
36.675
139
0.737226
4.665635
false
false
false
false
MimiReader/mimi-reader
mimi-app/src/main/java/com/emogoth/android/phone/mimi/activity/MimiActivity.kt
1
12379
package com.emogoth.android.phone.mimi.activity import android.content.Intent import android.content.pm.PackageManager import android.graphics.drawable.Drawable import android.graphics.drawable.LayerDrawable import android.os.Bundle import android.util.Log import android.view.ActionMode import android.view.Menu import android.view.MenuItem import android.view.View import android.widget.Toast import androidx.annotation.DrawableRes import androidx.annotation.IdRes import androidx.appcompat.app.ActionBarDrawerToggle import androidx.appcompat.app.AppCompatActivity import androidx.appcompat.widget.Toolbar import androidx.core.content.res.ResourcesCompat import androidx.drawerlayout.widget.DrawerLayout import androidx.fragment.app.Fragment import androidx.vectordrawable.graphics.drawable.VectorDrawableCompat import com.emogoth.android.phone.mimi.BuildConfig import com.emogoth.android.phone.mimi.R import com.emogoth.android.phone.mimi.activity.GalleryActivity2.Companion.start import com.emogoth.android.phone.mimi.db.HistoryTableConnection.observeHistory import com.emogoth.android.phone.mimi.fragment.NavDrawerFragment import com.emogoth.android.phone.mimi.interfaces.* import com.emogoth.android.phone.mimi.util.* import com.mimireader.chanlib.models.ChanPost import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.disposables.Disposable import io.reactivex.schedulers.Schedulers import java.util.* import java.util.prefs.PreferenceChangeEvent import java.util.prefs.PreferenceChangeListener abstract class MimiActivity : AppCompatActivity(), PreferenceChangeListener, ThumbnailClickListener, PostItemClickListener, ReplyClickListener, HistoryClickedListener, ActionMode.Callback, HomeButtonListener { // private val refreshScheduler = RefreshScheduler.getInstance() private var navDrawerView: View? = null var drawerLayout: DrawerLayout? = null private set var drawerToggle: ActionBarDrawerToggle? = null private set private var showBadge = true var resultFragment: Fragment? = null private set private var bookmarksOrHistory = 0 var toolbar: Toolbar? = null set(toolbar) { field = toolbar if (field != null) { field?.logo = null setSupportActionBar(field) supportActionBar?.setDisplayHomeAsUpEnabled(true) } } private var fetchPostSubscription: Disposable? = null private var savedRequestCode = 0 private var savedResultCode = 0 private var savedIntentData: Intent? = null @DrawableRes protected var navDrawable: Int = R.drawable.ic_nav_menu private var historyObserver: Disposable? = null // var onBookmarkClicked: ((boardName: String, threadId: Long, boardTitle: String, orderId: Int) -> Unit)? = null override fun onCreate(savedInstanceState: Bundle?) { try { val currentTheme = packageManager.getActivityInfo(componentName, 0).theme if (currentTheme != R.style.Theme_Mimi_Gallery) { setTheme(MimiUtil.getInstance().themeResourceId) } theme.applyStyle(MimiUtil.getFontStyle(this), true) } catch (e: PackageManager.NameNotFoundException) { e.printStackTrace() setTheme(MimiUtil.getInstance().themeResourceId) } super.onCreate(savedInstanceState) val extras = intent.extras if (extras != null) { if (extras.containsKey(Extras.EXTRAS_SHOW_ACTIONBAR_BADGE)) { showBadge = extras.getBoolean(Extras.EXTRAS_SHOW_ACTIONBAR_BADGE, true) } if (extras.containsKey(Extras.EXTRAS_VIEWING_HISTORY)) { bookmarksOrHistory = extras.getInt(Extras.EXTRAS_VIEWING_HISTORY) } } } override fun onPostCreate(savedInstanceState: Bundle?) { super.onPostCreate(savedInstanceState) if (drawerToggle != null) { // Sync the toggle state after onRestoreInstanceState has occurred. drawerToggle?.syncState() } } override fun onPause() { super.onPause() RxUtil.safeUnsubscribe(historyObserver) } override fun onResume() { super.onResume() try { updateBadge() } catch (e: Exception) { Log.e(LOG_TAG, "Caught exception", e) } } protected fun drawerItemSelected(item: MenuItem?) { drawerToggle?.onOptionsItemSelected(item) } fun toggleNavDrawer() { if (navDrawerView == null) { return } val view = navDrawerView as View if (drawerLayout?.isDrawerOpen(view) == true) { drawerLayout?.closeDrawer(view) } else { drawerLayout?.openDrawer(view) } } override fun onBackPressed() { try { if (drawerLayout != null && navDrawerView != null && drawerLayout?.isDrawerOpen(navDrawerView!!) == true) { toggleNavDrawer() } else { super.onBackPressed() } } catch (e: Exception) { Log.e(LOG_TAG, "Caught exception in onBackPressed()", e) Log.e(LOG_TAG, "Caught exception", e) } } override fun onDestroy() { super.onDestroy() if (drawerLayout != null && drawerToggle != null) { drawerLayout?.removeDrawerListener(drawerToggle!!) } } protected fun initDrawers(@IdRes navRes: Int, @IdRes drawerLayoutRes: Int, drawerIndicator: Boolean) { navDrawerView = findViewById(navRes) drawerLayout = findViewById<View>(drawerLayoutRes) as DrawerLayout val dt = object : ActionBarDrawerToggle(this, drawerLayout, R.string.app_name, R.string.app_name) { override fun onDrawerOpened(drawerView: View) { invalidateOptionsMenu() syncState() } override fun onDrawerClosed(drawerView: View) { invalidateOptionsMenu() syncState() } override fun onDrawerSlide(drawerView: View, slideOffset: Float) { super.onDrawerSlide(drawerView, slideOffset) } } dt.isDrawerIndicatorEnabled = false if (drawerIndicator) { navDrawable = R.drawable.ic_nav_menu } else { navDrawable = R.drawable.ic_nav_arrow_back } drawerLayout?.addDrawerListener(dt) drawerToggle = dt } fun updateBadge() { historyObserver = observeHistory(true) .subscribeOn(Schedulers.computation()) .observeOn(AndroidSchedulers.mainThread()) .subscribe { var unread = 0 for (history in it) { unread += history.unreadCount } setNavigationIconWithBadge(navDrawable, unread) } } protected fun setNavigationIconWithBadge(drawableRes: Int, count: Int) { Log.d(LOG_TAG, "Setting nav icon: count=$count") val layers: Array<Drawable?> val layerDrawable: LayerDrawable? if (drawableRes > 0) { if (count > 0) { layers = arrayOfNulls(2) layers[0] = VectorDrawableCompat.create(resources, drawableRes, theme) layers[1] = ResourcesCompat.getDrawable(resources, R.drawable.notification_unread, theme) } else { layers = arrayOfNulls(1) layers[0] = VectorDrawableCompat.create(resources, drawableRes, theme) } layerDrawable = LayerDrawable(layers) } else { val navDrawable = toolbar?.navigationIcon if (navDrawable is LayerDrawable) { val icon = navDrawable.getDrawable(0) if (count > 0) { layers = arrayOfNulls(2) layers[0] = icon layers[1] = ResourcesCompat.getDrawable(resources, R.drawable.notification_unread, theme) } else { layers = arrayOfNulls(1) layers[0] = icon } layerDrawable = LayerDrawable(layers) } else { layerDrawable = null } } if (layerDrawable != null) { drawerToggle?.setHomeAsUpIndicator(layerDrawable) } } protected fun createDrawers(@IdRes navRes: Int) { val ft = supportFragmentManager.beginTransaction() val navDrawerFragment = NavDrawerFragment() val args = Bundle() args.putInt(Extras.EXTRAS_VIEWING_HISTORY, bookmarksOrHistory) ft.add(navRes, navDrawerFragment, TAG_NAV_DRAWER) ft.commit() } override fun preferenceChange(pce: PreferenceChangeEvent) { Log.i(LOG_TAG, "Preference Changed: name=" + pce.key + ", value=" + pce.newValue) } fun showBadge(): Boolean { return showBadge } fun setResultFragment(resultFragment: Fragment, dispatchResults: Boolean) { this.resultFragment = resultFragment if (dispatchResults && savedIntentData != null) { resultFragment.onActivityResult(savedRequestCode, savedResultCode, savedIntentData) } } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) if (requestCode == SETTINGS_ID) { if (resultCode == RESTART_ACTIVITY_RESULT) { startActivity(Intent(this, StartupActivity::class.java)) finish() } } else { savedRequestCode = requestCode savedResultCode = resultCode savedIntentData = data } } override fun onThumbnailClick(posts: List<ChanPost>, threadId: Long, position: Int, boardName: String) { try { val id: Long id = if (position < 0 || posts.size <= position) { val e = Exception("Could not locate post in post list: position=" + position + ", list size=" + posts.size) Log.e(LOG_TAG, "Caught exception", e) Log.e(LOG_TAG, "Error opening gallery into a post", e) threadId } else { posts[position].no } // ThreadRegistry.getInstance().setPosts(threadId, posts) start(this, GalleryActivity2.GALLERY_TYPE_PAGER, id, boardName, threadId, LongArray(0)) } catch (e: Exception) { Log.e(LOG_TAG, "Caught exception", e) Log.e(LOG_TAG, "Could not open thumbnail: posts.size()=" + posts.size + ", position=" + position) Toast.makeText(this, R.string.error_opening_gallery, Toast.LENGTH_SHORT).show() } } override fun onPostItemClick(v: View?, posts: List<ChanPost>, position: Int, boardTitle: String, boardName: String, threadId: Long) { // no op } override fun onReplyClicked(boardName: String, threadId: Long, id: Long, replies: List<String>) { // no op } override fun onHistoryItemClicked(boardName: String, threadId: Long, boardTitle: String, position: Int, watched: Boolean) { // no op } override fun openHistoryPage(watched: Boolean) { // no op } // ActionMode.Callback override fun onActionItemClicked(p0: ActionMode?, p1: MenuItem?): Boolean { // no op return false } override fun onCreateActionMode(p0: ActionMode?, p1: Menu?): Boolean { // no op return false } override fun onPrepareActionMode(p0: ActionMode?, p1: Menu?): Boolean { // no op return false } override fun onDestroyActionMode(p0: ActionMode?) { // no op } override fun onHomeButtonClicked() { // no op } protected abstract val pageName: String? companion object { const val LOG_TAG = "MimiActivity" private const val LOG_DEBUG = false private const val TAG_NAV_DRAWER = "nav_drawer" const val VIEWING_NONE = 0 const val VIEWING_BOOKMARKS = 1 const val VIEWING_HISTORY = 2 const val SETTINGS_ID = 10 const val RESTART_ACTIVITY_RESULT = 2 } }
apache-2.0
f0850296ba18916bf1fbd4d6a18a74f9
35.19883
140
0.623718
4.869788
false
false
false
false
ojacquemart/spring-kotlin-euro-bets
src/main/kotlin/org/ojacquemart/eurobets/firebase/management/table/Bet.kt
2
603
package org.ojacquemart.eurobets.firebase.management.table import com.fasterxml.jackson.annotation.JsonIgnoreProperties import org.ojacquemart.eurobets.firebase.management.match.ScoreGap import org.ojacquemart.eurobets.firebase.support.ScoreType @JsonIgnoreProperties(ignoreUnknown = true) data class Bet(val homeGoals: Int = -1, val awayGoals: Int = -1, val feelingLucky: Boolean = false, val timestamp: Long = -1) { fun getScoreType() = ScoreType.toScoreType(homeGoals, awayGoals) fun getScoreGap() = ScoreGap.toScoreGap(homeGoals, awayGoals) }
unlicense
3d5c1018d1520fbe6b73597d308c1503
39.2
68
0.739635
4.246479
false
false
false
false
ivan-osipov/Clabo
src/main/kotlin/com/github/ivan_osipov/clabo/api/output/dto/EditMessageReplyMarkupParams.kt
1
1000
package com.github.ivan_osipov.clabo.api.output.dto import com.github.ivan_osipov.clabo.api.input.toJson import com.github.ivan_osipov.clabo.api.model.HasEditableReplyMarkup import com.github.ivan_osipov.clabo.api.model.InlineKeyboardMarkup import com.github.ivan_osipov.clabo.utils.ChatId import com.github.ivan_osipov.clabo.utils.MessageId class EditMessageReplyMarkupParams : OutputParams, HasEditableReplyMarkup<InlineKeyboardMarkup> { override var chatId: ChatId? = null var messageId: MessageId? = null var inlineMessageId: MessageId? = null override var replyMarkup: InlineKeyboardMarkup? = null override val queryId: String get() = Queries.EDIT_MESSAGE_REPLY_MARKUP override fun toListOfPairs(): List<Pair<String, *>> { return listOf( "chat_id" to chatId, "message_id" to messageId, "inline_message_id" to inlineMessageId, "reply_markup" to replyMarkup.toJson() ) } }
apache-2.0
9605a2e5653d764ad12324af38506da6
31.290323
97
0.708
3.952569
false
false
false
false
werelord/nullpod
nullpodApp/src/main/kotlin/com/cyrix/nullpod/NullpodManager.kt
1
19196
/** * NullpodManager * * Copyright 2017 Joel Braun * * This file is part of nullPod. * * nullPod 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. * * nullPod 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 nullPod. If not, see <http://www.gnu.org/licenses/>. */ package com.cyrix.nullpod import android.content.Context import android.media.MediaMetadataRetriever import android.webkit.URLUtil import android.widget.TextView import com.cyrix.nullpod.data.FeedImageCache import com.cyrix.nullpod.data.PodcastFeed import com.cyrix.nullpod.data.PodcastTrack import com.cyrix.util.* import kotlinx.coroutines.experimental.CommonPool import kotlinx.coroutines.experimental.async import kotlinx.coroutines.experimental.launch import java.io.File import java.text.SimpleDateFormat import java.util.* @Suppress("EXPERIMENTAL_FEATURE_WARNING") class NullpodManager constructor(ctx: Context) { private val log = CxLogger<NullpodManager>() private val db: NullpodDb = NullpodDb(ctx) private val imgPath: String private val tracksPath: String private val _net by lazy { Network() } private val _nullpodPlayer: NullpodPlayer val playlist: List<PodcastTrack> get() { return db.playlist } //var errorHandler: ErrorHandler? by WeakDelegate<ErrorHandler>(null) val feedImageCache = FeedImageCache() // testing, see if this works.. private val _playerListener = object : NullpodPlayer.PlayerListener { override fun onPlayStarted() { log.function() } override fun onPlayPaused() { log.function() // todo: commit current progress to db } override fun onTrackFinished() { log.function() // todo: commit current progress to db } override fun onInterval(progressMs: Long) { log.function("progress: $progressMs") // todo: update current track with current progress } } //--------------------------------------------------------------------------- init { val imgDir = File(ctx.filesDir, "img/") imgPath = imgDir.path log.debug { "shit ${imgDir.path}" } if (imgDir.exists() == false) { log.debug { "creating ${imgDir.path}" } imgDir.mkdirs() } val trackDir = File(ctx.filesDir, "tracks/") tracksPath = trackDir.path log.debug { "shit ${trackDir.path}" } if (trackDir.exists() == false) { log.debug { "creating ${trackDir.path}" } trackDir.mkdirs() } _nullpodPlayer = NullpodPlayer(ctx) // add this as a listener target _nullpodPlayer.addListener(_playerListener) } //--------------------------------------------------------------------------- private companion object { // todo: config object, store in objbox var deleteAfterListening = true } suspend fun commitPlaylistAsync() = db.commitConfigAsync() fun attachDebugTV(tv: TextView) = _nullpodPlayer.attachDebugTV(tv) fun detachDebugTV() = _nullpodPlayer.detachDebugTV() fun addPlayerListener(l: NullpodPlayer.PlayerListener) = _nullpodPlayer.addListener(l) fun removePlayerListener(l: NullpodPlayer.PlayerListener) = _nullpodPlayer.removeListener(l) fun togglePlayback() = _nullpodPlayer.togglePlayback(getCurrentTrack()) fun releasePlayer() { _nullpodPlayer.removeListener(_playerListener) // todo: release player } //--------------------------------------------------------------------------- suspend fun addFeed(url: String) = async<PodcastFeed?>(CommonPool) { log.function() try { val dbFeed = db.getFeed(url = url).await() log.debug { "dbfeed = $dbFeed" } assert (dbFeed.id > 0) { "Id is zero; has the object been inserted??" } updateFeed(dbFeed).await() return@async dbFeed } catch (e: Exception) { log.error("caught unhandled exception; do multiple entries exist?", e) return@async null } } //--------------------------------------------------------------------------- suspend fun updateAllFeeds() { log.function() db.getAllFeeds().await().forEach { updateFeed(it) } } //--------------------------------------------------------------------------- suspend fun updateFeed(feed: PodcastFeed) = async(CommonPool) { try { val parsedTracks = refreshFeed(feed) log.debug { "after refresh: $feed" } // make sure feed image updated if (checkUpdateFeedImage(feed)) { log.debug { "Feed image updated!!" } } val newTrackList = mutableListOf<PodcastTrack>() // check to see what tracks were not in before parsedTracks.forEach { newTrack -> val idx = feed.trackList.indexOf(newTrack) if (idx < 0) { log.debug { "new track found: $newTrack" } feed.trackList.add(newTrack) // todo: shit not working here newTrackList.add(newTrack) } else { val oldtrack = feed.trackList[idx] // possible duplicate; check date to determine if we need to update if (oldtrack.pubDate.after(newTrack.pubDate)) { log.debug { "old track (${oldtrack.pubDate} newer than \"new\" track (${newTrack.pubDate}); not adding" } } else if (oldtrack.equalsCompareDeep(newTrack) == false) { log.debug { "oldTrack:$oldtrack" } log.debug { "newTrack:$newTrack" } // future: this seems over-complicated.. instead, grab existing track and read directly from xml maybe?? log.debug { "cloning possible updated info from newtrack" } oldtrack.cloneFrom(newTrack) // } else { // log.debug { "old track duplicate of new track.. no-op" } } } } // update feed in db, regardless of changes db.updateFeedAsync(feed).await() for (i in newTrackList.indices) { log.debug { "$i: ${newTrackList[i]}" } } // add new tracks to current playlist, sorting first log.debug { "before sort: $newTrackList" } newTrackList.sortBy { it.pubDate } log.debug { "after sort: $newTrackList" } db.playlist.addAll(newTrackList) db.commitConfigAsync() checkDownloadedTracksAsync() } catch (e: Exception) { log.error("caught unhandled exception!", e) } } //--------------------------------------------------------------------------- suspend fun markTrackCompleted(track: PodcastTrack) = async(CommonPool) { log.function() track.completed = true db.updateTrack(track) db.config.playlist.remove(track) db.commitConfigAsync() } fun getCurrentTrack() : PodcastTrack { // todo: check if playlist is empty return playlist[0] } suspend fun dumpDatabase() = launch(CommonPool) { db.dumpDatabase() } suspend fun nukeDatabase() = launch(CommonPool) { db.nukeDatabase() // todo: nuking database should remove downloaded files.. } //--------------------------------------------------------------------------- suspend private fun refreshFeed(feed: PodcastFeed): MutableList<PodcastTrack> { // logtry shit not working, bah try { log.function() val xml = _net.fetchStringAsync(feed.url).await() return parseFeed(feed, xml) } catch (e: Exception) { log.error("caught unhandled exception!", e) return mutableListOf() } } //--------------------------------------------------------------------------- private fun parseFeed(feed: PodcastFeed, xml: String): MutableList<PodcastTrack> { log.function() val newTracks = mutableListOf<PodcastTrack>() if (xml.isEmpty()) return newTracks logTry(log, { val formatter = SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzzzz", Locale.US) val parser = XmlParser(xml) parser.processXml( onStartTag = { tag -> //log.debug { "processFeed onStartTag, Start $tag"} when (tag.toLowerCase()) { "rss", "channel" -> { } // we're already parsing rss and channel here "item" -> { // recursive call on item node val track = PodcastTrack() parser.processXml(tag, onTagAttribute = { trackTag, attrName, attrValue -> if (trackTag.equals("enclosure", ignoreCase = true)) { when (attrName.toLowerCase()) { "url" -> track.enclosureUrl = attrValue "length" -> track.enclosureLength = attrValue.toLong() "type" -> track.enclosureType = attrValue } } }, onText = {trackTag, text -> when (trackTag.toLowerCase()) { "title" -> track.title = text "pubdate" -> { // parse the date try { track.pubDate = formatter.parse(text) } catch (e: Exception) { log.warn("Error parsing date: ", e) } } "description" -> track.description = text } }) // node finished at this point newTracks.add(track) } "image" -> { // recursive call on image node parser.processXml(tag, onText = { imageTag, text -> when (imageTag.toLowerCase()) { "url" -> { feed.imageUrl = text // todo: update image file path right away?? } "title" -> feed.imageTitle = text "link" -> feed.imageLink = text //else -> log.warn{ "image: parser text unhandled, tag:$tag, text:$text" } } }) } //else -> { log.warn{ "parser tag unhandled: $tag" } } } }, // onEndTag = { tag -> // log.debug { "processFeed onEndTag, End $tag" } // }, onText = { tag, text -> //log.debug { "processFeed onText, tag: $tag, text: $text"} when (tag.toLowerCase()) { "title" -> feed.title = text "link" -> feed.link = text "description" -> feed.description = text //else -> log.warn{ "parser text unhandled, tag: $tag, text: $text" } } } ) }) log.debug { "parsed: $feed" } log.debug { "parsed tracks: ${newTracks.size}"} // processing successful return newTracks } //--------------------------------------------------------------------------- suspend private fun checkUpdateFeedImage(feed: PodcastFeed): Boolean { // logtry shit not working, bah try { log.function() if (feed.imageUrl.isBlank()) return false // make sure the paths are set if (feed.imageFilePath.isNullOrEmpty()) { val filename = "${feed.id}.${URLUtil.guessFileName(feed.imageUrl, null, null)}" feed.imageFilePath = File(imgPath, filename).path } log.debug { "imagefile: ${feed.imageFilePath}" } // committing to db db.updateFeedAsync(feed) // see if original is downloaded val imgFile = File(feed.imageFilePath) log.debug { "image file: $imgFile, exists = ${imgFile.exists()}" } launch(CommonPool) { if (imgFile.exists() == false) { // download and save file if ((_net.fetchToFile(feed.imageUrl, imgFile).await()) && (imgFile.exists())) { // download successful; update database with the image file name log.debug{"file downloaded and exists, updating database"} } else { log.warn { "Failed to download image file: ${feed.imageUrl}" } } // file should be downloaded log.debug { "image file: ${imgFile.path}, exists = ${imgFile.exists()}" } } } return true } catch (e: Exception) { log.error("caught unhandled exception!", e) return false } } //--------------------------------------------------------------------------- suspend fun checkDownloadedTracksAsync() = async(CommonPool) { log.function() try { val downloadPlaylist = playlist.subList(0, minOf(playlist.size, db.config.maxDownloadedTracks)) log.debug { "download playlist (limit ${db.config.maxDownloadedTracks}, actual ${downloadPlaylist.size}):$downloadPlaylist" } downloadPlaylist.forEach { track -> if (track.filepath.isEmpty()) { val trackName = "${track.feed.targetId}.${track.id}.${URLUtil.guessFileName(track.enclosureUrl, null, null)}" track.filepath = File(tracksPath, trackName).path log.debug { "updating track ${track.id} filepath: $${track.filepath}" } db.updateTrack(track) } val trackFile = File(track.filepath) if (trackFile.exists() == false) { log.debug { "track file: $trackFile, exists = ${trackFile.exists()}" } log.debug { "downloading track ${trackFile.name}" } // download and save file //log.debug { "downloading file ${track.enclosureUrl} to $trackFile" } if (_net.fetchToFile(track.enclosureUrl, trackFile).await() && (trackFile.exists())) { log.debug{"file downloaded and exists"} // todo: notify download updateMetaData(track) } else { // todo: what to do in download error?? } } } } catch (e: Exception) { log.error("caught unhandled exception!", e) } } //--------------------------------------------------------------------------- suspend fun updateMetaData(track: PodcastTrack) = launch(CommonPool) { log.function() try { val mmr = MediaMetadataRetriever() mmr.use { it.setDataSource(track.filepath) // right now, just get duration track.durationMs = (it.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION)).toLong() /* log.debug { track.filepath } log.debug { track.enclosureUrl } log.debug { track.enclosureLength } log.debug { "\t${it.extractMetadata(MediaMetadataRetriever.METADATA_KEY_ALBUM)}" } log.debug { "\t${it.extractMetadata(MediaMetadataRetriever.METADATA_KEY_ALBUMARTIST)}" } log.debug { "\t${it.extractMetadata(MediaMetadataRetriever.METADATA_KEY_ARTIST)}" } log.debug { "\t${it.extractMetadata(MediaMetadataRetriever.METADATA_KEY_AUTHOR)}" } log.debug { "\t${it.extractMetadata(MediaMetadataRetriever.METADATA_KEY_BITRATE)}" } log.debug { "\t${it.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DATE)}" } log.debug { "\tduration: ${it.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION)}" } val durationMs = (it.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION)).toLong() log.debug { "\t\t$durationMs ms" } val h = TimeUnit.MILLISECONDS.toHours(durationMs) val m = TimeUnit.MILLISECONDS.toMinutes(durationMs) % TimeUnit.HOURS.toMinutes(1) val s = TimeUnit.MILLISECONDS.toSeconds(durationMs) % TimeUnit.MINUTES.toSeconds(1) log.debug { "\t\t\t%d:%02d:%02d".format(h, m, s) } log.debug { "\t${it.extractMetadata(MediaMetadataRetriever.METADATA_KEY_GENRE)}" } log.debug { "\t${it.extractMetadata(MediaMetadataRetriever.METADATA_KEY_MIMETYPE)}" } log.debug { "\t${it.extractMetadata(MediaMetadataRetriever.METADATA_KEY_TITLE)}" } */ } // todo: can we get metadata from exoplayer?? db.updateTrack(track) } catch (e: Exception) { log.error("caught unhandled exception!", e) } } }
gpl-3.0
a5d397e873b1da0ed8016603402d043c
40.283871
137
0.486195
5.35304
false
false
false
false
vondear/RxTools
RxKit/src/main/java/com/tamsiree/rxkit/RxTextTool.kt
1
14748
package com.tamsiree.rxkit import android.graphics.Bitmap import android.graphics.BlurMaskFilter import android.graphics.BlurMaskFilter.Blur import android.graphics.Typeface import android.graphics.drawable.Drawable import android.net.Uri import android.text.Layout import android.text.SpannableStringBuilder import android.text.Spanned import android.text.style.* import android.widget.TextView import androidx.annotation.ColorInt import androidx.annotation.DrawableRes /** * @author tamsiree * @date 2016/12/23 */ object RxTextTool { /** * ่Žทๅ–ๅปบ้€ ่€… * * @param text ๆ ทๅผๅญ—็ฌฆไธฒๆ–‡ๆœฌ * @return [Builder] */ @JvmStatic fun getBuilder(text: CharSequence): Builder { return Builder(text) } class Builder internal constructor(private var text: CharSequence) { private val defaultValue = 0x12000000 private var flag: Int @ColorInt private var foregroundColor: Int @ColorInt private var backgroundColor: Int @ColorInt private var quoteColor: Int private var isLeadingMargin = false private var first = 0 private var rest = 0 private var isBullet = false private var gapWidth = 0 private var bulletColor = 0 private var proportion: Float private var xProportion: Float private var isStrikethrough = false private var isUnderline = false private var isSuperscript = false private var isSubscript = false private var isBold = false private var isItalic = false private var isBoldItalic = false private var fontFamily: String? = null private var align: Layout.Alignment? = null private var imageIsBitmap = false private var bitmap: Bitmap? = null private var imageIsDrawable = false private var drawable: Drawable? = null private var imageIsUri = false private var uri: Uri? = null private var imageIsResourceId = false @DrawableRes private var resourceId = 0 private var clickSpan: ClickableSpan? = null private var url: String? = null private var isBlur = false private var radius = 0f private var style: Blur? = null private val mBuilder: SpannableStringBuilder /** * ่ฎพ็ฝฎๆ ‡่ฏ† * * @param flag * * [Spanned.SPAN_INCLUSIVE_EXCLUSIVE] * * [Spanned.SPAN_INCLUSIVE_INCLUSIVE] * * [Spanned.SPAN_EXCLUSIVE_EXCLUSIVE] * * [Spanned.SPAN_EXCLUSIVE_INCLUSIVE] * * @return [Builder] */ fun setFlag(flag: Int): Builder { this.flag = flag return this } /** * ่ฎพ็ฝฎๅ‰ๆ™ฏ่‰ฒ * * @param color ๅ‰ๆ™ฏ่‰ฒ * @return [Builder] */ fun setForegroundColor(@ColorInt color: Int): Builder { foregroundColor = color return this } /** * ่ฎพ็ฝฎ่ƒŒๆ™ฏ่‰ฒ * * @param color ่ƒŒๆ™ฏ่‰ฒ * @return [Builder] */ fun setBackgroundColor(@ColorInt color: Int): Builder { backgroundColor = color return this } /** * ่ฎพ็ฝฎๅผ•็”จ็บฟ็š„้ขœ่‰ฒ * * @param color ๅผ•็”จ็บฟ็š„้ขœ่‰ฒ * @return [Builder] */ fun setQuoteColor(@ColorInt color: Int): Builder { quoteColor = color return this } /** * ่ฎพ็ฝฎ็ผฉ่ฟ› * * @param first ้ฆ–่กŒ็ผฉ่ฟ› * @param rest ๅ‰ฉไฝ™่กŒ็ผฉ่ฟ› * @return [Builder] */ fun setLeadingMargin(first: Int, rest: Int): Builder { this.first = first this.rest = rest isLeadingMargin = true return this } /** * ่ฎพ็ฝฎๅˆ—่กจๆ ‡่ฎฐ * * @param gapWidth ๅˆ—่กจๆ ‡่ฎฐๅ’Œๆ–‡ๅญ—้—ด่ท็ฆป * @param color ๅˆ—่กจๆ ‡่ฎฐ็š„้ขœ่‰ฒ * @return [Builder] */ fun setBullet(gapWidth: Int, color: Int): Builder { this.gapWidth = gapWidth bulletColor = color isBullet = true return this } /** * ่ฎพ็ฝฎๅญ—ไฝ“ๆฏ”ไพ‹ * * @param proportion ๆฏ”ไพ‹ * @return [Builder] */ fun setProportion(proportion: Float): Builder { this.proportion = proportion return this } /** * ่ฎพ็ฝฎๅญ—ไฝ“ๆจชๅ‘ๆฏ”ไพ‹ * * @param proportion ๆฏ”ไพ‹ * @return [Builder] */ fun setXProportion(proportion: Float): Builder { xProportion = proportion return this } /** * ่ฎพ็ฝฎๅˆ ้™ค็บฟ * * @return [Builder] */ fun setStrikethrough(): Builder { isStrikethrough = true return this } /** * ่ฎพ็ฝฎไธ‹ๅˆ’็บฟ * * @return [Builder] */ fun setUnderline(): Builder { isUnderline = true return this } /** * ่ฎพ็ฝฎไธŠๆ ‡ * * @return [Builder] */ fun setSuperscript(): Builder { isSuperscript = true return this } /** * ่ฎพ็ฝฎไธ‹ๆ ‡ * * @return [Builder] */ fun setSubscript(): Builder { isSubscript = true return this } /** * ่ฎพ็ฝฎ็ฒ—ไฝ“ * * @return [Builder] */ fun setBold(): Builder { isBold = true return this } /** * ่ฎพ็ฝฎๆ–œไฝ“ * * @return [Builder] */ fun setItalic(): Builder { isItalic = true return this } /** * ่ฎพ็ฝฎ็ฒ—ๆ–œไฝ“ * * @return [Builder] */ fun setBoldItalic(): Builder { isBoldItalic = true return this } /** * ่ฎพ็ฝฎๅญ—ไฝ“ * * @param fontFamily ๅญ—ไฝ“ * * * monospace * * serif * * sans-serif * * @return [Builder] */ fun setFontFamily(fontFamily: String?): Builder { this.fontFamily = fontFamily return this } /** * ่ฎพ็ฝฎๅฏน้ฝ * * @param align ๅฏนๅ…ถๆ–นๅผ * * * [Alignment.ALIGN_NORMAL]ๆญฃๅธธ * * [Alignment.ALIGN_OPPOSITE]็›ธๅ * * [Alignment.ALIGN_CENTER]ๅฑ…ไธญ * * @return [Builder] */ fun setAlign(align: Layout.Alignment?): Builder { this.align = align return this } /** * ่ฎพ็ฝฎๅ›พ็‰‡ * * @param bitmap ๅ›พ็‰‡ไฝๅ›พ * @return [Builder] */ fun setBitmap(bitmap: Bitmap): Builder { this.bitmap = bitmap imageIsBitmap = true return this } /** * ่ฎพ็ฝฎๅ›พ็‰‡ * * @param drawable ๅ›พ็‰‡่ต„ๆบ * @return [Builder] */ fun setDrawable(drawable: Drawable): Builder { this.drawable = drawable imageIsDrawable = true return this } /** * ่ฎพ็ฝฎๅ›พ็‰‡ * * @param uri ๅ›พ็‰‡uri * @return [Builder] */ fun setUri(uri: Uri): Builder { this.uri = uri imageIsUri = true return this } /** * ่ฎพ็ฝฎๅ›พ็‰‡ * * @param resourceId ๅ›พ็‰‡่ต„ๆบid * @return [Builder] */ fun setResourceId(@DrawableRes resourceId: Int): Builder { this.resourceId = resourceId imageIsResourceId = true return this } /** * ่ฎพ็ฝฎ็‚นๅ‡ปไบ‹ไปถ * * ้œ€ๆทปๅŠ view.setMovementMethod(LinkMovementMethod.getInstance()) * * @param clickSpan ็‚นๅ‡ปไบ‹ไปถ * @return [Builder] */ fun setClickSpan(clickSpan: ClickableSpan): Builder { this.clickSpan = clickSpan return this } /** * ่ฎพ็ฝฎ่ถ…้“พๆŽฅ * * ้œ€ๆทปๅŠ view.setMovementMethod(LinkMovementMethod.getInstance()) * * @param url ่ถ…้“พๆŽฅ * @return [Builder] */ fun setUrl(url: String): Builder { this.url = url return this } /** * ่ฎพ็ฝฎๆจก็ณŠ * * ๅฐšๅญ˜bug๏ผŒๅ…ถไป–ๅœฐๆ–นๅญ˜ๅœจ็›ธๅŒ็š„ๅญ—ไฝ“็š„่ฏ๏ผŒ็›ธๅŒๅญ—ไฝ“ๅ‡บ็Žฐๅœจไน‹ๅ‰็š„่ฏ้‚ฃไนˆๅฐฑไธไผšๆจก็ณŠ๏ผŒๅ‡บ็Žฐๅœจไน‹ๅŽ็š„่ฏ้‚ฃไผšไธ€่ตทๆจก็ณŠ * * ๆŽจ่่ฟ˜ๆ˜ฏๆŠŠๆ‰€ๆœ‰ๅญ—ไฝ“้ƒฝๆจก็ณŠ่ฟ™ๆ ทไฝฟ็”จ * * @param radius ๆจก็ณŠๅŠๅพ„๏ผˆ้œ€ๅคงไบŽ0๏ผ‰ * @param style ๆจก็ณŠๆ ทๅผ * * [Blur.NORMAL] * * [Blur.SOLID] * * [Blur.OUTER] * * [Blur.INNER] * * @return [Builder] */ fun setBlur(radius: Float, style: Blur?): Builder { this.radius = radius this.style = style isBlur = true return this } /** * ่ฟฝๅŠ ๆ ทๅผๅญ—็ฌฆไธฒ * * @param text ๆ ทๅผๅญ—็ฌฆไธฒๆ–‡ๆœฌ * @return [Builder] */ fun append(text: CharSequence): Builder { setSpan() this.text = text return this } /** * ๅˆ›ๅปบๆ ทๅผๅญ—็ฌฆไธฒ * * @return ๆ ทๅผๅญ—็ฌฆไธฒ */ fun create(): SpannableStringBuilder { setSpan() return mBuilder } fun into(textView: TextView?) { setSpan() if (textView != null) { textView.text = mBuilder } } /** * ่ฎพ็ฝฎๆ ทๅผ */ private fun setSpan() { val start = mBuilder.length mBuilder.append(text) val end = mBuilder.length if (foregroundColor != defaultValue) { mBuilder.setSpan(ForegroundColorSpan(foregroundColor), start, end, flag) foregroundColor = defaultValue } if (backgroundColor != defaultValue) { mBuilder.setSpan(BackgroundColorSpan(backgroundColor), start, end, flag) backgroundColor = defaultValue } if (isLeadingMargin) { mBuilder.setSpan(LeadingMarginSpan.Standard(first, rest), start, end, flag) isLeadingMargin = false } if (quoteColor != defaultValue) { mBuilder.setSpan(QuoteSpan(quoteColor), start, end, 0) quoteColor = defaultValue } if (isBullet) { mBuilder.setSpan(BulletSpan(gapWidth, bulletColor), start, end, 0) isBullet = false } if (proportion != -1f) { mBuilder.setSpan(RelativeSizeSpan(proportion), start, end, flag) proportion = -1f } if (xProportion != -1f) { mBuilder.setSpan(ScaleXSpan(xProportion), start, end, flag) xProportion = -1f } if (isStrikethrough) { mBuilder.setSpan(StrikethroughSpan(), start, end, flag) isStrikethrough = false } if (isUnderline) { mBuilder.setSpan(UnderlineSpan(), start, end, flag) isUnderline = false } if (isSuperscript) { mBuilder.setSpan(SuperscriptSpan(), start, end, flag) isSuperscript = false } if (isSubscript) { mBuilder.setSpan(SubscriptSpan(), start, end, flag) isSubscript = false } if (isBold) { mBuilder.setSpan(StyleSpan(Typeface.BOLD), start, end, flag) isBold = false } if (isItalic) { mBuilder.setSpan(StyleSpan(Typeface.ITALIC), start, end, flag) isItalic = false } if (isBoldItalic) { mBuilder.setSpan(StyleSpan(Typeface.BOLD_ITALIC), start, end, flag) isBoldItalic = false } if (fontFamily != null) { mBuilder.setSpan(TypefaceSpan(fontFamily), start, end, flag) fontFamily = null } if (align != null) { mBuilder.setSpan(AlignmentSpan.Standard(align!!), start, end, flag) align = null } if (imageIsBitmap || imageIsDrawable || imageIsUri || imageIsResourceId) { if (imageIsBitmap) { mBuilder.setSpan(ImageSpan(RxTool.getContext(), bitmap!!), start, end, flag) bitmap = null imageIsBitmap = false } else if (imageIsDrawable) { mBuilder.setSpan(ImageSpan(drawable!!), start, end, flag) drawable = null imageIsDrawable = false } else if (imageIsUri) { mBuilder.setSpan(ImageSpan(RxTool.getContext(), uri!!), start, end, flag) uri = null imageIsUri = false } else { mBuilder.setSpan(ImageSpan(RxTool.getContext(), resourceId), start, end, flag) resourceId = 0 imageIsResourceId = false } } if (clickSpan != null) { mBuilder.setSpan(clickSpan, start, end, flag) clickSpan = null } if (url != null) { mBuilder.setSpan(URLSpan(url), start, end, flag) url = null } if (isBlur) { mBuilder.setSpan(MaskFilterSpan(BlurMaskFilter(radius, style)), start, end, flag) isBlur = false } flag = Spanned.SPAN_EXCLUSIVE_EXCLUSIVE } init { flag = Spanned.SPAN_EXCLUSIVE_EXCLUSIVE foregroundColor = defaultValue backgroundColor = defaultValue quoteColor = defaultValue proportion = -1f xProportion = -1f mBuilder = SpannableStringBuilder() } } }
apache-2.0
fa51259f0dbdc1e192e466a0cede1d46
26.092131
98
0.480587
5.033524
false
false
false
false
ToxicBakery/ViewPagerTransforms
library/src/main/java/com/ToxicBakery/viewpager/transforms/DepthPageTransformer.kt
1
1403
/* * Copyright 2014 Toxic Bakery * * 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.ToxicBakery.viewpager.transforms import android.view.View open class DepthPageTransformer : ABaseTransformer() { override val isPagingEnabled: Boolean get() = true override fun onTransform(page: View, position: Float) { if (position <= 0f) { page.translationX = 0f page.scaleX = 1f page.scaleY = 1f } else if (position <= 1f) { val scaleFactor = MIN_SCALE + (1 - MIN_SCALE) * (1 - Math.abs(position)) page.alpha = 1 - position page.pivotY = 0.5f * page.height page.translationX = page.width * -position page.scaleX = scaleFactor page.scaleY = scaleFactor } } companion object { private const val MIN_SCALE = 0.75f } }
apache-2.0
e8c9d7d0c00791dafb0c0e356e43836b
30.177778
84
0.644334
4.126471
false
false
false
false
vanita5/twittnuker
twittnuker/src/main/kotlin/de/vanita5/twittnuker/util/database/SuggestionsCursorCreator.kt
1
12747
/* * Twittnuker - Twitter client for Android * * Copyright (C) 2013-2017 vanita5 <[email protected]> * * This program incorporates a modified version of Twidere. * Copyright (C) 2012-2017 Mariotaku Lee <[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 de.vanita5.twittnuker.util.database import android.database.Cursor import android.database.MatrixCursor import android.database.MergeCursor import android.net.Uri import android.text.TextUtils import org.mariotaku.ktextension.mapToArray import org.mariotaku.sqliteqb.library.Columns import org.mariotaku.sqliteqb.library.Expression import org.mariotaku.sqliteqb.library.OrderBy import org.mariotaku.sqliteqb.library.SQLConstants import de.vanita5.twittnuker.TwittnukerConstants.* import de.vanita5.twittnuker.model.UserKey import de.vanita5.twittnuker.provider.TwidereDataStore.* import de.vanita5.twittnuker.util.SQLiteDatabaseWrapper import de.vanita5.twittnuker.util.UserColorNameManager import de.vanita5.twittnuker.util.Utils import java.util.regex.Pattern object SuggestionsCursorCreator { private val PATTERN_SCREEN_NAME = Pattern.compile("(?i)[@\uFF20]?([a-z0-9_]{1,20})") private val historyProjectionMap = mapOf( Suggestions._ID to Columns.Column(SearchHistory._ID, Suggestions._ID).sql, Suggestions.TYPE to Columns.Column("'${Suggestions.Search.TYPE_SEARCH_HISTORY}'", Suggestions.TYPE).sql, Suggestions.TITLE to Columns.Column(SearchHistory.QUERY, Suggestions.TITLE).sql, Suggestions.SUMMARY to Columns.Column(SQLConstants.NULL, Suggestions.SUMMARY).sql, Suggestions.ICON to Columns.Column(SQLConstants.NULL, Suggestions.ICON).sql, Suggestions.EXTRA_ID to Columns.Column("0", Suggestions.EXTRA_ID).sql, Suggestions.EXTRA to Columns.Column(SQLConstants.NULL, Suggestions.EXTRA).sql, Suggestions.VALUE to Columns.Column(SearchHistory.QUERY, Suggestions.VALUE).sql ) private val savedSearchesProjectionMap = mapOf(Suggestions._ID to Columns.Column(SavedSearches._ID, Suggestions._ID).sql, Suggestions.TYPE to Columns.Column("'${Suggestions.Search.TYPE_SAVED_SEARCH}'", Suggestions.TYPE).sql, Suggestions.TITLE to Columns.Column(SavedSearches.QUERY, Suggestions.TITLE).sql, Suggestions.SUMMARY to Columns.Column(SQLConstants.NULL, Suggestions.SUMMARY).sql, Suggestions.ICON to Columns.Column(SQLConstants.NULL, Suggestions.ICON).sql, Suggestions.EXTRA_ID to Columns.Column("0", Suggestions.EXTRA_ID).sql, Suggestions.EXTRA to Columns.Column(SQLConstants.NULL, Suggestions.EXTRA).sql, Suggestions.VALUE to Columns.Column(SavedSearches.QUERY, Suggestions.VALUE).sql ) private val suggestionUsersProjectionMap = mapOf(Suggestions._ID to Columns.Column(CachedUsers._ID, Suggestions._ID).sql, Suggestions.TYPE to Columns.Column("'${Suggestions.Search.TYPE_USER}'", Suggestions.TYPE).sql, Suggestions.TITLE to Columns.Column(CachedUsers.NAME, Suggestions.TITLE).sql, Suggestions.SUMMARY to Columns.Column(CachedUsers.SCREEN_NAME, Suggestions.SUMMARY).sql, Suggestions.ICON to Columns.Column(CachedUsers.PROFILE_IMAGE_URL, Suggestions.ICON).sql, Suggestions.EXTRA_ID to Columns.Column(CachedUsers.USER_KEY, Suggestions.EXTRA_ID).sql, Suggestions.EXTRA to Columns.Column(SQLConstants.NULL, Suggestions.EXTRA).sql, Suggestions.VALUE to Columns.Column(CachedUsers.SCREEN_NAME, Suggestions.VALUE).sql ) private val autoCompleteUsersProjectionMap = mapOf(Suggestions._ID to Columns.Column(CachedUsers._ID, Suggestions._ID).sql, Suggestions.TYPE to Columns.Column("'${Suggestions.AutoComplete.TYPE_USERS}'", Suggestions.TYPE).sql, Suggestions.TITLE to Columns.Column(CachedUsers.NAME, Suggestions.TITLE).sql, Suggestions.SUMMARY to Columns.Column(CachedUsers.SCREEN_NAME, Suggestions.SUMMARY).sql, Suggestions.ICON to Columns.Column(CachedUsers.PROFILE_IMAGE_URL, Suggestions.ICON).sql, Suggestions.EXTRA_ID to Columns.Column(CachedUsers.USER_KEY, Suggestions.EXTRA_ID).sql, Suggestions.EXTRA to Columns.Column(SQLConstants.NULL, Suggestions.EXTRA).sql, Suggestions.VALUE to Columns.Column(CachedUsers.SCREEN_NAME, Suggestions.VALUE).sql ) private val hashtagsProjectionMap = mapOf(Suggestions._ID to Columns.Column(CachedHashtags._ID, Suggestions._ID).sql, Suggestions.TYPE to Columns.Column("'${Suggestions.AutoComplete.TYPE_HASHTAGS}'", Suggestions.TYPE).sql, Suggestions.TITLE to Columns.Column(CachedHashtags.NAME, Suggestions.TITLE).sql, Suggestions.SUMMARY to Columns.Column(SQLConstants.NULL, Suggestions.SUMMARY).sql, Suggestions.ICON to Columns.Column(SQLConstants.NULL, Suggestions.ICON).sql, Suggestions.EXTRA_ID to Columns.Column("0", Suggestions.EXTRA_ID).sql, Suggestions.EXTRA to Columns.Column(SQLConstants.NULL, Suggestions.EXTRA).sql, Suggestions.VALUE to Columns.Column(CachedHashtags.NAME, Suggestions.VALUE).sql ) fun forSearch(db: SQLiteDatabaseWrapper, manager: UserColorNameManager, uri: Uri, projection: Array<String>?): Cursor? { val nonNullProjection = projection ?: Suggestions.COLUMNS val query = uri.getQueryParameter(QUERY_PARAM_QUERY) ?: return null val accountKey = uri.getQueryParameter(QUERY_PARAM_ACCOUNT_KEY)?.let(UserKey::valueOf) ?: return null val filterHost = uri.getQueryParameter(QUERY_PARAM_ACCOUNT_HOST) val filterType = uri.getQueryParameter(QUERY_PARAM_ACCOUNT_TYPE) val emptyQuery = TextUtils.isEmpty(query) val cursors = mutableListOf(getHistoryCursor(db, nonNullProjection, query)) if (emptyQuery) { cursors.add(getSavedSearchCursor(db, nonNullProjection, accountKey)) } else { val queryTrimmed = query.replace("_", "^_").substringAfter("@") val usersCursor = getUsersCursor(db, manager, nonNullProjection, accountKey, filterHost, filterType, query, queryTrimmed, 10) if (!usersCursor.hasName(queryTrimmed)) { val m = PATTERN_SCREEN_NAME.matcher(query) if (m.matches()) { val screenName = m.group(1) cursors.add(getScreenNameCursor(nonNullProjection, screenName)) } } cursors.add(usersCursor) } return MergeCursor(cursors.toTypedArray()) } fun forAutoComplete(db: SQLiteDatabaseWrapper, manager: UserColorNameManager, uri: Uri, projection: Array<String>?): Cursor? { val nonNullProjection = projection ?: Suggestions.COLUMNS val query = uri.getQueryParameter(QUERY_PARAM_QUERY) ?: return null val type = uri.getQueryParameter(QUERY_PARAM_TYPE) ?: return null val accountKey = uri.getQueryParameter(QUERY_PARAM_ACCOUNT_KEY)?.let(UserKey::valueOf) ?: return null val accountHost = uri.getQueryParameter(QUERY_PARAM_ACCOUNT_HOST) val accountType = uri.getQueryParameter(QUERY_PARAM_ACCOUNT_TYPE) val queryEscaped = query.replace("_", "^_") when (type) { Suggestions.AutoComplete.TYPE_USERS -> { val where = Expression.or( Expression.likeRaw(Columns.Column(CachedUsers.SCREEN_NAME), "?||'%'", "^"), Expression.likeRaw(Columns.Column(CachedUsers.NAME), "?||'%'", "^")) val whereArgs = arrayOf(queryEscaped, queryEscaped) val orderBy = arrayOf(CachedUsers.SCORE, CachedUsers.LAST_SEEN, CachedUsers.SCREEN_NAME, CachedUsers.NAME) val ascending = booleanArrayOf(false, false, true, true) val mappedProjection = nonNullProjection.mapToArray { autoCompleteUsersProjectionMap[it]!! } val (sql, bindingArgs) = CachedUsersQueryBuilder.withScore(mappedProjection, where, whereArgs, OrderBy(orderBy, ascending).sql, accountKey, accountHost, accountType, 0) return db.rawQuery(sql.sql, bindingArgs) } Suggestions.AutoComplete.TYPE_HASHTAGS -> { val where = Expression.likeRaw(Columns.Column(CachedHashtags.NAME), "?||'%'", "^") val whereArgs = arrayOf(queryEscaped) val mappedProjection = nonNullProjection.mapToArray { hashtagsProjectionMap[it] } return db.query(CachedHashtags.TABLE_NAME, mappedProjection, where.sql, whereArgs, null, null, null) } else -> return null } } private fun getUsersCursor(db: SQLiteDatabaseWrapper, manager: UserColorNameManager, projection: Array<String>, accountKey: UserKey, filterHost: String?, filterType: String?, query: String, queryTrimmed: String, limit: Int = 0): Cursor { val usersSelection = Expression.or( Expression.likeRaw(Columns.Column(CachedUsers.SCREEN_NAME), "?||'%'", "^"), Expression.likeRaw(Columns.Column(CachedUsers.NAME), "?||'%'", "^") ) val selectionArgs = arrayOf(queryTrimmed, queryTrimmed) val order = arrayOf(CachedUsers.LAST_SEEN, CachedUsers.SCORE, CachedUsers.SCREEN_NAME, CachedUsers.NAME) val ascending = booleanArrayOf(false, false, true, true) val orderBy = OrderBy(order, ascending) val usersProjection = projection.mapToArray { suggestionUsersProjectionMap[it]!! } val usersQuery = CachedUsersQueryBuilder.withScore(usersProjection, usersSelection, selectionArgs, orderBy.sql, accountKey, filterHost, filterType, limit) return db.rawQuery(usersQuery.first.sql, usersQuery.second) } private fun getSavedSearchCursor(db: SQLiteDatabaseWrapper, projection: Array<String>, accountKey: UserKey): Cursor { val savedSearchesWhere = Expression.equalsArgs(SavedSearches.ACCOUNT_KEY) val whereArgs = arrayOf(accountKey.toString()) val savedSearchesProjection = projection.mapToArray { savedSearchesProjectionMap[it] } return db.query(true, SavedSearches.TABLE_NAME, savedSearchesProjection, savedSearchesWhere.sql, whereArgs, null, null, SavedSearches.DEFAULT_SORT_ORDER, null) } private fun getHistoryCursor(db: SQLiteDatabaseWrapper, projection: Array<String>, query: String): Cursor { val queryEscaped = query.replace("_", "^_") val historySelection = Expression.likeRaw(Columns.Column(SearchHistory.QUERY), "?||'%'", "^") val historySelectionArgs = arrayOf(queryEscaped) val historyProjection = projection.mapToArray { historyProjectionMap[it] } val cursorLimit = if (TextUtils.isEmpty(query)) "3" else "2" return db.query(true, SearchHistory.TABLE_NAME, historyProjection, historySelection.sql, historySelectionArgs, null, null, SearchHistory.DEFAULT_SORT_ORDER, cursorLimit) } private fun getScreenNameCursor(projection: Array<String>, screenName: String): Cursor { fun mapSelectionToValue(column: String) = when (column) { Suggestions._ID -> "0" Suggestions.TYPE -> Suggestions.Search.TYPE_SCREEN_NAME Suggestions.TITLE -> screenName Suggestions.EXTRA_ID -> "0" Suggestions.VALUE -> screenName else -> null } val cursor = MatrixCursor(projection) cursor.addRow(projection.map(::mapSelectionToValue)) return cursor } private fun Cursor.hasName(queryTrimmed: String): Boolean { val valueIdx = getColumnIndex(Suggestions.VALUE) moveToFirst() while (!isAfterLast) { if (queryTrimmed.equals(getString(valueIdx), true)) { return true } moveToNext() } return false } }
gpl-3.0
0dcbd417985d118da64de7934ee26c01
55.657778
127
0.685495
4.802939
false
false
false
false
yoavst/quickwatchfaces
app/src/main/java/com/yoavst/quickcirclewatchfaces/Prefs.kt
1
1167
package com.yoavst.quickcirclewatchfaces import android.graphics.Color import com.chibatching.kotpref.KotprefModel import com.yoavst.kotlin.putStringSet import java.util.HashSet public object Prefs : KotprefModel() { override val kotprefName: String = "prefs" var clocks: Set<String> get() { return kotprefPreference.getStringSet("clocks", emptySet()) } set(value) { kotprefPreference.putStringSet("clocks", value) } var activeClockData by stringPrefVar("") var forceMinute by booleanPrefVar(false) var forceHideDate by booleanPrefVar(false) var forceDateGravity by stringPrefVar("") var forcedColorForDate by booleanPrefVar(false) var forcedDateColor by intPrefVar(Color.parseColor("#ff000000")) var forcedDateBackgroundColor by intPrefVar(Color.GRAY) var activeClock: Clock? get() { val data = activeClockData if (data == "") return null return Clock.parse(activeClockData) } set(value) { if (value == null) activeClockData = "" else activeClockData = value.toString() } }
apache-2.0
daaf09a6e4d5675652ed50ef58a0249e
30.567568
71
0.664953
4.540856
false
false
false
false
AlexLandau/semlang
kotlin/semlang-parser/src/main/kotlin/parser/writer.kt
1
13903
package net.semlang.parser import net.semlang.api.* import net.semlang.api.Annotation import net.semlang.api.Function import net.semlang.transforms.invalidate import java.io.StringWriter import java.io.Writer fun writeToString(module: ValidatedModule): String { val writer = StringWriter() write(module, writer) return writer.toString() } // TODO: Right now deterministicMode is defined just for fake0 versioning fun writeToString(context: RawContext, deterministicMode: Boolean = false): String { val writer = StringWriter() write(context, writer, deterministicMode) return writer.toString() } fun write(module: ValidatedModule, writer: Writer) { val context = invalidate(module) write(context, writer) } // TODO: Right now deterministicMode is defined just for fake0 versioning fun write(context: RawContext, writer: Writer, deterministicMode: Boolean = false) { Sem1Writer(writer, deterministicMode).write(context) } private class Sem1Writer(val writer: Writer, val deterministicMode: Boolean) { fun write(context: RawContext) { fun <T : HasId> maybeSort(list: List<T>): List<T> { return if (deterministicMode) { list.sortedWith(HasEntityIdComparator) } else { list } } for (struct in maybeSort(context.structs)) { write(struct) } for (union in maybeSort(context.unions)) { write(union) } for (function in maybeSort(context.functions)) { write(function) } } private fun write(struct: UnvalidatedStruct) { val newline = if (deterministicMode) "\n" else System.lineSeparator() writeAnnotations(struct.annotations) writer.append("struct ") .append(struct.id.toString()) if (struct.typeParameters.isNotEmpty()) { writer.append("<") .append(struct.typeParameters.joinToString(", ")) .append(">") } writer.append(" {$newline") for (member in struct.members) { writer.append(SINGLE_INDENTATION) .append(member.name) .append(": ") .append(member.type.toString() + newline) } val requires = struct.requires if (requires != null) { writer.append(SINGLE_INDENTATION) .append("requires {$newline") this.write(requires, 2) writer.append(SINGLE_INDENTATION) .append("}$newline") } writer.append("}$newline$newline") } private fun write(union: UnvalidatedUnion) { val newline = if (deterministicMode) "\n" else System.lineSeparator() writeAnnotations(union.annotations) writer.append("union ") .append(union.id.toString()) if (union.typeParameters.isNotEmpty()) { writer.append("<") .append(union.typeParameters.joinToString(", ")) .append(">") } writer.append(" {$newline") for (option in union.options) { val type = option.type if (type == null) { writer.append(SINGLE_INDENTATION) .append(option.name + newline) } else { writer.append(SINGLE_INDENTATION) .append(option.name) .append(": ") .append(type.toString() + newline) } } writer.append("}$newline$newline") } private fun write(function: Function) { val newline = if (deterministicMode) "\n" else System.lineSeparator() writeAnnotations(function.annotations) writer.append("function ") .append(function.id.toString()) if (function.typeParameters.isNotEmpty()) { writer.append("<") .append(function.typeParameters.joinToString(", ")) .append(">") } writer.append("(") .append(function.arguments.joinToString { argument -> argument.name + ": " + argument.type.toString() }) .append("): ") .append(function.returnType.toString()) writer.append(" {$newline") this.write(function.block, 1) writer.append("}$newline$newline") } private fun writeAnnotations(annotations: List<Annotation>) { val newline = if (deterministicMode) "\n" else System.lineSeparator() for (annotation in annotations) { writer.append("@") .append(annotation.name.toString()) if (annotation.values.isNotEmpty()) { writer.append("(") writeAnnotationArguments(annotation.values) writer.append(")") } writer.append(newline) } } private fun writeAnnotationArguments(annotationArgs: List<AnnotationArgument>) { var isFirst = true for (arg in annotationArgs) { if (!isFirst) { writer.append(", ") } isFirst = false val unused = when (arg) { is AnnotationArgument.Literal -> { writer.append("\"") .append(escapeLiteralContents(arg.value)) .append("\"") } is AnnotationArgument.List -> { writer.append("[") writeAnnotationArguments(arg.values) writer.append("]") } } } } private val SINGLE_INDENTATION = " " private fun write(block: Block, indentationLevel: Int) { val newline = if (deterministicMode) "\n" else System.lineSeparator() val indent: String = SINGLE_INDENTATION.repeat(indentationLevel) for (statement in block.statements) { writer.append(indent) this.write(statement, indentationLevel) writer.append(newline) } } // Note: This doesn't include indentation or newlines private fun write(statement: Statement, indentationLevel: Int) { val unused: Any? = when (statement) { is Statement.Assignment -> { writer.append("let ") .append(statement.name) if (statement.type != null && !deterministicMode) { writer.append(": ") .append(statement.type.toString()) } writer.append(" = ") write(statement.expression, indentationLevel) } is Statement.Bare -> { write(statement.expression, indentationLevel) } } } private fun write( expression: Expression, indentationLevel: Int ) { val newline = if (deterministicMode) "\n" else System.lineSeparator() val unused = when (expression) { is Expression.Variable -> { writer.append(expression.name) } is Expression.Literal -> { writer.append(expression.type.toString()) .append(".\"") .append(escapeLiteralContents(expression.literal)) // TODO: Might need escaping here? .append("\"") } is Expression.ListLiteral -> { writer.append("[") var first = true for (item in expression.contents) { if (!first) { writer.append(", ") } first = false write(item, indentationLevel) } writer.append("]<") .append(expression.chosenParameter.toString()) .append(">") } is Expression.Follow -> { write(expression.structureExpression, indentationLevel) writer.append("->") .append(expression.name) } is Expression.NamedFunctionCall -> { writer.append(expression.functionRef.toString()) if (expression.chosenParameters.isNotEmpty()) { writer.append("<") .append(expression.chosenParameters.joinToString(", ")) .append(">") } writer.append("(") var first = true for (argument in expression.arguments) { if (!first) { writer.append(", ") } first = false write(argument, indentationLevel) } writer.append(")") } is Expression.NamedFunctionBinding -> { writer.append(expression.functionRef.toString()) if (expression.chosenParameters.isNotEmpty()) { writer.append("<") .append(expression.chosenParameters.map { if (it == null) "_" else it }.joinToString(", ")) .append(">") } writer.append("|(") var first = true for (binding in expression.bindings) { if (!first) { writer.append(", ") } first = false if (binding == null) { writer.append("_") } else { write(binding, indentationLevel) } } writer.append(")") } is Expression.ExpressionFunctionCall -> { write(expression.functionExpression, indentationLevel) if (expression.chosenParameters.isNotEmpty()) { writer.append("<") .append(expression.chosenParameters.joinToString(", ")) .append(">") } writer.append("(") var first = true for (argument in expression.arguments) { if (!first) { writer.append(", ") } first = false write(argument, indentationLevel) } writer.append(")") } is Expression.ExpressionFunctionBinding -> { write(expression.functionExpression, indentationLevel) if (expression.chosenParameters.isNotEmpty()) { writer.append("<") .append(expression.chosenParameters.map { if (it == null) "_" else it }.joinToString(", ")) .append(">") } writer.append("|(") var first = true for (binding in expression.bindings) { if (!first) { writer.append(", ") } first = false if (binding == null) { writer.append("_") } else { write(binding, indentationLevel) } } writer.append(")") } is Expression.IfThen -> { val indent: String = SINGLE_INDENTATION.repeat(indentationLevel) writer.append("if (") write(expression.condition, indentationLevel) writer.append(") {$newline") this.write(expression.thenBlock, indentationLevel + 1) writer.append(indent) .append("} else {$newline") this.write(expression.elseBlock, indentationLevel + 1) writer.append(indent).append("}") } is Expression.InlineFunction -> { val indent: String = SINGLE_INDENTATION.repeat(indentationLevel) writer.append("function(") writer.append(expression.arguments.joinToString { argument -> argument.name + ": " + argument.type.toString() }) writer.append("): ") writer.append(expression.returnType.toString()) writer.append(" {$newline") this.write(expression.block, indentationLevel + 1) writer.append(indent).append("}") } } } } fun escapeLiteralContents(literal: String): String { val sb = StringBuilder() var i = 0 while (i < literal.length) { val c = literal[i] when (c) { '\\' -> sb.append("\\\\") '\"' -> sb.append("\\\"") '\n' -> sb.append("\\n") '\r' -> sb.append("\\r") '\t' -> sb.append("\\t") else -> sb.append(c) } i++ } return sb.toString() } private object HasEntityIdComparator : Comparator<HasId> { override fun compare(hasId1: HasId, hasId2: HasId): Int { val strings1 = hasId1.id.namespacedName val strings2 = hasId2.id.namespacedName var i = 0 while (true) { // When they are otherwise the same, shorter precedes longer val done1 = i >= strings1.size val done2 = i >= strings2.size if (done1) { if (done2) { return 0 } else { return -1 } } if (done2) { return 1 } val stringComparison = strings1[i].compareTo(strings2[i]) if (stringComparison != 0) { return stringComparison } i++ } } }
apache-2.0
4dfb734e4afe3437ab8e79394db48706
35.589474
115
0.492771
5.405521
false
false
false
false
peterLaurence/TrekAdvisor
app/src/main/java/com/peterlaurence/trekme/util/gpx/model/TrackPoint.kt
1
481
package com.peterlaurence.trekme.util.gpx.model /** * Represents a waypoint, point of interest, or named feature on a map. * * @author peterLaurence on 12/02/17. */ data class TrackPoint( var latitude: Double = 0.0, var longitude: Double = 0.0, var elevation: Double? = null, /** * The UTC time of this point, in milliseconds since January 1, 1970. */ var time: Long? = null, var name: String? = null )
gpl-3.0
64c980bca1dcea5aa3fe7ac29f1e067e
27.352941
77
0.594595
3.848
false
false
false
false
AndroidX/androidx
compose/compiler/compiler-hosted/src/main/java/androidx/compose/compiler/plugins/kotlin/VersionChecker.kt
3
7775
/* * 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.compiler.plugins.kotlin import org.jetbrains.kotlin.backend.common.extensions.IrPluginContext import org.jetbrains.kotlin.ir.declarations.IrProperty import org.jetbrains.kotlin.ir.expressions.IrConst import org.jetbrains.kotlin.ir.expressions.IrConstKind import org.jetbrains.kotlin.platform.jvm.isJvm class VersionChecker(val context: IrPluginContext) { companion object { /** * A table of runtime version ints to version strings for compose-runtime. * This should be updated every time a new version of the Compose Runtime is released. * Typically updated via update_versions_for_release.py */ private val runtimeVersionToMavenVersionTable = mapOf( 1600 to "0.1.0-dev16", 1700 to "1.0.0-alpha06", 1800 to "1.0.0-alpha07", 1900 to "1.0.0-alpha08", 2000 to "1.0.0-alpha09", 2100 to "1.0.0-alpha10", 2200 to "1.0.0-alpha11", 2300 to "1.0.0-alpha12", 2400 to "1.0.0-alpha13", 2500 to "1.0.0-beta04", 2600 to "1.0.0-beta05", 2700 to "1.0.0-beta06", 2800 to "1.0.0-beta07", 2900 to "1.0.0-beta08", 3000 to "1.0.0-beta09", 3100 to "1.0.0-rc01", 3200 to "1.0.0-rc02", 3300 to "1.0.0", 3301 to "1.0.1", 3302 to "1.0.2", 3303 to "1.0.3", 3304 to "1.0.4", 3305 to "1.0.5", 4000 to "1.1.0-alpha01", 4100 to "1.1.0-alpha02", 4200 to "1.1.0-alpha03", 4300 to "1.1.0-alpha04", 4400 to "1.1.0-alpha05", 4500 to "1.1.0-alpha06", 4600 to "1.1.0-beta01", 4700 to "1.1.0-beta02", 4800 to "1.1.0-beta03", 4900 to "1.1.0-beta04", 5000 to "1.1.0-rc01", 5001 to "1.1.0-rc02", 5002 to "1.1.0-rc03", 5003 to "1.1.0", 5004 to "1.1.1", 6000 to "1.2.0-alpha01", 6100 to "1.2.0-alpha02", 6200 to "1.2.0-alpha03", 6300 to "1.2.0-alpha04", 6400 to "1.2.0-alpha05", 6500 to "1.2.0-alpha06", 6600 to "1.2.0-alpha07", 6700 to "1.2.0-alpha08", 6800 to "1.2.0-beta01", 6900 to "1.2.0-beta02", 7000 to "1.2.0-beta03", 7100 to "1.2.0-rc01", 7101 to "1.2.0-rc02", 7102 to "1.2.0-rc03", 7103 to "1.2.0", 7104 to "1.2.1", 7105 to "1.2.2", 8000 to "1.3.0-alpha01", 8100 to "1.3.0-alpha02", 8200 to "1.3.0-alpha03", 8300 to "1.3.0-beta01", 8400 to "1.3.0-beta02", 8500 to "1.3.0-beta03", 8600 to "1.3.0-rc01", 8601 to "1.3.0-rc02", 8602 to "1.3.0", 8603 to "1.3.1", 8604 to "1.3.2", 9000 to "1.4.0-alpha01", 9001 to "1.4.0-alpha02", 9100 to "1.4.0-alpha03", ) /** * The minimum version int that this compiler is guaranteed to be compatible with. Typically * this will match the version int that is in ComposeVersion.kt in the runtime. */ private const val minimumRuntimeVersionInt: Int = 3300 /** * The maven version string of this compiler. This string should be updated before/after every * release. */ const val compilerVersion: String = "1.4.0-alpha02" private val minimumRuntimeVersion: String get() = runtimeVersionToMavenVersionTable[minimumRuntimeVersionInt] ?: "unknown" } fun check() { // version checker accesses bodies of the functions that are not deserialized in KLIB if (!context.platform.isJvm()) return val versionClass = context.referenceClass(ComposeClassIds.ComposeVersion) if (versionClass == null) { // If the version class isn't present, it likely means that compose runtime isn't on the // classpath anywhere. But also for dev03-dev15 there wasn't any ComposeVersion class at // all, so we check for the presence of the Composer class here to try and check for the // case that an older version of Compose runtime is available. val composerClass = context.referenceClass(ComposeClassIds.Composer) if (composerClass != null) { outdatedRuntimeWithUnknownVersionNumber() } else { noRuntimeOnClasspathError() } } val versionExpr = versionClass .owner .declarations .mapNotNull { it as? IrProperty } .firstOrNull { it.name.asString() == "version" } ?.backingField ?.initializer ?.expression as? IrConst<*> if (versionExpr == null || versionExpr.kind != IrConstKind.Int) { outdatedRuntimeWithUnknownVersionNumber() } val versionInt = versionExpr.value as Int if (versionInt < minimumRuntimeVersionInt) { outdatedRuntime(runtimeVersionToMavenVersionTable[versionInt] ?: "<unknown>") } // success. We are compatible with this runtime version! } private fun noRuntimeOnClasspathError(): Nothing { throw IncompatibleComposeRuntimeVersionException( """ The Compose Compiler requires the Compose Runtime to be on the class path, but none could be found. The compose compiler plugin you are using (version $compilerVersion) expects a minimum runtime version of $minimumRuntimeVersion. """.trimIndent().replace('\n', ' ') ) } private fun outdatedRuntimeWithUnknownVersionNumber(): Nothing { throw IncompatibleComposeRuntimeVersionException( """ You are using an outdated version of Compose Runtime that is not compatible with the version of the Compose Compiler plugin you have installed. The compose compiler plugin you are using (version $compilerVersion) expects a minimum runtime version of $minimumRuntimeVersion. """.trimIndent().replace('\n', ' ') ) } private fun outdatedRuntime(actualVersion: String): Nothing { throw IncompatibleComposeRuntimeVersionException( """ You are using an outdated version of Compose Runtime that is not compatible with the version of the Compose Compiler plugin you have installed. The compose compiler plugin you are using (version $compilerVersion) expects a minimum runtime version of $minimumRuntimeVersion. The version of the runtime on the classpath currently is $actualVersion. """.trimIndent().replace('\n', ' ') ) } } class IncompatibleComposeRuntimeVersionException(override val message: String) : Exception(message)
apache-2.0
e1bff9d943f956ee94df8d6e341b2e37
39.921053
102
0.581222
4.047371
false
false
false
false
AndroidX/androidx
compose/ui/ui/src/androidAndroidTest/kotlin/androidx/compose/ui/focus/ClearFocusTest.kt
3
12974
/* * 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.focus import androidx.compose.foundation.layout.Box import androidx.compose.runtime.SideEffect import androidx.compose.ui.Modifier import androidx.compose.ui.focus.FocusStateImpl.Active import androidx.compose.ui.focus.FocusStateImpl.ActiveParent import androidx.compose.ui.focus.FocusStateImpl.Captured import androidx.compose.ui.focus.FocusStateImpl.Deactivated import androidx.compose.ui.focus.FocusStateImpl.DeactivatedParent import androidx.compose.ui.focus.FocusStateImpl.Inactive import androidx.compose.ui.test.junit4.createComposeRule import androidx.test.filters.SmallTest import com.google.common.truth.Truth.assertThat import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith import org.junit.runners.Parameterized @SmallTest @RunWith(Parameterized::class) class ClearFocusTest(private val forced: Boolean) { @get:Rule val rule = createComposeRule() companion object { @JvmStatic @Parameterized.Parameters(name = "forcedClear = {0}") fun initParameters() = listOf(true, false) } @Test fun active_isCleared() { // Arrange. val modifier = FocusModifier(Active) rule.setFocusableContent { Box(Modifier.focusTarget(modifier)) } // Act. val cleared = rule.runOnIdle { modifier.clearFocus(forced) } // Assert. rule.runOnIdle { assertThat(cleared).isTrue() assertThat(modifier.focusState).isEqualTo(Inactive) } } @Test fun active_isClearedAndRemovedFromParentsFocusedChild() { // Arrange. val parent = FocusModifier(ActiveParent) val modifier = FocusModifier(Active) rule.setFocusableContent { Box(Modifier.focusTarget(parent)) { Box(Modifier.focusTarget(modifier)) } SideEffect { parent.focusedChild = modifier } } // Act. val cleared = rule.runOnIdle { modifier.clearFocus(forced) } // Assert. rule.runOnIdle { assertThat(cleared).isTrue() assertThat(modifier.focusState).isEqualTo(Inactive) } } @Test(expected = IllegalArgumentException::class) fun activeParent_noFocusedChild_throwsException() { // Arrange. val modifier = FocusModifier(ActiveParent) rule.setFocusableContent { Box(Modifier.focusTarget(modifier)) } // Act. rule.runOnIdle { modifier.clearFocus(forced) } } @Test fun activeParent_isClearedAndRemovedFromParentsFocusedChild() { // Arrange. val parent = FocusModifier(ActiveParent) val modifier = FocusModifier(ActiveParent) val child = FocusModifier(Active) rule.setFocusableContent { Box(Modifier.focusTarget(parent)) { Box(Modifier.focusTarget(modifier)) { Box(Modifier.focusTarget(child)) } } SideEffect { parent.focusedChild = modifier modifier.focusedChild = child } } // Act. val cleared = rule.runOnIdle { modifier.clearFocus(forced) } // Assert. rule.runOnIdle { assertThat(cleared).isTrue() assertThat(modifier.focusedChild).isNull() assertThat(modifier.focusState).isEqualTo(Inactive) } } @Test fun activeParent_clearsEntireHierarchy() { // Arrange. val modifier = FocusModifier(ActiveParent) val child = FocusModifier(ActiveParent) val grandchild = FocusModifier(ActiveParent) val greatGrandchild = FocusModifier(Active) rule.setFocusableContent { Box(Modifier.focusTarget(modifier)) { Box(Modifier.focusTarget(child)) { Box(Modifier.focusTarget(grandchild)) { Box(Modifier.focusTarget(greatGrandchild)) } } } SideEffect { modifier.focusedChild = child child.focusedChild = grandchild grandchild.focusedChild = greatGrandchild } } // Act. val cleared = rule.runOnIdle { modifier.clearFocus(forced) } // Assert. rule.runOnIdle { assertThat(cleared).isTrue() assertThat(modifier.focusedChild).isNull() assertThat(child.focusedChild).isNull() assertThat(grandchild.focusedChild).isNull() assertThat(modifier.focusState).isEqualTo(Inactive) assertThat(child.focusState).isEqualTo(Inactive) assertThat(grandchild.focusState).isEqualTo(Inactive) assertThat(greatGrandchild.focusState).isEqualTo(Inactive) } } @Test fun captured_isCleared_whenForced() { // Arrange. val modifier = FocusModifier(Captured) rule.setFocusableContent { Box(Modifier.focusTarget(modifier)) } // Act. val cleared = rule.runOnIdle { modifier.clearFocus(forced) } // Assert. rule.runOnIdle { when (forced) { true -> { assertThat(cleared).isTrue() assertThat(modifier.focusState).isEqualTo(Inactive) } false -> { assertThat(cleared).isFalse() assertThat(modifier.focusState).isEqualTo(Captured) } } } } @Test fun active_isClearedAndRemovedFromParentsFocusedChild_whenForced() { // Arrange. val parent = FocusModifier(ActiveParent) val modifier = FocusModifier(Captured) rule.setFocusableContent { Box(Modifier.focusTarget(parent)) { Box(Modifier.focusTarget(modifier)) } SideEffect { parent.focusedChild = modifier } } // Act. val cleared = rule.runOnIdle { modifier.clearFocus(forced) } // Assert. rule.runOnIdle { when (forced) { true -> { assertThat(cleared).isTrue() assertThat(modifier.focusState).isEqualTo(Inactive) } false -> { assertThat(cleared).isFalse() assertThat(modifier.focusState).isEqualTo(Captured) } } } } @Test fun Inactive_isUnchanged() { // Arrange. val modifier = FocusModifier(Inactive) rule.setFocusableContent { Box(Modifier.focusTarget(modifier)) } // Act. val cleared = rule.runOnIdle { modifier.clearFocus(forced) } // Assert. rule.runOnIdle { assertThat(cleared).isTrue() assertThat(modifier.focusState).isEqualTo(Inactive) } } @Test fun Deactivated_isUnchanged() { // Arrange. val modifier = FocusModifier(Inactive) rule.setFocusableContent { Box( Modifier .focusProperties { canFocus = false } .focusTarget(modifier) ) } // Act. val cleared = rule.runOnIdle { modifier.clearFocus(forced) } // Assert. rule.runOnIdle { assertThat(cleared).isTrue() assertThat(modifier.focusState.isDeactivated).isTrue() } } @Test(expected = IllegalArgumentException::class) fun deactivatedParent_noFocusedChild_throwsException() { // Arrange. val modifier = FocusModifier(DeactivatedParent) rule.setFocusableContent { Box(Modifier.focusTarget(modifier)) } // Act. rule.runOnIdle { modifier.clearFocus(forced) } } @Test fun deactivatedParent_isClearedAndRemovedFromParentsFocusedChild() { // Arrange. val parent = FocusModifier(ActiveParent) val modifier = FocusModifier(ActiveParent) val child = FocusModifier(Active) rule.setFocusableContent { Box(Modifier.focusTarget(parent)) { Box( Modifier .focusProperties { canFocus = false } .focusTarget(modifier) ) { Box(Modifier.focusTarget(child)) } } SideEffect { parent.focusedChild = modifier modifier.focusedChild = child } } // Act. val cleared = rule.runOnIdle { modifier.clearFocus(forced) } // Assert. rule.runOnIdle { assertThat(cleared).isTrue() assertThat(modifier.focusedChild).isNull() assertThat(modifier.focusState.isDeactivated).isTrue() } } @Test fun deactivatedParent_withDeactivatedGrandParent_isClearedAndRemovedFromParentsFocusedChild() { // Arrange. val parent = FocusModifier(ActiveParent) val modifier = FocusModifier(ActiveParent) val child = FocusModifier(Active) rule.setFocusableContent { Box(Modifier .focusProperties { canFocus = false } .focusTarget(parent) ) { Box(Modifier .focusProperties { canFocus = false } .focusTarget(modifier) ) { Box(Modifier.focusTarget(child)) } } SideEffect { parent.focusedChild = modifier modifier.focusedChild = child } } // Act. val cleared = rule.runOnIdle { modifier.clearFocus(forced) } // Assert. rule.runOnIdle { assertThat(cleared).isTrue() assertThat(modifier.focusedChild).isNull() assertThat(modifier.focusState.isDeactivated).isTrue() } } @Test fun deactivatedParent_clearsEntireHierarchy() { // Arrange. val modifier = FocusModifier(ActiveParent) val child = FocusModifier(ActiveParent) val grandchild = FocusModifier(ActiveParent) val greatGrandchild = FocusModifier(ActiveParent) val greatGreatGrandchild = FocusModifier(Active) rule.setFocusableContent { Box(Modifier .focusProperties { canFocus = false } .focusTarget(modifier) ) { Box(modifier = Modifier.focusTarget(child)) { Box(Modifier .focusProperties { canFocus = false } .focusTarget(grandchild) ) { Box(Modifier.focusTarget(greatGrandchild)) { Box(Modifier.focusTarget(greatGreatGrandchild)) } } } } SideEffect { modifier.focusedChild = child child.focusedChild = grandchild grandchild.focusedChild = greatGrandchild greatGrandchild.focusedChild = greatGreatGrandchild } } // Act. val cleared = rule.runOnIdle { modifier.clearFocus(forced) } // Assert. rule.runOnIdle { assertThat(cleared).isTrue() assertThat(modifier.focusedChild).isNull() assertThat(child.focusedChild).isNull() assertThat(grandchild.focusedChild).isNull() assertThat(modifier.focusState).isEqualTo(Deactivated) assertThat(child.focusState).isEqualTo(Inactive) assertThat(grandchild.focusState).isEqualTo(Deactivated) assertThat(greatGrandchild.focusState).isEqualTo(Inactive) assertThat(greatGreatGrandchild.focusState).isEqualTo(Inactive) } } }
apache-2.0
5488509a3d52dd4ddbdaa5c77aff73ea
29.817102
99
0.566441
5.667977
false
false
false
false
exponent/exponent
android/expoview/src/main/java/host/exp/exponent/kernel/Kernel.kt
2
40274
// Copyright 2015-present 650 Industries. All rights reserved. package host.exp.exponent.kernel import android.app.Activity import android.app.ActivityManager import android.app.ActivityManager.AppTask import android.app.ActivityManager.RecentTaskInfo import android.app.Application import android.app.RemoteInput import android.content.Context import android.content.Intent import android.net.Uri import android.nfc.NfcAdapter import android.os.Build import android.os.Bundle import android.os.Handler import android.util.Log import android.widget.Toast import com.facebook.internal.BundleJSONConverter import com.facebook.proguard.annotations.DoNotStrip import com.facebook.react.ReactInstanceManager import com.facebook.react.ReactRootView import com.facebook.react.bridge.Arguments import com.facebook.react.bridge.JavaScriptContextHolder import com.facebook.react.bridge.ReactApplicationContext import com.facebook.react.bridge.ReadableMap import com.facebook.react.common.LifecycleState import com.facebook.react.modules.network.ReactCookieJarContainer import com.facebook.react.shell.MainReactPackage import com.facebook.soloader.SoLoader import de.greenrobot.event.EventBus import expo.modules.notifications.service.NotificationsService.Companion.getNotificationResponseFromIntent import expo.modules.notifications.service.delegates.ExpoHandlingDelegate import expo.modules.manifests.core.Manifest import host.exp.exponent.* import host.exp.exponent.ExpoUpdatesAppLoader.AppLoaderCallback import host.exp.exponent.ExpoUpdatesAppLoader.AppLoaderStatus import host.exp.exponent.analytics.EXL import host.exp.exponent.di.NativeModuleDepsProvider import host.exp.exponent.exceptions.ExceptionUtils import host.exp.exponent.experience.BaseExperienceActivity import host.exp.exponent.experience.ErrorActivity import host.exp.exponent.experience.ExperienceActivity import host.exp.exponent.experience.HomeActivity import host.exp.exponent.headless.InternalHeadlessAppLoader import host.exp.exponent.kernel.ExponentErrorMessage.Companion.developerErrorMessage import host.exp.exponent.kernel.ExponentKernelModuleProvider.KernelEventCallback import host.exp.exponent.kernel.ExponentKernelModuleProvider.queueEvent import host.exp.exponent.kernel.ExponentUrls.toHttp import host.exp.exponent.kernel.KernelConstants.ExperienceOptions import host.exp.exponent.network.ExponentNetwork import host.exp.exponent.notifications.ExponentNotification import host.exp.exponent.notifications.ExponentNotificationManager import host.exp.exponent.notifications.NotificationActionCenter import host.exp.exponent.notifications.ScopedNotificationsUtils import host.exp.exponent.storage.ExponentDB import host.exp.exponent.storage.ExponentSharedPreferences import host.exp.exponent.utils.AsyncCondition import host.exp.exponent.utils.AsyncCondition.AsyncConditionListener import host.exp.expoview.BuildConfig import host.exp.expoview.ExpoViewBuildConfig import host.exp.expoview.Exponent import host.exp.expoview.Exponent.BundleListener import okhttp3.OkHttpClient import org.json.JSONException import org.json.JSONObject import versioned.host.exp.exponent.ExpoTurboPackage import versioned.host.exp.exponent.ExponentPackage import versioned.host.exp.exponent.ReactUnthemedRootView import versioned.host.exp.exponent.modules.api.reanimated.ReanimatedJSIModulePackage import java.lang.ref.WeakReference import java.util.* import java.util.concurrent.TimeUnit import javax.inject.Inject // TOOD: need to figure out when we should reload the kernel js. Do we do it every time you visit // the home screen? only when the app gets kicked out of memory? class Kernel : KernelInterface() { class KernelStartedRunningEvent class ExperienceActivityTask(val manifestUrl: String) { var taskId = 0 var experienceActivity: WeakReference<ExperienceActivity>? = null var activityId = 0 var bundleUrl: String? = null } // React var reactInstanceManager: ReactInstanceManager? = null private set // Contexts @Inject lateinit var context: Context @Inject lateinit var applicationContext: Application @Inject lateinit var exponentManifest: ExponentManifest @Inject lateinit var exponentSharedPreferences: ExponentSharedPreferences @Inject lateinit var exponentNetwork: ExponentNetwork var activityContext: Activity? = null set(value) { if (value != null) { field = value } } private var optimisticActivity: ExperienceActivity? = null private var optimisticTaskId: Int? = null private fun experienceActivityTaskForTaskId(taskId: Int): ExperienceActivityTask? { return manifestUrlToExperienceActivityTask.values.find { it.taskId == taskId } } // Misc var isStarted = false private set private var hasError = false private fun updateKernelRNOkHttp() { val client = OkHttpClient.Builder() .connectTimeout(0, TimeUnit.MILLISECONDS) .readTimeout(0, TimeUnit.MILLISECONDS) .writeTimeout(0, TimeUnit.MILLISECONDS) .cookieJar(ReactCookieJarContainer()) .cache(exponentNetwork.cache) if (BuildConfig.DEBUG) { // FIXME: 8/9/17 // broke with lib versioning // clientBuilder.addNetworkInterceptor(new StethoInterceptor()); } ReactNativeStaticHelpers.setExponentNetwork(exponentNetwork) } private val kernelInitialURL: String? get() { val activity = activityContext ?: return null val intent = activity.intent ?: return null val action = intent.action val uri = intent.data return if (( uri != null && ((Intent.ACTION_VIEW == action) || (NfcAdapter.ACTION_NDEF_DISCOVERED == action)) ) ) { uri.toString() } else null } // Don't call this until a loading screen is up, since it has to do some work on the main thread. fun startJSKernel(activity: Activity?) { if (Constants.isStandaloneApp()) { return } activityContext = activity SoLoader.init(context, false) synchronized(this) { if (isStarted && !hasError) { return } isStarted = true } hasError = false if (!exponentSharedPreferences.shouldUseInternetKernel()) { try { // Make sure we can get the manifest successfully. This can fail in dev mode // if the kernel packager is not running. exponentManifest.getKernelManifest() } catch (e: Throwable) { Exponent.instance .runOnUiThread { // Hack to make this show up for a while. Can't use an Alert because LauncherActivity has a transparent theme. This should only be seen by internal developers. var i = 0 while (i < 3) { Toast.makeText( activityContext, "Kernel manifest invalid. Make sure `expo start` is running inside of exponent/home and rebuild the app.", Toast.LENGTH_LONG ).show() i++ } } return } } // On first run use the embedded kernel js but fire off a request for the new js in the background. val bundleUrlToLoad = bundleUrl + (if (ExpoViewBuildConfig.DEBUG) "" else "?versionName=" + ExpoViewKernel.instance.versionName) if (exponentSharedPreferences.shouldUseInternetKernel() && exponentSharedPreferences.getBoolean(ExponentSharedPreferences.ExponentSharedPreferencesKey.IS_FIRST_KERNEL_RUN_KEY) ) { kernelBundleListener().onBundleLoaded(Constants.EMBEDDED_KERNEL_PATH) // Now preload bundle for next run Handler().postDelayed( { Exponent.instance.loadJSBundle( null, bundleUrlToLoad, KernelConstants.KERNEL_BUNDLE_ID, RNObject.UNVERSIONED, object : BundleListener { override fun onBundleLoaded(localBundlePath: String) { exponentSharedPreferences.setBoolean( ExponentSharedPreferences.ExponentSharedPreferencesKey.IS_FIRST_KERNEL_RUN_KEY, false ) EXL.d(TAG, "Successfully preloaded kernel bundle") } override fun onError(e: Exception) { EXL.e(TAG, "Error preloading kernel bundle: $e") } } ) }, KernelConstants.DELAY_TO_PRELOAD_KERNEL_JS ) } else { var shouldNotUseKernelCache = exponentSharedPreferences.getBoolean(ExponentSharedPreferences.ExponentSharedPreferencesKey.SHOULD_NOT_USE_KERNEL_CACHE) if (!ExpoViewBuildConfig.DEBUG) { val oldKernelRevisionId = exponentSharedPreferences.getString(ExponentSharedPreferences.ExponentSharedPreferencesKey.KERNEL_REVISION_ID, "") if (oldKernelRevisionId != kernelRevisionId) { shouldNotUseKernelCache = true } } Exponent.instance.loadJSBundle( null, bundleUrlToLoad, KernelConstants.KERNEL_BUNDLE_ID, RNObject.UNVERSIONED, kernelBundleListener(), shouldNotUseKernelCache ) } } private fun kernelBundleListener(): BundleListener { return object : BundleListener { override fun onBundleLoaded(localBundlePath: String) { if (!ExpoViewBuildConfig.DEBUG) { exponentSharedPreferences.setString( ExponentSharedPreferences.ExponentSharedPreferencesKey.KERNEL_REVISION_ID, kernelRevisionId ) } Exponent.instance.runOnUiThread { val initialURL = kernelInitialURL val builder = ReactInstanceManager.builder() .setApplication(applicationContext) .setCurrentActivity(activityContext) .setJSBundleFile(localBundlePath) .addPackage(MainReactPackage()) .addPackage( ExponentPackage.kernelExponentPackage( context, exponentManifest.getKernelManifest(), HomeActivity.homeExpoPackages(), initialURL ) ) .addPackage( ExpoTurboPackage.kernelExpoTurboPackage( exponentManifest.getKernelManifest(), initialURL ) ) .setJSIModulesPackage { reactApplicationContext: ReactApplicationContext?, jsContext: JavaScriptContextHolder? -> ReanimatedJSIModulePackage().getJSIModules( reactApplicationContext, jsContext ) } .setInitialLifecycleState(LifecycleState.RESUMED) if (!KernelConfig.FORCE_NO_KERNEL_DEBUG_MODE && exponentManifest.getKernelManifest().isDevelopmentMode()) { Exponent.enableDeveloperSupport( kernelDebuggerHost, kernelMainModuleName, RNObject.wrap(builder) ) } reactInstanceManager = builder.build() reactInstanceManager!!.createReactContextInBackground() reactInstanceManager!!.onHostResume(activityContext, null) isRunning = true EventBus.getDefault().postSticky(KernelStartedRunningEvent()) EXL.d(TAG, "Kernel started running.") // Reset this flag if we crashed exponentSharedPreferences.setBoolean( ExponentSharedPreferences.ExponentSharedPreferencesKey.SHOULD_NOT_USE_KERNEL_CACHE, false ) } } override fun onError(e: Exception) { setHasError() if (ExpoViewBuildConfig.DEBUG) { handleError("Can't load kernel. Are you sure your packager is running and your phone is on the same wifi? " + e.message) } else { handleError("Expo requires an internet connection.") EXL.d(TAG, "Expo requires an internet connection." + e.message) } } } } private val kernelDebuggerHost: String get() = exponentManifest.getKernelManifest().getDebuggerHost() private val kernelMainModuleName: String get() = exponentManifest.getKernelManifest().getMainModuleName() private val bundleUrl: String? get() { return try { exponentManifest.getKernelManifest().getBundleURL() } catch (e: JSONException) { KernelProvider.instance.handleError(e) null } } private val kernelRevisionId: String? get() { return try { exponentManifest.getKernelManifest().getRevisionId() } catch (e: JSONException) { KernelProvider.instance.handleError(e) null } } var isRunning: Boolean = false get() = field && !hasError private set val reactRootView: ReactRootView get() { val reactRootView: ReactRootView = ReactUnthemedRootView(context) reactRootView.startReactApplication( reactInstanceManager, KernelConstants.HOME_MODULE_NAME, kernelLaunchOptions ) return reactRootView } private val kernelLaunchOptions: Bundle get() { val exponentProps = JSONObject() val referrer = exponentSharedPreferences.getString(ExponentSharedPreferences.ExponentSharedPreferencesKey.REFERRER_KEY) if (referrer != null) { try { exponentProps.put("referrer", referrer) } catch (e: JSONException) { EXL.e(TAG, e) } } val bundle = Bundle() try { bundle.putBundle("exp", BundleJSONConverter.convertToBundle(exponentProps)) } catch (e: JSONException) { throw Error("JSONObject failed to be converted to Bundle", e) } return bundle } fun hasOptionsForManifestUrl(manifestUrl: String?): Boolean { return manifestUrlToOptions.containsKey(manifestUrl) } fun popOptionsForManifestUrl(manifestUrl: String?): ExperienceOptions? { return manifestUrlToOptions.remove(manifestUrl) } fun addAppLoaderForManifestUrl(manifestUrl: String, appLoader: ExpoUpdatesAppLoader) { manifestUrlToAppLoader[manifestUrl] = appLoader } override fun getAppLoaderForManifestUrl(manifestUrl: String?): ExpoUpdatesAppLoader? { return manifestUrlToAppLoader[manifestUrl] } fun getExperienceActivityTask(manifestUrl: String): ExperienceActivityTask { var task = manifestUrlToExperienceActivityTask[manifestUrl] if (task != null) { return task } task = ExperienceActivityTask(manifestUrl) manifestUrlToExperienceActivityTask[manifestUrl] = task return task } fun removeExperienceActivityTask(manifestUrl: String?) { if (manifestUrl != null) { manifestUrlToExperienceActivityTask.remove(manifestUrl) } } fun openHomeActivity() { val manager = context.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager for (task: AppTask in manager.appTasks) { val baseIntent = task.taskInfo.baseIntent if ((HomeActivity::class.java.name == baseIntent.component!!.className)) { task.moveToFront() return } } val intent = Intent(activityContext, HomeActivity::class.java) addIntentDocumentFlags(intent) activityContext!!.startActivity(intent) } private fun openShellAppActivity(forceCache: Boolean) { try { val activityClass = Class.forName("host.exp.exponent.MainActivity") val manager = context.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager for (task: AppTask in manager.appTasks) { val baseIntent = task.taskInfo.baseIntent if ((activityClass.name == baseIntent.component!!.className)) { moveTaskToFront(task.taskInfo.id) return } } val intent = Intent(activityContext, activityClass) addIntentDocumentFlags(intent) if (forceCache) { intent.putExtra(KernelConstants.LOAD_FROM_CACHE_KEY, true) } activityContext!!.startActivity(intent) } catch (e: ClassNotFoundException) { throw IllegalStateException("Could not find activity to open (MainActivity is not present).") } } /* * * Manifests * */ fun handleIntent(activity: Activity, intent: Intent) { try { if (intent.getBooleanExtra("EXKernelDisableNuxDefaultsKey", false)) { Constants.DISABLE_NUX = true } } catch (e: Throwable) { } activityContext = activity if (intent.action != null && (ExpoHandlingDelegate.OPEN_APP_INTENT_ACTION == intent.action)) { if (!openExperienceFromNotificationIntent(intent)) { openDefaultUrl() } return } val bundle = intent.extras val uri = intent.data val intentUri = uri?.toString() if (bundle != null) { // Notification val notification = bundle.getString(KernelConstants.NOTIFICATION_KEY) // deprecated val notificationObject = bundle.getString(KernelConstants.NOTIFICATION_OBJECT_KEY) val notificationManifestUrl = bundle.getString(KernelConstants.NOTIFICATION_MANIFEST_URL_KEY) if (notificationManifestUrl != null) { val exponentNotification = ExponentNotification.fromJSONObjectString(notificationObject) if (exponentNotification != null) { // Add action type if (bundle.containsKey(KernelConstants.NOTIFICATION_ACTION_TYPE_KEY)) { exponentNotification.actionType = bundle.getString(KernelConstants.NOTIFICATION_ACTION_TYPE_KEY) val manager = ExponentNotificationManager(context) val experienceKey = ExperienceKey(exponentNotification.experienceScopeKey) manager.cancel(experienceKey, exponentNotification.notificationId) } // Add remote input val remoteInput = RemoteInput.getResultsFromIntent(intent) if (remoteInput != null) { exponentNotification.inputText = remoteInput.getString(NotificationActionCenter.KEY_TEXT_REPLY) } } openExperience( ExperienceOptions( notificationManifestUrl, intentUri ?: notificationManifestUrl, notification, exponentNotification ) ) return } // Shortcut // TODO: Remove once we decide to stop supporting shortcuts to experiences. val shortcutManifestUrl = bundle.getString(KernelConstants.SHORTCUT_MANIFEST_URL_KEY) if (shortcutManifestUrl != null) { openExperience(ExperienceOptions(shortcutManifestUrl, intentUri, null)) return } } if (uri != null && shouldOpenUrl(uri)) { if (Constants.INITIAL_URL == null) { // We got an "exp://", "exps://", "http://", or "https://" app link openExperience(ExperienceOptions(uri.toString(), uri.toString(), null)) return } else { // We got a custom scheme link // TODO: we still might want to parse this if we're running a different experience inside a // shell app. For example, we are running Brighten in the List shell and go to Twitter login. // We might want to set the return uri to thelistapp://exp.host/@brighten/brighten+deeplink // But we also can't break thelistapp:// deep links that look like thelistapp://l/listid openExperience(ExperienceOptions(Constants.INITIAL_URL, uri.toString(), null)) return } } openDefaultUrl() } // Certain links (i.e. 'expo.io/expo-go') should just open the HomeScreen private fun shouldOpenUrl(uri: Uri): Boolean { val host = uri.host ?: "" val path = uri.path ?: "" return !(((host == "expo.io") || (host == "expo.dev")) && (path == "/expo-go")) } private fun openExperienceFromNotificationIntent(intent: Intent): Boolean { val response = getNotificationResponseFromIntent(intent) val experienceScopeKey = ScopedNotificationsUtils.getExperienceScopeKey(response) ?: return false val exponentDBObject = try { val exponentDBObjectInner = ExponentDB.experienceScopeKeyToExperienceSync(experienceScopeKey) if (exponentDBObjectInner == null) { Log.w("expo-notifications", "Couldn't find experience from scopeKey: $experienceScopeKey") } exponentDBObjectInner } catch (e: JSONException) { Log.w("expo-notifications", "Couldn't deserialize experience from scopeKey: $experienceScopeKey") null } ?: return false val manifestUrl = exponentDBObject.manifestUrl openExperience(ExperienceOptions(manifestUrl, manifestUrl, null)) return true } private fun openDefaultUrl() { val defaultUrl = if (Constants.INITIAL_URL == null) KernelConstants.HOME_MANIFEST_URL else Constants.INITIAL_URL openExperience(ExperienceOptions(defaultUrl, defaultUrl, null)) } override fun openExperience(options: ExperienceOptions) { openManifestUrl(getManifestUrlFromFullUri(options.manifestUri), options, true) } private fun getManifestUrlFromFullUri(uriString: String?): String? { if (uriString == null) { return null } val uri = Uri.parse(uriString) val builder = uri.buildUpon() val deepLinkPositionDashes = uriString.indexOf(ExponentManifest.DEEP_LINK_SEPARATOR_WITH_SLASH) if (deepLinkPositionDashes >= 0) { // do this safely so we preserve any query string val pathSegments = uri.pathSegments builder.path(null) for (segment: String in pathSegments) { if ((ExponentManifest.DEEP_LINK_SEPARATOR == segment)) { break } builder.appendEncodedPath(segment) } } // transfer the release-channel param to the built URL as this will cause Expo Go to treat // this as a different project var releaseChannel = uri.getQueryParameter(ExponentManifest.QUERY_PARAM_KEY_RELEASE_CHANNEL) builder.query(null) if (releaseChannel != null) { // release channels cannot contain the ' ' character, so if this is present, // it must be an encoded form of '+' which indicated a deep link in SDK <27. // therefore, nothing after this is part of the release channel name so we should strip it. // TODO: remove this check once SDK 26 and below are no longer supported val releaseChannelDeepLinkPosition = releaseChannel.indexOf(' ') if (releaseChannelDeepLinkPosition > -1) { releaseChannel = releaseChannel.substring(0, releaseChannelDeepLinkPosition) } builder.appendQueryParameter( ExponentManifest.QUERY_PARAM_KEY_RELEASE_CHANNEL, releaseChannel ) } // transfer the expo-updates query params: runtime-version, channel-name val expoUpdatesQueryParameters = listOf( ExponentManifest.QUERY_PARAM_KEY_EXPO_UPDATES_RUNTIME_VERSION, ExponentManifest.QUERY_PARAM_KEY_EXPO_UPDATES_CHANNEL_NAME ) for (queryParameter: String in expoUpdatesQueryParameters) { val queryParameterValue = uri.getQueryParameter(queryParameter) if (queryParameterValue != null) { builder.appendQueryParameter(queryParameter, queryParameterValue) } } // ignore fragments as well (e.g. those added by auth-session) builder.fragment(null) var newUriString = builder.build().toString() val deepLinkPositionPlus = newUriString.indexOf('+') if (deepLinkPositionPlus >= 0 && deepLinkPositionDashes < 0) { // need to keep this for backwards compatibility newUriString = newUriString.substring(0, deepLinkPositionPlus) } // manifest url doesn't have a trailing slash if (newUriString.isNotEmpty()) { val lastUrlChar = newUriString[newUriString.length - 1] if (lastUrlChar == '/') { newUriString = newUriString.substring(0, newUriString.length - 1) } } return newUriString } private fun openManifestUrl( manifestUrl: String?, options: ExperienceOptions?, isOptimistic: Boolean, forceCache: Boolean = false ) { SoLoader.init(context, false) if (options == null) { manifestUrlToOptions.remove(manifestUrl) } else { manifestUrlToOptions[manifestUrl] = options } if (manifestUrl == null || (manifestUrl == KernelConstants.HOME_MANIFEST_URL)) { openHomeActivity() return } if (Constants.isStandaloneApp()) { openShellAppActivity(forceCache) return } ErrorActivity.clearErrorList() val tasks: List<AppTask> = experienceActivityTasks var existingTask: AppTask? = null for (i in tasks.indices) { val task = tasks[i] val baseIntent = task.taskInfo.baseIntent if (baseIntent.hasExtra(KernelConstants.MANIFEST_URL_KEY) && ( baseIntent.getStringExtra( KernelConstants.MANIFEST_URL_KEY ) == manifestUrl ) ) { existingTask = task break } } if (isOptimistic && existingTask == null) { openOptimisticExperienceActivity(manifestUrl) } if (existingTask != null) { try { moveTaskToFront(existingTask.taskInfo.id) } catch (e: IllegalArgumentException) { // Sometimes task can't be found. existingTask = null openOptimisticExperienceActivity(manifestUrl) } } val finalExistingTask = existingTask if (existingTask == null) { ExpoUpdatesAppLoader( manifestUrl, object : AppLoaderCallback { override fun onOptimisticManifest(optimisticManifest: Manifest) { Exponent.instance .runOnUiThread { sendOptimisticManifestToExperienceActivity(optimisticManifest) } } override fun onManifestCompleted(manifest: Manifest) { Exponent.instance.runOnUiThread { try { openManifestUrlStep2(manifestUrl, manifest, finalExistingTask) } catch (e: JSONException) { handleError(e) } } } override fun onBundleCompleted(localBundlePath: String) { Exponent.instance.runOnUiThread { sendBundleToExperienceActivity(localBundlePath) } } override fun emitEvent(params: JSONObject) { val task = manifestUrlToExperienceActivityTask[manifestUrl] if (task != null) { val experienceActivity = task.experienceActivity!!.get() experienceActivity?.emitUpdatesEvent(params) } } override fun updateStatus(status: AppLoaderStatus) { if (optimisticActivity != null) { optimisticActivity!!.setLoadingProgressStatusIfEnabled(status) } } override fun onError(e: Exception) { Exponent.instance.runOnUiThread { handleError(e) } } }, forceCache ).start(context) } } @Throws(JSONException::class) private fun openManifestUrlStep2( manifestUrl: String, manifest: Manifest, existingTask: AppTask? ) { val bundleUrl = toHttp(manifest.getBundleURL()) val task = getExperienceActivityTask(manifestUrl) task.bundleUrl = bundleUrl ExponentManifest.normalizeManifestInPlace(manifest, manifestUrl) if (existingTask == null) { sendManifestToExperienceActivity(manifestUrl, manifest, bundleUrl) } val params = Arguments.createMap().apply { putString("manifestUrl", manifestUrl) putString("manifestString", manifest.toString()) } queueEvent( "ExponentKernel.addHistoryItem", params, object : KernelEventCallback { override fun onEventSuccess(result: ReadableMap) { EXL.d(TAG, "Successfully called ExponentKernel.addHistoryItem in kernel JS.") } override fun onEventFailure(errorMessage: String?) { EXL.e(TAG, "Error calling ExponentKernel.addHistoryItem in kernel JS: $errorMessage") } } ) killOrphanedLauncherActivities() } /* * * Optimistic experiences * */ private fun openOptimisticExperienceActivity(manifestUrl: String?) { try { val intent = Intent(activityContext, ExperienceActivity::class.java).apply { addIntentDocumentFlags(this) putExtra(KernelConstants.MANIFEST_URL_KEY, manifestUrl) putExtra(KernelConstants.IS_OPTIMISTIC_KEY, true) } activityContext!!.startActivity(intent) } catch (e: Throwable) { EXL.e(TAG, e) } } fun setOptimisticActivity(experienceActivity: ExperienceActivity, taskId: Int) { optimisticActivity = experienceActivity optimisticTaskId = taskId AsyncCondition.notify(KernelConstants.OPEN_OPTIMISTIC_EXPERIENCE_ACTIVITY_KEY) AsyncCondition.notify(KernelConstants.OPEN_EXPERIENCE_ACTIVITY_KEY) } fun sendOptimisticManifestToExperienceActivity(optimisticManifest: Manifest) { AsyncCondition.wait( KernelConstants.OPEN_OPTIMISTIC_EXPERIENCE_ACTIVITY_KEY, object : AsyncConditionListener { override fun isReady(): Boolean { return optimisticActivity != null && optimisticTaskId != null } override fun execute() { optimisticActivity!!.setOptimisticManifest(optimisticManifest) } } ) } private fun sendManifestToExperienceActivity( manifestUrl: String, manifest: Manifest, bundleUrl: String, ) { AsyncCondition.wait( KernelConstants.OPEN_EXPERIENCE_ACTIVITY_KEY, object : AsyncConditionListener { override fun isReady(): Boolean { return optimisticActivity != null && optimisticTaskId != null } override fun execute() { optimisticActivity!!.setManifest(manifestUrl, manifest, bundleUrl) AsyncCondition.notify(KernelConstants.LOAD_BUNDLE_FOR_EXPERIENCE_ACTIVITY_KEY) } } ) } private fun sendBundleToExperienceActivity(localBundlePath: String) { AsyncCondition.wait( KernelConstants.LOAD_BUNDLE_FOR_EXPERIENCE_ACTIVITY_KEY, object : AsyncConditionListener { override fun isReady(): Boolean { return optimisticActivity != null && optimisticTaskId != null } override fun execute() { optimisticActivity!!.setBundle(localBundlePath) optimisticActivity = null optimisticTaskId = null } } ) } /* * * Tasks * */ val tasks: List<AppTask> get() { val manager = context.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager return manager.appTasks } // Get list of tasks in our format. val experienceActivityTasks: List<AppTask> get() = tasks // Sometimes LauncherActivity.finish() doesn't close the activity and task. Not sure why exactly. // Thought it was related to launchMode="singleTask" but other launchModes seem to have the same problem. // This can be reproduced by creating a shortcut, exiting app, clicking on shortcut, refreshing, pressing // home, clicking on shortcut, click recent apps button. There will be a blank LauncherActivity behind // the ExperienceActivity. killOrphanedLauncherActivities solves this but would be nice to figure out // the root cause. private fun killOrphanedLauncherActivities() { try { // Crash with NoSuchFieldException instead of hard crashing at taskInfo.numActivities RecentTaskInfo::class.java.getDeclaredField("numActivities") for (task: AppTask in tasks) { val taskInfo = task.taskInfo if (taskInfo.numActivities == 0 && (taskInfo.baseIntent.action == Intent.ACTION_MAIN)) { task.finishAndRemoveTask() return } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { if (taskInfo.numActivities == 1 && (taskInfo.topActivity!!.className == LauncherActivity::class.java.name)) { task.finishAndRemoveTask() return } } } } catch (e: NoSuchFieldException) { // Don't EXL here because this isn't actually a problem Log.e(TAG, e.toString()) } catch (e: Throwable) { EXL.e(TAG, e) } } fun moveTaskToFront(taskId: Int) { tasks.find { it.taskInfo.id == taskId }?.also { task -> // If we have the task in memory, tell the ExperienceActivity to check for new options. // Otherwise options will be added in initialProps when the Experience starts. val exponentTask = experienceActivityTaskForTaskId(taskId) if (exponentTask != null) { val experienceActivity = exponentTask.experienceActivity!!.get() experienceActivity?.shouldCheckOptions() } task.moveToFront() } } fun killActivityStack(activity: Activity) { val exponentTask = experienceActivityTaskForTaskId(activity.taskId) if (exponentTask != null) { removeExperienceActivityTask(exponentTask.manifestUrl) } // Kill the current task. val manager = activity.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager manager.appTasks.find { it.taskInfo.id == activity.taskId }?.also { task -> task.finishAndRemoveTask() } } override fun reloadVisibleExperience(manifestUrl: String, forceCache: Boolean): Boolean { var activity: ExperienceActivity? = null for (experienceActivityTask: ExperienceActivityTask in manifestUrlToExperienceActivityTask.values) { if (manifestUrl == experienceActivityTask.manifestUrl) { val weakActivity = if (experienceActivityTask.experienceActivity == null) { null } else { experienceActivityTask.experienceActivity!!.get() } activity = weakActivity if (weakActivity == null) { // No activity, just force a reload break } Exponent.instance.runOnUiThread { weakActivity.startLoading() } break } } activity?.let { killActivityStack(it) } openManifestUrl(manifestUrl, null, true, forceCache) return true } override fun handleError(errorMessage: String) { handleReactNativeError(developerErrorMessage(errorMessage), null, -1, true) } override fun handleError(exception: Exception) { handleReactNativeError(ExceptionUtils.exceptionToErrorMessage(exception), null, -1, true) } // TODO: probably need to call this from other places. fun setHasError() { hasError = true } companion object { private val TAG = Kernel::class.java.simpleName private lateinit var instance: Kernel // Activities/Tasks private val manifestUrlToExperienceActivityTask = mutableMapOf<String, ExperienceActivityTask>() private val manifestUrlToOptions = mutableMapOf<String?, ExperienceOptions>() private val manifestUrlToAppLoader = mutableMapOf<String?, ExpoUpdatesAppLoader>() private fun addIntentDocumentFlags(intent: Intent) = intent.apply { addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP) addFlags(Intent.FLAG_ACTIVITY_NEW_DOCUMENT) addFlags(Intent.FLAG_ACTIVITY_MULTIPLE_TASK) } @JvmStatic @DoNotStrip fun reloadVisibleExperience(activityId: Int) { val manifestUrl = getManifestUrlForActivityId(activityId) if (manifestUrl != null) { instance.reloadVisibleExperience(manifestUrl, false) } } // Called from DevServerHelper via ReactNativeStaticHelpers @JvmStatic @DoNotStrip fun getManifestUrlForActivityId(activityId: Int): String? { return manifestUrlToExperienceActivityTask.values.find { it.activityId == activityId }?.manifestUrl } // Called from DevServerHelper via ReactNativeStaticHelpers @JvmStatic @DoNotStrip fun getBundleUrlForActivityId( activityId: Int, host: String, mainModuleId: String?, bundleTypeId: String?, devMode: Boolean, jsMinify: Boolean ): String? { // NOTE: This current implementation doesn't look at the bundleTypeId (see RN's private // BundleType enum for the possible values) but may need to if (activityId == -1) { // This is the kernel return instance.bundleUrl } if (InternalHeadlessAppLoader.hasBundleUrlForActivityId(activityId)) { return InternalHeadlessAppLoader.getBundleUrlForActivityId(activityId) } return manifestUrlToExperienceActivityTask.values.find { it.activityId == activityId }?.bundleUrl } // <= SDK 25 @DoNotStrip fun getBundleUrlForActivityId( activityId: Int, host: String, jsModulePath: String?, devMode: Boolean, jsMinify: Boolean ): String? { if (activityId == -1) { // This is the kernel return instance.bundleUrl } return manifestUrlToExperienceActivityTask.values.find { it.activityId == activityId }?.bundleUrl } // <= SDK 21 @DoNotStrip fun getBundleUrlForActivityId( activityId: Int, host: String, jsModulePath: String?, devMode: Boolean, hmr: Boolean, jsMinify: Boolean ): String? { if (activityId == -1) { // This is the kernel return instance.bundleUrl } return manifestUrlToExperienceActivityTask.values.find { it.activityId == activityId }?.let { task -> var url = task.bundleUrl ?: return null if (hmr) { url = if (url.contains("hot=false")) { url.replace("hot=false", "hot=true") } else { "$url&hot=true" } } return url } } /* * * Error handling * */ // Called using reflection from ReactAndroid. @DoNotStrip fun handleReactNativeError( errorMessage: String?, detailsUnversioned: Any?, exceptionId: Int?, isFatal: Boolean ) { handleReactNativeError( developerErrorMessage(errorMessage), detailsUnversioned, exceptionId, isFatal ) } // Called using reflection from ReactAndroid. @DoNotStrip fun handleReactNativeError( throwable: Throwable?, errorMessage: String?, detailsUnversioned: Any?, exceptionId: Int?, isFatal: Boolean ) { handleReactNativeError( developerErrorMessage(errorMessage), detailsUnversioned, exceptionId, isFatal ) } private fun handleReactNativeError( errorMessage: ExponentErrorMessage, detailsUnversioned: Any?, exceptionId: Int?, isFatal: Boolean ) { val stackList = ArrayList<Bundle>() if (detailsUnversioned != null) { val details = RNObject.wrap(detailsUnversioned) val arguments = RNObject("com.facebook.react.bridge.Arguments") arguments.loadVersion(details.version()) for (i in 0 until details.call("size") as Int) { try { val bundle = arguments.callStatic("toBundle", details.call("getMap", i)) as Bundle stackList.add(bundle) } catch (e: Exception) { e.printStackTrace() } } } else if (BuildConfig.DEBUG) { val stackTraceElements = Thread.currentThread().stackTrace // stackTraceElements starts with a bunch of stuff we don't care about. for (i in 2 until stackTraceElements.size) { val element = stackTraceElements[i] if (( (element.fileName != null) && element.fileName.startsWith(Kernel::class.java.simpleName) && ((element.methodName == "handleReactNativeError") || (element.methodName == "handleError")) ) ) { // Ignore these base error handling methods. continue } val bundle = Bundle().apply { putInt("column", 0) putInt("lineNumber", element.lineNumber) putString("methodName", element.methodName) putString("file", element.fileName) } stackList.add(bundle) } } val stack = stackList.toTypedArray() BaseExperienceActivity.addError( ExponentError( errorMessage, stack, getExceptionId(exceptionId), isFatal ) ) } private fun getExceptionId(originalId: Int?): Int { return if (originalId == null || originalId == -1) { (-(Math.random() * Int.MAX_VALUE)).toInt() } else originalId } } init { NativeModuleDepsProvider.instance.inject(Kernel::class.java, this) instance = this updateKernelRNOkHttp() } }
bsd-3-clause
2bb6e3306c18a86ad411d51d4526ddf1
34.421284
186
0.676665
5.0691
false
false
false
false
Nunnery/MythicDrops
src/main/kotlin/com/tealcube/minecraft/bukkit/mythicdrops/armor/ArmorListener.kt
1
13862
/* * This file is part of MythicDrops, licensed under the MIT License. * * Copyright (C) 2020 Richard Harrah * * 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.tealcube.minecraft.bukkit.mythicdrops.armor import com.tealcube.minecraft.bukkit.mythicdrops.api.settings.SettingsManager import com.tealcube.minecraft.bukkit.mythicdrops.getThenSetItemMetaAsDamageable import com.tealcube.minecraft.bukkit.mythicdrops.utils.AirUtil import org.bukkit.Bukkit import org.bukkit.entity.Player import org.bukkit.event.Event import org.bukkit.event.EventHandler import org.bukkit.event.EventPriority import org.bukkit.event.Listener import org.bukkit.event.block.Action import org.bukkit.event.block.BlockDispenseArmorEvent import org.bukkit.event.entity.PlayerDeathEvent import org.bukkit.event.inventory.ClickType import org.bukkit.event.inventory.InventoryAction import org.bukkit.event.inventory.InventoryClickEvent import org.bukkit.event.inventory.InventoryDragEvent import org.bukkit.event.inventory.InventoryType import org.bukkit.event.player.PlayerInteractEvent import org.bukkit.event.player.PlayerItemBreakEvent import org.bukkit.inventory.EntityEquipment import org.bukkit.inventory.Inventory import org.bukkit.inventory.ItemStack /** * Modified version of ArmorListener from ArmorEquipEvent. * * https://github.com/Arnuh/ArmorEquipEvent */ class ArmorListener( private val settingsManager: SettingsManager ) : Listener { @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) fun onBlockDispenseArmorEvent(event: BlockDispenseArmorEvent) { val armorType = ArmorType.from(event.item.type) val player = event.targetEntity as? Player if (armorType == null || player == null) { return } val armorEquipEvent = ArmorEquipEvent(player, ArmorEquipEvent.EquipMethod.DISPENSER, armorType, null, event.item) Bukkit.getServer().pluginManager.callEvent(armorEquipEvent) if (armorEquipEvent.isCancelled) { event.isCancelled = true } } @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) fun onInventoryClickEvent(event: InventoryClickEvent) { val shift = event.click == ClickType.SHIFT_LEFT || event.click == ClickType.SHIFT_RIGHT val numberKey = event.click == ClickType.NUMBER_KEY val currentItem = event.currentItem val cursor = event.cursor val armorType = if (shift) { currentItem?.let { ArmorType.from(it.type) } } else { cursor?.let { ArmorType.from(it.type) } } val clickedInventory = event.clickedInventory val isNotSlotWeCareAbout = event.slotType != InventoryType.SlotType.ARMOR val isClickedInventoryNotPlayerInventory = clickedInventory == null || clickedInventory.type != InventoryType.PLAYER val isInventoryNotPlayerOrCrafting = event.inventory.type != InventoryType.PLAYER && event.inventory.type != InventoryType.CRAFTING val isWhoClickedNotAPlayer = event.whoClicked !is Player val isNotDraggingToCorrectSlot = !shift && armorType != null && event.rawSlot != armorType.slot val equipment = (event.whoClicked as? Player)?.equipment val firstCondition = event.action == InventoryAction.NOTHING || isNotSlotWeCareAbout || isClickedInventoryNotPlayerInventory val secondCondition = isInventoryNotPlayerOrCrafting || isWhoClickedNotAPlayer || isNotDraggingToCorrectSlot if (firstCondition || secondCondition || equipment == null) { return } val player = event.whoClicked as Player if (shift) { handleShiftInventoryClick(armorType, event, equipment, player) } else { handleNonShiftInventoryClick(cursor, currentItem, numberKey, clickedInventory, event, armorType, player) } } @EventHandler fun onPlayerInteractEvent(event: PlayerInteractEvent) { val eventItem = event.item val player = event.player val equipment = player.equipment val firstCondition = event.useItemInHand() == Event.Result.DENY || event.action == Action.PHYSICAL || event.action == Action.LEFT_CLICK_AIR || event.action == Action.LEFT_CLICK_BLOCK if (firstCondition || eventItem == null || equipment == null) { return } if (event.useInteractedBlock() != Event.Result.DENY) { val clickedBlock = event.clickedBlock if (clickedBlock != null && event.action == Action.RIGHT_CLICK_BLOCK && !player.isSneaking) { val material = clickedBlock.type if (settingsManager.armorSettings.blocked.contains(material)) { // we kick out since this isn't going to be equipping armor anyway return } } } val armorType = ArmorType.from(eventItem.type) if (armorType != null) { val (isEquippingHelmet, isEquippingChestplate) = determineIfEquippingHelmetOrChestplate( armorType, equipment ) val (isEquippingLeggings, isEquippingBoots) = determineIfEquippingLeggingsOrBoots(armorType, equipment) val isTriggerEvent = isEquippingHelmet || isEquippingChestplate || isEquippingLeggings || isEquippingBoots if (isTriggerEvent) { val armorEquipEvent = ArmorEquipEvent(player, ArmorEquipEvent.EquipMethod.HOTBAR_INTERACT, armorType, null, eventItem) Bukkit.getServer().pluginManager.callEvent(armorEquipEvent) if (armorEquipEvent.isCancelled) { event.isCancelled = true player.updateInventory() } } } } @EventHandler fun onInventoryDragEvent(event: InventoryDragEvent) { val player = event.whoClicked as? Player val armorType = ArmorType.from(event.oldCursor.type) val matchingSlot = event.rawSlots.find { armorType?.slot == it } if (matchingSlot == null || armorType == null || player == null) return val armorEquipEvent = ArmorEquipEvent( player, ArmorEquipEvent.EquipMethod.DEATH, armorType, null, event.oldCursor ) Bukkit.getServer().pluginManager.callEvent(armorEquipEvent) if (armorEquipEvent.isCancelled) { event.result = Event.Result.DENY event.isCancelled = true } } @EventHandler fun onPlayerItemBreakEvent(event: PlayerItemBreakEvent) { val armorType = ArmorType.from(event.brokenItem.type) ?: return val player = event.player val armorEquipEvent = ArmorEquipEvent( player, ArmorEquipEvent.EquipMethod.DEATH, armorType, event.brokenItem, null ) Bukkit.getServer().pluginManager.callEvent(armorEquipEvent) if (!armorEquipEvent.isCancelled) { return } val unbrokenItem = event.brokenItem.clone() unbrokenItem.amount = 1 unbrokenItem.getThenSetItemMetaAsDamageable { damage = (damage - 1).coerceAtLeast(0).coerceAtMost(unbrokenItem.type.maxDurability.toInt()) } when (armorType) { ArmorType.HELMET -> { player.equipment?.helmet = unbrokenItem } ArmorType.CHESTPLATE -> { player.equipment?.chestplate = unbrokenItem } ArmorType.LEGGINGS -> { player.equipment?.leggings = unbrokenItem } ArmorType.BOOTS -> { player.equipment?.boots = unbrokenItem } } } @EventHandler fun onPlayerDeathEvent(event: PlayerDeathEvent) { if (event.keepInventory) return val player = event.entity player.inventory.armorContents.filterNotNull().filterNot { AirUtil.isAir(it.type) }.forEach { itemStack -> ArmorType.from(itemStack.type)?.let { Bukkit.getServer().pluginManager.callEvent( ArmorEquipEvent( player, ArmorEquipEvent.EquipMethod.DEATH, it, itemStack, null ) ) } } } private fun handleNonShiftInventoryClick( cursor: ItemStack?, currentItem: ItemStack?, numberKey: Boolean, clickedInventory: Inventory?, event: InventoryClickEvent, armorType: ArmorType?, player: Player ) { var newArmorType = armorType var newArmorPiece = cursor var oldArmorPiece = currentItem if (numberKey) { if (clickedInventory?.type == InventoryType.PLAYER) { // no crafting 2x2 val hotbarItem = clickedInventory.getItem(event.hotbarButton) if (!isAirOrNull(hotbarItem)) { newArmorType = hotbarItem?.let { ArmorType.from(it.type) } oldArmorPiece = clickedInventory.getItem(event.slot) newArmorPiece = hotbarItem } else { newArmorType = if (!isAirOrNull(currentItem)) { ArmorType.from(currentItem?.type) } else { ArmorType.from(cursor?.type) } } } } else { if (isAirOrNull(cursor) && !isAirOrNull(currentItem)) { newArmorType = ArmorType.from(currentItem?.type) } } if (newArmorType != null && event.rawSlot == newArmorType.slot) { val method = if (event.action == InventoryAction.HOTBAR_SWAP || numberKey) { ArmorEquipEvent.EquipMethod.HOTBAR_SWAP } else { ArmorEquipEvent.EquipMethod.CLICK } val armorEquipEvent = ArmorEquipEvent(player, method, newArmorType, oldArmorPiece, newArmorPiece) Bukkit.getServer().pluginManager.callEvent(armorEquipEvent) if (armorEquipEvent.isCancelled) { event.isCancelled = true } } } private fun handleShiftInventoryClick( armorType: ArmorType?, event: InventoryClickEvent, equipment: EntityEquipment, player: Player ) = armorType?.let { val equipping = event.rawSlot != it.slot val (isEquippingHelmet, isEquippingChestplate) = determineIfEquippingHelmetOrChestplate( armorType, equipment ) val (isEquippingLeggings, isEquippingBoots) = determineIfEquippingLeggingsOrBoots(armorType, equipment) val isTriggerEvent = isEquippingHelmet || isEquippingChestplate || isEquippingLeggings || isEquippingBoots if (isTriggerEvent) { val oldArmorPiece = if (equipping) { null } else { event.currentItem } val newArmorPiece = if (equipping) { event.currentItem } else { null } val armorEquipEvent = ArmorEquipEvent( player, ArmorEquipEvent.EquipMethod.SHIFT_CLICK, armorType, oldArmorPiece, newArmorPiece ) Bukkit.getServer().pluginManager.callEvent(armorEquipEvent) if (armorEquipEvent.isCancelled) { event.isCancelled = true player.updateInventory() } } } private fun determineIfEquippingLeggingsOrBoots( armorType: ArmorType?, equipment: EntityEquipment ): Pair<Boolean, Boolean> { val isEquippingLeggings = armorType == ArmorType.LEGGINGS && isAirOrNull(equipment.leggings) val isEquippingBoots = armorType == ArmorType.BOOTS && isAirOrNull(equipment.boots) return Pair(isEquippingLeggings, isEquippingBoots) } private fun determineIfEquippingHelmetOrChestplate( armorType: ArmorType?, equipment: EntityEquipment ): Pair<Boolean, Boolean> { val isEquippingHelmet = armorType == ArmorType.HELMET && isAirOrNull(equipment.helmet) val isEquippingChestplate = armorType == ArmorType.CHESTPLATE && isAirOrNull(equipment.chestplate) return Pair(isEquippingHelmet, isEquippingChestplate) } private fun isAirOrNull(item: ItemStack?) = item == null || AirUtil.isAir(item.type) }
mit
6b24d2d078cb7c92877207b6bb270664
40.011834
118
0.632809
5.311111
false
false
false
false
Undin/intellij-rust
src/main/kotlin/org/rust/ide/refactoring/move/RsMoveTopLevelItemsProcessor.kt
3
4443
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.ide.refactoring.move import com.intellij.openapi.project.Project import com.intellij.openapi.util.NlsContexts.DialogMessage import com.intellij.openapi.util.Ref import com.intellij.psi.PsiElement import com.intellij.psi.PsiWhiteSpace import com.intellij.refactoring.BaseRefactoringProcessor import com.intellij.refactoring.move.MoveMultipleElementsViewDescriptor import com.intellij.usageView.UsageInfo import com.intellij.usageView.UsageViewDescriptor import com.intellij.util.containers.MultiMap import org.rust.ide.refactoring.move.common.ElementToMove import org.rust.ide.refactoring.move.common.RsMoveCommonProcessor import org.rust.ide.refactoring.move.common.RsMoveUtil.addInner import org.rust.lang.core.psi.RsModItem import org.rust.lang.core.psi.RsPsiFactory import org.rust.lang.core.psi.ext.* import org.rust.lang.core.resolve.namespaces /** See overview of move refactoring in comment for [RsMoveCommonProcessor] */ class RsMoveTopLevelItemsProcessor( private val project: Project, private val itemsToMove: Set<RsItemElement>, private val targetMod: RsMod, private val searchForReferences: Boolean ) : BaseRefactoringProcessor(project) { private val commonProcessor: RsMoveCommonProcessor = run { val elementsToMove = itemsToMove.map { ElementToMove.fromItem(it) } RsMoveCommonProcessor(project, elementsToMove, targetMod) } override fun findUsages(): Array<out UsageInfo> { if (!searchForReferences) return UsageInfo.EMPTY_ARRAY return commonProcessor.findUsages() } private fun checkNoItemsWithSameName(@Suppress("UnstableApiUsage") conflicts: MultiMap<PsiElement, @DialogMessage String>) { if (!searchForReferences) return val targetModItems = targetMod.expandedItemsExceptImplsAndUses .filterIsInstance<RsNamedElement>() .groupBy { it.name } for (item in itemsToMove) { val name = (item as? RsNamedElement)?.name ?: continue val namespaces = item.namespaces val itemsExisting = targetModItems[name] ?: continue for (itemExisting in itemsExisting) { val namespacesExisting = itemExisting.namespaces if ((namespacesExisting intersect namespaces).isNotEmpty()) { conflicts.putValue(itemExisting, "Target file already contains item with name $name") } } } } override fun preprocessUsages(refUsages: Ref<Array<UsageInfo>>): Boolean { val usages = refUsages.get() val conflicts = MultiMap<PsiElement, String>() checkNoItemsWithSameName(conflicts) return commonProcessor.preprocessUsages(usages, conflicts) && showConflicts(conflicts, usages) } override fun performRefactoring(usages: Array<out UsageInfo>) { commonProcessor.performRefactoring(usages, this::moveItems) } private fun moveItems(): List<ElementToMove> { val psiFactory = RsPsiFactory(project) return itemsToMove .sortedBy { it.startOffset } .map { item -> moveItem(item, psiFactory) } } private fun moveItem(item: RsItemElement, psiFactory: RsPsiFactory): ElementToMove { commonProcessor.updateMovedItemVisibility(item) if (targetMod.lastChildInner !is PsiWhiteSpace) { targetMod.addInner(psiFactory.createNewline()) } val targetModLastWhiteSpace = targetMod.lastChildInner as PsiWhiteSpace val space = (item.prevSibling as? PsiWhiteSpace) ?: (item.nextSibling as? PsiWhiteSpace) // have to call `copy` because of rare suspicious `PsiInvalidElementAccessException` val itemNew = targetMod.addBefore(item.copy(), targetModLastWhiteSpace) as RsItemElement targetMod.addBefore(space?.copy() ?: psiFactory.createNewline(), itemNew) space?.delete() item.delete() return ElementToMove.fromItem(itemNew) } override fun createUsageViewDescriptor(usages: Array<out UsageInfo>): UsageViewDescriptor = MoveMultipleElementsViewDescriptor(itemsToMove.toTypedArray(), targetMod.name ?: "") override fun getCommandName(): String = "Move Items" } private val RsMod.lastChildInner: PsiElement? get() = if (this is RsModItem) rbrace?.prevSibling else lastChild
mit
8a6fe5e641c78a6738f97b54f9060bba
40.915094
128
0.72406
4.866375
false
false
false
false
deva666/anko
anko/library/generator/src/org/jetbrains/android/anko/utils/KType.kt
4
1307
package org.jetbrains.android.anko.utils data class KType( val fqName: String, val isNullable: Boolean = false, val variance: Variance = KType.Variance.INVARIANT, val arguments: List<KType> = emptyList() ) { init { assert(!fqName.endsWith("?")) } companion object { val STAR_TYPE = KType("*", isNullable = false) val ANY_TYPE = KType("Any") } enum class Variance { INVARIANT, COVARIANT, CONTRAVARIANT } override fun toString(): String = buildString { val variance = when (variance) { KType.Variance.INVARIANT -> "" KType.Variance.COVARIANT -> "out " KType.Variance.CONTRAVARIANT -> "in " } if (variance.isNotEmpty()) { append(variance) } append(fqName) if (arguments.isNotEmpty()) { append('<') arguments.forEach { append(it.toString()) } append('>') } if (isNullable) { append('?') } } val className: String get() = fqName.split('.').dropWhile { it.all(Char::isPackageSymbol) }.joinToString(".") val packageName: String get() = fqName.split('.').takeWhile { it.all(Char::isPackageSymbol) }.joinToString(".") }
apache-2.0
010b43fee4025f193efa67b9a5965605
25.16
95
0.547054
4.684588
false
false
false
false
HabitRPG/habitrpg-android
Habitica/src/main/java/com/habitrpg/android/habitica/models/tasks/TaskGroupPlan.kt
1
780
package com.habitrpg.android.habitica.models.tasks import com.google.gson.annotations.SerializedName import com.habitrpg.android.habitica.models.BaseObject import io.realm.RealmList import io.realm.RealmObject import io.realm.annotations.RealmClass import java.util.Date @RealmClass(embedded = true) open class TaskGroupPlan : RealmObject(), BaseObject { @SerializedName("id") var groupID: String? = null var managerNotes: String? = null var sharedCompletion: String? = null var assignedDate: Date? = null var assigningUsername: String? = null var assignedUsers: RealmList<String> = RealmList() var approvalRequested: Boolean = false var approvalApproved: Boolean = false var approvalRequired: Boolean = false }
gpl-3.0
a2cb1a04884d49a1d721e8f0cc679b04
30.5
54
0.738462
4.285714
false
false
false
false
edx/edx-app-android
OpenEdXMobile/src/main/java/org/edx/mobile/view/dialog/VideoDownloadQualityDialogFragment.kt
1
4075
package org.edx.mobile.view.dialog import android.app.Dialog import android.content.DialogInterface import android.graphics.Typeface import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Button import androidx.appcompat.app.AlertDialog import androidx.core.content.ContextCompat import androidx.fragment.app.DialogFragment import org.edx.mobile.R import org.edx.mobile.core.IEdxEnvironment import org.edx.mobile.databinding.VideoQualityDialogFragmentBinding import org.edx.mobile.model.video.VideoQuality import org.edx.mobile.module.analytics.Analytics import org.edx.mobile.module.prefs.LoginPrefs import org.edx.mobile.util.ResourceUtil import org.edx.mobile.view.adapters.VideoQualityAdapter class VideoDownloadQualityDialogFragment( var environment: IEdxEnvironment, var callback: IListDialogCallback ) : DialogFragment() { private var loginPref: LoginPrefs? = environment.loginPrefs private val videoQualities: ArrayList<VideoQuality> = arrayListOf() private lateinit var binding: VideoQualityDialogFragmentBinding init { videoQualities.addAll(VideoQuality.values()) } companion object { @JvmStatic val TAG: String = VideoDownloadQualityDialogFragment::class.java.name @JvmStatic fun getInstance( environment: IEdxEnvironment, callback: IListDialogCallback ): VideoDownloadQualityDialogFragment { return VideoDownloadQualityDialogFragment(environment, callback) } } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) environment.analyticsRegistry.trackScreenView( Analytics.Screens.VIDEO_DOWNLOAD_QUALITY, null, Analytics.Values.SCREEN_NAVIGATION ) val platformName = resources.getString(R.string.platform_name) binding.tvVideoQualityMessage.text = ResourceUtil.getFormattedString( resources, R.string.video_download_quality_message, "platform_name", platformName ) var selectedVideoQuality = VideoQuality.AUTO loginPref?.videoQuality?.let { selectedVideoQuality = it } val adapter = object : VideoQualityAdapter(context, environment, selectedVideoQuality) { override fun onItemClicked(videoQuality: VideoQuality) { environment.analyticsRegistry.trackVideoDownloadQualityChanged( videoQuality, environment.loginPrefs.videoQuality ) environment.loginPrefs.videoQuality = videoQuality callback.onItemClicked(videoQuality) dismiss() } } adapter.setItems(videoQualities) binding.videoQualityList.adapter = adapter binding.videoQualityList.onItemClickListener = adapter } override fun onCreateDialog(savedInstanceState: Bundle?): Dialog { binding = VideoQualityDialogFragmentBinding.inflate(LayoutInflater.from(context), null, false) return AlertDialog.Builder(requireContext()) .setNegativeButton( R.string.label_cancel ) { dialog, _ -> dialog.dismiss() }.setView(binding.root).create() } override fun onStart() { super.onStart() val negativeButton: Button = (dialog as AlertDialog).getButton(DialogInterface.BUTTON_NEGATIVE) negativeButton.setTextColor( ContextCompat.getColor( requireContext(), R.color.primaryBaseColor ) ) negativeButton.setTypeface(null, Typeface.BOLD) } interface IListDialogCallback { fun onItemClicked(videoQuality: VideoQuality) } }
apache-2.0
c871bbd75eb7825ccce9549092145d70
34.745614
96
0.689325
5.361842
false
false
false
false
Adonai/Man-Man
app/src/main/java/com/adonai/manman/adapters/ChapterContentsArrayAdapter.kt
1
2328
package com.adonai.manman.adapters import android.content.Context import android.view.View import android.view.ViewGroup import android.widget.ArrayAdapter import android.widget.ImageView import android.widget.SectionIndexer import android.widget.TextView import com.adonai.manman.R import com.adonai.manman.ManChaptersFragment import com.adonai.manman.Utils import com.adonai.manman.entities.ManSectionIndex import com.adonai.manman.entities.ManSectionItem import com.adonai.manman.misc.ManChapterItemOnClickListener /** * Array adapter for showing commands with their description in ListView * It's convenient whet all the data is retrieved via network, * so we have complete command list at hand * * The data retrieval is done through [ManChaptersFragment.loadChapterFromNetwork] * * @see ArrayAdapter * @see ManSectionItem * * @author Kanedias */ class ChapterContentsArrayAdapter(context: Context, resource: Int, textViewResourceId: Int, objects: List<ManSectionItem>) : ArrayAdapter<ManSectionItem>(context, resource, textViewResourceId, objects), SectionIndexer { private val indexes: List<ManSectionIndex> = Utils.createIndexer(objects) override fun getView(position: Int, convertView: View?, parent: ViewGroup): View { val root = super.getView(position, convertView, parent) val current = getItem(position) val command = root.findViewById<View>(R.id.command_name_label) as TextView val desc = root.findViewById<View>(R.id.command_description_label) as TextView val moreActions = root.findViewById<View>(R.id.popup_menu) as ImageView command.text = current!!.name desc.text = current.description moreActions.setOnClickListener(ManChapterItemOnClickListener(context, current)) return root } override fun getSections(): Array<Char> { val chars = CharArray(indexes.size) for (i in indexes.indices) { chars[i] = indexes[i].letter } return chars.toTypedArray() } override fun getPositionForSection(sectionIndex: Int): Int { return indexes[sectionIndex].index } override fun getSectionForPosition(position: Int): Int { for (i in indexes.indices) { if (indexes[i].index > position) return i - 1 } return 0 } }
gpl-3.0
b7b59b4180273c59e0d1c35fb1eb9ebe
33.761194
219
0.730241
4.425856
false
false
false
false
solkin/drawa-android
app/src/main/java/com/tomclaw/drawa/share/ShareView.kt
1
3419
package com.tomclaw.drawa.share import android.view.View import android.view.animation.Animation import android.view.animation.LinearInterpolator import android.view.animation.RotateAnimation import android.widget.Toast import android.widget.ViewFlipper import androidx.appcompat.widget.Toolbar import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import com.jakewharton.rxrelay2.PublishRelay import com.tomclaw.drawa.R import com.tomclaw.drawa.util.CircleProgressView import com.tomclaw.drawa.util.hideWithAlphaAnimation import com.tomclaw.drawa.util.showWithAlphaAnimation import io.reactivex.Observable import java.util.concurrent.TimeUnit interface ShareView { fun showProgress() fun showOverlayProgress() fun resetOverlayProgress() fun setOverlayProgress(value: Float) fun showContent() fun showMessage(text: String) fun navigationClicks(): Observable<Unit> fun itemClicks(): Observable<ShareItem> } class ShareViewImpl( view: View, adapter: ShareAdapter ) : ShareView { private val context = view.context private val toolbar: Toolbar = view.findViewById(R.id.toolbar) private val overlayProgress: View = view.findViewById(R.id.overlay_progress) private val progress: CircleProgressView = view.findViewById(R.id.progress) private val flipper: ViewFlipper = view.findViewById(R.id.flipper) private val recycler: RecyclerView = view.findViewById(R.id.recycler) private val navigationRelay = PublishRelay.create<Unit>() private val itemRelay = PublishRelay.create<ShareItem>() init { toolbar.setTitle(R.string.share) toolbar.setNavigationOnClickListener { navigationRelay.accept(Unit) } val layoutManager = LinearLayoutManager( context, RecyclerView.VERTICAL, false ) adapter.setHasStableIds(true) adapter.itemRelay = itemRelay recycler.adapter = adapter recycler.layoutManager = layoutManager } override fun showProgress() { flipper.displayedChild = 0 } override fun showOverlayProgress() { overlayProgress.showWithAlphaAnimation(animateFully = true) progress.animation = RotateAnimation( 0.0f, 360.0f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f).apply { duration = TimeUnit.SECONDS.toMillis(1) repeatCount = Animation.INFINITE repeatMode = Animation.RESTART fillAfter = true interpolator = LinearInterpolator() } } override fun resetOverlayProgress() { progress.progress = 0f } override fun setOverlayProgress(value: Float) { progress.setProgressWithAnimation(value, 500) } override fun showContent() { flipper.displayedChild = 1 overlayProgress.hideWithAlphaAnimation( animateFully = false, endCallback = { progress.clearAnimation() } ) } override fun showMessage(text: String) { Toast.makeText(context, text, Toast.LENGTH_LONG).show() } override fun navigationClicks(): Observable<Unit> = navigationRelay override fun itemClicks(): Observable<ShareItem> = itemRelay }
apache-2.0
e12bd754d3eab949d3a163130cbb8a71
28.222222
80
0.685288
4.849645
false
false
false
false
adgvcxz/Diycode
app/src/main/java/com/adgvcxz/diycode/ui/main/home/sites/SitesFragmentViewModel.kt
1
2418
package com.adgvcxz.diycode.ui.main.home.sites import android.support.v7.widget.GridLayoutManager import android.support.v7.widget.RecyclerView import com.adgvcxz.diycode.R import com.adgvcxz.diycode.binding.base.BaseViewModel import com.adgvcxz.diycode.binding.recycler.RefreshRecyclerViewModel import com.adgvcxz.diycode.net.ApiService import com.adgvcxz.diycode.ui.base.BaseFragmentViewModel import com.adgvcxz.diycode.util.extensions.actionBarHeight import com.adgvcxz.diycode.util.extensions.app import io.reactivex.Observable import javax.inject.Inject /** * zhaowei * Created by zhaowei on 2017/2/26. */ class SitesFragmentViewModel @Inject constructor(private val apiService: ApiService) : BaseFragmentViewModel() { val listViewModel = SitesViewModel() override fun onCreateView() { super.onCreateView() listViewModel.refresh.set(true) } override fun contentId(): Int = R.layout.fragment_sites inner class SitesViewModel : RefreshRecyclerViewModel<BaseViewModel>() { init { topMargin.set(app.actionBarHeight * 2) } override fun request(offset: Int): Observable<List<BaseViewModel>> { return apiService.getSites().flatMapIterable { it } .flatMap { val list: List<BaseViewModel> = ArrayList() (list as ArrayList<BaseViewModel>).add(SiteTitleViewModel(it.name)) it.sites.mapTo(list, ::SiteViewModel) Observable.fromArray(list) } .flatMapIterable { it } .toList() .toObservable() .compose(httpScheduler<List<BaseViewModel>>()) } override fun createLayoutManager(recyclerView: RecyclerView): RecyclerView.LayoutManager { val layoutManager = GridLayoutManager(recyclerView.context, 2) layoutManager.spanSizeLookup = object : GridLayoutManager.SpanSizeLookup() { override fun getSpanSize(position: Int): Int { if (position >= 1 && position <= items.size) { if (items[position - 1] is SiteTitleViewModel) { return 2 } } return 1 } } return layoutManager } } }
apache-2.0
e592c8a4bed6d520882161b0ce2be53c
35.089552
112
0.616625
5.188841
false
false
false
false
Shockah/Godwit
core/src/pl/shockah/godwit/node/NodeGame.kt
1
1207
package pl.shockah.godwit.node import com.badlogic.gdx.Gdx import com.badlogic.gdx.graphics.GL20 import com.badlogic.gdx.utils.viewport.ScreenViewport import com.badlogic.gdx.utils.viewport.Viewport import pl.shockah.godwit.GodwitApplication import pl.shockah.godwit.LateInitAwaitable import kotlin.math.min open class NodeGame( private val initialStageFactory: () -> Stage ) : GodwitApplication() { companion object { operator fun invoke(stageLayerFactory: () -> StageLayer): NodeGame { return NodeGame { Stage(stageLayerFactory()) } } } var stage: Stage by LateInitAwaitable { _, _, new -> Gdx.input.inputProcessor = new } var maximumDeltaTime: Float? = 1f / 15f constructor(viewport: Viewport = ScreenViewport()) : this({ Stage(StageLayer(viewport)) }) override fun create() { super.create() stage = initialStageFactory() } override fun resize(width: Int, height: Int) { super.resize(width, height) stage.resize(width, height) } override fun render() { super.render() val gdxDelta = Gdx.graphics.deltaTime val delta = maximumDeltaTime?.let { min(gdxDelta, it) } ?: gdxDelta Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT) stage.update(delta) stage.draw() } }
apache-2.0
8634957183babfabc0e7de9945505278
24.166667
91
0.734051
3.288828
false
false
false
false
HabitRPG/habitica-android
Habitica/src/main/java/com/habitrpg/android/habitica/ui/activities/MaintenanceActivity.kt
1
3358
package com.habitrpg.android.habitica.ui.activities import android.content.Intent import android.os.Bundle import android.text.method.LinkMovementMethod import android.view.View import androidx.core.net.toUri import com.habitrpg.android.habitica.R import com.habitrpg.android.habitica.api.MaintenanceApiService import com.habitrpg.android.habitica.components.UserComponent import com.habitrpg.android.habitica.data.ApiClient import com.habitrpg.android.habitica.databinding.ActivityMaintenanceBinding import com.habitrpg.android.habitica.helpers.ExceptionHandler import com.habitrpg.common.habitica.helpers.setMarkdown import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers import io.reactivex.rxjava3.schedulers.Schedulers import javax.inject.Inject class MaintenanceActivity : BaseActivity() { private lateinit var binding: ActivityMaintenanceBinding @Inject lateinit var maintenanceService: MaintenanceApiService @Inject lateinit var apiClient: ApiClient private var isDeprecationNotice: Boolean = false override fun getLayoutResId(): Int { return R.layout.activity_maintenance } override fun getContentView(): View { binding = ActivityMaintenanceBinding.inflate(layoutInflater) return binding.root } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val data = intent.extras ?: return binding.titleTextView.text = data.getString("title") @Suppress("DEPRECATION") binding.imageView.setImageURI(data.getString("imageUrl")?.toUri()) binding.descriptionTextView.setMarkdown(data.getString("description")) binding.descriptionTextView.movementMethod = LinkMovementMethod.getInstance() isDeprecationNotice = data.getBoolean("deprecationNotice") if (isDeprecationNotice) { binding.playStoreButton.visibility = View.VISIBLE } else { binding.playStoreButton.visibility = View.GONE } binding.playStoreButton.setOnClickListener { openInPlayStore() } } override fun injectActivity(component: UserComponent?) { component?.inject(this) } override fun onResume() { super.onResume() if (!isDeprecationNotice) { compositeSubscription.add( this.maintenanceService.maintenanceStatus .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe( { maintenanceResponse -> if (maintenanceResponse.activeMaintenance == false) { finish() } }, ExceptionHandler.rx() ) ) } } private fun openInPlayStore() { val appPackageName = packageName try { startActivity(Intent(Intent.ACTION_VIEW, "market://details?id=$appPackageName".toUri())) } catch (anfe: android.content.ActivityNotFoundException) { startActivity(Intent(Intent.ACTION_VIEW, "https://play.google.com/store/apps/details?id=$appPackageName".toUri())) } } }
gpl-3.0
94984ffaa9a7e823f4b74108dc8f2ad4
34.107527
126
0.65545
5.29653
false
false
false
false
google/private-compute-services
src/com/google/android/as/oss/policies/api/Policy.kt
1
4999
/* * Copyright 2021 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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. */ /* * Copyright 2020 Google LLC. * * This code may only be used under the BSD style license found at * http://polymer.github.io/LICENSE.txt * * Code distributed by Google as part of this project is also subject to an additional IP rights * grant found at * http://polymer.github.io/PATENTS.txt */ package com.google.android.`as`.oss.policies.api import com.google.android.`as`.oss.policies.api.annotation.Annotation import com.google.android.`as`.oss.policies.api.capabilities.Capabilities import com.google.android.`as`.oss.policies.api.capabilities.Capability import com.google.android.`as`.oss.policies.api.contextrules.All import com.google.android.`as`.oss.policies.api.contextrules.PolicyContextRule /** The name of a field within an entity. */ typealias FieldName = String /** Defines a data usage policy. See [PolicyProto] for the canonical definition of a policy. */ data class Policy( val name: String, val egressType: String, val description: String = "", val targets: List<PolicyTarget> = emptyList(), val configs: Map<String, PolicyConfig> = emptyMap(), val annotations: List<Annotation> = emptyList(), val allowedContext: PolicyContextRule = All ) { /** All fields mentioned the policy (includes nested fields). */ val allFields: List<PolicyField> = collectAllFields() /** The set of all redaction labels mentioned in the policy. */ val allRedactionLabels: Set<String> = allFields.flatMap { it.redactedUsages.keys }.toSet() private fun collectAllFields(): List<PolicyField> { fun getAllFields(field: PolicyField): List<PolicyField> { return listOf(field) + field.subfields.flatMap { getAllFields(it) } } return targets.flatMap { target -> target.fields.flatMap { getAllFields(it) } } } } /** Target schema governed by a policy, see [PolicyTargetProto]. */ data class PolicyTarget( val schemaName: String, val maxAgeMs: Long = 0, val retentions: List<PolicyRetention> = emptyList(), val fields: List<PolicyField> = emptyList(), val annotations: List<Annotation> = emptyList() ) { fun toCapabilities(): List<Capabilities> { return retentions.map { val ranges = mutableListOf<Capability>() ranges.add( when (it.medium) { StorageMedium.DISK -> Capability.Persistence.ON_DISK StorageMedium.RAM -> Capability.Persistence.IN_MEMORY } ) if (it.encryptionRequired) { ranges.add(Capability.Encryption(true)) } ranges.add(Capability.Ttl.Minutes((maxAgeMs / Capability.Ttl.MILLIS_IN_MIN).toInt())) Capabilities(ranges) } } } /** Allowed usages for fields in a schema, see [PolicyFieldProto]. */ data class PolicyField( /** List of field names leading from the [PolicyTarget] to this nested field. */ val fieldPath: List<FieldName>, /** Valid usages of this field without redaction. */ val rawUsages: Set<UsageType> = emptySet(), /** Valid usages of this field with redaction first. Maps from redaction label to usages. */ val redactedUsages: Map<String, Set<UsageType>> = emptyMap(), val subfields: List<PolicyField> = emptyList(), val annotations: List<Annotation> = emptyList() ) { init { subfields.forEach { subfield -> require( fieldPath.size < subfield.fieldPath.size && subfield.fieldPath.subList(0, fieldPath.size) == fieldPath ) { "Subfield's field path must be nested inside parent's field path, " + "but got parent: '$fieldPath', child: '${subfield.fieldPath}'." } } } } /** Retention options for storing data, see [PolicyRetentionProto]. */ data class PolicyRetention(val medium: StorageMedium, val encryptionRequired: Boolean = false) /** * Config options specified by a policy, see [PolicyConfigProto]. These are arbitrary string * key-value pairs set by the policy author. They have no direct affect on the policy itself. */ typealias PolicyConfig = Map<String, String> /** Type of usage permitted of a field, see [PolicyFieldProto.UsageType]. */ enum class UsageType { ANY, EGRESS, JOIN, SANDBOX; val canEgress get() = this == ANY || this == EGRESS } /** Convenience method for checking if any usage in a set allows egress. */ fun Set<UsageType>.canEgress(): Boolean = any { it.canEgress } /** Target schema governed by a policy, see [PolicyRetentionProto.Medium]. */ enum class StorageMedium { RAM, DISK, }
apache-2.0
c2a6b24ea92f94d8588ed98afb03f182
34.453901
96
0.708542
4.097541
false
false
false
false
rhdunn/xquery-intellij-plugin
src/main/java/uk/co/reecedunn/intellij/plugin/xquery/codeInspection/xqst/XQST0118.kt
1
2838
/* * Copyright (C) 2017-2018 Reece H. Dunn * * 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 uk.co.reecedunn.intellij.plugin.xquery.codeInspection.xqst import com.intellij.codeInspection.InspectionManager import com.intellij.codeInspection.LocalQuickFix import com.intellij.codeInspection.ProblemDescriptor import com.intellij.codeInspection.ProblemHighlightType import com.intellij.psi.PsiElement import com.intellij.psi.PsiFile import com.intellij.util.SmartList import uk.co.reecedunn.intellij.plugin.core.codeInspection.Inspection import uk.co.reecedunn.intellij.plugin.core.sequences.walkTree import uk.co.reecedunn.intellij.plugin.intellij.resources.XQueryPluginBundle import uk.co.reecedunn.intellij.plugin.xdm.functions.op.qname_presentation import uk.co.reecedunn.intellij.plugin.xquery.ast.xquery.XQueryDirElemConstructor import uk.co.reecedunn.intellij.plugin.xquery.ast.xquery.XQueryModule class XQST0118 : Inspection("xqst/XQST0118.md", XQST0118::class.java.classLoader) { override fun checkFile(file: PsiFile, manager: InspectionManager, isOnTheFly: Boolean): Array<ProblemDescriptor>? { if (file !is XQueryModule) return null val descriptors = SmartList<ProblemDescriptor>() file.walkTree().filterIsInstance<XQueryDirElemConstructor>().forEach { elem -> val openTag = elem.nodeName val closeTag = elem.closingTag if (openTag?.localName == null || closeTag?.localName == null) return@forEach if (openTag.prefix?.data != closeTag.prefix?.data || openTag.localName?.data != closeTag.localName?.data) { val description = XQueryPluginBundle.message( "inspection.XQST0118.mismatched-dir-elem-tag-name.message", qname_presentation(closeTag)!!, qname_presentation(openTag)!! ) val context = closeTag as PsiElement descriptors.add( manager.createProblemDescriptor( context, description, null as LocalQuickFix?, ProblemHighlightType.GENERIC_ERROR, isOnTheFly ) ) } } return descriptors.toTypedArray() } }
apache-2.0
8695f38c69cd15afa744389581112b0a
44.790323
119
0.687456
4.777778
false
false
false
false
jiaminglu/kotlin-native
backend.native/tests/external/codegen/box/classes/kt1726.kt
5
284
class Foo( var state : Int, val f : (Int) -> Int){ fun next() : Int { val nextState = f(state) state = nextState return state } } fun box(): String { val f = Foo(23, {x -> 2 * x}) return if (f.next() == 46) "OK" else "fail" }
apache-2.0
05c4af50393add1c28675f20d6f673d0
17.933333
47
0.461268
3.227273
false
false
false
false
M4R1KU/releasr
backend/src/main/kotlin/me/mkweb/releasr/web/auth/JwtAuthenticationProvider.kt
1
2254
package me.mkweb.releasr.web.auth import me.mkweb.releasr.model.repository.UserRepository import me.mkweb.releasr.web.auth.model.GitHubUser import me.mkweb.releasr.web.auth.model.JwtAuthenticationToken import me.mkweb.releasr.web.auth.util.JwtUtil import org.springframework.security.authentication.AuthenticationProvider import org.springframework.security.authentication.BadCredentialsException import org.springframework.security.core.Authentication import org.springframework.stereotype.Component @Component class JwtAuthenticationProvider(val jwtUtil: JwtUtil, val userRepository: UserRepository) : AuthenticationProvider { override fun authenticate(authentication: Authentication?): Authentication { val jwtAuthenticationToken = authentication as JwtAuthenticationToken val token = jwtAuthenticationToken.token val parsedUser = jwtUtil.parseToken(token) ?: throw BadCredentialsException("JWT token is not valid") val user = userRepository.findByMail(parsedUser["mail"] as String) ?: throw IllegalStateException("User must exist in db") return JwtAuthenticationToken(token, GitHubUser(parsedUser.subject, user.accessToken, user.mail)) } override fun supports(authentication: Class<*>?): Boolean { return JwtAuthenticationToken::class.java.isAssignableFrom(authentication) } /*override fun supports(authentication: Class<*>): Boolean { return JwtAuthenticationToken::class.java.isAssignableFrom(authentication) } @Throws(AuthenticationException::class) override fun additionalAuthenticationChecks(userDetails: UserDetails, authentication: UsernamePasswordAuthenticationToken) { } @Throws(AuthenticationException::class) override fun retrieveUser(username: String, authentication: Authentication): UserDetails { val jwtAuthenticationToken = authentication as JwtAuthenticationToken val token = jwtAuthenticationToken.token val parsedUser = jwtUtil.parseToken(token) ?: throw BadCredentialsException("JWT token is not valid") //val authorityList = AuthorityUtils.commaSeparatedStringToAuthorityList(parsedUser.getRole()) return GitHubUser(parsedUser.username) }*/ }
mit
17150acfb199d469ddcd895776e4be2e
45.979167
130
0.77551
5.497561
false
false
false
false
StepicOrg/stepic-android
app/src/main/java/org/stepic/droid/code/highlight/themes/CodeSyntax.kt
2
2247
package org.stepic.droid.code.highlight.themes import androidx.annotation.ColorInt import org.stepic.droid.code.highlight.prettify.parser.Prettify.PR_ATTRIB_NAME import org.stepic.droid.code.highlight.prettify.parser.Prettify.PR_ATTRIB_VALUE import org.stepic.droid.code.highlight.prettify.parser.Prettify.PR_COMMENT import org.stepic.droid.code.highlight.prettify.parser.Prettify.PR_DECLARATION import org.stepic.droid.code.highlight.prettify.parser.Prettify.PR_KEYWORD import org.stepic.droid.code.highlight.prettify.parser.Prettify.PR_LITERAL import org.stepic.droid.code.highlight.prettify.parser.Prettify.PR_NOCODE import org.stepic.droid.code.highlight.prettify.parser.Prettify.PR_PLAIN import org.stepic.droid.code.highlight.prettify.parser.Prettify.PR_PUNCTUATION import org.stepic.droid.code.highlight.prettify.parser.Prettify.PR_SOURCE import org.stepic.droid.code.highlight.prettify.parser.Prettify.PR_STRING import org.stepic.droid.code.highlight.prettify.parser.Prettify.PR_TAG import org.stepic.droid.code.highlight.prettify.parser.Prettify.PR_TYPE class CodeSyntax( @ColorInt val plain: Int, @ColorInt string: Int = plain, @ColorInt keyword: Int = plain, @ColorInt comment: Int = plain, @ColorInt type: Int = plain, @ColorInt literal: Int = plain, @ColorInt punctuation: Int = plain, @ColorInt tag: Int = plain, @ColorInt declaration: Int = plain, @ColorInt source: Int = plain, @ColorInt attributeName: Int = plain, @ColorInt attributeValue: Int = plain, @ColorInt nocode: Int = plain ) { fun shouldBePainted(prType: String) = colorMap[prType] != plain val colorMap = hashMapOf( PR_STRING to string, PR_KEYWORD to keyword, PR_COMMENT to comment, PR_TYPE to type, PR_LITERAL to literal, PR_PUNCTUATION to punctuation, PR_PLAIN to plain, PR_TAG to tag, PR_DECLARATION to declaration, PR_SOURCE to source, PR_ATTRIB_NAME to attributeName, PR_ATTRIB_VALUE to attributeValue, PR_NOCODE to nocode ) }
apache-2.0
b341b97e20d2c51a9691a3136797a472
42.230769
79
0.686693
4.019678
false
false
false
false
jiaminglu/kotlin-native
backend.native/tests/external/codegen/boxInline/lambdaTransformation/sameCaptured.kt
3
1042
// FILE: 1.kt package test inline fun <R> doWork(crossinline job: ()-> R) : R { val k = 10; return notInline({k; job()}) } inline fun <R> doWork(crossinline job: ()-> R, crossinline job2: () -> R) : R { val k = 10; return notInline({k; job(); job2()}) } fun <R> notInline(job: ()-> R) : R { return job() } // FILE: 2.kt //NO_CHECK_LAMBDA_INLINING import test.* fun testSameCaptured() : String { var result = 0; result = doWork({result+=1; result}, {result += 11; result}) return if (result == 12) "OK" else "fail ${result}" } inline fun testSameCaptured(crossinline lambdaWithResultCaptured: () -> Unit) : String { var result = 1; result = doWork({result+=11; lambdaWithResultCaptured(); result}) return if (result == 12) "OK" else "fail ${result}" } fun box(): String { if (testSameCaptured() != "OK") return "test1 : ${testSameCaptured()}" var result = 0; if (testSameCaptured{result += 1111} != "OK") return "test2 : ${testSameCaptured{result = 1111}}" return "OK" }
apache-2.0
f16d20ee5bf78cadc0d7288949109d4c
22.681818
101
0.603647
3.318471
false
true
false
false
CarlosEsco/tachiyomi
app/src/main/java/eu/kanade/presentation/more/settings/widget/MultiSelectListPreferenceWidget.kt
1
4302
package eu.kanade.presentation.more.settings.widget import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.selection.selectable import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material3.AlertDialog import androidx.compose.material3.Checkbox import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.material3.TextButton import androidx.compose.runtime.Composable import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.toMutableStateList import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.res.stringResource import androidx.compose.ui.unit.dp import androidx.compose.ui.window.DialogProperties import eu.kanade.presentation.more.settings.Preference import eu.kanade.presentation.util.minimumTouchTargetSize @Composable fun MultiSelectListPreferenceWidget( preference: Preference.PreferenceItem.MultiSelectListPreference, values: Set<String>, onValuesChange: (Set<String>) -> Unit, ) { val (isDialogShown, showDialog) = remember { mutableStateOf(false) } TextPreferenceWidget( title = preference.title, subtitle = preference.subtitle, icon = preference.icon, onPreferenceClick = { showDialog(true) }, ) if (isDialogShown) { val selected = remember { preference.entries.keys .filter { values.contains(it) } .toMutableStateList() } AlertDialog( onDismissRequest = { showDialog(false) }, title = { Text(text = preference.title) }, text = { LazyColumn { preference.entries.forEach { current -> item { val isSelected = selected.contains(current.key) val onSelectionChanged = { when (!isSelected) { true -> selected.add(current.key) false -> selected.remove(current.key) } } Row( verticalAlignment = Alignment.CenterVertically, modifier = Modifier .clip(RoundedCornerShape(8.dp)) .selectable( selected = isSelected, onClick = { onSelectionChanged() }, ) .minimumTouchTargetSize() .fillMaxWidth(), ) { Checkbox( checked = isSelected, onCheckedChange = null, ) Text( text = current.value, style = MaterialTheme.typography.bodyMedium, modifier = Modifier.padding(start = 24.dp), ) } } } } }, properties = DialogProperties( usePlatformDefaultWidth = true, ), confirmButton = { TextButton( onClick = { onValuesChange(selected.toMutableSet()) showDialog(false) }, ) { Text(text = stringResource(android.R.string.ok)) } }, dismissButton = { TextButton(onClick = { showDialog(false) }) { Text(text = stringResource(android.R.string.cancel)) } }, ) } }
apache-2.0
73079adfac83257fbaa8aa876203fa98
39.205607
80
0.514179
6.189928
false
false
false
false
Saketme/JRAW
meta/src/main/kotlin/net/dean/jraw/meta/EnumCreator.kt
1
5039
package net.dean.jraw.meta import com.grosner.kpoet.* import com.squareup.javapoet.ClassName import java.io.File class EnumCreator(val endpoints: List<ParsedEndpoint>, val indent: Int = 4) { fun writeTo(out: File): File { createJavaFile().writeTo(out); return absoluteOutput(out) } fun writeTo(out: Appendable): File { createJavaFile().writeTo(out); return File(".") } private fun absoluteOutput(srcRoot: File): File { return File(srcRoot, RELATIVE_OUTPUT_FILE) } private fun createJavaFile() = // Create the file definition belonging to package net.dean.jraw and configuring the indent using spaces javaFile(PACKAGE, { indent(" ".repeat(indent)) skipJavaLangImports(true) `import static`(ClassName.get(PACKAGE, ENUM_NAME, INNER_CLASS_NAME), SUBREDDIT_PREFIX_CONSTANT_NAME) }) { // public enum Endpoint enum(ENUM_NAME) { modifiers(public) // Add Javadoc to the enum javadoc("This is a dynamically generated enumeration of all reddit API endpoints.\n\n") javadoc( "For JRAW developers: this class should not be edited by hand. This class can be regenerated " + "through the ${code(":meta:update")} Gradle task.") // Dynamically add a enum value for each endpoint for (e in endpoints) { case(enumName(e), "\$S, \$L, \$S", e.method, enumPath(e), e.oauthScope) { javadoc(javadocFor(e)) } } // Declare the inner static class with the 'optional subreddit' constant addType(`public class`(INNER_CLASS_NAME) { modifiers(static) `public static final field`(String::class, SUBREDDIT_PREFIX_CONSTANT_NAME, { this.`=`(SUBREDDIT_PREFIX_CONSTANT_VALUE.S) }) }) // Declare three private final fields "method", "path", and "scope" `private final field`(String::class, "method") `private final field`(String::class, "path") `private final field`(String::class, "scope") // Create constructor which takes those three fields as parameters `constructor`(`final param`(String::class, "method"), `final param`(String::class, "path"), `final param`(String::class, "scope")) { statement("this.method = method") statement("this.path = path") statement("this.scope = scope") } // Create getters for the "path" and "method" fields `public`(String::class, "getPath") { javadoc("Gets this Endpoint's path, e.g. ${code("/api/comment")}") `return`("this.path") } `public`(String::class, "getMethod") { javadoc("Gets this Endpoint's HTTP method (\"GET\", \"POST\", etc.)") `return`("this.method") } `public`(String::class, "getScope") { javadoc("Gets the OAuth2 scope required to use this endpoint") `return`("this.scope") } } } companion object { const val ENUM_NAME = "Endpoint" const val PACKAGE = "net.dean.jraw" const val INNER_CLASS_NAME = "Constant" const val SUBREDDIT_PREFIX_CONSTANT_NAME = "OPTIONAL_SUBREDDIT" const val SUBREDDIT_PREFIX_CONSTANT_VALUE = "[/r/{subreddit}]" @JvmField val RELATIVE_OUTPUT_FILE = PACKAGE.replace('.', File.separatorChar) + "/$ENUM_NAME.java" private val stripPrefixes = listOf("/api/v1/", "/api/", "/") private fun enumName(e: ParsedEndpoint): String { var name = e.path stripPrefixes .asSequence() .filter { name.startsWith(it) } .forEach { name = name.substring(it.length).removeSuffix(".json") } if (name.startsWith("r/{subreddit}")) name = "subreddit" + name.substring("r/{subreddit}".length) return (e.method + '_' + name.replace('/', '_')) .toUpperCase() .replace("{", "") .replace("}", "") } private fun enumPath(e: ParsedEndpoint) = if (e.subredditPrefix) "$SUBREDDIT_PREFIX_CONSTANT_NAME + ${e.path.S}" else e.path.S private fun javadocFor(e: ParsedEndpoint): String = "Represents the endpoint ${code(e.method + " " + e.path)}. Requires OAuth scope '${e.oauthScope}'. See " + link("here", e.redditDocLink) + " for more information" private fun link(displayText: String, url: String) = "<a href=\"$url\">$displayText</a>" fun code(text: String) = "{@code $text}" } }
mit
53de33c1da465f9943e6f2acaf480f67
42.068376
143
0.538004
4.704949
false
false
false
false
Tandrial/Advent_of_Code
src/aoc2018/kot/Day23.kt
1
2405
package aoc2018.kot import diffBy import getNumbers import java.io.File import java.util.* import kotlin.math.abs object Day23 { data class State(val sender: Sender, val inRange: Int) : Comparable<State> { override fun compareTo(other: State) = if (other.inRange == inRange) sender.r.compareTo(other.sender.r) else other.inRange.compareTo(inRange) } data class Sender(val x: Long, val y: Long, val z: Long, var r: Long) { val dist = abs(x) + abs(y) + abs(z) fun inRange(other: Sender) = (abs(x - other.x) + abs(y - other.y) + abs(z - other.z)) <= r fun intersect(other: Sender) = (abs(x - other.x) + abs(y - other.y) + abs(z - other.z)) <= r + other.r } fun partOne(input: List<String>): Int { val senders = parse(input) val maxSender = senders.maxBy { it.r }!! return senders.count { maxSender.inRange(it) } } fun partTwo(input: List<String>): Long { val senders = parse(input) val radius = maxOf(senders.diffBy { it.x }, senders.diffBy { it.y }, senders.diffBy { it.z }) val checked = mutableSetOf<Sender>() val queue = PriorityQueue<State>(listOf(State(Sender(0, 0, 0, radius), 0))) var max = queue.peek() while (queue.isNotEmpty()) { val (sender, inRange) = queue.poll() if (sender.r == 0L) { if (inRange > max.inRange || (inRange == max.inRange && sender.dist < max.sender.dist)) { max = State(sender, inRange) queue.removeIf { it.inRange <= inRange } } } else if (checked.add(sender)) { val neuR = sender.r / 2 val next = (-1L..1L).flatMap { xOff -> (-1L..1L).flatMap { yOff -> (-1L..1L).mapNotNull { zOff -> val neu = Sender(sender.x + xOff * neuR, sender.y + yOff * neuR, sender.z + zOff * neuR, neuR) val count = senders.count { it.intersect(neu) } if (count >= max.inRange) State(neu, count) else null } } } queue.addAll(next) } } return max.sender.dist } fun parse(input: List<String>) = input.map { val (x, y, z, r) = it.getNumbers() Sender(x.toLong(), y.toLong(), z.toLong(), r.toLong()) } } fun main(args: Array<String>) { val input = File("./input/2018/Day23_input.txt").readLines() println("Part One = ${Day23.partOne(input)}") println("Part Two = ${Day23.partTwo(input)}") }
mit
1e4aee15597ab0e18981884b1470d28a
32.402778
145
0.583784
3.281037
false
false
false
false
Maccimo/intellij-community
plugins/kotlin/fir-fe10-binding/src/org/jetbrains/kotlin/idea/fir/fe10/BaseDescriptorsWrappers.kt
2
37775
// 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.fir.fe10 import org.jetbrains.kotlin.analysis.api.KtConstantInitializerValue import org.jetbrains.kotlin.analysis.api.annotations.* import org.jetbrains.kotlin.analysis.api.base.KtConstantValue import org.jetbrains.kotlin.analysis.api.symbols.* import org.jetbrains.kotlin.analysis.api.symbols.markers.KtAnnotatedSymbol import org.jetbrains.kotlin.analysis.api.symbols.markers.KtNamedSymbol import org.jetbrains.kotlin.analysis.api.symbols.markers.KtSymbolWithKind import org.jetbrains.kotlin.analysis.api.symbols.markers.KtSymbolWithTypeParameters import org.jetbrains.kotlin.analysis.api.types.KtType import org.jetbrains.kotlin.descriptors.* import org.jetbrains.kotlin.descriptors.annotations.AnnotationDescriptor import org.jetbrains.kotlin.descriptors.annotations.Annotations import org.jetbrains.kotlin.descriptors.impl.AbstractReceiverParameterDescriptor import org.jetbrains.kotlin.descriptors.impl.ReceiverParameterDescriptorImpl import org.jetbrains.kotlin.ir.util.IdSignature import org.jetbrains.kotlin.name.FqName import org.jetbrains.kotlin.name.Name import org.jetbrains.kotlin.name.SpecialNames import org.jetbrains.kotlin.psi.KtPureElement import org.jetbrains.kotlin.resolve.constants.* import org.jetbrains.kotlin.resolve.scopes.MemberScope import org.jetbrains.kotlin.resolve.scopes.receivers.ExtensionReceiver import org.jetbrains.kotlin.resolve.scopes.receivers.ImplicitClassReceiver import org.jetbrains.kotlin.resolve.scopes.receivers.ReceiverValue import org.jetbrains.kotlin.resolve.source.toSourceElement import org.jetbrains.kotlin.storage.StorageManager import org.jetbrains.kotlin.types.* import org.jetbrains.kotlin.utils.addToStdlib.safeAs /** * List of known problems/not-implemented: * - getOrigin return itself all the time. Formally it should return "unsubstituted" version of itself, but it isn't clear, * if we really needed that nor how to implemented it. Btw, it is relevant only to member functions/properties (unlikely, but may be to * inner classes) and not for "resulting descriptor". I.e. only class/interface type parameters could be substituted in FIR, * there is no "resulting descriptor" and type arguments are passed together with the target function. * - equals on descriptors and type constructors. It isn't clear what type of equality we should implement, * will figure that later o real cases. * See the functions below */ internal fun FE10BindingContext.containerDeclarationImplementationPostponed(): Nothing = implementationPostponed("It isn't clear what we really need and how to implement it") internal fun FE10BindingContext.typeAliasImplementationPlanned(): Nothing = implementationPlanned("It is easy to implement, but it isn't first priority") interface KtSymbolBasedNamed : Named { val ktSymbol: KtNamedSymbol override fun getName(): Name = ktSymbol.name } private fun Visibility.toDescriptorVisibility(): DescriptorVisibility = when (this) { Visibilities.Public -> DescriptorVisibilities.PUBLIC Visibilities.Private -> DescriptorVisibilities.PRIVATE Visibilities.PrivateToThis -> DescriptorVisibilities.PRIVATE_TO_THIS Visibilities.Protected -> DescriptorVisibilities.PROTECTED Visibilities.Internal -> DescriptorVisibilities.INTERNAL Visibilities.Local -> DescriptorVisibilities.LOCAL else -> error("Unknown visibility: $this") } private fun KtClassKind.toDescriptorKlassKind(): ClassKind = when (this) { KtClassKind.CLASS -> ClassKind.CLASS KtClassKind.ENUM_CLASS -> ClassKind.ENUM_CLASS KtClassKind.ENUM_ENTRY -> ClassKind.ENUM_ENTRY KtClassKind.ANNOTATION_CLASS -> ClassKind.ANNOTATION_CLASS KtClassKind.OBJECT, KtClassKind.COMPANION_OBJECT, KtClassKind.ANONYMOUS_OBJECT -> ClassKind.OBJECT KtClassKind.INTERFACE -> ClassKind.INTERFACE } private fun KtAnnotationValue.toConstantValue(): ConstantValue<*> { return when (this) { KtUnsupportedAnnotationValue -> ErrorValue.create("Unsupported annotation value") is KtArrayAnnotationValue -> ArrayValue(values.map { it.toConstantValue() }) { TODO() } is KtAnnotationApplicationValue -> TODO() is KtKClassAnnotationValue.KtNonLocalKClassAnnotationValue -> KClassValue(classId, arrayDimensions = 0) is KtKClassAnnotationValue.KtLocalKClassAnnotationValue -> TODO() is KtKClassAnnotationValue.KtErrorClassAnnotationValue -> ErrorValue.create("Unresolved class") is KtEnumEntryAnnotationValue -> { val callableId = callableId ?: return ErrorValue.create("Unresolved enum entry") val classId = callableId.classId ?: return ErrorValue.create("Unresolved enum entry") EnumValue(classId, callableId.callableName) } is KtConstantAnnotationValue -> constantValue.toConstantValue() } } private fun KtConstantValue.toConstantValue(): ConstantValue<*> = when (this) { is KtConstantValue.KtErrorConstantValue -> ErrorValue.create(errorMessage) else -> when (constantValueKind) { ConstantValueKind.Null -> NullValue() ConstantValueKind.Boolean -> BooleanValue(value as Boolean) ConstantValueKind.Char -> CharValue(value as Char) ConstantValueKind.Byte -> ByteValue(value as Byte) ConstantValueKind.Short -> ShortValue(value as Short) ConstantValueKind.Int -> IntValue(value as Int) ConstantValueKind.Long -> LongValue(value as Long) ConstantValueKind.String -> StringValue(value as String) ConstantValueKind.Float -> FloatValue(value as Float) ConstantValueKind.Double -> DoubleValue(value as Double) ConstantValueKind.UnsignedByte -> UByteValue(value as Byte) ConstantValueKind.UnsignedShort -> UShortValue(value as Short) ConstantValueKind.UnsignedInt -> UIntValue(value as Int) ConstantValueKind.UnsignedLong -> ULongValue(value as Long) else -> error("Unexpected constant KtSimpleConstantValue: $value (class: ${value?.javaClass}") } } abstract class KtSymbolBasedDeclarationDescriptor(val context: FE10BindingContext) : DeclarationDescriptorWithSource { abstract val ktSymbol: KtSymbol override val annotations: Annotations get() { val ktAnnotations = (ktSymbol as? KtAnnotatedSymbol)?.annotations ?: return Annotations.EMPTY return Annotations.create(ktAnnotations.map { KtSymbolBasedAnnotationDescriptor(it, context) }) } override fun getSource(): SourceElement = ktSymbol.psi.safeAs<KtPureElement>().toSourceElement() override fun getContainingDeclaration(): DeclarationDescriptor { if (ktSymbol !is KtSymbolWithKind) error("ContainingDeclaration should be overridden") val containerSymbol = context.withAnalysisSession { (ktSymbol as KtSymbolWithKind).getContainingSymbol() } if (containerSymbol != null) return containerSymbol.toDeclarationDescriptor(context) // i.e. declaration is top-level return KtSymbolBasedPackageFragmentDescriptor(getPackageFqNameIfTopLevel(), context) } protected abstract fun getPackageFqNameIfTopLevel(): FqName private fun KtSymbol.toSignature(): IdSignature = context.ktAnalysisSessionFacade.toSignature(this) override fun equals(other: Any?): Boolean { if (other === this) return true if (other !is KtSymbolBasedDeclarationDescriptor) return false ktSymbol.psi?.let { return other.ktSymbol.psi == it } return ktSymbol.toSignature() == other.ktSymbol.toSignature() } override fun hashCode(): Int { ktSymbol.psi?.let { return it.hashCode() } return ktSymbol.toSignature().hashCode() } override fun <R : Any?, D : Any?> accept(visitor: DeclarationDescriptorVisitor<R, D>?, data: D): R = noImplementation() override fun acceptVoid(visitor: DeclarationDescriptorVisitor<Void, Void>?): Unit = noImplementation() // stub for automatic Substitutable<T> implementation for all relevant subclasses fun substitute(substitutor: TypeSubstitutor): Nothing = noImplementation() protected fun noImplementation(): Nothing = context.noImplementation("ktSymbol = $ktSymbol") protected fun implementationPostponed(): Nothing = context.implementationPostponed("ktSymbol = $ktSymbol") protected fun implementationPlanned(): Nothing = context.implementationPlanned("ktSymbol = $ktSymbol") override fun toString(): String = this.javaClass.getSimpleName() + " " + this.getName() } class KtSymbolBasedAnnotationDescriptor( private val ktAnnotationCall: KtAnnotationApplication, val context: FE10BindingContext ) : AnnotationDescriptor { override val type: KotlinType get() = context.implementationPlanned("ktAnnotationCall = $ktAnnotationCall") override val fqName: FqName? get() = ktAnnotationCall.classId?.asSingleFqName() override val allValueArguments: Map<Name, ConstantValue<*>> = ktAnnotationCall.arguments.associate { it.name to it.expression.toConstantValue() } override val source: SourceElement get() = ktAnnotationCall.psi.toSourceElement() } class KtSymbolBasedClassDescriptor(override val ktSymbol: KtNamedClassOrObjectSymbol, context: FE10BindingContext) : KtSymbolBasedDeclarationDescriptor(context), KtSymbolBasedNamed, ClassDescriptor { override fun isInner(): Boolean = ktSymbol.isInner override fun isCompanionObject(): Boolean = ktSymbol.classKind == KtClassKind.COMPANION_OBJECT override fun isData(): Boolean = ktSymbol.isData override fun isInline(): Boolean = ktSymbol.isInline // seems like th`is `flag should be removed in favor of isValue override fun isValue(): Boolean = ktSymbol.isInline override fun isFun(): Boolean = ktSymbol.isFun override fun isExpect(): Boolean = implementationPostponed() override fun isActual(): Boolean = implementationPostponed() override fun isExternal(): Boolean = ktSymbol.isExternal override fun getVisibility(): DescriptorVisibility = ktSymbol.visibility.toDescriptorVisibility() override fun getModality(): Modality = ktSymbol.modality override fun getKind(): ClassKind = ktSymbol.classKind.toDescriptorKlassKind() override fun getCompanionObjectDescriptor(): ClassDescriptor? = ktSymbol.companionObject?.let { KtSymbolBasedClassDescriptor(it, context) } override fun getTypeConstructor(): TypeConstructor = KtSymbolBasedClassTypeConstructor(this) override fun getDeclaredTypeParameters(): List<TypeParameterDescriptor> = getTypeParameters(ktSymbol) override fun getDefaultType(): SimpleType { val arguments = TypeUtils.getDefaultTypeProjections(typeConstructor.parameters) return KotlinTypeFactory.simpleTypeWithNonTrivialMemberScope( TypeAttributes.Empty, typeConstructor, arguments, false, MemberScopeForKtSymbolBasedDescriptors { "ktSymbol = $ktSymbol" } ) } override fun getThisAsReceiverParameter(): ReceiverParameterDescriptor = ReceiverParameterDescriptorImpl(this, ImplicitClassReceiver(this), Annotations.EMPTY) override fun getContextReceivers(): List<ReceiverParameterDescriptor> = implementationPlanned() override fun getOriginal(): ClassDescriptor = this override fun getUnsubstitutedPrimaryConstructor(): ClassConstructorDescriptor? = context.withAnalysisSession { ktSymbol.getDeclaredMemberScope().getConstructors().firstOrNull { it.isPrimary } ?.let { KtSymbolBasedConstructorDescriptor(it, this@KtSymbolBasedClassDescriptor) } } @OptIn(ExperimentalStdlibApi::class) override fun getConstructors(): Collection<ClassConstructorDescriptor> = context.withAnalysisSession { ktSymbol.getDeclaredMemberScope().getConstructors().map { KtSymbolBasedConstructorDescriptor(it, this@KtSymbolBasedClassDescriptor) }.toList() } override fun getPackageFqNameIfTopLevel(): FqName = (ktSymbol.classIdIfNonLocal ?: error("should be top-level")).packageFqName override fun getSealedSubclasses(): Collection<ClassDescriptor> = implementationPostponed() override fun getValueClassRepresentation(): ValueClassRepresentation<SimpleType> = TODO("Not yet implemented") override fun getMemberScope(typeArguments: MutableList<out TypeProjection>): MemberScope = noImplementation() override fun getMemberScope(typeSubstitution: TypeSubstitution): MemberScope = noImplementation() override fun getUnsubstitutedMemberScope(): MemberScope = noImplementation() override fun getUnsubstitutedInnerClassesScope(): MemberScope = noImplementation() override fun getStaticScope(): MemberScope = noImplementation() override fun isDefinitelyNotSamInterface(): Boolean = noImplementation() override fun getDefaultFunctionTypeForSamInterface(): SimpleType = noImplementation() } class KtSymbolBasedTypeParameterDescriptor( override val ktSymbol: KtTypeParameterSymbol, context: FE10BindingContext ) : KtSymbolBasedDeclarationDescriptor(context), KtSymbolBasedNamed, TypeParameterDescriptor { override fun isReified(): Boolean = ktSymbol.isReified override fun getVariance(): Variance = ktSymbol.variance override fun getTypeConstructor(): TypeConstructor = KtSymbolBasedTypeParameterTypeConstructor(this) override fun getDefaultType(): SimpleType = KotlinTypeFactory.simpleTypeWithNonTrivialMemberScope( TypeAttributes.Empty, typeConstructor, emptyList(), false, MemberScopeForKtSymbolBasedDescriptors { "ktSymbol = $ktSymbol" } ) override fun getUpperBounds(): List<KotlinType> = ktSymbol.upperBounds.map { it.toKotlinType(context) } override fun getOriginal(): TypeParameterDescriptor = this override fun getContainingDeclaration(): DeclarationDescriptor = context.containerDeclarationImplementationPostponed() override fun getPackageFqNameIfTopLevel(): FqName = error("Should be called") // there is no such thing in FIR, and it seems like it isn't really needed for IDE and could be bypassed on client site override fun getIndex(): Int = implementationPostponed() override fun isCapturedFromOuterDeclaration(): Boolean = noImplementation() override fun getStorageManager(): StorageManager = noImplementation() } abstract class KtSymbolBasedFunctionLikeDescriptor(context: FE10BindingContext) : KtSymbolBasedDeclarationDescriptor(context), FunctionDescriptor { abstract override val ktSymbol: KtFunctionLikeSymbol override fun getReturnType(): KotlinType = ktSymbol.returnType.toKotlinType(context) override fun getValueParameters(): List<ValueParameterDescriptor> = ktSymbol.valueParameters.mapIndexed { index, it -> KtSymbolBasedValueParameterDescriptor(it, context,this, index) } override fun hasStableParameterNames(): Boolean = ktSymbol.hasStableParameterNames override fun hasSynthesizedParameterNames(): Boolean = implementationPostponed() override fun getKind(): CallableMemberDescriptor.Kind = implementationPostponed() override fun <V : Any?> getUserData(key: CallableDescriptor.UserDataKey<V>?): V? = null override fun getOriginal(): FunctionDescriptor = this override fun isHiddenForResolutionEverywhereBesideSupercalls(): Boolean = implementationPostponed() override fun getInitialSignatureDescriptor(): FunctionDescriptor? = noImplementation() override fun isHiddenToOvercomeSignatureClash(): Boolean = noImplementation() override fun setOverriddenDescriptors(overriddenDescriptors: MutableCollection<out CallableMemberDescriptor>) = noImplementation() override fun newCopyBuilder(): FunctionDescriptor.CopyBuilder<out FunctionDescriptor> = noImplementation() override fun copy( newOwner: DeclarationDescriptor?, modality: Modality?, visibility: DescriptorVisibility?, kind: CallableMemberDescriptor.Kind?, copyOverrides: Boolean ): FunctionDescriptor = noImplementation() } class KtSymbolBasedFunctionDescriptor(override val ktSymbol: KtFunctionSymbol, context: FE10BindingContext) : KtSymbolBasedFunctionLikeDescriptor(context), SimpleFunctionDescriptor, KtSymbolBasedNamed { override fun getExtensionReceiverParameter(): ReceiverParameterDescriptor? = getExtensionReceiverParameter(ktSymbol) override fun getDispatchReceiverParameter(): ReceiverParameterDescriptor? = getDispatchReceiverParameter(ktSymbol) override fun getContextReceiverParameters(): List<ReceiverParameterDescriptor> = implementationPlanned() override fun getPackageFqNameIfTopLevel(): FqName = (ktSymbol.callableIdIfNonLocal ?: error("should be top-level")).packageName override fun isSuspend(): Boolean = ktSymbol.isSuspend override fun isOperator(): Boolean = ktSymbol.isOperator override fun isExternal(): Boolean = ktSymbol.isExternal override fun isInline(): Boolean = ktSymbol.isInline override fun isInfix(): Boolean = implementationPostponed() override fun isTailrec(): Boolean = implementationPostponed() override fun isExpect(): Boolean = context.incorrectImplementation { false } override fun isActual(): Boolean = context.incorrectImplementation { false } override fun getVisibility(): DescriptorVisibility = ktSymbol.visibility.toDescriptorVisibility() override fun getModality(): Modality = ktSymbol.modality override fun getTypeParameters(): List<TypeParameterDescriptor> = getTypeParameters(ktSymbol) override fun getOverriddenDescriptors(): Collection<FunctionDescriptor> { val overriddenKtSymbols = context.withAnalysisSession { ktSymbol.getAllOverriddenSymbols() } return overriddenKtSymbols.map { KtSymbolBasedFunctionDescriptor(it as KtFunctionSymbol, context) } } override fun copy( newOwner: DeclarationDescriptor?, modality: Modality?, visibility: DescriptorVisibility?, kind: CallableMemberDescriptor.Kind?, copyOverrides: Boolean ): SimpleFunctionDescriptor = context.noImplementation() override fun getOriginal(): SimpleFunctionDescriptor = context.incorrectImplementation { this } override fun newCopyBuilder(): FunctionDescriptor.CopyBuilder<out SimpleFunctionDescriptor> = context.noImplementation() } class KtSymbolBasedConstructorDescriptor( override val ktSymbol: KtConstructorSymbol, private val ktSBClassDescriptor: KtSymbolBasedClassDescriptor ) : KtSymbolBasedFunctionLikeDescriptor(ktSBClassDescriptor.context), ClassConstructorDescriptor { override fun getName(): Name = Name.special("<init>") override fun getExtensionReceiverParameter(): ReceiverParameterDescriptor? = null override fun getDispatchReceiverParameter(): ReceiverParameterDescriptor? = getDispatchReceiverParameter(ktSymbol) override fun getContextReceiverParameters(): List<ReceiverParameterDescriptor> = ktSBClassDescriptor.contextReceivers override fun getConstructedClass(): ClassDescriptor = ktSBClassDescriptor override fun getContainingDeclaration(): ClassDescriptor = ktSBClassDescriptor override fun getPackageFqNameIfTopLevel(): FqName = error("should not be called") override fun isPrimary(): Boolean = ktSymbol.isPrimary override fun getReturnType(): KotlinType = ktSBClassDescriptor.defaultType override fun isSuspend(): Boolean = false override fun isOperator(): Boolean = false override fun isExternal(): Boolean = false override fun isInline(): Boolean = false override fun isInfix(): Boolean = false override fun isTailrec(): Boolean = false override fun isExpect(): Boolean = implementationPostponed() override fun isActual(): Boolean = implementationPostponed() override fun getVisibility(): DescriptorVisibility = ktSymbol.visibility.toDescriptorVisibility() override fun getModality(): Modality = Modality.FINAL override fun getTypeParameters(): List<TypeParameterDescriptor> = getTypeParameters(ktSymbol) override fun getOriginal(): ClassConstructorDescriptor = this override fun getOverriddenDescriptors(): Collection<FunctionDescriptor> = emptyList() override fun copy( newOwner: DeclarationDescriptor, modality: Modality, visibility: DescriptorVisibility, kind: CallableMemberDescriptor.Kind, copyOverrides: Boolean ): ClassConstructorDescriptor = noImplementation() } class KtSymbolBasedAnonymousFunctionDescriptor( override val ktSymbol: KtAnonymousFunctionSymbol, context: FE10BindingContext ) : KtSymbolBasedFunctionLikeDescriptor(context), SimpleFunctionDescriptor { override fun getName(): Name = SpecialNames.ANONYMOUS override fun getExtensionReceiverParameter(): ReceiverParameterDescriptor? = getExtensionReceiverParameter(ktSymbol) override fun getDispatchReceiverParameter(): ReceiverParameterDescriptor? = null override fun getContextReceiverParameters(): List<ReceiverParameterDescriptor> = implementationPlanned() override fun getPackageFqNameIfTopLevel(): FqName = error("Impossible to be a top-level declaration") override fun isOperator(): Boolean = false override fun isExternal(): Boolean = false override fun isInline(): Boolean = false override fun isInfix(): Boolean = false override fun isTailrec(): Boolean = false override fun isExpect(): Boolean = false override fun isActual(): Boolean = false override fun getVisibility(): DescriptorVisibility = DescriptorVisibilities.LOCAL override fun getModality(): Modality = Modality.FINAL override fun getTypeParameters(): List<TypeParameterDescriptor> = emptyList() // it doesn't seems like isSuspend are used in FIR for anonymous functions, but it used in FIR2IR so if we really need that // we could implement that later override fun isSuspend(): Boolean = implementationPostponed() override fun getOverriddenDescriptors(): Collection<FunctionDescriptor> = emptyList() override fun copy( newOwner: DeclarationDescriptor?, modality: Modality?, visibility: DescriptorVisibility?, kind: CallableMemberDescriptor.Kind?, copyOverrides: Boolean ): SimpleFunctionDescriptor = noImplementation() override fun getOriginal(): SimpleFunctionDescriptor = this override fun newCopyBuilder(): FunctionDescriptor.CopyBuilder<out SimpleFunctionDescriptor> = noImplementation() } private fun KtSymbolBasedDeclarationDescriptor.getDispatchReceiverParameter(ktSymbol: KtCallableSymbol): ReceiverParameterDescriptor? { val ktDispatchTypeAndAnnotations = context.withAnalysisSession { ktSymbol.getDispatchReceiverType() } ?: return null return KtSymbolStubDispatchReceiverParameterDescriptor(ktDispatchTypeAndAnnotations, context) } private fun <T> T.getExtensionReceiverParameter( ktSymbol: KtCallableSymbol, ): ReceiverParameterDescriptor? where T : KtSymbolBasedDeclarationDescriptor, T : CallableDescriptor { val receiverType = ktSymbol.receiverType ?: return null val receiverValue = ExtensionReceiver(this, receiverType.toKotlinType(context), null) return ReceiverParameterDescriptorImpl(this, receiverValue, receiverType.getDescriptorsAnnotations(context)) } private fun KtSymbolBasedDeclarationDescriptor.getTypeParameters(ktSymbol: KtSymbolWithTypeParameters) = ktSymbol.typeParameters.map { KtSymbolBasedTypeParameterDescriptor(it, context) } private class KtSymbolBasedReceiverValue(val ktType: KtType, val context: FE10BindingContext) : ReceiverValue { override fun getType(): KotlinType = ktType.toKotlinType(context) override fun replaceType(newType: KotlinType): ReceiverValue = context.noImplementation("Should be called from IDE") override fun getOriginal(): ReceiverValue = this } // Don't think that annotation is important here, because containingDeclaration used way more then annotation and they are not supported here private class KtSymbolStubDispatchReceiverParameterDescriptor( val receiverType: KtType, val context: FE10BindingContext ) : AbstractReceiverParameterDescriptor(Annotations.EMPTY) { override fun getContainingDeclaration(): DeclarationDescriptor = context.containerDeclarationImplementationPostponed() override fun getValue(): ReceiverValue = KtSymbolBasedReceiverValue(receiverType, context) override fun copy(newOwner: DeclarationDescriptor): ReceiverParameterDescriptor = context.noImplementation("Copy should be called from IDE code") } class KtSymbolBasedValueParameterDescriptor( override val ktSymbol: KtValueParameterSymbol, context: FE10BindingContext, val containingDeclaration: KtSymbolBasedFunctionLikeDescriptor, index: Int = -1, ) : KtSymbolBasedDeclarationDescriptor(context), KtSymbolBasedNamed, ValueParameterDescriptor { override val index: Int init { if (index != -1) { this.index = index } else { val containerSymbol = containingDeclaration.ktSymbol this.index = containerSymbol.valueParameters.indexOfFirst { it === ktSymbol } check(this.index != -1) { "Parameter not found in container symbol = $containerSymbol" } } } override fun getExtensionReceiverParameter(): ReceiverParameterDescriptor? = null override fun getDispatchReceiverParameter(): ReceiverParameterDescriptor? = null override fun getContextReceiverParameters(): List<ReceiverParameterDescriptor> = emptyList() override fun getTypeParameters(): List<TypeParameterDescriptor> = emptyList() override fun getReturnType(): KotlinType = this.getType() override fun getValueParameters(): List<ValueParameterDescriptor> = emptyList() override fun hasStableParameterNames(): Boolean = false override fun hasSynthesizedParameterNames(): Boolean = false override fun <V : Any?> getUserData(key: CallableDescriptor.UserDataKey<V>?): V? = null override fun getVisibility(): DescriptorVisibility = DescriptorVisibilities.LOCAL // for old FE it should return ArrayType in case of vararg override fun getType(): KotlinType { val elementType = ktSymbol.returnType.toKotlinType(context) if (!ktSymbol.isVararg) return elementType // copy from org.jetbrains.kotlin.resolve.DescriptorResolver.getVarargParameterType val primitiveArrayType = context.builtIns.getPrimitiveArrayKotlinTypeByPrimitiveKotlinType(elementType) return primitiveArrayType ?: context.builtIns.getArrayType(Variance.OUT_VARIANCE, elementType) } override fun getContainingDeclaration(): CallableDescriptor = containingDeclaration override fun getPackageFqNameIfTopLevel(): FqName = error("Couldn't be top-level") override fun declaresDefaultValue(): Boolean = ktSymbol.hasDefaultValue override val varargElementType: KotlinType? get() { if (!ktSymbol.isVararg) return null return type } override fun cleanCompileTimeInitializerCache() {} override fun getOriginal(): ValueParameterDescriptor = context.incorrectImplementation { this } override fun copy(newOwner: CallableDescriptor, newName: Name, newIndex: Int): ValueParameterDescriptor = context.noImplementation() override fun getOverriddenDescriptors(): Collection<ValueParameterDescriptor> { return containingDeclaration.overriddenDescriptors.map { it.valueParameters[index] } } override val isCrossinline: Boolean get() = implementationPostponed() override val isNoinline: Boolean get() = implementationPostponed() override fun isVar(): Boolean = false override fun getCompileTimeInitializer(): ConstantValue<*>? = null override fun isConst(): Boolean = false override fun equals(other: Any?): Boolean { if (other === this) return true if (other !is KtSymbolBasedValueParameterDescriptor) return false return index == other.index && containingDeclaration == other.containingDeclaration } override fun hashCode(): Int = containingDeclaration.hashCode() * 37 + index } class KtSymbolBasedPropertyDescriptor( override val ktSymbol: KtPropertySymbol, context: FE10BindingContext ) : KtSymbolBasedDeclarationDescriptor(context), KtSymbolBasedNamed, PropertyDescriptor { override fun getPackageFqNameIfTopLevel(): FqName = (ktSymbol.callableIdIfNonLocal ?: error("should be top-level")).packageName override fun getOriginal(): PropertyDescriptor = context.incorrectImplementation { this } override fun getVisibility(): DescriptorVisibility = ktSymbol.visibility.toDescriptorVisibility() override fun getExtensionReceiverParameter(): ReceiverParameterDescriptor? = getExtensionReceiverParameter(ktSymbol) override fun getDispatchReceiverParameter(): ReceiverParameterDescriptor? = getDispatchReceiverParameter(ktSymbol) override fun getContextReceiverParameters(): List<ReceiverParameterDescriptor> = implementationPlanned() override fun getTypeParameters(): List<TypeParameterDescriptor> = emptyList() override fun getReturnType(): KotlinType = ktSymbol.returnType.toKotlinType(context) override fun getValueParameters(): List<ValueParameterDescriptor> = emptyList() override fun hasStableParameterNames(): Boolean = false override fun hasSynthesizedParameterNames(): Boolean = false override fun getOverriddenDescriptors(): Collection<PropertyDescriptor> = implementationPostponed() override fun <V : Any?> getUserData(key: CallableDescriptor.UserDataKey<V>?): V? = null override fun getType(): KotlinType = ktSymbol.returnType.toKotlinType(context) override fun isVar(): Boolean = !ktSymbol.isVal override fun getCompileTimeInitializer(): ConstantValue<*>? { val constantInitializer = ktSymbol.initializer as? KtConstantInitializerValue ?: return null return constantInitializer.constant.toConstantValue() } override fun cleanCompileTimeInitializerCache() {} override fun isConst(): Boolean = ktSymbol.initializer != null override fun isLateInit(): Boolean = implementationPostponed() override fun getModality(): Modality = implementationPlanned() override fun isExpect(): Boolean = implementationPostponed() override fun isActual(): Boolean = implementationPostponed() override fun isExternal(): Boolean = implementationPlanned() override fun getInType(): KotlinType = implementationPostponed() override fun setOverriddenDescriptors(overriddenDescriptors: MutableCollection<out CallableMemberDescriptor>) = noImplementation() override fun getKind(): CallableMemberDescriptor.Kind = implementationPlanned() override fun copy( newOwner: DeclarationDescriptor?, modality: Modality?, visibility: DescriptorVisibility?, kind: CallableMemberDescriptor.Kind?, copyOverrides: Boolean ): CallableMemberDescriptor = noImplementation() override fun newCopyBuilder(): CallableMemberDescriptor.CopyBuilder<out PropertyDescriptor> = noImplementation() override fun isSetterProjectedOut(): Boolean = implementationPostponed() override fun getAccessors(): List<PropertyAccessorDescriptor> = listOfNotNull(getter, setter) override fun getBackingField(): FieldDescriptor = implementationPostponed() override fun getDelegateField(): FieldDescriptor = implementationPostponed() override val isDelegated: Boolean get() = implementationPostponed() override val getter: PropertyGetterDescriptor? get() = ktSymbol.getter?.let { KtSymbolBasedPropertyGetterDescriptor(it, this) } override val setter: PropertySetterDescriptor? get() = ktSymbol.setter?.let { KtSymbolBasedPropertySetterDescriptor(it, this) } } abstract class KtSymbolBasedVariableAccessorDescriptor( val propertyDescriptor: KtSymbolBasedPropertyDescriptor ) : KtSymbolBasedDeclarationDescriptor(propertyDescriptor.context), VariableAccessorDescriptor { abstract override val ktSymbol: KtPropertyAccessorSymbol override fun getPackageFqNameIfTopLevel(): FqName = error("should be called") override fun getContainingDeclaration(): DeclarationDescriptor = propertyDescriptor override val correspondingVariable: VariableDescriptorWithAccessors get() = propertyDescriptor override fun getExtensionReceiverParameter(): ReceiverParameterDescriptor? = propertyDescriptor.extensionReceiverParameter override fun getDispatchReceiverParameter(): ReceiverParameterDescriptor? = propertyDescriptor.dispatchReceiverParameter override fun getContextReceiverParameters(): List<ReceiverParameterDescriptor> = propertyDescriptor.contextReceiverParameters override fun getTypeParameters(): List<TypeParameterDescriptor> = emptyList() override fun getValueParameters(): List<ValueParameterDescriptor> = emptyList() override fun hasStableParameterNames(): Boolean = false override fun hasSynthesizedParameterNames(): Boolean = false override fun <V : Any?> getUserData(key: CallableDescriptor.UserDataKey<V>?): V? = null override fun setOverriddenDescriptors(overriddenDescriptors: MutableCollection<out CallableMemberDescriptor>) = noImplementation() override fun getKind(): CallableMemberDescriptor.Kind = propertyDescriptor.kind override fun getVisibility(): DescriptorVisibility = propertyDescriptor.visibility override fun getInitialSignatureDescriptor(): FunctionDescriptor? = noImplementation() override fun isHiddenToOvercomeSignatureClash(): Boolean = false override fun isOperator(): Boolean = false override fun isInfix(): Boolean = false override fun isInline(): Boolean = ktSymbol.isInline override fun isTailrec(): Boolean = false override fun isHiddenForResolutionEverywhereBesideSupercalls(): Boolean = implementationPostponed() override fun isSuspend(): Boolean = false override fun newCopyBuilder(): FunctionDescriptor.CopyBuilder<out FunctionDescriptor> = noImplementation() override fun getModality(): Modality = implementationPlanned() override fun isExpect(): Boolean = implementationPostponed() override fun isActual(): Boolean = implementationPostponed() override fun isExternal(): Boolean = implementationPostponed() } class KtSymbolBasedPropertyGetterDescriptor( override val ktSymbol: KtPropertyGetterSymbol, propertyDescriptor: KtSymbolBasedPropertyDescriptor ) : KtSymbolBasedVariableAccessorDescriptor(propertyDescriptor), PropertyGetterDescriptor { override fun getReturnType(): KotlinType = propertyDescriptor.returnType override fun getName(): Name = Name.special("<get-${propertyDescriptor.name}>") override fun isDefault(): Boolean = ktSymbol.isDefault override fun getCorrespondingProperty(): PropertyDescriptor = propertyDescriptor override fun copy( newOwner: DeclarationDescriptor?, modality: Modality?, visibility: DescriptorVisibility?, kind: CallableMemberDescriptor.Kind?, copyOverrides: Boolean ): PropertyAccessorDescriptor = noImplementation() override fun getOriginal(): PropertyGetterDescriptor = context.incorrectImplementation { this } override fun getOverriddenDescriptors(): Collection<PropertyGetterDescriptor> = implementationPostponed() } class KtSymbolBasedPropertySetterDescriptor( override val ktSymbol: KtPropertySetterSymbol, propertyDescriptor: KtSymbolBasedPropertyDescriptor ) : KtSymbolBasedVariableAccessorDescriptor(propertyDescriptor), PropertySetterDescriptor { override fun getReturnType(): KotlinType = propertyDescriptor.returnType override fun getName(): Name = Name.special("<set-${propertyDescriptor.name}>") override fun isDefault(): Boolean = ktSymbol.isDefault override fun getCorrespondingProperty(): PropertyDescriptor = propertyDescriptor override fun copy( newOwner: DeclarationDescriptor?, modality: Modality?, visibility: DescriptorVisibility?, kind: CallableMemberDescriptor.Kind?, copyOverrides: Boolean ): PropertyAccessorDescriptor = noImplementation() override fun getOriginal(): PropertySetterDescriptor = context.incorrectImplementation { this } override fun getOverriddenDescriptors(): Collection<PropertySetterDescriptor> = implementationPostponed() } class KtSymbolBasedPackageFragmentDescriptor( override val fqName: FqName, val context: FE10BindingContext ) : PackageFragmentDescriptor { override fun getName(): Name = fqName.shortName() override fun getOriginal(): DeclarationDescriptorWithSource = this override fun getSource(): SourceElement = SourceElement.NO_SOURCE override val annotations: Annotations get() = Annotations.EMPTY override fun getContainingDeclaration(): ModuleDescriptor = context.moduleDescriptor override fun getMemberScope(): MemberScope = context.noImplementation() override fun <R : Any?, D : Any?> accept(visitor: DeclarationDescriptorVisitor<R, D>?, data: D): R = context.noImplementation("IDE shouldn't use visitor on descriptors") override fun acceptVoid(visitor: DeclarationDescriptorVisitor<Void, Void>?) = context.noImplementation("IDE shouldn't use visitor on descriptors") }
apache-2.0
65b1f098ba521c3d1dc8751cd9024b67
46.937817
141
0.765109
6.226306
false
false
false
false
Maccimo/intellij-community
platform/workspaceModel/storage/src/com/intellij/workspaceModel/storage/impl/VersionedEntityStorageImpl.kt
4
7932
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.workspaceModel.storage.impl import com.github.benmanes.caffeine.cache.Cache import com.github.benmanes.caffeine.cache.Caffeine import com.intellij.workspaceModel.storage.* import java.util.concurrent.atomic.AtomicReference internal class ValuesCache { private val cachedValues: Cache<CachedValue<*>, Any?> = Caffeine.newBuilder().build() private val cachedValuesWithParameter: Cache<Pair<CachedValueWithParameter<*, *>, *>, Any?> = Caffeine.newBuilder().build() fun <R> cachedValue(value: CachedValue<R>, storage: EntityStorage): R { if (storage is MutableEntityStorage) { error("storage must be immutable") } val o = cachedValues.getIfPresent(value) // recursive update - loading get cannot be used if (o != null) { @Suppress("UNCHECKED_CAST") return o as R } else { val newValue = value.source(storage)!! cachedValues.put(value, newValue) return newValue } } fun <P, R> cachedValue(value: CachedValueWithParameter<P, R>, parameter: P, storage: EntityStorage): R { if (storage is MutableEntityStorage) { error("storage must be immutable") } // recursive update - loading get cannot be used val o = cachedValuesWithParameter.getIfPresent(value to parameter) if (o != null) { @Suppress("UNCHECKED_CAST") return o as R } else { val newValue = value.source(storage, parameter)!! cachedValuesWithParameter.put(value to parameter, newValue) return newValue } } fun <R> clearCachedValue(value: CachedValue<R>) { cachedValues.invalidate(value) } fun <P, R> clearCachedValue(value: CachedValueWithParameter<P, R>, parameter: P) { cachedValuesWithParameter.invalidate(value to parameter) } } class VersionedEntityStorageOnBuilder(private val builder: MutableEntityStorage) : VersionedEntityStorage { private val currentSnapshot: AtomicReference<StorageSnapshotCache> = AtomicReference() private val valuesCache: ValuesCache get() = getCurrentSnapshot().cache override val version: Long get() = builder.modificationCount override val current: EntityStorage get() = getCurrentSnapshot().storage override val base: MutableEntityStorage get() = builder override fun <R> cachedValue(value: CachedValue<R>): R = valuesCache.cachedValue(value, current) override fun <P, R> cachedValue(value: CachedValueWithParameter<P, R>, parameter: P): R = valuesCache.cachedValue(value, parameter, current) override fun <R> clearCachedValue(value: CachedValue<R>) = valuesCache.clearCachedValue(value) override fun <P, R> clearCachedValue(value: CachedValueWithParameter<P, R>, parameter: P) = valuesCache.clearCachedValue(value, parameter) private fun getCurrentSnapshot(): StorageSnapshotCache { val snapshotCache = currentSnapshot.get() if (snapshotCache == null || builder.modificationCount != snapshotCache.storageVersion) { val storageSnapshotCache = StorageSnapshotCache(builder.modificationCount, ValuesCache(), builder.toSnapshot()) currentSnapshot.set(storageSnapshotCache) return storageSnapshotCache } return snapshotCache } } class VersionedEntityStorageOnStorage(private val storage: EntityStorage) : VersionedEntityStorage { init { if (storage is MutableEntityStorage) error("storage must be immutable, but got: ${storage.javaClass.name}") } private val valuesCache = ValuesCache() override val version: Long get() = 0 override val current: EntityStorage get() = storage override val base: EntityStorage get() = storage override fun <R> cachedValue(value: CachedValue<R>): R = valuesCache.cachedValue(value, current) override fun <P, R> cachedValue(value: CachedValueWithParameter<P, R>, parameter: P): R = valuesCache.cachedValue(value, parameter, current) override fun <R> clearCachedValue(value: CachedValue<R>) = valuesCache.clearCachedValue(value) override fun <P, R> clearCachedValue(value: CachedValueWithParameter<P, R>, parameter: P) = valuesCache.clearCachedValue(value, parameter) } class DummyVersionedEntityStorage(private val builder: MutableEntityStorage) : VersionedEntityStorage { override val version: Long get() = builder.modificationCount override val current: EntityStorage get() = builder override val base: EntityStorage get() = builder override fun <R> cachedValue(value: CachedValue<R>): R = value.source(current) override fun <P, R> cachedValue(value: CachedValueWithParameter<P, R>, parameter: P): R = value.source(current, parameter) override fun <R> clearCachedValue(value: CachedValue<R>) { } override fun <P, R> clearCachedValue(value: CachedValueWithParameter<P, R>, parameter: P) {} } open class VersionedEntityStorageImpl(initialStorage: EntityStorageSnapshot) : VersionedEntityStorage { private val currentSnapshot: AtomicReference<StorageSnapshotCache> = AtomicReference() private val valuesCache: ValuesCache get() { val snapshotCache = currentSnapshot.get() if (snapshotCache == null || version != snapshotCache.storageVersion) { val cache = ValuesCache() currentSnapshot.set(StorageSnapshotCache(version, cache, current)) return cache } return snapshotCache.cache } override val current: EntityStorage get() = currentPointer.storage override val base: EntityStorage get() = current override val version: Long get() = currentPointer.version val pointer: Current get() = currentPointer override fun <R> cachedValue(value: CachedValue<R>): R = valuesCache.cachedValue(value, current) override fun <P, R> cachedValue(value: CachedValueWithParameter<P, R>, parameter: P): R = valuesCache.cachedValue(value, parameter, current) override fun <R> clearCachedValue(value: CachedValue<R>) = valuesCache.clearCachedValue(value) override fun <P, R> clearCachedValue(value: CachedValueWithParameter<P, R>, parameter: P) = valuesCache.clearCachedValue(value, parameter) class Current(val version: Long, val storage: EntityStorageSnapshot) @Volatile private var currentPointer: Current = Current(0, initialStorage) @Synchronized fun replace(newStorage: EntityStorageSnapshot, changes: Map<Class<*>, List<EntityChange<*>>>, beforeChanged: (VersionedStorageChange) -> Unit, afterChanged: (VersionedStorageChange) -> Unit) { val oldCopy = currentPointer if (oldCopy.storage == newStorage) return val change = VersionedStorageChangeImpl(this, oldCopy.storage, newStorage, changes) beforeChanged(change) currentPointer = Current(version = oldCopy.version + 1, storage = newStorage) afterChanged(change) } @Synchronized fun replaceSilently(newStorage: EntityStorageSnapshot) { val oldCopy = currentPointer if (oldCopy.storage == newStorage) return currentPointer = Current(version = oldCopy.version + 1, storage = newStorage) } } private class VersionedStorageChangeImpl(entityStorage: VersionedEntityStorage, override val storageBefore: EntityStorage, override val storageAfter: EntityStorage, private val changes: Map<Class<*>, List<EntityChange<*>>>) : VersionedStorageChange( entityStorage) { @Suppress("UNCHECKED_CAST") override fun <T : WorkspaceEntity> getChanges(entityClass: Class<T>): List<EntityChange<T>> = (changes[entityClass] as? List<EntityChange<T>>) ?: emptyList() override fun getAllChanges(): Sequence<EntityChange<*>> = changes.values.asSequence().flatten() } private data class StorageSnapshotCache(val storageVersion: Long, val cache: ValuesCache, val storage: EntityStorage)
apache-2.0
3c61e74401ab3afd06c3ea5ce32aabae
37.509709
140
0.726046
4.893276
false
false
false
false
JetBrains/ideavim
src/main/java/com/maddyhome/idea/vim/helper/EditorHelper.kt
1
3729
/* * Copyright 2003-2022 The IdeaVim authors * * Use of this source code is governed by an MIT-style * license that can be found in the LICENSE.txt file or at * https://opensource.org/licenses/MIT. */ @file:JvmName("EditorHelperRt") package com.maddyhome.idea.vim.helper import com.intellij.codeWithMe.ClientId import com.intellij.openapi.editor.Caret import com.intellij.openapi.editor.Editor import com.intellij.openapi.editor.ex.util.EditorUtil import com.intellij.openapi.fileEditor.ex.FileEditorManagerEx import com.intellij.util.ui.table.JBTableRowEditor import com.maddyhome.idea.vim.VimPlugin import com.maddyhome.idea.vim.options.OptionScope import com.maddyhome.idea.vim.vimscript.model.datatypes.VimString import com.maddyhome.idea.vim.vimscript.services.IjVimOptionService import java.awt.Component import javax.swing.JComponent import javax.swing.JTable val Editor.fileSize: Int get() = document.textLength /** * There is a problem with one-line editors. At the moment of the editor creation, this property is always set to false. * So, we should enable IdeaVim for such editors and disable it on the first interaction */ val Editor.isIdeaVimDisabledHere: Boolean get() { val ideaVimSupportValue = (VimPlugin.getOptionService().getOptionValue(OptionScope.GLOBAL, IjVimOptionService.ideavimsupportName) as VimString).value return disabledInDialog || (!ClientId.isCurrentlyUnderLocalId) || // CWM-927 (!ideaVimSupportValue.contains(IjVimOptionService.ideavimsupport_singleline) && isDatabaseCell()) || (!ideaVimSupportValue.contains(IjVimOptionService.ideavimsupport_singleline) && isOneLineMode) } private fun Editor.isDatabaseCell(): Boolean { return isTableCellEditor(this.component) } private val Editor.disabledInDialog: Boolean get() { val ideaVimSupportValue = (VimPlugin.getOptionService().getOptionValue(OptionScope.GLOBAL, IjVimOptionService.ideavimsupportName) as VimString).value return (!ideaVimSupportValue.contains(IjVimOptionService.ideavimsupport_dialog) && !ideaVimSupportValue.contains(IjVimOptionService.ideavimsupport_dialoglegacy)) && (!this.isPrimaryEditor() && !EditorHelper.isFileEditor(this)) } /** * Checks if the editor is a primary editor in the main editing area. */ fun Editor.isPrimaryEditor(): Boolean { val project = project ?: return false val fileEditorManager = FileEditorManagerEx.getInstanceEx(project) ?: return false return fileEditorManager.allEditors.any { fileEditor -> this == EditorUtil.getEditorEx(fileEditor) } } // Optimized clone of com.intellij.ide.ui.laf.darcula.DarculaUIUtil.isTableCellEditor private fun isTableCellEditor(c: Component): Boolean { return (java.lang.Boolean.TRUE == (c as JComponent).getClientProperty("JComboBox.isTableCellEditor")) || (findParentByCondition(c) { it is JTable } != null) && (findParentByCondition(c) { it is JBTableRowEditor } == null) } private const val PARENT_BY_CONDITION_DEPTH = 10 private inline fun findParentByCondition(c: Component?, condition: (Component?) -> Boolean): Component? { var eachParent = c var goDeep = PARENT_BY_CONDITION_DEPTH while (eachParent != null && --goDeep > 0) { if (condition(eachParent)) return eachParent eachParent = eachParent.parent } return null } fun Editor.endsWithNewLine(): Boolean { val textLength = this.document.textLength if (textLength == 0) return false return this.document.charsSequence[textLength - 1] == '\n' } /** * Get caret line in vim notation (1-based) */ val Caret.vimLine: Int get() = this.logicalPosition.line + 1 /** * Get current caret line in vim notation (1-based) */ val Editor.vimLine: Int get() = this.caretModel.currentCaret.vimLine
mit
47558516e6489521dabd20360fb76634
37.05102
168
0.766962
4.199324
false
false
false
false
Turbo87/intellij-rust
src/main/kotlin/org/toml/lang/core/parser/TomlParserDefinition.kt
1
1772
package org.toml.lang.core.parser import com.intellij.lang.ASTNode import com.intellij.lang.ParserDefinition import com.intellij.lang.PsiParser import com.intellij.lexer.Lexer import com.intellij.openapi.project.Project import com.intellij.psi.FileViewProvider import com.intellij.psi.PsiElement import com.intellij.psi.PsiFile import com.intellij.psi.TokenType import com.intellij.psi.tree.IFileElementType import com.intellij.psi.tree.TokenSet import org.toml.lang.TomlLanguage import org.toml.lang.core.lexer.TomlLexer import org.toml.lang.core.psi.TomlFile import org.toml.lang.core.psi.TomlTypes public class TomlParserDefinition : ParserDefinition { override fun createParser(project: Project?): PsiParser = TomlParser() override fun createFile(viewProvider: FileViewProvider): PsiFile = TomlFile(viewProvider) override fun spaceExistanceTypeBetweenTokens(left: ASTNode?, right: ASTNode?): ParserDefinition.SpaceRequirements? { return ParserDefinition.SpaceRequirements.MAY } override fun getStringLiteralElements(): TokenSet = TokenSet.EMPTY; override fun getWhitespaceTokens(): TokenSet = WHITE_SPACES override fun getCommentTokens(): TokenSet = COMMENTS override fun getFileNodeType(): IFileElementType? = FILE override fun createLexer(project: Project?): Lexer = TomlLexer() override fun createElement(node: ASTNode?): PsiElement = TomlTypes.Factory.createElement(node) companion object { val FILE: IFileElementType = IFileElementType(TomlLanguage) val WHITE_SPACES: TokenSet = TokenSet.create(TokenType.WHITE_SPACE); val COMMENTS: TokenSet = TokenSet.create(TomlTypes.COMMENT); } }
mit
4f369f6ac200cbba41896eff304ed2d2
30.087719
120
0.74605
4.77628
false
false
false
false
trustin/armeria
examples/annotated-http-service-kotlin/src/main/kotlin/example/armeria/server/annotated/kotlin/DecoratingService.kt
4
2027
package example.armeria.server.annotated.kotlin import com.linecorp.armeria.common.HttpResponse import com.linecorp.armeria.server.HttpService import com.linecorp.armeria.server.annotation.Blocking import com.linecorp.armeria.server.annotation.DecoratorFactory import com.linecorp.armeria.server.annotation.DecoratorFactoryFunction import com.linecorp.armeria.server.annotation.Get import com.linecorp.armeria.server.kotlin.CoroutineContextService import kotlinx.coroutines.CoroutineName import org.slf4j.LoggerFactory import java.util.function.Function import kotlin.coroutines.coroutineContext @CoroutineNameDecorator(name = "default") class DecoratingService { @Get("/foo") suspend fun foo(): HttpResponse { log.info("My name is ${coroutineContext[CoroutineName]?.name}") return HttpResponse.of("OK") } @CoroutineNameDecorator(name = "bar") @Get("/bar") suspend fun bar(): HttpResponse { log.info("My name is ${coroutineContext[CoroutineName]?.name}") return HttpResponse.of("OK") } @Blocking @CoroutineNameDecorator(name = "blocking") @Get("/blocking") suspend fun blocking(): HttpResponse { log.info("My name is ${coroutineContext[CoroutineName]?.name}") assert(Thread.currentThread().name.contains("armeria-common-blocking-tasks")) return HttpResponse.of("OK") } companion object { private val log = LoggerFactory.getLogger(DecoratingService::class.java) } } @DecoratorFactory(CoroutineNameDecoratorFactory::class) @Target(AnnotationTarget.CLASS, AnnotationTarget.FUNCTION) @Retention(AnnotationRetention.RUNTIME) annotation class CoroutineNameDecorator(val name: String) class CoroutineNameDecoratorFactory : DecoratorFactoryFunction<CoroutineNameDecorator> { override fun newDecorator(parameter: CoroutineNameDecorator): Function<in HttpService, out HttpService> { return CoroutineContextService.newDecorator { CoroutineName(name = parameter.name) } } }
apache-2.0
0d00b9b48306d1600bfeb8682859f862
34.561404
109
0.75481
4.724942
false
false
false
false
mdaniel/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/AddFullQualifierIntention.kt
1
7473
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.intentions import com.intellij.codeInsight.intention.LowPriorityAction import com.intellij.openapi.editor.Editor import com.intellij.psi.PsiElement import com.intellij.psi.util.createSmartPointer import com.intellij.psi.util.descendantsOfType import com.intellij.psi.util.elementType import com.intellij.psi.util.prevLeaf import org.jetbrains.kotlin.descriptors.CallableMemberDescriptor import org.jetbrains.kotlin.descriptors.ConstructorDescriptor import org.jetbrains.kotlin.descriptors.DeclarationDescriptor import org.jetbrains.kotlin.descriptors.PackageFragmentDescriptor import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.core.quoteSegmentsIfNeeded import org.jetbrains.kotlin.idea.base.psi.replaced import org.jetbrains.kotlin.idea.codeinsight.api.classic.intentions.SelfTargetingIntention import org.jetbrains.kotlin.idea.imports.importableFqName import org.jetbrains.kotlin.idea.references.resolveMainReferenceToDescriptors import org.jetbrains.kotlin.idea.util.application.executeWriteCommand import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.name.FqName import org.jetbrains.kotlin.name.parentOrNull import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.getPrevSiblingIgnoringWhitespaceAndComments import org.jetbrains.kotlin.resolve.descriptorUtil.isExtension import org.jetbrains.kotlin.utils.addToStdlib.safeAs class AddFullQualifierIntention : SelfTargetingIntention<KtNameReferenceExpression>( KtNameReferenceExpression::class.java, KotlinBundle.lazyMessage("add.full.qualifier") ), LowPriorityAction { override fun isApplicableTo(element: KtNameReferenceExpression, caretOffset: Int): Boolean = isApplicableTo( referenceExpression = element, contextDescriptor = null, ) override fun applyTo(element: KtNameReferenceExpression, editor: Editor?) { val fqName = element.findSingleDescriptor()?.importableFqName ?: return applyTo(element, fqName) } override fun startInWriteAction(): Boolean = false companion object { fun isApplicableTo(referenceExpression: KtNameReferenceExpression, contextDescriptor: DeclarationDescriptor?): Boolean { if (referenceExpression.parent is KtInstanceExpressionWithLabel) return false val prevElement = referenceExpression.prevElementWithoutSpacesAndComments() if (prevElement.elementType == KtTokens.DOT) return false val resultDescriptor = contextDescriptor ?: referenceExpression.findSingleDescriptor() ?: return false if (resultDescriptor.isExtension || resultDescriptor.isInRoot) return false if (prevElement.elementType == KtTokens.COLONCOLON) { if (resultDescriptor.isTopLevelCallable) return false val prevSibling = prevElement?.getPrevSiblingIgnoringWhitespaceAndComments() if (prevSibling is KtNameReferenceExpression || prevSibling is KtDotQualifiedExpression) return false } val file = referenceExpression.containingKtFile val identifier = referenceExpression.getIdentifier()?.text val fqName = resultDescriptor.importableFqName if (file.importDirectives.any { it.aliasName == identifier && it.importedFqName == fqName }) return false return true } fun applyTo(referenceExpression: KtNameReferenceExpression, fqName: FqName): KtElement { val qualifier = fqName.parent().quoteSegmentsIfNeeded() return referenceExpression.project.executeWriteCommand(KotlinBundle.message("add.full.qualifier"), groupId = null) { val psiFactory = KtPsiFactory(referenceExpression) when (val parent = referenceExpression.parent) { is KtCallableReferenceExpression -> addOrReplaceQualifier(psiFactory, parent, qualifier) is KtCallExpression -> replaceExpressionWithDotQualifier(psiFactory, parent, qualifier) is KtUserType -> addQualifierToType(psiFactory, parent, qualifier) else -> replaceExpressionWithQualifier(psiFactory, referenceExpression, fqName) } } } fun addQualifiersRecursively(root: KtElement): KtElement { if (root is KtNameReferenceExpression) return applyIfApplicable(root) ?: root root.descendantsOfType<KtNameReferenceExpression>() .map { it.createSmartPointer() } .toList() .asReversed() .forEach { it.element?.let(::applyIfApplicable) } return root } private fun applyIfApplicable(referenceExpression: KtNameReferenceExpression): KtElement? { val descriptor = referenceExpression.findSingleDescriptor() ?: return null val fqName = descriptor.importableFqName ?: return null if (!isApplicableTo(referenceExpression, descriptor)) return null return applyTo(referenceExpression, fqName) } } } private fun addOrReplaceQualifier(factory: KtPsiFactory, expression: KtCallableReferenceExpression, qualifier: String): KtElement { val receiver = expression.receiverExpression return if (receiver != null) { replaceExpressionWithDotQualifier(factory, receiver, qualifier) } else { val qualifierExpression = factory.createExpression(qualifier) expression.addBefore(qualifierExpression, expression.firstChild) as KtElement } } private fun replaceExpressionWithDotQualifier(psiFactory: KtPsiFactory, expression: KtExpression, qualifier: String): KtElement { val expressionWithQualifier = psiFactory.createExpressionByPattern("$0.$1", qualifier, expression) return expression.replaced(expressionWithQualifier) } private fun addQualifierToType(psiFactory: KtPsiFactory, userType: KtUserType, qualifier: String): KtElement { val type = userType.parent.safeAs<KtNullableType>() ?: userType val typeWithQualifier = psiFactory.createType("$qualifier.${type.text}") return type.parent.replaced(typeWithQualifier) } private fun replaceExpressionWithQualifier( psiFactory: KtPsiFactory, referenceExpression: KtNameReferenceExpression, fqName: FqName ): KtElement { val expressionWithQualifier = psiFactory.createExpression(fqName.asString()) return referenceExpression.replaced(expressionWithQualifier) } private val DeclarationDescriptor.isInRoot: Boolean get() { val fqName = importableFqName ?: return true return fqName.isRoot || fqName.parentOrNull()?.isRoot == true } private val DeclarationDescriptor.isTopLevelCallable: Boolean get() = safeAs<CallableMemberDescriptor>()?.containingDeclaration is PackageFragmentDescriptor || safeAs<ConstructorDescriptor>()?.containingDeclaration?.containingDeclaration is PackageFragmentDescriptor private fun KtNameReferenceExpression.prevElementWithoutSpacesAndComments(): PsiElement? = prevLeaf { it.elementType !in KtTokens.WHITE_SPACE_OR_COMMENT_BIT_SET } private fun KtNameReferenceExpression.findSingleDescriptor(): DeclarationDescriptor? = resolveMainReferenceToDescriptors().singleOrNull()
apache-2.0
11777840820c5a678ad36b2da5630e9c
49.154362
158
0.750033
5.973621
false
false
false
false
ingokegel/intellij-community
platform/workspaceModel/storage/testEntities/gen/com/intellij/workspaceModel/storage/entities/test/api/ChildFirstEntityImpl.kt
1
10354
package com.intellij.workspaceModel.storage.entities.test.api import com.intellij.workspaceModel.storage.EntityInformation import com.intellij.workspaceModel.storage.EntitySource import com.intellij.workspaceModel.storage.EntityStorage import com.intellij.workspaceModel.storage.GeneratedCodeApiVersion import com.intellij.workspaceModel.storage.GeneratedCodeImplVersion import com.intellij.workspaceModel.storage.ModifiableWorkspaceEntity import com.intellij.workspaceModel.storage.MutableEntityStorage import com.intellij.workspaceModel.storage.WorkspaceEntity import com.intellij.workspaceModel.storage.impl.ConnectionId import com.intellij.workspaceModel.storage.impl.EntityLink import com.intellij.workspaceModel.storage.impl.ModifiableWorkspaceEntityBase import com.intellij.workspaceModel.storage.impl.UsedClassesCollector import com.intellij.workspaceModel.storage.impl.WorkspaceEntityBase import com.intellij.workspaceModel.storage.impl.WorkspaceEntityData import com.intellij.workspaceModel.storage.impl.extractOneToAbstractManyParent import com.intellij.workspaceModel.storage.impl.updateOneToAbstractManyParentOfChild import org.jetbrains.deft.ObjBuilder import org.jetbrains.deft.Type import org.jetbrains.deft.annotations.Abstract import org.jetbrains.deft.annotations.Child @GeneratedCodeApiVersion(1) @GeneratedCodeImplVersion(1) open class ChildFirstEntityImpl : ChildFirstEntity, WorkspaceEntityBase() { companion object { internal val PARENTENTITY_CONNECTION_ID: ConnectionId = ConnectionId.create(ParentAbEntity::class.java, ChildAbstractBaseEntity::class.java, ConnectionId.ConnectionType.ONE_TO_ABSTRACT_MANY, false) val connections = listOf<ConnectionId>( PARENTENTITY_CONNECTION_ID, ) } @JvmField var _commonData: String? = null override val commonData: String get() = _commonData!! override val parentEntity: ParentAbEntity get() = snapshot.extractOneToAbstractManyParent(PARENTENTITY_CONNECTION_ID, this)!! @JvmField var _firstData: String? = null override val firstData: String get() = _firstData!! override fun connectionIdList(): List<ConnectionId> { return connections } class Builder(val result: ChildFirstEntityData?) : ModifiableWorkspaceEntityBase<ChildFirstEntity>(), ChildFirstEntity.Builder { constructor() : this(ChildFirstEntityData()) override fun applyToBuilder(builder: MutableEntityStorage) { if (this.diff != null) { if (existsInBuilder(builder)) { this.diff = builder return } else { error("Entity ChildFirstEntity is already created in a different builder") } } this.diff = builder this.snapshot = builder addToBuilder() this.id = getEntityData().createEntityId() // Process linked entities that are connected without a builder processLinkedEntities(builder) checkInitialization() // TODO uncomment and check failed tests } fun checkInitialization() { val _diff = diff if (!getEntityData().isEntitySourceInitialized()) { error("Field WorkspaceEntity#entitySource should be initialized") } if (!getEntityData().isCommonDataInitialized()) { error("Field ChildAbstractBaseEntity#commonData should be initialized") } if (_diff != null) { if (_diff.extractOneToAbstractManyParent<WorkspaceEntityBase>(PARENTENTITY_CONNECTION_ID, this) == null) { error("Field ChildAbstractBaseEntity#parentEntity should be initialized") } } else { if (this.entityLinks[EntityLink(false, PARENTENTITY_CONNECTION_ID)] == null) { error("Field ChildAbstractBaseEntity#parentEntity should be initialized") } } if (!getEntityData().isFirstDataInitialized()) { error("Field ChildFirstEntity#firstData should be initialized") } } override fun connectionIdList(): List<ConnectionId> { return connections } // Relabeling code, move information from dataSource to this builder override fun relabel(dataSource: WorkspaceEntity, parents: Set<WorkspaceEntity>?) { dataSource as ChildFirstEntity this.entitySource = dataSource.entitySource this.commonData = dataSource.commonData this.firstData = dataSource.firstData if (parents != null) { this.parentEntity = parents.filterIsInstance<ParentAbEntity>().single() } } override var entitySource: EntitySource get() = getEntityData().entitySource set(value) { checkModificationAllowed() getEntityData().entitySource = value changedProperty.add("entitySource") } override var commonData: String get() = getEntityData().commonData set(value) { checkModificationAllowed() getEntityData().commonData = value changedProperty.add("commonData") } override var parentEntity: ParentAbEntity get() { val _diff = diff return if (_diff != null) { _diff.extractOneToAbstractManyParent(PARENTENTITY_CONNECTION_ID, this) ?: this.entityLinks[EntityLink(false, PARENTENTITY_CONNECTION_ID)]!! as ParentAbEntity } else { this.entityLinks[EntityLink(false, PARENTENTITY_CONNECTION_ID)]!! as ParentAbEntity } } set(value) { checkModificationAllowed() val _diff = diff if (_diff != null && value is ModifiableWorkspaceEntityBase<*> && value.diff == null) { // Setting backref of the list if (value is ModifiableWorkspaceEntityBase<*>) { val data = (value.entityLinks[EntityLink(true, PARENTENTITY_CONNECTION_ID)] as? List<Any> ?: emptyList()) + this value.entityLinks[EntityLink(true, PARENTENTITY_CONNECTION_ID)] = data } // else you're attaching a new entity to an existing entity that is not modifiable _diff.addEntity(value) } if (_diff != null && (value !is ModifiableWorkspaceEntityBase<*> || value.diff != null)) { _diff.updateOneToAbstractManyParentOfChild(PARENTENTITY_CONNECTION_ID, this, value) } else { // Setting backref of the list if (value is ModifiableWorkspaceEntityBase<*>) { val data = (value.entityLinks[EntityLink(true, PARENTENTITY_CONNECTION_ID)] as? List<Any> ?: emptyList()) + this value.entityLinks[EntityLink(true, PARENTENTITY_CONNECTION_ID)] = data } // else you're attaching a new entity to an existing entity that is not modifiable this.entityLinks[EntityLink(false, PARENTENTITY_CONNECTION_ID)] = value } changedProperty.add("parentEntity") } override var firstData: String get() = getEntityData().firstData set(value) { checkModificationAllowed() getEntityData().firstData = value changedProperty.add("firstData") } override fun getEntityData(): ChildFirstEntityData = result ?: super.getEntityData() as ChildFirstEntityData override fun getEntityClass(): Class<ChildFirstEntity> = ChildFirstEntity::class.java } } class ChildFirstEntityData : WorkspaceEntityData<ChildFirstEntity>() { lateinit var commonData: String lateinit var firstData: String fun isCommonDataInitialized(): Boolean = ::commonData.isInitialized fun isFirstDataInitialized(): Boolean = ::firstData.isInitialized override fun wrapAsModifiable(diff: MutableEntityStorage): ModifiableWorkspaceEntity<ChildFirstEntity> { val modifiable = ChildFirstEntityImpl.Builder(null) modifiable.allowModifications { modifiable.diff = diff modifiable.snapshot = diff modifiable.id = createEntityId() modifiable.entitySource = this.entitySource } modifiable.changedProperty.clear() return modifiable } override fun createEntity(snapshot: EntityStorage): ChildFirstEntity { val entity = ChildFirstEntityImpl() entity._commonData = commonData entity._firstData = firstData entity.entitySource = entitySource entity.snapshot = snapshot entity.id = createEntityId() return entity } override fun getEntityInterface(): Class<out WorkspaceEntity> { return ChildFirstEntity::class.java } override fun serialize(ser: EntityInformation.Serializer) { } override fun deserialize(de: EntityInformation.Deserializer) { } override fun createDetachedEntity(parents: List<WorkspaceEntity>): WorkspaceEntity { return ChildFirstEntity(commonData, firstData, entitySource) { this.parentEntity = parents.filterIsInstance<ParentAbEntity>().single() } } override fun getRequiredParents(): List<Class<out WorkspaceEntity>> { val res = mutableListOf<Class<out WorkspaceEntity>>() res.add(ParentAbEntity::class.java) return res } override fun equals(other: Any?): Boolean { if (other == null) return false if (this::class != other::class) return false other as ChildFirstEntityData if (this.entitySource != other.entitySource) return false if (this.commonData != other.commonData) return false if (this.firstData != other.firstData) return false return true } override fun equalsIgnoringEntitySource(other: Any?): Boolean { if (other == null) return false if (this::class != other::class) return false other as ChildFirstEntityData if (this.commonData != other.commonData) return false if (this.firstData != other.firstData) return false return true } override fun hashCode(): Int { var result = entitySource.hashCode() result = 31 * result + commonData.hashCode() result = 31 * result + firstData.hashCode() return result } override fun hashCodeIgnoringEntitySource(): Int { var result = javaClass.hashCode() result = 31 * result + commonData.hashCode() result = 31 * result + firstData.hashCode() return result } override fun collectClassUsagesData(collector: UsedClassesCollector) { collector.sameForAllEntities = true } }
apache-2.0
5c9b3339c7d3ed3510835e6fde73a048
36.111111
160
0.694611
5.513312
false
false
false
false
failex234/FastHub
app/src/main/java/com/fastaccess/ui/modules/main/donation/DonateActivity.kt
1
5583
package com.fastaccess.ui.modules.main.donation import android.app.Activity import android.content.Context import android.content.Intent import android.os.Bundle import android.support.v4.app.Fragment import com.fastaccess.BuildConfig import com.fastaccess.R import com.fastaccess.helper.* import com.fastaccess.provider.fabric.FabricProvider import com.fastaccess.ui.base.BaseActivity import com.fastaccess.ui.base.mvp.BaseMvp import com.fastaccess.ui.base.mvp.presenter.BasePresenter import com.miguelbcr.io.rx_billing_service.RxBillingService import com.miguelbcr.io.rx_billing_service.RxBillingServiceError import com.miguelbcr.io.rx_billing_service.RxBillingServiceException import com.miguelbcr.io.rx_billing_service.entities.ProductType import com.miguelbcr.io.rx_billing_service.entities.Purchase import io.reactivex.disposables.Disposable /** * Created by Kosh on 10 Jun 2017, 1:04 PM */ class DonateActivity : BaseActivity<BaseMvp.FAView, BasePresenter<BaseMvp.FAView>>() { private var subscription: Disposable? = null override fun layout(): Int = 0 override fun isTransparent(): Boolean = true override fun canBack(): Boolean = false override fun isSecured(): Boolean = true override fun providePresenter(): BasePresenter<BaseMvp.FAView> = BasePresenter() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val bundle: Bundle = intent.extras val productKey = bundle.getString(BundleConstant.EXTRA) val price = bundle.getLong(BundleConstant.EXTRA_FOUR, 0) val priceText = bundle.getString(BundleConstant.EXTRA_FIVE) subscription = RxHelper.getSingle<Purchase>(RxBillingService.getInstance(this, BuildConfig.DEBUG) .purchase(ProductType.IN_APP, productKey, "inapp:com.fastaccess.github:" + productKey)) .subscribe({ p: Purchase?, throwable: Throwable? -> if (throwable == null) { FabricProvider.logPurchase(productKey, price, priceText) showMessage(R.string.success, R.string.success_purchase_message) enableProduct(productKey, applicationContext) val intent = Intent() intent.putExtra(BundleConstant.ITEM, productKey) setResult(Activity.RESULT_OK, intent) } else { if (throwable is RxBillingServiceException) { val code = throwable.code if (code == RxBillingServiceError.ITEM_ALREADY_OWNED) { enableProduct(productKey, applicationContext) val intent = Intent() intent.putExtra(BundleConstant.ITEM, productKey) setResult(Activity.RESULT_OK, intent) } else { showErrorMessage(throwable.message!!) Logger.e(code) setResult(Activity.RESULT_CANCELED) } } throwable.printStackTrace() } finish() }) } override fun onDestroy() { subscription?.let { if (!it.isDisposed) it.dispose() } super.onDestroy() } companion object { fun start(context: Activity, product: String?, price: Long? = 0, priceText: String? = null) { val intent = Intent(context, DonateActivity::class.java) intent.putExtras(Bundler.start() .put(BundleConstant.EXTRA, product) .put(BundleConstant.EXTRA_FOUR, price) .put(BundleConstant.EXTRA_FIVE, priceText) .end()) context.startActivityForResult(intent, BundleConstant.REQUEST_CODE) } fun start(context: Fragment, product: String?, price: Long? = 0, priceText: String? = null) { val intent = Intent(context.context, DonateActivity::class.java) intent.putExtras(Bundler.start() .put(BundleConstant.EXTRA, product) .put(BundleConstant.EXTRA_FOUR, price) .put(BundleConstant.EXTRA_FIVE, priceText) .end()) context.startActivityForResult(intent, BundleConstant.REQUEST_CODE) } fun enableProduct(productKey: String, context: Context) { when (productKey) { context.getString(R.string.donation_product_1), context.getString(R.string.amlod_theme_purchase) -> PrefGetter.enableAmlodTheme() context.getString(R.string.midnight_blue_theme_purchase) -> PrefGetter.enableMidNightBlueTheme() context.getString(R.string.theme_bluish_purchase) -> PrefGetter.enableBluishTheme() context.getString(R.string.donation_product_2), context.getString(R.string.fasthub_pro_purchase) -> PrefGetter.setProItems() context.getString(R.string.fasthub_enterprise_purchase) -> PrefGetter.setEnterpriseItem() context.getString(R.string.donation_product_3), context.getString(R.string.donation_product_4), context.getString(R.string.fasthub_all_features_purchase) -> { PrefGetter.setProItems() PrefGetter.setEnterpriseItem() } else -> Logger.e(productKey) } } } }
gpl-3.0
389730fbe093957c43f683c8b8fe92f5
46.322034
145
0.616335
5.025203
false
false
false
false
Major-/Vicis
scene3d/src/main/kotlin/rs/emulate/scene3d/Geometry.kt
1
3069
package rs.emulate.scene3d import org.joml.Vector2f import org.joml.Vector3f import org.joml.Vector3i import rs.emulate.scene3d.material.VertexAttribute import kotlin.properties.ReadWriteProperty import kotlin.reflect.KProperty /** * Specification for a [Node] that has vertex data associated with it. */ abstract class Geometry : Node() { /** * The type of geometry the vertex data is rendered as. */ abstract var geometryType: GeometryType /** * Geometry is dirty when it's initialized so the renderer knows to configure its state first. */ override var dirty: Boolean = true /** * The collection of vertex attribute data that makes up this geometry. */ var data: GeometryData = GeometryData() /** * The vertex positions of this [Geometry]. */ var positions: List<Vector3f> by attribute(VertexAttribute.Position) /** * The vertex normals of this [Geometry]. */ var normals: List<Vector3f> by attribute(VertexAttribute.Normal) /** * The vertex colors of this [Geometry]. */ var colors: List<Vector3f> by attribute(VertexAttribute.Color) /** * The texture coordinates of this [Geometry]. */ var texCoords: List<Vector2f> by attribute(VertexAttribute.TexCoord) /** * Optional list of vertex indices for drawing indexed geometry. May be empty. */ var indices: List<Vector3i> by attribute(VertexAttribute.Index) /** * Get a list of the data for the given vertex [attribute]. */ fun <C : List<V>, V : Any> get(attribute: VertexAttribute<V>): C = data.buffer(attribute).data as C /** * Serialize the collection of vertex [items] for the vertex [attribute] to the respective backing buffer. */ fun <T : Any> setAll(attribute: VertexAttribute<T>, items: Collection<T>) { data.buffer(attribute).setAll(items) dirty = true } /** * Serialize the single [datum] for the vertex [attribute] to the respective backing buffer. */ fun <T : Any> set(attribute: VertexAttribute<T>, datum: T) { data.buffer(attribute).set(datum) dirty = true } /** * Attribute delegate factory that provides accessors for lists of object values over [GeometryBuffer]s. * * @param C The type of the vertex attribute data container. * @param V The type of the vertex attribute data values. */ protected fun <C : List<V>, V : Any> attribute(attribute: VertexAttribute<V>): ReadWriteProperty<Geometry, C> { return AttributeDelegate(attribute) } /** * A property delegate for [VertexAttribute]s that are backed by a list of elements. */ protected class AttributeDelegate<T : Any, L : List<T>>(val attribute: VertexAttribute<T>) : ReadWriteProperty<Geometry, L> { override fun getValue(thisRef: Geometry, property: KProperty<*>): L = thisRef.get(attribute) override fun setValue(thisRef: Geometry, property: KProperty<*>, value: L) = thisRef.setAll(attribute, value) } }
isc
e878bcdf88fb1799b4a282b86192710e
31.648936
129
0.667644
4.334746
false
false
false
false
JavaEden/Orchid-Core
OrchidCore/src/main/kotlin/com/eden/orchid/impl/publication/ScriptPublisher.kt
2
1818
package com.eden.orchid.impl.publication import com.caseyjbrooks.clog.Clog import com.eden.common.util.EdenUtils import com.eden.common.util.IOStreamUtils import com.eden.orchid.api.OrchidContext import com.eden.orchid.api.options.annotations.Description import com.eden.orchid.api.options.annotations.Option import com.eden.orchid.api.publication.OrchidPublisher import java.io.File import java.util.concurrent.Executors import java.util.concurrent.TimeUnit import javax.inject.Inject import javax.inject.Named import javax.validation.constraints.NotEmpty @Description(value = "Run arbitrary shell scripts.", name = "Script") class ScriptPublisher : OrchidPublisher("script") { @Option @Description("The executable name") @NotEmpty(message = "Must set the command to run.") lateinit var command: List<String> @Option @Description("The working directory of the script to run") lateinit var cwd: String override fun publish(context: OrchidContext) { val builder = ProcessBuilder() builder.command(*command.toTypedArray()) var directory: String if (!EdenUtils.isEmpty(cwd)) { directory = cwd if (directory.startsWith("~")) { directory = System.getProperty("user.home") + directory.substring(1) } } else { directory = context.sourceDir } builder.directory(File(directory)) Clog.i("[{}]> {}", directory, command.joinToString(" ")) val process = builder.start() val future = Executors.newSingleThreadExecutor().submit(IOStreamUtils.InputStreamPrinter(process.inputStream, "Script Publisher")) // pause for the process to finish and input to finish printing process.waitFor() future.get(3, TimeUnit.SECONDS) } }
mit
540c242eec23eed21b32866fb89e28d5
34.647059
138
0.70022
4.46683
false
false
false
false
AberrantFox/hotbot
src/main/kotlin/me/aberrantfox/hotbot/services/PoolToChannelService.kt
1
2944
package me.aberrantfox.hotbot.services import com.fatboyindustrial.gsonjodatime.Converters import com.google.common.reflect.TypeToken import com.google.gson.GsonBuilder import me.aberrantfox.hotbot.extensions.stdlib.retrieveIdToName import net.dv8tion.jda.core.EmbedBuilder import net.dv8tion.jda.core.JDA import net.dv8tion.jda.core.entities.MessageEmbed import org.joda.time.DateTime import org.joda.time.format.DateTimeFormat import java.io.File import java.time.LocalDateTime import java.util.* data class PoolRecord(val sender: String, val dateTime: DateTime, val message: String, val avatarURL: String) { fun describe(jda: JDA, datumName: String): MessageEmbed = EmbedBuilder() .setTitle("$datumName by ${sender.retrieveIdToName(jda)}") .setDescription(message) .addField("Time of Creation", formatConstructionDate(), false) .addField("Member ID", sender, false) .build() fun prettyPrint(jda: JDA, datumName: String): EmbedBuilder = EmbedBuilder() .setTitle("${sender.retrieveIdToName(jda)}'s $datumName") .addField("Time of Creation", formatConstructionDate(), false) .addField("Content", message, false) .setThumbnail(avatarURL) .setTimestamp(LocalDateTime.now()) private fun formatConstructionDate() = dateTime.toString(DateTimeFormat.forPattern("dd/MM/yyyy")) } enum class AddResponse { Accepted, UserFull, PoolFull } class UserElementPool(val userLimit: Int = 3, val poolLimit: Int = 20, val poolName: String) { private val saveLocation = File(configPath("pools/$poolName.json")) private val pool: Queue<PoolRecord> = LinkedList<PoolRecord>() private val gson = Converters.registerDateTime(GsonBuilder()).create() init { if(saveLocation.exists()) { val type = object : TypeToken<LinkedList<PoolRecord>>(){}.type val records = gson.fromJson<LinkedList<PoolRecord>>(saveLocation.readText(), type) records.forEach { pool.add(it) } } else { File(saveLocation.parent).mkdirs() saveLocation.createNewFile() } } fun addRecord(sender: String, avatarURL: String, message: String): AddResponse { if(totalInPool(sender) == userLimit) return AddResponse.UserFull if(pool.size == poolLimit) return AddResponse.PoolFull pool.add(PoolRecord(sender, DateTime.now(), message, avatarURL)) save() return AddResponse.Accepted } fun top(): PoolRecord? { val record = pool.poll() save() return record } fun entries() = pool.size fun isEmpty() = pool.isEmpty() fun peek(): PoolRecord? = pool.peek() private fun save() { val json = gson.toJson(pool) saveLocation.writeText(json) } private fun totalInPool(userID: String) = pool.count { it.sender == userID } }
mit
6b1a6fd69ee2407945cda7f9a866d24a
32.454545
111
0.672894
4.29781
false
false
false
false
iPoli/iPoli-android
app/src/main/java/io/ipoli/android/quest/CompletedQuestViewController.kt
1
9568
package io.ipoli.android.quest import android.content.res.ColorStateList import android.graphics.Color import android.graphics.drawable.GradientDrawable import android.os.Bundle import android.support.annotation.ColorInt import android.view.LayoutInflater import android.view.MenuItem import android.view.View import android.view.ViewGroup import com.mikepenz.iconics.IconicsDrawable import io.ipoli.android.R import io.ipoli.android.common.datetime.Duration import io.ipoli.android.common.datetime.Minute import io.ipoli.android.common.redux.android.ReduxViewController import io.ipoli.android.common.text.DateFormatter import io.ipoli.android.common.text.DurationFormatter import io.ipoli.android.common.view.* import io.ipoli.android.quest.CompletedQuestViewState.StateType.DATA_LOADED import io.ipoli.android.quest.CompletedQuestViewState.StateType.QUEST_UNDO_COMPLETED import io.ipoli.android.quest.CompletedQuestViewState.Timer import io.ipoli.android.tag.Tag import kotlinx.android.synthetic.main.controller_completed_quest.view.* import kotlinx.android.synthetic.main.item_quest_tag_list.view.* import kotlinx.android.synthetic.main.view_default_toolbar.view.* /** * Created by Polina Zhelyazkova <[email protected]> * on 1/24/18. */ class CompletedQuestViewController : ReduxViewController<CompletedQuestAction, CompletedQuestViewState, CompletedQuestReducer> { private lateinit var questId: String override val reducer = CompletedQuestReducer constructor(args: Bundle? = null) : super(args) constructor(questId: String) : super() { this.questId = questId } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup, savedViewState: Bundle? ): View { setHasOptionsMenu(true) val view = inflater.inflate(R.layout.controller_completed_quest, container, false) setToolbar(view.toolbar) toolbarTitle = "Completed Quest" return view } override fun onOptionsItemSelected(item: MenuItem): Boolean { if (item.itemId == android.R.id.home) { return router.handleBack() } return super.onOptionsItemSelected(item) } override fun onCreateLoadAction() = CompletedQuestAction.Load(questId) override fun onAttach(view: View) { showBackButton() super.onAttach(view) } override fun render(state: CompletedQuestViewState, view: View) { when (state.type) { DATA_LOADED -> { view.questName.text = state.name renderTags(state.tags, view) state.icon?.let { view.questName.setCompoundDrawablesWithIntrinsicBounds( IconicsDrawable(view.context) .icon(it.icon) .colorRes(R.color.md_white) .sizeDp(24), null, null, null ) } val color = state.color!! view.questName.setBackgroundResource(color.color500) view.questDate.text = DateFormatter.format(view.context, state.completeAt) view.questTime.text = "${state.startedAt!!.toString(shouldUse24HourFormat)} - ${state.finishedAt!!.toString( shouldUse24HourFormat )}" view.questProgressDuration.text = DurationFormatter.formatShort(view.context, state.totalDuration!!.intValue) renderTimer(state.timer!!, view, state) renderBounty(view, state) view.questDurationProgress.secondaryProgressTintList = ColorStateList.valueOf(colorRes(color.color100)) view.questDurationProgress.progressTintList = ColorStateList.valueOf(colorRes(color.color300)) view.questDurationProgress.backgroundTintList = ColorStateList.valueOf(colorRes(color.color500)) view.level.text = "Lvl ${state.playerLevel!!}" view.levelProgress.backgroundTintList = ColorStateList.valueOf(attrData(R.attr.colorAccent)) view.levelProgress.progressTintList = ColorStateList.valueOf( lighten(attrData(R.attr.colorAccent), 0.6f) ) view.levelProgress.secondaryProgressTintList = ColorStateList.valueOf( lighten(attrData(R.attr.colorAccent), 0.3f) ) view.levelProgress.max = state.playerLevelMaxProgress!! view.levelProgress.secondaryProgress = state.playerLevelMaxProgress view.levelProgress.animateProgressFromZero(state.playerLevelProgress!!) } QUEST_UNDO_COMPLETED -> navigateFromRoot().setHome() else -> { } } } private fun renderTags( tags: List<Tag>, view: View ) { view.questTagList.removeAllViews() val inflater = LayoutInflater.from(activity!!) tags.forEach { tag -> val item = inflater.inflate(R.layout.item_quest_tag_list, view.questTagList, false) renderTag(item, tag) view.questTagList.addView(item) } } private fun renderTag(view: View, tag: Tag) { view.tagName.text = tag.name val indicator = view.tagName.compoundDrawablesRelative[0] as GradientDrawable indicator.setColor(colorRes(AndroidColor.valueOf(tag.color.name).color500)) } private fun lighten(@ColorInt color: Int, factor: Float): Int { val hsv = FloatArray(3) Color.colorToHSV(color, hsv) hsv[1] *= factor return Color.HSVToColor(hsv) } private fun renderBounty(view: View, state: CompletedQuestViewState) { view.bountyCoins.text = "+${state.coins} life coins" view.bountyXP.text = "+${state.experience} XP" if (state.bounty != null) { view.bonusItemGroup.showViews() view.bonusItemImage.setImageResource(state.bounty.image) } else { view.bonusItemGroup.goneViews() } } private fun renderTimer( timer: Timer, view: View, state: CompletedQuestViewState ) { when (timer) { is Timer.Pomodoro -> { view.pomodoroGroup.showViews() view.timerGroup.showViews() view.pomodoro.text = "${timer.completedPomodoros}/${timer.totalPomodoros} pomodoros" view.questWorkTime.text = createDurationLabel( view, "Work", timer.workDuration, timer.overdueWorkDuration ) view.questBreakTime.text = createDurationLabel( view, "Break", timer.breakDuration, timer.overdueBreakDuration ) view.questDurationProgress.max = state.totalDuration!!.intValue view.questDurationProgress.secondaryProgress = state.totalDuration.intValue view.questDurationProgress.animateProgressFromZero((timer.workDuration + timer.overdueWorkDuration).intValue) } is Timer.Countdown -> { view.pomodoroGroup.goneViews() view.timerGroup.showViews() view.questWorkTime.text = createDurationLabel( view, "Work", state.totalDuration!!, timer.overdueDuration ) val isOverdue = timer.overdueDuration.intValue > 0 view.questDurationProgress.max = timer.duration.intValue view.questDurationProgress.secondaryProgress = timer.duration.intValue if (isOverdue) { view.questDurationProgress.secondaryProgressTintList = ColorStateList.valueOf(colorRes(state.color!!.color300)) view.questDurationProgress.progressTintList = ColorStateList.valueOf(colorRes(state.color.color700)) view.questDurationProgress.animateProgressFromZero(timer.overdueDuration.intValue) } else { view.questDurationProgress.animateProgressFromZero(state.totalDuration.intValue) } } Timer.Untracked -> { view.pomodoroGroup.goneViews() view.timerGroup.goneViews() view.questDurationProgress.max = state.totalDuration!!.intValue view.questDurationProgress.animateProgressFromZero(state.totalDuration.intValue) } } } private fun createDurationLabel( view: View, startLabel: String, duration: Duration<Minute>, overdueDuration: Duration<Minute> ): String { var label = "$startLabel: ${DurationFormatter.formatShort( view.context, duration.intValue )}" if (overdueDuration.intValue > 0) { label += " (${DurationFormatter.formatShort( view.context, overdueDuration.intValue )})" } return label } }
gpl-3.0
117defcc329a4f29a67e07e5fd4d08fa
33.796364
125
0.601066
5.286188
false
false
false
false
JavaEden/Orchid-Core
plugins/OrchidKSS/src/main/kotlin/com/eden/orchid/kss/parser/StyleguideSection.kt
3
6928
package com.eden.orchid.kss.parser import com.eden.common.util.EdenPair import com.eden.common.util.EdenUtils import org.apache.commons.lang3.StringUtils import java.util.regex.Pattern import kotlin.collections.ArrayList class StyleguideSection(val raw: String, val filename: String) { val commentSections: MutableList<String> = ArrayList() val tags: MutableMap<String, String> = HashMap() var name: String = "" var description: String = "" var styleGuideReference: String = "" var styleGuidePath: Array<String> = emptyArray() var parent: StyleguideSection? = null var children: MutableList<StyleguideSection> = ArrayList() var modifiersText: String = "" var modifiers: List<Modifier> = ArrayList() val markup: String get() = getTaggedSection("markup") val stylesheet: String get() = getTaggedSection("source") private val ownWrapper: String get() { val formattedMarkup = "" + getTaggedSection("wrapper") return if (!EdenUtils.isEmpty(formattedMarkup) && formattedMarkup.contains("-markup")) { formattedMarkup } else { "-markup" } } // if we have our own wrapper, add it now // if parent has a wrapper, add it now val wrapper: String get() { var formattedMarkup = ownWrapper val parentWrapper = if (parent != null) parent!!.wrapper else "" if (!EdenUtils.isEmpty(parentWrapper) && parentWrapper.contains("-markup")) { formattedMarkup = parentWrapper.replace("-markup".toRegex(), formattedMarkup) } return formattedMarkup } val depth: Int get() = if (!EdenUtils.isEmpty(styleGuidePath)) styleGuidePath.size else 0 init { // Split comment block into sections, then put into a list so they can be manipulated val commentSectionsArray = raw.split("\n\n") for (commentSection in commentSectionsArray) { this.commentSections.add(commentSection) } for (i in commentSectionsArray.indices) { val section = commentSectionsArray[i] // line is Styleguide section. Parse then remove it if (isSectionReferenceCommentLine(section)) { val cleaned = section.trim().replace("\\.$", "") val m = Pattern.compile("Styleguide (.+)").matcher(cleaned) this.styleGuideReference = if (m.find()) StringUtils.strip(m.group(1), " .") else "1" this.styleGuidePath = this.styleGuideReference.split("\\.".toRegex()).toTypedArray() this.commentSections.removeAt(i) continue } // Line is tagged section, leave for now until needed if (isTaggedSection(section)) { val taggedSection = parseTaggedSection(section) tags.put(taggedSection!!.first.toLowerCase(), taggedSection.second) continue } // line is modifiers text if (isModifiersSection(section)) { this.modifiersText = section modifiers = parseModifiersSection(section) continue } // We don't have a name, so make this the name first if (EdenUtils.isEmpty(this.name)) { this.name = section } else { description += section + "\n" }// we already did the name, start adding to the description } } fun getTaggedSection(sectionKey: String): String { return tags.getOrDefault(sectionKey.toLowerCase(), "") } fun formatMarkup(modifier: Modifier): String { // set markup and add modifier class val markup = getTaggedSection("markup") var formattedMarkup = if (!EdenUtils.isEmpty(markup) && markup.contains("-modifierClass")) { markup.replace("-modifierClass".toRegex(), modifier.className()) } else { "<div class='-modifierClass'>Markup</div>".replace("-modifierClass".toRegex(), modifier.className()) } // if we have our own wrapper, add it now val wrapper = wrapper if (!EdenUtils.isEmpty(wrapper) && wrapper.contains("-markup")) { formattedMarkup = wrapper.replace("-markup".toRegex(), formattedMarkup) } return formattedMarkup } fun isParentOf(styleguideSection: StyleguideSection): Boolean { if (styleguideSection.styleGuidePath.size == styleGuidePath.size + 1) { for (i in styleGuidePath.indices) { if (!styleguideSection.styleGuidePath[i].equals(styleGuidePath[i], ignoreCase = true)) { return false } } return true } return false } // Implementation Helpers //---------------------------------------------------------------------------------------------------------------------- private fun isSectionReferenceCommentLine(section: String): Boolean { return KssParser.STYLEGUIDE_PATTERN.matcher(section).find() } private fun isTaggedSection(section: String): Boolean { return section.matches(TAGGED_SECTION_REGEX.toRegex()) } private fun parseTaggedSection(section: String): EdenPair<String, String>? { val m = Pattern.compile(TAGGED_SECTION_REGEX).matcher(section) return if (m.find()) { EdenPair(m.group(1), m.group(2)) } else null } private fun isModifiersSection(section: String): Boolean { return section.matches(MODIFIERS_SECTION_REGEX.toRegex()) } private fun parseModifiersSection(section: String?): ArrayList<Modifier> { var lastIndent: Int? = null val modifiers = ArrayList<Modifier>() if (section == null) { return modifiers } val precedingWhitespacePattern = Pattern.compile("^\\s*") for (modifierLine in section.split("\n")) { if ("" == modifierLine.trim()) { continue } val m = precedingWhitespacePattern.matcher(modifierLine) var match = "" if (m.find()) { match = m.group() } val indent = match.length if (lastIndent != null && indent > lastIndent) { //? } else { val name = modifierLine.split(" - ")[0].trim() val desc = modifierLine.split(" - ")[1].trim() val modifier = Modifier(name, desc) modifiers.add(modifier) } lastIndent = indent } return modifiers } companion object { internal val MODIFIERS_SECTION_REGEX = "(?sm)(^(.*)(\\s+-\\s+)(.*)$)+" internal val TAGGED_SECTION_REGEX = "(?s)(^\\w*):(.*)" } }
mit
7c26f65b379d503a14429e2fa95db8e6
33.467662
120
0.57448
4.98059
false
false
false
false
GunoH/intellij-community
platform/vcs-impl/src/com/intellij/openapi/vcs/VcsNotificationIdsHolder.kt
2
4226
// 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 import com.intellij.notification.impl.NotificationIdsHolder class VcsNotificationIdsHolder : NotificationIdsHolder { override fun getNotificationIds(): List<String> { return listOf( EXTERNALLY_ADDED_FILES, PROJECT_CONFIGURATION_FILES_ADDED, MANAGE_IGNORE_FILES, IGNORED_TO_EXCLUDE_NOT_FOUND, CHERRY_PICK_ERROR, COMMIT_CANCELED, COMMIT_FAILED, COMMIT_FINISHED, COMMIT_FINISHED_WITH_WARNINGS, COMMIT_CHECKS_FAILED, COMMIT_CHECKS_ONLY_FAILED, POST_COMMIT_CHECKS_FAILED, COMPARE_FAILED, COULD_NOT_COMPARE_WITH_BRANCH, INACTIVE_RANGES_DAMAGED, PATCH_APPLY_ABORTED, PATCH_ALREADY_APPLIED, PATCH_APPLY_CANNOT_FIND_PATCH_FILE, PATCH_APPLY_NEW_FILES_ERROR, PATCH_APPLY_NOT_PATCH_FILE, PATCH_PARTIALLY_APPLIED, PATCH_APPLY_ROLLBACK_FAILED, PATCH_APPLY_SUCCESS, PATCH_COPIED_TO_CLIPBOARD, PATCH_CREATION_FAILED, PROJECT_PARTIALLY_UPDATED, PROJECT_UPDATE_FINISHED, ROOT_ADDED, ROOTS_INVALID, ROOTS_REGISTERED, SHELVE_DELETION_UNDO, SHELVE_FAILED, SHELVE_SUCCESSFUL, SHELF_UNDO_DELETE, UNCOMMITTED_CHANGES_SAVING_ERROR, CANNOT_LOAD_ANNOTATIONS, SUGGESTED_PLUGIN_INSTALL_FAILED, OBSOLETE_PLUGIN_UNBUNDLED, ADD_UNVERSIONED_ERROR ) } companion object { const val EXTERNALLY_ADDED_FILES = "externally.added.files.notification" const val PROJECT_CONFIGURATION_FILES_ADDED = "project.configuration.files.added.notification" const val MANAGE_IGNORE_FILES = "manage.ignore.files.notification" const val IGNORED_TO_EXCLUDE_NOT_FOUND = "ignored.to.exclude.not.found" const val CHERRY_PICK_ERROR = "vcs.cherry.pick.error" const val COMMIT_CANCELED = "vcs.commit.canceled" const val COMMIT_FAILED = "vcs.commit.failed" const val COMMIT_FINISHED = "vcs.commit.finished" const val COMMIT_FINISHED_WITH_WARNINGS = "vcs.commit.finished.with.warnings" const val COMMIT_CHECKS_FAILED = "vcs.commit.checks.failed" const val POST_COMMIT_CHECKS_FAILED = "vcs.commit.checks.failed" const val COMMIT_CHECKS_ONLY_FAILED = "vcs.commit.checks.only.failed" const val COMPARE_FAILED = "vcs.compare.failed" const val COULD_NOT_COMPARE_WITH_BRANCH = "vcs.could.not.compare.with.branch" const val INACTIVE_RANGES_DAMAGED = "vcs.inactive.ranges.damaged" const val PATCH_APPLY_ABORTED = "vcs.patch.apply.aborted" const val PATCH_ALREADY_APPLIED = "vcs.patch.already.applied" const val PATCH_APPLY_CANNOT_FIND_PATCH_FILE = "vcs.patch.apply.cannot.find.patch.file" const val PATCH_APPLY_NEW_FILES_ERROR = "vcs.patch.apply.new.files.error" const val PATCH_APPLY_NOT_PATCH_FILE = "vcs.patch.apply.not.patch.type.file" const val PATCH_PARTIALLY_APPLIED = "vcs.patch.partially.applied" const val PATCH_APPLY_ROLLBACK_FAILED = "vcs.patch.apply.rollback.failed" const val PATCH_APPLY_SUCCESS = "vcs.patch.apply.success.applied" const val PATCH_COPIED_TO_CLIPBOARD = "vcs.patch.copied.to.clipboard" const val PATCH_CREATION_FAILED = "vcs.patch.creation.failed" const val PROJECT_PARTIALLY_UPDATED = "vcs.project.partially.updated" const val PROJECT_UPDATE_FINISHED = "vcs.project.update.finished" const val ROOT_ADDED = "vcs.root.added" const val ROOTS_INVALID = "vcs.roots.invalid" const val ROOTS_REGISTERED = "vcs.roots.registered" const val SHELVE_DELETION_UNDO = "vcs.shelve.deletion.undo" const val SHELVE_FAILED = "vcs.shelve.failed" const val SHELVE_SUCCESSFUL = "vcs.shelve.successful" const val SHELF_UNDO_DELETE = "vcs.shelf.undo.delete" const val UNCOMMITTED_CHANGES_SAVING_ERROR = "vcs.uncommitted.changes.saving.error" const val CANNOT_LOAD_ANNOTATIONS = "vcs.cannot.load.annotations" const val SUGGESTED_PLUGIN_INSTALL_FAILED = "vcs.suggested.plugin.install.failed" const val OBSOLETE_PLUGIN_UNBUNDLED = "vcs.obsolete.plugin.unbundled" const val ADD_UNVERSIONED_ERROR = "vcs.add.unversioned.error" } }
apache-2.0
5a0920a6c111f486b33a1edb1463c33c
44.44086
120
0.722196
3.700525
false
false
false
false
GunoH/intellij-community
plugins/kotlin/base/analysis/src/org/jetbrains/kotlin/idea/util/ProjectRootsUtil.kt
4
1882
// 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.util import com.intellij.openapi.module.Module import com.intellij.openapi.module.ModulePointerManager import com.intellij.openapi.module.ModuleUtilCore import com.intellij.openapi.project.Project import com.intellij.openapi.roots.ModuleRootManager import com.intellij.openapi.roots.ProjectRootManager import com.intellij.openapi.vfs.VirtualFile import com.intellij.psi.PsiElement import com.intellij.psi.PsiFileSystemItem import org.jetbrains.kotlin.idea.base.util.module as newModule fun VirtualFile.getSourceRoot(project: Project): VirtualFile? = ProjectRootManager.getInstance(project).fileIndex.getSourceRootForFile(this) val PsiFileSystemItem.sourceRoot: VirtualFile? get() = virtualFile?.getSourceRoot(project) @Deprecated( "Use 'com.intellij.openapi.project.rootManager' instead.", ReplaceWith("rootManager", imports = ["com.intellij.openapi.project.rootManager"]) ) val Module.rootManager: ModuleRootManager get() = ModuleRootManager.getInstance(this) val Module.sourceRoots: Array<VirtualFile> get() { @Suppress("DEPRECATION") return rootManager.sourceRoots } @Deprecated( "Use org.jetbrains.kotlin.idea.base.util.module instead.", ReplaceWith("module", "org.jetbrains.kotlin.idea.base.util.module") ) val PsiElement.module: Module? get() = newModule @Deprecated( "Use 'ModuleUtilCore.findModuleForFile()' instead.", ReplaceWith("ModuleUtilCore.findModuleForFile(this, project)", "com.intellij.openapi.module.ModuleUtilCore") ) fun VirtualFile.findModule(project: Project) = ModuleUtilCore.findModuleForFile(this, project) fun Module.createPointer() = ModulePointerManager.getInstance(project).create(this)
apache-2.0
9e24d5f18fb8ad1db50630d6cd512f59
38.229167
158
0.790648
4.356481
false
false
false
false
GunoH/intellij-community
plugins/kotlin/idea/tests/test/org/jetbrains/kotlin/idea/structuralsearch/search/KotlinSSTypeReferenceTest.kt
5
2950
// 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.structuralsearch.search import org.jetbrains.kotlin.idea.structuralsearch.KotlinStructuralSearchTest class KotlinSSTypeReferenceTest : KotlinStructuralSearchTest() { fun testAny() { doTest(pattern = "fun '_('_ : '_) { '_* }", highlighting = """ class Foo { class Int } <warning descr="SSR">fun foo1 (bar: Int = 1) { print(bar.hashCode()) }</warning> <warning descr="SSR">fun foo2 (bar: kotlin.Int) { print(bar.hashCode()) }</warning> <warning descr="SSR">fun foo3 (bar: Int?) { print(bar.hashCode()) }</warning> <warning descr="SSR">fun foo4 (bar: (Int) -> Int) { print(bar.hashCode()) }</warning> <warning descr="SSR">fun foo5 (bar: Foo.Int) { print(bar.hashCode()) }</warning> """.trimIndent()) } fun testFqType() { doTest(pattern = "fun '_('_ : kotlin.Int) { '_* }", highlighting = """ class Foo { class Int } fun foo1 (bar: Int = 1) { print(bar.hashCode()) } <warning descr="SSR">fun foo2 (bar: kotlin.Int) { print(bar.hashCode()) }</warning> fun foo3 (bar: Int?) { print(bar.hashCode()) } fun foo4 (bar: (Int) -> Int) { print(bar.hashCode()) } fun foo5 (bar: Foo.Int) { print(bar.hashCode()) } """.trimIndent()) } fun testFunctionType() { doTest(pattern = "fun '_('_ : ('_) -> '_) { '_* }", highlighting = """ fun foo1 (bar: Int) { print(bar.hashCode()) } fun foo2 (bar: kotlin.Int) { print(bar.hashCode()) } fun foo3 (bar: Int?) { print(bar.hashCode()) } <warning descr="SSR">fun foo4 (bar: (Int) -> Int) { print(bar.hashCode()) }</warning> """.trimIndent()) } fun testNullableType() { doTest(pattern = "fun '_('_ : '_ ?) { '_* }", highlighting = """ fun foo1 (bar: Int) { print(bar.hashCode()) } fun foo2 (bar: kotlin.Int) { print(bar.hashCode()) } <warning descr="SSR">fun foo3 (bar: Int?) { print(bar.hashCode()) }</warning> fun foo4 (bar: (Int) -> Int) { print(bar.hashCode()) } """.trimIndent()) } fun testFqTextFilter() { doTest(pattern = "fun '_('_ : '_:[regex( kotlin\\.Int )])", highlighting = """ <warning descr="SSR">fun foo1(x : Int) { print(x) }</warning> <warning descr="SSR">fun foo2(x : kotlin.Int) { print(x) }</warning> class X { class Int fun bar(x : Int) { print(x) } } """.trimIndent()) } fun testStandaloneNullable() { doTest(pattern = "Int?", highlighting = """ val foo: <warning descr="SSR">Int?</warning> = 1 var bar: Int = 1 """.trimIndent()) } fun testStandaloneParameter() { doTest(pattern = "Array<Int>", highlighting = """ val foo: <warning descr="SSR">Array<Int></warning> = arrayOf() var bar: Array<String> = arrayOf() """.trimIndent()) } }
apache-2.0
10b4643305f3e6e8cc954aa7d1aaec2f
49.87931
120
0.573559
3.673724
false
true
false
false
GunoH/intellij-community
plugins/kotlin/idea/tests/testData/inspectionsLocal/nullableBooleanElvis/inIfWithIfExpression.kt
4
256
fun foo() { var a: Int? = null fun isOddNumber(n: Int?): Boolean? { if (n == null) return null if (n < 0) return null return n % 2 == 1 } if ((if (isOddNumber(a) == true) a == 3 else null) <caret>?: false) { } }
apache-2.0
f0cf3130defd373bc35e0370d0f9156c
22.363636
73
0.476563
3.2
false
false
false
false
AsamK/TextSecure
app/src/main/java/org/thoughtcrime/securesms/components/settings/app/data/DataAndStorageSettingsFragment.kt
1
5712
package org.thoughtcrime.securesms.components.settings.app.data import androidx.lifecycle.ViewModelProvider import androidx.navigation.Navigation import androidx.preference.PreferenceManager import org.thoughtcrime.securesms.R import org.thoughtcrime.securesms.components.settings.DSLConfiguration import org.thoughtcrime.securesms.components.settings.DSLSettingsAdapter import org.thoughtcrime.securesms.components.settings.DSLSettingsFragment import org.thoughtcrime.securesms.components.settings.DSLSettingsText import org.thoughtcrime.securesms.components.settings.configure import org.thoughtcrime.securesms.mms.SentMediaQuality import org.thoughtcrime.securesms.util.Util import org.thoughtcrime.securesms.util.navigation.safeNavigate import org.thoughtcrime.securesms.webrtc.CallBandwidthMode import kotlin.math.abs class DataAndStorageSettingsFragment : DSLSettingsFragment(R.string.preferences__data_and_storage) { private val autoDownloadValues by lazy { resources.getStringArray(R.array.pref_media_download_entries) } private val autoDownloadLabels by lazy { resources.getStringArray(R.array.pref_media_download_values) } private val sentMediaQualityLabels by lazy { SentMediaQuality.getLabels(requireContext()) } private val callBandwidthLabels by lazy { resources.getStringArray(R.array.pref_data_and_storage_call_bandwidth_values) } private lateinit var viewModel: DataAndStorageSettingsViewModel override fun onResume() { super.onResume() viewModel.refresh() } override fun bindAdapter(adapter: DSLSettingsAdapter) { val preferences = PreferenceManager.getDefaultSharedPreferences(requireContext()) val repository = DataAndStorageSettingsRepository() val factory = DataAndStorageSettingsViewModel.Factory(preferences, repository) viewModel = ViewModelProvider(this, factory)[DataAndStorageSettingsViewModel::class.java] viewModel.state.observe(viewLifecycleOwner) { adapter.submitList(getConfiguration(it).toMappingModelList()) } } fun getConfiguration(state: DataAndStorageSettingsState): DSLConfiguration { return configure { clickPref( title = DSLSettingsText.from(R.string.preferences_data_and_storage__manage_storage), summary = DSLSettingsText.from(Util.getPrettyFileSize(state.totalStorageUse)), onClick = { Navigation.findNavController(requireView()).safeNavigate(R.id.action_dataAndStorageSettingsFragment_to_storagePreferenceFragment) } ) dividerPref() sectionHeaderPref(R.string.preferences_chats__media_auto_download) multiSelectPref( title = DSLSettingsText.from(R.string.preferences_chats__when_using_mobile_data), listItems = autoDownloadLabels, selected = autoDownloadValues.map { state.mobileAutoDownloadValues.contains(it) }.toBooleanArray(), onSelected = { val resultSet = it.mapIndexed { index, selected -> if (selected) autoDownloadValues[index] else null }.filterNotNull().toSet() viewModel.setMobileAutoDownloadValues(resultSet) } ) multiSelectPref( title = DSLSettingsText.from(R.string.preferences_chats__when_using_wifi), listItems = autoDownloadLabels, selected = autoDownloadValues.map { state.wifiAutoDownloadValues.contains(it) }.toBooleanArray(), onSelected = { val resultSet = it.mapIndexed { index, selected -> if (selected) autoDownloadValues[index] else null }.filterNotNull().toSet() viewModel.setWifiAutoDownloadValues(resultSet) } ) multiSelectPref( title = DSLSettingsText.from(R.string.preferences_chats__when_roaming), listItems = autoDownloadLabels, selected = autoDownloadValues.map { state.roamingAutoDownloadValues.contains(it) }.toBooleanArray(), onSelected = { val resultSet = it.mapIndexed { index, selected -> if (selected) autoDownloadValues[index] else null }.filterNotNull().toSet() viewModel.setRoamingAutoDownloadValues(resultSet) } ) dividerPref() sectionHeaderPref(R.string.DataAndStorageSettingsFragment__media_quality) radioListPref( title = DSLSettingsText.from(R.string.DataAndStorageSettingsFragment__sent_media_quality), listItems = sentMediaQualityLabels, selected = SentMediaQuality.values().indexOf(state.sentMediaQuality), onSelected = { viewModel.setSentMediaQuality(SentMediaQuality.values()[it]) } ) textPref( summary = DSLSettingsText.from(R.string.DataAndStorageSettingsFragment__sending_high_quality_media_will_use_more_data) ) dividerPref() sectionHeaderPref(R.string.DataAndStorageSettingsFragment__calls) radioListPref( title = DSLSettingsText.from(R.string.preferences_data_and_storage__use_less_data_for_calls), listItems = callBandwidthLabels, selected = abs(state.callBandwidthMode.code - 2), onSelected = { viewModel.setCallBandwidthMode(CallBandwidthMode.fromCode(abs(it - 2))) } ) textPref( summary = DSLSettingsText.from(R.string.preference_data_and_storage__using_less_data_may_improve_calls_on_bad_networks) ) dividerPref() sectionHeaderPref(R.string.preferences_proxy) clickPref( title = DSLSettingsText.from(R.string.preferences_use_proxy), summary = DSLSettingsText.from(if (state.isProxyEnabled) R.string.preferences_on else R.string.preferences_off), onClick = { Navigation.findNavController(requireView()).safeNavigate(R.id.action_dataAndStorageSettingsFragment_to_editProxyFragment) } ) } } }
gpl-3.0
323f1104716795db9b23cbd0e0a4ba9e
41.626866
139
0.743697
4.962641
false
false
false
false
walleth/kethereum
crypto_impl_java_provider/src/main/kotlin/org/kethereum/crypto/impl/mac/HmacImpl.kt
1
764
package org.kethereum.crypto.impl.mac import org.kethereum.crypto.impl.hashing.DigestParams import org.kethereum.crypto.api.mac.Hmac import javax.crypto.Mac import javax.crypto.spec.SecretKeySpec class HmacImpl : Hmac { private lateinit var mac: Mac override fun init(key: ByteArray, digestParams: DigestParams): Hmac { val version = digestParams.toHmacVersion() mac = Mac.getInstance(version) val keySpec = SecretKeySpec(key, version) mac.init(keySpec) return this } override fun generate(data: ByteArray): ByteArray = mac.doFinal(data) private fun DigestParams.toHmacVersion() = when(this) { DigestParams.Sha512 -> "HmacSHA512" DigestParams.Sha256 -> "HmacSHA256" } }
mit
a8372013f30b6d8da1d0caa6a5d9fa51
27.296296
73
0.697644
4.06383
false
false
false
false
ktorio/ktor
ktor-client/ktor-client-core/common/src/io/ktor/client/request/forms/FormDataContent.kt
1
5764
/* * 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.client.request.forms import io.ktor.http.* import io.ktor.http.content.* import io.ktor.utils.io.* import io.ktor.utils.io.charsets.* import io.ktor.utils.io.core.* import kotlin.random.* private val RN_BYTES = "\r\n".toByteArray() /** * [OutgoingContent] with for the `application/x-www-form-urlencoded` formatted request. * * Example: [Form parameters](https://ktor.io/docs/request.html#form_parameters). * * @param formData: data to send. */ public class FormDataContent( public val formData: Parameters ) : OutgoingContent.ByteArrayContent() { private val content = formData.formUrlEncode().toByteArray() override val contentLength: Long = content.size.toLong() override val contentType: ContentType = ContentType.Application.FormUrlEncoded.withCharset(Charsets.UTF_8) override fun bytes(): ByteArray = content } /** * [OutgoingContent] for a `multipart/form-data` formatted request. * * Example: [Upload a file](https://ktor.io/docs/request.html#upload_file). * * @param parts: form part data */ public class MultiPartFormDataContent( parts: List<PartData>, public val boundary: String = generateBoundary(), override val contentType: ContentType = ContentType.MultiPart.FormData.withParameter("boundary", boundary) ) : OutgoingContent.WriteChannelContent() { private val BOUNDARY_BYTES = "--$boundary\r\n".toByteArray() private val LAST_BOUNDARY_BYTES = "--$boundary--\r\n".toByteArray() private val BODY_OVERHEAD_SIZE = LAST_BOUNDARY_BYTES.size private val PART_OVERHEAD_SIZE = RN_BYTES.size * 2 + BOUNDARY_BYTES.size private val rawParts: List<PreparedPart> = parts.map { part -> val headersBuilder = BytePacketBuilder() for ((key, values) in part.headers.entries()) { headersBuilder.writeText("$key: ${values.joinToString("; ")}") headersBuilder.writeFully(RN_BYTES) } val bodySize = part.headers[HttpHeaders.ContentLength]?.toLong() when (part) { is PartData.FileItem -> { val headers = headersBuilder.build().readBytes() val size = bodySize?.plus(PART_OVERHEAD_SIZE)?.plus(headers.size) PreparedPart.InputPart(headers, part.provider, size) } is PartData.BinaryItem -> { val headers = headersBuilder.build().readBytes() val size = bodySize?.plus(PART_OVERHEAD_SIZE)?.plus(headers.size) PreparedPart.InputPart(headers, part.provider, size) } is PartData.FormItem -> { val bytes = buildPacket { writeText(part.value) }.readBytes() val provider = { buildPacket { writeFully(bytes) } } if (bodySize == null) { headersBuilder.writeText("${HttpHeaders.ContentLength}: ${bytes.size}") headersBuilder.writeFully(RN_BYTES) } val headers = headersBuilder.build().readBytes() val size = bytes.size + PART_OVERHEAD_SIZE + headers.size PreparedPart.InputPart(headers, provider, size.toLong()) } is PartData.BinaryChannelItem -> { val headers = headersBuilder.build().readBytes() val size = bodySize?.plus(PART_OVERHEAD_SIZE)?.plus(headers.size) PreparedPart.ChannelPart(headers, part.provider, size) } } } override val contentLength: Long? init { var rawLength: Long? = 0 for (part in rawParts) { val size = part.size if (size == null) { rawLength = null break } rawLength = rawLength?.plus(size) } if (rawLength != null) { rawLength += BODY_OVERHEAD_SIZE } contentLength = rawLength } override suspend fun writeTo(channel: ByteWriteChannel) { try { for (part in rawParts) { channel.writeFully(BOUNDARY_BYTES) channel.writeFully(part.headers) channel.writeFully(RN_BYTES) when (part) { is PreparedPart.InputPart -> { part.provider().use { input -> input.copyTo(channel) } } is PreparedPart.ChannelPart -> { part.provider().copyTo(channel) } } channel.writeFully(RN_BYTES) } channel.writeFully(LAST_BOUNDARY_BYTES) } catch (cause: Throwable) { channel.close(cause) } finally { channel.close() } } } private fun generateBoundary(): String = buildString { repeat(32) { append(Random.nextInt().toString(16)) } }.take(70) private sealed class PreparedPart(val headers: ByteArray, val size: Long?) { class InputPart(headers: ByteArray, val provider: () -> Input, size: Long?) : PreparedPart(headers, size) class ChannelPart( headers: ByteArray, val provider: () -> ByteReadChannel, size: Long? ) : PreparedPart(headers, size) } private suspend fun Input.copyTo(channel: ByteWriteChannel) { if (this is ByteReadPacket) { channel.writePacket(this) return } while ([email protected]) { channel.write { freeSpace, startOffset, endExclusive -> [email protected](freeSpace, startOffset, endExclusive - startOffset).toInt() } } }
apache-2.0
4a8ff7f51f2c3445b2cbb99b785a23f4
33.309524
118
0.597502
4.60016
false
false
false
false
google/android-fhir
workflow/src/main/java/com/google/android/fhir/workflow/FhirEngineTerminologyProvider.kt
1
5062
/* * Copyright 2022 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.fhir.workflow import ca.uhn.fhir.context.FhirContext import com.google.android.fhir.FhirEngine import com.google.android.fhir.db.ResourceNotFoundException import com.google.android.fhir.search.search import kotlinx.coroutines.runBlocking import org.hl7.fhir.r4.model.CodeSystem import org.hl7.fhir.r4.model.Resource import org.hl7.fhir.r4.model.ResourceType import org.hl7.fhir.r4.model.ValueSet import org.opencds.cqf.cql.engine.exception.TerminologyProviderException import org.opencds.cqf.cql.engine.runtime.Code import org.opencds.cqf.cql.engine.terminology.CodeSystemInfo import org.opencds.cqf.cql.engine.terminology.TerminologyProvider import org.opencds.cqf.cql.engine.terminology.ValueSetInfo import org.opencds.cqf.cql.evaluator.engine.util.ValueSetUtil class FhirEngineTerminologyProvider( private val fhirContext: FhirContext, private val fhirEngine: FhirEngine ) : TerminologyProvider { companion object { const val URN_UUID = "urn:uuid:" const val URN_OID = "urn:oid:" } override fun `in`(code: Code, valueSet: ValueSetInfo): Boolean { try { return expand(valueSet).any { it.code == code.code && it.system == code.system } } catch (e: Exception) { throw TerminologyProviderException( "Error performing membership check of Code: $code in ValueSet: ${valueSet.id}", e ) } } override fun expand(valueSetInfo: ValueSetInfo): MutableIterable<Code> { try { val valueSet = resolveValueSet(valueSetInfo) return ValueSetUtil.getCodesInExpansion(fhirContext, valueSet) ?: ValueSetUtil.getCodesInCompose(fhirContext, valueSet) } catch (e: Exception) { throw TerminologyProviderException( "Error performing expansion of ValueSet: ${valueSetInfo.id}", e ) } } override fun lookup(code: Code, codeSystem: CodeSystemInfo): Code { try { val codeSystems = runBlocking { fhirEngine.search<CodeSystem> { filter(CodeSystem.CODE, { value = of(code.code) }) filter(CodeSystem.SYSTEM, { value = codeSystem.id }) } } val concept = codeSystems.first().concept.first { it.code == code.code } return Code().apply { this.code = code.code display = concept.display system = codeSystem.id } } catch (e: Exception) { throw TerminologyProviderException( "Error performing lookup of Code: $code in CodeSystem: ${codeSystem.id}", e ) } } private fun searchByUrl(url: String?): List<ValueSet> { if (url == null) return emptyList() return runBlocking { fhirEngine.search { filter(ValueSet.URL, { value = url }) } } } private fun searchByIdentifier(identifier: String?): List<ValueSet> { if (identifier == null) return emptyList() return runBlocking { fhirEngine.search { filter(ValueSet.IDENTIFIER, { value = of(identifier) }) } } } private fun searchById(id: String): List<ValueSet> { return runBlocking { listOfNotNull( safeGet(fhirEngine, ResourceType.ValueSet, id.removePrefix(URN_OID).removePrefix(URN_UUID)) as? ValueSet ) } } private suspend fun safeGet(fhirEngine: FhirEngine, type: ResourceType, id: String): Resource? { return try { fhirEngine.get(type, id) } catch (e: ResourceNotFoundException) { null } } fun resolveValueSet(valueSet: ValueSetInfo): ValueSet { if (valueSet.version != null || (valueSet.codeSystems != null && valueSet.codeSystems.isNotEmpty()) ) { // Cannot do both at the same time yet. throw UnsupportedOperationException( "Could not expand value set ${valueSet.id}; version and code system bindings are not supported at this time." ) } var searchResults = searchByUrl(valueSet.id) if (searchResults.isEmpty()) { searchResults = searchByIdentifier(valueSet.id) } if (searchResults.isEmpty()) { searchResults = searchById(valueSet.id) } return if (searchResults.isEmpty()) { throw IllegalArgumentException("Could not resolve value set ${valueSet.id}.") } else if (searchResults.size > 1) { throw IllegalArgumentException("Found more than 1 ValueSet with url: ${valueSet.id}") } else { searchResults.first() } } fun resolveValueSetId(valueSet: ValueSetInfo): String { return resolveValueSet(valueSet).idElement.idPart } }
apache-2.0
4e166db3692a1bd0dcaed2a79b31796d
32.302632
117
0.692809
4.155993
false
false
false
false
mdanielwork/intellij-community
python/src/com/jetbrains/python/sdk/PySdkSettings.kt
4
3890
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.jetbrains.python.sdk import com.intellij.application.options.ReplacePathToMacroMap import com.intellij.openapi.components.* import com.intellij.openapi.util.io.FileUtil import com.intellij.util.PathUtil import com.intellij.util.SystemProperties import com.intellij.util.xmlb.XmlSerializerUtil import com.jetbrains.python.sdk.flavors.VirtualEnvSdkFlavor import org.jetbrains.annotations.SystemIndependent import org.jetbrains.jps.model.serialization.PathMacroUtil /** * @author vlan */ @State(name = "PySdkSettings", storages = [ Storage(value = "pySdk.xml", roamingType = RoamingType.DISABLED), Storage(value = "py_sdk_settings.xml", roamingType = RoamingType.DISABLED, deprecated = true) ]) class PySdkSettings : PersistentStateComponent<PySdkSettings.State> { companion object { @JvmStatic val instance: PySdkSettings get() = ServiceManager.getService(PySdkSettings::class.java) private const val VIRTUALENV_ROOT_DIR_MACRO_NAME = "VIRTUALENV_ROOT_DIR" } private val state: State = State() var useNewEnvironmentForNewProject: Boolean get() = state.USE_NEW_ENVIRONMENT_FOR_NEW_PROJECT set(value) { state.USE_NEW_ENVIRONMENT_FOR_NEW_PROJECT = value } var preferredEnvironmentType: String? get() = state.PREFERRED_ENVIRONMENT_TYPE set(value) { state.PREFERRED_ENVIRONMENT_TYPE = value } var preferredVirtualEnvBaseSdk: String? get() = state.PREFERRED_VIRTUALENV_BASE_SDK set(value) { state.PREFERRED_VIRTUALENV_BASE_SDK = value } fun setPreferredVirtualEnvBasePath(value: @SystemIndependent String, projectPath: @SystemIndependent String?) { val pathMap = ReplacePathToMacroMap().apply { projectPath?.let { addMacroReplacement(it, PathMacroUtil.PROJECT_DIR_MACRO_NAME) } addMacroReplacement(defaultVirtualEnvRoot, VIRTUALENV_ROOT_DIR_MACRO_NAME) } val pathToSave = when { projectPath != null && FileUtil.isAncestor(projectPath, value, true) -> value.trimEnd { !it.isLetter() } else -> PathUtil.getParentPath(value) } state.PREFERRED_VIRTUALENV_BASE_PATH = pathMap.substitute(pathToSave, true) } fun getPreferredVirtualEnvBasePath(projectPath: @SystemIndependent String?): @SystemIndependent String { val pathMap = ExpandMacroToPathMap().apply { addMacroExpand(PathMacroUtil.PROJECT_DIR_MACRO_NAME, projectPath ?: userHome) addMacroExpand(VIRTUALENV_ROOT_DIR_MACRO_NAME, defaultVirtualEnvRoot) } val defaultPath = when { defaultVirtualEnvRoot != userHome -> defaultVirtualEnvRoot else -> "$${PathMacroUtil.PROJECT_DIR_MACRO_NAME}$/venv" } val rawSavedPath = state.PREFERRED_VIRTUALENV_BASE_PATH ?: defaultPath val savedPath = pathMap.substitute(rawSavedPath, true) return when { projectPath != null && FileUtil.isAncestor(projectPath, savedPath, true) -> savedPath projectPath != null -> "$savedPath/${PathUtil.getFileName(projectPath)}" else -> savedPath } } override fun getState(): State = state override fun loadState(state: PySdkSettings.State) { XmlSerializerUtil.copyBean(state, this.state) } @Suppress("PropertyName") class State { @JvmField var USE_NEW_ENVIRONMENT_FOR_NEW_PROJECT: Boolean = true @JvmField var PREFERRED_ENVIRONMENT_TYPE: String? = null @JvmField var PREFERRED_VIRTUALENV_BASE_PATH: String? = null @JvmField var PREFERRED_VIRTUALENV_BASE_SDK: String? = null } private val defaultVirtualEnvRoot: @SystemIndependent String get() = VirtualEnvSdkFlavor.getDefaultLocation()?.path ?: userHome private val userHome: @SystemIndependent String get() = FileUtil.toSystemIndependentName(SystemProperties.getUserHome()) }
apache-2.0
6fb25b160de0989c5073a3b42eb491f2
36.057143
140
0.736761
4.486736
false
false
false
false
Frederikam/FredBoat
FredBoat/src/main/java/fredboat/command/music/control/PlayCommand.kt
1
7839
/* * MIT License * * Copyright (c) 2017 Frederik Ar. Mikkelsen * * 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 fredboat.command.music.control import com.sedmelluq.discord.lavaplayer.track.AudioPlaylist import fredboat.audio.player.GuildPlayer import fredboat.audio.player.PlayerLimiter import fredboat.audio.player.VideoSelectionCache import fredboat.command.info.HelpCommand import fredboat.commandmeta.abs.Command import fredboat.commandmeta.abs.CommandContext import fredboat.commandmeta.abs.ICommandRestricted import fredboat.commandmeta.abs.IMusicCommand import fredboat.definitions.PermissionLevel import fredboat.definitions.SearchProvider import fredboat.main.Launcher import fredboat.messaging.internal.Context import fredboat.shared.constant.BotConstants import fredboat.util.TextUtils import fredboat.util.extension.edit import fredboat.util.localMessageBuilder import fredboat.util.rest.TrackSearcher import org.apache.commons.lang3.StringUtils import org.slf4j.LoggerFactory class PlayCommand(private val playerLimiter: PlayerLimiter, private val trackSearcher: TrackSearcher, private val videoSelectionCache: VideoSelectionCache, private val searchProviders: List<SearchProvider>, name: String, vararg aliases: String, private val isPriority: Boolean = false ) : Command(name, *aliases), IMusicCommand, ICommandRestricted { override val minimumPerms: PermissionLevel get() = if (isPriority) PermissionLevel.DJ else PermissionLevel.USER override suspend fun invoke(context: CommandContext) { if (context.member.voiceChannel == null) { context.reply(context.i18n("playerUserNotInChannel")) return } if (!playerLimiter.checkLimitResponsive(context, Launcher.botController.playerRegistry)) return if (!context.msg.attachments.isEmpty()) { val player = Launcher.botController.playerRegistry.getOrCreate(context.guild) for (atc in context.msg.attachments) { player.queue(atc, context, isPriority) } player.setPause(false) return } if (!context.hasArguments()) { val player = Launcher.botController.playerRegistry.getExisting(context.guild) handleNoArguments(context, player) return } if (TextUtils.isSplitSelect(context.rawArgs)) { SelectCommand.select(context, videoSelectionCache) return } var url = StringUtils.strip(context.args[0], "<>") //Search youtube for videos and let the user select a video if (!url.startsWith("http") && !url.startsWith(FILE_PREFIX)) { searchForVideos(context) return } if (url.startsWith(FILE_PREFIX)) { url = url.replaceFirst(FILE_PREFIX.toRegex(), "") //LocalAudioSourceManager does not manage this itself } val player = Launcher.botController.playerRegistry.getOrCreate(context.guild) player.queue(url, context, isPriority) player.setPause(false) context.deleteMessage() } private suspend fun handleNoArguments(context: CommandContext, player: GuildPlayer?) { if (player == null || player.isQueueEmpty) { context.reply(context.i18n("playQueueEmpty") .replace(";;play", context.prefix + context.command.name)) } else if (player.isPlaying && !isPriority) { context.reply(context.i18n("playAlreadyPlaying")) } else if (player.humanUsersInCurrentVC.isEmpty() && context.guild.selfMember.voiceChannel != null) { context.reply(context.i18n("playVCEmpty")) } else if (context.guild.selfMember.voiceChannel == null) { // When we just want to continue playing, but the user is not in a VC JOIN_COMMAND.invoke(context) if (context.guild.selfMember.voiceChannel != null) { player.play() context.reply(context.i18n("playWillNowPlay")) } } else if (isPriority) { HelpCommand.sendFormattedCommandHelp(context) } else { player.play() context.reply(context.i18n("playWillNowPlay")) } } private fun searchForVideos(context: CommandContext) { //Now remove all punctuation val query = context.rawArgs.replace(TrackSearcher.PUNCTUATION_REGEX.toRegex(), "") context.replyMono(context.i18n("playSearching").replace("{q}", query)) .subscribe{ outMsg -> val list: AudioPlaylist? try { list = trackSearcher.searchForTracks(query, searchProviders) } catch (e: TrackSearcher.SearchingException) { context.reply(context.i18n("playYoutubeSearchError")) log.error("YouTube search exception", e) return@subscribe } if (list == null || list.tracks.isEmpty()) { outMsg.edit( context.textChannel, context.i18n("playSearchNoResults").replace("{q}", query) ).subscribe() } else { //Get at most 5 tracks val selectable = list.tracks.subList(0, Math.min(TrackSearcher.MAX_RESULTS, list.tracks.size)) val oldSelection = videoSelectionCache.remove(context.member) oldSelection?.deleteMessage() val builder = localMessageBuilder() builder.append(context.i18nFormat("playSelectVideo", TextUtils.escapeMarkdown(context.prefix))) var i = 1 for (track in selectable) { builder.append("\n**") .append(i.toString()) .append(":** ") .append(TextUtils.escapeAndDefuse(track.info.title)) .append(" (") .append(TextUtils.formatTime(track.info.length)) .append(")") i++ } outMsg.edit(context.textChannel, builder.build()).subscribe() videoSelectionCache.put(outMsg.messageId, context, selectable, isPriority) } } } override fun help(context: Context): String { val usage = "{0}{1} <url> OR {0}{1} <search-term>\n#" return usage + context.i18nFormat(if (!isPriority) "helpPlayCommand" else "helpPlayNextCommand", BotConstants.DOCS_URL) } companion object { private val log = LoggerFactory.getLogger(PlayCommand::class.java) private val JOIN_COMMAND = JoinCommand("") private const val FILE_PREFIX = "file://" } }
mit
b9c54260a4e87516129d788c16d850c1
40.47619
127
0.646894
4.776965
false
false
false
false
cdietze/klay
src/main/kotlin/klay/core/RenderTarget.kt
1
3393
package klay.core import klay.core.GL20.Companion.GL_COLOR_ATTACHMENT0 import klay.core.GL20.Companion.GL_FRAMEBUFFER import klay.core.GL20.Companion.GL_TEXTURE_2D import react.Closeable /** * Encapsulates an OpenGL render target (i.e. a framebuffer). * @see Graphics.defaultRenderTarget */ abstract class RenderTarget( /** A handle on our graphics services. */ val gfx: Graphics) : Closeable { /** The framebuffer id. */ abstract fun id(): Int /** The width of the framebuffer in pixels. */ abstract fun width(): Int /** The height of the framebuffer in pixels. */ abstract fun height(): Int /** The x-scale between display units and pixels for this target. */ abstract fun xscale(): Float /** The y-scale between display units and pixels for this target. */ abstract fun yscale(): Float /** Whether or not to flip the y-axis when rendering to this target. When rendering to textures * we do not want to flip the y-axis, but when rendering to the screen we do (so that the origin * is at the upper-left of the screen). */ abstract fun flip(): Boolean /** Binds the framebuffer. */ fun bind() { gfx.gl.glBindFramebuffer(GL_FRAMEBUFFER, id()) gfx.gl.glViewport(0, 0, width(), height()) } /** Deletes the framebuffer associated with this render target. */ override fun close() { if (!disposed) { disposed = true if (gfx.exec.isMainThread()) { gfx.gl.glDeleteFramebuffer(id()) } else { gfx.exec.invokeLater { gfx.gl.glDeleteFramebuffer(id()) } } } } override fun toString(): String { return "[id=" + id() + ", size=" + width() + "x" + height() + " @ " + xscale() + "x" + yscale() + ", flip=" + flip() + "]" } /** * Java finalizer, see [Kotlin documentation](https://kotlinlang.org/docs/reference/java-interop.html#finalize) */ @Suppress("unused") protected fun finalize() { this.close() } private var disposed: Boolean = false companion object { /** Creates a render target that renders to `texture`. */ fun create(gfx: Graphics, tex: Texture): RenderTarget { val gl = gfx.gl val fb = gl.glGenFramebuffer() if (fb == 0) throw RuntimeException("Failed to gen framebuffer: " + gl.glGetError()) gl.glBindFramebuffer(GL_FRAMEBUFFER, fb) gl.glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, tex.id, 0) gl.checkError("RenderTarget.create") return object : RenderTarget(gfx) { override fun id(): Int { return fb } override fun width(): Int { return tex.pixelWidth } override fun height(): Int { return tex.pixelHeight } override fun xscale(): Float { return tex.pixelWidth / tex.displayWidth } override fun yscale(): Float { return tex.pixelHeight / tex.displayHeight } override fun flip(): Boolean { return false } } } } }
apache-2.0
c426957e2254777806d2de3598287879
31.009434
115
0.558503
4.560484
false
false
false
false
DreierF/MyTargets
app/src/main/java/de/dreier/mytargets/features/statistics/DispersionPatternActivity.kt
1
5545
/* * 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.features.statistics import android.content.Intent import androidx.databinding.DataBindingUtil import android.os.Build import android.os.Bundle import android.print.PrintAttributes import android.print.PrintManager import androidx.annotation.RequiresApi import android.view.Menu import android.view.MenuItem import androidx.core.content.getSystemService import com.google.android.material.snackbar.Snackbar import de.dreier.mytargets.R import de.dreier.mytargets.base.activities.ChildActivityBase import de.dreier.mytargets.databinding.ActivityArrowRankingDetailsBinding import de.dreier.mytargets.features.scoreboard.EFileType import de.dreier.mytargets.features.settings.ESettingsScreens import de.dreier.mytargets.features.settings.SettingsManager import de.dreier.mytargets.utils.ToolbarUtils import de.dreier.mytargets.utils.Utils import de.dreier.mytargets.utils.print.CustomPrintDocumentAdapter import de.dreier.mytargets.utils.print.DrawableToPdfWriter import de.dreier.mytargets.utils.toUri import java.io.File import java.io.IOException class DispersionPatternActivity : ChildActivityBase() { private var binding: ActivityArrowRankingDetailsBinding? = null private lateinit var statistic: ArrowStatistic override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = DataBindingUtil .setContentView(this, R.layout.activity_arrow_ranking_details) statistic = intent.getParcelableExtra(ITEM) ToolbarUtils.showHomeAsUp(this) if (statistic.arrowName != null) { ToolbarUtils.setTitle( this, getString( R.string.arrow_number_x, statistic .arrowNumber ) ) ToolbarUtils.setSubtitle(this, statistic.arrowName!!) } else { ToolbarUtils.setTitle(this, R.string.dispersion_pattern) } } override fun onResume() { super.onResume() val drawable = DispersionPatternUtils.targetFromArrowStatistics(statistic) binding!!.dispersionView.setImageDrawable(drawable) } override fun onCreateOptionsMenu(menu: Menu): Boolean { menuInflater.inflate(R.menu.menu_scoreboard, menu) menu.findItem(R.id.action_print).isVisible = Utils.isKitKat return true } override fun onOptionsItemSelected(item: MenuItem): Boolean { when (item.itemId) { R.id.action_share -> shareImage() R.id.action_print -> if (Utils.isKitKat) print() R.id.action_settings -> navigationController.navigateToSettings(ESettingsScreens.STATISTICS) else -> return super.onOptionsItemSelected(item) } return true } /* Called after the user selected with items he wants to share */ private fun shareImage() { Thread { try { val fileType = SettingsManager.statisticsDispersionPatternFileType val f = File(cacheDir, getDefaultFileName(fileType)) if (fileType === EFileType.PDF && Utils.isKitKat) { DispersionPatternUtils.generatePdf(f, statistic) } else { DispersionPatternUtils.createDispersionPatternImageFile(1200, f, statistic) } // Build and fire intent to ask for share provider val shareIntent = Intent(Intent.ACTION_SEND) shareIntent.type = fileType.mimeType shareIntent.putExtra(Intent.EXTRA_STREAM, f.toUri(this@DispersionPatternActivity)) startActivity(Intent.createChooser(shareIntent, getString(R.string.share))) } catch (e: IOException) { e.printStackTrace() Snackbar.make(binding!!.root, R.string.sharing_failed, Snackbar.LENGTH_SHORT) .show() } }.start() } @RequiresApi(Build.VERSION_CODES.KITKAT) private fun print() { val target = DispersionPatternUtils.targetFromArrowStatistics(statistic) val fileName = getDefaultFileName(EFileType.PDF) val pda = CustomPrintDocumentAdapter(DrawableToPdfWriter(target), fileName) // Create a print job with name and adapter instance val printManager = getSystemService<PrintManager>()!! val jobName = "Dispersion Pattern" printManager.print(jobName, pda, PrintAttributes.Builder().build()) } private fun getDefaultFileName(extension: EFileType): String { var name = if (statistic.arrowName != null) { statistic.arrowName!! + "-" + getString(R.string.arrow_number_x, statistic.arrowNumber) } else { statistic.exportFileName } if (!name.isNullOrEmpty()) { name = "-" + name } return getString(R.string.dispersion_pattern) + name + "." + extension.name.toLowerCase() } companion object { const val ITEM = "item" } }
gpl-2.0
c5255d4ef0c63352dac1d55279c044fc
38.049296
104
0.681515
4.838569
false
false
false
false
skydoves/ElasticViews
elasticviews/src/main/java/com/skydoves/elasticviews/ElasticImageView.kt
1
4594
/* * The MIT License (MIT) * * Copyright (c) 2017 skydoves * * 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.skydoves.elasticviews import android.content.Context import android.content.res.TypedArray import android.util.AttributeSet import android.view.View import android.view.View.OnClickListener import androidx.appcompat.widget.AppCompatImageView @Suppress("unused") class ElasticImageView @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null, defStyle: Int = 0 ) : AppCompatImageView(context, attrs, defStyle), ElasticInterface { /** The target elastic scale size of the animation. */ var scale = Definitions.DEFAULT_SCALE /** The default duration of the animation. */ var duration = Definitions.DEFAULT_DURATION private var onClickListener: OnClickListener? = null private var onFinishListener: ElasticFinishListener? = null init { onCreate() when { attrs != null && defStyle != 0 -> getAttrs(attrs, defStyle) attrs != null -> getAttrs(attrs) } } private fun onCreate() { this.isClickable = true super.setOnClickListener { elasticAnimation(this) { setDuration([email protected]) setScaleX([email protected]) setScaleY([email protected]) setOnFinishListener { invokeListeners() } }.doAction() } } private fun getAttrs(attrs: AttributeSet) { val typedArray = context.obtainStyledAttributes(attrs, R.styleable.ElasticImageView) try { setTypeArray(typedArray) } finally { typedArray.recycle() } } private fun getAttrs(attrs: AttributeSet, defStyle: Int) { val typedArray = context.obtainStyledAttributes(attrs, R.styleable.ElasticImageView, defStyle, 0) try { setTypeArray(typedArray) } finally { typedArray.recycle() } } private fun setTypeArray(typedArray: TypedArray) { this.scale = typedArray.getFloat(R.styleable.ElasticImageView_imageView_scale, scale) this.duration = typedArray.getInt(R.styleable.ElasticImageView_imageView_duration, duration) } override fun setOnClickListener(listener: OnClickListener?) { this.onClickListener = listener } override fun setOnFinishListener(listener: ElasticFinishListener?) { this.onFinishListener = listener } override fun setOnClickListener(block: (View) -> Unit) = setOnClickListener(OnClickListener(block)) override fun setOnFinishListener(block: () -> Unit) = setOnFinishListener(ElasticFinishListener(block)) private fun invokeListeners() { this.onClickListener?.onClick(this) this.onFinishListener?.onFinished() } /** Builder class for creating [ElasticImageView]. */ class Builder(context: Context) { private val elasticImageView = ElasticImageView(context) fun setScale(value: Float) = apply { this.elasticImageView.scale = value } fun setDuration(value: Int) = apply { this.elasticImageView.duration = value } @JvmSynthetic fun setOnClickListener(block: (View) -> Unit) = apply { setOnClickListener(OnClickListener(block)) } fun setOnClickListener(value: OnClickListener) = apply { this.elasticImageView.setOnClickListener(value) } @JvmSynthetic fun setOnFinishListener(block: () -> Unit) = apply { setOnFinishListener(ElasticFinishListener(block)) } fun setOnFinishListener(value: ElasticFinishListener) = apply { this.elasticImageView.setOnFinishListener(value) } fun build() = this.elasticImageView } }
mit
6fa2f9c13b9db9f2a0291b140bdea3cd
32.05036
96
0.730083
4.760622
false
false
false
false
seratch/jslack
slack-api-model-kotlin-extension/src/main/kotlin/com/slack/api/model/kotlin_extension/block/element/MultiConversationsSelectElementBuilder.kt
1
5964
package com.slack.api.model.kotlin_extension.block.element import com.slack.api.model.block.composition.ConfirmationDialogObject import com.slack.api.model.block.composition.PlainTextObject import com.slack.api.model.block.element.ConversationsFilter import com.slack.api.model.block.element.MultiConversationsSelectElement import com.slack.api.model.kotlin_extension.block.BlockLayoutBuilder import com.slack.api.model.kotlin_extension.block.Builder import com.slack.api.model.kotlin_extension.block.composition.ConfirmationDialogObjectBuilder @BlockLayoutBuilder class MultiConversationsSelectElementBuilder : Builder<MultiConversationsSelectElement> { private var placeholder: PlainTextObject? = null private var actionId: String? = null private var initialConversations: List<String>? = null private var maxSelectedItems: Int? = null private var defaultToCurrentConversation: Boolean? = null private var filter: ConversationsFilter? = null private var confirm: ConfirmationDialogObject? = null /** * Adds a plain text object in the placeholder field. * * The placeholder text shown on the menu. Maximum length for the text in this field is 150 characters. * * @see <a href="https://api.slack.com/reference/block-kit/block-elements#conversation_multi_select">Multi conversations select element documentation</a> */ fun placeholder(text: String, emoji: Boolean? = null) { placeholder = PlainTextObject(text, emoji) } /** * An identifier for the action triggered when a menu option is selected. You can use this when you receive an * interaction payload to identify the source of the action. Should be unique among all other action_ids used * elsewhere by your app. Maximum length for this field is 255 characters. * * @see <a href="https://api.slack.com/reference/block-kit/block-elements#conversation_multi_select">Multi conversations select element documentation</a> */ fun actionId(id: String) { actionId = id } /** * An array of one or more IDs of any valid conversations to be pre-selected when the menu loads. * * @see <a href="https://api.slack.com/reference/block-kit/block-elements#conversation_multi_select">Multi conversations select element documentation</a> */ fun initialConversations(vararg conversations: String) { initialConversations = conversations.toList() } /** * Specifies the maximum number of items that can be selected in the menu. Minimum number is 1. * * @see <a href="https://api.slack.com/reference/block-kit/block-elements#conversation_multi_select">Multi conversations select element documentation</a> */ fun maxSelectedItems(items: Int) { maxSelectedItems = items } /** * Pre-populates the select menu with the conversation that the user was viewing when they opened the modal, * if available. If initial_conversations is also supplied, it will be ignored. Default is false. * * @see <a href="https://api.slack.com/reference/block-kit/block-elements#conversation_multi_select">Multi conversations select element documentation</a> */ fun defaultToCurrentConversation(defaultToCurrentConversation: Boolean) { this.defaultToCurrentConversation = defaultToCurrentConversation } /** * A filter object that reduces the list of available conversations using the specified criteria. * * This implementation uses a type-safe enum to specify the conversation types to be filtered. * * @see <a href="https://api.slack.com/reference/block-kit/block-elements#conversation_multi_select">Multi conversations select element documentation</a> */ fun filter(vararg include: ConversationType, excludeExternalSharedChannels: Boolean? = null, excludeBotUsers: Boolean? = null) { filter = ConversationsFilter.builder() .include(include.map { it.value }) .excludeExternalSharedChannels(excludeExternalSharedChannels) .excludeBotUsers(excludeBotUsers) .build() } /** * A filter object that reduces the list of available conversations using the specified criteria. * * This implementation uses strings to specify the conversation types to be filtered. This may be preferable if * a new conversation type gets introduced and the enum class is not sufficient. * * @see <a href="https://api.slack.com/reference/block-kit/block-elements#conversation_multi_select">Multi conversations select element documentation</a> */ fun filter(vararg include: String, excludeExternalSharedChannels: Boolean? = null, excludeBotUsers: Boolean? = null) { filter = ConversationsFilter.builder() .include(include.toList()) .excludeExternalSharedChannels(excludeExternalSharedChannels) .excludeBotUsers(excludeBotUsers) .build() } /** * A confirm object that defines an optional confirmation dialog that appears before the multi-select choices are * submitted. * * @see <a href="https://api.slack.com/reference/block-kit/block-elements#conversation_multi_select">Multi conversations select element documentation</a> */ fun confirm(builder: ConfirmationDialogObjectBuilder.() -> Unit) { confirm = ConfirmationDialogObjectBuilder().apply(builder).build() } override fun build(): MultiConversationsSelectElement { return MultiConversationsSelectElement.builder() .placeholder(placeholder) .actionId(actionId) .initialConversations(initialConversations) .confirm(confirm) .maxSelectedItems(maxSelectedItems) .defaultToCurrentConversation(defaultToCurrentConversation) .filter(filter) .build() } }
mit
c95ed325d3bc54ec887e8bab956c6d99
47.495935
157
0.711268
4.856678
false
false
false
false
DemonWav/MinecraftDevIntelliJ
src/main/kotlin/com/demonwav/mcdev/platform/mixin/config/reference/MixinPackage.kt
1
2404
/* * Minecraft Dev for IntelliJ * * https://minecraftdev.org * * Copyright (c) 2020 minecraft-dev * * MIT License */ package com.demonwav.mcdev.platform.mixin.config.reference import com.demonwav.mcdev.platform.mixin.util.MixinConstants.Annotations.MIXIN import com.demonwav.mcdev.util.packageName import com.demonwav.mcdev.util.reference.PackageNameReferenceProvider import com.intellij.codeInsight.lookup.LookupElementBuilder import com.intellij.psi.JavaPsiFacade import com.intellij.psi.PsiClass import com.intellij.psi.PsiElement import com.intellij.psi.PsiPackage import com.intellij.psi.search.PackageScope import com.intellij.psi.search.searches.AnnotatedElementsSearch import com.intellij.util.ArrayUtil import com.intellij.util.PlatformIcons object MixinPackage : PackageNameReferenceProvider() { override fun collectVariants(element: PsiElement, context: PsiElement?): Array<Any> { val mixinAnnotation = JavaPsiFacade.getInstance(element.project).findClass(MIXIN, element.resolveScope) ?: return ArrayUtil.EMPTY_OBJECT_ARRAY return if (context == null) { findPackages(mixinAnnotation, element) } else { findChildrenPackages(mixinAnnotation, element, context as PsiPackage) } } private fun findPackages(mixinAnnotation: PsiClass, element: PsiElement): Array<Any> { val packages = HashSet<String>() val list = ArrayList<LookupElementBuilder>() for (mixin in AnnotatedElementsSearch.searchPsiClasses(mixinAnnotation, element.resolveScope)) { val packageName = mixin.packageName ?: continue if (packages.add(packageName)) { list.add(LookupElementBuilder.create(packageName).withIcon(PlatformIcons.PACKAGE_ICON)) } val topLevelPackage = packageName.substringBefore('.') if (packages.add(topLevelPackage)) { list.add(LookupElementBuilder.create(topLevelPackage).withIcon(PlatformIcons.PACKAGE_ICON)) } } return list.toArray() } private fun findChildrenPackages(mixinAnnotation: PsiClass, element: PsiElement, context: PsiPackage): Array<Any> { val scope = PackageScope(context, true, true).intersectWith(element.resolveScope) return collectSubpackages(context, AnnotatedElementsSearch.searchPsiClasses(mixinAnnotation, scope)) } }
mit
0df7e537b6ac38c101f609d1092fd74e
38.409836
119
0.730865
4.946502
false
false
false
false
indianpoptart/RadioControl
RadioControl/app/src/main/java/com/nikhilparanjape/radiocontrol/fragments/WLANFragment.kt
1
1077
package com.nikhilparanjape.radiocontrol.fragments import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import com.nikhilparanjape.radiocontrol.R import com.nikhilparanjape.radiocontrol.adapters.RecyclerAdapter /** * Created by Nikhil on 07/31/2018. * * @author Nikhil Paranjape * * */ class WLANFragment : Fragment() { private var wlanTrouble = arrayOf("Blacklist", "Crisis", "Gotham", "Banshee", "Breaking Bad") override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { val rootView = inflater.inflate(R.layout.wlan_fragment, container, false) val rv = rootView.findViewById<RecyclerView>(R.id.wlanRV) rv.layoutManager = LinearLayoutManager(this.activity) val adapter = RecyclerAdapter(wlanTrouble) rv.adapter = adapter return rootView } }
gpl-3.0
ddd9787da28dd216131450464ae2f61b
28.108108
116
0.756732
4.360324
false
false
false
false
JetBrains/intellij-community
platform/platform-tests/testSrc/com/intellij/openapi/vfs/newvfs/persistent/VfsEventsTest.kt
1
11053
// 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.vfs.newvfs.persistent import com.intellij.openapi.Disposable import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.application.WriteAction import com.intellij.openapi.vfs.* import com.intellij.openapi.vfs.impl.jar.TimedZipHandler import com.intellij.openapi.vfs.newvfs.BulkFileListener import com.intellij.openapi.vfs.newvfs.events.VFileCreateEvent import com.intellij.openapi.vfs.newvfs.events.VFileEvent import com.intellij.testFramework.EdtRule import com.intellij.testFramework.RunsInEdt import com.intellij.testFramework.fixtures.BareTestFixtureTestCase import com.intellij.testFramework.rules.TempDirectory import com.intellij.util.FileContentUtilCore import com.intellij.util.io.zip.JBZipFile import com.intellij.util.messages.MessageBusConnection import org.junit.Assert.assertTrue import org.junit.Rule import org.junit.Test import org.junit.rules.ExternalResource import org.junit.runner.Description import org.junit.runners.model.Statement import java.io.IOException import java.nio.file.Files import java.nio.file.Path import java.util.* import java.util.concurrent.atomic.AtomicBoolean import kotlin.io.path.moveTo import kotlin.io.path.writeText import kotlin.test.assertEquals import kotlin.test.assertFalse import kotlin.test.assertTrue @RunsInEdt class VfsEventsTest : BareTestFixtureTestCase() { @JvmField @Rule val edtRule = EdtRule() @JvmField @Rule val tempDir = TempDirectory() @JvmField @Rule val useCrcRule = UseCrcRule() private fun connectToAppBus(): MessageBusConnection = ApplicationManager.getApplication().messageBus.connect(testRootDisposable) @Test fun testFireEvent() { val dir = createDir() var eventFired = false connectToAppBus().subscribe(VirtualFileManager.VFS_CHANGES, object : BulkFileListener { override fun after(events: List<VFileEvent>) { eventFired = eventFired || events.any { it is VFileCreateEvent } } }) addChild(dir, "x.txt") assertTrue(eventFired) } @Test fun testRefreshNewFile() { val vDir = createDir() val allVfsListeners = AllVfsListeners(testRootDisposable) vDir.toNioPath().resolve("added.txt").writeText("JB") vDir.syncRefresh() allVfsListeners.assertEvents(1) } @Test fun testRefreshDeletedFile() { val vDir = createDir() val file = WriteAction.computeAndWait<VirtualFile, IOException> { vDir.createChildData(this, "x.txt") } val nioFile = file.toNioPath() val allVfsListeners = AllVfsListeners(testRootDisposable) assertTrue { Files.deleteIfExists(nioFile) } vDir.syncRefresh() allVfsListeners.assertEvents(1) } @Test fun testRefreshModifiedFile() { val vDir = createDir() val file = WriteAction.computeAndWait<VirtualFile, IOException> { val child = vDir.createChildData(this, "x.txt") VfsUtil.saveText(child, "42.2") child } val nioFile = file.toNioPath() val allVfsListeners = AllVfsListeners(testRootDisposable) nioFile.writeText("21.12") vDir.syncRefresh() allVfsListeners.assertEvents(1) } @Test fun testAddedJar() = doTestAddedJar() @Test fun testRemovedJar() = doTestRemovedJar() @Test fun testMovedJar() = doTestMovedJar() @Test fun testModifiedJar() = doTestModifiedJar() @Test fun testAddedJarWithCrc() = doTestAddedJar() @Test fun testRemovedJarWithCrc() = doTestRemovedJar() @Test fun testMovedJarWithCrc() = doTestMovedJar() @Test fun testModifiedJarWithCrc() = doTestModifiedJar() @Test fun testNestedEventProcessing() { val fileForNestedMove = tempDir.newVirtualFile("to-move.txt") val nestedMoveTarget = tempDir.newVirtualDirectory("move-target") val fireMove = AtomicBoolean(false) val movePerformed = AtomicBoolean(false) // execute nested event while async refresh below connectToAppBus().subscribe(VirtualFileManager.VFS_CHANGES, object : BulkFileListener { override fun after(events: List<VFileEvent>) { if (fireMove.get() && !movePerformed.get()) { movePerformed.set(true) PersistentFS.getInstance().moveFile(this, fileForNestedMove, nestedMoveTarget) } } }) val vDir = createDir() val allVfsListeners = AllVfsListeners(testRootDisposable) fireMove.set(true) assertFalse { movePerformed.get() } // execute async refresh vDir.toNioPath().resolve("added.txt").writeText("JB") vDir.syncRefresh() allVfsListeners.assertEvents(2) } @Test fun testNestedManualEventProcessing() { val fileToReparse = tempDir.newVirtualFile("to-reparse.txt") val fireReparse = AtomicBoolean(false) val reparsePerformed = AtomicBoolean(false) // execute nested event manually via vfs changes message bus publisher connectToAppBus().subscribe(VirtualFileManager.VFS_CHANGES, object : BulkFileListener { override fun after(events: List<VFileEvent>) { if (fireReparse.get() && !reparsePerformed.get()) { reparsePerformed.set(true) FileContentUtilCore.reparseFiles(fileToReparse) } } }) val vDir = createDir() val allVfsListeners = AllVfsListeners(testRootDisposable) fireReparse.set(true) assertFalse { reparsePerformed.get() } // execute async refresh vDir.toNioPath().resolve("added.txt").writeText("JB") vDir.syncRefresh() allVfsListeners.assertEvents(2) } private fun doTestAddedJar() { val vDir = createDir() val allVfsListeners = AllVfsListeners(testRootDisposable) createJar(vDir.toNioPath()) vDir.syncRefresh() // in case of jar added we don't expect creation events for all of jar's entries. allVfsListeners.assertEvents(1) } private fun doTestRemovedJar() { val vDir = createDir() val jar = createJar(vDir.toNioPath()) vDir.syncRefresh() val allVfsListeners = AllVfsListeners(testRootDisposable) TimedZipHandler.closeOpenZipReferences() assertTrue { Files.deleteIfExists(jar) } vDir.syncRefresh() allVfsListeners.assertEvents(2) } private fun doTestMovedJar() { val vDir = createDir() val childDir1 = addChild(vDir, "childDir1", true).toNioPath() val childDir2 = addChild(vDir, "childDir2", true).toNioPath() val jar = createJar(childDir1) vDir.syncRefresh() val allVfsListeners = AllVfsListeners(testRootDisposable) TimedZipHandler.closeOpenZipReferences() jar.moveTo(childDir2.resolve(jar.fileName), true) vDir.syncRefresh() allVfsListeners.assertEvents(3) } private fun doTestModifiedJar() { val vDir = createDir() val jar = createJar(vDir.toNioPath()) vDir.syncRefresh() modifyJar(jar) val allVfsListeners = AllVfsListeners(testRootDisposable) vDir.syncRefresh() allVfsListeners.assertEvents(if(useCrcRule.useCrcForTimestamp) 3 else 4) } private fun addChild(dir: VirtualFile, name: String, directory: Boolean = false): VirtualFile { return WriteAction.computeAndWait<VirtualFile, IOException> { if (directory) { dir.createChildDirectory(this, name) } else { dir.createChildData(this, name) } } } private fun createDir(): VirtualFile { val dir = tempDir.newDirectory("vDir") val vDir = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(dir)!! vDir.children return vDir } private fun createJar(directory: Path): Path { val jarPath = directory.resolve("Test.jar") JBZipFile(jarPath.toFile()).use { it.getOrCreateEntry("awesome.txt").setData("Hello!".toByteArray(Charsets.UTF_8), 666L) it.getOrCreateEntry("readme.txt").setData("Read it!".toByteArray(Charsets.UTF_8), 777L) } var jarFileCount = 0 //ensure we have file system val virtualFile = VfsUtil.findFile(jarPath, true)!! val jarRoot = JarFileSystem.getInstance().getJarRootForLocalFile(virtualFile) VfsUtil.visitChildrenRecursively(jarRoot!!, object : VirtualFileVisitor<Any>() { override fun visitFile(file: VirtualFile): Boolean { jarFileCount++ return true } }) assertTrue("Generated jar is empty") { jarFileCount > 0 } return jarPath } private fun modifyJar(jarPath: Path) { assertTrue { Files.exists(jarPath) } JBZipFile(jarPath.toFile()).use { // modify it.getOrCreateEntry("awesome.txt").setData("Hello_modified!".toByteArray(Charsets.UTF_8), 666L) // add it.getOrCreateEntry("readme_2.txt").setData("Read it!".toByteArray(Charsets.UTF_8), 777L) } } private fun VirtualFile.syncRefresh() = refresh(false, true) private class AllVfsListeners(disposable: Disposable) { private val asyncEvents: MutableList<VFileEvent> = Collections.synchronizedList(mutableListOf()) private val bulkEvents: MutableList<VFileEvent> = mutableListOf() init { VirtualFileManager.getInstance().addAsyncFileListener( { events -> object : AsyncFileListener.ChangeApplier { override fun afterVfsChange() { asyncEvents.addAll(events) } } }, disposable) ApplicationManager.getApplication().messageBus.connect(disposable).subscribe(VirtualFileManager.VFS_CHANGES, object : BulkFileListener { override fun after(events: List<VFileEvent>) { bulkEvents.addAll(events) } }) } fun resetEvents() { asyncEvents.clear() bulkEvents.clear() } fun assertEvents(expectedEventCount: Int) { val asyncEventsSize = asyncEvents.size val bulkEventsSize = bulkEvents.size val asyncEventsToString = asyncEvents.joinToString("\n ") { it.toString() } val bulkEventsToString = bulkEvents.joinToString("\n ") { it.toString() } assertEquals(asyncEventsSize, bulkEventsSize, "Async & bulk listener events mismatch." + "\n Async events : $asyncEventsToString," + "\n Bulk events: $bulkEventsToString") assertEquals(expectedEventCount, asyncEventsSize, "Unexpected VFS event count received by async listener: $asyncEventsToString") assertEquals(asyncEvents.toSet(), bulkEvents.toSet(), "Async & bulk listener events mismatch") resetEvents() } } class UseCrcRule : ExternalResource() { var useCrcForTimestamp = false override fun apply(base: Statement, description: Description): Statement { useCrcForTimestamp = description.methodName.endsWith("WithCrc") return super.apply(base, description) } override fun before() { if (useCrcForTimestamp) { System.setProperty("zip.handler.uses.crc.instead.of.timestamp", true.toString()) } } override fun after() { if (useCrcForTimestamp) { System.setProperty("zip.handler.uses.crc.instead.of.timestamp", false.toString()) } } } }
apache-2.0
c0543f41466d1193156f3801890cdb2e
32.804281
142
0.708948
4.640218
false
true
false
false
JetBrains/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/actions/generate/KotlinGenerateEqualsAndHashcodeAction.kt
1
15321
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.actions.generate import com.intellij.codeInsight.CodeInsightSettings import com.intellij.openapi.application.runWriteAction import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import com.intellij.psi.PsiNameIdentifierOwner import com.intellij.util.IncorrectOperationException import org.jetbrains.kotlin.builtins.KotlinBuiltIns import org.jetbrains.kotlin.config.ApiVersion import org.jetbrains.kotlin.config.LanguageFeature import org.jetbrains.kotlin.descriptors.ClassDescriptor import org.jetbrains.kotlin.descriptors.FunctionDescriptor import org.jetbrains.kotlin.descriptors.Modality import org.jetbrains.kotlin.descriptors.VariableDescriptor import org.jetbrains.kotlin.idea.core.CollectingNameValidator import org.jetbrains.kotlin.idea.base.facet.platform.platform import org.jetbrains.kotlin.idea.base.fe10.codeInsight.newDeclaration.Fe10KotlinNameSuggester import org.jetbrains.kotlin.idea.base.projectStructure.languageVersionSettings import org.jetbrains.kotlin.idea.base.psi.isInlineOrValue import org.jetbrains.kotlin.idea.caches.resolve.analyzeWithContent import org.jetbrains.kotlin.idea.codeInsight.DescriptorToSourceUtilsIde import org.jetbrains.kotlin.idea.core.insertMembersAfterAndReformat import org.jetbrains.kotlin.idea.util.IdeDescriptorRenderers import org.jetbrains.kotlin.idea.util.application.isUnitTestMode import org.jetbrains.kotlin.platform.isCommon import org.jetbrains.kotlin.platform.isJs import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.hasExpectModifier import org.jetbrains.kotlin.psi.psiUtil.quoteIfNeeded import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.descriptorUtil.builtIns import org.jetbrains.kotlin.resolve.descriptorUtil.getSuperClassOrAny import org.jetbrains.kotlin.resolve.source.getPsi import org.jetbrains.kotlin.types.TypeUtils import org.jetbrains.kotlin.utils.addIfNotNull import org.jetbrains.kotlin.utils.addToStdlib.lastIsInstanceOrNull import org.jetbrains.kotlin.utils.addToStdlib.safeAs fun ClassDescriptor.findDeclaredEquals(checkSupers: Boolean): FunctionDescriptor? { return findDeclaredFunction("equals", checkSupers) { it.modality != Modality.ABSTRACT && it.valueParameters.singleOrNull()?.type == it.builtIns.nullableAnyType && it.typeParameters.isEmpty() } } fun ClassDescriptor.findDeclaredHashCode(checkSupers: Boolean): FunctionDescriptor? { return findDeclaredFunction("hashCode", checkSupers) { it.modality != Modality.ABSTRACT && it.valueParameters.isEmpty() && it.typeParameters.isEmpty() } } class KotlinGenerateEqualsAndHashcodeAction : KotlinGenerateMemberActionBase<KotlinGenerateEqualsAndHashcodeAction.Info>() { companion object { private val LOG = Logger.getInstance(KotlinGenerateEqualsAndHashcodeAction::class.java) } class Info( val needEquals: Boolean, val needHashCode: Boolean, val classDescriptor: ClassDescriptor, val variablesForEquals: List<VariableDescriptor>, val variablesForHashCode: List<VariableDescriptor> ) override fun isValidForClass(targetClass: KtClassOrObject): Boolean { return targetClass is KtClass && targetClass !is KtEnumEntry && !targetClass.isEnum() && !targetClass.isAnnotation() && !targetClass.isInterface() && !targetClass.isInlineOrValue() } override fun prepareMembersInfo(klass: KtClassOrObject, project: Project, editor: Editor?): Info? { val asClass = klass.safeAs<KtClass>() ?: return null return prepareMembersInfo(asClass, project, true) } fun prepareMembersInfo(klass: KtClass, project: Project, askDetails: Boolean): Info? { val context = klass.analyzeWithContent() val classDescriptor = context.get(BindingContext.CLASS, klass) ?: return null val equalsDescriptor = classDescriptor.findDeclaredEquals(false) val hashCodeDescriptor = classDescriptor.findDeclaredHashCode(false) var needEquals = equalsDescriptor == null var needHashCode = hashCodeDescriptor == null if (!needEquals && !needHashCode && askDetails) { if (!confirmMemberRewrite(klass, equalsDescriptor!!, hashCodeDescriptor!!)) return null runWriteAction { try { equalsDescriptor.source.getPsi()?.delete() hashCodeDescriptor.source.getPsi()?.delete() needEquals = true needHashCode = true } catch (e: IncorrectOperationException) { LOG.error(e) } } } val properties = getPropertiesToUseInGeneratedMember(klass) if (properties.isEmpty() || isUnitTestMode() || !askDetails) { val descriptors = properties.map { context[BindingContext.DECLARATION_TO_DESCRIPTOR, it] as VariableDescriptor } return Info(needEquals, needHashCode, classDescriptor, descriptors, descriptors) } return with(KotlinGenerateEqualsWizard(project, klass, properties, needEquals, needHashCode)) { if (!klass.hasExpectModifier() && !showAndGet()) return null Info(needEquals, needHashCode, classDescriptor, getPropertiesForEquals().map { context[BindingContext.DECLARATION_TO_DESCRIPTOR, it] as VariableDescriptor }, getPropertiesForHashCode().map { context[BindingContext.DECLARATION_TO_DESCRIPTOR, it] as VariableDescriptor }) } } private fun generateClassLiteralsNotEqual(paramName: String, targetClass: KtClassOrObject): String { val defaultExpression = "javaClass != $paramName?.javaClass" if (!targetClass.languageVersionSettings.supportsFeature(LanguageFeature.BoundCallableReferences)) return defaultExpression return when { targetClass.platform.isJs() -> "other == null || this::class.js != $paramName::class.js" targetClass.platform.isCommon() -> "other == null || this::class != $paramName::class" else -> defaultExpression } } private fun generateClassLiteral(targetClass: KtClassOrObject): String { val defaultExpression = "javaClass" if (!targetClass.languageVersionSettings.supportsFeature(LanguageFeature.BoundCallableReferences)) return defaultExpression return when { targetClass.platform.isJs() -> "this::class.js" targetClass.platform.isCommon() -> "this::class" else -> defaultExpression } } private fun isNestedArray(variable: VariableDescriptor) = KotlinBuiltIns.isArrayOrPrimitiveArray(variable.builtIns.getArrayElementType(variable.type)) private fun KtElement.canUseArrayContentFunctions() = languageVersionSettings.apiVersion >= ApiVersion.KOTLIN_1_1 private fun generateArraysEqualsCall( variable: VariableDescriptor, canUseContentFunctions: Boolean, arg1: String, arg2: String ): String { return if (canUseContentFunctions) { val methodName = if (isNestedArray(variable)) "contentDeepEquals" else "contentEquals" "$arg1.$methodName($arg2)" } else { val methodName = if (isNestedArray(variable)) "deepEquals" else "equals" "java.util.Arrays.$methodName($arg1, $arg2)" } } private fun generateArrayHashCodeCall( variable: VariableDescriptor, canUseContentFunctions: Boolean, argument: String ): String { return if (canUseContentFunctions) { val methodName = if (isNestedArray(variable)) "contentDeepHashCode" else "contentHashCode" val dot = if (TypeUtils.isNullableType(variable.type)) "?." else "." "$argument$dot$methodName()" } else { val methodName = if (isNestedArray(variable)) "deepHashCode" else "hashCode" "java.util.Arrays.$methodName($argument)" } } fun generateEquals(project: Project, info: Info, targetClass: KtClassOrObject): KtNamedFunction? { with(info) { if (!needEquals) return null val superEquals = classDescriptor.getSuperClassOrAny().findDeclaredEquals(true)!! val equalsFun = generateFunctionSkeleton(superEquals, targetClass) val paramName = equalsFun.valueParameters.first().name!!.quoteIfNeeded() var typeForCast = IdeDescriptorRenderers.SOURCE_CODE.renderClassifierName(classDescriptor) val typeParams = classDescriptor.declaredTypeParameters if (typeParams.isNotEmpty()) { typeForCast += typeParams.joinToString(prefix = "<", postfix = ">") { "*" } } val useIsCheck = CodeInsightSettings.getInstance().USE_INSTANCEOF_ON_EQUALS_PARAMETER val isNotInstanceCondition = if (useIsCheck) { "$paramName !is $typeForCast" } else { generateClassLiteralsNotEqual(paramName, targetClass) } val bodyText = buildString { append("if (this === $paramName) return true\n") append("if ($isNotInstanceCondition) return false\n") val builtIns = superEquals.builtIns if (!builtIns.isMemberOfAny(superEquals)) { append("if (!super.equals($paramName)) return false\n") } if (variablesForEquals.isNotEmpty()) { if (!useIsCheck) { append("\n$paramName as $typeForCast\n") } append('\n') variablesForEquals.forEach { val isNullable = TypeUtils.isNullableType(it.type) val isArray = KotlinBuiltIns.isArrayOrPrimitiveArray(it.type) val canUseArrayContentFunctions = targetClass.canUseArrayContentFunctions() val propName = (DescriptorToSourceUtilsIde.getAnyDeclaration(project, it) as PsiNameIdentifierOwner).nameIdentifier!!.text val notEquals = when { isArray -> { "!${generateArraysEqualsCall(it, canUseArrayContentFunctions, propName, "$paramName.$propName")}" } else -> { "$propName != $paramName.$propName" } } val equalsCheck = "if ($notEquals) return false\n" if (isArray && isNullable && canUseArrayContentFunctions) { append("if ($propName != null) {\n") append("if ($paramName.$propName == null) return false\n") append(equalsCheck) append("} else if ($paramName.$propName != null) return false\n") } else { append(equalsCheck) } } append('\n') } append("return true") } equalsFun.replaceBody { KtPsiFactory(project).createBlock(bodyText) } return equalsFun } } fun generateHashCode(project: Project, info: Info, targetClass: KtClassOrObject): KtNamedFunction? { fun VariableDescriptor.genVariableHashCode(parenthesesNeeded: Boolean): String { val ref = (DescriptorToSourceUtilsIde.getAnyDeclaration(project, this) as PsiNameIdentifierOwner).nameIdentifier!!.text val isNullable = TypeUtils.isNullableType(type) val builtIns = builtIns val typeClass = type.constructor.declarationDescriptor var text = when { typeClass == builtIns.byte || typeClass == builtIns.short || typeClass == builtIns.int -> ref KotlinBuiltIns.isArrayOrPrimitiveArray(type) -> { val canUseArrayContentFunctions = targetClass.canUseArrayContentFunctions() val shouldWrapInLet = isNullable && !canUseArrayContentFunctions val hashCodeArg = if (shouldWrapInLet) "it" else ref val hashCodeCall = generateArrayHashCodeCall(this, canUseArrayContentFunctions, hashCodeArg) if (shouldWrapInLet) "$ref?.let { $hashCodeCall }" else hashCodeCall } else -> if (isNullable) "$ref?.hashCode()" else "$ref.hashCode()" } if (isNullable) { text += " ?: 0" if (parenthesesNeeded) { text = "($text)" } } return text } with(info) { if (!needHashCode) return null val superHashCode = classDescriptor.getSuperClassOrAny().findDeclaredHashCode(true)!! val hashCodeFun = generateFunctionSkeleton(superHashCode, targetClass) val builtins = superHashCode.builtIns val propertyIterator = variablesForHashCode.iterator() val initialValue = when { !builtins.isMemberOfAny(superHashCode) -> "super.hashCode()" propertyIterator.hasNext() -> propertyIterator.next().genVariableHashCode(false) else -> generateClassLiteral(targetClass) + ".hashCode()" } val bodyText = if (propertyIterator.hasNext()) { val validator = CollectingNameValidator(variablesForEquals.map { it.name.asString().quoteIfNeeded() }) val resultVarName = Fe10KotlinNameSuggester.suggestNameByName("result", validator) StringBuilder().apply { append("var $resultVarName = $initialValue\n") propertyIterator.forEach { append("$resultVarName = 31 * $resultVarName + ${it.genVariableHashCode(true)}\n") } append("return $resultVarName") }.toString() } else "return $initialValue" hashCodeFun.replaceBody { KtPsiFactory(project).createBlock(bodyText) } return hashCodeFun } } override fun generateMembers(project: Project, editor: Editor?, info: Info): List<KtDeclaration> { val targetClass = info.classDescriptor.source.getPsi() as KtClass val prototypes = ArrayList<KtDeclaration>(2) .apply { addIfNotNull(generateEquals(project, info, targetClass)) addIfNotNull(generateHashCode(project, info, targetClass)) } val anchor = with(targetClass.declarations) { lastIsInstanceOrNull<KtNamedFunction>() ?: lastOrNull() } return insertMembersAfterAndReformat(editor, targetClass, prototypes, anchor) } }
apache-2.0
d1f1d2eaad56d102a12e54a049b2b579
45.853211
158
0.644214
5.527056
false
false
false
false
apollographql/apollo-android
apollo-normalized-cache-api/src/commonTest/kotlin/com/apollographql/apollo3/cache/normalized/CacheKeyResolverTest.kt
1
3610
package com.apollographql.apollo3.cache.normalized import com.apollographql.apollo3.api.CompiledField import com.apollographql.apollo3.api.CompiledListType import com.apollographql.apollo3.api.Executable import com.apollographql.apollo3.api.ObjectType import com.apollographql.apollo3.cache.normalized.CacheKeyResolverTest.Fixtures.TEST_LIST_FIELD import com.apollographql.apollo3.cache.normalized.CacheKeyResolverTest.Fixtures.TEST_SIMPLE_FIELD import com.apollographql.apollo3.cache.normalized.api.CacheKey import com.apollographql.apollo3.cache.normalized.api.CacheKeyResolver import com.apollographql.apollo3.exception.CacheMissException import kotlin.test.BeforeTest import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertFailsWith import kotlin.test.fail class CacheKeyResolverTest { private lateinit var subject: CacheKeyResolver lateinit var onCacheKeyForField: (field: CompiledField, variables: Executable.Variables) -> CacheKey? lateinit var onListOfCacheKeysForField: (field: CompiledField, variables: Executable.Variables) -> List<CacheKey?>? @BeforeTest fun setup() { subject = FakeCacheKeyResolver() onCacheKeyForField = { _, _ -> fail("Unexpected call to cacheKeyForField") } onListOfCacheKeysForField = { _, _ -> fail("Unexpected call to listOfCacheKeysForField") } } @Test fun verify_cacheKeyForField_called_for_named_composite_field() { val expectedKey = CacheKey("test") val fields = mutableListOf<CompiledField>() onCacheKeyForField = { field: CompiledField, _: Executable.Variables -> fields += field expectedKey } val returned = subject.resolveField(TEST_SIMPLE_FIELD, Executable.Variables(emptyMap()), emptyMap(), "") assertEquals(returned, expectedKey) assertEquals(fields[0], TEST_SIMPLE_FIELD) } @Test fun listOfCacheKeysForField_called_for_list_field() { val expectedKeys = listOf(CacheKey("test")) val fields = mutableListOf<CompiledField>() onListOfCacheKeysForField = { field: CompiledField, _: Executable.Variables -> fields += field expectedKeys } val returned = subject.resolveField(TEST_LIST_FIELD, Executable.Variables(emptyMap()), emptyMap(), "") assertEquals(returned, expectedKeys) assertEquals(fields[0], TEST_LIST_FIELD) } @Test fun super_called_for_null_return_values() { onCacheKeyForField = { _, _ -> null } onListOfCacheKeysForField = { _, _ -> null } // The best way to ensure that super was called is to check for a cache miss exception from CacheResolver() assertFailsWith<CacheMissException> { subject.resolveField(TEST_SIMPLE_FIELD, Executable.Variables(emptyMap()), emptyMap(), "") } assertFailsWith<CacheMissException> { subject.resolveField(TEST_LIST_FIELD, Executable.Variables(emptyMap()), emptyMap(), "") } } inner class FakeCacheKeyResolver : CacheKeyResolver() { override fun cacheKeyForField(field: CompiledField, variables: Executable.Variables): CacheKey? { return onCacheKeyForField(field, variables) } override fun listOfCacheKeysForField(field: CompiledField, variables: Executable.Variables): List<CacheKey?>? { return onListOfCacheKeysForField(field, variables) } } object Fixtures { private val TEST_TYPE = ObjectType(name = "Test", keyFields = listOf("id")) val TEST_SIMPLE_FIELD = CompiledField.Builder(name = "test", type = TEST_TYPE).build() val TEST_LIST_FIELD = CompiledField.Builder(name = "testList", type = CompiledListType(ofType = TEST_TYPE)).build() } }
mit
83cf994e320ade492dfd2d672b88df03
34.742574
119
0.742105
4.592875
false
true
false
false
JetBrains/intellij-community
plugins/kotlin/base/code-insight/src/org/jetbrains/kotlin/idea/base/codeInsight/KotlinPsiElementMemberChooserObject.kt
1
4631
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.kotlin.idea.base.codeInsight import com.intellij.codeInsight.generation.* import com.intellij.openapi.application.ReadAction import com.intellij.openapi.util.Iconable import com.intellij.openapi.util.NlsContexts import com.intellij.openapi.util.NlsSafe import com.intellij.psi.* import com.intellij.psi.util.PsiFormatUtil import com.intellij.psi.util.PsiFormatUtilBase import com.intellij.util.concurrency.AppExecutorUtil import org.jetbrains.kotlin.analysis.api.KtAnalysisSession import org.jetbrains.kotlin.analysis.api.analyze import org.jetbrains.kotlin.analysis.api.renderer.declarations.impl.KtDeclarationRendererForSource import org.jetbrains.kotlin.analysis.api.renderer.declarations.modifiers.renderers.KtRendererModifierFilter import org.jetbrains.kotlin.analysis.api.symbols.KtClassOrObjectSymbol import org.jetbrains.kotlin.analysis.api.symbols.KtDeclarationSymbol import org.jetbrains.kotlin.analysis.api.symbols.KtSymbol import org.jetbrains.kotlin.idea.base.codeInsight.KotlinIconProvider.getIconFor import org.jetbrains.kotlin.idea.core.KotlinPluginDisposable import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.getParentOfTypes import javax.swing.Icon class KotlinPsiElementMemberChooserObject( psiElement: KtElement, @NlsContexts.Label text: String, icon: Icon? ) : PsiElementMemberChooserObject(psiElement, text, icon), ClassMemberWithElement { override fun getParentNodeDelegate(): MemberChooserObject { val containingDeclaration = element.getParentOfTypes<KtElement>(strict = true, KtNamedDeclaration::class.java, KtFile::class.java)!! return ReadAction.nonBlocking<PsiElementMemberChooserObject> { getMemberChooserObject(containingDeclaration) } .expireWith(KotlinPluginDisposable.getInstance(containingDeclaration.project)) .submit(AppExecutorUtil.getAppExecutorService()) .get() } override fun getElement(): KtElement = psiElement as KtElement companion object { private val renderer = KtDeclarationRendererForSource.WITH_SHORT_NAMES.with { modifiersRenderer = modifiersRenderer.with { modifierFilter = KtRendererModifierFilter.NONE } } @JvmStatic fun getKotlinMemberChooserObject(declaration: KtDeclaration): KotlinPsiElementMemberChooserObject { return analyze(declaration) { val symbol = declaration.getSymbol() val text = getChooserText(symbol) val icon = getChooserIcon(declaration, symbol) KotlinPsiElementMemberChooserObject(declaration, text, icon) } } @JvmStatic fun getMemberChooserObject(declaration: PsiElement): PsiElementMemberChooserObject { return when (declaration) { is KtFile -> PsiElementMemberChooserObject(declaration, declaration.name) is KtDeclaration -> getKotlinMemberChooserObject(declaration) is PsiField -> PsiFieldMember(declaration) is PsiMethod -> PsiMethodMember(declaration) is PsiClass -> { val text = PsiFormatUtil.formatClass(declaration, PsiFormatUtilBase.SHOW_NAME or PsiFormatUtilBase.SHOW_FQ_NAME) PsiDocCommentOwnerMemberChooserObject(declaration, text, declaration.getIcon(0)) } else -> { val name = (declaration as? PsiNamedElement)?.name ?: "<No name>" PsiElementMemberChooserObject(declaration, name) } } } private fun KtAnalysisSession.getChooserText(symbol: KtSymbol): @NlsSafe String { if (symbol is KtClassOrObjectSymbol) { val classId = symbol.classIdIfNonLocal if (classId != null) { return classId.asFqNameString() } } if (symbol is KtDeclarationSymbol) { return symbol.render(renderer) } return "" } private fun KtAnalysisSession.getChooserIcon(element: PsiElement, symbol: KtSymbol): Icon? { val isClass = element is KtClass || element is PsiClass val flags = if (isClass) 0 else Iconable.ICON_FLAG_VISIBILITY return when (element) { is KtDeclaration -> getIconFor(symbol) else -> element.getIcon(flags) } } } }
apache-2.0
4060b46ad261147c896a0bfee325e4a8
44.411765
140
0.692075
5.473995
false
false
false
false
apollographql/apollo-android
tests/websockets/src/jvmTest/kotlin/WebSocketErrorsTest.kt
1
6830
import app.cash.turbine.test import com.apollographql.apollo.sample.server.DefaultApplication import com.apollographql.apollo3.ApolloClient import com.apollographql.apollo3.exception.ApolloNetworkException import com.apollographql.apollo3.exception.ApolloWebSocketClosedException import com.apollographql.apollo3.network.ws.SubscriptionWsProtocol import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.async import kotlinx.coroutines.delay import kotlinx.coroutines.flow.catch import kotlinx.coroutines.flow.map import kotlinx.coroutines.flow.toList import kotlinx.coroutines.launch import kotlinx.coroutines.runBlocking import org.junit.AfterClass import org.junit.BeforeClass import org.junit.Test import org.springframework.boot.runApplication import org.springframework.context.ConfigurableApplicationContext import sample.server.CloseSocketQuery import sample.server.CountSubscription import sample.server.OperationErrorSubscription import sample.server.TimeSubscription import java.util.concurrent.Executors import kotlin.coroutines.EmptyCoroutineContext import kotlin.test.assertEquals import kotlin.test.assertIs import kotlin.test.assertTrue class WebSocketErrorsTest { companion object { private lateinit var context: ConfigurableApplicationContext @BeforeClass @JvmStatic fun beforeClass() { context = runApplication<DefaultApplication>() } @AfterClass @JvmStatic fun afterClass() { context.close() } } @Test fun connectionErrorThrows() = runBlocking { val apolloClient = ApolloClient.Builder() .serverUrl("http://localhost:8080/subscriptions") .wsProtocol( SubscriptionWsProtocol.Factory( connectionPayload = { mapOf("return" to "error") } ) ) .build() apolloClient.subscription(TimeSubscription()) .toFlow() .test { val error = awaitError() assertIs<ApolloNetworkException>(error) assertTrue(error.cause?.message?.contains("Connection error") == true) } apolloClient.dispose() } @Test fun socketClosedThrows() = runBlocking { val apolloClient = ApolloClient.Builder() .serverUrl("http://localhost:8080/subscriptions") .wsProtocol( SubscriptionWsProtocol.Factory( // Not all codes are valid. See RFC-6455 // https://datatracker.ietf.org/doc/html/rfc6455#section-7.4.2 connectionPayload = { mapOf("return" to "close(3666)") } ) ) .build() apolloClient.subscription(TimeSubscription()) .toFlow() .test { val error = awaitError() assertIs<ApolloNetworkException>(error) assertTrue(error.cause?.message?.contains("WebSocket Closed code='3666'") == true) } apolloClient.dispose() } @Test fun socketReconnectsAfterAnError() = runBlocking { var connectionInitCount = 0 var exception: Throwable? = null val apolloClient = ApolloClient.Builder() .httpServerUrl("http://localhost:8080/graphql") .webSocketServerUrl("http://localhost:8080/subscriptions") .wsProtocol( SubscriptionWsProtocol.Factory( connectionPayload = { connectionInitCount++ mapOf("return" to "success") } ) ) .webSocketReconnectWhen { exception = it // Only retry once connectionInitCount == 1 } .build() val items = async { apolloClient.subscription(CountSubscription(2, 500)) .toFlow() .map { it.dataAssertNoErrors.count } .toList() } /** * The timings in the sample-server are a bit weird. It takes 500ms for the query to reach the * backend code during which the subscription code hasn't started yet and then suddendly starts * just as the WebSocket is going to be closed. If that ever happen to be an issue in CI or in * another place, relaxing the timings should be ok * * 1639070973776: wait... * 1639070973986: triggering an error * 1639070974311: closing session... * 1639070974326: emitting 0 * 1639070974353: session closed. * 1639070974373: emitting 0 * 1639070974877: emitting 1 */ println("${System.currentTimeMillis()}: wait...") delay(200) println("${System.currentTimeMillis()}: triggering an error") // Trigger an error val response = apolloClient.query(CloseSocketQuery()).execute() assertEquals(response.dataAssertNoErrors.closeWebSocket, "Closed 1 session(s)") /** * The subscription should be restarted and complete successfully the second time */ assertEquals(listOf(0, 0, 1), items.await()) assertEquals(2, connectionInitCount) assertIs<ApolloWebSocketClosedException>(exception) assertEquals(1011, (exception as ApolloWebSocketClosedException).code) apolloClient.dispose() } @Test fun disposingTheClientClosesTheWebSocket() = runBlocking { var apolloClient = ApolloClient.Builder() .httpServerUrl("http://localhost:8080/graphql") .webSocketServerUrl("http://localhost:8080/subscriptions") .build() apolloClient.subscription(CountSubscription(2, 0)) .toFlow() .test { awaitItem() awaitItem() awaitComplete() } println("dispose") apolloClient.dispose() apolloClient = ApolloClient.Builder() .httpServerUrl("http://localhost:8080/graphql") .webSocketServerUrl("http://localhost:8080/subscriptions") .build() delay(1000) val response = apolloClient.query(CloseSocketQuery()).execute() println(response.dataAssertNoErrors) } @Test fun flowThrowsIfNoReconnect() = runBlocking { val apolloClient = ApolloClient.Builder() .httpServerUrl("http://localhost:8080/graphql") .webSocketServerUrl("http://localhost:8080/subscriptions") .wsProtocol( SubscriptionWsProtocol.Factory( connectionPayload = { mapOf("return" to "success") } ) ) .build() launch { delay(200) apolloClient.query(CloseSocketQuery()).execute() } apolloClient.subscription(CountSubscription(2, 500)) .toFlow() .map { it.dataAssertNoErrors.count } .test { awaitItem() val exception = awaitError() assertIs<ApolloNetworkException>(exception) val cause = exception.cause assertIs<ApolloWebSocketClosedException>(cause) assertEquals(1011, cause.code) } apolloClient.dispose() } }
mit
944f555cddbde16963c3ea2a9af35f24
29.495536
99
0.660469
4.906609
false
true
false
false
spacecowboy/Feeder
app/src/main/java/com/nononsenseapps/feeder/sync/Moshi.kt
1
892
package com.nononsenseapps.feeder.sync import com.squareup.moshi.FromJson import com.squareup.moshi.JsonAdapter import com.squareup.moshi.Moshi import com.squareup.moshi.ToJson import com.squareup.moshi.kotlin.reflect.KotlinJsonAdapterFactory import java.net.URL import org.threeten.bp.Instant fun getMoshi(): Moshi = Moshi.Builder() .add(InstantAdapter()) .add(URLAdapter()) .addLast(KotlinJsonAdapterFactory()) .build() class InstantAdapter { @ToJson fun toJSon(value: Instant): Long = value.toEpochMilli() @FromJson fun fromJson(value: Long): Instant = Instant.ofEpochMilli(value) } class URLAdapter { @ToJson fun toJSon(value: URL): String = value.toString() @FromJson fun fromJson(value: String): URL = URL(value) } inline fun <reified T> Moshi.adapter(): JsonAdapter<T> = adapter(T::class.java)
gpl-3.0
54067fbffeda54bb7e9c583050d73617
22.473684
65
0.705157
3.895197
false
false
false
false
chrislo27/RhythmHeavenRemixEditor2
core/src/main/kotlin/io/github/chrislo27/rhre3/screen/PatternDeleteScreen.kt
2
2961
package io.github.chrislo27.rhre3.screen import com.badlogic.gdx.Screen import com.badlogic.gdx.graphics.Color import com.badlogic.gdx.graphics.Texture import com.badlogic.gdx.graphics.g2d.TextureRegion import io.github.chrislo27.rhre3.RHRE3Application import io.github.chrislo27.rhre3.editor.Editor import io.github.chrislo27.rhre3.patternstorage.FileStoredPattern import io.github.chrislo27.rhre3.patternstorage.PatternStorage import io.github.chrislo27.rhre3.stage.GenericStage import io.github.chrislo27.toolboks.ToolboksScreen import io.github.chrislo27.toolboks.registry.AssetRegistry import io.github.chrislo27.toolboks.registry.ScreenRegistry import io.github.chrislo27.toolboks.ui.Button import io.github.chrislo27.toolboks.ui.TextLabel class PatternDeleteScreen(main: RHRE3Application, val editor: Editor, val pattern: FileStoredPattern, val lastScreen: Screen?) : ToolboksScreen<RHRE3Application, PatternDeleteScreen>(main) { override val stage: GenericStage<PatternDeleteScreen> = GenericStage(main.uiPalette, null, main.defaultCamera) private val button: Button<PatternDeleteScreen> init { stage.titleLabel.text = "screen.patternStore.delete.title" stage.titleIcon.image = TextureRegion(AssetRegistry.get<Texture>("ui_icon_pattern_delete")) stage.backButton.visible = true stage.onBackButtonClick = { main.screen = lastScreen ?: ScreenRegistry["editor"] } val palette = main.uiPalette stage.centreStage.elements += TextLabel(palette, stage.centreStage, stage.centreStage).apply { this.isLocalizationKey = true this.text = "screen.patternStore.delete.confirmation" this.textWrapping = true this.location.set(screenY = 0.5f, screenHeight = 0.25f) } stage.centreStage.elements += TextLabel(palette, stage.centreStage, stage.centreStage).apply { this.isLocalizationKey = false this.textColor = Color.LIGHT_GRAY this.text = pattern.name this.textWrapping = false this.location.set(screenY = 0.25f, screenHeight = 0.25f) } button = Button(palette.copy(highlightedBackColor = Color(1f, 0f, 0f, 0.5f), clickedBackColor = Color(1f, 0.5f, 0.5f, 0.5f)), stage.bottomStage, stage.bottomStage).apply { this.location.set(screenX = 0.25f, screenWidth = 0.5f) this.addLabel(TextLabel(palette, this, this.stage).apply { this.isLocalizationKey = true this.text = "screen.patternStore.delete.button" }) this.leftClickAction = { _, _ -> PatternStorage.deletePattern(pattern).persist() editor.stage.updateSelected() main.screen = ScreenRegistry["editor"] } } stage.bottomStage.elements += button } override fun tickUpdate() { } override fun dispose() { } }
gpl-3.0
c7d866cb8ca7f46d0226fd0f235429cb
40.704225
179
0.694022
4.147059
false
false
false
false
exercism/xkotlin
exercises/practice/triangle/.meta/src/reference/kotlin/Triangle.kt
1
591
class Triangle<out T: Number>(val a: T, val b: T, val c: T) { init { require(a > 0 && b > 0 && c > 0) { "Sides must be > 0" } require(a + b >= c && b + c >= a && c + a >= b) { "Sides must satisfy triangle inequality" } } val isEquilateral = a == b && b == c val isIsosceles = a == b || b == c || c == a val isScalene = !isIsosceles private infix operator fun <T: Number> T.compareTo(other: T): Int = this.toDouble().compareTo(other.toDouble()) private infix operator fun <T: Number> T.plus(b: T): Double = this.toDouble().plus(b.toDouble()) }
mit
f68228cacf05795396e893f3dc4def58
38.4
115
0.560068
3.046392
false
false
false
false
allotria/intellij-community
python/python-terminal/src/com/jetbrains/python/sdk/PyVirtualEnvTerminalCustomizer.kt
1
4337
// 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.jetbrains.python.sdk import com.intellij.openapi.components.PersistentStateComponent import com.intellij.openapi.components.ServiceManager import com.intellij.openapi.components.State import com.intellij.openapi.components.Storage import com.intellij.openapi.module.ModuleManager import com.intellij.openapi.options.UnnamedConfigurable import com.intellij.openapi.project.Project import com.intellij.openapi.projectRoots.Sdk import com.intellij.openapi.util.SystemInfo import com.jetbrains.python.run.findActivateScript import org.jetbrains.plugins.terminal.LocalTerminalCustomizer import org.jetbrains.plugins.terminal.TerminalOptionsProvider import java.io.File import javax.swing.JCheckBox class PyVirtualEnvTerminalCustomizer : LocalTerminalCustomizer() { override fun customizeCommandAndEnvironment(project: Project, command: Array<out String>, envs: MutableMap<String, String>): Array<out String> { val sdk: Sdk? = findSdk(project) if (sdk != null && (PythonSdkUtil.isVirtualEnv(sdk) || PythonSdkUtil.isConda(sdk)) && PyVirtualEnvTerminalSettings.getInstance(project).virtualEnvActivate) { // in case of virtualenv sdk on unix we activate virtualenv val path = sdk.homePath if (path != null && command.isNotEmpty()) { val shellPath = command[0] if (isShellIntegrationAvailable(shellPath)) { //fish shell works only for virtualenv and not for conda //for bash we pass activate script to jediterm shell integration (see jediterm-bash.in) to source it there //TODO: fix conda for fish findActivateScript(path, shellPath)?.let { activate -> envs.put("JEDITERM_SOURCE", activate.first) envs.put("JEDITERM_SOURCE_ARGS", activate.second?:"") } } else { //for other shells we read envs from activate script by the default shell and pass them to the process envs.putAll(PySdkUtil.activateVirtualEnv(sdk)) } } } return command } private fun isShellIntegrationAvailable(shellPath: String) : Boolean { if (TerminalOptionsProvider.instance.shellIntegration()) { val shellName = File(shellPath).name return shellName == "bash" || (SystemInfo.isMac && shellName == "sh") || shellName == "zsh" || shellName == "fish" } return false } private fun findSdk(project: Project): Sdk? { for (m in ModuleManager.getInstance(project).modules) { val sdk: Sdk? = PythonSdkUtil.findPythonSdk(m) if (sdk != null && !PythonSdkUtil.isRemote(sdk)) { return sdk } } return null } override fun getDefaultFolder(project: Project): String? { return null } override fun getConfigurable(project: Project): UnnamedConfigurable = object : UnnamedConfigurable { val settings = PyVirtualEnvTerminalSettings.getInstance(project) var myCheckbox: JCheckBox = JCheckBox(PyTerminalBundle.message("activate.virtualenv.checkbox.text")) override fun createComponent() = myCheckbox override fun isModified() = myCheckbox.isSelected != settings.virtualEnvActivate override fun apply() { settings.virtualEnvActivate = myCheckbox.isSelected } override fun reset() { myCheckbox.isSelected = settings.virtualEnvActivate } } } class SettingsState { var virtualEnvActivate: Boolean = true } @State(name = "PyVirtualEnvTerminalCustomizer", storages = [(Storage("python-terminal.xml"))]) class PyVirtualEnvTerminalSettings : PersistentStateComponent<SettingsState> { var myState: SettingsState = SettingsState() var virtualEnvActivate: Boolean get() = myState.virtualEnvActivate set(value) { myState.virtualEnvActivate = value } override fun getState(): SettingsState = myState override fun loadState(state: SettingsState) { myState.virtualEnvActivate = state.virtualEnvActivate } companion object { fun getInstance(project: Project): PyVirtualEnvTerminalSettings { return ServiceManager.getService(project, PyVirtualEnvTerminalSettings::class.java) } } }
apache-2.0
4730ef8bcda514ef9ec705ac95098563
33.975806
140
0.711552
4.862108
false
false
false
false
allotria/intellij-community
plugins/gradle/java/src/service/resolve/GradleTaskProperty.kt
4
1609
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.plugins.gradle.service.resolve import com.intellij.codeInsight.javadoc.JavaDocInfoGenerator.generateType import com.intellij.ide.presentation.Presentation import com.intellij.openapi.util.Key import com.intellij.psi.OriginInfoAwareElement import com.intellij.psi.PsiElement import com.intellij.util.lazyPub import icons.ExternalSystemIcons import org.jetbrains.plugins.gradle.settings.GradleExtensionsSettings.GradleTask import org.jetbrains.plugins.groovy.dsl.holders.NonCodeMembersHolder.DOCUMENTATION import org.jetbrains.plugins.groovy.lang.resolve.api.LazyTypeProperty import javax.swing.Icon @Presentation(typeName = "Gradle Task") class GradleTaskProperty( val task: GradleTask, context: PsiElement ) : LazyTypeProperty(task.name, task.typeFqn, context), OriginInfoAwareElement { override fun getIcon(flags: Int): Icon? = ExternalSystemIcons.Task override fun getOriginInfo(): String? = "task" private val doc by lazyPub { val result = StringBuilder() result.append("<PRE>") generateType(result, propertyType, myContext, true) result.append(" " + task.name) result.append("</PRE>") task.description?.let(result::append) result.toString() } override fun <T : Any?> getUserData(key: Key<T>): T? { if (key == DOCUMENTATION) { @Suppress("UNCHECKED_CAST") return doc as T } return super.getUserData(key) } override fun toString(): String = "Gradle Task: $name" }
apache-2.0
e470d03dcb87617448226a9668cc28f0
33.978261
140
0.759478
4.073418
false
false
false
false
JetBrains/teamcity-dnx-plugin
plugin-dotnet-server/src/test/kotlin/jetbrains/buildServer/dotnet/test/ProjectTypeSelectorTest.kt
1
3456
package jetbrains.buildServer.dotnet.test import jetbrains.buildServer.dotnet.discovery.Project import jetbrains.buildServer.dotnet.discovery.ProjectType import jetbrains.buildServer.dotnet.discovery.ProjectTypeSelectorImpl import jetbrains.buildServer.dotnet.discovery.Reference import org.testng.Assert import org.testng.annotations.DataProvider import org.testng.annotations.Test class ProjectTypeSelectorTest { @DataProvider fun testData(): Array<Array<Any>> { return arrayOf( // Test arrayOf(create(false, "Microsoft.NET.Test.Sdk"), setOf(ProjectType.Test)), arrayOf(create(false, "microsofT.net.test.SDK"), setOf(ProjectType.Test)), arrayOf(create(false, "Microsoft.NET.Test.Sdk", "abc"), setOf(ProjectType.Test)), arrayOf(create(false, "abc.Microsoft.NET.Test.Sdk"), setOf(ProjectType.Unknown)), arrayOf(create(false, "abcMicrosoft.NET.Test.Sdk"), setOf(ProjectType.Unknown)), arrayOf(create(false, "Microsoft.NET.Test.Sdk.abc"), setOf(ProjectType.Unknown)), arrayOf(create(false, "Microsoft.NET.Test.Sdkabc"), setOf(ProjectType.Unknown)), arrayOf(create(false, "Microsoft.NET.Test.Sdkรพ"), setOf(ProjectType.Unknown)), arrayOf(create(false, "abc.Microsoft.NET.Test.Sdk.abc"), setOf(ProjectType.Unknown)), arrayOf(create(false, "abcMicrosoft.NET.Test.Sdkabc"), setOf(ProjectType.Unknown)), arrayOf(create(false, ".Microsoft.NET.Test."), setOf(ProjectType.Unknown)), // Publish arrayOf(create(false, "Microsoft.aspnet.Abc"), setOf(ProjectType.Publish)), arrayOf(create(false, "Microsoft.ASPNET.Abc"), setOf(ProjectType.Publish)), arrayOf(create(false, "Microsoft.aspnet.Abc", "abc"), setOf(ProjectType.Publish)), arrayOf(create(false, "Microsoft.aspnet."), setOf(ProjectType.Publish)), arrayOf(create(true, "Microsoft.aspnet.Abc"), setOf(ProjectType.Publish)), arrayOf(create(true), setOf(ProjectType.Publish)), arrayOf(create(false, "Microsoft.aspnet."), setOf(ProjectType.Publish)), arrayOf(create(false, ".Microsoft.aspnet.abc"), setOf(ProjectType.Unknown)), arrayOf(create(false, "abc.Microsoft.aspnet.abc"), setOf(ProjectType.Unknown)), arrayOf(create(false, "abcMicrosoft.aspnetabc"), setOf(ProjectType.Unknown)), // Mixed arrayOf(create(true, "Microsoft.NET.Test.Sdk", "abc"), setOf(ProjectType.Publish, ProjectType.Test)), // Empty arrayOf(create(false, "abc"), setOf(ProjectType.Unknown)), arrayOf(create(), setOf(ProjectType.Unknown))) } @Test(dataProvider = "testData") fun shouldSelectProjectTypes(project: Project, expectedProjectTypes: Set<ProjectType>) { // Given val projectTypeSelector = ProjectTypeSelectorImpl() // When val actualProjectTypes = projectTypeSelector.select(project) // Then Assert.assertEquals(actualProjectTypes, expectedProjectTypes) } private fun create(generatePackageOnBuild: Boolean = false, vararg references: String): Project = Project("abc.proj", emptyList(), emptyList(), emptyList(), references.map { Reference(it) }, emptyList(), generatePackageOnBuild) }
apache-2.0
8a416379973a102e3d30d5cee47e1711
57.59322
141
0.661169
4.559367
false
true
false
false
romannurik/muzei
legacy-standalone/src/main/java/com/google/android/apps/muzei/legacy/SourceDao.kt
2
2709
/* * Copyright 2017 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.muzei.legacy import android.content.ComponentName import androidx.room.Dao import androidx.room.Delete import androidx.room.Insert import androidx.room.Query import androidx.room.TypeConverters import androidx.room.Update import kotlinx.coroutines.flow.Flow /** * Dao for Sources */ @Dao abstract class SourceDao { @get:Query("SELECT * FROM sources") abstract val sources: Flow<List<Source>> @Query("SELECT * FROM sources") abstract suspend fun getSources(): List<Source> @TypeConverters(ComponentNameTypeConverter::class) @Query("SELECT component_name FROM sources") abstract suspend fun getSourceComponentNames(): List<ComponentName> @get:Query("SELECT * FROM sources WHERE selected=1 ORDER BY component_name") abstract val currentSource: Flow<Source?> @get:Query("SELECT * FROM sources WHERE selected=1 ORDER BY component_name") abstract val currentSourceBlocking: Source? @Query("SELECT * FROM sources WHERE selected=1 ORDER BY component_name") abstract suspend fun getCurrentSource(): Source? @Query("SELECT * FROM sources WHERE selected=1 AND wantsNetworkAvailable=1") abstract suspend fun getCurrentSourcesThatWantNetwork(): List<Source> @Insert abstract suspend fun insert(source: Source) @TypeConverters(ComponentNameTypeConverter::class) @Query("SELECT component_name FROM sources WHERE component_name LIKE :packageName || '%'") abstract suspend fun getSourcesComponentNamesByPackageName(packageName: String): List<ComponentName> @TypeConverters(ComponentNameTypeConverter::class) @Query("SELECT * FROM sources WHERE component_name = :componentName") abstract suspend fun getSourceByComponentName(componentName: ComponentName): Source? @Update abstract suspend fun update(source: Source) @Delete abstract suspend fun delete(source: Source) @TypeConverters(ComponentNameTypeConverter::class) @Query("DELETE FROM sources WHERE component_name IN (:componentNames)") abstract suspend fun deleteAll(componentNames: Array<ComponentName>) }
apache-2.0
7c8c87c1bd4d791eccf4336b126eafcd
34.644737
104
0.755999
4.638699
false
false
false
false
benoitletondor/EasyBudget
Android/EasyBudget/app/src/main/java/com/benoitletondor/easybudgetapp/EasyBudget.kt
1
15940
/* * Copyright 2022 Benoit LETONDOR * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.benoitletondor.easybudgetapp import android.app.* import android.content.Intent import android.os.Build import android.os.Bundle import androidx.appcompat.app.AppCompatDelegate import androidx.core.app.ActivityCompat import androidx.core.content.ContextCompat import androidx.hilt.work.HiltWorkerFactory import androidx.work.Configuration import com.batch.android.Batch import com.batch.android.BatchActivityLifecycleHelper import com.batch.android.BatchNotificationChannelsManager.DEFAULT_CHANNEL_ID import com.batch.android.Config import com.batch.android.PushNotificationType import com.benoitletondor.easybudgetapp.db.DB import com.benoitletondor.easybudgetapp.helper.* import com.benoitletondor.easybudgetapp.iab.Iab import com.benoitletondor.easybudgetapp.notif.* import com.benoitletondor.easybudgetapp.parameters.* import com.benoitletondor.easybudgetapp.push.PushService.Companion.DAILY_REMINDER_KEY import com.benoitletondor.easybudgetapp.push.PushService.Companion.MONTHLY_REMINDER_KEY import com.benoitletondor.easybudgetapp.view.main.MainActivity import com.benoitletondor.easybudgetapp.view.RatingPopup import com.benoitletondor.easybudgetapp.view.settings.SettingsActivity import com.benoitletondor.easybudgetapp.view.getRatingPopupUserStep import com.google.android.material.dialog.MaterialAlertDialogBuilder import com.google.firebase.crashlytics.FirebaseCrashlytics import dagger.hilt.android.HiltAndroidApp import kotlinx.coroutines.runBlocking import java.util.* import javax.inject.Inject /** * EasyBudget application. Implements GA tracking, Batch set-up, Crashlytics set-up && iab. * * @author Benoit LETONDOR */ @HiltAndroidApp class EasyBudget : Application(), Configuration.Provider { @Inject lateinit var iab: Iab @Inject lateinit var parameters: Parameters @Inject lateinit var db: DB @Inject lateinit var workerFactory: HiltWorkerFactory // ------------------------------------------> override fun onCreate() { super.onCreate() // Init actions init() // Crashlytics if ( BuildConfig.CRASHLYTICS_ACTIVATED ) { FirebaseCrashlytics.getInstance().setCrashlyticsCollectionEnabled(true) parameters.getLocalId()?.let { FirebaseCrashlytics.getInstance().setUserId(it) } } else { FirebaseCrashlytics.getInstance().setCrashlyticsCollectionEnabled(false) } // Check if an update occurred and perform action if needed checkUpdateAction() // Ensure DB is created and reset init date if needed db.run { ensureDBCreated() // FIXME this should be done on restore, change that for the whole parameters restoration if( parameters.getShouldResetInitDate() ) { runBlocking { getOldestExpense() }?.let { expense -> parameters.setInitDate(expense.date.toStartOfDayDate()) } parameters.setShouldResetInitDate(false) } } // Batch setUpBatchSDK() // Setup theme AppCompatDelegate.setDefaultNightMode(parameters.getTheme().toPlatformValue()) } override fun getWorkManagerConfiguration() = Configuration.Builder() .setWorkerFactory(workerFactory) .build() /** * Init app const and parameters * * DO NOT USE LOGGER HERE */ private fun init() { /* * Save first launch date if needed */ val initDate = parameters.getInitDate() if (initDate == null) { parameters.setInitDate(Date()) // Set a default currency before onboarding val currency = try { Currency.getInstance(Locale.getDefault()) } catch (e: Exception) { Currency.getInstance("USD") } parameters.setUserCurrency(currency) } /* * Create local ID if needed */ var localId = parameters.getLocalId() if (localId == null) { localId = UUID.randomUUID().toString() parameters.setLocalId(localId) } // Activity counter for app foreground & background registerActivityLifecycleCallbacks(object : ActivityLifecycleCallbacks { private var activityCounter = 0 override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) {} override fun onActivityStarted(activity: Activity) { if (activityCounter == 0) { onAppForeground(activity) } activityCounter++ } override fun onActivityResumed(activity: Activity) {} override fun onActivityPaused(activity: Activity) {} override fun onActivityStopped(activity: Activity) { if (activityCounter == 1) { onAppBackground() } activityCounter-- } override fun onActivitySaveInstanceState(activity: Activity, outState: Bundle) {} override fun onActivityDestroyed(activity: Activity) {} }) } /** * Show the rating popup if the user didn't asked not to every day after the app has been open * in 3 different days. */ private fun showRatingPopupIfNeeded(activity: Activity) { try { if (activity !is MainActivity) { Logger.debug("Not showing rating popup cause app is not opened by the MainActivity") return } val dailyOpens = parameters.getNumberOfDailyOpen() if (dailyOpens > 2) { if (!hasRatingPopupBeenShownToday()) { val shown = RatingPopup(activity, parameters).show(false) if (shown) { parameters.setRatingPopupLastAutoShowTimestamp(Date().time) } } } } catch (e: Exception) { Logger.error("Error while showing rating popup", e) } } private fun showPremiumPopupIfNeeded(activity: Activity) { try { if (activity !is MainActivity) { return } if ( parameters.hasPremiumPopupBeenShow() ) { return } if ( iab.isUserPremium() ) { return } if ( !parameters.hasUserCompleteRating() ) { return } val currentStep = parameters.getRatingPopupUserStep() if (currentStep == RatingPopup.RatingPopupStep.STEP_LIKE || currentStep == RatingPopup.RatingPopupStep.STEP_LIKE_NOT_RATED || currentStep == RatingPopup.RatingPopupStep.STEP_LIKE_RATED) { if ( !hasRatingPopupBeenShownToday() && shouldShowPremiumPopup() ) { parameters.setPremiumPopupLastAutoShowTimestamp(Date().time) MaterialAlertDialogBuilder(activity) .setTitle(R.string.premium_popup_become_title) .setMessage(R.string.premium_popup_become_message) .setPositiveButton(R.string.premium_popup_become_cta) { dialog13, _ -> val startIntent = Intent(activity, SettingsActivity::class.java) startIntent.putExtra(SettingsActivity.SHOW_PREMIUM_INTENT_KEY, true) ActivityCompat.startActivity(activity, startIntent, null) dialog13.dismiss() } .setNegativeButton(R.string.premium_popup_become_not_now) { dialog12, _ -> dialog12.dismiss() } .setNeutralButton(R.string.premium_popup_become_not_ask_again) { dialog1, _ -> parameters.setPremiumPopupShown() dialog1.dismiss() } .show() .centerButtons() } } } catch (e: Exception) { Logger.error("Error while showing become premium popup", e) } } /** * Has the rating popup been shown automatically today * * @return true if the rating popup has been shown today, false otherwise */ private fun hasRatingPopupBeenShownToday(): Boolean { val lastRatingTS = parameters.getRatingPopupLastAutoShowTimestamp() if (lastRatingTS > 0) { val cal = Calendar.getInstance() val currentDay = cal.get(Calendar.DAY_OF_YEAR) cal.time = Date(lastRatingTS) val lastTimeDay = cal.get(Calendar.DAY_OF_YEAR) return currentDay == lastTimeDay } return false } /** * Check that last time the premium popup was shown was 2 days ago or more * * @return true if we can show premium popup, false otherwise */ private fun shouldShowPremiumPopup(): Boolean { val lastPremiumTS = parameters.getPremiumPopupLastAutoShowTimestamp() if (lastPremiumTS == 0L) { return true } // Set calendar to last time 00:00 + 2 days val cal = Calendar.getInstance() cal.time = Date(lastPremiumTS) cal.set(Calendar.HOUR, 0) cal.set(Calendar.MINUTE, 0) cal.set(Calendar.SECOND, 0) cal.set(Calendar.MILLISECOND, 0) cal.add(Calendar.DAY_OF_YEAR, 2) return Date().after(cal.time) } /** * Set-up Batch SDK config + lifecycle */ private fun setUpBatchSDK() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { // Monthly report channel val name = getString(R.string.setting_category_notifications_monthly_title) val description = getString(R.string.setting_category_notifications_monthly_message) val importance = NotificationManager.IMPORTANCE_DEFAULT val monthlyReportChannel = NotificationChannel(CHANNEL_MONTHLY_REMINDERS, name, importance) monthlyReportChannel.description = description // Daily reminder channel val dailyName = getString(R.string.setting_category_notifications_daily_title) val dailyDescription = getString(R.string.setting_category_notifications_daily_message) val dailyImportance = NotificationManager.IMPORTANCE_DEFAULT val dailyReportChannel = NotificationChannel(CHANNEL_DAILY_REMINDERS, dailyName, dailyImportance) dailyReportChannel.description = dailyDescription // New features channel val newFeatureName = getString(R.string.setting_category_notifications_update_title) val newFeatureDescription = getString(R.string.setting_category_notifications_update_message) val newFeatureImportance = NotificationManager.IMPORTANCE_LOW val newFeatureChannel = NotificationChannel(CHANNEL_NEW_FEATURES, newFeatureName, newFeatureImportance) newFeatureChannel.description = newFeatureDescription val notificationManager = getSystemService(NotificationManager::class.java) if (notificationManager != null) { notificationManager.createNotificationChannel(newFeatureChannel) notificationManager.createNotificationChannel(monthlyReportChannel) notificationManager.createNotificationChannel(dailyReportChannel) // Remove Batch's default notificationManager.deleteNotificationChannel(DEFAULT_CHANNEL_ID) } } Batch.setConfig(Config(BuildConfig.BATCH_API_KEY).setCanUseAdvertisingID(false)) Batch.Push.setManualDisplay(true) Batch.Push.setSmallIconResourceId(R.drawable.ic_push) Batch.Push.setNotificationsColor(ContextCompat.getColor(this, R.color.accent)) Batch.Push.getChannelsManager().setChannelIdInterceptor { payload, _ -> if ( "true".equals(payload.pushBundle.getString(DAILY_REMINDER_KEY), ignoreCase = true) ) { return@setChannelIdInterceptor CHANNEL_DAILY_REMINDERS } if ( "true".equals(payload.pushBundle.getString(MONTHLY_REMINDER_KEY), ignoreCase = true) ) { return@setChannelIdInterceptor CHANNEL_MONTHLY_REMINDERS } CHANNEL_NEW_FEATURES } // Remove vibration & sound val notificationTypes = EnumSet.allOf(PushNotificationType::class.java) notificationTypes.remove(PushNotificationType.VIBRATE) notificationTypes.remove(PushNotificationType.SOUND) Batch.Push.setNotificationsType(notificationTypes) registerActivityLifecycleCallbacks(BatchActivityLifecycleHelper()) } /** * Check if a an update occured and call [.onUpdate] if so */ private fun checkUpdateAction() { val savedVersion = parameters.getCurrentAppVersion() if (savedVersion > 0 && savedVersion != BuildConfig.VERSION_CODE) { onUpdate(savedVersion, BuildConfig.VERSION_CODE) } parameters.setCurrentAppVersion(BuildConfig.VERSION_CODE) } /** * Called when an update occurred */ private fun onUpdate(previousVersion: Int, @Suppress("SameParameterValue") newVersion: Int) { Logger.debug("Update detected, from $previousVersion to $newVersion") } // --------------------------------------> /** * Called when the app goes foreground * * @param activity The activity that gone foreground */ private fun onAppForeground(activity: Activity) { Logger.debug("onAppForeground") /* * Increment the number of open */ parameters.setNumberOfOpen(parameters.getNumberOfOpen() + 1) /* * Check if last open is from another day */ var shouldIncrementDailyOpen = false val lastOpen = parameters.getLastOpenTimestamp() if (lastOpen > 0) { val cal = Calendar.getInstance() cal.time = Date(lastOpen) val lastDay = cal.get(Calendar.DAY_OF_YEAR) cal.time = Date() val currentDay = cal.get(Calendar.DAY_OF_YEAR) if (lastDay != currentDay) { shouldIncrementDailyOpen = true } } else { shouldIncrementDailyOpen = true } // Increment daily open if (shouldIncrementDailyOpen) { parameters.setNumberOfDailyOpen(parameters.getNumberOfDailyOpen() + 1) } /* * Save last open date */ parameters.setLastOpenTimestamp(Date().time) /* * Rating popup every day after 3 opens */ showRatingPopupIfNeeded(activity) /* * Premium popup after rating complete */ showPremiumPopupIfNeeded(activity) /* * Update iap status if needed */ iab.updateIAPStatusIfNeeded() } /** * Called when the app goes background */ private fun onAppBackground() { Logger.debug("onAppBackground") } }
apache-2.0
16894e7688d0e10389911e9379144172
34.580357
119
0.625157
5.229659
false
false
false
false
JuliusKunze/kotlin-native
backend.native/tests/external/codegen/box/reflection/enclosing/classInLambda.kt
2
711
// TODO: muted automatically, investigate should it be ran for JS or not // IGNORE_BACKEND: JS, NATIVE // WITH_REFLECT fun box(): String { val classInLambda = { class Z {} Z() }() val enclosingMethod = classInLambda.javaClass.getEnclosingMethod() if (enclosingMethod?.getName() != "invoke") return "method: $enclosingMethod" val enclosingClass = classInLambda.javaClass.getEnclosingClass()!!.getName() if (enclosingClass != "ClassInLambdaKt\$box\$classInLambda\$1") return "enclosing class: $enclosingClass" val declaringClass = classInLambda.javaClass.getDeclaringClass() if (declaringClass != null) return "class has a declaring class" return "OK" }
apache-2.0
8bf2ca092a814a4cf005813a29230d49
29.913043
109
0.697609
4.557692
false
false
false
false
JuliusKunze/kotlin-native
backend.native/tests/external/codegen/box/reified/arraysReification/jaggedDeep.kt
5
640
inline fun <reified T> jaggedArray(x: (Int, Int, Int) -> T): Array<Array<Array<T>>> = Array(1) { i -> Array(1) { j -> Array(1) { k -> x(i, j, k) } } } fun box(): String { val x1: Array<Array<Array<String>>> = jaggedArray<String>() { x, y, z -> "$x-$y-$z" } if (x1[0][0][0] != "0-0-0") return "fail 1" val x2: Array<Array<Array<Array<String>>>> = jaggedArray() { x, y, z -> arrayOf("$x-$y-$z") } if (x2[0][0][0][0] != "0-0-0") return "fail 2" val x3: Array<Array<Array<IntArray>>> = jaggedArray() { x, y, z -> intArrayOf(x + y + z + 1) } if (x3[0][0][0][0] != 1) return "fail 3" return "OK" }
apache-2.0
edcd133c304406289450d44129c819f5
36.647059
101
0.504688
2.38806
false
false
false
false
JuliusKunze/kotlin-native
backend.native/tests/external/stdlib/collections/ArraysTest/joinToString.kt
2
497
import kotlin.test.* fun box() { val text = arrayOf("foo", "bar").joinToString("-", "<", ">") assertEquals("<foo-bar>", text) val text2 = arrayOf('a', "b", StringBuilder("c"), null, "d", 'e', 'f').joinToString(limit = 4, truncated = "*") assertEquals("a, b, c, null, *", text2) val text3 = intArrayOf(1, 2, 5, 8).joinToString("+", "[", "]") assertEquals("[1+2+5+8]", text3) val text4 = charArrayOf('f', 'o', 'o').joinToString() assertEquals("f, o, o", text4) }
apache-2.0
4e84e6539626b11fe8eacda9e2bcfd14
32.133333
115
0.551308
3.291391
false
true
false
false
AndroidX/androidx
lint-checks/src/main/java/androidx/build/lint/TargetApiAnnotationUsageDetector.kt
3
3145
/* * Copyright (C) 2018 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:Suppress("UnstableApiUsage") package androidx.build.lint import com.android.tools.lint.client.api.UElementHandler import com.android.tools.lint.detector.api.Category import com.android.tools.lint.detector.api.Detector import com.android.tools.lint.detector.api.Implementation import com.android.tools.lint.detector.api.Incident import com.android.tools.lint.detector.api.Issue import com.android.tools.lint.detector.api.JavaContext import com.android.tools.lint.detector.api.Scope import com.android.tools.lint.detector.api.Severity import org.jetbrains.uast.UAnnotation /** * Enforces policy banning use of the `@TargetApi` annotation. */ class TargetApiAnnotationUsageDetector : Detector(), Detector.UastScanner { override fun getApplicableUastTypes() = listOf(UAnnotation::class.java) override fun createUastHandler(context: JavaContext): UElementHandler { return AnnotationChecker(context) } private inner class AnnotationChecker(val context: JavaContext) : UElementHandler() { override fun visitAnnotation(node: UAnnotation) { if (node.qualifiedName == "android.annotation.TargetApi") { val lintFix = fix().name("Replace with `@RequiresApi`") .replace() .pattern("(?:android\\.annotation\\.)?TargetApi") .with("androidx.annotation.RequiresApi") .shortenNames() .autoFix(true, true) .build() val incident = Incident(context) .fix(lintFix) .issue(ISSUE) .location(context.getNameLocation(node)) .message("Use `@RequiresApi` instead of `@TargetApi`") .scope(node) context.report(incident) } } } companion object { val ISSUE = Issue.create( "BanTargetApiAnnotation", "Replace usage of `@TargetApi` with `@RequiresApi`", "The `@TargetApi` annotation satisfies the `NewApi` lint check, but it does " + "not ensure that calls to the annotated API are correctly guarded on an `SDK_INT`" + " (or equivalent) check. Instead, use the `@RequiresApi` annotation to ensure " + "that all calls are correctly guarded.", Category.CORRECTNESS, 5, Severity.ERROR, Implementation(TargetApiAnnotationUsageDetector::class.java, Scope.JAVA_FILE_SCOPE) ) } }
apache-2.0
c86e13a95a327c75ed60aed6da031a85
39.844156
100
0.65787
4.638643
false
false
false
false