repo_name
stringlengths 7
81
| path
stringlengths 6
242
| copies
stringclasses 53
values | size
stringlengths 2
6
| content
stringlengths 73
737k
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 5.44
99.8
| line_max
int64 15
977
| alpha_frac
float64 0.3
0.91
| ratio
float64 2
9.93
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
exponent/exponent | android/versioned-abis/expoview-abi43_0_0/src/main/java/abi43_0_0/host/exp/exponent/modules/api/components/pagerview/PagerViewViewManager.kt | 2 | 10552 | package abi43_0_0.host.exp.exponent.modules.api.components.pagerview
import android.view.View
import android.view.ViewGroup
import androidx.viewpager2.widget.ViewPager2
import androidx.viewpager2.widget.ViewPager2.OnPageChangeCallback
import com.facebook.infer.annotation.Assertions
import abi43_0_0.com.facebook.react.bridge.ReadableArray
import abi43_0_0.com.facebook.react.common.MapBuilder
import abi43_0_0.com.facebook.react.uimanager.PixelUtil
import abi43_0_0.com.facebook.react.uimanager.ThemedReactContext
import abi43_0_0.com.facebook.react.uimanager.UIManagerModule
import abi43_0_0.com.facebook.react.uimanager.ViewGroupManager
import abi43_0_0.com.facebook.react.uimanager.annotations.ReactProp
import abi43_0_0.com.facebook.react.uimanager.events.EventDispatcher
import abi43_0_0.host.exp.exponent.modules.api.components.pagerview.event.PageScrollEvent
import abi43_0_0.host.exp.exponent.modules.api.components.pagerview.event.PageScrollStateChangedEvent
import abi43_0_0.host.exp.exponent.modules.api.components.pagerview.event.PageSelectedEvent
class PagerViewViewManager : ViewGroupManager<NestedScrollableHost>() {
private lateinit var eventDispatcher: EventDispatcher
override fun getName(): String {
return REACT_CLASS
}
override fun createViewInstance(reactContext: ThemedReactContext): NestedScrollableHost {
val host = NestedScrollableHost(reactContext)
host.layoutParams = ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)
host.isSaveEnabled = false
val vp = ViewPager2(reactContext)
vp.adapter = ViewPagerAdapter()
// https://github.com/callstack/react-native-viewpager/issues/183
vp.isSaveEnabled = false
eventDispatcher = reactContext.getNativeModule(UIManagerModule::class.java)!!.eventDispatcher
vp.post {
vp.registerOnPageChangeCallback(object : OnPageChangeCallback() {
override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) {
super.onPageScrolled(position, positionOffset, positionOffsetPixels)
eventDispatcher.dispatchEvent(
PageScrollEvent(host.id, position, positionOffset)
)
}
override fun onPageSelected(position: Int) {
super.onPageSelected(position)
eventDispatcher.dispatchEvent(
PageSelectedEvent(host.id, position)
)
}
override fun onPageScrollStateChanged(state: Int) {
super.onPageScrollStateChanged(state)
val pageScrollState: String = when (state) {
ViewPager2.SCROLL_STATE_IDLE -> "idle"
ViewPager2.SCROLL_STATE_DRAGGING -> "dragging"
ViewPager2.SCROLL_STATE_SETTLING -> "settling"
else -> throw IllegalStateException("Unsupported pageScrollState")
}
eventDispatcher.dispatchEvent(
PageScrollStateChangedEvent(host.id, pageScrollState)
)
}
})
eventDispatcher.dispatchEvent(PageSelectedEvent(host.id, vp.currentItem))
}
host.addView(vp)
return host
}
private fun getViewPager(view: NestedScrollableHost): ViewPager2 {
if (view.getChildAt(0) is ViewPager2) {
return view.getChildAt(0) as ViewPager2
} else {
throw ClassNotFoundException("Could not retrieve ViewPager2 instance")
}
}
private fun setCurrentItem(view: ViewPager2, selectedTab: Int, scrollSmooth: Boolean) {
refreshViewChildrenLayout(view)
view.setCurrentItem(selectedTab, scrollSmooth)
}
override fun addView(host: NestedScrollableHost, child: View?, index: Int) {
if (child == null) {
return
}
val parent = getViewPager(host)
(parent.adapter as ViewPagerAdapter?)?.addChild(child, index)
if (parent.currentItem == index) {
// Solves https://github.com/callstack/react-native-pager-view/issues/219
// Required so ViewPager actually displays first dynamically added child
// (otherwise a white screen is shown until the next user interaction).
// https://github.com/facebook/react-native/issues/17968#issuecomment-697136929
refreshViewChildrenLayout(parent)
}
}
override fun getChildCount(parent: NestedScrollableHost) = getViewPager(parent).adapter?.itemCount ?: 0
override fun getChildAt(parent: NestedScrollableHost, index: Int): View {
val view = getViewPager(parent)
return (view.adapter as ViewPagerAdapter?)!!.getChildAt(index)
}
override fun removeView(parent: NestedScrollableHost, view: View) {
val pager = getViewPager(parent)
(pager.adapter as ViewPagerAdapter?)?.removeChild(view)
// Required so ViewPager actually animates the removed view right away (otherwise
// a white screen is shown until the next user interaction).
// https://github.com/facebook/react-native/issues/17968#issuecomment-697136929
refreshViewChildrenLayout(pager)
}
override fun removeAllViews(parent: NestedScrollableHost) {
val pager = getViewPager(parent)
pager.isUserInputEnabled = false
val adapter = pager.adapter as ViewPagerAdapter?
adapter?.removeAll()
}
override fun removeViewAt(parent: NestedScrollableHost, index: Int) {
val pager = getViewPager(parent)
val adapter = pager.adapter as ViewPagerAdapter?
adapter?.removeChildAt(index)
// Required so ViewPager actually animates the removed view right away (otherwise
// a white screen is shown until the next user interaction).
// https://github.com/facebook/react-native/issues/17968#issuecomment-697136929
refreshViewChildrenLayout(pager)
}
override fun needsCustomLayoutForChildren(): Boolean {
return true
}
@ReactProp(name = "scrollEnabled", defaultBoolean = true)
fun setScrollEnabled(host: NestedScrollableHost, value: Boolean) {
getViewPager(host).isUserInputEnabled = value
}
@ReactProp(name = "initialPage", defaultInt = 0)
fun setInitialPage(host: NestedScrollableHost, value: Int) {
val view = getViewPager(host)
// https://github.com/callstack/react-native-pager-view/issues/456
// Initial index should be set only once.
if (host.initialIndex === null) {
view.post {
setCurrentItem(view, value, false)
host.initialIndex = value
}
}
}
@ReactProp(name = "orientation")
fun setOrientation(host: NestedScrollableHost, value: String) {
getViewPager(host).orientation = if (value == "vertical") ViewPager2.ORIENTATION_VERTICAL else ViewPager2.ORIENTATION_HORIZONTAL
}
@ReactProp(name = "offscreenPageLimit", defaultInt = ViewPager2.OFFSCREEN_PAGE_LIMIT_DEFAULT)
operator fun set(host: NestedScrollableHost, value: Int) {
getViewPager(host).offscreenPageLimit = value
}
@ReactProp(name = "overScrollMode")
fun setOverScrollMode(host: NestedScrollableHost, value: String) {
val child = getViewPager(host).getChildAt(0)
when (value) {
"never" -> {
child.overScrollMode = ViewPager2.OVER_SCROLL_NEVER
}
"always" -> {
child.overScrollMode = ViewPager2.OVER_SCROLL_ALWAYS
}
else -> {
child.overScrollMode = ViewPager2.OVER_SCROLL_IF_CONTENT_SCROLLS
}
}
}
@ReactProp(name = "layoutDirection")
fun setLayoutDirection(host: NestedScrollableHost, value: String) {
val view = getViewPager(host)
when (value) {
"rtl" -> {
view.layoutDirection = View.LAYOUT_DIRECTION_RTL
}
else -> {
view.layoutDirection = View.LAYOUT_DIRECTION_LTR
}
}
}
override fun getExportedCustomDirectEventTypeConstants(): MutableMap<String, Map<String, String>> {
return MapBuilder.of(
PageScrollEvent.EVENT_NAME, MapBuilder.of("registrationName", "onPageScroll"),
PageScrollStateChangedEvent.EVENT_NAME, MapBuilder.of("registrationName", "onPageScrollStateChanged"),
PageSelectedEvent.EVENT_NAME, MapBuilder.of("registrationName", "onPageSelected")
)
}
override fun getCommandsMap(): Map<String, Int>? {
return MapBuilder.of(
"setPage",
COMMAND_SET_PAGE,
"setPageWithoutAnimation",
COMMAND_SET_PAGE_WITHOUT_ANIMATION,
"setScrollEnabled",
COMMAND_SET_SCROLL_ENABLED
)
}
override fun receiveCommand(root: NestedScrollableHost, commandId: Int, args: ReadableArray?) {
super.receiveCommand(root, commandId, args)
val view = getViewPager(root)
Assertions.assertNotNull(view)
Assertions.assertNotNull(args)
val childCount = view.adapter?.itemCount
when (commandId) {
COMMAND_SET_PAGE, COMMAND_SET_PAGE_WITHOUT_ANIMATION -> {
val pageIndex = args!!.getInt(0)
val canScroll = childCount != null && childCount > 0 && pageIndex >= 0 && pageIndex < childCount
if (canScroll) {
val scrollWithAnimation = commandId == COMMAND_SET_PAGE
setCurrentItem(view, pageIndex, scrollWithAnimation)
eventDispatcher.dispatchEvent(PageSelectedEvent(root.id, pageIndex))
}
}
COMMAND_SET_SCROLL_ENABLED -> {
view.isUserInputEnabled = args!!.getBoolean(0)
}
else -> throw IllegalArgumentException(
String.format(
"Unsupported command %d received by %s.",
commandId,
javaClass.simpleName
)
)
}
}
@ReactProp(name = "pageMargin", defaultFloat = 0F)
fun setPageMargin(host: NestedScrollableHost, margin: Float) {
val pager = getViewPager(host)
val pageMargin = PixelUtil.toPixelFromDIP(margin).toInt()
/**
* Don't use MarginPageTransformer to be able to support negative margins
*/
pager.setPageTransformer { page, position ->
val offset = pageMargin * position
if (pager.orientation == ViewPager2.ORIENTATION_HORIZONTAL) {
val isRTL = pager.layoutDirection == View.LAYOUT_DIRECTION_RTL
page.translationX = if (isRTL) -offset else offset
} else {
page.translationY = offset
}
}
}
private fun refreshViewChildrenLayout(view: View) {
view.post {
view.measure(
View.MeasureSpec.makeMeasureSpec(view.width, View.MeasureSpec.EXACTLY),
View.MeasureSpec.makeMeasureSpec(view.height, View.MeasureSpec.EXACTLY)
)
view.layout(view.left, view.top, view.right, view.bottom)
}
}
companion object {
private const val REACT_CLASS = "RNCViewPager"
private const val COMMAND_SET_PAGE = 1
private const val COMMAND_SET_PAGE_WITHOUT_ANIMATION = 2
private const val COMMAND_SET_SCROLL_ENABLED = 3
}
}
| bsd-3-clause | fad6dec3f1e8caf74c53444fcdf92b5a | 36.41844 | 132 | 0.710008 | 4.526813 | false | false | false | false |
deva666/anko | anko/library/generated/sdk21/src/Layouts.kt | 2 | 69586 | @file:JvmName("Sdk21LayoutsKt")
package org.jetbrains.anko
import android.content.Context
import android.util.AttributeSet
import android.view.ViewGroup
import android.widget.FrameLayout
import android.appwidget.AppWidgetHostView
import android.view.View
import android.webkit.WebView
import android.widget.AbsoluteLayout
import android.widget.ActionMenuView
import android.widget.Gallery
import android.widget.GridLayout
import android.widget.GridView
import android.widget.AbsListView
import android.widget.HorizontalScrollView
import android.widget.ImageSwitcher
import android.widget.LinearLayout
import android.widget.RadioGroup
import android.widget.RelativeLayout
import android.widget.ScrollView
import android.widget.TableLayout
import android.widget.TableRow
import android.widget.TextSwitcher
import android.widget.Toolbar
import android.app.ActionBar
import android.widget.ViewAnimator
import android.widget.ViewSwitcher
open class _AppWidgetHostView(ctx: Context): AppWidgetHostView(ctx) {
inline fun <T: View> T.lparams(
c: Context?,
attrs: AttributeSet?,
init: FrameLayout.LayoutParams.() -> Unit
): T {
val layoutParams = FrameLayout.LayoutParams(c!!, attrs!!)
layoutParams.init()
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
c: Context?,
attrs: AttributeSet?
): T {
val layoutParams = FrameLayout.LayoutParams(c!!, attrs!!)
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
init: FrameLayout.LayoutParams.() -> Unit
): T {
val layoutParams = FrameLayout.LayoutParams(width, height)
layoutParams.init()
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT
): T {
val layoutParams = FrameLayout.LayoutParams(width, height)
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
gravity: Int,
init: FrameLayout.LayoutParams.() -> Unit
): T {
val layoutParams = FrameLayout.LayoutParams(width, height, gravity)
layoutParams.init()
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
gravity: Int
): T {
val layoutParams = FrameLayout.LayoutParams(width, height, gravity)
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
source: ViewGroup.LayoutParams?,
init: FrameLayout.LayoutParams.() -> Unit
): T {
val layoutParams = FrameLayout.LayoutParams(source!!)
layoutParams.init()
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
source: ViewGroup.LayoutParams?
): T {
val layoutParams = FrameLayout.LayoutParams(source!!)
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
source: ViewGroup.MarginLayoutParams?,
init: FrameLayout.LayoutParams.() -> Unit
): T {
val layoutParams = FrameLayout.LayoutParams(source!!)
layoutParams.init()
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
source: ViewGroup.MarginLayoutParams?
): T {
val layoutParams = FrameLayout.LayoutParams(source!!)
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
source: FrameLayout.LayoutParams?,
init: FrameLayout.LayoutParams.() -> Unit
): T {
val layoutParams = FrameLayout.LayoutParams(source!!)
layoutParams.init()
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
source: FrameLayout.LayoutParams?
): T {
val layoutParams = FrameLayout.LayoutParams(source!!)
[email protected] = layoutParams
return this
}
}
open class _WebView(ctx: Context): WebView(ctx) {
inline fun <T: View> T.lparams(
c: Context?,
attrs: AttributeSet?,
init: ViewGroup.LayoutParams.() -> Unit
): T {
val layoutParams = ViewGroup.LayoutParams(c!!, attrs!!)
layoutParams.init()
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
c: Context?,
attrs: AttributeSet?
): T {
val layoutParams = ViewGroup.LayoutParams(c!!, attrs!!)
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
init: ViewGroup.LayoutParams.() -> Unit
): T {
val layoutParams = ViewGroup.LayoutParams(width, height)
layoutParams.init()
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT
): T {
val layoutParams = ViewGroup.LayoutParams(width, height)
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
source: ViewGroup.LayoutParams?,
init: ViewGroup.LayoutParams.() -> Unit
): T {
val layoutParams = ViewGroup.LayoutParams(source!!)
layoutParams.init()
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
source: ViewGroup.LayoutParams?
): T {
val layoutParams = ViewGroup.LayoutParams(source!!)
[email protected] = layoutParams
return this
}
}
open class _AbsoluteLayout(ctx: Context): AbsoluteLayout(ctx) {
inline fun <T: View> T.lparams(
width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
x: Int,
y: Int,
init: AbsoluteLayout.LayoutParams.() -> Unit
): T {
val layoutParams = AbsoluteLayout.LayoutParams(width, height, x, y)
layoutParams.init()
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
x: Int,
y: Int
): T {
val layoutParams = AbsoluteLayout.LayoutParams(width, height, x, y)
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
c: Context?,
attrs: AttributeSet?,
init: AbsoluteLayout.LayoutParams.() -> Unit
): T {
val layoutParams = AbsoluteLayout.LayoutParams(c!!, attrs!!)
layoutParams.init()
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
c: Context?,
attrs: AttributeSet?
): T {
val layoutParams = AbsoluteLayout.LayoutParams(c!!, attrs!!)
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
source: ViewGroup.LayoutParams?,
init: AbsoluteLayout.LayoutParams.() -> Unit
): T {
val layoutParams = AbsoluteLayout.LayoutParams(source!!)
layoutParams.init()
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
source: ViewGroup.LayoutParams?
): T {
val layoutParams = AbsoluteLayout.LayoutParams(source!!)
[email protected] = layoutParams
return this
}
}
open class _ActionMenuView(ctx: Context): ActionMenuView(ctx) {
inline fun <T: View> T.lparams(
c: Context?,
attrs: AttributeSet?,
init: ActionMenuView.LayoutParams.() -> Unit
): T {
val layoutParams = ActionMenuView.LayoutParams(c!!, attrs!!)
layoutParams.init()
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
c: Context?,
attrs: AttributeSet?
): T {
val layoutParams = ActionMenuView.LayoutParams(c!!, attrs!!)
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
other: ViewGroup.LayoutParams?,
init: ActionMenuView.LayoutParams.() -> Unit
): T {
val layoutParams = ActionMenuView.LayoutParams(other!!)
layoutParams.init()
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
other: ViewGroup.LayoutParams?
): T {
val layoutParams = ActionMenuView.LayoutParams(other!!)
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
other: ActionMenuView.LayoutParams?,
init: ActionMenuView.LayoutParams.() -> Unit
): T {
val layoutParams = ActionMenuView.LayoutParams(other!!)
layoutParams.init()
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
other: ActionMenuView.LayoutParams?
): T {
val layoutParams = ActionMenuView.LayoutParams(other!!)
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
init: ActionMenuView.LayoutParams.() -> Unit
): T {
val layoutParams = ActionMenuView.LayoutParams(width, height)
layoutParams.init()
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT
): T {
val layoutParams = ActionMenuView.LayoutParams(width, height)
[email protected] = layoutParams
return this
}
}
open class _FrameLayout(ctx: Context): FrameLayout(ctx) {
inline fun <T: View> T.lparams(
c: Context?,
attrs: AttributeSet?,
init: FrameLayout.LayoutParams.() -> Unit
): T {
val layoutParams = FrameLayout.LayoutParams(c!!, attrs!!)
layoutParams.init()
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
c: Context?,
attrs: AttributeSet?
): T {
val layoutParams = FrameLayout.LayoutParams(c!!, attrs!!)
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
init: FrameLayout.LayoutParams.() -> Unit
): T {
val layoutParams = FrameLayout.LayoutParams(width, height)
layoutParams.init()
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT
): T {
val layoutParams = FrameLayout.LayoutParams(width, height)
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
gravity: Int,
init: FrameLayout.LayoutParams.() -> Unit
): T {
val layoutParams = FrameLayout.LayoutParams(width, height, gravity)
layoutParams.init()
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
gravity: Int
): T {
val layoutParams = FrameLayout.LayoutParams(width, height, gravity)
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
source: ViewGroup.LayoutParams?,
init: FrameLayout.LayoutParams.() -> Unit
): T {
val layoutParams = FrameLayout.LayoutParams(source!!)
layoutParams.init()
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
source: ViewGroup.LayoutParams?
): T {
val layoutParams = FrameLayout.LayoutParams(source!!)
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
source: ViewGroup.MarginLayoutParams?,
init: FrameLayout.LayoutParams.() -> Unit
): T {
val layoutParams = FrameLayout.LayoutParams(source!!)
layoutParams.init()
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
source: ViewGroup.MarginLayoutParams?
): T {
val layoutParams = FrameLayout.LayoutParams(source!!)
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
source: FrameLayout.LayoutParams?,
init: FrameLayout.LayoutParams.() -> Unit
): T {
val layoutParams = FrameLayout.LayoutParams(source!!)
layoutParams.init()
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
source: FrameLayout.LayoutParams?
): T {
val layoutParams = FrameLayout.LayoutParams(source!!)
[email protected] = layoutParams
return this
}
}
open class _Gallery(ctx: Context): Gallery(ctx) {
inline fun <T: View> T.lparams(
c: Context?,
attrs: AttributeSet?,
init: Gallery.LayoutParams.() -> Unit
): T {
val layoutParams = Gallery.LayoutParams(c!!, attrs!!)
layoutParams.init()
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
c: Context?,
attrs: AttributeSet?
): T {
val layoutParams = Gallery.LayoutParams(c!!, attrs!!)
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
init: Gallery.LayoutParams.() -> Unit
): T {
val layoutParams = Gallery.LayoutParams(width, height)
layoutParams.init()
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT
): T {
val layoutParams = Gallery.LayoutParams(width, height)
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
source: ViewGroup.LayoutParams?,
init: Gallery.LayoutParams.() -> Unit
): T {
val layoutParams = Gallery.LayoutParams(source!!)
layoutParams.init()
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
source: ViewGroup.LayoutParams?
): T {
val layoutParams = Gallery.LayoutParams(source!!)
[email protected] = layoutParams
return this
}
}
open class _GridLayout(ctx: Context): GridLayout(ctx) {
inline fun <T: View> T.lparams(
rowSpec: GridLayout.Spec?,
columnSpec: GridLayout.Spec?,
init: GridLayout.LayoutParams.() -> Unit
): T {
val layoutParams = GridLayout.LayoutParams(rowSpec!!, columnSpec!!)
layoutParams.init()
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
rowSpec: GridLayout.Spec?,
columnSpec: GridLayout.Spec?
): T {
val layoutParams = GridLayout.LayoutParams(rowSpec!!, columnSpec!!)
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
init: GridLayout.LayoutParams.() -> Unit
): T {
val layoutParams = GridLayout.LayoutParams()
layoutParams.init()
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
): T {
val layoutParams = GridLayout.LayoutParams()
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
params: ViewGroup.LayoutParams?,
init: GridLayout.LayoutParams.() -> Unit
): T {
val layoutParams = GridLayout.LayoutParams(params!!)
layoutParams.init()
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
params: ViewGroup.LayoutParams?
): T {
val layoutParams = GridLayout.LayoutParams(params!!)
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
params: ViewGroup.MarginLayoutParams?,
init: GridLayout.LayoutParams.() -> Unit
): T {
val layoutParams = GridLayout.LayoutParams(params!!)
layoutParams.init()
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
params: ViewGroup.MarginLayoutParams?
): T {
val layoutParams = GridLayout.LayoutParams(params!!)
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
source: GridLayout.LayoutParams?,
init: GridLayout.LayoutParams.() -> Unit
): T {
val layoutParams = GridLayout.LayoutParams(source!!)
layoutParams.init()
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
source: GridLayout.LayoutParams?
): T {
val layoutParams = GridLayout.LayoutParams(source!!)
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
context: Context?,
attrs: AttributeSet?,
init: GridLayout.LayoutParams.() -> Unit
): T {
val layoutParams = GridLayout.LayoutParams(context!!, attrs!!)
layoutParams.init()
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
context: Context?,
attrs: AttributeSet?
): T {
val layoutParams = GridLayout.LayoutParams(context!!, attrs!!)
[email protected] = layoutParams
return this
}
}
open class _GridView(ctx: Context): GridView(ctx) {
inline fun <T: View> T.lparams(
c: Context?,
attrs: AttributeSet?,
init: AbsListView.LayoutParams.() -> Unit
): T {
val layoutParams = AbsListView.LayoutParams(c!!, attrs!!)
layoutParams.init()
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
c: Context?,
attrs: AttributeSet?
): T {
val layoutParams = AbsListView.LayoutParams(c!!, attrs!!)
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
init: AbsListView.LayoutParams.() -> Unit
): T {
val layoutParams = AbsListView.LayoutParams(width, height)
layoutParams.init()
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT
): T {
val layoutParams = AbsListView.LayoutParams(width, height)
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
viewType: Int,
init: AbsListView.LayoutParams.() -> Unit
): T {
val layoutParams = AbsListView.LayoutParams(width, height, viewType)
layoutParams.init()
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
viewType: Int
): T {
val layoutParams = AbsListView.LayoutParams(width, height, viewType)
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
source: ViewGroup.LayoutParams?,
init: AbsListView.LayoutParams.() -> Unit
): T {
val layoutParams = AbsListView.LayoutParams(source!!)
layoutParams.init()
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
source: ViewGroup.LayoutParams?
): T {
val layoutParams = AbsListView.LayoutParams(source!!)
[email protected] = layoutParams
return this
}
}
open class _HorizontalScrollView(ctx: Context): HorizontalScrollView(ctx) {
inline fun <T: View> T.lparams(
c: Context?,
attrs: AttributeSet?,
init: FrameLayout.LayoutParams.() -> Unit
): T {
val layoutParams = FrameLayout.LayoutParams(c!!, attrs!!)
layoutParams.init()
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
c: Context?,
attrs: AttributeSet?
): T {
val layoutParams = FrameLayout.LayoutParams(c!!, attrs!!)
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
init: FrameLayout.LayoutParams.() -> Unit
): T {
val layoutParams = FrameLayout.LayoutParams(width, height)
layoutParams.init()
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT
): T {
val layoutParams = FrameLayout.LayoutParams(width, height)
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
gravity: Int,
init: FrameLayout.LayoutParams.() -> Unit
): T {
val layoutParams = FrameLayout.LayoutParams(width, height, gravity)
layoutParams.init()
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
gravity: Int
): T {
val layoutParams = FrameLayout.LayoutParams(width, height, gravity)
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
source: ViewGroup.LayoutParams?,
init: FrameLayout.LayoutParams.() -> Unit
): T {
val layoutParams = FrameLayout.LayoutParams(source!!)
layoutParams.init()
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
source: ViewGroup.LayoutParams?
): T {
val layoutParams = FrameLayout.LayoutParams(source!!)
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
source: ViewGroup.MarginLayoutParams?,
init: FrameLayout.LayoutParams.() -> Unit
): T {
val layoutParams = FrameLayout.LayoutParams(source!!)
layoutParams.init()
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
source: ViewGroup.MarginLayoutParams?
): T {
val layoutParams = FrameLayout.LayoutParams(source!!)
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
source: FrameLayout.LayoutParams?,
init: FrameLayout.LayoutParams.() -> Unit
): T {
val layoutParams = FrameLayout.LayoutParams(source!!)
layoutParams.init()
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
source: FrameLayout.LayoutParams?
): T {
val layoutParams = FrameLayout.LayoutParams(source!!)
[email protected] = layoutParams
return this
}
}
open class _ImageSwitcher(ctx: Context): ImageSwitcher(ctx) {
inline fun <T: View> T.lparams(
c: Context?,
attrs: AttributeSet?,
init: FrameLayout.LayoutParams.() -> Unit
): T {
val layoutParams = FrameLayout.LayoutParams(c!!, attrs!!)
layoutParams.init()
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
c: Context?,
attrs: AttributeSet?
): T {
val layoutParams = FrameLayout.LayoutParams(c!!, attrs!!)
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
init: FrameLayout.LayoutParams.() -> Unit
): T {
val layoutParams = FrameLayout.LayoutParams(width, height)
layoutParams.init()
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT
): T {
val layoutParams = FrameLayout.LayoutParams(width, height)
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
gravity: Int,
init: FrameLayout.LayoutParams.() -> Unit
): T {
val layoutParams = FrameLayout.LayoutParams(width, height, gravity)
layoutParams.init()
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
gravity: Int
): T {
val layoutParams = FrameLayout.LayoutParams(width, height, gravity)
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
source: ViewGroup.LayoutParams?,
init: FrameLayout.LayoutParams.() -> Unit
): T {
val layoutParams = FrameLayout.LayoutParams(source!!)
layoutParams.init()
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
source: ViewGroup.LayoutParams?
): T {
val layoutParams = FrameLayout.LayoutParams(source!!)
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
source: ViewGroup.MarginLayoutParams?,
init: FrameLayout.LayoutParams.() -> Unit
): T {
val layoutParams = FrameLayout.LayoutParams(source!!)
layoutParams.init()
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
source: ViewGroup.MarginLayoutParams?
): T {
val layoutParams = FrameLayout.LayoutParams(source!!)
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
source: FrameLayout.LayoutParams?,
init: FrameLayout.LayoutParams.() -> Unit
): T {
val layoutParams = FrameLayout.LayoutParams(source!!)
layoutParams.init()
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
source: FrameLayout.LayoutParams?
): T {
val layoutParams = FrameLayout.LayoutParams(source!!)
[email protected] = layoutParams
return this
}
}
open class _LinearLayout(ctx: Context): LinearLayout(ctx) {
inline fun <T: View> T.lparams(
c: Context?,
attrs: AttributeSet?,
init: LinearLayout.LayoutParams.() -> Unit
): T {
val layoutParams = LinearLayout.LayoutParams(c!!, attrs!!)
layoutParams.init()
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
c: Context?,
attrs: AttributeSet?
): T {
val layoutParams = LinearLayout.LayoutParams(c!!, attrs!!)
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
init: LinearLayout.LayoutParams.() -> Unit
): T {
val layoutParams = LinearLayout.LayoutParams(width, height)
layoutParams.init()
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT
): T {
val layoutParams = LinearLayout.LayoutParams(width, height)
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
weight: Float,
init: LinearLayout.LayoutParams.() -> Unit
): T {
val layoutParams = LinearLayout.LayoutParams(width, height, weight)
layoutParams.init()
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
weight: Float
): T {
val layoutParams = LinearLayout.LayoutParams(width, height, weight)
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
p: ViewGroup.LayoutParams?,
init: LinearLayout.LayoutParams.() -> Unit
): T {
val layoutParams = LinearLayout.LayoutParams(p!!)
layoutParams.init()
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
p: ViewGroup.LayoutParams?
): T {
val layoutParams = LinearLayout.LayoutParams(p!!)
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
source: ViewGroup.MarginLayoutParams?,
init: LinearLayout.LayoutParams.() -> Unit
): T {
val layoutParams = LinearLayout.LayoutParams(source!!)
layoutParams.init()
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
source: ViewGroup.MarginLayoutParams?
): T {
val layoutParams = LinearLayout.LayoutParams(source!!)
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
source: LinearLayout.LayoutParams?,
init: LinearLayout.LayoutParams.() -> Unit
): T {
val layoutParams = LinearLayout.LayoutParams(source!!)
layoutParams.init()
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
source: LinearLayout.LayoutParams?
): T {
val layoutParams = LinearLayout.LayoutParams(source!!)
[email protected] = layoutParams
return this
}
}
open class _RadioGroup(ctx: Context): RadioGroup(ctx) {
inline fun <T: View> T.lparams(
c: Context?,
attrs: AttributeSet?,
init: RadioGroup.LayoutParams.() -> Unit
): T {
val layoutParams = RadioGroup.LayoutParams(c!!, attrs!!)
layoutParams.init()
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
c: Context?,
attrs: AttributeSet?
): T {
val layoutParams = RadioGroup.LayoutParams(c!!, attrs!!)
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
init: RadioGroup.LayoutParams.() -> Unit
): T {
val layoutParams = RadioGroup.LayoutParams(width, height)
layoutParams.init()
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT
): T {
val layoutParams = RadioGroup.LayoutParams(width, height)
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
initWeight: Float,
init: RadioGroup.LayoutParams.() -> Unit
): T {
val layoutParams = RadioGroup.LayoutParams(width, height, initWeight)
layoutParams.init()
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
initWeight: Float
): T {
val layoutParams = RadioGroup.LayoutParams(width, height, initWeight)
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
p: ViewGroup.LayoutParams?,
init: RadioGroup.LayoutParams.() -> Unit
): T {
val layoutParams = RadioGroup.LayoutParams(p!!)
layoutParams.init()
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
p: ViewGroup.LayoutParams?
): T {
val layoutParams = RadioGroup.LayoutParams(p!!)
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
source: ViewGroup.MarginLayoutParams?,
init: RadioGroup.LayoutParams.() -> Unit
): T {
val layoutParams = RadioGroup.LayoutParams(source!!)
layoutParams.init()
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
source: ViewGroup.MarginLayoutParams?
): T {
val layoutParams = RadioGroup.LayoutParams(source!!)
[email protected] = layoutParams
return this
}
}
open class _RelativeLayout(ctx: Context): RelativeLayout(ctx) {
inline fun <T: View> T.lparams(
c: Context?,
attrs: AttributeSet?,
init: RelativeLayout.LayoutParams.() -> Unit
): T {
val layoutParams = RelativeLayout.LayoutParams(c!!, attrs!!)
layoutParams.init()
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
c: Context?,
attrs: AttributeSet?
): T {
val layoutParams = RelativeLayout.LayoutParams(c!!, attrs!!)
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
init: RelativeLayout.LayoutParams.() -> Unit
): T {
val layoutParams = RelativeLayout.LayoutParams(width, height)
layoutParams.init()
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT
): T {
val layoutParams = RelativeLayout.LayoutParams(width, height)
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
source: ViewGroup.LayoutParams?,
init: RelativeLayout.LayoutParams.() -> Unit
): T {
val layoutParams = RelativeLayout.LayoutParams(source!!)
layoutParams.init()
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
source: ViewGroup.LayoutParams?
): T {
val layoutParams = RelativeLayout.LayoutParams(source!!)
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
source: ViewGroup.MarginLayoutParams?,
init: RelativeLayout.LayoutParams.() -> Unit
): T {
val layoutParams = RelativeLayout.LayoutParams(source!!)
layoutParams.init()
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
source: ViewGroup.MarginLayoutParams?
): T {
val layoutParams = RelativeLayout.LayoutParams(source!!)
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
source: RelativeLayout.LayoutParams?,
init: RelativeLayout.LayoutParams.() -> Unit
): T {
val layoutParams = RelativeLayout.LayoutParams(source!!)
layoutParams.init()
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
source: RelativeLayout.LayoutParams?
): T {
val layoutParams = RelativeLayout.LayoutParams(source!!)
[email protected] = layoutParams
return this
}
}
open class _ScrollView(ctx: Context): ScrollView(ctx) {
inline fun <T: View> T.lparams(
c: Context?,
attrs: AttributeSet?,
init: FrameLayout.LayoutParams.() -> Unit
): T {
val layoutParams = FrameLayout.LayoutParams(c!!, attrs!!)
layoutParams.init()
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
c: Context?,
attrs: AttributeSet?
): T {
val layoutParams = FrameLayout.LayoutParams(c!!, attrs!!)
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
init: FrameLayout.LayoutParams.() -> Unit
): T {
val layoutParams = FrameLayout.LayoutParams(width, height)
layoutParams.init()
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT
): T {
val layoutParams = FrameLayout.LayoutParams(width, height)
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
gravity: Int,
init: FrameLayout.LayoutParams.() -> Unit
): T {
val layoutParams = FrameLayout.LayoutParams(width, height, gravity)
layoutParams.init()
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
gravity: Int
): T {
val layoutParams = FrameLayout.LayoutParams(width, height, gravity)
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
source: ViewGroup.LayoutParams?,
init: FrameLayout.LayoutParams.() -> Unit
): T {
val layoutParams = FrameLayout.LayoutParams(source!!)
layoutParams.init()
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
source: ViewGroup.LayoutParams?
): T {
val layoutParams = FrameLayout.LayoutParams(source!!)
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
source: ViewGroup.MarginLayoutParams?,
init: FrameLayout.LayoutParams.() -> Unit
): T {
val layoutParams = FrameLayout.LayoutParams(source!!)
layoutParams.init()
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
source: ViewGroup.MarginLayoutParams?
): T {
val layoutParams = FrameLayout.LayoutParams(source!!)
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
source: FrameLayout.LayoutParams?,
init: FrameLayout.LayoutParams.() -> Unit
): T {
val layoutParams = FrameLayout.LayoutParams(source!!)
layoutParams.init()
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
source: FrameLayout.LayoutParams?
): T {
val layoutParams = FrameLayout.LayoutParams(source!!)
[email protected] = layoutParams
return this
}
}
open class _TableLayout(ctx: Context): TableLayout(ctx) {
inline fun <T: View> T.lparams(
c: Context?,
attrs: AttributeSet?,
init: TableLayout.LayoutParams.() -> Unit
): T {
val layoutParams = TableLayout.LayoutParams(c!!, attrs!!)
layoutParams.init()
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
c: Context?,
attrs: AttributeSet?
): T {
val layoutParams = TableLayout.LayoutParams(c!!, attrs!!)
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
init: TableLayout.LayoutParams.() -> Unit
): T {
val layoutParams = TableLayout.LayoutParams(width, height)
layoutParams.init()
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT
): T {
val layoutParams = TableLayout.LayoutParams(width, height)
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
initWeight: Float,
init: TableLayout.LayoutParams.() -> Unit
): T {
val layoutParams = TableLayout.LayoutParams(width, height, initWeight)
layoutParams.init()
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
initWeight: Float
): T {
val layoutParams = TableLayout.LayoutParams(width, height, initWeight)
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
init: TableLayout.LayoutParams.() -> Unit
): T {
val layoutParams = TableLayout.LayoutParams()
layoutParams.init()
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
): T {
val layoutParams = TableLayout.LayoutParams()
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
p: ViewGroup.LayoutParams?,
init: TableLayout.LayoutParams.() -> Unit
): T {
val layoutParams = TableLayout.LayoutParams(p!!)
layoutParams.init()
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
p: ViewGroup.LayoutParams?
): T {
val layoutParams = TableLayout.LayoutParams(p!!)
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
source: ViewGroup.MarginLayoutParams?,
init: TableLayout.LayoutParams.() -> Unit
): T {
val layoutParams = TableLayout.LayoutParams(source!!)
layoutParams.init()
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
source: ViewGroup.MarginLayoutParams?
): T {
val layoutParams = TableLayout.LayoutParams(source!!)
[email protected] = layoutParams
return this
}
}
open class _TableRow(ctx: Context): TableRow(ctx) {
inline fun <T: View> T.lparams(
c: Context?,
attrs: AttributeSet?,
init: TableRow.LayoutParams.() -> Unit
): T {
val layoutParams = TableRow.LayoutParams(c!!, attrs!!)
layoutParams.init()
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
c: Context?,
attrs: AttributeSet?
): T {
val layoutParams = TableRow.LayoutParams(c!!, attrs!!)
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
init: TableRow.LayoutParams.() -> Unit
): T {
val layoutParams = TableRow.LayoutParams(width, height)
layoutParams.init()
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT
): T {
val layoutParams = TableRow.LayoutParams(width, height)
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
initWeight: Float,
init: TableRow.LayoutParams.() -> Unit
): T {
val layoutParams = TableRow.LayoutParams(width, height, initWeight)
layoutParams.init()
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
initWeight: Float
): T {
val layoutParams = TableRow.LayoutParams(width, height, initWeight)
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
init: TableRow.LayoutParams.() -> Unit
): T {
val layoutParams = TableRow.LayoutParams()
layoutParams.init()
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
): T {
val layoutParams = TableRow.LayoutParams()
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
column: Int,
init: TableRow.LayoutParams.() -> Unit
): T {
val layoutParams = TableRow.LayoutParams(column)
layoutParams.init()
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
column: Int
): T {
val layoutParams = TableRow.LayoutParams(column)
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
p: ViewGroup.LayoutParams?,
init: TableRow.LayoutParams.() -> Unit
): T {
val layoutParams = TableRow.LayoutParams(p!!)
layoutParams.init()
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
p: ViewGroup.LayoutParams?
): T {
val layoutParams = TableRow.LayoutParams(p!!)
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
source: ViewGroup.MarginLayoutParams?,
init: TableRow.LayoutParams.() -> Unit
): T {
val layoutParams = TableRow.LayoutParams(source!!)
layoutParams.init()
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
source: ViewGroup.MarginLayoutParams?
): T {
val layoutParams = TableRow.LayoutParams(source!!)
[email protected] = layoutParams
return this
}
}
open class _TextSwitcher(ctx: Context): TextSwitcher(ctx) {
inline fun <T: View> T.lparams(
c: Context?,
attrs: AttributeSet?,
init: FrameLayout.LayoutParams.() -> Unit
): T {
val layoutParams = FrameLayout.LayoutParams(c!!, attrs!!)
layoutParams.init()
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
c: Context?,
attrs: AttributeSet?
): T {
val layoutParams = FrameLayout.LayoutParams(c!!, attrs!!)
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
init: FrameLayout.LayoutParams.() -> Unit
): T {
val layoutParams = FrameLayout.LayoutParams(width, height)
layoutParams.init()
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT
): T {
val layoutParams = FrameLayout.LayoutParams(width, height)
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
gravity: Int,
init: FrameLayout.LayoutParams.() -> Unit
): T {
val layoutParams = FrameLayout.LayoutParams(width, height, gravity)
layoutParams.init()
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
gravity: Int
): T {
val layoutParams = FrameLayout.LayoutParams(width, height, gravity)
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
source: ViewGroup.LayoutParams?,
init: FrameLayout.LayoutParams.() -> Unit
): T {
val layoutParams = FrameLayout.LayoutParams(source!!)
layoutParams.init()
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
source: ViewGroup.LayoutParams?
): T {
val layoutParams = FrameLayout.LayoutParams(source!!)
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
source: ViewGroup.MarginLayoutParams?,
init: FrameLayout.LayoutParams.() -> Unit
): T {
val layoutParams = FrameLayout.LayoutParams(source!!)
layoutParams.init()
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
source: ViewGroup.MarginLayoutParams?
): T {
val layoutParams = FrameLayout.LayoutParams(source!!)
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
source: FrameLayout.LayoutParams?,
init: FrameLayout.LayoutParams.() -> Unit
): T {
val layoutParams = FrameLayout.LayoutParams(source!!)
layoutParams.init()
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
source: FrameLayout.LayoutParams?
): T {
val layoutParams = FrameLayout.LayoutParams(source!!)
[email protected] = layoutParams
return this
}
}
open class _Toolbar(ctx: Context): Toolbar(ctx) {
inline fun <T: View> T.lparams(
c: Context?,
attrs: AttributeSet?,
init: Toolbar.LayoutParams.() -> Unit
): T {
val layoutParams = Toolbar.LayoutParams(c!!, attrs!!)
layoutParams.init()
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
c: Context?,
attrs: AttributeSet?
): T {
val layoutParams = Toolbar.LayoutParams(c!!, attrs!!)
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
init: Toolbar.LayoutParams.() -> Unit
): T {
val layoutParams = Toolbar.LayoutParams(width, height)
layoutParams.init()
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT
): T {
val layoutParams = Toolbar.LayoutParams(width, height)
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
gravity: Int,
init: Toolbar.LayoutParams.() -> Unit
): T {
val layoutParams = Toolbar.LayoutParams(width, height, gravity)
layoutParams.init()
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
gravity: Int
): T {
val layoutParams = Toolbar.LayoutParams(width, height, gravity)
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
gravity: Int,
init: Toolbar.LayoutParams.() -> Unit
): T {
val layoutParams = Toolbar.LayoutParams(gravity)
layoutParams.init()
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
gravity: Int
): T {
val layoutParams = Toolbar.LayoutParams(gravity)
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
source: Toolbar.LayoutParams?,
init: Toolbar.LayoutParams.() -> Unit
): T {
val layoutParams = Toolbar.LayoutParams(source!!)
layoutParams.init()
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
source: Toolbar.LayoutParams?
): T {
val layoutParams = Toolbar.LayoutParams(source!!)
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
source: ActionBar.LayoutParams?,
init: Toolbar.LayoutParams.() -> Unit
): T {
val layoutParams = Toolbar.LayoutParams(source!!)
layoutParams.init()
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
source: ActionBar.LayoutParams?
): T {
val layoutParams = Toolbar.LayoutParams(source!!)
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
source: ViewGroup.MarginLayoutParams?,
init: Toolbar.LayoutParams.() -> Unit
): T {
val layoutParams = Toolbar.LayoutParams(source!!)
layoutParams.init()
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
source: ViewGroup.MarginLayoutParams?
): T {
val layoutParams = Toolbar.LayoutParams(source!!)
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
source: ViewGroup.LayoutParams?,
init: Toolbar.LayoutParams.() -> Unit
): T {
val layoutParams = Toolbar.LayoutParams(source!!)
layoutParams.init()
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
source: ViewGroup.LayoutParams?
): T {
val layoutParams = Toolbar.LayoutParams(source!!)
[email protected] = layoutParams
return this
}
}
open class _ViewAnimator(ctx: Context): ViewAnimator(ctx) {
inline fun <T: View> T.lparams(
c: Context?,
attrs: AttributeSet?,
init: FrameLayout.LayoutParams.() -> Unit
): T {
val layoutParams = FrameLayout.LayoutParams(c!!, attrs!!)
layoutParams.init()
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
c: Context?,
attrs: AttributeSet?
): T {
val layoutParams = FrameLayout.LayoutParams(c!!, attrs!!)
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
init: FrameLayout.LayoutParams.() -> Unit
): T {
val layoutParams = FrameLayout.LayoutParams(width, height)
layoutParams.init()
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT
): T {
val layoutParams = FrameLayout.LayoutParams(width, height)
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
gravity: Int,
init: FrameLayout.LayoutParams.() -> Unit
): T {
val layoutParams = FrameLayout.LayoutParams(width, height, gravity)
layoutParams.init()
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
gravity: Int
): T {
val layoutParams = FrameLayout.LayoutParams(width, height, gravity)
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
source: ViewGroup.LayoutParams?,
init: FrameLayout.LayoutParams.() -> Unit
): T {
val layoutParams = FrameLayout.LayoutParams(source!!)
layoutParams.init()
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
source: ViewGroup.LayoutParams?
): T {
val layoutParams = FrameLayout.LayoutParams(source!!)
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
source: ViewGroup.MarginLayoutParams?,
init: FrameLayout.LayoutParams.() -> Unit
): T {
val layoutParams = FrameLayout.LayoutParams(source!!)
layoutParams.init()
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
source: ViewGroup.MarginLayoutParams?
): T {
val layoutParams = FrameLayout.LayoutParams(source!!)
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
source: FrameLayout.LayoutParams?,
init: FrameLayout.LayoutParams.() -> Unit
): T {
val layoutParams = FrameLayout.LayoutParams(source!!)
layoutParams.init()
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
source: FrameLayout.LayoutParams?
): T {
val layoutParams = FrameLayout.LayoutParams(source!!)
[email protected] = layoutParams
return this
}
}
open class _ViewSwitcher(ctx: Context): ViewSwitcher(ctx) {
inline fun <T: View> T.lparams(
c: Context?,
attrs: AttributeSet?,
init: FrameLayout.LayoutParams.() -> Unit
): T {
val layoutParams = FrameLayout.LayoutParams(c!!, attrs!!)
layoutParams.init()
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
c: Context?,
attrs: AttributeSet?
): T {
val layoutParams = FrameLayout.LayoutParams(c!!, attrs!!)
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
init: FrameLayout.LayoutParams.() -> Unit
): T {
val layoutParams = FrameLayout.LayoutParams(width, height)
layoutParams.init()
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT
): T {
val layoutParams = FrameLayout.LayoutParams(width, height)
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
gravity: Int,
init: FrameLayout.LayoutParams.() -> Unit
): T {
val layoutParams = FrameLayout.LayoutParams(width, height, gravity)
layoutParams.init()
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
width: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
height: Int = android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
gravity: Int
): T {
val layoutParams = FrameLayout.LayoutParams(width, height, gravity)
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
source: ViewGroup.LayoutParams?,
init: FrameLayout.LayoutParams.() -> Unit
): T {
val layoutParams = FrameLayout.LayoutParams(source!!)
layoutParams.init()
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
source: ViewGroup.LayoutParams?
): T {
val layoutParams = FrameLayout.LayoutParams(source!!)
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
source: ViewGroup.MarginLayoutParams?,
init: FrameLayout.LayoutParams.() -> Unit
): T {
val layoutParams = FrameLayout.LayoutParams(source!!)
layoutParams.init()
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
source: ViewGroup.MarginLayoutParams?
): T {
val layoutParams = FrameLayout.LayoutParams(source!!)
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
source: FrameLayout.LayoutParams?,
init: FrameLayout.LayoutParams.() -> Unit
): T {
val layoutParams = FrameLayout.LayoutParams(source!!)
layoutParams.init()
[email protected] = layoutParams
return this
}
inline fun <T: View> T.lparams(
source: FrameLayout.LayoutParams?
): T {
val layoutParams = FrameLayout.LayoutParams(source!!)
[email protected] = layoutParams
return this
}
}
| apache-2.0 | 9516e4c8f6b30e757e71e44bdd8cbfde | 30.745438 | 78 | 0.610381 | 4.868878 | false | false | false | false |
yzbzz/beautifullife | icore/src/main/java/com/ddu/icore/common/ext/ICoreInternals.kt | 2 | 4658 | package com.ddu.icore.common.ext
import android.app.Activity
import android.app.Service
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.os.Parcelable
import java.io.Serializable
object ICoreInternals {
@JvmStatic
fun <T> createIntent(ctx: Context, clazz: Class<out T>, vararg args: Pair<String, Any?>): Intent {
val intent = Intent(ctx, clazz)
if (args.isNotEmpty()) {
fillIntentArguments(intent, *args)
}
return intent
}
@JvmStatic
fun internalStartActivity(
ctx: Context,
activity: Class<out Activity>,
vararg args: Pair<String, Any?>
) {
ctx.startActivity(createIntent(ctx, activity, *args))
}
@JvmStatic
fun internalStartActivityForResult(
act: Activity,
activity: Class<out Activity>,
requestCode: Int,
vararg args: Pair<String, Any?>
) {
act.startActivityForResult(createIntent(act, activity, *args), requestCode)
}
@JvmStatic
fun internalStartService(
ctx: Context,
service: Class<out Service>,
vararg args: Pair<String, Any?>
): ComponentName? = ctx.startService(createIntent(ctx, service, *args))
@JvmStatic
fun internalStopService(
ctx: Context,
service: Class<out Service>,
vararg args: Pair<String, Any?>
): Boolean = ctx.stopService(createIntent(ctx, service, *args))
@JvmStatic
fun fillIntentArguments(intent: Intent, vararg pairs: Pair<String, Any?>) {
intent.apply {
for ((key, value) in pairs) {
when (value) {
null -> putExtra(key, null as Serializable?) // Any nullable type will suffice.
// Scalars
is Boolean -> putExtra(key, value)
is Byte -> putExtra(key, value)
is Char -> putExtra(key, value)
is Double -> putExtra(key, value)
is Float -> putExtra(key, value)
is Int -> putExtra(key, value)
is Long -> putExtra(key, value)
is Short -> putExtra(key, value)
// References
is String -> putExtra(key, value)
is Bundle -> putExtra(key, value)
is CharSequence -> putExtra(key, value)
is Parcelable -> putExtra(key, value)
// Last resort. Also we must check this after Array<*> as all arrays are serializable.
is Serializable -> putExtra(key, value)
// Scalar arrays
is BooleanArray -> putExtra(key, value)
is ByteArray -> putExtra(key, value)
is CharArray -> putExtra(key, value)
is DoubleArray -> putExtra(key, value)
is FloatArray -> putExtra(key, value)
is IntArray -> putExtra(key, value)
is LongArray -> putExtra(key, value)
is ShortArray -> putExtra(key, value)
// Reference arrays
is Array<*> -> {
val componentType = value::class.java.componentType!!
@Suppress("UNCHECKED_CAST") // Checked by reflection.
when {
Parcelable::class.java.isAssignableFrom(componentType) -> {
putExtra(key, value as Array<Parcelable>)
}
String::class.java.isAssignableFrom(componentType) -> {
putExtra(key, value as Array<String>)
}
CharSequence::class.java.isAssignableFrom(componentType) -> {
putExtra(key, value as Array<CharSequence>)
}
Int::class.java.isAssignableFrom(componentType) -> {
putExtra(key, value as Array<Int>)
}
else -> {
val valueType = componentType.canonicalName
throw IllegalArgumentException(
"Illegal value array type $valueType for key \"$key\"")
}
}
}
}
}
}
}
}
| apache-2.0 | 084dc1cfb688a4c4df4fbebaa75baccc | 36.564516 | 106 | 0.496994 | 5.565114 | false | false | false | false |
HabitRPG/habitrpg-android | Habitica/src/main/java/com/habitrpg/android/habitica/ui/fragments/inventory/items/ItemDialogFragment.kt | 1 | 13335 | package com.habitrpg.android.habitica.ui.fragments.inventory.items
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.Window
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout
import com.habitrpg.android.habitica.R
import com.habitrpg.android.habitica.components.UserComponent
import com.habitrpg.android.habitica.data.InventoryRepository
import com.habitrpg.android.habitica.data.SocialRepository
import com.habitrpg.android.habitica.data.UserRepository
import com.habitrpg.android.habitica.databinding.FragmentItemsBinding
import com.habitrpg.android.habitica.extensions.addCloseButton
import com.habitrpg.android.habitica.extensions.subscribeWithErrorHandler
import com.habitrpg.android.habitica.helpers.MainNavigationController
import com.habitrpg.android.habitica.helpers.RxErrorHandler
import com.habitrpg.android.habitica.interactors.FeedPetUseCase
import com.habitrpg.android.habitica.interactors.HatchPetUseCase
import com.habitrpg.android.habitica.models.inventory.Egg
import com.habitrpg.android.habitica.models.inventory.Food
import com.habitrpg.android.habitica.models.inventory.HatchingPotion
import com.habitrpg.android.habitica.models.inventory.Item
import com.habitrpg.android.habitica.models.inventory.Pet
import com.habitrpg.android.habitica.models.inventory.QuestContent
import com.habitrpg.android.habitica.models.inventory.SpecialItem
import com.habitrpg.android.habitica.models.user.OwnedPet
import com.habitrpg.android.habitica.models.user.User
import com.habitrpg.android.habitica.ui.activities.BaseActivity
import com.habitrpg.android.habitica.ui.activities.MainActivity
import com.habitrpg.android.habitica.ui.adapter.inventory.ItemRecyclerAdapter
import com.habitrpg.android.habitica.ui.fragments.BaseDialogFragment
import com.habitrpg.android.habitica.ui.helpers.EmptyItem
import com.habitrpg.android.habitica.ui.helpers.SafeDefaultItemAnimator
import com.habitrpg.android.habitica.ui.helpers.loadImage
import com.habitrpg.android.habitica.ui.views.dialogs.OpenedMysteryitemDialog
import javax.inject.Inject
class ItemDialogFragment : BaseDialogFragment<FragmentItemsBinding>(), SwipeRefreshLayout.OnRefreshListener {
@Inject
lateinit var inventoryRepository: InventoryRepository
@Inject
lateinit var socialRepository: SocialRepository
@Inject
lateinit var userRepository: UserRepository
@Inject
lateinit var hatchPetUseCase: HatchPetUseCase
@Inject
lateinit var feedPetUseCase: FeedPetUseCase
var adapter: ItemRecyclerAdapter? = null
var itemType: String? = null
var itemTypeText: String? = null
var isHatching: Boolean = false
var isFeeding: Boolean = false
internal var hatchingItem: Item? = null
var feedingPet: Pet? = null
var user: User? = null
internal var layoutManager: androidx.recyclerview.widget.LinearLayoutManager? = null
override var binding: FragmentItemsBinding? = null
override fun createBinding(inflater: LayoutInflater, container: ViewGroup?): FragmentItemsBinding {
return FragmentItemsBinding.inflate(inflater, container, false)
}
override fun onDestroy() {
inventoryRepository.close()
super.onDestroy()
}
override fun injectFragment(component: UserComponent) {
component.inject(this)
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
when {
this.isHatching -> {
dialog?.requestWindowFeature(Window.FEATURE_NO_TITLE)
}
this.isFeeding -> {
dialog?.requestWindowFeature(Window.FEATURE_NO_TITLE)
}
else -> {
}
}
return super.onCreateView(inflater, container, savedInstanceState)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
binding?.refreshLayout?.setOnRefreshListener(this)
binding?.recyclerView?.emptyItem = EmptyItem(
getString(R.string.empty_items, itemTypeText ?: itemType),
getString(R.string.open_market)
) {
openMarket()
}
val context = activity
layoutManager = androidx.recyclerview.widget.LinearLayoutManager(context)
binding?.recyclerView?.layoutManager = layoutManager
adapter = binding?.recyclerView?.adapter as? ItemRecyclerAdapter
if (adapter == null) {
context?.let {
adapter = ItemRecyclerAdapter(context)
adapter?.isHatching = this.isHatching
adapter?.isFeeding = this.isFeeding
adapter?.fragment = this
}
if (this.hatchingItem != null) {
adapter?.hatchingItem = this.hatchingItem
}
if (this.feedingPet != null) {
adapter?.feedingPet = this.feedingPet
}
binding?.recyclerView?.adapter = adapter
adapter?.let { adapter ->
compositeSubscription.add(
adapter.getSellItemFlowable()
.flatMap { item -> inventoryRepository.sellItem(item) }
.subscribe({ }, RxErrorHandler.handleEmptyError())
)
compositeSubscription.add(
adapter.getQuestInvitationFlowable()
.flatMap { quest -> inventoryRepository.inviteToQuest(quest) }
.flatMap { socialRepository.retrieveGroup("party") }
.subscribe(
{
if (isModal) {
dismiss()
} else {
MainNavigationController.navigate(R.id.partyFragment)
}
},
RxErrorHandler.handleEmptyError()
)
)
compositeSubscription.add(
adapter.getOpenMysteryItemFlowable()
.flatMap { inventoryRepository.openMysteryItem(user) }
.doOnNext {
val activity = activity as? MainActivity
if (activity != null) {
val dialog = OpenedMysteryitemDialog(activity)
dialog.isCelebratory = true
dialog.setTitle(R.string.mystery_item_title)
dialog.binding.iconView.loadImage("shop_${it.key}")
dialog.binding.titleView.text = it.text
dialog.binding.descriptionView.text = it.notes
dialog.addButton(R.string.equip, true) { _, _ ->
inventoryRepository.equip("equipped", it.key ?: "").subscribe({}, RxErrorHandler.handleEmptyError())
}
dialog.addCloseButton()
dialog.enqueue()
}
}
.subscribe({ }, RxErrorHandler.handleEmptyError())
)
compositeSubscription.add(adapter.hatchPetEvents.subscribeWithErrorHandler { hatchPet(it.first, it.second) })
compositeSubscription.add(adapter.feedPetEvents.subscribeWithErrorHandler { feedPet(it) })
}
}
activity?.let {
binding?.recyclerView?.addItemDecoration(androidx.recyclerview.widget.DividerItemDecoration(it, androidx.recyclerview.widget.DividerItemDecoration.VERTICAL))
}
binding?.recyclerView?.itemAnimator = SafeDefaultItemAnimator()
if (savedInstanceState != null) {
this.itemType = savedInstanceState.getString(ITEM_TYPE_KEY, "")
}
when {
this.isHatching -> {
binding?.titleTextView?.text = getString(R.string.hatch_with, this.hatchingItem?.text)
binding?.titleTextView?.visibility = View.VISIBLE
binding?.footerTextView?.text = getString(R.string.hatching_market_info)
binding?.footerTextView?.visibility = View.VISIBLE
binding?.openMarketButton?.visibility = View.VISIBLE
}
this.isFeeding -> {
binding?.titleTextView?.text = getString(R.string.dialog_feeding, this.feedingPet?.text)
binding?.titleTextView?.visibility = View.VISIBLE
binding?.footerTextView?.text = getString(R.string.feeding_market_info)
binding?.footerTextView?.visibility = View.VISIBLE
binding?.openMarketButton?.visibility = View.VISIBLE
}
else -> {
binding?.titleTextView?.visibility = View.GONE
binding?.footerTextView?.visibility = View.GONE
binding?.openMarketButton?.visibility = View.GONE
}
}
binding?.openMarketButton?.setOnClickListener {
dismiss()
openMarket()
}
this.loadItems()
}
private fun feedPet(food: Food) {
val pet = feedingPet ?: return
(activity as? BaseActivity)?.let {
it.compositeSubscription.add(
feedPetUseCase.observable(
FeedPetUseCase.RequestValues(
pet, food,
it
)
).subscribeWithErrorHandler {}
)
}
}
override fun onResume() {
if ((this.isHatching || this.isFeeding) && dialog?.window != null) {
val params = dialog?.window?.attributes
params?.width = ViewGroup.LayoutParams.MATCH_PARENT
params?.verticalMargin = 60f
dialog?.window?.attributes = params
}
super.onResume()
}
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
outState.putString(ITEM_TYPE_KEY, this.itemType)
}
override fun onRefresh() {
binding?.refreshLayout?.isRefreshing = true
compositeSubscription.add(
userRepository.retrieveUser(true, true)
.doOnTerminate {
binding?.refreshLayout?.isRefreshing = false
}.subscribe({ }, RxErrorHandler.handleEmptyError())
)
}
private fun hatchPet(potion: HatchingPotion, egg: Egg) {
dismiss()
(activity as? BaseActivity)?.let {
it.compositeSubscription.add(
hatchPetUseCase.observable(
HatchPetUseCase.RequestValues(
potion, egg,
it
)
).subscribeWithErrorHandler {}
)
}
}
private fun loadItems() {
val itemClass: Class<out Item> = when (itemType) {
"eggs" -> Egg::class.java
"hatchingPotions" -> HatchingPotion::class.java
"food" -> Food::class.java
"quests" -> QuestContent::class.java
"special" -> SpecialItem::class.java
else -> Egg::class.java
}
itemType?.let { type ->
compositeSubscription.add(
inventoryRepository.getOwnedItems(type)
.doOnNext { items ->
val filteredItems = if (isFeeding) {
items.filter { it.key != "Saddle" }
} else {
items
}
adapter?.data = filteredItems
}
.map { items -> items.mapNotNull { it.key } }
.flatMap { inventoryRepository.getItems(itemClass, it.toTypedArray()) }
.map {
val itemMap = mutableMapOf<String, Item>()
for (item in it) {
itemMap[item.key] = item
}
itemMap
}
.subscribe(
{ items ->
adapter?.items = items
},
RxErrorHandler.handleEmptyError()
)
)
}
compositeSubscription.add(inventoryRepository.getPets().subscribe({ adapter?.setExistingPets(it) }, RxErrorHandler.handleEmptyError()))
compositeSubscription.add(
inventoryRepository.getOwnedPets()
.map { ownedMounts ->
val mountMap = mutableMapOf<String, OwnedPet>()
ownedMounts.forEach { mountMap[it.key ?: ""] = it }
return@map mountMap
}
.subscribe({ adapter?.setOwnedPets(it) }, RxErrorHandler.handleEmptyError())
)
}
private fun openMarket() {
MainNavigationController.navigate(R.id.marketFragment)
}
companion object {
private const val ITEM_TYPE_KEY = "CLASS_TYPE_KEY"
}
}
| gpl-3.0 | d67b22066bdbc712c14e7b75dfb1adbd | 40.542056 | 169 | 0.587627 | 5.728093 | false | false | false | false |
androidx/androidx | paging/samples/src/main/java/androidx/paging/samples/ListenableFuturePagingSourceSample.kt | 3 | 3174 | /*
* Copyright 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
@file:Suppress("unused", "UnstableApiUsage")
package androidx.paging.samples
import androidx.annotation.Sampled
import androidx.paging.ListenableFuturePagingSource
import androidx.paging.PagingState
import com.google.common.util.concurrent.FluentFuture
import com.google.common.util.concurrent.ListenableFuture
import retrofit2.HttpException
import java.io.IOException
import java.util.concurrent.Executor
data class RemoteResult(
val items: List<Item>,
val prev: String,
val next: String
)
private class GuavaBackendService {
@Suppress("UNUSED_PARAMETER")
fun searchUsers(searchTerm: String, pageKey: String?): FluentFuture<RemoteResult> {
throw NotImplementedError()
}
}
lateinit var networkExecutor: Executor
@Sampled
fun listenableFuturePagingSourceSample() {
class MyListenableFuturePagingSource(
val myBackend: GuavaBackendService,
val searchTerm: String
) : ListenableFuturePagingSource<String, Item>() {
override fun loadFuture(
params: LoadParams<String>
): ListenableFuture<LoadResult<String, Item>> {
return myBackend
.searchUsers(
searchTerm = searchTerm,
pageKey = params.key
)
.transform<LoadResult<String, Item>>(
{ response ->
LoadResult.Page(
data = response!!.items,
prevKey = response.prev,
nextKey = response.next
)
},
networkExecutor
)
// Retrofit calls that return the body type throw either IOException for
// network failures, or HttpException for any non-2xx HTTP status codes.
// This code reports all errors to the UI, but you can inspect/wrap the
// exceptions to provide more context.
.catching(
IOException::class.java,
{ t: IOException? -> LoadResult.Error(t!!) },
networkExecutor
)
.catching(
HttpException::class.java,
{ t: HttpException? -> LoadResult.Error(t!!) },
networkExecutor
)
}
override fun getRefreshKey(state: PagingState<String, Item>): String? {
return state.anchorPosition?.let { state.closestItemToPosition(it)?.id }
}
}
} | apache-2.0 | 966900bf6aac986248d1a4a7dbd964ed | 34.674157 | 88 | 0.611216 | 5.237624 | false | false | false | false |
minecraft-dev/MinecraftDev | src/test/kotlin/framework/ProjectBuilderTest.kt | 1 | 2006 | /*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2022 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev.framework
import com.intellij.codeInspection.LocalInspectionTool
import com.intellij.openapi.module.Module
import com.intellij.openapi.project.Project
import com.intellij.testFramework.LightProjectDescriptor
import com.intellij.testFramework.fixtures.IdeaTestFixtureFactory
import com.intellij.testFramework.fixtures.JavaCodeInsightTestFixture
import com.intellij.testFramework.fixtures.JavaTestFixtureFactory
import com.intellij.testFramework.fixtures.TempDirTestFixture
import com.intellij.testFramework.fixtures.impl.LightTempDirTestFixtureImpl
import kotlin.reflect.KClass
import org.junit.jupiter.api.AfterEach
import org.junit.jupiter.api.BeforeEach
abstract class ProjectBuilderTest(descriptor: LightProjectDescriptor? = null) {
protected val fixture: JavaCodeInsightTestFixture
protected val project: Project
get() = fixture.project
protected val module: Module
get() = fixture.module
private val tempDirFixture: TempDirTestFixture
init {
val lightFixture = IdeaTestFixtureFactory.getFixtureFactory()
.createLightFixtureBuilder(descriptor)
.fixture
// This is a poorly named class - it actually means create a temp dir test fixture _in-memory_
tempDirFixture = LightTempDirTestFixtureImpl(true)
fixture = JavaTestFixtureFactory.getFixtureFactory().createCodeInsightFixture(lightFixture, tempDirFixture)
}
fun buildProject(builder: ProjectBuilder.() -> Unit) =
ProjectBuilder(fixture, tempDirFixture).build(builder)
fun JavaCodeInsightTestFixture.enableInspections(vararg classes: KClass<out LocalInspectionTool>) {
this.enableInspections(classes.map { it.java })
}
@NoEdt
@BeforeEach
fun setup() {
fixture.setUp()
}
@AfterEach
fun tearDown() {
fixture.tearDown()
}
}
| mit | f5d7cedf0a893ddb2f139f7b82b350b2 | 30.84127 | 115 | 0.75673 | 5.015 | false | true | false | false |
andstatus/andstatus | app/src/main/kotlin/org/andstatus/app/data/ProjectionMap.kt | 1 | 4883 | /*
* Copyright (C) 2015 yvolk (Yuri Volkov), http://yurivolkov.com
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.andstatus.app.data
import android.provider.BaseColumns
import org.andstatus.app.database.table.ActivityTable
import org.andstatus.app.database.table.ActorTable
import org.andstatus.app.database.table.DownloadTable
import org.andstatus.app.database.table.NoteTable
import java.util.*
object ProjectionMap {
val ACTIVITY_TABLE_ALIAS: String = "act1"
val NOTE_TABLE_ALIAS: String = "msg1"
val ATTACHMENT_IMAGE_TABLE_ALIAS: String = "img"
/**
* Projection map used by SQLiteQueryBuilder
* Projection map for a Timeline
* @see android.database.sqlite.SQLiteQueryBuilder.setProjectionMap
*/
val TIMELINE: MutableMap<String, String> = HashMap()
init {
TIMELINE[ActivityTable.ACTIVITY_ID] = (ACTIVITY_TABLE_ALIAS + "." + BaseColumns._ID
+ " AS " + ActivityTable.ACTIVITY_ID)
TIMELINE[ActivityTable.ORIGIN_ID] = ActivityTable.ORIGIN_ID
TIMELINE[ActivityTable.ACCOUNT_ID] = ActivityTable.ACCOUNT_ID
TIMELINE[ActivityTable.ACTIVITY_TYPE] = ActivityTable.ACTIVITY_TYPE
TIMELINE[ActivityTable.ACTOR_ID] = ActivityTable.ACTOR_ID
TIMELINE[ActivityTable.AUTHOR_ID] = ActivityTable.AUTHOR_ID
TIMELINE[ActivityTable.NOTE_ID] = ActivityTable.NOTE_ID
TIMELINE[ActivityTable.OBJ_ACTOR_ID] = ActivityTable.OBJ_ACTOR_ID
TIMELINE[ActivityTable.SUBSCRIBED] = ActivityTable.SUBSCRIBED
TIMELINE[ActivityTable.NOTIFIED] = ActivityTable.NOTIFIED
TIMELINE[ActivityTable.INS_DATE] = ActivityTable.INS_DATE
TIMELINE[ActivityTable.UPDATED_DATE] = ActivityTable.UPDATED_DATE
TIMELINE[BaseColumns._ID] = NOTE_TABLE_ALIAS + "." + BaseColumns._ID + " AS " + BaseColumns._ID
TIMELINE[NoteTable.NOTE_ID] = NOTE_TABLE_ALIAS + "." + BaseColumns._ID + " AS " + NoteTable.NOTE_ID
TIMELINE[NoteTable.ORIGIN_ID] = NoteTable.ORIGIN_ID
TIMELINE[NoteTable.NOTE_OID] = NoteTable.NOTE_OID
TIMELINE[NoteTable.CONVERSATION_ID] = NoteTable.CONVERSATION_ID
TIMELINE[NoteTable.AUTHOR_ID] = NoteTable.AUTHOR_ID
TIMELINE[ActorTable.AUTHOR_NAME] = ActorTable.AUTHOR_NAME
TIMELINE[DownloadTable.DOWNLOAD_STATUS] = DownloadTable.DOWNLOAD_STATUS
TIMELINE[DownloadTable.FILE_NAME] = DownloadTable.FILE_NAME
TIMELINE[DownloadTable.IMAGE_FILE_NAME] = (ATTACHMENT_IMAGE_TABLE_ALIAS + "." + DownloadTable.FILE_NAME
+ " AS " + DownloadTable.IMAGE_FILE_NAME)
TIMELINE[DownloadTable.IMAGE_ID] = (ATTACHMENT_IMAGE_TABLE_ALIAS + "." + BaseColumns._ID
+ " AS " + DownloadTable.IMAGE_ID)
TIMELINE[DownloadTable.IMAGE_URI] = (ATTACHMENT_IMAGE_TABLE_ALIAS + "." + DownloadTable.URL
+ " AS " + DownloadTable.IMAGE_URI)
TIMELINE[DownloadTable.PREVIEW_OF_DOWNLOAD_ID] = DownloadTable.PREVIEW_OF_DOWNLOAD_ID
TIMELINE[DownloadTable.WIDTH] = DownloadTable.WIDTH
TIMELINE[DownloadTable.HEIGHT] = DownloadTable.HEIGHT
TIMELINE[DownloadTable.DURATION] = DownloadTable.DURATION
TIMELINE[NoteTable.NAME] = NoteTable.NAME
TIMELINE[NoteTable.SUMMARY] = NoteTable.SUMMARY
TIMELINE[NoteTable.SENSITIVE] = NoteTable.SENSITIVE
TIMELINE[NoteTable.CONTENT] = NoteTable.CONTENT
TIMELINE[NoteTable.CONTENT_TO_SEARCH] = NoteTable.CONTENT_TO_SEARCH
TIMELINE[NoteTable.VIA] = NoteTable.VIA
TIMELINE[NoteTable.URL] = NoteTable.URL
TIMELINE[NoteTable.IN_REPLY_TO_NOTE_ID] = NoteTable.IN_REPLY_TO_NOTE_ID
TIMELINE[NoteTable.IN_REPLY_TO_ACTOR_ID] = NoteTable.IN_REPLY_TO_ACTOR_ID
TIMELINE[NoteTable.VISIBILITY] = NoteTable.VISIBILITY
TIMELINE[NoteTable.FAVORITED] = NoteTable.FAVORITED
TIMELINE[NoteTable.REBLOGGED] = NoteTable.REBLOGGED
TIMELINE[NoteTable.LIKES_COUNT] = NoteTable.LIKES_COUNT
TIMELINE[NoteTable.REBLOGS_COUNT] = NoteTable.REBLOGS_COUNT
TIMELINE[NoteTable.REPLIES_COUNT] = NoteTable.REPLIES_COUNT
TIMELINE[NoteTable.UPDATED_DATE] = NoteTable.UPDATED_DATE
TIMELINE[NoteTable.NOTE_STATUS] = NoteTable.NOTE_STATUS
TIMELINE[NoteTable.INS_DATE] = NoteTable.INS_DATE
TIMELINE[NoteTable.ATTACHMENTS_COUNT] = NoteTable.ATTACHMENTS_COUNT
}
}
| apache-2.0 | 3867b5d4af5325c7aab567577782a137 | 53.255556 | 111 | 0.712472 | 4.290861 | false | false | false | false |
EventFahrplan/EventFahrplan | commons/src/main/java/info/metadude/android/eventfahrplan/commons/temporal/DateFormatter.kt | 1 | 6339 | package info.metadude.android.eventfahrplan.commons.temporal
import org.threeten.bp.Instant
import org.threeten.bp.OffsetDateTime
import org.threeten.bp.ZoneId
import org.threeten.bp.ZoneOffset
import org.threeten.bp.ZonedDateTime
import org.threeten.bp.format.DateTimeFormatter
import org.threeten.bp.format.FormatStyle
/**
* Format timestamps according to system locale and system time zone.
*/
class DateFormatter private constructor(
val useDeviceTimeZone: Boolean
) {
private val timeShortNumberOnlyFormatter = DateTimeFormatter.ofPattern("HH:mm")
private val timeShortFormatter = DateTimeFormatter.ofLocalizedTime(FormatStyle.SHORT)
private val dateShortFormatter = DateTimeFormatter.ofLocalizedDate(FormatStyle.SHORT)
private val dateShortTimeShortFormatter = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.SHORT, FormatStyle.SHORT)
private val dateLongTimeShortFormatter = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.LONG, FormatStyle.SHORT)
private val dateFullTimeShortFormatter = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.FULL, FormatStyle.SHORT)
private val timeZoneOffsetFormatter = DateTimeFormatter.ofPattern("z")
/**
* Returns a formatted `hours:minutes` string. Formatting happens by taking the [original time
* zone of the associated session][sessionZoneOffset] into account. If [sessionZoneOffset] is
* missing then formatting falls back to using the current time zone offset of the device.
*
* The returned text is formatted equally for all locales, e.g. 01:00, 14:00 etc. - always
* without AM or PM postfix - in 24 hours format.
*/
fun getFormattedTime24Hour(moment: Moment, sessionZoneOffset: ZoneOffset?): String {
val zoneOffset = getAvailableZoneOffset(sessionZoneOffset)
return timeShortNumberOnlyFormatter.format(moment.toZonedDateTime(zoneOffset))
}
/**
* Returns 01:00 AM, 02:00 PM, 14:00 etc, depending on current system locale either
* in 24 or 12 hour format. The latter featuring AM or PM postfixes.
*
* Formatting happens by taking the [original time zone of the associated session][sessionZoneOffset]
* into account. If [sessionZoneOffset] is missing then formatting falls back to using the
* current time zone offset of the device.
*/
fun getFormattedTime(time: Long, sessionZoneOffset: ZoneOffset?): String {
val zoneOffset = getAvailableZoneOffset(sessionZoneOffset)
return timeShortFormatter.withZone(zoneOffset).format(Instant.ofEpochMilli(time))
}
/**
* Returns day, month and year in current system locale.
* E.g. 1/22/19 or 22.01.19
*
* Formatting happens by taking the [original time zone of the associated session][sessionZoneOffset]
* into account. If [sessionZoneOffset] is missing then formatting falls back to using the
* current time zone offset of the device.
*/
fun getFormattedDate(time: Long, sessionZoneOffset: ZoneOffset?): String {
val zoneOffset = getAvailableZoneOffset(sessionZoneOffset)
return dateShortFormatter.withZone(zoneOffset).format(Instant.ofEpochMilli(time))
}
/**
* Returns a formatted string suitable for sharing it with people worldwide.
* It consists of day, month, year, time, time zone offset in the time zone of the event or
* in current system time zone if the former is not provided.
*
* The human readable name '{area}/{city}' of the time zone ID is appended if available.
*
* Formatting example:
* Tuesday, January 22, 2019, 1:00 AM GMT+01:00 (Europe/Berlin)
*/
fun getFormattedShareable(time: Long, timeZoneId: ZoneId?): String {
val displayTimeZone = timeZoneId ?: ZoneId.systemDefault()
val sessionStartTime = Instant.ofEpochMilli(time)
val timeZoneOffset = timeZoneOffsetFormatter.withZone(displayTimeZone).format(sessionStartTime)
val sessionDateTime = dateFullTimeShortFormatter.withZone(displayTimeZone).format(sessionStartTime)
var shareableText = "$sessionDateTime $timeZoneOffset"
if (timeZoneId != null) {
shareableText += " (${displayTimeZone.id})"
}
return shareableText
}
/**
* Returns day, month, year and time in short format. Formatting happens by taking the [original
* time zone of the associated session][sessionZoneOffset] into account. If [sessionZoneOffset]
* is missing then formatting falls back to using the current time zone offset of the device.
*
* E.g. 1/22/19, 1:00 AM
*/
fun getFormattedDateTimeShort(time: Long, sessionZoneOffset: ZoneOffset?): String {
val zoneOffset = getAvailableZoneOffset(sessionZoneOffset)
val toZonedDateTime: ZonedDateTime = Moment.ofEpochMilli(time).toZonedDateTime(zoneOffset)
return dateShortTimeShortFormatter.format(toZonedDateTime)
}
/**
* Returns day, month, year and time in long format. Formatting happens by taking the [original
* time zone of the associated session][sessionZoneOffset] into account. If [sessionZoneOffset]
* is missing then formatting falls back to using the current time zone offset of the device.
*
* E.g. January 22, 2019, 1:00 AM
*/
fun getFormattedDateTimeLong(time: Long, sessionZoneOffset: ZoneOffset?): String {
val zoneOffset = getAvailableZoneOffset(sessionZoneOffset)
val toZonedDateTime = Moment.ofEpochMilli(time).toZonedDateTime(zoneOffset)
return dateLongTimeShortFormatter.format(toZonedDateTime)
}
/**
* Returns the available zone offset - either the given [sessionZoneOffset] or the zone offset
* of the device. The user can overrule the logic by setting [useDeviceTimeZone].
*/
private fun getAvailableZoneOffset(sessionZoneOffset: ZoneOffset?): ZoneOffset {
val deviceZoneOffset = OffsetDateTime.now().offset
val useDeviceZoneOffset = sessionZoneOffset == null || sessionZoneOffset == deviceZoneOffset
return if (useDeviceTimeZone || useDeviceZoneOffset) deviceZoneOffset else sessionZoneOffset!!
}
companion object {
@JvmStatic
fun newInstance(useDeviceTimeZone: Boolean): DateFormatter {
return DateFormatter(useDeviceTimeZone)
}
}
}
| apache-2.0 | bf16ea12be6a83d2e751656ccd826315 | 47.022727 | 121 | 0.730715 | 5.08748 | false | false | false | false |
InfiniteSoul/ProxerAndroid | src/main/kotlin/me/proxer/app/anime/resolver/ProxerStreamResolver.kt | 2 | 1760 | package me.proxer.app.anime.resolver
import android.net.Uri
import io.reactivex.Single
import me.proxer.app.MainApplication.Companion.USER_AGENT
import me.proxer.app.exception.StreamResolutionException
import me.proxer.app.util.extension.buildSingle
import me.proxer.app.util.extension.toBodySingle
import me.proxer.app.util.extension.toPrefixedUrlOrNull
import okhttp3.HttpUrl.Companion.toHttpUrlOrNull
import okhttp3.Request
/**
* @author Ruben Gees
*/
object ProxerStreamResolver : StreamResolver() {
private val regex = Regex("<source type=\"(.*?)\" src=\"(.*?)\">")
override val name = "Proxer-Stream"
override fun resolve(id: String): Single<StreamResolutionResult> {
return api.anime.vastLink(id)
.buildSingle()
.flatMap { (link, adTag) ->
client
.newCall(
Request.Builder()
.get()
.url(link.toPrefixedUrlOrNull() ?: throw StreamResolutionException())
.header("User-Agent", USER_AGENT)
.header("Connection", "close")
.build()
)
.toBodySingle()
.map {
val regexResult = regex.find(it) ?: throw StreamResolutionException()
val url = regexResult.groupValues[2].toHttpUrlOrNull() ?: throw StreamResolutionException()
val type = regexResult.groupValues[1]
val adTagUri = if (adTag.isNotBlank()) Uri.parse(adTag) else null
StreamResolutionResult.Video(url, type, adTag = adTagUri)
}
}
}
}
| gpl-3.0 | c1d720b4628750dbd9fb994bb99178ce | 35.666667 | 115 | 0.565909 | 5.146199 | false | false | false | false |
inorichi/tachiyomi-extensions | multisrc/overrides/mangacatalog/readgoblinslayermangaonline/src/ReadGoblinSlayerMangaOnline.kt | 1 | 1857 | package eu.kanade.tachiyomi.extension.en.readgoblinslayermangaonline
import eu.kanade.tachiyomi.multisrc.mangacatalog.MangaCatalog
import eu.kanade.tachiyomi.source.model.MangasPage
import eu.kanade.tachiyomi.util.asJsoup
import eu.kanade.tachiyomi.network.GET
import eu.kanade.tachiyomi.source.model.FilterList
import eu.kanade.tachiyomi.source.model.SChapter
import eu.kanade.tachiyomi.source.model.SManga
import eu.kanade.tachiyomi.source.model.Page
import eu.kanade.tachiyomi.source.online.ParsedHttpSource
import okhttp3.Request
import rx.Observable
import org.jsoup.nodes.Document
import org.jsoup.nodes.Element
class ReadGoblinSlayerMangaOnline : MangaCatalog("Read Goblin Slayer Manga Online", "https://manga.watchgoblinslayer.com", "en") {
override val sourceList = listOf(
Pair("Goblin Slayer", "$baseUrl/manga/goblin-slayer/"),
Pair("Side Story: Brand New Day", "$baseUrl/manga/goblin-slayer-side-story-brand-new-day/"),
Pair("Side Story: Year One", "$baseUrl/manga/goblin-slayer-side-story-year-one/"),
Pair("Side Story: Gaiden 2", "$baseUrl/manga/goblin-slayer-gaiden-2-tsubanari-no-daikatana/"),
).sortedBy { it.first }.distinctBy { it.second }
override fun mangaDetailsParse(document: Document): SManga = SManga.create().apply {
description = document.select("div.card-body > p").text()
title = document.select("h2 > span").text()
thumbnail_url = document.select(".card-img-right").attr("src")
}
override fun chapterListSelector(): String = "tbody > tr"
override fun chapterFromElement(element: Element): SChapter = SChapter.create().apply {
name = element.select("td:first-child").text()
url = element.select("a.btn-primary").attr("abs:href")
date_upload = System.currentTimeMillis() //I have no idear how to parse Date stuff
}
}
| apache-2.0 | 1dcc002fa30c5d3427ce379001e0cf21 | 50.583333 | 130 | 0.735595 | 3.789796 | false | false | false | false |
felipebz/sonar-plsql | zpa-checks/src/main/kotlin/org/sonar/plsqlopen/checks/UnusedVariableCheck.kt | 1 | 1972 | /**
* Z PL/SQL Analyzer
* Copyright (C) 2015-2022 Felipe Zorzo
* mailto:felipe AT felipezorzo DOT com DOT br
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.plsqlopen.checks
import com.felipebz.flr.api.AstNode
import org.sonar.plugins.plsqlopen.api.PlSqlGrammar
import org.sonar.plugins.plsqlopen.api.annotations.*
import org.sonar.plugins.plsqlopen.api.symbols.Scope
import org.sonar.plugins.plsqlopen.api.symbols.Symbol
@Rule(priority = Priority.MAJOR, tags = [Tags.UNUSED])
@ConstantRemediation("2min")
@RuleInfo(scope = RuleInfo.Scope.ALL)
@ActivatedByDefault
class UnusedVariableCheck : AbstractBaseCheck() {
override fun leaveFile(node: AstNode) {
val scopes = context.symbolTable.scopes
for (scope in scopes) {
if (scope.tree().isNot(PlSqlGrammar.CREATE_PACKAGE, PlSqlGrammar.FOR_STATEMENT)) {
checkScope(scope)
}
}
}
private fun checkScope(scope: Scope) {
val symbols = scope.getSymbols(Symbol.Kind.VARIABLE)
for (symbol in symbols) {
if (symbol.usages().isEmpty()) {
addIssue(symbol.declaration(), getLocalizedMessage(),
symbol.declaration().tokenOriginalValue)
}
}
}
}
| lgpl-3.0 | ee86b7898201c105fef9e64d2ccecc72 | 36.207547 | 94 | 0.700304 | 4.268398 | false | false | false | false |
StepicOrg/stepic-android | app/src/main/java/org/stepik/android/domain/video_player/analytic/VideoPlayerControlClickedEvent.kt | 2 | 920 | package org.stepik.android.domain.video_player.analytic
import org.stepik.android.domain.base.analytic.AnalyticEvent
class VideoPlayerControlClickedEvent(
action: String
) : AnalyticEvent {
companion object {
private const val PARAM_ACTION = "action"
const val ACTION_PREVIOS = "previos"
const val ACTION_REWIND = "rewind"
const val ACTION_FORWARD = "forward"
const val ACTION_NEXT = "next"
const val ACTION_SEEK_BACK = "seek_back"
const val ACTION_SEEK_FORWARD = "seek_forward"
const val ACTION_DOUBLE_CLICK_LEFT = "double_click_left"
const val ACTION_DOUBLE_CLICK_RIGHT = "double_click_right"
const val ACTION_PLAY = "play"
const val ACTION_PAUSE = "pause"
}
override val name: String =
"Video player control clicked"
override val params: Map<String, Any> =
mapOf(PARAM_ACTION to action)
} | apache-2.0 | d4bd6e62bf907b4f7f51cf59efe2eaf0 | 31.892857 | 66 | 0.666304 | 4.035088 | false | false | false | false |
NerdNumber9/TachiyomiEH | app/src/main/java/exh/search/Text.kt | 1 | 2034 | package exh.search
import exh.plusAssign
import exh.search.SearchEngine.Companion.escapeLike
class Text: QueryComponent() {
val components = mutableListOf<TextComponent>()
private var query: String? = null
private var lenientTitleQuery: String? = null
private var lenientTagQueries: List<String>? = null
private var rawText: String? = null
fun asQuery(): String {
if(query == null) {
query = rBaseBuilder().toString()
}
return query!!
}
fun asLenientTitleQuery(): String {
if(lenientTitleQuery == null) {
lenientTitleQuery = StringBuilder("%").append(rBaseBuilder()).append("%").toString()
}
return lenientTitleQuery!!
}
fun asLenientTagQueries(): List<String> {
if(lenientTagQueries == null) {
lenientTagQueries = listOf(
//Match beginning of tag
rBaseBuilder().append("%").toString(),
//Tag word matcher (that matches multiple words)
//Can't make it match a single word in Realm :(
StringBuilder(" ").append(rBaseBuilder()).append(" ").toString(),
StringBuilder(" ").append(rBaseBuilder()).toString(),
rBaseBuilder().append(" ").toString()
)
}
return lenientTagQueries!!
}
fun rBaseBuilder(): StringBuilder {
val builder = StringBuilder()
for(component in components) {
when(component) {
is StringTextComponent -> builder += escapeLike(component.value)
is SingleWildcard -> builder += "_"
is MultiWildcard -> builder += "%"
}
}
return builder
}
fun rawTextOnly() = if(rawText != null)
rawText!!
else {
rawText = components
.joinToString(separator = "", transform = { it.rawText })
rawText!!
}
fun rawTextEscapedForLike() = escapeLike(rawTextOnly())
}
| apache-2.0 | 932a73eb5660c8d4d8c57d982054c105 | 30.78125 | 96 | 0.561947 | 5.26943 | false | false | false | false |
deltaDNA/android-sdk | library-notifications/src/main/java/com/deltadna/android/sdk/notifications/NotificationFactory.kt | 1 | 8496 | /*
* Copyright (c) 2017 deltaDNA Ltd. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.deltadna.android.sdk.notifications
import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.os.Build
import androidx.annotation.RequiresApi
import androidx.core.app.NotificationCompat
/**
* Factory class responsible for filling details from a push message and
* creating a notification to be posted on the UI.
*
*
* The default implementation uses the 'title' and 'alert' fields from the push
* message as the title and message respectively for the notification. If the
* title has not been defined in the message then the application's name will
* be used instead. Upon selection the notification will open the launch
* `Intent` of your application.
*
*
* The default behaviour can be customised by extending the class and overriding
* [.configure]. The
* [NotificationListenerService] will then need to be extended in order
* to define the new factory to be used for creating notifications.
*/
open class NotificationFactory(protected val context: Context) {
companion object {
/**
* Identifier for the default [NotificationChannel] used for
* notifications.
*/
const val DEFAULT_CHANNEL = "com.deltadna.default"
}
/**
* Fills a [androidx.core.app.NotificationCompat.Builder]
* with details from a [PushMessage].
*
* @param context the context for the notification
* @param message the push message
*
* @return configured notification builder
*/
open fun configure(context: Context?, message: PushMessage): NotificationCompat.Builder? {
var builder: NotificationCompat.Builder = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationCompat.Builder(context!!, getChannel().id)
} else {
NotificationCompat.Builder(context)
}
builder = builder
.setSmallIcon(message.icon)
.setContentTitle(message.title)
.setContentText(message.message)
.setAutoCancel(true)
if (message.imageUrl != null) {
builder.setLargeIcon(message.imageUrl)
.setStyle(
NotificationCompat.BigPictureStyle()
.bigPicture(message.imageUrl).bigLargeIcon(null)
)
}
return builder
}
/**
* Creates a [Notification] from a previously configured
* [NotificationCompat.Builder] and a [NotificationInfo]
* instance.
*
* Implementations which call
* [NotificationCompat.Builder.setContentIntent]
* or
* [NotificationCompat.Builder.setDeleteIntent]
* on the [NotificationCompat.Builder] and thus override the default
* behaviour should notify the SDK that the push notification has been
* opened or dismissed respectively.
*
* @param builder the configured notification builder
* @param info the notification info
*
* @return notification to post on the UI, or `null` if a
* notification shouldn't be posted
*
* @see EventReceiver
*/
fun create(builder: NotificationCompat.Builder, info: NotificationInfo): Notification? {
val intentFlags: Int = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT
} else {
PendingIntent.FLAG_UPDATE_CURRENT
}
builder.setContentIntent(createContentIntent(info, intentFlags))
builder.setDeleteIntent(createDeleteIntent(info, intentFlags))
return builder.build()
}
/**
* Gets the [NotificationChannel] to be used for configuring the
* push notification.
*
* The [.DEFAULT_CHANNEL] is used as the default identifier.
*
* @return notification channel to be used
*/
@RequiresApi(Build.VERSION_CODES.O)
protected fun getChannel(): NotificationChannel {
val channel = NotificationChannel(
DEFAULT_CHANNEL,
context.getString(R.string.ddna_notification_channel_name),
NotificationManager.IMPORTANCE_DEFAULT
)
(context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager)
.createNotificationChannel(channel)
return channel
}
/**
* Creates the intent which is used when a user opens the host app from a notification. In most
* cases, this will be a set of two activities - our DeltaDNA tracking activity that records the
* opened notification, and the host app's launch intent. Once the deltaDNA Intent completes, the
* launch intent will be shown as part of Android's normal behaviour, and won't be blocked by the
* trampolining prevention that blocks launching intents from Broadcast Receivers.
*/
private fun createContentIntent(info: NotificationInfo, intentFlags: Int): PendingIntent {
val notificationOpenedHandlerClass = if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
NotificationOpenedHandlerAndroid23AndHigher::class.java
} else {
NotificationOpenedHandlerPreAndroid23::class.java
}
val notificationOpenedHandlerIntent = Intent(context, notificationOpenedHandlerClass)
.setPackage(context.packageName)
.setAction(Actions.NOTIFICATION_OPENED_INTERNAL)
.putExtra(Actions.NOTIFICATION_INFO, info)
.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP or Intent.FLAG_ACTIVITY_CLEAR_TOP) // Only ever have one notification opened tracking activity
val launchIntent = context.packageManager.getLaunchIntentForPackage(context.packageName)
if (launchIntent == null) {
// If the app hasn't specified a launch intent, we just use our notification handler activity, to still enable notificationOpened tracking.
return PendingIntent.getActivity(context, info.id, notificationOpenedHandlerIntent, intentFlags)
} else {
// If the app specifies a launch intent, we add it to the activity stack, so that once we've finished capturing the notificationOpened behaviour
// the app will open as normal, without the need for a BroadcastReceiver trampoline which is no longer allowed in Android 12.
launchIntent.setPackage(null) // This makes the app start as if it was launched externally, preventing duplicate activities from being created
launchIntent.flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED
val intents: Array<Intent> = arrayOf(launchIntent, notificationOpenedHandlerIntent)
return PendingIntent.getActivities(context, info.id, intents, intentFlags)
}
}
/**
* Creates the intent which is used when a user dismisses our push notification without opening it. Now
* that we've moved to using a custom activity to track notification opens, and we previously had no custom
* behaviour on notification dismissed, we can instead directly signal our notifications receiver that the notification
* was dismissed, instead of relaying via an intermediate broadcast receiver.
*/
private fun createDeleteIntent(info: NotificationInfo, intentFlags: Int): PendingIntent {
val intent = Intent(Actions.NOTIFICATION_DISMISSED)
synchronized(DDNANotifications::class.java) {
if (DDNANotifications.receiver != null) {
intent.setClass(context, DDNANotifications.receiver!!)
}
}
return PendingIntent.getBroadcast(
context,
info.id,
intent,
intentFlags
)
}
} | apache-2.0 | 7639901b0140830f1c11f1e7d88812d3 | 41.914141 | 156 | 0.690796 | 5.045131 | false | false | false | false |
Asqatasun/Asqatasun | engine/crawler/src/test/kotlin/org/asqatasun/crawler/CrawlerImplTest.kt | 1 | 5089 | /*
* Asqatasun - Automated webpage assessment
* Copyright (C) 2008-2021 Asqatasun.org
*
* This file is part of Asqatasun.
*
* Asqatasun is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Contact us by mail: asqatasun AT asqatasun DOT org
*/
package org.asqatasun.crawler
import org.asqatasun.entity.audit.AuditImpl
import org.asqatasun.entity.parameterization.Parameter
import org.asqatasun.entity.parameterization.ParameterElementImpl
import org.asqatasun.entity.parameterization.ParameterImpl
import org.asqatasun.entity.service.subject.WebResourceDataService
import org.asqatasun.entity.subject.PageImpl
import org.asqatasun.entity.subject.SiteImpl
import org.junit.jupiter.api.Test
import org.mockito.Matchers.anyString
import org.mockito.Mockito
import org.mockito.Mockito.never
import org.mockito.Mockito.times
class CrawlerImplTest {
private val webResourceDataService: WebResourceDataService = Mockito.mock(WebResourceDataService::class.java)
companion object {
private const val URL = "https://site-robot.asqatasun.ovh/"
private const val rootPageUrl = URL
private const val depthOnePageUrl = URL + "page-1.html"
private const val depthTwoPageUrl = URL + "page-2.html"
private const val robotsAccessForbiddenPageUrl = URL + "page-access-forbidden-for-robots.html"
private const val politenessDelay = 100
}
@Test
fun crawlSiteDepth0() {
crawlSite(0, listOf(rootPageUrl), listOf(depthOnePageUrl, depthTwoPageUrl, robotsAccessForbiddenPageUrl))
}
@Test
fun crawlSiteDepth1() {
crawlSite(1, listOf(rootPageUrl, depthOnePageUrl), listOf(depthTwoPageUrl, robotsAccessForbiddenPageUrl))
}
@Test
fun crawlSiteDepth2() {
crawlSite(2, listOf(rootPageUrl, depthOnePageUrl, depthTwoPageUrl), listOf(robotsAccessForbiddenPageUrl))
}
@Test
fun crawlSiteDepth2AndNotRespectRobotsTxtDirectives() {
crawlSite(2, listOf(rootPageUrl, depthOnePageUrl, depthTwoPageUrl, robotsAccessForbiddenPageUrl), listOf(), false)
}
private fun crawlSite(depth: Int, calledUrlList: List<String>, neverCalledUrlList: List<String>, respectRobotsTxt: Boolean = true) {
val site = SiteImpl()
Mockito.`when`(webResourceDataService.createSite(URL)).thenReturn(site)
Mockito.`when`(webResourceDataService.createPage(anyString())).thenReturn(PageImpl())
Mockito.`when`(webResourceDataService.saveOrUpdate(site)).thenReturn(site)
val audit = AuditImpl()
audit.parameterSet = setParameters(depth, respectRobotsTxt)
val crawler = CrawlerImpl(audit, URL, webResourceDataService,
"", "", "", "", emptyList(), politenessDelay)
crawler.run()
calledUrlList.forEach {
Mockito.verify(webResourceDataService, times(1)).createPage(it)
}
neverCalledUrlList.forEach {
Mockito.verify(webResourceDataService, never()).createPage(it)
}
}
private fun setParameters(depth: Int, respectRobotsTxt: Boolean): Set<Parameter> {
val param1 = ParameterImpl()
param1.value = "10"
val paramElem1 = ParameterElementImpl()
paramElem1.parameterElementCode = "MAX_DOCUMENTS"
param1.parameterElement = paramElem1
val param2 = ParameterImpl()
param2.value = depth.toString()
val paramElem2 = ParameterElementImpl()
paramElem2.parameterElementCode = "DEPTH"
param2.parameterElement = paramElem2
val param3 = ParameterImpl()
param3.value = ""
val paramElem3 = ParameterElementImpl()
paramElem3.parameterElementCode = "INCLUSION_REGEXP"
param3.parameterElement = paramElem3
val param4 = ParameterImpl()
param4.value = ""
val paramElem4 = ParameterElementImpl()
paramElem4.parameterElementCode = "EXCLUSION_REGEXP"
param4.parameterElement = paramElem4
val param5 = ParameterImpl()
param5.value = "600"
val paramElem5 = ParameterElementImpl()
paramElem5.parameterElementCode = "MAX_DURATION"
param5.parameterElement = paramElem5
val param6 = ParameterImpl()
param6.value = respectRobotsTxt.toString()
val paramElem6 = ParameterElementImpl()
paramElem6.parameterElementCode = "ROBOTS_TXT_ACTIVATION"
param6.parameterElement = paramElem6
return setOf(param1, param2, param3, param4, param5, param6)
}
}
| agpl-3.0 | ee9ac309c7f74a23fcb41a74e6c07eca | 41.057851 | 136 | 0.715465 | 4.626364 | false | false | false | false |
exponentjs/exponent | android/versioned-abis/expoview-abi44_0_0/src/main/java/abi44_0_0/expo/modules/facedetector/FaceDetectorUtils.kt | 2 | 4640 | package abi44_0_0.expo.modules.facedetector
import android.os.Bundle
import com.google.android.gms.vision.face.Landmark
import com.google.firebase.ml.vision.face.FirebaseVisionFace
import com.google.firebase.ml.vision.common.FirebaseVisionPoint
object FaceDetectorUtils {
@JvmStatic
@JvmOverloads
fun serializeFace(face: FirebaseVisionFace, scaleX: Double = 1.0, scaleY: Double = 1.0): Bundle {
val encodedFace = Bundle().apply {
putInt("faceID", face.trackingId)
putDouble("rollAngle", face.headEulerAngleZ.toDouble())
putDouble("yawAngle", face.headEulerAngleY.toDouble())
if (face.smilingProbability >= 0) {
putDouble("smilingProbability", face.smilingProbability.toDouble())
}
if (face.leftEyeOpenProbability >= 0) {
putDouble("leftEyeOpenProbability", face.leftEyeOpenProbability.toDouble())
}
if (face.rightEyeOpenProbability >= 0) {
putDouble("rightEyeOpenProbability", face.rightEyeOpenProbability.toDouble())
}
LandmarkId.values()
.forEach { id ->
face.getLandmark(id.id)?.let { faceLandmark ->
putBundle(id.name, mapFromPoint(faceLandmark.position, scaleX, scaleY))
}
}
val box = face.boundingBox
val origin = Bundle(2).apply {
putDouble("x", box.left * scaleX)
putDouble("y", box.top * scaleY)
}
val size = Bundle(2).apply {
putDouble("width", (box.right - box.left) * scaleX)
putDouble("height", (box.bottom - box.top) * scaleY)
}
val bounds = Bundle(2).apply {
putBundle("origin", origin)
putBundle("size", size)
}
putBundle("bounds", bounds)
}
return mirrorRollAngle(encodedFace)
}
@JvmStatic
fun rotateFaceX(face: Bundle, sourceWidth: Int, scaleX: Double): Bundle {
val faceBounds = face.getBundle("bounds") as Bundle
val oldOrigin = faceBounds.getBundle("origin")
val mirroredOrigin = positionMirroredHorizontally(oldOrigin, sourceWidth, scaleX)
val translateX = - (faceBounds.getBundle("size") as Bundle).getDouble("width")
val translatedMirroredOrigin = positionTranslatedHorizontally(mirroredOrigin, translateX)
val newBounds = Bundle(faceBounds).apply {
putBundle("origin", translatedMirroredOrigin)
}
face.apply {
LandmarkId.values().forEach { id ->
face.getBundle(id.name)?.let { landmark ->
val mirroredPosition = positionMirroredHorizontally(landmark, sourceWidth, scaleX)
putBundle(id.name, mirroredPosition)
}
}
putBundle("bounds", newBounds)
}
return mirrorYawAngle(mirrorRollAngle(face))
}
private fun mirrorRollAngle(face: Bundle) = face.apply {
putDouble("rollAngle", (-face.getDouble("rollAngle") + 360) % 360)
}
private fun mirrorYawAngle(face: Bundle) = face.apply {
putDouble("yawAngle", (-face.getDouble("yawAngle") + 360) % 360)
}
private fun mapFromPoint(point: FirebaseVisionPoint, scaleX: Double, scaleY: Double) = Bundle().apply {
putDouble("x", point.x * scaleX)
putDouble("y", point.y * scaleY)
}
private fun positionTranslatedHorizontally(position: Bundle, translateX: Double) =
Bundle(position).apply {
putDouble("x", position.getDouble("x") + translateX)
}
private fun positionMirroredHorizontally(position: Bundle?, containerWidth: Int, scaleX: Double) =
Bundle(position).apply {
putDouble("x", valueMirroredHorizontally(position!!.getDouble("x"), containerWidth, scaleX))
}
private fun valueMirroredHorizontally(elementX: Double, containerWidth: Int, scaleX: Double) =
-elementX + containerWidth * scaleX
// All the landmarks reported by Google Mobile Vision in constants' order.
// https://developers.google.com/android/reference/com/google/android/gms/vision/face/Landmark
private enum class LandmarkId(val id: Int, val landmarkName: String) {
BOTTOM_MOUTH(Landmark.BOTTOM_MOUTH, "bottomMouthPosition"),
LEFT_CHEEK(Landmark.LEFT_CHEEK, "leftCheekPosition"),
LEFT_EAR(Landmark.LEFT_EAR, "leftEarPosition"),
LEFT_EAR_TIP(Landmark.LEFT_EAR_TIP, "leftEarTipPosition"),
LEFT_EYE(Landmark.LEFT_EYE, "leftEyePosition"),
LEFT_MOUTH(Landmark.LEFT_MOUTH, "leftMouthPosition"),
NOSE_BASE(Landmark.NOSE_BASE, "noseBasePosition"),
RIGHT_CHEEK(Landmark.RIGHT_CHEEK, "rightCheekPosition"),
RIGHT_EAR(Landmark.RIGHT_EAR, "rightEarPosition"),
RIGHT_EAR_TIP(Landmark.RIGHT_EAR_TIP, "rightEarTipPosition"),
RIGHT_EYE(Landmark.RIGHT_EYE, "rightEyePosition"),
RIGHT_MOUTH(Landmark.RIGHT_MOUTH, "rightMouthPosition");
}
}
| bsd-3-clause | d900bd36f2e3eb3eddbd94e0c65c01ff | 38.322034 | 105 | 0.692888 | 4.124444 | false | false | false | false |
boxtape/boxtape-api | src/main/java/io/boxtape/core/configuration/Configuration.kt | 2 | 2642 | package io.boxtape.core.configuration
import io.boxtape.withPlaceholdersReplaced
import org.apache.commons.lang3.text.StrSubstitutor
/**
* Project configuration -- allows components
* to register properties that will be ultimately written out
* and configure the running application
*
* Not the same as BoxtapeSettings -- which focusses on Boxtape itself
*/
class Configuration {
private val properties: MutableMap<String, String> = hashMapOf()
val vagrantSettings = VagrantSettings()
fun registerPropertyWithDefault(propertyName: String, defaultValue: String) {
properties.put(propertyName, defaultValue)
}
fun registerPropertyWithoutValue(propertyName:String) {
if (!properties.containsKey(propertyName)) {
properties.put(propertyName,"")
}
}
fun registerProperty(property: String) {
// remove ${ and } at either end
val strippedProperty =
if (property.startsWith("\${") && property.endsWith("}")) {
property.substring(2, property.length() - 1)
} else {
property
}
if (strippedProperty.contains(":")) {
val keyValue = strippedProperty.splitBy(":")
registerPropertyWithDefault(keyValue.get(0), keyValue.get(1))
} else {
registerPropertyWithoutValue(strippedProperty)
}
}
fun getValue(property: String): String? {
return properties.get(property).withPlaceholdersReplaced(properties)
}
fun hasProperty(property: String): Boolean {
return properties.contains(property)
}
fun asStrings(): List<String> {
return properties.map { "${it.key}=${it.value.withPlaceholdersReplaced(properties)}" }
}
fun addForwardedPort(hostPort: String, guestPort: String) {
vagrantSettings.addForwardedPort(hostPort, guestPort)
}
fun resolveProperties(source: Map<String, Any>): Map<String,Any> {
fun internalResolveProperties(value:Any):Any {
return when (value) {
is String -> value.withPlaceholdersReplaced(properties)
is List<*> -> value.map { internalResolveProperties(it as Any) }
is Map<*,*> -> resolveProperties(value as Map<String, Any>)
else -> value
}
}
val result:MutableMap<String,Any> = hashMapOf()
val updated = source.map { entry ->
val resolved = internalResolveProperties(entry.value)
Pair(entry.key,resolved)
}
result.plusAssign(updated)
return result
}
}
| apache-2.0 | f7af5aca62ea7bc277422ced4d02c486 | 32.443038 | 94 | 0.63134 | 4.847706 | false | true | false | false |
square/wire | wire-library/wire-tests/src/commonTest/kotlin/com/squareup/wire/TestAllTypesData.kt | 1 | 18480 | /*
* Copyright 2013 Square Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.squareup.wire
import okio.ByteString.Companion.decodeHex
object TestAllTypesData {
const val expectedToString = (
"" +
"AllTypes{opt_int32=111, opt_uint32=112, opt_sint32=113, opt_fixed32=114, opt_sfixed32=115," +
" opt_int64=116, opt_uint64=117, opt_sint64=118, opt_fixed64=119, opt_sfixed64=120, opt_boo" +
"l=true, opt_float=122.0, opt_double=123.0, opt_string=124, opt_bytes=[hex=7de1], opt_neste" +
"d_enum=A, opt_nested_message=NestedMessage{a=999}, req_int32=111, req_uint32=112, req_sint" +
"32=113, req_fixed32=114, req_sfixed32=115, req_int64=116, req_uint64=117, req_sint64=118, " +
"req_fixed64=119, req_sfixed64=120, req_bool=true, req_float=122.0, req_double=123.0, req_s" +
"tring=124, req_bytes=[hex=7de1], req_nested_enum=A, req_nested_message=NestedMessage{a=999" +
"}, rep_int32=[111, 111], rep_uint32=[112, 112], rep_sint32=[113, 113], rep_fixed32=[114, 1" +
"14], rep_sfixed32=[115, 115], rep_int64=[116, 116], rep_uint64=[117, 117], rep_sint64=[118" +
", 118], rep_fixed64=[119, 119], rep_sfixed64=[120, 120], rep_bool=[true, true], rep_float=" +
"[122.0, 122.0], rep_double=[123.0, 123.0], rep_string=[124, 124], rep_bytes=[[hex=7de1], [" +
"hex=7de1]], rep_nested_enum=[A, A], rep_nested_message=[NestedMessage{a=999}, NestedMessag" +
"e{a=999}], pack_int32=[111, 111], pack_uint32=[112, 112], pack_sint32=[113, 113], pack_fix" +
"ed32=[114, 114], pack_sfixed32=[115, 115], pack_int64=[116, 116], pack_uint64=[117, 117], " +
"pack_sint64=[118, 118], pack_fixed64=[119, 119], pack_sfixed64=[120, 120], pack_bool=[true" +
", true], pack_float=[122.0, 122.0], pack_double=[123.0, 123.0], pack_nested_enum=[A, A], e" +
"xt_opt_bool=true, ext_rep_bool=[true, true], ext_pack_bool=[true, true]}"
)
val expectedOutput = (
"" +
// optional
"08" + // tag = 1, type = 0
"6f" + // value = 111
"10" + // tag = 2, type = 0
"70" + // value = 112
"18" + // tag = 3, type = 0
"e201" + // value = 226 (=113 zig-zag)
"25" + // tag = 4, type = 5
"72000000" + // value = 114 (fixed32)
"2d" + // tag = 5, type = 5
"73000000" + // value = 115 (sfixed32)
"30" + // tag = 6, type = 0
"74" + // value = 116
"38" + // tag = 7, type = 0
"75" + // value = 117
"40" + // tag = 8, type = 0
"ec01" + // value = 236 (=118 zigzag)
"49" + // tag = 9, type = 1
"7700000000000000" + // value = 119
"51" + // tag = 10, type = 1
"7800000000000000" + // value = 120
"58" + // tag = 11, type = 0
"01" + // value = 1 (true)
"65" + // tag = 12, type = 5
"0000f442" + // value = 122.0F
"69" + // tag = 13, type = 1
"0000000000c05e40" + // value = 123.0
"72" + // tag = 14, type = 2
"03" + // length = 3
"313234" +
"7a" + // tag = 15, type = 2
"02" + // length = 2
"7de1" + // value = { 125, 225 }
"8001" + // tag = 16, type = 0
"01" + // value = 1
"8a01" + // tag = 17, type = 2
"03" + // length = 3
"08" + // nested tag = 1, type = 0
"e707" + // value = 999
// required
"a806" + // tag = 101, type = 0
"6f" + // value = 111
"b006" + // tag = 102, type = 0
"70" + // value = 112
"b806" + // tag = 103, type = 0
"e201" + // value = 226 (=113 zig-zag)
"c506" + // tag = 104, type = 5
"72000000" + // value = 114 (fixed32)
"cd06" + // tag = 105, type = 5
"73000000" + // value = 115 (sfixed32)
"d006" + // tag = 106, type = 0
"74" + // value = 116
"d806" + // tag = 107, type = 0
"75" + // value = 117
"e006" + // tag = 108, type = 0
"ec01" + // value = 236 (=118 zigzag)
"e906" + // tag = 109, type = 1
"7700000000000000" + // value = 119
"f106" + // tag = 110, type = 1
"7800000000000000" + // value = 120
"f806" + // tag = 111, type = 0
"01" + // value = 1 (true)
"8507" + // tag = 112, type = 5
"0000f442" + // value = 122.0F
"8907" + // tag = 113, type = 1
"0000000000c05e40" + // value = 123.0
"9207" + // tag = 114, type = 2
"03" + // length = 3
"313234" + // value = "124"
"9a07" + // tag = 115, type = 2
"02" + // length = 2
"7de1" + // value = { 125, 225 }
"a007" + // tag = 116, type = 0
"01" + // value = 1
"aa07" + // tag = 117, type = 2
"03" + // length = 3
"08" + // nested tag = 1, type = 0
"e707" + // value = 999
// repeated
"c80c" + // tag = 201, type = 0
"6f" + // value = 111
"c80c" + // tag = 201, type = 0
"6f" + // value = 111
"d00c" + // tag = 202, type = 0
"70" + // value = 112
"d00c" + // tag = 202, type = 0
"70" + // value = 112
"d80c" + // tag = 203, type = 0
"e201" + // value = 226 (=113 zig-zag)
"d80c" + // tag = 203, type = 0
"e201" + // value = 226 (=113 zig-zag)
"e50c" + // tag = 204, type = 5
"72000000" + // value = 114 (fixed32)
"e50c" + // tag = 204, type = 5
"72000000" + // value = 114 (fixed32)
"ed0c" + // tag = 205, type = 5
"73000000" + // value = 115 (sfixed32)
"ed0c" + // tag = 205, type = 5
"73000000" + // value = 115 (sfixed32)
"f00c" + // tag = 206, type = 0
"74" + // value = 116
"f00c" + // tag = 206, type = 0
"74" + // value = 116
"f80c" + // tag = 207, type = 0
"75" + // value = 117
"f80c" + // tag = 207, type = 0
"75" + // value = 117
"800d" + // tag = 208, type = 0
"ec01" + // value = 236 (=118 zigzag)
"800d" + // tag = 208, type = 0
"ec01" + // value = 236 (=118 zigzag)
"890d" + // tag = 209, type = 1
"7700000000000000" + // value = 119
"890d" + // tag = 209, type = 1
"7700000000000000" + // value = 119
"910d" + // tag = 210, type = 1
"7800000000000000" + // value = 120
"910d" + // tag = 210, type = 1
"7800000000000000" + // value = 120
"980d" + // tag = 211, type = 0
"01" + // value = 1 (true)
"980d" + // tag = 211, type = 0
"01" + // value = 1 (true)
"a50d" + // tag = 212, type = 5
"0000f442" + // value = 122.0F
"a50d" + // tag = 212, type = 5
"0000f442" + // value = 122.0F
"a90d" + // tag = 213, type = 1
"0000000000c05e40" + // value = 123.0
"a90d" + // tag = 213, type = 1
"0000000000c05e40" + // value = 123.0
"b20d" + // tag = 214, type = 2
"03" + // length = 3
"313234" + // value = "124"
"b20d" + // tag = 214, type = 2
"03" + // length = 3
"313234" + // value = "124"
"ba0d" + // tag = 215, type = 2
"02" + // length = 2
"7de1" + // value = { 125, 225 }
"ba0d" + // tag = 215, type = 2
"02" + // length = 2
"7de1" + // value = { 125, 225 }
"c00d" + // tag = 216, type = 0
"01" + // value = 1
"c00d" + // tag = 216, type = 0
"01" + // value = 1
"ca0d" + // tag = 217, type = 2
"03" + // length = 3
"08" + // nested tag = 1, type = 0
"e707" + // value = 999
"ca0d" + // tag = 217, type = 2
"03" + // length = 3
"08" + // nested tag = 1, type = 0
"e707" + // value = 999
// packed
"ea12" + // tag = 301, type = 2
"02" + // length = 2
"6f" + // value = 111
"6f" + // value = 111
"f212" + // tag = 302, type = 2
"02" + // length = 2
"70" + // value = 112
"70" + // value = 112
"fa12" + // tag = 303, type = 2
"04" + // length = 4
"e201" + // value = 226 (=113 zig-zag)
"e201" + // value = 226 (=113 zig-zag)
"8213" + // tag = 304, type = 2
"08" + // length = 8
"72000000" + // value = 114 (fixed32)
"72000000" + // value = 114 (fixed32)
"8a13" + // tag = 305, type = 2
"08" + // length = 8
"73000000" + // value = 115 (sfixed32)
"73000000" + // value = 115 (sfixed32)
"9213" + // tag = 306, type = 2
"02" + // length = 2
"74" + // value = 116
"74" + // value = 116
"9a13" + // tag = 307, type = 2
"02" + // length = 2
"75" + // value = 117
"75" + // value = 117
"a213" + // tag = 308, type = 2
"04" + // length = 4
"ec01" + // value = 236 (=118 zigzag)
"ec01" + // value = 236 (=118 zigzag)
"aa13" + // tag = 309, type = 2
"10" + // length = 16
"7700000000000000" + // value = 119
"7700000000000000" + // value = 119
"b213" + // tag = 310, type = 2
"10" + // length = 16
"7800000000000000" + // value = 120
"7800000000000000" + // value = 120
"ba13" + // tag = 311, type = 2
"02" + // length = 2
"01" + // value = 1 (true)
"01" + // value = 1 (true)
"c213" + // tag = 312, type = 2
"08" + // length = 8
"0000f442" + // value = 122.0F
"0000f442" + // value = 122.0F
"ca13" + // tag = 313, type = 2
"10" + // length = 16
"0000000000c05e40" + // value = 123.0
"0000000000c05e40" + // value = 123.0
"e213" + // tag = 316, type = 2
"02" + // length = 2
"01" + // value = 1
"01" + // value = 1
// extensions
"983f" + // tag = 1011, type = 0
"01" + // value = 1 (true)
"b845" + // tag = 1111, type = 0
"01" + // value = 1 (true)
"b845" + // tag = 1111, type = 0
"01" + // value = 1 (true)
"da4b" + // tag = 1211, type = 2
"02" + // length = 2
"01" + // value = 1 (true)
"01" // value = 1 (true)
).decodeHex()
// message with 'packed' fields stored non-packed, must still be readable
val nonPacked = (
"" +
// optional
"08" + // tag = 1, type = 0
"6f" + // value = 111
"10" + // tag = 2, type = 0
"70" + // value = 112
"18" + // tag = 3, type = 0
"e201" + // value = 226 (=113 zig-zag)
"25" + // tag = 4, type = 5
"72000000" + // value = 114 (fixed32)
"2d" + // tag = 5, type = 5
"73000000" + // value = 115 (sfixed32)
"30" + // tag = 6, type = 0
"74" + // value = 116
"38" + // tag = 7, type = 0
"75" + // value = 117
"40" + // tag = 8, type = 0
"ec01" + // value = 236 (=118 zigzag)
"49" + // tag = 9, type = 1
"7700000000000000" + // value = 119
"51" + // tag = 10, type = 1
"7800000000000000" + // value = 120
"58" + // tag = 11, type = 0
"01" + // value = 1 (true)
"65" + // tag = 12, type = 5
"0000f442" + // value = 122.0F
"69" + // tag = 13, type = 1
"0000000000c05e40" + // value = 123.0
"72" + // tag = 14, type = 2
"03" + // length = 3
"313234" +
"7a" + // tag = 15, type = 2
"02" + // length = 2
"7de1" + // value = { 125, 225 }
"8001" + // tag = 16, type = 0
"01" + // value = 1
"8a01" + // tag = 17, type = 2
"03" + // length = 3
"08" + // nested tag = 1, type = 0
"e707" + // value = 999
// required
"a806" + // tag = 101, type = 0
"6f" + // value = 111
"b006" + // tag = 102, type = 0
"70" + // value = 112
"b806" + // tag = 103, type = 0
"e201" + // value = 226 (=113 zig-zag)
"c506" + // tag = 104, type = 5
"72000000" + // value = 114 (fixed32)
"cd06" + // tag = 105, type = 5
"73000000" + // value = 115 (sfixed32)
"d006" + // tag = 106, type = 0
"74" + // value = 116
"d806" + // tag = 107, type = 0
"75" + // value = 117
"e006" + // tag = 108, type = 0
"ec01" + // value = 236 (=118 zigzag)
"e906" + // tag = 109, type = 1
"7700000000000000" + // value = 119
"f106" + // tag = 110, type = 1
"7800000000000000" + // value = 120
"f806" + // tag = 111, type = 0
"01" + // value = 1 (true)
"8507" + // tag = 112, type = 5
"0000f442" + // value = 122.0F
"8907" + // tag = 113, type = 1
"0000000000c05e40" + // value = 123.0
"9207" + // tag = 114, type = 2
"03" + // length = 3
"313234" + // value = "124"
"9a07" + // tag = 115, type = 2
"02" + // length = 2
"7de1" + // value = { 125, 225 }
"a007" + // tag = 116, type = 0
"01" + // value = 1
"aa07" + // tag = 117, type = 2
"03" + // length = 3
"08" + // nested tag = 1, type = 0
"e707" + // value = 999
// repeated
"c80c" + // tag = 201, type = 0
"6f" + // value = 111
"c80c" + // tag = 201, type = 0
"6f" + // value = 111
"d00c" + // tag = 202, type = 0
"70" + // value = 112
"d00c" + // tag = 202, type = 0
"70" + // value = 112
"d80c" + // tag = 203, type = 0
"e201" + // value = 226 (=113 zig-zag)
"d80c" + // tag = 203, type = 0
"e201" + // value = 226 (=113 zig-zag)
"e50c" + // tag = 204, type = 5
"72000000" + // value = 114 (fixed32)
"e50c" + // tag = 204, type = 5
"72000000" + // value = 114 (fixed32)
"ed0c" + // tag = 205, type = 5
"73000000" + // value = 115 (sfixed32)
"ed0c" + // tag = 205, type = 5
"73000000" + // value = 115 (sfixed32)
"f00c" + // tag = 206, type = 0
"74" + // value = 116
"f00c" + // tag = 206, type = 0
"74" + // value = 116
"f80c" + // tag = 207, type = 0
"75" + // value = 117
"f80c" + // tag = 207, type = 0
"75" + // value = 117
"800d" + // tag = 208, type = 0
"ec01" + // value = 236 (=118 zigzag)
"800d" + // tag = 208, type = 0
"ec01" + // value = 236 (=118 zigzag)
"890d" + // tag = 209, type = 1
"7700000000000000" + // value = 119
"890d" + // tag = 209, type = 1
"7700000000000000" + // value = 119
"910d" + // tag = 210, type = 1
"7800000000000000" + // value = 120
"910d" + // tag = 210, type = 1
"7800000000000000" + // value = 120
"980d" + // tag = 211, type = 0
"01" + // value = 1 (true)
"980d" + // tag = 211, type = 0
"01" + // value = 1 (true)
"a50d" + // tag = 212, type = 5
"0000f442" + // value = 122.0F
"a50d" + // tag = 212, type = 5
"0000f442" + // value = 122.0F
"a90d" + // tag = 213, type = 1
"0000000000c05e40" + // value = 123.0
"a90d" + // tag = 213, type = 1
"0000000000c05e40" + // value = 123.0
"b20d" + // tag = 214, type = 2
"03" + // length = 3
"313234" + // value = "124"
"b20d" + // tag = 214, type = 2
"03" + // length = 3
"313234" + // value = "124"
"ba0d" + // tag = 215, type = 2
"02" + // length = 2
"7de1" + // value = { 125, 225 }
"ba0d" + // tag = 215, type = 2
"02" + // length = 2
"7de1" + // value = { 125, 225 }
"c00d" + // tag = 216, type = 0
"01" + // value = 1
"c00d" + // tag = 216, type = 0
"01" + // value = 1
"ca0d" + // tag = 217, type = 2
"03" + // length = 3
"08" + // nested tag = 1, type = 0
"e707" + // value = 999
"ca0d" + // tag = 217, type = 2
"03" + // length = 3
"08" + // nested tag = 1, type = 0
"e707" + // value = 999
// packed
"e812" + // tag = 301, type = 0
"6f" + // value = 111
"e812" + // tag = 301, type = 0
"6f" + // value = 111
"f012" + // tag = 302, type = 0
"70" + // value = 112
"f012" + // tag = 302, type = 0
"70" + // value = 112
"f812" + // tag = 303, type = 0
"e201" + // value = 226 (=113 zig-zag)
"f812" + // tag = 303, type = -
"e201" + // value = 226 (=113 zig-zag)
"8513" + // tag = 304, type = 5
"72000000" + // value = 114 (fixed32)
"8513" + // tag = 304, type = 5
"72000000" + // value = 114 (fixed32)
"8d13" + // tag = 305, type = 5
"73000000" + // value = 115 (sfixed32)
"8d13" + // tag = 305, type = 5
"73000000" + // value = 115 (sfixed32)
"9013" + // tag = 306, type = 0
"74" + // value = 116
"9013" + // tag = 306, type = 0
"74" + // value = 116
"9813" + // tag = 307, type = 0
"75" + // value = 117
"9813" + // tag = 307, type = 0
"75" + // value = 117
"a013" + // tag = 308, type = 0
"ec01" + // value = 236 (=118 zigzag)
"a013" + // tag = 308, type = 0
"ec01" + // value = 236 (=118 zigzag)
"a913" + // tag = 309, type = 0
"7700000000000000" + // value = 119
"a913" + // tag = 309, type = 0
"7700000000000000" + // value = 119
"b113" + // tag = 310, type = 0
"7800000000000000" + // value = 120
"b113" + // tag = 310, type = 0
"7800000000000000" + // value = 120
"b813" + // tag = 311, type = 0
"01" + // value = 1 (true)
"b813" + // tag = 311, type = 0
"01" + // value = 1 (true)
"c513" + // tag = 312, type = 0
"0000f442" + // value = 122.0F
"c513" + // tag = 312, type = 0
"0000f442" + // value = 122.0F
"c913" + // tag = 313, type = 0
"0000000000c05e40" + // value = 123.0
"c913" + // tag = 313, type = 0
"0000000000c05e40" + // value = 123.0
"e013" + // tag = 316, type = 0
"01" + // value = 1
"e013" + // tag = 316, type = 0
"01" + // value = 1
// extension
"983f" + // tag = 1011, type = 0
"01" + // value = 1 (true)
"b845" + // tag = 1111, type = 0
"01" + // value = 1 (true)
"b845" + // tag = 1111, type = 0
"01" + // value = 1 (true)
"d84b" + // tag = 1211, type = 0
"01" + // value = 1 (true)
"d84b" + // tag = 1211, type = 0
"01" // value = 1 (true)
).decodeHex()
}
| apache-2.0 | c77c5db926fdb0a6761e82a770417ab8 | 34.953307 | 100 | 0.448701 | 2.907489 | false | false | false | false |
Maccimo/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/rename/KotlinVariableInplaceRenameHandler.kt | 3 | 3286 | // 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.refactoring.rename
import com.intellij.openapi.editor.Editor
import com.intellij.psi.*
import com.intellij.refactoring.RefactoringActionHandler
import com.intellij.refactoring.rename.inplace.VariableInplaceRenameHandler
import com.intellij.refactoring.rename.inplace.VariableInplaceRenamer
import org.jetbrains.kotlin.idea.base.psi.unquoteKotlinIdentifier
import org.jetbrains.kotlin.psi.*
open class KotlinVariableInplaceRenameHandler : VariableInplaceRenameHandler() {
companion object {
fun isInplaceRenameAvailable(element: PsiElement): Boolean {
when (element) {
is KtTypeParameter -> return true
is KtDestructuringDeclarationEntry -> return true
is KtParameter -> {
val parent = element.parent
if (parent is KtForExpression) {
return true
}
if (parent is KtParameterList) {
val grandparent = parent.parent
return grandparent is KtCatchClause || grandparent is KtFunctionLiteral
}
}
is KtLabeledExpression, is KtImportAlias -> return true
}
return false
}
}
protected open class RenamerImpl : VariableInplaceRenamer {
constructor(elementToRename: PsiNamedElement, editor: Editor) : super(elementToRename, editor)
constructor(
elementToRename: PsiNamedElement,
editor: Editor,
currentName: String,
oldName: String
) : super(elementToRename, editor, editor.project!!, currentName, oldName)
override fun acceptReference(reference: PsiReference): Boolean {
val refElement = reference.element
val textRange = reference.rangeInElement
val referenceText = refElement.text.substring(textRange.startOffset, textRange.endOffset).unquoteKotlinIdentifier()
return referenceText == myElementToRename.name
}
override fun startsOnTheSameElement(handler: RefactoringActionHandler?, element: PsiElement?): Boolean {
return variable == element && (handler is VariableInplaceRenameHandler || handler is KotlinRenameDispatcherHandler)
}
override fun createInplaceRenamerToRestart(variable: PsiNamedElement, editor: Editor, initialName: String): VariableInplaceRenamer {
return RenamerImpl(variable, editor, initialName, myOldName)
}
}
override fun createRenamer(elementToRename: PsiElement, editor: Editor): VariableInplaceRenamer? {
val currentElementToRename = elementToRename as PsiNameIdentifierOwner
val currentName = currentElementToRename.nameIdentifier?.text ?: ""
return RenamerImpl(currentElementToRename, editor, currentName, currentName)
}
public override fun isAvailable(element: PsiElement?, editor: Editor, file: PsiFile) =
editor.settings.isVariableInplaceRenameEnabled && element != null && isInplaceRenameAvailable(element)
} | apache-2.0 | a39aa83bc20b291f72d35373303568cb | 47.338235 | 158 | 0.685027 | 5.920721 | false | false | false | false |
Maccimo/intellij-community | platform/workspaceModel/storage/testEntities/gen/com/intellij/workspaceModel/storage/entities/test/api/MainEntityImpl.kt | 2 | 5622 | package com.intellij.workspaceModel.storage.entities.test.api
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.ModifiableReferableWorkspaceEntity
import com.intellij.workspaceModel.storage.ModifiableWorkspaceEntity
import com.intellij.workspaceModel.storage.MutableEntityStorage
import com.intellij.workspaceModel.storage.WorkspaceEntity
import com.intellij.workspaceModel.storage.impl.ConnectionId
import com.intellij.workspaceModel.storage.impl.ModifiableWorkspaceEntityBase
import com.intellij.workspaceModel.storage.impl.WorkspaceEntityBase
import com.intellij.workspaceModel.storage.impl.WorkspaceEntityData
import com.intellij.workspaceModel.storage.referrersx
import org.jetbrains.deft.ObjBuilder
import org.jetbrains.deft.Type
import org.jetbrains.deft.annotations.Child
@GeneratedCodeApiVersion(1)
@GeneratedCodeImplVersion(1)
open class MainEntityImpl: MainEntity, WorkspaceEntityBase() {
companion object {
val connections = listOf<ConnectionId>(
)
}
@JvmField var _x: String? = null
override val x: String
get() = _x!!
override fun connectionIdList(): List<ConnectionId> {
return connections
}
class Builder(val result: MainEntityData?): ModifiableWorkspaceEntityBase<MainEntity>(), MainEntity.Builder {
constructor(): this(MainEntityData())
override fun applyToBuilder(builder: MutableEntityStorage) {
if (this.diff != null) {
if (existsInBuilder(builder)) {
this.diff = builder
return
}
else {
error("Entity MainEntity is already created in a different builder")
}
}
this.diff = builder
this.snapshot = builder
addToBuilder()
this.id = getEntityData().createEntityId()
// Process linked entities that are connected without a builder
processLinkedEntities(builder)
checkInitialization() // TODO uncomment and check failed tests
}
fun checkInitialization() {
val _diff = diff
if (!getEntityData().isXInitialized()) {
error("Field MainEntity#x should be initialized")
}
if (!getEntityData().isEntitySourceInitialized()) {
error("Field MainEntity#entitySource should be initialized")
}
}
override fun connectionIdList(): List<ConnectionId> {
return connections
}
override var x: String
get() = getEntityData().x
set(value) {
checkModificationAllowed()
getEntityData().x = value
changedProperty.add("x")
}
override var entitySource: EntitySource
get() = getEntityData().entitySource
set(value) {
checkModificationAllowed()
getEntityData().entitySource = value
changedProperty.add("entitySource")
}
override fun getEntityData(): MainEntityData = result ?: super.getEntityData() as MainEntityData
override fun getEntityClass(): Class<MainEntity> = MainEntity::class.java
}
}
class MainEntityData : WorkspaceEntityData<MainEntity>() {
lateinit var x: String
fun isXInitialized(): Boolean = ::x.isInitialized
override fun wrapAsModifiable(diff: MutableEntityStorage): ModifiableWorkspaceEntity<MainEntity> {
val modifiable = MainEntityImpl.Builder(null)
modifiable.allowModifications {
modifiable.diff = diff
modifiable.snapshot = diff
modifiable.id = createEntityId()
modifiable.entitySource = this.entitySource
}
modifiable.changedProperty.clear()
return modifiable
}
override fun createEntity(snapshot: EntityStorage): MainEntity {
val entity = MainEntityImpl()
entity._x = x
entity.entitySource = entitySource
entity.snapshot = snapshot
entity.id = createEntityId()
return entity
}
override fun getEntityInterface(): Class<out WorkspaceEntity> {
return MainEntity::class.java
}
override fun serialize(ser: EntityInformation.Serializer) {
}
override fun deserialize(de: EntityInformation.Deserializer) {
}
override fun equals(other: Any?): Boolean {
if (other == null) return false
if (this::class != other::class) return false
other as MainEntityData
if (this.x != other.x) return false
if (this.entitySource != other.entitySource) return false
return true
}
override fun equalsIgnoringEntitySource(other: Any?): Boolean {
if (other == null) return false
if (this::class != other::class) return false
other as MainEntityData
if (this.x != other.x) return false
return true
}
override fun hashCode(): Int {
var result = entitySource.hashCode()
result = 31 * result + x.hashCode()
return result
}
} | apache-2.0 | 5a112619ff2aca7e7669ffcb7aa8ec59 | 33.078788 | 113 | 0.640697 | 5.862357 | false | false | false | false |
JStege1206/AdventOfCode | aoc-2016/src/main/kotlin/nl/jstege/adventofcode/aoc2016/days/Day01.kt | 1 | 2131 | package nl.jstege.adventofcode.aoc2016.days
import nl.jstege.adventofcode.aoccommon.days.Day
import nl.jstege.adventofcode.aoccommon.utils.Direction
import nl.jstege.adventofcode.aoccommon.utils.Point
import nl.jstege.adventofcode.aoccommon.utils.extensions.scan
import kotlin.reflect.KProperty1
/**
*
* @author Jelle Stege
*/
class Day01 : Day(title = "No Time for a Taxicab") {
override fun first(input: Sequence<String>): Any {
var dir = Direction.NORTH
return input
.first()
.parse()
.fold(Point.ZERO_ZERO) { p, (turn, steps) ->
dir = dir.let(turn.directionMod)
p.moveDirection(dir, steps)
}
.manhattan(Point.ZERO_ZERO)
}
override fun second(input: Sequence<String>): Any {
var dir = Direction.NORTH
var coordinate = Point.ZERO_ZERO
val visited = mutableSetOf(coordinate)
input.first().parse().forEach { (turn, steps) ->
dir = dir.let(turn.directionMod)
val first = coordinate.moveDirection(dir)
val last = coordinate.moveDirection(dir, steps)
val xs = if (last.x < first.x) first.x downTo last.x else first.x..last.x
val ys = if (last.y < first.y) first.y downTo last.y else first.y..last.y
Point.of(xs, ys).forEach {
coordinate = it
if (coordinate in visited) return coordinate.manhattan(Point.ZERO_ZERO)
visited += coordinate
}
}
throw IllegalStateException("No answer found.")
}
private fun String.parse(): List<Instruction> = this.split(", ").map {
Instruction(Turn.parse(it.substring(0, 1)), it.substring(1).toInt())
}
private data class Instruction(val turn: Turn, val steps: Int)
private enum class Turn(val directionMod: KProperty1<Direction, Direction>) {
LEFT(Direction::left), RIGHT(Direction::right);
companion object {
fun parse(v: String) = when (v) {
"L" -> LEFT
else -> RIGHT
}
}
}
}
| mit | 5291f170f115447731a45c95aabbe285 | 31.784615 | 87 | 0.595026 | 4.137864 | false | false | false | false |
fcostaa/kotlin-rxjava-android | library/cache/src/main/kotlin/com/github/felipehjcosta/marvelapp/cache/data/StoryListRelations.kt | 1 | 439 | package com.github.felipehjcosta.marvelapp.cache.data
import androidx.room.Embedded
import androidx.room.Relation
data class StoryListRelations(
@Embedded
var storyListEntity: StoryListEntity = StoryListEntity(),
@Relation(
parentColumn = "story_list_id",
entityColumn = "summary_story_list_id",
entity = SummaryEntity::class
)
var storyListSummary: List<SummaryEntity> = mutableListOf()
)
| mit | 90ae81a450cc43126c2855e3aa221978 | 23.388889 | 63 | 0.719818 | 4.303922 | false | false | false | false |
ligi/PassAndroid | android/src/main/java/org/ligi/passandroid/ui/quirk_fix/USAirwaysLoadActivity.kt | 1 | 1235 | package org.ligi.passandroid.ui.quirk_fix
import android.content.Intent
import android.os.Bundle
import androidx.core.net.toUri
import androidx.fragment.app.commit
import org.ligi.passandroid.ui.AlertFragment
import org.ligi.passandroid.ui.PassAndroidActivity
import org.ligi.passandroid.ui.PassImportActivity
class USAirwaysLoadActivity : PassAndroidActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val data = intent.data
if (data == null || "$data".indexOf("/") == -1){
val alert = AlertFragment()
supportFragmentManager.commit { add(alert,"AlertFrag") }
return
}
val url = "$data".removeSuffix("/") ?: ""
val split = url.split("/".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()
val passId = split[split.size - 2] + "/" + split[split.size - 1]
val redirectUrl = "http://prod.wap.ncrwebhost.mobi/mobiqa/wap/$passId/passbook"
tracker.trackEvent("quirk_fix", "redirect", "usairways", null)
val intent = Intent(this, PassImportActivity::class.java)
intent.data = redirectUrl.toUri()
startActivity(intent)
finish()
}
}
| gpl-3.0 | 3c40f78973bdbe7fff5d07c1ff139ee4 | 32.378378 | 90 | 0.663968 | 4.0625 | false | false | false | false |
blindpirate/gradle | .teamcity/src/main/kotlin/promotion/PublishNightlySnapshot.kt | 1 | 1998 | /*
* Copyright 2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package promotion
import common.VersionedSettingsBranch
import configurations.branchFilter
import jetbrains.buildServer.configs.kotlin.v2019_2.triggers.schedule
import vcsroots.gradlePromotionBranches
class PublishNightlySnapshot(branch: VersionedSettingsBranch) : PublishGradleDistributionBothSteps(
promotedBranch = branch.branchName,
prepTask = branch.prepNightlyTaskName(),
step2TargetTask = branch.promoteNightlyTaskName(),
triggerName = "ReadyforNightly",
vcsRootId = gradlePromotionBranches
) {
init {
id("Promotion_Nightly")
name = "Nightly Snapshot"
description = "Promotes the latest successful changes on '${branch.branchName}' from Ready for Nightly as a new nightly snapshot"
triggers {
branch.triggeredHour()?.apply {
schedule {
schedulingPolicy = daily {
this.hour = this@apply
}
triggerBuild = always()
withPendingChangesOnly = true
enabled = branch.enableTriggers
branchFilter = branch.branchFilter()
}
}
}
}
}
// Avoid two jobs running at the same time and causing troubles
private fun VersionedSettingsBranch.triggeredHour() = when {
isMaster -> 0
isRelease -> 1
else -> null
}
| apache-2.0 | 5445a46359192b094efccfadd26665a3 | 34.052632 | 137 | 0.670671 | 5.020101 | false | false | false | false |
wordpress-mobile/WordPress-Android | WordPress/src/main/java/org/wordpress/android/ui/stats/refresh/lists/sections/viewholders/GuideCardViewHolder.kt | 1 | 2726 | package org.wordpress.android.ui.stats.refresh.lists.sections.viewholders
import android.content.Context
import android.graphics.Typeface
import android.text.Spannable
import android.text.SpannableString
import android.text.TextPaint
import android.text.method.LinkMovementMethod
import android.text.style.ClickableSpan
import android.text.style.StyleSpan
import android.view.View
import android.view.ViewGroup
import org.wordpress.android.R
import org.wordpress.android.databinding.StatsBlockListGuideCardBinding
import org.wordpress.android.ui.stats.refresh.lists.sections.BlockListItem.ListItemGuideCard
import org.wordpress.android.util.extensions.getColorFromAttribute
import org.wordpress.android.util.extensions.viewBinding
class GuideCardViewHolder(
val parent: ViewGroup,
val binding: StatsBlockListGuideCardBinding = parent.viewBinding(StatsBlockListGuideCardBinding::inflate)
) : BlockListItemViewHolder(binding.root) {
fun bind(
item: ListItemGuideCard
) = with(binding) {
val spannableString = SpannableString(item.text)
item.links?.forEach { link ->
link.link?.let {
spannableString.withClickableSpan(root.context, it) {
link.navigationAction.click()
}
}
}
item.bolds?.forEach { bold ->
spannableString.withBoldSpan(bold)
}
guideMessage.movementMethod = LinkMovementMethod.getInstance()
guideMessage.text = spannableString
}
}
private fun SpannableString.withClickableSpan(
context: Context,
clickablePart: String,
onClickListener: (Context) -> Unit
): SpannableString {
val clickableSpan = object : ClickableSpan() {
override fun onClick(widget: View) {
widget.context?.let { onClickListener.invoke(it) }
}
override fun updateDrawState(ds: TextPaint) {
ds.color = context.getColorFromAttribute(R.attr.colorPrimary)
ds.typeface = Typeface.create(
Typeface.DEFAULT_BOLD,
Typeface.NORMAL
)
ds.isUnderlineText = false
}
}
val clickablePartStart = indexOf(clickablePart)
setSpan(
clickableSpan,
clickablePartStart,
clickablePartStart + clickablePart.length,
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
)
return this
}
private fun SpannableString.withBoldSpan(boldPart: String): SpannableString {
val boldPartIndex = indexOf(boldPart)
setSpan(
StyleSpan(Typeface.BOLD),
boldPartIndex,
boldPartIndex + boldPart.length,
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
)
return this
}
| gpl-2.0 | 244dd92a9838b5982715a4f9847b055b | 33.075 | 109 | 0.689288 | 4.876565 | false | false | false | false |
koleno/SunWidget | app/src/main/kotlin/xyz/koleno/sunwidget/widget/SunWidgetProvider.kt | 1 | 4273 | package xyz.koleno.sunwidget.widget
import android.app.PendingIntent
import android.appwidget.AppWidgetManager
import android.appwidget.AppWidgetProvider
import android.content.Context
import android.content.Intent
import android.widget.RemoteViews
import androidx.preference.PreferenceManager
import xyz.koleno.sunwidget.PrefHelper
import xyz.koleno.sunwidget.R
/**
* Broadcast receiver that controls the widgets
* @author Dusan Koleno
*/
class SunWidgetProvider : AppWidgetProvider() {
companion object {
const val ACTION_NO_CONNECTION = "actionNoConnection" // no internet connection notification
const val ACTION_UPDATE_WIDGETS = "actionUpdateViews" // sent by update service to update views with new data
const val ACTION_RUN_UPDATE = "actionRunUpdate" // generated after refresh button click to start update service
}
/**
* Called by the system when widgets need to be updated
*/
override fun onUpdate(context: Context, appWidgetManager: AppWidgetManager, appWidgetIds: IntArray) {
val prefs = PrefHelper(PreferenceManager.getDefaultSharedPreferences(context))
// start service if user's location is set
if (prefs.hasLocation()) {
updateWidgetsFromSaved(context, appWidgetIds) // first get saved data
UpdateService.enqueueWork(context, appWidgetIds)
} else {
// notify user about missing location
updateWidgets(context, appWidgetIds, context.resources.getString(R.string.no_location), context.resources.getString(R.string.no_location))
}
}
/**
* Custom actions used to handle various widget updates
*/
override fun onReceive(context: Context, intent: Intent) {
val prefs = PrefHelper(PreferenceManager.getDefaultSharedPreferences(context))
val widgetIds = intent.getIntArrayExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS)
?: return // stop if no widget ids
when (intent.action) {
ACTION_NO_CONNECTION -> {
updateWidgets(context, widgetIds, context.getString(R.string.no_internet), context.getString(R.string.no_internet_try))
}
ACTION_UPDATE_WIDGETS -> {
updateWidgetsFromSaved(context, widgetIds)
}
ACTION_RUN_UPDATE -> {
if (!prefs.hasTimes()) { // no previous times saved, show loading
updateWidgets(context, widgetIds, context.getString(R.string.loading), context.getString(R.string.loading))
}
// start the update service
UpdateService.enqueueWork(context, widgetIds)
}
}
super.onReceive(context, intent)
}
/**
* Generates widget update intent for the refresh button click
*/
private fun generateUpdateIntent(context: Context, appWidgetIds: IntArray): PendingIntent {
val intent = Intent(context, javaClass)
intent.action = ACTION_RUN_UPDATE
intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, appWidgetIds)
return PendingIntent.getBroadcast(context, 0, intent, 0)
}
/**
* Updates widgets with given data
*/
private fun updateWidgets(context: Context, appWidgetIds: IntArray, sunriseText: String, sunsetText: String) {
val manager = AppWidgetManager.getInstance(context.applicationContext)
val remoteViews = RemoteViews(context.applicationContext.packageName, R.layout.sunwidget)
remoteViews.setOnClickPendingIntent(R.id.button_refresh, generateUpdateIntent(context, appWidgetIds))
for (widgetId in appWidgetIds) {
remoteViews.setTextViewText(R.id.text_sunrise_value, sunriseText)
remoteViews.setTextViewText(R.id.text_sunset_value, sunsetText)
manager.updateAppWidget(widgetId, remoteViews)
}
}
/**
* Updates widgets from saved data
*/
private fun updateWidgetsFromSaved(context: Context, appWidgetIds: IntArray) {
val prefs = PrefHelper(PreferenceManager.getDefaultSharedPreferences(context))
if (prefs.hasTimes()) {
val data = prefs.loadTimes()
updateWidgets(context, appWidgetIds, data.sunrise, data.sunset)
}
}
}
| gpl-2.0 | 244811a8c0c79ad8580722360095436e | 40.086538 | 150 | 0.683595 | 5.027059 | false | false | false | false |
mdaniel/intellij-community | platform/vcs-impl/src/com/intellij/openapi/vcs/changes/committed/EditSourceFromChangesBrowserAction.kt | 5 | 1880 | // 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.openapi.vcs.changes.committed
import com.intellij.icons.AllIcons
import com.intellij.ide.actions.EditSourceAction
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.CommonDataKeys.PROJECT
import com.intellij.openapi.actionSystem.DataContext
import com.intellij.openapi.actionSystem.PlatformCoreDataKeys
import com.intellij.openapi.vcs.VcsBundle
import com.intellij.openapi.vcs.VcsDataKeys.SELECTED_CHANGES
import com.intellij.openapi.vcs.changes.ChangesUtil.getNavigatableArray
import com.intellij.openapi.vcs.changes.ChangesUtil.iterateFiles
import com.intellij.openapi.vcs.changes.committed.CommittedChangesBrowserUseCase.IN_AIR
import com.intellij.openapi.vcs.changes.ui.ChangesBrowserBase
import com.intellij.pom.Navigatable
internal class EditSourceFromChangesBrowserAction : EditSourceAction() {
override fun update(e: AnActionEvent) {
super.update(e)
e.presentation.apply {
icon = AllIcons.Actions.EditSource
text = VcsBundle.message("edit.source.action.text")
val isModalContext = e.getData(PlatformCoreDataKeys.IS_MODAL_CONTEXT) == true
val changesBrowser = e.getData(ChangesBrowserBase.DATA_KEY)
isVisible = isVisible && changesBrowser != null
isEnabled = isEnabled && changesBrowser != null &&
!isModalContext &&
e.getData(CommittedChangesBrowserUseCase.DATA_KEY) != IN_AIR
}
}
override fun getNavigatables(dataContext: DataContext): Array<Navigatable>? {
val project = PROJECT.getData(dataContext) ?: return null
val changes = SELECTED_CHANGES.getData(dataContext) ?: return null
return getNavigatableArray(project, iterateFiles(changes.asList()))
}
} | apache-2.0 | 25ac88e72acfdaf273153ca56e93c695 | 44.878049 | 140 | 0.780851 | 4.497608 | false | false | false | false |
mdaniel/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/dfa/KtVariableDescriptor.kt | 1 | 9445 | // 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.dfa
import com.intellij.codeInspection.dataFlow.jvm.descriptors.JvmVariableDescriptor
import com.intellij.codeInspection.dataFlow.types.DfType
import com.intellij.codeInspection.dataFlow.value.DfaValueFactory
import com.intellij.codeInspection.dataFlow.value.DfaVariableValue
import com.intellij.psi.PsiElement
import com.intellij.psi.util.CachedValuesManager
import com.intellij.psi.util.PsiTreeUtil
import org.jetbrains.kotlin.builtins.getValueParameterTypesFromFunctionType
import org.jetbrains.kotlin.descriptors.DeclarationDescriptorWithSource
import org.jetbrains.kotlin.descriptors.ValueParameterDescriptor
import org.jetbrains.kotlin.idea.caches.resolve.resolveToDescriptorIfAny
import org.jetbrains.kotlin.idea.core.resolveType
import org.jetbrains.kotlin.idea.refactoring.move.moveMethod.type
import org.jetbrains.kotlin.idea.references.mainReference
import org.jetbrains.kotlin.idea.references.readWriteAccess
import org.jetbrains.kotlin.idea.references.resolveMainReferenceToDescriptors
import org.jetbrains.kotlin.idea.util.findAnnotation
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.containingClass
import org.jetbrains.kotlin.psi.psiUtil.containingClassOrObject
import org.jetbrains.kotlin.psi.psiUtil.isExtensionDeclaration
import org.jetbrains.kotlin.resolve.jvm.annotations.VOLATILE_ANNOTATION_FQ_NAME
import org.jetbrains.kotlin.resolve.source.KotlinSourceElement
import org.jetbrains.kotlin.types.KotlinType
class KtVariableDescriptor(val variable: KtCallableDeclaration) : JvmVariableDescriptor() {
val stable: Boolean = calculateStable()
private fun calculateStable(): Boolean {
if (variable is KtParameter && variable.isMutable) return false
if (variable !is KtProperty || !variable.isVar) return true
if (!variable.isLocal) return false
return !getVariablesChangedInNestedFunctions(variable.parent).contains(variable)
}
private fun getVariablesChangedInNestedFunctions(parent: PsiElement): Set<KtProperty> =
CachedValuesManager.getProjectPsiDependentCache(parent) { scope ->
val result = hashSetOf<KtProperty>()
PsiTreeUtil.processElements(scope) { e ->
if (e is KtSimpleNameExpression && e.readWriteAccess(false).isWrite) {
val target = e.mainReference.resolve()
if (target is KtProperty && target.isLocal && PsiTreeUtil.isAncestor(parent, target, true)) {
var parentScope : KtFunction?
var context = e
while(true) {
parentScope = PsiTreeUtil.getParentOfType(context, KtFunction::class.java)
val maybeLambda = parentScope?.parent as? KtLambdaExpression
val maybeCall = (maybeLambda?.parent as? KtLambdaArgument)?.parent as? KtCallExpression
if (maybeCall != null && getInlineableLambda(maybeCall)?.lambda == maybeLambda) {
context = maybeCall
continue
}
break
}
if (parentScope != null && PsiTreeUtil.isAncestor(parent, parentScope, true)) {
result.add(target)
}
}
}
return@processElements true
}
return@getProjectPsiDependentCache result
}
override fun isStable(): Boolean = stable
override fun canBeCapturedInClosure(): Boolean {
if (variable is KtParameter && variable.isMutable) return false
return variable !is KtProperty || !variable.isVar
}
override fun getPsiElement(): KtCallableDeclaration = variable
override fun getDfType(qualifier: DfaVariableValue?): DfType = variable.type().toDfType()
override fun equals(other: Any?): Boolean = other is KtVariableDescriptor && other.variable == variable
override fun hashCode(): Int = variable.hashCode()
override fun toString(): String = variable.name ?: "<unknown>"
companion object {
fun getSingleLambdaParameter(factory: DfaValueFactory, lambda: KtLambdaExpression): DfaVariableValue? {
val parameters = lambda.valueParameters
if (parameters.size > 1) return null
if (parameters.size == 1) {
return if (parameters[0].destructuringDeclaration == null)
factory.varFactory.createVariableValue(KtVariableDescriptor(parameters[0]))
else null
}
val kotlinType = lambda.resolveType()?.getValueParameterTypesFromFunctionType()?.singleOrNull()?.type ?: return null
return factory.varFactory.createVariableValue(KtItVariableDescriptor(lambda.functionLiteral, kotlinType))
}
fun createFromQualified(factory: DfaValueFactory, expr: KtExpression?): DfaVariableValue? {
var selector = expr
while (selector is KtQualifiedExpression) {
selector = selector.selectorExpression
}
return createFromSimpleName(factory, selector)
}
fun createFromSimpleName(factory: DfaValueFactory, expr: KtExpression?): DfaVariableValue? {
val varFactory = factory.varFactory
if (expr is KtSimpleNameExpression) {
val target = expr.mainReference.resolve()
if (target is KtCallableDeclaration) {
if (target is KtParameter && target.ownerFunction !is KtPrimaryConstructor ||
target is KtProperty && target.isLocal ||
target is KtDestructuringDeclarationEntry
) {
return varFactory.createVariableValue(KtVariableDescriptor(target))
}
if (isTrackableProperty(target)) {
val parent = expr.parent
var qualifier: DfaVariableValue? = null
if (target.parent is KtClassBody && target.parent.parent is KtObjectDeclaration) {
// property in object: singleton, can track
return varFactory.createVariableValue(KtVariableDescriptor(target), null)
}
if (parent is KtQualifiedExpression && parent.selectorExpression == expr) {
val receiver = parent.receiverExpression
qualifier = createFromSimpleName(factory, receiver)
} else {
if (target.parent is KtFile) {
// top-level declaration
return varFactory.createVariableValue(KtVariableDescriptor(target), null)
}
val classOrObject = target.containingClassOrObject?.resolveToDescriptorIfAny()
if (classOrObject != null) {
val dfType = classOrObject.defaultType.toDfType()
qualifier = varFactory.createVariableValue(KtThisDescriptor(classOrObject, dfType))
}
}
if (qualifier != null) {
return varFactory.createVariableValue(KtVariableDescriptor(target), qualifier)
}
}
}
if (expr.textMatches("it")) {
val descriptor = expr.resolveMainReferenceToDescriptors().singleOrNull()
if (descriptor is ValueParameterDescriptor) {
val fn = ((descriptor.containingDeclaration as? DeclarationDescriptorWithSource)?.source as? KotlinSourceElement)?.psi
if (fn != null) {
val type = descriptor.type
return varFactory.createVariableValue(KtItVariableDescriptor(fn, type))
}
}
}
}
return null
}
private fun isTrackableProperty(target: PsiElement?) =
target is KtParameter && target.ownerFunction is KtPrimaryConstructor ||
target is KtProperty && !target.hasDelegate() && target.getter == null && target.setter == null &&
!target.hasModifier(KtTokens.ABSTRACT_KEYWORD) &&
target.findAnnotation(VOLATILE_ANNOTATION_FQ_NAME) == null &&
target.containingClass()?.isInterface() != true &&
!target.isExtensionDeclaration()
}
}
class KtItVariableDescriptor(val lambda: KtElement, val type: KotlinType): JvmVariableDescriptor() {
override fun getDfType(qualifier: DfaVariableValue?): DfType = type.toDfType()
override fun isStable(): Boolean = true
override fun equals(other: Any?): Boolean = other is KtItVariableDescriptor && other.lambda == lambda
override fun hashCode(): Int = lambda.hashCode()
override fun toString(): String = "it"
}
| apache-2.0 | da53f0c5d2ad93f5f68e0dc16d862bad | 53.595376 | 158 | 0.624987 | 6.081777 | false | false | false | false |
GunoH/intellij-community | platform/platform-impl/src/com/intellij/ui/colorpicker/SliderComponent.kt | 2 | 7328 | /*
* Copyright (C) 2018 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.ui.colorpicker
import com.intellij.ui.JBColor
import com.intellij.util.containers.ContainerUtil
import com.intellij.util.ui.JBUI
import com.intellij.util.ui.UIUtil
import java.awt.*
import java.awt.event.*
import javax.swing.AbstractAction
import javax.swing.JComponent
import javax.swing.KeyStroke
import kotlin.math.max
private val DEFAULT_HORIZONTAL_PADDING = JBUI.scale(5)
private val DEFAULT_VERTICAL_PADDING = JBUI.scale(5)
private val KNOB_COLOR = Color(255, 255, 255)
private val KNOB_BORDER_COLOR = JBColor(Color(100, 100, 100), Color(64, 64, 64))
private val KNOB_BORDER_STROKE = BasicStroke(1.5f)
private const val KNOB_WIDTH = 5
private const val KNOB_CORNER_ARC = 5
private const val FOCUS_BORDER_CORNER_ARC = 5
private const val FOCUS_BORDER_WIDTH = 3
private const val ACTION_SLIDE_LEFT = "actionSlideLeft"
private const val ACTION_SLIDE_LEFT_STEP = "actionSlideLeftStep"
private const val ACTION_SLIDE_RIGHT = "actionSlideRight"
private const val ACTION_SLIDE_RIGHT_STEP = "actionSlideRightStep"
abstract class SliderComponent<T: Number>(initialValue: T) : JComponent() {
protected val leftPadding = DEFAULT_HORIZONTAL_PADDING
protected val rightPadding = DEFAULT_HORIZONTAL_PADDING
protected val topPadding = DEFAULT_VERTICAL_PADDING
protected val bottomPadding = DEFAULT_VERTICAL_PADDING
private var _knobPosition: Int = 0
private var knobPosition: Int
get() = _knobPosition
set(newPointerValue) {
_knobPosition = newPointerValue
_value = knobPositionToValue(newPointerValue)
}
private var _value: T = initialValue
var value: T
get() = _value
set(newValue) {
_value = newValue
_knobPosition = valueToKnobPosition(newValue)
}
private val polygonToDraw = Polygon()
private val listeners = ContainerUtil.createLockFreeCopyOnWriteList<(T) -> Unit>()
/**
* @return size of slider, must be positive value or zero.
*/
val sliderWidth get() = max(0, width - leftPadding - rightPadding)
init {
this.addMouseMotionListener(object : MouseAdapter() {
override fun mouseDragged(e: MouseEvent) {
processMouse(e)
e.consume()
}
})
this.addMouseListener(object : MouseAdapter() {
override fun mousePressed(e: MouseEvent) {
processMouse(e)
e.consume()
}
})
addMouseWheelListener { e ->
runAndUpdateIfNeeded {
value = slide(-e.preciseWheelRotation.toInt())
}
e.consume()
}
this.addFocusListener(object : FocusAdapter() {
override fun focusGained(e: FocusEvent?) {
repaint()
}
override fun focusLost(e: FocusEvent?) {
repaint()
}
})
this.addComponentListener(object : ComponentAdapter() {
override fun componentResized(e: ComponentEvent?) {
repaint()
}
})
with (actionMap) {
put(ACTION_SLIDE_LEFT, object : AbstractAction() {
override fun actionPerformed(e: ActionEvent) = runAndUpdateIfNeeded { doSlide(-1) }
})
put(ACTION_SLIDE_LEFT_STEP, object : AbstractAction() {
override fun actionPerformed(e: ActionEvent) = runAndUpdateIfNeeded { doSlide(-10) }
})
put(ACTION_SLIDE_RIGHT, object : AbstractAction() {
override fun actionPerformed(e: ActionEvent) = runAndUpdateIfNeeded { doSlide(1) }
})
put(ACTION_SLIDE_RIGHT_STEP, object : AbstractAction() {
override fun actionPerformed(e: ActionEvent) = runAndUpdateIfNeeded { doSlide(10) }
})
}
with (getInputMap(WHEN_FOCUSED)) {
put(KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, 0), ACTION_SLIDE_LEFT)
put(KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, InputEvent.SHIFT_DOWN_MASK), ACTION_SLIDE_LEFT_STEP)
put(KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, 0), ACTION_SLIDE_RIGHT)
put(KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, KeyEvent.SHIFT_DOWN_MASK), ACTION_SLIDE_RIGHT_STEP)
}
}
/**
* Helper function to execute the code and check if needs to invoke [repaint] and/or [fireValueChanged]
*/
private fun runAndUpdateIfNeeded(task: () -> Unit) {
val oldValue = value
task()
repaint()
if (oldValue != value) {
fireValueChanged()
}
}
private fun processMouse(e: MouseEvent) = runAndUpdateIfNeeded {
val newKnobPosition = Math.max(0, Math.min(e.x - leftPadding, sliderWidth))
knobPosition = newKnobPosition
}
fun addListener(listener: (T) -> Unit) {
listeners.add(listener)
}
private fun fireValueChanged() = listeners.forEach { it.invoke(value) }
protected abstract fun knobPositionToValue(knobPosition: Int): T
protected abstract fun valueToKnobPosition(value: T): Int
private fun doSlide(shift: Int) {
value = slide(shift)
}
/**
* return the new value after sliding. The [shift] is the amount of sliding.
*/
protected abstract fun slide(shift: Int): T
override fun getPreferredSize(): Dimension = JBUI.size(100, 22)
override fun getMinimumSize(): Dimension = JBUI.size(50, 22)
override fun getMaximumSize(): Dimension = Dimension(Integer.MAX_VALUE, preferredSize.height)
override fun isFocusable() = true
override fun setToolTipText(text: String) = Unit
override fun paintComponent(g: Graphics) {
val g2d = g as Graphics2D
if (isFocusOwner) {
g2d.color = UIUtil.getFocusedFillColor() ?: Color.BLUE.brighter()
val left = leftPadding - FOCUS_BORDER_WIDTH
val top = topPadding - FOCUS_BORDER_WIDTH
val width = width - left - rightPadding + FOCUS_BORDER_WIDTH
val height = height - top - bottomPadding + FOCUS_BORDER_WIDTH
g2d.fillRoundRect(left, top, width, height, FOCUS_BORDER_CORNER_ARC, FOCUS_BORDER_CORNER_ARC)
}
paintSlider(g2d)
drawKnob(g2d, leftPadding + valueToKnobPosition(value))
}
protected abstract fun paintSlider(g2d: Graphics2D)
private fun drawKnob(g2d: Graphics2D, x: Int) {
val originalAntialiasing = g2d.getRenderingHint(RenderingHints.KEY_ANTIALIASING)
val originalStroke = g2d.stroke
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON)
val knobLeft = x - KNOB_WIDTH / 2
val knobTop = topPadding / 2
val knobWidth = KNOB_WIDTH
val knobHeight = height - (topPadding + bottomPadding) / 2
g2d.color = KNOB_COLOR
g2d.fillRoundRect(knobLeft, knobTop, knobWidth, knobHeight, KNOB_CORNER_ARC, KNOB_CORNER_ARC)
g2d.color = KNOB_BORDER_COLOR
g2d.stroke = KNOB_BORDER_STROKE
g2d.drawRoundRect(knobLeft, knobTop, knobWidth, knobHeight, KNOB_CORNER_ARC, KNOB_CORNER_ARC)
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, originalAntialiasing)
g2d.stroke = originalStroke
}
}
| apache-2.0 | 09594271246ffc2780b17513db9c1a56 | 32.461187 | 105 | 0.70524 | 4.091569 | false | false | false | false |
GunoH/intellij-community | platform/testFramework/extensions/src/com/intellij/testFramework/assertions/snapshot.kt | 7 | 4447 | // 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.testFramework.assertions
import com.intellij.openapi.util.SystemInfo
import com.intellij.openapi.util.text.StringUtil
import com.intellij.openapi.util.text.StringUtilRt
import com.intellij.rt.execution.junit.FileComparisonFailure
import com.intellij.testFramework.UsefulTestCase
import com.intellij.util.io.readChars
import com.intellij.util.io.write
import org.assertj.core.api.ListAssert
import org.yaml.snakeyaml.DumperOptions
import org.yaml.snakeyaml.Yaml
import org.yaml.snakeyaml.nodes.Node
import org.yaml.snakeyaml.nodes.Tag
import org.yaml.snakeyaml.representer.Represent
import org.yaml.snakeyaml.representer.Representer
import java.nio.file.NoSuchFileException
import java.nio.file.Path
import java.util.*
import java.util.concurrent.ConcurrentHashMap
import java.util.regex.Pattern
internal interface SnapshotFileUsageListener {
fun beforeMatch(file: Path)
}
internal val snapshotFileUsageListeners = Collections.newSetFromMap<SnapshotFileUsageListener>(ConcurrentHashMap())
class ListAssertEx<ELEMENT>(actual: List<ELEMENT>?) : ListAssert<ELEMENT>(actual) {
fun toMatchSnapshot(snapshotFile: Path) {
snapshotFileUsageListeners.forEach { it.beforeMatch(snapshotFile) }
isNotNull
compareFileContent(actual, snapshotFile)
}
}
fun dumpData(data: Any): String {
val dumperOptions = DumperOptions()
dumperOptions.isAllowReadOnlyProperties = true
dumperOptions.lineBreak = DumperOptions.LineBreak.UNIX
val yaml = Yaml(DumpRepresenter(), dumperOptions)
return yaml.dump(data)
}
private class DumpRepresenter : Representer() {
init {
representers.put(Pattern::class.java, RepresentDump())
}
private inner class RepresentDump : Represent {
override fun representData(data: Any): Node = representScalar(Tag.STR, data.toString())
}
}
internal fun loadSnapshotContent(snapshotFile: Path, convertLineSeparators: Boolean = SystemInfo.isWindows): CharSequence {
// because developer can open file and depending on editor settings, newline maybe added to the end of file
var content = snapshotFile.readChars().trimEnd()
if (convertLineSeparators) {
content = StringUtilRt.convertLineSeparators(content, "\n")
}
return content
}
@Throws(FileComparisonFailure::class)
fun compareFileContent(actual: Any, snapshotFile: Path, updateIfMismatch: Boolean = isUpdateSnapshotIfMismatch(), writeIfNotFound: Boolean = true) {
val actualContent = if (actual is CharSequence) getNormalizedActualContent(actual) else dumpData(actual).trimEnd()
val expected = try {
loadSnapshotContent(snapshotFile)
}
catch (e: NoSuchFileException) {
if (!writeIfNotFound || UsefulTestCase.IS_UNDER_TEAMCITY) {
throw e
}
println("Write a new snapshot: ${snapshotFile.fileName}")
snapshotFile.write(actualContent)
return
}
if (StringUtil.equal(actualContent, expected, true)) {
return
}
if (updateIfMismatch) {
println("UPDATED snapshot ${snapshotFile.fileName}")
snapshotFile.write(actualContent)
}
else {
val firstMismatch = StringUtil.commonPrefixLength(actualContent, expected)
@Suppress("SpellCheckingInspection")
val message = "Received value does not match stored snapshot '${snapshotFile.fileName}' at ${firstMismatch}.\n" +
"Expected: '${expected.contextAround(firstMismatch, 10)}'\n" +
"Actual : '${actualContent.contextAround(firstMismatch, 10)}'\n" +
"Inspect your code changes or run with `-Dtest.update.snapshots` to update"
throw FileComparisonFailure(message, expected.toString(), actualContent.toString(), snapshotFile.toString())
}
}
internal fun getNormalizedActualContent(actual: CharSequence): CharSequence {
var actualContent = actual
if (SystemInfo.isWindows) {
actualContent = StringUtilRt.convertLineSeparators(actualContent, "\n")
}
return actualContent.trimEnd()
}
private fun isUpdateSnapshotIfMismatch(): Boolean {
if (UsefulTestCase.IS_UNDER_TEAMCITY) {
return false
}
val value = System.getProperty("test.update.snapshots")
return value != null && (value.isEmpty() || value.toBoolean())
}
private fun CharSequence.contextAround(offset: Int, context: Int): String =
substring((offset - context).coerceAtLeast(0), (offset + context).coerceAtMost(length)) | apache-2.0 | 3abc131f4c69c61bfb1ab6ca7102c202 | 36.066667 | 148 | 0.762761 | 4.565708 | false | true | false | false |
GunoH/intellij-community | plugins/kotlin/idea/tests/testData/checker/Builders.fir.kt | 10 | 2900 | package html
import java.util.*
interface Factory<T> {
fun create() : T
}
interface Element
class TextElement(val text : String) : Element
abstract class Tag(val name : String) : Element {
val children = ArrayList<Element>()
val attributes = HashMap<String, String>()
protected fun <T : Element> initTag(init : T.() -> Unit) : T
{
val tag = <error descr="[TYPE_PARAMETER_ON_LHS_OF_DOT] Type parameter 'T' cannot have or inherit a companion object, so it cannot be on the left hand side of dot">T</error>.<error descr="[UNRESOLVED_REFERENCE] Unresolved reference: create">create</error>()
tag.init()
children.add(tag)
return tag
}
}
abstract class TagWithText(name : String) : Tag(name) {
operator fun String.unaryPlus() {
children.add(TextElement(this))
}
}
class HTML() : TagWithText("html") {
companion object : Factory<HTML> {
override fun create() = HTML()
}
fun head(init : Head.() -> Unit) = initTag<Head>(init)
fun body(init : Body.() -> Unit) = initTag<Body>(init)
}
class Head() : TagWithText("head") {
companion object : Factory<Head> {
override fun create() = Head()
}
fun title(init : Title.() -> Unit) = initTag<Title>(init)
}
class Title() : TagWithText("title")
abstract class BodyTag(name : String) : TagWithText(name) {
}
class Body() : BodyTag("body") {
companion object : Factory<Body> {
override fun create() = Body()
}
fun b(init : B.() -> Unit) = initTag<B>(init)
fun p(init : P.() -> Unit) = initTag<P>(init)
fun h1(init : H1.() -> Unit) = initTag<H1>(init)
fun a(href : String, init : A.() -> Unit) {
val a = initTag<A>(init)
a.href = href
}
}
class B() : BodyTag("b")
class P() : BodyTag("p")
class H1() : BodyTag("h1")
class A() : BodyTag("a") {
var href : String?
get() = attributes["href"]
set(value) {
if (value != null)
attributes["href"] = value
}
}
operator fun MutableMap<String, String>.set(key : String, value : String) = this.put(key, value)
fun html(init : HTML.() -> Unit) : HTML {
val html = HTML()
html.init()
return html
}
fun result(args : Array<String>) =
html {
head {
title {+"XML encoding with Groovy"}
}
body {
h1 {+"XML encoding with Groovy"}
p {+"this format can be used as an alternative markup to XML"}
// an element with attributes and text content
a(href = "https://groovy.codehaus.org") {+"Groovy"}
// mixed content
p {
+"This is some"
b {+"mixed"}
+"text. For more see the"
a(href = "https://groovy.codehaus.org") {+"Groovy"}
+"project"
}
p {+"some text"}
// content generated by
p {
for (arg in args)
+arg
}
}
}
| apache-2.0 | 1e98a692bc8243cc105ef5f70f552996 | 23.786325 | 262 | 0.566207 | 3.717949 | false | false | false | false |
AsamK/TextSecure | app/src/main/java/org/thoughtcrime/securesms/stories/settings/select/BaseStoryRecipientSelectionViewModel.kt | 1 | 2426 | package org.thoughtcrime.securesms.stories.settings.select
import androidx.lifecycle.LiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import io.reactivex.rxjava3.core.Observable
import io.reactivex.rxjava3.disposables.CompositeDisposable
import io.reactivex.rxjava3.kotlin.plusAssign
import io.reactivex.rxjava3.kotlin.subscribeBy
import io.reactivex.rxjava3.subjects.PublishSubject
import org.thoughtcrime.securesms.database.model.DistributionListId
import org.thoughtcrime.securesms.recipients.RecipientId
import org.thoughtcrime.securesms.util.livedata.Store
class BaseStoryRecipientSelectionViewModel(
private val distributionListId: DistributionListId?,
private val repository: BaseStoryRecipientSelectionRepository
) : ViewModel() {
private val store = Store(emptySet<RecipientId>())
private val subject = PublishSubject.create<Action>()
private val disposable = CompositeDisposable()
var actionObservable: Observable<Action> = subject
var state: LiveData<Set<RecipientId>> = store.stateLiveData
init {
if (distributionListId != null) {
disposable += repository.getListMembers(distributionListId)
.subscribe { members ->
store.update { it + members }
}
}
}
override fun onCleared() {
disposable.clear()
}
fun toggleSelectAll() {
disposable += repository.getAllSignalContacts().subscribeBy { allSignalRecipients ->
store.update { allSignalRecipients }
}
}
fun addRecipient(recipientId: RecipientId) {
store.update { it + recipientId }
}
fun removeRecipient(recipientId: RecipientId) {
store.update { it - recipientId }
}
fun onAction() {
if (distributionListId != null) {
repository.updateDistributionListMembership(distributionListId, store.state)
subject.onNext(Action.ExitFlow)
} else {
subject.onNext(Action.GoToNextScreen(store.state))
}
}
sealed class Action {
data class GoToNextScreen(val recipients: Set<RecipientId>) : Action()
object ExitFlow : Action()
}
class Factory(
private val distributionListId: DistributionListId?,
private val repository: BaseStoryRecipientSelectionRepository
) : ViewModelProvider.Factory {
override fun <T : ViewModel> create(modelClass: Class<T>): T {
return modelClass.cast(BaseStoryRecipientSelectionViewModel(distributionListId, repository)) as T
}
}
}
| gpl-3.0 | 3700cda7ec55b15b411defd470e36065 | 31.346667 | 103 | 0.755565 | 4.747554 | false | false | false | false |
jk1/intellij-community | plugins/git4idea/tests/git4idea/test/GitTestUtil.kt | 3 | 6538 | /*
* Copyright 2000-2013 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.
*/
@file:JvmName("GitTestUtil")
package git4idea.test
import com.intellij.dvcs.push.PushSpec
import com.intellij.openapi.extensions.Extensions
import com.intellij.openapi.project.Project
import com.intellij.openapi.vcs.Executor.*
import com.intellij.openapi.vcs.ProjectLevelVcsManager
import com.intellij.openapi.vcs.impl.ProjectLevelVcsManagerImpl
import com.intellij.openapi.vfs.LocalFileSystem
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.vcs.log.VcsLogObjectsFactory
import com.intellij.vcs.log.VcsLogProvider
import com.intellij.vcs.log.VcsRef
import git4idea.GitRemoteBranch
import git4idea.GitStandardRemoteBranch
import git4idea.GitUtil
import git4idea.GitVcs
import git4idea.config.GitVersionSpecialty
import git4idea.log.GitLogProvider
import git4idea.push.GitPushSource
import git4idea.push.GitPushTarget
import git4idea.repo.GitRepository
import org.junit.Assert.*
import org.junit.Assume.assumeTrue
import java.io.File
const val USER_NAME = "John Doe"
const val USER_EMAIL = "[email protected]"
/**
*
* Creates file structure for given paths. Path element should be a relative (from project root)
* path to a file or a directory. All intermediate paths will be created if needed.
* To create a dir without creating a file pass "dir/" as a parameter.
*
* Usage example:
* `createFileStructure("a.txt", "b.txt", "dir/c.txt", "dir/subdir/d.txt", "anotherdir/");`
*
* This will create files a.txt and b.txt in the project dir, create directories dir, dir/subdir and anotherdir,
* and create file c.txt in dir and d.txt in dir/subdir.
*
* Note: use forward slash to denote directories, even if it is backslash that separates dirs in your system.
*
* All files are populated with "initial content" string.
*/
fun createFileStructure(rootDir: VirtualFile, vararg paths: String) {
for (path in paths) {
cd(rootDir)
val dir = path.endsWith("/")
if (dir) {
mkdir(path)
}
else {
touch(path, "initial_content_" + Math.random())
}
}
}
fun initRepo(project: Project, repoRoot: String, makeInitialCommit: Boolean) {
cd(repoRoot)
git(project, "init")
setupDefaultUsername(project)
if (makeInitialCommit) {
touch("initial.txt")
git(project, "add initial.txt")
git(project, "commit -m initial")
}
}
fun GitPlatformTest.cloneRepo(source: String, destination: String, bare: Boolean) {
cd(source)
if (bare) {
git("clone --bare -- . $destination")
}
else {
git("clone -- . $destination")
}
cd(destination)
setupDefaultUsername()
}
fun setupDefaultUsername(project: Project) = setupUsername(project, USER_NAME, USER_EMAIL)
fun GitPlatformTest.setupDefaultUsername() = setupDefaultUsername(project)
fun setupUsername(project: Project, name: String, email: String) {
assertFalse("Can not set empty user name ", name.isEmpty())
assertFalse("Can not set empty user email ", email.isEmpty())
git(project, "config user.name '$name'")
git(project, "config user.email '$email'")
}
/**
* Creates a Git repository in the given root directory;
* registers it in the Settings;
* return the [GitRepository] object for this newly created repository.
*/
fun createRepository(project: Project, root: String) = createRepository(project, root, true)
fun createRepository(project: Project, root: String, makeInitialCommit: Boolean): GitRepository {
initRepo(project, root, makeInitialCommit)
val gitDir = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(File(root, GitUtil.DOT_GIT))
assertNotNull(gitDir)
return registerRepo(project, root)
}
fun registerRepo(project: Project, root: String): GitRepository {
val vcsManager = ProjectLevelVcsManager.getInstance(project) as ProjectLevelVcsManagerImpl
vcsManager.setDirectoryMapping(root, GitVcs.NAME)
val file = LocalFileSystem.getInstance().findFileByIoFile(File(root))
assertFalse(vcsManager.allVcsRoots.isEmpty())
val repository = GitUtil.getRepositoryManager(project).getRepositoryForRoot(file)
assertNotNull("Couldn't find repository for root " + root, repository)
return repository!!
}
fun assumeSupportedGitVersion(vcs: GitVcs) {
val version = vcs.version
assumeTrue("Unsupported Git version: " + version, version.isSupported)
}
fun GitPlatformTest.readAllRefs(root: VirtualFile, objectsFactory: VcsLogObjectsFactory): Set<VcsRef> {
val refs = git("log --branches --tags --no-walk --format=%H%d --decorate=full").lines()
val result = mutableSetOf<VcsRef>()
for (ref in refs) {
result.addAll(RefParser(objectsFactory).parseCommitRefs(ref, root))
}
return result
}
fun GitPlatformTest.makeCommit(file: String): String {
append(file, "some content")
addCommit("some message")
return last()
}
fun findGitLogProvider(project: Project): GitLogProvider {
val providers = Extensions.getExtensions(VcsLogProvider.LOG_PROVIDER_EP, project)
.filter { provider -> provider.supportedVcs == GitVcs.getKey() }
assertEquals("Incorrect number of GitLogProviders", 1, providers.size)
return providers[0] as GitLogProvider
}
fun makePushSpec(repository: GitRepository, from: String, to: String): PushSpec<GitPushSource, GitPushTarget> {
val source = repository.branches.findLocalBranch(from)!!
var target: GitRemoteBranch? = repository.branches.findBranchByName(to) as GitRemoteBranch?
val newBranch: Boolean
if (target == null) {
val firstSlash = to.indexOf('/')
val remote = GitUtil.findRemoteByName(repository, to.substring(0, firstSlash))!!
target = GitStandardRemoteBranch(remote, to.substring(firstSlash + 1))
newBranch = true
}
else {
newBranch = false
}
return PushSpec(GitPushSource.create(source), GitPushTarget(target, newBranch))
}
fun GitRepository.resolveConflicts() {
cd(this)
this.git("add -u .")
}
fun getPrettyFormatTagForFullCommitMessage(project: Project) =
if (GitVersionSpecialty.STARTED_USING_RAW_BODY_IN_FORMAT.existsIn(project)) "%B" else "%s%n%n%-b"
| apache-2.0 | 7faf08cd733071fcd436e3842fb221ba | 34.923077 | 112 | 0.751912 | 4.033313 | false | false | false | false |
cicdevelopmentnz/Android-BLE | library/src/main/java/nz/co/cic/ble/scanner/ScanFilter.kt | 1 | 2245 | package nz.co.cic.ble.scanner
import com.beust.klaxon.*
import io.reactivex.BackpressureStrategy
import io.reactivex.Flowable
import org.json.JSONObject
import java.util.*
/**
* Created by dipshit on 10/03/17.
*/
class ScanFilter(val name: String, val messageKeys: Array<String>) {
private var uuid: UUID? = null
private var messageUuids: Map<UUID, String>? = null
private val parser: Parser = Parser()
init {
this.uuid = UUID.nameUUIDFromBytes(name.toByteArray())
this.messageUuids = this.messageKeys.associateBy {
keySelector ->
UUID.nameUUIDFromBytes(keySelector.toByteArray())
}
}
fun filter(radioFlow: Flowable<JSONObject>?): Flowable<JsonObject> {
return Flowable.create({
subscriber ->
radioFlow?.subscribe({
jsonInfo ->
var json = parser.parse(StringBuilder(jsonInfo.toString())) as JsonObject
var filteredReturn = runFilter(json)
filteredReturn.set("deviceAddress", json.get("deviceAddress"))
subscriber.onNext(filteredReturn)
}, {
err ->
subscriber.onError(err)
}, {
subscriber.onComplete()
})
}, BackpressureStrategy.BUFFER)
}
private fun runFilter(json: JsonObject): JsonObject {
var filtered = getServiceById(json)
filtered?.set("id", this.name)
filtered?.set("messages", nameMessages(filtered.array<JsonObject>("messages")))
return filtered!!
}
private fun nameMessages(json: JsonArray<JsonObject>?): JsonArray<JsonObject>? {
var it = json?.iterator()
while (it!!.hasNext()) {
var message = it.next()
var id = UUID.fromString(message.get("id") as String)
var name = this.messageUuids?.get(id)
message.set("id", name)
}
return json
}
private fun getServiceById(json: JsonObject): JsonObject? {
var prefiltered = json.array<JsonObject>("messages")
var filtered = prefiltered?.filter {
it.string("id") == this.uuid.toString()
}
return filtered?.get(0)
}
}
| gpl-3.0 | 7cb22d7d6d510855bac06487aca6d4ee | 28.155844 | 89 | 0.594655 | 4.609856 | false | false | false | false |
walleth/kethereum | erc961/src/main/kotlin/org/kethereum/erc961/ERC961Generator.kt | 1 | 443 | package org.kethereum.erc961
import org.kethereum.model.Token
fun Token.generateURL(): String {
val params = mutableListOf<String>()
params.add("symbol=$symbol")
if (decimals != 18) {
params.add("decimals=$decimals")
}
name?.let {
params.add("name=$it")
}
type?.let {
params.add("type=$it")
}
return "ethereum:token_info-$address@${chain.value}?" + params.joinToString("&")
} | mit | 85b982d259685cb15ad7036794d93911 | 17.5 | 84 | 0.600451 | 3.786325 | false | false | false | false |
RayBa82/DVBViewerController | dvbViewerController/src/main/java/org/dvbviewer/controller/data/api/handler/FFMPEGPrefsHandler.kt | 1 | 1781 | package org.dvbviewer.controller.data.api.handler
import org.apache.commons.lang3.StringUtils
import org.dvbviewer.controller.data.entities.FFMpegPresetList
import org.dvbviewer.controller.data.entities.Preset
import org.dvbviewer.controller.utils.INIParser
import org.dvbviewer.controller.utils.StreamUtils
class FFMPEGPrefsHandler {
@Throws(Exception::class)
fun parse(ffmpegprefs: String?): FFMpegPresetList {
val ffPrefs = FFMpegPresetList()
if (StringUtils.isBlank(ffmpegprefs)) {
return ffPrefs
}
val iniParser = INIParser(ffmpegprefs)
ffPrefs.version = iniParser.getString("Version", "Version")
val sectionIterator = iniParser.sections
while (sectionIterator.hasNext()) {
val sectionName = sectionIterator.next()
if (isPreset(iniParser, sectionName)) {
val preset = Preset()
preset.title = sectionName
val mimeType = iniParser.getString(sectionName, "MimeType")
if (StringUtils.isEmpty(mimeType)) {
preset.mimeType = StreamUtils.M3U8_MIME_TYPE
} else {
preset.mimeType = mimeType
}
preset.extension = iniParser.getString(sectionName, "Ext")
ffPrefs.presets.add(preset)
}
}
return ffPrefs
}
private fun isPreset(iniParser: INIParser, sectionName: String): Boolean {
val keysIterator = iniParser.getKeys(sectionName)
var isPreset = false
while (keysIterator!!.hasNext()) {
val keyName = keysIterator.next()
if ("Cmd" == keyName) {
isPreset = true
}
}
return isPreset
}
}
| apache-2.0 | 12d1de5a90fcc9be330db069421f60d1 | 34.62 | 78 | 0.612577 | 4.724138 | false | false | false | false |
jovr/imgui | core/src/main/kotlin/imgui/demo/ShowDemoWindowLayout.kt | 2 | 36121 | package imgui.demo
import gli_.has
import glm_.L
import glm_.f
import glm_.i
import glm_.vec2.Vec2
import glm_.vec4.Vec4
import imgui.*
import imgui.ImGui.alignTextToFramePadding
import imgui.ImGui.begin
import imgui.ImGui.beginChild
import imgui.ImGui.beginGroup
import imgui.ImGui.beginMenu
import imgui.ImGui.beginMenuBar
import imgui.ImGui.beginTabBar
import imgui.ImGui.beginTabItem
import imgui.ImGui.beginTable
import imgui.ImGui.bulletText
import imgui.ImGui.button
import imgui.ImGui.checkbox
import imgui.ImGui.collapsingHeader
import imgui.ImGui.columns
import imgui.ImGui.combo
import imgui.ImGui.contentRegionAvail
import imgui.ImGui.cursorScreenPos
import imgui.ImGui.cursorStartPos
import imgui.ImGui.dragFloat
import imgui.ImGui.dragInt
import imgui.ImGui.dragVec2
import imgui.ImGui.dummy
import imgui.ImGui.end
import imgui.ImGui.endChild
import imgui.ImGui.endGroup
import imgui.ImGui.endMenu
import imgui.ImGui.endMenuBar
import imgui.ImGui.endTabBar
import imgui.ImGui.endTabItem
import imgui.ImGui.endTable
import imgui.ImGui.getColumnWidth
import imgui.ImGui.getID
import imgui.ImGui.invisibleButton
import imgui.ImGui.io
import imgui.ImGui.isItemActive
import imgui.ImGui.isItemHovered
import imgui.ImGui.itemRectMax
import imgui.ImGui.itemRectSize
import imgui.ImGui.listBox
import imgui.ImGui.listBoxFooter
import imgui.ImGui.listBoxHeader
import imgui.ImGui.nextColumn
import imgui.ImGui.plotHistogram
import imgui.ImGui.popID
import imgui.ImGui.popItemWidth
import imgui.ImGui.popStyleColor
import imgui.ImGui.popStyleVar
import imgui.ImGui.pushID
import imgui.ImGui.pushItemWidth
import imgui.ImGui.pushStyleColor
import imgui.ImGui.pushStyleVar
import imgui.ImGui.sameLine
import imgui.ImGui.scrollMaxX
import imgui.ImGui.scrollMaxY
import imgui.ImGui.scrollX
import imgui.ImGui.scrollY
import imgui.ImGui.selectable
import imgui.ImGui.separator
import imgui.ImGui.setNextItemWidth
import imgui.ImGui.setNextWindowContentSize
import imgui.ImGui.setScrollFromPosX
import imgui.ImGui.setScrollFromPosY
import imgui.ImGui.setScrollHereX
import imgui.ImGui.setScrollHereY
import imgui.ImGui.setTooltip
import imgui.ImGui.sliderFloat
import imgui.ImGui.sliderInt
import imgui.ImGui.smallButton
import imgui.ImGui.spacing
import imgui.ImGui.style
import imgui.ImGui.tableNextColumn
import imgui.ImGui.text
import imgui.ImGui.textColored
import imgui.ImGui.textLineHeight
import imgui.ImGui.textUnformatted
import imgui.ImGui.textWrapped
import imgui.ImGui.treeNode
import imgui.ImGui.treePop
import imgui.ImGui.windowContentRegionMax
import imgui.ImGui.windowContentRegionWidth
import imgui.ImGui.windowDrawList
import imgui.ImGui.windowPos
import imgui.api.demoDebugInformations.Companion.helpMarker
import imgui.classes.Color
import imgui.demo.showExampleApp.MenuFile
import imgui.dsl.child
import imgui.dsl.group
import imgui.dsl.indent
import imgui.dsl.menuBar
import imgui.dsl.treeNode
import imgui.dsl.withClipRect
import imgui.dsl.withID
import imgui.dsl.withItemWidth
import imgui.dsl.withStyleColor
import imgui.dsl.withStyleVar
import kotlin.math.sin
import imgui.WindowFlag as Wf
object ShowDemoWindowLayout {
operator fun invoke() {
if (!collapsingHeader("Layout & Scrolling"))
return
`Child Windows`()
`Widgets Width`()
`Basic Horizontal SimpleLayout`()
treeNode("Groups") {
helpMarker(
"BeginGroup() basically locks the horizontal position for new line. " +
"EndGroup() bundles the whole group so that you can use \"item\" functions such as " +
"IsItemHovered()/IsItemActive() or SameLine() etc. on the whole group.")
beginGroup()
group {
button("AAA")
sameLine()
button("BBB")
sameLine()
group {
button("CCC")
button("DDD")
}
sameLine()
button("EEE")
}
if (isItemHovered()) setTooltip("First group hovered")
// Capture the group size and create widgets using the same size
val size = Vec2(itemRectSize)
val values = floatArrayOf(0.5f, 0.2f, 0.8f, 0.6f, 0.25f)
plotHistogram("##values", values, 0, "", 0f, 1f, size)
button("ACTION", Vec2((size.x - style.itemSpacing.x) * 0.5f, size.y))
sameLine()
button("REACTION", Vec2((size.x - style.itemSpacing.x) * 0.5f, size.y))
endGroup()
sameLine()
button("LEVERAGE\nBUZZWORD", size)
sameLine()
if (listBoxHeader("List", size)) {
selectable("Selected", true)
selectable("Not Selected", false)
listBoxFooter()
}
}
treeNode("Text Baseline Alignment") {
run {
bulletText("Text baseline:")
sameLine(); helpMarker(
"This is testing the vertical alignment that gets applied on text to keep it aligned with widgets. " +
"Lines only composed of text or \"small\" widgets use less vertical space than lines with framed widgets.")
indent {
text("KO Blahblah"); sameLine()
button("Some framed item"); sameLine()
helpMarker("Baseline of button will look misaligned with text..")
// If your line starts with text, call AlignTextToFramePadding() to align text to upcoming widgets.
// (because we don't know what's coming after the Text() statement, we need to move the text baseline
// down by FramePadding.y ahead of time)
alignTextToFramePadding()
text("OK Blahblah"); sameLine()
button("Some framed item"); sameLine()
helpMarker("We call AlignTextToFramePadding() to vertically align the text baseline by +FramePadding.y")
// SmallButton() uses the same vertical padding as Text
button("TEST##1"); sameLine()
text("TEST"); sameLine()
smallButton("TEST##2")
// If your line starts with text, call AlignTextToFramePadding() to align text to upcoming widgets.
alignTextToFramePadding()
text("Text aligned to framed item"); sameLine()
button("Item##1"); sameLine()
text("Item"); sameLine()
smallButton("Item##2"); sameLine()
button("Item##3")
}
}
spacing()
run {
bulletText("Multi-line text:")
indent {
text("One\nTwo\nThree"); sameLine()
text("Hello\nWorld"); sameLine()
text("Banana")
text("Banana"); sameLine()
text("Hello\nWorld"); sameLine()
text("One\nTwo\nThree")
button("HOP##1"); sameLine()
text("Banana"); sameLine()
text("Hello\nWorld"); sameLine()
text("Banana")
button("HOP##2"); sameLine()
text("Hello\nWorld"); sameLine()
text("Banana")
}
}
spacing()
run {
bulletText("Misc items:")
indent {
// SmallButton() sets FramePadding to zero. Text baseline is aligned to match baseline of previous Button.
button("80x80", Vec2(80))
sameLine()
button("50x50", Vec2(50))
sameLine()
button("Button()")
sameLine()
smallButton("SmallButton()")
// Tree
val spacing = style.itemInnerSpacing.x
button("Button##1")
sameLine(0f, spacing)
treeNode("Node##1") {
// Placeholder tree data
for (i in 0..5)
bulletText("Item $i..")
}
// Vertically align text node a bit lower so it'll be vertically centered with upcoming widget.
// Otherwise you can use SmallButton() (smaller fit).
alignTextToFramePadding()
// Common mistake to avoid: if we want to SameLine after TreeNode we need to do it before we add
// other contents below the node.
val nodeOpen = treeNode("Node##2")
sameLine(0f, spacing); button("Button##2")
if (nodeOpen) {
// Placeholder tree data
for (i in 0..5)
bulletText("Item $i..")
treePop()
}
// Bullet
button("Button##3")
sameLine(0f, spacing)
bulletText("Bullet text")
alignTextToFramePadding()
bulletText("Node")
sameLine(0f, spacing); button("Button##4")
}
}
}
Scrolling()
Clipping()
}
object `Child Windows` {
var disableMouseWheel = false
var disableMenu = false
var offsetX = 0
operator fun invoke() {
treeNode("Child Windows") {
helpMarker("Use child windows to begin into a self-contained independent scrolling/clipping regions within a host window.")
checkbox("Disable Mouse Wheel", ::disableMouseWheel)
checkbox("Disable Menu", ::disableMenu)
// Child 1: no border, enable horizontal scrollbar
run {
var windowFlags = Wf.HorizontalScrollbar.i
if (disableMouseWheel)
windowFlags = windowFlags or Wf.NoScrollWithMouse
child("ChildL", Vec2(windowContentRegionWidth * 0.5f, 260), false, windowFlags) {
for (i in 0..99)
text("%04d: scrollable region", i)
}
}
sameLine()
// Child 2: rounded border
run {
var windowFlags = Wf.None.i
if (disableMouseWheel)
windowFlags = windowFlags or Wf.NoScrollWithMouse
if (!disableMenu)
windowFlags = windowFlags or Wf.MenuBar
withStyleVar(StyleVar.ChildRounding, 5f) {
child("ChildR", Vec2(0, 260), true, windowFlags) {
if (!disableMenu && beginMenuBar()) {
if (beginMenu("Menu")) {
MenuFile()
endMenu()
}
endMenuBar()
}
columns(2)
if (beginTable("split", 2, TableFlag.Resizable or TableFlag.NoSavedSettings)) {
for (i in 0..99) {
val text = "%03d".format(style.locale, i)
tableNextColumn()
button(text, Vec2(-Float.MIN_VALUE, 0f))
}
}
endTable()
}
}
}
separator()
// Demonstrate a few extra things
// - Changing ImGuiCol_ChildBg (which is transparent black in default styles)
// - Using SetCursorPos() to position child window (the child window is an item from the POV of parent window)
// You can also call SetNextWindowPos() to position the child window. The parent window will effectively
// layout from this position.
// - Using ImGui::GetItemRectMin/Max() to query the "item" state (because the child window is an item from
// the POV of the parent window). See 'Demo->Querying Status (Active/Focused/Hovered etc.)' for details.
run {
setNextItemWidth(100f)
dragInt("Offset X", ::offsetX, 1f, -1000, 1000)
ImGui.cursorPosX += offsetX
withStyleColor(Col.ChildBg, COL32(255, 0, 0, 100)) {
beginChild("Red", Vec2(200, 100), true, Wf.None.i)
for (n in 0..49)
text("Some test $n")
endChild()
}
val childIsHovered = ImGui.isItemHovered()
val childRectMin = ImGui.itemRectMin
val childRectMax = ImGui.itemRectMax
text("Hovered: ${childIsHovered.i}")
text("Rect of child window is: (%.0f,%.0f) (%.0f,%.0f)", childRectMin.x, childRectMin.y, childRectMax.x, childRectMax.y)
}
}
}
}
object `Widgets Width` {
var f = 0f
var showIndentedItems = true
operator fun invoke() {
treeNode("Widgets Width") {
// Use SetNextItemWidth() to set the width of a single upcoming item.
// Use PushItemWidth()/PopItemWidth() to set the width of a group of items.
// In real code use you'll probably want to choose width values that are proportional to your font size
// e.g. Using '20.0f * GetFontSize()' as width instead of '200.0f', etc.
checkbox("Show indented items", ::showIndentedItems)
text("SetNextItemWidth/PushItemWidth(100)")
sameLine(); helpMarker("Fixed width.")
pushItemWidth(100)
dragFloat("float##1b", ::f)
if (showIndentedItems)
indent {
dragFloat("float (indented)##1b", ::f)
}
popItemWidth()
text("SetNextItemWidth/PushItemWidth(-100)")
sameLine(); helpMarker("Align to right edge minus 100")
pushItemWidth(-100)
dragFloat("float##2a", ::f)
if (showIndentedItems)
indent {
dragFloat("float (indented)##2b", ::f)
}
popItemWidth()
text("SetNextItemWidth/PushItemWidth(GetContentRegionAvail().x * 0.5f)")
sameLine(); helpMarker("Half of available width.\n(~ right-cursor_pos)\n(works within a column set)")
pushItemWidth(contentRegionAvail.x * 0.5f)
dragFloat("float##3a", ::f)
if (showIndentedItems)
indent {
dragFloat("float (indented)##3b", ::f)
}
popItemWidth()
text("SetNextItemWidth/PushItemWidth(-GetContentRegionAvail().x * 0.5f)")
sameLine(); helpMarker("Align to right edge minus half")
pushItemWidth(-ImGui.contentRegionAvail.x * 0.5f)
dragFloat("float##4a", ::f)
if (showIndentedItems)
indent {
dragFloat("float (indented)##4b", ::f)
}
popItemWidth()
// Demonstrate using PushItemWidth to surround three items.
// Calling SetNextItemWidth() before each of them would have the same effect.
text("SetNextItemWidth/PushItemWidth(-FLT_MIN)")
sameLine(); helpMarker("Align to right edge")
pushItemWidth(-Float.MIN_VALUE)
dragFloat("##float5a", ::f)
if (showIndentedItems)
indent {
dragFloat("float (indented)##5b", ::f)
}
popItemWidth()
}
}
}
object `Basic Horizontal SimpleLayout` {
var c1 = false
var c2 = false
var c3 = false
var c4 = false
var f0 = 1f
var f1 = 2f
var f2 = 3f
var item = -1
val selection = intArrayOf(0, 1, 2, 3)
operator fun invoke() {
treeNode("Basic Horizontal SimpleLayout") {
textWrapped("(Use SameLine() to keep adding items to the right of the preceding item)")
// Text
text("Two items: Hello"); sameLine()
textColored(Vec4(1, 1, 0, 1), "Sailor")
// Adjust spacing
text("More spacing: Hello"); sameLine(0, 20)
textColored(Vec4(1, 1, 0, 1), "Sailor")
// Button
alignTextToFramePadding()
text("Normal buttons"); sameLine()
button("Banana"); sameLine()
button("Apple"); sameLine()
button("Corniflower")
// Button
text("Small buttons"); sameLine()
smallButton("Like this one"); sameLine()
text("can fit within a text block.")
// Aligned to arbitrary position. Easy/cheap column.
text("Aligned")
sameLine(150); text("x=150")
sameLine(300); text("x=300")
text("Aligned")
sameLine(150); smallButton("x=150")
sameLine(300); smallButton("x=300")
// Checkbox
checkbox("My", ::c1); sameLine()
checkbox("Tailor", ::c2); sameLine()
checkbox("Is", ::c3); sameLine()
checkbox("Rich", ::c4)
// Various
val items = arrayOf("AAAA", "BBBB", "CCCC", "DDDD")
withItemWidth(80f) {
combo("Combo", ::item, items); sameLine()
sliderFloat("X", ::f0, 0f, 5f); sameLine()
sliderFloat("Y", ::f1, 0f, 5f); sameLine()
sliderFloat("Z", ::f2, 0f, 5f)
}
withItemWidth(80f) {
text("Lists:")
for (i in 0..3) {
if (i > 0) sameLine()
withID(i) {
withInt(selection, i) {
listBox("", it, items)
}
}
//if (IsItemHovered()) SetTooltip("ListBox %d hovered", i);
}
}
// Dummy
val buttonSz = Vec2(40)
button("A", buttonSz); sameLine()
dummy(buttonSz); sameLine()
button("B", buttonSz)
// Manually wrapping
// (we should eventually provide this as an automatic layout feature, but for now you can do it manually)
text("Manually wrapping:")
val buttonsCount = 20
val windowVisibleX2 = windowPos.x + windowContentRegionMax.x
for (n in 0 until buttonsCount) {
pushID(n)
button("Box", buttonSz)
val lastButtonX2 = itemRectMax.x
val nextButtonX2 = lastButtonX2 + style.itemSpacing.x + buttonSz.x // Expected position if next button was on same line
if (n + 1 < buttonsCount && nextButtonX2 < windowVisibleX2)
sameLine()
popID()
}
}
}
}
object Scrolling {
var enableTrack = true
var enableExtraDecorations = false
var trackItem = 50
val names = arrayOf("Left", "25%%", "Center", "75%%", "Right")
var scrollToOffPx = 0f
var scrollToPosPx = 200f
var lines = 7
var showHorizontalContentsSizeDemoWindow = false
var showHscrollbar = true
var showButton = true
var showTreeNodes = true
var showTextWrapped = false
var open = true
var showColumns = true
var showTabBar = true
var showChild = false
var explicitContentSize = false
var contentsSizeX = 300f
operator fun invoke() {
treeNode("Scrolling") {
// Vertical scroll functions
helpMarker("Use SetScrollHereY() or SetScrollFromPosY() to scroll to a given vertical position.")
checkbox("Decoration", ::enableExtraDecorations)
checkbox("Track", ::enableTrack)
pushItemWidth(100)
sameLine(140); enableTrack = dragInt("##item", ::trackItem, 0.25f, 0, 99, "Item = %d") or enableTrack
var scrollToOff = button("Scroll Offset")
sameLine(140); scrollToOff = dragFloat("##off", ::scrollToOffPx, 1f, 0f, Float.MAX_VALUE, "+%.0f px") or scrollToOff
var scrollToPos = button("Scroll To Pos")
sameLine(140); scrollToPos = dragFloat("##pos", ::scrollToPosPx, 1f, -10f, Float.MAX_VALUE, "X/Y = %.0f px") or scrollToPos
popItemWidth()
if (scrollToOff || scrollToPos)
enableTrack = false
var childW = (contentRegionAvail.x - 4 * style.itemSpacing.x) / 5
if (childW < 1f)
childW = 1f
pushID("##VerticalScrolling")
for (i in 0..4) {
if (i > 0) sameLine()
group {
val names = arrayOf("Top", "25%%", "Center", "75%%", "Bottom") // double quote for ::format escaping
textUnformatted(names[i])
val childFlags = if (enableExtraDecorations) Wf.MenuBar else Wf.None
val childId = getID(i.L)
val childIsVisible = beginChild(childId, Vec2(childW, 200f), true, childFlags.i)
menuBar { textUnformatted("abc") }
if (scrollToOff)
scrollY = scrollToOffPx
if (scrollToPos)
setScrollFromPosY(cursorStartPos.y + scrollToPosPx, i * 0.25f)
// Avoid calling SetScrollHereY when running with culled items
if (childIsVisible)
for (item in 0..99)
if (enableTrack && item == trackItem) {
textColored(Vec4(1, 1, 0, 1), "Item %d", item)
setScrollHereY(i * 0.25f) // 0.0f:top, 0.5f:center, 1.0f:bottom
} else
text("Item $item")
val scrollY = scrollY
val scrollMaxY = scrollMaxY
endChild()
text("%.0f/%.0f", scrollY, scrollMaxY)
}
}
popID()
// Horizontal scroll functions
spacing()
helpMarker(
"Use SetScrollHereX() or SetScrollFromPosX() to scroll to a given horizontal position.\n\n" +
"Because the clipping rectangle of most window hides half worth of WindowPadding on the " +
"left/right, using SetScrollFromPosX(+1) will usually result in clipped text whereas the " +
"equivalent SetScrollFromPosY(+1) wouldn't.")
pushID("##HorizontalScrolling")
for (i in 0..4) {
val childHeight = textLineHeight + style.scrollbarSize + style.windowPadding.y * 2f
val childFlags = Wf.HorizontalScrollbar or if (enableExtraDecorations) Wf.AlwaysVerticalScrollbar else Wf.None
val childId = getID(i.L)
val childIsVisible = beginChild(childId, Vec2(-100f, childHeight), true, childFlags)
if (scrollToOff)
scrollX = scrollToOffPx
if (scrollToPos)
setScrollFromPosX(cursorStartPos.x + scrollToPosPx, i * 0.25f)
if (childIsVisible) // Avoid calling SetScrollHereY when running with culled items
for (item in 0..99) {
if (enableTrack && item == trackItem) {
textColored(Vec4(1, 1, 0, 1), "Item $item")
setScrollHereX(i * 0.25f) // 0.0f:left, 0.5f:center, 1.0f:right
} else
text("Item $item")
sameLine()
}
endChild()
sameLine()
text("${names[i]}\n%.0f/%.0f", scrollX, scrollMaxX)
spacing()
}
popID()
// Miscellaneous Horizontal Scrolling Demo
helpMarker(
"Horizontal scrolling for a window is enabled via the ImGuiWindowFlags_HorizontalScrollbar flag.\n\n" +
"You may want to also explicitly specify content width by using SetNextWindowContentWidth() before Begin().")
sliderInt("Lines", ::lines, 1, 15)
pushStyleVar(StyleVar.FrameRounding, 3f)
pushStyleVar(StyleVar.FramePadding, Vec2(2f, 1f))
val scrollingChildSize = Vec2(0f, ImGui.frameHeightWithSpacing * 7 + 30)
beginChild("scrolling", scrollingChildSize, true, Wf.HorizontalScrollbar.i)
for (line in 0 until lines) {
// Display random stuff. For the sake of this trivial demo we are using basic Button() + SameLine()
// If you want to create your own time line for a real application you may be better off manipulating
// the cursor position yourself, aka using SetCursorPos/SetCursorScreenPos to position the widgets
// yourself. You may also want to use the lower-level ImDrawList API.
val numButtons = 10 + (line * if (line has 1) 9 else 3)
for (n in 0 until numButtons) {
if (n > 0) sameLine()
pushID(n + line * 1000)
val label = if (n % 15 == 0) "FizzBuzz" else if (n % 3 == 0) "Fizz" else if (n % 5 == 0) "Buzz" else "$n"
val hue = n * 0.05f
pushStyleColor(Col.Button, Color.hsv(hue, 0.6f, 0.6f))
pushStyleColor(Col.ButtonHovered, Color.hsv(hue, 0.7f, 0.7f))
pushStyleColor(Col.ButtonActive, Color.hsv(hue, 0.8f, 0.8f))
button(label, Vec2(40f + sin((line + n).f) * 20f, 0f))
popStyleColor(3)
popID()
}
}
val _scrollX = scrollX
val scrollMaxX = scrollMaxX
endChild()
popStyleVar(2)
var scrollXDelta = 0f
smallButton("<<")
if (isItemActive)
scrollXDelta = -io.deltaTime * 1000f
sameLine()
text("Scroll from code"); sameLine()
smallButton(">>")
if (isItemActive)
scrollXDelta = io.deltaTime * 1000f
sameLine()
text("%.0f/%.0f", _scrollX, scrollMaxX)
if (scrollXDelta != 0f) {
// Demonstrate a trick: you can use Begin to set yourself in the context of another window
// (here we are already out of your child window)
beginChild("scrolling")
scrollX += scrollXDelta
endChild()
}
spacing()
checkbox("Show Horizontal contents size demo window", ::showHorizontalContentsSizeDemoWindow)
if (showHorizontalContentsSizeDemoWindow) {
if (explicitContentSize)
setNextWindowContentSize(Vec2(contentsSizeX, 0f))
begin("Horizontal contents size demo window", ::showHorizontalContentsSizeDemoWindow, if (showHscrollbar) Wf.HorizontalScrollbar.i else Wf.None.i)
pushStyleVar(StyleVar.ItemSpacing, Vec2(2, 0))
pushStyleVar(StyleVar.FramePadding, Vec2(2, 0))
helpMarker("Test of different widgets react and impact the work rectangle growing when horizontal scrolling is enabled.\n\nUse 'Metrics->Tools->Show windows rectangles' to visualize rectangles.")
checkbox("H-scrollbar", ::showHscrollbar)
checkbox("Button", ::showButton) // Will grow contents size (unless explicitly overwritten)
checkbox("Tree nodes", ::showTreeNodes) // Will grow contents size and display highlight over full width
checkbox("Text wrapped", ::showTextWrapped) // Will grow and use contents size
checkbox("Columns", ::showColumns) // Will use contents size
checkbox("Tab bar", ::showTabBar) // Will use contents size
checkbox("Child", ::showChild) // Will grow and use contents size
checkbox("Explicit content size", ::explicitContentSize)
text("Scroll %.1f/%.1f %.1f/%.1f", scrollX, scrollMaxX, scrollY, scrollMaxY)
if (explicitContentSize) {
sameLine()
setNextItemWidth(100f)
dragFloat("##csx", ::contentsSizeX)
val p = cursorScreenPos
windowDrawList.addRectFilled(p, Vec2(p.x + 10, p.y + 10), COL32_WHITE)
windowDrawList.addRectFilled(Vec2(p.x + contentsSizeX - 10, p.y), Vec2(p.x + contentsSizeX, p.y + 10), COL32_WHITE)
dummy(Vec2(0, 10))
}
popStyleVar(2)
separator()
if (showButton)
button("this is a 300-wide button", Vec2(300, 0))
if (showTreeNodes) {
open = true
treeNode("this is a tree node") {
treeNode("another one of those tree node...") {
text("Some tree contents")
}
}
collapsingHeader("CollapsingHeader", ::open)
}
if (showTextWrapped)
textWrapped("This text should automatically wrap on the edge of the work rectangle.")
if (showColumns) {
text("Tables:")
if (beginTable("table", 4, TableFlag.Borders.i)) {
for (n in 0..3) {
tableNextColumn()
text("Width %.2f", ImGui.contentRegionAvail.x)
}
endTable()
}
text("Columns:")
columns(4)
for (n in 0..3) {
text("Width %.2f", getColumnWidth())
nextColumn()
}
columns(1)
}
if (showTabBar && beginTabBar("Hello")) {
if (beginTabItem("OneOneOne"))
endTabItem()
if (beginTabItem("TwoTwoTwo"))
endTabItem()
if (beginTabItem("ThreeThreeThree"))
endTabItem()
if (beginTabItem("FourFourFour"))
endTabItem()
endTabBar()
}
if (showChild) {
beginChild("child", Vec2(), true)
endChild()
}
end()
}
}
}
}
object Clipping {
val size = Vec2(100f)
val offset = Vec2(30)
operator fun invoke() {
treeNode("Clipping") {
dragVec2("size", size, 0.5f, 1f, 200f, "%.0f")
textWrapped("(Click and drag to scroll)")
for (n in 0..2) {
if (n > 0)
sameLine()
pushID(n)
group { // Lock X position
invisibleButton("##empty", size)
if (ImGui.isItemActive && ImGui.isMouseDragging(MouseButton.Left))
offset += io.mouseDelta
val p0 = Vec2(ImGui.itemRectMin)
val p1 = Vec2(ImGui.itemRectMax)
val textStr = "Line 1 hello\nLine 2 clip me!"
val textPos = p0 + offset
val drawList = ImGui.windowDrawList
when (n) {
0 -> {
helpMarker("""
Using ImGui::PushClipRect():
Will alter ImGui hit-testing logic + ImDrawList rendering.
(use this if you want your clipping rectangle to affect interactions)""".trimIndent())
withClipRect(p0, p1, true) {
drawList.addRectFilled(p0, p1, COL32(90, 90, 120, 255))
drawList.addText(textPos, COL32_WHITE, textStr)
}
}
1 -> {
helpMarker("""
Using ImDrawList::PushClipRect():
Will alter ImDrawList rendering only.
(use this as a shortcut if you are only using ImDrawList calls)""".trimIndent())
drawList.withClipRect(p0, p1, true) {
addRectFilled(p0, p1, COL32(90, 90, 120, 255))
addText(textPos, COL32_WHITE, textStr)
}
}
2 -> {
helpMarker("""
Using ImDrawList::AddText() with a fine ClipRect:
Will alter only this specific ImDrawList::AddText() rendering.
(this is often used internally to avoid altering the clipping rectangle and minimize draw calls)""".trimIndent())
val clipRect = Vec4(p0, p1) // AddText() takes a ImVec4* here so let's convert.
drawList.addRectFilled(p0, p1, COL32(90, 90, 120, 255))
drawList.addText(ImGui.font, ImGui.fontSize, textPos, COL32_WHITE, textStr, 0f, clipRect)
}
}
}
popID()
}
}
}
}
} | mit | 69104fb161c648a73a8b0fcddbb9f7be | 42.311751 | 215 | 0.491349 | 5.328367 | false | false | false | false |
pureal-code/pureal-os | traits/src/net/pureal/traits/graphics/TextElement.kt | 1 | 1572 | package net.pureal.traits.graphics
import net.pureal.traits.math.*
import net.pureal.traits.*
import net.pureal.traits.interaction.KeysElement
import net.pureal.traits.interaction.PointersElement
trait TextElement : ColoredElement<String> {
val font: Font
val size: Number
override val shape: Shape get() = font.shape(content).transformed(Transforms2.scale(size))
}
fun textElement(content: String, font: Font, size: Number, fill: Fill) = object : TextElement {
override val content = content
override val font = font
override val size = size
override val fill = fill
}
trait Font {
fun shape(text: String): Shape
}
trait TextInput : Composed<String>, KeysElement<String>, PointersElement<String> {
var text: String
override val content: String get() = text
var cursorPosition: Int
val textChanged: Observable<String>
}
fun textInput(text: String = "", bound: Rectangle, font: Font, fontFill: Fill, size: Number, backgroundFill: Fill) = object : TextInput {
override val shape: Shape = null!!
override val textChanged: Observable<String> = null!!
override var cursorPosition: Int = null!!
override var text = text
private fun textElement() = textElement(text, font, size, fontFill)
private fun cursor() = coloredElement(rectangle(vector(0,0)), fontFill)
private fun background() = coloredElement(bound, backgroundFill)
override val elements = observableList<TransformedElement<*>>()
private fun refresh() {
//elements.setTo(textElement(), cursor(), background())
}
} | bsd-3-clause | e7830cdbaa5ca8247401a6b01a6dcc61 | 31.770833 | 137 | 0.716285 | 4.203209 | false | false | false | false |
code-disaster/lwjgl3 | modules/lwjgl/opengl/src/templates/kotlin/opengl/templates/EXT_direct_state_access.kt | 4 | 73611 | /*
* Copyright LWJGL. All rights reserved.
* License terms: https://www.lwjgl.org/license
*/
package opengl.templates
import org.lwjgl.generator.*
import opengl.*
val EXT_direct_state_access = "EXTDirectStateAccess".nativeClassGL("EXT_direct_state_access", postfix = EXT) {
documentation =
"""
Native bindings to the $registryLink extension.
This extension introduces a set of new "direct state access" commands (meaning no selector is involved) to access (update and query) OpenGL state that
previously depended on the OpenGL state selectors for access. These new commands supplement the existing selector-based OpenGL commands to access the
same state.
The intent of this extension is to make it more efficient for libraries to avoid disturbing selector and latched state. The extension also allows more
efficient command usage by eliminating the need for selector update commands.
Two derivative advantages of this extension are 1) display lists can be executed using these commands that avoid disturbing selectors that subsequent
commands may depend on, and 2) drivers implemented with a dual-thread partitioning with OpenGL command buffering from an application thread and then
OpenGL command dispatching in a concurrent driver thread can avoid thread synchronization created by selector saving, setting, command execution, and
selector restoration.
This extension does not itself add any new OpenGL state.
We call a state variable in OpenGL an "OpenGL state selector" or simply a "selector" if OpenGL commands depend on the state variable to determine what
state to query or update. The matrix mode and active texture are both selectors. Object bindings for buffers, programs, textures, and framebuffer
objects are also selectors.
We call OpenGL state "latched" if the state is set by one OpenGL command but then that state is saved by a subsequent command or the state determines
how client memory or buffer object memory is accessed by a subsequent command. The array and element array buffer bindings are latched by vertex array
specification commands to determine which buffer a given vertex array uses. Vertex array state and pixel pack/unpack state decides how client memory or
buffer object memory is accessed by subsequent vertex pulling or image specification commands.
The existence of selectors and latched state in the OpenGL API reduces the number of parameters to various sets of OpenGL commands but complicates the
access to state for layered libraries which seek to access state without disturbing other state, namely the state of state selectors and latched state.
In many cases, selectors and latched state were introduced by extensions as OpenGL evolved to minimize the disruption to the OpenGL API when new
functionality, particularly the pluralization of existing functionality as when texture objects and later multiple texture units, was introduced.
The OpenGL API involves several selectors (listed in historical order of introduction):
${ul(
"The matrix mode.",
"The current bound texture for each supported texture target.",
"The active texture.",
"The active client texture.",
"The current bound program for each supported program target.",
"The current bound buffer for each supported buffer target.",
"The current GLSL program.",
"The current framebuffer object."
)}
The new selector-free update commands can be compiled into display lists.
The OpenGL API has latched state for vertex array buffer objects and pixel store state. When an application issues a GL command to unpack or pack pixels
(for example, glTexImage2D or glReadPixels respectively), the current unpack and pack pixel store state determines how the pixels are unpacked
from/packed to client memory or pixel buffer objects. For example, consider:
${codeBlock("""
glPixelStorei(GL_UNPACK_SWAP_BYTES, GL_TRUE);
glPixelStorei(GL_UNPACK_ROW_LENGTH, 640);
glBindBuffer(GL_PIXEL_UNPACK_BUFFER, 47);
glDrawPixels(100, 100, GL_RGB, GL_FLOAT, pixels);""")}
The unpack swap bytes and row length state set by the preceding glPixelStorei commands (as well as the 6 other unpack pixel store state variables)
control how data is read (unpacked) from buffer of data pointed to by pixels. The glBindBuffer command also specifies an unpack buffer object (47) so
the pixel pointer is actually treated as a byte offset into buffer object 47.
When an application issues a command to configure a vertex array, the current array buffer state is latched as the binding for the particular vertex
array being specified. For example, consider:
${codeBlock("""
glBindBuffer(GL_ARRAY_BUFFER, 23);
glVertexPointer(3, GL_FLOAT, 12, pointer);""")}
The glBindBuffer command updates the array buffering binding (GL_ARRAY_BUFFER_BINDING) to the buffer object named 23. The subsequent glVertexPointer
command specifies explicit parameters for the size, type, stride, and pointer to access the position vertex array BUT ALSO latches the current array
buffer binding for the vertex array buffer binding (GL_VERTEX_ARRAY_BUFFER_BINDING). Effectively the current array buffer binding buffer object becomes
an implicit fifth parameter to glVertexPointer and this applies to all the gl*Pointer vertex array specification commands.
Selectors and latched state create problems for layered libraries using OpenGL because selectors require the selector state to be modified to update
some other state and latched state means implicit state can affect the operation of commands specifying, packing, or unpacking data through
pointers/offsets. For layered libraries, a state update performed by the library may attempt to save the selector state, set the selector, update/query
some state the selector controls, and then restore the selector to its saved state. Layered libraries can skip the selector save/restore but this risks
introducing uncertainty about the state of a selector after calling layered library routines. Such selector side-effects are difficult to document and
lead to compatibility issues as the layered library evolves or its usage varies. For latched state, layered libraries may find commands such as
glDrawPixels do not work as expected because latched pixel store state is not what the library expects. Querying or pushing the latched state, setting
the latched state explicitly, performing the operation involving latched state, and then restoring or popping the latched state avoids entanglements
with latched state but at considerable cost.
<h3>EXAMPLE USAGE OF THIS EXTENSION'S FUNCTIONALITY</h3>
Consider the following routine to set the modelview matrix involving the matrix mode selector:
${codeBlock("""
void setModelviewMatrix(const GLfloat matrix[16])
{
GLenum savedMatrixMode;
glGetIntegerv(GL_MATRIX_MODE, &savedMatrixMode);
glMatrixMode(GL_MODELVIEW);
glLoadMatrixf(matrix);
glMatrixMode(savedMatrixMode);
}""")}
Notice that four OpenGL commands are required to update the current modelview matrix without disturbing the matrix mode selector.
OpenGL query commands can also substantially reduce the performance of modern OpenGL implementations which may off-load OpenGL state processing to
another CPU core/thread or to the GPU itself.
An alternative to querying the selector is to use the glPushAttrib/glPopAttrib commands. However this approach typically involves pushing far more state
than simply the one or two selectors that need to be saved and restored. Because so much state is associated with a given push/pop attribute bit, the
glPushAttrib and glPopAttrib commands are considerably more costly than the save/restore approach. Additionally glPushAttrib risks overflowing the
attribute stack.
The reliability and performance of layered libraries and applications can be improved by adding to the OpenGL API a new set of commands to access
directly OpenGL state that otherwise involves selectors to access.
The above example can be reimplemented more efficiently and without selector side-effects:
${codeBlock("""
void setModelviewMatrix(const GLfloat matrix[16])
{
glMatrixLoadfEXT(GL_MODELVIEW, matrix);
}""")}
Consider a layered library seeking to load a texture:
${codeBlock("""
void loadTexture(GLint texobj, GLint width, GLint height, void *data)
{
glBindTexture(GL_TEXTURE_2D, texobj);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB8, width, height, GL_RGB, GL_FLOAT, data);
}""")}
The library expects the data to be packed into the buffer pointed to by data. But what if the current pixel unpack buffer binding is not zero so the
current pixel unpack buffer, rather than client memory, will be read? Or what if the application has modified the GL_UNPACK_ROW_LENGTH pixel store state
before loadTexture is called?
We can fix the routine by calling glBindBuffer(GL_PIXEL_UNPACK_BUFFER, 0) and setting all the pixel store unpack state to the initial state the
loadTexture routine expects, but this is expensive. It also risks disturbing the state so when loadTexture returns to the application, the application
doesn't realize the current texture object (for whatever texture unit the current active texture happens to be) and pixel store state has changed.
We can more efficiently implement this routine without disturbing selector or latched state as follows:
${codeBlock("""
void loadTexture(GLint texobj, GLint width, GLint height, void *data)
{
glPushClientAttribDefaultEXT(GL_CLIENT_PIXEL_STORE_BIT);
glTextureImage2D(texobj, GL_TEXTURE_2D, 0, GL_RGB8, width, height, GL_RGB, GL_FLOAT, data);
glPopClientAttrib();
}""")}
Now loadTexture does not have to worry about inappropriately configured pixel store state or a non-zero pixel unpack buffer binding. And loadTexture has
no unintended side-effects for selector or latched state (assuming the client attrib state does not overflow).
"""
IntConstant(
"GetBooleani_v, GetIntegeri_v, GetFloati_vEXT, GetDoublei_vEXT.",
"PROGRAM_MATRIX_EXT"..0x8E2D,
"TRANSPOSE_PROGRAM_MATRIX_EXT"..0x8E2E,
"PROGRAM_MATRIX_STACK_DEPTH_EXT"..0x8E2F
)
// OpenGL 1.1: New client commands
void(
"ClientAttribDefaultEXT",
"",
GLbitfield("mask", "")
)
void(
"PushClientAttribDefaultEXT",
"",
GLbitfield("mask", "")
)
/*
OpenGL 1.0: New matrix commands add "Matrix" prefix to name,
drops "Matrix" suffix from name, and add initial "enum matrixMode"
parameter
*/
void(
"MatrixLoadfEXT",
"",
GLenum("matrixMode", ""),
Check(16)..GLfloat.const.p("m", "")
)
void(
"MatrixLoaddEXT",
"",
GLenum("matrixMode", ""),
Check(16)..GLdouble.const.p("m", "")
)
void(
"MatrixMultfEXT",
"",
GLenum("matrixMode", ""),
Check(16)..GLfloat.const.p("m", "")
)
void(
"MatrixMultdEXT",
"",
GLenum("matrixMode", ""),
Check(16)..GLdouble.const.p("m", "")
)
void(
"MatrixLoadIdentityEXT",
"",
GLenum("matrixMode", "")
)
void(
"MatrixRotatefEXT",
"",
GLenum("matrixMode", ""),
GLfloat("angle", ""),
GLfloat("x", ""),
GLfloat("y", ""),
GLfloat("z", "")
)
void(
"MatrixRotatedEXT",
"",
GLenum("matrixMode", ""),
GLdouble("angle", ""),
GLdouble("x", ""),
GLdouble("y", ""),
GLdouble("z", "")
)
void(
"MatrixScalefEXT",
"",
GLenum("matrixMode", ""),
GLfloat("x", ""),
GLfloat("y", ""),
GLfloat("z", "")
)
void(
"MatrixScaledEXT",
"",
GLenum("matrixMode", ""),
GLdouble("x", ""),
GLdouble("y", ""),
GLdouble("z", "")
)
void(
"MatrixTranslatefEXT",
"",
GLenum("matrixMode", ""),
GLfloat("x", ""),
GLfloat("y", ""),
GLfloat("z", "")
)
void(
"MatrixTranslatedEXT",
"",
GLenum("matrixMode", ""),
GLdouble("x", ""),
GLdouble("y", ""),
GLdouble("z", "")
)
void(
"MatrixOrthoEXT",
"",
GLenum("matrixMode", ""),
GLdouble("l", ""),
GLdouble("r", ""),
GLdouble("b", ""),
GLdouble("t", ""),
GLdouble("n", ""),
GLdouble("f", "")
)
void(
"MatrixFrustumEXT",
"",
GLenum("matrixMode", ""),
GLdouble("l", ""),
GLdouble("r", ""),
GLdouble("b", ""),
GLdouble("t", ""),
GLdouble("n", ""),
GLdouble("f", "")
)
void(
"MatrixPushEXT",
"",
GLenum("matrixMode", "")
)
void(
"MatrixPopEXT",
"",
GLenum("matrixMode", "")
)
/*
OpenGL 1.1: New texture object commands and queries replace "Tex"
in name with "Texture" and add initial "uint texture" parameter
*/
void(
"TextureParameteriEXT",
"",
GLuint("texture", ""),
GLenum("target", ""),
GLenum("pname", ""),
GLint("param", "")
)
void(
"TextureParameterivEXT",
"",
GLuint("texture", ""),
GLenum("target", ""),
GLenum("pname", ""),
Check(4)..GLint.const.p("param", "")
)
void(
"TextureParameterfEXT",
"",
GLuint("texture", ""),
GLenum("target", ""),
GLenum("pname", ""),
GLfloat("param", "")
)
void(
"TextureParameterfvEXT",
"",
GLuint("texture", ""),
GLenum("target", ""),
GLenum("pname", ""),
Check(4)..GLfloat.const.p("param", "")
)
void(
"TextureImage1DEXT",
"",
GLuint("texture", ""),
GLenum("target", ""),
GLint("level", ""),
GLint("internalformat", ""),
GLsizei("width", ""),
GLint("border", ""),
GLenum("format", ""),
GLenum("type", ""),
MultiType(
PointerMapping.DATA_SHORT, PointerMapping.DATA_INT, PointerMapping.DATA_FLOAT, PointerMapping.DATA_DOUBLE
)..Unsafe..RawPointer..nullable..void.const.p("pixels", "")
)
void(
"TextureImage2DEXT",
"",
GLuint("texture", ""),
GLenum("target", ""),
GLint("level", ""),
GLint("internalformat", ""),
GLsizei("width", ""),
GLsizei("height", ""),
GLint("border", ""),
GLenum("format", ""),
GLenum("type", ""),
MultiType(
PointerMapping.DATA_SHORT, PointerMapping.DATA_INT, PointerMapping.DATA_FLOAT, PointerMapping.DATA_DOUBLE
)..Unsafe..RawPointer..nullable..void.const.p("pixels", "")
)
void(
"TextureSubImage1DEXT",
"",
GLuint("texture", ""),
GLenum("target", ""),
GLint("level", ""),
GLint("xoffset", ""),
GLsizei("width", ""),
GLenum("format", ""),
GLenum("type", ""),
MultiType(
PointerMapping.DATA_SHORT, PointerMapping.DATA_INT, PointerMapping.DATA_FLOAT, PointerMapping.DATA_DOUBLE
)..Unsafe..RawPointer..void.const.p("pixels", "")
)
void(
"TextureSubImage2DEXT",
"",
GLuint("texture", ""),
GLenum("target", ""),
GLint("level", ""),
GLint("xoffset", ""),
GLint("yoffset", ""),
GLsizei("width", ""),
GLsizei("height", ""),
GLenum("format", ""),
GLenum("type", ""),
MultiType(
PointerMapping.DATA_SHORT, PointerMapping.DATA_INT, PointerMapping.DATA_FLOAT, PointerMapping.DATA_DOUBLE
)..Unsafe..RawPointer..void.const.p("pixels", "")
)
void(
"CopyTextureImage1DEXT",
"",
GLuint("texture", ""),
GLenum("target", ""),
GLint("level", ""),
GLenum("internalformat", ""),
GLint("x", ""),
GLint("y", ""),
GLsizei("width", ""),
GLint("border", "")
)
void(
"CopyTextureImage2DEXT",
"",
GLuint("texture", ""),
GLenum("target", ""),
GLint("level", ""),
GLenum("internalformat", ""),
GLint("x", ""),
GLint("y", ""),
GLsizei("width", ""),
GLsizei("height", ""),
GLint("border", "")
)
void(
"CopyTextureSubImage1DEXT",
"",
GLuint("texture", ""),
GLenum("target", ""),
GLint("level", ""),
GLint("xoffset", ""),
GLint("x", ""),
GLint("y", ""),
GLsizei("width", "")
)
void(
"CopyTextureSubImage2DEXT",
"",
GLuint("texture", ""),
GLenum("target", ""),
GLint("level", ""),
GLint("xoffset", ""),
GLint("yoffset", ""),
GLint("x", ""),
GLint("y", ""),
GLsizei("width", ""),
GLsizei("height", "")
)
void(
"GetTextureImageEXT",
"",
GLuint("texture", ""),
GLenum("target", ""),
GLint("level", ""),
GLenum("format", ""),
GLenum("type", ""),
MultiType(
PointerMapping.DATA_SHORT,
PointerMapping.DATA_INT,
PointerMapping.DATA_FLOAT,
PointerMapping.DATA_DOUBLE
)..Unsafe..RawPointer..void.p("pixels", "")
)
void(
"GetTextureParameterfvEXT",
"",
GLuint("texture", ""),
GLenum("target", ""),
GLenum("pname", ""),
Check(1)..ReturnParam..GLfloat.p("params", "")
)
void(
"GetTextureParameterivEXT",
"",
GLuint("texture", ""),
GLenum("target", ""),
GLenum("pname", ""),
Check(1)..ReturnParam..GLint.p("params", "")
)
void(
"GetTextureLevelParameterfvEXT",
"",
GLuint("texture", ""),
GLenum("target", ""),
GLint("level", ""),
GLenum("pname", ""),
Check(1)..ReturnParam..GLfloat.p("params", "")
)
void(
"GetTextureLevelParameterivEXT",
"",
GLuint("texture", ""),
GLenum("target", ""),
GLint("level", ""),
GLenum("pname", ""),
Check(1)..ReturnParam..GLint.p("params", "")
)
/*
OpenGL 1.2: New 3D texture object commands replace "Tex" in name with
"Texture" and adds initial "uint texture" parameter
*/
DependsOn("OpenGL12")..void(
"TextureImage3DEXT",
"",
GLuint("texture", ""),
GLenum("target", ""),
GLint("level", ""),
GLint("internalformat", ""),
GLsizei("width", ""),
GLsizei("height", ""),
GLsizei("depth", ""),
GLint("border", ""),
GLenum("format", ""),
GLenum("type", ""),
MultiType(
PointerMapping.DATA_SHORT, PointerMapping.DATA_INT, PointerMapping.DATA_FLOAT, PointerMapping.DATA_DOUBLE
)..Unsafe..nullable..RawPointer..void.const.p("pixels", "")
)
DependsOn("OpenGL12")..void(
"TextureSubImage3DEXT",
"",
GLuint("texture", ""),
GLenum("target", ""),
GLint("level", ""),
GLint("xoffset", ""),
GLint("yoffset", ""),
GLint("zoffset", ""),
GLsizei("width", ""),
GLsizei("height", ""),
GLsizei("depth", ""),
GLenum("format", ""),
GLenum("type", ""),
MultiType(
PointerMapping.DATA_SHORT, PointerMapping.DATA_INT, PointerMapping.DATA_FLOAT, PointerMapping.DATA_DOUBLE
)..Unsafe..RawPointer..void.const.p("pixels", "")
)
DependsOn("OpenGL12")..void(
"CopyTextureSubImage3DEXT",
"",
GLuint("texture", ""),
GLenum("target", ""),
GLint("level", ""),
GLint("xoffset", ""),
GLint("yoffset", ""),
GLint("zoffset", ""),
GLint("x", ""),
GLint("y", ""),
GLsizei("width", ""),
GLsizei("height", "")
)
/*
OpenGL 1.2.1: New multitexture commands and queries prefix "Multi"
before "Tex" and add an initial "enum texunit" parameter (to identify
the texture unit).
*/
DependsOn("OpenGL13")..void(
"BindMultiTextureEXT",
"",
GLenum("texunit", ""),
GLenum("target", ""),
GLuint("texture", "")
)
DependsOn("OpenGL13")..void(
"MultiTexCoordPointerEXT",
"",
GLenum("texunit", ""),
GLint("size", ""),
GLenum("type", ""),
GLsizei("stride", ""),
MultiType(
PointerMapping.DATA_SHORT, PointerMapping.DATA_INT, PointerMapping.DATA_FLOAT
)..Unsafe..RawPointer..void.const.p("pointer", "")
)
DependsOn("OpenGL13")..void(
"MultiTexEnvfEXT",
"",
GLenum("texunit", ""),
GLenum("target", ""),
GLenum("pname", ""),
GLfloat("param", "")
)
DependsOn("OpenGL13")..void(
"MultiTexEnvfvEXT",
"",
GLenum("texunit", ""),
GLenum("target", ""),
GLenum("pname", ""),
Check(4)..GLfloat.const.p("params", "")
)
DependsOn("OpenGL13")..void(
"MultiTexEnviEXT",
"",
GLenum("texunit", ""),
GLenum("target", ""),
GLenum("pname", ""),
GLint("param", "")
)
DependsOn("OpenGL13")..void(
"MultiTexEnvivEXT",
"",
GLenum("texunit", ""),
GLenum("target", ""),
GLenum("pname", ""),
Check(4)..GLint.const.p("params", "")
)
DependsOn("OpenGL13")..void(
"MultiTexGendEXT",
"",
GLenum("texunit", ""),
GLenum("coord", ""),
GLenum("pname", ""),
GLdouble("param", "")
)
DependsOn("OpenGL13")..void(
"MultiTexGendvEXT",
"",
GLenum("texunit", ""),
GLenum("coord", ""),
GLenum("pname", ""),
Check(4)..GLdouble.const.p("params", "")
)
DependsOn("OpenGL13")..void(
"MultiTexGenfEXT",
"",
GLenum("texunit", ""),
GLenum("coord", ""),
GLenum("pname", ""),
GLfloat("param", "")
)
DependsOn("OpenGL13")..void(
"MultiTexGenfvEXT",
"",
GLenum("texunit", ""),
GLenum("coord", ""),
GLenum("pname", ""),
Check(4)..GLfloat.const.p("params", "")
)
DependsOn("OpenGL13")..void(
"MultiTexGeniEXT",
"",
GLenum("texunit", ""),
GLenum("coord", ""),
GLenum("pname", ""),
GLint("param", "")
)
DependsOn("OpenGL13")..void(
"MultiTexGenivEXT",
"",
GLenum("texunit", ""),
GLenum("coord", ""),
GLenum("pname", ""),
Check(4)..GLint.const.p("params", "")
)
DependsOn("OpenGL13")..void(
"GetMultiTexEnvfvEXT",
"",
GLenum("texunit", ""),
GLenum("target", ""),
GLenum("pname", ""),
Check(1)..ReturnParam..GLfloat.p("params", "")
)
DependsOn("OpenGL13")..void(
"GetMultiTexEnvivEXT",
"",
GLenum("texunit", ""),
GLenum("target", ""),
GLenum("pname", ""),
Check(1)..ReturnParam..GLint.p("params", "")
)
DependsOn("OpenGL13")..void(
"GetMultiTexGendvEXT",
"",
GLenum("texunit", ""),
GLenum("coord", ""),
GLenum("pname", ""),
Check(1)..ReturnParam..GLdouble.p("params", "")
)
DependsOn("OpenGL13")..void(
"GetMultiTexGenfvEXT",
"",
GLenum("texunit", ""),
GLenum("coord", ""),
GLenum("pname", ""),
Check(1)..ReturnParam..GLfloat.p("params", "")
)
DependsOn("OpenGL13")..void(
"GetMultiTexGenivEXT",
"",
GLenum("texunit", ""),
GLenum("coord", ""),
GLenum("pname", ""),
Check(1)..ReturnParam..GLint.p("params", "")
)
DependsOn("OpenGL13")..void(
"MultiTexParameteriEXT",
"",
GLenum("texunit", ""),
GLenum("target", ""),
GLenum("pname", ""),
GLint("param", "")
)
DependsOn("OpenGL13")..void(
"MultiTexParameterivEXT",
"",
GLenum("texunit", ""),
GLenum("target", ""),
GLenum("pname", ""),
Check(4)..GLint.const.p("param", "")
)
DependsOn("OpenGL13")..void(
"MultiTexParameterfEXT",
"",
GLenum("texunit", ""),
GLenum("target", ""),
GLenum("pname", ""),
GLfloat("param", "")
)
DependsOn("OpenGL13")..void(
"MultiTexParameterfvEXT",
"",
GLenum("texunit", ""),
GLenum("target", ""),
GLenum("pname", ""),
Check(4)..GLfloat.const.p("param", "")
)
DependsOn("OpenGL13")..void(
"MultiTexImage1DEXT",
"",
GLenum("texunit", ""),
GLenum("target", ""),
GLint("level", ""),
GLint("internalformat", ""),
GLsizei("width", ""),
GLint("border", ""),
GLenum("format", ""),
GLenum("type", ""),
MultiType(
PointerMapping.DATA_SHORT, PointerMapping.DATA_INT, PointerMapping.DATA_FLOAT, PointerMapping.DATA_DOUBLE
)..Unsafe..RawPointer..nullable..void.const.p("pixels", "")
)
DependsOn("OpenGL13")..void(
"MultiTexImage2DEXT",
"",
GLenum("texunit", ""),
GLenum("target", ""),
GLint("level", ""),
GLint("internalformat", ""),
GLsizei("width", ""),
GLsizei("height", ""),
GLint("border", ""),
GLenum("format", ""),
GLenum("type", ""),
MultiType(
PointerMapping.DATA_SHORT, PointerMapping.DATA_INT, PointerMapping.DATA_FLOAT, PointerMapping.DATA_DOUBLE
)..Unsafe..RawPointer..nullable..void.const.p("pixels", "")
)
DependsOn("OpenGL13")..void(
"MultiTexSubImage1DEXT",
"",
GLenum("texunit", ""),
GLenum("target", ""),
GLint("level", ""),
GLint("xoffset", ""),
GLsizei("width", ""),
GLenum("format", ""),
GLenum("type", ""),
MultiType(
PointerMapping.DATA_SHORT, PointerMapping.DATA_INT, PointerMapping.DATA_FLOAT, PointerMapping.DATA_DOUBLE
)..Unsafe..RawPointer..void.const.p("pixels", "")
)
DependsOn("OpenGL13")..void(
"MultiTexSubImage2DEXT",
"",
GLenum("texunit", ""),
GLenum("target", ""),
GLint("level", ""),
GLint("xoffset", ""),
GLint("yoffset", ""),
GLsizei("width", ""),
GLsizei("height", ""),
GLenum("format", ""),
GLenum("type", ""),
MultiType(
PointerMapping.DATA_SHORT, PointerMapping.DATA_INT, PointerMapping.DATA_FLOAT, PointerMapping.DATA_DOUBLE
)..Unsafe..RawPointer..void.const.p("pixels", "")
)
DependsOn("OpenGL13")..void(
"CopyMultiTexImage1DEXT",
"",
GLenum("texunit", ""),
GLenum("target", ""),
GLint("level", ""),
GLenum("internalformat", ""),
GLint("x", ""),
GLint("y", ""),
GLsizei("width", ""),
GLint("border", "")
)
DependsOn("OpenGL13")..void(
"CopyMultiTexImage2DEXT",
"",
GLenum("texunit", ""),
GLenum("target", ""),
GLint("level", ""),
GLenum("internalformat", ""),
GLint("x", ""),
GLint("y", ""),
GLsizei("width", ""),
GLsizei("height", ""),
GLint("border", "")
)
DependsOn("OpenGL13")..void(
"CopyMultiTexSubImage1DEXT",
"",
GLenum("texunit", ""),
GLenum("target", ""),
GLint("level", ""),
GLint("xoffset", ""),
GLint("x", ""),
GLint("y", ""),
GLsizei("width", "")
)
DependsOn("OpenGL13")..void(
"CopyMultiTexSubImage2DEXT",
"",
GLenum("texunit", ""),
GLenum("target", ""),
GLint("level", ""),
GLint("xoffset", ""),
GLint("yoffset", ""),
GLint("x", ""),
GLint("y", ""),
GLsizei("width", ""),
GLsizei("height", "")
)
DependsOn("OpenGL13")..void(
"GetMultiTexImageEXT",
"",
GLenum("texunit", ""),
GLenum("target", ""),
GLint("level", ""),
GLenum("format", ""),
GLenum("type", ""),
MultiType(
PointerMapping.DATA_SHORT,
PointerMapping.DATA_INT,
PointerMapping.DATA_FLOAT,
PointerMapping.DATA_DOUBLE
)..Unsafe..RawPointer..void.p("pixels", "")
)
DependsOn("OpenGL13")..void(
"GetMultiTexParameterfvEXT",
"",
GLenum("texunit", ""),
GLenum("target", ""),
GLenum("pname", ""),
Check(1)..ReturnParam..GLfloat.p("params", "")
)
DependsOn("OpenGL13")..void(
"GetMultiTexParameterivEXT",
"",
GLenum("texunit", ""),
GLenum("target", ""),
GLenum("pname", ""),
Check(1)..ReturnParam..GLint.p("params", "")
)
DependsOn("OpenGL13")..void(
"GetMultiTexLevelParameterfvEXT",
"",
GLenum("texunit", ""),
GLenum("target", ""),
GLint("level", ""),
GLenum("pname", ""),
Check(1)..ReturnParam..GLfloat.p("params", "")
)
DependsOn("OpenGL13")..void(
"GetMultiTexLevelParameterivEXT",
"",
GLenum("texunit", ""),
GLenum("target", ""),
GLint("level", ""),
GLenum("pname", ""),
Check(1)..ReturnParam..GLint.p("params", "")
)
DependsOn("OpenGL13")..void(
"MultiTexImage3DEXT",
"",
GLenum("texunit", ""),
GLenum("target", ""),
GLint("level", ""),
GLint("internalformat", ""),
GLsizei("width", ""),
GLsizei("height", ""),
GLsizei("depth", ""),
GLint("border", ""),
GLenum("format", ""),
GLenum("type", ""),
MultiType(
PointerMapping.DATA_SHORT, PointerMapping.DATA_INT, PointerMapping.DATA_FLOAT, PointerMapping.DATA_DOUBLE
)..Unsafe..nullable..RawPointer..void.const.p("pixels", "")
)
DependsOn("OpenGL13")..void(
"MultiTexSubImage3DEXT",
"",
GLenum("texunit", ""),
GLenum("target", ""),
GLint("level", ""),
GLint("xoffset", ""),
GLint("yoffset", ""),
GLint("zoffset", ""),
GLsizei("width", ""),
GLsizei("height", ""),
GLsizei("depth", ""),
GLenum("format", ""),
GLenum("type", ""),
MultiType(
PointerMapping.DATA_SHORT, PointerMapping.DATA_INT, PointerMapping.DATA_FLOAT, PointerMapping.DATA_DOUBLE
)..Unsafe..RawPointer..void.const.p("pixels", "")
)
DependsOn("OpenGL13")..void(
"CopyMultiTexSubImage3DEXT",
"",
GLenum("texunit", ""),
GLenum("target", ""),
GLint("level", ""),
GLint("xoffset", ""),
GLint("yoffset", ""),
GLint("zoffset", ""),
GLint("x", ""),
GLint("y", ""),
GLsizei("width", ""),
GLsizei("height", "")
)
/*
OpenGL 1.2.1: New indexed texture commands and queries append
"Indexed" to name and add "uint index" parameter (to identify the
texture unit index) after state name parameters (if any) and before
state value parameters
*/
DependsOn("OpenGL13")..void(
"EnableClientStateIndexedEXT",
"",
GLenum("array", ""),
GLuint("index", "")
)
DependsOn("OpenGL13")..void(
"DisableClientStateIndexedEXT",
"",
GLenum("array", ""),
GLuint("index", "")
)
/*
OpenGL 3.0: New indexed texture commands and queries append "i"
to name and add "uint index" parameter (to identify the texture
unit index) after state name parameters (if any) and before state
value parameters
*/
DependsOn("OpenGL30")..IgnoreMissing..void(
"EnableClientStateiEXT",
"",
GLenum("array", ""),
GLuint("index", "")
)
DependsOn("OpenGL30")..IgnoreMissing..void(
"DisableClientStateiEXT",
"",
GLenum("array", ""),
GLuint("index", "")
)
/*
OpenGL 1.2.1: New indexed generic queries (added for indexed texture
state) append "Indexed" to name and add "uint index" parameter
(to identify the texture unit) after state name parameters (if any) and
before state value parameters
*/
DependsOn("OpenGL13")..void(
"GetFloatIndexedvEXT",
"",
GLenum("target", ""),
GLuint("index", ""),
Check(1)..ReturnParam..GLfloat.p("params", "")
)
DependsOn("OpenGL13")..void(
"GetDoubleIndexedvEXT",
"",
GLenum("target", ""),
GLuint("index", ""),
Check(1)..ReturnParam..GLdouble.p("params", "")
)
DependsOn("OpenGL13")..void(
"GetPointerIndexedvEXT",
"",
GLenum("target", ""),
GLuint("index", ""),
Check(1)..ReturnParam..void.p.p("params", "")
)
/*
OpenGL 3.0: New indexed generic queries (added for indexed texture
state) replace "v" for "i_v" to name and add "uint index" parameter
(to identify the texture unit) after state name parameters (if any)
and before state value parameters
*/
DependsOn("OpenGL30")..IgnoreMissing..void(
"GetFloati_vEXT",
"",
GLenum("pname", ""),
GLuint("index", ""),
Check(1)..ReturnParam..GLfloat.p("params", "")
)
DependsOn("OpenGL30")..IgnoreMissing..void(
"GetDoublei_vEXT",
"",
GLenum("pname", ""),
GLuint("index", ""),
Check(1)..ReturnParam..GLdouble.p("params", "")
)
DependsOn("OpenGL30")..IgnoreMissing..void(
"GetPointeri_vEXT",
"",
GLenum("pname", ""),
GLuint("index", ""),
Check(1)..ReturnParam..void.p.p("params", "")
)
/*
OpenGL 1.2.1: Extend the functionality of these EXT_draw_buffers2
commands and queries for multitexture
*/
DependsOn("OpenGL13")..(reuse(EXT_draw_buffers2, "EnableIndexedEXT"))
DependsOn("OpenGL13")..(reuse(EXT_draw_buffers2, "DisableIndexedEXT"))
DependsOn("OpenGL13")..(reuse(EXT_draw_buffers2, "IsEnabledIndexedEXT"))
DependsOn("OpenGL13")..(reuse(EXT_draw_buffers2, "GetIntegerIndexedvEXT"))
DependsOn("OpenGL13")..(reuse(EXT_draw_buffers2, "GetBooleanIndexedvEXT"))
/*
ARB_vertex_program: New program commands and queries add "Named"
prefix to name and adds initial "uint program" parameter
*/
DependsOn("GL_ARB_vertex_program")..void(
"NamedProgramStringEXT",
"",
GLuint("program", ""),
GLenum("target", ""),
GLenum("format", ""),
AutoSize("string")..GLsizei("len", ""),
void.const.p("string", "")
)
DependsOn("GL_ARB_vertex_program")..void(
"NamedProgramLocalParameter4dEXT",
"",
GLuint("program", ""),
GLenum("target", ""),
GLuint("index", ""),
GLdouble("x", ""),
GLdouble("y", ""),
GLdouble("z", ""),
GLdouble("w", "")
)
DependsOn("GL_ARB_vertex_program")..void(
"NamedProgramLocalParameter4dvEXT",
"",
GLuint("program", ""),
GLenum("target", ""),
GLuint("index", ""),
Check(4)..GLdouble.const.p("params", "")
)
DependsOn("GL_ARB_vertex_program")..void(
"NamedProgramLocalParameter4fEXT",
"",
GLuint("program", ""),
GLenum("target", ""),
GLuint("index", ""),
GLfloat("x", ""),
GLfloat("y", ""),
GLfloat("z", ""),
GLfloat("w", "")
)
DependsOn("GL_ARB_vertex_program")..void(
"NamedProgramLocalParameter4fvEXT",
"",
GLuint("program", ""),
GLenum("target", ""),
GLuint("index", ""),
Check(4)..GLfloat.const.p("params", "")
)
DependsOn("GL_ARB_vertex_program")..void(
"GetNamedProgramLocalParameterdvEXT",
"",
GLuint("program", ""),
GLenum("target", ""),
GLuint("index", ""),
Check(4)..GLdouble.p("params", "")
)
DependsOn("GL_ARB_vertex_program")..void(
"GetNamedProgramLocalParameterfvEXT",
"",
GLuint("program", ""),
GLenum("target", ""),
GLuint("index", ""),
Check(4)..GLfloat.p("params", "")
)
DependsOn("GL_ARB_vertex_program")..void(
"GetNamedProgramivEXT",
"",
GLuint("program", ""),
GLenum("target", ""),
GLenum("pname", ""),
ReturnParam..Check(1)..GLint.p("params", "")
)
DependsOn("GL_ARB_vertex_program")..void(
"GetNamedProgramStringEXT",
"",
GLuint("program", ""),
GLenum("target", ""),
GLenum("pname", ""),
Check("glGetNamedProgramiEXT(program, target, ARBVertexProgram.GL_PROGRAM_LENGTH_ARB)", debug = true)..void.p("string", "")
)
/*
OpenGL 1.3: New compressed texture object commands replace "Tex"
in name with "Texture" and add initial "uint texture" parameter
*/
DependsOn("OpenGL13")..void(
"CompressedTextureImage3DEXT",
"",
GLuint("texture", ""),
GLenum("target", ""),
GLint("level", ""),
GLenum("internalformat", ""),
GLsizei("width", ""),
GLsizei("height", ""),
GLsizei("depth", ""),
GLint("border", ""),
AutoSize("data")..GLsizei("imageSize", ""),
RawPointer..nullable..void.const.p("data", "")
)
DependsOn("OpenGL13")..void(
"CompressedTextureImage2DEXT",
"",
GLuint("texture", ""),
GLenum("target", ""),
GLint("level", ""),
GLenum("internalformat", ""),
GLsizei("width", ""),
GLsizei("height", ""),
GLint("border", ""),
AutoSize("data")..GLsizei("imageSize", ""),
RawPointer..nullable..void.const.p("data", "")
)
DependsOn("OpenGL13")..void(
"CompressedTextureImage1DEXT",
"",
GLuint("texture", ""),
GLenum("target", ""),
GLint("level", ""),
GLenum("internalformat", ""),
GLsizei("width", ""),
GLint("border", ""),
AutoSize("data")..GLsizei("imageSize", ""),
RawPointer..nullable..void.const.p("data", "")
)
DependsOn("OpenGL13")..void(
"CompressedTextureSubImage3DEXT",
"",
GLuint("texture", ""),
GLenum("target", ""),
GLint("level", ""),
GLint("xoffset", ""),
GLint("yoffset", ""),
GLint("zoffset", ""),
GLsizei("width", ""),
GLsizei("height", ""),
GLsizei("depth", ""),
GLenum("format", ""),
AutoSize("data")..GLsizei("imageSize", ""),
RawPointer..void.const.p("data", "")
)
DependsOn("OpenGL13")..void(
"CompressedTextureSubImage2DEXT",
"",
GLuint("texture", ""),
GLenum("target", ""),
GLint("level", ""),
GLint("xoffset", ""),
GLint("yoffset", ""),
GLsizei("width", ""),
GLsizei("height", ""),
GLenum("format", ""),
AutoSize("data")..GLsizei("imageSize", ""),
RawPointer..void.const.p("data", "")
)
DependsOn("OpenGL13")..void(
"CompressedTextureSubImage1DEXT",
"",
GLuint("texture", ""),
GLenum("target", ""),
GLint("level", ""),
GLint("xoffset", ""),
GLsizei("width", ""),
GLenum("format", ""),
AutoSize("data")..GLsizei("imageSize", ""),
RawPointer..void.const.p("data", "")
)
DependsOn("OpenGL13")..void(
"GetCompressedTextureImageEXT",
"",
GLuint("texture", ""),
GLenum("target", ""),
GLint("level", ""),
Check(
expression = "glGetTextureLevelParameteriEXT(texture, target, level, GL13.GL_TEXTURE_COMPRESSED_IMAGE_SIZE)", debug = true
)..RawPointer..void.p("img", "")
)
/*
OpenGL 1.3: New multitexture compressed texture commands and queries
prefix "Multi" before "Tex" and add an initial "enum texunit"
parameter (to identify the texture unit).
*/
DependsOn("OpenGL13")..void(
"CompressedMultiTexImage3DEXT",
"",
GLenum("texunit", ""),
GLenum("target", ""),
GLint("level", ""),
GLenum("internalformat", ""),
GLsizei("width", ""),
GLsizei("height", ""),
GLsizei("depth", ""),
GLint("border", ""),
AutoSize("data")..GLsizei("imageSize", ""),
RawPointer..nullable..void.const.p("data", "")
)
DependsOn("OpenGL13")..void(
"CompressedMultiTexImage2DEXT",
"",
GLenum("texunit", ""),
GLenum("target", ""),
GLint("level", ""),
GLenum("internalformat", ""),
GLsizei("width", ""),
GLsizei("height", ""),
GLint("border", ""),
AutoSize("data")..GLsizei("imageSize", ""),
RawPointer..nullable..void.const.p("data", "")
)
DependsOn("OpenGL13")..void(
"CompressedMultiTexImage1DEXT",
"",
GLenum("texunit", ""),
GLenum("target", ""),
GLint("level", ""),
GLenum("internalformat", ""),
GLsizei("width", ""),
GLint("border", ""),
AutoSize("data")..GLsizei("imageSize", ""),
RawPointer..nullable..void.const.p("data", "")
)
DependsOn("OpenGL13")..void(
"CompressedMultiTexSubImage3DEXT",
"",
GLenum("texunit", ""),
GLenum("target", ""),
GLint("level", ""),
GLint("xoffset", ""),
GLint("yoffset", ""),
GLint("zoffset", ""),
GLsizei("width", ""),
GLsizei("height", ""),
GLsizei("depth", ""),
GLenum("format", ""),
AutoSize("data")..GLsizei("imageSize", ""),
RawPointer..void.const.p("data", "")
)
DependsOn("OpenGL13")..void(
"CompressedMultiTexSubImage2DEXT",
"",
GLenum("texunit", ""),
GLenum("target", ""),
GLint("level", ""),
GLint("xoffset", ""),
GLint("yoffset", ""),
GLsizei("width", ""),
GLsizei("height", ""),
GLenum("format", ""),
AutoSize("data")..GLsizei("imageSize", ""),
RawPointer..void.const.p("data", "")
)
DependsOn("OpenGL13")..void(
"CompressedMultiTexSubImage1DEXT",
"",
GLenum("texunit", ""),
GLenum("target", ""),
GLint("level", ""),
GLint("xoffset", ""),
GLsizei("width", ""),
GLenum("format", ""),
AutoSize("data")..GLsizei("imageSize", ""),
RawPointer..void.const.p("data", "")
)
DependsOn("OpenGL13")..void(
"GetCompressedMultiTexImageEXT",
"",
GLenum("texunit", ""),
GLenum("target", ""),
GLint("level", ""),
Check(
expression = "glGetMultiTexLevelParameteriEXT(texunit, target, level, GL13.GL_TEXTURE_COMPRESSED_IMAGE_SIZE)", debug = true
)..RawPointer..void.p("img", "")
)
/*
<OpenGL 1.3: New transpose matrix commands add "Matrix" suffix
to name, drops "Matrix" suffix from name, and add initial "enum
matrixMode" parameter
*/
DependsOn("OpenGL13")..void(
"MatrixLoadTransposefEXT",
"",
GLenum("matrixMode", ""),
Check(16)..GLfloat.const.p("m", "")
)
DependsOn("OpenGL13")..void(
"MatrixLoadTransposedEXT",
"",
GLenum("matrixMode", ""),
Check(16)..GLdouble.const.p("m", "")
)
DependsOn("OpenGL13")..void(
"MatrixMultTransposefEXT",
"",
GLenum("matrixMode", ""),
Check(16)..GLfloat.const.p("m", "")
)
DependsOn("OpenGL13")..void(
"MatrixMultTransposedEXT",
"",
GLenum("matrixMode", ""),
Check(16)..GLdouble.const.p("m", "")
)
/*
OpenGL 1.5: New buffer commands and queries replace "Buffer" with
"NamedBuffer" in name and replace "enum target" parameter with
"uint buffer"
*/
DependsOn("OpenGL15")..void(
"NamedBufferDataEXT",
"",
GLuint("buffer", ""),
AutoSize("data")..GLsizeiptr("size", ""),
optional..MultiType(
PointerMapping.DATA_SHORT,
PointerMapping.DATA_INT,
PointerMapping.DATA_FLOAT,
PointerMapping.DATA_DOUBLE
)..void.const.p("data", ""),
GLenum("usage", "")
)
DependsOn("OpenGL15")..void(
"NamedBufferSubDataEXT",
"",
GLuint("buffer", ""),
GLintptr("offset", ""),
AutoSize("data")..GLsizeiptr("size", ""),
MultiType(
PointerMapping.DATA_SHORT,
PointerMapping.DATA_INT,
PointerMapping.DATA_FLOAT,
PointerMapping.DATA_DOUBLE
)..void.const.p("data", "")
)
DependsOn("OpenGL15")..MapPointer("glGetNamedBufferParameteriEXT(buffer, GL15.GL_BUFFER_SIZE)", oldBufferOverloads = true)..void.p(
"MapNamedBufferEXT",
"",
GLuint("buffer", ""),
GLenum("access", "")
)
DependsOn("OpenGL15")..GLboolean(
"UnmapNamedBufferEXT",
"",
GLuint("buffer", "")
)
DependsOn("OpenGL15")..void(
"GetNamedBufferParameterivEXT",
"",
GLuint("buffer", ""),
GLenum("pname", ""),
Check(1)..ReturnParam..GLint.p("params", "")
)
DependsOn("OpenGL15")..void(
"GetNamedBufferSubDataEXT",
"",
GLuint("buffer", ""),
GLintptr("offset", ""),
AutoSize("data")..GLsizeiptr("size", ""),
MultiType(
PointerMapping.DATA_SHORT,
PointerMapping.DATA_INT,
PointerMapping.DATA_FLOAT,
PointerMapping.DATA_DOUBLE
)..void.p("data", "")
)
/*
OpenGL 2.0: New uniform commands add "Program" prefix to name and
add initial "uint program" parameter
*/
DependsOn("OpenGL20")..void(
"ProgramUniform1fEXT",
"",
GLuint("program", ""),
GLint("location", ""),
GLfloat("v0", "")
)
DependsOn("OpenGL20")..void(
"ProgramUniform2fEXT",
"",
GLuint("program", ""),
GLint("location", ""),
GLfloat("v0", ""),
GLfloat("v1", "")
)
DependsOn("OpenGL20")..void(
"ProgramUniform3fEXT",
"",
GLuint("program", ""),
GLint("location", ""),
GLfloat("v0", ""),
GLfloat("v1", ""),
GLfloat("v2", "")
)
DependsOn("OpenGL20")..void(
"ProgramUniform4fEXT",
"",
GLuint("program", ""),
GLint("location", ""),
GLfloat("v0", ""),
GLfloat("v1", ""),
GLfloat("v2", ""),
GLfloat("v3", "")
)
DependsOn("OpenGL20")..void(
"ProgramUniform1iEXT",
"",
GLuint("program", ""),
GLint("location", ""),
GLint("v0", "")
)
DependsOn("OpenGL20")..void(
"ProgramUniform2iEXT",
"",
GLuint("program", ""),
GLint("location", ""),
GLint("v0", ""),
GLint("v1", "")
)
DependsOn("OpenGL20")..void(
"ProgramUniform3iEXT",
"",
GLuint("program", ""),
GLint("location", ""),
GLint("v0", ""),
GLint("v1", ""),
GLint("v2", "")
)
DependsOn("OpenGL20")..void(
"ProgramUniform4iEXT",
"",
GLuint("program", ""),
GLint("location", ""),
GLint("v0", ""),
GLint("v1", ""),
GLint("v2", ""),
GLint("v3", "")
)
DependsOn("OpenGL20")..void(
"ProgramUniform1fvEXT",
"",
GLuint("program", ""),
GLint("location", ""),
AutoSize("value")..GLsizei("count", ""),
GLfloat.const.p("value", "")
)
DependsOn("OpenGL20")..void(
"ProgramUniform2fvEXT",
"",
GLuint("program", ""),
GLint("location", ""),
AutoSize(2, "value")..GLsizei("count", ""),
GLfloat.const.p("value", "")
)
DependsOn("OpenGL20")..void(
"ProgramUniform3fvEXT",
"",
GLuint("program", ""),
GLint("location", ""),
AutoSize(3, "value")..GLsizei("count", ""),
GLfloat.const.p("value", "")
)
DependsOn("OpenGL20")..void(
"ProgramUniform4fvEXT",
"",
GLuint("program", ""),
GLint("location", ""),
AutoSize(4, "value")..GLsizei("count", ""),
GLfloat.const.p("value", "")
)
DependsOn("OpenGL20")..void(
"ProgramUniform1ivEXT",
"",
GLuint("program", ""),
GLint("location", ""),
AutoSize("value")..GLsizei("count", ""),
GLint.const.p("value", "")
)
DependsOn("OpenGL20")..void(
"ProgramUniform2ivEXT",
"",
GLuint("program", ""),
GLint("location", ""),
AutoSize(2, "value")..GLsizei("count", ""),
GLint.const.p("value", "")
)
DependsOn("OpenGL20")..void(
"ProgramUniform3ivEXT",
"",
GLuint("program", ""),
GLint("location", ""),
AutoSize(3, "value")..GLsizei("count", ""),
GLint.const.p("value", "")
)
DependsOn("OpenGL20")..void(
"ProgramUniform4ivEXT",
"",
GLuint("program", ""),
GLint("location", ""),
AutoSize(4, "value")..GLsizei("count", ""),
GLint.const.p("value", "")
)
DependsOn("OpenGL20")..void(
"ProgramUniformMatrix2fvEXT",
"",
GLuint("program", ""),
GLint("location", ""),
AutoSize(2 x 2, "value")..GLsizei("count", ""),
GLboolean("transpose", ""),
GLfloat.const.p("value", "")
)
DependsOn("OpenGL20")..void(
"ProgramUniformMatrix3fvEXT",
"",
GLuint("program", ""),
GLint("location", ""),
AutoSize(3 x 3, "value")..GLsizei("count", ""),
GLboolean("transpose", ""),
GLfloat.const.p("value", "")
)
DependsOn("OpenGL20")..void(
"ProgramUniformMatrix4fvEXT",
"",
GLuint("program", ""),
GLint("location", ""),
AutoSize(4 x 4, "value")..GLsizei("count", ""),
GLboolean("transpose", ""),
GLfloat.const.p("value", "")
)
/*
OpenGL 2.1: New uniform matrix commands add "Program" prefix to
name and add initial "uint program" parameter
*/
DependsOn("OpenGL21")..void(
"ProgramUniformMatrix2x3fvEXT",
"",
GLuint("program", ""),
GLint("location", ""),
AutoSize(2 x 3, "value")..GLsizei("count", ""),
GLboolean("transpose", ""),
GLfloat.const.p("value", "")
)
DependsOn("OpenGL21")..void(
"ProgramUniformMatrix3x2fvEXT",
"",
GLuint("program", ""),
GLint("location", ""),
AutoSize(3 x 2, "value")..GLsizei("count", ""),
GLboolean("transpose", ""),
GLfloat.const.p("value", "")
)
DependsOn("OpenGL21")..void(
"ProgramUniformMatrix2x4fvEXT",
"",
GLuint("program", ""),
GLint("location", ""),
AutoSize(2 x 4, "value")..GLsizei("count", ""),
GLboolean("transpose", ""),
GLfloat.const.p("value", "")
)
DependsOn("OpenGL21")..void(
"ProgramUniformMatrix4x2fvEXT",
"",
GLuint("program", ""),
GLint("location", ""),
AutoSize(4 x 2, "value")..GLsizei("count", ""),
GLboolean("transpose", ""),
GLfloat.const.p("value", "")
)
DependsOn("OpenGL21")..void(
"ProgramUniformMatrix3x4fvEXT",
"",
GLuint("program", ""),
GLint("location", ""),
AutoSize(3 x 4, "value")..GLsizei("count", ""),
GLboolean("transpose", ""),
GLfloat.const.p("value", "")
)
DependsOn("OpenGL21")..void(
"ProgramUniformMatrix4x3fvEXT",
"",
GLuint("program", ""),
GLint("location", ""),
AutoSize(4 x 3, "value")..GLsizei("count", ""),
GLboolean("transpose", ""),
GLfloat.const.p("value", "")
)
/*
EXT_texture_buffer_object: New texture buffer object command
replaces "Tex" in name with "Texture" and adds initial "uint texture"
parameter
*/
DependsOn("GL_EXT_texture_buffer_object")..void(
"TextureBufferEXT",
"",
GLuint("texture", ""),
GLenum("target", ""),
GLenum("internalformat", ""),
GLuint("buffer", "")
)
/*
EXT_texture_buffer_object: New multitexture texture buffer command
prefixes "Multi" before "Tex" and add an initial "enum texunit"
parameter (to identify the texture unit).
*/
DependsOn("GL_EXT_texture_buffer_object")..void(
"MultiTexBufferEXT",
"",
GLenum("texunit", ""),
GLenum("target", ""),
GLenum("internalformat", ""),
GLuint("buffer", "")
)
/*
EXT_texture_integer: New integer texture object commands and queries
replace "Tex" in name with "Texture" and add initial "uint texture"
parameter
*/
DependsOn("GL_EXT_texture_integer")..void(
"TextureParameterIivEXT",
"",
GLuint("texture", ""),
GLenum("target", ""),
GLenum("pname", ""),
Check(4)..GLint.const.p("params", "")
)
DependsOn("GL_EXT_texture_integer")..void(
"TextureParameterIuivEXT",
"",
GLuint("texture", ""),
GLenum("target", ""),
GLenum("pname", ""),
Check(4)..GLuint.const.p("params", "")
)
DependsOn("GL_EXT_texture_integer")..void(
"GetTextureParameterIivEXT",
"",
GLuint("texture", ""),
GLenum("target", ""),
GLenum("pname", ""),
Check(1)..ReturnParam..GLint.p("params", "")
)
DependsOn("GL_EXT_texture_integer")..void(
"GetTextureParameterIuivEXT",
"",
GLuint("texture", ""),
GLenum("target", ""),
GLenum("pname", ""),
Check(1)..ReturnParam..GLuint.p("params", "")
)
/*
EXT_texture_integer: New multitexture integer texture commands and
queries prefix "Multi" before "Tex" and add an initial "enum texunit"
parameter (to identify the texture unit).
*/
DependsOn("GL_EXT_texture_integer")..void(
"MultiTexParameterIivEXT",
"",
GLenum("texunit", ""),
GLenum("target", ""),
GLenum("pname", ""),
Check(4)..GLint.const.p("params", "")
)
DependsOn("GL_EXT_texture_integer")..void(
"MultiTexParameterIuivEXT",
"",
GLenum("texunit", ""),
GLenum("target", ""),
GLenum("pname", ""),
Check(4)..GLuint.const.p("params", "")
)
DependsOn("GL_EXT_texture_integer")..void(
"GetMultiTexParameterIivEXT",
"",
GLenum("texunit", ""),
GLenum("target", ""),
GLenum("pname", ""),
Check(1)..ReturnParam..GLint.p("params", "")
)
DependsOn("GL_EXT_texture_integer")..void(
"GetMultiTexParameterIuivEXT",
"",
GLenum("texunit", ""),
GLenum("target", ""),
GLenum("pname", ""),
Check(1)..ReturnParam..GLuint.p("params", "")
)
/*
EXT_gpu_shader4: New integer uniform commands add "Program" prefix
to name and add initial "uint program" parameter
*/
DependsOn("GL_EXT_gpu_shader4")..void(
"ProgramUniform1uiEXT",
"",
GLuint("program", ""),
GLint("location", ""),
GLuint("v0", "")
)
DependsOn("GL_EXT_gpu_shader4")..void(
"ProgramUniform2uiEXT",
"",
GLuint("program", ""),
GLint("location", ""),
GLuint("v0", ""),
GLuint("v1", "")
)
DependsOn("GL_EXT_gpu_shader4")..void(
"ProgramUniform3uiEXT",
"",
GLuint("program", ""),
GLint("location", ""),
GLuint("v0", ""),
GLuint("v1", ""),
GLuint("v2", "")
)
DependsOn("GL_EXT_gpu_shader4")..void(
"ProgramUniform4uiEXT",
"",
GLuint("program", ""),
GLint("location", ""),
GLuint("v0", ""),
GLuint("v1", ""),
GLuint("v2", ""),
GLuint("v3", "")
)
DependsOn("GL_EXT_gpu_shader4")..void(
"ProgramUniform1uivEXT",
"",
GLuint("program", ""),
GLint("location", ""),
AutoSize("value")..GLsizei("count", ""),
GLuint.const.p("value", "")
)
DependsOn("GL_EXT_gpu_shader4")..void(
"ProgramUniform2uivEXT",
"",
GLuint("program", ""),
GLint("location", ""),
AutoSize(2, "value")..GLsizei("count", ""),
GLuint.const.p("value", "")
)
DependsOn("GL_EXT_gpu_shader4")..void(
"ProgramUniform3uivEXT",
"",
GLuint("program", ""),
GLint("location", ""),
AutoSize(3, "value")..GLsizei("count", ""),
GLuint.const.p("value", "")
)
DependsOn("GL_EXT_gpu_shader4")..void(
"ProgramUniform4uivEXT",
"",
GLuint("program", ""),
GLint("location", ""),
AutoSize(4, "value")..GLsizei("count", ""),
GLuint.const.p("value", "")
)
/*
EXT_gpu_program_parameters: New program command adds "Named" prefix
to name and adds "uint program" parameter
*/
DependsOn("GL_EXT_gpu_program_parameters")..void(
"NamedProgramLocalParameters4fvEXT",
"",
GLuint("program", ""),
GLenum("target", ""),
GLuint("index", ""),
AutoSize(4, "params")..GLsizei("count", ""),
GLfloat.const.p("params", "")
)
/*
NV_gpu_program4: New program commands and queries add "Named"
prefix to name and replace "enum target" with "uint program"
*/
DependsOn("GL_NV_gpu_program4")..void(
"NamedProgramLocalParameterI4iEXT",
"",
GLuint("program", ""),
GLenum("target", ""),
GLuint("index", ""),
GLint("x", ""),
GLint("y", ""),
GLint("z", ""),
GLint("w", "")
)
DependsOn("GL_NV_gpu_program4")..void(
"NamedProgramLocalParameterI4ivEXT",
"",
GLuint("program", ""),
GLenum("target", ""),
GLuint("index", ""),
Check(4)..GLint.const.p("params", "")
)
DependsOn("GL_NV_gpu_program4")..void(
"NamedProgramLocalParametersI4ivEXT",
"",
GLuint("program", ""),
GLenum("target", ""),
GLuint("index", ""),
AutoSize(4, "params")..GLsizei("count", ""),
GLint.const.p("params", "")
)
DependsOn("GL_NV_gpu_program4")..void(
"NamedProgramLocalParameterI4uiEXT",
"",
GLuint("program", ""),
GLenum("target", ""),
GLuint("index", ""),
GLuint("x", ""),
GLuint("y", ""),
GLuint("z", ""),
GLuint("w", "")
)
DependsOn("GL_NV_gpu_program4")..void(
"NamedProgramLocalParameterI4uivEXT",
"",
GLuint("program", ""),
GLenum("target", ""),
GLuint("index", ""),
Check(4)..GLuint.const.p("params", "")
)
DependsOn("GL_NV_gpu_program4")..void(
"NamedProgramLocalParametersI4uivEXT",
"",
GLuint("program", ""),
GLenum("target", ""),
GLuint("index", ""),
AutoSize(4, "params")..GLsizei("count", ""),
GLuint.const.p("params", "")
)
DependsOn("GL_NV_gpu_program4")..void(
"GetNamedProgramLocalParameterIivEXT",
"",
GLuint("program", ""),
GLenum("target", ""),
GLuint("index", ""),
Check(4)..GLint.p("params", "")
)
DependsOn("GL_NV_gpu_program4")..void(
"GetNamedProgramLocalParameterIuivEXT",
"",
GLuint("program", ""),
GLenum("target", ""),
GLuint("index", ""),
Check(4)..GLuint.p("params", "")
)
/*
OpenGL 3.0: New renderbuffer commands add "Named" prefix to name
and replace "enum target" with "uint renderbuffer"
*/
DependsOn("OpenGL30")..void(
"NamedRenderbufferStorageEXT",
"",
GLuint("renderbuffer", ""),
GLenum("internalformat", ""),
GLsizei("width", ""),
GLsizei("height", "")
)
DependsOn("OpenGL30")..void(
"GetNamedRenderbufferParameterivEXT",
"",
GLuint("renderbuffer", ""),
GLenum("pname", ""),
Check(1)..ReturnParam..GLint.p("params", "")
)
/*
OpenGL 3.0: New renderbuffer commands add "Named"
prefix to name and replace "enum target" with "uint renderbuffer"
*/
DependsOn("OpenGL30")..void(
"NamedRenderbufferStorageMultisampleEXT",
"",
GLuint("renderbuffer", ""),
GLsizei("samples", ""),
GLenum("internalformat", ""),
GLsizei("width", ""),
GLsizei("height", "")
)
/*
NV_framebuffer_multisample_coverage: New renderbuffer commands
add "Named" prefix to name and replace "enum target" with "uint
renderbuffer"
*/
DependsOn("GL_NV_framebuffer_multisample_coverage")..void(
"NamedRenderbufferStorageMultisampleCoverageEXT",
"",
GLuint("renderbuffer", ""),
GLsizei("coverageSamples", ""),
GLsizei("colorSamples", ""),
GLenum("internalformat", ""),
GLsizei("width", ""),
GLsizei("height", "")
)
/*
OpenGL 3.0: New framebuffer commands add "Named" prefix to name
and replace "enum target" with "uint framebuffer"
*/
DependsOn("OpenGL30")..GLenum(
"CheckNamedFramebufferStatusEXT",
"",
GLuint("framebuffer", ""),
GLenum("target", "")
)
DependsOn("OpenGL30")..void(
"NamedFramebufferTexture1DEXT",
"",
GLuint("framebuffer", ""),
GLenum("attachment", ""),
GLenum("textarget", ""),
GLuint("texture", ""),
GLint("level", "")
)
DependsOn("OpenGL30")..void(
"NamedFramebufferTexture2DEXT",
"",
GLuint("framebuffer", ""),
GLenum("attachment", ""),
GLenum("textarget", ""),
GLuint("texture", ""),
GLint("level", "")
)
DependsOn("OpenGL30")..void(
"NamedFramebufferTexture3DEXT",
"",
GLuint("framebuffer", ""),
GLenum("attachment", ""),
GLenum("textarget", ""),
GLuint("texture", ""),
GLint("level", ""),
GLint("zoffset", "")
)
DependsOn("OpenGL30")..void(
"NamedFramebufferRenderbufferEXT",
"",
GLuint("framebuffer", ""),
GLenum("attachment", ""),
GLenum("renderbuffertarget", ""),
GLuint("renderbuffer", "")
)
DependsOn("OpenGL30")..void(
"GetNamedFramebufferAttachmentParameterivEXT",
"",
GLuint("framebuffer", ""),
GLenum("attachment", ""),
GLenum("pname", ""),
Check(1)..ReturnParam..GLint.p("params", "")
)
/*
OpenGL 3.0: New texture commands add "Texture" within name and
replace "enum target" with "uint texture"
*/
DependsOn("OpenGL30")..void(
"GenerateTextureMipmapEXT",
"",
GLuint("texture", ""),
GLenum("target", "")
)
/*
OpenGL 3.0: New texture commands add "MultiTex" within name and
replace "enum target" with "enum texunit"
*/
DependsOn("OpenGL30")..void(
"GenerateMultiTexMipmapEXT",
"",
GLenum("texunit", ""),
GLenum("target", "")
)
// OpenGL 3.0: New framebuffer commands
DependsOn("OpenGL30")..void(
"FramebufferDrawBufferEXT",
"",
GLuint("framebuffer", ""),
GLenum("mode", "")
)
DependsOn("OpenGL30")..void(
"FramebufferDrawBuffersEXT",
"",
GLuint("framebuffer", ""),
AutoSize("bufs")..GLsizei("n", ""),
GLenum.const.p("bufs", "")
)
DependsOn("OpenGL30")..void(
"FramebufferReadBufferEXT",
"",
GLuint("framebuffer", ""),
GLenum("mode", "")
)
// OpenGL 3.0: New framebuffer query
DependsOn("OpenGL30")..void(
"GetFramebufferParameterivEXT",
"",
GLuint("framebuffer", ""),
GLenum("pname", ""),
Check(1)..ReturnParam..GLint.p("param", "")
)
// OpenGL 3.0: New buffer data copy command
DependsOn("OpenGL30")..void(
"NamedCopyBufferSubDataEXT",
"",
GLuint("readBuffer", ""),
GLuint("writeBuffer", ""),
GLintptr("readOffset", ""),
GLintptr("writeOffset", ""),
GLsizeiptr("size", "")
)
/*
EXT_geometry_shader4 or NV_gpu_program4: New framebuffer commands
add "Named" prefix to name and replace "enum target" with "uint
framebuffer"
*/
DependsOn("ext.contains(\"GL_EXT_geometry_shader4\") || ext.contains(\"GL_NV_gpu_program4\")")..void(
"NamedFramebufferTextureEXT",
"",
GLuint("framebuffer", ""),
GLenum("attachment", ""),
GLuint("texture", ""),
GLint("level", "")
)
DependsOn("ext.contains(\"GL_EXT_geometry_shader4\") || ext.contains(\"GL_NV_gpu_program4\")")..void(
"NamedFramebufferTextureLayerEXT",
"",
GLuint("framebuffer", ""),
GLenum("attachment", ""),
GLuint("texture", ""),
GLint("level", ""),
GLint("layer", "")
)
DependsOn("ext.contains(\"GL_EXT_geometry_shader4\") || ext.contains(\"GL_NV_gpu_program4\")")..void(
"NamedFramebufferTextureFaceEXT",
"",
GLuint("framebuffer", ""),
GLenum("attachment", ""),
GLuint("texture", ""),
GLint("level", ""),
GLenum("face", "")
)
/*
NV_explicit_multisample: New texture renderbuffer object command
replaces "Tex" in name with "Texture" and add initial "uint texture"
parameter
*/
DependsOn("GL_NV_explicit_multisample")..void(
"TextureRenderbufferEXT",
"",
GLuint("texture", ""),
GLenum("target", ""),
GLuint("renderbuffer", "")
)
/*
NV_explicit_multisample: New multitexture texture renderbuffer command
prefixes "Multi" before "Tex" and add an initial "enum texunit"
parameter (to identify the texture unit)
*/
DependsOn("GL_NV_explicit_multisample")..void(
"MultiTexRenderbufferEXT",
"",
GLenum("texunit", ""),
GLenum("target", ""),
GLuint("renderbuffer", "")
)
/*
OpenGL 3.0: New vertex array specification commands for vertex
array objects prefix "VertexArray", add initial "uint vaobj" and
"uint buffer" parameters, change "Pointer" suffix to "Offset",
and change the final parameter from "const void *" to "intptr offset"
*/
DependsOn("OpenGL30")..void(
"VertexArrayVertexOffsetEXT",
"",
GLuint("vaobj", ""),
GLuint("buffer", ""),
GLint("size", ""),
GLenum("type", ""),
GLsizei("stride", ""),
GLintptr("offset", "")
)
DependsOn("OpenGL30")..void(
"VertexArrayColorOffsetEXT",
"",
GLuint("vaobj", ""),
GLuint("buffer", ""),
GLint("size", ""),
GLenum("type", ""),
GLsizei("stride", ""),
GLintptr("offset", "")
)
DependsOn("OpenGL30")..void(
"VertexArrayEdgeFlagOffsetEXT",
"",
GLuint("vaobj", ""),
GLuint("buffer", ""),
GLsizei("stride", ""),
GLintptr("offset", "")
)
DependsOn("OpenGL30")..void(
"VertexArrayIndexOffsetEXT",
"",
GLuint("vaobj", ""),
GLuint("buffer", ""),
GLenum("type", ""),
GLsizei("stride", ""),
GLintptr("offset", "")
)
DependsOn("OpenGL30")..void(
"VertexArrayNormalOffsetEXT",
"",
GLuint("vaobj", ""),
GLuint("buffer", ""),
GLenum("type", ""),
GLsizei("stride", ""),
GLintptr("offset", "")
)
DependsOn("OpenGL30")..void(
"VertexArrayTexCoordOffsetEXT",
"",
GLuint("vaobj", ""),
GLuint("buffer", ""),
GLint("size", ""),
GLenum("type", ""),
GLsizei("stride", ""),
GLintptr("offset", "")
)
DependsOn("OpenGL30")..void(
"VertexArrayMultiTexCoordOffsetEXT",
"",
GLuint("vaobj", ""),
GLuint("buffer", ""),
GLenum("texunit", ""),
GLint("size", ""),
GLenum("type", ""),
GLsizei("stride", ""),
GLintptr("offset", "")
)
DependsOn("OpenGL30")..void(
"VertexArrayFogCoordOffsetEXT",
"",
GLuint("vaobj", ""),
GLuint("buffer", ""),
GLenum("type", ""),
GLsizei("stride", ""),
GLintptr("offset", "")
)
DependsOn("OpenGL30")..void(
"VertexArraySecondaryColorOffsetEXT",
"",
GLuint("vaobj", ""),
GLuint("buffer", ""),
GLint("size", ""),
GLenum("type", ""),
GLsizei("stride", ""),
GLintptr("offset", "")
)
DependsOn("OpenGL30")..void(
"VertexArrayVertexAttribOffsetEXT",
"",
GLuint("vaobj", ""),
GLuint("buffer", ""),
GLuint("index", ""),
GLint("size", ""),
GLenum("type", ""),
GLboolean("normalized", ""),
GLsizei("stride", ""),
GLintptr("offset", "")
)
DependsOn("OpenGL30")..void(
"VertexArrayVertexAttribIOffsetEXT",
"",
GLuint("vaobj", ""),
GLuint("buffer", ""),
GLuint("index", ""),
GLint("size", ""),
GLenum("type", ""),
GLsizei("stride", ""),
GLintptr("offset", "")
)
/*
OpenGL 3.0: New vertex array enable commands for vertex array
objects change "ClientState" to "VertexArray" and add an initial
"uint vaobj" parameter
*/
DependsOn("OpenGL30")..void(
"EnableVertexArrayEXT",
"",
GLuint("vaobj", ""),
GLenum("array", "")
)
DependsOn("OpenGL30")..void(
"DisableVertexArrayEXT",
"",
GLuint("vaobj", ""),
GLenum("array", "")
)
/*
OpenGL 3.0: New vertex attrib array enable commands for vertex
array objects change "VertexAttribArray" to "VertexArrayAttrib"
and add an initial "uint vaobj" parameter
*/
DependsOn("OpenGL30")..void(
"EnableVertexArrayAttribEXT",
"",
GLuint("vaobj", ""),
GLuint("index", "")
)
DependsOn("OpenGL30")..void(
"DisableVertexArrayAttribEXT",
"",
GLuint("vaobj", ""),
GLuint("index", "")
)
// OpenGL 3.0: New queries for vertex array objects
DependsOn("OpenGL30")..void(
"GetVertexArrayIntegervEXT",
"",
GLuint("vaobj", ""),
GLenum("pname", ""),
Check(1)..ReturnParam..GLint.p("param", "")
)
DependsOn("OpenGL30")..void(
"GetVertexArrayPointervEXT",
"",
GLuint("vaobj", ""),
GLenum("pname", ""),
Check(1)..ReturnParam..void.p.p("param", "")
)
DependsOn("OpenGL30")..void(
"GetVertexArrayIntegeri_vEXT",
"",
GLuint("vaobj", ""),
GLuint("index", ""),
GLenum("pname", ""),
Check(1)..ReturnParam..GLint.p("param", "")
)
DependsOn("OpenGL30")..void(
"GetVertexArrayPointeri_vEXT",
"",
GLuint("vaobj", ""),
GLuint("index", ""),
GLenum("pname", ""),
Check(1)..ReturnParam..void.p.p("param", "")
)
/*
OpenGL 3.0: New buffer commands replace "Buffer" with "NamedBuffer"
in name and replace "enum target" parameter with "uint buffer"
*/
DependsOn("OpenGL30")..MapPointer("length", oldBufferOverloads = true)..void.p(
"MapNamedBufferRangeEXT",
"",
GLuint("buffer", ""),
GLintptr("offset", ""),
GLsizeiptr("length", ""),
GLbitfield("access", "")
)
DependsOn("OpenGL30")..void(
"FlushMappedNamedBufferRangeEXT",
"",
GLuint("buffer", ""),
GLintptr("offset", ""),
GLsizeiptr("length", "")
)
} | bsd-3-clause | a865c69c3214c1eb0d09decb5b3666a5 | 25.895141 | 160 | 0.529391 | 4.715631 | false | false | false | false |
dbrant/apps-android-wikipedia | app/src/main/java/org/wikipedia/suggestededits/SuggestedEditsImageTagsFragment.kt | 1 | 19625 | package org.wikipedia.suggestededits
import android.content.res.ColorStateList
import android.graphics.Color
import android.graphics.Typeface
import android.os.Bundle
import android.text.method.LinkMovementMethod
import android.view.HapticFeedbackConstants
import android.view.LayoutInflater
import android.view.View
import android.view.View.*
import android.view.ViewGroup
import android.widget.CompoundButton
import android.widget.Toast
import androidx.core.view.children
import com.google.android.material.chip.Chip
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers
import io.reactivex.rxjava3.schedulers.Schedulers
import org.wikipedia.Constants
import org.wikipedia.Constants.InvokeSource
import org.wikipedia.R
import org.wikipedia.WikipediaApp
import org.wikipedia.activity.FragmentUtil
import org.wikipedia.analytics.EditFunnel
import org.wikipedia.analytics.SuggestedEditsFunnel
import org.wikipedia.csrf.CsrfTokenClient
import org.wikipedia.databinding.FragmentSuggestedEditsImageTagsItemBinding
import org.wikipedia.dataclient.Service
import org.wikipedia.dataclient.ServiceFactory
import org.wikipedia.dataclient.WikiSite
import org.wikipedia.dataclient.mwapi.MwQueryPage
import org.wikipedia.dataclient.mwapi.media.MediaHelper
import org.wikipedia.descriptions.DescriptionEditActivity.Action.ADD_IMAGE_TAGS
import org.wikipedia.page.PageTitle
import org.wikipedia.settings.Prefs
import org.wikipedia.suggestededits.provider.EditingSuggestionsProvider
import org.wikipedia.util.*
import org.wikipedia.util.L10nUtil.setConditionalLayoutDirection
import org.wikipedia.util.log.L
import org.wikipedia.views.ImageZoomHelper
import org.wikipedia.views.ViewUtil
import java.util.*
import kotlin.collections.ArrayList
class SuggestedEditsImageTagsFragment : SuggestedEditsItemFragment(), CompoundButton.OnCheckedChangeListener, OnClickListener, SuggestedEditsImageTagDialog.Callback {
private var _binding: FragmentSuggestedEditsImageTagsItemBinding? = null
private val binding get() = _binding!!
var publishing: Boolean = false
var publishSuccess: Boolean = false
private var page: MwQueryPage? = null
private val tagList: MutableList<MwQueryPage.ImageLabel> = ArrayList()
private var wasCaptionLongClicked: Boolean = false
private var lastSearchTerm: String = ""
var invokeSource: InvokeSource = InvokeSource.SUGGESTED_EDITS
private var funnel: EditFunnel? = null
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
super.onCreateView(inflater, container, savedInstanceState)
_binding = FragmentSuggestedEditsImageTagsItemBinding.inflate(inflater, container, false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
setConditionalLayoutDirection(binding.contentContainer, callback().getLangCode())
binding.cardItemErrorView.backClickListener = OnClickListener { requireActivity().finish() }
binding.cardItemErrorView.retryClickListener = OnClickListener {
binding.cardItemProgressBar.visibility = VISIBLE
binding.cardItemErrorView.visibility = GONE
getNextItem()
}
val transparency = 0xcc000000
binding.tagsContainer.setBackgroundColor(transparency.toInt() or (ResourceUtil.getThemedColor(requireContext(), R.attr.paper_color) and 0xffffff))
binding.imageCaption.setBackgroundColor(transparency.toInt() or (ResourceUtil.getThemedColor(requireContext(), R.attr.paper_color) and 0xffffff))
binding.publishOverlayContainer.setBackgroundColor(transparency.toInt() or (ResourceUtil.getThemedColor(requireContext(), R.attr.paper_color) and 0xffffff))
binding.publishOverlayContainer.visibility = GONE
val colorStateList = ColorStateList(arrayOf(intArrayOf()),
intArrayOf(if (WikipediaApp.getInstance().currentTheme.isDark) Color.WHITE else ResourceUtil.getThemedColor(requireContext(), R.attr.colorAccent)))
binding.publishProgressBar.progressTintList = colorStateList
binding.publishProgressBarComplete.progressTintList = colorStateList
binding.publishProgressCheck.imageTintList = colorStateList
binding.publishProgressText.setTextColor(colorStateList)
binding.tagsLicenseText.text = StringUtil.fromHtml(getString(R.string.suggested_edits_cc0_notice,
getString(R.string.terms_of_use_url), getString(R.string.cc_0_url)))
binding.tagsLicenseText.movementMethod = LinkMovementMethod.getInstance()
binding.imageView.setOnClickListener {
if (Prefs.shouldShowImageZoomTooltip()) {
Prefs.setShouldShowImageZoomTooltip(false)
FeedbackUtil.showToastOverView(binding.imageView, getString(R.string.suggested_edits_image_zoom_tooltip), Toast.LENGTH_LONG)
}
}
if (callback().getSinglePage() != null) {
page = callback().getSinglePage()
}
binding.imageCaption.setOnLongClickListener {
wasCaptionLongClicked = true
false
}
getNextItem()
updateContents()
updateTagChips()
}
override fun onStart() {
super.onStart()
callback().updateActionButton()
}
override fun onDestroyView() {
super.onDestroyView()
_binding = null
}
private fun getNextItem() {
if (page != null) {
return
}
disposables.add(EditingSuggestionsProvider.getNextImageWithMissingTags()
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe({ page ->
this.page = page
updateContents()
updateTagChips()
}, { this.setErrorState(it) })!!)
}
private fun setErrorState(t: Throwable) {
L.e(t)
binding.cardItemErrorView.setError(t)
binding.cardItemErrorView.visibility = VISIBLE
binding.cardItemProgressBar.visibility = GONE
binding.contentContainer.visibility = GONE
}
private fun updateContents() {
binding.cardItemErrorView.visibility = GONE
binding.contentContainer.visibility = if (page != null) VISIBLE else GONE
binding.cardItemProgressBar.visibility = if (page != null) GONE else VISIBLE
if (page == null) {
return
}
funnel = EditFunnel(WikipediaApp.getInstance(), PageTitle(page!!.title(), WikiSite(Service.COMMONS_URL)))
binding.tagsLicenseText.visibility = GONE
binding.tagsHintText.visibility = VISIBLE
ImageZoomHelper.setViewZoomable(binding.imageView)
ViewUtil.loadImage(binding.imageView, ImageUrlUtil.getUrlForPreferredSize(page!!.imageInfo()!!.thumbUrl, Constants.PREFERRED_CARD_THUMBNAIL_SIZE))
disposables.add(MediaHelper.getImageCaptions(page!!.title())
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe { captions ->
if (captions.containsKey(callback().getLangCode())) {
binding.imageCaption.text = captions[callback().getLangCode()]
binding.imageCaption.visibility = VISIBLE
} else {
if (page!!.imageInfo() != null && page!!.imageInfo()!!.metadata != null) {
binding.imageCaption.text = StringUtil.fromHtml(page!!.imageInfo()!!.metadata!!.imageDescription()).toString().trim()
binding.imageCaption.visibility = VISIBLE
} else {
binding.imageCaption.visibility = GONE
}
}
})
updateLicenseTextShown()
callback().updateActionButton()
}
private fun updateTagChips() {
val typeface = Typeface.create("sans-serif-medium", Typeface.NORMAL)
binding.tagsChipGroup.removeAllViews()
if (!publishSuccess) {
// add an artificial chip for adding a custom tag
addChip(null, typeface)
}
for (label in tagList) {
val chip = addChip(label, typeface)
chip.isChecked = label.isSelected
if (publishSuccess) {
chip.isEnabled = false
if (chip.isChecked) {
chip.setChipBackgroundColorResource(ResourceUtil.getThemedAttributeId(requireContext(), R.attr.color_group_57))
chip.setChipStrokeColorResource(ResourceUtil.getThemedAttributeId(requireContext(), R.attr.color_group_58))
} else {
chip.setChipBackgroundColorResource(ResourceUtil.getThemedAttributeId(requireContext(), R.attr.chip_background_color))
chip.setChipStrokeColorResource(ResourceUtil.getThemedAttributeId(requireContext(), R.attr.chip_background_color))
}
}
}
updateLicenseTextShown()
callback().updateActionButton()
}
private fun addChip(label: MwQueryPage.ImageLabel?, typeface: Typeface): Chip {
val chip = Chip(requireContext())
chip.text = label?.label ?: getString(R.string.suggested_edits_image_tags_add_tag)
chip.textAlignment = TEXT_ALIGNMENT_CENTER
chip.setChipBackgroundColorResource(ResourceUtil.getThemedAttributeId(requireContext(), R.attr.chip_background_color))
chip.chipStrokeWidth = DimenUtil.dpToPx(1f)
chip.setChipStrokeColorResource(ResourceUtil.getThemedAttributeId(requireContext(), R.attr.chip_background_color))
chip.setTextColor(ResourceUtil.getThemedColor(requireContext(), R.attr.material_theme_primary_color))
chip.typeface = typeface
chip.isCheckable = true
chip.setChipIconResource(R.drawable.ic_chip_add_24px)
chip.iconEndPadding = 0f
chip.textStartPadding = DimenUtil.dpToPx(2f)
chip.chipIconSize = DimenUtil.dpToPx(24f)
chip.chipIconTint = ColorStateList.valueOf(ResourceUtil.getThemedColor(requireContext(), R.attr.material_theme_de_emphasised_color))
chip.setCheckedIconResource(R.drawable.ic_chip_check_24px)
chip.setOnCheckedChangeListener(this)
chip.setOnClickListener(this)
chip.setEnsureMinTouchTargetSize(true)
chip.ensureAccessibleTouchTarget(DimenUtil.dpToPx(48f).toInt())
chip.tag = label
if (label != null) {
chip.isChecked = label.isSelected
}
// add some padding to the Chip, since our container view doesn't support item spacing yet.
val params = ViewGroup.MarginLayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT)
val margin = DimenUtil.roundedDpToPx(8f)
params.setMargins(margin, 0, margin, 0)
chip.layoutParams = params
binding.tagsChipGroup.addView(chip)
return chip
}
companion object {
fun newInstance(): SuggestedEditsItemFragment {
return SuggestedEditsImageTagsFragment()
}
}
override fun onClick(v: View?) {
val chip = v as Chip
if (chip.tag == null) {
// they clicked the chip to add a new tag, so cancel out the check changing...
chip.isChecked = !chip.isChecked
// and launch the selection dialog for the custom tag.
SuggestedEditsImageTagDialog.newInstance(wasCaptionLongClicked, lastSearchTerm).show(childFragmentManager, null)
}
}
override fun onCheckedChanged(button: CompoundButton?, isChecked: Boolean) {
val chip = button as Chip
if (chip.isChecked) {
chip.setChipBackgroundColorResource(ResourceUtil.getThemedAttributeId(requireContext(), R.attr.color_group_55))
chip.setChipStrokeColorResource(ResourceUtil.getThemedAttributeId(requireContext(), R.attr.color_group_56))
chip.isChipIconVisible = false
} else {
chip.setChipBackgroundColorResource(ResourceUtil.getThemedAttributeId(requireContext(), R.attr.chip_background_color))
chip.setChipStrokeColorResource(ResourceUtil.getThemedAttributeId(requireContext(), R.attr.chip_background_color))
chip.isChipIconVisible = true
}
if (chip.tag != null) {
(chip.tag as MwQueryPage.ImageLabel).isSelected = chip.isChecked
}
updateLicenseTextShown()
callback().updateActionButton()
}
override fun onSearchSelect(item: MwQueryPage.ImageLabel) {
var exists = false
for (tag in tagList) {
if (tag.wikidataId == item.wikidataId) {
exists = true
tag.isSelected = true
break
}
}
if (!exists) {
item.isSelected = true
tagList.add(item)
}
updateTagChips()
}
override fun onSearchDismiss(searchTerm: String) {
lastSearchTerm = searchTerm
}
override fun publish() {
if (publishing || publishSuccess || binding.tagsChipGroup.childCount == 0) {
return
}
val acceptedLabels = ArrayList<MwQueryPage.ImageLabel>()
val iterator = tagList.iterator()
while (iterator.hasNext()) {
val tag = iterator.next()
if (tag.isSelected) {
acceptedLabels.add(tag)
} else {
iterator.remove()
}
}
if (acceptedLabels.isEmpty()) {
return
}
// -- point of no return --
publishing = true
publishSuccess = false
funnel?.logSaveAttempt()
binding.publishProgressText.setText(R.string.suggested_edits_image_tags_publishing)
binding.publishProgressCheck.visibility = GONE
binding.publishOverlayContainer.visibility = VISIBLE
binding.publishProgressBarComplete.visibility = GONE
binding.publishProgressBar.visibility = VISIBLE
val commonsSite = WikiSite(Service.COMMONS_URL)
disposables.add(CsrfTokenClient(WikiSite(Service.COMMONS_URL)).token
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe({ token ->
val mId = "M" + page!!.pageId()
var claimStr = "{\"claims\":["
var commentStr = "/* add-depicts: "
var first = true
for (label in acceptedLabels) {
if (!first) {
claimStr += ","
}
if (!first) {
commentStr += ","
}
first = false
claimStr += "{\"mainsnak\":" +
"{\"snaktype\":\"value\",\"property\":\"P180\"," +
"\"datavalue\":{\"value\":" +
"{\"entity-type\":\"item\",\"id\":\"${label.wikidataId}\"}," +
"\"type\":\"wikibase-entityid\"},\"datatype\":\"wikibase-item\"}," +
"\"type\":\"statement\"," +
"\"id\":\"${mId}\$${UUID.randomUUID()}\"," +
"\"rank\":\"normal\"}"
commentStr += label.wikidataId + "|" + label.label.replace("|", "").replace(",", "")
}
claimStr += "]}"
commentStr += " */"
disposables.add(ServiceFactory.get(commonsSite).postEditEntity(mId, token, claimStr, commentStr, null)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.doAfterTerminate {
publishing = false
}
.subscribe({
if (it.entity != null) {
funnel?.logSaved(it.entity!!.lastRevId, invokeSource.getName())
}
publishSuccess = true
onSuccess()
}, { caught ->
onError(caught)
})
)
}, {
onError(it)
}))
}
private fun onSuccess() {
SuggestedEditsFunnel.get()!!.success(ADD_IMAGE_TAGS)
val duration = 500L
binding.publishProgressBar.alpha = 1f
binding.publishProgressBar.animate()
.alpha(0f)
.duration = duration / 2
binding.publishProgressBarComplete.alpha = 0f
binding.publishProgressBarComplete.visibility = VISIBLE
binding.publishProgressBarComplete.animate()
.alpha(1f)
.withEndAction {
binding.publishProgressText.setText(R.string.suggested_edits_image_tags_published)
playSuccessVibration()
}
.duration = duration / 2
binding.publishProgressCheck.alpha = 0f
binding.publishProgressCheck.visibility = VISIBLE
binding.publishProgressCheck.animate()
.alpha(1f)
.duration = duration
binding.publishProgressBar.postDelayed({
if (isAdded) {
updateLicenseTextShown()
binding.publishOverlayContainer.visibility = GONE
callback().nextPage(this)
callback().logSuccess()
updateTagChips()
}
}, duration * 3)
}
private fun onError(caught: Throwable) {
// TODO: expand this a bit.
SuggestedEditsFunnel.get()!!.failure(ADD_IMAGE_TAGS)
funnel?.logError(caught.localizedMessage)
binding.publishOverlayContainer.visibility = GONE
FeedbackUtil.showError(requireActivity(), caught)
}
private fun playSuccessVibration() {
binding.imageView.performHapticFeedback(HapticFeedbackConstants.LONG_PRESS)
}
private fun updateLicenseTextShown() {
when {
publishSuccess -> {
binding.tagsLicenseText.visibility = GONE
binding.tagsHintText.setText(R.string.suggested_edits_image_tags_published_list)
binding.tagsHintText.visibility = VISIBLE
}
atLeastOneTagChecked() -> {
binding.tagsLicenseText.visibility = VISIBLE
binding.tagsHintText.visibility = GONE
}
else -> {
binding.tagsLicenseText.visibility = GONE
binding.tagsHintText.visibility = GONE
}
}
}
private fun atLeastOneTagChecked(): Boolean {
return binding.tagsChipGroup.children.filterIsInstance<Chip>().any { it.isChecked }
}
override fun publishEnabled(): Boolean {
return !publishSuccess && atLeastOneTagChecked()
}
override fun publishOutlined(): Boolean {
if (_binding == null) {
return false
}
return !atLeastOneTagChecked()
}
private fun callback(): Callback {
return FragmentUtil.getCallback(this, Callback::class.java)!!
}
}
| apache-2.0 | b0fe2419593aaf854e2e79fecad42808 | 40.84435 | 166 | 0.623185 | 5.523501 | false | false | false | false |
iSoron/uhabits | uhabits-core/src/jvmMain/java/org/isoron/uhabits/core/ui/screens/habits/show/views/HistoryCard.kt | 1 | 7624 | /*
* Copyright (C) 2016-2021 Álinson Santos Xavier <[email protected]>
*
* This file is part of Loop Habit Tracker.
*
* Loop Habit Tracker is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by the
* Free Software Foundation, either version 3 of the License, or (at your
* option) any later version.
*
* Loop Habit Tracker is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.isoron.uhabits.core.ui.screens.habits.show.views
import org.isoron.platform.time.DayOfWeek
import org.isoron.platform.time.LocalDate
import org.isoron.uhabits.core.commands.CommandRunner
import org.isoron.uhabits.core.commands.CreateRepetitionCommand
import org.isoron.uhabits.core.models.Entry
import org.isoron.uhabits.core.models.Entry.Companion.SKIP
import org.isoron.uhabits.core.models.Entry.Companion.YES_AUTO
import org.isoron.uhabits.core.models.Entry.Companion.YES_MANUAL
import org.isoron.uhabits.core.models.Habit
import org.isoron.uhabits.core.models.HabitList
import org.isoron.uhabits.core.models.NumericalHabitType.AT_LEAST
import org.isoron.uhabits.core.models.NumericalHabitType.AT_MOST
import org.isoron.uhabits.core.models.PaletteColor
import org.isoron.uhabits.core.models.Timestamp
import org.isoron.uhabits.core.preferences.Preferences
import org.isoron.uhabits.core.ui.screens.habits.list.ListHabitsBehavior
import org.isoron.uhabits.core.ui.views.HistoryChart
import org.isoron.uhabits.core.ui.views.HistoryChart.Square.DIMMED
import org.isoron.uhabits.core.ui.views.HistoryChart.Square.GREY
import org.isoron.uhabits.core.ui.views.HistoryChart.Square.HATCHED
import org.isoron.uhabits.core.ui.views.HistoryChart.Square.OFF
import org.isoron.uhabits.core.ui.views.HistoryChart.Square.ON
import org.isoron.uhabits.core.ui.views.OnDateClickedListener
import org.isoron.uhabits.core.ui.views.Theme
import org.isoron.uhabits.core.utils.DateUtils
import kotlin.math.roundToInt
data class HistoryCardState(
val color: PaletteColor,
val firstWeekday: DayOfWeek,
val series: List<HistoryChart.Square>,
val defaultSquare: HistoryChart.Square,
val notesIndicators: List<Boolean>,
val theme: Theme,
val today: LocalDate,
)
class HistoryCardPresenter(
val commandRunner: CommandRunner,
val habit: Habit,
val habitList: HabitList,
val preferences: Preferences,
val screen: Screen,
) : OnDateClickedListener {
override fun onDateLongPress(date: LocalDate) {
val timestamp = Timestamp.fromLocalDate(date)
screen.showFeedback()
if (habit.isNumerical) {
showNumberPopup(timestamp)
} else {
if (preferences.isShortToggleEnabled) showCheckmarkPopup(timestamp)
else toggle(timestamp)
}
}
override fun onDateShortPress(date: LocalDate) {
val timestamp = Timestamp.fromLocalDate(date)
screen.showFeedback()
if (habit.isNumerical) {
showNumberPopup(timestamp)
} else {
if (preferences.isShortToggleEnabled) toggle(timestamp)
else showCheckmarkPopup(timestamp)
}
}
private fun showCheckmarkPopup(timestamp: Timestamp) {
val entry = habit.computedEntries.get(timestamp)
screen.showCheckmarkPopup(
entry.value,
entry.notes,
preferences,
habit.color,
) { newValue, newNotes ->
commandRunner.run(
CreateRepetitionCommand(
habitList,
habit,
timestamp,
newValue,
newNotes,
),
)
}
}
private fun toggle(timestamp: Timestamp) {
val entry = habit.computedEntries.get(timestamp)
val nextValue = Entry.nextToggleValue(
value = entry.value,
isSkipEnabled = preferences.isSkipEnabled,
areQuestionMarksEnabled = preferences.areQuestionMarksEnabled
)
commandRunner.run(
CreateRepetitionCommand(
habitList,
habit,
timestamp,
nextValue,
entry.notes,
),
)
}
private fun showNumberPopup(timestamp: Timestamp) {
val entry = habit.computedEntries.get(timestamp)
val oldValue = entry.value
screen.showNumberPopup(
value = oldValue / 1000.0,
notes = entry.notes,
preferences = preferences,
) { newValue: Double, newNotes: String ->
val thousands = (newValue * 1000).roundToInt()
commandRunner.run(
CreateRepetitionCommand(
habitList,
habit,
timestamp,
thousands,
newNotes,
),
)
}
}
fun onClickEditButton() {
screen.showHistoryEditorDialog(this)
}
companion object {
fun buildState(
habit: Habit,
firstWeekday: DayOfWeek,
theme: Theme,
): HistoryCardState {
val today = DateUtils.getTodayWithOffset()
val oldest = habit.computedEntries.getKnown().lastOrNull()?.timestamp ?: today
val entries = habit.computedEntries.getByInterval(oldest, today)
val series = if (habit.isNumerical) {
entries.map {
when {
it.value == Entry.UNKNOWN -> OFF
it.value == SKIP -> HATCHED
(habit.targetType == AT_MOST) && (it.value / 1000.0 <= habit.targetValue) -> ON
(habit.targetType == AT_LEAST) && (it.value / 1000.0 >= habit.targetValue) -> ON
else -> GREY
}
}
} else {
entries.map {
when (it.value) {
YES_MANUAL -> ON
YES_AUTO -> DIMMED
SKIP -> HATCHED
else -> OFF
}
}
}
val notesIndicators = entries.map {
when (it.notes) {
"" -> false
else -> true
}
}
return HistoryCardState(
color = habit.color,
firstWeekday = firstWeekday,
today = today.toLocalDate(),
theme = theme,
series = series,
defaultSquare = OFF,
notesIndicators = notesIndicators,
)
}
}
interface Screen {
fun showHistoryEditorDialog(listener: OnDateClickedListener)
fun showFeedback()
fun showNumberPopup(
value: Double,
notes: String,
preferences: Preferences,
callback: ListHabitsBehavior.NumberPickerCallback,
)
fun showCheckmarkPopup(
selectedValue: Int,
notes: String,
preferences: Preferences,
color: PaletteColor,
callback: ListHabitsBehavior.CheckMarkDialogCallback,
)
}
}
| gpl-3.0 | 2c2f0821d6967103abf1ba63998dab5f | 34.129032 | 104 | 0.602125 | 4.905405 | false | false | false | false |
dahlstrom-g/intellij-community | platform/vcs-impl/src/com/intellij/openapi/vcs/changes/ui/ChangesGroupingSupport.kt | 7 | 4778 | // Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.openapi.vcs.changes.ui
import com.intellij.openapi.actionSystem.DataKey
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.ClearableLazyValue
import com.intellij.openapi.vcs.changes.ui.ChangesGroupingSupport.Companion.DIRECTORY_GROUPING
import com.intellij.openapi.vcs.changes.ui.ChangesGroupingSupport.Companion.MODULE_GROUPING
import com.intellij.openapi.vcs.changes.ui.ChangesGroupingSupport.Companion.REPOSITORY_GROUPING
import org.jetbrains.annotations.NonNls
import java.beans.PropertyChangeListener
import java.beans.PropertyChangeSupport
import javax.swing.tree.DefaultTreeModel
private val PREDEFINED_PRIORITIES = mapOf(DIRECTORY_GROUPING to 10, MODULE_GROUPING to 20, REPOSITORY_GROUPING to 30)
open class ChangesGroupingSupport(val project: Project, source: Any, val showConflictsNode: Boolean) {
private val changeSupport = PropertyChangeSupport(source)
private val _groupingKeys = mutableSetOf<String>()
val groupingKeys get() = _groupingKeys.toSet()
operator fun get(groupingKey: @NonNls String): Boolean {
if (!isAvailable(groupingKey)) return false
return _groupingKeys.contains(groupingKey)
}
operator fun set(groupingKey: String, state: Boolean) {
if (!isAvailable(groupingKey)) throw IllegalArgumentException("Unknown grouping $groupingKey") // NON-NLS
val currentState = _groupingKeys.contains(groupingKey)
if (currentState == state) return
val oldGroupingKeys = _groupingKeys.toSet()
if (state) {
_groupingKeys += groupingKey
}
else {
_groupingKeys -= groupingKey
}
changeSupport.firePropertyChange(PROP_GROUPING_KEYS, oldGroupingKeys, _groupingKeys.toSet())
}
val grouping: ChangesGroupingPolicyFactory get() = CombinedGroupingPolicyFactory()
val isNone: Boolean get() = _groupingKeys.isEmpty()
val isDirectory: Boolean get() = this[DIRECTORY_GROUPING]
fun setGroupingKeysOrSkip(newGroupingKeys: Set<String>) {
_groupingKeys.clear()
_groupingKeys += newGroupingKeys.filter { groupingKey -> isAvailable(groupingKey) }
}
open fun isAvailable(groupingKey: String) = findFactory(groupingKey) != null
fun addPropertyChangeListener(listener: PropertyChangeListener) {
changeSupport.addPropertyChangeListener(listener)
}
fun removePropertyChangeListener(listener: PropertyChangeListener) {
changeSupport.removePropertyChangeListener(listener)
}
private inner class CombinedGroupingPolicyFactory : ChangesGroupingPolicyFactory() {
override fun createGroupingPolicy(project: Project, model: DefaultTreeModel): ChangesGroupingPolicy {
var result = DefaultChangesGroupingPolicy.Factory(showConflictsNode).createGroupingPolicy(project, model)
_groupingKeys.sortedByDescending { PREDEFINED_PRIORITIES[it] }.forEach { groupingKey ->
val factory = findFactory(groupingKey) ?: throw IllegalArgumentException("Unknown grouping $groupingKey") // NON-NLS
result = factory.createGroupingPolicy(project, model).apply { setNextGroupingPolicy(result) }
}
return result
}
}
companion object {
@JvmField
val KEY = DataKey.create<ChangesGroupingSupport>("ChangesTree.GroupingSupport")
const val PROP_GROUPING_KEYS = "ChangesGroupingKeys" // NON-NLS
const val DIRECTORY_GROUPING = "directory" // NON-NLS
const val MODULE_GROUPING = "module" // NON-NLS
const val REPOSITORY_GROUPING = "repository" // NON-NLS
const val NONE_GROUPING = "none" // NON-NLS
private val FACTORIES = ClearableLazyValue.create { buildFactories() }
init {
ChangesGroupingPolicyFactory.EP_NAME.addChangeListener({ FACTORIES.drop() }, null)
}
@JvmStatic
fun getFactory(key: String): ChangesGroupingPolicyFactory {
return findFactory(key) ?: NoneChangesGroupingFactory
}
@JvmStatic
fun findFactory(key: String): ChangesGroupingPolicyFactory? {
return FACTORIES.value[key]
}
private fun buildFactories(): Map<String, ChangesGroupingPolicyFactory> {
val result = mutableMapOf<String, ChangesGroupingPolicyFactory>()
for (bean in ChangesGroupingPolicyFactory.EP_NAME.extensionList) {
val key = bean.key ?: continue
val clazz = bean.implementationClass ?: continue
try {
result[key] = ApplicationManager.getApplication().instantiateClass(clazz, bean.pluginDescriptor)
}
catch (e: Throwable) {
logger<ChangesGroupingSupport>().error(e)
}
}
return result
}
}
} | apache-2.0 | a5413b6fcc17b5b977d954771d5fd1f3 | 39.846154 | 140 | 0.752616 | 4.977083 | false | false | false | false |
dahlstrom-g/intellij-community | plugins/laf/macos/src/com/intellij/laf/macos/MacLafProvider.kt | 8 | 1062 | package com.intellij.laf.macos
import com.intellij.ide.ui.LafProvider
import com.intellij.ide.ui.laf.PluggableLafInfo
import com.intellij.ide.ui.laf.darcula.ui.DarculaEditorTextFieldBorder
import com.intellij.openapi.editor.ex.EditorEx
import com.intellij.openapi.util.NlsSafe
import com.intellij.ui.EditorTextField
import javax.swing.LookAndFeel
internal class MacLafProvider : LafProvider {
override fun getLookAndFeelInfo() = instance
private class MacOsLookAndFeelInfo : PluggableLafInfo(LAF_NAME, MacIntelliJLaf::class.java.name) {
override fun createLookAndFeel(): LookAndFeel = MacIntelliJLaf()
override fun createSearchAreaPainter(context: SearchAreaContext) = MacSearchPainter(context)
override fun createEditorTextFieldBorder(editorTextField: EditorTextField, editor: EditorEx): DarculaEditorTextFieldBorder {
return MacEditorTextFieldBorder(editorTextField, editor)
}
}
companion object {
@NlsSafe
const val LAF_NAME = "macOS Light"
private val instance: PluggableLafInfo = MacOsLookAndFeelInfo()
}
} | apache-2.0 | c6784207de5b76905a8f5dbd9e45d085 | 34.433333 | 128 | 0.801318 | 4.317073 | false | false | false | false |
SpectraLogic/ds3_java_browser | dsb-gui/src/main/java/com/spectralogic/dsbrowser/gui/services/jobService/data/PutJobData.kt | 1 | 8969 | /*
* ***************************************************************************
* Copyright 2014-2018 Spectra Logic Corporation. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use
* this file except in compliance with the License. A copy of the License is located at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* or in the "license" file accompanying this file.
* This file 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.spectralogic.dsbrowser.gui.services.jobService.data
import com.spectralogic.ds3client.Ds3Client
import com.spectralogic.ds3client.commands.spectrads3.GetActiveJobSpectraS3Request
import com.spectralogic.ds3client.commands.spectrads3.GetJobSpectraS3Request
import com.spectralogic.ds3client.commands.spectrads3.PutBulkJobSpectraS3Request
import com.spectralogic.ds3client.helpers.Ds3ClientHelpers
import com.spectralogic.ds3client.helpers.FileObjectPutter
import com.spectralogic.ds3client.helpers.WriteJobImpl
import com.spectralogic.ds3client.helpers.events.ConcurrentEventRunner
import com.spectralogic.ds3client.helpers.strategy.blobstrategy.BlackPearlChunkAttemptRetryDelayBehavior
import com.spectralogic.ds3client.helpers.strategy.blobstrategy.MaxChunkAttemptsRetryBehavior
import com.spectralogic.ds3client.helpers.strategy.blobstrategy.PutSequentialBlobStrategy
import com.spectralogic.ds3client.helpers.strategy.transferstrategy.EventDispatcherImpl
import com.spectralogic.ds3client.helpers.strategy.transferstrategy.TransferStrategyBuilder
import com.spectralogic.ds3client.models.JobStatus
import com.spectralogic.ds3client.models.Priority
import com.spectralogic.ds3client.models.bulk.Ds3Object
import com.spectralogic.dsbrowser.api.services.logging.LogType
import com.spectralogic.dsbrowser.api.services.logging.LoggingService
import com.spectralogic.dsbrowser.gui.services.jobService.JobTaskElement
import com.spectralogic.dsbrowser.gui.services.jobService.util.EmptyChannelBuilder
import com.spectralogic.dsbrowser.gui.util.DateTimeUtils
import com.spectralogic.dsbrowser.gui.util.ParseJobInterruptionMap
import javafx.beans.property.BooleanProperty
import java.io.File
import java.lang.RuntimeException
import java.nio.file.Files
import java.nio.file.NoSuchFileException
import java.nio.file.Path
import java.time.Instant
import java.util.UUID
data class PutJobData(
private val items: List<Pair<String, Path>>,
private val targetDir: String,
override val bucket: String,
private val jobTaskElement: JobTaskElement
) : JobData {
override fun runningTitle(): String {
val transferringPut = jobTaskElement.resourceBundle.getString("transferringPut")
val jobId = job.jobId
val startedAt = jobTaskElement.resourceBundle.getString("startedAt")
val started = jobTaskElement.dateTimeUtils.format(getStartTime())
return "$transferringPut $jobId $startedAt $started"
}
override val jobId: UUID by lazy { job.jobId }
override fun client(): Ds3Client = jobTaskElement.client
override fun internationalize(labelName: String): String = jobTaskElement.resourceBundle.getString(labelName)
override fun modifyJob(job: Ds3ClientHelpers.Job) {
job.withMaxParallelRequests(jobTaskElement.settingsStore.processSettings.maximumNumberOfParallelThreads)
}
override val job: Ds3ClientHelpers.Job by lazy {
val ds3Objects = items.map { pathToDs3Object(it.second) }.flatten()
ds3Objects.map { pair: Pair<Ds3Object, Path> -> Pair<String, Path>(pair.first.name, pair.second) }
.forEach { prefixMap.put(it.first, it.second) }
if (ds3Objects.isEmpty()) {
loggingService().logMessage("File list is empty, cannot create job", LogType.ERROR)
throw RuntimeException("File list is empty")
}
val priority =
if (jobTaskElement.savedJobPrioritiesStore.jobSettings.putJobPriority.equals("Data Policy Default (no change)")) {
null
} else {
Priority.valueOf(jobTaskElement.savedJobPrioritiesStore.jobSettings.putJobPriority)
}
val request = PutBulkJobSpectraS3Request(
bucket,
ds3Objects.map { it.first }
).withPriority(priority)
val response = jobTaskElement.client.putBulkJobSpectraS3(request)
val eventDispatcher = EventDispatcherImpl(ConcurrentEventRunner())
val blobStrategy = PutSequentialBlobStrategy(
jobTaskElement.client,
response.masterObjectList,
eventDispatcher,
MaxChunkAttemptsRetryBehavior(1),
BlackPearlChunkAttemptRetryDelayBehavior(eventDispatcher)
)
val transferStrategyBuilder = TransferStrategyBuilder()
.withDs3Client(jobTaskElement.client)
.withMasterObjectList(response.masterObjectList)
.withBlobStrategy(blobStrategy)
.withChannelBuilder(null)
.withNumConcurrentTransferThreads(jobTaskElement.settingsStore.processSettings.maximumNumberOfParallelThreads)
WriteJobImpl(transferStrategyBuilder)
}
override var prefixMap: MutableMap<String, Path> = mutableMapOf()
override fun showCachedJobProperty(): BooleanProperty = jobTaskElement.settingsStore.showCachedJobSettings.showCachedJobEnableProperty()
override fun loggingService(): LoggingService = jobTaskElement.loggingService
override fun targetPath(): String = targetDir
override fun dateTimeUtils(): DateTimeUtils = jobTaskElement.dateTimeUtils
private var startTime: Instant = Instant.now()
override fun getStartTime(): Instant = startTime
override fun setStartTime(): Instant {
startTime = Instant.now()
return startTime
}
override fun getObjectChannelBuilder(prefix: String): Ds3ClientHelpers.ObjectChannelBuilder =
EmptyChannelBuilder(FileObjectPutter(prefixMap.get(prefix)!!.parent), prefixMap.get(prefix)!!)
private fun pathToDs3Object(path: Path): List<Pair<Ds3Object, Path>> {
val parent = path.parent
return path
.toFile()
.walk(FileWalkDirection.TOP_DOWN)
.filter(::rejectEmptyDirectory)
.filter(::rejectDeadLinks)
.map(::addSize)
.map { convertToDs3Object(it, parent) }
.map { Pair(it, path) }
.distinct()
.toList()
}
private fun addSize(file: File): Pair<File, Long> =
Pair(file, if (Files.isDirectory(file.toPath())) 0L else file.length())
private fun rejectEmptyDirectory(file: File) =
!(file.isDirectory && Files.list(file.toPath()).use { f -> f.findAny().isPresent })
private fun convertToDs3Object(fileParts: Pair<File, Long>, parent: Path): Ds3Object {
val (file, size) = fileParts
val pathBuilder = StringBuilder(targetDir)
val localDelim = file.toPath().fileSystem.separator
pathBuilder.append(parent.relativize(file.toPath()).toString().replace(localDelim, "/"))
if (file.isDirectory) { pathBuilder.append("/") }
return Ds3Object(pathBuilder.toString(), size)
}
private fun rejectDeadLinks(file: File): Boolean {
return try {
file.toPath().toRealPath()
true
} catch (e: NoSuchFileException) {
loggingService().logMessage("Could not resolve link " + file, LogType.ERROR)
false
}
}
override fun jobSize() = jobTaskElement.client.getActiveJobSpectraS3(GetActiveJobSpectraS3Request(job.jobId)).activeJobResult.originalSizeInBytes
override fun shouldRestoreFileAttributes(): Boolean = jobTaskElement.settingsStore.filePropertiesSettings.isFilePropertiesEnabled
override fun isCompleted() = jobTaskElement.client.getJobSpectraS3(GetJobSpectraS3Request(job.jobId)).masterObjectListResult.status == JobStatus.COMPLETED
override fun removeJob() {
ParseJobInterruptionMap.removeJobIdFromFile(jobTaskElement.jobInterruptionStore, job.jobId.toString(), jobTaskElement.client.connectionDetails.endpoint)
}
override fun saveJob(jobSize: Long) {
ParseJobInterruptionMap.saveValuesToFiles(jobTaskElement.jobInterruptionStore, prefixMap, mapOf(), jobTaskElement.client.connectionDetails.endpoint, job.jobId, jobSize, targetPath(), jobTaskElement.dateTimeUtils, "PUT", bucket)
}
} | apache-2.0 | debf6903130eae6a3a39b1c71d4416a7 | 50.551724 | 235 | 0.704092 | 4.840259 | false | false | false | false |
JuliaSoboleva/SmartReceiptsLibrary | app/src/test/java/co/smartreceipts/android/workers/EmailAssistantTest.kt | 1 | 12191 | package co.smartreceipts.android.workers
import android.content.Context
import android.content.Intent
import co.smartreceipts.android.DefaultObjects
import co.smartreceipts.android.R
import co.smartreceipts.android.date.DateFormatter
import co.smartreceipts.android.model.Distance
import co.smartreceipts.android.model.Receipt
import co.smartreceipts.android.model.factory.ReceiptBuilderFactory
import co.smartreceipts.android.persistence.DatabaseHelper
import co.smartreceipts.android.persistence.database.tables.DistanceTable
import co.smartreceipts.android.persistence.database.tables.ReceiptsTable
import co.smartreceipts.android.settings.UserPreferenceManager
import co.smartreceipts.android.settings.catalog.UserPreference
import co.smartreceipts.android.utils.IntentUtils
import co.smartreceipts.android.workers.EmailAssistant.EmailOptions
import co.smartreceipts.android.workers.widget.EmailResult
import co.smartreceipts.android.workers.widget.GenerationErrors
import com.nhaarman.mockitokotlin2.*
import io.reactivex.Single
import org.junit.Assert.assertEquals
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import java.io.File
import java.util.*
@RunWith(RobolectricTestRunner::class)
class EmailAssistantTest {
// Class under test
private lateinit var emailAssistant: EmailAssistant
private val context = mock<Context>()
private val databaseHelper = mock<DatabaseHelper>()
private val preferenceManager = mock<UserPreferenceManager>()
private val attachmentFilesWriter = mock<AttachmentFilesWriter>()
private val dateFormatter = mock<DateFormatter>()
private val intentUtils = mock<IntentUtils>()
private val trip = DefaultObjects.newDefaultTrip()
private val receiptsTable = mock<ReceiptsTable>()
private val distancesTable = mock<DistanceTable>()
private val to = "to"
private val cc = "cc"
private val bcc = "bcc"
private val subject = "subject"
@Before
fun setUp() {
whenever(databaseHelper.receiptsTable).thenReturn(receiptsTable)
whenever(databaseHelper.distanceTable).thenReturn(distancesTable)
whenever(receiptsTable.get(trip, true)).thenReturn(Single.just(emptyList()))
whenever(distancesTable.get(trip, true)).thenReturn(Single.just(emptyList()))
whenever(preferenceManager.get(UserPreference.Email.ToAddresses)).thenReturn(to)
whenever(preferenceManager.get(UserPreference.Email.CcAddresses)).thenReturn(cc)
whenever(preferenceManager.get(UserPreference.Email.BccAddresses)).thenReturn(bcc)
whenever(preferenceManager.get(UserPreference.Email.Subject)).thenReturn(subject)
whenever(preferenceManager.get(UserPreference.Receipts.OnlyIncludeReimbursable)).thenReturn(false)
whenever(preferenceManager.get(UserPreference.Receipts.UsePreTaxPrice)).thenReturn(false)
whenever(preferenceManager.get(UserPreference.ReportOutput.UserId)).thenReturn("")
whenever(context.getString(R.string.report_attached)).thenReturn("1 report attached")
whenever(context.packageName).thenReturn("")
whenever(dateFormatter.getFormattedDate(trip.startDisplayableDate)).thenReturn("")
whenever(dateFormatter.getFormattedDate(trip.endDisplayableDate)).thenReturn("")
emailAssistant = EmailAssistant(context, databaseHelper, preferenceManager, attachmentFilesWriter, dateFormatter, intentUtils)
}
@Test
fun emailTripErrorNoOptionsTest() {
val options = EnumSet.noneOf(EmailOptions::class.java)
val result = emailAssistant.emailTrip(trip, options).blockingGet()
assert(result is EmailResult.Error && result.errorType == GenerationErrors.ERROR_NO_SELECTION)
verifyZeroInteractions(databaseHelper, preferenceManager, attachmentFilesWriter, dateFormatter)
}
@Test
fun emailTripErrorNoReceiptsNoDistancesTest() {
// user wants to create report but there are no receipts and no distances
val options = EnumSet.allOf(EmailOptions::class.java)
val result = emailAssistant.emailTrip(trip, options).blockingGet()
assert(result is EmailResult.Error && result.errorType == GenerationErrors.ERROR_NO_RECEIPTS)
verify(databaseHelper).receiptsTable
verify(databaseHelper).distanceTable
verifyNoMoreInteractions(databaseHelper)
verifyZeroInteractions(preferenceManager, attachmentFilesWriter, dateFormatter)
}
@Test
fun emailTripErrorNoReceiptsDistancesNotPdfNotCsvTest() {
// user wants to create report (not PDF or CSV) with just distances
val options = EnumSet.of(EmailOptions.ZIP, EmailOptions.ZIP_WITH_METADATA, EmailOptions.PDF_IMAGES_ONLY)
whenever(distancesTable.get(trip, true)).thenReturn(Single.just(listOf(mock())))
val result = emailAssistant.emailTrip(trip, options).blockingGet()
assert(result is EmailResult.Error && result.errorType == GenerationErrors.ERROR_NO_RECEIPTS)
verify(databaseHelper).receiptsTable
verify(databaseHelper).distanceTable
verifyNoMoreInteractions(databaseHelper)
verifyZeroInteractions(preferenceManager, attachmentFilesWriter, dateFormatter)
}
@Test
fun emailTripErrorNoReceiptsDisabledDistancesPdfTest() {
// user wants to create PDF report with just distances but this option is disabled
val optionsPdf = EnumSet.of(EmailOptions.PDF_FULL)
whenever(distancesTable.get(trip, true)).thenReturn(Single.just(listOf(mock())))
whenever(preferenceManager.get(UserPreference.Distance.PrintDistanceTableInReports)).thenReturn(false)
val result = emailAssistant.emailTrip(trip, optionsPdf).blockingGet()
assert(result is EmailResult.Error && result.errorType == GenerationErrors.ERROR_DISABLED_DISTANCES)
verify(databaseHelper).receiptsTable
verify(databaseHelper).distanceTable
verifyNoMoreInteractions(databaseHelper)
verify(preferenceManager).get(UserPreference.Distance.PrintDistanceTableInReports)
verifyNoMoreInteractions(preferenceManager)
verifyZeroInteractions(attachmentFilesWriter, dateFormatter)
}
@Test
fun emailTripErrorNoReceiptsDisabledDistancesCsvTest() {
// user wants to create CSV report with just distances but this option is disabled
val optionsCsv = EnumSet.of(EmailOptions.CSV)
whenever(distancesTable.get(trip, true)).thenReturn(Single.just(listOf(mock())))
whenever(preferenceManager.get(UserPreference.Distance.PrintDistanceTableInReports)).thenReturn(false)
val result = emailAssistant.emailTrip(trip, optionsCsv).blockingGet()
assert(result is EmailResult.Error && result.errorType == GenerationErrors.ERROR_DISABLED_DISTANCES)
verify(databaseHelper).receiptsTable
verify(databaseHelper).distanceTable
verifyNoMoreInteractions(databaseHelper)
verify(preferenceManager).get(UserPreference.Distance.PrintDistanceTableInReports)
verifyNoMoreInteractions(preferenceManager)
verifyZeroInteractions(attachmentFilesWriter, dateFormatter)
}
@Test
fun emailTripErrorMemoryTest() {
val options = EnumSet.allOf(EmailOptions::class.java)
val distancesList: List<Distance> = emptyList()
val receiptsList: List<Receipt> = listOf(mock())
val writerResults = AttachmentFilesWriter.WriterResults()
writerResults.didMemoryErrorOccure = true
whenever(receiptsTable.get(trip, true)).thenReturn(Single.just(receiptsList))
whenever(attachmentFilesWriter.write(trip, receiptsList, distancesList, options)).thenReturn(writerResults)
val result = emailAssistant.emailTrip(trip, options).blockingGet()
assert(result is EmailResult.Error && result.errorType == GenerationErrors.ERROR_MEMORY)
verify(databaseHelper).receiptsTable
verify(databaseHelper).distanceTable
verify(attachmentFilesWriter).write(trip, receiptsList, distancesList, options)
verifyNoMoreInteractions(databaseHelper, attachmentFilesWriter)
}
@Test
fun emailTripErrorTooManyColumns() {
val options = EnumSet.of(EmailOptions.PDF_FULL)
val distancesList: List<Distance> = emptyList()
val receiptsList: List<Receipt> = listOf(mock())
val writerResults = AttachmentFilesWriter.WriterResults()
writerResults.didPDFFailCompletely = true
writerResults.didPDFFailTooManyColumns = true
whenever(receiptsTable.get(trip, true)).thenReturn(Single.just(receiptsList))
whenever(attachmentFilesWriter.write(trip, receiptsList, distancesList, options)).thenReturn(writerResults)
val result = emailAssistant.emailTrip(trip, options).blockingGet()
assert(result is EmailResult.Error && result.errorType == GenerationErrors.ERROR_TOO_MANY_COLUMNS)
verify(databaseHelper).receiptsTable
verify(databaseHelper).distanceTable
verify(attachmentFilesWriter).write(trip, receiptsList, distancesList, options)
verifyNoMoreInteractions(databaseHelper, attachmentFilesWriter)
}
@Test
fun emailTripErrorPdfGeneration() {
val options = EnumSet.of(EmailOptions.PDF_FULL)
val distancesList: List<Distance> = emptyList()
val receiptsList: List<Receipt> = listOf(mock())
val writerResults = AttachmentFilesWriter.WriterResults()
writerResults.didPDFFailCompletely = true
whenever(receiptsTable.get(trip, true)).thenReturn(Single.just(receiptsList))
whenever(attachmentFilesWriter.write(trip, receiptsList, distancesList, options)).thenReturn(writerResults)
val result = emailAssistant.emailTrip(trip, options).blockingGet()
assert(result is EmailResult.Error && result.errorType == GenerationErrors.ERROR_PDF_GENERATION)
verify(databaseHelper).receiptsTable
verify(databaseHelper).distanceTable
verify(attachmentFilesWriter).write(trip, receiptsList, distancesList, options)
verifyNoMoreInteractions(databaseHelper, attachmentFilesWriter)
}
@Test
fun emailTripSuccess() {
val options = EnumSet.of(EmailOptions.PDF_FULL, EmailOptions.CSV)
val distancesList: List<Distance> = emptyList()
val receiptsList: List<Receipt> = listOf(ReceiptBuilderFactory().setTrip(trip).build())
val filesList: Array<File?> = arrayOf(mock())
val sendIntent = Intent()
val writerResults = mock<AttachmentFilesWriter.WriterResults>()
whenever(writerResults.didPDFFailCompletely).thenReturn(false)
whenever(writerResults.didMemoryErrorOccure).thenReturn(false)
whenever(writerResults.files).thenReturn(filesList)
whenever(receiptsTable.get(trip, true)).thenReturn(Single.just(receiptsList))
whenever(attachmentFilesWriter.write(trip, receiptsList, distancesList, options)).thenReturn(writerResults)
whenever(intentUtils.getSendIntent(context, filesList.filterNotNull())).thenReturn(sendIntent)
val result = emailAssistant.emailTrip(trip, options).blockingGet()
assert(result is EmailResult.Success)
val intent = (result as EmailResult.Success).intent
val ccExtra = intent.getStringArrayExtra(Intent.EXTRA_CC)
assert(ccExtra.size == 1 && ccExtra[0] == cc)
val bccExtra = intent.getStringArrayExtra(Intent.EXTRA_BCC)
assert(bccExtra.size == 1 && bccExtra[0] == bcc)
val toExtra = intent.getStringArrayExtra(Intent.EXTRA_EMAIL)
assert(toExtra.size == 1 && toExtra[0] == to)
val subjectExtra = intent.getStringExtra(Intent.EXTRA_SUBJECT)
assertEquals(subject, subjectExtra)
val bodyExtra = intent.getStringExtra(Intent.EXTRA_TEXT)
assertEquals("1 report attached", bodyExtra)
verify(databaseHelper).receiptsTable
verify(databaseHelper).distanceTable
verify(attachmentFilesWriter).write(trip, receiptsList, distancesList, options)
verify(intentUtils).getSendIntent(context, filesList.filterNotNull())
}
} | agpl-3.0 | 9669ad8186068383006ea1c4bdd014fa | 42.856115 | 134 | 0.749487 | 5.300435 | false | true | false | false |
paplorinc/intellij-community | uast/uast-java/src/org/jetbrains/uast/java/expressions/JavaUSimpleNameReferenceExpression.kt | 2 | 3164 | /*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.uast.java
import com.intellij.psi.*
import com.intellij.psi.infos.CandidateInfo
import org.jetbrains.annotations.ApiStatus
import org.jetbrains.uast.*
class JavaUSimpleNameReferenceExpression(
override val psi: PsiElement?,
override val identifier: String,
givenParent: UElement?,
val reference: PsiReference? = null
) : JavaAbstractUExpression(givenParent), USimpleNameReferenceExpression, UMultiResolvable {
override fun resolve(): PsiElement? = (reference ?: psi as? PsiReference)?.resolve()
override fun multiResolve(): Iterable<ResolveResult> =
(reference as? PsiPolyVariantReference ?: psi as? PsiPolyVariantReference)?.multiResolve(false)?.asIterable()
?: listOfNotNull(resolve()?.let { CandidateInfo(it, PsiSubstitutor.EMPTY) })
override val resolvedName: String?
get() = ((reference ?: psi as? PsiReference)?.resolve() as? PsiNamedElement)?.name
override fun getPsiParentForLazyConversion(): PsiElement? {
val parent = super.getPsiParentForLazyConversion()
if (parent is PsiReferenceExpression && parent.parent is PsiMethodCallExpression) {
return parent.parent
}
return parent
}
override fun convertParent(): UElement? = super.convertParent().let(this::unwrapCompositeQualifiedReference)
override val referenceNameElement: UElement?
get() = when (psi) {
is PsiJavaCodeReferenceElement -> psi.referenceNameElement.toUElement()
else -> this
}
}
class JavaUTypeReferenceExpression(
override val psi: PsiTypeElement,
givenParent: UElement?
) : JavaAbstractUExpression(givenParent), UTypeReferenceExpression {
override val type: PsiType
get() = psi.type
}
class LazyJavaUTypeReferenceExpression(
override val psi: PsiElement,
givenParent: UElement?,
private val typeSupplier: () -> PsiType
) : JavaAbstractUExpression(givenParent), UTypeReferenceExpression {
override val type: PsiType by lz { typeSupplier() }
}
@Deprecated("no known usages, to be removed in IDEA 2019.2")
@ApiStatus.ScheduledForRemoval(inVersion = "2019.2")
class JavaClassUSimpleNameReferenceExpression(
override val identifier: String,
val ref: PsiJavaReference,
override val psi: PsiElement,
givenParent: UElement?
) : JavaAbstractUExpression(givenParent), USimpleNameReferenceExpression, UMultiResolvable {
override fun resolve(): PsiElement? = ref.resolve()
override fun multiResolve(): Iterable<ResolveResult> = ref.multiResolve(false).asIterable()
override val resolvedName: String?
get() = (ref.resolve() as? PsiNamedElement)?.name
} | apache-2.0 | d420aca3b419384456aec82869c6b059 | 35.37931 | 113 | 0.757901 | 4.905426 | false | false | false | false |
auricgoldfinger/Memento-Namedays | memento/src/main/java/com/alexstyl/specialdates/people/PeoplePresenter.kt | 3 | 3150 | package com.alexstyl.specialdates.people
import com.alexstyl.specialdates.CrashAndErrorTracker
import com.alexstyl.specialdates.date.TimePeriod
import com.alexstyl.specialdates.events.peopleevents.PeopleEventsProvider
import com.alexstyl.specialdates.permissions.MementoPermissions
import io.reactivex.Scheduler
import io.reactivex.disposables.Disposable
import io.reactivex.subjects.PublishSubject
class PeoplePresenter(
private val permissions: MementoPermissions,
private val peopleEventsProvider: PeopleEventsProvider,
private val viewModelFactory: PeopleViewModelFactory,
private val errorTracker: CrashAndErrorTracker,
private val workScheduler: Scheduler,
private val resultScheduler: Scheduler) {
companion object {
private const val TRIGGER = 1
}
private var disposable: Disposable? = null
private val subject = PublishSubject.create<Int>()
fun startPresentingInto(view: PeopleView) {
disposable =
subject
.doOnSubscribe { _ ->
view.showLoading()
}
.observeOn(workScheduler)
.map { _ ->
peopleEventsProvider.fetchEventsBetween(TimePeriod.aYearFromNow())
}
.map { contacts ->
val viewModels = arrayListOf<PeopleRowViewModel>()
val contactIDs = HashSet<Long>()
viewModels.add(viewModelFactory.facebookViewModel())
if (contacts.isEmpty()) {
viewModels.add(viewModelFactory.noContactsViewModel())
} else {
val mutableList = contacts.toMutableList()
mutableList.sortWith(compareBy(String.CASE_INSENSITIVE_ORDER, { it.contact.displayName.toString() }))
mutableList.forEach { contactEvent ->
val contact = contactEvent.contact
if (!contactIDs.contains(contact.contactID)) {
viewModels.add(viewModelFactory.personViewModel(contact))
contactIDs.add(contact.contactID)
}
}
}
viewModels
}
.observeOn(resultScheduler)
.onErrorReturn { error ->
errorTracker.track(error)
arrayListOf()
}
.subscribe { viewModels ->
view.displayPeople(viewModels)
}
if (permissions.canReadAndWriteContacts()) {
refreshData()
}
}
fun refreshData() {
subject.onNext(TRIGGER)
}
fun stopPresenting() {
disposable?.dispose()
}
}
| mit | b625e29d3085121bec574ebf597fb69c | 37.888889 | 133 | 0.517143 | 6.659619 | false | false | false | false |
google/intellij-community | platform/platform-impl/src/com/intellij/ide/impl/ProjectUtil.kt | 1 | 28594 | // 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.ide.impl
import com.intellij.CommonBundle
import com.intellij.configurationStore.runInAutoSaveDisabledMode
import com.intellij.configurationStore.saveSettings
import com.intellij.execution.wsl.WslPath.Companion.isWslUncPath
import com.intellij.featureStatistics.fusCollectors.LifecycleUsageTriggerCollector
import com.intellij.ide.GeneralSettings
import com.intellij.ide.IdeBundle
import com.intellij.ide.RecentProjectsManager
import com.intellij.ide.actions.OpenFileAction
import com.intellij.ide.highlighter.ProjectFileType
import com.intellij.openapi.application.*
import com.intellij.openapi.components.StorageScheme
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.fileChooser.impl.FileChooserUtil
import com.intellij.openapi.progress.*
import com.intellij.openapi.progress.impl.CoreProgressManager
import com.intellij.openapi.project.Project
import com.intellij.openapi.project.ProjectManager
import com.intellij.openapi.project.ex.ProjectManagerEx
import com.intellij.openapi.startup.StartupManager
import com.intellij.openapi.ui.MessageDialogBuilder.Companion.yesNo
import com.intellij.openapi.ui.Messages
import com.intellij.openapi.util.*
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.util.io.FileUtilRt
import com.intellij.openapi.util.text.StringUtil
import com.intellij.openapi.vfs.LocalFileSystem
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.openapi.wm.IdeFrame
import com.intellij.openapi.wm.ToolWindowId
import com.intellij.openapi.wm.ToolWindowManager
import com.intellij.openapi.wm.WindowManager
import com.intellij.platform.CommandLineProjectOpenProcessor
import com.intellij.platform.PlatformProjectOpenProcessor
import com.intellij.platform.PlatformProjectOpenProcessor.Companion.attachToProject
import com.intellij.platform.PlatformProjectOpenProcessor.Companion.createOptionsToOpenDotIdeaOrCreateNewIfNotExists
import com.intellij.project.stateStore
import com.intellij.projectImport.ProjectAttachProcessor
import com.intellij.projectImport.ProjectOpenProcessor
import com.intellij.ui.AppIcon
import com.intellij.ui.ComponentUtil
import com.intellij.util.ModalityUiUtil
import com.intellij.util.PathUtil
import com.intellij.util.PlatformUtils
import com.intellij.util.SystemProperties
import com.intellij.util.concurrency.annotations.RequiresEdt
import com.intellij.util.io.basicAttributesIfExists
import kotlinx.coroutines.*
import kotlinx.coroutines.future.asCompletableFuture
import org.jetbrains.annotations.ApiStatus.Internal
import org.jetbrains.annotations.ApiStatus.ScheduledForRemoval
import org.jetbrains.annotations.Nls
import org.jetbrains.annotations.PropertyKey
import org.jetbrains.annotations.SystemDependent
import org.jetbrains.annotations.VisibleForTesting
import java.awt.Component
import java.awt.Frame
import java.awt.KeyboardFocusManager
import java.awt.Window
import java.io.File
import java.io.IOException
import java.nio.file.Files
import java.nio.file.Path
import java.util.concurrent.Callable
import java.util.concurrent.CompletableFuture
import kotlin.Result
private val LOG = Logger.getInstance(ProjectUtil::class.java)
private var ourProjectsPath: String? = null
object ProjectUtil {
const val DEFAULT_PROJECT_NAME = "default"
private const val PROJECTS_DIR = "projects"
private const val PROPERTY_PROJECT_PATH = "%s.project.path"
@Deprecated("Use {@link #updateLastProjectLocation(Path)} ", ReplaceWith("updateLastProjectLocation(Path.of(projectFilePath))",
"com.intellij.ide.impl.ProjectUtil.updateLastProjectLocation",
"java.nio.file.Path"))
fun updateLastProjectLocation(projectFilePath: String) {
updateLastProjectLocation(Path.of(projectFilePath))
}
@JvmStatic
fun updateLastProjectLocation(lastProjectLocation: Path) {
var location: Path? = lastProjectLocation
if (Files.isRegularFile(location!!)) {
// for directory-based project storage
location = location.parent
}
if (location == null) {
// the immediate parent of the ipr file
return
}
// the candidate directory to be saved
location = location.parent
if (location == null) {
return
}
var path = location.toString()
path = try {
FileUtil.resolveShortWindowsName(path)
}
catch (e: IOException) {
LOG.info(e)
return
}
RecentProjectsManager.getInstance().lastProjectCreationLocation = PathUtil.toSystemIndependentName(path)
}
@Deprecated("Use {@link ProjectManager#closeAndDispose(Project)} ",
ReplaceWith("ProjectManager.getInstance().closeAndDispose(project)", "com.intellij.openapi.project.ProjectManager"))
@JvmStatic
fun closeAndDispose(project: Project): Boolean {
return ProjectManager.getInstance().closeAndDispose(project)
}
@JvmStatic
fun openOrImport(path: Path, projectToClose: Project?, forceOpenInNewFrame: Boolean): Project? {
return openOrImport(path, OpenProjectTask().withProjectToClose(projectToClose).withForceOpenInNewFrame(forceOpenInNewFrame))
}
/**
* @param path project file path
* @param projectToClose currently active project
* @param forceOpenInNewFrame forces opening in new frame
* @return project by path if the path was recognized as IDEA project file or one of the project formats supported by
* installed importers (regardless of opening/import result)
* null otherwise
*/
@JvmStatic
fun openOrImport(path: String, projectToClose: Project?, forceOpenInNewFrame: Boolean): Project? {
return openOrImport(Path.of(path), OpenProjectTask().withProjectToClose(projectToClose).withForceOpenInNewFrame(forceOpenInNewFrame))
}
@JvmStatic
@JvmOverloads
fun openOrImport(file: Path, options: OpenProjectTask = OpenProjectTask()): Project? {
return runUnderModalProgressIfIsEdt {
openOrImportAsync(file, options)
}
}
suspend fun openOrImportAsync(file: Path, options: OpenProjectTask = OpenProjectTask()): Project? {
if (!options.forceOpenInNewFrame) {
findAndFocusExistingProjectForPath(file)?.let {
return it
}
}
var virtualFileResult: Result<VirtualFile>? = null
for (provider in ProjectOpenProcessor.EXTENSION_POINT_NAME.iterable) {
if (!provider.isStrongProjectInfoHolder) {
continue
}
// `PlatformProjectOpenProcessor` is not a strong project info holder, so there is no need to optimize (VFS not required)
val virtualFile: VirtualFile = virtualFileResult?.getOrThrow() ?: blockingContext {
ProjectUtilCore.getFileAndRefresh(file)
}?.also {
virtualFileResult = Result.success(it)
} ?: return null
if (provider.canOpenProject(virtualFile)) {
return chooseProcessorAndOpenAsync(mutableListOf(provider), virtualFile, options)
}
}
if (ProjectUtilCore.isValidProjectPath(file)) {
// see OpenProjectTest.`open valid existing project dir with inability to attach using OpenFileAction` test about why `runConfigurators = true` is specified here
return ProjectManagerEx.getInstanceEx().openProjectAsync(file, options.copy(runConfigurators = true))
}
if (!options.preventIprLookup && Files.isDirectory(file)) {
try {
withContext(Dispatchers.IO) {
Files.newDirectoryStream(file)
}.use { directoryStream ->
for (child in directoryStream) {
val childPath = child.toString()
if (childPath.endsWith(ProjectFileType.DOT_DEFAULT_EXTENSION)) {
return openProject(Path.of(childPath), options)
}
}
}
}
catch (ignore: IOException) {
}
}
var nullableVirtualFileResult: Result<VirtualFile?>? = virtualFileResult
val processors = blockingContext {
computeProcessors(file) {
val capturedNullableVirtualFileResult = nullableVirtualFileResult
if (capturedNullableVirtualFileResult != null) {
capturedNullableVirtualFileResult.getOrThrow()
}
else {
ProjectUtilCore.getFileAndRefresh(file).also {
nullableVirtualFileResult = Result.success(it)
}
}
}
}
if (processors.isEmpty()) {
return null
}
val project: Project?
if (processors.size == 1 && processors[0] is PlatformProjectOpenProcessor) {
project = ProjectManagerEx.getInstanceEx().openProjectAsync(
projectStoreBaseDir = file,
options = options.copy(
isNewProject = true,
useDefaultProjectAsTemplate = true,
runConfigurators = true,
beforeOpen = {
it.putUserData(PlatformProjectOpenProcessor.PROJECT_OPENED_BY_PLATFORM_PROCESSOR, true)
true
},
)
)
}
else {
val virtualFile = nullableVirtualFileResult?.let {
it.getOrThrow() ?: return null
} ?: blockingContext {
ProjectUtilCore.getFileAndRefresh(file)
} ?: return null
project = chooseProcessorAndOpenAsync(processors, virtualFile, options)
}
return postProcess(project)
}
private fun computeProcessors(file: Path, lazyVirtualFile: () -> VirtualFile?): MutableList<ProjectOpenProcessor> {
val processors = ArrayList<ProjectOpenProcessor>()
ProjectOpenProcessor.EXTENSION_POINT_NAME.forEachExtensionSafe { processor: ProjectOpenProcessor ->
if (processor is PlatformProjectOpenProcessor) {
if (Files.isDirectory(file)) {
processors.add(processor)
}
}
else {
val virtualFile = lazyVirtualFile()
if (virtualFile != null && processor.canOpenProject(virtualFile)) {
processors.add(processor)
}
}
}
return processors
}
private fun postProcess(project: Project?): Project? {
if (project == null) {
return null
}
StartupManager.getInstance(project).runAfterOpened {
ModalityUiUtil.invokeLaterIfNeeded(ModalityState.NON_MODAL, project.disposed) {
val toolWindow = ToolWindowManager.getInstance(project).getToolWindow(ToolWindowId.PROJECT_VIEW)
toolWindow?.activate(null)
}
}
return project
}
fun openProject(path: String, projectToClose: Project?, forceOpenInNewFrame: Boolean): Project? {
return openProject(Path.of(path), OpenProjectTask().withProjectToClose(projectToClose).withForceOpenInNewFrame(forceOpenInNewFrame))
}
private suspend fun chooseProcessorAndOpenAsync(processors: MutableList<ProjectOpenProcessor>,
virtualFile: VirtualFile,
options: OpenProjectTask): Project? {
val processor = when (processors.size) {
1 -> {
processors.first()
}
else -> {
processors.removeIf { it is PlatformProjectOpenProcessor }
if (processors.size == 1) {
processors.first()
}
else {
val chooser = options.processorChooser
if (chooser == null) {
withContext(Dispatchers.EDT) {
SelectProjectOpenProcessorDialog.showAndGetChoice(processors, virtualFile)
} ?: return null
}
else {
LOG.info("options.openProcessorChooser will handle the open processor dilemma")
chooser(processors) as ProjectOpenProcessor
}
}
}
}
processor.openProjectAsync(virtualFile, options.projectToClose, options.forceOpenInNewFrame)?.let {
return it.orElse(null)
}
return withContext(Dispatchers.EDT) {
processor.doOpenProject(virtualFile, options.projectToClose, options.forceOpenInNewFrame)
}
}
@JvmStatic
fun openProject(file: Path, options: OpenProjectTask): Project? {
val fileAttributes = file.basicAttributesIfExists()
if (fileAttributes == null) {
Messages.showErrorDialog(IdeBundle.message("error.project.file.does.not.exist", file.toString()), CommonBundle.getErrorTitle())
return null
}
val existing = findAndFocusExistingProjectForPath(file)
if (existing != null) {
return existing
}
if (isRemotePath(file.toString()) && !RecentProjectsManager.getInstance().hasPath(FileUtil.toSystemIndependentName(file.toString()))) {
if (!confirmLoadingFromRemotePath(file.toString(), "warning.load.project.from.share", "title.load.project.from.share")) {
return null
}
}
if (fileAttributes.isDirectory) {
val dir = file.resolve(Project.DIRECTORY_STORE_FOLDER)
if (!Files.isDirectory(dir)) {
Messages.showErrorDialog(IdeBundle.message("error.project.file.does.not.exist", dir.toString()), CommonBundle.getErrorTitle())
return null
}
}
try {
return ProjectManagerEx.getInstanceEx().openProject(file, options)
}
catch (e: Exception) {
Messages.showMessageDialog(IdeBundle.message("error.cannot.load.project", e.message),
IdeBundle.message("title.cannot.load.project"), Messages.getErrorIcon())
}
return null
}
fun confirmLoadingFromRemotePath(path: String,
msgKey: @PropertyKey(resourceBundle = IdeBundle.BUNDLE) String,
titleKey: @PropertyKey(resourceBundle = IdeBundle.BUNDLE) String): Boolean {
return showYesNoDialog(IdeBundle.message(msgKey, path), titleKey)
}
fun showYesNoDialog(message: @Nls String, titleKey: @PropertyKey(resourceBundle = IdeBundle.BUNDLE) String): Boolean {
return yesNo(IdeBundle.message(titleKey), message)
.icon(Messages.getWarningIcon())
.ask(getActiveFrameOrWelcomeScreen())
}
@JvmStatic
fun getActiveFrameOrWelcomeScreen(): Window? {
val window = KeyboardFocusManager.getCurrentKeyboardFocusManager().focusedWindow
if (window != null) {
return window
}
for (frame in Frame.getFrames()) {
if (frame is IdeFrame && frame.isVisible) {
return frame
}
}
return null
}
fun isRemotePath(path: String): Boolean {
return (path.contains("://") || path.contains("\\\\")) && !isWslUncPath(path)
}
fun findProject(file: Path): Project? = getOpenProjects().firstOrNull { isSameProject(file, it) }
@JvmStatic
fun findAndFocusExistingProjectForPath(file: Path): Project? {
val project = findProject(file)
if (project != null) {
focusProjectWindow(project = project)
}
return project
}
/**
* @return [GeneralSettings.OPEN_PROJECT_SAME_WINDOW] or
* [GeneralSettings.OPEN_PROJECT_NEW_WINDOW] or
* [GeneralSettings.OPEN_PROJECT_SAME_WINDOW_ATTACH] or
* `-1` (when a user cancels the dialog)
*/
fun confirmOpenOrAttachProject(): Int {
var mode = GeneralSettings.getInstance().confirmOpenNewProject
if (mode == GeneralSettings.OPEN_PROJECT_ASK) {
val exitCode = Messages.showDialog(
IdeBundle.message("prompt.open.project.or.attach"),
IdeBundle.message("prompt.open.project.or.attach.title"), arrayOf(
IdeBundle.message("prompt.open.project.or.attach.button.this.window"),
IdeBundle.message("prompt.open.project.or.attach.button.new.window"),
IdeBundle.message("prompt.open.project.or.attach.button.attach"),
CommonBundle.getCancelButtonText()
),
0,
Messages.getQuestionIcon(),
ProjectNewWindowDoNotAskOption())
mode = if (exitCode == 0) GeneralSettings.OPEN_PROJECT_SAME_WINDOW else if (exitCode == 1) GeneralSettings.OPEN_PROJECT_NEW_WINDOW else if (exitCode == 2) GeneralSettings.OPEN_PROJECT_SAME_WINDOW_ATTACH else -1
if (mode != -1) {
LifecycleUsageTriggerCollector.onProjectFrameSelected(mode)
}
}
return mode
}
@Deprecated("Use {@link #isSameProject(Path, Project)} ",
ReplaceWith("projectFilePath != null && isSameProject(Path.of(projectFilePath), project)",
"com.intellij.ide.impl.ProjectUtil.isSameProject", "java.nio.file.Path"))
fun isSameProject(projectFilePath: String?, project: Project): Boolean {
return projectFilePath != null && isSameProject(Path.of(projectFilePath), project)
}
@JvmStatic
fun isSameProject(projectFile: Path, project: Project): Boolean {
val projectStore = project.stateStore
val existingBaseDirPath = projectStore.projectBasePath
if (existingBaseDirPath.fileSystem !== projectFile.fileSystem) {
return false
}
if (Files.isDirectory(projectFile)) {
return try {
Files.isSameFile(projectFile, existingBaseDirPath)
}
catch (ignore: IOException) {
false
}
}
if (projectStore.storageScheme == StorageScheme.DEFAULT) {
return try {
Files.isSameFile(projectFile, projectStore.projectFilePath)
}
catch (ignore: IOException) {
false
}
}
var parent: Path? = projectFile.parent ?: return false
val parentFileName = parent!!.fileName
if (parentFileName != null && parentFileName.toString() == Project.DIRECTORY_STORE_FOLDER) {
parent = parent.parent
return parent != null && FileUtil.pathsEqual(parent.toString(), existingBaseDirPath.toString())
}
return projectFile.fileName.toString().endsWith(ProjectFileType.DOT_DEFAULT_EXTENSION) &&
FileUtil.pathsEqual(parent.toString(), existingBaseDirPath.toString())
}
/**
* Focuses the specified project's window. If `stealFocusIfAppInactive` is `true` and corresponding logic is supported by OS
* (making it work on Windows requires enabling focus stealing system-wise, see [com.intellij.ui.WinFocusStealer]), the window will
* get the focus even if other application is currently active. Otherwise, there will be some indication that the target window requires
* user attention. Focus stealing behaviour (enabled by `stealFocusIfAppInactive`) is generally not considered a proper application
* behaviour, and should only be used in special cases, when we know that user definitely expects it.
*/
@JvmStatic
fun focusProjectWindow(project: Project?, stealFocusIfAppInactive: Boolean = false) {
val frame = WindowManager.getInstance().getFrame(project) ?: return
val appIsActive = KeyboardFocusManager.getCurrentKeyboardFocusManager().activeWindow != null
// On macOS, `j.a.Window#toFront` restores the frame if needed.
// On X Window, restoring minimized frame can steal focus from an active application, so we do it only when the IDE is active.
if (SystemInfoRt.isWindows || (SystemInfoRt.isXWindow && appIsActive)) {
val state = frame.extendedState
if (state and Frame.ICONIFIED != 0) {
frame.extendedState = state and Frame.ICONIFIED.inv()
}
}
if (stealFocusIfAppInactive) {
AppIcon.getInstance().requestFocus(frame as IdeFrame)
}
else {
if (!SystemInfoRt.isXWindow || appIsActive) {
// some Linux window managers allow `j.a.Window#toFront` to steal focus, so we don't call it on Linux when the IDE is inactive
frame.toFront()
}
if (!SystemInfoRt.isWindows) {
// on Windows, `j.a.Window#toFront` will request attention if needed
AppIcon.getInstance().requestAttention(project, true)
}
}
}
@JvmStatic
fun getBaseDir(): String {
val defaultDirectory = GeneralSettings.getInstance().defaultProjectDirectory
if (!defaultDirectory.isNullOrEmpty()) {
return defaultDirectory.replace('/', File.separatorChar)
}
val lastProjectLocation = RecentProjectsManager.getInstance().lastProjectCreationLocation
return lastProjectLocation?.replace('/', File.separatorChar) ?: getUserHomeProjectDir()
}
@JvmStatic
fun getUserHomeProjectDir(): String {
val productName = if (PlatformUtils.isCLion() || PlatformUtils.isAppCode() || PlatformUtils.isDataGrip()) {
ApplicationNamesInfo.getInstance().productName
}
else {
ApplicationNamesInfo.getInstance().lowercaseProductName
}
return SystemProperties.getUserHome().replace('/', File.separatorChar) + File.separator + productName + "Projects"
}
suspend fun openOrImportFilesAsync(list: List<Path>, location: String, projectToClose: Project? = null): Project? {
for (file in list) {
openOrImportAsync(file = file, options = OpenProjectTask {
this.projectToClose = projectToClose
forceOpenInNewFrame = true
})?.let { return it }
}
var result: Project? = null
for (file in list) {
if (!Files.exists(file)) {
continue
}
LOG.debug("$location: open file ", file)
if (projectToClose == null) {
val processor = CommandLineProjectOpenProcessor.getInstanceIfExists()
if (processor != null) {
val opened = PlatformProjectOpenProcessor.openProjectAsync(file)
if (opened != null && result == null) {
result = opened
}
}
}
else {
val virtualFile = LocalFileSystem.getInstance().refreshAndFindFileByPath(FileUtilRt.toSystemIndependentName(file.toString()))
if (virtualFile != null && virtualFile.isValid) {
OpenFileAction.openFile(virtualFile, projectToClose)
}
result = projectToClose
}
}
return result
}
//todo: merge somehow with getBaseDir
@JvmStatic
fun getProjectsPath(): @SystemDependent String {
val application = ApplicationManager.getApplication()
val fromSettings = if (application == null || application.isHeadlessEnvironment) null else GeneralSettings.getInstance().defaultProjectDirectory
if (!fromSettings.isNullOrEmpty()) {
return PathManager.getAbsolutePath(fromSettings)
}
if (ourProjectsPath == null) {
val produceName = ApplicationNamesInfo.getInstance().productName.lowercase()
val propertyName = String.format(PROPERTY_PROJECT_PATH, produceName)
val propertyValue = System.getProperty(propertyName)
ourProjectsPath = if (propertyValue != null) PathManager.getAbsolutePath(StringUtil.unquoteString(propertyValue, '\"'))
else projectsDirDefault
}
return ourProjectsPath!!
}
private val projectsDirDefault: String
get() = if (PlatformUtils.isDataGrip()) getUserHomeProjectDir() else PathManager.getConfigPath() + File.separator + PROJECTS_DIR
fun getProjectPath(name: String): Path {
return Path.of(getProjectsPath(), name)
}
fun getProjectFile(name: String): Path? {
val projectDir = getProjectPath(name)
return if (isProjectFile(projectDir)) projectDir else null
}
private fun isProjectFile(projectDir: Path): Boolean {
return Files.isDirectory(projectDir.resolve(Project.DIRECTORY_STORE_FOLDER))
}
@JvmStatic
fun openOrCreateProject(name: String, file: Path): Project? {
return runBlockingUnderModalProgress {
openOrCreateProjectInner(name, file)
}
}
private suspend fun openOrCreateProjectInner(name: String, file: Path): Project? {
val existingFile = if (isProjectFile(file)) file else null
val projectManager = ProjectManagerEx.getInstanceEx()
if (existingFile != null) {
val openProjects = ProjectManager.getInstance().openProjects
for (p in openProjects) {
if (!p.isDefault && isSameProject(existingFile, p)) {
focusProjectWindow(p, false)
return p
}
}
return projectManager.openProjectAsync(existingFile, OpenProjectTask { runConfigurators = true })
}
@Suppress("BlockingMethodInNonBlockingContext")
val created = try {
withContext(Dispatchers.IO) {
!Files.exists(file) && Files.createDirectories(file) != null || Files.isDirectory(file)
}
}
catch (e: IOException) {
false
}
var projectFile: Path? = null
if (created) {
val options = OpenProjectTask {
isNewProject = true
runConfigurators = true
projectName = name
}
val project = projectManager.newProjectAsync(file = file, options = options)
runInAutoSaveDisabledMode {
saveSettings(componentManager = project, forceSavingAllSettings = true)
}
writeAction {
Disposer.dispose(project)
}
projectFile = file
}
if (projectFile == null) {
return null
}
return projectManager.openProjectAsync(projectStoreBaseDir = projectFile, options = OpenProjectTask {
runConfigurators = true
isProjectCreatedWithWizard = true
isRefreshVfsNeeded = false
})
}
@JvmStatic
fun getRootFrameForWindow(window: Window?): IdeFrame? {
var w = window ?: return null
while (w.owner != null) {
w = w.owner
}
return w as? IdeFrame
}
fun getProjectForWindow(window: Window?): Project? {
return getRootFrameForWindow(window)?.project
}
@JvmStatic
fun getProjectForComponent(component: Component?): Project? = getProjectForWindow(ComponentUtil.getWindow(component))
@JvmStatic
fun getActiveProject(): Project? = getProjectForWindow(KeyboardFocusManager.getCurrentKeyboardFocusManager().activeWindow)
interface ProjectCreatedCallback {
fun projectCreated(project: Project?)
}
@JvmStatic
fun getOpenProjects(): Array<Project> = ProjectUtilCore.getOpenProjects()
@Internal
@VisibleForTesting
suspend fun openExistingDir(file: Path, currentProject: Project?): Project? {
val canAttach = ProjectAttachProcessor.canAttachToProject()
val preferAttach = currentProject != null &&
canAttach &&
(PlatformUtils.isDataGrip() && !ProjectUtilCore.isValidProjectPath(file) || PlatformUtils.isDataSpell())
if (preferAttach && attachToProject(currentProject!!, file, null)) {
return null
}
val project = if (canAttach) {
val options = createOptionsToOpenDotIdeaOrCreateNewIfNotExists(file, currentProject)
ProjectManagerEx.getInstanceEx().openProjectAsync(file, options)
}
else {
openOrImportAsync(file, OpenProjectTask().withProjectToClose(currentProject))
}
if (!ApplicationManager.getApplication().isUnitTestMode) {
FileChooserUtil.setLastOpenedFile(project, file)
}
return project
}
@JvmStatic
fun isValidProjectPath(file: Path): Boolean {
return ProjectUtilCore.isValidProjectPath(file)
}
}
@Suppress("DeprecatedCallableAddReplaceWith")
@Internal
@ScheduledForRemoval
@Deprecated(
"Use runBlockingModal on EDT with proper owner and title, " +
"or runBlockingCancellable(+withBackgroundProgressIndicator with proper title) on BGT"
)
// inline is not used - easier debug
fun <T> runUnderModalProgressIfIsEdt(task: suspend CoroutineScope.() -> T): T {
if (!ApplicationManager.getApplication().isDispatchThread) {
return runBlocking(CoreProgressManager.getCurrentThreadProgressModality().asContextElement()) { task() }
}
return runBlockingUnderModalProgress(task = task)
}
@Suppress("DeprecatedCallableAddReplaceWith")
@Internal
@RequiresEdt
@ScheduledForRemoval
@Deprecated("Use runBlockingModal with proper owner and title")
fun <T> runBlockingUnderModalProgress(@NlsContexts.ProgressTitle title: String = "", project: Project? = null, task: suspend CoroutineScope.() -> T): T {
return ProgressManager.getInstance().runProcessWithProgressSynchronously(ThrowableComputable {
val modalityState = CoreProgressManager.getCurrentThreadProgressModality()
runBlocking(modalityState.asContextElement()) {
task()
}
}, title, true, project)
}
@Suppress("DeprecatedCallableAddReplaceWith")
@Internal
@Deprecated(message = "temporary solution for old code in java", level = DeprecationLevel.ERROR)
fun Project.executeOnPooledThread(task: Runnable) {
coroutineScope.launch { task.run() }
}
@Suppress("DeprecatedCallableAddReplaceWith")
@Internal
@Deprecated(message = "temporary solution for old code in java", level = DeprecationLevel.ERROR)
fun <T> Project.computeOnPooledThread(task: Callable<T>): CompletableFuture<T> {
return coroutineScope.async { task.call() }.asCompletableFuture()
}
@Suppress("DeprecatedCallableAddReplaceWith")
@Internal
@Deprecated(message = "temporary solution for old code in java", level = DeprecationLevel.ERROR)
fun Project.executeOnPooledIoThread(task: Runnable) {
coroutineScope.launch(Dispatchers.IO) { task.run() }
} | apache-2.0 | 8765a8ed10ea0fce69f146cba437d577 | 37.589744 | 216 | 0.70882 | 4.985876 | false | false | false | false |
EvelynSubarrow/Commandspy3 | src/main/kotlin/moe/evelyn/commandspy/util/Util.kt | 1 | 2473 | /*
Commandspy - A Minecraft server plugin to facilitate real-time usage of commands, and sign-changes
Copyright (C) 2014,2015 Evelyn Snow
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 moe.evelyn.commandspy.util
import moe.evelyn.commandspy.Main
import java.io.Closeable
import java.io.InputStream
import java.io.Writer
import java.security.cert.CertificateFactory
import java.security.cert.X509Certificate
inline fun <T :Closeable, R> T.with(block: (T) -> R): R
{
val a = block(this)
tryonly {
if (this is Writer) flush()
close()
}
return a
}
fun <R> tryonly(catch :(Exception) -> R? = { null }, lambda :() -> R) :R?
{
try {
return lambda()
} catch (e :Exception) {
return catch(e)
}
}
class Util
{
private constructor() { }
companion object
{
val util = Util()
fun join(a :Array<String>, delimiter :String, startIndex :Int) :String
{
var result = ""
for (i in startIndex..a.size - 1)
result += a[i] + if (i != a.size - 1) delimiter else ""
return result
}
}
/*
*/
fun sit(iStr :String, delimiter :Char, part :Int) :String
{
if (part == 0) {
if (!iStr.contains(delimiter))
return iStr
} else {
if (!iStr.contains(delimiter))
return ""
}
if (part == 0)
return iStr.substring(0, (iStr.indexOf(delimiter, 0)))
return iStr.substring(iStr.indexOf(delimiter, 0) + 1, iStr.length)
}
fun getPemResource(path :String) :X509Certificate
{
val ins : InputStream = Main::class.java.classLoader.getResource(path).openStream()
val cf = CertificateFactory.getInstance("X.509")
return cf.generateCertificate(ins) as X509Certificate
}
} | gpl-3.0 | 277a0e178e976566e6b767afa890866f | 28.105882 | 102 | 0.623939 | 3.975884 | false | false | false | false |
JetBrains/intellij-community | platform/build-scripts/src/org/jetbrains/intellij/build/impl/MacDistributionBuilder.kt | 1 | 23316 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
@file:Suppress("BlockingMethodInNonBlockingContext")
package org.jetbrains.intellij.build.impl
import com.intellij.diagnostic.telemetry.use
import com.intellij.diagnostic.telemetry.useWithScope2
import com.intellij.openapi.util.SystemInfoRt
import com.intellij.util.SystemProperties
import io.opentelemetry.api.common.AttributeKey
import io.opentelemetry.api.trace.Span
import kotlinx.collections.immutable.PersistentMap
import kotlinx.collections.immutable.persistentListOf
import kotlinx.collections.immutable.persistentMapOf
import kotlinx.coroutines.*
import org.apache.commons.compress.archivers.zip.ZipArchiveEntry
import org.jetbrains.intellij.build.*
import org.jetbrains.intellij.build.TraceManager.spanBuilder
import org.jetbrains.intellij.build.impl.productInfo.ProductInfoLaunchData
import org.jetbrains.intellij.build.impl.productInfo.checkInArchive
import org.jetbrains.intellij.build.impl.productInfo.generateMultiPlatformProductJson
import org.jetbrains.intellij.build.io.copyDir
import org.jetbrains.intellij.build.io.copyFile
import org.jetbrains.intellij.build.io.substituteTemplatePlaceholders
import org.jetbrains.intellij.build.io.writeNewFile
import java.io.File
import java.nio.file.Files
import java.nio.file.Path
import java.nio.file.attribute.PosixFilePermission
import java.time.LocalDate
import java.util.function.BiConsumer
import java.util.zip.Deflater
import kotlin.io.path.nameWithoutExtension
internal val MAC_CODE_SIGN_OPTIONS: PersistentMap<String, String> = persistentMapOf(
"mac_codesign_options" to "runtime",
"mac_codesign_force" to "true",
"mac_codesign_deep" to "true",
)
class MacDistributionBuilder(override val context: BuildContext,
private val customizer: MacDistributionCustomizer,
private val ideaProperties: Path?) : OsSpecificDistributionBuilder {
private val targetIcnsFileName: String = "${context.productProperties.baseFileName}.icns"
override val targetOs: OsFamily
get() = OsFamily.MACOS
private fun getDocTypes(): String {
val associations = mutableListOf<String>()
if (customizer.associateIpr) {
val association = """<dict>
<key>CFBundleTypeExtensions</key>
<array>
<string>ipr</string>
</array>
<key>CFBundleTypeIconFile</key>
<string>${targetIcnsFileName}</string>
<key>CFBundleTypeName</key>
<string>${context.applicationInfo.productName} Project File</string>
<key>CFBundleTypeRole</key>
<string>Editor</string>
</dict>"""
associations.add(association)
}
for (fileAssociation in customizer.fileAssociations) {
val iconPath = fileAssociation.iconPath
val association = """<dict>
<key>CFBundleTypeExtensions</key>
<array>
<string>${fileAssociation.extension}</string>
</array>
<key>CFBundleTypeIconFile</key>
<string>${if (iconPath.isEmpty()) targetIcnsFileName else File(iconPath).name}</string>
<key>CFBundleTypeRole</key>
<string>Editor</string>
</dict>"""
associations.add(association)
}
return associations.joinToString(separator = "\n ") + customizer.additionalDocTypes
}
override suspend fun copyFilesForOsDistribution(targetPath: Path, arch: JvmArchitecture) {
withContext(Dispatchers.IO) {
doCopyExtraFiles(macDistDir = targetPath, arch = arch, copyDistFiles = true)
}
}
private suspend fun doCopyExtraFiles(macDistDir: Path, arch: JvmArchitecture, copyDistFiles: Boolean) {
@Suppress("SpellCheckingInspection")
val platformProperties = mutableListOf(
"\n#---------------------------------------------------------------------",
"# macOS-specific system properties",
"#---------------------------------------------------------------------",
"com.apple.mrj.application.live-resize=false",
"jbScreenMenuBar.enabled=true",
"apple.awt.fileDialogForDirectories=true",
"apple.awt.graphics.UseQuartz=true",
"apple.awt.fullscreencapturealldisplays=false"
)
customizer.getCustomIdeaProperties(context.applicationInfo).forEach(BiConsumer { k, v -> platformProperties.add("$k=$v") })
layoutMacApp(ideaPropertiesFile = ideaProperties!!,
platformProperties = platformProperties,
docTypes = getDocTypes(),
macDistDir = macDistDir,
arch = arch,
context = context)
generateBuildTxt(context, macDistDir.resolve("Resources"))
// if copyDistFiles false, it means that we will copy dist files directly without stage dir
if (copyDistFiles) {
copyDistFiles(context = context, newDir = macDistDir, os = OsFamily.MACOS, arch = arch)
}
customizer.copyAdditionalFiles(context = context, targetDirectory = macDistDir.toString())
customizer.copyAdditionalFiles(context = context, targetDirectory = macDistDir, arch = arch)
generateUnixScripts(distBinDir = macDistDir.resolve("bin"),
os = OsFamily.MACOS,
arch = arch,
context = context)
}
override suspend fun buildArtifacts(osAndArchSpecificDistPath: Path, arch: JvmArchitecture) {
withContext(Dispatchers.IO) {
doCopyExtraFiles(macDistDir = osAndArchSpecificDistPath, arch = arch, copyDistFiles = false)
}
context.executeStep(spanBuilder("build macOS artifacts").setAttribute("arch", arch.name), BuildOptions.MAC_ARTIFACTS_STEP) {
val baseName = context.productProperties.getBaseArtifactName(context.applicationInfo, context.buildNumber)
val publishSit = context.publishSitArchive
val publishZipOnly = !publishSit && context.options.buildStepsToSkip.contains(BuildOptions.MAC_DMG_STEP)
val binariesToSign = customizer.getBinariesToSign(context, arch)
if (!binariesToSign.isEmpty()) {
context.executeStep(spanBuilder("sign binaries for macOS distribution")
.setAttribute("arch", arch.name), BuildOptions.MAC_SIGN_STEP) {
context.signFiles(binariesToSign.map(osAndArchSpecificDistPath::resolve), MAC_CODE_SIGN_OPTIONS)
}
}
val macZip = (if (publishZipOnly) context.paths.artifactDir else context.paths.tempDir).resolve("$baseName.mac.${arch.name}.zip")
val macZipWithoutRuntime = macZip.resolveSibling(macZip.nameWithoutExtension + "-no-jdk.zip")
val zipRoot = getMacZipRoot(customizer, context)
val runtimeDist = context.bundledRuntime.extract(BundledRuntimeImpl.getProductPrefix(context), OsFamily.MACOS, arch)
val directories = listOf(context.paths.distAllDir, osAndArchSpecificDistPath, runtimeDist)
val extraFiles = context.getDistFiles(os = OsFamily.MACOS, arch = arch)
val compressionLevel = if (publishSit || publishZipOnly) Deflater.DEFAULT_COMPRESSION else Deflater.BEST_SPEED
if (context.options.buildMacArtifactsWithRuntime) {
buildMacZip(
targetFile = macZip,
zipRoot = zipRoot,
productJson = generateMacProductJson(builtinModule = context.builtinModule,
arch = arch,
javaExecutablePath = "../jbr/Contents/Home/bin/java",
context = context),
directories = directories,
extraFiles = extraFiles,
executableFilePatterns = generateExecutableFilesPatterns(true),
compressionLevel = compressionLevel
)
}
if (context.options.buildMacArtifactsWithoutRuntime) {
buildMacZip(
targetFile = macZipWithoutRuntime,
zipRoot = zipRoot,
productJson = generateMacProductJson(builtinModule = context.builtinModule,
arch = arch,
javaExecutablePath = null,
context = context),
directories = directories.filterNot { it == runtimeDist },
extraFiles = extraFiles,
executableFilePatterns = generateExecutableFilesPatterns(false),
compressionLevel = compressionLevel
)
}
if (publishZipOnly) {
Span.current().addEvent("skip DMG and SIT artifacts producing")
if (context.options.buildMacArtifactsWithRuntime) {
context.notifyArtifactBuilt(macZip)
}
if (context.options.buildMacArtifactsWithoutRuntime) {
context.notifyArtifactBuilt(macZipWithoutRuntime)
}
}
else {
buildForArch(builtinModule = context.builtinModule,
arch = arch,
macZip = macZip,
macZipWithoutRuntime = macZipWithoutRuntime,
customizer = customizer,
context = context)
}
}
}
private fun layoutMacApp(ideaPropertiesFile: Path,
platformProperties: List<String>,
docTypes: String?,
macDistDir: Path,
arch: JvmArchitecture,
context: BuildContext) {
val macCustomizer = customizer
copyDirWithFileFilter(context.paths.communityHomeDir.resolve("bin/mac"), macDistDir.resolve("bin"), customizer.binFilesFilter)
copyDir(context.paths.communityHomeDir.resolve("platform/build-scripts/resources/mac/Contents"), macDistDir)
val executable = context.productProperties.baseFileName
Files.move(macDistDir.resolve("MacOS/executable"), macDistDir.resolve("MacOS/$executable"))
//noinspection SpellCheckingInspection
val icnsPath = Path.of((if (context.applicationInfo.isEAP) customizer.icnsPathForEAP else null) ?: customizer.icnsPath)
val resourcesDistDir = macDistDir.resolve("Resources")
copyFile(icnsPath, resourcesDistDir.resolve(targetIcnsFileName))
for (fileAssociation in customizer.fileAssociations) {
if (!fileAssociation.iconPath.isEmpty()) {
val source = Path.of(fileAssociation.iconPath)
val dest = resourcesDistDir.resolve(source.fileName)
Files.deleteIfExists(dest)
copyFile(source, dest)
}
}
val fullName = context.applicationInfo.productName
//todo[nik] improve
val minor = context.applicationInfo.minorVersion
val isNotRelease = context.applicationInfo.isEAP && !minor.contains("RC") && !minor.contains("Beta")
val version = if (isNotRelease) "EAP ${context.fullBuildNumber}" else "${context.applicationInfo.majorVersion}.${minor}"
val isEap = if (isNotRelease) "-EAP" else ""
val properties = Files.readAllLines(ideaPropertiesFile)
properties.addAll(platformProperties)
Files.write(macDistDir.resolve("bin/idea.properties"), properties)
val bootClassPath = context.xBootClassPathJarNames.joinToString(separator = ":") { "\$APP_PACKAGE/Contents/lib/$it" }
val classPath = context.bootClassPathJarNames.joinToString(separator = ":") { "\$APP_PACKAGE/Contents/lib/$it" }
val fileVmOptions = VmOptionsGenerator.computeVmOptions(context.applicationInfo.isEAP, context.productProperties).toMutableList()
val additionalJvmArgs = context.getAdditionalJvmArguments(OsFamily.MACOS, arch).toMutableList()
if (!bootClassPath.isEmpty()) {
//noinspection SpellCheckingInspection
additionalJvmArgs.add("-Xbootclasspath/a:$bootClassPath")
}
val predicate: (String) -> Boolean = { it.startsWith("-D") }
val launcherProperties = additionalJvmArgs.filter(predicate)
val launcherVmOptions = additionalJvmArgs.filterNot(predicate)
fileVmOptions.add("-XX:ErrorFile=\$USER_HOME/java_error_in_${executable}_%p.log")
fileVmOptions.add("-XX:HeapDumpPath=\$USER_HOME/java_error_in_${executable}.hprof")
VmOptionsGenerator.writeVmOptions(macDistDir.resolve("bin/${executable}.vmoptions"), fileVmOptions, "\n")
val urlSchemes = macCustomizer.urlSchemes
val urlSchemesString = if (urlSchemes.isEmpty()) {
""
}
else {
"""
<key>CFBundleURLTypes</key>
<array>
<dict>
<key>CFBundleTypeRole</key>
<string>Editor</string>
<key>CFBundleURLName</key>
<string>Stacktrace</string>
<key>CFBundleURLSchemes</key>
<array>
${urlSchemes.joinToString(separator = "\n") { " <string>$it</string>" }}
</array>
</dict>
</array>
"""
}
val todayYear = LocalDate.now().year.toString()
//noinspection SpellCheckingInspection
substituteTemplatePlaceholders(
inputFile = macDistDir.resolve("Info.plist"),
outputFile = macDistDir.resolve("Info.plist"),
placeholder = "@@",
values = listOf(
Pair("build", context.fullBuildNumber),
Pair("doc_types", docTypes ?: ""),
Pair("executable", executable),
Pair("icns", targetIcnsFileName),
Pair("bundle_name", fullName),
Pair("product_state", isEap),
Pair("bundle_identifier", macCustomizer.bundleIdentifier),
Pair("year", todayYear),
Pair("version", version),
Pair("vm_options", optionsToXml(launcherVmOptions)),
Pair("vm_properties", propertiesToXml(launcherProperties, mapOf("idea.executable" to context.productProperties.baseFileName))),
Pair("class_path", classPath),
Pair("main_class_name", context.productProperties.mainClassName.replace('.', '/')),
Pair("url_schemes", urlSchemesString),
Pair("architectures", "<key>LSArchitecturePriority</key>\n <array>\n" +
macCustomizer.architectures.joinToString(separator = "\n") { " <string>$it</string>\n" } +
" </array>"),
Pair("min_osx", macCustomizer.minOSXVersion),
)
)
val distBinDir = macDistDir.resolve("bin")
Files.createDirectories(distBinDir)
val sourceScriptDir = context.paths.communityHomeDir.resolve("platform/build-scripts/resources/mac/scripts")
Files.newDirectoryStream(sourceScriptDir).use { stream ->
val inspectCommandName = context.productProperties.inspectCommandName
for (file in stream) {
if (file.toString().endsWith(".sh")) {
var fileName = file.fileName.toString()
if (fileName == "inspect.sh" && inspectCommandName != "inspect") {
fileName = "${inspectCommandName}.sh"
}
val sourceFileLf = Files.createTempFile(context.paths.tempDir, file.fileName.toString(), "")
try {
// Until CR (\r) will be removed from the repository checkout, we need to filter it out from Unix-style scripts
// https://youtrack.jetbrains.com/issue/IJI-526/Force-git-to-use-LF-line-endings-in-working-copy-of-via-gitattri
Files.writeString(sourceFileLf, Files.readString(file).replace("\r", ""))
val target = distBinDir.resolve(fileName)
substituteTemplatePlaceholders(
sourceFileLf,
target,
"@@",
listOf(
Pair("product_full", fullName),
Pair("script_name", executable),
Pair("inspectCommandName", inspectCommandName),
),
false,
)
}
finally {
Files.delete(sourceFileLf)
}
}
}
}
}
override fun generateExecutableFilesPatterns(includeRuntime: Boolean): List<String> {
var executableFilePatterns = persistentListOf(
"bin/*.sh",
"plugins/**/*.sh",
"bin/*.py",
"bin/fsnotifier",
"bin/printenv",
"bin/restarter",
"bin/repair",
"MacOS/*"
)
if (includeRuntime) {
executableFilePatterns = executableFilePatterns.addAll(context.bundledRuntime.executableFilesPatterns(OsFamily.MACOS))
}
return executableFilePatterns
.addAll(customizer.extraExecutables)
.addAll(context.getExtraExecutablePattern(OsFamily.MACOS))
}
private suspend fun buildForArch(builtinModule: BuiltinModulesFileData?,
arch: JvmArchitecture,
macZip: Path, macZipWithoutRuntime: Path?,
customizer: MacDistributionCustomizer,
context: BuildContext) {
spanBuilder("build macOS artifacts for specific arch").setAttribute("arch", arch.name).useWithScope2 {
val notarize = SystemProperties.getBooleanProperty("intellij.build.mac.notarize", true)
withContext(Dispatchers.IO) {
buildForArch(builtinModule, arch, macZip, macZipWithoutRuntime, notarize, customizer, context)
Files.deleteIfExists(macZip)
}
}
}
private suspend fun buildForArch(builtinModule: BuiltinModulesFileData?,
arch: JvmArchitecture,
macZip: Path, macZipWithoutRuntime: Path?,
notarize: Boolean,
customizer: MacDistributionCustomizer,
context: BuildContext) {
val suffix = if (arch == JvmArchitecture.x64) "" else "-${arch.fileSuffix}"
val archStr = arch.name
coroutineScope {
if (context.options.buildMacArtifactsWithRuntime) {
createSkippableJob(
spanBuilder("build DMG with Runtime").setAttribute("arch", archStr), "${BuildOptions.MAC_ARTIFACTS_STEP}_jre_$archStr",
context
) {
signAndBuildDmg(builder = this@MacDistributionBuilder,
builtinModule = builtinModule,
context = context,
customizer = customizer,
macHostProperties = context.proprietaryBuildTools.macHostProperties,
macZip = macZip,
isRuntimeBundled = true,
suffix = suffix,
arch = arch,
notarize = notarize)
}
}
if (context.options.buildMacArtifactsWithoutRuntime) {
requireNotNull(macZipWithoutRuntime)
createSkippableJob(
spanBuilder("build DMG without Runtime").setAttribute("arch", archStr), "${BuildOptions.MAC_ARTIFACTS_STEP}_no_jre_$archStr",
context
) {
signAndBuildDmg(builder = this@MacDistributionBuilder,
builtinModule = builtinModule,
context = context,
customizer = customizer,
macHostProperties = context.proprietaryBuildTools.macHostProperties,
macZip = macZipWithoutRuntime,
isRuntimeBundled = false,
suffix = "-no-jdk$suffix",
arch = arch,
notarize = notarize)
}
}
}
}
}
private fun optionsToXml(options: List<String>): String {
val buff = StringBuilder()
for (it in options) {
buff.append(" <string>").append(it).append("</string>\n")
}
return buff.toString().trim()
}
private fun propertiesToXml(properties: List<String>, moreProperties: Map<String, String>): String {
val buff = StringBuilder()
for (it in properties) {
val p = it.indexOf('=')
buff.append(" <key>").append(it.substring(2, p)).append("</key>\n")
buff.append(" <string>").append(it.substring(p + 1)).append("</string>\n")
}
moreProperties.forEach { (key, value) ->
buff.append(" <key>").append(key).append("</key>\n")
buff.append(" <string>").append(value).append("</string>\n")
}
return buff.toString().trim()
}
internal fun getMacZipRoot(customizer: MacDistributionCustomizer, context: BuildContext): String =
"${customizer.getRootDirectoryName(context.applicationInfo, context.buildNumber)}/Contents"
internal fun generateMacProductJson(builtinModule: BuiltinModulesFileData?,
arch: JvmArchitecture,
javaExecutablePath: String?,
context: BuildContext): String {
val executable = context.productProperties.baseFileName
return generateMultiPlatformProductJson(
relativePathToBin = "../bin",
builtinModules = builtinModule,
launch = listOf(ProductInfoLaunchData(
os = OsFamily.MACOS.osName,
arch = arch.dirName,
launcherPath = "../MacOS/${executable}",
javaExecutablePath = javaExecutablePath,
vmOptionsFilePath = "../bin/${executable}.vmoptions",
startupWmClass = null,
bootClassPathJarNames = context.bootClassPathJarNames,
additionalJvmArguments = context.getAdditionalJvmArguments(OsFamily.MACOS, arch))),
context = context)
}
private fun MacDistributionBuilder.buildMacZip(targetFile: Path,
zipRoot: String,
productJson: String,
directories: List<Path>,
extraFiles: Collection<DistFile>,
executableFilePatterns: List<String>,
compressionLevel: Int) {
spanBuilder("build zip archive for macOS")
.setAttribute("file", targetFile.toString())
.setAttribute("zipRoot", zipRoot)
.setAttribute(AttributeKey.stringArrayKey("executableFilePatterns"), executableFilePatterns)
.use {
for (dir in directories) {
updateExecutablePermissions(dir, executableFilePatterns)
}
val entryCustomizer: (ZipArchiveEntry, Path, String) -> Unit = { entry, file, _ ->
if (SystemInfoRt.isUnix && PosixFilePermission.OWNER_EXECUTE in Files.getPosixFilePermissions(file)) {
entry.unixMode = executableFileUnixMode
}
}
writeNewFile(targetFile) { targetFileChannel ->
NoDuplicateZipArchiveOutputStream(targetFileChannel, compress = context.options.compressZipFiles).use { zipOutStream ->
zipOutStream.setLevel(compressionLevel)
zipOutStream.entry("$zipRoot/Resources/product-info.json", productJson.encodeToByteArray())
val fileFilter: (Path, String) -> Boolean = { sourceFile, relativePath ->
if (relativePath.endsWith(".txt") && !relativePath.contains('/')) {
zipOutStream.entry("$zipRoot/Resources/${relativePath}", sourceFile)
false
}
else {
true
}
}
for (dir in directories) {
zipOutStream.dir(dir, "$zipRoot/", fileFilter = fileFilter, entryCustomizer = entryCustomizer)
}
for (item in extraFiles) {
zipOutStream.entry(name = "$zipRoot/${item.relativePath}", file = item.file)
}
}
}
checkInArchive(archiveFile = targetFile, pathInArchive = "$zipRoot/Resources", context = context)
}
}
| apache-2.0 | 8f9fe91cd0797a4796d99be276ac2a3b | 43.924855 | 135 | 0.636473 | 5.241906 | false | false | false | false |
StepicOrg/stepik-android | app/src/main/java/org/stepik/android/domain/user_courses/repository/UserCoursesRepository.kt | 1 | 1101 | package org.stepik.android.domain.user_courses.repository
import io.reactivex.Completable
import io.reactivex.Maybe
import io.reactivex.Single
import ru.nobird.app.core.model.PagedList
import org.stepik.android.domain.base.DataSourceType
import org.stepik.android.domain.course_list.model.UserCourseQuery
import org.stepik.android.domain.user_courses.model.UserCourse
interface UserCoursesRepository {
fun getAllUserCourses(userCourseQuery: UserCourseQuery = UserCourseQuery(page = 1), sourceType: DataSourceType = DataSourceType.CACHE): Single<List<UserCourse>>
fun getUserCourses(userCourseQuery: UserCourseQuery = UserCourseQuery(page = 1, isArchived = false), sourceType: DataSourceType = DataSourceType.CACHE): Single<PagedList<UserCourse>>
fun getUserCourseByCourseId(courseId: Long, sourceType: DataSourceType = DataSourceType.CACHE): Maybe<UserCourse>
fun saveUserCourse(userCourse: UserCourse): Single<UserCourse>
/***
* Cached purpose only
*/
fun addUserCourse(userCourse: UserCourse): Completable
fun removeUserCourse(courseId: Long): Completable
} | apache-2.0 | c0b0cfced7665d8577add37c045ab663 | 49.090909 | 186 | 0.802906 | 4.74569 | false | false | false | false |
ursjoss/sipamato | core/core-web/src/main/java/ch/difty/scipamato/core/web/paper/csv/CsvAdapter.kt | 1 | 2801 | package ch.difty.scipamato.core.web.paper.csv
import ch.difty.scipamato.core.entity.Paper
import ch.difty.scipamato.core.web.paper.jasper.ReportHeaderFields
import ch.difty.scipamato.core.web.paper.jasper.review.PaperReview
import com.univocity.parsers.csv.CsvFormat
import com.univocity.parsers.csv.CsvWriter
import com.univocity.parsers.csv.CsvWriterSettings
import java.io.Serializable
import java.io.StringWriter
/**
* CSV Adapter accepting a list of objects of type [T]
* and builds a full CSV file as a single String.
*
* Works well for small number of records but doesn't scale well.
*/
interface CsvAdapter<T> : Serializable {
fun build(types: List<T>): String
}
@Suppress("FunctionName")
abstract class AbstractCsvAdapter<T>(
private val rowMapper: (Collection<T>) -> List<Array<String>>,
private val headers: Array<String?>
) : CsvAdapter<T> {
override fun build(types: List<T>): String {
val rows: List<Array<String>> = rowMapper(types)
StringWriterWithBom().apply {
CsvWriter(this, SemicolonDelimitedSettings()).apply {
writeHeaders(*headers)
writeRowsAndClose(rows)
}
return toString()
}
}
private fun StringWriterWithBom() = StringWriter().apply { write("\ufeff") }
private fun SemicolonDelimitedSettings() = CsvWriterSettings().apply {
format = CsvFormat().apply { delimiter = ';' }
}
}
/**
* Adapter to build the Review CSV file, accepting a list of [Paper]s
*/
class ReviewCsvAdapter(private val rhf: ReportHeaderFields) : AbstractCsvAdapter<Paper>(
rowMapper = { types -> types.map { PaperReview(it, rhf).toRow() } },
headers = arrayOf(
rhf.numberLabel,
rhf.authorYearLabel,
rhf.populationPlaceLabel,
rhf.methodOutcomeLabel,
rhf.exposurePollutantLabel,
rhf.methodStudyDesignLabel,
rhf.populationDurationLabel,
rhf.populationParticipantsLabel,
rhf.exposureAssessmentLabel,
rhf.resultExposureRangeLabel,
rhf.methodConfoundersLabel,
rhf.resultEffectEstimateLabel,
rhf.conclusionLabel,
rhf.commentLabel,
rhf.internLabel,
rhf.goalsLabel,
rhf.populationLabel,
rhf.methodsLabel,
rhf.resultLabel,
),
) {
companion object {
const val FILE_NAME = "review.csv"
}
}
private fun PaperReview.toRow() = arrayOf(
number,
authorYear,
populationPlace,
methodOutcome,
exposurePollutant,
methodStudyDesign,
populationDuration,
populationParticipants,
exposureAssessment,
resultExposureRange,
methodConfounders,
resultEffectEstimate,
conclusion,
comment,
intern,
goals,
population,
methods,
result,
)
| gpl-3.0 | ba64834cfa8fcc3ae7c42197d9bb1e3c | 27.581633 | 88 | 0.6794 | 4.237519 | false | false | false | false |
allotria/intellij-community | platform/workspaceModel/storage/src/com/intellij/workspaceModel/storage/impl/indices/MultimapStorageIndex.kt | 3 | 2637 | // 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.workspaceModel.storage.impl.indices
import com.intellij.util.containers.BidirectionalMultiMap
import com.intellij.workspaceModel.storage.PersistentEntityId
import com.intellij.workspaceModel.storage.impl.EntityId
import com.intellij.workspaceModel.storage.impl.containers.copy
import com.intellij.workspaceModel.storage.impl.containers.putAll
import org.jetbrains.annotations.TestOnly
open class MultimapStorageIndex private constructor(
internal open val index: BidirectionalMultiMap<EntityId, PersistentEntityId<*>>
) {
constructor() : this(BidirectionalMultiMap<EntityId, PersistentEntityId<*>>())
internal fun getIdsByEntry(entitySource: PersistentEntityId<*>): Set<EntityId> = index.getKeys(entitySource)
internal fun getEntriesById(id: EntityId): Set<PersistentEntityId<*>> = index.getValues(id)
internal fun entries(): Collection<PersistentEntityId<*>> = index.values
class MutableMultimapStorageIndex private constructor(
// Do not write to [index] directly! Create a method in this index and call [startWrite] before write.
override var index: BidirectionalMultiMap<EntityId, PersistentEntityId<*>>
) : MultimapStorageIndex(index) {
private var freezed = true
internal fun index(id: EntityId, elements: Set<PersistentEntityId<*>>? = null) {
startWrite()
index.removeKey(id)
if (elements == null) return
elements.forEach { index.put(id, it) }
}
internal fun index(id: EntityId, element: PersistentEntityId<*>) {
startWrite()
index.put(id, element)
}
internal fun remove(id: EntityId, element: PersistentEntityId<*>) {
startWrite()
index.remove(id, element)
}
@TestOnly
internal fun clear() {
startWrite()
index.clear()
}
@TestOnly
internal fun copyFrom(another: MultimapStorageIndex) {
startWrite()
this.index.putAll(another.index)
}
private fun startWrite() {
if (!freezed) return
freezed = false
index = copyIndex()
}
private fun copyIndex(): BidirectionalMultiMap<EntityId, PersistentEntityId<*>> = index.copy()
fun toImmutable(): MultimapStorageIndex {
freezed = true
return MultimapStorageIndex(index)
}
companion object {
fun from(other: MultimapStorageIndex): MutableMultimapStorageIndex {
if (other is MutableMultimapStorageIndex) other.freezed = true
return MutableMultimapStorageIndex(other.index)
}
}
}
}
| apache-2.0 | 9779f24bf5c6e8216eeee2735ff5ff87 | 32.379747 | 140 | 0.722412 | 4.947467 | false | false | false | false |
allotria/intellij-community | platform/statistics/src/com/intellij/internal/statistic/eventLog/StatisticsEventLogProviderUtil.kt | 2 | 2642 | // Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.internal.statistic.eventLog
import com.intellij.internal.statistic.utils.StatisticsRecorderUtil
import com.intellij.internal.statistic.utils.getPluginInfo
import com.intellij.openapi.application.ApplicationInfo
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.extensions.ExtensionPointName
import com.intellij.openapi.util.text.StringUtil
import com.intellij.util.PlatformUtils
import com.intellij.util.containers.ContainerUtil
object StatisticsEventLogProviderUtil {
private val LOG = Logger.getInstance(StatisticsEventLogProviderUtil::class.java)
private val EP_NAME = ExtensionPointName<StatisticsEventLoggerProvider>("com.intellij.statistic.eventLog.eventLoggerProvider")
@JvmStatic
fun getEventLogProviders(): List<StatisticsEventLoggerProvider> {
val providers = EP_NAME.extensionsIfPointIsRegistered
if (providers.isEmpty()) {
return emptyList()
}
val isJetBrainsProduct = isJetBrainsProduct()
return ContainerUtil.filter(providers) { isProviderApplicable(isJetBrainsProduct, it.recorderId, it) }
}
@JvmStatic
fun getEventLogProvider(recorderId: String): StatisticsEventLoggerProvider {
if (ApplicationManager.getApplication().extensionArea.hasExtensionPoint(EP_NAME.name)) {
val isJetBrainsProduct = isJetBrainsProduct()
val provider = EP_NAME.findFirstSafe { isProviderApplicable(isJetBrainsProduct, recorderId, it) }
provider?.let {
if (LOG.isTraceEnabled) {
LOG.trace("Use event log provider '${provider.javaClass.simpleName}' for recorder-id=${recorderId}")
}
return it
}
}
LOG.warn("Cannot find event log provider with recorder-id=${recorderId}")
return EmptyStatisticsEventLoggerProvider(recorderId)
}
private fun isJetBrainsProduct(): Boolean {
val appInfo = ApplicationInfo.getInstance()
if (appInfo == null || StringUtil.isEmpty(appInfo.shortCompanyName)) {
return true
}
return PlatformUtils.isJetBrainsProduct()
}
private fun isProviderApplicable(isJetBrainsProduct: Boolean, recorderId: String, extension: StatisticsEventLoggerProvider): Boolean {
if (recorderId == extension.recorderId) {
if (!isJetBrainsProduct || !StatisticsRecorderUtil.isBuildInRecorder(recorderId)) {
return true
}
return getPluginInfo(extension::class.java).type.isPlatformOrJetBrainsBundled()
}
return false
}
} | apache-2.0 | bf4c788aae2652776816757481efdb33 | 42.327869 | 140 | 0.769114 | 5.100386 | false | false | false | false |
zoetrope/elastiko | src/main/kotlin/elastiko/Client.kt | 1 | 1762 | package elastiko
import org.elasticsearch.client.Client
import org.elasticsearch.client.transport.TransportClient
import org.elasticsearch.common.settings.Settings
import org.elasticsearch.common.transport.InetSocketTransportAddress
import org.elasticsearch.common.transport.TransportAddress
import org.elasticsearch.node.Node
import org.elasticsearch.node.NodeBuilder
import java.net.InetAddress
public fun TransportClient.Builder.settings(block: Settings.Builder.() -> Unit) {
val set = Settings.settingsBuilder()
.apply { block() }
.build()
this.settings(set)
}
public fun address(hostname: String, port: Int): TransportAddress {
return InetSocketTransportAddress(InetAddress.getByName(hostname), port)
}
public fun transportClient(nodes: List<TransportAddress>, block: TransportClient.Builder.() -> Unit): Client {
val client = TransportClient.builder()
.apply { block() }
.build()
nodes.forEach {
client.addTransportAddress(it)
}
return client
}
public fun <T : AutoCloseable, R> T.use(block: (T) -> R): R {
var closed = false
try {
return block(this)
} catch (e: Exception) {
closed = true
try {
close()
} catch (closeException: Exception) {
}
throw e
} finally {
if (!closed) {
close()
}
}
}
public fun NodeBuilder.settings(block: Settings.Builder.() -> Unit) {
val set = Settings.settingsBuilder()
.apply { block() }
.build()
this.settings(set)
}
public fun nodeClient(block: NodeBuilder.() -> Unit): Pair<Node, Client> {
val node = NodeBuilder.nodeBuilder().apply { block() }.node()
return node to node.client()
}
| mit | f6a21ba2cb20275d1126f0485b8477ce | 27.885246 | 110 | 0.657208 | 4.205251 | false | false | false | false |
Kotlin/kotlinx.coroutines | kotlinx-coroutines-debug/test/EnhanceStackTraceWithTreadDumpAsJsonTest.kt | 1 | 1874 | /*
* Copyright 2016-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
*/
@file:Suppress("INVISIBLE_MEMBER", "INVISIBLE_REFERENCE")
package kotlinx.coroutines.debug
import com.google.gson.*
import kotlinx.coroutines.*
import kotlinx.coroutines.debug.internal.*
import org.junit.Test
import kotlin.test.*
class EnhanceStackTraceWithTreadDumpAsJsonTest : DebugTestBase() {
private data class StackTraceElementInfoFromJson(
val declaringClass: String,
val methodName: String,
val fileName: String?,
val lineNumber: Int
)
@Test
fun testEnhancedStackTraceFormatWithDeferred() = runTest {
val deferred = async {
suspendingMethod()
assertTrue(true)
}
yield()
val coroutineInfo = DebugProbesImpl.dumpCoroutinesInfo()
assertEquals(coroutineInfo.size, 2)
val info = coroutineInfo[1]
val enhancedStackTraceAsJsonString = DebugProbesImpl.enhanceStackTraceWithThreadDumpAsJson(info)
val enhancedStackTraceFromJson = Gson().fromJson(enhancedStackTraceAsJsonString, Array<StackTraceElementInfoFromJson>::class.java)
val enhancedStackTrace = DebugProbesImpl.enhanceStackTraceWithThreadDump(info, info.lastObservedStackTrace)
assertEquals(enhancedStackTrace.size, enhancedStackTraceFromJson.size)
for ((frame, frameFromJson) in enhancedStackTrace.zip(enhancedStackTraceFromJson)) {
assertEquals(frame.className, frameFromJson.declaringClass)
assertEquals(frame.methodName, frameFromJson.methodName)
assertEquals(frame.fileName, frameFromJson.fileName)
assertEquals(frame.lineNumber, frameFromJson.lineNumber)
}
deferred.cancelAndJoin()
}
private suspend fun suspendingMethod() {
delay(Long.MAX_VALUE)
}
}
| apache-2.0 | dc215bbac141af1e44b9182eafb35143 | 37.244898 | 138 | 0.720918 | 5.205556 | false | true | false | false |
SmokSmog/smoksmog-android | domain/src/main/kotlin/com/antyzero/smoksmog/storage/model/Module.kt | 1 | 700 | package com.antyzero.smoksmog.storage.model
sealed class Module {
private val _class: String = javaClass.canonicalName
/**
* Show AQI and it's type
*/
class AirQualityIndex(val type: Type = AirQualityIndex.Type.POLISH) : Module() {
enum class Type {
POLISH
}
}
/**
* List of measurements for particulates
*/
class Measurements : Module()
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is Module) return false
if (_class != other._class) return false
return true
}
override fun hashCode(): Int {
return _class.hashCode()
}
} | gpl-3.0 | 0a979ad0789a9fab00e007e2ef1d4e7b | 19.617647 | 84 | 0.585714 | 4.458599 | false | false | false | false |
googlecodelabs/android-gestural-navigation | app/src/main/java/com/example/android/uamp/MediaItemAdapter.kt | 1 | 3761 | /*
* Copyright 2020 Google Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.uamp
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import com.bumptech.glide.Glide
import com.example.android.uamp.MediaItemData.Companion.PLAYBACK_RES_CHANGED
import kotlinx.android.synthetic.main.fragment_mediaitem.view.albumArt
import kotlinx.android.synthetic.main.fragment_mediaitem.view.item_state
import kotlinx.android.synthetic.main.fragment_mediaitem.view.subtitle
import kotlinx.android.synthetic.main.fragment_mediaitem.view.title
/**
* [RecyclerView.Adapter] of [MediaItemData]s used by the [MediaItemFragment].
*/
class MediaItemAdapter(private val itemClickedListener: (MediaItemData) -> Unit
) : ListAdapter<MediaItemData, MediaViewHolder>(MediaItemData.diffCallback) {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MediaViewHolder {
val view = LayoutInflater.from(parent.context)
.inflate(R.layout.fragment_mediaitem, parent, false)
return MediaViewHolder(view, itemClickedListener)
}
override fun onBindViewHolder(holder: MediaViewHolder,
position: Int,
payloads: MutableList<Any>) {
val mediaItem = getItem(position)
var fullRefresh = payloads.isEmpty()
if (payloads.isNotEmpty()) {
payloads.forEach { payload ->
when (payload) {
PLAYBACK_RES_CHANGED -> {
holder.playbackState.setImageResource(mediaItem.playbackRes)
}
// If the payload wasn't understood, refresh the full item (to be safe).
else -> fullRefresh = true
}
}
}
// Normally we only fully refresh the list item if it's being initially bound, but
// we might also do it if there was a payload that wasn't understood, just to ensure
// there isn't a stale item.
if (fullRefresh) {
holder.item = mediaItem
holder.titleView.text = mediaItem.title
holder.subtitleView.text = mediaItem.subtitle
holder.playbackState.setImageResource(mediaItem.playbackRes)
Glide.with(holder.albumArt)
.load(mediaItem.albumArtUri)
.into(holder.albumArt)
}
}
override fun onBindViewHolder(holder: MediaViewHolder, position: Int) {
onBindViewHolder(holder, position, mutableListOf())
}
}
class MediaViewHolder(view: View,
itemClickedListener: (MediaItemData) -> Unit
) : RecyclerView.ViewHolder(view) {
val titleView: TextView = view.title
val subtitleView: TextView = view.subtitle
val albumArt: ImageView = view.albumArt
val playbackState: ImageView = view.item_state
var item: MediaItemData? = null
init {
view.setOnClickListener {
item?.let { itemClickedListener(it) }
}
}
}
| apache-2.0 | a9ce88353f09639b187a1f37be55e480 | 36.61 | 92 | 0.675086 | 4.87808 | false | false | false | false |
agoda-com/Kakao | kakao/src/main/kotlin/com/agoda/kakao/common/matchers/DrawableMatcher.kt | 1 | 2779 | @file:Suppress("unused")
package com.agoda.kakao.common.matchers
import android.content.res.ColorStateList
import android.graphics.Bitmap
import android.graphics.PorterDuff
import android.graphics.drawable.Drawable
import android.os.Build
import android.view.View
import android.widget.ImageView
import androidx.annotation.ColorRes
import androidx.annotation.DrawableRes
import androidx.core.graphics.drawable.DrawableCompat
import com.agoda.kakao.common.extentions.toBitmap
import com.agoda.kakao.common.utilities.getResourceColor
import com.agoda.kakao.common.utilities.getResourceDrawable
import org.hamcrest.Description
import org.hamcrest.TypeSafeMatcher
/**
* Matches given drawable with current one
*
* @param resId Drawable resource to be matched (default is -1)
* @param drawable Drawable instance to be matched (default is null)
* @param toBitmap Lambda with custom Drawable -> Bitmap converter (default is null)
*/
class DrawableMatcher(
@DrawableRes private val resId: Int = -1,
private val drawable: Drawable? = null,
@ColorRes private val tintColorId: Int? = null,
private val toBitmap: ((drawable: Drawable) -> Bitmap)? = null
) : TypeSafeMatcher<View>(View::class.java) {
override fun describeTo(desc: Description) {
desc.appendText("with drawable id $resId or provided instance")
}
override fun matchesSafely(view: View?): Boolean {
if (view !is ImageView && drawable == null) {
return false
}
if (resId < 0 && drawable == null) {
return (view as ImageView).drawable == null
}
return view?.let { imageView ->
var expectedDrawable: Drawable? = drawable ?: getResourceDrawable(resId)?.mutate()
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP && expectedDrawable != null) {
expectedDrawable = DrawableCompat.wrap(expectedDrawable).mutate()
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
tintColorId?.let { tintColorId ->
val tintColor = getResourceColor(tintColorId)
expectedDrawable?.apply {
setTintList(ColorStateList.valueOf(tintColor))
setTintMode(PorterDuff.Mode.SRC_IN)
}
}
}
if (expectedDrawable == null) {
return false
}
val convertDrawable = (imageView as ImageView).drawable.mutate()
val bitmap = toBitmap?.invoke(convertDrawable) ?: convertDrawable.toBitmap()
val otherBitmap = toBitmap?.invoke(expectedDrawable) ?: expectedDrawable.toBitmap()
return bitmap.sameAs(otherBitmap)
} ?: false
}
}
| apache-2.0 | 52fa7f1d8b3cc2f650b664dbc0d44734 | 34.628205 | 99 | 0.662469 | 4.841463 | false | false | false | false |
zdary/intellij-community | platform/execution-impl/src/com/intellij/execution/wsl/target/WslTargetEnvironment.kt | 1 | 6472 | // Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.execution.wsl.target
import com.intellij.execution.ExecutionException
import com.intellij.execution.Platform
import com.intellij.execution.configurations.GeneralCommandLine
import com.intellij.execution.target.*
import com.intellij.execution.target.TargetEnvironmentAwareRunProfileState.TargetProgressIndicator
import com.intellij.execution.wsl.WSLCommandLineOptions
import com.intellij.execution.wsl.WSLDistribution
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.util.io.FileUtil
import com.intellij.util.io.sizeOrNull
import java.io.IOException
import java.nio.file.Path
import java.util.*
import java.util.concurrent.TimeUnit
class WslTargetEnvironment(wslRequest: WslTargetEnvironmentRequest,
private val distribution: WSLDistribution) : TargetEnvironment(wslRequest) {
private val myUploadVolumes: MutableMap<UploadRoot, UploadableVolume> = HashMap()
private val myDownloadVolumes: MutableMap<DownloadRoot, DownloadableVolume> = HashMap()
private val myTargetPortBindings: MutableMap<TargetPortBinding, Int> = HashMap()
private val myLocalPortBindings: MutableMap<LocalPortBinding, ResolvedPortBinding> = HashMap()
private val localPortBindingsSession : WslTargetLocalPortBindingsSession
override val uploadVolumes: Map<UploadRoot, UploadableVolume>
get() = Collections.unmodifiableMap(myUploadVolumes)
override val downloadVolumes: Map<DownloadRoot, DownloadableVolume>
get() = Collections.unmodifiableMap(myDownloadVolumes)
override val targetPortBindings: Map<TargetPortBinding, Int>
get() = Collections.unmodifiableMap(myTargetPortBindings)
override val localPortBindings: Map<LocalPortBinding, ResolvedPortBinding>
get() = Collections.unmodifiableMap(myLocalPortBindings)
override val targetPlatform: TargetPlatform
get() = TargetPlatform(Platform.UNIX)
init {
for (uploadRoot in wslRequest.uploadVolumes) {
val targetRoot: String? = toLinuxPath(uploadRoot.localRootPath.toAbsolutePath().toString())
if (targetRoot != null) {
myUploadVolumes[uploadRoot] = Volume(uploadRoot.localRootPath, targetRoot)
}
}
for (downloadRoot in wslRequest.downloadVolumes) {
val localRootPath = downloadRoot.localRootPath ?: FileUtil.createTempDirectory("intellij-target.", "").toPath()
val targetRoot: String? = toLinuxPath(localRootPath.toAbsolutePath().toString())
if (targetRoot != null) {
myDownloadVolumes[downloadRoot] = Volume(localRootPath, targetRoot)
}
}
for (targetPortBinding in wslRequest.targetPortBindings) {
val theOnlyPort = targetPortBinding.target
if (targetPortBinding.local != null && targetPortBinding.local != theOnlyPort) {
throw UnsupportedOperationException("Local target's TCP port forwarder is not implemented")
}
myTargetPortBindings[targetPortBinding] = theOnlyPort
}
localPortBindingsSession = WslTargetLocalPortBindingsSession(distribution, wslRequest.localPortBindings)
localPortBindingsSession.start()
for (localPortBinding in wslRequest.localPortBindings) {
val targetHostPortFuture = localPortBindingsSession.getTargetHostPortFuture(localPortBinding)
val localHostPort = HostPort("localhost", localPortBinding.local)
var targetHostPort = localHostPort
try {
targetHostPort = targetHostPortFuture.get(10, TimeUnit.SECONDS)
}
catch (e: Exception) {
LOG.info("Cannot get target host and port for $localPortBinding")
}
myLocalPortBindings[localPortBinding] = ResolvedPortBinding(localHostPort, targetHostPort)
}
}
private fun toLinuxPath(localPath: String): String? {
val linuxPath = distribution.getWslPath(localPath)
if (linuxPath != null) {
return linuxPath
}
return convertUncPathToLinux(localPath)
}
private fun convertUncPathToLinux(localPath: String): String? {
val root: String = WSLDistribution.UNC_PREFIX + distribution.msId
val winLocalPath = FileUtil.toSystemDependentName(localPath)
if (winLocalPath.startsWith(root)) {
val linuxPath = winLocalPath.substring(root.length)
if (linuxPath.isEmpty()) {
return "/"
}
if (linuxPath.startsWith("\\")) {
return FileUtil.toSystemIndependentName(linuxPath)
}
}
return null
}
@Throws(ExecutionException::class)
override fun createProcess(commandLine: TargetedCommandLine, indicator: ProgressIndicator): Process {
var line = GeneralCommandLine(commandLine.collectCommandsSynchronously())
line.environment.putAll(commandLine.environmentVariables)
val options = WSLCommandLineOptions().setRemoteWorkingDirectory(commandLine.workingDirectory)
line = distribution.patchCommandLine(line, null, options)
val process = line.createProcess()
localPortBindingsSession.stopWhenProcessTerminated(process)
return process
}
override fun shutdown() {}
private inner class Volume(override val localRoot: Path, override val targetRoot: String) : UploadableVolume, DownloadableVolume {
@Throws(IOException::class)
override fun resolveTargetPath(relativePath: String): String {
val localPath = FileUtil.toCanonicalPath(FileUtil.join(localRoot.toString(), relativePath))
return toLinuxPath(localPath)!!
}
@Throws(IOException::class)
override fun upload(relativePath: String, targetProgressIndicator: TargetProgressIndicator) {
}
@Throws(IOException::class)
override fun download(relativePath: String, progressIndicator: ProgressIndicator) {
// Synchronization may be slow -- let us wait until file size does not change
// in a reasonable amount of time
// (see https://github.com/microsoft/WSL/issues/4197)
val path = localRoot.resolve(relativePath)
var previousSize = -2L // sizeOrNull returns -1 if file does not exist
var newSize = path.sizeOrNull()
while (previousSize < newSize) {
Thread.sleep(100)
previousSize = newSize
newSize = path.sizeOrNull()
}
if (newSize == -1L) {
LOG.warn("Path $path was not found on local filesystem")
}
}
}
companion object {
val LOG = logger<WslTargetEnvironment>()
}
}
| apache-2.0 | db3cba2a8fd7608100c4c52d525d0b03 | 42.146667 | 140 | 0.750309 | 5.185897 | false | false | false | false |
AndroidX/androidx | bluetooth/bluetooth-core/src/main/java/androidx/bluetooth/core/AdvertisingSetParameters.kt | 3 | 6857 | /*
* 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.bluetooth.core
import android.bluetooth.BluetoothDevice as FwkBluetoothDevice
import android.bluetooth.le.AdvertisingSetParameters as FwkAdvertisingSetParameters
import android.os.Build
import android.os.Bundle
import androidx.annotation.RequiresApi
/**
* TODO: Add docs
* TODO: Support API 21
*
* @hide
*/
@RequiresApi(Build.VERSION_CODES.O)
class AdvertisingSetParameters internal constructor(
internal val fwkInstance: FwkAdvertisingSetParameters
) : Bundleable {
companion object {
internal const val FIELD_FWK_ADVERTISING_SET_PARAMETERS = 0
val CREATOR: Bundleable.Creator<AdvertisingSetParameters> =
object : Bundleable.Creator<AdvertisingSetParameters> {
override fun fromBundle(bundle: Bundle): AdvertisingSetParameters {
val fwkAdvertisingSetParameters =
Utils.getParcelableFromBundle(
bundle,
keyForField(FIELD_FWK_ADVERTISING_SET_PARAMETERS),
android.bluetooth.le.AdvertisingSetParameters::class.java
) ?: throw IllegalArgumentException(
"Bundle doesn't include a framework advertising set parameters"
)
return AdvertisingSetParameters(fwkAdvertisingSetParameters)
}
}
internal fun keyForField(field: Int): String {
return field.toString(Character.MAX_RADIX)
}
internal fun buildFwkAdvertisingSetParameters(
connectable: Boolean = false,
scannable: Boolean = false,
isLegacy: Boolean = false,
isAnonymous: Boolean = false,
includeTxPower: Boolean = false,
primaryPhy: Int = FwkBluetoothDevice.PHY_LE_1M,
secondaryPhy: Int = FwkBluetoothDevice.PHY_LE_1M,
txPowerLevel: Int = TX_POWER_MEDIUM
): FwkAdvertisingSetParameters {
val builder = FwkAdvertisingSetParameters.Builder()
.setConnectable(connectable)
.setScannable(scannable)
.setLegacyMode(isLegacy)
.setAnonymous(isAnonymous)
.setIncludeTxPower(includeTxPower)
.setPrimaryPhy(primaryPhy)
.setSecondaryPhy(secondaryPhy)
.setTxPowerLevel(txPowerLevel)
return builder.build()
}
/**
* Advertise on low frequency, around every 1000ms. This is the default and preferred
* advertising mode as it consumes the least power.
*/
const val INTERVAL_HIGH = FwkAdvertisingSetParameters.INTERVAL_HIGH
/**
* Advertise on medium frequency, around every 250ms. This is balanced between advertising
* frequency and power consumption.
*/
const val INTERVAL_MEDIUM = FwkAdvertisingSetParameters.INTERVAL_MEDIUM
/**
* Perform high frequency, low latency advertising, around every 100ms. This has the highest
* power consumption and should not be used for continuous background advertising.
*/
const val INTERVAL_LOW = FwkAdvertisingSetParameters.INTERVAL_LOW
/**
* Minimum value for advertising interval.
*/
const val INTERVAL_MIN = FwkAdvertisingSetParameters.INTERVAL_MIN
/**
* Maximum value for advertising interval.
*/
const val INTERVAL_MAX = FwkAdvertisingSetParameters.INTERVAL_MAX
/**
* Advertise using the lowest transmission (TX) power level. Low transmission power can be
* used to restrict the visibility range of advertising packets.
*/
const val TX_POWER_ULTRA_LOW = FwkAdvertisingSetParameters.TX_POWER_ULTRA_LOW
/**
* Advertise using low TX power level.
*/
const val TX_POWER_LOW = FwkAdvertisingSetParameters.TX_POWER_LOW
/**
* Advertise using medium TX power level.
*/
const val TX_POWER_MEDIUM = FwkAdvertisingSetParameters.TX_POWER_MEDIUM
/**
* Advertise using high TX power level. This corresponds to largest visibility range of the
* advertising packet.
*/
const val TX_POWER_HIGH = FwkAdvertisingSetParameters.TX_POWER_HIGH
/**
* Minimum value for TX power.
*/
const val TX_POWER_MIN = FwkAdvertisingSetParameters.TX_POWER_MIN
/**
* Maximum value for TX power.
*/
const val TX_POWER_MAX = FwkAdvertisingSetParameters.TX_POWER_MAX
/**
* The maximum limited advertisement duration as specified by the Bluetooth
* SIG
*/
private const val LIMITED_ADVERTISING_MAX_MILLIS = 180_000
}
val connectable: Boolean
get() = fwkInstance.isConnectable
val scannable: Boolean
get() = fwkInstance.isScannable
val isLegacy: Boolean
get() = fwkInstance.isLegacy
val isAnonymous: Boolean
get() = fwkInstance.isAnonymous
val includeTxPower: Boolean
get() = fwkInstance.includeTxPower()
val primaryPhy: Int
get() = fwkInstance.primaryPhy
val secondaryPhy: Int
get() = fwkInstance.secondaryPhy
val interval: Int
get() = fwkInstance.interval
val txPowerLevel: Int
get() = fwkInstance.txPowerLevel
constructor(
connectable: Boolean = false,
scannable: Boolean = false,
isLegacy: Boolean = false,
isAnonymous: Boolean = false,
includeTxPower: Boolean = false,
primaryPhy: Int = FwkBluetoothDevice.PHY_LE_1M,
secondaryPhy: Int = FwkBluetoothDevice.PHY_LE_1M,
txPowerLevel: Int = TX_POWER_MEDIUM
) : this(buildFwkAdvertisingSetParameters(
connectable,
scannable,
isLegacy,
isAnonymous,
includeTxPower,
primaryPhy,
secondaryPhy,
txPowerLevel
))
override fun toBundle(): Bundle {
val bundle = Bundle()
bundle.putParcelable(keyForField(FIELD_FWK_ADVERTISING_SET_PARAMETERS), fwkInstance)
return bundle
}
} | apache-2.0 | 42a192482cdcc8a0e564c67300a1f422 | 34.71875 | 100 | 0.636576 | 5.348674 | false | false | false | false |
smmribeiro/intellij-community | plugins/ide-features-trainer/src/training/actions/PreviousLessonAction.kt | 4 | 1276 | // 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 training.actions
import com.intellij.icons.AllIcons
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.AnActionEvent
import training.learn.CourseManager
import training.statistic.LessonStartingWay
import training.statistic.StatisticBase
import training.util.getLearnToolWindowForProject
import training.util.getPreviousLessonForCurrent
import training.util.lessonOpenedInProject
private class PreviousLessonAction : AnAction(AllIcons.Actions.Back) {
override fun actionPerformed(e: AnActionEvent) {
val project = e.project ?: return
if (getLearnToolWindowForProject(project) == null) return
val previousLesson = getPreviousLessonForCurrent()
StatisticBase.logLessonStopped(StatisticBase.LessonStopReason.OPEN_NEXT_OR_PREV_LESSON)
CourseManager.instance.openLesson(project, previousLesson, LessonStartingWay.PREV_BUTTON)
}
override fun update(e: AnActionEvent) {
val project = e.project
val lesson = lessonOpenedInProject(project)
e.presentation.isEnabled = lesson != null && CourseManager.instance.lessonsForModules.firstOrNull() != lesson
}
}
| apache-2.0 | ccce292872f973bb0cba0355d0a2fc9b | 44.571429 | 140 | 0.811129 | 4.623188 | false | false | false | false |
fabmax/kool | kool-core/src/jvmMain/kotlin/de/fabmax/kool/platform/vk/LoadedTextureVk.kt | 1 | 2510 | package de.fabmax.kool.platform.vk
import de.fabmax.kool.pipeline.*
import de.fabmax.kool.platform.vk.util.vkBytesPerPx
import de.fabmax.kool.util.logD
import org.lwjgl.vulkan.VK10.vkDestroySampler
import java.util.concurrent.atomic.AtomicLong
class LoadedTextureVk(val sys: VkSystem, val format: TexFormat, val textureImage: Image,
val textureImageView: ImageView, val sampler: Long,
private val isSharedRes: Boolean = false) : VkResource(), LoadedTexture {
val texId = nextTexId.getAndIncrement()
override var width = 0
override var height = 0
override var depth = 0
init {
if (!isSharedRes) {
addDependingResource(textureImage)
addDependingResource(textureImageView)
sys.ctx.engineStats.textureAllocated(texId, Texture.estimatedTexSize(
textureImage.width, textureImage.height, textureImage.arrayLayers, textureImage.mipLevels, format.vkBytesPerPx))
}
logD { "Created texture: Image: ${textureImage.vkImage}, view: ${textureImageView.vkImageView}, sampler: $sampler" }
}
fun setSize(width: Int, height: Int, depth: Int) {
this.width = width
this.height = height
this.depth = depth
}
override fun freeResources() {
if (!isSharedRes) {
vkDestroySampler(sys.device.vkDevice, sampler, null)
sys.ctx.engineStats.textureDeleted(texId)
}
logD { "Destroyed texture" }
}
override fun dispose() {
if (!isDestroyed) {
// fixme: kinda hacky... also might be depending resource of something else than sys.device
sys.ctx.runDelayed(sys.swapChain?.nImages ?: 3) {
sys.device.removeDependingResource(this)
destroy()
}
}
}
companion object {
private val nextTexId = AtomicLong(1L)
fun fromTexData(sys: VkSystem, texProps: TextureProps, data: TextureData): LoadedTextureVk {
return when(data) {
is TextureData1d -> TextureLoader.loadTexture2d(sys, texProps, data)
is TextureData2d -> TextureLoader.loadTexture2d(sys, texProps, data)
is TextureData3d -> TextureLoader.loadTexture3d(sys, texProps, data)
is TextureDataCube -> TextureLoader.loadCubeMap(sys, texProps, data)
else -> TODO("texture data not implemented: ${data::class.java.name}")
}
}
}
}
| apache-2.0 | 4d9ec9815802ef8b9015ef0a1495aa31 | 36.462687 | 132 | 0.635458 | 4.372822 | false | false | false | false |
ingokegel/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/ReplaceIsEmptyWithIfEmptyInspection.kt | 3 | 6661 | // 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.inspections
import com.intellij.codeInspection.LocalQuickFix
import com.intellij.codeInspection.ProblemDescriptor
import com.intellij.codeInspection.ProblemsHolder
import com.intellij.openapi.project.Project
import org.jetbrains.kotlin.builtins.KotlinBuiltIns
import org.jetbrains.kotlin.config.LanguageVersion
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.base.projectStructure.languageVersionSettings
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.intentions.branchedTransformations.isElseIf
import org.jetbrains.kotlin.idea.intentions.loopToCallChain.targetLoop
import org.jetbrains.kotlin.idea.util.textRangeIn
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.anyDescendantOfType
import org.jetbrains.kotlin.psi.psiUtil.blockExpressionsOrSingle
import org.jetbrains.kotlin.psi.psiUtil.getPossiblyQualifiedCallExpression
import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType
import org.jetbrains.kotlin.resolve.calls.util.getResolvedCall
import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameOrNull
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
import org.jetbrains.kotlin.idea.codeinsight.api.classic.inspections.AbstractKotlinInspection
class ReplaceIsEmptyWithIfEmptyInspection : AbstractKotlinInspection() {
private data class Replacement(
val conditionFunctionFqName: FqName,
val replacementFunctionName: String,
val negativeCondition: Boolean = false
)
companion object {
private val replacements = listOf(
Replacement(FqName("kotlin.collections.Collection.isEmpty"), "ifEmpty"),
Replacement(FqName("kotlin.collections.List.isEmpty"), "ifEmpty"),
Replacement(FqName("kotlin.collections.Set.isEmpty"), "ifEmpty"),
Replacement(FqName("kotlin.collections.Map.isEmpty"), "ifEmpty"),
Replacement(FqName("kotlin.text.isEmpty"), "ifEmpty"),
Replacement(FqName("kotlin.text.isBlank"), "ifBlank"),
Replacement(FqName("kotlin.collections.isNotEmpty"), "ifEmpty", negativeCondition = true),
Replacement(FqName("kotlin.text.isNotEmpty"), "ifEmpty", negativeCondition = true),
Replacement(FqName("kotlin.text.isNotBlank"), "ifBlank", negativeCondition = true),
).associateBy { it.conditionFunctionFqName }
private val conditionFunctionShortNames = replacements.keys.map { it.shortName().asString() }.toSet()
}
override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean) = ifExpressionVisitor(fun(ifExpression: KtIfExpression) {
if (ifExpression.languageVersionSettings.languageVersion < LanguageVersion.KOTLIN_1_3) return
if (ifExpression.isElseIf()) return
val thenExpression = ifExpression.then ?: return
val elseExpression = ifExpression.`else` ?: return
if (elseExpression is KtIfExpression) return
val condition = ifExpression.condition ?: return
val conditionCallExpression = condition.getPossiblyQualifiedCallExpression() ?: return
val conditionCalleeExpression = conditionCallExpression.calleeExpression ?: return
if (conditionCalleeExpression.text !in conditionFunctionShortNames) return
val context = ifExpression.analyze(BodyResolveMode.PARTIAL)
val resultingDescriptor = conditionCallExpression.getResolvedCall(context)?.resultingDescriptor ?: return
val receiverParameter = resultingDescriptor.dispatchReceiverParameter ?: resultingDescriptor.extensionReceiverParameter
val receiverType = receiverParameter?.type ?: return
if (KotlinBuiltIns.isArrayOrPrimitiveArray(receiverType)) return
val conditionCallFqName = resultingDescriptor.fqNameOrNull() ?: return
val replacement = replacements[conditionCallFqName] ?: return
val selfBranch = if (replacement.negativeCondition) thenExpression else elseExpression
val selfValueExpression = selfBranch.blockExpressionsOrSingle().singleOrNull() ?: return
if (condition is KtDotQualifiedExpression) {
if (selfValueExpression.text != condition.receiverExpression.text) return
} else {
if (selfValueExpression !is KtThisExpression) return
}
val loop = ifExpression.getStrictParentOfType<KtLoopExpression>()
if (loop != null) {
val defaultValueExpression = (if (replacement.negativeCondition) elseExpression else thenExpression)
if (defaultValueExpression.anyDescendantOfType<KtExpression> {
(it is KtContinueExpression || it is KtBreakExpression) && (it as KtExpressionWithLabel).targetLoop(context) == loop
}
) return
}
holder.registerProblem(
ifExpression,
conditionCalleeExpression.textRangeIn(ifExpression),
KotlinBundle.message("replace.with.0", "${replacement.replacementFunctionName} {...}"),
ReplaceFix(replacement)
)
})
private class ReplaceFix(private val replacement: Replacement) : LocalQuickFix {
override fun getName() = KotlinBundle.message("replace.with.0", "${replacement.replacementFunctionName} {...}")
override fun getFamilyName() = name
override fun applyFix(project: Project, descriptor: ProblemDescriptor) {
val ifExpression = descriptor.psiElement as? KtIfExpression ?: return
val condition = ifExpression.condition ?: return
val thenExpression = ifExpression.then ?: return
val elseExpression = ifExpression.`else` ?: return
val defaultValueExpression = (if (replacement.negativeCondition) elseExpression else thenExpression)
val psiFactory = KtPsiFactory(ifExpression)
val receiverText = (condition as? KtDotQualifiedExpression)?.receiverExpression?.text?.let { "$it." } ?: ""
val replacementFunctionName = replacement.replacementFunctionName
val newExpression = if (defaultValueExpression is KtBlockExpression) {
psiFactory.createExpression("${receiverText}$replacementFunctionName ${defaultValueExpression.text}")
} else {
psiFactory.createExpressionByPattern("${receiverText}$replacementFunctionName { $0 }", defaultValueExpression)
}
ifExpression.replace(newExpression)
}
}
}
| apache-2.0 | b5a7045901f3ba94c222b74095206cec | 54.508333 | 136 | 0.734574 | 5.698033 | false | false | false | false |
bitsydarel/DBWeather | dbweatherdata/src/main/java/com/dbeginc/dbweatherdata/proxies/local/lives/LocalIpTvPlaylistWithChannels.kt | 1 | 1109 | /*
* Copyright (C) 2017 Darel Bitsy
* 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.dbeginc.dbweatherdata.proxies.local.lives
import android.arch.persistence.room.Embedded
import android.arch.persistence.room.Relation
import android.support.annotation.RestrictTo
@RestrictTo(RestrictTo.Scope.LIBRARY)
data class LocalIpTvPlaylistWithChannels(
@Embedded var playlist: LocalIpTvPlaylist = LocalIpTvPlaylist(""),
@Relation(entity = LocalIpTvLive::class, parentColumn = "name", entityColumn = "playlist_id")
var channels: List<LocalIpTvLive> = emptyList()
) | gpl-3.0 | 4a692338ecaac2773757d3a71bbb940c | 40.111111 | 101 | 0.754734 | 4.122677 | false | false | false | false |
siosio/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/RedundantNullableReturnTypeInspection.kt | 1 | 6195 | // 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.ProblemsHolder
import com.intellij.openapi.project.Project
import com.intellij.psi.impl.source.tree.LeafPsiElement
import org.jetbrains.kotlin.config.LanguageVersionSettings
import org.jetbrains.kotlin.descriptors.ModuleDescriptor
import org.jetbrains.kotlin.idea.FrontendInternals
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.caches.resolve.findModuleDescriptor
import org.jetbrains.kotlin.idea.caches.resolve.getResolutionFacade
import org.jetbrains.kotlin.idea.core.isOverridable
import org.jetbrains.kotlin.idea.project.languageVersionSettings
import org.jetbrains.kotlin.idea.resolve.frontendService
import org.jetbrains.kotlin.idea.util.textRangeIn
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.collectDescendantsOfType
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.bindingContextUtil.getTargetFunctionDescriptor
import org.jetbrains.kotlin.resolve.calls.smartcasts.DataFlowValueFactory
import org.jetbrains.kotlin.types.KotlinType
import org.jetbrains.kotlin.types.isNullable
class RedundantNullableReturnTypeInspection : AbstractKotlinInspection() {
override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean) = object : KtVisitorVoid() {
override fun visitNamedFunction(function: KtNamedFunction) {
check(function)
}
override fun visitProperty(property: KtProperty) {
if (property.isVar) return
check(property)
}
private fun check(declaration: KtCallableDeclaration) {
val typeReference = declaration.typeReference ?: return
val typeElement = typeReference.typeElement as? KtNullableType ?: return
if (typeElement.innerType == null) return
val questionMark = typeElement.questionMarkNode as? LeafPsiElement ?: return
if (declaration.isOverridable()) return
val (body, targetDeclaration) = when (declaration) {
is KtNamedFunction -> {
val body = declaration.bodyExpression
if (body != null) body to declaration else null
}
is KtProperty -> {
val initializer = declaration.initializer
val getter = declaration.accessors.singleOrNull { it.isGetter }
val getterBody = getter?.bodyExpression
when {
initializer != null -> initializer to declaration
getterBody != null -> getterBody to getter
else -> null
}
}
else -> null
} ?: return
val actualReturnTypes = body.actualReturnTypes(targetDeclaration)
if (actualReturnTypes.isEmpty() || actualReturnTypes.any { it.isNullable() }) return
val declarationName = declaration.nameAsSafeName.asString()
val description = if (declaration is KtProperty) {
KotlinBundle.message("0.is.always.non.null.type", declarationName)
} else {
KotlinBundle.message("0.always.returns.non.null.type", declarationName)
}
holder.registerProblem(
typeReference,
questionMark.textRangeIn(typeReference),
description,
MakeNotNullableFix()
)
}
}
@OptIn(FrontendInternals::class)
private fun KtExpression.actualReturnTypes(declaration: KtDeclaration): List<KotlinType> {
val context = analyze()
val declarationDescriptor = context[BindingContext.DECLARATION_TO_DESCRIPTOR, declaration] ?: return emptyList()
val dataFlowValueFactory = getResolutionFacade().frontendService<DataFlowValueFactory>()
val moduleDescriptor = findModuleDescriptor()
val languageVersionSettings = languageVersionSettings
val returnTypes = collectDescendantsOfType<KtReturnExpression> {
it.labelQualifier == null && it.getTargetFunctionDescriptor(context) == declarationDescriptor
}.flatMap {
it.returnedExpression.types(context, dataFlowValueFactory, moduleDescriptor, languageVersionSettings)
}
return if (this is KtBlockExpression) {
returnTypes
} else {
returnTypes + types(context, dataFlowValueFactory, moduleDescriptor, languageVersionSettings)
}
}
private fun KtExpression?.types(
context: BindingContext,
dataFlowValueFactory: DataFlowValueFactory,
moduleDescriptor: ModuleDescriptor,
languageVersionSettings: LanguageVersionSettings
): List<KotlinType> {
if (this == null) return emptyList()
val type = context.getType(this) ?: return emptyList()
val dataFlowInfo = context[BindingContext.EXPRESSION_TYPE_INFO, this]?.dataFlowInfo ?: return emptyList()
val dataFlowValue = dataFlowValueFactory.createDataFlowValue(this, type, context, moduleDescriptor)
val stableTypes = dataFlowInfo.getStableTypes(dataFlowValue, languageVersionSettings)
return if (stableTypes.isNotEmpty()) stableTypes.toList() else listOf(type)
}
private class MakeNotNullableFix : LocalQuickFix {
override fun getName() = KotlinBundle.message("make.not.nullable")
override fun getFamilyName() = name
override fun applyFix(project: Project, descriptor: ProblemDescriptor) {
val typeReference = descriptor.psiElement as? KtTypeReference ?: return
val typeElement = typeReference.typeElement as? KtNullableType ?: return
val innerType = typeElement.innerType ?: return
typeElement.replace(innerType)
}
}
}
| apache-2.0 | 69556ee17871a5ab8952eb770cca8073 | 47.398438 | 158 | 0.693301 | 5.773532 | false | false | false | false |
jwren/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/branchedTransformations/intentions/FoldIfToFunctionCallIntention.kt | 3 | 6770 | // 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.kotlin.idea.intentions.branchedTransformations.intentions
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.util.TextRange
import org.jetbrains.kotlin.descriptors.ValueParameterDescriptor
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.intentions.*
import org.jetbrains.kotlin.idea.util.reformatted
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.getQualifiedExpressionForSelectorOrThis
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.calls.util.getResolvedCall
import org.jetbrains.kotlin.resolve.calls.model.ArgumentMatch
import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameOrNull
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
class FoldIfToFunctionCallIntention : SelfTargetingRangeIntention<KtIfExpression>(
KtIfExpression::class.java,
KotlinBundle.lazyMessage("lift.function.call.out.of.if"),
) {
override fun applicabilityRange(element: KtIfExpression): TextRange? =
if (canFoldToFunctionCall(element)) element.ifKeyword.textRange else null
override fun applyTo(element: KtIfExpression, editor: Editor?) {
foldToFunctionCall(element)
}
companion object {
fun branches(expression: KtExpression): List<KtExpression>? {
val branches = when (expression) {
is KtIfExpression -> expression.branches
is KtWhenExpression -> expression.entries.map { it.expression }
else -> emptyList()
}
val branchesSize = branches.size
if (branchesSize < 2) return null
return branches.filterNotNull().takeIf { it.size == branchesSize }
}
private fun canFoldToFunctionCall(element: KtExpression): Boolean {
val branches = branches(element) ?: return false
val callExpressions = branches.mapNotNull { it.callExpression() }
if (branches.size != callExpressions.size) return false
if (differentArgumentIndex(callExpressions) == null) return false
val headCall = callExpressions.first()
val tailCalls = callExpressions.drop(1)
val context = headCall.analyze(BodyResolveMode.PARTIAL)
val (headFunctionFqName, headFunctionParameters) = headCall.fqNameAndParameters(context) ?: return false
return tailCalls.all { call ->
val (fqName, parameters) = call.fqNameAndParameters(context) ?: return@all false
fqName == headFunctionFqName && parameters.zip(headFunctionParameters).all { it.first == it.second }
}
}
private fun foldToFunctionCall(element: KtExpression) {
val branches = branches(element) ?: return
val callExpressions = branches.mapNotNull { it.callExpression() }
val headCall = callExpressions.first()
val argumentIndex = differentArgumentIndex(callExpressions) ?: return
val hasNamedArgument = callExpressions.any { call -> call.valueArguments.any { it.getArgumentName() != null } }
val copiedIf = element.copy() as KtIfExpression
copiedIf.branches.forEach { branch ->
val call = branch.callExpression() ?: return
val argument = call.valueArguments[argumentIndex].getArgumentExpression() ?: return
call.getQualifiedExpressionForSelectorOrThis().replace(argument)
}
headCall.valueArguments[argumentIndex].getArgumentExpression()?.replace(copiedIf)
if (hasNamedArgument) {
headCall.valueArguments.forEach {
if (it.getArgumentName() == null) AddNameToArgumentIntention.apply(it)
}
}
element.replace(headCall.getQualifiedExpressionForSelectorOrThis()).reformatted()
}
private fun differentArgumentIndex(callExpressions: List<KtCallExpression>): Int? {
val headCall = callExpressions.first()
val headCalleeText = headCall.calleeText()
val tailCalls = callExpressions.drop(1)
if (headCall.valueArguments.any { it is KtLambdaArgument }) return null
val headArguments = headCall.valueArguments.mapNotNull { it.getArgumentExpression()?.text }
val headArgumentsSize = headArguments.size
if (headArgumentsSize != headCall.valueArguments.size) return null
val differentArgumentIndexes = tailCalls.mapNotNull { call ->
if (call.calleeText() != headCalleeText) return@mapNotNull null
val arguments = call.valueArguments.mapNotNull { it.getArgumentExpression()?.text }
if (arguments.size != headArgumentsSize) return@mapNotNull null
val differentArgumentIndexes = arguments.zip(headArguments).mapIndexedNotNull { index, (arg, headArg) ->
if (arg != headArg) index else null
}
differentArgumentIndexes.singleOrNull()
}
if (differentArgumentIndexes.size != tailCalls.size || differentArgumentIndexes.distinct().size != 1) return null
return differentArgumentIndexes.first()
}
private fun KtExpression?.callExpression(): KtCallExpression? {
return when (val expression = if (this is KtBlockExpression) statements.singleOrNull() else this) {
is KtCallExpression -> expression
is KtQualifiedExpression -> expression.callExpression
else -> null
}?.takeIf { it.calleeExpression != null }
}
private fun KtCallExpression.calleeText(): String {
val parent = this.parent
val (receiver, op) = if (parent is KtQualifiedExpression) {
parent.receiverExpression.text to parent.operationSign.value
} else {
"" to ""
}
return "$receiver$op${calleeExpression?.text.orEmpty()}"
}
private fun KtCallExpression.fqNameAndParameters(context: BindingContext): Pair<FqName, List<ValueParameterDescriptor>>? {
val resolvedCall = getResolvedCall(context) ?: return null
val fqName = resolvedCall.resultingDescriptor.fqNameOrNull() ?: return null
val parameters = valueArguments.mapNotNull { (resolvedCall.getArgumentMapping(it) as? ArgumentMatch)?.valueParameter }
return fqName to parameters
}
}
}
| apache-2.0 | 76cc6da87af9e404e48c4cc074358f00 | 50.287879 | 140 | 0.672526 | 5.540098 | false | false | false | false |
jwren/intellij-community | platform/external-system-impl/src/com/intellij/openapi/externalSystem/statistics/ProjectImportCollector.kt | 1 | 1274 | // Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.openapi.externalSystem.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 com.intellij.openapi.externalSystem.statistics.ExternalSystemActionsCollector.Companion.EXTERNAL_SYSTEM_ID
class ProjectImportCollector : CounterUsagesCollector() {
companion object {
val GROUP = EventLogGroup("project.import", 6)
@JvmField
val TASK_CLASS = EventFields.Class("task_class")
@JvmField
val IMPORT_ACTIVITY = GROUP.registerIdeActivity("import_project", startEventAdditionalFields = arrayOf(EXTERNAL_SYSTEM_ID, TASK_CLASS,
EventFields.PluginInfo))
@JvmField
val IMPORT_STAGE = GROUP.registerIdeActivity("stage", startEventAdditionalFields = arrayOf(TASK_CLASS),
parentActivity = IMPORT_ACTIVITY)
}
override fun getGroup(): EventLogGroup {
return GROUP
}
} | apache-2.0 | ebf13465b54cb1f6ac0336acbc873d89 | 44.535714 | 140 | 0.705651 | 5.352941 | false | false | false | false |
dkandalov/katas | kotlin/src/katas/kotlin/permutation/Lehmer.kt | 1 | 4941 | package katas.kotlin.permutation
import datsok.shouldEqual
import org.junit.Test
import java.util.*
import kotlin.collections.ArrayList
class LehmerTests {
@Test fun `map permutation to Lehmer code`() {
emptyList<Int>().toLehmerCode() shouldEqual LehmerCode()
listOf(0).toLehmerCode() shouldEqual LehmerCode(0)
listOf(0, 1, 2).toLehmerCode() shouldEqual LehmerCode(0, 0, 0)
listOf(0, 2, 1).toLehmerCode() shouldEqual LehmerCode(0, 1, 0)
listOf(1, 0, 2).toLehmerCode() shouldEqual LehmerCode(1, 0, 0)
listOf(1, 2, 0).toLehmerCode() shouldEqual LehmerCode(1, 1, 0)
listOf(2, 0, 1).toLehmerCode() shouldEqual LehmerCode(2, 0, 0)
listOf(2, 1, 0).toLehmerCode() shouldEqual LehmerCode(2, 1, 0)
listOf(1, 0, 4, 3, 2).toLehmerCode() shouldEqual LehmerCode(1, 0, 2, 1, 0)
}
@Test fun `map Lehmer code to a number`() {
LehmerCode().toLong() shouldEqual 0
LehmerCode(123).toLong() shouldEqual 0
LehmerCode(0, 0, 0).toLong() shouldEqual 0
LehmerCode(0, 1, 0).toLong() shouldEqual 1
LehmerCode(1, 0, 0).toLong() shouldEqual 2
LehmerCode(1, 1, 0).toLong() shouldEqual 3
LehmerCode(2, 0, 0).toLong() shouldEqual 4
LehmerCode(2, 1, 0).toLong() shouldEqual 5
LehmerCode(0, 0, 0, 0, 1).toLong() shouldEqual 0
LehmerCode(0, 0, 0, 1, 0).toLong() shouldEqual 1
LehmerCode(0, 0, 1, 0, 0).toLong() shouldEqual 2
LehmerCode(0, 1, 0, 0, 0).toLong() shouldEqual 6
LehmerCode(1, 0, 0, 0, 0).toLong() shouldEqual 24
LehmerCode(1, 0, 2, 1, 0).toLong() shouldEqual 29
}
@Test fun `map number to a Lehmer code`() {
0.toLehmerCode() shouldEqual LehmerCode(0)
0.toLehmerCode(size = 1) shouldEqual LehmerCode(0)
0.toLehmerCode(size = 2) shouldEqual LehmerCode(0, 0)
0.toLehmerCode() shouldEqual LehmerCode(0)
1.toLehmerCode() shouldEqual LehmerCode(1, 0)
2.toLehmerCode() shouldEqual LehmerCode(1, 0, 0)
3.toLehmerCode() shouldEqual LehmerCode(1, 1, 0)
4.toLehmerCode() shouldEqual LehmerCode(2, 0, 0)
5.toLehmerCode() shouldEqual LehmerCode(2, 1, 0)
0.toLehmerCode() shouldEqual LehmerCode(0)
1.toLehmerCode() shouldEqual LehmerCode(1, 0)
2.toLehmerCode() shouldEqual LehmerCode(1, 0, 0)
6.toLehmerCode() shouldEqual LehmerCode(1, 0, 0, 0)
24.toLehmerCode() shouldEqual LehmerCode(1, 0, 0, 0, 0)
29.toLehmerCode() shouldEqual LehmerCode(1, 0, 2, 1, 0)
}
@Test fun `map Lehmer code to a permutation`() {
LehmerCode().toPermutation() shouldEqual emptyList()
LehmerCode(0).toPermutation() shouldEqual listOf(0)
LehmerCode(0, 0, 0).toPermutation() shouldEqual listOf(0, 1, 2)
LehmerCode(0, 1, 0).toPermutation() shouldEqual listOf(0, 2, 1)
LehmerCode(1, 0, 0).toPermutation() shouldEqual listOf(1, 0, 2)
LehmerCode(1, 1, 0).toPermutation() shouldEqual listOf(1, 2, 0)
LehmerCode(2, 0, 0).toPermutation() shouldEqual listOf(2, 0, 1)
LehmerCode(2, 1, 0).toPermutation() shouldEqual listOf(2, 1, 0)
LehmerCode(1, 0, 2, 1, 0).toPermutation() shouldEqual listOf(1, 0, 4, 3, 2)
LehmerCode(1, 0, 2, 1, 0).toPermutation(listOf(1, 2, 3, 4, 5)) shouldEqual listOf(2, 1, 5, 4, 3)
LehmerCode(1, 0, 2, 1, 0).toPermutation(listOf('a', 'b', 'c', 'd', 'e')) shouldEqual listOf('b', 'a', 'e', 'd', 'c')
}
}
data class LehmerCode(val value: List<Int>) {
constructor(vararg value: Int): this(value.toList())
fun toLong(): Long {
var factorial = 1
var result = 0L
value.dropLast(1).asReversed().forEachIndexed { index, n ->
factorial *= index + 1
result += n * factorial
}
return result
}
fun toPermutation(): List<Int> {
val indices = value.indices.toMutableList()
return value.map {
indices.removeAt(it)
}
}
fun <T> toPermutation(list: List<T>): List<T> {
return toPermutation().map { list[it] }
}
}
fun List<Int>.toLehmerCode(): LehmerCode {
val bitSet = BitSet(size)
return LehmerCode(map {
bitSet[it] = true
it - bitSet.get(0, it).cardinality()
})
}
fun Int.toLehmerCode(size: Int = -1): LehmerCode = toLong().toLehmerCode(size)
fun Long.toLehmerCode(size: Int = -1): LehmerCode {
val result = ArrayList<Int>()
result.add(0)
var value = this
var factorial = 1
var iteration = 1
while (value != 0L) {
factorial *= iteration
iteration += 1
val divisor = value / factorial
val remainder = divisor % iteration
result.add(0, remainder.toInt())
value -= remainder * factorial
}
if (size != -1) {
IntRange(result.size, size - 1).forEach { result.add(0, 0) }
}
return LehmerCode(result)
} | unlicense | ce143ade359db111c10c8309eb144f28 | 34.3 | 124 | 0.612629 | 3.839161 | false | false | false | false |
androidx/androidx | room/room-paging-guava/src/androidTest/kotlin/androidx/room/paging/guava/LimitOffsetListenableFuturePagingSourceTest.kt | 3 | 40763 | /*
* 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.room.paging.guava
import android.database.Cursor
import androidx.arch.core.executor.testing.CountingTaskExecutorRule
import androidx.paging.LoadType
import androidx.paging.PagingConfig
import androidx.paging.PagingSource
import androidx.paging.PagingSource.LoadResult
import androidx.room.Dao
import androidx.room.Database
import androidx.room.Entity
import androidx.room.Insert
import androidx.room.PrimaryKey
import androidx.room.Room
import androidx.room.RoomDatabase
import androidx.room.RoomSQLiteQuery
import androidx.room.paging.util.ThreadSafeInvalidationObserver
import androidx.room.util.getColumnIndexOrThrow
import androidx.sqlite.db.SimpleSQLiteQuery
import androidx.test.core.app.ApplicationProvider
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.filters.SmallTest
import androidx.testutils.TestExecutor
import com.google.common.truth.Truth.assertThat
import com.google.common.truth.Truth.assertWithMessage
import com.google.common.util.concurrent.FutureCallback
import com.google.common.util.concurrent.Futures.addCallback
import com.google.common.util.concurrent.ListenableFuture
import java.util.LinkedList
import java.util.concurrent.CancellationException
import java.util.concurrent.Executor
import java.util.concurrent.TimeUnit
import java.util.concurrent.atomic.AtomicBoolean
import kotlin.test.assertFailsWith
import kotlin.test.assertFalse
import kotlin.test.assertTrue
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.guava.await
import kotlinx.coroutines.test.runTest
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
private const val tableName: String = "TestItem"
@OptIn(ExperimentalCoroutinesApi::class)
@RunWith(AndroidJUnit4::class)
@SmallTest
class LimitOffsetListenableFuturePagingSourceTest {
@JvmField
@Rule
val countingTaskExecutorRule = CountingTaskExecutorRule()
@Test
fun initialLoad_registersInvalidationObserver() =
setupAndRunWithTestExecutor { db, queryExecutor, _ ->
val pagingSource = LimitOffsetListenableFuturePagingSourceImpl(
db = db,
registerObserver = true
)
val listenableFuture = pagingSource.refresh()
assertFalse(pagingSource.privateObserver().privateRegisteredState().get())
// observer registration is queued up on queryExecutor by refresh() call
queryExecutor.executeAll()
assertTrue(pagingSource.privateObserver().privateRegisteredState().get())
// note that listenableFuture is not done yet
// The future has been transformed into a ListenableFuture<LoadResult> whose result
// is still pending
assertFalse(listenableFuture.isDone)
}
@Test
fun initialEmptyLoad_futureIsDone() = setupAndRun { db ->
val pagingSource = LimitOffsetListenableFuturePagingSourceImpl(
db = db,
registerObserver = true
)
runTest {
val listenableFuture = pagingSource.refresh()
val page = listenableFuture.await() as LoadResult.Page
assertThat(page.data).isEmpty()
assertTrue(listenableFuture.isDone)
}
}
@Test
fun initialLoad_returnsFutureImmediately() =
setupAndRunWithTestExecutor { db, queryExecutor, transactionExecutor ->
val pagingSource = LimitOffsetListenableFuturePagingSourceImpl(
db = db,
registerObserver = true
)
val listenableFuture = pagingSource.refresh()
// ensure future is returned even as its result is still pending
assertFalse(listenableFuture.isDone)
assertThat(pagingSource.itemCount.get()).isEqualTo(-1)
queryExecutor.executeAll() // run loadFuture
transactionExecutor.executeAll() // start initialLoad callable + load data
val page = listenableFuture.await() as LoadResult.Page
assertThat(page.data).containsExactlyElementsIn(
ITEMS_LIST.subList(0, 15)
)
assertTrue(listenableFuture.isDone)
}
@Test
fun append_returnsFutureImmediately() =
setupAndRunWithTestExecutor { db, queryExecutor, _ ->
val pagingSource = LimitOffsetListenableFuturePagingSourceImpl(db)
pagingSource.itemCount.set(100)
val listenableFuture = pagingSource.append(key = 20)
// ensure future is returned even as its result is still pending
assertFalse(listenableFuture.isDone)
// run transformAsync and async function
queryExecutor.executeAll()
val page = listenableFuture.await() as LoadResult.Page
assertThat(page.data).containsExactlyElementsIn(
ITEMS_LIST.subList(20, 25)
)
assertTrue(listenableFuture.isDone)
}
@Test
fun prepend_returnsFutureImmediately() =
setupAndRunWithTestExecutor { db, queryExecutor, _ ->
val pagingSource = LimitOffsetListenableFuturePagingSourceImpl(db)
pagingSource.itemCount.set(100) // bypass check for initial load
val listenableFuture = pagingSource.prepend(key = 20)
// ensure future is returned even as its result is still pending
assertFalse(listenableFuture.isDone)
// run transformAsync and async function
queryExecutor.executeAll()
val page = listenableFuture.await() as LoadResult.Page
assertThat(page.data).containsExactlyElementsIn(
ITEMS_LIST.subList(15, 20)
)
assertTrue(listenableFuture.isDone)
}
@Test
fun append_returnsInvalid() =
setupAndRunWithTestExecutor { db, queryExecutor, _ ->
val pagingSource = LimitOffsetListenableFuturePagingSourceImpl(db)
pagingSource.itemCount.set(100) // bypass check for initial load
val listenableFuture = pagingSource.append(key = 50)
pagingSource.invalidate() // imitate refreshVersionsAsync invalidating the PagingSource
assertTrue(pagingSource.invalid)
queryExecutor.executeAll() // run transformAsync and async function
val result = listenableFuture.await()
assertThat(result).isInstanceOf(LoadResult.Invalid::class.java)
assertTrue(listenableFuture.isDone)
}
@Test
fun prepend_returnsInvalid() =
setupAndRunWithTestExecutor { db, queryExecutor, _ ->
val pagingSource = LimitOffsetListenableFuturePagingSourceImpl(db)
pagingSource.itemCount.set(100) // bypass check for initial load
val listenableFuture = pagingSource.prepend(key = 50)
pagingSource.invalidate() // imitate refreshVersionsAsync invalidating the PagingSource
assertTrue(pagingSource.invalid)
queryExecutor.executeAll() // run transformAsync and async function
val result = listenableFuture.await()
assertThat(result).isInstanceOf(LoadResult.Invalid::class.java)
assertTrue(listenableFuture.isDone)
}
@Test
fun refresh_consecutively() = setupAndRun { db ->
db.dao.addAllItems(ITEMS_LIST)
val pagingSource = LimitOffsetListenableFuturePagingSourceImpl(db, true)
val pagingSource2 = LimitOffsetListenableFuturePagingSourceImpl(db, true)
val listenableFuture1 = pagingSource.refresh(key = 10)
val listenableFuture2 = pagingSource2.refresh(key = 15)
// check that first Future completes first. If the first future didn't complete first,
// this await() would not return.
val page1 = listenableFuture1.await() as LoadResult.Page
assertThat(page1.data).containsExactlyElementsIn(
ITEMS_LIST.subList(10, 25)
)
val page2 = listenableFuture2.await() as LoadResult.Page
assertThat(page2.data).containsExactlyElementsIn(
ITEMS_LIST.subList(15, 30)
)
}
@Test
fun append_consecutively() =
setupAndRunWithTestExecutor { db, queryExecutor, _ ->
val pagingSource = LimitOffsetListenableFuturePagingSourceImpl(db)
pagingSource.itemCount.set(100) // bypass check for initial load
assertThat(queryExecutor.queuedSize()).isEqualTo(0)
val listenableFuture1 = pagingSource.append(key = 10)
val listenableFuture2 = pagingSource.append(key = 15)
// both load futures are queued
assertThat(queryExecutor.queuedSize()).isEqualTo(2)
queryExecutor.executeNext() // first transformAsync
queryExecutor.executeNext() // second transformAsync
// both async functions are queued
assertThat(queryExecutor.queuedSize()).isEqualTo(2)
queryExecutor.executeNext() // first async function
queryExecutor.executeNext() // second async function
// both nonInitial loads are queued
assertThat(queryExecutor.queuedSize()).isEqualTo(2)
queryExecutor.executeNext() // first db load
val page1 = listenableFuture1.await() as LoadResult.Page
assertThat(page1.data).containsExactlyElementsIn(
ITEMS_LIST.subList(10, 15)
)
queryExecutor.executeNext() // second db load
val page2 = listenableFuture2.await() as LoadResult.Page
assertThat(page2.data).containsExactlyElementsIn(
ITEMS_LIST.subList(15, 20)
)
assertTrue(listenableFuture1.isDone)
assertTrue(listenableFuture2.isDone)
}
@Test
fun prepend_consecutively() =
setupAndRunWithTestExecutor { db, queryExecutor, _ ->
val pagingSource = LimitOffsetListenableFuturePagingSourceImpl(db)
pagingSource.itemCount.set(100) // bypass check for initial load
assertThat(queryExecutor.queuedSize()).isEqualTo(0)
val listenableFuture1 = pagingSource.prepend(key = 25)
val listenableFuture2 = pagingSource.prepend(key = 20)
// both load futures are queued
assertThat(queryExecutor.queuedSize()).isEqualTo(2)
queryExecutor.executeNext() // first transformAsync
queryExecutor.executeNext() // second transformAsync
// both async functions are queued
assertThat(queryExecutor.queuedSize()).isEqualTo(2)
queryExecutor.executeNext() // first async function
queryExecutor.executeNext() // second async function
// both nonInitial loads are queued
assertThat(queryExecutor.queuedSize()).isEqualTo(2)
queryExecutor.executeNext() // first db load
val page1 = listenableFuture1.await() as LoadResult.Page
assertThat(page1.data).containsExactlyElementsIn(
ITEMS_LIST.subList(20, 25)
)
queryExecutor.executeNext() // second db load
val page2 = listenableFuture2.await() as LoadResult.Page
assertThat(page2.data).containsExactlyElementsIn(
ITEMS_LIST.subList(15, 20)
)
assertTrue(listenableFuture1.isDone)
assertTrue(listenableFuture2.isDone)
}
@Test
fun refresh_onSuccess() = setupAndRun { db ->
db.dao.addAllItems(ITEMS_LIST)
val pagingSource = LimitOffsetListenableFuturePagingSourceImpl(db, true)
val listenableFuture = pagingSource.refresh(key = 30)
var onSuccessReceived = false
val callbackExecutor = TestExecutor()
listenableFuture.onSuccess(callbackExecutor) { result ->
val page = result as LoadResult.Page
assertThat(page.data).containsExactlyElementsIn(
ITEMS_LIST.subList(30, 45)
)
onSuccessReceived = true
}
// wait until Room db's refresh load is complete
countingTaskExecutorRule.drainTasks(500, TimeUnit.MILLISECONDS)
assertTrue(listenableFuture.isDone)
callbackExecutor.executeAll()
// make sure onSuccess callback was executed
assertTrue(onSuccessReceived)
assertTrue(listenableFuture.isDone)
}
@Test
fun append_onSuccess() = setupAndRun { db ->
db.dao.addAllItems(ITEMS_LIST)
val pagingSource = LimitOffsetListenableFuturePagingSourceImpl(db)
pagingSource.itemCount.set(100) // bypass check for initial load
val listenableFuture = pagingSource.append(key = 20)
// ensure future is returned even as its result is still pending
assertFalse(listenableFuture.isDone)
var onSuccessReceived = false
val callbackExecutor = TestExecutor()
listenableFuture.onSuccess(callbackExecutor) { result ->
val page = result as LoadResult.Page
assertThat(page.data).containsExactlyElementsIn(
ITEMS_LIST.subList(20, 25)
)
onSuccessReceived = true
}
// let room db complete load
countingTaskExecutorRule.drainTasks(500, TimeUnit.MILLISECONDS)
callbackExecutor.executeAll()
// make sure onSuccess callback was executed
assertTrue(onSuccessReceived)
assertTrue(listenableFuture.isDone)
}
@Test
fun prepend_onSuccess() = setupAndRun { db ->
db.dao.addAllItems(ITEMS_LIST)
val pagingSource = LimitOffsetListenableFuturePagingSourceImpl(db)
pagingSource.itemCount.set(100) // bypass check for initial load
val listenableFuture = pagingSource.prepend(key = 40)
// ensure future is returned even as its result is still pending
assertFalse(listenableFuture.isDone)
var onSuccessReceived = false
val callbackExecutor = TestExecutor()
listenableFuture.onSuccess(callbackExecutor) { result ->
val page = result as LoadResult.Page
assertThat(page.data).containsExactlyElementsIn(
ITEMS_LIST.subList(35, 40)
)
onSuccessReceived = true
}
// let room db complete load
countingTaskExecutorRule.drainTasks(500, TimeUnit.MILLISECONDS)
callbackExecutor.executeAll()
// make sure onSuccess callback was executed
assertTrue(onSuccessReceived)
assertTrue(listenableFuture.isDone)
}
@Test
fun refresh_cancelBeforeObserverRegistered_CancellationException() =
setupAndRunWithTestExecutor { db, queryExecutor, transactionExecutor ->
val pagingSource = LimitOffsetListenableFuturePagingSourceImpl(db, true)
val listenableFuture = pagingSource.refresh(key = 50)
assertThat(queryExecutor.queuedSize()).isEqualTo(1) // transformAsync
// cancel before observer has been registered. This queues up another task which is
// the cancelled async function
listenableFuture.cancel(true)
// even though future is cancelled, transformAsync was already queued up which means
// observer will still get registered
assertThat(queryExecutor.queuedSize()).isEqualTo(2)
// start async function but doesn't proceed further
queryExecutor.executeAll()
// ensure initial load is not queued up
assertThat(transactionExecutor.queuedSize()).isEqualTo(0)
// await() should throw after cancellation
assertFailsWith<CancellationException> {
listenableFuture.await()
}
// executors should be idle
assertThat(queryExecutor.queuedSize()).isEqualTo(0)
assertThat(transactionExecutor.queuedSize()).isEqualTo(0)
assertTrue(listenableFuture.isDone)
// even though initial refresh load is cancelled, the paging source itself
// is NOT invalidated
assertFalse(pagingSource.invalid)
}
@Test
fun refresh_cancelAfterObserverRegistered_CancellationException() =
setupAndRunWithTestExecutor { db, queryExecutor, transactionExecutor ->
val pagingSource = LimitOffsetListenableFuturePagingSourceImpl(db, true)
val listenableFuture = pagingSource.refresh(key = 50)
// start transformAsync and register observer
queryExecutor.executeNext()
// cancel after observer registration
listenableFuture.cancel(true)
// start the async function but it has been cancelled so it doesn't queue up
// initial load
queryExecutor.executeNext()
// initialLoad not queued
assertThat(transactionExecutor.queuedSize()).isEqualTo(0)
// await() should throw after cancellation
assertFailsWith<CancellationException> {
listenableFuture.await()
}
// executors should be idle
assertThat(queryExecutor.queuedSize()).isEqualTo(0)
assertThat(transactionExecutor.queuedSize()).isEqualTo(0)
assertTrue(listenableFuture.isDone)
// even though initial refresh load is cancelled, the paging source itself
// is NOT invalidated
assertFalse(pagingSource.invalid)
}
@Test
fun refresh_cancelAfterLoadIsQueued_CancellationException() =
setupAndRunWithTestExecutor { db, queryExecutor, transactionExecutor ->
val pagingSource = LimitOffsetListenableFuturePagingSourceImpl(db, true)
val listenableFuture = pagingSource.refresh(key = 50)
queryExecutor.executeAll() // run loadFuture and queue up initial load
listenableFuture.cancel(true)
// initialLoad has been queued
assertThat(transactionExecutor.queuedSize()).isEqualTo(1)
assertThat(queryExecutor.queuedSize()).isEqualTo(0)
transactionExecutor.executeAll() // room starts transaction but doesn't complete load
queryExecutor.executeAll() // InvalidationTracker from end of transaction
// await() should throw after cancellation
assertFailsWith<CancellationException> {
listenableFuture.await()
}
// executors should be idle
assertThat(queryExecutor.queuedSize()).isEqualTo(0)
assertThat(transactionExecutor.queuedSize()).isEqualTo(0)
assertTrue(listenableFuture.isDone)
// even though initial refresh load is cancelled, the paging source itself
// is NOT invalidated
assertFalse(pagingSource.invalid)
}
@Test
fun append_awaitThrowsCancellationException() =
setupAndRunWithTestExecutor { db, queryExecutor, _ ->
val pagingSource = LimitOffsetListenableFuturePagingSourceImpl(db)
pagingSource.itemCount.set(100) // bypass check for initial load
// queue up the append first
val listenableFuture = pagingSource.append(key = 20)
assertThat(queryExecutor.queuedSize()).isEqualTo(1)
listenableFuture.cancel(true)
queryExecutor.executeAll()
// await() should throw after cancellation
assertFailsWith<CancellationException> {
listenableFuture.await()
}
// although query was executed, it should not complete due to the cancellation signal.
// If query was completed, paging source would call refreshVersionsAsync manually
// and queuedSize() would be 1 instead of 0 with InvalidationTracker queued up
assertThat(queryExecutor.queuedSize()).isEqualTo(0)
}
@Test
fun prepend_awaitThrowsCancellationException() =
setupAndRunWithTestExecutor { db, queryExecutor, _ ->
val pagingSource = LimitOffsetListenableFuturePagingSourceImpl(db)
pagingSource.itemCount.set(100) // bypass check for initial load
// queue up the prepend first
val listenableFuture = pagingSource.prepend(key = 30)
assertThat(queryExecutor.queuedSize()).isEqualTo(1)
listenableFuture.cancel(true)
queryExecutor.executeAll()
// await() should throw after cancellation
assertFailsWith<CancellationException> {
listenableFuture.await()
}
// although query was executed, it should not complete due to the cancellation signal.
// If query was completed, paging source would call refreshVersionsAsync manually
// and queuedSize() would be 1 instead of 0 with InvalidationTracker queued up
assertThat(queryExecutor.queuedSize()).isEqualTo(0)
}
@Test
fun refresh_canceledFutureRunsOnFailureCallback() =
setupAndRunWithTestExecutor { db, queryExecutor, transactionExecutor ->
val pagingSource = LimitOffsetListenableFuturePagingSourceImpl(db, true)
val listenableFuture = pagingSource.refresh(key = 30)
queryExecutor.executeAll() // start transformAsync & async function
assertThat(transactionExecutor.queuedSize()).isEqualTo(1)
val callbackExecutor = TestExecutor()
var onFailureReceived = false
listenableFuture.onFailure(callbackExecutor) { throwable ->
assertThat(throwable).isInstanceOf(CancellationException::class.java)
onFailureReceived = true
}
// now cancel future and execute the refresh load. The refresh should not complete.
listenableFuture.cancel(true)
transactionExecutor.executeAll()
assertThat(transactionExecutor.queuedSize()).isEqualTo(0)
callbackExecutor.executeAll()
// make sure onFailure callback was executed
assertTrue(onFailureReceived)
assertTrue(listenableFuture.isDone)
}
@Test
fun append_canceledFutureRunsOnFailureCallback2() =
setupAndRunWithTestExecutor { db, queryExecutor, _ ->
val pagingSource = LimitOffsetListenableFuturePagingSourceImpl(db)
pagingSource.itemCount.set(100) // bypass check for initial load
val listenableFuture = pagingSource.append(key = 20)
assertThat(queryExecutor.queuedSize()).isEqualTo(1)
val callbackExecutor = TestExecutor()
var onFailureReceived = false
listenableFuture.onFailure(callbackExecutor) { throwable ->
assertThat(throwable).isInstanceOf(CancellationException::class.java)
onFailureReceived = true
}
// now cancel future and execute the append load. The append should not complete.
listenableFuture.cancel(true)
queryExecutor.executeNext() // transformAsync
queryExecutor.executeNext() // nonInitialLoad
// if load was erroneously completed, InvalidationTracker would be queued
assertThat(queryExecutor.queuedSize()).isEqualTo(0)
callbackExecutor.executeAll()
// make sure onFailure callback was executed
assertTrue(onFailureReceived)
assertTrue(listenableFuture.isDone)
}
@Test
fun prepend_canceledFutureRunsOnFailureCallback() =
setupAndRunWithTestExecutor { db, queryExecutor, _ ->
val pagingSource = LimitOffsetListenableFuturePagingSourceImpl(db)
pagingSource.itemCount.set(100) // bypass check for initial load
// queue up the prepend first
val listenableFuture = pagingSource.prepend(key = 30)
assertThat(queryExecutor.queuedSize()).isEqualTo(1)
val callbackExecutor = TestExecutor()
var onFailureReceived = false
listenableFuture.onFailure(callbackExecutor) { throwable ->
assertThat(throwable).isInstanceOf(CancellationException::class.java)
onFailureReceived = true
}
// now cancel future and execute the prepend which should not complete.
listenableFuture.cancel(true)
queryExecutor.executeNext() // transformAsync
queryExecutor.executeNext() // nonInitialLoad
// if load was erroneously completed, InvalidationTracker would be queued
assertThat(queryExecutor.queuedSize()).isEqualTo(0)
callbackExecutor.executeAll()
// make sure onFailure callback was executed
assertTrue(onFailureReceived)
assertTrue(listenableFuture.isDone)
}
@Test
fun refresh_AfterCancellation() = setupAndRun { db ->
db.dao.addAllItems(ITEMS_LIST)
val pagingSource = LimitOffsetListenableFuturePagingSourceImpl(db, true)
pagingSource.itemCount.set(100) // bypass check for initial load
val listenableFuture = pagingSource.prepend(key = 50)
listenableFuture.cancel(true)
assertFailsWith<CancellationException> {
listenableFuture.await()
}
// new gen after query from previous gen was cancelled
val pagingSource2 = LimitOffsetListenableFuturePagingSourceImpl(db, true)
val listenableFuture2 = pagingSource2.refresh()
val result = listenableFuture2.await() as LoadResult.Page
// the new generation should load as usual
assertThat(result.data).containsExactlyElementsIn(
ITEMS_LIST.subList(0, 15)
)
}
@Test
fun appendAgain_afterFutureCanceled() = setupAndRun { db ->
db.dao.addAllItems(ITEMS_LIST)
val pagingSource = LimitOffsetListenableFuturePagingSourceImpl(db)
pagingSource.itemCount.set(100) // bypass check for initial load
val listenableFuture = pagingSource.append(key = 30)
listenableFuture.cancel(true)
assertFailsWith<CancellationException> {
listenableFuture.await()
}
assertTrue(listenableFuture.isDone)
assertFalse(pagingSource.invalid)
val listenableFuture2 = pagingSource.append(key = 30)
val result = listenableFuture2.await() as LoadResult.Page
assertThat(result.data).containsExactlyElementsIn(
ITEMS_LIST.subList(30, 35)
)
assertTrue(listenableFuture2.isDone)
}
@Test
fun prependAgain_afterFutureCanceled() = setupAndRun { db ->
db.dao.addAllItems(ITEMS_LIST)
val pagingSource = LimitOffsetListenableFuturePagingSourceImpl(db)
pagingSource.itemCount.set(100) // bypass check for initial load
val listenableFuture = pagingSource.prepend(key = 30)
listenableFuture.cancel(true)
assertFailsWith<CancellationException> {
listenableFuture.await()
}
assertFalse(pagingSource.invalid)
assertTrue(listenableFuture.isDone)
val listenableFuture2 = pagingSource.prepend(key = 30)
val result = listenableFuture2.await() as LoadResult.Page
assertThat(result.data).containsExactlyElementsIn(
ITEMS_LIST.subList(25, 30)
)
assertTrue(listenableFuture2.isDone)
}
@Test
fun append_insertInvalidatesPagingSource() =
setupAndRunWithTestExecutor { db, queryExecutor, _ ->
val pagingSource = LimitOffsetListenableFuturePagingSourceImpl(
db = db,
registerObserver = true
)
pagingSource.itemCount.set(100) // bypass check for initial load
// queue up the append first
val listenableFuture = pagingSource.append(key = 20)
assertThat(queryExecutor.queuedSize()).isEqualTo(1)
queryExecutor.executeNext() // start transformAsync
queryExecutor.executeNext() // start async function
assertThat(queryExecutor.queuedSize()).isEqualTo(1) // nonInitialLoad is queued up
// run this async separately from queryExecutor
run {
db.dao.addItem(TestItem(101))
}
// tasks in queue [nonInitialLoad, InvalidationTracker(from additem)]
assertThat(queryExecutor.queuedSize()).isEqualTo(2)
// run nonInitialLoad first. The InvalidationTracker
// is still queued up. This imitates delayed notification from Room.
queryExecutor.executeNext()
val result = listenableFuture.await()
assertThat(result).isInstanceOf(LoadResult.Invalid::class.java)
assertThat(pagingSource.invalid)
}
@Test
fun prepend_insertInvalidatesPagingSource() =
setupAndRunWithTestExecutor { db, queryExecutor, _ ->
val pagingSource = LimitOffsetListenableFuturePagingSourceImpl(
db = db,
registerObserver = true
)
pagingSource.itemCount.set(100) // bypass check for initial load
// queue up the append first
val listenableFuture = pagingSource.prepend(key = 20)
assertThat(queryExecutor.queuedSize()).isEqualTo(1)
queryExecutor.executeNext() // start transformAsync
queryExecutor.executeNext() // start async function
assertThat(queryExecutor.queuedSize()).isEqualTo(1) // nonInitialLoad is queued up
// run this async separately from queryExecutor
run {
db.dao.addItem(TestItem(101))
}
// tasks in queue [nonInitialLoad, InvalidationTracker(from additem)]
assertThat(queryExecutor.queuedSize()).isEqualTo(2)
// run nonInitialLoad first. The InvalidationTracker
// is still queued up. This imitates delayed notification from Room.
queryExecutor.executeNext()
val result = listenableFuture.await()
assertThat(result).isInstanceOf(LoadResult.Invalid::class.java)
assertThat(pagingSource.invalid)
}
@Test
fun test_jumpSupport() = setupAndRun { db ->
val pagingSource = LimitOffsetListenableFuturePagingSourceImpl(db)
assertTrue(pagingSource.jumpingSupported)
}
@Test
fun refresh_secondaryConstructor() = setupAndRun { db ->
val pagingSource = object : LimitOffsetListenableFuturePagingSource<TestItem>(
db = db,
supportSQLiteQuery = SimpleSQLiteQuery(
"SELECT * FROM $tableName ORDER BY id ASC"
)
) {
override fun convertRows(cursor: Cursor): List<TestItem> {
return convertRowsHelper(cursor)
}
}
db.dao.addAllItems(ITEMS_LIST)
val listenableFuture = pagingSource.refresh()
val page = listenableFuture.await() as LoadResult.Page
assertThat(page.data).containsExactlyElementsIn(
ITEMS_LIST.subList(0, 15)
)
assertTrue(listenableFuture.isDone)
}
@Test
fun append_secondaryConstructor() = setupAndRun { db ->
val pagingSource = object : LimitOffsetListenableFuturePagingSource<TestItem>(
db = db,
supportSQLiteQuery = SimpleSQLiteQuery(
"SELECT * FROM $tableName ORDER BY id ASC"
)
) {
override fun convertRows(cursor: Cursor): List<TestItem> {
return convertRowsHelper(cursor)
}
}
db.dao.addAllItems(ITEMS_LIST)
pagingSource.itemCount.set(100)
val listenableFuture = pagingSource.append(key = 50)
val page = listenableFuture.await() as LoadResult.Page
assertThat(page.data).containsExactlyElementsIn(
ITEMS_LIST.subList(50, 55)
)
assertTrue(listenableFuture.isDone)
}
@Test
fun prepend_secondaryConstructor() = setupAndRun { db ->
val pagingSource = object : LimitOffsetListenableFuturePagingSource<TestItem>(
db = db,
supportSQLiteQuery = SimpleSQLiteQuery(
"SELECT * FROM $tableName ORDER BY id ASC"
)
) {
override fun convertRows(cursor: Cursor): List<TestItem> {
return convertRowsHelper(cursor)
}
}
db.dao.addAllItems(ITEMS_LIST)
pagingSource.itemCount.set(100)
val listenableFuture = pagingSource.prepend(key = 50)
val page = listenableFuture.await() as LoadResult.Page
assertThat(page.data).containsExactlyElementsIn(
ITEMS_LIST.subList(45, 50)
)
assertTrue(listenableFuture.isDone)
}
private fun setupAndRun(
test: suspend (LimitOffsetTestDb) -> Unit
) {
val db = Room.inMemoryDatabaseBuilder(
ApplicationProvider.getApplicationContext(),
LimitOffsetTestDb::class.java
).build()
runTest {
test(db)
}
tearDown(db)
}
private fun setupAndRunWithTestExecutor(
test: suspend (LimitOffsetTestDb, TestExecutor, TestExecutor) -> Unit
) {
val queryExecutor = TestExecutor()
val transactionExecutor = TestExecutor()
val db = Room.inMemoryDatabaseBuilder(
ApplicationProvider.getApplicationContext(),
LimitOffsetTestDb::class.java
)
.setTransactionExecutor(transactionExecutor)
.setQueryExecutor(queryExecutor)
.build()
runTest {
db.dao.addAllItems(ITEMS_LIST)
queryExecutor.executeAll() // InvalidationTracker from the addAllItems
test(db, queryExecutor, transactionExecutor)
}
tearDown(db)
}
private fun tearDown(db: LimitOffsetTestDb) {
if (db.isOpen) db.close()
countingTaskExecutorRule.drainTasks(500, TimeUnit.MILLISECONDS)
assertThat(countingTaskExecutorRule.isIdle).isTrue()
}
}
private class LimitOffsetListenableFuturePagingSourceImpl(
db: RoomDatabase,
registerObserver: Boolean = false,
queryString: String = "SELECT * FROM $tableName ORDER BY id ASC",
) : LimitOffsetListenableFuturePagingSource<TestItem>(
sourceQuery = RoomSQLiteQuery.acquire(
queryString,
0
),
db = db,
tables = arrayOf(tableName)
) {
init {
// bypass register check and avoid registering observer
if (!registerObserver) {
privateObserver().privateRegisteredState().set(true)
}
}
override fun convertRows(cursor: Cursor): List<TestItem> {
return convertRowsHelper(cursor)
}
}
private fun convertRowsHelper(cursor: Cursor): List<TestItem> {
val cursorIndexOfId = getColumnIndexOrThrow(cursor, "id")
val data = mutableListOf<TestItem>()
while (cursor.moveToNext()) {
val tmpId = cursor.getInt(cursorIndexOfId)
data.add(TestItem(tmpId))
}
return data
}
@Suppress("UNCHECKED_CAST")
private fun TestExecutor.executeNext() {
val tasks = javaClass.getDeclaredField("mTasks").let {
it.isAccessible = true
it.get(this)
} as LinkedList<Runnable>
if (!tasks.isEmpty()) {
val task = tasks.poll()
task?.run()
}
}
@Suppress("UNCHECKED_CAST")
private fun TestExecutor.queuedSize(): Int {
val tasks = javaClass.getDeclaredField("mTasks").let {
it.isAccessible = true
it.get(this)
} as LinkedList<Runnable>
return tasks.size
}
@Suppress("UNCHECKED_CAST")
private fun ThreadSafeInvalidationObserver.privateRegisteredState(): AtomicBoolean {
return ThreadSafeInvalidationObserver::class.java
.getDeclaredField("registered")
.let {
it.isAccessible = true
it.get(this)
} as AtomicBoolean
}
@Suppress("UNCHECKED_CAST")
private fun LimitOffsetListenableFuturePagingSource<TestItem>.privateObserver():
ThreadSafeInvalidationObserver {
return LimitOffsetListenableFuturePagingSource::class.java
.getDeclaredField("observer")
.let {
it.isAccessible = true
it.get(this)
} as ThreadSafeInvalidationObserver
}
private fun LimitOffsetListenableFuturePagingSource<TestItem>.refresh(
key: Int? = null,
): ListenableFuture<LoadResult<Int, TestItem>> {
return loadFuture(
createLoadParam(
loadType = LoadType.REFRESH,
key = key,
)
)
}
private fun LimitOffsetListenableFuturePagingSource<TestItem>.append(
key: Int? = -1,
): ListenableFuture<LoadResult<Int, TestItem>> {
return loadFuture(
createLoadParam(
loadType = LoadType.APPEND,
key = key,
)
)
}
private fun LimitOffsetListenableFuturePagingSource<TestItem>.prepend(
key: Int? = -1,
): ListenableFuture<LoadResult<Int, TestItem>> {
return loadFuture(
createLoadParam(
loadType = LoadType.PREPEND,
key = key,
)
)
}
private val CONFIG = PagingConfig(
pageSize = 5,
enablePlaceholders = true,
initialLoadSize = 15
)
private val ITEMS_LIST = createItemsForDb(0, 100)
private fun createItemsForDb(startId: Int, count: Int): List<TestItem> {
return List(count) {
TestItem(
id = it + startId,
)
}
}
private fun createLoadParam(
loadType: LoadType,
key: Int? = null,
initialLoadSize: Int = CONFIG.initialLoadSize,
pageSize: Int = CONFIG.pageSize,
placeholdersEnabled: Boolean = CONFIG.enablePlaceholders
): PagingSource.LoadParams<Int> {
return when (loadType) {
LoadType.REFRESH -> {
PagingSource.LoadParams.Refresh(
key = key,
loadSize = initialLoadSize,
placeholdersEnabled = placeholdersEnabled
)
}
LoadType.APPEND -> {
PagingSource.LoadParams.Append(
key = key ?: -1,
loadSize = pageSize,
placeholdersEnabled = placeholdersEnabled
)
}
LoadType.PREPEND -> {
PagingSource.LoadParams.Prepend(
key = key ?: -1,
loadSize = pageSize,
placeholdersEnabled = placeholdersEnabled
)
}
}
}
private fun ListenableFuture<LoadResult<Int, TestItem>>.onSuccess(
executor: Executor,
onSuccessCallback: (LoadResult<Int, TestItem>?) -> Unit,
) {
addCallback(
this,
object : FutureCallback<LoadResult<Int, TestItem>> {
override fun onSuccess(result: LoadResult<Int, TestItem>?) {
onSuccessCallback(result)
}
override fun onFailure(t: Throwable) {
assertWithMessage("Expected onSuccess callback instead of onFailure, " +
"received ${t.localizedMessage}").fail()
}
},
executor
)
}
private fun ListenableFuture<LoadResult<Int, TestItem>>.onFailure(
executor: Executor,
onFailureCallback: (Throwable) -> Unit,
) {
addCallback(
this,
object : FutureCallback<LoadResult<Int, TestItem>> {
override fun onSuccess(result: LoadResult<Int, TestItem>?) {
assertWithMessage("Expected onFailure callback instead of onSuccess, " +
"received result $result").fail()
}
override fun onFailure(t: Throwable) {
onFailureCallback(t)
}
},
executor
)
}
@Database(entities = [TestItem::class], version = 1, exportSchema = false)
abstract class LimitOffsetTestDb : RoomDatabase() {
abstract val dao: TestItemDao
}
@Entity(tableName = "TestItem")
data class TestItem(
@PrimaryKey val id: Int,
val value: String = "item $id"
)
@Dao
interface TestItemDao {
@Insert
fun addAllItems(testItems: List<TestItem>)
@Insert
fun addItem(testItem: TestItem)
}
| apache-2.0 | e2b8116083a2394fc4804f0155f210db | 35.723423 | 99 | 0.652381 | 5.796786 | false | true | false | false |
OnyxDevTools/onyx-database-parent | onyx-database/src/main/kotlin/com/onyx/interactors/relationship/data/RelationshipReference.kt | 1 | 1364 | package com.onyx.interactors.relationship.data
import com.onyx.buffer.BufferStream
import com.onyx.buffer.BufferStreamable
/**
* Created by timothy.osborn on 3/19/15.
*
* Reference of a relationship
*/
class RelationshipReference @JvmOverloads constructor(var identifier: Any? = "", var partitionId: Long = 0L) : BufferStreamable, Comparable<RelationshipReference> {
override fun read(buffer: BufferStream) {
partitionId = buffer.long
identifier = buffer.value
}
override fun write(buffer: BufferStream) {
buffer.putLong(partitionId)
buffer.putObject(identifier)
}
override fun compareTo(other: RelationshipReference): Int = when {
this.partitionId < other.partitionId -> -1
this.partitionId > other.partitionId -> 1
other.identifier!!.javaClass == this.identifier!!.javaClass && this.identifier is Comparable<*> -> @Suppress("UNCHECKED_CAST") (this.identifier as Comparable<Any>).compareTo(other.identifier!! as Comparable<Any>)
else -> 0
}
override fun hashCode(): Int = when (identifier) {
null -> partitionId.hashCode()
else -> identifier!!.hashCode() + partitionId.hashCode()
}
override fun equals(other:Any?):Boolean = other != null && (other as RelationshipReference).partitionId == partitionId && other.identifier == identifier
} | agpl-3.0 | 2a930b0231ab658a709208ed8cca2be2 | 36.916667 | 220 | 0.696481 | 4.65529 | false | false | false | false |
GunoH/intellij-community | platform/platform-impl/src/com/intellij/ui/docking/impl/DockManagerImpl.kt | 1 | 28090 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
@file:Suppress("ReplacePutWithAssignment", "ReplaceGetOrSet")
package com.intellij.ui.docking.impl
import com.intellij.ide.IdeEventQueue
import com.intellij.ide.ui.UISettings
import com.intellij.ide.ui.UISettingsListener
import com.intellij.openapi.Disposable
import com.intellij.openapi.actionSystem.Presentation
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.components.PersistentStateComponent
import com.intellij.openapi.components.State
import com.intellij.openapi.components.Storage
import com.intellij.openapi.components.StoragePathMacros
import com.intellij.openapi.fileEditor.FileEditor
import com.intellij.openapi.fileEditor.FileEditorComposite
import com.intellij.openapi.fileEditor.ex.FileEditorManagerEx
import com.intellij.openapi.fileEditor.impl.*
import com.intellij.openapi.fileEditor.impl.EditorTabbedContainer.DockableEditor
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.FrameWrapper
import com.intellij.openapi.util.*
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.openapi.wm.*
import com.intellij.openapi.wm.ex.ToolWindowManagerListener
import com.intellij.openapi.wm.ex.ToolWindowManagerListener.ToolWindowManagerEventType
import com.intellij.openapi.wm.ex.WindowManagerEx
import com.intellij.toolWindow.ToolWindowButtonManager
import com.intellij.toolWindow.ToolWindowPane
import com.intellij.toolWindow.ToolWindowPaneNewButtonManager
import com.intellij.toolWindow.ToolWindowPaneOldButtonManager
import com.intellij.ui.ComponentUtil
import com.intellij.ui.ExperimentalUI
import com.intellij.ui.ScreenUtil
import com.intellij.ui.awt.DevicePoint
import com.intellij.ui.awt.RelativePoint
import com.intellij.ui.components.panels.NonOpaquePanel
import com.intellij.ui.components.panels.VerticalBox
import com.intellij.ui.docking.*
import com.intellij.ui.docking.DockContainer.ContentResponse
import com.intellij.util.IconUtil
import com.intellij.util.ObjectUtils
import com.intellij.util.containers.sequenceOfNotNull
import com.intellij.util.ui.EdtInvocationManager
import com.intellij.util.ui.ImageUtil
import com.intellij.util.ui.StartupUiUtil
import com.intellij.util.ui.update.Activatable
import com.intellij.util.ui.update.UiNotifyConnector
import org.jdom.Element
import org.jetbrains.annotations.Contract
import java.awt.*
import java.awt.event.KeyEvent
import java.awt.event.MouseEvent
import java.awt.event.WindowAdapter
import java.awt.event.WindowEvent
import java.util.*
import java.util.function.Predicate
import javax.swing.*
@State(name = "DockManager", storages = [Storage(StoragePathMacros.PRODUCT_WORKSPACE_FILE)])
class DockManagerImpl(private val project: Project) : DockManager(), PersistentStateComponent<Element?> {
private val factories = HashMap<String, DockContainerFactory>()
private val containers = HashSet<DockContainer>()
private val containerToWindow = HashMap<DockContainer, DockWindow>()
private var currentDragSession: MyDragSession? = null
private val busyObject: BusyObject.Impl = object : BusyObject.Impl() {
override fun isReady(): Boolean = currentDragSession == null
}
private var windowIdCounter = 1
private var loadedState: Element? = null
companion object {
val SHOW_NORTH_PANEL = Key.create<Boolean>("SHOW_NORTH_PANEL")
val WINDOW_DIMENSION_KEY = Key.create<String>("WINDOW_DIMENSION_KEY")
@JvmField
val REOPEN_WINDOW = Key.create<Boolean>("REOPEN_WINDOW")
@JvmField
val ALLOW_DOCK_TOOL_WINDOWS = Key.create<Boolean>("ALLOW_DOCK_TOOL_WINDOWS")
@JvmStatic
fun isSingletonEditorInWindow(editors: List<FileEditor>): Boolean {
return editors.any { FileEditorManagerImpl.SINGLETON_EDITOR_IN_WINDOW.get(it, false) || EditorWindow.HIDE_TABS.get(it, false) }
}
private fun getWindowDimensionKey(content: DockableContent<*>): String? {
return if (content is DockableEditor) getWindowDimensionKey(content.file) else null
}
private fun getWindowDimensionKey(file: VirtualFile): String? = WINDOW_DIMENSION_KEY.get(file)
@JvmStatic
fun isNorthPanelVisible(uiSettings: UISettings): Boolean {
return uiSettings.showNavigationBar && !uiSettings.presentationMode
}
@JvmStatic
fun isNorthPanelAvailable(editors: List<FileEditor>): Boolean {
val defaultNorthPanelVisible = isNorthPanelVisible(UISettings.getInstance())
for (editor in editors) {
if (SHOW_NORTH_PANEL.isIn(editor)) {
return SHOW_NORTH_PANEL.get(editor, defaultNorthPanelVisible)
}
}
return defaultNorthPanelVisible
}
}
override fun register(container: DockContainer, parentDisposable: Disposable) {
containers.add(container)
Disposer.register(parentDisposable) { containers.remove(container) }
}
override fun register(id: String, factory: DockContainerFactory, parentDisposable: Disposable) {
factories.put(id, factory)
if (parentDisposable !== project) {
Disposer.register(parentDisposable) { factories.remove(id) }
}
readStateFor(id)
}
fun readState() {
for (id in factories.keys) {
readStateFor(id)
}
}
override fun getContainers(): Set<DockContainer> = allContainers.toSet()
override fun getIdeFrame(container: DockContainer): IdeFrame? {
return ComponentUtil.findUltimateParent(container.containerComponent) as? IdeFrame
}
override fun getDimensionKeyForFocus(key: String): String {
val owner = IdeFocusManager.getInstance(project).focusOwner ?: return key
val window = containerToWindow.get(getContainerFor(owner) { _ -> true })
return if (window == null) key else "$key#${window.id}"
}
@Suppress("OVERRIDE_DEPRECATION", "removal")
override fun getContainerFor(c: Component): DockContainer? {
return getContainerFor(c) { true }
}
@Contract("null, _ -> null")
override fun getContainerFor(c: Component?, filter: Predicate<in DockContainer>): DockContainer? {
if (c == null) {
return null
}
for (eachContainer in allContainers) {
if (SwingUtilities.isDescendingFrom(c, eachContainer.containerComponent) && filter.test(eachContainer)) {
return eachContainer
}
}
val parent = ComponentUtil.findUltimateParent(c)
for (eachContainer in allContainers) {
if (parent === ComponentUtil.findUltimateParent(eachContainer.containerComponent) && filter.test(eachContainer)) {
return eachContainer
}
}
return null
}
override fun createDragSession(mouseEvent: MouseEvent, content: DockableContent<*>): DragSession {
stopCurrentDragSession()
for (each in allContainers) {
if (each.isEmpty && each.isDisposeWhenEmpty) {
val window = containerToWindow.get(each)
window?.setTransparent(true)
}
}
currentDragSession = MyDragSession(mouseEvent, content)
return currentDragSession!!
}
fun stopCurrentDragSession() {
if (currentDragSession != null) {
currentDragSession!!.cancelSession()
currentDragSession = null
busyObject.onReady()
for (each in allContainers) {
if (!each.isEmpty) {
val window = containerToWindow.get(each)
window?.setTransparent(false)
}
}
}
}
private val ready: ActionCallback
get() = busyObject.getReady(this)
private inner class MyDragSession(mouseEvent: MouseEvent, content: DockableContent<*>) : DragSession {
private val window: JDialog
private var dragImage: Image?
private val defaultDragImage: Image
private val content: DockableContent<*>
val startDragContainer: DockContainer?
private var currentOverContainer: DockContainer? = null
private val imageContainer: JLabel
init {
window = JDialog(ComponentUtil.getWindow(mouseEvent.component))
window.isUndecorated = true
this.content = content
@Suppress("DEPRECATION")
startDragContainer = getContainerFor(mouseEvent.component)
val buffer = ImageUtil.toBufferedImage(content.previewImage)
val requiredSize = 220.0
val width = buffer.getWidth(null).toDouble()
val height = buffer.getHeight(null).toDouble()
val ratio = if (width > height) requiredSize / width else requiredSize / height
defaultDragImage = buffer.getScaledInstance((width * ratio).toInt(), (height * ratio).toInt(), Image.SCALE_SMOOTH)
dragImage = defaultDragImage
imageContainer = JLabel(object : Icon {
override fun getIconWidth(): Int = defaultDragImage.getWidth(window)
override fun getIconHeight(): Int = defaultDragImage.getHeight(window)
@Synchronized
override fun paintIcon(c: Component, g: Graphics, x: Int, y: Int) {
StartupUiUtil.drawImage(g, defaultDragImage, x, y, window)
}
})
window.contentPane = imageContainer
setLocationFrom(mouseEvent)
window.isVisible = true
val windowManager = WindowManagerEx.getInstanceEx()
windowManager.setAlphaModeEnabled(window, true)
windowManager.setAlphaModeRatio(window, 0.1f)
}
private fun setLocationFrom(me: MouseEvent) {
val devicePoint = DevicePoint(me)
val showPoint = devicePoint.locationOnScreen
val size = imageContainer.size
showPoint.x -= size.width / 2
showPoint.y -= size.height / 2
window.bounds = Rectangle(showPoint, size)
}
override fun getResponse(e: MouseEvent): ContentResponse {
val point = DevicePoint(e)
for (each in allContainers) {
val rec = each.acceptArea
if (rec.contains(point)) {
val component = each.containerComponent
if (component.graphicsConfiguration != null) {
val response = each.getContentResponse(content, point.toRelativePoint(component))
if (response.canAccept()) {
return response
}
}
}
}
return ContentResponse.DENY
}
override fun process(e: MouseEvent) {
val devicePoint = DevicePoint(e)
var img: Image? = null
if (e.id == MouseEvent.MOUSE_DRAGGED) {
val over = findContainerFor(devicePoint, content)
if (currentOverContainer != null && currentOverContainer !== over) {
currentOverContainer!!.resetDropOver(content)
currentOverContainer = null
}
if (currentOverContainer == null && over != null) {
currentOverContainer = over
val point = devicePoint.toRelativePoint(over.containerComponent)
img = currentOverContainer!!.startDropOver(content, point)
}
if (currentOverContainer != null) {
val point = devicePoint.toRelativePoint(currentOverContainer!!.containerComponent)
img = currentOverContainer!!.processDropOver(content, point)
}
if (img == null) {
img = defaultDragImage
}
if (img !== dragImage) {
dragImage = img
imageContainer.icon = IconUtil.createImageIcon(dragImage!!)
window.pack()
}
setLocationFrom(e)
}
else if (e.id == MouseEvent.MOUSE_RELEASED) {
if (currentOverContainer == null) {
// This relative point might be relative to a component that's on a different screen, with a different DPI scaling factor than
// the target location. Ideally, we should pass the DevicePoint to createNewDockContainerFor, but that will change the API. We'll
// fix it up inside createNewDockContainerFor
val point = RelativePoint(e)
createNewDockContainerFor(content, point)
e.consume() //Marker for DragHelper: drag into separate window is not tabs reordering
}
else {
val point = devicePoint.toRelativePoint(currentOverContainer!!.containerComponent)
currentOverContainer!!.add(content, point)
ObjectUtils.consumeIfCast(currentOverContainer,
DockableEditorTabbedContainer::class.java) { container: DockableEditorTabbedContainer ->
//Marker for DragHelper, not 'refined' drop in tab-set shouldn't affect ABC-order setting
if (container.currentDropSide == SwingConstants.CENTER) e.consume()
}
}
stopCurrentDragSession()
}
}
override fun cancel() {
stopCurrentDragSession()
}
fun cancelSession() {
window.dispose()
if (currentOverContainer != null) {
currentOverContainer!!.resetDropOver(content)
currentOverContainer = null
}
}
}
private fun findContainerFor(devicePoint: DevicePoint, content: DockableContent<*>): DockContainer? {
val containers = containers.toMutableList()
FileEditorManagerEx.getInstanceEx(project)?.dockContainer?.let(containers::add)
val startDragContainer = currentDragSession?.startDragContainer
if (startDragContainer != null) {
containers.remove(startDragContainer)
containers.add(0, startDragContainer)
}
for (each in containers) {
val rec = each.acceptArea
if (rec.contains(devicePoint) && each.getContentResponse(content, devicePoint.toRelativePoint(each.containerComponent)).canAccept()) {
return each
}
}
for (each in containers) {
val rec = each.acceptAreaFallback
if (rec.contains(devicePoint) && each.getContentResponse(content, devicePoint.toRelativePoint(each.containerComponent)).canAccept()) {
return each
}
}
return null
}
private fun getFactory(type: String): DockContainerFactory? {
assert(factories.containsKey(type)) { "No factory for content type=$type" }
return factories.get(type)
}
fun createNewDockContainerFor(content: DockableContent<*>, point: RelativePoint) {
val container = getFactory(content.dockContainerType)!!.createContainer(content)
val canReopenWindow = content.presentation.getClientProperty(REOPEN_WINDOW)
val reopenWindow = canReopenWindow == null || canReopenWindow
val window = createWindowFor(getWindowDimensionKey(content), null, container, reopenWindow)
val isNorthPanelAvailable = if (content is DockableEditor) content.isNorthPanelAvailable else isNorthPanelVisible(UISettings.getInstance())
if (isNorthPanelAvailable) {
window.setupNorthPanel()
}
val canDockToolWindows = content.presentation.getClientProperty(ALLOW_DOCK_TOOL_WINDOWS)
if (canDockToolWindows == null || canDockToolWindows) {
window.setupToolWindowPane()
}
val size = content.preferredSize
// The given relative point might be relative to a component on a different screen, using different DPI screen coordinates. Convert to
// device coordinates first. Ideally, we would be given a DevicePoint
val showPoint = DevicePoint(point).locationOnScreen
showPoint.x -= size.width / 2
showPoint.y -= size.height / 2
val target = Rectangle(showPoint, size)
ScreenUtil.moveRectangleToFitTheScreen(target)
ScreenUtil.cropRectangleToFitTheScreen(target)
window.setLocation(target.location)
window.dockContentUiContainer.preferredSize = target.size
window.show(false)
window.getFrame().pack()
container.add(content, RelativePoint(target.location))
SwingUtilities.invokeLater { window.uiContainer.preferredSize = null }
}
fun createNewDockContainerFor(file: VirtualFile,
fileEditorManager: FileEditorManagerImpl): FileEditorComposite {
val container = getFactory(DockableEditorContainerFactory.TYPE)!!.createContainer(null)
// Order is important here. Create the dock window, then create the editor window. That way, any listeners can check to see if the
// parent window is floating.
val window = createWindowFor(getWindowDimensionKey(file), null, container, REOPEN_WINDOW.get(file, true))
if (!ApplicationManager.getApplication().isHeadlessEnvironment && !ApplicationManager.getApplication().isUnitTestMode) {
window.show(true)
}
val editorWindow = (container as DockableEditorTabbedContainer).splitters.getOrCreateCurrentWindow(file)
val result = fileEditorManager.openFileImpl2(editorWindow, file, FileEditorOpenOptions(requestFocus = true))
if (!isSingletonEditorInWindow(result.allEditors)) {
window.setupToolWindowPane()
}
val isNorthPanelAvailable = isNorthPanelAvailable(result.allEditors)
if (isNorthPanelAvailable) {
window.setupNorthPanel()
}
container.add(
EditorTabbedContainer.createDockableEditor(project, null, file, Presentation(file.name), editorWindow, isNorthPanelAvailable),
null
)
SwingUtilities.invokeLater { window.uiContainer.preferredSize = null }
return result
}
private fun createWindowFor(dimensionKey: String?,
id: String?,
container: DockContainer,
canReopenWindow: Boolean): DockWindow {
val window = DockWindow(dimensionKey = dimensionKey,
id = id ?: (windowIdCounter++).toString(),
project = project,
container = container,
isDialog = container is DockContainer.Dialog,
supportReopen = canReopenWindow)
containerToWindow.put(container, window)
return window
}
private fun getOrCreateWindowFor(id: String, container: DockContainer): DockWindow {
val existingWindow = containerToWindow.values.firstOrNull { it.id == id }
if (existingWindow != null) {
val oldContainer = existingWindow.replaceContainer(container)
containerToWindow.remove(oldContainer)
containerToWindow.put(container, existingWindow)
if (oldContainer is Disposable) {
Disposer.dispose(oldContainer)
}
return existingWindow
}
return createWindowFor(dimensionKey = null, id = id, container = container, canReopenWindow = true)
}
private inner class DockWindow(dimensionKey: String?,
val id: String,
project: Project,
private var container: DockContainer,
isDialog: Boolean,
val supportReopen: Boolean) : FrameWrapper(project, dimensionKey ?: "dock-window-$id", isDialog) {
var northPanelAvailable = false
private val northPanel = VerticalBox()
private val northExtensions = LinkedHashMap<String, JComponent>()
val uiContainer: NonOpaquePanel
private val centerPanel = JPanel(BorderLayout(0, 2))
val dockContentUiContainer: JPanel
var toolWindowPane: ToolWindowPane? = null
init {
if (!ApplicationManager.getApplication().isHeadlessEnvironment && container !is DockContainer.Dialog) {
val statusBar = WindowManager.getInstance().getStatusBar(project)
if (statusBar != null) {
val frame = getFrame()
if (frame is IdeFrame) {
this.statusBar = statusBar.createChild(frame)
}
}
}
uiContainer = NonOpaquePanel(BorderLayout())
centerPanel.isOpaque = false
dockContentUiContainer = JPanel(BorderLayout())
dockContentUiContainer.isOpaque = false
dockContentUiContainer.add(container.containerComponent, BorderLayout.CENTER)
centerPanel.add(dockContentUiContainer, BorderLayout.CENTER)
uiContainer.add(centerPanel, BorderLayout.CENTER)
statusBar?.let {
uiContainer.add(it.component, BorderLayout.SOUTH)
}
component = uiContainer
IdeEventQueue.getInstance().addPostprocessor({ e ->
if (e is KeyEvent) {
if (currentDragSession != null) {
stopCurrentDragSession()
}
}
false
}, this)
container.addListener(object : DockContainer.Listener {
override fun contentRemoved(key: Any) {
ready.doWhenDone(Runnable(::closeIfEmpty))
}
}, this)
}
fun setupToolWindowPane() {
if (ApplicationManager.getApplication().isUnitTestMode || getFrame() !is JFrame || toolWindowPane != null) {
return
}
val paneId = dimensionKey!!
val buttonManager: ToolWindowButtonManager
if (ExperimentalUI.isNewUI()) {
buttonManager = ToolWindowPaneNewButtonManager(paneId, false)
buttonManager.add(dockContentUiContainer)
buttonManager.initMoreButton()
}
else {
buttonManager = ToolWindowPaneOldButtonManager(paneId)
}
val containerComponent = container.containerComponent
toolWindowPane = ToolWindowPane((getFrame() as JFrame), this, paneId, buttonManager)
toolWindowPane!!.setDocumentComponent(containerComponent)
dockContentUiContainer.remove(containerComponent)
dockContentUiContainer.add(toolWindowPane!!, BorderLayout.CENTER)
// Close the container if it's empty, and we've just removed the last tool window
project.messageBus.connect(this).subscribe(ToolWindowManagerListener.TOPIC, object : ToolWindowManagerListener {
override fun stateChanged(toolWindowManager: ToolWindowManager, eventType: ToolWindowManagerEventType) {
if (eventType == ToolWindowManagerEventType.ActivateToolWindow ||
eventType == ToolWindowManagerEventType.MovedOrResized ||
eventType == ToolWindowManagerEventType.SetContentUiType) {
return
}
ready.doWhenDone(Runnable(::closeIfEmpty))
}
})
}
fun replaceContainer(container: DockContainer): DockContainer {
val newContainerComponent = container.containerComponent
if (toolWindowPane != null) {
toolWindowPane!!.setDocumentComponent(newContainerComponent)
}
else {
dockContentUiContainer.remove(this.container.containerComponent)
dockContentUiContainer.add(newContainerComponent)
}
val oldContainer = this.container
this.container = container
if (container is Activatable && getFrame().isVisible) {
(container as Activatable).showNotify()
}
return oldContainer
}
private fun closeIfEmpty() {
if (container.isEmpty && (toolWindowPane == null || !toolWindowPane!!.buttonManager.hasButtons())) {
close()
containers.remove(container)
}
}
fun setupNorthPanel() {
if (northPanelAvailable) {
return
}
centerPanel.add(northPanel, BorderLayout.NORTH)
northPanelAvailable = true
project.messageBus.connect(this).subscribe(UISettingsListener.TOPIC, UISettingsListener { uiSettings ->
val visible = isNorthPanelVisible(uiSettings)
if (northPanel.isVisible != visible) {
updateNorthPanel(visible)
}
})
updateNorthPanel(isNorthPanelVisible(UISettings.getInstance()))
}
override fun getNorthExtension(key: String?): JComponent? = northExtensions.get(key)
private fun updateNorthPanel(visible: Boolean) {
if (ApplicationManager.getApplication().isUnitTestMode || !northPanelAvailable) {
return
}
northPanel.removeAll()
northExtensions.clear()
northPanel.isVisible = visible && container !is DockContainer.Dialog
for (extension in IdeRootPaneNorthExtension.EP_NAME.extensionList) {
val component = extension.createComponent(project, true) ?: continue
northExtensions.put(extension.key, component)
northPanel.add(component)
}
northPanel.revalidate()
northPanel.repaint()
}
fun setTransparent(transparent: Boolean) {
val windowManager = WindowManagerEx.getInstanceEx()
if (transparent) {
windowManager.setAlphaModeEnabled(getFrame(), true)
windowManager.setAlphaModeRatio(getFrame(), 0.5f)
}
else {
windowManager.setAlphaModeEnabled(getFrame(), true)
windowManager.setAlphaModeRatio(getFrame(), 0f)
}
}
override fun dispose() {
super.dispose()
containerToWindow.remove(container)
if (container is Disposable) {
Disposer.dispose((container as Disposable))
}
northExtensions.clear()
}
override fun createJFrame(parent: IdeFrame): JFrame {
val frame = super.createJFrame(parent)
installListeners(frame)
return frame
}
override fun createJDialog(parent: IdeFrame): JDialog {
val frame = super.createJDialog(parent)
installListeners(frame)
return frame
}
private fun installListeners(frame: Window) {
val uiNotifyConnector = if (container is Activatable) {
UiNotifyConnector((frame as RootPaneContainer).contentPane, (container as Activatable))
}
else {
null
}
frame.addWindowListener(object : WindowAdapter() {
override fun windowClosing(e: WindowEvent) {
container.closeAll()
if (uiNotifyConnector != null) {
Disposer.dispose(uiNotifyConnector)
}
}
})
}
}
override fun getState(): Element {
val root = Element("state")
for (each in allContainers) {
val eachWindow = containerToWindow.get(each)
if (eachWindow != null && eachWindow.supportReopen && each is DockContainer.Persistent) {
val eachWindowElement = Element("window")
eachWindowElement.setAttribute("id", eachWindow.id)
eachWindowElement.setAttribute("withNorthPanel", eachWindow.northPanelAvailable.toString())
eachWindowElement.setAttribute("withToolWindowPane", (eachWindow.toolWindowPane != null).toString())
val content = Element("content")
content.setAttribute("type", each.dockContainerType)
content.addContent(each.state)
eachWindowElement.addContent(content)
root.addContent(eachWindowElement)
}
}
return root
}
private val allContainers: Sequence<DockContainer>
get() {
return sequenceOfNotNull(FileEditorManagerEx.getInstanceEx (project)?.dockContainer) +
containers.asSequence () +
containerToWindow.keys
}
override fun loadState(state: Element) {
loadedState = state
}
private fun readStateFor(type: String) {
for (windowElement in (loadedState ?: return).getChildren("window")) {
val eachContent = windowElement.getChild("content") ?: continue
val eachType = eachContent.getAttributeValue("type")
if (type != eachType || !factories.containsKey(eachType)) {
continue
}
val factory = factories.get(eachType) as? DockContainerFactory.Persistent ?: continue
val container = factory.loadContainerFrom(eachContent)
// If the window already exists, reuse it, otherwise create it. This handles changes in tasks & contexts. When we clear the current
// context, all open editors are closed, but a floating editor container with a docked tool window will remain open. Switching to a
// new context will reuse the window and open editors in that editor container. If the new context doesn't use this window, or it's
// a default clean context, the window will remain open, containing only the docked tool windows.
val window = getOrCreateWindowFor(windowElement.getAttributeValue("id"), container)
// If the window already exists, we can't remove the north panel or tool window pane, but we can add them
if (windowElement.getAttributeValue("withNorthPanel", "true").toBoolean()) {
window.setupNorthPanel()
}
if (windowElement.getAttributeValue("withToolWindowPane", "true").toBoolean()) {
window.setupToolWindowPane()
}
// If the window exists, it's already visible. Don't show multiple times as this will set up additional listeners and window decoration
EdtInvocationManager.invokeLaterIfNeeded {
if (!window.getFrame().isVisible) {
window.show()
}
}
}
}
} | apache-2.0 | ec946f544aed7b9300ce77c55d1c91e6 | 39.187411 | 143 | 0.698576 | 5.106344 | false | false | false | false |
jwren/intellij-community | plugins/kotlin/project-wizard/idea/src/org/jetbrains/kotlin/tools/projectWizard/wizard/service/IdeaKotlinVersionProviderService.kt | 1 | 3508 | // 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.tools.projectWizard.wizard.service
import com.intellij.util.text.VersionComparatorUtil
import org.jetbrains.annotations.NonNls
import org.jetbrains.kotlin.idea.compiler.configuration.KotlinPluginLayout
import org.jetbrains.kotlin.idea.framework.ui.ConfigureDialogWithModulesAndVersion
import org.jetbrains.kotlin.idea.util.application.isApplicationInternalMode
import org.jetbrains.kotlin.tools.projectWizard.Versions
import org.jetbrains.kotlin.tools.projectWizard.core.asNullable
import org.jetbrains.kotlin.tools.projectWizard.core.safe
import org.jetbrains.kotlin.tools.projectWizard.core.service.EapVersionDownloader
import org.jetbrains.kotlin.tools.projectWizard.core.service.KotlinVersionProviderService
import org.jetbrains.kotlin.tools.projectWizard.core.service.WizardKotlinVersion
import org.jetbrains.kotlin.tools.projectWizard.plugins.kotlin.ProjectKind
import org.jetbrains.kotlin.tools.projectWizard.settings.version.Version
import org.jetbrains.kotlin.tools.projectWizard.wizard.KotlinNewProjectWizardUIBundle
import org.jetbrains.kotlin.tools.projectWizard.wizard.ui.runWithProgressBar
@NonNls
private const val SNAPSHOT_TAG = "snapshot"
class IdeaKotlinVersionProviderService : KotlinVersionProviderService(), IdeaWizardService {
override fun getKotlinVersion(projectKind: ProjectKind): WizardKotlinVersion {
if (projectKind == ProjectKind.COMPOSE) {
val version = Versions.KOTLIN_VERSION_FOR_COMPOSE
return kotlinVersionWithDefaultValues(version)
}
val version = getPatchedKotlinVersion()
?: getKotlinVersionFromCompiler()
?: VersionsDownloader.downloadLatestEapOrStableKotlinVersion()
?: Versions.KOTLIN
return kotlinVersionWithDefaultValues(version)
}
private fun getPatchedKotlinVersion() =
if (isApplicationInternalMode()) {
System.getProperty(KOTLIN_COMPILER_VERSION_TAG)?.let { Version.fromString(it) }
} else {
null
}
companion object {
private const val KOTLIN_COMPILER_VERSION_TAG = "kotlin.compiler.version"
private fun getKotlinVersionFromCompiler(): Version? {
val kotlinCompilerVersion = KotlinPluginLayout.instance.standaloneCompilerVersion
val kotlinArtifactVersion = kotlinCompilerVersion.takeUnless { it.isSnapshot }?.artifactVersion ?: return null
return Version.fromString(kotlinArtifactVersion)
}
}
}
private object VersionsDownloader {
fun downloadLatestEapOrStableKotlinVersion(): Version? =
runWithProgressBar(KotlinNewProjectWizardUIBundle.message("version.provider.downloading.kotlin.version")) {
val latestEap = EapVersionDownloader.getLatestEapVersion()
val latestStable = getLatestStableVersion()
when {
latestEap == null -> latestStable
latestStable == null -> latestEap
VersionComparatorUtil.compare(latestEap.text, latestStable.text) > 0 -> latestEap
else -> latestStable
}
}
private fun getLatestStableVersion() = safe {
ConfigureDialogWithModulesAndVersion.loadVersions("1.0.0")
}.asNullable?.firstOrNull { !it.contains(SNAPSHOT_TAG, ignoreCase = true) }?.let { Version.fromString(it) }
}
| apache-2.0 | 60f1755fa29b4da9309aa4dac6c0204b | 47.722222 | 158 | 0.750285 | 5.197037 | false | true | false | false |
GunoH/intellij-community | plugins/devkit/intellij.devkit.workspaceModel/tests/testData/symbolicId/after/gen/SimpleSymbolicIdEntityImpl.kt | 2 | 9446 | package com.intellij.workspaceModel.test.api
import com.intellij.workspaceModel.deft.api.annotations.Default
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.PersistentEntityId
import com.intellij.workspaceModel.storage.SymbolicEntityId
import com.intellij.workspaceModel.storage.WorkspaceEntity
import com.intellij.workspaceModel.storage.WorkspaceEntityWithSymbolicId
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 SimpleSymbolicIdEntityImpl(val dataSource: SimpleSymbolicIdEntityData) : SimpleSymbolicIdEntity, WorkspaceEntityBase() {
companion object {
val connections = listOf<ConnectionId>(
)
}
override val version: Int get() = dataSource.version
override val name: String
get() = dataSource.name
override val related: SimpleId
get() = dataSource.related
override val sealedClassWithLinks: SealedClassWithLinks
get() = dataSource.sealedClassWithLinks
override val entitySource: EntitySource
get() = dataSource.entitySource
override fun connectionIdList(): List<ConnectionId> {
return connections
}
class Builder(result: SimpleSymbolicIdEntityData?) : ModifiableWorkspaceEntityBase<SimpleSymbolicIdEntity, SimpleSymbolicIdEntityData>(
result), SimpleSymbolicIdEntity.Builder {
constructor() : this(SimpleSymbolicIdEntityData())
override fun applyToBuilder(builder: MutableEntityStorage) {
if (this.diff != null) {
if (existsInBuilder(builder)) {
this.diff = builder
return
}
else {
error("Entity SimpleSymbolicIdEntity 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 SimpleSymbolicIdEntity#name should be initialized")
}
if (!getEntityData().isRelatedInitialized()) {
error("Field SimpleSymbolicIdEntity#related should be initialized")
}
if (!getEntityData().isSealedClassWithLinksInitialized()) {
error("Field SimpleSymbolicIdEntity#sealedClassWithLinks 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 SimpleSymbolicIdEntity
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.related != dataSource.related) this.related = dataSource.related
if (this.sealedClassWithLinks != dataSource.sealedClassWithLinks) this.sealedClassWithLinks = dataSource.sealedClassWithLinks
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 related: SimpleId
get() = getEntityData().related
set(value) {
checkModificationAllowed()
getEntityData(true).related = value
changedProperty.add("related")
}
override var sealedClassWithLinks: SealedClassWithLinks
get() = getEntityData().sealedClassWithLinks
set(value) {
checkModificationAllowed()
getEntityData(true).sealedClassWithLinks = value
changedProperty.add("sealedClassWithLinks")
}
override fun getEntityClass(): Class<SimpleSymbolicIdEntity> = SimpleSymbolicIdEntity::class.java
}
}
class SimpleSymbolicIdEntityData : WorkspaceEntityData.WithCalculableSymbolicId<SimpleSymbolicIdEntity>() {
var version: Int = 0
lateinit var name: String
lateinit var related: SimpleId
lateinit var sealedClassWithLinks: SealedClassWithLinks
fun isNameInitialized(): Boolean = ::name.isInitialized
fun isRelatedInitialized(): Boolean = ::related.isInitialized
fun isSealedClassWithLinksInitialized(): Boolean = ::sealedClassWithLinks.isInitialized
override fun wrapAsModifiable(diff: MutableEntityStorage): WorkspaceEntity.Builder<SimpleSymbolicIdEntity> {
val modifiable = SimpleSymbolicIdEntityImpl.Builder(null)
modifiable.diff = diff
modifiable.snapshot = diff
modifiable.id = createEntityId()
return modifiable
}
override fun createEntity(snapshot: EntityStorage): SimpleSymbolicIdEntity {
return getCached(snapshot) {
val entity = SimpleSymbolicIdEntityImpl(this)
entity.snapshot = snapshot
entity.id = createEntityId()
entity
}
}
override fun symbolicId(): SymbolicEntityId<*> {
return SimpleId(name)
}
override fun getEntityInterface(): Class<out WorkspaceEntity> {
return SimpleSymbolicIdEntity::class.java
}
override fun serialize(ser: EntityInformation.Serializer) {
}
override fun deserialize(de: EntityInformation.Deserializer) {
}
override fun createDetachedEntity(parents: List<WorkspaceEntity>): WorkspaceEntity {
return SimpleSymbolicIdEntity(version, name, related, sealedClassWithLinks, 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 SimpleSymbolicIdEntityData
if (this.entitySource != other.entitySource) return false
if (this.version != other.version) return false
if (this.name != other.name) return false
if (this.related != other.related) return false
if (this.sealedClassWithLinks != other.sealedClassWithLinks) return false
return true
}
override fun equalsIgnoringEntitySource(other: Any?): Boolean {
if (other == null) return false
if (this.javaClass != other.javaClass) return false
other as SimpleSymbolicIdEntityData
if (this.version != other.version) return false
if (this.name != other.name) return false
if (this.related != other.related) return false
if (this.sealedClassWithLinks != other.sealedClassWithLinks) 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 + related.hashCode()
result = 31 * result + sealedClassWithLinks.hashCode()
return result
}
override fun hashCodeIgnoringEntitySource(): Int {
var result = javaClass.hashCode()
result = 31 * result + version.hashCode()
result = 31 * result + name.hashCode()
result = 31 * result + related.hashCode()
result = 31 * result + sealedClassWithLinks.hashCode()
return result
}
override fun collectClassUsagesData(collector: UsedClassesCollector) {
collector.add(SimpleId::class.java)
collector.add(SealedClassWithLinks.Many.Unordered::class.java)
collector.add(SealedClassWithLinks.Many::class.java)
collector.add(SealedClassWithLinks.Single::class.java)
collector.add(SealedClassWithLinks::class.java)
collector.add(SealedClassWithLinks.Many.Ordered::class.java)
collector.addObject(SealedClassWithLinks.Nothing::class.java)
this.sealedClassWithLinks?.let { collector.add(it::class.java) }
collector.sameForAllEntities = true
}
}
| apache-2.0 | 7b0d86865b880d305e8d467f50e3bb7f | 34.645283 | 137 | 0.734067 | 5.416284 | false | false | false | false |
smmribeiro/intellij-community | platform/platform-impl/src/com/intellij/openapi/actionSystem/impl/segmentedActionBar/SegmentedActionToolbarComponent.kt | 1 | 7438 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.openapi.actionSystem.impl.segmentedActionBar
import com.intellij.openapi.actionSystem.*
import com.intellij.openapi.actionSystem.ex.ActionButtonLook
import com.intellij.openapi.actionSystem.ex.ComboBoxAction
import com.intellij.openapi.actionSystem.ex.ComboBoxAction.ComboBoxButton
import com.intellij.openapi.actionSystem.ex.CustomComponentAction
import com.intellij.openapi.actionSystem.impl.ActionButton
import com.intellij.openapi.actionSystem.impl.ActionToolbarImpl
import com.intellij.openapi.diagnostic.Logger
import com.intellij.util.ui.JBInsets
import com.intellij.util.ui.JBUI
import com.intellij.util.ui.UIUtil
import java.awt.*
import javax.swing.JComponent
import javax.swing.border.Border
open class SegmentedActionToolbarComponent(place: String, group: ActionGroup, val paintBorderForSingleItem: Boolean = true) : ActionToolbarImpl(place, group, true) {
companion object {
internal const val CONTROL_BAR_PROPERTY = "CONTROL_BAR_PROPERTY"
internal const val CONTROL_BAR_FIRST = "CONTROL_BAR_PROPERTY_FIRST"
internal const val CONTROL_BAR_LAST = "CONTROL_BAR_PROPERTY_LAST"
internal const val CONTROL_BAR_MIDDLE = "CONTROL_BAR_PROPERTY_MIDDLE"
internal const val CONTROL_BAR_SINGLE = "CONTROL_BAR_PROPERTY_SINGLE"
const val RUN_TOOLBAR_COMPONENT_ACTION = "RUN_TOOLBAR_COMPONENT_ACTION"
private val LOG = Logger.getInstance(SegmentedActionToolbarComponent::class.java)
internal val segmentedButtonLook = object : ActionButtonLook() {
override fun paintBorder(g: Graphics, c: JComponent, state: Int) {
}
override fun paintBackground(g: Graphics, component: JComponent, state: Int) {
SegmentedBarPainter.paintActionButtonBackground(g, component, state)
}
}
fun isCustomBar(component: Component): Boolean {
if (component !is JComponent) return false
return component.getClientProperty(CONTROL_BAR_PROPERTY)?.let {
it != CONTROL_BAR_SINGLE
} ?: false
}
fun paintButtonDecorations(g: Graphics2D, c: JComponent, paint: Paint): Boolean {
return SegmentedBarPainter.paintButtonDecorations(g, c, paint)
}
}
init {
layoutPolicy = NOWRAP_LAYOUT_POLICY
}
private var isActive = false
private var visibleActions: MutableList<out AnAction>? = null
override fun getInsets(): Insets {
return JBInsets.emptyInsets()
}
override fun setBorder(border: Border?) {
}
override fun createCustomComponent(action: CustomComponentAction, presentation: Presentation): JComponent {
if (!isActive) {
return super.createCustomComponent(action, presentation)
}
var component = super.createCustomComponent(action, presentation)
if (action is ComboBoxAction) {
UIUtil.uiTraverser(component).filter(ComboBoxButton::class.java).firstOrNull()?.let {
component.remove(it)
component = it
}
}
else if (component is ActionButton) {
val actionButton = component as ActionButton
updateActionButtonLook(actionButton)
}
component.border = JBUI.Borders.empty()
return component
}
override fun createToolbarButton(action: AnAction,
look: ActionButtonLook?,
place: String,
presentation: Presentation,
minimumSize: Dimension): ActionButton {
if (!isActive) {
return super.createToolbarButton(action, look, place, presentation, minimumSize)
}
val createToolbarButton = super.createToolbarButton(action, segmentedButtonLook, place, presentation, minimumSize)
updateActionButtonLook(createToolbarButton)
return createToolbarButton
}
private fun updateActionButtonLook(actionButton: ActionButton) {
actionButton.border = JBUI.Borders.empty(0, 3)
actionButton.setLook(segmentedButtonLook)
}
override fun fillToolBar(actions: MutableList<out AnAction>, layoutSecondaries: Boolean) {
if (!isActive) {
super.fillToolBar(actions, layoutSecondaries)
return
}
val rightAligned: MutableList<AnAction> = ArrayList()
for (i in actions.indices) {
val action = actions[i]
if (action is RightAlignedToolbarAction) {
rightAligned.add(action)
continue
}
if (action is CustomComponentAction) {
val component = getCustomComponent(action)
addMetadata(component, i, actions.size)
add(CUSTOM_COMPONENT_CONSTRAINT, component)
component.putClientProperty(RUN_TOOLBAR_COMPONENT_ACTION, action)
}
else {
val component = createToolbarButton(action)
addMetadata(component, i, actions.size)
add(ACTION_BUTTON_CONSTRAINT, component)
component.putClientProperty(RUN_TOOLBAR_COMPONENT_ACTION, action)
}
}
}
protected open fun isSuitableAction(action: AnAction): Boolean {
return true
}
override fun paintComponent(g: Graphics) {
super.paintComponent(g)
paintActiveBorder(g)
}
private fun paintActiveBorder(g: Graphics) {
if((isActive || paintBorderForSingleItem) && visibleActions != null) {
SegmentedBarPainter.paintActionBarBorder(this, g)
}
}
override fun paintBorder(g: Graphics) {
super.paintBorder(g)
paintActiveBorder(g)
}
override fun paint(g: Graphics) {
super.paint(g)
paintActiveBorder(g)
}
private fun addMetadata(component: JComponent, index: Int, count: Int) {
if (count == 1) {
component.putClientProperty(CONTROL_BAR_PROPERTY, CONTROL_BAR_SINGLE)
return
}
val property = when (index) {
0 -> CONTROL_BAR_FIRST
count - 1 -> CONTROL_BAR_LAST
else -> CONTROL_BAR_MIDDLE
}
component.putClientProperty(CONTROL_BAR_PROPERTY, property)
}
protected open fun logNeeded() = false
protected fun forceUpdate() {
if(logNeeded()) LOG.info("RunToolbar MAIN SLOT forceUpdate")
visibleActions?.let {
update(true, it)
revalidate()
repaint()
}
}
override fun actionsUpdated(forced: Boolean, newVisibleActions: MutableList<out AnAction>) {
visibleActions = newVisibleActions
update(forced, newVisibleActions)
}
private var lastIds: List<String> = emptyList()
private fun update(forced: Boolean, newVisibleActions: MutableList<out AnAction>) {
val filtered = newVisibleActions.filter { isSuitableAction(it) }
val ides = newVisibleActions.map { ActionManager.getInstance().getId(it) }.toList()
val filteredIds = filtered.map { ActionManager.getInstance().getId(it) }.toList()
if(logNeeded() && filteredIds != lastIds) LOG.info("MAIN SLOT new filtered: ${filteredIds}} visible: $ides RunToolbar")
lastIds = filteredIds
isActive = filtered.size > 1
super.actionsUpdated(forced, if (isActive) filtered else newVisibleActions)
}
override fun calculateBounds(size2Fit: Dimension, bounds: MutableList<Rectangle>) {
bounds.clear()
for (i in 0 until componentCount) {
bounds.add(Rectangle())
}
var offset = 0
for (i in 0 until componentCount) {
val d = getChildPreferredSize(i)
val r = bounds[i]
r.setBounds(insets.left + offset, insets.top, d.width, DEFAULT_MINIMUM_BUTTON_SIZE.height)
offset += d.width
}
}
} | apache-2.0 | 6dbc99976a78e93c2fa6f4a9d4ddd1df | 31.770925 | 165 | 0.705297 | 4.666248 | false | false | false | false |
Cognifide/gradle-aem-plugin | src/main/kotlin/com/cognifide/gradle/aem/AemVersion.kt | 1 | 2849 | package com.cognifide.gradle.aem
import com.cognifide.gradle.common.utils.Formats
import com.cognifide.gradle.common.utils.Patterns
import org.gradle.api.JavaVersion
class AemVersion(val value: String) : Comparable<AemVersion> {
private val base = Formats.asVersion(value)
val version get() = base.version
fun atLeast(other: AemVersion) = this >= other
fun atLeast(other: String) = atLeast(AemVersion(other))
fun atMost(other: AemVersion) = other <= this
fun atMost(other: String) = atMost(AemVersion(other))
fun inRange(range: String): Boolean = range.contains("-") && this in unclosedRange(range, "-")
/**
* Indicates repository restructure performed in AEM 6.4.0 / preparations for making AEM available on cloud.
*
* After this changes, nodes under '/apps' or '/libs' are frozen and some features (like workflow manager)
* requires to copy these nodes under '/var' by plugin (or AEM itself).
*
* @see <https://docs.adobe.com/content/help/en/experience-manager-64/deploying/restructuring/repository-restructuring.html>
*/
val frozen get() = atLeast(VERSION_6_4_0)
/**
* Cloud manager version contains time in the end
*/
val cloud get() = Patterns.wildcard(value, "*.*.*.*T*Z")
val type get() = when {
cloud -> "cloud"
else -> "on-prem"
}
// === Overriddes ===
override fun toString() = "$value ($type)"
override fun compareTo(other: AemVersion): Int = base.compareTo(other.base)
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as AemVersion
if (base != other.base) return false
return true
}
override fun hashCode(): Int = base.hashCode()
class UnclosedRange(val start: AemVersion, val end: AemVersion) {
operator fun contains(version: AemVersion) = version >= start && version < end
}
companion object {
val UNKNOWN = AemVersion("0.0.0")
val VERSION_6_0_0 = AemVersion("6.0.0")
val VERSION_6_1_0 = AemVersion("6.1.0")
val VERSION_6_2_0 = AemVersion("6.2.0")
val VERSION_6_3_0 = AemVersion("6.3.0")
val VERSION_6_4_0 = AemVersion("6.4.0")
val VERSION_6_5_0 = AemVersion("6.5.0")
fun unclosedRange(value: String, delimiter: String = "-"): UnclosedRange {
val versions = value.split(delimiter)
if (versions.size != 2) {
throw AemException("AEM version range has invalid format: '$value'!")
}
val (start, end) = versions.map { AemVersion(it) }
return UnclosedRange(start, end)
}
}
}
fun String.javaVersions(delimiter: String = ",") = this.split(delimiter).map { JavaVersion.toVersion(it) }
| apache-2.0 | 27240252c33e80cd5f65d8cd2cd4533e | 30.307692 | 128 | 0.628642 | 3.935083 | false | false | false | false |
shalupov/idea-cloudformation | src/main/kotlin/com/intellij/aws/cloudformation/CloudFormationParser.kt | 2 | 2127 | package com.intellij.aws.cloudformation
import com.intellij.aws.cloudformation.model.CfnNode
import com.intellij.json.psi.JsonFile
import com.intellij.openapi.util.Key
import com.intellij.psi.PsiFile
import org.jetbrains.yaml.psi.YAMLFile
import java.lang.reflect.AccessibleObject
import java.lang.reflect.Field
import java.lang.reflect.Modifier
object CloudFormationParser {
private val PARSED_KEY = Key.create<CloudFormationParsedFile>("CFN_PARSED_FILE")
fun parse(psiFile: PsiFile): CloudFormationParsedFile {
val cached = psiFile.getUserData(PARSED_KEY)
if (cached != null && cached.fileModificationStamp == psiFile.modificationStamp) {
return cached
}
assert(CloudFormationPsiUtils.isCloudFormationFile(psiFile)) { psiFile.name + " is not a CloudFormation file" }
val parsed = when (psiFile) {
is JsonFile -> JsonCloudFormationParser.parse(psiFile)
is YAMLFile -> YamlCloudFormationParser.parse(psiFile)
else -> error("Unsupported PSI file type: " + psiFile.javaClass.name)
}
assertAllNodesAreMapped(parsed)
psiFile.putUserData(PARSED_KEY, parsed)
return parsed
}
private fun assertAllNodesAreMapped(parsed: CloudFormationParsedFile) {
fun isGoodField(field: Field): Boolean =
field.name.indexOf('$') == -1 && !Modifier.isTransient(field.modifiers) && !Modifier.isStatic(field.modifiers)
val seen = mutableSetOf<Any>()
fun processInstance(obj: Any, parent: Any) {
if (seen.contains(obj)) return
seen.add(obj)
if (obj is CfnNode) {
try {
parsed.getPsiElement(obj)
} catch (t: Throwable) {
error("Node $obj under $parent is not mapped")
}
}
if (obj is Collection<*>) {
obj.forEach { it?.let { processInstance(it, parent) } }
return
}
val fields = obj.javaClass.declaredFields
AccessibleObject.setAccessible(fields, true)
fields
.filter { isGoodField(it) }
.mapNotNull { it.get(obj) }
.forEach { processInstance(it, obj) }
}
processInstance(parsed.root, parsed.root)
}
} | apache-2.0 | 2b7082805584721fb7d8770a772816af | 29.84058 | 116 | 0.686883 | 4.220238 | false | false | false | false |
TachiWeb/TachiWeb-Server | TachiServer/src/main/java/xyz/nulldev/ts/api/http/auth/CheckSessionRoute.kt | 1 | 1585 | /*
* Copyright 2016 Andy Bao
*
* 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 xyz.nulldev.ts.api.http.auth
import spark.Request
import spark.Response
import xyz.nulldev.ts.api.http.TachiWebRoute
/**
* Simple route to check if an auth password is correct.
*
* If the auth password is correct, the user is authenticated.
*/
class CheckSessionRoute: TachiWebRoute(requiresAuth = false) {
override fun handleReq(request: Request, response: Response): Any {
val session: String = request.attribute("session")
val password = request.queryParams("password")
val authPw = SessionManager.authPassword()
val valid = if(password.isEmpty())
authPw.isEmpty()
else
authPw.isNotEmpty() && PasswordHasher.check(password, authPw)
return if (valid) {
sessionManager.authenticateSession(session)
success().put(KEY_TOKEN, session)
} else {
error("Incorrect password!")
}
}
companion object {
val KEY_TOKEN = "token"
}
}
| apache-2.0 | f5f53c641066c363ad5923152f43a1be | 30.078431 | 75 | 0.677603 | 4.24933 | false | false | false | false |
ObsidianLang/obsidian-grammar | src/com/obsidian/compiler/daemon/Daemon.kt | 1 | 2452 | /*
* Copyright 2017 Obsidian Foundation
*
* 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.obsidian.compiler.daemon
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.jaxrs.json.JacksonJaxbJsonProvider
import org.glassfish.grizzly.http.server.HttpServer
import org.glassfish.jersey.grizzly2.httpserver.GrizzlyHttpServerFactory
import org.glassfish.jersey.server.ResourceConfig
import javax.ws.rs.core.UriBuilder
import java.net.URI
/**
*
* The daemon's responsibility is to intercept requests from external entities such as editors (VSCode's Language
* Server, for example), debuggers, and anything a person would want to build to use Obsidian's compiler and analysis
* output really.
*
* The daemon provides a RESTful interface to various aspects of Obsidian's internals. These
* internals include, but are not limited to: * Static Analysis * Complexity Analysis
* * Linting * Runtime Debugging
*/
class Daemon : Thread() {
override fun run() {
server = startHttpServer()
}
companion object {
/**
* Where the daemon will listen as its root address
* @TODO Make configurable via command-line arguments
*/
val URI_BASE = UriBuilder.fromUri("http://localhost/").port(9090).path("obsidian/").build()
fun startHttpServer(): HttpServer {
val mapper = ObjectMapper()
val provider = JacksonJaxbJsonProvider()
provider.setMapper(mapper)
// Scans this package for JAX-RS resources needed to build endpoints and responses
val rc = ResourceConfig()
.packages(true, "com.obsidian.compiler.daemon.resources")
.register(provider)
return GrizzlyHttpServerFactory.createHttpServer(URI_BASE, rc)
}
}
var server: HttpServer? = null
init {
if(server != null){
server = startHttpServer()
}
}
}
| apache-2.0 | 0eb7958e9c344ca63b4ac170d8826fec | 32.589041 | 117 | 0.703915 | 4.347518 | false | false | false | false |
rahulchowdhury/Mystique | app/src/main/java/co/upcurve/mystiquesample/items/BannerItem.kt | 1 | 964 | package co.upcurve.mystiquesample.items
import android.view.View
import android.widget.TextView
import butterknife.BindView
import butterknife.ButterKnife
import co.upcurve.mystique.MystiqueItemPresenter
import co.upcurve.mystiquesample.R
import co.upcurve.mystiquesample.models.BannerModel
/**
* Created by rahulchowdhury on 5/29/17.
*/
class BannerItem(var bannerModel: BannerModel = BannerModel()) : MystiqueItemPresenter() {
@BindView(R.id.heading_banner)
lateinit var bannerHeading: TextView
override fun loadModel(model: Any) {
bannerModel = model as BannerModel
}
override fun getModel() = bannerModel
override fun setListener(listener: Any?) {
}
override fun getLayout() = R.layout.view_item_banner
override fun displayView(itemView: View) {
ButterKnife.bind(this, itemView)
bannerHeading.text = bannerModel.heading
}
override fun handleClickEvents(itemView: View) {
}
} | apache-2.0 | 56a0fa29aa85b85dca8f6a9189e6ba76 | 23.125 | 90 | 0.737552 | 4.17316 | false | false | false | false |
intrigus/jtransc | jtransc-utils/src/com/jtransc/text/indent.kt | 2 | 4570 | /*
* Copyright 2016 Carlos Ballesteros Velasco
*
* 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.jtransc.text
import com.jtransc.text.Indenter.Companion
import java.util.*
object INDENTS {
private val INDENTS = arrayListOf<String>("")
operator fun get(index: Int): String {
if (index >= INDENTS.size) {
val calculate = INDENTS.size * 10
var indent = INDENTS[INDENTS.size - 1]
while (calculate >= INDENTS.size) {
indent += "\t"
INDENTS.add(indent)
}
}
return if (index <= 0) "" else INDENTS[index]
}
}
class Indenter(private val actions: ArrayList<Action> = arrayListOf<Indenter.Action>()) : ToString {
interface Action {
data class Marker(val data: Any) : Action
data class Line(val str: String) : Action
data class LineDeferred(val callback: () -> Indenter) : Action
object Indent : Action
object Unindent : Action
}
val noIndentEmptyLines = true
companion object {
fun genString(init: Indenter.() -> Unit) = this(init).toString()
val EMPTY = Indenter { }
inline operator fun invoke(init: Indenter.() -> Unit): Indenter {
val indenter = Indenter()
indenter.init()
return indenter
}
@Deprecated("", ReplaceWith("this(str)", "com.jtransc.text.Indenter.Companion"))
fun single(str: String): Indenter = this(str)
operator fun invoke(str: String): Indenter = Indenter(arrayListOf(Action.Line(str)))
fun replaceString(templateString: String, replacements: Map<String, String>): String {
val pattern = Regex("\\$(\\w+)")
return pattern.replace(templateString) { result ->
replacements[result.groupValues[1]] ?: ""
}
}
}
var out: String = ""
fun line(indenter: Indenter) = this.apply { this.actions.addAll(indenter.actions) }
fun line(str: String) = this.apply { this.actions.add(Action.Line(str)) }
fun line(str: String?) {
if (str != null) line(str)
}
fun mark(data: Any) = this.apply { this.actions.add(Action.Marker(data)) }
fun linedeferred(init: Indenter.() -> Unit): Indenter {
this.actions.add(Action.LineDeferred({
val indenter = Indenter()
indenter.init()
indenter
}))
return this
}
fun lines(strs: List<String>): Indenter = this.apply {
for (str in strs) line(str)
}
inline fun line(str: String, callback: () -> Unit): Indenter {
line(if (str.isEmpty()) "{" else "$str {")
indent(callback)
line("}")
return this
}
inline fun line(str: String, after: String = "", after2:String = "", callback: () -> Unit): Indenter {
line(if (str.isEmpty()) "{ $after" else "$str { $after")
indent(callback)
line("}$after2")
return this
}
inline fun indent(callback: () -> Unit): Indenter {
_indent()
try {
callback()
} finally {
_unindent()
}
return this
}
fun _indent() {
actions.add(Action.Indent)
}
fun _unindent() {
actions.add(Action.Unindent)
}
fun toString(markHandler: ((sb: StringBuilder, line: Int, data: Any) -> Unit)?, doIndent: Boolean): String {
val out = StringBuilder()
var line = 0
var indentIndex = 0
fun eval(actions: List<Action>) {
for (action in actions) {
when (action) {
is Action.Line -> {
if (noIndentEmptyLines && action.str.isEmpty()) {
if (doIndent) out.append('\n')
line++
} else {
if (doIndent) out.append(INDENTS[indentIndex]) else out.append(" ")
out.append(action.str)
line += action.str.count { it == '\n' }
if (doIndent) out.append('\n')
line++
}
}
is Action.LineDeferred -> eval(action.callback().actions)
Action.Indent -> indentIndex++
Action.Unindent -> indentIndex--
is Action.Marker -> {
markHandler?.invoke(out, line, action.data)
}
}
}
}
eval(actions)
return out.toString()
}
fun toString(markHandler: ((sb: StringBuilder, line: Int, data: Any) -> Unit)?): String = toString(markHandler = markHandler, doIndent = true)
fun toString(doIndent: Boolean = true): String = toString(markHandler = null, doIndent = doIndent)
override fun toString(): String = toString(null, doIndent = true)
}
| apache-2.0 | 66d2d417e695dfe0b444cc599668733b | 26.53012 | 143 | 0.657987 | 3.438676 | false | false | false | false |
CenturyLinkCloud/mdw | mdw-workflow/assets/com/centurylink/mdw/kotlin/ScriptEvaluator.kt | 2 | 5548 | /*
* Copyright (C) 2018 CenturyLink, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.centurylink.mdw.kotlin
import org.jetbrains.kotlin.cli.common.repl.InvokeWrapper
import org.jetbrains.kotlin.cli.common.repl.ReplEvalResult
import org.jetbrains.kotlin.cli.common.repl.ScriptArgsWithTypes
import org.jetbrains.kotlin.cli.common.repl.renderReplStackTrace
import org.jetbrains.kotlin.resolve.jvm.JvmClassName
import java.io.File
import java.lang.reflect.InvocationTargetException
import java.net.URLClassLoader
import javax.script.Bindings
open class ScriptEvaluator(
val baseClasspath: Iterable<File>,
val baseClassloader: ClassLoader? = Thread.currentThread().contextClassLoader,
protected val fallbackScriptArgs: ScriptArgsWithTypes? = null
) {
fun eval(compileResult: ScriptCompileResult.CompiledClasses,
scriptArgs: ScriptArgsWithTypes?,
invokeWrapper: InvokeWrapper?): ReplEvalResult {
val (classLoader, scriptClass) = try {
processClasses(compileResult)
}
catch (e: Exception) {
e.printStackTrace() // TODO
return@eval ReplEvalResult.Error.Runtime(e.message ?: "unknown", e)
}
val currentScriptArgs = scriptArgs ?: fallbackScriptArgs
val useScriptArgs = currentScriptArgs?.scriptArgs
val useScriptArgsTypes = currentScriptArgs?.scriptArgsTypes?.map { it.java }
val constructorParams: Array<Class<*>> = emptyArray<Class<*>>() +
(useScriptArgs?.mapIndexed { i, it -> useScriptArgsTypes?.getOrNull(i) ?: it?.javaClass ?: Any::class.java } ?: emptyList())
val constructorArgs: Array<out Any?> = useScriptArgs.orEmpty()
// TODO: try/catch ?
val scriptInstanceConstructor = scriptClass.getConstructor(*constructorParams)
val scriptInstance =
try {
if (invokeWrapper != null) invokeWrapper.invoke { scriptInstanceConstructor.newInstance(*constructorArgs) }
else scriptInstanceConstructor.newInstance(*constructorArgs)
}
catch (e: InvocationTargetException) {
// ignore everything in the stack trace until this constructor call
return@eval ReplEvalResult.Error.Runtime(renderReplStackTrace(e.cause!!, startFromMethodName = "${scriptClass.name}.<init>"), e.targetException as? Exception)
}
catch (e: Throwable) {
// ignore everything in the stack trace until this constructor call
return@eval ReplEvalResult.Error.Runtime(renderReplStackTrace(e.cause!!, startFromMethodName = "${scriptClass.name}.<init>"), e as? Exception)
}
val resultField = scriptClass.getDeclaredField(SCRIPT_RESULT_FIELD_NAME).apply { isAccessible = true }
val resultValue: Any? = resultField.get(scriptInstance)
if (currentScriptArgs != null) {
val bindings = currentScriptArgs.scriptArgs[0] as Bindings
val vars = currentScriptArgs.scriptArgs[1] as Map<String,Any?>
for ((key, value) in vars) {
bindings[key] = value
}
}
return if (compileResult.hasResult) ReplEvalResult.ValueResult(resultValue, compileResult.type)
else ReplEvalResult.UnitResult()
}
companion object {
private val SCRIPT_RESULT_FIELD_NAME = "\$\$result"
}
private fun processClasses(compileResult: ScriptCompileResult.CompiledClasses
): Pair<ClassLoader, Class<out Any>> {
var mainLineClassName: String? = null
val classLoader = makeScriptClassLoader(baseClassloader, compileResult.classpathAddendum)
fun classNameFromPath(path: String) = JvmClassName.byInternalName(path.removeSuffix(".class"))
fun compiledClassesNames() = compileResult.classes.map { classNameFromPath(it.path).internalName.replace('/', '.') }
val expectedClassName = compileResult.mainClassName
compileResult.classes.filter { it.path.endsWith(".class") }
.forEach {
val className = classNameFromPath(it.path)
if (className.internalName == expectedClassName || className.internalName.endsWith("/$expectedClassName")) {
mainLineClassName = className.internalName.replace('/', '.')
}
classLoader.addClass(className, it.bytes)
}
val scriptClass = try {
classLoader.loadClass(mainLineClassName!!)
}
catch (t: Throwable) {
throw Exception("Error loading class $mainLineClassName: known classes: ${compiledClassesNames()}", t)
}
return Pair(classLoader, scriptClass)
}
fun makeScriptClassLoader(baseClassloader: ClassLoader?, baseClasspath: Iterable<File>) =
ScriptClassLoader(URLClassLoader(baseClasspath.map { it.toURI().toURL() }.toTypedArray(), baseClassloader))
} | mit | d057d3d56d0fd16a4a1afbd53ac42176 | 45.241667 | 178 | 0.669971 | 4.980251 | false | false | false | false |
timakden/advent-of-code | src/main/kotlin/ru/timakden/aoc/year2016/day10/Puzzle.kt | 1 | 3360 | package ru.timakden.aoc.year2016.day10
import ru.timakden.aoc.util.Constants.Part
import ru.timakden.aoc.util.Constants.Part.PART_ONE
import ru.timakden.aoc.util.Constants.Part.PART_TWO
import ru.timakden.aoc.util.measure
import kotlin.time.ExperimentalTime
@ExperimentalTime
fun main() {
measure {
println("Part One: ${solve(input.toMutableList(), listOf(17, 61), PART_ONE)}")
println("Part Two: ${solve(input.toMutableList(), listOf(17, 61), PART_TWO)}")
}
}
fun solve(input: MutableList<String>, valuesToCompare: List<Int>, part: Part): Int {
val bots = mutableMapOf<Int, MutableList<Int>>()
val outputs = mutableMapOf<Int, Int>()
while (input.isNotEmpty()) {
val iterator = input.listIterator()
while (iterator.hasNext()) {
val instruction = iterator.next()
if (instruction.startsWith("value")) {
val botNumber = instruction.substringAfter("bot ").toInt()
val chipValue = instruction.substringAfter("value ").substringBefore(" goes").toInt()
if (bots.contains(botNumber)) {
bots[botNumber]?.add(chipValue)
} else {
bots[botNumber] = mutableListOf(chipValue)
}
iterator.remove()
} else {
val botNumber = instruction.substringAfter("bot ").substringBefore(" gives").toInt()
if (bots.contains(botNumber) && bots[botNumber]?.size == 2) {
val lowTo = instruction.substringAfter("low to ").substringBefore(" and high")
val lowToNumber = lowTo.substringAfter(" ").toInt()
val highTo = instruction.substringAfter("high to ")
val highToNumber = highTo.substringAfter(" ").toInt()
val lowValue = bots[botNumber]?.minOrNull()!!
val highValue = bots[botNumber]?.maxOrNull()!!
if (lowTo.contains("bot")) {
if (bots.contains(lowToNumber)) {
bots[lowToNumber]?.add(lowValue)
} else {
bots[lowToNumber] = mutableListOf(lowValue)
}
} else {
outputs[lowToNumber] = lowValue
}
if (highTo.contains("bot")) {
if (bots.contains(highToNumber)) {
bots[highToNumber]?.add(highValue)
} else {
bots[highToNumber] = mutableListOf(highValue)
}
} else {
outputs[highToNumber] = highValue
}
bots.remove(botNumber)
iterator.remove()
}
}
if (part == PART_ONE) {
for ((key, value) in bots) {
if (value.size == 2 && value.containsAll(valuesToCompare)) {
return key
}
}
}
if (part == PART_TWO && outputs.contains(0) && outputs.contains(1) && outputs.contains(2)) {
return outputs[0]!! * outputs[1]!! * outputs[2]!!
}
}
}
return -1
}
| apache-2.0 | ef3f5b8e24fb1862a6b077432523f52d | 36.752809 | 104 | 0.497024 | 5.067873 | false | false | false | false |
thuytrinh/KotlinPlayground | src/main/kotlin/JsonPlayground.kt | 1 | 524 | import kotlinx.serialization.Serializable
import kotlinx.serialization.encodeToString
import kotlinx.serialization.json.Json
@Serializable
data class Event(
val title: String,
val beginDateTime: String,
val endDateTime: String
)
fun main() {
val expected = Event(
title = "Team retro",
beginDateTime = "20.08.2020 16:00",
endDateTime = "20.08.2020 17:00",
)
val json = Json.encodeToString(expected)
val actual = Json.decodeFromString(Event.serializer(), json)
println(json)
println(actual)
}
| mit | 6b71f1d3242b94f05457f3da92e644a9 | 22.818182 | 62 | 0.732824 | 3.824818 | false | false | false | false |
hazuki0x0/YuzuBrowser | module/adblock/src/main/java/jp/hazuki/yuzubrowser/adblock/filter/unified/Tag.kt | 1 | 2264 | /*
* Copyright 2020 Hazuki
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package jp.hazuki.yuzubrowser.adblock.filter.unified
import java.util.*
object Tag {
fun create(url: String): List<String> {
return url.toLowerCase(Locale.ENGLISH).getTagCandidates().also {
it += ""
}
}
fun createBest(pattern: String): String {
var maxLength = 0
var tag = ""
val candidates = pattern.toLowerCase(Locale.ENGLISH).getTagCandidates()
for (i in 0 until candidates.size) {
val candidate = candidates[i]
if (candidate.length > maxLength) {
maxLength = candidate.length
tag = candidate
}
}
return tag
}
private fun String.getTagCandidates(): MutableList<String> {
var start = 0
val list = mutableListOf<String>()
for (i in 0 until length) {
when (get(i)) {
in 'a'..'z', in '0'..'9', '%' -> continue
else -> {
if (i != start && i - start >= 3) {
val tag = substring(start, i)
if (!isPrevent(tag)) {
list += tag
}
}
start = i + 1
}
}
}
if (length != start && length - start >= 3) {
val tag = substring(start, length)
if (!isPrevent(tag)) {
list += tag
}
}
return list
}
private fun isPrevent(tag: String): Boolean {
return when (tag) {
"http", "https", "html", "jpg", "png" -> true
else -> false
}
}
}
| apache-2.0 | 5b6a5264c51ecbebc274f24b228c4f4e | 28.789474 | 79 | 0.518551 | 4.555332 | false | false | false | false |
tmarsteel/kotlin-prolog | parser/src/main/kotlin/com/github/prologdb/parser/parser/InternalParserError.kt | 1 | 799 | package com.github.prologdb.parser.parser
private const val FEEDBACK_NOTE = "Please send the stacktrace and steps to reproduce to the author of this library."
open class InternalParserError private constructor(actualMessage: Any) : Exception(actualMessage.toString()) {
// the (Any) constructor serves a purpose:
// Calling InternalParserError() should result in ex.message == FEEDBACK_NOTE
// Calling InternalParserError(someMessage) should result in ex.message == someMessage + " " + FEEDBACK_NOTE
// The any constructor is used so that (String) can be declared separately; otherwise the signatures would be
// equal and the code would not compile.
constructor() : this(FEEDBACK_NOTE as Any)
constructor(message: String) : this(("$message $FEEDBACK_NOTE") as Any)
} | mit | 0d2bf20fe00247f1e2d4a4dca1281b27 | 52.333333 | 116 | 0.747184 | 4.463687 | false | false | false | false |
terracotta-ko/Android_Treasure_House | LiveData_MVVM_Example/app/src/main/java/com/kobe/livedata_mvvm_example/ui/main/MainViewModel.kt | 1 | 574 | package com.kobe.livedata_mvvm_example.ui.main
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
class MainViewModel : ViewModel() {
private var number: Int = 1
private val _message = MutableLiveData<String>()
//>> this is the public immutable LiveData
//>> override the getter here
val message: LiveData<String>
get() = _message
init {
_message.value = "This is the ViewModel"
}
fun shuffleMessage() {
_message.value = "Shuffle " + number++
}
}
| mit | 7cb83fa7442d3e0a7d1d717da1005445 | 23.956522 | 52 | 0.675958 | 4.315789 | false | false | false | false |
hwki/SimpleBitcoinWidget | bitcoin/src/main/java/com/brentpanther/bitcoinwidget/ui/settings/SettingsComponents.kt | 1 | 12710 | package com.brentpanther.bitcoinwidget.ui.settings
import androidx.annotation.StringRes
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.itemsIndexed
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.foundation.selection.selectable
import androidx.compose.foundation.selection.toggleable
import androidx.compose.foundation.text.KeyboardActions
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material.*
import androidx.compose.material.ripple.LocalRippleTheme
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.semantics.Role
import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.unit.dp
import androidx.compose.ui.window.Dialog
import com.brentpanther.bitcoinwidget.ui.theme.HighlightRippleTheme
import java.lang.Integer.max
import java.util.*
@Composable
fun Setting(
modifier: Modifier = Modifier,
icon: @Composable () -> Unit = {},
title: @Composable () -> Unit,
subtitle: @Composable (() -> Unit)? = null,
content: @Composable ((BoxScope).() -> Unit) = {}
) {
CompositionLocalProvider(LocalRippleTheme provides HighlightRippleTheme()) {
Row(
modifier = modifier
.fillMaxWidth()
.padding(horizontal = 16.dp)
.heightIn(min = 72.dp),
verticalAlignment = Alignment.CenterVertically
) {
Box(
contentAlignment = Alignment.Center,
modifier = Modifier
.padding(end = 16.dp)
.size(24.dp)
) {
CompositionLocalProvider(LocalContentAlpha provides ContentAlpha.medium) {
icon()
}
}
Column(
verticalArrangement = Arrangement.Center,
modifier = Modifier
.weight(1f, true)
.padding(start = 16.dp)
) {
ProvideTextStyle(value = MaterialTheme.typography.subtitle1) {
title()
}
if (subtitle != null) {
CompositionLocalProvider(LocalContentAlpha provides ContentAlpha.medium) {
ProvideTextStyle(value = MaterialTheme.typography.body2) {
subtitle()
}
}
}
}
Box(
modifier = Modifier
.size(48.dp)
.padding(16.dp),
contentAlignment = Alignment.Center
) {
content()
}
}
}
}
@Composable
fun SettingsHeader(@StringRes title: Int, modifier: Modifier = Modifier, withDivider: Boolean = true) {
Surface {
if (withDivider) {
Divider()
}
Row(
modifier
.fillMaxWidth()
.height(36.dp)
.padding(top = 16.dp, start = 16.dp),
verticalAlignment = Alignment.CenterVertically
) {
CompositionLocalProvider(LocalContentAlpha provides ContentAlpha.medium) {
ProvideTextStyle(value = MaterialTheme.typography.subtitle2.copy(color = MaterialTheme.colors.secondary)) {
Text(stringResource(id = title), Modifier.padding(start = 56.dp))
}
}
}
}
}
@Composable
fun SettingsSwitch(
icon: @Composable () -> Unit = {},
title: @Composable () -> Unit,
subtitle: (@Composable () -> Unit)? = null,
value: Boolean = false,
onChange: (Boolean) -> Unit
) {
Setting(
modifier = Modifier.toggleable(
value = value,
role = Role.Switch,
onValueChange = onChange
),
icon = icon,
title = title,
subtitle = subtitle
) {
Switch(
checked = value,
onCheckedChange = null,
colors = SwitchDefaults.colors(
uncheckedThumbColor = Color(0xffdddddd)
)
)
}
}
@Composable
fun SettingsEditText(
icon: @Composable () -> Unit = {},
title: @Composable () -> Unit,
subtitle: (@Composable () -> Unit)? = null,
dialogText: (@Composable () -> Unit)? = null,
value: String? = null,
onChange: (String) -> Unit
) {
var dialogVisible by remember { mutableStateOf(false) }
Setting(
modifier = Modifier.clickable {
dialogVisible = true
},
icon = icon,
title = title,
subtitle = subtitle
) {
var tempValue by remember { mutableStateOf(value) }
if (dialogVisible) {
Dialog(
onDismissRequest = {
dialogVisible = false
}
) {
Surface(
shape = MaterialTheme.shapes.medium,
modifier = Modifier.padding(vertical = 8.dp)
) {
Column(
Modifier.padding(start = 20.dp, top = 20.dp)
)
{
Row(
Modifier.padding(bottom = 12.dp)
) {
ProvideTextStyle(value = MaterialTheme.typography.h6) {
title()
}
}
Row(
Modifier.padding(bottom = 8.dp)
) {
dialogText?.invoke()
}
OutlinedTextField(
value = tempValue ?: "",
keyboardOptions = KeyboardOptions(
keyboardType = KeyboardType.Decimal,
imeAction = ImeAction.Done
),
keyboardActions = KeyboardActions {
onChange(tempValue ?: "1")
dialogVisible = false
},
singleLine = true,
onValueChange = {
tempValue = it
}
)
Row(
Modifier
.fillMaxWidth()
.padding(8.dp),
horizontalArrangement = Arrangement.End
) {
TextButton(
onClick = {
onChange(tempValue ?: "1")
dialogVisible = false
}
) {
Text(
stringResource(android.R.string.ok).uppercase(Locale.getDefault())
)
}
TextButton(
onClick = {
dialogVisible = false
}
) {
Text(
stringResource(android.R.string.cancel).uppercase(Locale.getDefault())
)
}
}
}
}
}
}
}
}
@Composable
fun SettingsList(
icon: @Composable () -> Unit = {},
title: @Composable () -> Unit,
subtitle: (@Composable (String?) -> Unit)? = null,
items: List<String>,
itemValues: List<String> = items,
value: String? = null,
onChange: (String) -> Unit
) {
var dialogVisible by remember { mutableStateOf(false) }
val currentIndex = itemValues.indexOf(value)
SettingsButton(
icon = icon,
title = title,
subtitle = {
val subtitleValue = if (currentIndex > -1) items[currentIndex] else null
subtitle?.invoke(subtitleValue)
},
onClick = {
dialogVisible = true
}
)
if (dialogVisible) {
Dialog(
onDismissRequest = {
dialogVisible = false
}
) {
Surface(
shape = MaterialTheme.shapes.medium,
modifier = Modifier.padding(vertical = 8.dp)
) {
Column {
Row(
Modifier.padding(start = 20.dp, top = 20.dp, bottom = 12.dp)
) {
ProvideTextStyle(value = MaterialTheme.typography.h6) {
title()
}
}
val state = rememberLazyListState(max(0, currentIndex))
LazyColumn(state = state, modifier = Modifier.weight(1f, false)) {
itemsIndexed(items) { index, item ->
RadioDialogItem(
item = item,
selected = index == currentIndex,
onClick = {
onChange(itemValues[index])
dialogVisible = false
}
)
}
}
Row(
Modifier
.fillMaxWidth()
.padding(8.dp),
horizontalArrangement = Arrangement.End
) {
TextButton(
onClick = {
dialogVisible = false
}
) {
Text(
stringResource(android.R.string.cancel).uppercase(Locale.getDefault())
)
}
}
}
}
}
}
}
@Composable
fun SettingsButton(
icon: @Composable () -> Unit = {},
title: @Composable () -> Unit,
subtitle: (@Composable () -> Unit)? = null,
onClick: () -> Unit
) {
Setting(
modifier = Modifier.clickable(onClick = onClick),
icon = icon,
title = title,
subtitle = subtitle
)
}
@Composable
fun SettingsSlider(
icon: @Composable () -> Unit = {},
title: @Composable () -> Unit,
subtitle: (@Composable () -> Unit)? = null,
range: IntRange,
value: Int,
onChange: (Int) -> Unit
) {
Column {
Setting(
icon = icon,
title = title,
subtitle = subtitle
)
Slider(
value.toFloat(),
onValueChange = {
onChange(it.toInt())
},
valueRange = range.first.toFloat()..range.last.toFloat(),
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 16.dp)
.padding(start = 48.dp),
colors = SliderDefaults.colors(
thumbColor = MaterialTheme.colors.secondaryVariant,
activeTrackColor = MaterialTheme.colors.secondaryVariant
)
)
}
}
@Composable
private fun RadioDialogItem(
item: String,
selected: Boolean,
onClick: () -> Unit
) {
CompositionLocalProvider(LocalRippleTheme provides HighlightRippleTheme()) {
Row(
Modifier
.fillMaxWidth()
.height(48.dp)
.selectable(
selected = selected,
onClick = onClick,
role = Role.RadioButton
)
.padding(horizontal = 20.dp),
verticalAlignment = Alignment.CenterVertically
) {
RadioButton(
selected = selected,
onClick = null
)
Text(
text = item,
style = MaterialTheme.typography.body1,
modifier = Modifier.padding(start = 16.dp)
)
}
}
} | mit | 50a7b33fc00a6a680d7191f95f2ffef1 | 32.274869 | 123 | 0.452478 | 5.873383 | false | false | false | false |
dkhmelenko/Varis-Android | app-v3/src/main/java/com/khmelenko/lab/varis/util/StringUtils.kt | 2 | 1163 | package com.khmelenko.lab.varis.util
import java.util.Random
/**
* Provides utils methods for the work with Strings
*
* @author Dmytro Khmelenko
*/
object StringUtils {
/**
* Gets random string
*
* @return Random string
*/
@JvmStatic
fun getRandomString(): String {
val length = 10
return getRandomString(length)
}
/**
* Gets random string
*
* @param length String length
* @return Random string
*/
@JvmStatic
fun getRandomString(length: Int): String {
val chars = "ABCDEFGHIJKLMONPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".toCharArray()
val builder = StringBuilder()
val random = Random()
for (i in 0 until length) {
val c = chars[random.nextInt(chars.size)]
builder.append(c)
}
return builder.toString()
}
/**
* Checks whether the string is null or not
*
* @param string String for checking
* @return True if string is empty. False otherwise
*/
@JvmStatic
fun isEmpty(string: String?): Boolean {
return string == null || string.isEmpty()
}
}
| apache-2.0 | abde9903d8355e3c33e1deefbdd13e61 | 21.803922 | 88 | 0.596733 | 4.57874 | false | false | false | false |
wakim/esl-pod-client | app/src/main/java/br/com/wakim/eslpodclient/ui/podcastlist/view/PodcastListActivity.kt | 1 | 8465 | package br.com.wakim.eslpodclient.ui.podcastlist.view
import android.os.Bundle
import android.support.design.widget.AppBarLayout
import android.support.design.widget.CoordinatorLayout
import android.support.design.widget.FloatingActionButton
import android.support.design.widget.Snackbar
import android.support.v4.app.Fragment
import android.view.Menu
import android.view.MenuItem
import br.com.wakim.eslpodclient.R
import br.com.wakim.eslpodclient.android.widget.LoadingFloatingActionButton
import br.com.wakim.eslpodclient.dagger.PodcastPlayerComponent
import br.com.wakim.eslpodclient.dagger.module.PodcastPlayerModule
import br.com.wakim.eslpodclient.ui.podcastlist.downloaded.view.DownloadedListFragment
import br.com.wakim.eslpodclient.ui.podcastlist.favorited.view.FavoritedListFragment
import br.com.wakim.eslpodclient.ui.podcastplayer.view.ListPlayerView
import br.com.wakim.eslpodclient.ui.settings.view.SettingsActivity
import br.com.wakim.eslpodclient.ui.view.BaseActivity
import br.com.wakim.eslpodclient.util.extensions.snack
import br.com.wakim.eslpodclient.util.extensions.startActivity
import butterknife.BindView
import it.sephiroth.android.library.bottomnavigation.BottomBehavior
import it.sephiroth.android.library.bottomnavigation.BottomNavigation
open class PodcastListActivity : BaseActivity() {
companion object {
const val MINIMUM_THRESHOLD = 5
const val FRAGMENT_TAG = "FRAGMENT"
}
private var podcastPlayerComponent: PodcastPlayerComponent? = null
@BindView(R.id.coordinator_layout)
lateinit var coordinatorLayout: CoordinatorLayout
@BindView(R.id.appbar)
lateinit var appBarLayout: AppBarLayout
@BindView(R.id.player_view)
lateinit var playerView: ListPlayerView
@BindView(R.id.fab_play)
lateinit var playFab: FloatingActionButton
@BindView(R.id.fab_pause)
lateinit var pauseFab: FloatingActionButton
@BindView(R.id.fab_loading)
lateinit var loadingFab: LoadingFloatingActionButton
@BindView(R.id.bottom_navigation)
lateinit var bottomBar: BottomNavigation
var podcastListFragment: PodcastListFragment? = null
var downloadedListFragment: DownloadedListFragment? = null
var favoritedListFragment: FavoritedListFragment? = null
var currentFragment: PodcastListFragment? = null
var savedState = arrayOfNulls<Fragment.SavedState>(3)
var lastSelectedPosition = 0
var lastOffset: Int = 0
override fun onCreate(savedInstanceState: Bundle?) {
setTheme(R.style.AppTheme)
createActivityComponent()
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_podcastlist)
createPlayerComponent()
restoreFragmentStates(savedInstanceState)
configureAppBarLayout()
configureBottomBar()
addFragmentIfNeeded()
playerView.setControls(playFab, pauseFab, loadingFab)
}
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
val fragmentManager = supportFragmentManager
podcastListFragment?.let {
if (it.isAdded) {
fragmentManager.putFragment(outState, "PODCAST_LIST", it)
}
}
favoritedListFragment?.let {
if (it.isAdded) {
fragmentManager.putFragment(outState, "FAVORITED_LIST", it)
}
}
downloadedListFragment?.let {
if (it.isAdded) {
fragmentManager.putFragment(outState, "DOWNLOADED_LIST", it)
}
}
}
fun configureAppBarLayout() {
appBarLayout.addOnOffsetChangedListener { appBarLayout, offset ->
currentFragment?.let {
if (offset == 0) {
it.setSwipeRefreshEnabled(true)
} else if (lastOffset == 0 && it.isSwipeRefreshEnabled()) {
it.setSwipeRefreshEnabled(false)
}
}
lastOffset = offset
}
}
override fun onCreateOptionsMenu(menu: Menu?): Boolean {
menuInflater.inflate(R.menu.podcast_list_menu, menu)
return super.onCreateOptionsMenu(menu)
}
override fun onOptionsItemSelected(item: MenuItem?): Boolean {
if (item?.itemId == R.id.menu_settings) {
startActivity<SettingsActivity>()
return true
}
return super.onOptionsItemSelected(item)
}
fun restoreFragmentStates(savedInstanceState: Bundle?) {
savedInstanceState?.let {
val fragmentManager = supportFragmentManager
podcastListFragment = fragmentManager.getFragment(it, "PODCAST_LIST") as? PodcastListFragment
favoritedListFragment = fragmentManager.getFragment(it, "FAVORITED_LIST") as? FavoritedListFragment
downloadedListFragment = fragmentManager.getFragment(it, "DOWNLOADED_LIST") as? DownloadedListFragment
}
}
fun configureBottomBar() {
bottomBar.setOnMenuItemClickListener(object: BottomNavigation.OnMenuItemSelectionListener {
override fun onMenuItemSelect(id: Int, position: Int) {
when (position) {
0 -> replaceListFragment(PodcastListFragment(), lastSelectedPosition, position)
1 -> replaceFavoritedFragment(FavoritedListFragment(), lastSelectedPosition, position)
2 -> replaceDownloadedFragment(DownloadedListFragment(), lastSelectedPosition, position)
}
lastSelectedPosition = position
}
override fun onMenuItemReselect(p0: Int, p1: Int) { }
})
}
fun addFragmentIfNeeded() {
currentFragment = supportFragmentManager.findFragmentByTag(FRAGMENT_TAG) as PodcastListFragment?
if (currentFragment == null) {
podcastListFragment = PodcastListFragment()
currentFragment = podcastListFragment
supportFragmentManager
.beginTransaction()
.add(R.id.container, podcastListFragment, FRAGMENT_TAG)
.commit()
}
}
fun replaceListFragment(fragment: PodcastListFragment, previousPosition: Int, position: Int) {
podcastListFragment = fragment
replaceFragment(fragment, previousPosition, position)
}
fun replaceFavoritedFragment(fragment: FavoritedListFragment, previousPosition: Int, position: Int) {
favoritedListFragment = favoritedListFragment
replaceFragment(fragment, previousPosition, position)
}
fun replaceDownloadedFragment(fragment: DownloadedListFragment, previousPosition: Int, position: Int) {
downloadedListFragment = fragment
replaceFragment(fragment, previousPosition, position)
}
fun replaceFragment(fragment: PodcastListFragment, previousPosition: Int, position: Int) {
val fragmentManager = supportFragmentManager
val previousFragment = fragmentManager.findFragmentByTag(FRAGMENT_TAG)
val state = savedState[position]
savedState[previousPosition] = fragmentManager.saveFragmentInstanceState(previousFragment)
state?.let {
fragment.setInitialSavedState(state)
}
currentFragment = fragment
fragmentManager
.beginTransaction()
.replace(R.id.container, fragment, FRAGMENT_TAG)
.commit()
}
override fun getSystemService(name: String?): Any? {
if (name == PodcastPlayerComponent::class.java.simpleName) {
return podcastPlayerComponent
}
return super.getSystemService(name)
}
fun createPlayerComponent() {
podcastPlayerComponent = activityComponent + PodcastPlayerModule(playerView)
}
override fun onBackPressed() {
with (playerView) {
if (isExpanded()) {
collapse()
return
}
if (isVisible()) {
hide()
return
}
}
disposePlayerIfNeeded()
super.onBackPressed()
}
override fun finish() {
disposePlayerIfNeeded()
super.finish()
}
open fun disposePlayerIfNeeded() {
if (!playerView.isPlaying()) {
playerView.explicitlyStop()
}
}
override fun showMessage(messageResId: Int): Snackbar = snack(coordinatorLayout, messageResId)
} | apache-2.0 | cdcb289a33e25729a5d38e37a772f2cf | 32.2 | 114 | 0.677259 | 5.482513 | false | false | false | false |
cketti/k-9 | mail/common/src/test/java/com/fsck/k9/mail/BoundaryGeneratorTest.kt | 1 | 1152 | package com.fsck.k9.mail
import com.google.common.truth.Truth.assertThat
import java.util.Random
import org.junit.Test
import org.mockito.kotlin.mock
class BoundaryGeneratorTest {
@Test
fun `generateBoundary() with all zeros`() {
val random = createRandom(0)
val boundaryGenerator = BoundaryGenerator(random)
val result = boundaryGenerator.generateBoundary()
assertThat(result).isEqualTo("----000000000000000000000000000000")
}
@Test
fun generateBoundary() {
val random = createRandom(
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 35
)
val boundaryGenerator = BoundaryGenerator(random)
val result = boundaryGenerator.generateBoundary()
assertThat(result).isEqualTo("----0123456789ABCDEFGHIJKLMNOPQRSZ")
}
private fun createRandom(vararg values: Int): Random {
return mock {
var ongoingStubbing = on { nextInt(36) }
for (value in values) {
ongoingStubbing = ongoingStubbing.thenReturn(value)
}
}
}
}
| apache-2.0 | c14f50a1fc0b39257d6fa8dab386d7db | 28.538462 | 120 | 0.62934 | 4.20438 | false | true | false | false |
hotpodata/Twistris | app/src/main/java/com/hotpodata/twistris/data/TwistrisGame.kt | 1 | 13285 | package com.hotpodata.twistris.data
import android.graphics.Color
import android.os.Bundle
import android.text.TextUtils
import com.hotpodata.blocklib.Grid
import com.hotpodata.blocklib.GridHelper
import com.hotpodata.twistris.utils.TetrisFactory
import org.json.JSONArray
import org.json.JSONObject
import timber.log.Timber
import java.util.*
/**
* Created by jdrotos on 1/3/16.
*/
class TwistrisGame() {
val VERT_W = 8
val VERT_H = 16
val HORI_W = 12
val HORI_H = 8
val MAX_LEVEL = 10
val LEVEL_STEP = 6
var currentRowsDestroyed = 0
var currentScore = 0
var currentLevel = 1
var twistCount = 0
var gameIsOver = false
var boardVert: Grid
var boardHoriz: Grid
var activePiece: Grid
get() = horizPieces[horizPieces.size - 1].first
set(piece: Grid) {
horizPieces[horizPieces.size - 1] = Pair(piece, horizPieces[horizPieces.size - 1].second)
}
var activeXOffset: Int
get() = horizPieces[horizPieces.size - 1].second.first
set(offset: Int) {
horizPieces[horizPieces.size - 1] = Pair(horizPieces[horizPieces.size - 1].first, Pair(offset, horizPieces[horizPieces.size - 1].second.second))
}
var activeYOffset: Int
get() = horizPieces[horizPieces.size - 1].second.second
set(offset: Int) {
horizPieces[horizPieces.size - 1] = Pair(horizPieces[horizPieces.size - 1].first, Pair(horizPieces[horizPieces.size - 1].second.first, offset))
}
var upcomingPiece: Grid = TetrisFactory.randomPiece()
var horizPieces = ArrayList<Pair<Grid, Pair<Int, Int>>>()
init {
boardVert = Grid(VERT_W, VERT_H)
boardHoriz = Grid(HORI_W, HORI_H)
actionNextPiece()
}
constructor(source: TwistrisGame) : this() {
currentRowsDestroyed = source.currentRowsDestroyed
currentScore = source.currentScore
currentLevel = source.currentLevel
boardVert = GridHelper.copyGrid(source.boardVert)
boardHoriz = GridHelper.copyGrid(source.boardHoriz)
upcomingPiece = GridHelper.copyGrid(source.upcomingPiece)
horizPieces.clear()
for (item in source.horizPieces) {
horizPieces.add(Pair(GridHelper.copyGrid(item.first), Pair(item.second.first, item.second.second)))
}
}
fun peekMoveActiveUp(): Boolean {
return GridHelper.gridInBounds(boardHoriz, activePiece, activeXOffset, activeYOffset - 1) && !GridHelper.gridsCollide(boardHoriz, activePiece, activeXOffset, activeYOffset - 1)
}
fun actionMoveActiveUp(): Boolean {
if (peekMoveActiveUp()) {
activeYOffset--
return true
}
return false
}
fun peekMoveActiveDown(): Boolean {
return GridHelper.gridInBounds(boardHoriz, activePiece, activeXOffset, activeYOffset + 1) && !GridHelper.gridsCollide(boardHoriz, activePiece, activeXOffset, activeYOffset + 1)
}
fun actionMoveActiveDown(): Boolean {
if (peekMoveActiveDown()) {
activeYOffset++
return true
}
return false
}
fun peekMoveActiveLeft(): Boolean {
return GridHelper.gridInBounds(boardHoriz, activePiece, activeXOffset - 1, activeYOffset) && !GridHelper.gridsCollide(boardHoriz, activePiece, activeXOffset - 1, activeYOffset);
}
fun actionMoveActiveLeft(): Boolean {
if (peekMoveActiveLeft()) {
activeXOffset--
return true
}
return false
}
fun actionMoveActiveAllTheWayLeft(): Boolean {
var ret = false
while (actionMoveActiveLeft()) {
currentScore += 10
ret = true
}
return ret
}
fun actionRotate(left: Boolean): Boolean {
var rot = activePiece.rotate(left)
var xOff = activeXOffset
var yOff = activeYOffset
//Now we make sure the coordinates are ok with the board (since rotations next to the edge are ok)
while (xOff + rot.width > boardHoriz.width) {
xOff--
}
while (yOff + rot.height > boardHoriz.height) {
yOff--
}
//If we've got no collisions we're in great shape
if (!GridHelper.gridsCollide(boardHoriz, rot, xOff, yOff)) {
activeXOffset = xOff
activeYOffset = yOff
activePiece = rot
return true
} else {
return false
}
}
fun actionRotateActiveLeft(): Boolean {
return actionRotate(true)
}
fun actionRotateActiveRight(): Boolean {
return actionRotate(false)
}
fun actionTwistBoard() {
//The working board is twice as tall as the display board, so pieces can be added over the bounds
var workingBoard = Grid(boardVert.width, boardVert.height * 2)
GridHelper.addGrid(workingBoard, GridHelper.copyGrid(boardVert), 0, boardVert.height);
Timber.d("1 workingBoard:" + workingBoard.getPrintString(" - ", " * "))
//Move all of the pieces down
for (pieceAndCoords in horizPieces.reversed()) {
var coords = pieceAndCoords.second
if (coords != null) {
var rotated = pieceAndCoords.first.rotate(false)
var startX = boardHoriz.height - coords.second - rotated.width
var endY = 0
while (GridHelper.gridInBounds(workingBoard, rotated, startX, endY + 1) && !GridHelper.gridsCollide(workingBoard, rotated, startX, endY + 1)) {
endY++
}
GridHelper.addGrid(workingBoard, rotated, startX, endY)
}
}
//Figure out the shift values
var shifts = ArrayList<Int>()
var shiftVal = 0
for (i in workingBoard.height - 1 downTo 0) {
if (workingBoard.rowFull(i)) {
shifts.add(0, -1)
shiftVal++
} else {
shifts.add(0, shiftVal)
}
}
//Shift working board for realz
if (shiftVal > 0) {
for (i in shifts.size - 1 downTo 0) {
if (shifts[i] > 0) {
for (j in 0..workingBoard.width - 1) {
workingBoard.put(j, i + shifts[i], workingBoard.at(j, i))
}
}
}
}
horizPieces.clear()
boardHoriz.clear()
currentScore += (50 * shiftVal * shiftVal)
currentRowsDestroyed += shiftVal
currentLevel = currentRowsDestroyed / LEVEL_STEP + 1
gameIsOver = !workingBoard.rowEmpty(boardVert.height - 1)
twistCount++
boardVert = GridHelper.copyGridPortion(workingBoard, 0, boardVert.height, boardVert.width, workingBoard.height)
}
private fun randomWidePiece(): Grid {
var newPiece = TetrisFactory.randomPiece()
if (newPiece.height > newPiece.width) {
newPiece = newPiece.rotate(false)
}
return newPiece
}
fun actionNextPiece() {
//Commit the active piece to the board
if (horizPieces.size > 0) {
GridHelper.addGrid(boardHoriz, activePiece, activeXOffset, activeYOffset)
}
if (upcomingPiece == null) {
upcomingPiece = randomWidePiece()
}
var piece = upcomingPiece
var x = boardHoriz.width - piece.width
var y = (boardHoriz.height / 2f - piece.height / 2f).toInt()
horizPieces.add(Pair(piece, Pair(x, y)))
upcomingPiece = randomWidePiece()
}
fun gameNeedsTwist(): Boolean {
return !peekMoveActiveLeft() && horizPieces.size >= currentLevel
}
fun gameNeedsNextPiece(): Boolean {
return horizPieces.size == 0 || !peekMoveActiveLeft()
}
/**
* SERIALIZER
*/
object Serializer {
val JSON_KEY_ROWS_DESTROYED = "rowsDestroyed"
val JSON_KEY_SCORE = "score"
val JSON_KEY_LEVEL = "level"
val JSON_KEY_TWISTS = "twists"
val JSON_KEY_GAMEOVER = "gameover"
val JSON_KEY_VERTBOARD = "vertBoard"
val JSON_KEY_HORIZBOARD = "horizBoard"
val JSON_KEY_XOFF = "xOffset"
val JSON_KEY_YOFF = "yOffset"
val JSON_KEY_UPCOMING = "upcoming"
val JSON_KEY_HORIZ_PIECES = "horizPieces"
val JSON_KEY_HORIZ_PIECE_GRID = "horizPieceGrid"
val JSON_KEY_HORIZ_PIECE_X = "horizPieceX"
val JSON_KEY_HORIZ_PIECE_Y = "horizPieceY"
fun gameToJson(game: TwistrisGame): JSONObject {
var chainjson = JSONObject()
chainjson.put(JSON_KEY_ROWS_DESTROYED, game.currentRowsDestroyed)
chainjson.put(JSON_KEY_SCORE, game.currentScore)
chainjson.put(JSON_KEY_LEVEL, game.currentLevel)
chainjson.put(JSON_KEY_TWISTS, game.twistCount)
chainjson.put(JSON_KEY_GAMEOVER, game.gameIsOver)
chainjson.put(JSON_KEY_VERTBOARD, gridToJson(game.boardVert))
chainjson.put(JSON_KEY_HORIZBOARD, gridToJson(game.boardHoriz))
chainjson.put(JSON_KEY_XOFF, game.activeXOffset)
chainjson.put(JSON_KEY_YOFF, game.activeYOffset)
chainjson.put(JSON_KEY_UPCOMING, gridToJson(game.upcomingPiece))
var jsonArrHoriz = JSONArray()
for (p in game.horizPieces) {
var horiP = JSONObject()
horiP.put(JSON_KEY_HORIZ_PIECE_GRID, gridToJson(p.first))
horiP.put(JSON_KEY_HORIZ_PIECE_X, p.second.first)
horiP.put(JSON_KEY_HORIZ_PIECE_Y, p.second.second)
jsonArrHoriz.put(horiP)
}
chainjson.put(JSON_KEY_HORIZ_PIECES, jsonArrHoriz)
return chainjson
}
fun gameFromJson(gameJsonStr: String): TwistrisGame? {
try {
if (!TextUtils.isEmpty(gameJsonStr)) {
var game = TwistrisGame()
var gamejson = JSONObject(gameJsonStr)
game.currentRowsDestroyed =gamejson.getInt(JSON_KEY_ROWS_DESTROYED)
game.currentScore = gamejson.getInt(JSON_KEY_SCORE)
game.currentLevel = gamejson.getInt(JSON_KEY_LEVEL)
game.twistCount = gamejson.getInt(JSON_KEY_TWISTS)
game.gameIsOver = gamejson.getBoolean(JSON_KEY_GAMEOVER)
game.boardVert = gridFromJson(gamejson.getJSONObject(JSON_KEY_VERTBOARD))
game.boardHoriz = gridFromJson(gamejson.getJSONObject(JSON_KEY_HORIZBOARD))
game.activeXOffset = gamejson.getInt(JSON_KEY_XOFF)
game.activeYOffset = gamejson.getInt(JSON_KEY_YOFF)
game.upcomingPiece = gridFromJson(gamejson.getJSONObject(JSON_KEY_UPCOMING))
game.horizPieces.clear()
var horizPiecesJsonArr = gamejson.getJSONArray(JSON_KEY_HORIZ_PIECES)
for(i in 0..(horizPiecesJsonArr.length() - 1)){
var obj = horizPiecesJsonArr.getJSONObject(i)
var grid = gridFromJson(obj.getJSONObject(JSON_KEY_HORIZ_PIECE_GRID))
var x = obj.getInt(JSON_KEY_HORIZ_PIECE_X)
var y = obj.getInt(JSON_KEY_HORIZ_PIECE_Y)
game.horizPieces.add(Pair(grid,Pair(x,y)))
}
return game
}
} catch(ex: Exception) {
Timber.e(ex, "gameFromJson Fail")
}
return null
}
val JSONKEY_WIDTH = "WIDTH"
val JSONKEY_HEIGHT = "HEIGHT"
val JSONKEY_VALUES = "VALS"
val JSON_EMPTY_COLOR = Color.TRANSPARENT
fun gridToJson(grid: Grid): JSONObject {
var json = JSONObject()
json.put(JSONKEY_WIDTH, grid.width)
json.put(JSONKEY_HEIGHT, grid.height)
var vals = JSONArray()
for (i in 0..grid.width - 1) {
for (j in 0..grid.height - 1) {
vals.put((grid.at(i, j) as Int?) ?: JSON_EMPTY_COLOR)
}
}
json.put(JSONKEY_VALUES, vals)
return json
}
fun gridFromJson(json: JSONObject): Grid {
val w = json.getInt(JSONKEY_WIDTH)
val h = json.getInt(JSONKEY_HEIGHT)
var vals = json.getJSONArray(JSONKEY_VALUES)
var grid = Grid(w, h)
var valsInd = 0
for (i in 0..grid.width - 1) {
for (j in 0..grid.height - 1) {
grid.slots[i][j] = if (vals[valsInd] == JSON_EMPTY_COLOR) null else vals[valsInd]
valsInd++
}
}
return grid
}
val BUNDLE_KEY_GAME = "BUNDLE_KEY_GAME"
fun gameToBundle(game: TwistrisGame, bundle: Bundle = Bundle()): Bundle {
bundle.putString(BUNDLE_KEY_GAME, TwistrisGame.Serializer.gameToJson(game).toString())
return bundle
}
fun gameFromBundle(bundle: Bundle?): TwistrisGame? {
return bundle?.getString(BUNDLE_KEY_GAME)?.let {
TwistrisGame.Serializer.gameFromJson(it)
}
}
}
} | apache-2.0 | 30564b900ddb72a59536a4076ec2a078 | 34.908108 | 185 | 0.585548 | 4.471558 | false | false | false | false |
kittinunf/ReactiveAndroid | reactiveandroid-ui/src/main/kotlin/com/github/kittinunf/reactiveandroid/widget/SeekBarEvent.kt | 1 | 2835 | package com.github.kittinunf.reactiveandroid.widget
import android.widget.SeekBar
import com.github.kittinunf.reactiveandroid.ExtensionFieldDelegate
import com.github.kittinunf.reactiveandroid.subscription.AndroidMainThreadSubscription
import io.reactivex.Observable
//================================================================================
// Events
//================================================================================
data class SeekBarProgressChangeListener(val seekBar: SeekBar?, val progress: Int, val fromUser: Boolean)
fun SeekBar.rx_progressChanged(): Observable<SeekBarProgressChangeListener> {
return Observable.create { subscriber ->
_seekBarChange.onProgressChanged { seekBar, progress, fromUser ->
subscriber.onNext(SeekBarProgressChangeListener(seekBar, progress, fromUser))
}
subscriber.setDisposable(AndroidMainThreadSubscription {
setOnSeekBarChangeListener(null)
})
}
}
fun SeekBar.rx_startTrackingTouch(): Observable<SeekBar> {
return Observable.create { subscriber ->
_seekBarChange.onStartTrackingTouch {
if (it != null) subscriber.onNext(it)
}
subscriber.setDisposable(AndroidMainThreadSubscription {
setOnSeekBarChangeListener(null)
})
}
}
fun SeekBar.rx_stopTrackingTouch(): Observable<SeekBar> {
return Observable.create { subscriber ->
_seekBarChange.onStopTrackingTouch {
if (it != null) subscriber.onNext(it)
}
subscriber.setDisposable(AndroidMainThreadSubscription {
setOnSeekBarChangeListener(null)
})
}
}
private val SeekBar._seekBarChange: _SeekBar_OnSeekBarChangeListener
by ExtensionFieldDelegate({ _SeekBar_OnSeekBarChangeListener() }, { setOnSeekBarChangeListener(it) })
internal class _SeekBar_OnSeekBarChangeListener : SeekBar.OnSeekBarChangeListener {
var onProgressChanged: ((SeekBar?, Int, Boolean) -> Unit)? = null
var onStartTrackingTouch: ((SeekBar?) -> Unit)? = null
var onStopTrackingTouch: ((SeekBar?) -> Unit)? = null
fun onProgressChanged(listener: (SeekBar?, Int, Boolean) -> Unit) {
onProgressChanged = listener
}
override fun onProgressChanged(seekBar: SeekBar?, progress: Int, fromUser: Boolean) {
onProgressChanged?.invoke(seekBar, progress, fromUser)
}
fun onStartTrackingTouch(listener: (SeekBar?) -> Unit) {
onStartTrackingTouch = listener
}
override fun onStartTrackingTouch(seekBar: SeekBar?) {
onStartTrackingTouch?.invoke(seekBar)
}
fun onStopTrackingTouch(listener: (SeekBar?) -> Unit) {
onStopTrackingTouch = listener
}
override fun onStopTrackingTouch(seekBar: SeekBar?) {
onStopTrackingTouch?.invoke(seekBar)
}
}
| mit | 55a3a8362b3fcc98ab8840c5c0a7e6ae | 30.853933 | 109 | 0.665608 | 5.715726 | false | false | false | false |
zhengjiong/ZJ_KotlinStudy | src/main/kotlin/com/zj/example/kotlin/shengshiyuan/helloworld/29.HelloKotlin-对象表达式object.kt | 1 | 2427 | package com.zj.example.kotlin.shengshiyuan.helloworld
/**
*
* CreateTime: 18/3/5 13:56
* @author 郑炯
*/
/**
* 对象表达式: (object expression)
* Java当中匿名内部类在很多场景下都得到了大量使用
* Kotlin的对象表达式就是为了解决匿名内部类的一些缺陷而产生的.
*/
/**
* 1.匿名内部类是没有名字的类
* 2.匿名内部类一定是继承了某个父类,或是实现了某个接口(java), kotlin可以不实现接口或继承父类
* 3.Java运行时会将该匿名内部类当做它所实现的接口或是所继承的父类来看待.
*/
/*
对象表达式的格式:
object [:若干个父类型,中间用逗号分隔]{
}
中括号中的可以省略, 省略后就是没有继承任何类和任何接口的一个内部类
*/
interface MyInterface {
fun println(i: Int)
}
abstract class MyAbstractClass {
abstract val age: Int
abstract fun printMyAbstractClassInfo()
}
fun main(args: Array<String>) {
/**
* 对象表达式最终返回的其实是一个匿名内部类
*/
var myObject = object : MyInterface {
override fun println(i: Int) {
println("i的值是$i")
}
//可以定义其他方法
fun test() {
println("test")
}
}
myObject.println(100)
myObject.test()
println("-------------------")
/**
* 没有实现接口的对象表达式, 相当于是一个没有继承任何子类和实现任何接口的匿名内部类
*/
var myObject2 = object {
init {
println("init")
}
var myProperty = "p1"
fun myMethod() = "myMethod()"
}
println(myObject2.myProperty)
println(myObject2.myMethod())
println("-------------------")
/**
* 和java不同的是:
* java的匿名内部类只能实现一个接口或者继承一个类,
* kotlin中的对象表达式就可以实现多个接口或者1个父类+多个接口.
*/
var myObject3 = object : MyInterface, MyAbstractClass() {
override fun println(i: Int) {
println("i的值是$i")
}
override val age: Int
get() = 30
override fun printMyAbstractClassInfo() {
println("myAbstractClassInfo")
}
}
myObject3.println(99)
println(myObject3.age)
myObject3.printMyAbstractClassInfo()
} | mit | 527c177fc36f5c4fa915b12deaac5823 | 16.72549 | 61 | 0.579413 | 3.279492 | false | false | false | false |
coil-kt/coil | coil-base/src/main/java/coil/intercept/RealInterceptorChain.kt | 1 | 2069 | package coil.intercept
import coil.EventListener
import coil.request.ImageRequest
import coil.request.ImageResult
import coil.request.NullRequestData
import coil.size.Size
internal class RealInterceptorChain(
val initialRequest: ImageRequest,
val interceptors: List<Interceptor>,
val index: Int,
override val request: ImageRequest,
override val size: Size,
val eventListener: EventListener,
val isPlaceholderCached: Boolean,
) : Interceptor.Chain {
override fun withSize(size: Size) = copy(size = size)
override suspend fun proceed(request: ImageRequest): ImageResult {
if (index > 0) checkRequest(request, interceptors[index - 1])
val interceptor = interceptors[index]
val next = copy(index = index + 1, request = request)
val result = interceptor.intercept(next)
checkRequest(result.request, interceptor)
return result
}
private fun checkRequest(request: ImageRequest, interceptor: Interceptor) {
check(request.context === initialRequest.context) {
"Interceptor '$interceptor' cannot modify the request's context."
}
check(request.data !== NullRequestData) {
"Interceptor '$interceptor' cannot set the request's data to null."
}
check(request.target === initialRequest.target) {
"Interceptor '$interceptor' cannot modify the request's target."
}
check(request.lifecycle === initialRequest.lifecycle) {
"Interceptor '$interceptor' cannot modify the request's lifecycle."
}
check(request.sizeResolver === initialRequest.sizeResolver) {
"Interceptor '$interceptor' cannot modify the request's size resolver. " +
"Use `Interceptor.Chain.withSize` instead."
}
}
private fun copy(
index: Int = this.index,
request: ImageRequest = this.request,
size: Size = this.size,
) = RealInterceptorChain(initialRequest, interceptors, index, request, size, eventListener, isPlaceholderCached)
}
| apache-2.0 | 4067dad1e718c206014f89068a62595a | 37.314815 | 116 | 0.676655 | 4.937947 | false | false | false | false |
luxons/seven-wonders | sw-engine/src/test/kotlin/org/luxons/sevenwonders/engine/effects/ProductionIncreaseTest.kt | 1 | 2546 | package org.luxons.sevenwonders.engine.effects
import org.junit.experimental.theories.DataPoints
import org.junit.experimental.theories.Theories
import org.junit.experimental.theories.Theory
import org.junit.runner.RunWith
import org.luxons.sevenwonders.engine.SimplePlayer
import org.luxons.sevenwonders.engine.resources.resourcesOf
import org.luxons.sevenwonders.engine.test.fixedProduction
import org.luxons.sevenwonders.engine.test.testBoard
import org.luxons.sevenwonders.engine.test.testTable
import org.luxons.sevenwonders.model.resources.ResourceType
import kotlin.test.assertEquals
import kotlin.test.assertFalse
import kotlin.test.assertTrue
@RunWith(Theories::class)
class ProductionIncreaseTest {
@Theory
fun apply_boardContainsAddedResourceType(
initialType: ResourceType,
addedType: ResourceType,
extraType: ResourceType,
) {
val board = testBoard(initialType)
val effect = ProductionIncrease(fixedProduction(addedType), false)
effect.applyTo(board)
val resources = resourcesOf(initialType, addedType)
assertTrue(board.production.contains(resources))
assertFalse(board.publicProduction.contains(resources))
val moreResources = resourcesOf(initialType, addedType, extraType)
assertFalse(board.production.contains(moreResources))
assertFalse(board.publicProduction.contains(moreResources))
}
@Theory
fun apply_boardContainsAddedResourceType_sellable(
initialType: ResourceType,
addedType: ResourceType,
extraType: ResourceType,
) {
val board = testBoard(initialType)
val effect = ProductionIncrease(fixedProduction(addedType), true)
effect.applyTo(board)
val resources = resourcesOf(initialType, addedType)
assertTrue(board.production.contains(resources))
assertTrue(board.publicProduction.contains(resources))
val moreResources = resourcesOf(initialType, addedType, extraType)
assertFalse(board.production.contains(moreResources))
assertFalse(board.publicProduction.contains(moreResources))
}
@Theory
fun computePoints_isAlwaysZero(addedType: ResourceType) {
val effect = ProductionIncrease(fixedProduction(addedType), false)
val player = SimplePlayer(0, testTable(5))
assertEquals(0, effect.computePoints(player))
}
companion object {
@JvmStatic
@DataPoints
fun resourceTypes(): Array<ResourceType> = ResourceType.values()
}
}
| mit | a44d4bcbd82b1d71fbb23f338791a6a3 | 33.876712 | 74 | 0.742734 | 4.794727 | false | true | false | false |
MaibornWolff/codecharta | analysis/import/GitLogParser/src/main/kotlin/de/maibornwolff/codecharta/importer/gitlogparser/parser/VersionControlledFilesInGitProject.kt | 1 | 2428 | package de.maibornwolff.codecharta.importer.gitlogparser.parser
import de.maibornwolff.codecharta.importer.gitlogparser.input.VersionControlledFile
class VersionControlledFilesInGitProject(private val vcFList: MutableMap<String, VersionControlledFile>, private val filesInGitLog: List<String>) {
// TODO salts should not be part of filenames, change logic error
private fun removeSaltFromFilenames() {
vcFList.values
.forEach {
it.filename = it.filename.substringBefore("_\\0_")
}
}
private fun findDuplicates(): MutableMap<String, Set<String>> {
val occurrencesPerFilename = vcFList.values.groupingBy { it.filename }.eachCount()
val duplicateFilenames = occurrencesPerFilename.filterValues { it > 1 }
val trackingNamesPerFilename = mutableMapOf<String, Set<String>>()
duplicateFilenames.keys.forEach { element ->
trackingNamesPerFilename[element] = vcFList.keys.filter {
vcFList[it]?.filename == element
}.toSet()
}
return trackingNamesPerFilename
}
// We always keep deleted files until the end, because they might be re-added in a merge commit
// This might result in multiple files with the same filename being stored in VCF
// the following function tries to find the correct version to keep for later visualization, by accounting for flags and time of addition
private fun removeDuplicates(trackingNamesPerFilename: MutableMap<String, Set<String>>) {
trackingNamesPerFilename.keys.forEach { elem ->
var chooseElement = ""
trackingNamesPerFilename[elem]?.forEach {
if (!vcFList[it]?.isDeleted()!!) {
chooseElement = it
}
}
if (chooseElement == "") {
chooseElement = trackingNamesPerFilename[elem]?.last().toString()
}
trackingNamesPerFilename[elem]?.forEach {
if (it != chooseElement)
vcFList.remove(it)
}
}
}
fun getListOfVCFilesMatchingGitProject(): Set<VersionControlledFile> {
removeSaltFromFilenames()
val trackingNamesPerFilename = findDuplicates()
removeDuplicates(trackingNamesPerFilename)
return vcFList.values
.filter { filesInGitLog.contains(it.filename) }.toSet()
}
}
| bsd-3-clause | 06fe0012f3e62b4c7e8dee92d5b25613 | 39.466667 | 147 | 0.651565 | 5.480813 | false | false | false | false |
Quireg/AnotherMovieApp | app/src/main/java/com/anothermovieapp/repository/EntityDBMovieReview.kt | 1 | 1113 | /*
* Created by Arcturus Mengsk
* 2021.
*/
package com.anothermovieapp.repository
import androidx.room.ColumnInfo
import androidx.room.Entity
import org.json.JSONObject
@Entity(primaryKeys = ["reviewId"], tableName = "reviews")
data class EntityDBMovieReview(
@ColumnInfo(name = "id") var movieId: String,
@ColumnInfo(name = "reviewId") var reviewId: String,
@ColumnInfo(name = "author") var author: String,
@ColumnInfo(name = "content") var content: String
) {
companion object {
const val JSON_ID = "id"
const val JSON_PAGE = "page"
const val JSON_ARRAY_RESULTS = "results"
const val JSON_REVIEW_ID = "id"
const val JSON_AUTHOR = "author"
const val JSON_CONTENT = "content"
const val JSON_TOTAL_PAGES = "total_pages"
fun fromJSON(obj: JSONObject, movieId: String): EntityDBMovieReview {
return EntityDBMovieReview(
movieId,
obj.optString(JSON_REVIEW_ID),
obj.optString(JSON_AUTHOR),
obj.optString(JSON_CONTENT)
)
}
}
} | mit | 2cc2f8744abf19b9c33c5c560033e996 | 29.108108 | 77 | 0.621743 | 4.062044 | false | false | false | false |
Lennoard/HEBF | app/src/main/java/com/androidvip/hebf/services/LockScreenWork.kt | 1 | 2690 | package com.androidvip.hebf.services
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import androidx.work.*
import com.androidvip.hebf.receivers.UnlockReceiver
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import java.util.concurrent.TimeUnit
class LockScreenWork(context: Context, params: WorkerParameters): CoroutineWorker(context, params) {
override suspend fun doWork(): Result = withContext(Dispatchers.IO) {
unregisterReceiver(applicationContext)
return@withContext registerUnlockReceiver(applicationContext)
}
companion object {
private const val WORK_TAG = "LOCK_SCREEN_WORK_REQUEST"
var receiver: UnlockReceiver? = null
fun registerUnlockReceiver(context: Context): Result {
return runCatching {
receiver = UnlockReceiver()
IntentFilter(Intent.ACTION_SCREEN_OFF).apply {
addAction(Intent.ACTION_SCREEN_ON)
context.applicationContext.registerReceiver(receiver, this)
}
Result.success()
}.getOrDefault(Result.failure())
}
fun unregisterReceiver(context: Context) {
try {
if (receiver != null) {
context.applicationContext.unregisterReceiver(receiver)
}
} catch (e: Exception) {
e.printStackTrace()
} finally {
receiver = null
}
}
fun scheduleJobPeriodic(context: Context?) {
if (context == null) return
val constraints = Constraints.Builder()
.setRequiredNetworkType(NetworkType.NOT_REQUIRED)
.setRequiresCharging(false)
.build()
val request = PeriodicWorkRequest.Builder(
LockScreenWork::class.java,
PeriodicWorkRequest.MIN_PERIODIC_INTERVAL_MILLIS,
TimeUnit.MILLISECONDS,
PeriodicWorkRequest.MIN_PERIODIC_FLEX_MILLIS,
TimeUnit.MILLISECONDS
).setConstraints(constraints).build()
val workManager = WorkManager.getInstance(context.applicationContext)
workManager.enqueueUniquePeriodicWork(
WORK_TAG,
ExistingPeriodicWorkPolicy.KEEP,
request
)
}
fun cancelJob(context: Context) {
WorkManager.getInstance(context.applicationContext).cancelAllWorkByTag(WORK_TAG)
unregisterReceiver(context)
}
}
} | apache-2.0 | 4570cfd910880830c37b7f7659ade7d3 | 34.407895 | 100 | 0.605948 | 5.899123 | false | false | false | false |
houtengzhi/seventimer | app/src/main/java/com/latitude/seventimer/util/L.kt | 1 | 2447 | package com.latitude.seventimer.util
import android.util.Log
object L {
const val logSwitch = true
const val logLevel = 1
private val version = ""
private val LOG_MAXLENGTH = 2000
@JvmStatic
fun e(tag: String, msg: String) {
if (logLevel <= Log.ERROR || logSwitch) {
Log.e(version + tag, msg)
}
}
fun e(tag: String, format: String, vararg args: Any) {
e(tag, formatMessage(format, *args))
}
@JvmStatic
fun d(tag: String, msg: String) {
if (logLevel <= Log.DEBUG || logSwitch) {
Log.d(version + tag, msg)
}
}
@JvmStatic
fun d(tag: String, format: String, vararg args: Any) {
d(tag, formatMessage(format, *args))
}
@JvmStatic
fun w(tag: String, msg: String) {
if (logLevel <= Log.WARN || logSwitch) {
Log.w(version + tag, msg)
}
}
@JvmStatic
fun w(tag: String, format: String, vararg args: Any) {
w(tag, formatMessage(format, *args))
}
@JvmStatic
fun i(tag: String, msg: String) {
if (logLevel <= Log.INFO || logSwitch) {
Log.i(version + tag, msg)
}
}
@JvmStatic
fun i(tag: String, format: String, vararg args: Any) {
i(tag, formatMessage(format, *args))
}
@JvmStatic
fun v(tag: String, msg: String) {
if (logLevel <= Log.VERBOSE || logSwitch) {
Log.v(version + tag, msg)
}
}
@JvmStatic
fun v(tag: String, format: String, vararg args: Any) {
v(tag, formatMessage(format, *args))
}
@JvmStatic
fun LongString(tag: String, msg: String) {
if (logLevel <= Log.VERBOSE || logSwitch) {
val strLength = msg.length
var start = 0
var end = LOG_MAXLENGTH
for (i in 0..99) {
if (strLength > end) {
L.e(tag, i.toString() + ": " + msg.substring(start, end))
start = end
end = end + LOG_MAXLENGTH
} else {
L.e(tag, i.toString() + ": " + msg.substring(start, strLength))
break
}
}
}
}
fun formatMessage(message: String, vararg args: Any): String {
return String.format(message, *args)
}
}
| apache-2.0 | b88e06121f1de808f572933036b0cba6 | 23.757895 | 83 | 0.491214 | 4.00491 | false | false | false | false |
Subsets and Splits