repo_name
stringlengths
7
79
path
stringlengths
8
206
copies
stringclasses
36 values
size
stringlengths
2
6
content
stringlengths
55
523k
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
7.18
99.5
line_max
int64
16
979
alpha_frac
float64
0.3
0.87
ratio
float64
2.01
8.07
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
solokot/Simple-Gallery
app/src/main/kotlin/com/simplemobiletools/gallery/pro/dialogs/ChangeFileThumbnailStyleDialog.kt
1
3364
package com.simplemobiletools.gallery.pro.dialogs import android.content.DialogInterface import android.view.View import androidx.appcompat.app.AlertDialog import com.simplemobiletools.commons.activities.BaseSimpleActivity import com.simplemobiletools.commons.dialogs.RadioGroupDialog import com.simplemobiletools.commons.extensions.setupDialogStuff import com.simplemobiletools.commons.models.RadioItem import com.simplemobiletools.gallery.pro.R import com.simplemobiletools.gallery.pro.extensions.config import kotlinx.android.synthetic.main.dialog_change_file_thumbnail_style.view.* class ChangeFileThumbnailStyleDialog(val activity: BaseSimpleActivity) : DialogInterface.OnClickListener { private var config = activity.config private var view: View private var thumbnailSpacing = config.thumbnailSpacing init { view = activity.layoutInflater.inflate(R.layout.dialog_change_file_thumbnail_style, null).apply { dialog_file_style_rounded_corners.isChecked = config.fileRoundedCorners dialog_file_style_animate_gifs.isChecked = config.animateGifs dialog_file_style_show_thumbnail_video_duration.isChecked = config.showThumbnailVideoDuration dialog_file_style_show_thumbnail_file_types.isChecked = config.showThumbnailFileTypes dialog_file_style_rounded_corners_holder.setOnClickListener { dialog_file_style_rounded_corners.toggle() } dialog_file_style_animate_gifs_holder.setOnClickListener { dialog_file_style_animate_gifs.toggle() } dialog_file_style_show_thumbnail_video_duration_holder.setOnClickListener { dialog_file_style_show_thumbnail_video_duration.toggle() } dialog_file_style_show_thumbnail_file_types_holder.setOnClickListener { dialog_file_style_show_thumbnail_file_types.toggle() } dialog_file_style_spacing_holder.setOnClickListener { val items = arrayListOf( RadioItem(0, "0x"), RadioItem(1, "1x"), RadioItem(2, "2x"), RadioItem(4, "4x"), RadioItem(8, "8x"), RadioItem(16, "16x"), RadioItem(32, "32x"), RadioItem(64, "64x")) RadioGroupDialog(activity, items, thumbnailSpacing) { thumbnailSpacing = it as Int updateThumbnailSpacingText() } } } updateThumbnailSpacingText() AlertDialog.Builder(activity) .setPositiveButton(R.string.ok, this) .setNegativeButton(R.string.cancel, null) .create().apply { activity.setupDialogStuff(view, this) } } override fun onClick(dialog: DialogInterface, which: Int) { config.fileRoundedCorners = view.dialog_file_style_rounded_corners.isChecked config.animateGifs = view.dialog_file_style_animate_gifs.isChecked config.showThumbnailVideoDuration = view.dialog_file_style_show_thumbnail_video_duration.isChecked config.showThumbnailFileTypes = view.dialog_file_style_show_thumbnail_file_types.isChecked config.thumbnailSpacing = thumbnailSpacing } private fun updateThumbnailSpacingText() { view.dialog_file_style_spacing.text = "${thumbnailSpacing}x" } }
gpl-3.0
c240bb15fc5317b83ad3c397116b6452
47.057143
146
0.689655
4.620879
false
true
false
false
Txuritan/mental
src/main/kotlin/com/github/txuritan/mental/script/common/utils/Recipe.kt
1
8317
/* * MIT License * * Copyright (c) 2017 Ian Cronkright * * 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.github.txuritan.mental.script.common.utils import com.github.txuritan.mental.script.common.IGlobal import net.minecraftforge.fml.common.registry.GameRegistry import net.minecraftforge.oredict.OreDictionary import net.minecraftforge.oredict.ShapedOreRecipe import org.luaj.vm2.LuaValue /** * @author Ian 'Txuritan/Captain Daro'Ma'Sohni Tavia' Cronkright */ class Recipe : IGlobal { override var name : String = "recipe" fun addShapedRecipe(output : LuaValue, crafting : LuaValue, elements : LuaValue) { } fun addShapedOreRecipe(output : LuaValue, crafting : LuaValue, elements : LuaValue) { if (elements.length() == 1) { GameRegistry.addRecipe( ShapedOreRecipe( OreDictionary.getOres(output.tojstring())[0], crafting.get(1), crafting.get(2), crafting.get(3), elements.get(1).get(1).tochar(), elements.get(1).get(2).tojstring() ) ) } else if (elements.length() == 2) { GameRegistry.addRecipe( ShapedOreRecipe( OreDictionary.getOres(output.tojstring())[0], crafting.get(1), crafting.get(2), crafting.get(3), elements.get(1).get(1).tochar(), elements.get(1).get(2).tojstring(), elements.get(2).get(1).tochar(), elements.get(2).get(2).tojstring() ) ) } else if (elements.length() == 3) { GameRegistry.addRecipe( ShapedOreRecipe( OreDictionary.getOres(output.tojstring())[0], crafting.get(1), crafting.get(2), crafting.get(3), elements.get(1).get(1).tochar(), elements.get(1).get(2).tojstring(), elements.get(2).get(1).tochar(), elements.get(2).get(2).tojstring(), elements.get(3).get(1).tochar(), elements.get(3).get(2).tojstring() ) ) } else if (elements.length() == 4) { GameRegistry.addRecipe( ShapedOreRecipe( OreDictionary.getOres(output.tojstring())[0], crafting.get(1), crafting.get(2), crafting.get(3), elements.get(1).get(1).tochar(), elements.get(1).get(2).tojstring(), elements.get(2).get(1).tochar(), elements.get(2).get(2).tojstring(), elements.get(3).get(1).tochar(), elements.get(3).get(2).tojstring(), elements.get(4).get(1).tochar(), elements.get(4).get(2).tojstring() ) ) } else if (elements.length() == 5) { GameRegistry.addRecipe( ShapedOreRecipe( OreDictionary.getOres(output.tojstring())[0], crafting.get(1), crafting.get(2), crafting.get(3), elements.get(1).get(1).tochar(), elements.get(1).get(2).tojstring(), elements.get(2).get(1).tochar(), elements.get(2).get(2).tojstring(), elements.get(3).get(1).tochar(), elements.get(3).get(2).tojstring(), elements.get(4).get(1).tochar(), elements.get(4).get(2).tojstring(), elements.get(5).get(1).tochar(), elements.get(5).get(2).tojstring() ) ) } else if (elements.length() == 6) { GameRegistry.addRecipe( ShapedOreRecipe( OreDictionary.getOres(output.tojstring())[0], crafting.get(1), crafting.get(2), crafting.get(3), elements.get(1).get(1).tochar(), elements.get(1).get(2).tojstring(), elements.get(2).get(1).tochar(), elements.get(2).get(2).tojstring(), elements.get(3).get(1).tochar(), elements.get(3).get(2).tojstring(), elements.get(4).get(1).tochar(), elements.get(4).get(2).tojstring(), elements.get(5).get(1).tochar(), elements.get(5).get(2).tojstring(), elements.get(6).get(1).tochar(), elements.get(6).get(2).tojstring() ) ) } else if (elements.length() == 7) { GameRegistry.addRecipe( ShapedOreRecipe( OreDictionary.getOres(output.tojstring())[0], crafting.get(1), crafting.get(2), crafting.get(3), elements.get(1).get(1).tochar(), elements.get(1).get(2).tojstring(), elements.get(2).get(1).tochar(), elements.get(2).get(2).tojstring(), elements.get(3).get(1).tochar(), elements.get(3).get(2).tojstring(), elements.get(4).get(1).tochar(), elements.get(4).get(2).tojstring(), elements.get(5).get(1).tochar(), elements.get(5).get(2).tojstring(), elements.get(6).get(1).tochar(), elements.get(6).get(2).tojstring(), elements.get(7).get(1).tochar(), elements.get(7).get(2).tojstring() ) ) } else if (elements.length() == 8) { GameRegistry.addRecipe( ShapedOreRecipe( OreDictionary.getOres(output.tojstring())[0], crafting.get(1), crafting.get(2), crafting.get(3), elements.get(1).get(1).tochar(), elements.get(1).get(2).tojstring(), elements.get(2).get(1).tochar(), elements.get(2).get(2).tojstring(), elements.get(3).get(1).tochar(), elements.get(3).get(2).tojstring(), elements.get(4).get(1).tochar(), elements.get(4).get(2).tojstring(), elements.get(5).get(1).tochar(), elements.get(5).get(2).tojstring(), elements.get(6).get(1).tochar(), elements.get(6).get(2).tojstring(), elements.get(7).get(1).tochar(), elements.get(7).get(2).tojstring(), elements.get(8).get(1).tochar(), elements.get(8).get(2).tojstring() ) ) } else if (elements.length() == 9) { GameRegistry.addRecipe( ShapedOreRecipe( OreDictionary.getOres(output.tojstring())[0], crafting.get(1), crafting.get(2), crafting.get(3), elements.get(1).get(1).tochar(), elements.get(1).get(2).tojstring(), elements.get(2).get(1).tochar(), elements.get(2).get(2).tojstring(), elements.get(3).get(1).tochar(), elements.get(3).get(2).tojstring(), elements.get(4).get(1).tochar(), elements.get(4).get(2).tojstring(), elements.get(5).get(1).tochar(), elements.get(5).get(2).tojstring(), elements.get(6).get(1).tochar(), elements.get(6).get(2).tojstring(), elements.get(7).get(1).tochar(), elements.get(7).get(2).tojstring(), elements.get(8).get(1).tochar(), elements.get(8).get(2).tojstring(), elements.get(9).get(1).tochar(), elements.get(9).get(2).tojstring() ) ) } } }
mit
7891719f2ca1a78cf41fc89b49d32c0b
53.006494
89
0.555489
3.753159
false
false
false
false
RSDT/Japp
app/src/main/java/nl/rsdt/japp/service/LocationService.kt
1
15384
package nl.rsdt.japp.service import android.app.Activity import android.app.NotificationManager import android.app.PendingIntent import android.content.* import android.graphics.BitmapFactory import android.graphics.Color import android.location.Location import android.location.LocationManager import android.net.Uri import android.os.Binder import android.os.Handler import android.os.IBinder import android.os.Looper import android.util.Log import android.widget.Toast import androidx.core.app.NotificationCompat import com.google.android.gms.common.api.Status import com.google.android.gms.location.LocationRequest import com.google.android.gms.location.LocationSettingsResult import com.google.android.gms.location.LocationSettingsStatusCodes import com.google.android.gms.maps.model.LatLng import nl.rsdt.japp.R import nl.rsdt.japp.application.Japp import nl.rsdt.japp.application.JappPreferences import nl.rsdt.japp.application.activities.MainActivity import nl.rsdt.japp.jotial.data.bodies.HunterPostBody import nl.rsdt.japp.jotial.data.structures.area348.AutoInzittendeInfo import nl.rsdt.japp.jotial.data.structures.area348.HunterInfo import nl.rsdt.japp.jotial.maps.NavigationLocationManager import nl.rsdt.japp.jotial.maps.deelgebied.Deelgebied import nl.rsdt.japp.jotial.maps.locations.LocationProviderService import nl.rsdt.japp.jotial.net.apis.AutoApi import nl.rsdt.japp.jotial.net.apis.HunterApi import retrofit2.Call import retrofit2.Callback import retrofit2.Response import java.util.* /** * @author Dingenis Sieger Sinke * @version 1.0 * @since 8-7-2016 * Description... */ class LocationService : LocationProviderService<Binder>(), SharedPreferences.OnSharedPreferenceChangeListener { private val binder = LocationBinder() private var wasSending = false private var listener: OnResolutionRequiredListener? = null internal var lastUpdate = Calendar.getInstance() private val locationSettingReceiver = object : BroadcastReceiver() { override fun onReceive(context: Context, intent: Intent?) { if (intent?.action?.matches("android.location.PROVIDERS_CHANGED".toRegex()) == true) { // Make an action or refresh an already managed state. val locationManager = getSystemService(Context.LOCATION_SERVICE) as LocationManager val gps = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) if (!gps) { val notificationIntent = Intent(this@LocationService, MainActivity::class.java) notificationIntent.action = ACTION_REQUEST_LOCATION_SETTING notificationIntent.flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_SINGLE_TOP or Intent.FLAG_ACTIVITY_CLEAR_TOP val pendingIntent = PendingIntent.getActivity(this@LocationService, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT) showLocationNotification(getString(R.string.japp_not_sending_location), getString(R.string.torn_on_gps), Color.rgb(244, 66, 66), pendingIntent) } } } } val standard: LocationRequest get() = LocationRequest() .setInterval(JappPreferences.locationUpdateIntervalInMs.toLong()) .setFastestInterval(JappPreferences.locationUpdateIntervalInMs.toLong()) .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY) fun setListener(listener: OnResolutionRequiredListener?) { this.listener = listener } override fun onCreate() { super.onCreate() JappPreferences.visiblePreferences.registerOnSharedPreferenceChangeListener(this) registerReceiver(locationSettingReceiver, IntentFilter(LocationManager.PROVIDERS_CHANGED_ACTION)) val locationManager = NavigationLocationManager() locationManager.setCallback(object : NavigationLocationManager.OnNewLocation { override fun onNewLocation(location: nl.rsdt.japp.jotial.data.firebase.Location) { if (JappPreferences.isNavigationPhone) { try { val mesg = getString(R.string.location_received, location.createdBy, location.lat, location.lon) showToast(mesg, Toast.LENGTH_LONG) when (JappPreferences.navigationApp()) { JappPreferences.NavigationApp.GoogleMaps -> { val uristr = getString(R.string.google_uri, java.lang.Double.toString(location.lat), java.lang.Double.toString(location.lon)) val gmmIntentUri = Uri.parse(uristr) val mapIntent = Intent(Intent.ACTION_VIEW, gmmIntentUri) mapIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) mapIntent.setPackage("com.google.android.apps.maps") startActivity(mapIntent) } JappPreferences.NavigationApp.Waze -> { val uri = getString(R.string.waze_uri, java.lang.Double.toString(location.lat), java.lang.Double.toString(location.lon)) val wazeIntent = Intent(Intent.ACTION_VIEW, Uri.parse(uri)) wazeIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) startActivity(wazeIntent) } JappPreferences.NavigationApp.OSMAnd -> { val osmUri = getString(R.string.osmand_uri, java.lang.Double.toString(location.lat), java.lang.Double.toString(location.lon)) val osmIntent = Intent(Intent.ACTION_VIEW, Uri.parse(osmUri)) osmIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) startActivity(osmIntent) } JappPreferences.NavigationApp.OSMAndWalk -> { val osmuriwalk = getString(R.string.osmandwalk_uri, java.lang.Double.toString(location.lat), java.lang.Double.toString(location.lon)) val osmWalkIntent = Intent(Intent.ACTION_VIEW, Uri.parse(osmuriwalk)) osmWalkIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) startActivity(osmWalkIntent) } JappPreferences.NavigationApp.Geo -> { val geoUri = getString(R.string.geo_uri, java.lang.Double.toString(location.lat), java.lang.Double.toString(location.lon)) val geoIntent = Intent(Intent.ACTION_VIEW, Uri.parse(geoUri)) geoIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) startActivity(geoIntent) } } } catch (e: ActivityNotFoundException) { println(e.toString()) val mesg = getString(R.string.navigation_app_not_installed, JappPreferences.navigationApp().toString()) showToast(mesg, Toast.LENGTH_SHORT) } } } override fun onNotInCar() { val mesg = getString(R.string.fout_not_in_car) showToast(mesg, Toast.LENGTH_LONG) } }) } private fun showToast(message: String, length: Int) { val handler = Handler(Looper.getMainLooper()) handler.post { Toast.makeText(applicationContext, message, length).show() } } fun showLocationNotification(title: String, color: Int) { showLocationNotification(title, getString(R.string.open_japp), color) } fun showLocationNotification(title: String, description: String, color: Int) { val notificationIntent = Intent(this, MainActivity::class.java) notificationIntent.flags = Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_SINGLE_TOP val intent = PendingIntent.getActivity(this, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT) showLocationNotification(title, description, color, intent) } fun showLocationNotification(title: String, description: String, color: Int, intent: PendingIntent) { val notification = NotificationCompat.Builder(this, LOCATION_NOTIFICATION_CHANNEL) .setContentTitle(title) .setContentText(description) .setSmallIcon(R.drawable.ic_my_location_white_48dp) .setLargeIcon(BitmapFactory.decodeResource(resources, R.mipmap.ic_launcher)) .setColor(color) .setOngoing(true) .setPriority(NotificationCompat.PRIORITY_HIGH) .setContentIntent(intent) .build() val mNotifyMgr = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager mNotifyMgr.notify(1923, notification) } override fun onLocationChanged(location: Location) { super.onLocationChanged(location) Japp.lastLocation = location val dif = Calendar.getInstance().timeInMillis - lastUpdate.timeInMillis val shouldSend = JappPreferences.isUpdatingLocationToServer if (shouldSend != wasSending) { val title: String val color: Int if (shouldSend) { title = getString(R.string.japp_sends_location) color = Color.rgb(113, 244, 66) } else { title = getString(R.string.japp_not_sending_location) color = Color.rgb(244, 66, 66) } showLocationNotification(title, color) } if (shouldSend) { if (dif >= Math.round(JappPreferences.locationUpdateIntervalInMs)) { sendLocation(location) } } } override fun onResult(result: LocationSettingsResult) { val status = result.status when (status.statusCode) { LocationSettingsStatusCodes.SUCCESS -> { wasSending = JappPreferences.isUpdatingLocationToServer if (!wasSending) { showLocationNotification(getString(R.string.japp_sends_location), Color.rgb(244, 66, 66)) } else { showLocationNotification(getString(R.string.japp_not_sending_location), Color.rgb(113, 244, 66)) } } LocationSettingsStatusCodes.RESOLUTION_REQUIRED -> if (listener != null) { listener!!.onResolutionRequired(status) } } } fun handleResolutionResult(code: Int) { when (code) { Activity.RESULT_OK -> { startLocationUpdates() val wasSending = JappPreferences.isUpdatingLocationToServer if (!wasSending) { showLocationNotification(getString(R.string.japp_not_sending_location), getString(R.string.turn_on_location_in_app), Color.rgb(244, 66, 66)) } else { showLocationNotification(getString(R.string.japp_sends_location), Color.rgb(113, 244, 66)) } } Activity.RESULT_CANCELED -> { val notificationIntent = Intent(this, MainActivity::class.java) notificationIntent.action = ACTION_REQUEST_LOCATION_SETTING notificationIntent.flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_SINGLE_TOP or Intent.FLAG_ACTIVITY_CLEAR_TOP val intent = PendingIntent.getActivity(this, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT) showLocationNotification(getString(R.string.japp_not_sending_location), getString(R.string.click_to_activate_location_setting), Color.rgb(244, 66, 66), intent) } } } private fun sendlocation2(location: Location, builder: HunterPostBody){ val api = Japp.getApi(HunterApi::class.java) api.post(builder).enqueue(object : Callback<Void> { override fun onResponse(call: Call<Void>, response: Response<Void>) { Log.i(TAG, getString(R.string.location_sent)) } override fun onFailure(call: Call<Void>, t: Throwable) { Log.e(TAG, t.toString(), t) } }) } private fun sendLocation(location: Location) { val builder = HunterPostBody.default builder.setLatLng(LatLng(location.latitude, location.longitude)) if (JappPreferences.accountIcon == 0 && JappPreferences.prependDeelgebied){ val api = Japp.getApi(AutoApi::class.java) api.getInfoById(JappPreferences.accountKey, JappPreferences.accountId).enqueue( object: Callback<AutoInzittendeInfo?>{ override fun onFailure(call: Call<AutoInzittendeInfo?>, t: Throwable) { sendlocation2(location, builder) } override fun onResponse(call: Call<AutoInzittendeInfo?>, response: Response<AutoInzittendeInfo?>) { if (response.isSuccessful) { val dg = Deelgebied.parse(response.body()?.taak ?: "X") ?: Deelgebied.Xray builder.prependDeelgebiedToName(dg) } sendlocation2(location, builder) } } ) }else{ sendlocation2(location, builder) } lastUpdate = Calendar.getInstance() wasSending = true } override fun onSharedPreferenceChanged(sharedPreferences: SharedPreferences, s: String) { when (s) { JappPreferences.UPDATE_LOCATION -> { val shouldSend = JappPreferences.isUpdatingLocationToServer val title: String val color: Int if (shouldSend) { title = getString(R.string.japp_sends_location) color = Color.rgb(113, 244, 66) } else { title = getString(R.string.japp_not_sending_location) color = Color.rgb(244, 66, 66) } showLocationNotification(title, color) } } } override fun onBind(intent: Intent): IBinder? { return binder } override fun onDestroy() { super.onDestroy() JappPreferences.visiblePreferences.unregisterOnSharedPreferenceChangeListener(this) } inner class LocationBinder : Binder() { val instance: LocationService get() = this@LocationService } interface OnResolutionRequiredListener { fun onResolutionRequired(status: Status) } companion object { val TAG = "LocationService" val ACTION_REQUEST_LOCATION_SETTING = "ACTION_REQUEST_LOCATION_SETTING" private val LOCATION_NOTIFICATION_CHANNEL = "notification_chan" } }
apache-2.0
aa3361dda0048c14eb4118b34c167ee2
44.649852
175
0.610114
5.065525
false
false
false
false
firebase/quickstart-android
firestore/app/src/main/java/com/google/firebase/example/fireeats/kotlin/adapter/FirestoreAdapter.kt
2
3689
package com.google.firebase.example.fireeats.kotlin.adapter import androidx.recyclerview.widget.RecyclerView import android.util.Log import com.google.firebase.firestore.DocumentChange import com.google.firebase.firestore.DocumentSnapshot import com.google.firebase.firestore.EventListener import com.google.firebase.firestore.FirebaseFirestoreException import com.google.firebase.firestore.ListenerRegistration import com.google.firebase.firestore.Query import com.google.firebase.firestore.QuerySnapshot import java.util.ArrayList /** * RecyclerView adapter for displaying the results of a Firestore [Query]. * * Note that this class forgoes some efficiency to gain simplicity. For example, the result of * [DocumentSnapshot.toObject] is not cached so the same object may be deserialized * many times as the user scrolls. */ abstract class FirestoreAdapter<VH : RecyclerView.ViewHolder>(private var query: Query?) : RecyclerView.Adapter<VH>(), EventListener<QuerySnapshot> { private var registration: ListenerRegistration? = null private val snapshots = ArrayList<DocumentSnapshot>() override fun onEvent(documentSnapshots: QuerySnapshot?, e: FirebaseFirestoreException?) { if (e != null) { Log.w(TAG, "onEvent:error", e) onError(e) return } if (documentSnapshots == null) { return } // Dispatch the event Log.d(TAG, "onEvent:numChanges:" + documentSnapshots.documentChanges.size) for (change in documentSnapshots.documentChanges) { when (change.type) { DocumentChange.Type.ADDED -> onDocumentAdded(change) DocumentChange.Type.MODIFIED -> onDocumentModified(change) DocumentChange.Type.REMOVED -> onDocumentRemoved(change) } } onDataChanged() } fun startListening() { if (query != null && registration == null) { registration = query!!.addSnapshotListener(this) } } fun stopListening() { registration?.remove() registration = null snapshots.clear() notifyDataSetChanged() } fun setQuery(query: Query) { // Stop listening stopListening() // Clear existing data snapshots.clear() notifyDataSetChanged() // Listen to new query this.query = query startListening() } open fun onError(e: FirebaseFirestoreException) { Log.w(TAG, "onError", e) } open fun onDataChanged() {} override fun getItemCount(): Int { return snapshots.size } protected fun getSnapshot(index: Int): DocumentSnapshot { return snapshots[index] } private fun onDocumentAdded(change: DocumentChange) { snapshots.add(change.newIndex, change.document) notifyItemInserted(change.newIndex) } private fun onDocumentModified(change: DocumentChange) { if (change.oldIndex == change.newIndex) { // Item changed but remained in same position snapshots[change.oldIndex] = change.document notifyItemChanged(change.oldIndex) } else { // Item changed and changed position snapshots.removeAt(change.oldIndex) snapshots.add(change.newIndex, change.document) notifyItemMoved(change.oldIndex, change.newIndex) } } private fun onDocumentRemoved(change: DocumentChange) { snapshots.removeAt(change.oldIndex) notifyItemRemoved(change.oldIndex) } companion object { private const val TAG = "FirestoreAdapter" } }
apache-2.0
621ae64f389d5aaa4b65ee98cf10f8af
29.487603
94
0.661697
4.918667
false
false
false
false
tmarsteel/kotlin-prolog
core/src/main/kotlin/com/github/prologdb/runtime/term/CompoundTerm.kt
1
10561
package com.github.prologdb.runtime.term import com.github.prologdb.runtime.Clause import com.github.prologdb.runtime.NullSourceInformation import com.github.prologdb.runtime.PrologSourceInformation import com.github.prologdb.runtime.RandomVariableScope import com.github.prologdb.runtime.proofsearch.PrologCallableFulfill import com.github.prologdb.runtime.unification.Unification import com.github.prologdb.runtime.util.OperatorDefinition import com.github.prologdb.runtime.util.OperatorRegistry import com.github.prologdb.runtime.util.OperatorType import com.github.prologdb.runtime.util.OperatorType.* import sensibleHashCode @PrologTypeName("compound term") class CompoundTerm( override val functor: String, val arguments: Array<out Term>, ) : Term, Clause { override val arity = arguments.size override fun unify(rhs: Term, randomVarsScope: RandomVariableScope): Unification? { if (rhs is CompoundTerm) { if (this.functor != rhs.functor) { return Unification.FALSE } return arguments.unify(rhs.arguments, randomVarsScope) } else if (rhs is Variable) { return rhs.unify(this, randomVarsScope) } else { return Unification.FALSE } } override val fulfill: PrologCallableFulfill = { arguments, context -> arguments.unify(arguments, context.randomVariableScope) } override val variables by lazy { arguments.flatMap(Term::variables).toSet() } override fun substituteVariables(mapper: (Variable) -> Term): CompoundTerm { return CompoundTerm(functor, arguments.map { it.substituteVariables(mapper) }.toTypedArray()).also { it.sourceInformation = this.sourceInformation } } override fun compareTo(other: Term): Int { if (other is Variable || other is PrologNumber || other is PrologString || other is Atom || other is PrologList) { // these are by category lesser than compound terms return 1 } other as? CompoundTerm ?: throw IllegalArgumentException("Given argument is not a known prolog term type (expected variable, number, string, atom, list or compound)") val arityCmp = this.arity - other.arity if (arityCmp != 0) return arityCmp val functorNameCmp = this.functor.compareTo(other.functor) if (functorNameCmp != 0) return functorNameCmp for (argumentIndex in 0 until arity) { val selfArgument = this.arguments[argumentIndex] val otherArgument = other.arguments[argumentIndex] val argumentCmp = selfArgument.compareTo(otherArgument) if (argumentCmp != 0) return argumentCmp } return 0 } override fun toString(): String { return functor + "(" + arguments.joinToString(", ") + ")" } override fun toStringUsingOperatorNotations(operators: OperatorRegistry): String { return toStringUsingOperatorNotationsInternal(operators).first } override fun equals(other: Any?): Boolean { if (this === other) return true if (other !is CompoundTerm) return false if (functor != other.functor) return false if (arguments contentDeepEquals other.arguments) return true return false } override fun hashCode(): Int { var result = functor.hashCode() result = 31 * result + arguments.sensibleHashCode() return result } override var sourceInformation: PrologSourceInformation = NullSourceInformation /** Whether there were explicit parenthesis around this term. Important for the parser mostly. */ var parenthesized: Boolean = false } class CompoundBuilder(private val functor: String) { operator fun invoke(vararg arguments: Term) = CompoundTerm(functor, arguments) } /** * @return first: the result string, second: the precedence of the term, third: the topmost/outmost operator * in the string (or null if none) */ private fun Term.toStringUsingOperatorNotationsInternal(operators: OperatorRegistry): Triple<String, Short, OperatorDefinition?> { if (this !is CompoundTerm) { return Triple(this.toStringUsingOperatorNotations(operators), 0, null) } val operator = operators.getOperatorDefinitionsFor(functor) .firstOrNull { it.type.arity == this.arity } ?: return toStringThisUsingStrictNotationArgumentsUsingOperatorNotations(operators) when { operator.type.isPrefix -> { val arg = arguments[0] val argumentTriple = arg.toStringUsingOperatorNotationsInternal(operators) val parenthesisRequirement = if (operator.precedence > argumentTriple.second) { // priorities are clear, looking at associativity or putting parenthesis not necessary ParenthesisRequirement.NOT_REQUIRED } else if (operator.precedence < argumentTriple.second) { // priorities are directly inverted to what would be if we simply prepended the operator // thus, parenthesis are required. ParenthesisRequirement.REQUIRED } // priorities are ambiguous, need to look at associativity else if (operator.type == FY && argumentTriple.third?.type in setOf(XF, XFX, XFY)) { // associativity removes the ambiguity in this case ParenthesisRequirement.NOT_REQUIRED } else { // priorities are directly inverted to what would be if we simply prepended the operator // thus, parenthesis are required. ParenthesisRequirement.REQUIRED } return when (parenthesisRequirement) { ParenthesisRequirement.NOT_REQUIRED -> Triple(operator.name + " " + argumentTriple.first, operator.precedence, operator) ParenthesisRequirement.REQUIRED -> { // for prefix, parenthesis are, to the reader, equal to invocation syntax (compare op(a) op (a)). // for easier reading and parsing, we go with the invocation syntax (no whitespace) return Triple( operator.name + "(" + argumentTriple.first + ")", operator.precedence, operator ) } } } operator.type.isPostfix -> { val arg = arguments[0] val argumentTriple = arg.toStringUsingOperatorNotationsInternal(operators) val parenthesisRequirement = if (operator.precedence > argumentTriple.second) { // priorities are clear, looking at associativity or putting parenthesis not necessary ParenthesisRequirement.NOT_REQUIRED } else if (operator.precedence < argumentTriple.second) { // priorities are directly inverted to what would be if we simply prepended the operator // thus, parenthesis are required. ParenthesisRequirement.REQUIRED } // priorities are ambiguous, need to look at associativity else if (argumentTriple.third?.type in setOf(FX, XFX, YFX) && operator.type == YF) { // associativity removes the ambiguity in this case ParenthesisRequirement.NOT_REQUIRED } else { // priorities are directly inverted to what would be if we simply prepended the operator // thus, parenthesis are required. ParenthesisRequirement.REQUIRED } return when (parenthesisRequirement) { ParenthesisRequirement.NOT_REQUIRED -> Triple(argumentTriple.first + " " + operator.name, operator.precedence, operator) ParenthesisRequirement.REQUIRED -> { return Triple( "(" + argumentTriple.first + ") " + operator.name, operator.precedence, operator ) } } } operator.type.isInfix -> { val leftTriple = arguments[0].toStringUsingOperatorNotationsInternal(operators) val rightTriple = arguments[1].toStringUsingOperatorNotationsInternal(operators) val leftParenthesisRequirements = if (operator.precedence > leftTriple.second) { ParenthesisRequirement.NOT_REQUIRED } else { ParenthesisRequirement.REQUIRED } val rightParenthesisRequirement = if (operator.precedence > rightTriple.second) { ParenthesisRequirement.NOT_REQUIRED } else { ParenthesisRequirement.REQUIRED } val leftString = if (leftParenthesisRequirements == ParenthesisRequirement.REQUIRED) { "(${leftTriple.first})" } else { leftTriple.first } val rightString = if (rightParenthesisRequirement == ParenthesisRequirement.REQUIRED) { "(${rightTriple.first})" } else { rightTriple.first } return Triple( "$leftString ${operator.name} $rightString", operator.precedence, operator ) } else -> throw RuntimeException("This should not have happened. ${OperatorType::class.qualifiedName}.isPrefix / .isPostfix / .isInfix are erroneous (exactly one of the three MUST be true)") } } private enum class ParenthesisRequirement { REQUIRED, NOT_REQUIRED } /** * @return compatible with [toStringUsingOperatorNotationsInternal], but second always 0 and third always null. */ private fun CompoundTerm.toStringThisUsingStrictNotationArgumentsUsingOperatorNotations(operators: OperatorRegistry): Triple<String, Short, OperatorDefinition?> { val argumentStrings = arguments.map { val triple = it.toStringUsingOperatorNotationsInternal(operators) if (triple.third?.name == ",") "(${triple.first})" else triple.first } return Triple( argumentStrings.joinToString( separator = ", ", prefix = "$functor(", // TODO functor that needs escaping postfix = ")" ), 0, null ) }
mit
6363cd0f8734c7dbe5d56c0a262fa493
39.934109
196
0.626835
5.277861
false
false
false
false
tmarsteel/kotlin-prolog
core/src/test/kotlin/com/github/prologdb/runtime/term/OperatorNotationToStringTest.kt
1
20399
package com.github.prologdb.runtime.term import com.github.prologdb.runtime.util.DefaultOperatorRegistry import com.github.prologdb.runtime.util.OperatorDefinition import com.github.prologdb.runtime.util.OperatorType import io.kotest.core.spec.style.FreeSpec import io.kotest.matchers.shouldBe class OperatorNotationToStringTest : FreeSpec({ "prefix operator nesting" - { val a = Atom("a") val b = Atom("b") val prefix = CompoundBuilder("prefix") val postfix = CompoundBuilder("postfix") val infix = CompoundBuilder("infix") "prefix has higher priority" - { "nesting XF" { val registry = DefaultOperatorRegistry() registry.defineOperator(OperatorDefinition(300, OperatorType.FX, "prefix")) registry.defineOperator(OperatorDefinition(200, OperatorType.XF, "postfix")) val term = prefix(postfix(a)) term.toStringUsingOperatorNotations(registry) shouldBe "prefix a postfix" } "nesting YF" { val registry = DefaultOperatorRegistry() registry.defineOperator(OperatorDefinition(300, OperatorType.FX, "prefix")) registry.defineOperator(OperatorDefinition(200, OperatorType.YF, "postfix")) val term = prefix(postfix(a)) term.toStringUsingOperatorNotations(registry) shouldBe "prefix a postfix" } "nesting XFX" { val registry = DefaultOperatorRegistry() registry.defineOperator(OperatorDefinition(300, OperatorType.FX, "prefix")) registry.defineOperator(OperatorDefinition(200, OperatorType.XFX, "infix")) val term = prefix(infix(a, b)) term.toStringUsingOperatorNotations(registry) shouldBe "prefix a infix b" } "nesting XFY" { val registry = DefaultOperatorRegistry() registry.defineOperator(OperatorDefinition(300, OperatorType.FX, "prefix")) registry.defineOperator(OperatorDefinition(200, OperatorType.XFY, "infix")) val term = prefix(infix(a, b)) term.toStringUsingOperatorNotations(registry) shouldBe "prefix a infix b" } "nesting YFX" { val registry = DefaultOperatorRegistry() registry.defineOperator(OperatorDefinition(300, OperatorType.FX, "prefix")) registry.defineOperator(OperatorDefinition(200, OperatorType.YFX, "infix")) val term = prefix(infix(a, b)) term.toStringUsingOperatorNotations(registry) shouldBe "prefix a infix b" } } "prefix has lower priority" - { "nesting XF" { val registry = DefaultOperatorRegistry() registry.defineOperator(OperatorDefinition(100, OperatorType.FX, "prefix")) registry.defineOperator(OperatorDefinition(200, OperatorType.XF, "postfix")) val term = prefix(postfix(a)) term.toStringUsingOperatorNotations(registry) shouldBe "prefix(a postfix)" } "nesting YF" { val registry = DefaultOperatorRegistry() registry.defineOperator(OperatorDefinition(100, OperatorType.FX, "prefix")) registry.defineOperator(OperatorDefinition(200, OperatorType.YF, "postfix")) val term = prefix(postfix(a)) term.toStringUsingOperatorNotations(registry) shouldBe "prefix(a postfix)" } "nesting XFX" { val registry = DefaultOperatorRegistry() registry.defineOperator(OperatorDefinition(100, OperatorType.FX, "prefix")) registry.defineOperator(OperatorDefinition(200, OperatorType.XFX, "infix")) val term = prefix(infix(a, b)) term.toStringUsingOperatorNotations(registry) shouldBe "prefix(a infix b)" } "nesting XFY" { val registry = DefaultOperatorRegistry() registry.defineOperator(OperatorDefinition(100, OperatorType.FX, "prefix")) registry.defineOperator(OperatorDefinition(200, OperatorType.XFY, "infix")) val term = prefix(infix(a, b)) term.toStringUsingOperatorNotations(registry) shouldBe "prefix(a infix b)" } "nesting YFX" { val registry = DefaultOperatorRegistry() registry.defineOperator(OperatorDefinition(100, OperatorType.FX, "prefix")) registry.defineOperator(OperatorDefinition(200, OperatorType.YFX, "infix")) val term = prefix(infix(a, b)) term.toStringUsingOperatorNotations(registry) shouldBe "prefix(a infix b)" } } "equal priority" - { "FX nesting XF" { val registry = DefaultOperatorRegistry() registry.defineOperator(OperatorDefinition(200, OperatorType.FX, "prefix")) registry.defineOperator(OperatorDefinition(200, OperatorType.XF, "postfix")) val term = prefix(postfix(a)) term.toStringUsingOperatorNotations(registry) shouldBe "prefix(a postfix)" } "FX nesting YF" { val registry = DefaultOperatorRegistry() registry.defineOperator(OperatorDefinition(200, OperatorType.FX, "prefix")) registry.defineOperator(OperatorDefinition(200, OperatorType.YF, "postfix")) val term = prefix(postfix(a)) term.toStringUsingOperatorNotations(registry) shouldBe "prefix(a postfix)" } "FX nesting XFX" { val registry = DefaultOperatorRegistry() registry.defineOperator(OperatorDefinition(200, OperatorType.FX, "prefix")) registry.defineOperator(OperatorDefinition(200, OperatorType.XFX, "infix")) val term = prefix(infix(a, b)) term.toStringUsingOperatorNotations(registry) shouldBe "prefix(a infix b)" } "FX nesting XFY" { val registry = DefaultOperatorRegistry() registry.defineOperator(OperatorDefinition(200, OperatorType.FX, "prefix")) registry.defineOperator(OperatorDefinition(200, OperatorType.XFY, "infix")) val term = prefix(infix(a, b)) term.toStringUsingOperatorNotations(registry) shouldBe "prefix(a infix b)" } "FX nesting YFX" { val registry = DefaultOperatorRegistry() registry.defineOperator(OperatorDefinition(200, OperatorType.FX, "prefix")) registry.defineOperator(OperatorDefinition(200, OperatorType.YFX, "infix")) val term = prefix(infix(a, b)) term.toStringUsingOperatorNotations(registry) shouldBe "prefix(a infix b)" } "FY nesting XF" { val registry = DefaultOperatorRegistry() registry.defineOperator(OperatorDefinition(200, OperatorType.FY, "prefix")) registry.defineOperator(OperatorDefinition(200, OperatorType.XF, "postfix")) val term = prefix(postfix(a)) term.toStringUsingOperatorNotations(registry) shouldBe "prefix a postfix" } "FY nesting XFX" { val registry = DefaultOperatorRegistry() registry.defineOperator(OperatorDefinition(200, OperatorType.FY, "prefix")) registry.defineOperator(OperatorDefinition(200, OperatorType.XFX, "infix")) val term = prefix(infix(a, b)) term.toStringUsingOperatorNotations(registry) shouldBe "prefix a infix b" } "FY nesting XFY" { val registry = DefaultOperatorRegistry() registry.defineOperator(OperatorDefinition(200, OperatorType.FY, "prefix")) registry.defineOperator(OperatorDefinition(200, OperatorType.XFY, "infix")) val term = prefix(infix(a, b)) term.toStringUsingOperatorNotations(registry) shouldBe "prefix a infix b" } } } "postfix operator nesting" - { val a = Atom("a") val b = Atom("b") val prefix = CompoundBuilder("prefix") val postfix = CompoundBuilder("postfix") val infix = CompoundBuilder("infix") "postfix has higher priority" - { "nesting FX" { val registry = DefaultOperatorRegistry() registry.defineOperator(OperatorDefinition(200, OperatorType.FX, "prefix")) registry.defineOperator(OperatorDefinition(300, OperatorType.XF, "postfix")) val term = postfix(prefix(a)) term.toStringUsingOperatorNotations(registry) shouldBe "prefix a postfix" } "nesting FY" { val registry = DefaultOperatorRegistry() registry.defineOperator(OperatorDefinition(200, OperatorType.FY, "prefix")) registry.defineOperator(OperatorDefinition(300, OperatorType.XF, "postfix")) val term = postfix(prefix(a)) term.toStringUsingOperatorNotations(registry) shouldBe "prefix a postfix" } "nesting XFX" { val registry = DefaultOperatorRegistry() registry.defineOperator(OperatorDefinition(300, OperatorType.XF, "postfix")) registry.defineOperator(OperatorDefinition(200, OperatorType.XFX, "infix")) val term = postfix(infix(a, b)) term.toStringUsingOperatorNotations(registry) shouldBe "a infix b postfix" } "nesting XFY" { val registry = DefaultOperatorRegistry() registry.defineOperator(OperatorDefinition(300, OperatorType.XF, "postfix")) registry.defineOperator(OperatorDefinition(200, OperatorType.XFY, "infix")) val term = postfix(infix(a, b)) term.toStringUsingOperatorNotations(registry) shouldBe "a infix b postfix" } "nesting YFX" { val registry = DefaultOperatorRegistry() registry.defineOperator(OperatorDefinition(300, OperatorType.XF, "postfix")) registry.defineOperator(OperatorDefinition(200, OperatorType.YFX, "infix")) val term = postfix(infix(a, b)) term.toStringUsingOperatorNotations(registry) shouldBe "a infix b postfix" } } "postfix has lower priority" - { "nesting FX" { val registry = DefaultOperatorRegistry() registry.defineOperator(OperatorDefinition(200, OperatorType.FX, "prefix")) registry.defineOperator(OperatorDefinition(100, OperatorType.XF, "postfix")) val term = postfix(prefix(a)) term.toStringUsingOperatorNotations(registry) shouldBe "(prefix a) postfix" } "nesting FY" { val registry = DefaultOperatorRegistry() registry.defineOperator(OperatorDefinition(200, OperatorType.FY, "prefix")) registry.defineOperator(OperatorDefinition(100, OperatorType.XF, "postfix")) val term = postfix(prefix(a)) term.toStringUsingOperatorNotations(registry) shouldBe "(prefix a) postfix" } "nesting XFX" { val registry = DefaultOperatorRegistry() registry.defineOperator(OperatorDefinition(200, OperatorType.XF, "postfix")) registry.defineOperator(OperatorDefinition(300, OperatorType.XFX, "infix")) val term = postfix(infix(a, b)) term.toStringUsingOperatorNotations(registry) shouldBe "(a infix b) postfix" } "nesting XFY" { val registry = DefaultOperatorRegistry() registry.defineOperator(OperatorDefinition(200, OperatorType.XF, "postfix")) registry.defineOperator(OperatorDefinition(300, OperatorType.XFY, "infix")) val term = postfix(infix(a, b)) term.toStringUsingOperatorNotations(registry) shouldBe "(a infix b) postfix" } "nesting YFX" { val registry = DefaultOperatorRegistry() registry.defineOperator(OperatorDefinition(200, OperatorType.XF, "postfix")) registry.defineOperator(OperatorDefinition(300, OperatorType.YFX, "infix")) val term = postfix(infix(a, b)) term.toStringUsingOperatorNotations(registry) shouldBe "(a infix b) postfix" } } "equal priority" - { "XF nesting FX" { val registry = DefaultOperatorRegistry() registry.defineOperator(OperatorDefinition(200, OperatorType.FX, "prefix")) registry.defineOperator(OperatorDefinition(200, OperatorType.XF, "postfix")) val term = postfix(prefix(a)) term.toStringUsingOperatorNotations(registry) shouldBe "(prefix a) postfix" } "XF nesting FY" { val registry = DefaultOperatorRegistry() registry.defineOperator(OperatorDefinition(200, OperatorType.FY, "prefix")) registry.defineOperator(OperatorDefinition(200, OperatorType.XF, "postfix")) val term = postfix(prefix(a)) term.toStringUsingOperatorNotations(registry) shouldBe "(prefix a) postfix" } "XF nesting XFX" { val registry = DefaultOperatorRegistry() registry.defineOperator(OperatorDefinition(200, OperatorType.XF, "postfix")) registry.defineOperator(OperatorDefinition(200, OperatorType.XFX, "infix")) val term = postfix(infix(a, b)) term.toStringUsingOperatorNotations(registry) shouldBe "(a infix b) postfix" } "XF nesting XFY" { val registry = DefaultOperatorRegistry() registry.defineOperator(OperatorDefinition(200, OperatorType.XF, "postfix")) registry.defineOperator(OperatorDefinition(200, OperatorType.XFY, "infix")) val term = postfix(infix(a, b)) term.toStringUsingOperatorNotations(registry) shouldBe "(a infix b) postfix" } "XF nesting YFX" { val registry = DefaultOperatorRegistry() registry.defineOperator(OperatorDefinition(200, OperatorType.XF, "postfix")) registry.defineOperator(OperatorDefinition(200, OperatorType.YFX, "infix")) val term = postfix(infix(a, b)) term.toStringUsingOperatorNotations(registry) shouldBe "(a infix b) postfix" } "YF nesting XF" { val registry = DefaultOperatorRegistry() registry.defineOperator(OperatorDefinition(200, OperatorType.FX, "prefix")) registry.defineOperator(OperatorDefinition(200, OperatorType.YF, "postfix")) val term = postfix(prefix(a)) term.toStringUsingOperatorNotations(registry) shouldBe "prefix a postfix" } "YF nesting XFX" { val registry = DefaultOperatorRegistry() registry.defineOperator(OperatorDefinition(200, OperatorType.YF, "postfix")) registry.defineOperator(OperatorDefinition(200, OperatorType.XFX, "infix")) val term = postfix(infix(a, b)) term.toStringUsingOperatorNotations(registry) shouldBe "a infix b postfix" } "YF nesting XFY" { val registry = DefaultOperatorRegistry() registry.defineOperator(OperatorDefinition(200, OperatorType.YF, "postfix")) registry.defineOperator(OperatorDefinition(200, OperatorType.XFY, "infix")) val term = postfix(infix(a, b)) term.toStringUsingOperatorNotations(registry) shouldBe "(a infix b) postfix" } } } "infix nesting" - { val a = Atom("a") val b = Atom("b") val lhsPrefix = CompoundBuilder("lhsPrefix") val rhsPostfix = CompoundBuilder("rhsPostfix") val infix = CompoundBuilder("infix") "lhs lower priority, rhs lower priority" { val registry = DefaultOperatorRegistry() registry.defineOperator(OperatorDefinition(300, OperatorType.XFX, "infix")) registry.defineOperator(OperatorDefinition(200, OperatorType.FY, "lhsPrefix")) registry.defineOperator(OperatorDefinition(200, OperatorType.YF, "rhsPostfix")) val term = infix(lhsPrefix(a), rhsPostfix(b)) term.toStringUsingOperatorNotations(registry) shouldBe "lhsPrefix a infix b rhsPostfix" } "lhs lower priority, rhs higher priority" { val registry = DefaultOperatorRegistry() registry.defineOperator(OperatorDefinition(300, OperatorType.XFX, "infix")) registry.defineOperator(OperatorDefinition(200, OperatorType.FY, "lhsPrefix")) registry.defineOperator(OperatorDefinition(400, OperatorType.YF, "rhsPostfix")) val term = infix(lhsPrefix(a), rhsPostfix(b)) term.toStringUsingOperatorNotations(registry) shouldBe "lhsPrefix a infix (b rhsPostfix)" } "lhs higher priority, rhs lower priority" { val registry = DefaultOperatorRegistry() registry.defineOperator(OperatorDefinition(300, OperatorType.XFX, "infix")) registry.defineOperator(OperatorDefinition(400, OperatorType.FY, "lhsPrefix")) registry.defineOperator(OperatorDefinition(200, OperatorType.YF, "rhsPostfix")) val term = infix(lhsPrefix(a), rhsPostfix(b)) term.toStringUsingOperatorNotations(registry) shouldBe "(lhsPrefix a) infix b rhsPostfix" } "lhs higher priority, rhs higher priority" { val registry = DefaultOperatorRegistry() registry.defineOperator(OperatorDefinition(300, OperatorType.XFX, "infix")) registry.defineOperator(OperatorDefinition(400, OperatorType.FY, "lhsPrefix")) registry.defineOperator(OperatorDefinition(400, OperatorType.YF, "rhsPostfix")) val term = infix(lhsPrefix(a), rhsPostfix(b)) term.toStringUsingOperatorNotations(registry) shouldBe "(lhsPrefix a) infix (b rhsPostfix)" } } "invocation syntax" - { "plain" { val registry = DefaultOperatorRegistry() val term = CompoundTerm("foo", arrayOf( Atom("a"), Atom("b"), Atom("c") // there are no ternary operators in prolog )) term.toStringUsingOperatorNotations(registry) shouldBe "foo(a, b, c)" } "nested terms have operators" { val registry = DefaultOperatorRegistry() registry.defineOperator(OperatorDefinition(400, OperatorType.FX, "bar")) val term = CompoundTerm("foo", arrayOf( Atom("a"), CompoundTerm("bar", arrayOf(Atom("b"))), Atom("c") )) term.toStringUsingOperatorNotations(registry) shouldBe "foo(a, bar b, c)" } "nested uses comma operator" { val registry = DefaultOperatorRegistry() registry.defineOperator(OperatorDefinition(400, OperatorType.XFX, ",")) val term = CompoundTerm("foo", arrayOf( Atom("a"), Atom("b"), CompoundTerm(",", arrayOf(Atom("c"), Atom("d"))) )) term.toStringUsingOperatorNotations(registry) shouldBe "foo(a, b, (c , d))" } } })
mit
38a222b5e2ea5fd37c5d580f146a6328
41.236025
103
0.596402
5.007118
false
false
false
false
NephyProject/Penicillin
src/main/kotlin/jp/nephy/penicillin/endpoints/account/Profile.kt
1
3951
/* * The MIT License (MIT) * * Copyright (c) 2017-2019 Nephy Project Team * * 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. */ @file:Suppress("UNUSED", "PublicApiImplicitType") package jp.nephy.penicillin.endpoints.account import jp.nephy.penicillin.core.request.action.JsonObjectApiAction import jp.nephy.penicillin.core.request.formBody import jp.nephy.penicillin.core.session.post import jp.nephy.penicillin.endpoints.Account import jp.nephy.penicillin.endpoints.Option import jp.nephy.penicillin.models.User /** * Sets some values that users are able to set under the "Account" tab of their settings page. Only the parameters specified will be updated. * * [Twitter API reference](https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/post-account-update_profile) * * @param name Optional. Full name associated with the profile. * @param url URL associated with the profile. Will be prepended with `http://` if not present. * @param location The city or country describing where the user of the account is located. The contents are not normalized or geocoded in any way. * @param description A description of the user owning the account. * @param profileLinkColor Sets a hex value that controls the color scheme of links used on the authenticating user's profile page on twitter.com. This must be a valid hexadecimal value, and may be either three or six characters (ex: F00 or FF0000). This parameter replaces the deprecated (and separate) update_profile_colors API method. * @param includeEntities The entities node will not be included when set to *false*. * @param skipStatus When set to either true, t or 1 statuses will not be included in the returned user object. * @param options Optional. Custom parameters of this request. * @receiver [Account] endpoint instance. * @return [JsonObjectApiAction] for [User] model. */ fun Account.updateProfile( name: String? = null, url: String? = null, location: String? = null, description: String? = null, profileLinkColor: String? = null, includeEntities: Boolean? = null, skipStatus: Boolean? = null, birthdateYear: Int? = null, birthdateMonth: Int? = null, birthdateDay: Int? = null, vararg options: Option ) = client.session.post("/1.1/account/update_profile.json") { formBody( "name" to name, "url" to url, "location" to location, "description" to description, "profile_link_color" to profileLinkColor, "include_entities" to includeEntities, "skip_status" to skipStatus, "birthdate_year" to birthdateYear, "birthdate_month" to birthdateMonth, "birthdate_day" to birthdateDay, *options ) }.jsonObject<User>() /** * Shorthand extension property to [Account.updateProfile]. * @see Account.updateProfile */ val Account.updateProfile get() = updateProfile()
mit
c44da252553fe3e2a58e6c71e6eb3c11
44.94186
337
0.739053
4.212154
false
false
false
false
daemontus/Distributed-CTL-Model-Checker
src/main/kotlin/com/github/sybila/checker/operator/BoolOperator.kt
3
2151
package com.github.sybila.checker.operator import com.github.sybila.checker.Channel import com.github.sybila.checker.CheckerStats import com.github.sybila.checker.Operator class AndOperator<out Params : Any>( left: Operator<Params>, right: Operator<Params>, partition: Channel<Params> ) : LazyOperator<Params>(partition, { val result = partition.newLocalMutableMap(partitionId) val l = left.compute() val r = right.compute() CheckerStats.setOperator("And") partition.run { for ((state, value) in l.entries()) { if (state in r) { val and = value and r[state] if (and.isSat()) { result[state] = and } } } } result }) class OrOperator<out Params : Any>( left: Operator<Params>, right: Operator<Params>, partition: Channel<Params> ) : LazyOperator<Params>(partition, { val result = partition.newLocalMutableMap(partitionId) val l = left.compute() val r = right.compute() CheckerStats.setOperator("Or") partition.run { for ((state, value) in l.entries()) { if (state in r) { result[state] = value or r[state] } else { result[state] = value } } for ((state, value) in r.entries()) { if (state !in l) { result[state] = value } } } result }) class ComplementOperator<out Params : Any>( full: Operator<Params>, inner: Operator<Params>, partition: Channel<Params> ) : LazyOperator<Params>(partition, { val result = partition.newLocalMutableMap(partitionId) val f = full.compute() val i = inner.compute() CheckerStats.setOperator("Not") partition.run { for ((state, value) in f.entries()) { if (state in i) { val new = value and i[state].not() if (new.isSat()) { result[state] = new } } else { result[state] = value } } } result })
gpl-3.0
e54994c5ea164c045f03e2b8462f07f4
24.317647
58
0.541144
4.242604
false
false
false
false
AlmasB/FXGL
fxgl/src/main/kotlin/com/almasb/fxgl/dsl/components/DraggableComponent.kt
1
1594
/* * FXGL - JavaFX Game Library. The MIT License (MIT). * Copyright (c) AlmasB ([email protected]). * See LICENSE for details. */ package com.almasb.fxgl.dsl.components import com.almasb.fxgl.dsl.FXGL import com.almasb.fxgl.entity.component.Component import javafx.event.EventHandler import javafx.scene.input.MouseEvent /** * Allows entities to be dragged using mouse input. * Only works on entities without PhysicsComponent. * * @author Almas Baimagambetov ([email protected]) */ class DraggableComponent : Component() { var isDragging = false private set private var offsetX = 0.0 private var offsetY = 0.0 private val onPress = EventHandler<MouseEvent> { isDragging = true offsetX = FXGL.getInput().mouseXWorld - entity.x offsetY = FXGL.getInput().mouseYWorld - entity.y } private val onRelease = EventHandler<MouseEvent> { isDragging = false } override fun onAdded() { entity.viewComponent.addEventHandler(MouseEvent.MOUSE_PRESSED, onPress) entity.viewComponent.addEventHandler(MouseEvent.MOUSE_RELEASED, onRelease) } override fun onUpdate(tpf: Double) { if (!isDragging) return entity.setPosition(FXGL.getInput().mouseXWorld - offsetX, FXGL.getInput().mouseYWorld - offsetY) } override fun onRemoved() { entity.viewComponent.removeEventHandler(MouseEvent.MOUSE_PRESSED, onPress) entity.viewComponent.removeEventHandler(MouseEvent.MOUSE_RELEASED, onRelease) } override fun isComponentInjectionRequired(): Boolean = false }
mit
f36fee9636c4d25982321c359351ec6f
28.537037
104
0.709536
4.427778
false
false
false
false
AlmasB/FXGL
fxgl-samples/src/main/kotlin/dev/SandboxGameApp.kt
1
3914
/* * FXGL - JavaFX Game Library. The MIT License (MIT). * Copyright (c) AlmasB ([email protected]). * See LICENSE for details. */ package dev import com.almasb.fxgl.app.GameApplication import com.almasb.fxgl.app.GameSettings import com.almasb.fxgl.dsl.* import com.almasb.fxgl.entity.Entity import javafx.beans.property.IntegerProperty import javafx.scene.input.KeyCode import javafx.scene.input.KeyEvent import javafx.scene.input.MouseButton import javafx.util.Duration import kotlin.collections.set /** * * @author Almas Baimagambetov ([email protected]) */ class SandboxGameApp : GameApplication() { override fun initSettings(settings: GameSettings) { with(settings) { width = 720 height = 640 title = "Kotlin Game" } } companion object { val conditionals = hashMapOf<() -> Boolean, () -> Unit>() } override fun initGameVars(vars: MutableMap<String, Any>) { vars["score"] = 0 } private enum class AIType { IDLE, GUARD } override fun initInput() { onBtnDown(MouseButton.PRIMARY) { fire(KeyEvent(KeyEvent.KEY_PRESSED, "", "", KeyCode.K, false, false, false, false)) } } override fun initGame() { // DSL test // getEventBus().addEventHandler(KeyEvent.KEY_PRESSED, EventHandler { // println(it.code) // }) onEvent(KeyEvent.KEY_PRESSED) { event -> println(event.code) } eventBuilder() .interval(Duration.seconds(2.0)) .`when` { true } .thenFire { KeyEvent(KeyEvent.KEY_PRESSED, "", "", KeyCode.K, false, false, false, false) } .limit(3) .buildAndStart() } // override fun initGame() { // val player = entityBuilder().at(100.0, 100.0) // .viewWithBBox(Rectangle(20.0, 20.0)) // .with(DeveloperWASDControl()) // .buildAndAttach() // // val enemy = entityBuilder().at(100.0, 100.0) // .viewWithBBox(Rectangle(20.0, 20.0, Color.RED)) // .buildAndAttach() // // val gate = entityBuilder().at(300.0, 100.0) // .viewWithBBox(Rectangle(20.0, 20.0, Color.RED)) // .buildAndAttach() // // val t = Text("HELLO WORLD") // t.textProperty().bind(getip("score").asString()) // // addUINode(t, 100.0, 200.0) // // // when e.x > 150 then println("Hello") // // val invisibleBlock = entityBuilder().at(300.0, 100.0) // .viewWithBBox(Rectangle(20.0, 20.0, Color.RED)) // .buildAndAttach() // // // `when` { player.x > 150 } then { enemy AI GUARD } // // `when` { player collidesWith enemy } then { getip("score") decrease 1 } // // `when` { gate `is` "open" } then { invisibleBlock.removeFromWorld() } // } private infix fun Entity.`is`(propName: String): Boolean { return this.getBoolean(propName) } private infix fun IntegerProperty.decrease(value: Int) { this.value -= value } private infix fun Entity.AI(aiType: AIType) { } private infix fun Entity.collidesWith(other: Entity): Boolean { return this.isColliding(other) } infix fun remove(e: Entity) { } private infix fun `when`(condition: () -> Boolean): ConditionBuilder { return ConditionBuilder(condition) } private class ConditionBuilder(private val condition: () -> Boolean) { infix fun then(action: () -> Unit) { conditionals[condition] = action } } override fun onUpdate(tpf: Double) { // conditionals.forEach { condition, action -> // if (condition()) // action() // } } } fun main() { GameApplication.launch(SandboxGameApp::class.java, emptyArray()) }
mit
8f480526e2ca8fa0b63346656e7ff048
26
107
0.57537
3.859961
false
false
false
false
RP-Kit/RPKit
bukkit/rpk-monsters-bukkit/src/main/kotlin/com/rpkit/monsters/bukkit/monsterspawnarea/RPKMonsterSpawnAreaImpl.kt
1
3966
/* * Copyright 2022 Ren Binden * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.rpkit.monsters.bukkit.monsterspawnarea import com.rpkit.core.location.RPKBlockLocation import com.rpkit.monsters.bukkit.RPKMonstersBukkit import com.rpkit.monsters.bukkit.database.table.RPKMonsterSpawnAreaMonsterTable import com.rpkit.monsters.bukkit.database.table.RPKMonsterSpawnAreaTable import org.bukkit.entity.EntityType import java.util.concurrent.CompletableFuture import java.util.logging.Level class RPKMonsterSpawnAreaImpl( private val plugin: RPKMonstersBukkit, override var id: RPKMonsterSpawnAreaId? = null, override val minPoint: RPKBlockLocation, override val maxPoint: RPKBlockLocation, override val allowedMonsters: MutableSet<EntityType>, private val minLevels: MutableMap<EntityType, Int>, private val maxLevels: MutableMap<EntityType, Int> ) : RPKMonsterSpawnArea { constructor( plugin: RPKMonstersBukkit, id: RPKMonsterSpawnAreaId? = null, minPoint: RPKBlockLocation, maxPoint: RPKBlockLocation ): this(plugin, id, minPoint, maxPoint, mutableSetOf(), mutableMapOf(), mutableMapOf()) @Synchronized override fun getMinLevel(entityType: EntityType): Int { if (!allowedMonsters.contains(entityType)) return 0 return minLevels[entityType] ?: 1 } @Synchronized override fun getMaxLevel(entityType: EntityType): Int { if (!allowedMonsters.contains(entityType)) return 0 return maxLevels[entityType] ?: 1 } override fun addMonster(entityType: EntityType, minLevel: Int, maxLevel: Int): CompletableFuture<Void> { return CompletableFuture.runAsync { if (id == null) plugin.database.getTable(RPKMonsterSpawnAreaTable::class.java).insert(this).join() }.thenRunAsync { val finalId = id if (finalId != null) { plugin.database.getTable(RPKMonsterSpawnAreaMonsterTable::class.java).insert( finalId, RPKMonsterSpawnAreaMonster( entityType = entityType, minLevel = minLevel, maxLevel = maxLevel ) ).join() synchronized(this) { allowedMonsters.add(entityType) minLevels[entityType] = minLevel maxLevels[entityType] = maxLevel } } }.exceptionally { exception -> plugin.logger.log(Level.SEVERE, "Failed to add monster to monster spawn area", exception) throw exception } } override fun removeMonster(entityType: EntityType): CompletableFuture<Void> { val finalId = id ?: return CompletableFuture.completedFuture(null) val monsterSpawnAreaMonsterTable = plugin.database.getTable(RPKMonsterSpawnAreaMonsterTable::class.java) return monsterSpawnAreaMonsterTable.get(finalId).thenAccept { monsters -> monsters .filter { monster -> monster.entityType == entityType } .forEach { monsterSpawnAreaMonsterTable.delete(finalId, it) synchronized(this) { allowedMonsters.remove(entityType) minLevels.remove(entityType) maxLevels.remove(entityType) } } } } }
apache-2.0
d0653cb498ddf7fa7ef0fc98a645a347
39.070707
112
0.657085
4.902349
false
false
false
false
RP-Kit/RPKit
bukkit/rpk-permissions-bukkit/src/main/kotlin/com/rpkit/permissions/bukkit/command/charactergroup/CharacterGroupAddCommand.kt
1
3801
/* * Copyright 2021 Ren Binden * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.rpkit.permissions.bukkit.command.charactergroup import com.rpkit.characters.bukkit.character.RPKCharacterService import com.rpkit.core.service.Services import com.rpkit.permissions.bukkit.RPKPermissionsBukkit import com.rpkit.permissions.bukkit.group.RPKGroupName import com.rpkit.permissions.bukkit.group.RPKGroupService import com.rpkit.permissions.bukkit.group.addGroup import com.rpkit.players.bukkit.profile.minecraft.RPKMinecraftProfileService import org.bukkit.command.Command import org.bukkit.command.CommandExecutor import org.bukkit.command.CommandSender /** * Group add command. * Adds a player to a group. */ class CharacterGroupAddCommand(private val plugin: RPKPermissionsBukkit) : CommandExecutor { override fun onCommand(sender: CommandSender, command: Command, label: String, args: Array<out String>): Boolean { if (!sender.hasPermission("rpkit.permissions.command.charactergroup.add")) { sender.sendMessage(plugin.messages.noPermissionCharacterGroupAdd) return true } if (args.size <= 1) { sender.sendMessage(plugin.messages.characterGroupAddUsage) return true } val minecraftProfileService = Services[RPKMinecraftProfileService::class.java] if (minecraftProfileService == null) { sender.sendMessage(plugin.messages.noMinecraftProfileService) return true } val groupService = Services[RPKGroupService::class.java] if (groupService == null) { sender.sendMessage(plugin.messages.noGroupService) return true } val bukkitPlayer = plugin.server.getPlayer(args[0]) if (bukkitPlayer == null) { sender.sendMessage(plugin.messages.characterGroupAddInvalidPlayer) return true } val minecraftProfile = minecraftProfileService.getPreloadedMinecraftProfile(bukkitPlayer) if (minecraftProfile == null) { sender.sendMessage(plugin.messages.noMinecraftProfileOther) return true } val characterService = Services[RPKCharacterService::class.java] if (characterService == null) { sender.sendMessage(plugin.messages.noCharacterService) return true } val character = characterService.getPreloadedActiveCharacter(minecraftProfile) if (character == null) { sender.sendMessage(plugin.messages.noCharacter) return true } val group = groupService.getGroup(RPKGroupName(args[1])) if (group == null) { sender.sendMessage(plugin.messages.characterGroupAddInvalidGroup) return true } if (!sender.hasPermission("rpkit.permissions.command.charactergroup.add.${group.name.value}")) { sender.sendMessage(plugin.messages.noPermissionCharacterGroupAddGroup.withParameters( group = group )) return true } character.addGroup(group) sender.sendMessage(plugin.messages.characterGroupAddValid.withParameters( group = group, character = character )) return true } }
apache-2.0
230345097a063fde69ec91cb30246c83
39.88172
118
0.693765
4.891892
false
false
false
false
ujpv/intellij-rust
src/main/kotlin/org/rust/lang/core/types/visitors/RustTypeVisitorWithDefaults.kt
1
1170
package org.rust.lang.core.types.visitors import org.rust.lang.core.types.* abstract class RustTypeVisitorWithDefaults<T> : RustTypeVisitor<T> { protected abstract fun visitByDefault(type: RustType): T override fun visitStruct(type: RustStructType): T = visitByDefault(type) override fun visitTupleType(type: RustTupleType): T = visitByDefault(type) override fun visitUnknown(type: RustUnknownType): T = visitByDefault(type) override fun visitUnitType(type: RustUnitType): T = visitByDefault(type) override fun visitFunctionType(type: RustFunctionType): T = visitByDefault(type) override fun visitEnum(type: RustEnumType): T = visitByDefault(type) override fun visitInteger(type: RustIntegerType): T = visitByDefault(type) override fun visitReference(type: RustReferenceType): T = visitByDefault(type) override fun visitFloat(type: RustFloatType): T = visitByDefault(type) override fun visitString(type: RustStringSliceType): T = visitByDefault(type) override fun visitChar(type: RustCharacterType): T = visitByDefault(type) override fun visitBoolean(type: RustBooleanType): T = visitByDefault(type) }
mit
234527c492f3234f653e488e67c0ca9c
34.454545
84
0.764957
4.193548
false
false
false
false
NoodleMage/tachiyomi
app/src/main/java/eu/kanade/tachiyomi/ui/reader/viewer/base/BaseReader.kt
2
7290
package eu.kanade.tachiyomi.ui.reader.viewer.base import android.support.v4.app.Fragment import com.davemorrissey.labs.subscaleview.decoder.* import eu.kanade.tachiyomi.data.preference.getOrDefault import eu.kanade.tachiyomi.source.model.Page import eu.kanade.tachiyomi.ui.reader.ReaderActivity import eu.kanade.tachiyomi.ui.reader.ReaderChapter import java.util.* /** * Base reader containing the common data that can be used by its implementations. It does not * contain any UI related action. */ abstract class BaseReader : Fragment() { companion object { /** * Image decoder. */ const val IMAGE_DECODER = 0 /** * Rapid decoder. */ const val RAPID_DECODER = 1 /** * Skia decoder. */ const val SKIA_DECODER = 2 } /** * List of chapters added in the reader. */ private val chapters = ArrayList<ReaderChapter>() /** * List of pages added in the reader. It can contain pages from more than one chapter. */ var pages: MutableList<Page> = ArrayList() private set /** * Current visible position of [pages]. */ var currentPage: Int = 0 protected set /** * Region decoder class to use. */ lateinit var regionDecoderClass: Class<out ImageRegionDecoder> private set /** * Bitmap decoder class to use. */ lateinit var bitmapDecoderClass: Class<out ImageDecoder> private set /** * Whether tap navigation is enabled or not. */ val tappingEnabled by lazy { readerActivity.preferences.readWithTapping().getOrDefault() } /** * Whether the reader has requested to append a chapter. Used with seamless mode to avoid * restarting requests when changing pages. */ private var hasRequestedNextChapter: Boolean = false /** * Returns the active page. */ fun getActivePage(): Page? { return pages.getOrNull(currentPage) } /** * Called when a page changes. Implementations must call this method. * * @param position the new current page. */ fun onPageChanged(position: Int) { val oldPage = pages[currentPage] val newPage = pages[position] val oldChapter = oldPage.chapter val newChapter = newPage.chapter // Update page indicator and seekbar readerActivity.onPageChanged(newPage) // Active chapter has changed. if (oldChapter.id != newChapter.id) { readerActivity.onEnterChapter(newPage.chapter, newPage.index) } // Request next chapter only when the conditions are met. if (pages.size - position < 5 && chapters.last().id == newChapter.id && readerActivity.presenter.hasNextChapter() && !hasRequestedNextChapter) { hasRequestedNextChapter = true readerActivity.presenter.appendNextChapter() } currentPage = position } /** * Sets the active page. * * @param page the page to display. */ fun setActivePage(page: Page) { setActivePage(getPageIndex(page)) } /** * Searchs for the index of a page in the current list without requiring them to be the same * object. * * @param search the page to search. * @return the index of the page in [pages] or 0 if it's not found. */ fun getPageIndex(search: Page): Int { for ((index, page) in pages.withIndex()) { if (page.index == search.index && page.chapter.id == search.chapter.id) { return index } } return 0 } /** * Called from the presenter when the page list of a chapter is ready. This method is called * on every [onResume], so we add some logic to avoid duplicating chapters. * * @param chapter the chapter to set. * @param currentPage the initial page to display. */ fun onPageListReady(chapter: ReaderChapter, currentPage: Page) { if (!chapters.contains(chapter)) { // if we reset the loaded page we also need to reset the loaded chapters chapters.clear() chapters.add(chapter) pages = ArrayList(chapter.pages) onChapterSet(chapter, currentPage) } else { setActivePage(currentPage) } } /** * Called from the presenter when the page list of a chapter to append is ready. This method is * called on every [onResume], so we add some logic to avoid duplicating chapters. * * @param chapter the chapter to append. */ fun onPageListAppendReady(chapter: ReaderChapter) { if (!chapters.contains(chapter)) { hasRequestedNextChapter = false chapters.add(chapter) pages.addAll(chapter.pages!!) onChapterAppended(chapter) } } /** * Sets the active page. * * @param pageNumber the index of the page from [pages]. */ abstract fun setActivePage(pageNumber: Int) /** * Called when a new chapter is set in [BaseReader]. * * @param chapter the chapter set. * @param currentPage the initial page to display. */ abstract fun onChapterSet(chapter: ReaderChapter, currentPage: Page) /** * Called when a chapter is appended in [BaseReader]. * * @param chapter the chapter appended. */ abstract fun onChapterAppended(chapter: ReaderChapter) /** * Moves pages to right. Implementations decide how to move (by a page, by some distance...). */ abstract fun moveRight() /** * Moves pages to left. Implementations decide how to move (by a page, by some distance...). */ abstract fun moveLeft() /** * Moves pages down. Implementations decide how to move (by a page, by some distance...). */ open fun moveDown() { moveRight() } /** * Moves pages up. Implementations decide how to move (by a page, by some distance...). */ open fun moveUp() { moveLeft() } /** * Method the implementations can call to show a menu with options for the given page. */ fun onLongClick(page: Page?): Boolean { if (isAdded && page != null) { readerActivity.onLongClick(page) } return true } /** * Sets the active decoder class. * * @param value the decoder class to use. */ fun setDecoderClass(value: Int) { when (value) { IMAGE_DECODER -> { bitmapDecoderClass = IImageDecoder::class.java regionDecoderClass = IImageRegionDecoder::class.java } RAPID_DECODER -> { bitmapDecoderClass = RapidImageDecoder::class.java regionDecoderClass = RapidImageRegionDecoder::class.java } SKIA_DECODER -> { bitmapDecoderClass = SkiaImageDecoder::class.java regionDecoderClass = SkiaImageRegionDecoder::class.java } } } /** * Property to get the reader activity. */ val readerActivity: ReaderActivity get() = activity as ReaderActivity }
apache-2.0
8405b1f96141bbf04bf5f1f444a2df25
27.814229
99
0.604801
4.613924
false
false
false
false
mua-uniandes/weekly-problems
livearchive/127/12788.kt
1
972
package uvalive import java.io.BufferedReader import java.io.InputStreamReader fun main(args: Array<String>) { val In = BufferedReader(InputStreamReader(System.`in`)) var line = In.readLine()!! while (line != null) { val n = line.toInt() val nums = In.readLine()!!.split(" ").map { it.toInt() } println(getAns(nums, n)) line = In.readLine()!! } } fun getAns(nums: List<Int>, n: Int): Int { // Base case if (n == 1) { return 1 } // Count sequences val sums = ArrayList<Int>() var count = 1 for (i in 1 until n) { if (nums[i - 1] <= nums[i]) { count += 1 } else { sums.add(count) count = 1 } } sums.add(count) // Get biggets 2-sum if (sums.size == 1) { return sums[0] } var ans = 0 for (i in 0 until sums.size - 1) { ans = Math.max(sums[i] + sums[i + 1], ans) } return ans }
gpl-3.0
65b77a1be4f99bdb92275b5057f3b119
21.113636
64
0.507202
3.294915
false
false
false
false
ngageoint/mage-android
mage/src/main/java/mil/nga/giat/mage/form/field/BooleanFieldState.kt
1
651
package mil.nga.giat.mage.form.field import mil.nga.giat.mage.form.FormField class BooleanFieldState(definition: FormField<Boolean>) : FieldState<Boolean, FieldValue.Boolean>( definition, validator = ::isValid, errorFor = ::errorMessage, hasValue = ::hasValue ) private fun errorMessage(definition: FormField<Boolean>, value: FieldValue.Boolean?): String { return "${definition.title} is required" } private fun isValid(definition: FormField<Boolean>, value: FieldValue.Boolean?): Boolean { return !definition.required || value?.boolean == true } private fun hasValue(value: FieldValue.Boolean?): Boolean { return true }
apache-2.0
7365f95d59e3db5d2c79cbea605b4c92
27.347826
94
0.741935
4.146497
false
false
false
false
Magneticraft-Team/Magneticraft
src/main/kotlin/com/cout970/magneticraft/registry/Capabilities.kt
2
8868
package com.cout970.magneticraft.registry import com.cout970.magneticraft.api.computer.IFloppyDisk import com.cout970.magneticraft.api.conveyorbelt.IConveyorBelt import com.cout970.magneticraft.api.conveyorbelt.Route import com.cout970.magneticraft.api.core.INode import com.cout970.magneticraft.api.core.INodeHandler import com.cout970.magneticraft.api.core.ITileRef import com.cout970.magneticraft.api.core.NodeID import com.cout970.magneticraft.api.energy.IElectricConnection import com.cout970.magneticraft.api.energy.IElectricNode import com.cout970.magneticraft.api.energy.IElectricNodeHandler import com.cout970.magneticraft.api.energy.IManualConnectionHandler import com.cout970.magneticraft.api.heat.IHeatConnection import com.cout970.magneticraft.api.heat.IHeatNode import com.cout970.magneticraft.api.heat.IHeatNodeHandler import com.cout970.magneticraft.api.pneumatic.ITubeConnectable import com.cout970.magneticraft.api.pneumatic.PneumaticBox import com.cout970.magneticraft.api.pneumatic.PneumaticMode import com.cout970.magneticraft.api.tool.IGear import com.cout970.magneticraft.features.items.ComputerItems import com.cout970.magneticraft.systems.computer.FloppyDisk import com.cout970.magneticraft.systems.tilemodules.conveyorbelt.BoxedItem import net.minecraft.block.Block import net.minecraft.entity.Entity import net.minecraft.entity.player.EntityPlayer import net.minecraft.item.ItemStack import net.minecraft.nbt.NBTBase import net.minecraft.nbt.NBTTagCompound import net.minecraft.tileentity.TileEntity import net.minecraft.util.EnumFacing import net.minecraft.util.math.BlockPos import net.minecraft.world.World import net.minecraftforge.common.capabilities.Capability import net.minecraftforge.common.capabilities.CapabilityInject import net.minecraftforge.common.capabilities.CapabilityManager import net.minecraftforge.common.capabilities.ICapabilityProvider import net.minecraftforge.energy.IEnergyStorage import net.minecraftforge.fluids.capability.IFluidHandler import net.minecraftforge.fluids.capability.IFluidHandlerItem import net.minecraftforge.items.IItemHandler /** * Stores instances of Capabilities * to use them you need to add !! at the end * for example: * ITEM_HANDLER!!.fromTile(tile) */ @CapabilityInject(IItemHandler::class) var ITEM_HANDLER: Capability<IItemHandler>? = null @CapabilityInject(IElectricNodeHandler::class) var ELECTRIC_NODE_HANDLER: Capability<IElectricNodeHandler>? = null @CapabilityInject(IHeatNodeHandler::class) var HEAT_NODE_HANDLER: Capability<IHeatNodeHandler>? = null @CapabilityInject(IManualConnectionHandler::class) var MANUAL_CONNECTION_HANDLER: Capability<IManualConnectionHandler>? = null @CapabilityInject(IFluidHandler::class) var FLUID_HANDLER: Capability<IFluidHandler>? = null @CapabilityInject(IFluidHandlerItem::class) var ITEM_FLUID_HANDLER: Capability<IFluidHandlerItem>? = null @CapabilityInject(IEnergyStorage::class) var FORGE_ENERGY: Capability<IEnergyStorage>? = null @CapabilityInject(IFloppyDisk::class) var ITEM_FLOPPY_DISK: Capability<IFloppyDisk>? = null @CapabilityInject(IGear::class) var ITEM_GEAR: Capability<IGear>? = null @CapabilityInject(ITubeConnectable::class) var TUBE_CONNECTABLE: Capability<ITubeConnectable>? = null @CapabilityInject(IConveyorBelt::class) var CONVEYOR_BELT: Capability<IConveyorBelt>? = null /** * This is called on the server and the client at preInit */ fun registerCapabilities() { CapabilityManager.INSTANCE.apply { register(IElectricNodeHandler::class.java, EmptyStorage()) { DefaultElectricNodeProvider() } register(IHeatNodeHandler::class.java, EmptyStorage()) { DefaultHeatNodeProvider() } register(IManualConnectionHandler::class.java, EmptyStorage()) { DefaultManualConnectionHandler() } register(IGear::class.java, EmptyStorage()) { DefaultGear() } register(ITubeConnectable::class.java, EmptyStorage()) { DefaultTubeConnectable() } register(IConveyorBelt::class.java, EmptyStorage()) { DefaultConveyorBelt() } register(IFloppyDisk::class.java, EmptyStorage()) { FloppyDisk( ItemStack(ComputerItems.floppyDisk, 1, 0, ComputerItems.createNBT(128, read = true, write = true) ) ) } } } /** * Extension functions to get capabilities from TileEntities, Blocks and Items */ fun <T> Capability<T>.fromTile(tile: TileEntity, side: EnumFacing? = null): T? { if (tile.hasCapability(this, side)) { return tile.getCapability(this, side) } return null } fun <T> Capability<T>.fromEntity(tile: Entity, side: EnumFacing? = null): T? { if (tile.hasCapability(this, side)) { return tile.getCapability(this, side) } return null } fun <T> Capability<T>.fromBlock(block: Block, side: EnumFacing? = null): T? { if (block is ICapabilityProvider && block.hasCapability(this, side)) { return block.getCapability(this, side) } return null } fun <T> Capability<T>.fromItem(tile: ItemStack): T? { if (tile.hasCapability(this, null)) { return tile.getCapability(this, null) } return null } fun <T> TileEntity.getOrNull(cap: Capability<T>?, side: EnumFacing?): T? { cap ?: return null if (this.hasCapability(cap, side)) { return this.getCapability(cap, side) } return null } /** * Empty implementation of IStorage * At some point this should be changed, or just ignored */ class EmptyStorage<T> : Capability.IStorage<T> { override fun writeNBT(capability: Capability<T>?, instance: T, side: EnumFacing?): NBTBase? = NBTTagCompound() override fun readNBT(capability: Capability<T>?, instance: T, side: EnumFacing?, nbt: NBTBase?) = Unit } /** * Default implementation of API interfaces, used to register Capabilities */ class DefaultElectricNodeProvider : INodeHandler, IElectricNodeHandler { override fun getNode(id: NodeID): INode? = null override fun getNodes(): List<INode> = listOf() override fun getRef(): ITileRef { throw NotImplementedError("DefaultNodeProvider doesn't have a parent TileEntity") } override fun getInputConnections(): MutableList<IElectricConnection> = mutableListOf() override fun getOutputConnections(): MutableList<IElectricConnection> = mutableListOf() override fun canConnect(thisNode: IElectricNode?, other: IElectricNodeHandler?, otherNode: IElectricNode?, side: EnumFacing?): Boolean { return false } override fun addConnection(connection: IElectricConnection?, side: EnumFacing?, output: Boolean) = Unit override fun removeConnection(connection: IElectricConnection?) = Unit } class DefaultHeatNodeProvider : INodeHandler, IHeatNodeHandler { override fun getNode(id: NodeID): INode? = null override fun getNodes(): List<INode> = listOf() override fun getRef(): ITileRef { throw NotImplementedError("DefaultNodeProvider doesn't have a parent TileEntity") } override fun getInputConnections(): MutableList<IHeatConnection> = mutableListOf() override fun getOutputConnections(): MutableList<IHeatConnection> = mutableListOf() override fun canConnect(thisNode: IHeatNode?, other: IHeatNodeHandler?, otherNode: IHeatNode?, side: EnumFacing): Boolean { return false } override fun addConnection(connection: IHeatConnection?, side: EnumFacing, output: Boolean) = Unit override fun removeConnection(connection: IHeatConnection?) = Unit } class DefaultManualConnectionHandler : IManualConnectionHandler { override fun getBasePos(thisBlock: BlockPos, world: World, player: EntityPlayer, side: EnumFacing, stack: ItemStack): BlockPos? = thisBlock override fun connectWire(otherBlock: BlockPos, thisBlock: BlockPos, world: World, player: EntityPlayer, side: EnumFacing, stack: ItemStack) = IManualConnectionHandler.Result.ERROR } class DefaultGear : IGear { override fun getSpeedMultiplier(): Float = 1f override fun getMaxDurability(): Int = 0 override fun getDurability(): Int = 0 override fun applyDamage(stack: ItemStack): ItemStack = ItemStack.EMPTY } class DefaultTubeConnectable : ITubeConnectable { override fun insert(box: PneumaticBox, mode: PneumaticMode): Boolean = false override fun canInsert(box: PneumaticBox, mode: PneumaticMode): Boolean = false override fun getWeight(): Int = 0 } class DefaultConveyorBelt : IConveyorBelt { override fun getFacing(): EnumFacing = EnumFacing.NORTH override fun getBoxes(): MutableList<BoxedItem> = mutableListOf() override fun getLevel(): Int = 0 override fun addItem(stack: ItemStack, simulated: Boolean): Boolean = false override fun addItem(stack: ItemStack, side: EnumFacing, oldRoute: Route): Boolean = false }
gpl-2.0
3d7bf425003414732037a654427bf7e2
37.899123
127
0.755864
4.171214
false
false
false
false
mozilla-mobile/focus-android
app/src/main/java/org/mozilla/focus/settings/privacy/PreferenceSwitch.kt
1
1810
package org.mozilla.focus.settings.privacy import android.content.Context import android.util.AttributeSet import androidx.appcompat.widget.SwitchCompat import androidx.core.content.edit import androidx.core.content.withStyledAttributes import androidx.preference.PreferenceManager import org.mozilla.focus.R class PreferenceSwitch( context: Context, attrs: AttributeSet, ) : SwitchCompat(context, attrs) { private var clickListener: (() -> Unit)? = null var key: Int = 0 var title: Int = 0 var description: Int = 0 init { context.withStyledAttributes( attrs, R.styleable.PreferenceSwitch, 0, 0, ) { key = getResourceId(R.styleable.PreferenceSwitch_preferenceKey, 0) title = getResourceId(R.styleable.PreferenceSwitch_preferenceKeyTitle, 0) description = getResourceId(R.styleable.PreferenceSwitch_preferenceKeyDescription, 0) } } init { setInitialValue() setOnCheckedChangeListener(null) setOnClickListener { togglePreferenceValue(this.isChecked) clickListener?.invoke() } if (title != 0) { this.text = context.getString(title) } } private fun setInitialValue() { this.isChecked = PreferenceManager.getDefaultSharedPreferences(context) .getBoolean(context.getString(key), true) } fun onClickListener(listener: () -> Unit) { clickListener = listener } private fun togglePreferenceValue(isChecked: Boolean) { this.isChecked = isChecked PreferenceManager.getDefaultSharedPreferences(context).edit(commit = true) { putBoolean(context.getString(key), isChecked) } } }
mpl-2.0
88fa44caaf5c76e3ec124ead701b375f
27.28125
87
0.650829
5
false
false
false
false
facebook/litho
litho-widget-kotlin/src/main/kotlin/com/facebook/litho/widget/collection/LazyList.kt
1
4105
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.facebook.litho.widget.collection import androidx.recyclerview.widget.RecyclerView import com.facebook.litho.Component import com.facebook.litho.ComponentContext import com.facebook.litho.Dimen import com.facebook.litho.Handle import com.facebook.litho.LithoStartupLogger import com.facebook.litho.ResourcesScope import com.facebook.litho.Style import com.facebook.litho.widget.LithoRecyclerView import com.facebook.litho.widget.SnapUtil /** A scrollable collection of components arranged linearly */ inline fun ResourcesScope.LazyList( @RecyclerView.Orientation orientation: Int = RecyclerView.VERTICAL, @SnapUtil.SnapMode snapMode: Int = SnapUtil.SNAP_NONE, reverse: Boolean = false, crossAxisWrapMode: CrossAxisWrapMode = CrossAxisWrapMode.NoWrap, mainAxisWrapContent: Boolean = false, itemAnimator: RecyclerView.ItemAnimator? = null, itemDecoration: RecyclerView.ItemDecoration? = null, clipToPadding: Boolean? = null, clipChildren: Boolean? = null, startPadding: Dimen? = null, endPadding: Dimen? = null, topPadding: Dimen? = null, bottomPadding: Dimen? = null, nestedScrollingEnabled: Boolean? = null, scrollBarStyle: Int? = null, recyclerViewId: Int? = null, overScrollMode: Int? = null, refreshProgressBarColor: Int? = null, touchInterceptor: LithoRecyclerView.TouchInterceptor? = null, itemTouchListener: RecyclerView.OnItemTouchListener? = null, sectionTreeTag: String? = null, startupLogger: LithoStartupLogger? = null, style: Style? = null, noinline onViewportChanged: OnViewportChanged? = null, noinline onDataBound: ((c: ComponentContext) -> Unit)? = null, handle: Handle? = null, noinline onPullToRefresh: (() -> Unit)? = null, onNearEnd: OnNearCallback? = null, onScrollListener: RecyclerView.OnScrollListener? = null, onScrollListeners: List<RecyclerView.OnScrollListener?>? = null, lazyCollectionController: LazyCollectionController? = null, noinline onDataRendered: OnDataRendered? = null, rangeRatio: Float? = null, useBackgroundChangeSets: Boolean = false, isReconciliationEnabled: Boolean = false, childEquivalenceIncludesCommonProps: Boolean = true, overlayRenderCount: Boolean = false, alwaysDetectDuplicates: Boolean = false, noinline init: LazyListScope.() -> Unit ): Component { val lazyListScope = LazyListScope(context).apply { init() } return LazyCollection( layout = CollectionLayouts.Linear( orientation, snapMode, reverse, rangeRatio, useBackgroundChangeSets, isReconciliationEnabled, crossAxisWrapMode, mainAxisWrapContent), itemAnimator, itemDecoration, clipToPadding, clipChildren, startPadding, endPadding, topPadding, bottomPadding, nestedScrollingEnabled, scrollBarStyle, recyclerViewId, overScrollMode, refreshProgressBarColor, touchInterceptor, itemTouchListener, sectionTreeTag, startupLogger, style, onViewportChanged, onDataBound, handle, onPullToRefresh, onNearEnd, onScrollListener, onScrollListeners, lazyCollectionController, onDataRendered, childEquivalenceIncludesCommonProps, overlayRenderCount, alwaysDetectDuplicates, lazyListScope.children) }
apache-2.0
ca66a70addadb8ee3d819658776e5bdc
34.387931
75
0.713276
4.675399
false
false
false
false
google/horologist
media-sample/src/main/java/com/google/android/horologist/mediasample/di/SyncModule.kt
1
4423
/* * Copyright 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.horologist.mediasample.di import android.content.Context import com.google.android.horologist.media.data.datasource.MediaLocalDataSource import com.google.android.horologist.media.data.datasource.PlaylistLocalDataSource import com.google.android.horologist.media.data.mapper.PlaylistMapper import com.google.android.horologist.media.sync.api.ChangeListVersionRepository import com.google.android.horologist.media.sync.api.CoroutineDispatcherProvider import com.google.android.horologist.media.sync.api.NotificationConfigurationProvider import com.google.android.horologist.media.sync.api.Syncable import com.google.android.horologist.mediasample.R import com.google.android.horologist.mediasample.data.api.NetworkChangeListService import com.google.android.horologist.mediasample.data.datasource.PlaylistRemoteDataSource import com.google.android.horologist.mediasample.data.repository.PlaylistRepositorySyncable import com.google.android.horologist.mediasample.di.annotation.Dispatcher import com.google.android.horologist.mediasample.di.annotation.UampDispatchers.IO import dagger.Module import dagger.Provides import dagger.hilt.InstallIn import dagger.hilt.android.qualifiers.ApplicationContext import dagger.hilt.components.SingletonComponent import kotlinx.coroutines.CoroutineDispatcher import javax.inject.Singleton @Module @InstallIn(SingletonComponent::class) object SyncModule { const val CHANGE_LIST_VERSION = 1 @Singleton @Provides fun coroutineDispatcherProvider( @Dispatcher(IO) ioDispatcher: CoroutineDispatcher ): CoroutineDispatcherProvider = object : CoroutineDispatcherProvider { override fun getIODispatcher(): CoroutineDispatcher = ioDispatcher } @Singleton @Provides fun notificationConfigurationProvider( @ApplicationContext application: Context ): NotificationConfigurationProvider = object : NotificationConfigurationProvider { override fun getNotificationTitle(): String = application.getString(R.string.sync_notification_title) override fun getNotificationIcon(): Int = R.drawable.ic_uamp_headset override fun getChannelName(): String = application.getString(R.string.sync_notification_channel_name) override fun getChannelDescription(): String = application.getString(R.string.sync_notification_channel_description) } @Singleton @Provides fun changeListVersionRepository(): ChangeListVersionRepository = object : ChangeListVersionRepository { override suspend fun getChangeListVersion(model: String): Int { // always return the same value for now, given change list endpoint is not available // in the API return CHANGE_LIST_VERSION } override suspend fun updateChangeListVersion(model: String, newVersion: Int) { // do nothing for now } } @Singleton @Provides fun syncables( playlistRepositorySyncable: PlaylistRepositorySyncable ): Array<Syncable> = arrayOf( playlistRepositorySyncable ) @Provides fun playlistRepositorySyncable( playlistLocalDataSource: PlaylistLocalDataSource, playlistRemoteDataSource: PlaylistRemoteDataSource, networkChangeListService: NetworkChangeListService, mediaLocalDataSource: MediaLocalDataSource, playlistMapper: PlaylistMapper ): PlaylistRepositorySyncable = PlaylistRepositorySyncable( playlistLocalDataSource, playlistRemoteDataSource, networkChangeListService, mediaLocalDataSource, playlistMapper ) }
apache-2.0
21553c13f7a8c3ba2fbad432ef09f410
37.798246
100
0.744291
5.203529
false
false
false
false
camsteffen/polite
src/main/java/me/camsteffen/polite/db/PoliteStateDao.kt
1
2157
package me.camsteffen.polite.db import androidx.room.Dao import androidx.room.Insert import androidx.room.OnConflictStrategy import androidx.room.Query import androidx.room.Transaction import me.camsteffen.polite.model.ActiveRuleEvent import me.camsteffen.polite.model.EventCancel import me.camsteffen.polite.model.ScheduleRuleCancel import org.threeten.bp.Instant @Dao abstract class PoliteStateDao { @Query("select * from active_rule_event") abstract fun getActiveRuleEvent(): ActiveRuleEvent? @Transaction open fun setActiveRuleEvent(activeRuleEvent: ActiveRuleEvent?) { deleteActiveRuleEvent() if (activeRuleEvent != null) { insertActiveRuleEvent(activeRuleEvent) } } @Query("select * from event_cancel") abstract fun getEventCancels(): List<EventCancel> @Insert(onConflict = OnConflictStrategy.REPLACE) abstract fun insertEventCancels(vararg eventCancels: EventCancel) @Query("select * from schedule_rule_cancel") abstract fun getScheduleRuleCancels(): List<ScheduleRuleCancel> @Insert(onConflict = OnConflictStrategy.REPLACE) abstract fun insertScheduleRuleCancels(vararg scheduleRuleCancels: ScheduleRuleCancel) fun deleteDeadCancels(now: Instant) { deleteDeadEventCancels(now) deleteDeadScheduleRuleCancels(now) } @Insert protected abstract fun insertActiveRuleEvent(activeRuleEvent: ActiveRuleEvent) @Query("delete from active_rule_event") protected abstract fun deleteActiveRuleEvent(): Int @Query( """delete from event_cancel where `end` <= :now or rule_id in (select rule_id from event_cancel c left join rule r on c.rule_id = r.id where enabled != 1)""") protected abstract fun deleteDeadEventCancels(now: Instant): Int @Query( """delete from schedule_rule_cancel where `end` <= :now or rule_id in ( select rule_id from schedule_rule_cancel c left join rule r on c.rule_id = r.id where enabled != 1 )""" ) protected abstract fun deleteDeadScheduleRuleCancels(now: Instant): Int }
mpl-2.0
40b68e4538e0d0e144484539deef18d5
32.184615
92
0.711173
4.420082
false
false
false
false
google/horologist
media-ui/src/main/java/com/google/android/horologist/media/ui/components/PodcastControlButtons.kt
1
7650
/* * Copyright 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.horologist.media.ui.components import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.wear.compose.material.ButtonColors import com.google.android.horologist.media.ui.ExperimentalHorologistMediaUiApi import com.google.android.horologist.media.ui.components.controls.MediaButtonDefaults import com.google.android.horologist.media.ui.components.controls.SeekBackButton import com.google.android.horologist.media.ui.components.controls.SeekButtonIncrement import com.google.android.horologist.media.ui.components.controls.SeekForwardButton import com.google.android.horologist.media.ui.state.PlayerUiController import com.google.android.horologist.media.ui.state.PlayerUiState /** * Convenience wrapper of [PodcastControlButtons]. * * This version passes events to the provided [PlayerUiController]. */ @ExperimentalHorologistMediaUiApi @Composable public fun PodcastControlButtons( playerController: PlayerUiController, playerUiState: PlayerUiState, modifier: Modifier = Modifier, showProgress: Boolean = true, colors: ButtonColors = MediaButtonDefaults.mediaButtonDefaultColors ) { val percent = if (showProgress) { playerUiState.trackPosition?.percent ?: 0f } else { null } PodcastControlButtons( onPlayButtonClick = { playerController.play() }, onPauseButtonClick = { playerController.pause() }, playPauseButtonEnabled = playerUiState.playPauseEnabled, playing = playerUiState.playing, onSeekBackButtonClick = { playerController.skipToPreviousMedia() }, seekBackButtonIncrement = playerUiState.seekBackButtonIncrement, seekBackButtonEnabled = playerUiState.seekBackEnabled, onSeekForwardButtonClick = { playerController.skipToNextMedia() }, seekForwardButtonIncrement = playerUiState.seekForwardButtonIncrement, seekForwardButtonEnabled = playerUiState.seekForwardEnabled, showProgress = showProgress, modifier = modifier, percent = percent, colors = colors ) } /** * Standard Podcast control buttons, showing [SeekBackButton], [PlayPauseProgressButton] and * [SeekForwardButton]. */ @ExperimentalHorologistMediaUiApi @Composable public fun PodcastControlButtons( onPlayButtonClick: () -> Unit, onPauseButtonClick: () -> Unit, playPauseButtonEnabled: Boolean, playing: Boolean, percent: Float, onSeekBackButtonClick: () -> Unit, seekBackButtonEnabled: Boolean, onSeekForwardButtonClick: () -> Unit, seekForwardButtonEnabled: Boolean, modifier: Modifier = Modifier, seekBackButtonIncrement: SeekButtonIncrement = SeekButtonIncrement.Unknown, seekForwardButtonIncrement: SeekButtonIncrement = SeekButtonIncrement.Unknown, colors: ButtonColors = MediaButtonDefaults.mediaButtonDefaultColors ) { PodcastControlButtons( onPlayButtonClick = onPlayButtonClick, onPauseButtonClick = onPauseButtonClick, playPauseButtonEnabled = playPauseButtonEnabled, playing = playing, onSeekBackButtonClick = onSeekBackButtonClick, seekBackButtonIncrement = seekBackButtonIncrement, seekBackButtonEnabled = seekBackButtonEnabled, onSeekForwardButtonClick = onSeekForwardButtonClick, seekForwardButtonIncrement = seekForwardButtonIncrement, seekForwardButtonEnabled = seekForwardButtonEnabled, showProgress = true, modifier = modifier, percent = percent, colors = colors ) } /** * Standard Podcast control buttons with no progress indicator, showing [SeekBackButton], * [PlayPauseProgressButton] and [SeekForwardButton]. */ @ExperimentalHorologistMediaUiApi @Composable public fun PodcastControlButtons( onPlayButtonClick: () -> Unit, onPauseButtonClick: () -> Unit, playPauseButtonEnabled: Boolean, playing: Boolean, onSeekBackButtonClick: () -> Unit, seekBackButtonEnabled: Boolean, onSeekForwardButtonClick: () -> Unit, seekForwardButtonEnabled: Boolean, modifier: Modifier = Modifier, seekBackButtonIncrement: SeekButtonIncrement = SeekButtonIncrement.Unknown, seekForwardButtonIncrement: SeekButtonIncrement = SeekButtonIncrement.Unknown, colors: ButtonColors = MediaButtonDefaults.mediaButtonDefaultColors ) { PodcastControlButtons( onPlayButtonClick = onPlayButtonClick, onPauseButtonClick = onPauseButtonClick, playPauseButtonEnabled = playPauseButtonEnabled, playing = playing, onSeekBackButtonClick = onSeekBackButtonClick, seekBackButtonIncrement = seekBackButtonIncrement, seekBackButtonEnabled = seekBackButtonEnabled, onSeekForwardButtonClick = onSeekForwardButtonClick, seekForwardButtonIncrement = seekForwardButtonIncrement, seekForwardButtonEnabled = seekForwardButtonEnabled, showProgress = false, modifier = modifier, colors = colors ) } @ExperimentalHorologistMediaUiApi @Composable private fun PodcastControlButtons( onPlayButtonClick: () -> Unit, onPauseButtonClick: () -> Unit, playPauseButtonEnabled: Boolean, playing: Boolean, onSeekBackButtonClick: () -> Unit, seekBackButtonIncrement: SeekButtonIncrement, seekBackButtonEnabled: Boolean, onSeekForwardButtonClick: () -> Unit, seekForwardButtonIncrement: SeekButtonIncrement, seekForwardButtonEnabled: Boolean, showProgress: Boolean, modifier: Modifier = Modifier, percent: Float? = null, colors: ButtonColors = MediaButtonDefaults.mediaButtonDefaultColors ) { ControlButtonLayout( modifier = modifier, leftButton = { SeekBackButton( onClick = onSeekBackButtonClick, seekButtonIncrement = seekBackButtonIncrement, colors = colors, enabled = seekBackButtonEnabled ) }, middleButton = { if (showProgress) { checkNotNull(percent) PlayPauseProgressButton( onPlayClick = onPlayButtonClick, onPauseClick = onPauseButtonClick, enabled = playPauseButtonEnabled, playing = playing, percent = percent, colors = colors ) } else { PlayPauseButton( onPlayClick = onPlayButtonClick, onPauseClick = onPauseButtonClick, enabled = playPauseButtonEnabled, playing = playing, colors = colors ) } }, rightButton = { SeekForwardButton( onClick = onSeekForwardButtonClick, seekButtonIncrement = seekForwardButtonIncrement, colors = colors, enabled = seekForwardButtonEnabled ) } ) }
apache-2.0
4a2a398503df64f9f572f8443eb55169
36.684729
92
0.702876
5.948678
false
false
false
false
Kotlin/dokka
runners/gradle-plugin/src/main/kotlin/org/jetbrains/dokka/gradle/kotlin/KotlinSourceSetGist.kt
1
1240
package org.jetbrains.dokka.gradle.kotlin import org.gradle.api.Project import org.gradle.api.file.FileCollection import org.gradle.api.provider.Provider import org.jetbrains.kotlin.gradle.plugin.KotlinPlatformType import org.jetbrains.kotlin.gradle.plugin.KotlinSourceSet internal data class KotlinSourceSetGist( val name: String, val platform: Provider<KotlinPlatformType>, val isMain: Provider<Boolean>, val classpath: Provider<FileCollection>, val sourceRoots: FileCollection, val dependentSourceSetNames: Provider<Set<String>>, ) internal fun Project.gistOf(sourceSet: KotlinSourceSet): KotlinSourceSetGist = KotlinSourceSetGist( name = sourceSet.name, platform = project.provider { platformOf(sourceSet) }, isMain = project.provider { isMainSourceSet(sourceSet) }, classpath = project.provider { classpathOf(sourceSet).filter { it.exists() } }, // TODO: Needs to respect filters. // We probably need to change from "sourceRoots" to support "sourceFiles" // https://github.com/Kotlin/dokka/issues/1215 sourceRoots = sourceSet.kotlin.sourceDirectories.filter { it.exists() }, dependentSourceSetNames = project.provider { sourceSet.dependsOn.map { it.name }.toSet() }, )
apache-2.0
bd28940dd7189b1071bda4da151dc7f0
41.758621
99
0.760484
4.350877
false
false
false
false
jglrxavpok/SBM
src/main/kotlin/org/jglr/sbm/generation/VisitorGenerator.kt
1
5429
package org.jglr.sbm.generation import com.beust.klaxon.JsonArray import com.beust.klaxon.JsonObject abstract class VisitorGenerator : ClassGenerator() { protected fun createVisitFunction(opname: String, name: String, instruction: JsonObject): ClassFunction { val argumentNames = mutableListOf<String>() val argumentTypes = mutableListOf<String>() @Suppress("UNCHECKED_CAST") val operands = instruction["Operands"] as JsonArray<JsonObject> fillOperandNameAndTypes(opname, operands, argumentNames, argumentTypes) val function = ClassFunction(name, "void", argumentNames, argumentTypes, "") function.documentation = instruction["DescriptionPlain"] as String? function.documentation?.let { function.documentation = function.documentation?.replace("\n", "\n<br/>") } function.bodyless = true return function } fun fillOperandNameAndTypes(instructionName: String, operands: JsonArray<JsonObject>, argumentNames: MutableList<String>, argumentTypes: MutableList<String>) { operands.forEachIndexed { i, infos -> var opname = if(infos["Name"] == null) "nullNamePleaseFix" else infos["Name"] as String val readType = if(infos["Type"] == null) "NullTypePleaseFix" else infos["Type"] as String var type = getType(opname, readType) if(opname == "Param" && instructionName == "OpConstantSampler") { type = "boolean" } when(opname) { "Optional" -> { opname = "optional"+type.capitalize().replace("[]", "Array") } "Default" -> { opname = "defaultValue" } else -> { opname = opname.decapitalize() } } if(argumentNames.contains(opname)) { var index = 2 while(argumentNames.contains(opname+index)) { index++ } opname += index } argumentNames.add(opname) argumentTypes.add(type) } if(argumentTypes.contains("ImageOperands")) { val index = argumentTypes.indexOfFirst { t -> t == "ImageOperands" } argumentTypes[index+1] = "Map<Integer, long[]>" argumentNames[index+1] = "splitOperands" } } fun getCorrespondingVisitFunction(instruction: JsonObject): String { val opName = instruction["Name"] as String return when (instruction["Category"]) { "Type-Declaration" -> { SPIRVTypeVisitorGenerator.transformTypeOpName(opName) } else -> { if (opName == "OpExtInst") { "visitExecExtendedInstruction" } else if (opName == "OpExtInstImport") { "visitExtendedInstructionSetImport" } else { // remove "Op" from name "visit${opName.substring(2)}" } } } } protected fun getType(name: String, typeID: String): String { if(typeID.endsWith("?")) { return getType(name, typeID.substring(0, typeID.length-1)) } if(typeID.endsWith("[]")) { return getType(name, typeID.substring(0, typeID.length-2))+"[]" } when (typeID) { "Dim" -> { return "Dimensionality" } "ImageFormat" -> { return "ImageFormat" } "StorageClass" -> { return "StorageClass" } "AccessQualifier" -> { return "AccessQualifier" } "LiteralString" -> { return "String" } "FunctionControl" -> { return "FunctionControl" } "SamplerFilterMode" -> { return "SamplerFilterMode" } "Capability" -> { return "Capability" } "SourceLanguage" -> { return "SourceLanguage" } "SamplerAddressingMode" -> { return "SamplerAddressingMode" } "ExecutionMode" -> { return "ExecutionMode" } "MemoryModel" -> { return "MemoryModel" } "AddressingModel" -> { return "AddressingModel" } "ImageOperands" -> { return "ImageOperands" } "ExecutionModel" -> { return "ExecutionModel" } "MemoryAccess" -> { return "MemoryAccess" } } if(typeID.startsWith("LiteralString")) return "String" if(name.startsWith("LiteralString")) return "String" return when (name) { "Arrayed" -> { "boolean" } "MS" -> { "boolean" } "Sampled" -> { "Sampling" } "Depth" -> { "ImageDepth" } "Signedness" -> { "boolean" } else -> { "long" } } } }
mit
3cdc48f75f50b08eb506d3908ba884dc
32.9375
163
0.482778
5.165557
false
false
false
false
herbeth1u/VNDB-Android
app/src/main/java/com/booboot/vndbandroid/util/view/LockableBottomSheetBehavior.kt
1
1637
package com.booboot.vndbandroid.util.view import android.content.Context import android.util.AttributeSet import android.view.MotionEvent import android.view.View import androidx.coordinatorlayout.widget.CoordinatorLayout import com.google.android.material.bottomsheet.BottomSheetBehavior class LockableBottomSheetBehavior<V : View> @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null ) : BottomSheetBehavior<V>(context, attrs) { var locked = false override fun onInterceptTouchEvent(parent: CoordinatorLayout, child: V, event: MotionEvent) = if (!locked) super.onInterceptTouchEvent(parent, child, event) else false override fun onTouchEvent(parent: CoordinatorLayout, child: V, event: MotionEvent) = if (!locked) super.onTouchEvent(parent, child, event) else false override fun onStartNestedScroll(coordinatorLayout: CoordinatorLayout, child: V, directTargetChild: View, target: View, axes: Int, type: Int) = if (!locked) super.onStartNestedScroll(coordinatorLayout, child, directTargetChild, target, axes, type) else false override fun onNestedPreScroll(coordinatorLayout: CoordinatorLayout, child: V, target: View, dx: Int, dy: Int, consumed: IntArray, type: Int) { if (!locked) super.onNestedPreScroll(coordinatorLayout, child, target, dx, dy, consumed, type) } override fun onNestedPreFling(coordinatorLayout: CoordinatorLayout, child: V, target: View, velocityX: Float, velocityY: Float) = if (!locked) super.onNestedPreFling(coordinatorLayout, child, target, velocityX, velocityY) else false }
gpl-3.0
e7dd827bbd182dcc4fa3adb50927bdf0
45.8
147
0.753207
4.744928
false
false
false
false
gameover-fwk/gameover-fwk
src/main/kotlin/gameover/fwk/pool/ObjectPool.kt
1
2395
package gameover.fwk.pool import com.badlogic.gdx.utils.Pool import com.badlogic.gdx.math.GridPoint2 import com.badlogic.gdx.math.Rectangle import com.badlogic.gdx.math.Vector2 import gameover.fwk.libgdx.utils.GdxArray import java.util.* abstract class ObjectPool<T> { abstract fun instantiateObject(): T private val pool = object: Pool<T>() { override fun newObject(): T { return instantiateObject() } } /** * Clear all objects in pool. */ fun clear() { pool.clear() } fun free(a: Array<T>) { for (e in 0..(a.size - 1)) free(a.get(e)) } fun free(a: GdxArray<T>) { for (e in 0..(a.size - 1)) free(a.get(e)) } fun free(l: List<T>) { for (e in l) free(e) } fun free(t: T) { pool.free(t) } fun obtain(): T = pool.obtain() abstract fun obtainAsArray(nb: Int) : Array<T> fun obtainAsGdxArray(nb: Int): GdxArray<T> { val a = GdxArray<T>(nb) for (i in 1..nb) a.add(obtain()) return a } fun obtainAsList(nb: Int): ArrayList<T> { val a = ArrayList<T>(nb) for (i in 1..nb) a.add(obtain()) return a } } object GridPoint2Pool : ObjectPool<GridPoint2>() { override fun instantiateObject() : GridPoint2 = GridPoint2() fun obtain(o: GridPoint2): GridPoint2 = obtain().set(o) fun obtain(x: Int, y: Int): GridPoint2 = obtain().set(x, y) override fun obtainAsArray(nb: Int) : Array<GridPoint2> = Array(nb) { obtain() } } object RectanglePool : ObjectPool<Rectangle>() { override fun instantiateObject(): Rectangle = Rectangle() fun obtain(rectangle: Rectangle): Rectangle = obtain().set(rectangle) fun obtain(v1: Vector2, v2: Vector2): Rectangle = obtain().set(v1.x, v1.y, v2.x, v2.y) fun obtain(x1: Float, y1: Float, w: Float, h: Float): Rectangle = obtain().set(x1, y1, w, h) override fun obtainAsArray(nb: Int) : Array<Rectangle> = Array(nb) { obtain() } } object Vector2Pool : ObjectPool<Vector2>() { override fun instantiateObject(): Vector2 = Vector2() fun obtain(o: Vector2): Vector2 = obtain().set(o) fun obtain(x: Float, y: Float): Vector2 = obtain().set(x, y) override fun obtainAsArray(nb: Int) : Array<Vector2> = Array(nb) { obtain() } }
mit
0081f3f08d40af399f7bc5c88db8efbb
22.262136
96
0.590397
3.308011
false
false
false
false
square/duktape-android
zipline-kotlin-plugin/src/main/kotlin/app/cash/zipline/kotlin/ir.kt
1
13856
/* * Copyright (C) 2021 Square, 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 app.cash.zipline.kotlin import org.jetbrains.kotlin.backend.common.ScopeWithIr import org.jetbrains.kotlin.backend.common.extensions.IrPluginContext import org.jetbrains.kotlin.backend.common.ir.createDispatchReceiverParameter import org.jetbrains.kotlin.backend.common.ir.createImplicitParameterDeclarationWithWrappedDescriptor import org.jetbrains.kotlin.backend.common.lower.DeclarationIrBuilder import org.jetbrains.kotlin.cli.common.messages.CompilerMessageLocationWithRange import org.jetbrains.kotlin.cli.common.messages.CompilerMessageSeverity import org.jetbrains.kotlin.cli.common.messages.CompilerMessageSourceLocation import org.jetbrains.kotlin.descriptors.ClassKind import org.jetbrains.kotlin.descriptors.DescriptorVisibilities import org.jetbrains.kotlin.descriptors.Modality import org.jetbrains.kotlin.ir.IrElement import org.jetbrains.kotlin.ir.IrStatement import org.jetbrains.kotlin.ir.UNDEFINED_OFFSET import org.jetbrains.kotlin.ir.builders.IrBlockBodyBuilder import org.jetbrains.kotlin.ir.builders.IrBlockBuilder import org.jetbrains.kotlin.ir.builders.IrBuilderWithScope import org.jetbrains.kotlin.ir.builders.IrGeneratorContext import org.jetbrains.kotlin.ir.builders.Scope import org.jetbrains.kotlin.ir.builders.declarations.IrClassBuilder import org.jetbrains.kotlin.ir.builders.declarations.IrFunctionBuilder import org.jetbrains.kotlin.ir.builders.declarations.IrValueParameterBuilder import org.jetbrains.kotlin.ir.builders.declarations.addConstructor import org.jetbrains.kotlin.ir.builders.declarations.buildClass import org.jetbrains.kotlin.ir.builders.irGet import org.jetbrains.kotlin.ir.builders.irGetField import org.jetbrains.kotlin.ir.builders.irReturn import org.jetbrains.kotlin.ir.declarations.IrClass import org.jetbrains.kotlin.ir.declarations.IrConstructor import org.jetbrains.kotlin.ir.declarations.IrDeclarationOrigin import org.jetbrains.kotlin.ir.declarations.IrFile import org.jetbrains.kotlin.ir.declarations.IrProperty import org.jetbrains.kotlin.ir.declarations.IrSimpleFunction import org.jetbrains.kotlin.ir.expressions.IrDelegatingConstructorCall import org.jetbrains.kotlin.ir.expressions.IrExpression import org.jetbrains.kotlin.ir.expressions.IrExpressionBody import org.jetbrains.kotlin.ir.expressions.IrInstanceInitializerCall import org.jetbrains.kotlin.ir.expressions.IrReturn import org.jetbrains.kotlin.ir.expressions.impl.IrClassReferenceImpl import org.jetbrains.kotlin.ir.expressions.impl.IrDelegatingConstructorCallImpl import org.jetbrains.kotlin.ir.expressions.impl.IrInstanceInitializerCallImpl import org.jetbrains.kotlin.ir.expressions.impl.IrReturnImpl import org.jetbrains.kotlin.ir.symbols.IrClassSymbol import org.jetbrains.kotlin.ir.symbols.IrConstructorSymbol import org.jetbrains.kotlin.ir.symbols.IrPropertySymbol import org.jetbrains.kotlin.ir.symbols.IrReturnTargetSymbol import org.jetbrains.kotlin.ir.symbols.IrSymbol import org.jetbrains.kotlin.ir.symbols.impl.IrFieldSymbolImpl import org.jetbrains.kotlin.ir.symbols.impl.IrPropertySymbolImpl import org.jetbrains.kotlin.ir.symbols.impl.IrSimpleFunctionSymbolImpl import org.jetbrains.kotlin.ir.types.IrSimpleType import org.jetbrains.kotlin.ir.types.IrType import org.jetbrains.kotlin.ir.types.classFqName import org.jetbrains.kotlin.ir.types.typeWith import org.jetbrains.kotlin.ir.util.SYNTHETIC_OFFSET import org.jetbrains.kotlin.ir.util.constructors import org.jetbrains.kotlin.ir.util.defaultType import org.jetbrains.kotlin.name.FqName import org.jetbrains.kotlin.name.Name internal val IrSimpleFunction.signature: String get() = buildString { if (isSuspend) { append("suspend ") } append("fun ${name.identifier}(${valueParameters.joinToString { (it.type as IrSimpleType).asString() }}): ${(returnType as IrSimpleType).asString()}") } internal fun FqName.child(name: String) = child(Name.identifier(name)) /** Thrown on invalid or unexpected input code. */ class ZiplineCompilationException( override val message: String, val element: IrElement? = null, val severity: CompilerMessageSeverity = CompilerMessageSeverity.ERROR, ) : Exception(message) /** Finds the line and column of [irElement] within this file. */ fun IrFile.locationOf(irElement: IrElement?): CompilerMessageSourceLocation { val sourceRangeInfo = fileEntry.getSourceRangeInfo( beginOffset = irElement?.startOffset ?: SYNTHETIC_OFFSET, endOffset = irElement?.endOffset ?: SYNTHETIC_OFFSET ) return CompilerMessageLocationWithRange.create( path = sourceRangeInfo.filePath, lineStart = sourceRangeInfo.startLineNumber + 1, columnStart = sourceRangeInfo.startColumnNumber + 1, lineEnd = sourceRangeInfo.endLineNumber + 1, columnEnd = sourceRangeInfo.endColumnNumber + 1, lineContent = null )!! } /** `return ...` */ internal fun IrBuilderWithScope.irReturn( value: IrExpression, returnTargetSymbol: IrReturnTargetSymbol, type: IrType = value.type, ): IrReturn { return IrReturnImpl( startOffset = startOffset, endOffset = endOffset, type = type, returnTargetSymbol = returnTargetSymbol, value = value, ) } /** Set up reasonable defaults for a generated function or constructor. */ fun IrFunctionBuilder.initDefaults(original: IrElement) { this.startOffset = original.startOffset.toSyntheticIfUnknown() this.endOffset = original.endOffset.toSyntheticIfUnknown() this.origin = IrDeclarationOrigin.DEFINED this.visibility = DescriptorVisibilities.PUBLIC this.modality = Modality.OPEN this.isPrimary = true } /** Set up reasonable defaults for a generated class. */ fun IrClassBuilder.initDefaults(original: IrElement) { this.startOffset = original.startOffset.toSyntheticIfUnknown() this.endOffset = original.endOffset.toSyntheticIfUnknown() this.name = Name.special("<no name provided>") this.visibility = DescriptorVisibilities.LOCAL } /** Set up reasonable defaults for a value parameter. */ fun IrValueParameterBuilder.initDefaults(original: IrElement) { this.startOffset = original.startOffset.toSyntheticIfUnknown() this.endOffset = original.endOffset.toSyntheticIfUnknown() } /** * When we generate code based on classes outside of the current module unit we get elements that * use `UNDEFINED_OFFSET`. Make sure we don't propagate this further into generated code; that * causes LLVM code generation to fail. */ private fun Int.toSyntheticIfUnknown(): Int { return when (this) { UNDEFINED_OFFSET -> SYNTHETIC_OFFSET else -> this } } fun IrConstructor.irConstructorBody( context: IrGeneratorContext, blockBody: DeclarationIrBuilder.(MutableList<IrStatement>) -> Unit ) { val constructorIrBuilder = DeclarationIrBuilder( generatorContext = context, symbol = IrSimpleFunctionSymbolImpl(), startOffset = startOffset, endOffset = endOffset ) body = context.irFactory.createBlockBody( startOffset = constructorIrBuilder.startOffset, endOffset = constructorIrBuilder.endOffset, ) { constructorIrBuilder.blockBody(statements) } } fun DeclarationIrBuilder.irDelegatingConstructorCall( context: IrGeneratorContext, symbol: IrConstructorSymbol, typeArgumentsCount: Int = 0, valueArgumentsCount: Int = 0, block: IrDelegatingConstructorCall.() -> Unit = {}, ): IrDelegatingConstructorCall { val result = IrDelegatingConstructorCallImpl( startOffset = startOffset, endOffset = endOffset, type = context.irBuiltIns.unitType, symbol = symbol, typeArgumentsCount = typeArgumentsCount, valueArgumentsCount = valueArgumentsCount ) result.block() return result } fun DeclarationIrBuilder.irInstanceInitializerCall( context: IrGeneratorContext, classSymbol: IrClassSymbol, ): IrInstanceInitializerCall { return IrInstanceInitializerCallImpl( startOffset = startOffset, endOffset = endOffset, classSymbol = classSymbol, type = context.irBuiltIns.unitType, ) } fun IrSimpleFunction.irFunctionBody( context: IrGeneratorContext, scopeOwnerSymbol: IrSymbol, blockBody: IrBlockBodyBuilder.() -> Unit ) { val bodyBuilder = IrBlockBodyBuilder( startOffset = startOffset, endOffset = endOffset, context = context, scope = Scope(scopeOwnerSymbol), ) body = bodyBuilder.blockBody { blockBody() } } /** Create a private val with a backing field and an accessor function. */ fun irVal( pluginContext: IrPluginContext, propertyType: IrType, declaringClass: IrClass, propertyName: Name, overriddenProperty: IrPropertySymbol? = null, initializer: IrBlockBuilder.() -> IrExpressionBody, ): IrProperty { val irFactory = pluginContext.irFactory val result = irFactory.createProperty( startOffset = declaringClass.startOffset, endOffset = declaringClass.endOffset, origin = IrDeclarationOrigin.DEFINED, symbol = IrPropertySymbolImpl(), name = propertyName, visibility = overriddenProperty?.owner?.visibility ?: DescriptorVisibilities.PRIVATE, modality = Modality.FINAL, isVar = false, isConst = false, isLateinit = false, isDelegated = false, isExternal = false, isExpect = false, isFakeOverride = false, containerSource = null, ).apply { overriddenSymbols = listOfNotNull(overriddenProperty) parent = declaringClass } result.backingField = irFactory.createField( startOffset = declaringClass.startOffset, endOffset = declaringClass.endOffset, origin = IrDeclarationOrigin.PROPERTY_BACKING_FIELD, symbol = IrFieldSymbolImpl(), name = result.name, type = propertyType, visibility = DescriptorVisibilities.PRIVATE, isFinal = true, isExternal = false, isStatic = false ).apply { parent = declaringClass correspondingPropertySymbol = result.symbol val initializerBuilder = IrBlockBuilder( startOffset = declaringClass.startOffset, endOffset = declaringClass.endOffset, context = pluginContext, scope = Scope(symbol), ) this.initializer = initializerBuilder.initializer() } result.getter = irFactory.createFunction( startOffset = declaringClass.startOffset, endOffset = declaringClass.endOffset, origin = IrDeclarationOrigin.DEFAULT_PROPERTY_ACCESSOR, name = Name.special("<get-${propertyName.identifier}>"), visibility = overriddenProperty?.owner?.getter?.visibility ?: DescriptorVisibilities.PRIVATE, isExternal = false, symbol = IrSimpleFunctionSymbolImpl(), modality = Modality.FINAL, returnType = propertyType, isInline = false, isTailrec = false, isSuspend = false, isOperator = false, isInfix = false, isExpect = false, isFakeOverride = false, containerSource = null ).apply { parent = declaringClass correspondingPropertySymbol = result.symbol overriddenSymbols = listOfNotNull(overriddenProperty?.owner?.getter?.symbol) createDispatchReceiverParameter() irFunctionBody( context = pluginContext, scopeOwnerSymbol = symbol ) { +irReturn( value = irGetField( irGet(dispatchReceiverParameter!!), result.backingField!! ) ) } } return result } internal fun IrBuilderWithScope.irKClass( containerClass: IrClass, ): IrClassReferenceImpl { return IrClassReferenceImpl( startOffset = startOffset, endOffset = endOffset, type = context.irBuiltIns.kClassClass.typeWith(containerClass.defaultType), symbol = containerClass.symbol, classType = containerClass.defaultType ) } fun irBlockBodyBuilder( irPluginContext: IrGeneratorContext, scopeWithIr: ScopeWithIr, original: IrElement ): IrBlockBodyBuilder { return IrBlockBodyBuilder( context = irPluginContext, scope = scopeWithIr.scope, startOffset = original.startOffset.toSyntheticIfUnknown(), endOffset = original.endOffset.toSyntheticIfUnknown(), ) } /** This creates `companion object` if it doesn't exist already. */ fun getOrCreateCompanion( enclosing: IrClass, irPluginContext: IrPluginContext, ): IrClass { val existing = enclosing.declarations.firstOrNull { it is IrClass && it.name.identifier == "Companion" } if (existing != null) return existing as IrClass val irFactory = irPluginContext.irFactory val anyType = irPluginContext.referenceClass(irPluginContext.irBuiltIns.anyType.classFqName!!)!! val companionClass = irFactory.buildClass { initDefaults(enclosing) name = Name.identifier("Companion") visibility = DescriptorVisibilities.PUBLIC kind = ClassKind.OBJECT isCompanion = true }.apply { parent = enclosing superTypes = listOf(irPluginContext.irBuiltIns.anyType) createImplicitParameterDeclarationWithWrappedDescriptor() } companionClass.addConstructor { initDefaults(enclosing) visibility = DescriptorVisibilities.PRIVATE }.apply { irConstructorBody(irPluginContext) { statements -> statements += irDelegatingConstructorCall( context = irPluginContext, symbol = anyType.constructors.single() ) statements += irInstanceInitializerCall( context = irPluginContext, classSymbol = companionClass.symbol, ) } } enclosing.declarations.add(companionClass) return companionClass }
apache-2.0
ecc3a3a83e21de379cda615f47e1ea5f
34.803618
154
0.771579
4.595688
false
false
false
false
OdysseusLevy/kale
src/main/kotlin/org/kale/mail/FolderWrapper.kt
1
1900
package org.kale.mail import org.apache.logging.log4j.LogManager import java.time.Instant import java.util.* import javax.mail.Folder import javax.mail.Message import javax.mail.internet.MimeMessage import javax.mail.search.ComparisonTerm import javax.mail.search.ReceivedDateTerm /** * Folder information */ class FolderWrapper(val store: StoreWrapper, /** * Name of this folder * eg "Trash" */ val name: String, /** * Fully qualified name, so it includes parents as well. * Eg. [Gmail]/Trash */ val fullName: String, /** * Is this the type of folder that can contain messages? * For example, Google's [GMail] folder returns false */ val canHoldMessages: Boolean, /** * Is this the type of folder than contains folders (and not messages)? * For example, Google's [Gmail] folder returns true * @return */ val holdsFolders: Boolean, val messageCount: Int, val exists: Boolean) { // // Internal // companion object { fun create(folder: Folder, storeWrapper: StoreWrapper) = FolderWrapper(store= storeWrapper, name = folder.name, fullName = folder.fullName, canHoldMessages = (folder.getType() and Folder.HOLDS_MESSAGES) != 0, holdsFolders = (folder.getType() and Folder.HOLDS_FOLDERS) != 0, messageCount = folder.messageCount, exists = folder.exists()) } }
apache-2.0
8466c3dd0bfcc55fac027cad37fdf9b9
30.683333
91
0.497368
5.292479
false
false
false
false
loziuu/vehicle-management
ivms/src/main/kotlin/pl/loziuu/ivms/management/vehicle/query/VehicleDto.kt
1
676
package pl.loziuu.ivms.management.vehicle.query import com.fasterxml.jackson.annotation.JsonIgnore import pl.loziuu.ivms.maintenance.journal.query.JournalDto import java.util.* import javax.persistence.* @Entity @Table(name = "vehicle") class VehicleDto( @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @JsonIgnore val id: Long = 0, val model: String = "", val manufacturer: String = "", val productionYear: Int = 0, @JsonIgnore val fleetId: Long = 0, @JsonIgnore val local: Long = 0, @OneToMany(mappedBy = "vehicleId", fetch = FetchType.EAGER) val journal: MutableSet<JournalDto> = HashSet())
gpl-3.0
e292380102161f6349e92722e9951606
34.578947
67
0.683432
4.09697
false
false
false
false
Gu3pardo/PasswordSafe-AndroidClient
mobile/src/main/java/guepardoapps/passwordsafe/controller/SystemInfoController.kt
1
3436
package guepardoapps.passwordsafe.controller import android.app.Activity import android.app.ActivityManager import android.content.ContentResolver import android.content.Context import android.content.Intent import android.hardware.display.DisplayManager import android.net.Uri import android.os.Build import android.provider.Settings import android.util.Log import android.view.Display import android.view.WindowManager import android.view.accessibility.AccessibilityEvent import android.view.accessibility.AccessibilityManager import androidx.annotation.RequiresApi class SystemInfoController(private val context: Context) : ISystemInfoController { private val tag: String = SystemInfoController::class.java.simpleName private val accessibilityManager: AccessibilityManager = context.getSystemService(Context.ACCESSIBILITY_SERVICE) as AccessibilityManager private val activityManager: ActivityManager = context.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager override fun isServiceRunning(serviceClassName: String): Boolean { return activityManager .getRunningServices(Integer.MAX_VALUE)!! .any { serviceInfo -> serviceClassName == serviceInfo.service.className } } override fun isServiceRunning(serviceClass: Class<*>): Boolean { return isServiceRunning(serviceClass.name) } override fun isAccessibilityServiceEnabled(serviceId: String): Boolean { return accessibilityManager .getEnabledAccessibilityServiceList(AccessibilityEvent.TYPES_ALL_MASK)!! .any { serviceInfo -> serviceInfo.id == serviceId } } @RequiresApi(Build.VERSION_CODES.M) override fun isBaseActivityRunning(): Boolean { return activityManager .appTasks!! .any { task -> task.taskInfo.baseActivity.packageName == context.packageName } } override fun currentAndroidApi(): Int { return Build.VERSION.SDK_INT } @RequiresApi(Build.VERSION_CODES.M) override fun checkAPI23SystemPermission(permissionRequestId: Int): Boolean { if (!Settings.canDrawOverlays(context)) { val intent = Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION, Uri.parse("package:" + context.packageName)) (context as Activity).startActivityForResult(intent, permissionRequestId) return false } return true } override fun mayReadNotifications(contentResolver: ContentResolver, packageName: String): Boolean { return try { Settings.Secure.getString(contentResolver, "enabled_notification_listeners").contains(packageName) } catch (exception: Exception) { Log.e(tag, exception.message) false } } @RequiresApi(Build.VERSION_CODES.M) override fun canDrawOverlay(): Boolean { return Settings.canDrawOverlays(context) } override fun displayDimension(): Display { val windowManager: WindowManager = context.getSystemService(Context.WINDOW_SERVICE) as WindowManager return windowManager.defaultDisplay } @RequiresApi(Build.VERSION_CODES.KITKAT_WATCH) override fun isScreeOn(): Boolean { val displayManager: DisplayManager = context.getSystemService(Context.DISPLAY_SERVICE) as DisplayManager return displayManager.displays.any { display -> display.state == Display.STATE_ON } } }
mit
25adfb43151dee9c28523012f45d1c54
38.965116
140
0.729919
5.182504
false
false
false
false
alex-tavella/MooV
feature/movie-details/impl/src/main/java/br/com/moov/moviedetails/domain/MovieDetail.kt
1
1044
/* * Copyright 2020 Alex Almeida Tavella * * 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 br.com.moov.moviedetails.domain data class MovieDetail( val id: Int, val title: String?, val posterUrl: String? = null, val overview: String? = null, val releaseDate: String? = null, val genres: List<String> = emptyList(), val originalLanguage: String? = null, val backdropUrl: String? = null, val popularity: Float = 0F, val voteAverage: Float = 0F, val isBookmarked: Boolean = false )
apache-2.0
7ddce0c452aa412eeb6e1e98efabc18c
33.8
75
0.707854
4.062257
false
false
false
false
binaryfoo/emv-bertlv
src/main/java/io/github/binaryfoo/decoders/EmvBitStringDecoder.kt
1
2526
package io.github.binaryfoo.decoders import io.github.binaryfoo.DecodedData import io.github.binaryfoo.Decoder import io.github.binaryfoo.bit.fromHex import io.github.binaryfoo.decoders.bit.BitStringField import io.github.binaryfoo.decoders.bit.EmvBitStringParser import io.github.binaryfoo.res.ClasspathIO import io.github.binaryfoo.tlv.ISOUtil import org.apache.commons.io.IOUtils import java.io.IOException import java.util.* /** * Decoder based on the config language (DSL...). * <p> * Each line in fileName should be parseable in one of the 3 formats: * <ul> * <li>Enumerated - a direct mapping from a set of bits to a name. Bits can be spread over multiple bytes.</li> * <li>Full byte - similar to enumerated but only handles a single byte.</li> * <li>Numeric - the left or right nibble in a byte is interpreted as an integer.</li> * </ul> */ open class EmvBitStringDecoder(fileName: String, val showFieldHexInDecoding: Boolean) : Decoder { private val bitMappings: List<BitStringField> private val maxLength: Int init { val input = ClasspathIO.open(fileName) try { bitMappings = EmvBitStringParser.parse(IOUtils.readLines(input)) } catch (e: IOException) { throw RuntimeException(e) } finally { IOUtils.closeQuietly(input) } this.maxLength = findMaxLengthInBytes() * 2 } override fun getMaxLength(): Int = maxLength private fun findMaxLengthInBytes(): Int { if (bitMappings.isEmpty()) { return 0 } fun max(a: Int, b: Int): Int = if ((a >= b)) a else b return bitMappings.map { it.getStartBytesOffset() + it.getLengthInBytes() }.reduce(::max) } override fun decode(input: String, startIndexInBytes: Int, session: DecodeSession): List<DecodedData> { val decoded = ArrayList<DecodedData>() val bits = fromHex(input) for (field in bitMappings) { val v = field.getValueIn(bits) if (v != null) { val fieldStartIndex = startIndexInBytes + field.getStartBytesOffset() decoded.add(DecodedData.primitive(field.getPositionIn(if (showFieldHexInDecoding) bits else null), v, fieldStartIndex, fieldStartIndex + field.getLengthInBytes())) } } return decoded } override fun validate(input: String?): String? { if (input == null || input.length != maxLength) { return "Value must be exactly $maxLength characters" } if (!ISOUtil.isValidHexString(input)) { return "Value must contain only the characters 0-9 and A-F" } return null } }
mit
dc6981d53ce0827cf795a0e0e07489e1
33.135135
171
0.702296
3.92236
false
false
false
false
yujintao529/android_practice
MyPractice/app/src/main/java/com/example/mypractice/kotlin/ThemesDsl2.kt
1
2666
package com.example.mypractice.kotlin class Gradle { //采用成员变量进行dsl val dependencies = Dependencies() //采用函数dsl,Android不包含invoke函数 private val _android = Android() fun android(block: Android.() -> Unit) { _android.block() } //invoke约束函数 operator fun invoke(block: Gradle.() -> Unit) { block() } } //android对象配置 class Android { //两种方式 var compileSdkVersion = -1 fun compileSdkVersion(sdk: Int) { compileSdkVersion = sdk } var targetSdkVersion = 12 //defaultConfig对象配置 val defaultConfig = DefaultConfig() } class DefaultConfig { var applicationId = "" get() { println("get applicationId") return field } set(value) { println("set applicationId") field = value } operator fun invoke(block: DefaultConfig.() -> Unit) { block() } } class Dependencies { fun compile(str: String) { println("compile $str") } fun annotationProcessor(str: String) { println("annotationProcessor $str") } operator fun invoke(block: Dependencies.() -> Unit) { block() } } class DownloadManager { fun download(url: String) { println("downManager down $url ") } operator fun invoke(url: String) { println("invoke $url ") download(url) } } fun main(args: Array<String>) { val block = { x: Int, y: Int -> x + y } var gradle = Gradle() gradle { android { compileSdkVersion(2) compileSdkVersion = 2 targetSdkVersion = 27 defaultConfig { applicationId = "com.google.android.internal" } } dependencies { compile("com.android.support:support-v4:23.1.1") annotationProcessor("com.jakewharton:butterknife-compiler:8.4.0") } } val downloadManager = DownloadManager() //正常调用方法 downloadManager.download("www.demon-yu.com/file") //高级调用方法 downloadManager("www.demon-yu.com/file1") downloadManager("www.demon-yu.com/file2") downloadManager("www.demon-yu.com/file3") val theme = global { icon = "柯南皮肤" color = "蓝色" } println(theme) } class Theme { var icon: String? = null var color: String? = null override fun toString(): String { return "$icon $color" } } fun global(block: Theme.() -> Unit): Theme { val theme = Theme() theme.block() return theme }
apache-2.0
8322d59af604581211e430de7c9862df
17.3
77
0.567916
4.086124
false
false
false
false
ageery/kwicket
kwicket-core/src/main/kotlin/org/kwicket/model/PropModel.kt
1
3206
package org.kwicket.model import org.apache.wicket.WicketRuntimeException import org.apache.wicket.model.IModel import java.io.Serializable import kotlin.reflect.KMutableProperty1 import kotlin.reflect.KProperty1 import kotlin.reflect.jvm.javaGetter import kotlin.reflect.jvm.javaMethod import kotlin.reflect.jvm.jvmErasure /** * [IModel] that applies the [props] to the [model] for getting and setting the model's value. * * @param T type of the [IModel]'s value/object * @param model [IModel] whose value is * @param props [PropChain] that is applied to the [model] value to get the value of the [IModel] */ class PropModel<T>(val model: IModel<*>, private val props: PropChain<T>) : IModel<T> { constructor(model: IModel<*>, prop: KProperty1<*, T>) : this(model = model, props = PropChain { +prop }) override fun getObject(): T = if (model.value == null) null as T else props.getValue(model.value) override fun setObject(value: T) = props.setValue(model.value, value) } /** * Represents a [Serializable] chain of properties. */ class PropChain<T>(init: PropChainBuilder.() -> KProperty1<*, T>) : Serializable { private val getters: List<String> private val setter: SetterInfo<T>? init { val builder = PropChainBuilder() val lastProp = init(builder) getters = builder.getterNamees.toList() @Suppress("UNCHECKED_CAST") setter = if (lastProp !is KMutableProperty1) null else SetterInfo( name = lastProp.setter.javaMethod!!.name, type = lastProp.setter.parameters[1].type.jvmErasure.java as Class<out T> ) } @Suppress("UNCHECKED_CAST") private fun computeValue(obj: Any?, getters: List<String>): T = getters.fold(obj, { value, getterName -> value?.let { it::class.java.getMethod(getterName).invoke(value) } }) as T fun getValue(obj: Any?): T = computeValue(obj, getters) fun setValue(obj: Any?, value: T) { if (setter != null) { val setterParentValue = computeValue(obj, getters.subList(0, getters.size - 1)) if (setterParentValue != null) { setter.setValue(setterParentValue, value) } else { throw WicketRuntimeException("Parent object is null") } } else { throw WicketRuntimeException("There is no setter") } } } /** * Builder for creating a [PropChain] object. */ class PropChainBuilder { private var props: MutableList<KProperty1<*, *>> = mutableListOf() operator fun <T, R> KProperty1<T, R>.unaryPlus(): KProperty1<T, R> { props.add(this) return this } operator fun <T, S, R> KProperty1<T, R>.plus(other: KProperty1<S, R>): KProperty1<S, R> { if (props.isEmpty()) { props.add(this) } props.add(other) return other } val getterNamees: Sequence<String> get() = props.asSequence().map { it.javaGetter!!.name } } private class SetterInfo<T>(val name: String, val type: Class<out T>) : Serializable { fun setValue(obj: Any, value: T) { obj::class.java.getMethod(name, type).invoke(obj, value) } }
apache-2.0
bf8a6d13340dca4649983a700bb2f363
31.06
108
0.640674
3.881356
false
false
false
false
PaulWoitaschek/Voice
app/src/main/kotlin/voice/app/features/bookmarks/BookmarkController.kt
1
4452
package voice.app.features.bookmarks import android.os.Bundle import android.view.View import androidx.appcompat.widget.PopupMenu import androidx.recyclerview.widget.DefaultItemAnimator import androidx.recyclerview.widget.ItemTouchHelper import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import com.google.android.material.snackbar.Snackbar import voice.app.R import voice.app.databinding.BookmarkBinding import voice.app.features.bookmarks.dialogs.AddBookmarkDialog import voice.app.features.bookmarks.dialogs.EditBookmarkDialog import voice.app.features.bookmarks.list.BookMarkHolder import voice.app.features.bookmarks.list.BookmarkAdapter import voice.app.features.bookmarks.list.BookmarkClickListener import voice.app.injection.appComponent import voice.app.misc.conductor.context import voice.app.mvp.MvpController import voice.common.BookId import voice.data.Bookmark import voice.data.Chapter import voice.data.getBookId import voice.data.putBookId /** * Dialog for creating a bookmark */ private const val NI_BOOK_ID = "ni#bookId" class BookmarkController(args: Bundle) : MvpController<BookmarkView, BookmarkPresenter, BookmarkBinding>(BookmarkBinding::inflate, args), BookmarkView, BookmarkClickListener, AddBookmarkDialog.Callback, EditBookmarkDialog.Callback { constructor(bookId: BookId) : this( Bundle().apply { putBookId(NI_BOOK_ID, bookId) }, ) private val bookId = args.getBookId(NI_BOOK_ID)!! private val adapter = BookmarkAdapter(this) override fun createPresenter() = appComponent.bookmarkPresenter.apply { bookId = [email protected] } override fun render(bookmarks: List<Bookmark>, chapters: List<Chapter>) { adapter.newData(bookmarks, chapters) } override fun showBookmarkAdded(bookmark: Bookmark) { val index = adapter.indexOf(bookmark) binding.recycler.smoothScrollToPosition(index) Snackbar.make(view!!, R.string.bookmark_added, Snackbar.LENGTH_SHORT) .show() } override fun onBookmarkClicked(bookmark: Bookmark) { presenter.selectBookmark(bookmark.id) router.popController(this) } override fun onEditBookmark(id: Bookmark.Id, title: String) { presenter.editBookmark(id, title) } override fun onBookmarkNameChosen(name: String) { presenter.addBookmark(name) } override fun finish() { router.popController(this) } override fun BookmarkBinding.onBindingCreated() { setupToolbar() setupList() addBookmarkFab.setOnClickListener { showAddBookmarkDialog() } } override fun onDestroyView() { binding.recycler.adapter = null } private fun BookmarkBinding.setupToolbar() { toolbar.setNavigationIcon(R.drawable.close) toolbar.setNavigationOnClickListener { router.popController(this@BookmarkController) } } private fun BookmarkBinding.setupList() { val layoutManager = LinearLayoutManager(context) recycler.layoutManager = layoutManager recycler.adapter = adapter val itemAnimator = recycler.itemAnimator as DefaultItemAnimator itemAnimator.supportsChangeAnimations = false val swipeCallback = object : ItemTouchHelper.SimpleCallback(0, ItemTouchHelper.RIGHT) { override fun onMove( recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder, target: RecyclerView.ViewHolder, ): Boolean { return false } override fun onSwiped(viewHolder: RecyclerView.ViewHolder, direction: Int) { val boundBookmark = (viewHolder as BookMarkHolder).boundBookmark boundBookmark?.let { presenter.deleteBookmark(it.id) } } } ItemTouchHelper(swipeCallback).attachToRecyclerView(recycler) } override fun onOptionsMenuClicked(bookmark: Bookmark, v: View) { val popup = PopupMenu(context, v) popup.menuInflater.inflate(R.menu.bookmark_popup, popup.menu) popup.setOnMenuItemClickListener { when (it.itemId) { R.id.edit -> { showEditBookmarkDialog(bookmark) true } R.id.delete -> { presenter.deleteBookmark(bookmark.id) true } else -> false } } popup.show() } private fun showEditBookmarkDialog(bookmark: Bookmark) { EditBookmarkDialog(this, bookmark).showDialog(router) } private fun showAddBookmarkDialog() { AddBookmarkDialog(this).showDialog(router) } }
gpl-3.0
9619bbe592973efa3fc1b128d94f8a9c
28.68
98
0.743037
4.515213
false
false
false
false
AcapellaSoft/Aconite
aconite-core/src/io/aconite/Exceptions.kt
1
1014
package io.aconite /** * Throws if something go wrong with HTTP interfaces. Most of the time this * exception means, that the interface is not satisfy some constraints. */ open class AconiteException(message: String? = null, cause: Throwable? = null): RuntimeException(message, cause) open class HttpException(val code: Int, message: String? = null, cause: Throwable? = null): Exception(message, cause) { override fun toString(): String { return "HttpException(code=$code, message=$message)" } } open class BadRequestException(message: String? = null, cause: Throwable? = null): HttpException(400, message, cause) open class ArgumentMissingException(message: String? = null, cause: Throwable? = null): BadRequestException(message, cause) open class MethodNotAllowedException(message: String? = null, cause: Throwable? = null): HttpException(405, message, cause) open class UnsupportedMediaTypeException(message: String? = null, cause: Throwable? = null): HttpException(415, message, cause)
mit
7f102342a7428de4a56893a817db4d46
47.333333
127
0.751479
4.314894
false
false
false
false
GeoffreyMetais/vlc-android
application/tools/src/main/java/org/videolan/tools/PathUtils.kt
1
757
package org.videolan.tools /** * Checks if the specified (sanitized) path is contained in this collection (of sanitized paths) */ fun List<String>.containsPath(path: String) = any { it.sanitizePath() == path.sanitizePath() } /** * Checks if the specified (sanitized) path is contained in this array (of sanitized paths) */ fun Array<String>.containsPath(path: String) = any { it.sanitizePath() == path.sanitizePath() } /** * Sanitize a path [String] to remove leading "file://" and trailing "/" */ fun String.sanitizePath(): String { var result = this if (result.endsWith('/')) { result = result.substringBeforeLast("/") } if (result.startsWith("file://")) { result = result.substring(7) } return result }
gpl-2.0
08602b4d75ce70d0157364735ceae5cf
29.28
97
0.659181
3.882051
false
false
false
false
tasks/tasks
app/src/main/java/org/tasks/filters/FilterProvider.kt
1
14614
package org.tasks.filters import android.content.Context import android.content.Intent import com.todoroo.astrid.api.CustomFilter import com.todoroo.astrid.api.Filter import com.todoroo.astrid.api.FilterListItem import com.todoroo.astrid.api.FilterListItem.NO_ORDER import com.todoroo.astrid.core.BuiltInFilterExposer import dagger.hilt.android.qualifiers.ApplicationContext import org.tasks.BuildConfig import org.tasks.R import org.tasks.activities.GoogleTaskListSettingsActivity import org.tasks.activities.NavigationDrawerCustomization import org.tasks.activities.TagSettingsActivity import org.tasks.billing.Inventory import org.tasks.caldav.BaseCaldavCalendarSettingsActivity import org.tasks.data.* import org.tasks.data.CaldavAccount.Companion.TYPE_ETESYNC import org.tasks.data.CaldavAccount.Companion.TYPE_LOCAL import org.tasks.data.CaldavAccount.Companion.TYPE_OPENTASKS import org.tasks.filters.NavigationDrawerSubheader.SubheaderType import org.tasks.location.LocationPickerActivity import org.tasks.preferences.HelpAndFeedback import org.tasks.preferences.MainPreferences import org.tasks.preferences.Preferences import org.tasks.ui.NavigationDrawerFragment import javax.inject.Inject class FilterProvider @Inject constructor( @param:ApplicationContext private val context: Context, private val inventory: Inventory, private val builtInFilterExposer: BuiltInFilterExposer, private val filterDao: FilterDao, private val tagDataDao: TagDataDao, private val googleTaskListDao: GoogleTaskListDao, private val caldavDao: CaldavDao, private val preferences: Preferences, private val locationDao: LocationDao) { suspend fun listPickerItems(): List<FilterListItem> = googleTaskFilters(false).plus(caldavFilters(false)) suspend fun navDrawerItems(): List<FilterListItem> = getAllFilters(hideUnused = true).plus(navDrawerFooter) suspend fun filterPickerItems(): List<FilterListItem> = getAllFilters(showCreate = false) suspend fun drawerCustomizationItems(): List<FilterListItem> = getAllFilters(showBuiltIn = false) private fun getDebugFilters(): List<FilterListItem> = if (BuildConfig.DEBUG) { val collapsed = preferences.getBoolean(R.string.p_collapse_debug, false) listOf(NavigationDrawerSubheader( context.getString(R.string.debug), false, collapsed, SubheaderType.PREFERENCE, R.string.p_collapse_debug.toLong(), 0, null, )) .apply { if (collapsed) return this } .plus(listOf( BuiltInFilterExposer.getNoListFilter(), BuiltInFilterExposer.getNoTitleFilter(), BuiltInFilterExposer.getMissingListFilter(), BuiltInFilterExposer.getMissingAccountFilter(), BuiltInFilterExposer.getNoCreateDateFilter(), BuiltInFilterExposer.getNoModificationDateFilter(), BuiltInFilterExposer.getDeleted() )) } else { emptyList() } private suspend fun addFilters(showCreate: Boolean, showBuiltIn: Boolean): List<FilterListItem> = if (!preferences.getBoolean(R.string.p_filters_enabled, true)) { emptyList() } else { val collapsed = preferences.getBoolean(R.string.p_collapse_filters, false) listOf( NavigationDrawerSubheader( context.getString(R.string.filters), false, collapsed, SubheaderType.PREFERENCE, R.string.p_collapse_filters.toLong(), NavigationDrawerFragment.REQUEST_NEW_FILTER, if (showCreate) Intent() else null)) .apply { if (collapsed) return this } .plusAllIf(showBuiltIn) { builtInFilterExposer.filters() } .plus(filterDao.getFilters().map(::CustomFilter).sort()) } private suspend fun addTags(showCreate: Boolean, hideUnused: Boolean): List<FilterListItem> = if (!preferences.getBoolean(R.string.p_tags_enabled, true)) { emptyList() } else { val collapsed = preferences.getBoolean(R.string.p_collapse_tags, false) listOf( NavigationDrawerSubheader( context.getString(R.string.tags), false, collapsed, SubheaderType.PREFERENCE, R.string.p_collapse_tags.toLong(), NavigationDrawerFragment.REQUEST_NEW_LIST, if (showCreate) { Intent(context, TagSettingsActivity::class.java) } else { null })) .apply { if (collapsed) return this } .plus(tagDataDao.getTagFilters() .filterIf(hideUnused && preferences.getBoolean(R.string.p_tags_hide_unused, false)) { it.count > 0 } .map(TagFilters::toTagFilter) .sort()) } private suspend fun addPlaces(showCreate: Boolean, hideUnused: Boolean): List<FilterListItem> = if (!preferences.getBoolean(R.string.p_places_enabled, true)) { emptyList() } else { val collapsed = preferences.getBoolean(R.string.p_collapse_locations, false) listOf( NavigationDrawerSubheader( context.getString(R.string.places), false, collapsed, SubheaderType.PREFERENCE, R.string.p_collapse_locations.toLong(), NavigationDrawerFragment.REQUEST_NEW_PLACE, if (showCreate) { Intent(context, LocationPickerActivity::class.java) } else { null })) .apply { if (collapsed) return this } .plus(locationDao.getPlaceFilters() .filterIf(hideUnused && preferences.getBoolean(R.string.p_places_hide_unused, false)) { it.count > 0 } .map(LocationFilters::toLocationFilter) .sort()) } private suspend fun getAllFilters( showCreate: Boolean = true, showBuiltIn: Boolean = true, hideUnused: Boolean = false, ): List<FilterListItem> = if (showBuiltIn) { arrayListOf(builtInFilterExposer.myTasksFilter) } else { ArrayList<FilterListItem>() } .asSequence() .plus(addFilters(showCreate, showBuiltIn)) .plus(addTags(showCreate, hideUnused)) .plus(addPlaces(showCreate, hideUnused)) .plus(googleTaskFilters(showCreate)) .plus(caldavFilters(showCreate)) .toList() .plusAllIf(BuildConfig.DEBUG) { getDebugFilters() } private val navDrawerFooter: List<FilterListItem> get() = listOf(NavigationDrawerSeparator()) .plusIf(BuildConfig.FLAVOR == "generic" && !inventory.hasTasksAccount) { NavigationDrawerAction( context.getString(R.string.TLA_menu_donate), R.drawable.ic_outline_attach_money_24px, NavigationDrawerFragment.REQUEST_DONATE) } .plusIf(!inventory.hasPro) { NavigationDrawerAction( context.getString(R.string.name_your_price), R.drawable.ic_outline_attach_money_24px, NavigationDrawerFragment.REQUEST_PURCHASE) } .plus(NavigationDrawerAction( context.getString(R.string.manage_drawer), R.drawable.ic_outline_edit_24px, Intent(context, NavigationDrawerCustomization::class.java), 0)) .plus(NavigationDrawerAction( context.getString(R.string.TLA_menu_settings), R.drawable.ic_outline_settings_24px, Intent(context, MainPreferences::class.java), NavigationDrawerFragment.REQUEST_SETTINGS)) .plus(NavigationDrawerAction( context.getString(R.string.help_and_feedback), R.drawable.ic_outline_help_outline_24px, Intent(context, HelpAndFeedback::class.java), 0)) private suspend fun googleTaskFilters(showCreate: Boolean = true): List<FilterListItem> = googleTaskListDao.getAccounts().flatMap { googleTaskFilter(it, showCreate) } private suspend fun googleTaskFilter(account: GoogleTaskAccount, showCreate: Boolean): List<FilterListItem> = listOf( NavigationDrawerSubheader( account.account, account.error?.isNotBlank() ?: false, account.isCollapsed, SubheaderType.GOOGLE_TASKS, account.id, NavigationDrawerFragment.REQUEST_NEW_LIST, if (showCreate) { Intent(context, GoogleTaskListSettingsActivity::class.java) .putExtra(GoogleTaskListSettingsActivity.EXTRA_ACCOUNT, account) } else { null })) .apply { if (account.isCollapsed) return this } .plus(googleTaskListDao .getGoogleTaskFilters(account.account!!) .map(GoogleTaskFilters::toGtasksFilter) .sort()) private suspend fun caldavFilters(showCreate: Boolean = true): List<FilterListItem> = caldavDao.getAccounts() .ifEmpty { listOf(caldavDao.setupLocalAccount(context)) } .filter { it.accountType != TYPE_LOCAL || preferences.getBoolean(R.string.p_lists_enabled, true) } .flatMap { caldavFilter(it, showCreate && it.accountType != TYPE_OPENTASKS && it.accountType != TYPE_ETESYNC) } private suspend fun caldavFilter(account: CaldavAccount, showCreate: Boolean): List<FilterListItem> = listOf( NavigationDrawerSubheader( if (account.accountType == TYPE_LOCAL) { context.getString(R.string.local_lists) } else { account.name }, account.error?.isNotBlank() ?: false, account.isCollapsed, when { account.isTasksOrg -> SubheaderType.TASKS account.isEteSyncAccount -> SubheaderType.ETESYNC else -> SubheaderType.CALDAV }, account.id, NavigationDrawerFragment.REQUEST_NEW_LIST, if (showCreate) { Intent(context, account.listSettingsClass()) .putExtra( BaseCaldavCalendarSettingsActivity.EXTRA_CALDAV_ACCOUNT, account ) } else { null } )) .apply { if (account.isCollapsed) return this } .plus(caldavDao .getCaldavFilters(account.uuid!!) .map(CaldavFilters::toCaldavFilter) .sort()) companion object { private val COMPARATOR = Comparator<Filter> { f1, f2 -> when { f1.order == NO_ORDER && f2.order == NO_ORDER -> f1.id.compareTo(f2.id) f1.order == NO_ORDER -> 1 f2.order == NO_ORDER -> -1 f1.order < f2.order -> -1 f1.order > f2.order -> 1 else -> AlphanumComparator.FILTER.compare(f1, f2) } } private fun List<Filter>.sort(): List<Filter> = if (all { it.order == NO_ORDER }) { sortedWith(AlphanumComparator.FILTER) } else { sortedWith(COMPARATOR) } private suspend fun <T> Collection<T>.plusAllIf(predicate: Boolean, item: suspend () -> Iterable<T>): List<T> = plus(if (predicate) item() else emptyList()) private fun <T> Iterable<T>.plusIf(predicate: Boolean, item: () -> T): Iterable<T> = if (predicate) plus(item()) else this private fun <T> Iterable<T>.filterIf(predicate: Boolean, predicate2: (T) -> Boolean): Iterable<T> = if (predicate) filter(predicate2) else this } }
gpl-3.0
14d76d19d87d015ffa85fb3be1b8d710
48.538983
131
0.507869
5.603528
false
false
false
false
arturbosch/detekt
detekt-core/src/test/kotlin/io/gitlab/arturbosch/detekt/core/rules/RuleSetLocatorSpec.kt
1
1665
package io.gitlab.arturbosch.detekt.core.rules import io.gitlab.arturbosch.detekt.api.RuleSetProvider import io.gitlab.arturbosch.detekt.core.createNullLoggingSpec import io.gitlab.arturbosch.detekt.core.tooling.withSettings import org.assertj.core.api.Assertions.assertThat import org.assertj.core.api.Assertions.fail import org.reflections.Reflections import org.spekframework.spek2.Spek import org.spekframework.spek2.style.specification.describe import java.lang.reflect.Modifier class RuleSetLocatorSpec : Spek({ describe("locating RuleSetProvider's") { it("contains all RuleSetProviders") { val providers = createNullLoggingSpec().withSettings { RuleSetLocator(this).load() } val providerClasses = getProviderClasses() assertThat(providerClasses).isNotEmpty providerClasses .filter { clazz -> providers.firstOrNull { it.javaClass == clazz } == null } .forEach { fail("$it rule set is not loaded by the RuleSetLocator") } } it("does not load any default rule set provider when opt out") { val providers = createNullLoggingSpec { extensions { disableDefaultRuleSets = true } } .withSettings { RuleSetLocator(this).load() } val defaultProviders = getProviderClasses().toSet() assertThat(providers).noneMatch { it.javaClass in defaultProviders } } } }) private fun getProviderClasses(): List<Class<out RuleSetProvider>> = Reflections("io.gitlab.arturbosch.detekt.rules") .getSubTypesOf(RuleSetProvider::class.java) .filter { !Modifier.isAbstract(it.modifiers) }
apache-2.0
c9e5063c359107fa7724392002fe5ad3
39.609756
98
0.708108
4.730114
false
false
false
false
hypercube1024/firefly
firefly-net/src/test/kotlin/com/fireflysource/net/http/client/impl/content/handler/TestFileContentHandler.kt
1
1690
package com.fireflysource.net.http.client.impl.content.handler import com.fireflysource.common.io.readFileBytesAsync import com.fireflysource.net.http.client.HttpClientContentHandlerFactory.fileHandler import com.fireflysource.net.http.client.HttpClientResponse import kotlinx.coroutines.future.await import kotlinx.coroutines.test.runTest import org.junit.jupiter.api.AfterEach import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.DisplayName import org.junit.jupiter.api.Test import org.mockito.Mockito import java.nio.ByteBuffer import java.nio.file.Files import java.nio.file.Paths import java.nio.file.StandardOpenOption.WRITE import java.util.* class TestFileContentHandler { private val response = Mockito.mock(HttpClientResponse::class.java) private val tmpFile = Paths.get(System.getProperty("user.home"), "tmpFile${UUID.randomUUID()}.txt") @BeforeEach fun init() { Files.createFile(tmpFile) println("create a file: $tmpFile") } @AfterEach fun destroy() { Files.delete(tmpFile) println("delete file: $tmpFile") } @Test @DisplayName("should write data to file successfully") fun test() = runTest { val handler = fileHandler(tmpFile, WRITE) arrayOf( ByteBuffer.wrap("hello".toByteArray()), ByteBuffer.wrap(" file".toByteArray()), ByteBuffer.wrap(" handler".toByteArray()) ).forEach { handler.accept(it, response) } handler.closeAsync().await() val str = readFileBytesAsync(tmpFile).await() assertEquals("hello file handler", String(str)) } }
apache-2.0
336c414aac0db4b070b3c4d6a8a50812
30.90566
103
0.721893
4.300254
false
true
false
false
hewking/HUILibrary
app/src/main/java/com/hewking/custom/textview/GCLinkTextView.kt
1
3560
package com.hewking.custom.textview import android.content.Context import android.graphics.Region import androidx.core.util.PatternsCompat import androidx.appcompat.widget.AppCompatTextView import android.text.InputFilter import android.text.Spannable import android.text.SpannableStringBuilder import android.text.TextPaint import android.text.method.LinkMovementMethod import android.text.style.ClickableSpan import android.text.style.URLSpan import android.util.AttributeSet import android.view.View /** * 项目名称:FlowChat * 类的描述: * 创建人员:hewking * 创建时间:2018/11/22 0022 * 修改人员:hewking * 修改时间:2018/11/22 0022 * 修改备注: * Version: 1.0.0 */ class GCLinkTextView(ctx: Context, attrs: AttributeSet) : AppCompatTextView(ctx, attrs) { private var mOriginText: CharSequence? = null private var regionList: MutableList<MatchRegion> = mutableListOf() init { movementMethod = LinkMovementMethod() } override fun setText(text: CharSequence?, type: BufferType?) { //1.通过正则表达式匹配出 text 的url //2.把匹配出的url 通过spannable 的方式,下划线标出来 并且设置点击事件 //3.在设置行数 如果超过 n 行,则 spannable 的位置截取 并且最后设置 三个点 more // 没设置 text 之前肯定是没有layout 设置过值的,所以也没有 Linecount,所以匹配出的 url 都要保存一下 mOriginText = text if (regionList == null) { regionList = mutableListOf() } var maxLength = 0 for (filter in filters) { if (filter is InputFilter.LengthFilter) { val field = filter.javaClass.getDeclaredField("mMax") field.isAccessible = true maxLength = Math.max(maxLength, field.get(filter) as Int) } } val matcher = PatternsCompat.WEB_URL.matcher(text) val offset = getMoreString().length while (matcher.find()) { var end = matcher.end() if (end >= maxLength - 1) { end = maxLength val start = matcher.start() var group = matcher.group() // val subLen = maxLength - start - offset // group = group.substring(0, subLen) + getMoreString() val region = MatchRegion(start, end, group) regionList.add(region) break } val region = MatchRegion(matcher.start(), end, matcher.group()) regionList.add(region) } var text = mOriginText if (mOriginText?.length ?: 0 > maxLength) { text = mOriginText?.substring(0, maxLength - offset) + getMoreString() } val span = SpannableStringBuilder(text) for (region in regionList) { span.setSpan(object : URLSpan(region.text) { override fun onClick(widget: View?) { super.onClick(widget) } override fun updateDrawState(ds: TextPaint?) { super.updateDrawState(ds) } }, region.start, region.end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE) } super.setText(span, type) } data class MatchRegion(val start: Int, val end: Int, val text: String) fun getMoreString(): String { return "..." } }
mit
1a49143d9894525431f8f35fc2616ec7
31
82
0.591874
4.24453
false
false
false
false
Karumi/Shot
shot-consumer-compose/app/src/main/java/com/karumi/shotconsumercompose/ui/Theme.kt
1
1166
package com.karumi.shotconsumercompose.ui import androidx.compose.foundation.isSystemInDarkTheme import androidx.compose.material.MaterialTheme import androidx.compose.material.darkColors import androidx.compose.material.lightColors import androidx.compose.runtime.Composable private val DarkColorPalette = darkColors( primary = purple200, primaryVariant = purple700, secondary = teal200 ) private val LightColorPalette = lightColors( primary = purple500, primaryVariant = purple700, secondary = teal200 /* Other default colors to override background = Color.White, surface = Color.White, onPrimary = Color.White, onSecondary = Color.Black, onBackground = Color.Black, onSurface = Color.Black, */ ) @Composable fun ShotConsumerComposeTheme(darkTheme: Boolean = isSystemInDarkTheme(), content: @Composable() () -> Unit) { val colors = if (darkTheme) { DarkColorPalette } else { LightColorPalette } MaterialTheme( colors = colors, typography = typography, shapes = shapes, content = content ) }
apache-2.0
1ebc5ca71214cd98d78bb1501fec4860
25.522727
109
0.683533
4.982906
false
false
false
false
openstreetview/android
app/src/main/java/com/telenav/osv/data/collector/phonedata/collector/WifiCollector.kt
1
5040
package com.telenav.osv.data.collector.phonedata.collector import android.Manifest import android.content.BroadcastReceiver import android.content.Context import android.content.Intent import android.content.IntentFilter import android.content.pm.PackageManager import android.net.wifi.WifiManager import android.os.Handler import androidx.core.app.ActivityCompat import com.telenav.osv.data.collector.datatype.datatypes.WifiObject import com.telenav.osv.data.collector.datatype.util.LibraryUtil import com.telenav.osv.data.collector.phonedata.manager.PhoneDataListener import timber.log.Timber import java.net.NetworkInterface import java.util.* import kotlin.experimental.and /** * WifiCollector class collects information about wifi connection */ class WifiCollector(private val context: Context, phoneDataListener: PhoneDataListener?, notifyHandler: Handler?) : PhoneCollector(phoneDataListener, notifyHandler) { /** * BroadcastReceiver used for detecting any changes on battery */ private var wifiBroadcastReceiver: BroadcastReceiver? = null /** * Field used to verify if the wifi receiver was registerd or not */ private var isWifiReceiverRegisterd = false /** * Register a [BroadcastReceiver] for monitoring the wifi state. * Every change of wifi state will notify the receiver */ fun startCollectingWifiData() { if (!isWifiReceiverRegisterd && ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_WIFI_STATE) === PackageManager.PERMISSION_GRANTED) { wifiBroadcastReceiver = object : BroadcastReceiver() { override fun onReceive(context: Context, intent: Intent) { onWifiChanged() } } val intentFilter = IntentFilter() intentFilter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION) context.registerReceiver(wifiBroadcastReceiver, intentFilter, null, notifyHandler) isWifiReceiverRegisterd = true } } /** * Retrieve the wifi information and send the information to the client * The method is called every time when the wifi state is changed */ private fun onWifiChanged() { val wifiManager = context.getSystemService(Context.WIFI_SERVICE) as WifiManager val wifiInfo = wifiManager.connectionInfo val wifiObject = WifiObject(LibraryUtil.PHONE_SENSOR_READ_SUCCESS) wifiObject.wifiState = wifiManager.wifiState wifiObject.bssid = wifiInfo.bssid wifiObject.ssid = wifiInfo.ssid wifiObject.macAddress = macAddress wifiObject.ipAddress = getFormatedIpAddres(wifiInfo.ipAddress) wifiObject.networkId = wifiInfo.networkId onNewSensorEvent(wifiObject) } /** * Converts an integer to the specific IP address * * @param ip Integer that represents the IP address * @return The formated IP address */ fun getFormatedIpAddres(ip: Int): String { return String.format( Locale.US, "%d.%d.%d.%d", ip and 0xff, ip shr 8 and 0xff, ip shr 16 and 0xff, ip shr 24 and 0xff) } fun unregisterReceiver() { if (wifiBroadcastReceiver != null && isWifiReceiverRegisterd) { context.unregisterReceiver(wifiBroadcastReceiver) isWifiReceiverRegisterd = false } } companion object { /** * Fake mac address used for OS versions > 5 */ private const val FAKE_MAC_ADDRESS = "02:00:00:00:00:00" private const val TAG = "WifiCollector" private const val WLAN_NAME = "wlan0" /** * Extract the mac address of the device if it is accessible * * @return The real mac address is the OS version is < 6 or a fake mac address if not */ private val macAddress: String private get() { try { val networkInterfaceList: List<NetworkInterface> = Collections.list(NetworkInterface.getNetworkInterfaces()) for (networkInterface in networkInterfaceList) { if (!networkInterface.name.equals(WLAN_NAME, ignoreCase = true)) continue val macAddressBytes = networkInterface.hardwareAddress ?: return "" val macAddress = StringBuilder() for (b in macAddressBytes) { macAddress.append(Integer.toHexString((b and 0xFF.toByte()).toInt())).append(":") } if (macAddress.isNotEmpty()) { macAddress.deleteCharAt(macAddress.length - 1) } return macAddress.toString() } } catch (ex: Exception) { Timber.tag(TAG).e(ex) } return FAKE_MAC_ADDRESS } } }
lgpl-3.0
520cd077b330ce57127d5c13735b148f
38.692913
166
0.633532
5.174538
false
false
false
false
vanita5/twittnuker
twittnuker/src/main/kotlin/de/vanita5/twittnuker/util/ListViewScrollHandler.kt
1
2437
package de.vanita5.twittnuker.util import android.widget.AbsListView import android.widget.ListView import de.vanita5.twittnuker.util.support.ViewSupport class ListViewScrollHandler<A>( contentListSupport: ContentScrollHandler.ContentListSupport<A>, viewCallback: ContentScrollHandler.ViewCallback? ) : ContentScrollHandler<A>(contentListSupport, viewCallback), AbsListView.OnScrollListener, ListScrollDistanceCalculator.ScrollDistanceListener { private val calculator: ListScrollDistanceCalculator = ListScrollDistanceCalculator() var onScrollListener: AbsListView.OnScrollListener? = null private var dy: Int = 0 private var oldState = AbsListView.OnScrollListener.SCROLL_STATE_IDLE constructor(contentListSupport: ContentScrollHandler.ContentListSupport<A>, listView: ListView) : this(contentListSupport, ListViewCallback(listView)) override fun onScrollStateChanged(view: AbsListView, scrollState: Int) { calculator.onScrollStateChanged(view, scrollState) calculator.setScrollDistanceListener(this) handleScrollStateChanged(scrollState, AbsListView.OnScrollListener.SCROLL_STATE_IDLE) if (onScrollListener != null) { onScrollListener!!.onScrollStateChanged(view, scrollState) } } override fun onScroll(view: AbsListView, firstVisibleItem: Int, visibleItemCount: Int, totalItemCount: Int) { calculator.onScroll(view, firstVisibleItem, visibleItemCount, totalItemCount) val scrollState = scrollState handleScroll(dy, scrollState, oldState, AbsListView.OnScrollListener.SCROLL_STATE_IDLE) if (onScrollListener != null) { onScrollListener!!.onScroll(view, firstVisibleItem, visibleItemCount, totalItemCount) } } val totalScrollDistance: Int get() = calculator.totalScrollDistance override fun onScrollDistanceChanged(delta: Int, total: Int) { dy = -delta val scrollState = scrollState handleScroll(dy, scrollState, oldState, AbsListView.OnScrollListener.SCROLL_STATE_IDLE) oldState = scrollState } class ListViewCallback(private val listView: AbsListView) : ContentScrollHandler.ViewCallback { override val computingLayout: Boolean get() = ViewSupport.isInLayout(listView) override fun post(runnable: Runnable) { listView.post(runnable) } } }
gpl-3.0
a7c0915548b6396543518aba49396c92
41.034483
113
0.738613
5.24086
false
false
false
false
stripe/stripe-android
paymentsheet/src/main/java/com/stripe/android/paymentsheet/BottomSheetController.kt
1
2535
package com.stripe.android.paymentsheet import android.view.View import android.view.ViewGroup import androidx.lifecycle.MutableLiveData import androidx.lifecycle.distinctUntilChanged import com.google.android.material.bottomsheet.BottomSheetBehavior internal class BottomSheetController( private val bottomSheetBehavior: BottomSheetBehavior<ViewGroup> ) { private val _shouldFinish = MutableLiveData(false) internal val shouldFinish = _shouldFinish.distinctUntilChanged() fun setup() { bottomSheetBehavior.isHideable = true bottomSheetBehavior.isDraggable = false bottomSheetBehavior.state = BottomSheetBehavior.STATE_HIDDEN bottomSheetBehavior.saveFlags = BottomSheetBehavior.SAVE_ALL bottomSheetBehavior.addBottomSheetCallback( object : BottomSheetBehavior.BottomSheetCallback() { override fun onSlide(bottomSheet: View, slideOffset: Float) { } override fun onStateChanged(bottomSheet: View, newState: Int) { when (newState) { BottomSheetBehavior.STATE_EXPANDED -> { // isFitToContents causes conflicts when calculating the sheet position // upon resize. CoordinatorLayout will already position the sheet // correctly with gravity = bottom. bottomSheetBehavior.isFitToContents = false } BottomSheetBehavior.STATE_HIDDEN -> { // finish the activity only after the bottom sheet's state has // transitioned to `BottomSheetBehavior.STATE_HIDDEN` _shouldFinish.value = true } else -> { } } } } ) } fun expand() { bottomSheetBehavior.state = BottomSheetBehavior.STATE_EXPANDED } fun hide() { if (bottomSheetBehavior.state == BottomSheetBehavior.STATE_HIDDEN) { // If the state is already hidden, setting the state to hidden is a no-op, // so we need to finish it now. _shouldFinish.value = true } else { // When the bottom sheet finishes animating to its new state, // the callback will finish the activity. bottomSheetBehavior.state = BottomSheetBehavior.STATE_HIDDEN } } }
mit
4ee6c0971869bace17f1484e0626a2ed
39.887097
99
0.597633
6.198044
false
false
false
false
stripe/stripe-android
stripecardscan/src/main/java/com/stripe/android/stripecardscan/framework/util/Device.kt
1
3683
package com.stripe.android.stripecardscan.framework.util import android.annotation.SuppressLint import android.content.Context import android.os.Build import android.provider.Settings import android.telephony.TelephonyManager import com.stripe.android.camera.framework.util.cacheFirstResult import java.util.Locale internal data class Device( val android_id: String?, val name: String, val bootCount: Int, val locale: String?, val carrier: String?, val networkOperator: String?, val phoneType: Int?, val phoneCount: Int, val osVersion: Int, val platform: String ) { companion object { private val getDeviceDetails = cacheFirstResult { context: Context? -> Device( android_id = getAndroidId(), name = getDeviceName(), bootCount = getDeviceBootCount(context), locale = getDeviceLocale(), carrier = getDeviceCarrier(context), networkOperator = getNetworkOperator(context), phoneType = getDevicePhoneType(context), phoneCount = getDevicePhoneCount(context), osVersion = getOsVersion(), platform = getPlatform() ) } @JvmStatic fun fromContext(context: Context?) = getDeviceDetails(context?.applicationContext) } } /** * This was redacted for privacy reasons. Normally, this would be retrieved by this code: * * ``` * Settings.Secure.getString(context.contentResolver, Settings.Secure.ANDROID_ID) * ``` */ @SuppressLint("HardwareIds") private fun getAndroidId() = "Redacted" private fun getDeviceBootCount(context: Context?): Int = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { try { context?.let { Settings.Global.getInt(it.contentResolver, Settings.Global.BOOT_COUNT) } ?: -1 } catch (t: Throwable) { -1 } } else { -1 } private fun getDeviceLocale(): String = "${Locale.getDefault().isO3Language}_${Locale.getDefault().isO3Country}" private fun getDeviceCarrier(context: Context?) = try { (context?.getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager?)?.networkOperatorName } catch (t: Throwable) { null } private fun getDevicePhoneType(context: Context?) = try { (context?.getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager?)?.phoneType } catch (t: Throwable) { null } private fun getDevicePhoneCount(context: Context?) = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { try { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) { (context?.getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager?) ?.activeModemCount ?: -1 } else { @Suppress("deprecation") (context?.getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager?) ?.phoneCount ?: -1 } } catch (t: Throwable) { -1 } } else { -1 } private fun getNetworkOperator(context: Context?) = (context?.getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager?)?.networkOperator internal fun getOsVersion() = Build.VERSION.SDK_INT internal fun getPlatform() = "android" /** * from https://stackoverflow.com/a/27836910/947883 */ internal fun getDeviceName(): String { val manufacturer = Build.MANUFACTURER?.lowercase() ?: "" val model = Build.MODEL?.lowercase() ?: "" return if (model.startsWith(manufacturer)) { model } else { "$manufacturer $model" } }
mit
06905198da233712c47e1bec949fa679
30.211864
100
0.635352
4.496947
false
false
false
false
nrizzio/Signal-Android
app/src/main/java/org/thoughtcrime/securesms/contacts/paged/ContactSearchViewModel.kt
1
6105
package org.thoughtcrime.securesms.contacts.paged import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.Transformations import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelProvider import io.reactivex.rxjava3.core.Observable import io.reactivex.rxjava3.disposables.CompositeDisposable import io.reactivex.rxjava3.kotlin.plusAssign import io.reactivex.rxjava3.subjects.PublishSubject import org.signal.paging.LivePagedData import org.signal.paging.PagedData import org.signal.paging.PagingConfig import org.signal.paging.PagingController import org.thoughtcrime.securesms.database.model.DistributionListPrivacyMode import org.thoughtcrime.securesms.groups.SelectionLimits import org.thoughtcrime.securesms.recipients.Recipient import org.thoughtcrime.securesms.util.livedata.Store import org.whispersystems.signalservice.api.util.Preconditions /** * Simple, reusable view model that manages a ContactSearchPagedDataSource as well as filter and expansion state. */ class ContactSearchViewModel( private val selectionLimits: SelectionLimits, private val contactSearchRepository: ContactSearchRepository, private val performSafetyNumberChecks: Boolean, private val safetyNumberRepository: SafetyNumberRepository = SafetyNumberRepository(), ) : ViewModel() { private val disposables = CompositeDisposable() private val pagingConfig = PagingConfig.Builder() .setBufferPages(1) .setPageSize(20) .setStartIndex(0) .build() private val pagedData = MutableLiveData<LivePagedData<ContactSearchKey, ContactSearchData>>() private val configurationStore = Store(ContactSearchState()) private val selectionStore = Store<Set<ContactSearchKey>>(emptySet()) private val errorEvents = PublishSubject.create<ContactSearchError>() val controller: LiveData<PagingController<ContactSearchKey>> = Transformations.map(pagedData) { it.controller } val data: LiveData<List<ContactSearchData>> = Transformations.switchMap(pagedData) { it.data } val configurationState: LiveData<ContactSearchState> = configurationStore.stateLiveData val selectionState: LiveData<Set<ContactSearchKey>> = selectionStore.stateLiveData val errorEventsStream: Observable<ContactSearchError> = errorEvents override fun onCleared() { disposables.clear() } fun setConfiguration(contactSearchConfiguration: ContactSearchConfiguration) { val pagedDataSource = ContactSearchPagedDataSource(contactSearchConfiguration) pagedData.value = PagedData.createForLiveData(pagedDataSource, pagingConfig) } fun setQuery(query: String?) { configurationStore.update { it.copy(query = query) } } fun expandSection(sectionKey: ContactSearchConfiguration.SectionKey) { configurationStore.update { it.copy(expandedSections = it.expandedSections + sectionKey) } } fun setKeysSelected(contactSearchKeys: Set<ContactSearchKey>) { disposables += contactSearchRepository.filterOutUnselectableContactSearchKeys(contactSearchKeys).subscribe { results -> if (results.any { !it.isSelectable }) { errorEvents.onNext(ContactSearchError.CONTACT_NOT_SELECTABLE) return@subscribe } val newSelectionEntries = results.filter { it.isSelectable }.map { it.key } - getSelectedContacts() val newSelectionSize = newSelectionEntries.size + getSelectedContacts().size if (selectionLimits.hasRecommendedLimit() && getSelectedContacts().size < selectionLimits.recommendedLimit && newSelectionSize >= selectionLimits.recommendedLimit) { errorEvents.onNext(ContactSearchError.RECOMMENDED_LIMIT_REACHED) } else if (selectionLimits.hasHardLimit() && newSelectionSize > selectionLimits.hardLimit) { errorEvents.onNext(ContactSearchError.HARD_LIMIT_REACHED) return@subscribe } if (performSafetyNumberChecks) { safetyNumberRepository.batchSafetyNumberCheck(newSelectionEntries) } selectionStore.update { state -> state + newSelectionEntries } } } fun setKeysNotSelected(contactSearchKeys: Set<ContactSearchKey>) { selectionStore.update { it - contactSearchKeys } } fun getSelectedContacts(): Set<ContactSearchKey> { return selectionStore.state } fun addToVisibleGroupStories(groupStories: Set<ContactSearchKey.RecipientSearchKey.Story>) { disposables += contactSearchRepository.markDisplayAsStory(groupStories.map { it.recipientId }).subscribe { configurationStore.update { state -> state.copy( groupStories = state.groupStories + groupStories.map { val recipient = Recipient.resolved(it.recipientId) ContactSearchData.Story(recipient, recipient.participantIds.size, DistributionListPrivacyMode.ALL) } ) } } } fun removeGroupStory(story: ContactSearchData.Story) { Preconditions.checkArgument(story.recipient.isGroup) setKeysNotSelected(setOf(story.contactSearchKey)) disposables += contactSearchRepository.unmarkDisplayAsStory(story.recipient.requireGroupId()).subscribe { configurationStore.update { state -> state.copy( groupStories = state.groupStories.filter { it.recipient.id == story.recipient.id }.toSet() ) } refresh() } } fun deletePrivateStory(story: ContactSearchData.Story) { Preconditions.checkArgument(story.recipient.isDistributionList && !story.recipient.isMyStory) setKeysNotSelected(setOf(story.contactSearchKey)) disposables += contactSearchRepository.deletePrivateStory(story.recipient.requireDistributionListId()).subscribe { refresh() } } fun refresh() { controller.value?.onDataInvalidated() } class Factory( private val selectionLimits: SelectionLimits, private val repository: ContactSearchRepository, private val performSafetyNumberChecks: Boolean ) : ViewModelProvider.Factory { override fun <T : ViewModel> create(modelClass: Class<T>): T { return modelClass.cast(ContactSearchViewModel(selectionLimits, repository, performSafetyNumberChecks)) as T } } }
gpl-3.0
619587b906d8822952adf487ecabfb87
40.25
171
0.773464
4.788235
false
true
false
false
androidx/androidx
glance/glance-appwidget/src/androidMain/kotlin/androidx/glance/appwidget/GlanceAppWidget.kt
3
20238
/* * Copyright 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.glance.appwidget import android.appwidget.AppWidgetManager import android.content.Context import android.os.Build import android.os.Bundle import android.util.Log import android.widget.RemoteViews import androidx.annotation.DoNotInline import androidx.annotation.LayoutRes import androidx.annotation.RequiresApi import androidx.annotation.VisibleForTesting import androidx.compose.runtime.BroadcastFrameClock import androidx.compose.runtime.Composable import androidx.compose.runtime.Composition import androidx.compose.runtime.CompositionLocalProvider import androidx.compose.runtime.Recomposer import androidx.compose.ui.unit.DpSize import androidx.glance.Applier import androidx.glance.GlanceComposable import androidx.glance.GlanceId import androidx.glance.LocalContext import androidx.glance.LocalGlanceId import androidx.glance.LocalSize import androidx.glance.LocalState import androidx.glance.appwidget.state.getAppWidgetState import androidx.glance.session.SessionManager import androidx.glance.state.GlanceState import androidx.glance.state.GlanceStateDefinition import androidx.glance.state.PreferencesGlanceStateDefinition import kotlinx.coroutines.CancellationException import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Job import kotlinx.coroutines.async import kotlinx.coroutines.awaitAll import kotlinx.coroutines.coroutineScope import kotlinx.coroutines.launch import kotlinx.coroutines.withContext fun interface AppWidgetProviderScope { /** * Provides [content] to the Glance host, suspending until the Glance session is * shut down. If this method is called concurrently with itself, the previous * call will throw [CancellationException] and the new content will replace it. */ suspend fun setContent(content: @Composable @GlanceComposable () -> Unit) } /** * Object handling the composition and the communication with [AppWidgetManager]. * * The UI is defined by the [Content] composable function. Calling [update] will start * the composition and translate [Content] into a [RemoteViews] which is then sent to the * [AppWidgetManager]. * * @param errorUiLayout If different from 0 and an error occurs within this GlanceAppWidget, * the App Widget is updated with an error UI using this layout resource ID. */ abstract class GlanceAppWidget( @LayoutRes internal val errorUiLayout: Int = R.layout.glance_error_layout, ) { /** * Override this function to provide the Glance Composable. * * This is a good place to load any data needed to render the Composable. Use * [AppWidgetProviderScope.setContent] to provide the Composable once it is ready. * * TODO(b/239747024) make abstract once Content() is removed. */ @Suppress("UNUSED_PARAMETER") open suspend fun AppWidgetProviderScope.provideGlance( @Suppress("ContextFirst") context: Context, glanceId: GlanceId, ) { setContent { Content() } } /** * Definition of the UI. * TODO(b/239747024) remove and update any usage to the new provideGlance API. */ @Composable @GlanceComposable abstract fun Content() /** * Defines the handling of sizes. */ open val sizeMode: SizeMode = SizeMode.Single /** * Data store for widget data specific to the view. */ open val stateDefinition: GlanceStateDefinition<*>? = PreferencesGlanceStateDefinition /** * Method called by the framework when an App Widget has been removed from its host. * * When the method returns, the state associated with the [glanceId] will be deleted. */ open suspend fun onDelete(context: Context, glanceId: GlanceId) {} // TODO(b/239747024) remove once SessionManager is the default open val sessionManager: SessionManager? = null /** * Triggers the composition of [Content] and sends the result to the [AppWidgetManager]. */ suspend fun update( context: Context, glanceId: GlanceId ) { require(glanceId is AppWidgetId) { "The glanceId '$glanceId' is not a valid App Widget glance id" } update(context, AppWidgetManager.getInstance(context), glanceId.appWidgetId) } /** * Calls [onDelete], then clear local data associated with the [appWidgetId]. * * This is meant to be called when the App Widget instance has been deleted from the host. */ internal suspend fun deleted(context: Context, appWidgetId: Int) { val glanceId = AppWidgetId(appWidgetId) sessionManager?.closeSession(glanceId.toSessionKey()) try { onDelete(context, glanceId) } catch (cancelled: CancellationException) { // Nothing to do here } catch (t: Throwable) { Log.e(GlanceAppWidgetTag, "Error in user-provided deletion callback", t) } finally { stateDefinition?.let { GlanceState.deleteStore(context, it, createUniqueRemoteUiName(appWidgetId)) } } } /** * Internal version of [update], to be used by the broadcast receiver directly. */ internal suspend fun update( context: Context, appWidgetManager: AppWidgetManager, appWidgetId: Int, options: Bundle? = null, ) { Tracing.beginGlanceAppWidgetUpdate() sessionManager?.let { val glanceId = AppWidgetId(appWidgetId) if (!it.isSessionRunning(context, glanceId.toSessionKey())) { it.startSession(context, AppWidgetSession(this, glanceId, options)) } else { val session = it.getSession(glanceId.toSessionKey()) as AppWidgetSession session.updateGlance() } return } safeRun(context, appWidgetManager, appWidgetId) { val opts = options ?: appWidgetManager.getAppWidgetOptions(appWidgetId)!! val state = stateDefinition?.let { GlanceState.getValue(context, it, createUniqueRemoteUiName(appWidgetId)) } appWidgetManager.updateAppWidget( appWidgetId, compose(context, appWidgetManager, appWidgetId, state, opts) ) } } /** * Trigger an action to be run in the AppWidgetSession for this widget, starting the session if * necessary. */ internal suspend fun triggerAction( context: Context, appWidgetId: Int, actionKey: String, options: Bundle? = null, ) { sessionManager?.let { manager -> val glanceId = AppWidgetId(appWidgetId) val session = if (!manager.isSessionRunning(context, glanceId.toSessionKey())) { AppWidgetSession(this, glanceId, options).also { session -> manager.startSession(context, session) } } else { manager.getSession(glanceId.toSessionKey()) as AppWidgetSession } session.runLambda(actionKey) } ?: error( "GlanceAppWidget.triggerAction may only be used when a SessionManager is provided" ) } /** * Internal method called when a resize event is detected. */ internal suspend fun resize( context: Context, appWidgetManager: AppWidgetManager, appWidgetId: Int, options: Bundle ) { sessionManager?.let { manager -> val glanceId = AppWidgetId(appWidgetId) if (!manager.isSessionRunning(context, glanceId.toSessionKey())) { manager.startSession(context, AppWidgetSession(this, glanceId, options)) } else { val session = manager.getSession(glanceId.toSessionKey()) as AppWidgetSession session.updateAppWidgetOptions(options) } return } // Note, on Android S, if the mode is `Responsive`, then all the sizes are specified from // the start and we don't need to update the AppWidget when the size changes. if (sizeMode is SizeMode.Exact || (Build.VERSION.SDK_INT < Build.VERSION_CODES.S && sizeMode is SizeMode.Responsive) ) { update(context, appWidgetManager, appWidgetId, options) } } // Trigger the composition of the View to create the RemoteViews. @VisibleForTesting internal suspend fun compose( context: Context, appWidgetManager: AppWidgetManager, appWidgetId: Int, state: Any?, options: Bundle ): RemoteViews { val layoutConfig = LayoutConfiguration.load(context, appWidgetId) return try { compose(context, appWidgetManager, appWidgetId, state, options, layoutConfig) } finally { layoutConfig.save() } } @VisibleForTesting internal suspend fun compose( context: Context, appWidgetManager: AppWidgetManager, appWidgetId: Int, state: Any?, options: Bundle, layoutConfig: LayoutConfiguration, ): RemoteViews = when (val localSizeMode = this.sizeMode) { is SizeMode.Single -> { composeForSize( context, appWidgetId, state, options, appWidgetMinSize( context.resources.displayMetrics, appWidgetManager, appWidgetId ), layoutConfig, ) } is SizeMode.Exact -> { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) { Api31Impl.composeAllSizes( this, context, appWidgetId, state, options, options.extractAllSizes { appWidgetMinSize( context.resources.displayMetrics, appWidgetManager, appWidgetId ) }, layoutConfig, ) } else { composeExactMode( context, appWidgetManager, appWidgetId, state, options, layoutConfig, ) } } is SizeMode.Responsive -> { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) { Api31Impl.composeAllSizes( this, context, appWidgetId, state, options, localSizeMode.sizes, layoutConfig, ) } else { composeResponsiveMode( context, appWidgetId, state, options, localSizeMode.sizes, layoutConfig, ) } } } private suspend fun composeExactMode( context: Context, appWidgetManager: AppWidgetManager, appWidgetId: Int, state: Any?, options: Bundle, layoutConfig: LayoutConfiguration, ) = coroutineScope { val views = options.extractOrientationSizes() .map { size -> async { composeForSize( context, appWidgetId, state, options, size, layoutConfig, ) } }.awaitAll() combineLandscapeAndPortrait(views) ?: composeForSize( context, appWidgetId, state, options, appWidgetMinSize(context.resources.displayMetrics, appWidgetManager, appWidgetId), layoutConfig, ) } // Combine the views, which should be landscape and portrait, in that order, if they are // available. private fun combineLandscapeAndPortrait(views: List<RemoteViews>): RemoteViews? = when (views.size) { 2 -> RemoteViews(views[0], views[1]) 1 -> views[0] 0 -> null else -> throw IllegalArgumentException("There must be between 0 and 2 views.") } private suspend fun composeResponsiveMode( context: Context, appWidgetId: Int, state: Any?, options: Bundle, sizes: Set<DpSize>, layoutConfig: LayoutConfiguration, ) = coroutineScope { // Find the best view, emulating what Android S+ would do. val orderedSizes = sizes.sortedBySize() val smallestSize = orderedSizes[0] val views = options.extractOrientationSizes() .map { size -> findBestSize(size, sizes) ?: smallestSize } .map { size -> async { composeForSize( context, appWidgetId, state, options, size, layoutConfig, ) } }.awaitAll() combineLandscapeAndPortrait(views) ?: composeForSize( context, appWidgetId, state, options, smallestSize, layoutConfig, ) } @VisibleForTesting internal suspend fun composeForSize( context: Context, appWidgetId: Int, state: Any?, options: Bundle, size: DpSize, layoutConfig: LayoutConfiguration, ): RemoteViews = withContext(BroadcastFrameClock()) { // The maximum depth must be reduced if the compositions are combined val root = RemoteViewsRoot(maxDepth = MaxComposeTreeDepth) val applier = Applier(root) val recomposer = Recomposer(coroutineContext) val composition = Composition(applier, recomposer) val glanceId = AppWidgetId(appWidgetId) composition.setContent(context, glanceId, options, state, size) launch { recomposer.runRecomposeAndApplyChanges() } recomposer.close() recomposer.join() normalizeCompositionTree(root) translateComposition( context, appWidgetId, root, layoutConfig, layoutConfig.addLayout(root), size ) } private fun Composition.setContent( context: Context, glanceId: AppWidgetId, options: Bundle, state: Any?, size: DpSize ) { setContent { CompositionLocalProvider( LocalContext provides context, LocalGlanceId provides glanceId, LocalAppWidgetOptions provides options, LocalState provides state, LocalSize provides size, ) { Content() } } } private companion object { /** * Maximum depth for a composition. Although there is no hard limit, this should avoid deep * recursions, which would create [RemoteViews] too large to be sent. */ private const val MaxComposeTreeDepth = 50 } @RequiresApi(Build.VERSION_CODES.S) private object Api31Impl { @DoNotInline suspend fun composeAllSizes( glance: GlanceAppWidget, context: Context, appWidgetId: Int, state: Any?, options: Bundle, allSizes: Collection<DpSize>, layoutConfig: LayoutConfiguration ): RemoteViews = coroutineScope { val allViews = allSizes.map { size -> async { size.toSizeF() to glance.composeForSize( context, appWidgetId, state, options, size, layoutConfig, ) } }.awaitAll() allViews.singleOrNull()?.second ?: RemoteViews(allViews.toMap()) } } private suspend fun safeRun( context: Context, appWidgetManager: AppWidgetManager, appWidgetId: Int, block: suspend () -> Unit, ) { try { block() } catch (ex: CancellationException) { // Nothing to do } catch (throwable: Throwable) { if (errorUiLayout == 0) { throw throwable } logException(throwable) val rv = RemoteViews(context.packageName, errorUiLayout) appWidgetManager.updateAppWidget(appWidgetId, rv) } finally { Tracing.endGlanceAppWidgetUpdate() } } /** * Creates a snapshot of the GlanceAppWidget content without running recomposition. * Useful to only generate once the composed RemoteViews instance. * * @see GlanceAppWidget.composeForSize * @see GlanceAppWidgetManager.requestPinGlanceAppWidget */ internal fun snapshot( context: Context, appWidgetId: Int, state: Any?, options: Bundle, size: DpSize, ): RemoteViews { // The maximum depth must be reduced if the compositions are combined val root = RemoteViewsRoot(maxDepth = MaxComposeTreeDepth) val applier = Applier(root) val scope = CoroutineScope(Job() + Dispatchers.Main) val recomposer = Recomposer(scope.coroutineContext) val composition = Composition(applier, recomposer) val glanceId = AppWidgetId(appWidgetId) composition.setContent(context, glanceId, options, state, size) normalizeCompositionTree(root) return translateComposition(context, appWidgetId, root, null, 0, size) } } internal data class AppWidgetId(val appWidgetId: Int) : GlanceId /** Update all App Widgets managed by the [GlanceAppWidget] class. */ suspend fun GlanceAppWidget.updateAll(@Suppress("ContextFirst") context: Context) { val manager = GlanceAppWidgetManager(context) manager.getGlanceIds(javaClass).forEach { update(context, it) } } /** * Update all App Widgets managed by the [GlanceAppWidget] class, if they fulfill some condition. */ suspend inline fun <reified State> GlanceAppWidget.updateIf( @Suppress("ContextFirst") context: Context, predicate: (State) -> Boolean ) { val stateDef = stateDefinition requireNotNull(stateDef) { "GlanceAppWidget.updateIf cannot be used if no state is defined." } val manager = GlanceAppWidgetManager(context) manager.getGlanceIds(javaClass).forEach { glanceId -> val state = getAppWidgetState(context, stateDef, glanceId) as State if (predicate(state)) update(context, glanceId) } }
apache-2.0
3de09f226db1d4b5db5a4de645b34e9f
34.135417
99
0.584544
5.472688
false
false
false
false
odd-poet/kotlin-expect
src/main/kotlin/net/oddpoet/expect/extension/Int.kt
1
1016
package net.oddpoet.expect.extension import net.oddpoet.expect.Expect /** * Extension: Int * * @author Yunsang Choi */ fun Expect<Int>.beGreaterThan(other: Int) = satisfyThat("be greater than ${other.literal}") { it > other } fun Expect<Int>.beGreaterThanOrEqualTo(other: Int) = satisfyThat("be greater than or equal to ${other.literal}") { it >= other } fun Expect<Int>.beLessThan(other: Int) = satisfyThat("be less than ${other.literal}") { it < other } fun Expect<Int>.beLessThanOrEqualTo(other: Int) = satisfyThat("be less than or equal to ${other.literal}") { it <= other } fun Expect<Int>.beBetween(lower: Int, upper: Int) = satisfyThat("be between ${lower.literal} and ${upper.literal}") { it in lower..upper } fun Expect<Int>.beIn(range: ClosedRange<Int>) = satisfyThat("be in the range of ${range.literal}") { it in range }
apache-2.0
0d5d099f4a432834db6066f4f0d45757
23.190476
73
0.586614
3.907692
false
false
false
false
DemonWav/StatCraft
src/main/kotlin/com/demonwav/statcraft/listeners/JumpListener.kt
1
1224
/* * StatCraft Bukkit Plugin * * Copyright (c) 2016 Kyle Wood (DemonWav) * https://www.demonwav.com * * MIT License */ package com.demonwav.statcraft.listeners import com.demonwav.statcraft.StatCraft import com.demonwav.statcraft.querydsl.QJumps import org.bukkit.Statistic import org.bukkit.event.EventHandler import org.bukkit.event.EventPriority import org.bukkit.event.Listener import org.bukkit.event.player.PlayerStatisticIncrementEvent class JumpListener(private val plugin: StatCraft) : Listener { @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) fun onJump(event: PlayerStatisticIncrementEvent) { if (event.statistic == Statistic.JUMP) { val uuid = event.player.uniqueId val worldName = event.player.world.name plugin.threadManager.schedule<QJumps>( uuid, worldName, { j, clause, id, worldId -> clause.columns(j.id, j.worldId, j.amount).values(id, worldId, 1).execute() }, { j, clause, id, worldId -> clause.where(j.id.eq(id), j.worldId.eq(worldId)).set(j.amount, j.amount.add(1)).execute() } ) } } }
mit
db3171080888205e9bfacc3b536cd477
32.081081
109
0.651144
4.026316
false
false
false
false
ushastikin/rubocop-for-rubymine
src/io/github/sirlantis/rubymine/rubocop/RubocopTask.kt
1
8841
package io.github.sirlantis.rubymine.rubocop import com.intellij.openapi.progress.Task import com.intellij.openapi.project.Project import com.intellij.openapi.progress.ProgressIndicator import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.projectRoots.Sdk import com.intellij.openapi.module.ModuleManager import com.intellij.openapi.roots.ModuleRootManager import com.intellij.openapi.vfs.VirtualFile import com.intellij.openapi.roots.ProjectRootManager import com.intellij.openapi.project.ProjectLocator import java.io.InputStreamReader import io.github.sirlantis.rubymine.rubocop.model.RubocopResult import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.module.Module import java.io.Closeable import java.io.BufferedInputStream import com.intellij.openapi.application.Application import kotlin.properties.Delegates import org.jetbrains.plugins.ruby.ruby.run.RunnerUtil import io.github.sirlantis.rubymine.rubocop.utils.NotifyUtil import org.jetbrains.plugins.ruby.gem.util.BundlerUtil import java.util.LinkedList class RubocopTask(val module: Module, val paths: List<String>) : Task.Backgroundable(module.getProject(), "Running RuboCop", true) { var result: RubocopResult? = null val sdk: Sdk { sdk = getSdkForModule(module) } val sdkRoot: String get() { return sdk.getHomeDirectory().getParent().getCanonicalPath() } override fun run(indicator: ProgressIndicator) { run() } fun run() { if (!isRubySdk(sdk)) { logger.warn("Not a Ruby SDK") return } if (!hasRubocopConfig) { logger.warn("Didn't find $RUBOCOP_CONFIG_FILENAME") return } runViaCommandLine() } fun parseProcessOutput(start: () -> Process) { val process: Process try { process = start.invoke() } catch (e: Exception) { logger.warn("Failed to run RuboCop command", e) logger.error("Failed to run RuboCop command - is it (or bundler) installed? (SDK=%s)".format(sdkRoot), e) return } val bufferSize = 5 * 1024 * 1024 val stdoutStream = BufferedInputStream(process.getInputStream(), bufferSize) val stdoutReader = InputStreamReader(stdoutStream) val stderrStream = BufferedInputStream(process.getErrorStream(), bufferSize) try { result = RubocopResult.readFromReader(stdoutReader) } catch (e: Exception) { logger.warn("Failed to parse RuboCop output", e) logParseFailure(stderrStream, stdoutStream) } var exited = false try { process.waitFor() exited = true } catch (e: Exception) { logger.error("Interrupted while waiting for RuboCop", e) } tryClose(stdoutStream) tryClose(stderrStream) if (exited) { when (process.exitValue()) { 0, 1 -> logger.warn("RuboCop exited with %d".format(process.exitValue())) else -> logger.info("RuboCop exited with %d".format(process.exitValue())) } } if (result != null) { onComplete?.invoke(this) } } private fun logParseFailure(stderrStream: BufferedInputStream, stdoutStream: BufferedInputStream) { val stdout = readStreamToString(stdoutStream, true) val stderr = readStreamToString(stderrStream) logger.warn("=== RuboCop STDOUT START ===\n%s\n=== RuboCop STDOUT END ===".format(stdout)) logger.warn("=== RuboCop STDERR START ===\n%s\n=== RuboCop STDERR END ===".format(stderr)) val errorBuilder = StringBuilder("Please make sure that:") errorBuilder.append("<ul>") if (usesBundler) { errorBuilder.append("<li>you added <code>gem 'rubocop'</code> to your <code>Gemfile</code></li>") errorBuilder.append("<li>you did run <code>bundle install</code> successfully</li>") } else { errorBuilder.append("<li>you installed RuboCop for this Ruby version</li>") } errorBuilder.append("<li>your RuboCop version isn't ancient</li>") errorBuilder.append("</ul>") errorBuilder.append("<pre><code>") errorBuilder.append(stderr) errorBuilder.append("</code></pre>") NotifyUtil.notifyError(getProject(), "Failed to parse RuboCop output", errorBuilder.toString()) } fun readStreamToString(stream: BufferedInputStream, reset: Boolean = false): String { if (reset) { try { stream.reset() } catch(e: Exception) { logger.warn("Couldn't reset stream", e) return "" } } var result: String try { result = InputStreamReader(stream).readText() } catch (e: Exception) { logger.warn("Couldn't read stream", e) result = "" } return result } fun runViaCommandLine() { val runner = RunnerUtil.getRunner(sdk, module) val commandLineList = linkedListOf("rubocop", "--format", "json") commandLineList.addAll(paths) if (usesBundler) { val bundler = BundlerUtil.getBundlerGem(sdk, module, true) val bundleCommand = bundler.getFile().findChild("bin").findChild("bundle") commandLineList.addAll(0, linkedListOf(bundleCommand.getCanonicalPath(), "exec")) } // prepend ruby binary to the command val rubyInterpreterExecutable = sdk.getHomePath(); commandLineList.add(0, rubyInterpreterExecutable) val command = commandLineList.removeFirst() val args = commandLineList.copyToArray() val commandLine = runner.createAndSetupCmdLine(workDirectory.getCanonicalPath(), null, true, command, sdk, *args) if (usesBundler) { val preprocessor = BundlerUtil.createBundlerPreprocessor(module, sdk) preprocessor.preprocess(commandLine) } logger.debug("Executing RuboCop (SDK=%s, Bundler=%b)".format(sdkRoot, usesBundler), commandLine.getCommandLineString()) parseProcessOutput { commandLine.createProcess() } } val app: Application by Delegates.lazy { ApplicationManager.getApplication() } val workDirectory: VirtualFile by Delegates.lazy { var file: VirtualFile? = null app.runReadAction { val roots = ModuleRootManager.getInstance(module).getContentRoots() file = roots.first() } file as VirtualFile } val usesBundler: Boolean get() { // TODO: better check possible? return workDirectory.findChild("Gemfile") != null } val hasRubocopConfig: Boolean get() { return workDirectory.findChild(RUBOCOP_CONFIG_FILENAME) != null } fun tryClose(closable: Closeable?) { if (closable != null) { try { closable.close() } catch (e: Exception) { // ignore } } } var onComplete: ((RubocopTask) -> Unit)? = null class object { val logger = Logger.getInstance(RubocopBundle.LOG_ID) val RUBOCOP_CONFIG_FILENAME: String = ".rubocop.yml" fun isRubySdk(sdk: Sdk): Boolean { return sdk.getSdkType().getName() == "RUBY_SDK" } fun getModuleForFile(project: Project, file: VirtualFile): Module { return ProjectRootManager.getInstance(project).getFileIndex().getModuleForFile(file) } fun getFirstRubyModuleForProject(project: Project): Module { val modules = ModuleManager.getInstance(project).getModules() return modules first { isRubySdk(ModuleRootManager.getInstance(it).getSdk()) } } fun getSdkForModule(module: Module): Sdk { return ModuleRootManager.getInstance(module).getSdk() } fun forFiles(vararg files: VirtualFile): RubocopTask { kotlin.check(files.count() > 0) { "files must not be empty" } val project = ProjectLocator.getInstance().guessProjectForFile(files.first()) val module = getModuleForFile(project, files.first()) return forFiles(module, *files) } fun forFiles(module: Module, vararg files: VirtualFile): RubocopTask { kotlin.check(files.count() > 0) { "files must not be empty" } val paths = files map { it.getCanonicalPath() } return RubocopTask(module, paths) } fun forPaths(module: Module, vararg paths: String): RubocopTask { return RubocopTask(module, paths.toList()) } } }
mit
8a985c10bc234fb370cff55549532a0f
32.744275
132
0.627418
4.422711
false
false
false
false
jvsegarra/kotlin-koans
src/v_builders/_39_HtmlBuilders.kt
1
1598
package v_builders import v_builders.data.getProducts import v_builders.htmlLibrary.* import util.* fun getTitleColor() = "#b9c9fe" fun getCellColor(index: Int, row: Int) = if ((index + row) % 2 == 0) "#dce4ff" else "#eff2ff" fun todoTask39(): Nothing = TODO( """ Task 39. 1) Fill the table with the proper values from products. 2) Color the table like a chess board (using getTitleColor() and getCellColor() functions above). Pass a color as an argument to functions 'tr', 'td'. You can run the 'Html Demo' configuration in IntelliJ to see the rendered table. """, documentation = doc39() ) fun renderProductTable(): String { return html { table { tr(color = getTitleColor()) { td { text("Product") } td { text("Price") } td { text("Popularity") } } val products = getProducts() var row: Int = 0; for (product in products) { tr { td(color = getCellColor(0, row)) { text(product.description) } td(color = getCellColor(1, row)) { text(product.price) } td(color = getCellColor(2, row)) { text(product.popularity) } } row++; } } }.toString() }
mit
93d5cffd8c478bfa9763f3f9c0bcb020
28.592593
105
0.453692
4.755952
false
false
false
false
fengbaicanhe/intellij-community
platform/configuration-store-impl/testSrc/StorageManagerTest.kt
1
2848
/* * Copyright 2000-2015 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.configurationStore import com.intellij.openapi.components.RoamingType import com.intellij.testFramework.FixtureRule import junit.framework.TestCase import org.hamcrest.CoreMatchers.equalTo import org.hamcrest.CoreMatchers.notNullValue import org.junit.Assert.assertThat import org.junit.Before import org.junit.Rule import org.junit.Test import org.junit.rules.ExpectedException import kotlin.properties.Delegates class StorageManagerTest { private val fixtureManager = FixtureRule() public Rule fun getFixtureManager(): FixtureRule = fixtureManager private val thrown = ExpectedException.none() public Rule fun getThrown(): ExpectedException = thrown private var storageManager: StateStorageManagerImpl by Delegates.notNull() companion object { val MACRO = "\$MACRO1$" } public Before fun setUp() { storageManager = StateStorageManagerImpl("foo") storageManager.addMacro(MACRO, "/temp/m1") } public Test fun testCreateFileStateStorageMacroSubstituted() { assertThat(storageManager.getStateStorage("$MACRO/test.xml", RoamingType.PER_USER), notNullValue()) } public Test fun `collapse macro`() { assertThat(storageManager.collapseMacros("/temp/m1/foo"), equalTo("$MACRO/foo")) assertThat(storageManager.collapseMacros("\\temp\\m1\\foo"), equalTo("\\temp\\m1\\foo")) } public Test fun `add system-dependent macro`() { val key = "\$INVALID$" val expansion = "\\temp" thrown.expectMessage("Macro $key set to system-dependent expansion $expansion"); storageManager.addMacro(key, expansion) } public Test fun `create storage assertion thrown when unknown macro`() { try { storageManager.getStateStorage("\$UNKNOWN_MACRO$/test.xml", RoamingType.PER_USER) TestCase.fail("Exception expected") } catch (e: IllegalArgumentException) { assertThat(e.getMessage(), equalTo("Unknown macro: \$UNKNOWN_MACRO$ in storage file spec: \$UNKNOWN_MACRO$/test.xml")) } } public Test fun `create file storage macro substituted when expansion has$`() { storageManager.addMacro("\$DOLLAR_MACRO$", "/temp/d$") assertThat(storageManager.getStateStorage("\$DOLLAR_MACRO$/test.xml", RoamingType.PER_USER), notNullValue()) } }
apache-2.0
cf74fbb6be2810bb88a8dbcb0f1d043a
35.512821
124
0.74368
4.456964
false
true
false
false
inorichi/tachiyomi-extensions
multisrc/src/main/java/eu/kanade/tachiyomi/multisrc/mangamainac/MangaMainacGenerator.kt
1
2387
package eu.kanade.tachiyomi.multisrc.mangamainac import generator.ThemeSourceData.SingleLang import generator.ThemeSourceGenerator class MangaMainacGenerator : ThemeSourceGenerator { override val themePkg = "mangamainac" override val themeClass = "MangaMainac" override val baseVersionCode: Int = 1 override val sources = listOf( SingleLang("Read Boku No Hero Academia Manga Online", "https://w23.readheroacademia.com/", "en"), SingleLang("Read One Punch Man Manga Online", "https://w17.readonepunchman.net/", "en"), SingleLang("Read One Webcomic Manga Online", "https://w1.onewebcomic.net/", "en"), SingleLang("Read Solo Leveling", "https://w3.sololeveling.net/", "en"), SingleLang("Read Jojolion", "https://readjojolion.com/", "en"), SingleLang("Hajime no Ippo Manga", "https://readhajimenoippo.com/", "en"), SingleLang("Read Berserk Manga Online", "https://berserkmanga.net/", "en"), SingleLang("Read Kaguya-sama: Love is War", "https://kaguyasama.net/", "en", className = "ReadKaguyaSamaLoveIsWar", pkgName = "readkaguyasamaloveiswar"), SingleLang("Read Domestic Girlfriend Manga", "https://domesticgirlfriend.net/", "en"), SingleLang("Read Black Clover Manga", "https://w1.blackclovermanga2.com/", "en"), SingleLang("TCB Scans", "https://onepiecechapters.com/", "en", overrideVersionCode = 2), SingleLang("Read Shingeki no Kyojin Manga", "https://readshingekinokyojin.com/", "en"), SingleLang("Read Nanatsu no Taizai Manga", "https://w1.readnanatsutaizai.net/", "en"), SingleLang("Read Rent a Girlfriend Manga", "https://kanojo-okarishimasu.com/", "en"), //Sites that are currently down from my end, should be rechecked by some one else at some point // //SingleLang("", "https://5-toubunnohanayome.net/", "en"), //Down at time of creating this generator //SingleLang("", "http://beastars.net/", "en"), //Down at time of creating this generator //SingleLang("", "https://neverlandmanga.net/", "en"), //Down at time of creating this generator //SingleLang("", "https://ww1.readhunterxhunter.net/", "en"), //Down at time of creating this generator ) companion object { @JvmStatic fun main(args: Array<String>) { MangaMainacGenerator().createAll() } } }
apache-2.0
19e7c40043e7157f4d8426f8cebade5f
54.511628
161
0.66527
3.611195
false
false
false
false
stfalcon-studio/uaroads_android
app/src/main/java/com/stfalcon/new_uaroads_android/features/tracks/adapter/TracksListAdapter.kt
1
3701
/* * Copyright (c) 2017 stfalcon.com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.stfalcon.new_uaroads_android.features.tracks.adapter import android.content.Context import android.support.v7.widget.RecyclerView import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ImageButton import android.widget.ImageView import android.widget.TextView import com.stfalcon.new_uaroads_android.R import com.stfalcon.new_uaroads_android.common.database.models.TrackRealm import com.stfalcon.new_uaroads_android.ext.hideView import com.stfalcon.new_uaroads_android.ext.showView import io.realm.RealmRecyclerViewAdapter import io.realm.RealmResults import org.jetbrains.anko.find /* * Created by Anton Bevza on 4/27/17. */ class TracksListAdapter(val context: Context, realmResults: RealmResults<TrackRealm>) : RealmRecyclerViewAdapter<TrackRealm, TracksListAdapter.ViewHolder>(realmResults, true) { var onDeleteButtonClick: ((trackId: String) -> Unit)? = null var onSendButtonClick: ((trackId: String) -> Unit)? = null val statusImages = mapOf( TrackRealm.STATUS_SENT to R.drawable.ic_session_status_sent, TrackRealm.STATUS_NOT_SENT to R.drawable.ic_session_status_error, TrackRealm.STATUS_IS_SENDING to R.drawable.ic_session_status_waiting) override fun onBindViewHolder(holder: ViewHolder?, position: Int) { val item = getItem(position) item?.let { track -> holder?.tvTrackComment?.text = track.comment holder?.tvTrackDistance?.text = context.getString(R.string.tracks_distance, track.distance) holder?.ivStatus?.setImageResource(statusImages.getValue(track.status)) when (track.status) { TrackRealm.STATUS_SENT -> { holder?.progress?.hideView() holder?.btnSend?.hideView() } TrackRealm.STATUS_IS_SENDING -> { holder?.progress?.showView() holder?.btnSend?.hideView() } TrackRealm.STATUS_NOT_SENT -> { holder?.progress?.hideView() holder?.btnSend?.showView() } } holder?.btnDelete?.setOnClickListener { onDeleteButtonClick?.invoke(track.id) } holder?.btnSend?.setOnClickListener { onSendButtonClick?.invoke(track.id) } } } override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): ViewHolder { return ViewHolder(LayoutInflater.from(context).inflate(R.layout.item_track, parent, false)) } class ViewHolder(val rootView: View) : RecyclerView.ViewHolder(rootView) { val ivStatus = rootView.find<ImageView>(R.id.ivStatus) val tvTrackComment = rootView.find<TextView>(R.id.tvTrackComment) val tvTrackDistance = rootView.find<TextView>(R.id.tvTrackDistance) val btnSend = rootView.find<ImageButton>(R.id.btnSend) val btnDelete = rootView.find<ImageButton>(R.id.btnDelete) val progress = rootView.find<View>(R.id.progressBar) } }
apache-2.0
6ef0a5281eeb80e694953873b512393e
41.068182
103
0.683059
4.244266
false
false
false
false
PassionateWsj/YH-Android
app/src/main/java/com/intfocus/template/subject/nine/module/text/TextModelImpl.kt
1
1856
package com.intfocus.template.subject.nine.module.text import com.alibaba.fastjson.JSONObject import com.intfocus.template.model.DaoUtil import com.intfocus.template.model.callback.LoadDataCallback import com.intfocus.template.model.gen.SourceDao import com.intfocus.template.subject.nine.CollectionModelImpl import com.intfocus.template.subject.nine.module.ModuleModel /** * @author liuruilin * @data 2017/11/2 * @describe */ class TextModelImpl : ModuleModel<TextEntity> { companion object { private var INSTANCE: TextModelImpl? = null /** * Returns the single instance of this class, creating it if necessary. */ @JvmStatic fun getInstance(): TextModelImpl { return INSTANCE ?: TextModelImpl() .apply { INSTANCE = this } } /** * Used to force [getInstance] to create a new instance * next time it's called. */ @JvmStatic fun destroyInstance() { INSTANCE = null } } override fun analyseData(params: String, callback: LoadDataCallback<TextEntity>) { val data = JSONObject.parseObject(params, TextEntity::class.java) callback.onSuccess(data) } override fun insertDb(value: String, key: String, listItemType: Int) { val sourceDao = DaoUtil.getDaoSession()!!.sourceDao val sourceQb = sourceDao.queryBuilder() val sourceItem = sourceQb.where(sourceQb.and(SourceDao.Properties.Key.eq(key), SourceDao.Properties.Uuid.eq(CollectionModelImpl.uuid))).unique() if (null != sourceItem) { sourceItem.value = value sourceDao.update(sourceItem) if (listItemType != 0) { CollectionModelImpl.getInstance().updateCollectionData(listItemType, value) } } } }
gpl-3.0
4ab817643d35ede455a42848809341bc
32.745455
152
0.651401
4.526829
false
false
false
false
PassionateWsj/YH-Android
app/src/main/java/com/intfocus/template/filter/FilterFragment.kt
1
1854
package com.intfocus.template.filter import android.os.Bundle import android.support.v4.app.Fragment import android.support.v7.widget.RecyclerView import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import com.intfocus.template.R import com.intfocus.template.dashboard.mine.adapter.FilterAdapter import com.intfocus.template.model.response.filter.MenuItem import com.intfocus.template.ui.view.CustomLinearLayoutManager /** * Created by CANC on 2017/8/8. * 筛选界面 */ class FilterFragment(menuDatas: List<MenuItem>, myLisenter: NewFilterFragmentListener) : Fragment(), FilterAdapter.FilterMenuListener { lateinit var mAdapter: FilterAdapter var datas = menuDatas lateinit var mView: View lateinit var recyclerView: RecyclerView var lisenter = myLisenter override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { mView = inflater.inflate(R.layout.fragment_filter, container, false) initView() return mView } fun initView() { recyclerView = mView.findViewById(R.id.recycler_view) mAdapter = FilterAdapter(context!!, datas, this) val layoutManager = CustomLinearLayoutManager(context!!) recyclerView.layoutManager = layoutManager recyclerView.adapter = mAdapter mAdapter.update() } override fun itemClick(position: Int) { for (i in 0 until datas.size) { if (i == position) { datas[position].arrorDirection = true } else { datas[i].arrorDirection = false } } mAdapter.setData(datas) lisenter.itemClick(position, datas) } interface NewFilterFragmentListener { fun itemClick(position: Int, menuDatas: List<MenuItem>) } }
gpl-3.0
5fcae88816c494eab633cbd3e0752183
31.964286
135
0.701517
4.469734
false
false
false
false
TCA-Team/TumCampusApp
app/src/main/java/de/tum/in/tumcampusapp/component/ui/eduroam/EduroamFixCardViewHolder.kt
1
1665
package de.tum.`in`.tumcampusapp.component.ui.eduroam import android.content.Context import android.content.Intent import android.net.wifi.WifiConfiguration import android.view.View import de.tum.`in`.tumcampusapp.R import de.tum.`in`.tumcampusapp.component.ui.overview.CardInteractionListener import de.tum.`in`.tumcampusapp.component.ui.overview.card.CardViewHolder import de.tum.`in`.tumcampusapp.utils.Const import kotlinx.android.synthetic.main.card_eduroam_fix.view.* import org.jetbrains.anko.wifiManager class EduroamFixCardViewHolder( itemView: View, interactionListener: CardInteractionListener ) : CardViewHolder(itemView, interactionListener) { fun bind(eduroam: WifiConfiguration?, errors: List<String>) = with(itemView) { if (errors.isNotEmpty()) { eduroam_errors.visibility = View.VISIBLE eduroam_errors.text = errors.joinToString("\n") } eduroam_action_button.setOnClickListener { performEduroamFix(context, eduroam) } if (errors.size == 1 && errors.first() == context.getString(R.string.wifi_identity_zone)) { eduroam_insecure_message.visibility = View.GONE } } private fun performEduroamFix(context: Context, eduroam: WifiConfiguration?) { eduroam?.let { context.wifiManager.removeNetwork(it.networkId) } val intent = Intent(context, SetupEduroamActivity::class.java) // TCA should only produce correct profiles, so incorrect ones were configured somewhere else intent.putExtra(Const.EXTRA_FOREIGN_CONFIGURATION_EXISTS, true) context.startActivity(intent) } }
gpl-3.0
e54aefce6bcf17090deebc276f6fe4ea
36.840909
101
0.718318
4.131514
false
true
false
false
czyzby/ktx
collections/src/main/kotlin/ktx/collections/arrays.kt
2
19080
@file:Suppress("NOTHING_TO_INLINE", "LoopToCallChain") package ktx.collections import com.badlogic.gdx.utils.Pool import kotlin.contracts.ExperimentalContracts import kotlin.contracts.contract /** Alias for [com.badlogic.gdx.utils.Array] avoiding name collision with the standard library. */ typealias GdxArray<Element> = com.badlogic.gdx.utils.Array<Element> /** Alias for [com.badlogic.gdx.utils.BooleanArray] avoiding name collision with the standard library. */ typealias GdxBooleanArray = com.badlogic.gdx.utils.BooleanArray /** Alias for [com.badlogic.gdx.utils.FloatArray] avoiding name collision with the standard library. */ typealias GdxFloatArray = com.badlogic.gdx.utils.FloatArray /** Alias for [com.badlogic.gdx.utils.IntArray] avoiding name collision with the standard library. */ typealias GdxIntArray = com.badlogic.gdx.utils.IntArray /** Alias for [com.badlogic.gdx.utils.CharArray] avoiding name collision with the standard library. */ typealias GdxCharArray = com.badlogic.gdx.utils.CharArray /** Alias for [com.badlogic.gdx.utils.LongArray] avoiding name collision with the standard library. */ typealias GdxLongArray = com.badlogic.gdx.utils.LongArray /** Alias for [com.badlogic.gdx.utils.ShortArray] avoiding name collision with the standard library. */ typealias GdxShortArray = com.badlogic.gdx.utils.ShortArray /** Alias for [com.badlogic.gdx.utils.ByteArray] avoiding name collision with the standard library. */ typealias GdxByteArray = com.badlogic.gdx.utils.ByteArray /** * Default libGDX array size used by most constructors. */ const val defaultArraySize = 16 /** * Returns the last valid index for the array. -1 if the array is empty. */ inline val <Type> GdxArray<Type>?.lastIndex: Int get() = size() - 1 /** * Returns the last valid index for the array. -1 if the array is empty. */ inline val GdxIntArray?.lastIndex: Int get() = size() - 1 /** * Returns the last valid index for the array. -1 if the array is empty. */ inline val GdxFloatArray?.lastIndex: Int get() = size() - 1 /** * Returns the last valid index for the array. -1 if the array is empty. */ inline val GdxBooleanArray?.lastIndex: Int get() = size() - 1 /** * @param ordered if false, methods that remove elements may change the order of other elements in the array, * which avoids a memory copy. * @param initialCapacity initial size of the backing array. * @return a new instance of [Array]. */ inline fun <reified Type : Any> gdxArrayOf(ordered: Boolean = true, initialCapacity: Int = defaultArraySize): GdxArray<Type> = GdxArray(ordered, initialCapacity, Type::class.java) /** * @param elements will be initially stored in the array. * @return a new instance of [Array]. */ inline fun <Type : Any> gdxArrayOf(vararg elements: Type): GdxArray<Type> = GdxArray(elements) /** * A method wrapper over [Array.size] variable compatible with nullable types. * @return current amount of elements in the array. */ inline fun <Type> GdxArray<Type>?.size(): Int = this?.size ?: 0 /** * A method wrapper over [IntArray.size] variable compatible with nullable types. * @return current amount of elements in the array. */ inline fun GdxIntArray?.size(): Int = this?.size ?: 0 /** * A method wrapper over [FloatArray.size] variable compatible with nullable types. * @return current amount of elements in the array. */ inline fun GdxFloatArray?.size(): Int = this?.size ?: 0 /** * A method wrapper over [BooleanArray.size] variable compatible with nullable types. * @return current amount of elements in the array. */ inline fun GdxBooleanArray?.size(): Int = this?.size ?: 0 /** * @return true if the array is null or has no elements. */ @OptIn(ExperimentalContracts::class) inline fun <Type> GdxArray<Type>?.isEmpty(): Boolean { contract { returns(false) implies (this@isEmpty != null) } return this == null || this.size == 0 } /** * @return true if the array is not null and contains at least one element. */ @OptIn(ExperimentalContracts::class) inline fun <Type> GdxArray<Type>?.isNotEmpty(): Boolean { contract { returns(true) implies (this@isNotEmpty != null) } return this != null && this.size > 0 } /** * @param index index of the element in the array. * @param alternative returned if index is out of bounds or the element is null. * @return a non-null value of stored element or the alternative. */ operator fun <Type> GdxArray<Type>.get(index: Int, alternative: Type): Type { if (index >= this.size) return alternative return this[index] ?: alternative } /** * @param elements will be iterated over and added to the array. */ fun <Type> GdxArray<Type>.addAll(elements: Iterable<Type>) = elements.forEach { this.add(it) } /** * @param elements will be iterated over and removed from the array. * @param identity if true, values will be compared by references. If false, equals method will be invoked. */ fun <Type> GdxArray<Type>.removeAll(elements: Iterable<Type>, identity: Boolean = false) = elements.forEach { this.removeValue(it, identity) } /** * @param elements will be iterated over and removed from the array. * @param identity if true, values will be compared by references. If false, equals method will be invoked. */ fun <Type> GdxArray<Type>.removeAll(elements: Array<out Type>, identity: Boolean = false) = elements.forEach { this.removeValue(it, identity) } /** * Creates a new [GdxArray] with appended [element]. * @param element will be added at the end of the new array. * @return a new [GdxArray] with elements from this array and [element]. */ operator fun <Type> GdxArray<Type>.plus(element: Type): GdxArray<Type> { val result = GdxArray<Type>(size + 1) result.addAll(this) result.add(element) return result } /** * Creates a new [GdxArray] with appended [elements]. * @param elements will be added at the end of the new array. * @return a new [GdxArray] with elements from this array and [elements]. */ operator fun <Type> GdxArray<Type>.plus(elements: Iterable<Type>): GdxArray<Type> { val result = GdxArray<Type>(this) result.addAll(elements) return result } /** * Creates a new [GdxArray] with appended [elements]. * @param elements will be added at the end of the new array. * @return a new [GdxArray] with elements from this array and [elements]. */ operator fun <Type> GdxArray<Type>.plus(elements: Collection<Type>): GdxArray<Type> { val result = GdxArray<Type>(size + elements.size) result.addAll(this) result.addAll(elements) return result } /** * Allows to quickly addAll all elements of a native array to this array with a pleasant, chainable operator syntax. * @param elements will be added to the array. * @return this array. */ operator fun <Type> GdxArray<Type>.plus(elements: Array<out Type>): GdxArray<Type> { val result = GdxArray<Type>(size + elements.size) result.addAll(this) result.addAll(elements, 0, elements.size) return result } /** * Allows to append elements to arrays with `array += element` syntax. * @param element will be added to the array. */ operator fun <Type> GdxArray<Type>.plusAssign(element: Type) { add(element) } /** * Allows to quickly add all elements of another iterable to this array with += operator syntax. * @param elements will be added to the array. */ operator fun <Type> GdxArray<Type>.plusAssign(elements: Iterable<Type>) { addAll(elements) } /** * Allows to quickly add all elements of a native array to this array with += operator syntax. * @param elements will be added to the array. */ operator fun <Type> GdxArray<Type>.plusAssign(elements: Array<out Type>) { addAll(elements, 0, elements.size) } /** * Allows to remove elements from arrays with `array - element` syntax. * @param element will not be copied to the new array. * @return a new [GdxArray] with removed element. */ operator fun <Type> GdxArray<Type>.minus(element: Type): GdxArray<Type> { val result = GdxArray(this) result.removeValue(element, false) return result } /** * Allows to quickly remove all elements of another iterable from this array with - operator syntax. * @param elements will not be copied to the new array. * @return a new [GdxArray] with removed elements. */ operator fun <Type> GdxArray<Type>.minus(elements: Iterable<Type>): GdxArray<Type> { val result = GdxArray(this) result.removeAll(elements) return result } /** * Allows to quickly remove all elements of a native array from this array with -= operator syntax. * @param elements will not be copied to the new array. * @return a new [GdxArray] with removed elements. */ operator fun <Type> GdxArray<Type>.minus(elements: Array<out Type>): GdxArray<Type> { val result = GdxArray(this) result.removeAll(elements) return result } /** * Allows to remove elements from arrays with `array -= element` syntax. * @param element will be removed from the array. * @return this array. */ operator fun <Type> GdxArray<Type>.minusAssign(element: Type) { removeValue(element, false) } /** * Allows to quickly remove all elements of another iterable from this array with -= operator syntax. * @param elements will be removed from the array. */ operator fun <Type> GdxArray<Type>.minusAssign(elements: Iterable<Type>) { removeAll(elements) } /** * Allows to quickly remove all elements of a native array from this array with -= operator syntax. * @param elements will be removed from the array. */ operator fun <Type> GdxArray<Type>.minusAssign(elements: Array<out Type>) { removeAll(elements) } /** * Allows to check if an array contains an element using the "in" operator. * @param element might be in the array. * @return true if the element is equal to any value stored in the array. */ operator fun <Type> GdxArray<Type>.contains(element: Type): Boolean = this.contains(element, false) /** * Allows to iterate over the array with access to [MutableIterator], which allows to remove elements from the collection * during iteration. * @param action will be invoked for each array element. Allows to remove elements during iteration. The first function * argument is the element from the array, the second is the array iterator. The iterator is guaranteed to be the * same instance during one iteration. */ inline fun <Type> GdxArray<Type>.iterate(action: (Type, MutableIterator<Type>) -> Unit) { val iterator = iterator() while (iterator.hasNext()) action.invoke(iterator.next(), iterator) } /** * Sorts elements in the array in-place descending according to their natural sort order. */ fun <Type : Comparable<Type>> GdxArray<out Type>.sortDescending() { this.sort(reverseOrder()) } /** * Sorts elements in the array in-place according to natural sort order of the value returned by specified [selector] function. */ inline fun <Type, R : Comparable<R>> GdxArray<out Type>.sortBy(crossinline selector: (Type) -> R?) { if (size > 1) this.sort(compareBy(selector)) } /** * Sorts elements in the array in-place descending according to natural sort order of the value returned by specified [selector] function. */ inline fun <Type, R : Comparable<R>> GdxArray<out Type>.sortByDescending(crossinline selector: (Type) -> R?) { if (size > 1) this.sort(compareByDescending(selector)) } /** * Removes elements from the array that satisfy the [predicate]. * @param pool Removed items are freed to this pool. * @return true if the array was modified, false otherwise. */ inline fun <Type> GdxArray<Type>.removeAll(pool: Pool<Type>? = null, predicate: (Type) -> Boolean): Boolean { var currentWriteIndex = 0 for (i in 0 until size) { val value = items[i] if (!predicate(value)) { if (currentWriteIndex != i) { items[currentWriteIndex] = value } currentWriteIndex++ } else { pool?.free(value) } } if (currentWriteIndex < size) { truncate(currentWriteIndex) return true } return false } /** * Removes elements from the array that do not satisfy the [predicate]. * @param pool Removed items are freed to this optional pool. * @return true if the array was modified, false otherwise. */ inline fun <Type> GdxArray<Type>.retainAll(pool: Pool<Type>? = null, predicate: (Type) -> Boolean): Boolean { var currentWriteIndex = 0 for (i in 0 until size) { val value = items[i] if (predicate(value)) { if (currentWriteIndex != i) { items[currentWriteIndex] = value } currentWriteIndex++ } else { pool?.free(value) } } if (currentWriteIndex < size) { truncate(currentWriteIndex) return true } return false } /** * Transfers elements that match the [predicate] into the selected [toArray]. * The elements will be removed from this array and added [toArray]. */ inline fun <Type : T, T> GdxArray<Type>.transfer(toArray: GdxArray<T>, predicate: (Type) -> Boolean) { var currentWriteIndex = 0 for (i in 0 until size) { val value = items[i] if (predicate(value)) { toArray.add(value) } else { if (currentWriteIndex != i) { items[currentWriteIndex] = value } currentWriteIndex++ } } truncate(currentWriteIndex) } /** * Returns a [GdxArray] containing the results of applying the given [transform] function * to each element in the original [GdxArray]. */ inline fun <Type, R> GdxArray<Type>.map(transform: (Type) -> R): GdxArray<R> { val destination = GdxArray<R>(this.size) for (item in this) { destination.add(transform(item)) } return destination } /** * Returns a [GdxArray] containing only elements matching the given [predicate]. */ inline fun <Type> GdxArray<Type>.filter(predicate: (Type) -> Boolean): GdxArray<Type> { val destination = GdxArray<Type>() for (item in this) { if (predicate(item)) { destination.add(item) } } return destination } /** * Returns a single [GdxArray] of all elements from all collections in the given [GdxArray]. */ inline fun <Type, C : Iterable<Type>> GdxArray<out C>.flatten(): GdxArray<Type> { val destination = GdxArray<Type>() for (item in this) { destination.addAll(item) } return destination } /** * Returns a single [GdxArray] of all elements yielded from results of transform function being invoked * on each entry of original [GdxArray]. */ inline fun <Type, R> GdxArray<Type>.flatMap(transform: (Type) -> Iterable<R>): GdxArray<R> { return this.map(transform).flatten() } /** * @param initialCapacity initial capacity of the set. Will be resized if necessary. Defaults to array size. * @param loadFactor decides how many elements the set might contain in relation to its total capacity before it is resized. * @return values copied from this array stored in a libGDX set. */ fun <Type : Any> GdxArray<Type>.toGdxSet( initialCapacity: Int = this.size, loadFactor: Float = defaultLoadFactor ): GdxSet<Type> { val set = GdxSet<Type>(initialCapacity, loadFactor) set.addAll(this) return set } /** * @param ordered if false, methods that remove elements may change the order of other elements in the array, * which avoids a memory copy. * @param initialCapacity initial size of the backing array. * @return values copied from this iterable stored in a libGDX array. */ inline fun <reified Type : Any> Iterable<Type>.toGdxArray( ordered: Boolean = true, initialCapacity: Int = defaultArraySize ): GdxArray<Type> { val array = GdxArray<Type>(ordered, initialCapacity, Type::class.java) array.addAll(this) return array } /** * @param ordered if false, methods that remove elements may change the order of other elements in the array, * which avoids a memory copy. * @param initialCapacity initial size of the backing array. Defaults to this array size. * @return values copied from this array stored in a libGDX array. */ inline fun <reified Type : Any> Array<Type>.toGdxArray( ordered: Boolean = true, initialCapacity: Int = this.size ): GdxArray<Type> { val array = GdxArray<Type>(ordered, initialCapacity, Type::class.java) array.addAll(this, 0, this.size) return array } /** * @param ordered if false, methods that remove elements may change the order of other elements in the array, * which avoids a memory copy. * @param initialCapacity initial size of the backing array. Defaults to this array size. * @return values copied from this array stored in an optimized libGDX int array. */ fun IntArray.toGdxArray(ordered: Boolean = true, initialCapacity: Int = this.size): GdxIntArray { val array = GdxIntArray(ordered, initialCapacity) array.addAll(this, 0, this.size) return array } /** * @param ordered if false, methods that remove elements may change the order of other elements in the array, * which avoids a memory copy. * @param initialCapacity initial size of the backing array. Defaults to this array size. * @return values copied from this array stored in an optimized libGDX float array. */ fun FloatArray.toGdxArray(ordered: Boolean = true, initialCapacity: Int = this.size): GdxFloatArray { val array = GdxFloatArray(ordered, initialCapacity) array.addAll(this, 0, this.size) return array } /** * @param ordered if false, methods that remove elements may change the order of other elements in the array, * which avoids a memory copy. * @param initialCapacity initial size of the backing array. Defaults to this array size. * @return values copied from this array stored in an optimized libGDX boolean array. */ fun BooleanArray.toGdxArray(ordered: Boolean = true, initialCapacity: Int = this.size): GdxBooleanArray { val array = GdxBooleanArray(ordered, initialCapacity) array.addAll(this, 0, this.size) return array } /** * @param elements will be initially stored in the array. * @return a new instance of [GdxBooleanArray]. */ fun gdxBooleanArrayOf(vararg elements: Boolean): GdxBooleanArray = GdxBooleanArray(elements) /** * @param elements will be initially stored in the array. * @return a new instance of [GdxByteArray]. */ fun gdxByteArrayOf(vararg elements: Byte): GdxByteArray = GdxByteArray(elements) /** * @param elements will be initially stored in the array. * @return a new instance of [GdxCharArray]. */ fun gdxCharArrayOf(vararg elements: Char): GdxCharArray = GdxCharArray(elements) /** * @param elements will be initially stored in the array. * @return a new instance of [GdxShortArray]. */ fun gdxShortArrayOf(vararg elements: Short): GdxShortArray = GdxShortArray(elements) /** * @param elements will be initially stored in the array. * @return a new instance of [GdxIntArray]. */ fun gdxIntArrayOf(vararg elements: Int): GdxIntArray = GdxIntArray(elements) /** * @param elements will be initially stored in the array. * @return a new instance of [GdxLongArray]. */ fun gdxLongArrayOf(vararg elements: Long): GdxLongArray = GdxLongArray(elements) /** * @param elements will be initially stored in the array. * @return a new instance of [GdxFloatArray]. */ fun gdxFloatArrayOf(vararg elements: Float): GdxFloatArray = GdxFloatArray(elements)
cc0-1.0
cb41edc9b899a29d1a1f418970c4331c
33.316547
138
0.719025
3.848326
false
false
false
false
westnordost/StreetComplete
app/src/main/java/de/westnordost/streetcomplete/MainActivity.kt
1
14832
package de.westnordost.streetcomplete import android.content.* import android.content.res.Configuration import android.graphics.Point import android.net.ConnectivityManager import android.os.Build import android.os.Bundle import android.text.method.LinkMovementMethod import android.text.util.Linkify import android.view.KeyEvent import android.view.View import android.view.WindowManager import android.widget.TextView import android.widget.Toast import androidx.annotation.AnyThread import androidx.appcompat.app.AlertDialog import androidx.appcompat.app.AppCompatActivity import androidx.core.content.edit import androidx.core.content.getSystemService import androidx.localbroadcastmanager.content.LocalBroadcastManager import androidx.preference.PreferenceManager import de.westnordost.osmapi.common.errors.OsmApiException import de.westnordost.osmapi.common.errors.OsmApiReadResponseException import de.westnordost.osmapi.common.errors.OsmAuthorizationException import de.westnordost.osmapi.common.errors.OsmConnectionException import de.westnordost.osmapi.map.data.OsmLatLon import de.westnordost.streetcomplete.Injector.applicationComponent import de.westnordost.streetcomplete.controls.NotificationButtonFragment import de.westnordost.streetcomplete.data.download.DownloadController import de.westnordost.streetcomplete.data.download.DownloadProgressListener import de.westnordost.streetcomplete.data.notifications.Notification import de.westnordost.streetcomplete.data.quest.Quest import de.westnordost.streetcomplete.data.quest.QuestAutoSyncer import de.westnordost.streetcomplete.data.quest.UnsyncedChangesCountSource import de.westnordost.streetcomplete.data.upload.UploadController import de.westnordost.streetcomplete.data.upload.UploadProgressListener import de.westnordost.streetcomplete.data.upload.VersionBannedException import de.westnordost.streetcomplete.data.user.UserController import de.westnordost.streetcomplete.ktx.toast import de.westnordost.streetcomplete.location.LocationRequestFragment import de.westnordost.streetcomplete.location.LocationState import de.westnordost.streetcomplete.location.LocationUtil import de.westnordost.streetcomplete.map.MainFragment import de.westnordost.streetcomplete.notifications.NotificationsContainerFragment import de.westnordost.streetcomplete.tutorial.TutorialFragment import de.westnordost.streetcomplete.util.CrashReportExceptionHandler import de.westnordost.streetcomplete.util.parseGeoUri import de.westnordost.streetcomplete.view.dialogs.RequestLoginDialog import javax.inject.Inject class MainActivity : AppCompatActivity(), MainFragment.Listener, TutorialFragment.Listener, NotificationButtonFragment.Listener { @Inject lateinit var crashReportExceptionHandler: CrashReportExceptionHandler @Inject lateinit var locationRequestFragment: LocationRequestFragment @Inject lateinit var questAutoSyncer: QuestAutoSyncer @Inject lateinit var downloadController: DownloadController @Inject lateinit var uploadController: UploadController @Inject lateinit var unsyncedChangesCountSource: UnsyncedChangesCountSource @Inject lateinit var prefs: SharedPreferences @Inject lateinit var userController: UserController private var mainFragment: MainFragment? = null private val locationAvailabilityReceiver: BroadcastReceiver = object : BroadcastReceiver() { override fun onReceive(context: Context, intent: Intent) { updateLocationAvailability() } } private val locationRequestFinishedReceiver: BroadcastReceiver = object : BroadcastReceiver() { override fun onReceive(context: Context, intent: Intent) { val state = LocationState.valueOf(intent.getStringExtra(LocationRequestFragment.STATE)!!) onLocationRequestFinished(state) } } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) applicationComponent.inject(this) lifecycle.addObserver(questAutoSyncer) crashReportExceptionHandler.askUserToSendCrashReportIfExists(this) PreferenceManager.setDefaultValues(this, R.xml.preferences, false) if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION) window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS) } if (prefs.getBoolean(Prefs.KEEP_SCREEN_ON, false)) { window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON) } supportFragmentManager.beginTransaction() .add(locationRequestFragment, LocationRequestFragment::class.java.simpleName) .commit() setContentView(R.layout.activity_main) mainFragment = supportFragmentManager.findFragmentById(R.id.map_fragment) as MainFragment? if (savedInstanceState == null) { val hasShownTutorial = prefs.getBoolean(Prefs.HAS_SHOWN_TUTORIAL, false) if (!hasShownTutorial && !userController.isLoggedIn) { supportFragmentManager.beginTransaction() .setCustomAnimations(R.anim.fade_in_from_bottom, R.anim.fade_out_to_bottom) .add(R.id.fragment_container, TutorialFragment()) .commit() } if (userController.isLoggedIn && isConnected) { userController.updateUser() } } handleGeoUri() } private fun handleGeoUri() { if (Intent.ACTION_VIEW != intent.action) return val data = intent.data ?: return if ("geo" != data.scheme) return val geo = parseGeoUri(data) ?: return val zoom = if (geo.zoom == null || geo.zoom < 14) 18f else geo.zoom val pos = OsmLatLon(geo.latitude, geo.longitude) mainFragment?.setCameraPosition(pos, zoom) } public override fun onStart() { super.onStart() registerReceiver(locationAvailabilityReceiver, LocationUtil.createLocationAvailabilityIntentFilter()) LocalBroadcastManager.getInstance(this).registerReceiver( locationRequestFinishedReceiver, IntentFilter(LocationRequestFragment.ACTION_FINISHED)) downloadController.showNotification = false uploadController.addUploadProgressListener(uploadProgressListener) downloadController.addDownloadProgressListener(downloadProgressListener) if (!hasAskedForLocation && !prefs.getBoolean(Prefs.LAST_LOCATION_REQUEST_DENIED, false)) { locationRequestFragment.startRequest() } else { updateLocationAvailability() } } override fun onBackPressed() { if (!forwardBackPressedToChildren()) super.onBackPressed() } private fun forwardBackPressedToChildren(): Boolean { val notificationsContainerFragment = notificationsContainerFragment if (notificationsContainerFragment != null) { if (notificationsContainerFragment.onBackPressed()) return true } val mainFragment = mainFragment if (mainFragment != null) { if (mainFragment.onBackPressed()) return true } return false } override fun dispatchKeyEvent(event: KeyEvent): Boolean { val mainFragment = mainFragment if (event.keyCode == KeyEvent.KEYCODE_MENU && mainFragment != null) { if (event.action == KeyEvent.ACTION_UP) { mainFragment.onClickMainMenu() } return true } return super.dispatchKeyEvent(event) } public override fun onPause() { super.onPause() val pos = mainFragment?.getCameraPosition()?.position ?: return prefs.edit { putLong(Prefs.MAP_LATITUDE, java.lang.Double.doubleToRawLongBits(pos.latitude)) putLong(Prefs.MAP_LONGITUDE, java.lang.Double.doubleToRawLongBits(pos.longitude)) } } public override fun onStop() { super.onStop() LocalBroadcastManager.getInstance(this).unregisterReceiver(locationRequestFinishedReceiver) unregisterReceiver(locationAvailabilityReceiver) downloadController.showNotification = true uploadController.removeUploadProgressListener(uploadProgressListener) downloadController.removeDownloadProgressListener(downloadProgressListener) } override fun onConfigurationChanged(newConfig: Configuration) { super.onConfigurationChanged(newConfig) findViewById<View>(R.id.main).requestLayout() // recreate the NotificationsContainerFragment because it should load a new layout, see #2330 supportFragmentManager .beginTransaction() .replace(R.id.notifications_container_fragment, NotificationsContainerFragment()) .commit() } private fun ensureLoggedIn() { if (questAutoSyncer.isAllowedByPreference) { if (!userController.isLoggedIn) { // new users should not be immediately pestered to login after each change (#1446) if (unsyncedChangesCountSource.count >= 3 && !dontShowRequestAuthorizationAgain) { RequestLoginDialog(this).show() dontShowRequestAuthorizationAgain = true } } } } private val isConnected: Boolean get() = getSystemService<ConnectivityManager>()?.activeNetworkInfo?.isConnected == true /* ------------------------------ Upload progress listener ---------------------------------- */ private val uploadProgressListener: UploadProgressListener = object : UploadProgressListener { @AnyThread override fun onError(e: Exception) { runOnUiThread { if (e is VersionBannedException) { var message = getString(R.string.version_banned_message) if (e.banReason != null) { message += "\n\n\n${e.banReason}" } val dialog = AlertDialog.Builder(this@MainActivity) .setMessage(message) .setPositiveButton(android.R.string.ok, null) .create() dialog.show() // Makes links in the alert dialog clickable val messageView = dialog.findViewById<View>(android.R.id.message) if (messageView is TextView) { messageView.movementMethod = LinkMovementMethod.getInstance() Linkify.addLinks(messageView, Linkify.WEB_URLS) } } else if (e is OsmConnectionException) { // a 5xx error is not the fault of this app. Nothing we can do about it, so // just notify the user toast(R.string.upload_server_error, Toast.LENGTH_LONG) } else if (e is OsmAuthorizationException) { // delete secret in case it failed while already having a token -> token is invalid userController.logOut() RequestLoginDialog(this@MainActivity).show() } else { crashReportExceptionHandler.askUserToSendErrorReport(this@MainActivity, R.string.upload_error, e) } } } } /* ----------------------------- Download Progress listener -------------------------------- */ private val downloadProgressListener: DownloadProgressListener = object : DownloadProgressListener { @AnyThread override fun onError(e: Exception) { runOnUiThread { // a 5xx error is not the fault of this app. Nothing we can do about it, so it does // not make sense to send an error report. Just notify the user. Further, we treat // the following errors the same as a (temporary) connection error: // - an invalid response (OsmApiReadResponseException) // - request timeout (OsmApiException with error code 408) val isEnvironmentError = e is OsmConnectionException || e is OsmApiReadResponseException || e is OsmApiException && e.errorCode == 408 if (isEnvironmentError) { toast(R.string.download_server_error, Toast.LENGTH_LONG) } else { crashReportExceptionHandler.askUserToSendErrorReport(this@MainActivity, R.string.download_error, e) } } } } /* --------------------------------- NotificationButtonFragment.Listener ---------------------------------- */ override fun onClickShowNotification(notification: Notification) { notificationsContainerFragment?.showNotification(notification) } private val notificationsContainerFragment get() = supportFragmentManager.findFragmentById(R.id.notifications_container_fragment) as? NotificationsContainerFragment /* --------------------------------- MainFragment.Listener ---------------------------------- */ override fun onQuestSolved(quest: Quest, source: String?) { ensureLoggedIn() } override fun onCreatedNote(screenPosition: Point) { ensureLoggedIn() } /* ------------------------------- TutorialFragment.Listener -------------------------------- */ override fun onFinishedTutorial() { prefs.edit().putBoolean(Prefs.HAS_SHOWN_TUTORIAL, true).apply() val tutorialFragment = supportFragmentManager.findFragmentById(R.id.fragment_container) if (tutorialFragment != null) { supportFragmentManager.beginTransaction() .setCustomAnimations(R.anim.fade_in_from_bottom, R.anim.fade_out_to_bottom) .remove(tutorialFragment) .commit() } } /* ------------------------------------ Location listener ----------------------------------- */ private fun updateLocationAvailability() { if (LocationUtil.isLocationOn(this)) { questAutoSyncer.startPositionTracking() } else { questAutoSyncer.stopPositionTracking() } } private fun onLocationRequestFinished(withLocationState: LocationState) { hasAskedForLocation = true val enabled = withLocationState.isEnabled prefs.edit().putBoolean(Prefs.LAST_LOCATION_REQUEST_DENIED, !enabled).apply() if (enabled) { updateLocationAvailability() } else { toast(R.string.no_gps_no_quests, Toast.LENGTH_LONG) } } companion object { // per application start settings private var hasAskedForLocation = false private var dontShowRequestAuthorizationAgain = false } }
gpl-3.0
91ef8a56e1d054d47063a6ddea9e19b7
43.945455
121
0.672465
5.385621
false
false
false
false
westnordost/StreetComplete
app/src/test/java/de/westnordost/streetcomplete/quests/housenumber/AddHousenumberTest.kt
1
8259
package de.westnordost.streetcomplete.quests.housenumber import de.westnordost.osmapi.map.data.* import de.westnordost.streetcomplete.data.osm.changes.StringMapEntryAdd import de.westnordost.streetcomplete.data.osm.elementgeometry.ElementGeometry import de.westnordost.streetcomplete.data.osm.elementgeometry.ElementPointGeometry import de.westnordost.streetcomplete.data.osm.elementgeometry.ElementPolygonsGeometry import de.westnordost.streetcomplete.quests.TestMapDataWithGeometry import de.westnordost.streetcomplete.quests.verifyAnswer import org.junit.Assert.* import org.junit.Test class AddHousenumberTest { private val questType = AddHousenumber() @Test fun `does not create quest for generic building`() { val mapData = createMapData(mapOf( OsmWay(1L, 1, NODES1, mapOf("building" to "yes")) to POSITIONS1 )) assertEquals(0, questType.getApplicableElements(mapData).toList().size) } @Test fun `does not create quest for building with address`() { val mapData = createMapData(mapOf( OsmWay(1L, 1, NODES1, mapOf( "building" to "detached", "addr:housenumber" to "123" )) to POSITIONS1 )) assertEquals(0, questType.getApplicableElements(mapData).toList().size) } @Test fun `does create quest for building without address`() { val mapData = createMapData(mapOf( OsmWay(1L, 1, NODES1, mapOf( "building" to "detached" )) to POSITIONS1 )) assertEquals(1, questType.getApplicableElements(mapData).toList().size) } @Test fun `does not create quest for building with address node on outline`() { val mapData = createMapData(mapOf( OsmWay(1L, 1, NODES1, mapOf( "building" to "detached" )) to POSITIONS1, OsmNode(2L, 1, P2, mapOf( "addr:housenumber" to "123" )) to ElementPointGeometry(P2) )) assertEquals(0, questType.getApplicableElements(mapData).toList().size) } @Test fun `does not create quest for building that is part of a relation with an address`() { val mapData = createMapData(mapOf( OsmWay(1L, 1, NODES1, mapOf( "building" to "detached" )) to POSITIONS1, OsmRelation(2L, 1, listOf( OsmRelationMember(1L, "something", Element.Type.WAY) ), mapOf( "addr:housenumber" to "123" )) to ElementPointGeometry(P2) )) assertEquals(0, questType.getApplicableElements(mapData).toList().size) } @Test fun `does not create quest for building that is inside an area with an address`() { val mapData = createMapData(mapOf( OsmWay(1L, 1, NODES1, mapOf( "building" to "detached" )) to POSITIONS1, OsmWay(1L, 1, NODES2, mapOf( "addr:housenumber" to "123", "amenity" to "school", )) to POSITIONS2, )) assertEquals(0, questType.getApplicableElements(mapData).toList().size) } @Test fun `does not create quest for building that is inside an area with an address on its outline`() { val mapData = createMapData(mapOf( OsmWay(1L, 1, NODES1, mapOf( "building" to "detached" )) to POSITIONS1, OsmWay(1L, 1, NODES2, mapOf( "amenity" to "school" )) to POSITIONS2, OsmNode(6L, 1, P6, mapOf( "addr:housenumber" to "123" )) to ElementPointGeometry(P6) )) assertEquals(0, questType.getApplicableElements(mapData).toList().size) } @Test fun `does not create quest for building that contains an address node`() { val mapData = createMapData(mapOf( OsmWay(1L, 1, NODES1, mapOf( "building" to "detached" )) to POSITIONS1, OsmNode(1L, 1, PC, mapOf( "addr:housenumber" to "123" )) to ElementPointGeometry(PC), )) assertEquals(0, questType.getApplicableElements(mapData).toList().size) } @Test fun `does not create quest for building that intersects bounding box`() { val mapData = createMapData(mapOf( OsmWay(1L, 1, NODES1, mapOf( "building" to "detached" )) to ElementPolygonsGeometry(listOf(listOf(P1, P2, PO, P4, P1)), PC) )) assertEquals(0, questType.getApplicableElements(mapData).toList().size) } @Test fun `housenumber regex`() { val r = VALID_HOUSENUMBER_REGEX assertTrue("1".matches(r)) assertTrue("1234".matches(r)) assertTrue("1234a".matches(r)) assertTrue("1234/a".matches(r)) assertTrue("1234 / a".matches(r)) assertTrue("1234 / A".matches(r)) assertTrue("1234A".matches(r)) assertTrue("1234/9".matches(r)) assertTrue("1234 / 9".matches(r)) assertTrue("12345".matches(r)) assertFalse("123456".matches(r)) assertFalse("1234 5".matches(r)) assertFalse("1234/55".matches(r)) assertFalse("1234AB".matches(r)) } @Test fun `blocknumber regex`() { val r = VALID_BLOCKNUMBER_REGEX assertTrue("1".matches(r)) assertTrue("1234".matches(r)) assertFalse("12345".matches(r)) assertTrue("1234a".matches(r)) assertTrue("1234 a".matches(r)) assertFalse("1234 ab".matches(r)) } @Test fun `apply house number answer`() { questType.verifyAnswer( HouseNumber("99b"), StringMapEntryAdd("addr:housenumber", "99b") ) } @Test fun `apply house name answer`() { questType.verifyAnswer( HouseName("La Escalera"), StringMapEntryAdd("addr:housename", "La Escalera") ) } @Test fun `apply conscription number answer`() { questType.verifyAnswer( ConscriptionNumber("I.123"), StringMapEntryAdd("addr:conscriptionnumber", "I.123"), StringMapEntryAdd("addr:housenumber", "I.123") ) } @Test fun `apply conscription and street number answer`() { questType.verifyAnswer( ConscriptionNumber("I.123", "12b"), StringMapEntryAdd("addr:conscriptionnumber", "I.123"), StringMapEntryAdd("addr:streetnumber", "12b"), StringMapEntryAdd("addr:housenumber", "12b") ) } @Test fun `apply block and house number answer`() { questType.verifyAnswer( HouseAndBlockNumber("12A", "123"), StringMapEntryAdd("addr:block_number", "123"), StringMapEntryAdd("addr:housenumber", "12A") ) } @Test fun `apply no house number answer`() { questType.verifyAnswer( NoHouseNumber, StringMapEntryAdd("nohousenumber", "yes") ) } } private val P1 = OsmLatLon(0.25,0.25) private val P2 = OsmLatLon(0.25,0.75) private val P3 = OsmLatLon(0.75,0.75) private val P4 = OsmLatLon(0.75,0.25) private val P5 = OsmLatLon(0.1,0.1) private val P6 = OsmLatLon(0.1,0.9) private val P7 = OsmLatLon(0.9,0.9) private val P8 = OsmLatLon(0.9,0.1) private val PO = OsmLatLon(1.5, 1.5) private val PC = OsmLatLon(0.5,0.5) private val NODES1 = listOf<Long>(1,2,3,4,1) private val NODES2 = listOf<Long>(5,6,7,8,5) private val POSITIONS1 = ElementPolygonsGeometry(listOf(listOf(P1, P2, P3, P4, P1)), PC) private val POSITIONS2 = ElementPolygonsGeometry(listOf(listOf(P5, P6, P7, P8, P5)), PC) private fun createMapData(elements: Map<Element, ElementGeometry?>): TestMapDataWithGeometry { val result = TestMapDataWithGeometry(elements.keys) for((element, geometry) in elements) { when(element) { is Node -> result.nodeGeometriesById[element.id] = geometry as ElementPointGeometry is Way -> result.wayGeometriesById[element.id] = geometry is Relation -> result.relationGeometriesById[element.id] = geometry } } result.handle(BoundingBox(0.0, 0.0, 1.0, 1.0)) return result }
gpl-3.0
806cf9be8f5a7c377269f647cf734582
35.065502
108
0.60758
4.042584
false
true
false
false
WangDaYeeeeee/GeometricWeather
app/src/main/java/wangdaye/com/geometricweather/settings/preference/PreferenceItems.kt
1
3217
package wangdaye.com.geometricweather.settings.preference import androidx.annotation.StringRes import androidx.compose.foundation.layout.* import androidx.compose.foundation.lazy.LazyListScope import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.stringResource import androidx.compose.ui.unit.dp import wangdaye.com.geometricweather.common.ui.widgets.getCardListItemMarginDp import wangdaye.com.geometricweather.settings.preference.composables.SectionFooter import wangdaye.com.geometricweather.settings.preference.composables.SectionHeader fun LazyListScope.sectionHeaderItem( @StringRes sectionTitleId: Int ) { val token = PreferenceToken.SectionHeader(sectionTitleId = sectionTitleId) item( key = token.preferenceKey, contentType = token::class.java, ) { SectionHeader(title = stringResource(sectionTitleId)) } } fun LazyListScope.sectionFooterItem( @StringRes sectionTitleId: Int ) { val token = PreferenceToken.SectionFooter(sectionTitleId = sectionTitleId) item( key = token.preferenceKey, contentType = token::class.java, ) { SectionFooter() } } fun LazyListScope.bottomInsetItem() { val token = PreferenceToken.BottomInset() item( key = token.preferenceKey, contentType = token::class.java, ) { Column { Spacer(modifier = Modifier.height(getCardListItemMarginDp(LocalContext.current).dp)) Spacer(modifier = Modifier.windowInsetsBottomHeight(WindowInsets.navigationBars)) } } } fun LazyListScope.clickablePreferenceItem( @StringRes titleId: Int, content: @Composable (Int) -> Unit, ) { val token = PreferenceToken.ClickablePreference(titleId = titleId) item( key = token.preferenceKey, contentType = token::class.java, ) { content(titleId) } } fun LazyListScope.checkboxPreferenceItem( @StringRes titleId: Int, content: @Composable (Int) -> Unit, ) { val token = PreferenceToken.CheckboxPreference(titleId = titleId) item( key = token.preferenceKey, contentType = token::class.java, ) { content(titleId) } } fun LazyListScope.listPreferenceItem( @StringRes titleId: Int, content: @Composable (Int) -> Unit, ) { val token = PreferenceToken.ListPreference(titleId = titleId) item( key = token.preferenceKey, contentType = token::class.java, ) { content(titleId) } } fun LazyListScope.timePickerPreferenceItem( @StringRes titleId: Int, content: @Composable (Int) -> Unit, ) { val token = PreferenceToken.TimePickerPreference(titleId = titleId) item( key = token.preferenceKey, contentType = token::class.java, ) { content(titleId) } } fun LazyListScope.editTextPreferenceItem( @StringRes titleId: Int, content: @Composable (Int) -> Unit, ) { val token = PreferenceToken.EditTextPreference(titleId = titleId) item( key = token.preferenceKey, contentType = token::class.java, ) { content(titleId) } }
lgpl-3.0
af9afa2555953364d2918e2057039e9f
26.982609
96
0.696301
4.382834
false
false
false
false
StepicOrg/stepic-android
app/src/main/java/org/stepik/android/view/step_quiz_text/ui/fragment/TextStepQuizFragment.kt
1
1256
package org.stepik.android.view.step_quiz_text.ui.fragment import android.view.View import androidx.fragment.app.Fragment import kotlinx.android.synthetic.main.layout_step_quiz_text.* import org.stepic.droid.R import org.stepik.android.presentation.step_quiz.StepQuizFeature import org.stepik.android.view.step_quiz.ui.delegate.StepQuizFormDelegate import org.stepik.android.view.step_quiz.ui.fragment.DefaultStepQuizFragment import org.stepik.android.view.step_quiz_text.ui.delegate.TextStepQuizFormDelegate import ru.nobird.android.presentation.redux.container.ReduxView class TextStepQuizFragment : DefaultStepQuizFragment(), ReduxView<StepQuizFeature.State, StepQuizFeature.Action.ViewAction> { companion object { fun newInstance(stepId: Long): Fragment = TextStepQuizFragment() .apply { this.stepId = stepId } } override val quizLayoutRes: Int = R.layout.layout_step_quiz_text override val quizViews: Array<View> get() = arrayOf(stringStepQuizField) override fun createStepQuizFormDelegate(view: View): StepQuizFormDelegate = TextStepQuizFormDelegate(view, stepWrapper.step.block?.name, onQuizChanged = ::syncReplyState) }
apache-2.0
b35200fe96a45d7940c68fa68c384715
38.28125
102
0.749204
4.376307
false
false
false
false
WangDaYeeeeee/GeometricWeather
app/src/main/java/wangdaye/com/geometricweather/settings/ConfigStore.kt
1
2877
package wangdaye.com.geometricweather.settings import android.content.Context import android.content.SharedPreferences import androidx.preference.PreferenceManager class ConfigStore private constructor(sp: SharedPreferences) { companion object { @JvmStatic fun getInstance(context: Context) = getInstance(context, null) @JvmStatic fun getInstance(context: Context, name: String? = null): ConfigStore { return ConfigStore( if (name == null) { PreferenceManager.getDefaultSharedPreferences(context) } else { context.getSharedPreferences(name, Context.MODE_PRIVATE) } ) } } private val preferences = sp fun preload() { // do nothing. } fun getString(key: String, defValue: String?): String? { return preferences.getString(key, defValue) } fun getStringSet(key: String, defValues: Set<String>?): Set<String>? { return preferences.getStringSet(key, defValues) } fun getInt(key: String, defValue: Int): Int { return preferences.getInt(key, defValue) } fun getLong(key: String, defValue: Long): Long { return preferences.getLong(key, defValue) } fun getFloat(key: String, defValue: Float): Float { return preferences.getFloat(key, defValue) } fun getBoolean(key: String, defValue: Boolean): Boolean { return preferences.getBoolean(key, defValue) } fun contains(key: String): Boolean { return preferences.contains(key) } fun edit(): Editor { return Editor(this) } class Editor internal constructor(host: ConfigStore) { private val editor = host.preferences.edit() fun putString(key: String, value: String?): Editor { editor.putString(key, value) return this } fun putStringSet(key: String, values: Set<String?>?): Editor { editor.putStringSet(key, values) return this } fun putInt(key: String, value: Int): Editor { editor.putInt(key, value) return this } fun putLong(key: String, value: Long): Editor { editor.putLong(key, value) return this } fun putFloat(key: String, value: Float): Editor { editor.putFloat(key, value) return this } fun putBoolean(key: String, value: Boolean): Editor { editor.putBoolean(key, value) return this } fun remove(key: String): Editor { editor.remove(key) return this } fun clear(): Editor { editor.clear() return this } fun apply() { editor.apply() } } }
lgpl-3.0
09916049239e5d823b1f0a78b1577bd1
24.696429
78
0.57699
4.843434
false
false
false
false
Cognifide/APM
app/aem/core/src/main/kotlin/com/cognifide/apm/core/services/version/VersionService.kt
1
1286
/*- * ========================LICENSE_START================================= * AEM Permission Management * %% * Copyright (C) 2013 Wunderman Thompson Technology * %% * 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. * =========================LICENSE_END================================== */ package com.cognifide.apm.core.services.version import com.cognifide.apm.api.scripts.Script import org.apache.sling.api.resource.ResourceResolver interface VersionService { fun getScriptVersion(resolver: ResourceResolver, script: Script): ScriptVersion fun getVersionPath(script: Script): String fun updateVersionIfNeeded(resolver: ResourceResolver, vararg script: Script) fun countChecksum(root: Iterable<Script>): String }
apache-2.0
215e5a1365093736a91bb6a8965a439f
34.8
83
0.667963
4.745387
false
false
false
false
CarlosEsco/tachiyomi
app/src/main/java/eu/kanade/tachiyomi/ui/reader/setting/OrientationType.kt
1
1677
package eu.kanade.tachiyomi.ui.reader.setting import android.content.pm.ActivityInfo import androidx.annotation.DrawableRes import androidx.annotation.StringRes import eu.kanade.tachiyomi.R enum class OrientationType(val prefValue: Int, val flag: Int, @StringRes val stringRes: Int, @DrawableRes val iconRes: Int, val flagValue: Int) { DEFAULT(0, ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED, R.string.label_default, R.drawable.ic_screen_rotation_24dp, 0x00000000), FREE(1, ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED, R.string.rotation_free, R.drawable.ic_screen_rotation_24dp, 0x00000008), PORTRAIT(2, ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT, R.string.rotation_portrait, R.drawable.ic_stay_current_portrait_24dp, 0x00000010), REVERSE_PORTRAIT(6, ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT, R.string.rotation_reverse_portrait, R.drawable.ic_stay_current_portrait_24dp, 0x00000030), LANDSCAPE(3, ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE, R.string.rotation_landscape, R.drawable.ic_stay_current_landscape_24dp, 0x00000018), LOCKED_PORTRAIT(4, ActivityInfo.SCREEN_ORIENTATION_PORTRAIT, R.string.rotation_force_portrait, R.drawable.ic_screen_lock_portrait_24dp, 0x00000020), LOCKED_LANDSCAPE(5, ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE, R.string.rotation_force_landscape, R.drawable.ic_screen_lock_landscape_24dp, 0x00000028), ; companion object { const val MASK = 0x00000038 fun fromPreference(preference: Int?): OrientationType = values().find { it.flagValue == preference } ?: FREE fun fromSpinner(position: Int?) = values().find { value -> value.prefValue == position } ?: DEFAULT } }
apache-2.0
b2dcb4dfeaf1380d4f2024e7bbf5f835
66.08
164
0.774001
3.685714
false
false
false
false
exponentjs/exponent
packages/expo-modules-core/android/src/main/java/expo/modules/adapters/react/permissions/PermissionsService.kt
2
14375
package expo.modules.adapters.react.permissions import android.Manifest import android.annotation.TargetApi import android.content.Context import android.content.Intent import android.content.SharedPreferences import android.content.pm.PackageManager import android.net.Uri import android.os.Build import android.os.Bundle import android.provider.Settings import androidx.core.app.ActivityCompat import androidx.core.content.ContextCompat import com.facebook.react.modules.core.PermissionAwareActivity import com.facebook.react.modules.core.PermissionListener import expo.modules.interfaces.permissions.Permissions import expo.modules.interfaces.permissions.PermissionsResponse import expo.modules.interfaces.permissions.PermissionsResponseListener import expo.modules.interfaces.permissions.PermissionsStatus import expo.modules.core.ModuleRegistry import expo.modules.core.Promise import expo.modules.core.interfaces.ActivityProvider import expo.modules.core.interfaces.InternalModule import expo.modules.core.interfaces.LifecycleEventListener import expo.modules.core.interfaces.services.UIManager import java.util.* import kotlin.collections.HashMap private const val PERMISSIONS_REQUEST: Int = 13 private const val PREFERENCE_FILENAME = "expo.modules.permissions.asked" open class PermissionsService(val context: Context) : InternalModule, Permissions, LifecycleEventListener { private var mActivityProvider: ActivityProvider? = null // state holders for asking for writing permissions private var mWriteSettingsPermissionBeingAsked = false // change this directly before calling corresponding startActivity private var mAskAsyncListener: PermissionsResponseListener? = null private var mAskAsyncRequestedPermissions: Array<out String>? = null private val mPendingPermissionCalls: Queue<Pair<Array<out String>, PermissionsResponseListener>> = LinkedList() private var mCurrentPermissionListener: PermissionsResponseListener? = null private lateinit var mAskedPermissionsCache: SharedPreferences private fun didAsk(permission: String): Boolean = mAskedPermissionsCache.getBoolean(permission, false) private fun addToAskedPermissionsCache(permissions: Array<out String>) { with(mAskedPermissionsCache.edit()) { permissions.forEach { putBoolean(it, true) } apply() } } override fun getExportedInterfaces(): List<Class<out Any>> = listOf(Permissions::class.java) @Throws(IllegalStateException::class) override fun onCreate(moduleRegistry: ModuleRegistry) { mActivityProvider = moduleRegistry.getModule(ActivityProvider::class.java) ?: throw IllegalStateException("Couldn't find implementation for ActivityProvider.") moduleRegistry.getModule(UIManager::class.java).registerLifecycleEventListener(this) mAskedPermissionsCache = context.applicationContext.getSharedPreferences(PREFERENCE_FILENAME, Context.MODE_PRIVATE) } override fun getPermissionsWithPromise(promise: Promise, vararg permissions: String) { getPermissions( PermissionsResponseListener { permissionsMap: MutableMap<String, PermissionsResponse> -> val areAllGranted = permissionsMap.all { (_, response) -> response.status == PermissionsStatus.GRANTED } val areAllDenied = permissionsMap.all { (_, response) -> response.status == PermissionsStatus.DENIED } val canAskAgain = permissionsMap.all { (_, response) -> response.canAskAgain } promise.resolve( Bundle().apply { putString(PermissionsResponse.EXPIRES_KEY, PermissionsResponse.PERMISSION_EXPIRES_NEVER) putString( PermissionsResponse.STATUS_KEY, when { areAllGranted -> PermissionsStatus.GRANTED.status areAllDenied -> PermissionsStatus.DENIED.status else -> PermissionsStatus.UNDETERMINED.status } ) putBoolean(PermissionsResponse.CAN_ASK_AGAIN_KEY, canAskAgain) putBoolean(PermissionsResponse.GRANTED_KEY, areAllGranted) } ) }, *permissions ) } override fun askForPermissionsWithPromise(promise: Promise, vararg permissions: String) { askForPermissions( PermissionsResponseListener { getPermissionsWithPromise(promise, *permissions) }, *permissions ) } override fun getPermissions(responseListener: PermissionsResponseListener, vararg permissions: String) { responseListener.onResult( parseNativeResult( permissions, permissions.map { if (isPermissionGranted(it)) { PackageManager.PERMISSION_GRANTED } else { PackageManager.PERMISSION_DENIED } }.toIntArray() ) ) } @Throws(IllegalStateException::class) override fun askForPermissions(responseListener: PermissionsResponseListener, vararg permissions: String) { if (permissions.contains(Manifest.permission.WRITE_SETTINGS) && isRuntimePermissionsAvailable()) { val permissionsToAsk = permissions.toMutableList().apply { remove(Manifest.permission.WRITE_SETTINGS) }.toTypedArray() val newListener = PermissionsResponseListener { val status = if (hasWriteSettingsPermission()) { PackageManager.PERMISSION_GRANTED } else { PackageManager.PERMISSION_DENIED } it[Manifest.permission.WRITE_SETTINGS] = getPermissionResponseFromNativeResponse(Manifest.permission.WRITE_SETTINGS, status) responseListener.onResult(it) } if (!hasWriteSettingsPermission()) { if (mAskAsyncListener != null) { throw IllegalStateException("Another permissions request is in progress. Await the old request and then try again.") } mAskAsyncListener = newListener mAskAsyncRequestedPermissions = permissionsToAsk addToAskedPermissionsCache(arrayOf(Manifest.permission.WRITE_SETTINGS)) askForWriteSettingsPermissionFirst() } else { askForManifestPermissions(permissionsToAsk, newListener) } } else { askForManifestPermissions(permissions, responseListener) } } override fun hasGrantedPermissions(vararg permissions: String): Boolean { return permissions.all { isPermissionGranted(it) } } /** * Checks whether given permission is present in AndroidManifest or not. */ override fun isPermissionPresentInManifest(permission: String): Boolean { try { context.packageManager.getPackageInfo(context.packageName, PackageManager.GET_PERMISSIONS)?.run { return requestedPermissions.contains(permission) } return false } catch (e: PackageManager.NameNotFoundException) { return false } } /** * Checks status for Android built-in permission * * @param permission [android.Manifest.permission] */ private fun isPermissionGranted(permission: String): Boolean { return when (permission) { // we need to handle this permission in different way Manifest.permission.WRITE_SETTINGS -> hasWriteSettingsPermission() else -> getManifestPermission(permission) == PackageManager.PERMISSION_GRANTED } } /** * Gets status for Android built-in permission * * @param permission [android.Manifest.permission] */ private fun getManifestPermission(permission: String): Int { mActivityProvider?.currentActivity?.let { if (it is PermissionAwareActivity) { return ContextCompat.checkSelfPermission(it, permission) } } // We are in the headless mode. So, we ask current context. return getManifestPermissionFromContext(permission) } protected open fun getManifestPermissionFromContext(permission: String): Int { return ContextCompat.checkSelfPermission(context, permission) } private fun canAskAgain(permission: String): Boolean { return mActivityProvider?.currentActivity?.let { ActivityCompat.shouldShowRequestPermissionRationale(it, permission) } ?: false } private fun parseNativeResult(permissionsString: Array<out String>, grantResults: IntArray): Map<String, PermissionsResponse> { return HashMap<String, PermissionsResponse>().apply { grantResults.zip(permissionsString).forEach { (result, permission) -> this[permission] = getPermissionResponseFromNativeResponse(permission, result) } } } private fun getPermissionResponseFromNativeResponse(permission: String, result: Int): PermissionsResponse { val status = when { result == PackageManager.PERMISSION_GRANTED -> PermissionsStatus.GRANTED didAsk(permission) -> PermissionsStatus.DENIED else -> PermissionsStatus.UNDETERMINED } return PermissionsResponse( status, if (status == PermissionsStatus.DENIED) { canAskAgain(permission) } else { true } ) } protected open fun askForManifestPermissions(permissions: Array<out String>, listener: PermissionsResponseListener) { if (!isRuntimePermissionsAvailable()) { // It's not possible to ask for the permissions in the runtime. // We return to the user the permissions status, which was granted during installation. addToAskedPermissionsCache(permissions) val permissionsResult = permissions.map { getManifestPermission(it) }.toIntArray() listener.onResult(parseNativeResult(permissions, permissionsResult)) return } delegateRequestToActivity(permissions, listener) } /** * Asks for Android built-in permission * According to Android documentation [android.Manifest.permission.WRITE_SETTINGS] need to be handled in different way * * @param permissions [android.Manifest.permission] */ protected fun delegateRequestToActivity(permissions: Array<out String>, listener: PermissionsResponseListener) { addToAskedPermissionsCache(permissions) val currentActivity = mActivityProvider?.currentActivity if (currentActivity is PermissionAwareActivity) { synchronized(this@PermissionsService) { if (mCurrentPermissionListener != null) { mPendingPermissionCalls.add(permissions to listener) } else { mCurrentPermissionListener = listener currentActivity.requestPermissions(permissions, PERMISSIONS_REQUEST, createListenerWithPendingPermissionsRequest()) } } } else { listener.onResult(parseNativeResult(permissions, IntArray(permissions.size) { PackageManager.PERMISSION_DENIED })) } } private fun createListenerWithPendingPermissionsRequest(): PermissionListener { return PermissionListener { requestCode, receivePermissions, grantResults -> if (requestCode == PERMISSIONS_REQUEST) { synchronized(this@PermissionsService) { val currentListener = requireNotNull(mCurrentPermissionListener) currentListener.onResult(parseNativeResult(receivePermissions, grantResults)) mCurrentPermissionListener = null mPendingPermissionCalls.poll()?.let { pendingCall -> val activity = mActivityProvider?.currentActivity as? PermissionAwareActivity if (activity == null) { // clear all pending calls, because we don't have access to the activity instance pendingCall.second.onResult(parseNativeResult(pendingCall.first, IntArray(pendingCall.first.size) { PackageManager.PERMISSION_DENIED })) mPendingPermissionCalls.forEach { it.second.onResult(parseNativeResult(it.first, IntArray(it.first.size) { PackageManager.PERMISSION_DENIED })) } mPendingPermissionCalls.clear() return@let } mCurrentPermissionListener = pendingCall.second activity.requestPermissions(pendingCall.first, PERMISSIONS_REQUEST, createListenerWithPendingPermissionsRequest()) return@PermissionListener false } return@PermissionListener true } } return@PermissionListener false } } /** * Asking for [android.provider.Settings.ACTION_MANAGE_WRITE_SETTINGS] via separate activity * WARNING: has to be asked first among all permissions being asked in request * Scenario that forces this order: * 1. user asks for "systemBrightness" (actual [android.provider.Settings.ACTION_MANAGE_WRITE_SETTINGS]) and for some other permission (e.g. [android.Manifest.permission.CAMERA]) * 2. first goes ACTION_MANAGE_WRITE_SETTINGS that moves app into background and launches system-specific fullscreen activity * 3. upon user action system resumes app and [onHostResume] is being called for the first time and logic for other permission is invoked * 4. other permission invokes other system-specific activity that is visible as dialog what moves app again into background * 5. upon user action app is restored and [onHostResume] is being called again, but no further action is invoked and promise is resolved */ @TargetApi(Build.VERSION_CODES.M) private fun askForWriteSettingsPermissionFirst() { Intent(Settings.ACTION_MANAGE_WRITE_SETTINGS).apply { data = Uri.parse("package:${context.packageName}") addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) }.let { mWriteSettingsPermissionBeingAsked = true context.startActivity(it) } } private fun hasWriteSettingsPermission(): Boolean { return if (isRuntimePermissionsAvailable()) { Settings.System.canWrite(context.applicationContext) } else { true } } private fun isRuntimePermissionsAvailable() = Build.VERSION.SDK_INT >= Build.VERSION_CODES.M override fun onHostResume() { if (!mWriteSettingsPermissionBeingAsked) { return } mWriteSettingsPermissionBeingAsked = false // cleanup val askAsyncListener = mAskAsyncListener!! val askAsyncRequestedPermissions = mAskAsyncRequestedPermissions!! mAskAsyncListener = null mAskAsyncRequestedPermissions = null if (askAsyncRequestedPermissions.isNotEmpty()) { // invoke actual asking for permissions askForManifestPermissions(askAsyncRequestedPermissions, askAsyncListener) } else { // user asked only for Manifest.permission.WRITE_SETTINGS askAsyncListener.onResult(mutableMapOf()) } } override fun onHostPause() = Unit override fun onHostDestroy() = Unit }
bsd-3-clause
c96ae3ba6c2f0934d1d6429952f03dc4
39.607345
180
0.7344
5.208333
false
false
false
false
lhw5123/GmailKotlinSample
GmailKotlion/app/src/main/java/org/hevin/gmailkotlion/activtiy/MainActivity.kt
1
7037
package org.hevin.gmailkotlion.activtiy import android.content.res.TypedArray import android.graphics.Color import android.os.Bundle import android.support.design.widget.FloatingActionButton import android.support.design.widget.Snackbar import android.support.v4.widget.SwipeRefreshLayout import android.support.v7.app.AppCompatActivity import android.support.v7.view.ActionMode import android.support.v7.widget.* import android.view.Menu import android.view.MenuItem import android.widget.Toast import org.hevin.gmailkotlion.R import org.hevin.gmailkotlion.adapter.MessageAdapter import org.hevin.gmailkotlion.helper.DividerItemDecoration import org.hevin.gmailkotlion.model.Message import org.hevin.gmailkotlion.network.ApiClient import org.hevin.gmailkotlion.network.ApiInterface import retrofit2.Call import retrofit2.Callback import retrofit2.Response class MainActivity : AppCompatActivity(), SwipeRefreshLayout.OnRefreshListener, MessageAdapter.MessageAdapterListener { private val swipeRefreshLayout: SwipeRefreshLayout? = null private val messages: ArrayList<Message> = ArrayList() private val mAdapter: MessageAdapter = MessageAdapter(this, messages, this) private var actionMode: ActionMode? = null private val actionModeCallback: ActionModeCallback = ActionModeCallback() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) setSupportActionBar(findViewById(R.id.toolbar) as Toolbar) val fab = findViewById(R.id.fab) as FloatingActionButton fab.setOnClickListener { view -> Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG) .setAction("Action", null).show() } val swipeRefreshLayout = findViewById(R.id.swipe_refresh_layout) as SwipeRefreshLayout swipeRefreshLayout.setOnRefreshListener(this) swipeRefreshLayout.post { Runnable { getInbox() } } val recyclerView = findViewById(R.id.recyclerview_main_messages) as RecyclerView recyclerView.layoutManager = LinearLayoutManager(applicationContext) recyclerView.itemAnimator = DefaultItemAnimator() recyclerView.addItemDecoration(DividerItemDecoration(this, LinearLayoutManager.VERTICAL)) recyclerView.adapter = mAdapter } private fun getInbox() { swipeRefreshLayout?.isRefreshing = true val apiService = ApiClient.instance.create(ApiInterface::class.java) val call: Call<List<Message>> = apiService.getInbox() call.enqueue(object : Callback<List<Message>> { override fun onResponse(call: Call<List<Message>>?, response: Response<List<Message>>?) { messages.clear() for (msg in response!!.body()) { msg.color = getRandomMaterialColor("400") messages.add(msg) } mAdapter.notifyDataSetChanged() swipeRefreshLayout?.isRefreshing = false } override fun onFailure(call: Call<List<Message>>?, t: Throwable?) { Toast.makeText(applicationContext, "Unable to fetch json", Toast.LENGTH_LONG).show() swipeRefreshLayout?.isRefreshing = false } }) } private fun getRandomMaterialColor(typeColor: String): Int { var returnColor = Color.GRAY val arrayId = resources.getIdentifier("mdcolor_" + typeColor, "array", packageName) if (arrayId == 0) { val colors: TypedArray = resources.obtainTypedArray(arrayId) val index: Int = (Math.random() * colors.length()).toInt() returnColor = colors.getColor(index, Color.GRAY) colors.recycle() } return returnColor } override fun onCreateOptionsMenu(menu: Menu?): Boolean { menuInflater.inflate(R.menu.menu_main, menu) return true } override fun onOptionsItemSelected(item: MenuItem): Boolean { val id = item.itemId if (id == R.id.action_search) { Toast.makeText(applicationContext, "Search...", Toast.LENGTH_SHORT).show() return true } return super.onOptionsItemSelected(item) } override fun onRefresh() { getInbox() } override fun onIconClicked(position: Int) { if (actionMode == null) { actionMode = startSupportActionMode(actionModeCallback) } } override fun onIconImportantClicked(position: Int) { val msg = messages[position] msg.isImport = !msg.isImport messages[position] = msg mAdapter.notifyItemChanged(position) } override fun onMessageRowClicked(position: Int) { if (mAdapter.selectedItems.size() > 0) { enableActionMode(position) } else { val msg = messages[position] msg.isRead = true messages[position] = msg mAdapter.notifyItemChanged(position) Toast.makeText(applicationContext, "Read: " + msg.message, Toast.LENGTH_SHORT).show() } } override fun onRowLongClicked(position: Int) { enableActionMode(position) } private fun enableActionMode(position: Int) { if (actionMode == null) { actionMode = startSupportActionMode(actionModeCallback) } toggleSelection(position) } private fun toggleSelection(position: Int) { mAdapter.toggleSelection(position) val count = mAdapter.selectedItems.size() if (count == 0) { actionMode?.finish() } else { actionMode?.title = count.toString() actionMode?.invalidate() } } inner class ActionModeCallback : ActionMode.Callback { override fun onActionItemClicked(mode: ActionMode, item: MenuItem): Boolean { when (item.itemId) { R.id.action_delete -> { deleteMessages() mode.finish() return true } else -> return false } } override fun onCreateActionMode(mode: ActionMode, menu: Menu): Boolean { mode.menuInflater.inflate(R.menu.menu_action_mode, menu) swipeRefreshLayout?.isEnabled = false return true } override fun onPrepareActionMode(mode: ActionMode?, menu: Menu?): Boolean { return false } override fun onDestroyActionMode(mode: ActionMode?) { mAdapter.clearSelections() } private fun deleteMessages() { mAdapter.resetAnimationIndex() val selectionItemPositions: List<Int> = mAdapter.getSelectedItems() for (i in selectionItemPositions.size - 1 downTo 0) { mAdapter.removeData(i) } mAdapter.notifyDataSetChanged() } } }
apache-2.0
e03f7e917911b0fa7007f93a3d07a938
34.185
101
0.642888
5.080866
false
false
false
false
sirixdb/sirix
bundles/sirix-rest-api/src/main/kotlin/org/sirix/rest/crud/DiffHandler.kt
1
6552
package org.sirix.rest.crud import com.google.gson.JsonArray import com.google.gson.JsonObject import io.vertx.core.http.HttpHeaders import io.vertx.ext.web.Route import io.vertx.ext.web.RoutingContext import io.vertx.kotlin.coroutines.await import org.sirix.access.DatabaseType import org.sirix.access.Databases.* import org.sirix.access.DatabasesInternals import org.sirix.access.ResourceConfiguration import org.sirix.api.Database import org.sirix.api.json.JsonNodeReadOnlyTrx import org.sirix.api.json.JsonResourceSession import org.sirix.service.json.BasicJsonDiff import org.sirix.utils.LogWrapper import org.slf4j.LoggerFactory import java.nio.charset.StandardCharsets import java.nio.file.Files import java.nio.file.Path /** * [LogWrapper] reference. */ private val logger = LogWrapper(LoggerFactory.getLogger(DiffHandler::class.java)) class DiffHandler(private val location: Path) { suspend fun handle(ctx: RoutingContext): Route { val context = ctx.vertx().orCreateContext val databaseName = ctx.pathParam("database") val resourceName = ctx.pathParam("resource") if (databaseName == null || resourceName == null) { throw IllegalArgumentException("Database name and resource name must be in the URL path.") } logger.debug("Open databases before: ${DatabasesInternals.getOpenDatabases()}") val database = openDatabase(databaseName) val diff = context.executeBlocking<String> { resultPromise -> var diffString: String? = null database.use { val resourceManager = database.beginResourceSession(resourceName) resourceManager.use { if (resourceManager is JsonResourceSession) { val firstRevision: String? = ctx.queryParam("first-revision").getOrNull(0) val secondRevision: String? = ctx.queryParam("second-revision").getOrNull(0) if (firstRevision == null || secondRevision == null) { throw IllegalArgumentException("First and second revision must be specified.") } val startNodeKey: String? = ctx.queryParam("startNodeKey").getOrNull(0) val maxDepth: String? = ctx.queryParam("maxDepth").getOrNull(0) val startNodeKeyAsLong = startNodeKey?.let { startNodeKey.toLong() } ?: 0 val maxDepthAsLong = maxDepth?.let { maxDepth.toLong() } ?: Long.MAX_VALUE if (resourceManager.resourceConfig.areDeweyIDsStored && secondRevision.toInt() - 1 == firstRevision.toInt()) { if (startNodeKeyAsLong == 0L && maxDepthAsLong == 0L) { val diffPath = resourceManager.getResourceConfig() .resource .resolve(ResourceConfiguration.ResourcePaths.UPDATE_OPERATIONS.path) .resolve("diffFromRev${firstRevision.toInt()}toRev${secondRevision.toInt()}.json") diffString = Files.readString(diffPath) } else { val rtx = resourceManager.beginNodeReadOnlyTrx(secondRevision.toInt()) rtx.use { diffString = useUpdateOperations( rtx, startNodeKeyAsLong, databaseName, resourceName, firstRevision, secondRevision, maxDepthAsLong ) } } } else { diffString = BasicJsonDiff(databaseName).generateDiff( resourceManager, firstRevision.toInt(), secondRevision.toInt(), startNodeKeyAsLong, maxDepthAsLong ) } } } } resultPromise.complete(diffString) }.await() logger.debug("Open databases after: ${DatabasesInternals.getOpenDatabases()}") val res = ctx.response().setStatusCode(200) .putHeader(HttpHeaders.CONTENT_TYPE, "application/json") .putHeader( HttpHeaders.CONTENT_LENGTH, diff!!.toByteArray(StandardCharsets.UTF_8).size.toString() ) res.write(diff) res.end() return ctx.currentRoute() } private fun useUpdateOperations( rtx: JsonNodeReadOnlyTrx, startNodeKeyAsLong: Long, databaseName: String, resourceName: String, firstRevision: String, secondRevision: String, maxDepthAsLong: Long ): String { rtx.moveTo(startNodeKeyAsLong) val metaInfo = createMetaInfo( databaseName, resourceName, firstRevision.toInt(), secondRevision.toInt() ) val diffs = metaInfo.getAsJsonArray("diffs") val updateOperations = rtx.getUpdateOperationsInSubtreeOfNode(rtx.deweyID, maxDepthAsLong) updateOperations.forEach { diffs.add(it) } return metaInfo.toString() } private fun openDatabase(databaseName: String): Database<*> { @Suppress("WHEN_ENUM_CAN_BE_NULL_IN_JAVA") return when (getDatabaseType(location.resolve(databaseName).toAbsolutePath())) { DatabaseType.JSON -> openJsonDatabase(location.resolve(databaseName)) DatabaseType.XML -> openXmlDatabase(location.resolve(databaseName)) } } private fun createMetaInfo( databaseName: String, resourceName: String, oldRevision: Int, newRevision: Int ): JsonObject { val json = JsonObject() json.addProperty("database", databaseName) json.addProperty("resource", resourceName) json.addProperty("old-revision", oldRevision) json.addProperty("new-revision", newRevision) val diffsArray = JsonArray() json.add("diffs", diffsArray) return json } }
bsd-3-clause
78e887e9481ede3a6e690b140af4ed02
39.95
134
0.565171
5.482845
false
false
false
false
bajdcc/jMiniLang
src/main/kotlin/com/bajdcc/LALR1/ui/UIMainFrame.kt
1
7184
package com.bajdcc.LALR1.ui import com.bajdcc.LALR1.grammar.Grammar import com.bajdcc.LALR1.grammar.runtime.RuntimeCodePage import com.bajdcc.LALR1.grammar.runtime.RuntimeException import com.bajdcc.LALR1.interpret.Interpreter import com.bajdcc.LALR1.interpret.module.ModuleRemote import com.bajdcc.LALR1.interpret.os.irq.IRPrint import com.bajdcc.LALR1.interpret.os.irq.IRRemote import com.bajdcc.LALR1.interpret.os.irq.IRSignal import com.bajdcc.LALR1.interpret.os.irq.IRTask import com.bajdcc.LALR1.interpret.os.kern.OSEntry import com.bajdcc.LALR1.interpret.os.kern.OSIrq import com.bajdcc.LALR1.interpret.os.kern.OSTask import com.bajdcc.LALR1.interpret.os.task.* import com.bajdcc.LALR1.interpret.os.ui.UIClock import com.bajdcc.LALR1.interpret.os.ui.UIHitokoto import com.bajdcc.LALR1.interpret.os.ui.UIMain import com.bajdcc.LALR1.interpret.os.ui.UIMonitor import com.bajdcc.LALR1.interpret.os.user.UserMain import com.bajdcc.LALR1.interpret.os.user.routine.* import com.bajdcc.LALR1.interpret.os.user.routine.file.URFileAppend import com.bajdcc.LALR1.interpret.os.user.routine.file.URFileLoad import com.bajdcc.LALR1.interpret.os.user.routine.file.URFileSave import com.bajdcc.LALR1.syntax.handler.SyntaxException import com.bajdcc.util.lexer.error.RegexException import com.sun.jna.platform.win32.User32 import org.apache.log4j.Logger import java.awt.Dimension import java.awt.Font import java.awt.event.WindowAdapter import java.awt.event.WindowEvent import java.io.ByteArrayInputStream import java.io.ByteArrayOutputStream import java.util.* import javax.swing.JFrame import javax.swing.UIManager import javax.swing.WindowConstants import javax.swing.plaf.FontUIResource /** * 【界面】窗口 * * @author bajdcc */ class UIMainFrame : JFrame() { private val panel: UIPanel private var isExitNormally = false private var interpreter: Interpreter? = null init { initGlobalFont() panel = UIPanel() this.title = mainWndTitle this.defaultCloseOperation = WindowConstants.DO_NOTHING_ON_CLOSE this.preferredSize = Dimension(panel.uiGraphics.w, panel.uiGraphics.h) this.contentPane = panel this.pack() this.setLocationRelativeTo(null) //this.setAlwaysOnTop(true); this.isResizable = false this.isVisible = true this.addWindowListener(object : WindowAdapter() { override fun windowClosing(e: WindowEvent?) { if (isExitNormally) { logger.info("Exit.") } else { logger.info("Exit by window closing.") [email protected]() } } }) } private fun stopOS() { interpreter!!.stop() } private fun exit() { isExitNormally = true [email protected] = WindowConstants.EXIT_ON_CLOSE dispatchEvent(WindowEvent(this, WindowEvent.WINDOW_CLOSING)) } private fun setTimer() { javax.swing.Timer(33) { panel.repaint() }.start() } private fun startOS() { val pages = arrayOf( // OS OSEntry(), OSIrq(), OSTask(), // IRQ IRPrint(), IRRemote(), IRTask(), IRSignal(), // TASK TKSystem(), TKUtil(), TKUI(), TKNet(), TKStore(), TKProc(), // UI UIMain(), UIClock(), UIHitokoto(), UIMonitor(), // USER UserMain(), // USER ROUTINE URShell(), UREcho(), URPipe(), URDup(), URGrep(), URRange(), URProc(), URTask(), URSleep(), URTime(), URCount(), URTest(), URMsg(), URNews(), URBash(), URReplace(), URUtil(), URAI(), URPC(), URMusic(), // USER FILE URFileLoad(), URFileSave(), URFileAppend()) try { val code = "import \"sys.base\";\n" + "import \"sys.proc\";\n" + "call g_load_sync_x(\"/kern/entry\");\n" interpreter = Interpreter() for (page in pages) { interpreter!!.load(page) } val grammar = Grammar(code) //System.out.println(grammar.toString()); val page = grammar.codePage //System.out.println(page.toString()); val baos = ByteArrayOutputStream() RuntimeCodePage.exportFromStream(page, baos) val bais = ByteArrayInputStream(baos.toByteArray()) interpreter!!.run("@main", bais) System.exit(0) } catch (e: RegexException) { System.err.println() System.err.println(e.position.toString() + "," + e.message) e.printStackTrace() } catch (e: SyntaxException) { System.err.println() System.err.println(String.format("模块名:%s. 位置:%s. 错误:%s-%s(%s:%d)", e.pageName, e.position, e.message, e.info, e.fileName, e.position.line + 1)) e.printStackTrace() } catch (e: RuntimeException) { System.err.println() System.err.println(e.error!!.message + " " + e.position + ": " + e.info) e.printStackTrace() } catch (e: Exception) { System.err.println() System.err.println(e.message) e.printStackTrace() } } fun showDelay() { Timer().schedule(object : TimerTask() { override fun run() { while (System.getProperty("os.name") != null) { if (System.getProperty("os.name").startsWith("Windows")) { val hwnd = User32.INSTANCE.FindWindow("SunAwtFrame", mainWndTitle) if (hwnd != null) { User32.INSTANCE.SetFocus(hwnd) User32.INSTANCE.SetForegroundWindow(hwnd) return } } try { Thread.sleep(1000) } catch (e: InterruptedException) { e.printStackTrace() } } isAlwaysOnTop = true } }, 1000) } companion object { private val logger = Logger.getLogger("window") private val mainWndTitle = "jMiniLang Command Window" private fun initGlobalFont() { val fontUIResource = FontUIResource(Font("楷体", Font.PLAIN, 18)) val keys = UIManager.getDefaults().keys() while (keys.hasMoreElements()) { val key = keys.nextElement() val value = UIManager.get(key) if (value is FontUIResource) { UIManager.put(key, fontUIResource) } } } @JvmStatic fun main(args: Array<String>) { val frame = UIMainFrame() ModuleRemote.enabled() ModuleRemote.setMainFrame(frame) frame.setTimer() frame.startOS() frame.exit() } } }
mit
f5cbbcd4ab49c6a4c55efd6d919d21c2
34.74
217
0.577364
4.163075
false
false
false
false
RonnChyran/Face-of-Sidonia
Sidonia/SidoniaWatchface/src/main/java/moe/chyyran/sidonia/drawables/TimeDrawable.kt
1
3958
package moe.chyyran.sidonia.drawables import android.graphics.Canvas import android.graphics.Paint import android.graphics.PointF import com.ustwo.clockwise.common.WatchFaceTime import com.ustwo.clockwise.common.util.Logr import com.ustwo.clockwise.wearable.WatchFace import moe.chyyran.sidonia.R class TimeDrawable(watch: WatchFace) : SidoniaDrawable(watch) { private var STATUS_WAIT_SEC: Int = 0 private var mTextPaint: Paint private var mArabicTextPaint: Paint private var mCenterBlockWidth: Float = 0.toFloat() private var mCenterBoldLines: FloatArray init { val resources = watch.resources STATUS_WAIT_SEC = resources.getInteger(R.integer.animation_delay) var textSize = desiredMinimumWidth / 5f mCenterBlockWidth = (desiredMinimumWidth - (edgeOffset * 2f + hudCellWidth * 2f)) / 2f // Digit Display mTextPaint = Paint() mTextPaint.typeface = this.kanjiFont mTextPaint.textSize = textSize mTextPaint.color = alertColor mTextPaint.isAntiAlias = true mArabicTextPaint = Paint(mTextPaint) mArabicTextPaint.typeface = this.latinFont mCenterBoldLines = floatArrayOf( // Vertical Lines hudCellWidth * 1f + edgeOffset, hudCellWidth * 1f + edgeOffset, hudCellWidth * 1f + edgeOffset, hudCellWidth * 4f + edgeOffset, hudCellWidth * 4f + edgeOffset, hudCellWidth * 1f + edgeOffset, hudCellWidth * 4f + edgeOffset, hudCellWidth * 4f + edgeOffset, // Horizontal Lines hudCellWidth * 1f + edgeOffset, hudCellWidth * 1f + edgeOffset, hudCellWidth * 4f + edgeOffset, hudCellWidth * 1f + edgeOffset, hudCellWidth * 1f + edgeOffset, hudCellWidth * 4f + edgeOffset, hudCellWidth * 4f + edgeOffset, hudCellWidth * 4f + edgeOffset) } fun drawTime(canvas: Canvas?, time: WatchFaceTime, formatNumeral: (Int) -> String, isArabic: Boolean = false, is24hour: Boolean = true) { canvas?.save() val timeHour = if (is24hour) time.hour else time.hour12 val topLeftDigit = formatNumeral(timeHour / 10) val mTLTextPoint = getDrawPoint(0, 0, topLeftDigit, mTextPaint) val topRightDigit = formatNumeral(timeHour % 10) val mTRTextPoint = getDrawPoint(1, 0, topRightDigit, mTextPaint) val bottomLeftDigit = formatNumeral(time.minute / 10) val mBLTextPoint = getDrawPoint(0, 1, bottomLeftDigit, mTextPaint) val bottomRightDigit = formatNumeral(time.minute % 10) val mBRTextPoint = getDrawPoint(1, 1, bottomRightDigit, mTextPaint) val timePaint = if (isArabic) mArabicTextPaint else mTextPaint alertBoldPaint.color = alertColor canvas?.drawLine(hudCellWidth * 1f + edgeOffset, desiredMinimumWidth / 2f, hudCellWidth * 4f + edgeOffset, desiredMinimumWidth / 2f, alertBoldPaint) canvas?.drawLine(desiredMinimumWidth / 2f, hudCellWidth * 1f + edgeOffset, desiredMinimumWidth / 2f, hudCellWidth * 4f + edgeOffset, alertBoldPaint) canvas?.drawLines(mCenterBoldLines, alertBoldPaint) canvas?.drawText(topLeftDigit, mTLTextPoint.x, mTLTextPoint.y, timePaint) canvas?.drawText(topRightDigit, mTRTextPoint.x, mTRTextPoint.y, timePaint) canvas?.drawText(bottomLeftDigit, mBLTextPoint.x, mBLTextPoint.y, timePaint) canvas?.drawText(bottomRightDigit, mBRTextPoint.x, mBRTextPoint.y, timePaint) canvas?.restore() } fun getDrawPoint(column: Int, row: Int, numeral: String, paint: Paint): PointF { val fontMetrics = paint.fontMetrics var halfTextWidth = mTextPaint.measureText(numeral) / 2f var halfTextHeight = (fontMetrics.ascent + fontMetrics.descent) / 2f var top = edgeOffset + hudCellWidth + mCenterBlockWidth / 2f return PointF(top - halfTextWidth + column * mCenterBlockWidth + if (numeral.equals("1")) 8f else 0f, top - halfTextHeight + row * mCenterBlockWidth) } }
mit
724d1d4daf496f2b161125e0344df347
47.268293
271
0.705659
3.938308
false
false
false
false
wordpress-mobile/WordPress-Android
WordPress/src/main/java/org/wordpress/android/ui/deeplinks/DeepLinkOpenWebLinksWithJetpackHelper.kt
1
4865
package org.wordpress.android.ui.deeplinks import android.content.pm.PackageManager import org.wordpress.android.ui.prefs.AppPrefsWrapper import org.wordpress.android.util.AppLog import org.wordpress.android.util.AppLog.T import org.wordpress.android.util.BuildConfigWrapper import org.wordpress.android.util.DateTimeUtilsWrapper import org.wordpress.android.util.FirebaseRemoteConfigWrapper import org.wordpress.android.util.PackageManagerWrapper import org.wordpress.android.util.config.OpenWebLinksWithJetpackFlowFeatureConfig import java.util.Date import javax.inject.Inject @Suppress("TooManyFunctions") class DeepLinkOpenWebLinksWithJetpackHelper @Inject constructor( private val openWebLinksWithJetpackFlowFeatureConfig: OpenWebLinksWithJetpackFlowFeatureConfig, private val appPrefsWrapper: AppPrefsWrapper, private val firebaseRemoteConfigWrapper: FirebaseRemoteConfigWrapper, private val packageManagerWrapper: PackageManagerWrapper, private val dateTimeUtilsWrapper: DateTimeUtilsWrapper, private val buildConfigWrapper: BuildConfigWrapper ) { fun shouldShowDeepLinkOpenWebLinksWithJetpackOverlay() = showOverlay() fun shouldShowAppSetting(): Boolean { return openWebLinksWithJetpackFlowFeatureConfig.isEnabled() && isJetpackInstalled() } fun enableDisableOpenWithJetpackComponents(newValue: Boolean) { when (newValue) { true -> { packageManagerWrapper.disableReaderDeepLinks() packageManagerWrapper.disableComponentEnabledSetting(WEB_LINKS_DEEPLINK_ACTIVITY_ALIAS) } false -> { packageManagerWrapper.enableReaderDeeplinks() packageManagerWrapper.enableComponentEnableSetting(WEB_LINKS_DEEPLINK_ACTIVITY_ALIAS) } } } fun handleJetpackUninstalled() { resetAll() } fun resetAll() { enableDisableOpenWithJetpackComponents(false) appPrefsWrapper.setIsOpenWebLinksWithJetpack(false) appPrefsWrapper.setOpenWebLinksWithJetpackOverlayLastShownTimestamp(0L) } @Suppress("SwallowedException") fun handleOpenWebLinksWithJetpack() : Boolean { try { enableDisableOpenWithJetpackComponents(true) packageManagerWrapper.disableReaderDeepLinks() appPrefsWrapper.setIsOpenWebLinksWithJetpack(true) return true } catch (ex: PackageManager.NameNotFoundException) { AppLog.e(T.UTILS, "Unable to set open web links with Jetpack ${ex.message}") } return false } private fun showOverlay() : Boolean { return openWebLinksWithJetpackFlowFeatureConfig.isEnabled() && isJetpackInstalled() && !isOpenWebLinksWithJetpack() && isValidOverlayFrequency() } private fun isJetpackInstalled() = packageManagerWrapper.isPackageInstalled(getPackageName()) private fun isValidOverlayFrequency() : Boolean { if (!hasOverlayBeenShown()) return true // short circuit if the overlay has never been shown return hasExceededOverlayFrequency() } private fun hasExceededOverlayFrequency() : Boolean { val frequency = firebaseRemoteConfigWrapper.getOpenWebLinksWithJetpackFlowFrequency() if (frequency == 0L) return false // Only show the overlay 1X and it's already been shown do not show again val lastShownDate = Date(getOpenWebLinksWithJetpackOverlayLastShownTimestamp()) val daysPastOverlayShown = dateTimeUtilsWrapper.daysBetween( lastShownDate, getTodaysDate()) return daysPastOverlayShown >= frequency } private fun hasOverlayBeenShown() = getOpenWebLinksWithJetpackOverlayLastShownTimestamp() > 0L private fun getOpenWebLinksWithJetpackOverlayLastShownTimestamp() = appPrefsWrapper.getOpenWebLinksWithJetpackOverlayLastShownTimestamp() private fun isOpenWebLinksWithJetpack() = appPrefsWrapper.getIsOpenWebLinksWithJetpack() private fun getTodaysDate() = Date(System.currentTimeMillis()) private fun getPackageName(): String { val appSuffix = buildConfigWrapper.getApplicationId().split(".").last() val appPackage = if (appSuffix.isNotBlank() && !appSuffix.equals("ANDROID", ignoreCase = true)) { "$JETPACK_PACKAGE_NAME.${appSuffix}" } else { JETPACK_PACKAGE_NAME } return appPackage } fun onOverlayShown() = appPrefsWrapper.setOpenWebLinksWithJetpackOverlayLastShownTimestamp(System.currentTimeMillis()) companion object { const val JETPACK_PACKAGE_NAME = "com.jetpack.android" const val WEB_LINKS_DEEPLINK_ACTIVITY_ALIAS = "org.wordpress.android.WebLinksDeepLinkingIntentReceiverActivity" } }
gpl-2.0
5aa2cfa72c7e6dc821bb4a485c15dd01
39.206612
115
0.724358
5.208779
false
true
false
false
Turbo87/intellij-rust
src/main/kotlin/org/rust/lang/core/resolve/ref/RustQualifiedReferenceImpl.kt
1
1832
package org.rust.lang.core.resolve.ref import com.intellij.openapi.util.TextRange import com.intellij.psi.PsiElement import com.intellij.psi.PsiReferenceBase import org.rust.lang.core.completion.RustCompletionEngine import org.rust.lang.core.lexer.RustTokenElementTypes import org.rust.lang.core.psi.RustNamedElement import org.rust.lang.core.psi.RustQualifiedReferenceElement import org.rust.lang.core.resolve.RustResolveEngine internal class RustQualifiedReferenceImpl<T : RustQualifiedReferenceElement>(element: T, soft: Boolean = false) : PsiReferenceBase<T>(element, null, soft) , RustReference { override fun resolve(): RustNamedElement? = RustResolveEngine.resolve(element).element override fun getVariants(): Array<out Any> = RustCompletionEngine.complete(element).toTypedArray() override fun isReferenceTo(element: PsiElement): Boolean { val target = resolve() return element.manager.areElementsEquivalent(target, element) } override fun getCanonicalText(): String = element.let { qualRef -> var qual = qualRef.qualifier?.reference?.canonicalText .orEmpty() if (qual.isNotEmpty()) qual += RustTokenElementTypes.COLONCOLON.s; qual + qualRef.name } override fun getRangeInElement(): TextRange? = element.separator.let { sep -> when (sep) { null -> TextRange.from(0, element.textLength) else -> TextRange(sep.startOffsetInParent + sep.textLength, element.textLength) } } override fun bindToElement(element: PsiElement): PsiElement? { throw UnsupportedOperationException() } }
mit
d6f9b4cc0bf89a5717208744c149f883
34.230769
99
0.654476
5.032967
false
false
false
false
ingokegel/intellij-community
plugins/github/src/org/jetbrains/plugins/github/api/data/GHRepositoryOwnerName.kt
10
923
// 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.github.api.data import com.fasterxml.jackson.annotation.JsonSubTypes import com.fasterxml.jackson.annotation.JsonTypeInfo import com.intellij.collaboration.api.dto.GraphQLFragment @GraphQLFragment("/graphql/fragment/repositoryOwnerName.graphql") @JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "__typename", visible = false) @JsonSubTypes( JsonSubTypes.Type(name = "User", value = GHRepositoryOwnerName.User::class), JsonSubTypes.Type(name = "Organization", value = GHRepositoryOwnerName.Organization::class) ) interface GHRepositoryOwnerName { val login: String class User(override val login: String) : GHRepositoryOwnerName class Organization(override val login: String) : GHRepositoryOwnerName }
apache-2.0
d6a22f43fe20e1a6fbf2ab82208316cc
47.631579
140
0.801733
4.293023
false
false
false
false
mdaniel/intellij-community
plugins/kotlin/code-insight/intentions-k2/src/org/jetbrains/kotlin/idea/k2/codeinsight/intentions/AddPropertyAccessorsIntention.kt
1
3195
// 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.k2.codeinsight.intentions import com.intellij.codeInsight.intention.LowPriorityAction import org.jetbrains.kotlin.analysis.api.annotations.containsAnnotation import org.jetbrains.kotlin.analysis.api.symbols.KtPropertySymbol import org.jetbrains.kotlin.idea.codeinsight.api.applicators.* import org.jetbrains.kotlin.idea.codeinsights.impl.base.applicators.AddAccessorApplicator import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.load.java.JvmAbi import org.jetbrains.kotlin.name.ClassId import org.jetbrains.kotlin.psi.KtProperty import org.jetbrains.kotlin.psi.psiUtil.containingClass import org.jetbrains.kotlin.psi.psiUtil.containingClassOrObject import org.jetbrains.kotlin.psi.psiUtil.hasExpectModifier internal abstract class AbstractAddAccessorIntention(private val addGetter: Boolean, private val addSetter: Boolean) : AbstractKotlinApplicatorBasedIntention<KtProperty, KotlinApplicatorInput.Empty>(KtProperty::class) { override fun getApplicator() = AddAccessorApplicator.applicator(addGetter, addSetter).with { isApplicableByPsi { ktProperty -> if (ktProperty.isLocal || ktProperty.hasDelegate() || ktProperty.containingClass()?.isInterface() == true || ktProperty.containingClassOrObject?.hasExpectModifier() == true || ktProperty.hasModifier(KtTokens.ABSTRACT_KEYWORD) || ktProperty.hasModifier(KtTokens.LATEINIT_KEYWORD) || ktProperty.hasModifier(KtTokens.CONST_KEYWORD) ) { return@isApplicableByPsi false } if (ktProperty.typeReference == null && !ktProperty.hasInitializer()) return@isApplicableByPsi false if (addSetter && (!ktProperty.isVar || ktProperty.setter != null)) return@isApplicableByPsi false if (addGetter && ktProperty.getter != null) return@isApplicableByPsi false true } } override fun getApplicabilityRange() = applicabilityTarget { ktProperty: KtProperty -> if (ktProperty.hasInitializer()) ktProperty.nameIdentifier else ktProperty } override fun getInputProvider(): KotlinApplicatorInputProvider<KtProperty, KotlinApplicatorInput.Empty> = inputProvider { ktProperty -> val symbol = ktProperty.getVariableSymbol() as? KtPropertySymbol ?: return@inputProvider null if (symbol.containsAnnotation(JVM_FIELD_CLASS_ID)) return@inputProvider null KotlinApplicatorInput.Empty } } private val JVM_FIELD_CLASS_ID = ClassId.topLevel(JvmAbi.JVM_FIELD_ANNOTATION_FQ_NAME) internal class AddPropertyAccessorsIntention : AbstractAddAccessorIntention(addGetter = true, addSetter = true), LowPriorityAction internal class AddPropertyGetterIntention : AbstractAddAccessorIntention(addGetter = true, addSetter = false) internal class AddPropertySetterIntention : AbstractAddAccessorIntention(addGetter = false, addSetter = true)
apache-2.0
00f7beed8c70f2b1719195f2fac6cb85
54.103448
158
0.744601
5.246305
false
false
false
false
mdaniel/intellij-community
platform/build-scripts/groovy/org/jetbrains/intellij/build/impl/JarPackager.kt
2
23778
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. @file:Suppress("ReplaceGetOrSet", "ReplacePutWithAssignment", "ReplaceJavaStaticMethodWithKotlinAnalog") package org.jetbrains.intellij.build.impl import com.intellij.openapi.util.io.FileUtil import com.intellij.util.PathUtilRt import com.intellij.util.io.URLUtil import io.opentelemetry.api.common.AttributeKey import io.opentelemetry.api.common.Attributes import io.opentelemetry.api.trace.Span import org.jetbrains.intellij.build.BuildContext import org.jetbrains.intellij.build.BuildOptions import org.jetbrains.intellij.build.impl.BaseLayout.Companion.APP_JAR import org.jetbrains.intellij.build.impl.projectStructureMapping.DistributionFileEntry import org.jetbrains.intellij.build.impl.projectStructureMapping.ModuleLibraryFileEntry import org.jetbrains.intellij.build.impl.projectStructureMapping.ModuleOutputEntry import org.jetbrains.intellij.build.impl.projectStructureMapping.ProjectLibraryEntry import org.jetbrains.intellij.build.tasks.* import org.jetbrains.jps.model.java.JpsJavaClasspathKind import org.jetbrains.jps.model.java.JpsJavaExtensionService import org.jetbrains.jps.model.library.JpsLibrary import org.jetbrains.jps.model.library.JpsOrderRootType import org.jetbrains.jps.model.module.JpsLibraryDependency import org.jetbrains.jps.model.module.JpsModule import org.jetbrains.jps.model.module.JpsModuleReference import java.io.File import java.nio.file.FileSystems import java.nio.file.Files import java.nio.file.Path import java.util.* import java.util.concurrent.ConcurrentHashMap import java.util.concurrent.ConcurrentLinkedQueue import java.util.function.IntConsumer private val JAR_NAME_WITH_VERSION_PATTERN = "(.*)-\\d+(?:\\.\\d+)*\\.jar*".toPattern() @Suppress("ReplaceJavaStaticMethodWithKotlinAnalog") private val libsThatUsedInJps = java.util.Set.of( "ASM", "aalto-xml", "netty-buffer", "netty-codec-http", "netty-handler-proxy", "fastutil-min", "gson", "Log4J", "Slf4j", "slf4j-jdk14", // see getBuildProcessApplicationClasspath - used in JPS "lz4-java", "maven-resolver-provider", "OroMatcher", "jgoodies-forms", "jgoodies-common", "NanoXML", // see ArtifactRepositoryManager.getClassesFromDependencies "plexus-utils", "Guava", "http-client", "commons-codec", "commons-logging", "commons-lang3", "kotlin-stdlib-jdk8" ) class JarPackager private constructor(private val context: BuildContext) { private val jarDescriptors = LinkedHashMap<Path, JarDescriptor>() private val projectStructureMapping = ConcurrentLinkedQueue<DistributionFileEntry>() private val libToMetadata = HashMap<JpsLibrary, ProjectLibraryData>() companion object { private val extraMergeRules = LinkedHashMap<String, (String) -> Boolean>() init { extraMergeRules.put("groovy.jar") { it.startsWith("org.codehaus.groovy:") } extraMergeRules.put("jsch-agent.jar") { it.startsWith("jsch-agent") } extraMergeRules.put("rd.jar") { it.startsWith("rd-") } // see ClassPathUtil.getUtilClassPath extraMergeRules.put("3rd-party-rt.jar") { libsThatUsedInJps.contains(it) || it.startsWith("kotlinx-") || it == "kotlin-reflect" } } fun getLibraryName(lib: JpsLibrary): String { val name = lib.name if (!name.startsWith("#")) { return name } val roots = lib.getRoots(JpsOrderRootType.COMPILED) if (roots.size != 1) { throw IllegalStateException("Non-single entry module library $name: ${roots.joinToString { it.url }}") } return PathUtilRt.getFileName(roots.first().url.removeSuffix(URLUtil.JAR_SEPARATOR)) } fun pack(actualModuleJars: Map<String, List<String>>, outputDir: Path, layout: BaseLayout = BaseLayout(), moduleOutputPatcher: ModuleOutputPatcher = ModuleOutputPatcher(), dryRun: Boolean = false, context: BuildContext): Collection<DistributionFileEntry> { val copiedFiles = HashMap<Path, CopiedFor>() val packager = JarPackager(context) for (data in layout.includedModuleLibraries) { val library = context.findRequiredModule(data.moduleName).libraryCollection.libraries .find { getLibraryName(it) == data.libraryName } ?: throw IllegalArgumentException("Cannot find library ${data.libraryName} in \'${data.moduleName}\' module") var fileName = libNameToMergedJarFileName(data.libraryName) var relativePath = data.relativeOutputPath var targetFile: Path? = null if (relativePath.endsWith(".jar")) { val index = relativePath.lastIndexOf('/') if (index == -1) { fileName = relativePath relativePath = "" } else { fileName = relativePath.substring(index + 1) relativePath = relativePath.substring(0, index) } } if (!relativePath.isEmpty()) { targetFile = outputDir.resolve(relativePath).resolve(fileName) } if (targetFile == null) { targetFile = outputDir.resolve(fileName) } packager.addLibrary( library = library, targetFile = targetFile!!, files = getLibraryFiles(library = library, copiedFiles = copiedFiles, isModuleLevel = true, targetFile = targetFile) ) } val extraLibSources = HashMap<String, MutableList<Source>>() val libraryToMerge = packager.packProjectLibraries(jarToModuleNames = actualModuleJars, outputDir = outputDir, layout = layout, copiedFiles = copiedFiles, extraLibSources = extraLibSources) val isRootDir = context.paths.distAllDir == outputDir.parent if (isRootDir) { for ((key, value) in extraMergeRules) { packager.mergeLibsByPredicate(key, libraryToMerge, outputDir, value) } if (!libraryToMerge.isEmpty()) { packager.filesToSourceWithMappings(outputDir.resolve(APP_JAR), libraryToMerge) } } else if (!libraryToMerge.isEmpty()) { val mainJarName = (layout as PluginLayout).getMainJarName() assert(actualModuleJars.containsKey(mainJarName)) packager.filesToSourceWithMappings(outputDir.resolve(mainJarName), libraryToMerge) } // must be concurrent - buildJars executed in parallel val moduleNameToSize = ConcurrentHashMap<String, Int>() for ((jarPath, modules) in actualModuleJars) { val jarFile = outputDir.resolve(jarPath) val descriptor = packager.jarDescriptors.computeIfAbsent(jarFile) { JarDescriptor(jarFile = it) } val includedModules = descriptor.includedModules if (includedModules == null) { descriptor.includedModules = modules.toMutableList() } else { includedModules.addAll(modules) } val sourceList = descriptor.sources extraLibSources.get(jarPath)?.let(sourceList::addAll) packager.packModuleOutputAndUnpackedProjectLibraries(modules = modules, jarPath = jarPath, jarFile = jarFile, moduleOutputPatcher = moduleOutputPatcher, layout = layout, moduleNameToSize = moduleNameToSize, sourceList = sourceList) } val entries = ArrayList<Triple<Path, String, List<Source>>>(packager.jarDescriptors.size) val isReorderingEnabled = !context.options.buildStepsToSkip.contains(BuildOptions.GENERATE_JAR_ORDER_STEP) for (descriptor in packager.jarDescriptors.values) { var pathInClassLog = "" if (isReorderingEnabled) { if (isRootDir) { pathInClassLog = outputDir.parent.relativize(descriptor.jarFile).toString().replace(File.separatorChar, '/') } else if (outputDir.startsWith(context.paths.distAllDir)) { pathInClassLog = context.paths.distAllDir.relativize(descriptor.jarFile).toString().replace(File.separatorChar, '/') } else { val parent = outputDir.parent if (parent?.fileName.toString() == "plugins") { pathInClassLog = outputDir.parent.parent.relativize(descriptor.jarFile).toString().replace(File.separatorChar, '/') } } } entries.add(Triple(descriptor.jarFile, pathInClassLog, descriptor.sources)) } buildJars(entries, dryRun) for (item in packager.jarDescriptors.values) { for (moduleName in (item.includedModules ?: emptyList())) { val size = moduleNameToSize.get(moduleName) ?: throw IllegalStateException("Size is not set for $moduleName (moduleNameToSize=$moduleNameToSize)") packager.projectStructureMapping.add(ModuleOutputEntry(path = item.jarFile, moduleName, size)) } } return packager.projectStructureMapping } fun getSearchableOptionsDir(buildContext: BuildContext): Path = buildContext.paths.tempDir.resolve("searchableOptionsResult") } private fun mergeLibsByPredicate(jarName: String, libraryToMerge: MutableMap<JpsLibrary, List<Path>>, outputDir: Path, predicate: (String) -> Boolean) { val result = LinkedHashMap<JpsLibrary, List<Path>>() val iterator = libraryToMerge.entries.iterator() while (iterator.hasNext()) { val (key, value) = iterator.next() if (predicate(key.name)) { iterator.remove() result.put(key, value) } } if (result.isEmpty()) { return } filesToSourceWithMappings(outputDir.resolve(jarName), result) } private fun filesToSourceWithMappings(uberJarFile: Path, libraryToMerge: Map<JpsLibrary, List<Path>>) { val sources = getJarDescriptorSources(uberJarFile) for ((key, value) in libraryToMerge) { filesToSourceWithMapping(sources, value, key, uberJarFile) } } private fun packModuleOutputAndUnpackedProjectLibraries(modules: Collection<String>, jarPath: String, jarFile: Path, moduleOutputPatcher: ModuleOutputPatcher, layout: BaseLayout, moduleNameToSize: MutableMap<String, Int>, sourceList: MutableList<Source>) { val searchableOptionsDir = getSearchableOptionsDir(context) Span.current().addEvent("include module outputs", Attributes.of(AttributeKey.stringArrayKey("modules"), java.util.List.copyOf(modules))) for (moduleName in modules) { addModuleSources(moduleName = moduleName, moduleNameToSize = moduleNameToSize, moduleOutputDir = context.getModuleOutputDir(context.findRequiredModule(moduleName)), modulePatches = moduleOutputPatcher.getPatchedDir(moduleName), modulePatchContents = moduleOutputPatcher.getPatchedContent(moduleName), searchableOptionsRootDir = searchableOptionsDir, extraExcludes = layout.moduleExcludes.get(moduleName), sourceList = sourceList) } for (libraryName in layout.projectLibrariesToUnpack.get(jarPath)) { val library = context.project.libraryCollection.findLibrary(libraryName) if (library == null) { context.messages.error("Project library \'$libraryName\' from $jarPath should be unpacked but it isn\'t found") continue } for (ioFile in library.getFiles(JpsOrderRootType.COMPILED)) { val file = ioFile.toPath() sourceList.add(ZipSource(file = file) { size: Int -> val libraryData = ProjectLibraryData(libraryName = library.name, outPath = null, packMode = LibraryPackMode.MERGED, reason = "explicitUnpack") projectStructureMapping.add(ProjectLibraryEntry(jarFile, libraryData, file, size)) }) } } } private fun packProjectLibraries(jarToModuleNames: Map<String, List<String>>, outputDir: Path, layout: BaseLayout, copiedFiles: MutableMap<Path, CopiedFor>, extraLibSources: MutableMap<String, MutableList<Source>>): MutableMap<JpsLibrary, List<Path>> { val toMerge = LinkedHashMap<JpsLibrary, List<Path>>() val projectLibs = if (layout.includedProjectLibraries.isEmpty()) { emptyList() } else { layout.includedProjectLibraries.sortedBy { it.libraryName } } for (libraryData in projectLibs) { val library = context.project.libraryCollection.findLibrary(libraryData.libraryName) ?: throw IllegalArgumentException("Cannot find library ${libraryData.libraryName} in the project") libToMetadata.put(library, libraryData) val libName = library.name var packMode = libraryData.packMode if (packMode == LibraryPackMode.MERGED && !extraMergeRules.values.any { it(libName) } && !isLibraryMergeable(libName)) { packMode = LibraryPackMode.STANDALONE_MERGED } val outPath = libraryData.outPath val files = getLibraryFiles(library = library, copiedFiles = copiedFiles, isModuleLevel = false, targetFile = null) if (packMode == LibraryPackMode.MERGED && outPath == null) { toMerge.put(library, files) } else { var libOutputDir = outputDir if (outPath != null) { libOutputDir = if (outPath.endsWith(".jar")) { addLibrary(library, outputDir.resolve(outPath), files) continue } else { outputDir.resolve(outPath) } } if (packMode == LibraryPackMode.STANDALONE_MERGED) { addLibrary(library, libOutputDir.resolve(libNameToMergedJarFileName(libName)), files) } else { for (file in files) { var fileName = file.fileName.toString() if (packMode == LibraryPackMode.STANDALONE_SEPARATE_WITHOUT_VERSION_NAME) { fileName = removeVersionFromJar(fileName) } addLibrary(library, libOutputDir.resolve(fileName), listOf(file)) } } } } for ((targetFilename, value) in jarToModuleNames) { if (targetFilename.contains("/")) { continue } for (moduleName in value) { if (layout.modulesWithExcludedModuleLibraries.contains(moduleName)) { continue } val excluded = layout.excludedModuleLibraries.get(moduleName) for (element in context.findRequiredModule(moduleName).dependenciesList.dependencies) { if (element !is JpsLibraryDependency) { continue } packModuleLibs(moduleName = moduleName, targetFilename = targetFilename, libraryDependency = element, excluded = excluded, layout = layout, outputDir = outputDir, copiedFiles = copiedFiles, extraLibSources = extraLibSources) } } } return toMerge } private fun packModuleLibs(moduleName: String, targetFilename: String, libraryDependency: JpsLibraryDependency, excluded: Collection<String>, layout: BaseLayout, outputDir: Path, copiedFiles: MutableMap<Path, CopiedFor>, extraLibSources: MutableMap<String, MutableList<Source>>) { if (libraryDependency.libraryReference.parentReference!!.resolve() !is JpsModule) { return } if (JpsJavaExtensionService.getInstance().getDependencyExtension(libraryDependency)?.scope ?.isIncludedIn(JpsJavaClasspathKind.PRODUCTION_RUNTIME) != true) { return } val library = libraryDependency.library!! val libraryName = getLibraryName(library) if (excluded.contains(libraryName) || layout.includedModuleLibraries.any { it.libraryName == libraryName }) { return } val targetFile = outputDir.resolve(targetFilename) val files = getLibraryFiles(library = library, copiedFiles = copiedFiles, isModuleLevel = true, targetFile = targetFile) for (i in (files.size - 1) downTo 0) { val file = files.get(i) val fileName = file.fileName.toString() if (fileName.endsWith("-rt.jar") || fileName.contains("-agent") || fileName == "yjp-controller-api-redist.jar") { files.removeAt(i) addLibrary(library, outputDir.resolve(removeVersionFromJar(fileName)), listOf(file)) } } if (!files.isEmpty()) { val sources = extraLibSources.computeIfAbsent(targetFilename) { mutableListOf() } for (file in files) { sources.add(ZipSource(file) { size -> projectStructureMapping.add(ModuleLibraryFileEntry(targetFile, moduleName, file, size)) }) } } } private fun filesToSourceWithMapping(to: MutableList<Source>, files: List<Path>, library: JpsLibrary, targetFile: Path) { val moduleName = (library.createReference().parentReference as? JpsModuleReference) ?.moduleName for (file in files) { to.add(ZipSource(file) { size -> val libraryEntry = moduleName?.let { ModuleLibraryFileEntry( path = targetFile, moduleName = it, libraryFile = file, size = size, ) } ?: ProjectLibraryEntry( path = targetFile, data = libToMetadata.get(library)!!, libraryFile = file, size = size, ) projectStructureMapping.add(libraryEntry) }) } } private fun addLibrary(library: JpsLibrary, targetFile: Path, files: List<Path>) { filesToSourceWithMapping(getJarDescriptorSources(targetFile), files, library, targetFile) } private fun getJarDescriptorSources(targetFile: Path): MutableList<Source> { return jarDescriptors.computeIfAbsent(targetFile) { JarDescriptor(targetFile) }.sources } } private data class JarDescriptor(val jarFile: Path) { val sources: MutableList<Source> = mutableListOf() var includedModules: MutableList<String>? = null } private fun removeVersionFromJar(fileName: String): String { val matcher = JAR_NAME_WITH_VERSION_PATTERN.matcher(fileName) return if (matcher.matches()) "${matcher.group(1)}.jar" else fileName } private fun getLibraryFiles(library: JpsLibrary, copiedFiles: MutableMap<Path, CopiedFor>, isModuleLevel: Boolean, targetFile: Path?): MutableList<Path> { val files = library.getPaths(JpsOrderRootType.COMPILED) val libName = library.name // allow duplication if packed into the same target file and have the same common prefix files.removeIf { val alreadyCopiedFor = copiedFiles.get(it) if (alreadyCopiedFor == null) { false } else { alreadyCopiedFor.targetFile == targetFile && alreadyCopiedFor.library.name.startsWith("ktor-") } } for (file in files) { val alreadyCopiedFor = copiedFiles.putIfAbsent(file, CopiedFor(library, targetFile)) if (alreadyCopiedFor != null) { // check name - we allow to have same named module level library name if (isModuleLevel && alreadyCopiedFor.library.name == libName) { continue } throw IllegalStateException("File $file from $libName is already provided by ${alreadyCopiedFor.library.name} library") } } return files } private fun libNameToMergedJarFileName(libName: String): String { return "${FileUtil.sanitizeFileName(libName.lowercase(Locale.getDefault()), false)}.jar" } @Suppress("SpellCheckingInspection") private val excludedFromMergeLibs = java.util.Set.of( "sqlite", "async-profiler", "dexlib2", // android-only lib "intellij-test-discovery", // used as an agent "winp", "junixsocket-core", "pty4j", "grpc-netty-shaded", // these contain a native library "protobuf", // https://youtrack.jetbrains.com/issue/IDEA-268753 ) private fun isLibraryMergeable(libName: String): Boolean { return !excludedFromMergeLibs.contains(libName) && !(libName.startsWith("kotlin-") && !libName.startsWith("kotlin-test-")) && !libName.startsWith("kotlinc.") && !libName.startsWith("projector-") && !libName.contains("-agent-") && !libName.startsWith("rd-") && !libName.contains("annotations", ignoreCase = true) && !libName.startsWith("junit", ignoreCase = true) && !libName.startsWith("cucumber-", ignoreCase = true) && !libName.contains("groovy", ignoreCase = true) } internal val commonModuleExcludes = java.util.List.of( FileSystems.getDefault().getPathMatcher("glob:**/icon-robots.txt"), FileSystems.getDefault().getPathMatcher("glob:icon-robots.txt"), FileSystems.getDefault().getPathMatcher("glob:.unmodified"), // compilation cache on TC FileSystems.getDefault().getPathMatcher("glob:.hash"), FileSystems.getDefault().getPathMatcher("glob:classpath.index"), ) private fun addModuleSources(moduleName: String, moduleNameToSize: MutableMap<String, Int>, moduleOutputDir: Path, modulePatches: Collection<Path>, modulePatchContents: Map<String, ByteArray>, searchableOptionsRootDir: Path, extraExcludes: Collection<String>, sourceList: MutableList<Source>) { val sizeConsumer = IntConsumer { moduleNameToSize.merge(moduleName, it) { oldValue, value -> oldValue + value } } for (entry in modulePatchContents) { sourceList.add(InMemoryContentSource(entry.key, entry.value, sizeConsumer)) } // must be before module output to override for (moduleOutputPatch in modulePatches) { sourceList.add(DirSource(moduleOutputPatch, Collections.emptyList(), sizeConsumer)) } val searchableOptionsModuleDir = searchableOptionsRootDir.resolve(moduleName) if (Files.exists(searchableOptionsModuleDir)) { sourceList.add(DirSource(searchableOptionsModuleDir, Collections.emptyList(), sizeConsumer)) } val excludes = if (extraExcludes.isEmpty()) { commonModuleExcludes } else { commonModuleExcludes.plus(extraExcludes.map { FileSystems.getDefault().getPathMatcher("glob:$it") }) } sourceList.add(DirSource(dir = moduleOutputDir, excludes = excludes, sizeConsumer = sizeConsumer)) } private data class CopiedFor(val library: JpsLibrary, val targetFile: Path?)
apache-2.0
638339cb0dfc0b78db0e1727b140e2ae
41.922383
140
0.636429
5.017514
false
false
false
false
android/nowinandroid
core/network/src/main/java/com/google/samples/apps/nowinandroid/core/network/fake/FakeNiaNetworkDataSource.kt
1
3607
/* * Copyright 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.samples.apps.nowinandroid.core.network.fake import JvmUnitTestFakeAssetManager import com.google.samples.apps.nowinandroid.core.network.Dispatcher import com.google.samples.apps.nowinandroid.core.network.NiaDispatchers.IO import com.google.samples.apps.nowinandroid.core.network.NiaNetworkDataSource import com.google.samples.apps.nowinandroid.core.network.model.NetworkAuthor import com.google.samples.apps.nowinandroid.core.network.model.NetworkChangeList import com.google.samples.apps.nowinandroid.core.network.model.NetworkNewsResource import com.google.samples.apps.nowinandroid.core.network.model.NetworkTopic import javax.inject.Inject import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.withContext import kotlinx.serialization.ExperimentalSerializationApi import kotlinx.serialization.json.Json import kotlinx.serialization.json.decodeFromStream /** * [NiaNetworkDataSource] implementation that provides static news resources to aid development */ class FakeNiaNetworkDataSource @Inject constructor( @Dispatcher(IO) private val ioDispatcher: CoroutineDispatcher, private val networkJson: Json, private val assets: FakeAssetManager = JvmUnitTestFakeAssetManager, ) : NiaNetworkDataSource { companion object { private const val AUTHORS_ASSET = "authors.json" private const val NEWS_ASSET = "news.json" private const val TOPICS_ASSET = "topics.json" } @OptIn(ExperimentalSerializationApi::class) override suspend fun getTopics(ids: List<String>?): List<NetworkTopic> = withContext(ioDispatcher) { assets.open(TOPICS_ASSET).use(networkJson::decodeFromStream) } @OptIn(ExperimentalSerializationApi::class) override suspend fun getNewsResources(ids: List<String>?): List<NetworkNewsResource> = withContext(ioDispatcher) { assets.open(NEWS_ASSET).use(networkJson::decodeFromStream) } @OptIn(ExperimentalSerializationApi::class) override suspend fun getAuthors(ids: List<String>?): List<NetworkAuthor> = withContext(ioDispatcher) { assets.open(AUTHORS_ASSET).use(networkJson::decodeFromStream) } override suspend fun getTopicChangeList(after: Int?): List<NetworkChangeList> = getTopics().mapToChangeList(NetworkTopic::id) override suspend fun getAuthorChangeList(after: Int?): List<NetworkChangeList> = getAuthors().mapToChangeList(NetworkAuthor::id) override suspend fun getNewsResourceChangeList(after: Int?): List<NetworkChangeList> = getNewsResources().mapToChangeList(NetworkNewsResource::id) } /** * Converts a list of [T] to change list of all the items in it where [idGetter] defines the * [NetworkChangeList.id] */ private fun <T> List<T>.mapToChangeList( idGetter: (T) -> String ) = mapIndexed { index, item -> NetworkChangeList( id = idGetter(item), changeListVersion = index, isDelete = false, ) }
apache-2.0
b11179a0a3de0032612d2dfc1af92f27
39.52809
95
0.754644
4.475186
false
false
false
false
siarhei-luskanau/android-iot-doorbell
di/di_koin/di_koin_doorbell_list/src/main/kotlin/siarhei/luskanau/iot/doorbell/koin/doorbelllist/di/DoorbellListModule.kt
1
1291
package siarhei.luskanau.iot.doorbell.koin.doorbelllist.di import android.os.Bundle import androidx.fragment.app.Fragment import androidx.fragment.app.FragmentActivity import androidx.lifecycle.ViewModelProvider import androidx.lifecycle.ViewModelStoreOwner import org.koin.core.parameter.parametersOf import org.koin.dsl.module import siarhei.luskanau.iot.doorbell.koin.common.di.fragment import siarhei.luskanau.iot.doorbell.koin.common.di.viewModel import siarhei.luskanau.iot.doorbell.ui.doorbelllist.DoorbellListFragment import siarhei.luskanau.iot.doorbell.ui.doorbelllist.DoorbellListViewModel val doorbellListModule = module { fragment { activity: FragmentActivity -> DoorbellListFragment { fragment: Fragment -> val viewModelFactory: ViewModelProvider.Factory = get { parametersOf(activity, fragment, fragment.arguments) } ViewModelProvider(fragment as ViewModelStoreOwner, viewModelFactory) .get(DoorbellListViewModel::class.java) } } viewModel { activity: FragmentActivity, _: Fragment, _: Bundle? -> DoorbellListViewModel( appNavigation = get { parametersOf(activity) }, thisDeviceRepository = get(), doorbellsDataSource = get() ) } }
mit
4ad0f2a8a2ef527859100503bdebb630
38.121212
80
0.740511
4.835206
false
false
false
false
GunoH/intellij-community
platform/platform-impl/src/com/intellij/ui/layout/LayoutBuilder.kt
2
3117
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.ui.layout import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.actionSystem.PlatformCoreDataKeys import com.intellij.openapi.actionSystem.PlatformDataKeys import com.intellij.openapi.fileChooser.FileChooser import com.intellij.openapi.fileChooser.FileChooserDescriptor import com.intellij.openapi.util.NlsContexts import com.intellij.openapi.vfs.VirtualFile import com.intellij.ui.components.JBRadioButton import org.jetbrains.annotations.ApiStatus import org.jetbrains.annotations.Nls import javax.swing.AbstractButton import javax.swing.ButtonGroup open class LayoutBuilder @PublishedApi internal constructor(@PublishedApi internal val builder: LayoutBuilderImpl) : RowBuilder by builder.rootRow { @ApiStatus.ScheduledForRemoval @Deprecated("Use Kotlin UI DSL Version 2") override fun withButtonGroup(title: String?, buttonGroup: ButtonGroup, body: () -> Unit) { builder.withButtonGroup(buttonGroup, body) } @Suppress("PropertyName") @PublishedApi @get:Deprecated("", replaceWith = ReplaceWith("builder"), level = DeprecationLevel.ERROR) @get:ApiStatus.ScheduledForRemoval internal val `$`: LayoutBuilderImpl get() = builder } @ApiStatus.ScheduledForRemoval @Deprecated("Use Kotlin UI DSL Version 2") class CellBuilderWithButtonGroupProperty<T : Any> @PublishedApi internal constructor(private val prop: PropertyBinding<T>) @Deprecated("Use Kotlin UI DSL Version 2") class RowBuilderWithButtonGroupProperty<T : Any> @PublishedApi internal constructor(private val builder: RowBuilder, private val prop: PropertyBinding<T>) : RowBuilder by builder { @Deprecated("Use Kotlin UI DSL Version 2") fun Row.radioButton(@NlsContexts.RadioButton text: String, value: T, @Nls comment: String? = null): CellBuilder<JBRadioButton> { val component = JBRadioButton(text, prop.get() == value) attachSubRowsEnabled(component) return component(comment = comment).bindValue(value) } @Deprecated("Use Kotlin UI DSL Version 2") fun CellBuilder<JBRadioButton>.bindValue(value: T): CellBuilder<JBRadioButton> = bindValueToProperty(prop, value) } @Deprecated("Use Kotlin UI DSL Version 2") private fun <T> CellBuilder<JBRadioButton>.bindValueToProperty(prop: PropertyBinding<T>, value: T): CellBuilder<JBRadioButton> = apply { onApply { if (component.isSelected) prop.set(value) } onReset { component.isSelected = prop.get() == value } onIsModified { component.isSelected != (prop.get() == value) } } fun FileChooserDescriptor.chooseFile(event: AnActionEvent, fileChosen: (chosenFile: VirtualFile) -> Unit) { FileChooser.chooseFile(this, event.getData(PlatformDataKeys.PROJECT), event.getData(PlatformCoreDataKeys.CONTEXT_COMPONENT), null, fileChosen) } @Deprecated("Use Kotlin UI DSL Version 2") fun Row.attachSubRowsEnabled(component: AbstractButton) { subRowsEnabled = component.selected() component.selected.addListener { subRowsEnabled = it } }
apache-2.0
f09b4797678a22e5654671c5f6e5b23b
43.528571
148
0.782804
4.504335
false
false
false
false
GunoH/intellij-community
plugins/kotlin/j2k/new/src/org/jetbrains/kotlin/nj2k/expressions.kt
2
14893
// 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.nj2k import com.intellij.openapi.module.Module import com.intellij.openapi.project.Project import com.intellij.psi.PsiElement import com.intellij.psi.tree.TokenSet import org.jetbrains.annotations.ApiStatus import org.jetbrains.kotlin.config.AnalysisFlags import org.jetbrains.kotlin.config.LanguageFeature import org.jetbrains.kotlin.config.LanguageVersionSettings import org.jetbrains.kotlin.idea.base.projectStructure.ExternalCompilerVersionProvider import org.jetbrains.kotlin.idea.base.projectStructure.languageVersionSettings import org.jetbrains.kotlin.idea.compiler.configuration.IdeKotlinVersion import org.jetbrains.kotlin.idea.compiler.configuration.KotlinJpsPluginSettings import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.name.FqName import org.jetbrains.kotlin.nj2k.symbols.JKMethodSymbol import org.jetbrains.kotlin.nj2k.symbols.JKSymbol import org.jetbrains.kotlin.nj2k.symbols.JKUnresolvedMethod import org.jetbrains.kotlin.nj2k.tree.* import org.jetbrains.kotlin.nj2k.types.JKNoType import org.jetbrains.kotlin.nj2k.types.JKType import org.jetbrains.kotlin.nj2k.types.JKTypeFactory import org.jetbrains.kotlin.nj2k.types.replaceJavaClassWithKotlinClassType import org.jetbrains.kotlin.resolve.annotations.KOTLIN_THROWS_ANNOTATION_FQ_NAME import org.jetbrains.kotlin.utils.addToStdlib.cast import org.jetbrains.kotlin.utils.addToStdlib.firstIsInstanceOrNull import org.jetbrains.kotlin.utils.addToStdlib.safeAs fun JKOperator.isEquals() = token.safeAs<JKKtSingleValueOperatorToken>()?.psiToken in equalsOperators private val equalsOperators = TokenSet.create( KtTokens.EQEQEQ, KtTokens.EXCLEQEQEQ, KtTokens.EQEQ, KtTokens.EXCLEQ ) fun untilToExpression( from: JKExpression, to: JKExpression, conversionContext: NewJ2kConverterContext ): JKExpression { val isPossibleToUseRangeUntil = conversionContext.converter.targetModule ?.let { it.languageVersionSettings.isPossibleToUseRangeUntil(it, conversionContext.project) } == true return rangeExpression( from, to, if (isPossibleToUseRangeUntil) "..<" else "until", conversionContext ) } fun downToExpression( from: JKExpression, to: JKExpression, conversionContext: NewJ2kConverterContext ): JKExpression = rangeExpression( from, to, "downTo", conversionContext ) fun JKExpression.parenthesizeIfCompoundExpression() = when (this) { is JKIfElseExpression, is JKBinaryExpression, is JKTypeCastExpression -> JKParenthesizedExpression(this) else -> this } fun JKExpression.parenthesize() = JKParenthesizedExpression(this) fun rangeExpression( from: JKExpression, to: JKExpression, operatorName: String, conversionContext: NewJ2kConverterContext ): JKExpression = JKBinaryExpression( from, to, JKKtOperatorImpl( JKKtWordOperatorToken(operatorName), conversionContext.symbolProvider.provideMethodSymbol("kotlin.ranges.$operatorName").returnType!! ) ) fun blockStatement(vararg statements: JKStatement) = JKBlockStatement(JKBlockImpl(statements.toList())) fun blockStatement(statements: List<JKStatement>) = JKBlockStatement(JKBlockImpl(statements)) fun useExpression( receiver: JKExpression, variableIdentifier: JKNameIdentifier?, body: JKStatement, symbolProvider: JKSymbolProvider ): JKExpression { val useSymbol = symbolProvider.provideMethodSymbol("kotlin.io.use") val lambdaParameter = if (variableIdentifier != null) JKParameter(JKTypeElement(JKNoType), variableIdentifier) else null val lambda = JKLambdaExpression( body, listOfNotNull(lambdaParameter) ) val methodCall = JKCallExpressionImpl( useSymbol, listOf(lambda).toArgumentList() ) return JKQualifiedExpression(receiver, methodCall) } fun kotlinAssert(assertion: JKExpression, message: JKExpression?, typeFactory: JKTypeFactory) = JKCallExpressionImpl( JKUnresolvedMethod( //TODO resolve assert "assert", typeFactory, typeFactory.types.unit ), listOfNotNull(assertion, message).toArgumentList() ) fun jvmAnnotation(name: String, symbolProvider: JKSymbolProvider) = JKAnnotation( symbolProvider.provideClassSymbol("kotlin.jvm.$name") ) fun throwsAnnotation(throws: List<JKType>, symbolProvider: JKSymbolProvider) = JKAnnotation( symbolProvider.provideClassSymbol(KOTLIN_THROWS_ANNOTATION_FQ_NAME.asString()), throws.map { JKAnnotationParameterImpl( JKClassLiteralExpression(JKTypeElement(it), JKClassLiteralExpression.ClassLiteralType.KOTLIN_CLASS) ) } ) fun JKAnnotationList.annotationByFqName(fqName: String): JKAnnotation? = annotations.firstOrNull { it.classSymbol.fqName == fqName } fun stringLiteral(content: String, typeFactory: JKTypeFactory): JKExpression { val lines = content.split('\n') return lines.mapIndexed { i, line -> val newlineSeparator = if (i == lines.size - 1) "" else "\\n" JKLiteralExpression("\"$line$newlineSeparator\"", JKLiteralExpression.LiteralType.STRING) }.reduce { acc: JKExpression, literalExpression: JKLiteralExpression -> JKBinaryExpression(acc, literalExpression, JKKtOperatorImpl(JKOperatorToken.PLUS, typeFactory.types.string)) } } fun JKVariable.findUsages(scope: JKTreeElement, context: NewJ2kConverterContext): List<JKFieldAccessExpression> { val symbol = context.symbolProvider.provideUniverseSymbol(this) val usages = mutableListOf<JKFieldAccessExpression>() val searcher = object : RecursiveApplicableConversionBase(context) { override fun applyToElement(element: JKTreeElement): JKTreeElement { if (element is JKExpression) { element.unboxFieldReference()?.also { if (it.identifier == symbol) { usages += it } } } return recurse(element) } } searcher.runConversion(scope, context) return usages } internal fun JKTreeElement.forEachDescendant(action: (JKElement) -> Unit) { action(this) this.forEachChild { it.forEachDescendant(action) } } internal inline fun <reified E : JKElement> JKTreeElement.forEachDescendantOfType(crossinline action: (E) -> Unit) { forEachDescendant { if (it is E) action(it) } } fun JKExpression.unboxFieldReference(): JKFieldAccessExpression? = when { this is JKFieldAccessExpression -> this this is JKQualifiedExpression && receiver is JKThisExpression -> selector as? JKFieldAccessExpression else -> null } fun JKFieldAccessExpression.asAssignmentFromTarget(): JKKtAssignmentStatement? = parent.safeAs<JKKtAssignmentStatement>()?.takeIf { it.field == this } fun JKFieldAccessExpression.isInDecrementOrIncrement(): Boolean = when (parent.safeAs<JKUnaryExpression>()?.operator?.token) { JKOperatorToken.PLUSPLUS, JKOperatorToken.MINUSMINUS -> true else -> false } fun JKVariable.hasWritableUsages(scope: JKTreeElement, context: NewJ2kConverterContext): Boolean = findUsages(scope, context).any { it.asAssignmentFromTarget() != null || it.isInDecrementOrIncrement() } fun equalsExpression(left: JKExpression, right: JKExpression, typeFactory: JKTypeFactory) = JKBinaryExpression( left, right, JKKtOperatorImpl( JKOperatorToken.EQEQ, typeFactory.types.boolean ) ) fun createCompanion(declarations: List<JKDeclaration>): JKClass = JKClass( JKNameIdentifier(""), JKInheritanceInfo(emptyList(), emptyList()), JKClass.ClassKind.COMPANION, JKTypeParameterList(), JKClassBody(declarations), JKAnnotationList(), emptyList(), JKVisibilityModifierElement(Visibility.PUBLIC), JKModalityModifierElement(Modality.FINAL) ) fun JKClass.getCompanion(): JKClass? = declarationList.firstOrNull { it is JKClass && it.classKind == JKClass.ClassKind.COMPANION } as? JKClass fun JKClass.getOrCreateCompanionObject(): JKClass = getCompanion() ?: createCompanion(declarations = emptyList()) .also { classBody.declarations += it } fun runExpression(body: JKStatement, symbolProvider: JKSymbolProvider): JKExpression { val lambda = JKLambdaExpression( body, emptyList() ) return JKCallExpressionImpl( symbolProvider.provideMethodSymbol("kotlin.run"), JKArgumentList(lambda) ) } fun assignmentStatement(target: JKVariable, expression: JKExpression, symbolProvider: JKSymbolProvider): JKKtAssignmentStatement = JKKtAssignmentStatement( field = JKFieldAccessExpression(symbolProvider.provideUniverseSymbol(target)), expression = expression, token = JKOperatorToken.EQ, ) fun JKAnnotationMemberValue.toExpression(symbolProvider: JKSymbolProvider): JKExpression { fun handleAnnotationParameter(element: JKTreeElement): JKTreeElement = when (element) { is JKClassLiteralExpression -> element.also { element.literalType = JKClassLiteralExpression.ClassLiteralType.KOTLIN_CLASS } is JKTypeElement -> JKTypeElement( element.type.replaceJavaClassWithKotlinClassType(symbolProvider), element::annotationList.detached() ) else -> applyRecursive(element, ::handleAnnotationParameter) } return handleAnnotationParameter( when (this) { is JKStubExpression -> this is JKAnnotation -> JKNewExpression( classSymbol, JKArgumentList( arguments.map { argument -> val value = argument.value.copyTreeAndDetach().toExpression(symbolProvider) when (argument) { is JKAnnotationNameParameter -> JKNamedArgument(value, JKNameIdentifier(argument.name.value)) else -> JKArgumentImpl(value) } } ) ) is JKKtAnnotationArrayInitializerExpression -> JKKtAnnotationArrayInitializerExpression(initializers.map { it.detached(this).toExpression(symbolProvider) }) is JKExpression -> this else -> error("Bad initializer") } ) as JKExpression } fun JKExpression.asLiteralTextWithPrefix(): String? = when { this is JKPrefixExpression && (operator.token == JKOperatorToken.MINUS || operator.token == JKOperatorToken.PLUS) && expression is JKLiteralExpression -> operator.token.text + expression.cast<JKLiteralExpression>().literal this is JKLiteralExpression -> literal else -> null } fun JKClass.primaryConstructor(): JKKtPrimaryConstructor? = classBody.declarations.firstIsInstanceOrNull() fun List<JKExpression>.toArgumentList(): JKArgumentList = JKArgumentList(map { JKArgumentImpl(it) }) fun JKExpression.asStatement(): JKExpressionStatement = JKExpressionStatement(this) fun <T : JKExpression> T.nullIfStubExpression(): T? = if (this is JKStubExpression) null else this fun JKExpression.qualified(qualifier: JKExpression?) = if (qualifier != null && qualifier !is JKStubExpression) { JKQualifiedExpression(qualifier, this) } else this fun JKExpression.callOn( symbol: JKMethodSymbol, arguments: List<JKExpression> = emptyList(), typeArguments: List<JKTypeElement> = emptyList() ) = JKQualifiedExpression( this, JKCallExpressionImpl( symbol, JKArgumentList(arguments.map { JKArgumentImpl(it) }), JKTypeArgumentList(typeArguments) ) ) val JKStatement.statements: List<JKStatement> get() = when (this) { is JKBlockStatement -> block.statements else -> listOf(this) } val JKElement.psi: PsiElement? get() = (this as? PsiOwner)?.psi inline fun <reified Elem : PsiElement> JKElement.psi(): Elem? = (this as? PsiOwner)?.psi as? Elem fun JKTypeElement.present(): Boolean = type != JKNoType fun JKStatement.isEmpty(): Boolean = when (this) { is JKEmptyStatement -> true is JKBlockStatement -> block is JKBodyStub is JKExpressionStatement -> expression is JKStubExpression else -> false } fun JKInheritanceInfo.present(): Boolean = extends.isNotEmpty() || implements.isNotEmpty() fun JKInheritanceInfo.supertypeCount(): Int = extends.size + implements.size fun JKClass.isLocalClass(): Boolean = parent !is JKClassBody && parent !is JKFile && parent !is JKTreeRoot val JKClass.declarationList: List<JKDeclaration> get() = classBody.declarations val JKTreeElement.identifier: JKSymbol? get() = when (this) { is JKFieldAccessExpression -> identifier is JKCallExpression -> identifier is JKClassAccessExpression -> identifier is JKPackageAccessExpression -> identifier is JKNewExpression -> classSymbol else -> null } val JKClass.isObjectOrCompanionObject get() = classKind == JKClass.ClassKind.OBJECT || classKind == JKClass.ClassKind.COMPANION const val EXPERIMENTAL_STDLIB_API_ANNOTATION = "kotlin.ExperimentalStdlibApi" @ApiStatus.Internal fun LanguageVersionSettings.isPossibleToUseRangeUntil(module: Module, project: Project): Boolean = areKotlinVersionsSufficientToUseRangeUntil(module, project) && FqName(EXPERIMENTAL_STDLIB_API_ANNOTATION).asString() in getFlag(AnalysisFlags.optIn) /** * Checks that compilerVersion and languageVersion (or -XXLanguage:+RangeUntilOperator) versions are high enough to use rangeUntil * operator. * * Note that this check is not enough. You also need to check for OptIn (because stdlib declarations are annotated with OptIn) */ @ApiStatus.Internal fun LanguageVersionSettings.areKotlinVersionsSufficientToUseRangeUntil(module: Module, project: Project): Boolean { val compilerVersion = ExternalCompilerVersionProvider.get(module) ?: IdeKotlinVersion.opt(KotlinJpsPluginSettings.jpsVersion(project)) ?: return false // `rangeUntil` is added to languageVersion 1.8 only since 1.7.20-Beta compiler return compilerVersion >= COMPILER_VERSION_WITH_RANGEUNTIL_SUPPORT && supportsFeature(LanguageFeature.RangeUntilOperator) } private val COMPILER_VERSION_WITH_RANGEUNTIL_SUPPORT = IdeKotlinVersion.get("1.7.20-Beta")
apache-2.0
a93f5b3453a4d6226b35896a40f4b2a3
35.32439
130
0.709259
5.23848
false
false
false
false
GunoH/intellij-community
plugins/maven/src/main/java/org/jetbrains/idea/maven/server/DummyMavenServerConnector.kt
2
10366
// 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.idea.maven.server import com.intellij.build.events.MessageEvent import com.intellij.build.issue.BuildIssue import com.intellij.build.issue.BuildIssueQuickFix import com.intellij.openapi.actionSystem.DataContext import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.project.Project import com.intellij.openapi.projectRoots.Sdk import org.jetbrains.annotations.NotNull import org.jetbrains.idea.maven.execution.SyncBundle import org.jetbrains.idea.maven.model.* import org.jetbrains.idea.maven.project.MavenConfigurableBundle import org.jetbrains.idea.maven.project.MavenProjectsManager import org.jetbrains.idea.maven.server.security.MavenToken import org.jetbrains.idea.maven.utils.MavenUtil import java.io.File import java.util.* import java.util.concurrent.CompletableFuture class DummyMavenServerConnector(project: @NotNull Project, val manager: @NotNull MavenServerManager, jdk: @NotNull Sdk, vmOptions: @NotNull String, mavenDistribution: @NotNull MavenDistribution, multimoduleDirectory: @NotNull String) : MavenServerConnector(project, manager, jdk, vmOptions, mavenDistribution, multimoduleDirectory) { override fun isNew() = false override fun isCompatibleWith(jdk: Sdk?, vmOptions: String?, distribution: MavenDistribution?) = true override fun connect() { } override fun getServer(): MavenServer { return DummyMavenServer(myProject) } override fun stop(wait: Boolean) { } override fun getSupportType() = MavenConfigurableBundle.message("connector.ui.dummy") override fun getState() = State.RUNNING override fun checkConnected() = true } class DummyMavenServer(val project: Project) : MavenServer { override fun createEmbedder(settings: MavenEmbedderSettings?, token: MavenToken?): MavenServerEmbedder { return DummyEmbedder(project) } override fun createIndexer(token: MavenToken?): MavenServerIndexer { return DummyIndexer() } override fun interpolateAndAlignModel(model: MavenModel, basedir: File?, token: MavenToken?): MavenModel { return model } override fun assembleInheritance(model: MavenModel, parentModel: MavenModel?, token: MavenToken?): MavenModel { return model } override fun applyProfiles(model: MavenModel, basedir: File?, explicitProfiles: MavenExplicitProfiles?, alwaysOnProfiles: Collection<String>?, token: MavenToken?): ProfileApplicationResult { return ProfileApplicationResult(model, MavenExplicitProfiles.NONE) } override fun createPullLogger(token: MavenToken?): MavenPullServerLogger? { return null } override fun createPullDownloadListener(token: MavenToken?): MavenPullDownloadListener? { return null } } class TrustProjectQuickFix : BuildIssueQuickFix { override val id = ID override fun runQuickFix(project: Project, dataContext: DataContext): CompletableFuture<*> { val future = CompletableFuture<Void>() ApplicationManager.getApplication().invokeLater { try { val result = MavenUtil.isProjectTrustedEnoughToImport(project) if (result) { MavenProjectsManager.getInstance(project).forceUpdateAllProjectsOrFindAllAvailablePomFiles() } future.complete(null) } catch (e: Throwable) { future.completeExceptionally(e) } } return future } companion object { val ID = "TRUST_MAVEN_PROJECT_QUICK_FIX_ID" } } class DummyIndexer : MavenServerIndexer { override fun releaseIndex(id: MavenIndexId, token: MavenToken?) { } override fun getIndexCount(token: MavenToken?): Int { return 0 } override fun updateIndex(id: MavenIndexId, indicator: MavenServerProgressIndicator?, token: MavenToken?) { } override fun processArtifacts(indexId: MavenIndexId, startFrom: Int, token: MavenToken?): List<IndexedMavenId>? = null override fun addArtifact(indexId: MavenIndexId, artifactFile: File?, token: MavenToken?): IndexedMavenId { return IndexedMavenId(null, null, null, null, null) } override fun search(indexId: MavenIndexId, query: String, maxResult: Int, token: MavenToken?): Set<MavenArtifactInfo> { return emptySet() } override fun getInternalArchetypes(token: MavenToken?): Collection<MavenArchetype> { return emptySet() } override fun release(token: MavenToken?) { } override fun indexExists(dir: File?, token: MavenToken?): Boolean { return false } } class DummyEmbedder(val myProject: Project) : MavenServerEmbedder { override fun customizeAndGetProgressIndicator(workspaceMap: MavenWorkspaceMap?, failOnUnresolvedDependency: Boolean, alwaysUpdateSnapshots: Boolean, userProperties: Properties?, token: MavenToken?): MavenServerPullProgressIndicator { return object : MavenServerPullProgressIndicator { override fun pullDownloadEvents(): MutableList<MavenArtifactDownloadServerProgressEvent>? { return null } override fun pullConsoleEvents(): MutableList<MavenServerConsoleEvent>? { return null } override fun cancel() { } } } override fun customizeComponents(token: MavenToken?) { } override fun retrieveAvailableVersions(groupId: String, artifactId: String, remoteRepositories: List<MavenRemoteRepository>, token: MavenToken?): List<String> { return emptyList() } override fun resolveProject(files: Collection<File>, activeProfiles: Collection<String>, inactiveProfiles: Collection<String>, token: MavenToken?): Collection<MavenServerExecutionResult> { MavenProjectsManager.getInstance(myProject).syncConsole.addBuildIssue( object : BuildIssue { override val title = SyncBundle.message("maven.sync.not.trusted.title") override val description = SyncBundle.message("maven.sync.not.trusted.description") + "\n<a href=\"${TrustProjectQuickFix.ID}\">${SyncBundle.message("maven.sync.trust.project")}</a>" override val quickFixes: List<BuildIssueQuickFix> = listOf(TrustProjectQuickFix()) override fun getNavigatable(project: Project) = null }, MessageEvent.Kind.WARNING ) return emptyList() } override fun evaluateEffectivePom(file: File, activeProfiles: List<String>, inactiveProfiles: List<String>, token: MavenToken?): String? { return null } override fun resolve(info: MavenArtifactInfo, remoteRepositories: List<MavenRemoteRepository>, token: MavenToken?): MavenArtifact { return MavenArtifact(info.groupId, info.artifactId, info.version, info.version, null, info.classifier, null, false, info.packaging, null, null, false, true) } override fun resolveTransitively(artifacts: List<MavenArtifactInfo>, remoteRepositories: List<MavenRemoteRepository>, token: MavenToken?): List<MavenArtifact> { return emptyList() } override fun resolveArtifactTransitively(artifacts: MutableList<MavenArtifactInfo>, remoteRepositories: MutableList<MavenRemoteRepository>, token: MavenToken?): MavenArtifactResolveResult { return MavenArtifactResolveResult(emptyList(), null) } override fun resolvePlugin(plugin: MavenPlugin, repositories: List<MavenRemoteRepository>, nativeMavenProjectId: Int, transitive: Boolean, token: MavenToken?): Collection<MavenArtifact> { return emptyList() } override fun execute(file: File, activeProfiles: Collection<String>, inactiveProfiles: Collection<String>, goals: List<String>, selectedProjects: List<String>, alsoMake: Boolean, alsoMakeDependents: Boolean, token: MavenToken?): MavenServerExecutionResult { return MavenServerExecutionResult(null, emptySet(), emptySet()) } override fun reset(token: MavenToken?) { } override fun release(token: MavenToken?) { } override fun clearCaches(token: MavenToken?) { } override fun clearCachesFor(projectId: MavenId?, token: MavenToken?) { } override fun readModel(file: File?, token: MavenToken?): MavenModel? { return null } override fun resolveRepositories(repositories: MutableCollection<MavenRemoteRepository>, token: MavenToken?): MutableSet<MavenRemoteRepository> { return mutableSetOf() } override fun getArchetypes(token: MavenToken?): MutableCollection<MavenArchetype> { return mutableSetOf() } override fun getLocalArchetypes(token: MavenToken?, path: String): MutableCollection<MavenArchetype> { return mutableSetOf() } override fun getRemoteArchetypes(token: MavenToken?, url: String): MutableCollection<MavenArchetype> { return mutableSetOf() } override fun resolveAndGetArchetypeDescriptor(groupId: String, artifactId: String, version: String, repositories: MutableList<MavenRemoteRepository>, url: String?, token: MavenToken?): MutableMap<String, String> { return mutableMapOf() } }
apache-2.0
fa6b956861cb9ce674c8dd5808105cbd
36.154122
158
0.650299
5.354339
false
false
false
false
GunoH/intellij-community
plugins/kotlin/code-insight/postfix-templates/src/org/jetbrains/kotlin/idea/codeInsight/postfix/KotlinAssertPostfixTemplate.kt
3
890
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.kotlin.idea.codeInsight.postfix import com.intellij.codeInsight.template.postfix.templates.StringBasedPostfixTemplate import com.intellij.psi.PsiElement internal class KotlinAssertPostfixTemplate : StringBasedPostfixTemplate { @Suppress("ConvertSecondaryConstructorToPrimary") constructor(provider: KotlinPostfixTemplateProvider) : super( /* name = */ "assert", /* example = */ "assert(expr)", /* selector = */ allExpressions(ValuedFilter, StatementFilter, ExpressionTypeFilter { it.isBoolean && !it.isMarkedNullable }), /* provider = */ provider ) override fun getTemplateString(element: PsiElement) = "kotlin.assert(\$expr$)\$END$" override fun getElementToRemove(expr: PsiElement) = expr }
apache-2.0
60d7b9589fcdc071d947583ed5aba98f
48.5
134
0.744944
4.784946
false
true
false
false
AsamK/TextSecure
app/src/main/java/org/thoughtcrime/securesms/conversation/ThreadAnimationState.kt
2
567
package org.thoughtcrime.securesms.conversation /** * Represents how conversation bubbles should animate at any given time. */ data class ThreadAnimationState constructor( val threadId: Long, val threadMetadata: ConversationData?, val hasCommittedNonEmptyMessageList: Boolean ) { fun shouldPlayMessageAnimations(): Boolean { return when { threadId == -1L || threadMetadata == null -> false threadMetadata.threadSize == 0 -> true threadMetadata.threadSize > 0 && hasCommittedNonEmptyMessageList -> true else -> false } } }
gpl-3.0
3a5873d9ab2ba61557efa31b170cfeef
28.842105
78
0.72134
4.68595
false
false
false
false
ktorio/ktor
ktor-client/ktor-client-core/common/src/io/ktor/client/call/HttpClientCall.kt
1
7172
/* * 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.call import io.ktor.client.* import io.ktor.client.request.* import io.ktor.client.statement.* import io.ktor.http.content.* import io.ktor.util.* import io.ktor.util.reflect.* import io.ktor.utils.io.* import io.ktor.utils.io.concurrent.* import kotlinx.atomicfu.* import kotlinx.coroutines.* import kotlin.coroutines.* import kotlin.reflect.* /** * A pair of a [request] and [response] for a specific [HttpClient]. * * @property client the client that executed the call. */ public open class HttpClientCall( public val client: HttpClient ) : CoroutineScope { private val received: AtomicBoolean = atomic(false) override val coroutineContext: CoroutineContext get() = response.coroutineContext /** * Typed [Attributes] associated to this call serving as a lightweight container. */ public val attributes: Attributes get() = request.attributes /** * The [request] sent by the client. */ public lateinit var request: HttpRequest protected set /** * The [response] sent by the server. */ public lateinit var response: HttpResponse protected set @InternalAPI public constructor( client: HttpClient, requestData: HttpRequestData, responseData: HttpResponseData ) : this(client) { this.request = DefaultHttpRequest(this, requestData) this.response = DefaultHttpResponse(this, responseData) if (responseData.body !is ByteReadChannel) { @Suppress("DEPRECATION_ERROR") attributes.put(CustomResponse, responseData.body) } } protected open val allowDoubleReceive: Boolean = false @OptIn(InternalAPI::class) protected open suspend fun getResponseContent(): ByteReadChannel = response.content /** * Tries to receive the payload of the [response] as a specific expected type provided in [info]. * Returns [response] if [info] corresponds to [HttpResponse]. * * @throws NoTransformationFoundException If no transformation is found for the type [info]. * @throws DoubleReceiveException If already called [body]. */ @OptIn(InternalAPI::class) public suspend fun bodyNullable(info: TypeInfo): Any? { try { if (response.instanceOf(info.type)) return response if (!allowDoubleReceive && !received.compareAndSet(false, true)) { throw DoubleReceiveException(this) } @Suppress("DEPRECATION_ERROR") val responseData = attributes.getOrNull(CustomResponse) ?: getResponseContent() val subject = HttpResponseContainer(info, responseData) val result = client.responsePipeline.execute(this, subject).response.takeIf { it != NullBody } if (result != null && !result.instanceOf(info.type)) { val from = result::class val to = info.type throw NoTransformationFoundException(response, from, to) } return result } catch (cause: Throwable) { response.cancel("Receive failed", cause) throw cause } finally { response.complete() } } /** * Tries to receive the payload of the [response] as a specific expected type provided in [info]. * Returns [response] if [info] corresponds to [HttpResponse]. * * @throws NoTransformationFoundException If no transformation is found for the type [info]. * @throws DoubleReceiveException If already called [body]. * @throws NullPointerException If content is `null`. */ @OptIn(InternalAPI::class) public suspend fun body(info: TypeInfo): Any = bodyNullable(info)!! override fun toString(): String = "HttpClientCall[${request.url}, ${response.status}]" internal fun setResponse(response: HttpResponse) { this.response = response } internal fun setRequest(request: HttpRequest) { this.request = request } public companion object { /** * [CustomResponse] key used to process the response of custom type in case of [HttpClientEngine] can't return body bytes directly. * If present, attribute value will be an initial value for [HttpResponseContainer] in [HttpClient.responsePipeline]. * * Example: [WebSocketSession] */ @Deprecated( "This is going to be removed. Please file a ticket with clarification why and what for do you need it.", level = DeprecationLevel.ERROR ) public val CustomResponse: AttributeKey<Any> = AttributeKey("CustomResponse") } } /** * Tries to receive the payload of the [response] as a specific type [T]. * * @throws NoTransformationFoundException If no transformation is found for the type [T]. * @throws DoubleReceiveException If already called [body]. */ public suspend inline fun <reified T> HttpClientCall.body(): T = bodyNullable(typeInfo<T>()) as T /** * Tries to receive the payload of the [response] as a specific type [T]. * * @throws NoTransformationFoundException If no transformation is found for the type [T]. * @throws DoubleReceiveException If already called [body]. */ public suspend inline fun <reified T> HttpResponse.body(): T = call.bodyNullable(typeInfo<T>()) as T /** * Tries to receive the payload of the [response] as a specific type [T] described in [typeInfo]. * * @throws NoTransformationFoundException If no transformation is found for the type info [typeInfo]. * @throws DoubleReceiveException If already called [body]. */ @Suppress("UNCHECKED_CAST") public suspend fun <T> HttpResponse.body(typeInfo: TypeInfo): T = call.bodyNullable(typeInfo) as T /** * Exception representing that the response payload has already been received. */ @Suppress("KDocMissingDocumentation") public class DoubleReceiveException(call: HttpClientCall) : IllegalStateException() { override val message: String = "Response already received: $call" } /** * Exception representing fail of the response pipeline * [cause] contains origin pipeline exception */ @Suppress("KDocMissingDocumentation", "unused") public class ReceivePipelineException( public val request: HttpClientCall, public val info: TypeInfo, override val cause: Throwable ) : IllegalStateException("Fail to run receive pipeline: $cause") /** * Exception representing the no transformation was found. * It includes the received type and the expected type as part of the message. */ @Suppress("KDocMissingDocumentation") public class NoTransformationFoundException( response: HttpResponse, from: KClass<*>, to: KClass<*> ) : UnsupportedOperationException() { override val message: String? = """No transformation found: $from -> $to |with response from ${response.request.url}: |status: ${response.status} |response headers: |${response.headers.flattenEntries().joinToString { (key, value) -> "$key: $value\n" }} """.trimMargin() }
apache-2.0
dc546423d8ec1673e56c3e79ecac37f6
34.681592
139
0.682515
4.666233
false
false
false
false
xenomachina/kotlin-argparser
src/main/kotlin/com/xenomachina/argparser/SystemExitException.kt
1
3357
// Copyright © 2016 Laurence Gonsalves // // This file is part of kotlin-argparser, a library which can be found at // http://github.com/xenomachina/kotlin-argparser // // This library is free software; you can redistribute it and/or modify it // under the terms of the GNU Lesser General Public License as published by the // Free Software Foundation; either version 2.1 of the License, or (at your // option) any later version. // // This library is distributed in the hope that it will be useful, but WITHOUT // ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or // FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License // for more details. // // You should have received a copy of the GNU Lesser General Public License // along with this library; if not, see http://www.gnu.org/licenses/ package com.xenomachina.argparser import java.io.OutputStreamWriter import java.io.Writer import kotlin.system.exitProcess /** * An exception that wants the process to terminate with a specific status code, and also (optionally) wants to display * a message to [System.out] or [System.err]. * * @property returnCode the return code that this process should exit with */ open class SystemExitException(message: String, val returnCode: Int) : Exception(message) { /** * Prints a message for the user to either `System.err` or `System.out`, and then exits with the appropriate * return code. * * @param programName the name of this program as invoked, or null if not known * @param columns the number of columns to wrap at, or 0 if not to wrap at all */ fun printAndExit(programName: String? = null, columns: Int = 0): Nothing { val writer = OutputStreamWriter(if (returnCode == 0) System.out else System.err) printUserMessage(writer, programName, columns) writer.flush() exitProcess(returnCode) } /** * Prints a message for the user to the specified `Writer`. * * @param writer where to write message for the user * @param programName the name of this program as invoked, or null if not known * @param columns the number of columns to wrap at, or 0 if not to wrap at all */ open fun printUserMessage(writer: Writer, programName: String?, columns: Int) { val leader = if (programName == null) "" else "$programName: " writer.write("$leader$message\n") } } /** * Calls [SystemExitException.printAndExit] on any `SystemExitException` that * is caught. * * @param programName the name of the program. If null, the system property com.xenomachina.argparser.programName will * be used, if set. * @param columns the number of columns to wrap any caught * `SystemExitException` to. Specify null for reasonable defaults, or 0 to not * wrap at all. * @param body the code that may throw a `SystemExitException` */ fun <R> mainBody(programName: String? = null, columns: Int? = null, body: () -> R): R { try { return body() } catch (e: SystemExitException) { e.printAndExit( programName ?: System.getProperty(PROGRAM_NAME_PROPERTY), columns ?: System.getenv("COLUMNS")?.toInt() ?: DEFAULT_COLUMNS) } } private const val PROGRAM_NAME_PROPERTY = "com.xenomachina.argparser.programName" private const val DEFAULT_COLUMNS = 80
lgpl-2.1
da9143bd3387391fe8a8f52611992ce8
40.432099
119
0.703218
4.158612
false
false
false
false
emoji-gen/Emoji-Android
app/src/main/java/moe/pine/emoji/activity/WebViewActivity.kt
1
1938
package moe.pine.emoji.activity import android.content.Context import android.content.Intent import android.os.Bundle import android.os.Handler import android.support.v7.app.AppCompatActivity import android.view.MenuItem import moe.pine.emoji.R import moe.pine.emoji.components.common.ActionBarBackButtonComponent import moe.pine.emoji.components.common.SupportActionBarComponent import moe.pine.emoji.fragment.webview.WebViewLazyFragment import moe.pine.emoji.model.value.WebViewPage /** * Activity for WebView * Created by pine on Apr 21, 2017. */ class WebViewActivity : AppCompatActivity() { companion object { private val PAGE_KEY = "page" private val LAZY_MS = 10L fun createIntent(context: Context, page: WebViewPage): Intent { return Intent(context, WebViewActivity::class.java).also { intent -> intent.putExtra(PAGE_KEY, page.ordinal) } } } private val handler = Handler() private val actionBar by lazy { SupportActionBarComponent(this) } private val backButton by lazy { ActionBarBackButtonComponent(this) } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) this.setContentView(R.layout.activity_webview) this.actionBar.onCreate() val page = WebViewPage.of(this.intent.extras[PAGE_KEY] as Int)!! this.title = page.title if (savedInstanceState == null) { this.handler.postDelayed({ val transaction = this.supportFragmentManager.beginTransaction() transaction.add(R.id.container, WebViewLazyFragment.newInstance(page.url), null) transaction.commitAllowingStateLoss() }, LAZY_MS) } } override fun onOptionsItemSelected(item: MenuItem): Boolean { return this.backButton.onOptionsItemSelected(item) or super.onOptionsItemSelected(item) } }
mit
ca12977f7ad20c47b55c1c87d0b80d7f
33.625
96
0.703818
4.56
false
false
false
false
ClearVolume/scenery
src/main/kotlin/graphics/scenery/utils/TimestampedConcurrentHashMap.kt
1
1232
package graphics.scenery.utils import java.util.concurrent.ConcurrentHashMap class TimestampedConcurrentHashMap<K, V: Timestamped>(initialCapacity: Int = 10) : ConcurrentHashMap<K, V>(initialCapacity) { private var added = ConcurrentHashMap<K, Long>() override fun put(key: K, value: V): V? { added[key] = System.nanoTime() return super.put(key, value) } override fun remove(key: K): V? { val before = super.remove(key) if(before != null) { added.remove(key) } return before } fun hasChanged(key: K, value: V, now: Long = System.nanoTime()): Boolean { return added.getOrDefault(key, now) >= now || value.updated >= now || value.created >= now } inline fun forEachChanged(now: Long = System.nanoTime(), action: (Map.Entry<K, V>) -> Unit) { for (element in this) { if(hasChanged(element.key, element.value, now)) { action(element) } } } inline fun <R> mapChanged(now: Long = System.nanoTime(), transform: (Map.Entry<K, V>) -> R): List<R> { return filter { this.hasChanged(it.key, it.value, now)} .mapTo(ArrayList<R>(size), transform) } }
lgpl-3.0
be688eba11542581f29f07c2c178683d
31.421053
125
0.596591
3.85
false
false
false
false
mdanielwork/intellij-community
platform/vcs-log/impl/src/com/intellij/vcs/log/ui/actions/GoToParentOrChildAction.kt
2
3271
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.vcs.log.ui.actions import com.intellij.openapi.actionSystem.ActionGroup import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.actionSystem.DefaultActionGroup import com.intellij.openapi.project.DumbAwareAction import com.intellij.openapi.ui.popup.JBPopupFactory import com.intellij.vcs.log.VcsCommitMetadata import com.intellij.vcs.log.VcsLogDataKeys import com.intellij.vcs.log.data.LoadingDetails import com.intellij.vcs.log.statistics.VcsLogUsageTriggerCollector import com.intellij.vcs.log.ui.AbstractVcsLogUi import com.intellij.vcs.log.ui.frame.CommitPresentationUtil import java.awt.event.KeyEvent open class GoToParentOrChildAction(val parent: Boolean) : DumbAwareAction() { override fun update(e: AnActionEvent) { val ui = e.getData(VcsLogDataKeys.VCS_LOG_UI) if (ui == null || ui !is AbstractVcsLogUi) { e.presentation.isEnabledAndVisible = false return } e.presentation.isVisible = true e.presentation.isEnabled = ui.table.isFocusOwner && (e.inputEvent is KeyEvent || getRowsToJump(ui).isNotEmpty()) } override fun actionPerformed(e: AnActionEvent) { VcsLogUsageTriggerCollector.triggerUsage(e) val ui = e.getRequiredData(VcsLogDataKeys.VCS_LOG_UI) as AbstractVcsLogUi val rows = getRowsToJump(ui) if (rows.isEmpty()) { // can happen if the action was invoked by shortcut return } if (rows.size == 1) { ui.jumpToRow(rows.single()) } else { val popup = JBPopupFactory.getInstance().createActionGroupPopup("Select ${if (parent) "Parent" else "Child"} to Navigate", createGroup(ui, rows), e.dataContext, JBPopupFactory.ActionSelectionAid.NUMBERING, false) popup.showInBestPositionFor(e.dataContext) } } private fun createGroup(ui: AbstractVcsLogUi, rows: List<Int>): ActionGroup { val actions = rows.mapTo(mutableListOf()) { row -> val text = getActionText(ui.table.model.getCommitMetadata(row)) object : DumbAwareAction(text, "Navigate to $text", null) { override fun actionPerformed(e: AnActionEvent) { VcsLogUsageTriggerCollector.triggerUsage(e, "Go to ${if (parent) "Parent" else "Child"} Commit.Select from Popup") ui.jumpToRow(row) } } } return DefaultActionGroup(actions) } private fun getActionText(commitMetadata: VcsCommitMetadata): String { var text = commitMetadata.id.toShortString() if (commitMetadata !is LoadingDetails) { text += " " + CommitPresentationUtil.getShortSummary(commitMetadata, false, 40) } return text } private fun getRowsToJump(ui: AbstractVcsLogUi): List<Int> { val selectedRows = ui.table.selectedRows if (selectedRows.size != 1) return emptyList() return ui.dataPack.visibleGraph.getRowInfo(selectedRows.single()).getAdjacentRows(parent).sorted() } } class GoToParentRowAction : GoToParentOrChildAction(true) class GoToChildRowAction : GoToParentOrChildAction(false)
apache-2.0
1a200b7760fc056857e8094956288e77
38.902439
140
0.709875
4.462483
false
false
false
false
iSoron/uhabits
uhabits-android/src/androidTest/java/org/isoron/uhabits/activities/habits/show/views/StreakCardViewTest.kt
1
2068
/* * Copyright (C) 2016-2021 Álinson Santos Xavier <[email protected]> * * This file is part of Loop Habit Tracker. * * Loop Habit Tracker 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. * * Loop Habit Tracker is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.isoron.uhabits.activities.habits.show.views import android.view.LayoutInflater import android.view.View import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.test.filters.MediumTest import org.isoron.uhabits.BaseViewTest import org.isoron.uhabits.R import org.isoron.uhabits.core.ui.screens.habits.show.views.StreakCardState import org.isoron.uhabits.core.ui.views.LightTheme import org.junit.Before import org.junit.Test import org.junit.runner.RunWith @RunWith(AndroidJUnit4::class) @MediumTest class StreakCardViewTest : BaseViewTest() { val PATH = "habits/show/StreakCard/" private lateinit var view: StreakCardView @Before override fun setUp() { super.setUp() val habit = fixtures.createLongHabit() view = LayoutInflater .from(targetContext) .inflate(R.layout.show_habit, null) .findViewById<View>(R.id.streakCard) as StreakCardView view.setState( StreakCardState( bestStreaks = habit.streaks.getBest(10), color = habit.color, theme = LightTheme(), ) ) measureView(view, 800f, 600f) } @Test fun testRender() { assertRenders(view, PATH + "render.png") } }
gpl-3.0
e9a18dd656f6f63b8f90bdbbbe9c965b
32.885246
78
0.701984
4.076923
false
true
false
false
iSoron/uhabits
uhabits-android/src/main/java/org/isoron/uhabits/activities/habits/show/views/SubtitleCardView.kt
1
3414
/* * Copyright (C) 2016-2021 Álinson Santos Xavier <[email protected]> * * This file is part of Loop Habit Tracker. * * Loop Habit Tracker 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. * * Loop Habit Tracker is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.isoron.uhabits.activities.habits.show.views import android.annotation.SuppressLint import android.content.Context import android.util.AttributeSet import android.view.LayoutInflater import android.view.View import android.widget.LinearLayout import org.isoron.platform.gui.toInt import org.isoron.uhabits.R import org.isoron.uhabits.activities.habits.edit.formatFrequency import org.isoron.uhabits.activities.habits.list.views.toShortString import org.isoron.uhabits.core.models.NumericalHabitType import org.isoron.uhabits.core.ui.screens.habits.show.views.SubtitleCardState import org.isoron.uhabits.databinding.ShowHabitSubtitleBinding import org.isoron.uhabits.utils.InterfaceUtils import org.isoron.uhabits.utils.formatTime class SubtitleCardView(context: Context, attrs: AttributeSet) : LinearLayout(context, attrs) { private val binding = ShowHabitSubtitleBinding.inflate(LayoutInflater.from(context), this) init { val fontAwesome = InterfaceUtils.getFontAwesome(context) binding.targetIcon.typeface = fontAwesome binding.frequencyIcon.typeface = fontAwesome binding.reminderIcon.typeface = fontAwesome } @SuppressLint("SetTextI18n") fun setState(state: SubtitleCardState) { val color = state.theme.color(state.color).toInt() val reminder = state.reminder binding.frequencyLabel.text = formatFrequency( state.frequency.numerator, state.frequency.denominator, resources, ) binding.questionLabel.setTextColor(color) binding.questionLabel.text = state.question binding.reminderLabel.text = if (reminder != null) { formatTime(context, reminder.hour, reminder.minute) } else { resources.getString(R.string.reminder_off) } binding.targetText.text = "${state.targetValue.toShortString()} ${state.unit}" binding.questionLabel.visibility = View.VISIBLE binding.targetIcon.visibility = View.VISIBLE binding.targetText.visibility = View.VISIBLE if (state.isNumerical) { binding.targetIcon.text = when (state.targetType) { NumericalHabitType.AT_LEAST -> resources.getString(R.string.fa_arrow_circle_up) else -> resources.getString(R.string.fa_arrow_circle_down) } } else { binding.targetIcon.visibility = View.GONE binding.targetText.visibility = View.GONE } if (state.question.isEmpty()) { binding.questionLabel.visibility = View.GONE } postInvalidate() } }
gpl-3.0
1104aeed2d50e091d544f426317c798f
39.630952
95
0.716379
4.370038
false
false
false
false
dahlstrom-g/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/script/ScriptDefinitionMarkerFileType.kt
5
1049
// 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.script import com.intellij.openapi.fileTypes.ex.FakeFileType import com.intellij.openapi.vfs.VirtualFile import org.jetbrains.kotlin.scripting.definitions.SCRIPT_DEFINITION_MARKERS_PATH object ScriptDefinitionMarkerFileType: FakeFileType() { private val markerPathComponents = SCRIPT_DEFINITION_MARKERS_PATH.split('/').filter { it.isNotEmpty() }.reversed() override fun getName(): String = "script-definition-marker" // doesn't make sense for fake file types override fun getDescription(): String = name override fun getDefaultExtension(): String = "" override fun isMyFileType(file: VirtualFile): Boolean { var parentPath = file for (pathComponent in markerPathComponents) { parentPath = parentPath.parent?.takeIf { it.name == pathComponent } ?: return false } return true } }
apache-2.0
10301774376a99115bb2c1777aebfac9
39.384615
158
0.734032
4.600877
false
false
false
false
tateisu/SubwayTooter
app/src/main/java/jp/juggler/subwaytooter/view/ListDivider.kt
1
1946
package jp.juggler.subwaytooter.view import android.content.Context import android.graphics.Canvas import android.graphics.Paint import android.graphics.Rect import android.view.View import androidx.recyclerview.widget.RecyclerView import jp.juggler.subwaytooter.R import jp.juggler.util.attrDrawable class ListDivider(context: Context) : RecyclerView.ItemDecoration() { companion object { var color: Int = 0 var height: Int = 0 var marginH: Int = 0 } private val drawable = context.attrDrawable(R.attr.colorSettingDivider) private val paint = Paint() private val rect = Rect() init { val density = context.resources.displayMetrics.density height = (density * 1f + 0.5f).toInt() marginH = (density * 12f + 0.5f).toInt() paint.style = Paint.Style.FILL paint.isAntiAlias = true } override fun getItemOffsets( outRect: Rect, view: View, parent: RecyclerView, state: RecyclerView.State, ) { outRect.set(0, 0, 0, height) } override fun onDraw(canvas: Canvas, parent: RecyclerView, state: RecyclerView.State) { val left = parent.paddingLeft + marginH val right = parent.width - parent.paddingRight - marginH if (color != 0) { paint.color = color } for (i in 0 until parent.childCount) { val child = parent.getChildAt(i) val params = child.layoutParams as RecyclerView.LayoutParams val top = child.bottom + params.bottomMargin val bottom = top + height if (color != 0) { rect.set(left, top, right, bottom) canvas.drawRect(rect, paint) } else { drawable.setBounds(left, top, right, bottom) drawable.draw(canvas) } } } }
apache-2.0
e048a5b0f49de3316f1e7b593a4c58de
28.40625
90
0.593011
4.422727
false
false
false
false
cd1/motofretado
app/src/main/java/com/gmail/cristiandeives/motofretado/http/response_listener.kt
1
1572
package com.gmail.cristiandeives.motofretado.http import android.util.Log import com.android.volley.Response import com.android.volley.VolleyError import org.json.JSONObject internal sealed class BaseResponseListener<in T>(val mListener: ModelListener<T>) : Response.Listener<JSONObject>, Response.ErrorListener { protected val TAG: String = javaClass.simpleName override fun onErrorResponse(error: VolleyError) { Log.v(TAG, "> onErrorResponse(error=$error)") Log.e(TAG, "unexpected error", error) error.networkResponse?.let { resp -> val httpError = Error.createFromHTTPBody(String(resp.data)) Log.e(TAG, "JSONAPI details: $httpError") } mListener.onError(error) Log.v(TAG, "< onErrorResponse(error=$error)") } } internal class BusResponseListener(listener: ModelListener<Bus>) : BaseResponseListener<Bus>(listener) { override fun onResponse(response: JSONObject) { Log.v(TAG, "> onResponse(response=$response)") val bus = Bus.createFromHTTPBody(response.toString()) mListener.onSuccess(bus) Log.v(TAG, "< onResponse(response=$response)") } } internal class BusesResponseListener(listener: ModelListener<List<Bus>>) : BaseResponseListener<List<Bus>>(listener) { override fun onResponse(response: JSONObject) { Log.v(TAG, "> onResponse(response=$response)") val buses = Bus.createBusesFromHTTPBody(response.toString()) mListener.onSuccess(buses) Log.v(TAG, "< onResponse(response=$response)") } }
gpl-3.0
913e11dc97f35c757359da0af724f02f
33.195652
139
0.697201
4.125984
false
false
false
false
google/intellij-community
plugins/package-search/src/com/jetbrains/packagesearch/intellij/plugin/ui/toolwindow/models/DataStatus.kt
5
1273
/******************************************************************************* * Copyright 2000-2022 JetBrains s.r.o. and contributors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models internal data class DataStatus( val isSearching: Boolean = false, val isRefreshingData: Boolean = false, val isExecutingOperations: Boolean = false ) { val isBusy = isRefreshingData || isSearching || isExecutingOperations override fun toString() = "DataStatus(isBusy=$isBusy " + "[isSearching=$isSearching, isRefreshingData=$isRefreshingData, isExecutingOperations=$isExecutingOperations])" }
apache-2.0
c8bda86a29172ce97cd567419e007a5a
42.896552
119
0.659073
5.031621
false
false
false
false
Atsky/haskell-idea-plugin
plugin/src/org/jetbrains/yesod/julius/highlight/JuliusColors.kt
1
717
package org.jetbrains.yesod.julius.highlight /** * @author Leyla H */ import com.intellij.openapi.editor.colors.TextAttributesKey interface JuliusColors { companion object { val COMMENT: TextAttributesKey = TextAttributesKey.createTextAttributesKey("JULIUS_COMMENT") val STRING: TextAttributesKey = TextAttributesKey.createTextAttributesKey("JULIUS_STRING") val DOT_IDENTIFIER: TextAttributesKey = TextAttributesKey.createTextAttributesKey("JULIUS_DOTIDENTIFIER") val NUMBER: TextAttributesKey = TextAttributesKey.createTextAttributesKey("JULIUS_NUMBER") val INTERPOLATION: TextAttributesKey = TextAttributesKey.createTextAttributesKey("JULIUS_INTERPOLATION") } }
apache-2.0
dbbf271286ba2e7fd41145e38fe08224
41.176471
113
0.781032
5.049296
false
false
false
false
JetBrains/intellij-community
plugins/maven/src/main/java/org/jetbrains/idea/maven/importing/workspaceModel/ContentRootCollector.kt
1
6619
// 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.idea.maven.importing.workspaceModel import com.intellij.openapi.util.Comparing import com.intellij.openapi.util.io.FileUtil import org.jetbrains.jps.model.java.JavaResourceRootType import org.jetbrains.jps.model.java.JavaSourceRootType import org.jetbrains.jps.model.module.JpsModuleSourceRootType object ContentRootCollector { fun collect(folders: List<ImportedFolder>): Collection<ContentRootResult> { class ContentRootWithFolders(val path: String, val folders: MutableList<ImportedFolder> = mutableListOf()) val result = mutableListOf<ContentRootWithFolders>() folders.sorted().forEach { curr -> // 1. ADD CONTENT ROOT, IF NEEDED: var nearestRoot = result.lastOrNull() if (nearestRoot != null && FileUtil.isAncestor(nearestRoot.path, curr.path, false)) { if (curr is ProjectRootFolder) { // don't add nested content roots return@forEach } if (curr is ExcludedFolder && FileUtil.pathsEqual(nearestRoot.path, curr.path)) { // don't add exclude that points at the root return@forEach } } else { if (curr is ExcludedFolder) { // don't add root when there is only an exclude folder under it return@forEach } nearestRoot = ContentRootWithFolders(curr.path) result.add(nearestRoot) if (curr is ProjectRootFolder) { return@forEach } } // 2. MERGE DUPLICATE PATHS val prev = nearestRoot.folders.lastOrNull() if (prev != null && FileUtil.pathsEqual(prev.path, curr.path)) { if (prev.rank <= curr.rank) { return@forEach } } // 3. MERGE SUBFOLDERS: if (prev != null && FileUtil.isAncestor(prev.path, curr.path, true)) { if (prev is SourceFolder && curr is UserOrGeneratedSourceFolder) { // don't add resource under source folder, test under production if (prev.rootTypeRank <= curr.rootTypeRank) { return@forEach } else { nearestRoot.folders.removeLast() } } else if (prev is GeneratedSourceFolder && curr is UserOrGeneratedSourceFolder) { // don't add generated folder when there are sub source folder nearestRoot.folders.removeLast() } else if (prev is ExcludedFolderAndPreventSubfolders && curr is UserOrGeneratedSourceFolder) { // don't add source folders under corresponding exclude folders return@forEach } else if (prev.rank == curr.rank) { // merge other subfolders of the same type return@forEach } } // 4. REGISTER FOLDER UNDER THE ROOT nearestRoot.folders.add(curr) } // Now, we need a second pass over the merged folders, to remove nested exclude folders. // Couldn't do it during the first pass, since exclude folders have different properties (preventing subfolders), // which need to be taken into account during the first pass. val rootIterator = result.iterator() while (rootIterator.hasNext()) { val root = rootIterator.next() val folderIterator = root.folders.iterator() var prev: ImportedFolder? = null while (folderIterator.hasNext()) { val curr = folderIterator.next() if (prev is BaseExcludedFolder && curr is BaseExcludedFolder && FileUtil.isAncestor(prev.path, curr.path, false)) { folderIterator.remove() } else { prev = curr } } } return result.map { root -> val sourceFolders = root.folders.asSequence().filterIsInstance<UserOrGeneratedSourceFolder>().map { folder -> SourceFolderResult(folder.path, folder.type, folder is GeneratedSourceFolder) } val excludeFolders = root.folders.asSequence().filterIsInstance<BaseExcludedFolder>().map { folder -> ExcludedFolderResult(folder.path) } ContentRootResult(root.path, sourceFolders.toList(), excludeFolders.toList()) } } sealed class ImportedFolder(path: String, internal val rank: Int) : Comparable<ImportedFolder> { val path: String = FileUtil.toCanonicalPath(path) override fun compareTo(other: ImportedFolder): Int { val result = FileUtil.comparePaths(path, other.path) if (result != 0) return result return Comparing.compare(rank, other.rank) } override fun toString(): String { return path } } abstract class UserOrGeneratedSourceFolder(path: String, val type: JpsModuleSourceRootType<*>, rank: Int) : ImportedFolder(path, rank) { override fun compareTo(other: ImportedFolder): Int { val result = super.compareTo(other) if (result != 0 || other !is UserOrGeneratedSourceFolder) return result return Comparing.compare(rootTypeRank, other.rootTypeRank) } val rootTypeRank get() = when (type) { JavaSourceRootType.SOURCE -> 0 JavaSourceRootType.TEST_SOURCE -> 1 JavaResourceRootType.RESOURCE -> 2 JavaResourceRootType.TEST_RESOURCE -> 3 else -> error("$type not match to maven root item") } override fun toString(): String { return "$path rootType='${if (type.isForTests) "test" else "main"} ${type.javaClass.simpleName}'" } } abstract class BaseExcludedFolder(path: String, rank: Int) : ImportedFolder(path, rank) class ProjectRootFolder(path: String) : ImportedFolder(path, 0) class SourceFolder(path: String, type: JpsModuleSourceRootType<*>) : UserOrGeneratedSourceFolder(path, type, 1) class ExcludedFolderAndPreventSubfolders(path: String) : BaseExcludedFolder(path, 2) class GeneratedSourceFolder(path: String, type: JpsModuleSourceRootType<*>) : UserOrGeneratedSourceFolder(path, type, 3) class ExcludedFolder(path: String) : BaseExcludedFolder(path, 4) class ContentRootResult(val path: String, val sourceFolders: List<SourceFolderResult>, val excludeFolders: List<ExcludedFolderResult>) { override fun toString() = path } class SourceFolderResult(val path: String, val type: JpsModuleSourceRootType<*>, val isGenerated: Boolean) { override fun toString() = "$path ${if (isGenerated) "generated" else ""} rootType='${if (type.isForTests) "test" else "main"} ${type.javaClass.simpleName}'" } class ExcludedFolderResult(val path: String) { override fun toString() = path } }
apache-2.0
5e6dc924619f7bd9aec6ffe711378221
38.634731
161
0.667019
4.77217
false
false
false
false
JetBrains/intellij-community
plugins/kotlin/jvm-debugger/core/src/org/jetbrains/kotlin/idea/debugger/core/DebuggerUtils.kt
1
9370
// 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.debugger.core import com.intellij.debugger.SourcePosition import com.intellij.debugger.impl.DebuggerUtilsAsync import com.intellij.debugger.impl.DebuggerUtilsImpl.getLocalVariableBorders import com.intellij.openapi.application.runReadAction import com.intellij.openapi.project.DumbService import com.intellij.openapi.project.Project import com.intellij.openapi.util.io.FileUtilRt import com.intellij.openapi.util.registry.Registry import com.intellij.psi.search.GlobalSearchScope import com.intellij.util.concurrency.annotations.RequiresReadLock import com.sun.jdi.LocalVariable import com.sun.jdi.Location import com.sun.jdi.ReferenceType import org.jetbrains.annotations.ApiStatus import org.jetbrains.annotations.TestOnly import org.jetbrains.kotlin.analysis.api.analyze import org.jetbrains.kotlin.analysis.api.calls.successfulFunctionCallOrNull import org.jetbrains.kotlin.asJava.finder.JavaElementFinder import org.jetbrains.kotlin.idea.base.facet.platform.platform import org.jetbrains.kotlin.idea.base.indices.KotlinPackageIndexUtils.findFilesWithExactPackage import org.jetbrains.kotlin.idea.base.projectStructure.scope.KotlinSourceFilterScope import org.jetbrains.kotlin.idea.base.psi.getLineStartOffset import org.jetbrains.kotlin.idea.base.util.KOTLIN_FILE_EXTENSIONS import org.jetbrains.kotlin.idea.debugger.base.util.FileApplicabilityChecker import org.jetbrains.kotlin.idea.debugger.base.util.KotlinSourceMapCache import org.jetbrains.kotlin.idea.stubindex.KotlinFileFacadeFqNameIndex import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.load.kotlin.PackagePartClassUtils import org.jetbrains.kotlin.name.FqName import org.jetbrains.kotlin.platform.isCommon import org.jetbrains.kotlin.platform.jvm.isJvm import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.parents import org.jetbrains.kotlin.resolve.jvm.JvmClassName import org.jetbrains.kotlin.utils.addToStdlib.firstIsInstanceOrNull import java.util.* object DebuggerUtils { @set:TestOnly var forceRanking = false private val IR_BACKEND_LAMBDA_REGEX = ".+\\\$lambda[$-]\\d+".toRegex() fun findSourceFileForClassIncludeLibrarySources( project: Project, scope: GlobalSearchScope, className: JvmClassName, fileName: String, location: Location? = null ): KtFile? { return runReadAction { findSourceFileForClass( project, listOf(scope, KotlinSourceFilterScope.librarySources(GlobalSearchScope.allScope(project), project)), className, fileName, location ) } } fun findSourceFileForClass( project: Project, scopes: List<GlobalSearchScope>, className: JvmClassName, fileName: String, location: Location? ): KtFile? { if (!isKotlinSourceFile(fileName)) return null if (DumbService.getInstance(project).isDumb) return null val partFqName = className.fqNameForClassNameWithoutDollars for (scope in scopes) { val files = findFilesByNameInPackage(className, fileName, project, scope) .filter { it.platform.isJvm() || it.platform.isCommon() } if (files.isEmpty()) { continue } if (files.size == 1 && !forceRanking || location == null) { return files.first() } val singleFile = runReadAction { val matchingFiles = KotlinFileFacadeFqNameIndex.get(partFqName.asString(), project, scope) PackagePartClassUtils.getFilesWithCallables(matchingFiles).singleOrNull { it.name == fileName } } if (singleFile != null) { return singleFile } return chooseApplicableFile(files, location) } return null } private fun chooseApplicableFile(files: List<KtFile>, location: Location): KtFile { return if (Registry.`is`("kotlin.debugger.analysis.api.file.applicability.checker")) { FileApplicabilityChecker.chooseMostApplicableFile(files, location) } else { KotlinDebuggerLegacyFacade.getInstance()?.fileSelector?.chooseMostApplicableFile(files, location) ?: FileApplicabilityChecker.chooseMostApplicableFile(files, location) } } private fun findFilesByNameInPackage( className: JvmClassName, fileName: String, project: Project, searchScope: GlobalSearchScope ): List<KtFile> { val files = findFilesWithExactPackage(className.packageFqName, searchScope, project).filter { it.name == fileName } return files.sortedWith(JavaElementFinder.byClasspathComparator(searchScope)) } fun isKotlinSourceFile(fileName: String): Boolean { val extension = FileUtilRt.getExtension(fileName).lowercase(Locale.getDefault()) return extension in KOTLIN_FILE_EXTENSIONS } fun String.trimIfMangledInBytecode(isMangledInBytecode: Boolean): String = if (isMangledInBytecode) getMethodNameWithoutMangling() else this private fun String.getMethodNameWithoutMangling() = substringBefore('-') fun String.isGeneratedIrBackendLambdaMethodName() = matches(IR_BACKEND_LAMBDA_REGEX) fun LocalVariable.getBorders(): ClosedRange<Location>? { val range = getLocalVariableBorders(this) ?: return null return range.from..range.to } @RequiresReadLock @ApiStatus.Internal fun getLocationsOfInlinedLine(type: ReferenceType, position: SourcePosition, sourceSearchScope: GlobalSearchScope): List<Location> { val line = position.line val file = position.file val project = position.file.project val lineStartOffset = file.getLineStartOffset(line) ?: return listOf() val element = file.findElementAt(lineStartOffset) ?: return listOf() val ktElement = element.parents.firstIsInstanceOrNull<KtElement>() ?: return listOf() val isInInline = element.parents.any { it is KtFunction && it.hasModifier(KtTokens.INLINE_KEYWORD) } if (!isInInline) { // Lambdas passed to cross-inline arguments are inlined when they are used in non-inlined lambdas val isInCrossInlineArgument = isInCrossInlineArgument(ktElement) if (!isInCrossInlineArgument) { return listOf() } } val lines = inlinedLinesNumbers(line + 1, position.file.name, FqName(type.name()), type.sourceName(), project, sourceSearchScope) return lines.flatMap { DebuggerUtilsAsync.locationsOfLineSync(type, it) } } private fun isInCrossInlineArgument(ktElement: KtElement): Boolean { for (function in ktElement.parents.filterIsInstance<KtFunction>()) { when (function) { is KtFunctionLiteral -> { val lambdaExpression = function.parent as? KtLambdaExpression ?: continue val argumentExpression = lambdaExpression.parent if (argumentExpression is KtValueArgument && isCrossInlineArgument(lambdaExpression)) { return true } } is KtNamedFunction -> { if (function.parent is KtValueArgument && isCrossInlineArgument(function)) { return true } } } } return false } private fun isCrossInlineArgument(argumentExpression: KtExpression): Boolean { val callExpression = KtPsiUtil.getParentCallIfPresent(argumentExpression) ?: return false return analyze(callExpression) f@ { val call = callExpression.resolveCall()?.successfulFunctionCallOrNull() ?: return@f false val parameter = call.argumentMapping[argumentExpression]?.symbol ?: return@f false return@f parameter.isCrossinline } } private fun inlinedLinesNumbers( inlineLineNumber: Int, inlineFileName: String, destinationTypeFqName: FqName, destinationFileName: String, project: Project, sourceSearchScope: GlobalSearchScope ): List<Int> { val internalName = destinationTypeFqName.asString().replace('.', '/') val jvmClassName = JvmClassName.byInternalName(internalName) val file = findSourceFileForClassIncludeLibrarySources(project, sourceSearchScope, jvmClassName, destinationFileName) ?: return listOf() val virtualFile = file.virtualFile ?: return listOf() val sourceMap = KotlinSourceMapCache.getInstance(project).getSourceMap(virtualFile, jvmClassName) ?: return listOf() val mappingsToInlinedFile = sourceMap.fileMappings.filter { it.name == inlineFileName } val mappingIntervals = mappingsToInlinedFile.flatMap { it.lineMappings } return mappingIntervals.asSequence().filter { rangeMapping -> rangeMapping.hasMappingForSource(inlineLineNumber) } .map { rangeMapping -> rangeMapping.mapSourceToDest(inlineLineNumber) }.filter { line -> line != -1 }.toList() } }
apache-2.0
aabb2183a8db66aefaf5952fce5eca45
40.830357
137
0.695838
5.078591
false
false
false
false
StepicOrg/stepik-android
app/src/main/java/org/stepik/android/domain/course_calendar/interactor/CourseCalendarInteractor.kt
1
3412
package org.stepik.android.domain.course_calendar.interactor import android.content.Context import io.reactivex.Completable import io.reactivex.Single import io.reactivex.rxkotlin.toObservable import org.stepic.droid.R import ru.nobird.android.domain.rx.doCompletableOnSuccess import ru.nobird.app.core.model.mapToLongArray import org.stepik.android.domain.calendar.model.CalendarEventData import org.stepik.android.domain.calendar.model.CalendarItem import org.stepik.android.domain.calendar.repository.CalendarRepository import org.stepik.android.domain.course_calendar.model.SectionDateEvent import org.stepik.android.domain.course_calendar.repository.CourseCalendarRepository import org.stepik.android.view.course_content.model.CourseContentItem import org.stepik.android.view.course_content.model.CourseContentSectionDate import javax.inject.Inject class CourseCalendarInteractor @Inject constructor( private val context: Context, private val calendarRepository: CalendarRepository, private val courseCalendarRepository: CourseCalendarRepository ) { fun getCalendarItems(): Single<List<CalendarItem>> = calendarRepository.getCalendarItems() fun exportScheduleToCalendar(courseContentItems: List<CourseContentItem>, calendarItem: CalendarItem): Completable = Single .fromCallable { courseContentItems .filterIsInstance<CourseContentItem.SectionItem>() } .doCompletableOnSuccess(::removeOldSchedule) .flatMapObservable { sectionItems -> sectionItems .flatMap { sectionItem -> sectionItem.dates.map { date -> mapDateToCalendarEventData(sectionItem, date) } } .toObservable() } .flatMapSingle { (sectionId, eventData) -> calendarRepository .saveCalendarEventData(eventData, calendarItem) .map { eventId -> SectionDateEvent(eventId, sectionId) } } .toList() .flatMapCompletable(courseCalendarRepository::saveSectionDateEvents) private fun removeOldSchedule(sectionItems: List<CourseContentItem.SectionItem>): Completable = courseCalendarRepository .getSectionDateEventsByIds(*sectionItems.mapToLongArray { it.section.id }) .flatMapCompletable { dateEvents -> calendarRepository .removeCalendarEventDataByIds(*dateEvents.mapToLongArray(SectionDateEvent::eventId)) // mapToLongArray for varargs .andThen(courseCalendarRepository .removeSectionDateEventsByIds(*dateEvents.mapToLongArray(SectionDateEvent::sectionId))) } private fun mapDateToCalendarEventData( sectionItem: CourseContentItem.SectionItem, date: CourseContentSectionDate ): Pair<Long, CalendarEventData> = sectionItem.section.id to CalendarEventData( title = context .getString( R.string.course_content_calendar_title, sectionItem.section.title, context.getString(date.titleRes) ), date = date.date ) }
apache-2.0
237c4b849f07832242b2f8b104e64cd6
43.324675
134
0.661489
5.753794
false
false
false
false
mikepenz/Android-Iconics
iconics-core/src/main/java/com/mikepenz/iconics/utils/IconicsDrawableExtensions.kt
1
9810
/* * Copyright 2020 Mike Penz * * 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("NOTHING_TO_INLINE", "LargeClass") package com.mikepenz.iconics.utils import android.graphics.Typeface import android.util.Log import androidx.annotation.ColorInt import com.mikepenz.iconics.Iconics import com.mikepenz.iconics.IconicsColor import com.mikepenz.iconics.IconicsDrawable import com.mikepenz.iconics.IconicsSize import com.mikepenz.iconics.dsl.NON_READABLE import com.mikepenz.iconics.typeface.IIcon import com.mikepenz.iconics.typeface.ITypeface /** * Loads and draws given text * * @return The current IconicsDrawable for chaining. */ fun IconicsDrawable.icon(icon: String): IconicsDrawable { if (!Iconics.isInitDone()) { Log.e("IconicsDrawable", "Iconics.init() not yet executed, icon will be missing") } try { val foundFont = Iconics.findFont(icon.iconPrefix) if (foundFont == null) { Log.w("IconicsDrawable", "No font identified matching the given `${icon.iconPrefix}` prefix") } else { icon(foundFont.getIcon(icon.clearedIconName)) } } catch (ex: Exception) { Iconics.logger.log(Log.ERROR, Iconics.TAG, "Wrong icon name: $icon") } return this } /** * Loads and draws given icon * * @return The current IconicsDrawable for chaining. */ fun IconicsDrawable.icon(icon: IIcon): IconicsDrawable { if (!Iconics.isInitDone()) { Log.e("IconicsDrawable", "Iconics.init() not yet executed, icon will be missing") } this.icon = icon return this } /** * Loads and draws given icon * * @return The current IconicsDrawable for chaining. */ fun IconicsDrawable.icon(typeface: ITypeface, icon: IIcon): IconicsDrawable { if (!Iconics.isInitDone()) { Log.e("IconicsDrawable", "Iconics.init() not yet executed, icon will be missing") } iconBrush.paint.typeface = typeface.rawTypeface this.icon = icon return this } /** * Loads and draws given text * * @return The current IconicsDrawable for chaining. */ fun IconicsDrawable.iconText(icon: String, typeface: Typeface? = null): IconicsDrawable { iconBrush.paint.typeface = typeface ?: Typeface.DEFAULT iconText = icon return this } /** * Loads and draws given char * * @return The current IconicsDrawable for chaining. */ fun IconicsDrawable.icon(icon: Char): IconicsDrawable { iconText = icon.toString() return this } /** * Set the size and the padding to the correct values to be used for the actionBar / toolBar * * @return The current IconicsDrawable for chaining. */ fun IconicsDrawable.actionBar(): IconicsDrawable { size = IconicsSize.TOOLBAR_ICON_SIZE padding = IconicsSize.TOOLBAR_ICON_PADDING return this } var IconicsDrawable.color: IconicsColor? get() = iconBrush.colorsList?.let { IconicsColor.colorList(it) } set(value) { colorList = value?.extractList(res, theme) } /** @return the icon current color for the current state */ var IconicsDrawable.colorInt: Int @ColorInt get() = iconBrush.colorForCurrentState set(@ColorInt value) { color = IconicsColor.colorInt(value) } var IconicsDrawable.backgroundContourColor: IconicsColor? get() = backgroundContourBrush.colorsList?.let { IconicsColor.colorList(it) } set(value) { backgroundContourColorList = value?.extractList(res, theme) } /** @return the icon background contour color */ var IconicsDrawable.backgroundContourColorInt: Int @ColorInt get() = backgroundContourBrush.colorForCurrentState set(@ColorInt value) { backgroundContourColor = IconicsColor.colorInt(value) } var IconicsDrawable.backgroundColor: IconicsColor? get() = backgroundBrush.colorsList?.let { IconicsColor.colorList(it) } set(value) { backgroundColorList = value?.extractList(res, theme) } /** @return the icon background color */ var IconicsDrawable.backgroundColorInt: Int @ColorInt get() = backgroundBrush.colorForCurrentState set(@ColorInt value) { backgroundColor = IconicsColor.colorInt(value) } var IconicsDrawable.contourColor: IconicsColor? get() = contourBrush.colorsList?.let { IconicsColor.colorList(it) } set(value) { contourColorList = value?.extractList(res, theme) } /** @return the icon contour color */ var IconicsDrawable.contourColorInt: Int @ColorInt get() = contourBrush.colorForCurrentState set(@ColorInt value) { contourColor = IconicsColor.colorInt(value) } /** Set the size by Y axis of the drawable.*/ var IconicsDrawable.sizePx: Int @Deprecated(level = DeprecationLevel.ERROR, message = NON_READABLE) get() = throw UnsupportedOperationException("Please get either sizeX or sizeY directly") set(value) { sizeXPx = value sizeYPx = value } /** Set the size by Y axis of the drawable.*/ var IconicsDrawable.size: IconicsSize? @Deprecated(level = DeprecationLevel.ERROR, message = NON_READABLE) get() = throw UnsupportedOperationException("Please get either sizeX or sizeY directly") set(value) { (value?.extract(res) ?: -1).let { sizeXPx = it sizeYPx = it } } /** Set the size by Y axis of the drawable.*/ var IconicsDrawable.sizeX: IconicsSize? get() = sizeXPx.takeIf { it != -1 }?.let { IconicsSize.px(it) } set(value) { sizeXPx = value?.extract(res) ?: -1 } /** Set the size by Y axis of the drawable.*/ var IconicsDrawable.sizeY: IconicsSize? get() = sizeYPx.takeIf { it != -1 }?.let { IconicsSize.px(it) } set(value) { sizeYPx = value?.extract(res) ?: -1 } /** Set rounded corner rx as IconicsSize */ var IconicsDrawable.roundedCornersRx: IconicsSize? get() = IconicsSize.px(roundedCornerRxPx) set(value) { roundedCornerRxPx = value?.extractFloat(res) ?: -1f } /** Set rounded corner ry as IconicsSize */ var IconicsDrawable.roundedCornersRy: IconicsSize? get() = IconicsSize.px(roundedCornerRyPx) set(value) { roundedCornerRyPx = value?.extractFloat(res) ?: -1f } /** Set rounded corner rx as IconicsSize */ var IconicsDrawable.roundedCornersPx: Float @Deprecated(level = DeprecationLevel.ERROR, message = NON_READABLE) get() = throw UnsupportedOperationException("Please get either roundedCornerRxPx or roundedCornerRyPx directly") set(value) { roundedCornerRxPx = value roundedCornerRyPx = value } /** Set rounded corner rx and ry as IconicsSize */ var IconicsDrawable.roundedCorners: IconicsSize? @Deprecated(level = DeprecationLevel.ERROR, message = NON_READABLE) get() = throw UnsupportedOperationException("Please get either roundedCornerRxPx or roundedCornerRyPx directly") set(value) { (value?.extractFloat(res) ?: 0f).let { roundedCornerRxPx = it roundedCornerRyPx = it } } /** Set the size by Y axis of the drawable.*/ var IconicsDrawable.padding: IconicsSize? get() = paddingPx.takeIf { it != 0 }?.let { IconicsSize.px(it) } set(value) { paddingPx = value?.extract(res) ?: 0 } /** Set the size by Y axis of the drawable.*/ var IconicsDrawable.contourWidth: IconicsSize? get() = contourWidthPx.takeIf { it != 0 }?.let { IconicsSize.px(it) } set(value) { contourWidthPx = value?.extract(res) ?: 0 } /** Set the size by Y axis of the drawable.*/ var IconicsDrawable.backgroundContourWidth: IconicsSize? get() = backgroundContourWidthPx.takeIf { it != 0 }?.let { IconicsSize.px(it) } set(value) { backgroundContourWidthPx = value?.extract(res) ?: 0 } /** Set the size by Y axis of the drawable.*/ var IconicsDrawable.iconOffsetX: IconicsSize? get() = iconOffsetXPx.takeIf { it != 0 }?.let { IconicsSize.px(it) } set(value) { iconOffsetXPx = value?.extract(res) ?: 0 } /** Set the size by Y axis of the drawable.*/ var IconicsDrawable.iconOffsetY: IconicsSize? get() = iconOffsetYPx.takeIf { it != 0 }?.let { IconicsSize.px(it) } set(value) { iconOffsetYPx = value?.extract(res) ?: 0 } /** Set the size by Y axis of the drawable.*/ var IconicsDrawable.shadowRadius: IconicsSize? get() = shadowRadiusPx.takeIf { it != 0f }?.let { IconicsSize.px(it) } set(value) { shadowRadiusPx = value?.extractFloat(res) ?: 0f } /** Set the size by Y axis of the drawable.*/ var IconicsDrawable.shadowDx: IconicsSize? get() = shadowDxPx.takeIf { it != 0f }?.let { IconicsSize.px(it) } set(value) { shadowDxPx = value?.extractFloat(res) ?: 0f } /** Set the size by Y axis of the drawable.*/ var IconicsDrawable.shadowDy: IconicsSize? get() = shadowDyPx.takeIf { it != 0f }?.let { IconicsSize.px(it) } set(value) { shadowDyPx = value?.extractFloat(res) ?: 0f } /** Set the size by Y axis of the drawable.*/ var IconicsDrawable.shadowColor: IconicsColor? get() = shadowColorInt.takeIf { it != 0 }?.let { IconicsColor.colorInt(it) } set(value) { shadowColorInt = value?.extract(res, theme) ?: 0 } /** Clear the shadow for the icon*/ fun IconicsDrawable.clearShadow(): IconicsDrawable { iconBrush.paint.clearShadowLayer() invalidateThis() return this }
apache-2.0
ff039dd36b0864f758fb30b961466ab0
31.486755
116
0.684811
3.955645
false
false
false
false
chrislo27/RhythmHeavenRemixEditor2
core/src/main/kotlin/io/github/chrislo27/rhre3/editor/stage/TapalongStage.kt
2
10990
package io.github.chrislo27.rhre3.editor.stage import com.badlogic.gdx.Gdx import com.badlogic.gdx.Input import com.badlogic.gdx.graphics.OrthographicCamera import com.badlogic.gdx.graphics.g2d.BitmapFont import com.badlogic.gdx.graphics.g2d.SpriteBatch import com.badlogic.gdx.graphics.glutils.ShapeRenderer import com.badlogic.gdx.utils.Align import io.github.chrislo27.rhre3.RHRE3 import io.github.chrislo27.rhre3.editor.Editor import io.github.chrislo27.rhre3.screen.EditorScreen import io.github.chrislo27.rhre3.track.PlayState import io.github.chrislo27.rhre3.track.Remix import io.github.chrislo27.toolboks.i18n.Localization import io.github.chrislo27.toolboks.ui.* import kotlin.math.roundToInt import kotlin.math.sqrt class TapalongStage(val editor: Editor, val palette: UIPalette, parent: EditorStage, camera: OrthographicCamera) : Stage<EditorScreen>(parent, camera) { companion object { const val AUTO_RESET_SECONDS = 5 const val MAX_INPUTS = 4096 } var markersEnabled: Boolean = RHRE3.showTapalongMarkersByDefault val tapRecords = mutableListOf<TapRecord>() var tempo: Float = 0f private set var stdDeviation: Float = 0f private set val roundedTempo: Int get() = tempo.roundToInt() private val tempoLabel: TextLabel<EditorScreen> private val inputsLabel: TextLabel<EditorScreen> private val rawTempoLabel: TextLabel<EditorScreen> private val stdDevLabel: TextLabel<EditorScreen> private val remix: Remix get() = editor.remix private var timeSinceLastTap: Long = System.currentTimeMillis() private var internalTimekeeper: Float = 0f init { this.elements += ColourPane(this, this).apply { this.colour.set(Editor.TRANSLUCENT_BLACK) this.location.set(0f, 0f, 1f, 1f) } tempoLabel = object : TextLabel<EditorScreen>(palette, this, this) { override fun getFont(): BitmapFont { return this.palette.titleFont } }.apply { this.location.set(screenWidth = 0.15f, screenHeight = 0.4f) this.location.set(screenX = 0.5f - this.location.screenWidth / 2, screenY = run { val buttonHeight = 0.35f val padding = 0.05f val totalHeight = buttonHeight + padding * 2 val remainder = 1f - totalHeight totalHeight + remainder / 2 } - this.location.screenHeight / 2) this.isLocalizationKey = false this.textAlign = Align.center this.fontScaleMultiplier = 0.75f this.textWrapping = false } this.elements += tempoLabel val quarterNoteLabel = object : TextLabel<EditorScreen>(palette, this, this) { override fun getFont(): BitmapFont { return this.palette.titleFont } }.apply { this.location.set(screenWidth = 0.1f, screenHeight = tempoLabel.location.screenHeight) this.location.set(screenX = tempoLabel.location.screenX - this.location.screenWidth, screenY = tempoLabel.location.screenY) this.isLocalizationKey = false this.textAlign = Align.right this.fontScaleMultiplier = 0.75f this.text = "♩=" } this.elements += quarterNoteLabel inputsLabel = object : TextLabel<EditorScreen>(palette, this, this) { override fun getRealText(): String { return Localization[text, tapRecords.size] } }.apply { this.location.set(screenWidth = 0.25f, screenHeight = tempoLabel.location.screenHeight) this.location.set(screenX = (1 / 5f) - this.location.screenWidth / 2, screenY = tempoLabel.location.screenY) this.isLocalizationKey = true this.textAlign = Align.center this.text = "editor.tapalong.numberOfInputs" } this.elements += inputsLabel rawTempoLabel = object : TextLabel<EditorScreen>(palette, this, this) { override fun getRealText(): String { return Localization[text, tempo] } }.apply { this.location.set(screenWidth = 0.2f, screenHeight = tempoLabel.location.screenHeight) this.location.set(screenX = (4 / 5f) - 0.125f, screenY = tempoLabel.location.screenY) this.isLocalizationKey = true this.textAlign = Align.center this.textWrapping = false this.text = "editor.tapalong.avgTempo" } this.elements += rawTempoLabel stdDevLabel = object : TextLabel<EditorScreen>(palette, this, this) { override fun getRealText(): String { return Localization[text, stdDeviation] } }.apply { this.location.set(screenWidth = 0.1f, screenHeight = tempoLabel.location.screenHeight) this.location.set(screenX = (4 / 5f) - 0.125f + 0.0125f + rawTempoLabel.location.screenWidth, screenY = tempoLabel.location.screenY) this.isLocalizationKey = true this.fontScaleMultiplier = 0.75f this.textAlign = Align.center this.textWrapping = false this.text = "editor.tapalong.stdDev" this.tooltipTextIsLocalizationKey = true this.tooltipText = "editor.tapalong.stdDev.tooltip" } this.elements += stdDevLabel this.elements += Button(palette, this, this).apply { leftClickAction = { _, _ -> reset() } addLabel(object : TextLabel<EditorScreen>(palette, this, this@TapalongStage) { override fun getRealText(): String { return Localization[text, AUTO_RESET_SECONDS] } }.apply { this.isLocalizationKey = true this.text = "editor.tapalong.button.reset" this.fontScaleMultiplier = 0.75f }) this.location.set(screenWidth = 0.3125f, screenHeight = 0.35f) this.location.set(screenX = 0.0125f, screenY = 0.05f) } this.elements += Button(palette, this, this).apply { leftClickAction = { _, _ -> remix.cuesMuted = !remix.cuesMuted } addLabel(object : TextLabel<EditorScreen>(palette, this, this@TapalongStage) { override fun getRealText(): String { return Localization["editor.tapalong.button.toggleCues.${remix.cuesMuted}"] } }.apply { this.isLocalizationKey = true this.fontScaleMultiplier = 0.75f }) this.location.set(screenWidth = (0.3125f - 0.0125f) / 2f, screenHeight = 0.35f) this.location.set(screenX = 0.675f, screenY = 0.05f) } this.elements += Button(palette, this, this).apply { leftClickAction = { _, _ -> [email protected] = [email protected] } addLabel(object : TextLabel<EditorScreen>(palette, this, this@TapalongStage) { override fun getRealText(): String { return Localization["editor.tapalong.button.toggleMarkers.${[email protected]}"] } }.apply { this.isLocalizationKey = true this.fontScaleMultiplier = 0.75f }) this.location.set(screenWidth = (0.3125f - 0.0125f) / 2f, screenHeight = 0.35f) this.location.set(screenX = 0.675f + this.location.screenWidth + 0.0125f, screenY = 0.05f) } this.elements += Button(palette, this, this).apply { leftClickAction = { _, _ -> tap() } addLabel(TextLabel(palette, this, this@TapalongStage).apply { this.isLocalizationKey = true this.text = "editor.tapalong.button.tap" this.fontScaleMultiplier = 0.75f }) this.location.set(screenWidth = 0.3f, screenHeight = 0.35f) this.location.set(screenX = 0.35f, screenY = 0.05f) } this.updatePositions() updateLabels() } private fun tap() { if (tapRecords.isNotEmpty() && (System.currentTimeMillis() - timeSinceLastTap) >= 1000 * AUTO_RESET_SECONDS) { reset() } while (tapRecords.size >= MAX_INPUTS) { tapRecords.removeAt(0) } if (!tapRecords.any { it.sec == internalTimekeeper }) { // Prevents instantaneous duplicates tapRecords.add(TapRecord(internalTimekeeper, if (remix.playState == PlayState.PLAYING) (remix.seconds - remix.musicStartSec) else Float.NaN)) } timeSinceLastTap = System.currentTimeMillis() // compute new tempo if (tapRecords.size >= 2) { tapRecords.sortBy { it.sec } val deltas = tapRecords.drop(1).mapIndexed { index, rec -> rec.sec - tapRecords[index].sec } val bpms = deltas.map { 60.0 / it } val avgDeltas = deltas.average() val avgBpms = bpms.average() val stdDev = sqrt((deltas.map { (it - avgDeltas) * (it - avgDeltas) }).average()) * 1000.0 // 120 BPM is 2 beats per second b/c 120 / 60 // 120 BPM is 0.5 seconds per beat b/c 60 / 120 // sec = 60 / tempo // tempo = 60 / sec tempo = avgBpms.toFloat() stdDeviation = stdDev.toFloat() } updateLabels() } private fun updateLabels() { when { tapRecords.isEmpty() -> { tempoLabel.text = "0" } tapRecords.size == 1 -> { tempoLabel.text = Localization["editor.tapalong.first"] } else -> { tempoLabel.text = "$roundedTempo" } } } fun reset() { tapRecords.clear() tempo = 0f stdDeviation = 0f updateLabels() } override fun render(screen: EditorScreen, batch: SpriteBatch, shapeRenderer: ShapeRenderer) { internalTimekeeper += Gdx.graphics.deltaTime super.render(screen, batch, shapeRenderer) } override fun keyDown(keycode: Int): Boolean { if (visible) { if (keycode == Input.Keys.T) { tap() return true } else if (keycode == Input.Keys.R) { reset() return true } } return false } data class TapRecord(val sec: Float, val remixSec: Float) }
gpl-3.0
fce1f32ce6f41a8c0f1cbaeaf7bc263f
38.67148
153
0.5749
4.516235
false
false
false
false