repo_name
stringlengths 7
79
| path
stringlengths 8
206
| copies
stringclasses 36
values | size
stringlengths 2
6
| content
stringlengths 55
523k
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 7.18
99.5
| line_max
int64 16
979
| alpha_frac
float64 0.3
0.87
| ratio
float64 2.01
8.07
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
GunoH/intellij-community | platform/platform-impl/src/com/intellij/openapi/wm/impl/customFrameDecorations/header/toolbar/MainMenuButton.kt | 2 | 7788 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.openapi.wm.impl.customFrameDecorations.header.toolbar
import com.intellij.icons.AllIcons
import com.intellij.ide.DataManager
import com.intellij.ide.IdeBundle
import com.intellij.ide.ui.UISettings.Companion.getInstance
import com.intellij.ide.ui.customization.CustomActionsSchema
import com.intellij.openapi.Disposable
import com.intellij.openapi.actionSystem.*
import com.intellij.openapi.actionSystem.impl.ActionButton
import com.intellij.openapi.actionSystem.impl.PresentationFactory
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.diagnostic.thisLogger
import com.intellij.openapi.keymap.Keymap
import com.intellij.openapi.keymap.KeymapManagerListener
import com.intellij.openapi.project.DumbAwareAction
import com.intellij.openapi.ui.popup.JBPopupFactory
import com.intellij.openapi.util.Disposer
import com.intellij.ui.IconManager
import com.intellij.ui.popup.PopupFactoryImpl
import com.intellij.ui.popup.list.ListPopupImpl
import com.intellij.ui.popup.util.PopupImplUtil
import com.intellij.util.messages.MessageBusConnection
import com.intellij.util.ui.JBUI
import org.jetbrains.annotations.ApiStatus
import java.awt.Dimension
import java.awt.event.ActionEvent
import java.awt.event.ActionListener
import java.awt.event.HierarchyEvent
import java.awt.event.KeyEvent
import javax.swing.JComponent
import javax.swing.KeyStroke
import javax.swing.SwingUtilities
@ApiStatus.Internal
internal class MainMenuButton {
private val menuAction = ShowMenuAction()
private var disposable: Disposable? = null
private var shortcutsChangeConnection: MessageBusConnection? = null
private var registeredKeyStrokes = mutableListOf<KeyStroke>()
val button: ActionButton = createMenuButton(menuAction)
var rootPane: JComponent? = null
set(value) {
if (field !== value) {
uninstall()
field = value
if (button.isShowing) {
install()
}
}
}
init {
button.addHierarchyListener { e ->
if (e!!.changeFlags.toInt() and HierarchyEvent.SHOWING_CHANGED != 0) {
if (button.isShowing) {
install()
}
else {
uninstall()
}
}
}
}
private fun initShortcutsChangeConnection() {
shortcutsChangeConnection = ApplicationManager.getApplication().messageBus.connect()
.apply {
subscribe(KeymapManagerListener.TOPIC, object : KeymapManagerListener {
override fun activeKeymapChanged(keymap: Keymap?) {
button.update()
}
})
}
}
private fun install() {
val rootPaneCopy = rootPane
if (rootPaneCopy == null) {
thisLogger().warn("rootPane is not set, MainMenu button listeners are not installed")
return
}
if (disposable == null) {
disposable = Disposer.newDisposable()
registerMenuButtonShortcut(rootPaneCopy)
registerSubMenuShortcuts(rootPaneCopy)
initShortcutsChangeConnection()
}
}
private fun uninstall() {
disposable?.let { Disposer.dispose(it) }
disposable = null
shortcutsChangeConnection?.let { Disposer.dispose(it) }
shortcutsChangeConnection = null
rootPane?.let {
for (keyStroke in registeredKeyStrokes) {
it.unregisterKeyboardAction(keyStroke)
}
}
registeredKeyStrokes.clear()
}
private fun registerMenuButtonShortcut(component: JComponent) {
val showMenuAction = ActionManager.getInstance().getAction(MAIN_MENU_ACTION_ID)
if (showMenuAction == null) {
logger<MainMenuButton>().warn("Cannot find action by id $MAIN_MENU_ACTION_ID")
return
}
menuAction.registerCustomShortcutSet(showMenuAction.shortcutSet, component, disposable)
button.update() // Update shortcut in tooltip
}
private fun registerSubMenuShortcuts(component: JComponent) {
val mainMenu = getMainMenuGroup()
for (action in mainMenu.getChildren(null)) {
val mnemonic = action.templatePresentation.mnemonic
if (mnemonic > 0) {
val keyStroke = KeyStroke.getKeyStroke(mnemonic, KeyEvent.ALT_DOWN_MASK)
component.registerKeyboardAction(ShowSubMenuAction(action), keyStroke, JComponent.WHEN_IN_FOCUSED_WINDOW)
registeredKeyStrokes.add(keyStroke)
}
}
}
private inner class ShowMenuAction : DumbAwareAction() {
private val icon = IconManager.getInstance().getIcon("expui/general/[email protected]", AllIcons::class.java)
override fun update(e: AnActionEvent) {
e.presentation.icon = icon
e.presentation.text = IdeBundle.message("main.toolbar.menu.button")
}
override fun getActionUpdateThread(): ActionUpdateThread {
return ActionUpdateThread.BGT
}
override fun actionPerformed(e: AnActionEvent) = showPopup(e.dataContext)
fun showPopup(context: DataContext, actionToShow: AnAction? = null) {
val mainMenu = getMainMenuGroup()
val popup = JBPopupFactory.getInstance()
.createActionGroupPopup(null, mainMenu, context, JBPopupFactory.ActionSelectionAid.SPEEDSEARCH, true,
ActionPlaces.MAIN_MENU)
.apply { setShowSubmenuOnHover(true) }
.apply { setMinimumSize(Dimension(JBUI.CurrentTheme.CustomFrameDecorations.menuPopupMinWidth(), 0)) }
as ListPopupImpl
PopupImplUtil.setPopupToggleButton(popup, button)
popup.showUnderneathOf(button)
if (actionToShow != null) {
for (listStep in popup.listStep.values) {
listStep as PopupFactoryImpl.ActionItem
if (listStep.action.unwrap() === actionToShow.unwrap()) {
SwingUtilities.invokeLater {
// Wait popup showing
popup.selectAndExpandValue(listStep)
}
}
}
}
}
}
private inner class ShowSubMenuAction(private val actionToShow: AnAction) : ActionListener {
override fun actionPerformed(e: ActionEvent?) {
if (!getInstance().disableMnemonics) {
menuAction.showPopup(DataManager.getInstance().getDataContext(button), actionToShow)
}
}
}
}
private fun createMenuButton(action: AnAction): ActionButton {
val button = object : ActionButton(action, PresentationFactory().getPresentation(action),
ActionPlaces.MAIN_MENU, Dimension(40, 40)) {
override fun getDataContext(): DataContext {
return DataManager.getInstance().dataContextFromFocusAsync.blockingGet(200) ?: super.getDataContext()
}
}
button.setLook(HeaderToolbarButtonLook())
return button
}
private fun getMainMenuGroup(): ActionGroup {
val mainMenuGroup = CustomActionsSchema.getInstance().getCorrectedAction(IdeActions.GROUP_MAIN_MENU)
mainMenuGroup as ActionGroup
return DefaultActionGroup(
mainMenuGroup.getChildren(null).mapNotNull { child ->
if (child is ActionGroup) {
// Wrap action groups to force them to be popup groups,
// otherwise they end up as separate items in the burger menu (IDEA-294669).
ActionGroupPopupWrapper(child)
} else {
LOG.error("A top-level child of the main menu is not an action group: $child")
null
}
}
)
}
private class ActionGroupPopupWrapper(val wrapped: ActionGroup) : ActionGroupWrapper(wrapped) {
override fun update(e: AnActionEvent) {
super.update(e)
e.presentation.isPopupGroup = true
}
}
private fun AnAction.unwrap(): AnAction =
if (this is ActionGroupPopupWrapper)
this.wrapped
else
this
private const val MAIN_MENU_ACTION_ID = "MainMenuButton.ShowMenu"
private val LOG = logger<MainMenuButton>()
| apache-2.0 | 3be5a70091ac2e428c07e477b0882d70 | 33.30837 | 120 | 0.717257 | 4.660682 | false | false | false | false |
codebutler/farebot | farebot-app/src/main/java/com/codebutler/farebot/app/feature/help/HelpScreen.kt | 1 | 2139 | /*
* HelpScreen.kt
*
* This file is part of FareBot.
* Learn more at: https://codebutler.github.io/farebot/
*
* Copyright (C) 2017 Eric Butler <[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.codebutler.farebot.app.feature.help
import android.content.Context
import com.codebutler.farebot.R
import com.codebutler.farebot.app.core.inject.ScreenScope
import com.codebutler.farebot.app.core.ui.ActionBarOptions
import com.codebutler.farebot.app.core.ui.FareBotScreen
import com.codebutler.farebot.app.feature.main.MainActivity
import dagger.Component
class HelpScreen : FareBotScreen<HelpScreen.HelpComponent, HelpScreenView>() {
override fun getTitle(context: Context): String = context.getString(R.string.supported_cards)
override fun getActionBarOptions(): ActionBarOptions = ActionBarOptions(
backgroundColorRes = R.color.accent,
textColorRes = R.color.white
)
override fun onCreateView(context: Context): HelpScreenView = HelpScreenView(context)
override fun createComponent(parentComponent: MainActivity.MainActivityComponent): HelpComponent =
DaggerHelpScreen_HelpComponent.builder()
.mainActivityComponent(parentComponent)
.build()
override fun inject(component: HelpComponent) {
component.inject(this)
}
@ScreenScope
@Component(dependencies = arrayOf(MainActivity.MainActivityComponent::class))
interface HelpComponent {
fun inject(helpScreen: HelpScreen)
}
}
| gpl-3.0 | 1a521ed225a9dc429b3db6a20e607b01 | 35.87931 | 102 | 0.747078 | 4.321212 | false | false | false | false |
ktorio/ktor | ktor-io/posix/src/io/ktor/utils/io/core/InputArraysNative.kt | 1 | 1346 | package io.ktor.utils.io.core
import kotlinx.cinterop.*
@Suppress("EXTENSION_SHADOWED_BY_MEMBER")
public fun Input.readFully(dst: CPointer<ByteVar>, offset: Int, length: Int) {
if (readAvailable(dst, offset, length) != length) {
prematureEndOfStream(length)
}
}
@Suppress("EXTENSION_SHADOWED_BY_MEMBER")
public fun Input.readFully(dst: CPointer<ByteVar>, offset: Long, length: Long) {
if (readAvailable(dst, offset, length) != length) {
prematureEndOfStream(length)
}
}
@Suppress("EXTENSION_SHADOWED_BY_MEMBER")
public fun Input.readAvailable(dst: CPointer<ByteVar>, offset: Int, length: Int): Int {
var bytesCopied = 0
takeWhile { buffer ->
val partSize = minOf(length - bytesCopied, buffer.readRemaining)
buffer.readFully(dst, offset + bytesCopied, partSize)
bytesCopied += partSize
bytesCopied < length
}
return bytesCopied
}
@Suppress("EXTENSION_SHADOWED_BY_MEMBER")
public fun Input.readAvailable(dst: CPointer<ByteVar>, offset: Long, length: Long): Long {
var bytesCopied = 0L
takeWhile { buffer ->
val partSize = minOf(length - bytesCopied, buffer.readRemaining.toLong()).toInt()
buffer.readFully(dst, offset + bytesCopied, partSize)
bytesCopied += partSize
bytesCopied < length
}
return bytesCopied
}
| apache-2.0 | b33c2b867b4bfb765ff36254a2af94fc | 28.911111 | 90 | 0.686478 | 4.193146 | false | false | false | false |
cnevinc/Bandhook-Kotlin | app/src/main/java/com/antonioleiva/bandhookkotlin/ui/custom/AutofitRecyclerView.kt | 4 | 2257 | /*
* Copyright (C) 2015 Antonio Leiva
*
* 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.antonioleiva.bandhookkotlin.ui.custom
import android.content.Context
import android.support.v7.widget.GridLayoutManager
import android.support.v7.widget.RecyclerView
import android.util.AttributeSet
import kotlin.properties.Delegates
/**
* AutofitRecyclerView was orignally explained by Chiu-Ki Chan and explained on its blog:
* http://blog.sqisland.com/2014/12/recyclerview-autofit-grid.html
*
* I just converted to Kotlin code.
*/
class AutofitRecyclerView : RecyclerView {
private var manager:GridLayoutManager by Delegates.notNull()
private var columnWidth = -1
public constructor(context: Context) : super(context) {
init(context)
}
public constructor(context: Context, attrs: AttributeSet) : super(context, attrs) {
init(context, attrs)
}
public constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int) : super(context, attrs, defStyleAttr) {
init(context, attrs)
}
fun init(context: Context, attrs: AttributeSet? = null) {
if (attrs != null){
val attrsArray = intArrayOf(android.R.attr.columnWidth)
val ta = context.obtainStyledAttributes(attrs, attrsArray)
columnWidth = ta.getDimensionPixelSize(0, -1)
ta.recycle()
}
manager = GridLayoutManager(context, 1)
setLayoutManager(manager)
}
override fun onMeasure(widthSpec: Int, heightSpec: Int) {
super.onMeasure(widthSpec, heightSpec)
if (columnWidth > 0) {
val spanCount = Math.max(1, getMeasuredWidth() / columnWidth)
manager.setSpanCount(spanCount)
}
}
}
| apache-2.0 | e49cc5bf105b1e64dfca75cdc4f760ec | 32.686567 | 120 | 0.698715 | 4.299048 | false | false | false | false |
inorichi/mangafeed | app/src/main/java/eu/kanade/tachiyomi/data/database/models/Category.kt | 2 | 1230 | package eu.kanade.tachiyomi.data.database.models
import android.content.Context
import eu.kanade.tachiyomi.R
import eu.kanade.tachiyomi.ui.library.setting.DisplayModeSetting
import eu.kanade.tachiyomi.ui.library.setting.SortDirectionSetting
import eu.kanade.tachiyomi.ui.library.setting.SortModeSetting
import java.io.Serializable
interface Category : Serializable {
var id: Int?
var name: String
var order: Int
var flags: Int
private fun setFlags(flag: Int, mask: Int) {
flags = flags and mask.inv() or (flag and mask)
}
var displayMode: Int
get() = flags and DisplayModeSetting.MASK
set(mode) = setFlags(mode, DisplayModeSetting.MASK)
var sortMode: Int
get() = flags and SortModeSetting.MASK
set(mode) = setFlags(mode, SortModeSetting.MASK)
var sortDirection: Int
get() = flags and SortDirectionSetting.MASK
set(mode) = setFlags(mode, SortDirectionSetting.MASK)
companion object {
fun create(name: String): Category = CategoryImpl().apply {
this.name = name
}
fun createDefault(context: Context): Category = create(context.getString(R.string.label_default)).apply { id = 0 }
}
}
| apache-2.0 | ac20603d70263ae46df21e9c128a7a1e | 26.954545 | 122 | 0.692683 | 4.183673 | false | false | false | false |
ClearVolume/scenery | src/test/kotlin/graphics/scenery/tests/examples/basic/DistanceMeasurement.kt | 2 | 4406 | package graphics.scenery.tests.examples.basic
import graphics.scenery.*
import graphics.scenery.backends.Renderer
import graphics.scenery.controls.behaviours.SelectCommand
import graphics.scenery.numerics.Random
import graphics.scenery.primitives.Line
import graphics.scenery.primitives.TextBoard
import graphics.scenery.attribute.material.Material
import graphics.scenery.attribute.spatial.Spatial
import graphics.scenery.utils.extensions.plus
import org.joml.Vector3f
import org.joml.Vector4f
import kotlin.concurrent.thread
/**
* Example of how to measure the distance between two nodes.
*
* @author Justin Buerger <[email protected]>
*/
class DistanceMeasurement: SceneryBase("RulerPick", wantREPL = true) {
private var secondNode = false
override fun init() {
renderer = hub.add(Renderer.createRenderer(hub, applicationName, scene, 512, 512))
for(i in 0 until 200) {
val s = Icosphere(Random.randomFromRange(0.04f, 0.2f), 2)
s.spatial {
position = Random.random3DVectorFromRange(-5.0f, 5.0f)
}
scene.addChild(s)
}
val box = Box(Vector3f(10.0f, 10.0f, 10.0f), insideNormals = true)
box.material {
diffuse = Vector3f(1.0f, 1.0f, 1.0f)
cullingMode = Material.CullingMode.Front
}
scene.addChild(box)
val light = PointLight(radius = 15.0f)
light.spatial {
position = Vector3f(0.0f, 0.0f, 2.0f)
}
light.intensity = 1.0f
light.emissionColor = Vector3f(1.0f, 1.0f, 1.0f)
scene.addChild(light)
val cam: Camera = DetachedHeadCamera()
with(cam) {
cam.spatial {
position = Vector3f(0.0f, 0.0f, 5.0f)
}
perspectiveCamera(50.0f, 512, 512)
scene.addChild(this)
}
}
override fun inputSetup() {
super.inputSetup()
var lastSpatial: Spatial? = null
val wiggle: (Scene.RaycastResult, Int, Int) -> Unit = { result, _, _ ->
result.matches.firstOrNull()?.let { nearest ->
nearest.node.ifSpatial {
val originalPosition = Vector3f(this.position)
thread {
for(i in 0 until 200) {
this.position = originalPosition + Random.random3DVectorFromRange(-0.05f, 0.05f)
Thread.sleep(2)
}
}
if(!secondNode) {
lastSpatial = this
}
else {
val position0 = lastSpatial?.position ?: Vector3f(0f, 0f, 0f)
val position1 = this.position
val lastToPresent = Vector3f()
logger.info("distance: ${position1.sub(position0, lastToPresent).length()}")
val line = Line(simple = true)
line.addPoint(position0)
line.addPoint(position1)
scene.addChild(line)
val board = TextBoard()
board.text = "Distance: ${lastToPresent.length()} units"
board.name = "DistanceTextBoard"
board.transparent = 0
board.fontColor = Vector4f(0.0f, 0.0f, 0.0f, 1.0f)
board.backgroundColor = Vector4f(100f, 100f, 100f, 1.0f)
val boardPosition = Vector3f()
position0.add(position1, boardPosition)
board.spatial {
position = boardPosition.mul(0.5f)
scale = Vector3f(0.5f, 0.5f, 0.5f)
}
scene.addChild(board)
}
secondNode = !secondNode
}
}
}
renderer?.let { r ->
inputHandler?.addBehaviour("select", SelectCommand("select", r, scene,
{ scene.findObserver() }, action = wiggle, debugRaycast = false))
inputHandler?.addKeyBinding("select", "double-click button1")
}
}
companion object {
@JvmStatic
fun main(args: Array<String>) {
DistanceMeasurement().main()
}
}
}
| lgpl-3.0 | 3f5cb81e6f054e73a18a0d9deb19f244 | 35.413223 | 109 | 0.528597 | 4.353755 | false | false | false | false |
google/ground-android | ground/src/main/java/com/google/android/ground/ui/map/gms/GoogleMapsFragment.kt | 1 | 17493 | /*
* Copyright 2018 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
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.ground.ui.map.gms
import android.annotation.SuppressLint
import android.graphics.Color
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.RelativeLayout
import androidx.annotation.IdRes
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import com.cocoahero.android.gmaps.addons.mapbox.MapBoxOfflineTileProvider
import com.google.android.gms.maps.CameraUpdateFactory
import com.google.android.gms.maps.GoogleMap
import com.google.android.gms.maps.GoogleMap.OnCameraMoveStartedListener
import com.google.android.gms.maps.SupportMapFragment
import com.google.android.gms.maps.model.*
import com.google.android.gms.maps.model.Polygon as MapsPolygon
import com.google.android.ground.R
import com.google.android.ground.model.geometry.LineString
import com.google.android.ground.model.geometry.LinearRing
import com.google.android.ground.model.geometry.MultiPolygon
import com.google.android.ground.model.geometry.Point
import com.google.android.ground.model.geometry.Polygon
import com.google.android.ground.model.job.Style
import com.google.android.ground.model.locationofinterest.LocationOfInterest
import com.google.android.ground.rx.Nil
import com.google.android.ground.rx.annotations.Hot
import com.google.android.ground.ui.MarkerIconFactory
import com.google.android.ground.ui.common.AbstractFragment
import com.google.android.ground.ui.map.*
import com.google.android.ground.ui.map.CameraPosition
import com.google.android.ground.ui.util.BitmapUtil
import com.google.common.collect.ImmutableList
import com.google.common.collect.ImmutableSet
import com.google.maps.android.PolyUtil
import dagger.hilt.android.AndroidEntryPoint
import io.reactivex.Flowable
import io.reactivex.Observable
import io.reactivex.processors.FlowableProcessor
import io.reactivex.processors.PublishProcessor
import io.reactivex.subjects.PublishSubject
import io.reactivex.subjects.Subject
import java.io.File
import java8.util.function.Consumer
import javax.inject.Inject
import kotlin.math.min
import kotlin.math.sqrt
import timber.log.Timber
/**
* Customization of Google Maps API Fragment that automatically adjusts the Google watermark based
* on window insets.
*/
@AndroidEntryPoint
class GoogleMapsFragment : SupportMapFragment(), MapFragment {
/** Marker click events. */
private val markerClicks: @Hot Subject<MapLocationOfInterest> = PublishSubject.create()
/** Ambiguous click events. */
private val locationOfInterestClicks: @Hot Subject<ImmutableList<MapLocationOfInterest>> =
PublishSubject.create()
/** Map drag events. Emits items when the map drag has started. */
private val startDragEventsProcessor: @Hot FlowableProcessor<Nil> = PublishProcessor.create()
/** Camera move events. Emits items after the camera has stopped moving. */
private val cameraMovedEventsProcessor: @Hot FlowableProcessor<CameraPosition> =
PublishProcessor.create()
// TODO(#693): Simplify impl of tile providers.
// TODO(#691): This is a limitation of the MapBox tile provider we're using;
// since one need to call `close` explicitly, we cannot generically expose these as TileProviders;
// instead we must retain explicit reference to the concrete type.
private val tileProvidersSubject: @Hot PublishSubject<MapBoxOfflineTileProvider> =
PublishSubject.create()
/**
* References to Google Maps SDK Markers present on the map. Used to sync and update polylines
* with current view and data state.
*/
private val markers: MutableMap<Marker, MapLocationOfInterest> = HashMap()
private val polygons: MutableMap<MapLocationOfInterest, MutableList<MapsPolygon>> = HashMap()
@Inject lateinit var bitmapUtil: BitmapUtil
@Inject lateinit var markerIconFactory: MarkerIconFactory
private var map: GoogleMap? = null
/**
* User selected [LocationOfInterest] by either clicking the bottom card or horizontal scrolling.
*/
private var activeLocationOfInterest: String? = null
/**
* References to Google Maps SDK CustomCap present on the map. Used to set the custom drawable to
* start and end of polygon.
*/
private lateinit var customCap: CustomCap
private var cameraChangeReason = OnCameraMoveStartedListener.REASON_DEVELOPER_ANIMATION
private fun onApplyWindowInsets(view: View, insets: WindowInsetsCompat): WindowInsetsCompat {
val insetBottom = insets.systemWindowInsetBottom
// TODO: Move extra padding to dimens.xml.
// HACK: Fix padding when keyboard is shown; we limit the padding here to prevent the
// watermark from flying up too high due to the combination of translateY and big inset
// size due to keyboard.
setWatermarkPadding(view, 20, 0, 0, min(insetBottom, 250) + 8)
return insets
}
private fun setWatermarkPadding(view: View, left: Int, top: Int, right: Int, bottom: Int) {
// Watermark may be null if Maps failed to load.
val watermark = view.findViewWithTag<ImageView>("GoogleWatermark") ?: return
val params = watermark.layoutParams as RelativeLayout.LayoutParams
params.setMargins(left, top, right, bottom)
watermark.layoutParams = params
}
override val availableMapTypes: ImmutableList<MapType> = MAP_TYPES
private fun getMap(): GoogleMap {
checkNotNull(map) { "Map is not ready" }
return map!!
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
customCap = CustomCap(bitmapUtil.bitmapDescriptorFromVector(R.drawable.ic_endpoint))
}
override fun onCreateView(
layoutInflater: LayoutInflater,
viewGroup: ViewGroup?,
bundle: Bundle?
): View =
super.onCreateView(layoutInflater, viewGroup, bundle)!!.apply {
ViewCompat.setOnApplyWindowInsetsListener(this) { view, insets ->
onApplyWindowInsets(view, insets)
}
}
override fun attachToFragment(
containerFragment: AbstractFragment,
@IdRes containerId: Int,
mapAdapter: Consumer<MapFragment>
) {
containerFragment.replaceFragment(containerId, this)
getMapAsync { googleMap: GoogleMap ->
onMapReady(googleMap)
mapAdapter.accept(this)
}
}
private fun onMapReady(map: GoogleMap) {
this.map = map
map.setOnMarkerClickListener { marker: Marker -> onMarkerClick(marker) }
val uiSettings = map.uiSettings
uiSettings.isRotateGesturesEnabled = false
uiSettings.isTiltGesturesEnabled = false
uiSettings.isMyLocationButtonEnabled = false
uiSettings.isMapToolbarEnabled = false
uiSettings.isCompassEnabled = false
uiSettings.isIndoorLevelPickerEnabled = false
map.setOnCameraIdleListener { onCameraIdle() }
map.setOnCameraMoveStartedListener { reason: Int -> onCameraMoveStarted(reason) }
map.setOnMapClickListener { latLng: LatLng -> onMapClick(latLng) }
}
// Handle taps on ambiguous features.
private fun handleAmbiguity(latLng: LatLng) {
val candidates = ImmutableList.builder<MapLocationOfInterest>()
val processed = ArrayList<String>()
for ((mapLocationOfInterest, value) in polygons) {
val loiId = mapLocationOfInterest.locationOfInterest.id
if (processed.contains(loiId)) {
continue
}
if (value.any { PolyUtil.containsLocation(latLng, it.points, false) }) {
candidates.add(mapLocationOfInterest)
}
processed.add(loiId)
}
val result = candidates.build()
if (!result.isEmpty()) {
locationOfInterestClicks.onNext(result)
}
}
private fun onMarkerClick(marker: Marker): Boolean =
if (getMap().uiSettings.isZoomGesturesEnabled) {
markers[marker]?.let { markerClicks.onNext(it) }
// Allow map to pan to marker.
false
} else {
// Prevent map from panning to marker.
true
}
override val locationOfInterestInteractions: @Hot Observable<MapLocationOfInterest> = markerClicks
override val ambiguousLocationOfInterestInteractions:
@Hot
Observable<ImmutableList<MapLocationOfInterest>> =
locationOfInterestClicks
override val startDragEvents: @Hot Flowable<Nil> = this.startDragEventsProcessor
override val cameraMovedEvents: @Hot Flowable<CameraPosition> = cameraMovedEventsProcessor
override val tileProviders: @Hot Observable<MapBoxOfflineTileProvider> = tileProvidersSubject
override fun getDistanceInPixels(point1: Point, point2: Point): Double {
if (map == null) {
Timber.e("Null Map reference")
return 0.toDouble()
}
val projection = map!!.projection
val loc1 = projection.toScreenLocation(point1.toLatLng())
val loc2 = projection.toScreenLocation(point2.toLatLng())
val dx = (loc1.x - loc2.x).toDouble()
val dy = (loc1.y - loc2.y).toDouble()
return sqrt(dx * dx + dy * dy)
}
override fun enableGestures() = getMap().uiSettings.setAllGesturesEnabled(true)
override fun disableGestures() = getMap().uiSettings.setAllGesturesEnabled(false)
override fun moveCamera(point: Point) =
getMap().moveCamera(CameraUpdateFactory.newLatLng(point.toLatLng()))
override fun moveCamera(point: Point, zoomLevel: Float) =
getMap().moveCamera(CameraUpdateFactory.newLatLngZoom(point.toLatLng(), zoomLevel))
private fun addMapPin(mapLocationOfInterest: MapLocationOfInterest, point: Point) {
val position = point.toLatLng()
// TODO: add the anchor values into the resource dimensions file
val marker =
getMap()
.addMarker(
MarkerOptions().position(position).icon(getMarkerIcon()).anchor(0.5f, 0.85f).alpha(1.0f)
)
markers[marker] = mapLocationOfInterest
marker.tag = Pair(mapLocationOfInterest.locationOfInterest.id, LocationOfInterest::javaClass)
}
private fun getMarkerIcon(isSelected: Boolean = false): BitmapDescriptor =
markerIconFactory.getMarkerIcon(parseColor(Style().color), currentZoomLevel, isSelected)
private fun addMultiPolygon(
locationOfInterest: MapLocationOfInterest,
multiPolygon: MultiPolygon
) = multiPolygon.polygons.forEach { addPolygon(locationOfInterest, it) }
private fun addPolygon(locationOfInterest: MapLocationOfInterest, polygon: Polygon) {
val options = PolygonOptions()
options.clickable(false)
val shellVertices = polygon.shell.vertices.map { it.toLatLng() }
options.addAll(shellVertices)
val holes = polygon.holes.map { hole -> hole.vertices.map { point -> point.toLatLng() } }
holes.forEach { options.addHole(it) }
val mapsPolygon = getMap().addPolygon(options)
mapsPolygon.tag = Pair(locationOfInterest.locationOfInterest.id, LocationOfInterest::javaClass)
mapsPolygon.strokeWidth = polylineStrokeWidth.toFloat()
// TODO(jsunde): Figure out where we want to get the style from
// parseColor(Style().color)
mapsPolygon.fillColor = parseColor("#55ffffff")
mapsPolygon.strokeColor = parseColor(Style().color)
mapsPolygon.strokeJointType = JointType.ROUND
polygons.getOrPut(locationOfInterest) { mutableListOf() }.add(mapsPolygon)
}
private val polylineStrokeWidth: Int
get() = resources.getDimension(R.dimen.polyline_stroke_width).toInt()
private fun onMapClick(latLng: LatLng) = handleAmbiguity(latLng)
override val currentZoomLevel: Float
get() = getMap().cameraPosition.zoom
@SuppressLint("MissingPermission")
override fun enableCurrentLocationIndicator() {
if (!getMap().isMyLocationEnabled) {
getMap().isMyLocationEnabled = true
}
}
override fun renderLocationsOfInterest(features: ImmutableSet<MapLocationOfInterest>) {
Timber.v("setMapLocationsOfInterest() called with ${features.size} locations of interest")
val featuresToUpdate: MutableSet<MapLocationOfInterest> = HashSet(features)
val deletedMarkers: MutableList<Marker> = ArrayList()
for ((marker, pinLocationOfInterest) in markers) {
if (features.contains(pinLocationOfInterest)) {
// If existing pin is present and up-to-date, don't update it.
featuresToUpdate.remove(pinLocationOfInterest)
} else {
// If pin isn't present or up-to-date, remove it so it can be added back later.
removeMarker(marker)
deletedMarkers.add(marker)
}
}
// Update markers list.
deletedMarkers.forEach { markers.remove(it) }
val mapsPolygonIterator = polygons.entries.iterator()
while (mapsPolygonIterator.hasNext()) {
val (mapLocationOfInterest, polygons) = mapsPolygonIterator.next()
if (features.contains(mapLocationOfInterest)) {
// If polygons already exists on map, don't add them.
featuresToUpdate.remove(mapLocationOfInterest)
} else {
// Remove existing polygons not in list of updatedLocationsOfInterest.
polygons.forEach { removePolygon(it) }
mapsPolygonIterator.remove()
}
}
if (features.isEmpty()) return
Timber.v("Updating ${features.size} features")
features.forEach {
val geometry = it.locationOfInterest.geometry
when (geometry) {
is LineString -> TODO()
is LinearRing -> TODO()
is MultiPolygon -> addMultiPolygon(it, geometry)
is Point -> addMapPin(it, geometry)
is Polygon -> addPolygon(it, geometry)
}
}
}
override fun refreshRenderedLocationsOfInterest() {
for ((marker, mapLocationOfInterest) in markers) {
val isSelected = mapLocationOfInterest.locationOfInterest.id == activeLocationOfInterest
marker.setIcon(getMarkerIcon(isSelected))
}
}
override var mapType: Int
get() = getMap().mapType
set(mapType) {
getMap().mapType = mapType
}
private fun removeMarker(marker: Marker) {
Timber.v("Removing marker ${marker.id}")
marker.remove()
}
private fun removePolygon(polygon: MapsPolygon) {
Timber.v("Removing polygon ${polygon.id}")
polygon.remove()
}
private fun parseColor(colorHexCode: String?): Int =
try {
Color.parseColor(colorHexCode.toString())
} catch (e: IllegalArgumentException) {
Timber.w("Invalid color code in job style: $colorHexCode")
resources.getColor(R.color.colorMapAccent)
}
private fun onCameraIdle() {
if (cameraChangeReason == OnCameraMoveStartedListener.REASON_GESTURE) {
cameraMovedEventsProcessor.onNext(
CameraPosition(
getMap().cameraPosition.target.toPoint(),
getMap().cameraPosition.zoom,
false,
getMap().projection.visibleRegion.latLngBounds.toModelObject()
)
)
cameraChangeReason = OnCameraMoveStartedListener.REASON_DEVELOPER_ANIMATION
}
}
private fun onCameraMoveStarted(reason: Int) {
cameraChangeReason = reason
if (reason == OnCameraMoveStartedListener.REASON_GESTURE) {
this.startDragEventsProcessor.onNext(Nil.NIL)
}
}
override var viewport: Bounds
get() = getMap().projection.visibleRegion.latLngBounds.toModelObject()
set(bounds) =
getMap().moveCamera(CameraUpdateFactory.newLatLngBounds(bounds.toGoogleMapsObject(), 0))
private fun addTileOverlay(filePath: String) {
val mbtilesFile = File(requireContext().filesDir, filePath)
if (!mbtilesFile.exists()) {
Timber.i("mbtiles file ${mbtilesFile.absolutePath} does not exist")
return
}
try {
val tileProvider = MapBoxOfflineTileProvider(mbtilesFile)
tileProvidersSubject.onNext(tileProvider)
getMap().addTileOverlay(TileOverlayOptions().tileProvider(tileProvider))
} catch (e: Exception) {
Timber.e(e, "Couldn't initialize tile provider for mbtiles file $mbtilesFile")
}
}
override fun addLocalTileOverlays(mbtilesFiles: ImmutableSet<String>) =
mbtilesFiles.forEach { filePath -> addTileOverlay(filePath) }
private fun addRemoteTileOverlay(url: String) {
val webTileProvider = WebTileProvider(url)
getMap().addTileOverlay(TileOverlayOptions().tileProvider(webTileProvider))
}
override fun addRemoteTileOverlays(urls: ImmutableList<String>) =
urls.forEach { addRemoteTileOverlay(it) }
override fun setActiveLocationOfInterest(locationOfInterest: LocationOfInterest?) {
val newId = locationOfInterest?.id
if (activeLocationOfInterest == newId) return
activeLocationOfInterest = newId
// TODO: Optimize the performance by refreshing old and new rendered geometries
refreshRenderedLocationsOfInterest()
}
companion object {
// TODO(#936): Remove placeholder with appropriate images
private val MAP_TYPES =
ImmutableList.builder<MapType>()
.add(MapType(GoogleMap.MAP_TYPE_NORMAL, R.string.road_map, R.drawable.ground_logo))
.add(MapType(GoogleMap.MAP_TYPE_TERRAIN, R.string.terrain, R.drawable.ground_logo))
.add(MapType(GoogleMap.MAP_TYPE_HYBRID, R.string.satellite, R.drawable.ground_logo))
.build()
}
}
| apache-2.0 | e0a751346f649e1a7b50fd3a921c8554 | 36.700431 | 100 | 0.73961 | 4.495759 | false | false | false | false |
mdanielwork/intellij-community | platform/platform-impl/src/com/intellij/ide/ui/laf/darcula/ui/customFrameDecorations/HelpAction.kt | 4 | 1126 | // Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.ide.ui.laf.darcula.ui.customFrameDecorations
import com.intellij.openapi.ui.DialogWrapper
import java.awt.event.ActionEvent
import javax.swing.AbstractAction
import javax.swing.Action
import javax.swing.JComponent
class HelpAction(val component : JComponent) : AbstractAction() {
fun isAvailable(): Boolean {
return getHelpAction() != null
}
private fun getHelpAction(): Action? {
val dialog = DialogWrapper.findInstance(component)
if (dialog != null) {
try {
val getHelpAction = DialogWrapper::class.java.getDeclaredMethod("getHelpAction")
getHelpAction.isAccessible = true
val helpAction = getHelpAction.invoke(dialog)
if (helpAction is Action && helpAction.isEnabled) {
return helpAction
}
}
catch (e: Exception) {
e.printStackTrace()
}
}
return null
}
override fun actionPerformed(e: ActionEvent) {
getHelpAction()?.actionPerformed(e)
}
} | apache-2.0 | 9799bafcd8cfa643e1daac17323ffd8e | 30.305556 | 140 | 0.702487 | 4.415686 | false | false | false | false |
Frederikam/FredBoat | FredBoat/src/main/java/fredboat/command/moderation/HardbanCommand.kt | 1 | 5848 | /*
* MIT License
*
* Copyright (c) 2017 Frederik Ar. Mikkelsen
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package fredboat.command.moderation
import com.fredboat.sentinel.SentinelExchanges
import com.fredboat.sentinel.entities.ModRequest
import com.fredboat.sentinel.entities.ModRequestType
import fredboat.messaging.internal.Context
import fredboat.perms.Permission
import fredboat.util.DiscordUtil
import fredboat.util.TextUtils
import fredboat.util.extension.escapeAndDefuse
import kotlinx.coroutines.reactive.awaitFirst
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import org.springframework.amqp.core.MessageDeliveryMode
import reactor.core.publisher.Mono
/**
* Created by napster on 19.04.17.
*
* Ban a user.
*/
class HardbanCommand(name: String, vararg aliases: String) : DiscordModerationCommand(name, *aliases) {
companion object {
private val log: Logger = LoggerFactory.getLogger(HardbanCommand::class.java)
}
override fun modAction(args: DiscordModerationCommand.ModActionInfo): Mono<Unit> {
val deleteDays = if(args.isKeepMessages) 0 else DiscordModerationCommand.DEFAULT_DELETE_DAYS
return args.context.sentinel.genericMonoSendAndReceive<String, Unit>(
exchange = SentinelExchanges.REQUESTS,
request = ModRequest(
guildId = args.context.guild.id,
userId = args.targetUser.id,
type = ModRequestType.BAN,
banDeleteDays = deleteDays,
reason = args.formattedReason
),
routingKey = args.context.routingKey,
mayBeEmpty = true,
deliveryMode = MessageDeliveryMode.PERSISTENT,
transform = {}
)
}
override fun requiresMember() = false
override fun onSuccess(args: DiscordModerationCommand.ModActionInfo) = {
val successOutput = (args.context.i18nFormat("hardbanSuccess",
args.targetUser.asMention + " " + TextUtils.escapeAndDefuse(args.targetAsString()))
+ "\n" + TextUtils.escapeAndDefuse(args.plainReason))
args.context.replyWithName(successOutput)
}
override fun onFail(args: DiscordModerationCommand.ModActionInfo): (t: Throwable) -> Unit {
val escapedTargetName = TextUtils.escapeAndDefuse(args.targetAsString())
return { t ->
log.error("Failed to issue ban", t)
args.context.replyWithName(args.context.i18nFormat("modBanFail", "${args.targetUser.asMention} $escapedTargetName"))
}
}
override suspend fun checkAuthorizationWithFeedback(args: DiscordModerationCommand.ModActionInfo): Boolean {
val context = args.context
val target = args.targetMember
val mod = context.member
if (!context.checkInvokerPermissionsWithFeedback(Permission.BAN_MEMBERS)) return false
if (!context.checkSelfPermissionsWithFeedback(Permission.BAN_MEMBERS)) return false
if (target == null) return false
if (mod == target) {
context.replyWithName(context.i18n("hardbanFailSelf"))
return false
}
if (target.isOwner()) {
context.replyWithName(context.i18n("hardbanFailOwner"))
return false
}
if (target == target.guild.selfMember) {
context.replyWithName(context.i18n("hardbanFailMyself"))
return false
}
val modRole = DiscordUtil.getHighestRolePosition(mod).awaitFirst()
val targetRole = DiscordUtil.getHighestRolePosition(target).awaitFirst()
val selfRole = DiscordUtil.getHighestRolePosition(mod.guild.selfMember).awaitFirst()
if (modRole <= targetRole && !mod.isOwner()) {
context.replyWithName(context.i18nFormat("modFailUserHierarchy", target.effectiveName.escapeAndDefuse()))
return false
}
if (selfRole <= targetRole) {
context.replyWithName(context.i18nFormat("modFailBotHierarchy", target.effectiveName.escapeAndDefuse()))
return false
}
return true
}
override fun dmForTarget(args: DiscordModerationCommand.ModActionInfo): String? {
return args.context.i18nFormat("modActionTargetDmBanned",
"**${TextUtils.escapeMarkdown(args.context.guild.name)}**",
TextUtils.asString(args.context.user))+ "\n" + args.plainReason
}
override fun help(context: Context): String {
return ("{0}{1} <user>\n"
+ "{0}{1} <user> <reason>\n"
+ "{0}{1} <user> <reason> --keep\n"
+ "#" + context.i18n("helpHardbanCommand") + "\n" + context.i18nFormat("modKeepMessages", "--keep or -k"))
}
}
| mit | b87ed852d10e97391c77056f01c54bd6 | 40.475177 | 128 | 0.674419 | 4.697189 | false | false | false | false |
MasoodFallahpoor/InfoCenter | InfoCenter/src/main/java/com/fallahpoor/infocenter/fragments/StorageFragment.kt | 1 | 7348 | /*
Copyright (C) 2014-2018 Masood Fallahpoor
This file is part of Info Center.
Info Center 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.
Info Center 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 Info Center. If not, see <http://www.gnu.org/licenses/>.
*/
package com.fallahpoor.infocenter.fragments
import android.Manifest
import android.annotation.TargetApi
import android.content.pm.PackageManager
import android.os.Build
import android.os.Bundle
import android.os.Environment
import android.os.StatFs
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.app.ActivityCompat
import androidx.fragment.app.Fragment
import com.fallahpoor.infocenter.R
import com.fallahpoor.infocenter.Utils
import com.fallahpoor.infocenter.adapters.CustomArrayAdapter
import com.fallahpoor.infocenter.adapters.HeaderListItem
import com.fallahpoor.infocenter.adapters.ListItem
import com.fallahpoor.infocenter.adapters.OrdinaryListItem
import kotlinx.android.synthetic.main.fragment_storage.*
import java.io.File
import java.util.*
/**
* StorageFragment displays some information about the size of internal and
* external storage of the device.
*/
class StorageFragment : Fragment() {
private var utils: Utils? = null
private var isApiAtLeast18: Boolean = false
private val listItems: ArrayList<ListItem>
get() {
val freeSpace: String = getString(R.string.sto_item_free_space)
val totalSpace: String = getString(R.string.sto_item_total_space)
return ArrayList<ListItem>().apply {
add(HeaderListItem(getString(R.string.sto_item_int_storage)))
add(OrdinaryListItem(totalSpace, internalTotal))
add(OrdinaryListItem(freeSpace, internalFree))
add(HeaderListItem(getString(R.string.sto_item_ext_storage)))
add(OrdinaryListItem(totalSpace, externalTotal))
add(OrdinaryListItem(freeSpace, externalFree))
}
}
// Returns the total size of internal storage
private val internalTotal: String
@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2)
get() {
val size: Long
val internalStatFs = StatFs(Environment.getDataDirectory().absolutePath)
size = if (isApiAtLeast18) {
internalStatFs.totalBytes
} else {
internalStatFs.blockCount.toLong() * internalStatFs.blockSize.toLong()
}
return utils!!.getFormattedSize(size)
}
// Returns the free size of internal storage
private val internalFree: String
@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2)
get() {
val size: Long
val internalStatFs = StatFs(Environment.getDataDirectory().absolutePath)
size = if (isApiAtLeast18) {
internalStatFs.availableBytes
} else {
internalStatFs.availableBlocks.toLong() * internalStatFs.blockSize.toLong()
}
return utils!!.getFormattedSize(size)
}
// Returns the total size of external storage
private val externalTotal: String
@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2)
get() {
val size: Long
val extStorageStatFs: StatFs
val extStoragePath = externalStoragePath
if (extStoragePath == null || !File(extStoragePath).exists()) {
return getString(R.string.sto_sub_item_ext_storage_not_available)
}
extStorageStatFs = StatFs(File(extStoragePath).absolutePath)
size = if (isApiAtLeast18) {
extStorageStatFs.totalBytes
} else {
extStorageStatFs.blockCount.toLong() * extStorageStatFs.blockSize.toLong()
}
return utils!!.getFormattedSize(size)
}
// Returns the free size of external storage
private val externalFree: String
@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2)
get() {
val size: Long
val extStorageStatFs: StatFs
val extStoragePath = externalStoragePath
if (extStoragePath == null || !File(extStoragePath).exists()) {
return getString(R.string.sto_sub_item_ext_storage_not_available)
}
extStorageStatFs = StatFs(File(extStoragePath).absolutePath)
size = if (isApiAtLeast18) {
extStorageStatFs.availableBytes
} else {
extStorageStatFs.availableBlocks.toLong() * extStorageStatFs.blockSize.toLong()
}
return utils!!.getFormattedSize(size)
}
private val externalStoragePath: String?
get() = if (!Environment.isExternalStorageEmulated() && Environment.getExternalStorageState().equals(
Environment.MEDIA_MOUNTED,
ignoreCase = true
)
) {
Environment.getExternalStorageDirectory().absolutePath
} else {
System.getenv("SECONDARY_STORAGE")
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
super.onCreateView(inflater, container, savedInstanceState)
return inflater.inflate(R.layout.fragment_storage, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
utils = Utils(activity!!)
isApiAtLeast18 = Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2
listView.setShadowVisible(false)
textView.setText(R.string.sto_sub_item_ext_storage_not_available)
if (ActivityCompat.checkSelfPermission(
activity!!,
Manifest.permission.READ_EXTERNAL_STORAGE
) == PackageManager.PERMISSION_GRANTED
) {
populateListView()
} else {
requestPermissions(
arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE),
REQUEST_CODE_READ_EXTERNAL_STORAGE
)
}
}
private fun populateListView() {
listView.adapter = CustomArrayAdapter(activity, listItems)
}
override fun onRequestPermissionsResult(
requestCode: Int, permissions: Array<String>,
grantResults: IntArray
) {
if (requestCode == REQUEST_CODE_READ_EXTERNAL_STORAGE) {
if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
populateListView()
} else {
listView.emptyView = textView
}
}
}
private companion object {
private const val REQUEST_CODE_READ_EXTERNAL_STORAGE = 1004
}
} | gpl-3.0 | 5d73fe320af021c4f28fb4a5fc9aaba7 | 32.404545 | 109 | 0.648476 | 4.771429 | false | false | false | false |
flesire/ontrack | ontrack-job/src/main/java/net/nemerosa/ontrack/job/JobKey.kt | 1 | 849 | package net.nemerosa.ontrack.job
import io.micrometer.core.instrument.Tag
data class JobKey(
val type: JobType,
val id: String
) {
fun sameType(type: JobType): Boolean {
return this.type == type
}
fun sameCategory(category: JobCategory): Boolean {
return this.type.category == category
}
override fun toString(): String {
return String.format(
"%s[%s]",
type,
id
)
}
val metricTags: List<Tag>
get() = listOf(
Tag.of("job-id", id),
Tag.of("job-type", type.key),
Tag.of("job-category", type.category.key)
)
companion object {
@JvmStatic
fun of(type: JobType, id: String): JobKey {
return JobKey(type, id)
}
}
}
| mit | 24c66f4eb92cba22bf7acd3a10a0dc44 | 20.225 | 57 | 0.512367 | 4.20297 | false | false | false | false |
nibarius/opera-park-android | app/src/main/java/se/barsk/park/managecars/EditCarDialog.kt | 1 | 908 | package se.barsk.park.managecars
import android.os.Bundle
import se.barsk.park.ParkApp
import se.barsk.park.R
import se.barsk.park.datatypes.OwnCar
class EditCarDialog : ManageCarDialog() {
override val dialogTitle: Int
get() = R.string.edit_car_dialog_title
override val dialogType: DialogType
get() = DialogType.EDIT
override fun fetchOwnCar(): OwnCar {
// This dialog always have a Bundle with one parameter when set up as expected
val carId = arguments!!.getString(ARG_ID)!!
return ParkApp.carCollection.getCar(carId)
}
companion object {
private const val ARG_ID: String = "id"
fun newInstance(carId: String): EditCarDialog {
val dialog = EditCarDialog()
val args = Bundle()
args.putString(ARG_ID, carId)
dialog.arguments = args
return dialog
}
}
} | mit | 60a2897ae570d1ad445c74546bb888c3 | 26.545455 | 86 | 0.644273 | 4.203704 | false | false | false | false |
BreakOutEvent/breakout-backend | src/test/java/backend/model/payment/SponsoringInvoiceServiceImplTest.kt | 1 | 3163 | package backend.model.payment
import backend.Integration.IntegrationTest
import backend.model.misc.Coord
import backend.model.sponsoring.TeamBuilder
import backend.model.user.Admin
import backend.model.user.Sponsor
import backend.util.euroOf
import org.junit.Test
import java.time.LocalDateTime
import kotlin.test.assertFalse
import kotlin.test.assertTrue
class SponsoringInvoiceServiceImplTest : IntegrationTest() {
@Test
fun findAllNotFullyPaidInvoicesForEvent() {
// given a team with sponsors and completed challenges at one event
// with one complete and one partial payment for the sponsors invoices
val sponsor1 = userService.create("[email protected]", "test", { addRole(Sponsor::class) }).getRole(Sponsor::class)!!
val sponsor2 = userService.create("[email protected]", "test", { addRole(Sponsor::class) }).getRole(Sponsor::class)!!
val admin = userService.create("[email protected]", "pw", { addRole(Admin::class) }).getRole(Admin::class)!!
val event = eventService.createEvent("Muc", LocalDateTime.now(), "", Coord(0.0), 36)
val team = TeamBuilder.createWith(teamService, userService, userDetailsService) {
name = "Testteam"
description = ""
creator {
firstname = ""
lastname = ""
email = "[email protected]"
password = "pw"
}
invited {
firstname = ""
lastname = ""
email = "[email protected]"
password = "pw"
}
this.event = event
}.build()
setAuthenticatedUser(sponsor1.email)
val challenge1 = challengeService.proposeChallenge(sponsor1, team, euroOf(10.0), "Do something funny")
setAuthenticatedUser(sponsor2.email)
val challenge2 = challengeService.proposeChallenge(sponsor2, team, euroOf(10.0), "Yeah, but my idea is better")
val firstProof = postingService.createPosting(team.members.first(), "lol", null, null, LocalDateTime.now())
val secondProof = postingService.createPosting(team.members.first(), "nice", null, null, LocalDateTime.now())
setAuthenticatedUser(team.members.first().email)
challengeService.addProof(challenge1, firstProof)
challengeService.addProof(challenge2, secondProof)
eventService.regenerateCache(event.id!!)
sponsoringInvoiceService.createInvoicesForEvent(event)
val invoices = sponsoringInvoiceService.findAll()
val first = invoices.toList()[0]
val second = invoices.toList()[1]
sponsoringInvoiceService.addAdminPaymentToInvoice(admin, euroOf(10.0), first, null, null)
sponsoringInvoiceService.addAdminPaymentToInvoice(admin, euroOf(5.0), first, null, null)
// when looking for not fully paid invoices
val notFullyPaid = sponsoringInvoiceService.findAllNotFullyPaidInvoicesForEvent(event)
// then it only contains the one which is not fully paid yet
assertTrue(notFullyPaid.contains(second))
assertFalse(notFullyPaid.contains(first))
}
}
| agpl-3.0 | 976d93f4c73365e3ea2b45080fe461b7 | 40.077922 | 128 | 0.674044 | 4.53802 | false | true | false | false |
google/intellij-community | plugins/kotlin/project-wizard/core/src/org/jetbrains/kotlin/tools/projectWizard/projectTemplates/ProjectTemplates.kt | 2 | 21521 | // 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.tools.projectWizard.projectTemplates
import org.jetbrains.annotations.NonNls
import org.jetbrains.kotlin.tools.projectWizard.KotlinNewProjectWizardBundle
import org.jetbrains.kotlin.tools.projectWizard.Versions
import org.jetbrains.kotlin.tools.projectWizard.core.buildList
import org.jetbrains.kotlin.tools.projectWizard.core.entity.settings.*
import org.jetbrains.kotlin.tools.projectWizard.moduleConfigurators.*
import org.jetbrains.kotlin.tools.projectWizard.plugins.StructurePlugin
import org.jetbrains.kotlin.tools.projectWizard.plugins.buildSystem.gradle.GradlePlugin
import org.jetbrains.kotlin.tools.projectWizard.plugins.kotlin.KotlinPlugin
import org.jetbrains.kotlin.tools.projectWizard.plugins.kotlin.ModuleSubType
import org.jetbrains.kotlin.tools.projectWizard.plugins.kotlin.ModuleType
import org.jetbrains.kotlin.tools.projectWizard.plugins.kotlin.ProjectKind
import org.jetbrains.kotlin.tools.projectWizard.settings.DisplayableSettingItem
import org.jetbrains.kotlin.tools.projectWizard.settings.buildsystem.*
import org.jetbrains.kotlin.tools.projectWizard.templates.*
import org.jetbrains.kotlin.tools.projectWizard.templates.compose.*
import org.jetbrains.kotlin.tools.projectWizard.templates.mpp.MobileMppTemplate
abstract class ProjectTemplate : DisplayableSettingItem {
abstract val title: String
override val text: String get() = title
abstract val description: String
abstract val suggestedProjectName: String
abstract val projectKind: ProjectKind
abstract val id: String
private val setsDefaultValues: List<SettingWithValue<*, *>>
get() = listOf(KotlinPlugin.projectKind.reference withValue projectKind)
protected open val setsPluginSettings: List<SettingWithValue<*, *>> = emptyList()
protected open val setsModules: List<Module> = emptyList()
val setsAdditionalSettingValues = mutableListOf<SettingWithValue<*, *>>()
val setsValues: List<SettingWithValue<*, *>>
get() = buildList {
setsModules.takeIf { it.isNotEmpty() }?.let { modules ->
+(KotlinPlugin.modules.reference withValue modules)
}
+setsDefaultValues
+setsPluginSettings
+setsAdditionalSettingValues
}
protected fun <T : Template> Module.withTemplate(
template: T,
createSettings: TemplateSettingsBuilder<T>.() -> Unit = {}
) = apply {
this.template = template
with(TemplateSettingsBuilder(this, template)) {
createSettings()
setsAdditionalSettingValues += setsSettings
}
}
protected inline fun <reified C: ModuleConfigurator> Module.withConfiguratorSettings(
createSettings: ConfiguratorSettingsBuilder<C>.() -> Unit = {}
) = apply {
check(configurator is C)
with(ConfiguratorSettingsBuilder(this, configurator)) {
createSettings()
setsAdditionalSettingValues += setsSettings
}
}
companion object {
val ALL = listOf(
FullStackWebApplicationProjectTemplate,
MultiplatformLibraryProjectTemplate,
NativeApplicationProjectTemplate,
FrontendApplicationProjectTemplate,
ReactApplicationProjectTemplate,
NodeJsApplicationProjectTemplate,
ComposeDesktopApplicationProjectTemplate,
ComposeMultiplatformApplicationProjectTemplate,
ComposeWebApplicationProjectTemplate,
ConsoleApplicationProjectTemplateWithSample
)
fun byId(id: String): ProjectTemplate? = ALL.firstOrNull {
it.id.equals(id, ignoreCase = true)
}
}
}
private infix fun <V : Any, T : SettingType<V>> PluginSettingReference<V, T>.withValue(value: V): SettingWithValue<V, T> =
SettingWithValue(this, value)
private inline infix fun <V : Any, reified T : SettingType<V>> PluginSetting<V, T>.withValue(value: V): SettingWithValue<V, T> =
SettingWithValue(reference, value)
fun createDefaultSourceSets() =
SourcesetType.values().map { sourceSetType ->
Sourceset(
sourceSetType,
dependencies = emptyList()
)
}
private fun ModuleType.createDefaultTarget(name: String = this.name, permittedTemplateIds: Set<String>? = null) =
MultiplatformTargetModule(name, defaultTarget, createDefaultSourceSets(), permittedTemplateIds)
open class ConsoleApplicationProjectTemplate(private val addSampleCode: Boolean) : ProjectTemplate() {
override val title = KotlinNewProjectWizardBundle.message("project.template.empty.jvm.console.title")
override val description = KotlinNewProjectWizardBundle.message("project.template.empty.jvm.console.description")
override val id = "consoleApplication"
@NonNls
override val suggestedProjectName = "myConsoleApplication"
override val projectKind = ProjectKind.Singleplatform
override val setsPluginSettings: List<SettingWithValue<*, *>>
get() = listOf(
KotlinPlugin.modules.reference withValue listOf(
SinglePlatformModule(
"consoleApp",
createDefaultSourceSets(),
permittedTemplateIds = setOf(ConsoleJvmApplicationTemplate.id)
).apply {
if (addSampleCode)
withTemplate(ConsoleJvmApplicationTemplate)
}
)
)
}
object ConsoleApplicationProjectTemplateWithSample : ConsoleApplicationProjectTemplate(addSampleCode = true)
object MultiplatformLibraryProjectTemplate : ProjectTemplate() {
override val title = KotlinNewProjectWizardBundle.message("project.template.mpp.lib.title")
override val description = KotlinNewProjectWizardBundle.message("project.template.mpp.lib.description")
override val id = "multiplatformLibrary"
@NonNls
override val suggestedProjectName = "myMultiplatformLibrary"
override val projectKind = ProjectKind.Multiplatform
override val setsPluginSettings: List<SettingWithValue<*, *>>
get() = listOf(
KotlinPlugin.modules.reference withValue listOf(
MultiplatformModule(
"library",
permittedTemplateIds = emptySet(),
targets = listOf(
ModuleType.common.createDefaultTarget(),
ModuleType.jvm.createDefaultTarget(permittedTemplateIds = emptySet()),
MultiplatformTargetModule(
"js",
MppLibJsBrowserTargetConfigurator,
createDefaultSourceSets(),
permittedTemplateIds = emptySet()
)
.withConfiguratorSettings<MppLibJsBrowserTargetConfigurator> {
JSConfigurator.kind withValue JsTargetKind.LIBRARY
},
ModuleType.native.createDefaultTarget(permittedTemplateIds = emptySet())
)
)
)
)
}
object FullStackWebApplicationProjectTemplate : ProjectTemplate() {
override val title: String = KotlinNewProjectWizardBundle.message("project.template.full.stack.title")
override val description: String = KotlinNewProjectWizardBundle.message("project.template.full.stack.description")
override val id = "fullStackWebApplication"
@NonNls
override val suggestedProjectName: String = "myFullStackApplication"
override val projectKind: ProjectKind = ProjectKind.Multiplatform
override val setsPluginSettings: List<SettingWithValue<*, *>> = listOf(
KotlinPlugin.modules.reference withValue listOf(
MultiplatformModule(
"application",
permittedTemplateIds = emptySet(),
targets = listOf(
ModuleType.common.createDefaultTarget(),
ModuleType.jvm.createDefaultTarget(permittedTemplateIds = setOf(KtorServerTemplate.id)).apply {
withTemplate(KtorServerTemplate)
},
ModuleType.js.createDefaultTarget(permittedTemplateIds = setOf(ReactJsClientTemplate.id)).apply {
withTemplate(ReactJsClientTemplate)
}
)
)
)
)
}
object NativeApplicationProjectTemplate : ProjectTemplate() {
override val title = KotlinNewProjectWizardBundle.message("project.template.native.console.title")
override val description = KotlinNewProjectWizardBundle.message("project.template.native.console.description")
override val id = "nativeApplication"
@NonNls
override val suggestedProjectName = "myNativeConsoleApp"
override val projectKind = ProjectKind.Multiplatform
override val setsPluginSettings: List<SettingWithValue<*, *>>
get() = listOf(
KotlinPlugin.modules.reference withValue listOf(
Module(
"app",
MppModuleConfigurator,
permittedTemplateIds = emptySet(),
sourceSets = emptyList(),
subModules = listOf(
ModuleType.native.createDefaultTarget("native", permittedTemplateIds = setOf(NativeConsoleApplicationTemplate.id))
.apply {
withTemplate(NativeConsoleApplicationTemplate)
}
)
)
)
)
}
object FrontendApplicationProjectTemplate : ProjectTemplate() {
override val title = KotlinNewProjectWizardBundle.message("project.template.browser.title")
override val description = KotlinNewProjectWizardBundle.message("project.template.browser.description")
override val id = "frontendApplication"
@NonNls
override val suggestedProjectName = "myKotlinJsApplication"
override val projectKind = ProjectKind.Js
override val setsPluginSettings: List<SettingWithValue<*, *>>
get() = listOf(
KotlinPlugin.modules.reference withValue listOf(
Module(
"browser",
BrowserJsSinglePlatformModuleConfigurator,
template = SimpleJsClientTemplate,
permittedTemplateIds = setOf(SimpleJsClientTemplate.id),
sourceSets = SourcesetType.ALL.map { type ->
Sourceset(type, dependencies = emptyList())
},
subModules = emptyList()
)
)
)
}
object ReactApplicationProjectTemplate : ProjectTemplate() {
override val title = KotlinNewProjectWizardBundle.message("project.template.react.title")
override val description = KotlinNewProjectWizardBundle.message("project.template.react.description")
override val id = "reactApplication"
@NonNls
override val suggestedProjectName = "myKotlinJsApplication"
override val projectKind = ProjectKind.Js
override val setsPluginSettings: List<SettingWithValue<*, *>>
get() = listOf(
KotlinPlugin.modules.reference withValue listOf(
Module(
"react",
BrowserJsSinglePlatformModuleConfigurator,
template = ReactJsClientTemplate,
permittedTemplateIds = setOf(ReactJsClientTemplate.id),
sourceSets = SourcesetType.ALL.map { type ->
Sourceset(type, dependencies = emptyList())
},
subModules = emptyList()
)
)
)
}
abstract class MultiplatformMobileApplicationProjectTemplateBase : ProjectTemplate() {
override val title = KotlinNewProjectWizardBundle.message("project.template.mpp.mobile.title")
override val description = KotlinNewProjectWizardBundle.message("project.template.mpp.mobile.description")
@NonNls
override val suggestedProjectName = "myIOSApplication"
override val projectKind = ProjectKind.Multiplatform
override val setsModules: List<Module> = buildList {
val shared = MultiplatformModule(
"shared",
template = MobileMppTemplate(),
targets = listOf(
ModuleType.common.createDefaultTarget(),
Module(
"android",
AndroidTargetConfigurator,
null,
sourceSets = createDefaultSourceSets(),
subModules = emptyList()
).withConfiguratorSettings<AndroidTargetConfigurator> {
configurator.androidPlugin withValue AndroidGradlePlugin.LIBRARY
},
Module(
"ios",
sharedIosConfigurator,
null,
permittedTemplateIds = emptySet(),
sourceSets = createDefaultSourceSets(),
subModules = emptyList()
)
)
)
+iosAppModule(shared)
+androidAppModule(shared)
+shared // shared module must be the last so dependent modules could create actual files
}
protected abstract fun iosAppModule(shared: Module): Module
protected abstract fun androidAppModule(shared: Module): Module
open val sharedIosConfigurator get() = RealNativeTargetConfigurator.configuratorsByModuleType.getValue(ModuleSubType.ios)
}
object NodeJsApplicationProjectTemplate : ProjectTemplate() {
override val title = KotlinNewProjectWizardBundle.message("project.template.nodejs.title")
override val description = KotlinNewProjectWizardBundle.message("project.template.nodejs.description")
override val id = "nodejsApplication"
@NonNls
override val suggestedProjectName = "myKotlinJsApplication"
override val projectKind = ProjectKind.Js
override val setsPluginSettings: List<SettingWithValue<*, *>>
get() = listOf(
KotlinPlugin.modules.reference withValue listOf(
Module(
"nodejs",
NodeJsSinglePlatformModuleConfigurator,
template = SimpleNodeJsTemplate,
permittedTemplateIds = setOf(SimpleNodeJsTemplate.id),
sourceSets = SourcesetType.ALL.map { type ->
Sourceset(type, dependencies = emptyList())
},
subModules = emptyList()
)
)
)
}
object ComposeDesktopApplicationProjectTemplate : ProjectTemplate() {
override val title = KotlinNewProjectWizardBundle.message("project.template.compose.desktop.title")
override val description = KotlinNewProjectWizardBundle.message("project.template.compose.desktop.description")
override val id = "composeDesktopApplication"
@NonNls
override val suggestedProjectName = "myComposeDesktopApplication"
override val projectKind = ProjectKind.COMPOSE
override val setsPluginSettings: List<SettingWithValue<*, *>>
get() = listOf(
GradlePlugin.gradleVersion withValue Versions.GRADLE_VERSION_FOR_COMPOSE,
StructurePlugin.version withValue "1.0",
)
override val setsModules: List<Module>
get() = listOf(
Module(
"compose",
JvmSinglePlatformModuleConfigurator,
template = ComposeJvmDesktopTemplate(),
sourceSets = SourcesetType.ALL.map { type ->
Sourceset(type, dependencies = emptyList())
},
subModules = emptyList()
).withConfiguratorSettings<JvmSinglePlatformModuleConfigurator> {
JvmModuleConfigurator.testFramework withValue KotlinTestFramework.NONE
JvmModuleConfigurator.targetJvmVersion withValue TargetJvmVersion.JVM_11
}
)
}
object ComposeMultiplatformApplicationProjectTemplate : ProjectTemplate() {
override val title = KotlinNewProjectWizardBundle.message("project.template.compose.multiplatform.title")
override val description = KotlinNewProjectWizardBundle.message("project.template.compose.multiplatform.description")
override val id = "composeMultiplatformApplication"
@NonNls
override val suggestedProjectName = "myComposeMultiplatformApplication"
override val projectKind = ProjectKind.COMPOSE
override val setsPluginSettings: List<SettingWithValue<*, *>>
get() = listOf(
GradlePlugin.gradleVersion withValue Versions.GRADLE_VERSION_FOR_COMPOSE,
StructurePlugin.version withValue "1.0",
)
override val setsModules: List<Module>
get() = buildList {
val common = MultiplatformModule(
"common",
template = ComposeMppModuleTemplate(),
listOf(
ModuleType.common.createDefaultTarget().withConfiguratorSettings<CommonTargetConfigurator> {
JvmModuleConfigurator.testFramework withValue KotlinTestFramework.NONE
},
Module(
"android",
AndroidTargetConfigurator,
template = ComposeCommonAndroidTemplate(),
sourceSets = createDefaultSourceSets(),
subModules = emptyList()
).withConfiguratorSettings<AndroidTargetConfigurator> {
configurator.androidPlugin withValue AndroidGradlePlugin.LIBRARY
JvmModuleConfigurator.testFramework withValue KotlinTestFramework.NONE
},
Module(
"desktop",
JvmTargetConfigurator,
template = ComposeCommonDesktopTemplate(),
sourceSets = createDefaultSourceSets(),
subModules = emptyList()
).withConfiguratorSettings<JvmTargetConfigurator> {
JvmModuleConfigurator.testFramework withValue KotlinTestFramework.NONE
JvmModuleConfigurator.targetJvmVersion withValue TargetJvmVersion.JVM_11
}
)
)
+Module(
"android",
AndroidSinglePlatformModuleConfigurator,
template = ComposeAndroidTemplate(),
sourceSets = createDefaultSourceSets(),
subModules = emptyList(),
dependencies = mutableListOf(ModuleReference.ByModule(common))
).withConfiguratorSettings<AndroidSinglePlatformModuleConfigurator> {
JvmModuleConfigurator.testFramework withValue KotlinTestFramework.NONE
}
+Module(
"desktop",
MppModuleConfigurator,
template = ComposeCommonDesktopTemplate(),
sourceSets = createDefaultSourceSets(),
subModules = listOf(
Module(
"jvm",
JvmTargetConfigurator,
template = ComposeJvmDesktopTemplate(),
sourceSets = createDefaultSourceSets(),
subModules = emptyList(),
dependencies = mutableListOf(ModuleReference.ByModule(common))
).withConfiguratorSettings<JvmTargetConfigurator> {
JvmModuleConfigurator.testFramework withValue KotlinTestFramework.NONE
JvmModuleConfigurator.targetJvmVersion withValue TargetJvmVersion.JVM_11
}
),
)
+common
}
}
object ComposeWebApplicationProjectTemplate : ProjectTemplate() {
override val title = KotlinNewProjectWizardBundle.message("project.template.compose.web.title")
override val description = KotlinNewProjectWizardBundle.message("project.template.compose.web.description")
override val id = "composeWebApplication"
@NonNls
override val suggestedProjectName = "myComposeWebApplication"
override val projectKind = ProjectKind.COMPOSE
override val setsPluginSettings: List<SettingWithValue<*, *>>
get() = listOf(
GradlePlugin.gradleVersion withValue Versions.GRADLE_VERSION_FOR_COMPOSE,
StructurePlugin.version withValue "1.0",
)
override val setsModules: List<Module>
get() = listOf(
Module(
"web",
MppModuleConfigurator,
template = null,
sourceSets = createDefaultSourceSets(),
subModules = listOf(
Module(
"js",
JsComposeMppConfigurator,
template = ComposeWebModuleTemplate,
permittedTemplateIds = setOf(ComposeWebModuleTemplate.id),
sourceSets = createDefaultSourceSets(),
subModules = emptyList()
)
)
)
)
} | apache-2.0 | 47c3d9865c74dd8d6fa2c30c949edb8d | 42.922449 | 158 | 0.635008 | 6.279837 | false | true | false | false |
apache/isis | incubator/clients/kroviz/src/test/kotlin/org/apache/causeway/client/kroviz/snapshots/demo2_0_0/TUPLE_OBJECT_LAYOUT.kt | 2 | 25809 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.apache.causeway.client.kroviz.snapshots.demo2_0_0
import org.apache.causeway.client.kroviz.snapshots.Response
object TUPLE_OBJECT_LAYOUT : Response() {
override val url = "http://localhost:8080/restful/objects/demo.TupleDemo/AKztAAVzcgARamF2YS51dGlsLkhhc2hNYXAFB9rBwxZg0QMAAkYACmxvYWRGYWN0b3JJAAl0aHJlc2hvbGR4cD9AAAAAAAAAdwgAAAAQAAAAAHg=/object-layout"
override val str = """{
"row": [
{
"cols": [
{
"col": {
"domainObject": {
"named": null,
"describedAs": null,
"plural": null,
"metadataError": null,
"link": {
"rel": "urn:org.restfulobjects:rels/element",
"method": "GET",
"href": "http://localhost:8080/restful/objects/demo.TupleDemo/AKztAAVzcgARamF2YS51dGlsLkhhc2hNYXAFB9rBwxZg0QMAAkYACmxvYWRGYWN0b3JJAAl0aHJlc2hvbGR4cD9AAAAAAAAAdwgAAAAQAAAAAHg=",
"type": "application/json;profile=\"urn:org.restfulobjects:repr-types/object\""
},
"bookmarking": "AS_ROOT",
"cssClass": null,
"cssClassFa": null,
"cssClassFaPosition": null,
"namedEscaped": null
},
"action": [
{
"named": null,
"describedAs": null,
"metadataError": null,
"link": {
"rel": "urn:org.restfulobjects:rels/action",
"method": "GET",
"href": "http://localhost:8080/restful/objects/demo.TupleDemo/AKztAAVzcgARamF2YS51dGlsLkhhc2hNYXAFB9rBwxZg0QMAAkYACmxvYWRGYWN0b3JJAAl0aHJlc2hvbGR4cD9AAAAAAAAAdwgAAAAQAAAAAHg=/actions/clearHints",
"type": "application/json;profile=\"urn:org.restfulobjects:repr-types/object-action\""
},
"id": "clearHints",
"bookmarking": null,
"cssClass": null,
"cssClassFa": null,
"cssClassFaPosition": null,
"hidden": null,
"namedEscaped": null,
"position": null,
"promptStyle": null,
"redirect": null
}
],
"metadataError": null,
"cssClass": null,
"size": null,
"id": null,
"span": 12,
"unreferencedActions": true,
"unreferencedCollections": null
}
}
],
"metadataError": null,
"cssClass": null,
"id": null
},
{
"cols": [
{
"col": {
"domainObject": null,
"row": [
{
"cols": [
{
"col": {
"domainObject": null,
"tabGroup": [
{
"tab": [
{
"name": "Identity",
"row": [
{
"cols": [
{
"col": {
"domainObject": null,
"fieldSet": [
{
"name": "Identity",
"metadataError": null,
"id": "identity",
"unreferencedActions": null,
"unreferencedProperties": null
}
],
"metadataError": null,
"cssClass": null,
"size": null,
"id": null,
"span": 12,
"unreferencedActions": null,
"unreferencedCollections": null
}
}
],
"metadataError": null,
"cssClass": null,
"id": null
}
],
"cssClass": null
},
{
"name": "Other",
"row": [
{
"cols": [
{
"col": {
"domainObject": null,
"fieldSet": [
{
"name": "Other",
"property": [
{
"named": null,
"describedAs": null,
"metadataError": null,
"link": {
"rel": "urn:org.restfulobjects:rels/property",
"method": "GET",
"href": "http://localhost:8080/restful/objects/demo.TupleDemo/AKztAAVzcgARamF2YS51dGlsLkhhc2hNYXAFB9rBwxZg0QMAAkYACmxvYWRGYWN0b3JJAAl0aHJlc2hvbGR4cD9AAAAAAAAAdwgAAAAQAAAAAHg=/properties/description",
"type": "application/json;profile=\"urn:org.restfulobjects:repr-types/object-property\""
},
"id": "description",
"cssClass": null,
"hidden": null,
"labelPosition": null,
"multiLine": null,
"namedEscaped": null,
"promptStyle": null,
"renderDay": null,
"typicalLength": null,
"repainting": null,
"unchanging": null
}
],
"metadataError": null,
"id": "other",
"unreferencedActions": null,
"unreferencedProperties": true
}
],
"metadataError": null,
"cssClass": null,
"size": null,
"id": null,
"span": 12,
"unreferencedActions": null,
"unreferencedCollections": null
}
}
],
"metadataError": null,
"cssClass": null,
"id": null
}
],
"cssClass": null
},
{
"name": "Metadata",
"row": [
{
"cols": [
{
"col": {
"domainObject": null,
"fieldSet": [
{
"name": "Metadata",
"action": [
{
"named": null,
"describedAs": null,
"metadataError": null,
"link": {
"rel": "urn:org.restfulobjects:rels/action",
"method": "GET",
"href": "http://localhost:8080/restful/objects/demo.TupleDemo/AKztAAVzcgARamF2YS51dGlsLkhhc2hNYXAFB9rBwxZg0QMAAkYACmxvYWRGYWN0b3JJAAl0aHJlc2hvbGR4cD9AAAAAAAAAdwgAAAAQAAAAAHg=/actions/downloadLayoutXml",
"type": "application/json;profile=\"urn:org.restfulobjects:repr-types/object-action\""
},
"id": "downloadLayoutXml",
"bookmarking": null,
"cssClass": null,
"cssClassFa": null,
"cssClassFaPosition": null,
"hidden": null,
"namedEscaped": null,
"position": "PANEL_DROPDOWN",
"promptStyle": null,
"redirect": null
},
{
"named": null,
"describedAs": null,
"metadataError": null,
"link": {
"rel": "urn:org.restfulobjects:rels/action",
"method": "GET",
"href": "http://localhost:8080/restful/objects/demo.TupleDemo/AKztAAVzcgARamF2YS51dGlsLkhhc2hNYXAFB9rBwxZg0QMAAkYACmxvYWRGYWN0b3JJAAl0aHJlc2hvbGR4cD9AAAAAAAAAdwgAAAAQAAAAAHg=/actions/downloadMetaModelXml",
"type": "application/json;profile=\"urn:org.restfulobjects:repr-types/object-action\""
},
"id": "downloadMetaModelXml",
"bookmarking": null,
"cssClass": null,
"cssClassFa": null,
"cssClassFaPosition": null,
"hidden": null,
"namedEscaped": null,
"position": "PANEL_DROPDOWN",
"promptStyle": null,
"redirect": null
},
{
"named": null,
"describedAs": null,
"metadataError": null,
"link": {
"rel": "urn:org.restfulobjects:rels/action",
"method": "GET",
"href": "http://localhost:8080/restful/objects/demo.TupleDemo/AKztAAVzcgARamF2YS51dGlsLkhhc2hNYXAFB9rBwxZg0QMAAkYACmxvYWRGYWN0b3JJAAl0aHJlc2hvbGR4cD9AAAAAAAAAdwgAAAAQAAAAAHg=/actions/openRestApi",
"type": "application/json;profile=\"urn:org.restfulobjects:repr-types/object-action\""
},
"id": "openRestApi",
"bookmarking": null,
"cssClass": null,
"cssClassFa": null,
"cssClassFaPosition": null,
"hidden": null,
"namedEscaped": null,
"position": "PANEL_DROPDOWN",
"promptStyle": null,
"redirect": null
},
{
"named": null,
"describedAs": null,
"metadataError": null,
"link": {
"rel": "urn:org.restfulobjects:rels/action",
"method": "GET",
"href": "http://localhost:8080/restful/objects/demo.TupleDemo/AKztAAVzcgARamF2YS51dGlsLkhhc2hNYXAFB9rBwxZg0QMAAkYACmxvYWRGYWN0b3JJAAl0aHJlc2hvbGR4cD9AAAAAAAAAdwgAAAAQAAAAAHg=/actions/rebuildMetamodel",
"type": "application/json;profile=\"urn:org.restfulobjects:repr-types/object-action\""
},
"id": "rebuildMetamodel",
"bookmarking": null,
"cssClass": null,
"cssClassFa": null,
"cssClassFaPosition": null,
"hidden": null,
"namedEscaped": null,
"position": "PANEL_DROPDOWN",
"promptStyle": null,
"redirect": null
}
],
"property": [
{
"named": null,
"describedAs": null,
"metadataError": null,
"link": {
"rel": "urn:org.restfulobjects:rels/property",
"method": "GET",
"href": "http://localhost:8080/restful/objects/demo.TupleDemo/AKztAAVzcgARamF2YS51dGlsLkhhc2hNYXAFB9rBwxZg0QMAAkYACmxvYWRGYWN0b3JJAAl0aHJlc2hvbGR4cD9AAAAAAAAAdwgAAAAQAAAAAHg=/properties/objectType",
"type": "application/json;profile=\"urn:org.restfulobjects:repr-types/object-property\""
},
"id": "objectType",
"cssClass": null,
"hidden": null,
"labelPosition": null,
"multiLine": null,
"namedEscaped": null,
"promptStyle": null,
"renderDay": null,
"typicalLength": null,
"repainting": null,
"unchanging": null
},
{
"named": null,
"describedAs": null,
"metadataError": null,
"link": {
"rel": "urn:org.restfulobjects:rels/property",
"method": "GET",
"href": "http://localhost:8080/restful/objects/demo.TupleDemo/AKztAAVzcgARamF2YS51dGlsLkhhc2hNYXAFB9rBwxZg0QMAAkYACmxvYWRGYWN0b3JJAAl0aHJlc2hvbGR4cD9AAAAAAAAAdwgAAAAQAAAAAHg=/properties/objectIdentifier",
"type": "application/json;profile=\"urn:org.restfulobjects:repr-types/object-property\""
},
"id": "objectIdentifier",
"cssClass": null,
"hidden": null,
"labelPosition": null,
"multiLine": null,
"namedEscaped": null,
"promptStyle": null,
"renderDay": null,
"typicalLength": null,
"repainting": null,
"unchanging": null
}
],
"metadataError": null,
"id": "metadata",
"unreferencedActions": null,
"unreferencedProperties": null
}
],
"metadataError": null,
"cssClass": null,
"size": null,
"id": null,
"span": 12,
"unreferencedActions": null,
"unreferencedCollections": null
}
}
],
"metadataError": null,
"cssClass": null,
"id": null
}
],
"cssClass": null
}
],
"metadataError": null,
"cssClass": null,
"unreferencedCollections": null,
"collapseIfOne": null
}
],
"metadataError": null,
"cssClass": null,
"size": null,
"id": null,
"span": 12,
"unreferencedActions": null,
"unreferencedCollections": null
}
}
],
"metadataError": null,
"cssClass": null,
"id": null
},
{
"cols": [
{
"col": {
"domainObject": null,
"fieldSet": [
{
"name": "Details",
"metadataError": null,
"id": "details",
"unreferencedActions": null,
"unreferencedProperties": null
}
],
"metadataError": null,
"cssClass": null,
"size": null,
"id": null,
"span": 12,
"unreferencedActions": null,
"unreferencedCollections": null
}
}
],
"metadataError": null,
"cssClass": null,
"id": null
}
],
"metadataError": null,
"cssClass": null,
"size": null,
"id": null,
"span": 4,
"unreferencedActions": null,
"unreferencedCollections": null
}
},
{
"col": {
"domainObject": null,
"tabGroup": [
{
"tab": [
{
"name": "All Constants",
"row": [
{
"cols": [
{
"col": {
"domainObject": null,
"collection": [
{
"named": null,
"describedAs": null,
"sortedBy": null,
"metadataError": null,
"link": {
"rel": "urn:org.restfulobjects:rels/collection",
"method": "GET",
"href": "http://localhost:8080/restful/objects/demo.TupleDemo/AKztAAVzcgARamF2YS51dGlsLkhhc2hNYXAFB9rBwxZg0QMAAkYACmxvYWRGYWN0b3JJAAl0aHJlc2hvbGR4cD9AAAAAAAAAdwgAAAAQAAAAAHg=/collections/allConstants",
"type": "application/json;profile=\"urn:org.restfulobjects:repr-types/object-collection\""
},
"id": "allConstants",
"cssClass": null,
"defaultView": "table",
"hidden": null,
"namedEscaped": null,
"paged": null
}
],
"metadataError": null,
"cssClass": null,
"size": "MD",
"id": null,
"span": 12,
"unreferencedActions": null,
"unreferencedCollections": null
}
}
],
"metadataError": null,
"cssClass": null,
"id": null
}
],
"cssClass": null
}
],
"metadataError": null,
"cssClass": null,
"unreferencedCollections": true,
"collapseIfOne": null
}
],
"metadataError": null,
"cssClass": null,
"size": null,
"id": null,
"span": 8,
"unreferencedActions": null,
"unreferencedCollections": null
}
}
],
"metadataError": null,
"cssClass": null,
"id": null
}
],
"cssClass": null
}"""
}
| apache-2.0 | df4f0b8ee3661943e223cf44205343d5 | 51.564155 | 255 | 0.300748 | 6.829585 | false | false | false | false |
EvelynSubarrow/Commandspy3 | src/main/kotlin/moe/evelyn/commandspy/platform/bukkit/EventBukkit.kt | 1 | 2485 | package moe.evelyn.commandspy.platform.bukkit
import moe.evelyn.commandspy.platform.common.CommonCommandEntity
import moe.evelyn.commandspy.platform.common.event.CommonEvent
import org.bukkit.event.block.SignChangeEvent
import org.bukkit.event.player.PlayerCommandPreprocessEvent
import org.bukkit.event.server.ServerCommandEvent
import java.util.*
class EventBukkit : CommonEvent
{
override val event: Int
override val message: String
override val command: String?
override val commandArgs: String?
override val line0: String?
override val line1: String?
override val line2: String?
override val line3: String?
override val sender: CommonCommandEntity
override val x: Int
override val y: Int
override val z: Int
override val worldName: String?
constructor(event :ServerCommandEvent, sender :CommonCommandEntity)
{
this.sender = sender
this.event = 0
message = event.command
command = if (event.command.contains(' ')) event.command.split(' ', limit=2)[0] else event.command
commandArgs = if (event.command.contains(' ')) event.command.split(' ', limit=2)[1] else ""
x = 0 ; y = 0 ; z = 0
line0 = null ; line1 = null
line2 = null ; line3 = null
worldName = null
}
constructor(event :PlayerCommandPreprocessEvent, sender :CommonCommandEntity)
{
this.sender = sender
this.event = 0
message = event.message.substring(1)
command = if (event.message.contains(' ')) event.message.split(' ', limit=2)[0].substring(1) else event.message
commandArgs = if (event.message.contains(' ')) event.message.split(' ', limit=2)[1] else ""
x = event.player.location.blockX
y = event.player.location.blockY
z = event.player.location.blockZ
worldName = event.player.location.world.name
line0 = null ; line1 = null
line2 = null ; line3 = null
}
constructor(event :SignChangeEvent, sender :CommonCommandEntity)
{
this.sender = sender
this.event = 1
message = event.lines.joinToString()
line0 = event.lines[0]
line1 = event.lines[1]
line2 = event.lines[2]
line3 = event.lines[3]
x = event.block.location.blockX
y = event.block.location.blockY
z = event.block.location.blockZ
worldName = event.block.location.world.name
command = null ; commandArgs = null
}
} | gpl-3.0 | ef15b6183d5d7d93907be6f178ac9627 | 33.527778 | 119 | 0.659155 | 4.00161 | false | false | false | false |
google/intellij-community | plugins/kotlin/jvm-debugger/base/util/src/org/jetbrains/kotlin/idea/debugger/base/util/evaluate/ExecutionContext.kt | 2 | 8470 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.idea.debugger.base.util.evaluate
import com.intellij.debugger.engine.DebugProcessImpl
import com.intellij.debugger.engine.SuspendContextImpl
import com.intellij.debugger.engine.evaluation.EvaluateException
import com.intellij.debugger.engine.evaluation.EvaluateExceptionUtil
import com.intellij.debugger.engine.evaluation.EvaluationContextImpl
import com.intellij.debugger.jdi.ClassesByNameProvider
import com.intellij.debugger.jdi.StackFrameProxyImpl
import com.intellij.debugger.jdi.VirtualMachineProxyImpl
import com.intellij.openapi.project.Project
import com.sun.jdi.*
import com.sun.jdi.request.EventRequest
import org.jetbrains.kotlin.idea.debugger.base.util.hopelessAware
import org.jetbrains.org.objectweb.asm.Type
class ExecutionContext(evaluationContext: EvaluationContextImpl, val frameProxy: StackFrameProxyImpl) :
BaseExecutionContext(evaluationContext)
class DefaultExecutionContext(evaluationContext: EvaluationContextImpl) : BaseExecutionContext(evaluationContext) {
constructor(suspendContext: SuspendContextImpl) : this(
EvaluationContextImpl(
suspendContext,
null
)
)
constructor(suspendContext: SuspendContextImpl, frameProxy: StackFrameProxyImpl?) : this(
EvaluationContextImpl(
suspendContext,
frameProxy
)
)
val frameProxy: StackFrameProxyImpl?
get() =
evaluationContext.frameProxy
fun keepReference(ref: ObjectReference?): ObjectReference? {
ref?.let {
super.keepReference(ref)
}
return ref
}
val classesCache: ClassesByNameProvider by lazy {
ClassesByNameProvider.createCache(vm.allClasses())
}
}
sealed class BaseExecutionContext(val evaluationContext: EvaluationContextImpl) {
val vm: VirtualMachineProxyImpl
get() = evaluationContext.debugProcess.virtualMachineProxy
val classLoader: ClassLoaderReference?
get() = evaluationContext.classLoader
val suspendContext: SuspendContextImpl
get() = evaluationContext.suspendContext
val debugProcess: DebugProcessImpl
get() = evaluationContext.debugProcess
val project: Project
get() = evaluationContext.project
val invokePolicy = run {
val suspendContext = evaluationContext.suspendContext
if (suspendContext.suspendPolicy == EventRequest.SUSPEND_EVENT_THREAD) ObjectReference.INVOKE_SINGLE_THREADED else 0
}
@Throws(EvaluateException::class)
fun invokeMethod(obj: ObjectReference, method: Method, args: List<Value?>, invocationOptions: Int = 0): Value? {
return debugProcess.invokeInstanceMethod(evaluationContext, obj, method, args, invocationOptions)
}
fun invokeMethod(type: ClassType, method: Method, args: List<Value?>): Value? {
return debugProcess.invokeMethod(evaluationContext, type, method, args)
}
fun invokeMethod(type: InterfaceType, method: Method, args: List<Value?>): Value? {
return debugProcess.invokeMethod(evaluationContext, type, method, args)
}
@Throws(EvaluateException::class)
fun newInstance(type: ClassType, constructor: Method, args: List<Value?>): ObjectReference {
return debugProcess.newInstance(evaluationContext, type, constructor, args)
}
@Throws(EvaluateException::class)
fun newInstance(arrayType: ArrayType, dimension: Int): ArrayReference {
return debugProcess.newInstance(arrayType, dimension)
}
@Throws(EvaluateException::class)
fun findClass(name: String, classLoader: ClassLoaderReference? = null): ReferenceType? {
debugProcess.findClass(evaluationContext, name, classLoader)?.let { return it }
// If 'isAutoLoadClasses' is true, `findClass()` already did this
if (!evaluationContext.isAutoLoadClasses) {
try {
debugProcess.loadClass(evaluationContext, name, classLoader)
} catch (e: InvocationException) {
throw EvaluateExceptionUtil.createEvaluateException(e)
} catch (e: ClassNotLoadedException) {
throw EvaluateExceptionUtil.createEvaluateException(e)
} catch (e: IncompatibleThreadStateException) {
throw EvaluateExceptionUtil.createEvaluateException(e)
} catch (e: InvalidTypeException) {
throw EvaluateExceptionUtil.createEvaluateException(e)
}
}
return null
}
@Throws(EvaluateException::class)
fun findClass(asmType: Type, classLoader: ClassLoaderReference? = null): ReferenceType? {
if (asmType.sort != Type.OBJECT && asmType.sort != Type.ARRAY) {
return null
}
return findClass(asmType.className, classLoader)
}
fun keepReference(reference: ObjectReference) {
evaluationContext.keep(reference)
}
fun findClassSafe(className: String): ClassType? =
hopelessAware { findClass(className) as? ClassType }
fun invokeMethodSafe(type: ClassType, method: Method, args: List<Value?>): Value? {
return hopelessAware { debugProcess.invokeMethod(evaluationContext, type, method, args) }
}
fun invokeMethodAsInt(instance: ObjectReference, methodName: String): Int? =
(findAndInvoke(instance, instance.referenceType(), methodName, "()I") as? IntegerValue)?.value()
fun invokeMethodAsObject(type: ClassType, methodName: String, vararg params: Value): ObjectReference? =
invokeMethodAsObject(type, methodName, null, *params)
fun invokeMethodAsObject(type: ClassType, methodName: String, methodSignature: String?, vararg params: Value): ObjectReference? =
findAndInvoke(type, methodName, methodSignature, *params) as? ObjectReference
fun invokeMethodAsObject(instance: ObjectReference, methodName: String, vararg params: Value): ObjectReference? =
invokeMethodAsObject(instance, methodName, null, *params)
fun invokeMethodAsObject(
instance: ObjectReference,
methodName: String,
methodSignature: String?,
vararg params: Value
): ObjectReference? =
findAndInvoke(instance, methodName, methodSignature, *params) as? ObjectReference
fun invokeMethodAsObject(instance: ObjectReference, method: Method, vararg params: Value): ObjectReference? =
invokeMethod(instance, method, params.asList()) as? ObjectReference
fun invokeMethodAsVoid(type: ClassType, methodName: String, methodSignature: String? = null, vararg params: Value = emptyArray()) =
findAndInvoke(type, methodName, methodSignature, *params)
fun invokeMethodAsVoid(
instance: ObjectReference,
methodName: String,
methodSignature: String? = null,
vararg params: Value = emptyArray()
) =
findAndInvoke(instance, methodName, methodSignature, *params)
fun invokeMethodAsArray(instance: ClassType, methodName: String, methodSignature: String, vararg params: Value): ArrayReference? =
findAndInvoke(instance, methodName, methodSignature, *params) as? ArrayReference
private fun findAndInvoke(
ref: ObjectReference,
type: ReferenceType,
name: String,
methodSignature: String,
vararg params: Value
): Value? {
val method = type.methodsByName(name, methodSignature).single()
return invokeMethod(ref, method, params.asList())
}
/**
* static method invocation
*/
fun findAndInvoke(type: ClassType, name: String, methodSignature: String? = null, vararg params: Value): Value? {
val method =
if (methodSignature is String)
type.methodsByName(name, methodSignature).single()
else
type.methodsByName(name).single()
return invokeMethod(type, method, params.asList())
}
fun findAndInvoke(instance: ObjectReference, name: String, methodSignature: String? = null, vararg params: Value): Value? {
val type = instance.referenceType()
type.allMethods()
val method =
if (methodSignature is String)
type.methodsByName(name, methodSignature).single()
else
type.methodsByName(name).single()
return invokeMethod(instance, method, params.asList())
}
}
| apache-2.0 | 719dc55894c3a29a286b4f75c9a2debd | 39.333333 | 135 | 0.704368 | 5.196319 | false | false | false | false |
google/intellij-community | platform/lang-impl/src/com/intellij/codeInsight/documentation/actions/ShowQuickDocInfoAction.kt | 5 | 4158 | // 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.codeInsight.documentation.actions
import com.intellij.codeInsight.documentation.DocumentationManager
import com.intellij.codeInsight.documentation.QuickDocUtil.isDocumentationV2Enabled
import com.intellij.codeInsight.hint.HintManagerImpl.ActionToIgnore
import com.intellij.codeInsight.lookup.LookupManager
import com.intellij.featureStatistics.FeatureUsageTracker
import com.intellij.lang.documentation.ide.actions.DOCUMENTATION_TARGETS
import com.intellij.lang.documentation.ide.impl.DocumentationManager.Companion.instance
import com.intellij.openapi.actionSystem.*
import com.intellij.openapi.editor.EditorGutter
import com.intellij.openapi.project.DumbAware
import com.intellij.psi.PsiDocumentManager
import com.intellij.psi.util.PsiUtilBase
open class ShowQuickDocInfoAction : AnAction(),
ActionToIgnore,
DumbAware,
PopupAction,
PerformWithDocumentsCommitted {
init {
isEnabledInModalContext = true
@Suppress("LeakingThis")
setInjectedContext(true)
}
override fun getActionUpdateThread() = ActionUpdateThread.BGT
override fun update(e: AnActionEvent) {
if (isDocumentationV2Enabled()) {
e.presentation.isEnabled = e.dataContext.getData(DOCUMENTATION_TARGETS)?.isNotEmpty() ?: false
return
}
val presentation = e.presentation
val dataContext = e.dataContext
presentation.isEnabled = false
val project = CommonDataKeys.PROJECT.getData(dataContext) ?: return
val editor = CommonDataKeys.EDITOR.getData(dataContext)
val element = CommonDataKeys.PSI_ELEMENT.getData(dataContext)
if (editor == null && element == null) return
if (LookupManager.getInstance(project).activeLookup != null) {
presentation.isEnabled = true
}
else {
if (editor != null) {
if (e.getData(EditorGutter.KEY) != null) return
val file = PsiDocumentManager.getInstance(project).getPsiFile(editor.document)
if (file == null && element == null) return
}
presentation.isEnabled = true
}
}
override fun actionPerformed(e: AnActionEvent) {
if (isDocumentationV2Enabled()) {
actionPerformedV2(e.dataContext)
return
}
val dataContext = e.dataContext
val project = CommonDataKeys.PROJECT.getData(dataContext) ?: return
val editor = CommonDataKeys.EDITOR.getData(dataContext)
if (editor != null) {
FeatureUsageTracker.getInstance().triggerFeatureUsed(CODEASSISTS_QUICKJAVADOC_FEATURE)
val activeLookup = LookupManager.getActiveLookup(editor)
if (activeLookup != null) {
FeatureUsageTracker.getInstance().triggerFeatureUsed(CODEASSISTS_QUICKJAVADOC_LOOKUP_FEATURE)
}
val psiFile = PsiUtilBase.getPsiFileInEditor(editor, project) ?: return
val documentationManager = DocumentationManager.getInstance(project)
val hint = documentationManager.docInfoHint
documentationManager.showJavaDocInfo(editor, psiFile, hint != null || activeLookup == null)
return
}
val element = CommonDataKeys.PSI_ELEMENT.getData(dataContext)
if (element != null) {
FeatureUsageTracker.getInstance().triggerFeatureUsed(CODEASSISTS_QUICKJAVADOC_CTRLN_FEATURE)
val documentationManager = DocumentationManager.getInstance(project)
val hint = documentationManager.docInfoHint
documentationManager.showJavaDocInfo(element, null, hint != null, null)
}
}
private fun actionPerformedV2(dataContext: DataContext) {
val project = dataContext.getData(CommonDataKeys.PROJECT) ?: return
instance(project).actionPerformed(dataContext)
}
@Suppress("SpellCheckingInspection")
companion object {
const val CODEASSISTS_QUICKJAVADOC_FEATURE = "codeassists.quickjavadoc"
const val CODEASSISTS_QUICKJAVADOC_LOOKUP_FEATURE = "codeassists.quickjavadoc.lookup"
const val CODEASSISTS_QUICKJAVADOC_CTRLN_FEATURE = "codeassists.quickjavadoc.ctrln"
}
}
| apache-2.0 | 83eeebd0db97d0673c48a7c20a2e0ed9 | 41.865979 | 120 | 0.734247 | 4.746575 | false | false | false | false |
jiro-aqua/vertical-text-viewer | vtextview/src/main/java/jp/gr/aqua/vjap/VTextView.kt | 1 | 2630 | package jp.gr.aqua.vjap
import android.content.Context
import android.graphics.Canvas
import android.util.AttributeSet
import android.view.View
import android.widget.Toast
class VTextView : View {
private var currentIndex = 0
private var layout: VerticalLayout? = null
constructor(context: Context) : this(context, null)
constructor(context: Context, attrs: AttributeSet?) : super(context, attrs)
constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int) : super(context, attrs, defStyleAttr)
public override fun onDraw(canvas: Canvas) {
super.onDraw(canvas)
try {
// ここで落ちると親を巻き込むので対策しておく
layout?.textDraw(canvas, currentIndex)
}catch(ex:Exception){
Toast.makeText(context,"Error", Toast.LENGTH_LONG).show()
ex.printStackTrace()
}
}
fun setLayout(layout: VerticalLayout, page: Int) {
this.layout = layout
this.currentIndex = page
}
// private val touchSlop by lazy { ViewConfiguration.get(context).scaledTouchSlop }
// private val doubleTapTimeout by lazy { getDoubleTapTimeout() }
// var lastTapTime = 0L
// var lastTouchX = 0F
// var lastTouchY = 0F
//
// override fun onTouchEvent(event: MotionEvent?): Boolean {
// if ( event!= null ){
// val action = event.action
// if ( action == MotionEvent.ACTION_DOWN ){
// val now = System.currentTimeMillis()
// val xdiff = Math.abs(event.x - lastTouchX)
// val ydiff = Math.abs(event.y - lastTouchY)
// if ( xdiff < touchSlop && ydiff < touchSlop && ( now - lastTapTime ) < doubleTapTimeout ){
// val theChar = layout?.getTouchedChar(currentIndex , event.x, event.y) ?: -1
// if ( theChar != -1 ) {
// layout?.onDoubleClick(theChar)
// }
// }
// lastTapTime = now
// lastTouchX = event.x
// lastTouchY = event.y
// }
// }
// return super.onTouchEvent(event)
// }
fun onDoubleTapped(x: Float , y :Float){
val theChar = layout?.getTouchedChar(currentIndex , x, y) ?: -1
if ( theChar != -1 ) {
layout?.onDoubleClick(theChar)
}
}
fun getTappedPosition(x: Float , y :Float) : Int
{
return layout?.getTouchedChar(currentIndex , x, y) ?: - 1
}
override fun onDetachedFromWindow() {
super.onDetachedFromWindow()
layout = null
}
}
| apache-2.0 | d74c30512c123ac22fe22ae1832beb32 | 31.759494 | 111 | 0.58153 | 4.050078 | false | false | false | false |
fluidsonic/fluid-json | annotation-processor/test-cases/1/output-expected/json/decoding/AutomaticSecondaryConstructorPrimaryInaccessibleJsonCodec.kt | 1 | 2250 | package json.decoding
import codecProvider.CustomCodingContext
import io.fluidsonic.json.AbstractJsonCodec
import io.fluidsonic.json.JsonCodingType
import io.fluidsonic.json.JsonDecoder
import io.fluidsonic.json.JsonEncoder
import io.fluidsonic.json.missingPropertyError
import io.fluidsonic.json.readBooleanOrNull
import io.fluidsonic.json.readByteOrNull
import io.fluidsonic.json.readCharOrNull
import io.fluidsonic.json.readDoubleOrNull
import io.fluidsonic.json.readFloatOrNull
import io.fluidsonic.json.readFromMapByElementValue
import io.fluidsonic.json.readIntOrNull
import io.fluidsonic.json.readLongOrNull
import io.fluidsonic.json.readShortOrNull
import io.fluidsonic.json.readStringOrNull
import io.fluidsonic.json.readValueOfType
import io.fluidsonic.json.readValueOfTypeOrNull
import io.fluidsonic.json.writeBooleanOrNull
import io.fluidsonic.json.writeByteOrNull
import io.fluidsonic.json.writeCharOrNull
import io.fluidsonic.json.writeDoubleOrNull
import io.fluidsonic.json.writeFloatOrNull
import io.fluidsonic.json.writeIntOrNull
import io.fluidsonic.json.writeIntoMap
import io.fluidsonic.json.writeLongOrNull
import io.fluidsonic.json.writeMapElement
import io.fluidsonic.json.writeShortOrNull
import io.fluidsonic.json.writeStringOrNull
import io.fluidsonic.json.writeValueOrNull
import kotlin.Unit
internal object AutomaticSecondaryConstructorPrimaryInaccessibleJsonCodec :
AbstractJsonCodec<AutomaticSecondaryConstructorPrimaryInaccessible, CustomCodingContext>() {
public override
fun JsonDecoder<CustomCodingContext>.decode(valueType: JsonCodingType<AutomaticSecondaryConstructorPrimaryInaccessible>):
AutomaticSecondaryConstructorPrimaryInaccessible {
var _value = 0
var value_isPresent = false
readFromMapByElementValue { key ->
when (key) {
"value" -> {
_value = readInt()
value_isPresent = true
}
else -> skipValue()
}
}
value_isPresent || missingPropertyError("value")
return AutomaticSecondaryConstructorPrimaryInaccessible(
`value` = _value
)
}
public override
fun JsonEncoder<CustomCodingContext>.encode(`value`: AutomaticSecondaryConstructorPrimaryInaccessible):
Unit {
writeIntoMap {
writeMapElement("value", string = value.`value`)
}
}
}
| apache-2.0 | 7f7fb4f582194e875efca2e7f2a01765 | 32.58209 | 124 | 0.829778 | 4.756871 | false | false | false | false |
allotria/intellij-community | plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/codeInspection/style/string/GrStringStyleViolationInspection.kt | 3 | 11141 | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.plugins.groovy.codeInspection.style.string
import com.intellij.codeInspection.ProblemHighlightType
import com.intellij.openapi.ui.ComboBox
import com.intellij.ui.SimpleListCellRenderer
import com.intellij.ui.layout.*
import com.intellij.util.ui.CheckBox
import org.jetbrains.annotations.Nls
import org.jetbrains.plugins.groovy.GroovyBundle
import org.jetbrains.plugins.groovy.codeInspection.BaseInspection
import org.jetbrains.plugins.groovy.codeInspection.BaseInspectionVisitor
import org.jetbrains.plugins.groovy.codeInspection.style.string.GrStringStyleViolationInspection.InspectionStringQuotationKind.*
import org.jetbrains.plugins.groovy.codeInspection.style.string.GrStringStyleViolationInspection.StringUsageKind.*
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.literals.GrLiteral
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.literals.GrString
import org.jetbrains.plugins.groovy.lang.psi.util.GrStringUtil
import java.awt.GridBagConstraints
import java.awt.GridBagLayout
import javax.swing.*
import kotlin.reflect.KMutableProperty
import org.jetbrains.plugins.groovy.lang.psi.util.StringKind as OuterStringKind
class GrStringStyleViolationInspection : BaseInspection() {
internal enum class InspectionStringQuotationKind {
UNDEFINED,
DOUBLE_QUOTED,
SINGLE_QUOTED,
SLASHY,
TRIPLE_QUOTED,
TRIPLE_DOUBLE_QUOTED,
DOLLAR_SLASHY_QUOTED;
@Nls
fun representation(): String = when (this) {
UNDEFINED -> GroovyBundle.message("string.option.do.not.handle.specifically")
DOUBLE_QUOTED -> GroovyBundle.message("string.option.double.quoted.string")
SINGLE_QUOTED -> GroovyBundle.message("string.option.single.quoted.string")
SLASHY -> GroovyBundle.message("string.option.slashy.string")
TRIPLE_QUOTED -> GroovyBundle.message("string.option.triple.quoted.string")
TRIPLE_DOUBLE_QUOTED -> GroovyBundle.message("string.option.triple.double.quoted.string")
DOLLAR_SLASHY_QUOTED -> GroovyBundle.message("string.option.dollar.slashy.string")
}
}
companion object {
private val PLAIN_STRING_OPTIONS = arrayOf(DOUBLE_QUOTED, SINGLE_QUOTED, SLASHY, TRIPLE_QUOTED, TRIPLE_DOUBLE_QUOTED, DOLLAR_SLASHY_QUOTED)
private val MULTILINE_STRING_OPTIONS = arrayOf(TRIPLE_QUOTED, SLASHY, TRIPLE_DOUBLE_QUOTED, DOLLAR_SLASHY_QUOTED)
private val ESCAPED_STRING_OPTIONS = arrayOf(DOUBLE_QUOTED, SINGLE_QUOTED, SLASHY, TRIPLE_QUOTED, TRIPLE_DOUBLE_QUOTED, DOLLAR_SLASHY_QUOTED)
private val INTERPOLATED_STRING_OPTIONS = arrayOf(DOUBLE_QUOTED, SLASHY, TRIPLE_DOUBLE_QUOTED, DOLLAR_SLASHY_QUOTED)
private fun JPanel.addStringKindComboBox(@Nls description: String,
field: KMutableProperty<InspectionStringQuotationKind>,
values: Array<InspectionStringQuotationKind>,
id: Int,
constraints: GridBagConstraints) {
constraints.gridy = id
constraints.gridx = 0
add(JLabel(description), constraints)
val comboBox: JComboBox<InspectionStringQuotationKind> = ComboBox(values).apply {
renderer = SimpleListCellRenderer.create("") { it.representation() }
selectedItem = field.getter.call()
addItemListener { e ->
val selectedItem = e.item
if (field.getter.call() != selectedItem) {
field.setter.call(selectedItem)
}
}
}
constraints.gridx = 1
add(comboBox, constraints)
}
private fun getActualKind(kind: InspectionStringQuotationKind): OuterStringKind? = when (kind) {
UNDEFINED -> null
DOUBLE_QUOTED -> OuterStringKind.DOUBLE_QUOTED
SINGLE_QUOTED -> OuterStringKind.SINGLE_QUOTED
SLASHY -> OuterStringKind.SLASHY
TRIPLE_QUOTED -> OuterStringKind.TRIPLE_SINGLE_QUOTED
TRIPLE_DOUBLE_QUOTED -> OuterStringKind.TRIPLE_DOUBLE_QUOTED
DOLLAR_SLASHY_QUOTED -> OuterStringKind.DOLLAR_SLASHY
}
}
@Volatile
internal var plainStringQuotation = SINGLE_QUOTED
@Volatile
internal var escapedStringQuotation = UNDEFINED
@Volatile
internal var interpolatedStringQuotation = UNDEFINED
@Volatile
internal var multilineStringQuotation = TRIPLE_QUOTED
@Volatile
internal var inspectGradle: Boolean = true
private fun generateComboBoxes(): JPanel = JPanel(GridBagLayout()).apply {
val constraints = GridBagConstraints().apply {
weightx = 1.0; weighty = 1.0; fill = GridBagConstraints.HORIZONTAL; anchor = GridBagConstraints.WEST
}
addStringKindComboBox(GroovyBundle.message("string.sort.default"), ::plainStringQuotation, PLAIN_STRING_OPTIONS, 0, constraints)
addStringKindComboBox(GroovyBundle.message("string.sort.strings.with.escaping"), ::escapedStringQuotation,
arrayOf(UNDEFINED, *ESCAPED_STRING_OPTIONS), 1, constraints)
addStringKindComboBox(GroovyBundle.message("string.sort.strings.with.interpolation"), ::interpolatedStringQuotation,
arrayOf(UNDEFINED, *INTERPOLATED_STRING_OPTIONS), 2, constraints)
addStringKindComboBox(GroovyBundle.message("string.sort.multiline.string"), ::multilineStringQuotation,
arrayOf(UNDEFINED, *MULTILINE_STRING_OPTIONS), 3, constraints)
}
override fun createOptionsPanel(): JComponent {
return panel {
titledRow(GroovyBundle.message("separator.preferable.string.kind")) {
row { generateComboBoxes()() }
}
titledRow(GroovyBundle.message("separator.domain.of.inspection.usage")) {
row { CheckBox(GroovyBundle.message("checkbox.inspect.gradle.files"), this@GrStringStyleViolationInspection, "inspectGradle")() }
}
}
}
private enum class StringUsageKind {
PLAIN_STRING, MULTILINE_STRING, ESCAPED_STRING, INTERPOLATED_STRING
}
override fun buildErrorString(vararg args: Any?): String {
val targetQuotationKind = args[1] as InspectionStringQuotationKind
return when (args[0] as StringUsageKind) {
PLAIN_STRING -> when (targetQuotationKind) {
DOUBLE_QUOTED -> GroovyBundle.message("inspection.message.plain.string.should.be.double.quoted")
SINGLE_QUOTED -> GroovyBundle.message("inspection.message.plain.string.should.be.single.quoted")
SLASHY -> GroovyBundle.message("inspection.message.plain.string.should.be.slashy.quoted")
DOLLAR_SLASHY_QUOTED -> GroovyBundle.message("inspection.message.plain.string.should.be.dollar.slashy.quoted")
TRIPLE_QUOTED -> GroovyBundle.message("inspection.message.plain.string.should.be.quoted.with.triple.quotes")
TRIPLE_DOUBLE_QUOTED -> GroovyBundle.message("inspection.message.plain.string.should.be.quoted.with.triple.double.quotes")
else -> error("Unexpected error message")
}
MULTILINE_STRING -> when (targetQuotationKind) {
TRIPLE_QUOTED -> GroovyBundle.message("inspection.message.multiline.string.should.be.quoted.with.triple.quotes")
TRIPLE_DOUBLE_QUOTED -> GroovyBundle.message("inspection.message.multiline.string.should.be.quoted.with.triple.double.quotes")
SLASHY -> GroovyBundle.message("inspection.message.multiline.string.should.be.slashy.quoted")
DOLLAR_SLASHY_QUOTED -> GroovyBundle.message("inspection.message.multiline.string.should.be.dollar.slashy.quoted")
else -> error("Unexpected error message")
}
ESCAPED_STRING -> GroovyBundle.message("inspection.message.string.escaping.could.be.minimized")
INTERPOLATED_STRING -> when (targetQuotationKind) {
DOUBLE_QUOTED -> GroovyBundle.message("inspection.message.interpolated.string.should.be.double.quoted")
DOLLAR_SLASHY_QUOTED -> GroovyBundle.message("inspection.message.interpolated.string.should.be.dollar.slashy.quoted")
SLASHY -> GroovyBundle.message("inspection.message.interpolated.string.should.be.slashy.quoted")
TRIPLE_DOUBLE_QUOTED -> GroovyBundle.message("inspection.message.interpolated.string.should.be.quoted.with.triple.double.quotes")
else -> error("Unexpected error message")
}
}
}
override fun buildVisitor(): BaseInspectionVisitor = object : BaseInspectionVisitor() {
override fun visitLiteralExpression(literal: GrLiteral) {
if (!inspectGradle && literal.containingFile.name.endsWith("gradle")) {
return
}
if (literal is GrString) {
handleGString(literal)
}
else if (GrStringUtil.getStartQuote(literal.text) != "") {
handlePlainString(literal)
}
super.visitLiteralExpression(literal)
}
private fun handleGString(literal: GrLiteral) {
checkInconsistency(interpolatedStringQuotation, literal, INTERPOLATED_STRING, INTERPOLATED_STRING_OPTIONS)
}
private fun handlePlainString(literal: GrLiteral) {
val literalText = literal.text
if (multilineStringQuotation != UNDEFINED && GrStringUtil.isMultilineStringLiteral(literal) && literalText.contains("\n")) {
checkInconsistency(multilineStringQuotation, literal, MULTILINE_STRING, MULTILINE_STRING_OPTIONS)
return
}
else if (escapedStringQuotation != UNDEFINED) {
val bestEscaping = findBestQuotationForEscaping(literalText, escapedStringQuotation, plainStringQuotation)
if (bestEscaping != null) {
if (bestEscaping.second != 0) {
checkInconsistency(bestEscaping.first, literal, ESCAPED_STRING, ESCAPED_STRING_OPTIONS)
}
return
}
}
if ("\n" !in literalText) {
checkInconsistency(plainStringQuotation, literal, PLAIN_STRING, PLAIN_STRING_OPTIONS)
}
}
private fun checkInconsistency(expected: InspectionStringQuotationKind,
literal: GrLiteral,
usageKind: StringUsageKind,
availableStringKinds: Array<InspectionStringQuotationKind>) {
if (expected !in availableStringKinds) {
return
}
fun doCheck(predicate: (GrLiteral) -> Boolean) {
if (!predicate(literal)) {
val description = buildErrorString(usageKind, expected)
val fixes = getActualKind(expected)?.let { arrayOf(getStringTransformationFix(it)) } ?: emptyArray()
registerError(literal, description, fixes, ProblemHighlightType.GENERIC_ERROR_OR_WARNING)
}
}
when (expected) {
DOUBLE_QUOTED -> doCheck(GrStringUtil::isDoubleQuoteString)
SINGLE_QUOTED -> doCheck(GrStringUtil::isSingleQuoteString)
SLASHY -> doCheck(GrStringUtil::isSlashyString)
TRIPLE_QUOTED -> doCheck(GrStringUtil::isTripleQuoteString)
TRIPLE_DOUBLE_QUOTED -> doCheck(GrStringUtil::isTripleDoubleQuoteString)
DOLLAR_SLASHY_QUOTED -> doCheck(GrStringUtil::isDollarSlashyString)
else -> Unit
}
}
}
}
| apache-2.0 | 661b2d93314eb32a9c87645f517ca031 | 48.515556 | 145 | 0.714299 | 4.463542 | false | false | false | false |
android/wear-os-samples | WearTilesKotlin/app/src/main/java/com/example/wear/tiles/messaging/MessagingRepo.kt | 1 | 3214 | /*
* 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
*
* 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.wear.tiles.messaging
import android.content.Context
import androidx.datastore.core.DataStore
import androidx.datastore.preferences.core.Preferences
import androidx.datastore.preferences.core.edit
import androidx.datastore.preferences.core.intPreferencesKey
import androidx.datastore.preferences.core.stringPreferencesKey
import androidx.datastore.preferences.preferencesDataStore
import com.example.wear.tiles.messaging.Contact.Companion.toContact
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.map
private val Context.dataStore: DataStore<Preferences> by preferencesDataStore(name = "contacts")
class MessagingRepo(private val context: Context) {
fun getFavoriteContacts(): Flow<List<Contact>> = context.dataStore.data.map { preferences ->
val count = preferences[intPreferencesKey("contact.count")] ?: 0
(0 until count).mapNotNull {
preferences[stringPreferencesKey("contact.$it")]?.toContact()
}
}
suspend fun updateContacts(contacts: List<Contact>) {
context.dataStore.edit {
it.clear()
contacts.forEachIndexed { index, contact ->
it[stringPreferencesKey("contact.$index")] = contact.toPreferenceString()
}
it[intPreferencesKey("contact.count")] = contacts.size
}
}
companion object {
private const val avatarPath =
"https://github.com/android/wear-os-samples/raw/main/WearTilesKotlin/" +
"app/src/main/res/drawable-nodpi"
val knownContacts = listOf(
Contact(
id = 0,
initials = "JV",
name = "Jyoti V",
avatarUrl = null
),
Contact(
id = 1,
initials = "AC",
name = "Ali C",
avatarUrl = "$avatarPath/ali.png"
),
Contact(
id = 2,
initials = "TB",
name = "Taylor B",
avatarUrl = "$avatarPath/taylor.jpg"
),
Contact(
id = 3,
initials = "FS",
name = "Felipe S",
avatarUrl = null
),
Contact(
id = 4,
initials = "JG",
name = "Judith G",
avatarUrl = null
),
Contact(
id = 5,
initials = "AO",
name = "Andrew O",
avatarUrl = null
)
)
}
}
| apache-2.0 | f200cf5899cb6c06c33fc98819dac5da | 33.191489 | 96 | 0.585563 | 4.69883 | false | false | false | false |
leafclick/intellij-community | java/java-tests/testSrc/com/intellij/java/codeInspection/JavaReflectionInvocationTest.kt | 1 | 1814 | /*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.java.codeInspection
import com.intellij.JavaTestUtil
import com.intellij.codeInspection.reflectiveAccess.JavaReflectionInvocationInspection
import com.intellij.openapi.roots.LanguageLevelProjectExtension
import com.intellij.pom.java.LanguageLevel
import com.intellij.testFramework.LightProjectDescriptor
import com.intellij.testFramework.fixtures.LightJavaCodeInsightFixtureTestCase
/**
* @author Pavel.Dolgov
*/
class JavaReflectionInvocationTest : LightJavaCodeInsightFixtureTestCase() {
override fun setUp() {
super.setUp()
LanguageLevelProjectExtension.getInstance(project).languageLevel = LanguageLevel.JDK_1_5
myFixture.enableInspections(JavaReflectionInvocationInspection())
}
override fun getProjectDescriptor(): LightProjectDescriptor = LightJavaCodeInsightFixtureTestCase.JAVA_8
override fun getBasePath() = JavaTestUtil.getRelativeJavaTestDataPath() + "/inspection/javaReflectionInvocation"
fun testMethodParamCount() = doTest()
fun testMethodParamTypes() = doTest()
fun testConstructorParamCount() = doTest()
fun testConstructorParamTypes() = doTest()
private fun doTest() {
myFixture.testHighlighting("${getTestName(false)}.java")
}
} | apache-2.0 | 9539edc40e847eacfc72a0e1c79a51e6 | 36.8125 | 114 | 0.791069 | 4.902703 | false | true | false | false |
leafclick/intellij-community | platform/platform-impl/src/com/intellij/internal/statistic/fileTypes/UpdateComponentEditorListener.kt | 1 | 4573 | // 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.intellij.internal.statistic.fileTypes
import com.intellij.ide.plugins.PluginManagerCore
import com.intellij.ide.util.PropertiesComponent
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.PermanentInstallationID
import com.intellij.openapi.application.ex.ApplicationInfoEx
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.editor.event.EditorFactoryEvent
import com.intellij.openapi.editor.event.EditorFactoryListener
import com.intellij.openapi.editor.ex.EditorEx
import com.intellij.openapi.editor.ex.FocusChangeListener
import com.intellij.openapi.extensions.PluginId
import com.intellij.openapi.fileEditor.FileDocumentManager
import com.intellij.openapi.util.JDOMUtil
import com.intellij.openapi.util.SystemInfo
import com.intellij.util.ObjectUtils
import com.intellij.util.io.HttpRequests
import org.jdom.JDOMException
import java.io.IOException
import java.net.URLEncoder
import java.net.UnknownHostException
import java.util.concurrent.TimeUnit
private class UpdateComponentEditorListener : EditorFactoryListener {
override fun editorCreated(event: EditorFactoryEvent) {
if (ApplicationManager.getApplication().isUnitTestMode) return
val document = event.editor.document
val file = FileDocumentManager.getInstance().getFile(document) ?: return
val fileType = file.fileType
FileTypeStatisticProvider.EP_NAME.extensionList.find { ep -> ep.accept(event, fileType) }?.let { ep ->
updateOnPooledThread(ep)
(event.editor as? EditorEx)?.addFocusListener(FocusChangeListener {
updateOnPooledThread(ep)
})
}
}
companion object {
private val lock = ObjectUtils.sentinel("updating_monitor")
private val LOG = Logger.getInstance(UpdateComponentEditorListener::class.java)
private fun updateOnPooledThread(ep: FileTypeStatisticProvider) =
ApplicationManager.getApplication().executeOnPooledThread {
update(ep)
}
private fun update(ep: FileTypeStatisticProvider) {
val pluginIdString = ep.pluginId
val plugin = PluginManagerCore.getPlugin(PluginId.getId(pluginIdString))
if (plugin == null) {
LOG.error("Unknown plugin id: $pluginIdString is reported by ${ep::class.java}")
return
}
val pluginVersion = plugin.version
if (!checkUpdateRequired(pluginIdString, pluginVersion)) return
val url = getUpdateUrl(pluginIdString, pluginVersion)
sendRequest(url)
}
private fun checkUpdateRequired(pluginIdString: String, pluginVersion: String): Boolean {
synchronized(lock) {
val lastVersionKey = "$pluginIdString.LAST_VERSION"
val lastUpdateKey = "$pluginIdString.LAST_UPDATE"
val properties = PropertiesComponent.getInstance()
val lastPluginVersion = properties.getValue(lastVersionKey)
val lastUpdate = properties.getLong(lastUpdateKey, 0L)
val shouldUpdate = lastUpdate == 0L
|| System.currentTimeMillis() - lastUpdate > TimeUnit.DAYS.toMillis(1)
|| lastPluginVersion == null
|| lastPluginVersion != pluginVersion
if (!shouldUpdate) return false
properties.setValue(lastUpdateKey, System.currentTimeMillis().toString())
properties.setValue(lastVersionKey, pluginVersion)
return true
}
}
private fun sendRequest(url: String) {
try {
HttpRequests.request(url).connect {
try {
JDOMUtil.load(it.reader)
}
catch (e: JDOMException) {
LOG.warn(e)
}
LOG.info("updated: $url")
}
}
catch (ignored: UnknownHostException) {
// No internet connections, no need to log anything
}
catch (e: IOException) {
LOG.warn(e)
}
}
private fun getUpdateUrl(pluginIdString: String, pluginVersion: String): String {
val applicationInfo = ApplicationInfoEx.getInstanceEx()
val buildNumber = applicationInfo.build.asString()
val os = URLEncoder.encode("${SystemInfo.OS_NAME} ${SystemInfo.OS_VERSION}", Charsets.UTF_8.name())
val uid = PermanentInstallationID.get()
val baseUrl = "https://plugins.jetbrains.com/plugins/list"
return "$baseUrl?pluginId=$pluginIdString&build=$buildNumber&pluginVersion=$pluginVersion&os=$os&uuid=$uid"
}
}
} | apache-2.0 | 191267a4a0adc146ff5bf520e37133bf | 38.094017 | 140 | 0.71616 | 4.839153 | false | false | false | false |
intellij-purescript/intellij-purescript | src/main/kotlin/org/purescript/psi/typeconstructor/TypeConstructorReference.kt | 1 | 3206 | package org.purescript.psi.typeconstructor
import com.intellij.codeInspection.LocalQuickFix
import com.intellij.codeInspection.LocalQuickFixProvider
import com.intellij.psi.PsiNamedElement
import com.intellij.psi.PsiReferenceBase
import org.purescript.file.ExportedTypesIndex
import org.purescript.psi.PSPsiFactory
import org.purescript.psi.expression.ImportQuickFix
class TypeConstructorReference(typeConstructor: PSTypeConstructor) :
LocalQuickFixProvider,
PsiReferenceBase<PSTypeConstructor>(
typeConstructor,
typeConstructor.textRangeInParent,
false
) {
override fun getVariants(): Array<PsiNamedElement> =
candidates.toTypedArray()
override fun resolve(): PsiNamedElement? =
candidates.firstOrNull { it.name == myElement.name }
/**
* Type constructors can reference any data, new type, or synonym declaration
* in the current module or any of the imported modules.
*/
private val candidates: List<PsiNamedElement>
get() {
val name = element.moduleName?.name
return if (name != null) {
candidatesFor(name)
} else {
allCandidates
}
}
private fun candidatesFor(name: String): List<PsiNamedElement> {
val module = element.module ?: return emptyList()
val importDeclaration = module
.importDeclarations
.firstOrNull { it.importAlias?.name == name }
?: return emptyList()
val candidates = mutableListOf<PsiNamedElement>()
candidates.addAll(importDeclaration.importedDataDeclarations)
candidates.addAll(importDeclaration.importedNewTypeDeclarations)
candidates.addAll(importDeclaration.importedTypeSynonymDeclarations)
candidates.addAll(importDeclaration.importedForeignDataDeclarations)
return candidates
}
private val allCandidates: List<PsiNamedElement> get() {
val module = element.module ?: return emptyList()
val candidates = mutableListOf<PsiNamedElement>()
candidates.addAll(module.dataDeclarations)
candidates.addAll(module.newTypeDeclarations)
candidates.addAll(module.typeSynonymDeclarations)
candidates.addAll(module.foreignDataDeclarations)
for (importDeclaration in module.importDeclarations) {
candidates.addAll(importDeclaration.importedDataDeclarations)
candidates.addAll(importDeclaration.importedNewTypeDeclarations)
candidates.addAll(importDeclaration.importedTypeSynonymDeclarations)
candidates.addAll(importDeclaration.importedForeignDataDeclarations)
}
return candidates
}
override fun getQuickFixes(): Array<LocalQuickFix> {
val factory = PSPsiFactory(element.project)
val importedData = factory.createImportedData(element.name)
return importCandidates
.map { ImportQuickFix(it, importedData) }
.toTypedArray()
}
private val importCandidates: List<String>
get() = ExportedTypesIndex
.filesExportingType(element.project, element.name)
.mapNotNull { it.module?.name }
}
| bsd-3-clause | 51050a51699ff385b57594e77823bc38 | 38.580247 | 81 | 0.702433 | 5.388235 | false | false | false | false |
illuzor/Mighty-Preferences | mightypreferences/src/androidTest/kotlin/com/illuzor/mightypreferences/ListenersTest.kt | 1 | 2182 | package com.illuzor.mightypreferences
import android.content.Context
import android.content.SharedPreferences
import androidx.test.core.app.ApplicationProvider
import org.junit.Assert.*
import org.junit.Test
class ListenersTest {
private val prefs = ApplicationProvider.getApplicationContext<Context>().defaultPrefs
@Test
fun add_listener() {
prefs.clear()
var changed = false
prefs.addListener { _, key ->
assertEquals("i", key)
changed = true
}
prefs.putInt("i", 1)
Thread.sleep(100)
assertTrue(changed)
prefs.clearListeners()
}
@Test
fun add_and_remove_listener() {
prefs.clear()
var changed = false
val listener = { _: SharedPreferences, _: String ->
changed = true
}
prefs.addListener(listener)
prefs.removeListener(listener)
prefs.putInt("i", 1)
Thread.sleep(100)
assertFalse(changed)
}
@Test
fun add_multiple_listeners() {
prefs.clear()
var changed1 = false
var changed2 = false
var changed3 = false
prefs.addListener { _, key ->
assertEquals("i", key)
changed1 = true
}
prefs.addListener { _, key ->
assertEquals("i", key)
changed2 = true
}
prefs.addListener { _, key ->
assertEquals("i", key)
changed3 = true
}
prefs.putInt("i", 1)
Thread.sleep(100)
assertTrue(changed1)
assertTrue(changed2)
assertTrue(changed3)
prefs.clearListeners()
}
@Test
fun remove_multiple_listeners() {
prefs.clear()
var changed1 = false
var changed2 = false
var changed3 = false
prefs.addListener { _, _ -> changed1 = true }
prefs.addListener { _, _ -> changed2 = true }
prefs.addListener { _, _ -> changed3 = true }
prefs.clearListeners()
prefs.putInt("i", 1)
Thread.sleep(100)
assertFalse(changed1)
assertFalse(changed2)
assertFalse(changed3)
}
}
| mit | 8bddfd7b4d9213f91fca1f5217d88d66 | 21.729167 | 89 | 0.558203 | 4.545833 | false | true | false | false |
room-15/ChatSE | app/src/main/java/com/tristanwiley/chatse/chat/DividerItemDecoration.kt | 1 | 2586 | package com.tristanwiley.chatse.chat
import android.annotation.SuppressLint
import android.content.Context
import android.graphics.Canvas
import android.graphics.Rect
import android.graphics.drawable.Drawable
import android.support.v7.widget.RecyclerView
import android.view.View
@SuppressLint("DuplicateDivider")
class DividerItemDecoration @JvmOverloads constructor(
context: Context,
private val orientation: ListOrientation = ListOrientation.VERTICAL
) : RecyclerView.ItemDecoration() {
/**
* The actual divider that is displayed.
*/
private val divider: Drawable
init {
val attrs = context.obtainStyledAttributes(ATTRS)
divider = attrs.getDrawable(DIVIDER_POSITION)!!
attrs.recycle()
}
/**
* Draws the divider depending on the orientation of the RecyclerView.
*/
override fun onDraw(c: Canvas, parent: RecyclerView, state: RecyclerView.State) {
val childCount = parent.childCount
for (i in 0 until childCount) {
val child = parent.getChildAt(i)
val params = child.layoutParams as RecyclerView.LayoutParams
when (orientation) {
ListOrientation.VERTICAL -> {
val top = child.bottom + params.bottomMargin
val bottom = top + divider.intrinsicHeight
divider.setBounds(parent.paddingLeft, top,
parent.width - parent.paddingRight, bottom)
}
ListOrientation.HORIZONTAL -> {
val left = child.right + params.rightMargin
val right = left + divider.intrinsicHeight
divider.setBounds(left, parent.paddingTop, right,
parent.height - parent.paddingBottom)
}
}
divider.draw(c)
}
}
/**
* Determines the offset of the divider based on the orientation of the list.
*/
override fun getItemOffsets(outRect: Rect, view: View, parent: RecyclerView, state: RecyclerView.State) =
when (orientation) {
ListOrientation.VERTICAL -> outRect.set(0, 0, 0, divider.intrinsicHeight)
ListOrientation.HORIZONTAL -> outRect.set(0, 0, divider.intrinsicWidth, 0)
}
companion object {
// Attributes for the divider
private val ATTRS = intArrayOf(android.R.attr.listDivider)
private const val DIVIDER_POSITION = 0
}
enum class ListOrientation {
HORIZONTAL,
VERTICAL
}
} | apache-2.0 | 4064dc52b3f2b1edc705680f00d8aa33 | 33.493333 | 109 | 0.623357 | 5.224242 | false | false | false | false |
windchopper/password-drop | src/main/kotlin/com/github/windchopper/tools/password/drop/ui/EditController.kt | 1 | 4665 | @file:Suppress("unused", "UNUSED_ANONYMOUS_PARAMETER")
package com.github.windchopper.tools.password.drop.ui
import com.github.windchopper.common.fx.cdi.form.Form
import com.github.windchopper.common.fx.cdi.form.FormLoad
import com.github.windchopper.common.fx.cdi.form.StageFormLoad
import com.github.windchopper.common.util.ClassPathResource
import com.github.windchopper.tools.password.drop.Application
import com.github.windchopper.tools.password.drop.book.BookPart
import com.github.windchopper.tools.password.drop.book.Phrase
import com.github.windchopper.tools.password.drop.misc.*
import jakarta.enterprise.context.ApplicationScoped
import jakarta.enterprise.event.Event
import jakarta.enterprise.event.Observes
import jakarta.inject.Inject
import javafx.beans.binding.Bindings
import javafx.beans.property.adapter.JavaBeanStringPropertyBuilder
import javafx.event.ActionEvent
import javafx.fxml.FXML
import javafx.scene.Parent
import javafx.scene.control.Button
import javafx.scene.control.Label
import javafx.scene.control.TextField
import javafx.scene.layout.GridPane
import javafx.stage.Modality
import javafx.stage.StageStyle
@ApplicationScoped @Form(Application.FXML_EDIT) class EditController: Controller() {
@Inject private lateinit var formLoadEvent: Event<FormLoad>
@Inject private lateinit var treeUpdateRequestEvent: Event<TreeUpdateRequest>
@FXML private lateinit var rootPane: GridPane
@FXML private lateinit var nameField: TextField
@FXML private lateinit var textLabel: Label
@FXML private lateinit var textField: TextField
@FXML private lateinit var restoreButton: Button
private var savedName: String? = null
private var savedText: String? = null
override fun afterLoad(form: Parent, parameters: MutableMap<String, *>, formNamespace: MutableMap<String, *>) {
super.afterLoad(form, parameters, formNamespace)
bind(parameters["bookPart"] as BookPart)
rootPane.prefWidth = stage.screen().visualBounds.width / 4
nameField.textProperty().addListener { property, oldValue, newValue ->
treeUpdateRequestEvent.fire(TreeUpdateRequest())
}
restoreButton.disableProperty().bind(Bindings.createBooleanBinding(
{ savedName == nameField.text && savedText == textField.text },
nameField.textProperty(),
textField.textProperty()))
}
fun unbind() {
nameField.textProperty().unbindBidirectionalAndForget()
textField.textProperty().unbindBidirectionalAndForget()
}
fun bind(bookPart: BookPart) {
stage.title = "${Application.messages["edit.titlePrefix"]} - ${bookPart.type?.uncapitalize()}"
textLabel.isVisible = false
textField.isVisible = false
with (JavaBeanStringPropertyBuilder.create().bean(bookPart).name("name").build()) {
savedName = get()
nameField.textProperty().bindBidirectionalAndRemember(this)
}
if (bookPart !is Phrase) {
return
}
textLabel.isVisible = true
textField.isVisible = true
with (JavaBeanStringPropertyBuilder.create().bean(bookPart).name("text").build()) {
textField.isDisable = true
exceptionally {
savedText = get()
textField.textProperty().bindBidirectionalAndRemember(this)
textField.isDisable = false
}
}
}
fun editFired(@Observes event: TreeEdit<BookPart>) {
if (stage != null) if (stage.isShowing) {
unbind()
bind(event.item.value)
stage.toFront()
} else {
unbind()
bind(event.item.value)
stage.show()
} else {
formLoadEvent.fire(StageFormLoad(ClassPathResource(Application.FXML_EDIT), mutableMapOf("bookPart" to event.item.value)) {
event.invokerController.prepareChildStage(modality = Modality.NONE, style = StageStyle.UTILITY).also {
it.isResizable = false
}
})
}
}
fun selectionFired(@Observes event: TreeSelection<BookPart>) {
if (stage != null && stage.isShowing) {
unbind()
if (event.newSelection != null) {
bind(event.newSelection.value)
stage.toFront()
} else {
stage.hide()
}
}
}
fun hideFired(@Observes event: MainHide) {
stage?.hide()
}
@FXML fun restore(event: ActionEvent) {
nameField.textProperty().set(savedName)
textField.textProperty().set(savedText)
}
} | apache-2.0 | f7f26ffe7ababec3966a9cff6be4cecd | 34.348485 | 134 | 0.672883 | 4.632572 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/ReplaceManualRangeWithIndicesCallsInspection.kt | 3 | 8137 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.inspections
import com.intellij.codeInspection.LocalQuickFix
import com.intellij.codeInspection.ProblemDescriptor
import com.intellij.codeInspection.ProblemHighlightType
import com.intellij.codeInspection.ProblemsHolder
import com.intellij.openapi.project.Project
import com.intellij.psi.search.searches.ReferencesSearch
import org.jetbrains.kotlin.builtins.DefaultBuiltIns
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.caches.resolve.resolveToCall
import org.jetbrains.kotlin.idea.inspections.collections.isMap
import org.jetbrains.kotlin.idea.intentions.callExpression
import org.jetbrains.kotlin.idea.intentions.getArguments
import org.jetbrains.kotlin.idea.intentions.receiverTypeIfSelectorIsSizeOrLength
import org.jetbrains.kotlin.idea.references.mainReference
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType
import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameOrNull
import org.jetbrains.kotlin.utils.addToStdlib.safeAs
class ReplaceManualRangeWithIndicesCallsInspection : AbstractKotlinInspection() {
companion object {
private val rangeFunctionNames = setOf("until", "rangeTo", "..")
private val rangeFunctionFqNames = listOf(
"Char",
"Byte", "Short", "Int", "Long",
"UByte", "UShort", "UInt", "ULong"
).map { FqName("kotlin.$it.rangeTo") } + FqName("kotlin.ranges.until")
}
override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean) = object : KtVisitorVoid() {
override fun visitBinaryExpression(binaryExpression: KtBinaryExpression) {
val left = binaryExpression.left ?: return
val right = binaryExpression.right ?: return
val operator = binaryExpression.operationReference
visitRange(holder, binaryExpression, left, right, operator)
}
override fun visitDotQualifiedExpression(expression: KtDotQualifiedExpression) {
val call = expression.callExpression ?: return
val left = expression.receiverExpression
val right = call.valueArguments.singleOrNull()?.getArgumentExpression() ?: return
val operator = call.calleeExpression ?: return
visitRange(holder, expression, left, right, operator)
}
}
private fun visitRange(holder: ProblemsHolder, range: KtExpression, left: KtExpression, right: KtExpression, operator: KtExpression) {
if (operator.text !in rangeFunctionNames) return
val functionFqName = range.resolveToCall()?.resultingDescriptor?.fqNameOrNull() ?: return
if (functionFqName !in rangeFunctionFqNames) return
val rangeFunction = functionFqName.shortName().asString()
if (left.toIntConstant() != 0) return
val sizeOrLengthCall = right.sizeOrLengthCall(rangeFunction) ?: return
val collection = sizeOrLengthCall.safeAs<KtQualifiedExpression>()?.receiverExpression
if (collection != null && collection !is KtSimpleNameExpression) return
val parent = range.parent.parent
if (parent is KtForExpression) {
val paramElement = parent.loopParameter?.originalElement ?: return
val usageElement = ReferencesSearch.search(paramElement).singleOrNull()?.element
val arrayAccess = usageElement?.parent?.parent as? KtArrayAccessExpression
if (arrayAccess != null &&
arrayAccess.indexExpressions.singleOrNull() == usageElement &&
(arrayAccess.arrayExpression as? KtSimpleNameExpression)?.mainReference?.resolve() == collection?.mainReference?.resolve()
) {
val arrayAccessParent = arrayAccess.parent
if (arrayAccessParent !is KtBinaryExpression ||
arrayAccessParent.left != arrayAccess ||
arrayAccessParent.operationToken !in KtTokens.ALL_ASSIGNMENTS
) {
holder.registerProblem(
range,
KotlinBundle.message("for.loop.over.indices.could.be.replaced.with.loop.over.elements"),
ProblemHighlightType.GENERIC_ERROR_OR_WARNING,
ReplaceIndexLoopWithCollectionLoopQuickFix(rangeFunction)
)
return
}
}
}
holder.registerProblem(
range,
KotlinBundle.message("range.could.be.replaced.with.indices.call"),
ProblemHighlightType.GENERIC_ERROR_OR_WARNING,
ReplaceManualRangeWithIndicesCallQuickFix()
)
}
}
class ReplaceManualRangeWithIndicesCallQuickFix : LocalQuickFix {
override fun getName() = KotlinBundle.message("replace.manual.range.with.indices.call.quick.fix.text")
override fun getFamilyName() = name
override fun applyFix(project: Project, descriptor: ProblemDescriptor) {
val element = descriptor.psiElement as KtExpression
val receiver = when (val secondArg = element.getArguments()?.second) {
is KtBinaryExpression -> (secondArg.left as? KtDotQualifiedExpression)?.receiverExpression
is KtDotQualifiedExpression -> secondArg.receiverExpression
else -> null
}
val psiFactory = KtPsiFactory(project)
val newExpression = if (receiver != null) {
psiFactory.createExpressionByPattern("$0.indices", receiver)
} else {
psiFactory.createExpression("indices")
}
element.replace(newExpression)
}
}
class ReplaceIndexLoopWithCollectionLoopQuickFix(private val rangeFunction: String) : LocalQuickFix {
override fun getName() = KotlinBundle.message("replace.index.loop.with.collection.loop.quick.fix.text")
override fun getFamilyName() = name
override fun applyFix(project: Project, descriptor: ProblemDescriptor) {
val element = descriptor.psiElement.getStrictParentOfType<KtForExpression>() ?: return
val loopParameter = element.loopParameter ?: return
val loopRange = element.loopRange ?: return
val collectionParent = when (loopRange) {
is KtDotQualifiedExpression -> (loopRange.parent as? KtCallExpression)?.valueArguments?.firstOrNull()?.getArgumentExpression()
is KtBinaryExpression -> loopRange.right
else -> null
} ?: return
val sizeOrLengthCall = collectionParent.sizeOrLengthCall(rangeFunction) ?: return
val collection = (sizeOrLengthCall as? KtDotQualifiedExpression)?.receiverExpression
val paramElement = loopParameter.originalElement ?: return
val usageElement = ReferencesSearch.search(paramElement).singleOrNull()?.element ?: return
val arrayAccessElement = usageElement.parent.parent as? KtArrayAccessExpression ?: return
val factory = KtPsiFactory(project)
val newParameter = factory.createLoopParameter("element")
val newReferenceExpression = factory.createExpression("element")
arrayAccessElement.replace(newReferenceExpression)
loopParameter.replace(newParameter)
loopRange.replace(collection ?: factory.createThisExpression())
}
}
private fun KtExpression.toIntConstant(): Int? {
return (this as? KtConstantExpression)?.text?.toIntOrNull()
}
private fun KtExpression.sizeOrLengthCall(rangeFunction: String): KtExpression? {
val expression = when(rangeFunction) {
"until" -> this
"rangeTo" -> (this as? KtBinaryExpression)
?.takeIf { operationToken == KtTokens.MINUS && right?.toIntConstant() == 1}
?.left
else -> null
} ?: return null
val receiverType = expression.receiverTypeIfSelectorIsSizeOrLength() ?: return null
if (receiverType.isMap(DefaultBuiltIns.Instance)) return null
return expression
}
| apache-2.0 | 129e63f11482e7803aee5216420623b2 | 48.920245 | 158 | 0.700995 | 5.406645 | false | false | false | false |
smmribeiro/intellij-community | python/python-psi-impl/src/com/jetbrains/python/inspections/PyFinalInspection.kt | 9 | 19092 | // 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.python.inspections
import com.intellij.codeInspection.LocalInspectionToolSession
import com.intellij.codeInspection.ProblemHighlightType
import com.intellij.codeInspection.ProblemsHolder
import com.intellij.openapi.util.NlsSafe
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiElementVisitor
import com.jetbrains.python.PyNames
import com.jetbrains.python.PyPsiBundle
import com.jetbrains.python.codeInsight.controlflow.ScopeOwner
import com.jetbrains.python.codeInsight.dataflow.scope.ScopeUtil
import com.jetbrains.python.codeInsight.functionTypeComments.psi.PyFunctionTypeAnnotation
import com.jetbrains.python.codeInsight.functionTypeComments.psi.PyParameterTypeList
import com.jetbrains.python.codeInsight.typeHints.PyTypeHintFile
import com.jetbrains.python.codeInsight.typing.PyTypingTypeProvider.*
import com.jetbrains.python.psi.*
import com.jetbrains.python.psi.impl.PyClassImpl
import com.jetbrains.python.psi.search.PySuperMethodsSearch
import com.jetbrains.python.psi.types.PyClassType
import com.jetbrains.python.psi.types.TypeEvalContext
import com.jetbrains.python.pyi.PyiUtil
import com.jetbrains.python.refactoring.PyDefUseUtil
class PyFinalInspection : PyInspection() {
override fun buildVisitor(holder: ProblemsHolder,
isOnTheFly: Boolean,
session: LocalInspectionToolSession): PsiElementVisitor = Visitor(holder, PyInspectionVisitor.getContext(session))
private class Visitor(holder: ProblemsHolder, context: TypeEvalContext) : PyInspectionVisitor(holder, context) {
override fun visitPyClass(node: PyClass) {
super.visitPyClass(node)
node.getSuperClasses(myTypeEvalContext).filter { isFinal(it) }.let { finalSuperClasses ->
if (finalSuperClasses.isEmpty()) return@let
@NlsSafe val superClassList = finalSuperClasses.joinToString { "'${it.name}'" }
registerProblem(node.nameIdentifier,
PyPsiBundle.message("INSP.final.super.classes.are.marked.as.final.and.should.not.be.subclassed",
superClassList, finalSuperClasses.size))
}
if (PyiUtil.isInsideStub(node)) {
val visitedNames = mutableSetOf<String?>()
node.visitMethods(
{ m ->
if (!visitedNames.add(m.name) && isFinal(m)) {
registerProblem(m.nameIdentifier, PyPsiBundle.message("INSP.final.final.should.be.placed.on.first.overload"))
}
true
},
false,
myTypeEvalContext
)
}
else {
val (classLevelFinals, initAttributes) = getClassLevelFinalsAndInitAttributes(node)
checkClassLevelFinalsAreInitialized(classLevelFinals, initAttributes)
checkSameNameClassAndInstanceFinals(classLevelFinals, initAttributes)
}
checkOverridingInheritedFinalWithNewOne(node)
}
override fun visitPyFunction(node: PyFunction) {
super.visitPyFunction(node)
val cls = node.containingClass
if (cls != null) {
PySuperMethodsSearch
.search(node, myTypeEvalContext)
.asSequence()
.filterIsInstance<PyFunction>()
.firstOrNull { isFinal(it) }
?.let {
@NlsSafe val qualifiedName = it.qualifiedName ?: (it.containingClass?.name + "." + it.name)
registerProblem(node.nameIdentifier,
PyPsiBundle.message("INSP.final.method.marked.as.final.should.not.be.overridden", qualifiedName))
}
if (!PyiUtil.isInsideStub(node)) {
if (isFinal(node) && PyiUtil.isOverload(node, myTypeEvalContext)) {
registerProblem(node.nameIdentifier, PyPsiBundle.message("INSP.final.final.should.be.placed.on.implementation"))
}
checkInstanceFinalsOutsideInit(node)
}
if (PyKnownDecoratorUtil.hasAbstractDecorator(node, myTypeEvalContext)) {
if (isFinal(node)) {
registerProblem(node.nameIdentifier, PyPsiBundle.message("INSP.final.final.could.not.be.mixed.with.abstract.decorators"))
}
else if (isFinal(cls)) {
val message = PyPsiBundle.message("INSP.final.final.class.could.not.contain.abstract.methods")
registerProblem(node.nameIdentifier, message)
registerProblem(cls.nameIdentifier, message)
}
}
else if (isFinal(node) && isFinal(cls)) {
registerProblem(node.nameIdentifier, PyPsiBundle.message("INSP.final.no.need.to.mark.method.in.final.class.as.final"),
ProblemHighlightType.WEAK_WARNING)
}
}
else if (isFinal(node)) {
registerProblem(node.nameIdentifier, PyPsiBundle.message("INSP.final.non.method.function.could.not.be.marked.as.final"))
}
getFunctionTypeAnnotation(node)?.let { comment ->
if (comment.parameterTypeList.parameterTypes.any { resolvesToFinal(if (it is PySubscriptionExpression) it.operand else it) }) {
registerProblem(node.typeComment,
PyPsiBundle.message("INSP.final.final.could.not.be.used.in.annotations.for.function.parameters"))
}
}
getReturnTypeAnnotation(node, myTypeEvalContext)?.let {
if (resolvesToFinal(if (it is PySubscriptionExpression) it.operand else it)) {
registerProblem(node.typeComment ?: node.annotation,
PyPsiBundle.message("INSP.final.final.could.not.be.used.in.annotation.for.function.return.value"))
}
}
}
override fun visitPyTargetExpression(node: PyTargetExpression) {
super.visitPyTargetExpression(node)
if (!node.hasAssignedValue()) {
node.annotation?.value?.let {
if (PyiUtil.isInsideStub(node) || ScopeUtil.getScopeOwner(node) is PyClass) {
if (resolvesToFinal(it)) {
registerProblem(it,
PyPsiBundle.message("INSP.final.if.assigned.value.omitted.there.should.be.explicit.type.argument.to.final"))
}
}
else {
if (resolvesToFinal(if (it is PySubscriptionExpression) it.operand else it)) {
registerProblem(node, PyPsiBundle.message("INSP.final.final.name.should.be.initialized.with.value"))
}
}
}
}
else if (!isFinal(node)) {
checkFinalReassignment(node)
}
if (isFinal(node) && PyUtil.multiResolveTopPriority(node, resolveContext).any {
it != node && !PyDefUseUtil.isDefinedBefore(node, it)
}) {
registerProblem(node, PyPsiBundle.message("INSP.final.already.declared.name.could.not.be.redefined.as.final"))
}
}
override fun visitPyNamedParameter(node: PyNamedParameter) {
super.visitPyNamedParameter(node)
if (isFinal(node)) {
registerProblem(node.annotation?.value ?: node.typeComment,
PyPsiBundle.message("INSP.final.final.could.not.be.used.in.annotations.for.function.parameters"))
}
}
override fun visitPyReferenceExpression(node: PyReferenceExpression) {
super.visitPyReferenceExpression(node)
checkFinalIsOuterMost(node)
}
override fun visitPyForStatement(node: PyForStatement) {
super.visitPyForStatement(node)
checkFinalInsideLoop(node)
}
override fun visitPyWhileStatement(node: PyWhileStatement) {
super.visitPyWhileStatement(node)
checkFinalInsideLoop(node)
}
override fun visitPyAugAssignmentStatement(node: PyAugAssignmentStatement) {
super.visitPyAugAssignmentStatement(node)
val target = node.target
if (target is PyQualifiedExpression) {
checkFinalReassignment(target)
}
}
private fun getClassLevelFinalsAndInitAttributes(cls: PyClass): Pair<Map<String?, PyTargetExpression>, Map<String, PyTargetExpression>> {
val classLevelFinals = mutableMapOf<String?, PyTargetExpression>()
cls.classAttributes.forEach { if (isFinal(it)) classLevelFinals[it.name] = it }
val initAttributes = mutableMapOf<String, PyTargetExpression>()
cls.findMethodByName(PyNames.INIT, false, myTypeEvalContext)?.let { PyClassImpl.collectInstanceAttributes(it, initAttributes) }
return Pair(classLevelFinals, initAttributes)
}
private fun getDeclaredClassAndInstanceFinals(cls: PyClass): Pair<Map<String, PyTargetExpression>, Map<String, PyTargetExpression>> {
val classFinals = mutableMapOf<String, PyTargetExpression>()
val instanceFinals = mutableMapOf<String, PyTargetExpression>()
for (classAttribute in cls.classAttributes) {
val name = classAttribute.name ?: continue
if (isFinal(classAttribute)) {
val mapToPut = if (classAttribute.hasAssignedValue()) classFinals else instanceFinals
mapToPut[name] = classAttribute
}
}
cls.findMethodByName(PyNames.INIT, false, myTypeEvalContext)?.let { init ->
val attributesInInit = mutableMapOf<String, PyTargetExpression>()
PyClassImpl.collectInstanceAttributes(init, attributesInInit)
attributesInInit.keys.removeAll(instanceFinals.keys)
instanceFinals += attributesInInit.filterValues { isFinal(it) }
}
return Pair(classFinals, instanceFinals)
}
private fun checkClassLevelFinalsAreInitialized(classLevelFinals: Map<String?, PyTargetExpression>,
initAttributes: Map<String, PyTargetExpression>) {
classLevelFinals.forEach { (name, psi) ->
if (!psi.hasAssignedValue() && name !in initAttributes) {
registerProblem(psi, PyPsiBundle.message("INSP.final.final.name.should.be.initialized.with.value"))
}
}
}
private fun checkSameNameClassAndInstanceFinals(classLevelFinals: Map<String?, PyTargetExpression>,
initAttributes: Map<String, PyTargetExpression>) {
initAttributes.forEach { (name, initAttribute) ->
val sameNameClassLevelFinal = classLevelFinals[name]
if (sameNameClassLevelFinal != null && isFinal(initAttribute)) {
if (sameNameClassLevelFinal.hasAssignedValue()) {
registerProblem(initAttribute, PyPsiBundle.message("INSP.final.already.declared.name.could.not.be.redefined.as.final"))
}
else {
val message = PyPsiBundle.message("INSP.final.either.instance.attribute.or.class.attribute.could.be.type.hinted.as.final")
registerProblem(sameNameClassLevelFinal, message)
registerProblem(initAttribute, message)
}
}
}
}
private fun checkOverridingInheritedFinalWithNewOne(cls: PyClass) {
val (newClassFinals, newInstanceFinals) = getDeclaredClassAndInstanceFinals(cls)
val notRegisteredClassFinals = newClassFinals.keys.toMutableSet()
val notRegisteredInstanceFinals = newInstanceFinals.keys.toMutableSet()
if (notRegisteredClassFinals.isEmpty() && notRegisteredInstanceFinals.isEmpty()) return
for (ancestor in cls.getAncestorClasses(myTypeEvalContext)) {
val (inheritedClassFinals, inheritedInstanceFinals) = getDeclaredClassAndInstanceFinals(ancestor)
checkOverridingInheritedFinalWithNewOne(newClassFinals, inheritedClassFinals, ancestor.name, notRegisteredClassFinals)
checkOverridingInheritedFinalWithNewOne(newInstanceFinals, inheritedInstanceFinals, ancestor.name, notRegisteredInstanceFinals)
if (notRegisteredClassFinals.isEmpty() && notRegisteredInstanceFinals.isEmpty()) break
}
}
private fun checkOverridingInheritedFinalWithNewOne(newFinals: Map<String, PyTargetExpression>,
inheritedFinals: Map<String, PyTargetExpression>,
ancestorName: String?,
notRegistered: MutableSet<String>) {
if (notRegistered.isEmpty()) return
for (commonFinal in newFinals.keys.intersect(inheritedFinals.keys)) {
@NlsSafe val qualifiedName = "$ancestorName.$commonFinal"
registerProblem(newFinals[commonFinal], PyPsiBundle.message("INSP.final.final.attribute.could.not.be.overridden", qualifiedName))
notRegistered.remove(commonFinal)
}
}
private fun checkInstanceFinalsOutsideInit(method: PyFunction) {
if (PyUtil.isInitMethod(method)) return
val instanceAttributes = mutableMapOf<String, PyTargetExpression>()
PyClassImpl.collectInstanceAttributes(method, instanceAttributes)
instanceAttributes.values.forEach {
if (isFinal(it)) registerProblem(it, PyPsiBundle.message("INSP.final.final.attribute.should.be.declared.in.class.body.or.init"))
}
}
private fun checkFinalReassignment(target: PyQualifiedExpression) {
val qualifierType = target.qualifier?.let { myTypeEvalContext.getType(it) }
if (qualifierType is PyClassType && !qualifierType.isDefinition) {
checkInstanceFinalReassignment(target, qualifierType.pyClass)
return
}
// TODO: revert back to PyUtil#multiResolveTopPriority when resolve into global statement is implemented
val resolved = when (target) {
is PyReferenceOwner -> target.getReference(resolveContext).multiResolve(false).mapNotNull { it.element }
else -> PyUtil.multiResolveTopPriority(target, resolveContext)
}
if (resolved.any { it is PyTargetExpression && isFinal(it) }) {
registerProblem(target, PyPsiBundle.message("INSP.final.final.target.could.not.be.reassigned", target.name))
return
}
for (e in resolved) {
if (myTypeEvalContext.maySwitchToAST(e) &&
e.parent.let { it is PyNonlocalStatement || it is PyGlobalStatement } &&
PyUtil.multiResolveTopPriority(e, resolveContext).any { it is PyTargetExpression && isFinal(it) }) {
registerProblem(target, PyPsiBundle.message("INSP.final.final.target.could.not.be.reassigned", target.name))
return
}
}
if (!target.isQualified) {
val scopeOwner = ScopeUtil.getScopeOwner(target)
if (scopeOwner is PyClass) {
checkInheritedClassFinalReassignmentOnClassLevel(target, scopeOwner)
}
}
}
private fun checkInstanceFinalReassignment(target: PyQualifiedExpression, cls: PyClass) {
val name = target.name ?: return
val classAttribute = cls.findClassAttribute(name, false, myTypeEvalContext)
if (classAttribute != null && !classAttribute.hasAssignedValue() && isFinal(classAttribute)) {
if (target is PyTargetExpression &&
ScopeUtil.getScopeOwner(target).let { it is PyFunction && PyUtil.turnConstructorIntoClass(it) == cls }) {
return
}
registerProblem(target, PyPsiBundle.message("INSP.final.final.target.could.not.be.reassigned", name))
}
for (ancestor in cls.getAncestorClasses(myTypeEvalContext)) {
val inheritedClassAttribute = ancestor.findClassAttribute(name, false, myTypeEvalContext)
if (inheritedClassAttribute != null && !inheritedClassAttribute.hasAssignedValue() && isFinal(inheritedClassAttribute)) {
@NlsSafe val qualifiedName = "${ancestor.name}.$name"
registerProblem(target, PyPsiBundle.message("INSP.final.final.target.could.not.be.reassigned", qualifiedName))
return
}
}
for (current in (sequenceOf(cls) + cls.getAncestorClasses(myTypeEvalContext).asSequence())) {
val init = current.findMethodByName(PyNames.INIT, false, myTypeEvalContext)
if (init != null) {
val attributesInInit = mutableMapOf<String, PyTargetExpression>()
PyClassImpl.collectInstanceAttributes(init, attributesInInit)
if (attributesInInit[name]?.let { it != target && isFinal(it) } == true) {
@NlsSafe val qualifiedName = (if (cls == current) "" else "${current.name}.") + name
registerProblem(target, PyPsiBundle.message("INSP.final.final.target.could.not.be.reassigned", qualifiedName))
break
}
}
}
}
private fun checkInheritedClassFinalReassignmentOnClassLevel(target: PyQualifiedExpression, cls: PyClass) {
val name = target.name ?: return
for (ancestor in cls.getAncestorClasses(myTypeEvalContext)) {
val ancestorClassAttribute = ancestor.findClassAttribute(name, false, myTypeEvalContext)
if (ancestorClassAttribute != null && ancestorClassAttribute.hasAssignedValue() && isFinal(ancestorClassAttribute)) {
@NlsSafe val qualifiedName = "${ancestor.name}.$name"
registerProblem(target, PyPsiBundle.message("INSP.final.final.target.could.not.be.reassigned", qualifiedName))
break
}
}
}
private fun checkFinalIsOuterMost(node: PyReferenceExpression) {
if (isTopLevelInAnnotationOrTypeComment(node)) return
(node.parent as? PySubscriptionExpression)?.let {
if (it.operand == node && isTopLevelInAnnotationOrTypeComment(it)) return
}
if (isInsideTypeHint(node, myTypeEvalContext) && resolvesToFinal(node)) {
registerProblem(node, PyPsiBundle.message("INSP.final.final.could.only.be.used.as.outermost.type"))
}
}
private fun checkFinalInsideLoop(loop: PyLoopStatement) {
loop.acceptChildren(
object : PyRecursiveElementVisitor() {
override fun visitElement(element: PsiElement) {
if (element !is ScopeOwner) super.visitElement(element)
}
override fun visitPyForStatement(node: PyForStatement) {}
override fun visitPyWhileStatement(node: PyWhileStatement) {}
override fun visitPyTargetExpression(node: PyTargetExpression) {
if (isFinal(node)) registerProblem(node, PyPsiBundle.message("INSP.final.final.could.not.be.used.inside.loop"))
}
}
)
}
private fun isFinal(decoratable: PyDecoratable) = isFinal(decoratable, myTypeEvalContext)
private fun <T> isFinal(node: T): Boolean where T : PyAnnotationOwner, T : PyTypeCommentOwner {
return isFinal(node, myTypeEvalContext)
}
private fun resolvesToFinal(expression: PyExpression?): Boolean {
return expression is PyReferenceExpression &&
resolveToQualifiedNames(expression, myTypeEvalContext).any { it == FINAL || it == FINAL_EXT }
}
private fun isTopLevelInAnnotationOrTypeComment(node: PyExpression): Boolean {
val parent = node.parent
if (parent is PyAnnotation) return true
if (parent is PyExpressionStatement && parent.parent is PyTypeHintFile) return true
if (parent is PyParameterTypeList) return true
if (parent is PyFunctionTypeAnnotation) return true
return false
}
}
}
| apache-2.0 | ce53c618434b13988dd32aec5e072073 | 44.134752 | 142 | 0.686885 | 4.750435 | false | false | false | false |
jjandxa/circularrevealdemo | src/main/kotlin/com/tangcuxa/circularrevealdemo/OtherActivity.kt | 1 | 1663 | package com.tangcuxa.circularrevealdemo
import android.animation.Animator
import android.animation.AnimatorListenerAdapter
import android.os.Bundle
import android.os.Handler
import android.support.v7.app.AppCompatActivity
import android.view.View
import android.view.ViewAnimationUtils
import kotlinx.android.synthetic.main.content_main.*
/**
* Created by jjand on 2016/3/1.
*/
class OtherActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.content_main)
setSupportActionBar(toolbar)
Handler().post {
showActivity()
}
}
private fun showActivity() {
//获取动画开始坐标,以fab浮动按钮坐标为主
var cx: Int = (fab.left + fab.right) /2
var cy: Int = ((fab.top + fab.bottom)-75) /2
var anim: Animator
var finalRadius: Int = Math.max(relalayout.width,relalayout.height)
if (coordlayout.visibility == View.VISIBLE) {
anim = ViewAnimationUtils.createCircularReveal(coordlayout,cx,cy,finalRadius.toFloat(),0.toFloat())
anim.duration = 500
anim.addListener(object : AnimatorListenerAdapter() {
override fun onAnimationEnd(animation: Animator?) {
coordlayout.visibility = View.GONE
}
})
} else {
anim = ViewAnimationUtils.createCircularReveal(coordlayout,cx,cy,0.toFloat(),finalRadius.toFloat())
anim.duration = 500
coordlayout.visibility = View.VISIBLE
anim.start()
}
}
} | mit | 79a1e0a3176a95fd7cc07f14ad9b7fbf | 29.716981 | 111 | 0.651506 | 4.445355 | false | false | false | false |
jotomo/AndroidAPS | core/src/main/java/info/nightscout/androidaps/events/EventNetworkChange.kt | 1 | 294 | package info.nightscout.androidaps.events
import info.nightscout.androidaps.utils.StringUtils
class EventNetworkChange : Event() {
var mobileConnected = false
var wifiConnected = false
var vpnConnected = false
var ssid = ""
var roaming = false
var metered = false
}
| agpl-3.0 | f85686e83846ad47be0e9ffdb785e958 | 20 | 51 | 0.721088 | 4.323529 | false | false | false | false |
afollestad/assent | core/src/main/java/com/afollestad/assent/Activities.kt | 1 | 2564 | /**
* Designed and developed by Aidan Follestad (@afollestad)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
@file:Suppress("unused")
package com.afollestad.assent
import android.app.Activity
import android.content.Intent
import android.net.Uri
import android.provider.Settings.ACTION_APPLICATION_DETAILS_SETTINGS
import com.afollestad.assent.internal.Assent.Companion.ensureFragment
import com.afollestad.assent.rationale.RationaleHandler
import com.afollestad.assent.rationale.RealShouldShowRationale
import com.afollestad.assent.rationale.ShouldShowRationale
typealias Callback = (result: AssentResult) -> Unit
/**
* Performs a permission request, asking for all given [permissions], and
* invoking the [callback] with the result.
*/
fun Activity.askForPermissions(
vararg permissions: Permission,
requestCode: Int = 20,
rationaleHandler: RationaleHandler? = null,
callback: Callback
) {
val prefs: Prefs = RealPrefs(this)
val shouldShowRationale: ShouldShowRationale = RealShouldShowRationale(this, prefs)
startPermissionRequest(
ensure = { activity -> ensureFragment(activity) },
permissions = permissions,
requestCode = requestCode,
shouldShowRationale = shouldShowRationale,
rationaleHandler = rationaleHandler,
callback = callback
)
}
/**
* Like [askForPermissions], but only executes the [execute] callback if all given
* [permissions] are granted.
*/
fun Activity.runWithPermissions(
vararg permissions: Permission,
requestCode: Int = 40,
rationaleHandler: RationaleHandler? = null,
execute: Callback
) {
askForPermissions(
*permissions,
requestCode = requestCode,
rationaleHandler = rationaleHandler
) {
if (it.isAllGranted(*permissions)) {
execute.invoke(it)
}
}
}
/**
* Launches app settings for the current app. Useful when permissions are permanently
* denied.
*/
fun Activity.showSystemAppDetailsPage() {
startActivity(
Intent(ACTION_APPLICATION_DETAILS_SETTINGS).apply {
data = Uri.parse("package:$packageName")
}
)
}
| apache-2.0 | 4eb0db8305851fae104359f86c97a45e | 29.52381 | 85 | 0.75078 | 4.323777 | false | false | false | false |
mdaniel/intellij-community | plugins/kotlin/base/util/src/org/jetbrains/kotlin/caches/project/CacheUtils.kt | 1 | 3131 | // 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.caches.project
import com.intellij.openapi.module.Module
import com.intellij.openapi.project.Project
import com.intellij.openapi.roots.ProjectRootModificationTracker
import com.intellij.openapi.util.UserDataHolder
import com.intellij.psi.util.CachedValue
import com.intellij.psi.util.CachedValueProvider
import com.intellij.psi.util.CachedValuesManager
import kotlin.reflect.KProperty
fun <T> Module.cacheByClass(classForKey: Class<*>, vararg dependencies: Any, provider: () -> T): T {
return CachedValuesManager.getManager(project).cache(this, dependencies, classForKey, provider)
}
@Deprecated("consider to use WorkspaceModelChangeListener")
fun <T> Module.cacheByClassInvalidatingOnRootModifications(classForKey: Class<*>, provider: () -> T): T {
return cacheByClass(classForKey, ProjectRootModificationTracker.getInstance(project), provider = provider)
}
/**
* Note that it uses lambda's class for caching (essentially, anonymous class), which means that all invocations will be cached
* by the one and the same key.
* It is encouraged to use explicit class, just for the sake of readability.
*/
@Deprecated("consider to use WorkspaceModelChangeListener")
fun <T> Module.cacheInvalidatingOnRootModifications(provider: () -> T): T {
return cacheByClassInvalidatingOnRootModifications(provider::class.java, provider)
}
fun <T> Project.cacheByClass(classForKey: Class<*>, vararg dependencies: Any, provider: () -> T): T {
return CachedValuesManager.getManager(this).cache(this, dependencies, classForKey, provider)
}
@Deprecated("consider to use WorkspaceModelChangeListener")
fun <T> Project.cacheByClassInvalidatingOnRootModifications(classForKey: Class<*>, provider: () -> T): T {
return cacheByClass(classForKey, ProjectRootModificationTracker.getInstance(this), provider = provider)
}
/**
* Note that it uses lambda's class for caching (essentially, anonymous class), which means that all invocations will be cached
* by the one and the same key.
* It is encouraged to use explicit class, just for the sake of readability.
*/
@Suppress("DEPRECATION")
@Deprecated("consider to use WorkspaceModelChangeListener")
fun <T> Project.cacheInvalidatingOnRootModifications(provider: () -> T): T {
return cacheByClassInvalidatingOnRootModifications(provider::class.java, provider)
}
private fun <T> CachedValuesManager.cache(
holder: UserDataHolder,
dependencies: Array<out Any>,
classForKey: Class<*>,
provider: () -> T
): T {
return getCachedValue(
holder,
getKeyForClass(classForKey),
{ CachedValueProvider.Result.create(provider(), *dependencies) },
false
)
}
operator fun <T> CachedValue<T>.getValue(o: Any, property: KProperty<*>): T = value
fun <T> CachedValue(project: Project, trackValue: Boolean = false, provider: () -> CachedValueProvider.Result<T>) =
CachedValuesManager.getManager(project).createCachedValue(provider, trackValue)
| apache-2.0 | bb6b1dee58d6b4d561598b42212e863d | 43.728571 | 158 | 0.766209 | 4.336565 | false | false | false | false |
intellij-purescript/intellij-purescript | src/main/kotlin/org/purescript/psi/expression/PSExpressionWhere.kt | 1 | 519 | package org.purescript.psi.expression
import com.intellij.lang.ASTNode
import org.purescript.psi.PSPsiElement
import org.purescript.psi.declaration.PSValueDeclaration
/**
* A where claus un a expression, e.g.
* ```
* where x = 1
* ```
* in
* ```
* f = x
* where x = 1
* ```
*/
class PSExpressionWhere(node: ASTNode) : PSPsiElement(node) {
val where get() = findChildByClass(PSExpressionWhere::class.java)
val valueDeclarations get() =
findChildrenByClass(PSValueDeclaration::class.java)
} | bsd-3-clause | 3ad5b613682dec68c8bf2e41f832a963 | 22.636364 | 69 | 0.695568 | 3.554795 | false | false | false | false |
siosio/intellij-community | plugins/kotlin/gradle/gradle-tooling/src/KotlinDslScriptModelProvider.kt | 1 | 1596 | // 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.gradle
import org.gradle.tooling.BuildController
import org.gradle.tooling.model.Model
import org.gradle.tooling.model.gradle.GradleBuild
import org.gradle.tooling.model.kotlin.dsl.KotlinDslScriptsModel
import org.jetbrains.plugins.gradle.model.ProjectImportModelProvider
class KotlinDslScriptModelProvider : ProjectImportModelProvider {
private val kotlinDslScriptModelClass: Class<*> = KotlinDslScriptsModel::class.java
override fun populateBuildModels(
controller: BuildController,
buildModel: GradleBuild,
consumer: ProjectImportModelProvider.BuildModelConsumer
) {
buildModel.projects.forEach {
if (it.parent == null) {
try {
val model = controller.findModel(it, kotlinDslScriptModelClass)
if (model != null) {
consumer.consumeProjectModel(it, model, kotlinDslScriptModelClass)
}
} catch (e: Throwable) {
consumer.consumeProjectModel(
it,
BrokenKotlinDslScriptsModel(e), kotlinDslScriptModelClass
)
}
}
}
}
override fun populateProjectModels(
controller: BuildController,
projectModel: Model,
modelConsumer: ProjectImportModelProvider.ProjectModelConsumer
) = Unit
} | apache-2.0 | a58fc8e8bab82461224a1955216d1e6c | 37.95122 | 158 | 0.653509 | 5.428571 | false | false | false | false |
siosio/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/codeInliner/CodeToInlineBuilder.kt | 1 | 20759 | // 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.codeInliner
import com.intellij.psi.util.elementType
import org.jetbrains.kotlin.builtins.isExtensionFunctionType
import org.jetbrains.kotlin.descriptors.*
import org.jetbrains.kotlin.diagnostics.Errors
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.caches.resolve.getResolutionFacade
import org.jetbrains.kotlin.idea.codeInliner.CommentHolder.CommentNode.Companion.mergeComments
import org.jetbrains.kotlin.idea.core.asExpression
import org.jetbrains.kotlin.idea.core.copied
import org.jetbrains.kotlin.idea.core.replaced
import org.jetbrains.kotlin.idea.imports.importableFqName
import org.jetbrains.kotlin.idea.intentions.InsertExplicitTypeArgumentsIntention
import org.jetbrains.kotlin.idea.intentions.SpecifyExplicitLambdaSignatureIntention
import org.jetbrains.kotlin.idea.references.canBeResolvedViaImport
import org.jetbrains.kotlin.idea.resolve.ResolutionFacade
import org.jetbrains.kotlin.idea.util.IdeDescriptorRenderers
import org.jetbrains.kotlin.idea.util.getResolutionScope
import org.jetbrains.kotlin.idea.util.isAnonymousFunction
import org.jetbrains.kotlin.incremental.components.NoLookupLocation
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.*
import org.jetbrains.kotlin.renderer.render
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.ImportedFromObjectCallableDescriptor
import org.jetbrains.kotlin.resolve.calls.callUtil.getResolvedCall
import org.jetbrains.kotlin.resolve.calls.model.ResolvedCall
import org.jetbrains.kotlin.resolve.calls.model.isReallySuccess
import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameOrNull
import org.jetbrains.kotlin.resolve.descriptorUtil.isExtension
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
import org.jetbrains.kotlin.resolve.scopes.receivers.ImplicitReceiver
import org.jetbrains.kotlin.resolve.scopes.utils.findClassifier
import org.jetbrains.kotlin.types.ErrorUtils
import org.jetbrains.kotlin.utils.addToStdlib.cast
import org.jetbrains.kotlin.utils.addToStdlib.safeAs
import org.jetbrains.kotlin.utils.sure
class CodeToInlineBuilder(
private val targetCallable: CallableDescriptor,
private val resolutionFacade: ResolutionFacade,
private val originalDeclaration: KtDeclaration?,
private val fallbackToSuperCall: Boolean = false,
) {
private val psiFactory = KtPsiFactory(resolutionFacade.project)
fun prepareCodeToInlineWithAdvancedResolution(
bodyOrExpression: KtExpression,
expressionMapper: (bodyOrExpression: KtExpression) -> Pair<KtExpression?, List<KtExpression>>?,
): CodeToInline? {
val (mainExpression, statementsBefore) = expressionMapper(bodyOrExpression) ?: return null
val codeToInline = prepareMutableCodeToInline(
mainExpression = mainExpression,
statementsBefore = statementsBefore,
analyze = { it.analyze(BodyResolveMode.PARTIAL) },
reformat = true,
)
val copyOfBodyOrExpression = bodyOrExpression.copied()
// Body's expressions to be inlined contain related comments as a user data (see CommentHolder.CommentNode.Companion.mergeComments).
// When inlining (with untouched declaration!) is reverted and called again expressions become polluted with duplicates (^ merge!).
// Now that we copied required data it's time to clear the storage.
codeToInline.expressions.forEach { it.putCopyableUserData(CommentHolder.COMMENTS_TO_RESTORE_KEY, null) }
val (resultMainExpression, resultStatementsBefore) = expressionMapper(copyOfBodyOrExpression) ?: return null
codeToInline.mainExpression = resultMainExpression
codeToInline.statementsBefore.clear()
codeToInline.statementsBefore.addAll(resultStatementsBefore)
return codeToInline.toNonMutable()
}
private fun prepareMutableCodeToInline(
mainExpression: KtExpression?,
statementsBefore: List<KtExpression>,
analyze: (KtExpression) -> BindingContext,
reformat: Boolean,
): MutableCodeToInline {
val alwaysKeepMainExpression =
when (val descriptor = mainExpression?.getResolvedCall(analyze(mainExpression))?.resultingDescriptor) {
is PropertyDescriptor -> descriptor.getter?.isDefault == false
else -> false
}
val codeToInline = MutableCodeToInline(
mainExpression,
statementsBefore.toMutableList(),
mutableSetOf(),
alwaysKeepMainExpression,
extraComments = null,
)
if (originalDeclaration != null) {
saveComments(codeToInline, originalDeclaration)
}
insertExplicitTypeArguments(codeToInline, analyze)
processReferences(codeToInline, analyze, reformat)
removeContracts(codeToInline, analyze)
when {
mainExpression == null -> Unit
mainExpression.isNull() -> targetCallable.returnType?.let { returnType ->
codeToInline.addPreCommitAction(mainExpression) {
codeToInline.replaceExpression(
it,
psiFactory.createExpression(
"null as ${
IdeDescriptorRenderers.FQ_NAMES_IN_TYPES_WITH_NORMALIZER.renderType(returnType)
}"
),
)
}
}
else -> {
val functionLiteralExpression = mainExpression.unpackFunctionLiteral(true)
if (functionLiteralExpression != null) {
val functionLiteralParameterTypes = getParametersForFunctionLiteral(functionLiteralExpression, analyze)
if (functionLiteralParameterTypes != null) {
codeToInline.addPostInsertionAction(mainExpression) { inlinedExpression ->
addFunctionLiteralParameterTypes(functionLiteralParameterTypes, inlinedExpression)
}
}
}
}
}
return codeToInline
}
private fun removeContracts(codeToInline: MutableCodeToInline, analyze: (KtExpression) -> BindingContext) {
for (statement in codeToInline.statementsBefore) {
val context = analyze(statement)
if (statement.getResolvedCall(context)?.resultingDescriptor?.fqNameOrNull()?.asString() == "kotlin.contracts.contract") {
codeToInline.addPreCommitAction(statement) {
codeToInline.statementsBefore.remove(it)
}
}
}
}
fun prepareCodeToInline(
mainExpression: KtExpression?,
statementsBefore: List<KtExpression>,
analyze: (KtExpression) -> BindingContext,
reformat: Boolean,
): CodeToInline = prepareMutableCodeToInline(mainExpression, statementsBefore, analyze, reformat).toNonMutable()
private fun saveComments(codeToInline: MutableCodeToInline, contextDeclaration: KtDeclaration) {
val bodyBlockExpression = contextDeclaration.safeAs<KtDeclarationWithBody>()?.bodyBlockExpression
if (bodyBlockExpression != null) addCommentHoldersForStatements(codeToInline, bodyBlockExpression)
}
private fun addCommentHoldersForStatements(mutableCodeToInline: MutableCodeToInline, blockExpression: KtBlockExpression) {
val expressions = mutableCodeToInline.expressions
for ((indexOfIteration, commentHolder) in CommentHolder.extract(blockExpression).withIndex()) {
if (commentHolder.isEmpty) continue
if (expressions.isEmpty()) {
mutableCodeToInline.addExtraComments(commentHolder)
} else {
val expression = expressions.elementAtOrNull(indexOfIteration)
if (expression != null) {
expression.mergeComments(commentHolder)
} else {
expressions.last().mergeComments(
CommentHolder(emptyList(), trailingComments = commentHolder.leadingComments + commentHolder.trailingComments)
)
}
}
}
}
private fun getParametersForFunctionLiteral(
functionLiteralExpression: KtLambdaExpression,
analyze: (KtExpression) -> BindingContext
): String? {
val context = analyze(functionLiteralExpression)
val lambdaDescriptor = context.get(BindingContext.FUNCTION, functionLiteralExpression.functionLiteral)
if (lambdaDescriptor == null ||
ErrorUtils.containsErrorTypeInParameters(lambdaDescriptor) ||
ErrorUtils.containsErrorType(lambdaDescriptor.returnType)
) return null
return lambdaDescriptor.valueParameters.joinToString {
it.name.render() + ": " + IdeDescriptorRenderers.SOURCE_CODE.renderType(it.type)
}
}
private fun addFunctionLiteralParameterTypes(parameters: String, inlinedExpression: KtExpression) {
val containingFile = inlinedExpression.containingKtFile
val resolutionFacade = containingFile.getResolutionFacade()
val lambdaExpr = inlinedExpression.unpackFunctionLiteral(true).sure {
"can't find function literal expression for " + inlinedExpression.text
}
if (!needToAddParameterTypes(lambdaExpr, resolutionFacade)) return
SpecifyExplicitLambdaSignatureIntention.applyWithParameters(lambdaExpr, parameters)
}
private fun needToAddParameterTypes(
lambdaExpression: KtLambdaExpression,
resolutionFacade: ResolutionFacade
): Boolean {
val functionLiteral = lambdaExpression.functionLiteral
val context = resolutionFacade.analyze(lambdaExpression, BodyResolveMode.PARTIAL_WITH_DIAGNOSTICS)
return context.diagnostics.any { diagnostic ->
val factory = diagnostic.factory
val element = diagnostic.psiElement
val hasCantInferParameter = factory == Errors.CANNOT_INFER_PARAMETER_TYPE && element.parent.parent == functionLiteral
val hasUnresolvedItOrThis = factory == Errors.UNRESOLVED_REFERENCE &&
element.text == "it" &&
element.getStrictParentOfType<KtFunctionLiteral>() == functionLiteral
hasCantInferParameter || hasUnresolvedItOrThis
}
}
private fun insertExplicitTypeArguments(
codeToInline: MutableCodeToInline,
analyze: (KtExpression) -> BindingContext,
) = codeToInline.forEachDescendantOfType<KtCallExpression> {
val bindingContext = analyze(it)
if (InsertExplicitTypeArgumentsIntention.isApplicableTo(it, bindingContext)) {
val typeArguments = InsertExplicitTypeArgumentsIntention.createTypeArguments(it, bindingContext)!!
codeToInline.addPreCommitAction(it) { callExpression ->
callExpression.addAfter(typeArguments, callExpression.calleeExpression)
}
}
}
private fun findDescriptorAndContext(
expression: KtSimpleNameExpression,
analyzer: (KtExpression) -> BindingContext
): Pair<BindingContext, DeclarationDescriptor>? {
val currentContext = analyzer(expression)
val descriptor = currentContext[BindingContext.SHORT_REFERENCE_TO_COMPANION_OBJECT, expression]
?: currentContext[BindingContext.REFERENCE_TARGET, expression]
if (descriptor != null) return currentContext to descriptor
return findCallableDescriptorAndContext(expression, analyzer)
}
private fun findCallableDescriptorAndContext(
expression: KtSimpleNameExpression,
analyzer: (KtExpression) -> BindingContext
): Pair<BindingContext, CallableDescriptor>? {
val callExpression = expression.parent as? KtCallExpression ?: return null
val context = analyzer(callExpression)
return callExpression.getResolvedCall(context)?.resultingDescriptor?.let { context to it }
}
private fun findResolvedCall(
expression: KtSimpleNameExpression,
bindingContext: BindingContext,
analyzer: (KtExpression) -> BindingContext,
): Pair<KtExpression, ResolvedCall<out CallableDescriptor>>? {
return getResolvedCallIfReallySuccess(expression, bindingContext)?.let { expression to it }
?: expression.parent?.safeAs<KtCallExpression>()?.let { callExpression ->
getResolvedCallIfReallySuccess(callExpression, analyzer(callExpression))?.let { callExpression to it }
}
}
private fun getResolvedCallIfReallySuccess(
expression: KtExpression,
bindingContext: BindingContext
): ResolvedCall<out CallableDescriptor>? {
return expression.getResolvedCall(bindingContext)?.takeIf { it.isReallySuccess() }
}
private fun processReferences(codeToInline: MutableCodeToInline, analyze: (KtExpression) -> BindingContext, reformat: Boolean) {
val targetDispatchReceiverType = targetCallable.dispatchReceiverParameter?.value?.type
val targetExtensionReceiverType = targetCallable.extensionReceiverParameter?.value?.type
val isAnonymousFunction = originalDeclaration?.isAnonymousFunction == true
val isAnonymousFunctionWithReceiver = isAnonymousFunction &&
originalDeclaration.cast<KtNamedFunction>().receiverTypeReference != null
fun getParameterName(parameter: ValueParameterDescriptor): Name = if (isAnonymousFunction) {
val shift = if (isAnonymousFunctionWithReceiver) 2 else 1
Name.identifier("p${parameter.index + shift}")
} else {
parameter.name
}
codeToInline.forEachDescendantOfType<KtSimpleNameExpression> { expression ->
val parent = expression.parent
if (parent is KtValueArgumentName || parent is KtCallableReferenceExpression) return@forEachDescendantOfType
val (bindingContext, target) = findDescriptorAndContext(expression, analyze)
?: return@forEachDescendantOfType addFakeSuperReceiver(codeToInline, expression)
//TODO: other types of references ('[]' etc)
if (expression.canBeResolvedViaImport(target, bindingContext)) {
val importableFqName = target.importableFqName
if (importableFqName != null) {
val lexicalScope = (expression.containingFile as? KtFile)?.getResolutionScope(bindingContext, resolutionFacade)
val lookupName = lexicalScope?.findClassifier(importableFqName.shortName(), NoLookupLocation.FROM_IDE)
?.typeConstructor
?.declarationDescriptor
?.fqNameOrNull()
codeToInline.fqNamesToImport.add(lookupName ?: importableFqName)
}
}
val callableDescriptor = targetCallable.safeAs<ImportedFromObjectCallableDescriptor<*>>()?.callableFromObject ?: targetCallable
val receiverExpression = expression.getReceiverExpression()
if (receiverExpression != null &&
parent is KtCallExpression &&
target is ValueParameterDescriptor &&
target.type.isExtensionFunctionType &&
target.containingDeclaration == callableDescriptor
) {
codeToInline.addPreCommitAction(parent) { callExpression ->
val qualifiedExpression = callExpression.parent as KtDotQualifiedExpression
val valueArgumentList = callExpression.getOrCreateValueArgumentList()
val newArgument = psiFactory.createArgument(qualifiedExpression.receiverExpression)
valueArgumentList.addArgumentBefore(newArgument, valueArgumentList.arguments.firstOrNull())
val newExpression = qualifiedExpression.replaced(callExpression)
if (qualifiedExpression in codeToInline) {
codeToInline.replaceExpression(qualifiedExpression, newExpression)
}
}
expression.putCopyableUserData(CodeToInline.PARAMETER_USAGE_KEY, getParameterName(target))
} else if (receiverExpression == null) {
if (isAnonymousFunctionWithReceiver && target == callableDescriptor) {
// parent is [KtThisExpression]
parent.putCopyableUserData(CodeToInline.PARAMETER_USAGE_KEY, getFirstParameterName())
} else if (target is ValueParameterDescriptor && target.containingDeclaration == callableDescriptor) {
expression.putCopyableUserData(CodeToInline.PARAMETER_USAGE_KEY, getParameterName(target))
} else if (target is TypeParameterDescriptor && target.containingDeclaration == callableDescriptor) {
expression.putCopyableUserData(CodeToInline.TYPE_PARAMETER_USAGE_KEY, target.name)
}
if (targetCallable !is ImportedFromObjectCallableDescriptor<*>) {
val (expressionToResolve, resolvedCall) = findResolvedCall(expression, bindingContext, analyze)
?: return@forEachDescendantOfType
val receiver = if (resolvedCall.resultingDescriptor.isExtension)
resolvedCall.extensionReceiver
else
resolvedCall.dispatchReceiver
if (receiver is ImplicitReceiver) {
val resolutionScope = expression.getResolutionScope(bindingContext, resolutionFacade)
val receiverExpressionToInline = receiver.asExpression(resolutionScope, psiFactory)
if (receiverExpressionToInline != null) {
val receiverType = receiver.type
codeToInline.addPreCommitAction(expressionToResolve) { expr ->
val expressionToReplace = expr.parent as? KtCallExpression ?: expr
val replaced = codeToInline.replaceExpression(
expressionToReplace,
psiFactory.createExpressionByPattern(
"$0.$1", receiverExpressionToInline, expressionToReplace,
reformat = reformat
)
) as? KtQualifiedExpression
val thisExpression = replaced?.receiverExpression ?: return@addPreCommitAction
if (isAnonymousFunctionWithReceiver && receiverType == targetExtensionReceiverType) {
thisExpression.putCopyableUserData(CodeToInline.PARAMETER_USAGE_KEY, getFirstParameterName())
} else if (receiverType != targetDispatchReceiverType && receiverType != targetExtensionReceiverType) {
thisExpression.putCopyableUserData(CodeToInline.SIDE_RECEIVER_USAGE_KEY, Unit)
}
}
}
}
}
}
}
}
private fun addFakeSuperReceiver(codeToInline: MutableCodeToInline, expression: KtExpression) {
if (!fallbackToSuperCall || expression !is KtNameReferenceExpression) return
val parent = expression.parent
val prevSiblingElementType = expression.getPrevSiblingIgnoringWhitespaceAndComments()?.elementType
if (prevSiblingElementType != KtTokens.SAFE_ACCESS && prevSiblingElementType != KtTokens.DOT) {
val expressionToReplace = if (parent is KtCallExpression) parent else expression
codeToInline.addPreCommitAction(expressionToReplace) { referenceExpression ->
val qualifierExpression = codeToInline.replaceExpression(
referenceExpression,
psiFactory.createExpressionByPattern("super.$0", referenceExpression),
) as? KtDotQualifiedExpression
qualifierExpression?.receiverExpression?.putCopyableUserData(CodeToInline.FAKE_SUPER_CALL_KEY, Unit)
}
}
}
}
private fun getFirstParameterName(): Name = Name.identifier("p1")
| apache-2.0 | 073af6b5e1dfcb2f1a15cbdfb4ea07b8 | 50.8975 | 158 | 0.676092 | 6.387385 | false | false | false | false |
siosio/intellij-community | platform/util-ex/src/com/intellij/openapi/progress/sink.kt | 1 | 2490 | // Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
@file:ApiStatus.Experimental
package com.intellij.openapi.progress
import kotlinx.coroutines.CoroutineScope
import org.jetbrains.annotations.ApiStatus
import kotlin.coroutines.AbstractCoroutineContextElement
import kotlin.coroutines.CoroutineContext
import kotlin.coroutines.coroutineContext
/**
* Usage example:
* ```
* val sink = new MyCoolSink()
* // launch a coroutine to update UI with data from MyCoolSink
* withContext(progressSinkElement(sink)) {
* // available on CoroutineScope as a property
* // safe null operator allows to skip the evaluation of the resource bundle part
* progressSink?.text(ResourceBundle.message("starting.progress.text"))
* ...
* doStuff()
* }
* suspend fun doStuff() {
* // available inside suspend functions as a function
* progressSink()?.details("stuff")
* }
* ```
*/
fun progressSinkElement(sink: ProgressSink): CoroutineContext.Element {
return ProgressSinkElement(sink)
}
internal val CoroutineContext.progressSink: ProgressSink? get() = this[ProgressSinkKey]?.sink
val CoroutineScope.progressSink: ProgressSink? get() = coroutineContext.progressSink
// kotlin doesn't allow suspend on properties
suspend fun progressSink(): ProgressSink? = coroutineContext.progressSink
private object ProgressSinkKey : CoroutineContext.Key<ProgressSinkElement>
private class ProgressSinkElement(val sink: ProgressSink) : AbstractCoroutineContextElement(ProgressSinkKey)
private object SilentProgressSink : ProgressSink {
override fun text(text: String): Unit = Unit
override fun details(details: String): Unit = Unit
override fun fraction(fraction: Double): Unit = Unit
}
internal class ProgressIndicatorSink(private val indicator: ProgressIndicator) : ProgressSink {
override fun text(text: String) {
indicator.text = text
}
override fun details(details: String) {
indicator.text2 = details
}
override fun fraction(fraction: Double) {
indicator.fraction = fraction
}
}
internal class ProgressSinkIndicator(private val sink: ProgressSink) : EmptyProgressIndicator() {
override fun setText(text: String?) {
if (text != null) {
sink.text(text)
}
}
override fun setText2(text: String?) {
if (text != null) {
sink.details(text)
}
}
override fun setFraction(fraction: Double) {
sink.fraction(fraction)
}
}
| apache-2.0 | d43f50840f9fc740b9b75b9570f3adeb | 29.365854 | 140 | 0.747791 | 4.430605 | false | false | false | false |
siosio/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/OverridingDeprecatedMemberInspection.kt | 1 | 2844 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.inspections
import com.intellij.codeInspection.ProblemHighlightType
import com.intellij.codeInspection.ProblemsHolder
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiElementVisitor
import org.jetbrains.kotlin.descriptors.CallableMemberDescriptor
import org.jetbrains.kotlin.idea.FrontendInternals
import org.jetbrains.kotlin.idea.caches.resolve.getResolutionFacade
import org.jetbrains.kotlin.idea.caches.resolve.resolveToDescriptorIfAny
import org.jetbrains.kotlin.idea.resolve.frontendService
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.KtDeclaration
import org.jetbrains.kotlin.psi.KtNamedDeclaration
import org.jetbrains.kotlin.psi.KtPropertyAccessor
import org.jetbrains.kotlin.psi.KtVisitorVoid
import org.jetbrains.kotlin.resolve.deprecation.DeprecationResolver
import org.jetbrains.kotlin.resolve.deprecation.deprecatedByOverriddenMessage
class OverridingDeprecatedMemberInspection : AbstractKotlinInspection() {
override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean): PsiElementVisitor {
return object : KtVisitorVoid() {
override fun visitNamedDeclaration(declaration: KtNamedDeclaration) {
if (!declaration.hasModifier(KtTokens.OVERRIDE_KEYWORD)) return
registerProblemIfNeeded(declaration, declaration.nameIdentifier ?: return)
}
override fun visitPropertyAccessor(accessor: KtPropertyAccessor) {
if (!accessor.property.hasModifier(KtTokens.OVERRIDE_KEYWORD)) return
registerProblemIfNeeded(accessor, accessor.namePlaceholder)
}
private fun registerProblemIfNeeded(declaration: KtDeclaration, targetForProblem: PsiElement) {
val resolutionFacade = declaration.getResolutionFacade()
val accessorDescriptor = declaration.resolveToDescriptorIfAny(resolutionFacade) as? CallableMemberDescriptor ?: return
@OptIn(FrontendInternals::class)
val deprecationProvider = resolutionFacade.frontendService<DeprecationResolver>()
val message = deprecationProvider.getDeprecations(accessorDescriptor)
.firstOrNull()
?.deprecatedByOverriddenMessage() ?: return
val problem = holder.manager.createProblemDescriptor(
targetForProblem,
message,
/* showTooltip = */ true,
ProblemHighlightType.LIKE_DEPRECATED,
isOnTheFly
)
holder.registerProblem(problem)
}
}
}
}
| apache-2.0 | 66a6c3538cf01adfb581fb90ff821e40 | 49.785714 | 158 | 0.72398 | 5.839836 | false | false | false | false |
jwren/intellij-community | plugins/kotlin/j2k/old/src/org/jetbrains/kotlin/j2k/Utils.kt | 6 | 7492 | // 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.j2k
import com.intellij.psi.*
import com.intellij.psi.util.PsiMethodUtil
import org.jetbrains.kotlin.asJava.classes.KtLightClass
import org.jetbrains.kotlin.builtins.StandardNames
import org.jetbrains.kotlin.j2k.ast.*
import org.jetbrains.kotlin.types.expressions.OperatorConventions
fun quoteKeywords(packageName: String): String = packageName.split('.').joinToString(".") { Identifier.toKotlin(it) }
fun getDefaultInitializer(property: Property): Expression? {
val t = property.type
val result = when {
t.isNullable -> LiteralExpression("null")
t is PrimitiveType -> when (t.name.name) {
"Boolean" -> LiteralExpression("false")
"Char" -> LiteralExpression("' '")
"Double" -> MethodCallExpression.buildNonNull(LiteralExpression("0").assignNoPrototype(), OperatorConventions.DOUBLE.toString())
"Float" -> MethodCallExpression.buildNonNull(LiteralExpression("0").assignNoPrototype(), OperatorConventions.FLOAT.toString())
else -> LiteralExpression("0")
}
else -> null
}
return result?.assignNoPrototype()
}
fun shouldGenerateDefaultInitializer(searcher: ReferenceSearcher, field: PsiField)
= field.initializer == null && (field.isVar(searcher) || !field.hasWriteAccesses(searcher, field.containingClass))
fun PsiReferenceExpression.isQualifierEmptyOrThis(): Boolean {
val qualifier = qualifierExpression
return qualifier == null || (qualifier is PsiThisExpression && qualifier.qualifier == null)
}
fun PsiReferenceExpression.isQualifierEmptyOrClass(psiClass: PsiClass): Boolean {
val qualifier = qualifierExpression
return qualifier == null || (qualifier is PsiReferenceExpression && qualifier.isReferenceTo(psiClass))
}
fun PsiElement.isInSingleLine(): Boolean {
if (this is PsiWhiteSpace) {
val text = text!!
return text.indexOf('\n') < 0 && text.indexOf('\r') < 0
}
var child = firstChild
while (child != null) {
if (!child.isInSingleLine()) return false
child = child.nextSibling
}
return true
}
//TODO: check for variables that are definitely assigned in constructors
fun PsiElement.getContainingMethod(): PsiMethod? {
var context = context
while (context != null) {
val _context = context
if (_context is PsiMethod) return _context
context = _context.context
}
return null
}
fun PsiElement.getContainingClass(): PsiClass? {
var context = context
while (context != null) {
val _context = context
if (_context is PsiClass) return _context
if (_context is PsiMember) return _context.containingClass
context = _context.context
}
return null
}
fun PsiElement.getContainingConstructor(): PsiMethod? {
val method = getContainingMethod()
return if (method?.isConstructor == true) method else null
}
fun PsiMember.isConstructor(): Boolean = this is PsiMethod && this.isConstructor
fun PsiModifierListOwner.accessModifier(): String = when {
hasModifierProperty(PsiModifier.PUBLIC) -> PsiModifier.PUBLIC
hasModifierProperty(PsiModifier.PRIVATE) -> PsiModifier.PRIVATE
hasModifierProperty(PsiModifier.PROTECTED) -> PsiModifier.PROTECTED
else -> PsiModifier.PACKAGE_LOCAL
}
fun PsiMethod.isMainMethod(): Boolean = PsiMethodUtil.isMainMethod(this)
fun PsiReferenceExpression.dot(): PsiElement? = node.findChildByType(JavaTokenType.DOT)?.psi
fun PsiExpressionList.lPar(): PsiElement? = node.findChildByType(JavaTokenType.LPARENTH)?.psi
fun PsiExpressionList.rPar(): PsiElement? = node.findChildByType(JavaTokenType.RPARENTH)?.psi
fun PsiMember.isImported(file: PsiJavaFile): Boolean {
return if (this is PsiClass) {
val fqName = qualifiedName
val index = fqName?.lastIndexOf('.') ?: -1
val parentName = if (index >= 0) fqName!!.substring(0, index) else null
file.importList?.allImportStatements?.any {
it.importReference?.qualifiedName == (if (it.isOnDemand) parentName else fqName)
} ?: false
}
else {
containingClass != null && file.importList?.importStaticStatements?.any {
it.resolveTargetClass() == containingClass && (it.isOnDemand || it.referenceName == name)
} ?: false
}
}
fun PsiExpression.isNullLiteral() = this is PsiLiteralExpression && type == PsiType.NULL
// TODO: set origin for facade classes in library
fun isFacadeClassFromLibrary(element: PsiElement?) = element is KtLightClass && element.kotlinOrigin == null
fun Converter.convertToKotlinAnalog(classQualifiedName: String?, mutability: Mutability): String? {
if (classQualifiedName == null) return null
return (if (mutability.isMutable(settings)) toKotlinMutableTypesMap[classQualifiedName] else null)
?: toKotlinTypesMap[classQualifiedName]
}
fun Converter.convertToKotlinAnalogIdentifier(classQualifiedName: String?, mutability: Mutability): Identifier? {
val kotlinClassName = convertToKotlinAnalog(classQualifiedName, mutability) ?: return null
return Identifier.withNoPrototype(kotlinClassName.substringAfterLast('.'))
}
val toKotlinTypesMap: Map<String, String> = mapOf(
CommonClassNames.JAVA_LANG_OBJECT to StandardNames.FqNames.any.asString(),
CommonClassNames.JAVA_LANG_BYTE to StandardNames.FqNames._byte.asString(),
CommonClassNames.JAVA_LANG_CHARACTER to StandardNames.FqNames._char.asString(),
CommonClassNames.JAVA_LANG_DOUBLE to StandardNames.FqNames._double.asString(),
CommonClassNames.JAVA_LANG_FLOAT to StandardNames.FqNames._float.asString(),
CommonClassNames.JAVA_LANG_INTEGER to StandardNames.FqNames._int.asString(),
CommonClassNames.JAVA_LANG_LONG to StandardNames.FqNames._long.asString(),
CommonClassNames.JAVA_LANG_SHORT to StandardNames.FqNames._short.asString(),
CommonClassNames.JAVA_LANG_BOOLEAN to StandardNames.FqNames._boolean.asString(),
CommonClassNames.JAVA_LANG_ITERABLE to StandardNames.FqNames.iterable.asString(),
CommonClassNames.JAVA_UTIL_ITERATOR to StandardNames.FqNames.iterator.asString(),
CommonClassNames.JAVA_UTIL_LIST to StandardNames.FqNames.list.asString(),
CommonClassNames.JAVA_UTIL_COLLECTION to StandardNames.FqNames.collection.asString(),
CommonClassNames.JAVA_UTIL_SET to StandardNames.FqNames.set.asString(),
CommonClassNames.JAVA_UTIL_MAP to StandardNames.FqNames.map.asString(),
CommonClassNames.JAVA_UTIL_MAP_ENTRY to StandardNames.FqNames.mapEntry.asString(),
java.util.ListIterator::class.java.canonicalName to StandardNames.FqNames.listIterator.asString()
)
val toKotlinMutableTypesMap: Map<String, String> = mapOf(
CommonClassNames.JAVA_UTIL_ITERATOR to StandardNames.FqNames.mutableIterator.asString(),
CommonClassNames.JAVA_UTIL_LIST to StandardNames.FqNames.mutableList.asString(),
CommonClassNames.JAVA_UTIL_COLLECTION to StandardNames.FqNames.mutableCollection.asString(),
CommonClassNames.JAVA_UTIL_SET to StandardNames.FqNames.mutableSet.asString(),
CommonClassNames.JAVA_UTIL_MAP to StandardNames.FqNames.mutableMap.asString(),
CommonClassNames.JAVA_UTIL_MAP_ENTRY to StandardNames.FqNames.mutableMapEntry.asString(),
java.util.ListIterator::class.java.canonicalName to StandardNames.FqNames.mutableListIterator.asString()
)
| apache-2.0 | 4397ba13b61bb2c8eaf0a42e6078f4e5 | 45.825 | 158 | 0.743727 | 4.768937 | false | false | false | false |
allotria/intellij-community | platform/lang-impl/src/com/intellij/find/actions/FindSelectionInPathAction.kt | 3 | 681 | // 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.find.actions
import com.intellij.ide.lightEdit.LightEdit
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.CommonDataKeys
class FindSelectionInPathAction : FindInPathAction() {
override fun update(e: AnActionEvent) {
val project = e.project
val editor = e.getData(CommonDataKeys.EDITOR)
if (project == null || LightEdit.owns(project) || editor == null || !editor.selectionModel.hasSelection()) {
e.presentation.isEnabledAndVisible = false
}
}
}
| apache-2.0 | 47b8ef2d54d6c18ffa72486cc67072e2 | 41.5625 | 140 | 0.760646 | 4.229814 | false | false | false | false |
androidx/androidx | tv/tv-foundation/src/androidTest/java/androidx/tv/foundation/lazy/list/LazyListSlotsReuseTest.kt | 3 | 16305 | /*
* 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.tv.foundation.lazy.list
import androidx.compose.foundation.focusable
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.width
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.layout.layout
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.test.assertIsDisplayed
import androidx.compose.ui.test.assertIsNotDisplayed
import androidx.compose.ui.test.junit4.createComposeRule
import androidx.compose.ui.test.onNodeWithTag
import androidx.compose.ui.unit.IntOffset
import androidx.compose.ui.unit.dp
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.filters.LargeTest
import androidx.tv.foundation.PivotOffsets
import com.google.common.truth.Truth
import kotlinx.coroutines.runBlocking
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
@LargeTest
@RunWith(AndroidJUnit4::class)
class LazyListSlotsReuseTest {
@get:Rule
val rule = createComposeRule()
val itemsSizePx = 30f
val itemsSizeDp = with(rule.density) { itemsSizePx.toDp() }
@Test
fun scroll1ItemScrolledOffItemIsKeptForReuse() {
lateinit var state: TvLazyListState
rule.setContent {
state = rememberTvLazyListState()
TvLazyColumn(
Modifier.height(itemsSizeDp * 1.5f),
state,
pivotOffsets = PivotOffsets(parentFraction = 0f)
) {
items(100) {
Box(
Modifier.height(itemsSizeDp).fillParentMaxWidth().testTag("$it")
.focusable())
}
}
}
rule.onNodeWithTag("0")
.assertIsDisplayed()
rule.runOnIdle {
runBlocking {
state.scrollToItem(1)
}
}
rule.onNodeWithTag("0")
.assertExists()
.assertIsNotDisplayed()
rule.onNodeWithTag("1")
.assertIsDisplayed()
}
@Test
fun scroll2ItemsScrolledOffItemsAreKeptForReuse() {
lateinit var state: TvLazyListState
rule.setContent {
state = rememberTvLazyListState()
TvLazyColumn(
Modifier.height(itemsSizeDp * 1.5f),
state,
pivotOffsets = PivotOffsets(parentFraction = 0f)
) {
items(100) {
Box(
Modifier.height(itemsSizeDp).fillParentMaxWidth().testTag("$it")
.focusable())
}
}
}
rule.onNodeWithTag("0")
.assertIsDisplayed()
rule.onNodeWithTag("1")
.assertIsDisplayed()
rule.runOnIdle {
runBlocking {
state.scrollToItem(2)
}
}
rule.onNodeWithTag("0")
.assertExists()
.assertIsNotDisplayed()
rule.onNodeWithTag("1")
.assertExists()
.assertIsNotDisplayed()
rule.onNodeWithTag("2")
.assertIsDisplayed()
}
@Test
fun checkMaxItemsKeptForReuse() {
lateinit var state: TvLazyListState
rule.setContent {
state = rememberTvLazyListState()
TvLazyColumn(
Modifier.height(itemsSizeDp * (DefaultMaxItemsToRetain + 0.5f)),
state,
pivotOffsets = PivotOffsets(parentFraction = 0f)
) {
items(100) {
Box(
Modifier.height(itemsSizeDp).fillParentMaxWidth().testTag("$it")
.focusable())
}
}
}
rule.runOnIdle {
runBlocking {
state.scrollToItem(DefaultMaxItemsToRetain + 1)
}
}
repeat(DefaultMaxItemsToRetain) {
rule.onNodeWithTag("$it")
.assertExists()
.assertIsNotDisplayed()
}
rule.onNodeWithTag("$DefaultMaxItemsToRetain")
.assertDoesNotExist()
rule.onNodeWithTag("${DefaultMaxItemsToRetain + 1}")
.assertIsDisplayed()
}
@Test
fun scroll3Items2OfScrolledOffItemsAreKeptForReuse() {
lateinit var state: TvLazyListState
rule.setContent {
state = rememberTvLazyListState()
TvLazyColumn(
Modifier.height(itemsSizeDp * 1.5f),
state,
pivotOffsets = PivotOffsets(parentFraction = 0f)
) {
items(100) {
Box(
Modifier.height(itemsSizeDp).fillParentMaxWidth().testTag("$it")
.focusable())
}
}
}
rule.onNodeWithTag("0")
.assertIsDisplayed()
rule.onNodeWithTag("1")
.assertIsDisplayed()
rule.runOnIdle {
runBlocking {
// after this step 0 and 1 are in reusable buffer
state.scrollToItem(2)
// this step requires one item and will take the last item from the buffer - item
// 1 plus will put 2 in the buffer. so expected buffer is items 2 and 0
state.scrollToItem(3)
}
}
// recycled
rule.onNodeWithTag("1")
.assertDoesNotExist()
// in buffer
rule.onNodeWithTag("0")
.assertExists()
.assertIsNotDisplayed()
rule.onNodeWithTag("2")
.assertExists()
.assertIsNotDisplayed()
// visible
rule.onNodeWithTag("3")
.assertIsDisplayed()
rule.onNodeWithTag("4")
.assertIsDisplayed()
}
@Test
fun doMultipleScrollsOneByOne() {
lateinit var state: TvLazyListState
rule.setContent {
state = rememberTvLazyListState()
TvLazyColumn(
Modifier.height(itemsSizeDp * 1.5f),
state,
pivotOffsets = PivotOffsets(parentFraction = 0f)
) {
items(100) {
Box(
Modifier.height(itemsSizeDp).fillParentMaxWidth().testTag("$it")
.focusable())
}
}
}
rule.runOnIdle {
runBlocking {
state.scrollToItem(1) // buffer is [0]
state.scrollToItem(2) // 0 used, buffer is [1]
state.scrollToItem(3) // 1 used, buffer is [2]
state.scrollToItem(4) // 2 used, buffer is [3]
}
}
// recycled
rule.onNodeWithTag("0")
.assertDoesNotExist()
rule.onNodeWithTag("1")
.assertDoesNotExist()
rule.onNodeWithTag("2")
.assertDoesNotExist()
// in buffer
rule.onNodeWithTag("3")
.assertExists()
.assertIsNotDisplayed()
// visible
rule.onNodeWithTag("4")
.assertIsDisplayed()
rule.onNodeWithTag("5")
.assertIsDisplayed()
}
@Test
fun scrollBackwardOnce() {
lateinit var state: TvLazyListState
rule.setContent {
state = rememberTvLazyListState(10)
TvLazyColumn(
Modifier.height(itemsSizeDp * 1.5f),
state,
pivotOffsets = PivotOffsets(parentFraction = 0f)
) {
items(100) {
Box(
Modifier.height(itemsSizeDp).fillParentMaxWidth().testTag("$it")
.focusable())
}
}
}
rule.runOnIdle {
runBlocking {
state.scrollToItem(8) // buffer is [10, 11]
}
}
// in buffer
rule.onNodeWithTag("10")
.assertExists()
.assertIsNotDisplayed()
rule.onNodeWithTag("11")
.assertExists()
.assertIsNotDisplayed()
// visible
rule.onNodeWithTag("8")
.assertIsDisplayed()
rule.onNodeWithTag("9")
.assertIsDisplayed()
}
@Test
fun scrollBackwardOneByOne() {
lateinit var state: TvLazyListState
rule.setContent {
state = rememberTvLazyListState(10)
TvLazyColumn(
Modifier.height(itemsSizeDp * 1.5f),
state,
pivotOffsets = PivotOffsets(parentFraction = 0f)
) {
items(100) {
Box(
Modifier.height(itemsSizeDp).fillParentMaxWidth().testTag("$it")
.focusable())
}
}
}
rule.runOnIdle {
runBlocking {
state.scrollToItem(9) // buffer is [11]
state.scrollToItem(7) // 11 reused, buffer is [9]
state.scrollToItem(6) // 9 reused, buffer is [8]
}
}
// in buffer
rule.onNodeWithTag("8")
.assertExists()
.assertIsNotDisplayed()
// visible
rule.onNodeWithTag("6")
.assertIsDisplayed()
rule.onNodeWithTag("7")
.assertIsDisplayed()
}
@Test
fun scrollingBackReusesTheSameSlot() {
lateinit var state: TvLazyListState
var counter0 = 0
var counter1 = 0
val measureCountModifier0 = Modifier.layout { measurable, constraints ->
counter0++
val placeable = measurable.measure(constraints)
layout(placeable.width, placeable.height) {
placeable.place(IntOffset.Zero)
}
}
val measureCountModifier1 = Modifier.layout { measurable, constraints ->
counter1++
val placeable = measurable.measure(constraints)
layout(placeable.width, placeable.height) {
placeable.place(IntOffset.Zero)
}
}
rule.setContent {
state = rememberTvLazyListState()
TvLazyColumn(
Modifier.height(itemsSizeDp * 1.5f),
state,
pivotOffsets = PivotOffsets(parentFraction = 0f)
) {
items(100) {
val modifier = when (it) {
0 -> measureCountModifier0
1 -> measureCountModifier1
else -> Modifier
}
Spacer(
Modifier
.height(itemsSizeDp)
.fillParentMaxWidth()
.testTag("$it")
.then(modifier)
)
}
}
}
rule.runOnIdle {
runBlocking {
state.scrollToItem(2) // buffer is [0, 1]
state.scrollToItem(0) // scrolled back, 0 and 1 are reused back. buffer: [2, 3]
}
}
rule.runOnIdle {
Truth.assertWithMessage("Item 0 measured $counter0 times, expected 1.")
.that(counter0).isEqualTo(1)
Truth.assertWithMessage("Item 1 measured $counter1 times, expected 1.")
.that(counter1).isEqualTo(1)
}
rule.onNodeWithTag("0")
.assertIsDisplayed()
rule.onNodeWithTag("1")
.assertIsDisplayed()
rule.onNodeWithTag("2")
.assertExists()
.assertIsNotDisplayed()
rule.onNodeWithTag("3")
.assertExists()
.assertIsNotDisplayed()
}
@Test
fun differentContentTypes() {
lateinit var state: TvLazyListState
val visibleItemsCount = (DefaultMaxItemsToRetain + 1) * 2
val startOfType1 = DefaultMaxItemsToRetain + 1
rule.setContent {
state = rememberTvLazyListState()
TvLazyColumn(
Modifier.height(itemsSizeDp * (visibleItemsCount - 0.5f)),
state,
pivotOffsets = PivotOffsets(parentFraction = 0f)
) {
items(
100,
contentType = { if (it >= startOfType1) 1 else 0 }
) {
Box(
Modifier.height(itemsSizeDp).fillMaxWidth().testTag("$it").focusable())
}
}
}
for (i in 0 until visibleItemsCount) {
rule.onNodeWithTag("$i")
.assertIsDisplayed()
}
rule.runOnIdle {
runBlocking {
state.scrollToItem(visibleItemsCount)
}
}
rule.onNodeWithTag("$visibleItemsCount")
.assertIsDisplayed()
// [DefaultMaxItemsToRetain] items of type 0 are left for reuse
for (i in 0 until DefaultMaxItemsToRetain) {
rule.onNodeWithTag("$i")
.assertExists()
.assertIsNotDisplayed()
}
rule.onNodeWithTag("$DefaultMaxItemsToRetain")
.assertDoesNotExist()
// and 7 items of type 1
for (i in startOfType1 until startOfType1 + DefaultMaxItemsToRetain) {
rule.onNodeWithTag("$i")
.assertExists()
.assertIsNotDisplayed()
}
rule.onNodeWithTag("${startOfType1 + DefaultMaxItemsToRetain}")
.assertDoesNotExist()
}
@Test
fun differentTypesFromDifferentItemCalls() {
lateinit var state: TvLazyListState
rule.setContent {
state = rememberTvLazyListState()
TvLazyColumn(
Modifier.height(itemsSizeDp * 2.5f),
state,
pivotOffsets = PivotOffsets(parentFraction = 0f)
) {
val content = @Composable { tag: String ->
Spacer(Modifier.height(itemsSizeDp).width(10.dp).testTag(tag).focusable())
}
item(contentType = "not-to-reuse-0") {
content("0")
}
item(contentType = "reuse") {
content("1")
}
items(
List(100) { it + 2 },
contentType = { if (it == 10) "reuse" else "not-to-reuse-$it" }) {
content("$it")
}
}
}
rule.runOnIdle {
runBlocking {
state.scrollToItem(2)
// now items 0 and 1 are put into reusables
}
}
rule.onNodeWithTag("0")
.assertExists()
.assertIsNotDisplayed()
rule.onNodeWithTag("1")
.assertExists()
.assertIsNotDisplayed()
rule.runOnIdle {
runBlocking {
state.scrollToItem(9)
// item 10 should reuse slot 1
}
}
rule.onNodeWithTag("0")
.assertExists()
.assertIsNotDisplayed()
rule.onNodeWithTag("1")
.assertDoesNotExist()
rule.onNodeWithTag("9")
.assertIsDisplayed()
rule.onNodeWithTag("10")
.assertIsDisplayed()
rule.onNodeWithTag("11")
.assertIsDisplayed()
}
}
private val DefaultMaxItemsToRetain = 7
| apache-2.0 | 56a3a511baf896b30785b69bfbf9972d | 30.057143 | 97 | 0.521067 | 5.409754 | false | true | false | false |
androidx/androidx | camera/camera-camera2-pipe/src/main/java/androidx/camera/camera2/pipe/compat/Camera2DeviceCache.kt | 3 | 3577 | /*
* 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.camera.camera2.pipe.compat
import android.hardware.camera2.CameraAccessException
import android.hardware.camera2.CameraManager
import androidx.annotation.GuardedBy
import androidx.annotation.RequiresApi
import androidx.camera.camera2.pipe.CameraId
import androidx.camera.camera2.pipe.core.Debug
import androidx.camera.camera2.pipe.core.Log
import androidx.camera.camera2.pipe.core.Threads
import javax.inject.Inject
import javax.inject.Provider
import javax.inject.Singleton
import kotlinx.coroutines.withContext
@RequiresApi(21) // TODO(b/200306659): Remove and replace with annotation on package-info.java
@Singleton
internal class Camera2DeviceCache @Inject constructor(
private val cameraManager: Provider<CameraManager>,
private val threads: Threads,
) {
private val lock = Any()
@GuardedBy("lock")
private var openableCameras: List<CameraId>? = null
suspend fun getCameras(): List<CameraId> {
val cameras = synchronized(lock) { openableCameras }
if (cameras?.isNotEmpty() == true) {
return cameras
}
// Suspend and query the list of Cameras on the ioDispatcher
return withContext(threads.backgroundDispatcher) {
Debug.trace("readCameraIds") {
val cameraIds = readCameraIdList()
if (cameraIds.isNotEmpty()) {
synchronized(lock) {
openableCameras = cameraIds
}
return@trace cameraIds
}
// TODO(b/159052778): Find a way to make this poll for the camera list and to
// suspend if the value is not yet available. It will be important to detect and
// differentiate between devices that should have cameras, but don't, vs devices
// that do not physically have cameras. It may also be worthwhile to re-query if
// looking for external cameras, since they can be attached and/or detached.
return@trace listOf<CameraId>()
}
}
}
private fun readCameraIdList(): List<CameraId> {
val cameras = synchronized(lock) { openableCameras }
if (cameras?.isNotEmpty() == true) {
return cameras
}
val cameraManager = cameraManager.get()
val cameraIdArray = try {
// WARNING: This method can, at times, return an empty list of cameras on devices that
// will normally return a valid list of cameras (b/159052778)
cameraManager.cameraIdList
} catch (e: CameraAccessException) {
Log.warn(e) { "Failed to query CameraManager#getCameraIdList!" }
null
}
if (cameraIdArray?.isEmpty() == true) {
Log.warn { "Failed to query CameraManager#getCameraIdList: No values returned." }
}
return cameraIdArray?.map { CameraId(it) } ?: listOf()
}
} | apache-2.0 | 5cdc8842d84042e3964fe76b17e402e1 | 37.473118 | 98 | 0.660889 | 4.681937 | false | false | false | false |
djkovrik/YapTalker | data/src/main/java/com/sedsoftware/yaptalker/data/mapper/SettingsPageMapper.kt | 1 | 1069 | package com.sedsoftware.yaptalker.data.mapper
import com.sedsoftware.yaptalker.data.parsed.SitePreferencesPageParsed
import com.sedsoftware.yaptalker.domain.entity.base.SitePreferences
import io.reactivex.functions.Function
import javax.inject.Inject
class SettingsPageMapper @Inject constructor() : Function<SitePreferencesPageParsed, SitePreferences> {
companion object {
private const val MESSAGES_PER_PAGE_DEFAULT = 25
private const val TOPICS_PER_PAGE_DEFAULT = 30
}
override fun apply(from: SitePreferencesPageParsed): SitePreferences {
val messages = from.messagesPerTopicPage.toInt()
val topics = from.topicsPerForumPage.toInt()
val mappedMessages = if (messages == -1)
MESSAGES_PER_PAGE_DEFAULT
else
messages
val mappedTopics = if (topics == -1)
TOPICS_PER_PAGE_DEFAULT
else
topics
return SitePreferences(
messagesPerTopicPage = mappedMessages,
topicsPerForumPage = mappedTopics
)
}
}
| apache-2.0 | d5b7b3b87b00a9aad81d066a0d1a9109 | 30.441176 | 103 | 0.689429 | 4.587983 | false | false | false | false |
GunoH/intellij-community | plugins/maven/src/main/java/org/jetbrains/idea/maven/statistics/MavenImportCollector.kt | 2 | 4744 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.idea.maven.statistics
import com.intellij.internal.statistic.eventLog.EventLogGroup
import com.intellij.internal.statistic.eventLog.events.EventFields
import com.intellij.internal.statistic.service.fus.collectors.CounterUsagesCollector
import org.jetbrains.annotations.ApiStatus
@ApiStatus.Internal
class MavenImportCollector : CounterUsagesCollector() {
companion object {
val GROUP = EventLogGroup("maven.import", 8)
@JvmField
val HAS_USER_ADDED_LIBRARY_DEP = GROUP.registerEvent("hasUserAddedLibraryDependency")
@JvmField
val HAS_USER_ADDED_MODULE_DEP = GROUP.registerEvent("hasUserAddedModuleDependency")
@JvmField
val HAS_USER_MODIFIED_IMPORTED_LIBRARY = GROUP.registerEvent("hasUserModifiedImportedLibrary")
@JvmField
val NUMBER_OF_MODULES = EventFields.RoundedInt("number_of_modules")
// >>> Legacy import phases
@JvmField
val LEGACY_IMPORT = GROUP.registerIdeActivity("legacy_import",
finishEventAdditionalFields = arrayOf(NUMBER_OF_MODULES))
@JvmField
val LEGACY_CREATE_MODULES_PHASE = GROUP.registerIdeActivity("create_modules", parentActivity = LEGACY_IMPORT)
@JvmField
val LEGACY_DELETE_OBSOLETE_PHASE = GROUP.registerIdeActivity("delete_obsolete", parentActivity = LEGACY_IMPORT)
@JvmField
val LEGACY_IMPORTERS_PHASE = GROUP.registerIdeActivity("importers", parentActivity = LEGACY_IMPORT)
// <<< Legacy import phases
@JvmField
val ACTIVITY_ID = EventFields.IdeActivityIdField
// >>> Workspace import phases
@JvmField
val WORKSPACE_IMPORT = GROUP.registerIdeActivity("workspace_import",
finishEventAdditionalFields = arrayOf(NUMBER_OF_MODULES))
@JvmField
val WORKSPACE_FOLDERS_UPDATE = GROUP.registerIdeActivity("workspace_folders_update",
finishEventAdditionalFields = arrayOf(NUMBER_OF_MODULES))
@JvmField
val WORKSPACE_POPULATE_PHASE = GROUP.registerIdeActivity("populate", parentActivity = WORKSPACE_IMPORT)
@JvmField
val DURATION_BACKGROUND_MS = EventFields.Long("duration_in_background_ms")
@JvmField
val DURATION_WRITE_ACTION_MS = EventFields.Long("duration_in_write_action_ms")
@JvmField
val DURATION_OF_WORKSPACE_UPDATE_CALL_MS = EventFields.Long("duration_of_workspace_update_call_ms")
@JvmField
val ATTEMPTS = EventFields.Int("attempts")
@JvmField
val WORKSPACE_COMMIT_STATS = GROUP.registerVarargEvent("workspace_commit", ACTIVITY_ID, DURATION_BACKGROUND_MS,
DURATION_WRITE_ACTION_MS, DURATION_OF_WORKSPACE_UPDATE_CALL_MS, ATTEMPTS)
@JvmField
val WORKSPACE_COMMIT_PHASE = GROUP.registerIdeActivity("commit", parentActivity = WORKSPACE_IMPORT)
@JvmField
val WORKSPACE_LEGACY_IMPORTERS_PHASE = GROUP.registerIdeActivity("legacy_importers", parentActivity = WORKSPACE_IMPORT)
// <<< Workspace import phases
@JvmField
val TOTAL_DURATION_MS = EventFields.Long("total_duration_ms")
@JvmField
val COLLECT_FOLDERS_DURATION_MS = EventFields.Long("collect_folders_duration_ms")
@JvmField
val CONFIG_MODULES_DURATION_MS = EventFields.Long("config_modules_duration_ms")
@JvmField
val BEFORE_APPLY_DURATION_MS = EventFields.Long("before_apply_duration_ms")
@JvmField
val AFTER_APPLY_DURATION_MS = EventFields.Long("after_apply_duration_ms")
@JvmField
val IMPORTER_CLASS = EventFields.Class("importer_class")
@JvmField
val IMPORTER_RUN = GROUP.registerVarargEvent("importer_run", ACTIVITY_ID, IMPORTER_CLASS, NUMBER_OF_MODULES, TOTAL_DURATION_MS)
@JvmField
val CONFIGURATOR_CLASS = EventFields.Class("configurator_class")
@JvmField
val CONFIGURATOR_RUN = GROUP.registerVarargEvent("workspace_import.configurator_run",
ACTIVITY_ID,
CONFIGURATOR_CLASS,
NUMBER_OF_MODULES,
TOTAL_DURATION_MS,
COLLECT_FOLDERS_DURATION_MS,
CONFIG_MODULES_DURATION_MS,
BEFORE_APPLY_DURATION_MS,
AFTER_APPLY_DURATION_MS)
}
override fun getGroup(): EventLogGroup {
return GROUP
}
} | apache-2.0 | 1e09dd83836824c1f085f14763541bab | 39.211864 | 132 | 0.651981 | 4.993684 | false | true | false | false |
GunoH/intellij-community | plugins/github/src/org/jetbrains/plugins/github/GHOpenInBrowserActionGroup.kt | 2 | 11513 | // 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.github
import com.intellij.icons.AllIcons
import com.intellij.ide.BrowserUtil
import com.intellij.openapi.actionSystem.*
import com.intellij.openapi.actionSystem.impl.ActionButton
import com.intellij.openapi.components.service
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.progress.Task
import com.intellij.openapi.project.DumbAware
import com.intellij.openapi.project.DumbAwareAction
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.NlsSafe
import com.intellij.openapi.util.Ref
import com.intellij.openapi.util.text.StringUtil
import com.intellij.openapi.vcs.VcsDataKeys
import com.intellij.openapi.vcs.changes.Change
import com.intellij.openapi.vcs.changes.ChangeListManager
import com.intellij.openapi.vfs.VfsUtilCore
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.util.containers.ContainerUtil
import com.intellij.util.io.URLUtil
import com.intellij.vcs.log.VcsLogDataKeys
import com.intellij.vcsUtil.VcsUtil
import git4idea.GitFileRevision
import git4idea.GitRevisionNumber
import git4idea.GitUtil
import git4idea.history.GitHistoryUtils
import git4idea.remote.hosting.findKnownRepositories
import git4idea.repo.GitRepository
import org.jetbrains.annotations.Nls
import org.jetbrains.plugins.github.api.GHRepositoryCoordinates
import org.jetbrains.plugins.github.api.data.pullrequest.GHPullRequestShort
import org.jetbrains.plugins.github.i18n.GithubBundle
import org.jetbrains.plugins.github.pullrequest.action.GHPRActionKeys
import org.jetbrains.plugins.github.util.GHHostedRepositoriesManager
import org.jetbrains.plugins.github.util.GithubNotificationIdsHolder
import org.jetbrains.plugins.github.util.GithubNotifications
import org.jetbrains.plugins.github.util.GithubUtil
open class GHOpenInBrowserActionGroup
: ActionGroup(GithubBundle.messagePointer("open.on.github.action"),
GithubBundle.messagePointer("open.on.github.action.description"),
AllIcons.Vcs.Vendors.Github), DumbAware {
override fun getActionUpdateThread(): ActionUpdateThread = ActionUpdateThread.BGT
override fun update(e: AnActionEvent) {
val data = getData(e.dataContext)
e.presentation.isEnabledAndVisible = !data.isNullOrEmpty()
e.presentation.isPerformGroup = data?.size == 1
e.presentation.putClientProperty(ActionButton.HIDE_DROPDOWN_ICON, e.presentation.isPerformGroup);
e.presentation.isPopupGroup = true
e.presentation.isDisableGroupIfEmpty = false
}
override fun getChildren(e: AnActionEvent?): Array<AnAction> {
e ?: return emptyArray()
val data = getData(e.dataContext) ?: return emptyArray()
if (data.size <= 1) return emptyArray()
return data.map { GithubOpenInBrowserAction(it) }.toTypedArray()
}
override fun actionPerformed(e: AnActionEvent) {
getData(e.dataContext)?.let { GithubOpenInBrowserAction(it.first()) }?.actionPerformed(e)
}
protected open fun getData(dataContext: DataContext): List<Data>? {
val project = dataContext.getData(CommonDataKeys.PROJECT) ?: return null
return getDataFromPullRequest(project, dataContext)
?: getDataFromHistory(project, dataContext)
?: getDataFromLog(project, dataContext)
?: getDataFromVirtualFile(project, dataContext)
}
private fun getDataFromPullRequest(project: Project, dataContext: DataContext): List<Data>? {
val pullRequest: GHPullRequestShort =
dataContext.getData(GHPRActionKeys.SELECTED_PULL_REQUEST)
?: dataContext.getData(GHPRActionKeys.PULL_REQUEST_DATA_PROVIDER)?.detailsData?.loadedDetails
?: return null
return listOf(Data.URL(project, pullRequest.url))
}
private fun getDataFromHistory(project: Project, dataContext: DataContext): List<Data>? {
val fileRevision = dataContext.getData(VcsDataKeys.VCS_FILE_REVISION) ?: return null
if (fileRevision !is GitFileRevision) return null
val repository = GitUtil.getRepositoryManager(project).getRepositoryForFileQuick(fileRevision.path)
if (repository == null) return null
val accessibleRepositories = project.service<GHHostedRepositoriesManager>().findKnownRepositories(repository)
if (accessibleRepositories.isEmpty()) return null
return accessibleRepositories.map { Data.Revision(project, it.repository, fileRevision.revisionNumber.asString()) }
}
private fun getDataFromLog(project: Project, dataContext: DataContext): List<Data>? {
val selection = dataContext.getData(VcsLogDataKeys.VCS_LOG_COMMIT_SELECTION) ?: return null
val selectedCommits = selection.commits
if (selectedCommits.size != 1) return null
val commit = ContainerUtil.getFirstItem(selectedCommits) ?: return null
val repository = GitUtil.getRepositoryManager(project).getRepositoryForRootQuick(commit.root)
if (repository == null) return null
val accessibleRepositories = project.service<GHHostedRepositoriesManager>().findKnownRepositories(repository)
if (accessibleRepositories.isEmpty()) return null
return accessibleRepositories.map { Data.Revision(project, it.repository, commit.hash.asString()) }
}
private fun getDataFromVirtualFile(project: Project, dataContext: DataContext): List<Data>? {
val virtualFile = dataContext.getData(CommonDataKeys.VIRTUAL_FILE) ?: return null
val repository = GitUtil.getRepositoryManager(project).getRepositoryForFileQuick(virtualFile)
if (repository == null) return null
val accessibleRepositories = project.service<GHHostedRepositoriesManager>().findKnownRepositories(repository)
if (accessibleRepositories.isEmpty()) return null
val changeListManager = ChangeListManager.getInstance(project)
if (changeListManager.isUnversioned(virtualFile)) return null
val change = changeListManager.getChange(virtualFile)
return if (change != null && change.type == Change.Type.NEW) null
else accessibleRepositories.map { Data.File(project, it.repository, repository.root, virtualFile) }
}
protected sealed class Data(val project: Project) {
@Nls
abstract fun getName(): String
class File(project: Project,
val repository: GHRepositoryCoordinates,
val gitRepoRoot: VirtualFile,
val virtualFile: VirtualFile) : Data(project) {
override fun getName(): String {
@NlsSafe
val formatted = repository.toString().replace('_', ' ')
return formatted
}
}
class Revision(project: Project, val repository: GHRepositoryCoordinates, val revisionHash: String) : Data(project) {
override fun getName(): String {
@NlsSafe
val formatted = repository.toString().replace('_', ' ')
return formatted
}
}
class URL(project: Project, @NlsSafe val htmlUrl: String) : Data(project) {
override fun getName() = htmlUrl
}
}
private companion object {
class GithubOpenInBrowserAction(val data: Data)
: DumbAwareAction({ data.getName() }) {
override fun getActionUpdateThread(): ActionUpdateThread = ActionUpdateThread.BGT
override fun actionPerformed(e: AnActionEvent) {
when (data) {
is Data.Revision -> openCommitInBrowser(data.repository, data.revisionHash)
is Data.File -> openFileInBrowser(data.project, data.gitRepoRoot, data.repository, data.virtualFile,
e.getData(CommonDataKeys.EDITOR))
is Data.URL -> BrowserUtil.browse(data.htmlUrl)
}
}
private fun openCommitInBrowser(path: GHRepositoryCoordinates, revisionHash: String) {
BrowserUtil.browse("${path.toUrl()}/commit/$revisionHash")
}
private fun openFileInBrowser(project: Project,
repositoryRoot: VirtualFile,
path: GHRepositoryCoordinates,
virtualFile: VirtualFile,
editor: Editor?) {
val relativePath = VfsUtilCore.getRelativePath(virtualFile, repositoryRoot)
if (relativePath == null) {
GithubNotifications.showError(project, GithubNotificationIdsHolder.OPEN_IN_BROWSER_FILE_IS_NOT_UNDER_REPO,
GithubBundle.message("cannot.open.in.browser"),
GithubBundle.message("open.on.github.file.is.not.under.repository"),
"Root: " + repositoryRoot.presentableUrl + ", file: " + virtualFile.presentableUrl)
return
}
val hash = getCurrentFileRevisionHash(project, virtualFile)
if (hash == null) {
GithubNotifications.showError(project,
GithubNotificationIdsHolder.OPEN_IN_BROWSER_CANNOT_GET_LAST_REVISION,
GithubBundle.message("cannot.open.in.browser"),
GithubBundle.message("cannot.get.last.revision"))
return
}
val githubUrl = GHPathUtil.makeUrlToOpen(editor, relativePath, hash, path)
BrowserUtil.browse(githubUrl)
}
private fun getCurrentFileRevisionHash(project: Project, file: VirtualFile): String? {
val ref = Ref<GitRevisionNumber>()
object : Task.Modal(project, GithubBundle.message("open.on.github.getting.last.revision"), true) {
override fun run(indicator: ProgressIndicator) {
ref.set(GitHistoryUtils.getCurrentRevision(project, VcsUtil.getFilePath(file), "HEAD") as GitRevisionNumber?)
}
override fun onThrowable(error: Throwable) {
GithubUtil.LOG.warn(error)
}
}.queue()
return if (ref.isNull) null else ref.get().rev
}
}
}
}
object GHPathUtil {
fun getFileURL(repository: GitRepository,
path: GHRepositoryCoordinates,
virtualFile: VirtualFile,
editor: Editor?): String? {
val relativePath = VfsUtilCore.getRelativePath(virtualFile, repository.root)
if (relativePath == null) {
return null
}
val hash = repository.currentRevision
if (hash == null) {
return null
}
return makeUrlToOpen(editor, relativePath, hash, path)
}
fun makeUrlToOpen(editor: Editor?, relativePath: String, branch: String, path: GHRepositoryCoordinates): String {
val builder = StringBuilder()
if (StringUtil.isEmptyOrSpaces(relativePath)) {
builder.append(path.toUrl()).append("/tree/").append(branch)
}
else {
builder.append(path.toUrl()).append("/blob/").append(branch).append('/').append(URLUtil.encodePath(relativePath))
}
if (editor != null && editor.document.lineCount >= 1) {
// lines are counted internally from 0, but from 1 on github
val selectionModel = editor.selectionModel
val begin = editor.document.getLineNumber(selectionModel.selectionStart) + 1
val selectionEnd = selectionModel.selectionEnd
var end = editor.document.getLineNumber(selectionEnd) + 1
if (editor.document.getLineStartOffset(end - 1) == selectionEnd) {
end -= 1
}
builder.append("#L").append(begin)
if (begin != end) {
builder.append("-L").append(end)
}
}
return builder.toString()
}
} | apache-2.0 | 682f1e2278a083d1df0feb682c146926 | 41.175824 | 123 | 0.707548 | 4.920085 | false | false | false | false |
GunoH/intellij-community | plugins/gradle/tooling-proxy/src/org/jetbrains/plugins/gradle/tooling/proxy/ProgressEventConverter.kt | 2 | 4380 | // Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.plugins.gradle.tooling.proxy
import org.gradle.tooling.Failure
import org.gradle.tooling.events.*
import org.gradle.tooling.events.task.*
import org.gradle.tooling.model.UnsupportedMethodException
import org.jetbrains.plugins.gradle.tooling.serialization.internal.adapter.events.*
import org.jetbrains.plugins.gradle.tooling.serialization.internal.adapter.events.task.*
import java.util.*
class ProgressEventConverter {
private val descriptorsMap = IdentityHashMap<OperationDescriptor, InternalOperationDescriptor>()
fun convert(progressEvent: ProgressEvent): ProgressEvent = when (progressEvent) {
is TaskStartEvent -> progressEvent.run {
InternalTaskStartEvent(eventTime, displayName, convert(descriptor) as InternalTaskOperationDescriptor)
}
is TaskFinishEvent -> progressEvent.run {
InternalTaskFinishEvent(eventTime, displayName, convert(descriptor) as InternalTaskOperationDescriptor, convert(result))
}
is StatusEvent -> progressEvent.run { InternalStatusEvent(eventTime, displayName, convert(descriptor), total, progress, unit) }
is StartEvent -> progressEvent.run { InternalStartEvent(eventTime, displayName, convert(descriptor)) }
is FinishEvent -> progressEvent.run { InternalFinishEvent(eventTime, displayName, convert(descriptor), convert(result)) }
else -> progressEvent
}
private fun convert(result: TaskOperationResult?): TaskOperationResult? {
when (result) {
null -> return null
is TaskSuccessResult -> return result.run {
InternalTaskSuccessResult(startTime, endTime, isUpToDate, isFromCache, taskExecutionDetails())
}
is TaskFailureResult -> return result.run {
InternalTaskFailureResult(startTime, endTime, failures?.map<Failure?, Failure?>(::convert), taskExecutionDetails())
}
is TaskSkippedResult -> return result.run { InternalTaskSkippedResult(startTime, endTime, skipMessage) }
else -> throw IllegalArgumentException("Unsupported task operation result ${result.javaClass}")
}
}
private fun convert(result: OperationResult?): OperationResult? {
when (result) {
null -> return null
is SuccessResult -> return result.run { InternalOperationSuccessResult(startTime, endTime) }
is FailureResult -> return result.run {
InternalOperationFailureResult(startTime, endTime, failures?.map<Failure?, Failure?>(::convert))
}
else -> throw IllegalArgumentException("Unsupported operation result ${result.javaClass}")
}
}
private fun TaskExecutionResult.taskExecutionDetails(): InternalTaskExecutionDetails? = try {
InternalTaskExecutionDetails.of(isIncremental, executionReasons)
}
catch (e: UnsupportedMethodException) {
InternalTaskExecutionDetails.unsupported()
}
private fun convert(failure: Failure?): InternalFailure? {
return failure?.run { InternalFailure(message, description, causes?.map<Failure?, InternalFailure?>(::convert)) }
}
private fun convert(operationDescriptor: OperationDescriptor?): InternalOperationDescriptor? {
if (operationDescriptor == null) return null
val id = if (operationDescriptor is org.gradle.tooling.internal.protocol.events.InternalOperationDescriptor) operationDescriptor.id.toString() else operationDescriptor.displayName
return descriptorsMap.getOrPut(operationDescriptor, {
when (operationDescriptor) {
is TaskOperationDescriptor -> operationDescriptor.run {
InternalTaskOperationDescriptor(
id, name, displayName, convert(parent), taskPath,
{ mutableSetOf<OperationDescriptor>().apply { dependencies.mapNotNullTo(this) { convert(it) } } },
{ convert(originPlugin) })
}
else -> operationDescriptor.run { InternalOperationDescriptor(id, name, displayName, convert(parent)) }
}
})
}
private fun convert(pluginIdentifier: PluginIdentifier?): PluginIdentifier? = when (pluginIdentifier) {
null -> null
is BinaryPluginIdentifier -> pluginIdentifier.run { InternalBinaryPluginIdentifier(displayName, className, pluginId) }
is ScriptPluginIdentifier -> pluginIdentifier.run { InternalScriptPluginIdentifier(displayName, uri) }
else -> null
}
}
| apache-2.0 | ecc7a6acb2f4608253a5856f2703d7a4 | 49.930233 | 183 | 0.751142 | 4.926884 | false | false | false | false |
siosio/intellij-community | plugins/github/src/org/jetbrains/plugins/github/ui/cloneDialog/GHCloneDialogExtensionComponentBase.kt | 1 | 22517 | // Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.plugins.github.ui.cloneDialog
import com.intellij.collaboration.auth.AccountsListener
import com.intellij.collaboration.messages.CollaborationToolsBundle
import com.intellij.collaboration.ui.CollaborationToolsUIUtil
import com.intellij.dvcs.repo.ClonePathProvider
import com.intellij.dvcs.ui.CloneDvcsValidationUtils
import com.intellij.dvcs.ui.DvcsBundle.message
import com.intellij.dvcs.ui.SelectChildTextFieldWithBrowseButton
import com.intellij.icons.AllIcons
import com.intellij.ide.BrowserUtil
import com.intellij.openapi.actionSystem.IdeActions
import com.intellij.openapi.application.ModalityState
import com.intellij.openapi.application.runInEdt
import com.intellij.openapi.fileChooser.FileChooserDescriptorFactory
import com.intellij.openapi.keymap.KeymapUtil
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.progress.Task
import com.intellij.openapi.project.DumbAwareAction
import com.intellij.openapi.project.Project
import com.intellij.openapi.project.ProjectManager
import com.intellij.openapi.ui.DialogPanel
import com.intellij.openapi.ui.ValidationInfo
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.util.text.StringUtil
import com.intellij.openapi.vcs.CheckoutProvider
import com.intellij.openapi.vcs.ui.cloneDialog.VcsCloneDialogExtensionComponent
import com.intellij.openapi.vfs.LocalFileSystem
import com.intellij.openapi.wm.IdeFocusManager
import com.intellij.ui.*
import com.intellij.ui.SingleSelectionModel
import com.intellij.ui.components.JBList
import com.intellij.ui.components.panels.Wrapper
import com.intellij.ui.layout.*
import com.intellij.util.IconUtil
import com.intellij.util.containers.ContainerUtil
import com.intellij.util.progress.ProgressVisibilityManager
import com.intellij.util.ui.JBEmptyBorder
import com.intellij.util.ui.JBUI
import com.intellij.util.ui.JBValue
import com.intellij.util.ui.UIUtil
import com.intellij.util.ui.cloneDialog.AccountMenuItem
import com.intellij.util.ui.cloneDialog.AccountMenuItem.Account
import com.intellij.util.ui.cloneDialog.AccountMenuItem.Action
import com.intellij.util.ui.cloneDialog.AccountMenuPopupStep
import com.intellij.util.ui.cloneDialog.AccountsMenuListPopup
import com.intellij.util.ui.cloneDialog.VcsCloneDialogUiSpec
import git4idea.GitUtil
import git4idea.checkout.GitCheckoutProvider
import git4idea.commands.Git
import git4idea.remote.GitRememberedInputs
import org.jetbrains.plugins.github.GithubIcons
import org.jetbrains.plugins.github.api.*
import org.jetbrains.plugins.github.api.data.GithubAuthenticatedUser
import org.jetbrains.plugins.github.api.data.GithubRepo
import org.jetbrains.plugins.github.api.data.request.Affiliation
import org.jetbrains.plugins.github.api.data.request.GithubRequestPagination
import org.jetbrains.plugins.github.api.util.GithubApiPagesLoader
import org.jetbrains.plugins.github.authentication.GithubAuthenticationManager
import org.jetbrains.plugins.github.authentication.accounts.GithubAccount
import org.jetbrains.plugins.github.authentication.accounts.GithubAccountInformationProvider
import org.jetbrains.plugins.github.exceptions.GithubMissingTokenException
import org.jetbrains.plugins.github.i18n.GithubBundle
import org.jetbrains.plugins.github.ui.avatars.GHAvatarIconsProvider
import org.jetbrains.plugins.github.util.*
import java.awt.FlowLayout
import java.awt.event.MouseAdapter
import java.awt.event.MouseEvent
import java.nio.file.Paths
import javax.swing.*
import javax.swing.event.DocumentEvent
import kotlin.properties.Delegates
internal abstract class GHCloneDialogExtensionComponentBase(
private val project: Project,
private val authenticationManager: GithubAuthenticationManager,
private val executorManager: GithubApiRequestExecutorManager,
private val accountInformationProvider: GithubAccountInformationProvider,
private val avatarLoader: CachingGHUserAvatarLoader
) : VcsCloneDialogExtensionComponent(),
AccountsListener<GithubAccount> {
private val LOG = GithubUtil.LOG
private val progressManager: ProgressVisibilityManager
private val githubGitHelper: GithubGitHelper = GithubGitHelper.getInstance()
// UI
private val defaultAvatar = IconUtil.resizeSquared(GithubIcons.DefaultAvatar, VcsCloneDialogUiSpec.Components.avatarSize)
private val defaultPopupAvatar = IconUtil.resizeSquared(GithubIcons.DefaultAvatar, VcsCloneDialogUiSpec.Components.popupMenuAvatarSize)
private val avatarSizeUiInt = JBValue.UIInteger("GHCloneDialogExtensionComponent.popupAvatarSize",
VcsCloneDialogUiSpec.Components.popupMenuAvatarSize)
private val wrapper: Wrapper = Wrapper()
private val repositoriesPanel: DialogPanel
private val repositoryList: JBList<GHRepositoryListItem>
private val popupMenuMouseAdapter = object : MouseAdapter() {
override fun mouseClicked(e: MouseEvent?) = showPopupMenu()
}
private val accountsPanel: JPanel = JPanel(FlowLayout(FlowLayout.LEADING, JBUI.scale(1), 0)).apply {
addMouseListener(popupMenuMouseAdapter)
}
private val searchField: SearchTextField
private val directoryField = SelectChildTextFieldWithBrowseButton(
ClonePathProvider.defaultParentDirectoryPath(project, GitRememberedInputs.getInstance())).apply {
val fcd = FileChooserDescriptorFactory.createSingleFolderDescriptor()
fcd.isShowFileSystemRoots = true
fcd.isHideIgnored = false
addBrowseFolderListener(message("clone.destination.directory.browser.title"),
message("clone.destination.directory.browser.description"),
project,
fcd)
}
// state
private val userDetailsByAccount = hashMapOf<GithubAccount, GithubAuthenticatedUser>()
private val repositoriesByAccount = hashMapOf<GithubAccount, LinkedHashSet<GithubRepo>>()
private val errorsByAccount = hashMapOf<GithubAccount, GHRepositoryListItem.Error>()
private val originListModel = CollectionListModel<GHRepositoryListItem>()
private var inLoginState = false
private var selectedUrl by Delegates.observable<String?>(null) { _, _, _ -> onSelectedUrlChanged() }
// popup menu
private val accountComponents = hashMapOf<GithubAccount, JLabel>()
private val avatarsByAccount = hashMapOf<GithubAccount, Icon>()
protected val content: JComponent get() = wrapper.targetComponent
init {
repositoryList = JBList(originListModel).apply {
cellRenderer = GHRepositoryListCellRenderer { getAccounts() }
isFocusable = false
selectionModel = SingleSelectionModel()
}.also {
val mouseAdapter = GHRepositoryMouseAdapter(it)
it.addMouseListener(mouseAdapter)
it.addMouseMotionListener(mouseAdapter)
it.addListSelectionListener { evt ->
if (evt.valueIsAdjusting) return@addListSelectionListener
updateSelectedUrl()
}
}
searchField = SearchTextField(false).also {
it.addDocumentListener(object : DocumentAdapter() {
override fun textChanged(e: DocumentEvent) = updateSelectedUrl()
})
createFocusFilterFieldAction(it)
}
CollaborationToolsUIUtil.attachSearch(repositoryList, searchField) {
when (it) {
is GHRepositoryListItem.Repo -> it.repo.fullName
is GHRepositoryListItem.Error -> ""
}
}
progressManager = object : ProgressVisibilityManager() {
override fun setProgressVisible(visible: Boolean) = repositoryList.setPaintBusy(visible)
override fun getModalityState() = ModalityState.any()
}
Disposer.register(this, progressManager)
repositoriesPanel = panel {
row {
cell(isFullWidth = true) {
searchField.textEditor(pushX, growX)
JSeparator(JSeparator.VERTICAL)(growY)
accountsPanel()
}
}
row {
ScrollPaneFactory.createScrollPane(repositoryList)(push, grow)
}
row(GithubBundle.message("clone.dialog.directory.field")) {
directoryField(growX, pushX)
}
}
repositoriesPanel.border = JBEmptyBorder(UIUtil.getRegularPanelInsets())
}
protected abstract fun getAccounts(): Collection<GithubAccount>
protected abstract fun createLoginPanel(account: GithubAccount?, cancelHandler: () -> Unit): JComponent
fun setup() {
val accounts = getAccounts()
if (accounts.isNotEmpty()) {
switchToRepositories()
accounts.forEach(::addAccount)
}
else {
switchToLogin(null)
}
}
override fun onAccountListChanged(old: Collection<GithubAccount>, new: Collection<GithubAccount>) {
val removed = old - new
if (removed.isNotEmpty()) {
removeAccounts(removed)
dialogStateListener.onListItemChanged()
}
val added = new - old
if (added.isNotEmpty()) {
for (account in added) {
if (repositoriesByAccount[account] != null) continue
addAccount(account)
}
switchToRepositories()
dialogStateListener.onListItemChanged()
}
}
override fun onAccountCredentialsChanged(account: GithubAccount) {
if (repositoriesByAccount[account] != null) return
dialogStateListener.onListItemChanged()
addAccount(account)
switchToRepositories()
}
protected fun switchToLogin(account: GithubAccount?) {
wrapper.setContent(createLoginPanel(account) { switchToRepositories() })
wrapper.repaint()
inLoginState = true
updateSelectedUrl()
}
private fun switchToRepositories() {
wrapper.setContent(repositoriesPanel)
wrapper.repaint()
inLoginState = false
updateSelectedUrl()
}
private fun addAccount(account: GithubAccount) {
repositoriesByAccount.remove(account)
val label = accountComponents.getOrPut(account) {
JLabel().apply {
icon = defaultAvatar
toolTipText = account.name
isOpaque = false
addMouseListener(popupMenuMouseAdapter)
}
}
accountsPanel.add(label)
try {
val executor = executorManager.getExecutor(account)
loadUserDetails(account, executor)
loadRepositories(account, executor)
}
catch (e: GithubMissingTokenException) {
errorsByAccount[account] = GHRepositoryListItem.Error(account,
GithubBundle.message("account.token.missing"),
GithubBundle.message("login.link"),
Runnable { switchToLogin(account) })
refillRepositories()
}
}
private fun removeAccounts(accounts: Collection<GithubAccount>) {
for (account in accounts) {
repositoriesByAccount.remove(account)
accountComponents.remove(account).let {
accountsPanel.remove(it)
}
}
accountsPanel.revalidate()
accountsPanel.repaint()
refillRepositories()
if (getAccounts().isEmpty()) switchToLogin(null)
}
private fun loadUserDetails(account: GithubAccount,
executor: GithubApiRequestExecutor.WithTokenAuth) {
progressManager.run(object : Task.Backgroundable(project, GithubBundle.message("progress.title.not.visible")) {
lateinit var user: GithubAuthenticatedUser
lateinit var iconProvider: GHAvatarIconsProvider
override fun run(indicator: ProgressIndicator) {
user = accountInformationProvider.getInformation(executor, indicator, account)
iconProvider = GHAvatarIconsProvider(avatarLoader, executor)
}
override fun onSuccess() {
userDetailsByAccount[account] = user
val avatar = iconProvider.getIcon(user.avatarUrl, avatarSizeUiInt.get())
avatarsByAccount[account] = avatar
accountComponents[account]?.icon = IconUtil.resizeSquared(avatar, VcsCloneDialogUiSpec.Components.avatarSize)
refillRepositories()
}
override fun onThrowable(error: Throwable) {
LOG.error(error)
errorsByAccount[account] = GHRepositoryListItem.Error(account,
GithubBundle.message("clone.error.load.repositories"),
GithubBundle.message("retry.link"),
Runnable { addAccount(account) })
}
})
}
private fun loadRepositories(account: GithubAccount,
executor: GithubApiRequestExecutor.WithTokenAuth) {
repositoriesByAccount.remove(account)
errorsByAccount.remove(account)
progressManager.run(object : Task.Backgroundable(project, GithubBundle.message("progress.title.not.visible")) {
override fun run(indicator: ProgressIndicator) {
val repoPagesRequest = GithubApiRequests.CurrentUser.Repos.pages(account.server,
affiliation = Affiliation.combine(Affiliation.OWNER,
Affiliation.COLLABORATOR),
pagination = GithubRequestPagination.DEFAULT)
val pageItemsConsumer: (List<GithubRepo>) -> Unit = {
runInEdt {
repositoriesByAccount.getOrPut(account) { UpdateOrderLinkedHashSet() }.addAll(it)
refillRepositories()
}
}
GithubApiPagesLoader.loadAll(executor, indicator, repoPagesRequest, pageItemsConsumer)
val orgsRequest = GithubApiRequests.CurrentUser.Orgs.pages(account.server)
val userOrganizations = GithubApiPagesLoader.loadAll(executor, indicator, orgsRequest).sortedBy { it.login }
for (org in userOrganizations) {
val orgRepoRequest = GithubApiRequests.Organisations.Repos.pages(account.server, org.login, GithubRequestPagination.DEFAULT)
GithubApiPagesLoader.loadAll(executor, indicator, orgRepoRequest, pageItemsConsumer)
}
}
override fun onThrowable(error: Throwable) {
LOG.error(error)
errorsByAccount[account] = GHRepositoryListItem.Error(account,
GithubBundle.message("clone.error.load.repositories"),
GithubBundle.message("retry.link"),
Runnable { loadRepositories(account, executor) })
}
})
}
private fun refillRepositories() {
val selectedValue = repositoryList.selectedValue
originListModel.removeAll()
for (account in getAccounts()) {
if (errorsByAccount[account] != null) {
originListModel.add(errorsByAccount[account])
}
val user = userDetailsByAccount[account] ?: continue
val repos = repositoriesByAccount[account] ?: continue
for (repo in repos) {
originListModel.add(GHRepositoryListItem.Repo(account, user, repo))
}
}
repositoryList.setSelectedValue(selectedValue, false)
ScrollingUtil.ensureSelectionExists(repositoryList)
}
override fun getView() = wrapper
override fun doValidateAll(): List<ValidationInfo> {
val list = ArrayList<ValidationInfo>()
ContainerUtil.addIfNotNull(list, CloneDvcsValidationUtils.checkDirectory(directoryField.text, directoryField.textField))
return list
}
override fun doClone(checkoutListener: CheckoutProvider.Listener) {
val parent = Paths.get(directoryField.text).toAbsolutePath().parent
val destinationValidation = CloneDvcsValidationUtils.createDestination(parent.toString())
if (destinationValidation != null) {
LOG.error("Unable to create destination directory", destinationValidation.message)
GithubNotifications.showError(project,
GithubNotificationIdsHolder.CLONE_UNABLE_TO_CREATE_DESTINATION_DIR,
GithubBundle.message("clone.dialog.clone.failed"),
GithubBundle.message("clone.error.unable.to.create.dest.dir"))
return
}
val lfs = LocalFileSystem.getInstance()
var destinationParent = lfs.findFileByIoFile(parent.toFile())
if (destinationParent == null) {
destinationParent = lfs.refreshAndFindFileByIoFile(parent.toFile())
}
if (destinationParent == null) {
LOG.error("Clone Failed. Destination doesn't exist")
GithubNotifications.showError(project,
GithubNotificationIdsHolder.CLONE_UNABLE_TO_FIND_DESTINATION,
GithubBundle.message("clone.dialog.clone.failed"),
GithubBundle.message("clone.error.unable.to.find.dest"))
return
}
val directoryName = Paths.get(directoryField.text).fileName.toString()
val parentDirectory = parent.toAbsolutePath().toString()
GitCheckoutProvider.clone(project, Git.getInstance(), checkoutListener, destinationParent, selectedUrl, directoryName, parentDirectory)
}
override fun onComponentSelected() {
dialogStateListener.onOkActionNameChanged(GithubBundle.message("clone.button"))
updateSelectedUrl()
val focusManager = IdeFocusManager.getInstance(project)
getPreferredFocusedComponent()?.let { focusManager.requestFocus(it, true) }
}
override fun getPreferredFocusedComponent(): JComponent? {
return searchField
}
private fun updateSelectedUrl() {
repositoryList.emptyText.clear()
if (inLoginState) {
selectedUrl = null
return
}
val githubRepoPath = getGithubRepoPath(searchField.text)
if (githubRepoPath != null) {
selectedUrl = githubGitHelper.getRemoteUrl(githubRepoPath.serverPath,
githubRepoPath.repositoryPath.owner,
githubRepoPath.repositoryPath.repository)
repositoryList.emptyText.appendText(GithubBundle.message("clone.dialog.text", selectedUrl!!))
return
}
val selectedValue = repositoryList.selectedValue
if (selectedValue is GHRepositoryListItem.Repo) {
selectedUrl = githubGitHelper.getRemoteUrl(selectedValue.account.server,
selectedValue.repo.userName,
selectedValue.repo.name)
return
}
selectedUrl = null
}
private fun getGithubRepoPath(searchText: String): GHRepositoryCoordinates? {
val url = searchText
.trim()
.removePrefix("git clone")
.removeSuffix(".git")
.trim()
try {
var serverPath = GithubServerPath.from(url)
serverPath = GithubServerPath.from(serverPath.toUrl().removeSuffix(serverPath.suffix ?: ""))
val githubFullPath = GithubUrlUtil.getUserAndRepositoryFromRemoteUrl(url) ?: return null
return GHRepositoryCoordinates(serverPath, githubFullPath)
}
catch (e: Throwable) {
return null
}
}
private fun onSelectedUrlChanged() {
val urlSelected = selectedUrl != null
dialogStateListener.onOkActionEnabled(urlSelected)
if (urlSelected) {
val path = StringUtil.trimEnd(ClonePathProvider.relativeDirectoryPathForVcsUrl(project, selectedUrl!!), GitUtil.DOT_GIT)
directoryField.trySetChildPath(path)
}
}
/**
* Since each repository can be in several states at the same time (shared access for a collaborator and shared access for org member) and
* repositories for collaborators are loaded in separate request before repositories for org members, we need to update order of re-added
* repo in order to place it close to other organization repos
*/
private class UpdateOrderLinkedHashSet<T> : LinkedHashSet<T>() {
override fun add(element: T): Boolean {
val wasThere = remove(element)
super.add(element)
// Contract is "true if this set did not already contain the specified element"
return !wasThere
}
}
protected abstract fun createAccountMenuLoginActions(account: GithubAccount?): Collection<Action>
private fun showPopupMenu() {
val menuItems = mutableListOf<AccountMenuItem>()
val project = ProjectManager.getInstance().defaultProject
for ((index, account) in getAccounts().withIndex()) {
val user = userDetailsByAccount[account]
val accountTitle = user?.login ?: account.name
val serverInfo = CollaborationToolsUIUtil.cleanupUrl(account.server.toUrl())
val avatar = avatarsByAccount[account] ?: defaultPopupAvatar
val accountActions = mutableListOf<Action>()
val showSeparatorAbove = index != 0
if (user == null) {
accountActions += createAccountMenuLoginActions(account)
accountActions += Action(GithubBundle.message("accounts.remove"), { authenticationManager.removeAccount(account) },
showSeparatorAbove = true)
}
else {
if (account != authenticationManager.getDefaultAccount(project)) {
accountActions += Action(CollaborationToolsBundle.message("accounts.set.default"),
{ authenticationManager.setDefaultAccount(project, account) })
}
accountActions += Action(GithubBundle.message("open.on.github.action"), { BrowserUtil.browse(user.htmlUrl) },
AllIcons.Ide.External_link_arrow)
accountActions += Action(GithubBundle.message("accounts.log.out"), { authenticationManager.removeAccount(account) },
showSeparatorAbove = true)
}
menuItems += Account(accountTitle, serverInfo, avatar, accountActions, showSeparatorAbove)
}
menuItems += createAccountMenuLoginActions(null)
AccountsMenuListPopup(null, AccountMenuPopupStep(menuItems)).showUnderneathOf(accountsPanel)
}
private fun createFocusFilterFieldAction(searchField: SearchTextField) {
val action = DumbAwareAction.create {
val focusManager = IdeFocusManager.getInstance(project)
if (focusManager.getFocusedDescendantFor(repositoriesPanel) != null) {
focusManager.requestFocus(searchField, true)
}
}
val shortcuts = KeymapUtil.getActiveKeymapShortcuts(IdeActions.ACTION_FIND)
action.registerCustomShortcutSet(shortcuts, repositoriesPanel, this)
}
} | apache-2.0 | 928ad2906fad7ec73419b6f0927a692c | 41.247655 | 140 | 0.706888 | 5.354816 | false | false | false | false |
vovagrechka/fucking-everything | alraune/alraune/src/main/java/alraune/desktop/AlDesktopApplication.kt | 1 | 3530 | package alraune.desktop
import alraune.*
import alraune.entity.*
import javafx.application.Application
import javafx.application.Platform
import javafx.geometry.Insets
import javafx.scene.Scene
import javafx.scene.control.*
import javafx.scene.layout.Priority
import javafx.scene.layout.VBox
import javafx.stage.Stage
import javafx.stage.WindowEvent
import javafx.util.Callback
import pieces100.*
import vgrechka.*
import kotlin.system.exitProcess
fun <T> tx(block: () -> T): T =
rctx0.al.useConnection {
AlDB.tx {
block()
}
}
class AlDesktopApplication : Application() {
var primaryStage by notNullOnce<Stage>()
var statusLabel by notNullOnce<Label>()
var mainSplitPane by notNullOnce<SplitPane>()
override fun start(primaryStage: Stage) {
JFXPile.installUncaughtExceptionHandler_errorAlert()
primaryStage.addEventHandler(WindowEvent.WINDOW_HIDDEN) {
exitProcess(0)
}
this.primaryStage = primaryStage
primaryStage.width = 1500.0
primaryStage.height = 600.0
primaryStage.title = "Alraune Desktop"
val vbox = VBox()
vbox.children += MenuBar().also {
it.menus += Menu("_Tools").also {
it.addItem("_Mess Around") {action_messAround()}
}
}
mainSplitPane = SplitPane()
VBox.setVgrow(mainSplitPane, Priority.ALWAYS)
mainSplitPane.setDividerPosition(0, 0.4)
vbox.children += mainSplitPane
statusLabel = Label()
statusLabel.padding = Insets(5.0)
resetStatusLabel()
vbox.children += statusLabel
primaryStage.scene = Scene(vbox).also {
// it.stylesheets.add(FreakingCommander::class.simpleName + ".css")
}
primaryStage.show()
start0()
}
fun start0() {
Platform.runLater {
initStandaloneToolMode__envyAda1__drop_create_fuck1()
OrderWindow(7).stage.show()
}
}
fun resetStatusLabel() {
statusLabel.text = "Hello, little pizda :)"
}
fun action_messAround() {
JFXPile.infoAlert("Fucking around, user?")
}
companion object {
@JvmStatic fun main(args: Array<String>) {
TimePile.setSystemTimezoneGMT()
launch(AlDesktopApplication::class.java, *args)
}
}
}
class OrderWindow(val orderId: Long) {
val order = tx {dbSelectMaybeOrderById(orderId) ?: bitch("Can't find your freaking order")}
val stage = Stage()
val tabPane = TabPane()
init {
stage.width = 1000.0
stage.height = 500.0
stage.title = "Заказ №$orderId: ${order.data.documentTitle}"
NotesTab()
stage.scene = Scene(tabPane)
debug1()
}
inner class NotesTab {
init {
val tab = Tab("Заметки")
tab.isClosable = false
tabPane.tabs.add(tab)
val listView = ListView<FreakingItem>()
tab.content = listView
listView.cellFactory = Callback {
ListCell<FreakingItem>()
}
for (note in order.viewBucket().notes) {
listView.items.add(FreakingItem(note))
}
}
}
class FreakingItem(val note: Order.UserNote) {
override fun toString() = note.text
}
fun debug1() {
stage.addEventHandler(WindowEvent.WINDOW_HIDDEN) {
exitProcess(0)
}
}
}
| apache-2.0 | 9ce9eb2834e6dd6a7ac33d1301afa631 | 20.703704 | 95 | 0.599829 | 4.351485 | false | false | false | false |
vovagrechka/fucking-everything | phizdets/phizdetsc/src/org/jetbrains/kotlin/js/resolve/diagnostics/JsInheritanceChecker.kt | 3 | 3689 | /*
* Copyright 2010-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.kotlin.js.resolve.diagnostics
import org.jetbrains.kotlin.builtins.isBuiltinFunctionalTypeOrSubtype
import org.jetbrains.kotlin.descriptors.ClassDescriptor
import org.jetbrains.kotlin.descriptors.DeclarationDescriptor
import org.jetbrains.kotlin.descriptors.FunctionDescriptor
import org.jetbrains.kotlin.descriptors.Modality
import org.jetbrains.kotlin.diagnostics.DiagnosticSink
import org.jetbrains.kotlin.psi.KtClassOrObject
import org.jetbrains.kotlin.psi.KtDeclaration
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.DescriptorUtils
import org.jetbrains.kotlin.resolve.checkers.SimpleDeclarationChecker
import org.jetbrains.kotlin.resolve.descriptorUtil.hasDefaultValue
import org.jetbrains.kotlin.resolve.scopes.DescriptorKindFilter
import org.jetbrains.kotlin.types.typeUtil.immediateSupertypes
object JsInheritanceChecker : SimpleDeclarationChecker {
override fun check(
declaration: KtDeclaration,
descriptor: DeclarationDescriptor,
diagnosticHolder: DiagnosticSink,
bindingContext: BindingContext
) {
if (descriptor is FunctionDescriptor && !DescriptorUtils.isEffectivelyExternal(descriptor) &&
isOverridingExternalWithOptionalParams(descriptor)
) {
diagnosticHolder.report(ErrorsJs.OVERRIDING_EXTERNAL_FUN_WITH_OPTIONAL_PARAMS.on(declaration))
}
else if (descriptor is ClassDescriptor && !DescriptorUtils.isEffectivelyExternal(descriptor)) {
val fakeOverriddenMethod = findFakeMethodOverridingExternalWithOptionalParams(descriptor)
if (fakeOverriddenMethod != null) {
diagnosticHolder.report(ErrorsJs.OVERRIDING_EXTERNAL_FUN_WITH_OPTIONAL_PARAMS_WITH_FAKE.on(
declaration, fakeOverriddenMethod))
}
}
if (descriptor is ClassDescriptor &&
descriptor.defaultType.immediateSupertypes().any { it.isBuiltinFunctionalTypeOrSubtype }
) {
diagnosticHolder.report(ErrorsJs.IMPLEMENTING_FUNCTION_INTERFACE.on(declaration as KtClassOrObject))
}
}
private fun isOverridingExternalWithOptionalParams(function: FunctionDescriptor): Boolean {
if (!function.kind.isReal && function.modality == Modality.ABSTRACT) return false
for (overriddenFunction in function.overriddenDescriptors.filter { DescriptorUtils.isEffectivelyExternal(it) }) {
if (overriddenFunction.valueParameters.any { it.hasDefaultValue() }) return true
}
return false
}
private fun findFakeMethodOverridingExternalWithOptionalParams(cls: ClassDescriptor): FunctionDescriptor? {
val members = cls.unsubstitutedMemberScope.getContributedDescriptors(DescriptorKindFilter.CALLABLES)
.mapNotNull { it as? FunctionDescriptor }
.filter { it.containingDeclaration == cls && !it.kind.isReal && it.overriddenDescriptors.size > 1 }
return members.firstOrNull { isOverridingExternalWithOptionalParams(it) }
}
}
| apache-2.0 | 7a61af2ec25d831c5dbab6adc42e7274 | 46.294872 | 121 | 0.749526 | 5.116505 | false | false | false | false |
GunoH/intellij-community | plugins/devkit/intellij.devkit.workspaceModel/tests/testData/simpleCase/after/gen/SimpleEntityImpl.kt | 2 | 7053 | package com.intellij.workspaceModel.test.api
import com.intellij.workspaceModel.storage.EntityInformation
import com.intellij.workspaceModel.storage.EntitySource
import com.intellij.workspaceModel.storage.EntityStorage
import com.intellij.workspaceModel.storage.GeneratedCodeApiVersion
import com.intellij.workspaceModel.storage.GeneratedCodeImplVersion
import com.intellij.workspaceModel.storage.MutableEntityStorage
import com.intellij.workspaceModel.storage.WorkspaceEntity
import com.intellij.workspaceModel.storage.impl.ConnectionId
import com.intellij.workspaceModel.storage.impl.ModifiableWorkspaceEntityBase
import com.intellij.workspaceModel.storage.impl.UsedClassesCollector
import com.intellij.workspaceModel.storage.impl.WorkspaceEntityBase
import com.intellij.workspaceModel.storage.impl.WorkspaceEntityData
@GeneratedCodeApiVersion(1)
@GeneratedCodeImplVersion(1)
open class SimpleEntityImpl(val dataSource: SimpleEntityData) : SimpleEntity, WorkspaceEntityBase() {
companion object {
val connections = listOf<ConnectionId>(
)
}
override val version: Int get() = dataSource.version
override val name: String
get() = dataSource.name
override val isSimple: Boolean get() = dataSource.isSimple
override val entitySource: EntitySource
get() = dataSource.entitySource
override fun connectionIdList(): List<ConnectionId> {
return connections
}
class Builder(result: SimpleEntityData?) : ModifiableWorkspaceEntityBase<SimpleEntity, SimpleEntityData>(result), SimpleEntity.Builder {
constructor() : this(SimpleEntityData())
override fun applyToBuilder(builder: MutableEntityStorage) {
if (this.diff != null) {
if (existsInBuilder(builder)) {
this.diff = builder
return
}
else {
error("Entity SimpleEntity is already created in a different builder")
}
}
this.diff = builder
this.snapshot = builder
addToBuilder()
this.id = getEntityData().createEntityId()
// After adding entity data to the builder, we need to unbind it and move the control over entity data to builder
// Builder may switch to snapshot at any moment and lock entity data to modification
this.currentEntityData = null
// Process linked entities that are connected without a builder
processLinkedEntities(builder)
checkInitialization() // TODO uncomment and check failed tests
}
fun checkInitialization() {
val _diff = diff
if (!getEntityData().isEntitySourceInitialized()) {
error("Field WorkspaceEntity#entitySource should be initialized")
}
if (!getEntityData().isNameInitialized()) {
error("Field SimpleEntity#name should be initialized")
}
}
override fun connectionIdList(): List<ConnectionId> {
return connections
}
// Relabeling code, move information from dataSource to this builder
override fun relabel(dataSource: WorkspaceEntity, parents: Set<WorkspaceEntity>?) {
dataSource as SimpleEntity
if (this.entitySource != dataSource.entitySource) this.entitySource = dataSource.entitySource
if (this.version != dataSource.version) this.version = dataSource.version
if (this.name != dataSource.name) this.name = dataSource.name
if (this.isSimple != dataSource.isSimple) this.isSimple = dataSource.isSimple
if (parents != null) {
}
}
override var entitySource: EntitySource
get() = getEntityData().entitySource
set(value) {
checkModificationAllowed()
getEntityData(true).entitySource = value
changedProperty.add("entitySource")
}
override var version: Int
get() = getEntityData().version
set(value) {
checkModificationAllowed()
getEntityData(true).version = value
changedProperty.add("version")
}
override var name: String
get() = getEntityData().name
set(value) {
checkModificationAllowed()
getEntityData(true).name = value
changedProperty.add("name")
}
override var isSimple: Boolean
get() = getEntityData().isSimple
set(value) {
checkModificationAllowed()
getEntityData(true).isSimple = value
changedProperty.add("isSimple")
}
override fun getEntityClass(): Class<SimpleEntity> = SimpleEntity::class.java
}
}
class SimpleEntityData : WorkspaceEntityData<SimpleEntity>() {
var version: Int = 0
lateinit var name: String
var isSimple: Boolean = false
fun isNameInitialized(): Boolean = ::name.isInitialized
override fun wrapAsModifiable(diff: MutableEntityStorage): WorkspaceEntity.Builder<SimpleEntity> {
val modifiable = SimpleEntityImpl.Builder(null)
modifiable.diff = diff
modifiable.snapshot = diff
modifiable.id = createEntityId()
return modifiable
}
override fun createEntity(snapshot: EntityStorage): SimpleEntity {
return getCached(snapshot) {
val entity = SimpleEntityImpl(this)
entity.snapshot = snapshot
entity.id = createEntityId()
entity
}
}
override fun getEntityInterface(): Class<out WorkspaceEntity> {
return SimpleEntity::class.java
}
override fun serialize(ser: EntityInformation.Serializer) {
}
override fun deserialize(de: EntityInformation.Deserializer) {
}
override fun createDetachedEntity(parents: List<WorkspaceEntity>): WorkspaceEntity {
return SimpleEntity(version, name, isSimple, entitySource) {
}
}
override fun getRequiredParents(): List<Class<out WorkspaceEntity>> {
val res = mutableListOf<Class<out WorkspaceEntity>>()
return res
}
override fun equals(other: Any?): Boolean {
if (other == null) return false
if (this.javaClass != other.javaClass) return false
other as SimpleEntityData
if (this.entitySource != other.entitySource) return false
if (this.version != other.version) return false
if (this.name != other.name) return false
if (this.isSimple != other.isSimple) return false
return true
}
override fun equalsIgnoringEntitySource(other: Any?): Boolean {
if (other == null) return false
if (this.javaClass != other.javaClass) return false
other as SimpleEntityData
if (this.version != other.version) return false
if (this.name != other.name) return false
if (this.isSimple != other.isSimple) return false
return true
}
override fun hashCode(): Int {
var result = entitySource.hashCode()
result = 31 * result + version.hashCode()
result = 31 * result + name.hashCode()
result = 31 * result + isSimple.hashCode()
return result
}
override fun hashCodeIgnoringEntitySource(): Int {
var result = javaClass.hashCode()
result = 31 * result + version.hashCode()
result = 31 * result + name.hashCode()
result = 31 * result + isSimple.hashCode()
return result
}
override fun collectClassUsagesData(collector: UsedClassesCollector) {
collector.sameForAllEntities = true
}
}
| apache-2.0 | 46f73f1b10062bfa3fee7ea89303e20e | 30.914027 | 138 | 0.712037 | 5.167033 | false | false | false | false |
GunoH/intellij-community | plugins/gradle/java/src/codeInspection/fix/GradleTaskToRegisterFix.kt | 2 | 3046 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.plugins.gradle.codeInspection.fix
import com.intellij.codeInspection.LocalQuickFix
import com.intellij.codeInspection.ProblemDescriptor
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiElement
import com.intellij.psi.util.parentOfType
import com.intellij.util.asSafely
import org.jetbrains.plugins.gradle.codeInspection.GradleInspectionBundle
import org.jetbrains.plugins.groovy.GroovyBundle
import org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElementFactory
import org.jetbrains.plugins.groovy.lang.psi.api.statements.blocks.GrClosableBlock
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrMethodCall
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrReferenceExpression
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.literals.GrLiteral
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.path.GrMethodCallExpression
import org.jetbrains.plugins.groovy.lang.psi.impl.stringValue
class GradleTaskToRegisterFix : LocalQuickFix {
override fun getFamilyName(): String {
return GroovyBundle.message("intention.family.name.replace.keywords")
}
override fun getName(): String {
return GradleInspectionBundle.message("intention.name.use.tasks.register")
}
override fun applyFix(project: Project, descriptor: ProblemDescriptor) {
val callParent = descriptor.psiElement.parentOfType<GrMethodCall>() ?: return
val firstArgument = inferFirstArgument(callParent) ?: return
val secondArgument = inferSecondArgument(callParent)
val representation = "tasks.register" + when (secondArgument) {
null -> "('$firstArgument')"
is GrClosableBlock -> "('$firstArgument') ${secondArgument.text}"
else -> "('$firstArgument', ${secondArgument.text})"
}
val newCall = GroovyPsiElementFactory.getInstance(project).createExpressionFromText(representation)
callParent.replace(newCall)
}
private fun inferFirstArgument(callParent: GrMethodCall) : String? {
val argument = callParent.expressionArguments.firstOrNull() ?: return null
return when (argument) {
is GrMethodCallExpression -> argument.invokedExpression.text
is GrLiteral -> argument.stringValue()
is GrReferenceExpression -> argument.text
else -> null
}
}
private fun inferSecondArgument(callParent: GrMethodCall, inspectFirstArg: Boolean = true) : PsiElement? {
val closureArgument = callParent.closureArguments.firstOrNull()
if (closureArgument != null) {
return closureArgument
}
val argument = callParent.expressionArguments.getOrNull(1)
if (argument != null) {
return argument
}
if (inspectFirstArg) {
val firstArgument = callParent.expressionArguments.firstOrNull()?.asSafely<GrMethodCall>() ?: return null
return inferSecondArgument(firstArgument, false)
}
return null
}
} | apache-2.0 | 489c0042e7038973fb7ef8c792db9a0a | 44.477612 | 120 | 0.7761 | 4.722481 | false | false | false | false |
GunoH/intellij-community | platform/workspaceModel/storage/gen/com/intellij/workspaceModel/storage/bridgeEntities/ModuleEntityImpl.kt | 1 | 29520 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.workspaceModel.storage.bridgeEntities
import com.intellij.workspaceModel.storage.*
import com.intellij.workspaceModel.storage.EntityInformation
import com.intellij.workspaceModel.storage.EntitySource
import com.intellij.workspaceModel.storage.EntityStorage
import com.intellij.workspaceModel.storage.GeneratedCodeApiVersion
import com.intellij.workspaceModel.storage.GeneratedCodeImplVersion
import com.intellij.workspaceModel.storage.MutableEntityStorage
import com.intellij.workspaceModel.storage.SymbolicEntityId
import com.intellij.workspaceModel.storage.WorkspaceEntity
import com.intellij.workspaceModel.storage.impl.ConnectionId
import com.intellij.workspaceModel.storage.impl.EntityLink
import com.intellij.workspaceModel.storage.impl.ModifiableWorkspaceEntityBase
import com.intellij.workspaceModel.storage.impl.SoftLinkable
import com.intellij.workspaceModel.storage.impl.UsedClassesCollector
import com.intellij.workspaceModel.storage.impl.WorkspaceEntityBase
import com.intellij.workspaceModel.storage.impl.WorkspaceEntityData
import com.intellij.workspaceModel.storage.impl.containers.MutableWorkspaceList
import com.intellij.workspaceModel.storage.impl.containers.toMutableWorkspaceList
import com.intellij.workspaceModel.storage.impl.extractOneToManyChildren
import com.intellij.workspaceModel.storage.impl.extractOneToOneChild
import com.intellij.workspaceModel.storage.impl.indices.WorkspaceMutableIndex
import com.intellij.workspaceModel.storage.impl.updateOneToManyChildrenOfParent
import com.intellij.workspaceModel.storage.impl.updateOneToOneChildOfParent
import com.intellij.workspaceModel.storage.url.VirtualFileUrl
import org.jetbrains.deft.ObjBuilder
import org.jetbrains.deft.Type
import org.jetbrains.deft.annotations.Child
@GeneratedCodeApiVersion(1)
@GeneratedCodeImplVersion(1)
open class ModuleEntityImpl(val dataSource: ModuleEntityData) : ModuleEntity, WorkspaceEntityBase() {
companion object {
internal val CONTENTROOTS_CONNECTION_ID: ConnectionId = ConnectionId.create(ModuleEntity::class.java, ContentRootEntity::class.java,
ConnectionId.ConnectionType.ONE_TO_MANY, false)
internal val CUSTOMIMLDATA_CONNECTION_ID: ConnectionId = ConnectionId.create(ModuleEntity::class.java,
ModuleCustomImlDataEntity::class.java,
ConnectionId.ConnectionType.ONE_TO_ONE, false)
internal val GROUPPATH_CONNECTION_ID: ConnectionId = ConnectionId.create(ModuleEntity::class.java, ModuleGroupPathEntity::class.java,
ConnectionId.ConnectionType.ONE_TO_ONE, false)
internal val JAVASETTINGS_CONNECTION_ID: ConnectionId = ConnectionId.create(ModuleEntity::class.java,
JavaModuleSettingsEntity::class.java,
ConnectionId.ConnectionType.ONE_TO_ONE, false)
internal val EXMODULEOPTIONS_CONNECTION_ID: ConnectionId = ConnectionId.create(ModuleEntity::class.java,
ExternalSystemModuleOptionsEntity::class.java,
ConnectionId.ConnectionType.ONE_TO_ONE, false)
internal val FACETS_CONNECTION_ID: ConnectionId = ConnectionId.create(ModuleEntity::class.java, FacetEntity::class.java,
ConnectionId.ConnectionType.ONE_TO_MANY, false)
val connections = listOf<ConnectionId>(
CONTENTROOTS_CONNECTION_ID,
CUSTOMIMLDATA_CONNECTION_ID,
GROUPPATH_CONNECTION_ID,
JAVASETTINGS_CONNECTION_ID,
EXMODULEOPTIONS_CONNECTION_ID,
FACETS_CONNECTION_ID,
)
}
override val name: String
get() = dataSource.name
override val type: String?
get() = dataSource.type
override val dependencies: List<ModuleDependencyItem>
get() = dataSource.dependencies
override val contentRoots: List<ContentRootEntity>
get() = snapshot.extractOneToManyChildren<ContentRootEntity>(CONTENTROOTS_CONNECTION_ID, this)!!.toList()
override val customImlData: ModuleCustomImlDataEntity?
get() = snapshot.extractOneToOneChild(CUSTOMIMLDATA_CONNECTION_ID, this)
override val groupPath: ModuleGroupPathEntity?
get() = snapshot.extractOneToOneChild(GROUPPATH_CONNECTION_ID, this)
override val javaSettings: JavaModuleSettingsEntity?
get() = snapshot.extractOneToOneChild(JAVASETTINGS_CONNECTION_ID, this)
override val exModuleOptions: ExternalSystemModuleOptionsEntity?
get() = snapshot.extractOneToOneChild(EXMODULEOPTIONS_CONNECTION_ID, this)
override val facets: List<FacetEntity>
get() = snapshot.extractOneToManyChildren<FacetEntity>(FACETS_CONNECTION_ID, this)!!.toList()
override val entitySource: EntitySource
get() = dataSource.entitySource
override fun connectionIdList(): List<ConnectionId> {
return connections
}
class Builder(result: ModuleEntityData?) : ModifiableWorkspaceEntityBase<ModuleEntity, ModuleEntityData>(result), ModuleEntity.Builder {
constructor() : this(ModuleEntityData())
override fun applyToBuilder(builder: MutableEntityStorage) {
if (this.diff != null) {
if (existsInBuilder(builder)) {
this.diff = builder
return
}
else {
error("Entity ModuleEntity is already created in a different builder")
}
}
this.diff = builder
this.snapshot = builder
addToBuilder()
this.id = getEntityData().createEntityId()
// After adding entity data to the builder, we need to unbind it and move the control over entity data to builder
// Builder may switch to snapshot at any moment and lock entity data to modification
this.currentEntityData = null
// Process linked entities that are connected without a builder
processLinkedEntities(builder)
checkInitialization() // TODO uncomment and check failed tests
}
fun checkInitialization() {
val _diff = diff
if (!getEntityData().isEntitySourceInitialized()) {
error("Field WorkspaceEntity#entitySource should be initialized")
}
if (!getEntityData().isNameInitialized()) {
error("Field ModuleEntity#name should be initialized")
}
if (!getEntityData().isDependenciesInitialized()) {
error("Field ModuleEntity#dependencies should be initialized")
}
// Check initialization for list with ref type
if (_diff != null) {
if (_diff.extractOneToManyChildren<WorkspaceEntityBase>(CONTENTROOTS_CONNECTION_ID, this) == null) {
error("Field ModuleEntity#contentRoots should be initialized")
}
}
else {
if (this.entityLinks[EntityLink(true, CONTENTROOTS_CONNECTION_ID)] == null) {
error("Field ModuleEntity#contentRoots should be initialized")
}
}
// Check initialization for list with ref type
if (_diff != null) {
if (_diff.extractOneToManyChildren<WorkspaceEntityBase>(FACETS_CONNECTION_ID, this) == null) {
error("Field ModuleEntity#facets should be initialized")
}
}
else {
if (this.entityLinks[EntityLink(true, FACETS_CONNECTION_ID)] == null) {
error("Field ModuleEntity#facets should be initialized")
}
}
}
override fun connectionIdList(): List<ConnectionId> {
return connections
}
override fun afterModification() {
val collection_dependencies = getEntityData().dependencies
if (collection_dependencies is MutableWorkspaceList<*>) {
collection_dependencies.cleanModificationUpdateAction()
}
}
// Relabeling code, move information from dataSource to this builder
override fun relabel(dataSource: WorkspaceEntity, parents: Set<WorkspaceEntity>?) {
dataSource as ModuleEntity
if (this.entitySource != dataSource.entitySource) this.entitySource = dataSource.entitySource
if (this.name != dataSource.name) this.name = dataSource.name
if (this.type != dataSource?.type) this.type = dataSource.type
if (this.dependencies != dataSource.dependencies) this.dependencies = dataSource.dependencies.toMutableList()
if (parents != null) {
}
}
override var entitySource: EntitySource
get() = getEntityData().entitySource
set(value) {
checkModificationAllowed()
getEntityData(true).entitySource = value
changedProperty.add("entitySource")
}
override var name: String
get() = getEntityData().name
set(value) {
checkModificationAllowed()
getEntityData(true).name = value
changedProperty.add("name")
}
override var type: String?
get() = getEntityData().type
set(value) {
checkModificationAllowed()
getEntityData(true).type = value
changedProperty.add("type")
}
private val dependenciesUpdater: (value: List<ModuleDependencyItem>) -> Unit = { value ->
changedProperty.add("dependencies")
}
override var dependencies: MutableList<ModuleDependencyItem>
get() {
val collection_dependencies = getEntityData().dependencies
if (collection_dependencies !is MutableWorkspaceList) return collection_dependencies
if (diff == null || modifiable.get()) {
collection_dependencies.setModificationUpdateAction(dependenciesUpdater)
}
else {
collection_dependencies.cleanModificationUpdateAction()
}
return collection_dependencies
}
set(value) {
checkModificationAllowed()
getEntityData(true).dependencies = value
dependenciesUpdater.invoke(value)
}
// List of non-abstract referenced types
var _contentRoots: List<ContentRootEntity>? = emptyList()
override var contentRoots: List<ContentRootEntity>
get() {
// Getter of the list of non-abstract referenced types
val _diff = diff
return if (_diff != null) {
_diff.extractOneToManyChildren<ContentRootEntity>(CONTENTROOTS_CONNECTION_ID, this)!!.toList() + (this.entityLinks[EntityLink(
true, CONTENTROOTS_CONNECTION_ID)] as? List<ContentRootEntity> ?: emptyList())
}
else {
this.entityLinks[EntityLink(true, CONTENTROOTS_CONNECTION_ID)] as? List<ContentRootEntity> ?: emptyList()
}
}
set(value) {
// Setter of the list of non-abstract referenced types
checkModificationAllowed()
val _diff = diff
if (_diff != null) {
for (item_value in value) {
if (item_value is ModifiableWorkspaceEntityBase<*, *> && (item_value as? ModifiableWorkspaceEntityBase<*, *>)?.diff == null) {
// Backref setup before adding to store
if (item_value is ModifiableWorkspaceEntityBase<*, *>) {
item_value.entityLinks[EntityLink(false, CONTENTROOTS_CONNECTION_ID)] = this
}
// else you're attaching a new entity to an existing entity that is not modifiable
_diff.addEntity(item_value)
}
}
_diff.updateOneToManyChildrenOfParent(CONTENTROOTS_CONNECTION_ID, this, value)
}
else {
for (item_value in value) {
if (item_value is ModifiableWorkspaceEntityBase<*, *>) {
item_value.entityLinks[EntityLink(false, CONTENTROOTS_CONNECTION_ID)] = this
}
// else you're attaching a new entity to an existing entity that is not modifiable
}
this.entityLinks[EntityLink(true, CONTENTROOTS_CONNECTION_ID)] = value
}
changedProperty.add("contentRoots")
}
override var customImlData: ModuleCustomImlDataEntity?
get() {
val _diff = diff
return if (_diff != null) {
_diff.extractOneToOneChild(CUSTOMIMLDATA_CONNECTION_ID, this) ?: this.entityLinks[EntityLink(true,
CUSTOMIMLDATA_CONNECTION_ID)] as? ModuleCustomImlDataEntity
}
else {
this.entityLinks[EntityLink(true, CUSTOMIMLDATA_CONNECTION_ID)] as? ModuleCustomImlDataEntity
}
}
set(value) {
checkModificationAllowed()
val _diff = diff
if (_diff != null && value is ModifiableWorkspaceEntityBase<*, *> && value.diff == null) {
if (value is ModifiableWorkspaceEntityBase<*, *>) {
value.entityLinks[EntityLink(false, CUSTOMIMLDATA_CONNECTION_ID)] = this
}
// else you're attaching a new entity to an existing entity that is not modifiable
_diff.addEntity(value)
}
if (_diff != null && (value !is ModifiableWorkspaceEntityBase<*, *> || value.diff != null)) {
_diff.updateOneToOneChildOfParent(CUSTOMIMLDATA_CONNECTION_ID, this, value)
}
else {
if (value is ModifiableWorkspaceEntityBase<*, *>) {
value.entityLinks[EntityLink(false, CUSTOMIMLDATA_CONNECTION_ID)] = this
}
// else you're attaching a new entity to an existing entity that is not modifiable
this.entityLinks[EntityLink(true, CUSTOMIMLDATA_CONNECTION_ID)] = value
}
changedProperty.add("customImlData")
}
override var groupPath: ModuleGroupPathEntity?
get() {
val _diff = diff
return if (_diff != null) {
_diff.extractOneToOneChild(GROUPPATH_CONNECTION_ID, this) ?: this.entityLinks[EntityLink(true,
GROUPPATH_CONNECTION_ID)] as? ModuleGroupPathEntity
}
else {
this.entityLinks[EntityLink(true, GROUPPATH_CONNECTION_ID)] as? ModuleGroupPathEntity
}
}
set(value) {
checkModificationAllowed()
val _diff = diff
if (_diff != null && value is ModifiableWorkspaceEntityBase<*, *> && value.diff == null) {
if (value is ModifiableWorkspaceEntityBase<*, *>) {
value.entityLinks[EntityLink(false, GROUPPATH_CONNECTION_ID)] = this
}
// else you're attaching a new entity to an existing entity that is not modifiable
_diff.addEntity(value)
}
if (_diff != null && (value !is ModifiableWorkspaceEntityBase<*, *> || value.diff != null)) {
_diff.updateOneToOneChildOfParent(GROUPPATH_CONNECTION_ID, this, value)
}
else {
if (value is ModifiableWorkspaceEntityBase<*, *>) {
value.entityLinks[EntityLink(false, GROUPPATH_CONNECTION_ID)] = this
}
// else you're attaching a new entity to an existing entity that is not modifiable
this.entityLinks[EntityLink(true, GROUPPATH_CONNECTION_ID)] = value
}
changedProperty.add("groupPath")
}
override var javaSettings: JavaModuleSettingsEntity?
get() {
val _diff = diff
return if (_diff != null) {
_diff.extractOneToOneChild(JAVASETTINGS_CONNECTION_ID, this) ?: this.entityLinks[EntityLink(true,
JAVASETTINGS_CONNECTION_ID)] as? JavaModuleSettingsEntity
}
else {
this.entityLinks[EntityLink(true, JAVASETTINGS_CONNECTION_ID)] as? JavaModuleSettingsEntity
}
}
set(value) {
checkModificationAllowed()
val _diff = diff
if (_diff != null && value is ModifiableWorkspaceEntityBase<*, *> && value.diff == null) {
if (value is ModifiableWorkspaceEntityBase<*, *>) {
value.entityLinks[EntityLink(false, JAVASETTINGS_CONNECTION_ID)] = this
}
// else you're attaching a new entity to an existing entity that is not modifiable
_diff.addEntity(value)
}
if (_diff != null && (value !is ModifiableWorkspaceEntityBase<*, *> || value.diff != null)) {
_diff.updateOneToOneChildOfParent(JAVASETTINGS_CONNECTION_ID, this, value)
}
else {
if (value is ModifiableWorkspaceEntityBase<*, *>) {
value.entityLinks[EntityLink(false, JAVASETTINGS_CONNECTION_ID)] = this
}
// else you're attaching a new entity to an existing entity that is not modifiable
this.entityLinks[EntityLink(true, JAVASETTINGS_CONNECTION_ID)] = value
}
changedProperty.add("javaSettings")
}
override var exModuleOptions: ExternalSystemModuleOptionsEntity?
get() {
val _diff = diff
return if (_diff != null) {
_diff.extractOneToOneChild(EXMODULEOPTIONS_CONNECTION_ID, this) ?: this.entityLinks[EntityLink(true,
EXMODULEOPTIONS_CONNECTION_ID)] as? ExternalSystemModuleOptionsEntity
}
else {
this.entityLinks[EntityLink(true, EXMODULEOPTIONS_CONNECTION_ID)] as? ExternalSystemModuleOptionsEntity
}
}
set(value) {
checkModificationAllowed()
val _diff = diff
if (_diff != null && value is ModifiableWorkspaceEntityBase<*, *> && value.diff == null) {
if (value is ModifiableWorkspaceEntityBase<*, *>) {
value.entityLinks[EntityLink(false, EXMODULEOPTIONS_CONNECTION_ID)] = this
}
// else you're attaching a new entity to an existing entity that is not modifiable
_diff.addEntity(value)
}
if (_diff != null && (value !is ModifiableWorkspaceEntityBase<*, *> || value.diff != null)) {
_diff.updateOneToOneChildOfParent(EXMODULEOPTIONS_CONNECTION_ID, this, value)
}
else {
if (value is ModifiableWorkspaceEntityBase<*, *>) {
value.entityLinks[EntityLink(false, EXMODULEOPTIONS_CONNECTION_ID)] = this
}
// else you're attaching a new entity to an existing entity that is not modifiable
this.entityLinks[EntityLink(true, EXMODULEOPTIONS_CONNECTION_ID)] = value
}
changedProperty.add("exModuleOptions")
}
// List of non-abstract referenced types
var _facets: List<FacetEntity>? = emptyList()
override var facets: List<FacetEntity>
get() {
// Getter of the list of non-abstract referenced types
val _diff = diff
return if (_diff != null) {
_diff.extractOneToManyChildren<FacetEntity>(FACETS_CONNECTION_ID, this)!!.toList() + (this.entityLinks[EntityLink(true,
FACETS_CONNECTION_ID)] as? List<FacetEntity>
?: emptyList())
}
else {
this.entityLinks[EntityLink(true, FACETS_CONNECTION_ID)] as? List<FacetEntity> ?: emptyList()
}
}
set(value) {
// Setter of the list of non-abstract referenced types
checkModificationAllowed()
val _diff = diff
if (_diff != null) {
for (item_value in value) {
if (item_value is ModifiableWorkspaceEntityBase<*, *> && (item_value as? ModifiableWorkspaceEntityBase<*, *>)?.diff == null) {
// Backref setup before adding to store
if (item_value is ModifiableWorkspaceEntityBase<*, *>) {
item_value.entityLinks[EntityLink(false, FACETS_CONNECTION_ID)] = this
}
// else you're attaching a new entity to an existing entity that is not modifiable
_diff.addEntity(item_value)
}
}
_diff.updateOneToManyChildrenOfParent(FACETS_CONNECTION_ID, this, value)
}
else {
for (item_value in value) {
if (item_value is ModifiableWorkspaceEntityBase<*, *>) {
item_value.entityLinks[EntityLink(false, FACETS_CONNECTION_ID)] = this
}
// else you're attaching a new entity to an existing entity that is not modifiable
}
this.entityLinks[EntityLink(true, FACETS_CONNECTION_ID)] = value
}
changedProperty.add("facets")
}
override fun getEntityClass(): Class<ModuleEntity> = ModuleEntity::class.java
}
}
class ModuleEntityData : WorkspaceEntityData.WithCalculableSymbolicId<ModuleEntity>(), SoftLinkable {
lateinit var name: String
var type: String? = null
lateinit var dependencies: MutableList<ModuleDependencyItem>
fun isNameInitialized(): Boolean = ::name.isInitialized
fun isDependenciesInitialized(): Boolean = ::dependencies.isInitialized
override fun getLinks(): Set<SymbolicEntityId<*>> {
val result = HashSet<SymbolicEntityId<*>>()
for (item in dependencies) {
when (item) {
is ModuleDependencyItem.Exportable -> {
when (item) {
is ModuleDependencyItem.Exportable.LibraryDependency -> {
result.add(item.library)
}
is ModuleDependencyItem.Exportable.ModuleDependency -> {
result.add(item.module)
}
}
}
is ModuleDependencyItem.InheritedSdkDependency -> {
}
is ModuleDependencyItem.ModuleSourceDependency -> {
}
is ModuleDependencyItem.SdkDependency -> {
}
}
}
return result
}
override fun index(index: WorkspaceMutableIndex<SymbolicEntityId<*>>) {
for (item in dependencies) {
when (item) {
is ModuleDependencyItem.Exportable -> {
when (item) {
is ModuleDependencyItem.Exportable.LibraryDependency -> {
index.index(this, item.library)
}
is ModuleDependencyItem.Exportable.ModuleDependency -> {
index.index(this, item.module)
}
}
}
is ModuleDependencyItem.InheritedSdkDependency -> {
}
is ModuleDependencyItem.ModuleSourceDependency -> {
}
is ModuleDependencyItem.SdkDependency -> {
}
}
}
}
override fun updateLinksIndex(prev: Set<SymbolicEntityId<*>>, index: WorkspaceMutableIndex<SymbolicEntityId<*>>) {
// TODO verify logic
val mutablePreviousSet = HashSet(prev)
for (item in dependencies) {
when (item) {
is ModuleDependencyItem.Exportable -> {
when (item) {
is ModuleDependencyItem.Exportable.LibraryDependency -> {
val removedItem_item_library = mutablePreviousSet.remove(item.library)
if (!removedItem_item_library) {
index.index(this, item.library)
}
}
is ModuleDependencyItem.Exportable.ModuleDependency -> {
val removedItem_item_module = mutablePreviousSet.remove(item.module)
if (!removedItem_item_module) {
index.index(this, item.module)
}
}
}
}
is ModuleDependencyItem.InheritedSdkDependency -> {
}
is ModuleDependencyItem.ModuleSourceDependency -> {
}
is ModuleDependencyItem.SdkDependency -> {
}
}
}
for (removed in mutablePreviousSet) {
index.remove(this, removed)
}
}
override fun updateLink(oldLink: SymbolicEntityId<*>, newLink: SymbolicEntityId<*>): Boolean {
var changed = false
val dependencies_data = dependencies.map {
val _it = it
val res_it = when (_it) {
is ModuleDependencyItem.Exportable -> {
val __it = _it
val res__it = when (__it) {
is ModuleDependencyItem.Exportable.LibraryDependency -> {
val __it_library_data = if (__it.library == oldLink) {
changed = true
newLink as LibraryId
}
else {
null
}
var __it_data = __it
if (__it_library_data != null) {
__it_data = __it_data.copy(library = __it_library_data)
}
__it_data
}
is ModuleDependencyItem.Exportable.ModuleDependency -> {
val __it_module_data = if (__it.module == oldLink) {
changed = true
newLink as ModuleId
}
else {
null
}
var __it_data = __it
if (__it_module_data != null) {
__it_data = __it_data.copy(module = __it_module_data)
}
__it_data
}
}
res__it
}
is ModuleDependencyItem.InheritedSdkDependency -> {
_it
}
is ModuleDependencyItem.ModuleSourceDependency -> {
_it
}
is ModuleDependencyItem.SdkDependency -> {
_it
}
}
if (res_it != null) {
res_it
}
else {
it
}
}
if (dependencies_data != null) {
dependencies = dependencies_data as MutableList
}
return changed
}
override fun wrapAsModifiable(diff: MutableEntityStorage): WorkspaceEntity.Builder<ModuleEntity> {
val modifiable = ModuleEntityImpl.Builder(null)
modifiable.diff = diff
modifiable.snapshot = diff
modifiable.id = createEntityId()
return modifiable
}
override fun createEntity(snapshot: EntityStorage): ModuleEntity {
return getCached(snapshot) {
val entity = ModuleEntityImpl(this)
entity.snapshot = snapshot
entity.id = createEntityId()
entity
}
}
override fun clone(): ModuleEntityData {
val clonedEntity = super.clone()
clonedEntity as ModuleEntityData
clonedEntity.dependencies = clonedEntity.dependencies.toMutableWorkspaceList()
return clonedEntity
}
override fun symbolicId(): SymbolicEntityId<*> {
return ModuleId(name)
}
override fun getEntityInterface(): Class<out WorkspaceEntity> {
return ModuleEntity::class.java
}
override fun serialize(ser: EntityInformation.Serializer) {
}
override fun deserialize(de: EntityInformation.Deserializer) {
}
override fun createDetachedEntity(parents: List<WorkspaceEntity>): WorkspaceEntity {
return ModuleEntity(name, dependencies, entitySource) {
this.type = [email protected]
}
}
override fun getRequiredParents(): List<Class<out WorkspaceEntity>> {
val res = mutableListOf<Class<out WorkspaceEntity>>()
return res
}
override fun equals(other: Any?): Boolean {
if (other == null) return false
if (this.javaClass != other.javaClass) return false
other as ModuleEntityData
if (this.entitySource != other.entitySource) return false
if (this.name != other.name) return false
if (this.type != other.type) return false
if (this.dependencies != other.dependencies) return false
return true
}
override fun equalsIgnoringEntitySource(other: Any?): Boolean {
if (other == null) return false
if (this.javaClass != other.javaClass) return false
other as ModuleEntityData
if (this.name != other.name) return false
if (this.type != other.type) return false
if (this.dependencies != other.dependencies) return false
return true
}
override fun hashCode(): Int {
var result = entitySource.hashCode()
result = 31 * result + name.hashCode()
result = 31 * result + type.hashCode()
result = 31 * result + dependencies.hashCode()
return result
}
override fun hashCodeIgnoringEntitySource(): Int {
var result = javaClass.hashCode()
result = 31 * result + name.hashCode()
result = 31 * result + type.hashCode()
result = 31 * result + dependencies.hashCode()
return result
}
override fun collectClassUsagesData(collector: UsedClassesCollector) {
collector.add(ModuleDependencyItem.Exportable.ModuleDependency::class.java)
collector.add(ModuleDependencyItem.Exportable.LibraryDependency::class.java)
collector.add(LibraryTableId::class.java)
collector.add(LibraryTableId.ModuleLibraryTableId::class.java)
collector.add(ModuleDependencyItem.SdkDependency::class.java)
collector.add(ModuleId::class.java)
collector.add(LibraryTableId.GlobalLibraryTableId::class.java)
collector.add(ModuleDependencyItem::class.java)
collector.add(LibraryId::class.java)
collector.add(ModuleDependencyItem.Exportable::class.java)
collector.add(ModuleDependencyItem.DependencyScope::class.java)
collector.addObject(ModuleDependencyItem.InheritedSdkDependency::class.java)
collector.addObject(ModuleDependencyItem.ModuleSourceDependency::class.java)
collector.addObject(LibraryTableId.ProjectLibraryTableId::class.java)
this.dependencies?.let { collector.add(it::class.java) }
collector.sameForAllEntities = false
}
}
| apache-2.0 | ea5aa06ddc96aa10192da0c5579650a3 | 39.717241 | 174 | 0.631944 | 5.333333 | false | false | false | false |
erdo/asaf-project | example-kt-04retrofit/src/main/java/foo/bar/example/foreretrofitkt/api/CustomGlobalErrorHandler.kt | 1 | 3525 | package foo.bar.example.foreretrofitkt.api
import co.early.fore.kt.core.logging.Logger
import co.early.fore.net.MessageProvider
import com.google.gson.Gson
import foo.bar.example.foreretrofitkt.message.ErrorMessage
import foo.bar.example.foreretrofitkt.message.ErrorMessage.*
import okhttp3.Request
import retrofit2.Response
import java.io.InputStreamReader
import java.io.UnsupportedEncodingException
/**
* You can probably use this class almost as it is for your own app, but you might want to
* customise the behaviour for specific HTTP codes etc, hence it's not in the fore library
*/
class CustomGlobalErrorHandler(private val logWrapper: Logger) : co.early.fore.net.retrofit2.ErrorHandler<ErrorMessage> {
override fun <CE : MessageProvider<ErrorMessage>> handleError(
t: Throwable?,
errorResponse: Response<*>?,
customErrorClazz: Class<CE>?,
originalRequest: Request?
): ErrorMessage {
var message = ERROR_MISC
if (errorResponse != null) {
logWrapper.e("handleError() HTTP:" + errorResponse.code())
when (errorResponse.code()) {
401 -> message = ERROR_SESSION_TIMED_OUT
400, 405 -> message = ERROR_CLIENT
429 -> message = ERROR_RATE_LIMITED
//realise 404 is officially a "client" error, but in my experience if it happens in prod it is usually the fault of the server ;)
404, 500, 503 -> message = ERROR_SERVER
}
if (customErrorClazz != null) {
//let's see if we can get more specifics about the error
message = parseCustomError(message, errorResponse, customErrorClazz)
}
} else {//non HTTP error, probably some connection problem, but might be JSON parsing related also
logWrapper.e("handleError() throwable:$t")
if (t != null) {
message = when (t) {
is com.google.gson.stream.MalformedJsonException -> ERROR_SERVER
is java.net.UnknownServiceException -> ERROR_SECURITY_UNKNOWN
else -> ERROR_NETWORK
}
t.printStackTrace()
}
}
logWrapper.e("handleError() returning:$message")
return message
}
private fun <CE : MessageProvider<ErrorMessage>> parseCustomError(
provisionalErrorMessage: ErrorMessage,
errorResponse: Response<*>,
customErrorClazz: Class<CE>
): ErrorMessage {
val gson = Gson()
var customError: CE? = null
try {
customError = gson.fromJson(InputStreamReader(errorResponse.errorBody()!!.byteStream(), "UTF-8"), customErrorClazz)
} catch (e: UnsupportedEncodingException) {
logWrapper.e("parseCustomError() No more error details", e)
} catch (e: IllegalStateException) {
logWrapper.e("parseCustomError() No more error details", e)
} catch (e: NullPointerException) {
logWrapper.e("parseCustomError() No more error details", e)
} catch (e: com.google.gson.JsonSyntaxException) {//the server probably gave us something that is not JSON
logWrapper.e("parseCustomError() Problem parsing customServerError", e)
return ERROR_SERVER
}
return if (customError == null) {
provisionalErrorMessage
} else {
customError.message
}
}
}
| apache-2.0 | b1968f56ec98c79450f04f575a0caaaa | 33.558824 | 145 | 0.62383 | 4.725201 | false | false | false | false |
kerubistan/kerub | src/main/kotlin/com/github/kerubistan/kerub/utils/ListUtils.kt | 1 | 3893 | package com.github.kerubistan.kerub.utils
import com.github.kerubistan.kerub.model.Entity
import io.github.kerubistan.kroki.collections.concat
operator fun <X, Y> Collection<X>.times(other: Collection<Y>): List<Pair<X, Y>> {
return this.map { x -> other.map { y -> x to y } }.concat()
}
// TODO: USE kroki
inline fun <reified C : Any> Iterable<*>.hasAny(predicate: (C) -> Boolean = { true }) =
this.any { it is C && predicate(it) }
// TODO: USE kroki
inline fun <reified C : Any> Iterable<*>.hasNone(crossinline predicate: (C) -> Boolean = { true }) =
!this.hasAny(predicate)
// move to kroki
inline fun <reified C : Any> Iterable<*>.any() = this.any { it is C }
// move to kroki
inline fun <reified C : Any> Iterable<*>.none() = this.none { it is C }
fun <T> Collection<T>.containsAny(vararg elems: T) =
elems.any {
this.contains(it)
}
fun <K, V : Entity<K>> Collection<V>.toMap(): Map<K, V> =
this.associateBy { it.id }
fun <T> Collection<T>.avgBy(fn: (T) -> Int): Double {
var sum = 0
this.forEach { sum += fn(it) }
return sum.toDouble() / this.size
}
// TODO should be moved to kroki
inline fun <T> List<T>.update(
selector: (T) -> Boolean, default: () -> T = { throw IllegalArgumentException("key not found") }, map: (T) -> T
): List<T> =
this.firstOrNull(selector)?.let {
this.filterNot(selector) + map(it)
} ?: this + map(default())
/**
* Update a list with another, different type of items. Not updated items will remain the same, updates
* not matching a data will be ignored.
* @param updateList a list of elements with which the list is to be updated
* @param selfKey extract the join key from the original list
* @param upKey extract the join key from the update list
* @param merge creates an updated instance from the original
*/
inline fun <T : Any, U : Any, I : Any> List<T>.update(
updateList: List<U>,
selfKey: (T) -> I,
upKey: (U) -> I,
merge: (T, U) -> T
): List<T> = this.update(updateList, selfKey, upKey, merge, { it }, { null })
/**
* Update a list with another, different type of items
* @param updateList a list of elements with which the list is to be updated
* @param selfKey extract the join key from the original list
* @param upKey extract the join key from the update list
* @param merge creates an updated instance from the original
* @param updateMiss handle items that did not get updated
* @param selfMiss handle updates that do not match any data
*/
inline fun <T : Any, U : Any, I : Any> List<T>.update(
updateList: List<U>,
selfKey: (T) -> I,
upKey: (U) -> I,
merge: (T, U) -> T,
updateMiss: (T) -> T?,
selfMiss: (U) -> T?
): List<T> {
val selfMap = this.associateBy(selfKey)
val updateMap = updateList.associateBy(upKey)
return selfMap.map { (key, value) ->
updateMap[key]?.let { merge(value, it) } ?: updateMiss(value)
}.filterNotNull() + updateMap.filterNot { selfMap.containsKey(it.key) }.map {
selfMiss(it.value)
}.filterNotNull()
}
fun <T> List<T>.subLists(minLength: Int = 1, selector: (T) -> Boolean): List<List<T>> {
val ret = mutableListOf<List<T>>()
var start: Int? = null
for (idx in this.indices) {
val match = selector(this[idx])
if (start != null) {
if (!match) {
if (idx - 1 - start > minLength) {
ret += listOf(this.subList(start, idx))
}
start = null
}
} else if (match) {
start = idx
}
}
if (start != null && this.size - 1 - start >= minLength) {
ret += listOf(this.subList(start, this.size + 1))
}
return ret
}
fun <I, E : Entity<I>> Collection<E>.byId() = this.associateBy { it.id }
inline fun <reified C : Any, reified R : Any> Iterable<*>.mapInstances(predicate: (C) -> R?) = this.mapNotNull {
if (it is C) {
predicate(it)
} else null
}
operator fun <T> Collection<T>?.contains(element: T): Boolean =
this?.contains(element) ?: false
| apache-2.0 | f8426f44c84ce3abd94aeac42f06f559 | 31.441667 | 113 | 0.641151 | 3.075039 | false | false | false | false |
odnoklassniki/ok-android-sdk | odnoklassniki-android-sdk/src/main/java/ru/ok/android/sdk/util/Utils.kt | 2 | 3656 | package ru.ok.android.sdk.util
import android.content.Context
import android.os.Handler
import android.os.Looper
import android.provider.Settings
import android.util.Log
import ru.ok.android.sdk.LOG_TAG
import java.lang.IllegalStateException
import java.lang.reflect.InvocationTargetException
import java.security.MessageDigest
object Utils {
private var mainThreadHandler: Handler? = null
fun toMD5(toEncrypt: String): String {
return try {
val digest = MessageDigest.getInstance("md5")
digest.update(toEncrypt.toByteArray())
val bytes = digest.digest()
val sb = StringBuilder()
for (i in bytes.indices) {
sb.append(String.format("%02X", bytes[i]))
}
sb.toString().toLowerCase()
} catch (exc: Exception) {
throw IllegalStateException(exc)
}
}
/**
* Retrieves unique device advertising id (if applicable), or device id (as a fallback)<br></br>
* Required for some methods like sdk.getInstallSource<br></br>
* Could not be called from UI thread, needs wrapping via AsyncTask in this case due to gms restrictions.<br></br>
* WARNING: This requires dependency on 'com.google.android.gms:play-services-ads:8.4.0' to work properly<br></br>
* Consider caching the returning value if the result is needed frequently
*/
@Suppress("unused")
fun getAdvertisingId(context: Context, fallbackToAndroidId: Boolean = false): String {
var advId: String? = null
try {
// here we do AdvertisingIdClient.getAdvertisingIdInfo(context).getId() via reflection in order to
// avoid using extra SDK dependency (gms)
val googlePlayServicesUtil = Class.forName("com.google.android.gms.ads.identifier.AdvertisingIdClient")
val getAdvertisingIdInfo = googlePlayServicesUtil.getMethod("getAdvertisingIdInfo", Context::class.java)
val advertisingIdInfo = getAdvertisingIdInfo.invoke(null, context)
if (advertisingIdInfo != null) {
val getId = advertisingIdInfo.javaClass.getMethod("getId")
advId = getId.invoke(advertisingIdInfo) as String
} else {
Log.d(LOG_TAG, "Requesting advertising info from gms, got null")
}
} catch (e: ClassNotFoundException) {
if (fallbackToAndroidId) {
Log.d(LOG_TAG, "A dependency on com.google.android.gms:play-services-ads is required in order to use Utils.getAdvertisingId, falling back to ANDROID_ID instead")
} else {
throw IllegalStateException("A dependency on com.google.android.gms:play-services-ads is required in order to use Utils.getAdvertisingId")
}
} catch (ignore: NoSuchMethodException) {
} catch (ignore: InvocationTargetException) {
} catch (ignore: IllegalAccessException) {
}
if (advId == null) {
advId = Settings.Secure.getString(context.contentResolver, Settings.Secure.ANDROID_ID)
}
return advId ?: ""
}
fun getMainThreadHandler(): Handler {
if (mainThreadHandler == null) mainThreadHandler = Handler(Looper.getMainLooper())
return mainThreadHandler!!
}
fun isMainThread(): Boolean = Looper.getMainLooper() == Looper.myLooper()
fun executeOnMain(runnable: Runnable) {
if (isMainThread()) runnable.run()
else queueOnMain(runnable)
}
fun queueOnMain(runnable: Runnable, delayMillis: Long = 10) {
getMainThreadHandler().postDelayed(runnable, delayMillis)
}
}
| apache-2.0 | 2b6de669d6dedac043e2667ee9634c9a | 41.022989 | 177 | 0.657823 | 4.581454 | false | false | false | false |
fossasia/rp15 | app/src/main/java/org/fossasia/openevent/general/speakers/SpeakerViewHolder.kt | 2 | 1793 | package org.fossasia.openevent.general.speakers
import android.view.View
import androidx.core.view.isVisible
import androidx.recyclerview.widget.RecyclerView
import com.squareup.picasso.Picasso
import kotlinx.android.synthetic.main.item_speaker.view.shortBioTv
import kotlinx.android.synthetic.main.item_speaker.view.speakerImgView
import kotlinx.android.synthetic.main.item_speaker.view.speakerNameTv
import kotlinx.android.synthetic.main.item_speaker.view.speakerOrgTv
import org.fossasia.openevent.general.CircleTransform
import org.fossasia.openevent.general.R
import org.fossasia.openevent.general.common.SpeakerClickListener
import org.fossasia.openevent.general.utils.Utils
import org.fossasia.openevent.general.utils.nullToEmpty
import org.fossasia.openevent.general.utils.stripHtml
import timber.log.Timber
class SpeakerViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
var speakerClickListener: SpeakerClickListener? = null
fun bind(speaker: Speaker) {
itemView.speakerNameTv.text = speaker.name
itemView.speakerOrgTv.text = speaker.organisation
val shortBio = speaker.shortBiography.nullToEmpty().stripHtml()
when (shortBio.isNullOrBlank()) {
true -> itemView.shortBioTv.isVisible = false
false -> itemView.shortBioTv.text = shortBio
}
Picasso.get()
.load(speaker.photoUrl)
.placeholder(Utils.requireDrawable(itemView.context, R.drawable.ic_account_circle_grey))
.transform(CircleTransform())
.into(itemView.speakerImgView)
itemView.setOnClickListener {
speakerClickListener?.onClick(speaker.id)
?: Timber.e("Speaker Click listener on ${this::class.java.canonicalName} is null")
}
}
}
| apache-2.0 | c27da5c274879cb2938134975d8625fb | 40.697674 | 100 | 0.750697 | 4.29976 | false | false | false | false |
pvarry/intra42 | app/src/main/java/com/paulvarry/intra42/ui/galaxy/TextCalculator.kt | 1 | 3178 | package com.paulvarry.intra42.ui.galaxy
import android.graphics.Paint
import com.paulvarry.intra42.ui.galaxy.model.ProjectDataIntra
import java.util.*
import kotlin.math.roundToInt
object TextCalculator {
internal fun split(projectData: ProjectDataIntra, paintText: Paint, scale: Float): List<String> {
val oldTextSize = paintText.textSize
paintText.textSize = oldTextSize * 1.05f // make text just a little bit bigger to avoid text glued to the border
val projectWidth = projectData.kind!!.data.textWidth * scale // size of the preferable draw space
val textWidth = paintText.measureText(projectData.name) // size of the entire text
val textToDraw = ArrayList<String>()
if (projectWidth != -1f && projectWidth < textWidth) {
val numberCut = (textWidth / projectWidth).roundToInt() + 1
var tmpText = projectData.name ?: ""
var posToCut = tmpText.length / numberCut
var i = 0
while (true) {
posToCut = splitAt(tmpText, posToCut)
if (posToCut == -1) {
textToDraw.add(tmpText)
break
}
tmpText = if (tmpText[posToCut] == ' ') {
textToDraw.add(tmpText.substring(0, posToCut))
tmpText.substring(posToCut + 1)
} else {
textToDraw.add(tmpText.substring(0, posToCut + 1))
tmpText.substring(posToCut + 1)
}
tmpText = tmpText.trim { it <= ' ' }
i++
posToCut = tmpText.length / (numberCut - i)
}
} else
textToDraw.add(projectData.name ?: "")
paintText.textSize = oldTextSize
return textToDraw
}
private fun splitAt(stringToSplit: String?, posSplit: Int): Int {
if (posSplit < 0 || stringToSplit == null || stringToSplit.length <= posSplit)
return -1
if (isSplittablePos(stringToSplit, posSplit))
return posSplit
val stringLength = stringToSplit.length
var searchShift = 0
var pursueBefore = true
var pursueAfter = true
while (pursueBefore || pursueAfter) {
if (pursueBefore && posSplit - searchShift >= 0) {
if (isSplittablePos(stringToSplit, posSplit - searchShift))
return posSplit - searchShift
} else
pursueBefore = false
if (pursueAfter && posSplit + searchShift < stringLength) {
if (isSplittablePos(stringToSplit, posSplit + searchShift))
return posSplit + searchShift
} else
pursueAfter = false
searchShift++
}
return -1
}
private fun isSplittablePos(str: String, index: Int): Boolean {
if (index <= 1 || index >= str.length - 2)
// a single char can't be split apart.
return false
val c = str[index]
return if (c == ' ' || c == '-' || c == '_') index > 2 && index < str.length - 3 || str.length >= 8 else false
}
} | apache-2.0 | 062d164dbe488ebbf95c085c27dc08fa | 34.322222 | 120 | 0.559157 | 4.37741 | false | false | false | false |
bropane/Job-Seer | app/src/main/java/com/taylorsloan/jobseer/data/job/repo/JobRepositoryImpl.kt | 1 | 1810 | package com.taylorsloan.jobseer.data.job.repo
import com.taylorsloan.jobseer.data.DataModuleImpl
import com.taylorsloan.jobseer.data.common.model.DataResult
import com.taylorsloan.jobseer.data.job.local.service.JobDao
import com.taylorsloan.jobseer.data.job.repo.sources.DataSourceFactory
import com.taylorsloan.jobseer.domain.job.models.Job
import io.reactivex.Flowable
import javax.inject.Inject
/**
* Implementation of a job repository
* Created by taylo on 10/29/2017.
*/
class JobRepositoryImpl : JobRepository {
@Inject
lateinit var jobDao : JobDao
init {
DataModuleImpl.storageComponent().inject(this)
}
private val dataSourceFactory = DataSourceFactory(DataModuleImpl)
override fun getJobs(description: String?,
location: String?,
lat: Double?,
long: Double?,
fullTime: Boolean?,
saved: Boolean?): Flowable<DataResult<List<Job>>> =
dataSourceFactory.jobs(description = description,
location = location,
fullTime = fullTime,
saved = saved)
override fun getMoreJobs(page: Int){
dataSourceFactory.getMoreJobs(page)
}
override fun getJob(id: String): Flowable<DataResult<Job>> = dataSourceFactory.job(id)
override fun saveJob(id: String) {
jobDao.saveJob(1, id)
}
override fun getSavedJobs(description: String?, location: String?, fullTime: Boolean?): Flowable<DataResult<List<Job>>> {
return dataSourceFactory.savedJobs(description, location, fullTime)
}
override fun unsaveJob(id: String) {
jobDao.saveJob(0, id)
}
override fun clearJobs() {
dataSourceFactory.clearJobs()
}
} | mit | d9f7dc9fa61be34af649bf127f666fb1 | 30.224138 | 125 | 0.653039 | 4.513716 | false | false | false | false |
EMResearch/EvoMaster | e2e-tests/spring-rest-openapi-v3/src/main/kotlin/com/foo/rest/examples/spring/openapi/v3/extraquery/ExtraQueryRest.kt | 1 | 2296 | package com.foo.rest.examples.spring.openapi.v3.extraquery
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.PostMapping
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RestController
import java.net.URLDecoder
import javax.servlet.http.HttpServletRequest
@RestController
@RequestMapping(path = ["/api/extraquery"])
class ExtraQueryRest {
@GetMapping("servlet")
open fun servlet(hr: HttpServletRequest): String {
val a = hr.parameterMap["a"]!![0]
return if (a == null) {
"FALSE"
} else "OK"
}
@GetMapping("proxyprint")
open fun proxyprint(hr: HttpServletRequest): String {
val map = hr.parameterMap
val payerEmail= map["payer_email"]!![0]
val quantity= java.lang.Double.valueOf(map["mc_gross"]!![0])
val paymentStatus= map["payment_status"]!![0]
return if (payerEmail == null || quantity== null || paymentStatus == null) {
"FALSE"
} else "OK"
}
@GetMapping("languagetool")
open fun languagetool(hr: HttpServletRequest): String {
val query = hr.queryString
val params = getParameterMap(query)
val a = params["a"]
return if (a == null) {
"FALSE"
} else "OK"
}
@PostMapping
open fun post(){
//nothing needed to do, just make sure hidden filter is used
}
private fun getParameterMap(query: String): Map<String, String> {
val pairs = query.split("&".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()
val parameters: MutableMap<String, String> = HashMap()
for (pair: String in pairs) {
val delimPos = pair.indexOf('=')
if (delimPos != -1) {
val param = pair.substring(0, delimPos)
val key = URLDecoder.decode(param, "utf-8")
try {
parameters[key] = URLDecoder.decode(pair.substring(delimPos + 1), "utf-8")
} catch (e: IllegalArgumentException) {
throw RuntimeException("Could not decode query. Query length: " + query.length, e)
}
}
}
return parameters
}
} | lgpl-3.0 | 41dba46ddf1fe28af71dc5886b9d9ed4 | 30.465753 | 102 | 0.606707 | 4.291589 | false | false | false | false |
savoirfairelinux/ring-client-android | ring-android/app/src/main/java/cx/ring/account/ChangePasswordDialog.kt | 1 | 4663 | /*
* Copyright (C) 2004-2021 Savoir-faire Linux Inc.
*
* Author: Adrien Beraud <[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 cx.ring.account
import android.app.Dialog
import android.content.DialogInterface
import android.os.Bundle
import android.view.KeyEvent
import android.view.View
import android.view.WindowManager
import android.view.inputmethod.EditorInfo
import android.widget.TextView
import androidx.appcompat.app.AlertDialog
import androidx.fragment.app.DialogFragment
import com.google.android.material.dialog.MaterialAlertDialogBuilder
import cx.ring.R
import cx.ring.databinding.DialogSetPasswordBinding
class ChangePasswordDialog : DialogFragment() {
private var mListener: PasswordChangedListener? = null
private var binding: DialogSetPasswordBinding? = null
fun setListener(listener: PasswordChangedListener?) {
mListener = listener
}
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
binding = DialogSetPasswordBinding.inflate(requireActivity().layoutInflater)
val hasPassword = arguments?.getBoolean(AccountEditionFragment.ACCOUNT_HAS_PASSWORD_KEY, true) ?: true
val passwordMessage = if (hasPassword) R.string.account_password_change else R.string.account_password_set
binding!!.oldPasswordTxtBox.visibility = if (hasPassword) View.VISIBLE else View.GONE
binding!!.newPasswordRepeatTxt.setOnEditorActionListener { v: TextView?, actionId: Int, event: KeyEvent? ->
if (actionId == EditorInfo.IME_ACTION_DONE) {
if (validate()) {
dialog!!.dismiss()
return@setOnEditorActionListener true
}
}
false
}
val result = MaterialAlertDialogBuilder(requireContext())
.setView(binding!!.root)
.setMessage(R.string.help_password_choose)
.setTitle(passwordMessage)
.setPositiveButton(passwordMessage, null) //Set to null. We override the onclick
.setNegativeButton(android.R.string.cancel) { dialog: DialogInterface?, whichButton: Int -> dismiss() }
.create()
result.setOnShowListener { dialog: DialogInterface ->
val positiveButton = (dialog as AlertDialog).getButton(AlertDialog.BUTTON_POSITIVE)
positiveButton.setOnClickListener {
if (validate()) {
dismiss()
}
}
}
result.window!!.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE or WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE)
return result
}
private fun checkInput(): Boolean {
if (!binding!!.newPasswordTxt.text.toString().contentEquals(binding!!.newPasswordRepeatTxt.text)) {
binding!!.newPasswordTxtBox.isErrorEnabled = true
binding!!.newPasswordTxtBox.error = getText(R.string.error_passwords_not_equals)
binding!!.newPasswordRepeatTxtBox.isErrorEnabled = true
binding!!.newPasswordRepeatTxtBox.error = getText(R.string.error_passwords_not_equals)
return false
} else {
binding!!.newPasswordTxtBox.isErrorEnabled = false
binding!!.newPasswordTxtBox.error = null
binding!!.newPasswordRepeatTxtBox.isErrorEnabled = false
binding!!.newPasswordRepeatTxtBox.error = null
}
return true
}
private fun validate(): Boolean {
if (checkInput() && mListener != null) {
val oldPassword = binding!!.oldPasswordTxt.text.toString()
val newPassword = binding!!.newPasswordTxt.text.toString()
mListener!!.onPasswordChanged(oldPassword, newPassword)
return true
}
return false
}
interface PasswordChangedListener {
fun onPasswordChanged(oldPassword: String, newPassword: String)
}
companion object {
val TAG = ChangePasswordDialog::class.simpleName!!
}
} | gpl-3.0 | 75d7dab463302aadb72ef872ab7fccd5 | 42.185185 | 148 | 0.685396 | 4.929175 | false | false | false | false |
savoirfairelinux/ring-client-android | ring-android/libjamiclient/src/main/kotlin/net/jami/account/JamiAccountConnectPresenter.kt | 1 | 2526 | /*
* Copyright (C) 2004-2021 Savoir-faire Linux Inc.
*
* Author: Hadrien De Sousa <[email protected]>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
package net.jami.account
import net.jami.model.AccountCreationModel
import net.jami.mvp.RootPresenter
import net.jami.utils.StringUtils
import javax.inject.Inject
class JamiAccountConnectPresenter @Inject constructor() : RootPresenter<JamiConnectAccountView>() {
private var mAccountCreationModel: AccountCreationModel? = null
fun init(accountCreationModel: AccountCreationModel?) {
mAccountCreationModel = accountCreationModel
if (mAccountCreationModel == null) {
view?.cancel()
return
}
/*boolean hasArchive = mAccountCreationModel.getArchive() != null;
JamiConnectAccountView view = getView();
if (view != null) {
view.showPin(!hasArchive);
view.enableLinkButton(hasArchive);
}*/
}
fun passwordChanged(password: String) {
mAccountCreationModel!!.password = password
showConnectButton()
}
fun usernameChanged(username: String) {
mAccountCreationModel!!.username = username
showConnectButton()
}
fun serverChanged(server: String?) {
mAccountCreationModel!!.managementServer = server
showConnectButton()
}
fun connectClicked() {
if (isFormValid) {
view?.createAccount(mAccountCreationModel!!)
}
}
private fun showConnectButton() {
view?.enableConnectButton(isFormValid)
}
private val isFormValid: Boolean
get() = !StringUtils.isEmpty(mAccountCreationModel!!.password)
&& !StringUtils.isEmpty(mAccountCreationModel!!.username)
&& !StringUtils.isEmpty(mAccountCreationModel!!.managementServer)
} | gpl-3.0 | 20d90ed7f2b88b03cd92577521434717 | 34.097222 | 99 | 0.689232 | 4.543165 | false | false | false | false |
OpenConference/OpenConference-android | app/src/main/java/com/openconference/util/picasso/PicassoScrollListener.kt | 1 | 1324 | package com.openconference.util.picasso
import android.support.v7.widget.RecyclerView
import com.squareup.picasso.Picasso
/**
* This is a scroll listener that listens for scroll events on recyclerviews
* to avoid picasso loading images while scrolling (avoid laggy scroll behavior)
*/
class PicassoScrollListener(private val picasso: Picasso) : RecyclerView.OnScrollListener() {
companion object {
val TAG = "PicassoScrollTag"
}
private var previousScrollState = RecyclerView.SCROLL_STATE_IDLE
private var scrollingFirstTime = true
init {
picasso.resumeTag(TAG)
}
override fun onScrollStateChanged(view: RecyclerView?, scrollState: Int) {
if (scrollingFirstTime) {
resume()
scrollingFirstTime = false
}
// TO the picasso staff
if (!isScrolling(scrollState) && isScrolling(previousScrollState)) {
resume()
}
if (isScrolling(scrollState) && !isScrolling(previousScrollState)) {
pause()
}
previousScrollState = scrollState
}
private inline fun isScrolling(scrollState: Int): Boolean {
return scrollState == RecyclerView.SCROLL_STATE_DRAGGING || scrollState == RecyclerView.SCROLL_STATE_SETTLING
}
private inline fun resume() {
picasso.resumeTag(TAG)
}
private inline fun pause() {
picasso.pauseTag(TAG)
}
} | apache-2.0 | 254ec1c1187db3c4293378ece1db74f3 | 23.537037 | 113 | 0.719789 | 4.645614 | false | false | false | false |
jrenner/kotlin-voxel | core/src/main/kotlin/org/jrenner/learngl/gameworld/ChunkMesh.kt | 1 | 7813 | package org.jrenner.learngl.gameworld
import com.badlogic.gdx.graphics.Mesh
import com.badlogic.gdx.graphics.VertexAttributes.Usage
import com.badlogic.gdx.graphics.VertexAttribute
import com.badlogic.gdx.math.Vector3
import com.badlogic.gdx.utils.GdxRuntimeException
import org.jrenner.learngl.cube.CubeDataGrid
import com.badlogic.gdx.math.Vector2
import kotlin.properties.Delegates
import org.jrenner.learngl.Direction
class ChunkMesh() {
companion object {
private val cubeRectData = RectData()
private val POSITION_COMPONENTS = 3
//private val COLOR_COMPONENTS = 4
private val TEXTURE_COORDS = 2
private val NORMAL_COMPONENTS = 3
private val NUM_COMPONENTS = POSITION_COMPONENTS + TEXTURE_COORDS + NORMAL_COMPONENTS
private val VERTS_PER_TRI = 3
private val TRIS_PER_FACE = 2
private val FACES_PER_CUBE = 6
private val CUBE_SIZE = 1f
val MAX_VERTS = VERTS_PER_TRI * TRIS_PER_FACE * FACES_PER_CUBE * (Chunk.chunkSize * Chunk.chunkSize * Chunk.chunkSize) * NUM_COMPONENTS
val verts = FloatArray(MAX_VERTS)
}
//private val PRIMITIVE_SIZE = 3 * NUM_COMPONENTS
private var cdg: CubeDataGrid by Delegates.notNull()
var numCubes = 0
var numFaces = 0
var numTris = 0
var numVerts = 0
var numFloats = 0
fun reset(cdg: CubeDataGrid) {
this.cdg = cdg
numCubes = cdg.numberOfNonVoidCubes()
numFaces = FACES_PER_CUBE * numCubes - cdg.numberOfHiddenFaces()
numTris = numFaces * TRIS_PER_FACE
numVerts = numTris * VERTS_PER_TRI
numFloats = numVerts * NUM_COMPONENTS
}
private var cubesCreated = 0
private var idx = 0
private var triangles = 0
var vertexCount = 0
var hasMesh = false
fun resetMesh() {
if (hasMesh) {
mesh.dispose()
}
mesh = Mesh(true, numVerts, 0,
VertexAttribute(Usage.Position, POSITION_COMPONENTS, "a_position"),
//VertexAttribute(Usage.ColorUnpacked, COLOR_COMPONENTS, "a_color"),
VertexAttribute(Usage.TextureCoordinates, TEXTURE_COORDS, "a_textureCoords"),
VertexAttribute(Usage.Normal, NORMAL_COMPONENTS, "a_normal"))
hasMesh = true
}
var mesh: Mesh by Delegates.notNull()
// EXPERIMENTAL: re-use the same mesh to avoid diposal peformance cost
// the downside is that every mesh will be of max size = MAX_VERTS, ballooning native memory
/*val mesh = Mesh(true, MAX_VERTS, 0,
VertexAttribute(Usage.Position, POSITION_COMPONENTS, "a_position"),
//VertexAttribute(Usage.ColorUnpacked, COLOR_COMPONENTS, "a_color"),
VertexAttribute(Usage.TextureCoordinates, TEXTURE_COORDS, "a_textureCoords"),
VertexAttribute(Usage.Normal, NORMAL_COMPONENTS, "a_normal"))
fun resetMesh() {
// do nothing
}*/
var started = false
private fun start() {
if (started) throw GdxRuntimeException("call end() first!")
started = true
idx = 0
triangles = 0
cubesCreated = 0
vertexCount = 0
}
fun buildMesh() {
resetMesh()
start()
for (cubeData in cdg) {
//println("create cube at: ${cubeData.position.fmt}")
//println("cube: ${cubeData.cubeType}")
if (cubeData.cubeType != CubeType.Void) {
addCube(cubeData.getPositionTempVec(), CUBE_SIZE, cubeData.hiddenFaces)
}
}
end()
}
private fun end() {
if (!started) throw GdxRuntimeException("call start() first!")
/* if (cubesCreated != NUM_CUBES) {
throw GdxRuntimeException("cubes created (${cubesCreated}) is not equal to NUM_CUBES (${NUM_CUBES})")
}*/
/* if (vertexCount != NUM_VERTS) {
throw GdxRuntimeException("vertexCount ($vertexCount) != NUM_VERTS ($NUM_VERTS)")
}*/
started = false
mesh.setVertices(verts, 0, numFloats);
//mesh.updateVertices(0, verts, 0, numFloats)
}
private fun addRect(rv: RectData) {
triangle(rv.v00, rv.v10, rv.v11, rv.normal, rv.uv00, rv.uv10, rv.uv11)
triangle(rv.v00, rv.v11, rv.v01, rv.normal, rv.uv00, rv.uv11, rv.uv01)
}
private fun addCube(origin: Vector3, sz: Float, hiddenBitwise: Int) {
cubesCreated++
val r = cubeRectData
val n = 1f
r.uv00.set(0f, n)
r.uv10.set(n, n)
r.uv11.set(n, 0f)
r.uv01.set(0f, 0f)
/*var hiddenFaces = 0
for (dir in array(NORTH, SOUTH, EAST, WEST, UP, DOWN)) {
if (hiddenBitwise and dir != 0) {
hiddenFaces++
}
}
println("hidden faces for cube: $hiddenFaces")*/
if (hiddenBitwise and Direction.North == 0) {
r.v00.set(0f, 0f, sz).add(origin)
r.v10.set(sz, 0f, sz).add(origin)
r.v11.set(sz, sz, sz).add(origin)
r.v01.set(0f, sz, sz).add(origin)
r.normal.set(0f, 0f, 1f)
addRect(r)
}
if (hiddenBitwise and Direction.South == 0) {
r.v00.set(sz, 0f, 0f).add(origin)
r.v10.set(0f, 0f, 0f).add(origin)
r.v11.set(0f, sz, 0f).add(origin)
r.v01.set(sz, sz, 0f).add(origin)
r.normal.set(0f, 0f, -1f)
addRect(r)
}
if (hiddenBitwise and Direction.Down == 0) {
r.v00.set(0f, 0f, 0f).add(origin)
r.v10.set(sz, 0f, 0f).add(origin)
r.v11.set(sz, 0f, sz).add(origin)
r.v01.set(0f, 0f, sz).add(origin)
r.normal.set(0f, -1f, 0f)
addRect(r)
}
if (hiddenBitwise and Direction.Up == 0) {
r.v00.set(sz, sz, 0f).add(origin)
r.v10.set(0f, sz, 0f).add(origin)
r.v11.set(0f, sz, sz).add(origin)
r.v01.set(sz, sz, sz).add(origin)
r.normal.set(0f, 1f, 0f)
addRect(r)
}
if (hiddenBitwise and Direction.West == 0) {
r.v00.set(0f, 0f, 0f).add(origin)
r.v10.set(0f, 0f, sz).add(origin)
r.v11.set(0f, sz, sz).add(origin)
r.v01.set(0f, sz, 0f).add(origin)
r.normal.set(-1f, 0f, 0f)
addRect(r)
}
if (hiddenBitwise and Direction.East == 0) {
r.v00.set(sz, 0f, sz).add(origin)
r.v10.set(sz, 0f, 0f).add(origin)
r.v11.set(sz, sz, 0f).add(origin)
r.v01.set(sz, sz, sz).add(origin)
r.normal.set(1f, 0f, 0f)
addRect(r)
}
}
private fun triangle(a: Vector3, b: Vector3, c: Vector3, nor: Vector3, uvA: Vector2, uvB: Vector2, uvC: Vector2) {
triangles++
vertex(a, nor, uvA)
vertex(b, nor, uvB)
vertex(c, nor, uvC)
}
private fun vertex(v: Vector3, nor: Vector3, uv: Vector2) {
vertexCount++
// POSITION
verts[idx++] = v.x
verts[idx++] = v.y
verts[idx++] = v.z
// TEXTURE_UV
verts[idx++] = uv.x
verts[idx++] = uv.y
// NORMAL
verts[idx++] = nor.x
verts[idx++] = nor.y
verts[idx++] = nor.z
}
fun dispose() {
mesh.dispose()
}
}
class RectData() {
val v00 = Vector3()
val v10 = Vector3()
val v01 = Vector3()
val v11 = Vector3()
val normal = Vector3()
val uv00 = Vector2()
val uv10 = Vector2()
val uv01 = Vector2()
val uv11 = Vector2()
}
| apache-2.0 | 036d7c90e23c08f3f858ed5b47379d5e | 30.285124 | 143 | 0.548189 | 3.503587 | false | false | false | false |
hzsweers/palettehelper | palettehelper/src/main/java/io/sweers/palettehelper/BugsnagTree.kt | 1 | 1757 | package io.sweers.palettehelper
import android.util.Log
import com.bugsnag.android.Bugsnag
import com.bugsnag.android.Error
import timber.log.Timber
import java.util.ArrayDeque
import java.util.Deque
/**
* A logging implementation which buffers the last 200 messages and notifies on error exceptions.
*
* Borrowed from here: https://github.com/JakeWharton/Telecine/blob/master/telecine/src/main/java/com/jakewharton/telecine/BugsnagTree.java
*/
final class BugsnagTree: Timber.Tree() {
companion object {
private val BUFFER_SIZE = 200
private fun priorityToString(priority: Int): String {
when (priority) {
Log.ERROR -> return "E"
Log.WARN -> return "W"
Log.INFO -> return "I"
Log.DEBUG -> return "D"
else -> return java.lang.String.valueOf(priority)
}
}
}
// Adding one to the initial size accounts for the add before remove.
private val buffer: Deque<String> = ArrayDeque(BUFFER_SIZE + 1)
override fun log(priority: Int, tag: String?, message: String?, t: Throwable?) {
var adjustedMessage = "${System.currentTimeMillis()} ${priorityToString(priority)} $message"
synchronized (buffer) {
buffer.addLast(adjustedMessage);
if (buffer.size > BUFFER_SIZE) {
buffer.removeFirst();
}
}
if (t != null && priority == Log.ERROR) {
Bugsnag.notify(t);
}
}
public fun update(error: Error) {
synchronized (buffer) {
for ((i, message) in buffer.withIndex()) {
error.addToTab("Log", java.lang.String.format("%03d", i + 1), message);
}
}
}
}
| apache-2.0 | befb3a89234b5a4d757a32efeea2a105 | 32.150943 | 139 | 0.602163 | 4.264563 | false | false | false | false |
joseph-roque/BowlingCompanion | app/src/main/java/ca/josephroque/bowlingcompanion/common/fragments/TabbedFragment.kt | 1 | 4252 | package ca.josephroque.bowlingcompanion.common.fragments
import android.content.Context
import android.os.Bundle
import android.support.design.widget.TabLayout
import android.support.v4.app.FragmentPagerAdapter
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import ca.josephroque.bowlingcompanion.R
import ca.josephroque.bowlingcompanion.common.interfaces.IFloatingActionButtonHandler
import ca.josephroque.bowlingcompanion.common.interfaces.IRefreshable
import kotlinx.android.synthetic.main.fragment_common_tabs.tabbed_fragment_pager as fragmentPager
import kotlinx.android.synthetic.main.fragment_common_tabs.view.*
/**
* Copyright (C) 2018 Joseph Roque
*
* Base implementation for a fragment with tabs.
*/
abstract class TabbedFragment : BaseFragment(),
IFloatingActionButtonHandler,
IRefreshable {
companion object {
@Suppress("unused")
private const val TAG = "TabbedFragment"
}
protected var currentTab: Int
get() = fragmentPager?.currentItem ?: 0
set(value) { fragmentPager?.currentItem = value }
private var delegate: TabbedFragmentDelegate? = null
// MARK: Lifecycle functions
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
val rootView = inflater.inflate(R.layout.fragment_common_tabs, container, false)
configureTabLayout(rootView)
return rootView
}
override fun onAttach(context: Context?) {
super.onAttach(context)
context as? TabbedFragmentDelegate ?: throw RuntimeException("${context!!} must implement TabbedFragmentDelegate")
delegate = context
}
override fun onDetach() {
super.onDetach()
delegate = null
}
// MARK: TabbedFragment
fun resetTabLayout() {
configureTabLayout(view!!)
}
fun refreshTabs(ignored: Set<Int> = HashSet()) {
val adapter = fragmentPager.adapter as? FragmentPagerAdapter
adapter?.let {
for (i in 0 until it.count) {
if (ignored.contains(i)) {
continue
}
val fragment = findFragmentByPosition(i) as? IRefreshable
fragment?.refresh()
}
}
}
abstract fun addTabs(tabLayout: TabLayout)
abstract fun buildPagerAdapter(tabCount: Int): FragmentPagerAdapter
abstract fun handleTabSwitch(newTab: Int)
fun findFragmentByPosition(position: Int): BaseFragment? {
val fragmentPagerAdapter = fragmentPager.adapter as? FragmentPagerAdapter ?: return null
val tag = "android:switcher:${fragmentPager.id}:${fragmentPagerAdapter.getItemId(position)}"
return childFragmentManager.findFragmentByTag(tag) as? BaseFragment
}
// MARK: Private functions
private fun configureTabLayout(rootView: View) {
rootView.tabbed_fragment_tabs.removeAllTabs()
addTabs(rootView.tabbed_fragment_tabs)
rootView.tabbed_fragment_pager.scrollingEnabled = false
val adapter = buildPagerAdapter(rootView.tabbed_fragment_tabs.tabCount)
rootView.tabbed_fragment_pager.adapter = adapter
rootView.tabbed_fragment_pager.addOnPageChangeListener(TabLayout.TabLayoutOnPageChangeListener(rootView.tabbed_fragment_tabs))
rootView.tabbed_fragment_tabs.addOnTabSelectedListener(object : TabLayout.OnTabSelectedListener {
override fun onTabSelected(tab: TabLayout.Tab) {
rootView.tabbed_fragment_pager.currentItem = tab.position
handleTabSwitch(tab.position)
delegate?.onTabSwitched()
}
override fun onTabUnselected(tab: TabLayout.Tab) {}
override fun onTabReselected(tab: TabLayout.Tab) {}
})
}
// MARK: IRefreshable
override fun refresh() {
refreshTabs()
}
// MARK: BaseFragment
override fun popChildFragment(): Boolean {
val fragment = findFragmentByPosition(currentTab)
return fragment?.popChildFragment() ?: super.popChildFragment()
}
// MARK: TabbedFragmentDelegate
interface TabbedFragmentDelegate {
fun onTabSwitched()
}
}
| mit | 86b7c5356e540fcc020eb60444b8af36 | 32.21875 | 134 | 0.693791 | 5.049881 | false | false | false | false |
DVT/showcase-android | app/src/main/kotlin/za/co/dvt/android/showcase/model/AppModel.kt | 1 | 615 | package za.co.dvt.android.showcase.model
import android.support.annotation.Keep
@Keep
data class AppModel(var id: String? = null,
var name: String? = null,
var shortDescription: String? = null,
var enabled: Boolean = false,
var iconUrl: String? = null,
var functionality: String? = null,
var technologyUsed: String? = null,
var client: String? = null,
var androidPackageName: String? = null,
var screenshots: List<String>? = null)
| apache-2.0 | 848456977054ea0db816e3096dbbedce | 35.176471 | 59 | 0.525203 | 4.92 | false | false | false | false |
BoD/CountdownWidget | handheld/src/main/kotlin/org/jraf/android/countdownwidget/util/ViewUtil.kt | 1 | 1757 | /*
* This source is part of the
* _____ ___ ____
* __ / / _ \/ _ | / __/___ _______ _
* / // / , _/ __ |/ _/_/ _ \/ __/ _ `/
* \___/_/|_/_/ |_/_/ (_)___/_/ \_, /
* /___/
* repository.
*
* Copyright (C) 2014-present Benoit 'BoD' Lubek ([email protected])
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.jraf.android.countdownwidget.util
import android.graphics.Bitmap
import android.graphics.Canvas
import android.view.View
fun View.toBitmap(widthPx: Int, heightPx: Int): Bitmap {
val widthMeasureSpec = View.MeasureSpec.makeMeasureSpec(widthPx, View.MeasureSpec.EXACTLY)
val heightMeasureSpec = View.MeasureSpec.makeMeasureSpec(heightPx, View.MeasureSpec.EXACTLY)
measure(widthMeasureSpec, heightMeasureSpec)
layout(0, 0, measuredWidth, measuredHeight)
val res = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888)
val canvas = Canvas(res)
canvas.translate((-scrollX).toFloat(), (-scrollY).toFloat())
// Drawable bgDrawable = view.getBackground();
// if (bgDrawable != null) bgDrawable.draw(canvas);
draw(canvas)
return res
}
| gpl-3.0 | 37fb0f69c5ceca8100044d192b08f9c3 | 39.860465 | 96 | 0.659078 | 4.124413 | false | false | false | false |
HelloHuDi/usb-with-serial-port | usbserialport/src/main/java/com/hd/serialport/param/UsbMeasureParameter.kt | 1 | 1143 | package com.hd.serialport.param
import com.hd.serialport.config.UsbPortDeviceType
/**
* Created by hd on 2017/8/22 .
* Sets various serial port parameters.
* @param usbPortDeviceType set usb type [UsbPortDeviceType]
* @param baudRate baud rate as an integer, for example {@code 115200}.
* @param dataBits one of {@link UsbSerialPort#DATABITS_5}, {@link UsbSerialPort#DATABITS_6},
* {@link UsbSerialPort#DATABITS_7}, or {@link UsbSerialPort#DATABITS_8}.
* @param stopBits one of {@link UsbSerialPort#STOPBITS_1}, {@link UsbSerialPort#STOPBITS_1_5}, or
* {@link UsbSerialPort#STOPBITS_2}.
* @param parity one of {@link UsbSerialPort#PARITY_NONE}, {@link UsbSerialPort#PARITY_ODD},
* {@link UsbSerialPort#PARITY_EVEN}, {@link UsbSerialPort#PARITY_MARK}, or
* {@link UsbSerialPort#PARITY_SPACE}.
* @param tag set tag
*/
data class UsbMeasureParameter(var usbPortDeviceType: UsbPortDeviceType?=UsbPortDeviceType.USB_OTHERS,
var baudRate: Int = 115200, var dataBits: Int = 8, var stopBits: Int = 1,
var parity: Int = 0,var tag : Any?="default_usb_tag"):MeasureParameter() | apache-2.0 | 41b1ca71add715666886baead0f91df2 | 51 | 104 | 0.704287 | 3.506135 | false | false | false | false |
google/xplat | j2kt/jre/java/native/java/util/Comparator.kt | 1 | 3181 | /*
* Copyright 2022 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package java.util
import java.util.function.Function
import java.util.function.ToDoubleFunction
import java.util.function.ToIntFunction
import java.util.function.ToLongFunction
import kotlin.comparisons.reversed as default_reversed
fun interface Comparator<T> : kotlin.Comparator<T> {
override fun compare(a: T, b: T): Int
fun reversed(): kotlin.Comparator<T> = default_reversed()
fun thenComparing(other: kotlin.Comparator<in T>): kotlin.Comparator<T> = then(other)
fun <U> thenComparing(
keyExtractor: Function<in T, out U>,
keyComparator: kotlin.Comparator<in U>
): kotlin.Comparator<T> = thenBy(keyComparator, keyExtractor::apply)
fun <U : Comparable<U>> thenComparing(keyExtractor: Function<in T, out U>): kotlin.Comparator<T> =
thenBy(keyExtractor::apply)
fun thenComparingInt(keyExtractor: ToIntFunction<in T>): kotlin.Comparator<T> =
then(comparingInt(keyExtractor))
fun thenComparingLong(keyExtractor: ToLongFunction<in T>): kotlin.Comparator<T> =
then(comparingLong(keyExtractor))
fun thenComparingDouble(keyExtractor: ToDoubleFunction<in T>): kotlin.Comparator<T> =
then(comparingDouble(keyExtractor))
companion object {
fun <T, U> comparing(
keyExtractor: Function<in T, out U>,
keyComparator: kotlin.Comparator<in U>
): kotlin.Comparator<T> = compareBy(keyComparator, keyExtractor::apply)
fun <T, U : Comparable<U>> comparing(
keyExtractor: Function<in T, out U>
): kotlin.Comparator<T> = compareBy(naturalOrder(), keyExtractor::apply)
fun <T> comparingDouble(keyExtractor: ToDoubleFunction<in T>): kotlin.Comparator<T> =
Comparator<T> { a, b ->
keyExtractor.applyAsDouble(a).compareTo(keyExtractor.applyAsDouble(b))
}
fun <T> comparingInt(keyExtractor: ToIntFunction<in T>): kotlin.Comparator<T> =
Comparator<T> { a, b -> keyExtractor.applyAsInt(a).compareTo(keyExtractor.applyAsInt(b)) }
fun <T> comparingLong(keyExtractor: ToLongFunction<in T>): kotlin.Comparator<T> =
Comparator<T> { a, b -> keyExtractor.applyAsLong(a).compareTo(keyExtractor.applyAsLong(b)) }
fun <T> nullsFirst(comparator: kotlin.Comparator<in T>): kotlin.Comparator<T?> =
kotlin.comparisons.nullsFirst(comparator)
fun <T> nullsLast(comparator: kotlin.Comparator<in T>): kotlin.Comparator<T?> =
kotlin.comparisons.nullsLast(comparator)
fun <T : Comparable<T>> naturalOrder(): kotlin.Comparator<T> = kotlin.comparisons.naturalOrder()
fun <T : Comparable<T>> reverseOrder(): kotlin.Comparator<T> = kotlin.comparisons.reverseOrder()
}
}
| apache-2.0 | 55cb784b32e8ab4bcb5d7280c4409d2b | 39.265823 | 100 | 0.728702 | 3.800478 | false | false | false | false |
danrien/projectBlue | projectBlueWater/src/main/java/com/lasthopesoftware/bluewater/client/connection/settings/changes/ObservableConnectionSettingsLibraryStorage.kt | 2 | 2058 | package com.lasthopesoftware.bluewater.client.connection.settings.changes
import android.content.Intent
import com.lasthopesoftware.bluewater.client.browsing.library.access.ILibraryStorage
import com.lasthopesoftware.bluewater.client.browsing.library.repository.Library
import com.lasthopesoftware.bluewater.client.connection.settings.LookupConnectionSettings
import com.lasthopesoftware.bluewater.shared.MagicPropertyBuilder
import com.lasthopesoftware.bluewater.shared.android.messages.SendMessages
import com.namehillsoftware.handoff.promises.Promise
class ObservableConnectionSettingsLibraryStorage(
private val inner: ILibraryStorage,
private val connectionSettingsLookup: LookupConnectionSettings,
private val sendMessages: SendMessages) : ILibraryStorage {
override fun saveLibrary(library: Library): Promise<Library> {
val promisedOriginalConnectionSettings = connectionSettingsLookup
.lookupConnectionSettings(library.libraryId)
return inner.saveLibrary(library).then { updatedLibrary ->
promisedOriginalConnectionSettings
.then { originalConnectionSettings ->
connectionSettingsLookup
.lookupConnectionSettings(library.libraryId)
.then { updatedConnectionSettings ->
if (updatedConnectionSettings != originalConnectionSettings) {
val connectionSettingsUpdatedIntent = Intent(connectionSettingsUpdated)
connectionSettingsUpdatedIntent.putExtra(
updatedConnectionSettingsLibraryId,
library.libraryId.id)
sendMessages.sendBroadcast(connectionSettingsUpdatedIntent)
}
}
}
updatedLibrary
}
}
override fun removeLibrary(library: Library): Promise<Unit> = inner.removeLibrary(library)
companion object {
private val magicPropertyBuilder = MagicPropertyBuilder(ObservableConnectionSettingsLibraryStorage::class.java)
val connectionSettingsUpdated = magicPropertyBuilder.buildProperty("connectionSettingsUpdated")
val updatedConnectionSettingsLibraryId = magicPropertyBuilder.buildProperty("updatedConnectionSettingsLibraryId")
}
}
| lgpl-3.0 | 8bc12840fc7fa71e7d4eb7a187735605 | 41 | 115 | 0.823129 | 5.170854 | false | false | false | false |
PizzaGames/emulio | core/src/main/com/github/emulio/scrapers/tgdb/model/GameImageFields.kt | 1 | 797 | package com.github.emulio.scrapers.tgdb.model
class GameImageFields(private val fanart: Boolean = false,
private val banner: Boolean = false,
private val boxart: Boolean = false,
private val screenshot: Boolean = false,
private val clearlogo: Boolean = false) {
fun fields(): String {
return StringBuilder().apply {
append(if (fanart) "icon," else "")
append(if (banner) "console," else "")
append(if (boxart) "controller," else "")
append(if (screenshot) "developer," else "")
append(if (clearlogo) "manufacturer," else "")
if (length > 0) {
setLength(length - 1)
}
}.toString()
}
} | gpl-3.0 | 77e6f00ab99092e24a1d4ab4b191fc13 | 37 | 63 | 0.523212 | 4.715976 | false | false | false | false |
Magneticraft-Team/Magneticraft | src/main/kotlin/com/cout970/magneticraft/misc/fluid/Tank.kt | 2 | 1454 | package com.cout970.magneticraft.misc.fluid
import com.cout970.magneticraft.misc.network.IBD
import com.cout970.magneticraft.systems.gui.DATA_ID_FLUID_AMOUNT
import com.cout970.magneticraft.systems.gui.DATA_ID_FLUID_NAME
import net.minecraftforge.fluids.FluidStack
import net.minecraftforge.fluids.FluidTank
/**
* Created by cout970 on 10/07/2016.
*/
open class Tank(
capacity: Int,
var fluidFilter: (FluidStack) -> Boolean = { true },
allowInput: Boolean = true,
allowOutput: Boolean = true
) : FluidTank(capacity) {
var clientFluidAmount = 0
var clientFluidName = ""
init {
canDrain = allowOutput
canFill = allowInput
}
fun isEmpty() = fluidAmount == 0
fun isNonEmpty() = !isEmpty()
override fun canDrainFluidType(fluid: FluidStack?): Boolean {
return fluid != null && canDrain && fluidFilter(fluid)
}
override fun canFillFluidType(fluid: FluidStack?): Boolean {
return fluid != null && canFill && fluidFilter(fluid)
}
//server only
fun getData(): IBD {
val data = IBD()
data.setInteger(DATA_ID_FLUID_AMOUNT, getFluid()?.amount ?: 0)
data.setString(DATA_ID_FLUID_NAME, getFluid()?.fluid?.name ?: "")
return data
}
//client only
fun setData(ibd: IBD) {
ibd.getInteger(DATA_ID_FLUID_AMOUNT, { clientFluidAmount = it })
ibd.getString(DATA_ID_FLUID_NAME, { clientFluidName = it })
}
} | gpl-2.0 | bd2abc9f618db0963af112dc0061e23a | 26.980769 | 73 | 0.660248 | 3.940379 | false | false | false | false |
fare1990/telegram-bot-bumblebee | telegram-bot-bumblebee-core/src/main/java/com/github/bumblebee/polling/LongPollingService.kt | 1 | 1499 | package com.github.bumblebee.polling
import com.github.bumblebee.bot.consumer.UpdateProcessor
import com.github.bumblebee.util.logger
import com.github.telegram.api.BotApi
import com.github.telegram.domain.Update
import org.springframework.stereotype.Service
@Service
class LongPollingService(private val botApi: BotApi,
private val updateProcessor: UpdateProcessor) {
private var lastUpdateOffset: Long = 0
fun poll() {
try {
log.debug("Calling getUpdates() with offset {}", lastUpdateOffset)
val response = botApi.getUpdates(lastUpdateOffset, pollItemsBatchSize, pollTimeoutSec)
if (response.ok) {
val updates = response.result.orEmpty()
updates.forEach { updateProcessor.process(it) }
if (updates.isNotEmpty()) {
updateLastUpdateOffset(updates)
}
} else {
log.error("Update failed, offset = {}", lastUpdateOffset)
}
} catch (e: RuntimeException) {
log.error("Failed to call telegram api", e)
}
}
private fun updateLastUpdateOffset(updates: List<Update>) {
if (updates.isNotEmpty()) {
lastUpdateOffset = updates.last().updateId + 1
}
}
companion object {
private val log = logger<LongPollingService>()
private const val pollTimeoutSec = 60
private const val pollItemsBatchSize = 100
}
}
| mit | 9a8de0917729a3c95690d30d7bb8e1a2 | 30.893617 | 98 | 0.623749 | 4.728707 | false | false | false | false |
ReactiveCircus/FlowBinding | flowbinding-material/src/main/java/reactivecircus/flowbinding/material/RangeSliderChangeEventFlow.kt | 1 | 1867 | package reactivecircus.flowbinding.material
import androidx.annotation.CheckResult
import com.google.android.material.slider.RangeSlider
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.channels.awaitClose
import kotlinx.coroutines.flow.callbackFlow
import kotlinx.coroutines.flow.conflate
import reactivecircus.flowbinding.common.InitialValueFlow
import reactivecircus.flowbinding.common.asInitialValueFlow
import reactivecircus.flowbinding.common.checkMainThread
/**
* Create a [InitialValueFlow] of change events on the [RangeSlider] instance.
*
* Note: Created flow keeps a strong reference to the [RangeSlider] instance
* until the coroutine that launched the flow collector is cancelled.
*
* Example of usage:
*
* ```
* rangeSlider.changeEvents()
* .onEach { event ->
* // handle event
* }
* .launchIn(uiScope)
* ```
*/
@CheckResult
@OptIn(ExperimentalCoroutinesApi::class)
public fun RangeSlider.changeEvents(): InitialValueFlow<RangeSliderChangeEvent> =
callbackFlow {
checkMainThread()
val listener = RangeSlider.OnChangeListener { rangeSlider, _, fromUser ->
trySend(
RangeSliderChangeEvent(
rangeSlider = rangeSlider,
values = rangeSlider.values,
fromUser = fromUser
)
)
}
addOnChangeListener(listener)
awaitClose { removeOnChangeListener(listener) }
}
.conflate()
.asInitialValueFlow {
RangeSliderChangeEvent(
rangeSlider = this,
values = this.values,
fromUser = false
)
}
public data class RangeSliderChangeEvent(
public val rangeSlider: RangeSlider,
public val values: List<Float>,
public val fromUser: Boolean
)
| apache-2.0 | a82fad83d9c0c597bc1d73943e1744f8 | 30.644068 | 81 | 0.675415 | 5.274011 | false | false | false | false |
Shashi-Bhushan/General | cp-trials/src/main/kotlin/in/shabhushan/cp_trials/logic/polynomial.kt | 1 | 423 | package `in`.shabhushan.cp_trials.logic
/**
* Solve polynomial using horner method
* 5x^4 - 6x^3 + 7x^2 + 8x - 9
* => (((5x - 6)x + 7)x + 8)x - 9
*/
fun horner(
coefficientArray: IntArray,
xValue: Int,
eval: Int = coefficientArray.size - 1 // second last
): Int = if (eval == 0) coefficientArray[eval] else {
val horner = horner(coefficientArray, xValue, eval - 1)
horner * xValue + coefficientArray[eval]
}
| gpl-2.0 | b72681b6236b7c2d96acc9dbcc74c52f | 27.2 | 57 | 0.64539 | 2.858108 | false | false | false | false |
SUPERCILEX/Robot-Scouter | feature/teams/src/main/java/com/supercilex/robotscouter/feature/teams/TeamMenuHelper.kt | 1 | 6181 | package com.supercilex.robotscouter.feature.teams
import android.view.Menu
import android.view.MenuInflater
import android.view.MenuItem
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.widget.Toolbar
import androidx.core.view.GravityCompat
import androidx.core.view.children
import androidx.drawerlayout.widget.DrawerLayout
import androidx.lifecycle.DefaultLifecycleObserver
import androidx.lifecycle.LifecycleOwner
import androidx.recyclerview.selection.SelectionTracker
import com.google.android.material.floatingactionbutton.FloatingActionButton
import com.supercilex.robotscouter.DrawerToggler
import com.supercilex.robotscouter.TeamExporter
import com.supercilex.robotscouter.core.data.isFullUser
import com.supercilex.robotscouter.core.data.model.trash
import com.supercilex.robotscouter.core.data.model.untrashTeam
import com.supercilex.robotscouter.core.data.teams
import com.supercilex.robotscouter.core.model.Team
import com.supercilex.robotscouter.core.ui.DrawerMenuHelperBase
import com.supercilex.robotscouter.core.ui.longSnackbar
import com.supercilex.robotscouter.shared.TeamDetailsDialog
import com.supercilex.robotscouter.shared.TeamSharer
import com.supercilex.robotscouter.R as RC
internal class TeamMenuHelper(
private val fragment: TeamListFragment,
private val tracker: SelectionTracker<String>,
private val activity: AppCompatActivity = fragment.requireActivity() as AppCompatActivity
) : DrawerMenuHelperBase<String>(activity, tracker) {
private val fab: FloatingActionButton = activity.findViewById(RC.id.fab)
private val drawerLayout: DrawerLayout = activity.findViewById(RC.id.drawerLayout)
private val teamMenuItems = mutableListOf<MenuItem>()
private val teamsMenuItems = mutableListOf<MenuItem>()
private val normalMenuItems = mutableListOf<MenuItem>()
init {
fragment.viewLifecycleOwner.lifecycle.addObserver(object : DefaultLifecycleObserver {
private val toolbar: Toolbar = activity.findViewById(RC.id.toolbar)
private val fallback = FallbackNavigationClickListener(drawerLayout)
override fun onStart(owner: LifecycleOwner) {
if (!tracker.hasSelection()) return
// Check for deleted teams
val remaining = tracker.selection.toMutableList()
remaining.removeAll(teams.map(Team::id))
for (deleted in remaining) tracker.deselect(deleted)
}
override fun onDestroy(owner: LifecycleOwner) {
toolbar.setNavigationOnClickListener(fallback)
}
})
}
override fun handleNavigationClick(hasSelection: Boolean) {
if (!hasSelection) drawerLayout.openDrawer(GravityCompat.START)
}
override fun createMenu(menu: Menu, inflater: MenuInflater) {
inflater.inflate(R.menu.team_options, menu)
teamMenuItems.clear()
teamMenuItems.addAll(menu.children.filter { teamMenuIds.contains(it.itemId) })
teamsMenuItems.clear()
teamsMenuItems.addAll(menu.children.filter { teamsMenuIds.contains(it.itemId) })
normalMenuItems.clear()
normalMenuItems.addAll(menu.children.filterNot { menuIds.contains(it.itemId) })
}
override fun handleItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
R.id.action_export_teams -> (activity as TeamExporter).export()
R.id.action_share -> if (TeamSharer.shareTeams(fragment, fragment.selectedTeams)) {
tracker.clearSelection()
}
R.id.action_edit_team_details -> TeamDetailsDialog.show(
fragment.childFragmentManager, fragment.selectedTeams.first())
R.id.action_delete -> {
val deleted = fragment.selectedTeams.toList()
for (team in deleted) team.trash()
fragment.requireView().longSnackbar(
activity.resources.getQuantityString(
R.plurals.teams_deleted_message, deleted.size, deleted.size),
activity.getString(RC.string.undo)
) { for (team in deleted) untrashTeam(team.id) }
}
else -> return false
}
return true
}
override fun updateNormalMenu(visible: Boolean) {
for (item in normalMenuItems) {
item.isVisible =
visible && if (item.itemId == RC.id.action_sign_in) !isFullUser else true
}
if (visible) {
drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNDEFINED)
} else {
drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED)
}
// Don't change global FAB state unless we own the fragment
if (!fragment.isDetached) if (visible) fab.show() else fab.hide()
}
override fun updateSingleSelectMenu(visible: Boolean) {
for (item in teamMenuItems) item.isVisible = visible
}
override fun updateMultiSelectMenu(visible: Boolean) {
for (item in teamsMenuItems) item.isVisible = visible
}
override fun updateNavigationIcon(default: Boolean) {
val toggler = activity as DrawerToggler
if (default) {
toggler.toggle(true)
} else {
checkNotNull(activity.supportActionBar).apply {
// Replace hamburger icon with back button
setDisplayHomeAsUpEnabled(false)
toggler.toggle(false)
setDisplayHomeAsUpEnabled(true)
}
}
}
private class FallbackNavigationClickListener(
private val drawer: DrawerLayout
) : View.OnClickListener {
override fun onClick(v: View) {
drawer.openDrawer(GravityCompat.START)
}
}
private companion object {
val teamMenuIds = listOf(R.id.action_edit_team_details)
val teamsMenuIds = listOf(
R.id.action_export_teams,
R.id.action_share,
R.id.action_delete
)
val menuIds = teamMenuIds + teamsMenuIds
}
}
| gpl-3.0 | 08e20e3abd3a03e069229d8af029709c | 38.621795 | 97 | 0.677722 | 4.878453 | false | false | false | false |
Kiskae/Twitch-Archiver | ui/src/main/kotlin/net/serverpeon/twitcharchiver/fx/sections/ChannelInput.kt | 1 | 4907 | package net.serverpeon.twitcharchiver.fx.sections
import javafx.beans.binding.When
import javafx.beans.property.ReadOnlyStringProperty
import javafx.beans.property.SimpleBooleanProperty
import javafx.beans.property.SimpleIntegerProperty
import javafx.beans.property.SimpleStringProperty
import javafx.event.ActionEvent
import javafx.event.EventHandler
import javafx.geometry.Insets
import javafx.geometry.Orientation
import javafx.geometry.Pos
import javafx.scene.control.*
import javafx.scene.layout.Region
import net.serverpeon.twitcharchiver.fx.hbox
import net.serverpeon.twitcharchiver.fx.makeEditable
import net.serverpeon.twitcharchiver.fx.stretch
import net.serverpeon.twitcharchiver.fx.vbox
import net.serverpeon.twitcharchiver.network.ApiWrapper
import net.serverpeon.twitcharchiver.twitch.api.KrakenApi
import net.serverpeon.twitcharchiver.twitch.playlist.Playlist
import rx.Observable
import rx.Subscription
class ChannelInput(val api: ApiWrapper, username: ReadOnlyStringProperty, val feed: ChannelInput.VideoFeed) : TitledPane() {
companion object {
private val DEBUG_USER: ReadOnlyStringProperty = SimpleStringProperty(null)
}
private val selectedUser = When(DEBUG_USER.isNotNull).then(DEBUG_USER).otherwise(username)
private val videoLimit = SimpleIntegerProperty()
private val loadingVideos = SimpleBooleanProperty(false)
private var runningSubscription: Subscription? = null
set(v) {
field?.unsubscribe()
field = v
loadingVideos.set(field != null)
}
val hasAccess = api.hasAccess(this)
init {
text = "Channel"
content = vbox {
+hbox {
+Label("Channel Name:").apply {
padding = Insets(0.0, 5.0, 0.0, 0.0)
}
+Label().apply {
textProperty().bind(selectedUser)
style = "-fx-font-weight: bold"
stretch(Orientation.HORIZONTAL)
}
init {
alignment = Pos.CENTER_RIGHT
}
}
+hbox {
+Label("Video Limit").apply {
padding = Insets(0.0, 5.0, 0.0, 0.0)
}
+Spinner(NonZeroSpinner(-1, Int.MAX_VALUE)).apply {
videoLimit.bind(valueProperty())
disableProperty().bind(loadingVideos)
makeEditable()
}
init {
alignment = Pos.CENTER_RIGHT
}
}
+vbox {
+Button().apply {
stretch(Orientation.HORIZONTAL)
textProperty().bind(When(loadingVideos).then("Cancel Query").otherwise("Query Twitch for Videos"))
onActionProperty().bind(When(loadingVideos).then(EventHandler<ActionEvent> {
runningSubscription = null
}).otherwise(EventHandler {
feed.resetFeed()
runningSubscription = retrieveVideoStream(selectedUser.get(), videoLimit.get())
.doOnUnsubscribe { runningSubscription = null }
.subscribe {
feed.insertVideo(it.first, it.second)
}
}))
}
+ProgressBar().apply {
progressProperty().bind(When(loadingVideos).then(-1.0).otherwise(0.0))
stretch(Orientation.HORIZONTAL)
}
}
forEach<Region> {
padding = Insets(3.0)
}
}
disableProperty().bind(username.isNull.or(hasAccess.not()))
}
private fun retrieveVideoStream(username: String, limit: Int): Observable<Pair<KrakenApi.VideoListResponse.Video, Playlist>> {
return api.request(this) {
this.videoList(channelName = username, limit = limit)
.flatMap { video ->
this.loadPlaylist(video.internalId)
.map { Pair(video, it) }
.toObservable()
}
}
}
private class NonZeroSpinner(min: Int, max: Int) : SpinnerValueFactory.IntegerSpinnerValueFactory(min, max, min) {
override fun increment(steps: Int) {
super.increment(steps)
if (value == 0) {
super.increment(1)
}
}
override fun decrement(steps: Int) {
super.decrement(steps)
if (value == 0) {
super.decrement(1)
}
}
}
interface VideoFeed {
fun resetFeed()
fun insertVideo(info: KrakenApi.VideoListResponse.Video, playlist: Playlist)
}
} | mit | a0cbbc0f6dd7640b1a6b7b0ec318c246 | 33.808511 | 130 | 0.562869 | 5.084974 | false | false | false | false |
michael-johansen/workshop-jb | src/iv_builders/data.kt | 13 | 967 | package iv_builders.data
data class Product(val description: String, val price: Double, val popularity: Int)
val cactus = Product("cactus", 11.2, 13)
val cake = Product("cake", 3.2, 111)
val camera = Product("camera", 134.5, 2)
val car = Product("car", 30000.0, 0)
val carrot = Product("carrot", 1.34, 5)
val cellPhone = Product("cell phone", 129.9, 99)
val chimney = Product("chimney", 190.0, 2)
val certificate = Product("certificate", 99.9, 1)
val cigar = Product("cigar", 8.0, 51)
val coffee = Product("coffee", 8.0, 67)
val coffeeMaker = Product("coffee maker", 201.2, 1)
val cola = Product("cola", 4.0, 67)
val cranberry = Product("cranberry", 4.1, 39)
val crocs = Product("crocs", 18.7, 10)
val crocodile = Product("crocodile", 20000.2, 1)
val cushion = Product("cushion", 131.0, 0)
fun getProducts() = listOf(cactus, cake, camera, car, carrot, cellPhone, chimney, certificate, cigar, coffee, coffeeMaker,
cola, cranberry, crocs, crocodile, cushion) | mit | d291a0b12836b91b7d5d0c7e4fe618eb | 41.086957 | 122 | 0.692865 | 2.852507 | false | false | false | false |
charlesmadere/smash-ranks-android | smash-ranks-android/app/src/main/java/com/garpr/android/features/setRegion/SetRegionActivity.kt | 1 | 9204 | package com.garpr.android.features.setRegion
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.appcompat.app.AlertDialog
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.RecyclerView
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout
import com.garpr.android.R
import com.garpr.android.data.models.Region
import com.garpr.android.extensions.layoutInflater
import com.garpr.android.features.common.activities.BaseActivity
import com.garpr.android.features.common.views.RegionSelectionItemView
import com.garpr.android.features.setRegion.SetRegionViewModel.ListItem
import com.garpr.android.misc.Refreshable
import com.garpr.android.misc.RegionHandleUtils
import kotlinx.android.synthetic.main.activity_set_region.*
import org.koin.android.ext.android.inject
import org.koin.androidx.viewmodel.ext.android.viewModel
class SetRegionActivity : BaseActivity(), Refreshable, RegionSelectionItemView.Listener,
SetRegionToolbar.Listener, SwipeRefreshLayout.OnRefreshListener {
private val adapter = Adapter(this)
private val viewModel: SetRegionViewModel by viewModel()
protected val regionHandleUtils: RegionHandleUtils by inject()
companion object {
private const val TAG = "SetRegionActivity"
fun getLaunchIntent(context: Context) = Intent(context, SetRegionActivity::class.java)
}
override val activityName = TAG
private fun fetchRegions() {
viewModel.fetchRegions()
}
private fun initListeners() {
viewModel.stateLiveData.observe(this, Observer {
refreshState(it)
})
}
override fun navigateUp() {
if (!viewModel.warnBeforeClose) {
super.navigateUp()
return
}
AlertDialog.Builder(this)
.setMessage(R.string.youve_selected_a_region_but_havent_saved)
.setNegativeButton(R.string.cancel, null)
.setPositiveButton(R.string.yes) { dialog, which ->
[email protected]()
}
.show()
}
override fun onBackPressed() {
if (!viewModel.warnBeforeClose) {
super.onBackPressed()
return
}
AlertDialog.Builder(this)
.setMessage(R.string.youve_selected_a_region_but_havent_saved)
.setNegativeButton(R.string.cancel, null)
.setPositiveButton(R.string.yes) { dialog, which ->
[email protected]()
}
.show()
}
override fun onClick(v: RegionSelectionItemView) {
viewModel.selectedRegion = v.region
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_set_region)
initListeners()
fetchRegions()
}
override fun onRefresh() {
refresh()
}
override fun onSaveClick(v: SetRegionToolbar) {
viewModel.saveSelectedRegion()
setResult(Activity.RESULT_OK)
supportFinishAfterTransition()
}
override fun onViewsBound() {
super.onViewsBound()
val region = regionHandleUtils.getRegion(this)
toolbar.subtitleText = getString(R.string.region_endpoint_format, region.displayName,
getText(region.endpoint.title))
toolbar.listener = this
refreshLayout.setOnRefreshListener(this)
recyclerView.setHasFixedSize(true)
recyclerView.adapter = adapter
}
override fun refresh() {
fetchRegions()
}
private fun refreshState(state: SetRegionViewModel.State) {
when (state.saveIconStatus) {
SetRegionViewModel.SaveIconStatus.DISABLED -> {
toolbar.showSaveIcon = true
toolbar.enableSaveIcon = false
}
SetRegionViewModel.SaveIconStatus.ENABLED -> {
toolbar.showSaveIcon = true
toolbar.enableSaveIcon = true
}
SetRegionViewModel.SaveIconStatus.GONE -> {
toolbar.showSaveIcon = false
toolbar.enableSaveIcon = false
}
}
if (state.hasError) {
adapter.clear()
recyclerView.visibility = View.GONE
error.visibility = View.VISIBLE
} else {
adapter.set(state.list, state.selectedRegion)
error.visibility = View.GONE
recyclerView.visibility = View.VISIBLE
}
if (state.isFetching) {
refreshLayout.isEnabled = true
refreshLayout.isRefreshing = true
} else {
refreshLayout.isRefreshing = false
refreshLayout.isEnabled = state.isRefreshEnabled
}
}
private class Adapter(
private val regionItemViewListener: RegionSelectionItemView.Listener
) : RecyclerView.Adapter<RecyclerView.ViewHolder>() {
private val list = mutableListOf<ListItem>()
private var selectedRegion: Region? = null
init {
setHasStableIds(true)
}
private fun bindEndpoint(holder: EndpointViewHolder, item: ListItem.Endpoint) {
holder.endpointDividerView.setContent(item.endpoint)
}
private fun bindEndpointError(holder: EndpointErrorViewHolder, item: ListItem.EndpointError) {
holder.endpointErrorItemView.text = holder.endpointErrorItemView.context.getString(
R.string.error_loading_regions_from_x,
holder.endpointErrorItemView.context.getText(item.endpoint.title)
)
}
private fun bindRegion(holder: RegionViewHolder, item: ListItem.Region) {
holder.regionSelectionItemView.setContent(item.region, item.region == selectedRegion)
}
internal fun clear() {
list.clear()
selectedRegion = null
notifyDataSetChanged()
}
override fun getItemCount(): Int {
return list.size
}
override fun getItemId(position: Int): Long {
return list[position].listId
}
override fun getItemViewType(position: Int): Int {
return when (list[position]) {
is ListItem.Endpoint -> VIEW_TYPE_ENDPOINT
is ListItem.EndpointError -> VIEW_TYPE_ENDPOINT_ERROR
is ListItem.Region -> VIEW_TYPE_REGION
}
}
override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
when (val item = list[position]) {
is ListItem.Endpoint -> bindEndpoint(holder as EndpointViewHolder, item)
is ListItem.EndpointError -> bindEndpointError(holder as EndpointErrorViewHolder, item)
is ListItem.Region -> bindRegion(holder as RegionViewHolder, item)
else -> throw RuntimeException("unknown item: $item, position: $position")
}
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
val inflater = parent.layoutInflater
return when (viewType) {
VIEW_TYPE_ENDPOINT -> EndpointViewHolder(inflater.inflate(
R.layout.divider_endpoint, parent, false))
VIEW_TYPE_ENDPOINT_ERROR -> EndpointErrorViewHolder(inflater.inflate(
R.layout.item_string_with_background, parent, false))
VIEW_TYPE_REGION -> RegionViewHolder(regionItemViewListener,
inflater.inflate(R.layout.item_region_selection, parent, false))
else -> throw IllegalArgumentException("unknown viewType: $viewType")
}
}
internal fun set(list: List<ListItem>?, selectedRegion: Region?) {
this.list.clear()
if (!list.isNullOrEmpty()) {
this.list.addAll(list)
}
this.selectedRegion = selectedRegion
notifyDataSetChanged()
}
companion object {
private const val VIEW_TYPE_ENDPOINT = 0
private const val VIEW_TYPE_ENDPOINT_ERROR = 1
private const val VIEW_TYPE_REGION = 2
}
}
private class EndpointErrorViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
internal val endpointErrorItemView: TextView = itemView as TextView
}
private class EndpointViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
internal val endpointDividerView: EndpointDividerView = itemView as EndpointDividerView
}
private class RegionViewHolder(
listener: RegionSelectionItemView.Listener,
itemView: View
) : RecyclerView.ViewHolder(itemView) {
internal val regionSelectionItemView: RegionSelectionItemView = itemView as RegionSelectionItemView
init {
regionSelectionItemView.listener = listener
}
}
}
| unlicense | a98a8b56a96ac1e9298e63f71e3eb9a9 | 33.47191 | 107 | 0.640265 | 5.090708 | false | false | false | false |
Softwee/codeview-android | codeview/src/main/java/io/github/kbiakov/codeview/views/LineNoteView.kt | 2 | 1387 | package io.github.kbiakov.codeview.views
import android.content.Context
import android.widget.TextView
import io.github.kbiakov.codeview.R
import io.github.kbiakov.codeview.dpToPx
/**
* @class LineNoteView
*
* Note view for code line. Default footer view.
*
* @author Kirill Biakov
*/
class LineNoteView(context: Context?) : TextView(context) {
companion object Factory {
/**
* Simple factory method to create note view.
*
* @param context Context
* @param text Note text
* @param isFirst Is first footer view
* @param bgColor Background color
* @param textColor Text Color
* @return Created line note view
*/
fun create(context: Context, text: String, isFirst: Boolean, bgColor: Int, textColor: Int): LineNoteView {
val noteView = LineNoteView(context)
noteView.textSize = 12f
noteView.text = text
noteView.setTextColor(textColor)
noteView.setBackgroundColor(bgColor)
val dp8 = dpToPx(context, 8)
val leftPadding = context.resources.getDimension(
R.dimen.line_num_width).toInt() + dpToPx(context, 14)
val topPadding = if (isFirst) dp8 else 0
noteView.setPadding(leftPadding, topPadding, dp8, dp8)
return noteView
}
}
}
| mit | aa2cb6d69fd2fefa660155e4a79839c3 | 28.510638 | 114 | 0.623648 | 4.320872 | false | false | false | false |
MaisonWan/AppFileExplorer | FileExplorer/src/main/java/com/domker/app/explorer/file/FileManager.kt | 1 | 1528 | package com.domker.app.explorer.file
import android.content.Context
import android.content.pm.PackageManager
import android.graphics.drawable.Drawable
import java.io.File
/**
* 封装文件相关操作的类
* Created by Maison on 2017/8/31.
*/
class FileManager {
/**
* 获取目录中的文件和文件夹列表
*/
fun getFileList(path: String): List<FileInfo> {
val fileList = ArrayList<FileInfo>()
val dir = File(path)
if (dir.isDirectory) {
dir.listFiles()?.forEach {
val fileInfo = FileInfo(it)
fileList.add(fileInfo)
}
}
return fileList
}
/**
* 获取该目录下的文件信息
*/
fun getFileList(file: File): List<FileInfo> {
return getFileList(file.absolutePath)
}
companion object {
/**
* 获取apk文件的图标
*/
fun getApkIcon(context: Context, apkPath: String): Drawable? {
val pm = context.packageManager
val info = pm.getPackageArchiveInfo(apkPath, PackageManager.GET_ACTIVITIES)
if (info != null) {
val appInfo = info!!.applicationInfo
appInfo.sourceDir = apkPath
appInfo.publicSourceDir = apkPath
try {
return appInfo.loadIcon(pm)
} catch (e: OutOfMemoryError) {
e.printStackTrace()
}
}
return null
}
}
} | apache-2.0 | a223e12a82e4ac2bf26070e0e154475f | 24.350877 | 87 | 0.542936 | 4.45679 | false | false | false | false |
Bodo1981/swapi.co | app/src/main/java/com/christianbahl/swapico/list/model/ListResponse.kt | 1 | 715 | package com.christianbahl.swapico.list.model
import android.os.Parcelable
import org.jetbrains.anko.db.TEXT
/**
* @author Christian Bahl
*/
enum class ListItemType {
TEXT, LOAD_MORE
}
enum class ListType {
FILMS, PEOPLE, PLANETS, SPECIES, STARSHIPS, VEHICLES
}
data class ListModel(val listData: List<ListItem>,
val loadMoreUrl: String?) : ILoadMoreList {
override val loadMore: Boolean
get() = loadMoreUrl?.isNotBlank() ?: false
override val adapterList: MutableList<ListItem>
get() = listData as MutableList<ListItem>
}
data class ListItem(val text: String = "",
val url: String = "",
val type: ListItemType = ListItemType.TEXT) | apache-2.0 | 1801423d4235a1766d8fa0e3ed098ab2 | 24.571429 | 64 | 0.674126 | 3.994413 | false | false | false | false |
strooooke/quickfit | app/src/main/java/com/lambdasoup/quickfit/util/ui/DividerItemDecoration.kt | 1 | 4423 | /*
* Copyright 2016-2019 Juliane Lehmann <[email protected]>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.lambdasoup.quickfit.util.ui
import android.content.Context
import android.graphics.Canvas
import android.graphics.Rect
import android.graphics.drawable.Drawable
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import android.view.View
import androidx.recyclerview.widget.RecyclerView.NO_ID
import androidx.recyclerview.widget.RecyclerView.NO_POSITION
/**
* See https://gist.github.com/alexfu/0f464fc3742f134ccd1e
*
*
* and http://stackoverflow.com/a/30386358/1428514
*/
class DividerItemDecoration(context: Context, private val drawAtEnd: Boolean) : RecyclerView.ItemDecoration() {
private val divider: Drawable
init {
val a = context.obtainStyledAttributes(intArrayOf(android.R.attr.listDivider))
divider = a.getDrawable(0)!!
a.recycle()
}
override fun onDraw(c: Canvas, parent: RecyclerView, state: RecyclerView.State) {
if (getOrientation(parent) == LinearLayoutManager.VERTICAL) {
drawVertical(c, parent)
} else {
drawHorizontal(c, parent)
}
}
private fun drawVertical(c: Canvas, parent: RecyclerView) {
val manager = parent.layoutManager
val left = parent.paddingLeft
val right = parent.width - parent.paddingRight
val lastDecoratedChild = getLastDecoratedChild(parent)
for (i in 0 until parent.childCount) {
val child = parent.getChildAt(i)
val pos = parent.getChildAdapterPosition(child)
if (pos == NO_POSITION || pos > lastDecoratedChild) {
continue
}
val ty = (child.translationY + 0.5f).toInt()
val tx = (child.translationX + 0.5f).toInt()
val bottom = manager!!.getDecoratedBottom(child) + ty
val top = bottom - divider.intrinsicHeight
divider.setBounds(left + tx, top, right + tx, bottom)
divider.draw(c)
}
}
private fun drawHorizontal(c: Canvas, parent: RecyclerView) {
val manager = parent.layoutManager
val top = parent.paddingTop
val bottom = parent.height - parent.paddingBottom
val lastDecoratedChild = getLastDecoratedChild(parent)
for (i in 0 until parent.childCount) {
val child = parent.getChildAt(i)
val pos = parent.getChildAdapterPosition(child)
if (pos == NO_POSITION || pos > lastDecoratedChild) {
continue
}
val ty = (child.translationY + 0.5f).toInt()
val tx = (child.translationX + 0.5f).toInt()
val right = manager!!.getDecoratedRight(child) + tx
val left = right - divider.intrinsicWidth
divider.setBounds(left, top + ty, right, bottom + ty)
divider.draw(c)
}
}
private fun getLastDecoratedChild(parent: RecyclerView): Int {
return parent.adapter!!.itemCount - 1 - if (drawAtEnd) 0 else 1
}
override fun getItemOffsets(outRect: Rect, view: View, parent: RecyclerView, state: RecyclerView.State) {
super.getItemOffsets(outRect, view, parent, state)
val pos = parent.getChildAdapterPosition(view)
if (pos != NO_POSITION) {
if (getOrientation(parent) == LinearLayoutManager.VERTICAL) {
outRect.bottom = divider.intrinsicHeight
} else {
outRect.right = divider.intrinsicWidth
}
}
}
private fun getOrientation(parent: RecyclerView): Int {
val layoutManager = parent.layoutManager
require(layoutManager is LinearLayoutManager) { "DividerItemDecoration can only be added to RecyclerView with LinearLayoutManager" }
return layoutManager.orientation
}
}
| apache-2.0 | 8989b19f0c683ab984cfb2df264db0a4 | 35.254098 | 140 | 0.660864 | 4.58342 | false | false | false | false |
suncycheng/intellij-community | platform/configuration-store-impl/src/DirectoryBasedStorage.kt | 6 | 9053 | /*
* Copyright 2000-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.configurationStore
import com.intellij.openapi.application.runUndoTransparentWriteAction
import com.intellij.openapi.components.StateSplitter
import com.intellij.openapi.components.StateSplitterEx
import com.intellij.openapi.components.StateStorage
import com.intellij.openapi.components.TrackingPathMacroSubstitutor
import com.intellij.openapi.components.impl.stores.DirectoryStorageUtil
import com.intellij.openapi.components.impl.stores.FileStorageCoreUtil
import com.intellij.openapi.util.Pair
import com.intellij.openapi.vfs.LocalFileSystem
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.util.LineSeparator
import com.intellij.util.SmartList
import com.intellij.util.SystemProperties
import com.intellij.util.containers.SmartHashSet
import com.intellij.util.io.systemIndependentPath
import com.intellij.util.isEmpty
import gnu.trove.THashMap
import gnu.trove.THashSet
import org.jdom.Element
import java.io.IOException
import java.nio.ByteBuffer
import java.nio.file.Path
abstract class DirectoryBasedStorageBase(@Suppress("DEPRECATION") protected val splitter: StateSplitter,
protected val pathMacroSubstitutor: TrackingPathMacroSubstitutor? = null) : StateStorageBase<StateMap>() {
protected var componentName: String? = null
protected abstract val virtualFile: VirtualFile?
override fun loadData() = StateMap.fromMap(DirectoryStorageUtil.loadFrom(virtualFile, pathMacroSubstitutor))
override fun startExternalization(): StateStorage.ExternalizationSession? = null
override fun analyzeExternalChangesAndUpdateIfNeed(componentNames: MutableSet<String>) {
// todo reload only changed file, compute diff
val newData = loadData()
storageDataRef.set(newData)
if (componentName != null) {
componentNames.add(componentName!!)
}
}
override fun getSerializedState(storageData: StateMap, component: Any?, componentName: String, archive: Boolean): Element? {
this.componentName = componentName
if (storageData.isEmpty()) {
return null
}
val state = Element(FileStorageCoreUtil.COMPONENT)
if (splitter is StateSplitterEx) {
for (fileName in storageData.keys()) {
val subState = storageData.getState(fileName, archive) ?: return null
splitter.mergeStateInto(state, subState)
}
}
else {
val subElements = SmartList<Element>()
for (fileName in storageData.keys()) {
val subState = storageData.getState(fileName, archive) ?: return null
subElements.add(subState)
}
if (!subElements.isEmpty()) {
splitter.mergeStatesInto(state, subElements.toTypedArray())
}
}
return state
}
override fun hasState(storageData: StateMap, componentName: String) = storageData.hasStates()
}
open class DirectoryBasedStorage(private val dir: Path,
@Suppress("DEPRECATION") splitter: StateSplitter,
pathMacroSubstitutor: TrackingPathMacroSubstitutor? = null) : DirectoryBasedStorageBase(splitter, pathMacroSubstitutor) {
private @Volatile var cachedVirtualFile: VirtualFile? = null
override val virtualFile: VirtualFile?
get() {
var result = cachedVirtualFile
if (result == null) {
result = LocalFileSystem.getInstance().findFileByPath(dir.systemIndependentPath)
cachedVirtualFile = result
}
return result
}
internal fun setVirtualDir(dir: VirtualFile?) {
cachedVirtualFile = dir
}
override fun startExternalization(): StateStorage.ExternalizationSession? = if (checkIsSavingDisabled()) null else MySaveSession(this, getStorageData())
private class MySaveSession(private val storage: DirectoryBasedStorage, private val originalStates: StateMap) : SaveSessionBase() {
private var copiedStorageData: MutableMap<String, Any>? = null
private val dirtyFileNames = SmartHashSet<String>()
private var someFileRemoved = false
override fun setSerializedState(componentName: String, element: Element?) {
storage.componentName = componentName
if (element.isEmpty()) {
if (copiedStorageData != null) {
copiedStorageData!!.clear()
}
else if (!originalStates.isEmpty()) {
copiedStorageData = THashMap<String, Any>()
}
}
else {
val stateAndFileNameList = storage.splitter.splitState(element!!)
val existingFiles = THashSet<String>(stateAndFileNameList.size)
for (pair in stateAndFileNameList) {
doSetState(pair.second, pair.first)
existingFiles.add(pair.second)
}
for (key in originalStates.keys()) {
if (existingFiles.contains(key)) {
continue
}
if (copiedStorageData == null) {
copiedStorageData = originalStates.toMutableMap()
}
someFileRemoved = true
copiedStorageData!!.remove(key)
}
}
}
private fun doSetState(fileName: String, subState: Element) {
if (copiedStorageData == null) {
copiedStorageData = setStateAndCloneIfNeed(fileName, subState, originalStates)
if (copiedStorageData != null) {
dirtyFileNames.add(fileName)
}
}
else if (updateState(copiedStorageData!!, fileName, subState)) {
dirtyFileNames.add(fileName)
}
}
override fun createSaveSession() = if (storage.checkIsSavingDisabled() || copiedStorageData == null) null else this
override fun save() {
val stateMap = StateMap.fromMap(copiedStorageData!!)
var dir = storage.virtualFile
if (copiedStorageData!!.isEmpty()) {
if (dir != null && dir.exists()) {
deleteFile(this, dir)
}
storage.setStorageData(stateMap)
return
}
if (dir == null || !dir.isValid) {
dir = createDir(storage.dir, this)
storage.cachedVirtualFile = dir
}
if (!dirtyFileNames.isEmpty) {
saveStates(dir, stateMap)
}
if (someFileRemoved && dir.exists()) {
deleteFiles(dir)
}
storage.setStorageData(stateMap)
}
private fun saveStates(dir: VirtualFile, states: StateMap) {
val storeElement = Element(FileStorageCoreUtil.COMPONENT)
for (fileName in states.keys()) {
if (!dirtyFileNames.contains(fileName)) {
continue
}
var element: Element? = null
try {
element = states.getElement(fileName) ?: continue
storage.pathMacroSubstitutor?.collapsePaths(element)
storeElement.setAttribute(FileStorageCoreUtil.NAME, storage.componentName!!)
storeElement.addContent(element)
val file = dir.getOrCreateChild(fileName, this)
// we don't write xml prolog due to historical reasons (and should not in any case)
writeFile(null, this, file, storeElement, LineSeparator.fromString(if (file.exists()) loadFile(file).second else SystemProperties.getLineSeparator()), false)
}
catch (e: IOException) {
LOG.error(e)
}
finally {
if (element != null) {
element.detach()
}
}
}
}
private fun deleteFiles(dir: VirtualFile) {
runUndoTransparentWriteAction {
for (file in dir.children) {
val fileName = file.name
if (fileName.endsWith(FileStorageCoreUtil.DEFAULT_EXT) && !copiedStorageData!!.containsKey(fileName)) {
if (file.isWritable) {
file.delete(this)
}
else {
throw ReadOnlyModificationException(file, null)
}
}
}
}
}
}
private fun setStorageData(newStates: StateMap) {
storageDataRef.set(newStates)
}
}
private val NON_EXISTENT_FILE_DATA = Pair.create<ByteArray, String>(null, SystemProperties.getLineSeparator())
/**
* @return pair.first - file contents (null if file does not exist), pair.second - file line separators
*/
private fun loadFile(file: VirtualFile?): Pair<ByteArray, String> {
if (file == null || !file.exists()) {
return NON_EXISTENT_FILE_DATA
}
val bytes = file.contentsToByteArray()
val lineSeparator = file.detectedLineSeparator ?: detectLineSeparators(Charsets.UTF_8.decode(ByteBuffer.wrap(bytes)), null).separatorString
return Pair.create<ByteArray, String>(bytes, lineSeparator)
} | apache-2.0 | d2c73251bf724ceb818e75d031f15536 | 34.229572 | 167 | 0.68353 | 5.009961 | false | false | false | false |
rcgroot/adb-awake | studio/app/src/main/java/nl/renedegroot/android/adbawake/businessmodel/LockControl.kt | 2 | 3082 | /*------------------------------------------------------------------------------
** Author: René de Groot
** Copyright: (c) 2017 René de Groot All Rights Reserved.
**------------------------------------------------------------------------------
** No part of this file may be reproduced
** or transmitted in any form or by any
** means, electronic or mechanical, for the
** purpose, without the express written
** permission of the copyright holder.
*------------------------------------------------------------------------------
*
* This file is part of "Stay-awake on adb".
*
* "Stay-awake on adb" 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.
*
* "Stay-awake on adb" 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 "Stay-awake on adb". If not, see <http://www.gnu.org/licenses/>.
*
*/
package nl.renedegroot.android.adbawake.businessmodel
import android.content.Context
import android.os.PowerManager
import nl.renedegroot.android.adbawake.Application
import nl.renedegroot.android.adbawake.providers.PowerManagerProvider
import javax.inject.Inject
class LockControl {
var isAcquired = false
private val LOCK_TAG = "adbawake"
private var dimLock: PowerManager.WakeLock? = null
private var wakeLock: PowerManager.WakeLock? = null
private val listeners = mutableSetOf<OnLockChangedListener>()
@Inject
lateinit var powerManagerProvider: PowerManagerProvider
init {
Application.appComponent.inject(this)
}
fun createLocks(context: Context) {
val powerManager = powerManagerProvider.getPowerManager(context)
if (dimLock == null) {
dimLock = powerManager.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, LOCK_TAG)
}
if (wakeLock == null) {
wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, LOCK_TAG)
}
}
fun enableWakelock(context: Context, enabled: Boolean) {
if (enabled) {
createLocks(context)
wakeLock?.acquire()
dimLock?.acquire()
isAcquired = true
} else if (wakeLock?.isHeld ?: false) {
wakeLock?.release()
dimLock?.release()
isAcquired = false
}
listeners.forEach { it.onLockChanged(this, enabled) }
}
fun addListener(listener: OnLockChangedListener) {
listeners.add(listener)
}
fun removeListener(listener: OnLockChangedListener) {
listeners.remove(listener)
}
interface OnLockChangedListener {
fun onLockChanged(control: LockControl, newValue: Boolean)
}
}
| gpl-3.0 | 126dd3ab22b9e17b16e6cfa5d8d44db1 | 34.402299 | 91 | 0.629545 | 4.716692 | false | false | false | false |
matkoniecz/StreetComplete | app/src/main/java/de/westnordost/streetcomplete/data/osm/edits/split_way/SplitWayAt.kt | 1 | 5340 | package de.westnordost.streetcomplete.data.osm.edits.split_way
import de.westnordost.streetcomplete.data.osm.mapdata.LatLon
import de.westnordost.streetcomplete.data.upload.ConflictException
import de.westnordost.streetcomplete.ktx.equalsInOsm
import de.westnordost.streetcomplete.util.measuredLength
import de.westnordost.streetcomplete.util.pointOnPolylineFromStart
import kotlin.math.sign
/** data class that carries the information for one split to perform on a random position on a way.
* So, same as SplitPolylineAtPosition, but additionally with the index of the split in the way. */
sealed class SplitWayAt : Comparable<SplitWayAt> {
abstract val pos: LatLon
protected abstract val index: Int
protected abstract val delta: Double
/** sort by index, then delta, ascending. The algorithm relies on this order! */
override fun compareTo(other: SplitWayAt): Int {
val diffIndex = index - other.index
if (diffIndex != 0) return diffIndex
val diffDelta = delta - other.delta
return diffDelta.sign.toInt()
}
}
data class SplitWayAtIndex(override val pos: LatLon, public override val index: Int) : SplitWayAt() {
override val delta get() = 0.0
}
data class SplitWayAtLinePosition(val pos1: LatLon, val index1: Int,
val pos2: LatLon, val index2: Int,
public override val delta: Double) : SplitWayAt() {
override val index get() = index1
override val pos: LatLon
get() {
val line = listOf(pos1, pos2)
return line.pointOnPolylineFromStart(line.measuredLength() * delta)!!
}
}
/** creates a SplitWay from a SplitLineAtPosition, given the nodes of the way. So, basically it
* simply finds the node index/indices at which the split should be made.
* One SplitPolylineAtPosition will map to several SplitWays for self-intersecting ways that have
* a split at the position where they self-intersect. I.e. a way in the shape of an 8 split exactly
* in the centre.
* If the way changed significantly in the meantime, it will throw an ElementConflictException */
fun SplitPolylineAtPosition.toSplitWayAt(positions: List<LatLon>): SplitWayAt {
/* For stability reasons, or to be more precise, to be able to state in advance how many new
elements will be created by this change, we always only split at the first intersection of
self-intersecting. This doesn't make a huge difference anyway as self-intersecting ways are
very rare and likely an error and splitting such a way only once and not several times at
the same position does not lead to wrong or corrupted data */
return when(this) {
is SplitAtPoint -> toSplitWays(positions)
is SplitAtLinePosition -> toSplitWaysAt(positions)
}.first()
}
private fun SplitAtPoint.toSplitWays(positions: List<LatLon>): Collection<SplitWayAtIndex> {
/* could be several indices, for example if the way has the shape of an 8.
For example a line going through points 1,2,3,4,2,5
3 1
|\ /
| 2
|/ \
4 5
*/
var indicesOf = positions.osmIndicesOf(pos)
if (indicesOf.isEmpty()) throw ConflictException("To be split point has been moved")
indicesOf = indicesOf.filter { index -> index > 0 && index < positions.lastIndex }
if (indicesOf.isEmpty())
throw ConflictException("Split position is now at the very start or end of the way - can't split there")
return indicesOf.map { indexOf -> SplitWayAtIndex(pos, indexOf) }.sorted()
}
private fun SplitAtLinePosition.toSplitWaysAt(positions: List<LatLon>): Collection<SplitWayAtLinePosition> {
// could be several indices, for example if the way has the shape of an 8,
// see SplitAtPoint.toSplitWay
val indicesOf1 = positions.osmIndicesOf(pos1)
if (indicesOf1.isEmpty()) throw ConflictException("To be split line has been moved")
val indicesOf2 = positions.osmIndicesOf(pos2)
if (indicesOf2.isEmpty()) throw ConflictException("To be split line has been moved")
// ...and we need to find out which of the lines is meant
val result = mutableListOf<SplitWayAtLinePosition>()
for (i1 in indicesOf1) {
for (i2 in indicesOf2) {
/* For SplitAtLinePosition, the direction of the way does not matter. But for the
SplitWayAtLinePosition it must be in the same order as the OSM way. */
if (i1 + 1 == i2) result.add(SplitWayAtLinePosition(pos1, i1, pos2, i2, delta))
if (i2 + 1 == i1) result.add(SplitWayAtLinePosition(pos2, i2, pos1, i1, 1.0 - delta))
}
}
/* The result can still be several split SplitWayAtLinePosition: if two lines are on top of each
other. For example a line going through the points 1,2,3,4,2,1,5
3
|\
| 2 -- 1 -- 5
|/
4
*/
if (result.isNotEmpty())
return result.sorted()
else
throw ConflictException("End points of the to be split line are not directly successive anymore")
}
/** returns the indices at which the given pos is found in this list, taking into account the limited
* precision of positions in OSM. */
private fun List<LatLon>.osmIndicesOf(pos: LatLon): List<Int> =
mapIndexedNotNull { i, p -> if (p.equalsInOsm(pos)) i else null }
| gpl-3.0 | b4e369b9c7c8ba4d3aac5c1061ea34b3 | 44.254237 | 112 | 0.695131 | 4.110855 | false | false | false | false |
kikermo/Things-Audio-Renderer | renderer/src/main/java/org/kikermo/thingsaudio/renderer/api/ReceiverRepositoryImp.kt | 1 | 3034 | package org.kikermo.thingsaudio.renderer.api
import io.reactivex.Completable
import io.reactivex.Observable
import io.reactivex.subjects.BehaviorSubject
import io.reactivex.subjects.PublishSubject
import org.kikermo.thingsaudio.core.api.ReceiverRepository
import org.kikermo.thingsaudio.core.model.PlayState
import org.kikermo.thingsaudio.core.model.RepeatMode
import org.kikermo.thingsaudio.core.model.Track
import org.kikermo.thingsaudio.core.rx.RxSchedulers
import java.util.concurrent.Callable
import javax.inject.Inject
class ReceiverRepositoryImp @Inject constructor(
private val trackUpdatesObservable: Observable<Track>,
private val playStateObservable: Observable<PlayState>,
private val playPositionObservable: Observable<Int>,
private val playerControlActionsSubject: PublishSubject<PlayerControlActions>,
private val repeatModeBehaviourSubject: BehaviorSubject<RepeatMode>,
private val rxSchedulers: RxSchedulers
) : ReceiverRepository {
override fun setRepeatMode(repeatMode: RepeatMode) = createCompletable(Callable { repeatModeBehaviourSubject.onNext(repeatMode) })
override fun sendPauseCommand() = createCompletable(Callable {
playerControlActionsSubject.onNext(PlayerControlActions.Pause)
})
override fun sendStopCommand() = createCompletable(Callable {
playerControlActionsSubject.onNext(PlayerControlActions.Stop)
})
override fun sendPlayCommand() = createCompletable(Callable {
playerControlActionsSubject.onNext(PlayerControlActions.Play)
})
override fun sendSkipNextCommand(songsToSkip: Int) = createCompletable(Callable {
playerControlActionsSubject.onNext(PlayerControlActions.SkipNext(songsToSkip))
})
override fun sendSkipPreviousCommand(songsToSkip: Int) = createCompletable(Callable {
playerControlActionsSubject.onNext(PlayerControlActions.SkipPrevious(songsToSkip))
})
override fun addTrack(track: Track) = createCompletable(Callable {
playerControlActionsSubject.onNext(PlayerControlActions.AddTrack(track))
})
override fun deleteTrack(track: Track) = createCompletable(Callable {
playerControlActionsSubject.onNext(PlayerControlActions.DeleteTrack(track))
})
override fun clearTrackList() = createCompletable(Callable {
playerControlActionsSubject.onNext(PlayerControlActions.ClearTackList)
})
override fun addTrackList(trackList: List<Track>) = createCompletable(Callable {
playerControlActionsSubject.onNext(PlayerControlActions.AddTrackList(trackList))
})
override fun getTrackUpdates() = trackUpdatesObservable.subscribeOn(rxSchedulers.io())
override fun getPlayStateUpdates() = playStateObservable.subscribeOn(rxSchedulers.io())
override fun getPlayPositionUpdates() = playPositionObservable.subscribeOn(rxSchedulers.io())
private fun createCompletable(callable: Callable<*>): Completable {
return Completable.fromCallable(callable)
.subscribeOn(rxSchedulers.io())
}
}
| gpl-3.0 | 8d7f614fbdf69f70adc314d4d4036b7f | 41.732394 | 134 | 0.789717 | 4.762951 | false | false | false | false |
wordpress-mobile/WordPress-Stores-Android | plugins/woocommerce/src/main/kotlin/org/wordpress/android/fluxc/model/user/WCUserRole.kt | 2 | 844 | package org.wordpress.android.fluxc.model.user
enum class WCUserRole(val value: String = "") {
OWNER("owner"),
ADMINISTRATOR("administrator"),
EDITOR("editor"),
AUTHOR("author"),
CUSTOMER("customer"),
SUBSCRIBER("subscriber"),
SHOP_MANAGER("shop_manager"),
OTHER;
companion object {
private val valueMap = values().associateBy(WCUserRole::value)
/**
* Convert the base value into the associated UserRole object.
* There are plugins available that can add custom roles.
* So if we are unable to find a matching [WCUserRole] object, [OTHER] is returned.
* This is not currently supported by our app.
*/
fun fromValue(value: String) = valueMap[value] ?: OTHER
}
fun isSupported() = this == ADMINISTRATOR || this == SHOP_MANAGER
}
| gpl-2.0 | 220973b6c8d2670ae54f804b489cc31e | 31.461538 | 91 | 0.638626 | 4.373057 | false | false | false | false |
shkschneider/android_Skeleton | core/src/main/kotlin/me/shkschneider/skeleton/datax/IParser.kt | 1 | 1119 | package me.shkschneider.skeleton.datax
interface IParser<Object, Array> {
fun parse(string: String): Object?
fun keys(jsonObject: Object): List<String>
fun values(jsonObject: Object): List<Any>
fun has(jsonObject: Object, key: String): Boolean
// from Object
fun get(jsonObject: Object, key: String, fallback: Object? = null): Object?
fun array(jsonObject: Object, key: String, fallback: Array? = null): Array?
fun string(jsonObject: Object, key: String, fallback: String? = null): String?
fun number(jsonObject: Object, key: String, fallback: Number? = null): Number?
fun bool(jsonObject: Object, key: String, fallback: Boolean? = null): Boolean?
// from Array
fun get(jsonArray: Array, index: Int, fallback: Object? = null): Object?
fun array(jsonArray: Array, index: Int, fallback: Array? = null): Array?
fun string(jsonArray: Array, index: Int, fallback: String? = null): String?
fun number(jsonArray: Array, index: Int, fallback: Number? = null): Number?
fun bool(jsonArray: Array, index: Int, fallback: Boolean? = null): Boolean?
} | apache-2.0 | 05d778484db3ec55bc63697404fb167a | 29.27027 | 82 | 0.680965 | 3.885417 | false | false | false | false |
aCoder2013/general | general-gossip/src/main/java/com/song/general/gossip/GossipDigest.kt | 1 | 1064 | package com.song.general.gossip
import java.io.Serializable
import java.net.SocketAddress
/**
* Created by song on 2017/8/13.
*/
class GossipDigest(val socketAddress: SocketAddress, val generation: Long, val version: Int) : Serializable {
override fun equals(other: Any?): Boolean {
if (this === other) {
return true
}
if (other == null || javaClass != other.javaClass) {
return false
}
val that = other as GossipDigest?
if (version != that!!.version) {
return false
}
return socketAddress == that.socketAddress
}
override fun hashCode(): Int {
var result = socketAddress.hashCode()
result = 31 * result + version
return result
}
override fun toString(): String {
return "GossipDigest{" +
"inetAddress=" + socketAddress +
", version=" + version +
'}'
}
companion object {
private const val serialVersionUID = 557834866830039832L
}
}
| apache-2.0 | 36060c405d8d36852ed2668441c59244 | 23.181818 | 109 | 0.572368 | 4.707965 | false | false | false | false |
jrenner/kotlin-algorithms-ds | src/datastructs/tree/BinarySearchTree.kt | 1 | 3484 | package datastructs.tree
import java.util.ArrayList
import java.util.HashMap
public class BinarySearchTree<T: Comparable<T>> : Iterable<T> {
var root: Node<T>? = null
fun isEmpty(): Boolean {
return root == null
}
fun size(): Int {
return toList().size
}
override fun iterator(): Iterator<T> {
return toList().iterator()
}
fun toList(): List<out T> {
val list = ArrayList<T>()
fun addToList(node: Node<T>?) {
if (node == null) return
list.add(node.cargo)
addToList(node.left)
addToList(node.right)
}
addToList(root)
return list
}
/** Returns true if the item was added, false if it was already in the tree */
fun add(item: T): Boolean {
var result = true
if (root == null) {
root = Node<T>(item)
} else {
result = add(item, root!!)
}
return result
}
/** Returns true if the item was added, false if it was already in the tree */
fun add(item: T, node: Node<T>): Boolean {
var result = true
if (item < node.cargo) {
if (node.left == null) {
node.left = Node<T>(item)
} else {
result = add(item, node.left!!)
}
} else if (item > node.cargo) {
if (node.right == null) {
node.right = Node<T>(item)
} else {
result = add(item, node.right!!)
}
} else {
// item is equal, it is already in the tree
result = false
}
return result
}
fun contains(item: T): Boolean {
if (root == null) return false
var node: Node<T>? = root
while (node != null) {
val n = node!!
if (item == n.cargo) return true
if (item < n.cargo) {
node = n.left
} else {
node = n.right
}
}
return false
}
fun remove(item: T): Boolean {
return false
}
fun clear() {
root = null
}
fun details() {
println("BinarySearchTree, size: ${size()}")
val depthCount = HashMap<Int, Int>()
fun incDepth(depth: Int) {
val current = depthCount.getOrElse(depth, { 0 })
depthCount.put(depth, current + 1)
}
val sb = StringBuilder()
fun processNode(node: Node<T>?, depth: Int, side: String) {
if (node != null) {
sb.append(" " * depth)
sb.append("$side:${node.cargo}\n")
incDepth(depth)
processNode(node.left, depth + 1, "L")
processNode(node.right, depth + 1, "R")
}
}
processNode(root, 0, "*")
println(sb.toString())
for (level in depthCount.keySet()) {
println("depth $level: ${depthCount.get(level)}")
}
}
}
private class Node<T>(val cargo: T) {
var left: Node<T>? = null
var right: Node<T>? = null
override fun equals(other: Any?): Boolean {
if (other is Node<*>) {
return this.cargo == other.cargo
}
return false
}
}
/** Used in function details(), implementation */
fun String.times(num: Int): String{
val sb = StringBuilder()
for (n in 1..num) {
sb.append(this)
}
return sb.toString()
}
| apache-2.0 | 8795a5db765c29c28f4b02d3fb9c0709 | 24.617647 | 82 | 0.485362 | 4.060606 | false | false | false | false |
mercadopago/px-android | px-checkout/src/main/java/com/mercadopago/android/px/internal/datasource/cache/InitDiskCache.kt | 1 | 1581 | package com.mercadopago.android.px.internal.datasource.cache
import com.mercadopago.android.px.internal.callbacks.MPCall
import com.mercadopago.android.px.internal.core.FileManager
import com.mercadopago.android.px.internal.util.JsonUtil
import com.mercadopago.android.px.model.exceptions.ApiException
import com.mercadopago.android.px.model.internal.InitResponse
import com.mercadopago.android.px.services.Callback
import java.io.File
class InitDiskCache(private val fileManager: FileManager) : Cache<InitResponse?> {
private val initFile: File
init {
initFile = fileManager.create(DEF_FILE_NAME)
}
override fun get(): MPCall<InitResponse?> {
return MPCall { callback: Callback<InitResponse> -> read(callback) }
}
override fun put(initResponse: InitResponse) {
if (!isCached) {
fileManager.writeToFile(initFile, JsonUtil.toJson(initResponse))
}
}
override fun evict() {
if (isCached) {
fileManager.removeFile(initFile)
}
}
override fun isCached() = fileManager.exists(initFile)
private fun read(callback: Callback<InitResponse>) {
if (isCached) {
val fileContent = fileManager.readText(initFile)
val initResponse = JsonUtil.fromJson(fileContent, InitResponse::class.java)
initResponse?.let { callback.success(it) } ?: callback.failure(ApiException())
} else {
callback.failure(ApiException())
}
}
companion object {
private const val DEF_FILE_NAME = "px_init"
}
} | mit | 6953b10dcf72c8f0f29c8a64ab8da460 | 31.285714 | 90 | 0.686907 | 4.261456 | false | false | false | false |
Ruben-Sten/TeXiFy-IDEA | src/nl/hannahsten/texifyidea/run/linuxpdfviewer/evince/EvinceConversation.kt | 1 | 4889 | package nl.hannahsten.texifyidea.run.linuxpdfviewer.evince
import com.intellij.notification.Notification
import com.intellij.notification.NotificationType
import com.intellij.openapi.project.Project
import nl.hannahsten.texifyidea.TeXception
import nl.hannahsten.texifyidea.run.linuxpdfviewer.ViewerConversation
import nl.hannahsten.texifyidea.util.runCommand
import org.freedesktop.dbus.connections.impl.DBusConnection
import org.freedesktop.dbus.errors.NoReply
import org.freedesktop.dbus.errors.ServiceUnknown
import org.gnome.evince.Daemon
/**
* Send commands to Evince.
* For more information about D-Bus and forward/inverse search, see https://github.com/PHPirates/evince_dbus
*
* @author Thomas Schouten
*/
object EvinceConversation : ViewerConversation() {
/**
* Object path of the Evince daemon. Together with the object name, this allows us to find the
* D-Bus object which allows us to execute the FindDocument function, which is exported on the D-Bus
* by Evince.
*/
private const val evinceDaemonPath = "/org/gnome/evince/Daemon"
/**
* Object name of the Evince daemon.
*/
private const val evinceDaemonName = "org.gnome.evince.Daemon"
/**
* This variable will hold the latest known Evince process owner. We need to know the owner of the pdf file in order to execute forward search.
*/
private var processOwner: String? = null
/**
* Open a file in Evince, starting it if it is not running yet. This also finds the process owner of the pdf, so we can execute forward search later.
*/
fun openFile(pdfFilePath: String, project: Project) {
// Will do nothing if file is already open in Evince
findProcessOwner(pdfFilePath, project)
}
/**
* Execute forward search, highlighting a certain line in Evince.
* If a pdf file is given, it will execute FindDocument and open the pdf file again to find the latest process owner. If the pdf file is already open, this will do nothing.
*
* @param pdfPath Full path to a pdf file.
* @param sourceFilePath Full path to the LaTeX source file.
* @param line Line number in the source file to highlight in the pdf.
*/
override fun forwardSearch(pdfPath: String?, sourceFilePath: String, line: Int, project: Project, focusAllowed: Boolean) {
// If we are not allowed to change focus, we cannot open the pdf or do forward search because this will always change focus with Evince
if (!focusAllowed) {
return
}
if (pdfPath != null) {
findProcessOwner(pdfPath, project)
}
if (processOwner != null) {
// Theoretically we should use the Java D-Bus bindings as well to call SyncView, but that did
// not succeed with a NoReply exception, so we will execute a command via the shell
val command = "gdbus call --session --dest $processOwner --object-path /org/gnome/evince/Window/0 --method org.gnome.evince.Window.SyncView $sourceFilePath '($line, 1)' 0"
runCommand("bash", "-c", command)
}
else {
// If the user used the forward search menu action
if (pdfPath == null) {
Notification("LaTeX", "Could not execute forward search", "Please make sure you have compiled the document first, and that your path does not contain spaces.", NotificationType.ERROR).notify(project)
}
else {
throw TeXception("Could not execute forward search with Evince because something went wrong when finding the pdf file at $pdfPath")
}
}
}
/**
* Execute FindDocument on the D-Bus in order to find the process owner of the given pdf file, i.e. the process name which we can use for
* forward/inverse search.
* The value found will be saved for later use.
*
* @param pdfFilePath Full path to the pdf file to find the owner of.
*/
private fun findProcessOwner(pdfFilePath: String, project: Project) {
// Initialize a session bus
val connection = DBusConnection.getConnection(DBusConnection.DBusBusType.SESSION)
// Get the Daemon object using its bus name and object path
val daemon = connection.getRemoteObject(evinceDaemonName, evinceDaemonPath, Daemon::class.java)
// Call the method on the D-Bus by using the function we defined in the Daemon interface
// Catch a NoReply, because it is unknown why Evince cannot start so we don't try to fix that
try {
processOwner = daemon.FindDocument("file://$pdfFilePath", true)
}
catch (ignored: NoReply) {}
catch (e: ServiceUnknown) {
Notification("LaTeX", "Cannot communicate to Evince", "Please update Evince and then try again.", NotificationType.ERROR).notify(project)
}
}
}
| mit | 335e789b79d796fb648f3a0a7b97e6bf | 44.691589 | 215 | 0.68603 | 4.345778 | false | false | false | false |
ansman/okhttp | okhttp/src/main/kotlin/okhttp3/internal/ws/WebSocketWriter.kt | 7 | 5961 | /*
* Copyright (C) 2014 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package okhttp3.internal.ws
import java.io.Closeable
import java.io.IOException
import java.util.Random
import okhttp3.internal.ws.WebSocketProtocol.B0_FLAG_FIN
import okhttp3.internal.ws.WebSocketProtocol.B0_FLAG_RSV1
import okhttp3.internal.ws.WebSocketProtocol.B1_FLAG_MASK
import okhttp3.internal.ws.WebSocketProtocol.OPCODE_CONTROL_CLOSE
import okhttp3.internal.ws.WebSocketProtocol.OPCODE_CONTROL_PING
import okhttp3.internal.ws.WebSocketProtocol.OPCODE_CONTROL_PONG
import okhttp3.internal.ws.WebSocketProtocol.PAYLOAD_BYTE_MAX
import okhttp3.internal.ws.WebSocketProtocol.PAYLOAD_LONG
import okhttp3.internal.ws.WebSocketProtocol.PAYLOAD_SHORT
import okhttp3.internal.ws.WebSocketProtocol.PAYLOAD_SHORT_MAX
import okhttp3.internal.ws.WebSocketProtocol.toggleMask
import okhttp3.internal.ws.WebSocketProtocol.validateCloseCode
import okio.Buffer
import okio.BufferedSink
import okio.ByteString
/**
* An [RFC 6455][rfc_6455]-compatible WebSocket frame writer.
*
* This class is not thread safe.
*
* [rfc_6455]: http://tools.ietf.org/html/rfc6455
*/
class WebSocketWriter(
private val isClient: Boolean,
val sink: BufferedSink,
val random: Random,
private val perMessageDeflate: Boolean,
private val noContextTakeover: Boolean,
private val minimumDeflateSize: Long
) : Closeable {
/** This holds outbound data for compression and masking. */
private val messageBuffer = Buffer()
/** The [Buffer] of [sink]. Write to this and then flush/emit [sink]. */
private val sinkBuffer: Buffer = sink.buffer
private var writerClosed = false
/** Lazily initialized on first use. */
private var messageDeflater: MessageDeflater? = null
// Masks are only a concern for client writers.
private val maskKey: ByteArray? = if (isClient) ByteArray(4) else null
private val maskCursor: Buffer.UnsafeCursor? = if (isClient) Buffer.UnsafeCursor() else null
/** Send a ping with the supplied [payload]. */
@Throws(IOException::class)
fun writePing(payload: ByteString) {
writeControlFrame(OPCODE_CONTROL_PING, payload)
}
/** Send a pong with the supplied [payload]. */
@Throws(IOException::class)
fun writePong(payload: ByteString) {
writeControlFrame(OPCODE_CONTROL_PONG, payload)
}
/**
* Send a close frame with optional code and reason.
*
* @param code Status code as defined by
* [Section 7.4 of RFC 6455](http://tools.ietf.org/html/rfc6455#section-7.4) or `0`.
* @param reason Reason for shutting down or `null`.
*/
@Throws(IOException::class)
fun writeClose(code: Int, reason: ByteString?) {
var payload = ByteString.EMPTY
if (code != 0 || reason != null) {
if (code != 0) {
validateCloseCode(code)
}
payload = Buffer().run {
writeShort(code)
if (reason != null) {
write(reason)
}
readByteString()
}
}
try {
writeControlFrame(OPCODE_CONTROL_CLOSE, payload)
} finally {
writerClosed = true
}
}
@Throws(IOException::class)
private fun writeControlFrame(opcode: Int, payload: ByteString) {
if (writerClosed) throw IOException("closed")
val length = payload.size
require(length <= PAYLOAD_BYTE_MAX) {
"Payload size must be less than or equal to $PAYLOAD_BYTE_MAX"
}
val b0 = B0_FLAG_FIN or opcode
sinkBuffer.writeByte(b0)
var b1 = length
if (isClient) {
b1 = b1 or B1_FLAG_MASK
sinkBuffer.writeByte(b1)
random.nextBytes(maskKey!!)
sinkBuffer.write(maskKey)
if (length > 0) {
val payloadStart = sinkBuffer.size
sinkBuffer.write(payload)
sinkBuffer.readAndWriteUnsafe(maskCursor!!)
maskCursor.seek(payloadStart)
toggleMask(maskCursor, maskKey)
maskCursor.close()
}
} else {
sinkBuffer.writeByte(b1)
sinkBuffer.write(payload)
}
sink.flush()
}
@Throws(IOException::class)
fun writeMessageFrame(formatOpcode: Int, data: ByteString) {
if (writerClosed) throw IOException("closed")
messageBuffer.write(data)
var b0 = formatOpcode or B0_FLAG_FIN
if (perMessageDeflate && data.size >= minimumDeflateSize) {
val messageDeflater = this.messageDeflater
?: MessageDeflater(noContextTakeover).also { this.messageDeflater = it }
messageDeflater.deflate(messageBuffer)
b0 = b0 or B0_FLAG_RSV1
}
val dataSize = messageBuffer.size
sinkBuffer.writeByte(b0)
var b1 = 0
if (isClient) {
b1 = b1 or B1_FLAG_MASK
}
when {
dataSize <= PAYLOAD_BYTE_MAX -> {
b1 = b1 or dataSize.toInt()
sinkBuffer.writeByte(b1)
}
dataSize <= PAYLOAD_SHORT_MAX -> {
b1 = b1 or PAYLOAD_SHORT
sinkBuffer.writeByte(b1)
sinkBuffer.writeShort(dataSize.toInt())
}
else -> {
b1 = b1 or PAYLOAD_LONG
sinkBuffer.writeByte(b1)
sinkBuffer.writeLong(dataSize)
}
}
if (isClient) {
random.nextBytes(maskKey!!)
sinkBuffer.write(maskKey)
if (dataSize > 0L) {
messageBuffer.readAndWriteUnsafe(maskCursor!!)
maskCursor.seek(0L)
toggleMask(maskCursor, maskKey)
maskCursor.close()
}
}
sinkBuffer.write(messageBuffer, dataSize)
sink.emit()
}
override fun close() {
messageDeflater?.close()
}
}
| apache-2.0 | e8fe6f4f6fc33d77ca820ca67ea5fdab | 28.656716 | 94 | 0.685288 | 3.921711 | false | false | false | false |
AoEiuV020/PaNovel | app/src/main/java/cc/aoeiuv020/panovel/util/notification.kt | 1 | 8124 | package cc.aoeiuv020.panovel.util
import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.Context
import android.os.Build
import android.os.Handler
import android.os.Looper
import androidx.core.app.NotificationCompat
import androidx.core.app.NotificationManagerCompat
import cc.aoeiuv020.panovel.BuildConfig
import cc.aoeiuv020.panovel.R
import cc.aoeiuv020.panovel.main.MainActivity
import org.jetbrains.anko.AnkoLogger
import org.jetbrains.anko.intentFor
import java.util.concurrent.TimeUnit
/**
* Created by AoEiuV020 on 2018.10.06-19:33:43.
*/
object NotificationChannelId {
const val default = BuildConfig.APPLICATION_ID + ".default"
const val update = BuildConfig.APPLICATION_ID + ".update"
const val download = BuildConfig.APPLICATION_ID + ".download"
const val downloading = BuildConfig.APPLICATION_ID + ".downloading"
const val export = BuildConfig.APPLICATION_ID + ".export"
}
/**
* 初始化项目中用到的通知渠道,
*/
fun Context.initNotificationChannel() {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) {
return
}
val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
notificationManager.createNotificationChannel(
NotificationChannel(
NotificationChannelId.default,
getString(R.string.channel_name_default),
NotificationManager.IMPORTANCE_DEFAULT).apply {
description = getString(R.string.channel_description_default)
}
)
notificationManager.createNotificationChannel(
NotificationChannel(
NotificationChannelId.update,
getString(R.string.channel_name_update),
NotificationManager.IMPORTANCE_DEFAULT).apply {
description = getString(R.string.channel_description_update)
}
)
notificationManager.createNotificationChannel(
NotificationChannel(
NotificationChannelId.download,
getString(R.string.channel_name_download),
NotificationManager.IMPORTANCE_DEFAULT).apply {
description = getString(R.string.channel_description_download)
}
)
notificationManager.createNotificationChannel(
NotificationChannel(
NotificationChannelId.downloading,
getString(R.string.channel_name_downloading),
NotificationManager.IMPORTANCE_DEFAULT).apply {
description = getString(R.string.channel_description_downloading)
}
)
notificationManager.createNotificationChannel(
NotificationChannel(
NotificationChannelId.export,
getString(R.string.channel_name_export),
NotificationManager.IMPORTANCE_DEFAULT).apply {
description = getString(R.string.channel_description_export)
}
)
}
/**
* 用来代理循环通知的情况,
* 没有死循环,就算不主动结束,也会在delay时间后自动结束,
*/
class NotifyLoopProxy(
ctx: Context,
private val id: Int = (Math.random() * Int.MAX_VALUE).toInt(),
// 最多delay毫秒一个通知,
private val delay: Long = 300L
) : AnkoLogger {
companion object {
val DEFAULT_CANCEL_DELAY: Long = TimeUnit.SECONDS.toMillis(5)
}
private val handler = Handler(Looper.getMainLooper())
// System services not available to Activities before onCreate()
private val manager by lazy { NotificationManagerCompat.from(ctx) }
private var waiting = false
private var done = false
private var canceled = false
private var cancelDelay: Long = DEFAULT_CANCEL_DELAY
private var mNotification: Notification? = null
private val cancelBlock = Runnable {
// 如果延时期间取消了取消,就不取消,
if (canceled) {
manager.cancel(id)
}
}
private val loopBlock = Runnable {
// 取出wrapper中的notification,
if (mNotification != null) {
notifyCached()
}
if (canceled) {
handler.postDelayed(cancelBlock, cancelDelay)
}
// 执行完了取消等待状态,
waiting = false
}
private val mainThread = Looper.getMainLooper().thread
private fun runOnUiThread(block: () -> Unit) {
if (mainThread == Thread.currentThread()) {
block()
} else {
handler.post(block)
}
}
private fun notifyCached() {
val notification = mNotification
// 置空,免得重复弹,
mNotification = null
notification?.let { n ->
runOnUiThread {
manager.notify(id, n)
}
}
}
fun start(notification: Notification) {
done = false
canceled = false
handler.removeCallbacks(cancelBlock)
handler.removeCallbacks(loopBlock)
// 循环开始前先弹一次通知,
// 之后隔delay时间弹一次,
mNotification = notification
notifyCached()
waiting = true
handler.postDelayed(loopBlock, delay)
}
fun modify(notification: Notification) {
// 如果已经结束,无视modify, 不再弹通知,
if (done) return
// 如果正在等待状态,也就是loopBlock已经提交,还没执行,
// 直接修改当前缓存的notification,
// 不论当前是否已经存在notification, 只弹最后一个通知,跳过频率过高的通知,
mNotification = notification
if (!waiting) {
notifyCached()
waiting = true
handler.postDelayed(loopBlock, delay)
}
}
fun complete(notification: Notification) {
done = true
// 就算完成了,也等最后一个循环节走完,
// 这里无视线程冲突,尽量都只用主线程,
// 要是说刚好主线程正在进入loopBlock拿走notification,可能导致最后一个通知不是完成通知,
mNotification = notification
if (!waiting) {
notifyCached()
}
}
fun cancel(cancelDelay: Long = DEFAULT_CANCEL_DELAY) {
if (canceled) {
return
}
canceled = true
this.cancelDelay = cancelDelay
if (!waiting) {
handler.postDelayed(cancelBlock, cancelDelay)
}
}
fun error() {
done = true
waiting = false
// 出错了直接停止循环,
handler.removeCallbacks(loopBlock)
}
}
fun Context.notify(id: Int, text: String? = null, title: String? = null, icon: Int = R.mipmap.ic_launcher_foreground, time: Long? = null, bigText: String? = null, channelId: String = NotificationChannelId.default) {
val intent = intentFor<MainActivity>()
val pendingIntent = PendingIntent.getActivity(this, 0, intent, 0)
val nb = NotificationCompat.Builder(this, channelId)
.setContentTitle(title)
.setContentText(text)
.setAutoCancel(true)
.setOnlyAlertOnce(true)
.setContentIntent(pendingIntent)
bigText?.let {
nb.setStyle(NotificationCompat.BigTextStyle().bigText(it))
}
time?.let {
nb.setWhen(it)
}
nb.apply {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
setLargeIcon(getBitmapFromVectorDrawable(icon))
setSmallIcon(R.mipmap.ic_launcher_round)
} else {
setSmallIcon(icon)
}
}
val manager = NotificationManagerCompat.from(this)
manager.notify(id, nb.build())
}
fun Context.cancelNotify(id: Int) {
val manager = NotificationManagerCompat.from(this)
manager.cancel(id)
}
fun Context.cancelAllNotify() {
val manager = NotificationManagerCompat.from(this)
manager.cancelAll()
}
| gpl-3.0 | 06324463602b3a5f7ae3363d203eac26 | 30.823529 | 215 | 0.630974 | 4.551683 | false | false | false | false |
arturbosch/detekt | detekt-tooling/src/test/kotlin/io/github/detekt/tooling/api/FunctionSignatureSpec.kt | 1 | 7437 | package io.github.detekt.tooling.api
import io.github.detekt.test.utils.compileContentForTest
import io.gitlab.arturbosch.detekt.rules.setupKotlinEnvironment
import io.gitlab.arturbosch.detekt.test.getContextForPaths
import org.assertj.core.api.Assertions.assertThat
import org.jetbrains.kotlin.cli.jvm.compiler.KotlinCoreEnvironment
import org.jetbrains.kotlin.psi.KtNamedFunction
import org.jetbrains.kotlin.resolve.BindingContext
import org.spekframework.spek2.Spek
import org.spekframework.spek2.style.specification.describe
class FunctionSignatureSpec : Spek({
setupKotlinEnvironment()
val env: KotlinCoreEnvironment by memoized()
describe("MethodSignature.fromString") {
listOf(
TestCase(
testDescription = "should return method name and null params list in case of simplifies signature",
methodSignature = "java.time.LocalDate.now",
expectedFunctionSignature = FunctionSignature.Name("java.time.LocalDate.now"),
),
TestCase(
testDescription = "should return method name and empty params list for full signature parameterless method",
methodSignature = "java.time.LocalDate.now()",
expectedFunctionSignature = FunctionSignature.Parameters("java.time.LocalDate.now", emptyList()),
),
TestCase(
testDescription = "should return method name and params list for full signature method with single param",
methodSignature = "java.time.LocalDate.now(java.time.Clock)",
expectedFunctionSignature = FunctionSignature.Parameters(
"java.time.LocalDate.now",
listOf("java.time.Clock"),
),
),
TestCase(
testDescription = "should return method name and params list for full signature method with multiple params",
methodSignature = "java.time.LocalDate.of(kotlin.Int, kotlin.Int, kotlin.Int)",
expectedFunctionSignature = FunctionSignature.Parameters(
"java.time.LocalDate.of",
listOf("kotlin.Int", "kotlin.Int", "kotlin.Int"),
),
),
TestCase(
testDescription = "should return method name and params list for full signature method with multiple params " +
"where method name has spaces and special characters",
methodSignature = "io.gitlab.arturbosch.detekt.SomeClass.`some , method`(kotlin.String)",
expectedFunctionSignature = FunctionSignature.Parameters(
"io.gitlab.arturbosch.detekt.SomeClass.some , method",
listOf("kotlin.String"),
),
)
).forEach { testCase ->
it(testCase.testDescription) {
val functionSignature = FunctionSignature.fromString(testCase.methodSignature)
assertThat(functionSignature).isEqualTo(testCase.expectedFunctionSignature)
}
}
}
describe("match KtNamedFunctions") {
matrixCase.forEach { (methodSignature, cases) ->
context("When $methodSignature") {
cases.forEach { (code, result) ->
it("in case $code it returns $result") {
val (function, bindingContext) = buildKtFunction(env, code)
assertThat(methodSignature.match(function, bindingContext)).apply {
if (result) isTrue() else isFalse()
}
}
}
}
}
}
})
private val matrixCase: Map<FunctionSignature, Map<String, Boolean>> = run {
val functions = arrayOf(
"fun toString() = Unit",
"fun toString(hello: String) = Unit",
"fun toString(hello: String, world: Int) = Unit",
"fun compare() = Unit",
"fun compare(hello: String) = Unit",
"fun compare(hello: String, world: Int) = Unit",
)
linkedMapOf(
FunctionSignature.fromString("toString") to linkedMapOf(
functions[0] to true, // fun toString()
functions[1] to true, // fun toString(hello: String)
functions[2] to true, // fun toString(hello: String, world: Int)
functions[3] to false, // fun compare()
functions[4] to false, // fun compare(hello: String)
functions[5] to false, // fun compare(hello: String, world: Int)
),
FunctionSignature.fromString("toString()") to linkedMapOf(
functions[0] to true, // fun toString()
functions[1] to false, // fun toString(hello: String)
functions[2] to false, // fun toString(hello: String, world: Int)
functions[3] to false, // fun compare()
functions[4] to false, // fun compare(hello: String)
functions[5] to false, // fun compare(hello: String, world: Int)
),
FunctionSignature.fromString("toString(kotlin.String)") to linkedMapOf(
functions[0] to false, // fun toString()
functions[1] to true, // fun toString(hello: String)
functions[2] to false, // fun toString(hello: String, world: Int)
functions[3] to false, // fun compare()
functions[4] to false, // fun compare(hello: String)
functions[5] to false, // fun compare(hello: String, world: Int)
),
FunctionSignature.fromString("toString(kotlin.Int)") to linkedMapOf(
functions[0] to false, // fun toString()
functions[1] to false, // fun toString(hello: String)
functions[2] to false, // fun toString(hello: String, world: Int)
functions[3] to false, // fun compare()
functions[4] to false, // fun compare(hello: String)
functions[5] to false, // fun compare(hello: String, world: Int)
),
FunctionSignature.fromString("toString(kotlin.String, kotlin.Int)") to linkedMapOf(
functions[0] to false, // fun toString()
functions[1] to false, // fun toString(hello: String)
functions[2] to true, // fun toString(hello: String, world: Int)
functions[3] to false, // fun compare()
functions[4] to false, // fun compare(hello: String)
functions[5] to false, // fun compare(hello: String, world: Int)
),
FunctionSignature.fromString("toString(String)") to linkedMapOf(
functions[0] to false, // fun toString()
functions[1] to false, // fun toString(hello: String)
functions[2] to false, // fun toString(hello: String, world: Int)
functions[3] to false, // fun compare()
functions[4] to false, // fun compare(hello: String)
functions[5] to false, // fun compare(hello: String, world: Int)
),
)
}
private class TestCase(
val testDescription: String,
val methodSignature: String,
val expectedFunctionSignature: FunctionSignature,
)
private fun buildKtFunction(environment: KotlinCoreEnvironment, code: String): Pair<KtNamedFunction, BindingContext> {
val ktFile = compileContentForTest(code)
val bindingContext = getContextForPaths(environment, listOf(ktFile))
return ktFile.findChildByClass(KtNamedFunction::class.java)!! to bindingContext
}
| apache-2.0 | c2c6896d2795c2124e09ef86bb8767d0 | 48.251656 | 127 | 0.612478 | 4.791881 | false | true | false | false |
ohmae/mmupnp | mmupnp/src/main/java/net/mm2d/upnp/internal/manager/SubscribeServiceHolder.kt | 1 | 5384 | /*
* Copyright (c) 2019 大前良介 (OHMAE Ryosuke)
*
* This software is released under the MIT License.
* http://opensource.org/licenses/MIT
*/
package net.mm2d.upnp.internal.manager
import kotlinx.coroutines.runBlocking
import net.mm2d.upnp.Service
import net.mm2d.upnp.internal.thread.TaskExecutors
import net.mm2d.upnp.internal.thread.ThreadCondition
import java.util.concurrent.TimeUnit
import java.util.concurrent.locks.ReentrantLock
import kotlin.concurrent.withLock
/**
* Class to manage the Service that became subscribed state.
*
* If specified, renew will be executed periodically so that the Subscription will not expire.
* Also, expired services are deleted.
*
* @author [大前良介 (OHMAE Ryosuke)](mailto:[email protected])
*/
internal class SubscribeServiceHolder(
taskExecutors: TaskExecutors
) : Runnable {
private val threadCondition = ThreadCondition(taskExecutors.manager)
private val lock = ReentrantLock()
private val condition = lock.newCondition()
private val subscriptionMap = mutableMapOf<String, SubscribeService>()
fun start(): Unit = threadCondition.start(this)
fun stop(): Unit = threadCondition.stop()
fun add(service: Service, timeout: Long, keepRenew: Boolean): Unit = lock.withLock {
val id = service.subscriptionId
if (id.isNullOrEmpty()) {
return
}
subscriptionMap[id] = SubscribeService(service, timeout, keepRenew)
condition.signalAll()
}
fun renew(service: Service, timeout: Long): Unit = lock.withLock {
subscriptionMap[service.subscriptionId]?.renew(timeout)
}
fun setKeepRenew(service: Service, keep: Boolean): Unit = lock.withLock {
subscriptionMap[service.subscriptionId]?.setKeepRenew(keep)
condition.signalAll()
}
fun remove(service: Service): Unit = lock.withLock {
subscriptionMap.remove(service.subscriptionId)?.let {
condition.signalAll()
}
}
fun getService(subscriptionId: String): Service? = lock.withLock {
subscriptionMap[subscriptionId]?.service
}
fun clear(): Unit = lock.withLock {
subscriptionMap.values.forEach {
runBlocking {
it.service.unsubscribe()
}
}
subscriptionMap.clear()
}
override fun run() {
Thread.currentThread().let {
it.name = it.name + "-subscribe-holder"
}
try {
while (!threadCondition.isCanceled()) {
runBlocking {
renewSubscribe(waitEntry())
removeExpiredService()
}
waitNextRenewTime()
}
} catch (ignored: InterruptedException) {
}
}
/**
* Wait until some entry is added to ServiceList.
*
* Returns a collection of Service that triggers renew as return value.
* Since the renew process is executed without exclusion,
* it returns a copy which has no other effect so that there is no need for exclusion.
*
* @return collection of Service that triggers renew
* @throws InterruptedException An interrupt occurred
*/
@Throws(InterruptedException::class)
private fun waitEntry(): Collection<SubscribeService> = lock.withLock {
while (subscriptionMap.isEmpty()) {
condition.await()
}
// 操作をロックしないようにコピーに対して処理を行う。
ArrayList(subscriptionMap.values)
}
/**
* Trigger renew on the argument [Service].
*
* This process does not exclude the whole because it includes network communication.
* Therefore, the argument list is a collection that is not accessed by others.
*
* @param serviceList [Service] collection
*/
private suspend fun renewSubscribe(serviceList: Collection<SubscribeService>) {
serviceList.forEach {
if (!it.renewSubscribe(System.currentTimeMillis()) && it.isFailed()) {
remove(it.service)
}
}
}
/**
* Remove expired [Service].
*/
private suspend fun removeExpiredService(): Unit = lock.withLock {
val now = System.currentTimeMillis()
subscriptionMap.values
.filter { it.isExpired(now) }
.map { it.service }
.forEach {
remove(it)
runBlocking {
it.unsubscribe()
}
}
}
/**
* Wait until the latest Renew execution time.
*
* @throws InterruptedException An interrupt occurred
*/
@Throws(InterruptedException::class)
private fun waitNextRenewTime(): Unit = lock.withLock {
if (subscriptionMap.isEmpty()) {
return
}
val sleep = maxOf(findMostRecentTime() - System.currentTimeMillis(), MIN_INTERVAL)
// ビジーループを回避するため最小値を設ける
condition.await(sleep, TimeUnit.MILLISECONDS)
}
/**
* Returns the closest one of the times to scan.
*
* @return Next time to scan
*/
private fun findMostRecentTime(): Long =
subscriptionMap.values.minByOrNull { it.getNextScanTime() }?.getNextScanTime() ?: 0L
companion object {
private val MIN_INTERVAL = TimeUnit.SECONDS.toMillis(1)
}
}
| mit | 3a9af16ea8e0facabca6997867d629bd | 30.60479 | 94 | 0.631679 | 4.666667 | false | false | false | false |
openHPI/android-app | app/src/main/java/de/xikolo/controllers/video/VideoItemPlayerActivity.kt | 1 | 3915 | package de.xikolo.controllers.video
import android.content.Intent
import android.content.res.Configuration
import android.os.Bundle
import android.view.View
import android.view.ViewGroup
import android.widget.RelativeLayout
import butterknife.BindView
import com.google.android.gms.cast.framework.CastState
import com.yatatsu.autobundle.AutoBundleField
import de.xikolo.R
import de.xikolo.controllers.helper.VideoSettingsHelper
import de.xikolo.controllers.video.base.BaseVideoPlayerActivity
import de.xikolo.models.dao.VideoDao
import de.xikolo.utils.LanalyticsUtil
import de.xikolo.utils.extensions.cast
class VideoItemPlayerActivity : BaseVideoPlayerActivity() {
companion object {
val TAG: String = VideoItemPlayerActivity::class.java.simpleName
}
@AutoBundleField
lateinit var courseId: String
@AutoBundleField
lateinit var sectionId: String
@AutoBundleField
lateinit var itemId: String
@AutoBundleField
lateinit var videoId: String
@AutoBundleField(required = false)
override var parentIntent: Intent? = null
@AutoBundleField(required = false)
override var overrideActualParent: Boolean = false
@BindView(R.id.videoSecondaryFragment)
lateinit var descriptionFragmentContainer: ViewGroup
lateinit var descriptionFragment: VideoDescriptionFragment
override val layoutResource = R.layout.activity_video_dual
override fun createPlayerFragment(): VideoStreamPlayerFragment {
return VideoItemPlayerFragment.create(courseId, sectionId, itemId, videoId)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
updateDescriptionFragment()
}
private fun updateDescriptionFragment() {
descriptionFragment = VideoDescriptionFragmentAutoBundle.builder(itemId, videoId).build()
val fragmentTag = descriptionFragment.hashCode().toString()
val fragmentManager = supportFragmentManager
if (fragmentManager.findFragmentByTag(fragmentTag) == null) {
val transaction = fragmentManager.beginTransaction()
transaction.replace(R.id.videoSecondaryFragment, descriptionFragment, fragmentTag)
transaction.commit()
}
}
override fun onNewIntent(intent: Intent?) {
super.onNewIntent(intent)
if (intent != null) {
updateDescriptionFragment()
}
}
override fun onCastStateChanged(newState: Int) {
super.onCastStateChanged(newState)
if (newState == CastState.CONNECTED) {
LanalyticsUtil.trackVideoPlay(itemId,
courseId, sectionId,
playerFragment.currentPosition,
VideoSettingsHelper.PlaybackSpeed.X10.value,
Configuration.ORIENTATION_LANDSCAPE,
"hd",
"cast"
)
VideoDao.Unmanaged.find(videoId)?.cast(this, true)
finish()
}
}
override fun updateVideoView(orientation: Int) {
super.updateVideoView(orientation)
val playerLayoutParams = playerFragmentContainer.layoutParams as RelativeLayout.LayoutParams
if (isInLandscape(orientation)) {
descriptionFragmentContainer.visibility = View.GONE
playerLayoutParams.addRule(RelativeLayout.CENTER_IN_PARENT, RelativeLayout.TRUE)
playerLayoutParams.removeRule(RelativeLayout.ALIGN_PARENT_TOP)
} else {
descriptionFragmentContainer.visibility = View.VISIBLE
playerLayoutParams.removeRule(RelativeLayout.CENTER_IN_PARENT)
playerLayoutParams.addRule(RelativeLayout.ALIGN_PARENT_TOP, RelativeLayout.TRUE)
}
if (!playerFragment.isShowingControls) {
actionBar?.hide()
}
}
override fun onControlsHidden() {
super.onControlsHidden()
actionBar?.hide()
}
}
| bsd-3-clause | e6e89c8b9dc1ee3d405c3784f1224e45 | 31.090164 | 100 | 0.706003 | 5.178571 | false | false | false | false |
JimSeker/drawing | TextureViewDemo_kt/app/src/main/java/edu/cs4730/textureviewdemo_kt/myTextureView.kt | 1 | 4125 | package edu.cs4730.textureviewdemo_kt
import android.content.Context
import android.graphics.Color
import android.graphics.Paint
import android.view.TextureView
import android.view.TextureView.SurfaceTextureListener
import android.graphics.SurfaceTexture
import kotlin.jvm.Volatile
import android.graphics.PorterDuff
import android.util.AttributeSet
import android.util.Log
/**
* This separates all the TextureView code into the TextureView.
*/
class myTextureView : TextureView, SurfaceTextureListener {
private lateinit var mThread: RenderingThread
var TAG = "myTextView"
// set of consturctors needed for the TextureView, most of which we then ignore the parameters anyway.
constructor(context: Context?) : super(context!!) {
Log.v(TAG, "constructor")
surfaceTextureListener = this //Required or the TextureView never starts up.
}
constructor(context: Context?, attrs: AttributeSet?) : super(
context!!
) {
Log.v(TAG, "constructor2")
surfaceTextureListener = this //Required or the TextureView never starts up.
}
constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int) : super(
context!!
) {
Log.v(TAG, "constructor3")
surfaceTextureListener = this //Required or the TextureView never starts up.
}
constructor(
context: Context?,
attrs: AttributeSet?,
defStyleAttr: Int,
defStyleRes: Int
) : super(
context!!
) {
Log.v(TAG, "constructor4")
surfaceTextureListener = this //Required or the TextureView never starts up.
}
/**
* TextureView.SurfaceTextureListener overrides below, that start up the drawing thread.
*/
override fun onSurfaceTextureAvailable(surface: SurfaceTexture, width: Int, height: Int) {
Log.v(TAG, "onSurfaceTextureAvailable")
//We can't override the draw(canvas) function, so we need to access the surface
//via here and pass it to the thread to draw on it.
mThread = RenderingThread(this)
mThread.start()
}
override fun onSurfaceTextureSizeChanged(surface: SurfaceTexture, width: Int, height: Int) {
// Ignored
Log.v(TAG, "onSurfaceTextureSizeChanged")
}
override fun onSurfaceTextureDestroyed(surface: SurfaceTexture): Boolean {
Log.v(TAG, "onSurfaceTextureDestroyed")
mThread.stopRendering()
return true
}
override fun onSurfaceTextureUpdated(surface: SurfaceTexture) {
//Log.v(TAG, "onSurfaceTextureUpdated"); //this is called a lot!
// Ignored
}
/*
* Thread to draw a green square moving around the textureView.
*/
internal inner class RenderingThread(private val mSurface: TextureView) : Thread() {
@Volatile
private var mRunning = true
override fun run() {
var x = 0.0f
var y = 0.0f
var speedX = 5.0f
var speedY = 3.0f
val paint = Paint()
paint.color = -0xff0100
while (mRunning && !interrupted()) {
val canvas = mSurface.lockCanvas(null)
try {
canvas!!.drawColor(Color.WHITE, PorterDuff.Mode.CLEAR)
//canvas.drawColor(Color.BLACK, PorterDuff.Mode.CLEAR);
canvas.drawRect(x, y, x + 20.0f, y + 20.0f, paint)
} finally {
mSurface.unlockCanvasAndPost(canvas!!)
}
if (x + 20.0f + speedX >= mSurface.width || x + speedX <= 0.0f) {
speedX = -speedX
}
if (y + 20.0f + speedY >= mSurface.height || y + speedY <= 0.0f) {
speedY = -speedY
}
x += speedX
y += speedY
try {
sleep(15)
} catch (e: InterruptedException) {
// Interrupted
}
}
}
fun stopRendering() {
interrupt()
mRunning = false
}
}
} | apache-2.0 | bb3c610ad8190725efc949c01229da73 | 32.544715 | 106 | 0.593939 | 4.796512 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.