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
jorjoluiso/QuijoteLui
src/main/kotlin/com/quijotelui/electronico/comprobantes/factura/Pago.kt
1
544
package comprobantes.factura import java.math.BigDecimal import javax.xml.bind.annotation.XmlElement import javax.xml.bind.annotation.XmlRootElement import javax.xml.bind.annotation.XmlType @XmlRootElement @XmlType(propOrder= arrayOf( "formaPago", "total", "plazo", "unidadTiempo")) class Pago ( @XmlElement var formaPago: String? = null, @XmlElement var total: BigDecimal? = null, @XmlElement var plazo: String? = null, @XmlElement var unidadTiempo: String? = null )
gpl-3.0
bf874acdb085290f8bba19663ec87bb6
23.772727
52
0.678309
3.804196
false
false
false
false
mightyfrog/S4FD
app/src/main/java/org/mightyfrog/android/s4fd/data/KHCharacter.kt
1
1542
package org.mightyfrog.android.s4fd.data import com.google.gson.annotations.Expose import com.google.gson.annotations.SerializedName import com.raizlabs.android.dbflow.annotation.Column import com.raizlabs.android.dbflow.annotation.PrimaryKey import com.raizlabs.android.dbflow.annotation.Table import com.raizlabs.android.dbflow.structure.BaseModel /** * @author Shigehiro Soejima */ @Table(database = AppDatabase::class) class KHCharacter : BaseModel() { @Column @SerializedName("fullUrl") @Expose var fullUrl: String? = null @Column @SerializedName("style") @Expose var style: String? = null @Column @SerializedName("mainImageUrl") @Expose var mainImageUrl: String? = null @Column @SerializedName("thumbnailUrl") @Expose var thumbnailUrl: String? = null @Column @SerializedName("description") @Expose var description: String? = null @Column @SerializedName("colorTheme") @Expose var colorTheme: String? = null @Column @SerializedName("name") @Expose var name: String? = null @Column @SerializedName("displayName") @Expose var displayName: String? = null @PrimaryKey @Column @SerializedName("id") @Expose var id: Int = 0 override fun toString(): String { return "KHCharacter(fullUrl=$fullUrl, style=$style, mainImageUrl=$mainImageUrl, thumbnailUrl=$thumbnailUrl, description=$description, colorTheme=$colorTheme, name=$name, displayName=$displayName, id=$id)" } }
apache-2.0
a351215cc956a1e868910916cf44a3b2
23.109375
212
0.69585
4.247934
false
false
false
false
kiruto/debug-bottle
components/src/main/kotlin/com/exyui/android/debugbottle/components/DTDrawerActivity.kt
1
13169
package com.exyui.android.debugbottle.components import android.Manifest import android.app.ActivityManager import android.content.Intent import android.net.Uri import android.os.Bundle import android.support.annotation.DrawableRes import android.support.annotation.IdRes import android.support.annotation.StringRes import android.support.v7.app.ActionBarDrawerToggle import android.support.v4.widget.DrawerLayout import android.support.v7.app.AlertDialog import android.support.v7.app.AppCompatActivity import android.view.* import android.widget.* import com.squareup.leakcanary.internal.DisplayLeakActivity import com.exyui.android.debugbottle.components.fragments.* import com.exyui.android.debugbottle.components.guide.IntroductionActivity /** * Created by yuriel on 9/3/16. * * The main Activity of Debug Bottle */ internal class DTDrawerActivity : AppCompatActivity(), DialogsCollection.SPDialogAction, __ContentFragment.DrawerActivity { private var contentFragment: __ContentFragment? = null companion object { val KEY_SELECTED = "KEY_SELECTED" val KEY_SHOW_DRAWER = "KEY_SHOW_DRAWER" /** * Intent "selected item" must choose an string resource from items in this array. */ @Suppress("unused") val VALUE_SELECTED = R.array.__dt_drawer_items } private val titles: Array<String> by lazy { resources.getStringArray(R.array.__dt_drawer_items) } private val drawerLayout by lazy { findViewById(R.id.__dt_drawer_layout) as DrawerLayout } private val drawerRoot by lazy { findViewById(R.id.__dt_drawer_root) as ViewGroup } private val drawerListView by lazy { (findViewById(R.id.__dt_left_drawer) as ListView).apply { adapter = DrawerAdapter(titles) setOnItemClickListener { _: AdapterView<*>?, _: View?, position: Int, _: Long -> selectItem(position) } } } private val contentFrame by lazy { findViewById(R.id.__dt_content_frame) as ViewGroup } private val drawerToggle by lazy { object: ActionBarDrawerToggle(this, drawerLayout, R.string.__dt_drawer_open, R.string.__dt_drawer_close) { override fun onDrawerOpened(drawerView: View?) { super.onDrawerOpened(drawerView) invalidateOptionsMenu() // creates call to onPrepareOptionsMenu() } override fun onDrawerClosed(drawerView: View?) { super.onDrawerClosed(drawerView) invalidateOptionsMenu() // creates call to onPrepareOptionsMenu() } }.apply { setHomeAsUpIndicator(R.drawable.__dt_ic_bottle_24dp) } } private val infoLayout by lazy { (findViewById(R.id.__dt_info) as ViewGroup).apply { setOnClickListener { AlertDialog.Builder(this@DTDrawerActivity) .setIcon(R.drawable.__dt_ic_bottle_24dp) .setTitle(R.string.__dt_info) .setMessage(R.string.__dt_info_introduction) .setNegativeButton(R.string.__dt_close) { _, _ -> } .setNeutralButton(R.string.__dt_github) { _, _ -> val url = DTSettings.GITHUB_URL val intent = Intent(Intent.ACTION_VIEW) intent.data = Uri.parse(url) startActivity(intent) } .show() } } } private val introLayout by lazy { (findViewById(R.id.__dt_helper) as ViewGroup).apply { setOnClickListener { // To start IntroductionActivity, need a AppCompatTheme. // But this module does't has an access to AppCompatTheme. val intent = Intent(this@DTDrawerActivity, IntroductionActivity::class.java) val clazz = ContextThemeWrapper::class.java val method = clazz.getMethod("getThemeResId") method.isAccessible = true val themeResId = method.invoke(this) as Int intent.putExtra("theme", themeResId) startActivity(intent) } } } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) if (ActivityManager.isUserAMonkey()) { finish() return } setContentView(R.layout.__activity_dt_drawer) drawerLayout.addDrawerListener(drawerToggle) supportActionBar?.setDisplayHomeAsUpEnabled(true) supportActionBar?.setHomeButtonEnabled(true) supportActionBar?.setHomeAsUpIndicator(R.drawable.__dt_ic_bottle_24dp) drawerListView; infoLayout; introLayout val selectedItem = intent?.extras?.getInt(KEY_SELECTED) val showDrawer = intent?.extras?.getBoolean(KEY_SHOW_DRAWER) if (null == selectedItem || 0 == selectedItem) { selectItem(0) if (showDrawer == true) { drawerLayout.openDrawer(Gravity.LEFT) } } else { selectItemByRes(selectedItem) } } override fun onResume() { super.onResume() if (isSystemAlertPermissionGranted()) { runBubbleService() } } override fun onOptionsItemSelected(item: MenuItem?): Boolean { if (drawerToggle.onOptionsItemSelected(item)) { return true } return super.onOptionsItemSelected(item) } override fun setTitle(title: CharSequence?) { super.setTitle(title) supportActionBar?.title = title } override fun onBackPressed() { if (contentFragment?.onBackPressed() != true) { when { drawerLayout.isDrawerOpen(Gravity.LEFT) -> drawerLayout.closeDrawers() contentFragment?.isHome != true -> selectItem(0) else -> super.onBackPressed() } } } override fun updateSPViews() { val f = supportFragmentManager.findFragmentByTag(__SPViewerFragment.TAG) as __SPViewerFragment? f?.updateSPViews() } override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) { if (requestCode > -1 && requestCode < __StatusFragment.permissions.size) { //val permission = __StatusFragment.permissions[requestCode] updatePermissionStatus() } /** * Bubble service must run before add bubble view. */ if (!isSystemAlertPermissionGranted()) { requestingPermissionDrawOverOtherApps(null) } else { runBubbleService() } } private fun updatePermissionStatus() { val f = supportFragmentManager.findFragmentByTag(__StatusFragment.TAG) as __StatusFragment? f?: return f.updatePermissionStatus() } private fun s(@IdRes id: Int): String = resources.getString(id) override fun selectItemByRes(@StringRes res: Int) { selectItem(getString(res)) } private fun selectItem(title: String) { val i = titles.indexOf(title) if (-1 == i) return selectItem(i) } private fun selectItem(position: Int) { var fragment: __ContentFragment? = null // Create fragment by it's title when (titles[position]) { // Status fragment s(R.string.__dt_status) -> { fragment = __StatusFragment() } // All Activities fragment s(R.string.__dt_all_activities) -> { fragment = __InjectorFragment.newInstance(__InjectorFragment.TYPE_ALL_ACTIVITIES) } // Intent entries fragment s(R.string.__dt_intents) -> { fragment = __InjectorFragment.newInstance(__InjectorFragment.TYPE_INTENT) } // Runnable entries fragment s(R.string.__dt_runnable) -> { fragment = __InjectorFragment.newInstance(__InjectorFragment.TYPE_RUNNABLE) } // Shared Preferences editor fragment s(R.string.__dt_sp_viewer) -> { fragment = __SPViewerFragment() } // Block canary fragment s(R.string.__dt_blocks) -> { fragment = __DisplayBlockFragment() } // Network sniffer fragment s(R.string.__dt_network_traffics) -> { fragment = __DisplayHttpBlockFragment() } // Leak canary fragment s(R.string.__dt_leaks) -> { if (RunningFeatureMgr.has(RunningFeatureMgr.LEAK_CANARY)) { val intent = Intent(this, DisplayLeakActivity::class.java) startActivity(intent) } else { Toast.makeText(this, R.string.__dt_should_enable_leak_canary, Toast.LENGTH_SHORT).show() } return } // Crash report fragment s(R.string.__dt_crashes) -> { fragment = __DisplayCrashBlockFragment() } // Feedback fragment s(R.string.__dt_feedback) -> { fragment = __WebViewFragment.newInstance("${DTSettings.GITHUB_URL}/issues") } // Github fragment s(R.string.__dt_project) -> { fragment = __WebViewFragment.newInstance(DTSettings.GITHUB_URL) } // Settings fragment s(R.string.__dt_settings) -> { fragment = __SettingsFragment() } // Test s(R.string.__dt_black_box_testing) -> { if (isSystemAlertPermissionGranted()) { fragment = __TestSettingsFragment() } else { requestingPermissionDrawOverOtherApps(null) return } } // None else -> { } } if (null != fragment) { supportFragmentManager.beginTransaction() .replace(R.id.__dt_content_frame, fragment, fragment.TAG) .commit() contentFragment = fragment } drawerListView.setItemChecked(position, true) title = titles[position] drawerLayout.closeDrawer(drawerRoot) } internal inner class DrawerAdapter(private val titles: Array<String>): BaseAdapter() { // Menu item's title to icon map private val menu by lazy { titles.map { // Icon color is #8A000000 DrawerMenuItem(it, when (it) { s(R.string.__dt_status) -> R.drawable.__ic_home_black_24dp s(R.string.__dt_all_activities) -> R.drawable.__ic_find_in_page_black_24dp s(R.string.__dt_intents) -> R.drawable.__ic_android_black_24dp s(R.string.__dt_runnable) -> R.drawable.__ic_clear_all_black_24dp s(R.string.__dt_sp_viewer) -> R.drawable.__ic_edit_black_24dp s(R.string.__dt_blocks) -> R.drawable.__ic_block_black_24dp s(R.string.__dt_network_traffics) -> R.drawable.__ic_http_black_24dp s(R.string.__dt_leaks) -> R.drawable.__ic_bug_report_black_24dp s(R.string.__dt_settings) -> R.drawable.__ic_settings_black_24dp s(R.string.__dt_crashes) -> R.drawable.__ic_report_problem_black_24dp s(R.string.__dt_feedback) -> R.drawable.__ic_feedback_black_24dp s(R.string.__dt_project) -> R.drawable.__ic_code_black_24dp s(R.string.__dt_black_box_testing) -> R.drawable.__ic_fast_forward_black_24dp else -> R.drawable.__ic_info_outline_black_24dp }) } } override fun getCount(): Int = titles.size override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View? { var view = convertView val item = menu[position] (view?.let { view?.tag as ViewHolder }?: ViewHolder().apply { view = LayoutInflater.from(this@DTDrawerActivity).inflate(R.layout.__item_drawer_menu, parent, false) icon = view?.findViewById(R.id.__dt_icon) as ImageView title = view?.findViewById(R.id.__dt_item_title) as TextView view?.tag = this }).apply { icon?.setImageResource(item.icon) title?.text = item.title } return view } override fun getItem(position: Int): String = titles[position] override fun getItemId(position: Int): Long = position.toLong() } internal class ViewHolder { var icon: ImageView? = null var title: TextView? = null } internal data class DrawerMenuItem( val title: String, @DrawableRes val icon: Int ) }
apache-2.0
4eb978c60db39c70edfdb2d9f12e2c27
35.280992
123
0.571494
4.809715
false
false
false
false
googlemaps/android-maps-compose
maps-compose/src/main/java/com/google/maps/android/compose/GoogleMap.kt
1
9103
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.maps.android.compose import android.content.ComponentCallbacks import android.content.res.Configuration import android.location.Location import android.os.Bundle import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.PaddingValues import androidx.compose.runtime.Composable import androidx.compose.runtime.Composition import androidx.compose.runtime.CompositionContext import androidx.compose.runtime.DisposableEffect import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.MutableState import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.rememberCompositionContext import androidx.compose.runtime.rememberUpdatedState import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalInspectionMode import androidx.compose.ui.platform.LocalLifecycleOwner import androidx.compose.ui.viewinterop.AndroidView import androidx.lifecycle.Lifecycle import androidx.lifecycle.LifecycleEventObserver import com.google.android.gms.maps.GoogleMapOptions import com.google.android.gms.maps.LocationSource import com.google.android.gms.maps.MapView import com.google.android.gms.maps.model.LatLng import com.google.android.gms.maps.model.PointOfInterest import com.google.maps.android.ktx.awaitMap import kotlinx.coroutines.awaitCancellation /** * A compose container for a [MapView]. * * @param modifier Modifier to be applied to the GoogleMap * @param cameraPositionState the [CameraPositionState] to be used to control or observe the map's * camera state * @param contentDescription the content description for the map used by accessibility services to * describe the map. If none is specified, the default is "Google Map". * @param googleMapOptionsFactory the block for creating the [GoogleMapOptions] provided when the * map is created * @param properties the properties for the map * @param locationSource the [LocationSource] to be used to provide location data * @param uiSettings the [MapUiSettings] to be used for UI-specific settings on the map * @param indoorStateChangeListener listener for indoor building state changes * @param onMapClick lambda invoked when the map is clicked * @param onMapLoaded lambda invoked when the map is finished loading * @param onMyLocationButtonClick lambda invoked when the my location button is clicked * @param onMyLocationClick lambda invoked when the my location dot is clicked * @param onPOIClick lambda invoked when a POI is clicked * @param contentPadding the padding values used to signal that portions of the map around the edges * may be obscured. The map will move the Google logo, etc. to avoid overlapping the padding. * @param content the content of the map */ @Composable public fun GoogleMap( modifier: Modifier = Modifier, cameraPositionState: CameraPositionState = rememberCameraPositionState(), contentDescription: String? = null, googleMapOptionsFactory: () -> GoogleMapOptions = { GoogleMapOptions() }, properties: MapProperties = DefaultMapProperties, locationSource: LocationSource? = null, uiSettings: MapUiSettings = DefaultMapUiSettings, indoorStateChangeListener: IndoorStateChangeListener = DefaultIndoorStateChangeListener, onMapClick: (LatLng) -> Unit = {}, onMapLongClick: (LatLng) -> Unit = {}, onMapLoaded: () -> Unit = {}, onMyLocationButtonClick: () -> Boolean = { false }, onMyLocationClick: (Location) -> Unit = {}, onPOIClick: (PointOfInterest) -> Unit = {}, contentPadding: PaddingValues = NoPadding, content: (@Composable @GoogleMapComposable () -> Unit)? = null, ) { // When in preview, early return a Box with the received modifier preserving layout if (LocalInspectionMode.current) { Box(modifier = modifier) return } val context = LocalContext.current val mapView = remember { MapView(context, googleMapOptionsFactory()) } AndroidView(modifier = modifier, factory = { mapView }) MapLifecycle(mapView) // rememberUpdatedState and friends are used here to make these values observable to // the subcomposition without providing a new content function each recomposition val mapClickListeners = remember { MapClickListeners() }.also { it.indoorStateChangeListener = indoorStateChangeListener it.onMapClick = onMapClick it.onMapLongClick = onMapLongClick it.onMapLoaded = onMapLoaded it.onMyLocationButtonClick = onMyLocationButtonClick it.onMyLocationClick = onMyLocationClick it.onPOIClick = onPOIClick } val currentLocationSource by rememberUpdatedState(locationSource) val currentCameraPositionState by rememberUpdatedState(cameraPositionState) val currentContentPadding by rememberUpdatedState(contentPadding) val currentUiSettings by rememberUpdatedState(uiSettings) val currentMapProperties by rememberUpdatedState(properties) val parentComposition = rememberCompositionContext() val currentContent by rememberUpdatedState(content) LaunchedEffect(Unit) { disposingComposition { mapView.newComposition(parentComposition) { MapUpdater( contentDescription = contentDescription, cameraPositionState = currentCameraPositionState, clickListeners = mapClickListeners, contentPadding = currentContentPadding, locationSource = currentLocationSource, mapProperties = currentMapProperties, mapUiSettings = currentUiSettings, ) currentContent?.invoke() } } } } private suspend inline fun disposingComposition(factory: () -> Composition) { val composition = factory() try { awaitCancellation() } finally { composition.dispose() } } private suspend inline fun MapView.newComposition( parent: CompositionContext, noinline content: @Composable () -> Unit ): Composition { val map = awaitMap() return Composition( MapApplier(map, this), parent ).apply { setContent(content) } } /** * Registers lifecycle observers to the local [MapView]. */ @Composable private fun MapLifecycle(mapView: MapView) { val context = LocalContext.current val lifecycle = LocalLifecycleOwner.current.lifecycle val previousState = remember { mutableStateOf(Lifecycle.Event.ON_CREATE) } DisposableEffect(context, lifecycle, mapView) { val mapLifecycleObserver = mapView.lifecycleObserver(previousState) val callbacks = mapView.componentCallbacks() lifecycle.addObserver(mapLifecycleObserver) context.registerComponentCallbacks(callbacks) onDispose { lifecycle.removeObserver(mapLifecycleObserver) context.unregisterComponentCallbacks(callbacks) mapView.onDestroy() mapView.removeAllViews() } } } private fun MapView.lifecycleObserver(previousState: MutableState<Lifecycle.Event>): LifecycleEventObserver = LifecycleEventObserver { _, event -> event.targetState when (event) { Lifecycle.Event.ON_CREATE -> { // Skip calling mapView.onCreate if the lifecycle did not go through onDestroy - in // this case the GoogleMap composable also doesn't leave the composition. So, // recreating the map does not restore state properly which must be avoided. if (previousState.value != Lifecycle.Event.ON_STOP) { this.onCreate(Bundle()) } } Lifecycle.Event.ON_START -> this.onStart() Lifecycle.Event.ON_RESUME -> this.onResume() Lifecycle.Event.ON_PAUSE -> this.onPause() Lifecycle.Event.ON_STOP -> this.onStop() Lifecycle.Event.ON_DESTROY -> { //handled in onDispose } else -> throw IllegalStateException() } previousState.value = event } private fun MapView.componentCallbacks(): ComponentCallbacks = object : ComponentCallbacks { override fun onConfigurationChanged(config: Configuration) {} override fun onLowMemory() { [email protected]() } }
apache-2.0
9da3762252d901f0f88526a473da80ec
40.949309
109
0.724926
5.157507
false
false
false
false
androidx/androidx
compose/ui/ui/src/desktopMain/kotlin/androidx/compose/ui/awt/ComposeWindowDelegate.desktop.kt
3
6059
/* * Copyright 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.ui.awt import androidx.compose.runtime.Composable import androidx.compose.runtime.CompositionLocalProvider import androidx.compose.ui.input.key.KeyEvent import androidx.compose.ui.window.LocalWindow import androidx.compose.ui.window.UndecoratedWindowResizer import org.jetbrains.skiko.ClipComponent import org.jetbrains.skiko.GraphicsApi import org.jetbrains.skiko.OS import org.jetbrains.skiko.SkiaLayer import org.jetbrains.skiko.hostOs import java.awt.Color import java.awt.Component import java.awt.Window import java.awt.event.MouseListener import java.awt.event.MouseMotionListener import java.awt.event.MouseWheelListener import javax.swing.JLayeredPane internal class ComposeWindowDelegate( private val window: Window, private val isUndecorated: () -> Boolean ) { private var isDisposed = false // AWT can leak JFrame in some cases // (see https://github.com/JetBrains/compose-jb/issues/1688), // so we nullify layer on dispose, to prevent keeping // big objects in memory (like the whole LayoutNode tree of the window) private var _layer: ComposeLayer? = ComposeLayer() private val layer get() = requireNotNull(_layer) { "ComposeLayer is disposed" } val undecoratedWindowResizer = UndecoratedWindowResizer(window) private val _pane = object : JLayeredPane() { override fun setBounds(x: Int, y: Int, width: Int, height: Int) { layer.component.setSize(width, height) super.setBounds(x, y, width, height) } override fun add(component: Component): Component { val clipComponent = ClipComponent(component) clipMap[component] = clipComponent layer.component.clipComponents.add(clipComponent) return add(component, Integer.valueOf(0)) } override fun remove(component: Component) { layer.component.clipComponents.remove(clipMap[component]!!) clipMap.remove(component) super.remove(component) } override fun addNotify() { super.addNotify() layer.component.requestFocus() } override fun getPreferredSize() = if (isPreferredSizeSet) super.getPreferredSize() else layer.component.preferredSize init { layout = null super.add(layer.component, 1) } fun dispose() { super.remove(layer.component) } } val pane get() = _pane private val clipMap = mutableMapOf<Component, ClipComponent>() init { setContent {} } fun add(component: Component): Component { return _pane.add(component) } fun remove(component: Component) { _pane.remove(component) } var fullscreen: Boolean get() = layer.component.fullscreen set(value) { layer.component.fullscreen = value } fun setContent( onPreviewKeyEvent: (KeyEvent) -> Boolean = { false }, onKeyEvent: (KeyEvent) -> Boolean = { false }, content: @Composable () -> Unit ) { layer.setContent( onPreviewKeyEvent = onPreviewKeyEvent, onKeyEvent = onKeyEvent, ) { CompositionLocalProvider( LocalWindow provides window, LocalLayerContainer provides _pane ) { content() undecoratedWindowResizer.Content() } } } fun dispose() { if (!isDisposed) { layer.dispose() _pane.dispose() _layer = null isDisposed = true } } fun onRenderApiChanged(action: () -> Unit) { layer.component.onStateChanged(SkiaLayer.PropertyKind.Renderer) { action() } } val windowHandle: Long get() = layer.component.windowHandle val renderApi: GraphicsApi get() = layer.component.renderApi var isTransparent: Boolean get() = layer.component.transparency set(value) { if (value != layer.component.transparency) { check(isUndecorated()) { "Transparent window should be undecorated!" } check(!window.isDisplayable) { "Cannot change transparency if window is already displayable." } layer.component.transparency = value if (value) { if (hostOs != OS.Windows) { window.background = Color(0, 0, 0, 0) } } else { window.background = null } } } fun addMouseListener(listener: MouseListener) { layer.component.addMouseListener(listener) } fun removeMouseListener(listener: MouseListener) { layer.component.removeMouseListener(listener) } fun addMouseMotionListener(listener: MouseMotionListener) { layer.component.addMouseMotionListener(listener) } fun removeMouseMotionListener(listener: MouseMotionListener) { layer.component.removeMouseMotionListener(listener) } fun addMouseWheelListener(listener: MouseWheelListener) { layer.component.addMouseWheelListener(listener) } fun removeMouseWheelListener(listener: MouseWheelListener) { layer.component.removeMouseWheelListener(listener) } }
apache-2.0
063dcf5cac1fd19f4431d616c2158b13
30.231959
95
0.636244
4.78594
false
false
false
false
androidx/androidx
compose/ui/ui/src/commonMain/kotlin/androidx/compose/ui/layout/IntermediateLayoutModifier.kt
3
2213
/* * Copyright 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.ui.layout import androidx.compose.ui.ExperimentalComposeUiApi import androidx.compose.ui.platform.InspectorInfo import androidx.compose.ui.platform.InspectorValueInfo import androidx.compose.ui.unit.Constraints import androidx.compose.ui.unit.IntSize /** * IntermediateLayoutModifier is a [LayoutModifier] that will be skipped when * looking ahead. During measure pass, [measure] will be invoked with the constraints from the * look-ahead, as well as the target size. */ @ExperimentalComposeUiApi internal interface IntermediateLayoutModifier : LayoutModifier { var targetSize: IntSize } @OptIn(ExperimentalComposeUiApi::class) internal class LookaheadIntermediateLayoutModifierImpl( val measureBlock: MeasureScope.( measurable: Measurable, constraints: Constraints, lookaheadSize: IntSize ) -> MeasureResult, inspectorInfo: InspectorInfo.() -> Unit ) : IntermediateLayoutModifier, InspectorValueInfo(inspectorInfo) { override var targetSize: IntSize = IntSize.Zero override fun MeasureScope.measure( measurable: Measurable, constraints: Constraints ): MeasureResult = measureBlock(measurable, constraints, targetSize) override fun equals(other: Any?): Boolean { if (this === other) return true if (other !is LookaheadIntermediateLayoutModifierImpl) return false return measureBlock == other.measureBlock && targetSize == other.targetSize } override fun hashCode(): Int { return measureBlock.hashCode() * 31 + targetSize.hashCode() } }
apache-2.0
50ff2d4b7faeea3690a770660fb56e08
34.693548
94
0.745142
4.738758
false
false
false
false
rustamgaifullin/kotlin-lunch-learn
src/main/kotlin/com/rustam/basic/2.Constructors.kt
1
974
package com.rustam.basic class Engine (val horsePower: Int) { var injection: String = "defaultInjection" init { println("I'm engine with $horsePower horse powers") } constructor(horsePower: Int, injection: String) : this(horsePower) { this.injection = injection } } fun main(args: Array<String>) { val carEngine = Engine(100) val sportCarEngine = Engine(500, "superInjection") println("horsePower - ${carEngine.horsePower}, injection - ${carEngine.injection}") println("horsePower - ${sportCarEngine.horsePower}, injection - ${sportCarEngine.injection}") val valFromFactory = ClassWithPrivateConstructor.create(42) println(valFromFactory.someProperty) } class ClassWithPrivateConstructor private constructor(val someProperty: Int) { companion object { fun create(someProperty: Int): ClassWithPrivateConstructor { return ClassWithPrivateConstructor(someProperty) } } }
unlicense
570c557760a5f66d5cdc2028f5be67b5
26.828571
97
0.702259
4.253275
false
false
false
false
foolish314159/NHK-Easy-News
app/src/main/java/com/github/foolish314159/nhkeasynews/ui/NHKArticleListFragment.kt
1
2993
package com.github.foolish314159.nhkeasynews.ui import android.content.Context import android.os.Bundle import android.support.v4.app.Fragment import android.support.v7.widget.DividerItemDecoration 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.foolish314159.nhkeasynews.R import com.github.foolish314159.nhkeasynews.article.NHKArticle import com.github.foolish314159.nhkeasynews.article.NHKArticleLoader import com.github.foolish314159.nhkeasynews.util.addSorted import com.github.foolish314159.nhkeasynews.util.contains import com.orm.SugarRecord class NHKArticleListFragment : Fragment() { private var listener: OnListFragmentInteractionListener? = null private var articles = ArrayList<NHKArticle>() private var adapter: NHKArticleListRecyclerViewAdapter? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) // Load already downloaded articles from database val localArticles = SugarRecord.listAll(NHKArticle::class.java) articles.addAll(localArticles) articles.sort() val loader = NHKArticleLoader(activity) loader.articlesFromWeb(articles) { article -> if (!articles.contains { it.articleId == article.articleId }) { articles.add(0, article) adapter?.notifyDataSetChanged() } } } override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? { val view = inflater!!.inflate(R.layout.fragment_nhkarticlelist, container, false) // Set the adapter if (view is RecyclerView) { val context = view.getContext() val recyclerView = view val layoutManager = LinearLayoutManager(context) recyclerView.layoutManager = layoutManager recyclerView.addItemDecoration(DividerItemDecoration(context, layoutManager.orientation)) adapter = NHKArticleListRecyclerViewAdapter(activity, articles, listener) recyclerView.adapter = adapter } return view } override fun onResume() { super.onResume() if (activity is MainActivity) { (activity as MainActivity).currentFragment = this } } override fun onAttach(context: Context?) { super.onAttach(context) if (context is OnListFragmentInteractionListener) { listener = context } else { throw RuntimeException(context!!.toString() + " must implement OnListFragmentInteractionListener") } } override fun onDetach() { super.onDetach() listener = null } interface OnListFragmentInteractionListener { fun onListFragmentInteraction(item: NHKArticle) } }
mit
95122852bdf066fb227b4395e3b22f29
34.211765
110
0.696625
4.827419
false
false
false
false
inorichi/tachiyomi-extensions
src/all/ehentai/src/eu/kanade/tachiyomi/extension/all/ehentai/MetadataCopier.kt
1
2938
package eu.kanade.tachiyomi.extension.all.ehentai import eu.kanade.tachiyomi.source.model.SManga import java.text.SimpleDateFormat import java.util.Date import java.util.Locale private const val EH_ARTIST_NAMESPACE = "artist" private const val EH_AUTHOR_NAMESPACE = "author" private val ONGOING_SUFFIX = arrayOf( "[ongoing]", "(ongoing)", "{ongoing}" ) val EX_DATE_FORMAT = SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.US) fun ExGalleryMetadata.copyTo(manga: SManga) { url?.let { manga.url = it } thumbnailUrl?.let { manga.thumbnail_url = it } (title ?: altTitle)?.let { manga.title = it } // Set artist (if we can find one) tags[EH_ARTIST_NAMESPACE]?.let { if (it.isNotEmpty()) manga.artist = it.joinToString(transform = Tag::name) } // Set author (if we can find one) tags[EH_AUTHOR_NAMESPACE]?.let { if (it.isNotEmpty()) manga.author = it.joinToString(transform = Tag::name) } // Set genre genre?.let { manga.genre = it } // Try to automatically identify if it is ongoing, we try not to be too lenient here to avoid making mistakes // We default to completed manga.status = SManga.COMPLETED title?.let { t -> if (ONGOING_SUFFIX.any { t.endsWith(it, ignoreCase = true) } ) manga.status = SManga.ONGOING } // Build a nice looking description out of what we know val titleDesc = StringBuilder() title?.let { titleDesc += "Title: $it\n" } altTitle?.let { titleDesc += "Alternate Title: $it\n" } val detailsDesc = StringBuilder() uploader?.let { detailsDesc += "Uploader: $it\n" } datePosted?.let { detailsDesc += "Posted: ${EX_DATE_FORMAT.format(Date(it))}\n" } visible?.let { detailsDesc += "Visible: $it\n" } language?.let { detailsDesc += "Language: $it" if (translated == true) detailsDesc += " TR" detailsDesc += "\n" } size?.let { detailsDesc += "File Size: ${humanReadableByteCount(it, true)}\n" } length?.let { detailsDesc += "Length: $it pages\n" } favorites?.let { detailsDesc += "Favorited: $it times\n" } averageRating?.let { detailsDesc += "Rating: $it" ratingCount?.let { count -> detailsDesc += " ($count)" } detailsDesc += "\n" } val tagsDesc = buildTagsDescription(this) manga.description = listOf(titleDesc.toString(), detailsDesc.toString(), tagsDesc.toString()) .filter(String::isNotBlank) .joinToString(separator = "\n") } private fun buildTagsDescription(metadata: ExGalleryMetadata) = StringBuilder("Tags:\n").apply { // BiConsumer only available in Java 8, we have to use destructuring here metadata.tags.forEach { (namespace, tags) -> if (tags.isNotEmpty()) { val joinedTags = tags.joinToString(separator = " ", transform = { "<${it.name}>" }) this += "▪ $namespace: $joinedTags\n" } } }
apache-2.0
6bc9e223f3e67ddf34517ae0cf1fa4db
33.952381
113
0.632834
3.759283
false
false
false
false
ohmae/DmsExplorer
mobile/src/main/java/net/mm2d/dmsexplorer/viewmodel/PropertyItemModel.kt
1
713
/* * Copyright (c) 2017 大前良介 (OHMAE Ryosuke) * * This software is released under the MIT License. * http://opensource.org/licenses/MIT */ package net.mm2d.dmsexplorer.viewmodel import android.view.View.OnClickListener import net.mm2d.dmsexplorer.view.adapter.PropertyAdapter.Type /** * @author [大前良介 (OHMAE Ryosuke)](mailto:[email protected]) */ class PropertyItemModel( val title: CharSequence, type: Type, val description: CharSequence, listener: OnClickListener? ) { val isLink: Boolean = type == Type.LINK val enableDescription: Boolean = type !== Type.TITLE && description.isNotEmpty() val onClickListener: OnClickListener? = if (isLink) listener else null }
mit
050e680feea8eff898096c4e4a681613
26.88
84
0.724534
3.893855
false
false
false
false
jiaminglu/kotlin-native
backend.native/tests/external/codegen/box/lazyCodegen/optimizations/noOptimization.kt
5
390
class A class B var holder = 0 operator fun A.not(): A { holder++ return this; } operator fun B.not(): Boolean { holder++ return false; } fun box(): String { !!!!!A() if (holder != 5) return "fail 1" holder = 0; if (!!!B() || holder != 1) return "fail 2" if (!B() != false) return "fail 3" if (!!B() != true) return "fail 4" return "OK" }
apache-2.0
dbbc26b1219e86fe3d24b00feafd72da
12.964286
46
0.510256
3.046875
false
false
false
false
spkingr/50-android-kotlin-projects-in-100-days
ProjectService/app/src/main/java/me/liuqingwen/android/projectservice/GlobalData.kt
1
1443
package me.liuqingwen.android.projectservice import android.os.Looper /** * Created by Qingwen on 2018-5-14, project: ProjectService. * * @Author: Qingwen * @DateTime: 2018-5-14 * @Package: me.liuqingwen.android.projectservice in project: ProjectService * * Notice: If you are using this class or file, check it and do some modification. */ object GlobalCache { private val data = mutableListOf<Movie>() fun addMovies(movies: List<Movie>) { this.data.addAll(movies) } fun clearData() { this.data.clear() } fun searchMovie(text : String):List<Movie> { if (Looper.myLooper() == Looper.getMainLooper()) { throw RuntimeException("You cannot run this method on Android UI Thread!") } if (text.isBlank()) { return data } fun containsText(vararg strings:String) : Boolean { return strings.any { it.contains(text, false) } } return data.filter { containsText(*it.strings.toTypedArray()) } } } val Movie.strings get() = listOf(this.TranslationTitle, this.originalTitle, this.genres.joinToString(separator = ""), this.movieDirectors.joinToString(separator = "") { it.name }, this.movieStars.joinToString(separator = "") { it.name } )
mit
592e8de7068ccdc1b6a4a6239c6224e7
24.785714
86
0.578656
4.386018
false
false
false
false
walleth/walleth
app/src/main/java/org/walleth/startup/StartupViewModel.kt
1
1147
package org.walleth.startup import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import kotlinx.coroutines.delay import kotlinx.coroutines.launch import org.walleth.chains.ChainInfoProvider import org.walleth.data.addresses.CurrentAddressProvider class StartupViewModel(private val currentAddressProvider: CurrentAddressProvider, private val currentChainInfoProvider: ChainInfoProvider) : ViewModel() { val status = MutableLiveData<StartupStatus>() init { viewModelScope.launch { //1000 * 10ms = 10s (0..1000).forEach { _ -> if (currentAddressProvider.getCurrent() == null) { status.postValue(StartupStatus.NeedsAddress) return@launch } if (currentChainInfoProvider.getCurrent() != null) { status.postValue(StartupStatus.HasChainAndAddress) return@launch } delay(10) } status.postValue(StartupStatus.Timeout) } } }
gpl-3.0
5e07dd2ae3664e9f9b3dd4e90a04cd9e
30.027027
95
0.633827
5.410377
false
false
false
false
CarlosEsco/tachiyomi
app/src/main/java/eu/kanade/domain/manga/model/ComicInfo.kt
1
1790
package eu.kanade.domain.manga.model import kotlinx.serialization.Serializable import nl.adaptivity.xmlutil.serialization.XmlSerialName import nl.adaptivity.xmlutil.serialization.XmlValue @Serializable @XmlSerialName("ComicInfo", "", "") data class ComicInfo( val series: ComicInfoSeries?, val summary: ComicInfoSummary?, val writer: ComicInfoWriter?, val penciller: ComicInfoPenciller?, val inker: ComicInfoInker?, val colorist: ComicInfoColorist?, val letterer: ComicInfoLetterer?, val coverArtist: ComicInfoCoverArtist?, val genre: ComicInfoGenre?, val tags: ComicInfoTags?, ) @Serializable @XmlSerialName("Series", "", "") data class ComicInfoSeries(@XmlValue(true) val value: String = "") @Serializable @XmlSerialName("Summary", "", "") data class ComicInfoSummary(@XmlValue(true) val value: String = "") @Serializable @XmlSerialName("Writer", "", "") data class ComicInfoWriter(@XmlValue(true) val value: String = "") @Serializable @XmlSerialName("Penciller", "", "") data class ComicInfoPenciller(@XmlValue(true) val value: String = "") @Serializable @XmlSerialName("Inker", "", "") data class ComicInfoInker(@XmlValue(true) val value: String = "") @Serializable @XmlSerialName("Colorist", "", "") data class ComicInfoColorist(@XmlValue(true) val value: String = "") @Serializable @XmlSerialName("Letterer", "", "") data class ComicInfoLetterer(@XmlValue(true) val value: String = "") @Serializable @XmlSerialName("CoverArtist", "", "") data class ComicInfoCoverArtist(@XmlValue(true) val value: String = "") @Serializable @XmlSerialName("Genre", "", "") data class ComicInfoGenre(@XmlValue(true) val value: String = "") @Serializable @XmlSerialName("Tags", "", "") data class ComicInfoTags(@XmlValue(true) val value: String = "")
apache-2.0
02d394c7483cd7731ef66655757609d0
28.833333
71
0.728492
3.841202
false
false
false
false
Maccimo/intellij-community
plugins/package-search/src/com/jetbrains/packagesearch/intellij/plugin/util/LogExtensions.kt
2
5871
/******************************************************************************* * Copyright 2000-2022 JetBrains s.r.o. and contributors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ @file:Suppress("unused") package com.jetbrains.packagesearch.intellij.plugin.util import com.intellij.openapi.diagnostic.Logger import com.jetbrains.packagesearch.intellij.plugin.PluginEnvironment import kotlinx.coroutines.CancellationException private val logger = Logger.getInstance("#${PluginEnvironment.PLUGIN_ID}") fun logError(contextName: String? = null, messageProvider: () -> String) { logError(traceInfo = null, contextName = contextName, messageProvider = messageProvider) } fun logError(contextName: String? = null, throwable: Throwable? = null, messageProvider: () -> String) { logError(traceInfo = null, contextName = contextName, throwable = throwable, messageProvider = messageProvider) } fun logError(traceInfo: TraceInfo? = null, contextName: String? = null, throwable: Throwable? = null, messageProvider: () -> String) { logError(buildMessageFrom(traceInfo, contextName, messageProvider), throwable) } fun logError(message: String, throwable: Throwable? = null) { if (throwable is CancellationException) return logger.error(message, throwable) } fun logWarn(contextName: String? = null, messageProvider: () -> String) { logWarn(traceInfo = null, contextName = contextName, messageProvider = messageProvider) } fun logWarn(contextName: String? = null, throwable: Throwable? = null, messageProvider: () -> String) { logWarn(traceInfo = null, contextName = contextName, throwable = throwable, messageProvider = messageProvider) } fun logWarn(traceInfo: TraceInfo? = null, contextName: String? = null, throwable: Throwable? = null, messageProvider: () -> String) { logWarn(buildMessageFrom(traceInfo, contextName, messageProvider), throwable) } fun logWarn(message: String, throwable: Throwable? = null) { if (throwable is CancellationException) return logger.warn(message, throwable) } fun logInfo(contextName: String? = null, messageProvider: () -> String) { logInfo(traceInfo = null, contextName = contextName, messageProvider = messageProvider) } fun logInfo(contextName: String? = null, throwable: Throwable? = null, messageProvider: () -> String) { logInfo(traceInfo = null, contextName = contextName, throwable = throwable, messageProvider = messageProvider) } fun logInfo(traceInfo: TraceInfo? = null, contextName: String? = null, throwable: Throwable? = null, messageProvider: () -> String) { logInfo(buildMessageFrom(traceInfo, contextName, messageProvider), throwable) } fun logInfo(message: String, throwable: Throwable? = null) { logger.info(message, throwable) } fun logDebug(contextName: String? = null, messageProvider: () -> String) { logDebug(traceInfo = null, contextName = contextName, messageProvider = messageProvider) } fun logDebug(contextName: String? = null, throwable: Throwable? = null, messageProvider: () -> String) { logDebug(traceInfo = null, contextName = contextName, throwable = throwable, messageProvider = messageProvider) } fun logDebug(traceInfo: TraceInfo? = null, contextName: String? = null, throwable: Throwable? = null, messageProvider: () -> String) { logDebug(buildMessageFrom(traceInfo, contextName, messageProvider), throwable) } fun logDebug(message: String, throwable: Throwable? = null) { if (!FeatureFlags.useDebugLogging) return if (!logger.isDebugEnabled) warnNotLoggable() logger.debug(message, throwable) } fun logTrace(contextName: String? = null, messageProvider: () -> String) { logTrace(traceInfo = null, contextName = contextName, messageProvider = messageProvider) } fun logTrace(traceInfo: TraceInfo? = null, contextName: String? = null, messageProvider: () -> String) { logTrace(buildMessageFrom(traceInfo, contextName, messageProvider)) } private inline fun catchAndSuppress(action: () -> Unit) { try { action() } catch (e: Throwable) { } } fun logTrace(message: String) = catchAndSuppress { if (!FeatureFlags.useDebugLogging) return if (!logger.isTraceEnabled) warnNotLoggable() logger.trace(message) } fun logTrace(throwable: Throwable) = catchAndSuppress { if (!FeatureFlags.useDebugLogging) return if (!logger.isTraceEnabled) warnNotLoggable() logger.trace(throwable) } private fun warnNotLoggable() { logger.warn( """ |!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! |Debug logging not enabled. Make sure you have a line like this: | #${PluginEnvironment.PLUGIN_ID}:trace |in your debug log settings (Help | Diagnostic Tools | Debug Log Settings) |then restart the IDE. |!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! |""".trimMargin() ) } private fun buildMessageFrom( traceInfo: TraceInfo?, contextName: String?, messageProvider: () -> String ) = buildString { if (traceInfo != null) { append(traceInfo) append(' ') } if (!contextName.isNullOrBlank()) { append(contextName) append(' ') } if (isNotEmpty()) append("- ") append(messageProvider()) }
apache-2.0
cc0b02c72449712b02b1127607c67ac1
36.877419
134
0.680974
4.666932
false
false
false
false
Maccimo/intellij-community
platform/workspaceModel/storage/src/com/intellij/workspaceModel/storage/impl/EntityStorageSerializerImpl.kt
1
32891
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.workspaceModel.storage.impl import com.esotericsoftware.kryo.Kryo import com.esotericsoftware.kryo.KryoException import com.esotericsoftware.kryo.Serializer import com.esotericsoftware.kryo.io.Input import com.esotericsoftware.kryo.io.Output import com.esotericsoftware.kryo.serializers.DefaultSerializers import com.esotericsoftware.kryo.serializers.FieldSerializer import com.google.common.collect.HashBiMap import com.google.common.collect.HashMultimap import com.intellij.openapi.diagnostic.logger import com.intellij.util.ReflectionUtil import com.intellij.util.SmartList import com.intellij.util.containers.* import com.intellij.workspaceModel.storage.* import com.intellij.workspaceModel.storage.impl.containers.* import com.intellij.workspaceModel.storage.impl.containers.BidirectionalMap import com.intellij.workspaceModel.storage.impl.indices.* import com.intellij.workspaceModel.storage.url.VirtualFileUrl import com.intellij.workspaceModel.storage.url.VirtualFileUrlManager import it.unimi.dsi.fastutil.ints.Int2IntOpenHashMap import it.unimi.dsi.fastutil.objects.Object2LongOpenHashMap import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap import it.unimi.dsi.fastutil.objects.ObjectOpenHashSet import org.jetbrains.annotations.TestOnly import org.objenesis.instantiator.ObjectInstantiator import org.objenesis.strategy.StdInstantiatorStrategy import java.io.InputStream import java.io.OutputStream import java.lang.reflect.Modifier import java.lang.reflect.ParameterizedType import java.util.* import kotlin.reflect.KClass import kotlin.reflect.jvm.jvmName private val LOG = logger<EntityStorageSerializerImpl>() class EntityStorageSerializerImpl( private val typesResolver: EntityTypesResolver, private val virtualFileManager: VirtualFileUrlManager, private val versionsContributor: () -> Map<String, String> = { emptyMap() }, ) : EntityStorageSerializer { companion object { const val SERIALIZER_VERSION = "v32" } private val KRYO_BUFFER_SIZE = 64 * 1024 private val interner = HashSetInterner<SerializableEntityId>() @set:TestOnly override var serializerDataFormatVersion: String = SERIALIZER_VERSION internal fun createKryo(): Kryo { val kryo = Kryo() kryo.setAutoReset(false) kryo.isRegistrationRequired = true kryo.instantiatorStrategy = StdInstantiatorStrategy() kryo.addDefaultSerializer(VirtualFileUrl::class.java, object : Serializer<VirtualFileUrl>(false, true) { override fun write(kryo: Kryo, output: Output, obj: VirtualFileUrl) { // TODO Write IDs only output.writeString(obj.url) } override fun read(kryo: Kryo, input: Input, type: Class<VirtualFileUrl>): VirtualFileUrl { val url = input.readString() return virtualFileManager.fromUrl(url) } }) kryo.register(EntityId::class.java, object : Serializer<EntityId>(false, true) { override fun write(kryo: Kryo, output: Output, `object`: EntityId) { output.writeInt(`object`.arrayId) val typeClass = `object`.clazz.findEntityClass<WorkspaceEntity>() val typeInfo = TypeInfo(typeClass.name, typesResolver.getPluginId(typeClass)) kryo.writeClassAndObject(output, typeInfo) } override fun read(kryo: Kryo, input: Input, type: Class<EntityId>): EntityId { val arrayId = input.readInt() val clazzInfo = kryo.readClassAndObject(input) as TypeInfo val clazz = typesResolver.resolveClass(clazzInfo.name, clazzInfo.pluginId) return createEntityId(arrayId, clazz.toClassId()) } }) kryo.register(HashMultimap::class.java, object : Serializer<HashMultimap<*, *>>(false, true) { override fun write(kryo: Kryo, output: Output, `object`: HashMultimap<*, *>) { val res = HashMap<Any?, Collection<Any?>>() `object`.asMap().forEach { (key, values) -> res[key] = ArrayList(values) } kryo.writeClassAndObject(output, res) } @Suppress("UNCHECKED_CAST") override fun read(kryo: Kryo, input: Input, type: Class<HashMultimap<*, *>>): HashMultimap<*, *> { val res = HashMultimap.create<Any, Any>() val map = kryo.readClassAndObject(input) as HashMap<*, Collection<*>> map.forEach { (key, values) -> res.putAll(key, values) } return res } }) kryo.register(ConnectionId::class.java, object : Serializer<ConnectionId>(false, true) { override fun write(kryo: Kryo, output: Output, `object`: ConnectionId) { val parentClassType = `object`.parentClass.findEntityClass<WorkspaceEntity>() val childClassType = `object`.childClass.findEntityClass<WorkspaceEntity>() val parentTypeInfo = TypeInfo(parentClassType.name, typesResolver.getPluginId(parentClassType)) val childTypeInfo = TypeInfo(childClassType.name, typesResolver.getPluginId(childClassType)) kryo.writeClassAndObject(output, parentTypeInfo) kryo.writeClassAndObject(output, childTypeInfo) output.writeString(`object`.connectionType.name) output.writeBoolean(`object`.isParentNullable) } @Suppress("UNCHECKED_CAST") override fun read(kryo: Kryo, input: Input, type: Class<ConnectionId>): ConnectionId { val parentClazzInfo = kryo.readClassAndObject(input) as TypeInfo val childClazzInfo = kryo.readClassAndObject(input) as TypeInfo val parentClass = typesResolver.resolveClass(parentClazzInfo.name, parentClazzInfo.pluginId) as Class<WorkspaceEntity> val childClass = typesResolver.resolveClass(childClazzInfo.name, childClazzInfo.pluginId) as Class<WorkspaceEntity> val connectionType = ConnectionId.ConnectionType.valueOf(input.readString()) val parentNullable = input.readBoolean() return ConnectionId.create(parentClass, childClass, connectionType, parentNullable) } }) kryo.register(ImmutableEntitiesBarrel::class.java, object : Serializer<ImmutableEntitiesBarrel>(false, true) { override fun write(kryo: Kryo, output: Output, `object`: ImmutableEntitiesBarrel) { val res = HashMap<TypeInfo, EntityFamily<*>>() `object`.entityFamilies.forEachIndexed { i, v -> if (v == null) return@forEachIndexed val clazz = i.findEntityClass<WorkspaceEntity>() val typeInfo = TypeInfo(clazz.name, typesResolver.getPluginId(clazz)) res[typeInfo] = v } kryo.writeClassAndObject(output, res) } @Suppress("UNCHECKED_CAST") override fun read(kryo: Kryo, input: Input, type: Class<ImmutableEntitiesBarrel>): ImmutableEntitiesBarrel { val mutableBarrel = MutableEntitiesBarrel.create() val families = kryo.readClassAndObject(input) as HashMap<TypeInfo, EntityFamily<*>> for ((typeInfo, family) in families) { val classId = typesResolver.resolveClass(typeInfo.name, typeInfo.pluginId).toClassId() mutableBarrel.fillEmptyFamilies(classId) mutableBarrel.entityFamilies[classId] = family } return mutableBarrel.toImmutable() } }) kryo.register(ChildEntityId::class.java, object : Serializer<ChildEntityId>(false, true) { override fun write(kryo: Kryo, output: Output, `object`: ChildEntityId) { kryo.writeClassAndObject(output, `object`.id.toSerializableEntityId()) } override fun read(kryo: Kryo, input: Input, type: Class<ChildEntityId>): ChildEntityId { val entityId = kryo.readClassAndObject(input) as SerializableEntityId return ChildEntityId(entityId.toEntityId()) } }) kryo.register(ParentEntityId::class.java, object : Serializer<ParentEntityId>(false, true) { override fun write(kryo: Kryo, output: Output, `object`: ParentEntityId) { kryo.writeClassAndObject(output, `object`.id.toSerializableEntityId()) } override fun read(kryo: Kryo, input: Input, type: Class<ParentEntityId>): ParentEntityId { val entityId = kryo.readClassAndObject(input) as SerializableEntityId return ParentEntityId(entityId.toEntityId()) } }) kryo.register(ObjectOpenHashSet::class.java, object : Serializer<ObjectOpenHashSet<*>>(false, true) { override fun write(kryo: Kryo, output: Output, `object`: ObjectOpenHashSet<*>) { output.writeInt(`object`.size) `object`.forEach { kryo.writeClassAndObject(output, it) } } override fun read(kryo: Kryo, input: Input, type: Class<ObjectOpenHashSet<*>>): ObjectOpenHashSet<*> { val res = ObjectOpenHashSet<Any>() repeat(input.readInt()) { val data = kryo.readClassAndObject(input) res.add(data) } return res } }) kryo.register(TypeInfo::class.java) // TODO Dedup with OCSerializers // TODO Reuse OCSerializer.registerUtilitySerializers ? // TODO Scan OCSerializer for useful kryo settings and tricks kryo.register(ArrayList::class.java).instantiator = ObjectInstantiator { ArrayList<Any>() } kryo.register(HashMap::class.java).instantiator = ObjectInstantiator { HashMap<Any, Any>() } kryo.register(SmartList::class.java).instantiator = ObjectInstantiator { SmartList<Any>() } kryo.register(LinkedHashMap::class.java).instantiator = ObjectInstantiator { LinkedHashMap<Any, Any>() } kryo.register(BidirectionalMap::class.java).instantiator = ObjectInstantiator { BidirectionalMap<Any, Any>() } kryo.register(BidirectionalSetMap::class.java).instantiator = ObjectInstantiator { BidirectionalSetMap<Any, Any>() } kryo.register(HashSet::class.java).instantiator = ObjectInstantiator { HashSet<Any>() } kryo.register(BidirectionalMultiMap::class.java).instantiator = ObjectInstantiator { BidirectionalMultiMap<Any, Any>() } kryo.register(HashBiMap::class.java).instantiator = ObjectInstantiator { HashBiMap.create<Any, Any>() } kryo.register(LinkedBidirectionalMap::class.java).instantiator = ObjectInstantiator { LinkedBidirectionalMap<Any, Any>() } kryo.register(Int2IntOpenHashMap::class.java).instantiator = ObjectInstantiator { Int2IntOpenHashMap() } kryo.register(ObjectOpenHashSet::class.java).instantiator = ObjectInstantiator { ObjectOpenHashSet<Any>() } kryo.register(Object2ObjectOpenHashMap::class.java).instantiator = ObjectInstantiator { Object2ObjectOpenHashMap<Any, Any>() } @Suppress("ReplaceJavaStaticMethodWithKotlinAnalog") kryo.register(Arrays.asList("a").javaClass).instantiator = ObjectInstantiator { ArrayList<Any>() } kryo.register(ByteArray::class.java) kryo.register(ImmutableEntityFamily::class.java) kryo.register(RefsTable::class.java) kryo.register(ImmutableNonNegativeIntIntBiMap::class.java) kryo.register(ImmutableIntIntUniqueBiMap::class.java) kryo.register(VirtualFileIndex::class.java) kryo.register(EntityStorageInternalIndex::class.java) kryo.register(PersistentIdInternalIndex::class.java) kryo.register(ImmutableNonNegativeIntIntMultiMap.ByList::class.java) kryo.register(IntArray::class.java) kryo.register(Pair::class.java) kryo.register(MultimapStorageIndex::class.java) kryo.register(SerializableEntityId::class.java) kryo.register(ChangeEntry.AddEntity::class.java) kryo.register(ChangeEntry.RemoveEntity::class.java) kryo.register(ChangeEntry.ReplaceEntity::class.java) kryo.register(ChangeEntry.ChangeEntitySource::class.java) kryo.register(ChangeEntry.ReplaceAndChangeSource::class.java) kryo.register(LinkedHashSet::class.java).instantiator = ObjectInstantiator { LinkedHashSet<Any>() } registerFieldSerializer(kryo, Collections.unmodifiableCollection<Any>(emptySet()).javaClass) { Collections.unmodifiableCollection(emptySet()) } registerFieldSerializer(kryo, Collections.unmodifiableSet<Any>(emptySet()).javaClass) { Collections.unmodifiableSet(emptySet()) } registerFieldSerializer(kryo, Collections.unmodifiableList<Any>(emptyList()).javaClass) { Collections.unmodifiableList(emptyList()) } registerFieldSerializer(kryo, Collections.unmodifiableMap<Any, Any>(emptyMap()).javaClass) { Collections.unmodifiableMap(emptyMap()) } kryo.register(Collections.EMPTY_LIST.javaClass, DefaultSerializers.CollectionsEmptyListSerializer()) kryo.register(Collections.EMPTY_MAP.javaClass, DefaultSerializers.CollectionsEmptyMapSerializer()) kryo.register(Collections.EMPTY_SET.javaClass, DefaultSerializers.CollectionsEmptySetSerializer()) kryo.register(listOf(null).javaClass, DefaultSerializers.CollectionsSingletonListSerializer()) kryo.register(Collections.singletonMap<Any, Any>(null, null).javaClass, DefaultSerializers.CollectionsSingletonMapSerializer()) kryo.register(setOf(null).javaClass, DefaultSerializers.CollectionsSingletonSetSerializer()) registerSingletonSerializer(kryo) { ContainerUtil.emptyList<Any>() } registerSingletonSerializer(kryo) { MostlySingularMultiMap.emptyMap<Any, Any>() } registerSingletonSerializer(kryo) { MultiMap.empty<Any, Any>() } registerSingletonSerializer(kryo) { emptyMap<Any, Any>() } registerSingletonSerializer(kryo) { emptyList<Any>() } registerSingletonSerializer(kryo) { emptySet<Any>() } registerSingletonSerializer(kryo) { emptyArray<Any>() } return kryo } // TODO Dedup with OCSerializer private inline fun <reified T : Any> registerFieldSerializer(kryo: Kryo, type: Class<T> = T::class.java, crossinline create: () -> T) = registerSerializer(kryo, type, FieldSerializer(kryo, type), ObjectInstantiator { create() }) @JvmSynthetic private inline fun registerSingletonSerializer(kryo: Kryo, crossinline getter: () -> Any) { val getter1 = ObjectInstantiator { getter() } registerSerializer(kryo, getter1.newInstance().javaClass, EmptySerializer, getter1) } object EmptySerializer : Serializer<Any>(false, true) { override fun write(kryo: Kryo?, output: Output?, `object`: Any?) {} override fun read(kryo: Kryo, input: Input?, type: Class<Any>): Any? = kryo.newInstance(type) } private fun <T : Any> registerSerializer(kryo: Kryo, type: Class<T>, serializer: Serializer<in T>, initializer: ObjectInstantiator<T>) { kryo.register(type, serializer).apply { instantiator = initializer } } /** * Collect all classes existing in entity data. * [simpleClasses] - set of classes * [objectClasses] - set of kotlin objects */ private fun recursiveClassFinder(kryo: Kryo, entity: Any, simpleClasses: MutableMap<TypeInfo, Class<out Any>>, objectClasses: MutableMap<TypeInfo, Class<out Any>>) { val jClass = entity.javaClass val classAlreadyRegistered = registerKClass(entity::class, jClass, kryo, objectClasses, simpleClasses) if (classAlreadyRegistered) return if (entity is VirtualFileUrl) return if (entity is Enum<*>) return ReflectionUtil.collectFields(jClass).forEach { val retType = it.type.name if ((retType.startsWith("kotlin") || retType.startsWith("java")) && !retType.startsWith("kotlin.collections.List") && !retType.startsWith("java.util.List") ) return@forEach it.trySetAccessible() if (Modifier.isStatic(it.modifiers) || !it.canAccess(entity)) return@forEach val property = ReflectionUtil.getFieldValue<Any>(it, entity) ?: run { registerKClass(it.type.kotlin, it.type, kryo, objectClasses, simpleClasses) return@forEach } if (property === entity) return@forEach recursiveClassFinder(kryo, property, simpleClasses, objectClasses) if (property is List<*>) { val type = (it.genericType as ParameterizedType).actualTypeArguments[0] as? Class<*> if (type != null) { registerKClass(type.kotlin, type, kryo, objectClasses, simpleClasses) } property.filterNotNull().forEach { listItem -> recursiveClassFinder(kryo, listItem, simpleClasses, objectClasses) } } if (property is Array<*>) { val type = (it.genericType as Class<*>).componentType if (type != null) { registerKClass(type.kotlin, type, kryo, objectClasses, simpleClasses) } property.filterNotNull().forEach { listItem -> recursiveClassFinder(kryo, listItem, simpleClasses, objectClasses) } } } } private fun registerKClass(kClass: KClass<out Any>, jClass: Class<out Any>, kryo: Kryo, objectClasses: MutableMap<TypeInfo, Class<out Any>>, simpleClasses: MutableMap<TypeInfo, Class<out Any>>): Boolean { val typeInfo = TypeInfo(jClass.name, typesResolver.getPluginId(jClass)) if (kryo.classResolver.getRegistration(jClass) != null) return true val objectInstance = kClass.objectInstance if (objectInstance != null) { objectClasses[typeInfo] = jClass } else { simpleClasses[typeInfo] = jClass } return false } override fun serializeCache(stream: OutputStream, storage: EntityStorageSnapshot): SerializationResult { storage as EntityStorageSnapshotImpl val output = Output(stream, KRYO_BUFFER_SIZE) return try { val kryo = createKryo() // Save version output.writeString(serializerDataFormatVersion) saveContributedVersions(kryo, output) val entityDataSequence = storage.entitiesByType.entityFamilies.filterNotNull().asSequence().flatMap { family -> family.entities.asSequence().filterNotNull() } collectAndRegisterClasses(kryo, output, entityDataSequence) // Serialize and register persistent ids val persistentIds = storage.indexes.persistentIdIndex.entries().toSet() output.writeVarInt(persistentIds.size, true) persistentIds.forEach { val typeInfo = TypeInfo(it::class.jvmName, typesResolver.getPluginId(it::class.java)) kryo.register(it::class.java) kryo.writeClassAndObject(output, typeInfo) } // Write entity data and references kryo.writeClassAndObject(output, storage.entitiesByType) kryo.writeClassAndObject(output, storage.refs) // Write indexes storage.indexes.softLinks.writeSoftLinks(output, kryo) storage.indexes.virtualFileIndex.entityId2VirtualFileUrl.writeEntityIdToVfu(kryo, output) storage.indexes.virtualFileIndex.vfu2EntityId.write(kryo, output) storage.indexes.virtualFileIndex.entityId2JarDir.write(kryo, output) storage.indexes.entitySourceIndex.write(kryo, output) storage.indexes.persistentIdIndex.write(kryo, output) SerializationResult.Success } catch (e: Exception) { output.clear() LOG.warn("Exception at project serialization", e) SerializationResult.Fail(e.message) } finally { flush(output) } } private fun PersistentIdInternalIndex.write(kryo: Kryo, output: Output) { output.writeInt(this.index.keys.size) this.index.forEach { key, value -> kryo.writeObject(output, key.toSerializableEntityId()) kryo.writeClassAndObject(output, value) } } private fun readPersistentIdIndex(kryo: Kryo, input: Input): PersistentIdInternalIndex { val res = PersistentIdInternalIndex.MutablePersistentIdInternalIndex.from(PersistentIdInternalIndex()) repeat(input.readInt()) { val key = kryo.readObject(input, SerializableEntityId::class.java).toEntityId() val value = kryo.readClassAndObject(input) as PersistentEntityId<*> res.index(key, value) } return res.toImmutable() } private fun EntityStorageInternalIndex<EntitySource>.write(kryo: Kryo, output: Output) { output.writeInt(this.index.keys.size) this.index.forEach { entry -> kryo.writeObject(output, entry.longKey.toSerializableEntityId()) kryo.writeClassAndObject(output, entry.value) } } private fun readEntitySourceIndex(kryo: Kryo, input: Input): EntityStorageInternalIndex<EntitySource> { val res = EntityStorageInternalIndex.MutableEntityStorageInternalIndex.from(EntityStorageInternalIndex<EntitySource>(false)) repeat(input.readInt()) { val key = kryo.readObject(input, SerializableEntityId::class.java).toEntityId() val value = kryo.readClassAndObject(input) as EntitySource res.index(key, value) } return res.toImmutable() } private fun EntityId2JarDir.write(kryo: Kryo, output: Output) { output.writeInt(this.keys.size) this.keys.forEach { key -> val values: Set<VirtualFileUrl> = this.getValues(key) kryo.writeObject(output, key.toSerializableEntityId()) output.writeInt(values.size) for (value in values) { kryo.writeObject(output, value) } } } private fun readBimap(kryo: Kryo, input: Input): EntityId2JarDir { val res = EntityId2JarDir() repeat(input.readInt()) { val key = kryo.readObject(input, SerializableEntityId::class.java).toEntityId() repeat(input.readInt()) { res.put(key, kryo.readObject(input, VirtualFileUrl::class.java)) } } return res } private fun Vfu2EntityId.write(kryo: Kryo, output: Output) { output.writeInt(this.keys.size) this.forEach { (key: VirtualFileUrl, value) -> kryo.writeObject(output, key) output.writeInt(value.keys.size) value.forEach { (internalKey: String, internalValue) -> output.writeString(internalKey) kryo.writeObject(output, internalValue.toSerializableEntityId()) } } } private fun read(kryo: Kryo, input: Input): Vfu2EntityId { val vfu2EntityId = Vfu2EntityId(getHashingStrategy()) repeat(input.readInt()) { val file = kryo.readObject(input, VirtualFileUrl::class.java) as VirtualFileUrl val data = Object2LongOpenHashMap<String>() repeat(input.readInt()) { val internalKey = input.readString() val entityId = kryo.readObject(input, SerializableEntityId::class.java).toEntityId() data[internalKey] = entityId } vfu2EntityId[file] = data } return vfu2EntityId } private fun EntityId2Vfu.writeEntityIdToVfu(kryo: Kryo, output: Output) { output.writeInt(this.keys.size) this.forEach { (key: EntityId, value) -> kryo.writeObject(output, key.toSerializableEntityId()) kryo.writeClassAndObject(output, value) } } private fun readEntityIdToVfu(kryo: Kryo, input: Input): EntityId2Vfu { val index = EntityId2Vfu() repeat(input.readInt()) { val entityId = kryo.readObject(input, SerializableEntityId::class.java).toEntityId() val value = kryo.readClassAndObject(input) as Any index[entityId] = value } return index } private fun MultimapStorageIndex.writeSoftLinks(output: Output, kryo: Kryo) { output.writeInt(index.keys.size) for (key in index.keys) { val value: Set<PersistentEntityId<*>> = index.getValues(key) kryo.writeClassAndObject(output, key.toSerializableEntityId()) kryo.writeClassAndObject(output, value) } } @Suppress("UNCHECKED_CAST") private fun readSoftLinks(input: Input, kryo: Kryo): MultimapStorageIndex { val index = MultimapStorageIndex.MutableMultimapStorageIndex.from(MultimapStorageIndex()) repeat(input.readInt()) { val entityId = (kryo.readClassAndObject(input) as SerializableEntityId).toEntityId() val values = kryo.readClassAndObject(input) as Set<PersistentEntityId<*>> index.index(entityId, values) } return index } internal fun serializeDiffLog(stream: OutputStream, log: ChangeLog) { val output = Output(stream, KRYO_BUFFER_SIZE) try { val kryo = createKryo() // Save version output.writeString(serializerDataFormatVersion) saveContributedVersions(kryo, output) val entityDataSequence = log.values.mapNotNull { when (it) { is ChangeEntry.AddEntity -> it.entityData is ChangeEntry.RemoveEntity -> null is ChangeEntry.ReplaceEntity -> it.newData is ChangeEntry.ChangeEntitySource -> it.newData is ChangeEntry.ReplaceAndChangeSource -> it.dataChange.newData } }.asSequence() collectAndRegisterClasses(kryo, output, entityDataSequence) kryo.writeClassAndObject(output, log) } finally { flush(output) } } fun serializeClassToIntConverter(stream: OutputStream) { val converterMap = ClassToIntConverter.INSTANCE.getMap().toMap() val output = Output(stream, KRYO_BUFFER_SIZE) try { val kryo = createKryo() // Save version output.writeString(serializerDataFormatVersion) saveContributedVersions(kryo, output) val mapData = converterMap.map { (key, value) -> TypeInfo(key.name, typesResolver.getPluginId(key)) to value } kryo.writeClassAndObject(output, mapData) } finally { flush(output) } } private fun flush(output: Output) { try { output.flush() } catch (e: KryoException) { output.clear() LOG.warn("Exception at project serialization", e) SerializationResult.Fail(e.message) } } private fun collectAndRegisterClasses(kryo: Kryo, output: Output, entityDataSequence: Sequence<WorkspaceEntityData<*>>) { // Collect all classes existing in entity data val simpleClasses = HashMap<TypeInfo, Class<out Any>>() val objectClasses = HashMap<TypeInfo, Class<out Any>>() entityDataSequence.forEach { recursiveClassFinder(kryo, it, simpleClasses, objectClasses) } // Serialize and register types of kotlin objects output.writeVarInt(objectClasses.size, true) objectClasses.forEach { kryo.register(it.value) kryo.writeClassAndObject(output, it.key) } // Serialize and register all types existing in entity data output.writeVarInt(simpleClasses.size, true) simpleClasses.forEach { kryo.register(it.value) kryo.writeClassAndObject(output, it.key) } } @Suppress("UNCHECKED_CAST") override fun deserializeCache(stream: InputStream): MutableEntityStorage? { return Input(stream, KRYO_BUFFER_SIZE).use { input -> val kryo = createKryo() try { // Read version val cacheVersion = input.readString() if (cacheVersion != serializerDataFormatVersion) { LOG.info("Cache isn't loaded. Current version of cache: $serializerDataFormatVersion, version of cache file: $cacheVersion") return null } if (!checkContributedVersion(kryo, input)) return null readAndRegisterClasses(input, kryo) // Read and register persistent ids val persistentIdCount = input.readVarInt(true) repeat(persistentIdCount) { val objectClass = kryo.readClassAndObject(input) as TypeInfo kryo.register(typesResolver.resolveClass(objectClass.name, objectClass.pluginId)) } // Read entity data and references val entitiesBarrel = kryo.readClassAndObject(input) as ImmutableEntitiesBarrel val refsTable = kryo.readClassAndObject(input) as RefsTable // Read indexes val softLinks = readSoftLinks(input, kryo) val entityId2VirtualFileUrlInfo = readEntityIdToVfu(kryo, input) val vfu2VirtualFileUrlInfo = read(kryo, input) val entityId2JarDir = readBimap(kryo, input) val virtualFileIndex = VirtualFileIndex(entityId2VirtualFileUrlInfo, vfu2VirtualFileUrlInfo, entityId2JarDir) val entitySourceIndex = readEntitySourceIndex(kryo, input) val persistentIdIndex = readPersistentIdIndex(kryo, input) val storageIndexes = StorageIndexes(softLinks, virtualFileIndex, entitySourceIndex, persistentIdIndex) val storage = EntityStorageSnapshotImpl(entitiesBarrel, refsTable, storageIndexes) val builder = MutableEntityStorageImpl.from(storage) builder.entitiesByType.entityFamilies.forEach { family -> family?.entities?.asSequence()?.filterNotNull()?.forEach { entityData -> builder.createAddEvent(entityData) } } if (LOG.isTraceEnabled) { builder.assertConsistency() LOG.trace("Builder loaded from caches has no consistency issues") } builder } catch (e: Exception) { LOG.warn("Exception at project deserialization", e) null } } } private fun checkContributedVersion(kryo: Kryo, input: Input): Boolean { @Suppress("UNCHECKED_CAST") val cacheContributedVersions = kryo.readClassAndObject(input) as Map<String, String> val currentContributedVersions = versionsContributor() for ((id, version) in cacheContributedVersions) { // Cache is invalid in case: // - current version != cache version // cache version is missing in current version // // If some version that currently exists but missing in cache, cache is not treated as invalid val currentVersion = currentContributedVersions[id] ?: run { LOG.info("Cache isn't loaded. Cache id '$id' is missing in current state") return false } if (currentVersion != version) { LOG.info("Cache isn't loaded. For cache id '$id' cache version is '$version' and current versioni is '$currentVersion'") return false } } return true } private fun saveContributedVersions(kryo: Kryo, output: Output) { // Save contributed versions val versions = versionsContributor() kryo.writeClassAndObject(output, versions) } private fun readAndRegisterClasses(input: Input, kryo: Kryo) { // Read and register all kotlin objects val objectCount = input.readVarInt(true) repeat(objectCount) { val objectClass = kryo.readClassAndObject(input) as TypeInfo registerSingletonSerializer(kryo) { typesResolver.resolveClass(objectClass.name, objectClass.pluginId).kotlin.objectInstance!! } } // Read and register all types in entity data val nonObjectCount = input.readVarInt(true) repeat(nonObjectCount) { val objectClass = kryo.readClassAndObject(input) as TypeInfo kryo.register(typesResolver.resolveClass(objectClass.name, objectClass.pluginId)) } } @Suppress("UNCHECKED_CAST") fun deserializeCacheAndDiffLog(storeStream: InputStream, diffLogStream: InputStream): MutableEntityStorage? { val builder = this.deserializeCache(storeStream) ?: return null var log: ChangeLog Input(diffLogStream, KRYO_BUFFER_SIZE).use { input -> val kryo = createKryo() // Read version val cacheVersion = input.readString() if (cacheVersion != serializerDataFormatVersion) { LOG.info("Cache isn't loaded. Current version of cache: $serializerDataFormatVersion, version of cache file: $cacheVersion") return null } if (!checkContributedVersion(kryo, input)) return null readAndRegisterClasses(input, kryo) log = kryo.readClassAndObject(input) as ChangeLog } builder as MutableEntityStorageImpl builder.changeLog.changeLog.clear() builder.changeLog.changeLog.putAll(log) return builder } @Suppress("UNCHECKED_CAST") fun deserializeClassToIntConverter(stream: InputStream) { Input(stream, KRYO_BUFFER_SIZE).use { input -> val kryo = createKryo() // Read version val cacheVersion = input.readString() if (cacheVersion != serializerDataFormatVersion) { LOG.info("Cache isn't loaded. Current version of cache: $serializerDataFormatVersion, version of cache file: $cacheVersion") return } if (!checkContributedVersion(kryo, input)) return val classes = kryo.readClassAndObject(input) as List<Pair<TypeInfo, Int>> val map = classes.map { (first, second) -> typesResolver.resolveClass(first.name, first.pluginId) to second }.toMap() ClassToIntConverter.INSTANCE.fromMap(map) } } private data class TypeInfo(val name: String, val pluginId: String?) private data class SerializableEntityId(val arrayId: Int, val type: TypeInfo) private fun EntityId.toSerializableEntityId(): SerializableEntityId { val arrayId = this.arrayId val clazz = this.clazz.findEntityClass<WorkspaceEntity>() return interner.intern(SerializableEntityId(arrayId, TypeInfo(clazz.name, typesResolver.getPluginId(clazz)))) } private fun SerializableEntityId.toEntityId(): EntityId { val classId = typesResolver.resolveClass(this.type.name, this.type.pluginId).toClassId() return createEntityId(this.arrayId, classId) } }
apache-2.0
90ec6446f62348c9d35e972085a4b7fe
40.739848
138
0.709465
4.590509
false
false
false
false
pyamsoft/pydroid
ui/src/main/java/com/pyamsoft/pydroid/ui/internal/rating/RatingDelegate.kt
1
2164
/* * Copyright 2022 Peter Kenji Yamanaka * * 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.pyamsoft.pydroid.ui.internal.rating import androidx.lifecycle.lifecycleScope import com.pyamsoft.pydroid.bootstrap.rating.AppRatingLauncher import com.pyamsoft.pydroid.core.Logger import com.pyamsoft.pydroid.core.requireNotNull import com.pyamsoft.pydroid.ui.app.PYDroidActivity import com.pyamsoft.pydroid.util.doOnDestroy import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch internal class RatingDelegate(activity: PYDroidActivity, viewModel: RatingViewModeler) { private var activity: PYDroidActivity? = activity private var viewModel: RatingViewModeler? = viewModel private fun showRating(activity: PYDroidActivity, launcher: AppRatingLauncher) { // Enforce that we do this on the Main thread activity.lifecycleScope.launch(context = Dispatchers.Main) { launcher .rate(activity) .onSuccess { Logger.d("Call was made for in-app rating request") } .onFailure { err -> Logger.e(err, "Unable to launch in-app rating") } } } /** Bind Activity for related Rating events */ fun bindEvents() { activity.requireNotNull().doOnDestroy { viewModel = null activity = null } } /** * Attempt to call in-app rating dialog. Does not always result in showing the Dialog, that is up * to Google */ fun loadInAppRating() { val act = activity.requireNotNull() viewModel .requireNotNull() .loadInAppRating( scope = act.lifecycleScope, onLaunchInAppRating = { showRating(act, it) }, ) } }
apache-2.0
a0947fcebdbd56d9bc788bdacdf9c5f1
32.8125
99
0.720887
4.310757
false
false
false
false
DuncanCasteleyn/DiscordModBot
src/main/kotlin/be/duncanc/discordmodbot/bot/sequences/VoteEmoteSettings.kt
1
3025
/* * Copyright 2018 Duncan Casteleyn * * 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 be.duncanc.discordmodbot.bot.sequences import be.duncanc.discordmodbot.bot.commands.CommandModule import be.duncanc.discordmodbot.data.entities.VoteEmotes import be.duncanc.discordmodbot.data.repositories.jpa.VotingEmotesRepository import net.dv8tion.jda.api.Permission import net.dv8tion.jda.api.entities.MessageChannel import net.dv8tion.jda.api.entities.User import net.dv8tion.jda.api.events.message.MessageReceivedEvent import org.springframework.stereotype.Component import org.springframework.transaction.annotation.Transactional import java.util.concurrent.TimeUnit @Component class VoteEmoteSettings( val votingEmotesRepository: VotingEmotesRepository ) : CommandModule( arrayOf("VoteEmoteSettings", "VoteSettings"), null, "Command to change the vote yes and no emotes for a server", requiredPermissions = arrayOf(Permission.MANAGE_EMOTES) ) { override fun commandExec(event: MessageReceivedEvent, command: String, arguments: String?) { event.jda.addEventListener(VoteEmoteSettingsSequence(votingEmotesRepository, event.author, event.channel)) } } open class VoteEmoteSettingsSequence( private val votingEmotesRepository: VotingEmotesRepository, user: User, channel: MessageChannel ) : Sequence( user, channel, true, false ), MessageSequence { init { channel.sendMessage("${user.asMention} Please send the emote you want to use for yes votes.\nMake sure the bot has access to the server where this emote is hosted.") .queue { addMessageToCleaner(it) } } private var voteYesEmoteId: Long? = null @Transactional override fun onMessageReceivedDuringSequence(event: MessageReceivedEvent) { when (voteYesEmoteId) { null -> { val voteNotEmote = event.message.emotes[0] voteYesEmoteId = voteNotEmote.idLong channel.sendMessage("Please send the emote you want to use for no votes") .queue { addMessageToCleaner(it) } } else -> { val voteNoEmote = event.message.emotes[0] votingEmotesRepository.save(VoteEmotes(event.guild.idLong, voteYesEmoteId!!, voteNoEmote.idLong)) channel.sendMessage("New emotes have been set") .queue { it.delete().queueAfter(1, TimeUnit.MINUTES) } destroy() } } } }
apache-2.0
3960f21d166db630fec58cddc73fff3b
37.782051
173
0.712397
4.365079
false
false
false
false
koleno/SunWidget
app/src/main/kotlin/xyz/koleno/sunwidget/main/MainActivityViewModel.kt
1
6605
package xyz.koleno.sunwidget.main import android.app.Application import android.content.Context import android.content.res.Resources import android.location.Criteria import android.location.Location import android.location.LocationListener import android.location.LocationManager import android.os.Bundle import androidx.lifecycle.AndroidViewModel import androidx.lifecycle.MutableLiveData import androidx.preference.PreferenceManager import xyz.koleno.sunwidget.PrefHelper import xyz.koleno.sunwidget.R /** * View model for the main activity * @author Dusan Koleno */ class MainActivityViewModel(application: Application) : AndroidViewModel(application), LocationListener { enum class Action { REQUEST_PERM, LOAD_FULL_CONTENT, LOAD_MIN_CONTENT, UPDATE_WIDGETS, UPDATE_FINISH } private var permissionRequested = false private var openedFromWidget = false val action = MutableLiveData<Action>() val message = MutableLiveData<String>() val dialog = MutableLiveData<DialogData>() val location = MutableLiveData<PrefHelper.LocationData>() val locationActive = MutableLiveData<Boolean>(false) private val resources: Resources = application.resources private val prefs: PrefHelper = PrefHelper(PreferenceManager.getDefaultSharedPreferences(application)) private val locMgr: LocationManager = application.getSystemService(Context.LOCATION_SERVICE) as LocationManager fun init(permGranted: Boolean, openedFromWidget: Boolean, hasActiveWidgets: Boolean) { this.openedFromWidget = openedFromWidget if(!hasActiveWidgets) { dialog.postValue(DialogData(resources.getString(R.string.no_widgets_dialog_title), resources.getString(R.string.no_widgets_dialog_message), true)) return } if (!permGranted) { if (!permissionRequested) { // ask for permissions requestPermissions() } else { // permissions where not granted by user action.postValue(Action.LOAD_MIN_CONTENT) message.postValue(resources.getString(R.string.permission_denied)) if(prefs.hasLocation()) { location.postValue(prefs.loadLocation()) } } } else { // permissions granted, load full content with map action.postValue(Action.LOAD_FULL_CONTENT) if (prefs.hasLocation()) { val stored = prefs.loadLocation() location.postValue(stored) } else { // if no location was loaded, try to find current location startLocationService() } } } private fun requestPermissions() { action.postValue(Action.REQUEST_PERM) permissionRequested = true } private fun startLocationService() { if (!locMgr.isProviderEnabled(LocationManager.GPS_PROVIDER) && !locMgr.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) { // no gps or network provider enabled message.postValue(resources.getString(R.string.location_enable)) } else { try { // choose best provider for medium accuracy val criteria = Criteria() criteria.horizontalAccuracy = Criteria.ACCURACY_MEDIUM val bestProvider = locMgr.getBestProvider(criteria, true) // first get best last known location var lastKnownLocation: Location? = null for (provider in locMgr.getProviders(false)) { val current = locMgr.getLastKnownLocation(provider) ?: continue if (lastKnownLocation == null) { // if no last location, set currently checked as last lastKnownLocation = current } else if (lastKnownLocation.accuracy > current.accuracy) { // if current is better then last know, use it lastKnownLocation = current } } // display last known location lastKnownLocation?.let { this.location.postValue(PrefHelper.LocationData(it.latitude, it.longitude)) } // register for location updates bestProvider?.let { locationActive.postValue(true) locMgr.requestLocationUpdates(it, 10, 0f, this) } } catch (e: SecurityException) { requestPermissions() } } } private fun stopLocationService() { locMgr.removeUpdates(this) locationActive.postValue(false) } /** * Saves coordinates to shared preferences */ fun saveCoordinates(latitude: Float?, longitude: Float?) { if (latitude == null || longitude == null) { dialog.postValue(DialogData(resources.getString(R.string.empty_dialog_title), resources.getString(R.string.empty_dialog_message))) return } prefs.saveLocation(latitude, longitude) if (openedFromWidget) { message.postValue(resources.getString(R.string.coordinates_saved)) action.postValue(Action.UPDATE_FINISH) } else { action.postValue(Action.UPDATE_WIDGETS) dialog.postValue(DialogData(resources.getString(R.string.success_dialog_title), resources.getString(R.string.success_dialog_message))) } stopLocationService() } fun pause() { stopLocationService() } fun locationButtonClicked() { locationActive.value?.let { if (it) { stopLocationService() } else { startLocationService() } } } fun useMapClicked() { requestPermissions() } override fun onLocationChanged(location: Location?) { location?.let { this.location.postValue(PrefHelper.LocationData(it.latitude, it.longitude)) if (it.accuracy < LOCATION_ACCURACY) { // stop service if high enough accuracy is achieved stopLocationService() } } } override fun onStatusChanged(provider: String?, status: Int, extras: Bundle?) { } override fun onProviderEnabled(provider: String?) { } override fun onProviderDisabled(provider: String?) { } data class DialogData(val title: String, val message: String, val closeOnDismiss: Boolean = false) companion object { private const val LOCATION_ACCURACY = 10f } }
gpl-2.0
b35053253847c870b227d1180e318b11
34.708108
158
0.630583
5.168232
false
false
false
false
wordpress-mobile/WordPress-Android
WordPress/src/main/java/org/wordpress/android/ui/reader/utils/PostSubscribersApiCallsProvider.kt
1
12152
package org.wordpress.android.ui.reader.utils import com.android.volley.VolleyError import com.wordpress.rest.RestRequest.ErrorListener import com.wordpress.rest.RestRequest.Listener import org.json.JSONObject import org.wordpress.android.R import org.wordpress.android.WordPress import org.wordpress.android.ui.reader.utils.PostSubscribersApiCallsProvider.PostSubscribersCallResult.Failure import org.wordpress.android.ui.reader.utils.PostSubscribersApiCallsProvider.PostSubscribersCallResult.Success import org.wordpress.android.util.AppLog import org.wordpress.android.util.AppLog.T import org.wordpress.android.util.VolleyUtils import org.wordpress.android.viewmodel.ContextProvider import javax.inject.Inject import kotlin.coroutines.resume import kotlin.coroutines.suspendCoroutine class PostSubscribersApiCallsProvider @Inject constructor( private val contextProvider: ContextProvider ) { suspend fun getCanFollowComments(blogId: Long): Boolean = suspendCoroutine { cont -> val endPointPath = "/sites/$blogId/" val listener = Listener { jsonObject -> val result = canFollowComments(blogId, jsonObject) AppLog.d( T.READER, "getCanFollowComments > Succeeded [blogId=$blogId - result = $result]" ) cont.resume(result is Success) } val errorListener = ErrorListener { volleyError -> AppLog.d( T.READER, "getCanFollowComments > Failed [blogId=$blogId - volleyError = $volleyError]" ) cont.resume(false) } WordPress.getRestClientUtilsV1_1().get( endPointPath, listener, errorListener ) } suspend fun getMySubscriptionToPost( blogId: Long, postId: Long ): PostSubscribersCallResult = suspendCoroutine { cont -> val endPointPath = "/sites/$blogId/posts/$postId/subscribers/mine" val listener = Listener { jsonObject -> val result = getFollowingStateResult(jsonObject) AppLog.d( T.READER, "getMySubscriptionToPost > Succeeded [blogId=$blogId - postId=$postId - result = $result]" ) cont.resume(result) } val errorListener = ErrorListener { volleyError -> val error = getErrorStringAndLog("getMySubscriptionToPost", blogId, postId, volleyError) cont.resume(Failure(error)) } WordPress.getRestClientUtilsV1_1().get( endPointPath, listener, errorListener ) } suspend fun subscribeMeToPost(blogId: Long, postId: Long): PostSubscribersCallResult = suspendCoroutine { cont -> val endPointPath = "/sites/$blogId/posts/$postId/subscribers/new" val listener = Listener { jsonObject -> val result = wasSubscribed(jsonObject) AppLog.d( T.READER, "subscribeMeToPost > Succeeded [blogId=$blogId - postId=$postId - result = $result]" ) cont.resume(result) } val errorListener = ErrorListener { volleyError -> val error = getErrorStringAndLog("subscribeMeToPost", blogId, postId, volleyError) cont.resume(Failure(error)) } WordPress.getRestClientUtilsV1_1().post( endPointPath, listener, errorListener ) } suspend fun unsubscribeMeFromPost( blogId: Long, postId: Long ): PostSubscribersCallResult = suspendCoroutine { cont -> val endPointPath = "/sites/$blogId/posts/$postId/subscribers/mine/delete" val listener = Listener { jsonObject -> val result = wasUnsubscribed(jsonObject) AppLog.d( T.READER, "unsubscribeMeFromPost > Succeeded [blogId=$blogId - postId=$postId - result = $result]" ) cont.resume(result) } val errorListener = ErrorListener { volleyError -> val error = getErrorStringAndLog("unsubscribeMeFromPost", blogId, postId, volleyError) cont.resume(Failure(error)) } WordPress.getRestClientUtilsV1_1().post( endPointPath, listener, errorListener ) } suspend fun managePushNotificationsForPost( blogId: Long, postId: Long, activate: Boolean ): PostSubscribersCallResult = suspendCoroutine { cont -> val endPointPath = "/sites/$blogId/posts/$postId/subscribers/mine/update" val listener = Listener { jsonObject -> val result = if (activate) { wasSubscribedForPushNotifications(jsonObject) } else { wasUnsubscribedFromPushNotifications(jsonObject) } AppLog.d( T.READER, "managePushNotificationsForPost > Succeeded [blogId=$blogId - postId=$postId - result = $result]" ) cont.resume(result) } val errorListener = ErrorListener { volleyError -> val error = getErrorStringAndLog("managePushNotificationsForPost", blogId, postId, volleyError) cont.resume(Failure(error)) } val params = mutableMapOf<String, String>() params["receive_notifications"] = if (activate) "true" else "false" WordPress.getRestClientUtilsV1_1().post( endPointPath, params, null, listener, errorListener ) } private fun getErrorStringAndLog( functionName: String, blogId: Long, postId: Long, volleyError: VolleyError? ): String { val error = VolleyUtils.errStringFromVolleyError(volleyError) return if (error.isNullOrEmpty()) { AppLog.d( T.READER, "$functionName > Failed with empty string " + "[blogId=$blogId - postId=$postId - volleyError = $volleyError]" ) contextProvider.getContext().getString(R.string.reader_follow_comments_get_status_error) } else { AppLog.d( T.READER, "$functionName > Failed [blogId=$blogId - postId=$postId - error = $error]" ) error } } private fun getFollowingStateResult(json: JSONObject?): PostSubscribersCallResult { return json?.let { if (it.has(KEY_I_SUBSCRIBE) && (it.has(KEY_RECEIVES_NOTIFICATIONS))) { Success( isFollowing = it.optBoolean(KEY_I_SUBSCRIBE, false), isReceivingNotifications = it.optBoolean(KEY_RECEIVES_NOTIFICATIONS, false) ) } else { Failure(contextProvider.getContext().getString(R.string.reader_follow_comments_bad_format_response)) } } ?: Failure(contextProvider.getContext().getString(R.string.reader_follow_comments_null_response)) } private fun canFollowComments(blogId: Long, json: JSONObject?): PostSubscribersCallResult { return json?.let { if (it.has("ID") && it.optLong("ID", -1) == blogId) { Success(isFollowing = false, isReceivingNotifications = false) } else { Failure(contextProvider.getContext().getString(R.string.reader_follow_comments_bad_format_response)) } } ?: Failure(contextProvider.getContext().getString(R.string.reader_follow_comments_null_response)) } private fun wasSubscribed(json: JSONObject?): PostSubscribersCallResult { return json?.let { val success = it.optBoolean(KEY_SUCCESS, false) val subscribed = it.optBoolean(KEY_I_SUBSCRIBE, false) val receivingNotifications = it.optBoolean(KEY_RECEIVES_NOTIFICATIONS, false) if (success) { if (subscribed) { Success(isFollowing = true, isReceivingNotifications = receivingNotifications) } else { Failure(contextProvider.getContext().getString( R.string.reader_follow_comments_could_not_subscribe_error )) } } else { Failure(contextProvider.getContext().getString(R.string.reader_follow_comments_bad_format_response)) } } ?: Failure(contextProvider.getContext().getString(R.string.reader_follow_comments_null_response)) } private fun wasUnsubscribed(json: JSONObject?): PostSubscribersCallResult { return json?.let { val success = it.optBoolean(KEY_SUCCESS, false) val subscribed = it.optBoolean(KEY_I_SUBSCRIBE, true) val receivingNotifications = it.optBoolean(KEY_RECEIVES_NOTIFICATIONS, false) if (success) { if (!subscribed) { Success(isFollowing = false, isReceivingNotifications = receivingNotifications) } else { Failure(contextProvider.getContext().getString( R.string.reader_follow_comments_could_not_unsubscribe_error )) } } else { Failure(contextProvider.getContext().getString(R.string.reader_follow_comments_bad_format_response)) } } ?: Failure(contextProvider.getContext().getString(R.string.reader_follow_comments_null_response)) } private fun wasSubscribedForPushNotifications(json: JSONObject?): PostSubscribersCallResult { return json?.let { val subscribed = it.optBoolean(KEY_I_SUBSCRIBE, false) val receivingNotifications = it.optBoolean(KEY_RECEIVES_NOTIFICATIONS, false) if (subscribed) { if (receivingNotifications) { Success(isFollowing = subscribed, isReceivingNotifications = receivingNotifications) } else { Failure(contextProvider.getContext().getString( R.string.reader_follow_comments_could_not_unsubscribe_error )) } } else { Failure(contextProvider.getContext().getString(R.string.reader_follow_comments_bad_format_response)) } } ?: Failure(contextProvider.getContext().getString(R.string.reader_follow_comments_null_response)) } private fun wasUnsubscribedFromPushNotifications(json: JSONObject?): PostSubscribersCallResult { return json?.let { val subscribed = it.optBoolean(KEY_I_SUBSCRIBE, false) val receivingNotifications = it.optBoolean(KEY_RECEIVES_NOTIFICATIONS, true) if (subscribed) { if (!receivingNotifications) { Success(isFollowing = subscribed, isReceivingNotifications = receivingNotifications) } else { Failure(contextProvider.getContext().getString( R.string.reader_follow_comments_could_not_unsubscribe_error )) } } else { Failure(contextProvider.getContext().getString(R.string.reader_follow_comments_bad_format_response)) } } ?: Failure(contextProvider.getContext().getString(R.string.reader_follow_comments_null_response)) } sealed class PostSubscribersCallResult { data class Success( val isFollowing: Boolean, val isReceivingNotifications: Boolean ) : PostSubscribersCallResult() data class Failure(val error: String) : PostSubscribersCallResult() } companion object { private const val KEY_I_SUBSCRIBE = "i_subscribe" private const val KEY_RECEIVES_NOTIFICATIONS = "receives_notifications" private const val KEY_SUCCESS = "success" } }
gpl-2.0
8c75ef46c49277795c0969ccac2f8612
39.915825
117
0.601136
5.110177
false
false
false
false
mdaniel/intellij-community
platform/platform-impl/src/com/intellij/internal/statistic/collectors/fus/plugins/PluginsUsagesCollector.kt
2
3483
// 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.internal.statistic.collectors.fus.plugins import com.intellij.ide.plugins.DisabledPluginsState.Companion.getDisabledIds import com.intellij.ide.plugins.DynamicPluginEnabler import com.intellij.ide.plugins.PluginEnabler import com.intellij.ide.plugins.PluginManagerCore import com.intellij.ide.plugins.ProjectPluginTracker import com.intellij.internal.statistic.beans.MetricEvent import com.intellij.internal.statistic.eventLog.EventLogGroup import com.intellij.internal.statistic.eventLog.events.EventFields import com.intellij.internal.statistic.eventLog.events.EventId1 import com.intellij.internal.statistic.service.fus.collectors.AllowedDuringStartupCollector import com.intellij.internal.statistic.service.fus.collectors.ApplicationUsagesCollector import com.intellij.internal.statistic.utils.getPluginInfoByDescriptor import com.intellij.internal.statistic.utils.getPluginInfoById import com.intellij.openapi.extensions.PluginId class PluginsUsagesCollector : ApplicationUsagesCollector(), AllowedDuringStartupCollector { companion object { private val GROUP = EventLogGroup("plugins", 8) private val DISABLED_PLUGIN = GROUP.registerEvent("disabled.plugin", EventFields.PluginInfo) private val ENABLED_NOT_BUNDLED_PLUGIN = GROUP.registerEvent("enabled.not.bundled.plugin", EventFields.PluginInfo) private val PER_PROJECT_ENABLED = GROUP.registerEvent("per.project.enabled", EventFields.Count) private val PER_PROJECT_DISABLED = GROUP.registerEvent("per.project.disabled", EventFields.Count) private val UNSAFE_PLUGIN = GROUP.registerEvent("unsafe.plugin", EventFields.String("unsafe_id", emptyList()), EventFields.Boolean("enabled")) } override fun getGroup(): EventLogGroup = GROUP override fun getMetrics() = HashSet<MetricEvent>().apply { addAll(getDisabledPlugins()) addAll(getEnabledNonBundledPlugins()) addAll(getPerProjectPlugins(PER_PROJECT_ENABLED, ProjectPluginTracker::enabledPluginsIds)) addAll(getPerProjectPlugins(PER_PROJECT_DISABLED, ProjectPluginTracker::disabledPluginsIds)) addAll(getNotBundledPlugins()) } private fun getDisabledPlugins() = getDisabledIds() .map { DISABLED_PLUGIN.metric(getPluginInfoById(it)) }.toSet() private fun getEnabledNonBundledPlugins() = PluginManagerCore .getLoadedPlugins() .filter { it.isEnabled && !it.isBundled } .map { getPluginInfoByDescriptor(it) } .map(ENABLED_NOT_BUNDLED_PLUGIN::metric) .toSet() private fun getPerProjectPlugins( eventId: EventId1<Int>, countProducer: (ProjectPluginTracker) -> Set<PluginId> ): Set<MetricEvent> { return when (val pluginEnabler = PluginEnabler.getInstance()) { is DynamicPluginEnabler -> pluginEnabler.trackers.values .map { countProducer(it) } .filter { it.isNotEmpty() } .map { eventId.metric(it.size) } .toSet() else -> emptySet() } } private fun getNotBundledPlugins() = PluginManagerCore .getPlugins().asSequence() .filter { !it.isBundled && !getPluginInfoByDescriptor(it).isSafeToReport() } // This will be validated by list of plugin ids from server // and ONLY provided ids will be reported .map { UNSAFE_PLUGIN.metric(it.pluginId.idString, it.isEnabled) } .toSet() }
apache-2.0
ddd3706d4d542a9e31b2dbe21f2e8e25
45.453333
129
0.755958
4.594987
false
false
false
false
ingokegel/intellij-community
plugins/markdown/core/src/org/intellij/plugins/markdown/lang/parser/MarkdownParserManager.kt
3
1923
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.intellij.plugins.markdown.lang.parser import com.intellij.openapi.Disposable import com.intellij.openapi.components.Service import com.intellij.openapi.components.service import com.intellij.openapi.util.Key import org.intellij.markdown.MarkdownElementTypes import org.intellij.markdown.ast.ASTNode import org.intellij.markdown.flavours.MarkdownFlavourDescriptor import org.intellij.markdown.parser.MarkdownParser import java.util.concurrent.atomic.AtomicReference @Service class MarkdownParserManager: Disposable { private class ParsingResult( val buffer: CharSequence, val tree: ASTNode, val bufferHash: Int = buffer.hashCode() ) private val lastParsingResult = AtomicReference<ParsingResult?>() @JvmOverloads fun parse(buffer: CharSequence, flavour: MarkdownFlavourDescriptor = FLAVOUR): ASTNode { val info = lastParsingResult.get() if (info != null && info.bufferHash == buffer.hashCode() && info.buffer == buffer) { return info.tree } val parseResult = MarkdownParser(flavour).parse( MarkdownElementTypes.MARKDOWN_FILE, buffer.toString(), parseInlines = false ) lastParsingResult.set(ParsingResult(buffer, parseResult)) return parseResult } override fun dispose() { lastParsingResult.set(null) } companion object { @JvmField val FLAVOUR_DESCRIPTION = Key.create<MarkdownFlavourDescriptor>("Markdown.Flavour") @JvmField val FLAVOUR = GFMCommentAwareFlavourDescriptor() @JvmStatic fun getInstance(): MarkdownParserManager { return service() } @JvmStatic @JvmOverloads fun parseContent(buffer: CharSequence, flavour: MarkdownFlavourDescriptor = FLAVOUR): ASTNode { return getInstance().parse(buffer, flavour) } } }
apache-2.0
067e18dad9b81f29f860b003fb511e84
30.52459
140
0.74883
4.535377
false
false
false
false
ingokegel/intellij-community
java/java-tests/testSrc/com/intellij/java/configurationStore/LoadJavaProjectTest.kt
2
2207
// 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.java.configurationStore import com.intellij.openapi.application.ex.PathManagerEx import com.intellij.openapi.application.runReadAction import com.intellij.openapi.module.LanguageLevelUtil import com.intellij.openapi.module.ModuleManager import com.intellij.openapi.roots.LanguageLevelModuleExtensionImpl import com.intellij.pom.java.LanguageLevel import com.intellij.testFramework.ApplicationRule import com.intellij.testFramework.TemporaryDirectory import com.intellij.testFramework.loadProjectAndCheckResults import kotlinx.coroutines.runBlocking import org.assertj.core.api.Assertions.assertThat import org.junit.ClassRule import org.junit.Rule import org.junit.Test import java.nio.file.Paths class LoadJavaProjectTest { companion object { @JvmField @ClassRule val appRule = ApplicationRule() } @get:Rule val tempDirectory = TemporaryDirectory() @Test fun `load java project with custom language level`() = runBlocking { val projectPath = Paths.get(PathManagerEx.getCommunityHomePath()).resolve("java/java-tests/testData/configurationStore/java-module-with-custom-language-level") loadProjectAndCheckResults(listOf(projectPath), tempDirectory) { project -> val modules = ModuleManager.getInstance(project).modules.sortedBy { it.name } assertThat(modules).hasSize(2) val (bar, foo) = modules assertThat(foo.name).isEqualTo("foo") assertThat(bar.name).isEqualTo("bar") runReadAction { assertThat(LanguageLevelUtil.getEffectiveLanguageLevel(bar)).isEqualTo(LanguageLevel.JDK_11) assertThat(LanguageLevelUtil.getCustomLanguageLevel(bar)).isNull() assertThat(LanguageLevelModuleExtensionImpl.getInstance(bar).languageLevel).isNull() assertThat(LanguageLevelUtil.getEffectiveLanguageLevel(foo)).isEqualTo(LanguageLevel.JDK_1_8) assertThat(LanguageLevelUtil.getCustomLanguageLevel(foo)).isEqualTo(LanguageLevel.JDK_1_8) assertThat(LanguageLevelModuleExtensionImpl.getInstance(foo).languageLevel).isEqualTo(LanguageLevel.JDK_1_8) } } } }
apache-2.0
61dde8423868185d03fe4aff93800b8e
44.061224
163
0.791572
4.685775
false
true
false
false
GunoH/intellij-community
plugins/built-in-help/src/com/jetbrains/builtInHelp/indexer/HelpIndexer.kt
2
3927
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.jetbrains.builtInHelp.indexer import org.apache.lucene.analysis.standard.StandardAnalyzer import org.apache.lucene.document.Document import org.apache.lucene.document.Field import org.apache.lucene.document.StringField import org.apache.lucene.document.TextField import org.apache.lucene.index.IndexWriter import org.apache.lucene.index.IndexWriterConfig import org.apache.lucene.store.FSDirectory import org.jsoup.Jsoup import java.io.File import java.io.IOException import java.nio.file.Files import java.nio.file.Paths class HelpIndexer @Throws(IOException::class) internal constructor(indexDir: String) { private val writer: IndexWriter private val queue = ArrayList<File>() init { val dir = FSDirectory.open(Paths.get(indexDir)) val config = IndexWriterConfig(analyzer) writer = IndexWriter(dir, config) } @Throws(IOException::class) fun indexFileOrDirectory(fileName: String) { addFiles(File(fileName)) for (f in queue) { try { val doc = Document() val parsedDocument = Jsoup.parse(f, "UTF-8") val content = StringBuilder() val lineSeparator = System.lineSeparator() parsedDocument.body().getElementsByClass("article")[0].children() .filterNot { it.hasAttr("data-swiftype-index") } .forEach { content.append(it.text()).append(lineSeparator) } doc.add(TextField("contents", content.toString(), Field.Store.YES)) doc.add(StringField("filename", f.name, Field.Store.YES)) doc.add(StringField("title", parsedDocument.title(), Field.Store.YES)) writer.addDocument(doc) println("Added: $f") } catch (e: Throwable) { println("Could not add: $f because ${e.message}") } } queue.clear() } private fun addFiles(file: File) { if (file.isDirectory) { val files = file.listFiles() ?: emptyArray() for (f in files) { addFiles(f) } } else { val filename = file.name.toLowerCase() if (filename.endsWith(".htm") || filename.endsWith(".html")) { queue.add(file) } } } @Throws(IOException::class) fun closeIndex() { writer.close() } companion object { private val analyzer = StandardAnalyzer() private fun doIndex(dirToStore: String, dirToIndex: String) { val indexer = HelpIndexer(dirToStore) indexer.indexFileOrDirectory(dirToIndex) indexer.closeIndex() } @Throws(IOException::class) @JvmStatic fun main(args: Array<String>) { val tokens = listOf( "<noscript><iframe src=\"//www.googletagmanager.com/ns.html?id=GTM-5P98\" height=\"0\" width=\"0\" style=\"display:none;visibility:hidden\"></iframe></noscript>", "</script><script src=\"/help/app/v2/analytics.js\"></script>", "<script>(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':", "new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],", "j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=", "'//www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);", "})(window,document,'script','dataLayer','GTM-5P98');") val files = Paths.get(args[1]).toFile().listFiles() ?: emptyArray() files.filter { it.extension == "html" }.forEach { var contents = String(Files.readAllBytes(it.toPath()), Charsets.UTF_8) println("Removing analytics code from ${it.name}") for (token in tokens) { contents = contents.replace(token, "") } contents = contents.replace("//resources.jetbrains.com/storage/help-app/", "/help/") Files.write(it.toPath(), contents.toByteArray(Charsets.UTF_8)) } doIndex(args[0], args[1]) } } }
apache-2.0
4f186e4f10de803931210c832a390b0c
32.853448
170
0.652406
3.649628
false
false
false
false
AsamK/TextSecure
app/src/main/java/org/thoughtcrime/securesms/notifications/profiles/NotificationProfiles.kt
2
2663
package org.thoughtcrime.securesms.notifications.profiles import android.content.Context import org.thoughtcrime.securesms.R import org.thoughtcrime.securesms.keyvalue.NotificationProfileValues import org.thoughtcrime.securesms.keyvalue.SignalStore import org.thoughtcrime.securesms.util.formatHours import org.thoughtcrime.securesms.util.toLocalDateTime import org.thoughtcrime.securesms.util.toLocalTime import org.thoughtcrime.securesms.util.toMillis import org.thoughtcrime.securesms.util.toOffset import java.time.LocalDateTime import java.time.ZoneId /** * Helper for determining the single, currently active Notification Profile (if any) and also how to describe * how long the active profile will be on for. */ object NotificationProfiles { @JvmStatic @JvmOverloads fun getActiveProfile(profiles: List<NotificationProfile>, now: Long = System.currentTimeMillis(), zoneId: ZoneId = ZoneId.systemDefault()): NotificationProfile? { val storeValues: NotificationProfileValues = SignalStore.notificationProfileValues() val localNow: LocalDateTime = now.toLocalDateTime(zoneId) val manualProfile: NotificationProfile? = if (now < storeValues.manuallyEnabledUntil) { profiles.firstOrNull { it.id == storeValues.manuallyEnabledProfile } } else { null } val scheduledProfile: NotificationProfile? = profiles.sortedDescending().filter { it.schedule.isCurrentlyActive(now, zoneId) }.firstOrNull { profile -> profile.schedule.startDateTime(localNow).toMillis(zoneId.toOffset()) > storeValues.manuallyDisabledAt } if (manualProfile == null || scheduledProfile == null) { return manualProfile ?: scheduledProfile } return if (manualProfile == scheduledProfile) { manualProfile } else { scheduledProfile } } fun getActiveProfileDescription(context: Context, profile: NotificationProfile, now: Long = System.currentTimeMillis()): String { val storeValues: NotificationProfileValues = SignalStore.notificationProfileValues() if (profile.id == storeValues.manuallyEnabledProfile) { if (storeValues.manuallyEnabledUntil.isForever()) { return context.getString(R.string.NotificationProfilesFragment__on) } else if (now < storeValues.manuallyEnabledUntil) { return context.getString(R.string.NotificationProfileSelection__on_until_s, storeValues.manuallyEnabledUntil.toLocalTime().formatHours(context)) } } return context.getString(R.string.NotificationProfileSelection__on_until_s, profile.schedule.endTime().formatHours(context)) } private fun Long.isForever(): Boolean { return this == Long.MAX_VALUE } }
gpl-3.0
c5bc52a3ee434838a1d1e82805a6204f
39.969231
164
0.769808
4.680141
false
false
false
false
ForgetAll/GankKotlin
app/src/main/java/com/xiasuhuei321/gankkotlin/modules/girls/WelfareMVP.kt
1
1675
package com.xiasuhuei321.gankkotlin.modules.girls import android.app.Activity import com.xiasuhuei321.gankkotlin.base.Presenter import com.xiasuhuei321.gankkotlin.data.Data import com.xiasuhuei321.gankkotlin.data.DataManager import com.xiasuhuei321.gankkotlin.network.GankDataStore import com.xiasuhuei321.gankkotlin.network.asyncUI import com.xiasuhuei321.gankkotlin.network.gankService import com.xiasuhuei321.gankkotlin.util.IntentKey import com.xiasuhuei321.gankkotlin.util.XLog import org.jetbrains.anko.startActivity class WelfarePresenter(var view: WelfareView?) : Presenter { val TAG = "WelfarePresenter" var data: MutableList<Data> = mutableListOf() var pageIndex = 0 override fun release() { view = null } fun getGirls() = asyncUI { GankDataStore.requestWelfareData(++pageIndex)?.let { data.addAll(it) view?.setData(data) } view?.closeRefresh() } fun refresh() = asyncUI { val res = gankService { getWelfare(1) }.await() if (res.isSuccessful) if (res.body().isSuccess()) { res.body().results?.let { data.clear() data.addAll(it) view?.setData(data) } } view?.closeRefresh() } fun lookBitImg(activity: Activity, position: Int) { activity.startActivity<WelfareActivity>(IntentKey.IMG_URL_ARRAY to data.map { it.url }.toTypedArray(), IntentKey.IMG_POSITION to position) } } interface WelfareView { fun setData(data: List<Data>?) fun resetData(data: List<Data>?) fun closeRefresh() }
apache-2.0
b7294118243340e2c803b1db05dcc8c8
27.896552
110
0.653731
3.922717
false
false
false
false
ktorio/ktor
ktor-http/jvm/src/io/ktor/http/HttpMessagePropertiesJvm.kt
1
1410
/* * Copyright 2014-2019 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ package io.ktor.http import java.text.* import java.util.* private val HTTP_DATE_FORMAT: SimpleDateFormat get() = SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z", Locale.US).apply { timeZone = TimeZone.getTimeZone("GMT") } private fun parseHttpDate(date: String): Date = HTTP_DATE_FORMAT.parse(date) private fun formatHttpDate(date: Date): String = HTTP_DATE_FORMAT.format(date) /** * Set `If-Modified-Since` header. */ public fun HttpMessageBuilder.ifModifiedSince(date: Date): Unit = headers.set(HttpHeaders.IfModifiedSince, formatHttpDate(date)) /** * Parse `Last-Modified` header. */ public fun HttpMessageBuilder.lastModified(): Date? = headers[HttpHeaders.LastModified]?.let { parseHttpDate(it) } /** * Parse `Expires` header. */ public fun HttpMessageBuilder.expires(): Date? = headers[HttpHeaders.Expires]?.let { parseHttpDate(it) } /** * Parse `Last-Modified` header. */ public fun HttpMessage.lastModified(): Date? = headers[HttpHeaders.LastModified]?.let { parseHttpDate(it) } /** * Parse `Expires` header. */ public fun HttpMessage.expires(): Date? = headers[HttpHeaders.Expires]?.let { parseHttpDate(it) } /** * Parse `Date` header. */ public fun HttpMessage.date(): Date? = headers[HttpHeaders.Date]?.let { parseHttpDate(it) }
apache-2.0
0b1b8c02826a55cc0d239f2876a82d90
28.375
119
0.714894
3.587786
false
false
false
false
inorichi/mangafeed
app/src/main/java/eu/kanade/tachiyomi/ui/manga/info/MangaInfoHeaderAdapter.kt
1
12464
package eu.kanade.tachiyomi.ui.manga.info import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.core.view.isVisible import androidx.core.view.updateLayoutParams import androidx.recyclerview.widget.RecyclerView import com.google.android.material.dialog.MaterialAlertDialogBuilder import eu.kanade.tachiyomi.R import eu.kanade.tachiyomi.data.database.models.Manga import eu.kanade.tachiyomi.data.preference.PreferencesHelper import eu.kanade.tachiyomi.data.track.TrackManager import eu.kanade.tachiyomi.databinding.MangaInfoHeaderBinding import eu.kanade.tachiyomi.source.Source import eu.kanade.tachiyomi.source.SourceManager import eu.kanade.tachiyomi.source.model.SManga import eu.kanade.tachiyomi.source.online.HttpSource import eu.kanade.tachiyomi.ui.base.controller.getMainAppBarHeight import eu.kanade.tachiyomi.ui.manga.MangaController import eu.kanade.tachiyomi.util.system.copyToClipboard import eu.kanade.tachiyomi.util.view.loadAnyAutoPause import kotlinx.coroutines.flow.launchIn import kotlinx.coroutines.flow.onEach import reactivecircus.flowbinding.android.view.clicks import reactivecircus.flowbinding.android.view.longClicks import uy.kohesive.injekt.injectLazy class MangaInfoHeaderAdapter( private val controller: MangaController, private val fromSource: Boolean, private val isTablet: Boolean, ) : RecyclerView.Adapter<MangaInfoHeaderAdapter.HeaderViewHolder>() { private val trackManager: TrackManager by injectLazy() private val preferences: PreferencesHelper by injectLazy() private val sourceManager: SourceManager by injectLazy() private var manga: Manga = controller.presenter.manga private var source: Source = controller.presenter.source private var trackCount: Int = 0 private lateinit var binding: MangaInfoHeaderBinding override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): HeaderViewHolder { binding = MangaInfoHeaderBinding.inflate(LayoutInflater.from(parent.context), parent, false) updateCoverPosition() // Expand manga info if navigated from source listing or explicitly set to // (e.g. on tablets) binding.mangaSummarySection.expanded = fromSource || isTablet return HeaderViewHolder(binding.root) } override fun getItemCount(): Int = 1 override fun getItemId(position: Int): Long = hashCode().toLong() override fun onBindViewHolder(holder: HeaderViewHolder, position: Int) { holder.bind() } /** * Update the view with manga information. * * @param manga manga object containing information about manga. * @param source the source of the manga. */ fun update(manga: Manga, source: Source) { this.manga = manga this.source = source update() } fun update() { notifyItemChanged(0, this) } fun setTrackingCount(trackCount: Int) { this.trackCount = trackCount update() } private fun updateCoverPosition() { if (isTablet) return val appBarHeight = controller.getMainAppBarHeight() binding.mangaCover.updateLayoutParams<ViewGroup.MarginLayoutParams> { topMargin += appBarHeight } } inner class HeaderViewHolder(private val view: View) : RecyclerView.ViewHolder(view) { fun bind() { // For rounded corners binding.mangaCover.clipToOutline = true binding.btnFavorite.clicks() .onEach { controller.onFavoriteClick() } .launchIn(controller.viewScope) if (controller.presenter.manga.favorite && controller.presenter.getCategories().isNotEmpty()) { binding.btnFavorite.longClicks() .onEach { controller.onCategoriesClick() } .launchIn(controller.viewScope) } with(binding.btnTracking) { if (trackManager.hasLoggedServices()) { isVisible = true if (trackCount > 0) { setIconResource(R.drawable.ic_done_24dp) text = view.context.resources.getQuantityString( R.plurals.num_trackers, trackCount, trackCount ) isActivated = true } else { setIconResource(R.drawable.ic_sync_24dp) text = view.context.getString(R.string.manga_tracking_tab) isActivated = false } clicks() .onEach { controller.onTrackingClick() } .launchIn(controller.viewScope) } else { isVisible = false } } if (controller.presenter.source is HttpSource) { binding.btnWebview.isVisible = true binding.btnWebview.clicks() .onEach { controller.openMangaInWebView() } .launchIn(controller.viewScope) } binding.mangaFullTitle.longClicks() .onEach { controller.activity?.copyToClipboard( view.context.getString(R.string.title), binding.mangaFullTitle.text.toString() ) } .launchIn(controller.viewScope) binding.mangaFullTitle.clicks() .onEach { controller.performGlobalSearch(binding.mangaFullTitle.text.toString()) } .launchIn(controller.viewScope) binding.mangaAuthor.longClicks() .onEach { controller.activity?.copyToClipboard( binding.mangaAuthor.text.toString(), binding.mangaAuthor.text.toString() ) } .launchIn(controller.viewScope) binding.mangaAuthor.clicks() .onEach { controller.performGlobalSearch(binding.mangaAuthor.text.toString()) } .launchIn(controller.viewScope) binding.mangaArtist.longClicks() .onEach { controller.activity?.copyToClipboard( binding.mangaArtist.text.toString(), binding.mangaArtist.text.toString() ) } .launchIn(controller.viewScope) binding.mangaArtist.clicks() .onEach { controller.performGlobalSearch(binding.mangaArtist.text.toString()) } .launchIn(controller.viewScope) binding.mangaCover.clicks() .onEach { controller.showFullCoverDialog() } .launchIn(controller.viewScope) binding.mangaCover.longClicks() .onEach { showCoverOptionsDialog() } .launchIn(controller.viewScope) setMangaInfo() } private fun showCoverOptionsDialog() { val options = listOfNotNull( R.string.action_share, R.string.action_save, // Can only edit cover for library manga if (manga.favorite) R.string.action_edit else null ).map(controller.activity!!::getString).toTypedArray() MaterialAlertDialogBuilder(controller.activity!!) .setTitle(R.string.manga_cover) .setItems(options) { _, item -> when (item) { 0 -> controller.shareCover() 1 -> controller.saveCover() 2 -> controller.changeCover() } } .setNegativeButton(android.R.string.cancel, null) .show() } /** * Update the view with manga information. * * @param manga manga object containing information about manga. * @param source the source of the manga. */ private fun setMangaInfo() { // Update full title TextView. binding.mangaFullTitle.text = if (manga.title.isBlank()) { view.context.getString(R.string.unknown) } else { manga.title } // Update author TextView. binding.mangaAuthor.text = if (manga.author.isNullOrBlank()) { view.context.getString(R.string.unknown_author) } else { manga.author } // Update artist TextView. val hasArtist = !manga.artist.isNullOrBlank() && manga.artist != manga.author binding.mangaArtist.isVisible = hasArtist if (hasArtist) { binding.mangaArtist.text = manga.artist } // If manga source is known update source TextView. val mangaSource = source.toString() with(binding.mangaSource) { val enabledLanguages = preferences.enabledLanguages().get() .filterNot { it in listOf("all", "other") } val hasOneActiveLanguages = enabledLanguages.size == 1 val isInEnabledLanguages = source.lang in enabledLanguages text = when { // For edge cases where user disables a source they got manga of in their library. hasOneActiveLanguages && !isInEnabledLanguages -> mangaSource // Hide the language tag when only one language is used. hasOneActiveLanguages && isInEnabledLanguages -> source.name else -> mangaSource } setOnClickListener { controller.performSearch(sourceManager.getOrStub(source.id).name) } } // Update manga status. val (statusDrawable, statusString) = when (manga.status) { SManga.ONGOING -> R.drawable.ic_status_ongoing_24dp to R.string.ongoing SManga.COMPLETED -> R.drawable.ic_status_completed_24dp to R.string.completed SManga.LICENSED -> R.drawable.ic_status_licensed_24dp to R.string.licensed SManga.PUBLISHING_FINISHED -> R.drawable.ic_done_24dp to R.string.publishing_finished SManga.CANCELLED -> R.drawable.ic_close_24dp to R.string.cancelled SManga.ON_HIATUS -> R.drawable.ic_pause_24dp to R.string.on_hiatus else -> R.drawable.ic_status_unknown_24dp to R.string.unknown } binding.mangaStatusIcon.setImageResource(statusDrawable) binding.mangaStatus.setText(statusString) // Set the favorite drawable to the correct one. setFavoriteButtonState(manga.favorite) // Set cover if changed. binding.backdrop.loadAnyAutoPause(manga) binding.mangaCover.loadAnyAutoPause(manga) // Manga info section binding.mangaSummarySection.setTags(manga.getGenres(), controller::performGenreSearch) binding.mangaSummarySection.description = manga.description binding.mangaSummarySection.isVisible = !manga.description.isNullOrBlank() || !manga.genre.isNullOrBlank() } /** * Update favorite button with correct drawable and text. * * @param isFavorite determines if manga is favorite or not. */ private fun setFavoriteButtonState(isFavorite: Boolean) { // Set the Favorite drawable to the correct one. // Border drawable if false, filled drawable if true. val (iconResource, stringResource) = when (isFavorite) { true -> R.drawable.ic_favorite_24dp to R.string.in_library false -> R.drawable.ic_favorite_border_24dp to R.string.add_to_library } binding.btnFavorite.apply { setIconResource(iconResource) text = context.getString(stringResource) isActivated = isFavorite } } } }
apache-2.0
222150b7c7e1dd11976ee014b20195b8
38.318612
118
0.58673
5.290323
false
false
false
false
UdiOshi85/GenericSettings
app/src/main/java/com/oshi/genericsettings/kotlin/expandable/ExpandableTypesActivity.kt
1
1964
package com.oshi.genericsettings.kotlin.expandable import android.os.Bundle import android.support.design.widget.CoordinatorLayout import android.support.v7.app.AppCompatActivity import android.support.v7.widget.RecyclerView import android.support.v7.widget.Toolbar import android.view.MenuItem import com.oshi.genericsettings.R import com.oshi.genericsettings.java.expandable.ExpandableTypesPresenter import com.oshi.libgenericsettings.adapter.SettingsAdapter import com.oshi.libgenericsettings.presenter.ISettingsPresenter class ExpandableTypesActivity : AppCompatActivity() { lateinit var adapter : SettingsAdapter lateinit var recyclerView : RecyclerView lateinit var toolbar : Toolbar lateinit var coordinatorLayout : CoordinatorLayout lateinit var expandableTypesPresenter : ISettingsPresenter override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_expandables_types) toolbar = findViewById(R.id.toolbar) setSupportActionBar(toolbar) supportActionBar?.setDisplayHomeAsUpEnabled(true) supportActionBar?.setDisplayShowHomeEnabled(true) recyclerView = findViewById(R.id.recyclerView) coordinatorLayout = findViewById(R.id.coordinatorLayout) expandableTypesPresenter = ExpandableTypesPresenter(coordinatorLayout, object : ISettingsPresenter.OnSettingsChangedListener { override fun notifyItemChanged(position: Int) { adapter.notifyItemChanged(position) } }) adapter = SettingsAdapter(this, expandableTypesPresenter) recyclerView.adapter = adapter } override fun onOptionsItemSelected(item: MenuItem?): Boolean { val itemId = item?.itemId if (itemId == android.R.id.home) { onBackPressed() return true } return super.onOptionsItemSelected(item) } }
apache-2.0
dc0bb055a422c1d13ed5b206945ede61
29.703125
134
0.744908
5.336957
false
false
false
false
mdanielwork/intellij-community
uast/uast-java/src/org/jetbrains/uast/java/JavaUastLanguagePlugin.kt
4
16403
/* * Copyright 2000-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.uast.java import com.intellij.lang.Language import com.intellij.lang.java.JavaLanguage import com.intellij.psi.* import com.intellij.psi.util.PsiTreeUtil import org.jetbrains.uast.* import org.jetbrains.uast.java.expressions.JavaUAnnotationCallExpression import org.jetbrains.uast.java.expressions.JavaUNamedExpression import org.jetbrains.uast.java.expressions.JavaUSynchronizedExpression import org.jetbrains.uast.java.kinds.JavaSpecialExpressionKinds class JavaUastLanguagePlugin : UastLanguagePlugin { override val priority: Int = 0 override fun isFileSupported(fileName: String): Boolean = fileName.endsWith(".java", ignoreCase = true) override val language: Language get() = JavaLanguage.INSTANCE override fun isExpressionValueUsed(element: UExpression): Boolean = when (element) { is JavaUDeclarationsExpression -> false is UnknownJavaExpression -> (element.uastParent as? UExpression)?.let { isExpressionValueUsed(it) } ?: false else -> { val statement = element.psi as? PsiStatement statement != null && statement.parent !is PsiExpressionStatement } } override fun getMethodCallExpression( element: PsiElement, containingClassFqName: String?, methodName: String ): UastLanguagePlugin.ResolvedMethod? { if (element !is PsiMethodCallExpression) return null if (element.methodExpression.referenceName != methodName) return null val uElement = convertElementWithParent(element, null) val callExpression = when (uElement) { is UCallExpression -> uElement is UQualifiedReferenceExpression -> uElement.selector as UCallExpression else -> error("Invalid element type: $uElement") } val method = callExpression.resolve() ?: return null if (containingClassFqName != null) { val containingClass = method.containingClass ?: return null if (containingClass.qualifiedName != containingClassFqName) return null } return UastLanguagePlugin.ResolvedMethod(callExpression, method) } override fun getConstructorCallExpression( element: PsiElement, fqName: String ): UastLanguagePlugin.ResolvedConstructor? { if (element !is PsiNewExpression) return null val simpleName = fqName.substringAfterLast('.') if (element.classReference?.referenceName != simpleName) return null val callExpression = convertElementWithParent(element, null) as? UCallExpression ?: return null val constructorMethod = element.resolveConstructor() ?: return null val containingClass = constructorMethod.containingClass ?: return null if (containingClass.qualifiedName != fqName) return null return UastLanguagePlugin.ResolvedConstructor(callExpression, constructorMethod, containingClass) } override fun convertElement(element: PsiElement, parent: UElement?, requiredType: Class<out UElement>?): UElement? { return convertDeclaration(element, parent, requiredType) ?: JavaConverter.convertPsiElement(element, parent, requiredType) } override fun convertElementWithParent(element: PsiElement, requiredType: Class<out UElement>?): UElement? { if (element is PsiJavaFile) return requiredType.el<UFile> { JavaUFile(element, this) } return convertDeclaration(element, null, requiredType) ?: JavaConverter.convertPsiElement(element, null, requiredType) } private fun convertDeclaration(element: PsiElement, givenParent: UElement?, requiredType: Class<out UElement>?): UElement? { fun <P : PsiElement> build(ctor: (P, UElement?) -> UElement): () -> UElement? { return fun(): UElement? { return ctor(element as P, givenParent) } } return with(requiredType) { when (element) { is PsiJavaFile -> el<UFile> { JavaUFile(element, this@JavaUastLanguagePlugin) } is UDeclaration -> el<UDeclaration> { element } is PsiClass -> el<UClass> { JavaUClass.create(element, givenParent) } is PsiMethod -> el<UMethod> { JavaUMethod.create(element, this@JavaUastLanguagePlugin, givenParent) } is PsiClassInitializer -> el<UClassInitializer>(build(::JavaUClassInitializer)) is PsiEnumConstant -> el<UEnumConstant>(build(::JavaUEnumConstant)) is PsiLocalVariable -> el<ULocalVariable>(build(::JavaULocalVariable)) is PsiParameter -> el<UParameter>(build(::JavaUParameter)) is PsiField -> el<UField>(build(::JavaUField)) is PsiVariable -> el<UVariable>(build(::JavaUVariable)) is PsiAnnotation -> el<UAnnotation>(build(::JavaUAnnotation)) else -> null } } } } internal inline fun <reified ActualT : UElement> Class<out UElement>?.el(f: () -> UElement?): UElement? { return if (this == null || isAssignableFrom(ActualT::class.java)) f() else null } internal inline fun <reified ActualT : UElement> Class<out UElement>?.expr(f: () -> UExpression?): UExpression? { return if (this == null || isAssignableFrom(ActualT::class.java)) f() else null } internal object JavaConverter { internal tailrec fun unwrapElements(element: PsiElement?): PsiElement? = when (element) { is PsiExpressionStatement -> unwrapElements(element.parent) is PsiParameterList -> unwrapElements(element.parent) is PsiAnnotationParameterList -> unwrapElements(element.parent) is PsiModifierList -> unwrapElements(element.parent) is PsiExpressionList -> unwrapElements(element.parent) is PsiPackageStatement -> unwrapElements(element.parent) is PsiImportList -> unwrapElements(element.parent) else -> element } internal fun convertPsiElement(el: PsiElement, givenParent: UElement?, requiredType: Class<out UElement>? = null): UElement? { fun <P : PsiElement> build(ctor: (P, UElement?) -> UElement): () -> UElement? { return fun(): UElement? { return ctor(el as P, givenParent) } } return with(requiredType) { when (el) { is PsiCodeBlock -> el<UBlockExpression>(build(::JavaUCodeBlockExpression)) is PsiResourceExpression -> convertExpression(el.expression, givenParent, requiredType) is PsiExpression -> convertExpression(el, givenParent, requiredType) is PsiStatement -> convertStatement(el, givenParent, requiredType) is PsiImportStatementBase -> el<UImportStatement>(build(::JavaUImportStatement)) is PsiIdentifier -> el<USimpleNameReferenceExpression> { JavaUSimpleNameReferenceExpression(el, el.text, givenParent) } ?: el<UIdentifier> { LazyParentUIdentifier(el, givenParent) } is PsiNameValuePair -> el<UNamedExpression>(build(::JavaUNamedExpression)) is PsiArrayInitializerMemberValue -> el<UCallExpression>(build(::JavaAnnotationArrayInitializerUCallExpression)) is PsiTypeElement -> el<UTypeReferenceExpression>(build(::JavaUTypeReferenceExpression)) is PsiJavaCodeReferenceElement -> convertReference(el, givenParent, requiredType) is PsiAnnotation -> el.takeIf { PsiTreeUtil.getParentOfType(it, PsiAnnotationMemberValue::class.java, true) != null }?.let { el<UExpression> { JavaUAnnotationCallExpression(it, givenParent) } } else -> null } } } internal fun convertBlock(block: PsiCodeBlock, parent: UElement?): UBlockExpression = JavaUCodeBlockExpression(block, parent) internal fun convertReference(reference: PsiJavaCodeReferenceElement, givenParent: UElement?, requiredType: Class<out UElement>?): UExpression? { return with(requiredType) { if (reference.isQualified) { expr<UQualifiedReferenceExpression> { JavaUQualifiedReferenceExpression(reference, givenParent) } } else { val name = reference.referenceName ?: "<error name>" expr<USimpleNameReferenceExpression> { JavaUSimpleNameReferenceExpression(reference, name, givenParent, reference) } } } } internal fun convertExpression(el: PsiExpression, givenParent: UElement?, requiredType: Class<out UElement>? = null): UExpression? { fun <P : PsiElement> build(ctor: (P, UElement?) -> UExpression): () -> UExpression? { return fun(): UExpression? { return ctor(el as P, givenParent) } } return with(requiredType) { when (el) { is PsiAssignmentExpression -> expr<UBinaryExpression>(build(::JavaUAssignmentExpression)) is PsiConditionalExpression -> expr<UIfExpression>(build(::JavaUTernaryIfExpression)) is PsiNewExpression -> { if (el.anonymousClass != null) expr<UObjectLiteralExpression>(build(::JavaUObjectLiteralExpression)) else expr<UCallExpression>(build(::JavaConstructorUCallExpression)) } is PsiMethodCallExpression -> { if (el.methodExpression.qualifierExpression != null) { if (requiredType == null || requiredType.isAssignableFrom(UQualifiedReferenceExpression::class.java) || requiredType.isAssignableFrom(UCallExpression::class.java)) { val expr = JavaUCompositeQualifiedExpression(el, givenParent).apply { receiverInitializer = { convertOrEmpty(el.methodExpression.qualifierExpression!!, this) } selector = JavaUCallExpression(el, this) } if (requiredType?.isAssignableFrom(UCallExpression::class.java) == true) expr.selector else expr } else null } else expr<UCallExpression>(build(::JavaUCallExpression)) } is PsiArrayInitializerExpression -> expr<UCallExpression>(build(::JavaArrayInitializerUCallExpression)) is PsiBinaryExpression -> expr<UBinaryExpression>(build(::JavaUBinaryExpression)) // Should go after PsiBinaryExpression since it implements PsiPolyadicExpression is PsiPolyadicExpression -> expr<UPolyadicExpression>(build(::JavaUPolyadicExpression)) is PsiParenthesizedExpression -> expr<UParenthesizedExpression>(build(::JavaUParenthesizedExpression)) is PsiPrefixExpression -> expr<UPrefixExpression>(build(::JavaUPrefixExpression)) is PsiPostfixExpression -> expr<UPostfixExpression>(build(::JavaUPostfixExpression)) is PsiLiteralExpression -> expr<ULiteralExpression>(build(::JavaULiteralExpression)) is PsiMethodReferenceExpression -> expr<UCallableReferenceExpression>(build(::JavaUCallableReferenceExpression)) is PsiReferenceExpression -> convertReference(el, givenParent, requiredType) is PsiThisExpression -> expr<UThisExpression>(build(::JavaUThisExpression)) is PsiSuperExpression -> expr<USuperExpression>(build(::JavaUSuperExpression)) is PsiInstanceOfExpression -> expr<UBinaryExpressionWithType>(build(::JavaUInstanceCheckExpression)) is PsiTypeCastExpression -> expr<UBinaryExpressionWithType>(build(::JavaUTypeCastExpression)) is PsiClassObjectAccessExpression -> expr<UClassLiteralExpression>(build(::JavaUClassLiteralExpression)) is PsiArrayAccessExpression -> expr<UArrayAccessExpression>(build(::JavaUArrayAccessExpression)) is PsiLambdaExpression -> expr<ULambdaExpression>(build(::JavaULambdaExpression)) else -> expr<UExpression>(build(::UnknownJavaExpression)) } } } internal fun convertStatement(el: PsiStatement, givenParent: UElement?, requiredType: Class<out UElement>? = null): UExpression? { fun <P : PsiElement> build(ctor: (P, UElement?) -> UExpression): () -> UExpression? { return fun(): UExpression? { return ctor(el as P, givenParent) } } return with(requiredType) { when (el) { is PsiDeclarationStatement -> expr<UDeclarationsExpression> { convertDeclarations(el.declaredElements, givenParent ?: JavaConverter.unwrapElements(el.parent).toUElement()) } is PsiExpressionListStatement -> expr<UDeclarationsExpression> { convertDeclarations(el.expressionList.expressions, givenParent ?: JavaConverter.unwrapElements(el.parent).toUElement()) } is PsiBlockStatement -> expr<UBlockExpression>(build(::JavaUBlockExpression)) is PsiLabeledStatement -> expr<ULabeledExpression>(build(::JavaULabeledExpression)) is PsiExpressionStatement -> convertExpression(el.expression, givenParent, requiredType) is PsiIfStatement -> expr<UIfExpression>(build(::JavaUIfExpression)) is PsiSwitchStatement -> expr<USwitchExpression>(build(::JavaUSwitchExpression)) is PsiWhileStatement -> expr<UWhileExpression>(build(::JavaUWhileExpression)) is PsiDoWhileStatement -> expr<UDoWhileExpression>(build(::JavaUDoWhileExpression)) is PsiForStatement -> expr<UForExpression>(build(::JavaUForExpression)) is PsiForeachStatement -> expr<UForEachExpression>(build(::JavaUForEachExpression)) is PsiBreakStatement -> expr<UBreakExpression>(build(::JavaUBreakExpression)) is PsiContinueStatement -> expr<UContinueExpression>(build(::JavaUContinueExpression)) is PsiReturnStatement -> expr<UReturnExpression>(build(::JavaUReturnExpression)) is PsiAssertStatement -> expr<UCallExpression>(build(::JavaUAssertExpression)) is PsiThrowStatement -> expr<UThrowExpression>(build(::JavaUThrowExpression)) is PsiSynchronizedStatement -> expr<UBlockExpression>(build(::JavaUSynchronizedExpression)) is PsiTryStatement -> expr<UTryExpression>(build(::JavaUTryExpression)) is PsiEmptyStatement -> expr<UExpression> { UastEmptyExpression(el.parent?.toUElement()) } is PsiSwitchLabelStatement -> expr<UExpression> { when { givenParent is UExpressionList && givenParent.kind == JavaSpecialExpressionKinds.SWITCH -> findUSwitchEntry(givenParent, el) givenParent == null -> PsiTreeUtil.getParentOfType(el, PsiSwitchStatement::class.java)?.let { findUSwitchEntry(JavaUSwitchExpression(it, null).body, el) } else -> null } } else -> expr<UExpression>(build(::UnknownJavaExpression)) } } } private fun convertDeclarations(elements: Array<out PsiElement>, parent: UElement?): UDeclarationsExpression { return JavaUDeclarationsExpression(parent).apply { val declarations = mutableListOf<UDeclaration>() for (element in elements) { if (element is PsiVariable) { declarations += JavaUVariable.create(element, this) } else if (element is PsiClass) { declarations += JavaUClass.create(element, this) } } this.declarations = declarations } } internal fun convertOrEmpty(statement: PsiStatement?, parent: UElement?): UExpression { return statement?.let { convertStatement(it, parent, null) } ?: UastEmptyExpression(parent) } internal fun convertOrEmpty(expression: PsiExpression?, parent: UElement?): UExpression { return expression?.let { convertExpression(it, parent) } ?: UastEmptyExpression(parent) } internal fun convertOrNull(expression: PsiExpression?, parent: UElement?): UExpression? { return if (expression != null) convertExpression(expression, parent) else null } internal fun convertOrEmpty(block: PsiCodeBlock?, parent: UElement?): UExpression { return if (block != null) convertBlock(block, parent) else UastEmptyExpression(parent) } }
apache-2.0
5afe21d205780d677e95c29dd92e4ce7
47.532544
136
0.698592
5.532209
false
false
false
false
MarkusAmshove/Kluent
jvm/src/test/kotlin/org/amshove/kluent/tests/assertions/time/localdatetime/ShouldBeOnOrAfterShould.kt
1
838
package org.amshove.kluent.tests.assertions.time.localdatetime import org.amshove.kluent.shouldBeOnOrAfter import java.time.LocalDateTime import kotlin.test.Test import kotlin.test.assertFails class ShouldBeOnOrAfterShould { @Test fun passWhenPassingAnEarlierDate() { val dateToTest = LocalDateTime.of(2017, 3, 1, 10, 0) val dateBefore = dateToTest.minusDays(1) dateToTest shouldBeOnOrAfter dateBefore } @Test fun passWhenPassingTheSameDate() { val dateToTest = LocalDateTime.of(2017, 3, 1, 10, 0) dateToTest shouldBeOnOrAfter dateToTest } @Test fun failWhenPassingALaterDate() { val dateToTest = LocalDateTime.of(2017, 3, 1, 10, 0) val dateAfter = dateToTest.plusDays(1) assertFails { dateToTest shouldBeOnOrAfter dateAfter } } }
mit
1b502131cef023cb901f8f9ad9fb2dc6
25.21875
62
0.706444
4.067961
false
true
false
false
PaulWoitaschek/MaterialAudiobookPlayer
app/src/main/java/de/ph1b/audiobook/features/settings/dialogs/AutoRewindDialogController.kt
1
2129
package de.ph1b.audiobook.features.settings.dialogs import android.annotation.SuppressLint import android.app.Dialog import android.os.Bundle import com.afollestad.materialdialogs.MaterialDialog import com.afollestad.materialdialogs.customview.customView import de.ph1b.audiobook.R import de.ph1b.audiobook.injection.PrefKeys import de.ph1b.audiobook.injection.appComponent import de.ph1b.audiobook.misc.DialogController import de.ph1b.audiobook.misc.DialogLayoutContainer import de.ph1b.audiobook.misc.inflate import de.ph1b.audiobook.misc.onProgressChanged import de.ph1b.audiobook.persistence.pref.Pref import kotlinx.android.synthetic.main.dialog_amount_chooser.* import javax.inject.Inject import javax.inject.Named class AutoRewindDialogController : DialogController() { @field:[Inject Named(PrefKeys.AUTO_REWIND_AMOUNT)] lateinit var autoRewindAmountPref: Pref<Int> @SuppressLint("InflateParams") override fun onCreateDialog(savedViewState: Bundle?): Dialog { appComponent.inject(this) val container = DialogLayoutContainer(activity!!.layoutInflater.inflate(R.layout.dialog_amount_chooser)) val oldRewindAmount = autoRewindAmountPref.value container.seekBar.max = (MAX - MIN) * FACTOR container.seekBar.progress = (oldRewindAmount - MIN) * FACTOR container.seekBar.onProgressChanged(initialNotification = true) { val progress = it / FACTOR val autoRewindSummary = activity!!.resources.getQuantityString( R.plurals.pref_auto_rewind_summary, progress, progress ) container.textView.text = autoRewindSummary } return MaterialDialog(activity!!).apply { title(R.string.pref_auto_rewind_title) customView(view = container.containerView, scrollable = true) positiveButton(R.string.dialog_confirm) { val newRewindAmount = container.seekBar.progress / FACTOR + MIN autoRewindAmountPref.value = newRewindAmount } negativeButton(R.string.dialog_cancel) } } companion object { private const val MIN = 0 private const val MAX = 20 private const val FACTOR = 10 } }
lgpl-3.0
cb730e46a89f6ac89f1879a7b84f61d2
33.901639
94
0.760451
4.190945
false
false
false
false
JetBrains/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/createCallable/CreateSetFunctionActionFactory.kt
1
3190
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.quickfix.createFromUsage.createCallable import com.intellij.psi.util.findParentOfType import org.jetbrains.kotlin.diagnostics.Diagnostic import org.jetbrains.kotlin.idea.caches.resolve.analyze import org.jetbrains.kotlin.idea.caches.resolve.resolveToCall import org.jetbrains.kotlin.idea.inspections.isReadOnlyCollectionOrMap import org.jetbrains.kotlin.idea.project.builtIns 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.* import org.jetbrains.kotlin.resolve.calls.util.getType import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode import org.jetbrains.kotlin.types.error.ErrorUtils import org.jetbrains.kotlin.types.Variance import org.jetbrains.kotlin.types.expressions.OperatorConventions import org.jetbrains.kotlin.util.OperatorNameConventions import java.util.* object CreateSetFunctionActionFactory : CreateGetSetFunctionActionFactory(isGet = false) { override fun createCallableInfo(element: KtArrayAccessExpression, diagnostic: Diagnostic): CallableInfo? { val arrayExpr = element.arrayExpression ?: return null val arrayType = TypeInfo(arrayExpr, Variance.IN_VARIANCE) val builtIns = element.builtIns val parameters = element.indexExpressions.mapTo(ArrayList<ParameterInfo>()) { ParameterInfo(TypeInfo(it, Variance.IN_VARIANCE)) } val assignmentExpr = diagnostic.psiElement.findParentOfType<KtOperationExpression>(strict = false) ?: return null if (arrayExpr.getType(arrayExpr.analyze(BodyResolveMode.PARTIAL))?.isReadOnlyCollectionOrMap(builtIns) == true) return null val valType = when (assignmentExpr) { is KtBinaryExpression -> { TypeInfo(assignmentExpr.right ?: return null, Variance.IN_VARIANCE) } is KtUnaryExpression -> { if (assignmentExpr.operationToken !in OperatorConventions.INCREMENT_OPERATIONS) return null val rhsType = assignmentExpr.resolveToCall()?.resultingDescriptor?.returnType TypeInfo(if (rhsType == null || ErrorUtils.containsErrorType(rhsType)) builtIns.anyType else rhsType, Variance.IN_VARIANCE) } else -> return null } parameters.add(ParameterInfo(valType, "value")) val returnType = TypeInfo(builtIns.unitType, Variance.OUT_VARIANCE) return FunctionInfo( OperatorNameConventions.SET.asString(), arrayType, returnType, Collections.emptyList(), parameters, modifierList = KtPsiFactory(element.project).createModifierList(KtTokens.OPERATOR_KEYWORD) ) } }
apache-2.0
88917f6e0eac2f2cae27075ace44adb8
51.295082
158
0.752978
5
false
false
false
false
apollographql/apollo-android
apollo-api/src/commonMain/kotlin/com/apollographql/apollo3/api/json/internal/JsonWriters.kt
1
2593
@file:JvmName("-JsonWriters") package com.apollographql.apollo3.api.json.internal import com.apollographql.apollo3.annotations.ApolloInternal import com.apollographql.apollo3.api.json.BufferedSinkJsonWriter import com.apollographql.apollo3.api.json.JsonNumber import com.apollographql.apollo3.api.json.JsonWriter import com.apollographql.apollo3.api.json.MapJsonWriter import okio.Buffer import okio.ByteString import okio.ByteString.Companion.encodeUtf8 import kotlin.contracts.ExperimentalContracts import kotlin.contracts.InvocationKind import kotlin.contracts.contract import kotlin.jvm.JvmName @ApolloInternal fun JsonWriter.writeAny(value: Any?) { when (value) { null -> nullValue() is Map<*, *> -> { writeObject { value.forEach { (key, value) -> name(key.toString()) writeAny(value) } } } is List<*> -> { writeArray { value.forEach { writeAny(it) } } } is Boolean -> value(value) is Int -> value(value) is Long -> value(value) is Double -> value(value) is JsonNumber -> value(value) is String -> value(value) else -> error("Cannot write $value to Json") } } @OptIn(ExperimentalContracts::class) @ApolloInternal inline fun JsonWriter.writeObject(crossinline block: JsonWriter.() -> Unit) { contract { callsInPlace(block, InvocationKind.EXACTLY_ONCE) } beginObject() block() endObject() } @OptIn(ExperimentalContracts::class) @ApolloInternal inline fun JsonWriter.writeArray(crossinline block: JsonWriter.() -> Unit) { contract { callsInPlace(block, InvocationKind.EXACTLY_ONCE) } beginArray() block() endArray() } @OptIn(ExperimentalContracts::class) inline fun buildJsonString(indent: String? = null, crossinline block: JsonWriter.() -> Unit): String { contract { callsInPlace(block, InvocationKind.EXACTLY_ONCE) } val buffer = Buffer() BufferedSinkJsonWriter(buffer, indent).block() return buffer.readUtf8() } @OptIn(ExperimentalContracts::class) inline fun buildJsonByteString(indent: String? = null, crossinline block: JsonWriter.() -> Unit): ByteString { contract { callsInPlace(block, InvocationKind.EXACTLY_ONCE) } val buffer = Buffer() BufferedSinkJsonWriter(buffer, indent).block() return buffer.readByteString() } @OptIn(ExperimentalContracts::class) inline fun buildJsonMap(crossinline block: JsonWriter.() -> Unit): Any? { contract { callsInPlace(block, InvocationKind.EXACTLY_ONCE) } val writer = MapJsonWriter() writer.block() return writer.root() }
mit
3f0fd0a7f9122e3c5bca2f46dc5fda77
23.704762
110
0.711917
4.162119
false
false
false
false
JetBrains/intellij-community
plugins/gitlab/src/org/jetbrains/plugins/gitlab/mergerequest/ui/list/GitLabMergeRequestsListController.kt
1
3176
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.plugins.gitlab.mergerequest.ui.list import com.intellij.collaboration.messages.CollaborationToolsBundle import com.intellij.collaboration.ui.codereview.list.error.ErrorStatusPanelFactory import com.intellij.openapi.project.Project import com.intellij.ui.SimpleTextAttributes import com.intellij.util.ui.SingleComponentCenteringLayout import com.intellij.util.ui.StatusText import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.flow.combine import kotlinx.coroutines.launch import org.jetbrains.plugins.gitlab.mergerequest.ui.GitLabMergeRequestsListViewModel import org.jetbrains.plugins.gitlab.mergerequest.ui.filters.GitLabMergeRequestsFiltersValue import org.jetbrains.plugins.gitlab.util.GitLabBundle import java.awt.BorderLayout import javax.swing.JComponent import javax.swing.JPanel internal class GitLabMergeRequestsListController( project: Project, scope: CoroutineScope, private val listVm: GitLabMergeRequestsListViewModel, private val emptyText: StatusText, private val listPanel: JComponent, private val mainPanel: JPanel, ) { private val errorPanel: JComponent = createErrorPanel(project, scope, listVm) init { scope.launch { listVm.errorState.collect { error -> update(error) } } scope.launch { combine(listVm.loadingState, listVm.filterVm.searchState) { isLoading, searchState -> isLoading to searchState }.collect { (isLoading, searchState) -> updateEmptyText(isLoading, searchState, listVm.repository) } } } private fun update(error: Throwable?) { mainPanel.removeAll() val visiblePanel = if (error != null) errorPanel else listPanel mainPanel.add(visiblePanel, BorderLayout.CENTER) mainPanel.revalidate() mainPanel.repaint() } private fun updateEmptyText(isLoading: Boolean, searchState: GitLabMergeRequestsFiltersValue, repository: String) { emptyText.clear() if (isLoading) { emptyText.appendText(CollaborationToolsBundle.message("review.list.empty.state.loading")) return } if (searchState.filterCount == 0) { emptyText .appendText(GitLabBundle.message("merge.request.list.empty.state.matching.nothing", repository)) } else { emptyText .appendText(GitLabBundle.message("merge.request.list.empty.state.matching.nothing.with.filters")) .appendSecondaryText(GitLabBundle.message("merge.request.list.empty.state.clear.filters"), SimpleTextAttributes.LINK_ATTRIBUTES) { listVm.filterVm.searchState.value = GitLabMergeRequestsFiltersValue.EMPTY } } } private fun createErrorPanel(project: Project, scope: CoroutineScope, listVm: GitLabMergeRequestsListViewModel): JComponent { val errorPresenter = GitLabMergeRequestErrorStatusPresenter(project, scope, listVm.account, listVm.accountManager) val errorPanel = ErrorStatusPanelFactory.create(scope, listVm.errorState, errorPresenter) return JPanel(SingleComponentCenteringLayout()).apply { add(errorPanel) } } }
apache-2.0
59d7b1b24612855216bcd38997c2877e
37.277108
138
0.768262
4.602899
false
false
false
false
StepicOrg/stepik-android
app/src/main/java/org/stepik/android/view/banner/extension/ItemBannerBindingExtension.kt
1
1736
package org.stepik.android.view.banner.extension import android.net.Uri import androidx.appcompat.content.res.AppCompatResources import androidx.core.view.ViewCompat import androidx.fragment.app.FragmentManager import kotlinx.android.synthetic.main.item_banner.view.* import org.stepic.droid.databinding.ItemBannerBinding import org.stepik.android.domain.banner.model.Banner import org.stepik.android.view.banner.mapper.BannerResourcesMapper import org.stepik.android.view.base.routing.InternalDeeplinkRouter import org.stepik.android.view.in_app_web_view.ui.dialog.InAppWebViewDialogFragment import ru.nobird.android.view.base.ui.extension.showIfNotExists fun ItemBannerBinding.handleItemClick(banner: Banner, fragmentManager: FragmentManager) { InternalDeeplinkRouter.openInternalDeeplink(root.context, Uri.parse(banner.url)) { InAppWebViewDialogFragment .newInstance(banner.title, banner.url, isProvideAuth = false) .showIfNotExists(fragmentManager, InAppWebViewDialogFragment.TAG) } } fun ItemBannerBinding.bind(banner: Banner, bannerResourcesMapper: BannerResourcesMapper) { bannerTitle.text = banner.title bannerDescription.text = banner.description val imageRes = bannerResourcesMapper.mapBannerTypeToImageResource(banner.type) val backgroundColorRes = bannerResourcesMapper.mapBannerTypeToBackgroundColor(banner.type) val descriptionTextColorRes = bannerResourcesMapper.mapBannerTypeToDescriptionTextColor(root.context, banner.type) bannerImage.setImageResource(imageRes) ViewCompat.setBackgroundTintList(root.bannerRoot, AppCompatResources.getColorStateList(root.context, backgroundColorRes)) bannerDescription.setTextColor(descriptionTextColorRes) }
apache-2.0
5714c21d5980b49b676c28de3e68c91f
50.088235
125
0.831221
4.497409
false
false
false
false
allotria/intellij-community
platform/vcs-impl/src/com/intellij/openapi/vcs/VcsNotificationIdsHolder.kt
3
3089
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.openapi.vcs import com.intellij.notification.impl.NotificationIdsHolder class VcsNotificationIdsHolder : NotificationIdsHolder { override fun getNotificationIds(): List<String> { return listOf( EXTERNALLY_ADDED_FILES, PROJECT_CONFIGURATION_FILES_ADDED, MANAGE_IGNORE_FILES, CHERRY_PICK_ERROR, COMMIT_CANCELED, COMMIT_FAILED, COMMIT_FINISHED, COMMIT_FINISHED_WITH_WARNINGS, COMPARE_FAILED, COULD_NOT_COMPARE_WITH_BRANCH, PATCH_APPLY_ABORTED, PATCH_ALREADY_APPLIED, PATCH_APPLY_CANNOT_FIND_PATCH_FILE, PATCH_APPLY_NEW_FILES_ERROR, PATCH_APPLY_NOT_PATCH_FILE, PATCH_PARTIALLY_APPLIED, PATCH_APPLY_ROLLBACK_FAILED, PATCH_APPLY_SUCCESS, PATCH_COPIED_TO_CLIPBOARD, PATCH_CREATION_FAILED, ROOT_ADDED, ROOTS_INVALID, ROOTS_REGISTERED, SHELVE_DELETION_UNDO, SHELVE_FAILED, SHELVE_SUCCESSFUL, UNCOMMITTED_CHANGES_SAVING_ERROR ) } companion object { const val EXTERNALLY_ADDED_FILES = "externally.added.files.notification" const val PROJECT_CONFIGURATION_FILES_ADDED = "project.configuration.files.added.notification" const val MANAGE_IGNORE_FILES = "manage.ignore.files.notification" const val IGNORED_TO_EXCLUDE_NOT_FOUND = "ignored.to.exclude.not.found" const val CHERRY_PICK_ERROR = "vcs.cherry.pick.error" const val COMMIT_CANCELED = "vcs.commit.canceled" const val COMMIT_FAILED = "vcs.commit.failed" const val COMMIT_FINISHED = "vcs.commit.finished" const val COMMIT_FINISHED_WITH_WARNINGS = "vcs.commit.finished.with.warnings" const val COMPARE_FAILED = "vcs.compare.failed" const val COULD_NOT_COMPARE_WITH_BRANCH = "vcs.could.not.compare.with.branch" const val PATCH_APPLY_ABORTED = "vcs.patch.apply.aborted" const val PATCH_ALREADY_APPLIED = "vcs.patch.already.applied" const val PATCH_APPLY_CANNOT_FIND_PATCH_FILE = "vcs.patch.apply.cannot.find.patch.file" const val PATCH_APPLY_NEW_FILES_ERROR = "vcs.patch.apply.new.files.error" const val PATCH_APPLY_NOT_PATCH_FILE = "vcs.patch.apply.not.patch.type.file" const val PATCH_PARTIALLY_APPLIED = "vcs.patch.partially.applied" const val PATCH_APPLY_ROLLBACK_FAILED = "vcs.patch.apply.rollback.failed" const val PATCH_APPLY_SUCCESS = "vcs.patch.apply.success.applied" const val PATCH_COPIED_TO_CLIPBOARD = "vcs.patch.copied.to.clipboard" const val PATCH_CREATION_FAILED = "vcs.patch.creation.failed" const val ROOT_ADDED = "vcs.root.added" const val ROOTS_INVALID = "vcs.roots.invalid" const val ROOTS_REGISTERED = "vcs.roots.registered" const val SHELVE_DELETION_UNDO = "vcs.shelve.deletion.undo" const val SHELVE_FAILED = "vcs.shelve.failed" const val SHELVE_SUCCESSFUL = "vcs.shelve.successful" const val UNCOMMITTED_CHANGES_SAVING_ERROR = "vcs.uncommitted.changes.saving.error" } }
apache-2.0
ce81f580e96956f2bca36269a287827f
43.128571
140
0.720945
3.694976
false
false
false
false
allotria/intellij-community
xml/xml-psi-impl/src/com/intellij/html/embedding/HtmlEmbeddedContentSupport.kt
2
3124
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.html.embedding import com.intellij.lang.Language import com.intellij.lang.LanguageHtmlScriptContentProvider import com.intellij.lang.LanguageUtil import com.intellij.lexer.BaseHtmlLexer import com.intellij.lexer.EmbeddedTokenTypesProvider import com.intellij.lexer.Lexer import com.intellij.openapi.Disposable import com.intellij.openapi.application.Application import com.intellij.openapi.extensions.ExtensionPoint import com.intellij.openapi.extensions.ExtensionPointName import com.intellij.psi.tree.IElementType import org.jetbrains.annotations.NotNull import org.jetbrains.annotations.TestOnly import java.util.stream.Stream interface HtmlEmbeddedContentSupport { @JvmDefault fun isEnabled(lexer: BaseHtmlLexer): Boolean = true @JvmDefault fun createEmbeddedContentProviders(lexer: BaseHtmlLexer): List<HtmlEmbeddedContentProvider> = emptyList() companion object { internal val EP_NAME: ExtensionPointName<HtmlEmbeddedContentSupport> = ExtensionPointName.create( "com.intellij.html.embeddedContentSupport") fun getContentSupports(): @NotNull Stream<HtmlEmbeddedContentSupport> { return EP_NAME.extensions() } @JvmStatic fun getStyleTagEmbedmentInfo(language: Language): HtmlEmbedmentInfo? = if (LanguageUtil.isInjectableLanguage(language)) EmbeddedTokenTypesProvider.getProviders() .map { it.elementType } .filter { language.`is`(it.language) } .map { elementType -> HtmlLanguageEmbedmentInfo(elementType, language) } .firstOrNull() else null @JvmStatic fun getScriptTagEmbedmentInfo(language: Language): HtmlEmbedmentInfo? = if (LanguageUtil.isInjectableLanguage(language)) LanguageHtmlScriptContentProvider.getScriptContentProvider(language) ?.let { provider -> object: HtmlEmbedmentInfo { override fun getElementType(): IElementType? = provider.scriptElementType override fun createHighlightingLexer(): Lexer? = provider.highlightingLexer } } else null /** * Use this method to register support in ParsingTestCases only */ @TestOnly @JvmStatic fun register(application: Application, disposable: Disposable, vararg supports: Class<out HtmlEmbeddedContentSupport>) { val name = EP_NAME.name val extensionPoint = application.extensionArea.let { val point = it.getExtensionPointIfRegistered<HtmlEmbeddedContentSupport>(name) if (point == null) { it.registerDynamicExtensionPoint(name, HtmlEmbeddedContentSupport::class.java.name, ExtensionPoint.Kind.INTERFACE) it.getExtensionPoint(name) } else { point } } supports.asSequence().map { it.getDeclaredConstructor().newInstance() } .forEach { extensionPoint.registerExtension(it, disposable) } } } }
apache-2.0
af93f485a3e512d12667cf043c976565
37.580247
140
0.71991
4.88125
false
false
false
false
code-helix/slatekit
src/lib/kotlin/slatekit-tests/src/test/kotlin/test/setup/SampleEntityApi.kt
1
2553
package test.setup import slatekit.apis.Api import slatekit.apis.Action import slatekit.entities.EntityService import slatekit.integration.common.ApiBaseEntity import slatekit.connectors.entities.AppEntContext import slatekit.entities.features.Counts import slatekit.entities.features.Ordered /** * REST Sample * This example shows a REST compliant API. * The Slate Kit API Container comes with middle-ware. One of the * middle-ware components is the Rewrite which can convert 1 request * to another request. Using this Rewrite component, we can customize * and enforce conventions. * * * NOTES: * 1. REST : REST Support for methods with 0 or 1 parameters. * 2. Conventions : Create your own conventions using the Rewrite component * * HTTP: * Method Route * GET /SampleREST/ => getAll * GET /SampleREST/1 => getById ( 1 ) * POST /SampleREST/{item} => create ( item ) * PUT /SampleREST/{item} => update ( item ) * DELETE /SampleREST/{item} => delete ( item ) * DELETE /SampleREST/1 => deleteById( 1 ) * PATCH /SampleREST?id=1&title=abc => patch ( id, title ) * * * CLI: * SampleREST.getAll * SampleREST.getById -id=1 * SampleREST.create -title="abc" -category="action" * SampleREST.update -id=1 -title="abc" -category="action" * SampleREST.delete -id=1 -title="abc" -category="action" * SampleREST.deleteById -id=1 * SampleREST.patch -id=1 -title="abc" */ class SampleEntityApi(ctx: AppEntContext) : ApiBaseEntity<Long ,Movie, EntityService<Long, Movie>>(ctx, Long::class, Movie::class, ctx.ent.getService()) { fun patch(id:Long, title:String): String = "patched $id with $title" } @Api(area = "app", name = "tests", desc = "sample to test compositional apis with annotations", roles= ["admin"]) class SampleEntity2Api(ctx: AppEntContext){ private val svc = ctx.ent.getService<Long, Movie>() as Ordered<Long ,Movie> @Action(name = "", desc = "gets the total number of users") fun patch(id:Long, title:String): String = "patched $id with $title" @Action(name = "", desc = "gets recent items in the system") suspend fun recent(count: Int = 5): List<Movie> { return svc.recent(count) } @Action(name = "", desc = "gets oldest items in the system") suspend fun oldest(count: Int = 5): List<Movie> { return svc.oldest(count) } }
apache-2.0
450e6fbb218dc9d1977315261c143a83
37.104478
116
0.634156
3.683983
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/j2k/services/src/org/jetbrains/kotlin/nj2k/postProcessing/inspectionLikePostProcessings.kt
5
6986
// 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.nj2k.postProcessing import com.intellij.openapi.editor.RangeMarker import com.intellij.openapi.util.TextRange import com.intellij.psi.PsiElement import com.intellij.psi.PsiRecursiveElementVisitor import org.jetbrains.kotlin.idea.inspections.AbstractApplicabilityBasedInspection import org.jetbrains.kotlin.idea.intentions.SelfTargetingRangeIntention import org.jetbrains.kotlin.idea.util.application.runReadAction import org.jetbrains.kotlin.j2k.ConverterSettings import org.jetbrains.kotlin.nj2k.NewJ2kConverterContext import org.jetbrains.kotlin.psi.KtElement import org.jetbrains.kotlin.psi.KtFile import org.jetbrains.kotlin.utils.mapToIndex import java.util.* class InspectionLikeProcessingGroup( private val runSingleTime: Boolean = false, private val acceptNonKtElements: Boolean = false, private val processings: List<InspectionLikeProcessing> ) : FileBasedPostProcessing() { constructor(vararg processings: InspectionLikeProcessing) : this( runSingleTime = false, acceptNonKtElements = false, processings = processings.toList() ) private val processingsToPriorityMap = processings.mapToIndex() fun priority(processing: InspectionLikeProcessing): Int = processingsToPriorityMap.getValue(processing) override fun runProcessing(file: KtFile, allFiles: List<KtFile>, rangeMarker: RangeMarker?, converterContext: NewJ2kConverterContext) { do { var modificationStamp: Long? = file.modificationStamp val elementToActions = runReadAction { collectAvailableActions(file, converterContext, rangeMarker) } for ((processing, element, _) in elementToActions) { val needRun = runReadAction { element.isValid && processing.isApplicableToElement(element, converterContext.converter.settings) } if (needRun) runUndoTransparentActionInEdt(inWriteAction = processing.writeActionNeeded) { processing.applyToElement(element) } else { modificationStamp = null } } if (runSingleTime) break } while (modificationStamp != file.modificationStamp && elementToActions.isNotEmpty()) } private enum class RangeFilterResult { SKIP, GO_INSIDE, PROCESS } private data class ProcessingData( val processing: InspectionLikeProcessing, val element: PsiElement, val priority: Int ) private fun collectAvailableActions( file: KtFile, context: NewJ2kConverterContext, rangeMarker: RangeMarker? ): List<ProcessingData> { val availableActions = ArrayList<ProcessingData>() file.accept(object : PsiRecursiveElementVisitor() { override fun visitElement(element: PsiElement) { if (element is KtElement || acceptNonKtElements) { val rangeResult = rangeFilter(element, rangeMarker) if (rangeResult == RangeFilterResult.SKIP) return super.visitElement(element) if (rangeResult == RangeFilterResult.PROCESS) { for (processing in processings) { if (processing.isApplicableToElement(element, context.converter.settings)) { availableActions.add( ProcessingData(processing, element, priority(processing)) ) } } } } } }) availableActions.sortBy { it.priority } return availableActions } private fun rangeFilter(element: PsiElement, rangeMarker: RangeMarker?): RangeFilterResult { if (rangeMarker == null) return RangeFilterResult.PROCESS if (!rangeMarker.isValid) return RangeFilterResult.SKIP val range = TextRange(rangeMarker.startOffset, rangeMarker.endOffset) val elementRange = element.textRange return when { range.contains(elementRange) -> RangeFilterResult.PROCESS range.intersects(elementRange) -> RangeFilterResult.GO_INSIDE else -> RangeFilterResult.SKIP } } } abstract class InspectionLikeProcessing { abstract fun isApplicableToElement(element: PsiElement, settings: ConverterSettings?): Boolean abstract fun applyToElement(element: PsiElement) // Some post-processings may need to do some resolving operations when applying // Running it in outer write action may lead to UI freezes // So we let that post-processings to handle write actions by themselves open val writeActionNeeded = true val processingOptions: PostProcessingOptions = PostProcessingOptions.DEFAULT } abstract class InspectionLikeProcessingForElement<E : PsiElement>(private val classTag: Class<E>) : InspectionLikeProcessing() { protected abstract fun isApplicableTo(element: E, settings: ConverterSettings?): Boolean protected abstract fun apply(element: E) @Suppress("UNCHECKED_CAST") final override fun isApplicableToElement(element: PsiElement, settings: ConverterSettings?): Boolean { if (!classTag.isInstance(element)) return false if (!element.isValid) return false @Suppress("UNCHECKED_CAST") return isApplicableTo(element as E, settings) } final override fun applyToElement(element: PsiElement) { if (!classTag.isInstance(element)) return if (!element.isValid) return @Suppress("UNCHECKED_CAST") apply(element as E) } } inline fun <reified E : PsiElement, I : SelfTargetingRangeIntention<E>> intentionBasedProcessing( intention: I, writeActionNeeded: Boolean = true, noinline additionalChecker: (E) -> Boolean = { true } ) = object : InspectionLikeProcessingForElement<E>(E::class.java) { override fun isApplicableTo(element: E, settings: ConverterSettings?): Boolean = intention.applicabilityRange(element) != null && additionalChecker(element) override fun apply(element: E) { intention.applyTo(element, null) } override val writeActionNeeded = writeActionNeeded } inline fun <reified E : PsiElement, I : AbstractApplicabilityBasedInspection<E>> inspectionBasedProcessing( inspection: I, writeActionNeeded: Boolean = true ) = object : InspectionLikeProcessingForElement<E>(E::class.java) { override fun isApplicableTo(element: E, settings: ConverterSettings?): Boolean = inspection.isApplicable(element) override fun apply(element: E) { inspection.applyTo(element) } override val writeActionNeeded = writeActionNeeded }
apache-2.0
bc85a9601d310691befbf41ba5ed9223
39.616279
158
0.684655
5.398764
false
false
false
false
zielu/GitToolBox
src/main/kotlin/zielu/gittoolbox/ui/blame/BlameEditorData.kt
1
1025
package zielu.gittoolbox.ui.blame import com.intellij.openapi.util.Key import com.intellij.openapi.util.UserDataHolder import zielu.gittoolbox.revision.RevisionInfo internal data class BlameEditorData( val editorLineIndex: Int, val lineModified: Boolean, val generation: Int, val revisionInfo: RevisionInfo ) { fun isSameEditorLineIndex(editorLineIndex: Int): Boolean { return this.editorLineIndex == editorLineIndex } fun isSameGeneration(generation: Int): Boolean { return this.generation == generation } companion object { private val KEY = Key<BlameEditorData>("GitToolBox-blame-editor") @JvmStatic fun get(userDataHolder: UserDataHolder): BlameEditorData? { return userDataHolder.getUserData(KEY) } @JvmStatic fun set(userDataHolder: UserDataHolder, editorData: BlameEditorData) { userDataHolder.putUserData(KEY, editorData) } @JvmStatic fun clear(userDataHolder: UserDataHolder) { userDataHolder.putUserData(KEY, null) } } }
apache-2.0
148e5b4435518c0c149ba302782d34c5
24.625
74
0.742439
4.34322
false
false
false
false
ozbek/quran_android
app/src/main/java/com/quran/labs/androidquran/data/GlyphsBuilder.kt
2
2014
package com.quran.labs.androidquran.data import android.graphics.RectF import com.quran.data.model.AyahGlyph.AyahEndGlyph import com.quran.data.model.AyahGlyph.HizbGlyph import com.quran.data.model.AyahGlyph.PauseGlyph import com.quran.data.model.AyahGlyph.SajdahGlyph import com.quran.data.model.AyahGlyph.WordGlyph import com.quran.data.model.SuraAyah import com.quran.page.common.data.coordinates.GlyphCoords /** * Helper to convert the ordered glyph rows in the database to structured [GlyphCoords] classes. * * Usage: add glyphs to the builder in sequence so that word positions can be calculated correctly. * * Note: It is important that the glyphs are appended in sequence with no gaps, * otherwise the `wordPosition` for [WordGlyph] may be incorrect. */ class GlyphsBuilder { private val glyphs = mutableListOf<GlyphCoords>() private var curAyah: SuraAyah? = null private var nextWordPos: Int = 1 fun append(sura: Int, ayah: Int, glyphPosition: Int, line: Int, type: String, bounds: RectF) { val suraAyah = SuraAyah(sura, ayah) // If we're on a different ayah, reset word position to 1 if (curAyah == null || curAyah != suraAyah) { curAyah = suraAyah nextWordPos = 1 } val glyph = when (type) { HIZB -> HizbGlyph(suraAyah, glyphPosition) SAJDAH -> SajdahGlyph(suraAyah, glyphPosition) PAUSE -> PauseGlyph(suraAyah, glyphPosition) END -> AyahEndGlyph(suraAyah, glyphPosition) WORD -> WordGlyph(suraAyah, glyphPosition, nextWordPos++) else -> throw IllegalArgumentException("Unknown glyph type $type") } glyphs.add(GlyphCoords(glyph, line, bounds)) } fun build(): List<GlyphCoords> = glyphs.toList() // Glyph Type keys // Note: it's important these types match what is defined in the ayahinfo db private companion object { const val HIZB = "hizb" const val SAJDAH = "sajdah" const val PAUSE = "pause" const val END = "end" const val WORD = "word" } }
gpl-3.0
d74b5464d912439c5f1e3c01ae5ba61d
33.724138
99
0.709533
3.668488
false
false
false
false
MilosKozak/AndroidAPS
app/src/main/java/info/nightscout/androidaps/plugins/general/automation/AutomationPlugin.kt
3
9205
package info.nightscout.androidaps.plugins.general.automation import android.content.Intent import android.os.Build import android.os.Handler import info.nightscout.androidaps.MainApp import info.nightscout.androidaps.R import info.nightscout.androidaps.events.EventChargingState import info.nightscout.androidaps.events.EventLocationChange import info.nightscout.androidaps.events.EventNetworkChange import info.nightscout.androidaps.events.EventPreferenceChange import info.nightscout.androidaps.interfaces.PluginBase import info.nightscout.androidaps.interfaces.PluginDescription import info.nightscout.androidaps.interfaces.PluginType import info.nightscout.androidaps.logging.L import info.nightscout.androidaps.plugins.aps.loop.LoopPlugin import info.nightscout.androidaps.plugins.bus.RxBus import info.nightscout.androidaps.plugins.general.automation.actions.* import info.nightscout.androidaps.plugins.general.automation.events.EventAutomationDataChanged import info.nightscout.androidaps.plugins.general.automation.events.EventAutomationUpdateGui import info.nightscout.androidaps.plugins.general.automation.triggers.* import info.nightscout.androidaps.plugins.iob.iobCobCalculator.events.EventAutosensCalculationFinished import info.nightscout.androidaps.queue.Callback import info.nightscout.androidaps.services.LocationService import info.nightscout.androidaps.utils.* import io.reactivex.disposables.CompositeDisposable import io.reactivex.schedulers.Schedulers import org.json.JSONArray import org.json.JSONException import org.json.JSONObject import org.slf4j.LoggerFactory import java.util.* object AutomationPlugin : PluginBase(PluginDescription() .mainType(PluginType.GENERAL) .fragmentClass(AutomationFragment::class.qualifiedName) .pluginName(R.string.automation) .shortName(R.string.automation_short) .preferencesId(R.xml.pref_automation) .description(R.string.automation_description)) { private val log = LoggerFactory.getLogger(L.AUTOMATION) private var disposable: CompositeDisposable = CompositeDisposable() private const val key_AUTOMATION_EVENTS = "AUTOMATION_EVENTS" val automationEvents = ArrayList<AutomationEvent>() var executionLog: MutableList<String> = ArrayList() private val loopHandler = Handler() private lateinit var refreshLoop: Runnable init { refreshLoop = Runnable { processActions() loopHandler.postDelayed(refreshLoop, T.mins(1).msecs()) } } override fun onStart() { val context = MainApp.instance().applicationContext if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) context.startForegroundService(Intent(context, LocationService::class.java)) else context.startService(Intent(context, LocationService::class.java)) super.onStart() loadFromSP() loopHandler.postDelayed(refreshLoop, T.mins(1).msecs()) disposable += RxBus .toObservable(EventPreferenceChange::class.java) .observeOn(Schedulers.io()) .subscribe({ e -> if (e.isChanged(R.string.key_location)) { context.stopService(Intent(context, LocationService::class.java)) if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) context.startForegroundService(Intent(context, LocationService::class.java)) else context.startService(Intent(context, LocationService::class.java)) } }, { FabricPrivacy.logException(it) }) disposable += RxBus .toObservable(EventAutomationDataChanged::class.java) .observeOn(Schedulers.io()) .subscribe({ storeToSP() }, { FabricPrivacy.logException(it) }) disposable += RxBus .toObservable(EventLocationChange::class.java) .observeOn(Schedulers.io()) .subscribe({ e -> e?.let { log.debug("Grabbed location: $it.location.latitude $it.location.longitude Provider: $it.location.provider") processActions() } }, { FabricPrivacy.logException(it) }) disposable += RxBus .toObservable(EventChargingState::class.java) .observeOn(Schedulers.io()) .subscribe({ processActions() }, { FabricPrivacy.logException(it) }) disposable += RxBus .toObservable(EventNetworkChange::class.java) .observeOn(Schedulers.io()) .subscribe({ processActions() }, { FabricPrivacy.logException(it) }) disposable += RxBus .toObservable(EventAutosensCalculationFinished::class.java) .observeOn(Schedulers.io()) .subscribe({ processActions() }, { FabricPrivacy.logException(it) }) } override fun onStop() { disposable.clear() loopHandler.removeCallbacks(refreshLoop) val context = MainApp.instance().applicationContext context.stopService(Intent(context, LocationService::class.java)) super.onStop() } private fun storeToSP() { val array = JSONArray() try { for (event in automationEvents) { array.put(JSONObject(event.toJSON())) } } catch (e: JSONException) { e.printStackTrace() } SP.putString(key_AUTOMATION_EVENTS, array.toString()) } private fun loadFromSP() { automationEvents.clear() val data = SP.getString(key_AUTOMATION_EVENTS, "") if (data != "") { try { val array = JSONArray(data) for (i in 0 until array.length()) { val o = array.getJSONObject(i) val event = AutomationEvent().fromJSON(o.toString()) automationEvents.add(event) } } catch (e: JSONException) { e.printStackTrace() } } } @Synchronized private fun processActions() { if (!isEnabled(PluginType.GENERAL)) return if (LoopPlugin.getPlugin().isSuspended || !LoopPlugin.getPlugin().isEnabled(PluginType.LOOP)) { if (L.isEnabled(L.AUTOMATION)) log.debug("Loop deactivated") return } if (L.isEnabled(L.AUTOMATION)) log.debug("processActions") for (event in automationEvents) { if (event.isEnabled && event.trigger.shouldRun() && event.preconditions.shouldRun()) { val actions = event.actions for (action in actions) { action.doAction(object : Callback() { override fun run() { val sb = StringBuilder() sb.append(DateUtil.timeString(DateUtil.now())) sb.append(" ") sb.append(if (result.success) "☺" else "▼") sb.append(" <b>") sb.append(event.title) sb.append(":</b> ") sb.append(action.shortDescription()) sb.append(": ") sb.append(result.comment) executionLog.add(sb.toString()) if (L.isEnabled(L.AUTOMATION)) log.debug("Executed: $sb") RxBus.send(EventAutomationUpdateGui()) } }) } event.trigger.executed(DateUtil.now()) } } storeToSP() // save last run time } fun getActionDummyObjects(): List<Action> { return listOf( //ActionLoopDisable(), //ActionLoopEnable(), //ActionLoopResume(), //ActionLoopSuspend(), ActionStartTempTarget(), ActionStopTempTarget(), ActionNotification(), ActionProfileSwitchPercent(), ActionProfileSwitch(), ActionSendSMS() ) } fun getTriggerDummyObjects(): List<Trigger> { return listOf( TriggerTime(), TriggerRecurringTime(), TriggerTimeRange(), TriggerBg(), TriggerDelta(), TriggerIob(), TriggerCOB(), TriggerProfilePercent(), TriggerTempTarget(), TriggerWifiSsid(), TriggerLocation(), TriggerAutosensValue(), TriggerBolusAgo(), TriggerPumpLastConnection() ) } }
agpl-3.0
34c25e566b9110fa9a531514fa1f6e8f
38.153191
131
0.575046
5.340104
false
false
false
false
tensorflow/examples
lite/examples/posenet/android/posenet/src/main/java/org/tensorflow/lite/examples/posenet/lib/Posenet.kt
1
8664
/* * Copyright 2019 The TensorFlow Authors. All Rights Reserved. * * 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.tensorflow.lite.examples.posenet.lib import android.content.Context import android.graphics.Bitmap import android.os.SystemClock import android.util.Log import java.io.FileInputStream import java.nio.ByteBuffer import java.nio.ByteOrder import java.nio.MappedByteBuffer import java.nio.channels.FileChannel import kotlin.math.exp import org.tensorflow.lite.Interpreter import org.tensorflow.lite.gpu.GpuDelegate enum class BodyPart { NOSE, LEFT_EYE, RIGHT_EYE, LEFT_EAR, RIGHT_EAR, LEFT_SHOULDER, RIGHT_SHOULDER, LEFT_ELBOW, RIGHT_ELBOW, LEFT_WRIST, RIGHT_WRIST, LEFT_HIP, RIGHT_HIP, LEFT_KNEE, RIGHT_KNEE, LEFT_ANKLE, RIGHT_ANKLE } class Position { var x: Int = 0 var y: Int = 0 } class KeyPoint { var bodyPart: BodyPart = BodyPart.NOSE var position: Position = Position() var score: Float = 0.0f } class Person { var keyPoints = listOf<KeyPoint>() var score: Float = 0.0f } enum class Device { CPU, NNAPI, GPU } class Posenet( val context: Context, val filename: String = "posenet_model.tflite", val device: Device = Device.CPU ) : AutoCloseable { var lastInferenceTimeNanos: Long = -1 private set /** An Interpreter for the TFLite model. */ private var interpreter: Interpreter? = null private var gpuDelegate: GpuDelegate? = null private val NUM_LITE_THREADS = 4 private fun getInterpreter(): Interpreter { if (interpreter != null) { return interpreter!! } val options = Interpreter.Options() options.setNumThreads(NUM_LITE_THREADS) when (device) { Device.CPU -> { } Device.GPU -> { gpuDelegate = GpuDelegate() options.addDelegate(gpuDelegate) } Device.NNAPI -> options.setUseNNAPI(true) } interpreter = Interpreter(loadModelFile(filename, context), options) return interpreter!! } override fun close() { interpreter?.close() interpreter = null gpuDelegate?.close() gpuDelegate = null } /** Returns value within [0,1]. */ private fun sigmoid(x: Float): Float { return (1.0f / (1.0f + exp(-x))) } /** * Scale the image to a byteBuffer of [-1,1] values. */ private fun initInputArray(bitmap: Bitmap): ByteBuffer { val bytesPerChannel = 4 val inputChannels = 3 val batchSize = 1 val inputBuffer = ByteBuffer.allocateDirect( batchSize * bytesPerChannel * bitmap.height * bitmap.width * inputChannels ) inputBuffer.order(ByteOrder.nativeOrder()) inputBuffer.rewind() val mean = 128.0f val std = 128.0f val intValues = IntArray(bitmap.width * bitmap.height) bitmap.getPixels(intValues, 0, bitmap.width, 0, 0, bitmap.width, bitmap.height) for (pixelValue in intValues) { inputBuffer.putFloat(((pixelValue shr 16 and 0xFF) - mean) / std) inputBuffer.putFloat(((pixelValue shr 8 and 0xFF) - mean) / std) inputBuffer.putFloat(((pixelValue and 0xFF) - mean) / std) } return inputBuffer } /** Preload and memory map the model file, returning a MappedByteBuffer containing the model. */ private fun loadModelFile(path: String, context: Context): MappedByteBuffer { val fileDescriptor = context.assets.openFd(path) val inputStream = FileInputStream(fileDescriptor.fileDescriptor) return inputStream.channel.map( FileChannel.MapMode.READ_ONLY, fileDescriptor.startOffset, fileDescriptor.declaredLength ) } /** * Initializes an outputMap of 1 * x * y * z FloatArrays for the model processing to populate. */ private fun initOutputMap(interpreter: Interpreter): HashMap<Int, Any> { val outputMap = HashMap<Int, Any>() // 1 * 9 * 9 * 17 contains heatmaps val heatmapsShape = interpreter.getOutputTensor(0).shape() outputMap[0] = Array(heatmapsShape[0]) { Array(heatmapsShape[1]) { Array(heatmapsShape[2]) { FloatArray(heatmapsShape[3]) } } } // 1 * 9 * 9 * 34 contains offsets val offsetsShape = interpreter.getOutputTensor(1).shape() outputMap[1] = Array(offsetsShape[0]) { Array(offsetsShape[1]) { Array(offsetsShape[2]) { FloatArray(offsetsShape[3]) } } } // 1 * 9 * 9 * 32 contains forward displacements val displacementsFwdShape = interpreter.getOutputTensor(2).shape() outputMap[2] = Array(offsetsShape[0]) { Array(displacementsFwdShape[1]) { Array(displacementsFwdShape[2]) { FloatArray(displacementsFwdShape[3]) } } } // 1 * 9 * 9 * 32 contains backward displacements val displacementsBwdShape = interpreter.getOutputTensor(3).shape() outputMap[3] = Array(displacementsBwdShape[0]) { Array(displacementsBwdShape[1]) { Array(displacementsBwdShape[2]) { FloatArray(displacementsBwdShape[3]) } } } return outputMap } /** * Estimates the pose for a single person. * args: * bitmap: image bitmap of frame that should be processed * returns: * person: a Person object containing data about keypoint locations and confidence scores */ @Suppress("UNCHECKED_CAST") fun estimateSinglePose(bitmap: Bitmap): Person { val estimationStartTimeNanos = SystemClock.elapsedRealtimeNanos() val inputArray = arrayOf(initInputArray(bitmap)) Log.i( "posenet", String.format( "Scaling to [-1,1] took %.2f ms", 1.0f * (SystemClock.elapsedRealtimeNanos() - estimationStartTimeNanos) / 1_000_000 ) ) val outputMap = initOutputMap(getInterpreter()) val inferenceStartTimeNanos = SystemClock.elapsedRealtimeNanos() getInterpreter().runForMultipleInputsOutputs(inputArray, outputMap) lastInferenceTimeNanos = SystemClock.elapsedRealtimeNanos() - inferenceStartTimeNanos Log.i( "posenet", String.format("Interpreter took %.2f ms", 1.0f * lastInferenceTimeNanos / 1_000_000) ) val heatmaps = outputMap[0] as Array<Array<Array<FloatArray>>> val offsets = outputMap[1] as Array<Array<Array<FloatArray>>> val height = heatmaps[0].size val width = heatmaps[0][0].size val numKeypoints = heatmaps[0][0][0].size // Finds the (row, col) locations of where the keypoints are most likely to be. val keypointPositions = Array(numKeypoints) { Pair(0, 0) } for (keypoint in 0 until numKeypoints) { var maxVal = heatmaps[0][0][0][keypoint] var maxRow = 0 var maxCol = 0 for (row in 0 until height) { for (col in 0 until width) { if (heatmaps[0][row][col][keypoint] > maxVal) { maxVal = heatmaps[0][row][col][keypoint] maxRow = row maxCol = col } } } keypointPositions[keypoint] = Pair(maxRow, maxCol) } // Calculating the x and y coordinates of the keypoints with offset adjustment. val xCoords = IntArray(numKeypoints) val yCoords = IntArray(numKeypoints) val confidenceScores = FloatArray(numKeypoints) keypointPositions.forEachIndexed { idx, position -> val positionY = keypointPositions[idx].first val positionX = keypointPositions[idx].second yCoords[idx] = ( position.first / (height - 1).toFloat() * bitmap.height + offsets[0][positionY][positionX][idx] ).toInt() xCoords[idx] = ( position.second / (width - 1).toFloat() * bitmap.width + offsets[0][positionY] [positionX][idx + numKeypoints] ).toInt() confidenceScores[idx] = sigmoid(heatmaps[0][positionY][positionX][idx]) } val person = Person() val keypointList = Array(numKeypoints) { KeyPoint() } var totalScore = 0.0f enumValues<BodyPart>().forEachIndexed { idx, it -> keypointList[idx].bodyPart = it keypointList[idx].position.x = xCoords[idx] keypointList[idx].position.y = yCoords[idx] keypointList[idx].score = confidenceScores[idx] totalScore += confidenceScores[idx] } person.keyPoints = keypointList.toList() person.score = totalScore / numKeypoints return person } }
apache-2.0
f0cc63583f3b212ef5d9161f1282714a
30.165468
98
0.674977
3.81338
false
false
false
false
QuixomTech/DeviceInfo
app/src/main/java/com/quixom/apps/deviceinfo/fragments/SimFragment.kt
1
12677
package com.quixom.apps.deviceinfo.fragments import android.Manifest import android.annotation.SuppressLint import android.annotation.TargetApi import android.content.Context import android.content.pm.PackageManager import android.os.Build import android.os.Bundle import android.support.annotation.RequiresApi import android.support.v4.app.ActivityCompat import android.support.v7.widget.LinearLayoutManager import android.telephony.SubscriptionManager import android.telephony.TelephonyManager import android.telephony.gsm.GsmCellLocation import android.view.* import android.widget.Toast import com.quixom.apps.deviceinfo.MainActivity import com.quixom.apps.deviceinfo.R import com.quixom.apps.deviceinfo.adapters.SimAdapter import com.quixom.apps.deviceinfo.models.SimInfo import com.quixom.apps.deviceinfo.utilities.KeyUtil import kotlinx.android.synthetic.main.fragment_sim.* import kotlinx.android.synthetic.main.toolbar_ui.* /** * A simple [SimFragment] subclass. */ class SimFragment : BaseFragment() { private var telephonyManager: TelephonyManager? = null private var simInfoDataList: ArrayList<SimInfo>? = ArrayList<SimInfo>() /* override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? = inflater.inflate(R.layout.fragment_sim, container, false)*/ override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { val contextThemeWrapper = ContextThemeWrapper(activity, R.style.SimTheme) val localInflater = inflater.cloneInContext(contextThemeWrapper) val view = localInflater.inflate(R.layout.fragment_sim, container, false) if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { val window = activity!!.window window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS) window.statusBarColor = resources.getColor(R.color.dark_parrot_green) window.navigationBarColor = resources.getColor(R.color.dark_parrot_green) } return view } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) telephonyManager = mActivity.getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager? rvSimData?.layoutManager = LinearLayoutManager(mActivity) rvSimData?.hasFixedSize() initToolbar() } @RequiresApi(Build.VERSION_CODES.M) override fun onActivityCreated(savedInstanceState: Bundle?) { super.onActivityCreated(savedInstanceState) checkCameraPermission() } override fun onHiddenChanged(hidden: Boolean) { super.onHiddenChanged(hidden) if (!hidden && isAdded) { initToolbar() } } @RequiresApi(Build.VERSION_CODES.M) @TargetApi(Build.VERSION_CODES.LOLLIPOP) /** * this method will show permission pop up messages to user. */ private fun checkCameraPermission() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { val hasWriteCameraPermission = mActivity.checkSelfPermission(Manifest.permission.READ_PHONE_STATE) if (hasWriteCameraPermission != PackageManager.PERMISSION_GRANTED) { requestPermissions(arrayOf(Manifest.permission.READ_PHONE_STATE), KeyUtil.KEY_READ_PHONE_STATE) } else { retrieveSimInformation(telephonyManager!!) } } else { retrieveSimInformation(telephonyManager!!) } } override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) { super.onRequestPermissionsResult(requestCode, permissions, grantResults) when (requestCode) { KeyUtil.KEY_READ_PHONE_STATE -> if (permissions.isNotEmpty()) { if (grantResults[0] == PackageManager.PERMISSION_GRANTED) { retrieveSimInformation(telephonyManager!!) } else if (grantResults[0] == PackageManager.PERMISSION_DENIED) { if (ActivityCompat.shouldShowRequestPermissionRationale(mActivity, Manifest.permission.GET_ACCOUNTS)) { Toast.makeText(mActivity, "Need to grant account Permission", Toast.LENGTH_LONG).show() } } } else -> super.onRequestPermissionsResult(requestCode, permissions, grantResults) } } @TargetApi(Build.VERSION_CODES.O) @SuppressLint("MissingPermission", "HardwareIds") private fun retrieveSimInformation(telephonyManager: TelephonyManager) { if (telephonyManager != null && isSimAvailable(mActivity, 0) && telephonyManager.simState == TelephonyManager.SIM_STATE_READY) { cvSimDataParent.visibility = View.VISIBLE if (llEmptyState.isShown) { llEmptyState.visibility = View.GONE } simInfoDataList?.add(SimInfo("SIM 1 state", simState(telephonyManager.simState))) simInfoDataList?.add(SimInfo("Integrated circuit card identifier (ICCID)", telephonyManager.simSerialNumber!!)) simInfoDataList?.add(SimInfo("Unique device ID (IMEI or MEID/ESN for CDMA)", telephonyManager.getImei(0))) simInfoDataList?.add(SimInfo("International mobile subscriber identity (IMSI)", telephonyManager.subscriberId)) simInfoDataList?.add(SimInfo("Service provider name (SPN)", telephonyManager.simOperatorName)) simInfoDataList?.add(SimInfo("Mobile country code (MCC)", telephonyManager.networkCountryIso)) simInfoDataList?.add(SimInfo("Mobile operator name", telephonyManager.networkOperatorName)) simInfoDataList?.add(SimInfo("Network type", networkType(telephonyManager.networkType))) simInfoDataList?.add(SimInfo("Mobile country code + mobile network code (MCC+MNC)", telephonyManager.simOperator)) simInfoDataList?.add(SimInfo("Mobile station international subscriber directory number (MSISDN)", telephonyManager.line1Number)) /* if (isSimAvailable(mActivity, 1)) { simInfoDataList?.add(SimInfo("", "")) simInfoDataList?.add(SimInfo("SIM 2 state", simState(getDeviceIdBySlot(mActivity, "getSimState", 1).toInt()))) simInfoDataList?.add(SimInfo("Unique device ID (IMEI or MEID/ESN for CDMA)", telephonyManager.getImei(1))) simInfoDataList?.add(SimInfo("Integrated circuit card identifier (ICCID)", getDeviceIdBySlot(mActivity, "getSimSerialNumber", 1))) simInfoDataList?.add(SimInfo("International mobile subscriber identity (IMSI)", ""+getDeviceIdBySlot(mActivity, "getSubscriberId", 1))) simInfoDataList?.add(SimInfo("Service provider name (SPN)", getDeviceIdBySlot(mActivity, "getSimOperatorName", 1))) simInfoDataList?.add(SimInfo("Mobile country code (MCC)", getDeviceIdBySlot(mActivity, "getNetworkCountryIso", 1))) simInfoDataList?.add(SimInfo("Mobile operator name", ""+getDeviceIdBySlot(mActivity, "getNetworkOperatorName", 1))) simInfoDataList?.add(SimInfo("Network type", networkType(getDeviceIdBySlot(mActivity, "getNetworkType", 1).toInt()))) simInfoDataList?.add(SimInfo("Mobile country code + mobile network code (MCC+MNC)", ""+getDeviceIdBySlot(mActivity, "getSimOperator", 1))) simInfoDataList?.add(SimInfo("Mobile station international subscriber directory number (MSISDN)", ""+getDeviceIdBySlot(mActivity, "getLine1Number", 1))) }*/ //creating our adapter val adapter = simInfoDataList?.let { SimAdapter(mActivity, it) } rvSimData?.adapter = adapter } else { cvSimDataParent.visibility = View.GONE llEmptyState.visibility = View.VISIBLE } } private fun initToolbar() { mActivity.iv_menu?.visibility = View.VISIBLE mActivity.iv_back?.visibility = View.GONE mActivity.tv_title?.text = mResources.getString(R.string.sim) mActivity.iv_menu?.setOnClickListener { mActivity.openDrawer() } } @Throws(DIMethodNotFoundException::class) private fun getDeviceIdBySlot(context: MainActivity, predictedMethodName: String, slotID: Int): String { var imei: String? = null val telephony = context.getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager try { val telephonyClass = Class.forName(telephony.javaClass.name) val parameter = arrayOfNulls<Class<*>>(1) parameter[0] = Int::class.javaPrimitiveType val getSimID = telephonyClass.getMethod(predictedMethodName, *parameter) val obParameter = arrayOfNulls<Any>(1) obParameter[0] = slotID val ob_phone = getSimID.invoke(telephony, *obParameter) return ob_phone?.toString() ?: "No record" } catch (e: Exception) { e.printStackTrace() throw DIMethodNotFoundException(predictedMethodName) } } @Throws(DIMethodNotFoundException::class) private fun getCellLocBySlot(context: Context, predictedMethodName: String, slotID: Int): GsmCellLocation? { var cloc: GsmCellLocation? = null val telephony = context.getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager try { val telephonyClass = Class.forName(telephony.javaClass.name) val parameter = arrayOfNulls<Class<*>>(1) parameter[0] = Int::class.javaPrimitiveType val getSimID = telephonyClass.getMethod(predictedMethodName, *parameter) val obParameter = arrayOfNulls<Any>(1) obParameter[0] = slotID val obPhone = getSimID.invoke(telephony, *obParameter) if (obPhone != null) { cloc = obPhone as GsmCellLocation } } catch (e: Exception) { e.printStackTrace() throw DIMethodNotFoundException(predictedMethodName) } return cloc } private fun simState(simState: Int): String { return when (simState) { 0 -> "UNKNOWN" 1 -> "ABSENT" 2 -> "REQUIRED" 3 -> "PUK_REQUIRED" 4 -> "NETWORK_LOCKED" 5 -> "READY" 6 -> "NOT_READY" 7 -> "PERM_DISABLED" 8 -> "CARD_IO_ERROR" else -> "??? " + simState } } private fun networkType(simState: Int): String { return when (simState) { TelephonyManager.NETWORK_TYPE_GPRS -> "GPRS" TelephonyManager.NETWORK_TYPE_EDGE -> "EDGE" TelephonyManager.NETWORK_TYPE_CDMA -> "CDMA" TelephonyManager.NETWORK_TYPE_1xRTT -> "1xRTT" TelephonyManager.NETWORK_TYPE_IDEN -> "IDEN" TelephonyManager.NETWORK_TYPE_UMTS -> "UMTS" TelephonyManager.NETWORK_TYPE_EVDO_0 -> "EVDO 0" TelephonyManager.NETWORK_TYPE_EVDO_A -> "EVDO A" TelephonyManager.NETWORK_TYPE_HSDPA -> "HSDPA" TelephonyManager.NETWORK_TYPE_HSUPA -> "HSUPA" TelephonyManager.NETWORK_TYPE_HSPA -> "HSPA" TelephonyManager.NETWORK_TYPE_EVDO_B -> "EVDO B" TelephonyManager.NETWORK_TYPE_EHRPD -> "EHRPD" TelephonyManager.NETWORK_TYPE_HSPAP -> "HSPAP" TelephonyManager.NETWORK_TYPE_LTE -> "LTE" else -> "Unknown" } } private class DIMethodNotFoundException(info: String) : Exception(info) { companion object { private val serialVersionUID = -996812356902545308L } } @SuppressLint("MissingPermission", "HardwareIds") @RequiresApi(Build.VERSION_CODES.LOLLIPOP_MR1) private fun isSimAvailable(context: MainActivity, slotId: Int): Boolean { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1) { val sManager = context.getSystemService(Context.TELEPHONY_SUBSCRIPTION_SERVICE) as SubscriptionManager val infoSim = sManager.getActiveSubscriptionInfoForSimSlotIndex(slotId) if (infoSim != null) { return true } } else { val telephonyManager = context.getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager if (telephonyManager.simSerialNumber != null) { return true } } return false } }
apache-2.0
79a926770188d48766785869c66714bc
44.437276
176
0.659856
4.696925
false
false
false
false
SimpleMobileTools/Simple-Music-Player
app/src/main/kotlin/com/simplemobiletools/musicplayer/models/Artist.kt
1
1917
package com.simplemobiletools.musicplayer.models import android.provider.MediaStore import androidx.room.ColumnInfo import androidx.room.Entity import androidx.room.Index import androidx.room.PrimaryKey import com.simplemobiletools.commons.helpers.AlphanumericComparator import com.simplemobiletools.commons.helpers.SORT_DESCENDING import com.simplemobiletools.musicplayer.helpers.PLAYER_SORT_BY_ALBUM_COUNT import com.simplemobiletools.musicplayer.helpers.PLAYER_SORT_BY_TITLE @Entity(tableName = "artists", indices = [(Index(value = ["id"], unique = true))]) data class Artist( @PrimaryKey(autoGenerate = true) val id: Long, @ColumnInfo(name = "title") val title: String, @ColumnInfo(name = "album_cnt") var albumCnt: Int, @ColumnInfo(name = "track_cnt") var trackCnt: Int, @ColumnInfo(name = "album_art_id") var albumArtId: Long) : Comparable<Artist> { companion object { var sorting = 0 } override fun compareTo(other: Artist): Int { var result = when { sorting and PLAYER_SORT_BY_TITLE != 0 -> { when { title == MediaStore.UNKNOWN_STRING && other.title != MediaStore.UNKNOWN_STRING -> 1 title != MediaStore.UNKNOWN_STRING && other.title == MediaStore.UNKNOWN_STRING -> -1 else -> AlphanumericComparator().compare(title.toLowerCase(), other.title.toLowerCase()) } } sorting and PLAYER_SORT_BY_ALBUM_COUNT != 0 -> albumCnt.compareTo(other.albumCnt) else -> trackCnt.compareTo(other.trackCnt) } if (sorting and SORT_DESCENDING != 0) { result *= -1 } return result } fun getBubbleText() = when { sorting and PLAYER_SORT_BY_TITLE != 0 -> title sorting and PLAYER_SORT_BY_ALBUM_COUNT != 0 -> albumCnt.toString() else -> trackCnt.toString() } }
gpl-3.0
b967f4df93115db80a59108947799efc
38.122449
108
0.651017
4.279018
false
false
false
false
siosio/intellij-community
plugins/kotlin/idea/tests/testData/multiplatform/qualifiedReceiver/jvm/platform.kt
3
618
@file:Suppress("ACTUAL_WITHOUT_EXPECT") package foo actual interface <!LINE_MARKER("descr='Has declaration in common module'")!>A<!> { actual fun <!LINE_MARKER("descr='Has declaration in common module'")!>commonFun<!>() actual val <!LINE_MARKER("descr='Has declaration in common module'")!>b<!>: B actual fun <!LINE_MARKER("descr='Has declaration in common module'")!>bFun<!>(): B fun platformFun() } actual interface <!LINE_MARKER("descr='Has declaration in common module'")!>B<!> { actual fun <!LINE_MARKER("descr='Has declaration in common module'")!>commonFunB<!>() fun platformFunB() }
apache-2.0
9eed37660da142dda44eb68c43b2b001
40.2
89
0.682848
4.291667
false
false
false
false
siosio/intellij-community
plugins/kotlin/compiler-plugins/sam-with-receiver/common/src/org/jetbrains/kotlin/idea/compilerPlugin/samWithReceiver/IdeSamWithReceiverComponentContributor.kt
1
3183
// 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. // 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.compilerPlugin.samWithReceiver import com.intellij.openapi.module.Module import com.intellij.openapi.project.Project import com.intellij.openapi.roots.ProjectRootModificationTracker import com.intellij.psi.util.CachedValueProvider.Result import com.intellij.psi.util.CachedValuesManager import com.intellij.util.containers.ContainerUtil import org.jetbrains.kotlin.analyzer.ModuleInfo import org.jetbrains.kotlin.idea.compilerPlugin.getSpecialAnnotations import org.jetbrains.kotlin.container.StorageComponentContainer import org.jetbrains.kotlin.container.useInstance import org.jetbrains.kotlin.descriptors.ModuleDescriptor import org.jetbrains.kotlin.extensions.StorageComponentContainerContributor import org.jetbrains.kotlin.idea.caches.project.ModuleProductionSourceInfo import org.jetbrains.kotlin.idea.caches.project.ScriptDependenciesInfo import org.jetbrains.kotlin.idea.caches.project.ScriptModuleInfo import org.jetbrains.kotlin.platform.TargetPlatform import org.jetbrains.kotlin.platform.jvm.isJvm import org.jetbrains.kotlin.samWithReceiver.SamWithReceiverCommandLineProcessor.Companion.ANNOTATION_OPTION import org.jetbrains.kotlin.samWithReceiver.SamWithReceiverCommandLineProcessor.Companion.PLUGIN_ID import org.jetbrains.kotlin.samWithReceiver.SamWithReceiverResolverExtension class IdeSamWithReceiverComponentContributor(val project: Project) : StorageComponentContainerContributor { private companion object { val ANNOTATION_OPTION_PREFIX = "plugin:$PLUGIN_ID:${ANNOTATION_OPTION.optionName}=" } private val cache = CachedValuesManager.getManager(project).createCachedValue({ Result.create( ContainerUtil.createConcurrentWeakMap<Module, List<String>>(), ProjectRootModificationTracker.getInstance( project ) ) }, /* trackValue = */ false) private fun getAnnotationsForModule(module: Module): List<String> { return cache.value.getOrPut(module) { module.getSpecialAnnotations(ANNOTATION_OPTION_PREFIX) } } override fun registerModuleComponents( container: StorageComponentContainer, platform: TargetPlatform, moduleDescriptor: ModuleDescriptor ) { if (!platform.isJvm()) return val moduleInfo = moduleDescriptor.getCapability(ModuleInfo.Capability) val annotations = when (moduleInfo) { is ScriptModuleInfo -> moduleInfo.scriptDefinition.annotationsForSamWithReceivers is ScriptDependenciesInfo.ForFile -> moduleInfo.scriptDefinition.annotationsForSamWithReceivers is ModuleProductionSourceInfo -> getAnnotationsForModule(moduleInfo.module) else -> null } ?: return container.useInstance(SamWithReceiverResolverExtension(annotations)) } }
apache-2.0
2f738077d54449465a1fdf078dd8d907
48.75
158
0.781024
5.34958
false
false
false
false
HenningLanghorst/fancy-kotlin-stuff
src/main/kotlin/de/henninglanghorst/kotlinstuff/ui/Example.kt
1
663
package de.henninglanghorst.kotlinstuff.ui import javafx.application.Application import java.math.BigDecimal import java.math.BigInteger import java.time.LocalDate fun main(args: Array<String>) { Application.launch(PersonUI::class.java, *args) } class PersonUI : DataClassUI(Person::class, DefaultFieldDefinitions) data class Person( val firstName: String = "", val lastName: String = "", val birthName: String? = null, val birthday: LocalDate? = null, val someInt: Int? = null, val someLong: Long? = null, val someBigInteger: BigInteger? = null, val someBigDecimal: BigDecimal? = null )
apache-2.0
519aa755ebe87d1a17793095e6b275fc
24.5
68
0.686275
3.923077
false
false
false
false
JetBrains/kotlin-native
Interop/StubGenerator/src/main/kotlin/org/jetbrains/kotlin/native/interop/gen/TypeUtils.kt
2
3424
/* * Copyright 2010-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.kotlin.native.interop.gen import org.jetbrains.kotlin.native.interop.indexer.* val EnumDef.isAnonymous: Boolean get() = spelling.contains("(anonymous ") // TODO: it is a hack val StructDecl.isAnonymous: Boolean get() = spelling.contains("(anonymous ") // TODO: it is a hack /** * Returns the expression which could be used for this type in C code. * Note: the resulting string doesn't exactly represent this type, but it is enough for current purposes. * * TODO: use libclang to implement? */ fun Type.getStringRepresentation(): String = when (this) { VoidType -> "void" CharType -> "char" CBoolType -> "_Bool" ObjCBoolType -> "BOOL" is IntegerType -> this.spelling is FloatingType -> this.spelling is VectorType -> this.spelling is PointerType -> getPointerTypeStringRepresentation(this.pointeeType) is ArrayType -> getPointerTypeStringRepresentation(this.elemType) is RecordType -> this.decl.spelling is EnumType -> if (this.def.isAnonymous) { this.def.baseType.getStringRepresentation() } else { this.def.spelling } is Typedef -> this.def.aliased.getStringRepresentation() is ObjCPointer -> when (this) { is ObjCIdType -> "id$protocolQualifier" is ObjCClassPointer -> "Class$protocolQualifier" is ObjCObjectPointer -> "${def.name}$protocolQualifier*" is ObjCInstanceType -> TODO(this.toString()) // Must have already been handled. is ObjCBlockPointer -> "id" } else -> throw NotImplementedError() } fun getPointerTypeStringRepresentation(pointee: Type): String = (getStringRepresentationOfPointee(pointee) ?: "void") + "*" private fun getStringRepresentationOfPointee(type: Type): String? { val unwrapped = type.unwrapTypedefs() return when (unwrapped) { is PrimitiveType -> unwrapped.getStringRepresentation() is PointerType -> getStringRepresentationOfPointee(unwrapped.pointeeType)?.plus("*") is RecordType -> if (unwrapped.decl.isAnonymous || unwrapped.decl.spelling == "struct __va_list_tag") { null } else { unwrapped.decl.spelling } else -> null } } private val ObjCQualifiedPointer.protocolQualifier: String get() = if (this.protocols.isEmpty()) "" else " <${protocols.joinToString { it.name }}>" fun blockTypeStringRepresentation(type: ObjCBlockPointer): String { return buildString { append(type.returnType.getStringRepresentation()) append("(^)") append("(") val blockParameters = if (type.parameterTypes.isEmpty()) { "void" } else { type.parameterTypes.joinToString { it.getStringRepresentation() } } append(blockParameters) append(")") } }
apache-2.0
2e97f4b881c73ff79b7b4fd8f2e536a7
33.24
111
0.681075
4.412371
false
false
false
false
JetBrains/kotlin-native
backend.native/compiler/ir/backend.native/src/org/jetbrains/kotlin/backend/konan/objcexport/ObjCExportNamer.kt
1
35457
/* * Copyright 2010-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 org.jetbrains.kotlin.backend.konan.objcexport import org.jetbrains.kotlin.backend.common.serialization.findSourceFile import org.jetbrains.kotlin.backend.konan.cKeywords import org.jetbrains.kotlin.backend.konan.descriptors.isArray import org.jetbrains.kotlin.backend.konan.descriptors.isInterface import org.jetbrains.kotlin.descriptors.konan.isNativeStdlib import org.jetbrains.kotlin.builtins.KotlinBuiltIns import org.jetbrains.kotlin.builtins.StandardNames import org.jetbrains.kotlin.descriptors.* import org.jetbrains.kotlin.descriptors.konan.* import org.jetbrains.kotlin.incremental.components.NoLookupLocation import org.jetbrains.kotlin.library.shortName import org.jetbrains.kotlin.library.uniqueName import org.jetbrains.kotlin.load.kotlin.PackagePartClassUtils import org.jetbrains.kotlin.name.ClassId import org.jetbrains.kotlin.name.Name import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType import org.jetbrains.kotlin.resolve.descriptorUtil.isSubclassOf import org.jetbrains.kotlin.resolve.descriptorUtil.module import org.jetbrains.kotlin.resolve.descriptorUtil.propertyIfAccessor import org.jetbrains.kotlin.resolve.source.PsiSourceFile internal interface ObjCExportNameTranslator { fun getFileClassName(file: KtFile): ObjCExportNamer.ClassOrProtocolName fun getCategoryName(file: KtFile): String fun getClassOrProtocolName( ktClassOrObject: KtClassOrObject ): ObjCExportNamer.ClassOrProtocolName fun getTypeParameterName(ktTypeParameter: KtTypeParameter): String } interface ObjCExportNamer { data class ClassOrProtocolName(val swiftName: String, val objCName: String, val binaryName: String = objCName) interface Configuration { val topLevelNamePrefix: String fun getAdditionalPrefix(module: ModuleDescriptor): String? val objcGenerics: Boolean } val topLevelNamePrefix: String fun getFileClassName(file: SourceFile): ClassOrProtocolName fun getClassOrProtocolName(descriptor: ClassDescriptor): ClassOrProtocolName fun getSelector(method: FunctionDescriptor): String fun getSwiftName(method: FunctionDescriptor): String fun getPropertyName(property: PropertyDescriptor): String fun getObjectInstanceSelector(descriptor: ClassDescriptor): String fun getEnumEntrySelector(descriptor: ClassDescriptor): String fun getEnumValuesSelector(descriptor: FunctionDescriptor): String fun getTypeParameterName(typeParameterDescriptor: TypeParameterDescriptor): String fun numberBoxName(classId: ClassId): ClassOrProtocolName val kotlinAnyName: ClassOrProtocolName val mutableSetName: ClassOrProtocolName val mutableMapName: ClassOrProtocolName val kotlinNumberName: ClassOrProtocolName } fun createNamer(moduleDescriptor: ModuleDescriptor, topLevelNamePrefix: String = moduleDescriptor.namePrefix): ObjCExportNamer = createNamer(moduleDescriptor, emptyList(), topLevelNamePrefix) fun createNamer( moduleDescriptor: ModuleDescriptor, exportedDependencies: List<ModuleDescriptor>, topLevelNamePrefix: String = moduleDescriptor.namePrefix ): ObjCExportNamer = ObjCExportNamerImpl( (exportedDependencies + moduleDescriptor).toSet(), moduleDescriptor.builtIns, ObjCExportMapper(local = true), topLevelNamePrefix, local = true ) // Note: this class duplicates some of ObjCExportNamerImpl logic, // but operates on different representation. internal open class ObjCExportNameTranslatorImpl( configuration: ObjCExportNamer.Configuration ) : ObjCExportNameTranslator { private val helper = ObjCExportNamingHelper(configuration.topLevelNamePrefix, configuration.objcGenerics) override fun getFileClassName(file: KtFile): ObjCExportNamer.ClassOrProtocolName = helper.getFileClassName(file) override fun getCategoryName(file: KtFile): String = helper.translateFileName(file) override fun getClassOrProtocolName( ktClassOrObject: KtClassOrObject ): ObjCExportNamer.ClassOrProtocolName = helper.swiftClassNameToObjC( getClassOrProtocolSwiftName(ktClassOrObject) ) private fun getClassOrProtocolSwiftName( ktClassOrObject: KtClassOrObject ): String = buildString { val outerClass = ktClassOrObject.getStrictParentOfType<KtClassOrObject>() if (outerClass != null) { appendNameWithContainer(ktClassOrObject, outerClass) } else { append(ktClassOrObject.name!!.toIdentifier()) } } private fun StringBuilder.appendNameWithContainer( ktClassOrObject: KtClassOrObject, outerClass: KtClassOrObject ) = helper.appendNameWithContainer( this, ktClassOrObject, ktClassOrObject.name!!.toIdentifier(), outerClass, getClassOrProtocolSwiftName(outerClass), object : ObjCExportNamingHelper.ClassInfoProvider<KtClassOrObject> { override fun hasGenerics(clazz: KtClassOrObject): Boolean = clazz.typeParametersWithOuter.count() != 0 override fun isInterface(clazz: KtClassOrObject): Boolean = ktClassOrObject.isInterface } ) override fun getTypeParameterName(ktTypeParameter: KtTypeParameter): String = buildString { append(ktTypeParameter.name!!.toIdentifier()) while (helper.isTypeParameterNameReserved(this.toString())) append('_') } } private class ObjCExportNamingHelper( private val topLevelNamePrefix: String, private val objcGenerics: Boolean ) { fun translateFileName(fileName: String): String = PackagePartClassUtils.getFilePartShortName(fileName).toIdentifier() fun translateFileName(file: KtFile): String = translateFileName(file.name) fun getFileClassName(fileName: String): ObjCExportNamer.ClassOrProtocolName { val baseName = translateFileName(fileName) return ObjCExportNamer.ClassOrProtocolName(swiftName = baseName, objCName = "$topLevelNamePrefix$baseName") } fun swiftClassNameToObjC(swiftName: String): ObjCExportNamer.ClassOrProtocolName = ObjCExportNamer.ClassOrProtocolName(swiftName, buildString { append(topLevelNamePrefix) swiftName.split('.').forEachIndexed { index, part -> append(if (index == 0) part else part.capitalize()) } }) fun getFileClassName(file: KtFile): ObjCExportNamer.ClassOrProtocolName = getFileClassName(file.name) fun <T> appendNameWithContainer( builder: StringBuilder, clazz: T, ownName: String, containingClass: T, containerName: String, provider: ClassInfoProvider<T> ) = builder.apply { if (clazz.canBeSwiftInner(provider)) { append(containerName) if (!this.contains('.') && containingClass.canBeSwiftOuter(provider)) { // AB -> AB.C append('.') append(mangleSwiftNestedClassName(ownName)) } else { // AB -> ABC // A.B -> A.BC append(ownName.capitalize()) } } else { // AB, A.B -> ABC val dotIndex = containerName.indexOf('.') if (dotIndex == -1) { append(containerName) } else { append(containerName.substring(0, dotIndex)) append(containerName.substring(dotIndex + 1).capitalize()) } append(ownName.capitalize()) } } interface ClassInfoProvider<T> { fun hasGenerics(clazz: T): Boolean fun isInterface(clazz: T): Boolean } private fun <T> T.canBeSwiftOuter(provider: ClassInfoProvider<T>): Boolean = when { objcGenerics && provider.hasGenerics(this) -> { // Swift nested classes are static but capture outer's generics. false } provider.isInterface(this) -> { // Swift doesn't support outer protocols. false } else -> true } private fun <T> T.canBeSwiftInner(provider: ClassInfoProvider<T>): Boolean = when { objcGenerics && provider.hasGenerics(this) -> { // Swift compiler doesn't seem to handle this case properly. false } provider.isInterface(this) -> { // Swift doesn't support nested protocols. false } else -> true } fun mangleSwiftNestedClassName(name: String): String = when (name) { "Type" -> "${name}_" // See https://github.com/JetBrains/kotlin-native/issues/3167 else -> name } fun isTypeParameterNameReserved(name: String): Boolean = name in reservedTypeParameterNames private val reservedTypeParameterNames = setOf("id", "NSObject", "NSArray", "NSCopying", "NSNumber", "NSInteger", "NSUInteger", "NSString", "NSSet", "NSDictionary", "NSMutableArray", "int", "unsigned", "short", "char", "long", "float", "double", "int32_t", "int64_t", "int16_t", "int8_t", "unichar") } internal class ObjCExportNamerImpl( private val configuration: ObjCExportNamer.Configuration, builtIns: KotlinBuiltIns, private val mapper: ObjCExportMapper, private val local: Boolean ) : ObjCExportNamer { constructor( moduleDescriptors: Set<ModuleDescriptor>, builtIns: KotlinBuiltIns, mapper: ObjCExportMapper, topLevelNamePrefix: String, local: Boolean, objcGenerics: Boolean = false ) : this( object : ObjCExportNamer.Configuration { override val topLevelNamePrefix: String get() = topLevelNamePrefix override fun getAdditionalPrefix(module: ModuleDescriptor): String? = if (module in moduleDescriptors) null else module.namePrefix override val objcGenerics: Boolean get() = objcGenerics }, builtIns, mapper, local ) private val objcGenerics get() = configuration.objcGenerics override val topLevelNamePrefix get() = configuration.topLevelNamePrefix private val helper = ObjCExportNamingHelper(configuration.topLevelNamePrefix, objcGenerics) private fun String.toSpecialStandardClassOrProtocolName() = ObjCExportNamer.ClassOrProtocolName( swiftName = "Kotlin$this", objCName = "${topLevelNamePrefix}$this" ) override val kotlinAnyName = "Base".toSpecialStandardClassOrProtocolName() override val mutableSetName = "MutableSet".toSpecialStandardClassOrProtocolName() override val mutableMapName = "MutableDictionary".toSpecialStandardClassOrProtocolName() override fun numberBoxName(classId: ClassId): ObjCExportNamer.ClassOrProtocolName = classId.shortClassName.asString().toSpecialStandardClassOrProtocolName() override val kotlinNumberName = "Number".toSpecialStandardClassOrProtocolName() private val methodSelectors = object : Mapping<FunctionDescriptor, String>() { // Try to avoid clashing with critical NSObject instance methods: private val reserved = setOf( "retain", "release", "autorelease", "class", "superclass", "hash" ) override fun reserved(name: String) = name in reserved override fun conflict(first: FunctionDescriptor, second: FunctionDescriptor): Boolean = !mapper.canHaveSameSelector(first, second) } private val methodSwiftNames = object : Mapping<FunctionDescriptor, String>() { override fun conflict(first: FunctionDescriptor, second: FunctionDescriptor): Boolean = !mapper.canHaveSameSelector(first, second) // Note: this condition is correct but can be too strict. } private val propertyNames = object : Mapping<PropertyDescriptor, String>() { override fun reserved(name: String) = name in Reserved.propertyNames override fun conflict(first: PropertyDescriptor, second: PropertyDescriptor): Boolean = !mapper.canHaveSameName(first, second) } private open inner class GlobalNameMapping<in T : Any, N> : Mapping<T, N>() { final override fun conflict(first: T, second: T): Boolean = true } private val objCClassNames = GlobalNameMapping<Any, String>() private val objCProtocolNames = GlobalNameMapping<ClassDescriptor, String>() // Classes and protocols share the same namespace in Swift. private val swiftClassAndProtocolNames = GlobalNameMapping<Any, String>() private val genericTypeParameterNameMapping = GenericTypeParameterNameMapping() private abstract inner class ClassSelectorNameMapping<T : Any> : Mapping<T, String>() { // Try to avoid clashing with NSObject class methods: private val reserved = setOf( "retain", "release", "autorelease", "initialize", "load", "alloc", "new", "class", "superclass", "classFallbacksForKeyedArchiver", "classForKeyedUnarchiver", "description", "debugDescription", "version", "hash", "useStoredAccessor" ) override fun reserved(name: String) = (name in reserved) || (name in cKeywords) } private val objectInstanceSelectors = object : ClassSelectorNameMapping<ClassDescriptor>() { override fun conflict(first: ClassDescriptor, second: ClassDescriptor) = false } private val enumClassSelectors = object : ClassSelectorNameMapping<DeclarationDescriptor>() { override fun conflict(first: DeclarationDescriptor, second: DeclarationDescriptor) = first.containingDeclaration == second.containingDeclaration } override fun getFileClassName(file: SourceFile): ObjCExportNamer.ClassOrProtocolName { val candidate by lazy { val fileName = when (file) { is PsiSourceFile -> { val psiFile = file.psiFile val ktFile = psiFile as? KtFile ?: error("PsiFile '$psiFile' is not KtFile") ktFile.name } else -> file.name ?: error("$file has no name") } helper.getFileClassName(fileName) } val objCName = objCClassNames.getOrPut(file) { StringBuilder(candidate.objCName).mangledBySuffixUnderscores() } val swiftName = swiftClassAndProtocolNames.getOrPut(file) { StringBuilder(candidate.swiftName).mangledBySuffixUnderscores() } return ObjCExportNamer.ClassOrProtocolName(swiftName = swiftName, objCName = objCName) } override fun getClassOrProtocolName(descriptor: ClassDescriptor): ObjCExportNamer.ClassOrProtocolName = ObjCExportNamer.ClassOrProtocolName( swiftName = getClassOrProtocolSwiftName(descriptor), objCName = getClassOrProtocolObjCName(descriptor) ) private fun getClassOrProtocolSwiftName( descriptor: ClassDescriptor ): String = swiftClassAndProtocolNames.getOrPut(descriptor) { StringBuilder().apply { val containingDeclaration = descriptor.containingDeclaration if (containingDeclaration is ClassDescriptor) { appendNameWithContainer(descriptor, containingDeclaration) } else if (containingDeclaration is PackageFragmentDescriptor) { appendTopLevelClassBaseName(descriptor) } else { error("unexpected class parent: $containingDeclaration") } }.mangledBySuffixUnderscores() } private fun StringBuilder.appendNameWithContainer( clazz: ClassDescriptor, containingClass: ClassDescriptor ) = helper.appendNameWithContainer( this, clazz, clazz.name.asString().toIdentifier(), containingClass, getClassOrProtocolSwiftName(containingClass), object : ObjCExportNamingHelper.ClassInfoProvider<ClassDescriptor> { override fun hasGenerics(clazz: ClassDescriptor): Boolean = clazz.typeConstructor.parameters.isNotEmpty() override fun isInterface(clazz: ClassDescriptor): Boolean = clazz.isInterface } ) private fun getClassOrProtocolObjCName(descriptor: ClassDescriptor): String { val objCMapping = if (descriptor.isInterface) objCProtocolNames else objCClassNames return objCMapping.getOrPut(descriptor) { StringBuilder().apply { val containingDeclaration = descriptor.containingDeclaration if (containingDeclaration is ClassDescriptor) { append(getClassOrProtocolObjCName(containingDeclaration)) .append(descriptor.name.asString().toIdentifier().capitalize()) } else if (containingDeclaration is PackageFragmentDescriptor) { append(topLevelNamePrefix).appendTopLevelClassBaseName(descriptor) } else { error("unexpected class parent: $containingDeclaration") } }.mangledBySuffixUnderscores() } } private fun StringBuilder.appendTopLevelClassBaseName(descriptor: ClassDescriptor) = apply { configuration.getAdditionalPrefix(descriptor.module)?.let { append(it) } append(descriptor.name.asString().toIdentifier()) } override fun getSelector(method: FunctionDescriptor): String = methodSelectors.getOrPut(method) { assert(mapper.isBaseMethod(method)) getPredefined(method, Predefined.anyMethodSelectors)?.let { return it } val parameters = mapper.bridgeMethod(method).valueParametersAssociated(method) StringBuilder().apply { append(method.getMangledName(forSwift = false)) parameters.forEachIndexed { index, (bridge, it) -> val name = when (bridge) { is MethodBridgeValueParameter.Mapped -> when { it is ReceiverParameterDescriptor -> "" method is PropertySetterDescriptor -> when (parameters.size) { 1 -> "" else -> "value" } else -> it!!.name.asString().toIdentifier() } MethodBridgeValueParameter.ErrorOutParameter -> "error" MethodBridgeValueParameter.SuspendCompletion -> "completionHandler" } if (index == 0) { append(when { bridge is MethodBridgeValueParameter.ErrorOutParameter -> "AndReturn" bridge is MethodBridgeValueParameter.SuspendCompletion -> "With" method is ConstructorDescriptor -> "With" else -> "" }) append(name.capitalize()) } else { append(name) } append(':') } }.mangledSequence { if (parameters.isNotEmpty()) { // "foo:" -> "foo_:" insert(lastIndex, '_') } else { // "foo" -> "foo_" append("_") } } } override fun getSwiftName(method: FunctionDescriptor): String = methodSwiftNames.getOrPut(method) { assert(mapper.isBaseMethod(method)) getPredefined(method, Predefined.anyMethodSwiftNames)?.let { return it } val parameters = mapper.bridgeMethod(method).valueParametersAssociated(method) StringBuilder().apply { append(method.getMangledName(forSwift = true)) append("(") parameters@ for ((bridge, it) in parameters) { val label = when (bridge) { is MethodBridgeValueParameter.Mapped -> when { it is ReceiverParameterDescriptor -> "_" method is PropertySetterDescriptor -> when (parameters.size) { 1 -> "_" else -> "value" } else -> it!!.name.asString().toIdentifier() } MethodBridgeValueParameter.ErrorOutParameter -> continue@parameters MethodBridgeValueParameter.SuspendCompletion -> "completionHandler" } append(label) append(":") } append(")") }.mangledSequence { // "foo(label:)" -> "foo(label_:)" // "foo()" -> "foo_()" insert(lastIndex - 1, '_') } } private fun <T : Any> getPredefined(method: FunctionDescriptor, predefinedForAny: Map<Name, T>): T? { return if (method.containingDeclaration.let { it is ClassDescriptor && KotlinBuiltIns.isAny(it) }) { predefinedForAny.getValue(method.name) } else { null } } override fun getPropertyName(property: PropertyDescriptor): String = propertyNames.getOrPut(property) { assert(mapper.isBaseProperty(property)) assert(mapper.isObjCProperty(property)) StringBuilder().apply { append(property.name.asString().toIdentifier()) }.mangledSequence { append('_') } } override fun getObjectInstanceSelector(descriptor: ClassDescriptor): String { assert(descriptor.kind == ClassKind.OBJECT) return objectInstanceSelectors.getOrPut(descriptor) { val name = descriptor.name.asString().decapitalize().toIdentifier().mangleIfSpecialFamily("get") StringBuilder(name).mangledBySuffixUnderscores() } } override fun getEnumEntrySelector(descriptor: ClassDescriptor): String { assert(descriptor.kind == ClassKind.ENUM_ENTRY) return enumClassSelectors.getOrPut(descriptor) { // FOO_BAR_BAZ -> fooBarBaz: val name = descriptor.name.asString().split('_').mapIndexed { index, s -> val lower = s.toLowerCase() if (index == 0) lower else lower.capitalize() }.joinToString("").toIdentifier().mangleIfSpecialFamily("the") StringBuilder(name).mangledBySuffixUnderscores() } } override fun getEnumValuesSelector(descriptor: FunctionDescriptor): String { val containingDeclaration = descriptor.containingDeclaration require(containingDeclaration is ClassDescriptor && containingDeclaration.kind == ClassKind.ENUM_CLASS) require(descriptor.name == StandardNames.ENUM_VALUES) require(descriptor.dispatchReceiverParameter == null) { "must be static" } require(descriptor.extensionReceiverParameter == null) { "must be static" } require(descriptor.valueParameters.isEmpty()) return enumClassSelectors.getOrPut(descriptor) { StringBuilder(descriptor.name.asString()).mangledBySuffixUnderscores() } } override fun getTypeParameterName(typeParameterDescriptor: TypeParameterDescriptor): String { return genericTypeParameterNameMapping.getOrPut(typeParameterDescriptor) { StringBuilder().apply { append(typeParameterDescriptor.name.asString().toIdentifier()) }.mangledSequence { append('_') } } } init { if (!local) { forceAssignPredefined(builtIns) } } private fun forceAssignPredefined(builtIns: KotlinBuiltIns) { val any = builtIns.any val predefinedClassNames = mapOf( builtIns.any to kotlinAnyName, builtIns.mutableSet to mutableSetName, builtIns.mutableMap to mutableMapName ) predefinedClassNames.forEach { descriptor, name -> objCClassNames.forceAssign(descriptor, name.objCName) swiftClassAndProtocolNames.forceAssign(descriptor, name.swiftName) } fun ClassDescriptor.method(name: Name) = this.unsubstitutedMemberScope.getContributedFunctions( name, NoLookupLocation.FROM_BACKEND ).single() Predefined.anyMethodSelectors.forEach { name, selector -> methodSelectors.forceAssign(any.method(name), selector) } Predefined.anyMethodSwiftNames.forEach { name, swiftName -> methodSwiftNames.forceAssign(any.method(name), swiftName) } } private object Predefined { val anyMethodSelectors = mapOf( "hashCode" to "hash", "toString" to "description", "equals" to "isEqual:" ).mapKeys { Name.identifier(it.key) } val anyMethodSwiftNames = mapOf( "hashCode" to "hash()", "toString" to "description()", "equals" to "isEqual(_:)" ).mapKeys { Name.identifier(it.key) } } private object Reserved { val propertyNames = cKeywords + setOf("description") // https://youtrack.jetbrains.com/issue/KT-38641 } private fun FunctionDescriptor.getMangledName(forSwift: Boolean): String { if (this is ConstructorDescriptor) { return if (this.constructedClass.isArray && !forSwift) "array" else "init" } val candidate = when (this) { is PropertyGetterDescriptor -> this.correspondingProperty.name.asString() is PropertySetterDescriptor -> "set${this.correspondingProperty.name.asString().capitalize()}" else -> this.name.asString() }.toIdentifier() return candidate.mangleIfSpecialFamily("do") } private fun String.mangleIfSpecialFamily(prefix: String): String { val trimmed = this.dropWhile { it == '_' } for (family in listOf("alloc", "copy", "mutableCopy", "new", "init")) { if (trimmed.startsWithWords(family)) { // Then method can be detected as having special family by Objective-C compiler. // mangle the name: return prefix + this.capitalize() } } // TODO: handle clashes with NSObject methods etc. return this } private fun String.startsWithWords(words: String) = this.startsWith(words) && (this.length == words.length || !this[words.length].isLowerCase()) private inner class GenericTypeParameterNameMapping { private val elementToName = mutableMapOf<TypeParameterDescriptor, String>() private val typeParameterNameClassOverrides = mutableMapOf<ClassDescriptor, MutableSet<String>>() fun getOrPut(element: TypeParameterDescriptor, nameCandidates: () -> Sequence<String>): String { getIfAssigned(element)?.let { return it } nameCandidates().forEach { if (tryAssign(element, it)) { return it } } error("name candidates run out") } private fun tryAssign(element: TypeParameterDescriptor, name: String): Boolean { if (element in elementToName) error(element) if (helper.isTypeParameterNameReserved(name)) return false if (!validName(element, name)) return false assignName(element, name) return true } private fun assignName(element: TypeParameterDescriptor, name: String) { if (!local) { elementToName[element] = name classNameSet(element).add(name) } } private fun validName(element: TypeParameterDescriptor, name: String): Boolean { assert(element.containingDeclaration is ClassDescriptor) return !objCClassNames.nameExists(name) && !objCProtocolNames.nameExists(name) && (local || name !in classNameSet(element)) } private fun classNameSet(element: TypeParameterDescriptor): MutableSet<String> { require(!local) return typeParameterNameClassOverrides.getOrPut(element.containingDeclaration as ClassDescriptor) { mutableSetOf() } } private fun getIfAssigned(element: TypeParameterDescriptor): String? = elementToName[element] } private abstract inner class Mapping<in T : Any, N>() { private val elementToName = mutableMapOf<T, N>() private val nameToElements = mutableMapOf<N, MutableList<T>>() abstract fun conflict(first: T, second: T): Boolean open fun reserved(name: N) = false inline fun getOrPut(element: T, nameCandidates: () -> Sequence<N>): N { getIfAssigned(element)?.let { return it } nameCandidates().forEach { if (tryAssign(element, it)) { return it } } error("name candidates run out") } fun nameExists(name: N) = nameToElements.containsKey(name) private fun getIfAssigned(element: T): N? = elementToName[element] private fun tryAssign(element: T, name: N): Boolean { if (element in elementToName) error(element) if (reserved(name)) return false if (nameToElements[name].orEmpty().any { conflict(element, it) }) { return false } if (!local) { nameToElements.getOrPut(name) { mutableListOf() } += element elementToName[element] = name } return true } fun forceAssign(element: T, name: N) { if (name in nameToElements || element in elementToName) error(element) nameToElements[name] = mutableListOf(element) elementToName[element] = name } } } private inline fun StringBuilder.mangledSequence(crossinline mangle: StringBuilder.() -> Unit) = generateSequence(this.toString()) { [email protected]() [email protected]() } private fun StringBuilder.mangledBySuffixUnderscores() = this.mangledSequence { append("_") } private fun ObjCExportMapper.canHaveCommonSubtype(first: ClassDescriptor, second: ClassDescriptor): Boolean { if (first.isSubclassOf(second) || second.isSubclassOf(first)) { return true } if (first.isFinalClass || second.isFinalClass) { return false } return first.isInterface || second.isInterface } private fun ObjCExportMapper.canBeInheritedBySameClass( first: CallableMemberDescriptor, second: CallableMemberDescriptor ): Boolean { if (this.isTopLevel(first) || this.isTopLevel(second)) { return this.isTopLevel(first) && this.isTopLevel(second) && first.propertyIfAccessor.findSourceFile() == second.propertyIfAccessor.findSourceFile() } val firstClass = this.getClassIfCategory(first) ?: first.containingDeclaration as ClassDescriptor val secondClass = this.getClassIfCategory(second) ?: second.containingDeclaration as ClassDescriptor if (first is ConstructorDescriptor) { return firstClass == secondClass || second !is ConstructorDescriptor && firstClass.isSubclassOf(secondClass) } if (second is ConstructorDescriptor) { return secondClass == firstClass || first !is ConstructorDescriptor && secondClass.isSubclassOf(firstClass) } return canHaveCommonSubtype(firstClass, secondClass) } private fun ObjCExportMapper.canHaveSameSelector(first: FunctionDescriptor, second: FunctionDescriptor): Boolean { assert(isBaseMethod(first)) assert(isBaseMethod(second)) if (!canBeInheritedBySameClass(first, second)) { return true } if (first.dispatchReceiverParameter == null || second.dispatchReceiverParameter == null) { // I.e. any is category method. return false } if (first.name != second.name) { return false } if (first.extensionReceiverParameter?.type != second.extensionReceiverParameter?.type) { return false } if (first is PropertySetterDescriptor && second is PropertySetterDescriptor) { // Methods should merge in any common subclass as it can't have two properties with same name. } else if (first.valueParameters.map { it.type } == second.valueParameters.map { it.type }) { // Methods should merge in any common subclasses since they have the same signature. } else { return false } // Check if methods have the same bridge (and thus the same ABI): return bridgeMethod(first) == bridgeMethod(second) } private fun ObjCExportMapper.canHaveSameName(first: PropertyDescriptor, second: PropertyDescriptor): Boolean { assert(isBaseProperty(first)) assert(isObjCProperty(first)) assert(isBaseProperty(second)) assert(isObjCProperty(second)) if (!canBeInheritedBySameClass(first, second)) { return true } if (first.dispatchReceiverParameter == null || second.dispatchReceiverParameter == null) { // I.e. any is category property. return false } if (first.name != second.name) { return false } return bridgePropertyType(first) == bridgePropertyType(second) } internal val ModuleDescriptor.namePrefix: String get() { if (this.isNativeStdlib()) return "Kotlin" val fullPrefix = when(val module = this.klibModuleOrigin) { CurrentKlibModuleOrigin, SyntheticModulesOrigin -> this.name.asString().let { it.substring(1, it.lastIndex) } is DeserializedKlibModuleOrigin -> module.library.let { it.shortName ?: it.uniqueName } } return abbreviate(fullPrefix) } fun abbreviate(name: String): String { val normalizedName = name .capitalize() .replace("-|\\.".toRegex(), "_") val uppers = normalizedName.filterIndexed { index, character -> index == 0 || character.isUpperCase() } if (uppers.length >= 3) return uppers return normalizedName } // Note: most usages of this method rely on the fact that concatenation of valid identifiers is valid identifier. // This may sometimes be a bit conservative (since it requires mangling non-first character as if it was first); // ignore this for simplicity as having Kotlin identifiers starting from digits is supposed to be rare case. internal fun String.toValidObjCSwiftIdentifier(): String { if (this.isEmpty()) return "__" return this.replace('$', '_') // TODO: handle more special characters. .let { if (it.first().isDigit()) "_$it" else it } .let { if (it == "_") "__" else it } } // Private shortcut. private fun String.toIdentifier(): String = this.toValidObjCSwiftIdentifier()
apache-2.0
128b0da727eed67c70e0e380578fa3f3
37.624183
117
0.643963
5.275554
false
false
false
false
dahlstrom-g/intellij-community
platform/lang-impl/src/com/intellij/navigation/JBProtocolNavigateCommand.kt
4
2051
// 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.navigation import com.intellij.ide.IdeBundle import com.intellij.openapi.application.JBProtocolCommand import com.intellij.openapi.editor.Editor import com.intellij.openapi.editor.LogicalPosition import com.intellij.openapi.project.DumbService import java.util.concurrent.CompletableFuture import java.util.concurrent.Future open class JBProtocolNavigateCommand: JBProtocolCommand(NAVIGATE_COMMAND) { /** * The handler parses the following "navigate" command parameters: * * \\?project=(?<project>[\\w]+) * (&fqn[\\d]*=(?<fqn>[\\w.\\-#]+))* * (&path[\\d]*=(?<path>[\\w-_/\\\\.]+) * (:(?<lineNumber>[\\d]+))? * (:(?<columnNumber>[\\d]+))?)* * (&selection[\\d]*= * (?<line1>[\\d]+):(?<column1>[\\d]+) * -(?<line2>[\\d]+):(?<column2>[\\d]+))* */ override fun perform(target: String?, parameters: MutableMap<String, String>, fragment: String?): Future<String?> = if (target != REFERENCE_TARGET) { CompletableFuture.completedFuture(IdeBundle.message("jb.protocol.navigate.target", target)) } else { openProject(parameters).handle { project, t -> when { t != null -> "${t.javaClass.name}: ${t.message}" project == null -> IdeBundle.message("jb.protocol.navigate.no.project") else -> { DumbService.getInstance(project).runWhenSmart { NavigatorWithinProject(project, parameters, ::locationToOffset) .navigate(listOf( NavigatorWithinProject.NavigationKeyPrefix.FQN, NavigatorWithinProject.NavigationKeyPrefix.PATH )) } null } } } } private fun locationToOffset(locationInFile: LocationInFile, editor: Editor) = editor.logicalPositionToOffset(LogicalPosition(locationInFile.line, locationInFile.column)) }
apache-2.0
d4418adacb26bba173e8b438efd4abc9
40.02
158
0.637738
4.228866
false
false
false
false
nrizzio/Signal-Android
app/src/main/java/org/thoughtcrime/securesms/migrations/StoryViewedReceiptsStateMigrationJob.kt
1
1539
package org.thoughtcrime.securesms.migrations import org.thoughtcrime.securesms.database.SignalDatabase.Companion.recipients import org.thoughtcrime.securesms.jobmanager.Data import org.thoughtcrime.securesms.jobmanager.Job import org.thoughtcrime.securesms.keyvalue.SignalStore import org.thoughtcrime.securesms.recipients.Recipient import org.thoughtcrime.securesms.storage.StorageSyncHelper import org.thoughtcrime.securesms.util.TextSecurePreferences /** * Added as a way to initialize the story viewed receipts setting. */ internal class StoryViewedReceiptsStateMigrationJob( parameters: Parameters = Parameters.Builder().build() ) : MigrationJob(parameters) { companion object { const val KEY = "StoryViewedReceiptsStateMigrationJob" } override fun getFactoryKey(): String = KEY override fun isUiBlocking(): Boolean = false override fun performMigration() { if (!SignalStore.storyValues().isViewedReceiptsStateSet()) { SignalStore.storyValues().viewedReceiptsEnabled = TextSecurePreferences.isReadReceiptsEnabled(context) if (SignalStore.account().isRegistered) { recipients.markNeedsSync(Recipient.self().id) StorageSyncHelper.scheduleSyncForDataChange() } } } override fun shouldRetry(e: Exception): Boolean = false class Factory : Job.Factory<StoryViewedReceiptsStateMigrationJob> { override fun create(parameters: Parameters, data: Data): StoryViewedReceiptsStateMigrationJob { return StoryViewedReceiptsStateMigrationJob(parameters) } } }
gpl-3.0
70b63893f64025d368af00c918ec28ee
35.642857
108
0.789474
4.692073
false
false
false
false
androidx/androidx
room/room-compiler-processing-testing/src/main/java/androidx/room/compiler/processing/util/compiler/steps/KaptCompilationStep.kt
3
5981
/* * Copyright 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.room.compiler.processing.util.compiler.steps import androidx.room.compiler.processing.util.compiler.DiagnosticsMessageCollector import androidx.room.compiler.processing.util.compiler.KotlinCliRunner import androidx.room.compiler.processing.util.compiler.TestKapt3Registrar import androidx.room.compiler.processing.util.compiler.toSourceSet import java.io.File import javax.annotation.processing.Processor import org.jetbrains.kotlin.base.kapt3.AptMode import org.jetbrains.kotlin.base.kapt3.KaptFlag import org.jetbrains.kotlin.base.kapt3.KaptOptions import org.jetbrains.kotlin.cli.common.ExitCode import org.jetbrains.kotlin.compiler.plugin.parsePluginOption /** * Runs KAPT to run annotation processors. */ internal class KaptCompilationStep( private val annotationProcessors: List<Processor>, private val processorOptions: Map<String, String>, ) : KotlinCompilationStep { override val name = "kapt" private fun createKaptArgs( workingDir: File, javacArguments: List<String>, kotlincArguments: List<String> ): KaptOptions.Builder { return KaptOptions.Builder().also { it.stubsOutputDir = workingDir.resolve("kapt-stubs") // IGNORED it.sourcesOutputDir = workingDir.resolve(JAVA_SRC_OUT_FOLDER_NAME) // Compiled classes don't end up here but generated resources do. it.classesOutputDir = workingDir.resolve(RESOURCES_OUT_FOLDER_NAME) it.projectBaseDir = workingDir it.processingOptions["kapt.kotlin.generated"] = workingDir.resolve(KOTLIN_SRC_OUT_FOLDER_NAME) .also { it.mkdirs() } .canonicalPath it.processingOptions.putAll(processorOptions) it.mode = AptMode.STUBS_AND_APT it.processors.addAll(annotationProcessors.map { it::class.java.name }) // NOTE: this does not work very well until the following bug is fixed // https://youtrack.jetbrains.com/issue/KT-47934 it.flags.add(KaptFlag.MAP_DIAGNOSTIC_LOCATIONS) if (getPluginOptions(KAPT_PLUGIN_ID, kotlincArguments) .getOrDefault("correctErrorTypes", "false") == "true") { it.flags.add(KaptFlag.CORRECT_ERROR_TYPES) } javacArguments.forEach { javacArg -> it.javacOptions[javacArg.substringBefore("=")] = javacArg.substringAfter("=", missingDelimiterValue = "") } } } override fun execute( workingDir: File, arguments: CompilationStepArguments ): CompilationStepResult { if (annotationProcessors.isEmpty()) { return CompilationStepResult.skip(arguments) } val kaptMessages = DiagnosticsMessageCollector(name) val result = KotlinCliRunner.runKotlinCli( arguments = arguments, // output is ignored, destinationDir = workingDir.resolve(CLASS_OUT_FOLDER_NAME), pluginRegistrars = listOf( TestKapt3Registrar( processors = annotationProcessors, baseOptions = createKaptArgs( workingDir, arguments.javacArguments, arguments.kotlincArguments ), messageCollector = kaptMessages ) ) ) val generatedSources = listOfNotNull( workingDir.resolve(JAVA_SRC_OUT_FOLDER_NAME).toSourceSet(), workingDir.resolve(KOTLIN_SRC_OUT_FOLDER_NAME).toSourceSet() ) val diagnostics = resolveDiagnostics( diagnostics = result.diagnostics + kaptMessages.getDiagnostics(), sourceSets = arguments.sourceSets + generatedSources ) val outputClasspath = listOf(result.compiledClasspath) + workingDir.resolve(RESOURCES_OUT_FOLDER_NAME) return CompilationStepResult( success = result.exitCode == ExitCode.OK, generatedSourceRoots = generatedSources, diagnostics = diagnostics, nextCompilerArguments = arguments.copy( sourceSets = arguments.sourceSets + generatedSources ), outputClasspath = outputClasspath ) } companion object { private const val JAVA_SRC_OUT_FOLDER_NAME = "kapt-java-src-out" private const val KOTLIN_SRC_OUT_FOLDER_NAME = "kapt-kotlin-src-out" private const val RESOURCES_OUT_FOLDER_NAME = "kapt-classes-out" private const val CLASS_OUT_FOLDER_NAME = "class-out" private const val KAPT_PLUGIN_ID = "org.jetbrains.kotlin.kapt3" internal fun getPluginOptions( pluginId: String, kotlincArguments: List<String> ): Map<String, String> { val options = kotlincArguments.dropLast(1).zip(kotlincArguments.drop(1)) .filter { it.first == "-P" } .mapNotNull { parsePluginOption(it.second) } val filteredOptionsMap = options .filter { it.pluginId == pluginId } .associateBy({ it.optionName }, { it.value }) return filteredOptionsMap } } }
apache-2.0
7428f118f987664e0568815c86669cf9
41.126761
92
0.638689
4.910509
false
false
false
false
GunoH/intellij-community
platform/platform-tests/testSrc/com/intellij/execution/wsl/WSLDistributionConsoleFoldingTest.kt
8
6551
// 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.execution.wsl import com.intellij.execution.ExecutionBundle import com.intellij.execution.configurations.GeneralCommandLine import com.intellij.execution.wsl.WSLDistribution.* import com.intellij.testFramework.fixtures.TestFixtureRule import junit.framework.TestCase.assertEquals import org.junit.ClassRule import org.junit.Test import org.junit.rules.RuleChain class WSLDistributionConsoleFoldingTest { companion object { private val appRule = TestFixtureRule() private val wslRule = WslRule() @ClassRule @JvmField val ruleChain: RuleChain = RuleChain.outerRule(appRule).around(wslRule) } private val folding = WslDistributionConsoleFolding() @Test fun `should fold`() { fun assertShouldFold(commandLine: GeneralCommandLine = GeneralCommandLine("echo"), options: WSLCommandLineOptions) { val line = wslRule.wsl.patchCommandLine(commandLine, null, options).commandLineString assertShouldFold(expected = true, line = line) } val defaultOptions = WSLCommandLineOptions() assertShouldFold(options = defaultOptions) assertShouldFold(commandLine = GeneralCommandLine("foo", "bar", "buz"), options = defaultOptions) assertShouldFold(options = WSLCommandLineOptions().setExecuteCommandInShell(!defaultOptions.isExecuteCommandInShell)) assertShouldFold(options = WSLCommandLineOptions().setExecuteCommandInInteractiveShell(!defaultOptions.isExecuteCommandInInteractiveShell)) assertShouldFold(options = WSLCommandLineOptions().setExecuteCommandInLoginShell(!defaultOptions.isExecuteCommandInLoginShell)) assertShouldFold(options = WSLCommandLineOptions().setExecuteCommandInLoginShell(!defaultOptions.isExecuteCommandInLoginShell)) assertShouldFold(options = WSLCommandLineOptions().setSudo(!defaultOptions.isSudo)) assertShouldFold(options = WSLCommandLineOptions().setRemoteWorkingDirectory("/foo/bar/buz")) assertShouldFold(options = WSLCommandLineOptions().setRemoteWorkingDirectory("/foo bar/buz buz buz")) assertShouldFold(commandLine = GeneralCommandLine("echo").withEnvironment("foo", "bar"), options = WSLCommandLineOptions().setPassEnvVarsUsingInterop(true)) assertShouldFold(commandLine = GeneralCommandLine("echo").withEnvironment("foo", "bar"), options = WSLCommandLineOptions()) assertShouldFold(options = WSLCommandLineOptions().addInitCommand("foo bar")) } @Test fun `should not fold`() { fun assertShouldNotFold(line: String) { assertShouldFold(expected = false, line = line) } assertShouldNotFold("Foo bar") assertShouldNotFold("abracadabra") assertShouldNotFold("wsl.exe") // random wsl.exe assertShouldNotFold("wsl.exe --exec echo") // no --distribution assertShouldNotFold("--distribution Ubuntu-18.04 --exec echo") // no wsl.exe assertShouldNotFold("--distribution Ubuntu-18.04 wsl.exe --exec echo") // --distribution before wsl.exe assertShouldNotFold("wsl.exe --distribution Ubuntu-18.04") // no --exec val wslEcho = wslRule.wsl.patchCommandLine(GeneralCommandLine("echo"), null, WSLCommandLineOptions()).commandLineString assertShouldNotFold(wslEcho.remove(WSL_EXE)) // no wsl.exe assertShouldNotFold(wslEcho.remove(DISTRIBUTION_PARAMETER)) // no --distribution assertShouldNotFold(DISTRIBUTION_PARAMETER + wslEcho.remove(DISTRIBUTION_PARAMETER)) // --distribution before wsl.exe assertShouldNotFold(wslEcho.remove(EXEC_PARAMETER)) // no --exec assertShouldNotFold(EXEC_PARAMETER + wslEcho.remove(EXEC_PARAMETER)) // --exec before wsl.exe assertShouldNotFold("&& " + wslEcho.remove(EXEC_PARAMETER)) // && before wsl.exe val wslExeIndex = wslEcho.indexOf(WSL_EXE) val system32Prefix = wslEcho.substring(0, wslExeIndex) assertShouldNotFold(wslEcho.remove(system32Prefix)) // no C:\WINDOWS\system32 assertShouldNotFold(wslEcho.replace(system32Prefix, "foo bar")) // C:\WINDOWS\system32 broken } private fun assertShouldFold(expected: Boolean, line: String) { assertEquals( "Should ${if (expected) "fold" else "NOT fold"} line: $line", expected, folding.shouldFoldLineNoProject(line) ) } @Test fun `replacement text`() { fun assertReplacement(commandLine: GeneralCommandLine = GeneralCommandLine("echo"), options: WSLCommandLineOptions) { val commandLineString = commandLine.commandLineString val expectedLine = if (options.isExecuteCommandInShell && options.remoteWorkingDirectory.isNullOrEmpty() && (options.isPassEnvVarsUsingInterop || commandLine.environment.isEmpty()) && options.initShellCommands.isEmpty()) { if (commandLineString.contains(" ")) { "${options.shellPath} -c \"$commandLineString\"" } else { "${options.shellPath} -c $commandLineString" } } else { commandLineString } val expected = ExecutionBundle.message("wsl.folding.placeholder", wslRule.wsl.msId, expectedLine) val actual = folding.getPlaceholderText(wslRule.wsl.patchCommandLine(commandLine, null, options).commandLineString) assertEquals(expected, actual) } val defaultOptions = WSLCommandLineOptions() assertReplacement(options = defaultOptions) assertReplacement(commandLine = GeneralCommandLine("foo", "-bar", "/baz"), options = defaultOptions) assertReplacement(options = WSLCommandLineOptions().setExecuteCommandInShell(!defaultOptions.isExecuteCommandInShell)) assertReplacement(options = WSLCommandLineOptions().setSudo(!defaultOptions.isSudo)) assertReplacement(options = WSLCommandLineOptions().setRemoteWorkingDirectory("/foo/bar/buz")) assertReplacement(options = WSLCommandLineOptions().setRemoteWorkingDirectory("/foo bar/buz buz buz")) assertReplacement(commandLine = GeneralCommandLine("echo").withEnvironment("foo", "bar"), options = WSLCommandLineOptions().setPassEnvVarsUsingInterop(true)) assertReplacement(commandLine = GeneralCommandLine("echo").withEnvironment("foo", "bar"), options = WSLCommandLineOptions()) assertReplacement(options = WSLCommandLineOptions().addInitCommand("foo bar")) } private fun String.remove(substring: String): String { val start = this.indexOf(substring) return if (start < 0) this else this.removeRange(start, start + substring.length) } }
apache-2.0
6f2eabe522e13dbc4d824b4f0dd4fdfe
53.140496
161
0.750114
4.834686
false
true
false
false
K0zka/kerub
src/main/kotlin/com/github/kerubistan/kerub/planner/steps/vm/start/virtualbox/VirtualBoxStartVirtualMachine.kt
2
1657
package com.github.kerubistan.kerub.planner.steps.vm.start.virtualbox import com.fasterxml.jackson.annotation.JsonTypeName import com.github.kerubistan.kerub.model.Host import com.github.kerubistan.kerub.model.VirtualMachine import com.github.kerubistan.kerub.model.VirtualMachineStatus import com.github.kerubistan.kerub.model.dynamic.VirtualMachineDynamic import com.github.kerubistan.kerub.planner.OperationalState import com.github.kerubistan.kerub.planner.reservations.Reservation import com.github.kerubistan.kerub.planner.reservations.UseHostReservation import com.github.kerubistan.kerub.planner.reservations.VmReservation import com.github.kerubistan.kerub.planner.steps.vm.base.HostStep import io.github.kerubistan.kroki.collections.update import java.math.BigInteger @JsonTypeName("vbox-start-vm") data class VirtualBoxStartVirtualMachine(val vm: VirtualMachine, override val host: Host) : HostStep { override fun reservations(): List<Reservation<*>> = listOf(UseHostReservation(host), VmReservation(vm)) override fun take(state: OperationalState): OperationalState = state.copy( vms = state.vms.update(vm.id) { it.copy( dynamic = VirtualMachineDynamic( id = vm.id, status = VirtualMachineStatus.Up, hostId = host.id, memoryUsed = vm.memory.min ) ) }, hosts = state.hosts.update(host.id) { hostData -> val dynamic = requireNotNull(hostData.dynamic) hostData.copy( dynamic = dynamic.copy( memFree = (dynamic.memFree ?: host.capabilities?.totalMemory ?: BigInteger.ZERO) - vm.memory.min.coerceAtLeast( BigInteger.ZERO) ) ) } ) }
apache-2.0
419248bd9516dfec2a72c8359eeef7bb
38.47619
104
0.757996
3.945238
false
false
false
false
GunoH/intellij-community
plugins/kotlin/gradle/gradle-java/src/org/jetbrains/kotlin/idea/gradleJava/configuration/klib/KotlinNativeLibraryDataService.kt
4
3194
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.gradleJava.configuration.klib import com.intellij.openapi.externalSystem.model.DataNode import com.intellij.openapi.externalSystem.model.ProjectKeys import com.intellij.openapi.externalSystem.model.project.LibraryData import com.intellij.openapi.externalSystem.model.project.ProjectData import com.intellij.openapi.externalSystem.service.project.IdeModifiableModelsProvider import com.intellij.openapi.externalSystem.service.project.IdeUIModifiableModelsProvider import com.intellij.openapi.externalSystem.service.project.manage.AbstractProjectDataService import com.intellij.openapi.externalSystem.util.ExternalSystemConstants import com.intellij.openapi.externalSystem.util.Order import com.intellij.openapi.project.Project import com.intellij.openapi.roots.LibraryOrderEntry import com.intellij.openapi.roots.libraries.Library import org.jetbrains.kotlin.idea.gradle.configuration.klib.KotlinNativeLibraryNameUtil.KOTLIN_NATIVE_LIBRARY_PREFIX_PLUS_SPACE // KT-30490. This `ProjectDaaStervice` must be executed immediately after // `com.intellij.openapi.externalSystem.service.project.manage.LibraryDataService` to clean-up KLIBs before any other actions taken on them. @Order(ExternalSystemConstants.BUILTIN_LIBRARY_DATA_SERVICE_ORDER + 1) // force order class KotlinNativeLibraryDataService : AbstractProjectDataService<LibraryData, Library>() { override fun getTargetDataKey() = ProjectKeys.LIBRARY // See also `com.intellij.openapi.externalSystem.service.project.manage.LibraryDataService.postProcess()` override fun postProcess( toImport: MutableCollection<out DataNode<LibraryData>>, projectData: ProjectData?, project: Project, modelsProvider: IdeModifiableModelsProvider ) { if (projectData == null || modelsProvider is IdeUIModifiableModelsProvider) return val librariesModel = modelsProvider.modifiableProjectLibrariesModel val potentialOrphans = HashMap<String, Library>() librariesModel.libraries.forEach { library -> val libraryName = library.name?.takeIf { it.startsWith(KOTLIN_NATIVE_LIBRARY_PREFIX_PLUS_SPACE) } ?: return@forEach potentialOrphans[libraryName] = library } if (potentialOrphans.isEmpty()) return modelsProvider.modules.forEach { module -> modelsProvider.getOrderEntries(module).forEach inner@{ orderEntry -> val libraryOrderEntry = orderEntry as? LibraryOrderEntry ?: return@inner if (libraryOrderEntry.isModuleLevel) return@inner val libraryName = (libraryOrderEntry.library?.name ?: libraryOrderEntry.libraryName) ?.takeIf { it.startsWith(KOTLIN_NATIVE_LIBRARY_PREFIX_PLUS_SPACE) } ?: return@inner potentialOrphans.remove(libraryName) } } potentialOrphans.keys.forEach { libraryName -> librariesModel.getLibraryByName(libraryName)?.let { librariesModel.removeLibrary(it) } } } }
apache-2.0
d316b614a3662170e6a99b47b1a681e2
52.233333
158
0.762993
5.069841
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/editor/fixers/MissingConditionFixer.kt
6
2062
// 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.editor.fixers import com.intellij.lang.SmartEnterProcessorWithFixers import com.intellij.openapi.editor.Editor import com.intellij.psi.PsiElement import org.jetbrains.kotlin.idea.editor.KotlinSmartEnterHandler import kotlin.math.min abstract class MissingConditionFixer<T : PsiElement> : SmartEnterProcessorWithFixers.Fixer<KotlinSmartEnterHandler>() { override fun apply(editor: Editor, processor: KotlinSmartEnterHandler, element: PsiElement) { val workElement = getElement(element) ?: return val doc = editor.document val lParen = getLeftParenthesis(workElement) val rParen = getRightParenthesis(workElement) val condition = getCondition(workElement) if (condition == null) { if (lParen == null || rParen == null) { var stopOffset = doc.getLineEndOffset(doc.getLineNumber(workElement.range.start)) val then = getBody(workElement) if (then != null) { stopOffset = min(stopOffset, then.range.start) } stopOffset = min(stopOffset, workElement.range.end) doc.replaceString(workElement.range.start, stopOffset, "$keyword ()") processor.registerUnresolvedError(workElement.range.start + "$keyword (".length) } else { processor.registerUnresolvedError(lParen.range.end) } } else { if (rParen == null) { doc.insertString(condition.range.end, ")") } } } abstract val keyword: String abstract fun getElement(element: PsiElement?): T? abstract fun getCondition(element: T): PsiElement? abstract fun getLeftParenthesis(element: T): PsiElement? abstract fun getRightParenthesis(element: T): PsiElement? abstract fun getBody(element: T): PsiElement? }
apache-2.0
a861372e5d7fcc525d3c2c629cf86bf0
41.958333
158
0.667798
4.707763
false
false
false
false
chesslave/chesslave
backend/src/main/java/io/chesslave/visual/Images.kt
2
7628
package io.chesslave.visual import io.vavr.collection.Iterator import io.vavr.collection.Stream import org.slf4j.LoggerFactory import java.awt.Color import java.awt.Point import java.awt.image.BufferedImage import java.io.File import javax.imageio.ImageIO /** * Support methods for images. */ object Images { private val logger = LoggerFactory.getLogger(Images::class.java) /** * Reads the image from the classpath. */ fun read(path: String): BufferedImage { logger.trace("Reading image {}", path) return ImageIO.read(Images::class.java.getResource(path)) } /** * Writes the image of the given file as PNG. */ fun write(image: BufferedImage, file: File) { logger.debug("Writing image {}", file) ImageIO.write(image, "PNG", file) } /** * Clones the given image. */ fun copy(image: BufferedImage): BufferedImage { val copy = BufferedImage(image.width, image.height, image.type) val g = copy.graphics g.drawImage(image, 0, 0, null) g.dispose() return copy } /** * Removes the image border while the RGB pixel colors hold the given predicate. */ fun crop(image: BufferedImage, predicate: (Int) -> Boolean): BufferedImage { var top = 0 run { var accept = true while (accept) { for (x in 0..image.width - 1) { if (!predicate(image.getRGB(x, top))) { accept = false break } } if (accept) { ++top } } } var left = 0 run { var accept = true while (accept) { for (y in top..image.height - 1) { if (!predicate(image.getRGB(left, y))) { accept = false break } } if (accept) { ++left } } } var right = image.width - 1 run { var accept = true while (accept) { for (y in top..image.height - 1) { if (!predicate(image.getRGB(right, y))) { accept = false break } } if (accept) { --right } } } var bottom = image.height - 1 run { var accept = true while (accept) { for (x in left..right) { if (!predicate(image.getRGB(x, bottom))) { accept = false break } } if (accept) { --bottom } } } val width = right - left + 1 val height = bottom - top + 1 return image.getSubimage(left, top, width, height) } /** * Fills the outer background with the specific RGB color. */ fun fillOuterBackground(source: BufferedImage, newColor: Int): BufferedImage { val image = Images.copy(source) val oldColor = image.getRGB(0, 0) // top -> bottom for (x in 0..image.width - 1) { for (y in 0..image.height - 1) { val color = image.getRGB(x, y) if (color == oldColor) { image.setRGB(x, y, newColor) } else if (color != newColor) { break } } } // bottom -> top for (x in 0..image.width - 1) { for (y in image.height - 1 downTo 0) { val color = image.getRGB(x, y) if (color == oldColor) { image.setRGB(x, y, newColor) } else if (color != newColor) { break } } } // left -> right for (y in 0..image.height - 1) { for (x in 0..image.width - 1) { val color = image.getRGB(x, y) if (color == oldColor) { image.setRGB(x, y, newColor) } else if (color != newColor) { break } } } // right -> left for (y in 0..image.height - 1) { for (x in image.width - 1 downTo 0) { val color = image.getRGB(x, y) if (color == oldColor) { image.setRGB(x, y, newColor) } else if (color != newColor) { break } } } return image } /** * @param rowPoints The number of pixel colors to read for each image row. * * * @param columnPoints The number of pixel colors to read for each image column. * * * @return The stream of all pixel colors read from the upper-left corner to the down-right corner. * * For each row only `rowPoints` pixels are read at regular intervals at the center of the image. * * As the same way, for each column only `columnPoints` pixels are read at regular intervals at * * the center of the image. */ fun sample(image: BufferedImage, rowPoints: Int, columnPoints: Int): Iterator<Int> { val widthStep = image.width / (rowPoints + 1) val heightStep = image.height / (columnPoints + 1) return Stream.rangeClosed(1, rowPoints) .crossProduct(Stream.rangeClosed(1, columnPoints)) .map { image.getRGB(it._1 * widthStep, it._2 * heightStep) } } /** * @return True if the two images are *surely* different, false otherwise. */ fun areDifferent(fst: BufferedImage, snd: BufferedImage): Boolean = fst.width != snd.width || fst.height != snd.height || Images.sample(fst, 10, 10).sum().toInt() != Images.sample(snd, 10, 10).sum().toInt() /** * @return True if the two images are identical. */ fun areEquals(fst: BufferedImage, snd: BufferedImage): Boolean { if (fst.width != snd.width || fst.height != snd.height) { return false } for (x in 0..fst.width - 1) { for (y in 0..fst.height - 1) { if (fst.getRGB(x, y) != snd.getRGB(x, y)) { return false } } } return true } } typealias RBG = Int data class Movement(val dx: Int, val dy: Int) { companion object { val UP = Movement(0, -1) val DOWN = Movement(0, 1) val LEFT = Movement(-1, 0) val RIGHT = Movement(1, 0) } fun plus(that: Movement): Movement = Movement(this.dx + that.dx, this.dy + that.dy) } fun Point.move(movement: Movement): Point = Point(this).apply { translate(movement.dx, movement.dy) } fun BufferedImage.getColor(at: Point): Color = Color(this.getRGB(at.x, at.y)) fun BufferedImage.getRGB(at: Point): Int = this.getRGB(at.x, at.y) fun BufferedImage.moveFrom(from: Point, movement: Movement, predicate: (RBG) -> Boolean): Point { val current = Point(from) do current.translate(movement.dx, movement.dy) while (current in this && predicate(this.getRGB(current))) return current } operator fun BufferedImage.contains(point: Point): Boolean = 0 <= point.x && point.x < this.width && 0 <= point.y && point.y < this.height
gpl-2.0
5bc2d34b072e7f1e247c7332805084ba
29.88664
103
0.490561
4.263835
false
false
false
false
marverenic/Paper
app/src/main/java/com/marverenic/reader/model/Content.kt
1
1193
package com.marverenic.reader.model import android.os.Parcel import android.os.Parcelable private val HTML_TAG_REGEX = Regex("""<[^>]*>""") data class Content(val content: String) : Parcelable { @Transient private var plaintextContent: String? = null @Transient private var summary: String? = null constructor(parcel: Parcel) : this(parcel.readString()) fun asPlaintext(): String { if (plaintextContent == null) { plaintextContent = content.replace(HTML_TAG_REGEX, "").trim() } return plaintextContent!! } fun summary(): String { if (summary == null) { summary = asPlaintext().substringBefore("\n") } return summary!! } override fun writeToParcel(parcel: Parcel, flags: Int) { parcel.apply { writeString(content) } } override fun describeContents() = 0 companion object CREATOR : Parcelable.Creator<Content> { override fun createFromParcel(parcel: Parcel): Content { return Content(parcel) } override fun newArray(size: Int): Array<Content?> { return arrayOfNulls(size) } } }
apache-2.0
9dbce9eff739fe1d52493e7ea2785cec
23.367347
73
0.610226
4.678431
false
false
false
false
android/permissions-samples
RuntimePermissionsBasicKotlin/Application/src/main/java/com/example/android/basicpermissions/MainActivity.kt
1
5651
/* * Copyright 2017 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.android.basicpermissions import android.Manifest import android.content.Intent import android.content.pm.PackageManager import android.os.Bundle import android.view.View import android.widget.Button import androidx.appcompat.app.AppCompatActivity import androidx.core.app.ActivityCompat import com.example.android.basicpermissions.camera.CameraPreviewActivity import com.example.android.basicpermissions.util.checkSelfPermissionCompat import com.example.android.basicpermissions.util.requestPermissionsCompat import com.example.android.basicpermissions.util.shouldShowRequestPermissionRationaleCompat import com.example.android.basicpermissions.util.showSnackbar import com.google.android.material.snackbar.Snackbar const val PERMISSION_REQUEST_CAMERA = 0 /** * Launcher Activity that demonstrates the use of runtime permissions for Android M. * This Activity requests permissions to access the camera * ([android.Manifest.permission.CAMERA]) * when the 'Show Camera Preview' button is clicked to start [CameraPreviewActivity] once * the permission has been granted. * * <p>First, the status of the Camera permission is checked using [ActivityCompat.checkSelfPermission] * If it has not been granted ([PackageManager.PERMISSION_GRANTED]), it is requested by * calling [ActivityCompat.requestPermissions]. The result of the request is * returned to the * [android.support.v4.app.ActivityCompat.OnRequestPermissionsResultCallback], which starts * if the permission has been granted. * * <p>Note that there is no need to check the API level, the support library * already takes care of this. Similar helper methods for permissions are also available in * ([ActivityCompat], * [android.support.v4.content.ContextCompat] and [android.support.v4.app.Fragment]). */ class MainActivity : AppCompatActivity(), ActivityCompat.OnRequestPermissionsResultCallback { private lateinit var layout: View override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) layout = findViewById(R.id.main_layout) // Register a listener for the 'Show Camera Preview' button. findViewById<Button>(R.id.button_open_camera).setOnClickListener { showCameraPreview() } } override fun onRequestPermissionsResult( requestCode: Int, permissions: Array<String>, grantResults: IntArray ) { if (requestCode == PERMISSION_REQUEST_CAMERA) { // Request for camera permission. if (grantResults.size == 1 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { // Permission has been granted. Start camera preview Activity. layout.showSnackbar(R.string.camera_permission_granted, Snackbar.LENGTH_SHORT) startCamera() } else { // Permission request was denied. layout.showSnackbar(R.string.camera_permission_denied, Snackbar.LENGTH_SHORT) } } } private fun showCameraPreview() { // Check if the Camera permission has been granted if (checkSelfPermissionCompat(Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED) { // Permission is already available, start camera preview layout.showSnackbar(R.string.camera_permission_available, Snackbar.LENGTH_SHORT) startCamera() } else { // Permission is missing and must be requested. requestCameraPermission() } } /** * Requests the [android.Manifest.permission.CAMERA] permission. * If an additional rationale should be displayed, the user has to launch the request from * a SnackBar that includes additional information. */ private fun requestCameraPermission() { // Permission has not been granted and must be requested. if (shouldShowRequestPermissionRationaleCompat(Manifest.permission.CAMERA)) { // Provide an additional rationale to the user if the permission was not granted // and the user would benefit from additional context for the use of the permission. // Display a SnackBar with a button to request the missing permission. layout.showSnackbar(R.string.camera_access_required, Snackbar.LENGTH_INDEFINITE, R.string.ok) { requestPermissionsCompat(arrayOf(Manifest.permission.CAMERA), PERMISSION_REQUEST_CAMERA) } } else { layout.showSnackbar(R.string.camera_permission_not_available, Snackbar.LENGTH_SHORT) // Request the permission. The result will be received in onRequestPermissionResult(). requestPermissionsCompat(arrayOf(Manifest.permission.CAMERA), PERMISSION_REQUEST_CAMERA) } } private fun startCamera() { val intent = Intent(this, CameraPreviewActivity::class.java) startActivity(intent) } }
apache-2.0
677d43189f505c5fddfdfde139f82778
43.148438
102
0.716333
4.957018
false
false
false
false
intrigus/jtransc
jtransc-main/test/big/BigTest.kt
1
7323
package big import android.AndroidArgsTest import com.jtransc.annotation.JTranscKeepConstructors import com.jtransc.io.JTranscConsole import com.jtransc.util.JTranscStrings import issues.Issue100Double import issues.Issue94Enum import issues.issue130.Issue130 import issues.issue146.Issue146 import javatest.* import javatest.lang.* import javatest.misc.BenchmarkTest import javatest.misc.MiscTest import javatest.sort.CharCharMapTest import javatest.sort.ComparableTimSortTest import javatest.utils.Base64Test import javatest.utils.CopyTest import javatest.utils.DateTest import jtransc.WrappedTest import jtransc.bug.* import jtransc.java8.Java8Test import jtransc.jtransc.FastMemoryTest import jtransc.jtransc.SimdTest import jtransc.rt.test.* import java.io.BufferedReader import java.io.ByteArrayInputStream import java.io.InputStreamReader import java.text.NumberFormat import java.util.* object BigTest { @Throws(Throwable::class) @JvmStatic fun main(args: Array<String>) { //Thread.sleep(5000L) //KotlinPropertiesTest.main(args) JTranscConsole.log("BigTest:") // Misc tests JTranscConsole.log("sleep[1]") Thread.sleep(1L) JTranscConsole.log("/sleep[1]") StringsTest.main(args) PropertiesTest.main(args) BasicTypesTest.main(args) SystemTest.main(args) CopyTest.main(args) AtomicTest.main(args) FastMemoryTest.main(args) FastMemoryTest.main(args) MultidimensionalArrayTest.main(args) //KotlinCollections.main(args) //KotlinInheritanceTest.main(args) SimdTest.main(args) MiscTest.main(args) BenchmarkTest.main(args) // Suite tests JTranscBugWithStaticInits.main(args) JTranscCollectionsTest.main(args) JTranscCloneTest.main(args) StringBuilderTest.main(args) JTranscStackTraceTest.main(args) JTranscReflectionTest.main(args) JTranscNioTest.main(args) JTranscArithmeticTest.main(args) MathTest.main(args) DateTest.main(args) AtomicTest.main(args) JTranscBug12Test.main(args) //JTranscBug12Test2Kotlin.main(args) JTranscBug14Test.main(args) JTranscBugArrayGetClass.main(args) JTranscBugArrayDynamicInstantiate.main(args) JTranscBugAbstractInheritance1.main(args) JTranscBugAbstractInheritance2.main(args) JTranscBug41Test.main(args) JTranscBugClassRefTest.main(args) JTranscBugLongNotInitialized.main(args) JTranscBugClInitConflictInAsm.main(args) JTranscBugInnerMethodsWithSameName.main(args) JTranscBugCompareInterfaceAndObject.main(args) JTranscBugInterfaceWithToString.main(args) JTranscRegression1Test.main(args) JTranscRegression2Test.main(args) JTranscRegression3Test.main(args) ProxyTest.main(args) WrappedTest.main(args) // Android AndroidArgsTest.main(args) //AndroidTest8019.main(args) // Kotlin //StrangeNamesTest.main(args) ComparableTimSortTest.main(args) // Java8 tests //JTranscClinitNotStatic.main(args) //DefaultMethodsTest.main(args) Java8Test.main(args) // Misc Base64Test.main(args) CharCharMapTest.main(args) // Regex javatest.utils.regex.RegexTest.main(args) servicesTest() keepConstructorsTest() val `is` = InputStreamReader(ByteArrayInputStream(byteArrayOf('A'.toByte(), 'B'.toByte(), 0xC3.toByte(), 0xA1.toByte()))) println("readLine:" + TestStringTools.escape(BufferedReader(`is`).readLine())) // Hello World functionality! HelloWorldTest.main(args) NumberFormatTest.main(args) //NumberFormatTest2.main(args); KotlinStaticInitOrderTest.main(args) MemberCollisionsTest.main(args) ConcurrentCollectionsTest.main(args) MessageDigestTest.main(args) Issue94Enum.main(args) Issue100Double.main(args) CaseInsensitiveOrder.main(args) Issue130.main(args) JTranscBug127.main(args) System.out.println(String.format("%d%%", 100)) } private fun servicesTest() { val load = ServiceLoader.load(testservice.ITestService::class.java) println("Services:") for (testService in load) { println(testService.test()) } println("/Services:") } private fun keepConstructorsTest() { println("keepConstructorsTest:") println(Demo::class.java.declaredConstructors.size) } } object NumberFormatTest { @JvmStatic fun main(args: Array<String>) { val ints = intArrayOf(0, 1, 12, 123, 1234, 12345, 123456, 1234567, 12345678) val locales = arrayOf(Locale.ENGLISH, Locale.UK, Locale.US, Locale.FRENCH, Locale.forLanguageTag("es"), Locale.forLanguageTag("ja")) for (i in ints) { for (locale in locales) { val s = NumberFormat.getIntegerInstance(locale).format(i.toLong()) println(locale.language + ":" + TestStringTools.escape(s)) if (s.length == 5) { println(s[1].toInt()) } } } val strings = arrayOf("", "1", "12", "123", "1234", "12345", "123456", "1234567") for (s in strings) println(JTranscStrings.join(JTranscStrings.splitInChunks(s, 3), "-")) for (s in strings) println(JTranscStrings.join(JTranscStrings.splitInChunksRightToLeft(s, 3), "-")) /* //LinkedHashMap<String, Integer> stringIntegerLinkedHashMap = new LinkedHashMap<>(); //stringIntegerLinkedHashMap.put("a", 10); //stringIntegerLinkedHashMap.put("b", 20); //stringIntegerLinkedHashMap.put("a", 11); //System.out.println("Hello World! : " + stringIntegerLinkedHashMap.get("a")); System.out.println("Hello World!"); try { Thread.sleep(10000L); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("Hello World!"); */ //System.out.println(new File("c:/temp/2.bin").length()); //JTranscConsole.log("Hello World!"); //ProgramReflection.dynamicInvoke(0, null, null); //System.out.println("HelloWorldTest.class.field[10]: " + HelloWorldTest.class.getDeclaredField("a").get(null)); //HelloWorldTest.class.getDeclaredField("a").set(null, 20); //System.out.println("HelloWorldTest.class.field[20]: " + HelloWorldTest.class.getDeclaredField("a").get(null)); //System.out.println("HelloWorldTest.class.method: " + HelloWorldTest.class.getDeclaredMethod("hello").invoke(null)); // //System.out.println(HelloWorldTest.class.getConstructor().newInstance().demo); //System.out.println(HelloWorldTest.class.getConstructor().newInstance()); //System.out.println("####"); } } object NumberFormatTest2 { @JvmStatic fun main(args: Array<String>) { val numbers = listOf( "", "\t", "\n", " ", "1", "10", "-10", "+10", "10.3", "a10", "+a10", "10a", "10e", "10e10", "1.12345", "5e-10", "5.3e-10" ) //println("NumberFormat2(${JTranscSystem.getRuntimeName()}):") println("NumberFormat2:") for (num in numbers) { println(" - $num : int=${checkInt(num)} : double=${checkDouble(num)}") } } fun checkInt(str: String) = try { java.lang.Integer.parseInt(str) } catch (e: NumberFormatException) { -1 } fun checkDouble(str: String) = try { java.lang.Double.parseDouble(str) true } catch (e: NumberFormatException) { //-1.0 false } } private class CaseInsensitiveOrder { companion object { @JvmStatic fun main(args: Array<String>) { val tm = TreeMap<String, String>(String.CASE_INSENSITIVE_ORDER) tm["Ab"] = "hello" println(tm["ab"]) println(tm["aB"]) println(tm["Ab"]) println(tm["AB"]) } } } @JTranscKeepConstructors annotation class KeepConstructorsAnnotation() @KeepConstructorsAnnotation class Demo(val a: Int, val s: String)
apache-2.0
5b99e865648325098c46320754edad89
26.125926
134
0.73194
3.264824
false
true
false
false
chiken88/passnotes
app/src/main/kotlin/com/ivanovsky/passnotes/presentation/storagelist/StorageListViewModel.kt
1
9433
package com.ivanovsky.passnotes.presentation.storagelist import android.net.Uri import androidx.lifecycle.MutableLiveData import androidx.lifecycle.viewModelScope import com.github.terrakok.cicerone.Router import com.ivanovsky.passnotes.R import com.ivanovsky.passnotes.data.entity.FSAuthority import com.ivanovsky.passnotes.data.entity.FileDescriptor import com.ivanovsky.passnotes.data.entity.OperationResult import com.ivanovsky.passnotes.data.repository.file.AuthType import com.ivanovsky.passnotes.data.repository.file.FileSystemResolver import com.ivanovsky.passnotes.domain.ResourceProvider import com.ivanovsky.passnotes.domain.entity.StorageOption import com.ivanovsky.passnotes.domain.entity.StorageOptionType import com.ivanovsky.passnotes.domain.entity.StorageOptionType.DROPBOX import com.ivanovsky.passnotes.domain.entity.StorageOptionType.EXTERNAL_STORAGE import com.ivanovsky.passnotes.domain.entity.StorageOptionType.PRIVATE_STORAGE import com.ivanovsky.passnotes.domain.entity.StorageOptionType.WEBDAV import com.ivanovsky.passnotes.domain.interactor.ErrorInteractor import com.ivanovsky.passnotes.domain.interactor.storagelist.StorageListInteractor import com.ivanovsky.passnotes.presentation.Screens.FilePickerScreen import com.ivanovsky.passnotes.presentation.Screens.ServerLoginScreen import com.ivanovsky.passnotes.presentation.Screens.StorageListScreen import com.ivanovsky.passnotes.presentation.core.BaseScreenViewModel import com.ivanovsky.passnotes.presentation.core.DefaultScreenStateHandler import com.ivanovsky.passnotes.presentation.core.ScreenState import com.ivanovsky.passnotes.presentation.core.ViewModelTypes import com.ivanovsky.passnotes.presentation.core.event.SingleLiveEvent import com.ivanovsky.passnotes.presentation.core.viewmodel.SingleTextCellViewModel import com.ivanovsky.passnotes.presentation.filepicker.model.FilePickerArgs import com.ivanovsky.passnotes.presentation.server_login.ServerLoginArgs import com.ivanovsky.passnotes.presentation.storagelist.converter.toCellModels import com.ivanovsky.passnotes.presentation.storagelist.converter.toFilePickerAction import com.ivanovsky.passnotes.util.StringUtils.EMPTY import kotlinx.coroutines.launch class StorageListViewModel( private val interactor: StorageListInteractor, private val errorInteractor: ErrorInteractor, private val fileSystemResolver: FileSystemResolver, private val resourceProvider: ResourceProvider, private val router: Router ) : BaseScreenViewModel() { val viewTypes = ViewModelTypes() .add(SingleTextCellViewModel::class, R.layout.cell_single_text) val screenStateHandler = DefaultScreenStateHandler() val screenState = MutableLiveData(ScreenState.notInitialized()) val showAuthActivityEvent = SingleLiveEvent<FSAuthority>() val showSystemFilePickerEvent = SingleLiveEvent<Unit>() private val cellFactory = StorageListCellFactory() private var storageOptions: List<StorageOption>? = null private var requestedAction: Action? = null private var isExternalAuthActivityLaunched = false private var selectedOption: StorageOption? = null init { subscribeToEvents() } fun loadData(requestedAction: Action) { this.requestedAction = requestedAction screenState.value = ScreenState.loading() viewModelScope.launch { val options = interactor.getStorageOptions(requestedAction) val cellModels = options.toCellModels() setCellElements(cellFactory.createCellViewModels(cellModels, eventProvider)) storageOptions = options screenState.value = ScreenState.data() } } fun onScreenStart() { val selectedOption = selectedOption ?: return if (isExternalAuthActivityLaunched) { isExternalAuthActivityLaunched = false val fsAuthority = selectedOption.root.fsAuthority val provider = fileSystemResolver.resolveProvider(fsAuthority) if (provider.authenticator.isAuthenticationRequired()) { val errorMessage = resourceProvider.getString(R.string.authentication_failed) screenState.value = ScreenState.dataWithError(errorMessage) } else { viewModelScope.launch { val fsRoot = interactor.getRemoteFileSystemRoot(fsAuthority) onRemoteRootLoaded(fsRoot) } } } } fun onExternalStorageFileSelected(uri: Uri) { val fsAuthority = selectedOption?.root?.fsAuthority ?: return val path = uri.toString() viewModelScope.launch { val getFileResult = interactor.getFileByPath(path, fsAuthority) if (getFileResult.isSucceededOrDeferred) { val file = getFileResult.obj router.sendResult(StorageListScreen.RESULT_KEY, file) router.exit() } else { val message = errorInteractor.processAndGetMessage(getFileResult.error) screenState.value = ScreenState.dataWithError(message) } } } fun onExternalStorageFileSelectionCanceled() { screenState.value = ScreenState.data() } fun navigateBack() = router.exit() private fun onInternalAuthSuccess(fsAuthority: FSAuthority) { viewModelScope.launch { val remoteFsRoot = interactor.getRemoteFileSystemRoot(fsAuthority) onRemoteRootLoaded(remoteFsRoot) } } private fun onInternalAuthFailed() { screenState.value = ScreenState.data() } private fun navigateToFilePicker(args: FilePickerArgs) { router.setResultListener(FilePickerScreen.RESULT_KEY) { file -> if (file is FileDescriptor) { onFilePickedByPicker(file) } } router.navigateTo(FilePickerScreen(args)) } private fun onFilePickedByPicker(file: FileDescriptor) { router.sendResult(StorageListScreen.RESULT_KEY, file) router.exit() } private fun subscribeToEvents() { eventProvider.subscribe(this) { event -> if (event.containsKey(SingleTextCellViewModel.CLICK_EVENT)) { val id = event.getString(SingleTextCellViewModel.CLICK_EVENT) ?: EMPTY onStorageOptionClicked(StorageOptionType.valueOf(id)) } } } private fun onStorageOptionClicked(type: StorageOptionType) { val selectedOption = storageOptions?.find { type == it.type } ?: return this.selectedOption = selectedOption when (selectedOption.type) { PRIVATE_STORAGE -> onPrivateStorageSelected(selectedOption.root) EXTERNAL_STORAGE -> onExternalStorageSelected() DROPBOX, WEBDAV -> onRemoteFileStorageSelected(selectedOption.root) } } private fun onPrivateStorageSelected(root: FileDescriptor) { val action = requestedAction ?: return if (action == Action.PICK_FILE) { navigateToFilePicker( FilePickerArgs( action.toFilePickerAction(), root, false ) ) } else if (action == Action.PICK_STORAGE) { router.sendResult(StorageListScreen.RESULT_KEY, root) router.exit() } } private fun onExternalStorageSelected() { screenState.value = ScreenState.loading() showSystemFilePickerEvent.call() } private fun onRemoteFileStorageSelected(root: FileDescriptor) { val provider = fileSystemResolver.resolveProvider(root.fsAuthority) screenState.value = ScreenState.loading() val authenticator = provider.authenticator if (authenticator.isAuthenticationRequired()) { val authType = authenticator.getAuthType() if (authType == AuthType.CREDENTIALS) { router.setResultListener(ServerLoginScreen.RESULT_KEY) { fsAuthority -> if (fsAuthority is FSAuthority) { onInternalAuthSuccess(fsAuthority) } else { onInternalAuthFailed() } } router.navigateTo( ServerLoginScreen( ServerLoginArgs(root.fsAuthority) ) ) } else if (authType == AuthType.EXTERNAL) { isExternalAuthActivityLaunched = true showAuthActivityEvent.call(root.fsAuthority) } } else { viewModelScope.launch { val remoteFsRoot = interactor.getRemoteFileSystemRoot(root.fsAuthority) onRemoteRootLoaded(remoteFsRoot) } } } private fun onRemoteRootLoaded(result: OperationResult<FileDescriptor>) { val action = requestedAction ?: return if (result.isSucceededOrDeferred) { val rootFile = result.obj navigateToFilePicker( FilePickerArgs( action.toFilePickerAction(), rootFile, true ) ) } else { val message = errorInteractor.processAndGetMessage(result.error) screenState.value = ScreenState.error(message) } } }
gpl-2.0
e7bfbd5e740df0b0426c7b82fbcc35af
37.040323
93
0.681225
5.191524
false
false
false
false
seventhroot/elysium
bukkit/rpk-stores-bukkit/src/main/kotlin/com/rpkit/store/bukkit/storeitem/RPKStoreItemProviderImpl.kt
1
3863
/* * Copyright 2018 Ross Binden * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.rpkit.store.bukkit.storeitem import com.rpkit.core.bukkit.plugin.RPKBukkitPlugin import com.rpkit.store.bukkit.RPKStoresBukkit import com.rpkit.store.bukkit.database.table.RPKConsumableStoreItemTable import com.rpkit.store.bukkit.database.table.RPKPermanentStoreItemTable import com.rpkit.store.bukkit.database.table.RPKStoreItemTable import com.rpkit.store.bukkit.database.table.RPKTimedStoreItemTable import com.rpkit.store.bukkit.event.storeitem.RPKBukkitStoreItemCreateEvent import com.rpkit.store.bukkit.event.storeitem.RPKBukkitStoreItemDeleteEvent import com.rpkit.store.bukkit.event.storeitem.RPKBukkitStoreItemUpdateEvent class RPKStoreItemProviderImpl(private val plugin: RPKStoresBukkit): RPKStoreItemProvider { override fun getStoreItem(plugin: RPKBukkitPlugin, identifier: String): RPKStoreItem? { return this.plugin.core.database.getTable(RPKStoreItemTable::class).get(plugin, identifier) } override fun getStoreItem(id: Int): RPKStoreItem? { return plugin.core.database.getTable(RPKStoreItemTable::class)[id] } override fun getStoreItems(): List<RPKStoreItem> { return plugin.core.database.getTable(RPKStoreItemTable::class).getAll() } override fun addStoreItem(storeItem: RPKStoreItem) { val event = RPKBukkitStoreItemCreateEvent(storeItem) plugin.server.pluginManager.callEvent(event) if (event.isCancelled) return val eventStoreItem = event.storeItem when (eventStoreItem) { is RPKConsumableStoreItem -> plugin.core.database.getTable(RPKConsumableStoreItemTable::class).insert(eventStoreItem) is RPKPermanentStoreItem -> plugin.core.database.getTable(RPKPermanentStoreItemTable::class).insert(eventStoreItem) is RPKTimedStoreItem -> plugin.core.database.getTable(RPKTimedStoreItemTable::class).insert(eventStoreItem) } } override fun updateStoreItem(storeItem: RPKStoreItem) { val event = RPKBukkitStoreItemUpdateEvent(storeItem) plugin.server.pluginManager.callEvent(event) if (event.isCancelled) return val eventStoreItem = event.storeItem when (eventStoreItem) { is RPKConsumableStoreItem -> plugin.core.database.getTable(RPKConsumableStoreItemTable::class).update(eventStoreItem) is RPKPermanentStoreItem -> plugin.core.database.getTable(RPKPermanentStoreItemTable::class).update(eventStoreItem) is RPKTimedStoreItem -> plugin.core.database.getTable(RPKTimedStoreItemTable::class).update(eventStoreItem) } } override fun removeStoreItem(storeItem: RPKStoreItem) { val event = RPKBukkitStoreItemDeleteEvent(storeItem) plugin.server.pluginManager.callEvent(event) if (event.isCancelled) return val eventStoreItem = event.storeItem when (eventStoreItem) { is RPKConsumableStoreItem -> plugin.core.database.getTable(RPKConsumableStoreItemTable::class).delete(eventStoreItem) is RPKPermanentStoreItem -> plugin.core.database.getTable(RPKPermanentStoreItemTable::class).delete(eventStoreItem) is RPKTimedStoreItem -> plugin.core.database.getTable(RPKTimedStoreItemTable::class).delete(eventStoreItem) } } }
apache-2.0
58b305066b4623b14d2538e448eaadb7
47.911392
129
0.757442
4.902284
false
false
false
false
Goyatuzo/LurkerBot
entry/discord-bot/src/main/kotlin/gameTime/GameTimeTracker.kt
1
2558
package com.lurkerbot.gameTime import com.lurkerbot.core.gameTime.TimeRecord import com.lurkerbot.core.gameTime.TimerService import com.lurkerbot.discordUser.UserTracker import dev.kord.common.entity.ActivityType import dev.kord.core.event.gateway.ReadyEvent import dev.kord.core.event.user.PresenceUpdateEvent import kotlinx.coroutines.flow.collectIndexed import mu.KotlinLogging class GameTimeTracker( private val timerService: TimerService, private val userTracker: UserTracker ) { private val logger = KotlinLogging.logger {} suspend fun initialize(readyEvent: ReadyEvent) { val guilds = readyEvent.getGuilds() guilds.collectIndexed { _, guild -> guild.members.collectIndexed { _, member -> if (userTracker.userIsBeingTracked(member.id.toString())) { val gameActivity = member.getPresenceOrNull()?.activities?.firstOrNull { it.type == ActivityType.Game } if (gameActivity != null) { val toRecord = TimeRecord.fromActivity(member.id.toString(), gameActivity) timerService.beginLogging( member.id.toString(), guild.id.toString(), toRecord ) } } } } } suspend fun processEvent(event: PresenceUpdateEvent) { val user = event.getUser() if (!userTracker.userIsBeingTracked(user.id.value.toString())) { return } if (!user.isBot) { val currentGame = event.presence.activities.firstOrNull { it.type == ActivityType.Game } val oldGame = event.old?.activities?.firstOrNull { it.type == ActivityType.Game } if (currentGame == null || !(currentGame.sameActivityAs(oldGame))) { timerService.endLogging(user.id.value.toString(), event.guildId.value.toString()) } if (currentGame != null) { val toRecord = TimeRecord.fromActivity(user.id.value.toString(), currentGame) timerService.beginLogging( user.id.value.toString(), event.guildId.value.toString(), toRecord ) } if (event.presence.activities.size > 1) logger.info { "Multiple activities: ${event.presence.activities}" } } } }
apache-2.0
9237461d766ab03b8daeb695f9b0d661
34.527778
100
0.571931
4.96699
false
false
false
false
Magneticraft-Team/ModelLoader
src/main/kotlin/com/cout970/modelloader/animation/AnimatedModel.kt
1
8476
package com.cout970.modelloader.animation import com.cout970.modelloader.* import com.cout970.modelloader.api.IRenderCache import com.cout970.modelloader.api.TRSTransformation import com.mojang.blaze3d.platform.GlStateManager import javax.vecmath.Quat4d import javax.vecmath.Vector3d import javax.vecmath.Vector4d /** * A node in the animated model. * The more nodes a model has the more expensive it is to render the model */ data class AnimatedNode( val index: Int, var transform: TRSTransformation, val children: List<AnimatedNode>, val cache: IRenderCache ) { fun close() { children.forEach(AnimatedNode::close) cache.close() } fun asyncClose(runner: (Runnable) -> Unit) { children.forEach { it.asyncClose(runner) } cache.asyncClose(runner) } } /** * A channel of the animation * Stores changes to a property of the model, the value of the property is calculated using the keyframes * - index is the id of the node to modify * - type is the property to modify * - keyframes have the values to put in the property and the time where to put them */ data class AnimationChannel( val index: Int, val type: AnimationChannelType, val keyframes: List<AnimationKeyframe<Any>> ) /** * Type of an AnimationChannel */ enum class AnimationChannelType { TRANSLATION, ROTATION, SCALE } /** * A single keyframe of the animation, * Stores the value of a property of the model in a concrete animation time */ data class AnimationKeyframe<T>( val time: Float, val value: T ) /** * An animated model */ class AnimatedModel(val rootNodes: List<AnimatedNode>, val channels: List<AnimationChannel>) { /** * Total animation time in seconds */ val length: Float by lazy { channels.mapNotNull { channel -> channel.keyframes.map { it.time }.max() }.max() ?: 1f } init { for (channel in channels) { val value = channel.keyframes.first().value when (channel.type) { AnimationChannelType.TRANSLATION -> { check(value is Vector3d) { "Error: translate animation channel must use Vector3d for values, ${value::class.java} found" } } AnimationChannelType.ROTATION -> { check(value is Vector4d) { "Error: rotate animation channel must use Vector4d for values, ${value::class.java} found" } } AnimationChannelType.SCALE -> { check(value is Vector3d) { "Error: scale animation channel must use Vector3d for values, ${value::class.java} found" } } } } } /** * Renders the model with an specified animation time * Time is in seconds, to use ticks just divide by 20 */ fun render(time: Float) { val localTime = time % length rootNodes.forEach { renderNode(it, localTime) } } /** * Same but with Double as input, avoids hidden casts at call location */ fun render(time: Double) { render(time.toFloat()) } /** * Renders a single node tree of the model */ fun renderNode(node: AnimatedNode, time: Float) { GlStateManager.pushMatrix() getTransform(node, time).glMultiply() node.cache.render() node.children.forEach { renderNode(it, time) } GlStateManager.popMatrix() } /** * Gets the acumulated transformations to a node * * This is usefull to get the in-world position of a part of the model, * for example, to render an item in the arm of an inserter */ fun getNodeTransform(id: Int, time: Float): TRSTransformation { val path = findNode(id, rootNodes) ?: return TRSTransformation.IDENTITY var transformation = TRSTransformation.IDENTITY for (node in path) { transformation = getTransform(node, time) + transformation } return transformation } private fun findNode(id: Int, options: List<AnimatedNode>): List<AnimatedNode>? { for (option in options) { if (option.index == id) return listOf(option) val childPath = findNode(id, option.children) if (childPath != null) { return listOf(option) + childPath } } return null } /** * Renders the model without texture with an specified animation time * Time is in seconds, to use ticks just divide by 20 */ fun renderUntextured(time: Double) { val localTime = (time % length.toDouble()).toFloat() rootNodes.forEach { renderUntexturedNode(it, localTime) } } /** * Renders a single node tree of the model without textures */ fun renderUntexturedNode(node: AnimatedNode, time: Float) { GlStateManager.pushMatrix() getTransform(node, time).glMultiply() node.cache.renderUntextured() node.children.forEach { renderUntexturedNode(it, time) } GlStateManager.popMatrix() } /** * Gets the Transformation of a node given an animation time */ fun getTransform(node: AnimatedNode, time: Float): TRSTransformation { val channels = channels.filter { it.index == node.index } if (channels.isEmpty()) return node.transform val translation = channels .filter { it.type == AnimationChannelType.TRANSLATION } .fold<AnimationChannel, Vector3d?>(null) { acc, channel -> @Suppress("UNCHECKED_CAST") val keyframes = channel.keyframes as List<AnimationKeyframe<Vector3d>> val (prev, next) = getPrevAndNext(time, keyframes) val new = interpolateVec3(time, prev, next) if (acc == null) new else acc + new } ?: node.transform.translation val rotation = channels .filter { it.type == AnimationChannelType.ROTATION } .fold<AnimationChannel, Quat4d?>(null) { acc, channel -> @Suppress("UNCHECKED_CAST") val keyframes = channel.keyframes as List<AnimationKeyframe<Vector4d>> val (prev, next) = getPrevAndNext(time, keyframes) val new = interpolateQuat(time, prev, next) if (acc == null) new else acc * new } ?: node.transform.rotation val scale = channels .filter { it.type == AnimationChannelType.SCALE } .fold<AnimationChannel, Vector3d?>(null) { acc, channel -> @Suppress("UNCHECKED_CAST") val keyframes = channel.keyframes as List<AnimationKeyframe<Vector3d>> val (prev, next) = getPrevAndNext(time, keyframes) val new = interpolateVec3(time, prev, next) if (acc == null) new else acc + new } ?: node.transform.scale return TRSTransformation(translation, rotation, scale) } /** * Interpolate animation keyframes with Vectors */ fun interpolateVec3(time: Float, prev: AnimationKeyframe<Vector3d>, next: AnimationKeyframe<Vector3d>): Vector3d { if (next.time == prev.time) return next.value val size = next.time - prev.time val step = (time - prev.time) / size return (prev.value).interpolated(next.value, step.toDouble()) } /** * Interpolate animation keyframes with Quaternions */ fun interpolateQuat(time: Float, prev: AnimationKeyframe<Vector4d>, next: AnimationKeyframe<Vector4d>): Quat4d { if (next.time == prev.time) return next.value.asQuaternion() val size = next.time - prev.time val step = (time - prev.time) / size return prev.value.asQuaternion().interpolated(next.value.asQuaternion(), step.toDouble()) } /** * Returns a pair of keyframes to interpolate */ fun <T> getPrevAndNext(time: Float, keyframes: List<AnimationKeyframe<T>>): Pair<AnimationKeyframe<T>, AnimationKeyframe<T>> { val next = keyframes.firstOrNull { it.time > time } ?: keyframes.first() val prev = keyframes.lastOrNull { it.time <= time } ?: keyframes.last() return prev to next } /** * Frees the GPU memory used by the model */ fun close() { rootNodes.forEach { it.close() } } fun asyncClose(runner: (Runnable) -> Unit) { rootNodes.forEach { it.asyncClose(runner) } } }
gpl-2.0
434a0e42ffe94391559546b81af2467e
32.113281
142
0.621756
4.298174
false
false
false
false
EMResearch/EvoMaster
core/src/main/kotlin/org/evomaster/core/search/impact/impactinfocollection/value/collection/ArrayGeneImpact.kt
1
2694
package org.evomaster.core.search.impact.impactinfocollection.value.collection import org.evomaster.core.search.gene.collection.ArrayGene import org.evomaster.core.search.gene.Gene import org.evomaster.core.search.impact.impactinfocollection.* import org.evomaster.core.search.impact.impactinfocollection.value.numeric.IntegerGeneImpact /** * created by manzh on 2019-09-09 * * TODO need to further extend for elements */ class ArrayGeneImpact (sharedImpactInfo: SharedImpactInfo, specificImpactInfo: SpecificImpactInfo, val sizeImpact : IntegerGeneImpact = IntegerGeneImpact("size") ) : CollectionImpact, GeneImpact(sharedImpactInfo, specificImpactInfo){ constructor( id : String ) : this(SharedImpactInfo(id), SpecificImpactInfo()) override fun getSizeImpact(): Impact = sizeImpact override fun copy(): ArrayGeneImpact { return ArrayGeneImpact( shared.copy(), specific.copy(), sizeImpact = sizeImpact.copy()) } override fun clone(): ArrayGeneImpact { return ArrayGeneImpact( shared.clone(), specific.clone(), sizeImpact.clone() ) } override fun countImpactWithMutatedGeneWithContext(gc: MutatedGeneWithContext, noImpactTargets:Set<Int>, impactTargets: Set<Int>, improvedTargets: Set<Int>, onlyManipulation: Boolean) { countImpactAndPerformance(noImpactTargets = noImpactTargets, impactTargets = impactTargets, improvedTargets = improvedTargets, onlyManipulation = onlyManipulation, num = gc.numOfMutatedGene) if (gc.previous == null && impactTargets.isNotEmpty()) return if (gc.current !is ArrayGene<*>) throw IllegalStateException("gc.current (${gc.current::class.java.simpleName}) should be ArrayGene") if ((gc.previous != null && gc.previous !is ArrayGene<*>)) throw IllegalStateException("gc.previous (${gc.previous::class.java.simpleName}) should be ArrayGene") if (gc.previous != null && (gc.previous as ArrayGene<*>).getViewOfElements().size != gc.current.getViewOfElements().size) sizeImpact.countImpactAndPerformance(noImpactTargets = noImpactTargets, impactTargets = impactTargets, improvedTargets = improvedTargets, onlyManipulation = onlyManipulation, num = 1) //TODO for elements } override fun validate(gene: Gene): Boolean = gene is ArrayGene<*> override fun flatViewInnerImpact(): Map<String, Impact> { return mutableMapOf("${getId()}-${sizeImpact.getId()}" to sizeImpact) } override fun innerImpacts(): List<Impact> { return listOf(sizeImpact) } }
lgpl-3.0
fc18d5ee7cffac4d681bedb0f6335717
42.467742
198
0.698961
5.092628
false
false
false
false
juanavelez/crabzilla
crabzilla-core/src/main/java/io/github/crabzilla/internal/CommandController.kt
1
2734
package io.github.crabzilla.internal import io.github.crabzilla.framework.* import io.vertx.core.Promise import org.slf4j.LoggerFactory import java.util.concurrent.atomic.AtomicReference class CommandController<E : Entity>(private val commandAware: EntityCommandAware<E>, private val snapshotRepo: SnapshotRepository<E>, private val uowJournal: UnitOfWorkJournal<E>) { companion object { internal val log = LoggerFactory.getLogger(CommandController::class.java) } fun handle(metadata: CommandMetadata, command: Command) : Promise<Pair<UnitOfWork, Long>> { val promise = Promise.promise<Pair<UnitOfWork, Long>>() if (log.isTraceEnabled) log.trace("received $metadata\n $command") val constraints = commandAware.validateCmd(command) if (constraints.isNotEmpty()) { log.error("Command is invalid: $constraints") promise.fail(constraints.toString()) return promise } val snapshotValue: AtomicReference<Snapshot<E>> = AtomicReference() val uowValue: AtomicReference<UnitOfWork> = AtomicReference() val uowIdValue: AtomicReference<Long> = AtomicReference() snapshotRepo.retrieve(metadata.entityId).future() .compose { snapshot -> if (log.isTraceEnabled) log.trace("got snapshot $snapshot") val cachedSnapshot = snapshot ?: Snapshot(commandAware.initialState, 0) snapshotValue.set(cachedSnapshot) val cmdHandler = commandAware.cmdHandlerFactory.invoke(metadata, command, cachedSnapshot) cmdHandler.handleCommand().future() } .compose { unitOfWork -> if (log.isTraceEnabled) log.trace("got unitOfWork $unitOfWork") // append to journal uowValue.set(unitOfWork) uowJournal.append(unitOfWork).future() } .compose { uowId -> if (log.isTraceEnabled) log.trace("got uowId $uowId") uowIdValue.set(uowId) // compute new snapshot if (log.isTraceEnabled) log.trace("computing new snapshot") val newInstance = uowValue.get().events.fold(snapshotValue.get().state) { state, event -> commandAware.applyEvent.invoke(event.second, state) } val newSnapshot = Snapshot(newInstance, uowValue.get().version) if (log.isTraceEnabled) log.trace("now will store snapshot $newSnapshot") snapshotRepo.upsert(metadata.entityId, newSnapshot).future() } .compose({ // set result val pair: Pair<UnitOfWork, Long> = Pair(uowValue.get(), uowIdValue.get()) if (log.isTraceEnabled) log.trace("command handling success: $pair") promise.complete(pair) }, promise.future()) return promise } }
apache-2.0
bc3ea5bd5c43e82c33232dab7671c829
35.453333
97
0.677396
4.325949
false
false
false
false
fobo66/BookcrossingMobile
app/src/main/java/com/bookcrossing/mobile/presenters/MainPresenter.kt
1
2499
/* * Copyright 2019 Andrey Mukamolov * * 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.bookcrossing.mobile.presenters import android.content.SharedPreferences import android.os.Bundle import com.bookcrossing.mobile.data.AuthRepository import com.bookcrossing.mobile.data.BooksReferencesRepository import com.bookcrossing.mobile.ui.main.MainView import com.bookcrossing.mobile.util.BookCoverResolver import com.bookcrossing.mobile.util.KEY_CONSENT_STATUS import com.bookcrossing.mobile.util.UNKNOWN_CONSENT_STATUS import com.google.ads.consent.ConsentStatus import com.google.ads.mediation.admob.AdMobAdapter import com.google.android.gms.ads.AdRequest import com.google.firebase.database.DatabaseReference import moxy.InjectViewState import javax.inject.Inject /** * Presenter for main screen */ @InjectViewState class MainPresenter @Inject constructor( private val preferences: SharedPreferences, private val booksRepository: BooksReferencesRepository, private val authRepository: AuthRepository, val bookCoverResolver: BookCoverResolver ) : BasePresenter<MainView>() { val books: DatabaseReference get() = booksRepository.books() val isAuthenticated: Boolean get() = authRepository.isAuthenticated override fun onFirstViewAttach() { unsubscribeOnDestroy(authRepository.onAuthenticated() .filter { it.currentUser != null } .subscribe { viewState.showReleaseBookButton() } ) } fun checkForConsent(adBuilder: AdRequest.Builder) { val consentStatus = loadConsentStatus() if (consentStatus == ConsentStatus.NON_PERSONALIZED) { val extras = Bundle() extras.putString("npa", "1") adBuilder.addNetworkExtrasBundle(AdMobAdapter::class.java, extras) } } private fun loadConsentStatus(): ConsentStatus { return ConsentStatus.valueOf( preferences.getString(KEY_CONSENT_STATUS, UNKNOWN_CONSENT_STATUS) ?: UNKNOWN_CONSENT_STATUS ) } }
apache-2.0
6c80b520d70c497c913be39faa395ca1
31.894737
97
0.758703
4.353659
false
false
false
false
Maxr1998/MaxLock
app/src/main/java/net/dinglisch/android/tasker/IntentServiceParallel.kt
1
3805
package com.joaomgcd.common.tasker import android.app.Service import android.content.Intent import android.os.Handler import android.os.Looper import android.util.Log import java.util.concurrent.Executors import java.util.concurrent.atomic.AtomicInteger private const val TAG = "IntentServiceParallel" /** * A drop-in replacement for IntentService that performs various tasks at the same time instead of one after the other * * @property name Name for the service. Will be used to name the threads created in this service. */ abstract class IntentServiceParallel(val name: String) : Service() { /** * Simply call [onStart] like IntentService does */ override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int { onStart(intent, startId) return Service.START_NOT_STICKY } override fun onBind(intent: Intent) = null protected abstract fun onHandleIntent(intent: Intent) /** * Use a handler on the main thread to post exceptions and stop the service when all tasks are done */ private val handler = Handler(Looper.getMainLooper()) /** * Keep count of how many tasks are active so that we can stop when they reach 0 */ private var jobsCount: AtomicInteger = AtomicInteger(0) /** * Keep track of the last startId sent to the service. Will be used to make sure we only stop the service if the last startId was actually the last startId that the service received. */ private var lastStartId: Int? = null /** * * The executor to run tasks in parallel threads * */ private val executor by lazy { Executors.newCachedThreadPool { runnable -> Thread(runnable, "IntentServiceParallel$name") } } /** * Main function of the class. Starts processing each new task in parallel with existing tasks. When all tasks are processed will stop itself. Will ignore null intents. */ override fun onStart(intent: Intent?, startId: Int) { if (intent == null) return //Count +1 so that we know how many tasks are running val currentCount = jobsCount.addAndGet(1) /** * store the startId so that we will always use [stopSelf] with the correct Id. * This is stored after incrementing the count so that if [stopSelf] runs before * the increment the service is not stopped because the last startId is not used as a parameter */ lastStartId = startId Log.v(TAG, "Started with $startId; Current job count is $currentCount.") executor.submit { try { //run task in parallel onHandleIntent(intent) } catch (throwable: RuntimeException) { //throw any exception in the main thread handler.post { throw throwable } } finally { handler.post { //decrement in the main thread to avoid concurrency issues if (jobsCount.decrementAndGet() > 0) return@post //stop only if lastStartId was the last startId that was posted stop(lastStartId) } } } } /** * Will stop the service if the provided startId is null or is the last one that was pushed to [onStart] * Although [startId] is nullable, in practice it should never be null when this function is called */ private fun stop(startId: Int?) { Log.v(TAG, "Stopping with $startId;") if (startId != null) { stopSelf(startId) } else { stopSelf() } } /** * Shutdown the executor when the sevice is destroyed */ override fun onDestroy() { super.onDestroy() executor.shutdown() } }
gpl-3.0
82ea3a3863783e057674131b55935da9
33.917431
186
0.638633
4.804293
false
false
false
false
elect86/modern-jogl-examples
src/main/kotlin/main/tut03/cpuPositionOffset.kt
2
3448
package main.tut03 import com.jogamp.newt.event.KeyEvent import com.jogamp.opengl.GL.* import com.jogamp.opengl.GL2ES3.GL_COLOR import com.jogamp.opengl.GL3 import glNext.* import glm.glm import glm.set import glm.vec._2.Vec2 import glm.vec._4.Vec4 import main.framework.Framework import main.framework.Semantic import uno.buffer.* import uno.glsl.programOf /** * Created by GBarbieri on 21.02.2017. */ fun main(args: Array<String>) { CpuPositionOffset_().setup("Tutorial 03 - CPU Position Offset") } class CpuPositionOffset_ : Framework() { var theProgram = 0 val positionBufferObject = intBufferBig(1) val vao = intBufferBig(1) val vertexPositions = floatBufferOf( +0.25f, +0.25f, 0.0f, 1.0f, +0.25f, -0.25f, 0.0f, 1.0f, -0.25f, -0.25f, 0.0f, 1.0f) var startingTime = 0L override fun init(gl: GL3) = with(gl) { initializeProgram(gl) initializeVertexBuffer(gl) glGenVertexArray(vao) glBindVertexArray(vao) startingTime = System.currentTimeMillis() } fun initializeProgram(gl: GL3) { theProgram = programOf(gl, javaClass, "tut03", "standard.vert", "standard.frag") } fun initializeVertexBuffer(gl: GL3) = with(gl) { glGenBuffer(positionBufferObject) glBindBuffer(GL_ARRAY_BUFFER, positionBufferObject) glBufferData(GL_ARRAY_BUFFER, vertexPositions, GL_STATIC_DRAW) glBindBuffer(GL_ARRAY_BUFFER) } override fun display(gl: GL3) = with(gl) { val offset = Vec2(0f) computePositionOffsets(offset) adjustVertexData(gl, offset) glClearBufferf(GL_COLOR) glUseProgram(theProgram) glBindBuffer(GL_ARRAY_BUFFER, positionBufferObject) glEnableVertexAttribArray(glf.pos4) glVertexAttribPointer(glf.pos4) glDrawArrays(3) glDisableVertexAttribArray(glf.pos4) glUseProgram() } fun computePositionOffsets(offset: Vec2) { val loopDuration = 5.0f val scale = glm.PIf * 2.0f / loopDuration val elapsedTime = (System.currentTimeMillis() - startingTime) / 1_000f val fCurrTimeThroughLoop = elapsedTime % loopDuration offset.x = glm.cos(fCurrTimeThroughLoop * scale) * 0.5f offset.y = glm.sin(fCurrTimeThroughLoop * scale) * 0.5f } fun adjustVertexData(gl: GL3, offset: Vec2) = with(gl) { val newData = floatBufferBig(vertexPositions.capacity()) repeat(vertexPositions.capacity()) { newData[it] = vertexPositions[it] } for (iVertex in 0 until vertexPositions.capacity() step 4) { newData[iVertex + 0] = vertexPositions[iVertex + 0] + offset.x newData[iVertex + 1] = vertexPositions[iVertex + 1] + offset.y } glBindBuffer(GL_ARRAY_BUFFER, positionBufferObject) glBufferSubData(GL_ARRAY_BUFFER, newData) glBindBuffer(GL_ARRAY_BUFFER) newData.destroy() } override fun reshape(gl: GL3, w: Int, h: Int) = with(gl) { glViewport(w, h) } override fun end(gl: GL3) = with(gl) { glDeleteProgram(theProgram) glDeleteBuffer(positionBufferObject) glDeleteVertexArray(vao) destroyBuffers(positionBufferObject, vao, vertexPositions) } override fun keyPressed(keyEvent: KeyEvent) { when (keyEvent.keyCode) { KeyEvent.VK_ESCAPE -> quit() } } }
mit
244e674ee93bccadfcc9a8953e513fa3
25.328244
88
0.650232
3.963218
false
false
false
false
AsynkronIT/protoactor-kotlin
proto-actor/src/main/kotlin/actor/proto/PID.kt
1
512
package actor.proto typealias PID = Protos.PID fun PID(address: String, id: String): PID { val p = PID.newBuilder() p.address = address p.id = id return p.build() } fun PID.isLocal(): Boolean = address == ProcessRegistry.noHost || address == ProcessRegistry.address internal fun PID.cachedProcess(): Process? { if (cachedProcess_ == null) { cachedProcess_ = ProcessRegistry.get(this) } return cachedProcess_ } fun PID.toShortString(): String { return "$address/$id" }
apache-2.0
4461e876cc853efdf040f54c5b3f4648
22.272727
100
0.666016
3.764706
false
false
false
false
serebit/autotitan
src/main/kotlin/api/Access.kt
1
3584
package com.serebit.autotitan.api import com.serebit.autotitan.extensions.isBotOwner import net.dv8tion.jda.api.Permission import net.dv8tion.jda.api.entities.Member import net.dv8tion.jda.api.events.message.MessageReceivedEvent sealed class Access(val description: String, val hidden: Boolean) { abstract fun matches(evt: MessageReceivedEvent): Boolean class All(hidden: Boolean = false) : Access("Anyone", hidden) { override fun matches(evt: MessageReceivedEvent): Boolean = true } class BotOwner(hidden: Boolean = false) : Access("Bot owner only", hidden) { override fun matches(evt: MessageReceivedEvent): Boolean = evt.author.isBotOwner } sealed class Private(description: String, hidden: Boolean) : Access(description, hidden) { override fun matches(evt: MessageReceivedEvent): Boolean = !evt.isFromGuild class All(hidden: Boolean = false) : Private("In private messages only", hidden) class BotOwner(hidden: Boolean = false) : Private("Bot owner in private messages only", hidden) { override fun matches(evt: MessageReceivedEvent): Boolean = super.matches(evt) && evt.author.isBotOwner } } sealed class Guild( description: String, hidden: Boolean, private val permissions: Set<Permission> ) : Access("$description\nPermissions: ${permissions.joinToString()}", hidden) { override fun matches(evt: MessageReceivedEvent): Boolean = evt.isFromGuild && evt.member?.hasPermission(permissions) ?: false class All( vararg permissions: Permission, hidden: Boolean = false ) : Guild("Servers only", hidden, permissions.toSet()) class BotOwner( hidden: Boolean = false, vararg permissions: Permission ) : Guild("Bot owner in servers only", hidden, permissions.toSet()) { override fun matches(evt: MessageReceivedEvent): Boolean = super.matches(evt) && evt.author.isBotOwner } class GuildOwner( vararg permissions: Permission, hidden: Boolean = false ) : Guild("Server owner only", hidden, permissions.toSet()) { override fun matches(evt: MessageReceivedEvent): Boolean = super.matches(evt) && evt.member!!.isOwner } class RankAbove( vararg permissions: Permission, hidden: Boolean = false ) : Guild("Anyone with their top role above the bot's top role", hidden, permissions.toSet()) { override fun matches(evt: MessageReceivedEvent): Boolean = super.matches(evt) && evt.member!!.rolePosition > evt.guild.selfMember.rolePosition } class RankSame( vararg permissions: Permission, hidden: Boolean = false ) : Guild("Anyone with the same top role as the bot's top role", hidden, permissions.toSet()) { override fun matches(evt: MessageReceivedEvent): Boolean = super.matches(evt) && evt.member!!.rolePosition == evt.guild.selfMember.rolePosition } class RankBelow( vararg permissions: Permission, hidden: Boolean = false ) : Guild("Anyone with their top role below the bot's top role", hidden, permissions.toSet()) { override fun matches(evt: MessageReceivedEvent): Boolean = super.matches(evt) && evt.member!!.rolePosition < evt.guild.selfMember.rolePosition } } } private val Member.rolePosition get() = roles.getOrNull(0)?.position ?: -1
apache-2.0
75c203609547693ca5cf4b821fee5fa8
42.707317
114
0.652344
4.703412
false
false
false
false
saru95/DSA
Kotlin/HeapSort.kt
1
1608
import java.util.Scanner class HeapSort { fun main(args: Array<String>) { var arr: IntArray val n: Int val userIn = Scanner(System.`in`) System.out.println("Enter the number of elements: ") n = userIn.nextInt() arr = IntArray(n) System.out.println("Enter each of the elements: ") for (i in 0 until n) { arr[i] = userIn.nextInt() } userIn.close() arr = heapSort(arr, n) System.out.println("Sorted array is:") printArray(arr, n) } fun heapSort(arr: IntArray, n: Int): IntArray { var arr = arr var temp: Int for (i in n / 2 - 1 downTo 0) { arr = heapify(arr, n, i) } for (i in n - 1 downTo 0) { temp = arr[0] arr[0] = arr[i] arr[i] = temp arr = heapify(arr, i, 0) } return arr } fun heapify(arr: IntArray, n: Int, i: Int): IntArray { var large = i val l = 2 * i + 1 val r = 2 * i + 2 val temp: Int if (l < n && arr[l] > arr[large]) { large = l } if (r < n && arr[r] > arr[large]) { large = r } if (large != i) { temp = arr[i] arr[i] = arr[large] arr[large] = temp heapify(arr, n, large) } return arr } fun printArray(arr: IntArray, n: Int) { for (i in 0 until n) { System.out.print(arr[i].toString() + " ") } System.out.println() } }
mit
33ddcbf415f857d1b82bb6bb4546b938
20.171053
60
0.443408
3.573333
false
false
false
false
zametki/zametki
src/main/java/com/github/zametki/ajax/AjaxApiUtils.kt
1
3634
package com.github.zametki.ajax import com.github.openjson.JSONArray import com.github.openjson.JSONObject import com.github.zametki.Constants import com.github.zametki.Context import com.github.zametki.UserSession import com.github.zametki.component.group.GroupTreeModel import com.github.zametki.component.group.GroupTreeNode import com.github.zametki.model.* import com.github.zametki.util.ZDateFormat import java.util.* import java.util.stream.Collectors object AjaxApiUtils { val ROOT_GROUP = Group() private val NOTES_LIST_DF = ZDateFormat.getInstance("dd MMMM yyyy", Constants.MOSCOW_TZ) fun getGroups(userId: UserId): JSONArray { val treeModel = GroupTreeModel.build(userId) val groups = JSONArray() treeModel.flatList().forEach { n -> groups.put(toJSON(n)) } return groups } private fun toJSON(node: GroupTreeNode): JSONObject? { val json = JSONObject() val groupId = node.groupId val g = (if (groupId.isRoot) ROOT_GROUP else Context.getGroupsDbi().getById(groupId)) ?: return null json.put("id", if (g.id == null) 0 else g.id!!.intValue) json.put("name", g.name) json.put("parentId", g.parentId.intValue) json.put("level", node.level) json.put("entriesCount", Context.getZametkaDbi().countByGroup(g.userId, groupId)) val children = JSONArray() var i = 0 val n = node.childCount while (i < n) { val childNode = node.getChildAt(i) as GroupTreeNode children.put(childNode.groupId.intValue) i++ } json.put("children", children) return json } fun getGroupsListAsResponse(userId: UserId): String { val response = JSONObject() response.put("groups", getGroups(userId)) return response.toString() } fun getNotesListAsResponse(group: Group?) = AjaxApiUtils.getNotesListAsResponse(group?.id) private fun getNotesListAsResponse(groupId: GroupId?): String { val notesArray = AjaxApiUtils.getNotes(groupId) return JSONObject().put("notes", notesArray).toString() } private fun getNotes(groupId: GroupId?): JSONArray { val noteIds = AjaxApiUtils.getList(groupId) val notesArray = JSONArray() noteIds .mapNotNull { Context.getZametkaDbi().getById(it) } .forEach { notesArray.put(toJSON(it)) } return notesArray } fun getNotesAndGroupsAsResponse(userId: UserId, groupId: GroupId): String { return JSONObject() .put("groups", AjaxApiUtils.getGroups(userId)) .put("notes", AjaxApiUtils.getNotes(groupId)) .toString() } private fun getList(groupId: GroupId?): List<ZametkaId> { var res = Context.getZametkaDbi().getByUser(UserSession.get().userId) res = if (groupId != null) { res.stream() .map<Zametka> { id -> Context.getZametkaDbi().getById(id) } .filter { z -> z != null && z.groupId == groupId } .map { z -> z.id } .collect(Collectors.toList<ZametkaId>()) } else { ArrayList(res) } Collections.reverse(res) return res } private fun toJSON(z: Zametka): JSONObject { val json = JSONObject() json.put("id", z.id!!.intValue) json.put("group", z.groupId.intValue) json.put("type", z.type.id) json.put("content", z.content) json.put("dateText", NOTES_LIST_DF.format(z.creationDate)) return json } }
apache-2.0
a030b2ad7f136aa5198b51feb038cc0e
34.627451
108
0.624381
4.201156
false
false
false
false
nlefler/Glucloser
Glucloser/app/src/main/kotlin/com/nlefler/glucloser/a/user/UserManager.kt
1
4088
package com.nlefler.glucloser.a.user import android.content.Context import android.util.Base64 import com.facebook.android.crypto.keychain.SharedPrefsBackedKeyChain import com.facebook.crypto.Crypto import com.facebook.crypto.Entity import com.facebook.crypto.exception.CryptoInitializationException import com.facebook.crypto.exception.KeyChainException import com.facebook.crypto.util.SystemNativeCryptoLibrary import com.nlefler.glucloser.a.dataSource.sync.cairo.CairoServices import com.nlefler.glucloser.a.dataSource.sync.cairo.services.CairoUserService import com.nlefler.glucloser.a.util.EncryptedPrefsStorageHelper import com.squareup.moshi.Moshi import rx.Observable import java.io.IOException import java.nio.charset.Charset import java.util.* import java.util.concurrent.Semaphore import javax.inject.Inject /** * Created by nathan on 2/15/16. */ class UserManager @Inject constructor(val cairoServices: CairoServices, ctx: Context) { companion object { private val SHARED_PREFS_NAME = "com.nlefler.glucloser.a.usermanager" private val SHARED_PREFS_IDENTITY_KEY = "com.nlefler.glucloser.a.usermanager.identity" private val CONCEAL_ENTITY_NAME = "com.nlefler.glucloser.a.concealentity" } private class Identity (val sessionID: String?, val pushToken: String?) { } private val userService = cairoServices.userService() private val crypto = Crypto(SharedPrefsBackedKeyChain(ctx), SystemNativeCryptoLibrary()) private val storageHelper = EncryptedPrefsStorageHelper(crypto, ctx, SHARED_PREFS_NAME, CONCEAL_ENTITY_NAME) private var identity: UserManager.Identity = emptyIdentity() private val identityLock = Semaphore(1) init { identity = getDecryptedIdentity() } fun loginOrCreateUser(email: String): Observable<Void?> { val uuid = identity.sessionID ?: UUID.randomUUID().toString() updateIdentity(uuid, identity.pushToken) return createUserOrLogin(email, uuid) } fun savePushToken(token: String) { val uuid = identity.sessionID ?: return updateIdentity(uuid, identity.pushToken) savePushToken(uuid, token) } fun saveFoursquareId(fsqId: String) { val uuid = identity.sessionID ?: return saveFoursquareId(uuid, fsqId) } private fun createUserOrLogin(email: String, sessionID: String): Observable<Void?> { return userService.createOrLogin(CairoUserService.CreateOrLoginBody(email, sessionID)) } private fun savePushToken(sessionID: String, token: String): Observable<Unit> { return userService.savePushToken(CairoUserService.SavePushTokenBody(sessionID, token)) } private fun saveFoursquareId(sessionID: String, fsqId: String): Observable<Unit> { return userService.saveFoursquareID(CairoUserService.SaveFoursquareIDBody(sessionID, fsqId)) } fun sessionID(): String? { return identity.sessionID } private fun clearIdentity() { cairoServices.clearAuthentication() identityLock.acquire() identity = emptyIdentity() encryptAndStoreIdentity(identity) identityLock.release() } private fun updateIdentity(uuid: String, pushToken: String?) { identityLock.acquire() identity = UserManager.Identity(uuid, pushToken) encryptAndStoreIdentity(identity) identityLock.release() } // Helpers private fun encryptAndStoreIdentity(identity: UserManager.Identity) { val jsonAdapter = Moshi.Builder().build().adapter(UserManager.Identity::class.java) storageHelper.store(SHARED_PREFS_IDENTITY_KEY, jsonAdapter.toJson(identity)) } private fun getDecryptedIdentity(): UserManager.Identity { val jsonAdapter = Moshi.Builder().build().adapter(UserManager.Identity::class.java) val stored = storageHelper.fetch(SHARED_PREFS_IDENTITY_KEY) ?: return emptyIdentity() return jsonAdapter.fromJson(stored) } private fun emptyIdentity(): UserManager.Identity { return UserManager.Identity(null, null) } }
gpl-2.0
0bd79289a32863cdf4ebc2b06dd0d0e9
36.163636
112
0.736546
4.276151
false
false
false
false
Shynixn/PetBlocks
petblocks-bukkit-plugin/src/main/kotlin/com/github/shynixn/petblocks/bukkit/logic/business/service/ProxyServiceImpl.kt
1
11138
@file:Suppress("UNCHECKED_CAST", "RemoveExplicitTypeArguments") package com.github.shynixn.petblocks.bukkit.logic.business.service import com.github.shynixn.petblocks.api.business.enumeration.Permission import com.github.shynixn.petblocks.api.business.enumeration.Version import com.github.shynixn.petblocks.api.business.service.LoggingService import com.github.shynixn.petblocks.api.business.service.ProxyService import com.github.shynixn.petblocks.api.persistence.entity.Position import com.github.shynixn.petblocks.api.persistence.entity.PotionEffect import com.github.shynixn.petblocks.bukkit.logic.business.extension.toPosition import com.github.shynixn.petblocks.core.logic.business.extension.cast import com.google.inject.Inject import org.bukkit.Bukkit import org.bukkit.Location import org.bukkit.command.CommandSender import org.bukkit.entity.Entity import org.bukkit.entity.Player import org.bukkit.inventory.Inventory import org.bukkit.inventory.ItemStack import org.bukkit.potion.PotionEffectType import org.bukkit.util.Vector import java.util.* import kotlin.collections.ArrayList import kotlin.math.cos import kotlin.math.sin class ProxyServiceImpl @Inject constructor(private val version: Version, private val loggingService: LoggingService) : ProxyService { /** * Gets a list of points between 2 locations. */ override fun <L> getPointsBetweenLocations(location1: L, location2: L, amount: Int): List<L> { require(location1 is Location) require(location2 is Location) if (location1.world != location2.world) { return ArrayList() } val locations = ArrayList<Location>() val vectorBetween = location1.subtract(location2) val onePointLength = vectorBetween.length() / amount for (i in 0 until amount) { val location = location2.clone().add(0.0, 0.7, 0.0) .add(vectorBetween.toVector().normalize().multiply(i).multiply(onePointLength)) locations.add(location) } return locations as List<L> } /** * Applies the given [potionEffect] to the given [player]. */ override fun <P> applyPotionEffect(player: P, potionEffect: PotionEffect) { require(player is Player) // PotionEffectType.values() can return null values in some minecraft versions. val foundPotionType = PotionEffectType.values().cast<Array<PotionEffectType?>>() .firstOrNull { t -> t != null && t.name.equals(potionEffect.potionType, true) } if (foundPotionType == null) { loggingService.warn("PotionEffectType: ${potionEffect.potionType} does not exist!") return } val potionEffectBukkit = org.bukkit.potion.PotionEffect( foundPotionType, potionEffect.duration * 20, potionEffect.amplifier, potionEffect.ambient, potionEffect.particles ) if (player.hasPotionEffect(foundPotionType)) { player.removePotionEffect(foundPotionType) } player.addPotionEffect(potionEffectBukkit) } /** * Drops the given item at the given position. */ override fun <L, I> dropInventoryItem(location: L, item: I) { require(location is Location) require(item is ItemStack) try { location.world!!.dropItem(location, item) } catch (e: Exception) { // Cannot drop air. } } /** * Gets the inventory item at the given index. */ override fun <I, IT> getInventoryItem(inventory: I, index: Int): IT? { require(inventory is Inventory) return inventory.getItem(index) as IT? } /** * Gets if the given player has got the given permission. */ override fun <P> hasPermission(player: P, permission: String): Boolean { require(player is Player) return player.hasPermission(permission) } /** * Clears the given inventory. */ override fun <I> clearInventory(inventory: I) { require(inventory is Inventory) inventory.clear() } /** * Gets the lower inventory of an inventory. */ override fun <I> getLowerInventory(inventory: I): I { // Only necessary for sponge. return inventory } /** * Gets if the given inventory belongs to a player. Returns null if not. */ override fun <P, I> getPlayerFromInventory(inventory: I): P? { require(inventory is Inventory) if (inventory.holder is Player) { return inventory.holder as P } return null } /** * Updates the inventory. */ override fun <I, IT> setInventoryItem(inventory: I, index: Int, item: IT) { require(inventory is Inventory) require(item is ItemStack?) inventory.setItem(index, item) } /** * Updates the given player inventory. */ override fun <P> updateInventory(player: P) { require(player is Player) player.updateInventory() } /** * Opens a new inventory for the given player. */ override fun <P, I> openInventory(player: P, title: String, size: Int): I { require(player is Player) val inventory = Bukkit.getServer().createInventory(player, size, title) player.openInventory(inventory) return inventory as I } /** * Closes the inventory of the given player. */ override fun <P> closeInventory(player: P) { require(player is Player) player.closeInventory() } /** * Gets the name of a player. */ override fun <P> getPlayerName(player: P): String { require(player is Player) return player.name } /** * Gets the player from the given UUID. */ override fun <P> getPlayerFromUUID(uuid: String): P { val player = Bukkit.getPlayer(UUID.fromString(uuid)) if (player != null && player.isOnline) { return player as P } throw IllegalArgumentException("Player is no longer online!") } /** * Gets the entity id. */ override fun <E> getEntityId(entity: E): Int { require(entity is Entity) return entity.entityId } /** * Gets the location of the player. */ override fun <L, P> getPlayerLocation(player: P): L { require(player is Player) return player.location as L } /** * Converts the given [location] to a [Position]. */ override fun <L> toPosition(location: L): Position { require(location is Location) return location.toPosition() } /** * Converts the given [position] to a Location.. */ override fun <L> toLocation(position: Position): L { return Location( Bukkit.getWorld(position.worldName!!), position.x, position.y, position.z, position.yaw.toFloat(), position.pitch.toFloat() ) as L } /** * Gets the looking direction of the player. */ override fun <P> getDirectionVector(player: P): Position { require(player is Player) val vector = Vector() val rotX = player.location.yaw.toDouble() val rotY = player.location.pitch.toDouble() vector.y = -sin(Math.toRadians(rotY)) val h = cos(Math.toRadians(rotY)) vector.x = -h * sin(Math.toRadians(rotX)) vector.z = h * cos(Math.toRadians(rotX)) return vector.toPosition() } /** * Gets the item in the player hand. */ override fun <P, I> getPlayerItemInHand(player: P, offhand: Boolean): I? { require(player is Player) return if (version.isVersionSameOrGreaterThan(Version.VERSION_1_9_R1)) { val inventoryClazz = Class.forName("org.bukkit.inventory.PlayerInventory") if (offhand) { inventoryClazz.getDeclaredMethod("getItemInOffHand").invoke(player.inventory) as I } else { inventoryClazz.getDeclaredMethod("getItemInMainHand").invoke(player.inventory) as I } } else { Class.forName("org.bukkit.entity.HumanEntity").getDeclaredMethod("getItemInHand") .invoke(player) as I } } /** * Sets the item in the player hand. */ override fun <P, I> setPlayerItemInHand(player: P, itemStack: I, offhand: Boolean) { require(player is Player) if (version.isVersionSameOrGreaterThan(Version.VERSION_1_9_R1)) { val inventoryClazz = Class.forName("org.bukkit.inventory.PlayerInventory") if (offhand) { inventoryClazz.getDeclaredMethod("setItemInOffHand", ItemStack::class.java) .invoke(player.inventory, itemStack) } else { inventoryClazz.getDeclaredMethod("setItemInMainHand", ItemStack::class.java) .invoke(player.inventory, itemStack) } } else { Class.forName("org.bukkit.entity.HumanEntity").getDeclaredMethod("setItemInHand", ItemStack::class.java) .invoke(player, itemStack) } player.updateInventory() } /** * Gets if the given player has got the given permission. */ override fun <P> hasPermission(player: P, permission: Permission): Boolean { require(player is Player) return player.hasPermission(permission.permission) } /** * Gets the player uuid. */ override fun <P> getPlayerUUID(player: P): String { require(player is Player) return player.uniqueId.toString() } /** * Sends a message to the [sender]. */ override fun <S> sendMessage(sender: S, message: String) { require(sender is CommandSender) sender.sendMessage(message) } /** * Executes a server command. */ override fun executeServerCommand(message: String) { Bukkit.getServer().dispatchCommand(Bukkit.getConsoleSender(), message) } /** * Executes a player command. */ override fun <P> executePlayerCommand(player: P, message: String) { require(player is Player) player.performCommand(message) } /** * Gets if the player is currently online. */ override fun <P> isPlayerOnline(player: P): Boolean { require(player is Player) return player.isOnline } /** * Gets if the player with the given uuid is currently online. */ override fun isPlayerUUIDOnline(uuid: String): Boolean { try { val player = Bukkit.getPlayer(UUID.fromString(uuid)) return player?.isOnline!! } catch (e: Exception) { // This part may or may not throw an exception depending on implementation. } return false } /** * Gets if the given instance can be converted to a player. */ override fun <P> isPlayer(instance: P): Boolean { return instance is Player } }
apache-2.0
98eb6318048c0fb5edf6eae41916c4bb
29.515068
118
0.622105
4.444533
false
false
false
false
Ph1b/MaterialAudiobookPlayer
settings/src/main/kotlin/voice/settings/views/darkTheme.kt
1
807
package voice.settings.views import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.material.ListItem import androidx.compose.material.Switch import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.res.stringResource import voice.settings.R @Composable internal fun DarkThemeRow(useDarkTheme: Boolean, toggle: () -> Unit) { ListItem( modifier = Modifier .clickable { toggle() } .fillMaxWidth(), text = { Text(text = stringResource(R.string.pref_theme_dark)) }, trailing = { Switch( checked = useDarkTheme, onCheckedChange = { toggle() } ) } ) }
lgpl-3.0
af034b48a7d1842c7c017deb549c8b21
23.454545
70
0.696406
4.292553
false
false
false
false
inorichi/tachiyomi
app/src/main/java/eu/kanade/tachiyomi/ui/browse/migration/sources/MigrationSourcesController.kt
1
3931
package eu.kanade.tachiyomi.ui.browse.migration.sources import android.view.LayoutInflater import android.view.Menu import android.view.MenuInflater import android.view.MenuItem import android.view.View import androidx.recyclerview.widget.LinearLayoutManager import dev.chrisbanes.insetter.applyInsetter import eu.davidea.flexibleadapter.FlexibleAdapter import eu.kanade.tachiyomi.R import eu.kanade.tachiyomi.data.preference.PreferencesHelper import eu.kanade.tachiyomi.databinding.MigrationSourcesControllerBinding import eu.kanade.tachiyomi.ui.base.controller.NucleusController import eu.kanade.tachiyomi.ui.base.controller.withFadeTransaction import eu.kanade.tachiyomi.ui.browse.migration.manga.MigrationMangaController import eu.kanade.tachiyomi.util.system.openInBrowser import uy.kohesive.injekt.injectLazy class MigrationSourcesController : NucleusController<MigrationSourcesControllerBinding, MigrationSourcesPresenter>(), FlexibleAdapter.OnItemClickListener { private val preferences: PreferencesHelper by injectLazy() private var adapter: SourceAdapter? = null init { setHasOptionsMenu(true) } override fun createPresenter(): MigrationSourcesPresenter { return MigrationSourcesPresenter() } override fun createBinding(inflater: LayoutInflater) = MigrationSourcesControllerBinding.inflate(inflater) override fun onViewCreated(view: View) { super.onViewCreated(view) binding.recycler.applyInsetter { type(navigationBars = true) { padding() } } adapter = SourceAdapter(this) binding.recycler.layoutManager = LinearLayoutManager(view.context) binding.recycler.adapter = adapter adapter?.fastScroller = binding.fastScroller } override fun onDestroyView(view: View) { adapter = null super.onDestroyView(view) } override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) { inflater.inflate(R.menu.browse_migrate, menu) } override fun onOptionsItemSelected(item: MenuItem): Boolean { when (val itemId = item.itemId) { R.id.action_source_migration_help -> activity?.openInBrowser(HELP_URL) R.id.asc_alphabetical, R.id.desc_alphabetical -> { setSortingDirection(SortSetting.ALPHABETICAL, itemId == R.id.asc_alphabetical) } R.id.asc_count, R.id.desc_count -> { setSortingDirection(SortSetting.TOTAL, itemId == R.id.asc_count) } } return super.onOptionsItemSelected(item) } private fun setSortingDirection(sortSetting: SortSetting, isAscending: Boolean) { val direction = if (isAscending) { DirectionSetting.ASCENDING } else { DirectionSetting.DESCENDING } preferences.migrationSortingDirection().set(direction) preferences.migrationSortingMode().set(sortSetting) presenter.requestSortUpdate() } fun setSources(sourcesWithManga: List<SourceItem>) { // Show empty view if needed if (sourcesWithManga.isNotEmpty()) { binding.emptyView.hide() } else { binding.emptyView.show(R.string.information_empty_library) } adapter?.updateDataSet(sourcesWithManga) } override fun onItemClick(view: View, position: Int): Boolean { val item = adapter?.getItem(position) as? SourceItem ?: return false val controller = MigrationMangaController(item.source.id, item.source.name) parentController!!.router.pushController(controller.withFadeTransaction()) return false } enum class DirectionSetting { ASCENDING, DESCENDING; } enum class SortSetting { ALPHABETICAL, TOTAL; } } private const val HELP_URL = "https://tachiyomi.org/help/guides/source-migration/"
apache-2.0
a5f1ed8554b4edd2530d8e55e774aed6
32.598291
110
0.702111
4.776428
false
false
false
false
jdinkla/groovy-java-ray-tracer
src/main/kotlin/net/dinkla/raytracer/lights/DirectionalLight.kt
1
903
package net.dinkla.raytracer.lights import net.dinkla.raytracer.hits.Shade import net.dinkla.raytracer.colors.Color import net.dinkla.raytracer.math.Ray import net.dinkla.raytracer.math.Vector3D import net.dinkla.raytracer.worlds.World /** * TODO: DirectionalLight Light implementieren */ class DirectionalLight : Light() { var ls: Double = 0.toDouble() var color: Color var negatedDirection: Vector3D init { ls = 1.0 color = Color.WHITE negatedDirection = -Vector3D.DOWN } override fun L(world: World, sr: Shade): Color = color * ls override fun getDirection(sr: Shade): Vector3D = negatedDirection override fun inShadow(world: World, ray: Ray, sr: Shade): Boolean { return world.inShadow(ray, sr, java.lang.Double.MAX_VALUE) } fun setDirection(direction: Vector3D) { this.negatedDirection = -direction } }
apache-2.0
77c04b3c299d402de77de73390ec2460
24.083333
71
0.69546
3.778243
false
false
false
false
egenvall/TravelPlanner
app/src/main/java/com/egenvall/travelplanner/persistance/RealmInteractorImpl.kt
1
5073
package com.egenvall.travelplanner.persistance import com.egenvall.travelplanner.model.* import io.realm.Realm import javax.inject.Inject class RealmInteractorImpl @Inject constructor(val realm : Realm) : IRealmInteractor { //=================================================================================== // Favourites //=================================================================================== override fun addFavourite(origin: StopLocation, dest: StopLocation, nick: String, bg: String) { val favList = realm.where(Favourites::class.java).findFirst() if (favList == null) { realm.beginTransaction() realm.createObject(Favourites::class.java, "Favourites") realm.commitTransaction() addFavouriteToRealm(origin,dest,nick,bg) } else { addFavouriteToRealm(origin,dest,nick,bg) } } private fun addFavouriteToRealm(origin : StopLocation, dest : StopLocation, nick: String, bg : String){ val favourites = realm.where(Favourites::class.java).findFirst() val copy = realm.copyFromRealm(favourites.list) copy.add(0, Favourite(nick,bg,SearchPair(constructPkSearchPair(origin,dest), mapToRealmStopLocation(origin), mapToRealmStopLocation(dest))) ) realm.executeTransaction { with(favourites.list) { deleteAllFromRealm() realm.copyToRealmOrUpdate(copy) addAll(copy.distinctBy { it.pair.orgPlusDestId }) } } } override fun getFavourites(): List<Favourite> { var returnList = listOf<Favourite>() realm.executeTransaction { val res = realm.where(Favourites::class.java).findFirst() if (res != null) { returnList = realm.copyFromRealm(res.list.distinct()) } } return returnList } //=================================================================================== // Search History //=================================================================================== override fun addSearchHistory(origin: StopLocation, dest: StopLocation) { val history = realm.where(SearchHistory::class.java).findFirst() if (history == null) { realm.beginTransaction() realm.createObject(SearchHistory::class.java, "History") realm.commitTransaction() addPairToRealm(origin, dest) } else { addPairToRealm(origin, dest) } } private fun addPairToRealm(origin: StopLocation, dest: StopLocation) { val history = realm.where(SearchHistory::class.java).findFirst() val copy = realm.copyFromRealm(history.list) copy.add(0, SearchPair(constructPkSearchPair(origin, dest), mapToRealmStopLocation(origin), mapToRealmStopLocation(dest)) ) realm.executeTransaction { with(history.list) { deleteAllFromRealm() realm.copyToRealmOrUpdate(copy.take(6)) addAll(copy.distinctBy { it.orgPlusDestId }) } } } override fun getSearchHistory(): List<SearchPair> { //val res = realm.where(SearchHistory::class.java).findFirst().list.deleteAllFromRealm() val res = realm.where(SearchHistory::class.java).findFirst() if (res == null){ realm.beginTransaction() realm.createObject(SearchHistory::class.java, "History") realm.commitTransaction() } val result = realm.where(SearchHistory::class.java).findFirst().list.distinct() return result } override fun removeFromSearchHistory(pair: SearchPair) { realm.executeTransaction { val result = realm.where(SearchPair::class.java) .equalTo("orgPlusDestId", pair.orgPlusDestId).findFirst() result.deleteFromRealm() } } //=================================================================================== // Helper Methods //=================================================================================== private fun constructPkSearchPair(origin: StopLocation, dest: StopLocation): String { var originIdentifier: String = "" var destIdentifier: String = "" when (origin.type) { "STOP" -> originIdentifier = origin.id "ADR" -> originIdentifier = origin.name "POI" -> originIdentifier = origin.name } when (dest.type) { "STOP" -> destIdentifier = dest.id "ADR" -> destIdentifier = dest.name "POI" -> destIdentifier = dest.name } return originIdentifier + "/" + destIdentifier } private fun mapToRealmStopLocation(stop: StopLocation): RealmStopLocation { with(stop) { return RealmStopLocation(id, type, lat, lon, idx, name) } } }
apache-2.0
28f3b2f76360bb2d2e2a98e6dad37bf5
37.732824
107
0.539523
5.14503
false
false
false
false
Deletescape-Media/Lawnchair
lawnchair/src/app/lawnchair/ui/preferences/components/colorpreference/ColorPreference.kt
1
7367
/* * Copyright 2021, Lawnchair * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package app.lawnchair.ui.preferences.components.colorpreference import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.* import androidx.compose.material.RadioButton import androidx.compose.material3.Button import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.runtime.* import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.res.stringResource import androidx.compose.ui.unit.dp import app.lawnchair.preferences.PreferenceAdapter import app.lawnchair.theme.color.ColorOption import app.lawnchair.ui.AlertBottomSheetContent import app.lawnchair.ui.preferences.components.Chip import app.lawnchair.ui.preferences.components.PreferenceDivider import app.lawnchair.ui.preferences.components.PreferenceTemplate import app.lawnchair.ui.theme.lightenColor import app.lawnchair.ui.util.bottomSheetHandler import com.android.launcher3.R import com.google.accompanist.pager.ExperimentalPagerApi import com.google.accompanist.pager.HorizontalPager import com.google.accompanist.pager.rememberPagerState import kotlinx.coroutines.launch @OptIn(ExperimentalPagerApi::class) @Composable fun ColorPreference( adapter: PreferenceAdapter<ColorOption>, label: String, dynamicEntries: List<ColorPreferenceEntry<ColorOption>>, staticEntries: List<ColorPreferenceEntry<ColorOption>>, ) { var selectedColor by adapter val selectedEntry = dynamicEntries.firstOrNull { it.value == selectedColor } ?: staticEntries.firstOrNull { it.value == selectedColor } val defaultTabIndex = if (dynamicEntries.any { it.value == selectedColor }) 0 else 1 val description = selectedEntry?.label?.invoke() val bottomSheetHandler = bottomSheetHandler var bottomSheetShown by remember { mutableStateOf(false) } PreferenceTemplate( title = { Text(text = label) }, endWidget = { ColorDot(color = MaterialTheme.colorScheme.primary) }, modifier = Modifier.clickable { bottomSheetShown = true }, description = { if (description != null) { Text(text = description) } }, ) if (bottomSheetShown) { bottomSheetHandler.onDismiss { bottomSheetShown = false } bottomSheetHandler.show { val pagerState = rememberPagerState(defaultTabIndex) val scope = rememberCoroutineScope() val scrollToPage = { page: Int -> scope.launch { pagerState.animateScrollToPage(page) } } AlertBottomSheetContent( title = { Text(text = label) }, buttons = { Button(onClick = { bottomSheetHandler.hide() }) { Text(text = stringResource(id = R.string.done)) } } ) { Column { Row( horizontalArrangement = Arrangement.spacedBy(space = 8.dp), modifier = Modifier.padding(horizontal = 16.dp), ) { Chip( label = stringResource(id = R.string.dynamic), onClick = { scrollToPage(0) }, currentOffset = pagerState.currentPage + pagerState.currentPageOffset, page = 0, ) Chip( label = stringResource(id = R.string.presets), onClick = { scrollToPage(1) }, currentOffset = pagerState.currentPage + pagerState.currentPageOffset, page = 1, ) } HorizontalPager( count = 2, state = pagerState, verticalAlignment = Alignment.Top, modifier = Modifier.pagerHeight( dynamicCount = dynamicEntries.size, staticCount = staticEntries.size, ), ) { page -> when (page) { 0 -> { PresetsList( dynamicEntries = dynamicEntries, adapter = adapter, ) } 1 -> { SwatchGrid( entries = staticEntries, modifier = Modifier.padding( start = 16.dp, top = 20.dp, end = 16.dp, bottom = 16.dp, ), onSwatchClick = { selectedColor = it }, isSwatchSelected = { it == selectedColor }, ) } } } } } } } } @Composable private fun PresetsList( dynamicEntries: List<ColorPreferenceEntry<ColorOption>>, adapter: PreferenceAdapter<ColorOption>, ) { Box( modifier = Modifier .fillMaxHeight(), contentAlignment = Alignment.TopStart ) { Column(modifier = Modifier.padding(top = 16.dp)) { dynamicEntries.mapIndexed { index, entry -> key(entry) { if (index > 0) { PreferenceDivider(startIndent = 40.dp) } PreferenceTemplate( title = { Text(text = entry.label()) }, verticalPadding = 12.dp, modifier = Modifier.clickable { adapter.onChange(entry.value) }, startWidget = { RadioButton( selected = entry.value == adapter.state.value, onClick = null ) ColorDot( entry = entry, modifier = Modifier.padding(start = 16.dp) ) } ) } } } } } open class ColorPreferenceEntry<T>( val value: T, val label: @Composable () -> String, val lightColor: @Composable () -> Int, val darkColor: @Composable () -> Int = { lightenColor(lightColor()) }, )
gpl-3.0
5fa0ca6c30735cf829c7d6b14e88f04f
39.707182
139
0.525451
5.593774
false
false
false
false
android/camera-samples
Camera2Video/app/src/main/java/com/example/android/camera2/video/HardwarePipeline.kt
1
26344
/* * 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.example.android.camera2.video.fragments import android.annotation.SuppressLint import android.content.Context import android.content.Intent import android.content.pm.ActivityInfo import android.graphics.Color import android.graphics.ImageFormat import android.graphics.Rect import android.graphics.SurfaceTexture import android.hardware.camera2.CameraCaptureSession import android.hardware.camera2.CameraCharacteristics import android.hardware.camera2.CameraDevice import android.hardware.camera2.CameraManager import android.hardware.camera2.CaptureRequest import android.hardware.camera2.params.OutputConfiguration import android.hardware.HardwareBuffer import android.media.Image import android.media.ImageReader import android.media.ImageWriter import android.media.MediaCodec import android.media.MediaCodecInfo import android.media.MediaFormat import android.media.MediaScannerConnection import android.opengl.EGL14 import android.opengl.EGL14.EGL_CONTEXT_CLIENT_VERSION import android.opengl.EGL14.EGL_OPENGL_ES2_BIT import android.opengl.EGLConfig import android.opengl.EGLContext import android.opengl.EGLDisplay import android.opengl.EGLExt import android.opengl.EGLSurface import android.opengl.GLES11Ext import android.opengl.GLES20 import android.os.Bundle import android.os.ConditionVariable import android.os.Handler import android.os.HandlerThread import android.os.Looper import android.os.Message import android.util.Log import android.util.Range import android.util.Size import android.view.LayoutInflater import android.view.MotionEvent import android.view.Surface import android.view.SurfaceHolder import android.view.TextureView import android.view.View import android.view.ViewGroup import android.webkit.MimeTypeMap import androidx.core.content.FileProvider import androidx.core.graphics.drawable.toDrawable import androidx.fragment.app.Fragment import androidx.lifecycle.Observer import androidx.lifecycle.lifecycleScope import androidx.navigation.NavController import androidx.navigation.Navigation import androidx.navigation.fragment.navArgs import com.example.android.camera.utils.getPreviewOutputSize import com.example.android.camera.utils.AutoFitSurfaceView import com.example.android.camera2.video.BuildConfig import com.example.android.camera2.video.CameraActivity import com.example.android.camera2.video.R import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.delay import kotlinx.coroutines.launch import kotlinx.coroutines.suspendCancellableCoroutine import java.io.File import java.nio.ByteBuffer import java.nio.ByteOrder import java.nio.IntBuffer import java.text.SimpleDateFormat import java.util.Date import java.util.Locale import kotlin.RuntimeException import kotlin.coroutines.resume import kotlin.coroutines.resumeWithException import kotlin.coroutines.suspendCoroutine import com.example.android.camera2.video.EncoderWrapper /** Generates a fullscreen quad to cover the entire viewport. Applies the transform set on the camera surface to adjust for orientation and scaling when used for copying from the camera surface to the render surface. We will pass an identity matrix when copying from the render surface to the recording / preview surfaces. */ private val TRANSFORM_VSHADER = """ attribute vec4 vPosition; uniform mat4 texMatrix; varying vec2 vTextureCoord; void main() { gl_Position = vPosition; vec4 texCoord = vec4((vPosition.xy + vec2(1.0, 1.0)) / 2.0, 0.0, 1.0); vTextureCoord = (texMatrix * texCoord).xy; } """ /** Passthrough fragment shader, simply copies from the source texture */ private val PASSTHROUGH_FSHADER = """ #extension GL_OES_EGL_image_external : require precision mediump float; varying vec2 vTextureCoord; uniform samplerExternalOES sTexture; void main() { gl_FragColor = texture2D(sTexture, vTextureCoord); } """ private val PORTRAIT_FSHADER = """ #extension GL_OES_EGL_image_external : require precision mediump float; varying vec2 vTextureCoord; uniform samplerExternalOES sTexture; void main() { float x = vTextureCoord.x * 2.0 - 1.0, y = vTextureCoord.y * 2.0 - 1.0; vec4 color = texture2D(sTexture, vTextureCoord); float r = sqrt(x * x + y * y); float theta = atan(y, x); gl_FragColor = color * (1.0 - r); } """ private val IDENTITY_MATRIX = floatArrayOf( 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f ) private val FULLSCREEN_QUAD = floatArrayOf( -1.0f, -1.0f, // 0 bottom left 1.0f, -1.0f, // 1 bottom right -1.0f, 1.0f, // 2 top left 1.0f, 1.0f, // 3 top right ) class HardwarePipeline(width: Int, height: Int, fps: Int, filterOn: Boolean, characteristics: CameraCharacteristics, encoder: EncoderWrapper, viewFinder: AutoFitSurfaceView) : Pipeline(width, height, fps, filterOn, characteristics, encoder, viewFinder) { private val renderThread: HandlerThread by lazy { val renderThread = HandlerThread("Camera2Video.RenderThread") renderThread.start() renderThread } private val renderHandler = RenderHandler(renderThread.getLooper(), width, height, fps, filterOn, characteristics, encoder) override fun createRecordRequest(session: CameraCaptureSession, previewStabilization: Boolean) : CaptureRequest { return renderHandler.createRecordRequest(session, previewStabilization) } override fun startRecording() { renderHandler.startRecording() } override fun stopRecording() { renderHandler.stopRecording() } override fun destroyWindowSurface() { renderHandler.sendMessage(renderHandler.obtainMessage( RenderHandler.MSG_DESTROY_WINDOW_SURFACE)) } override fun setPreviewSize(previewSize: Size) { renderHandler.setPreviewSize(previewSize) } override fun createResources(surface: Surface) { renderHandler.sendMessage(renderHandler.obtainMessage( RenderHandler.MSG_CREATE_RESOURCES, 0, 0, surface)) } override fun getTargets(): List<Surface> { return renderHandler.getTargets() } override fun actionDown(encoderSurface: Surface) { renderHandler.sendMessage(renderHandler.obtainMessage( RenderHandler.MSG_ACTION_DOWN, 0, 0, encoderSurface)) } override fun clearFrameListener() { renderHandler.sendMessage(renderHandler.obtainMessage( RenderHandler.MSG_CLEAR_FRAME_LISTENER)) } override fun cleanup() { renderHandler.sendMessage(renderHandler.obtainMessage( RenderHandler.MSG_CLEANUP)) } private class ShaderProgram(id: Int, vPositionLoc: Int, texMatrixLoc: Int) { private val id = id private val vPositionLoc = vPositionLoc private val texMatrixLoc = texMatrixLoc public fun setVertexAttribArray(vertexCoords: FloatArray) { val nativeBuffer = ByteBuffer.allocateDirect(vertexCoords.size * 4) nativeBuffer.order(ByteOrder.nativeOrder()) val vertexBuffer = nativeBuffer.asFloatBuffer() vertexBuffer.put(vertexCoords) nativeBuffer.position(0) vertexBuffer.position(0) GLES20.glEnableVertexAttribArray(vPositionLoc) checkGlError("glEnableVertexAttribArray") GLES20.glVertexAttribPointer(vPositionLoc, 2, GLES20.GL_FLOAT, false, 8, vertexBuffer) checkGlError("glVertexAttribPointer") } public fun setTexMatrix(texMatrix: FloatArray) { GLES20.glUniformMatrix4fv(texMatrixLoc, 1, false, texMatrix, 0) checkGlError("glUniformMatrix4fv") } public fun useProgram() { GLES20.glUseProgram(id) checkGlError("glUseProgram") } } private class RenderHandler(looper: Looper, width: Int, height: Int, fps: Int, filterOn: Boolean, characteristics: CameraCharacteristics, encoder: EncoderWrapper): Handler(looper), SurfaceTexture.OnFrameAvailableListener { companion object { val MSG_CREATE_RESOURCES = 0 val MSG_DESTROY_WINDOW_SURFACE = 1 val MSG_ACTION_DOWN = 2 val MSG_CLEAR_FRAME_LISTENER = 3 val MSG_CLEANUP = 4 val MSG_ON_FRAME_AVAILABLE = 5 } private val width = width private val height = height private val fps = fps private val filterOn = filterOn private val characteristics = characteristics private val encoder = encoder private var previewSize = Size(0, 0) /** OpenGL texture for the SurfaceTexture provided to the camera */ private var cameraTexId: Int = 0 /** The SurfaceTexture provided to the camera for capture */ private lateinit var cameraTexture: SurfaceTexture /** The above SurfaceTexture cast as a Surface */ private lateinit var cameraSurface: Surface /** OpenGL texture that will combine the camera output with rendering */ private var renderTexId: Int = 0 /** The SurfaceTexture we're rendering to */ private lateinit var renderTexture: SurfaceTexture /** The above SurfaceTexture cast as a Surface */ private lateinit var renderSurface: Surface /** Storage space for setting the texMatrix uniform */ private val texMatrix = FloatArray(16) /** Orientation of the camera as 0, 90, 180, or 270 degrees */ private val orientation: Int by lazy { characteristics.get(CameraCharacteristics.SENSOR_ORIENTATION)!! } @Volatile private var currentlyRecording = false /** EGL / OpenGL data. */ private var eglDisplay = EGL14.EGL_NO_DISPLAY; private var eglContext = EGL14.EGL_NO_CONTEXT; private var eglConfig: EGLConfig? = null; private var eglRenderSurface: EGLSurface? = null private var eglEncoderSurface: EGLSurface? = null private var eglWindowSurface: EGLSurface? = null private var vertexShader = 0 private var passthroughFragmentShader = 0 private var portraitFragmentShader = 0 private var passthroughShaderProgram: ShaderProgram? = null private var portraitShaderProgram: ShaderProgram? = null private val cvResourcesCreated = ConditionVariable(false) public fun startRecording() { currentlyRecording = true } public fun stopRecording() { currentlyRecording = false } public fun createRecordRequest(session: CameraCaptureSession, previewStabilization: Boolean) : CaptureRequest { cvResourcesCreated.block() // Capture request holds references to target surfaces return session.device.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW).apply { // Add the preview surface target addTarget(cameraSurface) set(CaptureRequest.CONTROL_AE_TARGET_FPS_RANGE, Range(fps, fps)) if (previewStabilization) { set(CaptureRequest.CONTROL_VIDEO_STABILIZATION_MODE, CaptureRequest.CONTROL_VIDEO_STABILIZATION_MODE_PREVIEW_STABILIZATION) } }.build() } public fun setPreviewSize(previewSize: Size) { this.previewSize = previewSize } public fun getTargets(): List<Surface> { cvResourcesCreated.block() return listOf(cameraSurface) } /** Initialize the EGL display, context, and render surface */ private fun initEGL() { eglDisplay = EGL14.eglGetDisplay(EGL14.EGL_DEFAULT_DISPLAY) if (eglDisplay == EGL14.EGL_NO_DISPLAY) { throw RuntimeException("unable to get EGL14 display") } val version = intArrayOf(0, 0) if (!EGL14.eglInitialize(eglDisplay, version, 0, version, 1)) { eglDisplay = null; throw RuntimeException("unable to initialize EGL14") } val configAttribList = intArrayOf( EGL14.EGL_RENDERABLE_TYPE, EGL14.EGL_OPENGL_ES2_BIT, EGL14.EGL_RED_SIZE, 8, EGL14.EGL_GREEN_SIZE, 8, EGL14.EGL_BLUE_SIZE, 8, EGL14.EGL_ALPHA_SIZE, 8, EGL14.EGL_DEPTH_SIZE, 0, EGL14.EGL_STENCIL_SIZE, 0, EGLExt.EGL_RECORDABLE_ANDROID, 1, EGL14.EGL_NONE ) val configs = arrayOfNulls<EGLConfig>(1); val numConfigs = intArrayOf(1); EGL14.eglChooseConfig(eglDisplay, configAttribList, 0, configs, 0, configs.size, numConfigs, 0) eglConfig = configs[0]!! val contextAttribList = intArrayOf( EGL14.EGL_CONTEXT_CLIENT_VERSION, 2, EGL14.EGL_NONE ) eglContext = EGL14.eglCreateContext(eglDisplay, eglConfig, EGL14.EGL_NO_CONTEXT, contextAttribList, 0) if (eglContext == EGL14.EGL_NO_CONTEXT) { throw RuntimeException("Failed to create EGL context") } val clientVersion = intArrayOf(0) EGL14.eglQueryContext(eglDisplay, eglContext, EGL14.EGL_CONTEXT_CLIENT_VERSION, clientVersion, 0) Log.v(TAG, "EGLContext created, client version " + clientVersion[0]) val tmpSurfaceAttribs = intArrayOf( EGL14.EGL_WIDTH, 1, EGL14.EGL_HEIGHT, 1, EGL14.EGL_NONE) val tmpSurface = EGL14.eglCreatePbufferSurface( eglDisplay, eglConfig, tmpSurfaceAttribs, /*offset*/ 0) EGL14.eglMakeCurrent(eglDisplay, tmpSurface, tmpSurface, eglContext) } private fun createResources(surface: Surface) { if (eglContext == EGL14.EGL_NO_CONTEXT) { initEGL() } val surfaceAttribs = intArrayOf(EGL14.EGL_NONE) eglWindowSurface = EGL14.eglCreateWindowSurface(eglDisplay, eglConfig, surface, surfaceAttribs, 0) if (eglWindowSurface == EGL14.EGL_NO_SURFACE) { throw RuntimeException("Failed to create EGL texture view surface") } EGL14.eglMakeCurrent(eglDisplay, eglWindowSurface, eglWindowSurface, eglContext) cameraTexId = createTexture() cameraTexture = SurfaceTexture(cameraTexId) cameraTexture.setOnFrameAvailableListener(this) cameraTexture.setDefaultBufferSize(width, height) cameraSurface = Surface(cameraTexture) renderTexId = createTexture() renderTexture = SurfaceTexture(renderTexId) renderTexture.setDefaultBufferSize(width, height) renderSurface = Surface(renderTexture) eglRenderSurface = EGL14.eglCreateWindowSurface(eglDisplay, eglConfig, renderSurface, surfaceAttribs, 0) if (eglRenderSurface == EGL14.EGL_NO_SURFACE) { throw RuntimeException("Failed to create EGL render surface") } if (passthroughShaderProgram == null) { createShaderResources() } cvResourcesCreated.open() } private fun createShaderResources() { vertexShader = createShader(GLES20.GL_VERTEX_SHADER, TRANSFORM_VSHADER) passthroughFragmentShader = createShader(GLES20.GL_FRAGMENT_SHADER, PASSTHROUGH_FSHADER) portraitFragmentShader = createShader(GLES20.GL_FRAGMENT_SHADER, PORTRAIT_FSHADER) passthroughShaderProgram = createShaderProgram(passthroughFragmentShader) portraitShaderProgram = createShaderProgram(portraitFragmentShader) } /** Creates the shader program used to copy data from one texture to another */ private fun createShaderProgram(fragmentShader: Int): ShaderProgram { var shaderProgram = GLES20.glCreateProgram() GLES20.glAttachShader(shaderProgram, vertexShader) GLES20.glAttachShader(shaderProgram, fragmentShader) GLES20.glLinkProgram(shaderProgram) val linkStatus = intArrayOf(0) GLES20.glGetProgramiv(shaderProgram, GLES20.GL_LINK_STATUS, linkStatus, 0) if (linkStatus[0] == 0) { val msg = "Could not link program: " + GLES20.glGetProgramInfoLog(shaderProgram) GLES20.glDeleteProgram(shaderProgram) shaderProgram = 0 throw RuntimeException(msg) } var vPositionLoc = GLES20.glGetAttribLocation(shaderProgram, "vPosition") var texMatrixLoc = GLES20.glGetUniformLocation(shaderProgram, "texMatrix") return ShaderProgram(shaderProgram, vPositionLoc, texMatrixLoc) } /** Create a shader given its type and source string */ private fun createShader(type: Int, source: String): Int { var shader = GLES20.glCreateShader(type) GLES20.glShaderSource(shader, source) GLES20.glCompileShader(shader) val compiled = intArrayOf(0) GLES20.glGetShaderiv(shader, GLES20.GL_COMPILE_STATUS, compiled, 0) if (compiled[0] == 0) { val msg = "Could not compile shader " + type + ": " + GLES20.glGetShaderInfoLog(shader) GLES20.glDeleteShader(shader) throw RuntimeException(msg) } return shader } /** Create an OpenGL texture */ private fun createTexture(): Int { /* Check that EGL has been initialized. */ if (eglDisplay == null) { throw IllegalStateException("EGL not initialized before call to createTexture()"); } val buffer = IntBuffer.allocate(1) GLES20.glGenTextures(1, buffer) val texId = buffer.get(0) GLES20.glBindTexture(GLES11Ext.GL_TEXTURE_EXTERNAL_OES, texId) GLES20.glTexParameteri(GLES11Ext.GL_TEXTURE_EXTERNAL_OES, GLES20.GL_TEXTURE_MIN_FILTER, GLES20.GL_NEAREST) GLES20.glTexParameteri(GLES11Ext.GL_TEXTURE_EXTERNAL_OES, GLES20.GL_TEXTURE_MAG_FILTER, GLES20.GL_LINEAR) GLES20.glTexParameteri(GLES11Ext.GL_TEXTURE_EXTERNAL_OES, GLES20.GL_TEXTURE_WRAP_S, GLES20.GL_CLAMP_TO_EDGE) GLES20.glTexParameteri(GLES11Ext.GL_TEXTURE_EXTERNAL_OES, GLES20.GL_TEXTURE_WRAP_T, GLES20.GL_CLAMP_TO_EDGE) return texId } private fun destroyWindowSurface() { EGL14.eglDestroySurface(eglDisplay, eglWindowSurface) eglWindowSurface = null } private fun copyTexture(texId: Int, texture: SurfaceTexture, viewportRect: Rect, shaderProgram: ShaderProgram) { GLES20.glClearColor(0.0f, 0.0f, 0.0f, 1.0f) checkGlError("glClearColor") GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT) checkGlError("glClear") shaderProgram.useProgram() GLES20.glActiveTexture(GLES20.GL_TEXTURE0) checkGlError("glActiveTexture") GLES20.glBindTexture(GLES11Ext.GL_TEXTURE_EXTERNAL_OES, texId) checkGlError("glBindTexture") texture.getTransformMatrix(texMatrix) shaderProgram.setTexMatrix(texMatrix) shaderProgram.setVertexAttribArray(FULLSCREEN_QUAD) GLES20.glViewport(viewportRect.left, viewportRect.top, viewportRect.right, viewportRect.bottom) checkGlError("glViewport") GLES20.glDrawArrays(GLES20.GL_TRIANGLE_STRIP, 0, 4) checkGlError("glDrawArrays") } private fun copyCameraToRender() { EGL14.eglMakeCurrent(eglDisplay, eglRenderSurface, eglRenderSurface, eglContext) var shaderProgram = passthroughShaderProgram if (filterOn) { shaderProgram = portraitShaderProgram } copyTexture(cameraTexId, cameraTexture, Rect(0, 0, width, height), shaderProgram!!) EGL14.eglSwapBuffers(eglDisplay, eglRenderSurface) renderTexture.updateTexImage() } private fun copyRenderToPreview() { EGL14.eglMakeCurrent(eglDisplay, eglWindowSurface, eglRenderSurface, eglContext) val cameraAspectRatio = width.toFloat() / height.toFloat() val previewAspectRatio = previewSize.width.toFloat() / previewSize.height.toFloat() var viewportWidth = previewSize.width var viewportHeight = previewSize.height var viewportX = 0 var viewportY = 0 /** The camera display is not the same size as the video. Letterbox the preview so that we can see exactly how the video will turn out. */ if (previewAspectRatio < cameraAspectRatio) { /** Avoid vertical stretching */ viewportHeight = (viewportWidth.toFloat() / cameraAspectRatio).toInt() viewportY = (previewSize.height - viewportHeight) / 2 } else { /** Avoid horizontal stretching */ viewportWidth = (viewportHeight.toFloat() * cameraAspectRatio).toInt() viewportX = (previewSize.width - viewportWidth) / 2 } copyTexture(renderTexId, renderTexture, Rect(viewportX, viewportY, viewportWidth, viewportHeight), passthroughShaderProgram!!) EGL14.eglSwapBuffers(eglDisplay, eglWindowSurface) } private fun copyRenderToEncode() { EGL14.eglMakeCurrent(eglDisplay, eglEncoderSurface, eglRenderSurface, eglContext) var viewportWidth = width var viewportHeight = height /** Swap width and height if the camera is rotated on its side. */ if (orientation == 90 || orientation == 270) { viewportWidth = height viewportHeight = width } copyTexture(renderTexId, renderTexture, Rect(0, 0, viewportWidth, viewportHeight), passthroughShaderProgram!!) encoder.frameAvailable() EGLExt.eglPresentationTimeANDROID(eglDisplay, eglEncoderSurface, cameraTexture.getTimestamp()) EGL14.eglSwapBuffers(eglDisplay, eglEncoderSurface) } private fun actionDown(encoderSurface: Surface) { val surfaceAttribs = intArrayOf(EGL14.EGL_NONE) eglEncoderSurface = EGL14.eglCreateWindowSurface(eglDisplay, eglConfig, encoderSurface, surfaceAttribs, 0) if (eglEncoderSurface == EGL14.EGL_NO_SURFACE) { val error = EGL14.eglGetError() throw RuntimeException("Failed to create EGL encoder surface" + ": eglGetError = 0x" + Integer.toHexString(error)) } } private fun clearFrameListener() { cameraTexture.setOnFrameAvailableListener(null) } private fun cleanup() { EGL14.eglDestroySurface(eglDisplay, eglEncoderSurface) eglEncoderSurface = null EGL14.eglDestroySurface(eglDisplay, eglRenderSurface) eglRenderSurface = null cameraTexture.release() EGL14.eglDestroyContext(eglDisplay, eglContext) } private fun onFrameAvailableImpl(surfaceTexture: SurfaceTexture) { /** The camera API does not update the tex image. Do so here. */ cameraTexture.updateTexImage() /** Copy from the camera texture to the render texture */ if (eglRenderSurface != null) { copyCameraToRender() } /** Copy from the render texture to the TextureView */ if (eglWindowSurface != null) { copyRenderToPreview() } /** Copy to the encoder surface if we're currently recording. */ if (eglEncoderSurface != null && currentlyRecording) { copyRenderToEncode() } } override fun onFrameAvailable(surfaceTexture: SurfaceTexture) { sendMessage(obtainMessage(MSG_ON_FRAME_AVAILABLE, 0, 0, surfaceTexture)) } public override fun handleMessage(msg: Message) { when (msg.what) { MSG_CREATE_RESOURCES -> createResources(msg.obj as Surface) MSG_DESTROY_WINDOW_SURFACE -> destroyWindowSurface() MSG_ACTION_DOWN -> actionDown(msg.obj as Surface) MSG_CLEAR_FRAME_LISTENER -> clearFrameListener() MSG_CLEANUP -> cleanup() MSG_ON_FRAME_AVAILABLE -> onFrameAvailableImpl(msg.obj as SurfaceTexture) } } } companion object { private val TAG = HardwarePipeline::class.java.simpleName /** Check if OpenGL failed, and throw an exception if so */ private fun checkGlError(op: String) { val error = GLES20.glGetError() if (error != GLES20.GL_NO_ERROR) { val msg = op + ": glError 0x" + Integer.toHexString(error) Log.e(TAG, msg) throw RuntimeException(msg) } } } }
apache-2.0
f143009f088d7afb39ff2dcfc1b21c8f
38.086053
103
0.650774
4.795922
false
false
false
false
vase4kin/TeamCityApp
app/src/main/java/com/github/vase4kin/teamcityapp/TeamCityApplication.kt
1
3235
/* * Copyright 2020 Andrey Tolpeev * * 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.vase4kin.teamcityapp import android.app.Application import android.text.TextUtils import androidx.annotation.VisibleForTesting import com.github.vase4kin.teamcityapp.dagger.components.AppComponent import com.github.vase4kin.teamcityapp.dagger.components.DaggerAppComponent import com.github.vase4kin.teamcityapp.dagger.components.DaggerRestApiComponent import com.github.vase4kin.teamcityapp.dagger.components.RestApiComponent import com.github.vase4kin.teamcityapp.dagger.modules.AppModule import com.github.vase4kin.teamcityapp.dagger.modules.RestApiModule import dagger.android.AndroidInjector import dagger.android.DispatchingAndroidInjector import dagger.android.HasAndroidInjector import teamcityapp.libraries.utils.applyThemeFromSettings import javax.inject.Inject /** * TeamCityApplication class */ class TeamCityApplication : Application(), HasAndroidInjector { @Inject lateinit var activityInjector: DispatchingAndroidInjector<Any> lateinit var restApiInjector: RestApiComponent private set lateinit var appInjector: AppComponent private set override fun onCreate() { super.onCreate() // #=============== Dagger ================#// // app injector init // net injector init appInjector = DaggerAppComponent.builder() .appModule(AppModule(this)) .build() appInjector.inject(this) // Get default url val baseUrl = appInjector.sharedUserStorage().activeUser.teamcityUrl // Rest api init if (!TextUtils.isEmpty(baseUrl)) { buildRestApiInjectorWithBaseUrl(baseUrl) restApiInjector.inject(this) } // Theme applyThemeFromSettings() } /** * Build rest api injector with provided url */ fun buildRestApiInjectorWithBaseUrl(baseUrl: String) { restApiInjector = DaggerRestApiComponent.builder() .restApiModule(RestApiModule(baseUrl)) .appComponent(appInjector) .build() restApiInjector.inject(this) } /** * Setter for RestApiInjector */ @VisibleForTesting fun setRestApiInjector(restApiComponent: RestApiComponent) { this.restApiInjector = restApiComponent this.restApiInjector.inject(this) } /** * Setter for AppInjector */ @VisibleForTesting fun setAppInjector(appComponent: AppComponent) { this.appInjector = appComponent this.appInjector.inject(this) } override fun androidInjector(): AndroidInjector<Any> { return activityInjector } }
apache-2.0
a72a73ec186aa384a401d0d485563d5f
31.029703
79
0.710355
4.908953
false
false
false
false
google/ksp
integration-tests/src/test/kotlin/com/google/devtools/ksp/test/BuildCacheIT.kt
1
1382
package com.google.devtools.ksp.test import org.gradle.testkit.runner.GradleRunner import org.gradle.testkit.runner.TaskOutcome import org.junit.Assert import org.junit.Rule import org.junit.Test import java.io.File class BuildCacheIT { @Rule @JvmField val project1: TemporaryTestProject = TemporaryTestProject("buildcache", "playground") @Rule @JvmField val project2: TemporaryTestProject = TemporaryTestProject("buildcache", "playground") @Test fun testBuildCache() { val buildCacheDir = File(project1.root, "build-cache").absolutePath.replace(File.separatorChar, '/') File(project1.root, "gradle.properties").appendText("\nbuildCacheDir=$buildCacheDir") File(project2.root, "gradle.properties").appendText("\nbuildCacheDir=$buildCacheDir") GradleRunner.create().withProjectDir(project1.root).withArguments( "--build-cache", ":workload:clean", "build" ).build().let { Assert.assertEquals(TaskOutcome.SUCCESS, it.task(":workload:kspKotlin")?.outcome) } GradleRunner.create().withProjectDir(project2.root).withArguments( "--build-cache", ":workload:clean", "build" ).build().let { Assert.assertEquals(TaskOutcome.FROM_CACHE, it.task(":workload:kspKotlin")?.outcome) } } }
apache-2.0
adf3de70225a5b5d61a516e8fc012b61
32.707317
108
0.667149
4.387302
false
true
false
false
petrbalat/jlib
src/test/java/cz/softdeluxe/jlib/coroutine/SequenceTest.kt
1
812
package cz.softdeluxe.jlib.coroutine import org.junit.Test import kotlin.coroutines.experimental.buildSequence import kotlin.test.assertEquals /** * Created by balat on 3.2.2017. */ val fibonacci: Sequence<Long> = buildSequence { yield(1L) // first Fibonacci number var cur = 1L var next = 1L while (true) { yield(next) // next Fibonacci number val tmp = cur + next cur = next next = tmp } } class SequenceTest { @Test fun testFibonacci() { val fibList: List<Long> = fibonacci.take(60).toList() assertEquals(1, fibList[0]) assertEquals(1, fibList[1]) assertEquals(2, fibList[2]) assertEquals(89, fibList[10]) assertEquals(6765, fibList[19]) assertEquals(139583862445, fibList[54]) } }
apache-2.0
d5f484731dc65e643d1e0c82fd9180cd
21.583333
61
0.630542
3.657658
false
true
false
false
vsch/idea-multimarkdown
src/main/java/com/vladsch/md/nav/settings/MdApplicationSettings.kt
1
12042
// 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.settings import com.intellij.ide.ui.LafManager import com.intellij.ide.ui.LafManagerListener import com.intellij.openapi.Disposable import com.intellij.openapi.application.Application import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.components.ServiceManager import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.util.Disposer import com.vladsch.flexmark.util.data.DataKey import com.vladsch.md.nav.settings.api.MdApplicationSettingsExtensionProvider import com.vladsch.md.nav.settings.api.MdExtendableSettings import com.vladsch.md.nav.settings.api.MdExtendableSettingsImpl import com.vladsch.md.nav.settings.api.MdSettingsExtension import com.vladsch.plugin.util.LazyRunnable import com.vladsch.plugin.util.ListenersRunner import com.vladsch.plugin.util.ui.SettableForm import org.jdom.Element import org.jetbrains.annotations.TestOnly import javax.swing.UIManager class MdApplicationSettings(val isUnitTestMode: Boolean) : MdApplicationSettingsHolder , LafManagerListener , Disposable { constructor() : this(false) private val mySharedState = SharedState() private val myLocalState = LocalState() private var groupNotifications = 0 private var havePendingSettingsChanged = false private var isLastLAFWasDarcula = isDarcula private val documentSettingsUpdaters = ListenersRunner<SettableForm<MdApplicationSettingsHolder>>() val isDarcula: Boolean get() = !isUnitTestMode && isDarcula(LafManager.getInstance().currentLookAndFeel) // used to get current document settings which may not have been applied yet fun addDocumentSettingsUpdater(updater: SettableForm<MdApplicationSettingsHolder>) { documentSettingsUpdaters.addListener(updater) } fun removeDocumentSettingsUpdater(updater: SettableForm<MdApplicationSettingsHolder>) { documentSettingsUpdaters.removeListener(updater) } fun getUpdatedDocumentSettings(): MdApplicationSettingsHolder { var documentSettings = MdDocumentSettings(documentSettings) val applicationSettings = object : MdApplicationSettingsHolder, MdWasShownSettings.Holder by this , MdDocumentSettings.Holder , MdDebugSettings.Holder by this { override var documentSettings: MdDocumentSettings get() = documentSettings set(value) { documentSettings = MdDocumentSettings(value) } override fun <T : MdSettingsExtension<T>> getExtension(key: DataKey<T>): T { return [email protected](key) } override fun <T : MdSettingsExtension<T>> setExtension(value: T) { [email protected](value) } } documentSettingsUpdaters.fire { it.apply(applicationSettings) } return applicationSettings } fun resetDocumentSettings(settings: MdApplicationSettingsHolder) { documentSettingsUpdaters.fire { it.reset(settings) } } override fun lookAndFeelChanged(source: LafManager) { val newLookAndFeel = source.currentLookAndFeel val isNewLookAndFeelDarcula = isDarcula(newLookAndFeel) if (isNewLookAndFeelDarcula == isLastLAFWasDarcula) { return } notifyOnSettingsChangedRaw() isLastLAFWasDarcula = isNewLookAndFeelDarcula } init { if (!isUnitTestMode) { val settingsConnection = ApplicationManager.getApplication().messageBus.connect(this) settingsConnection.subscribe(LafManagerListener.TOPIC, this) ApplicationManager.getApplication().invokeLater { notifyOnSettingsChangedRaw() } } } override fun dispose() { } fun getSharedState(): SharedState { return mySharedState } fun getLocalState(): LocalState { return myLocalState } override fun <T : MdSettingsExtension<T>> getExtension(key: DataKey<T>): T { if (myLocalState.hasExtensionPoint(key)) { return myLocalState.getExtension(key) } return mySharedState.getExtension(key) } override fun <T : MdSettingsExtension<T>> setExtension(value: T) { val key = value.key if (myLocalState.hasExtensionPoint(key)) { return myLocalState.setExtension(value) } return mySharedState.setExtension(value) } override var documentSettings: MdDocumentSettings get() = myLocalState.documentSettings set(settings) { myLocalState.documentSettings.copyFrom(settings) notifyOnSettingsChangedRaw() } override var wasShownSettings: MdWasShownSettings get() = myLocalState.wasShownSettings set(settings) { myLocalState.wasShownSettings.copyFrom(settings) notifyOnSettingsChangedRaw() } override var debugSettings: MdDebugSettings get() = myLocalState.debugSettings set(settings) { myLocalState.debugSettings.copyFrom(settings) notifyOnSettingsChangedRaw() } fun groupNotifications(runnable: Runnable) { startGroupChangeNotifications() try { runnable.run() } finally { endGroupChangeNotifications() } } private fun startGroupChangeNotifications() { if (groupNotifications == 0) { havePendingSettingsChanged = false } groupNotifications++ } private fun endGroupChangeNotifications() { assert(groupNotifications > 0) { "endGroupNotifications called when groupNotifications is $groupNotifications" } if (groupNotifications > 0) { groupNotifications-- if (groupNotifications == 0) { myLocalState.notifyPendingSettingsChanged() mySharedState.notifyPendingSettingsChanged() if (havePendingSettingsChanged) notifyOnSettingsChangedRaw() } } } fun notifyOnSettingsChangedRaw() { if (groupNotifications > 0) havePendingSettingsChanged = true else ApplicationManager.getApplication().messageBus.syncPublisher(SettingsChangedListener.TOPIC).onSettingsChange(this) } class SharedState(private val mySettingsExtensions: MdExtendableSettingsImpl = MdExtendableSettingsImpl()) : ComponentItemHolder(), MdExtendableSettings by mySettingsExtensions { init { initializeExtensions(this) mySettingsExtensions.addUnwrappedItems(addItems( )) } @TestOnly internal fun copyFrom(other: SharedState) { this.mySettingsExtensions.copyFrom(other) } override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false other as SharedState return mySettingsExtensions.equals(other) } override fun hashCode(): Int { val result = mySettingsExtensions.hashCode() return result } } class LocalState(private val mySettingsExtensions: MdExtendableSettingsImpl = MdExtendableSettingsImpl()) : ComponentItemHolder(), MdExtendableSettings by mySettingsExtensions { val documentSettings = MdDocumentSettings() val wasShownSettings = MdWasShownSettings() val debugSettings = MdDebugSettings() init { initializeExtensions(this) // need to add extensions of extendable settings in case they saved by rendering profile // one caveat is that if the main settings are loaded then the extensions need to be copied from // the original otherwise these will load into a discarded object and not have any values val tagItemHolder = mySettingsExtensions.addUnwrappedItems(addItems( UnwrappedSettings(documentSettings), UnwrappedSettings(debugSettings), UnwrappedSettings(wasShownSettings) )) documentSettings.addUnwrappedItems(this, tagItemHolder) debugSettings.addUnwrappedItems(this, tagItemHolder) wasShownSettings.addUnwrappedItems(this, tagItemHolder) } override fun loadState(element: Element?) { super.loadState(element) documentSettings.migrateSettings(this) } @TestOnly internal fun copyFrom(other: LocalState) { documentSettings.copyFrom(other.documentSettings) wasShownSettings.copyFrom(other.wasShownSettings) debugSettings.copyFrom(other.debugSettings) this.mySettingsExtensions.copyFrom(other) } override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false other as LocalState if (documentSettings != other.documentSettings) return false if (wasShownSettings != other.wasShownSettings) return false if (debugSettings != other.debugSettings) return false return mySettingsExtensions == other } override fun hashCode(): Int { var result = mySettingsExtensions.hashCode() result = 31 * result + documentSettings.hashCode() result = 31 * result + wasShownSettings.hashCode() result = 31 * result + debugSettings.hashCode() return result } } @TestOnly fun copyFrom(other: MdApplicationSettings) { assert(isUnitTestMode) myLocalState.copyFrom(other.myLocalState) mySharedState.copyFrom(other.mySharedState) } override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false other as MdApplicationSettings if (mySharedState != other.mySharedState) return false if (myLocalState != other.myLocalState) return false return true } override fun hashCode(): Int { var result = mySharedState.hashCode() result = 31 * result + myLocalState.hashCode() return result } companion object { private val LOG = Logger.getInstance("com.vladsch.md.nav.settings") @JvmStatic fun isDarcula(laf: UIManager.LookAndFeelInfo?): Boolean { return laf?.name?.contains("Darcula") ?: false } private val dummyInstance: MdApplicationSettings by lazy { MdApplicationSettings(true) } private val componentsLoaded = LazyRunnable(Runnable { // NOTE: our shared and local state is provided by separate services, // these need to be instantiated so their state is loaded and will be saved. // The same for application settings extension services. MdApplicationSharedSettings.getInstance() MdApplicationLocalSettings.getInstance() for (extension in MdApplicationSettingsExtensionProvider.EP_NAME.extensions) { extension.initializeApplicationSettingsService() } }) @JvmStatic val instance: MdApplicationSettings get() { val application: Application? = ApplicationManager.getApplication() return if (application?.isUnitTestMode != false) { dummyInstance } else { val service = ServiceManager.getService(MdApplicationSettings::class.java) componentsLoaded.hasRun Disposer.register(ApplicationManager.getApplication().messageBus, service) service } } } }
apache-2.0
f3dd61685b0b662bf26f56a26629d0c6
35.601824
182
0.668909
5.501142
false
false
false
false
http4k/http4k
http4k-core/src/main/kotlin/org/http4k/lens/delegatedProperties.kt
1
2031
package org.http4k.lens import kotlin.properties.ReadOnlyProperty typealias Prop<OUT> = ReadOnlyProperty<Any?, OUT> interface DelegatedPropertyLensSpec<Req, OUT, Opt> { fun required(): Prop<Req> fun optional(): Prop<Opt> fun defaulted(default: OUT): Prop<Req> } @JvmName("named") fun <IN : Any, OUT, L : LensBuilder<IN, OUT>> L.of() = object : DelegatedPropertyLensSpec<Lens<IN, OUT>, OUT, Lens<IN, OUT?>> { override fun required() = Prop { _, p -> [email protected](p.name) } override fun optional() = Prop { _, p -> [email protected](p.name) } override fun defaulted(default: OUT) = Prop { _, property -> [email protected](property.name, default) } } @JvmName("namedList") fun <IN : Any, OUT, L : LensBuilder<IN, List<OUT>>> L.of() = object : DelegatedPropertyLensSpec<Lens<IN, List<OUT>>, List<OUT>, Lens<IN, List<OUT>?>> { override fun required() = Prop { _, p -> [email protected](p.name) } override fun optional() = Prop { _, p -> [email protected](p.name) } override fun defaulted(default: List<OUT>) = Prop { _, p -> [email protected](p.name, default) } } @JvmName("namedBiDi") fun <IN : Any, OUT, L : BiDiLensBuilder<IN, OUT>> L.of() = object : DelegatedPropertyLensSpec<BiDiLens<IN, OUT>, OUT, BiDiLens<IN, OUT?>> { override fun required() = Prop { _, p -> [email protected](p.name) } override fun optional() = Prop { _, p -> [email protected](p.name) } override fun defaulted(default: OUT) = Prop { _, p -> [email protected](p.name, default) } } @JvmName("namedBiDiList") fun <IN : Any, OUT, L : BiDiLensBuilder<IN, List<OUT>>> L.of() = object : DelegatedPropertyLensSpec<BiDiLens<IN, List<OUT>>, List<OUT>, BiDiLens<IN, List<OUT>?>> { override fun required() = Prop { _, p -> [email protected](p.name) } override fun optional() = Prop { _, p -> [email protected](p.name) } override fun defaulted(default: List<OUT>) = Prop { _, p -> [email protected](p.name, default) } }
apache-2.0
05dc9da65c5906e5e7590bee4a83b33a
38.823529
112
0.625308
3.324059
false
false
false
false
microg/android_packages_apps_GmsCore
play-services-nearby-core/src/main/kotlin/org/microg/gms/nearby/exposurenotification/CleanupService.kt
1
2230
/* * SPDX-FileCopyrightText: 2020, microG Project Team * SPDX-License-Identifier: Apache-2.0 */ package org.microg.gms.nearby.exposurenotification import android.app.AlarmManager import android.app.PendingIntent import android.content.Context import android.content.Intent import androidx.lifecycle.LifecycleService import androidx.lifecycle.lifecycleScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.delay import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import org.microg.gms.common.ForegroundServiceContext class CleanupService : LifecycleService() { override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int { ForegroundServiceContext.completeForegroundService(this, intent, TAG) super.onStartCommand(intent, flags, startId) if (isNeeded(this)) { lifecycleScope.launchWhenStarted { withContext(Dispatchers.IO) { var workPending = true while (workPending) { ExposureDatabase.with(this@CleanupService) { workPending = !it.dailyCleanup() } if (workPending) delay(5000L) } ExposurePreferences(this@CleanupService).lastCleanup = System.currentTimeMillis() } stop() } } else { stop() } return START_NOT_STICKY } fun stop() { val alarmManager = getSystemService(Context.ALARM_SERVICE) as AlarmManager val pendingIntent = PendingIntent.getService(applicationContext, CleanupService::class.java.name.hashCode(), Intent(applicationContext, CleanupService::class.java), PendingIntent.FLAG_ONE_SHOT or PendingIntent.FLAG_UPDATE_CURRENT) alarmManager.set(AlarmManager.RTC, ExposurePreferences(this).lastCleanup + CLEANUP_INTERVAL, pendingIntent) stopSelf() } companion object { fun isNeeded(context: Context): Boolean { return ExposurePreferences(context).let { it.enabled && it.lastCleanup < System.currentTimeMillis() - CLEANUP_INTERVAL } } } }
apache-2.0
cdc375c80517d7f12f1e5cb20c77a7d6
37.448276
238
0.657848
4.988814
false
false
false
false
Aunmag/a-zombie-shooter-game
src/main/java/aunmag/shooter/environment/terrain/Terrain.kt
1
3706
package aunmag.shooter.environment.terrain import aunmag.nightingale.Application import aunmag.nightingale.Configs import aunmag.nightingale.structures.Texture import aunmag.nightingale.utilities.UtilsGraphics import aunmag.shooter.client.App import org.lwjgl.opengl.GL11 class Terrain { private val blockSize = 4 private val shader = ShaderTerrain() private val texture: Texture private val textureQuantity: Int init { textureQuantity = Math.ceil( (Application.getCamera().distanceView + blockSize) / blockSize.toDouble() ).toInt() val size = (blockSize * textureQuantity).toFloat() texture = Texture.getOrCreate( "images/textures/terrain", Texture.Type.SPRITE, null, null, size, size ) } fun render() { if (App.main.isDebug) { renderGrid() } else { renderTexture() } } private fun renderTexture() { val camera = Application.getCamera() val offsetX = calculateAxisOffset(camera.position.x, blockSize / 2.0f) val offsetY = calculateAxisOffset(camera.position.y, blockSize / 2.0f) val x = camera.position.x + offsetX - (camera.position.x - offsetX) % blockSize val y = camera.position.y + offsetY - (camera.position.y - offsetY) % blockSize val projection = camera.calculateViewProjection(x, y, 0.0f) shader.bind() shader.setUniformProjection(projection) shader.setUniformQuantity(textureQuantity) texture.bind() texture.render() shader.setUniformQuantity(1) } private fun calculateAxisOffset(value: Float, offset: Float): Float { return when { value > +offset -> +offset value < -offset -> -offset else -> 0.0f } } private fun renderGrid() { val camera = Application.getCamera() val step = 1.0f val size = camera.distanceView / camera.scaleFull * Configs.getPixelsPerMeter() val center = removeRemainder(size * 1.25f, step * 2.0f) / 2.0f val xMin = camera.position.x - center val xMax = camera.position.x + center val yMin = camera.position.y - center val yMax = camera.position.y + center val gridX = removeRemainder(camera.position.x, step) val gridY = removeRemainder(camera.position.y, step) UtilsGraphics.drawPrepare() updateColor(0) var counter = -center + step while (counter <= center) { val x = gridX + counter * calculateMagnitude(camera.position.x) val y = gridY + counter * calculateMagnitude(camera.position.y) val isCenterByX = x == 0.0f if (isCenterByX) updateColor(1) UtilsGraphics.drawLine(x, yMin, x, yMax, true) if (isCenterByX) updateColor(0) val isCenterByY = y == 0.0f if (isCenterByY) updateColor(-1) UtilsGraphics.drawLine(xMin, y, xMax, y, true) if (isCenterByY) updateColor(0) counter += step } } private fun removeRemainder(value: Float, remainder: Float): Float { return value - value % remainder } private fun calculateMagnitude(value: Float): Float { return if (value < 0) { -1.0f } else { +1.0f } } private fun updateColor(axis: Int) { val max = 1.0f val min = 0.4f when (axis) { +1 -> GL11.glColor3f(max, min, min) -1 -> GL11.glColor3f(min, min, max) else -> GL11.glColor3f(min, min, min) } } }
apache-2.0
c509ef61429d6a465c0963b8035ec53c
29.130081
89
0.593092
4.108647
false
false
false
false
Aidanvii7/Toolbox
paging/src/main/java/com/aidanvii/toolbox/paging/PagedList.kt
1
20349
package com.aidanvii.toolbox.paging import androidx.annotation.IntRange import com.aidanvii.toolbox.Action import com.aidanvii.toolbox.Consumer import com.aidanvii.toolbox.checkAboveMin import com.aidanvii.toolbox.checkInBounds import com.aidanvii.toolbox.paging.PagedList.Companion.UNDEFINED import com.aidanvii.toolbox.paging.PagedList.DataSource import com.aidanvii.toolbox.paging.PagedList.DataSource.Page import com.aidanvii.toolbox.paging.PagedList.DataSource.Page.Builder import com.aidanvii.toolbox.paging.PagedList.ElementState import io.reactivex.Maybe import io.reactivex.Observable import io.reactivex.disposables.Disposable import io.reactivex.exceptions.OnErrorNotImplementedException import io.reactivex.subjects.BehaviorSubject private val onErrorStub: Consumer<Throwable> = { throw OnErrorNotImplementedException(it) } /** * A [PagedList] is a form of list that lazily loads its data in chunks ([DataSource.Page]) from a [DataSource]. * * Items can be retrieved with [get] or simply accessed via [loadAround] - both may trigger a call to [DataSource.loadPage]. * * To listen for changes, you may observe either [distinctObservableList], [observableListNonNull] or [observableChangePayload]. * * Typical usage would be to: * * 1st - Subscribe to either [distinctObservableList], [observableListNonNull] or [observableChangePayload] * * 2nd - Use [DiffUtil.calculateDiff] on a background thread to determined the changes * * 3rd - Update the [RecyclerView.Adapter] with the newly observed list * * 4th - Apply the calculated [DiffUtil.DiffResult] to the [RecyclerView.Adapter] (immediately after last step) * * 5th - Forward calls from the [RecyclerView.Adapter.onBindViewHolder] to [PagedList.loadAround] with the adapter position to trigger pagination calls to the provided [DataSource] * * @param dataSource The [DataSource] implementation that will provide the data. * @param pageSize The length of data that will determine the [DataSource.Page.Builder.pageSize]. May by [UNDEFINED] if unknown. * @param prefetchDistance Determines the range of elements to scan when [get] or [loadAround] is called. If elements in the scanned range are [ElementState.EMPTY] or [ElementState.DIRTY], [DataSource.loadPage] will be called at least once. * @param loadInitialPages Optional [IntArray] of page indexes. Non-zero indexing (first page is 1). * @param publishChangesOnInit Determines whether any subscribers to [distinctObservableList], [observableListNonNull] or [observableChangePayload] will be notified upon subscription when no changes to the data have been made (the initial empty state). * @param synchroniseAccess Determines whether access to the internal data is synchronised for the case where [get] or [loadAround] may be called from different threads. * @param onError Errors when loading pages will be passed here. The default implementation will throw a [OnErrorNotImplementedException]. * @param pageLoader The [PageLoader] that coordinates calls to the provided [DataSource]. */ class PagedList<T : Any>( dataSource: DataSource<T>, pageSize: Int = UNDEFINED, val prefetchDistance: Int = 0, loadInitialPages: IntArray? = null, publishChangesOnInit: Boolean = true, synchroniseAccess: Boolean = false, private val onError: Consumer<Throwable> = onErrorStub, private val pageLoader: PageLoader<T> = PageLoader.Default() ) : Disposable by pageLoader { companion object { const val UNDEFINED = 0 } /** * A [DataSource] is responsible for supplying the [PagedList] with data in the form of a [Page]. * * The [PagedList] will call [loadPage] when it requires a new [Page]. * */ interface DataSource<T> { /** * Represents the count of the data set that will be paged. If unknown this may be zero. * When a new value is emitted, the [PagedList] will resize itself. */ val dataCount: Observable<Int> /** * Called when the [PagedList] requires a new page. */ fun loadPage(pageBuilder: Page.Builder<T>): Maybe<Page<T>> /** * Provide am 'empty' value for the given position. * * This is called to fill 'not-yet-loaded' elements with some default instance, defaults to null. */ fun emptyAt(index: Int = UNDEFINED): T? = null /** * Represents a page in the [PagedList]. The [pageData] size cannot exceed the given [Builder.pageSize] */ class Page<out T> private constructor(val pageNumber: Int, val pageData: List<T>) { /** * Used to build a single [Page]. Call [build] */ class Builder<T> internal constructor(val pageNumber: Int, val pageSize: Int) { var used = false fun build(pageData: List<T>): Page<T> { if (used) throw IllegalStateException("Cannot build the same page twice!") used = true if (pageSize != UNDEFINED) { pageData.size.checkInBounds(0, pageSize, "given pageData has wrong size, should be between 0 and $pageSize") } return Page(pageNumber, pageData) } } } } /** * Represents the current state of an element in the [PagedList] */ enum class ElementState { /** * The element does not have a value, and no requests for it are in-flight. */ EMPTY, /** * The element does not have a value, though a request for it is in-flight. */ LOADING, /** * The element has a value, and no requests for it are in-flight. */ LOADED, /** * The element has a value, and no requests for it are in-flight, * but is considered 'dirty' and treated like [EMPTY], where a request to update it can occur */ DIRTY, /** * The element has a value, but a request to update it is in-flight. */ REFRESHING } /** * Represents both a snapshot of and changes to the [PagedList], provided by [observableChangePayload]. * * If [observableChangePayload] will be used, the provided type [T] should implement [equals] and [hashCode] * as this will determine the [addedItems] and [removedItems] items. * * @param allItems a snapshot of the entire [PagedList] based on the last modification to the [PagedList] * @param removedItems a snapshot of the items that have been removed from the [PagedList] based on the last modification to the [PagedList] * @param addedItems a snapshot of the items that have been added to the [PagedList] based on the last modification to the [PagedList] */ data class ChangePayload<out T>( val allItems: List<T> = emptyList(), val removedItems: Set<T> = emptySet(), val addedItems: Set<T> = emptySet() ) private var lastAccessedIndex = UNDEFINED private var lastLoadedPageNumber = 1 private val pageSizeUndefined: Boolean private val changeSubject = BehaviorSubject.create<List<T?>>() private val elements = Elements(publishChangesOnInit, synchroniseAccess, onError, dataSource, changeSubject) /** * The provided page size, or 1 if [UNDEFINED] is provided. */ val pageSize: Int init { pageSize.checkAboveMin(UNDEFINED, "pageSize must be a positive number, or PagedList.UNDEFINED") pageSizeUndefined = pageSize == UNDEFINED this.pageSize = if (pageSizeUndefined) 1 else pageSize pageLoader.dataSource = dataSource elements.runSynchronised { loadInitialPages?.forEach { loadPage(it) } } } /** * The current size of the list, including also the elements that have the state [ElementState.EMPTY]. */ val size get() = elements.runSynchronised { elements.size } /** * A distinct Observable List of the paged data. List elements may be null. */ val distinctObservableList get(): Observable<List<T?>> = changeSubject.distinctUntilChanged().doOnDispose { dispose() } /** * An Observable List of the paged data. List elements may be null. */ val observableList get(): Observable<List<T?>> = changeSubject.doOnDispose { dispose() } /** * Convenience version of [distinctObservableList] that provides non-null elements. * * This only works if the provided [DataSource] always returns non-null values for [DataSource.emptyAt], * otherwise an [KotlinNullPointerException] will be thrown. */ val observableListNonNull get(): Observable<List<T>> = distinctObservableList.map { it.map { it!! } } /** * Version of [distinctObservableList] that provides data in the form of a [ChangePayload]. * * As null elements are filtered, it is recommended that the provided [DataSource] always return a non-null value for [DataSource.emptyAt] */ val observableChangePayload get(): Observable<ChangePayload<T>> = distinctObservableList .map { it.filterNotNull() } .scan(ChangePayload<T>()) { lastPayload, newItems -> ChangePayload( allItems = newItems, removedItems = lastPayload.allItems subtract newItems, addedItems = newItems subtract lastPayload.allItems ) } val lastIndex: Int get() = elements.runSynchronised { lastIndex } /** * Gets a snapshot in the form of a standard [List] of the current elements. */ fun asList(): List<T?> = elements.runSynchronised { asList() } /** * Resets the state of the elements in the range from [startIndex] to [endIndex] to [ElementState.EMPTY], * and resets the element value to an 'empty' element from [DataSource.emptyAt] from the provided [DataSource]. * * @param startIndex the starting zero-based element index * @param endIndex the ending zero-based element index * @param refreshElementsInRange optional param that will force pages within the given range to refresh. */ fun invalidateAsEmpty( startIndex: Int = 0, endIndex: Int = lastIndex, refreshElementsInRange: Boolean = false ) { invalidate(refreshElementsInRange) { elements.invalidateAsEmpty(startIndex, endIndex) } } /** * Resets the state of the elements in the range from [startIndex] to [endIndex] that have the state [ElementState.LOADED] to [ElementState.DIRTY]. * * @param startIndex the starting zero-based element index * @param endIndex the ending zero-based element index * @param refreshElementsInRange optional param that will force pages within the given range to refresh. */ fun invalidateLoadedAsDirty( startIndex: Int = 0, endIndex: Int = lastIndex, refreshElementsInRange: Boolean = false ) { invalidate(refreshElementsInRange) { elements.invalidateLoadedAsDirty(startIndex, endIndex) } } /** * If the element at the given index, or any elements in range of the provided [prefetchDistance] * is considered 'empty' or 'dirty' (see [ElementState.EMPTY], [ElementState.DIRTY]), * It will trigger one or more pagination calls to [DataSource.loadPage] for those elements. * @param index the element to 'access' * @param growIfNecessary optional param that will cause the list to grow to the correct size if [index] exceeds [size] - 1 */ fun loadAround(@IntRange(from = 0) index: Int, growIfNecessary: Boolean = false) { elements.runSynchronised { if (growIfNecessary) { growIfNecessary(index + 1) } else if (!indexInBounds(index)) { throw IndexOutOfBoundsException("index: $index is out of bounds. current size is ${size}") } access(index) } } /** * Similar to [loadAround] but works with pageNumber indexes as opposed to element indexes. * @param pageNumber a non-zero based index for the pageNumber (the first pageNumber is not 0, it is 1) * @param growIfNecessary optional param that will cause the list to grow to the correct size if [pageNumber] exceeds [size] + [pageSize] - 1 */ fun loadAroundPage(pageNumber: Int, growIfNecessary: Boolean = false) { elements.runSynchronised { startingIndexOfPage(pageNumber).let { pageStartingIndex -> if (growIfNecessary) { elements.growIfNecessary(pageStartingIndex + pageSize) } else if (!elements.indexInBounds(startingIndexOfPage(pageNumber))) { throw IndexOutOfBoundsException( "pageNumber: $pageNumber is out of bounds. max pageNumber is ${currentPageForIndex( pageStartingIndex )}" ) } access(pageStartingIndex) } } } /** * Retrieves the element at the given index which may be null, * or a default 'empty' element from [DataSource.emptyAt] from the provided [DataSource]. * * Also calls [loadAround]. */ fun get(index: Int): T? { return elements.runSynchronised { loadAround(index, growIfNecessary = false) peek(index) } } /** * Retrieves the element at the given index which may be null, * or a default 'empty' element from [DataSource.emptyAt] from the provided [DataSource]. * * Unlike [get], this will not call [loadAround], so no pagination calls will be triggered. */ fun peek(index: Int): T? = elements.runSynchronised { get(index) } /** * Gets the [ElementState] for the given index. */ fun elementStateFor(index: Int): ElementState = elements.runSynchronised { elementStateFor(index) } /** * If any elements within the given page are [ElementState.EMPTY] or [ElementState.DIRTY], * [DataSource.loadPage] will be called on the provided [DataSource]. * * @param page a non-zero based index for the page (the first page is not 0, it is 1) */ fun loadPage(pageNumber: Int = lastLoadedPageNumber): Maybe<Page<T>> { pageNumber.checkAboveMin(0, "pageNumber must be greater than 0") elements.runSynchronised { val pageStartIndex = startingIndexOfPage(pageNumber) val pageEndIndex = endIndexOfPageFromStartingIndex(pageStartIndex) for (index in pageStartIndex..pageEndIndex) { if (isEmpty(index)) setLoading(index) else setRefreshingIfDirty(index) } } lastLoadedPageNumber = pageNumber return pageLoader.loadPage( pageBuilder = DataSource.Page.Builder(pageNumber, if (pageSizeUndefined) UNDEFINED else pageSize), onDisposeOrErrorOrComplete = { resetPageToEmpty(pageNumber) }, onError = onError, onSuccess = this::populatePage ) } private fun access(index: Int) { for (pageNumber in pageNumbersForIndex(index)) { pageLoader.accessed(index) if (shouldLoadPage(pageNumber)) { loadPage(pageNumber) } } lastAccessedIndex = index } private fun shouldLoadPage(pageNumber: Int): Boolean { val pageStartIndex = startingIndexOfPage(pageNumber) val pageEndIndex = endIndexOfPageFromStartingIndex(pageStartIndex) return (pageStartIndex..pageEndIndex).any { elements.isEmptyOrDirty(it) } } private fun pageNumbersForIndex(index: Int): IntArray { return when { accessIsIncrementallySequential(index) -> getIncrementallySequentialPageIfNecessary(index).let { indexToPageNumberList(it) } accessIsDecrementallySequential(index) -> getDecrementallySequentialPageIfNecessary(index).let { indexToPageNumberList(it) } else -> getPages(fromPage = firstPageInRangeForIndex(index), toPage = lastPageInRangeForIndex(index)) } } private fun accessIsIncrementallySequential(index: Int) = (lastAccessedIndex != UNDEFINED) && lastAccessedIndex == index - 1 private fun accessIsDecrementallySequential(index: Int) = (lastAccessedIndex != UNDEFINED) && lastAccessedIndex == index + 1 private fun getIncrementallySequentialPageIfNecessary(index: Int): Int = clamped(index + prefetchDistance).let { if (sequentialAccessCrossesPageBoundary( indexWithPrefetchOffset = it, previousIndexWithPrefetchOffset = clamped(lastAccessedIndex + prefetchDistance) ) ) it else UNDEFINED } private fun getDecrementallySequentialPageIfNecessary(index: Int): Int = clamped(index - prefetchDistance).let { if (sequentialAccessCrossesPageBoundary( indexWithPrefetchOffset = it, previousIndexWithPrefetchOffset = clamped(lastAccessedIndex - prefetchDistance) ) ) it else UNDEFINED } private fun indexToPageNumberList(index: Int) = if (index != UNDEFINED) { currentPageForIndex(index).let { pageNumber -> if (pageNumber != UNDEFINED) intArrayOf(pageNumber) else intArrayOf() } } else intArrayOf() private fun sequentialAccessCrossesPageBoundary( indexWithPrefetchOffset: Int, previousIndexWithPrefetchOffset: Int ) = currentPageForIndex(indexWithPrefetchOffset) != currentPageForIndex(previousIndexWithPrefetchOffset) private fun getPages(fromPage: Int, toPage: Int): IntArray { return if (fromPage <= toPage) { ((toPage - fromPage) + 1).let { size -> IntArray(size).also { pages -> var currentPage = fromPage for (index in 0 until size) pages[index] = currentPage++ } } } else intArrayOf() // no reverse support } private fun currentPageForIndex(index: Int): Int = (index / pageSize) + 1 private fun firstPageInRangeForIndex(index: Int): Int = currentPageForIndex(Math.max(index - prefetchDistance, 0)) private fun lastPageInRangeForIndex(index: Int): Int = currentPageForIndex(Math.min(index + prefetchDistance, elements.size - 1)) private fun startingIndexOfPage(pageNumber: Int): Int = (pageSize * (pageNumber - 1)) private fun endIndexOfPageFromStartingIndex(pageStartingIndex: Int) = clamped(pageStartingIndex + pageSize - 1) private fun clamped(index: Int) = index.let { if (it >= elements.size) elements.size - 1 else if (it < 0) 0 else it } private fun populatePage(page: DataSource.Page<T>) { page.apply { pageNumber.checkAboveMin(0, "pageNumber must be greater than 0") startingIndexOfPage(pageNumber).let { pageStartingIndex -> elements.runSynchronised { (pageStartingIndex + pageData.size).let { newSize -> growIfNecessary(newSize) } pageData.mapIndexed { index, item -> val offsetIndex = pageStartingIndex + index setLoaded(offsetIndex, item) } } } } } private fun resetPageToEmpty(pageNumber: Int) { elements.runSynchronised { val pageStartIndex = startingIndexOfPage(pageNumber) val pageEndIndex = endIndexOfPageFromStartingIndex(pageStartIndex) for (index in pageStartIndex..pageEndIndex) { if (indexInBounds(index)) { setEmpty(index) } } } } private inline fun invalidate(refreshElementsInRange: Boolean, invalidateElements: Action) { elements.runSynchronised { invalidateElements() } dispose() this.lastAccessedIndex.let { lastAccessedIndex -> if (refreshElementsInRange) { loadAround(lastAccessedIndex) } } } }
apache-2.0
243a58dc919ef8a6f77314349d947813
42.669528
252
0.653103
4.722441
false
false
false
false
ankidroid/Anki-Android
AnkiDroid/src/androidTest/java/com/ichi2/anki/tests/libanki/HttpTest.kt
1
5077
/*************************************************************************************** * * * Copyright (c) 2018 Mike Hardy <[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.anki.tests.libanki import android.Manifest import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.test.platform.app.InstrumentationRegistry import androidx.test.rule.GrantPermissionRule import com.ichi2.async.Connection import com.ichi2.libanki.sync.HostNum import com.ichi2.utils.NetworkUtils import org.junit.Assert import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith @RunWith(AndroidJUnit4::class) class HttpTest { @get:Rule var runtimeStoragePermissionRule = GrantPermissionRule.grant( Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.INTERNET, Manifest.permission.ACCESS_NETWORK_STATE ) // #7108: AsyncTask @Suppress("DEPRECATION") @Test fun testLogin() { val username = "AnkiDroidInstrumentedTestUser" val password = "AnkiDroidInstrumentedTestInvalidPass" val invalidPayload = Connection.Payload(arrayOf(username, password, HostNum(null))) val testListener = TestTaskListener(invalidPayload) // We have to carefully run things on the main thread here or the threading protections in BaseAsyncTask throw // The first one is just to run the static initializer, really val onlineRunnable = Runnable { try { Class.forName("com.ichi2.async.Connection") } catch (e: Exception) { Assert.fail("Unable to load Connection class: " + e.message) } } InstrumentationRegistry.getInstrumentation().runOnMainSync(onlineRunnable) // If we are not online this test is not nearly as interesting // TODO simulate offline programmatically - currently exercised by manually toggling an emulator offline pre-test if (!NetworkUtils.isOnline) { Connection.login(testListener, invalidPayload) Assert.assertFalse( "Successful login despite being offline", testListener.getPayload()!!.success ) Assert.assertTrue( "onDisconnected not called despite being offline", testListener.disconnectedCalled ) return } val r = Runnable { val conn = Connection.login(testListener, invalidPayload) try { // This forces us to synchronously wait for the AsyncTask to do it's work conn!!.get() } catch (e: Exception) { Assert.fail("Caught exception while trying to login: " + e.message) } } InstrumentationRegistry.getInstrumentation().runOnMainSync(r) Assert.assertFalse( "Successful login despite invalid credentials", testListener.getPayload()!!.success ) } class TestTaskListener(payload: Connection.Payload) : Connection.TaskListener { private var payload: Connection.Payload? = null var disconnectedCalled = false private fun setPayload(payload: Connection.Payload) { this.payload = payload } override fun onPreExecute() { // do nothing } override fun onProgressUpdate(vararg values: Any?) { // do nothing } fun getPayload(): Connection.Payload? { return payload } override fun onPostExecute(data: Connection.Payload) { // do nothing } override fun onDisconnected() { disconnectedCalled = true } init { setPayload(payload) } } }
gpl-3.0
629282d9f7435704d1674aa7e552c3d5
38.976378
121
0.556431
5.62237
false
true
false
false
ankidroid/Anki-Android
AnkiDroid/src/main/java/com/wildplot/android/parsing/AtomTypes/VariableAtom.kt
1
2341
/**************************************************************************************** * Copyright (c) 2014 Michael Goldbach <[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.wildplot.android.parsing.AtomTypes import com.wildplot.android.parsing.Atom.AtomType import com.wildplot.android.parsing.ExpressionFormatException import com.wildplot.android.parsing.TopLevelParser import com.wildplot.android.parsing.TreeElement import java.util.regex.Pattern class VariableAtom(private val varName: String, private val parser: TopLevelParser) : TreeElement { var atomType = AtomType.NUMBER @get:Throws(ExpressionFormatException::class) override val value: Double get() = if (atomType !== AtomType.INVALID) { parser.getVarVal(varName) } else { throw ExpressionFormatException("Number is Invalid, cannot parse") } override val isVariable: Boolean get() = true init { val p = Pattern.compile("[^a-zA-Z0-9]") val hasSpecialChar = p.matcher(varName).find() if (hasSpecialChar || varName.length <= 0) { atomType = AtomType.INVALID } } }
gpl-3.0
4b27b6c791e44e1a8766ba572f351a0c
51.022222
99
0.519009
5.456876
false
false
false
false
pdvrieze/ProcessManager
PMEditor/src/main/java/nl/adaptivity/process/ui/model/ProcessModelListOuterFragment.kt
1
6125
/* * Copyright (c) 2018. * * This file is part of ProcessManager. * * ProcessManager is free software: you can redistribute it and/or modify it under the terms of version 3 of the * GNU Lesser General Public License as published by the Free Software Foundation. * * ProcessManager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even * the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License along with ProcessManager. If not, * see <http://www.gnu.org/licenses/>. */ package nl.adaptivity.process.ui.model import android.app.Activity import android.content.Context import android.content.Intent import android.os.Bundle import nl.adaptivity.android.util.MasterDetailOuterFragment import nl.adaptivity.android.util.MasterListFragment.ListCallbacks import nl.adaptivity.process.editor.android.R import nl.adaptivity.process.ui.ProcessSyncManager import nl.adaptivity.process.ui.model.ProcessModelDetailFragment.ProcessModelDetailFragmentCallbacks import nl.adaptivity.sync.SyncManager /** * An activity representing a list of ProcessModels. This activity has different * presentations for handset and tablet-size devices. On handsets, the activity * presents a list of items, which when touched, lead to a * [ProcessModelDetailActivity] representing item details. On tablets, the * activity presents the list of items and item details side-by-side using two * vertical panes. * * * The activity makes heavy use of fragments. The list of items is a * [ProcessModelListFragment] and the item details (if present) is a * [ProcessModelDetailFragment]. * * * This activity also implements the required * [ListCallbacks] interface to listen for item * selections. */ class ProcessModelListOuterFragment constructor() : MasterDetailOuterFragment(R.layout.outer_processmodel_list, R.id.processmodel_list_container, R.id.processmodel_detail_container), ListCallbacks<SyncManager>, ProcessModelDetailFragmentCallbacks { private var mCallbacks: ProcessModelListCallbacks? = null interface ProcessModelListCallbacks { val syncManager: ProcessSyncManager? fun requestSyncProcessModelList(immediate: Boolean, minAge: Long) fun onInstantiateModel(id: Long, suggestedName: String) } public override fun createListFragment(args: Bundle?): ProcessModelListFragment { val listFragment = ProcessModelListFragment() if (args != null) { listFragment.arguments = args } return listFragment } @Suppress("DEPRECATION") override fun onAttach(activity: Activity) { super.onAttach(activity) if (activity is ProcessModelListCallbacks) { mCallbacks = activity } } override fun onStart() { super.onStart() if (mCallbacks != null) { mCallbacks!!.requestSyncProcessModelList(true, ProcessSyncManager.DEFAULT_MIN_AGE) } } /** * Callback method from [ListCallbacks] indicating * that the item with the given ID was selected. */ override fun onProcessModelSelected(processModelId: Long) { if (isTwoPane) { if (processModelId >= 0) { // In two-pane mode, show the detail view in this activity by // adding or replacing the detail fragment using a // fragment transaction. val arguments = Bundle() arguments.putLong(ProcessModelDetailFragment.ARG_ITEM_ID, processModelId) val fragment = ProcessModelDetailFragment() fragment.arguments = arguments childFragmentManager.beginTransaction() .replace(R.id.processmodel_detail_container, fragment) .commit() } else { val frag = childFragmentManager.findFragmentById(R.id.processmodel_detail_container) if (frag != null) { fragmentManager!!.beginTransaction() .remove(frag) .commit() } } } else { if (processModelId >= 0) { // In single-pane mode, simply start the detail activity // for the selected item ID. val detailIntent = Intent(activity, ProcessModelDetailActivity::class.java) detailIntent.putExtra(ProcessModelDetailFragment.ARG_ITEM_ID, processModelId) startActivity(detailIntent) } } } override val syncManager: ProcessSyncManager? get() { return mCallbacks!!.syncManager } override fun createDetailFragment(itemId: Long): ProcessModelDetailFragment { val fragment = ProcessModelDetailFragment() val arguments = Bundle() arguments.putLong(ProcessModelDetailFragment.ARG_ITEM_ID, itemId) fragment.arguments = arguments return fragment } override fun getDetailIntent(itemId: Long): Intent { val detailIntent = Intent(activity, ProcessModelDetailActivity::class.java) detailIntent.putExtra(ProcessModelDetailFragment.ARG_ITEM_ID, itemId) return detailIntent } override fun getTitle(context: Context): CharSequence { return context.getString(R.string.title_processmodel_list) } override fun onInstantiateModel(modelId: Long, suggestedName: String) { mCallbacks!!.onInstantiateModel(modelId, suggestedName) } companion object { fun newInstance(modelId: Long): ProcessModelListOuterFragment { val result = ProcessModelListOuterFragment() if (modelId != 0L) { result.arguments = MasterDetailOuterFragment.addArgs(null, modelId) } return result } } }
lgpl-3.0
7eaf03c4d1a1652eb0b416d63867fb29
37.043478
166
0.664
5.074565
false
false
false
false
tokenbrowser/token-android-client
app/src/main/java/com/toshi/view/custom/ProgressBar.kt
1
2526
/* * Copyright (c) 2017. Toshi Inc * * 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.toshi.view.custom import android.content.Context import android.graphics.Canvas import android.graphics.Paint import android.graphics.Rect import android.graphics.RectF import android.util.AttributeSet import android.view.View import com.toshi.R import com.toshi.extensions.getColorById import com.toshi.extensions.getPxSize class ProgressBar : View { private val backgroundColor by lazy { getColorById(R.color.web_view_progress_background) } private val foregroundColor by lazy { getColorById(R.color.web_view_progress_foreground) } private var bgRect: RectF? = null private var fgRect: RectF? = null private val paint by lazy { Paint() } private var progress = 0 constructor(context: Context): super(context) { init() } constructor(context: Context, attrs: AttributeSet): super(context, attrs) { init() } constructor(context: Context, attrs: AttributeSet, defStyle: Int): super(context, attrs, defStyle) { init() } private fun init() { val height = getPxSize(R.dimen.progress_height) bgRect = RectF(Rect(0, 0, right, height)) fgRect = RectF(Rect(0, 0, 0, height)) } override fun onDraw(canvas: Canvas?) { // Draw bg paint.color = backgroundColor canvas?.drawRect(bgRect, paint) // Draw fg val width = width.toDouble() * (progress.toDouble() / 100) paint.color = foregroundColor fgRect?.right = width.toFloat() canvas?.drawRect(fgRect, paint) if (progress == 100) animate() .alpha(0f) .setDuration(1000) .start() super.onDraw(canvas) } fun setProgress(progress: Int) { this.progress = progress invalidate() } }
gpl-3.0
2ba8daf4ef07d2cd98ab387ae446be08
30.5875
104
0.662708
4.127451
false
false
false
false
ekager/focus-android
app/src/main/java/org/mozilla/focus/web/GeckoWebViewProvider.kt
1
34956
/* -*- Mode: Java; c-basic-offset: 4; tab-width: 4; indent-tabs-mode: nil; -*- * 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 org.mozilla.focus.web import android.app.Activity import android.content.Context import android.content.SharedPreferences import android.net.Uri import android.os.Bundle import android.os.Environment import android.os.Parcelable import android.preference.PreferenceManager import android.text.TextUtils import android.util.AttributeSet import android.util.Log import android.view.View import android.webkit.WebSettings import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Dispatchers.IO import kotlinx.coroutines.Job import kotlinx.coroutines.launch import mozilla.components.browser.errorpages.ErrorPages import mozilla.components.browser.errorpages.ErrorType import mozilla.components.browser.session.Session import mozilla.components.concept.engine.HitResult import mozilla.components.lib.crash.handler.CrashHandlerService import mozilla.components.support.ktx.android.util.Base64 import mozilla.components.support.ktx.kotlin.isEmail import mozilla.components.support.ktx.kotlin.isGeoLocation import mozilla.components.support.ktx.kotlin.isPhone import org.json.JSONException import org.mozilla.focus.R import org.mozilla.focus.browser.LocalizedContent import org.mozilla.focus.ext.savedWebViewState import org.mozilla.focus.gecko.GeckoViewPrompt import org.mozilla.focus.gecko.NestedGeckoView import org.mozilla.focus.locale.LocaleManager import org.mozilla.focus.locale.Locales import org.mozilla.focus.telemetry.TelemetryWrapper import org.mozilla.focus.utils.AppConstants import org.mozilla.focus.utils.IntentUtils import org.mozilla.focus.utils.MobileMetricsPingStorage import org.mozilla.focus.utils.Settings import org.mozilla.focus.utils.UrlUtils import org.mozilla.focus.webview.SystemWebView import org.mozilla.geckoview.AllowOrDeny import org.mozilla.geckoview.GeckoResult import org.mozilla.geckoview.GeckoRuntime import org.mozilla.geckoview.GeckoRuntimeSettings import org.mozilla.geckoview.GeckoSession import org.mozilla.geckoview.GeckoSession.NavigationDelegate import org.mozilla.geckoview.GeckoSessionSettings import org.mozilla.geckoview.SessionFinder import org.mozilla.geckoview.WebRequestError import java.net.MalformedURLException import java.net.URL import java.util.Locale import kotlin.coroutines.CoroutineContext /** * WebViewProvider implementation for creating a Gecko based implementation of IWebView. */ @Suppress("TooManyFunctions") class GeckoWebViewProvider : IWebViewProvider { override fun preload(context: Context) { sendTelemetryEventOnSwitchToGecko(context) createGeckoRuntime(context) } private fun sendTelemetryEventOnSwitchToGecko(context: Context) { val settings = Settings.getInstance(context) if (!settings.shouldShowFirstrun() && settings.isFirstGeckoRun()) { PreferenceManager.getDefaultSharedPreferences(context) .edit().putBoolean(PREF_FIRST_GECKO_RUN, false).apply() Log.d(javaClass.simpleName, "Sending change to Gecko ping") TelemetryWrapper.changeToGeckoEngineEvent() } } override fun create(context: Context, attributeSet: AttributeSet?): View { return GeckoWebView(context, attributeSet) } override fun performCleanup(context: Context) { // Nothing: a WebKit work-around. } override fun performNewBrowserSessionCleanup() { // Nothing: a WebKit work-around. } private fun createGeckoRuntime(context: Context) { if (geckoRuntime == null) { val runtimeSettingsBuilder = GeckoRuntimeSettings.Builder() runtimeSettingsBuilder.useContentProcessHint(true) runtimeSettingsBuilder.blockMalware(Settings.getInstance(context).shouldUseSafeBrowsing()) runtimeSettingsBuilder.blockPhishing(Settings.getInstance(context).shouldUseSafeBrowsing()) runtimeSettingsBuilder.crashHandler(CrashHandlerService::class.java) runtimeSettingsBuilder.locales(arrayOf(getLocale(context))) geckoRuntime = GeckoRuntime.create(context.applicationContext, runtimeSettingsBuilder.build()) } } private fun getLocale(context: Context): String { val currentLocale = LocaleManager.getInstance().getCurrentLocale(context) return if (currentLocale != null) { Locales.getLanguageTag(currentLocale) } else { Locales.getLanguageTag(Locale.getDefault()) } } override fun requestMobileSite(context: Context, webSettings: WebSettings) { } override fun requestDesktopSite(webSettings: WebSettings) { } override fun applyAppSettings( context: Context, webSettings: WebSettings, systemWebView: SystemWebView ) { } override fun disableBlocking(webSettings: WebSettings, systemWebView: SystemWebView) { } override fun getUABrowserString(existingUAString: String, focusToken: String): String { return "" } @Suppress("LargeClass", "TooManyFunctions") class GeckoWebView(context: Context, attrs: AttributeSet?) : NestedGeckoView(context, attrs), IWebView, SharedPreferences.OnSharedPreferenceChangeListener, CoroutineScope { private var callback: IWebView.Callback? = null private var findListener: IFindListener? = null private var currentUrl: String = ABOUT_BLANK private var canGoBack: Boolean = false private var canGoForward: Boolean = false private var isSecure: Boolean = false private var geckoSession: GeckoSession private var webViewTitle: String? = null private var isLoadingInternalUrl = false private lateinit var finder: SessionFinder private var restored = false private var job = Job() override val coroutineContext: CoroutineContext get() = job + Dispatchers.Main init { PreferenceManager.getDefaultSharedPreferences(context) .registerOnSharedPreferenceChangeListener(this) geckoSession = createGeckoSession() applySettingsAndSetDelegates() setSession(geckoSession, geckoRuntime) } private fun applySettingsAndSetDelegates() { applyAppSettings() updateBlocking() geckoSession.contentDelegate = createContentDelegate() geckoSession.progressDelegate = createProgressDelegate() geckoSession.navigationDelegate = createNavigationDelegate() geckoSession.trackingProtectionDelegate = createTrackingProtectionDelegate() geckoSession.promptDelegate = createPromptDelegate() finder = geckoSession.finder finder.displayFlags = GeckoSession.FINDER_DISPLAY_HIGHLIGHT_ALL } private fun createGeckoSession(): GeckoSession { val settings = GeckoSessionSettings() settings.setBoolean(GeckoSessionSettings.USE_MULTIPROCESS, true) settings.setBoolean(GeckoSessionSettings.USE_PRIVATE_MODE, true) settings.setBoolean(GeckoSessionSettings.SUSPEND_MEDIA_WHEN_INACTIVE, true) return GeckoSession(settings) } override fun setCallback(callback: IWebView.Callback?) { this.callback = callback } override fun onPause() { job.cancel() } override fun goBack() { geckoSession.goBack() } override fun goForward() { geckoSession.goForward() } override fun reload() { geckoSession.reload() } override fun destroy() { } override fun onResume() { if (job.isCancelled) { job = Job() } storeTelemetrySnapshots() } override fun stopLoading() { geckoSession.stop() callback?.onPageFinished(isSecure) } override fun getUrl(): String? { return currentUrl } override fun loadUrl(url: String) { currentUrl = url geckoSession.loadUri(currentUrl) } override fun cleanup() { if (geckoSession.isOpen) { geckoSession.close() } } override fun updateLocale(currentLocale: Locale?) { geckoRuntime!!.settings.locales = arrayOf(Locales.getLanguageTag(currentLocale)) } override fun setBlockingEnabled(enabled: Boolean) { geckoSession.settings.setBoolean(GeckoSessionSettings.USE_TRACKING_PROTECTION, enabled) if (enabled) { updateBlocking() applyAppSettings() } else { geckoRuntime!!.settings.javaScriptEnabled = true geckoRuntime!!.settings.webFontsEnabled = true geckoRuntime!!.settings.cookieBehavior = GeckoRuntimeSettings.COOKIE_ACCEPT_ALL } callback?.onBlockingStateChanged(enabled) } override fun setRequestDesktop(shouldRequestDesktop: Boolean) { geckoSession.settings.setInt( GeckoSessionSettings.USER_AGENT_MODE, if (shouldRequestDesktop) GeckoSessionSettings.USER_AGENT_MODE_DESKTOP else GeckoSessionSettings.USER_AGENT_MODE_MOBILE ) callback?.onRequestDesktopStateChanged(shouldRequestDesktop) } @Suppress("ComplexMethod") override fun onSharedPreferenceChanged( sharedPreferences: SharedPreferences, key: String ) { when (key) { context.getString(R.string.pref_key_privacy_block_social), context.getString(R.string.pref_key_privacy_block_ads), context.getString(R.string.pref_key_privacy_block_analytics), context.getString(R.string.pref_key_privacy_block_other) -> updateBlocking() context.getString(R.string.pref_key_performance_block_javascript) -> geckoRuntime!!.settings.javaScriptEnabled = !Settings.getInstance(context).shouldBlockJavaScript() context.getString(R.string.pref_key_performance_block_webfonts) -> geckoRuntime!!.settings.webFontsEnabled = !Settings.getInstance(context).shouldBlockWebFonts() context.getString(R.string.pref_key_remote_debugging) -> geckoRuntime!!.settings.remoteDebuggingEnabled = Settings.getInstance(context).shouldEnableRemoteDebugging() context.getString(R.string.pref_key_performance_enable_cookies) -> { updateCookieSettings() } context.getString(R.string.pref_key_safe_browsing) -> { val shouldUseSafeBrowsing = Settings.getInstance(context).shouldUseSafeBrowsing() geckoRuntime!!.settings.blockMalware = shouldUseSafeBrowsing geckoRuntime!!.settings.blockPhishing = shouldUseSafeBrowsing } else -> return } reload() } private fun applyAppSettings() { geckoRuntime!!.settings.javaScriptEnabled = !Settings.getInstance(context).shouldBlockJavaScript() geckoRuntime!!.settings.webFontsEnabled = !Settings.getInstance(context).shouldBlockWebFonts() geckoRuntime!!.settings.remoteDebuggingEnabled = Settings.getInstance(context).shouldEnableRemoteDebugging() updateCookieSettings() } private fun updateCookieSettings() { geckoRuntime!!.settings.cookieBehavior = when (Settings.getInstance(context).getCookiesPrefValue()) { context.getString( R.string.pref_key_should_block_cookies_yes_option ) -> GeckoRuntimeSettings.COOKIE_ACCEPT_NONE context.getString( R.string.pref_key_should_block_cookies_third_party_trackers_only ) -> GeckoRuntimeSettings.COOKIE_ACCEPT_NON_TRACKERS context.getString( R.string.pref_key_should_block_cookies_third_party_only ) -> GeckoRuntimeSettings.COOKIE_ACCEPT_FIRST_PARTY else -> GeckoRuntimeSettings.COOKIE_ACCEPT_ALL } } private fun updateBlocking() { val settings = Settings.getInstance(context) var categories = 0 if (settings.shouldBlockSocialTrackers()) { categories += GeckoSession.TrackingProtectionDelegate.CATEGORY_SOCIAL } if (settings.shouldBlockAdTrackers()) { categories += GeckoSession.TrackingProtectionDelegate.CATEGORY_AD } if (settings.shouldBlockAnalyticTrackers()) { categories += GeckoSession.TrackingProtectionDelegate.CATEGORY_ANALYTIC } if (settings.shouldBlockOtherTrackers()) { categories += GeckoSession.TrackingProtectionDelegate.CATEGORY_CONTENT } geckoRuntime!!.settings.trackingProtectionCategories = categories } @Suppress("ComplexMethod", "ReturnCount") private fun createContentDelegate(): GeckoSession.ContentDelegate { return object : GeckoSession.ContentDelegate { override fun onContextMenu( session: GeckoSession, screenX: Int, screenY: Int, element: GeckoSession.ContentDelegate.ContextElement ) { val hitResult = handleLongClick(element.srcUri, element.type, element.linkUri) callback?.onLongPress(hitResult) } override fun onFirstComposite(session: GeckoSession?) { } override fun onTitleChange(session: GeckoSession, title: String) { webViewTitle = title callback?.onTitleChanged(title) } override fun onFullScreen(session: GeckoSession, fullScreen: Boolean) { if (fullScreen) { callback?.onEnterFullScreen({ geckoSession.exitFullScreen() }, null) } else { callback?.onExitFullScreen() } } override fun onExternalResponse( session: GeckoSession, response: GeckoSession.WebResponseInfo ) { if (!AppConstants.supportsDownloadingFiles()) { return } val scheme = Uri.parse(response.uri).scheme if (scheme == null || scheme != "http" && scheme != "https") { // We are ignoring everything that is not http or https. This is a limitation of // Android's download manager. There's no reason to show a download dialog for // something we can't download anyways. Log.w(TAG, "Ignoring download from non http(s) URL: " + response.uri) return } val download = Download( response.uri, USER_AGENT, response.filename, response.contentType, response.contentLength, Environment.DIRECTORY_DOWNLOADS, response.filename ) callback?.onDownloadStart(download) } override fun onCrash(session: GeckoSession) { geckoSession.close() geckoSession = createGeckoSession() applySettingsAndSetDelegates() geckoSession.open(geckoRuntime!!) setSession(geckoSession) currentUrl = ABOUT_BLANK geckoSession.loadUri(currentUrl) } override fun onFocusRequest(geckoSession: GeckoSession) {} override fun onCloseRequest(geckoSession: GeckoSession) { // Ignore this callback } } } @Suppress("ComplexMethod") private fun createProgressDelegate(): GeckoSession.ProgressDelegate { return object : GeckoSession.ProgressDelegate { override fun onProgressChange(session: GeckoSession?, progress: Int) { if (progress == PROGRESS_100) { if (UrlUtils.isLocalizedContent(url)) { // When the url is a localized content, then the page is secure isSecure = true } callback?.onPageFinished(isSecure) } else { callback?.onProgress(progress) } } override fun onPageStart(session: GeckoSession, url: String) { callback?.onPageStarted(url) callback?.resetBlockedTrackers() isSecure = false } override fun onPageStop(session: GeckoSession, success: Boolean) { if (success) { if (UrlUtils.isLocalizedContent(url)) { // When the url is a localized content, then the page is secure isSecure = true } callback?.onPageFinished(isSecure) } } override fun onSecurityChange( session: GeckoSession, securityInfo: GeckoSession.ProgressDelegate.SecurityInformation ) { isSecure = securityInfo.isSecure if (UrlUtils.isLocalizedContent(url)) { // When the url is a localized content, then the page is secure isSecure = true } callback?.onSecurityChanged( isSecure, securityInfo.host, securityInfo.issuerOrganization ) } } } @Suppress("ComplexMethod") private fun createNavigationDelegate(): GeckoSession.NavigationDelegate { return object : GeckoSession.NavigationDelegate { override fun onLoadError( session: GeckoSession?, uri: String?, error: WebRequestError? ): GeckoResult<String> { ErrorPages.createErrorPage( context, geckoErrorToErrorType(error), uri ).apply { return GeckoResult.fromValue(Base64.encodeToUriString(this)) } } override fun onLoadRequest( session: GeckoSession, request: NavigationDelegate.LoadRequest ): GeckoResult<AllowOrDeny>? { val uri = Uri.parse(request.uri) val complete = when { request.target == GeckoSession.NavigationDelegate.TARGET_WINDOW_NEW -> { geckoSession.loadUri(request.uri) AllowOrDeny.DENY } LocalizedContent.handleInternalContent( request.uri, this@GeckoWebView, context ) -> { AllowOrDeny.DENY } !UrlUtils.isSupportedProtocol(uri.scheme) && callback != null && IntentUtils.handleExternalUri( context, this@GeckoWebView, request.uri ) -> { AllowOrDeny.DENY } else -> { callback?.onRequest(request.isRedirect) AllowOrDeny.ALLOW } } return GeckoResult.fromValue(complete) } override fun onNewSession( session: GeckoSession, uri: String ): GeckoResult<GeckoSession>? { // Prevent new sessions to be created from onLoadRequest throw IllegalStateException() } override fun onLocationChange(session: GeckoSession, url: String) { var desiredUrl = url // Save internal data: urls we should override to present focus:about, focus:rights if (isLoadingInternalUrl) { if (currentUrl == LocalizedContent.URL_ABOUT) { internalAboutData = desiredUrl } else if (currentUrl == LocalizedContent.URL_RIGHTS) { internalRightsData = desiredUrl } isLoadingInternalUrl = false desiredUrl = currentUrl } // Check for internal data: urls to instead present focus:rights, focus:about if (!TextUtils.isEmpty(internalAboutData) && internalAboutData == desiredUrl) { desiredUrl = LocalizedContent.URL_ABOUT } else if (!TextUtils.isEmpty(internalRightsData) && internalRightsData == desiredUrl) { desiredUrl = LocalizedContent.URL_RIGHTS } currentUrl = desiredUrl callback?.onURLChanged(desiredUrl) } override fun onCanGoBack(session: GeckoSession, canGoBack: Boolean) { [email protected] = canGoBack } override fun onCanGoForward(session: GeckoSession, canGoForward: Boolean) { [email protected] = canGoForward } } } private fun createTrackingProtectionDelegate(): GeckoSession.TrackingProtectionDelegate { return GeckoSession.TrackingProtectionDelegate { _, _, _ -> callback?.countBlockedTracker() } } private fun createPromptDelegate(): GeckoSession.PromptDelegate { return GeckoViewPrompt(context as Activity) } @Suppress("ComplexMethod") fun handleLongClick(elementSrc: String?, elementType: Int, uri: String? = null): HitResult? { return when (elementType) { GeckoSession.ContentDelegate.ContextElement.TYPE_AUDIO -> elementSrc?.let { HitResult.AUDIO(it) } GeckoSession.ContentDelegate.ContextElement.TYPE_VIDEO -> elementSrc?.let { HitResult.VIDEO(it) } GeckoSession.ContentDelegate.ContextElement.TYPE_IMAGE -> { when { elementSrc != null && uri != null -> { val isValidURL = try { URL(uri) true } catch (e: MalformedURLException) { false } HitResult.IMAGE_SRC( elementSrc, if (isValidURL) uri else prefixLocationToRelativeURI(uri) ) } elementSrc != null -> HitResult.IMAGE(elementSrc) else -> HitResult.UNKNOWN("") } } GeckoSession.ContentDelegate.ContextElement.TYPE_NONE -> { elementSrc?.let { when { it.isPhone() -> HitResult.PHONE(it) it.isEmail() -> HitResult.EMAIL(it) it.isGeoLocation() -> HitResult.GEO(it) else -> HitResult.UNKNOWN(it) } } ?: uri?.let { val isValidURL = try { URL(uri) true } catch (e: MalformedURLException) { false } HitResult.UNKNOWN(if (isValidURL) it else prefixLocationToRelativeURI(uri)) } } else -> HitResult.UNKNOWN("") } } private fun prefixLocationToRelativeURI(uri: String): String { return try { val url = URL(currentUrl) url.protocol + "://" + url.host + uri } catch (e: MalformedURLException) { // We can't figure this out so just return the probably invalid URI uri } } override fun canGoForward(): Boolean { return canGoForward } override fun canGoBack(): Boolean { return canGoBack } override fun restoreWebViewState(session: Session) { val stateData = session.savedWebViewState!! val savedSession = stateData.getParcelable<GeckoSession>(GECKO_SESSION)!! if (geckoSession != savedSession && !restored) { // Tab changed, we need to close the default session and restore our saved session geckoSession.close() geckoSession = savedSession canGoBack = stateData.getBoolean(CAN_GO_BACK, false) canGoForward = stateData.getBoolean(CAN_GO_FORWARD, false) isSecure = stateData.getBoolean(IS_SECURE, false) webViewTitle = stateData.getString(WEBVIEW_TITLE, null) currentUrl = stateData.getString(CURRENT_URL, ABOUT_BLANK) applySettingsAndSetDelegates() if (!geckoSession.isOpen) { geckoSession.open(geckoRuntime!!) } setSession(geckoSession) } else { // App was backgrounded and restored; // GV restored the GeckoSession itself, but we need to restore our variables canGoBack = stateData.getBoolean(CAN_GO_BACK, false) canGoForward = stateData.getBoolean(CAN_GO_FORWARD, false) isSecure = stateData.getBoolean(IS_SECURE, false) webViewTitle = stateData.getString(WEBVIEW_TITLE, null) currentUrl = stateData.getString(CURRENT_URL, ABOUT_BLANK) applySettingsAndSetDelegates() restored = false } } override fun onRestoreInstanceState(state: Parcelable?) { restored = true super.onRestoreInstanceState(state) } override fun saveWebViewState(session: Session) { val sessionBundle = Bundle() sessionBundle.putParcelable(GECKO_SESSION, geckoSession) sessionBundle.putBoolean(CAN_GO_BACK, canGoBack) sessionBundle.putBoolean(CAN_GO_FORWARD, canGoForward) sessionBundle.putBoolean(IS_SECURE, isSecure) sessionBundle.putString(WEBVIEW_TITLE, webViewTitle) sessionBundle.putString(CURRENT_URL, currentUrl) session.savedWebViewState = sessionBundle } override fun getTitle(): String? { return webViewTitle } override fun exitFullscreen() { geckoSession.exitFullScreen() } override fun findAllAsync(find: String) { finder.find(find, 0).then({ result -> if (result != null) { findListener?.onFindResultReceived(result.current, result.total, true) } GeckoResult<Void>() }, { _ -> GeckoResult<Void>() }) } override fun findNext(forward: Boolean) { finder.find(null, if (forward) 0 else GeckoSession.FINDER_FIND_BACKWARDS) .then({ result -> if (result != null) { findListener?.onFindResultReceived(result.current, result.total, true) } GeckoResult<Void>() }, { _ -> GeckoResult<Void>() }) } override fun clearMatches() { finder.clear() } override fun setFindListener(findListener: IFindListener) { this.findListener = findListener } override fun loadData( baseURL: String, data: String, mimeType: String, encoding: String, historyURL: String ) { isLoadingInternalUrl = historyURL == LocalizedContent.URL_RIGHTS || historyURL == LocalizedContent.URL_ABOUT geckoSession.loadData(data.toByteArray(Charsets.UTF_8), mimeType) currentUrl = historyURL } private fun storeTelemetrySnapshots() { val storage = MobileMetricsPingStorage(context) if (!storage.shouldStoreMetrics()) return geckoRuntime!!.telemetry.getSnapshots(true).then({ value -> launch(IO) { try { value?.toJSONObject()?.also { storage.save(it) } } catch (e: JSONException) { Log.e("getSnapshots failed", e.message) } } GeckoResult<Void>() }, { GeckoResult<Void>() }) } override fun releaseGeckoSession() { releaseSession() } override fun onDetachedFromWindow() { PreferenceManager.getDefaultSharedPreferences(context) .unregisterOnSharedPreferenceChangeListener(this) releaseSession() super.onDetachedFromWindow() } companion object { private const val TAG = "GeckoWebView" } } companion object { @Volatile private var geckoRuntime: GeckoRuntime? = null private var internalAboutData: String? = null private var internalRightsData: String? = null private const val USER_AGENT = "Mozilla/5.0 (Android 8.1.0; Mobile; rv:60.0) Gecko/60.0 Firefox/60.0" const val PREF_FIRST_GECKO_RUN: String = "first_gecko_run" const val PROGRESS_100 = 100 const val CAN_GO_BACK = "canGoBack" const val CAN_GO_FORWARD = "canGoForward" const val GECKO_SESSION = "geckoSession" const val IS_SECURE = "isSecure" const val WEBVIEW_TITLE = "webViewTitle" const val CURRENT_URL = "currentUrl" const val ABOUT_BLANK = "about:blank" /** * Provides an ErrorType corresponding to the error code provided. */ @Suppress("ComplexMethod") internal fun geckoErrorToErrorType(errorCode: WebRequestError?) = when (errorCode?.code) { WebRequestError.ERROR_UNKNOWN -> ErrorType.UNKNOWN WebRequestError.ERROR_SECURITY_SSL -> ErrorType.ERROR_SECURITY_SSL WebRequestError.ERROR_SECURITY_BAD_CERT -> ErrorType.ERROR_SECURITY_BAD_CERT WebRequestError.ERROR_NET_INTERRUPT -> ErrorType.ERROR_NET_INTERRUPT WebRequestError.ERROR_NET_TIMEOUT -> ErrorType.ERROR_NET_TIMEOUT WebRequestError.ERROR_CONNECTION_REFUSED -> ErrorType.ERROR_CONNECTION_REFUSED WebRequestError.ERROR_UNKNOWN_SOCKET_TYPE -> ErrorType.ERROR_UNKNOWN_SOCKET_TYPE WebRequestError.ERROR_REDIRECT_LOOP -> ErrorType.ERROR_REDIRECT_LOOP WebRequestError.ERROR_OFFLINE -> ErrorType.ERROR_OFFLINE WebRequestError.ERROR_PORT_BLOCKED -> ErrorType.ERROR_PORT_BLOCKED WebRequestError.ERROR_NET_RESET -> ErrorType.ERROR_NET_RESET WebRequestError.ERROR_UNSAFE_CONTENT_TYPE -> ErrorType.ERROR_UNSAFE_CONTENT_TYPE WebRequestError.ERROR_CORRUPTED_CONTENT -> ErrorType.ERROR_CORRUPTED_CONTENT WebRequestError.ERROR_CONTENT_CRASHED -> ErrorType.ERROR_CONTENT_CRASHED WebRequestError.ERROR_INVALID_CONTENT_ENCODING -> ErrorType.ERROR_INVALID_CONTENT_ENCODING WebRequestError.ERROR_UNKNOWN_HOST -> ErrorType.ERROR_UNKNOWN_HOST WebRequestError.ERROR_MALFORMED_URI -> ErrorType.ERROR_MALFORMED_URI WebRequestError.ERROR_UNKNOWN_PROTOCOL -> ErrorType.ERROR_UNKNOWN_PROTOCOL WebRequestError.ERROR_FILE_NOT_FOUND -> ErrorType.ERROR_FILE_NOT_FOUND WebRequestError.ERROR_FILE_ACCESS_DENIED -> ErrorType.ERROR_FILE_ACCESS_DENIED WebRequestError.ERROR_PROXY_CONNECTION_REFUSED -> ErrorType.ERROR_PROXY_CONNECTION_REFUSED WebRequestError.ERROR_UNKNOWN_PROXY_HOST -> ErrorType.ERROR_UNKNOWN_PROXY_HOST WebRequestError.ERROR_SAFEBROWSING_MALWARE_URI -> ErrorType.ERROR_SAFEBROWSING_MALWARE_URI WebRequestError.ERROR_SAFEBROWSING_UNWANTED_URI -> ErrorType.ERROR_SAFEBROWSING_UNWANTED_URI WebRequestError.ERROR_SAFEBROWSING_HARMFUL_URI -> ErrorType.ERROR_SAFEBROWSING_HARMFUL_URI WebRequestError.ERROR_SAFEBROWSING_PHISHING_URI -> ErrorType.ERROR_SAFEBROWSING_PHISHING_URI else -> ErrorType.UNKNOWN } } }
mpl-2.0
f969d058dc860a3c17b4e0c28f5b7697
40.963986
108
0.570489
5.553861
false
false
false
false
world-federation-of-advertisers/cross-media-measurement
src/main/kotlin/org/wfanet/measurement/kingdom/service/api/v2alpha/ExchangeStepAttemptsService.kt
1
6821
// Copyright 2021 The Cross-Media Measurement Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package org.wfanet.measurement.kingdom.service.api.v2alpha import io.grpc.Status import io.grpc.StatusException import java.time.LocalDate import org.wfanet.measurement.api.v2alpha.AppendLogEntryRequest import org.wfanet.measurement.api.v2alpha.ExchangeStepAttempt import org.wfanet.measurement.api.v2alpha.ExchangeStepAttemptKey import org.wfanet.measurement.api.v2alpha.ExchangeStepAttemptsGrpcKt.ExchangeStepAttemptsCoroutineImplBase import org.wfanet.measurement.api.v2alpha.FinishExchangeStepAttemptRequest import org.wfanet.measurement.api.v2alpha.GetExchangeStepAttemptRequest import org.wfanet.measurement.api.v2alpha.ListExchangeStepAttemptsRequest import org.wfanet.measurement.api.v2alpha.ListExchangeStepAttemptsResponse import org.wfanet.measurement.api.v2alpha.getProviderFromContext import org.wfanet.measurement.common.grpc.failGrpc import org.wfanet.measurement.common.grpc.grpcRequireNotNull import org.wfanet.measurement.common.grpc.grpcStatusCode import org.wfanet.measurement.common.identity.apiIdToExternalId import org.wfanet.measurement.common.toProtoDate import org.wfanet.measurement.internal.kingdom.ExchangeStepAttemptDetailsKt import org.wfanet.measurement.internal.kingdom.ExchangeStepAttemptsGrpcKt.ExchangeStepAttemptsCoroutineStub as InternalExchangeStepAttemptsCoroutineStub import org.wfanet.measurement.internal.kingdom.ExchangeStepsGrpcKt.ExchangeStepsCoroutineStub as InternalExchangeStepsCoroutineStub import org.wfanet.measurement.internal.kingdom.appendLogEntryRequest import org.wfanet.measurement.internal.kingdom.finishExchangeStepAttemptRequest import org.wfanet.measurement.internal.kingdom.getExchangeStepRequest class ExchangeStepAttemptsService( private val internalExchangeStepAttempts: InternalExchangeStepAttemptsCoroutineStub, private val internalExchangeSteps: InternalExchangeStepsCoroutineStub ) : ExchangeStepAttemptsCoroutineImplBase() { override suspend fun appendLogEntry(request: AppendLogEntryRequest): ExchangeStepAttempt { val exchangeStepAttempt = grpcRequireNotNull(ExchangeStepAttemptKey.fromName(request.name)) { "Resource name unspecified or invalid." } val internalRequest = appendLogEntryRequest { externalRecurringExchangeId = apiIdToExternalId(exchangeStepAttempt.recurringExchangeId) date = LocalDate.parse(exchangeStepAttempt.exchangeId).toProtoDate() stepIndex = exchangeStepAttempt.exchangeStepId.toInt() attemptNumber = exchangeStepAttempt.exchangeStepAttemptId.toInt() for (entry in request.logEntriesList) { debugLogEntries += ExchangeStepAttemptDetailsKt.debugLog { time = entry.time message = entry.message } } } val response = internalExchangeStepAttempts.appendLogEntry(internalRequest) return try { response.toV2Alpha() } catch (e: Throwable) { failGrpc(Status.INVALID_ARGUMENT) { e.message ?: "Failed to convert InternalExchangeStepAttempt" } } } override suspend fun finishExchangeStepAttempt( request: FinishExchangeStepAttemptRequest ): ExchangeStepAttempt { val exchangeStepAttempt = grpcRequireNotNull(ExchangeStepAttemptKey.fromName(request.name)) { "Resource name unspecified or invalid." } val externalRecurringExchangeId = apiIdToExternalId(exchangeStepAttempt.recurringExchangeId) val date = LocalDate.parse(exchangeStepAttempt.exchangeId).toProtoDate() val stepIndex = exchangeStepAttempt.exchangeStepId.toInt() val provider = getProviderFromContext() // Ensure that `provider` is authorized to read the ExchangeStep. val exchangeStep = try { internalExchangeSteps.getExchangeStep( getExchangeStepRequest { this.externalRecurringExchangeId = externalRecurringExchangeId this.date = date this.stepIndex = stepIndex this.provider = provider } ) } catch (e: Exception) { if (e.grpcStatusCode() == Status.Code.NOT_FOUND) { failGrpc(Status.PERMISSION_DENIED) { "ExchangeStep access denied or does not exist" } } throw Status.INTERNAL.withCause(e).asRuntimeException() } // Ensure that `provider` is authorized to modify the ExchangeStep. if (exchangeStep.provider != provider) { failGrpc(Status.PERMISSION_DENIED) { "ExchangeStep write access denied" } } val internalRequest = finishExchangeStepAttemptRequest { this.provider = provider this.externalRecurringExchangeId = externalRecurringExchangeId this.date = date this.stepIndex = stepIndex attemptNumber = exchangeStepAttempt.attemptNumber state = try { request.finalState.toInternal() } catch (e: Throwable) { failGrpc(Status.INVALID_ARGUMENT) { e.message ?: "Failed to convert FinalState" } } debugLogEntries += request.logEntriesList.toInternal() } val response = try { internalExchangeStepAttempts.finishExchangeStepAttempt(internalRequest) } catch (ex: StatusException) { when (ex.status.code) { Status.Code.INVALID_ARGUMENT -> failGrpc(Status.INVALID_ARGUMENT, ex) { "Date must be provided in the request." } else -> failGrpc(Status.UNKNOWN, ex) { "Unknown exception." } } } return try { response.toV2Alpha() } catch (e: Throwable) { failGrpc(Status.INVALID_ARGUMENT) { e.message ?: "Failed to convert FinishExchangeStepAttempt" } } } override suspend fun getExchangeStepAttempt( request: GetExchangeStepAttemptRequest ): ExchangeStepAttempt { TODO("world-federation-of-advertisers/cross-media-measurement#3: implement this") } override suspend fun listExchangeStepAttempts( request: ListExchangeStepAttemptsRequest ): ListExchangeStepAttemptsResponse { TODO("world-federation-of-advertisers/cross-media-measurement#3: implement this") } } private val ExchangeStepAttemptKey.attemptNumber: Int get() { return if (exchangeStepAttemptId.isNotBlank()) { exchangeStepAttemptId.toInt() } else { 0 } }
apache-2.0
e696782bc31d82b6086db2ee321b7736
40.846626
152
0.751796
4.921356
false
false
false
false
Deanveloper/Overcraft
src/main/java/com/deanveloper/overcraft/item/offense/GenjiItems.kt
1
9121
package com.deanveloper.overcraft.item.offense import com.deanveloper.kbukkit.plus import com.deanveloper.kbukkit.runTaskLater import com.deanveloper.kbukkit.runTaskTimer import com.deanveloper.overcraft.PLUGIN import com.deanveloper.overcraft.hurt import com.deanveloper.overcraft.item.Ability import com.deanveloper.overcraft.item.ItemPair import com.deanveloper.overcraft.item.Ultimate import com.deanveloper.overcraft.item.Weapon import com.deanveloper.overcraft.oc import com.deanveloper.overcraft.util.* import org.bukkit.* import org.bukkit.entity.EntityType import org.bukkit.entity.LivingEntity import org.bukkit.entity.Player import org.bukkit.entity.Projectile import org.bukkit.event.EventHandler import org.bukkit.event.entity.EntityDamageByEntityEvent /** * @author Dean */ object Shuriken : Weapon() { override val cooldown: Long get() = throw UnsupportedOperationException("Custom cooldown impl") override val items = ItemPair( OcItem(Material.NETHER_STAR, ChatColor.GREEN + "Shuriken", listOf( "Left Click", " - Shoot three shurikens in a row", "", "Right Click", " - Shoot three shurikens in a fan pattern" ) ), toDefaultCooldown = false) override fun onUse(e: Interaction) { if (e.click == Interaction.Click.LEFT) { for (i in 0..11 step 4) { runTaskLater(PLUGIN, i.toLong()) { val arrow = e.player.world.spawnArrow( e.player.eyeLocation, e.player.eyeLocation.direction, 2.5f, 0f) arrow.shooter = e.player arrow.setGravity(false) arrow.world.playSound(arrow.location, Sound.ENTITY_PLAYER_ATTACK_SWEEP, 1f, .8f) object : ProjectileShot(e.player, arrow) { override fun whileFlying() { projectile.world.spigot().playEffect(projectile.location, Effect.MAGIC_CRIT, 0, 0, 0f, 0f, 0f, 0f, 1, 100) } override fun onHit(target: LivingEntity) { target.hurt(2.8, source) projectile.remove() } override fun onHit(loc: Location) { projectile.remove() } } } } cooldowns.addCooldown(e.player, 20L) } else if (e.click == Interaction.Click.RIGHT) { for (i in -15..15 step 15) { val arrow = e.player.world.spawnArrow( e.player.eyeLocation, e.player.eyeLocation.direction.rotateAroundY(i.toDouble()), 2.5f, 0f) arrow.shooter = e.player arrow.setGravity(false) arrow.world.playSound(arrow.location, Sound.ENTITY_PLAYER_ATTACK_SWEEP, 1f, .8f) object : ProjectileShot(e.player, arrow) { override fun whileFlying() { projectile.world.spigot().playEffect(projectile.location, Effect.MAGIC_CRIT, 0, 0, 0f, 0f, 0f, 0f, 1, 100) } override fun onHit(target: LivingEntity) { target.hurt(2.8, source) projectile.remove() } override fun onHit(loc: Location) { projectile.remove() } } } cooldowns.addCooldown(e.player, 12L) } } } object Reflect : Ability() { override val slot = 1 override val items = ItemPair( ItemPair.DEFAULT_ITEM.apply { name = ChatColor.LIGHT_PURPLE + "Reflect" lore = listOf( "Reflects projectiles in front of you", "in the direction you are looking" ) }, toDefaultCooldown = true) override val cooldown = 20 * 8L override fun onUse(i: Interaction) { val p = i.player p.oc.isGenjiReflecting = true val task = runTaskTimer(PLUGIN, 0, 4) { p.world.playSound(p.location, Sound.ENTITY_PLAYER_ATTACK_SWEEP, .5f, 1.5f) p.world.spigot().playEffect( p.location.add(0.0, 1.0, 0.0).add(p.location.direction), Effect.MAGIC_CRIT, 0, 0, .5f, 1f, .5f, 0f, 10, 30) } runTaskLater(PLUGIN, 20 * 2) { task.cancel() startCooldown(p) p.oc.isGenjiReflecting = false } } @EventHandler fun onHitUntrackedProjectile(e: EntityDamageByEntityEvent) { val damager = e.damager val player = e.entity if (damager.uniqueId !in ProjectileShot.trackedProjectiles && damager is Projectile) { if (player.type === EntityType.PLAYER) { player as Player // smart cast if (player.oc.shouldReflect(damager.velocity)) { e.isCancelled = true val newProj = damager.clone(player) player.world.playSound(player.location, Sound.BLOCK_ANVIL_PLACE, .6f, 2f) damager.remove() object : ProjectileShot(player, newProj) { override fun whileFlying() { } override fun onHit(target: LivingEntity) { target.hurt(5.0, source) projectile.remove() } override fun onHit(loc: Location) { projectile.remove() } } } } } } } object SwiftStrike : Ability() { override val items = ItemPair( OcItem(Material.FEATHER, ChatColor.LIGHT_PURPLE + "Swift Strike", listOf( "Move forward with extreme speed,", "damaging enemies as you pass them" ) ), toDefaultCooldown = true) override val slot = 2 override val cooldown = 8 * 20L override fun onUse(i: Interaction) { val from = i.player.location.clone() object : HitscanShot(i.player, isReflectable = false) { override fun whileFlying(loc: Location): Boolean { source.world.spigot().playEffect( loc, Effect.MAGIC_CRIT, 0, 0, .3f, .1f, .3f, 0f, 5, 30 ) if (loc.distanceSquared(from) > 14 * 14) { source.teleport(loc) return false } return true } override fun onHit(e: LivingEntity): Boolean { e.hurt(5.0, source) return true } override fun onHit(loc: Location): Boolean { source.teleport(loc.clone().subtract(loc.direction.multiply(.2))) return false } } startCooldown(i.player) } } object Dragonblade : Ultimate(true) { override val cooldown: Long get() = 20L override val slot = 3 override val items = ItemPair( OcItem( Material.DIAMOND_SWORD, ChatColor.GREEN + ChatColor.BOLD + "DRAGONBLADE", listOf( "Wield your sword, which deals", "an extremely large amount of damage" ) ), OcItem( Material.IRON_SWORD, ChatColor.GREEN + ChatColor.BOLD + "DRAGONBLADE", listOf( "Wield your sword, which deals", "an extremely large amount of damage" ) ) ) override val honorBound = true override fun onUse(i: Interaction) { runTaskTimer(PLUGIN, 0, 5) { i.player.world.spigot().playEffect( i.player.location.add(0.0, 1.0, 0.0).add(i.player.location.direction.multiply(-1)), Effect.MAGIC_CRIT, 0, 0, // id and data (for block break and item crack) .5f, 2f, .5f, // offsets 0.0f, 20, 30 // speed, number of particles, viewing radius ) percent -= 1.0 / 24.0 } } override fun onAttack(i: Interaction) { i.target?.hurt(8.0, i.player) startCooldown(i.player) } }
mit
16414a0316bb5673f47dc49f861f4b0a
34.772549
134
0.487447
4.608893
false
false
false
false
jeffersonvenancio/BarzingaNow
android/app/src/main/java/com/barzinga/view/CheckoutActivity.kt
1
5417
package com.barzinga.view import android.app.Activity import android.arch.lifecycle.ViewModelProviders import android.content.Context import android.content.Intent import android.databinding.DataBindingUtil import android.os.Bundle import android.support.v7.app.AppCompatActivity import android.view.View import android.view.View.VISIBLE import com.barzinga.R import com.barzinga.databinding.ActivityCheckoutBinding import com.barzinga.model.Product import com.barzinga.restClient.parameter.TransactionParameter import com.barzinga.util.ConvertObjectsUtil.Companion.getTransactionParameterFromJson import com.barzinga.view.adapter.ProductCartAdapter import com.barzinga.viewmodel.Constants.TRANSACTION_EXTRA import com.barzinga.viewmodel.ProductListViewModel import com.barzinga.viewmodel.TransactionViewModel import com.barzinga.viewmodel.UserViewModel import com.bumptech.glide.Glide import com.bumptech.glide.request.RequestOptions import jp.wasabeef.glide.transformations.CropCircleTransformation import kotlinx.android.synthetic.main.activity_checkout.* import kotlinx.android.synthetic.main.view_user_info.* import okhttp3.ResponseBody import retrofit2.Response import android.app.AlertDialog import android.content.DialogInterface import java.util.* import kotlin.concurrent.timerTask class CheckoutActivity : AppCompatActivity(), TransactionViewModel.TransactionListener, ProductListViewModel.ProductsListener { lateinit var binding: ActivityCheckoutBinding lateinit var viewModel: TransactionViewModel var transactionParameter: TransactionParameter? = null var price = 0.0 override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = DataBindingUtil.setContentView(this, R.layout.activity_checkout) if (intent.hasExtra(TRANSACTION_EXTRA)){ transactionParameter = getTransactionParameterFromJson(intent.getStringExtra(TRANSACTION_EXTRA)) } Glide.with(this) .load(transactionParameter?.user?.photoUrl) .apply(RequestOptions.bitmapTransform(CropCircleTransformation())) .into(mUserPhoto) binding.viewmodel = transactionParameter?.user?.let { UserViewModel(it) } transactionParameter?.products?.let { setupRecyclerView(it) } viewModel = ViewModelProviders.of(this).get(TransactionViewModel::class.java) updatePrice() llFinishOrder.setOnClickListener({ disableButton() disableList() transactionParameter?.pin = "Token Diego" transactionParameter?.products = (binding.cartProducts.adapter as ProductCartAdapter).getCartProducts() viewModel.buyProducts(transactionParameter, this) }) } private fun updatePrice() { price = (binding.cartProducts.adapter as ProductCartAdapter).getCurrentOrderPrice() if (price > 0.0) { binding.mOrderPrice.text = String.format("%.2f", price) } else { setResult(Activity.RESULT_CANCELED) finish() } } companion object { fun start(context: Context, transactionJson: String) { val starter = Intent(context, CheckoutActivity::class.java) starter.putExtra(TRANSACTION_EXTRA, transactionJson) context.startActivity(starter) } fun startIntent(context: Context, transactionJson: String) : Intent{ val starter = Intent(context, CheckoutActivity::class.java) starter.putExtra(TRANSACTION_EXTRA, transactionJson) return starter } } override fun onTransactionSuccess(response: Response<ResponseBody>) { if (response.code() == 200){ TransactionFinishedActivity.start(this, transactionParameter?.user?.money?.minus(price)) enableButton() setResult(Activity.RESULT_OK) finish() }else{ val builder1 = AlertDialog.Builder(this) builder1.setMessage(getString(R.string.transaction_error)) builder1.setCancelable(true) val alert11 = builder1.create() alert11.show() val timer = Timer() timer.schedule(timerTask { MainActivity.start(this@CheckoutActivity) finish() }, 3000) } } override fun onTransactionFailure() { enableButton() } private fun disableButton() { btFinishOrder.visibility = View.INVISIBLE pbLoading.visibility = View.VISIBLE llFinishOrder.isEnabled = false } private fun disableList() { blockListView.visibility = VISIBLE } private fun enableButton() { btFinishOrder.visibility = View.VISIBLE pbLoading.visibility = View.INVISIBLE llFinishOrder.isEnabled = true } private fun setupRecyclerView(products: List<Product>) { val productsAdapter = ProductCartAdapter(this, products as ArrayList<Product>, this) cartProducts.apply { adapter = productsAdapter setHasFixedSize(true) } pbLoading.visibility = View.GONE } override fun onProductsListGotten(products: ArrayList<Product>) { } override fun onProductsListError() { } override fun onProductsQuantityChanged() { updatePrice() } }
apache-2.0
93b54641f9ea0c2300c7bbf6945942b1
32.030488
127
0.696142
4.960623
false
false
false
false
Geobert/radis
app/src/main/kotlin/fr/geobert/radis/ui/ScheduledOpListFragment.kt
1
11799
package fr.geobert.radis.ui import android.app.Activity import android.app.AlertDialog import android.app.Dialog import android.content.DialogInterface import android.content.Intent import android.database.Cursor import android.os.Bundle import android.support.v4.app.DialogFragment import android.support.v4.app.LoaderManager.LoaderCallbacks import android.support.v4.content.CursorLoader import android.support.v4.content.Loader import android.support.v7.widget.DefaultItemAnimator import android.support.v7.widget.LinearLayoutManager import android.support.v7.widget.RecyclerView import android.util.Log import android.view.LayoutInflater import android.view.MenuItem import android.view.View import android.view.ViewGroup import android.widget.LinearLayout import android.widget.TextView import fr.geobert.radis.BaseFragment import fr.geobert.radis.MainActivity import fr.geobert.radis.R import fr.geobert.radis.data.Operation import fr.geobert.radis.data.ScheduledOperation import fr.geobert.radis.db.AccountTable import fr.geobert.radis.db.DbContentProvider import fr.geobert.radis.db.OperationTable import fr.geobert.radis.db.ScheduledOperationTable import fr.geobert.radis.tools.Tools import fr.geobert.radis.tools.formatSum import fr.geobert.radis.ui.adapter.SchedOpAdapter import fr.geobert.radis.ui.editor.ScheduledOperationEditor import hirondelle.date4j.DateTime import kotlin.properties.Delegates public class ScheduledOpListFragment : BaseFragment(), LoaderCallbacks<Cursor>, IOperationList { private var mContainer: LinearLayout by Delegates.notNull() private var mListView: RecyclerView by Delegates.notNull() private var mEmptyView: View by Delegates.notNull() private var mListLayout: LinearLayoutManager by Delegates.notNull() private var mAdapter: SchedOpAdapter? = null private var mLoader: CursorLoader? = null private var mTotalLbl: TextView by Delegates.notNull() override fun setupIcon() = setIcon(R.drawable.sched_48) override fun onCreateView(inflater: LayoutInflater, container: ViewGroup, savedInstanceState: Bundle?): View { super.onCreateView(inflater, container, savedInstanceState) val ll = inflater.inflate(R.layout.scheduled_list, container, false) as LinearLayout mContainer = ll mEmptyView = ll.findViewById(R.id.empty_textview) setupIcon() setMenu(R.menu.scheduled_list_menu) mListView = ll.findViewById(R.id.operation_list) as RecyclerView mTotalLbl = ll.findViewById(R.id.sch_op_sum_total) as TextView mListView.setHasFixedSize(true) mListLayout = LinearLayoutManager(activity) // if (mListView.getLayoutManager() == null) { mListView.layoutManager = mListLayout // } mListView.itemAnimator = DefaultItemAnimator() return ll } private fun fetchSchOpsOfAccount() { Log.d("ScheduledOpListFragment", "fetchSchOpsOfAccount mLoader:$mLoader") if (mLoader == null) { loaderManager.initLoader<Cursor>(GET_SCH_OPS_OF_ACCOUNT, Bundle(), this) } } override fun onSaveInstanceState(outState: Bundle) { super.onSaveInstanceState(outState) outState.putLong("mCurrentAccount", mActivity.getCurrentAccountId()) } override fun onResume() { super.onResume() Log.d("ScheduledOpListFragment", "onResume") mAccountManager.fetchAllAccounts(false, { fetchSchOpsOfAccount() }) } override fun onAccountChanged(itemId: Long): Boolean { if (mAccountManager.getCurrentAccountId(activity) != itemId) { mAccountManager.setCurrentAccountId(itemId, activity) val req = if (mActivity.getCurrentAccountId() == 0L) { GET_ALL_SCH_OPS } else { GET_SCH_OPS_OF_ACCOUNT } loaderManager.destroyLoader(req) fetchSchOpsOfAccount() } return true } private fun deleteSchOp(delAllOccurrences: Boolean, opId: Long) { val cursorOp = ScheduledOperationTable.fetchOneScheduledOp(mActivity, opId) val transId = cursorOp?.getLong(cursorOp.getColumnIndex(OperationTable.KEY_OP_TRANSFERT_ACC_ID)) var needRefresh = false if (delAllOccurrences) { ScheduledOperationTable.deleteAllOccurences(mActivity, opId) MainActivity.refreshAccountList(mActivity) needRefresh = true } if (ScheduledOperationTable.deleteScheduledOp(mActivity, opId)) { needRefresh = true mAdapter?.delOp(opId) setupListVisibility() } if (needRefresh) { if (transId != null && transId > 0) { AccountTable.consolidateSums(mActivity, transId) } } } override fun onMenuItemClick(item: MenuItem): Boolean { when (item.itemId) { R.id.create_operation -> { ScheduledOperationEditor.callMeForResult(mActivity, 0, mActivity.getCurrentAccountId(), ScheduledOperationEditor.ACTIVITY_SCH_OP_CREATE) return true } else -> return Tools.onDefaultOptionItemSelected(mActivity, item) } } override fun onCreateLoader(id: Int, args: Bundle): Loader<Cursor>? { val currentAccountId = mActivity.getCurrentAccountId() Log.d("SchedOpList", "onCreateLoader account id : $currentAccountId") when (id) { GET_ALL_SCH_OPS -> mLoader = CursorLoader(mActivity, DbContentProvider.SCHEDULED_JOINED_OP_URI, ScheduledOperationTable.SCHEDULED_OP_COLS_QUERY, null, null, ScheduledOperationTable.SCHEDULED_OP_ORDERING) GET_SCH_OPS_OF_ACCOUNT -> mLoader = CursorLoader(mActivity, DbContentProvider.SCHEDULED_JOINED_OP_URI, ScheduledOperationTable.SCHEDULED_OP_COLS_QUERY, "sch.${ScheduledOperationTable.KEY_SCHEDULED_ACCOUNT_ID} = ? OR sch.${OperationTable.KEY_OP_TRANSFERT_ACC_ID} = ?", arrayOf(java.lang.Long.toString(currentAccountId), java.lang.Long.toString(currentAccountId)), ScheduledOperationTable.SCHEDULED_OP_ORDERING) else -> { } } return mLoader } override fun onLoadFinished(cursorLoader: Loader<Cursor>, data: Cursor) { val adapter = mAdapter if (adapter == null) { mAdapter = SchedOpAdapter(mActivity, this, data) mListView.adapter = mAdapter } else { adapter.increaseCache(data) } setupListVisibility() computeTotal(data) } private fun setupListVisibility() { if (mAdapter?.itemCount == 0) { mListView.visibility = View.GONE mEmptyView.visibility = View.VISIBLE } else { mListView.visibility = View.VISIBLE mEmptyView.visibility = View.GONE } } private fun computeTotal(data: Cursor?) { var credit: Long = 0 var debit: Long = 0 if (data != null && data.count > 0 && data.moveToFirst()) { do { var s = data.getLong(data.getColumnIndex(OperationTable.KEY_OP_SUM)) val transId = data.getLong(data.getColumnIndex(OperationTable.KEY_OP_TRANSFERT_ACC_ID)) if (transId == mActivity.getCurrentAccountId()) { s = -s } if (s >= 0) { credit += s } else { debit += s } } while (data.moveToNext()) } mTotalLbl.text = getString(R.string.sched_op_total_sum).format( (credit.toDouble() / 100.0).formatSum(), (debit.toDouble() / 100.0).formatSum(), ((credit + debit).toDouble() / 100.0).formatSum()) } override fun onLoaderReset(cursorLoader: Loader<Cursor>) { mAdapter?.reset() mLoader = null } override fun getMoreOperations(startDate: DateTime?) { // not needed } override fun getDeleteConfirmationDialog(op: Operation): DialogFragment { return DeleteOpConfirmationDialog.newInstance(op.mRowId, this) } override fun updateDisplay(intent: Intent?) { fetchSchOpsOfAccount() } override public fun onOperationEditorResult(requestCode: Int, resultCode: Int, data: Intent?) { Log.d("ScheduledOpListFragment", "onOperationEditorResult req:$requestCode, result:$resultCode, adapter:$mAdapter") if (resultCode == Activity.RESULT_OK && data != null) { when (requestCode) { ScheduledOperationEditor.ACTIVITY_SCH_OP_CREATE -> { val op: ScheduledOperation = data.getParcelableExtra("operation") Log.d("ScheduledOpListFragment", "onOperationEditorResult ADD") mAdapter?.addOp(op) setupListVisibility() } ScheduledOperationEditor.ACTIVITY_SCH_OP_EDIT -> { val op: ScheduledOperation = data.getParcelableExtra("operation") Log.d("ScheduledOpListFragment", "onOperationEditorResult UPDATE") mAdapter?.updateOp(op) } else -> Log.d("ScheduledOpListFragment", "onOperationEditorResult ELSE:$requestCode") } } } override fun getListLayoutManager(): LinearLayoutManager = mListLayout override fun getRecyclerView(): RecyclerView = mListView override fun selectionChanged(selPos: Int, selId: Long) { // TODO } public class DeleteOpConfirmationDialog : DialogFragment() { private var operationId: Long = 0 override fun onCreateDialog(savedInstanceState: Bundle?): Dialog { super.onCreate(savedInstanceState) val args = arguments this.operationId = args.getLong("opId") val builder = AlertDialog.Builder(activity) builder.setMessage(R.string.ask_delete_occurrences).setCancelable(false). setPositiveButton(R.string.del_all_occurrences, object : DialogInterface.OnClickListener { override fun onClick(dialog: DialogInterface, id: Int) { parentFrag.deleteSchOp(true, operationId) } }).setNeutralButton(R.string.cancel_delete_occurrences, object : DialogInterface.OnClickListener { override fun onClick(dialog: DialogInterface, id: Int) { parentFrag.deleteSchOp(false, operationId) } }).setNegativeButton(R.string.cancel_sch_deletion, object : DialogInterface.OnClickListener { override fun onClick(dialog: DialogInterface, id: Int) { dialog.cancel() } }) return builder.create() } companion object { var parentFrag: ScheduledOpListFragment by Delegates.notNull() public fun newInstance(opId: Long, parentFrag: ScheduledOpListFragment): DeleteOpConfirmationDialog { DeleteOpConfirmationDialog.parentFrag = parentFrag val frag = DeleteOpConfirmationDialog() val args = Bundle() args.putLong("opId", opId) frag.arguments = args return frag } } } companion object { // public val CURRENT_ACCOUNT: String = "accountId" // private val TAG = "ScheduleOpList" // dialog ids private val GET_ALL_SCH_OPS = 900 private val GET_SCH_OPS_OF_ACCOUNT = 910 } }
gpl-2.0
9deaedab3fe2b9be89febb104302495d
39.542955
135
0.639261
4.784266
false
false
false
false