repo_name
stringlengths 7
81
| path
stringlengths 6
242
| copies
stringclasses 55
values | size
stringlengths 2
6
| content
stringlengths 55
737k
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 5.44
99.8
| line_max
int64 15
979
| alpha_frac
float64 0.3
0.91
| ratio
float64 2
9.93
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
westnordost/osmagent | app/src/main/java/de/westnordost/streetcomplete/quests/building_underground/AddIsBuildingUnderground.kt | 1 | 1231 | package de.westnordost.streetcomplete.quests.building_underground
import de.westnordost.streetcomplete.R
import de.westnordost.streetcomplete.data.osm.SimpleOverpassQuestType
import de.westnordost.streetcomplete.data.osm.changes.StringMapChangesBuilder
import de.westnordost.streetcomplete.data.osm.download.OverpassMapDataDao
import de.westnordost.streetcomplete.quests.YesNoQuestAnswerFragment
class AddIsBuildingUnderground(o: OverpassMapDataDao) : SimpleOverpassQuestType<Boolean>(o) {
override val tagFilters = "ways, relations with building and !location and layer~-[0-9]+"
override val commitMessage = "Determine whatever building is fully underground"
override val icon = R.drawable.ic_quest_building_underground
override fun getTitle(tags: Map<String, String>): Int {
val hasName = tags.containsKey("name")
return if (hasName)
R.string.quest_building_underground_name_title
else
R.string.quest_building_underground_title
}
override fun createForm() = YesNoQuestAnswerFragment()
override fun applyAnswerTo(answer: Boolean, changes: StringMapChangesBuilder) {
changes.add("location", if (answer) "underground" else "surface")
}
}
| gpl-3.0 | ed72dfedc369424b37994d0e306f1307 | 42.964286 | 93 | 0.766044 | 4.771318 | false | false | false | false |
trife/Field-Book | app/src/main/java/com/fieldbook/tracker/database/dao/ObservationUnitDao.kt | 1 | 1966 | package com.fieldbook.tracker.database.dao
import android.content.ContentValues
import com.fieldbook.tracker.database.*
import com.fieldbook.tracker.database.models.ObservationUnitModel
import java.util.HashMap
import com.fieldbook.tracker.database.Migrator.Study
import com.fieldbook.tracker.database.Migrator.ObservationUnit
class ObservationUnitDao {
companion object {
fun checkUnique(values: HashMap<String, String>): Boolean? = withDatabase { db ->
var result = true
db.query(ObservationUnit.tableName,
select = arrayOf("observation_unit_db_id")).toTable().forEach {
if (it["observation_unit_db_id"] in values.keys) {
result = false
}
}
result
} ?: false
fun getAll(): Array<ObservationUnitModel> = withDatabase { db ->
arrayOf(*db.query(ObservationUnit.tableName)
.toTable()
.map { ObservationUnitModel(it) }
.toTypedArray())
} ?: emptyArray()
fun getAll(eid: Int): Array<ObservationUnitModel> = withDatabase { db ->
arrayOf(*db.query(ObservationUnit.tableName,
where = "${Study.FK} = ?",
whereArgs = arrayOf(eid.toString())).toTable()
.map { ObservationUnitModel(it) }
.toTypedArray())
} ?: emptyArray()
/**
* Updates a given observation unit row with a geo coordinates string.
*/
fun updateObservationUnit(unit: ObservationUnitModel, geoCoordinates: String) = withDatabase { db ->
db.update(ObservationUnit.tableName,
ContentValues().apply {
put("geo_coordinates", geoCoordinates)
},
"${ObservationUnit.PK} = ?", arrayOf(unit.internal_id_observation_unit.toString()))
}
}
} | gpl-2.0 | 9024da710794ca60627bb1f535e6cfbc | 30.725806 | 108 | 0.577314 | 5.242667 | false | false | false | false |
farmerbb/Notepad | app/src/main/java/com/farmerbb/notepad/ui/content/ViewNoteContent.kt | 1 | 5541 | /* Copyright 2021 Braden Farmer
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
@file:OptIn(ExperimentalComposeUiApi::class)
package com.farmerbb.notepad.ui.content
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.text.selection.SelectionContainer
import androidx.compose.foundation.verticalScroll
import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.runtime.compositionLocalOf
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.ExperimentalComposeUiApi
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.input.pointer.pointerInteropFilter
import androidx.compose.ui.res.colorResource
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import com.farmerbb.notepad.R
import com.farmerbb.notepad.ui.components.RtlTextWrapper
import com.farmerbb.notepad.ui.previews.ViewNotePreview
import com.halilibo.richtext.markdown.Markdown
import com.halilibo.richtext.ui.RichText
import com.halilibo.richtext.ui.RichTextThemeIntegration
import com.linkifytext.LinkifyText
@Composable
fun ViewNoteContent(
text: String,
baseTextStyle: TextStyle = TextStyle(),
markdown: Boolean = false,
rtlLayout: Boolean = false,
isPrinting: Boolean = false,
showDoubleTapMessage: Boolean = false,
doubleTapMessageShown: () -> Unit = {},
onDoubleTap: () -> Unit = {}
) {
val textStyle = if (isPrinting) {
baseTextStyle.copy(color = Color.Black)
} else baseTextStyle
var doubleTapTime by remember { mutableStateOf(0L) }
Column(
modifier = Modifier
.fillMaxSize()
.pointerInteropFilter {
val now = System.currentTimeMillis()
when {
doubleTapTime > now -> onDoubleTap()
showDoubleTapMessage -> doubleTapMessageShown()
}
doubleTapTime = now + 300
false
}
) {
Box(
modifier = if (isPrinting) Modifier else Modifier
.verticalScroll(state = rememberScrollState())
) {
val modifier = Modifier
.padding(
horizontal = 16.dp,
vertical = 12.dp
)
.fillMaxWidth()
RtlTextWrapper(text, rtlLayout) {
SelectionContainer {
if (markdown) {
val localTextStyle = compositionLocalOf {
textStyle.copy(color = Color.Unspecified)
}
val localContentColor = compositionLocalOf {
textStyle.color
}
RichTextThemeIntegration(
textStyle = { localTextStyle.current },
contentColor = { localContentColor.current },
ProvideTextStyle = { textStyle, content ->
CompositionLocalProvider(
localTextStyle provides textStyle,
content = content
)
},
ProvideContentColor = { color, content ->
CompositionLocalProvider(
localContentColor provides color,
content = content
)
}
) {
RichText(modifier = modifier) {
Markdown(
// Replace markdown images with links
text.replace(Regex("!\\[([^\\[]+)](\\(.*\\))")) {
it.value.replaceFirst("![", "[")
}
)
}
}
} else {
LinkifyText(
text = text,
style = textStyle,
linkColor = colorResource(id = R.color.primary),
modifier = modifier
)
}
}
}
}
}
}
@Preview
@Composable
fun ViewNoteContentPreview() = ViewNotePreview() | apache-2.0 | 587a4003095a4e3c595e9d619af049bc | 37.22069 | 85 | 0.56506 | 5.724174 | false | false | false | false |
MrSugarCaney/DirtyArrows | src/main/kotlin/nl/sugcube/dirtyarrows/command/CommandList.kt | 1 | 877 | package nl.sugcube.dirtyarrows.command
import nl.sugcube.dirtyarrows.Broadcast
import nl.sugcube.dirtyarrows.DirtyArrows
import nl.sugcube.dirtyarrows.util.sendFormattedMessage
import org.bukkit.command.CommandSender
/**
* @author SugarCaney
*/
open class CommandList : SubCommand<DirtyArrows>(
name = "list",
usage = "/da list",
argumentCount = 0,
description = "Lists all registered protection regions."
) {
init {
addPermissions("dirtyarrows.admin")
}
override fun executeImpl(plugin: DirtyArrows, sender: CommandSender, vararg arguments: String) {
val regions = plugin.regionManager.allNames
val chat = regions.joinToString("&e, ") { "&a$it" }
sender.sendFormattedMessage(Broadcast.REGIONS_LIST.format(regions.size, chat))
}
override fun assertSender(sender: CommandSender) = true
} | gpl-3.0 | 227c6ffdd534a4ac9639ca94045ebd4b | 29.275862 | 100 | 0.706956 | 4.407035 | false | false | false | false |
y20k/trackbook | app/src/main/java/org/y20k/trackbook/MapFragment.kt | 1 | 15754 | /*
* MapFragment.kt
* Implements the MapFragment fragment
* A MapFragment displays a map using osmdroid as well as the controls to start / stop a recording
*
* This file is part of
* TRACKBOOK - Movement Recorder for Android
*
* Copyright (c) 2016-22 - Y20K.org
* Licensed under the MIT-License
* http://opensource.org/licenses/MIT
*
* Trackbook uses osmdroid - OpenStreetMap-Tools for Android
* https://github.com/osmdroid/osmdroid
*/
package org.y20k.trackbook
import YesNoDialog
import android.Manifest
import android.content.*
import android.content.pm.PackageManager
import android.location.Location
import android.os.*
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.activity.result.contract.ActivityResultContracts.RequestPermission
import androidx.core.content.ContextCompat
import androidx.fragment.app.Fragment
import androidx.navigation.fragment.findNavController
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers.IO
import kotlinx.coroutines.Dispatchers.Main
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import org.y20k.trackbook.core.Track
import org.y20k.trackbook.core.TracklistElement
import org.y20k.trackbook.helpers.*
import org.y20k.trackbook.ui.MapFragmentLayoutHolder
/*
* MapFragment class
*/
class MapFragment : Fragment(), YesNoDialog.YesNoDialogListener, MapOverlayHelper.MarkerListener {
/* Define log tag */
private val TAG: String = LogHelper.makeLogTag(MapFragment::class.java)
/* Main class variables */
private var bound: Boolean = false
private val handler: Handler = Handler(Looper.getMainLooper())
private var trackingState: Int = Keys.STATE_TRACKING_NOT
private var gpsProviderActive: Boolean = false
private var networkProviderActive: Boolean = false
private var track: Track = Track()
private lateinit var currentBestLocation: Location
private lateinit var layout: MapFragmentLayoutHolder
private lateinit var trackerService: TrackerService
/* Overrides onCreate from Fragment */
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
// TODO make only MapFragment's status bar transparent - see: https://gist.github.com/Dvik/a3de88d39da9d1d6d175025a56c5e797#file-viewextension-kt and https://proandroiddev.com/android-full-screen-ui-with-transparent-status-bar-ef52f3adde63
// get current best location
currentBestLocation = LocationHelper.getLastKnownLocation(activity as Context)
// get saved tracking state
trackingState = PreferencesHelper.loadTrackingState()
}
/* Overrides onStop from Fragment */
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
// initialize layout
val statusBarHeight: Int = UiHelper.getStatusBarHeight(activity as Context)
layout = MapFragmentLayoutHolder(activity as Context, this as MapOverlayHelper.MarkerListener, inflater, container, statusBarHeight, currentBestLocation, trackingState)
// set up buttons
layout.currentLocationButton.setOnClickListener {
layout.centerMap(currentBestLocation, animated = true)
}
layout.mainButton.setOnClickListener {
handleTrackingManagementMenu()
}
layout.saveButton.setOnClickListener {
saveTrack()
}
layout.clearButton.setOnClickListener {
if (track.wayPoints.isNotEmpty()) {
YesNoDialog(this as YesNoDialog.YesNoDialogListener).show(context = activity as Context, type = Keys.DIALOG_DELETE_CURRENT_RECORDING, message = R.string.dialog_delete_current_recording_message, yesButton = R.string.dialog_delete_current_recording_button_discard)
} else {
trackerService.clearTrack()
}
}
return layout.rootView
}
/* Overrides onStart from Fragment */
override fun onStart() {
super.onStart()
// request location permission if denied
if (ContextCompat.checkSelfPermission(activity as Context, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_DENIED) {
requestLocationPermissionLauncher.launch(Manifest.permission.ACCESS_FINE_LOCATION)
}
// bind to TrackerService
activity?.bindService(Intent(activity, TrackerService::class.java), connection, Context.BIND_AUTO_CREATE)
}
/* Overrides onResume from Fragment */
override fun onResume() {
super.onResume()
// if (bound) {
// trackerService.addGpsLocationListener()
// trackerService.addNetworkLocationListener()
// }
}
/* Overrides onPause from Fragment */
override fun onPause() {
super.onPause()
layout.saveState(currentBestLocation)
if (bound && trackingState != Keys.STATE_TRACKING_ACTIVE) {
trackerService.removeGpsLocationListener()
trackerService.removeNetworkLocationListener()
}
}
/* Overrides onStop from Fragment */
override fun onStop() {
super.onStop()
// unbind from TrackerService
activity?.unbindService(connection)
handleServiceUnbind()
}
/* Register the permission launcher for requesting location */
private val requestLocationPermissionLauncher = registerForActivityResult(RequestPermission()) { isGranted: Boolean ->
if (isGranted) {
// permission was granted - re-bind service
activity?.unbindService(connection)
activity?.bindService(Intent(activity, TrackerService::class.java), connection, Context.BIND_AUTO_CREATE)
LogHelper.i(TAG, "Request result: Location permission has been granted.")
} else {
// permission denied - unbind service
activity?.unbindService(connection)
}
layout.toggleLocationErrorBar(gpsProviderActive, networkProviderActive)
}
/* Register the permission launcher for starting the tracking service */
private val startTrackingPermissionLauncher = registerForActivityResult(RequestPermission()) { isGranted: Boolean ->
logPermissionRequestResult(isGranted)
// start service via intent so that it keeps running after unbind
startTrackerService()
trackerService.startTracking()
}
/* Register the permission launcher for resuming the tracking service */
private val resumeTrackingPermissionLauncher = registerForActivityResult(RequestPermission()) { isGranted: Boolean ->
logPermissionRequestResult(isGranted)
// start service via intent so that it keeps running after unbind
startTrackerService()
trackerService.resumeTracking()
}
/* Logs the request result of the Activity Recognition permission launcher */
private fun logPermissionRequestResult(isGranted: Boolean) {
if (isGranted) {
LogHelper.i(TAG, "Request result: Activity Recognition permission has been granted.")
} else {
LogHelper.i(TAG, "Request result: Activity Recognition permission has NOT been granted.")
}
}
/* Overrides onYesNoDialog from YesNoDialogListener */
override fun onYesNoDialog(type: Int, dialogResult: Boolean, payload: Int, payloadString: String) {
super.onYesNoDialog(type, dialogResult, payload, payloadString)
when (type) {
Keys.DIALOG_EMPTY_RECORDING -> {
when (dialogResult) {
// user tapped resume
true -> {
trackerService.resumeTracking()
}
}
}
Keys.DIALOG_DELETE_CURRENT_RECORDING -> {
when (dialogResult) {
true -> {
trackerService.clearTrack()
}
}
}
}
}
/* Overrides onMarkerTapped from MarkerListener */
override fun onMarkerTapped(latitude: Double, longitude: Double) {
super.onMarkerTapped(latitude, longitude)
if (bound) {
track = TrackHelper.toggleStarred(activity as Context, track, latitude, longitude)
layout.overlayCurrentTrack(track, trackingState)
trackerService.track = track
}
}
/* Start recording waypoints */
private fun startTracking() {
// request activity recognition permission on Android Q+ if denied
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q && ContextCompat.checkSelfPermission(activity as Context, Manifest.permission.ACTIVITY_RECOGNITION) == PackageManager.PERMISSION_DENIED) {
startTrackingPermissionLauncher.launch(Manifest.permission.ACTIVITY_RECOGNITION)
} else {
// start service via intent so that it keeps running after unbind
startTrackerService()
trackerService.startTracking()
}
}
/* Resume recording waypoints */
private fun resumeTracking() {
// request activity recognition permission on Android Q+ if denied
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q && ContextCompat.checkSelfPermission(activity as Context, Manifest.permission.ACTIVITY_RECOGNITION) == PackageManager.PERMISSION_DENIED) {
resumeTrackingPermissionLauncher.launch(Manifest.permission.ACTIVITY_RECOGNITION)
} else {
// start service via intent so that it keeps running after unbind
startTrackerService()
trackerService.resumeTracking()
}
}
/* Start tracker service */
private fun startTrackerService() {
val intent = Intent(activity, TrackerService::class.java)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
// ... start service in foreground to prevent it being killed on Oreo
activity?.startForegroundService(intent)
} else {
activity?.startService(intent)
}
}
/* Handles state when service is being unbound */
private fun handleServiceUnbind() {
bound = false
// unregister listener for changes in shared preferences
PreferencesHelper.unregisterPreferenceChangeListener(sharedPreferenceChangeListener)
// stop receiving location updates
handler.removeCallbacks(periodicLocationRequestRunnable)
}
/* Starts / pauses tracking and toggles the recording sub menu_bottom_navigation */
private fun handleTrackingManagementMenu() {
when (trackingState) {
Keys.STATE_TRACKING_PAUSED -> resumeTracking()
Keys.STATE_TRACKING_ACTIVE -> trackerService.stopTracking()
Keys.STATE_TRACKING_NOT -> startTracking()
}
}
/* Saves track - shows dialog, if recording is still empty */
private fun saveTrack() {
if (track.wayPoints.isEmpty()) {
YesNoDialog(this as YesNoDialog.YesNoDialogListener).show(context = activity as Context, type = Keys.DIALOG_EMPTY_RECORDING, message = R.string.dialog_error_empty_recording_message, yesButton = R.string.dialog_error_empty_recording_button_resume)
} else {
CoroutineScope(IO).launch {
// step 1: create and store filenames for json and gpx files
track.trackUriString = FileHelper.getTrackFileUri(activity as Context, track).toString()
track.gpxUriString = FileHelper.getGpxFileUri(activity as Context, track).toString()
// step 2: save track
FileHelper.saveTrackSuspended(track, saveGpxToo = true)
// step 3: save tracklist - suspended
FileHelper.addTrackAndSaveTracklistSuspended(activity as Context, track)
// step 3: clear track
trackerService.clearTrack()
// step 4: open track in TrackFragement
withContext(Main) {
openTrack(track.toTracklistElement(activity as Context))
}
}
}
}
/* Opens a track in TrackFragment */
private fun openTrack(tracklistElement: TracklistElement) {
val bundle: Bundle = Bundle()
bundle.putString(Keys.ARG_TRACK_TITLE, tracklistElement.name)
bundle.putString(Keys.ARG_TRACK_FILE_URI, tracklistElement.trackUriString)
bundle.putString(Keys.ARG_GPX_FILE_URI, tracklistElement.gpxUriString)
bundle.putLong(Keys.ARG_TRACK_ID, TrackHelper.getTrackId(tracklistElement))
findNavController().navigate(R.id.action_map_fragment_to_track_fragment, bundle)
}
/*
* Defines the listener for changes in shared preferences
*/
private val sharedPreferenceChangeListener = SharedPreferences.OnSharedPreferenceChangeListener { sharedPreferences, key ->
when (key) {
Keys.PREF_TRACKING_STATE -> {
if (activity != null) {
trackingState = PreferencesHelper.loadTrackingState()
layout.updateMainButton(trackingState)
}
}
}
}
/*
* End of declaration
*/
/*
* Defines callbacks for service binding, passed to bindService()
*/
private val connection = object : ServiceConnection {
override fun onServiceConnected(className: ComponentName, service: IBinder) {
bound = true
// get reference to tracker service
val binder = service as TrackerService.LocalBinder
trackerService = binder.service
// get state of tracking and update button if necessary
trackingState = trackerService.trackingState
layout.updateMainButton(trackingState)
// register listener for changes in shared preferences
PreferencesHelper.registerPreferenceChangeListener(sharedPreferenceChangeListener)
// start listening for location updates
handler.removeCallbacks(periodicLocationRequestRunnable)
handler.postDelayed(periodicLocationRequestRunnable, 0)
}
override fun onServiceDisconnected(arg0: ComponentName) {
// service has crashed, or was killed by the system
handleServiceUnbind()
}
}
/*
* End of declaration
*/
/*
* Runnable: Periodically requests location
*/
private val periodicLocationRequestRunnable: Runnable = object : Runnable {
override fun run() {
// pull current state from service
currentBestLocation = trackerService.currentBestLocation
track = trackerService.track
gpsProviderActive = trackerService.gpsProviderActive
networkProviderActive = trackerService.networkProviderActive
trackingState = trackerService.trackingState
// update location and track
layout.markCurrentPosition(currentBestLocation, trackingState)
layout.overlayCurrentTrack(track, trackingState)
layout.updateLiveStatics(length = track.length, duration = track.duration, trackingState = trackingState)
// center map, if it had not been dragged/zoomed before
if (!layout.userInteraction) { layout.centerMap(currentBestLocation, true)}
// show error snackbar if necessary
layout.toggleLocationErrorBar(gpsProviderActive, networkProviderActive)
// use the handler to start runnable again after specified delay
handler.postDelayed(this, Keys.REQUEST_CURRENT_LOCATION_INTERVAL)
}
}
/*
* End of declaration
*/
}
| mit | 33cf440fcbe716315908a4ecae4f8afa | 39.919481 | 278 | 0.674432 | 5.384142 | false | false | false | false |
Saketme/JRAW | lib/src/main/kotlin/net/dean/jraw/models/CommentSort.kt | 2 | 1179 | package net.dean.jraw.models
import com.squareup.moshi.Json
/** A list of sorting methods that can be used when examining comments */
enum class CommentSort {
/** What reddit thinks is best. Factors in score, age, and a few other variables. */
@Json(name = "confidence") CONFIDENCE,
/** Comments with the highest score are shown first. */
@Json(name = "top") TOP,
/** Newest comments are shown first */
@Json(name = "new") NEW,
/** The most controversial comments are shown first (usually this means the comments with the most downvotes) */
@Json(name = "controversial") CONTROVERSIAL,
/** Comments appear in the order they were created */
@Json(name = "old") OLD,
/** Self explanatory */
@Json(name = "random") RANDOM,
/**
* A special sorting made for Q&A-style (questions and answers) posts. Also known as AMA's (ask me anything). Puts
* comments where the submission author replied first, then sorts by [CONFIDENCE].
*/
@Json(name = "qa") QA,
/** As of the time of writing (15 Dec 2017), this sort is in beta. When disabled by reddit, functions like [NEW]. */
@Json(name = "live") LIVE
}
| mit | 6f619e6e11935f0f55acf65ca1db62db | 34.727273 | 120 | 0.659033 | 3.956376 | false | false | false | false |
auth0/Auth0.Android | auth0/src/main/java/com/auth0/android/authentication/ParameterBuilder.kt | 1 | 6301 | package com.auth0.android.authentication
import com.auth0.android.request.internal.OidcUtils
/**
* Builder for Auth0 Authentication API parameters
* You can build your parameters like this
* ```
* val parameters = ParameterBuilder.newBuilder()
* .setClientId("{CLIENT_ID}")
* .setConnection("{CONNECTION}")
* .set("{PARAMETER_NAME}", "{PARAMETER_VALUE}")
* .asDictionary()
* ```
*
* @see ParameterBuilder.newBuilder
* @see ParameterBuilder.newAuthenticationBuilder
*/
public class ParameterBuilder private constructor(parameters: Map<String, String>) {
private val parameters: MutableMap<String, String> = parameters.toMutableMap()
/**
* Sets the 'client_id' parameter
*
* @param clientId the application's client id
* @return itself
*/
public fun setClientId(clientId: String): ParameterBuilder {
return set(CLIENT_ID_KEY, clientId)
}
/**
* Sets the 'grant_type' parameter
*
* @param grantType grant type
* @return itself
*/
public fun setGrantType(grantType: String): ParameterBuilder {
return set(GRANT_TYPE_KEY, grantType)
}
/**
* Sets the 'connection' parameter
*
* @param connection name of the connection
* @return itself
*/
public fun setConnection(connection: String): ParameterBuilder {
return set(CONNECTION_KEY, connection)
}
/**
* Sets the 'realm' parameter. A realm identifies the host against which the authentication will be made, and usually helps to know which username and password to use.
*
* @param realm name of the realm
* @return itself
*/
public fun setRealm(realm: String): ParameterBuilder {
return set(REALM_KEY, realm)
}
/**
* Sets the 'scope' parameter.
*
* @param scope a scope value
* @return itself
*/
public fun setScope(scope: String): ParameterBuilder {
return set(SCOPE_KEY, OidcUtils.includeRequiredScope(scope))
}
/**
* Sets the 'audience' parameter.
*
* @param audience an audience value
* @return itself
*/
public fun setAudience(audience: String): ParameterBuilder {
return set(AUDIENCE_KEY, audience)
}
/**
* Sets the 'refresh_token' parameter
*
* @param refreshToken a access token
* @return itself
*/
public fun setRefreshToken(refreshToken: String): ParameterBuilder {
return set(REFRESH_TOKEN_KEY, refreshToken)
}
/**
* Sets the 'send' parameter
*
* @param passwordlessType the type of passwordless login
* @return itself
*/
public fun setSend(passwordlessType: PasswordlessType): ParameterBuilder {
return set(SEND_KEY, passwordlessType.value)
}
/**
* Sets a parameter
*
* @param key parameter name
* @param value parameter value. A null value will remove the key if present.
* @return itself
*/
public operator fun set(key: String, value: String?): ParameterBuilder {
if (value == null) {
parameters.remove(key)
} else {
parameters[key] = value
}
return this
}
/**
* Adds all parameter from a map
*
* @param parameters map with parameters to add. Null values will be skipped.
* @return itself
*/
public fun addAll(parameters: Map<String, String?>): ParameterBuilder {
parameters.filterValues { it != null }.map { this.parameters.put(it.key, it.value!!) }
return this
}
/**
* Clears all existing parameters
*
* @return itself
*/
public fun clearAll(): ParameterBuilder {
parameters.clear()
return this
}
/**
* Create a [Map] with all the parameters
*
* @return all parameters added previously as a [Map]
*/
public fun asDictionary(): Map<String, String> {
return parameters.toMap()
}
public companion object {
public const val GRANT_TYPE_REFRESH_TOKEN: String = "refresh_token"
public const val GRANT_TYPE_PASSWORD: String = "password"
public const val GRANT_TYPE_PASSWORD_REALM: String =
"http://auth0.com/oauth/grant-type/password-realm"
public const val GRANT_TYPE_AUTHORIZATION_CODE: String = "authorization_code"
public const val GRANT_TYPE_MFA_OTP: String = "http://auth0.com/oauth/grant-type/mfa-otp"
public const val GRANT_TYPE_MFA_OOB: String = "http://auth0.com/oauth/grant-type/mfa-oob"
public const val GRANT_TYPE_MFA_RECOVERY_CODE: String =
"http://auth0.com/oauth/grant-type/mfa-recovery-code"
public const val GRANT_TYPE_PASSWORDLESS_OTP: String =
"http://auth0.com/oauth/grant-type/passwordless/otp"
public const val GRANT_TYPE_TOKEN_EXCHANGE: String =
"urn:ietf:params:oauth:grant-type:token-exchange"
public const val SCOPE_OPENID: String = "openid"
public const val SCOPE_OFFLINE_ACCESS: String = "openid offline_access"
public const val SCOPE_KEY: String = "scope"
public const val REFRESH_TOKEN_KEY: String = "refresh_token"
public const val CONNECTION_KEY: String = "connection"
public const val REALM_KEY: String = "realm"
public const val SEND_KEY: String = "send"
public const val CLIENT_ID_KEY: String = "client_id"
public const val GRANT_TYPE_KEY: String = "grant_type"
public const val AUDIENCE_KEY: String = "audience"
/**
* Creates a new instance of the builder using default values for login request, e.g. 'openid profile email' for scope.
*
* @return a new builder
*/
@JvmStatic
public fun newAuthenticationBuilder(): ParameterBuilder {
return newBuilder()
.setScope(OidcUtils.DEFAULT_SCOPE)
}
/**
* Creates a new instance of the builder.
*
* @param parameters an optional map of initial parameters
* @return a new builder
*/
@JvmStatic
@JvmOverloads
public fun newBuilder(parameters: Map<String, String> = mutableMapOf()): ParameterBuilder {
return ParameterBuilder(parameters)
}
}
} | mit | 133694315704d6001b18aa38cb04a636 | 30.989848 | 171 | 0.627678 | 4.38483 | false | false | false | false |
square/wire | wire-library/wire-gradle-plugin/src/main/kotlin/com/squareup/wire/gradle/WireExtension.kt | 1 | 9604 | /*
* Copyright (C) 2019 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 com.squareup.wire.gradle
import org.gradle.api.Action
import org.gradle.api.Project
import org.gradle.api.artifacts.MinimalExternalModuleDependency
import org.gradle.api.file.SourceDirectorySet
import org.gradle.api.internal.catalog.DelegatingProjectDependency
import org.gradle.api.provider.Provider
import org.gradle.api.provider.ProviderConvertible
import org.gradle.api.tasks.Input
import org.gradle.api.tasks.InputFiles
import org.gradle.api.tasks.Optional
import org.gradle.api.tasks.util.PatternFilterable
open class WireExtension(project: Project) {
private val objectFactory = project.objects
internal val sourcePaths = mutableSetOf<String>()
internal val protoPaths = mutableSetOf<String>()
internal val sourceTrees = mutableSetOf<SourceDirectorySet>()
internal val protoTrees = mutableSetOf<SourceDirectorySet>()
internal val sourceJars = mutableSetOf<ProtoRootSet>()
internal val protoJars = mutableSetOf<ProtoRootSet>()
internal val roots = mutableSetOf<String>()
internal val prunes = mutableSetOf<String>()
internal val moves = mutableListOf<Move>()
internal var onlyVersion: String? = null
internal var sinceVersion: String? = null
internal var untilVersion: String? = null
internal var permitPackageCycles: Boolean = false
@Input
@Optional
fun roots() = roots.toSet()
/**
* See [com.squareup.wire.schema.WireRun.treeShakingRoots]
*/
fun root(vararg roots: String) {
this.roots.addAll(roots)
}
@Input
@Optional
fun prunes() = prunes.toSet()
/**
* See [com.squareup.wire.schema.WireRun.treeShakingRubbish]
*/
fun prune(vararg prunes: String) {
this.prunes.addAll(prunes)
}
@Input
@Optional
fun sinceVersion() = sinceVersion
/**
* See [com.squareup.wire.schema.WireRun.sinceVersion]
*/
fun sinceVersion(sinceVersion: String) {
this.sinceVersion = sinceVersion
}
@Input
@Optional
fun untilVersion() = untilVersion
/**
* See [com.squareup.wire.schema.WireRun.untilVersion]
*/
fun untilVersion(untilVersion: String) {
this.untilVersion = untilVersion
}
@Input
@Optional
fun onlyVersion() = onlyVersion
/**
* See [com.squareup.wire.schema.WireRun.onlyVersion].
*/
fun onlyVersion(onlyVersion: String) {
this.onlyVersion = onlyVersion
}
@Input
fun permitPackageCycles() = permitPackageCycles
/**
* See [com.squareup.wire.schema.WireRun.permitPackageCycles]
*/
fun permitPackageCycles(permitPackageCycles: Boolean) {
this.permitPackageCycles = permitPackageCycles
}
/**
* A user-provided file listing [roots] and [prunes]
*/
@get:Input
@get:Optional
var rules: String? = null
/** Specified what types to output where. Maps to [com.squareup.wire.schema.Target] */
@get:Input
val outputs = mutableListOf<WireOutput>()
/**
* True to emit `.proto` files into the output resources. Use this when your `.jar` file can be
* used as a library for other proto or Wire projects.
*
* Note that only the `.proto` files used in the library will be included, and these files will
* have tree-shaking applied.
*/
@get:Input
@get:Optional
var protoLibrary = false
@InputFiles
@Optional
fun getSourcePaths() = sourcePaths.toSet()
@InputFiles
@Optional
fun getSourceTrees() = sourceTrees.toSet()
@InputFiles
@Optional
fun getSourceJars() = sourceJars.toSet()
/**
* Source paths for local jars and directories, as well as remote binary dependencies
*/
// TODO(Benoit) Delete this because it seems unused? I think the DSL only pass down ProtoRootSet.
fun sourcePath(vararg sourcePaths: String) {
this.sourcePaths.addAll(sourcePaths)
}
/**
* Source paths for local file trees, backed by a [org.gradle.api.file.SourceDirectorySet]
* Must provide at least a [org.gradle.api.file.SourceDirectorySet.srcDir]
*/
fun sourcePath(action: Action<ProtoRootSet>) {
populateRootSets(action, sourceTrees, sourceJars, "source-tree")
}
@InputFiles
@Optional
fun getProtoPaths(): Set<String> {
return protoPaths
}
@InputFiles
@Optional
fun getProtoTrees(): Set<SourceDirectorySet> {
return protoTrees
}
@InputFiles
@Optional
fun getProtoJars(): Set<ProtoRootSet> {
return protoJars
}
/**
* Proto paths for local jars and directories, as well as remote binary dependencies
*/
fun protoPath(vararg protoPaths: String) {
this.protoPaths.addAll(protoPaths)
}
/**
* Proto paths for local file trees, backed by a [org.gradle.api.file.SourceDirectorySet]
* Must provide at least a [org.gradle.api.file.SourceDirectorySet.srcDir]
*/
fun protoPath(action: Action<ProtoRootSet>) {
populateRootSets(action, protoTrees, protoJars, "proto-tree")
}
private fun populateRootSets(
action: Action<ProtoRootSet>,
sourceTrees: MutableSet<SourceDirectorySet>,
sourceJars: MutableSet<ProtoRootSet>,
name: String
) {
val protoRootSet = objectFactory.newInstance(ProtoRootSet::class.java)
action.execute(protoRootSet)
protoRootSet.validate()
val hasSrcDirs = protoRootSet.srcDirs.isNotEmpty()
val hasSrcJar = protoRootSet.srcJar != null
val hasSrcJarAsExternalModuleDependency = protoRootSet.srcJarAsExternalModuleDependency != null
val hasSrcProjectDependency = protoRootSet.srcProjectDependency != null
val hasSrcProject = protoRootSet.srcProject != null
if (hasSrcDirs) {
// map to SourceDirectorySet which does the work for us!
val protoTree = objectFactory
.sourceDirectorySet(name, "Wire proto sources for $name.")
.srcDirs(protoRootSet.srcDirs)
protoRootSet.filters
.ifEmpty { listOf(Include("**/*.proto")) }
.forEach { it.act(protoTree.filter) }
sourceTrees.add(protoTree)
}
if (hasSrcJar || hasSrcJarAsExternalModuleDependency || hasSrcProject || hasSrcProjectDependency) {
sourceJars.add(protoRootSet)
}
}
fun java(action: Action<JavaOutput>) {
val javaOutput = objectFactory.newInstance(JavaOutput::class.java)
action.execute(javaOutput)
outputs += javaOutput
}
fun kotlin(action: Action<KotlinOutput>) {
val kotlinOutput = objectFactory.newInstance(KotlinOutput::class.java)
action.execute(kotlinOutput)
outputs += kotlinOutput
}
fun proto(action: Action<ProtoOutput>) {
val protoOutput = objectFactory.newInstance(ProtoOutput::class.java)
action.execute(protoOutput)
outputs += protoOutput
}
fun custom(action: Action<CustomOutput>) {
val customOutput = objectFactory.newInstance(CustomOutput::class.java)
action.execute(customOutput)
outputs += customOutput
}
fun move(action: Action<Move>) {
val move = objectFactory.newInstance(Move::class.java)
action.execute(move)
moves += move
}
// TODO(Benoit) See how we can make this class better, it's a mess and doesn't scale nicely.
open class ProtoRootSet {
val srcDirs = mutableListOf<String>()
var srcJar: String? = null
var srcProject: String? = null
var srcProjectDependency: DelegatingProjectDependency? = null
var srcJarAsExternalModuleDependency: Provider<MinimalExternalModuleDependency>? = null
val includes = mutableListOf<String>()
val excludes = mutableListOf<String>()
internal val filters: Collection<Filter>
get() = includes.map(::Include) + excludes.map(::Exclude)
fun srcDir(dir: String) {
srcDirs += dir
}
fun srcDirs(vararg dirs: String) {
srcDirs += dirs
}
fun srcJar(jar: String) {
srcJar = jar
}
fun srcJar(provider: Provider<MinimalExternalModuleDependency>) {
srcJarAsExternalModuleDependency = provider
}
fun srcJar(convertible: ProviderConvertible<MinimalExternalModuleDependency>) {
srcJar(convertible.asProvider())
}
fun srcProject(projectPath: String) {
srcProject = projectPath
}
fun srcProject(project: DelegatingProjectDependency) {
srcProjectDependency = project
}
fun include(vararg includePaths: String) {
includes += includePaths
}
fun exclude(vararg excludePaths: String) {
excludes += excludePaths
}
}
internal sealed class Filter(val glob: String) {
abstract fun act(filter: PatternFilterable)
}
internal class Exclude(glob: String) : Filter(glob) {
override fun act(filter: PatternFilterable) {
filter.exclude(glob)
}
}
internal class Include(glob: String) : Filter(glob) {
override fun act(filter: PatternFilterable) {
filter.include(glob)
}
}
}
private fun WireExtension.ProtoRootSet.validate() {
val sources = listOf(
srcDirs.isNotEmpty(),
srcJar != null,
srcJarAsExternalModuleDependency != null,
srcProjectDependency != null,
srcProject != null,
)
check(sources.count { it } <= 1) {
"Only one source can be set among srcDirs, srcJar, and srcProject within one sourcePath or protoPath closure."
}
}
| apache-2.0 | 3f1aac7d46c76c854cf04406dc76cf40 | 27.330383 | 114 | 0.711995 | 4.419696 | false | false | false | false |
Maccimo/intellij-community | platform/vcs-impl/src/com/intellij/openapi/vcs/changes/savedPatches/SavedPatchesEditorDiffPreview.kt | 2 | 1531 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.openapi.vcs.changes.savedPatches
import com.intellij.openapi.Disposable
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.vcs.changes.ui.ChangesTree
import com.intellij.openapi.vcs.changes.ui.SimpleTreeEditorDiffPreview
import com.intellij.openapi.wm.IdeFocusManager
import com.intellij.util.containers.isEmpty
import java.awt.Component
import javax.swing.JComponent
abstract class SavedPatchesEditorDiffPreview(diffProcessor: SavedPatchesDiffPreview, tree: ChangesTree, targetComponent: JComponent,
private val focusMainComponent: (Component?) -> Unit)
: SimpleTreeEditorDiffPreview(diffProcessor, tree, targetComponent, false) {
private var lastFocusOwner: Component? = null
init {
Disposer.register(diffProcessor, Disposable { lastFocusOwner = null })
}
override fun openPreview(requestFocus: Boolean): Boolean {
lastFocusOwner = IdeFocusManager.getInstance(project).focusOwner
return super.openPreview(requestFocus)
}
override fun returnFocusToTree() {
val focusOwner = lastFocusOwner
lastFocusOwner = null
focusMainComponent(focusOwner)
}
override fun updateDiffAction(event: AnActionEvent) {
event.presentation.isVisible = true
event.presentation.isEnabled = !changeViewProcessor.allChanges.isEmpty()
}
}
| apache-2.0 | 6f163549503e66346caf341555b98ea3 | 39.289474 | 132 | 0.779882 | 4.799373 | false | false | false | false |
bajdcc/jMiniLang | src/main/kotlin/com/bajdcc/LALR1/grammar/semantic/SemanticHandler.kt | 1 | 33158 | package com.bajdcc.LALR1.grammar.semantic
import com.bajdcc.LALR1.grammar.error.SemanticException.SemanticError
import com.bajdcc.LALR1.grammar.symbol.BlockType
import com.bajdcc.LALR1.grammar.symbol.IManageSymbol
import com.bajdcc.LALR1.grammar.symbol.IQuerySymbol
import com.bajdcc.LALR1.grammar.tree.*
import com.bajdcc.LALR1.grammar.type.TokenTools
import com.bajdcc.LALR1.semantic.token.IIndexedData
import com.bajdcc.LALR1.semantic.token.IRandomAccessOfTokens
import com.bajdcc.util.lexer.token.KeywordType
import com.bajdcc.util.lexer.token.OperatorType
import com.bajdcc.util.lexer.token.Token
import com.bajdcc.util.lexer.token.TokenType
import com.bajdcc.util.lexer.token.TokenType.ID
/**
* 【语义分析】语义处理器集合
*
* @author bajdcc
*/
class SemanticHandler {
/**
* 语义分析动作映射表
*/
private val semanticAnalyzier = mutableMapOf<String, ISemanticAnalyzer>()
/**
* 语义执行动作映射表
*/
private val semanticAction = mutableMapOf<String, ISemanticAction>()
init {
initializeAction()
initializeHandler()
}
/**
* 初始化动作
*/
private fun initializeAction() {
/* 进入块 */
semanticAction["do_enter_scope"] = object : ISemanticAction {
override fun handle(indexed: IIndexedData, manage: IManageSymbol, access: IRandomAccessOfTokens, recorder: ISemanticRecorder) {
manage.manageScopeService.enterScope()
}
}
/* 离开块 */
semanticAction["do_leave_scope"] = object : ISemanticAction {
override fun handle(indexed: IIndexedData, manage: IManageSymbol, access: IRandomAccessOfTokens, recorder: ISemanticRecorder) {
manage.manageScopeService.leaveScope()
}
}
/* 声明过程名 */
semanticAction["predeclear_funcname"] = object : ISemanticAction {
override fun handle(indexed: IIndexedData, manage: IManageSymbol, access: IRandomAccessOfTokens, recorder: ISemanticRecorder) {
val token = access.relativeGet(0)
val funcName = token.toRealString()
if (token.type === ID) {
if (manage.queryScopeService.entryName == funcName) {
recorder.add(SemanticError.DUP_ENTRY, token)
}
} else if (manage.queryScopeService.isRegisteredFunc(
funcName)) {
recorder.add(SemanticError.DUP_FUNCNAME, token)
}
val func = Func(token)
manage.manageScopeService.registerFunc(func)
if (token.type !== ID) {
token.obj = func.realName
token.type = ID
}
}
}
/* 声明变量名 */
semanticAction["declear_variable"] = object : ISemanticAction {
override fun handle(indexed: IIndexedData, manage: IManageSymbol, access: IRandomAccessOfTokens, recorder: ISemanticRecorder) {
val spec = access.relativeGet(-1).obj as KeywordType
val token = access.relativeGet(0)
val name = token.toRealString()
if (spec == KeywordType.VARIABLE) {
if (!manage.queryScopeService.findDeclaredSymbol(name)) {
if (!manage.queryScopeService.isRegisteredFunc(
name)) {
manage.manageScopeService.registerSymbol(name)
} else {
recorder.add(SemanticError.VAR_FUN_CONFLICT, token)
}
} else if (!TokenTools.isExternalName(name)
&& manage.queryScopeService
.findDeclaredSymbolDirect(name)) {
recorder.add(SemanticError.VARIABLE_REDECLARAED, token)
}
} else if (spec == KeywordType.LET) {
if (!manage.queryScopeService.findDeclaredSymbol(name)) {
recorder.add(SemanticError.VARIABLE_NOT_DECLARAED,
token)
}
}
}
}
/* 声明参数 */
semanticAction["declear_param"] = object : ISemanticAction {
override fun handle(indexed: IIndexedData, manage: IManageSymbol, access: IRandomAccessOfTokens, recorder: ISemanticRecorder) {
val token = access.relativeGet(0)
if (!manage.manageScopeService.registerFutureSymbol(
token.toRealString())) {
recorder.add(SemanticError.DUP_PARAM, token)
}
}
}
/* 清除参数 */
semanticAction["func_clearargs"] = object : ISemanticAction {
override fun handle(indexed: IIndexedData, manage: IManageSymbol, access: IRandomAccessOfTokens, recorder: ISemanticRecorder) {
manage.manageScopeService.clearFutureArgs()
val token = access.relativeGet(0)
val type = token.obj as KeywordType
if (type === KeywordType.YIELD) {
manage.queryBlockService.enterBlock(BlockType.kYield)
}
}
}
/* CATCH 清除参数 */
semanticAction["clear_catch"] = object : ISemanticAction {
override fun handle(indexed: IIndexedData, manage: IManageSymbol, access: IRandomAccessOfTokens, recorder: ISemanticRecorder) {
manage.manageScopeService.clearFutureArgs()
}
}
/* 循环体 */
semanticAction["do_enter_cycle"] = object : ISemanticAction {
override fun handle(indexed: IIndexedData, manage: IManageSymbol, access: IRandomAccessOfTokens, recorder: ISemanticRecorder) {
manage.queryBlockService.enterBlock(BlockType.kCycle)
}
}
/* 匿名函数处理 */
semanticAction["lambda"] = object : ISemanticAction {
override fun handle(indexed: IIndexedData, manage: IManageSymbol, access: IRandomAccessOfTokens, recorder: ISemanticRecorder) {
val token = access.relativeGet(0)
val func = Func(token)
manage.manageScopeService.registerLambda(func)
token.obj = func.realName
}
}
}
/**
* 初始化语义
*/
private fun initializeHandler() {
/* 复制 */
semanticAnalyzier["copy"] = object : ISemanticAnalyzer {
override fun handle(indexed: IIndexedData, query: IQuerySymbol, recorder: ISemanticRecorder): Any {
return indexed[0].obj!!
}
}
semanticAnalyzier["scope"] = object : ISemanticAnalyzer {
override fun handle(indexed: IIndexedData, query: IQuerySymbol, recorder: ISemanticRecorder): Any {
query.manageService.manageScopeService.leaveScope()
return indexed[0].obj!!
}
}
/* 表达式 */
semanticAnalyzier["exp"] = object : ISemanticAnalyzer {
override fun handle(indexed: IIndexedData, query: IQuerySymbol, recorder: ISemanticRecorder): Any {
if (indexed.exists(2)) {// 双目运算
val token = indexed[2].token
if (token!!.type === TokenType.OPERATOR) {
if (token!!.obj === OperatorType.DOT && indexed[0].obj is ExpInvokeProperty) {
val invoke = indexed[0].obj as ExpInvokeProperty
invoke.obj = indexed[1].toExp()
return invoke
} else if (TokenTools.isAssignment(token!!.obj as OperatorType)) {
if (indexed[1].obj is ExpBinop) {
val bin = indexed[1].obj as ExpBinop
if (bin.token.obj === OperatorType.DOT) {
val assign = ExpAssignProperty()
assign.setToken(token)
assign.obj = bin.leftOperand
assign.property = bin.rightOperand
assign.exp = indexed[0].toExp()
if (assign.property is ExpValue && assign.exp is ExpFunc) {
val v = assign.property as ExpValue
val f = assign.exp as ExpFunc
f.func!!.setMethodName(v.toString().replace("\"", ""))
}
return assign
}
} else if (indexed[1].obj is ExpIndex) {
val bin = indexed[1].obj as ExpIndex
val assign = ExpIndexAssign()
assign.setToken(token)
assign.exp = bin.exp
assign.index = bin.index
assign.obj = indexed[0].toExp()
return assign
}
}
}
val binop = ExpBinop(indexed[2].token!!)
binop.leftOperand = indexed[1].toExp()
binop.rightOperand = indexed[0].toExp()
return binop.simplify(recorder)
} else if (indexed.exists(3)) {// 单目运算
val token = indexed[3].token
if (token!!.type === TokenType.OPERATOR) {
if ((token!!.obj === OperatorType.PLUS_PLUS || token!!.obj === OperatorType.MINUS_MINUS) && indexed[1].obj is ExpBinop) {
val bin = indexed[1].obj as ExpBinop
if (bin.token.obj === OperatorType.DOT) {
val assign = ExpAssignProperty()
assign.setToken(token!!)
assign.obj = bin.leftOperand
assign.property = bin.rightOperand
return assign
}
}
}
val sinop = ExpSinop(indexed[3].token!!, indexed[1].toExp())
return sinop.simplify(recorder)
} else if (indexed.exists(4)) {// 三目运算
val triop = ExpTriop()
triop.firstToken = indexed[4].token
triop.secondToken = indexed[5].token
triop.firstOperand = indexed[0].toExp()
triop.secondOperand = indexed[6].toExp()
triop.thirdOperand = indexed[7].toExp()
return triop.simplify(recorder)
} else if (indexed.exists(5)) {
val exp = ExpIndex()
exp.exp = indexed[1].toExp()
exp.index = indexed[5].toExp()
return exp
} else if (!indexed.exists(10)) {
val obj = indexed[0].obj
if (obj is ExpValue) {
if (!obj.isConstant() && !query
.queryScopeService
.findDeclaredSymbol(
obj.token.toRealString())) {
recorder.add(SemanticError.VARIABLE_NOT_DECLARAED,
obj.token)
}
}
return obj!!
} else {
val token = indexed[10].token
val num = Token()
if (token!!.type === TokenType.INTEGER) {
val n = token!!.obj as Long
if (n > 0L) {
recorder.add(SemanticError.INVALID_OPERATOR,
token)
return indexed[0].obj!!
}
num.obj = -n
num.type = TokenType.INTEGER
} else {
val n = token!!.obj as Double
if (n > 0.0) {
recorder.add(SemanticError.INVALID_OPERATOR,
token)
return indexed[0].obj!!
}
num.obj = -n
num.type = TokenType.DECIMAL
}
val minus = Token()
minus.obj = OperatorType.MINUS
minus.type = TokenType.OPERATOR
minus.position = token.position
val binop = ExpBinop(minus)
binop.leftOperand = indexed[0].toExp()
num.position = token.position
num.position.column = num.position.column + 1
binop.rightOperand = ExpValue(num)
return binop.simplify(recorder)
}
}
}
/* 基本数据结构 */
semanticAnalyzier["type"] = object : ISemanticAnalyzer {
override fun handle(indexed: IIndexedData, query: IQuerySymbol, recorder: ISemanticRecorder): Any {
if (indexed.exists(1)) {
return indexed[1].obj!!
} else if (indexed.exists(2)) {
return indexed[2].obj!!
} else if (indexed.exists(3)) {
val token = indexed[0].token!!
if (token.type === ID) {
val invoke = ExpInvoke()
invoke.name = token
val func = query.queryScopeService.getFuncByName(
token.toRealString())
if (func == null) {
when {
TokenTools.isExternalName(token) -> invoke.extern = token
query.queryScopeService
.findDeclaredSymbol(token.toRealString()) -> {
invoke.extern = token
invoke.isInvoke = true
}
else -> recorder.add(SemanticError.MISSING_FUNCNAME, token)
}
} else {
invoke.func = func
}
if (indexed.exists(4)) {
invoke.params = indexed[4].toExps()
}
return invoke
} else {
val invoke = ExpInvokeProperty(token)
invoke.property = ExpValue(token)
if (indexed.exists(4)) {
invoke.params = indexed[4].toExps()
}
return invoke
}
} else {
val token = indexed[0].token!!
return ExpValue(token)
}
}
}
/* 入口 */
semanticAnalyzier["main"] = object : ISemanticAnalyzer {
override fun handle(indexed: IIndexedData, query: IQuerySymbol, recorder: ISemanticRecorder): Any {
val func = Func(query.queryScopeService.entryToken)
func.realName = func.name.toRealString()
val block = Block(indexed[0].toStmts())
block.stmts.add(StmtReturn())
func.block = block
return func
}
}
/* 块 */
semanticAnalyzier["block"] = object : ISemanticAnalyzer {
override fun handle(indexed: IIndexedData, query: IQuerySymbol, recorder: ISemanticRecorder): Any {
if (!indexed.exists(0)) {
return Block()
}
return Block(indexed[0].toStmts())
}
}
/* 语句集合 */
semanticAnalyzier["stmt_list"] = object : ISemanticAnalyzer {
override fun handle(indexed: IIndexedData, query: IQuerySymbol, recorder: ISemanticRecorder): Any {
val stmts = if (indexed.exists(1)) {
indexed[1].toStmts()
} else {
mutableListOf()
}
stmts.add(0, indexed[0].toStmt())
return stmts
}
}
/* 变量定义 */
semanticAnalyzier["var"] = object : ISemanticAnalyzer {
override fun handle(indexed: IIndexedData, query: IQuerySymbol, recorder: ISemanticRecorder): Any {
val assign = ExpAssign()
val token = indexed[0].token
assign.name = token
if (indexed.exists(11)) {
assign.isDecleared = true
}
if (indexed.exists(1)) {
val func = ExpFunc()
func.func = indexed[1].toFunc()
func.genClosure()
if (assign.isDecleared) {
val funcName = func.func!!.realName
if (!query.queryScopeService.isLambda(funcName) && funcName != token!!.toRealString()) {
recorder.add(SemanticError.DIFFERENT_FUNCNAME, token)
}
func.func!!.realName = token!!.toRealString()
}
assign.exp = func
} else if (indexed.exists(2)) {
assign.exp = indexed[2].toExp()
} else {
if (!assign.isDecleared) {
recorder.add(SemanticError.INVALID_ASSIGNMENT, token!!)
}
}
return assign
}
}
/* 属性设置 */
semanticAnalyzier["set"] = object : ISemanticAnalyzer {
override fun handle(indexed: IIndexedData, query: IQuerySymbol, recorder: ISemanticRecorder): Any {
val assign = ExpAssignProperty()
assign.obj = indexed[3].toExp()
assign.property = indexed[4].toExp()
assign.exp = indexed[2].toExp()
return assign
}
}
/* 调用表达式 */
semanticAnalyzier["call_exp"] = object : ISemanticAnalyzer {
override fun handle(indexed: IIndexedData, query: IQuerySymbol, recorder: ISemanticRecorder): Any {
val invoke = ExpInvoke()
if (indexed.exists(1)) {
val token = indexed[1].token
invoke.name = token
val func = query.queryScopeService.getFuncByName(
token!!.toRealString())
if (func == null) {
when {
TokenTools.isExternalName(token) -> invoke.extern = token
query.queryScopeService
.findDeclaredSymbol(token.toRealString()) -> {
invoke.extern = token
invoke.isInvoke = true
}
else -> recorder.add(SemanticError.MISSING_FUNCNAME, token)
}
} else {
invoke.func = func
}
} else if (indexed.exists(3)) {
invoke.invokeExp = indexed[3].toExp()
} else {
invoke.func = indexed[0].toFunc()
invoke.name = invoke.func!!.name
}
if (indexed.exists(2)) {
invoke.params = indexed[2].toExps()
}
return invoke
}
}
/* 类方法调用表达式 */
semanticAnalyzier["invoke"] = object : ISemanticAnalyzer {
override fun handle(indexed: IIndexedData, query: IQuerySymbol, recorder: ISemanticRecorder): Any {
val invoke = ExpInvokeProperty(indexed[0].token!!)
invoke.obj = indexed[1].toExp()
invoke.property = indexed[2].toExp()
if (indexed.exists(3)) {
invoke.params = indexed[3].toExps()
}
return invoke
}
}
/* 单词集合 */
semanticAnalyzier["token_list"] = object : ISemanticAnalyzer {
override fun handle(indexed: IIndexedData, query: IQuerySymbol, recorder: ISemanticRecorder): Any {
val tokens = if (indexed.exists(1)) {
indexed[1].toTokens()
} else {
mutableListOf()
}
tokens.add(0, indexed[0].token!!)
return tokens
}
}
/* 表达式集合 */
semanticAnalyzier["exp_list"] = object : ISemanticAnalyzer {
override fun handle(indexed: IIndexedData, query: IQuerySymbol, recorder: ISemanticRecorder): Any {
val exps = if (indexed.exists(1)) {
indexed[1].toExps()
} else {
mutableListOf()
}
exps.add(0, indexed[0].toExp())
return exps
}
}
/* 过程 */
semanticAnalyzier["func"] = object : ISemanticAnalyzer {
override fun handle(indexed: IIndexedData, query: IQuerySymbol, recorder: ISemanticRecorder): Any {
val token = indexed[1].token
val func = query.queryScopeService.getFuncByName(
token!!.toRealString())
if (!indexed.exists(10)) {
func!!.isYield = true
query.queryBlockService.leaveBlock(BlockType.kYield)
}
if (indexed.exists(2)) {
func!!.params = indexed[2].toTokens()
}
if (indexed.exists(0)) {
func!!.setDoc(indexed[0].toTokens())
}
val ret = StmtReturn()
if (func!!.isYield) {
ret.isYield = true
}
if (indexed.exists(3)) {
val stmts = mutableListOf<IStmt>()
ret.exp = indexed[3].toExp()
stmts.add(ret)
val block = Block(stmts)
func.block = block
} else {
val block = indexed[4].toBlock()
val stmts = block.stmts
if (func.isYield) {
if (stmts.isEmpty()) {
stmts.add(ret)
} else if (stmts[stmts.size - 1] is StmtReturn) {
val preRet = stmts[stmts.size - 1] as StmtReturn
if (preRet.exp != null) {
stmts.add(ret)
}
} else {
stmts.add(ret)
}
} else if (stmts.isEmpty() || stmts[stmts.size - 1] !is StmtReturn) {
stmts.add(ret)
}
func.block = block
}
return func
}
}
/* 匿名函数 */
semanticAnalyzier["lambda"] = object : ISemanticAnalyzer {
override fun handle(indexed: IIndexedData, query: IQuerySymbol, recorder: ISemanticRecorder): Any {
val token = indexed[1].token!!
val func = query.queryScopeService.lambda
func.name = token
if (indexed.exists(2)) {
func.params = indexed[2].toTokens()
}
val ret = StmtReturn()
if (indexed.exists(3)) {
val stmts = mutableListOf<IStmt>()
ret.exp = indexed[3].toExp()
stmts.add(ret)
val block = Block(stmts)
func.block = block
} else {
val block = indexed[4].toBlock()
val stmts = block.stmts
if (stmts.isEmpty() || stmts[stmts.size - 1] !is StmtReturn)
stmts.add(ret)
func.block = block
}
query.manageService.manageScopeService.clearFutureArgs()
val exp = ExpFunc()
exp.func = func
exp.genClosure()
return exp
}
}
/* 返回语句 */
semanticAnalyzier["return"] = object : ISemanticAnalyzer {
override fun handle(indexed: IIndexedData, query: IQuerySymbol, recorder: ISemanticRecorder): Any {
val ret = StmtReturn()
if (indexed.exists(0)) {
ret.exp = indexed[0].toExp()
}
if (query.queryBlockService.isInBlock(BlockType.kYield)) {
ret.isYield = true
}
return ret
}
}
/* 导入/导出 */
semanticAnalyzier["port"] = object : ISemanticAnalyzer {
override fun handle(indexed: IIndexedData, query: IQuerySymbol, recorder: ISemanticRecorder): Any {
val port = StmtPort()
val token = indexed[0].token
port.name = token
if (!indexed.exists(1)) {
port.isImported = false
val func = query.queryScopeService
.getFuncByName(token!!.obj!!.toString())
if (func == null) {
recorder.add(SemanticError.WRONG_EXTERN_SYMBOL, token)
} else {
func.isExtern = true
}
}
return port
}
}
/* 表达式语句 */
semanticAnalyzier["stmt_exp"] = object : ISemanticAnalyzer {
override fun handle(indexed: IIndexedData, query: IQuerySymbol, recorder: ISemanticRecorder): Any {
val exp = StmtExp()
if (indexed.exists(0)) {
exp.exp = indexed[0].toExp()
}
return exp
}
}
/* 条件语句 */
semanticAnalyzier["if"] = object : ISemanticAnalyzer {
override fun handle(indexed: IIndexedData, query: IQuerySymbol, recorder: ISemanticRecorder): Any {
val stmt = StmtIf()
stmt.exp = indexed[0].toExp()
stmt.trueBlock = indexed[1].toBlock()
if (indexed.exists(2)) {
stmt.falseBlock = indexed[2].toBlock()
} else if (indexed.exists(3)) {
val block = Block()
block.stmts.add(indexed[3].toStmt())
stmt.falseBlock = block
}
return stmt
}
}
/* 循环语句 */
semanticAnalyzier["for"] = object : ISemanticAnalyzer {
override fun handle(indexed: IIndexedData, query: IQuerySymbol, recorder: ISemanticRecorder): Any {
query.queryBlockService.leaveBlock(BlockType.kCycle)
val stmt = StmtFor()
if (indexed.exists(0)) {
stmt.variable = indexed[0].toExp()
}
if (indexed.exists(1)) {
stmt.cond = indexed[1].toExp()
}
if (indexed.exists(2)) {
stmt.ctrl = indexed[2].toExp()
}
stmt.block = indexed[3].toBlock()
return stmt
}
}
semanticAnalyzier["while"] = object : ISemanticAnalyzer {
override fun handle(indexed: IIndexedData, query: IQuerySymbol, recorder: ISemanticRecorder): Any {
query.queryBlockService.leaveBlock(BlockType.kCycle)
val stmt = StmtWhile()
stmt.cond = indexed[0].toExp()
stmt.block = indexed[1].toBlock()
return stmt
}
}
semanticAnalyzier["foreach"] = object : ISemanticAnalyzer {
override fun handle(indexed: IIndexedData, query: IQuerySymbol, recorder: ISemanticRecorder): Any {
query.queryBlockService.leaveBlock(BlockType.kCycle)
val stmt = StmtForeach()
stmt.variable = indexed[0].token
stmt.enumerator = indexed[1].toExp()
stmt.block = indexed[2].toBlock()
if (!stmt.enumerator!!.isEnumerable()) {
recorder.add(SemanticError.WRONG_ENUMERABLE, stmt.variable!!)
}
stmt.enumerator!!.setYield()
return stmt
}
}
/* 循环控制表达式 */
semanticAnalyzier["cycle"] = object : ISemanticAnalyzer {
override fun handle(indexed: IIndexedData, query: IQuerySymbol, recorder: ISemanticRecorder): Any {
val exp = ExpCycleCtrl()
if (indexed.exists(0)) {
exp.name = indexed[0].token
}
if (!query.queryBlockService.isInBlock(BlockType.kCycle)) {
recorder.add(SemanticError.WRONG_CYCLE, exp.name!!)
}
return exp
}
}
/* 块语句 */
semanticAnalyzier["block_stmt"] = object : ISemanticAnalyzer {
override fun handle(indexed: IIndexedData, query: IQuerySymbol, recorder: ISemanticRecorder): Any {
val block = StmtBlock()
block.block = indexed[0].toBlock()
return block
}
}
/* 数组 */
semanticAnalyzier["array"] = object : ISemanticAnalyzer {
override fun handle(indexed: IIndexedData, query: IQuerySymbol, recorder: ISemanticRecorder): Any {
val exp = ExpArray()
if (indexed.exists(0)) {
exp.setParams(indexed[0].toExps())
}
return exp
}
}
/* 字典 */
semanticAnalyzier["map_list"] = object : ISemanticAnalyzer {
override fun handle(indexed: IIndexedData, query: IQuerySymbol, recorder: ISemanticRecorder): Any {
val exps = if (indexed.exists(0)) {
indexed[0].toExps()
} else {
mutableListOf()
}
val binop = ExpBinop(indexed[3].token!!)
val value = ExpValue(indexed[1].token!!)
binop.leftOperand = value
binop.rightOperand = indexed[2].toExp()
exps.add(0, binop.simplify(recorder))
return exps
}
}
semanticAnalyzier["map"] = object : ISemanticAnalyzer {
override fun handle(indexed: IIndexedData, query: IQuerySymbol, recorder: ISemanticRecorder): Any {
val exp = ExpMap()
if (indexed.exists(0)) {
exp.params = indexed[0].toExps()
}
return exp
}
}
/* 异常处理 */
semanticAnalyzier["try"] = object : ISemanticAnalyzer {
override fun handle(indexed: IIndexedData, query: IQuerySymbol, recorder: ISemanticRecorder): Any {
val stmt = StmtTry(indexed[1].toBlock(), indexed[2].toBlock())
if (indexed.exists(0)) {
stmt.token = indexed[0].token
}
return stmt
}
}
semanticAnalyzier["throw"] = object : ISemanticAnalyzer {
override fun handle(indexed: IIndexedData, query: IQuerySymbol, recorder: ISemanticRecorder): Any =
StmtThrow(indexed[0].toExp())
}
}
/**
* 获得语义分析动作
*
* @param name 语义分析动作名称
* @return 语义分析动作
*/
fun getSemanticHandler(name: String): ISemanticAnalyzer {
return semanticAnalyzier[name]!!
}
/**
* 获得语义执行动作
*
* @param name 语义执行动作名称
* @return 语义执行动作
*/
fun getActionHandler(name: String): ISemanticAction {
return semanticAction[name]!!
}
}
| mit | 0a4c761fd637396592f651792f86638b | 43.194595 | 145 | 0.46979 | 5.665974 | false | false | false | false |
JStege1206/AdventOfCode | aoc-common/src/main/kotlin/nl/jstege/adventofcode/aoccommon/utils/machine/Program.kt | 1 | 3176 | package nl.jstege.adventofcode.aoccommon.utils.machine
/**
* Represents a Program, which is an iterable list of Instructions belonging to a machine.
* @author Jelle Stege
*/
class Program(
var instructions: MutableList<Instruction>,
val machine: Machine
) : Iterable<Instruction> {
init {
machine.program = this
}
/**
* The amount of instructions in this program.
*/
val size = instructions.size
/**
* Returns a [ProgramIterator], which iterates over the program. Do note that this iterator may
* have an infinite amount of elements due to jumping to previous instructions.
* @return The [ProgramIterator]
*/
override fun iterator(): Iterator<Instruction> {
return ProgramIterator()
}
/**
* An [Iterator] used to iterator over a [Program].
*/
inner class ProgramIterator : Iterator<Instruction> {
/**
* Returns the next [Instruction]
* @return The [Instruction]
*/
override fun next(): Instruction = instructions[machine.ir]
/**
* Checks whether there is a next [Instruction], this is the case when the [Machine]'s ir
* is larger than or equal to 0 and smaller than the [Program]'s size.
*/
override fun hasNext(): Boolean = machine.ir in (0..(size - 1))
}
companion object Assembler {
// /**
// * Assembles a List of Strings to a [Program].
// * @param rawInstructions A list of [Instruction] representations
// * @param machine The machine the resulting [Program] will belong to.
// * @param instructionParser The function that parses the given input to instructions.
// * @return A [Program] corresponding to the given list of [Instruction] representations
// */
// @JvmStatic fun assemble(rawInstructions: List<String>, machine: Machine,
// instructionParser: (List<String>) -> List<Instruction>) =
// Program(instructionParser(rawInstructions).map {
// it.machine = machine
// it
// }.toMutableList(), machine)
/**
* Assembles a List of Strings to a [Program]. Will also optimize the resulting program to
* run more efficiently.
* @param rawInstructions A list of [Instruction] representations
* @param machine The machine the resulting [Program] will belong to.
* @param instructionParser The function that parses the given input to instructions.
* @param optimizer The optimizer to use.
* @return A [Program] corresponding to the given list of [Instruction] representations
*/
@JvmStatic
fun assemble(
rawInstructions: List<String>, machine: Machine,
instructionParser: (List<String>) -> List<Instruction>,
optimizer: (MutableList<Instruction>) ->
MutableList<Instruction> = { it }
) =
Program(optimizer(instructionParser(rawInstructions)
.onEach { it.machine = machine }
.toMutableList()
), machine)
}
}
| mit | 95816b92fa867bbd3f98952548c67102 | 36.364706 | 99 | 0.61335 | 4.893683 | false | false | false | false |
KotlinNLP/SimpleDNN | src/main/kotlin/com/kotlinnlp/simplednn/deeplearning/sequenceencoder/FOFE.kt | 1 | 3311 | /* Copyright 2016-present The KotlinNLP Authors. All Rights Reserved.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, you can obtain one at http://mozilla.org/MPL/2.0/.
* ------------------------------------------------------------------*/
package com.kotlinnlp.simplednn.deeplearning.sequenceencoder
import com.kotlinnlp.simplednn.core.neuralprocessor.NeuralProcessor
import com.kotlinnlp.simplednn.core.optimizer.ParamsErrorsList
import com.kotlinnlp.simplednn.simplemath.ndarray.Shape
import com.kotlinnlp.simplednn.simplemath.ndarray.dense.DenseNDArray
import com.kotlinnlp.simplednn.simplemath.ndarray.dense.DenseNDArrayFactory
import kotlin.math.pow
/**
* Fixed-size Ordinally-Forgetting Encoding (Zhang et al., 2015b).
*
* @param alpha the forgetting factor (0 < α ≤ 0.5)
*/
class FOFE(
val alpha: Double,
override val id: Int = 0
) : NeuralProcessor<
List<DenseNDArray>, // InputType
List<DenseNDArray>, // OutputType
List<DenseNDArray>, // ErrorsType
List<DenseNDArray> // InputErrorsType
> {
companion object {
/**
* Build a T-order lower triangular matrix.
* Each row vector of the matrix represents a FOFE code of the partial sequence.
*/
private fun buildMatrix(alpha: Double, length: Int): DenseNDArray {
val matrix = DenseNDArrayFactory.zeros(Shape(length, length))
for (i in 0 until matrix.rows) {
for (j in 0 until matrix.columns) {
when {
i == j -> matrix[i, j] = 1.0
i >= j -> matrix[i, j] = alpha.pow(i - j)
else -> matrix[i, j] = 0.0
}
}
}
return matrix
}
}
/**
* TODO: write documentation
*/
override val propagateToInput: Boolean = true
/**
* TODO: write documentation
*/
private lateinit var matrix: DenseNDArray
/**
* TODO: write documentation
*/
private lateinit var inputErrors: List<DenseNDArray>
/**
* The Forward.
*
* @param input the input
*
* @return the result of the forward
*/
override fun forward(input: List<DenseNDArray>): List<DenseNDArray> {
val inputMatrix: DenseNDArray = DenseNDArrayFactory.fromRows(input)
this.matrix = buildMatrix(this.alpha, input.size)
return this.matrix.dot(inputMatrix).getRows().map { it.t }
}
/**
* The Backward.
*
* @param outputErrors the output errors
*/
override fun backward(outputErrors: List<DenseNDArray>) {
val errors: DenseNDArray = DenseNDArrayFactory.fromRows(outputErrors)
this.inputErrors = errors.dot(this.matrix.t).getRows().map { it.t }
}
/**
* Return the input errors of the last backward.
* Before calling this method make sure that [propagateToInput] is enabled.
*
* @param copy whether to return by value or by reference (default true)
*
* @return the input errors
*/
override fun getInputErrors(copy: Boolean): List<DenseNDArray> = this.inputErrors.map { if (copy) it.copy() else it }
/**
* @param copy a Boolean indicating whether the returned errors must be a copy or a reference
*
* @return the errors of the network parameters
*/
override fun getParamsErrors(copy: Boolean): ParamsErrorsList = emptyList()
}
| mpl-2.0 | 2ad018526e1dd448683d6c686f70e634 | 27.765217 | 119 | 0.666566 | 4.119552 | false | false | false | false |
alexander-schmidt/ihh | ihh-server/src/main/kotlin/com/asurasdevelopment/ihh/server/comparator/LeagueComparator.kt | 1 | 583 | package com.asurasdevelopment.ihh.server.comparator
import org.javers.core.JaversBuilder
import com.asurasdevelopment.ihh.server.persistence.dao.*
class LeagueComparator {
companion object {
private val javers = JaversBuilder.javers().build()
fun compareLeagues(working: League, base: League): LeagueChanges {
if (working.leagueData == null || base.leagueData == null) {
return LeagueChanges.empty()
}
val diff = javers.compare(working, base)
return LeagueChanges(diff.changes)
}
}
} | apache-2.0 | 342f92f259be16b0ece6334a90b74af7 | 29.736842 | 74 | 0.655232 | 4.318519 | false | false | false | false |
ACRA/acra | acra-http/src/main/java/org/acra/security/ProtocolSocketFactoryWrapper.kt | 1 | 2941 | /*
* Copyright (c) 2020
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.acra.security
import android.os.Build
import java.io.IOException
import java.net.InetAddress
import java.net.Socket
import java.net.UnknownHostException
import javax.net.ssl.SSLSocket
import javax.net.ssl.SSLSocketFactory
class ProtocolSocketFactoryWrapper(private val delegate: SSLSocketFactory, protocols: List<TLS>) : SSLSocketFactory() {
private val protocols: List<String>
init {
val list = protocols.toMutableList()
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) {
list.remove(TLS.V1_3)
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) {
list.remove(TLS.V1_2)
list.remove(TLS.V1_1)
}
}
this.protocols = list.map { it.id }
}
private fun setProtocols(socket: Socket): Socket {
if (socket is SSLSocket && isTLSServerEnabled(socket)) {
socket.enabledProtocols = protocols.toTypedArray()
}
return socket
}
private fun isTLSServerEnabled(sslSocket: SSLSocket): Boolean {
for (protocol in sslSocket.supportedProtocols) {
if (protocols.contains(protocol)) {
return true
}
}
return false
}
override fun getDefaultCipherSuites(): Array<String> = delegate.defaultCipherSuites
override fun getSupportedCipherSuites(): Array<String> = delegate.supportedCipherSuites
@Throws(IOException::class)
override fun createSocket(socket: Socket, s: String, i: Int, b: Boolean): Socket = setProtocols(delegate.createSocket(socket, s, i, b))
@Throws(IOException::class, UnknownHostException::class)
override fun createSocket(s: String, i: Int): Socket = setProtocols(delegate.createSocket(s, i))
@Throws(IOException::class, UnknownHostException::class)
override fun createSocket(s: String, i: Int, inetAddress: InetAddress, i1: Int): Socket = setProtocols(delegate.createSocket(s, i, inetAddress, i1))
@Throws(IOException::class)
override fun createSocket(inetAddress: InetAddress, i: Int): Socket = setProtocols(delegate.createSocket(inetAddress, i))
@Throws(IOException::class)
override fun createSocket(inetAddress: InetAddress, i: Int, inetAddress1: InetAddress, i1: Int): Socket = setProtocols(delegate.createSocket(inetAddress, i, inetAddress1, i1))
} | apache-2.0 | 0936eea6c0e9b282a416f3599c0f7e1d | 38.226667 | 179 | 0.700782 | 4.325 | false | false | false | false |
ktorio/ktor | ktor-shared/ktor-websockets/common/src/io/ktor/websocket/CloseReason.kt | 1 | 2251 | /*
* 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.websocket
import io.ktor.util.*
import kotlin.jvm.*
/**
* Websocket close reason
* @property code - close reason code as per RFC 6455, recommended to be one of [CloseReason.Codes]
* @property message - a close reason message, could be empty
*/
public data class CloseReason(val code: Short, val message: String) {
public constructor(code: Codes, message: String) : this(code.code, message)
/**
* An enum value for this [code] or `null` if the [code] is not listed in [Codes]
*/
val knownReason: Codes?
get() = Codes.byCode(code)
override fun toString(): String {
return "CloseReason(reason=${knownReason ?: code}, message=$message)"
}
/**
* Standard close reason codes
*
* see https://tools.ietf.org/html/rfc6455#section-7.4 for list of codes
*/
@Suppress("KDocMissingDocumentation")
public enum class Codes(public val code: Short) {
NORMAL(1000),
GOING_AWAY(1001),
PROTOCOL_ERROR(1002),
CANNOT_ACCEPT(1003),
@InternalAPI
@Deprecated("This code MUST NOT be set as a status code in a Close control frame by an endpoint")
CLOSED_ABNORMALLY(1006),
NOT_CONSISTENT(1007),
VIOLATED_POLICY(1008),
TOO_BIG(1009),
NO_EXTENSION(1010),
INTERNAL_ERROR(1011),
SERVICE_RESTART(1012),
TRY_AGAIN_LATER(1013);
public companion object {
private val byCodeMap = values().associateBy { it.code }
@Deprecated(
"Use INTERNAL_ERROR instead.",
ReplaceWith(
"INTERNAL_ERROR",
"io.ktor.websocket.CloseReason.Codes.INTERNAL_ERROR"
)
)
@JvmField
@Suppress("UNUSED")
public val UNEXPECTED_CONDITION: Codes = INTERNAL_ERROR
/**
* Get enum value by close reason code
* @return enum instance or null if [code] is not in standard
*/
public fun byCode(code: Short): Codes? = byCodeMap[code]
}
}
}
| apache-2.0 | 9c59fb0017883747a1ef2523e86aac03 | 30.263889 | 118 | 0.594402 | 4.271347 | false | false | false | false |
ktorio/ktor | ktor-io/posix/src/io/ktor/utils/io/bits/MemoryNative.kt | 1 | 9926 | @file:Suppress("NOTHING_TO_INLINE", "IntroduceWhenSubject")
package io.ktor.utils.io.bits
import io.ktor.utils.io.core.internal.*
import kotlinx.cinterop.*
import platform.posix.*
public actual class Memory constructor(
public val pointer: CPointer<ByteVar>,
public actual inline val size: Long
) {
init {
requirePositiveIndex(size, "size")
}
/**
* Size of memory range in bytes represented as signed 32bit integer
* @throws IllegalStateException when size doesn't fit into a signed 32bit integer
*/
public actual inline val size32: Int get() = size.toIntOrFail("size")
/**
* Returns byte at [index] position.
*/
public actual inline fun loadAt(index: Int): Byte = pointer[assertIndex(index, 1)]
/**
* Returns byte at [index] position.
*/
public actual inline fun loadAt(index: Long): Byte = pointer[assertIndex(index, 1)]
/**
* Write [value] at the specified [index].
*/
public actual inline fun storeAt(index: Int, value: Byte) {
pointer[assertIndex(index, 1)] = value
}
/**
* Write [value] at the specified [index]
*/
public actual inline fun storeAt(index: Long, value: Byte) {
pointer[assertIndex(index, 1)] = value
}
public actual fun slice(offset: Long, length: Long): Memory {
assertIndex(offset, length)
if (offset == 0L && length == size) {
return this
}
return Memory(pointer.plus(offset)!!, length)
}
public actual fun slice(offset: Int, length: Int): Memory {
assertIndex(offset, length)
if (offset == 0 && length.toLong() == size) {
return this
}
return Memory(pointer.plus(offset)!!, length.toLong())
}
/**
* Copies bytes from this memory range from the specified [offset] and [length]
* to the [destination] at [destinationOffset].
* Copying bytes from a memory to itself is allowed.
*/
@OptIn(UnsafeNumber::class)
public actual fun copyTo(destination: Memory, offset: Int, length: Int, destinationOffset: Int) {
require(offset >= 0) { "offset shouldn't be negative: $offset" }
require(length >= 0) { "length shouldn't be negative: $length" }
require(destinationOffset >= 0) { "destinationOffset shouldn't be negative: $destinationOffset" }
if (offset + length > size) {
throw IndexOutOfBoundsException("offset + length > size: $offset + $length > $size")
}
if (destinationOffset + length > destination.size) {
throw IndexOutOfBoundsException(
"dst offset + length > size: $destinationOffset + $length > ${destination.size}"
)
}
if (length == 0) return
memcpy(
destination.pointer + destinationOffset,
pointer + offset,
length.convert()
)
}
/**
* Copies bytes from this memory range from the specified [offset] and [length]
* to the [destination] at [destinationOffset].
* Copying bytes from a memory to itself is allowed.
*/
@OptIn(UnsafeNumber::class)
public actual fun copyTo(destination: Memory, offset: Long, length: Long, destinationOffset: Long) {
require(offset >= 0L) { "offset shouldn't be negative: $offset" }
require(length >= 0L) { "length shouldn't be negative: $length" }
require(destinationOffset >= 0L) { "destinationOffset shouldn't be negative: $destinationOffset" }
if (offset + length > size) {
throw IndexOutOfBoundsException("offset + length > size: $offset + $length > $size")
}
if (destinationOffset + length > destination.size) {
throw IndexOutOfBoundsException(
"dst offset + length > size: $destinationOffset + $length > ${destination.size}"
)
}
if (length == 0L) return
memcpy(
destination.pointer + destinationOffset,
pointer + offset,
length.convert()
)
}
public actual companion object {
public actual val Empty: Memory = Memory(nativeHeap.allocArray(0), 0L)
}
}
/**
* Copies bytes from this memory range from the specified [offset] and [length]
* to the [destination] at [destinationOffset].
*/
public actual fun Memory.copyTo(
destination: ByteArray,
offset: Int,
length: Int,
destinationOffset: Int
) {
if (destination.isEmpty() && destinationOffset == 0 && length == 0) {
// NOTE: this is required since pinned.getAddressOf(0) will crash with exception
return
}
destination.usePinned { pinned ->
copyTo(
destination = Memory(pinned.addressOf(0), destination.size.toLong()),
offset = offset,
length = length,
destinationOffset = destinationOffset
)
}
}
/**
* Copies bytes from this memory range from the specified [offset] and [length]
* to the [destination] at [destinationOffset].
*/
public actual fun Memory.copyTo(
destination: ByteArray,
offset: Long,
length: Int,
destinationOffset: Int
) {
if (destination.isEmpty() && destinationOffset == 0 && length == 0) {
// NOTE: this is required since pinned.getAddressOf(0) will crash with exception
return
}
destination.usePinned { pinned ->
copyTo(
destination = Memory(pinned.addressOf(0), destination.size.toLong()),
offset = offset,
length = length.toLong(),
destinationOffset = destinationOffset.toLong()
)
}
}
@PublishedApi
internal inline fun Memory.assertIndex(offset: Int, valueSize: Int): Int {
assert(offset in 0..size - valueSize) {
throw IndexOutOfBoundsException("offset $offset outside of range [0; ${size - valueSize})")
}
return offset
}
@PublishedApi
internal inline fun Memory.assertIndex(offset: Long, valueSize: Long): Long {
assert(offset in 0..size - valueSize) {
throw IndexOutOfBoundsException("offset $offset outside of range [0; ${size - valueSize})")
}
return offset
}
@PublishedApi
internal inline fun Short.toBigEndian(): Short {
return when {
!Platform.isLittleEndian -> this
else -> reverseByteOrder()
}
}
@PublishedApi
internal inline fun Int.toBigEndian(): Int = when {
!Platform.isLittleEndian -> this
else -> reverseByteOrder()
}
@PublishedApi
internal inline fun Long.toBigEndian(): Long = when {
!Platform.isLittleEndian -> this
else -> reverseByteOrder()
}
@PublishedApi
internal inline fun Float.toBigEndian(): Float = when {
!Platform.isLittleEndian -> this
else -> reverseByteOrder()
}
@PublishedApi
internal inline fun Double.toBigEndian(): Double = when {
!Platform.isLittleEndian -> this
else -> reverseByteOrder()
}
/**
* Fill memory range starting at the specified [offset] with [value] repeated [count] times.
*/
@OptIn(UnsafeNumber::class)
public actual fun Memory.fill(offset: Long, count: Long, value: Byte) {
requirePositiveIndex(offset, "offset")
requirePositiveIndex(count, "count")
requireRange(offset, count, size, "fill")
if (count.toULong() > size_t.MAX_VALUE.toULong()) {
throw IllegalArgumentException("count is too big: it shouldn't exceed size_t.MAX_VALUE")
}
memset(pointer + offset, value.toInt(), count.convert())
}
/**
* Fill memory range starting at the specified [offset] with [value] repeated [count] times.
*/
@OptIn(UnsafeNumber::class)
public actual fun Memory.fill(offset: Int, count: Int, value: Byte) {
requirePositiveIndex(offset, "offset")
requirePositiveIndex(count, "count")
requireRange(offset.toLong(), count.toLong(), size, "fill")
if (count.toULong() > size_t.MAX_VALUE.toULong()) {
throw IllegalArgumentException("count is too big: it shouldn't exceed size_t.MAX_VALUE")
}
memset(pointer + offset, value.toInt(), count.convert())
}
/**
* Copy content bytes to the memory addressed by the [destination] pointer with
* the specified [destinationOffset] in bytes.
*/
public fun Memory.copyTo(
destination: CPointer<ByteVar>,
offset: Int,
length: Int,
destinationOffset: Int
) {
copyTo(destination, offset.toLong(), length.toLong(), destinationOffset.toLong())
}
/**
* Copy content bytes to the memory addressed by the [destination] pointer with
* the specified [destinationOffset] in bytes.
*/
@OptIn(UnsafeNumber::class)
public fun Memory.copyTo(
destination: CPointer<ByteVar>,
offset: Long,
length: Long,
destinationOffset: Long
) {
requirePositiveIndex(offset, "offset")
requirePositiveIndex(length, "length")
requirePositiveIndex(destinationOffset, "destinationOffset")
requireRange(offset, length, size, "source memory")
memcpy(destination + destinationOffset, pointer + offset, length.convert())
}
/**
* Copy [length] bytes to the [destination] at the specified [destinationOffset]
* from the memory addressed by this pointer with [offset] in bytes.
*/
public fun CPointer<ByteVar>.copyTo(destination: Memory, offset: Int, length: Int, destinationOffset: Int) {
copyTo(destination, offset.toLong(), length.toLong(), destinationOffset.toLong())
}
/**
* Copy [length] bytes to the [destination] at the specified [destinationOffset]
* from the memory addressed by this pointer with [offset] in bytes.
*/
@OptIn(UnsafeNumber::class)
public fun CPointer<ByteVar>.copyTo(destination: Memory, offset: Long, length: Long, destinationOffset: Long) {
requirePositiveIndex(offset, "offset")
requirePositiveIndex(length, "length")
requirePositiveIndex(destinationOffset, "destinationOffset")
requireRange(destinationOffset, length, destination.size, "source memory")
memcpy(destination.pointer + destinationOffset, this + offset, length.convert())
}
| apache-2.0 | f48928bab58cb079249e6142ba218baa | 31.122977 | 111 | 0.656055 | 4.445141 | false | false | false | false |
jaycarey/ethtrader-ticker | src/main/java/org/ethtrader/ticker/Api.kt | 1 | 203639 | package org.ethtrader.ticker
import com.fasterxml.jackson.databind.DeserializationFeature
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.databind.PropertyNamingStrategy
import com.fasterxml.jackson.module.kotlin.KotlinModule
import com.fasterxml.jackson.module.kotlin.readValue
import org.glassfish.jersey.media.multipart.FormDataMultiPart
import org.glassfish.jersey.media.multipart.MultiPart
import org.glassfish.jersey.media.multipart.file.StreamDataBodyPart
import java.io.InputStream
import javax.ws.rs.client.Entity
import javax.ws.rs.core.MediaType
import javax.ws.rs.core.Response
data class JsonError(val error: Int)
internal fun List<String>?.csv(): String? =
this?.joinToString(",")
fun Array<out Pair<String, Any?>>.multipart(): Entity<MultiPart> =
Entity.entity(fold(FormDataMultiPart()) { multiPart, pair ->
when (pair.second) {
is InputStream ->
multiPart.bodyPart(StreamDataBodyPart(pair.first, pair.second as InputStream)) as FormDataMultiPart
else ->
multiPart.field (pair.first, pair.second.toString())
}
}, MediaType.MULTIPART_FORM_DATA)
private val objectMapper = ObjectMapper()
.registerModule(KotlinModule())
.setPropertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE)
.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)
private fun Response.getResponse(): ResponseWrapper {
val string = readEntity(String::class.java)
println(string)
try {
return objectMapper.readValue(string)
} catch (e: Throwable) {
val error: JsonError = objectMapper.readValue(string)
throw RuntimeException("Error Json Object returned, error code: ${error.error}", e)
}
}
data class ResponseWrapper(val kind: String?, val errors: List<String>?, val data: Map<String, Any?>?)
// Generated API start.
/*
* view code
* <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/apiv1/user.py#L57>
* # <https://www.reddit.com/dev/api#GET_api_v1_me>GET /api/v1/meidentity
* <https://github.com/reddit/reddit/wiki/OAuth2>
* - Returns the identity of the user currently authenticated via OAuth.
**/
fun OAuthClient.getV1Me() =
retry(3) { requestApi("/api/v1/me").get().getResponse() }
/*
* view code
* <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/apiv1/user.py#L106>
* # <https://www.reddit.com/dev/api#GET_api_v1_me_karma>GET /api/v1/me/karma
* mysubreddits <https://github.com/reddit/reddit/wiki/OAuth2>
* - Return a breakdown of subreddit karma.
**/
fun OAuthClient.getV1MeKarma() =
retry(3) { requestApi("/api/v1/me/karma").get().getResponse() }
/*
* view code
* <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/apiv1/user.py#L67>
* # <https://www.reddit.com/dev/api#GET_api_v1_me_prefs>GET /api/v1/me/prefs
* identity <https://github.com/reddit/reddit/wiki/OAuth2>
* - Return the preference settings of the logged in user
* - fieldsA comma-separated list of items from this set:
* - threaded_messages
* hide_downs
* email_messages
* show_link_flair
* creddit_autorenew
* show_trending
* private_feeds
* monitor_mentions
* research
* ignore_suggested_sort
* media
* clickgadget
* use_global_defaults
* label_nsfw
* domain_details
* show_stylesheets
* highlight_controversial
* no_profanity
* default_theme_sr
* lang
* hide_ups
* hide_from_robots
* compress
* store_visits
* threaded_modmail
* beta
* other_theme
* show_gold_expiration
* over_18
* enable_default_themes
* show_promote
* min_comment_score
* public_votes
* organic
* collapse_read_messages
* show_flair
* mark_messages_read
* hide_ads
* min_link_score
* newwindow
* numsites
* legacy_search
* num_comments
* highlight_new_comments
* default_comment_sort
* hide_locationbar
**/
fun OAuthClient.getV1MePrefs(fields: List<String>?) =
retry(3) { requestApi("/api/v1/me/prefs",
"fields" to fields.csv()).get().getResponse() }
/*
* view code
* <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/apiv1/user.py#L123>
* # <https://www.reddit.com/dev/api#PATCH_api_v1_me_prefs>PATCH /api/v1/me/prefs
* account <https://github.com/reddit/reddit/wiki/OAuth2>
* - This endpoint expects JSON data of this format{ "beta": boolean value,
* "clickgadget": boolean value, "collapse_read_messages": boolean value,
* "compress": boolean value, "creddit_autorenew": boolean value,
* "default_comment_sort": one of (`confidence`, `old`, `top`, `qa`,
* `controversial`, `new`), "domain_details": boolean value, "email_messages":
* boolean value, "enable_default_themes": boolean value, "hide_ads": boolean
* value, "hide_downs": boolean value, "hide_from_robots": boolean value,
* "hide_locationbar": boolean value, "hide_ups": boolean value,
* "highlight_controversial": boolean value, "highlight_new_comments": boolean
* value, "ignore_suggested_sort": boolean value, "label_nsfw": boolean value,
* "lang": a valid IETF language tag (underscore separated), "legacy_search":
* boolean value, "mark_messages_read": boolean value, "media": one of (`on`,
* `off`, `subreddit`), "min_comment_score": an integer between -100 and 100,
* "min_link_score": an integer between -100 and 100, "monitor_mentions": boolean
* value, "newwindow": boolean value, "no_profanity": boolean value,
* "num_comments": an integer between 1 and 500, "numsites": an integer between 1
* and 100, "organic": boolean value, "other_theme": subreddit name, "over_18":
* boolean value, "private_feeds": boolean value, "public_votes": boolean value,
* "research": boolean value, "show_flair": boolean value, "show_gold_expiration":
* boolean value, "show_link_flair": boolean value, "show_promote": boolean value,
* "show_stylesheets": boolean value, "show_trending": boolean value,
* "store_visits": boolean value, "theme_selector": subreddit name,
* "threaded_messages": boolean value, "threaded_modmail": boolean value,
* "use_global_defaults": boolean value, }
**/
fun OAuthClient.patchV1MePrefs(vararg urlParams: Pair<String, Any?>) =
retry(3) { requestApi("/api/v1/me/prefs").method("patch").getResponse() }
/*
* view code
* <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/apiv1/user.py#L94>
* # <https://www.reddit.com/dev/api#GET_api_v1_me_trophies>GET /api/v1/me/trophies
* identity <https://github.com/reddit/reddit/wiki/OAuth2>
* - Return a list of trophies for the current user.
**/
fun OAuthClient.getV1MeTrophies() =
retry(3) { requestApi("/api/v1/me/trophies").get().getResponse() }
/*
* view code
* <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/listingcontroller.py#L1818>
* # <https://www.reddit.com/dev/api#GET_prefs_{where}>GET /prefs/whereread
* <https://github.com/reddit/reddit/wiki/OAuth2>rss support
* <https://www.reddit.com/wiki/rss>
* * → /prefs/friends
* * → /prefs/blocked
* * → /api/v1/me/friends
* * → /api/v1/me/blockedThis endpoint is a listing
* <https://www.reddit.com/dev/api#listings>.
* - afterfullname <https://www.reddit.com/dev/api#fullnames> of a thing
* - beforefullname <https://www.reddit.com/dev/api#fullnames> of a thing
* - counta positive integer (default: 0)
* - limitthe maximum number of items desired (default: 25, maximum: 100)
* - show(optional) the string all
* - sr_detail(optional) expand subreddits
**/
fun OAuthClient.getPrefsWhere(where: String, after: String?, before: String?, count: Int?, limit: Int?, show: String?, srDetail: Boolean?) =
retry(3) { requestApi("/prefs/$where",
"after" to after,
"before" to before,
"count" to count,
"limit" to limit,
"show" to show,
"sr_detail" to srDetail).get().readEntity(String::class.java) }
/*
* view code
* <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/listingcontroller.py#L1818>
* # <https://www.reddit.com/dev/api#GET_prefs_{where}>GET /prefs/whereread
* <https://github.com/reddit/reddit/wiki/OAuth2>rss support
* <https://www.reddit.com/wiki/rss>
* * → /prefs/friends
* * → /prefs/blocked
* * → /api/v1/me/friends
* * → /api/v1/me/blockedThis endpoint is a listing
* <https://www.reddit.com/dev/api#listings>.
* - afterfullname <https://www.reddit.com/dev/api#fullnames> of a thing
* - beforefullname <https://www.reddit.com/dev/api#fullnames> of a thing
* - counta positive integer (default: 0)
* - limitthe maximum number of items desired (default: 25, maximum: 100)
* - show(optional) the string all
* - sr_detail(optional) expand subreddits
**/
fun OAuthClient.getPrefsFriends(after: String?, before: String?, count: Int?, limit: Int?, show: String?, srDetail: Boolean?) =
retry(3) { requestApi("/prefs/friends",
"after" to after,
"before" to before,
"count" to count,
"limit" to limit,
"show" to show,
"sr_detail" to srDetail).get().readEntity(String::class.java) }
/*
* view code
* <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/listingcontroller.py#L1818>
* # <https://www.reddit.com/dev/api#GET_prefs_{where}>GET /prefs/whereread
* <https://github.com/reddit/reddit/wiki/OAuth2>rss support
* <https://www.reddit.com/wiki/rss>
* * → /prefs/friends
* * → /prefs/blocked
* * → /api/v1/me/friends
* * → /api/v1/me/blockedThis endpoint is a listing
* <https://www.reddit.com/dev/api#listings>.
* - afterfullname <https://www.reddit.com/dev/api#fullnames> of a thing
* - beforefullname <https://www.reddit.com/dev/api#fullnames> of a thing
* - counta positive integer (default: 0)
* - limitthe maximum number of items desired (default: 25, maximum: 100)
* - show(optional) the string all
* - sr_detail(optional) expand subreddits
**/
fun OAuthClient.getPrefsBlocked(after: String?, before: String?, count: Int?, limit: Int?, show: String?, srDetail: Boolean?) =
retry(3) { requestApi("/prefs/blocked",
"after" to after,
"before" to before,
"count" to count,
"limit" to limit,
"show" to show,
"sr_detail" to srDetail).get().readEntity(String::class.java) }
/*
* view code
* <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/listingcontroller.py#L1818>
* # <https://www.reddit.com/dev/api#GET_prefs_{where}>GET /prefs/whereread
* <https://github.com/reddit/reddit/wiki/OAuth2>rss support
* <https://www.reddit.com/wiki/rss>
* * → /prefs/friends
* * → /prefs/blocked
* * → /api/v1/me/friends
* * → /api/v1/me/blockedThis endpoint is a listing
* <https://www.reddit.com/dev/api#listings>.
* - afterfullname <https://www.reddit.com/dev/api#fullnames> of a thing
* - beforefullname <https://www.reddit.com/dev/api#fullnames> of a thing
* - counta positive integer (default: 0)
* - limitthe maximum number of items desired (default: 25, maximum: 100)
* - show(optional) the string all
* - sr_detail(optional) expand subreddits
**/
fun OAuthClient.getV1MeFriends(after: String?, before: String?, count: Int?, limit: Int?, show: String?, srDetail: Boolean?) =
retry(3) { requestApi("/api/v1/me/friends",
"after" to after,
"before" to before,
"count" to count,
"limit" to limit,
"show" to show,
"sr_detail" to srDetail).get().getResponse() }
/*
* view code
* <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/listingcontroller.py#L1818>
* # <https://www.reddit.com/dev/api#GET_prefs_{where}>GET /prefs/whereread
* <https://github.com/reddit/reddit/wiki/OAuth2>rss support
* <https://www.reddit.com/wiki/rss>
* * → /prefs/friends
* * → /prefs/blocked
* * → /api/v1/me/friends
* * → /api/v1/me/blockedThis endpoint is a listing
* <https://www.reddit.com/dev/api#listings>.
* - afterfullname <https://www.reddit.com/dev/api#fullnames> of a thing
* - beforefullname <https://www.reddit.com/dev/api#fullnames> of a thing
* - counta positive integer (default: 0)
* - limitthe maximum number of items desired (default: 25, maximum: 100)
* - show(optional) the string all
* - sr_detail(optional) expand subreddits
**/
fun OAuthClient.getV1MeBlocked(after: String?, before: String?, count: Int?, limit: Int?, show: String?, srDetail: Boolean?) =
retry(3) { requestApi("/api/v1/me/blocked",
"after" to after,
"before" to before,
"count" to count,
"limit" to limit,
"show" to show,
"sr_detail" to srDetail).get().getResponse() }
/*
* view code
* <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/api.py#L335>#
* <https://www.reddit.com/dev/api#GET_api_needs_captcha>GET /api/needs_captchaany
* <https://github.com/reddit/reddit/wiki/OAuth2>
* - Check whether CAPTCHAs are needed for API methods that define the "captcha"
* and "iden" parameters.
**/
fun OAuthClient.getNeeds_captcha() =
retry(3) { requestApi("/api/needs_captcha").get().getResponse() }
/*
* view code
* <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/api.py#L145>#
* <https://www.reddit.com/dev/api#POST_api_new_captcha>POST /api/new_captchaany
* <https://github.com/reddit/reddit/wiki/OAuth2>
* - Responds with an iden of a new CAPTCHA.
* - Use this endpoint if a user cannot read a given CAPTCHA, and wishes to
* receive a new CAPTCHA.
* - To request the CAPTCHA image for an iden, use /captcha/iden
* <https://www.reddit.com/dev/api#GET_captcha_%7Biden%7D>.
* - api_typethe string json
**/
fun OAuthClient.postNew_captcha(vararg urlParams: Pair<String, Any?>) =
retry(3) { requestApi("/api/new_captcha").post(urlParams.multipart()).getResponse() }
/*
* view code
* <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/captcha.py#L32>#
* <https://www.reddit.com/dev/api#GET_captcha_{iden}>GET /captcha/idenany
* <https://github.com/reddit/reddit/wiki/OAuth2>
* - Request a CAPTCHA image given an iden.
* - An iden is given as the captcha field with a BAD_CAPTCHA error, you should
* use this endpoint if you get aBAD_CAPTCHA error response.
* - Responds with a 120x50 image/png which should be displayed to the user.
* - The user's response to the CAPTCHA should be sent as captcha along with your
* request.
* - To request a new CAPTCHA, use /api/new_captcha
* <https://www.reddit.com/dev/api#POST_api_new_captcha>.
**/
fun OAuthClient.getCaptchaIden(iden: String) =
retry(3) { requestApi("/captcha/$iden").get().readEntity(String::class.java) }
/*
* view code
* <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/api.py#L4280>#
* <https://www.reddit.com/dev/api#POST_api_clearflairtemplates>POST [/r/subreddit
* ]/api/clearflairtemplatesmodflair <https://github.com/reddit/reddit/wiki/OAuth2>
* - api_typethe string json
* - flair_typeone of (USER_FLAIR, LINK_FLAIR)
* - uh / X-Modhash headera modhash <https://www.reddit.com/dev/api#modhashes>
**/
fun OAuthClient.postRSubredditClearflairtemplates(subreddit: String, vararg urlParams: Pair<String, Any?>) =
retry(3) { requestApi("/r/$subreddit/api/clearflairtemplates").post(urlParams.multipart()).readEntity(String::class.java) }
/*
* view code
* <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/api.py#L4022>#
* <https://www.reddit.com/dev/api#POST_api_deleteflair>POST [/r/subreddit
* ]/api/deleteflairmodflair <https://github.com/reddit/reddit/wiki/OAuth2>
* - api_typethe string json
* - namea user by name
* - uh / X-Modhash headera modhash <https://www.reddit.com/dev/api#modhashes>
**/
fun OAuthClient.postRSubredditDeleteflair(subreddit: String, vararg urlParams: Pair<String, Any?>) =
retry(3) { requestApi("/r/$subreddit/api/deleteflair").post(urlParams.multipart()).readEntity(String::class.java) }
/*
* view code
* <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/api.py#L4261>#
* <https://www.reddit.com/dev/api#POST_api_deleteflairtemplate>POST [/r/subreddit
* ]/api/deleteflairtemplatemodflair <https://github.com/reddit/reddit/wiki/OAuth2>
* - api_typethe string json
* - flair_template_iduh / X-Modhash headera modhash
* <https://www.reddit.com/dev/api#modhashes>
**/
fun OAuthClient.postRSubredditDeleteflairtemplate(subreddit: String, vararg urlParams: Pair<String, Any?>) =
retry(3) { requestApi("/r/$subreddit/api/deleteflairtemplate").post(urlParams.multipart()).readEntity(String::class.java) }
/*
* view code
* <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/api.py#L3968>#
* <https://www.reddit.com/dev/api#POST_api_flair>POST [/r/subreddit]/api/flair
* modflair <https://github.com/reddit/reddit/wiki/OAuth2>
* - api_typethe string json
* - css_classa valid subreddit image name
* - linka fullname <https://www.reddit.com/dev/api#fullname> of a link
* - namea user by name
* - texta string no longer than 64 characters
* - uh / X-Modhash headera modhash <https://www.reddit.com/dev/api#modhashes>
**/
fun OAuthClient.postRSubredditFlair(subreddit: String, vararg urlParams: Pair<String, Any?>) =
retry(3) { requestApi("/r/$subreddit/api/flair").post(urlParams.multipart()).readEntity(String::class.java) }
/*
* view code
* <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/api.py#L4127>#
* <https://www.reddit.com/dev/api#POST_api_flairconfig>POST [/r/subreddit
* ]/api/flairconfigmodflair <https://github.com/reddit/reddit/wiki/OAuth2>
* - api_typethe string json
* - flair_enabledboolean value
* - flair_positionone of (left, right)
* - flair_self_assign_enabledboolean value
* - link_flair_positionone of (`,left,right`)
* - link_flair_self_assign_enabledboolean value
* - uh / X-Modhash headera modhash <https://www.reddit.com/dev/api#modhashes>
**/
fun OAuthClient.postRSubredditFlairconfig(subreddit: String, vararg urlParams: Pair<String, Any?>) =
retry(3) { requestApi("/r/$subreddit/api/flairconfig").post(urlParams.multipart()).readEntity(String::class.java) }
/*
* view code
* <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/api.py#L4042>#
* <https://www.reddit.com/dev/api#POST_api_flaircsv>POST [/r/subreddit
* ]/api/flaircsvmodflair <https://github.com/reddit/reddit/wiki/OAuth2>
* - Change the flair of multiple users in the same subreddit with a single API
* call.
* - Requires a string 'flair_csv' which has up to 100 lines of the form 'user,
* flairtext,cssclass' (Lines beyond the 100th are ignored).
* - If both cssclass and flairtext are the empty string for a given user, instead
* clears that user's flair.
* - Returns an array of objects indicating if each flair setting was applied, or
* a reason for the failure.
* - flair_csvcomma-seperated flair information
* - uh / X-Modhash headera modhash <https://www.reddit.com/dev/api#modhashes>
**/
fun OAuthClient.postRSubredditFlaircsv(subreddit: String, vararg urlParams: Pair<String, Any?>) =
retry(3) { requestApi("/r/$subreddit/api/flaircsv").post(urlParams.multipart()).readEntity(String::class.java) }
/*
* view code
* <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/api.py#L4169>#
* <https://www.reddit.com/dev/api#GET_api_flairlist>GET [/r/subreddit
* ]/api/flairlistmodflair <https://github.com/reddit/reddit/wiki/OAuth2>
* - This endpoint is a listing <https://www.reddit.com/dev/api#listings>.
* - afterfullname <https://www.reddit.com/dev/api#fullnames> of a thing
* - beforefullname <https://www.reddit.com/dev/api#fullnames> of a thing
* - counta positive integer (default: 0)
* - limitthe maximum number of items desired (default: 25, maximum: 1000)
* - namea user by name
* - show(optional) the string all
* - sr_detail(optional) expand subreddits
**/
fun OAuthClient.getRSubredditFlairlist(subreddit: String, after: String?, before: String?, count: Int?, limit: Int?, name: String?, show: String?, srDetail: Boolean?) =
retry(3) { requestApi("/r/$subreddit/api/flairlist",
"after" to after,
"before" to before,
"count" to count,
"limit" to limit,
"name" to name,
"show" to show,
"sr_detail" to srDetail).get().readEntity(String::class.java) }
/*
* view code
* <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/api.py#L4295>#
* <https://www.reddit.com/dev/api#POST_api_flairselector>POST [/r/subreddit
* ]/api/flairselectorflair <https://github.com/reddit/reddit/wiki/OAuth2>
* - Return information about a users's flair options.
* - If link is given, return link flair options. Otherwise, return user flair
* options for this subreddit.
* - The logged in user's flair is also returned. Subreddit moderators may give a
* user byname to instead retrieve that user's flair.
* - linka fullname <https://www.reddit.com/dev/api#fullname> of a link
* - namea user by name
**/
fun OAuthClient.postRSubredditFlairselector(subreddit: String, vararg urlParams: Pair<String, Any?>) =
retry(3) { requestApi("/r/$subreddit/api/flairselector").post(urlParams.multipart()).readEntity(String::class.java) }
/*
* view code
* <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/api.py#L4187>#
* <https://www.reddit.com/dev/api#POST_api_flairtemplate>POST [/r/subreddit
* ]/api/flairtemplatemodflair <https://github.com/reddit/reddit/wiki/OAuth2>
* - api_typethe string json
* - css_classa valid subreddit image name
* - flair_template_idflair_typeone of (USER_FLAIR, LINK_FLAIR)
* - texta string no longer than 64 characters
* - text_editableboolean value
* - uh / X-Modhash headera modhash <https://www.reddit.com/dev/api#modhashes>
**/
fun OAuthClient.postRSubredditFlairtemplate(subreddit: String, vararg urlParams: Pair<String, Any?>) =
retry(3) { requestApi("/r/$subreddit/api/flairtemplate").post(urlParams.multipart()).readEntity(String::class.java) }
/*
* view code
* <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/api.py#L4341>#
* <https://www.reddit.com/dev/api#POST_api_selectflair>POST [/r/subreddit
* ]/api/selectflairflair <https://github.com/reddit/reddit/wiki/OAuth2>
* - api_typethe string json
* - flair_template_idlinka fullname <https://www.reddit.com/dev/api#fullname> of
* a link
* - namea user by name
* - texta string no longer than 64 characters
* - uh / X-Modhash headera modhash <https://www.reddit.com/dev/api#modhashes>
**/
fun OAuthClient.postRSubredditSelectflair(subreddit: String, vararg urlParams: Pair<String, Any?>) =
retry(3) { requestApi("/r/$subreddit/api/selectflair").post(urlParams.multipart()).readEntity(String::class.java) }
/*
* view code
* <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/api.py#L4117>#
* <https://www.reddit.com/dev/api#POST_api_setflairenabled>POST [/r/subreddit
* ]/api/setflairenabledflair <https://github.com/reddit/reddit/wiki/OAuth2>
* - api_typethe string json
* - flair_enabledboolean value
* - uh / X-Modhash headera modhash <https://www.reddit.com/dev/api#modhashes>
**/
fun OAuthClient.postRSubredditSetflairenabled(subreddit: String, vararg urlParams: Pair<String, Any?>) =
retry(3) { requestApi("/r/$subreddit/api/setflairenabled").post(urlParams.multipart()).readEntity(String::class.java) }
/*
* view code
* <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/apiv1/gold.py#L77>
* # <https://www.reddit.com/dev/api#POST_api_v1_gold_gild_{fullname}>POST
* /api/v1/gold/gild/fullnamecreddits
* <https://github.com/reddit/reddit/wiki/OAuth2>
* - fullnamefullname <https://www.reddit.com/dev/api#fullnames> of a thing
**/
fun OAuthClient.postV1GoldGildFullname(fullname: String, vararg urlParams: Pair<String, Any?>) =
retry(3) { requestApi("/api/v1/gold/gild/$fullname").post(urlParams.multipart()).getResponse() }
/*
* view code
* <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/apiv1/gold.py#L102>
* # <https://www.reddit.com/dev/api#POST_api_v1_gold_give_{username}>POST
* /api/v1/gold/give/usernamecreddits
* <https://github.com/reddit/reddit/wiki/OAuth2>
* - monthsan integer between 1 and 36
* - usernameA valid, existing reddit username
**/
fun OAuthClient.postV1GoldGiveUsername(username: String, vararg urlParams: Pair<String, Any?>) =
retry(3) { requestApi("/api/v1/gold/give/$username").post(urlParams.multipart()).getResponse() }
/*
* view code
* <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/api.py#L2060>#
* <https://www.reddit.com/dev/api#POST_api_comment>POST /api/commentany
* <https://github.com/reddit/reddit/wiki/OAuth2>
* - Submit a new comment or reply to a message.
* - parent is the fullname of the thing being replied to. Its value changes the
* kind of object created by this request:
* * the fullname of a Link: a top-level comment in that Link's thread. (requires
* submit scope)
* * the fullname of a Comment: a comment reply to that comment. (requires submit
* scope)
* * the fullname of a Message: a message reply to that message. (requires
* privatemessages scope) text should be the raw markdown body of the comment or
* message.
* - To start a new message thread, use /api/compose
* <https://www.reddit.com/dev/api#POST_api_compose>.
* - api_typethe string json
* - textraw markdown text
* - thing_idfullname <https://www.reddit.com/dev/api#fullnames> of parent thing
* - uh / X-Modhash headera modhash <https://www.reddit.com/dev/api#modhashes>
**/
fun OAuthClient.postComment(vararg urlParams: Pair<String, Any?>) =
retry(3) { requestApi("/api/comment").post(urlParams.multipart()).getResponse() }
/*
* view code
* <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/api.py#L1491>#
* <https://www.reddit.com/dev/api#POST_api_del>POST /api/deledit
* <https://github.com/reddit/reddit/wiki/OAuth2>
* - Delete a Link or Comment.
* - idfullname <https://www.reddit.com/dev/api#fullnames> of a thing created by
* the user
* - uh / X-Modhash headera modhash <https://www.reddit.com/dev/api#modhashes>
**/
fun OAuthClient.postDel(vararg urlParams: Pair<String, Any?>) =
retry(3) { requestApi("/api/del").post(urlParams.multipart()).getResponse() }
/*
* view code
* <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/api.py#L1975>#
* <https://www.reddit.com/dev/api#POST_api_editusertext>POST /api/editusertextedit
* <https://github.com/reddit/reddit/wiki/OAuth2>
* - Edit the body text of a comment or self-post.
* - api_typethe string json
* - textraw markdown text
* - thing_idfullname <https://www.reddit.com/dev/api#fullnames> of a thing
* created by the user
* - uh / X-Modhash headera modhash <https://www.reddit.com/dev/api#modhashes>
**/
fun OAuthClient.postEditusertext(vararg urlParams: Pair<String, Any?>) =
retry(3) { requestApi("/api/editusertext").post(urlParams.multipart()).getResponse() }
/*
* view code
* <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/api.py#L3472>#
* <https://www.reddit.com/dev/api#POST_api_hide>POST /api/hidereport
* <https://github.com/reddit/reddit/wiki/OAuth2>
* - Hide a link.
* - This removes it from the user's default view of subreddit listings.
* - See also: /api/unhide <https://www.reddit.com/dev/api#POST_api_unhide>.
* - idA comma-separated list of link fullnames
* <https://www.reddit.com/dev/api#fullnames>
* - uh / X-Modhash headera modhash <https://www.reddit.com/dev/api#modhashes>
**/
fun OAuthClient.postHide(vararg urlParams: Pair<String, Any?>) =
retry(3) { requestApi("/api/hide").post(urlParams.multipart()).getResponse() }
/*
* view code
* <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/api.py#L173>#
* <https://www.reddit.com/dev/api#GET_api_info>GET [/r/subreddit]/api/inforead
* <https://github.com/reddit/reddit/wiki/OAuth2>
* - Return a listing of things specified by their fullnames.
* - Only Links, Comments, and Subreddits are allowed.
* - idA comma-separated list of thing fullnames
* <https://www.reddit.com/dev/api#fullnames>
* - urla valid URL
**/
fun OAuthClient.getRSubredditInfo(subreddit: String, id: List<String>?, url: String?) =
retry(3) { requestApi("/r/$subreddit/api/info",
"id" to id.csv(),
"url" to url).get().readEntity(String::class.java) }
/*
* view code
* <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/api.py#L1522>#
* <https://www.reddit.com/dev/api#POST_api_lock>POST /api/lockmodposts
* <https://github.com/reddit/reddit/wiki/OAuth2>
* - Lock a link.
* - Prevents a post from receiving new comments.
* - See also: /api/unlock <https://www.reddit.com/dev/api#POST_api_unlock>.
* - idfullname <https://www.reddit.com/dev/api#fullnames> of a link
* - uh / X-Modhash headera modhash <https://www.reddit.com/dev/api#modhashes>
**/
fun OAuthClient.postLock(vararg urlParams: Pair<String, Any?>) =
retry(3) { requestApi("/api/lock").post(urlParams.multipart()).getResponse() }
/*
* view code
* <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/api.py#L1568>#
* <https://www.reddit.com/dev/api#POST_api_marknsfw>POST /api/marknsfwmodposts
* <https://github.com/reddit/reddit/wiki/OAuth2>
* - Mark a link NSFW.
* - See also: /api/unmarknsfw <https://www.reddit.com/dev/api#POST_api_unmarknsfw>
* .
* - idfullname <https://www.reddit.com/dev/api#fullnames> of a thing
* - uh / X-Modhash headera modhash <https://www.reddit.com/dev/api#modhashes>
**/
fun OAuthClient.postMarknsfw(vararg urlParams: Pair<String, Any?>) =
retry(3) { requestApi("/api/marknsfw").post(urlParams.multipart()).getResponse() }
/*
* view code
* <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/api.py#L3535>#
* <https://www.reddit.com/dev/api#GET_api_morechildren>GET /api/morechildrenread
* <https://github.com/reddit/reddit/wiki/OAuth2>
* - Retrieve additional comments omitted from a base comment tree.
* - When a comment tree is rendered, the most relevant comments are selected for
* display first. Remaining comments are stubbed out with "MoreComments" links.
* This API call is used to retrieve the additional comments represented by those
* stubs, up to 20 at a time.
* - The two core parameters required are link and children. link is the fullname
* of the link whose comments are being fetched.children is a comma-delimited list
* of comment ID36s that need to be fetched.
* - If id is passed, it should be the ID of the MoreComments object this call is
* replacing. This is needed only for the HTML UI's purposes and is optional
* otherwise.
* - NOTE: you may only make one request at a time to this API endpoint. Higher
* concurrency will result in an error being returned.
* - api_typethe string json
* - childrena comma-delimited list of comment ID36s
* - id(optional) id of the associated MoreChildren object
* - link_idfullname <https://www.reddit.com/dev/api#fullnames> of a thing
* - sortone of (confidence, top, new, controversial, old, random, qa)
**/
fun OAuthClient.getMorechildren(apiType: String?, children: List<String>?, id: String?, linkId: String?, sort: String?) =
retry(3) { requestApi("/api/morechildren",
"api_type" to apiType,
"children" to children.csv(),
"id" to id,
"link_id" to linkId,
"sort" to sort).get().getResponse() }
/*
* view code
* <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/api.py#L1749>#
* <https://www.reddit.com/dev/api#POST_api_report>POST /api/reportreport
* <https://github.com/reddit/reddit/wiki/OAuth2>
* - Report a link, comment or message.
* - Reporting a thing brings it to the attention of the subreddit's moderators.
* Reporting a message sends it to a system for admin review.
* - For links and comments, the thing is implicitly hidden as well (see /api/hide
* <https://www.reddit.com/dev/api#POST_api_hide> for details).
* - api_typethe string json
* - other_reasona string no longer than 100 characters
* - reasona string no longer than 100 characters
* - site_reasona string no longer than 100 characters
* - thing_idfullname <https://www.reddit.com/dev/api#fullnames> of a thing
* - uh / X-Modhash headera modhash <https://www.reddit.com/dev/api#modhashes>
**/
fun OAuthClient.postReport(vararg urlParams: Pair<String, Any?>) =
retry(3) { requestApi("/api/report").post(urlParams.multipart()).getResponse() }
/*
* view code
* <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/api.py#L3340>#
* <https://www.reddit.com/dev/api#POST_api_save>POST /api/savesave
* <https://github.com/reddit/reddit/wiki/OAuth2>
* - Save a link or comment.
* - Saved things are kept in the user's saved listing for later perusal.
* - See also: /api/unsave <https://www.reddit.com/dev/api#POST_api_unsave>.
* - categorya category name
* - idfullname <https://www.reddit.com/dev/api#fullnames> of a thing
* - uh / X-Modhash headera modhash <https://www.reddit.com/dev/api#modhashes>
**/
fun OAuthClient.postSave(vararg urlParams: Pair<String, Any?>) =
retry(3) { requestApi("/api/save").post(urlParams.multipart()).getResponse() }
/*
* view code
* <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/api.py#L3323>#
* <https://www.reddit.com/dev/api#GET_api_saved_categories>GET
* /api/saved_categoriessave <https://github.com/reddit/reddit/wiki/OAuth2>
* - Get a list of categories in which things are currently saved.
* - See also: /api/save <https://www.reddit.com/dev/api#POST_api_save>.
**/
fun OAuthClient.getSaved_categories() =
retry(3) { requestApi("/api/saved_categories").get().getResponse() }
/*
* view code
* <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/api.py#L1619>#
* <https://www.reddit.com/dev/api#POST_api_sendreplies>POST /api/sendrepliesedit
* <https://github.com/reddit/reddit/wiki/OAuth2>
* - Enable or disable inbox replies for a link or comment.
* - state is a boolean that indicates whether you are enabling or disabling inbox
* replies - true to enable, false to disable.
* - idfullname <https://www.reddit.com/dev/api#fullnames> of a thing created by
* the user
* - stateboolean value
* - uh / X-Modhash headera modhash <https://www.reddit.com/dev/api#modhashes>
**/
fun OAuthClient.postSendreplies(vararg urlParams: Pair<String, Any?>) =
retry(3) { requestApi("/api/sendreplies").post(urlParams.multipart()).getResponse() }
/*
* view code
* <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/api.py#L1680>#
* <https://www.reddit.com/dev/api#POST_api_set_contest_mode>POST
* /api/set_contest_modemodposts <https://github.com/reddit/reddit/wiki/OAuth2>
* - Set or unset "contest mode" for a link's comments.
* - state is a boolean that indicates whether you are enabling or disabling
* contest mode - true to enable, false to disable.
* - api_typethe string json
* - idstateboolean value
* - uh / X-Modhash headera modhash <https://www.reddit.com/dev/api#modhashes>
**/
fun OAuthClient.postSet_contest_mode(vararg urlParams: Pair<String, Any?>) =
retry(3) { requestApi("/api/set_contest_mode").post(urlParams.multipart()).getResponse() }
/*
* view code
* <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/api.py#L1706>#
* <https://www.reddit.com/dev/api#POST_api_set_subreddit_sticky>POST
* /api/set_subreddit_stickymodposts <https://github.com/reddit/reddit/wiki/OAuth2>
* - Set or unset a Link as the sticky in its subreddit.
* - state is a boolean that indicates whether to sticky or unsticky this post -
* true to sticky, false to unsticky.
* - The num argument is optional, and only used when stickying a post. It allows
* specifying a particular "slot" to sticky the post into, and if there is already
* a post stickied in that slot it will be replaced. If there is no post in the
* specified slot to replace, ornum is None, the bottom-most slot will be used.
* - api_typethe string json
* - idnuman integer between 1 and 2
* - stateboolean value
* - uh / X-Modhash headera modhash <https://www.reddit.com/dev/api#modhashes>
**/
fun OAuthClient.postSet_subreddit_sticky(vararg urlParams: Pair<String, Any?>) =
retry(3) { requestApi("/api/set_subreddit_sticky").post(urlParams.multipart()).getResponse() }
/*
* view code
* <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/api.py#L1654>#
* <https://www.reddit.com/dev/api#POST_api_set_suggested_sort>POST
* /api/set_suggested_sortmodposts <https://github.com/reddit/reddit/wiki/OAuth2>
* - Set a suggested sort for a link.
* - Suggested sorts are useful to display comments in a certain preferred way for
* posts. For example, casual conversation may be better sorted by new by default,
* or AMAs may be sorted by Q&A. A sort of an empty string clears the default sort.
* - api_typethe string json
* - idsortone of (confidence, top, new, controversial, old, random, qa, blank)
* - uh / X-Modhash headera modhash <https://www.reddit.com/dev/api#modhashes>
**/
fun OAuthClient.postSet_suggested_sort(vararg urlParams: Pair<String, Any?>) =
retry(3) { requestApi("/api/set_suggested_sort").post(urlParams.multipart()).getResponse() }
/*
* view code
* <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/api.py#L5090>#
* <https://www.reddit.com/dev/api#POST_api_store_visits>POST /api/store_visitssave
* <https://github.com/reddit/reddit/wiki/OAuth2>
* - Requires a subscription to reddit gold <https://www.reddit.com/gold/about>
* - linksA comma-separated list of link fullnames
* <https://www.reddit.com/dev/api#fullnames>
* - uh / X-Modhash headera modhash <https://www.reddit.com/dev/api#modhashes>
**/
fun OAuthClient.postStore_visits(vararg urlParams: Pair<String, Any?>) =
retry(3) { requestApi("/api/store_visits").post(urlParams.multipart()).getResponse() }
/*
* view code
* <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/api.py#L438>#
* <https://www.reddit.com/dev/api#POST_api_submit>POST /api/submitsubmit
* <https://github.com/reddit/reddit/wiki/OAuth2>
* - Submit a link to a subreddit.
* - Submit will create a link or self-post in the subreddit sr with the title
* title. If kind is "link", then url is expected to be a valid URL to link to.
* Otherwise,text, if present, will be the body of the self-post.
* - If a link with the same URL has already been submitted to the specified
* subreddit an error will be returned unlessresubmit is true. extension is used
* for determining which view-type (e.g.json, compact etc.) to use for the
* redirect that is generated if theresubmit error occurs.
* - api_typethe string json
* - captchathe user's response to the CAPTCHA challenge
* - extensionextension used for redirects
* - identhe identifier of the CAPTCHA challenge
* - kindone of (link, self)
* - resubmitboolean value
* - sendrepliesboolean value
* - srname of a subreddit
* - textraw markdown text
* - titletitle of the submission. up to 300 characters long
* - uh / X-Modhash headera modhash <https://www.reddit.com/dev/api#modhashes>
* - urla valid URL
**/
fun OAuthClient.postSubmit(vararg urlParams: Pair<String, Any?>) =
retry(3) { requestApi("/api/submit").post(urlParams.multipart()).getResponse() }
/*
* view code
* <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/api.py#L3490>#
* <https://www.reddit.com/dev/api#POST_api_unhide>POST /api/unhidereport
* <https://github.com/reddit/reddit/wiki/OAuth2>
* - Unhide a link.
* - See also: /api/hide <https://www.reddit.com/dev/api#POST_api_hide>.
* - idA comma-separated list of link fullnames
* <https://www.reddit.com/dev/api#fullnames>
* - uh / X-Modhash headera modhash <https://www.reddit.com/dev/api#modhashes>
**/
fun OAuthClient.postUnhide(vararg urlParams: Pair<String, Any?>) =
retry(3) { requestApi("/api/unhide").post(urlParams.multipart()).getResponse() }
/*
* view code
* <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/api.py#L1545>#
* <https://www.reddit.com/dev/api#POST_api_unlock>POST /api/unlockmodposts
* <https://github.com/reddit/reddit/wiki/OAuth2>
* - Unlock a link.
* - Allow a post to receive new comments.
* - See also: /api/lock <https://www.reddit.com/dev/api#POST_api_lock>.
* - idfullname <https://www.reddit.com/dev/api#fullnames> of a link
* - uh / X-Modhash headera modhash <https://www.reddit.com/dev/api#modhashes>
**/
fun OAuthClient.postUnlock(vararg urlParams: Pair<String, Any?>) =
retry(3) { requestApi("/api/unlock").post(urlParams.multipart()).getResponse() }
/*
* view code
* <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/api.py#L1589>#
* <https://www.reddit.com/dev/api#POST_api_unmarknsfw>POST /api/unmarknsfwmodposts
* <https://github.com/reddit/reddit/wiki/OAuth2>
* - Remove the NSFW marking from a link.
* - See also: /api/marknsfw <https://www.reddit.com/dev/api#POST_api_marknsfw>.
* - idfullname <https://www.reddit.com/dev/api#fullnames> of a thing
* - uh / X-Modhash headera modhash <https://www.reddit.com/dev/api#modhashes>
**/
fun OAuthClient.postUnmarknsfw(vararg urlParams: Pair<String, Any?>) =
retry(3) { requestApi("/api/unmarknsfw").post(urlParams.multipart()).getResponse() }
/*
* view code
* <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/api.py#L3367>#
* <https://www.reddit.com/dev/api#POST_api_unsave>POST /api/unsavesave
* <https://github.com/reddit/reddit/wiki/OAuth2>
* - Unsave a link or comment.
* - This removes the thing from the user's saved listings as well.
* - See also: /api/save <https://www.reddit.com/dev/api#POST_api_save>.
* - idfullname <https://www.reddit.com/dev/api#fullnames> of a thing
* - uh / X-Modhash headera modhash <https://www.reddit.com/dev/api#modhashes>
**/
fun OAuthClient.postUnsave(vararg urlParams: Pair<String, Any?>) =
retry(3) { requestApi("/api/unsave").post(urlParams.multipart()).getResponse() }
/*
* view code
* <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/api.py#L2308>#
* <https://www.reddit.com/dev/api#POST_api_vote>POST /api/votevote
* <https://github.com/reddit/reddit/wiki/OAuth2>
* - Cast a vote on a thing.
* - id should be the fullname of the Link or Comment to vote on.
* - dir indicates the direction of the vote. Voting 1 is an upvote, -1 is a
* downvote, and0 is equivalent to "un-voting" by clicking again on a highlighted
* arrow.
* - Note: votes must be cast by humans. That is, API clients proxying a human's
* action one-for-one are OK, but bots deciding how to vote on content or
* amplifying a human's vote are not. Seethe reddit rules
* <https://www.reddit.com/rules> for more details on what constitutes vote
* cheating.
* - dirvote direction. one of (1, 0, -1)
* - idfullname <https://www.reddit.com/dev/api#fullnames> of a thing
* - rankan integer greater than 1
* - uh / X-Modhash headera modhash <https://www.reddit.com/dev/api#modhashes>
**/
fun OAuthClient.postVote(vararg urlParams: Pair<String, Any?>) =
retry(3) { requestApi("/api/vote").post(urlParams.multipart()).getResponse() }
/*
* view code
* <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/listingcontroller.py#L715>
* # <https://www.reddit.com/dev/api#GET_by_id_{names}>GET /by_id/namesread
* <https://github.com/reddit/reddit/wiki/OAuth2>
* - Get a listing of links by fullname.
* - names is a list of fullnames for links separated by commas or spaces.
* - namesA comma-separated list of link fullnames
* <https://www.reddit.com/dev/api#fullnames>
**/
fun OAuthClient.getBy_idNames(names: List<String>) =
retry(3) { requestApi("/by_id/$names",
"names" to names.csv()).get().readEntity(String::class.java) }
/*
* view code
* <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/front.py#L214>#
* <https://www.reddit.com/dev/api#GET_comments_{article}>GET [/r/subreddit
* ]/comments/articleread <https://github.com/reddit/reddit/wiki/OAuth2>rss support
* <https://www.reddit.com/wiki/rss>
* - Get the comment tree for a given Link article.
* - If supplied, comment is the ID36 of a comment in the comment tree for article
* . This comment will be the (highlighted) focal point of the returned view and
* context will be the number of parents shown.
* - depth is the maximum depth of subtrees in the thread.
* - limit is the maximum number of comments to return.
* - See also: /api/morechildren
* <https://www.reddit.com/dev/api#GET_api_morechildren> and /api/comment
* <https://www.reddit.com/dev/api#POST_api_comment>.
* - articleID36 of a link
* - comment(optional) ID36 of a comment
* - contextan integer between 0 and 8
* - depth(optional) an integer
* - limit(optional) an integer
* - showeditsboolean value
* - showmoreboolean value
* - sortone of (confidence, top, new, controversial, old, random, qa)
* - sr_detail(optional) expand subreddits
**/
fun OAuthClient.getRSubredditCommentsArticle(subreddit: String, article: String, comment: String?, context: String?, depth: String?, limit: String?, showedits: String?, showmore: String?, sort: String?, srDetail: Boolean?) =
retry(3) { requestApi("/r/$subreddit/comments/$article",
"article" to article,
"comment" to comment,
"context" to context,
"depth" to depth,
"limit" to limit,
"showedits" to showedits,
"showmore" to showmore,
"sort" to sort,
"sr_detail" to srDetail).get().readEntity(String::class.java) }
/*
* view code
* <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/front.py#L1004>#
* <https://www.reddit.com/dev/api#GET_duplicates_{article}>GET /duplicates/
* articleread <https://github.com/reddit/reddit/wiki/OAuth2>rss support
* <https://www.reddit.com/wiki/rss>
* - Return a list of other submissions of the same URL
* - This endpoint is a listing <https://www.reddit.com/dev/api#listings>.
* - afterfullname <https://www.reddit.com/dev/api#fullnames> of a thing
* - articleThe base 36 ID of a Link
* - beforefullname <https://www.reddit.com/dev/api#fullnames> of a thing
* - counta positive integer (default: 0)
* - limitthe maximum number of items desired (default: 25, maximum: 100)
* - show(optional) the string all
* - sr_detail(optional) expand subreddits
**/
fun OAuthClient.getDuplicatesArticle(article: String, after: String?, before: String?, count: Int?, limit: Int?, show: String?, srDetail: Boolean?) =
retry(3) { requestApi("/duplicates/$article",
"after" to after,
"article" to article,
"before" to before,
"count" to count,
"limit" to limit,
"show" to show,
"sr_detail" to srDetail).get().readEntity(String::class.java) }
/*
* view code
* <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/listingcontroller.py#L543>
* # <https://www.reddit.com/dev/api#GET_hot>GET [/r/subreddit]/hotread
* <https://github.com/reddit/reddit/wiki/OAuth2>rss support
* <https://www.reddit.com/wiki/rss>
* - This endpoint is a listing <https://www.reddit.com/dev/api#listings>.
* - afterfullname <https://www.reddit.com/dev/api#fullnames> of a thing
* - beforefullname <https://www.reddit.com/dev/api#fullnames> of a thing
* - counta positive integer (default: 0)
* - limitthe maximum number of items desired (default: 25, maximum: 100)
* - show(optional) the string all
* - sr_detail(optional) expand subreddits
**/
fun OAuthClient.getRSubredditHot(subreddit: String, after: String?, before: String?, count: Int?, limit: Int?, show: String?, srDetail: Boolean?) =
retry(3) { requestApi("/r/$subreddit/hot",
"after" to after,
"before" to before,
"count" to count,
"limit" to limit,
"show" to show,
"sr_detail" to srDetail).get().readEntity(String::class.java) }
/*
* view code
* <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/listingcontroller.py#L572>
* # <https://www.reddit.com/dev/api#GET_new>GET [/r/subreddit]/newread
* <https://github.com/reddit/reddit/wiki/OAuth2>rss support
* <https://www.reddit.com/wiki/rss>
* - This endpoint is a listing <https://www.reddit.com/dev/api#listings>.
* - afterfullname <https://www.reddit.com/dev/api#fullnames> of a thing
* - beforefullname <https://www.reddit.com/dev/api#fullnames> of a thing
* - counta positive integer (default: 0)
* - limitthe maximum number of items desired (default: 25, maximum: 100)
* - show(optional) the string all
* - sr_detail(optional) expand subreddits
**/
fun OAuthClient.getRSubredditNew(subreddit: String, after: String?, before: String?, count: Int?, limit: Int?, show: String?, srDetail: Boolean?) =
retry(3) { requestApi("/r/$subreddit/new",
"after" to after,
"before" to before,
"count" to count,
"limit" to limit,
"show" to show,
"sr_detail" to srDetail).get().readEntity(String::class.java) }
/*
* view code
* <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/front.py#L128>#
* <https://www.reddit.com/dev/api#GET_random>GET [/r/subreddit]/randomread
* <https://github.com/reddit/reddit/wiki/OAuth2>
* - The Serendipity button
**/
fun OAuthClient.getRSubredditRandom(subreddit: String) =
retry(3) { requestApi("/r/$subreddit/random").get().readEntity(String::class.java) }
/*
* view code
* <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/listingcontroller.py#L625>
* # <https://www.reddit.com/dev/api#GET_{sort}>GET [/r/subreddit]/sortread
* <https://github.com/reddit/reddit/wiki/OAuth2>rss support
* <https://www.reddit.com/wiki/rss>
* * → [/r/subreddit]/top
* * → [/r/subreddit]/controversialThis endpoint is a listing
* <https://www.reddit.com/dev/api#listings>.
* - tone of (hour, day, week, month, year, all)
* - afterfullname <https://www.reddit.com/dev/api#fullnames> of a thing
* - beforefullname <https://www.reddit.com/dev/api#fullnames> of a thing
* - counta positive integer (default: 0)
* - limitthe maximum number of items desired (default: 25, maximum: 100)
* - show(optional) the string all
* - sr_detail(optional) expand subreddits
**/
fun OAuthClient.getRSubredditSort(subreddit: String, sort: String, t: String?, after: String?, before: String?, count: Int?, limit: Int?, show: String?, srDetail: Boolean?) =
retry(3) { requestApi("/r/$subreddit/$sort",
"t" to t,
"after" to after,
"before" to before,
"count" to count,
"limit" to limit,
"show" to show,
"sr_detail" to srDetail).get().readEntity(String::class.java) }
/*
* view code
* <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/listingcontroller.py#L625>
* # <https://www.reddit.com/dev/api#GET_{sort}>GET [/r/subreddit]/sortread
* <https://github.com/reddit/reddit/wiki/OAuth2>rss support
* <https://www.reddit.com/wiki/rss>
* * → [/r/subreddit]/top
* * → [/r/subreddit]/controversialThis endpoint is a listing
* <https://www.reddit.com/dev/api#listings>.
* - tone of (hour, day, week, month, year, all)
* - afterfullname <https://www.reddit.com/dev/api#fullnames> of a thing
* - beforefullname <https://www.reddit.com/dev/api#fullnames> of a thing
* - counta positive integer (default: 0)
* - limitthe maximum number of items desired (default: 25, maximum: 100)
* - show(optional) the string all
* - sr_detail(optional) expand subreddits
**/
fun OAuthClient.getRSubredditTop(subreddit: String, t: String?, after: String?, before: String?, count: Int?, limit: Int?, show: String?, srDetail: Boolean?) =
retry(3) { requestApi("/r/$subreddit/top",
"t" to t,
"after" to after,
"before" to before,
"count" to count,
"limit" to limit,
"show" to show,
"sr_detail" to srDetail).get().readEntity(String::class.java) }
/*
* view code
* <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/listingcontroller.py#L625>
* # <https://www.reddit.com/dev/api#GET_{sort}>GET [/r/subreddit]/sortread
* <https://github.com/reddit/reddit/wiki/OAuth2>rss support
* <https://www.reddit.com/wiki/rss>
* * → [/r/subreddit]/top
* * → [/r/subreddit]/controversialThis endpoint is a listing
* <https://www.reddit.com/dev/api#listings>.
* - tone of (hour, day, week, month, year, all)
* - afterfullname <https://www.reddit.com/dev/api#fullnames> of a thing
* - beforefullname <https://www.reddit.com/dev/api#fullnames> of a thing
* - counta positive integer (default: 0)
* - limitthe maximum number of items desired (default: 25, maximum: 100)
* - show(optional) the string all
* - sr_detail(optional) expand subreddits
**/
fun OAuthClient.getRSubredditControversial(subreddit: String, t: String?, after: String?, before: String?, count: Int?, limit: Int?, show: String?, srDetail: Boolean?) =
retry(3) { requestApi("/r/$subreddit/controversial",
"t" to t,
"after" to after,
"before" to before,
"count" to count,
"limit" to limit,
"show" to show,
"sr_detail" to srDetail).get().readEntity(String::class.java) }
/*
* Real-time updates on reddit.
* - In addition to the standard reddit API, WebSockets play a huge role in reddit
* live. Receiving push notification of changes to the thread via websockets is
* much better than polling the thread repeatedly.
* - To connect to the websocket server, fetch /live/thread/about.json
* <https://www.reddit.com/dev/api#GET_live_%7Bthread%7D_about.json> and get the
* websocket_url field. The websocket URL expires after a period of time; if it
* does, fetch a new one from that endpoint.
* - Once connected to the socket, a variety of messages can come in. All messages
* will be in text frames containing a JSON object with two keys:type and payload.
* Live threads can send messages with manytypes:
* * update - a new update has been posted in the thread. the payload contains
* the JSON representation of the update.
* * activity - periodic update of the viewer counts for the thread.
* * settings - the thread's settings have changed. the payload is an object
* with each key being a property of the thread (as inabout.json) and its new
* value.
* * delete - an update has been deleted (removed from the thread). the payload
* is the ID of the deleted update.
* * strike - an update has been stricken (marked incorrect and crossed out). the
* payload is the ID of the stricken update.
* * embeds_ready - a previously posted update has been parsed and embedded
* media is available for it now. thepayload contains a liveupdate_id and list of
* embeds to add to it.
* * complete - the thread has been marked complete. no further updates will be
* sent. See /r/live <https://www.reddit.com/r/live> for more information.
**/
fun OAuthClient.get() =
retry(3) { requestApi("").get().readEntity(String::class.java) }
/*
* view code
* <https://github.com/reddit/reddit-plugin-liveupdate/blob/master/reddit_liveupdate/controllers.py#L1015>
* # <https://www.reddit.com/dev/api#POST_api_live_create>POST /api/live/create
* submit <https://github.com/reddit/reddit/wiki/OAuth2>
* - Create a new live thread.
* - Once created, the initial settings can be modified with /api/live/thread/edit
* <https://www.reddit.com/dev/api#POST_api_live_%7Bthread%7D_edit> and new
* updates can be posted with/api/live/thread/update
* <https://www.reddit.com/dev/api#POST_api_live_%7Bthread%7D_update>.
* - api_typethe string json
* - descriptionraw markdown text
* - nsfwboolean value
* - resourcesraw markdown text
* - titlea string no longer than 120 characters
* - uh / X-Modhash headera modhash <https://www.reddit.com/dev/api#modhashes>
**/
fun OAuthClient.postLiveCreate(vararg urlParams: Pair<String, Any?>) =
retry(3) { requestApi("/api/live/create").post(urlParams.multipart()).getResponse() }
/*
* view code
* <https://github.com/reddit/reddit-plugin-liveupdate/blob/master/reddit_liveupdate/controllers.py#L620>
* #
* <https://www.reddit.com/dev/api#POST_api_live_{thread}_accept_contributor_invite>
* POST /api/live/thread/accept_contributor_invitelivemanage
* <https://github.com/reddit/reddit/wiki/OAuth2>
* - Accept a pending invitation to contribute to the thread.
* - See also: /api/live/thread/leave_contributor
* <https://www.reddit.com/dev/api#POST_api_live_%7Bthread%7D_leave_contributor>.
* - api_typethe string json
* - uh / X-Modhash headera modhash <https://www.reddit.com/dev/api#modhashes>
**/
fun OAuthClient.postLiveThreadAccept_contributor_invite(thread: String, vararg urlParams: Pair<String, Any?>) =
retry(3) { requestApi("/api/live/$thread/accept_contributor_invite").post(urlParams.multipart()).getResponse() }
/*
* view code
* <https://github.com/reddit/reddit-plugin-liveupdate/blob/master/reddit_liveupdate/controllers.py#L828>
* # <https://www.reddit.com/dev/api#POST_api_live_{thread}_close_thread>POST
* /api/live/thread/close_threadlivemanage
* <https://github.com/reddit/reddit/wiki/OAuth2>
* - Permanently close the thread, disallowing future updates.
* - Requires the close permission for this thread.
* - api_typethe string json
* - uh / X-Modhash headera modhash <https://www.reddit.com/dev/api#modhashes>
**/
fun OAuthClient.postLiveThreadClose_thread(thread: String, vararg urlParams: Pair<String, Any?>) =
retry(3) { requestApi("/api/live/$thread/close_thread").post(urlParams.multipart()).getResponse() }
/*
* view code
* <https://github.com/reddit/reddit-plugin-liveupdate/blob/master/reddit_liveupdate/controllers.py#L770>
* # <https://www.reddit.com/dev/api#POST_api_live_{thread}_delete_update>POST
* /api/live/thread/delete_updateedit
* <https://github.com/reddit/reddit/wiki/OAuth2>
* - Delete an update from the thread.
* - Requires that specified update must have been authored by the user or that
* you have theedit permission for this thread.
* - See also: /api/live/thread/update
* <https://www.reddit.com/dev/api#POST_api_live_%7Bthread%7D_update>.
* - api_typethe string json
* - idthe ID of a single update. e.g.
* LiveUpdate_ff87068e-a126-11e3-9f93-12313b0b3603
* - uh / X-Modhash headera modhash <https://www.reddit.com/dev/api#modhashes>
**/
fun OAuthClient.postLiveThreadDelete_update(thread: String, vararg urlParams: Pair<String, Any?>) =
retry(3) { requestApi("/api/live/$thread/delete_update").post(urlParams.multipart()).getResponse() }
/*
* view code
* <https://github.com/reddit/reddit-plugin-liveupdate/blob/master/reddit_liveupdate/controllers.py#L427>
* # <https://www.reddit.com/dev/api#POST_api_live_{thread}_edit>POST /api/live/
* thread/editlivemanage <https://github.com/reddit/reddit/wiki/OAuth2>
* - Configure the thread.
* - Requires the settings permission for this thread.
* - See also: /live/thread/about.json
* <https://www.reddit.com/dev/api#GET_live_%7Bthread%7D_about.json>.
* - api_typethe string json
* - descriptionraw markdown text
* - nsfwboolean value
* - resourcesraw markdown text
* - titlea string no longer than 120 characters
* - uh / X-Modhash headera modhash <https://www.reddit.com/dev/api#modhashes>
**/
fun OAuthClient.postLiveThreadEdit(thread: String, vararg urlParams: Pair<String, Any?>) =
retry(3) { requestApi("/api/live/$thread/edit").post(urlParams.multipart()).getResponse() }
/*
* view code
* <https://github.com/reddit/reddit-plugin-liveupdate/blob/master/reddit_liveupdate/controllers.py#L517>
* # <https://www.reddit.com/dev/api#POST_api_live_{thread}_invite_contributor>
* POST /api/live/thread/invite_contributorlivemanage
* <https://github.com/reddit/reddit/wiki/OAuth2>
* - Invite another user to contribute to the thread.
* - Requires the manage permission for this thread. If the recipient accepts the
* invite, they will be granted the permissions specified.
* - See also: /api/live/thread/accept_contributor_invite
* <https://www.reddit.com/dev/api#POST_api_live_%7Bthread%7D_accept_contributor_invite>
* , and/api/live/thread/rm_contributor_invite
* <https://www.reddit.com/dev/api#POST_api_live_%7Bthread%7D_rm_contributor_invite>
* .
* - api_typethe string json
* - namethe name of an existing user
* - permissionspermission description e.g. +update,+edit,-manage
* - typeone of (liveupdate_contributor_invite, liveupdate_contributor)
* - uh / X-Modhash headera modhash <https://www.reddit.com/dev/api#modhashes>
**/
fun OAuthClient.postLiveThreadInvite_contributor(thread: String, vararg urlParams: Pair<String, Any?>) =
retry(3) { requestApi("/api/live/$thread/invite_contributor").post(urlParams.multipart()).getResponse() }
/*
* view code
* <https://github.com/reddit/reddit-plugin-liveupdate/blob/master/reddit_liveupdate/controllers.py#L580>
* # <https://www.reddit.com/dev/api#POST_api_live_{thread}_leave_contributor>POST
* /api/live/thread/leave_contributorlivemanage
* <https://github.com/reddit/reddit/wiki/OAuth2>
* - Abdicate contributorship of the thread.
* - See also: /api/live/thread/accept_contributor_invite
* <https://www.reddit.com/dev/api#POST_api_live_%7Bthread%7D_accept_contributor_invite>
* , and/api/live/thread/invite_contributor
* <https://www.reddit.com/dev/api#POST_api_live_%7Bthread%7D_invite_contributor>.
* - api_typethe string json
* - uh / X-Modhash headera modhash <https://www.reddit.com/dev/api#modhashes>
**/
fun OAuthClient.postLiveThreadLeave_contributor(thread: String, vararg urlParams: Pair<String, Any?>) =
retry(3) { requestApi("/api/live/$thread/leave_contributor").post(urlParams.multipart()).getResponse() }
/*
* view code
* <https://github.com/reddit/reddit-plugin-liveupdate/blob/master/reddit_liveupdate/controllers.py#L851>
* # <https://www.reddit.com/dev/api#POST_api_live_{thread}_report>POST /api/live/
* thread/reportreport <https://github.com/reddit/reddit/wiki/OAuth2>
* - Report the thread for violating the rules of reddit.
* - api_typethe string json
* - typeone of (spam, vote-manipulation, personal-information, sexualizing-minors,
* site-breaking)
* - uh / X-Modhash headera modhash <https://www.reddit.com/dev/api#modhashes>
**/
fun OAuthClient.postLiveThreadReport(thread: String, vararg urlParams: Pair<String, Any?>) =
retry(3) { requestApi("/api/live/$thread/report").post(urlParams.multipart()).getResponse() }
/*
* view code
* <https://github.com/reddit/reddit-plugin-liveupdate/blob/master/reddit_liveupdate/controllers.py#L702>
* # <https://www.reddit.com/dev/api#POST_api_live_{thread}_rm_contributor>POST
* /api/live/thread/rm_contributorlivemanage
* <https://github.com/reddit/reddit/wiki/OAuth2>
* - Revoke another user's contributorship.
* - Requires the manage permission for this thread.
* - See also: /api/live/thread/invite_contributor
* <https://www.reddit.com/dev/api#POST_api_live_%7Bthread%7D_invite_contributor>.
* - api_typethe string json
* - idfullname <https://www.reddit.com/dev/api#fullnames> of a account
* - uh / X-Modhash headera modhash <https://www.reddit.com/dev/api#modhashes>
**/
fun OAuthClient.postLiveThreadRm_contributor(thread: String, vararg urlParams: Pair<String, Any?>) =
retry(3) { requestApi("/api/live/$thread/rm_contributor").post(urlParams.multipart()).getResponse() }
/*
* view code
* <https://github.com/reddit/reddit-plugin-liveupdate/blob/master/reddit_liveupdate/controllers.py#L599>
* # <https://www.reddit.com/dev/api#POST_api_live_{thread}_rm_contributor_invite>
* POST /api/live/thread/rm_contributor_invitelivemanage
* <https://github.com/reddit/reddit/wiki/OAuth2>
* - Revoke an outstanding contributor invite.
* - Requires the manage permission for this thread.
* - See also: /api/live/thread/invite_contributor
* <https://www.reddit.com/dev/api#POST_api_live_%7Bthread%7D_invite_contributor>.
* - api_typethe string json
* - idfullname <https://www.reddit.com/dev/api#fullnames> of a account
* - uh / X-Modhash headera modhash <https://www.reddit.com/dev/api#modhashes>
**/
fun OAuthClient.postLiveThreadRm_contributor_invite(thread: String, vararg urlParams: Pair<String, Any?>) =
retry(3) { requestApi("/api/live/$thread/rm_contributor_invite").post(urlParams.multipart()).getResponse() }
/*
* view code
* <https://github.com/reddit/reddit-plugin-liveupdate/blob/master/reddit_liveupdate/controllers.py#L649>
* #
* <https://www.reddit.com/dev/api#POST_api_live_{thread}_set_contributor_permissions>
* POST /api/live/thread/set_contributor_permissionslivemanage
* <https://github.com/reddit/reddit/wiki/OAuth2>
* - Change a contributor or contributor invite's permissions.
* - Requires the manage permission for this thread.
* - See also: /api/live/thread/invite_contributor
* <https://www.reddit.com/dev/api#POST_api_live_%7Bthread%7D_invite_contributor>
* and/api/live/thread/rm_contributor
* <https://www.reddit.com/dev/api#POST_api_live_%7Bthread%7D_rm_contributor>.
* - api_typethe string json
* - namethe name of an existing user
* - permissionspermission description e.g. +update,+edit,-manage
* - typeone of (liveupdate_contributor_invite, liveupdate_contributor)
* - uh / X-Modhash headera modhash <https://www.reddit.com/dev/api#modhashes>
**/
fun OAuthClient.postLiveThreadSet_contributor_permissions(thread: String, vararg urlParams: Pair<String, Any?>) =
retry(3) { requestApi("/api/live/$thread/set_contributor_permissions").post(urlParams.multipart()).getResponse() }
/*
* view code
* <https://github.com/reddit/reddit-plugin-liveupdate/blob/master/reddit_liveupdate/controllers.py#L799>
* # <https://www.reddit.com/dev/api#POST_api_live_{thread}_strike_update>POST
* /api/live/thread/strike_updateedit
* <https://github.com/reddit/reddit/wiki/OAuth2>
* - Strike (mark incorrect and cross out) the content of an update.
* - Requires that specified update must have been authored by the user or that
* you have theedit permission for this thread.
* - See also: /api/live/thread/update
* <https://www.reddit.com/dev/api#POST_api_live_%7Bthread%7D_update>.
* - api_typethe string json
* - idthe ID of a single update. e.g.
* LiveUpdate_ff87068e-a126-11e3-9f93-12313b0b3603
* - uh / X-Modhash headera modhash <https://www.reddit.com/dev/api#modhashes>
**/
fun OAuthClient.postLiveThreadStrike_update(thread: String, vararg urlParams: Pair<String, Any?>) =
retry(3) { requestApi("/api/live/$thread/strike_update").post(urlParams.multipart()).getResponse() }
/*
* view code
* <https://github.com/reddit/reddit-plugin-liveupdate/blob/master/reddit_liveupdate/controllers.py#L722>
* # <https://www.reddit.com/dev/api#POST_api_live_{thread}_update>POST /api/live/
* thread/updatesubmit <https://github.com/reddit/reddit/wiki/OAuth2>
* - Post an update to the thread.
* - Requires the update permission for this thread.
* - See also: /api/live/thread/strike_update
* <https://www.reddit.com/dev/api#POST_api_live_%7Bthread%7D_strike_update>, and
* /api/live/thread/delete_update
* <https://www.reddit.com/dev/api#POST_api_live_%7Bthread%7D_delete_update>.
* - api_typethe string json
* - bodyraw markdown text
* - uh / X-Modhash headera modhash <https://www.reddit.com/dev/api#modhashes>
**/
fun OAuthClient.postLiveThreadUpdate(thread: String, vararg urlParams: Pair<String, Any?>) =
retry(3) { requestApi("/api/live/$thread/update").post(urlParams.multipart()).getResponse() }
/*
* view code
* <https://github.com/reddit/reddit-plugin-liveupdate/blob/master/reddit_liveupdate/controllers.py#L259>
* # <https://www.reddit.com/dev/api#GET_live_{thread}>GET /live/threadread
* <https://github.com/reddit/reddit/wiki/OAuth2>rss support
* <https://www.reddit.com/wiki/rss>
* - Get a list of updates posted in this thread.
* - See also: /api/live/thread/update
* <https://www.reddit.com/dev/api#POST_api_live_%7Bthread%7D_update>.
* - This endpoint is a listing <https://www.reddit.com/dev/api#listings>.
* - afterthe ID of a single update. e.g.
* LiveUpdate_ff87068e-a126-11e3-9f93-12313b0b3603
* - beforethe ID of a single update. e.g.
* LiveUpdate_ff87068e-a126-11e3-9f93-12313b0b3603
* - counta positive integer (default: 0)
* - is_embed(internal use only)
* - limitthe maximum number of items desired (default: 25, maximum: 100)
* - stylesrsubreddit name
**/
fun OAuthClient.getLiveThread(thread: String, after: String?, before: String?, count: Int?, isEmbed: String?, limit: Int?, stylesr: String?) =
retry(3) { requestApi("/live/$thread",
"after" to after,
"before" to before,
"count" to count,
"is_embed" to isEmbed,
"limit" to limit,
"stylesr" to stylesr).get().readEntity(String::class.java) }
/*
* view code
* <https://github.com/reddit/reddit-plugin-liveupdate/blob/master/reddit_liveupdate/controllers.py#L382>
* # <https://www.reddit.com/dev/api#GET_live_{thread}_about>GET /live/thread/about
* read <https://github.com/reddit/reddit/wiki/OAuth2>
* - Get some basic information about the live thread.
* - See also: /api/live/thread/edit
* <https://www.reddit.com/dev/api#POST_api_live_%7Bthread%7D_edit>.
**/
fun OAuthClient.getLiveThreadAbout(thread: String) =
retry(3) { requestApi("/live/$thread/about").get().readEntity(String::class.java) }
/*
* view code
* <https://github.com/reddit/reddit-plugin-liveupdate/blob/master/reddit_liveupdate/controllers.py#L472>
* # <https://www.reddit.com/dev/api#GET_live_{thread}_contributors>GET /live/
* thread/contributorsread <https://github.com/reddit/reddit/wiki/OAuth2>
* - Get a list of users that contribute to this thread.
* - See also: /api/live/thread/invite_contributor
* <https://www.reddit.com/dev/api#POST_api_live_%7Bthread%7D_invite_contributor>,
* and/api/live/thread/rm_contributor
* <https://www.reddit.com/dev/api#POST_api_live_%7Bthread%7D_rm_contributor>.
**/
fun OAuthClient.getLiveThreadContributors(thread: String) =
retry(3) { requestApi("/live/$thread/contributors").get().readEntity(String::class.java) }
/*
* view code
* <https://github.com/reddit/reddit-plugin-liveupdate/blob/master/reddit_liveupdate/controllers.py#L398>
* # <https://www.reddit.com/dev/api#GET_live_{thread}_discussions>GET /live/thread
* /discussionsread <https://github.com/reddit/reddit/wiki/OAuth2>rss support
* <https://www.reddit.com/wiki/rss>
* - Get a list of reddit submissions linking to this thread.
* - This endpoint is a listing <https://www.reddit.com/dev/api#listings>.
* - afterfullname <https://www.reddit.com/dev/api#fullnames> of a thing
* - beforefullname <https://www.reddit.com/dev/api#fullnames> of a thing
* - counta positive integer (default: 0)
* - limitthe maximum number of items desired (default: 25, maximum: 100)
* - show(optional) the string all
* - sr_detail(optional) expand subreddits
**/
fun OAuthClient.getLiveThreadDiscussions(thread: String, after: String?, before: String?, count: Int?, limit: Int?, show: String?, srDetail: Boolean?) =
retry(3) { requestApi("/live/$thread/discussions",
"after" to after,
"before" to before,
"count" to count,
"limit" to limit,
"show" to show,
"sr_detail" to srDetail).get().readEntity(String::class.java) }
/*
* view code
* <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/api.py#L1842>#
* <https://www.reddit.com/dev/api#POST_api_block>POST /api/blockprivatemessages
* <https://github.com/reddit/reddit/wiki/OAuth2>
* - For blocking via inbox.
* - idfullname <https://www.reddit.com/dev/api#fullnames> of a thing
* - uh / X-Modhash headera modhash <https://www.reddit.com/dev/api#modhashes>
**/
fun OAuthClient.postBlock(vararg urlParams: Pair<String, Any?>) =
retry(3) { requestApi("/api/block").post(urlParams.multipart()).getResponse() }
/*
* view code
* <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/api.py#L3403>#
* <https://www.reddit.com/dev/api#POST_api_collapse_message>POST
* /api/collapse_message
* - Collapse a message
* - See also: /api/uncollapse_message
* <https://www.reddit.com/dev/api#POST_uncollapse_message>
* - idA comma-separated list of thing fullnames
* <https://www.reddit.com/dev/api#fullnames>
* - uh / X-Modhash headera modhash <https://www.reddit.com/dev/api#modhashes>
**/
fun OAuthClient.postCollapse_message(vararg urlParams: Pair<String, Any?>) =
retry(3) { requestApi("/api/collapse_message").post(urlParams.multipart()).getResponse() }
/*
* view code
* <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/api.py#L345>#
* <https://www.reddit.com/dev/api#POST_api_compose>POST /api/compose
* privatemessages <https://github.com/reddit/reddit/wiki/OAuth2>
* - Handles message composition under /message/compose.
* - api_typethe string json
* - captchathe user's response to the CAPTCHA challenge
* - from_srsubreddit name
* - identhe identifier of the CAPTCHA challenge
* - subjecta string no longer than 100 characters
* - textraw markdown text
* - tothe name of an existing user
* - uh / X-Modhash headera modhash <https://www.reddit.com/dev/api#modhashes>
**/
fun OAuthClient.postCompose(vararg urlParams: Pair<String, Any?>) =
retry(3) { requestApi("/api/compose").post(urlParams.multipart()).getResponse() }
/*
* view code
* <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/api.py#L3455>#
* <https://www.reddit.com/dev/api#POST_api_read_all_messages>POST
* /api/read_all_messagesprivatemessages
* <https://github.com/reddit/reddit/wiki/OAuth2>
* - Queue up marking all messages for a user as read.
* - This may take some time, and returns 202 to acknowledge acceptance of the
* request.
* - uh / X-Modhash headera modhash <https://www.reddit.com/dev/api#modhashes>
**/
fun OAuthClient.postRead_all_messages(vararg urlParams: Pair<String, Any?>) =
retry(3) { requestApi("/api/read_all_messages").post(urlParams.multipart()).getResponse() }
/*
* view code
* <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/api.py#L3441>#
* <https://www.reddit.com/dev/api#POST_api_read_message>POST /api/read_message
* privatemessages <https://github.com/reddit/reddit/wiki/OAuth2>
* - idA comma-separated list of thing fullnames
* <https://www.reddit.com/dev/api#fullnames>
* - uh / X-Modhash headera modhash <https://www.reddit.com/dev/api#modhashes>
**/
fun OAuthClient.postRead_message(vararg urlParams: Pair<String, Any?>) =
retry(3) { requestApi("/api/read_message").post(urlParams.multipart()).getResponse() }
/*
* view code
* <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/api.py#L1881>#
* <https://www.reddit.com/dev/api#POST_api_unblock_subreddit>POST
* /api/unblock_subredditprivatemessages
* <https://github.com/reddit/reddit/wiki/OAuth2>
* - idfullname <https://www.reddit.com/dev/api#fullnames> of a thing
* - uh / X-Modhash headera modhash <https://www.reddit.com/dev/api#modhashes>
**/
fun OAuthClient.postUnblock_subreddit(vararg urlParams: Pair<String, Any?>) =
retry(3) { requestApi("/api/unblock_subreddit").post(urlParams.multipart()).getResponse() }
/*
* view code
* <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/api.py#L3415>#
* <https://www.reddit.com/dev/api#POST_api_uncollapse_message>POST
* /api/uncollapse_message
* - Uncollapse a message
* - See also: /api/collapse_message
* <https://www.reddit.com/dev/api#POST_collapse_message>
* - idA comma-separated list of thing fullnames
* <https://www.reddit.com/dev/api#fullnames>
* - uh / X-Modhash headera modhash <https://www.reddit.com/dev/api#modhashes>
**/
fun OAuthClient.postUncollapse_message(vararg urlParams: Pair<String, Any?>) =
retry(3) { requestApi("/api/uncollapse_message").post(urlParams.multipart()).getResponse() }
/*
* view code
* <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/api.py#L3427>#
* <https://www.reddit.com/dev/api#POST_api_unread_message>POST /api/unread_message
* privatemessages <https://github.com/reddit/reddit/wiki/OAuth2>
* - idA comma-separated list of thing fullnames
* <https://www.reddit.com/dev/api#fullnames>
* - uh / X-Modhash headera modhash <https://www.reddit.com/dev/api#modhashes>
**/
fun OAuthClient.postUnread_message(vararg urlParams: Pair<String, Any?>) =
retry(3) { requestApi("/api/unread_message").post(urlParams.multipart()).getResponse() }
/*
* view code
* <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/listingcontroller.py#L1299>
* # <https://www.reddit.com/dev/api#GET_message_{where}>GET /message/where
* privatemessages <https://github.com/reddit/reddit/wiki/OAuth2>rss support
* <https://www.reddit.com/wiki/rss>
* * → /message/inbox
* * → /message/unread
* * → /message/sentThis endpoint is a listing
* <https://www.reddit.com/dev/api#listings>.
* - markone of (true, false)
* - midafterfullname <https://www.reddit.com/dev/api#fullnames> of a thing
* - beforefullname <https://www.reddit.com/dev/api#fullnames> of a thing
* - counta positive integer (default: 0)
* - limitthe maximum number of items desired (default: 25, maximum: 100)
* - show(optional) the string all
* - sr_detail(optional) expand subreddits
**/
fun OAuthClient.getMessageWhere(where: String, mark: Boolean?, after: String?, before: String?, count: Int?, limit: Int?, show: String?, srDetail: Boolean?) =
retry(3) { requestApi("/message/$where",
"mark" to mark,
"after" to after,
"before" to before,
"count" to count,
"limit" to limit,
"show" to show,
"sr_detail" to srDetail).get().readEntity(String::class.java) }
/*
* view code
* <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/listingcontroller.py#L1299>
* # <https://www.reddit.com/dev/api#GET_message_{where}>GET /message/where
* privatemessages <https://github.com/reddit/reddit/wiki/OAuth2>rss support
* <https://www.reddit.com/wiki/rss>
* * → /message/inbox
* * → /message/unread
* * → /message/sentThis endpoint is a listing
* <https://www.reddit.com/dev/api#listings>.
* - markone of (true, false)
* - midafterfullname <https://www.reddit.com/dev/api#fullnames> of a thing
* - beforefullname <https://www.reddit.com/dev/api#fullnames> of a thing
* - counta positive integer (default: 0)
* - limitthe maximum number of items desired (default: 25, maximum: 100)
* - show(optional) the string all
* - sr_detail(optional) expand subreddits
**/
fun OAuthClient.getMessageInbox(mark: Boolean?, after: String?, before: String?, count: Int?, limit: Int?, show: String?, srDetail: Boolean?) =
retry(3) { requestApi("/message/inbox",
"mark" to mark,
"after" to after,
"before" to before,
"count" to count,
"limit" to limit,
"show" to show,
"sr_detail" to srDetail).get().readEntity(String::class.java) }
/*
* view code
* <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/listingcontroller.py#L1299>
* # <https://www.reddit.com/dev/api#GET_message_{where}>GET /message/where
* privatemessages <https://github.com/reddit/reddit/wiki/OAuth2>rss support
* <https://www.reddit.com/wiki/rss>
* * → /message/inbox
* * → /message/unread
* * → /message/sentThis endpoint is a listing
* <https://www.reddit.com/dev/api#listings>.
* - markone of (true, false)
* - midafterfullname <https://www.reddit.com/dev/api#fullnames> of a thing
* - beforefullname <https://www.reddit.com/dev/api#fullnames> of a thing
* - counta positive integer (default: 0)
* - limitthe maximum number of items desired (default: 25, maximum: 100)
* - show(optional) the string all
* - sr_detail(optional) expand subreddits
**/
fun OAuthClient.getMessageUnread(mark: Boolean?, after: String?, before: String?, count: Int?, limit: Int?, show: String?, srDetail: Boolean?) =
retry(3) { requestApi("/message/unread",
"mark" to mark,
"after" to after,
"before" to before,
"count" to count,
"limit" to limit,
"show" to show,
"sr_detail" to srDetail).get().readEntity(String::class.java) }
/*
* view code
* <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/listingcontroller.py#L1299>
* # <https://www.reddit.com/dev/api#GET_message_{where}>GET /message/where
* privatemessages <https://github.com/reddit/reddit/wiki/OAuth2>rss support
* <https://www.reddit.com/wiki/rss>
* * → /message/inbox
* * → /message/unread
* * → /message/sentThis endpoint is a listing
* <https://www.reddit.com/dev/api#listings>.
* - markone of (true, false)
* - midafterfullname <https://www.reddit.com/dev/api#fullnames> of a thing
* - beforefullname <https://www.reddit.com/dev/api#fullnames> of a thing
* - counta positive integer (default: 0)
* - limitthe maximum number of items desired (default: 25, maximum: 100)
* - show(optional) the string all
* - sr_detail(optional) expand subreddits
**/
fun OAuthClient.getMessageSent(mark: Boolean?, after: String?, before: String?, count: Int?, limit: Int?, show: String?, srDetail: Boolean?) =
retry(3) { requestApi("/message/sent",
"mark" to mark,
"after" to after,
"before" to before,
"count" to count,
"limit" to limit,
"show" to show,
"sr_detail" to srDetail).get().readEntity(String::class.java) }
/*
* view code
* <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/apiv1/scopes.py#L34>
* # <https://www.reddit.com/dev/api#GET_api_v1_scopes>GET /api/v1/scopesany
* <https://github.com/reddit/reddit/wiki/OAuth2>
* - Retrieve descriptions of reddit's OAuth2 scopes.
* - If no scopes are given, information on all scopes are returned.
* - Invalid scope(s) will result in a 400 error with body that indicates the
* invalid scope(s).
* - scopes(optional) An OAuth2 scope string
**/
fun OAuthClient.getV1Scopes(scopes: String?) =
retry(3) { requestApi("/api/v1/scopes",
"scopes" to scopes).get().getResponse() }
/*
* view code
* <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/front.py#L593>#
* <https://www.reddit.com/dev/api#GET_about_log>GET [/r/subreddit]/about/logmodlog
* <https://github.com/reddit/reddit/wiki/OAuth2>rss support
* <https://www.reddit.com/wiki/rss>
* - Get a list of recent moderation actions.
* - Moderator actions taken within a subreddit are logged. This listing is a view
* of that log with various filters to aid in analyzing the information.
* - The optional mod parameter can be a comma-delimited list of moderator names
* to restrict the results to, or the stringa to restrict the results to admin
* actions taken within the subreddit.
* - The type parameter is optional and if sent limits the log entries returned to
* only those of the type specified.
* - This endpoint is a listing <https://www.reddit.com/dev/api#listings>.
* - afterfullname <https://www.reddit.com/dev/api#fullnames> of a thing
* - beforefullname <https://www.reddit.com/dev/api#fullnames> of a thing
* - counta positive integer (default: 0)
* - limitthe maximum number of items desired (default: 25, maximum: 500)
* - mod(optional) a moderator filter
* - show(optional) the string all
* - sr_detail(optional) expand subreddits
* - typeone of (banuser, unbanuser, removelink, approvelink, removecomment,
* approvecomment, addmoderator, invitemoderator, uninvitemoderator,
* acceptmoderatorinvite, removemoderator, addcontributor, removecontributor,
* editsettings, editflair, distinguish, marknsfw, wikibanned, wikicontributor,
* wikiunbanned, wikipagelisted, removewikicontributor, wikirevise, wikipermlevel,
* ignorereports, unignorereports, setpermissions, setsuggestedsort, sticky,
* unsticky, setcontestmode, unsetcontestmode, lock, unlock, muteuser, unmuteuser,
* createrule, editrule, deleterule)
**/
fun OAuthClient.getRSubredditAboutLog(subreddit: String, after: String?, before: String?, count: Int?, limit: Int?, mod: String?, show: String?, srDetail: Boolean?, type: String?) =
retry(3) { requestApi("/r/$subreddit/about/log",
"after" to after,
"before" to before,
"count" to count,
"limit" to limit,
"mod" to mod,
"show" to show,
"sr_detail" to srDetail,
"type" to type).get().readEntity(String::class.java) }
/*
* view code
* <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/front.py#L818>#
* <https://www.reddit.com/dev/api#GET_about_{location}>GET [/r/subreddit]/about/
* locationread <https://github.com/reddit/reddit/wiki/OAuth2>
* * → [/r/subreddit]/about/reports
* * → [/r/subreddit]/about/spam
* * → [/r/subreddit]/about/modqueue
* * → [/r/subreddit]/about/unmoderated
* * → [/r/subreddit]/about/editedReturn a listing of posts relevant to
* moderators.
* * reports: Things that have been reported.
* * spam: Things that have been marked as spam or otherwise removed.
* * modqueue: Things requiring moderator review, such as reported things and
* items caught by the spam filter.
* * unmoderated: Things that have yet to be approved/removed by a mod.
* * edited: Things that have been edited recently. Requires the "posts"
* moderator permission for the subreddit.
* - This endpoint is a listing <https://www.reddit.com/dev/api#listings>.
* - afterfullname <https://www.reddit.com/dev/api#fullnames> of a thing
* - beforefullname <https://www.reddit.com/dev/api#fullnames> of a thing
* - counta positive integer (default: 0)
* - limitthe maximum number of items desired (default: 25, maximum: 100)
* - locationonlyone of (links, comments)
* - show(optional) the string all
* - sr_detail(optional) expand subreddits
**/
fun OAuthClient.getRSubredditAboutLocation(subreddit: String, location: String, after: String?, before: String?, count: Int?, limit: Int?, only: String?, show: String?, srDetail: Boolean?) =
retry(3) { requestApi("/r/$subreddit/about/$location",
"after" to after,
"before" to before,
"count" to count,
"limit" to limit,
"only" to only,
"show" to show,
"sr_detail" to srDetail).get().readEntity(String::class.java) }
/*
* view code
* <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/front.py#L818>#
* <https://www.reddit.com/dev/api#GET_about_{location}>GET [/r/subreddit]/about/
* locationread <https://github.com/reddit/reddit/wiki/OAuth2>
* * → [/r/subreddit]/about/reports
* * → [/r/subreddit]/about/spam
* * → [/r/subreddit]/about/modqueue
* * → [/r/subreddit]/about/unmoderated
* * → [/r/subreddit]/about/editedReturn a listing of posts relevant to
* moderators.
* * reports: Things that have been reported.
* * spam: Things that have been marked as spam or otherwise removed.
* * modqueue: Things requiring moderator review, such as reported things and
* items caught by the spam filter.
* * unmoderated: Things that have yet to be approved/removed by a mod.
* * edited: Things that have been edited recently. Requires the "posts"
* moderator permission for the subreddit.
* - This endpoint is a listing <https://www.reddit.com/dev/api#listings>.
* - afterfullname <https://www.reddit.com/dev/api#fullnames> of a thing
* - beforefullname <https://www.reddit.com/dev/api#fullnames> of a thing
* - counta positive integer (default: 0)
* - limitthe maximum number of items desired (default: 25, maximum: 100)
* - locationonlyone of (links, comments)
* - show(optional) the string all
* - sr_detail(optional) expand subreddits
**/
fun OAuthClient.getRSubredditAboutReports(subreddit: String, after: String?, before: String?, count: Int?, limit: Int?, only: String?, show: String?, srDetail: Boolean?) =
retry(3) { requestApi("/r/$subreddit/about/reports",
"after" to after,
"before" to before,
"count" to count,
"limit" to limit,
"only" to only,
"show" to show,
"sr_detail" to srDetail).get().readEntity(String::class.java) }
/*
* view code
* <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/front.py#L818>#
* <https://www.reddit.com/dev/api#GET_about_{location}>GET [/r/subreddit]/about/
* locationread <https://github.com/reddit/reddit/wiki/OAuth2>
* * → [/r/subreddit]/about/reports
* * → [/r/subreddit]/about/spam
* * → [/r/subreddit]/about/modqueue
* * → [/r/subreddit]/about/unmoderated
* * → [/r/subreddit]/about/editedReturn a listing of posts relevant to
* moderators.
* * reports: Things that have been reported.
* * spam: Things that have been marked as spam or otherwise removed.
* * modqueue: Things requiring moderator review, such as reported things and
* items caught by the spam filter.
* * unmoderated: Things that have yet to be approved/removed by a mod.
* * edited: Things that have been edited recently. Requires the "posts"
* moderator permission for the subreddit.
* - This endpoint is a listing <https://www.reddit.com/dev/api#listings>.
* - afterfullname <https://www.reddit.com/dev/api#fullnames> of a thing
* - beforefullname <https://www.reddit.com/dev/api#fullnames> of a thing
* - counta positive integer (default: 0)
* - limitthe maximum number of items desired (default: 25, maximum: 100)
* - locationonlyone of (links, comments)
* - show(optional) the string all
* - sr_detail(optional) expand subreddits
**/
fun OAuthClient.getRSubredditAboutSpam(subreddit: String, after: String?, before: String?, count: Int?, limit: Int?, only: String?, show: String?, srDetail: Boolean?) =
retry(3) { requestApi("/r/$subreddit/about/spam",
"after" to after,
"before" to before,
"count" to count,
"limit" to limit,
"only" to only,
"show" to show,
"sr_detail" to srDetail).get().readEntity(String::class.java) }
/*
* view code
* <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/front.py#L818>#
* <https://www.reddit.com/dev/api#GET_about_{location}>GET [/r/subreddit]/about/
* locationread <https://github.com/reddit/reddit/wiki/OAuth2>
* * → [/r/subreddit]/about/reports
* * → [/r/subreddit]/about/spam
* * → [/r/subreddit]/about/modqueue
* * → [/r/subreddit]/about/unmoderated
* * → [/r/subreddit]/about/editedReturn a listing of posts relevant to
* moderators.
* * reports: Things that have been reported.
* * spam: Things that have been marked as spam or otherwise removed.
* * modqueue: Things requiring moderator review, such as reported things and
* items caught by the spam filter.
* * unmoderated: Things that have yet to be approved/removed by a mod.
* * edited: Things that have been edited recently. Requires the "posts"
* moderator permission for the subreddit.
* - This endpoint is a listing <https://www.reddit.com/dev/api#listings>.
* - afterfullname <https://www.reddit.com/dev/api#fullnames> of a thing
* - beforefullname <https://www.reddit.com/dev/api#fullnames> of a thing
* - counta positive integer (default: 0)
* - limitthe maximum number of items desired (default: 25, maximum: 100)
* - locationonlyone of (links, comments)
* - show(optional) the string all
* - sr_detail(optional) expand subreddits
**/
fun OAuthClient.getRSubredditAboutModqueue(subreddit: String, after: String?, before: String?, count: Int?, limit: Int?, only: String?, show: String?, srDetail: Boolean?) =
retry(3) { requestApi("/r/$subreddit/about/modqueue",
"after" to after,
"before" to before,
"count" to count,
"limit" to limit,
"only" to only,
"show" to show,
"sr_detail" to srDetail).get().readEntity(String::class.java) }
/*
* view code
* <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/front.py#L818>#
* <https://www.reddit.com/dev/api#GET_about_{location}>GET [/r/subreddit]/about/
* locationread <https://github.com/reddit/reddit/wiki/OAuth2>
* * → [/r/subreddit]/about/reports
* * → [/r/subreddit]/about/spam
* * → [/r/subreddit]/about/modqueue
* * → [/r/subreddit]/about/unmoderated
* * → [/r/subreddit]/about/editedReturn a listing of posts relevant to
* moderators.
* * reports: Things that have been reported.
* * spam: Things that have been marked as spam or otherwise removed.
* * modqueue: Things requiring moderator review, such as reported things and
* items caught by the spam filter.
* * unmoderated: Things that have yet to be approved/removed by a mod.
* * edited: Things that have been edited recently. Requires the "posts"
* moderator permission for the subreddit.
* - This endpoint is a listing <https://www.reddit.com/dev/api#listings>.
* - afterfullname <https://www.reddit.com/dev/api#fullnames> of a thing
* - beforefullname <https://www.reddit.com/dev/api#fullnames> of a thing
* - counta positive integer (default: 0)
* - limitthe maximum number of items desired (default: 25, maximum: 100)
* - locationonlyone of (links, comments)
* - show(optional) the string all
* - sr_detail(optional) expand subreddits
**/
fun OAuthClient.getRSubredditAboutUnmoderated(subreddit: String, after: String?, before: String?, count: Int?, limit: Int?, only: String?, show: String?, srDetail: Boolean?) =
retry(3) { requestApi("/r/$subreddit/about/unmoderated",
"after" to after,
"before" to before,
"count" to count,
"limit" to limit,
"only" to only,
"show" to show,
"sr_detail" to srDetail).get().readEntity(String::class.java) }
/*
* view code
* <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/front.py#L818>#
* <https://www.reddit.com/dev/api#GET_about_{location}>GET [/r/subreddit]/about/
* locationread <https://github.com/reddit/reddit/wiki/OAuth2>
* * → [/r/subreddit]/about/reports
* * → [/r/subreddit]/about/spam
* * → [/r/subreddit]/about/modqueue
* * → [/r/subreddit]/about/unmoderated
* * → [/r/subreddit]/about/editedReturn a listing of posts relevant to
* moderators.
* * reports: Things that have been reported.
* * spam: Things that have been marked as spam or otherwise removed.
* * modqueue: Things requiring moderator review, such as reported things and
* items caught by the spam filter.
* * unmoderated: Things that have yet to be approved/removed by a mod.
* * edited: Things that have been edited recently. Requires the "posts"
* moderator permission for the subreddit.
* - This endpoint is a listing <https://www.reddit.com/dev/api#listings>.
* - afterfullname <https://www.reddit.com/dev/api#fullnames> of a thing
* - beforefullname <https://www.reddit.com/dev/api#fullnames> of a thing
* - counta positive integer (default: 0)
* - limitthe maximum number of items desired (default: 25, maximum: 100)
* - locationonlyone of (links, comments)
* - show(optional) the string all
* - sr_detail(optional) expand subreddits
**/
fun OAuthClient.getRSubredditAboutEdited(subreddit: String, after: String?, before: String?, count: Int?, limit: Int?, only: String?, show: String?, srDetail: Boolean?) =
retry(3) { requestApi("/r/$subreddit/about/edited",
"after" to after,
"before" to before,
"count" to count,
"limit" to limit,
"only" to only,
"show" to show,
"sr_detail" to srDetail).get().readEntity(String::class.java) }
/*
* view code
* <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/api.py#L1317>#
* <https://www.reddit.com/dev/api#POST_api_accept_moderator_invite>POST [/r/
* subreddit]/api/accept_moderator_invitemodself
* <https://github.com/reddit/reddit/wiki/OAuth2>
* - Accept an invite to moderate the specified subreddit.
* - The authenticated user must have been invited to moderate the subreddit by
* one of its current moderators.
* - See also: /api/friend <https://www.reddit.com/dev/api#POST_api_friend> and
* /subreddits/mine
* <https://www.reddit.com/dev/api#GET_subreddits_mine_%7Bwhere%7D>.
* - api_typethe string json
* - uh / X-Modhash headera modhash <https://www.reddit.com/dev/api#modhashes>
**/
fun OAuthClient.postRSubredditAccept_moderator_invite(subreddit: String, vararg urlParams: Pair<String, Any?>) =
retry(3) { requestApi("/r/$subreddit/api/accept_moderator_invite").post(urlParams.multipart()).readEntity(String::class.java) }
/*
* view code
* <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/api.py#L3096>#
* <https://www.reddit.com/dev/api#POST_api_approve>POST /api/approvemodposts
* <https://github.com/reddit/reddit/wiki/OAuth2>
* - Approve a link or comment.
* - If the thing was removed, it will be re-inserted into appropriate listings.
* Any reports on the approved thing will be discarded.
* - See also: /api/remove <https://www.reddit.com/dev/api#POST_api_remove>.
* - idfullname <https://www.reddit.com/dev/api#fullnames> of a thing
* - uh / X-Modhash headera modhash <https://www.reddit.com/dev/api#modhashes>
**/
fun OAuthClient.postApprove(vararg urlParams: Pair<String, Any?>) =
retry(3) { requestApi("/api/approve").post(urlParams.multipart()).getResponse() }
/*
* view code
* <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/api.py#L3192>#
* <https://www.reddit.com/dev/api#POST_api_distinguish>POST /api/distinguish
* modposts <https://github.com/reddit/reddit/wiki/OAuth2>
* - Distinguish a thing's author with a sigil.
* - This can be useful to draw attention to and confirm the identity of the user
* in the context of a link or comment of theirs. The options for distinguish are
* as follows:
* * yes - add a moderator distinguish ([M]). only if the user is a moderator of
* the subreddit the thing is in.
* * no - remove any distinguishes.
* * admin - add an admin distinguish ([A]). admin accounts only.
* * special - add a user-specific distinguish. depends on user. The first time
* a top-level comment is moderator distinguished, the author of the link the
* comment is in reply to will get a notification in their inbox.
* - api_typethe string json
* - howone of (yes, no, admin, special)
* - idfullname <https://www.reddit.com/dev/api#fullnames> of a thing
* - uh / X-Modhash headera modhash <https://www.reddit.com/dev/api#modhashes>
**/
fun OAuthClient.postDistinguish(vararg urlParams: Pair<String, Any?>) =
retry(3) { requestApi("/api/distinguish").post(urlParams.multipart()).getResponse() }
/*
* view code
* <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/api.py#L3140>#
* <https://www.reddit.com/dev/api#POST_api_ignore_reports>POST /api/ignore_reports
* modposts <https://github.com/reddit/reddit/wiki/OAuth2>
* - Prevent future reports on a thing from causing notifications.
* - Any reports made about a thing after this flag is set on it will not cause
* notifications or make the thing show up in the various moderation listings.
* - See also: /api/unignore_reports
* <https://www.reddit.com/dev/api#POST_api_unignore_reports>.
* - idfullname <https://www.reddit.com/dev/api#fullnames> of a thing
* - uh / X-Modhash headera modhash <https://www.reddit.com/dev/api#modhashes>
**/
fun OAuthClient.postIgnore_reports(vararg urlParams: Pair<String, Any?>) =
retry(3) { requestApi("/api/ignore_reports").post(urlParams.multipart()).getResponse() }
/*
* view code
* <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/api.py#L812>#
* <https://www.reddit.com/dev/api#POST_api_leavecontributor>POST
* /api/leavecontributormodself <https://github.com/reddit/reddit/wiki/OAuth2>
* - Abdicate approved submitter status in a subreddit.
* - See also: /api/friend <https://www.reddit.com/dev/api#POST_api_friend>.
* - idfullname <https://www.reddit.com/dev/api#fullnames> of a thing
* - uh / X-Modhash headera modhash <https://www.reddit.com/dev/api#modhashes>
**/
fun OAuthClient.postLeavecontributor(vararg urlParams: Pair<String, Any?>) =
retry(3) { requestApi("/api/leavecontributor").post(urlParams.multipart()).getResponse() }
/*
* view code
* <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/api.py#L796>#
* <https://www.reddit.com/dev/api#POST_api_leavemoderator>POST /api/leavemoderator
* modself <https://github.com/reddit/reddit/wiki/OAuth2>
* - Abdicate moderator status in a subreddit.
* - See also: /api/friend <https://www.reddit.com/dev/api#POST_api_friend>.
* - idfullname <https://www.reddit.com/dev/api#fullnames> of a thing
* - uh / X-Modhash headera modhash <https://www.reddit.com/dev/api#modhashes>
**/
fun OAuthClient.postLeavemoderator(vararg urlParams: Pair<String, Any?>) =
retry(3) { requestApi("/api/leavemoderator").post(urlParams.multipart()).getResponse() }
/*
* view code
* <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/api.py#L1901>#
* <https://www.reddit.com/dev/api#POST_api_mute_message_author>POST
* /api/mute_message_authormodcontributors
* <https://github.com/reddit/reddit/wiki/OAuth2>
* - For muting user via modmail.
* - idfullname <https://www.reddit.com/dev/api#fullnames> of a thing
* - uh / X-Modhash headera modhash <https://www.reddit.com/dev/api#modhashes>
**/
fun OAuthClient.postMute_message_author(vararg urlParams: Pair<String, Any?>) =
retry(3) { requestApi("/api/mute_message_author").post(urlParams.multipart()).getResponse() }
/*
* view code
* <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/api.py#L3034>#
* <https://www.reddit.com/dev/api#POST_api_remove>POST /api/removemodposts
* <https://github.com/reddit/reddit/wiki/OAuth2>
* - Remove a link, comment, or modmail message.
* - If the thing is a link, it will be removed from all subreddit listings. If
* the thing is a comment, it will be redacted and removed from all subreddit
* comment listings.
* - See also: /api/approve <https://www.reddit.com/dev/api#POST_api_approve>.
* - idfullname <https://www.reddit.com/dev/api#fullnames> of a thing
* - spamboolean value
* - uh / X-Modhash headera modhash <https://www.reddit.com/dev/api#modhashes>
**/
fun OAuthClient.postRemove(vararg urlParams: Pair<String, Any?>) =
retry(3) { requestApi("/api/remove").post(urlParams.multipart()).getResponse() }
/*
* view code
* <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/api.py#L3168>#
* <https://www.reddit.com/dev/api#POST_api_unignore_reports>POST
* /api/unignore_reportsmodposts <https://github.com/reddit/reddit/wiki/OAuth2>
* - Allow future reports on a thing to cause notifications.
* - See also: /api/ignore_reports
* <https://www.reddit.com/dev/api#POST_api_ignore_reports>.
* - idfullname <https://www.reddit.com/dev/api#fullnames> of a thing
* - uh / X-Modhash headera modhash <https://www.reddit.com/dev/api#modhashes>
**/
fun OAuthClient.postUnignore_reports(vararg urlParams: Pair<String, Any?>) =
retry(3) { requestApi("/api/unignore_reports").post(urlParams.multipart()).getResponse() }
/*
* view code
* <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/api.py#L1945>#
* <https://www.reddit.com/dev/api#POST_api_unmute_message_author>POST
* /api/unmute_message_authormodcontributors
* <https://github.com/reddit/reddit/wiki/OAuth2>
* - For unmuting user via modmail.
* - idfullname <https://www.reddit.com/dev/api#fullnames> of a thing
* - uh / X-Modhash headera modhash <https://www.reddit.com/dev/api#modhashes>
**/
fun OAuthClient.postUnmute_message_author(vararg urlParams: Pair<String, Any?>) =
retry(3) { requestApi("/api/unmute_message_author").post(urlParams.multipart()).getResponse() }
/*
* view code
* <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/front.py#L556>#
* <https://www.reddit.com/dev/api#GET_stylesheet>GET [/r/subreddit]/stylesheet
* modconfig <https://github.com/reddit/reddit/wiki/OAuth2>
* - Redirect to the subreddit's stylesheet if one exists.
* - See also: /api/subreddit_stylesheet
* <https://www.reddit.com/dev/api#POST_api_subreddit_stylesheet>.
**/
fun OAuthClient.getRSubredditStylesheet(subreddit: String) =
retry(3) { requestApi("/r/$subreddit/stylesheet").get().readEntity(String::class.java) }
/*
* view code
* <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/multi.py#L285>#
* <https://www.reddit.com/dev/api#POST_api_multi_copy>POST /api/multi/copy
* subscribe <https://github.com/reddit/reddit/wiki/OAuth2>
* - Copy a multi.
* - Responds with 409 Conflict if the target already exists.
* - A "copied from ..." line will automatically be appended to the description.
* - display_namea string no longer than 50 characters
* - frommultireddit url path
* - todestination multireddit url path
* - uh / X-Modhash headera modhash <https://www.reddit.com/dev/api#modhashes>
**/
fun OAuthClient.postMultiCopy(vararg urlParams: Pair<String, Any?>) =
retry(3) { requestApi("/api/multi/copy").post(urlParams.multipart()).getResponse() }
/*
* view code
* <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/multi.py#L115>#
* <https://www.reddit.com/dev/api#GET_api_multi_mine>GET /api/multi/mineread
* <https://github.com/reddit/reddit/wiki/OAuth2>
* - Fetch a list of multis belonging to the current user.
* - expand_srsboolean value
**/
fun OAuthClient.getMultiMine(expandSrs: String?) =
retry(3) { requestApi("/api/multi/mine",
"expand_srs" to expandSrs).get().getResponse() }
/*
* view code
* <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/multi.py#L334>#
* <https://www.reddit.com/dev/api#POST_api_multi_rename>POST /api/multi/rename
* subscribe <https://github.com/reddit/reddit/wiki/OAuth2>
* - Rename a multi.
* - display_namea string no longer than 50 characters
* - frommultireddit url path
* - todestination multireddit url path
* - uh / X-Modhash headera modhash <https://www.reddit.com/dev/api#modhashes>
**/
fun OAuthClient.postMultiRename(vararg urlParams: Pair<String, Any?>) =
retry(3) { requestApi("/api/multi/rename").post(urlParams.multipart()).getResponse() }
/*
* view code
* <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/multi.py#L104>#
* <https://www.reddit.com/dev/api#GET_api_multi_user_{username}>GET
* /api/multi/user/usernameread <https://github.com/reddit/reddit/wiki/OAuth2>
* - Fetch a list of public multis belonging to username
* - expand_srsboolean value
* - usernameA valid, existing reddit username
**/
fun OAuthClient.getMultiUserUsername(username: String, expandSrs: String?) =
retry(3) { requestApi("/api/multi/user/$username",
"expand_srs" to expandSrs,
"username" to username).get().getResponse() }
/*
* view code
* <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/multi.py#L255>#
* <https://www.reddit.com/dev/api#DELETE_api_multi_{multipath}>DELETE /api/multi/
* multipathsubscribe <https://github.com/reddit/reddit/wiki/OAuth2>
* * → /api/filter/filterpathDelete a multi.
* - multipathmultireddit url path
* - uh / X-Modhash headera modhash <https://www.reddit.com/dev/api#modhashes>
* - expand_srsboolean value
**/
fun OAuthClient.deleteMultiMultipath(multipath: String, vararg urlParams: Pair<String, Any?>) =
retry(3) { requestApi("/api/multi/$multipath").method("delete").getResponse() }
/*
* view code
* <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/multi.py#L255>#
* <https://www.reddit.com/dev/api#DELETE_api_multi_{multipath}>DELETE /api/multi/
* multipathsubscribe <https://github.com/reddit/reddit/wiki/OAuth2>
* * → /api/filter/filterpathDelete a multi.
* - multipathmultireddit url path
* - uh / X-Modhash headera modhash <https://www.reddit.com/dev/api#modhashes>
* - expand_srsboolean value
**/
fun OAuthClient.deleteFilterFilterpath(filterpath: String, vararg urlParams: Pair<String, Any?>) =
retry(3) { requestApi("/api/filter/$filterpath").method("delete").getResponse() }
/*
* view code
* <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/multi.py#L127>#
* <https://www.reddit.com/dev/api#GET_api_multi_{multipath}>GET /api/multi/
* multipathread <https://github.com/reddit/reddit/wiki/OAuth2>
* * → /api/filter/filterpathFetch a multi's data and subreddit list by name.
* - expand_srsboolean value
* - multipathmultireddit url path
**/
fun OAuthClient.getMultiMultipath(multipath: String, expandSrs: String?) =
retry(3) { requestApi("/api/multi/$multipath",
"expand_srs" to expandSrs,
"multipath" to multipath).get().getResponse() }
/*
* view code
* <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/multi.py#L127>#
* <https://www.reddit.com/dev/api#GET_api_multi_{multipath}>GET /api/multi/
* multipathread <https://github.com/reddit/reddit/wiki/OAuth2>
* * → /api/filter/filterpathFetch a multi's data and subreddit list by name.
* - expand_srsboolean value
* - multipathmultireddit url path
**/
fun OAuthClient.getFilterFilterpath(filterpath: String, expandSrs: String?, multipath: String?) =
retry(3) { requestApi("/api/filter/$filterpath",
"expand_srs" to expandSrs,
"multipath" to multipath).get().getResponse() }
/*
* view code
* <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/multi.py#L199>#
* <https://www.reddit.com/dev/api#POST_api_multi_{multipath}>POST /api/multi/
* multipathsubscribe <https://github.com/reddit/reddit/wiki/OAuth2>
* * → /api/filter/filterpathCreate a multi. Responds with 409 Conflict if it
* already exists.
* - modeljson data:
* - { "description_md": raw markdown text, "display_name": a string no longer
* than 50 characters, "icon_name": one of (`art and design`, `ask`, `books`,
* `business`, `cars`, `comics`, `cute animals`, `diy`, `entertainment`, `food and
* drink`, `funny`, `games`, `grooming`, `health`, `life advice`, `military`,
* `models pinup`, `music`, `news`, `philosophy`, `pictures and gifs`, `science`,
* `shopping`, `sports`, `style`, `tech`, `travel`, `unusual stories`, `video`,
* ``, `None`), "key_color": a 6-digit rgb hex color, e.g. `#AABBCC`,
* "subreddits": [ { "name": subreddit name, }, ... ], "visibility": one of
* (`private`, `public`, `hidden`), "weighting_scheme": one of (`classic`,
* `fresh`), } multipathmultireddit url path
* - uh / X-Modhash headera modhash <https://www.reddit.com/dev/api#modhashes>
* - expand_srsboolean value
**/
fun OAuthClient.postMultiMultipath(multipath: String, vararg urlParams: Pair<String, Any?>) =
retry(3) { requestApi("/api/multi/$multipath").post(urlParams.multipart()).getResponse() }
/*
* view code
* <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/multi.py#L199>#
* <https://www.reddit.com/dev/api#POST_api_multi_{multipath}>POST /api/multi/
* multipathsubscribe <https://github.com/reddit/reddit/wiki/OAuth2>
* * → /api/filter/filterpathCreate a multi. Responds with 409 Conflict if it
* already exists.
* - modeljson data:
* - { "description_md": raw markdown text, "display_name": a string no longer
* than 50 characters, "icon_name": one of (`art and design`, `ask`, `books`,
* `business`, `cars`, `comics`, `cute animals`, `diy`, `entertainment`, `food and
* drink`, `funny`, `games`, `grooming`, `health`, `life advice`, `military`,
* `models pinup`, `music`, `news`, `philosophy`, `pictures and gifs`, `science`,
* `shopping`, `sports`, `style`, `tech`, `travel`, `unusual stories`, `video`,
* ``, `None`), "key_color": a 6-digit rgb hex color, e.g. `#AABBCC`,
* "subreddits": [ { "name": subreddit name, }, ... ], "visibility": one of
* (`private`, `public`, `hidden`), "weighting_scheme": one of (`classic`,
* `fresh`), } multipathmultireddit url path
* - uh / X-Modhash headera modhash <https://www.reddit.com/dev/api#modhashes>
* - expand_srsboolean value
**/
fun OAuthClient.postFilterFilterpath(filterpath: String, vararg urlParams: Pair<String, Any?>) =
retry(3) { requestApi("/api/filter/$filterpath").post(urlParams.multipart()).getResponse() }
/*
* view code
* <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/multi.py#L233>#
* <https://www.reddit.com/dev/api#PUT_api_multi_{multipath}>PUT /api/multi/
* multipathsubscribe <https://github.com/reddit/reddit/wiki/OAuth2>
* * → /api/filter/filterpathCreate or update a multi.
* - modeljson data:
* - { "description_md": raw markdown text, "display_name": a string no longer
* than 50 characters, "icon_name": one of (`art and design`, `ask`, `books`,
* `business`, `cars`, `comics`, `cute animals`, `diy`, `entertainment`, `food and
* drink`, `funny`, `games`, `grooming`, `health`, `life advice`, `military`,
* `models pinup`, `music`, `news`, `philosophy`, `pictures and gifs`, `science`,
* `shopping`, `sports`, `style`, `tech`, `travel`, `unusual stories`, `video`,
* ``, `None`), "key_color": a 6-digit rgb hex color, e.g. `#AABBCC`,
* "subreddits": [ { "name": subreddit name, }, ... ], "visibility": one of
* (`private`, `public`, `hidden`), "weighting_scheme": one of (`classic`,
* `fresh`), } multipathmultireddit url path
* - uh / X-Modhash headera modhash <https://www.reddit.com/dev/api#modhashes>
* - expand_srsboolean value
**/
fun OAuthClient.putMultiMultipath(multipath: String, vararg urlParams: Pair<String, Any?>) =
retry(3) { requestApi("/api/multi/$multipath").method("put").getResponse() }
/*
* view code
* <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/multi.py#L233>#
* <https://www.reddit.com/dev/api#PUT_api_multi_{multipath}>PUT /api/multi/
* multipathsubscribe <https://github.com/reddit/reddit/wiki/OAuth2>
* * → /api/filter/filterpathCreate or update a multi.
* - modeljson data:
* - { "description_md": raw markdown text, "display_name": a string no longer
* than 50 characters, "icon_name": one of (`art and design`, `ask`, `books`,
* `business`, `cars`, `comics`, `cute animals`, `diy`, `entertainment`, `food and
* drink`, `funny`, `games`, `grooming`, `health`, `life advice`, `military`,
* `models pinup`, `music`, `news`, `philosophy`, `pictures and gifs`, `science`,
* `shopping`, `sports`, `style`, `tech`, `travel`, `unusual stories`, `video`,
* ``, `None`), "key_color": a 6-digit rgb hex color, e.g. `#AABBCC`,
* "subreddits": [ { "name": subreddit name, }, ... ], "visibility": one of
* (`private`, `public`, `hidden`), "weighting_scheme": one of (`classic`,
* `fresh`), } multipathmultireddit url path
* - uh / X-Modhash headera modhash <https://www.reddit.com/dev/api#modhashes>
* - expand_srsboolean value
**/
fun OAuthClient.putFilterFilterpath(filterpath: String, vararg urlParams: Pair<String, Any?>) =
retry(3) { requestApi("/api/filter/$filterpath").method("put").getResponse() }
/*
* view code
* <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/multi.py#L427>#
* <https://www.reddit.com/dev/api#GET_api_multi_{multipath}_description>GET
* /api/multi/multipath/descriptionread
* <https://github.com/reddit/reddit/wiki/OAuth2>
* - Get a multi's description.
* - multipathmultireddit url path
**/
fun OAuthClient.getMultiMultipathDescription(multipath: String) =
retry(3) { requestApi("/api/multi/$multipath/description",
"multipath" to multipath).get().getResponse() }
/*
* view code
* <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/multi.py#L440>#
* <https://www.reddit.com/dev/api#PUT_api_multi_{multipath}_description>PUT
* /api/multi/multipath/descriptionread
* <https://github.com/reddit/reddit/wiki/OAuth2>
* - Change a multi's markdown description.
* - modeljson data:
* - { "body_md": raw markdown text, } multipathmultireddit url path
* - uh / X-Modhash headera modhash <https://www.reddit.com/dev/api#modhashes>
**/
fun OAuthClient.putMultiMultipathDescription(multipath: String, vararg urlParams: Pair<String, Any?>) =
retry(3) { requestApi("/api/multi/$multipath/description").method("put").getResponse() }
/*
* view code
* <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/multi.py#L410>#
* <https://www.reddit.com/dev/api#DELETE_api_multi_{multipath}_r_{srname}>DELETE
* /api/multi/multipath/r/srnamesubscribe
* <https://github.com/reddit/reddit/wiki/OAuth2>
* * → /api/filter/filterpath/r/srnameRemove a subreddit from a multi.
* - multipathmultireddit url path
* - srnamesubreddit name
* - uh / X-Modhash headera modhash <https://www.reddit.com/dev/api#modhashes>
**/
fun OAuthClient.deleteMultiMultipathRSrname(multipath: String, srname: String, vararg urlParams: Pair<String, Any?>) =
retry(3) { requestApi("/api/multi/$multipath/r/$srname").method("delete").getResponse() }
/*
* view code
* <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/multi.py#L410>#
* <https://www.reddit.com/dev/api#DELETE_api_multi_{multipath}_r_{srname}>DELETE
* /api/multi/multipath/r/srnamesubscribe
* <https://github.com/reddit/reddit/wiki/OAuth2>
* * → /api/filter/filterpath/r/srnameRemove a subreddit from a multi.
* - multipathmultireddit url path
* - srnamesubreddit name
* - uh / X-Modhash headera modhash <https://www.reddit.com/dev/api#modhashes>
**/
fun OAuthClient.deleteFilterFilterpathRSrname(filterpath: String, srname: String, vararg urlParams: Pair<String, Any?>) =
retry(3) { requestApi("/api/filter/$filterpath/r/$srname").method("delete").getResponse() }
/*
* view code
* <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/multi.py#L371>#
* <https://www.reddit.com/dev/api#GET_api_multi_{multipath}_r_{srname}>GET
* /api/multi/multipath/r/srnameread <https://github.com/reddit/reddit/wiki/OAuth2>
* * → /api/filter/filterpath/r/srnameGet data about a subreddit in a multi.
* - multipathmultireddit url path
* - srnamesubreddit name
**/
fun OAuthClient.getMultiMultipathRSrname(multipath: String, srname: String) =
retry(3) { requestApi("/api/multi/$multipath/r/$srname",
"multipath" to multipath,
"srname" to srname).get().getResponse() }
/*
* view code
* <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/multi.py#L371>#
* <https://www.reddit.com/dev/api#GET_api_multi_{multipath}_r_{srname}>GET
* /api/multi/multipath/r/srnameread <https://github.com/reddit/reddit/wiki/OAuth2>
* * → /api/filter/filterpath/r/srnameGet data about a subreddit in a multi.
* - multipathmultireddit url path
* - srnamesubreddit name
**/
fun OAuthClient.getFilterFilterpathRSrname(filterpath: String, srname: String, multipath: String?) =
retry(3) { requestApi("/api/filter/$filterpath/r/$srname",
"multipath" to multipath,
"srname" to srname).get().getResponse() }
/*
* view code
* <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/multi.py#L386>#
* <https://www.reddit.com/dev/api#PUT_api_multi_{multipath}_r_{srname}>PUT
* /api/multi/multipath/r/srnamesubscribe
* <https://github.com/reddit/reddit/wiki/OAuth2>
* * → /api/filter/filterpath/r/srnameAdd a subreddit to a multi.
* - modeljson data:
* - { "name": subreddit name, } multipathmultireddit url path
* - srnamesubreddit name
* - uh / X-Modhash headera modhash <https://www.reddit.com/dev/api#modhashes>
**/
fun OAuthClient.putMultiMultipathRSrname(multipath: String, srname: String, vararg urlParams: Pair<String, Any?>) =
retry(3) { requestApi("/api/multi/$multipath/r/$srname").method("put").getResponse() }
/*
* view code
* <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/multi.py#L386>#
* <https://www.reddit.com/dev/api#PUT_api_multi_{multipath}_r_{srname}>PUT
* /api/multi/multipath/r/srnamesubscribe
* <https://github.com/reddit/reddit/wiki/OAuth2>
* * → /api/filter/filterpath/r/srnameAdd a subreddit to a multi.
* - modeljson data:
* - { "name": subreddit name, } multipathmultireddit url path
* - srnamesubreddit name
* - uh / X-Modhash headera modhash <https://www.reddit.com/dev/api#modhashes>
**/
fun OAuthClient.putFilterFilterpathRSrname(filterpath: String, srname: String, vararg urlParams: Pair<String, Any?>) =
retry(3) { requestApi("/api/filter/$filterpath/r/$srname").method("put").getResponse() }
/*
* view code
* <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/front.py#L1092>#
* <https://www.reddit.com/dev/api#GET_search>GET [/r/subreddit]/searchread
* <https://github.com/reddit/reddit/wiki/OAuth2>rss support
* <https://www.reddit.com/wiki/rss>
* - Search links page.
* - This endpoint is a listing <https://www.reddit.com/dev/api#listings>.
* - afterfullname <https://www.reddit.com/dev/api#fullnames> of a thing
* - beforefullname <https://www.reddit.com/dev/api#fullnames> of a thing
* - counta positive integer (default: 0)
* - include_facetsboolean value
* - limitthe maximum number of items desired (default: 25, maximum: 100)
* - qa string no longer than 512 characters
* - restrict_srboolean value
* - show(optional) the string all
* - sortone of (relevance, hot, top, new, comments)
* - sr_detail(optional) expand subreddits
* - syntaxone of (cloudsearch, lucene, plain)
* - tone of (hour, day, week, month, year, all)
* - type(optional) comma-delimited list of result types (sr, link)
**/
fun OAuthClient.getRSubredditSearch(subreddit: String, after: String?, before: String?, count: Int?, includeFacets: String?, limit: Int?, q: String?, restrictSr: String?, show: String?, sort: String?, srDetail: Boolean?, syntax: String?, t: String?, type: List<String>?) =
retry(3) { requestApi("/r/$subreddit/search",
"after" to after,
"before" to before,
"count" to count,
"include_facets" to includeFacets,
"limit" to limit,
"q" to q,
"restrict_sr" to restrictSr,
"show" to show,
"sort" to sort,
"sr_detail" to srDetail,
"syntax" to syntax,
"t" to t,
"type" to type.csv()).get().readEntity(String::class.java) }
/*
* view code
* <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/listingcontroller.py#L1855>
* # <https://www.reddit.com/dev/api#GET_about_{where}>GET [/r/subreddit]/about/
* whereread <https://github.com/reddit/reddit/wiki/OAuth2>rss support
* <https://www.reddit.com/wiki/rss>
* * → [/r/subreddit]/about/banned
* * → [/r/subreddit]/about/muted
* * → [/r/subreddit]/about/wikibanned
* * → [/r/subreddit]/about/contributors
* * → [/r/subreddit]/about/wikicontributors
* * → [/r/subreddit]/about/moderatorsThis endpoint is a listing
* <https://www.reddit.com/dev/api#listings>.
* - afterfullname <https://www.reddit.com/dev/api#fullnames> of a thing
* - beforefullname <https://www.reddit.com/dev/api#fullnames> of a thing
* - counta positive integer (default: 0)
* - limitthe maximum number of items desired (default: 25, maximum: 100)
* - show(optional) the string all
* - sr_detail(optional) expand subreddits
* - userA valid, existing reddit username
**/
fun OAuthClient.getRSubredditAboutWhere(subreddit: String, where: String, after: String?, before: String?, count: Int?, limit: Int?, show: String?, srDetail: Boolean?, user: String?) =
retry(3) { requestApi("/r/$subreddit/about/$where",
"after" to after,
"before" to before,
"count" to count,
"limit" to limit,
"show" to show,
"sr_detail" to srDetail,
"user" to user).get().readEntity(String::class.java) }
/*
* view code
* <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/listingcontroller.py#L1855>
* # <https://www.reddit.com/dev/api#GET_about_{where}>GET [/r/subreddit]/about/
* whereread <https://github.com/reddit/reddit/wiki/OAuth2>rss support
* <https://www.reddit.com/wiki/rss>
* * → [/r/subreddit]/about/banned
* * → [/r/subreddit]/about/muted
* * → [/r/subreddit]/about/wikibanned
* * → [/r/subreddit]/about/contributors
* * → [/r/subreddit]/about/wikicontributors
* * → [/r/subreddit]/about/moderatorsThis endpoint is a listing
* <https://www.reddit.com/dev/api#listings>.
* - afterfullname <https://www.reddit.com/dev/api#fullnames> of a thing
* - beforefullname <https://www.reddit.com/dev/api#fullnames> of a thing
* - counta positive integer (default: 0)
* - limitthe maximum number of items desired (default: 25, maximum: 100)
* - show(optional) the string all
* - sr_detail(optional) expand subreddits
* - userA valid, existing reddit username
**/
fun OAuthClient.getRSubredditAboutBanned(subreddit: String, after: String?, before: String?, count: Int?, limit: Int?, show: String?, srDetail: Boolean?, user: String?) =
retry(3) { requestApi("/r/$subreddit/about/banned",
"after" to after,
"before" to before,
"count" to count,
"limit" to limit,
"show" to show,
"sr_detail" to srDetail,
"user" to user).get().readEntity(String::class.java) }
/*
* view code
* <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/listingcontroller.py#L1855>
* # <https://www.reddit.com/dev/api#GET_about_{where}>GET [/r/subreddit]/about/
* whereread <https://github.com/reddit/reddit/wiki/OAuth2>rss support
* <https://www.reddit.com/wiki/rss>
* * → [/r/subreddit]/about/banned
* * → [/r/subreddit]/about/muted
* * → [/r/subreddit]/about/wikibanned
* * → [/r/subreddit]/about/contributors
* * → [/r/subreddit]/about/wikicontributors
* * → [/r/subreddit]/about/moderatorsThis endpoint is a listing
* <https://www.reddit.com/dev/api#listings>.
* - afterfullname <https://www.reddit.com/dev/api#fullnames> of a thing
* - beforefullname <https://www.reddit.com/dev/api#fullnames> of a thing
* - counta positive integer (default: 0)
* - limitthe maximum number of items desired (default: 25, maximum: 100)
* - show(optional) the string all
* - sr_detail(optional) expand subreddits
* - userA valid, existing reddit username
**/
fun OAuthClient.getRSubredditAboutMuted(subreddit: String, after: String?, before: String?, count: Int?, limit: Int?, show: String?, srDetail: Boolean?, user: String?) =
retry(3) { requestApi("/r/$subreddit/about/muted",
"after" to after,
"before" to before,
"count" to count,
"limit" to limit,
"show" to show,
"sr_detail" to srDetail,
"user" to user).get().readEntity(String::class.java) }
/*
* view code
* <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/listingcontroller.py#L1855>
* # <https://www.reddit.com/dev/api#GET_about_{where}>GET [/r/subreddit]/about/
* whereread <https://github.com/reddit/reddit/wiki/OAuth2>rss support
* <https://www.reddit.com/wiki/rss>
* * → [/r/subreddit]/about/banned
* * → [/r/subreddit]/about/muted
* * → [/r/subreddit]/about/wikibanned
* * → [/r/subreddit]/about/contributors
* * → [/r/subreddit]/about/wikicontributors
* * → [/r/subreddit]/about/moderatorsThis endpoint is a listing
* <https://www.reddit.com/dev/api#listings>.
* - afterfullname <https://www.reddit.com/dev/api#fullnames> of a thing
* - beforefullname <https://www.reddit.com/dev/api#fullnames> of a thing
* - counta positive integer (default: 0)
* - limitthe maximum number of items desired (default: 25, maximum: 100)
* - show(optional) the string all
* - sr_detail(optional) expand subreddits
* - userA valid, existing reddit username
**/
fun OAuthClient.getRSubredditAboutWikibanned(subreddit: String, after: String?, before: String?, count: Int?, limit: Int?, show: String?, srDetail: Boolean?, user: String?) =
retry(3) { requestApi("/r/$subreddit/about/wikibanned",
"after" to after,
"before" to before,
"count" to count,
"limit" to limit,
"show" to show,
"sr_detail" to srDetail,
"user" to user).get().readEntity(String::class.java) }
/*
* view code
* <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/listingcontroller.py#L1855>
* # <https://www.reddit.com/dev/api#GET_about_{where}>GET [/r/subreddit]/about/
* whereread <https://github.com/reddit/reddit/wiki/OAuth2>rss support
* <https://www.reddit.com/wiki/rss>
* * → [/r/subreddit]/about/banned
* * → [/r/subreddit]/about/muted
* * → [/r/subreddit]/about/wikibanned
* * → [/r/subreddit]/about/contributors
* * → [/r/subreddit]/about/wikicontributors
* * → [/r/subreddit]/about/moderatorsThis endpoint is a listing
* <https://www.reddit.com/dev/api#listings>.
* - afterfullname <https://www.reddit.com/dev/api#fullnames> of a thing
* - beforefullname <https://www.reddit.com/dev/api#fullnames> of a thing
* - counta positive integer (default: 0)
* - limitthe maximum number of items desired (default: 25, maximum: 100)
* - show(optional) the string all
* - sr_detail(optional) expand subreddits
* - userA valid, existing reddit username
**/
fun OAuthClient.getRSubredditAboutContributors(subreddit: String, after: String?, before: String?, count: Int?, limit: Int?, show: String?, srDetail: Boolean?, user: String?) =
retry(3) { requestApi("/r/$subreddit/about/contributors",
"after" to after,
"before" to before,
"count" to count,
"limit" to limit,
"show" to show,
"sr_detail" to srDetail,
"user" to user).get().readEntity(String::class.java) }
/*
* view code
* <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/listingcontroller.py#L1855>
* # <https://www.reddit.com/dev/api#GET_about_{where}>GET [/r/subreddit]/about/
* whereread <https://github.com/reddit/reddit/wiki/OAuth2>rss support
* <https://www.reddit.com/wiki/rss>
* * → [/r/subreddit]/about/banned
* * → [/r/subreddit]/about/muted
* * → [/r/subreddit]/about/wikibanned
* * → [/r/subreddit]/about/contributors
* * → [/r/subreddit]/about/wikicontributors
* * → [/r/subreddit]/about/moderatorsThis endpoint is a listing
* <https://www.reddit.com/dev/api#listings>.
* - afterfullname <https://www.reddit.com/dev/api#fullnames> of a thing
* - beforefullname <https://www.reddit.com/dev/api#fullnames> of a thing
* - counta positive integer (default: 0)
* - limitthe maximum number of items desired (default: 25, maximum: 100)
* - show(optional) the string all
* - sr_detail(optional) expand subreddits
* - userA valid, existing reddit username
**/
fun OAuthClient.getRSubredditAboutWikicontributors(subreddit: String, after: String?, before: String?, count: Int?, limit: Int?, show: String?, srDetail: Boolean?, user: String?) =
retry(3) { requestApi("/r/$subreddit/about/wikicontributors",
"after" to after,
"before" to before,
"count" to count,
"limit" to limit,
"show" to show,
"sr_detail" to srDetail,
"user" to user).get().readEntity(String::class.java) }
/*
* view code
* <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/listingcontroller.py#L1855>
* # <https://www.reddit.com/dev/api#GET_about_{where}>GET [/r/subreddit]/about/
* whereread <https://github.com/reddit/reddit/wiki/OAuth2>rss support
* <https://www.reddit.com/wiki/rss>
* * → [/r/subreddit]/about/banned
* * → [/r/subreddit]/about/muted
* * → [/r/subreddit]/about/wikibanned
* * → [/r/subreddit]/about/contributors
* * → [/r/subreddit]/about/wikicontributors
* * → [/r/subreddit]/about/moderatorsThis endpoint is a listing
* <https://www.reddit.com/dev/api#listings>.
* - afterfullname <https://www.reddit.com/dev/api#fullnames> of a thing
* - beforefullname <https://www.reddit.com/dev/api#fullnames> of a thing
* - counta positive integer (default: 0)
* - limitthe maximum number of items desired (default: 25, maximum: 100)
* - show(optional) the string all
* - sr_detail(optional) expand subreddits
* - userA valid, existing reddit username
**/
fun OAuthClient.getRSubredditAboutModerators(subreddit: String, after: String?, before: String?, count: Int?, limit: Int?, show: String?, srDetail: Boolean?, user: String?) =
retry(3) { requestApi("/r/$subreddit/about/moderators",
"after" to after,
"before" to before,
"count" to count,
"limit" to limit,
"show" to show,
"sr_detail" to srDetail,
"user" to user).get().readEntity(String::class.java) }
/*
* view code
* <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/api.py#L2539>#
* <https://www.reddit.com/dev/api#POST_api_delete_sr_banner>POST [/r/subreddit
* ]/api/delete_sr_bannermodconfig <https://github.com/reddit/reddit/wiki/OAuth2>
* - Remove the subreddit's custom mobile banner.
* - See also: /api/upload_sr_img
* <https://www.reddit.com/dev/api#POST_api_upload_sr_img>.
* - api_typethe string json
* - uh / X-Modhash headera modhash <https://www.reddit.com/dev/api#modhashes>
**/
fun OAuthClient.postRSubredditDelete_sr_banner(subreddit: String, vararg urlParams: Pair<String, Any?>) =
retry(3) { requestApi("/r/$subreddit/api/delete_sr_banner").post(urlParams.multipart()).readEntity(String::class.java) }
/*
* view code
* <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/api.py#L2479>#
* <https://www.reddit.com/dev/api#POST_api_delete_sr_header>POST [/r/subreddit
* ]/api/delete_sr_headermodconfig <https://github.com/reddit/reddit/wiki/OAuth2>
* - Remove the subreddit's custom header image.
* - The sitewide-default header image will be shown again after this call.
* - See also: /api/upload_sr_img
* <https://www.reddit.com/dev/api#POST_api_upload_sr_img>.
* - api_typethe string json
* - uh / X-Modhash headera modhash <https://www.reddit.com/dev/api#modhashes>
**/
fun OAuthClient.postRSubredditDelete_sr_header(subreddit: String, vararg urlParams: Pair<String, Any?>) =
retry(3) { requestApi("/r/$subreddit/api/delete_sr_header").post(urlParams.multipart()).readEntity(String::class.java) }
/*
* view code
* <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/api.py#L2512>#
* <https://www.reddit.com/dev/api#POST_api_delete_sr_icon>POST [/r/subreddit
* ]/api/delete_sr_iconmodconfig <https://github.com/reddit/reddit/wiki/OAuth2>
* - Remove the subreddit's custom mobile icon.
* - See also: /api/upload_sr_img
* <https://www.reddit.com/dev/api#POST_api_upload_sr_img>.
* - api_typethe string json
* - uh / X-Modhash headera modhash <https://www.reddit.com/dev/api#modhashes>
**/
fun OAuthClient.postRSubredditDelete_sr_icon(subreddit: String, vararg urlParams: Pair<String, Any?>) =
retry(3) { requestApi("/r/$subreddit/api/delete_sr_icon").post(urlParams.multipart()).readEntity(String::class.java) }
/*
* view code
* <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/api.py#L2447>#
* <https://www.reddit.com/dev/api#POST_api_delete_sr_img>POST [/r/subreddit
* ]/api/delete_sr_imgmodconfig <https://github.com/reddit/reddit/wiki/OAuth2>
* - Remove an image from the subreddit's custom image set.
* - The image will no longer count against the subreddit's image limit. However,
* the actual image data may still be accessible for an unspecified amount of
* time. If the image is currently referenced by the subreddit's stylesheet, that
* stylesheet will no longer validate and won't be editable until the image
* reference is removed.
* - See also: /api/upload_sr_img
* <https://www.reddit.com/dev/api#POST_api_upload_sr_img>.
* - api_typethe string json
* - img_namea valid subreddit image name
* - uh / X-Modhash headera modhash <https://www.reddit.com/dev/api#modhashes>
**/
fun OAuthClient.postRSubredditDelete_sr_img(subreddit: String, vararg urlParams: Pair<String, Any?>) =
retry(3) { requestApi("/r/$subreddit/api/delete_sr_img").post(urlParams.multipart()).readEntity(String::class.java) }
/*
* view code
* <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/api.py#L5046>#
* <https://www.reddit.com/dev/api#GET_api_recommend_sr_{srnames}>GET
* /api/recommend/sr/srnamesread <https://github.com/reddit/reddit/wiki/OAuth2>
* - Return subreddits recommended for the given subreddit(s).
* - Gets a list of subreddits recommended for srnames, filtering out any that
* appear in the optionalomit param.
* - omitcomma-delimited list of subreddit names
* - srnamescomma-delimited list of subreddit names
**/
fun OAuthClient.getRecommendSrSrnames(srnames: List<String>, omit: List<String>?) =
retry(3) { requestApi("/api/recommend/sr/$srnames",
"omit" to omit.csv(),
"srnames" to srnames.csv()).get().getResponse() }
/*
* view code
* <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/api.py#L4592>#
* <https://www.reddit.com/dev/api#POST_api_search_reddit_names>POST
* /api/search_reddit_namesread <https://github.com/reddit/reddit/wiki/OAuth2>
* - List subreddit names that begin with a query string.
* - Subreddits whose names begin with query will be returned. If include_over_18
* is false, subreddits with over-18 content restrictions will be filtered from
* the results.
* - If exact is true, only an exact match will be returned.
* - exactboolean value
* - include_over_18boolean value
* - querya string up to 50 characters long, consisting of printable characters.
**/
fun OAuthClient.postSearch_reddit_names(vararg urlParams: Pair<String, Any?>) =
retry(3) { requestApi("/api/search_reddit_names").post(urlParams.multipart()).getResponse() }
/*
* view code
* <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/api.py#L2710>#
* <https://www.reddit.com/dev/api#POST_api_site_admin>POST /api/site_admin
* modconfig <https://github.com/reddit/reddit/wiki/OAuth2>
* - Create or configure a subreddit.
* - If sr is specified, the request will attempt to modify the specified
* subreddit. If not, a subreddit with namename will be created.
* - This endpoint expects all values to be supplied on every request. If
* modifying a subset of options, it may be useful to get the current settings from
* /about/edit.json
* <https://www.reddit.com/dev/api#GET_r_%7Bsubreddit%7D_about_edit.json> first.
* - For backwards compatibility, description is the sidebar text and
* public_description is the publicly visible subreddit description.
* - Most of the parameters for this endpoint are identical to options visible in
* the user interface and their meanings are best explained there.
* - See also: /about/edit.json
* <https://www.reddit.com/dev/api#GET_r_%7Bsubreddit%7D_about_edit.json>.
* - allow_topboolean value
* - api_typethe string json
* - captchathe user's response to the CAPTCHA challenge
* - collapse_deleted_commentsboolean value
* - comment_score_hide_minsan integer between 0 and 1440 (default: 0)
* - descriptionraw markdown text
* - exclude_banned_modqueueboolean value
* - header-titlea string no longer than 500 characters
* - hide_adsboolean value
* - identhe identifier of the CAPTCHA challenge
* - langa valid IETF language tag (underscore separated)
* - link_typeone of (any, link, self)
* - namesubreddit name
* - over_18boolean value
* - public_descriptionraw markdown text
* - public_trafficboolean value
* - show_mediaboolean value
* - spam_commentsone of (low, high, all)
* - spam_linksone of (low, high, all)
* - spam_selfpostsone of (low, high, all)
* - srfullname <https://www.reddit.com/dev/api#fullnames> of a thing
* - submit_link_labela string no longer than 60 characters
* - submit_textraw markdown text
* - submit_text_labela string no longer than 60 characters
* - suggested_comment_sortone of (confidence, top, new, controversial, old, random
* ,qa)
* - titlea string no longer than 100 characters
* - typeone of (gold_restricted, archived, restricted, gold_only, employees_only,
* private, public)
* - uh / X-Modhash headera modhash <https://www.reddit.com/dev/api#modhashes>
* - wiki_edit_agean integer greater than 0 (default: 0)
* - wiki_edit_karmaan integer greater than 0 (default: 0)
* - wikimodeone of (disabled, modonly, anyone)
**/
fun OAuthClient.postSite_admin(vararg urlParams: Pair<String, Any?>) =
retry(3) { requestApi("/api/site_admin").post(urlParams.multipart()).getResponse() }
/*
* view code
* <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/api.py#L417>#
* <https://www.reddit.com/dev/api#GET_api_submit_text>GET [/r/subreddit
* ]/api/submit_textsubmit <https://github.com/reddit/reddit/wiki/OAuth2>
* - Get the submission text for the subreddit.
* - This text is set by the subreddit moderators and intended to be displayed on
* the submission form.
* - See also: /api/site_admin <https://www.reddit.com/dev/api#POST_api_site_admin>
* .
**/
fun OAuthClient.getRSubredditSubmit_text(subreddit: String) =
retry(3) { requestApi("/r/$subreddit/api/submit_text").get().readEntity(String::class.java) }
/*
* view code
* <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/api.py#L2364>#
* <https://www.reddit.com/dev/api#POST_api_subreddit_stylesheet>POST [/r/subreddit
* ]/api/subreddit_stylesheetmodconfig
* <https://github.com/reddit/reddit/wiki/OAuth2>
* - Update a subreddit's stylesheet.
* - op should be save to update the contents of the stylesheet.
* - api_typethe string json
* - opone of (save, preview)
* - reasona string up to 256 characters long, consisting of printable characters.
* - stylesheet_contentsthe new stylesheet content
* - uh / X-Modhash headera modhash <https://www.reddit.com/dev/api#modhashes>
**/
fun OAuthClient.postRSubredditSubreddit_stylesheet(subreddit: String, vararg urlParams: Pair<String, Any?>) =
retry(3) { requestApi("/r/$subreddit/api/subreddit_stylesheet").post(urlParams.multipart()).readEntity(String::class.java) }
/*
* view code
* <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/api.py#L4738>#
* <https://www.reddit.com/dev/api#GET_api_subreddits_by_topic>GET
* /api/subreddits_by_topicread <https://github.com/reddit/reddit/wiki/OAuth2>
* - Return a list of subreddits that are relevant to a search query.
* - querya string no longer than 50 characters
**/
fun OAuthClient.getSubreddits_by_topic(query: String?) =
retry(3) { requestApi("/api/subreddits_by_topic",
"query" to query).get().getResponse() }
/*
* view code
* <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/api.py#L3774>#
* <https://www.reddit.com/dev/api#POST_api_subscribe>POST /api/subscribesubscribe
* <https://github.com/reddit/reddit/wiki/OAuth2>
* - Subscribe to or unsubscribe from a subreddit.
* - To subscribe, action should be sub. To unsubscribe, action should be unsub.
* The user must have access to the subreddit to be able to subscribe to it.
* - See also: /subreddits/mine/
* <https://www.reddit.com/dev/api#GET_subreddits_mine_%7Bwhere%7D>.
* - actionone of (sub, unsub)
* - srthe name of a subreddit
* - uh / X-Modhash headera modhash <https://www.reddit.com/dev/api#modhashes>
**/
fun OAuthClient.postSubscribe(vararg urlParams: Pair<String, Any?>) =
retry(3) { requestApi("/api/subscribe").post(urlParams.multipart()).getResponse() }
/*
* view code
* <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/api.py#L2577>#
* <https://www.reddit.com/dev/api#POST_api_upload_sr_img>POST [/r/subreddit
* ]/api/upload_sr_imgmodconfig <https://github.com/reddit/reddit/wiki/OAuth2>
* - Add or replace a subreddit image, custom header logo, custom mobile icon, or
* custom mobile banner.
* * If the upload_type value is img, an image for use in the subreddit
* stylesheet is uploaded with the name specified inname.
* * If the upload_type value is header then the image uploaded will be the
* subreddit's new logo andname will be ignored.
* * If the upload_type value is icon then the image uploaded will be the
* subreddit's new mobile icon andname will be ignored.
* * If the upload_type value is banner then the image uploaded will be the
* subreddit's new mobile banner andname will be ignored. For backwards
* compatibility, ifupload_type is not specified, the header field will be used
* instead:
* * If the header field has value 0, then upload_type is img.
* * If the header field has value 1, then upload_type is header. The img_type
* field specifies whether to store the uploaded image as a PNG or JPEG.
* - Subreddits have a limited number of images that can be in use at any given
* time. If no image with the specified name already exists, one of the slots will
* be consumed.
* - If an image with the specified name already exists, it will be replaced. This
* does not affect the stylesheet immediately, but will take effect the next time
* the stylesheet is saved.
* - See also: /api/delete_sr_img
* <https://www.reddit.com/dev/api#POST_api_delete_sr_img>, /api/delete_sr_header
* <https://www.reddit.com/dev/api#POST_api_delete_sr_header>, /api/delete_sr_icon
* <https://www.reddit.com/dev/api#POST_api_delete_sr_icon>, and
* /api/delete_sr_banner <https://www.reddit.com/dev/api#POST_api_delete_sr_banner>
* .
* - filefile upload with maximum size of 500 KiB
* - formid(optional) can be ignored
* - headeran integer between 0 and 1
* - img_typeone of png or jpg (default: png)
* - namea valid subreddit image name
* - uh / X-Modhash headera modhash <https://www.reddit.com/dev/api#modhashes>
* - upload_typeone of (img, header, icon, banner)
**/
fun OAuthClient.postRSubredditUpload_sr_img(subreddit: String, vararg urlParams: Pair<String, Any?>) =
retry(3) { requestApi("/r/$subreddit/api/upload_sr_img").post(urlParams.multipart()).readEntity(String::class.java) }
/*
* view code
* <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/front.py#L919>#
* <https://www.reddit.com/dev/api#GET_r_{subreddit}_about>GET /r/subreddit/about
* read <https://github.com/reddit/reddit/wiki/OAuth2>
* - Return information about the subreddit.
* - Data includes the subscriber count, description, and header image.
**/
fun OAuthClient.getRSubredditAbout(subreddit: String) =
retry(3) { requestApi("/r/$subreddit/about").get().readEntity(String::class.java) }
/*
* view code
* <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/front.py#L897>#
* <https://www.reddit.com/dev/api#GET_r_{subreddit}_about_edit>GET /r/subreddit
* /about/editmodconfig <https://github.com/reddit/reddit/wiki/OAuth2>
* - Get the current settings of a subreddit.
* - In the API, this returns the current settings of the subreddit as used by
* /api/site_admin <https://www.reddit.com/dev/api#POST_api_site_admin>. On the
* HTML site, it will display a form for editing the subreddit.
* - createdone of (true, false)
* - location
**/
fun OAuthClient.getRSubredditAboutEdit(subreddit: String, created: Boolean?) =
retry(3) { requestApi("/r/$subreddit/about/edit",
"created" to created).get().readEntity(String::class.java) }
/*
* view code
* <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/front.py#L938>#
* <https://www.reddit.com/dev/api#GET_rules>GET [/r/subreddit]/rulesread
* <https://github.com/reddit/reddit/wiki/OAuth2>
* - Get the rules for the current subreddit
**/
fun OAuthClient.getRSubredditRules(subreddit: String) =
retry(3) { requestApi("/r/$subreddit/rules").get().readEntity(String::class.java) }
/*
* view code
* <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/front.py#L931>#
* <https://www.reddit.com/dev/api#GET_sidebar>GET [/r/subreddit]/sidebarread
* <https://github.com/reddit/reddit/wiki/OAuth2>
* - Get the sidebar for the current subreddit
**/
fun OAuthClient.getRSubredditSidebar(subreddit: String) =
retry(3) { requestApi("/r/$subreddit/sidebar").get().readEntity(String::class.java) }
/*
* view code
* <https://github.com/reddit/reddit/blob/master/r2/r2/lib/validator/validator.py#L200>
* # <https://www.reddit.com/dev/api#GET_sticky>GET [/r/subreddit]/stickyread
* <https://github.com/reddit/reddit/wiki/OAuth2>
* - Redirect to one of the posts stickied in the current subreddit
* - The "num" argument can be used to select a specific sticky, and will default
* to 1 (the top sticky) if not specified. Will 404 if there is not currently a
* sticky post in this subreddit.
* - numan integer between 1 and 2 (default: 1)
**/
fun OAuthClient.getRSubredditSticky(subreddit: String, num: String?) =
retry(3) { requestApi("/r/$subreddit/sticky",
"num" to num).get().readEntity(String::class.java) }
/*
* view code
* <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/listingcontroller.py#L1626>
* # <https://www.reddit.com/dev/api#GET_subreddits_mine_{where}>GET
* /subreddits/mine/wheremysubreddits
* <https://github.com/reddit/reddit/wiki/OAuth2>rss support
* <https://www.reddit.com/wiki/rss>
* * → /subreddits/mine/subscriber
* * → /subreddits/mine/contributor
* * → /subreddits/mine/moderatorGet subreddits the user has a relationship with.
* - The where parameter chooses which subreddits are returned as follows:
* * subscriber - subreddits the user is subscribed to
* * contributor - subreddits the user is an approved submitter in
* * moderator - subreddits the user is a moderator of See also: /api/subscribe
* <https://www.reddit.com/dev/api#POST_api_subscribe>, /api/friend
* <https://www.reddit.com/dev/api#POST_api_friend>, and
* /api/accept_moderator_invite
* <https://www.reddit.com/dev/api#POST_api_accept_moderator_invite>.
* - This endpoint is a listing <https://www.reddit.com/dev/api#listings>.
* - afterfullname <https://www.reddit.com/dev/api#fullnames> of a thing
* - beforefullname <https://www.reddit.com/dev/api#fullnames> of a thing
* - counta positive integer (default: 0)
* - limitthe maximum number of items desired (default: 25, maximum: 100)
* - show(optional) the string all
* - sr_detail(optional) expand subreddits
**/
fun OAuthClient.getSubredditsMineWhere(where: String, after: String?, before: String?, count: Int?, limit: Int?, show: String?, srDetail: Boolean?) =
retry(3) { requestApi("/subreddits/mine/$where",
"after" to after,
"before" to before,
"count" to count,
"limit" to limit,
"show" to show,
"sr_detail" to srDetail).get().readEntity(String::class.java) }
/*
* view code
* <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/listingcontroller.py#L1626>
* # <https://www.reddit.com/dev/api#GET_subreddits_mine_{where}>GET
* /subreddits/mine/wheremysubreddits
* <https://github.com/reddit/reddit/wiki/OAuth2>rss support
* <https://www.reddit.com/wiki/rss>
* * → /subreddits/mine/subscriber
* * → /subreddits/mine/contributor
* * → /subreddits/mine/moderatorGet subreddits the user has a relationship with.
* - The where parameter chooses which subreddits are returned as follows:
* * subscriber - subreddits the user is subscribed to
* * contributor - subreddits the user is an approved submitter in
* * moderator - subreddits the user is a moderator of See also: /api/subscribe
* <https://www.reddit.com/dev/api#POST_api_subscribe>, /api/friend
* <https://www.reddit.com/dev/api#POST_api_friend>, and
* /api/accept_moderator_invite
* <https://www.reddit.com/dev/api#POST_api_accept_moderator_invite>.
* - This endpoint is a listing <https://www.reddit.com/dev/api#listings>.
* - afterfullname <https://www.reddit.com/dev/api#fullnames> of a thing
* - beforefullname <https://www.reddit.com/dev/api#fullnames> of a thing
* - counta positive integer (default: 0)
* - limitthe maximum number of items desired (default: 25, maximum: 100)
* - show(optional) the string all
* - sr_detail(optional) expand subreddits
**/
fun OAuthClient.getSubredditsMineSubscriber(after: String?, before: String?, count: Int?, limit: Int?, show: String?, srDetail: Boolean?) =
retry(3) { requestApi("/subreddits/mine/subscriber",
"after" to after,
"before" to before,
"count" to count,
"limit" to limit,
"show" to show,
"sr_detail" to srDetail).get().readEntity(String::class.java) }
/*
* view code
* <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/listingcontroller.py#L1626>
* # <https://www.reddit.com/dev/api#GET_subreddits_mine_{where}>GET
* /subreddits/mine/wheremysubreddits
* <https://github.com/reddit/reddit/wiki/OAuth2>rss support
* <https://www.reddit.com/wiki/rss>
* * → /subreddits/mine/subscriber
* * → /subreddits/mine/contributor
* * → /subreddits/mine/moderatorGet subreddits the user has a relationship with.
* - The where parameter chooses which subreddits are returned as follows:
* * subscriber - subreddits the user is subscribed to
* * contributor - subreddits the user is an approved submitter in
* * moderator - subreddits the user is a moderator of See also: /api/subscribe
* <https://www.reddit.com/dev/api#POST_api_subscribe>, /api/friend
* <https://www.reddit.com/dev/api#POST_api_friend>, and
* /api/accept_moderator_invite
* <https://www.reddit.com/dev/api#POST_api_accept_moderator_invite>.
* - This endpoint is a listing <https://www.reddit.com/dev/api#listings>.
* - afterfullname <https://www.reddit.com/dev/api#fullnames> of a thing
* - beforefullname <https://www.reddit.com/dev/api#fullnames> of a thing
* - counta positive integer (default: 0)
* - limitthe maximum number of items desired (default: 25, maximum: 100)
* - show(optional) the string all
* - sr_detail(optional) expand subreddits
**/
fun OAuthClient.getSubredditsMineContributor(after: String?, before: String?, count: Int?, limit: Int?, show: String?, srDetail: Boolean?) =
retry(3) { requestApi("/subreddits/mine/contributor",
"after" to after,
"before" to before,
"count" to count,
"limit" to limit,
"show" to show,
"sr_detail" to srDetail).get().readEntity(String::class.java) }
/*
* view code
* <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/listingcontroller.py#L1626>
* # <https://www.reddit.com/dev/api#GET_subreddits_mine_{where}>GET
* /subreddits/mine/wheremysubreddits
* <https://github.com/reddit/reddit/wiki/OAuth2>rss support
* <https://www.reddit.com/wiki/rss>
* * → /subreddits/mine/subscriber
* * → /subreddits/mine/contributor
* * → /subreddits/mine/moderatorGet subreddits the user has a relationship with.
* - The where parameter chooses which subreddits are returned as follows:
* * subscriber - subreddits the user is subscribed to
* * contributor - subreddits the user is an approved submitter in
* * moderator - subreddits the user is a moderator of See also: /api/subscribe
* <https://www.reddit.com/dev/api#POST_api_subscribe>, /api/friend
* <https://www.reddit.com/dev/api#POST_api_friend>, and
* /api/accept_moderator_invite
* <https://www.reddit.com/dev/api#POST_api_accept_moderator_invite>.
* - This endpoint is a listing <https://www.reddit.com/dev/api#listings>.
* - afterfullname <https://www.reddit.com/dev/api#fullnames> of a thing
* - beforefullname <https://www.reddit.com/dev/api#fullnames> of a thing
* - counta positive integer (default: 0)
* - limitthe maximum number of items desired (default: 25, maximum: 100)
* - show(optional) the string all
* - sr_detail(optional) expand subreddits
**/
fun OAuthClient.getSubredditsMineModerator(after: String?, before: String?, count: Int?, limit: Int?, show: String?, srDetail: Boolean?) =
retry(3) { requestApi("/subreddits/mine/moderator",
"after" to after,
"before" to before,
"count" to count,
"limit" to limit,
"show" to show,
"sr_detail" to srDetail).get().readEntity(String::class.java) }
/*
* view code
* <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/front.py#L1034>#
* <https://www.reddit.com/dev/api#GET_subreddits_search>GET /subreddits/search
* read <https://github.com/reddit/reddit/wiki/OAuth2>rss support
* <https://www.reddit.com/wiki/rss>
* - Search subreddits by title and description.
* - This endpoint is a listing <https://www.reddit.com/dev/api#listings>.
* - afterfullname <https://www.reddit.com/dev/api#fullnames> of a thing
* - beforefullname <https://www.reddit.com/dev/api#fullnames> of a thing
* - counta positive integer (default: 0)
* - limitthe maximum number of items desired (default: 25, maximum: 100)
* - qa search query
* - show(optional) the string all
* - sortone of (relevance, activity)
* - sr_detail(optional) expand subreddits
**/
fun OAuthClient.getSubredditsSearch(after: String?, before: String?, count: Int?, limit: Int?, q: String?, show: String?, sort: String?, srDetail: Boolean?) =
retry(3) { requestApi("/subreddits/search",
"after" to after,
"before" to before,
"count" to count,
"limit" to limit,
"q" to q,
"show" to show,
"sort" to sort,
"sr_detail" to srDetail).get().readEntity(String::class.java) }
/*
* view code
* <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/listingcontroller.py#L1507>
* # <https://www.reddit.com/dev/api#GET_subreddits_{where}>GET /subreddits/where
* read <https://github.com/reddit/reddit/wiki/OAuth2>rss support
* <https://www.reddit.com/wiki/rss>
* * → /subreddits/popular
* * → /subreddits/new
* * → /subreddits/gold
* * → /subreddits/defaultGet all subreddits.
* - The where parameter chooses the order in which the subreddits are displayed.
* popular sorts on the activity of the subreddit and the position of the
* subreddits can shift around.new sorts the subreddits based on their creation
* date, newest first.
* - This endpoint is a listing <https://www.reddit.com/dev/api#listings>.
* - afterfullname <https://www.reddit.com/dev/api#fullnames> of a thing
* - beforefullname <https://www.reddit.com/dev/api#fullnames> of a thing
* - counta positive integer (default: 0)
* - limitthe maximum number of items desired (default: 25, maximum: 100)
* - show(optional) the string all
* - sr_detail(optional) expand subreddits
**/
fun OAuthClient.getSubredditsWhere(where: String, after: String?, before: String?, count: Int?, limit: Int?, show: String?, srDetail: Boolean?) =
retry(3) { requestApi("/subreddits/$where",
"after" to after,
"before" to before,
"count" to count,
"limit" to limit,
"show" to show,
"sr_detail" to srDetail).get().readEntity(String::class.java) }
/*
* view code
* <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/listingcontroller.py#L1507>
* # <https://www.reddit.com/dev/api#GET_subreddits_{where}>GET /subreddits/where
* read <https://github.com/reddit/reddit/wiki/OAuth2>rss support
* <https://www.reddit.com/wiki/rss>
* * → /subreddits/popular
* * → /subreddits/new
* * → /subreddits/gold
* * → /subreddits/defaultGet all subreddits.
* - The where parameter chooses the order in which the subreddits are displayed.
* popular sorts on the activity of the subreddit and the position of the
* subreddits can shift around.new sorts the subreddits based on their creation
* date, newest first.
* - This endpoint is a listing <https://www.reddit.com/dev/api#listings>.
* - afterfullname <https://www.reddit.com/dev/api#fullnames> of a thing
* - beforefullname <https://www.reddit.com/dev/api#fullnames> of a thing
* - counta positive integer (default: 0)
* - limitthe maximum number of items desired (default: 25, maximum: 100)
* - show(optional) the string all
* - sr_detail(optional) expand subreddits
**/
fun OAuthClient.getSubredditsPopular(after: String?, before: String?, count: Int?, limit: Int?, show: String?, srDetail: Boolean?) =
retry(3) { requestApi("/subreddits/popular",
"after" to after,
"before" to before,
"count" to count,
"limit" to limit,
"show" to show,
"sr_detail" to srDetail).get().readEntity(String::class.java) }
/*
* view code
* <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/listingcontroller.py#L1507>
* # <https://www.reddit.com/dev/api#GET_subreddits_{where}>GET /subreddits/where
* read <https://github.com/reddit/reddit/wiki/OAuth2>rss support
* <https://www.reddit.com/wiki/rss>
* * → /subreddits/popular
* * → /subreddits/new
* * → /subreddits/gold
* * → /subreddits/defaultGet all subreddits.
* - The where parameter chooses the order in which the subreddits are displayed.
* popular sorts on the activity of the subreddit and the position of the
* subreddits can shift around.new sorts the subreddits based on their creation
* date, newest first.
* - This endpoint is a listing <https://www.reddit.com/dev/api#listings>.
* - afterfullname <https://www.reddit.com/dev/api#fullnames> of a thing
* - beforefullname <https://www.reddit.com/dev/api#fullnames> of a thing
* - counta positive integer (default: 0)
* - limitthe maximum number of items desired (default: 25, maximum: 100)
* - show(optional) the string all
* - sr_detail(optional) expand subreddits
**/
fun OAuthClient.getSubredditsNew(after: String?, before: String?, count: Int?, limit: Int?, show: String?, srDetail: Boolean?) =
retry(3) { requestApi("/subreddits/new",
"after" to after,
"before" to before,
"count" to count,
"limit" to limit,
"show" to show,
"sr_detail" to srDetail).get().readEntity(String::class.java) }
/*
* view code
* <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/listingcontroller.py#L1507>
* # <https://www.reddit.com/dev/api#GET_subreddits_{where}>GET /subreddits/where
* read <https://github.com/reddit/reddit/wiki/OAuth2>rss support
* <https://www.reddit.com/wiki/rss>
* * → /subreddits/popular
* * → /subreddits/new
* * → /subreddits/gold
* * → /subreddits/defaultGet all subreddits.
* - The where parameter chooses the order in which the subreddits are displayed.
* popular sorts on the activity of the subreddit and the position of the
* subreddits can shift around.new sorts the subreddits based on their creation
* date, newest first.
* - This endpoint is a listing <https://www.reddit.com/dev/api#listings>.
* - afterfullname <https://www.reddit.com/dev/api#fullnames> of a thing
* - beforefullname <https://www.reddit.com/dev/api#fullnames> of a thing
* - counta positive integer (default: 0)
* - limitthe maximum number of items desired (default: 25, maximum: 100)
* - show(optional) the string all
* - sr_detail(optional) expand subreddits
**/
fun OAuthClient.getSubredditsGold(after: String?, before: String?, count: Int?, limit: Int?, show: String?, srDetail: Boolean?) =
retry(3) { requestApi("/subreddits/gold",
"after" to after,
"before" to before,
"count" to count,
"limit" to limit,
"show" to show,
"sr_detail" to srDetail).get().readEntity(String::class.java) }
/*
* view code
* <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/listingcontroller.py#L1507>
* # <https://www.reddit.com/dev/api#GET_subreddits_{where}>GET /subreddits/where
* read <https://github.com/reddit/reddit/wiki/OAuth2>rss support
* <https://www.reddit.com/wiki/rss>
* * → /subreddits/popular
* * → /subreddits/new
* * → /subreddits/gold
* * → /subreddits/defaultGet all subreddits.
* - The where parameter chooses the order in which the subreddits are displayed.
* popular sorts on the activity of the subreddit and the position of the
* subreddits can shift around.new sorts the subreddits based on their creation
* date, newest first.
* - This endpoint is a listing <https://www.reddit.com/dev/api#listings>.
* - afterfullname <https://www.reddit.com/dev/api#fullnames> of a thing
* - beforefullname <https://www.reddit.com/dev/api#fullnames> of a thing
* - counta positive integer (default: 0)
* - limitthe maximum number of items desired (default: 25, maximum: 100)
* - show(optional) the string all
* - sr_detail(optional) expand subreddits
**/
fun OAuthClient.getSubredditsDefault(after: String?, before: String?, count: Int?, limit: Int?, show: String?, srDetail: Boolean?) =
retry(3) { requestApi("/subreddits/default",
"after" to after,
"before" to before,
"count" to count,
"limit" to limit,
"show" to show,
"sr_detail" to srDetail).get().readEntity(String::class.java) }
/*
* view code
* <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/api.py#L1020>#
* <https://www.reddit.com/dev/api#POST_api_friend>POST [/r/subreddit]/api/friend
* any <https://github.com/reddit/reddit/wiki/OAuth2>
* - Create a relationship between a user and another user or subreddit
* - OAuth2 use requires appropriate scope based on the 'type' of the relationship:
* * moderator: Use "moderator_invite"
* * moderator_invite: modothers
* * contributor: modcontributors
* * banned: modcontributors
* * muted: modcontributors
* * wikibanned: modcontributors and modwiki
* * wikicontributor: modcontributors and modwiki
* * friend: Use /api/v1/me/friends/{username}
* <https://www.reddit.com/dev/api#PUT_api_v1_me_friends_%7Busername%7D>
* * enemy: Use /api/block <https://www.reddit.com/dev/api#POST_api_block>
* Complement toPOST_unfriend <https://www.reddit.com/dev/api#POST_api_unfriend>
* - api_typethe string json
* - ban_messageraw markdown text
* - ban_reasona string no longer than 100 characters
* - containerdurationan integer between 1 and 999
* - namethe name of an existing user
* - notea string no longer than 300 characters
* - permissionstypeone of (friend, moderator, moderator_invite, contributor,
* banned, muted, wikibanned, wikicontributor)
* - uh / X-Modhash headera modhash <https://www.reddit.com/dev/api#modhashes>
**/
fun OAuthClient.postRSubredditFriend(subreddit: String, vararg urlParams: Pair<String, Any?>) =
retry(3) { requestApi("/r/$subreddit/api/friend").post(urlParams.multipart()).readEntity(String::class.java) }
/*
* view code
* <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/api.py#L974>#
* <https://www.reddit.com/dev/api#POST_api_setpermissions>POST [/r/subreddit
* ]/api/setpermissionsmodothers <https://github.com/reddit/reddit/wiki/OAuth2>
* - api_typethe string json
* - namethe name of an existing user
* - permissionstypeuh / X-Modhash headera modhash
* <https://www.reddit.com/dev/api#modhashes>
**/
fun OAuthClient.postRSubredditSetpermissions(subreddit: String, vararg urlParams: Pair<String, Any?>) =
retry(3) { requestApi("/r/$subreddit/api/setpermissions").post(urlParams.multipart()).readEntity(String::class.java) }
/*
* view code
* <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/api.py#L868>#
* <https://www.reddit.com/dev/api#POST_api_unfriend>POST [/r/subreddit
* ]/api/unfriendany <https://github.com/reddit/reddit/wiki/OAuth2>
* - Remove a relationship between a user and another user or subreddit
* - The user can either be passed in by name (nuser) or by fullname
* <https://www.reddit.com/dev/api#fullnames> (iuser). If type is friend or enemy,
* 'container' MUST be the current user's fullname; for other types, the subreddit
* must be set via URL (e.g.,/r/funny/api/unfriend
* <https://www.reddit.com/r/funny/api/unfriend>)
* - OAuth2 use requires appropriate scope based on the 'type' of the relationship:
* * moderator: modothers
* * moderator_invite: modothers
* * contributor: modcontributors
* * banned: modcontributors
* * muted: modcontributors
* * wikibanned: modcontributors and modwiki
* * wikicontributor: modcontributors and modwiki
* * friend: Use /api/v1/me/friends/{username}
* <https://www.reddit.com/dev/api#DELETE_api_v1_me_friends_%7Busername%7D>
* * enemy: privatemessages Complement to POST_friend
* <https://www.reddit.com/dev/api#POST_api_friend>
* - containeridfullname <https://www.reddit.com/dev/api#fullnames> of a thing
* - namethe name of an existing user
* - typeone of (friend, enemy, moderator, moderator_invite, contributor, banned,
* muted, wikibanned, wikicontributor)
* - uh / X-Modhash headera modhash <https://www.reddit.com/dev/api#modhashes>
**/
fun OAuthClient.postRSubredditUnfriend(subreddit: String, vararg urlParams: Pair<String, Any?>) =
retry(3) { requestApi("/r/$subreddit/api/unfriend").post(urlParams.multipart()).readEntity(String::class.java) }
/*
* view code
* <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/api.py#L238>#
* <https://www.reddit.com/dev/api#GET_api_username_available>GET
* /api/username_available
* - Check whether a username is available for registration.
* - usera valid, unused, username
**/
fun OAuthClient.getUsername_available(user: String?) =
retry(3) { requestApi("/api/username_available",
"user" to user).get().getResponse() }
/*
* view code
* <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/apiv1/user.py#L202>
* # <https://www.reddit.com/dev/api#DELETE_api_v1_me_friends_{username}>DELETE
* /api/v1/me/friends/usernamesubscribe
* <https://github.com/reddit/reddit/wiki/OAuth2>
* - Stop being friends with a user.
* - idA valid, existing reddit username
**/
fun OAuthClient.deleteV1MeFriendsUsername(username: String, vararg urlParams: Pair<String, Any?>) =
retry(3) { requestApi("/api/v1/me/friends/$username").method("delete").getResponse() }
/*
* view code
* <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/apiv1/user.py#L191>
* # <https://www.reddit.com/dev/api#GET_api_v1_me_friends_{username}>GET
* /api/v1/me/friends/usernamemysubreddits
* <https://github.com/reddit/reddit/wiki/OAuth2>
* - Get information about a specific 'friend', such as notes.
* - idA valid, existing reddit username
**/
fun OAuthClient.getV1MeFriendsUsername(username: String, id: String?) =
retry(3) { requestApi("/api/v1/me/friends/$username",
"id" to id).get().getResponse() }
/*
* view code
* <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/apiv1/user.py#L146>
* # <https://www.reddit.com/dev/api#PUT_api_v1_me_friends_{username}>PUT
* /api/v1/me/friends/usernamesubscribe
* <https://github.com/reddit/reddit/wiki/OAuth2>
* - Create or update a "friend" relationship.
* - This operation is idempotent. It can be used to add a new friend, or update
* an existing friend (e.g., add/change the note on that friend)
* - This endpoint expects JSON data of this format{ "name": A valid, existing
* reddit username, "note": a string no longer than 300 characters, }
**/
fun OAuthClient.putV1MeFriendsUsername(username: String, vararg urlParams: Pair<String, Any?>) =
retry(3) { requestApi("/api/v1/me/friends/$username").method("put").getResponse() }
/*
* view code
* <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/apiv1/user.py#L82>
* # <https://www.reddit.com/dev/api#GET_api_v1_user_{username}_trophies>GET
* /api/v1/user/username/trophiesread
* <https://github.com/reddit/reddit/wiki/OAuth2>
* - Return a list of trophies for the a given user.
* - idA valid, existing reddit username
**/
fun OAuthClient.getV1UserUsernameTrophies(username: String, id: String?) =
retry(3) { requestApi("/api/v1/user/$username/trophies",
"id" to id).get().getResponse() }
/*
* view code
* <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/listingcontroller.py#L1015>
* # <https://www.reddit.com/dev/api#GET_user_{username}_about>GET /user/username
* /aboutread <https://github.com/reddit/reddit/wiki/OAuth2>
* - Return information about the user, including karma and gold status.
* - usernamethe name of an existing user
**/
fun OAuthClient.getUserUsernameAbout(username: String) =
retry(3) { requestApi("/user/$username/about",
"username" to username).get().readEntity(String::class.java) }
/*
* view code
* <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/listingcontroller.py#L890>
* # <https://www.reddit.com/dev/api#GET_user_{username}_{where}>GET /user/username
* /wherehistory <https://github.com/reddit/reddit/wiki/OAuth2>rss support
* <https://www.reddit.com/wiki/rss>
* * → /user/username/overview
* * → /user/username/submitted
* * → /user/username/comments
* * → /user/username/upvoted
* * → /user/username/downvoted
* * → /user/username/hidden
* * → /user/username/saved
* * → /user/username/gildedThis endpoint is a listing
* <https://www.reddit.com/dev/api#listings>.
* - showone of (given)
* - sortone of (hot, new, top, controversial)
* - tone of (hour, day, week, month, year, all)
* - usernamethe name of an existing user
* - afterfullname <https://www.reddit.com/dev/api#fullnames> of a thing
* - beforefullname <https://www.reddit.com/dev/api#fullnames> of a thing
* - counta positive integer (default: 0)
* - limitthe maximum number of items desired (default: 25, maximum: 100)
* - sr_detail(optional) expand subreddits
**/
fun OAuthClient.getUserUsernameWhere(username: String, where: String, show: String?, sort: String?, t: String?, after: String?, before: String?, count: Int?, limit: Int?, srDetail: Boolean?) =
retry(3) { requestApi("/user/$username/$where",
"show" to show,
"sort" to sort,
"t" to t,
"username" to username,
"after" to after,
"before" to before,
"count" to count,
"limit" to limit,
"sr_detail" to srDetail).get().readEntity(String::class.java) }
/*
* view code
* <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/listingcontroller.py#L890>
* # <https://www.reddit.com/dev/api#GET_user_{username}_{where}>GET /user/username
* /wherehistory <https://github.com/reddit/reddit/wiki/OAuth2>rss support
* <https://www.reddit.com/wiki/rss>
* * → /user/username/overview
* * → /user/username/submitted
* * → /user/username/comments
* * → /user/username/upvoted
* * → /user/username/downvoted
* * → /user/username/hidden
* * → /user/username/saved
* * → /user/username/gildedThis endpoint is a listing
* <https://www.reddit.com/dev/api#listings>.
* - showone of (given)
* - sortone of (hot, new, top, controversial)
* - tone of (hour, day, week, month, year, all)
* - usernamethe name of an existing user
* - afterfullname <https://www.reddit.com/dev/api#fullnames> of a thing
* - beforefullname <https://www.reddit.com/dev/api#fullnames> of a thing
* - counta positive integer (default: 0)
* - limitthe maximum number of items desired (default: 25, maximum: 100)
* - sr_detail(optional) expand subreddits
**/
fun OAuthClient.getUserUsernameOverview(username: String, show: String?, sort: String?, t: String?, after: String?, before: String?, count: Int?, limit: Int?, srDetail: Boolean?) =
retry(3) { requestApi("/user/$username/overview",
"show" to show,
"sort" to sort,
"t" to t,
"username" to username,
"after" to after,
"before" to before,
"count" to count,
"limit" to limit,
"sr_detail" to srDetail).get().readEntity(String::class.java) }
/*
* view code
* <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/listingcontroller.py#L890>
* # <https://www.reddit.com/dev/api#GET_user_{username}_{where}>GET /user/username
* /wherehistory <https://github.com/reddit/reddit/wiki/OAuth2>rss support
* <https://www.reddit.com/wiki/rss>
* * → /user/username/overview
* * → /user/username/submitted
* * → /user/username/comments
* * → /user/username/upvoted
* * → /user/username/downvoted
* * → /user/username/hidden
* * → /user/username/saved
* * → /user/username/gildedThis endpoint is a listing
* <https://www.reddit.com/dev/api#listings>.
* - showone of (given)
* - sortone of (hot, new, top, controversial)
* - tone of (hour, day, week, month, year, all)
* - usernamethe name of an existing user
* - afterfullname <https://www.reddit.com/dev/api#fullnames> of a thing
* - beforefullname <https://www.reddit.com/dev/api#fullnames> of a thing
* - counta positive integer (default: 0)
* - limitthe maximum number of items desired (default: 25, maximum: 100)
* - sr_detail(optional) expand subreddits
**/
fun OAuthClient.getUserUsernameSubmitted(username: String, show: String?, sort: String?, t: String?, after: String?, before: String?, count: Int?, limit: Int?, srDetail: Boolean?) =
retry(3) { requestApi("/user/$username/submitted",
"show" to show,
"sort" to sort,
"t" to t,
"username" to username,
"after" to after,
"before" to before,
"count" to count,
"limit" to limit,
"sr_detail" to srDetail).get().readEntity(String::class.java) }
/*
* view code
* <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/listingcontroller.py#L890>
* # <https://www.reddit.com/dev/api#GET_user_{username}_{where}>GET /user/username
* /wherehistory <https://github.com/reddit/reddit/wiki/OAuth2>rss support
* <https://www.reddit.com/wiki/rss>
* * → /user/username/overview
* * → /user/username/submitted
* * → /user/username/comments
* * → /user/username/upvoted
* * → /user/username/downvoted
* * → /user/username/hidden
* * → /user/username/saved
* * → /user/username/gildedThis endpoint is a listing
* <https://www.reddit.com/dev/api#listings>.
* - showone of (given)
* - sortone of (hot, new, top, controversial)
* - tone of (hour, day, week, month, year, all)
* - usernamethe name of an existing user
* - afterfullname <https://www.reddit.com/dev/api#fullnames> of a thing
* - beforefullname <https://www.reddit.com/dev/api#fullnames> of a thing
* - counta positive integer (default: 0)
* - limitthe maximum number of items desired (default: 25, maximum: 100)
* - sr_detail(optional) expand subreddits
**/
fun OAuthClient.getUserUsernameComments(username: String, show: String?, sort: String?, t: String?, after: String?, before: String?, count: Int?, limit: Int?, srDetail: Boolean?) =
retry(3) { requestApi("/user/$username/comments",
"show" to show,
"sort" to sort,
"t" to t,
"username" to username,
"after" to after,
"before" to before,
"count" to count,
"limit" to limit,
"sr_detail" to srDetail).get().readEntity(String::class.java) }
/*
* view code
* <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/listingcontroller.py#L890>
* # <https://www.reddit.com/dev/api#GET_user_{username}_{where}>GET /user/username
* /wherehistory <https://github.com/reddit/reddit/wiki/OAuth2>rss support
* <https://www.reddit.com/wiki/rss>
* * → /user/username/overview
* * → /user/username/submitted
* * → /user/username/comments
* * → /user/username/upvoted
* * → /user/username/downvoted
* * → /user/username/hidden
* * → /user/username/saved
* * → /user/username/gildedThis endpoint is a listing
* <https://www.reddit.com/dev/api#listings>.
* - showone of (given)
* - sortone of (hot, new, top, controversial)
* - tone of (hour, day, week, month, year, all)
* - usernamethe name of an existing user
* - afterfullname <https://www.reddit.com/dev/api#fullnames> of a thing
* - beforefullname <https://www.reddit.com/dev/api#fullnames> of a thing
* - counta positive integer (default: 0)
* - limitthe maximum number of items desired (default: 25, maximum: 100)
* - sr_detail(optional) expand subreddits
**/
fun OAuthClient.getUserUsernameUpvoted(username: String, show: String?, sort: String?, t: String?, after: String?, before: String?, count: Int?, limit: Int?, srDetail: Boolean?) =
retry(3) { requestApi("/user/$username/upvoted",
"show" to show,
"sort" to sort,
"t" to t,
"username" to username,
"after" to after,
"before" to before,
"count" to count,
"limit" to limit,
"sr_detail" to srDetail).get().readEntity(String::class.java) }
/*
* view code
* <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/listingcontroller.py#L890>
* # <https://www.reddit.com/dev/api#GET_user_{username}_{where}>GET /user/username
* /wherehistory <https://github.com/reddit/reddit/wiki/OAuth2>rss support
* <https://www.reddit.com/wiki/rss>
* * → /user/username/overview
* * → /user/username/submitted
* * → /user/username/comments
* * → /user/username/upvoted
* * → /user/username/downvoted
* * → /user/username/hidden
* * → /user/username/saved
* * → /user/username/gildedThis endpoint is a listing
* <https://www.reddit.com/dev/api#listings>.
* - showone of (given)
* - sortone of (hot, new, top, controversial)
* - tone of (hour, day, week, month, year, all)
* - usernamethe name of an existing user
* - afterfullname <https://www.reddit.com/dev/api#fullnames> of a thing
* - beforefullname <https://www.reddit.com/dev/api#fullnames> of a thing
* - counta positive integer (default: 0)
* - limitthe maximum number of items desired (default: 25, maximum: 100)
* - sr_detail(optional) expand subreddits
**/
fun OAuthClient.getUserUsernameDownvoted(username: String, show: String?, sort: String?, t: String?, after: String?, before: String?, count: Int?, limit: Int?, srDetail: Boolean?) =
retry(3) { requestApi("/user/$username/downvoted",
"show" to show,
"sort" to sort,
"t" to t,
"username" to username,
"after" to after,
"before" to before,
"count" to count,
"limit" to limit,
"sr_detail" to srDetail).get().readEntity(String::class.java) }
/*
* view code
* <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/listingcontroller.py#L890>
* # <https://www.reddit.com/dev/api#GET_user_{username}_{where}>GET /user/username
* /wherehistory <https://github.com/reddit/reddit/wiki/OAuth2>rss support
* <https://www.reddit.com/wiki/rss>
* * → /user/username/overview
* * → /user/username/submitted
* * → /user/username/comments
* * → /user/username/upvoted
* * → /user/username/downvoted
* * → /user/username/hidden
* * → /user/username/saved
* * → /user/username/gildedThis endpoint is a listing
* <https://www.reddit.com/dev/api#listings>.
* - showone of (given)
* - sortone of (hot, new, top, controversial)
* - tone of (hour, day, week, month, year, all)
* - usernamethe name of an existing user
* - afterfullname <https://www.reddit.com/dev/api#fullnames> of a thing
* - beforefullname <https://www.reddit.com/dev/api#fullnames> of a thing
* - counta positive integer (default: 0)
* - limitthe maximum number of items desired (default: 25, maximum: 100)
* - sr_detail(optional) expand subreddits
**/
fun OAuthClient.getUserUsernameHidden(username: String, show: String?, sort: String?, t: String?, after: String?, before: String?, count: Int?, limit: Int?, srDetail: Boolean?) =
retry(3) { requestApi("/user/$username/hidden",
"show" to show,
"sort" to sort,
"t" to t,
"username" to username,
"after" to after,
"before" to before,
"count" to count,
"limit" to limit,
"sr_detail" to srDetail).get().readEntity(String::class.java) }
/*
* view code
* <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/listingcontroller.py#L890>
* # <https://www.reddit.com/dev/api#GET_user_{username}_{where}>GET /user/username
* /wherehistory <https://github.com/reddit/reddit/wiki/OAuth2>rss support
* <https://www.reddit.com/wiki/rss>
* * → /user/username/overview
* * → /user/username/submitted
* * → /user/username/comments
* * → /user/username/upvoted
* * → /user/username/downvoted
* * → /user/username/hidden
* * → /user/username/saved
* * → /user/username/gildedThis endpoint is a listing
* <https://www.reddit.com/dev/api#listings>.
* - showone of (given)
* - sortone of (hot, new, top, controversial)
* - tone of (hour, day, week, month, year, all)
* - usernamethe name of an existing user
* - afterfullname <https://www.reddit.com/dev/api#fullnames> of a thing
* - beforefullname <https://www.reddit.com/dev/api#fullnames> of a thing
* - counta positive integer (default: 0)
* - limitthe maximum number of items desired (default: 25, maximum: 100)
* - sr_detail(optional) expand subreddits
**/
fun OAuthClient.getUserUsernameSaved(username: String, show: String?, sort: String?, t: String?, after: String?, before: String?, count: Int?, limit: Int?, srDetail: Boolean?) =
retry(3) { requestApi("/user/$username/saved",
"show" to show,
"sort" to sort,
"t" to t,
"username" to username,
"after" to after,
"before" to before,
"count" to count,
"limit" to limit,
"sr_detail" to srDetail).get().readEntity(String::class.java) }
/*
* view code
* <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/listingcontroller.py#L890>
* # <https://www.reddit.com/dev/api#GET_user_{username}_{where}>GET /user/username
* /wherehistory <https://github.com/reddit/reddit/wiki/OAuth2>rss support
* <https://www.reddit.com/wiki/rss>
* * → /user/username/overview
* * → /user/username/submitted
* * → /user/username/comments
* * → /user/username/upvoted
* * → /user/username/downvoted
* * → /user/username/hidden
* * → /user/username/saved
* * → /user/username/gildedThis endpoint is a listing
* <https://www.reddit.com/dev/api#listings>.
* - showone of (given)
* - sortone of (hot, new, top, controversial)
* - tone of (hour, day, week, month, year, all)
* - usernamethe name of an existing user
* - afterfullname <https://www.reddit.com/dev/api#fullnames> of a thing
* - beforefullname <https://www.reddit.com/dev/api#fullnames> of a thing
* - counta positive integer (default: 0)
* - limitthe maximum number of items desired (default: 25, maximum: 100)
* - sr_detail(optional) expand subreddits
**/
fun OAuthClient.getUserUsernameGilded(username: String, show: String?, sort: String?, t: String?, after: String?, before: String?, count: Int?, limit: Int?, srDetail: Boolean?) =
retry(3) { requestApi("/user/$username/gilded",
"show" to show,
"sort" to sort,
"t" to t,
"username" to username,
"after" to after,
"before" to before,
"count" to count,
"limit" to limit,
"sr_detail" to srDetail).get().readEntity(String::class.java) }
/*
* view code
* <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/wiki.py#L452>#
* <https://www.reddit.com/dev/api#POST_api_wiki_alloweditor_{act}>POST [/r/
* subreddit]/api/wiki/alloweditor/actmodwiki
* <https://github.com/reddit/reddit/wiki/OAuth2>
* * → [/r/subreddit]/api/wiki/alloweditor/del
* * → [/r/subreddit]/api/wiki/alloweditor/addAllow/deny username to edit this
* wikipage
* - actone of (del, add)
* - pagethe name of an existing wiki page
* - uh / X-Modhash headera modhash <https://www.reddit.com/dev/api#modhashes>
* - usernamethe name of an existing user
**/
fun OAuthClient.postRSubredditWikiAlloweditorAct(subreddit: String, act: String, vararg urlParams: Pair<String, Any?>) =
retry(3) { requestApi("/r/$subreddit/api/wiki/alloweditor/$act").post(urlParams.multipart()).readEntity(String::class.java) }
/*
* view code
* <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/wiki.py#L452>#
* <https://www.reddit.com/dev/api#POST_api_wiki_alloweditor_{act}>POST [/r/
* subreddit]/api/wiki/alloweditor/actmodwiki
* <https://github.com/reddit/reddit/wiki/OAuth2>
* * → [/r/subreddit]/api/wiki/alloweditor/del
* * → [/r/subreddit]/api/wiki/alloweditor/addAllow/deny username to edit this
* wikipage
* - actone of (del, add)
* - pagethe name of an existing wiki page
* - uh / X-Modhash headera modhash <https://www.reddit.com/dev/api#modhashes>
* - usernamethe name of an existing user
**/
fun OAuthClient.postRSubredditWikiAlloweditorDel(subreddit: String, vararg urlParams: Pair<String, Any?>) =
retry(3) { requestApi("/r/$subreddit/api/wiki/alloweditor/del").post(urlParams.multipart()).readEntity(String::class.java) }
/*
* view code
* <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/wiki.py#L452>#
* <https://www.reddit.com/dev/api#POST_api_wiki_alloweditor_{act}>POST [/r/
* subreddit]/api/wiki/alloweditor/actmodwiki
* <https://github.com/reddit/reddit/wiki/OAuth2>
* * → [/r/subreddit]/api/wiki/alloweditor/del
* * → [/r/subreddit]/api/wiki/alloweditor/addAllow/deny username to edit this
* wikipage
* - actone of (del, add)
* - pagethe name of an existing wiki page
* - uh / X-Modhash headera modhash <https://www.reddit.com/dev/api#modhashes>
* - usernamethe name of an existing user
**/
fun OAuthClient.postRSubredditWikiAlloweditorAdd(subreddit: String, vararg urlParams: Pair<String, Any?>) =
retry(3) { requestApi("/r/$subreddit/api/wiki/alloweditor/add").post(urlParams.multipart()).readEntity(String::class.java) }
/*
* view code
* <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/wiki.py#L376>#
* <https://www.reddit.com/dev/api#POST_api_wiki_edit>POST [/r/subreddit
* ]/api/wiki/editwikiedit <https://github.com/reddit/reddit/wiki/OAuth2>
* - Edit a wiki page
* - contentpagethe name of an existing page or a new page to create
* - previousthe starting point revision for this edit
* - reasona string up to 256 characters long, consisting of printable characters.
* - uh / X-Modhash headera modhash <https://www.reddit.com/dev/api#modhashes>
**/
fun OAuthClient.postRSubredditWikiEdit(subreddit: String, vararg urlParams: Pair<String, Any?>) =
retry(3) { requestApi("/r/$subreddit/api/wiki/edit").post(urlParams.multipart()).readEntity(String::class.java) }
/*
* view code
* <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/wiki.py#L493>#
* <https://www.reddit.com/dev/api#POST_api_wiki_hide>POST [/r/subreddit
* ]/api/wiki/hidemodwiki <https://github.com/reddit/reddit/wiki/OAuth2>
* - Toggle the public visibility of a wiki page revision
* - pagethe name of an existing wiki page
* - revisiona wiki revision ID
* - uh / X-Modhash headera modhash <https://www.reddit.com/dev/api#modhashes>
**/
fun OAuthClient.postRSubredditWikiHide(subreddit: String, vararg urlParams: Pair<String, Any?>) =
retry(3) { requestApi("/r/$subreddit/api/wiki/hide").post(urlParams.multipart()).readEntity(String::class.java) }
/*
* view code
* <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/wiki.py#L508>#
* <https://www.reddit.com/dev/api#POST_api_wiki_revert>POST [/r/subreddit
* ]/api/wiki/revertmodwiki <https://github.com/reddit/reddit/wiki/OAuth2>
* - Revert a wiki page to revision
* - pagethe name of an existing wiki page
* - revisiona wiki revision ID
* - uh / X-Modhash headera modhash <https://www.reddit.com/dev/api#modhashes>
**/
fun OAuthClient.postRSubredditWikiRevert(subreddit: String, vararg urlParams: Pair<String, Any?>) =
retry(3) { requestApi("/r/$subreddit/api/wiki/revert").post(urlParams.multipart()).readEntity(String::class.java) }
/*
* view code
* <https://github.com/reddit/reddit/blob/master/r2/r2/lib/validator/validator.py#L200>
* # <https://www.reddit.com/dev/api#GET_wiki_discussions_{page}>GET [/r/subreddit
* ]/wiki/discussions/pagewikiread <https://github.com/reddit/reddit/wiki/OAuth2>
* - Retrieve a list of discussions about this wiki page
* - This endpoint is a listing <https://www.reddit.com/dev/api#listings>.
* - afterfullname <https://www.reddit.com/dev/api#fullnames> of a thing
* - beforefullname <https://www.reddit.com/dev/api#fullnames> of a thing
* - counta positive integer (default: 0)
* - limitthe maximum number of items desired (default: 25, maximum: 100)
* - pagethe name of an existing wiki page
* - show(optional) the string all
* - sr_detail(optional) expand subreddits
**/
fun OAuthClient.getRSubredditWikiDiscussionsPage(subreddit: String, page: String, after: String?, before: String?, count: Int?, limit: Int?, show: String?, srDetail: Boolean?) =
retry(3) { requestApi("/r/$subreddit/wiki/discussions/$page",
"after" to after,
"before" to before,
"count" to count,
"limit" to limit,
"page" to page,
"show" to show,
"sr_detail" to srDetail).get().readEntity(String::class.java) }
/*
* view code
* <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/wiki.py#L258>#
* <https://www.reddit.com/dev/api#GET_wiki_pages>GET [/r/subreddit]/wiki/pages
* wikiread <https://github.com/reddit/reddit/wiki/OAuth2>
* - Retrieve a list of wiki pages in this subreddit
**/
fun OAuthClient.getRSubredditWikiPages(subreddit: String) =
retry(3) { requestApi("/r/$subreddit/wiki/pages").get().readEntity(String::class.java) }
/*
* view code
* <https://github.com/reddit/reddit/blob/master/r2/r2/lib/validator/validator.py#L200>
* # <https://www.reddit.com/dev/api#GET_wiki_revisions>GET [/r/subreddit
* ]/wiki/revisionswikiread <https://github.com/reddit/reddit/wiki/OAuth2>
* - Retrieve a list of recently changed wiki pages in this subreddit
* - afterfullname <https://www.reddit.com/dev/api#fullnames> of a thing
* - beforefullname <https://www.reddit.com/dev/api#fullnames> of a thing
* - counta positive integer (default: 0)
* - limitthe maximum number of items desired (default: 25, maximum: 100)
* - show(optional) the string all
* - sr_detail(optional) expand subreddits
**/
fun OAuthClient.getRSubredditWikiRevisions(subreddit: String, after: String?, before: String?, count: Int?, limit: Int?, show: String?, srDetail: Boolean?) =
retry(3) { requestApi("/r/$subreddit/wiki/revisions",
"after" to after,
"before" to before,
"count" to count,
"limit" to limit,
"show" to show,
"sr_detail" to srDetail).get().readEntity(String::class.java) }
/*
* view code
* <https://github.com/reddit/reddit/blob/master/r2/r2/lib/validator/validator.py#L200>
* # <https://www.reddit.com/dev/api#GET_wiki_revisions_{page}>GET [/r/subreddit
* ]/wiki/revisions/pagewikiread <https://github.com/reddit/reddit/wiki/OAuth2>
* - Retrieve a list of revisions of this wiki page
* - This endpoint is a listing <https://www.reddit.com/dev/api#listings>.
* - afterfullname <https://www.reddit.com/dev/api#fullnames> of a thing
* - beforefullname <https://www.reddit.com/dev/api#fullnames> of a thing
* - counta positive integer (default: 0)
* - limitthe maximum number of items desired (default: 25, maximum: 100)
* - pagethe name of an existing wiki page
* - show(optional) the string all
* - sr_detail(optional) expand subreddits
**/
fun OAuthClient.getRSubredditWikiRevisionsPage(subreddit: String, page: String, after: String?, before: String?, count: Int?, limit: Int?, show: String?, srDetail: Boolean?) =
retry(3) { requestApi("/r/$subreddit/wiki/revisions/$page",
"after" to after,
"before" to before,
"count" to count,
"limit" to limit,
"page" to page,
"show" to show,
"sr_detail" to srDetail).get().readEntity(String::class.java) }
/*
* view code
* <https://github.com/reddit/reddit/blob/master/r2/r2/lib/validator/validator.py#L200>
* # <https://www.reddit.com/dev/api#GET_wiki_settings_{page}>GET [/r/subreddit
* ]/wiki/settings/pagemodwiki <https://github.com/reddit/reddit/wiki/OAuth2>
* - Retrieve the current permission settings for page
* - pagethe name of an existing wiki page
**/
fun OAuthClient.getRSubredditWikiSettingsPage(subreddit: String, page: String) =
retry(3) { requestApi("/r/$subreddit/wiki/settings/$page",
"page" to page).get().readEntity(String::class.java) }
/*
* view code
* <https://github.com/reddit/reddit/blob/master/r2/r2/lib/validator/validator.py#L200>
* # <https://www.reddit.com/dev/api#POST_wiki_settings_{page}>POST [/r/subreddit
* ]/wiki/settings/pagemodwiki <https://github.com/reddit/reddit/wiki/OAuth2>
* - Update the permissions and visibility of wiki page
* - listedboolean value
* - pagethe name of an existing wiki page
* - permlevelan integer
* - uh / X-Modhash headera modhash <https://www.reddit.com/dev/api#modhashes>
**/
fun OAuthClient.postRSubredditWikiSettingsPage(subreddit: String, page: String, vararg urlParams: Pair<String, Any?>) =
retry(3) { requestApi("/r/$subreddit/wiki/settings/$page").post(urlParams.multipart()).readEntity(String::class.java) }
/*
* view code
* <https://github.com/reddit/reddit/blob/master/r2/r2/lib/validator/validator.py#L200>
* # <https://www.reddit.com/dev/api#GET_wiki_{page}>GET [/r/subreddit]/wiki/page
* wikiread <https://github.com/reddit/reddit/wiki/OAuth2>
* - Return the content of a wiki page
* - If v is given, show the wiki page as it was at that version If both v and v2
* are given, show a diff of the two
* - pagethe name of an existing wiki page
* - va wiki revision ID
* - v2a wiki revision ID
**/
fun OAuthClient.getRSubredditWikiPage(subreddit: String, page: String, v: String?, v2: String?) =
retry(3) { requestApi("/r/$subreddit/wiki/$page",
"page" to page,
"v" to v,
"v2" to v2).get().readEntity(String::class.java) }
// Generated API end.
| apache-2.0 | f0b72cd23b4c94ff051661c458d6eb5d | 48.982763 | 272 | 0.678875 | 3.410569 | false | false | false | false |
code-disaster/lwjgl3 | modules/generator/src/main/kotlin/org/lwjgl/generator/Functions.kt | 3 | 94489 | /*
* Copyright LWJGL. All rights reserved.
* License terms: https://www.lwjgl.org/license
*/
package org.lwjgl.generator
import org.lwjgl.generator.GenerationMode.*
import java.io.*
/*
****
The code below implements the more complex parts of LWJGL's code generation.
Please only modify if you fully understand what's going on.
****
The basic generation is relatively straightforward. It's an almost 1-to-1 mapping
of the native function signature to the proper Java -> JNI -> native function code.
We then try to generate additional Java methods that make the user's life easier. We
use the TemplateModifiers on the function signature parameters and return values to figure
out what kind of Transforms we should apply. Depending on the modifiers, we may generate
one or more additional methods.
*/
// Global definitions
internal const val ADDRESS = "address()"
const val RESULT = "__result"
internal const val ANONYMOUS = "*" // invalid character in Java identifiers
internal const val POINTER_POSTFIX = "Address"
internal const val MAP_OLD = "old_buffer"
internal const val MAP_LENGTH = "length"
const val FUNCTION_ADDRESS = "__functionAddress"
internal const val JNIENV = "__env"
/** Special parameter that generates an explicit function address parameter. */
val EXPLICIT_FUNCTION_ADDRESS = Parameter(opaque_p, FUNCTION_ADDRESS, "the function address")
/** Special parameter that will accept the JNI function's JNIEnv* parameter. Hidden in Java code. */
val JNI_ENV = Parameter("JNIEnv".opaque.p, JNIENV, "the JNI environment struct")
private val TRY_FINALLY_RESULT_REFERENCE = """(?<=^|\W)$RESULT(?=\W|$)""".toRegex()
private val TRY_FINALLY_ALIGN = "^(\\s+)".toRegex(RegexOption.MULTILINE)
enum class GenerationMode {
NORMAL,
ALTERNATIVE
}
// --- [ Native class functions ] ---
class Func(
val returns: ReturnValue,
val simpleName: String,
val name: String,
val documentation: ((Parameter) -> Boolean) -> String,
val nativeClass: NativeClass,
vararg val parameters: Parameter
) : ModifierTarget<FunctionModifier>() {
private val paramMap = HashMap<String, Parameter>()
init {
for (param in parameters)
paramMap[param.name] = param
validate()
}
private val hasNativeParams = getNativeParams().any()
fun getParam(paramName: String) = paramMap[paramName] ?: throw IllegalArgumentException("Referenced parameter does not exist: $simpleName.$paramName")
inline fun getParams(crossinline predicate: (Parameter) -> Boolean) = parameters.asSequence().filter {
predicate(it)
}
private inline fun getParam(crossinline predicate: (Parameter) -> Boolean) = getParams(predicate).single()
internal inline fun hasParam(crossinline predicate: (Parameter) -> Boolean) = getParams(predicate).any()
private fun getNativeParams(
withExplicitFunctionAddress: Boolean = true,
withJNIEnv: Boolean = false,
withAutoSizeResultParams: Boolean = true
) = parameters.asSequence()
.let { p -> if (withExplicitFunctionAddress) p else p.filter { it !== EXPLICIT_FUNCTION_ADDRESS } }
.let { p -> if (withJNIEnv) p else p.filter { it !== JNI_ENV } }
.let { p -> if (withAutoSizeResultParams)
p.filter { !it.has<Virtual>() }
else
p.filter { !((it.has<Virtual>() && !it.has<AutoSizeResultParam>()) || (it.isAutoSizeResultOut && hideAutoSizeResultParam)) }
}
/** Returns a parameter that has the specified ReferenceModifier with the specified reference. Returns null if no such parameter exists. */
internal inline fun <reified T> getReferenceParam(reference: String)
where T : ParameterModifier,
T : ReferenceModifier = parameters.asSequence().firstOrNull {
it.has<T>(reference)
} // Assumes at most 1 parameter will be found that references the specified parameter
override fun validate(modifier: FunctionModifier) = modifier.validate(this)
internal fun copyModifiers(other: Func): Func {
if (other.hasModifiers())
this._modifiers = HashMap(other.modifiers)
return this
}
val functionAddress get() = if (has<NativeName>()) get<NativeName>().name else "\"${this.name}\""
val nativeName get() = if (has<NativeName> { !nativeName.contains(' ') }) get<NativeName>().nativeName else this.name
private val accessModifier
get() = (if (has<AccessModifier>()) get<AccessModifier>().access else nativeClass.access).modifier
private fun stripPostfix(functionName: String = name): String {
if (!hasNativeParams)
return functionName
val param = parameters[parameters.lastIndex]
if (!param.isBufferPointer)
return functionName
var name = functionName
var postfix = (if (has<DependsOn>()) get<DependsOn>().postfix else null) ?: nativeClass.postfix
if (name.endsWith(postfix))
name = name.substring(0, name.length - postfix.length)
else
postfix = ""
return (if (name.endsWith("v"))
name.substring(0, name.length - (if (name.endsWith("_v")) 2 else 1))
else
name) + postfix
}
val javaDocLink
get() = "#${this.simpleName}()"
private val hasFunctionAddressParam: Boolean by lazy(LazyThreadSafetyMode.NONE) {
nativeClass.binding != null && (nativeClass.binding.apiCapabilities !== APICapabilities.JNI_CAPABILITIES || hasParam { it.nativeType is ArrayType<*> })
}
internal val hasExplicitFunctionAddress
get() = this.parameters.isNotEmpty() && this.parameters.last() === EXPLICIT_FUNCTION_ADDRESS
private val hasNativeCode
get() = (has<Code> { nativeBeforeCall != null || nativeCall != null || nativeAfterCall != null }) || this.parameters.contains(JNI_ENV)
internal val hasCustomJNIWithIgnoreAddress get() = (this.returns.isStructValue || hasNativeCode) && (!has<Macro> { expression != null })
internal val hasCustomJNI: Boolean by lazy(LazyThreadSafetyMode.NONE) {
(!hasFunctionAddressParam || hasNativeCode || ((nativeClass.module.library != null || nativeClass.module.key.startsWith("core.")) && (returns.isStructValue || hasParam { it.nativeType is StructType }))) && !has<Macro> { expression != null }
}
private val isNativeOnly: Boolean by lazy(LazyThreadSafetyMode.NONE) {
(nativeClass.binding == null || nativeClass.binding.apiCapabilities === APICapabilities.JNI_CAPABILITIES) &&
!(
modifiers.any { it.value.isSpecial }
|| this.returns.isSpecial
|| hasParam { it.isSpecial }
|| has<NativeName>()
|| (has<Macro> { expression != null })
)
}
private val hasUnsafeMethod by lazy(LazyThreadSafetyMode.NONE) {
hasFunctionAddressParam
&& !(hasExplicitFunctionAddress && hasNativeCode)
&& (this.returns.hasUnsafe || hasParam { it.hasUnsafe || it has MapToInt })
&& !has<Address>()
&& !hasParam { it.nativeType is ArrayType<*> }
&& (!has<Macro> { expression != null })
}
internal val hasArrayOverloads
get() = !has<OffHeapOnly>() && this.parameters
.count { it.isAutoSizeResultOut }
.let { autoSizeResultOutParams -> this.parameters.asSequence().any { it.has<MultiType>() || it.isArrayParameter(autoSizeResultOutParams) } }
private val ReturnValue.javaMethodType
get() = this.nativeType.let {
if (it is PointerType<*>) {
if (it.elementType is StructType && hasParam { param -> param.has<AutoSizeResultParam>() })
"${it.javaMethodType}.Buffer"
else if (it is FunctionType)
it.className
else
it.javaMethodType
} else
it.javaMethodType
}
private val ReturnValue.nativeMethodType
get() = if (this.isStructValue) "void" else this.nativeType.nativeMethodType
private val ReturnValue.jniFunctionType
get() = if (this.isStructValue) "void" else this.nativeType.jniFunctionType
internal val returnsNull
get() = !(has(Nonnull) || has(Address) || has<Macro> { !function })
private inline fun <reified T> hasReference(reference: Parameter): (Parameter) -> Boolean
where T : ParameterModifier,
T : ReferenceModifier = { it.has<T> { hasReference(reference.name) } }
private inline fun <reified T> hasReferenceFor(reference: Parameter)
where T : ParameterModifier,
T : ReferenceModifier = hasParam(hasReference<T>(reference))
internal fun hasAutoSizeFor(reference: Parameter) = hasReferenceFor<AutoSize>(reference)
internal val hideAutoSizeResultParam = returns.nativeType is PointerType<*> && getParams { it.isAutoSizeResultOut }.count() == 1
private fun Parameter.error(msg: String) {
throw IllegalArgumentException("$msg [${nativeClass.className}.${[email protected]}, parameter: ${this.name}]")
}
private fun Parameter.asJavaMethodParam(annotate: Boolean) =
(
if (nativeType is PointerType<*> && nativeType.elementType is StructType && (has<Check>() || has<Unsafe>() || getReferenceParam<AutoSize>(name) != null))
"$javaMethodType.Buffer"
else if (nativeType is ArrayType<*>)
"${nativeType.mapping.primitive}[]"
else if (has<MapToInt>())
"int"
else
javaMethodType
).let {
if (annotate) {
nativeType.annotate(it).let { annotatedType ->
if (nativeType.isReference && has(nullable)) {
"@Nullable $annotatedType"
} else {
annotatedType
}
}
} else {
it
}
}.let {
"$it $name"
}
private fun Parameter.asNativeMethodParam(nativeOnly: Boolean) =
(if (nativeType is ArrayType<*>)
"${nativeType.mapping.primitive}[]"
else
nativeType.nativeMethodType
).let {
if (nativeOnly) {
"${nativeType.annotate(it)} $name"
} else {
"$it $name"
}
}
private fun Parameter.asNativeMethodArgument(mode: GenerationMode) = when {
nativeType.dereference is StructType || nativeType is WrappedPointerType
->
if (has(nullable))
"memAddressSafe($name)"
else if (nativeType is WrappedPointerType && hasUnsafeMethod && nativeClass.binding!!.apiCapabilities === APICapabilities.PARAM_CAPABILITIES)
name
else
"$name.$ADDRESS"
nativeType.isPointerData ->
if (nativeType is ArrayType<*>)
name
else if (!isAutoSizeResultOut && (has(nullable) || (has(optional) && mode === NORMAL)))
"memAddressSafe($name)"
else
"memAddress($name)"
nativeType.mapping === PrimitiveMapping.BOOLEAN4 -> "$name ? 1 : 0"
has<MapToInt>() -> if (nativeType.mapping === PrimitiveMapping.BYTE) "(byte)$name" else "(short)$name"
else -> name
}
private val Parameter.isFunctionProvider
get() = nativeType is WrappedPointerType && nativeClass.binding != null && nativeClass.binding.apiCapabilities === APICapabilities.PARAM_CAPABILITIES && !has(nullable)
/** Validates parameters with modifiers that reference other parameters. */
private fun validate() {
returns.nativeType.let {
if (it is StructType)
it.definition.setUsageOutput()
else if (it is PointerType<*> && it.elementType is StructType)
it.elementType.definition.setUsageResultPointer()
}
var returnCount = 0
val autoSizeReferences = HashSet<String>()
parameters.forEachIndexed { i, it ->
it.nativeType.dereference.let { type ->
if (type is StructType) {
if (it.isInput)
type.definition.setUsageInput()
else
type.definition.setUsageOutput()
}
}
if (it === EXPLICIT_FUNCTION_ADDRESS && i != parameters.lastIndex)
it.error("The explicit function address parameter must be the last parameter.")
if (it.has<Check>()) {
val checkReference = paramMap[it.get<Check>().expression]
if (checkReference != null) {
if (checkReference.nativeType !is IntegerType) {
it.error("The Check expression refers to an invalid parameter: ${checkReference.name}")
}
}
}
if (it.has<AutoSize>()) {
val autoSize = it.get<AutoSize>()
val nullableReference = paramMap[autoSize.reference]?.has(nullable) ?: false
(sequenceOf(autoSize.reference) + autoSize.dependent.asSequence()).forEach { reference ->
if (autoSizeReferences.contains(reference))
it.error("An AutoSize reference already exists for: $reference")
autoSizeReferences.add(reference)
val bufferParam = paramMap[reference]
if (bufferParam == null)
it.error("Buffer reference does not exist: AutoSize($reference)")
else {
when {
!bufferParam.nativeType.isPointerData -> it.error("Buffer reference must be a data pointer: AutoSize($reference)")
nullableReference && !bufferParam.has(nullable)
-> it.error("If reference is nullable, dependent parameters must also be nullable: AutoSize($reference)")
}
if (bufferParam.nativeType is CharSequenceType && bufferParam.nativeType.charMapping == CharMapping.UTF16)
it.replaceModifier(nativeClass.AutoSize(2, autoSize.reference, *autoSize.dependent))
}
}
}
if (it.has<AutoSizeResultParam>()) {
if (!returns.nativeType.isPointerData)
it.error("Return type is not an array: AutoSizeResult")
}
if (it.isBufferPointer
&& it.nativeType !is CharSequenceType
&& !it.has<Check>()
&& !it.has<Unsafe>()
&& !hasAutoSizeFor(it)
&& !it.has<AutoSizeResultParam>()
&& !it.has<Terminated>()
) {
it.error("Data pointer not validated with Check/AutoSize/Terminated. If validation is not possible, use the Unsafe modifier.")
}
if (it.has<AutoType>()) {
val bufferParamName = it.get<AutoType>().reference
val bufferParam = paramMap[bufferParamName]
if (bufferParam == null)
it.error("Buffer reference does not exist: AutoType($bufferParamName)")
else when {
bufferParam.nativeType !is PointerType<*> -> it.error("Buffer reference must be a pointer type: AutoType($bufferParamName)")
bufferParam.nativeType.elementType !is VoidType -> it.error("Pointer reference must point to a void type: AutoType($bufferParamName)")
}
}
if (it.has<Return>()) {
returnCount++
if (1 < returnCount)
it.error("More than one return value found.")
val returnMod = it.get<Return>()
if (returnMod === ReturnParam) {
if (returns.isStructValue) {
if (returns.nativeType != it.nativeType)
it.error("The ReturnParam modifier can only be used on a struct value parameter if the function returns the same type.")
} else if (!returns.isVoid)
it.error("The ReturnParam modifier can only be used in functions with void return type.")
} else {
if (returnMod.lengthParam.startsWith(RESULT)) {
if (!returns.nativeType.mapping.let { it === PrimitiveMapping.INT || it === PrimitiveMapping.POINTER })
it.error("The Return modifier was used in a function with an unsupported return type")
if (!it.has<Check>()) {
if (!hasAutoSizeFor(it))
it.error("A Check or AutoSize for ReturnParam parameter does not exist")
else if (it.nativeType !is CharSequenceType)
it.error("Return parameters with AutoSize must have a CharSequence type")
} else if (it.get<Check>().expression != "1" || it.nativeType is CharSequenceType)
it.error("Return parameters with Check must be pointers to a single primitive value")
} else {
if (!returns.isVoid)
it.error("The Return modifier was used in a function with an unsupported return type")
if (!hasAutoSizeFor(it))
it.error("An AutoSize for Return parameter does not exist")
val lengthParam = paramMap[returnMod.lengthParam]
if (lengthParam == null)
it.error("The length parameter does not exist: Return(${returnMod.lengthParam})")
else if (!lengthParam.nativeType.isPointerSize)
it.error("The length parameter must be an integer pointer type: Return(${returnMod.lengthParam})")
}
}
}
if (it.has<PointerArray>()) {
if (!hasAutoSizeFor(it))
it.error("An AutoSize for PointerArray parameter does not exist")
val lengthsParamName = it.get<PointerArray>().lengthsParam
val lengthsParam = paramMap[lengthsParamName]
if (lengthsParam != null && !lengthsParam.nativeType.isPointerSize)
it.error("Lengths reference must be an integer pointer type: PointerArray($lengthsParamName)")
}
if (it.nativeType === va_list && i != parameters.lastIndex)
it.error("The va_list type can only be used on the last parameter of a function")
}
}
private fun PrintWriter.generateChecks(mode: GenerationMode, transforms: Map<QualifiedType, Transform>? = null) {
val checks = ArrayList<String>()
// Validate function address
if (hasFunctionAddressParam && (has<DependsOn>() || has<IgnoreMissing>() || (nativeClass.binding?.shouldCheckFunctionAddress(this@Func) == true)) && !hasUnsafeMethod)
checks.add("check($FUNCTION_ADDRESS);")
// We convert multi-byte-per-element buffers to ByteBuffer for NORMAL generation.
// So we need to scale the length check by the number of bytes per element.
fun bufferShift(expression: String, param: String, shift: String, transform: Transform?): String {
val nativeType = paramMap[param]!!.nativeType
val mapping =
if (transform != null && transform is AutoTypeTargetTransform) {
transform.autoType
} else
nativeType.mapping as PointerMapping
if (!mapping.isMultiByte)
return expression
val builder = StringBuilder(expression.length + 8)
if (expression.indexOf(' ') != -1) {
builder
.append('(')
.append(expression)
.append(')')
} else
builder.append(expression)
return builder
.append(' ')
.append(shift)
.append(' ')
.append(mapping.byteShift)
.toString()
}
// First pass
getNativeParams().forEach {
if (it.nativeType.mapping === PointerMapping.OPAQUE_POINTER) {
if (!it.has(nullable) && !hasUnsafeMethod && it.nativeType !is WrappedPointerType && transforms?.get(it) !is SkipCheckFunctionTransform)
checks.add("check(${it.name});")
return@forEach
}
var Safe = if (it.has<Nullable>()) "Safe" else ""
if (it.nativeType is CharSequenceType && !it.has<Check>() && !it.has<Unsafe>() && !hasAutoSizeFor(it) && transforms?.get(it) == null)
checks.add("checkNT${it.nativeType.charMapping.bytes}$Safe(${it.name});")
if (it.has<Terminated>()) {
val postfix = if ((it.nativeType.mapping as PointerMapping).isMultiByte) "" else "1"
checks.add("checkNT$postfix$Safe(${it.name}${it.get<Terminated>().let { terminated -> if (terminated === NullTerminated) "" else ", ${terminated.value}" }});")
}
if (it.has<Check>() && (!it.has<AutoSizeResultParam>() || !hideAutoSizeResultParam)) {
val check = it.get<Check>()
val transform = transforms?.get(it)
if (transform !is SkipCheckFunctionTransform) {
checks.add(when {
it.has<MultiType>() -> "check$Safe(${it.name}, ${bufferShift(check.expression, it.name, ">>", transform)});"
it.nativeType is StructType -> "check$Safe(${it.name}, ${bufferShift(check.expression, it.name, "<<", transform)});"
else -> "check$Safe(${it.name}, ${check.expression});"
}.let { code -> if (check.debug) "if (DEBUG) {\n$t$t$t$t$code\n$t$t$t}" else code})
}
}
if (it.has<AutoSize>()) {
val autoSize = it.get<AutoSize>()
if (mode === NORMAL || !it.isInput) {
var expression = it.name
if (!it.isInput) {
expression += if (it.nativeType is ArrayType<*>)
"[0]"
else
".get($expression.position())"
} else if (autoSize.factor != null)
expression = autoSize.factor.scaleInv(expression)
sequenceOf(autoSize.reference, *autoSize.dependent)
.map { reference ->
val bufferParam = paramMap[reference]!!
Safe = if (bufferParam.has<Nullable>()) "Safe" else ""
"check$Safe($reference, $expression);"
}
.let { expressions ->
if (it.has<Nullable>()) {
checks.add("if (${it.name} != null) { ${expressions.joinToString(" ")} }")
} else {
checks.addAll(expressions)
}
}
}
if (mode !== NORMAL) {
val reference = paramMap[autoSize.reference]!!
val referenceTransform = transforms!![reference]
val expression =
if (referenceTransform is SingleValueTransform || referenceTransform === PointerArrayTransformSingle) {
"1"
} else if (referenceTransform is PointerArrayTransform || reference.nativeType is ArrayType<*>) {
if (reference has nullable)
"lengthSafe(${autoSize.reference})"
else
"${autoSize.reference}.length"
} else {
if (reference has nullable)
"remainingSafe(${autoSize.reference})"
else
"${autoSize.reference}.remaining()"
}
autoSize.dependent.forEach { dependency ->
val param = paramMap[dependency]!!
val transform = transforms[param]
if (transform !is SkipCheckFunctionTransform) {
Safe = if (param.has<Nullable>() && transform !is PointerArrayTransform) "Safe" else ""
checks.add(if (transform === PointerArrayTransformArray)
"check$Safe($dependency, $expression);"
else
"check$Safe($dependency, $expression);")
}
}
}
}
}
// Second pass
getNativeParams()
.filter { it.isInput && it.nativeType.hasStructValidation && !hasUnsafeMethod }
.forEach {
// Do this after the AutoSize check
checks.add(
sequenceOf(
if (it.has<Check>()) it.get<Check>().expression else null,
getReferenceParam<AutoSize>(it.name).let { autoSize ->
if (autoSize == null)
null
else
transforms?.get(autoSize).let { transform ->
if (transform == null)
autoSize.name
else
@Suppress("UNCHECKED_CAST") (transform as FunctionTransform<Parameter>).transformCall(autoSize, autoSize.name)
}.let { name ->
if (autoSize.nativeType.mapping === PrimitiveMapping.INT || name.endsWith(".remaining()"))
name
else
"(int)$name"
}
}
)
.firstOrNull { size -> size != null }
.let { size ->
if (size == null)
"${it.nativeType.javaMethodType}.validate(${it.name}.address());"
else
"Struct.validate(${it.name}.address(), $size, ${it.nativeType.javaMethodType}.SIZEOF, ${it.nativeType.javaMethodType}::validate);"
}
.let { validation ->
if (it.has<Nullable>())
"if (${it.name} != null) { $validation }"
else
validation
}
)
}
// Third pass
getNativeParams().forEach {
// Special checks last
nativeClass.binding?.addParameterChecks(checks, mode, it) { transform ->
transforms?.get(this) === transform
}
}
if (checks.isEmpty())
return
println("$t${t}if (CHECKS) {")
checks.forEach {
print("$t$t$t")
println(it)
}
println("$t$t}")
}
/** This is where we start generating java code. */
internal fun generateMethods(writer: PrintWriter) {
val hasReuse = has<Reuse>()
val nativeOnly = isNativeOnly
val constantMacro = has<Macro> { constant }
if (hasCustomJNI && !(hasReuse && nativeOnly))
writer.generateNativeMethod(constantMacro, nativeOnly, hasReuse)
if (!nativeOnly || hasReuse) {
if (hasUnsafeMethod)
writer.generateUnsafeMethod(constantMacro, hasReuse)
if ((returns.nativeType !is CharSequenceType || has<Address>() || has<MustBeDisposed>()) && parameters.none { (it.has<AutoSize>() && it.isInput) || it.has<Expression> { skipNormal } })
writer.generateJavaMethod(constantMacro, hasReuse)
writer.generateAlternativeMethods()
}
if (constantMacro && !has(private)) {
writer.println()
writer.printDocumentation { true }
writer.println("$t${accessModifier}static final ${if (returns.nativeType is CharSequenceType) "String" else returns.javaMethodType} $name = $name(${
if (returns.nativeType !is StructType) "" else "${returns.nativeType.javaMethodType}.create()"
});")
}
}
// --[ JAVA METHODS ]--
private fun <T> PrintWriter.printList(items: Sequence<T>, itemPrint: (item: T) -> String?) = print(items.map(itemPrint).filterNotNull().joinToString(", "))
private fun PrintWriter.printUnsafeJavadoc(private: Boolean, verbose: Boolean = false) {
if (private)
return
val javadoc = documentation { it !== JNI_ENV }
if (javadoc.isEmpty()) {
if (verbose)
nativeClass.binding?.printCustomJavadoc(this, this@Func, javadoc)
return
}
if (verbose) {
if (nativeClass.binding?.printCustomJavadoc(this, this@Func, javadoc) != true)
println(javadoc)
} else if (hasParam { it.nativeType is ArrayType<*> } && !has<OffHeapOnly>()) {
println(nativeClass.processDocumentation("Array version of: ${nativeClass.className}#n$name()").toJavaDoc())
} else {
getNativeParams().filter {
it.documentation != null &&
(
it.has<AutoSize>() ||
it.has<AutoType>() ||
(it.isAutoSizeResultOut && hideAutoSizeResultParam)
// TODO: more?
)
}.let { hiddenParameters ->
val documentation = nativeClass.processDocumentation("Unsafe version of: $javaDocLink")
println(if (hiddenParameters.any())
nativeClass.toJavaDoc(documentation, hiddenParameters, returns.nativeType, "", null, "")
else
documentation.toJavaDoc()
)
}
}
}
private fun PrintWriter.generateNativeMethod(constantMacro: Boolean, nativeOnly: Boolean, hasReuse: Boolean) {
println()
printUnsafeJavadoc(constantMacro, nativeOnly)
if (returns.nativeType is JObjectType && returnsNull) {
println("$t@Nullable")
}
val retType = returns.nativeMethodType
if (nativeOnly) {
val retTypeAnnotation = returns.nativeType.annotation(retType)
if (retTypeAnnotation != null)
println("$t$retTypeAnnotation")
}
print("$t${if (constantMacro) "private " else accessModifier}static${if (hasReuse) "" else " native"} $retType ")
if (!nativeOnly) print('n')
print(name)
print("(")
val nativeParams = getNativeParams()
printList(nativeParams) {
it.asNativeMethodParam(nativeOnly)
}
if (hasFunctionAddressParam && !hasExplicitFunctionAddress) {
if (nativeParams.any()) print(", ")
print("long $FUNCTION_ADDRESS")
}
if (returns.isStructValue && !hasParam { it has ReturnParam }) {
if (nativeClass.binding != null || nativeParams.any()) print(", ")
print("long $RESULT")
}
if (hasReuse) {
print(") {\n$t$t")
if (retType != "void")
print("return ")
print("${get<Reuse>().source.className}.n$name(")
printList(nativeParams) {
it.name
}
if (hasFunctionAddressParam && !hasExplicitFunctionAddress) {
if (nativeParams.any()) print(", ")
print(FUNCTION_ADDRESS)
}
println(");\n$t}")
} else {
println(");")
}
}
private fun PrintWriter.generateUnsafeMethod(constantMacro: Boolean, hasReuse: Boolean) {
val customJNI = hasCustomJNI
val useLibFFI = !customJNI && (returns.isStructValue || hasParam { it.nativeType is StructType })
if (useLibFFI) {
println("""
private static final FFICIF ${name}CIF = apiCreateCIF(
${if (nativeClass.module.callingConvention == CallingConvention.DEFAULT) "FFI_DEFAULT_ABI" else "apiStdcall()"}, ${returns.nativeType.libffiType},
${parameters.joinToString(", ") { it.nativeType.libffiType }}
);""")
}
println()
printUnsafeJavadoc(constantMacro)
if (returns.nativeType is JObjectType && returnsNull) {
println("$t@Nullable")
}
print("$t${if (constantMacro) "private " else accessModifier}static ${returns.nativeMethodType} n$name(")
printList(getNativeParams()) {
if (it.isFunctionProvider)
it.asJavaMethodParam(false)
else
it.asNativeMethodParam(false)
}
if (returns.isStructValue && !hasParam { it has ReturnParam }) {
if ([email protected]) print(", ")
print("long $RESULT")
}
println(") {")
if (hasReuse) {
print("$t$t")
if (returns.nativeMethodType != "void") {
print("return ")
}
print("${get<Reuse>().source.className}.n$name(")
printList(getNativeParams()) {
it.name
}
println(");\n$t}")
return
}
val binding = nativeClass.binding!!
// Get function address
if (!hasExplicitFunctionAddress && !constantMacro)
binding.generateFunctionAddress(this, this@Func)
if (Module.CHECKS) {
// Basic checks
val checks = ArrayList<String>(4)
if (has<DependsOn>() || has<IgnoreMissing>() || binding.shouldCheckFunctionAddress(this@Func))
checks.add("check($FUNCTION_ADDRESS);")
getNativeParams().forEach {
if (it.nativeType.mapping === PointerMapping.OPAQUE_POINTER && !it.has(nullable) && it.nativeType !is WrappedPointerType)
checks.add("check(${it.name});")
else if (it.isInput && it.nativeType.hasStructValidation)
checks.add(
sequenceOf(
if (it.has<Check>()) it.get<Check>().expression else null,
getReferenceParam<AutoSize>(it.name).let { autoSize ->
autoSize?.name?.let { name ->
if (autoSize.nativeType.mapping === PrimitiveMapping.INT)
name
else
"(int)$name"
}
}
)
.firstOrNull { size -> size != null }
.let { size ->
if (size == null)
"${it.nativeType.javaMethodType}.validate(${it.name});"
else
"Struct.validate(${it.name}, $size, ${it.nativeType.javaMethodType}.SIZEOF, ${it.nativeType.javaMethodType}::validate);"
}
.let { validation ->
if (it.has<Nullable>())
"if (${it.name} != NULL) { $validation }"
else
validation
}
)
}
if (checks.isNotEmpty()) {
println("$t${t}if (CHECKS) {")
checks.forEach {
print("$t$t$t")
println(it)
}
println("$t$t}")
}
}
val hasReturnStatement = !(returns.isVoid || returns.isStructValue)
// Native method call
if (useLibFFI) {
// TODO: This implementation takes advantage of MemoryStack's automatic alignment. Could be precomputed + hardcoded for more efficiency.
// TODO: This implementation has not been tested with too many different signatures and probably contains bugs.
println("""$t${t}MemoryStack stack = stackGet(); int stackPointer = stack.getPointer();
try {
${if (hasReturnStatement) { """long __result = stack.n${when {
returns.nativeType.mapping == PrimitiveMapping.BOOLEAN -> "byte"
returns.nativeType is PointerType<*> -> "pointer"
else -> returns.nativeType.nativeMethodType
}}(0);
"""
} else ""}long arguments = stack.nmalloc(POINTER_SIZE, POINTER_SIZE * ${parameters.size});
${parameters.asSequence()
.withIndex()
.joinToString("\n$t$t$t") { (i, it) ->
"memPutAddress(arguments${when (i) {
0 -> ""
1 -> " + POINTER_SIZE"
else -> " + $i * POINTER_SIZE"
}}, ${
if (it.nativeType is StructType) {
it.name
} else {
"stack.n${when {
it.nativeType.mapping == PrimitiveMapping.BOOLEAN -> "byte"
it.nativeType is PointerType<*> -> "pointer"
else -> it.nativeType.nativeMethodType
}}(${it.name})"
}
});"
}
}
nffi_call(${name}CIF.address(), $FUNCTION_ADDRESS, ${if (returns.isVoid) "NULL" else "__result"}, arguments);${if (hasReturnStatement) {
"""
return memGet${when {
returns.nativeType.mapping == PrimitiveMapping.BOOLEAN -> "Byte"
returns.nativeType is PointerType<*> -> "Address"
else -> returns.nativeType.nativeMethodType.upperCaseFirst
}}(__result);"""
} else ""}
} finally {
stack.setPointer(stackPointer);
}""")
} else {
print("$t$t")
if (hasReturnStatement)
print("return ")
print(if (customJNI)
"n$name("
else
"${nativeClass.callingConvention.method}${getNativeParams(withExplicitFunctionAddress = false).map { it.nativeType.jniSignatureJava }.joinToString("")}${returns.nativeType.jniSignature}("
)
printList(getNativeParams()) {
if (it.isFunctionProvider)
"${it.name}.$ADDRESS"
else
it.name
}
if (!hasExplicitFunctionAddress) {
if (hasNativeParams) print(", ")
print(FUNCTION_ADDRESS)
}
if (returns.isStructValue && !hasParam { it has ReturnParam }) {
print(", ")
print(RESULT)
}
println(");")
}
println("$t}")
}
private fun PrintWriter.printDocumentation(parameterFilter: (Parameter) -> Boolean) {
val doc = documentation(parameterFilter)
val custom = nativeClass.binding?.printCustomJavadoc(this, this@Func, doc) ?: false
if (!custom && doc.isNotEmpty())
println(doc)
}
private fun PrintWriter.generateJavaMethod(constantMacro: Boolean, hasReuse: Boolean) {
println()
// JavaDoc
if (!constantMacro) {
val hideAutoSizeResult = parameters.count { it.isAutoSizeResultOut } == 1
printDocumentation {
!(hideAutoSizeResult && it.isAutoSizeResultOut)
}
}
// Method signature
if (returns.nativeType.isReference && returnsNull) {
println("$t@Nullable")
}
val retType = returns.javaMethodType
val retTypeAnnotation = returns.nativeType.annotation(retType)
if (retTypeAnnotation != null) {
println("$t$retTypeAnnotation")
}
print("$t${if (constantMacro) "private " else accessModifier}static ${if (has<MapPointer>() && returns.nativeType.dereference is StructType) "$retType.Buffer" else retType} $name(")
printList(getNativeParams(withAutoSizeResultParams = false)) {
it.asJavaMethodParam(true)
}
if (returns.isStructValue && !hasParam { it has ReturnParam }) {
if (parameters.isNotEmpty()) print(", ")
print("${returns.nativeType.annotate(retType)} $RESULT")
}
println(") {")
if (hasReuse) {
print("$t$t")
if (retType != "void") {
print("return ")
}
print("${get<Reuse>().source.className}.$name(")
printList(getNativeParams()) {
if (it.isAutoSizeResultOut && hideAutoSizeResultParam)
null
else
it.name
}
println(");\n$t}")
return
}
val hasArrays = hasParam { it.nativeType is ArrayType<*> }
val code = if (has<Code>()) get() else Code.NO_CODE
// Get function address
if (hasFunctionAddressParam && !hasUnsafeMethod && !hasExplicitFunctionAddress && !has<Macro>())
nativeClass.binding!!.generateFunctionAddress(this, this@Func)
// Generate checks
printCode(code.javaInit, false, hasArrays)
if (Module.CHECKS && !has<Macro>())
generateChecks(NORMAL)
// Prepare stack parameters
val hasStack = hideAutoSizeResultParam
if (hasStack) {
println("$t${t}MemoryStack stack = stackGet(); int stackPointer = stack.getPointer();")
val autoSizeParam = getParam { it.has<AutoSizeResultParam>() }
val autoSizeType = (autoSizeParam.nativeType.mapping as PointerMapping).mallocType
println("$t$t${autoSizeType}Buffer ${autoSizeParam.name} = stack.calloc$autoSizeType(1);")
}
val hasFinally = hasStack || code.hasStatements(code.javaFinally, false, hasArrays)
// Call the native method
generateCodeBeforeNative(code, false, hasArrays, hasFinally)
if (hasCustomJNI || !has<Address>()) {
generateNativeMethodCall(
code,
code.hasStatements(code.javaAfterNative, false, hasArrays),
hasStack || code.hasStatements(code.javaFinally, false, hasArrays)
) {
printList(getNativeParams()) {
it.asNativeMethodArgument(NORMAL)
}
}
}
generateCodeAfterNative(code, false, hasArrays, hasFinally)
if (returns.isStructValue) {
println("${if (hasFinally) "$t$t$t" else "$t$t"}return ${getParams { it has ReturnParam }.map { it.name }.singleOrNull() ?: RESULT};")
} else if (!returns.isVoid) {
if (returns.nativeType is PointerType<*> && returns.nativeType.mapping !== PointerMapping.OPAQUE_POINTER) {
if (hasFinally)
print(t)
print("$t${t}return ")
val isNullTerminated = returns.nativeType is CharSequenceType
print(
if (returns.nativeType.dereference is StructType) {
"${returns.nativeType.javaMethodType}.create"
} else {
"mem${if (isNullTerminated || returns.nativeType.elementType is VoidType)
"ByteBuffer"
else
returns.nativeType.mapping.javaMethodName}"
}
)
if (isNullTerminated) {
print("NT${(returns.nativeType as CharSequenceType).charMapping.bytes}")
}
if (returnsNull) {
print("Safe")
}
print("($RESULT")
if (has<MapPointer>())
get<MapPointer>().sizeExpression.let { expression ->
val castToInt =
paramMap[expression].run { this != null && nativeType.mapping !== PrimitiveMapping.INT }
||
expression.indexOf('(').run {
if (this == -1) false else expression.substring(0, this).run {
nativeClass.functions
.singleOrNull { it.nativeName == this }?.let { it.returns.nativeType.mapping !== PrimitiveMapping.INT } ?: false
}
}
print(", ${if (castToInt) "(int)" else ""}$expression")
}
else {
val hasAutoSizeResult = hasParam { it.has<AutoSizeResultParam>() }
if (!isNullTerminated || hasAutoSizeResult) {
if (hasAutoSizeResult) {
val params = getParams { it.has<AutoSizeResultParam>() }
val single = params.count() == 1
print(", ${params.map { getAutoSizeResultExpression(single, it) }.joinToString(" * ")}")
} else if (returns.nativeType.dereference !is StructType) {
if (has<Address>()) {
print(", 1")
} else {
throw IllegalStateException("No AutoSizeResult parameter could be found.")
}
}
}
}
println(");")
} else if (code.hasStatements(code.javaAfterNative, false, hasArrays)) {
if (hasFinally)
print(t)
println("$t${t}return $RESULT;")
}
}
generateCodeFinally(code, false, hasArrays, hasStack)
println("$t}")
}
private fun PrintWriter.printCode(statements: List<Code.Statement>, alternative: Boolean, arrays: Boolean, indent: String = "") {
if (statements.isEmpty())
return
statements
.filter { it.applyTo.filter(alternative, arrays) }
.forEach {
print(indent)
println(it.code)
}
}
private fun getAutoSizeResultExpression(single: Boolean, param: Parameter) =
if (param.isInput)
param.name.let {
val custom = param.get<AutoSizeResultParam>().expression
custom?.replace("\$original", it) ?: it.let { expression -> if (param.nativeType.mapping === PrimitiveMapping.INT) expression else "(int)$expression" }
}
else
when {
single -> "${param.name}.get(0)"
param.nativeType is ArrayType<*> -> "${param.name}[0]"
else -> "${param.name}.get(${param.name}.position())"
}.let {
val custom = param.get<AutoSizeResultParam>().expression
custom?.replace("\$original", it) ?: it.let { expression -> if (param.nativeType.mapping === PointerMapping.DATA_INT) expression else "(int)$expression" }
}
private fun PrintWriter.generateCodeBeforeNative(code: Code, alternative: Boolean, arrays: Boolean, hasFinally: Boolean) {
printCode(code.javaBeforeNative, alternative, arrays , "")
if (hasFinally) {
if (code.javaFinally.any { TRY_FINALLY_RESULT_REFERENCE.containsMatchIn(it.code) }) {
val returnsObject = returns.nativeType is WrappedPointerType
val returnType = if (returnsObject) (returns.nativeType as WrappedPointerType).className else returns.nativeMethodType
println("$t${t}$returnType $RESULT = ${if (returnsObject) "null" else "NULL"};") // TODO: support more types if necessary
}
println("$t${t}try {")
}
}
private fun PrintWriter.generateCodeAfterNative(code: Code, alternative: Boolean, arrays: Boolean, hasFinally: Boolean) {
printCode(code.javaAfterNative, alternative, arrays, if (hasFinally) t else "")
}
private fun PrintWriter.generateCodeFinally(code: Code, alternative: Boolean, arrays: Boolean, hasStack: Boolean) {
val finally = code.getStatements(code.javaFinally, alternative, arrays)
if (hasStack || finally.isNotEmpty()) {
println("$t$t} finally {")
finally.forEach {
println(it.code)
}
if (hasStack)
println("$t$t${t}stack.setPointer(stackPointer);")
println("$t$t}")
}
}
private fun PrintWriter.generateNativeMethodCall(
code: Code,
returnLater: Boolean,
hasFinally: Boolean,
printParams: PrintWriter.() -> Unit
) {
val returnsObject = returns.nativeType is WrappedPointerType
val returnType = if (returnsObject) (returns.nativeType as WrappedPointerType).className else returns.nativeMethodType
if (hasFinally)
print(t)
print("$t$t")
if (!(returns.isVoid || returns.isStructValue)) {
if (returnLater || returns.nativeType.isPointerData) {
if (!hasFinally || code.javaFinally.none { TRY_FINALLY_RESULT_REFERENCE.containsMatchIn(it.code) }) {
print("$returnType ")
}
print("$RESULT = ")
if (returnsObject)
print("$returnType.createSafe(")
} else {
print("return ")
if (returnsObject)
print("$returnType.createSafe(")
}
}
val macroExpression = if (has<Macro>()) get<Macro>().expression else null
if (hasUnsafeMethod) {
print("n$name(")
} else {
if (hasCustomJNI) {
if (!isNativeOnly) {
print('n')
}
print("$name(")
} else {
print(macroExpression ?: "${nativeClass.callingConvention.method}${getNativeParams(withExplicitFunctionAddress = false)
.map { it.nativeType.jniSignatureJava }
.joinToString("")
}${returns.nativeType.jniSignature}(")
}
}
if (macroExpression == null) {
printParams()
if (!hasUnsafeMethod && hasFunctionAddressParam && !hasExplicitFunctionAddress && !has<Macro>()) {
if (hasNativeParams) print(", ")
print(FUNCTION_ADDRESS)
}
if (returns.isStructValue && !hasParam { it has ReturnParam }) {
if (hasNativeParams) print(", ")
print("$RESULT.$ADDRESS")
}
print(")")
}
if (returnsObject) {
if (has<Construct>()) {
val construct = get<Construct>()
print(", ${construct.firstArg}")
for (arg in construct.otherArgs)
print(", $arg")
}
print(")")
}
if (returns.nativeType.mapping == PrimitiveMapping.BOOLEAN4)
print(" != 0")
println(";")
}
/** Alternative methods are generated by applying one or more transformations. */
private fun PrintWriter.generateAlternativeMethods() {
val transforms = LinkedHashMap<QualifiedType, Transform>()
nativeClass.binding?.generateAlternativeMethods(this, this@Func, transforms)
// Apply RawPointer transformations.
parameters.filter { it.has<RawPointer>() && it.nativeType !is ArrayType<*> }.let { params ->
if (params.isEmpty())
return@let
params.forEach {
transforms[it] = RawPointerTransform
}
generateAlternativeMethod(name, transforms)
params.forEach {
transforms.remove(it)
}
}
if (returns.nativeType is CharSequenceType && !has<Address>() && !has<MustBeDisposed>())
transforms[returns] = StringReturnTransform(returnsNull)
else if (has<MapPointer>()) {
val mapPointer = get<MapPointer>()
if (mapPointer.oldBufferOverloads) {
transforms[returns] = if (paramMap.containsKey(mapPointer.sizeExpression))
MapPointerExplicitTransform(mapPointer.sizeExpression, useOldBuffer = true, addParam = false)
else
MapPointerTransform(mapPointer.sizeExpression, useOldBuffer = true)
}
}
// Apply basic transformations
parameters.forEach {
if (it.has<AutoSize>() && it.isInput) {
val autoSize = it.get<AutoSize>()
val param = paramMap[autoSize.reference]!! // TODO: Check dependent too?
// Check if there's also an optional on the referenced parameter. Skip if so.
if (!(param has optional))
transforms[it] = AutoSizeTransform(param, hasCustomJNI || hasUnsafeMethod)
} else if (it has optional) {
transforms[it] = ExpressionTransform("NULL")
} else if (it.has<Expression>()) {
// We do this here in case another transform applies too.
// We overwrite the value with the expression but use the type of the other transform.
val expression = it.get<Expression>()
transforms[it] = ExpressionTransform(expression.value, expression.keepParam, @Suppress("UNCHECKED_CAST") (transforms[it] as FunctionTransform<Parameter>?))
}
}
// Check if we have any basic transformations to apply
if (transforms.isNotEmpty())
generateAlternativeMethod(name, transforms)
// Generate more complex alternatives if necessary
// The size expression may be an existing parameter, in which case we don't need an explicit size alternative.
if (has<MapPointer> { !paramMap.containsKey(sizeExpression) }) {
transforms[returns] = MapPointerExplicitTransform("length", get<MapPointer>().oldBufferOverloads)
generateAlternativeMethod(name, transforms)
}
// Apply any CharSequenceTransforms. These can be combined with any of the other transformations.
@Suppress("ReplaceSizeCheckWithIsNotEmpty")
if (parameters.count {
if (!it.isInput || it.nativeType !is CharSequenceType)
false
else {
val hasAutoSize = hasAutoSizeFor(it)
it.apply {
if (hasAutoSize)
getParams(hasReference<AutoSize>(this)).forEach { param -> transforms[param] = AutoSizeCharSequenceTransform(this) }
}
transforms[it] = CharSequenceTransform(!hasAutoSize)
true
}
} != 0)
generateAlternativeMethod(name, transforms)
fun applyReturnValueTransforms(param: Parameter) {
// Transform void to the proper type
transforms[returns] = PrimitiveValueReturnTransform(param.nativeType as PointerType<*>, param.name)
// Transform the AutoSize parameter, if there is one
getParams(hasReference<AutoSize>(param)).forEach {
transforms[it] = Expression1Transform
}
// Transform the returnValue parameter
transforms[param] = PrimitiveValueTransform
}
// Apply any complex transformations.
parameters.forEach {
if (it.has<Return>() && !hasParam { param -> param.has<PointerArray>() }) {
val returnMod = it.get<Return>()
if (returnMod === ReturnParam && returns.isVoid && it.nativeType !is CharSequenceType) {
if (!hasParam { param -> param.has<SingleValue>() || param.has<PointerArray>() }) {
// Skip, we inject the Return alternative in these transforms
applyReturnValueTransforms(it)
generateAlternativeMethod(stripPostfix(), transforms)
}
} else if (it.nativeType is CharSequenceType) {
// Remove any transform from the maxLength parameter
val maxLengthParam = getParam(hasReference<AutoSize>(it))
transforms.remove(maxLengthParam)
// Hide length parameter and use the stack
val lengthParam = returnMod.lengthParam
if (lengthParam.isNotEmpty() && lengthParam !== RESULT)
transforms[paramMap[lengthParam]!!] = BufferLengthTransform
// Hide target parameter and decode internally
val bufferAutoSizeTransform: FunctionTransform<Parameter> = if (returnMod.heapAllocate)
StringAutoSizeTransform(maxLengthParam)
else
StringAutoSizeStackTransform(maxLengthParam)
transforms[it] = bufferAutoSizeTransform
// Transform void to the buffer type
transforms[returns] = if (lengthParam.isNotEmpty())
BufferReturnTransform(it, lengthParam, it.nativeType.charMapping, returnMod.includesNT)
else
BufferReturnNTTransform(
it,
if (4 < (maxLengthParam.nativeType.mapping as PrimitiveMapping).bytes) "(int)${maxLengthParam.name}" else maxLengthParam.name
)
generateAlternativeMethod(name, transforms)
if (returnMod.maxLengthExpression != null) {
// Transform maxLength parameter and generate an additional alternative
transforms[maxLengthParam] = ExpressionTransform(returnMod.maxLengthExpression)
generateAlternativeMethodDelegate(name, transforms)
}
} else if (returnMod.lengthParam.startsWith(RESULT)) {
transforms[returns] = BufferAutoSizeReturnTransform(it, returnMod.lengthParam)
transforms[it] = BufferReplaceReturnTransform
generateAlternativeMethod(name, transforms)
} else {
check(!returns.isVoid)
}
} else if (it.has<AutoType>()) {
// Generate AutoType alternatives
val autoTypes = it.get<AutoType>()
val bufferParam = paramMap[autoTypes.reference]!!
// Disable AutoSize factor
val autoSizeParam = getReferenceParam<AutoSize>(bufferParam.name)
if (autoSizeParam != null)
transforms[autoSizeParam] = AutoSizeTransform(bufferParam, hasCustomJNI || hasUnsafeMethod, applyFactor = false)
for (autoType in autoTypes.types) {
transforms[it] = AutoTypeParamTransform("${autoType.className}.${autoType.name}")
transforms[bufferParam] = AutoTypeTargetTransform(autoType.mapping)
generateAlternativeMethod(name, transforms)
}
transforms.remove(bufferParam)
transforms.remove(it)
}
}
// Apply any MultiType transformations.
parameters.filter { it.has<MultiType>() }.let { params ->
if (params.isEmpty())
return@let
check(params.groupBy { it.get<MultiType>().types.contentHashCode() }.size == 1) {
"All MultiType modifiers in a function must have the same structure."
}
// Add the AutoSize transformation if we skipped it above
getParams { it.has<AutoSize>() }.forEach {
val autoSize = it.get<AutoSize>()
transforms[it] = AutoSizeTransform(paramMap[autoSize.reference]!!, hasCustomJNI || hasUnsafeMethod)
}
var multiTypes = params.first().get<MultiType>().types.asSequence()
if (params.any { it has optional })
multiTypes = sequenceOf(PointerMapping.DATA_BYTE) + multiTypes
for (autoType in multiTypes) {
params.forEach {
// Transform the AutoSize parameter, if there is one
getReferenceParam<AutoSize>(it.name).let { autoSizeParam ->
if (autoSizeParam != null)
transforms[autoSizeParam] = AutoSizeTransform(it, hasCustomJNI || hasUnsafeMethod, autoType.byteShift)
}
transforms[it] = AutoTypeTargetTransform(autoType)
}
generateAlternativeMethod(name, transforms)
}
val singleValueParams = params.filter { it.has<SingleValue>() }
if (singleValueParams.any()) {
// Generate a SingleValue alternative for each type
for (autoType in multiTypes) {
val primitiveType = autoType.box.lowercase()
// Generate type1, type2, type4 versions
// TODO: Make customizable? New modifier?
for (i in 1..4) {
if (i == 3) {
continue
}
singleValueParams.forEach {
// Transform the AutoSize parameter
val autoSizeParam = getParam(hasReference<AutoSize>(it)) // required
transforms[autoSizeParam] = ExpressionTransform("(1 << ${autoType.byteShift}) * $i")
val singleValue = it.get<SingleValue>()
transforms[it] = VectorValueTransform(autoType, primitiveType, singleValue.newName, i)
}
generateAlternativeMethod("$name$i${primitiveType[0]}", transforms)
}
}
singleValueParams.forEach {
transforms.remove(getParam(hasReference<AutoSize>(it)))
}
}
params.forEach {
getReferenceParam<AutoSize>(it.name).let { param ->
if (param != null)
transforms.remove(param)
}
transforms.remove(it)
}
}
// Apply any PointerArray transformations.
parameters.filter { it.has<PointerArray>() }.let { params ->
if (params.isEmpty())
return@let
fun Parameter.getAutoSizeReference(): Parameter? = getParams {
it.has<AutoSize> { reference == [email protected] }
}.firstOrNull()
// Array version
params.forEach {
val pointerArray = it.get<PointerArray>()
val lengthsParam = paramMap[pointerArray.lengthsParam]
if (lengthsParam != null)
transforms[lengthsParam] = PointerArrayLengthsTransform(it, true)
val countParam = it.getAutoSizeReference()
if (countParam != null)
transforms[countParam] = ExpressionTransform("${it.name}.length")
transforms[it] = if (it === parameters.last { param ->
param !== lengthsParam && param !== countParam // these will be hidden, ignore
}) PointerArrayTransformVararg else PointerArrayTransformArray
}
generateAlternativeMethod(name, transforms)
// Combine PointerArrayTransformSingle with BufferValueReturnTransform
getParams { it has ReturnParam }.forEach(::applyReturnValueTransforms)
// Single value version
params.forEach {
val pointerArray = it.get<PointerArray>()
val lengthsParam = paramMap[pointerArray.lengthsParam]
if (lengthsParam != null)
transforms[lengthsParam] = PointerArrayLengthsTransform(it, false)
val countParam = it.getAutoSizeReference()
if (countParam != null)
transforms[countParam] = ExpressionTransform("1")
transforms[it] = PointerArrayTransformSingle
}
generateAlternativeMethod(name, transforms)
// Cleanup
params.forEach {
val countParam = it.getAutoSizeReference()
if (countParam != null)
transforms.remove(countParam)
transforms.remove(it)
}
}
// Apply any SingleValue transformations.
@Suppress("ReplaceSizeCheckWithIsNotEmpty")
if (parameters.count {
if (!it.has<SingleValue>() || it.has<MultiType>()) {
false
} else {
// Compine SingleValueTransform with BufferValueReturnTransform
getParams { param -> param has ReturnParam }.forEach(::applyReturnValueTransforms)
// Transform the AutoSize parameter, if there is one
getParams(hasReference<AutoSize>(it)).forEach { param ->
transforms[param] = Expression1Transform
}
val singleValue = it.get<SingleValue>()
val pointerType = it.nativeType as PointerType<*>
if (pointerType.elementType is StructType) {
transforms[it] = SingleValueStructTransform(singleValue.newName)
} else {
transforms[it] = SingleValueTransform(
when (pointerType.elementType) {
is CharSequenceType -> "CharSequence"
is WrappedPointerType -> pointerType.elementType.className
is StructType -> it.javaMethodType
is PointerType<*> -> "long"
else -> pointerType.elementType.javaMethodType
},
pointerType.mapping.box.lowercase(),
singleValue.newName
)
}
true
}
} != 0)
generateAlternativeMethod(stripPostfix(), transforms)
}
private fun <T : QualifiedType> T.transformDeclarationOrElse(transforms: Map<QualifiedType, Transform>, original: String, annotate: Boolean): String? {
val transform = transforms[this]
return (
if (transform == null)
original
else
@Suppress("UNCHECKED_CAST")
(transform as FunctionTransform<T>).transformDeclaration(this, original)
).let {
if (!annotate || it == null)
it
else {
val space = it.lastIndexOf(' ')
"${nativeType.annotate(it.substring(0, space))} ${it.substring(space + 1)}"
}
}
}
private fun <T : QualifiedType> T.transformCallOrElse(transforms: Map<QualifiedType, Transform>, original: String): String {
val transform = transforms[this]
if (transform == null || this is Parameter && this.has(UseVariable))
return original
else
@Suppress("UNCHECKED_CAST")
return (transform as FunctionTransform<T>).transformCall(this, original)
}
private fun PrintWriter.generateAlternativeMethodSignature(
name: String,
transforms: Map<QualifiedType, Transform>,
description: String? = null,
constantMacro: Boolean
): String {
// JavaDoc
if (!constantMacro) {
if (description != null) {
val doc = nativeClass.processDocumentation("$description $javaDocLink").toJavaDoc()
val custom = nativeClass.binding?.printCustomJavadoc(this, this@Func, doc) ?: false
if (!custom && doc.isNotEmpty())
println(doc)
} else {
val hideAutoSizeResult = parameters.count { it.isAutoSizeResultOut } == 1
printDocumentation { param ->
!(hideAutoSizeResult && param.isAutoSizeResultOut) && transforms[param].let {
@Suppress("UNCHECKED_CAST")
(it == null || (it as FunctionTransform<Parameter>).transformDeclaration(param, param.name)
.let { declaration -> declaration != null && declaration.endsWith(param.name) })
}
}
}
}
// Method signature
val retType = returns.transformDeclarationOrElse(transforms, returns.javaMethodType, false)!!
if ((returns.nativeType.isReference && returnsNull) || (transforms[returns].let { it is FunctionTransform<*> && it.forceNullable }) ) {
println("$t@Nullable")
}
val retTypeAnnotation = returns.nativeType.annotation(retType)
if (retTypeAnnotation != null) {
println("$t$retTypeAnnotation")
}
print("$t${if (constantMacro) "private " else accessModifier}static $retType $name(")
printList(getNativeParams(withAutoSizeResultParams = false)) { param ->
param.transformDeclarationOrElse(transforms, param.asJavaMethodParam(false), true).let {
if (
it != null && param.nativeType.isReference && param.has(nullable) &&
transforms[param] !is SingleValueTransform &&
transforms[param] !is SingleValueStructTransform
) {
"@Nullable $it"
} else {
it
}
}
}
// Update Reuse delegation if the code below changes
when (val returnTransform = transforms[returns]) {
is MapPointerTransform -> {
if (returnTransform.useOldBuffer) {
if (parameters.isNotEmpty()) print(", ")
print("@Nullable ByteBuffer $MAP_OLD")
}
}
is MapPointerExplicitTransform -> {
var hasParams = parameters.isNotEmpty()
if (returnTransform.addParam) {
if (hasParams) print(", ") else hasParams = true
print("long ${returnTransform.lengthParam}")
}
if (returnTransform.useOldBuffer) {
if (hasParams) print(", ")
print("@Nullable ByteBuffer $MAP_OLD")
}
}
}
if (returns.isStructValue) {
if (parameters.isNotEmpty()) print(", ")
print("${returns.nativeType.annotate(retType)} $RESULT")
}
println(") {")
return retType
}
private fun PrintWriter.generateAlternativeMethod(
name: String,
transforms: Map<QualifiedType, Transform>,
description: String? = null
) {
println()
val macro = has<Macro>()
val retType = generateAlternativeMethodSignature(name, transforms, description, macro && get<Macro>().constant)
if (has<Reuse>()) {
print("$t$t")
if (retType != "void") {
print("return ")
}
print("${get<Reuse>().source.className}.$name(")
printList(getNativeParams(withAutoSizeResultParams = false)) {
it.transformDeclarationOrElse(transforms, it.name, false).let { name ->
name?.substring(name.lastIndexOf(' ') + 1)
}
}
when (val returnTransform = transforms[returns]) {
is MapPointerTransform -> {
if (returnTransform.useOldBuffer) {
if (parameters.isNotEmpty()) print(", ")
print(MAP_OLD)
}
}
is MapPointerExplicitTransform -> {
var hasParams = parameters.isNotEmpty()
if (returnTransform.addParam) {
if (hasParams) print(", ") else hasParams = true
print(returnTransform.lengthParam)
}
if (returnTransform.useOldBuffer) {
if (hasParams) print(", ")
print(MAP_OLD)
}
}
}
if (returns.isStructValue) {
if (parameters.isNotEmpty()) print(", ")
print(RESULT)
}
println(");\n$t}")
return
}
// Append CodeFunctionTransform statements to Code
val hasArrays = hasParam { it.nativeType is ArrayType<*> }
val code = transforms
.asSequence()
.filter { it.value is CodeFunctionTransform<*> }
.fold(if (has<Code>()) get() else Code.NO_CODE) { code, (qtype, transform) ->
@Suppress("UNCHECKED_CAST")
(transform as CodeFunctionTransform<QualifiedType>).generate(qtype, code)
}
// Get function address
if (hasFunctionAddressParam && !hasUnsafeMethod && !has<Macro>())
nativeClass.binding!!.generateFunctionAddress(this, this@Func)
// Generate checks
transforms
.asSequence()
.filter { it.key.let { qt -> qt is Parameter && qt.has<UseVariable>() } }
.forEach {
val param = it.key as Parameter
@Suppress("UNCHECKED_CAST")
val transform = it.value as FunctionTransform<Parameter>
println("$t$t${param.asJavaMethodParam(false)} = ${transform.transformCall(param, param.name)};")
}
printCode(code.javaInit, true, hasArrays)
if (Module.CHECKS && !macro)
generateChecks(ALTERNATIVE, transforms)
// Prepare stack parameters
val stackTransforms = if (macro) emptySequence() else transforms.asSequence().filter { it.value is StackFunctionTransform<*> }
val hideAutoSizeResultParam = [email protected]
val hasStack = (hideAutoSizeResultParam || stackTransforms.any()) && !macro
if (hasStack)
println("$t${t}MemoryStack stack = stackGet(); int stackPointer = stack.getPointer();")
val hasFinally = hasStack || code.hasStatements(code.javaFinally, true, hasArrays)
// Call the native method
generateCodeBeforeNative(code, true, hasArrays, hasFinally)
if (hideAutoSizeResultParam) {
val autoSizeParam = getParam { it.has<AutoSizeResultParam>() }
val autoSizeType = (autoSizeParam.nativeType.mapping as PointerMapping).mallocType
println("$t$t$t${autoSizeType}Buffer ${autoSizeParam.name} = stack.calloc$autoSizeType(1);")
}
for ((qtype, transform) in stackTransforms) {
@Suppress("UNCHECKED_CAST")
when (qtype) {
is Parameter -> (transform as StackFunctionTransform<Parameter>).setupStack(this@Func, qtype, this)
is ReturnValue -> (transform as StackFunctionTransform<ReturnValue>).setupStack(this@Func, qtype, this)
}
}
val returnLater = code.hasStatements(code.javaAfterNative, true, hasArrays) || transforms[returns] is ReturnLaterTransform
generateNativeMethodCall(code, returnLater, hasFinally) {
printList(getNativeParams()) {
it.transformCallOrElse(transforms, it.asNativeMethodArgument(ALTERNATIVE))
}
}
generateCodeAfterNative(code, true, hasArrays, hasFinally)
// Return
if (returns.isVoid || returns.isStructValue) {
// TODO: struct value + custom transform?
val result = returns.transformCallOrElse(transforms, "")
if (result.isNotEmpty()) {
println(if (hasFinally) result.replace(TRY_FINALLY_ALIGN, "$t$1") else result)
} else if (returns.isStructValue)
println("${if (hasFinally) "$t$t$t" else "$t$t"}return $RESULT;")
} else {
if (returns.nativeType is PointerType<*> && returns.nativeType.mapping !== PointerMapping.OPAQUE_POINTER) {
if (hasFinally)
print(t)
print("$t$t")
val builder = StringBuilder()
val isNullTerminated = returns.nativeType is CharSequenceType
builder.append(
if (returns.nativeType.dereference is StructType) {
"${returns.nativeType.javaMethodType}.create"
} else {
"mem${if (isNullTerminated || returns.nativeType.elementType is VoidType)
"ByteBuffer"
else
returns.nativeType.mapping.javaMethodName}"
}
)
if (isNullTerminated) {
builder.append("NT${(returns.nativeType as CharSequenceType).charMapping.bytes}")
} else if (returnsNull) {
builder.append("Safe")
}
builder.append("($RESULT")
if (has<MapPointer>())
builder.append(", ${get<MapPointer>().sizeExpression}")
else {
val hasAutoSizeResult = hasParam { it.has<AutoSizeResultParam>() }
if (!isNullTerminated || hasAutoSizeResult) {
if (hasAutoSizeResult) {
val params = getParams { it.has<AutoSizeResultParam>() }
val single = params.count() == 1
builder.append(", ${params.map { getAutoSizeResultExpression(single, it) }.joinToString(" * ")}")
} else {
check(returns.nativeType.dereference is StructType) {
"No AutoSizeResult parameter could be found."
}
}
}
}
builder.append(")")
val returnExpression = returns.transformCallOrElse(transforms, builder.toString())
if (returnExpression.indexOf('\n') == -1)
println("return $returnExpression;")
else // Multiple statements, assumes the transformation includes the return statement.
println(returnExpression)
} else if (returnLater) {
if (hasFinally)
print(t)
println(returns.transformCallOrElse(transforms, "$t${t}return $RESULT;"))
}
}
generateCodeFinally(code, true, hasArrays, hasStack)
println("$t}")
}
private fun PrintWriter.generateAlternativeMethodDelegate(
name: String,
transforms: Map<QualifiedType, Transform>,
description: String? = null
) {
println()
generateAlternativeMethodSignature(name, transforms, description, has<Macro> { constant })
// Call the native method
print("$t$t")
if (!((returns.isVoid && transforms[returns] == null) || returns.isStructValue))
print("return ")
print("$name(")
printList(getNativeParams().filter {
@Suppress("UNCHECKED_CAST")
val t = transforms[it] as FunctionTransform<Parameter>?
t == null || t is ExpressionTransform || t.transformDeclaration(it, it.asJavaMethodParam(false)) != null
}) {
val t = transforms[it]
if (t is ExpressionTransform)
t.transformCall(it, it.asNativeMethodArgument(ALTERNATIVE))
else
it.name
}
println(");")
println("$t}")
}
// --[ JNI FUNCTIONS ]--
internal fun generateFunctionDefinition(writer: PrintWriter) = writer.generateFunctionDefinitionImpl()
private fun PrintWriter.generateFunctionDefinitionImpl() {
print("typedef ${returns.toNativeType(nativeClass.binding)} (")
if (nativeClass.callingConvention !== CallingConvention.DEFAULT)
print("APIENTRY ")
print("*${nativeName}PROC) (")
val nativeParams = getNativeParams(withExplicitFunctionAddress = false, withJNIEnv = true)
if (nativeParams.any()) {
printList(nativeParams) {
it.toNativeType(nativeClass.binding)
}
} else
print("void")
println(");")
}
internal fun generateFunction(writer: PrintWriter) {
val hasArrays = hasParam { it.nativeType is ArrayType<*> }
val hasCritical = false && nativeClass.binding?.apiCapabilities != APICapabilities.JNI_CAPABILITIES && !parameters.contains(JNI_ENV)
if (hasCritical) {
writer.generateFunctionImpl(hasArrays, hasCritical, critical = true)
}
writer.generateFunctionImpl(hasArrays, hasCritical, critical = false)
}
private fun PrintWriter.generateFunctionImpl(hasArrays: Boolean, hasCritical: Boolean, critical: Boolean) {
val params = ArrayList<String>(4 + parameters.size)
if (!critical)
params.add("JNIEnv *$JNIENV, jclass clazz")
getNativeParams(withExplicitFunctionAddress = false).map {
if (it.nativeType is ArrayType<*>) {
if (critical)
"jint ${it.name}__length, j${it.nativeType.mapping.primitive}* ${it.name}"
else
"j${it.nativeType.mapping.primitive}Array ${it.name}$POINTER_POSTFIX"
} else {
"${it.nativeType.jniFunctionType} ${it.name}${if (it.nativeType is PointerType<*> || it.nativeType is StructType) POINTER_POSTFIX else ""}"
}
}.toCollection(params)
if (hasFunctionAddressParam)
params.add("jlong $FUNCTION_ADDRESS")
if (returns.isStructValue && !hasParam { it has ReturnParam })
params.add("jlong $RESULT")
// Function signature
print("JNIEXPORT${if (critical && workaroundJDK8167409()) "_CRITICAL" else ""} ${returns.jniFunctionType} JNICALL ${JNI_NAME(hasArrays, critical)}")
println("(${if (params.isEmpty()) "void" else params.joinToString(", ")}) {")
if (hasCritical && !(critical || hasArrays)) {
// Unused parameter macro
printUnusedParameters(false)
print(t)
if (!returns.isVoid && !returns.isStructValue)
print("return ")
print(JNI_NAME(hasArrays, critical = true, ignoreArrayType = true))
print('(')
params.clear()
getNativeParams(withExplicitFunctionAddress = true, withJNIEnv = false)
.mapTo(params) { "${it.name}${if (it.nativeType is PointerType<*> || it.nativeType is StructType) POINTER_POSTFIX else ""}" }
if (hasFunctionAddressParam)
params.add(FUNCTION_ADDRESS)
if (returns.isStructValue && !hasParam { it has ReturnParam })
params.add(RESULT)
print(params.joinToString(", "))
println(");")
println("}")
return
}
// Cast function address to pointer
if (nativeClass.binding != null) {
if (hasFunctionAddressParam) {
println("$t${nativeName}PROC $nativeName = (${nativeName}PROC)(uintptr_t)$FUNCTION_ADDRESS;")
} else
println("$t${nativeName}PROC $nativeName = (${nativeName}PROC)tlsGetFunction(${nativeClass.binding.getFunctionOrdinal(this@Func)});")
}
// Cast addresses to pointers
if (!hasCritical || !hasArrays) {
getNativeParams(withExplicitFunctionAddress = false)
.filter { it.nativeType.castAddressToPointer }
.forEach {
val variableType = if (it.nativeType === va_list)
"va_list *"
else
it.toNativeType(nativeClass.binding, pointerMode = true)
print(t)
if (it.nativeType is FunctionType && variableType.contains("(*)")) {
print(variableType.replace("(*)", "(*${it.name})"))
} else {
print(variableType)
if (!variableType.endsWith('*')) {
print(' ')
}
print(it.name)
}
println(
" = ${if (it.nativeType === va_list) {
"VA_LIST_CAST"
} else {
"($variableType)"
}
}${if (variableType != "uintptr_t") "(uintptr_t)" else ""}${it.name}$POINTER_POSTFIX;"
)
}
}
// Custom code
var code = if (has<Code>()) get() else Code.NO_CODE
if (hasArrays) {
if (!critical) {
code = code.append(
nativeBeforeCall = getParams { it.nativeType is ArrayType<*> }.map {
"j${(it.nativeType.mapping as PointerMapping).primitive} *${it.name} = ${
"(*$JNIENV)->Get${(it.nativeType as PointerType<*>).mapping.box}ArrayElements($JNIENV, ${it.name}$POINTER_POSTFIX, NULL)".let { expression ->
if (it.has<Nullable>())
"${it.name}$POINTER_POSTFIX == NULL ? NULL : $expression"
else
expression
}};"
}.joinToString("\n$t", prefix = t),
nativeAfterCall = getParams { it.nativeType is ArrayType<*> }
.withIndex()
.sortedByDescending { it.index }
.map { it.value }
.map {
"(*$JNIENV)->Release${(it.nativeType as PointerType<*>).mapping.box}ArrayElements($JNIENV, ${it.name}$POINTER_POSTFIX, ${it.name}, 0);".let { expression ->
if (it.has<Nullable>())
"if (${it.name} != NULL) { $expression }"
else
expression
}
}.joinToString("\n$t", prefix = t)
)
}
if (hasCritical) {
val callPrefix = if (!returns.isVoid && !returns.isStructValue) {
if (critical) "return " else "$RESULT = "
} else {
""
}
code = code.append(
nativeCall = "$t$callPrefix${JNI_NAME(hasArrays = true, critical = true, ignoreArrayType = true)}(${getNativeParams()
.map {
if (it.nativeType is ArrayType<*>)
"(uintptr_t)${it.name}"
else
"${it.name}${if (it.nativeType is PointerType<*> || it.nativeType is StructType) POINTER_POSTFIX else ""}"
}
.joinToString(", ")
}${if (returns.isStructValue) ", $RESULT" else ""});"
)
}
}
if (code.nativeAfterCall != null && !returns.isVoid && !returns.isStructValue)
println("$t${returns.jniFunctionType} $RESULT;")
code.nativeBeforeCall.let { if (it != null) println(it) }
// Unused parameter macro
printUnusedParameters(critical)
// Call native function
code.nativeCall.let { call ->
if (call != null)
println(call)
else {
print(t)
if (returns.isStructValue) {
getParams { it has ReturnParam }.map { it.name }.singleOrNull().let {
print(if (it != null)
"*$it = "
else
"*((${returns.nativeType.name}*)(uintptr_t)$RESULT) = "
)
}
} else if (!returns.isVoid) {
print(if (code.nativeAfterCall != null) "$RESULT = " else "return ")
if (returns.jniFunctionType != returns.nativeType.name)
print("(${returns.jniFunctionType})")
if (returns.nativeType is PointerType<*> && nativeClass.binding == null)
print("(uintptr_t)")
if (has<Address>())
print('&')
}
if (parameters.isNotEmpty() && parameters[0] === JNI_ENV && nativeClass.className == "JNINativeInterface")
print("(*$JNIENV)->")
print(nativeName)
if (!has<Macro> { !function }) print('(')
printList(getNativeParams(withExplicitFunctionAddress = false, withJNIEnv = true)) { param ->
param.nativeType.let {
if (it is StructType || it === va_list)
"*${param.name}"
else if (!it.castAddressToPointer) {
val nativeType = param.toNativeType(nativeClass.binding)
if (nativeType != it.jniFunctionType && "j$nativeType" != it.jniFunctionType)
"($nativeType)${param.name}" // Avoid implicit cast warnings
else
param.name
} else
param.name
}
}
if (!has<Macro> { !function }) print(')')
println(';')
}
}
code.nativeAfterCall.let {
if (it == null) return@let
println(it)
if (!returns.isVoid && !returns.isStructValue)
println("${t}return $RESULT;")
}
println("}")
}
private fun workaroundJDK8167409(ignoreArrayType: Boolean = false): Boolean = parameters.size.let {
6 <= it || (5 <= it && returns.isStructValue && !hasParam { param -> param has ReturnParam })
} && parameters[0].nativeType.let { type ->
(type is PointerType<*> && (ignoreArrayType || type !is ArrayType<*>)) || type.mapping.let { it is PrimitiveMapping && 4 < it.bytes }
}
private fun JNI_NAME(hasArrays: Boolean, critical: Boolean, ignoreArrayType: Boolean = false): String {
return "${nativeClass.nativeFileNameJNI}_${if (isNativeOnly) "" else "n"}${name.asJNIName}${if (nativeClass.module.arrayOverloads && (hasArrays || hasArrayOverloads))
getNativeParams(withExplicitFunctionAddress = false)
.map {
if (it.nativeType is ArrayType<*> && !(critical && ignoreArrayType))
it.nativeType.jniSignatureArray
else
it.nativeType.jniSignatureStrict
}
.joinToString(
"",
prefix = "__",
postfix = "J".repeat((if (returns.isStructValue) 1 else 0) + (if (hasFunctionAddressParam) 1 else 0))
)
else
""
}".let {
if (critical) {
if (workaroundJDK8167409(ignoreArrayType))
"CRITICAL($it)"
else
"JavaCritical_$it"
} else {
"Java_$it"
}
}
}
private fun PrintWriter.printUnusedParameters(critical: Boolean) {
if (!critical)
println(
if (parameters.contains(JNI_ENV) || (nativeClass.binding != null && !hasFunctionAddressParam))
"${t}UNUSED_PARAM(clazz)"
else
"${t}UNUSED_PARAMS($JNIENV, clazz)"
)
else
getParams { it.nativeType is ArrayType<*> }.forEach {
println("${t}UNUSED_PARAM(${it.name}__length)")
}
}
} | bsd-3-clause | f89ce61fdef184480195567309a3c39b | 43.071828 | 248 | 0.525818 | 5.603997 | false | false | false | false |
google/android-fhir | datacapture/src/main/java/com/google/android/fhir/datacapture/MoreQuestionnaires.kt | 1 | 2930 | /*
* Copyright 2022 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.fhir.datacapture
import org.hl7.fhir.r4.model.CanonicalType
import org.hl7.fhir.r4.model.Expression
import org.hl7.fhir.r4.model.Questionnaire
/**
* The StructureMap url in the
* [target structure-map extension](http://build.fhir.org/ig/HL7/sdc/StructureDefinition-sdc-questionnaire-targetStructureMap.html)
* s.
*/
val Questionnaire.targetStructureMap: String?
get() {
val extensionValue =
this.extension.singleOrNull { it.url == TARGET_STRUCTURE_MAP }?.value ?: return null
return if (extensionValue is CanonicalType) extensionValue.valueAsString else null
}
internal val Questionnaire.variableExpressions: List<Expression>
get() =
this.extension.filter { it.url == EXTENSION_VARIABLE_URL }.map { it.castToExpression(it.value) }
/**
* Finds the specific variable name [String] at questionnaire [Questionnaire] level
*
* @param variableName the [String] to match the variable at questionnaire [Questionnaire] level
* @return [Expression] the matching expression
*/
internal fun Questionnaire.findVariableExpression(variableName: String): Expression? =
variableExpressions.find { it.name == variableName }
/**
* See
* [Extension: target structure map](http://build.fhir.org/ig/HL7/sdc/StructureDefinition-sdc-questionnaire-targetStructureMap.html)
* .
*/
private const val TARGET_STRUCTURE_MAP: String =
"http://hl7.org/fhir/uv/sdc/StructureDefinition/sdc-questionnaire-targetStructureMap"
val Questionnaire.isPaginated: Boolean
get() = item.any { item -> item.displayItemControl == DisplayItemControlType.PAGE }
/**
* See
* [Extension: Entry mode](http://build.fhir.org/ig/HL7/sdc/StructureDefinition-sdc-questionnaire-entryMode.html)
* .
*/
internal const val EXTENSION_ENTRY_MODE_URL: String =
"http://hl7.org/fhir/uv/sdc/StructureDefinition/sdc-questionnaire-entryMode"
val Questionnaire.entryMode: EntryMode?
get() {
val entryMode =
this.extension
.firstOrNull { it.url == EXTENSION_ENTRY_MODE_URL }
?.value
?.toString()
?.lowercase()
return EntryMode.from(entryMode)
}
enum class EntryMode(val value: String) {
PRIOR_EDIT("prior-edit"),
RANDOM("random"),
SEQUENTIAL("sequential");
companion object {
fun from(type: String?): EntryMode? = values().find { it.value == type }
}
}
| apache-2.0 | 56da52ffd5d375c805c25c567771cb9f | 33.069767 | 132 | 0.732423 | 3.840105 | false | false | false | false |
code-disaster/lwjgl3 | modules/lwjgl/opengl/src/templates/kotlin/opengl/templates/ARB_imaging.kt | 4 | 25577 | /*
* Copyright LWJGL. All rights reserved.
* License terms: https://www.lwjgl.org/license
*/
package opengl.templates
import org.lwjgl.generator.*
import opengl.*
val ARB_imaging = "ARBImaging".nativeClassGL("ARB_imaging") {
documentation = "Native bindings to the OpenGL 1.2 optional imaging subset."
val IMAGING_INTERNAL_FORMATS =
"""
#RGB GL11#GL_RGBA
#RG8 #RG8_SNORM #R3_G3_B2 #RGB4 #RGB5 #RGB565 #RGB8
#RGB8_SNORM #RGB10 #RGB12 #RGB16 #RGB16_SNORM #RGBA2 #RGBA4 #RGB5_A1 #RGBA8 #RGBA8_SNORM #RGB10_A2
#RGBA12 #RGBA16 #RGBA16_SNORM #SRGB8 #SRGB8_ALPHA8 #RGB16F #RGBA16F #RGB32F #RGBA32F
#R11F_G11F_B10F
#ALPHA #LUMINANCE #LUMINANCE_ALPHA #INTENSITY #ALPHA4 #ALPHA8 #ALPHA12 #ALPHA16 #LUMINANCE4 #LUMINANCE8
#LUMINANCE12 #LUMINANCE16 #LUMINANCE4_ALPHA4 #LUMINANCE6_ALPHA2 #LUMINANCE8_ALPHA8 #LUMINANCE12_ALPHA4 #LUMINANCE12_ALPHA12
#LUMINANCE16_ALPHA16 #INTENSITY4 #INTENSITY8 #INTENSITY12 #INTENSITY16 #SLUMINANCE #SLUMINANCE8_ALPHA8
"""
val PIXEL_DATA_FORMATS =
"#RED #GREEN #BLUE #ALPHA #RGB GL11#GL_RGBA #BGR #BGRA #LUMINANCE #LUMINANCE_ALPHA"
val PIXEL_DATA_TYPES =
"""
#UNSIGNED_BYTE #BYTE #UNSIGNED_SHORT #SHORT #UNSIGNED_INT #INT
#UNSIGNED_BYTE_3_3_2 #UNSIGNED_BYTE_2_3_3_REV #UNSIGNED_SHORT_5_6_5 #UNSIGNED_SHORT_5_6_5_REV #UNSIGNED_SHORT_4_4_4_4
#UNSIGNED_SHORT_4_4_4_4_REV #UNSIGNED_SHORT_5_5_5_1 #UNSIGNED_SHORT_1_5_5_5_REV #UNSIGNED_INT_8_8_8_8
#UNSIGNED_INT_8_8_8_8_REV #UNSIGNED_INT_10_10_10_2 #UNSIGNED_INT_2_10_10_10_REV
"""
// SGI_color_table
val COLOR_TABLE_TARGETS = IntConstant(
"""
Accepted by the {@code cap} parameter of Enable, Disable, and IsEnabled, by the {@code pname} parameter of GetBooleanv, GetIntegerv, GetFloatv, and
GetDoublev, and by the {@code target} parameter of ColorTable, CopyColorTable, ColorTableParameteriv, ColorTableParameterfv,
GetColorTable, GetColorTableParameteriv, and GetColorTableParameterfv.
""",
"COLOR_TABLE"..0x80D0,
"POST_CONVOLUTION_COLOR_TABLE"..0x80D1,
"POST_COLOR_MATRIX_COLOR_TABLE"..0x80D2
).javaDocLinks
val PROXY_COLOR_TABLE_TARGETS = IntConstant(
"Accepted by the {@code target} parameter of ColorTable, GetColorTableParameteriv, and GetColorTableParameterfv.",
"PROXY_COLOR_TABLE"..0x80D3,
"PROXY_POST_CONVOLUTION_COLOR_TABLE"..0x80D4,
"PROXY_POST_COLOR_MATRIX_COLOR_TABLE"..0x80D5
).javaDocLinks
val COLOR_TABLE_PARAMS = IntConstant(
"""
Accepted by the {@code pname} parameter of ColorTableParameteriv, ColorTableParameterfv, GetColorTableParameteriv, and
GetColorTableParameterfv.
""",
"COLOR_TABLE_SCALE"..0x80D6,
"COLOR_TABLE_BIAS"..0x80D7
).javaDocLinks
val COLOR_TABLE_PROPERTIES = IntConstant(
"Accepted by the {@code pname} parameter of GetColorTableParameteriv and GetColorTableParameterfv.",
"COLOR_TABLE_FORMAT"..0x80D8,
"COLOR_TABLE_WIDTH"..0x80D9,
"COLOR_TABLE_RED_SIZE"..0x80DA,
"COLOR_TABLE_GREEN_SIZE"..0x80DB,
"COLOR_TABLE_BLUE_SIZE"..0x80DC,
"COLOR_TABLE_ALPHA_SIZE"..0x80DD,
"COLOR_TABLE_LUMINANCE_SIZE"..0x80DE,
"COLOR_TABLE_INTENSITY_SIZE"..0x80DF
).javaDocLinks
IntConstant(
"ErrorCode",
"TABLE_TOO_LARGE"..0x8031
)
DeprecatedGL..void(
"ColorTable",
"Specifies a color lookup table.",
GLenum("target", "the color table target", "$COLOR_TABLE_TARGETS $PROXY_COLOR_TABLE_TARGETS"),
GLenum("internalformat", "the color table internal format", IMAGING_INTERNAL_FORMATS),
GLsizei("width", "the color table width"),
GLenum("format", "the color data format", PIXEL_DATA_FORMATS),
GLenum("type", "the color data type", PIXEL_DATA_TYPES),
MultiType(
PointerMapping.DATA_SHORT, PointerMapping.DATA_INT, PointerMapping.DATA_FLOAT
)..Unsafe..RawPointer..void.const.p("table", "the color table data")
)
DeprecatedGL..void(
"CopyColorTable",
"Defines a color table in exactly the manner of #ColorTable(), except that the image data are taken from the framebuffer rather than from client memory.",
GLenum("target", "the color table target", COLOR_TABLE_TARGETS),
GLenum("internalformat", "the color table internal format", IMAGING_INTERNAL_FORMATS),
GLint("x", "the left framebuffer pixel coordinate"),
GLint("y", "the lower framebuffer pixel coordinate"),
GLsizei("width", "the color table width")
)
DeprecatedGL..void(
"ColorTableParameteriv",
"Specifies the scale and bias parameters for a color table.",
GLenum("target", "the color table target", COLOR_TABLE_TARGETS),
GLenum("pname", "the parameter to set", COLOR_TABLE_PARAMS),
Check(4)..GLint.const.p("params", "the parameter value")
)
DeprecatedGL..void(
"ColorTableParameterfv",
"Float version of #ColorTableParameteriv().",
GLenum("target", "the color table target"),
GLenum("pname", "the parameter to set"),
Check(4)..GLfloat.const.p("params", "the parameter value")
)
DeprecatedGL..void(
"GetColorTable",
"Returns the current contents of a color table.",
GLenum("target", "the color table target", COLOR_TABLE_TARGETS),
GLenum("format", "the color data format", PIXEL_DATA_FORMATS),
GLenum("type", "the color data type", PIXEL_DATA_TYPES),
MultiType(
PointerMapping.DATA_SHORT,
PointerMapping.DATA_INT,
PointerMapping.DATA_FLOAT
)..Unsafe..RawPointer..void.p("table", "the color table data")
)
DeprecatedGL..void(
"GetColorTableParameteriv",
"Returns the integer value of the specified color table parameter.",
GLenum("target", "the color table target", "$COLOR_TABLE_TARGETS $PROXY_COLOR_TABLE_TARGETS"),
GLenum("pname", "the parameter to query", "$COLOR_TABLE_PARAMS $COLOR_TABLE_PROPERTIES"),
Check(4)..ReturnParam..GLint.p("params", "a buffer in which to place the returned value")
)
DeprecatedGL..void(
"GetColorTableParameterfv",
"Float version of #GetColorTableParameteriv().",
GLenum("target", "the color table target"),
GLenum("pname", "the parameter to query"),
Check(4)..ReturnParam..GLfloat.p("params", "a buffer in which to place the returned value")
)
// EXT_color_subtable
DeprecatedGL..void(
"ColorSubTable",
"Respecifies a portion of an existing color table.",
GLenum("target", "the color table target", COLOR_TABLE_TARGETS),
GLsizei("start", "the starting index of the subregion to respecify"),
GLsizei("count", "the number of colors in the subregion to respecify"),
GLenum("format", "the color data format", PIXEL_DATA_FORMATS),
GLenum("type", "the color data type", PIXEL_DATA_TYPES),
Unsafe..RawPointer..void.const.p("data", "the color table data")
)
DeprecatedGL..void(
"CopyColorSubTable",
"Respecifies a portion of an existing color table using image taken from the framebuffer.",
GLenum("target", "the color table target", COLOR_TABLE_TARGETS),
GLsizei("start", "the start index of the subregion to respecify"),
GLint("x", "the left framebuffer pixel coordinate"),
GLint("y", "the lower framebuffer pixel coordinate"),
GLsizei("width", "the number of colors in the subregion to respecify")
)
// EXT_convolution
IntConstant(
"""
Accepted by the {@code cap} parameter of Enable, Disable, and IsEnabled, by the {@code pname} parameter of GetBooleanv, GetIntegerv, GetFloatv, and
GetDoublev, and by the {@code target} parameter of ConvolutionFilter1D, CopyConvolutionFilter1D, GetConvolutionFilter, ConvolutionParameteri,
ConvolutionParameterf, ConvolutionParameteriv, ConvolutionParameterfv, GetConvolutionParameteriv, and GetConvolutionParameterfv.
""",
"CONVOLUTION_1D"..0x8010
)
IntConstant(
"""
Accepted by the {@code cap} parameter of Enable, Disable, and IsEnabled, by the {@code pname} parameter of GetBooleanv, GetIntegerv, GetFloatv, and
GetDoublev, and by the {@code target} parameter of ConvolutionFilter2D, CopyConvolutionFilter2D, GetConvolutionFilter, ConvolutionParameteri,
ConvolutionParameterf, ConvolutionParameteriv, ConvolutionParameterfv, GetConvolutionParameteriv, and GetConvolutionParameterfv.
""",
"CONVOLUTION_2D"..0x8011
)
IntConstant(
"""
Accepted by the {@code cap} parameter of Enable, Disable, and IsEnabled, by the {@code pname} parameter of GetBooleanv, GetIntegerv, GetFloatv, and
GetDoublev, and by the {@code target} parameter of SeparableFilter2D, SeparableFilter2D, GetSeparableFilter, ConvolutionParameteri,
ConvolutionParameterf, ConvolutionParameteriv, ConvolutionParameterfv, GetConvolutionParameteriv, and GetConvolutionParameterfv.
""",
"SEPARABLE_2D"..0x8012
)
IntConstant(
"""
Accepted by the {@code pname} parameter of ConvolutionParameteri, ConvolutionParameterf, ConvolutionParameteriv, ConvolutionParameterfv,
GetConvolutionParameteriv, and GetConvolutionParameterfv.
""",
"CONVOLUTION_BORDER_MODE"..0x8013
)
val CONVOLUTION_FILTER_PARAMS = IntConstant(
"Accepted by the {@code pname} parameter of ConvolutionParameteriv, ConvolutionParameterfv, GetConvolutionParameteriv, and GetConvolutionParameterfv.",
"CONVOLUTION_FILTER_SCALE"..0x8014,
"CONVOLUTION_FILTER_BIAS"..0x8015
).javaDocLinks
IntConstant(
"""
Accepted by the {@code param} parameter of ConvolutionParameteri, and ConvolutionParameterf, and by the {@code params} parameter of
ConvolutionParameteriv and ConvolutionParameterfv, when the {@code pname} parameter is CONVOLUTION_BORDER_MODE.
""",
"REDUCE"..0x8016
)
val CONVOLUTION_FILTER_PROPERTIES = IntConstant(
"Accepted by the {@code pname} parameter of GetConvolutionParameteriv and GetConvolutionParameterfv.",
"CONVOLUTION_FORMAT"..0x8017,
"CONVOLUTION_WIDTH"..0x8018,
"CONVOLUTION_HEIGHT"..0x8019,
"MAX_CONVOLUTION_WIDTH"..0x801A,
"MAX_CONVOLUTION_HEIGHT"..0x801B
).javaDocLinks
IntConstant(
"""
Accepted by the {@code pname} parameter of PixelTransferi, PixelTransferf, and by the {@code pname} parameter of GetBooleanv, GetIntegerv, GetFloatv,
and GetDoublev.
""",
"POST_CONVOLUTION_RED_SCALE"..0x801C,
"POST_CONVOLUTION_GREEN_SCALE"..0x801D,
"POST_CONVOLUTION_BLUE_SCALE"..0x801E,
"POST_CONVOLUTION_ALPHA_SCALE"..0x801F,
"POST_CONVOLUTION_RED_BIAS"..0x8020,
"POST_CONVOLUTION_GREEN_BIAS"..0x8021,
"POST_CONVOLUTION_BLUE_BIAS"..0x8022,
"POST_CONVOLUTION_ALPHA_BIAS"..0x8023
)
DeprecatedGL..void(
"ConvolutionFilter1D",
"Defines a one-dimensional convolution filter.",
GLenum("target", "the convolution target", "#CONVOLUTION_1D"),
GLenum("internalformat", "the filter internal format", IMAGING_INTERNAL_FORMATS),
GLsizei("width", "the filter width"),
GLenum("format", "the filter data format", PIXEL_DATA_FORMATS),
GLenum("type", "the filter data type", PIXEL_DATA_TYPES),
Unsafe..RawPointer..void.const.p("data", "the filter data")
)
DeprecatedGL..void(
"ConvolutionFilter2D",
"Defines a two-dimensional convolution filter.",
GLenum("target", "the convolution target", "#CONVOLUTION_2D"),
GLenum("internalformat", "the filter internal format", IMAGING_INTERNAL_FORMATS),
GLsizei("width", "the filter width"),
GLsizei("height", "the filter height"),
GLenum("format", "the filter data format", PIXEL_DATA_FORMATS),
GLenum("type", "the filter data type", PIXEL_DATA_TYPES),
Unsafe..RawPointer..void.const.p("data", "the filter data")
)
DeprecatedGL..void(
"CopyConvolutionFilter1D",
"""
Defines a one-dimensional filter in exactly the manner of #ConvolutionFilter1D(), except that image data are taken from the framebuffer, rather than from
client memory.
""",
GLenum("target", "the convolution target", "#CONVOLUTION_1D"),
GLenum("internalformat", "the filter internal format", IMAGING_INTERNAL_FORMATS),
GLint("x", "the left framebuffer pixel coordinate"),
GLint("y", "the lower framebuffer pixel coordinate"),
GLsizei("width", "the filter width")
)
DeprecatedGL..void(
"CopyConvolutionFilter2D",
"""
Defines a two-dimensional filter in exactly the manner of #ConvolutionFilter1D(), except that image data are taken from the framebuffer, rather than from
client memory.
""",
GLenum("target", "the convolution target", "#CONVOLUTION_2D"),
GLenum("internalformat", "the filter internal format", IMAGING_INTERNAL_FORMATS),
GLint("x", "the left framebuffer pixel coordinate"),
GLint("y", "the lower framebuffer pixel coordinate"),
GLsizei("width", "the filter width"),
GLsizei("height", "the filter height")
)
DeprecatedGL..void(
"GetConvolutionFilter",
"Returns the contents of a convolution filter.",
GLenum("target", "the convolution target", "#CONVOLUTION_1D #CONVOLUTION_2D"),
GLenum("format", "the filter data format", PIXEL_DATA_FORMATS),
GLenum("type", "the filter data type", PIXEL_DATA_TYPES),
Unsafe..RawPointer..void.p("image", "the filter data")
)
DeprecatedGL..void(
"SeparableFilter2D",
"Specifies a two-dimensional separable convolution filter.",
GLenum("target", "the filter target", "#SEPARABLE_2D"),
GLenum("internalformat", "the filter internal format", IMAGING_INTERNAL_FORMATS),
GLsizei("width", "the filter width"),
GLsizei("height", "the filter height"),
GLenum("format", "the filter data format", PIXEL_DATA_FORMATS),
GLenum("type", "the filter data type", PIXEL_DATA_TYPES),
Unsafe..RawPointer..void.const.p("row", "the horizontal filter data"),
Unsafe..RawPointer..void.const.p("column", "the vertical filter data")
)
DeprecatedGL..void(
"GetSeparableFilter",
"Returns the current contents of a separable convolution filter.",
GLenum("target", "the filter target", "#SEPARABLE_2D"),
GLenum("format", "the filter data format", PIXEL_DATA_FORMATS),
GLenum("type", "the filter data type", PIXEL_DATA_TYPES),
Unsafe..RawPointer..void.p("row", "a buffer in which to return the filter row"),
Unsafe..RawPointer..void.p("column", "a buffer in which to return the filter column"),
Unsafe..nullable..void.p("span", "unused")
)
DeprecatedGL..void(
"ConvolutionParameteri",
"Specifies the scale and bias of a convolution filter.",
GLenum("target", "the filter target", "#CONVOLUTION_1D #CONVOLUTION_2D #SEPARABLE_2D"),
GLenum("pname", "the parameter to set", "#CONVOLUTION_BORDER_MODE"),
GLint("param", "the parameter value")
)
DeprecatedGL..void(
"ConvolutionParameteriv",
"Pointer version of #ConvolutionParameteri().",
GLenum("target", "the filter target"),
GLenum("pname", "the parameter to set", "$CONVOLUTION_FILTER_PARAMS #CONVOLUTION_BORDER_COLOR"),
Check(4)..GLint.const.p("params", "the parameter value")
)
DeprecatedGL..void(
"ConvolutionParameterf",
"Float version of #ConvolutionParameteri()",
GLenum("target", "the filter target"),
GLenum("pname", "the parameter to set"),
GLfloat("param", "the parameter value")
)
DeprecatedGL..void(
"ConvolutionParameterfv",
"Pointer version of #ConvolutionParameterf().",
GLenum("target", "the filter target"),
GLenum("pname", "the parameter to set", "$CONVOLUTION_FILTER_PARAMS #CONVOLUTION_BORDER_COLOR"),
Check(4)..GLfloat.const.p("params", "the parameter value")
)
DeprecatedGL..void(
"GetConvolutionParameteriv",
"Returns the value of a convolution filter parameter.",
GLenum("target", "the filter target", "#CONVOLUTION_1D #CONVOLUTION_2D #SEPARABLE_2D"),
GLenum("pname", "the parameter to query", CONVOLUTION_FILTER_PROPERTIES),
ReturnParam..Check(4)..GLint.p("params", "a buffer in which to return the parameter value")
)
DeprecatedGL..void(
"GetConvolutionParameterfv",
"Float version of #GetConvolutionParameteriv().",
GLenum("target", "the filter target"),
GLenum("pname", "the parameter to query"),
ReturnParam..Check(4)..GLfloat.p("params", "a buffer in which to return the parameter value")
)
// HP_convolution_border_modes
IntConstant(
"""
Accepted by the {@code param} parameter of ConvolutionParameteri, and ConvolutionParameterf, and by the {@code params} parameter of
ConvolutionParameteriv and ConvolutionParameterfv, when the {@code pname} parameter is CONVOLUTION_BORDER_MODE.
""",
//"IGNORE_BORDER"..0x8150,
"CONSTANT_BORDER"..0x8151,
"REPLICATE_BORDER"..0x8153
)
IntConstant(
"Accepted by the {@code pname} parameter of ConvolutionParameteriv, ConvolutionParameterfv, GetConvolutionParameteriv, and GetConvolutionParameterfv.",
"CONVOLUTION_BORDER_COLOR"..0x8154
)
// SGI_color_matrix
IntConstant(
"Accepted by the {@code pname} parameter of GetBooleanv, GetIntegerv, GetFloatv, and GetDoublev.",
"COLOR_MATRIX"..0x80B1,
"COLOR_MATRIX_STACK_DEPTH"..0x80B2,
"MAX_COLOR_MATRIX_STACK_DEPTH"..0x80B3
)
IntConstant(
"Accepted by the {@code pname} parameter of PixelTransfer*, and by the {@code pname} parameter of GetBooleanv, GetIntegerv, GetFloatv, and GetDoublev.",
"POST_COLOR_MATRIX_RED_SCALE"..0x80B4,
"POST_COLOR_MATRIX_GREEN_SCALE"..0x80B5,
"POST_COLOR_MATRIX_BLUE_SCALE"..0x80B6,
"POST_COLOR_MATRIX_ALPHA_SCALE"..0x80B7,
"POST_COLOR_MATRIX_RED_BIAS"..0x80B8,
"POST_COLOR_MATRIX_GREEN_BIAS"..0x80B9,
"POST_COLOR_MATRIX_BLUE_BIAS"..0x80BA,
"POST_COLOR_MATRIX_ALPHA_BIAS"..0x80BB
)
// EXT_histogram
IntConstant(
"""
Accepted by the {@code cap} parameter of Enable, Disable, and IsEnabled, by the {@code pname} parameter of GetBooleanv, GetIntegerv, GetFloatv, and
GetDoublev, and by the {@code target} parameter of Histogram, ResetHistogram, GetHistogram, GetHistogramParameteriv, and
GetHistogramParameterfv.
""",
"HISTOGRAM"..0x8024
)
IntConstant(
"Accepted by the {@code target} parameter of Histogram, GetHistogramParameteriv, and GetHistogramParameterfv.",
"PROXY_HISTOGRAM"..0x8025
)
val HISTOGRAM_PROPERTIES = IntConstant(
"Accepted by the {@code pname} parameter of GetHistogramParameteriv and GetHistogramParameterfv.",
"HISTOGRAM_WIDTH"..0x8026,
"HISTOGRAM_FORMAT"..0x8027,
"HISTOGRAM_RED_SIZE"..0x8028,
"HISTOGRAM_GREEN_SIZE"..0x8029,
"HISTOGRAM_BLUE_SIZE"..0x802A,
"HISTOGRAM_ALPHA_SIZE"..0x802B,
"HISTOGRAM_LUMINANCE_SIZE"..0x802C,
"HISTOGRAM_SINK"..0x802D
).javaDocLinks
IntConstant(
"""
Accepted by the {@code cap} parameter of Enable, Disable, and IsEnabled, by the {@code pname} parameter of GetBooleanv, GetIntegerv, GetFloatv, and
GetDoublev, and by the {@code target} parameter of Minmax, ResetMinmax, GetMinmax, GetMinmaxParameteriv, and GetMinmaxParameterfv.
""",
"MINMAX"..0x802E
)
IntConstant(
"Accepted by the {@code pname} parameter of GetMinmaxParameteriv and GetMinmaxParameterfv.",
"MINMAX_FORMAT"..0x802F,
"MINMAX_SINK"..0x8030
)
DeprecatedGL..void(
"Histogram",
"Specifies the histogram table.",
GLenum("target", "the histogram target", "#HISTOGRAM #PROXY_HISTOGRAM"),
GLsizei("width", "the histogram width"),
GLenum("internalformat", "the histogram internal format", IMAGING_INTERNAL_FORMATS),
GLboolean(
"sink",
"""
whether pixel groups will be consumed by the histogram operation (#TRUE) or passed on to the minmax operation (#FALSE)
"""
)
)
DeprecatedGL..void(
"ResetHistogram",
"Resets all counters of all elements of the histogram table to zero.",
GLenum("target", "the histogram target", "#HISTOGRAM")
)
DeprecatedGL..void(
"GetHistogram",
"Returns the current contents of the histogram table.",
GLenum("target", "the histogram target", "#HISTOGRAM"),
GLboolean(
"reset",
"if #TRUE, then all counters of all elements of the histogram are reset to zero. Counters are reset whether returned or not."
),
GLenum("format", "the pixel data format", PIXEL_DATA_FORMATS),
GLenum("type", "the pixel data types", PIXEL_DATA_TYPES),
Unsafe..RawPointer..void.p("values", "the pixel data")
)
DeprecatedGL..void(
"GetHistogramParameteriv",
"Returns the integer values of the specified histogram parameter",
GLenum("target", "the histogram target", "#HISTOGRAM"),
GLenum("pname", "the parameter to query", HISTOGRAM_PROPERTIES),
ReturnParam..Check(1)..GLint.p("params", "a buffer in which to return the parameter values")
)
DeprecatedGL..void(
"GetHistogramParameterfv",
"Float version of #GetHistogramParameteriv().",
GLenum("target", "the histogram target"),
GLenum("pname", "the parameter to query"),
ReturnParam..Check(1)..GLfloat.p("params", "a buffer in which to place the returned value")
)
DeprecatedGL..void(
"Minmax",
"Specifies the minmax table.",
GLenum("target", "the minmax target", "#MINMAX"),
GLenum("internalformat", "the minmax table internal format", IMAGING_INTERNAL_FORMATS),
GLboolean(
"sink",
"whether pixel groups will be consumed by the minmax operation (#TRUE) or passed on to final conversion (#FALSE)"
)
)
DeprecatedGL..void(
"ResetMinmax",
"Resets all minimum and maximum values of {@code target} to to their maximum and minimum representable values, respectively.",
GLenum("target", "the minmax target", "#MINMAX")
)
DeprecatedGL..void(
"GetMinmax",
"Returns the current contents of the minmax table.",
GLenum("target", "the minmax target", "#MINMAX"),
GLboolean(
"reset",
"""
If #TRUE, then each minimum value is reset to the maximum representable value, and each maximum value is reset to the minimum
representable value. All values are reset, whether returned or not.
"""
),
GLenum("format", "the pixel data format", PIXEL_DATA_FORMATS),
GLenum("type", "the pixel data type", PIXEL_DATA_TYPES),
Unsafe..RawPointer..void.p("values", "a buffer in which to place the minmax values")
)
DeprecatedGL..void(
"GetMinmaxParameteriv",
"Returns the integer value of the specified minmax parameter.",
GLenum("target", "the minmax target", "#MINMAX"),
GLenum("pname", "the parameter to query"),
ReturnParam..Check(1)..GLint.p("params", "a buffer in which to place the returned value")
)
DeprecatedGL..void(
"GetMinmaxParameterfv",
"Float version of #GetMinmaxParameteriv().",
GLenum("target", "the minmax target", "#MINMAX"),
GLenum("pname", "the parameter to query"),
ReturnParam..Check(1)..GLfloat.p("params", "a buffer in which to place the returned value")
)
// EXT_blend_color
IntConstant(
"Accepted by the {@code sfactor} and {@code dfactor} parameters of BlendFunc.",
"CONSTANT_COLOR"..0x8001,
"ONE_MINUS_CONSTANT_COLOR"..0x8002,
"CONSTANT_ALPHA"..0x8003,
"ONE_MINUS_CONSTANT_ALPHA"..0x8004
)
IntConstant(
"Accepted by the {@code pname} parameter of GetBooleanv, GetIntegerv, GetFloatv, and GetDoublev.",
"BLEND_COLOR"..0x8005
)
reuse(GL14C, "BlendColor")
// EXT_blend_minmax
IntConstant(
"Accepted by the {@code mode} parameter of BlendEquation.",
"FUNC_ADD"..0x8006,
"MIN"..0x8007,
"MAX"..0x8008
)
IntConstant(
"Accepted by the {@code pname} parameter of GetBooleanv, GetIntegerv, GetFloatv, and GetDoublev.",
"BLEND_EQUATION"..0x8009
)
// EXT_blend_subtract
IntConstant(
"Accepted by the {@code mode} parameter of BlendEquation.",
"FUNC_SUBTRACT"..0x800A,
"FUNC_REVERSE_SUBTRACT"..0x800B
)
reuse(GL14C, "BlendEquation")
} | bsd-3-clause | c123cbf6ec2794a8fbe12738cb69ed50 | 37.931507 | 162 | 0.648747 | 4.419734 | false | false | false | false |
code-disaster/lwjgl3 | modules/lwjgl/llvm/src/templates/kotlin/llvm/templates/LLVMExecutionEngine.kt | 4 | 7728 | /*
* Copyright LWJGL. All rights reserved.
* License terms: https://www.lwjgl.org/license
*/
package llvm.templates
import llvm.*
import org.lwjgl.generator.*
val LLVMExecutionEngine = "LLVMExecutionEngine".nativeClass(
Module.LLVM,
prefixConstant = "LLVM",
prefixMethod = "LLVM",
binding = LLVM_BINDING_DELEGATE
) {
documentation = ""
void(
"LinkInMCJIT",
"",
void()
)
void(
"LinkInInterpreter",
"",
void()
)
LLVMGenericValueRef(
"CreateGenericValueOfInt",
"",
LLVMTypeRef("Ty", ""),
unsigned_long_long("N", ""),
LLVMBool("IsSigned", "")
)
LLVMGenericValueRef(
"CreateGenericValueOfPointer",
"",
opaque_p("P", "")
)
LLVMGenericValueRef(
"CreateGenericValueOfFloat",
"",
LLVMTypeRef("Ty", ""),
double("N", "")
)
unsigned_int(
"GenericValueIntWidth",
"",
LLVMGenericValueRef("GenValRef", "")
)
unsigned_long_long(
"GenericValueToInt",
"",
LLVMGenericValueRef("GenVal", ""),
LLVMBool("IsSigned", "")
)
opaque_p(
"GenericValueToPointer",
"",
LLVMGenericValueRef("GenVal", "")
)
double(
"GenericValueToFloat",
"",
LLVMTypeRef("TyRef", ""),
LLVMGenericValueRef("GenVal", "")
)
void(
"DisposeGenericValue",
"",
LLVMGenericValueRef("GenVal", "")
)
LLVMBool(
"CreateExecutionEngineForModule",
"",
Check(1)..LLVMExecutionEngineRef.p("OutEE", ""),
LLVMModuleRef("M", ""),
Check(1)..charUTF8.p.p("OutError", "")
)
LLVMBool(
"CreateInterpreterForModule",
"",
Check(1)..LLVMExecutionEngineRef.p("OutInterp", ""),
LLVMModuleRef("M", ""),
Check(1)..charUTF8.p.p("OutError", "")
)
LLVMBool(
"CreateJITCompilerForModule",
"",
Check(1)..LLVMExecutionEngineRef.p("OutJIT", ""),
LLVMModuleRef("M", ""),
unsigned_int("OptLevel", ""),
Check(1)..charUTF8.p.p("OutError", "")
)
void(
"InitializeMCJITCompilerOptions",
"",
LLVMMCJITCompilerOptions.p("Options", ""),
AutoSize("Options")..size_t("SizeOfOptions", "")
)
LLVMBool(
"CreateMCJITCompilerForModule",
"""
Create an MCJIT execution engine for a module, with the given options. It is the responsibility of the caller to ensure that all fields in
{@code Options} up to the given {@code SizeOfOptions} are initialized. It is correct to pass a smaller value of {@code SizeOfOptions} that omits some
fields. The canonical way of using this is:
${codeBlock("""
LLVMMCJITCompilerOptions options;
LLVMInitializeMCJITCompilerOptions(&options, sizeof(options));
... fill in those options you care about
LLVMCreateMCJITCompilerForModule(&jit, mod, &options, sizeof(options),
&error);""")}
Note that this is also correct, though possibly suboptimal:
${codeBlock("""
LLVMCreateMCJITCompilerForModule(&jit, mod, 0, 0, &error);""")}
""",
Check(1)..LLVMExecutionEngineRef.p("OutJIT", ""),
LLVMModuleRef("M", ""),
LLVMMCJITCompilerOptions.p("Options", ""),
AutoSize("Options")..size_t("SizeOfOptions", ""),
Check(1)..charUTF8.p.p("OutError", "")
)
void(
"DisposeExecutionEngine",
"",
LLVMExecutionEngineRef("EE", "")
)
void(
"RunStaticConstructors",
"",
LLVMExecutionEngineRef("EE", "")
)
void(
"RunStaticDestructors",
"",
LLVMExecutionEngineRef("EE", "")
)
int(
"RunFunctionAsMain",
"",
LLVMExecutionEngineRef("EE", ""),
LLVMValueRef("F", ""),
AutoSize("ArgV")..unsigned_int("ArgC", ""),
charUTF8.const.p.const.p("ArgV", ""),
NullTerminated..charUTF8.const.p.const.p("EnvP", "")
)
LLVMGenericValueRef(
"RunFunction",
"",
LLVMExecutionEngineRef("EE", ""),
LLVMValueRef("F", ""),
AutoSize("Args")..unsigned_int("NumArgs", ""),
LLVMGenericValueRef.p("Args", "")
)
void(
"FreeMachineCodeForFunction",
"",
LLVMExecutionEngineRef("EE", ""),
LLVMValueRef("F", "")
)
void(
"AddModule",
"",
LLVMExecutionEngineRef("EE", ""),
LLVMModuleRef("M", "")
)
LLVMBool(
"RemoveModule",
"",
LLVMExecutionEngineRef("EE", ""),
LLVMModuleRef("M", ""),
Check(1)..LLVMModuleRef.p("OutMod", ""),
Check(1)..charUTF8.p.p("OutError", "")
)
LLVMBool(
"FindFunction",
"",
LLVMExecutionEngineRef("EE", ""),
Check(1)..charUTF8.const.p("Name", ""),
Check(1)..LLVMValueRef.p("OutFn", "")
)
opaque_p(
"RecompileAndRelinkFunction",
"",
LLVMExecutionEngineRef("EE", ""),
LLVMValueRef("Fn", "")
)
LLVMTargetDataRef(
"GetExecutionEngineTargetData",
"",
LLVMExecutionEngineRef("EE", "")
)
LLVMTargetMachineRef(
"GetExecutionEngineTargetMachine",
"",
LLVMExecutionEngineRef("EE", "")
)
void(
"AddGlobalMapping",
"",
LLVMExecutionEngineRef("EE", ""),
LLVMValueRef("Global", ""),
opaque_p("Addr", "")
)
opaque_p(
"GetPointerToGlobal",
"",
LLVMExecutionEngineRef("EE", ""),
LLVMValueRef("Global", "")
)
uint64_t(
"GetGlobalValueAddress",
"",
LLVMExecutionEngineRef("EE", ""),
charUTF8.const.p("Name", "")
)
uint64_t(
"GetFunctionAddress",
"",
LLVMExecutionEngineRef("EE", ""),
charUTF8.const.p("Name", "")
)
IgnoreMissing..LLVMBool(
"ExecutionEngineGetErrMsg",
"""
Returns true on error, false on success. If true is returned then the error message is copied to {@code OutStr} and cleared in the
{@code ExecutionEngine} instance.
""",
LLVMExecutionEngineRef("EE", ""),
Check(1)..charUTF8.p.p("OutError", ""),
since = "11"
)
LLVMMCJITMemoryManagerRef(
"CreateSimpleMCJITMemoryManager",
"""
Create a simple custom MCJIT memory manager. This memory manager can intercept allocations in a module-oblivious way. This will return #NULL if any of
the passed functions are #NULL.
""",
opaque_p("Opaque", "an opaque client object to pass back to the callbacks"),
LLVMMemoryManagerAllocateCodeSectionCallback("AllocateCodeSection", "allocate a block of memory for executable code"),
LLVMMemoryManagerAllocateDataSectionCallback("AllocateDataSection", "allocate a block of memory for data"),
LLVMMemoryManagerFinalizeMemoryCallback("FinalizeMemory", "set page permissions and flush cache. Return 0 on success, 1 on error."),
LLVMMemoryManagerDestroyCallback("Destroy", "")
)
void(
"DisposeMCJITMemoryManager",
"",
LLVMMCJITMemoryManagerRef("MM", "")
)
IgnoreMissing..LLVMJITEventListenerRef("CreateGDBRegistrationListener", "", void())
IgnoreMissing..LLVMJITEventListenerRef("CreateIntelJITEventListener", "", void())
IgnoreMissing..LLVMJITEventListenerRef("CreateOProfileJITEventListener", "", void())
IgnoreMissing..LLVMJITEventListenerRef("CreatePerfJITEventListener", "", void())
} | bsd-3-clause | 392d79e70ef9c37f2e4d2445b8673c75 | 22.708589 | 158 | 0.563794 | 4.814953 | false | false | false | false |
chromeos/video-decode-encode-demo | app/src/main/java/dev/hadrosaur/videodecodeencodedemo/AudioHelpers/AudioMixTrack.kt | 1 | 5928 | /*
* Copyright (c) 2022 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dev.hadrosaur.videodecodeencodedemo.AudioHelpers
import androidx.collection.CircularArray
import dev.hadrosaur.videodecodeencodedemo.MainActivity.Companion.logd
import dev.hadrosaur.videodecodeencodedemo.Utils.CircularBuffer
class AudioMixTrack(startTimeUs: Long = 0L) {
val BUFFER_LENGTH = 250 // About 5secs at ~0.02s per buffer
val SPLIT_BUFFER_LENGTH = 50 // Allocate some temporary space for split audio buffers
val mediaClock = AudioMixTrackMediaClock(startTimeUs)
private val audioBuffer = CircularBuffer<AudioBuffer>(BUFFER_LENGTH, AudioMainTrack.createEmptyAudioBuffer())
// This is temporary storage space, we will not pull from this buffer so allow overwriting
private val splitBuffer = CircularBuffer<AudioBuffer>(SPLIT_BUFFER_LENGTH,
AudioMainTrack.createEmptyAudioBuffer(),
CircularBuffer.FULL_BEHAVIOUR.OVERWRITE)
/**
* Indicate if the buffer already has BUFFER_LENGTH - 1 elements so as not to make it auto-grow
*/
fun isFull() : Boolean {
return audioBuffer.isFull()
}
fun getFirstPresentationTimeUs() : Long {
return if (audioBuffer.isEmpty()) {
Long.MAX_VALUE
} else {
// Buffers are in order so beginning of first buffer is first presentation time
audioBuffer.peek().presentationTimeUs
}
}
fun reset() {
audioBuffer.clear()
mediaClock.reset()
}
fun addAudioChunk(chunkToAdd: AudioBuffer) {
audioBuffer.add(chunkToAdd)
}
// Pop audio chunk and update playhead. Note: mediaClock is not updated here. It is expected to
// be updated manually from the main track
fun popAudioChunk(): AudioBuffer? {
if (!audioBuffer.isEmpty()) {
return null
}
return audioBuffer.get()
}
// Pop all chunks that contain some audio >= fromUs and < toUs
// This will simply discard chunks that are too early
fun popChunksFromTo(fromUs: Long, toUs: Long) : CircularArray<AudioBuffer> {
val chunksInRange = CircularArray<AudioBuffer>(2)
while (!audioBuffer.isEmpty()) {
var chunk = audioBuffer.get()
var chunkStartUs = chunk.presentationTimeUs;
var chunkEndUs = chunk.presentationTimeUs + chunk.lengthUs
var splitBufferPointer: AudioBuffer? = null
var isSplitBuffer = false
// If the next chunk is after the range (starts at or after toUs), put it back and exit
if (chunkStartUs >= toUs) {
audioBuffer.rewindTail() // This "puts back" the chunk, avoiding a copy
break
}
// If the chunk is earlier than the range, simply discard it
if (chunkEndUs < fromUs) {
continue
}
//TODO: If time doesn't line up exactly on a short boundary, there could be data loss
// or silence added here. Maybe presentation times need to be byte/short aligned?
// Or from -> to times?
// Only latter part of chunk required, chop off beginning part and add chunk
if (chunkStartUs < fromUs && chunkEndUs > fromUs) {
val timeToDiscard = fromUs - chunkStartUs
val bytesToDiscard = usToBytes(timeToDiscard)
chunk.buffer.position(chunk.buffer.position() + bytesToDiscard)
chunkStartUs = fromUs // Update new start for next check
}
// If only the first part is needed, copy the first part of the chunk into the split
// buffer queue and adjust the old/new buffer positions. Note if a chunk is larger than
// the from<->to window, both the above situation and this can apply: chop of some from
// beginning and some from the end.
if (chunkStartUs < toUs && chunkEndUs > toUs) {
val timeToKeepUs = toUs - chunkStartUs;
val bytesToKeep = usToBytes(timeToKeepUs)
// Copy into split buffer queue and reduce the limit to "cut off the end"
splitBufferPointer = splitBuffer.peekHead() // Get pointer to storage location
splitBuffer.add(chunk, true) // Copy full chunk into split buffer queue
// Adjust the copy to just be the first part
splitBufferPointer.buffer.limit(chunk.buffer.position() + bytesToKeep)
splitBufferPointer.lengthUs = toUs - chunkStartUs
splitBufferPointer.size = bytesToKeep
isSplitBuffer = true
// Advance start position of original buffer and rewind queue to cut off front and
// "put it back" in the queue for future playback
chunk.buffer.position(chunk.buffer.position() + bytesToKeep)
chunk.presentationTimeUs = toUs
chunk.lengthUs = chunkEndUs - toUs
chunk.size = chunk.size - bytesToKeep
audioBuffer.rewindTail()
}
// If we reach this point, chunk is now perfectly in range
if (isSplitBuffer) {
chunksInRange.addLast(splitBufferPointer)
} else {
chunksInRange.addLast(chunk)
}
}
return chunksInRange
}
} | apache-2.0 | 0db778e7e8a2331ad7e4fc5eb23efb24 | 41.963768 | 113 | 0.63917 | 4.94412 | false | true | false | false |
dahlstrom-g/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/createCallable/CreatePropertyDelegateAccessorsActionFactory.kt | 3 | 4702 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.quickfix.createFromUsage.createCallable
import com.intellij.util.SmartList
import org.jetbrains.kotlin.builtins.ReflectionTypes
import org.jetbrains.kotlin.config.LanguageFeature
import org.jetbrains.kotlin.descriptors.VariableAccessorDescriptor
import org.jetbrains.kotlin.descriptors.VariableDescriptorWithAccessors
import org.jetbrains.kotlin.descriptors.impl.LocalVariableDescriptor
import org.jetbrains.kotlin.diagnostics.Diagnostic
import org.jetbrains.kotlin.idea.base.projectStructure.languageVersionSettings
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.quickfix.createFromUsage.callableBuilder.CallableInfo
import org.jetbrains.kotlin.idea.quickfix.createFromUsage.callableBuilder.FunctionInfo
import org.jetbrains.kotlin.idea.quickfix.createFromUsage.callableBuilder.ParameterInfo
import org.jetbrains.kotlin.idea.quickfix.createFromUsage.callableBuilder.TypeInfo
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.KtExpression
import org.jetbrains.kotlin.psi.KtProperty
import org.jetbrains.kotlin.psi.KtPsiFactory
import org.jetbrains.kotlin.psi.psiUtil.getNonStrictParentOfType
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.descriptorUtil.builtIns
import org.jetbrains.kotlin.resolve.descriptorUtil.module
import org.jetbrains.kotlin.types.Variance
import org.jetbrains.kotlin.util.OperatorNameConventions
object CreatePropertyDelegateAccessorsActionFactory : CreateCallableMemberFromUsageFactory<KtExpression>() {
override fun getElementOfInterest(diagnostic: Diagnostic): KtExpression? {
return diagnostic.psiElement as? KtExpression
}
override fun extractFixData(element: KtExpression, diagnostic: Diagnostic): List<CallableInfo> {
val context = element.analyze()
fun isApplicableForAccessor(accessor: VariableAccessorDescriptor?): Boolean =
accessor != null && context[BindingContext.DELEGATED_PROPERTY_RESOLVED_CALL, accessor] == null
val property = element.getNonStrictParentOfType<KtProperty>() ?: return emptyList()
val propertyDescriptor = context[BindingContext.DECLARATION_TO_DESCRIPTOR, property] as? VariableDescriptorWithAccessors
?: return emptyList()
if (propertyDescriptor is LocalVariableDescriptor
&& !element.languageVersionSettings.supportsFeature(LanguageFeature.LocalDelegatedProperties)
) {
return emptyList()
}
val propertyReceiver = propertyDescriptor.extensionReceiverParameter ?: propertyDescriptor.dispatchReceiverParameter
val propertyType = propertyDescriptor.type
val accessorReceiverType = TypeInfo(element, Variance.IN_VARIANCE)
val builtIns = propertyDescriptor.builtIns
val thisRefParam = ParameterInfo(TypeInfo(propertyReceiver?.type ?: builtIns.nullableNothingType, Variance.IN_VARIANCE))
val kPropertyStarType = ReflectionTypes.createKPropertyStarType(propertyDescriptor.module) ?: return emptyList()
val metadataParam = ParameterInfo(TypeInfo(kPropertyStarType, Variance.IN_VARIANCE), "property")
val callableInfos = SmartList<CallableInfo>()
val psiFactory = KtPsiFactory(element)
if (isApplicableForAccessor(propertyDescriptor.getter)) {
val getterInfo = FunctionInfo(
name = OperatorNameConventions.GET_VALUE.asString(),
receiverTypeInfo = accessorReceiverType,
returnTypeInfo = TypeInfo(propertyType, Variance.OUT_VARIANCE),
parameterInfos = listOf(thisRefParam, metadataParam),
modifierList = psiFactory.createModifierList(KtTokens.OPERATOR_KEYWORD)
)
callableInfos.add(getterInfo)
}
if (propertyDescriptor.isVar && isApplicableForAccessor(propertyDescriptor.setter)) {
val newValueParam = ParameterInfo(TypeInfo(propertyType, Variance.IN_VARIANCE))
val setterInfo = FunctionInfo(
name = OperatorNameConventions.SET_VALUE.asString(),
receiverTypeInfo = accessorReceiverType,
returnTypeInfo = TypeInfo(builtIns.unitType, Variance.OUT_VARIANCE),
parameterInfos = listOf(thisRefParam, metadataParam, newValueParam),
modifierList = psiFactory.createModifierList(KtTokens.OPERATOR_KEYWORD)
)
callableInfos.add(setterInfo)
}
return callableInfos
}
}
| apache-2.0 | 7723126719c29078bd065d19f72d3eef | 52.431818 | 158 | 0.762867 | 5.678744 | false | false | false | false |
dahlstrom-g/intellij-community | plugins/ide-features-trainer/src/training/featuresSuggester/SuggesterSupport.kt | 9 | 2699 | // 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 training.featuresSuggester
import com.intellij.lang.Language
import com.intellij.lang.LanguageExtensionPoint
import com.intellij.openapi.extensions.ExtensionPointName
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
@Suppress("TooManyFunctions")
interface SuggesterSupport {
companion object {
private val EP_NAME: ExtensionPointName<LanguageExtensionPoint<SuggesterSupport>> =
ExtensionPointName.create("training.ifs.suggesterSupport")
private val extensions: List<LanguageExtensionPoint<SuggesterSupport>>
get() = EP_NAME.extensionList
fun getForLanguage(language: Language): SuggesterSupport? {
return if (language == Language.ANY) {
extensions.firstOrNull()?.instance
}
else {
val langSupport = extensions.find { it.language == language.id }?.instance
if (langSupport == null && language.baseLanguage != null) {
val baseLanguage = language.baseLanguage!!
extensions.find { it.language == baseLanguage.id }?.instance
}
else langSupport
}
}
}
fun isLoadedSourceFile(file: PsiFile): Boolean
fun isIfStatement(element: PsiElement): Boolean
fun isForStatement(element: PsiElement): Boolean
fun isWhileStatement(element: PsiElement): Boolean
fun isCodeBlock(element: PsiElement): Boolean
fun getCodeBlock(element: PsiElement): PsiElement?
fun getContainingCodeBlock(element: PsiElement): PsiElement?
/**
* element must be a code block @see [getCodeBlock], [getContainingCodeBlock], [isCodeBlock]
*/
fun getParentStatementOfBlock(element: PsiElement): PsiElement?
/**
* element must be a code block @see [getCodeBlock], [getContainingCodeBlock], [isCodeBlock]
*/
fun getStatements(element: PsiElement): List<PsiElement>
fun getTopmostStatementWithText(psiElement: PsiElement, text: String): PsiElement?
fun isSupportedStatementToIntroduceVariable(element: PsiElement): Boolean
fun isPartOfExpression(element: PsiElement): Boolean
fun isExpressionStatement(element: PsiElement): Boolean
fun isVariableDeclaration(element: PsiElement): Boolean
/**
* element must be a variable declaration @see [isVariableDeclaration]
*/
fun getVariableName(element: PsiElement): String?
/**
* Return true if element is class, method or non local property definition
*/
fun isFileStructureElement(element: PsiElement): Boolean
fun isIdentifier(element: PsiElement): Boolean
fun isLiteralExpression(element: PsiElement): Boolean
}
| apache-2.0 | e524d5b76f0eba20fe2168861543994f | 32.320988 | 158 | 0.747314 | 5.035448 | false | false | false | false |
mctoyama/PixelServer | src/main/kotlin/org/pixelndice/table/pixelserver/connection/main/State03JoinOrHostGame.kt | 1 | 1940 | package org.pixelndice.table.pixelserver.connection.main
import org.apache.logging.log4j.LogManager
import org.pixelndice.table.pixelprotocol.Protobuf
import org.pixelndice.table.pixelserver.connection.main.state04hostgame.State05HostGame
import org.pixelndice.table.pixelserver.connection.main.state04joingame.State05WaitingQueryGame
import org.pixelndice.table.pixelserver.connection.main.state04joingame.State06LobbyUnreachableByPlayer
import org.pixelndice.table.pixelserver.connection.main.state04listgame.State05WaitingListGame
private val logger = LogManager.getLogger(State03JoinOrHostGame::class.java)
class State03JoinOrHostGame : State {
override fun process(ctx: Context) {
val p = ctx.channel.peekPacket()
if( p!=null){
when(p.payloadCase){
Protobuf.Packet.PayloadCase.LOBBYUNREACHABLE -> ctx.state = State06LobbyUnreachableByPlayer()
Protobuf.Packet.PayloadCase.PUBLISHCAMPAIGN -> ctx.state = State05HostGame()
Protobuf.Packet.PayloadCase.QUERYGAME -> ctx.state = State05WaitingQueryGame()
Protobuf.Packet.PayloadCase.CHECKGAMELIST -> ctx.state = State05WaitingListGame()
Protobuf.Packet.PayloadCase.END -> ctx.state = StateStop()
Protobuf.Packet.PayloadCase.ENDWITHERROR -> ctx.state = StateStop()
else -> {
val resp = Protobuf.Packet.newBuilder()
logger.error("Expecting Lobby Unreachable by player, PublishCampaign, QueryGame, CheckGameList, END or EndWithError. Instead Received: $p")
val rend = Protobuf.EndWithError.newBuilder()
rend.reason = "key.expecting_lobbyunreachable_publishcampaign_querygame_checkgamelist_end_endwitherror"
resp.setEndWithError(rend)
ctx.channel.packet = resp.build()
}
}
}
}
}
| bsd-2-clause | 507e4f2faea46c89d173cdc6bc2c4e15 | 44.116279 | 159 | 0.695361 | 4.553991 | false | false | false | false |
securityfirst/Umbrella_android | app/src/main/java/org/secfirst/umbrella/data/database/content/ContentRepository.kt | 1 | 2235 | package org.secfirst.umbrella.data.database.content
import org.secfirst.umbrella.data.database.checklist.Checklist
import org.secfirst.umbrella.data.database.difficulty.Difficulty
import org.secfirst.umbrella.data.database.form.Form
import org.secfirst.umbrella.data.database.lesson.Module
import org.secfirst.umbrella.data.database.lesson.Subject
import org.secfirst.umbrella.data.database.reader.FeedSource
import org.secfirst.umbrella.data.database.reader.RSS
import org.secfirst.umbrella.data.database.segment.Markdown
import javax.inject.Inject
class ContentRepository @Inject constructor(private val contentDao: ContentDao) : ContentRepo {
override suspend fun resetContent() = contentDao.resetContent()
override suspend fun insertDefaultRSS(rssList: List<RSS>) = contentDao.insertDefaultRSS(rssList)
override suspend fun getSubject(subjectId: String) = contentDao.getSubject(subjectId)
override suspend fun getDifficulty(difficultyId: String) = contentDao.getDifficulty(difficultyId)
override suspend fun getModule(moduleId: String) = contentDao.getModule(moduleId)
override suspend fun getMarkdown(markdownId: String) = contentDao.getMarkdown(markdownId)
override suspend fun getChecklist(checklistId: String) = contentDao.getChecklist(checklistId)
override suspend fun getForm(formId: String) = contentDao.getForm(formId)
override suspend fun saveAllChecklists(checklists: List<Checklist>) = contentDao.saveChecklists(checklists)
override suspend fun saveAllMarkdowns(markdowns: List<Markdown>) = contentDao.saveMarkdowns(markdowns)
override suspend fun saveAllModule(modules: List<Module>) = contentDao.saveModules(modules)
override suspend fun saveAllDifficulties(difficulties: List<Difficulty>) = contentDao.saveDifficulties(difficulties)
override suspend fun saveAllForms(forms: List<Form>) = contentDao.saveForms(forms)
override suspend fun saveAllSubjects(subjects: List<Subject>) = contentDao.saveSubjects(subjects)
override suspend fun insertFeedSource(feedSources: List<FeedSource>) = contentDao.insertFeedSource(feedSources)
override suspend fun insertAllLessons(contentData: ContentData) = contentDao.insertAllContent(contentData)
} | gpl-3.0 | dc30fa26ce5c14e06e44fe023b2d96d5 | 46.574468 | 120 | 0.815213 | 4.524291 | false | false | false | false |
securityfirst/Umbrella_android | app/src/main/java/org/secfirst/umbrella/component/WebViewController.kt | 1 | 3242 | package org.secfirst.umbrella.component
import android.annotation.TargetApi
import android.graphics.Bitmap
import android.os.Bundle
import android.os.Handler
import android.view.LayoutInflater
import android.view.View
import android.view.View.INVISIBLE
import android.view.View.VISIBLE
import android.view.ViewGroup
import android.webkit.WebResourceError
import android.webkit.WebResourceRequest
import android.webkit.WebView
import android.webkit.WebViewClient
import kotlinx.android.synthetic.main.web_view.*
import org.secfirst.umbrella.R
import org.secfirst.umbrella.feature.base.view.BaseController
class WebViewController(bundle: Bundle) : BaseController(bundle) {
private val url by lazy { args.getString(EXTRA_WEB_VIEW_URL) }
private var refreshEnable: Boolean = false
companion object {
const val EXTRA_WEB_VIEW_URL = "url"
}
constructor(url: String) : this(Bundle().apply {
putString(EXTRA_WEB_VIEW_URL, url)
})
override fun onInject() {
}
override fun onAttach(view: View) {
super.onAttach(view)
setUpWebView()
setUpToolbar()
enableNavigation(false)
}
override fun onDestroyView(view: View) {
enableNavigation(true)
super.onDestroyView(view)
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup, savedViewState: Bundle?): View {
return inflater.inflate(R.layout.web_view, container, false)
}
private fun setUpWebView() {
webView?.let {
it.loadUrl(url)
it.webViewClient = object : WebViewClient() {
override fun onReceivedError(view: WebView, errorCode: Int, description: String, failingUrl: String) {
webViewLoad?.visibility = INVISIBLE
webViewSwipe?.isEnabled = false
}
@TargetApi(android.os.Build.VERSION_CODES.M)
override fun onReceivedError(view: WebView, req: WebResourceRequest, rerr: WebResourceError) {
onReceivedError(view, rerr.errorCode, rerr.description.toString(), req.url.toString())
webViewLoad?.visibility = INVISIBLE
webViewSwipe?.isEnabled = false
if (refreshEnable) webViewSwipe?.isRefreshing = false
}
override fun onPageStarted(view: WebView, url: String, favicon: Bitmap?) {
if (!refreshEnable) webViewLoad?.visibility = VISIBLE
Handler().postDelayed({
webViewLoad?.visibility = INVISIBLE
webViewSwipe?.isRefreshing = false
}, 30000)
}
override fun onPageFinished(view: WebView, url: String) {
webViewLoad?.visibility = INVISIBLE
if (refreshEnable) webViewSwipe?.isRefreshing = false
}
}
}
}
private fun setUpToolbar() {
webViewToolbar?.let {
mainActivity.setSupportActionBar(it)
mainActivity.supportActionBar?.setDisplayShowHomeEnabled(true)
mainActivity.supportActionBar?.setDisplayHomeAsUpEnabled(true)
}
}
} | gpl-3.0 | 746f7634bdccd78765d1413e168e9292 | 33.5 | 118 | 0.637261 | 5.195513 | false | false | false | false |
MGaetan89/ShowsRage | app/src/main/kotlin/com/mgaetan89/showsrage/fragment/ChangeQualityFragment.kt | 1 | 2861 | package com.mgaetan89.showsrage.fragment
import android.app.Dialog
import android.content.DialogInterface
import android.os.Bundle
import android.support.v4.app.DialogFragment
import android.support.v7.app.AlertDialog
import android.widget.Spinner
import com.mgaetan89.showsrage.Constants
import com.mgaetan89.showsrage.R
import com.mgaetan89.showsrage.network.SickRageApi
class ChangeQualityFragment : DialogFragment(), DialogInterface.OnClickListener {
override fun onClick(dialog: DialogInterface?, which: Int) {
val indexerId = this.arguments?.getInt(Constants.Bundle.INDEXER_ID) ?: return
val parentFragment = this.parentFragment
if (this.dialog == null || indexerId <= 0 || parentFragment !is ShowOverviewFragment) {
return
}
val allowedQualitySpinner = this.dialog.findViewById(R.id.allowed_quality) as Spinner?
val allowedQuality = this.getAllowedQuality(allowedQualitySpinner)
val preferredQualitySpinner = this.dialog.findViewById(R.id.preferred_quality) as Spinner?
val preferredQuality = this.getPreferredQuality(preferredQualitySpinner)
val callback = parentFragment.getSetShowQualityCallback()
SickRageApi.instance.services?.setShowQuality(indexerId, allowedQuality, preferredQuality, callback)
}
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
val context = this.context ?: return super.onCreateDialog(savedInstanceState)
val builder = AlertDialog.Builder(context)
builder.setTitle(R.string.change_quality)
builder.setView(R.layout.fragment_change_quality)
builder.setNegativeButton(R.string.cancel, null)
builder.setPositiveButton(R.string.change, this)
return builder.show()
}
internal fun getAllowedQuality(allowedQualitySpinner: Spinner?): String? {
var allowedQualityIndex = 0
if (allowedQualitySpinner != null) {
// Skip the "Ignore" first item
allowedQualityIndex = allowedQualitySpinner.selectedItemPosition - 1
}
if (allowedQualityIndex >= 0) {
val qualities = this.resources.getStringArray(R.array.allowed_qualities_keys)
if (allowedQualityIndex < qualities.size) {
return qualities[allowedQualityIndex]
}
}
return null
}
internal fun getPreferredQuality(preferredQualitySpinner: Spinner?): String? {
var preferredQualityIndex = 0
if (preferredQualitySpinner != null) {
// Skip the "Ignore" first item
preferredQualityIndex = preferredQualitySpinner.selectedItemPosition - 1
}
if (preferredQualityIndex >= 0) {
val qualities = this.resources.getStringArray(R.array.preferred_qualities_keys)
if (preferredQualityIndex < qualities.size) {
return qualities[preferredQualityIndex]
}
}
return null
}
companion object {
fun newInstance(indexerId: Int) = ChangeQualityFragment().apply {
this.arguments = Bundle().apply {
this.putInt(Constants.Bundle.INDEXER_ID, indexerId)
}
}
}
}
| apache-2.0 | a7bcb61052d9766915cdba626c68599b | 31.146067 | 102 | 0.775603 | 4.110632 | false | false | false | false |
google/intellij-community | plugins/kotlin/gradle/gradle-java/src/org/jetbrains/kotlin/idea/gradleJava/configuration/kpm/KotlinKPMGradleProjectResolver.kt | 3 | 12070 | // 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.gradleJava.configuration.kpm
import com.intellij.build.events.MessageEvent
import com.intellij.openapi.externalSystem.model.DataNode
import com.intellij.openapi.externalSystem.model.ProjectKeys
import com.intellij.openapi.externalSystem.model.project.*
import com.intellij.openapi.externalSystem.util.ExternalSystemApiUtil
import com.intellij.openapi.externalSystem.util.ExternalSystemConstants
import com.intellij.openapi.externalSystem.util.Order
import com.intellij.openapi.roots.DependencyScope
import com.intellij.util.PlatformUtils
import org.gradle.tooling.model.idea.IdeaModule
import org.jetbrains.kotlin.gradle.kpm.idea.*
import org.jetbrains.kotlin.idea.base.externalSystem.findAll
import org.jetbrains.kotlin.idea.base.util.KotlinPlatformUtils
import org.jetbrains.kotlin.idea.configuration.multiplatform.KotlinMultiplatformNativeDebugSuggester
import org.jetbrains.kotlin.idea.gradle.configuration.ResolveModulesPerSourceSetInMppBuildIssue
import org.jetbrains.kotlin.idea.gradle.configuration.buildClasspathData
import org.jetbrains.kotlin.idea.gradle.configuration.findChildModuleById
import org.jetbrains.kotlin.idea.gradle.configuration.kpm.ContentRootsCreator
import org.jetbrains.kotlin.idea.gradle.configuration.kpm.ModuleDataInitializer
import org.jetbrains.kotlin.idea.gradle.ui.notifyLegacyIsResolveModulePerSourceSetSettingIfNeeded
import org.jetbrains.kotlin.idea.gradleTooling.*
import org.jetbrains.kotlin.tooling.core.Extras
import org.jetbrains.plugins.gradle.model.ProjectImportModelProvider
import org.jetbrains.plugins.gradle.model.data.BuildScriptClasspathData
import org.jetbrains.plugins.gradle.model.data.GradleSourceSetData
import org.jetbrains.plugins.gradle.service.project.AbstractProjectResolverExtension
import org.jetbrains.plugins.gradle.service.project.ProjectResolverContext
import org.jetbrains.plugins.gradle.util.GradleConstants
import java.io.File
@Order(ExternalSystemConstants.UNORDERED + 1)
open class KotlinKPMGradleProjectResolver : AbstractProjectResolverExtension() {
override fun getExtraProjectModelClasses(): Set<Class<out Any>> =
throw UnsupportedOperationException("Use getModelProvider() instead!")
override fun getModelProvider(): ProjectImportModelProvider? = IdeaKpmProjectProvider
override fun getToolingExtensionsClasses(): Set<Class<out Any>> = setOf(
IdeaKpmProject::class.java, // representative of kotlin-gradle-plugin-idea
Extras::class.java, // representative of kotlin-tooling-core
Unit::class.java // representative of kotlin-stdlib
)
override fun populateModuleExtraModels(gradleModule: IdeaModule, ideModule: DataNode<ModuleData>) {
if (ExternalSystemApiUtil.find(ideModule, BuildScriptClasspathData.KEY) == null) {
val buildScriptClasspathData = buildClasspathData(gradleModule, resolverCtx)
ideModule.createChild(BuildScriptClasspathData.KEY, buildScriptClasspathData)
}
super.populateModuleExtraModels(gradleModule, ideModule)
}
override fun createModule(gradleModule: IdeaModule, projectDataNode: DataNode<ProjectData>): DataNode<ModuleData>? {
return super.createModule(gradleModule, projectDataNode)?.also { mainModuleNode ->
val initializerContext = ModuleDataInitializer.Context.EMPTY
ModuleDataInitializer.EP_NAME.extensions.forEach { moduleDataInitializer ->
moduleDataInitializer.initialize(gradleModule, mainModuleNode, projectDataNode, resolverCtx, initializerContext)
}
suggestNativeDebug(gradleModule, resolverCtx)
}
}
override fun populateModuleContentRoots(gradleModule: IdeaModule, ideModule: DataNode<ModuleData>) {
if (!modelExists(gradleModule)) {
return super.populateModuleContentRoots(gradleModule, ideModule)
}
ContentRootsCreator.EP_NAME.extensions.forEach { contentRootsCreator ->
contentRootsCreator.populateContentRoots(gradleModule, ideModule, resolverCtx)
}
}
override fun populateModuleDependencies(gradleModule: IdeaModule, ideModule: DataNode<ModuleData>, ideProject: DataNode<ProjectData>) {
if (!modelExists(gradleModule)) {
return super.populateModuleDependencies(gradleModule, ideModule, ideProject)
}
populateDependenciesByFragmentData(gradleModule, ideModule, ideProject, resolverCtx)
}
private fun modelExists(gradleModule: IdeaModule): Boolean = resolverCtx.getIdeaKpmProject(gradleModule) != null
companion object {
private val nativeDebugSuggester = object : KotlinMultiplatformNativeDebugSuggester<IdeaKpmProject>() {
override fun hasKotlinNativeHome(model: IdeaKpmProject?): Boolean = model?.kotlinNativeHome?.exists() ?: false
}
internal fun ProjectResolverContext.getIdeaKpmProject(gradleModule: IdeaModule): IdeaKpmProject? {
return this.getExtraProject(gradleModule, IdeaKpmProjectContainer::class.java)?.instanceOrNull
}
private fun suggestNativeDebug(gradleModule: IdeaModule, resolverCtx: ProjectResolverContext) {
nativeDebugSuggester.suggestNativeDebug(resolverCtx.getIdeaKpmProject(gradleModule), resolverCtx)
if (!resolverCtx.isResolveModulePerSourceSet && !KotlinPlatformUtils.isAndroidStudio && !PlatformUtils.isMobileIde() &&
!PlatformUtils.isAppCode()
) {
notifyLegacyIsResolveModulePerSourceSetSettingIfNeeded(resolverCtx.projectPath)
resolverCtx.report(MessageEvent.Kind.WARNING, ResolveModulesPerSourceSetInMppBuildIssue())
}
}
//TODO check this
internal fun extractPackagePrefix(fragment: IdeaKpmFragment): String? = null
internal fun extractContentRootSources(model: IdeaKpmProject): Collection<IdeaKpmFragment> =
model.modules.flatMap { it.fragments }
//TODO replace with proper implementation, like with KotlinTaskProperties
internal fun extractPureKotlinSourceFolders(fragment: IdeaKpmFragment): Collection<File> = fragment.sourceDirs
//TODO Unite with KotlinGradleProjectResolverExtension.getSourceSetName
internal val IdeaKpmProject.pureKotlinSourceFolders: Collection<String>
get() = extractContentRootSources(this).flatMap { extractPureKotlinSourceFolders(it) }.map { it.absolutePath }
internal val DataNode<out ModuleData>.sourceSetName
get() = (data as? GradleSourceSetData)?.id?.substringAfterLast(':')
//TODO Unite with KotlinGradleProjectResolverExtension.addDependency
internal fun addModuleDependency(
dependentModule: DataNode<out ModuleData>,
dependencyModule: DataNode<out ModuleData>,
) {
val moduleDependencyData = ModuleDependencyData(dependentModule.data, dependencyModule.data)
//TODO Replace with proper scope from dependency
moduleDependencyData.scope = DependencyScope.COMPILE
moduleDependencyData.isExported = false
moduleDependencyData.isProductionOnTestDependency = dependencyModule.sourceSetName == "test"
dependentModule.createChild(ProjectKeys.MODULE_DEPENDENCY, moduleDependencyData)
}
private fun populateDependenciesByFragmentData(
gradleModule: IdeaModule,
ideModule: DataNode<ModuleData>,
ideProject: DataNode<ProjectData>,
resolverCtx: ProjectResolverContext
) {
val allGradleModules = gradleModule.project.modules
val allModuleDataNodes = ExternalSystemApiUtil.findAll(ideProject, ProjectKeys.MODULE)
val allFragmentModulesById = allModuleDataNodes.flatMap { ExternalSystemApiUtil.findAll(it, GradleSourceSetData.KEY) }
.associateBy { it.data.id }
val sourceSetDataWithFragmentData = ExternalSystemApiUtil.findAll(ideModule, GradleSourceSetData.KEY)
.mapNotNull { ExternalSystemApiUtil.find(it, KotlinFragmentData.KEY)?.data?.let { fragmentData -> it to fragmentData } }
.sortedBy { it.second.refinesFragmentIds.size }
for ((fragmentSourceSetNode, kpmFragmentData) in sourceSetDataWithFragmentData) {
val refinesFragmentNodes = kpmFragmentData.refinesFragmentIds.mapNotNull { ideModule.findChildModuleById(it) }
refinesFragmentNodes.forEach {
addModuleDependency(fragmentSourceSetNode, it)
}
val sourceDependencyIds = kpmFragmentData.fragmentDependencies
.filterIsInstance<IdeaKpmFragmentDependency>()
.mapNotNull { fragmentDependency ->
val foundGradleModule = allGradleModules.singleOrNull { dependencyGradleModule ->
dependencyGradleModule.name == fragmentDependency.coordinates.module.projectName
} ?: return@mapNotNull null // Probably it's worth to log
fragmentDependency to foundGradleModule
}
.map { (dependency, module) -> calculateKotlinFragmentModuleId(module, dependency.coordinates, resolverCtx) }
val dependencyModuleNodes = sourceDependencyIds.mapNotNull { allFragmentModulesById[it] }
dependencyModuleNodes.forEach { addModuleDependency(fragmentSourceSetNode, it) }
val groupedBinaryDependencies = kpmFragmentData.fragmentDependencies
.filterIsInstance<IdeaKpmResolvedBinaryDependency>()
.groupBy { it.coordinates.toString() }
.map { (coordinates, binariesWithType) ->
GroupedLibraryDependency(coordinates, binariesWithType.map { it.binaryFile to it.binaryType.toBinaryType() })
}
groupedBinaryDependencies.forEach {
populateLibraryDependency(fragmentSourceSetNode, ideProject, it)
}
}
}
private fun String.toBinaryType(): LibraryPathType = when (this) {
IdeaKpmDependency.CLASSPATH_BINARY_TYPE -> LibraryPathType.BINARY
IdeaKpmDependency.SOURCES_BINARY_TYPE -> LibraryPathType.SOURCE
IdeaKpmDependency.DOCUMENTATION_BINARY_TYPE -> LibraryPathType.DOC
else -> LibraryPathType.EXCLUDED
}
private data class GroupedLibraryDependency(
val coordinates: String?,
val binariesWithType: Collection<Pair<File, LibraryPathType>>
)
private fun populateLibraryDependency(
dependentModule: DataNode<out ModuleData>,
projectDataNode: DataNode<out ProjectData>,
binaryDependency: GroupedLibraryDependency
) {
val coordinates = binaryDependency.coordinates ?: return
val existingLibraryNodeWithData = projectDataNode.findAll(ProjectKeys.LIBRARY).find {
it.data.owner == GradleConstants.SYSTEM_ID && it.data.externalName == coordinates
}
val libraryData: LibraryData
if (existingLibraryNodeWithData != null) {
libraryData = existingLibraryNodeWithData.data
} else {
libraryData = LibraryData(GradleConstants.SYSTEM_ID, coordinates).apply {
binaryDependency.binariesWithType.forEach { (binaryFile, pathType) ->
addPath(pathType, binaryFile.absolutePath)
}
}
projectDataNode.createChild(ProjectKeys.LIBRARY, libraryData)
}
val libraryDependencyData = LibraryDependencyData(dependentModule.data, libraryData, LibraryLevel.PROJECT)
dependentModule.createChild(ProjectKeys.LIBRARY_DEPENDENCY, libraryDependencyData)
}
}
}
| apache-2.0 | 95e3f7e0a3187f017859be6bb6812841 | 54.62212 | 139 | 0.720795 | 5.93412 | false | false | false | false |
tiarebalbi/okhttp | okhttp/src/test/java/okhttp3/internal/io/FaultyFileSystem.kt | 1 | 2726 | /*
* Copyright (C) 2011 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 okhttp3.internal.io
import okio.Buffer
import okio.ExperimentalFileSystem
import okio.FileSystem
import okio.ForwardingFileSystem
import okio.ForwardingSink
import okio.Path
import okio.Sink
import java.io.IOException
import java.util.LinkedHashSet
@OptIn(ExperimentalFileSystem::class)
class FaultyFileSystem constructor(delegate: FileSystem?) : ForwardingFileSystem(delegate!!) {
private val writeFaults: MutableSet<Path> = LinkedHashSet()
private val deleteFaults: MutableSet<Path> = LinkedHashSet()
private val renameFaults: MutableSet<Path> = LinkedHashSet()
fun setFaultyWrite(file: Path, faulty: Boolean) {
if (faulty) {
writeFaults.add(file)
} else {
writeFaults.remove(file)
}
}
fun setFaultyDelete(file: Path, faulty: Boolean) {
if (faulty) {
deleteFaults.add(file)
} else {
deleteFaults.remove(file)
}
}
fun setFaultyRename(file: Path, faulty: Boolean) {
if (faulty) {
renameFaults.add(file)
} else {
renameFaults.remove(file)
}
}
@Throws(IOException::class)
override fun atomicMove(source: Path, target: Path) {
if (renameFaults.contains(source) || renameFaults.contains(target)) throw IOException("boom!")
super.atomicMove(source, target)
}
@Throws(IOException::class)
override fun delete(path: Path) {
if (deleteFaults.contains(path)) throw IOException("boom!")
super.delete(path)
}
@Throws(IOException::class)
override fun deleteRecursively(fileOrDirectory: Path) {
if (deleteFaults.contains(fileOrDirectory)) throw IOException("boom!")
super.deleteRecursively(fileOrDirectory)
}
override fun appendingSink(file: Path): Sink = FaultySink(super.appendingSink(file), file)
override fun sink(file: Path): Sink = FaultySink(super.sink(file), file)
inner class FaultySink(sink: Sink, private val file: Path) : ForwardingSink(sink) {
override fun write(source: Buffer, byteCount: Long) {
if (writeFaults.contains(file)) {
throw IOException("boom!")
} else {
super.write(source, byteCount)
}
}
}
} | apache-2.0 | c694654c2d54531beef2926ac5d89cce | 29.640449 | 98 | 0.715334 | 4.180982 | false | false | false | false |
spacecowboy/Feeder | app/src/main/java/com/nononsenseapps/feeder/ui/compose/navdrawer/NavDrawer.kt | 1 | 14221 | package com.nononsenseapps.feeder.ui.compose.navdrawer
import android.util.Log
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.ExperimentalAnimationApi
import androidx.compose.animation.core.animateFloatAsState
import androidx.compose.animation.core.tween
import androidx.compose.animation.expandVertically
import androidx.compose.animation.fadeIn
import androidx.compose.animation.fadeOut
import androidx.compose.animation.shrinkVertically
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.WindowInsets
import androidx.compose.foundation.layout.asPaddingValues
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.systemBars
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ExpandLess
import androidx.compose.material3.Divider
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.derivedStateOf
import androidx.compose.runtime.getValue
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.rotate
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.semantics.CustomAccessibilityAction
import androidx.compose.ui.semantics.clearAndSetSemantics
import androidx.compose.ui.semantics.contentDescription
import androidx.compose.ui.semantics.customActions
import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.semantics.stateDescription
import androidx.compose.ui.semantics.testTag
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import coil.compose.AsyncImage
import coil.request.ImageRequest
import coil.size.Precision
import coil.size.Scale
import com.nononsenseapps.feeder.R
import com.nononsenseapps.feeder.ui.compose.theme.FeederTheme
import com.nononsenseapps.feeder.ui.compose.utils.ImmutableHolder
import com.nononsenseapps.feeder.ui.compose.utils.immutableListHolderOf
import java.net.URL
const val COLLAPSE_ANIMATION_DURATION = 300
@ExperimentalAnimationApi
@Composable
@Preview(showBackground = true)
private fun ListOfFeedsAndTagsPreview() {
FeederTheme {
Surface {
ListOfFeedsAndTags(
immutableListHolderOf(
DrawerTop(unreadCount = 100, totalChildren = 4),
DrawerTag(
tag = "News tag",
unreadCount = 3,
-1111,
totalChildren = 2,
),
DrawerFeed(
id = 1, displayTitle = "Times", tag = "News tag", unreadCount = 1
),
DrawerFeed(
id = 2,
displayTitle = "Post",
imageUrl = URL("https://cowboyprogrammer.org/apple-touch-icon.png"),
tag = "News tag",
unreadCount = 2
),
DrawerTag(
tag = "Funny tag", unreadCount = 6, -2222, totalChildren = 1
),
DrawerFeed(
id = 3, displayTitle = "Hidden", tag = "Funny tag", unreadCount = 6
),
DrawerFeed(
id = 4, displayTitle = "Top Dog", unreadCount = 99, tag = ""
),
DrawerFeed(
id = 5,
imageUrl = URL("https://cowboyprogrammer.org/apple-touch-icon.png"),
displayTitle = "Cowboy Programmer",
unreadCount = 7,
tag = ""
),
),
ImmutableHolder(
setOf(
"News tag", "Funny tag"
)
),
{},
) {}
}
}
}
@ExperimentalAnimationApi
@Composable
fun ListOfFeedsAndTags(
feedsAndTags: ImmutableHolder<List<DrawerItemWithUnreadCount>>,
expandedTags: ImmutableHolder<Set<String>>,
onToggleTagExpansion: (String) -> Unit,
onItemClick: (DrawerItemWithUnreadCount) -> Unit,
) {
val firstTopFeed by remember(feedsAndTags) {
derivedStateOf {
feedsAndTags.item.asSequence().filterIsInstance<DrawerFeed>()
.filter { it.tag.isEmpty() }.firstOrNull()
}
}
LazyColumn(
contentPadding = WindowInsets.systemBars.asPaddingValues(),
modifier = Modifier
.fillMaxSize()
.semantics {
testTag = "feedsAndTags"
}
) {
items(feedsAndTags.item, key = { it.uiId }) { item ->
when (item) {
is DrawerTag -> {
ExpandableTag(
expanded = item.tag in expandedTags.item,
onToggleExpansion = onToggleTagExpansion,
unreadCount = item.unreadCount,
title = item.title(),
onItemClick = {
onItemClick(item)
}
)
}
is DrawerFeed -> {
when {
item.tag.isEmpty() -> {
if (item.id == firstTopFeed?.id) {
Divider(
modifier = Modifier.fillMaxWidth()
)
}
TopLevelFeed(
unreadCount = item.unreadCount,
title = item.title(),
imageUrl = item.imageUrl,
onItemClick = {
onItemClick(item)
}
)
}
else -> {
ChildFeed(
unreadCount = item.unreadCount,
title = item.title(),
imageUrl = item.imageUrl,
visible = item.tag in expandedTags.item,
onItemClick = {
onItemClick(item)
}
)
}
}
}
is DrawerTop -> AllFeeds(
unreadCount = item.unreadCount,
title = item.title(),
onItemClick = {
onItemClick(item)
}
)
}
}
}
}
@ExperimentalAnimationApi
@Preview(showBackground = true)
@Composable
private fun ExpandableTag(
title: String = "Foo",
unreadCount: Int = 99,
expanded: Boolean = true,
onToggleExpansion: (String) -> Unit = {},
onItemClick: () -> Unit = {},
) {
val angle: Float by animateFloatAsState(
targetValue = if (expanded) 0f else 180f, animationSpec = tween()
)
val toggleExpandLabel = stringResource(id = R.string.toggle_tag_expansion)
val expandedLabel = stringResource(id = R.string.expanded_tag)
val contractedLabel = stringResource(id = R.string.contracted_tag)
Row(
verticalAlignment = Alignment.CenterVertically,
modifier = Modifier
.clickable(onClick = onItemClick)
.padding(top = 2.dp, bottom = 2.dp, end = 16.dp)
.fillMaxWidth()
.height(48.dp)
.semantics(mergeDescendants = true) {
try {
stateDescription = if (expanded) {
expandedLabel
} else {
contractedLabel
}
customActions = listOf(
CustomAccessibilityAction(toggleExpandLabel) {
onToggleExpansion(title)
true
}
)
} catch (e: Exception) {
// Observed nullpointer exception when setting customActions
// No clue why it could be null
Log.e("FeederNavDrawer", "Exception in semantics", e)
}
}
) {
ExpandArrow(degrees = angle, onClick = {
onToggleExpansion(title)
})
Box(
modifier = Modifier
.fillMaxHeight()
.weight(1.0f, fill = true)
) {
Text(
text = title,
maxLines = 1,
modifier = Modifier
.padding(end = 2.dp)
.fillMaxWidth()
.align(Alignment.CenterStart)
)
}
val unreadLabel = LocalContext.current.resources.getQuantityString(
R.plurals.n_unread_articles,
unreadCount,
unreadCount
)
Text(
text = unreadCount.toString(),
maxLines = 1,
modifier = Modifier
.padding(start = 2.dp)
.semantics {
contentDescription = unreadLabel
}
)
}
}
@Composable
private fun ExpandArrow(
degrees: Float,
onClick: () -> Unit,
) {
IconButton(onClick = onClick, modifier = Modifier.clearAndSetSemantics { }) {
Icon(
Icons.Filled.ExpandLess,
contentDescription = stringResource(id = R.string.toggle_tag_expansion),
modifier = Modifier.rotate(degrees = degrees)
)
}
}
@Preview(showBackground = true)
@Composable
private fun AllFeeds(
title: String = "Foo",
unreadCount: Int = 99,
onItemClick: () -> Unit = {},
) = Feed(
title = title,
imageUrl = null,
unreadCount = unreadCount,
startPadding = 16.dp,
onItemClick = onItemClick,
)
@Preview(showBackground = true)
@Composable
private fun TopLevelFeed(
title: String = "Foo",
unreadCount: Int = 99,
onItemClick: () -> Unit = {},
imageUrl: URL? = null,
) = Feed(
title = title,
imageUrl = imageUrl,
unreadCount = unreadCount,
startPadding = when (imageUrl) {
null -> 48.dp
else -> 0.dp
},
onItemClick = onItemClick,
)
@Preview(showBackground = true)
@Composable
private fun ChildFeed(
title: String = "Foo",
imageUrl: URL? = null,
unreadCount: Int = 99,
visible: Boolean = true,
onItemClick: () -> Unit = {},
) {
AnimatedVisibility(
visible = visible,
enter = fadeIn() + expandVertically(expandFrom = Alignment.Top),
exit = shrinkVertically(shrinkTowards = Alignment.Top) + fadeOut()
) {
Feed(
title = title,
imageUrl = imageUrl,
unreadCount = unreadCount,
startPadding = when (imageUrl) {
null -> 48.dp
else -> 0.dp
},
onItemClick = onItemClick,
)
}
}
@Composable
private fun Feed(
title: String,
imageUrl: URL?,
unreadCount: Int,
startPadding: Dp,
onItemClick: () -> Unit,
) {
Row(
horizontalArrangement = Arrangement.spacedBy(4.dp),
verticalAlignment = Alignment.CenterVertically,
modifier = Modifier
.clickable(onClick = onItemClick)
.padding(
start = startPadding, end = 16.dp, top = 2.dp, bottom = 2.dp
)
.fillMaxWidth()
.height(48.dp)
) {
if (imageUrl != null) {
Box(
contentAlignment = Alignment.Center,
modifier = Modifier
.height(48.dp)
// Taking 4dp spacing into account
.width(44.dp),
) {
AsyncImage(
model = ImageRequest.Builder(LocalContext.current)
.data(imageUrl.toString()).listener(onError = { a, b ->
Log.e("FEEDER_DRAWER", "error ${a.data}", b.throwable)
}).scale(Scale.FIT).size(64).precision(Precision.INEXACT).build(),
contentDescription = stringResource(id = R.string.feed_icon),
contentScale = ContentScale.Crop,
modifier = Modifier.size(24.dp)
)
}
}
Box(
modifier = Modifier
.fillMaxHeight()
.weight(1.0f, fill = true)
) {
Text(
text = title,
maxLines = 1,
modifier = Modifier
.fillMaxWidth()
.align(Alignment.CenterStart)
)
}
val unreadLabel = LocalContext.current.resources.getQuantityString(
R.plurals.n_unread_articles,
unreadCount,
unreadCount
)
Text(
text = unreadCount.toString(), maxLines = 1,
modifier = Modifier.semantics {
contentDescription = unreadLabel
}
)
}
}
| gpl-3.0 | f9610cf2fd3c86529606f71e2c82350e | 33.51699 | 92 | 0.535405 | 5.286617 | false | false | false | false |
StepicOrg/stepik-android | app/src/main/java/org/stepik/android/domain/course_list/interactor/RemindAppNotificationInteractor.kt | 2 | 1365 | package org.stepik.android.domain.course_list.interactor
import org.stepic.droid.preferences.SharedPreferenceHelper
import org.stepik.android.domain.base.DataSourceType
import org.stepik.android.domain.user_courses.repository.UserCoursesRepository
import javax.inject.Inject
class RemindAppNotificationInteractor
@Inject
constructor(
private val sharedPreferenceHelper: SharedPreferenceHelper,
private val userCoursesRepository: UserCoursesRepository
) {
fun isNotificationShown(): Boolean {
val isFirstDayNotificationShown = sharedPreferenceHelper.isNotificationWasShown(SharedPreferenceHelper.NotificationDay.DAY_ONE)
val isSevenDayNotificationShown = sharedPreferenceHelper.isNotificationWasShown(SharedPreferenceHelper.NotificationDay.DAY_SEVEN)
// already shown.
// do not show again
return isFirstDayNotificationShown && isSevenDayNotificationShown
}
fun hasUserInteractedWithApp(): Boolean =
sharedPreferenceHelper.authResponseFromStore == null ||
sharedPreferenceHelper.isStreakNotificationEnabled ||
hasEnrolledCourses() ||
sharedPreferenceHelper.anyStepIsSolved()
private fun hasEnrolledCourses(): Boolean =
userCoursesRepository
.getUserCourses(sourceType = DataSourceType.CACHE)
.blockingGet()
.isNotEmpty()
} | apache-2.0 | 503084d3661c5868f03a157dc85532f1 | 40.393939 | 137 | 0.773626 | 5.640496 | false | false | false | false |
allotria/intellij-community | python/src/com/jetbrains/python/console/PythonConsoleRemoteProcessCreator.kt | 10 | 4580 | /*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.jetbrains.python.console
import com.intellij.execution.ExecutionException
import com.intellij.execution.configurations.GeneralCommandLine
import com.intellij.execution.process.ProcessHandler
import com.intellij.openapi.extensions.ExtensionPointName
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Ref
import com.intellij.remote.CredentialsType
import com.intellij.remote.ext.CredentialsCase
import com.jetbrains.python.PyBundle
import com.jetbrains.python.remote.PyRemotePathMapper
import com.jetbrains.python.remote.PyRemoteSdkAdditionalDataBase
import com.jetbrains.python.remote.PyRemoteSocketToLocalHostProvider
import java.io.IOException
interface PythonConsoleRemoteProcessCreator<T> {
val credentialsType: CredentialsType<T>
@Throws(ExecutionException::class)
fun createRemoteConsoleProcess(commandLine: GeneralCommandLine,
pathMapper: PyRemotePathMapper,
project: Project,
data: PyRemoteSdkAdditionalDataBase,
runnerFileFromHelpers: String,
credentials: T): RemoteConsoleProcessData
/**
* Tries to create a remote tunnel.
* @return Port on the remote server or null if port forwarding by this method is not implemented.
*/
@JvmDefault
@Throws(IOException::class)
fun createRemoteTunnel(project: Project,
data: PyRemoteSdkAdditionalDataBase,
localPort: Int): Int? = localPort
companion object {
@JvmField
val EP_NAME: ExtensionPointName<PythonConsoleRemoteProcessCreator<Any>> = ExtensionPointName.create<PythonConsoleRemoteProcessCreator<Any>>(
"Pythonid.remoteConsoleProcessCreator")
}
}
data class RemoteConsoleProcessData(val remoteProcessHandlerBase: ProcessHandler,
val pydevConsoleCommunication: PydevConsoleCommunication,
val commandLine: String?,
val process: Process,
val socketProvider: PyRemoteSocketToLocalHostProvider)
@Throws(ExecutionException::class)
fun createRemoteConsoleProcess(commandLine: GeneralCommandLine,
pathMapper: PyRemotePathMapper,
project: Project,
data: PyRemoteSdkAdditionalDataBase,
runnerFileFromHelpers: String): RemoteConsoleProcessData {
val extensions = PythonConsoleRemoteProcessCreator.EP_NAME.extensions
val result = Ref.create<RemoteConsoleProcessData>()
val exception = Ref.create<ExecutionException>()
val collectedCases = extensions.map {
object : CredentialsCase<Any> {
override fun getType(): CredentialsType<Any> = it.credentialsType
override fun process(credentials: Any) {
try {
val remoteConsoleProcess = it.createRemoteConsoleProcess(commandLine = commandLine,
pathMapper = pathMapper,
project = project,
data = data,
runnerFileFromHelpers = runnerFileFromHelpers,
credentials = credentials)
result.set(remoteConsoleProcess)
}
catch (e: ExecutionException) {
exception.set(e)
}
}
} as CredentialsCase<Any>
}
data.switchOnConnectionType(*collectedCases.toTypedArray())
if (!exception.isNull) {
throw exception.get()
}
else if (!result.isNull) {
return result.get()
}
else {
throw ExecutionException(PyBundle.message("python.console.not.supported", data.remoteConnectionType.name))
}
} | apache-2.0 | 5faf8801df0b0593531c45210649786f | 41.813084 | 144 | 0.644541 | 5.849298 | false | false | false | false |
JuliusKunze/kotlin-native | backend.native/tests/external/codegen/box/innerNested/importNestedClass.kt | 5 | 220 | import A.B
import A.B.C
class A {
class B {
class C
}
}
fun box(): String {
val a = A()
val b = B()
val ab = A.B()
val c = C()
val bc = B.C()
val abc = A.B.C()
return "OK"
}
| apache-2.0 | d7119ce854b38d326b598aa0585d8b2c | 11.222222 | 21 | 0.422727 | 2.55814 | false | false | false | false |
blokadaorg/blokada | android5/app/src/main/java/repository/AppRepository.kt | 1 | 5014 | /*
* This file is part of Blokada.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*
* Copyright © 2021 Blocka AB. All rights reserved.
*
* @author Karol Gusak ([email protected])
*/
package repository
import android.content.pm.ApplicationInfo
import android.content.pm.PackageManager
import android.graphics.drawable.Drawable
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.async
import model.App
import model.AppId
import model.BypassedAppIds
import service.ContextService
import service.PersistenceService
import ui.utils.cause
import utils.Logger
object AppRepository {
private val log = Logger("AppRepository")
private val context = ContextService
private val persistence = PersistenceService
private val scope = GlobalScope
private var bypassedAppIds = persistence.load(BypassedAppIds::class).ids
set(value) {
persistence.save(BypassedAppIds(value))
field = value
}
private val alwaysBypassed by lazy {
listOf<AppId>(
// This app package name
context.requireContext().packageName
)
}
private val bypassedForFakeVpn = listOf(
"com.android.vending",
"com.android.providers.downloads",
"com.google.android.apps.fireball",
"com.google.android.apps.authenticator2",
"com.google.android.apps.docs",
"com.google.android.apps.tachyon",
"com.google.android.gm",
"com.google.android.apps.photos",
"com.google.android.play.games",
"org.thoughtcrime.securesms",
"com.plexapp.android",
"org.kde.kdeconnect_tp",
"com.samsung.android.email.provider",
"com.xda.labs",
"com.android.incallui",
"com.android.phone",
"com.android.providers.telephony",
"com.huawei.systemmanager",
"com.android.service.ims.RcsServiceApp",
"com.google.android.carriersetup",
"com.google.android.ims",
"com.codeaurora.ims",
"com.android.carrierconfig",
"ch.threema.app",
"ch.threema.app.work",
"ch.threema.app.hms",
"ch.threema.app.work.hms",
"com.xiaomi.discover",
"eu.siacs.conversations",
"org.jitsi.meet",
"com.tomtom.speedcams.android.map",
"com.tomtom.amigo.huawei",
// RCS: https://github.com/blokadaorg/blokadaorg.github.io/pull/31
"com.android.service.ims.RcsServiceApp",
"com.google.android.carriersetup",
"com.google.android.ims",
"com.codeaurora.ims",
"com.android.carrierconfig",
// MaaiiConnect #885
"com.m800.liveconnect.mobile.agent.prod",
"com.m800.liveconnect.mobile.agent.tb",
// TomTom Go #878
"com.tomtom.gplay.navapp"
)
fun getPackageNamesOfAppsToBypass(forRealTunnel: Boolean = false): List<AppId> {
return if (forRealTunnel) alwaysBypassed + bypassedAppIds
else alwaysBypassed + bypassedForFakeVpn + bypassedAppIds
}
suspend fun getApps(): List<App> {
return scope.async(Dispatchers.Default) {
log.v("Fetching apps")
val ctx = context.requireContext()
val installed = try {
ctx.packageManager.getInstalledApplications(PackageManager.GET_META_DATA)
.filter { it.packageName != ctx.packageName }
} catch (ex: Exception) {
log.w("Could not fetch apps, ignoring".cause(ex))
emptyList<ApplicationInfo>()
}
log.v("Fetched ${installed.size} apps, mapping")
val apps = installed.mapNotNull {
try {
App(
id = it.packageName,
name = ctx.packageManager.getApplicationLabel(it).toString(),
isSystem = (it.flags and ApplicationInfo.FLAG_SYSTEM) != 0,
isBypassed = isAppBypassed(it.packageName)
)
} catch (ex: Exception) {
log.w("Could not map app, ignoring".cause(ex))
null
}
}
log.v("Mapped ${apps.size} apps")
apps
}.await()
}
fun isAppBypassed(id: AppId): Boolean {
return bypassedAppIds.contains(id)
}
fun switchBypassForApp(id: AppId) {
if (isAppBypassed(id)) bypassedAppIds -= id
else bypassedAppIds += id
}
fun getAppIcon(id: AppId): Drawable? {
return try {
val ctx = context.requireContext()
ctx.packageManager.getApplicationIcon(
ctx.packageManager.getApplicationInfo(id, PackageManager.GET_META_DATA)
)
} catch (e: Exception) {
null
}
}
}
| mpl-2.0 | b12fd162217a7fc4d93851890ba8c3f7 | 32.42 | 89 | 0.605027 | 4.233953 | false | false | false | false |
mglukhikh/intellij-community | platform/diff-impl/src/com/intellij/diff/tools/util/base/TextDiffSettingsHolder.kt | 1 | 6473 | // 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.diff.tools.util.base
import com.intellij.diff.util.DiffPlaces
import com.intellij.diff.util.DiffUtil
import com.intellij.openapi.Disposable
import com.intellij.openapi.components.PersistentStateComponent
import com.intellij.openapi.components.State
import com.intellij.openapi.components.Storage
import com.intellij.openapi.components.service
import com.intellij.openapi.util.Key
import com.intellij.util.EventDispatcher
import com.intellij.util.xmlb.annotations.OptionTag
import com.intellij.util.xmlb.annotations.Transient
import com.intellij.util.xmlb.annotations.XMap
import java.util.*
@State(
name = "TextDiffSettings",
storages = arrayOf(Storage(value = DiffUtil.DIFF_CONFIG))
)
class TextDiffSettingsHolder : PersistentStateComponent<TextDiffSettingsHolder.State> {
companion object {
@JvmField val CONTEXT_RANGE_MODES: IntArray = intArrayOf(1, 2, 4, 8, -1)
@JvmField val CONTEXT_RANGE_MODE_LABELS: Array<String> = arrayOf("1", "2", "4", "8", "Disable")
}
data class SharedSettings(
// Fragments settings
var CONTEXT_RANGE: Int = 4,
var MERGE_AUTO_APPLY_NON_CONFLICTED_CHANGES: Boolean = false,
var MERGE_LST_GUTTER_MARKERS: Boolean = true
)
data class PlaceSettings(
// Diff settings
var HIGHLIGHT_POLICY: HighlightPolicy = HighlightPolicy.BY_WORD,
var IGNORE_POLICY: IgnorePolicy = IgnorePolicy.DEFAULT,
// Presentation settings
var ENABLE_SYNC_SCROLL: Boolean = true,
// Editor settings
var SHOW_WHITESPACES: Boolean = false,
var SHOW_LINE_NUMBERS: Boolean = true,
var SHOW_INDENT_LINES: Boolean = false,
var USE_SOFT_WRAPS: Boolean = false,
var HIGHLIGHTING_LEVEL: HighlightingLevel = HighlightingLevel.INSPECTIONS,
var READ_ONLY_LOCK: Boolean = true,
// Fragments settings
var EXPAND_BY_DEFAULT: Boolean = true
) {
@Transient
val eventDispatcher: EventDispatcher<TextDiffSettings.Listener> = EventDispatcher.create(TextDiffSettings.Listener::class.java)
}
class TextDiffSettings internal constructor(private val SHARED_SETTINGS: SharedSettings,
private val PLACE_SETTINGS: PlaceSettings) {
constructor() : this(SharedSettings(), PlaceSettings())
fun addListener(listener: Listener, disposable: Disposable) {
PLACE_SETTINGS.eventDispatcher.addListener(listener, disposable)
}
// Presentation settings
var isEnableSyncScroll: Boolean
get() = PLACE_SETTINGS.ENABLE_SYNC_SCROLL
set(value) { PLACE_SETTINGS.ENABLE_SYNC_SCROLL = value }
// Diff settings
var highlightPolicy: HighlightPolicy
get() = PLACE_SETTINGS.HIGHLIGHT_POLICY
set(value) { PLACE_SETTINGS.HIGHLIGHT_POLICY = value
PLACE_SETTINGS.eventDispatcher.multicaster.highlightPolicyChanged() }
var ignorePolicy: IgnorePolicy
get() = PLACE_SETTINGS.IGNORE_POLICY
set(value) { PLACE_SETTINGS.IGNORE_POLICY = value
PLACE_SETTINGS.eventDispatcher.multicaster.ignorePolicyChanged() }
//
// Merge
//
var isAutoApplyNonConflictedChanges: Boolean
get() = SHARED_SETTINGS.MERGE_AUTO_APPLY_NON_CONFLICTED_CHANGES
set(value) { SHARED_SETTINGS.MERGE_AUTO_APPLY_NON_CONFLICTED_CHANGES = value }
var isEnableLstGutterMarkersInMerge: Boolean
get() = SHARED_SETTINGS.MERGE_LST_GUTTER_MARKERS
set(value) { SHARED_SETTINGS.MERGE_LST_GUTTER_MARKERS = value }
// Editor settings
var isShowLineNumbers: Boolean
get() = PLACE_SETTINGS.SHOW_LINE_NUMBERS
set(value) { PLACE_SETTINGS.SHOW_LINE_NUMBERS = value }
var isShowWhitespaces: Boolean
get() = PLACE_SETTINGS.SHOW_WHITESPACES
set(value) { PLACE_SETTINGS.SHOW_WHITESPACES = value }
var isShowIndentLines: Boolean
get() = PLACE_SETTINGS.SHOW_INDENT_LINES
set(value) { PLACE_SETTINGS.SHOW_INDENT_LINES = value }
var isUseSoftWraps: Boolean
get() = PLACE_SETTINGS.USE_SOFT_WRAPS
set(value) { PLACE_SETTINGS.USE_SOFT_WRAPS = value }
var highlightingLevel: HighlightingLevel
get() = PLACE_SETTINGS.HIGHLIGHTING_LEVEL
set(value) { PLACE_SETTINGS.HIGHLIGHTING_LEVEL = value }
var contextRange: Int
get() = SHARED_SETTINGS.CONTEXT_RANGE
set(value) { SHARED_SETTINGS.CONTEXT_RANGE = value }
var isExpandByDefault: Boolean
get() = PLACE_SETTINGS.EXPAND_BY_DEFAULT
set(value) { PLACE_SETTINGS.EXPAND_BY_DEFAULT = value }
var isReadOnlyLock: Boolean
get() = PLACE_SETTINGS.READ_ONLY_LOCK
set(value) { PLACE_SETTINGS.READ_ONLY_LOCK = value }
//
// Impl
//
companion object {
@JvmField val KEY: Key<TextDiffSettings> = Key.create("TextDiffSettings")
@JvmStatic fun getSettings(): TextDiffSettings = getSettings(null)
@JvmStatic fun getSettings(place: String?): TextDiffSettings = service<TextDiffSettingsHolder>().getSettings(place)
}
interface Listener : EventListener {
fun highlightPolicyChanged() {}
fun ignorePolicyChanged() {}
}
}
fun getSettings(place: String?): TextDiffSettings {
val placeKey = place ?: DiffPlaces.DEFAULT
val placeSettings = myState.PLACES_MAP.getOrPut(placeKey, { defaultPlaceSettings(placeKey) })
return TextDiffSettings(myState.SHARED_SETTINGS, placeSettings)
}
private fun copyStateWithoutDefaults(): State {
val result = State()
result.SHARED_SETTINGS = myState.SHARED_SETTINGS
result.PLACES_MAP = DiffUtil.trimDefaultValues(myState.PLACES_MAP, { defaultPlaceSettings(it) })
return result
}
private fun defaultPlaceSettings(place: String): PlaceSettings {
val settings = PlaceSettings()
if (place == DiffPlaces.CHANGES_VIEW) {
settings.EXPAND_BY_DEFAULT = false
}
if (place == DiffPlaces.COMMIT_DIALOG) {
settings.EXPAND_BY_DEFAULT = false
}
return settings
}
class State {
@OptionTag
@XMap
@JvmField var PLACES_MAP: TreeMap<String, PlaceSettings> = TreeMap()
@JvmField var SHARED_SETTINGS = SharedSettings()
}
private var myState: State = State()
override fun getState(): State {
return copyStateWithoutDefaults()
}
override fun loadState(state: State) {
myState = state
}
} | apache-2.0 | 9b7d8b5719d9fddae138ec05af922fd8 | 33.253968 | 140 | 0.702765 | 4.412406 | false | false | false | false |
smmribeiro/intellij-community | java/java-impl/src/com/intellij/refactoring/extractMethod/newImpl/JavaDuplicatesFinder.kt | 7 | 8706 | // 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 com.intellij.refactoring.extractMethod.newImpl
import com.intellij.openapi.util.Key
import com.intellij.openapi.util.TextRange
import com.intellij.psi.*
import com.intellij.psi.util.PsiTreeUtil
data class ChangedExpression(val pattern: PsiExpression, val candidate: PsiExpression)
data class Duplicate(val pattern: List<PsiElement>, val candidate: List<PsiElement>, val changedExpressions: List<ChangedExpression>)
class JavaDuplicatesFinder(pattern: List<PsiElement>, private val predefinedChanges: Set<PsiExpression> = emptySet()) {
companion object {
private val ELEMENT_IN_PHYSICAL_FILE = Key<PsiElement>("ELEMENT_IN_PHYSICAL_FILE")
/**
* Ensures that all [PsiMember] elements in copied [root] will be linked to [PsiMember] in the original [root] element.
* These links are used to compare references between copied and original files.
*/
fun linkCopiedClassMembersWithOrigin(root: PsiElement) {
SyntaxTraverser.psiTraverser(root).filter(PsiMember::class.java).forEach { member ->
member.putCopyableUserData(ELEMENT_IN_PHYSICAL_FILE, member)
}
}
private fun getElementInPhysicalFile(element: PsiElement): PsiElement? = element.getCopyableUserData(ELEMENT_IN_PHYSICAL_FILE)
fun textRangeOf(range: List<PsiElement>) = TextRange(range.first().textRange.startOffset, range.last().textRange.endOffset)
}
private val pattern: List<PsiElement> = pattern.filterNot(::isNoise)
fun withPredefinedChanges(predefinedChanges: Set<PsiExpression>): JavaDuplicatesFinder {
return JavaDuplicatesFinder(pattern, this.predefinedChanges + predefinedChanges)
}
fun findDuplicates(scope: PsiElement): List<Duplicate> {
val ignoredElements = HashSet<PsiElement>(pattern)
val duplicates = mutableListOf<Duplicate>()
val patternExpression = pattern.singleOrNull() as? PsiExpression
val visitor = if (patternExpression != null) {
object : JavaRecursiveElementWalkingVisitor(){
override fun visitExpression(expression: PsiExpression) {
if (expression in ignoredElements) return
val duplicate = createDuplicate(childrenOf(patternExpression), childrenOf(expression))
if (duplicate != null) {
duplicates += duplicate.copy(pattern = listOf(patternExpression), candidate = listOf(expression))
} else {
super.visitExpression(expression)
}
}
}
} else {
object: JavaRecursiveElementWalkingVisitor() {
override fun visitStatement(statement: PsiStatement) {
if (statement in ignoredElements) return
val siblings = siblingsOf(statement).take(pattern.size).toList()
val duplicate = createDuplicate(pattern, siblings)
if (duplicate != null) {
duplicates += duplicate
ignoredElements += duplicate.candidate
} else {
super.visitStatement(statement)
}
}
}
}
scope.accept(visitor)
return duplicates.filterNot(::isOvercomplicated)
}
private fun isNoise(it: PsiElement) = it is PsiWhiteSpace || it is PsiComment || it is PsiEmptyStatement
private fun siblingsOf(element: PsiElement?): Sequence<PsiElement> {
return if (element != null) {
generateSequence(element) { it.nextSibling }.filterNot(::isNoise)
} else {
emptySequence()
}
}
private fun childrenOf(element: PsiElement?): List<PsiElement> {
return siblingsOf(element?.firstChild).toList()
}
fun createExpressionDuplicate(pattern: PsiExpression, candidate: PsiExpression): Duplicate? {
return createDuplicate(childrenOf(pattern), childrenOf(candidate))
?.copy(pattern = listOf(pattern), candidate = listOf(candidate))
}
fun createDuplicate(pattern: List<PsiElement>, candidate: List<PsiElement>): Duplicate? {
val changedExpressions = ArrayList<ChangedExpression>()
if (!traverseAndCollectChanges(pattern, candidate, changedExpressions)) return null
return removeInternalReferences(Duplicate(pattern, candidate, changedExpressions))
}
private fun removeInternalReferences(duplicate: Duplicate): Duplicate? {
val patternDeclarations = duplicate.pattern.flatMap { PsiTreeUtil.findChildrenOfType(it, PsiVariable::class.java) }
val candidateDeclarations = duplicate.candidate.flatMap { PsiTreeUtil.findChildrenOfType(it, PsiVariable::class.java) }
val declarationsMapping = patternDeclarations.zip(candidateDeclarations).toMap()
val changedExpressions = duplicate.changedExpressions.filterNot { (pattern, candidate) ->
val patternVariable = (pattern as? PsiReferenceExpression)?.resolve()
val candidateVariable = (candidate as? PsiReferenceExpression)?.resolve()
if (patternVariable !in declarationsMapping.keys && candidateVariable !in declarationsMapping.values) return@filterNot false
if (declarationsMapping[patternVariable] != candidateVariable) return null
return@filterNot true
}
if (ExtractMethodHelper.hasReferencesToScope(duplicate.pattern, changedExpressions.map{ change -> change.pattern }) ||
ExtractMethodHelper.hasReferencesToScope(duplicate.candidate, changedExpressions.map { change -> change.candidate })){
return null
}
return duplicate.copy(changedExpressions = changedExpressions)
}
fun traverseAndCollectChanges(pattern: List<PsiElement>,
candidate: List<PsiElement>,
changedExpressions: MutableList<ChangedExpression>): Boolean {
if (candidate.size != pattern.size) return false
val notEqualElements = pattern.zip(candidate).filterNot { (pattern, candidate) ->
pattern !in predefinedChanges &&
areEquivalent(pattern, candidate) &&
traverseAndCollectChanges(childrenOf(pattern), childrenOf(candidate), changedExpressions)
}
if (notEqualElements.any { (pattern, candidate) -> ! canBeReplaced(pattern, candidate) }) return false
changedExpressions += notEqualElements.map { (pattern, candidate) -> ChangedExpression(pattern as PsiExpression, candidate as PsiExpression) }
return true
}
fun areEquivalent(pattern: PsiElement, candidate: PsiElement): Boolean {
return when {
pattern is PsiTypeElement && candidate is PsiTypeElement -> canBeReplaced(pattern.type, candidate.type)
pattern is PsiJavaCodeReferenceElement && candidate is PsiJavaCodeReferenceElement ->
areElementsEquivalent(pattern.resolve(), candidate.resolve())
pattern is PsiLiteralExpression && candidate is PsiLiteralExpression -> pattern.text == candidate.text
pattern.node?.elementType == candidate.node?.elementType -> true
else -> false
}
}
private fun areElementsEquivalent(pattern: PsiElement?, candidate: PsiElement?): Boolean {
val manager = pattern?.manager ?: return false
return manager.areElementsEquivalent(getElementInPhysicalFile(pattern) ?: pattern, candidate)
}
private fun canBeReplaced(pattern: PsiElement, candidate: PsiElement): Boolean {
return when {
pattern.parent is PsiExpressionStatement -> false
pattern is PsiReferenceExpression && pattern.parent is PsiCall -> false
pattern is PsiExpression && candidate is PsiExpression -> pattern.type != PsiType.VOID && canBeReplaced(pattern.type, candidate.type)
else -> false
}
}
private fun canBeReplaced(pattern: PsiType?, candidate: PsiType?): Boolean {
if (pattern == null || candidate == null) return false
if (pattern is PsiDiamondType && candidate is PsiDiamondType) {
val patternTypes = getInferredTypes(pattern) ?: return false
val candidateTypes = getInferredTypes(candidate) ?: return false
if (patternTypes.size != candidateTypes.size) return false
return patternTypes.indices.all { i -> canBeReplaced(patternTypes[i], candidateTypes[i]) }
}
return pattern.isAssignableFrom(candidate)
}
private fun getInferredTypes(diamondType: PsiDiamondType): List<PsiType>? {
return diamondType.resolveInferredTypes()?.takeIf { resolveResult -> !resolveResult.failedToInfer() }?.inferredTypes
}
private fun isOvercomplicated(duplicate: Duplicate): Boolean {
val singleChangedExpression = duplicate.changedExpressions.singleOrNull()?.pattern ?: return false
val singleDeclaration = duplicate.pattern.singleOrNull() as? PsiDeclarationStatement
val variable = singleDeclaration?.declaredElements?.singleOrNull() as? PsiVariable
return variable?.initializer == singleChangedExpression
}
} | apache-2.0 | 1e4e63d28f531e51eda1b3566ef51b7c | 46.320652 | 158 | 0.732139 | 5.109155 | false | false | false | false |
WillowChat/Kale | src/test/kotlin/chat/willow/kale/irc/message/extension/batch/BatchEndMessageTests.kt | 2 | 1844 | package chat.willow.kale.irc.message.extension.batch
import chat.willow.kale.core.message.IrcMessage
import chat.willow.kale.irc.prefix.prefix
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNull
import org.junit.Before
import org.junit.Test
class BatchEndMessageTests {
private lateinit var messageParser: BatchMessage.End.Message.Parser
private lateinit var messageSerialiser: BatchMessage.End.Message.Serialiser
@Before fun setUp() {
messageParser = BatchMessage.End.Message.Parser
messageSerialiser= BatchMessage.End.Message.Serialiser
}
@Test fun test_parse_ReferenceWithCorrectToken() {
val message = messageParser.parse(IrcMessage(command = "BATCH", prefix = "someone", parameters = listOf("-batch1")))
assertEquals(BatchMessage.End.Message(source = prefix("someone"), reference = "batch1"), message)
}
@Test fun test_parse_MissingMinusCharacter_ReturnsNull() {
val message = messageParser.parse(IrcMessage(command = "BATCH", prefix = "someone", parameters = listOf("batch1")))
assertNull(message)
}
@Test fun test_parse_TooFewParameters_ReturnsNull() {
val messageOne = messageParser.parse(IrcMessage(command = "BATCH", prefix = "someone", parameters = listOf()))
assertNull(messageOne)
}
@Test fun test_parse_NoPrefix_ReturnsNull() {
val messageOne = messageParser.parse(IrcMessage(command = "BATCH", prefix = null, parameters = listOf("-batch1")))
assertNull(messageOne)
}
@Test fun test_serialise_WithReference() {
val message = messageSerialiser.serialise(BatchMessage.End.Message(source = prefix("someone"), reference = "reference"))
assertEquals(IrcMessage(command = "BATCH", prefix = "someone", parameters = listOf("-reference")), message)
}
} | isc | bd3c7af34dc4d8cbb4bfacde5a412451 | 35.9 | 128 | 0.715293 | 4.475728 | false | true | false | false |
firebase/firebase-android-sdk | buildSrc/src/test/kotlin/com/google/firebase/gradle/plugins/publishing.kt | 1 | 6716 | // Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.firebase.gradle.plugins
import java.io.File
import javax.xml.parsers.DocumentBuilderFactory
import org.gradle.api.GradleException
import org.w3c.dom.Element
import org.w3c.dom.NodeList
data class Project(
val name: String,
val group: String = "com.example",
val version: String = "undefined",
val latestReleasedVersion: String? = null,
val projectDependencies: Set<Project> = setOf(),
val externalDependencies: Set<Artifact> = setOf(),
val releaseWith: Project? = null,
val customizePom: String? = null,
val publishJavadoc: Boolean = false,
val libraryType: LibraryType = LibraryType.ANDROID
) {
fun generateBuildFile(): String {
return """
plugins {
id 'firebase-${if (libraryType == LibraryType.JAVA) "java-" else ""}library'
}
group = '$group'
version = '$version'
${if (latestReleasedVersion != null) "ext.latestReleasedVersion = $latestReleasedVersion" else ""}
firebaseLibrary {
${if (releaseWith != null) "releaseWith project(':${releaseWith.name}')" else ""}
${if (customizePom != null) "customizePom {$customizePom}" else ""}
${"publishJavadoc = $publishJavadoc"}
}
${if (libraryType == LibraryType.ANDROID) "android.compileSdkVersion = 26" else ""}
dependencies {
${projectDependencies.joinToString("\n") { "implementation project(':${it.name}')" }}
${externalDependencies.joinToString("\n") { "implementation '${it.simpleDepString}'" }}
}
"""
}
fun getPublishedPom(rootDirectory: String): Pom? {
val v = releaseWith?.version ?: version
return File(rootDirectory)
.walk()
.asSequence()
.filter { it.isFile }
.filter { it.path.matches(Regex(".*/${group.replace('.', '/')}/$name/$v.*/.*\\.pom$")) }
.map(Pom::parse)
.firstOrNull()
}
}
data class License(val name: String, val url: String)
enum class Type {
JAR,
AAR
}
data class Artifact(
val groupId: String,
val artifactId: String,
val version: String,
val type: Type = Type.JAR,
val scope: String = ""
) {
val simpleDepString: String
get() = "$groupId:$artifactId:$version"
}
data class Pom(
val artifact: Artifact,
val license: License =
License(
name = "The Apache Software License, Version 2.0",
url = "http://www.apache.org/licenses/LICENSE-2.0.txt"
),
val dependencies: List<Artifact> = listOf()
) {
companion object {
fun parse(file: File): Pom {
val document = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(file)
val childNodes = document.documentElement.childNodes
var groupId: String? = null
var artifactId: String? = null
var version: String? = null
var type = Type.JAR
var license: License? = null
var deps: List<Artifact> = listOf()
for (i in 0 until childNodes.length) {
val child = childNodes.item(i)
if (child !is Element) {
continue
}
when (child.tagName) {
"groupId" -> groupId = child.textContent.trim()
"artifactId" -> artifactId = child.textContent.trim()
"version" -> version = child.textContent.trim()
"packaging" -> type = Type.valueOf(child.textContent.trim().toUpperCase())
"licenses" -> license = parseLicense(child.getElementsByTagName("license"))
"dependencies" -> deps = parseDeps(child.getElementsByTagName("dependency"))
}
}
if (groupId == null) {
throw GradleException("'<groupId>' missing in pom")
}
if (artifactId == null) {
throw GradleException("'<artifactId>' missing in pom")
}
if (version == null) {
throw GradleException("'<version>' missing in pom")
}
if (license == null) {
throw GradleException("'<license>' missing in pom")
}
return Pom(Artifact(groupId, artifactId, version, type), license, deps)
}
private fun parseDeps(nodes: NodeList): List<Artifact> {
val deps = mutableListOf<Artifact>()
for (i in 0 until nodes.length) {
val child = nodes.item(i)
if (child !is Element) {
continue
}
deps.add(parseDep(child))
}
return deps
}
private fun parseDep(dependencies: Element): Artifact {
var groupId: String? = null
var artifactId: String? = null
var version: String? = null
var type = Type.JAR
var scope: String? = null
val nodes = dependencies.childNodes
for (i in 0 until nodes.length) {
val child = nodes.item(i)
if (child !is Element) {
continue
}
when (child.tagName) {
"groupId" -> groupId = child.textContent.trim()
"artifactId" -> artifactId = child.textContent.trim()
"version" -> version = child.textContent.trim()
"type" -> type = Type.valueOf(child.textContent.trim().toUpperCase())
"scope" -> scope = child.textContent.trim()
}
}
if (groupId == null) {
throw GradleException("'<groupId>' missing in pom")
}
if (artifactId == null) {
throw GradleException("'<artifactId>' missing in pom")
}
if (version == null) {
throw GradleException("'<version>' missing in pom")
}
if (scope == null) {
throw GradleException("'<scope>' missing in pom")
}
return Artifact(groupId, artifactId, version, type, scope)
}
private fun parseLicense(nodes: NodeList): License? {
if (nodes.length == 0) {
return null
}
val license = nodes.item(0) as Element
val urlElements = license.getElementsByTagName("url")
val url = if (urlElements.length == 0) "" else urlElements.item(0).textContent.trim()
val nameElements = license.getElementsByTagName("name")
val name = if (nameElements.length == 0) "" else nameElements.item(0).textContent.trim()
return License(name = name, url = url)
}
}
}
| apache-2.0 | 24326f9c55bbd422286f92fa1d49cd3e | 32.412935 | 110 | 0.615098 | 4.32175 | false | false | false | false |
evanchooly/gridfs-fs-provider | core/src/main/kotlin/com/antwerkz/gridfs/GridFSFileSystem.kt | 1 | 2714 | package com.antwerkz.gridfs
import com.mongodb.MongoClient
import com.mongodb.client.MongoDatabase
import com.mongodb.client.gridfs.GridFSBucket
import com.mongodb.client.gridfs.GridFSBuckets
import java.nio.file.FileStore
import java.nio.file.FileSystem
import java.nio.file.Path
import java.nio.file.PathMatcher
import java.nio.file.WatchService
import java.nio.file.attribute.UserPrincipalLookupService
import java.nio.file.spi.FileSystemProvider
class GridFSFileSystem(private val provider: GridFSFileSystemProvider, mongoClient: MongoClient, dbName: String?,
bucketName: String) : FileSystem() {
private var open = true
val database: MongoDatabase
val client: MongoClient
val bucketName: String
val bucket: GridFSBucket
init {
client = mongoClient
database = client.getDatabase(dbName)
this.bucketName = bucketName
bucket = GridFSBuckets.create(database, bucketName)
}
override fun getSeparator(): String {
return "/"
}
override fun newWatchService(): WatchService? {
throw UnsupportedOperationException()
}
override fun supportedFileAttributeViews(): MutableSet<String>? {
throw UnsupportedOperationException()
}
override fun isReadOnly(): Boolean {
return false
}
override fun getFileStores(): MutableIterable<FileStore>? {
throw UnsupportedOperationException()
}
override fun getPath(first: String, vararg more: String): GridFSPath {
return if (more.size == 0) GridFSPath(this, first) else GridFSPath(this, listOf(first) + more.asList())
}
override fun provider(): FileSystemProvider {
return provider
}
override fun isOpen(): Boolean {
return open
}
override fun getUserPrincipalLookupService(): UserPrincipalLookupService? {
throw UnsupportedOperationException()
}
override fun close() {
open = false
client.close()
}
override fun getPathMatcher(syntaxAndPattern: String?): PathMatcher? {
throw UnsupportedOperationException()
}
override fun getRootDirectories(): MutableIterable<Path>? {
throw UnsupportedOperationException()
}
override fun equals(other: Any?): Boolean{
if (this === other) return true
if (other?.javaClass != javaClass) return false
other as GridFSFileSystem
if (database != other.database) return false
if (bucketName != other.bucketName) return false
return true
}
override fun hashCode(): Int{
var result = database.hashCode()
result += 31 * result + bucketName.hashCode()
return result
}
} | apache-2.0 | 21940de072360f41fcbdc6f8fb419e13 | 26.989691 | 113 | 0.684598 | 5.169524 | false | false | false | false |
cout970/Modeler | src/main/kotlin/com/cout970/modeler/gui/leguicomp/MultilineStringInput.kt | 1 | 1228 | package com.cout970.modeler.gui.leguicomp
import com.cout970.glutilities.device.Keyboard
import org.liquidengine.legui.component.TextArea
import org.liquidengine.legui.component.event.textinput.TextInputContentChangeEvent
import org.liquidengine.legui.event.FocusEvent
import org.liquidengine.legui.event.KeyEvent
class MultilineStringInput(
text: String,
posX: Float = 0f,
posY: Float = 0f,
sizeX: Float = 80f,
sizeY: Float = 24f
) : TextArea(posX, posY, sizeX, sizeY) {
var onLoseFocus: (() -> Unit)? = null
var onEnterPress: (() -> Unit)? = null
var onTextChange: ((TextInputContentChangeEvent<*>) -> Unit)? = null
init {
textState.text = text
defaultTextColor()
classes("multiline_input")
listenerMap.addListener(FocusEvent::class.java) {
if (!it.isFocused) {
onLoseFocus?.invoke()
}
}
listenerMap.addListener(KeyEvent::class.java) {
if (it.key == Keyboard.KEY_ENTER) {
onEnterPress?.invoke()
}
}
listenerMap.addListener(TextInputContentChangeEvent::class.java) {
onTextChange?.invoke(it)
}
}
} | gpl-3.0 | 5a0e37a37e32d3e19b6d9e6699f4ef7c | 28.97561 | 83 | 0.624593 | 4.293706 | false | false | false | false |
vuyaniShabangu/now.next | Research/Tower-develop/Tower-develop/Android/src/org/droidplanner/android/fragments/widget/telemetry/MiniWidgetGeoInfo.kt | 10 | 3673 | package org.droidplanner.android.fragments.widget.telemetry
import android.content.*
import android.location.Location
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import android.widget.Toast
import com.o3dr.services.android.lib.drone.attribute.AttributeEvent
import com.o3dr.services.android.lib.drone.attribute.AttributeType
import com.o3dr.services.android.lib.drone.property.Gps
import org.droidplanner.android.R
import org.droidplanner.android.fragments.widget.TowerWidget
import org.droidplanner.android.fragments.widget.TowerWidgets
/**
* Created by Fredia Huya-Kouadio on 9/20/15.
*/
public class MiniWidgetGeoInfo : TowerWidget() {
companion object {
private val filter = initFilter()
private fun initFilter(): IntentFilter {
val temp = IntentFilter()
temp.addAction(AttributeEvent.GPS_POSITION)
temp.addAction(AttributeEvent.HOME_UPDATED)
return temp
}
}
private val receiver = object : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
when (intent.action) {
AttributeEvent.GPS_POSITION, AttributeEvent.HOME_UPDATED -> onPositionUpdate()
}
}
}
private var latitude: TextView? = null
private var longitude: TextView? = null
override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? {
return inflater?.inflate(R.layout.fragment_mini_widget_geo_info, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?){
super.onViewCreated(view, savedInstanceState)
latitude = view.findViewById(R.id.latitude_telem) as TextView?
longitude = view.findViewById(R.id.longitude_telem) as TextView?
val clipboardMgr = context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
val container = view.findViewById(R.id.mini_widget_geo_info_layout)
container?.setOnClickListener {
val drone = drone
if(drone.isConnected) {
val droneGps = drone.getAttribute<Gps>(AttributeType.GPS)
if(droneGps.isValid) {
//Copy the lat long to the clipboard.
val latLongText = "${droneGps.position.latitude}, ${droneGps.position.longitude}"
val clipData = ClipData.newPlainText("Vehicle Lat/Long", latLongText)
clipboardMgr.primaryClip = clipData
Toast.makeText(context, "Copied lat/long data", Toast.LENGTH_SHORT).show()
}
}
}
}
override fun getWidgetType() = TowerWidgets.GEO_INFO
override fun onApiConnected() {
onPositionUpdate()
broadcastManager.registerReceiver(receiver, filter)
}
override fun onApiDisconnected() {
broadcastManager.unregisterReceiver(receiver)
}
private fun onPositionUpdate() {
if (!isAdded)
return
val drone = drone
val droneGps = drone.getAttribute<Gps>(AttributeType.GPS) ?: return
if (droneGps.isValid) {
val latitudeValue = droneGps.position.latitude
val longitudeValue = droneGps.position.longitude
latitude?.text = getString(R.string.latitude_telem, Location.convert(latitudeValue, Location.FORMAT_DEGREES).toString())
longitude?.text = getString(R.string.longitude_telem, Location.convert(longitudeValue, Location.FORMAT_DEGREES).toString())
}
}
} | mit | 2884b1e3692320d4bbfa32b96fcc89b5 | 34.669903 | 135 | 0.676559 | 4.757772 | false | false | false | false |
TeamNewPipe/NewPipe | app/src/main/java/org/schabi/newpipe/player/gesture/MainPlayerGestureListener.kt | 1 | 8773 | package org.schabi.newpipe.player.gesture
import android.util.Log
import android.view.MotionEvent
import android.view.View
import android.view.View.OnTouchListener
import android.widget.ProgressBar
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.content.res.AppCompatResources
import androidx.core.math.MathUtils
import androidx.core.view.isVisible
import org.schabi.newpipe.MainActivity
import org.schabi.newpipe.R
import org.schabi.newpipe.ktx.AnimationType
import org.schabi.newpipe.ktx.animate
import org.schabi.newpipe.player.Player
import org.schabi.newpipe.player.helper.AudioReactor
import org.schabi.newpipe.player.helper.PlayerHelper
import org.schabi.newpipe.player.ui.MainPlayerUi
import org.schabi.newpipe.util.ThemeHelper.getAndroidDimenPx
import kotlin.math.abs
/**
* GestureListener for the player
*
* While [BasePlayerGestureListener] contains the logic behind the single gestures
* this class focuses on the visual aspect like hiding and showing the controls or changing
* volume/brightness during scrolling for specific events.
*/
class MainPlayerGestureListener(
private val playerUi: MainPlayerUi
) : BasePlayerGestureListener(playerUi), OnTouchListener {
private var isMoving = false
override fun onTouch(v: View, event: MotionEvent): Boolean {
super.onTouch(v, event)
if (event.action == MotionEvent.ACTION_UP && isMoving) {
isMoving = false
onScrollEnd(event)
}
return when (event.action) {
MotionEvent.ACTION_DOWN, MotionEvent.ACTION_MOVE -> {
v.parent?.requestDisallowInterceptTouchEvent(playerUi.isFullscreen)
true
}
MotionEvent.ACTION_UP -> {
v.parent?.requestDisallowInterceptTouchEvent(false)
false
}
else -> true
}
}
override fun onSingleTapConfirmed(e: MotionEvent): Boolean {
if (DEBUG)
Log.d(TAG, "onSingleTapConfirmed() called with: e = [$e]")
if (isDoubleTapping)
return true
super.onSingleTapConfirmed(e)
if (player.currentState != Player.STATE_BLOCKED)
onSingleTap()
return true
}
private fun onScrollVolume(distanceY: Float) {
val bar: ProgressBar = binding.volumeProgressBar
val audioReactor: AudioReactor = player.audioReactor
// If we just started sliding, change the progress bar to match the system volume
if (!binding.volumeRelativeLayout.isVisible) {
val volumePercent: Float = audioReactor.volume / audioReactor.maxVolume.toFloat()
bar.progress = (volumePercent * bar.max).toInt()
}
// Update progress bar
binding.volumeProgressBar.incrementProgressBy(distanceY.toInt())
// Update volume
val currentProgressPercent: Float = bar.progress / bar.max.toFloat()
val currentVolume = (audioReactor.maxVolume * currentProgressPercent).toInt()
audioReactor.volume = currentVolume
if (DEBUG) {
Log.d(TAG, "onScroll().volumeControl, currentVolume = $currentVolume")
}
// Update player center image
binding.volumeImageView.setImageDrawable(
AppCompatResources.getDrawable(
player.context,
when {
currentProgressPercent <= 0 -> R.drawable.ic_volume_off
currentProgressPercent < 0.25 -> R.drawable.ic_volume_mute
currentProgressPercent < 0.75 -> R.drawable.ic_volume_down
else -> R.drawable.ic_volume_up
}
)
)
// Make sure the correct layout is visible
if (!binding.volumeRelativeLayout.isVisible) {
binding.volumeRelativeLayout.animate(true, 200, AnimationType.SCALE_AND_ALPHA)
}
binding.brightnessRelativeLayout.isVisible = false
}
private fun onScrollBrightness(distanceY: Float) {
val parent: AppCompatActivity = playerUi.parentActivity.orElse(null) ?: return
val window = parent.window
val layoutParams = window.attributes
val bar: ProgressBar = binding.brightnessProgressBar
// Update progress bar
val oldBrightness = layoutParams.screenBrightness
bar.progress = (bar.max * MathUtils.clamp(oldBrightness, 0f, 1f)).toInt()
bar.incrementProgressBy(distanceY.toInt())
// Update brightness
val currentProgressPercent = bar.progress.toFloat() / bar.max
layoutParams.screenBrightness = currentProgressPercent
window.attributes = layoutParams
// Save current brightness level
PlayerHelper.setScreenBrightness(parent, currentProgressPercent)
if (DEBUG) {
Log.d(
TAG,
"onScroll().brightnessControl, " +
"currentBrightness = " + currentProgressPercent
)
}
// Update player center image
binding.brightnessImageView.setImageDrawable(
AppCompatResources.getDrawable(
player.context,
when {
currentProgressPercent < 0.25 -> R.drawable.ic_brightness_low
currentProgressPercent < 0.75 -> R.drawable.ic_brightness_medium
else -> R.drawable.ic_brightness_high
}
)
)
// Make sure the correct layout is visible
if (!binding.brightnessRelativeLayout.isVisible) {
binding.brightnessRelativeLayout.animate(true, 200, AnimationType.SCALE_AND_ALPHA)
}
binding.volumeRelativeLayout.isVisible = false
}
override fun onScrollEnd(event: MotionEvent) {
super.onScrollEnd(event)
if (binding.volumeRelativeLayout.isVisible) {
binding.volumeRelativeLayout.animate(false, 200, AnimationType.SCALE_AND_ALPHA, 200)
}
if (binding.brightnessRelativeLayout.isVisible) {
binding.brightnessRelativeLayout.animate(false, 200, AnimationType.SCALE_AND_ALPHA, 200)
}
}
override fun onScroll(
initialEvent: MotionEvent,
movingEvent: MotionEvent,
distanceX: Float,
distanceY: Float
): Boolean {
if (!playerUi.isFullscreen) {
return false
}
// Calculate heights of status and navigation bars
val statusBarHeight = getAndroidDimenPx(player.context, "status_bar_height")
val navigationBarHeight = getAndroidDimenPx(player.context, "navigation_bar_height")
// Do not handle this event if initially it started from status or navigation bars
val isTouchingStatusBar = initialEvent.y < statusBarHeight
val isTouchingNavigationBar = initialEvent.y > (binding.root.height - navigationBarHeight)
if (isTouchingStatusBar || isTouchingNavigationBar) {
return false
}
val insideThreshold = abs(movingEvent.y - initialEvent.y) <= MOVEMENT_THRESHOLD
if (
!isMoving && (insideThreshold || abs(distanceX) > abs(distanceY)) ||
player.currentState == Player.STATE_COMPLETED
) {
return false
}
isMoving = true
// -- Brightness and Volume control --
val isBrightnessGestureEnabled = PlayerHelper.isBrightnessGestureEnabled(player.context)
val isVolumeGestureEnabled = PlayerHelper.isVolumeGestureEnabled(player.context)
if (isBrightnessGestureEnabled && isVolumeGestureEnabled) {
if (getDisplayHalfPortion(initialEvent) === DisplayPortion.LEFT_HALF) {
onScrollBrightness(distanceY)
} else /* DisplayPortion.RIGHT_HALF */ {
onScrollVolume(distanceY)
}
} else if (isBrightnessGestureEnabled) {
onScrollBrightness(distanceY)
} else if (isVolumeGestureEnabled) {
onScrollVolume(distanceY)
}
return true
}
override fun getDisplayPortion(e: MotionEvent): DisplayPortion {
return when {
e.x < binding.root.width / 3.0 -> DisplayPortion.LEFT
e.x > binding.root.width * 2.0 / 3.0 -> DisplayPortion.RIGHT
else -> DisplayPortion.MIDDLE
}
}
override fun getDisplayHalfPortion(e: MotionEvent): DisplayPortion {
return when {
e.x < binding.root.width / 2.0 -> DisplayPortion.LEFT_HALF
else -> DisplayPortion.RIGHT_HALF
}
}
companion object {
private val TAG = MainPlayerGestureListener::class.java.simpleName
private val DEBUG = MainActivity.DEBUG
private const val MOVEMENT_THRESHOLD = 40
}
}
| gpl-3.0 | 8a4c6743cc182ae3369267d2df541eba | 36.652361 | 100 | 0.648011 | 5.076968 | false | false | false | false |
androidx/androidx | window/window/src/main/java/androidx/window/embedding/SplitPairRule.kt | 3 | 7794 | /*
* 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.window.embedding
import android.util.LayoutDirection.LOCALE
import androidx.annotation.FloatRange
import androidx.annotation.IntRange
import androidx.core.util.Preconditions.checkArgument
import androidx.core.util.Preconditions.checkArgumentNonnegative
/**
* Split configuration rules for activity pairs. Define when activities that were launched on top of
* each other should be shown side-by-side, and the visual properties of such splits. Can be set
* either statically via [SplitController.Companion.initialize] or at runtime via
* [SplitController.registerRule]. The rules can only be applied to activities that
* belong to the same application and are running in the same process. The rules are always
* applied only to activities that will be started after the rules were set.
*/
class SplitPairRule : SplitRule {
/**
* Filters used to choose when to apply this rule. The rule may be used if any one of the
* provided filters matches.
*/
val filters: Set<SplitPairFilter>
/**
* Determines what happens with the primary container when all activities are finished in the
* associated secondary container.
* @see SplitRule.SplitFinishBehavior
*/
@SplitFinishBehavior
val finishPrimaryWithSecondary: Int
/**
* Determines what happens with the secondary container when all activities are finished in the
* associated primary container.
* @see SplitRule.SplitFinishBehavior
*/
@SplitFinishBehavior
val finishSecondaryWithPrimary: Int
/**
* If there is an existing split with the same primary container, indicates whether the
* existing secondary container on top and all activities in it should be destroyed when a new
* split is created using this rule. Otherwise the new secondary will appear on top by default.
*/
val clearTop: Boolean
internal constructor(
filters: Set<SplitPairFilter>,
@SplitFinishBehavior finishPrimaryWithSecondary: Int = FINISH_NEVER,
@SplitFinishBehavior finishSecondaryWithPrimary: Int = FINISH_ALWAYS,
clearTop: Boolean = false,
@IntRange(from = 0) minWidthDp: Int = DEFAULT_SPLIT_MIN_DIMENSION_DP,
@IntRange(from = 0) minSmallestWidthDp: Int = DEFAULT_SPLIT_MIN_DIMENSION_DP,
@FloatRange(from = 0.0, to = 1.0) splitRatio: Float = 0.5f,
@LayoutDirection layoutDirection: Int = LOCALE
) : super(minWidthDp, minSmallestWidthDp, splitRatio, layoutDirection) {
checkArgumentNonnegative(minWidthDp, "minWidthDp must be non-negative")
checkArgumentNonnegative(minSmallestWidthDp, "minSmallestWidthDp must be non-negative")
checkArgument(splitRatio in 0.0..1.0, "splitRatio must be in 0.0..1.0 range")
this.filters = filters.toSet()
this.clearTop = clearTop
this.finishPrimaryWithSecondary = finishPrimaryWithSecondary
this.finishSecondaryWithPrimary = finishSecondaryWithPrimary
}
/**
* Builder for [SplitPairRule].
*
* @param filters See [SplitPairRule.filters].
*/
class Builder(
private val filters: Set<SplitPairFilter>,
) {
@IntRange(from = 0)
private var minWidthDp: Int = DEFAULT_SPLIT_MIN_DIMENSION_DP
@IntRange(from = 0)
private var minSmallestWidthDp: Int = DEFAULT_SPLIT_MIN_DIMENSION_DP
@SplitFinishBehavior
private var finishPrimaryWithSecondary: Int = FINISH_NEVER
@SplitFinishBehavior
private var finishSecondaryWithPrimary: Int = FINISH_ALWAYS
private var clearTop: Boolean = false
@FloatRange(from = 0.0, to = 1.0)
private var splitRatio: Float = 0.5f
@LayoutDirection
private var layoutDirection: Int = LOCALE
/**
* @see SplitPairRule.minWidthDp
*/
fun setMinWidthDp(@IntRange(from = 0) minWidthDp: Int): Builder =
apply { this.minWidthDp = minWidthDp }
/**
* @see SplitPairRule.minSmallestWidthDp
*/
fun setMinSmallestWidthDp(@IntRange(from = 0) minSmallestWidthDp: Int): Builder =
apply { this.minSmallestWidthDp = minSmallestWidthDp }
/**
* @see SplitPairRule.finishPrimaryWithSecondary
*/
fun setFinishPrimaryWithSecondary(
@SplitFinishBehavior finishPrimaryWithSecondary: Int
): Builder =
apply { this.finishPrimaryWithSecondary = finishPrimaryWithSecondary }
/**
* @see SplitPairRule.finishSecondaryWithPrimary
*/
fun setFinishSecondaryWithPrimary(
@SplitFinishBehavior finishSecondaryWithPrimary: Int
): Builder =
apply { this.finishSecondaryWithPrimary = finishSecondaryWithPrimary }
/**
* @see SplitPairRule.clearTop
*/
@SuppressWarnings("MissingGetterMatchingBuilder")
fun setClearTop(clearTop: Boolean): Builder =
apply { this.clearTop = clearTop }
/**
* @see SplitPairRule.splitRatio
*/
fun setSplitRatio(@FloatRange(from = 0.0, to = 1.0) splitRatio: Float): Builder =
apply { this.splitRatio = splitRatio }
/**
* @see SplitPairRule.layoutDirection
*/
fun setLayoutDirection(@LayoutDirection layoutDirection: Int): Builder =
apply { this.layoutDirection = layoutDirection }
fun build() = SplitPairRule(filters, finishPrimaryWithSecondary, finishSecondaryWithPrimary,
clearTop, minWidthDp, minSmallestWidthDp, splitRatio, layoutDirection)
}
/**
* Creates a new immutable instance by adding a filter to the set.
* @see filters
*/
internal operator fun plus(filter: SplitPairFilter): SplitPairRule {
val newSet = mutableSetOf<SplitPairFilter>()
newSet.addAll(filters)
newSet.add(filter)
return Builder(newSet.toSet())
.setMinWidthDp(minWidthDp)
.setMinSmallestWidthDp(minSmallestWidthDp)
.setFinishPrimaryWithSecondary(finishPrimaryWithSecondary)
.setFinishSecondaryWithPrimary(finishSecondaryWithPrimary)
.setClearTop(clearTop)
.setSplitRatio(splitRatio)
.setLayoutDirection(layoutDirection)
.build()
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is SplitPairRule) return false
if (!super.equals(other)) return false
if (filters != other.filters) return false
if (finishPrimaryWithSecondary != other.finishPrimaryWithSecondary) return false
if (finishSecondaryWithPrimary != other.finishSecondaryWithPrimary) return false
if (clearTop != other.clearTop) return false
return true
}
override fun hashCode(): Int {
var result = super.hashCode()
result = 31 * result + filters.hashCode()
result = 31 * result + finishPrimaryWithSecondary.hashCode()
result = 31 * result + finishSecondaryWithPrimary.hashCode()
result = 31 * result + clearTop.hashCode()
return result
}
} | apache-2.0 | b593f8c714f3115e287169af668d6c7e | 38.770408 | 100 | 0.68078 | 5.360385 | false | false | false | false |
androidx/androidx | viewpager2/integration-tests/testapp/src/main/java/androidx/viewpager2/integration/testapp/MutableCollectionFragmentActivity.kt | 4 | 3958 | /*
* Copyright 2019 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.viewpager2.integration.testapp
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.TextView
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.RecyclerView
import androidx.viewpager2.adapter.FragmentStateAdapter
import androidx.viewpager2.widget.ViewPager2
private const val KEY_ITEM_TEXT = "androidx.viewpager2.integration.testapp.KEY_ITEM_TEXT"
private const val KEY_CLICK_COUNT = "androidx.viewpager2.integration.testapp.KEY_CLICK_COUNT"
/**
* Shows how to use [FragmentStateAdapter.notifyDataSetChanged] with [ViewPager2]. Here [ViewPager2]
* represents pages as [Fragment]s.
*/
class MutableCollectionFragmentActivity : MutableCollectionBaseActivity() {
override fun createViewPagerAdapter(): RecyclerView.Adapter<*> {
val items = items // avoids resolving the ViewModel multiple times
return object : FragmentStateAdapter(this) {
override fun createFragment(position: Int): PageFragment {
val itemId = items.itemId(position)
val itemText = items.getItemById(itemId)
return PageFragment.create(itemText)
}
override fun getItemCount(): Int = items.size
override fun getItemId(position: Int): Long = items.itemId(position)
override fun containsItem(itemId: Long): Boolean = items.contains(itemId)
}
}
}
class PageFragment : Fragment() {
private lateinit var textViewItemText: TextView
private lateinit var textViewCount: TextView
private lateinit var buttonCountIncrease: Button
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val view = inflater.inflate(R.layout.item_mutable_collection, container, false)
textViewItemText = view.findViewById(R.id.textViewItemText)
textViewCount = view.findViewById(R.id.textViewCount)
buttonCountIncrease = view.findViewById(R.id.buttonCountIncrease)
textViewItemText.text = arguments?.getString(KEY_ITEM_TEXT) ?: throw IllegalStateException()
fun updateCountText(count: Int) {
textViewCount.text = "$count"
}
updateCountText(savedInstanceState?.getInt(KEY_CLICK_COUNT) ?: 0)
buttonCountIncrease.setOnClickListener {
updateCountText(clickCount() + 1)
}
return view
}
/**
* [FragmentStateAdapter] minimizes the number of [Fragment]s kept in memory by saving state of
[Fragment]s that are no longer near the viewport. Here we demonstrate this behavior by relying
on it to persist click counts through configuration changes (rotation) and data-set changes
(when items are added or removed).
*/
override fun onSaveInstanceState(outState: Bundle) {
outState.putInt(KEY_CLICK_COUNT, clickCount())
}
private fun clickCount(): Int {
return "${textViewCount.text}".toInt()
}
companion object {
fun create(itemText: String) =
PageFragment().apply {
arguments = Bundle(1).apply {
putString(KEY_ITEM_TEXT, itemText)
}
}
}
}
| apache-2.0 | 75f5afa7a3f4640cca99e5d36e838ea3 | 36.695238 | 100 | 0.699596 | 4.768675 | false | false | false | false |
pokk/SSFM | app/src/main/kotlin/taiwan/no1/app/ssfm/features/chart/RecyclerViewRankChartDetailViewModel.kt | 1 | 4704 | package taiwan.no1.app.ssfm.features.chart
import android.databinding.ObservableBoolean
import android.databinding.ObservableField
import android.graphics.Bitmap
import android.graphics.drawable.Drawable
import android.graphics.drawable.GradientDrawable
import android.view.View
import com.devrapid.kotlinknifer.glideListener
import com.devrapid.kotlinknifer.palette
import com.devrapid.kotlinknifer.toTimeString
import com.hwangjr.rxbus.RxBus
import com.hwangjr.rxbus.annotation.Subscribe
import com.hwangjr.rxbus.annotation.Tag
import com.trello.rxlifecycle2.LifecycleProvider
import taiwan.no1.app.ssfm.R
import taiwan.no1.app.ssfm.features.base.BaseViewModel
import taiwan.no1.app.ssfm.misc.constants.RxBusTag
import taiwan.no1.app.ssfm.misc.constants.RxBusTag.VIEWMODEL_TRACK_CLICK
import taiwan.no1.app.ssfm.misc.constants.RxBusTag.VIEWMODEL_TRACK_LONG_CLICK
import taiwan.no1.app.ssfm.misc.extension.changeState
import taiwan.no1.app.ssfm.misc.extension.gAlphaIntColor
import taiwan.no1.app.ssfm.misc.extension.gColor
import taiwan.no1.app.ssfm.misc.utilies.devices.helper.music.MusicPlayerHelper
import taiwan.no1.app.ssfm.misc.utilies.devices.helper.music.playMusic
import taiwan.no1.app.ssfm.misc.utilies.devices.helper.music.playerHelper
import taiwan.no1.app.ssfm.models.entities.PlaylistItemEntity
import taiwan.no1.app.ssfm.models.usecases.AddPlaylistItemCase
import weian.cheng.mediaplayerwithexoplayer.MusicPlayerState
/**
* @author jieyi
* @since 11/24/17
*/
class RecyclerViewRankChartDetailViewModel(private val addPlaylistItemCase: AddPlaylistItemCase,
private var item: PlaylistItemEntity,
private var index: Int) : BaseViewModel() {
val trackName by lazy { ObservableField<String>() }
val trackDuration by lazy { ObservableField<String>() }
val trackIndex by lazy { ObservableField<String>() }
val artistName by lazy { ObservableField<String>() }
val trackCover by lazy { ObservableField<String>() }
val isPlaying by lazy { ObservableBoolean(false) }
val layoutBackground by lazy { ObservableField<Drawable>() }
val imageCallback = glideListener<Bitmap> {
onResourceReady = { resource, _, _, _, _ ->
resource.palette(24).let {
val start = gAlphaIntColor(it.vibrantSwatch?.rgb ?: gColor(R.color.colorSimilarPrimaryDark), 0.65f)
val darkColor = gAlphaIntColor(it.darkVibrantSwatch?.rgb ?: gColor(R.color.colorPrimaryDark), 0.65f)
val background = GradientDrawable(GradientDrawable.Orientation.TL_BR, intArrayOf(start, darkColor))
layoutBackground.set(background)
}
false
}
}
private var clickedIndex = -1
init {
refreshView()
}
//region Lifecycle
override fun <E> onAttach(lifecycleProvider: LifecycleProvider<E>) {
super.onAttach(lifecycleProvider)
RxBus.get().register(this)
}
override fun onDetach() {
super.onDetach()
RxBus.get().unregister(this)
}
//endregion
fun setMusicItem(item: PlaylistItemEntity, index: Int) {
this.item = item
this.index = index
refreshView()
}
/**
* @param view
*
* @event_to [taiwan.no1.app.ssfm.features.chart.ChartRankChartDetailFragment.addToPlaylist]
*/
fun trackOnClick(view: View) {
lifecycleProvider.playMusic(addPlaylistItemCase, item, index)
}
/**
* @param view
*
* @event_to [taiwan.no1.app.ssfm.features.chart.ChartActivity.openBottomSheet]
*/
fun trackOnLongClick(view: View): Boolean {
RxBus.get().post(VIEWMODEL_TRACK_LONG_CLICK, item)
return true
}
@Subscribe(tags = [Tag(VIEWMODEL_TRACK_CLICK)])
fun changeToStopIcon(uri: String) {
isPlaying.set(uri == item.trackUri)
}
@Subscribe(tags = [Tag(VIEWMODEL_TRACK_CLICK)])
fun notifyClickIndex(index: Integer) {
clickedIndex = index.toInt()
}
/**
* @param state
*
* @event_from [MusicPlayerHelper.setPlayerListener]
*/
@Subscribe(tags = [(Tag(RxBusTag.MUSICPLAYER_STATE_CHANGED))])
fun playerStateChanged(state: MusicPlayerState) = isPlaying.changeState(state, index, clickedIndex)
private fun refreshView() {
item.let {
isPlaying.set(playerHelper.isCurrentUri(it.trackUri) && playerHelper.isPlaying)
trackName.set(it.trackName)
trackDuration.set(it.duration.toTimeString())
trackIndex.set(index.toString())
artistName.set(it.artistName)
trackCover.set(it.coverUrl)
}
}
} | apache-2.0 | 38ebc0cdc235688cfa498ce60156a71d | 35.757813 | 116 | 0.696216 | 4.230216 | false | false | false | false |
androidx/androidx | wear/compose/compose-navigation/src/main/java/androidx/wear/compose/navigation/SwipeDismissableNavHost.kt | 3 | 11745 | /*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.wear.compose.navigation
import androidx.activity.compose.LocalOnBackPressedDispatcherOwner
import androidx.compose.foundation.layout.Box
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.compose.runtime.remember
import androidx.compose.runtime.saveable.SaveableStateHolder
import androidx.compose.runtime.saveable.rememberSaveableStateHolder
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalLifecycleOwner
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleEventObserver
import androidx.lifecycle.viewmodel.compose.LocalViewModelStoreOwner
import androidx.navigation.NavBackStackEntry
import androidx.navigation.NavDestination
import androidx.navigation.NavGraph
import androidx.navigation.NavGraphBuilder
import androidx.navigation.NavHostController
import androidx.navigation.Navigator
import androidx.navigation.createGraph
import androidx.navigation.compose.LocalOwnersProvider
import androidx.navigation.get
import androidx.wear.compose.material.SwipeToDismissValue
import androidx.wear.compose.material.SwipeToDismissBox
import androidx.wear.compose.material.SwipeToDismissBoxState
import androidx.wear.compose.material.SwipeToDismissKeys
import androidx.wear.compose.material.edgeSwipeToDismiss
import androidx.wear.compose.material.rememberSwipeToDismissBoxState
/**
* Provides a place in the Compose hierarchy for self-contained navigation to occur,
* with backwards navigation provided by a swipe gesture.
*
* Once this is called, any Composable within the given [NavGraphBuilder] can be navigated to from
* the provided [navController].
*
* The builder passed into this method is [remember]ed. This means that for this NavHost, the
* contents of the builder cannot be changed.
*
* Content is displayed within a [SwipeToDismissBox], showing the current navigation level.
* During a swipe-to-dismiss gesture, the previous navigation level (if any) is shown in
* the background.
*
* Example of a [SwipeDismissableNavHost] alternating between 2 screens:
* @sample androidx.wear.compose.navigation.samples.SimpleNavHost
*
* Example of a [SwipeDismissableNavHost] for which a destination has a named argument:
* @sample androidx.wear.compose.navigation.samples.NavHostWithNamedArgument
*
* @param navController The navController for this host
* @param startDestination The route for the start destination
* @param modifier The modifier to be applied to the layout
* @param state State containing information about ongoing swipe and animation.
* @param route The route for the graph
* @param builder The builder used to construct the graph
*/
@Composable
public fun SwipeDismissableNavHost(
navController: NavHostController,
startDestination: String,
modifier: Modifier = Modifier,
state: SwipeDismissableNavHostState = rememberSwipeDismissableNavHostState(),
route: String? = null,
builder: NavGraphBuilder.() -> Unit
) =
SwipeDismissableNavHost(
navController,
remember(route, startDestination, builder) {
navController.createGraph(startDestination, route, builder)
},
modifier,
state = state,
)
/**
* Provides a place in the Compose hierarchy for self-contained navigation to occur,
* with backwards navigation provided by a swipe gesture.
*
* Once this is called, any Composable within the given [NavGraphBuilder] can be navigated to from
* the provided [navController].
*
* The builder passed into this method is [remember]ed. This means that for this NavHost, the
* contents of the builder cannot be changed.
*
* Content is displayed within a [SwipeToDismissBox], showing the current navigation level.
* During a swipe-to-dismiss gesture, the previous navigation level (if any) is shown in
* the background.
*
* Example of a [SwipeDismissableNavHost] alternating between 2 screens:
* @sample androidx.wear.compose.navigation.samples.SimpleNavHost
*
* Example of a [SwipeDismissableNavHost] for which a destination has a named argument:
* @sample androidx.wear.compose.navigation.samples.NavHostWithNamedArgument
*
* @param navController [NavHostController] for this host
* @param graph Graph for this host
* @param modifier [Modifier] to be applied to the layout
* @param state State containing information about ongoing swipe and animation.
*
* @throws IllegalArgumentException if no WearNavigation.Destination is on the navigation backstack.
*/
@Composable
public fun SwipeDismissableNavHost(
navController: NavHostController,
graph: NavGraph,
modifier: Modifier = Modifier,
state: SwipeDismissableNavHostState = rememberSwipeDismissableNavHostState(),
) {
val lifecycleOwner = LocalLifecycleOwner.current
val viewModelStoreOwner = checkNotNull(LocalViewModelStoreOwner.current) {
"SwipeDismissableNavHost requires a ViewModelStoreOwner to be provided " +
"via LocalViewModelStoreOwner"
}
val onBackPressedDispatcherOwner = LocalOnBackPressedDispatcherOwner.current
val onBackPressedDispatcher = onBackPressedDispatcherOwner?.onBackPressedDispatcher
// Setup the navController with proper owners
navController.setLifecycleOwner(lifecycleOwner)
navController.setViewModelStore(viewModelStoreOwner.viewModelStore)
if (onBackPressedDispatcher != null) {
navController.setOnBackPressedDispatcher(onBackPressedDispatcher)
}
// Ensure that the NavController only receives back events while
// the NavHost is in composition
DisposableEffect(navController) {
navController.enableOnBackPressed(true)
onDispose {
navController.enableOnBackPressed(false)
}
}
// Then set the graph
navController.graph = graph
val stateHolder = rememberSaveableStateHolder()
// Find the WearNavigator, returning early if it isn't found
// (such as is the case when using TestNavHostController).
val wearNavigator = navController.navigatorProvider.get<Navigator<out NavDestination>>(
WearNavigator.NAME
) as? WearNavigator ?: return
val backStack by wearNavigator.backStack.collectAsState()
val transitionsInProgress by wearNavigator.transitionsInProgress.collectAsState()
var initialContent by remember { mutableStateOf(true) }
val previous = if (backStack.size <= 1) null else backStack[backStack.lastIndex - 1]
// Get the current navigation backstack entry. If the backstack is empty, it could be because
// no WearNavigator.Destinations were added to the navigation backstack (be sure to build
// the NavGraph using androidx.wear.compose.navigation.composable) or because the last entry
// was popped prior to navigating (instead, use navigate with popUpTo).
val current = if (backStack.isNotEmpty()) backStack.last() else throw IllegalArgumentException(
"The WearNavigator backstack is empty, there is no navigation destination to display."
)
val swipeState = state.swipeToDismissBoxState
LaunchedEffect(swipeState.currentValue) {
// This effect operates when the swipe gesture is complete:
// 1) Resets the screen offset (otherwise, the next destination is draw off-screen)
// 2) Pops the navigation back stack to return to the previous level
if (swipeState.currentValue == SwipeToDismissValue.Dismissed) {
swipeState.snapTo(SwipeToDismissValue.Default)
navController.popBackStack()
}
}
LaunchedEffect(swipeState.isAnimationRunning) {
// This effect marks the transitions completed when swipe animations finish,
// so that the navigation backstack entries can go to Lifecycle.State.RESUMED.
if (swipeState.isAnimationRunning == false) {
transitionsInProgress.forEach { entry ->
wearNavigator.onTransitionComplete(entry)
}
}
}
SwipeToDismissBox(
state = swipeState,
modifier = Modifier,
hasBackground = previous != null,
backgroundKey = previous?.id ?: SwipeToDismissKeys.Background,
contentKey = current.id,
content = { isBackground ->
BoxedStackEntryContent(if (isBackground) previous else current, stateHolder, modifier)
}
)
DisposableEffect(previous, current) {
if (initialContent) {
// There are no animations for showing the initial content, so mark transitions complete,
// allowing the navigation backstack entry to go to Lifecycle.State.RESUMED.
transitionsInProgress.forEach { entry ->
wearNavigator.onTransitionComplete(entry)
}
initialContent = false
}
onDispose {
transitionsInProgress.forEach { entry ->
wearNavigator.onTransitionComplete(entry)
}
}
}
}
/**
* State for [SwipeDismissableNavHost]
*
* @param swipeToDismissBoxState State for [SwipeToDismissBox], which is used to support the
* swipe-to-dismiss gesture in [SwipeDismissableNavHost] and can also be used to support
* edge-swiping, using [edgeSwipeToDismiss].
*/
public class SwipeDismissableNavHostState(
internal val swipeToDismissBoxState: SwipeToDismissBoxState
)
/**
* Create a [SwipeToDismissBoxState] and remember it.
*
* @param swipeToDismissBoxState State for [SwipeToDismissBox], which is used to support the
* swipe-to-dismiss gesture in [SwipeDismissableNavHost] and can also be used to support
* edge-swiping, using [edgeSwipeToDismiss].
*/
@Composable
public fun rememberSwipeDismissableNavHostState(
swipeToDismissBoxState: SwipeToDismissBoxState = rememberSwipeToDismissBoxState(),
): SwipeDismissableNavHostState {
return remember(swipeToDismissBoxState) {
SwipeDismissableNavHostState(swipeToDismissBoxState)
}
}
@Composable
private fun BoxedStackEntryContent(
entry: NavBackStackEntry?,
saveableStateHolder: SaveableStateHolder,
modifier: Modifier = Modifier,
) {
if (entry != null) {
var lifecycleState by remember {
mutableStateOf(entry.lifecycle.currentState)
}
DisposableEffect(entry.lifecycle) {
val observer = LifecycleEventObserver { _, event ->
lifecycleState = event.targetState
}
entry.lifecycle.addObserver(observer)
onDispose {
entry.lifecycle.removeObserver(observer)
}
}
if (lifecycleState.isAtLeast(Lifecycle.State.CREATED)) {
Box(modifier, propagateMinConstraints = true) {
val destination = entry.destination as WearNavigator.Destination
entry.LocalOwnersProvider(saveableStateHolder) {
destination.content(entry)
}
}
}
}
}
| apache-2.0 | 9ab05fbe6cf7dd50e449d4d71539b5f2 | 40.797153 | 101 | 0.744572 | 5.309675 | false | false | false | false |
OnyxDevTools/onyx-database-parent | onyx-remote-driver/src/main/kotlin/com/onyx/persistence/query/RemoteQueryListener.kt | 1 | 4181 | package com.onyx.persistence.query
import com.onyx.buffer.BufferStream
import com.onyx.buffer.BufferStreamable
import com.onyx.network.connection.Connection
import com.onyx.network.push.PushSubscriber
import com.onyx.network.push.PushPublisher
import com.onyx.network.push.PushConsumer
import com.onyx.exception.BufferingException
import java.nio.channels.ByteChannel
import java.util.Objects
/**
* Created by Tim Osborn on 3/27/17.
*
* This is a 3 for one. It contains the push subscriber information, consumer for the client, and a
* base query listener.
*
*/
class RemoteQueryListener<in T>(private val baseListener: QueryListener<T>? = null) : BufferStreamable, QueryListener<T>, PushSubscriber, PushConsumer {
// Transfer information
override var pushObjectId: Long = 0
override var packet: Any? = null
override var subscribeEvent: Byte = 1
// Publisher information
@Transient
override var connection: Connection? = null
@Transient
override var channel: ByteChannel? = null
@Transient
private var pushPublisher: PushPublisher? = null
/**
* Read from buffer stream
* @param buffer Buffer Stream to read from
*/
@Throws(BufferingException::class)
override fun read(buffer: BufferStream) {
pushObjectId = buffer.long
packet = buffer.value
subscribeEvent = buffer.byte
}
/**
* Write to buffer stream
* @param buffer Buffer IO Stream to write to
*/
@Throws(BufferingException::class)
override fun write(buffer: BufferStream) {
buffer.putLong(pushObjectId)
buffer.putObject(packet)
buffer.putByte(subscribeEvent)
}
/**
* Server publisher for push notifications
* @param peer Publisher to send messages with
*/
override fun setPushPublisher(peer: PushPublisher) {
this.pushPublisher = peer
}
override fun setSubscriberEvent(event: Byte) {
this.subscribeEvent = event
}
/**
* Item has been modified. This occurs when an entity met the original criteria
* when querying the database and was updated. The updated values still match the criteria
*
* @param item Entity updated via the persistence manager
*
* @since 1.3.0
*/
override fun onItemUpdated(item: T) {
val event = QueryEvent(QueryListenerEvent.UPDATE, item)
this.pushPublisher!!.push(this, event)
}
/**
* Item has been inserted. This occurs when an entity was saved and it meets the query criteria.
*
* @param item Entity inserted via the persistence manager
*
* @since 1.3.0
*/
override fun onItemAdded(item: T) {
val event = QueryEvent(QueryListenerEvent.INSERT, item)
this.pushPublisher!!.push(this, event)
}
/**
* Item has been deleted or no longer meets the criteria of the query.
*
* @param item Entity persisted via the persistence manager
*
* @since 1.3.0
*/
override fun onItemRemoved(item: T) {
val event = QueryEvent(QueryListenerEvent.DELETE, item)
this.pushPublisher!!.push(this, event)
}
/**
* Helped to uniquely identify a subscriber
* @return Hash code of listener and socket channel
*/
override fun hashCode(): Int = Objects.hash(pushObjectId)
/**
* Comparator to see if the listener is uniquely identified. This compares exact identity.
* @param other Object to compare
* @return Whether objects are equal
*/
override fun equals(other: Any?): Boolean = other is RemoteQueryListener<*> && other.pushObjectId == this.pushObjectId
/**
* Accept query events
* @param o packet sent from server
*/
override fun accept(o: Any?) {
@Suppress("UNCHECKED_CAST")
val event = o as QueryEvent<T>
when (event.type){
QueryListenerEvent.INSERT -> baseListener!!.onItemAdded(event.entity!!)
QueryListenerEvent.UPDATE -> baseListener!!.onItemUpdated(event.entity!!)
QueryListenerEvent.DELETE -> baseListener!!.onItemRemoved(event.entity!!)
else -> { }
}
}
}
| agpl-3.0 | 513b955a4dd272f046a71c2fa04fe7db | 29.97037 | 152 | 0.66563 | 4.443146 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/analysis/src/org/jetbrains/kotlin/idea/caches/resolve/util/JavaResolveExtension.kt | 2 | 7392 | // 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.
@file:JvmName("JavaResolutionUtils")
package org.jetbrains.kotlin.idea.caches.resolve.util
import com.intellij.psi.*
import org.jetbrains.kotlin.asJava.classes.KtLightClass
import org.jetbrains.kotlin.asJava.unwrapped
import org.jetbrains.kotlin.caches.resolve.KotlinCacheService
import org.jetbrains.kotlin.descriptors.*
import org.jetbrains.kotlin.idea.FrontendInternals
import org.jetbrains.kotlin.idea.caches.lightClasses.KtLightClassForDecompiledDeclaration
import org.jetbrains.kotlin.idea.resolve.ResolutionFacade
import org.jetbrains.kotlin.idea.util.application.runReadAction
import org.jetbrains.kotlin.incremental.components.NoLookupLocation
import org.jetbrains.kotlin.load.java.sources.JavaSourceElement
import org.jetbrains.kotlin.load.java.structure.*
import org.jetbrains.kotlin.load.java.structure.impl.*
import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.psi.KtClassOrObject
import org.jetbrains.kotlin.psi.KtDeclaration
import org.jetbrains.kotlin.psi.psiUtil.parameterIndex
import org.jetbrains.kotlin.platform.jvm.JvmPlatforms
import org.jetbrains.kotlin.resolve.jvm.JavaDescriptorResolver
import org.jetbrains.kotlin.resolve.scopes.MemberScope
fun PsiMethod.getJavaMethodDescriptor(): FunctionDescriptor? = javaResolutionFacade()?.let { getJavaMethodDescriptor(it) }
private fun PsiMethod.getJavaMethodDescriptor(resolutionFacade: ResolutionFacade): FunctionDescriptor? {
val method = originalElement as? PsiMethod ?: return null
if (method.containingClass == null || !Name.isValidIdentifier(method.name)) return null
val resolver = method.getJavaDescriptorResolver(resolutionFacade)
return when {
method.isConstructor -> resolver?.resolveConstructor(JavaConstructorImpl(method))
else -> resolver?.resolveMethod(JavaMethodImpl(method))
}
}
fun PsiClass.getJavaClassDescriptor() = javaResolutionFacade()?.let { getJavaClassDescriptor(it) }
fun PsiClass.getJavaClassDescriptor(resolutionFacade: ResolutionFacade): ClassDescriptor? {
val psiClass = originalElement as? PsiClass ?: return null
return psiClass.getJavaDescriptorResolver(resolutionFacade)?.resolveClass(JavaClassImpl(psiClass))
}
private fun PsiField.getJavaFieldDescriptor(resolutionFacade: ResolutionFacade): PropertyDescriptor? {
val field = originalElement as? PsiField ?: return null
return field.getJavaDescriptorResolver(resolutionFacade)?.resolveField(JavaFieldImpl(field))
}
fun PsiMember.getJavaMemberDescriptor(resolutionFacade: ResolutionFacade): DeclarationDescriptor? {
return when (this) {
is PsiClass -> getJavaClassDescriptor(resolutionFacade)
is PsiMethod -> getJavaMethodDescriptor(resolutionFacade)
is PsiField -> getJavaFieldDescriptor(resolutionFacade)
else -> null
}
}
fun PsiMember.getJavaMemberDescriptor(): DeclarationDescriptor? = javaResolutionFacade()?.let { getJavaMemberDescriptor(it) }
fun PsiMember.getJavaOrKotlinMemberDescriptor(): DeclarationDescriptor? =
javaResolutionFacade()?.let { getJavaOrKotlinMemberDescriptor(it) }
fun PsiMember.getJavaOrKotlinMemberDescriptor(resolutionFacade: ResolutionFacade): DeclarationDescriptor? {
val callable = unwrapped
return when (callable) {
is PsiMember -> getJavaMemberDescriptor(resolutionFacade)
is KtDeclaration -> {
val descriptor = resolutionFacade.resolveToDescriptor(callable)
if (descriptor is ClassDescriptor && this is PsiMethod) descriptor.unsubstitutedPrimaryConstructor else descriptor
}
else -> null
}
}
fun PsiParameter.getParameterDescriptor(): ValueParameterDescriptor? = javaResolutionFacade()?.let {
getParameterDescriptor(it)
}
fun PsiParameter.getParameterDescriptor(resolutionFacade: ResolutionFacade): ValueParameterDescriptor? {
val method = declarationScope as? PsiMethod ?: return null
val methodDescriptor = method.getJavaMethodDescriptor(resolutionFacade) ?: return null
return methodDescriptor.valueParameters[parameterIndex()]
}
fun PsiClass.resolveToDescriptor(
resolutionFacade: ResolutionFacade,
declarationTranslator: (KtClassOrObject) -> KtClassOrObject? = { it }
): ClassDescriptor? {
return if (this is KtLightClass && this !is KtLightClassForDecompiledDeclaration) {
val origin = this.kotlinOrigin ?: return null
val declaration = declarationTranslator(origin) ?: return null
resolutionFacade.resolveToDescriptor(declaration)
} else {
getJavaClassDescriptor(resolutionFacade)
} as? ClassDescriptor
}
@OptIn(FrontendInternals::class)
private fun PsiElement.getJavaDescriptorResolver(resolutionFacade: ResolutionFacade): JavaDescriptorResolver? {
return resolutionFacade.tryGetFrontendService(this, JavaDescriptorResolver::class.java)
}
private fun JavaDescriptorResolver.resolveMethod(method: JavaMethod): FunctionDescriptor? {
return getContainingScope(method)?.getContributedFunctions(method.name, NoLookupLocation.FROM_IDE)?.findByJavaElement(method)
}
private fun JavaDescriptorResolver.resolveConstructor(constructor: JavaConstructor): ConstructorDescriptor? {
return resolveClass(constructor.containingClass)?.constructors?.findByJavaElement(constructor)
}
private fun JavaDescriptorResolver.resolveField(field: JavaField): PropertyDescriptor? {
return getContainingScope(field)?.getContributedVariables(field.name, NoLookupLocation.FROM_IDE)?.findByJavaElement(field)
}
private fun JavaDescriptorResolver.getContainingScope(member: JavaMember): MemberScope? {
val containingClass = resolveClass(member.containingClass)
return if (member.isStatic)
containingClass?.staticScope
else
containingClass?.defaultType?.memberScope
}
private fun <T : DeclarationDescriptorWithSource> Collection<T>.findByJavaElement(javaElement: JavaElement): T? {
return firstOrNull { member ->
val memberJavaElement = (member.original.source as? JavaSourceElement)?.javaElement
when {
memberJavaElement == javaElement ->
true
memberJavaElement is JavaElementImpl<*> && javaElement is JavaElementImpl<*> ->
memberJavaElement.psi.isEquivalentTo(javaElement.psi)
else ->
false
}
}
}
fun PsiElement.hasJavaResolutionFacade(): Boolean = this.originalElement.containingFile != null
fun PsiElement.javaResolutionFacade() =
KotlinCacheService.getInstance(project).getResolutionFacadeByFile(
this.originalElement.containingFile ?: reportCouldNotCreateJavaFacade(),
JvmPlatforms.unspecifiedJvmPlatform
)
private fun PsiElement.reportCouldNotCreateJavaFacade(): Nothing =
runReadAction {
error(
"Could not get javaResolutionFacade for element:\n" +
"same as originalElement = ${this === this.originalElement}" +
"class = ${javaClass.name}, text = $text, containingFile = ${containingFile?.name}\n" +
"originalElement.class = ${originalElement.javaClass.name}, originalElement.text = ${originalElement.text}), " +
"originalElement.containingFile = ${originalElement.containingFile?.name}"
)
}
| apache-2.0 | 4faf6be46b9e7f3a370133f2e66bcc77 | 46.082803 | 158 | 0.771104 | 5.5 | false | false | false | false |
kelemen/JTrim | buildSrc/src/main/kotlin/org/jtrim2/build/PackageUtils.kt | 1 | 2032 | package org.jtrim2.build
import java.io.IOException
import java.nio.file.FileVisitResult
import java.nio.file.FileVisitor
import java.nio.file.Files
import java.nio.file.Path
import java.nio.file.attribute.BasicFileAttributes
import java.util.ArrayDeque
import java.util.Deque
object PackageUtils {
fun collectPackageListFromSourceRoot(sourceRoot: Path, result: MutableSet<String>) {
if (!Files.isDirectory(sourceRoot)) {
return
}
val rootCounter = FileCounter()
Files.walkFileTree(sourceRoot, object : FileVisitor<Path> {
private val counters: Deque<FileCounter> = ArrayDeque()
private var topCounter = rootCounter
override fun preVisitDirectory(dir: Path, attrs: BasicFileAttributes): FileVisitResult {
counters.push(topCounter)
topCounter = FileCounter()
return FileVisitResult.CONTINUE
}
override fun visitFile(file: Path, attrs: BasicFileAttributes): FileVisitResult {
topCounter.fileCount++
return FileVisitResult.CONTINUE
}
override fun visitFileFailed(file: Path, exc: IOException?): FileVisitResult {
return FileVisitResult.CONTINUE
}
override fun postVisitDirectory(dir: Path, exc: IOException?): FileVisitResult {
if (topCounter.fileCount > 0) {
result.add(toPackageName(sourceRoot.relativize(dir)))
}
topCounter = counters.pop()
return FileVisitResult.CONTINUE
}
})
}
private fun toPackageName(relPath: Path): String {
val packageName = StringBuilder()
for (name in relPath) {
if (packageName.isNotEmpty()) {
packageName.append('.')
}
packageName.append(name.toString())
}
return packageName.toString()
}
}
private class FileCounter {
var fileCount = 0
}
| apache-2.0 | 2a4059c568d3cd357e970cbdaeede278 | 31.774194 | 100 | 0.617126 | 5.277922 | false | false | false | false |
Jire/Charlatano | src/main/kotlin/com/charlatano/Charlatano.kt | 1 | 2948 | /*
* Charlatano: Free and open-source (FOSS) cheat for CS:GO/CS:CO
* Copyright (C) 2017 - Thomas G. P. Nappo, Jonathan Beaudoin
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.charlatano
import com.charlatano.game.CSGO
import com.charlatano.overlay.Overlay
import com.charlatano.scripts.aim.flatAim
import com.charlatano.scripts.aim.pathAim
import com.charlatano.scripts.bombTimer
import com.charlatano.scripts.boneTrigger
import com.charlatano.scripts.bunnyHop
import com.charlatano.scripts.esp.esp
import com.charlatano.scripts.rcs
import com.charlatano.settings.*
import com.sun.jna.platform.win32.WinNT
import java.io.File
import java.util.*
import kotlin.script.experimental.jsr223.KotlinJsr223DefaultScriptEngineFactory
import kotlin.system.exitProcess
object Charlatano {
const val SETTINGS_DIRECTORY = "settings"
@JvmStatic
fun main(args: Array<String>) {
System.setProperty("jna.nosys", "true")
System.setProperty("idea.io.use.fallback", "true")
System.setProperty("idea.use.native.fs.for.win", "false")
loadSettings()
if (FLICKER_FREE_GLOW) {
PROCESS_ACCESS_FLAGS = PROCESS_ACCESS_FLAGS or
//required by FLICKER_FREE_GLOW
WinNT.PROCESS_VM_OPERATION
}
if (LEAGUE_MODE) {
GLOW_ESP = false
BOX_ESP = false
SKELETON_ESP = false
ENABLE_ESP = false
ENABLE_BOMB_TIMER = false
ENABLE_FLAT_AIM = false
SERVER_TICK_RATE = 128 // most leagues are 128-tick
CACHE_EXPIRE_MILLIS = 4
PROCESS_ACCESS_FLAGS = WinNT.PROCESS_QUERY_INFORMATION or WinNT.PROCESS_VM_READ // all we need
GARBAGE_COLLECT_ON_MAP_START = true // get rid of traces
}
CSGO.initialize()
bunnyHop()
rcs()
esp()
flatAim()
pathAim()
boneTrigger()
bombTimer()
val scanner = Scanner(System.`in`)
while (!Thread.interrupted()) {
when (scanner.nextLine()) {
"exit", "quit" -> exitProcess(0)
"reload" -> loadSettings()
}
}
}
private fun loadSettings() {
val ef = KotlinJsr223DefaultScriptEngineFactory()
val se = ef.scriptEngine
val strings = File(SETTINGS_DIRECTORY).listFiles()!!.map { file -> file.readText() }
for (string in strings) se.eval(string)
val needsOverlay = ENABLE_BOMB_TIMER or (ENABLE_ESP and (SKELETON_ESP or BOX_ESP))
if (!Overlay.opened && needsOverlay) Overlay.open()
}
} | agpl-3.0 | d5378a3c22a8db9099685b49eb73643c | 28.19802 | 97 | 0.721506 | 3.513707 | false | false | false | false |
ThiagoGarciaAlves/intellij-community | plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/resolve/processors/LocalVariableProcessor.kt | 1 | 1582 | // Copyright 2000-2017 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.plugins.groovy.lang.resolve.processors
import com.intellij.psi.PsiElement
import com.intellij.psi.ResolveState
import com.intellij.psi.scope.ElementClassHint
import com.intellij.psi.scope.NameHint
import com.intellij.psi.scope.ProcessorWithHints
import org.jetbrains.plugins.groovy.lang.psi.api.GroovyResolveResult
import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrField
import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrVariable
import org.jetbrains.plugins.groovy.lang.psi.impl.synthetic.GrBindingVariable
import org.jetbrains.plugins.groovy.lang.resolve.ElementGroovyResult
import org.jetbrains.plugins.groovy.lang.resolve.GrResolverProcessor
class LocalVariableProcessor(name: String) : ProcessorWithHints(), GrResolverProcessor<GroovyResolveResult> {
init {
hint(NameHint.KEY, NameHint { name })
hint(ElementClassHint.KEY, ElementClassHint { false })
hint(GroovyResolveKind.HINT_KEY, GroovyResolveKind.Hint { it === GroovyResolveKind.VARIABLE })
}
private var resolveResult: GroovyResolveResult? = null
override val results: List<GroovyResolveResult> get() = resolveResult?.let { listOf(it) } ?: emptyList()
override fun execute(element: PsiElement, state: ResolveState): Boolean {
if (element !is GrVariable || element is GrField) return true
assert(element !is GrBindingVariable)
resolveResult = ElementGroovyResult(element)
return false
}
}
| apache-2.0 | 29b289ff9c6133c58adc2212f3db820f | 45.529412 | 140 | 0.798989 | 4.298913 | false | false | false | false |
Waboodoo/HTTP-Shortcuts | HTTPShortcuts/app/src/withGoogleServices/kotlin/ch/rmy/android/http_shortcuts/utils/PlayServicesUtilImpl.kt | 1 | 2092 | package ch.rmy.android.http_shortcuts.utils
import android.content.Context
import android.location.Location
import com.google.android.gms.common.ConnectionResult
import com.google.android.gms.common.GoogleApiAvailabilityLight
import com.google.android.gms.location.CurrentLocationRequest
import com.google.android.gms.location.LocationServices
import com.google.android.gms.tasks.CancellationTokenSource
import kotlinx.coroutines.suspendCancellableCoroutine
import kotlin.coroutines.resume
import kotlin.coroutines.resumeWithException
import kotlin.time.Duration.Companion.seconds
class PlayServicesUtilImpl(
private val context: Context,
) : PlayServicesUtil {
override fun isPlayServicesAvailable(): Boolean =
GoogleApiAvailabilityLight.getInstance().isGooglePlayServicesAvailable(context) == ConnectionResult.SUCCESS
override suspend fun getLocation(): PlayServicesUtil.Location? =
suspendCancellableCoroutine { continuation ->
val cancellationTokenSource = CancellationTokenSource()
LocationServices.getFusedLocationProviderClient(context)
.getCurrentLocation(
CurrentLocationRequest.Builder()
.setDurationMillis(MAX_LOOKUP_TIME.inWholeMilliseconds)
.build(),
cancellationTokenSource.token,
)
.addOnSuccessListener { location: Location? ->
continuation.resume(location?.toDataObject())
}
.addOnFailureListener { error ->
continuation.resumeWithException(error)
}
continuation.invokeOnCancellation {
cancellationTokenSource.cancel()
}
}
companion object {
private val MAX_LOOKUP_TIME = 20.seconds
private fun Location.toDataObject() =
PlayServicesUtil.Location(
latitude = latitude,
longitude = longitude,
accuracy = if (hasAccuracy()) accuracy else null,
)
}
}
| mit | 5dbdea6686f22ac344c6b9052e33861c | 37.740741 | 115 | 0.672084 | 6.063768 | false | false | false | false |
sksamuel/ktest | kotest-property/src/commonMain/kotlin/io/kotest/property/Shrinker.kt | 1 | 2120 | package io.kotest.property
/**
* Given a value, T, this function returns reduced values to be used as candidates
* for shrinking.
*
* A smaller value is defined per Shrinker. For a string it may be considered a string with
* less characters, or less duplication/variation in the characters. For an integer it is typically
* considered a smaller value with a positive sign.
*
* Shrinkers can return one or more values in a shrink step. Shrinkers can
* return more than one value if there is no single "best path". For example,
* when shrinking an integer, you probably want to return a single smaller value
* at a time. For strings, you may wish to return a string that is simpler (YZ -> YY),
* as well as smaller (YZ -> Y).
*
* If the value cannot be shrunk further, or the type
* does not support meaningful shrinking, then this function should
* return an empty list.
*
* Note: It is important that you do not return the degenerate case as the first step in a shrinker.
* Otherwise, this could be tested first, it could pass, and no other routes would be explored.
*/
interface Shrinker<A> {
/**
* Returns the "next level" of shrinks for the given value, or empty list if a "base case" has been reached.
* For example, to shrink an int k we may decide to return k/2 and k-1.
*/
fun shrink(value: A): List<A>
}
/**
* Generates an [RTree] of all shrinks from an initial strict value.
*/
fun <A> Shrinker<A>.rtree(value: A): RTree<A> {
val fn = { value }
return rtree(fn)
}
/**
* Generates an [RTree] of all shrinks from an initial lazy value.
*/
fun <A> Shrinker<A>.rtree(value: () -> A): RTree<A> =
RTree(
value,
lazy {
val a = value()
shrink(a).distinct().filter { it != a }.map { rtree(it) }
}
)
data class RTree<out A>(val value: () -> A, val children: Lazy<List<RTree<A>>> = lazy { emptyList<RTree<A>>() })
fun <A, B> RTree<A>.map(f: (A) -> B): RTree<B> {
val b = { f(value()) }
val c = lazy { children.value.map { it.map(f) } }
return RTree(b, c)
}
fun <A> RTree<A>.isEmpty() = this.children.value.isEmpty()
| mit | 2b945c33514f29645a76bdae5e44a9f0 | 33.754098 | 112 | 0.663208 | 3.521595 | false | false | false | false |
mikepenz/MaterialDrawer | materialdrawer/src/main/java/com/mikepenz/materialdrawer/model/interfaces/SelectableColor.kt | 1 | 1540 | package com.mikepenz.materialdrawer.model.interfaces
import androidx.annotation.ColorInt
import androidx.annotation.ColorRes
import com.mikepenz.materialdrawer.holder.ColorHolder
/**
* Defines a [IDrawerItem] with support for having a different color when selected
*/
interface SelectableColor {
/** The background color of a selectable item */
var selectedColor: ColorHolder?
}
@Deprecated("Please consider to replace with the actual property setter")
fun <T : SelectableColor> T.withSelectedColor(@ColorInt selectedColor: Int): T {
this.selectedColor = ColorHolder.fromColor(selectedColor)
return this
}
@Deprecated("Please consider to replace with the actual property setter")
fun <T : SelectableColor> T.withSelectedColorRes(@ColorRes selectedColorRes: Int): T {
this.selectedColor = ColorHolder.fromColorRes(selectedColorRes)
return this
}
/** Set the selected color as color resource */
var SelectableColor.selectedColorRes: Int
@Deprecated(level = DeprecationLevel.ERROR, message = "Not readable")
get() = throw UnsupportedOperationException("Please use the direct property")
set(@ColorRes value) {
selectedColor = ColorHolder.fromColorRes(value)
}
/** Set the selected color as color int */
var SelectableColor.selectedColorInt: Int
@Deprecated(level = DeprecationLevel.ERROR, message = "Not readable")
get() = throw UnsupportedOperationException("Please use the direct property")
set(@ColorInt value) {
selectedColor = ColorHolder.fromColor(value)
}
| apache-2.0 | 43fd393e84798d8b8bcefb3d8464688a | 35.666667 | 86 | 0.759091 | 4.827586 | false | false | false | false |
intrigus/jtransc | jtransc-utils/src/com/jtransc/ds/ListReader.kt | 2 | 355 | package com.jtransc.ds
class ListReader<T>(val list: List<T>) {
var position = 0
val size: Int get() = list.size
val eof: Boolean get() = position >= list.size
val hasMore: Boolean get() = position < list.size
fun peek(): T = list[position]
fun skip(count:Int = 1) = this.apply { this.position += count }
fun read(): T = peek().apply { skip(1) }
} | apache-2.0 | 4024c05a4e50092e6b5ab2c23fa8059c | 31.363636 | 64 | 0.653521 | 2.983193 | false | false | false | false |
fgsguedes/adventofcode | 2017/src/main/kotlin/day1/Captcha.kt | 1 | 798 | package day1
import fromOneLineInput
import java.lang.Character.getNumericValue
fun solveCaptchaPart1(input: String) = input.foldIndexed(0) { index, sum, char ->
val nextChar = input[(index + 1) % input.length]
if (char == nextChar) getNumericValue(char) + sum
else sum
}
fun solveCaptchaPart2(input: String): Int {
val step = input.length / 2
return input.foldIndexed(0) { index, sum, char ->
val nextChar = input[(index + step) % input.length]
if (char == nextChar) getNumericValue(char) + sum
else sum
}
}
fun main(args: Array<String>) {
val part1Solution = fromOneLineInput(2017, 1, "Captcha.txt", ::solveCaptchaPart1)
println(part1Solution)
val part2Solution = fromOneLineInput(2017, 1, "CaptchaPart2.txt", ::solveCaptchaPart2)
println(part2Solution)
}
| gpl-2.0 | 591c3404493592ce412319cd4853efce | 25.6 | 88 | 0.713033 | 3.594595 | false | false | false | false |
hazuki0x0/YuzuBrowser | legacy/src/main/java/jp/hazuki/yuzubrowser/legacy/userjs/UserScript.kt | 1 | 6232 | /*
* Copyright (C) 2017-2021 Hazuki
*
* 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 jp.hazuki.yuzubrowser.legacy.userjs
import android.os.Parcel
import android.os.Parcelable
import jp.hazuki.yuzubrowser.core.utility.extensions.forEachLine
import jp.hazuki.yuzubrowser.core.utility.log.ErrorReport
import jp.hazuki.yuzubrowser.core.utility.log.Logger
import java.io.BufferedReader
import java.io.IOException
import java.io.StringReader
import java.util.regex.Pattern
class UserScript : Parcelable {
val info: UserScriptInfo
var name: String? = null
var version: String? = null
var author: String? = null
var description: String? = null
val include = ArrayList<Pattern>(0)
val exclude = ArrayList<Pattern>(0)
var isUnwrap: Boolean = false
private set
var runAt: RunAt = RunAt.END
var id: Long
get() = info.id
set(id) {
info.id = id
}
var data: String
get() = info.data
set(data) {
info.data = data
loadHeaderData()
}
val runnable: String
get() = if (isUnwrap) {
info.data
} else {
"(function() {\n${info.data}\n})()"
}
var isEnabled: Boolean
get() = info.isEnabled
set(enabled) {
info.isEnabled = enabled
}
constructor() {
info = UserScriptInfo()
}
constructor(id: Long, data: String, enabled: Boolean) {
info = UserScriptInfo(id, data, enabled)
loadHeaderData()
}
constructor(data: String) {
info = UserScriptInfo(data)
loadHeaderData()
}
constructor(info: UserScriptInfo) {
this.info = info
loadHeaderData()
}
override fun describeContents(): Int = 0
override fun writeToParcel(dest: Parcel, flags: Int) {
dest.writeLong(info.id)
dest.writeString(info.data)
dest.writeInt(if (info.isEnabled) 1 else 0)
}
constructor(source: Parcel) {
val id = source.readLong()
val data = source.readString()!!
val enabled = source.readInt() == 1
info = UserScriptInfo(id, data, enabled)
loadHeaderData()
}
private fun loadHeaderData() {
name = null
version = null
description = null
include.clear()
exclude.clear()
try {
val reader = BufferedReader(StringReader(info.data))
if (reader.readLine()?.let { sHeaderStartPattern.matcher(it).matches() } != true) {
Logger.w(TAG, "Header (start) parser error")
return
}
reader.forEachLine { line ->
val matcher = sHeaderMainPattern.matcher(line)
if (!matcher.matches()) {
if (sHeaderEndPattern.matcher(line).matches()) {
return
}
Logger.w(TAG, "Unknown header : $line")
} else {
val field = matcher.group(1)
val value = matcher.group(2)
readData(field, value, line)
}
}
Logger.w(TAG, "Header (end) parser error")
} catch (e: IOException) {
ErrorReport.printAndWriteLog(e)
}
}
private fun readData(field: String?, value: String?, line: String) {
if ("name".equals(field, ignoreCase = true)) {
name = value
} else if ("version".equals(field, ignoreCase = true)) {
version = value
} else if ("author".equals(field, ignoreCase = true)) {
author = value
} else if ("description".equals(field, ignoreCase = true)) {
description = value
} else if ("include".equals(field, ignoreCase = true)) {
makeUrlPattern(value)?.let {
include.add(it)
}
} else if ("exclude".equals(field, ignoreCase = true)) {
makeUrlPattern(value)?.let {
exclude.add(it)
}
} else if ("unwrap".equals(field, ignoreCase = true)) {
isUnwrap = true
} else if ("run-at".equals(field, ignoreCase = true)) {
runAt = when (value) {
"document-start" -> RunAt.START
"document-idle" -> RunAt.IDLE
else -> RunAt.END
}
} else if ("match".equals(field, ignoreCase = true) && value != null) {
val patternUrl = "^" + value.replace("?", "\\?").replace(".", "\\.")
.replace("*", ".*").replace("+", ".+")
.replace("://.*\\.", "://((?![\\./]).)*\\.").replace("^\\.\\*://".toRegex(), "https?://")
makeUrlPatternParsed(patternUrl)?.let {
include.add(it)
}
} else {
Logger.w(TAG, "Unknown header : $line")
}
}
enum class RunAt {
START,
END,
IDLE
}
companion object {
private const val TAG = "UserScript"
@JvmField
val CREATOR: Parcelable.Creator<UserScript> = object : Parcelable.Creator<UserScript> {
override fun createFromParcel(source: Parcel): UserScript = UserScript(source)
override fun newArray(size: Int): Array<UserScript?> = arrayOfNulls(size)
}
private val sHeaderStartPattern = Pattern.compile("\\s*//\\s*==UserScript==\\s*", Pattern.CASE_INSENSITIVE)
private val sHeaderEndPattern = Pattern.compile("\\s*//\\s*==/UserScript==\\s*", Pattern.CASE_INSENSITIVE)
private val sHeaderMainPattern = Pattern.compile("\\s*//\\s*@(\\S+)(?:\\s+(.*))?", Pattern.CASE_INSENSITIVE)
}
}
| apache-2.0 | 710a2858c741d04bae45470f4df89d52 | 30.634518 | 116 | 0.557285 | 4.470588 | false | false | false | false |
kpspemu/kpspemu | src/commonMain/kotlin/com/soywiz/kpspemu/hle/modules/pspDveManager.kt | 1 | 1958 | package com.soywiz.kpspemu.hle.modules
import com.soywiz.kpspemu.*
import com.soywiz.kpspemu.hle.*
@Suppress("UNUSED_PARAMETER")
class pspDveManager(emulator: Emulator) :
SceModule(emulator, "pspDveManager", 0x00010011, "pspDveManager.prx", "pspDveManager_Library") {
//STUB_START "pspDveManager",0x40090000,0x00020005
//STUB_FUNC 0x2ACFCB6D,pspDveMgrCheckVideoOut
//STUB_FUNC 0xF9C86C73,pspDveMgrSetVideoOut
//STUB_END
/*
*@return 0 - Cable not connected
*@return 1 - S-Video Cable / AV (composite) cable
*@return 2 - D Terminal Cable / Component Cable
*@return < 0 - Error
*/
fun pspDveMgrCheckVideoOut(): Int {
return 0 // Cable not connected
}
object Cable {
const val D_TERMINAL_CABLE = 0
const val S_VIDEO_CABLE = 2
}
object Mode {
const val PROGRESIVE = 0x1D2
const val INTERLACE = 0x1D1
}
//pspDveMgrSetVideoOut(2, 0x1D2, 720, 503, 1, 15, 0); // S-Video Cable / AV (Composite OUT) / Progressive (480p)
//pspDveMgrSetVideoOut(2, 0x1D1, 720, 503, 1, 15, 0); // S-Video Cable / AV (Composite OUT) / Interlace (480i)
//pspDveMgrSetVideoOut(0, 0x1D2, 720, 480, 1, 15, 0); // D Terminal Cable (Component OUT) / Progressive (480p)
//pspDveMgrSetVideoOut(0, 0x1D1, 720, 503, 1, 15, 0); // D Terminal Cable (Component OUT) / Interlace (480i)
fun pspDveMgrSetVideoOut(cable: Int, mode: Int, width: Int, height: Int, unk2: Int, unk3: Int, unk4: Int): Int {
return 0
}
override fun registerModule() {
registerFunctionInt("pspDveMgrCheckVideoOut", 0x2ACFCB6D, since = 150) { pspDveMgrCheckVideoOut() }
registerFunctionInt("pspDveMgrSetVideoOut", 0xF9C86C73, since = 150) {
pspDveMgrSetVideoOut(
int,
int,
int,
int,
int,
int,
int
)
}
}
}
| mit | d4b57bff2091220496e01f4a34cf4a5b | 32.186441 | 116 | 0.611849 | 3.599265 | false | false | false | false |
badoualy/kotlogram | api/src/main/kotlin/com/github/badoualy/telegram/api/TelegramClientPool.kt | 1 | 3807 | package com.github.badoualy.telegram.api
import org.slf4j.LoggerFactory
import org.slf4j.MarkerFactory
import java.util.*
import kotlin.concurrent.schedule
/**
* Util class to cache clients some time before closing them to be able to re-use them if it's likely that
* they'll be used again soon
*/
class TelegramClientPool private constructor(name: String) {
private val marker = MarkerFactory.getMarker(name)
private val DEFAULT_EXPIRATION_DELAY = 5L * 60L * 1000L // 5 minutes
private var timer = Timer("Timer-${TelegramClientPool::class.java.simpleName}-$name")
private val map = HashMap<Long, TelegramClient>()
private val listenerMap = HashMap<Long, OnClientTimeoutListener>()
private val expireMap = HashMap<Long, Long>()
/**
* Cache the given client for a fixed amount of time before closing it if not used during that time
*
* @param id id associated with the client (used in {@link getAndRemove}
* @param client client to keep open
* @param expiresIn time before expiration (in ms)
*/
@JvmOverloads
fun put(id: Long, client: TelegramClient, listener: OnClientTimeoutListener?, expiresIn: Long = DEFAULT_EXPIRATION_DELAY) {
logger.debug(marker, "Adding client with id $id")
synchronized(this) {
// Already have a client with this id, close the new one and reset timer
expireMap.put(id, System.currentTimeMillis() + expiresIn)
if (listener != null)
listenerMap.put(id, listener)
else listenerMap.remove(id)
if (map.containsKey(id) && map[id] != client)
client.close(false)
else {
map.put(id, client)
Unit // Fix warning...
}
}
try {
timer.schedule(expiresIn, { onTimeout(id) })
} catch (e: IllegalStateException) {
timer = Timer("${javaClass.simpleName}")
timer.schedule(expiresIn, { onTimeout(id) })
}
}
/**
* Retrieve a previously cached client associated with the id
* @param id id used to cache the client
* @return cached client, or null if no client cached for the given id
*/
fun peek(id: Long): TelegramClient? {
synchronized(this) {
return map[id]
}
}
/**
* Retrieve a previously cached client associated with the id and remove it from this pool
* @param id id used to cache the client
* @return cached client, or null if no client cached for the given id
*/
fun getAndRemove(id: Long): TelegramClient? {
synchronized(this) {
expireMap.remove(id)
return map.remove(id)
}
}
fun onTimeout(id: Long) {
val timeout =
synchronized(this) {
if (expireMap.getOrDefault(id, 0) <= System.currentTimeMillis()) {
val client = getAndRemove(id)
if (client != null) {
logger.info(marker, "$id client timeout")
client.close(false)
true
} else false
} else false
}
if (timeout)
listenerMap.remove(id)?.onClientTimeout(id)
}
fun shutdown() {
timer.cancel()
}
fun getKeys() = map.keys
fun getClients() = map.values
companion object {
private val logger = LoggerFactory.getLogger(TelegramClientPool::class.java)
@JvmField
val DEFAULT_POOL = TelegramClientPool("DefaultPool")
@JvmField
val DOWNLOADER_POOL = TelegramClientPool("DownloaderPool")
}
}
interface OnClientTimeoutListener {
fun onClientTimeout(id: Long)
} | mit | 4290fae40c10219a3d54eedbe9ce4136 | 31.547009 | 127 | 0.596007 | 4.648352 | false | false | false | false |
savoirfairelinux/ring-client-android | ring-android/app/src/main/java/cx/ring/account/JamiAccountPasswordFragment.kt | 1 | 7108 | /*
* Copyright (C) 2004-2021 Savoir-faire Linux Inc.
*
* Authors: AmirHossein Naghshzan <[email protected]>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
package cx.ring.account
import android.app.Activity
import android.content.Context
import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import android.view.KeyEvent
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.inputmethod.EditorInfo
import android.view.inputmethod.InputMethodManager
import android.widget.CompoundButton
import android.widget.TextView
import cx.ring.R
import cx.ring.databinding.FragAccJamiPasswordBinding
import cx.ring.mvp.BaseSupportFragment
import dagger.hilt.android.AndroidEntryPoint
import net.jami.account.JamiAccountCreationPresenter
import net.jami.account.JamiAccountCreationView
import net.jami.account.JamiAccountCreationView.UsernameAvailabilityStatus
import net.jami.model.AccountCreationModel
@AndroidEntryPoint
class JamiAccountPasswordFragment : BaseSupportFragment<JamiAccountCreationPresenter, JamiAccountCreationView>(),
JamiAccountCreationView {
private var model: AccountCreationModel? = null
private var binding: FragAccJamiPasswordBinding? = null
private var mIsChecked = false
override fun onSaveInstanceState(outState: Bundle) {
if (model != null) outState.putSerializable(KEY_MODEL, model)
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
if (savedInstanceState != null && model == null) {
model = savedInstanceState.getSerializable(KEY_MODEL) as AccountCreationModelImpl?
}
binding = FragAccJamiPasswordBinding.inflate(inflater, container, false)
return binding!!.root
}
override fun onDestroyView() {
super.onDestroyView()
binding = null
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
binding!!.createAccount.setOnClickListener { presenter.createAccount() }
binding!!.ringPasswordSwitch.setOnCheckedChangeListener { buttonView: CompoundButton?, isChecked: Boolean ->
mIsChecked = isChecked
if (isChecked) {
binding!!.passwordTxtBox.visibility = View.VISIBLE
binding!!.ringPasswordRepeatTxtBox.visibility = View.VISIBLE
binding!!.placeholder.visibility = View.GONE
val password: CharSequence? = binding!!.ringPassword.text
presenter.passwordChanged(password.toString(), binding!!.ringPasswordRepeat.text!!)
} else {
binding!!.passwordTxtBox.visibility = View.GONE
binding!!.ringPasswordRepeatTxtBox.visibility = View.GONE
binding!!.placeholder.visibility = View.VISIBLE
presenter.passwordUnset()
}
}
binding!!.ringPassword.addTextChangedListener(object : TextWatcher {
override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {}
override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {
presenter.passwordChanged(s.toString())
}
override fun afterTextChanged(s: Editable) {}
})
binding!!.ringPasswordRepeat.addTextChangedListener(object : TextWatcher {
override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {}
override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {
presenter.passwordConfirmChanged(s.toString())
}
override fun afterTextChanged(s: Editable) {}
})
binding!!.ringPasswordRepeat.setOnEditorActionListener { v: TextView?, actionId: Int, event: KeyEvent? ->
if (actionId == EditorInfo.IME_ACTION_DONE) {
presenter.createAccount()
}
false
}
binding!!.ringPasswordRepeat.setOnEditorActionListener { v: TextView, actionId: Int, event: KeyEvent? ->
if (actionId == EditorInfo.IME_ACTION_DONE && binding!!.createAccount.isEnabled) {
val inputMethodManager = v.context.getSystemService(Activity.INPUT_METHOD_SERVICE) as InputMethodManager
inputMethodManager.hideSoftInputFromWindow(v.windowToken, 0)
presenter.createAccount()
return@setOnEditorActionListener true
}
false
}
presenter.init(model)
}
override fun updateUsernameAvailability(status: UsernameAvailabilityStatus) {}
override fun showInvalidPasswordError(display: Boolean) {
binding!!.passwordTxtBox.error = if (display) getString(R.string.error_password_char_count) else null
}
override fun showNonMatchingPasswordError(display: Boolean) {
binding!!.ringPasswordRepeatTxtBox.error = if (display) getString(R.string.error_passwords_not_equals) else null
}
override fun enableNextButton(enabled: Boolean) {
binding!!.createAccount.isEnabled = if (mIsChecked) enabled else true
}
override fun goToAccountCreation(accountCreationModel: AccountCreationModel) {
val wizardActivity: Activity? = activity
if (wizardActivity is AccountWizardActivity) {
wizardActivity.createAccount(accountCreationModel)
val parent = parentFragment as JamiAccountCreationFragment?
if (parent != null) {
parent.scrollPagerFragment(accountCreationModel)
val imm = wizardActivity.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
imm.hideSoftInputFromWindow(binding!!.ringPassword.windowToken, 0)
}
}
}
override fun cancel() {
val wizardActivity: Activity? = activity
wizardActivity?.onBackPressed()
}
fun setUsername(username: String) {
model!!.username = username
}
companion object {
private const val KEY_MODEL = "model"
fun newInstance(ringAccountViewModel: AccountCreationModelImpl): JamiAccountPasswordFragment {
val fragment = JamiAccountPasswordFragment()
fragment.model = ringAccountViewModel
return fragment
}
}
} | gpl-3.0 | aac1c72f2ecc0ebd58e7a9354ec630fc | 42.613497 | 120 | 0.69668 | 5.211144 | false | false | false | false |
proxer/ProxerLibAndroid | library/src/main/kotlin/me/proxer/library/api/notifications/NewsEndpoint.kt | 2 | 945 | package me.proxer.library.api.notifications
import me.proxer.library.ProxerCall
import me.proxer.library.api.PagingLimitEndpoint
import me.proxer.library.entity.notifications.NewsArticle
/**
* Endpoint for retrieving news articles.
*
* @author Ruben Gees
*/
class NewsEndpoint internal constructor(private val internalApi: InternalApi) : PagingLimitEndpoint<List<NewsArticle>> {
private var page: Int? = null
private var limit: Int? = null
private var markAsRead: Boolean? = null
override fun page(page: Int?) = this.apply { this.page = page }
override fun limit(limit: Int?) = this.apply { this.limit = limit }
/**
* Sets if the news should be marked as read. Defaults to false.
*/
fun markAsRead(markAsRead: Boolean? = true) = this.apply { this.markAsRead = markAsRead }
override fun build(): ProxerCall<List<NewsArticle>> {
return internalApi.news(page, limit, markAsRead)
}
}
| gpl-3.0 | 323002b5f4ad95c97eb4690d1f484002 | 30.5 | 120 | 0.712169 | 4.181416 | false | false | false | false |
luks91/Team-Bucket | app/src/main/java/com/github/luks91/teambucket/main/statistics/load/StatisticsLoadFragment.kt | 2 | 3164 | /**
* Copyright (c) 2017-present, Team Bucket 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
*
* 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.github.luks91.teambucket.main.statistics.load
import android.content.Context
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ProgressBar
import android.widget.TextView
import com.github.luks91.teambucket.R
import com.hannesdorfmann.mosby3.mvp.MvpFragment
import dagger.android.support.AndroidSupportInjection
import io.reactivex.Observable
import io.reactivex.subjects.PublishSubject
import javax.inject.Inject
class StatisticsLoadFragment : MvpFragment<StatisticsLoadView, StatisticsLoadPresenter>(), StatisticsLoadView {
@Inject lateinit var statisticsPresenter: StatisticsLoadPresenter
private val intentPullToRefresh = PublishSubject.create<Any>()
private val loadProgressBar: ProgressBar by lazy { view!!.findViewById(R.id.statisticsLoadProgressBar) as ProgressBar }
private val progressText: TextView by lazy { view!!.findViewById(R.id.progressValue) as TextView }
companion object Factory {
fun newInstance() = StatisticsLoadFragment()
}
override fun onAttach(context: Context?) {
super.onAttach(context)
AndroidSupportInjection.inject(this)
}
override fun createPresenter() = statisticsPresenter
override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? {
return inflater!!.inflate(R.layout.fragment_load_statistics, container, false)
}
override fun intentRefreshData(): Observable<Any> = intentPullToRefresh
private var pullRequestsCount = 0
private var completedPullRequestsCount = 0
override fun onLoadingStarted() {
loadProgressBar.visibility = View.VISIBLE
completedPullRequestsCount = 0
pullRequestsCount = 0
}
override fun onPullRequestDetected() {
if (!isDetached) {
activity.runOnUiThread {
pullRequestsCount++
updateProgress()
}
}
}
private fun updateProgress() {
loadProgressBar.progress = if (pullRequestsCount == 0) 0 else (100.0 * completedPullRequestsCount / pullRequestsCount)
.toInt()
progressText.text = "$completedPullRequestsCount/$pullRequestsCount"
}
override fun onPullRequestProcessed() {
if (!isDetached) {
activity.runOnUiThread {
completedPullRequestsCount++
updateProgress()
}
}
}
override fun onLoadingCompleted() {
}
} | apache-2.0 | 2eb6d5424f8979a333632ccb2003d4e2 | 34.561798 | 126 | 0.720923 | 5.054313 | false | false | false | false |
luks91/Team-Bucket | app/src/main/java/com/github/luks91/teambucket/main/home/HomeFragment.kt | 2 | 2642 | /**
* Copyright (c) 2017-present, Team Bucket 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
*
* 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.github.luks91.teambucket.main.home
import android.os.Bundle
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.github.luks91.teambucket.R
import com.github.luks91.teambucket.main.base.BasePullRequestsFragment
import com.github.luks91.teambucket.model.AvatarLoadRequest
import com.github.luks91.teambucket.model.PullRequest
import com.github.luks91.teambucket.model.ReviewersInformation
import com.jakewharton.rxrelay2.PublishRelay
import com.jakewharton.rxrelay2.Relay
import javax.inject.Inject
class HomeFragment : BasePullRequestsFragment<HomeView, HomePresenter>(), HomeView {
private val imageLoadRequests: Relay<AvatarLoadRequest> = PublishRelay.create()
private val dataAdapter by lazy { HomeAdapter(context, imageLoadRequests) }
private val layoutManager by lazy { LinearLayoutManager(context) }
@Inject lateinit var homePresenter: HomePresenter
companion object Factory {
fun newInstance() : HomeFragment = HomeFragment()
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View =
inflater.inflate(R.layout.fragment_swipe_recycler_view, container, false)
override fun onViewCreated(view: View?, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val recyclerView = view!!.findViewById(R.id.reviewersRecyclerView) as RecyclerView
recyclerView.layoutManager = layoutManager
recyclerView.adapter = dataAdapter
}
override fun createPresenter() = homePresenter
override fun onReviewersReceived(reviewers: ReviewersInformation) = dataAdapter.onReviewersReceived(reviewers)
override fun intentLoadAvatarImage() = imageLoadRequests
override fun onUserPullRequestsProvided(pullRequests: List<PullRequest>) =
dataAdapter.onUserPullRequestsReceived(pullRequests)
} | apache-2.0 | 300012c80c9ac62c05f3f44eeeefd3be | 42.327869 | 115 | 0.784633 | 4.76036 | false | false | false | false |
evant/silent-support | silent-support/src/test/kotlin/me/tatarka/silentsupport/SupportMetadataProcessorTest.kt | 1 | 2506 | package me.tatarka.silentsupport
import com.android.tools.lint.client.api.JavaParser
import com.android.tools.lint.client.api.LintClient
import com.android.tools.lint.client.api.UastParser
import com.android.tools.lint.client.api.XmlParser
import com.android.tools.lint.detector.api.*
import me.tatarka.assertk.assert
import me.tatarka.assertk.assertions.isGreaterThan
import me.tatarka.silentsupport.lint.ApiLookup
import org.junit.Before
import org.junit.Test
import java.io.File
class SupportMetadataProcessorTest {
lateinit var processor: SupportMetadataProcessor
lateinit var lookup: ApiLookup
val outputDir = File("build/resources/test")
@Before
fun setup() {
processor = SupportMetadataProcessor(
SupportCompat(File("test-libs/support-compat-25.3.0.aar"), "25.3.0"),
outputDir)
}
@Test
fun `can find ContextCompat#getDrawable`() {
val lintClient = object : LintClient() {
override fun getUastParser(p0: Project): UastParser {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun report(context: Context, issue: Issue, severity: Severity?, location: Location?, message: String?, format: TextFormat?, fix: LintFix?) {
}
override fun log(severity: Severity?, exception: Throwable?, format: String?, vararg args: Any?) {
}
override fun getJavaParser(project: Project?): JavaParser {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun readFile(file: File?): CharSequence {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun getXmlParser(): XmlParser {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun getCacheDir(name: String, create: Boolean): File {
return outputDir
}
}
processor.process()
lookup = ApiLookup.create(lintClient, processor.metadataFile, true)
val result = lookup.getCallVersion("android/support/v4/content/ContextCompat", "getDrawable", "(Landroid/content/Context;I)Landroid/graphics/drawable/Drawable;")
assert(result).isGreaterThan(0)
}
}
| apache-2.0 | c3768e04b9ec28bdee29b9944e9b8ca3 | 35.852941 | 169 | 0.662809 | 4.623616 | false | true | false | false |
facebook/fresco | imagepipeline/src/main/java/com/facebook/imagepipeline/memory/MemoryPooledByteBufferFactory.kt | 1 | 3157 | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
package com.facebook.imagepipeline.memory
import androidx.annotation.VisibleForTesting
import com.facebook.common.internal.Throwables
import com.facebook.common.memory.PooledByteBufferFactory
import com.facebook.common.memory.PooledByteStreams
import com.facebook.common.references.CloseableReference
import java.io.IOException
import java.io.InputStream
import javax.annotation.concurrent.ThreadSafe
/**
* A factory to provide instances of [MemoryPooledByteBuffer] and
* [MemoryPooledByteBufferOutputStream]
*/
@ThreadSafe
class MemoryPooledByteBufferFactory( // memory pool
private val pool: MemoryChunkPool, private val pooledByteStreams: PooledByteStreams) :
PooledByteBufferFactory {
override fun newByteBuffer(size: Int): MemoryPooledByteBuffer {
check(size > 0)
val chunkRef = CloseableReference.of(pool[size], pool)
return try {
MemoryPooledByteBuffer(chunkRef, size)
} finally {
chunkRef.close()
}
}
@Throws(IOException::class)
override fun newByteBuffer(inputStream: InputStream): MemoryPooledByteBuffer {
val outputStream = MemoryPooledByteBufferOutputStream(pool)
return try {
newByteBuf(inputStream, outputStream)
} finally {
outputStream.close()
}
}
override fun newByteBuffer(bytes: ByteArray): MemoryPooledByteBuffer {
val outputStream = MemoryPooledByteBufferOutputStream(pool, bytes.size)
return try {
outputStream.write(bytes, 0, bytes.size)
outputStream.toByteBuffer()
} catch (ioe: IOException) {
throw Throwables.propagate(ioe)
} finally {
outputStream.close()
}
}
@Throws(IOException::class)
override fun newByteBuffer(
inputStream: InputStream,
initialCapacity: Int
): MemoryPooledByteBuffer {
val outputStream = MemoryPooledByteBufferOutputStream(pool, initialCapacity)
return try {
newByteBuf(inputStream, outputStream)
} finally {
outputStream.close()
}
}
/**
* Reads all bytes from inputStream and writes them to outputStream. When all bytes are read
* outputStream.toByteBuffer is called and obtained MemoryPooledByteBuffer is returned
*
* @param inputStream the input stream to read from
* @param outputStream output stream used to transform content of input stream to
* MemoryPooledByteBuffer
* @return an instance of MemoryPooledByteBuffer
* @throws IOException
*/
@VisibleForTesting
@Throws(IOException::class)
fun newByteBuf(
inputStream: InputStream,
outputStream: MemoryPooledByteBufferOutputStream
): MemoryPooledByteBuffer {
pooledByteStreams.copy(inputStream, outputStream)
return outputStream.toByteBuffer()
}
override fun newOutputStream(): MemoryPooledByteBufferOutputStream =
MemoryPooledByteBufferOutputStream(pool)
override fun newOutputStream(initialCapacity: Int): MemoryPooledByteBufferOutputStream =
MemoryPooledByteBufferOutputStream(pool, initialCapacity)
}
| mit | a17f27729704897da22dd53bd1c7438c | 31.214286 | 94 | 0.755147 | 5.200988 | false | true | false | false |
summerlly/Quiet | app/src/main/java/tech/summerly/quiet/service/SimpleMusicPlayer.kt | 1 | 5118 | /*
* Copyright (C) 2017 YangBin
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package tech.summerly.quiet.service
import tech.summerly.quiet.extensions.log
import tech.summerly.quiet.module.common.bean.Music
import tech.summerly.quiet.module.common.bus.RxBus
import tech.summerly.quiet.module.common.player.BaseMusicPlayer
import tech.summerly.quiet.module.common.player.PlayMode
import java.util.*
import kotlin.collections.ArrayList
/**
* author : yangbin10
* date : 2017/11/21
*/
class SimpleMusicPlayer private constructor() : BaseMusicPlayer() {
companion object {
@JvmStatic
val instance = SimpleMusicPlayer()
}
private val musicList = LinkedList<Music>()
private val shuffleMusicList = ArrayList<Music>()
override fun getNextMusic(current: Music?): Music? {
if (musicList.isEmpty()) {
log { "empty playlist!" }
return null
}
if (current == null) {
return musicList[0]
}
return when (playMode) {
PlayMode.SINGLE -> {
current
}
PlayMode.SEQUENCE -> {
//if can not find ,index will be zero , it will right too
val index = musicList.indexOf(current) + 1
if (index == musicList.size) {
musicList[0]
} else {
musicList[index]
}
}
PlayMode.SHUFFLE -> {
ensureShuffleListGenerate()
//if can not find ,index will be zero , it will right too
val index = shuffleMusicList.indexOf(current)
when (index) {
-1 -> musicList[0]
musicList.size - 1 -> {
generateShuffleList()
shuffleMusicList[0]
}
else -> shuffleMusicList[index + 1]
}
}
}
}
private fun ensureShuffleListGenerate() {
if (shuffleMusicList.size != musicList.size) {
generateShuffleList()
}
}
private fun generateShuffleList() {
val list = ArrayList(musicList)
var position = list.size - 1
while (position > 0) {
//生成一个随机数
val random = (Math.random() * (position + 1)).toInt()
//将random和position两个元素交换
val temp = list[position]
list[position] = list[random]
list[random] = temp
position--
}
shuffleMusicList.clear()
shuffleMusicList.addAll(list)
}
override fun getPreviousMusic(current: Music?): Music? {
if (musicList.isEmpty()) {
log { "try too play next with empty playlist!" }
return null
}
if (current == null) {
return musicList[0]
}
return when (playMode) {
PlayMode.SINGLE -> {
current
}
PlayMode.SEQUENCE -> {
val index = musicList.indexOf(current)
when (index) {
-1 -> musicList[0]
0 -> musicList[musicList.size - 1]
else -> musicList[index - 1]
}
}
PlayMode.SHUFFLE -> {
ensureShuffleListGenerate()
val index = shuffleMusicList.indexOf(current)
when (index) {
-1 -> musicList[0]
0 -> {
generateShuffleList()
shuffleMusicList[shuffleMusicList.size - 1]
}
else -> shuffleMusicList[index - 1]
}
}
}
}
override fun setPlaylist(musics: List<Music>) {
stop()
musicList.clear()
musicList.addAll(musics)
super.setPlaylist(musics)
}
override fun getPlaylist(): List<Music> = musicList
override fun remove(music: Music) {
musicList.remove(music)
}
override fun addToNext(music: Music) {
if (!musicList.contains(music)) {
val index = musicList.indexOf(currentPlaying()) + 1
musicList.add(index, music)
}
}
override fun destroy() {
super.destroy()
RxBus.publish(DestroyEvent())
}
class DestroyEvent
} | gpl-2.0 | 44eab355ce4d150767edaef4891aac96 | 29.842424 | 82 | 0.543632 | 4.873563 | false | false | false | false |
StevenDXC/DxLoadingButton | library/src/main/java/com/dx/dxloadingbutton/lib/LoadingButton.kt | 1 | 26823 | package com.dx.dxloadingbutton.lib
import android.animation.Animator
import android.animation.AnimatorSet
import android.animation.ValueAnimator
import android.annotation.SuppressLint
import android.content.Context
import android.graphics.*
import android.util.AttributeSet
import android.view.MotionEvent
import android.view.View
import android.view.animation.AccelerateDecelerateInterpolator
import android.view.animation.DecelerateInterpolator
import kotlin.math.max
import kotlin.math.min
enum class AnimationType{
SUCCESSFUL,
FAILED
}
@Suppress("unused")
class LoadingButton @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
defStyle: Int = 0) : View(context, attrs, defStyle){
companion object {
private const val STATE_BUTTON = 0
private const val STATE_ANIMATION_STEP1 = 1
private const val STATE_ANIMATION_STEP2 = 2
private const val STATE_ANIMATION_LOADING = 3
private const val STATE_STOP_LOADING = 4
private const val STATE_ANIMATION_SUCCESS = 5
private const val STATE_ANIMATION_FAILED = 6
private const val DEFAULT_WIDTH = 88
private const val DEFAULT_HEIGHT = 56
private const val DEFAULT_COLOR = Color.BLUE
private const val DEFAULT_TEXT_COLOR = Color.WHITE
}
private val mDensity = resources.displayMetrics.density
private val defaultMinHeight = 48 * mDensity
var animationEndAction: ((AnimationType) -> Unit)? = null
var rippleEnable = true
set(value) {
invalidate()
field = value
}
var rippleColor = Color.BLACK
set(value){
mRipplePaint.color = value
field = value
}
var textColor
get() = mTextColor
set(value) {
mTextColor = value
invalidate()
}
var typeface: Typeface
get() = mTextPaint.typeface
set(value) {
mTextPaint.typeface = value
invalidate()
}
var text
get() = mText
set(value) {
if (text.isEmpty()) {
return
}
this.mText = value
mTextWidth = mTextPaint.measureText(mText)
mTextHeight = measureTextHeight(mTextPaint)
invalidate()
}
/**
* set button text, dip
*/
var textSize
get() = (mTextPaint.textSize / mDensity).toInt()
set(value) {
mTextPaint.textSize = value * mDensity
mTextWidth = mTextPaint.measureText(mText)
invalidate()
}
var cornerRadius
get() = mButtonCorner
set(value) {
mButtonCorner = value
invalidate()
}
/** while loading data failed, reset view to normal state */
var resetAfterFailed = true
/**
* set button background as shader paint
*/
var backgroundShader: Shader?
get() = mStrokePaint.shader
set(value) {
mPaint.shader = value
mStrokePaint.shader = value
mPathEffectPaint.shader = value
mPathEffectPaint2.shader = value
invalidate()
}
private var mCurrentState = STATE_BUTTON
private var mMinHeight = defaultMinHeight
private var mColorPrimary = DEFAULT_COLOR
private var mDisabledBgColor = Color.LTGRAY
private var mTextColor = Color.WHITE
private var mDisabledTextColor = Color.DKGRAY
private var mRippleAlpha = 0.2f
private var mPadding = 6 * mDensity
private val mPaint = Paint()
private val mRipplePaint = Paint()
private val mStrokePaint = Paint()
private val mTextPaint = Paint()
private val mPathEffectPaint = Paint()
private val mPathEffectPaint2 = Paint()
private var mScaleWidth = 0
private var mScaleHeight = 0
private var mDegree = 0
private var mAngle = 0
private var mEndAngle= 0
private var mButtonCorner = 2 * mDensity
private var mRadius = 0
private var mTextWidth = 0f
private var mTextHeight = 0f
private val mMatrix = Matrix()
private var mPath = Path()
private var mSuccessPath: Path? = null
private var mSuccessPathLength = 0f
private var mSuccessPathIntervals: FloatArray? = null
private var mFailedPath: Path? = null
private var mFailedPath2: Path? = null
private var mFailedPathLength = 0f
private var mFailedPathIntervals: FloatArray? = null
private var mTouchX = 0f
private var mTouchY = 0f
private var mRippleRadius = 0f
private val mButtonRectF = RectF()
private val mArcRectF = RectF()
private var mText: String = ""
private var mLoadingAnimatorSet: AnimatorSet? = null
init {
if (attrs != null) {
val ta = context.obtainStyledAttributes(attrs, R.styleable.LoadingButton, 0, 0)
mColorPrimary = ta.getInt(R.styleable.LoadingButton_lb_btnColor, Color.BLUE)
mDisabledBgColor = ta.getColor(R.styleable.LoadingButton_lb_btnDisabledColor, Color.LTGRAY)
mDisabledTextColor = ta.getColor(R.styleable.LoadingButton_lb_disabledTextColor, Color.DKGRAY)
val text = ta.getString(R.styleable.LoadingButton_lb_btnText)
mText = text ?: ""
mTextColor = ta.getColor(R.styleable.LoadingButton_lb_textColor, Color.WHITE)
resetAfterFailed = ta.getBoolean(R.styleable.LoadingButton_lb_resetAfterFailed, true)
rippleColor = ta.getColor(R.styleable.LoadingButton_lb_btnRippleColor, Color.BLACK)
rippleEnable = ta.getBoolean(R.styleable.LoadingButton_lb_rippleEnable, true)
mRippleAlpha = ta.getFloat(R.styleable.LoadingButton_lb_btnRippleAlpha, 0.3f)
mButtonCorner = ta.getDimension(R.styleable.LoadingButton_lb_cornerRadius, 2 * mDensity)
mMinHeight = ta.getDimension(R.styleable.LoadingButton_lb_min_height, defaultMinHeight)
ta.recycle()
}
mPaint.apply {
setLayerType(LAYER_TYPE_SOFTWARE, this)
isAntiAlias = true
color = mColorPrimary
style = Paint.Style.FILL
setShadowDepth(2 * mDensity)
}
mRipplePaint.apply {
isAntiAlias = true
color = rippleColor
alpha = (mRippleAlpha * 255).toInt()
style = Paint.Style.FILL
}
mStrokePaint.apply {
isAntiAlias = true
color = mColorPrimary
style = Paint.Style.STROKE
strokeWidth = 2 * mDensity
}
mTextPaint.apply {
isAntiAlias = true
color = mTextColor
textSize = 16 * mDensity
isFakeBoldText = true
}
mTextWidth = mTextPaint.measureText(mText)
mTextHeight = measureTextHeight(mTextPaint)
mPathEffectPaint.apply {
isAntiAlias = true
color = mColorPrimary
style = Paint.Style.STROKE
strokeWidth = 2 * mDensity
}
mPathEffectPaint2.apply {
isAntiAlias = true
color = mColorPrimary
style = Paint.Style.STROKE
strokeWidth = 2 * mDensity
}
setLayerType(LAYER_TYPE_SOFTWARE, mPaint)
}
override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec)
setMeasuredDimension(
measureDimension((DEFAULT_WIDTH * mDensity).toInt(), widthMeasureSpec),
measureDimension((DEFAULT_HEIGHT * mDensity).toInt(), heightMeasureSpec))
}
override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
super.onSizeChanged(w, h, oldw, oldh)
val viewHeight = max(h, mMinHeight.toInt())
mRadius = (viewHeight - mPadding * 2).toInt() / 2
mButtonRectF.top = mPadding
mButtonRectF.bottom = viewHeight - mPadding
mArcRectF.left = (width / 2 - mRadius).toFloat()
mArcRectF.top = mPadding
mArcRectF.right = (width / 2 + mRadius).toFloat()
mArcRectF.bottom = viewHeight - mPadding
}
override fun setEnabled(enabled: Boolean) {
super.setEnabled(enabled)
if (mCurrentState == STATE_BUTTON) {
updateButtonColor()
}
}
@SuppressLint("ClickableViewAccessibility")
override fun onTouchEvent(event: MotionEvent): Boolean {
if (!isEnabled) {
return true
}
when (event.action) {
MotionEvent.ACTION_DOWN -> {
mTouchX = event.x
mTouchY = event.y
playTouchDownAnimation()
}
MotionEvent.ACTION_UP -> if (event.x > mButtonRectF.left && event.x < mButtonRectF.right && event.y > mButtonRectF.top && event.y < mButtonRectF.bottom) {
// only register as click if finger is up inside view
playRippleAnimation()
} else {
// if finger is moved outside view and lifted up, reset view
mTouchX = 0f
mTouchY = 0f
mRippleRadius = 0f
mRipplePaint.alpha = (mRippleAlpha * 255).toInt()
mPaint.setShadowDepth(2 * mDensity)
invalidate()
}
}
return true
}
override fun onDraw(canvas: Canvas) {
super.onDraw(canvas)
val viewHeight = max(height, mMinHeight.toInt())
when (mCurrentState) {
STATE_BUTTON, STATE_ANIMATION_STEP1 -> {
val cornerRadius = (mRadius - mButtonCorner) * (mScaleWidth / (width / 2 - viewHeight / 2).toFloat()) + mButtonCorner
mButtonRectF.left = mScaleWidth.toFloat()
mButtonRectF.right = (width - mScaleWidth).toFloat()
canvas.drawRoundRect(mButtonRectF, cornerRadius, cornerRadius, mPaint)
if (mCurrentState == STATE_BUTTON) {
canvas.drawText(mText, (width - mTextWidth) / 2, (viewHeight - mTextHeight) / 2 + mPadding * 2, mTextPaint)
if ((mTouchX > 0 || mTouchY > 0) && rippleEnable) {
canvas.clipRect(0f, mPadding, width.toFloat(), viewHeight - mPadding)
canvas.drawCircle(mTouchX, mTouchY, mRippleRadius, mRipplePaint)
}
}
}
STATE_ANIMATION_STEP2 -> {
canvas.drawCircle((width / 2).toFloat(), (viewHeight / 2).toFloat(), (mRadius - mScaleHeight).toFloat(), mPaint)
canvas.drawCircle((width / 2).toFloat(), (viewHeight / 2).toFloat(), mRadius - mDensity, mStrokePaint)
}
STATE_ANIMATION_LOADING -> {
mPath.reset()
mPath.addArc(mArcRectF, (270 + mAngle / 2).toFloat(), (360 - mAngle).toFloat())
if (mAngle != 0) {
mMatrix.setRotate(mDegree.toFloat(), (width / 2).toFloat(), (viewHeight / 2).toFloat())
mPath.transform(mMatrix)
mDegree += 10
}
canvas.drawPath(mPath, mStrokePaint)
}
STATE_STOP_LOADING -> {
mPath.reset()
mPath.addArc(mArcRectF, (270 + mAngle / 2).toFloat(), mEndAngle.toFloat())
if (mEndAngle != 360) {
mMatrix.setRotate(mDegree.toFloat(), (width / 2).toFloat(), (viewHeight / 2).toFloat())
mPath.transform(mMatrix)
mDegree += 10
}
canvas.drawPath(mPath, mStrokePaint)
}
STATE_ANIMATION_SUCCESS -> {
canvas.drawPath(mSuccessPath!!, mPathEffectPaint)
canvas.drawCircle((width / 2).toFloat(), (viewHeight / 2).toFloat(), mRadius - mDensity, mStrokePaint)
}
STATE_ANIMATION_FAILED -> {
canvas.drawPath(mFailedPath!!, mPathEffectPaint)
canvas.drawPath(mFailedPath2!!, mPathEffectPaint2)
canvas.drawCircle((width / 2).toFloat(), (viewHeight / 2).toFloat(), mRadius - mDensity, mStrokePaint)
}
}
}
/**
* start loading,play animation
*/
fun startLoading() {
if (mCurrentState == STATE_ANIMATION_FAILED && !resetAfterFailed) {
scaleFailedPath()
return
}
if (mCurrentState == STATE_BUTTON) {
mCurrentState = STATE_ANIMATION_STEP1
mPaint.clearShadowLayer()
playStartAnimation(false)
}
}
/**
* loading data successful
*/
fun loadingSuccessful() {
if (mLoadingAnimatorSet != null && mLoadingAnimatorSet!!.isStarted) {
mLoadingAnimatorSet!!.end()
mCurrentState = STATE_STOP_LOADING
playSuccessAnimation()
}
}
/**
* loading data failed
*/
fun loadingFailed() {
if (mLoadingAnimatorSet != null && mLoadingAnimatorSet!!.isStarted) {
mLoadingAnimatorSet!!.end()
mCurrentState = STATE_STOP_LOADING
playFailedAnimation()
}
}
fun cancelLoading() {
if (mCurrentState != STATE_ANIMATION_LOADING) {
return
}
cancel()
}
/**
* reset view to Button with animation
*/
fun reset(){
when(mCurrentState){
STATE_ANIMATION_SUCCESS -> scaleSuccessPath()
STATE_ANIMATION_FAILED -> scaleFailedPath()
}
}
private fun measureTextHeight(paint: Paint): Float{
val bounds = Rect()
paint.getTextBounds(mText, 0, mText.length, bounds)
return bounds.height().toFloat()
}
private fun createSuccessPath() {
if (mSuccessPath != null) {
mSuccessPath!!.reset()
} else {
mSuccessPath = Path()
}
val mLineWith = 2 * mDensity
val left = (width / 2 - mRadius).toFloat() + (mRadius / 3).toFloat() + mLineWith
val top = mPadding + (mRadius / 2).toFloat() + mLineWith
val right = (width / 2 + mRadius).toFloat() - mLineWith - (mRadius / 3).toFloat()
val bottom = (mLineWith + mRadius) * 1.5f + mPadding / 2
val xPoint = (width / 2 - mRadius / 6).toFloat()
mSuccessPath = Path().apply {
moveTo(left, mPadding + mRadius.toFloat() + mLineWith)
lineTo(xPoint, bottom)
lineTo(right, top)
}
mSuccessPathLength = PathMeasure(mSuccessPath, false).length
mSuccessPathIntervals = floatArrayOf(mSuccessPathLength, mSuccessPathLength)
}
private fun createFailedPath() {
if (mFailedPath != null) {
mFailedPath!!.reset()
mFailedPath2!!.reset()
} else {
mFailedPath = Path()
mFailedPath2 = Path()
}
val left = (width / 2 - mRadius + mRadius / 2).toFloat()
val top = mRadius / 2 + mPadding
mFailedPath!!.moveTo(left, top)
mFailedPath!!.lineTo(left + mRadius, top + mRadius)
mFailedPath2!!.moveTo((width / 2 + mRadius / 2).toFloat(), top)
mFailedPath2!!.lineTo((width / 2 - mRadius + mRadius / 2).toFloat(), top + mRadius)
mFailedPathLength = PathMeasure(mFailedPath, false).length
mFailedPathIntervals = floatArrayOf(mFailedPathLength, mFailedPathLength)
mPathEffectPaint2.pathEffect = DashPathEffect(mFailedPathIntervals, mFailedPathLength)
}
private fun measureDimension(defaultSize: Int, measureSpec: Int) =
when (MeasureSpec.getMode(measureSpec)) {
MeasureSpec.EXACTLY -> MeasureSpec.getSize(measureSpec)
MeasureSpec.AT_MOST -> min(defaultSize, MeasureSpec.getSize(measureSpec))
MeasureSpec.UNSPECIFIED -> defaultSize
else -> defaultSize
}
private fun updateButtonColor() {
mPaint.color = if(isEnabled) mColorPrimary else mDisabledBgColor
mTextPaint.color = if(isEnabled) mTextColor else mDisabledTextColor
if(backgroundShader != null){
if(isEnabled) mPaint.shader = backgroundShader else mPaint.shader = null
}
invalidate()
}
private fun playTouchDownAnimation(){
ValueAnimator.ofFloat(0f, 1f)
.apply {
duration = 240
interpolator = AccelerateDecelerateInterpolator()
addUpdateListener { valueAnimator ->
val progress = valueAnimator.animatedValue as Float
mPaint.setShadowDepth((2 + 4 * progress) * mDensity)
mRippleRadius = width * progress
//mRipplePaint.alpha = (255 * mRippleAlpha * (1 - progress)).toInt()
invalidate()
}
}
.start()
}
private fun playRippleAnimation() {
ValueAnimator.ofFloat(
1f,
0f)
.apply {
duration = 240
interpolator = DecelerateInterpolator()
addUpdateListener { valueAnimator ->
val progress = valueAnimator.animatedValue as Float
mRipplePaint.alpha = (255 * mRippleAlpha * progress).toInt()
mPaint.setShadowDepth((2 + 4 * progress) * mDensity)
invalidate()
}
doOnEnd {
doClick()
}
}.start()
}
private fun doClick(){
mTouchX = 0f
mTouchY = 0f
mRipplePaint.alpha = (mRippleAlpha * 255).toInt()
mRippleRadius = 0f
invalidate()
performClick()
}
private fun playStartAnimation(isReverse: Boolean) {
val viewHeight = max(height, mMinHeight.toInt())
val animator = ValueAnimator.ofInt(
if (isReverse) width / 2 - viewHeight / 2 else 0,
if (isReverse) 0 else width / 2 - viewHeight / 2)
.apply {
duration = 400
interpolator = AccelerateDecelerateInterpolator()
startDelay = 100
addUpdateListener { valueAnimator ->
mScaleWidth = valueAnimator.animatedValue as Int
invalidate()
}
doOnEnd {
mCurrentState = if (isReverse) STATE_BUTTON else STATE_ANIMATION_STEP2
if (mCurrentState == STATE_BUTTON) {
mPaint.setShadowDepth(2 * mDensity)
invalidate()
}
}
}
val animator2 = ValueAnimator.ofInt(if (isReverse) mRadius else 0, if (isReverse) 0 else mRadius)
.apply {
duration = 240
interpolator = AccelerateDecelerateInterpolator()
addUpdateListener { valueAnimator ->
mScaleHeight = valueAnimator.animatedValue as Int
invalidate()
}
doOnEnd {
mCurrentState = if (isReverse) STATE_ANIMATION_STEP1 else STATE_ANIMATION_LOADING
if (!isReverse) updateButtonColor()
}
}
val loadingAnimator = ValueAnimator.ofInt(30, 300)
.apply {
duration = 1000
repeatCount = ValueAnimator.INFINITE
repeatMode = ValueAnimator.REVERSE
interpolator = AccelerateDecelerateInterpolator()
addUpdateListener { valueAnimator ->
mAngle = valueAnimator.animatedValue as Int
invalidate()
}
}
mLoadingAnimatorSet?.cancel()
mLoadingAnimatorSet = AnimatorSet()
mLoadingAnimatorSet!!.doOnEnd {
isEnabled = true
updateButtonColor()
}
if (isReverse) {
mLoadingAnimatorSet!!.playSequentially(animator2, animator)
mLoadingAnimatorSet!!.start()
return
}
mLoadingAnimatorSet!!.playSequentially(animator, animator2, loadingAnimator)
mLoadingAnimatorSet!!.start()
}
private fun playSuccessAnimation() {
createSuccessPath()
val animator = ValueAnimator.ofInt(360 - mAngle, 360)
.apply {
duration = 240
interpolator = DecelerateInterpolator()
addUpdateListener { valueAnimator ->
mEndAngle = valueAnimator.animatedValue as Int
invalidate()
}
doOnEnd { mCurrentState = STATE_ANIMATION_SUCCESS }
}
val successAnimator = ValueAnimator.ofFloat(0.0f, 1.0f)
.apply {
duration = 500
interpolator = AccelerateDecelerateInterpolator()
addUpdateListener { valueAnimator ->
val value = valueAnimator.animatedValue as Float
val pathEffect = DashPathEffect(mSuccessPathIntervals, mSuccessPathLength - mSuccessPathLength * value)
mPathEffectPaint.pathEffect = pathEffect
invalidate()
}
}
AnimatorSet().apply {
playSequentially(animator, successAnimator)
doOnEnd {
animationEndAction?.invoke(AnimationType.SUCCESSFUL)
}
}.start()
}
private fun playFailedAnimation() {
createFailedPath()
val animator = ValueAnimator.ofInt(360 - mAngle, 360)
.apply {
duration = 240
interpolator = DecelerateInterpolator()
addUpdateListener { valueAnimator ->
mEndAngle = valueAnimator.animatedValue as Int
invalidate()
}
doOnEnd { mCurrentState = STATE_ANIMATION_FAILED }
}
val failedAnimator = ValueAnimator.ofFloat(0.0f, 1.0f)
.apply {
duration = 300
interpolator = AccelerateDecelerateInterpolator()
addUpdateListener { valueAnimator ->
val value = valueAnimator.animatedValue as Float
mPathEffectPaint.pathEffect = DashPathEffect(mFailedPathIntervals, mFailedPathLength - mFailedPathLength * value)
invalidate()
}
}
val failedAnimator2 = ValueAnimator.ofFloat(0.0f, 1.0f)
.apply {
duration = 300
interpolator = AccelerateDecelerateInterpolator()
addUpdateListener { valueAnimator ->
val value = valueAnimator.animatedValue as Float
mPathEffectPaint2.pathEffect = DashPathEffect(mFailedPathIntervals, mFailedPathLength - mFailedPathLength * value)
invalidate()
}
}
AnimatorSet().apply {
playSequentially(animator, failedAnimator, failedAnimator2)
doOnEnd {
if (resetAfterFailed) {
postDelayed({ scaleFailedPath() }, 1000)
}else{
animationEndAction?.invoke(AnimationType.FAILED)
}
}
}.start()
}
private fun cancel() {
mCurrentState = STATE_STOP_LOADING
ValueAnimator.ofInt(360 - mAngle, 360)
.apply {
duration = 240
interpolator = DecelerateInterpolator()
addUpdateListener { valueAnimator ->
mEndAngle = valueAnimator.animatedValue as Int
invalidate()
}
doOnEnd {
mCurrentState = STATE_ANIMATION_STEP2
playStartAnimation(true)
}
}.start()
}
private fun scaleSuccessPath() {
val scaleMatrix = Matrix()
val viewHeight = max(height, mMinHeight.toInt())
ValueAnimator.ofFloat(1.0f, 0.0f)
.apply {
duration = 300
interpolator = AccelerateDecelerateInterpolator()
addUpdateListener { valueAnimator ->
val value = valueAnimator.animatedValue as Float
scaleMatrix.setScale(value, value, (width / 2).toFloat(), (viewHeight / 2).toFloat())
mSuccessPath!!.transform(scaleMatrix)
invalidate()
}
doOnEnd {
mCurrentState = STATE_ANIMATION_STEP2
playStartAnimation(true)
}
}.start()
}
private fun scaleFailedPath() {
val scaleMatrix = Matrix()
val viewHeight = max(height, mMinHeight.toInt())
ValueAnimator.ofFloat(1.0f, 0.0f)
.apply {
duration = 300
interpolator = AccelerateDecelerateInterpolator()
addUpdateListener { valueAnimator ->
val value = valueAnimator.animatedValue as Float
scaleMatrix.setScale(value, value, (width / 2).toFloat(), (viewHeight / 2).toFloat())
mFailedPath!!.transform(scaleMatrix)
mFailedPath2!!.transform(scaleMatrix)
invalidate()
}
doOnEnd {
mCurrentState = STATE_ANIMATION_STEP2
playStartAnimation(true)
}
}.start()
}
}
private fun Animator.doOnEnd(action: (animator: Animator?) -> Unit) {
this.addListener(object : Animator.AnimatorListener{
override fun onAnimationRepeat(animation: Animator?){}
override fun onAnimationEnd(animation: Animator?) = action(animation)
override fun onAnimationCancel(animation: Animator?){}
override fun onAnimationStart(animation: Animator?){}
})
}
private fun Paint.setShadowDepth(depth: Float){
this.setShadowLayer(depth, 0f, 2f, 0x6F000000.toInt())
} | apache-2.0 | 71693d2465d1a754dab481d276a95220 | 35.2977 | 166 | 0.553667 | 5.686453 | false | false | false | false |
cliffano/swaggy-jenkins | clients/kotlin-spring/generated/src/main/kotlin/org/openapitools/model/Link.kt | 1 | 852 | package org.openapitools.model
import java.util.Objects
import com.fasterxml.jackson.annotation.JsonProperty
import javax.validation.constraints.DecimalMax
import javax.validation.constraints.DecimalMin
import javax.validation.constraints.Email
import javax.validation.constraints.Max
import javax.validation.constraints.Min
import javax.validation.constraints.NotNull
import javax.validation.constraints.Pattern
import javax.validation.constraints.Size
import javax.validation.Valid
import io.swagger.v3.oas.annotations.media.Schema
/**
*
* @param propertyClass
* @param href
*/
data class Link(
@Schema(example = "null", description = "")
@field:JsonProperty("_class") val propertyClass: kotlin.String? = null,
@Schema(example = "null", description = "")
@field:JsonProperty("href") val href: kotlin.String? = null
) {
}
| mit | 647f533182f81273c5c11da402a3e2f8 | 26.483871 | 75 | 0.776995 | 4.096154 | false | false | false | false |
googlearchive/android-Camera2Basic | kotlinApp/Application/src/main/java/com/example/android/camera2basic/ImageSaver.kt | 3 | 1244 | package com.example.android.camera2basic
import android.media.Image
import android.util.Log
import java.io.File
import java.io.FileOutputStream
import java.io.IOException
import java.nio.ByteBuffer
/**
* Saves a JPEG [Image] into the specified [File].
*/
internal class ImageSaver(
/**
* The JPEG image
*/
private val image: Image,
/**
* The file we save the image into.
*/
private val file: File
) : Runnable {
override fun run() {
val buffer = image.planes[0].buffer
val bytes = ByteArray(buffer.remaining())
buffer.get(bytes)
var output: FileOutputStream? = null
try {
output = FileOutputStream(file).apply {
write(bytes)
}
} catch (e: IOException) {
Log.e(TAG, e.toString())
} finally {
image.close()
output?.let {
try {
it.close()
} catch (e: IOException) {
Log.e(TAG, e.toString())
}
}
}
}
companion object {
/**
* Tag for the [Log].
*/
private val TAG = "ImageSaver"
}
}
| apache-2.0 | 2aae39c411eb1d6c472a760d00ad0b3e | 21.618182 | 51 | 0.5 | 4.427046 | false | false | false | false |
google/horologist | media3-backend/src/main/java/com/google/android/horologist/media3/service/NetworkAwareDownloadListener.kt | 1 | 5223 | /*
* 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.media3.service
import android.annotation.SuppressLint
import androidx.media3.exoplayer.offline.Download
import androidx.media3.exoplayer.offline.DownloadManager
import androidx.media3.exoplayer.scheduler.Requirements
import com.google.android.horologist.media3.ExperimentalHorologistMedia3BackendApi
import com.google.android.horologist.media3.logging.ErrorReporter
import com.google.android.horologist.media3.logging.ErrorReporter.Category.Downloads
import com.google.android.horologist.networks.ExperimentalHorologistNetworksApi
import com.google.android.horologist.networks.data.RequestType.MediaRequest
import com.google.android.horologist.networks.data.RequestType.MediaRequest.MediaRequestType
import com.google.android.horologist.networks.highbandwidth.HighBandwidthConnectionLease
import com.google.android.horologist.networks.highbandwidth.HighBandwidthNetworkMediator
import com.google.android.horologist.networks.request.HighBandwidthRequest
import com.google.android.horologist.networks.rules.NetworkingRulesEngine
/**
* Simple implementation of [DownloadManager.Listener] for downloading with
* a required high bandwidth network. Also includes event logging.
*/
@SuppressLint("UnsafeOptInUsageError")
@ExperimentalHorologistMedia3BackendApi
@ExperimentalHorologistNetworksApi
public class NetworkAwareDownloadListener(
private val appEventLogger: ErrorReporter,
private val highBandwidthNetworkMediator: HighBandwidthNetworkMediator,
private val networkingRulesEngine: NetworkingRulesEngine
) : DownloadManager.Listener {
private var networkRequest: HighBandwidthConnectionLease? = null
override fun onInitialized(downloadManager: DownloadManager) {
appEventLogger.logMessage("init", category = Downloads)
updateNetworkState(downloadManager)
}
override fun onDownloadsPausedChanged(
downloadManager: DownloadManager,
downloadsPaused: Boolean
) {
appEventLogger.logMessage("paused $downloadsPaused", category = Downloads)
}
override fun onDownloadChanged(
downloadManager: DownloadManager,
download: Download,
finalException: Exception?
) {
val percent = (download.percentDownloaded).toInt().coerceAtLeast(0)
appEventLogger.logMessage(
"download ${download.request.uri.lastPathSegment} $percent% ${finalException?.message.orEmpty()}",
category = Downloads
)
updateNetworkState(downloadManager)
}
override fun onDownloadRemoved(downloadManager: DownloadManager, download: Download) {
appEventLogger.logMessage("removed ${download.name}", category = Downloads)
}
override fun onIdle(downloadManager: DownloadManager) {
updateNetworkState(downloadManager)
appEventLogger.logMessage("idle", category = Downloads)
}
override fun onRequirementsStateChanged(
downloadManager: DownloadManager,
requirements: Requirements,
notMetRequirements: Int
) {
appEventLogger.logMessage("missingReqs $notMetRequirements", category = Downloads)
}
override fun onWaitingForRequirementsChanged(
downloadManager: DownloadManager,
waitingForRequirements: Boolean
) {
updateNetworkState(downloadManager)
appEventLogger.logMessage(
"waitingForRequirements $waitingForRequirements",
category = Downloads
)
}
private fun updateNetworkState(downloadManager: DownloadManager) {
val hasReadyDownloads =
downloadManager.currentDownloads.isNotEmpty() && !downloadManager.isWaitingForRequirements
if (hasReadyDownloads) {
if (networkRequest == null) {
val types =
networkingRulesEngine.supportedTypes(MediaRequest(MediaRequestType.Download))
val request = HighBandwidthRequest.from(types)
appEventLogger.logMessage(
"Requesting network for downloads $networkRequest",
category = Downloads
)
networkRequest = highBandwidthNetworkMediator.requestHighBandwidthNetwork(request)
}
} else {
if (networkRequest != null) {
appEventLogger.logMessage("Releasing network for downloads", category = Downloads)
networkRequest?.close()
networkRequest = null
}
}
}
private val Download.name: String
get() = this.request.uri.lastPathSegment ?: "unknown"
}
| apache-2.0 | b81c744be2d21df015e1d0626e2fc896 | 38.270677 | 110 | 0.730806 | 5.41805 | false | false | false | false |
google/horologist | compose-layout/src/main/java/com/google/android/horologist/compose/layout/StateUtils.kt | 1 | 1702 | /*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
@file:OptIn(ExperimentalLifecycleComposeApi::class)
package com.google.android.horologist.compose.layout
import androidx.compose.runtime.Composable
import androidx.compose.runtime.State
import androidx.compose.ui.platform.LocalLifecycleOwner
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.compose.ExperimentalLifecycleComposeApi
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import kotlinx.coroutines.flow.StateFlow
public object StateUtils {
@Deprecated(
message = "Replace with collectAsStateWithLifecycle",
replaceWith = ReplaceWith(
"flow.collectAsStateWithLifecycle()",
"androidx.lifecycle.compose.collectAsStateWithLifecycle"
)
)
@Composable
public fun <T> rememberStateWithLifecycle(
flow: StateFlow<T>,
lifecycle: Lifecycle = LocalLifecycleOwner.current.lifecycle,
minActiveState: Lifecycle.State = Lifecycle.State.STARTED
): State<T> = flow.collectAsStateWithLifecycle(
lifecycle = lifecycle,
minActiveState = minActiveState
)
}
| apache-2.0 | 1ff4e48541ccdaccd60b048a8f50b0ef | 36 | 75 | 0.752644 | 4.933333 | false | false | false | false |
artfable/telegram-api-java | src/main/kotlin/com/artfable/telegram/api/request/GetUpdatesRequest.kt | 1 | 1786 | package com.artfable.telegram.api.request
import com.fasterxml.jackson.annotation.JsonProperty
import com.fasterxml.jackson.core.type.TypeReference
import com.artfable.telegram.api.TelegramBotMethod
import com.artfable.telegram.api.TelegramResponse
import com.artfable.telegram.api.Update
import com.artfable.telegram.api.UpdateType
/**
* @author aveselov
* @since 05/08/2020
*/
data class GetUpdatesRequest(
@JsonProperty("offset") val offset: Long? = null,
@JsonProperty("timeout") val timeout: Int? = null,
@JsonProperty("limit") val limit: Int? = null,
@JsonProperty("allowed_updates") val allowedUpdates: Array<UpdateType>? = null
) : TelegramRequest<@JvmSuppressWildcards List<Update>>(
TelegramBotMethod.GET_UPDATES,
object : TypeReference<TelegramResponse<List<Update>>>() {}) {
init {
timeout?.let { check(it >= 0) }
limit?.let { check(it in 1..100) }
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as GetUpdatesRequest
if (offset != other.offset) return false
if (timeout != other.timeout) return false
if (limit != other.limit) return false
if (allowedUpdates != null) {
if (other.allowedUpdates == null) return false
if (!allowedUpdates.contentEquals(other.allowedUpdates)) return false
} else if (other.allowedUpdates != null) return false
return true
}
override fun hashCode(): Int {
var result = offset?.hashCode() ?: 0
result = 31 * result + (timeout ?: 0)
result = 31 * result + (limit ?: 0)
result = 31 * result + (allowedUpdates?.contentHashCode() ?: 0)
return result
}
}
| mit | 9cbe5b180c2effc0cfded175a1ba7dfe | 34.019608 | 82 | 0.660694 | 4.31401 | false | false | false | false |
yyued/CodeX-UIKit-Android | library/src/main/java/com/yy/codex/uikit/UITableViewCell_Editing.kt | 1 | 3992 | package com.yy.codex.uikit
import android.content.Context
import android.view.MotionEvent
import com.yy.codex.foundation.lets
/**
* Created by cuiminghui on 2017/3/9.
*/
internal fun UITableViewCell._initEditingTouches() {
val editingPanGesture = UIPanGestureRecognizer(this, "onEditingPanned:")
this._editingPanGesture = editingPanGesture
editingPanGesture.stealer = true
editingPanGesture.delegate = object : UIGestureRecognizer.Delegate {
override fun shouldBegin(gestureRecognizer: UIGestureRecognizer): Boolean {
return Math.abs((gestureRecognizer as UIPanGestureRecognizer).translation().y) < 8.0
}
}
addGestureRecognizer(editingPanGesture)
}
internal fun UITableViewCell._initEditingView() {
_editingView = UITableViewCellActionView(context)
}
internal fun UITableViewCell._enableEditingView() {
_editingPanGesture?.enabled = false
_editingView.clearViews()
lets(_tableView, _indexPath) { tableView, indexPath ->
tableView.delegate()?.editActionsForRow(tableView, indexPath)?.let {
_editingPanGesture?.enabled = it.size > 0
}
}
}
internal fun UITableViewCell._resetEditingView() {
_editingView.clearViews()
lets(_tableView, _indexPath) { tableView, indexPath ->
tableView.delegate()?.editActionsForRow(tableView, indexPath)?.let {
_editingView.resetViews(it.map {
return@map it.requestActionView(context, indexPath)
})
}
}
}
internal fun UITableViewCell._onEditingPanned(sender: UIPanGestureRecognizer) {
when (sender.state) {
UIGestureRecognizerState.Began -> {
_resetEditingView()
}
UIGestureRecognizerState.Changed -> {
layoutSubviews()
}
UIGestureRecognizerState.Ended, UIGestureRecognizerState.Cancelled, UIGestureRecognizerState.Failed -> {
editing = _editingPanGesture?.velocity()?.x ?: 0.0 < 80.0 && (_editingPanGesture?.velocity()?.x ?: 0.0 < -200.0 || -Math.ceil(_editingPanGesture?.translation()?.x ?: 0.0) > _editingView.contentWidth * 2 / 3)
UIViewAnimator.springWithBounciness(1.0, 20.0, Runnable { _updateFrames() }, null)
if (editing) {
val maskView = UITableViewCellActionMaskView(context)
maskView.addGestureRecognizer(UITapGestureRecognizer(this, "_endEditing"))
maskView.touchesView = _editingView
maskView.frame = _tableView?.frame ?: CGRect(0, 0, 0, 0)
_tableView?.superview?.addSubview(maskView)
this._editingMaskView = maskView
}
}
}
}
internal class UITableViewCellActionView(context: Context) : UIView(context) {
var contentWidth = 0.0
fun clearViews() {
subviews.forEach(UIView::removeFromSuperview)
}
fun resetViews(views: List<UITableViewRowActionView>) {
views.forEach {
addSubview(it)
}
contentWidth = views.sumByDouble { it.contentWidth }
}
override fun layoutSubviews() {
super.layoutSubviews()
if (contentWidth <= 0.0) {
return
}
val percentage = frame.width / contentWidth
var currentX = 0.0
subviews.forEachIndexed { idx, subview ->
val subview = (subview as? UITableViewRowActionView) ?: return@forEachIndexed
subview.frame = CGRect(currentX, 0.0, subview.contentWidth * percentage + 1.0, frame.height)
currentX += subview.contentWidth * percentage
}
}
}
private class UITableViewCellActionMaskView(context: Context): UIView(context) {
internal var touchesView: UIView? = null
override fun hitTest(point: CGPoint, event: MotionEvent): UIView? {
touchesView?.let {
if (UIViewHelpers.pointInside(it, this.convertPoint(point, it))) {
return null
}
}
return super.hitTest(point, event)
}
} | gpl-3.0 | 44277a27bffc24bbaf1ea67aee5208da | 33.721739 | 219 | 0.65005 | 4.780838 | false | false | false | false |
vsch/idea-multimarkdown | src/main/java/com/vladsch/md/nav/actions/handlers/util/ListItemContext.kt | 1 | 29164 | // Copyright (c) 2015-2020 Vladimir Schneider <[email protected]> Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.vladsch.md.nav.actions.handlers.util
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.editor.LogicalPosition
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
import com.vladsch.flexmark.util.sequence.RepeatedSequence
import com.vladsch.md.nav.actions.api.MdElementContextInfoProvider
import com.vladsch.md.nav.psi.element.*
import com.vladsch.md.nav.psi.util.BlockPrefixes
import com.vladsch.md.nav.psi.util.MdPsiImplUtil
import com.vladsch.md.nav.psi.util.MdPsiImplUtil.isWhitespaceOrBlankLine
import com.vladsch.md.nav.psi.util.MdTokenSets
import com.vladsch.md.nav.psi.util.MdTypes
import com.vladsch.md.nav.settings.ListIndentationType
import com.vladsch.md.nav.settings.MdRenderingProfileManager
import com.vladsch.md.nav.util.format.MdFormatter
import com.vladsch.plugin.util.maxLimit
import com.vladsch.plugin.util.minLimit
import com.vladsch.plugin.util.psi.isTypeIn
import com.vladsch.plugin.util.psi.isTypeOf
import com.vladsch.plugin.util.toBased
import java.util.*
open class ListItemContext(
val context: CaretContextInfo,
val listElement: MdListImpl,
val listItemElement: MdListItemImpl,
val lineOffset: Int,
val isEmptyItem: Boolean,
val isTaskItem: Boolean,
val isItemDone: Boolean,
val wrappingContext: WrappingContext
) {
fun canIndentItem(): Boolean {
if (isNonFirstListItem()) return true
// see if it preceded by a list item
val listElement = listElement
val listLevel = getListLevel(listElement)
var prevSibling = listElement.prevSibling
while (prevSibling != null && isWhitespaceOrBlankLine(prevSibling.node.elementType)) prevSibling = prevSibling.prevSibling
while (prevSibling != null && prevSibling !is PsiFile && prevSibling.node.elementType !in listOf(MdTypes.BULLET_LIST, MdTypes.ORDERED_LIST)) {
prevSibling = prevSibling.parent
}
if (prevSibling == null || prevSibling is PsiFile) return false
if (prevSibling.javaClass != listElement.javaClass) {
// see if common mark where list types must match
val profile = MdRenderingProfileManager.getProfile(listElement.containingFile)
if (profile.parserSettings.parserListIndentationType == ListIndentationType.COMMONMARK) {
return false
}
}
val prevListLevel = getListLevel(prevSibling)
return prevListLevel >= listLevel
}
fun canUnIndentItem(): Boolean {
return isNonFirstLevelList()
}
fun isNonFirstLevelList(): Boolean {
var element = listElement.parent ?: return false
while (!(element is MdList)) {
if (element is PsiFile || element.node == null) return false
element = element.parent ?: return false
}
return element.isTypeOf(MdTokenSets.LIST_ELEMENT_TYPES)
}
fun isNonFirstListItem(): Boolean {
val listItemElement = listItemElement
val listElement = listElement
return listElement.firstChild !== listItemElement
}
open fun indentItem(adjustCaret: Boolean, onlyEmptyItemLine: Boolean) {
if (!canIndentItem()) return
// need to take all its contents and indent
val list = listElement
val listItem = listItemElement
val prefixes = MdPsiImplUtil.getBlockPrefixes(list, null, context)
val caretLineInItem = context.caretLine - wrappingContext.firstLine
// indent this item by inserting 4 spaces for it and all its elements and changing its number to 1
val itemLines = MdPsiImplUtil.linesForWrapping(listItem, true, true, true, context)
var caretDelta = 0
var linesAdded = 0
// see if we need to insert a blank line before, if the previous item's last child is not the first indenting and not blank line
val prevSibling = context.findElementAt(context.offsetLineStart(listItem.node.startOffset)!! - 1)
if (prevSibling != null && !MdPsiImplUtil.isPrecededByBlankLine(listItem)) {
var blockElement = MdPsiImplUtil.getBlockElement(listItem)
if (blockElement != null && blockElement.node.elementType == MdTypes.PARAGRAPH_BLOCK) {
if (blockElement == MdPsiImplUtil.findChildTextBlock(blockElement.parent)?.parent) blockElement = blockElement.parent
}
if (blockElement !is MdListItemImpl) {
// add a blank line
if (blockElement == null || !MdPsiImplUtil.isFollowedByBlankLine(blockElement)) {
itemLines.insertLine(0, itemLines[0].prefix, "")
linesAdded++
}
}
}
val prevListItem = prevListItem(list, listItem) ?: listItem
val listItemPrefixes = (prevListItem as MdListItemImpl).itemPrefixes(prefixes, context)
val prefixedLines = itemLines.copyAppendable()
MdPsiImplUtil.addLinePrefix(prefixedLines, listItemPrefixes.childPrefix, listItemPrefixes.childContPrefix)
// adjust for prefix change
// add 1 char for every \n added, plus one prefix for every line added plus one prefix change for every additional line caret is offset from the first line
val prefixChange = prefixedLines[0].prefixLength - itemLines[0].prefixLength
caretDelta += linesAdded + (linesAdded * listItemPrefixes.childPrefix.length) + prefixChange * (caretLineInItem + 1)
// need to adjust the replaced end to include the EOL, if not done for empty task items this causes an extra \n to be left in the document
val postEditNodeEnd = context.postEditNodeEnd(listItem.node)
val virtualSpaces = context.editor.caretModel.logicalPosition.column - (context.caretOffset - context.document.getLineStartOffset(context.document.getLineNumber(context.caretOffset)))
var endDelta = 0
while (postEditNodeEnd + endDelta < context.document.textLength && !context.document.charsSequence.subSequence(context.offsetLineStart(context.postEditNodeStart(listItem.node))!!, postEditNodeEnd + endDelta).endsWith("\n")) {
endDelta++
}
// need to insert trailing spaces after an empty list item
if (isEmptyItem) {
val trailingSpaces = context.beforeCaretChars.toBased().countTrailingSpaceTab()
if (trailingSpaces > 0) {
prefixedLines.setLine(0, prefixedLines[0].prefix, prefixedLines[0].text.append(RepeatedSequence.ofSpaces(trailingSpaces)))
}
}
context.document.replaceString(context.offsetLineStart(context.postEditNodeStart(listItem.node))!!, postEditNodeEnd + endDelta, prefixedLines.toString(1, 1))
val caretOffset = context.adjustedDocumentPosition((context.caretOffset + caretDelta).maxLimit(context.charSequence.length))
if (adjustCaret) {
if (endDelta > 0 || virtualSpaces > 0) {
// adjust for any trailing spaces after the marker that were removed for an empty item
val pos = context.editor.offsetToLogicalPosition(caretOffset.adjustedOffset - (endDelta - 1).minLimit(0))
context.editor.caretModel.moveToLogicalPosition(LogicalPosition(pos.line, pos.column + (endDelta - 1).minLimit(0) + virtualSpaces))
} else {
// System.out.println("Adjusting: change $prefixChange, line $caretLineInItem, caretDelta $caretDelta")
context.editor.caretModel.moveToOffset(caretOffset.adjustedOffset)
}
}
}
// this will make this item the next after the parent list item
open fun unIndentItem(adjustCaret: Boolean, onlyEmptyItemLine: Boolean) {
if (!canUnIndentItem()) return
val list = listElement
val listItem = listItemElement
val parentListItem = getParentListItemElement(list)
val parentList = if (parentListItem != null) getParentListElement(parentListItem) else null
val parentPrefixes = if (parentList != null) MdPsiImplUtil.getBlockPrefixes(parentList, null, context) else BlockPrefixes.EMPTY
val caretLineInItem = context.caretLine - wrappingContext.firstLine
// un indent this item by inserting the previous parent's prefix
val itemLines = MdPsiImplUtil.linesForWrapping(listItem, true, true, true, context)
var caretDelta = 0
val linesAdded = 0
val prefixedLines = itemLines.copyAppendable()
MdPsiImplUtil.addLinePrefix(prefixedLines, parentPrefixes.childPrefix, parentPrefixes.childContPrefix)
// adjust for prefix change
// add 1 char for every \n added, plus one prefix for every line added plus one prefix change for every additional line caret is offset from the first line
val prefixChange = prefixedLines[0].prefixLength - itemLines[0].prefixLength
caretDelta += linesAdded + (linesAdded * parentPrefixes.childPrefix.length) + prefixChange * (caretLineInItem + 1)
// need to adjust the replaced end to include the EOL, if not done for empty task items this causes an extra \n to be left in the document
val postEditNodeEnd = context.postEditNodeEnd(listItem.node)
val virtualSpaces = context.editor.caretModel.logicalPosition.column - (context.caretOffset - context.document.getLineStartOffset(context.document.getLineNumber(context.caretOffset)))
var endDelta = 0
while (postEditNodeEnd + endDelta < context.document.textLength && !context.document.charsSequence.subSequence(context.offsetLineStart(context.postEditNodeStart(listItem.node))!!, postEditNodeEnd + endDelta).endsWith("\n")) {
endDelta++
}
context.document.replaceString(context.offsetLineStart(context.postEditNodeStart(listItem.node))!!, postEditNodeEnd + endDelta, prefixedLines.toString(1, 1))
val caretOffset = context.adjustedDocumentPosition((context.caretOffset + caretDelta).minLimit(0))
if (adjustCaret) {
if (endDelta > 0 || virtualSpaces > 0) {
// adjust for any trailing spaces after the marker that were removed for an empty item
val pos = context.editor.offsetToLogicalPosition(caretOffset.adjustedOffset - (endDelta - 1).minLimit(0))
context.editor.caretModel.moveToLogicalPosition(LogicalPosition(pos.line, pos.column + (endDelta - 1).minLimit(0) + virtualSpaces))
} else {
context.editor.caretModel.moveToOffset(caretOffset.adjustedOffset)
}
}
}
open fun addItem(adjustCaret: Boolean, removeDoneMarker: Boolean) {
val startLineOffset = context.offsetLineStart(context.caretOffset)
val endLineOffset = context.offsetLineEnd(context.caretOffset)
val list = listElement
if (startLineOffset != null && endLineOffset != null) {
val listItem = listItemElement
val prefixes = MdPsiImplUtil.getBlockPrefixes(list, null, context)
val prefix = prefixes.childPrefix
// take the prefix from wrapping context
val itemOnlyPrefix = listItem.actualTextPrefix(context, true).toString()
var itemPrefix = prefix.toString() + itemOnlyPrefix //wrappingContext.prefixText().toString()
if (removeDoneMarker) {
val taskMarkerPos = itemPrefix.toLowerCase().indexOf("[x]")
if (taskMarkerPos > 0) {
// replace by not completed task
itemPrefix = itemPrefix.substring(0, taskMarkerPos + 1) + " " + itemPrefix.substring(taskMarkerPos + 2)
}
}
// if prefix was inserted then it will have not just whitespace
var lastPos = startLineOffset
LOG.debug("replacing start of line prefix: '${context.charSequence.subSequence(lastPos, endLineOffset)}' with: '$itemPrefix'")
while (lastPos < endLineOffset) {
val c = context.charSequence[lastPos]
if (!(c.isWhitespace() || context.isIndentingChar(c))) break
lastPos++
}
context.document.replaceString(startLineOffset, lastPos, itemPrefix)
val prefixLength = itemPrefix.length
val caretOffset = context.adjustedDocumentPosition(startLineOffset + prefixLength)
if (adjustCaret) {
context.editor.caretModel.currentCaret.moveToOffset(caretOffset.adjustedOffset)
}
}
}
open fun removeItem(adjustCaret: Boolean, willBackspace: Boolean) {
val list = listElement
val listItem = listItemElement
val listMarkerNode = listItem.firstChild.node
val startLineOffset = context.offsetLineStart(context.caretOffset)
if (startLineOffset != null) {
val prefixes = MdPsiImplUtil.getBlockPrefixes(list, null, context)
val prefix = prefixes.childPrefix
var replacePrefix = if (willBackspace) " " else ""
var adjustCaretOffset = if (willBackspace) 1 else 0
val nodeStartOffset = context.postEditNodeStart(listMarkerNode)
val lastMarkerNode = MdPsiImplUtil.nextNonWhiteSpaceSibling(listMarkerNode) ?: listMarkerNode
val nodeEndOffset = context.postEditNodeEnd(lastMarkerNode)
// see if we need to insert a blank line before, if the previous item's last child is not the first indenting and not blank line
if (!isEmptyItem) {
val prevSibling = context.findElementAt(context.offsetLineStart(listItem.node.startOffset)!! - 1)
if (prevSibling != null) {
if (prevSibling !is MdBlankLine) {
val blockElement = MdPsiImplUtil.getBlockElement(prevSibling)
if (blockElement == null || !MdPsiImplUtil.isFollowedByBlankLine(blockElement)) {
// add a blank line
replacePrefix = "\n" + prefix + replacePrefix
adjustCaretOffset += prefix.length + 1
}
}
}
// see if we need to insert a blank line after, if the item's last child is not the first indenting and not blank line
val nextSibling = listItem.nextSibling
if (nextSibling !is MdBlankLine) {
if (listItem.children.size > 1) {
val childBlockElement = MdPsiImplUtil.getBlockElement(listItem.lastChild)
if (childBlockElement != null && !MdPsiImplUtil.isFollowedByBlankLine(childBlockElement)) {
val blockEndOffset = context.postEditNodeEnd(childBlockElement.node)
context.document.insertString(blockEndOffset, prefix.toString() + "\n")
}
}
// add a blank line after the paragraph or text
val blockElement = MdPsiImplUtil.findChildTextBlock(listItem)
if (blockElement != null && !MdPsiImplUtil.isFollowedByBlankLine(blockElement)) {
val blockEndOffset = context.postEditNodeEnd(blockElement.node)
context.document.insertString(blockEndOffset, prefix.toString() + "\n")
}
}
context.document.replaceString(nodeStartOffset, if (willBackspace) context.wrappingContext?.firstPrefixEnd
?: nodeEndOffset else nodeEndOffset, replacePrefix)
} else {
context.document.replaceString(nodeStartOffset, if (willBackspace) context.wrappingContext?.firstPrefixEnd
?: nodeEndOffset else nodeEndOffset, replacePrefix + if (willBackspace) "" else "\n")
}
val caretOffset = context.adjustedDocumentPosition(nodeStartOffset)
if (adjustCaret) {
context.editor.caretModel.currentCaret.moveToOffset(caretOffset.adjustedOffset + adjustCaretOffset)
}
}
}
companion object {
private val LOG = Logger.getInstance("com.vladsch.md.nav.editor.handlers.list")
@JvmField
val TRACE_LIST_ITEM_EDIT: Boolean = false
@JvmStatic
fun getContext(context: CaretContextInfo, preEditListItemElement: PsiElement? = null): ListItemContext? {
val caretOffset = context.caretOffset
var caretLine = context.offsetLineNumber(context.preEditOffset(caretOffset))!!
var useContext = context
if (MdPsiImplUtil.isBlankLine(context.findElementAt(caretOffset))) {
// go up to non blank and check
while (caretLine > 0) {
caretLine--
val startIndex = context.lineStart(caretLine)
val endIndex = context.lineEnd(caretLine)
if (startIndex != null && endIndex != null && startIndex < endIndex) {
if (!MdPsiImplUtil.isBlankLine(context.file.findElementAt(endIndex - 1))) {
// can find start here
useContext = CaretContextInfo.subContext(context, endIndex)
break
}
}
if (context.caretLine - caretLine > 1) return null
}
}
val wrappingContext = useContext.wrappingContext?.withMainListItem(context, preEditListItemElement) ?: return null
if (wrappingContext.mainElement is MdListItem) {
if (wrappingContext.mainElement === preEditListItemElement || wrappingContext.formatElement == null || MdPsiImplUtil.isFirstIndentedBlock(wrappingContext.formatElement, false)) {
val nextSibling = MdPsiImplUtil.nextNonWhiteSpaceSibling(wrappingContext.mainElement.firstChild.node)
val isTaskItem = nextSibling.isTypeIn(MdTokenSets.TASK_LIST_ITEM_MARKERS)
val isItemDone = isTaskItem && nextSibling != null && nextSibling.elementType != MdTypes.TASK_ITEM_MARKER
val listElement = getParentListElement(wrappingContext.mainElement) as MdListImpl?
val listItemElement = wrappingContext.mainElement as? MdListItemImpl
if (listElement != null && listItemElement != null) {
return MdElementContextInfoProvider.PROVIDER.value.getListItemContext(context,
listElement,
listItemElement,
context.caretLine - caretLine,
wrappingContext.startOffset == wrappingContext.endOffset,
isTaskItem,
isItemDone,
wrappingContext)
}
}
}
return null
}
@JvmStatic
fun lastListItem(list: PsiElement): MdListItemImpl? {
var childListItem = list.lastChild
while (childListItem != null && childListItem !is MdListItemImpl) childListItem = childListItem.prevSibling
return childListItem as? MdListItemImpl
}
@JvmStatic
fun listItemCount(list: PsiElement?): Int {
var items = 0
if (list != null) {
for (child in list.children) {
if (child is MdListItemImpl) items++
}
}
return items
}
fun getParentListElement(listItem: PsiElement): PsiElement? {
var element = listItem
while (element !is MdList) {
element = element.parent ?: return null
if (element is PsiFile || element.node == null) return null
}
return element
}
fun getParentListItemElement(list: PsiElement): PsiElement? {
var element = list.parent ?: return null
while (element !is MdListItem) {
element = element.parent ?: return null
if (element is PsiFile || element.node == null) return null
}
return element
}
fun prevListItem(list: PsiElement, listItem: PsiElement): PsiElement? {
var prevListItem: PsiElement? = null
for (item in list.children) {
if (item === listItem) break
if (item is MdListItem) prevListItem = item
}
return prevListItem
}
fun getListLevel(listElement: PsiElement): Int {
@Suppress("NAME_SHADOWING")
var listElement = listElement
var listLevel = 0
while (listElement !is PsiFile) {
if (listElement is MdList) listLevel++
listElement = listElement.parent ?: break
}
return listLevel
}
enum class AddBlankLineType(val addBefore: Boolean, val addAfter: Boolean) {
NONE(false, false), AFTER(false, true), BEFORE(true, false), AROUND(true, true)
}
@JvmStatic
fun loosenListItems(listElement: PsiElement, listItems: Set<PsiElement>? = null, maxWanted: Int = Int.MAX_VALUE): Pair<List<AddBlankLineType>, Int> {
val result = ArrayList<AddBlankLineType>()
val listItemCount = listItemCount(listElement)
var listItemOrdinal = 0
var state = 0
if (listItemCount < 2 || listElement !is MdList) {
result.add(AddBlankLineType.NONE)
return Pair(result, state)
}
for (item in listElement.children) {
if (item !is MdListItem) {
continue
}
var addBlankLineType = AddBlankLineType.NONE
if (listItems == null || listItems.contains(item)) {
if (!(item.nextSibling == null || item.nextSibling.isTypeOf(MdTokenSets.BLANK_LINE_SET)) && !MdPsiImplUtil.isFollowedByBlankLine(item)) {
if (listItemOrdinal == listItemCount - 1) {
if (listElement.parent is MdListItem) {
} else {
addBlankLineType = AddBlankLineType.AFTER
}
} else {
addBlankLineType = AddBlankLineType.AFTER
}
}
if (listItemOrdinal == 0 && MdFormatter.listNeedsBlankLineBefore(listElement, null, false)) {
val startOffset = item.node.startOffset
if (startOffset > 0) {
if (!addBlankLineType.addAfter) addBlankLineType = AddBlankLineType.BEFORE
else addBlankLineType = AddBlankLineType.AROUND
}
}
result.add(addBlankLineType)
if (addBlankLineType.addAfter) ++state
if (addBlankLineType.addBefore) ++state
if (state >= maxWanted) return Pair(result, state)
}
listItemOrdinal++
}
return Pair(result, state)
}
@JvmStatic
fun tightenListItems(listElement: PsiElement, listItems: Set<PsiElement>? = null, maxWanted: Int = Int.MAX_VALUE): Pair<List<PsiElement>, Int> {
val result = ArrayList<PsiElement>()
val listItemCount = listItemCount(listElement)
var listItemOrdinal = 0
var state = 0
if (listItemCount < 2 || listElement !is MdList) {
return Pair(result, state)
}
loopFor@
for (item in listElement.children) {
if (item !is MdListItem) {
continue
}
if (listItems == null || listItems.contains(item)) {
if (listItemOrdinal == 0 && MdPsiImplUtil.parentSkipBlockQuote(listElement) is MdListItem && !MdFormatter.listNeedsBlankLineBefore(listElement, null, true)) {
val prevSibling = MdPsiImplUtil.prevNonWhiteSpaceSibling(item.prevSibling)
if (prevSibling is MdParagraph) {
// see if this is our parent item paragraph
val parent = listElement.parent
if (parent is MdListItem) {
if (parent.isFirstItemBlock(prevSibling)) {
var blankLine = MdPsiImplUtil.precedingBlankLine(item)
val index = result.size
while (blankLine != null) {
result.add(index, blankLine)
state++
if (state >= maxWanted) break@loopFor
blankLine = MdPsiImplUtil.precedingBlankLine(blankLine)
}
}
}
}
}
if (listItemOrdinal != listItemCount - 1) {
var blankLine = MdPsiImplUtil.followingBlankLine(item)
while (blankLine != null) {
result.add(blankLine)
state++
if (state >= maxWanted) break@loopFor
blankLine = MdPsiImplUtil.followingBlankLine(blankLine)
}
}
}
listItemOrdinal++
}
return Pair(result, state)
}
@JvmStatic
fun canTightenList(listElement: PsiElement, listItems: Set<PsiElement>? = null): Boolean {
return listItemCount(listElement) > 1 && tightenListItems(listElement, listItems, 1).second > 0
}
@JvmStatic
fun canLoosenList(listElement: PsiElement, listItems: Set<PsiElement>? = null): Boolean {
return listItemCount(listElement) > 1 && loosenListItems(listElement, listItems, 1).second > 0
}
@JvmStatic
fun isLooseList(listElement: PsiElement, listItems: Set<PsiElement>? = null): Boolean {
return !canTightenList(listElement, listItems)
}
@JvmStatic
fun isTightList(listElement: PsiElement, listItems: Set<PsiElement>? = null): Boolean {
return !canLoosenList(listElement, listItems)
}
@JvmStatic
fun makeLooseList(context: CaretContextInfo, listElement: PsiElement, listItems: Set<PsiElement>?) {
val caretOffset = context.adjustedDocumentPosition(context.caretOffset)
val prefixes = MdPsiImplUtil.getBlockPrefixes(listElement, null, context)
val (itemList, _) = loosenListItems(listElement, listItems)
val children = listElement.children
var i = listItems?.size ?: listItemCount(listElement)
for (item in children.reversed()) {
if (item !is MdListItemImpl || listItems != null && !listItems.contains(item)) continue
val insertType = itemList[--i]
if (insertType.addAfter) {
context.document.insertString(context.postEditNodeEnd(item.node), prefixes.childPrefix.toString() + "\n")
}
if (insertType.addBefore) {
context.document.insertString(context.offsetLineStart(context.postEditNodeStart(item.node))!!, prefixes.childPrefix.toString() + "\n")
}
}
context.editor.caretModel.moveToOffset(caretOffset.adjustedOffset)
}
@JvmStatic
fun makeTightList(context: CaretContextInfo, listElement: PsiElement, listItems: Set<PsiElement>?) {
val (blankLines, _) = tightenListItems(listElement, listItems)
val caretOffset = context.adjustedDocumentPosition(context.caretOffset)
for (line in blankLines.reversed()) {
val startOffset = line.node.startOffset
val endOffset = startOffset + line.node.textLength
context.document.deleteString(startOffset, endOffset.maxLimit(context.charSequence.length))
}
context.editor.caretModel.moveToOffset(caretOffset.adjustedOffset)
}
fun listItemOrdinal(list: PsiElement, listItem: PsiElement): Int {
var listItemOrdinal = 0
for (item in list.children) {
if (item !is MdListItem) continue
listItemOrdinal++
if (item === listItem) break
}
return listItemOrdinal
}
}
}
| apache-2.0 | 11eaa552d8aa7df5756637b343cc2b1e | 48.430508 | 233 | 0.611404 | 5.623602 | false | false | false | false |
alygin/intellij-rust | src/main/kotlin/org/rust/ide/annotator/RsImplsLineMarkerProvider.kt | 1 | 2528 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.ide.annotator
import com.intellij.codeInsight.daemon.LineMarkerInfo
import com.intellij.codeInsight.daemon.LineMarkerProvider
import com.intellij.codeInsight.navigation.NavigationGutterIconBuilder
import com.intellij.openapi.util.NotNullLazyValue
import com.intellij.psi.PsiElement
import com.intellij.util.Query
import org.rust.ide.icons.RsIcons
import org.rust.lang.core.psi.RsEnumItem
import org.rust.lang.core.psi.RsImplItem
import org.rust.lang.core.psi.RsStructItem
import org.rust.lang.core.psi.RsTraitItem
import org.rust.lang.core.psi.ext.searchForImplementations
import org.rust.lang.core.psi.ext.union
/**
* Annotates trait declaration with an icon on the gutter that allows to jump to
* its implementations.
*
* See [org.rust.ide.navigation.goto.RsImplsSearch]
*/
class RsImplsLineMarkerProvider : LineMarkerProvider {
override fun getLineMarkerInfo(element: PsiElement): LineMarkerInfo<PsiElement>? = null
override fun collectSlowLineMarkers(elements: List<PsiElement>, result: MutableCollection<LineMarkerInfo<PsiElement>>) {
for (el in elements) {
val (query, anchor) = implsQuery(el) ?: continue
val targets: NotNullLazyValue<Collection<PsiElement>> = NotNullLazyValue.createValue { query.findAll() }
val info = NavigationGutterIconBuilder
.create(RsIcons.IMPLEMENTED)
.setTargets(targets)
.setPopupTitle("Go to implementation")
.setTooltipText("Has implementations")
.createLineMarkerInfo(anchor)
result.add(info)
}
}
companion object {
fun implsQuery(psi: PsiElement): Pair<Query<RsImplItem>, PsiElement>? {
val (query, anchor) = when (psi) {
is RsTraitItem -> psi.searchForImplementations() to psi.trait
is RsStructItem -> psi.searchForImplementations() to (psi.struct ?: psi.union)!!
is RsEnumItem -> psi.searchForImplementations() to psi.enum
else -> return null
}
// Ideally, we want to avoid showing an icon if there are no implementations,
// but that might be costly. To save time, we always show an icon, but calculate
// the actual icons only when the user clicks it.
// if (query.isEmptyQuery) return null
return query to anchor
}
}
}
| mit | 79157041c37cdda902d1d2422096baa8 | 39.126984 | 124 | 0.687896 | 4.655617 | false | false | false | false |
macleod2486/AndroidSwissKnife | app/src/main/java/com/macleod2486/androidswissknife/components/NFCTool.kt | 1 | 3157 | /*
AndroidSwissKnife
Copyright (C) 2016 macleod2486
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see [http://www.gnu.org/licenses/].
*/
package com.macleod2486.androidswissknife.components
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.nfc.NfcAdapter
import android.nfc.NfcManager
import android.nfc.tech.Ndef
import androidx.fragment.app.FragmentActivity
import android.util.Log
import android.view.View
import android.widget.EditText
import android.widget.Toast
import com.macleod2486.androidswissknife.R
class NFCTool(var activity: FragmentActivity) : View.OnClickListener {
lateinit var manager: NfcManager
lateinit var adapter: NfcAdapter
lateinit var entryText: EditText
override fun onClick(view: View) {
Log.i("NFCTool", "Clicked")
manager = activity.getSystemService(Context.NFC_SERVICE) as NfcManager
adapter = manager.defaultAdapter
if (view.id == R.id.writeNFC) {
adapter.disableForegroundDispatch(activity)
Log.i("NFCTool", "Writing")
write()
}
if (view.id == R.id.clearText) {
Log.i("NFCTool", "Clearing text")
entryText = activity.findViewById<View>(R.id.textEntry) as EditText
entryText.setText("")
}
}
private fun write() {
Log.i("NFCTool", "Write")
entryText = activity.findViewById<View>(R.id.textEntry) as EditText
setUpWrite(entryText.text.toString())
}
private fun setUpWrite(message: String) {
Log.i("NFCTool", "Message received $message")
val nfcIntent = Intent(activity.applicationContext, NFCActivity::class.java)
nfcIntent.putExtra("NFCMode", "write")
nfcIntent.putExtra("NFCMessage", message)
nfcIntent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP)
val pendingIntent = PendingIntent.getActivity(activity, 0, nfcIntent, 0)
val filter = IntentFilter()
filter.addAction(NfcAdapter.ACTION_TAG_DISCOVERED)
filter.addAction(NfcAdapter.ACTION_NDEF_DISCOVERED)
filter.addAction(NfcAdapter.ACTION_TECH_DISCOVERED)
val filterArray = arrayOf(filter)
val techListsArray = arrayOf(arrayOf(Ndef::class.java.name), arrayOf(Ndef::class.java.name))
adapter.disableReaderMode(activity)
adapter.enableForegroundDispatch(activity, pendingIntent, filterArray, techListsArray)
Toast.makeText(activity, "Please scan tag with device.", Toast.LENGTH_LONG).show()
}
} | gpl-3.0 | 8dfed6a926a092cde6b670c3c084453c | 40.012987 | 100 | 0.711435 | 4.503566 | false | false | false | false |
charlesmadere/smash-ranks-android | smash-ranks-android/app/src/main/java/com/garpr/android/extensions/ContextExt.kt | 1 | 2331 | package com.garpr.android.extensions
import android.app.Activity
import android.app.ActivityManager
import android.app.NotificationManager
import android.content.Context
import android.content.ContextWrapper
import android.content.res.Resources
import android.graphics.drawable.Drawable
import android.view.inputmethod.InputMethodManager
import androidx.annotation.AttrRes
import androidx.annotation.ColorInt
import androidx.annotation.DrawableRes
import androidx.core.app.NotificationManagerCompat
import androidx.core.content.ContextCompat
val Context.activity: Activity?
get() {
if (this is Activity) {
return this
}
if (this is ContextWrapper) {
var context = this
do {
context = (context as ContextWrapper).baseContext
if (context is Activity) {
return context
}
} while (context is ContextWrapper)
}
return null
}
val Context.activityManager: ActivityManager
get() = getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
@ColorInt
@Throws(Resources.NotFoundException::class)
fun Context.getAttrColor(@AttrRes attrResId: Int): Int {
val attrs = intArrayOf(attrResId)
val ta = obtainStyledAttributes(attrs)
if (!ta.hasValue(0)) {
ta.recycle()
throw Resources.NotFoundException("unable to find resId ($attrResId): " +
resources.getResourceEntryName(attrResId))
}
val color = ta.getColor(0, 0)
ta.recycle()
return color
}
val Context.inputMethodManager: InputMethodManager
get() = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
val Context.notificationManager: NotificationManager
get() = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
val Context.notificationManagerCompat: NotificationManagerCompat
get() = NotificationManagerCompat.from(this)
fun Context.requireActivity(): Activity {
return checkNotNull(activity) { "Context ($this) is not attached to an Activity" }
}
fun Context.requireDrawable(@DrawableRes id: Int): Drawable {
return ContextCompat.getDrawable(this, id) ?: throw Resources.NotFoundException(
"unable to find Drawable for resId ($id): ${resources.getResourceEntryName(id)}")
}
| unlicense | 27e13ab0f009684e84bf87c4310a98c5 | 30.08 | 93 | 0.720292 | 4.980769 | false | false | false | false |
strooooke/quickfit | app/src/main/java/com/lambdasoup/quickfit/ui/SchedulesFragment.kt | 1 | 9086 | /*
* Copyright 2016 Juliane Lehmann <[email protected]>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.lambdasoup.quickfit.ui
import android.content.ContentValues
import android.database.Cursor
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.content.ContextCompat
import androidx.fragment.app.Fragment
import androidx.loader.app.LoaderManager
import androidx.loader.content.Loader
import androidx.recyclerview.widget.ItemTouchHelper
import androidx.recyclerview.widget.RecyclerView
import com.lambdasoup.quickfit.alarm.AlarmService
import com.lambdasoup.quickfit.databinding.FragmentSchedulesBinding
import com.lambdasoup.quickfit.model.DayOfWeek
import com.lambdasoup.quickfit.persist.QuickFitContentProvider
import com.lambdasoup.quickfit.persist.QuickFitContract.ScheduleEntry
import com.lambdasoup.quickfit.util.ui.DividerItemDecoration
import com.lambdasoup.quickfit.util.ui.LeaveBehind
import com.lambdasoup.quickfit.util.ui.systemWindowInsetsRelative
import com.lambdasoup.quickfit.util.ui.updatePadding
import timber.log.Timber
import java.util.*
class SchedulesFragment : Fragment(),
LoaderManager.LoaderCallbacks<Cursor>, SchedulesRecyclerViewAdapter.OnScheduleInteractionListener,
TimeDialogFragment.OnFragmentInteractionListener, DayOfWeekDialogFragment.OnFragmentInteractionListener
{
internal var workoutId: Long = 0
private set
private lateinit var schedulesAdapter: SchedulesRecyclerViewAdapter
private lateinit var schedulesBinding: FragmentSchedulesBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
workoutId = arguments?.let {
if (it.containsKey(ARG_WORKOUT_ID)) {
it.getLong(ARG_WORKOUT_ID)
} else {
null
}
} ?: throw IllegalArgumentException("Argument 'workoutId' is missing")
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
schedulesBinding = FragmentSchedulesBinding.inflate(inflater, container, false)
return schedulesBinding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
view.setOnApplyWindowInsetsListener { v, windowInsets ->
v.setOnApplyWindowInsetsListener(null)
schedulesBinding.scheduleList.updatePadding {
oldPadding -> oldPadding + windowInsets.systemWindowInsetsRelative(v).copy(top = 0)
}
windowInsets
}
view.requestApplyInsets()
}
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
Timber.d("activity created, initializing view binding")
schedulesAdapter = SchedulesRecyclerViewAdapter().apply {
setOnScheduleInteractionListener(this@SchedulesFragment)
}
schedulesBinding.scheduleList.adapter = schedulesAdapter
val swipeDismiss = ItemTouchHelper(object : LeaveBehind() {
override fun onSwiped(viewHolder: RecyclerView.ViewHolder, direction: Int) {
onRemoveSchedule(viewHolder.itemId)
}
})
swipeDismiss.attachToRecyclerView(schedulesBinding.scheduleList)
schedulesBinding.scheduleList.addItemDecoration(DividerItemDecoration(requireContext(), true))
val bundle = Bundle(1)
bundle.putLong(ARG_WORKOUT_ID, workoutId)
loaderManager.initLoader(LOADER_SCHEDULES, bundle, this)
}
override fun onCreateLoader(id: Int, args: Bundle?): Loader<Cursor> {
Timber.d("onCreateLoader with args %s on schedules fragment %d", args, this.hashCode())
when (id) {
LOADER_SCHEDULES -> return SchedulesLoader(context, args!!.getLong(ARG_WORKOUT_ID))
}
throw IllegalArgumentException("Not a loader id: $id")
}
override fun onLoadFinished(loader: Loader<Cursor>, data: Cursor?) {
Timber.d("onLoadFinished, cursor is null? %s, cursor size is %d on schedules fragment %d",
data == null, data?.count ?: 0, this.hashCode())
when (loader.id) {
LOADER_SCHEDULES -> {
schedulesAdapter.swapCursor(data)
return
}
else -> throw IllegalArgumentException("Not a loader id: " + loader.id)
}
}
override fun onLoaderReset(loader: Loader<Cursor>) {
when (loader.id) {
LOADER_SCHEDULES -> {
schedulesAdapter.swapCursor(null)
return
}
else -> throw IllegalArgumentException("Not a loader id: " + loader.id)
}
}
override fun onDayOfWeekEditRequested(scheduleId: Long, oldValue: DayOfWeek) {
(activity as DialogActivity).showDialog(DayOfWeekDialogFragment.newInstance(scheduleId, oldValue))
}
override fun onListItemChanged(scheduleId: Long, newDayOfWeek: DayOfWeek) {
requireContext().contentResolver.update(
QuickFitContentProvider.getUriWorkoutsIdSchedulesId(workoutId, scheduleId),
ContentValues(1).apply {
put(ScheduleEntry.COL_DAY_OF_WEEK, newDayOfWeek.name)
},
null,
null
)
ContextCompat.startForegroundService(
requireContext(),
AlarmService.getOnScheduleChangedIntent(
requireContext(),
scheduleId
)
)
}
override fun onTimeEditRequested(scheduleId: Long, oldHour: Int, oldMinute: Int) {
(activity as DialogActivity).showDialog(TimeDialogFragment.newInstance(scheduleId, oldHour, oldMinute))
}
override fun onTimeChanged(scheduleId: Long, newHour: Int, newMinute: Int) {
requireContext().contentResolver.update(
QuickFitContentProvider.getUriWorkoutsIdSchedulesId(workoutId, scheduleId),
ContentValues(2).apply {
put(ScheduleEntry.COL_HOUR, newHour)
put(ScheduleEntry.COL_MINUTE, newMinute)
},
null,
null
)
ContextCompat.startForegroundService(
requireContext(),
AlarmService.getOnScheduleChangedIntent(
requireContext(),
scheduleId
)
)
}
internal fun onAddNewSchedule() {
// initialize with current day and time
val calendar = Calendar.getInstance()
val dayOfWeek = DayOfWeek.getByCalendarConst(calendar.get(Calendar.DAY_OF_WEEK))
val hour = calendar.get(Calendar.HOUR_OF_DAY)
val minute = calendar.get(Calendar.MINUTE)
val scheduleUri = requireContext().contentResolver.insert(
QuickFitContentProvider.getUriWorkoutsIdSchedules(workoutId),
ContentValues(3).apply {
put(ScheduleEntry.COL_DAY_OF_WEEK, dayOfWeek.name)
put(ScheduleEntry.COL_HOUR, hour)
put(ScheduleEntry.COL_MINUTE, minute)
}
)
ContextCompat.startForegroundService(
requireContext(),
AlarmService.getOnScheduleChangedIntent(
requireContext(),
QuickFitContentProvider.getScheduleIdFromUriOrThrow(scheduleUri)
)
)
}
private fun onRemoveSchedule(scheduleId: Long) {
requireContext().contentResolver.delete(
QuickFitContentProvider.getUriWorkoutsIdSchedulesId(workoutId, scheduleId),
null,
null
)
ContextCompat.startForegroundService(requireContext(), AlarmService.getOnScheduleDeletedIntent(requireContext(), scheduleId))
}
companion object {
private const val ARG_WORKOUT_ID = "com.lambdasoup.quickfit_workoutId"
private const val LOADER_SCHEDULES = 1
fun create(workoutId: Long): SchedulesFragment {
Timber.d("Creating schedules fragment with id %d", workoutId)
val fragment = SchedulesFragment().apply {
arguments = Bundle().apply {
putLong(ARG_WORKOUT_ID, workoutId)
}
}
Timber.d("created schedules fragment: %d", fragment.hashCode())
return fragment
}
}
}
| apache-2.0 | e1d8c78b44b392cc7aa34dc388e1bbd7 | 37.176471 | 133 | 0.659146 | 5.385892 | false | false | false | false |
rajeshdalsaniya/kotlin-tutorial | RandomNumber/src/Main.kt | 1 | 991 | import java.util.*
import kotlin.concurrent.fixedRateTimer
/**
* Created by rajeshdalsaniya on 05/08/17.
*/
fun main(args: Array<String>) {
// Random Number Generator Object
val newRandom = RandomNumber()
// Timer Print Random Numbers
var fixRateTimer = fixedRateTimer("randomNumber", false, 1000, 1000) {
// First Random Number
var random1 = newRandom.randomBetween(1,7)
// Second Random Number
var random2 = newRandom.randomBetween(1,7)
// Print Random Numbers
print("Random Numbers: $random1, $random2 \n")
}
// Run fix Rate Timer
try {
Thread.sleep(50000)
} finally {
fixRateTimer.cancel()
}
}
// Random Number Generator Class
class RandomNumber {
// Java Random Object
var random = Random()
/**
* Min is inclusive and max is exclusive in this case
*/
fun randomBetween(min: Int, max: Int): Int {
return random.nextInt(max - min) + min
}
} | mit | f7dbd1562794c06f33c999f6ca5a1d66 | 22.069767 | 74 | 0.624622 | 3.995968 | false | false | false | false |
xiaopansky/Sketch | sample/src/main/java/me/panpf/sketch/sample/ui/RepeatLoadOrDownloadTestFragment.kt | 1 | 2241 | package me.panpf.sketch.sample.ui
import android.os.Bundle
import android.view.View
import kotlinx.android.synthetic.main.fragment_repeat_load_or_download_test.*
import me.panpf.sketch.sample.base.BaseFragment
import me.panpf.sketch.sample.base.BindContentView
import me.panpf.sketch.sample.R
import me.panpf.sketch.uri.ApkIconUriModel
@BindContentView(R.layout.fragment_repeat_load_or_download_test)
class RepeatLoadOrDownloadTestFragment : BaseFragment() {
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val context = context ?: return
val selfApkFile = context.applicationInfo.publicSourceDir
arrayOf(image_repeatLoadOrDownloadTest_1
, image_repeatLoadOrDownloadTest_2
, image_repeatLoadOrDownloadTest_3
, image_repeatLoadOrDownloadTest_4
, image_repeatLoadOrDownloadTest_5
, image_repeatLoadOrDownloadTest_6
, image_repeatLoadOrDownloadTest_7
, image_repeatLoadOrDownloadTest_8
).forEach { it.displayImage(ApkIconUriModel.makeUri(selfApkFile)) }
arrayOf(image_repeatLoadOrDownloadTest_9
, image_repeatLoadOrDownloadTest_10
, image_repeatLoadOrDownloadTest_11
, image_repeatLoadOrDownloadTest_12
, image_repeatLoadOrDownloadTest_13
, image_repeatLoadOrDownloadTest_14
, image_repeatLoadOrDownloadTest_15
, image_repeatLoadOrDownloadTest_16
).forEach { it.displayImage("http://img3.imgtn.bdimg.com/it/u=1671737159,3601566602&fm=21&gp=0.jpg") }
arrayOf(image_repeatLoadOrDownloadTest_31
, image_repeatLoadOrDownloadTest_32
, image_repeatLoadOrDownloadTest_33
, image_repeatLoadOrDownloadTest_34
, image_repeatLoadOrDownloadTest_35
, image_repeatLoadOrDownloadTest_36
, image_repeatLoadOrDownloadTest_37
, image_repeatLoadOrDownloadTest_38
).forEach { it.displayImage("http://img3.duitang.com/uploads/item/201604/26/20160426001415_teGBZ.jpeg") }
}
}
| apache-2.0 | ef7dd7c89adc0654c5eaa90b909c433f | 44.734694 | 113 | 0.679161 | 4.991091 | false | true | false | false |
ankidroid/Anki-Android | AnkiDroid/src/main/java/com/ichi2/libanki/template/MathJax.kt | 1 | 1990 | /*
* Copyright (c) 2020 Arthur Milchior <[email protected]>
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation; either version 3 of the License, or (at your option) any later
* version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.ichi2.libanki.template
import com.ichi2.utils.KotlinCleanup
object MathJax {
// MathJax opening delimiters
private val sMathJaxOpenings = arrayOf("\\(", "\\[")
// MathJax closing delimiters
private val sMathJaxClosings = arrayOf("\\)", "\\]")
@KotlinCleanup("fix IDE lint issues")
fun textContainsMathjax(txt: String): Boolean {
// Do you have the first opening and then the first closing,
// or the second opening and the second closing...?
// This assumes that the openings and closings are the same length.
var opening: String
var closing: String
for (i in sMathJaxOpenings.indices) {
opening = sMathJaxOpenings[i]
closing = sMathJaxClosings[i]
// What if there are more than one thing?
// Let's look for the first opening, and the last closing, and if they're in the right order,
// we are good.
val first_opening_index = txt.indexOf(opening)
val last_closing_index = txt.lastIndexOf(closing)
if (first_opening_index != -1 && last_closing_index != -1 && first_opening_index < last_closing_index) {
return true
}
}
return false
}
}
| gpl-3.0 | 50042a648031ca8c2f2b89087a2accea | 38.8 | 116 | 0.656784 | 4.234043 | false | false | false | false |
envoyproxy/envoy | mobile/library/kotlin/io/envoyproxy/envoymobile/RetryPolicy.kt | 2 | 3539 | package io.envoyproxy.envoymobile
import java.lang.IllegalArgumentException
/**
* Specifies how a request may be retried, containing one or more rules.
*
* @param maxRetryCount Maximum number of retries that a request may be performed.
* @param retryOn Rules checked for retrying.
* @param retryStatusCodes Additional list of status codes that should be retried.
* @param perRetryTimeoutMS Timeout (in milliseconds) to apply to each retry.
* Must be <= `totalUpstreamTimeoutMS` if it's a positive number.
* @param totalUpstreamTimeoutMS Total timeout (in milliseconds) that includes all retries.
* Spans the point at which the entire downstream request has been processed and when the
* upstream response has been completely processed. Null or 0 may be specified to disable it.
*/
data class RetryPolicy(
val maxRetryCount: Int,
val retryOn: List<RetryRule>,
val retryStatusCodes: List<Int> = emptyList(),
val perRetryTimeoutMS: Long? = null,
val totalUpstreamTimeoutMS: Long? = 15000
) {
init {
if (perRetryTimeoutMS != null && totalUpstreamTimeoutMS != null &&
perRetryTimeoutMS > totalUpstreamTimeoutMS && totalUpstreamTimeoutMS != 0L
) {
throw IllegalArgumentException("Per-retry timeout cannot be less than total timeout")
}
}
companion object {
/**
* Initialize the retry policy from a set of headers.
*
* @param headers: The headers with which to initialize the retry policy.
*/
internal fun from(headers: RequestHeaders): RetryPolicy? {
val maxRetries = headers.value("x-envoy-max-retries")?.first()?.toIntOrNull() ?: return null
return RetryPolicy(
maxRetries,
// Envoy internally coalesces multiple x-envoy header values into one comma-delimited value.
// These flatMap transformations split those values up to correctly map back to
// Kotlin enums.
headers.value("x-envoy-retry-on")
?.flatMap { it.split(",") }?.map { retryOn -> RetryRule.enumValue(retryOn) }
?.filterNotNull() ?: emptyList(),
headers.value("x-envoy-retriable-status-codes")
?.flatMap { it.split(",") }?.map { statusCode -> statusCode.toIntOrNull() }
?.filterNotNull() ?: emptyList(),
headers.value("x-envoy-upstream-rq-per-try-timeout-ms")?.firstOrNull()?.toLongOrNull(),
headers.value("x-envoy-upstream-rq-timeout-ms")?.firstOrNull()?.toLongOrNull()
)
}
}
}
/**
* Rules that may be used with `RetryPolicy`.
* See the `x-envoy-retry-on` Envoy header for documentation.
*/
enum class RetryRule(internal val stringValue: String) {
STATUS_5XX("5xx"),
GATEWAY_ERROR("gateway-error"),
CONNECT_FAILURE("connect-failure"),
REFUSED_STREAM("refused-stream"),
RETRIABLE_4XX("retriable-4xx"),
RETRIABLE_HEADERS("retriable-headers"),
RESET("reset");
companion object {
internal fun enumValue(stringRepresentation: String): RetryRule? {
return when (stringRepresentation) {
"5xx" -> STATUS_5XX
"gateway-error" -> GATEWAY_ERROR
"connect-failure" -> CONNECT_FAILURE
"refused-stream" -> REFUSED_STREAM
"retriable-4xx" -> RETRIABLE_4XX
"retriable-headers" -> RETRIABLE_HEADERS
"reset" -> RESET
// This is mapped to null because this string value is added to headers automatically
// in RetryPolicy.outboundHeaders()
"retriable-status-codes" -> null
else -> throw IllegalArgumentException("invalid value $stringRepresentation")
}
}
}
}
| apache-2.0 | 63225597fa02011dffab75ec8a3d58cc | 38.764045 | 100 | 0.68607 | 4.440402 | false | false | false | false |
alex-tavella/MooV | feature/bookmark-movie/impl/src/test/java/br/com/bookmark/movie/testdoubles/TestMovieBookmarksDao.kt | 1 | 1754 | /*
* Copyright 2021 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.bookmark.movie.testdoubles
import br.com.bookmark.movie.data.local.dao.MovieBookmarksDao
import br.com.bookmark.movie.data.local.entity.MovieBookmark
import java.io.IOException
class TestMovieBookmarksDao(
initialMovies: List<MovieBookmark> = emptyList()
) : MovieBookmarksDao {
private val movies = initialMovies.toMutableList()
override suspend fun getAll(): List<MovieBookmark> {
return movies.toList()
}
override suspend fun get(movieId: Int): MovieBookmark? {
return movies.find { it.id == movieId }
}
override suspend fun loadAllByIds(movieIds: IntArray): List<MovieBookmark> {
return movies.filter { movieIds.contains(it.id) }
}
override suspend fun insert(movie: MovieBookmark): Long {
if (movies.contains(movie)) throw IOException("Movie already on database")
movies.add(movie)
return movies.size.toLong()
}
override suspend fun delete(movieId: Int): Int {
if (movies.none { it.id == movieId }) throw IOException("Movie not on database")
movies.removeIf { it.id == movieId }
return movies.size
}
}
| apache-2.0 | dd8a0ed041ca77ec1294eb6dc0d0b53b | 33.392157 | 88 | 0.708096 | 4.257282 | false | false | false | false |
matkoniecz/StreetComplete | app/src/main/java/de/westnordost/streetcomplete/quests/bridge_structure/AddBridgeStructure.kt | 1 | 1057 | package de.westnordost.streetcomplete.quests.bridge_structure
import de.westnordost.streetcomplete.R
import de.westnordost.streetcomplete.data.osm.osmquests.OsmFilterQuestType
import de.westnordost.streetcomplete.data.osm.edits.update_tags.StringMapChangesBuilder
import de.westnordost.streetcomplete.data.user.achievements.QuestTypeAchievement.BUILDING
class AddBridgeStructure : OsmFilterQuestType<BridgeStructure>() {
override val elementFilter = "ways with man_made = bridge and !bridge:structure and !bridge:movable"
override val commitMessage = "Add bridge structures"
override val wikiLink = "Key:bridge:structure"
override val icon = R.drawable.ic_quest_bridge
override val questTypeAchievements = listOf(BUILDING)
override fun getTitle(tags: Map<String, String>) = R.string.quest_bridge_structure_title
override fun createForm() = AddBridgeStructureForm()
override fun applyAnswerTo(answer: BridgeStructure, changes: StringMapChangesBuilder) {
changes.add("bridge:structure", answer.osmValue)
}
}
| gpl-3.0 | 7ab3fe77d15f369b3a11aea8a74cf398 | 43.041667 | 104 | 0.794702 | 4.782805 | false | false | false | false |
matkoniecz/StreetComplete | app/src/main/java/de/westnordost/streetcomplete/quests/diet_type/AddHalal.kt | 1 | 1507 | package de.westnordost.streetcomplete.quests.diet_type
import de.westnordost.streetcomplete.R
import de.westnordost.streetcomplete.data.meta.updateWithCheckDate
import de.westnordost.streetcomplete.data.osm.edits.update_tags.StringMapChangesBuilder
import de.westnordost.streetcomplete.data.osm.osmquests.OsmFilterQuestType
import de.westnordost.streetcomplete.data.user.achievements.QuestTypeAchievement.CITIZEN
class AddHalal : OsmFilterQuestType<DietAvailability>() {
override val elementFilter = """
nodes, ways with
(
amenity ~ restaurant|cafe|fast_food|ice_cream
or shop ~ butcher|supermarket|ice_cream
)
and name and (
!diet:halal
or diet:halal != only and diet:halal older today -4 years
)
"""
override val commitMessage = "Add Halal status"
override val wikiLink = "Key:diet:halal"
override val icon = R.drawable.ic_quest_halal
override val isReplaceShopEnabled = true
override val defaultDisabledMessage = R.string.default_disabled_msg_go_inside_regional_warning
override val questTypeAchievements = listOf(CITIZEN)
override fun getTitle(tags: Map<String, String>) = R.string.quest_dietType_halal_name_title
override fun createForm() = AddDietTypeForm.create(R.string.quest_dietType_explanation_halal)
override fun applyAnswerTo(answer: DietAvailability, changes: StringMapChangesBuilder) {
changes.updateWithCheckDate("diet:halal", answer.osmValue)
}
}
| gpl-3.0 | cef3c8181bd2f423e5bb6b873e958e92 | 39.72973 | 98 | 0.745189 | 4.445428 | false | false | false | false |
wordpress-mobile/WordPress-Stores-Android | example/src/test/java/org/wordpress/android/fluxc/store/stats/time/VisitsAndViewsStoreTest.kt | 1 | 6208 | package org.wordpress.android.fluxc.store.stats.time
import com.nhaarman.mockitokotlin2.any
import com.nhaarman.mockitokotlin2.eq
import com.nhaarman.mockitokotlin2.isNull
import com.nhaarman.mockitokotlin2.mock
import com.nhaarman.mockitokotlin2.never
import com.nhaarman.mockitokotlin2.verify
import com.nhaarman.mockitokotlin2.whenever
import org.assertj.core.api.Assertions.assertThat
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.Mock
import org.mockito.junit.MockitoJUnitRunner
import org.wordpress.android.fluxc.model.SiteModel
import org.wordpress.android.fluxc.model.stats.LimitMode
import org.wordpress.android.fluxc.model.stats.time.TimeStatsMapper
import org.wordpress.android.fluxc.model.stats.time.VisitsAndViewsModel
import org.wordpress.android.fluxc.network.rest.wpcom.stats.time.StatsUtils
import org.wordpress.android.fluxc.network.rest.wpcom.stats.time.VisitAndViewsRestClient
import org.wordpress.android.fluxc.network.rest.wpcom.stats.time.VisitAndViewsRestClient.VisitsAndViewsResponse
import org.wordpress.android.fluxc.network.utils.StatsGranularity.DAYS
import org.wordpress.android.fluxc.persistence.TimeStatsSqlUtils.VisitsAndViewsSqlUtils
import org.wordpress.android.fluxc.store.StatsStore.FetchStatsPayload
import org.wordpress.android.fluxc.store.StatsStore.StatsError
import org.wordpress.android.fluxc.store.StatsStore.StatsErrorType.API_ERROR
import org.wordpress.android.fluxc.test
import org.wordpress.android.fluxc.tools.initCoroutineEngine
import org.wordpress.android.fluxc.utils.AppLogWrapper
import org.wordpress.android.fluxc.utils.CurrentTimeProvider
import java.util.Date
import kotlin.test.assertEquals
import kotlin.test.assertNotNull
private const val ITEMS_TO_LOAD = 8
private val LIMIT_MODE = LimitMode.Top(ITEMS_TO_LOAD)
private const val FORMATTED_DATE = "2019-10-10"
@RunWith(MockitoJUnitRunner::class)
class VisitsAndViewsStoreTest {
@Mock lateinit var site: SiteModel
@Mock lateinit var restClient: VisitAndViewsRestClient
@Mock lateinit var sqlUtils: VisitsAndViewsSqlUtils
@Mock lateinit var statsUtils: StatsUtils
@Mock lateinit var currentTimeProvider: CurrentTimeProvider
@Mock lateinit var mapper: TimeStatsMapper
@Mock lateinit var appLogWrapper: AppLogWrapper
private lateinit var store: VisitsAndViewsStore
@Before
fun setUp() {
store = VisitsAndViewsStore(
restClient,
sqlUtils,
mapper,
statsUtils,
currentTimeProvider,
initCoroutineEngine(),
appLogWrapper
)
val currentDate = Date(0)
whenever(currentTimeProvider.currentDate()).thenReturn(currentDate)
val timeZone = "GMT"
whenever(site.timezone).thenReturn(timeZone)
whenever(
statsUtils.getFormattedDate(
eq(currentDate),
any()
)
).thenReturn(FORMATTED_DATE)
}
@Test
fun `returns data per site`() = test {
val fetchInsightsPayload = FetchStatsPayload(
VISITS_AND_VIEWS_RESPONSE
)
val forced = true
whenever(restClient.fetchVisits(site, DAYS, FORMATTED_DATE, ITEMS_TO_LOAD, forced)).thenReturn(
fetchInsightsPayload
)
whenever(mapper.map(VISITS_AND_VIEWS_RESPONSE, LIMIT_MODE)).thenReturn(VISITS_AND_VIEWS_MODEL)
val responseModel = store.fetchVisits(site, DAYS, LIMIT_MODE, forced)
assertThat(responseModel.model).isEqualTo(VISITS_AND_VIEWS_MODEL)
verify(sqlUtils).insert(site, VISITS_AND_VIEWS_RESPONSE, DAYS, FORMATTED_DATE, ITEMS_TO_LOAD)
}
@Test
fun `returns cached data per site`() = test {
whenever(sqlUtils.hasFreshRequest(site, DAYS, FORMATTED_DATE, ITEMS_TO_LOAD)).thenReturn(true)
whenever(sqlUtils.select(site, DAYS, FORMATTED_DATE)).thenReturn(VISITS_AND_VIEWS_RESPONSE)
val model = mock<VisitsAndViewsModel>()
whenever(mapper.map(VISITS_AND_VIEWS_RESPONSE, LIMIT_MODE)).thenReturn(model)
val forced = false
val responseModel = store.fetchVisits(site, DAYS, LIMIT_MODE, forced)
assertThat(responseModel.model).isEqualTo(model)
assertThat(responseModel.cached).isTrue()
verify(sqlUtils, never()).insert(any(), any(), any(), any<String>(), isNull())
}
@Test
fun `returns error when invalid data`() = test {
val forced = true
val fetchInsightsPayload = FetchStatsPayload(
VISITS_AND_VIEWS_RESPONSE
)
whenever(restClient.fetchVisits(site, DAYS, FORMATTED_DATE, ITEMS_TO_LOAD, forced)).thenReturn(
fetchInsightsPayload
)
val emptyModel = VisitsAndViewsModel("", emptyList())
whenever(mapper.map(VISITS_AND_VIEWS_RESPONSE, LIMIT_MODE)).thenReturn(emptyModel)
val responseModel = store.fetchVisits(site, DAYS, LIMIT_MODE, forced)
assertThat(responseModel.error.type).isEqualTo(INVALID_DATA_ERROR.type)
assertThat(responseModel.error.message).isEqualTo(INVALID_DATA_ERROR.message)
}
@Test
fun `returns error when data call fail`() = test {
val type = API_ERROR
val message = "message"
val errorPayload = FetchStatsPayload<VisitsAndViewsResponse>(StatsError(type, message))
val forced = true
whenever(restClient.fetchVisits(site, DAYS, FORMATTED_DATE, ITEMS_TO_LOAD, forced)).thenReturn(errorPayload)
val responseModel = store.fetchVisits(site, DAYS, LIMIT_MODE, forced)
assertNotNull(responseModel.error)
val error = responseModel.error!!
assertEquals(type, error.type)
assertEquals(message, error.message)
}
@Test
fun `returns data from db`() {
whenever(sqlUtils.select(site, DAYS, FORMATTED_DATE)).thenReturn(VISITS_AND_VIEWS_RESPONSE)
val model = mock<VisitsAndViewsModel>()
whenever(mapper.map(VISITS_AND_VIEWS_RESPONSE, LIMIT_MODE)).thenReturn(model)
val result = store.getVisits(site, DAYS, LIMIT_MODE)
assertThat(result).isEqualTo(model)
}
}
| gpl-2.0 | f0b2e226ca1d97bb926c24a141d1ae63 | 40.66443 | 116 | 0.716656 | 4.498551 | false | true | false | false |
cfig/Nexus_boot_image_editor | helper/src/main/kotlin/cfig/helper/KeyHelper2.kt | 1 | 4175 | // Copyright 2021 [email protected]
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package cfig.helper
import org.apache.commons.exec.CommandLine
import org.apache.commons.exec.DefaultExecutor
import org.apache.commons.exec.ExecuteException
import org.apache.commons.exec.PumpStreamHandler
import org.slf4j.LoggerFactory
import java.io.ByteArrayInputStream
import java.io.ByteArrayOutputStream
import java.security.MessageDigest
import javax.crypto.Cipher
class KeyHelper2 {
companion object {
private val log = LoggerFactory.getLogger(KeyHelper2::class.java)
/* inspired by
https://stackoverflow.com/questions/40242391/how-can-i-sign-a-raw-message-without-first-hashing-it-in-bouncy-castle
"specifying Cipher.ENCRYPT mode or Cipher.DECRYPT mode doesn't make a difference;
both simply perform modular exponentiation"
python counterpart:
import Crypto.PublicKey.RSA
key = Crypto.PublicKey.RSA.construct((modulus, exponent))
vRet = key.verify(decode_long(padding_and_digest), (decode_long(sig_blob), None))
print("verify padded digest: %s" % binascii.hexlify(padding_and_digest))
print("verify sig: %s" % binascii.hexlify(sig_blob))
print("X: Verify: %s" % vRet)
*/
fun rawRsa(key: java.security.Key, data: ByteArray): ByteArray {
return Cipher.getInstance("RSA/ECB/NoPadding").let { cipher ->
cipher.init(Cipher.ENCRYPT_MODE, key)
cipher.update(data)
cipher.doFinal()
}
}
fun rawSignOpenSsl(keyPath: String, data: ByteArray): ByteArray {
log.debug("raw input: " + Helper.toHexString(data))
log.debug("Raw sign data size = ${data.size}, key = $keyPath")
var ret = byteArrayOf()
val exe = DefaultExecutor()
val stdin = ByteArrayInputStream(data)
val stdout = ByteArrayOutputStream()
val stderr = ByteArrayOutputStream()
exe.streamHandler = PumpStreamHandler(stdout, stderr, stdin)
try {
exe.execute(CommandLine.parse("openssl rsautl -sign -inkey $keyPath -raw"))
ret = stdout.toByteArray()
log.debug("Raw signature size = " + ret.size)
} catch (e: ExecuteException) {
log.error("Execute error")
} finally {
log.debug("OUT: " + Helper.toHexString(stdout.toByteArray()))
log.debug("ERR: " + String(stderr.toByteArray()))
}
if (ret.isEmpty()) throw RuntimeException("raw sign failed")
return ret
}
fun pyAlg2java(alg: String): String {
return when (alg) {
"sha1" -> "sha-1"
"sha224" -> "sha-224"
"sha256" -> "sha-256"
"sha384" -> "sha-384"
"sha512" -> "sha-512"
else -> throw IllegalArgumentException("unknown algorithm: [$alg]")
}
}
/*
openssl dgst -sha256 <file>
*/
fun sha256(inData: ByteArray): ByteArray {
return MessageDigest.getInstance("SHA-256").digest(inData)
}
fun rsa(inData: ByteArray, inKey: java.security.PrivateKey): ByteArray {
return Cipher.getInstance("RSA").let {
it.init(Cipher.ENCRYPT_MODE, inKey)
it.doFinal(inData)
}
}
fun sha256rsa(inData: ByteArray, inKey: java.security.PrivateKey): ByteArray {
return rsa(sha256(inData), inKey)
}
}
}
| apache-2.0 | d7625484f1ea55c368b07d635250deec | 38.386792 | 124 | 0.610778 | 4.330913 | false | false | false | false |
cfig/Nexus_boot_image_editor | bbootimg/src/main/kotlin/bootimg/v3/BootV3.kt | 1 | 13352 | // Copyright 2021 [email protected]
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package cfig.bootimg.v3
import avb.AVBInfo
import avb.alg.Algorithms
import avb.blob.AuxBlob
import cfig.Avb
import cfig.EnvironmentVerifier
import cfig.bootimg.Common.Companion.deleleIfExists
import cfig.bootimg.Common.Companion.getPaddingSize
import cfig.bootimg.Signer
import cfig.helper.Helper
import cfig.packable.VBMetaParser
import com.fasterxml.jackson.databind.ObjectMapper
import de.vandermeer.asciitable.AsciiTable
import org.apache.commons.exec.CommandLine
import org.apache.commons.exec.DefaultExecutor
import org.slf4j.LoggerFactory
import java.io.File
import java.io.FileInputStream
import java.io.FileOutputStream
import java.nio.ByteBuffer
import java.nio.ByteOrder
import cfig.bootimg.Common as C
data class BootV3(
var info: MiscInfo = MiscInfo(),
var kernel: CommArgs = CommArgs(),
val ramdisk: CommArgs = CommArgs(),
var bootSignature: CommArgs = CommArgs(),
) {
companion object {
private val log = LoggerFactory.getLogger(BootV3::class.java)
private val mapper = ObjectMapper()
private val workDir = Helper.prop("workDir")
fun parse(fileName: String): BootV3 {
val ret = BootV3()
FileInputStream(fileName).use { fis ->
val header = BootHeaderV3(fis)
//info
ret.info.output = File(fileName).name
ret.info.json = File(fileName).name.removeSuffix(".img") + ".json"
ret.info.cmdline = header.cmdline
ret.info.headerSize = header.headerSize
ret.info.headerVersion = header.headerVersion
ret.info.osVersion = header.osVersion
ret.info.osPatchLevel = header.osPatchLevel
ret.info.pageSize = BootHeaderV3.pageSize
ret.info.signatureSize = header.signatureSize
//kernel
ret.kernel.file = workDir + "kernel"
ret.kernel.size = header.kernelSize
ret.kernel.position = BootHeaderV3.pageSize
//ramdisk
ret.ramdisk.file = workDir + "ramdisk.img"
ret.ramdisk.size = header.ramdiskSize
ret.ramdisk.position = ret.kernel.position + header.kernelSize +
getPaddingSize(header.kernelSize, BootHeaderV3.pageSize)
//boot signature
if (header.signatureSize > 0) {
ret.bootSignature.file = workDir + "bootsig"
ret.bootSignature.size = header.signatureSize
ret.bootSignature.position = ret.ramdisk.position + ret.ramdisk.size +
getPaddingSize(header.ramdiskSize, BootHeaderV3.pageSize)
}
}
ret.info.imageSize = File(fileName).length()
return ret
}
}
data class MiscInfo(
var output: String = "",
var json: String = "",
var headerVersion: Int = 0,
var headerSize: Int = 0,
var pageSize: Int = 0,
var cmdline: String = "",
var osVersion: String = "",
var osPatchLevel: String = "",
var imageSize: Long = 0,
var signatureSize: Int = 0,
)
data class CommArgs(
var file: String = "",
var position: Int = 0,
var size: Int = 0,
)
fun pack(): BootV3 {
if (File(this.ramdisk.file).exists() && !File(workDir + "root").exists()) {
//do nothing if we have ramdisk.img.gz but no /root
log.warn("Use prebuilt ramdisk file: ${this.ramdisk.file}")
} else {
File(this.ramdisk.file).deleleIfExists()
File(this.ramdisk.file.replaceFirst("[.][^.]+$", "")).deleleIfExists()
//TODO: remove cpio in C/C++
//C.packRootfs("$workDir/root", this.ramdisk.file, C.parseOsMajor(info.osVersion))
// enable advance JAVA cpio
C.packRootfs("$workDir/root", this.ramdisk.file)
}
this.kernel.size = File(this.kernel.file).length().toInt()
this.ramdisk.size = File(this.ramdisk.file).length().toInt()
//header
FileOutputStream(this.info.output + ".clear", false).use { fos ->
val encodedHeader = this.toHeader().encode()
fos.write(encodedHeader)
fos.write(
ByteArray(Helper.round_to_multiple(encodedHeader.size, this.info.pageSize) - encodedHeader.size)
)
}
//data
log.info("Writing data ...")
//BootV3 should have correct image size
val bf = ByteBuffer.allocate(maxOf(info.imageSize.toInt(), 64 * 1024 * 1024))
bf.order(ByteOrder.LITTLE_ENDIAN)
C.writePaddedFile(bf, this.kernel.file, this.info.pageSize)
C.writePaddedFile(bf, this.ramdisk.file, this.info.pageSize)
//write V3 data
FileOutputStream("${this.info.output}.clear", true).use { fos ->
fos.write(bf.array(), 0, bf.position())
}
//write V4 boot sig
if (this.info.headerVersion > 3) {
val bootSigJson = File(Avb.getJsonFileName(this.bootSignature.file))
var bootSigBytes = ByteArray(this.bootSignature.size)
if (bootSigJson.exists()) {
log.warn("V4 BootImage has GKI boot signature")
val readBackBootSig = mapper.readValue(bootSigJson, AVBInfo::class.java)
val alg = Algorithms.get(readBackBootSig.header!!.algorithm_type)!!
//replace new pub key
readBackBootSig.auxBlob!!.pubkey!!.pubkey = AuxBlob.encodePubKey(alg)
//update hash and sig
readBackBootSig.auxBlob!!.hashDescriptors.get(0).update(this.info.output + ".clear")
bootSigBytes = readBackBootSig.encodePadded()
}
//write V4 data
FileOutputStream("${this.info.output}.clear", true).use { fos ->
fos.write(bootSigBytes)
}
}
//google way
this.toCommandLine().addArgument(this.info.output + ".google").let {
log.info(it.toString())
DefaultExecutor().execute(it)
}
C.assertFileEquals(this.info.output + ".clear", this.info.output + ".google")
return this
}
fun sign(fileName: String): BootV3 {
if (File(Avb.getJsonFileName(info.output)).exists()) {
Signer.signAVB(fileName, this.info.imageSize, String.format(Helper.prop("avbtool"), "v1.2"))
} else {
log.warn("no AVB info found, assume it's clear image")
}
return this
}
private fun toHeader(): BootHeaderV3 {
return BootHeaderV3(
kernelSize = kernel.size,
ramdiskSize = ramdisk.size,
headerVersion = info.headerVersion,
osVersion = info.osVersion,
osPatchLevel = info.osPatchLevel,
headerSize = info.headerSize,
cmdline = info.cmdline,
signatureSize = info.signatureSize
)
}
fun extractImages(): BootV3 {
val workDir = Helper.prop("workDir")
//info
mapper.writerWithDefaultPrettyPrinter().writeValue(File(workDir + this.info.json), this)
//kernel
C.dumpKernel(Helper.Slice(info.output, kernel.position, kernel.size, kernel.file))
//ramdisk
val fmt = C.dumpRamdisk(
Helper.Slice(info.output, ramdisk.position, ramdisk.size, ramdisk.file), "${workDir}root"
)
this.ramdisk.file = this.ramdisk.file + ".$fmt"
//bootsig
if (info.signatureSize > 0) {
Helper.extractFile(
info.output, this.bootSignature.file,
this.bootSignature.position.toLong(), this.bootSignature.size
)
try {
AVBInfo.parseFrom(this.bootSignature.file).dumpDefault(this.bootSignature.file)
} catch (e: IllegalArgumentException) {
log.warn("boot signature is invalid")
}
}
//dump info again
mapper.writerWithDefaultPrettyPrinter().writeValue(File(workDir + this.info.json), this)
return this
}
fun extractVBMeta(): BootV3 {
try {
AVBInfo.parseFrom(info.output).dumpDefault(info.output)
if (File("vbmeta.img").exists()) {
log.warn("Found vbmeta.img, parsing ...")
VBMetaParser().unpack("vbmeta.img")
}
} catch (e: IllegalArgumentException) {
log.warn(e.message)
log.warn("failed to parse vbmeta info")
}
return this
}
fun printSummary(): BootV3 {
val workDir = Helper.prop("workDir")
val tableHeader = AsciiTable().apply {
addRule()
addRow("What", "Where")
addRule()
}
val tab = AsciiTable().let {
it.addRule()
it.addRow("image info", workDir + info.output.removeSuffix(".img") + ".json")
it.addRule()
it.addRow("kernel", this.kernel.file)
File(Helper.prop("kernelVersionFile")).let { kernelVersionFile ->
if (kernelVersionFile.exists()) {
it.addRow("\\-- version " + kernelVersionFile.readLines().toString(), kernelVersionFile.path)
}
}
File(Helper.prop("kernelConfigFile")).let { kernelConfigFile ->
if (kernelConfigFile.exists()) {
it.addRow("\\-- config", kernelConfigFile.path)
}
}
it.addRule()
it.addRow("ramdisk", this.ramdisk.file)
it.addRow("\\-- extracted ramdisk rootfs", "${workDir}root")
it.addRule()
if (this.info.signatureSize > 0) {
it.addRow("boot signature", this.bootSignature.file)
Avb.getJsonFileName(this.bootSignature.file).let { jsFile ->
it.addRow("\\-- decoded boot signature", if (File(jsFile).exists()) jsFile else "N/A")
}
it.addRule()
}
Avb.getJsonFileName(info.output).let { jsonFile ->
it.addRow("AVB info", if (File(jsonFile).exists()) jsonFile else "NONE")
}
it.addRule()
it
}
val tabVBMeta = AsciiTable().let {
if (File("vbmeta.img").exists()) {
it.addRule()
it.addRow("vbmeta.img", Avb.getJsonFileName("vbmeta.img"))
it.addRule()
"\n" + it.render()
} else {
""
}
}
log.info(
"\n\t\t\tUnpack Summary of ${info.output}\n{}\n{}{}",
tableHeader.render(), tab.render(), tabVBMeta
)
return this
}
private fun toCommandLine(): CommandLine {
val cmdPrefix = if (EnvironmentVerifier().isWindows) "python " else ""
return CommandLine.parse(cmdPrefix + Helper.prop("mkbootimg")).let { ret ->
ret.addArgument("--header_version")
ret.addArgument(info.headerVersion.toString())
if (kernel.size > 0) {
ret.addArgument("--kernel")
ret.addArgument(this.kernel.file)
}
if (ramdisk.size > 0) {
ret.addArgument("--ramdisk")
ret.addArgument(this.ramdisk.file)
}
if (info.cmdline.isNotBlank()) {
ret.addArgument(" --cmdline ")
ret.addArgument(info.cmdline, false)
}
if (info.osVersion.isNotBlank()) {
ret.addArgument(" --os_version")
ret.addArgument(info.osVersion)
}
if (info.osPatchLevel.isNotBlank()) {
ret.addArgument(" --os_patch_level")
ret.addArgument(info.osPatchLevel)
}
if (this.bootSignature.size > 0 && File(Avb.getJsonFileName(this.bootSignature.file)).exists()) {
val origSig = mapper.readValue(File(Avb.getJsonFileName(this.bootSignature.file)), AVBInfo::class.java)
val alg = Algorithms.get(origSig.header!!.algorithm_type)!!
ret.addArgument("--gki_signing_algorithm").addArgument(alg.name)
ret.addArgument("--gki_signing_key").addArgument(alg.defaultKey)
ret.addArgument("--gki_signing_avbtool_path").addArgument(String.format(Helper.prop("avbtool"), "v1.2"))
}
ret.addArgument(" --id ")
ret.addArgument(" --output ")
//ret.addArgument("boot.img" + ".google")
log.debug("To Commandline: $ret")
ret
}
}
}
| apache-2.0 | 20985bd4498578272a8dc207782b7b76 | 39.096096 | 120 | 0.572124 | 4.506244 | false | false | false | false |
fossasia/open-event-android | app/src/main/java/org/fossasia/openevent/general/StartupViewModel.kt | 1 | 4762 | package org.fossasia.openevent.general
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.rxkotlin.plusAssign
import org.fossasia.openevent.general.auth.AuthHolder
import org.fossasia.openevent.general.auth.AuthService
import org.fossasia.openevent.general.auth.RequestPasswordReset
import org.fossasia.openevent.general.auth.forgot.PasswordReset
import org.fossasia.openevent.general.common.SingleLiveEvent
import org.fossasia.openevent.general.data.Preference
import org.fossasia.openevent.general.data.Resource
import org.fossasia.openevent.general.event.NEW_NOTIFICATIONS
import org.fossasia.openevent.general.notification.NotificationService
import org.fossasia.openevent.general.settings.SettingsService
import org.fossasia.openevent.general.utils.HttpErrors
import org.fossasia.openevent.general.utils.extensions.withDefaultSchedulers
import retrofit2.HttpException
import timber.log.Timber
class StartupViewModel(
private val preference: Preference,
private val resource: Resource,
private val authHolder: AuthHolder,
private val authService: AuthService,
private val notificationService: NotificationService,
private val settingsService: SettingsService
) : ViewModel() {
private val compositeDisposable = CompositeDisposable()
val mutableNewNotifications = MutableLiveData<Boolean>()
val newNotifications: LiveData<Boolean> = mutableNewNotifications
private val mutableDialogProgress = MutableLiveData<Boolean>()
val dialogProgress: LiveData<Boolean> = mutableDialogProgress
private val mutableIsRefresh = MutableLiveData<Boolean>()
val isRefresh: LiveData<Boolean> = mutableIsRefresh
private val mutableResetPasswordEmail = MutableLiveData<String>()
val resetPasswordEmail: LiveData<String> = mutableResetPasswordEmail
private val mutableMessage = SingleLiveEvent<String>()
val message: SingleLiveEvent<String> = mutableMessage
fun isLoggedIn() = authHolder.isLoggedIn()
fun getId() = authHolder.getId()
fun syncNotifications() {
if (!isLoggedIn())
return
compositeDisposable += notificationService.syncNotifications(getId())
.withDefaultSchedulers()
.subscribe({ list ->
list?.forEach {
if (!it.isRead) {
preference.putBoolean(NEW_NOTIFICATIONS, true)
mutableNewNotifications.value = true
}
}
}, {
if (it is HttpException) {
if (authHolder.isLoggedIn() && it.code() == HttpErrors.UNAUTHORIZED) {
logoutAndRefresh()
}
}
Timber.e(it, "Error fetching notifications")
})
}
private fun logoutAndRefresh() {
compositeDisposable += authService.logout()
.withDefaultSchedulers()
.subscribe({
mutableIsRefresh.value = true
}, {
Timber.e(it, "Error while logout")
mutableMessage.value = resource.getString(R.string.error)
})
}
fun checkAndReset(token: String, newPassword: String) {
val resetRequest = RequestPasswordReset(PasswordReset(token, newPassword))
if (authHolder.isLoggedIn()) {
compositeDisposable += authService.logout()
.withDefaultSchedulers()
.doOnSubscribe {
mutableDialogProgress.value = true
}.subscribe {
resetPassword(resetRequest)
}
} else
resetPassword(resetRequest)
}
private fun resetPassword(resetRequest: RequestPasswordReset) {
compositeDisposable += authService.resetPassword(resetRequest)
.withDefaultSchedulers()
.doOnSubscribe {
mutableDialogProgress.value = true
}.doFinally {
mutableDialogProgress.value = false
}.subscribe({
Timber.e(it.toString())
mutableMessage.value = resource.getString(R.string.reset_password_message)
mutableResetPasswordEmail.value = it.email
}, {
Timber.e(it, "Failed to reset password")
})
}
fun fetchSettings() {
compositeDisposable += settingsService.fetchSettings()
.withDefaultSchedulers()
.subscribe({
Timber.d("Settings fetched successfully")
}, {
Timber.e(it, "Error in fetching settings form API")
})
}
}
| apache-2.0 | bcdfbfae1ca7d756693cd00da8e9e164 | 39.016807 | 90 | 0.655817 | 5.662307 | false | false | false | false |
openMF/self-service-app | app/src/main/java/org/mifos/mobile/models/accounts/loan/RepaymentSchedule.kt | 1 | 1785 | package org.mifos.mobile.models.accounts.loan
import android.os.Parcelable
import com.google.gson.annotations.SerializedName
import kotlinx.android.parcel.Parcelize
import java.util.ArrayList
/**
* Created by Rajan Maurya on 04/03/17.
*/
@Parcelize
data class RepaymentSchedule(
@SerializedName("currency")
var currency: Currency,
@SerializedName("loanTermInDays")
var loanTermInDays: Int? = null,
@SerializedName("totalPrincipalDisbursed")
var totalPrincipalDisbursed: Double? = null,
@SerializedName("totalPrincipalExpected")
var totalPrincipalExpected: Double? = null,
@SerializedName("totalPrincipalPaid")
var totalPrincipalPaid: Double? = null,
@SerializedName("totalInterestCharged")
var totalInterestCharged: Double? = null,
@SerializedName("totalFeeChargesCharged")
var totalFeeChargesCharged: Double? = null,
@SerializedName("totalPenaltyChargesCharged")
var totalPenaltyChargesCharged: Double? = null,
@SerializedName("totalWaived")
var totalWaived: Double? = null,
@SerializedName("totalWrittenOff")
var totalWrittenOff: Double? = null,
@SerializedName("totalRepaymentExpected")
var totalRepaymentExpected: Double? = null,
@SerializedName("totalRepayment")
var totalRepayment: Double? = null,
@SerializedName("totalPaidInAdvance")
var totalPaidInAdvance: Double? = null,
@SerializedName("totalPaidLate")
var totalPaidLate: Double? = null,
@SerializedName("totalOutstanding")
var totalOutstanding: Double? = null,
@SerializedName("periods")
var periods: List<Periods> = ArrayList()
) : Parcelable | mpl-2.0 | 226e5e7ff0baaac260d05a8b49c86428 | 26.90625 | 55 | 0.680112 | 4.76 | false | false | false | false |
Kotlin/kotlinx.serialization | formats/json/commonMain/src/kotlinx/serialization/json/JsonElement.kt | 1 | 8986 | /*
* Copyright 2017-2022 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
*/
@file:Suppress("unused")
package kotlinx.serialization.json
import kotlinx.serialization.*
import kotlinx.serialization.json.internal.*
/**
* Class representing single JSON element.
* Can be [JsonPrimitive], [JsonArray] or [JsonObject].
*
* [JsonElement.toString] properly prints JSON tree as valid JSON, taking into account quoted values and primitives.
* Whole hierarchy is serializable, but only when used with [Json] as [JsonElement] is purely JSON-specific structure
* which has a meaningful schemaless semantics only for JSON.
*
* The whole hierarchy is [serializable][Serializable] only by [Json] format.
*/
@Serializable(JsonElementSerializer::class)
public sealed class JsonElement
/**
* Class representing JSON primitive value.
* JSON primitives include numbers, strings, booleans and special null value [JsonNull].
*/
@Serializable(JsonPrimitiveSerializer::class)
public sealed class JsonPrimitive : JsonElement() {
/**
* Indicates whether the primitive was explicitly constructed from [String] and
* whether it should be serialized as one. E.g. `JsonPrimitive("42")` is represented
* by a string, while `JsonPrimitive(42)` is not.
* These primitives will be serialized as `42` and `"42"` respectively.
*/
public abstract val isString: Boolean
/**
* Content of given element without quotes. For [JsonNull] this methods returns `null`
*/
public abstract val content: String
public override fun toString(): String = content
}
/**
* Creates [JsonPrimitive] from the given boolean.
*/
public fun JsonPrimitive(value: Boolean?): JsonPrimitive {
if (value == null) return JsonNull
return JsonLiteral(value, isString = false)
}
/**
* Creates [JsonPrimitive] from the given number.
*/
public fun JsonPrimitive(value: Number?): JsonPrimitive {
if (value == null) return JsonNull
return JsonLiteral(value, isString = false)
}
/**
* Creates [JsonPrimitive] from the given string.
*/
public fun JsonPrimitive(value: String?): JsonPrimitive {
if (value == null) return JsonNull
return JsonLiteral(value, isString = true)
}
/**
* Creates [JsonNull].
*/
@ExperimentalSerializationApi
@Suppress("FunctionName", "UNUSED_PARAMETER") // allows to call `JsonPrimitive(null)`
public fun JsonPrimitive(value: Nothing?): JsonNull = JsonNull
// JsonLiteral is deprecated for public use and no longer available. Please use JsonPrimitive instead
internal class JsonLiteral internal constructor(
body: Any,
public override val isString: Boolean
) : JsonPrimitive() {
public override val content: String = body.toString()
public override fun toString(): String =
if (isString) buildString { printQuoted(content) }
else content
// Compare by `content` and `isString`, because body can be kotlin.Long=42 or kotlin.String="42"
public override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other == null || this::class != other::class) return false
other as JsonLiteral
if (isString != other.isString) return false
if (content != other.content) return false
return true
}
@SuppressAnimalSniffer // Boolean.hashCode(boolean)
public override fun hashCode(): Int {
var result = isString.hashCode()
result = 31 * result + content.hashCode()
return result
}
}
/**
* Class representing JSON `null` value
*/
@Serializable(JsonNullSerializer::class)
public object JsonNull : JsonPrimitive() {
override val isString: Boolean get() = false
override val content: String = "null"
}
/**
* Class representing JSON object, consisting of name-value pairs, where value is arbitrary [JsonElement]
*
* Since this class also implements [Map] interface, you can use
* traditional methods like [Map.get] or [Map.getValue] to obtain Json elements.
*/
@Serializable(JsonObjectSerializer::class)
public class JsonObject(private val content: Map<String, JsonElement>) : JsonElement(), Map<String, JsonElement> by content {
public override fun equals(other: Any?): Boolean = content == other
public override fun hashCode(): Int = content.hashCode()
public override fun toString(): String {
return content.entries.joinToString(
separator = ",",
prefix = "{",
postfix = "}",
transform = { (k, v) ->
buildString {
printQuoted(k)
append(':')
append(v)
}
}
)
}
}
/**
* Class representing JSON array, consisting of indexed values, where value is arbitrary [JsonElement]
*
* Since this class also implements [List] interface, you can use
* traditional methods like [List.get] or [List.getOrNull] to obtain Json elements.
*/
@Serializable(JsonArraySerializer::class)
public class JsonArray(private val content: List<JsonElement>) : JsonElement(), List<JsonElement> by content {
public override fun equals(other: Any?): Boolean = content == other
public override fun hashCode(): Int = content.hashCode()
public override fun toString(): String = content.joinToString(prefix = "[", postfix = "]", separator = ",")
}
/**
* Convenience method to get current element as [JsonPrimitive]
* @throws IllegalArgumentException if current element is not a [JsonPrimitive]
*/
public val JsonElement.jsonPrimitive: JsonPrimitive
get() = this as? JsonPrimitive ?: error("JsonPrimitive")
/**
* Convenience method to get current element as [JsonObject]
* @throws IllegalArgumentException if current element is not a [JsonObject]
*/
public val JsonElement.jsonObject: JsonObject
get() = this as? JsonObject ?: error("JsonObject")
/**
* Convenience method to get current element as [JsonArray]
* @throws IllegalArgumentException if current element is not a [JsonArray]
*/
public val JsonElement.jsonArray: JsonArray
get() = this as? JsonArray ?: error("JsonArray")
/**
* Convenience method to get current element as [JsonNull]
* @throws IllegalArgumentException if current element is not a [JsonNull]
*/
public val JsonElement.jsonNull: JsonNull
get() = this as? JsonNull ?: error("JsonNull")
/**
* Returns content of the current element as int
* @throws NumberFormatException if current element is not a valid representation of number
*/
public val JsonPrimitive.int: Int get() = content.toInt()
/**
* Returns content of the current element as int or `null` if current element is not a valid representation of number
*/
public val JsonPrimitive.intOrNull: Int? get() = content.toIntOrNull()
/**
* Returns content of current element as long
* @throws NumberFormatException if current element is not a valid representation of number
*/
public val JsonPrimitive.long: Long get() = content.toLong()
/**
* Returns content of current element as long or `null` if current element is not a valid representation of number
*/
public val JsonPrimitive.longOrNull: Long? get() = content.toLongOrNull()
/**
* Returns content of current element as double
* @throws NumberFormatException if current element is not a valid representation of number
*/
public val JsonPrimitive.double: Double get() = content.toDouble()
/**
* Returns content of current element as double or `null` if current element is not a valid representation of number
*/
public val JsonPrimitive.doubleOrNull: Double? get() = content.toDoubleOrNull()
/**
* Returns content of current element as float
* @throws NumberFormatException if current element is not a valid representation of number
*/
public val JsonPrimitive.float: Float get() = content.toFloat()
/**
* Returns content of current element as float or `null` if current element is not a valid representation of number
*/
public val JsonPrimitive.floatOrNull: Float? get() = content.toFloatOrNull()
/**
* Returns content of current element as boolean
* @throws IllegalStateException if current element doesn't represent boolean
*/
public val JsonPrimitive.boolean: Boolean get() = content.toBooleanStrictOrNull() ?: throw IllegalStateException("$this does not represent a Boolean")
/**
* Returns content of current element as boolean or `null` if current element is not a valid representation of boolean
*/
public val JsonPrimitive.booleanOrNull: Boolean? get() = content.toBooleanStrictOrNull()
/**
* Content of the given element without quotes or `null` if current element is [JsonNull]
*/
public val JsonPrimitive.contentOrNull: String? get() = if (this is JsonNull) null else content
private fun JsonElement.error(element: String): Nothing =
throw IllegalArgumentException("Element ${this::class} is not a $element")
@PublishedApi
internal fun unexpectedJson(key: String, expected: String): Nothing =
throw IllegalArgumentException("Element $key is not a $expected")
| apache-2.0 | 8520f0f619abdb01566132ade5120f51 | 35.088353 | 150 | 0.71578 | 4.643928 | false | false | false | false |
Luistlvr1989/authentication | app/src/main/java/com/belatrix/authentication/ui/RegistrationActivity.kt | 1 | 2010 | package com.belatrix.authentication.ui
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.view.View
import com.belatrix.authentication.R
import com.belatrix.authentication.utils.ValidationUtils
import kotlinx.android.synthetic.main.activity_registration.*
@Suppress("UNUSED_PARAMETER")
class RegistrationActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_registration)
}
/**
* Validates the registration, and return all the errors
* to the views
*/
fun attemptRegister(view: View) {
var message: String? = null
var editText: View? = null
if (etFirstName.text.isEmpty()) {
tilFirstName.error = getString(R.string.error_required)
editText = etFirstName
}
if (etLastName.text.isEmpty()) {
tilLastName.error = getString(R.string.error_required)
editText = etLastName
}
if (etEmail.text.isEmpty()) {
message = getString(R.string.error_required)
}
else if (!ValidationUtils.isEmailValid(etEmail.text)) {
message = getString(R.string.error_email)
}
tilEmail.error = message
if (message != null) {
editText = etEmail
message = null
}
if (etPassword.text.isEmpty()) {
message = getString(R.string.error_required)
}
else if (!ValidationUtils.isPasswordValid(etPassword.text)) {
message = getString(R.string.error_password)
}
tilPassword.error = message
if (message != null) {
editText = tilPassword
}
if (editText != null) {
editText.requestFocus()
} else {
finish()
}
}
/**
* Returns to the login activity
*/
fun login(view: View) {
finish()
}
}
| apache-2.0 | 0f614b90e42c9c8eb207ac19b0423807 | 26.162162 | 69 | 0.602985 | 4.537246 | false | false | false | false |
markspit93/Github-Feed-Sample | app/src/main/kotlin/com/github/feed/sample/ui/main/MainActivity.kt | 1 | 4574 | package com.github.feed.sample.ui.main
import android.arch.lifecycle.ViewModelProviders
import android.os.Bundle
import android.support.annotation.ColorRes
import android.support.annotation.IdRes
import android.support.v4.view.GravityCompat
import android.view.Gravity
import android.view.Menu
import android.view.MenuItem
import android.widget.CheckBox
import com.github.feed.sample.R
import com.github.feed.sample.data.*
import com.github.feed.sample.data.model.Event
import com.github.feed.sample.di.viewmodel.ViewModelFactory
import com.github.feed.sample.ext.*
import com.github.feed.sample.ui.common.mvp.MvpActivity
import com.github.feed.sample.ui.details.DetailsActivity
import com.github.feed.sample.ui.eventlist.EventListFragment
import com.google.android.gms.oss.licenses.OssLicensesMenuActivity
import kotlinx.android.synthetic.main.activity_main.*
import kotlinx.android.synthetic.main.toolbar.*
import org.jetbrains.anko.intentFor
class MainActivity : MvpActivity<MainContract.View, MainPresenter, MainViewModel>(), MainContract.View {
companion object {
private const val FRAGMENT_TAG_EVENTS = "fragment_tag_events"
}
private var eventsFragment: EventListFragment? = null
private var checkBoxList = mutableListOf<CheckBox>()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
setSupportActionBar(toolbar)
eventsFragment = findFragment(FRAGMENT_TAG_EVENTS) as EventListFragment?
if (eventsFragment == null){
eventsFragment = EventListFragment().apply {
addFragment(this, R.id.container, FRAGMENT_TAG_EVENTS)
}
}
requireNotNull(eventsFragment).eventClick = onEventClicked
setupFilters()
}
override fun getViewModel(viewModelFactory: ViewModelFactory): MainViewModel {
return ViewModelProviders.of(this, viewModelFactory).get()
}
override fun onStart() {
super.onStart()
presenter.loadFilterSelections()
setTaskColor(getColorCompat(R.color.colorPrimary))
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
menuInflater.inflate(R.menu.menu_main, menu)
menu.findItem(R.id.menu_item_filter).isVisible = hasInternetConnection()
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
R.id.menu_item_filter -> drawerLayout.openDrawer(Gravity.END)
R.id.menu_item_licenses -> startActivity(intentFor<OssLicensesMenuActivity>())
}
return true
}
private val onEventClicked: (Event) -> Unit = { event ->
startActivityTransition(DetailsActivity.createIntent(this, event))
}
override fun onBackPressed() {
if (drawerLayout.isDrawerOpen(GravityCompat.END)) {
drawerLayout.closeDrawer(Gravity.END)
} else {
super.onBackPressed()
}
}
override fun selectFilter(tag: String, selected: Boolean) {
checkBoxList.find { it.tag as String == tag }?.isChecked = selected
}
private fun setupFilters() {
setupCheckBox(R.id.action_filter_create, R.color.orange_A400, EVENT_CREATE)
setupCheckBox(R.id.action_filter_delete, R.color.purple_A200, EVENT_DELETE)
setupCheckBox(R.id.action_filter_fork, R.color.green_A400, EVENT_FORK)
setupCheckBox(R.id.action_filter_pull_request, R.color.deep_purple_A200, EVENT_PULL_REQUEST)
setupCheckBox(R.id.action_filter_push, R.color.red_A200, EVENT_PUSH)
setupCheckBox(R.id.action_filter_watch, R.color.indigo_A400, EVENT_WATCH)
navigationView.setNavigationItemSelectedListener { item ->
(item.actionView as CheckBox).apply { post { isChecked = !isChecked } }
true
}
}
private fun setupCheckBox(@IdRes checkboxId: Int, @ColorRes colorId: Int, eventType: String) {
navigationView.findCheckbox(checkboxId).apply {
checkBoxList.add(this)
tag = eventType
isChecked = true
setButtonTintColor(colorId)
setOnCheckedChangeListener { _, isChecked ->
presenter.saveFilterSelection(tag as String, isChecked)
if (isChecked) {
requireNotNull(eventsFragment).unfilterEventType(eventType)
} else {
requireNotNull(eventsFragment).filterEventType(eventType)
}
}
}
}
}
| apache-2.0 | f2a835c32dca057d9174f0cd4960d33a | 35.301587 | 104 | 0.689768 | 4.537698 | false | false | false | false |
ageery/kwicket | kwicket-wicket-core/src/main/kotlin/org/kwicket/wicket/core/markup/html/panel/KPanel.kt | 1 | 2604 | package org.kwicket.wicket.core.markup.html.panel
import org.apache.wicket.behavior.Behavior
import org.apache.wicket.markup.html.panel.Panel
import org.apache.wicket.model.IModel
import org.kwicket.component.init
/**
* [Panel] with named and default constructor arguments.
*
* @param id id of the [Component]
* @param model optional [IModel] of the [Component]
* @param outputMarkupId optional flag indicating whether an id attribute will be created on the HTML element
* @param outputMarkupPlaceholderTag optional flag indicating whether an id attribtue will be created on the HTML
* element, creating a placeholder id if the component is initially not visible
* @param visible optional flag indicating whether the [Component] is visible
* @param enabled optional flag indicating whether the [Component] is enabled
* @param renderBodyOnly optional flag indicating whether only the [Component]'s HTML will be rendered or whether the
* tag the [Component] is attached to will also be rendered
* @param escapeModelStrings optional flag indicating whether the [Component]'s model String values will be escaped
* @param behaviors [List] of [Behavior]s to add to the [Component]
*/
abstract class KPanel(
id: String,
model: IModel<*>? = null,
outputMarkupId: Boolean? = null,
outputMarkupPlaceholderTag: Boolean? = null,
visible: Boolean? = null,
enabled: Boolean? = null,
renderBodyOnly: Boolean? = null,
escapeModelStrings: Boolean? = null,
behaviors: List<Behavior>? = null
) : Panel(id, model) {
constructor(
id: String,
model: IModel<*>? = null,
outputMarkupId: Boolean? = null,
outputMarkupPlaceholderTag: Boolean? = null,
visible: Boolean? = null,
enabled: Boolean? = null,
renderBodyOnly: Boolean? = null,
escapeModelStrings: Boolean? = null,
behavior: Behavior
) : this(
id = id,
model = model,
outputMarkupId = outputMarkupId,
outputMarkupPlaceholderTag = outputMarkupPlaceholderTag,
visible = visible,
enabled = enabled,
escapeModelStrings = escapeModelStrings,
renderBodyOnly = renderBodyOnly,
behaviors = listOf(behavior)
)
init {
init(
outputMarkupId = outputMarkupId,
outputMarkupPlaceholderTag = outputMarkupPlaceholderTag,
visible = visible,
enabled = enabled,
escapeModelStrings = escapeModelStrings,
renderBodyOnly = renderBodyOnly,
behaviors = behaviors
)
}
} | apache-2.0 | ac76e677425d7fc266b473bc3b3b9a34 | 36.753623 | 117 | 0.685868 | 4.988506 | false | false | false | false |
Dimigo-AppClass-Mission/SaveTheEarth | app/src/main/kotlin/me/hyemdooly/sangs/dimigo/app/project/receiver/ScreenOnOffReceiver.kt | 1 | 1276 | package me.hyemdooly.sangs.dimigo.app.project.receiver
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import me.hyemdooly.sangs.dimigo.app.project.database.DataController
import java.util.*
class ScreenOnOffReceiver : BroadcastReceiver() {
var dataController: DataController? = null
var firstTime: Long = System.currentTimeMillis()
var lastTime: Long = 0
var countTime: Long = 0
override fun onReceive(p0: Context?, p1: Intent?) {
dataController = DataController(p0!!)
when(p1?.action){
Intent.ACTION_SCREEN_OFF -> {
lastTime = System.currentTimeMillis()
if(!firstTime.equals(0)){
countTime = lastTime-firstTime
dataController!!.addTimeData("used", countTime, Date())
firstTime = lastTime
}
}
Intent.ACTION_SCREEN_ON -> {
lastTime = System.currentTimeMillis()
if(!firstTime.equals(0)){
countTime = lastTime-firstTime
dataController!!.addTimeData("unused", countTime, Date())
firstTime = lastTime
}
}
}
}
} | gpl-3.0 | fe661534aece3fb033681b85d85ebee6 | 33.513514 | 77 | 0.586991 | 5.145161 | false | false | false | false |
lindar-open/acolyte | src/main/kotlin/lindar/acolyte/vo/pagination.kt | 1 | 3463 | package lindar.acolyte.vo
import java.util.function.Function
data class PaginatedCollection<out T>(val contents: List<T>, val pagination: PaginationVO, val sort: SortVO)
data class CursorPaginatedCollection<T>(val contents: List<T>, val pagination: CursorPaginationVO, val sort: SortVO) {
fun <U> map(converter: Function<T, U>): CursorPaginatedCollection<U> {
return CursorPaginatedCollection(contents.map(converter::apply), pagination, sort)
}
fun filter(predicate: Function<T, Boolean>): CursorPaginatedCollection<T> {
return CursorPaginatedCollection(contents.filter(predicate::apply), pagination, sort)
}
}
data class PaginationVO(val page: Int, val size: Int, val totalPages: Int, var totalElements: Long) {
companion object Builder {
private var builderPage = 0
private var builderSize = 20
private var builderTotalPages = 0
private var builderTotalElements = 0L
fun page(page: Int): PaginationVO.Builder {
this.builderPage = page
return this
}
fun size(size: Int): PaginationVO.Builder {
this.builderSize = size
return this
}
fun totalPages(totalPages: Int): PaginationVO.Builder {
this.builderTotalPages = totalPages
return this
}
fun totalElements(totalElements: Long): PaginationVO.Builder {
this.builderTotalElements = totalElements
return this
}
fun build() = PaginationVO(builderPage, builderSize, builderTotalPages, builderTotalElements)
}
}
data class CursorPaginationVO(val cursor: String?, val size: Int) {
val hasNext: Boolean
get() = this.cursor != null
companion object Builder {
private var builderCursor: String? = null
private var builderSize = 20
fun cursor(cursor: String?): CursorPaginationVO.Builder {
this.builderCursor = cursor
return this
}
fun size(size: Int): CursorPaginationVO.Builder {
this.builderSize = size
return this
}
fun build() = CursorPaginationVO(builderCursor, builderSize)
}
}
data class PageableVO(val page: Int, val size: Int, val sort: List<SortVO>? = null) {
companion object Builder {
private var builderPage = 0
private var builderSize = 20
private var builderSort: List<SortVO>? = null
fun page(page: Int): PageableVO.Builder {
this.builderPage = page
return this
}
fun size(size: Int): PageableVO.Builder {
this.builderSize = size
return this
}
fun sort(sort: List<SortVO>): PageableVO.Builder {
this.builderSort = sort
return this
}
fun build() = PageableVO(builderPage, builderSize, builderSort)
}
}
data class SortVO(val field: String, val dir: SortDirection = SortDirection.ASC) {
companion object Builder {
private var builderField = ""
private var builderDir = SortDirection.ASC
fun field(field: String): SortVO.Builder {
this.builderField = field
return this
}
fun dir(dir: SortDirection): SortVO.Builder {
this.builderDir = dir
return this
}
fun build() = SortVO(builderField, builderDir)
}
}
enum class SortDirection {
DESC, ASC
}
| apache-2.0 | b74693cd395f12cb49dec6e476a2d889 | 28.10084 | 118 | 0.628068 | 4.717984 | false | false | false | false |
grassrootza/grassroot-android-v2 | app/src/main/java/za/org/grassroot2/util/LastModifiedFormatter.kt | 1 | 1807 | package za.org.grassroot2.util
import android.content.Context
import java.util.Calendar
import java.util.concurrent.TimeUnit
import za.org.grassroot2.R
object LastModifiedFormatter {
fun lastSeen(c: Context, datetimeInMillis: Long): String {
var out = ""
try {
val calendar = Calendar.getInstance()
val diff = calendar.timeInMillis - datetimeInMillis
val difSeconds = TimeUnit.MILLISECONDS.toSeconds(diff).toInt()
val difMinutes = TimeUnit.MILLISECONDS.toMinutes(diff).toInt()
val difHours = TimeUnit.MILLISECONDS.toHours(diff).toInt()
val difDay = TimeUnit.MILLISECONDS.toDays(diff).toInt()
val difMonth = difDay / 30
val difYear = difMonth / 12
if (difSeconds <= 0) {
out = "Now"
} else if (difSeconds < 60) {
out = c.resources.getQuantityString(R.plurals.last_modified, difSeconds, difSeconds, "second")
} else if (difMinutes < 60) {
out = c.resources.getQuantityString(R.plurals.last_modified, difMinutes, difMinutes, "minute")
} else if (difHours < 24) {
out = c.resources.getQuantityString(R.plurals.last_modified, difHours, difHours, "hour")
} else if (difDay < 30) {
out = c.resources.getQuantityString(R.plurals.last_modified, difDay, difDay, "day")
} else if (difMonth < 12) {
out = c.resources.getQuantityString(R.plurals.last_modified, difMonth, difMonth, "month")
} else {
out = c.resources.getQuantityString(R.plurals.last_modified, difYear, difYear, "year")
}
} catch (e: Exception) {
e.printStackTrace()
}
return out
}
}
| bsd-3-clause | 146116aed3bcc342e2cd06ef6d5418e1 | 40.068182 | 110 | 0.600996 | 4.23185 | false | false | false | false |
alphafoobar/intellij-community | platform/built-in-server/src/org/jetbrains/builtInWebServer/NetService.kt | 2 | 4569 | package org.jetbrains.builtInWebServer
import com.intellij.execution.ExecutionException
import com.intellij.execution.filters.TextConsoleBuilder
import com.intellij.execution.process.OSProcessHandler
import com.intellij.execution.process.ProcessAdapter
import com.intellij.execution.process.ProcessEvent
import com.intellij.execution.ui.ConsoleViewContentType
import com.intellij.openapi.Disposable
import com.intellij.openapi.actionSystem.ActionGroup
import com.intellij.openapi.actionSystem.DefaultActionGroup
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Key
import com.intellij.util.Consumer
import com.intellij.util.net.NetUtils
import org.jetbrains.concurrency.AsyncPromise
import org.jetbrains.concurrency.AsyncValueLoader
import org.jetbrains.concurrency.Promise
import org.jetbrains.util.concurrency
import org.jetbrains.util.concurrency.toPromise
import javax.swing.Icon
public abstract class NetService @jvmOverloads protected constructor(protected val project: Project, private val consoleManager: ConsoleManager = ConsoleManager()) : Disposable {
companion object {
protected val LOG: Logger = Logger.getInstance(javaClass<NetService>())
}
protected val processHandler: AsyncValueLoader<OSProcessHandler> = object : AsyncValueLoader<OSProcessHandler>() {
override fun isCancelOnReject() = true
private fun doGetProcessHandler(port: Int): OSProcessHandler? {
try {
return createProcessHandler(project, port)
}
catch (e: ExecutionException) {
LOG.error(e)
return null
}
}
override fun load(promise: AsyncPromise<OSProcessHandler>): Promise<OSProcessHandler> {
val port = NetUtils.findAvailableSocketPort()
val processHandler = doGetProcessHandler(port)
if (processHandler == null) {
promise.setError("rejected")
return promise
}
promise.rejected(object : Consumer<Throwable> {
override fun consume(error: Throwable) {
processHandler.destroyProcess()
Promise.logError(LOG, error)
}
})
val processListener = MyProcessAdapter()
processHandler.addProcessListener(processListener)
processHandler.startNotify()
if (promise.getState() === Promise.State.REJECTED) {
return promise
}
ApplicationManager.getApplication().executeOnPooledThread(object : Runnable {
override fun run() {
if (promise.getState() !== Promise.State.REJECTED) {
try {
connectToProcess(promise.toPromise(), port, processHandler, processListener)
}
catch (e: Throwable) {
if (!promise.setError(e)) {
LOG.error(e)
}
}
}
}
})
return promise
}
override fun disposeResult(processHandler: OSProcessHandler) {
try {
closeProcessConnections()
}
finally {
processHandler.destroyProcess()
}
}
}
throws(ExecutionException::class)
protected abstract fun createProcessHandler(project: Project, port: Int): OSProcessHandler?
protected open fun connectToProcess(promise: concurrency.AsyncPromise<OSProcessHandler>, port: Int, processHandler: OSProcessHandler, errorOutputConsumer: Consumer<String>) {
promise.setResult(processHandler)
}
protected abstract fun closeProcessConnections()
override fun dispose() {
processHandler.reset()
}
protected open fun configureConsole(consoleBuilder: TextConsoleBuilder) {
}
protected abstract fun getConsoleToolWindowId(): String
protected abstract fun getConsoleToolWindowIcon(): Icon
public open fun getConsoleToolWindowActions(): ActionGroup = DefaultActionGroup()
private inner class MyProcessAdapter : ProcessAdapter(), Consumer<String> {
override fun onTextAvailable(event: ProcessEvent, outputType: Key<*>) {
print(event.getText(), ConsoleViewContentType.getConsoleViewType(outputType))
}
private fun print(text: String, contentType: ConsoleViewContentType) {
consoleManager.getConsole(this@NetService).print(text, contentType)
}
override fun processTerminated(event: ProcessEvent) {
processHandler.reset()
print("${getConsoleToolWindowId()} terminated\n", ConsoleViewContentType.SYSTEM_OUTPUT)
}
override fun consume(message: String) {
print(message, ConsoleViewContentType.ERROR_OUTPUT)
}
}
} | apache-2.0 | bcebeb4f64254d3c5c7dd173bbd4cc90 | 33.360902 | 178 | 0.727511 | 5.168552 | false | false | false | false |
didi/DoraemonKit | Android/dokit/src/main/java/com/didichuxing/doraemonkit/kit/dokitforweb/DokitForWebKit.kt | 1 | 1573 | package com.didichuxing.doraemonkit.kit.dokitforweb
import android.app.Activity
import android.content.Context
import com.didichuxing.doraemonkit.R
import com.didichuxing.doraemonkit.aop.DokitPluginConfig
import com.didichuxing.doraemonkit.kit.AbstractKit
import com.didichuxing.doraemonkit.kit.weaknetwork.WeakNetworkFragment
import com.didichuxing.doraemonkit.util.DoKitCommUtil
import com.didichuxing.doraemonkit.util.ToastUtils
import com.google.auto.service.AutoService
/**
* ================================================
* 作 者:jint(金台)
* 版 本:1.0
* 创建日期:2019-09-24-17:05
* 描 述:数据库远程访问入口 去掉
* 修订历史:
* ================================================
*/
@AutoService(AbstractKit::class)
class DokitForWebKit : AbstractKit() {
override val name: Int
get() = R.string.dk_kit_dokit_for_web
override val icon: Int
get() = R.mipmap.dk_dokit_for_web
override fun onClickWithReturn(activity: Activity): Boolean {
if (!DokitPluginConfig.SWITCH_DOKIT_PLUGIN) {
ToastUtils.showShort(DoKitCommUtil.getString(R.string.dk_plugin_close_tip))
return false
}
startUniversalActivity(DoKitForWebJsInjectFragment::class.java, activity, null, true)
return true
}
override fun onAppInit(context: Context?) {
DokitForWeb.loadConfig()
}
override val isInnerKit: Boolean
get() = true
override fun innerKitId(): String {
return "dokit_sdk_platform_ck_dokit_for_web"
}
}
| apache-2.0 | c47be9a9fb90d605c90e93a5ed96a7af | 31.021277 | 93 | 0.66711 | 3.981481 | false | true | false | false |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.