repo_name
stringlengths 7
79
| path
stringlengths 8
206
| copies
stringclasses 36
values | size
stringlengths 2
6
| content
stringlengths 55
523k
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 7.18
99.5
| line_max
int64 16
979
| alpha_frac
float64 0.3
0.87
| ratio
float64 2.01
8.07
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
debop/debop4k | debop4k-units/src/main/kotlin/debop4k/units/Prefixes.kt | 1 | 1408 | /*
* Copyright (c) 2016. Sunghyouk Bae <[email protected]>
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package debop4k.units
/**
* 단위의 계수를 나타냅니다.
* @author debop [email protected]
*/
object Prefixes {
// Multiples
const final val DECA = 10.0
const final val HECTO = 1.0e2
const final val KILO = 1.0e3
const final val MEGA = 1.0e6
const final val GIGA = 1.0e9
const final val TERA = 1.0e12
const final val PETA = 1.0e15
const final val EXA = 1.0e18
const final val ZETTA = 1.0e21
const final val YOTTA = 1.0e24
// Fractions
const final val DECI = 1.0e-1
const final val CENTI = 1.0e-2
const final val MILLI = 1.0e-3
const final val MICRO = 1.0e-6
const final val PICO = 1.0e-9
const final val FEMTO = 1.0e-15
const final val ATTO = 1.0e-18
const final val ZEPTO = 1.0e-21
const final val YOCTO = 1.0e-24
} | apache-2.0 | 07a5b2a6783f3886465804ed44437451 | 28.510638 | 75 | 0.699856 | 3.09375 | false | false | false | false |
bobrofon/easysshfs | app/src/main/java/ru/nsu/bobrofon/easysshfs/mountpointlist/mountpoint/MountPointsArrayAdapter.kt | 1 | 1727 | // SPDX-License-Identifier: MIT
package ru.nsu.bobrofon.easysshfs.mountpointlist.mountpoint
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ArrayAdapter
import android.widget.Button
import android.widget.TextView
import com.topjohnwu.superuser.Shell
import ru.nsu.bobrofon.easysshfs.R
import ru.nsu.bobrofon.easysshfs.databinding.RowLayoutBinding
class MountPointsArrayAdapter(
context: Context,
private val values: List<MountPoint>,
private val shell: Shell
) : ArrayAdapter<MountPoint>(context, R.layout.row_layout, values) {
override fun getView(position: Int, convertView: View?, parent: ViewGroup): View {
val inflater = context.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater
val rowView = convertView ?: RowLayoutBinding.inflate(inflater, parent, false).root
val nameView = rowView.findViewById<TextView>(R.id.mpNameView)
val statusView = rowView.findViewById<TextView>(R.id.mpStatusView)
val mountButton = rowView.findViewById<Button>(R.id.mountButton)
val self = values[position]
nameView.text = self.visiblePointName
if (self.isMounted) {
statusView.text = context.getString(R.string.mounted)
mountButton.text = context.getString(R.string.umount)
mountButton.setOnClickListener { self.umount(shell, context) }
} else {
statusView.text = context.getString(R.string.not_mounted)
mountButton.text = context.getString(R.string.mount)
mountButton.setOnClickListener { self.mount(shell, context) }
}
return rowView
}
}
| mit | 6b20ea10cb1b5559944d22ebb3bbf4df | 36.543478 | 98 | 0.726694 | 4.044496 | false | false | false | false |
mopsalarm/Pr0 | app/src/main/java/com/pr0gramm/app/ui/fragments/pager/PostPagerFragment.kt | 1 | 11355 | package com.pr0gramm.app.ui.fragments.pager
import android.os.Bundle
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import androidx.fragment.app.commitNow
import androidx.lifecycle.Lifecycle
import androidx.viewpager.widget.ViewPager
import com.pr0gramm.app.R
import com.pr0gramm.app.Settings
import com.pr0gramm.app.api.pr0gramm.Api
import com.pr0gramm.app.databinding.FragmentPostPagerBinding
import com.pr0gramm.app.feed.Feed
import com.pr0gramm.app.feed.FeedFilter
import com.pr0gramm.app.feed.FeedItem
import com.pr0gramm.app.feed.FeedType
import com.pr0gramm.app.parcel.getParcelableOrNull
import com.pr0gramm.app.parcel.getParcelableOrThrow
import com.pr0gramm.app.ui.*
import com.pr0gramm.app.ui.ScrollHideToolbarListener.ToolbarActivity
import com.pr0gramm.app.ui.base.BaseFragment
import com.pr0gramm.app.ui.base.bindViews
import com.pr0gramm.app.ui.base.launchInViewScope
import com.pr0gramm.app.ui.fragments.CommentRef
import com.pr0gramm.app.ui.fragments.IdFragmentStatePagerAdapter
import com.pr0gramm.app.ui.fragments.PreviewInfoSource
import com.pr0gramm.app.ui.fragments.feed.FeedFragment
import com.pr0gramm.app.ui.fragments.post.PostFragment
import com.pr0gramm.app.util.arguments
import com.pr0gramm.app.util.observeChangeEx
/**
*/
class PostPagerFragment : BaseFragment("PostPagerFragment", R.layout.fragment_post_pager), FilterFragment, TitleFragment, PreviewInfoSource {
private val views by bindViews(FragmentPostPagerBinding::bind)
private val model by viewModels { savedState ->
// get the feed to show and setup a loader to load more data
val feed = requireArguments().getParcelableOrThrow<Feed.FeedParcel>(ARG_FEED).feed
val startItem = requireArguments().getParcelableOrThrow<FeedItem>(ARG_START_ITEM)
PostPagerViewModel(
savedState = PostPagerViewModel.SavedState(savedState, feed, startItem),
feedService = instance(),
)
}
private lateinit var adapter: PostAdapter
private var previewInfo: PreviewInfo? = null
private var latestActivePostFragment: PostFragment? = null
private var initialCommentRef: CommentRef? = null
private val fcb = object : FragmentManager.FragmentLifecycleCallbacks() {
override fun onFragmentResumed(fm: FragmentManager, f: Fragment) {
if (f is PostFragment && latestActivePostFragment !== f) {
latestActivePostFragment = f
updateTitle()
}
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
initialCommentRef = requireArguments().getParcelableOrNull(ARG_START_ITEM_COMMENT_REF)
// Listen for changes in fragments. We use this, because with the ViewPager2
// callbacks we don't have any access to the fragment, and we don't even know,
// when the fragment will be there and available.
childFragmentManager.registerFragmentLifecycleCallbacks(fcb, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
// create the adapter on the view
adapter = PostAdapter()
launchInViewScope {
model.state.collect { state ->
logger.debug { "Update state: $state" }
adapter.feed = state.feed
}
}
if (activity is ToolbarActivity) {
val activity = activity as ToolbarActivity
activity.scrollHideToolbarListener.reset()
views.pager.addOnPageChangeListener(object : ViewPager.OnPageChangeListener {
override fun onPageScrollStateChanged(state: Int) {
activity.scrollHideToolbarListener.reset()
latestActivePostFragment?.exitFullscreen()
}
override fun onPageSelected(position: Int) {
activateFragmentAt(position)
}
override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) {}
})
}
if (Settings.fancyScrollHorizontal) {
views.pager.setPageTransformer(false) { page: View, position: Float ->
val viewer = page.findViewWithTag<View>(PostFragment.ViewerTag)
if (viewer != null) {
viewer.translationX = -(position * page.width / 5.0f)
}
}
}
views.pager.adapter = adapter
views.pager.offscreenPageLimit = 1
// calculate index of the first item to show if this is the first
// time we show this fragment.
makeItemCurrent(model.currentItem)
}
private fun activateFragmentAt(position: Int) {
val fragment = adapter.getFragment(position)
if (fragment != null && fragment != latestActivePostFragment) {
childFragmentManager.commitNow(allowStateLoss = true) {
val previousFragment = latestActivePostFragment
if (previousFragment != null && previousFragment.isAdded) {
setMaxLifecycle(previousFragment, Lifecycle.State.STARTED)
}
setMaxLifecycle(fragment, Lifecycle.State.RESUMED)
}
}
}
override fun onViewStateRestored(savedInstanceState: Bundle?) {
super.onViewStateRestored(savedInstanceState)
// if we've restored only a subset of the items, the index will be out of range.
// we now need to restore it based on the item id.
if (adapter.feed.getOrNull(views.pager.currentItem)?.id != model.currentItem.id) {
logger.debug { "Going to restore view position in onViewStateRestored" }
makeItemCurrent(model.currentItem)
}
}
private fun updateTitle() {
val activity = activity as? MainActivity ?: return
activity.updateActionbarTitle()
}
override fun onStop() {
val target = targetFragment as? FeedFragment
// merge the updated feed back into our parent fragment.
val feed = model.state.value.feed
if (target != null && model.currentItem.id in feed) {
target.updateFeedItemTarget(feed, model.currentItem)
}
super.onStop()
}
private fun makeItemCurrent(item: FeedItem) {
val index = adapter.feed.indexById(item.id) ?: 0
if (views.pager.currentItem != index) {
logger.info { "Move pager to item ${item.id} at index: $index" }
views.pager.setCurrentItem(index, false)
}
}
override fun previewInfoFor(item: FeedItem): PreviewInfo? {
return previewInfo?.takeIf { it.itemId == item.id }
}
/**
* Returns the feed filter for this fragment.
*/
override val currentFilter: FeedFilter
get() = model.state.value.feed.filter
override val title: TitleFragment.Title?
get() = buildFragmentTitle()
private fun buildFragmentTitle(): TitleFragment.Title? {
val titleOverride = requireArguments().getString(ARG_TITLE)
if (Settings.useTopTagAsTitle) {
// fetch title from the current active post fragment
var title = latestActivePostFragment?.title
if (titleOverride != null) {
// if the caller gave us a more specific title, we'll use that one.
title = title?.copy(title = titleOverride) ?: TitleFragment.Title(titleOverride)
}
return title
} else {
// build one from the current filter
val context = this.context ?: return null
return FeedFilterFormatter.toTitle(context, currentFilter)
}
}
fun onTagClicked(tag: Api.Tag) {
val handler = activity as MainActionHandler
handler.onFeedFilterSelected(currentFilter.basicWithTags(tag.text))
}
fun onUsernameClicked(username: String) {
// always show all uploads of a user.
val newFilter = currentFilter
.withFeedType(FeedType.NEW)
.basicWithUser(username)
(activity as MainActionHandler).onFeedFilterSelected(newFilter)
}
/**
* Sets the pixels that should be used in the transition.
*/
fun setPreviewInfo(previewInfo: PreviewInfo) {
this.previewInfo = previewInfo
}
private inner class PostAdapter
: IdFragmentStatePagerAdapter(childFragmentManager) {
var feed: Feed by observeChangeEx(Feed()) { oldValue, newValue ->
if (oldValue != newValue) {
notifyDataSetChanged()
}
}
override fun setPrimaryItem(container: ViewGroup, position: Int, `object`: Any) {
super.setPrimaryItem(container, position, `object`)
val currentItemIndex = views.pager.currentItem
val currentItem = feed.getOrNull(currentItemIndex)
logger.debug { "setPrimaryItem($currentItemIndex, ${currentItem?.id})" }
if (currentItem != null) {
// item was updated, make it the new current one.
model.currentItem = currentItem
}
}
override fun getItem(position: Int): Fragment {
when {
position > feed.size - 12 -> {
logger.debug { "Requested pos=$position, load next page" }
model.triggerLoadNext()
}
position < 12 -> {
logger.debug { "Requested pos=$position, load prev page" }
model.triggerLoadPrev()
}
}
// build a new fragment from the given item.
val capped = position.coerceIn(0, feed.size - 1)
val item = feed[capped]
// initialize with reference to comment
val initialCommentRef = initialCommentRef
if (initialCommentRef?.itemId == item.id) {
[email protected] = null
return PostFragment.newInstance(item, initialCommentRef)
}
return PostFragment.newInstance(item)
}
override fun getCount(): Int {
return feed.size
}
override fun getItemPosition(`object`: Any): Int {
val item = (`object` as PostFragment).feedItem
return feed.indexById(item.id) ?: POSITION_NONE
}
override fun getItemId(position: Int): Long {
return feed[position].id
}
}
companion object {
private const val ARG_FEED = "PP.feed"
private const val ARG_TITLE = "PP.title"
private const val ARG_START_ITEM = "PP.startItem"
private const val ARG_START_ITEM_COMMENT_REF = "PP.startItemComment"
fun newInstance(feed: Feed, idx: Int, commentRef: CommentRef?, fragmentTitle: String?): PostPagerFragment {
return PostPagerFragment().arguments {
putParcelable(ARG_FEED, feed.parcelAround(idx))
putParcelable(ARG_START_ITEM, feed[idx])
putParcelable(ARG_START_ITEM_COMMENT_REF, commentRef)
putString(ARG_TITLE, fragmentTitle)
}
}
}
}
| mit | 44ac178279c85e3a969825da9bbdd030 | 35.747573 | 141 | 0.639542 | 4.793162 | false | false | false | false |
bravelocation/yeltzland-android | app/src/main/java/com/bravelocation/yeltzlandnew/widget/YeltzlandGlanceWidget.kt | 1 | 4084 | package com.bravelocation.yeltzlandnew.widget
import android.appwidget.AppWidgetManager
import android.content.Context
import android.content.Intent
import android.util.Log
import androidx.compose.runtime.Composable
import androidx.datastore.preferences.core.Preferences
import androidx.datastore.preferences.core.longPreferencesKey
import androidx.glance.appwidget.GlanceAppWidget
import androidx.glance.appwidget.GlanceAppWidgetManager
import androidx.glance.appwidget.GlanceAppWidgetReceiver
import androidx.glance.appwidget.state.updateAppWidgetState
import androidx.glance.currentState
import androidx.glance.state.GlanceStateDefinition
import androidx.glance.state.PreferencesGlanceStateDefinition
import com.bravelocation.yeltzlandnew.dataproviders.TimelineManager
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.launch
import java.util.*
class YeltzlandGlanceWidget : GlanceAppWidget() {
override val stateDefinition: GlanceStateDefinition<*> = PreferencesGlanceStateDefinition
@Composable
override fun Content() {
Log.d("YeltzlandGlanceWidget", "Composing widget ...")
val prefs = currentState<Preferences>()
val lastUpdatedDate = prefs[YeltzlandGlanceWidgetReceiver.lastUpdatedDate]
val timelineEntries = TimelineManager.instance.timelineEntries()
if (TimelineManager.instance.endOfSeason()) {
WidgetSimpleTextView(title = "END OF SEASON", body = "Normal service will be resumed next season!")
} else if (timelineEntries.isEmpty()) {
WidgetSimpleTextView(title = "YELTZLAND", body = "No data available")
} else {
WidgetFixtureView(match = timelineEntries[0])
}
}
companion object {
fun updateAllWidgets(context: Context) {
Log.d("YeltzlandGlanceWidget", "Updating all widgets from static updateAllWidgets() ...")
// Broadcast an update message to the receiver
val intent = Intent(context, YeltzlandGlanceWidgetReceiver::class.java).apply {
action = "updateAction"
}
context.sendBroadcast(intent)
}
}
}
class YeltzlandGlanceWidgetReceiver : GlanceAppWidgetReceiver() {
private val coroutineScope = MainScope()
override val glanceAppWidget: GlanceAppWidget = YeltzlandGlanceWidget()
override fun onReceive(context: Context, intent: Intent) {
Log.d("YeltzlandWidget", "In onReceive for " + intent.action)
updateWidgetData(context)
super.onReceive(context, intent)
}
override fun onEnabled(context: Context) {
Log.d("YeltzlandGlanceWidget", "In onEnabled ...")
updateWidgetData(context)
super.onEnabled(context)
}
override fun onUpdate(
context: Context,
appWidgetManager: AppWidgetManager,
appWidgetIds: IntArray
) {
Log.d("YeltzlandGlanceWidget", "In onUpdate ...")
updateWidgetData(context)
super.onUpdate(context, appWidgetManager, appWidgetIds)
}
private fun updateWidgetData(context: Context?) {
Log.d("YeltzlandGlanceWidget", "Updating widget data ...")
// Update the timeline data
context?.let {
TimelineManager.instance.fetchLatestData(context) {
coroutineScope.launch {
// Update the widget state with the latest time
val glanceId = GlanceAppWidgetManager(context).getGlanceIds(YeltzlandGlanceWidget::class.java).firstOrNull()
glanceId?.let {
updateAppWidgetState(context, PreferencesGlanceStateDefinition, it) { pref ->
pref.toMutablePreferences().apply {
this[lastUpdatedDate] = Date().time
}
}
glanceAppWidget.update(context, it)
}
}
}
}
}
companion object {
val lastUpdatedDate = longPreferencesKey("lastUpdatedDate")
}
} | mit | 1c18f0fcf55ee15e000a138a6c98dabd | 35.150442 | 128 | 0.671645 | 5.229193 | false | false | false | false |
GeoffreyMetais/vlc-android | application/vlc-android/test/org/videolan/vlc/util/ModelsHelperTest.kt | 1 | 6085 | package org.videolan.vlc.util
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.ObsoleteCoroutinesApi
import org.junit.Assert.assertEquals
import org.junit.Test
import org.videolan.medialibrary.MLServiceLocator
import org.videolan.medialibrary.interfaces.Medialibrary
import org.videolan.medialibrary.stubs.StubDataSource
import org.videolan.vlc.BaseTest
import org.videolan.vlc.util.ModelsHelper.getHeader
@ExperimentalCoroutinesApi
@ObsoleteCoroutinesApi
class ModelsHelperTest : BaseTest() {
val dataSource: StubDataSource = StubDataSource.getInstance()
override fun beforeTest() {
super.beforeTest()
dataSource.resetData()
}
@Test
fun withDefaultSortingAndPreviousItemIsNullAndCurrentItemHasNoTitle_headerShouldBeSpecial() {
val item = dataSource.createFolder("")
assertEquals("#", getHeader(context, Medialibrary.SORT_DEFAULT, item, null))
}
@Test
fun withDefaultSortingAndPreviousItemAndCurrentItemHaveSameInitials_headerShouldBeNull() {
val item = dataSource.createFolder("abc")
val aboveItem = dataSource.createFolder("Adef")
assertEquals(null, getHeader(context, Medialibrary.SORT_DEFAULT, item, aboveItem))
}
@Test
fun withDefaultSortingAndPreviousItemIsNullAndCurrentItemStartsWithNumber_headerShouldBeSpecial() {
val item = dataSource.createFolder("9ab")
assertEquals("#", getHeader(context, Medialibrary.SORT_DEFAULT, item, null))
}
@Test
fun withDefaultSortingAndPreviousItemAndCurrentItemHaveDifferentInitials_headerShouldBeTheCurrentInitials() {
val item = dataSource.createFolder("abc")
val aboveItem = dataSource.createFolder("def")
assertEquals("A", getHeader(context, Medialibrary.SORT_DEFAULT, item, aboveItem))
}
@Test
fun withDefaultSortingAndPreviousItemAndCurrentItemStartWithDifferentNumber_headerShouldBeNull() {
val item = dataSource.createFolder("91c")
val aboveItem = dataSource.createFolder("7sc")
assertEquals(null, getHeader(context, Medialibrary.SORT_DEFAULT, item, aboveItem))
}
@Test
fun withDurationSortingAndPreviousItemIsNullAndCurrentItemIsZeroDuration_headerShouldBePlaceholder() {
val item = MLServiceLocator.getAbstractAlbum(dataSource.uuid, "Abc", 2018, "Artwork", "Dummy", 9, 1, 0)
assertEquals("-", getHeader(context, Medialibrary.SORT_DURATION, item, null))
}
@Test
fun withDurationSortingAndPreviousItemIsNullAndCurrentItemIsFolder_headerShouldBePlaceholder() {
val item = dataSource.createFolder("abc")
assertEquals("-", getHeader(context, Medialibrary.SORT_DURATION, item, null))
}
@Test
fun withDurationSortingAndPreviousItemIsNullAndCurrentItemIsAlbum_headerShouldBeLengthToCategory() {
val item = MLServiceLocator.getAbstractAlbum(dataSource.uuid, "Abc", 2018, "Artwork", "Dummy", 9, 1, 48000)
assertEquals(item.duration.lengthToCategory(), getHeader(context, Medialibrary.SORT_DURATION, item, null))
}
@Test
fun withDurationSortingAndPreviousItemAndCurrentItemAreBothFolder_headerShouldBeNull() {
val item = dataSource.createFolder("abc")
val aboveItem = dataSource.createFolder("cyz")
assertEquals(null, getHeader(context, Medialibrary.SORT_DURATION, item, aboveItem))
}
@Test
fun withDurationSortingAndPreviousItemAndCurrentItemAreBothAlbumLessThanMinute_headerShouldBeNull() {
val item = MLServiceLocator.getAbstractAlbum(dataSource.uuid, "Abc", 2018, "Artwork", "Dummy", 9, 1, 48000)
val aboveItem = MLServiceLocator.getAbstractAlbum(dataSource.uuid, "Abc", 2018, "Artwork", "Dummy", 9, 1, 51000)
assertEquals(null, getHeader(context, Medialibrary.SORT_DURATION, item, aboveItem))
}
@Test
fun withReleaseDateSortingAndPreviousItemIsNullAndCurrentItemIsFolder_headerShouldBeSpecial() {
val item = dataSource.createFolder("test")
assertEquals("-", getHeader(context, Medialibrary.SORT_RELEASEDATE, item, null))
}
@Test
fun withReleaseDateSortingAndPreviousItemIsNullAndCurrentItemIsAlbumWithNoDate_headerShouldBeSpecial() {
val item = MLServiceLocator.getAbstractAlbum(dataSource.uuid, "Abc", 0, "Artwork", "Dummy", 9, 1, 0)
assertEquals("-", getHeader(context, Medialibrary.SORT_RELEASEDATE, item, null))
}
@Test
fun withReleaseDateSortingAndPreviousItemIsNullAndCurrentItemIsAlbumWith2019Date_headerShouldBe2019() {
val item = MLServiceLocator.getAbstractAlbum(dataSource.uuid, "Abc", 2019, "Artwork", "Dummy", 9, 1, 0)
assertEquals("2019", getHeader(context, Medialibrary.SORT_RELEASEDATE, item, null))
}
@Test
fun withReleaseDateSortingAndPreviousItemAndCurrentItemAreAlbumWithNoDate_headerShouldBeNull() {
val item = MLServiceLocator.getAbstractAlbum(dataSource.uuid, "Abc", 0, "Artwork", "Dummy", 9, 1, 0)
val aboveItem = MLServiceLocator.getAbstractAlbum(dataSource.uuid, "dEF", 0, "Artwork", "Dummy", 9, 1, 0)
assertEquals(null, getHeader(context, Medialibrary.SORT_RELEASEDATE, item, aboveItem))
}
@Test
fun withReleaseDateSortingAndPreviousItemAndCurrentItemAreAlbumWithSameDate_headerShouldBeNull() {
val item = MLServiceLocator.getAbstractAlbum(dataSource.uuid, "Abc", 2019, "Artwork", "Dummy", 9, 1, 0)
val aboveItem = MLServiceLocator.getAbstractAlbum(dataSource.uuid, "dEF", 2019, "Artwork", "Dummy", 9, 1, 0)
assertEquals(null, getHeader(context, Medialibrary.SORT_RELEASEDATE, item, aboveItem))
}
@Test
fun withReleaseDateSortingAndPreviousItemIsAlbumWith2020DateAndCurrentItemIsAlbumWith2019Date_headerShouldBe2019() {
val item = MLServiceLocator.getAbstractAlbum(dataSource.uuid, "Abc", 2019, "Artwork", "Dummy", 9, 1, 0)
val aboveItem = MLServiceLocator.getAbstractAlbum(dataSource.uuid, "dEF", 2020, "Artwork", "Dummy", 9, 1, 0)
assertEquals("2019", getHeader(context, Medialibrary.SORT_RELEASEDATE, item, aboveItem))
}
} | gpl-2.0 | eaab3782b2decd61fec4007ac6923f0f | 47.301587 | 120 | 0.743139 | 4.451353 | false | true | false | false |
schaal/ocreader | app/src/main/java/email/schaal/ocreader/database/RealmViewModel.kt | 1 | 2734 | /*
* Copyright © 2020. Daniel Schaal <[email protected]>
*
* This file is part of ocreader.
*
* ocreader 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.
*
* ocreader 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 Foobar. If not, see <http://www.gnu.org/licenses/>.
*/
package email.schaal.ocreader.database
import android.util.Log
import androidx.lifecycle.ViewModel
import email.schaal.ocreader.database.model.Item
import email.schaal.ocreader.database.model.Item.Companion.UNREAD
import io.realm.Realm
import io.realm.exceptions.RealmException
import io.realm.kotlin.where
open class RealmViewModel : ViewModel() {
protected val realm: Realm by lazy { Realm.getDefaultInstance() }
override fun onCleared() {
Log.d(TAG, "onCleared called in ${this::class.simpleName}")
realm.close()
super.onCleared()
}
fun setItemUnread(unread: Boolean, vararg items: Item?) {
realm.executeTransaction {
try {
for (item in items.filterNotNull()) { /* If the item has a fingerprint, mark all items with the same fingerprint
as read
*/
if (item.fingerprint == null) {
item.unread = unread
} else {
val sameItems = it.where<Item>()
.equalTo(Item::fingerprint.name, item.fingerprint)
.equalTo(UNREAD, !unread)
.findAll()
for (sameItem in sameItems) {
sameItem.unread = unread
}
}
}
} catch (e: RealmException) {
Log.e(TAG, "Failed to set item as unread", e)
}
}
}
fun setItemStarred(starred: Boolean, vararg items: Item?) {
realm.executeTransaction {
try {
for (item in items.filterNotNull()) {
item.starred = starred
}
} catch (e: RealmException) {
Log.e(TAG, "Failed to set item as starred", e)
}
}
}
companion object {
const val TAG = "RealmViewModel"
}
} | gpl-3.0 | 2707c8308a14ef4ee46b376aab9241cb | 34.051282 | 128 | 0.574094 | 4.728374 | false | false | false | false |
didi/DoraemonKit | Android/app/src/main/java/com/didichuxing/doraemondemo/WebViewX5Activity.kt | 1 | 3544 | package com.didichuxing.doraemondemo
import android.annotation.SuppressLint
import android.os.Build
import android.os.Bundle
import androidx.annotation.RequiresApi
import androidx.appcompat.app.AppCompatActivity
import com.tencent.smtt.export.external.interfaces.ConsoleMessage
import com.tencent.smtt.export.external.interfaces.WebResourceRequest
import com.tencent.smtt.export.external.interfaces.WebResourceResponse
import com.tencent.smtt.sdk.WebChromeClient
import com.tencent.smtt.sdk.WebSettings
import com.tencent.smtt.sdk.WebView
import com.tencent.smtt.sdk.WebViewClient
/**
* Created by jintai on 2018/11/13.
*/
class WebViewX5Activity : AppCompatActivity() {
val TAG = "WebViewActivity"
lateinit var mWebView: WebView
val url = "https://jtsky.gitee.io/dokit-mock/index.html"
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_x5_webview)
mWebView = findViewById<WebView>(R.id.x5_web_view)
initWebView(mWebView)
mWebView.loadUrl(url)
}
@SuppressLint("JavascriptInterface")
private fun initWebView(webView: WebView) {
val webSettings: WebSettings = webView.settings
webSettings.pluginState = WebSettings.PluginState.ON
webSettings.javaScriptEnabled = true
webSettings.allowFileAccess = false
webSettings.loadsImagesAutomatically = true
webSettings.useWideViewPort = true
webSettings.builtInZoomControls = false
webSettings.defaultTextEncodingName = "UTF-8"
webSettings.domStorageEnabled = true
webSettings.cacheMode = WebSettings.LOAD_DEFAULT
webSettings.javaScriptCanOpenWindowsAutomatically = false
webSettings.setAllowFileAccessFromFileURLs(true)
webSettings.setAllowUniversalAccessFromFileURLs(true)
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR2) {
webSettings.setRenderPriority(WebSettings.RenderPriority.HIGH)
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
WebView.setWebContentsDebuggingEnabled(true)
}
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.GINGERBREAD_MR1 && Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR1) {
webView.removeJavascriptInterface("searchBoxJavaBridge_")
webView.removeJavascriptInterface("accessibilityTraversal")
webView.removeJavascriptInterface("accessibility")
}
webView.webViewClient = object : WebViewClient() {
override fun shouldOverrideUrlLoading(view: WebView, url: String): Boolean {
view.loadUrl(url)
return true
}
@RequiresApi(Build.VERSION_CODES.LOLLIPOP)
override fun shouldInterceptRequest(
view: WebView?,
request: WebResourceRequest?
): WebResourceResponse? {
return super.shouldInterceptRequest(view, request)
}
}
webView.webChromeClient = object : WebChromeClient() {
override fun onConsoleMessage(consoleMessage: ConsoleMessage?): Boolean {
//LogHelper.i(TAG, "consoleMessage===>${consoleMessage?.message()}")
return super.onConsoleMessage(consoleMessage)
}
}
}
override fun onBackPressed() {
if (mWebView.canGoBack()) {
mWebView.goBack()
} else {
super.onBackPressed()
}
}
} | apache-2.0 | 5f7e495d583d4fea9e255d40f8a79d62 | 37.11828 | 136 | 0.685948 | 4.874828 | false | false | false | false |
michaelgallacher/intellij-community | java/idea-ui/src/com/intellij/codeInsight/daemon/impl/LibrarySourceNotificationProvider.kt | 6 | 4696 | /*
* Copyright 2000-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.codeInsight.daemon.impl
import com.intellij.ProjectTopics
import com.intellij.diff.DiffContentFactory
import com.intellij.diff.DiffManager
import com.intellij.diff.requests.SimpleDiffRequest
import com.intellij.openapi.fileEditor.FileEditor
import com.intellij.openapi.fileEditor.OpenFileDescriptor
import com.intellij.openapi.fileTypes.LanguageFileType
import com.intellij.openapi.project.Project
import com.intellij.openapi.project.ProjectBundle
import com.intellij.openapi.roots.ModuleRootAdapter
import com.intellij.openapi.roots.ModuleRootEvent
import com.intellij.openapi.roots.ProjectRootManager
import com.intellij.openapi.util.Key
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.psi.*
import com.intellij.psi.impl.source.PsiExtensibleClass
import com.intellij.ui.EditorNotificationPanel
import com.intellij.ui.EditorNotifications
import com.intellij.ui.LightColors
import java.awt.Color
class LibrarySourceNotificationProvider(private val project: Project, notifications: EditorNotifications) :
EditorNotifications.Provider<EditorNotificationPanel>() {
private companion object {
private val KEY = Key.create<EditorNotificationPanel>("library.source.mismatch.panel")
private val ANDROID_SDK_PATTERN = ".*/platforms/android-\\d+/android.jar!/.*".toRegex()
}
init {
project.messageBus.connect(project).subscribe(ProjectTopics.PROJECT_ROOTS, object : ModuleRootAdapter() {
override fun rootsChanged(event: ModuleRootEvent) = notifications.updateAllNotifications()
})
}
override fun getKey(): Key<EditorNotificationPanel> = KEY
override fun createNotificationPanel(file: VirtualFile, fileEditor: FileEditor): EditorNotificationPanel? {
if (file.fileType is LanguageFileType && ProjectRootManager.getInstance(project).fileIndex.isInLibrarySource(file)) {
val psiFile = PsiManager.getInstance(project).findFile(file)
if (psiFile is PsiJavaFile) {
val offender = psiFile.classes.find { differs(it) }
if (offender != null) {
val clsFile = offender.originalElement.containingFile?.virtualFile
if (clsFile != null && !clsFile.path.matches(ANDROID_SDK_PATTERN)) {
val panel = ColoredNotificationPanel(LightColors.RED)
panel.setText(ProjectBundle.message("library.source.mismatch", offender.name))
panel.createActionLabel(ProjectBundle.message("library.source.open.class"), {
OpenFileDescriptor(project, clsFile, -1).navigate(true)
})
panel.createActionLabel(ProjectBundle.message("library.source.show.diff"), {
val cf = DiffContentFactory.getInstance()
val request = SimpleDiffRequest(null, cf.create(project, clsFile), cf.create(project, file), clsFile.path, file.path)
DiffManager.getInstance().showDiff(project, request)
})
return panel
}
}
}
}
return null
}
private fun differs(clazz: PsiClass): Boolean {
val binary = clazz.originalElement
return binary !== clazz &&
binary is PsiClass &&
(differs(fields(clazz), fields(binary)) || differs(methods(clazz), methods(binary)) || differs(inners(clazz), inners(binary)))
}
private fun differs(list1: List<PsiMember>, list2: List<PsiMember>): Boolean =
list1.size != list2.size || list1.map { it.name ?: "" }.sorted() != list2.map { it.name ?: "" }.sorted()
private fun fields(clazz: PsiClass) = if (clazz is PsiExtensibleClass) clazz.ownFields else clazz.fields.asList()
private fun methods(clazz: PsiClass): List<PsiMethod> =
(if (clazz is PsiExtensibleClass) clazz.ownMethods else clazz.methods.asList())
.filter { !(it.isConstructor && it.parameterList.parametersCount == 0) }
private fun inners(clazz: PsiClass) = if (clazz is PsiExtensibleClass) clazz.ownInnerClasses else clazz.innerClasses.asList()
}
private class ColoredNotificationPanel(private val color: Color?) : EditorNotificationPanel() {
override fun getBackground(): Color? = color ?: super.getBackground()
} | apache-2.0 | a9cbd374d2aaa39c91abb96bcfd9d6c4 | 45.50495 | 134 | 0.736797 | 4.463878 | false | false | false | false |
Light-Team/ModPE-IDE-Source | data/src/main/kotlin/com/brackeys/ui/data/utils/FileSorter.kt | 1 | 1698 | /*
* Copyright 2021 Brackeys IDE contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.brackeys.ui.data.utils
import com.brackeys.ui.filesystem.base.model.FileModel
import kotlin.Comparator
object FileSorter {
const val SORT_BY_NAME = 0
const val SORT_BY_SIZE = 1
const val SORT_BY_DATE = 2
private val fileNameComparator: Comparator<in FileModel>
get() = Comparator { first, second ->
first.name.compareTo(second.name, ignoreCase = true)
}
private val fileSizeComparator: Comparator<in FileModel>
get() = Comparator { first, second ->
first.size.compareTo(second.size)
}
private val fileDateComparator: Comparator<in FileModel>
get() = Comparator { first, second ->
first.lastModified.compareTo(second.lastModified)
}
fun getComparator(sortMode: Int): Comparator<in FileModel> {
return when (sortMode) {
SORT_BY_NAME -> fileNameComparator
SORT_BY_SIZE -> fileSizeComparator
SORT_BY_DATE -> fileDateComparator
else -> throw IllegalArgumentException("Unknown sort type")
}
}
} | apache-2.0 | dd9ed35d4ff82f7aea13b5052e6fbc2a | 32.313725 | 75 | 0.679623 | 4.421875 | false | false | false | false |
adrcotfas/Goodtime | app/src/main/java/com/apps/adrcotfas/goodtime/util/VibrationPatterns.kt | 1 | 1177 | package com.apps.adrcotfas.goodtime.util
object VibrationPatterns {
private val NONE = longArrayOf()
private val SOFT = longArrayOf(0, 50, 50, 50, 50, 50)
private val STRONG = longArrayOf(0, 500, 500, 500)
private const val dot = 150
private const val dash = 375
private const val short_gap = 150
private const val medium_gap = 375
private val SOS_PATTERN = longArrayOf(
0,
dot.toLong(), short_gap.toLong(), dot.toLong(), short_gap.toLong(), dot.toLong(),
medium_gap.toLong(),
dash.toLong(), short_gap.toLong(), dash.toLong(), short_gap.toLong(), dash.toLong(),
medium_gap.toLong(),
dot.toLong(), short_gap.toLong(), dot.toLong(), short_gap.toLong(), dot
.toLong()
)
private const val beat = 250
private const val interbeat = 100
private const val between_beat_pairs = 700
private val HEARTBEAT_PATTERN = longArrayOf(
0,
beat.toLong(), interbeat.toLong(), beat.toLong(),
between_beat_pairs.toLong(),
beat.toLong(), interbeat.toLong(), beat.toLong()
)
val LIST = arrayOf(NONE, SOFT, STRONG, SOS_PATTERN, HEARTBEAT_PATTERN)
} | apache-2.0 | f370af09f718f9cfd6e82b641875daf3 | 37 | 92 | 0.636364 | 3.923333 | false | false | false | false |
lambdasoup/watchlater | app/src/androidTest/java/com/lambdasoup/watchlater/test/AddActivityTest.kt | 1 | 6426 | /*
* Copyright (c) 2015 - 2022
*
* Maximilian Hille <[email protected]>
* Juliane Lehmann <[email protected]>
*
* This file is part of Watch Later.
*
* Watch Later 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.
*
* Watch Later 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 Watch Later. If not, see <http://www.gnu.org/licenses/>.
*/
package com.lambdasoup.watchlater.test
import android.accounts.Account
import android.accounts.AccountManager
import android.accounts.AccountManagerFuture
import android.app.Activity
import android.app.Instrumentation
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import androidx.compose.ui.test.junit4.createEmptyComposeRule
import androidx.compose.ui.test.onNodeWithText
import androidx.compose.ui.test.performClick
import androidx.test.core.app.ActivityScenario
import androidx.test.core.app.ApplicationProvider
import androidx.test.espresso.intent.Intents
import androidx.test.espresso.intent.matcher.IntentMatchers
import com.lambdasoup.tea.testing.TeaIdlingResource
import com.lambdasoup.watchlater.R
import com.lambdasoup.watchlater.onNodeWithTextRes
import com.lambdasoup.watchlater.ui.add.AddActivity
import com.nhaarman.mockitokotlin2.whenever
import okhttp3.mockwebserver.Dispatcher
import okhttp3.mockwebserver.MockResponse
import okhttp3.mockwebserver.MockWebServer
import okhttp3.mockwebserver.RecordedRequest
import org.hamcrest.Matchers
import org.junit.After
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.mockito.Mockito
import java.util.concurrent.TimeUnit
class AddActivityTest {
@Test
fun see_video_info() {
setupGoogleAccountIsSet()
openWatchlaterViaYoutubeUri()
assertVideoInfoVisible()
}
@Test
fun watch_now() {
setupGoogleAccountIsSet()
setupPlaylistSelected()
openWatchlaterViaYoutubeUri()
clickWatchNow()
assertYoutubeOpenedWithVideoUri()
}
@get:Rule
val composeTestRule = createEmptyComposeRule()
private lateinit var scenario: ActivityScenario<Activity>
private val accountManager = com.lambdasoup.watchlater.accountManager
private val sharedPreferences = com.lambdasoup.watchlater.sharedPreferences
private val server = MockWebServer()
private val idlingResource = TeaIdlingResource()
@Before
fun before() {
server.start(port = 8080)
server.dispatcher = object : Dispatcher() {
override fun dispatch(request: RecordedRequest) =
when (request.path) {
"/videos?part=snippet,contentDetails&maxResults=1&id=dGFSjKuJfrI" ->
MockResponse()
.setResponseCode(200)
.setBody(CucumberTest.VIDEO_INFO_JSON)
else -> MockResponse()
.setResponseCode(404)
.setBody("unhandled path + ${request.path}")
}
}
Intents.init()
Intents.intending(IntentMatchers.hasAction(Intent.ACTION_VIEW))
.respondWith(Instrumentation.ActivityResult(Activity.RESULT_OK, Intent()))
composeTestRule.registerIdlingResource(idlingResource.composeIdlingResource)
}
@After
fun after() {
composeTestRule.unregisterIdlingResource(idlingResource.composeIdlingResource)
Intents.release()
server.shutdown()
Mockito.reset(accountManager, sharedPreferences)
}
private fun setupGoogleAccountIsSet() {
whenever(sharedPreferences.getString("pref_key_default_account_name", null))
.thenReturn("[email protected]")
val account = Account("[email protected]", "com.google")
whenever(accountManager.getAccountsByType("com.google"))
.thenReturn(
arrayOf(account)
)
whenever(
accountManager.getAuthToken(
account,
"oauth2:https://www.googleapis.com/auth/youtube",
null,
false,
null,
null
)
)
.thenReturn(object : AccountManagerFuture<Bundle> {
override fun cancel(p0: Boolean) = throw NotImplementedError()
override fun isCancelled() = throw NotImplementedError()
override fun isDone() = throw NotImplementedError()
override fun getResult() = Bundle().apply {
putString(AccountManager.KEY_AUTHTOKEN, "test-auth-token")
}
override fun getResult(p0: Long, p1: TimeUnit?) = throw NotImplementedError()
})
}
private fun setupPlaylistSelected() {
whenever(sharedPreferences.getString("playlist-id", null))
.thenReturn("test-playlist-id")
whenever(sharedPreferences.getString("playlist-title", null))
.thenReturn("Test playlist title")
}
private fun openWatchlaterViaYoutubeUri() {
val intent = Intent(
ApplicationProvider.getApplicationContext(),
AddActivity::class.java
).apply {
action = Intent.ACTION_VIEW
data = Uri.parse("https://www.youtube.com/watch?v=dGFSjKuJfrI")
}
scenario = ActivityScenario.launch(intent)
}
private fun clickWatchNow() =
composeTestRule.onNodeWithTextRes(R.string.action_watchnow, ignoreCase = true).performClick()
private fun assertVideoInfoVisible() =
composeTestRule.onNodeWithText("Test video title").assertExists()
private fun assertYoutubeOpenedWithVideoUri() {
Intents.intended(
Matchers.allOf(
IntentMatchers.hasData("https://www.youtube.com/watch?v=dGFSjKuJfrI"),
IntentMatchers.hasAction(Intent.ACTION_VIEW),
IntentMatchers.hasPackage("com.google.android.youtube"),
)
)
}
}
| gpl-3.0 | 264c94a6a200999fd12fe9d92f6ee503 | 33.735135 | 101 | 0.671802 | 4.890411 | false | true | false | false |
LarsKrogJensen/graphql-kotlin | src/main/kotlin/graphql/validation/rules/OverlappingFieldsCanBeMerged.kt | 1 | 11913 | package graphql.validation.rules
import graphql.execution.TypeFromAST
import graphql.language.Argument
import graphql.language.AstComparator
import graphql.language.Directive
import graphql.language.*
import graphql.schema.GraphQLFieldsContainer
import graphql.schema.GraphQLObjectType
import graphql.schema.GraphQLOutputType
import graphql.schema.GraphQLType
import graphql.validation.AbstractRule
import graphql.validation.ErrorFactory
import graphql.validation.ValidationContext
import graphql.validation.ValidationErrorCollector
import graphql.validation.ValidationErrorType.FieldsConflict
import java.util.*
class OverlappingFieldsCanBeMerged(validationContext: ValidationContext, validationErrorCollector: ValidationErrorCollector) : AbstractRule(validationContext, validationErrorCollector) {
internal var errorFactory = ErrorFactory()
private val alreadyChecked = ArrayList<FieldPair>()
override fun leaveSelectionSet(selectionSet: SelectionSet) {
val fieldMap = LinkedHashMap<String, MutableList<FieldAndType>>()
val visitedFragmentSpreads = LinkedHashSet<String>()
collectFields(fieldMap, selectionSet, validationContext.outputType, visitedFragmentSpreads)
val conflicts = findConflicts(fieldMap)
for (conflict in conflicts) {
addError(errorFactory.newError(FieldsConflict, conflict.fields, conflict.reason))
}
}
private fun findConflicts(fieldMap: Map<String, List<FieldAndType>>): List<Conflict> {
val result = ArrayList<Conflict>()
for (name in fieldMap.keys) {
fieldMap[name]?.apply {
for (i in indices) {
for (j in i + 1..size - 1) {
val conflict = findConflict(name, get(i), get(j))
if (conflict != null) {
result.add(conflict)
}
}
}
}
}
return result
}
private fun isAlreadyChecked(field1: Field, field2: Field): Boolean {
for (fieldPair in alreadyChecked) {
if (fieldPair.field1 == field1 && fieldPair.field2 == field2) {
return true
}
if (fieldPair.field1 == field2 && fieldPair.field2 == field1) {
return true
}
}
return false
}
private fun findConflict(responseName: String, fieldAndType1: FieldAndType, fieldAndType2: FieldAndType): Conflict? {
val field1 = fieldAndType1.field
val field2 = fieldAndType2.field
val type1 = fieldAndType1.graphQLType
val type2 = fieldAndType2.graphQLType
val fieldName1 = field1.name
val fieldName2 = field2.name
if (isAlreadyChecked(field1, field2)) {
return null
}
alreadyChecked.add(FieldPair(field1, field2))
// If the statically known parent types could not possibly apply at the same
// time, then it is safe to permit them to diverge as they will not present
// any ambiguity by differing.
// It is known that two parent types could never overlap if they are
// different Object types. Interface or Union types might overlap - if not
// in the current state of the schema, then perhaps in some future version,
// thus may not safely diverge.
if (!sameType(fieldAndType1.parentType, fieldAndType1.parentType) &&
fieldAndType1.parentType is GraphQLObjectType &&
fieldAndType2.parentType is GraphQLObjectType) {
return null
}
if (fieldName1 != fieldName2) {
val reason = String.format("%s: %s and %s are different fields", responseName, fieldName1, fieldName2)
return Conflict(responseName, reason, field1, field2)
}
if (!sameType(type1, type2)) {
val name1 = type1?.name
val name2 = type2?.name
val reason = String.format("%s: they return differing types %s and %s", responseName, name1, name2)
return Conflict(responseName, reason, field1, field2)
}
if (!sameArguments(field1.arguments, field2.arguments)) {
val reason = String.format("%s: they have differing arguments", responseName)
return Conflict(responseName, reason, field1, field2)
}
if (!sameDirectives(field1.directives, field2.directives)) {
val reason = String.format("%s: they have differing directives", responseName)
return Conflict(responseName, reason, field1, field2)
}
val selectionSet1 = field1.selectionSet
val selectionSet2 = field2.selectionSet
if (!selectionSet1.isEmpty() && !selectionSet2.isEmpty()) {
val visitedFragmentSpreads = LinkedHashSet<String>()
val subFieldMap = LinkedHashMap<String, MutableList<FieldAndType>>()
collectFields(subFieldMap, selectionSet1, type1, visitedFragmentSpreads)
collectFields(subFieldMap, selectionSet2, type2, visitedFragmentSpreads)
val subConflicts = findConflicts(subFieldMap)
if (subConflicts.isNotEmpty()) {
val reason = String.format("%s: %s", responseName, joinReasons(subConflicts))
val fields = ArrayList<Field>()
fields.add(field1)
fields.add(field2)
fields.addAll(collectFields(subConflicts))
return Conflict(responseName, reason, fields)
}
}
return null
}
private fun collectFields(conflicts: List<Conflict>): List<Field> {
val result = ArrayList<Field>()
for (conflict in conflicts) {
result.addAll(conflict.fields)
}
return result
}
private fun joinReasons(conflicts: List<Conflict>): String {
val result = StringBuilder()
result.append("(")
for (conflict in conflicts) {
result.append(conflict.reason)
result.append(", ")
}
result.delete(result.length - 2, result.length)
result.append(")")
return result.toString()
}
private fun sameType(type1: GraphQLType?, type2: GraphQLType?): Boolean {
if (type1 == null || type2 == null) return true
return type1 == type2
}
private fun sameValue(value1: Value?, value2: Value?): Boolean {
if (value1 == null && value2 == null) return true
if (value1 == null) return false
if (value2 == null) return false
return AstComparator().isEqual(value1, value2)
}
private fun sameArguments(arguments1: List<Argument>, arguments2: List<Argument>): Boolean {
if (arguments1.size != arguments2.size) return false
for ((name, value) in arguments1) {
val matchedArgument = findArgumentByName(name, arguments2) ?: return false
if (!sameValue(value, matchedArgument.value)) return false
}
return true
}
private fun findArgumentByName(name: String, arguments: List<Argument>): Argument? {
return arguments.firstOrNull { it.name == name }
}
private fun sameDirectives(directives1: List<Directive>, directives2: List<Directive>): Boolean {
if (directives1.size != directives2.size) return false
for (directive in directives1) {
val matchedDirective = findDirectiveByName(directive.name, directives2) ?: return false
if (!sameArguments(directive.arguments, matchedDirective.arguments)) return false
}
return true
}
private fun findDirectiveByName(name: String, directives: List<Directive>): Directive? {
return directives.firstOrNull { it.name == name }
}
private fun collectFields(fieldMap: MutableMap<String, MutableList<FieldAndType>>,
selectionSet: SelectionSet?,
parentType: GraphQLType?,
visitedFragmentSpreads: MutableSet<String>) {
if (selectionSet != null) {
for (selection in selectionSet.selections) {
if (selection is Field) {
collectFieldsForField(fieldMap, parentType, selection)
} else if (selection is InlineFragment) {
collectFieldsForInlineFragment(fieldMap, visitedFragmentSpreads, parentType, selection)
} else if (selection is FragmentSpread) {
collectFieldsForFragmentSpread(fieldMap, visitedFragmentSpreads, selection)
}
}
}
}
private fun collectFieldsForFragmentSpread(fieldMap: MutableMap<String, MutableList<FieldAndType>>,
visitedFragmentSpreads: MutableSet<String>,
selection: FragmentSpread) {
val fragmentSpread = selection
val fragment = validationContext.fragment(fragmentSpread.name) ?: return
if (visitedFragmentSpreads.contains(fragment.name)) {
return
}
visitedFragmentSpreads.add(fragment.name)
val graphQLType = TypeFromAST.getTypeFromAST(validationContext.schema,
fragment.typeCondition) as GraphQLOutputType?
collectFields(fieldMap, fragment.selectionSet, graphQLType, visitedFragmentSpreads)
}
private fun collectFieldsForInlineFragment(fieldMap: MutableMap<String, MutableList<FieldAndType>>,
visitedFragmentSpreads: MutableSet<String>,
parentType: GraphQLType?,
selection: InlineFragment) {
val inlineFragment = selection
val graphQLType = if (inlineFragment.typeCondition != null)
TypeFromAST.getTypeFromAST(validationContext.schema, inlineFragment.typeCondition) as GraphQLOutputType
else
parentType
collectFields(fieldMap, inlineFragment.selectionSet, graphQLType, visitedFragmentSpreads)
}
private fun collectFieldsForField(fieldMap: MutableMap<String, MutableList<FieldAndType>>,
parentType: GraphQLType?,
selection: Field) {
val field = selection
val responseName = field.alias ?: field.name
if (!fieldMap.containsKey(responseName)) {
fieldMap.put(responseName, ArrayList<FieldAndType>())
}
var fieldType: GraphQLOutputType? = null
if (parentType is GraphQLFieldsContainer) {
val fieldsContainer = parentType
val fieldDefinition = fieldsContainer.fieldDefinitions.find { it.name == field.name }
fieldType = fieldDefinition?.type
}
fieldMap[responseName]?.add(FieldAndType(field, fieldType, parentType))
}
private class FieldPair(internal var field1: Field, internal var field2: Field)
private class Conflict {
internal var responseName: String
internal var reason: String
internal var fields: MutableList<Field> = mutableListOf()
constructor(responseName: String, reason: String, field1: Field, field2: Field) {
this.responseName = responseName
this.reason = reason
this.fields.add(field1)
this.fields.add(field2)
}
constructor(responseName: String, reason: String, fields: List<Field>) {
this.responseName = responseName
this.reason = reason
this.fields.addAll(fields)
}
}
private class FieldAndType(internal var field: Field,
internal var graphQLType: GraphQLType?,
internal var parentType: GraphQLType?)
}
| mit | ed049f19762dddf2053d5f10ed8ef470 | 40.508711 | 186 | 0.626626 | 4.943154 | false | false | false | false |
material-components/material-components-android-motion-codelab | app/src/main/java/com/materialstudies/reply/ui/search/SearchFragment.kt | 1 | 3267 | /*
* Copyright 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.materialstudies.reply.ui.search
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.annotation.StringRes
import androidx.fragment.app.Fragment
import androidx.navigation.fragment.findNavController
import com.materialstudies.reply.R
import com.materialstudies.reply.data.SearchSuggestion
import com.materialstudies.reply.data.SearchSuggestionStore
import com.materialstudies.reply.databinding.FragmentSearchBinding
import com.materialstudies.reply.databinding.SearchSuggestionItemBinding
import com.materialstudies.reply.databinding.SearchSuggestionTitleBinding
/**
* A [Fragment] that displays search.
*/
class SearchFragment : Fragment() {
private lateinit var binding: FragmentSearchBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
// TODO: Set up MaterialSharedAxis transition as exit and reenter transitions.
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
binding = FragmentSearchBinding.inflate(inflater, container, false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
binding.searchToolbar.setNavigationOnClickListener { findNavController().navigateUp() }
setUpSuggestions(binding.searchSuggestionContainer)
}
private fun setUpSuggestions(suggestionContainer: ViewGroup) {
addSuggestionTitleView(suggestionContainer, R.string.search_suggestion_title_yesterday)
addSuggestionItemViews(suggestionContainer, SearchSuggestionStore.YESTERDAY_SUGGESTIONS)
addSuggestionTitleView(suggestionContainer, R.string.search_suggestion_title_this_week)
addSuggestionItemViews(suggestionContainer, SearchSuggestionStore.THIS_WEEK_SUGGESTIONS)
}
private fun addSuggestionTitleView(parent: ViewGroup, @StringRes titleResId: Int) {
val inflater = LayoutInflater.from(parent.context)
val titleBinding = SearchSuggestionTitleBinding.inflate(inflater, parent, false)
titleBinding.title = titleResId
parent.addView(titleBinding.root)
}
private fun addSuggestionItemViews(parent: ViewGroup, suggestions: List<SearchSuggestion>) {
suggestions.forEach {
val inflater = LayoutInflater.from(parent.context)
val suggestionBinding = SearchSuggestionItemBinding.inflate(inflater, parent, false)
suggestionBinding.suggestion = it
parent.addView(suggestionBinding.root)
}
}
}
| apache-2.0 | d575a1c13dfe7c0c50489b0ede33cb15 | 38.841463 | 96 | 0.760331 | 4.957511 | false | false | false | false |
sksamuel/akka-patterns | rxhive-components/rxhive-components-akkastream_2.12/src/main/kotlin/com/sksamuel/reactivehive/akkastream/ParquetSource.kt | 1 | 1552 | package com.sksamuel.reactivehive.akkastream
import akka.stream.Attributes
import akka.stream.Outlet
import akka.stream.SourceShape
import akka.stream.stage.GraphStageLogic
import akka.stream.stage.GraphStageWithMaterializedValue
import akka.stream.stage.OutHandler
import com.sksamuel.reactivehive.Struct
import com.sksamuel.reactivehive.parquet.parquetReader
import org.apache.hadoop.conf.Configuration
import org.apache.hadoop.fs.Path
import scala.Tuple2
import java.util.concurrent.CompletableFuture
class ParquetSource(val path: Path,
val conf: Configuration) : GraphStageWithMaterializedValue<SourceShape<Struct>, CompletableFuture<Int>>() {
private val outlet: Outlet<Struct> = Outlet.create("ParquetSource.out")
override fun shape(): SourceShape<Struct> = SourceShape.of(outlet)
override fun createLogicAndMaterializedValue(inheritedAttributes: Attributes?): Tuple2<GraphStageLogic, CompletableFuture<Int>> {
val future = CompletableFuture<Int>()
val graph: GraphStageLogic = object : GraphStageLogic(shape()), OutHandler {
private val reader = parquetReader(path, conf)
private var count = 0
init {
setHandler(outlet, this)
}
override fun onPull() {
val struct = reader.read()
try {
if (struct == null) {
completeStage()
} else {
push(outlet, struct)
count++
}
} catch (t: Throwable) {
failStage(t)
}
}
}
return Tuple2(graph, future)
}
} | apache-2.0 | 4c6cf2ae9a861e72167f7d70a08cb4b6 | 28.865385 | 131 | 0.695876 | 4.299169 | false | false | false | false |
marcelgross90/Cineaste | app/src/main/kotlin/de/cineaste/android/viewholder/series/AbstractSeriesViewHolder.kt | 1 | 991 | package de.cineaste.android.viewholder.series
import android.content.Context
import android.text.TextUtils
import android.view.View
import android.widget.TextView
import de.cineaste.android.R
import de.cineaste.android.entity.series.Series
import de.cineaste.android.listener.ItemClickListener
import de.cineaste.android.viewholder.BaseViewHolder
abstract class AbstractSeriesViewHolder(
itemView: View,
listener: ItemClickListener,
context: Context
) :
BaseViewHolder(itemView, listener, context) {
private val vote: TextView = itemView.findViewById(R.id.vote)
abstract fun assignData(series: Series, position: Int)
fun setBaseInformation(series: Series) {
title.text = series.name
vote.text = resources.getString(R.string.vote, series.voteAverage.toString())
var posterName = series.posterPath
if (TextUtils.isEmpty(posterName)) {
posterName = series.posterPath
}
setPoster(posterName)
}
}
| gpl-3.0 | 4837d830b393c2e249424886bf13b1f8 | 28.147059 | 85 | 0.741675 | 4.290043 | false | false | false | false |
Ribesg/anko | preview/xml-converter/src/org/jetbrains/kotlin/android/xmlconverter/ConvertAction.kt | 1 | 6406 | /*
* Copyright 2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.kotlin.android.xmlconverter
import com.intellij.facet.FacetManager
import com.intellij.ide.highlighter.XmlFileType
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.CommonDataKeys
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.fileEditor.FileEditorManager
import com.intellij.openapi.module.Module
import com.intellij.openapi.project.Project
import com.intellij.openapi.roots.ModuleRootManager
import com.intellij.openapi.roots.ProjectRootManager
import com.intellij.openapi.ui.ex.MessagesEx
import com.intellij.openapi.vfs.LocalFileSystem
import com.intellij.openapi.vfs.VfsUtilCore
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.openapi.vfs.VirtualFileVisitor
import org.jetbrains.android.facet.AndroidFacet
import org.jetbrains.kotlin.idea.refactoring.fqName.getKotlinFqName
import java.io.File
import java.io.IOException
class ConvertAction : AnAction() {
private class FileToConvert(val xmlFile: VirtualFile, val ktFile: File)
override fun actionPerformed(e: AnActionEvent) {
val virtualFiles = e.getData(CommonDataKeys.VIRTUAL_FILE_ARRAY) ?: return
val project = CommonDataKeys.PROJECT.getData(e.dataContext) ?: return
val files = allFilesToConvert(virtualFiles, project)
if (files.isEmpty()) return
ApplicationManager.getApplication().runWriteAction {
var lastConvertedFile: VirtualFile? = null
for (file in files) {
System.err.println("Converting file " + file.xmlFile.path)
file.convert(project)
lastConvertedFile = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(file.ktFile)
}
if (lastConvertedFile != null) {
FileEditorManager.getInstance(project).openFile(lastConvertedFile, true)
}
}
}
private fun VirtualFile.getFileToConvert(project: Project): FileToConvert? {
if (fileType !is XmlFileType) return null
if (!parent.name.startsWith("layout")) return null
val androidFacet = resolveAndroidFacet(project) ?: return null
val probResourceDirectory = parent?.parent?.path
val resourceDirectories = androidFacet.allResourceDirectories
if (!resourceDirectories.any { it.canonicalPath == probResourceDirectory }) return null
val targetDirectory = getActivityDirectory(androidFacet) ?: getMainAndroidSourceRoot(androidFacet)
val ktFileNameBase = nameWithoutExtension.firstCapital()
var candidateKtFile = File(targetDirectory, ktFileNameBase + "LayoutActivity.kt")
var counter = 0
while (candidateKtFile.exists()) {
candidateKtFile = File(targetDirectory, ktFileNameBase + "LayoutActivity$counter.kt")
counter++
}
return FileToConvert(this, candidateKtFile)
}
private fun getActivityDirectory(androidFacet: AndroidFacet): String? {
val manifest = androidFacet.manifest
val appPackage = manifest?.`package`?.value
val activities = manifest?.application?.activities
if (appPackage == null || activities == null) return null
val activityClasses = activities.map { it.activityClass.value }
val activity = activityClasses
.filter { it?.getKotlinFqName()?.asString()?.startsWith(appPackage) ?: false }
.firstOrNull()
return activity?.containingFile?.containingDirectory?.virtualFile?.canonicalPath
}
private fun getMainAndroidSourceRoot(androidFacet: AndroidFacet): String? {
return ModuleRootManager.getInstance(androidFacet.module)
.contentRoots.filter { !it.canonicalPath!!.endsWith("/gen") }.first().canonicalPath
}
override fun update(e: AnActionEvent) {
e.presentation.isEnabled = selectedLayoutFiles(e).any()
}
private fun selectedLayoutFiles(e: AnActionEvent): List<FileToConvert> {
val virtualFiles = e.getData(CommonDataKeys.VIRTUAL_FILE_ARRAY) ?: return listOf()
val project = CommonDataKeys.PROJECT.getData(e.dataContext) ?: return listOf()
return allFilesToConvert(virtualFiles, project)
}
private fun allFilesToConvert(filesOrDirs: Array<VirtualFile>, project: Project): List<FileToConvert> {
val result = arrayListOf<FileToConvert>()
for (file in filesOrDirs) {
VfsUtilCore.visitChildrenRecursively(file, object : VirtualFileVisitor<Unit>() {
override fun visitFile(file: VirtualFile): Boolean {
val fileToConvert = file.getFileToConvert(project)
if (fileToConvert != null) result.add(fileToConvert)
return true
}
})
}
return result
}
private fun VirtualFile.resolveAndroidFacet(project: Project): AndroidFacet? {
return ProjectRootManager.getInstance(project).fileIndex.getModuleForFile(this)?.resolveAndroidFacet()
}
private fun Module.resolveAndroidFacet(): AndroidFacet? {
val facetManager = FacetManager.getInstance(this)
for (facet in facetManager.allFacets) {
if (facet is AndroidFacet) {
return facet
}
}
return null
}
private fun FileToConvert.convert(project: Project) {
try {
ktFile.writeText(XmlConverter.convert(xmlFile.contentsToByteArray().toString(charset("UTF-8"))))
}
catch (e: IOException) {
MessagesEx.error(project, e.message).showLater()
}
}
private fun String.firstCapital() = if (isEmpty()) "" else Character.toUpperCase(this[0]) + substring(1)
} | apache-2.0 | d81bcac6bf6275e95cb3bac222fdc65f | 40.070513 | 110 | 0.700125 | 4.897554 | false | false | false | false |
stripe/stripe-android | payments-ui-core/src/main/java/com/stripe/android/ui/core/elements/CvcConfig.kt | 1 | 2039 | package com.stripe.android.ui.core.elements
import androidx.annotation.RestrictTo
import androidx.compose.ui.text.input.KeyboardCapitalization
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.text.input.VisualTransformation
import com.stripe.android.model.CardBrand
import com.stripe.android.ui.core.R
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
class CvcConfig : CardDetailsTextFieldConfig {
override val capitalization: KeyboardCapitalization = KeyboardCapitalization.None
override val debugLabel: String = "cvc"
override val label: Int = R.string.cvc_number_hint
override val keyboard: KeyboardType = KeyboardType.NumberPassword
override val visualTransformation: VisualTransformation = VisualTransformation.None
override fun determineState(
brand: CardBrand,
number: String,
numberAllowedDigits: Int
): TextFieldState {
val isDigitLimit = brand.maxCvcLength != -1
return if (number.isEmpty()) {
TextFieldStateConstants.Error.Blank
} else if (brand == CardBrand.Unknown) {
when (number.length) {
numberAllowedDigits -> TextFieldStateConstants.Valid.Full
else -> TextFieldStateConstants.Valid.Limitless
}
} else if (isDigitLimit && number.length < numberAllowedDigits) {
TextFieldStateConstants.Error.Incomplete(R.string.invalid_cvc)
} else if (isDigitLimit && number.length > numberAllowedDigits) {
TextFieldStateConstants.Error.Invalid(R.string.invalid_cvc)
} else if (isDigitLimit && number.length == numberAllowedDigits) {
TextFieldStateConstants.Valid.Full
} else {
TextFieldStateConstants.Error.Invalid(R.string.invalid_cvc)
}
}
override fun filter(userTyped: String): String = userTyped.filter { it.isDigit() }
override fun convertToRaw(displayName: String): String = displayName
override fun convertFromRaw(rawValue: String): String = rawValue
}
| mit | b96a74909040a143dd687f3aa47c8aba | 42.382979 | 87 | 0.716037 | 4.634091 | false | false | false | false |
Dmedina88/SSB | example/app/src/main/kotlin/com/grayherring/devtalks/ui/home/HomeViewModel.kt | 1 | 3868 | package com.grayherring.devtalks.ui.home
import com.grayherring.devtalks.base.events.*
import com.grayherring.devtalks.base.ui.BaseViewModel
import com.grayherring.devtalks.base.util.capture.GsonPrefRecorder
import com.grayherring.devtalks.base.util.intervalEmitted
import com.grayherring.devtalks.base.util.plusAssign
import com.grayherring.devtalks.data.repository.Repository
import com.grayherring.devtalks.ui.home.events.*
import io.reactivex.Observable
import timber.log.Timber
import java.util.concurrent.TimeUnit
import javax.inject.Inject
/**
* Created by davidmedina on 5/19/17 =).
*/
class HomeViewModel @Inject constructor(private val repository: Repository,
private val homeRecorder: GsonPrefRecorder<HomeState>) : BaseViewModel<HomeState>() {
override fun init() {
super.init()
if (state.talks.isEmpty()) {
homeRecorder.clear()
getBooks()
}
}
var replaing = false
override fun initState() = HomeState()
override fun handleEvents(event: Event): HomeState {
Timber.d(event.toString())
val newState = when (event) {
is ClickEvent -> clickEventReducer(event, state)
is NetworkEvent -> networkReducer(event, state)
is ItemClickEvent -> state.copy(selectedTalk = event.talk, tab = 2)
is AllTalksEvent -> state.copy(loading = false, talks = event.talks)
is TextChangeEvent -> textChangeReducer(event, state)
is ErrorEvent -> state.copy(loading = false, error = event.errorMessage)
else -> state
}
Timber.d(newState.toString())
if (!replaing) {
homeRecorder.save(newState)
}
return newState
}
private fun clickEventReducer(clickEvent: ClickEvent, state: HomeState): HomeState {
return when (clickEvent) {
is Tab1Clicked -> state.copy(tab = 1)
is Tab2Clicked -> state.copy(tab = 2)
is Tab3Clicked -> state.copy(tab = 3)
is EditClicked -> state.copy(editScreen = !state.editScreen)
else -> state
}
}
private fun networkReducer(networkEvent: NetworkEvent, state: HomeState): HomeState {
return when (networkEvent) {
is GetTalkEvent -> {
getBooks()
state.copy(loading = true)
}
else -> state
}
}
private fun textChangeReducer(textChangeEvent: TextChangeEvent, state: HomeState): HomeState {
val newState = textChangeEvent.value.run {
when (textChangeEvent) {
is PresenterChangeEvent -> state.copy(newTalk = state.newTalk.copy(presenter = this))
is TitleChangeEvent -> state.copy(newTalk = state.newTalk.copy(title = this))
is PlatformChangeEvent -> state.copy(newTalk = state.newTalk.copy(platform = this))
is DescriptionChangeEvent -> state.copy(newTalk = state.newTalk.copy(description = this))
is DateChangeEvent -> state.copy(newTalk = state.newTalk.copy(date = this))
is EmailChangeEvent -> state.copy(newTalk = state.newTalk.copy(email = this))
is SlidesChangeEvent -> state.copy(newTalk = state.newTalk.copy(slides = this))
is StreamChangeEvent -> state.copy(newTalk = state.newTalk.copy(stream = this))
else -> state
}
}
//check state if new talk is valid
return newState
}
fun getBooks() {
disposable += repository.makeAllTalksCall(this::addEvent)
}
fun playback() {
val states = homeRecorder.states
replaing = true
Timber.i("${states.size}")
Observable.fromIterable(states)
.intervalEmitted(500, TimeUnit.MILLISECONDS)
.doOnComplete { replaing = false }
.subscribe({
Timber.i("##replay ${states.indexOf(it)} $it ")
state = it
}, {
Timber.e(it)
replaing = false
})
}
override fun onCleared() {
//should clear this in debug draw
homeRecorder.clear()
super.onCleared()
}
} | apache-2.0 | 7fc86e602cc838ccd40e79a0c3591bd4 | 31.241667 | 125 | 0.671148 | 4.080169 | false | false | false | false |
openmhealth/schemas | kotlin-schema-sdk/src/main/kotlin/org/openmhealth/schema/domain/SchemaVersion.kt | 1 | 1834 | package org.openmhealth.schema.domain
import java.util.regex.Pattern
/**
* A semantic schema version, consisting of a major number, minor number, and an optional qualifier.
*
* @author Emerson Farrugia
*/
data class SchemaVersion(
val major: Int = 1,
val minor: Int = 0,
val qualifier: String? = null
) : Comparable<SchemaVersion> {
init {
require(major >= 0) { "A negative major version has been specified." }
require(minor >= 0) { "A negative minor version has been specified." }
require(qualifier == null || QUALIFIER_PATTERN.matcher(qualifier).matches()) {
"A malformed qualifier has been specified."
}
}
companion object {
private const val QUALIFIER_PATTERN_STRING = "[a-zA-Z0-9]+"
private const val PATTERN_STRING = "(\\d+)\\.(\\d+)(?:\\.($QUALIFIER_PATTERN_STRING))?"
val QUALIFIER_PATTERN: Pattern = Pattern.compile(QUALIFIER_PATTERN_STRING)
private val PATTERN: Pattern = Pattern.compile(PATTERN_STRING)
fun fromString(version: String): SchemaVersion {
val matcher = PATTERN.matcher(version)
require(matcher.matches()) { "A malformed version has been specified." }
return SchemaVersion(
major = Integer.valueOf(matcher.group(1)),
minor = Integer.valueOf(matcher.group(2)),
qualifier = matcher.group(3)
)
}
val comparator = compareBy<SchemaVersion> { it.major }
.thenBy { it.minor }
.thenBy { it.qualifier }
}
override fun toString(): String =
"$major.$minor" +
(qualifier
?.let { ".$it" }
?: "")
override fun compareTo(other: SchemaVersion): Int =
comparator.compare(this, other)
}
| apache-2.0 | 2a71214bec67ceeb78b90a3f83c3171c | 32.345455 | 100 | 0.593239 | 4.462287 | false | false | false | false |
Undin/intellij-rust | src/main/kotlin/org/rust/ide/typing/paste/JsonStructParser.kt | 2 | 9543 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.ide.typing.paste
import com.fasterxml.jackson.core.JsonFactoryBuilder
import com.fasterxml.jackson.core.JsonParser
import com.fasterxml.jackson.core.JsonToken
import com.fasterxml.jackson.core.json.JsonReadFeature
import org.rust.stdext.mapToSet
import java.io.IOException
sealed class DataType {
object Integer : DataType()
object Float : DataType()
object Boolean : DataType()
object String : DataType()
object Unknown : DataType()
data class StructRef(val struct: Struct) : DataType()
data class Array(val type: DataType) : DataType()
data class Nullable(val type: DataType) : DataType() {
override fun unwrap(): DataType = type
}
/**
* Return the first non-nullable type contained in this type.
*/
open fun unwrap(): DataType = this
}
// Structs with the same field names and types are considered the same, regardless of field order.
// LinkedHashMap::equals ignores key (field) order.
data class Struct(val fields: LinkedHashMap<String, DataType>)
/**
* Try to parse the input text as a JSON object.
*
* Extract a list of (unique) structs that were encountered in the JSON object.
*/
fun extractStructsFromJson(text: String): List<Struct>? {
// Fast path to avoid creating a parser if the input does not look like a JSON object
val input = text.trim()
if (input.isEmpty() || input.first() != '{' || input.last() != '}') return null
return try {
val factory = JsonFactoryBuilder()
.enable(JsonReadFeature.ALLOW_TRAILING_COMMA)
.build()
val parser = factory.createParser(input)
val structParser = StructParser()
val rootStruct = parser.use {
// There must be an object at the root
val token = parser.nextToken()
if (token != JsonToken.START_OBJECT) return null
structParser.parseStruct(parser)
} ?: return null
// Return structs in reversed order to generate the inner structs first
gatherEncounteredStructs(rootStruct).toList().reversed()
} catch (e: IOException) {
null
}
}
data class Field(val name: String, val type: DataType)
open class DataTypeVisitor {
open fun visit(dataType: DataType) {
when (dataType) {
is DataType.Array -> visitArray(dataType)
is DataType.Nullable -> visitNullable(dataType)
is DataType.StructRef -> visitStruct(dataType)
is DataType.Boolean -> visitBoolean(dataType)
is DataType.Float -> visitFloat(dataType)
is DataType.Integer -> visitInteger(dataType)
is DataType.String -> visitString(dataType)
is DataType.Unknown -> visitUnknown(dataType)
}
}
open fun visitArray(dataType: DataType.Array) {
visit(dataType.type)
}
open fun visitNullable(dataType: DataType.Nullable) {
visit(dataType.type)
}
open fun visitStruct(dataType: DataType.StructRef) {
for (fieldType in dataType.struct.fields.values) {
visit(fieldType)
}
}
open fun visitInteger(dataType: DataType.Integer) {}
open fun visitFloat(dataType: DataType.Float) {}
open fun visitBoolean(dataType: DataType.Boolean) {}
open fun visitString(dataType: DataType.String) {}
open fun visitUnknown(dataType: DataType.Unknown) {}
}
/**
* Finds all unique structs contained in the root struct.
*/
fun gatherEncounteredStructs(root: Struct): Set<Struct> {
val structs = linkedSetOf<Struct>()
val visitor = object : DataTypeVisitor() {
override fun visitStruct(dataType: DataType.StructRef) {
structs.add(dataType.struct)
super.visitStruct(dataType)
}
}
visitor.visit(DataType.StructRef(root))
return structs
}
private class StructParser {
private val structMap = linkedSetOf<Struct>()
fun parseStruct(parser: JsonParser): Struct? {
if (parser.currentToken != JsonToken.START_OBJECT) return null
val fields = linkedMapOf<String, DataType>()
while (true) {
val field = parseField(parser) ?: break
// Ignore duplicate fields
if (field.name in fields) continue
fields[field.name] = field.type
}
if (parser.currentToken != JsonToken.END_OBJECT) return null
val struct = Struct(fields)
registerStruct(struct)
return struct
}
private fun registerStruct(struct: Struct) {
structMap.add(struct)
}
private fun parseField(parser: JsonParser): Field? {
if (parser.nextToken() != JsonToken.FIELD_NAME) return null
val name = parser.currentName
val type = parseDataType(parser)
return Field(name, type)
}
private fun parseArray(parser: JsonParser): DataType? {
if (parser.currentToken != JsonToken.START_ARRAY) return null
val foundDataTypes = linkedSetOf<DataType>()
val firstType = parseDataType(parser)
// Empty array
if (firstType == DataType.Unknown) {
return DataType.Array(DataType.Unknown)
}
foundDataTypes.add(firstType)
while (parser.currentToken != null) {
val dataType = parseDataType(parser)
if (dataType == DataType.Unknown && parser.currentToken == JsonToken.END_ARRAY) {
break
}
foundDataTypes.add(dataType)
}
return DataType.Array(generateContainedType(foundDataTypes))
}
private fun extractStructType(type: DataType): DataType.StructRef? {
return when {
type is DataType.StructRef -> type
type is DataType.Nullable && type.type is DataType.StructRef -> type.type
else -> null
}
}
/**
* Tries to unify multiple array types containing a similar value to a single array type.
*/
private fun unifyArrayTypes(types: Set<DataType>): Set<DataType> {
if (!types.all { it is DataType.Array } || types.size < 2) return types
val arrayTypes = types.filterIsInstance<DataType.Array>().toSet()
// Ignore unknown, since it is contained in empty arrays
val innerTypes = arrayTypes
.map { it.type.unwrap() }
.filter { it !is DataType.Unknown }
.toSet()
return if (innerTypes.size == 1) {
val inner = if (arrayTypes.any { it.type is DataType.Nullable }) {
setOf(DataType.Nullable(innerTypes.first()))
} else {
innerTypes
}
inner.mapToSet { DataType.Array(it) }
} else {
types
}
}
private fun generateContainedType(containedTypes: Set<DataType>): DataType {
val types = unifyArrayTypes(containedTypes)
val containsNullable = types.any { it is DataType.Nullable }
val typesWithoutNull = types.filterNot { it is DataType.Nullable && it.type is DataType.Unknown }
val structTypes = types.mapNotNull { extractStructType(it) }
val innerType = when {
types.size == 1 -> types.first()
types.size == 2 && containsNullable -> DataType.Nullable(types.first { it !is DataType.Nullable })
structTypes.size == typesWithoutNull.size -> {
val type = unifyStructs(structTypes)
if (containsNullable) {
DataType.Nullable(type)
} else {
type
}
}
containsNullable -> DataType.Nullable(DataType.Unknown)
else -> DataType.Unknown
}
return innerType
}
/**
* Look through a list of structs and try to unify them to a single struct type with optional fields.
*/
private fun unifyStructs(structTypes: List<DataType.StructRef>): DataType {
// Gather all field keys
val foundFields = structTypes
.flatMap { it.struct.fields.entries }
.groupByTo(mutableMapOf(), { it.key }, { it.value })
// Add null to fields that are not inside all structs
for (types in foundFields.values) {
if (types.size < structTypes.size) {
types.add(DataType.Nullable(types[0]))
}
}
// Use `LinkedHashSet` to keep a deterministic order
val fields = foundFields.mapValuesTo(linkedMapOf()) { generateContainedType(LinkedHashSet(it.value)) }
val struct = Struct(fields)
registerStruct(struct)
return DataType.StructRef(struct)
}
private fun parseDataType(parser: JsonParser): DataType {
return when (parser.nextToken()) {
JsonToken.START_OBJECT -> {
val struct = parseStruct(parser)
if (struct == null) {
DataType.Unknown
} else {
DataType.StructRef(struct)
}
}
JsonToken.START_ARRAY -> parseArray(parser) ?: DataType.Unknown
JsonToken.VALUE_NULL -> DataType.Nullable(DataType.Unknown)
JsonToken.VALUE_FALSE, JsonToken.VALUE_TRUE -> DataType.Boolean
JsonToken.VALUE_NUMBER_INT -> DataType.Integer
JsonToken.VALUE_NUMBER_FLOAT -> DataType.Float
JsonToken.VALUE_STRING -> DataType.String
else -> DataType.Unknown
}
}
}
| mit | 999bb7d2c69090dfb1197a724bafe573 | 33.451264 | 110 | 0.619512 | 4.659668 | false | false | false | false |
deva666/anko | anko/library/static/platform/src/CustomViewProperties.kt | 2 | 3217 | /*
* Copyright 2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
@file:Suppress("unused")
package org.jetbrains.anko
import android.os.Build
import android.graphics.drawable.Drawable
import android.util.TypedValue
import android.view.View
import android.widget.ImageView
import android.widget.TextView
import org.jetbrains.anko.internals.AnkoInternals.NO_GETTER
import org.jetbrains.anko.internals.AnkoInternals.noGetter
import kotlin.DeprecationLevel.ERROR
var View.backgroundDrawable: Drawable?
inline get() = background
set(value) = setBackgroundDrawable(value)
var View.leftPadding: Int
inline get() = paddingLeft
set(value) = setPadding(value, paddingTop, paddingRight, paddingBottom)
var View.topPadding: Int
inline get() = paddingTop
set(value) = setPadding(paddingLeft, value, paddingRight, paddingBottom)
var View.rightPadding: Int
inline get() = paddingRight
set(value) = setPadding(paddingLeft, paddingTop, value, paddingBottom)
var View.bottomPadding: Int
inline get() = paddingBottom
set(value) = setPadding(paddingLeft, paddingTop, paddingRight, value)
@Deprecated("Use horizontalPadding instead", ReplaceWith("horizontalPadding"))
var View.paddingHorizontal: Int
@Deprecated(NO_GETTER, level = ERROR) get() = noGetter()
set(value) = setPadding(value, paddingTop, value, paddingBottom)
var View.horizontalPadding: Int
@Deprecated(NO_GETTER, level = ERROR) get() = noGetter()
set(value) = setPadding(value, paddingTop, value, paddingBottom)
@Deprecated("Use verticalPadding instead", ReplaceWith("verticalPadding"))
var View.paddingVertical: Int
@Deprecated(NO_GETTER, level = ERROR) get() = noGetter()
set(value) = setPadding(paddingLeft, value, paddingRight, value)
var View.verticalPadding: Int
@Deprecated(NO_GETTER, level = ERROR) get() = noGetter()
set(value) = setPadding(paddingLeft, value, paddingRight, value)
var View.padding: Int
@Deprecated(NO_GETTER, level = ERROR) get() = noGetter()
inline set(value) = setPadding(value, value, value, value)
inline var TextView.isSelectable: Boolean
get() = isTextSelectable
set(value) = setTextIsSelectable(value)
var TextView.textAppearance: Int
@Deprecated(NO_GETTER, level = ERROR) get() = noGetter()
set(value) = if (Build.VERSION.SDK_INT >= 23) setTextAppearance(value) else setTextAppearance(context, value)
var TextView.textSizeDimen: Int
@Deprecated(NO_GETTER, level = ERROR) get() = noGetter()
set(value) = setTextSize(TypedValue.COMPLEX_UNIT_PX, context.resources.getDimension(value))
var ImageView.image: Drawable?
inline get() = drawable
inline set(value) = setImageDrawable(value)
| apache-2.0 | a575a9208718680e875051d336558133 | 36.406977 | 113 | 0.749145 | 4.072152 | false | false | false | false |
alexbobp/LingeringLoot | src/main/kotlin/lingerloot/Util.kt | 1 | 3648 | package lingerloot
import com.elytradev.concrete.common.Either
import lingerloot.ruleengine.ItemPredicate
import net.minecraft.entity.Entity
import net.minecraft.entity.item.EntityItem
import net.minecraft.item.Item
import net.minecraft.util.ResourceLocation
import net.minecraft.util.math.BlockPos
import net.minecraft.world.WorldServer
import net.minecraftforge.fml.relauncher.ReflectionHelper
import java.util.*
inline fun <T> MutableIterable<T>.filterInPlace(filter: (T)->Boolean) {
val it = iterator()
while (it.hasNext())
if (!filter(it.next()))
it.remove()
}
fun EntityItem?.ifAlive(): EntityItem? {
return if (this != null && !this.isDead) this else null
}
val ageField by lazy { ReflectionHelper.findField(EntityItem::class.java, "age", "field_70292_b") }
fun EntityItem.extractAge(): Int { return ageField.get(this) as Int }
val pickupDelayField by lazy { ReflectionHelper.findField(EntityItem::class.java, "pickupDelay", "field_145804_b") }
fun EntityItem.extractPickupDelay(): Int { return pickupDelayField.get(this) as Int }
fun goldenSplit(number: Int): Collection<Int> {
val major = number/2
val minor = (.618*(number-major)).toInt()
return listOf(major, minor, number-major-minor)
.filter{it > 0}
}
fun detectCreativeGiveSecondTick(item: EntityItem) =
item.extractAge() == CREATIVE_GIVE_DESPAWN_TICK && item.extractPickupDelay() == 39
fun square(x: Double) = x*x
/**
* Simplified entity-block collision box checking for entities that are within their block vertically,
* and no more than one meter wide
*/
fun blocksIntersectingSmallEntity(entity: Entity, cylinder: Boolean): List<BlockPos> {
val offX = entity.posX - (entity.position.x + .5) // offsets from center of closest block
val offZ = entity.posZ - (entity.position.z + .5)
val absOffX = Math.abs(offX) // 0 - .5
val absOffZ = Math.abs(offZ)
val sigOffX = Math.signum(offX).toInt() // who got drunk and made signum return double?
val sigOffZ = Math.signum(offZ).toInt()
val farCorner = if (cylinder)
Math.sqrt(square(.5-absOffX) + square(.5-absOffZ)) <= entity.width/2
else
.5 - absOffX <= entity.width/2 && .5 - absOffZ <= entity.width/2
return listOf(
entity.position,
if (.5 - absOffX <= entity.width/2) entity.position.add(sigOffX, 0, 0) else null,
if (.5 - absOffZ <= entity.width/2) entity.position.add(0, 0, sigOffZ) else null,
if (farCorner) entity.position.add(sigOffX, 0, sigOffZ) else null
).filterNotNull()
.sortedBy {square(entity.posX - (it.x + .5)) + square(entity.posZ - (it.z + .5))}
}
/**
* returns a list containing intersecting blocks on this level followed by one level below,
* but with any AIR sorted to the end
*/
fun blockAreaOfEffectForEntityAirLast(world: WorldServer, entity: Entity, cylinder: Boolean): List<BlockPos> {
val topLayer = blocksIntersectingSmallEntity(entity, cylinder)
val filtered = (topLayer + topLayer.map{it.down()}).partition{world.isAirBlock(it)}
return filtered.second + filtered.first
}
fun lookupItem(s: String): Either<ItemPredicate, String> {
val itemName = s.takeWhile{it != '@'}
val damage = if (itemName.length == s.length)
null
else
s.substring(itemName.length + 1).toIntOrNull()
?: return Either.right("Invalid damage value for item \"$s\"")
val item = Item.REGISTRY.getObject(ResourceLocation(itemName)) ?: return Either.right("Item not found: \"$s\"")
return Either.left(ItemPredicate(item, damage))
}
val rand = Random() | lgpl-3.0 | 4977efea0cba5fdeff153ec14e6e27ee | 39.544444 | 116 | 0.6875 | 3.604743 | false | false | false | false |
pokk/SSFM | app/src/main/kotlin/taiwan/no1/app/ssfm/features/chart/RecyclerViewChartArtistHotTrackViewModel.kt | 1 | 3318 | package taiwan.no1.app.ssfm.features.chart
import android.databinding.ObservableBoolean
import android.databinding.ObservableField
import android.view.View
import com.hwangjr.rxbus.RxBus
import com.hwangjr.rxbus.annotation.Subscribe
import com.hwangjr.rxbus.annotation.Tag
import com.trello.rxlifecycle2.LifecycleProvider
import taiwan.no1.app.ssfm.features.base.BaseViewModel
import taiwan.no1.app.ssfm.misc.constants.RxBusTag
import taiwan.no1.app.ssfm.misc.constants.RxBusTag.VIEWMODEL_TRACK_CLICK
import taiwan.no1.app.ssfm.misc.constants.RxBusTag.VIEWMODEL_TRACK_LONG_CLICK
import taiwan.no1.app.ssfm.misc.extension.changeState
import taiwan.no1.app.ssfm.misc.utilies.devices.helper.music.MusicPlayerHelper
import taiwan.no1.app.ssfm.misc.utilies.devices.helper.music.playMusic
import taiwan.no1.app.ssfm.misc.utilies.devices.helper.music.playerHelper
import taiwan.no1.app.ssfm.models.entities.PlaylistItemEntity
import taiwan.no1.app.ssfm.models.usecases.AddPlaylistItemCase
import weian.cheng.mediaplayerwithexoplayer.MusicPlayerState
/**
*
* @author jieyi
* @since 10/29/17
*/
class RecyclerViewChartArtistHotTrackViewModel(private val addPlaylistItemCase: AddPlaylistItemCase,
private var item: PlaylistItemEntity,
private var index: Int) : BaseViewModel() {
val trackName by lazy { ObservableField<String>() }
val trackNumber by lazy { ObservableField<String>() }
val isPlaying by lazy { ObservableBoolean() }
private var clickedIndex = -1
init {
refreshView()
}
//region Lifecycle
override fun <E> onAttach(lifecycleProvider: LifecycleProvider<E>) {
super.onAttach(lifecycleProvider)
RxBus.get().register(this)
}
override fun onDetach() {
super.onDetach()
RxBus.get().unregister(this)
}
//endregion
fun setTrackItem(item: PlaylistItemEntity, index: Int) {
this.item = item
this.index = index
refreshView()
}
/**
* @param view
*
* @event_to [taiwan.no1.app.ssfm.features.chart.ChartArtistDetailFragment.addToPlaylist]
*/
fun trackOnClick(view: View) {
lifecycleProvider.playMusic(addPlaylistItemCase, item, index)
}
/**
* @param view
*
* @event_to [taiwan.no1.app.ssfm.features.chart.ChartActivity.openBottomSheet]
*/
fun trackOptionalOnClick(view: View) {
RxBus.get().post(VIEWMODEL_TRACK_LONG_CLICK, item)
}
@Subscribe(tags = [Tag(VIEWMODEL_TRACK_CLICK)])
fun changeToStopIcon(uri: String) = isPlaying.set(uri == item.trackUri)
@Subscribe(tags = [Tag(VIEWMODEL_TRACK_CLICK)])
fun notifyClickIndex(index: Integer) {
clickedIndex = index.toInt()
}
/**
* @param state
*
* @event_from [MusicPlayerHelper.setPlayerListener]
*/
@Subscribe(tags = [(Tag(RxBusTag.MUSICPLAYER_STATE_CHANGED))])
fun playerStateChanged(state: MusicPlayerState) = isPlaying.changeState(state, index, clickedIndex)
private fun refreshView() {
item.also {
isPlaying.set(playerHelper.isCurrentUri(it.trackUri) && playerHelper.isPlaying)
trackName.set(it.trackName)
trackNumber.set(index.toString())
}
}
} | apache-2.0 | a25fba3fd4fb92086d4fc7178e5a4bcc | 32.867347 | 103 | 0.6956 | 4.111524 | false | false | false | false |
Gazer/localshare | app/src/main/java/ar/com/p39/localshare/sharer/network/ShareServer.kt | 1 | 2336 | package ar.com.p39.localshare.sharer.network
import android.content.ContentResolver
import android.util.Log
import java.io.IOException
import ar.com.p39.localshare.sharer.models.FileShare
import fi.iki.elonen.NanoHTTPD
import java.util.concurrent.Executors
/**
* Handle HTTP Server stuff
*
* Provide interface fot sharing thinks over http.
*
* Created by gazer on 3/31/16.
*/
class ShareServer @Throws(IOException::class)
constructor(val contentResolver: ContentResolver, val bssid:String, val ip: String, val files: List<FileShare>) : NanoHTTPD(ip, 8080) {
init {
setAsyncRunner(BoundRunner(Executors.newFixedThreadPool(5)));
Log.d("SERVER", "Publishing URL : http://$ip:8080/sharer")
start()
}
override fun serve(session: NanoHTTPD.IHTTPSession): NanoHTTPD.Response {
val path = session.uri
if ("/sharer".equals(path)) {
return doSharer(session)
} else if (path.startsWith("/get")) {
val index = path.split("/").last().toInt()
return doFile(index)
}
return do404()
}
private fun doFile(index: Int): Response {
if (index >= files.size) {
return do404()
} else {
val file = files[index]
val stream = contentResolver.openInputStream(file.uri)
return newChunkedResponse(Response.Status.OK, file.contentType, stream)
}
}
private fun do404(): Response {
return NanoHTTPD.newFixedLengthResponse("Not Found")
}
fun doSharer(session: NanoHTTPD.IHTTPSession): NanoHTTPD.Response {
val params = session.parms
if (params["shareInfo"] != null) {
val files = files.mapIndexed {
index, it -> """{"name": "${it.name}", "size": ${it.size}, "contentType": "${it.contentType}", "url": "http://$ip:8080/get/$index"}"""
}.joinToString(",", "[", "]")
val body = "{\"ssid\": \"$bssid\", \"files\": $files}"
val r = NanoHTTPD.newFixedLengthResponse(body)
r.addHeader("Content-Type", "application/json")
return r
} else {
return redirectToGooglePlay()
}
}
private fun redirectToGooglePlay(): NanoHTTPD.Response {
return NanoHTTPD.newFixedLengthResponse("Redirect")
}
}
| apache-2.0 | bd1f7bc88e9616d2d13537f2f0fd95b5 | 31 | 150 | 0.612158 | 4.020654 | false | false | false | false |
bsmr-java/lwjgl3 | modules/templates/src/main/kotlin/org/lwjgl/opengl/templates/EXT_direct_state_access.kt | 1 | 65849 | /*
* Copyright LWJGL. All rights reserved.
* License terms: https://www.lwjgl.org/license
*/
package org.lwjgl.opengl.templates
import org.lwjgl.generator.*
import org.lwjgl.opengl.*
import org.lwjgl.opengl.BufferType.*
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.IN("mask", "")
)
void(
"PushClientAttribDefaultEXT",
"",
GLbitfield.IN("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.IN("matrixMode", ""),
Check(16)..const..GLfloat_p.IN("m", "")
)
void(
"MatrixLoaddEXT",
"",
GLenum.IN("matrixMode", ""),
Check(16)..const..GLdouble_p.IN("m", "")
)
void(
"MatrixMultfEXT",
"",
GLenum.IN("matrixMode", ""),
Check(16)..const..GLfloat_p.IN("m", "")
)
void(
"MatrixMultdEXT",
"",
GLenum.IN("matrixMode", ""),
Check(16)..const..GLdouble_p.IN("m", "")
)
void(
"MatrixLoadIdentityEXT",
"",
GLenum.IN("matrixMode", "")
)
void(
"MatrixRotatefEXT",
"",
GLenum.IN("matrixMode", ""),
GLfloat.IN("angle", ""),
GLfloat.IN("x", ""),
GLfloat.IN("y", ""),
GLfloat.IN("z", "")
)
void(
"MatrixRotatedEXT",
"",
GLenum.IN("matrixMode", ""),
GLdouble.IN("angle", ""),
GLdouble.IN("x", ""),
GLdouble.IN("y", ""),
GLdouble.IN("z", "")
)
void(
"MatrixScalefEXT",
"",
GLenum.IN("matrixMode", ""),
GLfloat.IN("x", ""),
GLfloat.IN("y", ""),
GLfloat.IN("z", "")
)
void(
"MatrixScaledEXT",
"",
GLenum.IN("matrixMode", ""),
GLdouble.IN("x", ""),
GLdouble.IN("y", ""),
GLdouble.IN("z", "")
)
void(
"MatrixTranslatefEXT",
"",
GLenum.IN("matrixMode", ""),
GLfloat.IN("x", ""),
GLfloat.IN("y", ""),
GLfloat.IN("z", "")
)
void(
"MatrixTranslatedEXT",
"",
GLenum.IN("matrixMode", ""),
GLdouble.IN("x", ""),
GLdouble.IN("y", ""),
GLdouble.IN("z", "")
)
void(
"MatrixOrthoEXT",
"",
GLenum.IN("matrixMode", ""),
GLdouble.IN("l", ""),
GLdouble.IN("r", ""),
GLdouble.IN("b", ""),
GLdouble.IN("t", ""),
GLdouble.IN("n", ""),
GLdouble.IN("f", "")
)
void(
"MatrixFrustumEXT",
"",
GLenum.IN("matrixMode", ""),
GLdouble.IN("l", ""),
GLdouble.IN("r", ""),
GLdouble.IN("b", ""),
GLdouble.IN("t", ""),
GLdouble.IN("n", ""),
GLdouble.IN("f", "")
)
void(
"MatrixPushEXT",
"",
GLenum.IN("matrixMode", "")
)
void(
"MatrixPopEXT",
"",
GLenum.IN("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.IN("texture", ""),
GLenum.IN("target", ""),
GLenum.IN("pname", ""),
GLint.IN("param", "")
)
void(
"TextureParameterivEXT",
"",
GLuint.IN("texture", ""),
GLenum.IN("target", ""),
GLenum.IN("pname", ""),
Check(4)..const..GLint_p.IN("param", "")
)
void(
"TextureParameterfEXT",
"",
GLuint.IN("texture", ""),
GLenum.IN("target", ""),
GLenum.IN("pname", ""),
GLfloat.IN("param", "")
)
void(
"TextureParameterfvEXT",
"",
GLuint.IN("texture", ""),
GLenum.IN("target", ""),
GLenum.IN("pname", ""),
Check(4)..const..GLfloat_p.IN("param", "")
)
void(
"TextureImage1DEXT",
"",
GLuint.IN("texture", ""),
GLenum.IN("target", ""),
GLint.IN("level", ""),
GLint.IN("internalformat", ""),
GLsizei.IN("width", ""),
GLint.IN("border", ""),
GLenum.IN("format", ""),
GLenum.IN("type", ""),
nullable..MultiType(
PointerMapping.DATA_SHORT, PointerMapping.DATA_INT, PointerMapping.DATA_FLOAT, PointerMapping.DATA_DOUBLE
)..PIXEL_UNPACK_BUFFER..const..void_p.IN("pixels", "")
)
void(
"TextureImage2DEXT",
"",
GLuint.IN("texture", ""),
GLenum.IN("target", ""),
GLint.IN("level", ""),
GLint.IN("internalformat", ""),
GLsizei.IN("width", ""),
GLsizei.IN("height", ""),
GLint.IN("border", ""),
GLenum.IN("format", ""),
GLenum.IN("type", ""),
nullable..MultiType(
PointerMapping.DATA_SHORT, PointerMapping.DATA_INT, PointerMapping.DATA_FLOAT, PointerMapping.DATA_DOUBLE
)..PIXEL_UNPACK_BUFFER..const..void_p.IN("pixels", "")
)
void(
"TextureSubImage1DEXT",
"",
GLuint.IN("texture", ""),
GLenum.IN("target", ""),
GLint.IN("level", ""),
GLint.IN("xoffset", ""),
GLsizei.IN("width", ""),
GLenum.IN("format", ""),
GLenum.IN("type", ""),
MultiType(
PointerMapping.DATA_SHORT, PointerMapping.DATA_INT, PointerMapping.DATA_FLOAT, PointerMapping.DATA_DOUBLE
)..PIXEL_UNPACK_BUFFER..const..void_p.IN("pixels", "")
)
void(
"TextureSubImage2DEXT",
"",
GLuint.IN("texture", ""),
GLenum.IN("target", ""),
GLint.IN("level", ""),
GLint.IN("xoffset", ""),
GLint.IN("yoffset", ""),
GLsizei.IN("width", ""),
GLsizei.IN("height", ""),
GLenum.IN("format", ""),
GLenum.IN("type", ""),
MultiType(
PointerMapping.DATA_SHORT, PointerMapping.DATA_INT, PointerMapping.DATA_FLOAT, PointerMapping.DATA_DOUBLE
)..PIXEL_UNPACK_BUFFER..const..void_p.IN("pixels", "")
)
void(
"CopyTextureImage1DEXT",
"",
GLuint.IN("texture", ""),
GLenum.IN("target", ""),
GLint.IN("level", ""),
GLenum.IN("internalformat", ""),
GLint.IN("x", ""),
GLint.IN("y", ""),
GLsizei.IN("width", ""),
GLint.IN("border", "")
)
void(
"CopyTextureImage2DEXT",
"",
GLuint.IN("texture", ""),
GLenum.IN("target", ""),
GLint.IN("level", ""),
GLenum.IN("internalformat", ""),
GLint.IN("x", ""),
GLint.IN("y", ""),
GLsizei.IN("width", ""),
GLsizei.IN("height", ""),
GLint.IN("border", "")
)
void(
"CopyTextureSubImage1DEXT",
"",
GLuint.IN("texture", ""),
GLenum.IN("target", ""),
GLint.IN("level", ""),
GLint.IN("xoffset", ""),
GLint.IN("x", ""),
GLint.IN("y", ""),
GLsizei.IN("width", "")
)
void(
"CopyTextureSubImage2DEXT",
"",
GLuint.IN("texture", ""),
GLenum.IN("target", ""),
GLint.IN("level", ""),
GLint.IN("xoffset", ""),
GLint.IN("yoffset", ""),
GLint.IN("x", ""),
GLint.IN("y", ""),
GLsizei.IN("width", ""),
GLsizei.IN("height", "")
)
void(
"GetTextureImageEXT",
"",
GLuint.IN("texture", ""),
GLenum.IN("target", ""),
GLint.IN("level", ""),
GLenum.IN("format", ""),
GLenum.IN("type", ""),
MultiType(PointerMapping.DATA_SHORT, PointerMapping.DATA_INT, PointerMapping.DATA_FLOAT, PointerMapping.DATA_DOUBLE)..PIXEL_PACK_BUFFER..void_p.OUT("pixels", "")
)
void(
"GetTextureParameterfvEXT",
"",
GLuint.IN("texture", ""),
GLenum.IN("target", ""),
GLenum.IN("pname", ""),
Check(1)..ReturnParam..GLfloat_p.OUT("params", "")
)
void(
"GetTextureParameterivEXT",
"",
GLuint.IN("texture", ""),
GLenum.IN("target", ""),
GLenum.IN("pname", ""),
Check(1)..ReturnParam..GLint_p.OUT("params", "")
)
void(
"GetTextureLevelParameterfvEXT",
"",
GLuint.IN("texture", ""),
GLenum.IN("target", ""),
GLint.IN("level", ""),
GLenum.IN("pname", ""),
Check(1)..ReturnParam..GLfloat_p.OUT("params", "")
)
void(
"GetTextureLevelParameterivEXT",
"",
GLuint.IN("texture", ""),
GLenum.IN("target", ""),
GLint.IN("level", ""),
GLenum.IN("pname", ""),
Check(1)..ReturnParam..GLint_p.OUT("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.IN("texture", ""),
GLenum.IN("target", ""),
GLint.IN("level", ""),
GLint.IN("internalformat", ""),
GLsizei.IN("width", ""),
GLsizei.IN("height", ""),
GLsizei.IN("depth", ""),
GLint.IN("border", ""),
GLenum.IN("format", ""),
GLenum.IN("type", ""),
nullable..MultiType(
PointerMapping.DATA_SHORT, PointerMapping.DATA_INT, PointerMapping.DATA_FLOAT, PointerMapping.DATA_DOUBLE
)..PIXEL_UNPACK_BUFFER..const..void_p.IN("pixels", "")
)
DependsOn("OpenGL12")..void(
"TextureSubImage3DEXT",
"",
GLuint.IN("texture", ""),
GLenum.IN("target", ""),
GLint.IN("level", ""),
GLint.IN("xoffset", ""),
GLint.IN("yoffset", ""),
GLint.IN("zoffset", ""),
GLsizei.IN("width", ""),
GLsizei.IN("height", ""),
GLsizei.IN("depth", ""),
GLenum.IN("format", ""),
GLenum.IN("type", ""),
MultiType(
PointerMapping.DATA_SHORT, PointerMapping.DATA_INT, PointerMapping.DATA_FLOAT, PointerMapping.DATA_DOUBLE
)..PIXEL_UNPACK_BUFFER..const..void_p.IN("pixels", "")
)
DependsOn("OpenGL12")..void(
"CopyTextureSubImage3DEXT",
"",
GLuint.IN("texture", ""),
GLenum.IN("target", ""),
GLint.IN("level", ""),
GLint.IN("xoffset", ""),
GLint.IN("yoffset", ""),
GLint.IN("zoffset", ""),
GLint.IN("x", ""),
GLint.IN("y", ""),
GLsizei.IN("width", ""),
GLsizei.IN("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.IN("texunit", ""),
GLenum.IN("target", ""),
GLuint.IN("texture", "")
)
DependsOn("OpenGL13")..void(
"MultiTexCoordPointerEXT",
"",
GLenum.IN("texunit", ""),
GLint.IN("size", ""),
GLenum.IN("type", ""),
GLsizei.IN("stride", ""),
ARRAY_BUFFER..MultiType(
PointerMapping.DATA_SHORT, PointerMapping.DATA_INT, PointerMapping.DATA_FLOAT
)..const..void_p.IN("pointer", "")
)
DependsOn("OpenGL13")..void(
"MultiTexEnvfEXT",
"",
GLenum.IN("texunit", ""),
GLenum.IN("target", ""),
GLenum.IN("pname", ""),
GLfloat.IN("param", "")
)
DependsOn("OpenGL13")..void(
"MultiTexEnvfvEXT",
"",
GLenum.IN("texunit", ""),
GLenum.IN("target", ""),
GLenum.IN("pname", ""),
Check(4)..const..GLfloat_p.IN("params", "")
)
DependsOn("OpenGL13")..void(
"MultiTexEnviEXT",
"",
GLenum.IN("texunit", ""),
GLenum.IN("target", ""),
GLenum.IN("pname", ""),
GLint.IN("param", "")
)
DependsOn("OpenGL13")..void(
"MultiTexEnvivEXT",
"",
GLenum.IN("texunit", ""),
GLenum.IN("target", ""),
GLenum.IN("pname", ""),
Check(4)..const..GLint_p.IN("params", "")
)
DependsOn("OpenGL13")..void(
"MultiTexGendEXT",
"",
GLenum.IN("texunit", ""),
GLenum.IN("coord", ""),
GLenum.IN("pname", ""),
GLdouble.IN("param", "")
)
DependsOn("OpenGL13")..void(
"MultiTexGendvEXT",
"",
GLenum.IN("texunit", ""),
GLenum.IN("coord", ""),
GLenum.IN("pname", ""),
Check(4)..const..GLdouble_p.IN("params", "")
)
DependsOn("OpenGL13")..void(
"MultiTexGenfEXT",
"",
GLenum.IN("texunit", ""),
GLenum.IN("coord", ""),
GLenum.IN("pname", ""),
GLfloat.IN("param", "")
)
DependsOn("OpenGL13")..void(
"MultiTexGenfvEXT",
"",
GLenum.IN("texunit", ""),
GLenum.IN("coord", ""),
GLenum.IN("pname", ""),
Check(4)..const..GLfloat_p.IN("params", "")
)
DependsOn("OpenGL13")..void(
"MultiTexGeniEXT",
"",
GLenum.IN("texunit", ""),
GLenum.IN("coord", ""),
GLenum.IN("pname", ""),
GLint.IN("param", "")
)
DependsOn("OpenGL13")..void(
"MultiTexGenivEXT",
"",
GLenum.IN("texunit", ""),
GLenum.IN("coord", ""),
GLenum.IN("pname", ""),
Check(4)..const..GLint_p.IN("params", "")
)
DependsOn("OpenGL13")..void(
"GetMultiTexEnvfvEXT",
"",
GLenum.IN("texunit", ""),
GLenum.IN("target", ""),
GLenum.IN("pname", ""),
Check(1)..ReturnParam..GLfloat_p.OUT("params", "")
)
DependsOn("OpenGL13")..void(
"GetMultiTexEnvivEXT",
"",
GLenum.IN("texunit", ""),
GLenum.IN("target", ""),
GLenum.IN("pname", ""),
Check(1)..ReturnParam..GLint_p.OUT("params", "")
)
DependsOn("OpenGL13")..void(
"GetMultiTexGendvEXT",
"",
GLenum.IN("texunit", ""),
GLenum.IN("coord", ""),
GLenum.IN("pname", ""),
Check(1)..ReturnParam..GLdouble_p.OUT("params", "")
)
DependsOn("OpenGL13")..void(
"GetMultiTexGenfvEXT",
"",
GLenum.IN("texunit", ""),
GLenum.IN("coord", ""),
GLenum.IN("pname", ""),
Check(1)..ReturnParam..GLfloat_p.OUT("params", "")
)
DependsOn("OpenGL13")..void(
"GetMultiTexGenivEXT",
"",
GLenum.IN("texunit", ""),
GLenum.IN("coord", ""),
GLenum.IN("pname", ""),
Check(1)..ReturnParam..GLint_p.OUT("params", "")
)
DependsOn("OpenGL13")..void(
"MultiTexParameteriEXT",
"",
GLenum.IN("texunit", ""),
GLenum.IN("target", ""),
GLenum.IN("pname", ""),
GLint.IN("param", "")
)
DependsOn("OpenGL13")..void(
"MultiTexParameterivEXT",
"",
GLenum.IN("texunit", ""),
GLenum.IN("target", ""),
GLenum.IN("pname", ""),
Check(4)..const..GLint_p.IN("param", "")
)
DependsOn("OpenGL13")..void(
"MultiTexParameterfEXT",
"",
GLenum.IN("texunit", ""),
GLenum.IN("target", ""),
GLenum.IN("pname", ""),
GLfloat.IN("param", "")
)
DependsOn("OpenGL13")..void(
"MultiTexParameterfvEXT",
"",
GLenum.IN("texunit", ""),
GLenum.IN("target", ""),
GLenum.IN("pname", ""),
Check(4)..const..GLfloat_p.IN("param", "")
)
DependsOn("OpenGL13")..void(
"MultiTexImage1DEXT",
"",
GLenum.IN("texunit", ""),
GLenum.IN("target", ""),
GLint.IN("level", ""),
GLint.IN("internalformat", ""),
GLsizei.IN("width", ""),
GLint.IN("border", ""),
GLenum.IN("format", ""),
GLenum.IN("type", ""),
nullable..MultiType(
PointerMapping.DATA_SHORT, PointerMapping.DATA_INT, PointerMapping.DATA_FLOAT, PointerMapping.DATA_DOUBLE
)..PIXEL_UNPACK_BUFFER..const..void_p.IN("pixels", "")
)
DependsOn("OpenGL13")..void(
"MultiTexImage2DEXT",
"",
GLenum.IN("texunit", ""),
GLenum.IN("target", ""),
GLint.IN("level", ""),
GLint.IN("internalformat", ""),
GLsizei.IN("width", ""),
GLsizei.IN("height", ""),
GLint.IN("border", ""),
GLenum.IN("format", ""),
GLenum.IN("type", ""),
nullable..MultiType(
PointerMapping.DATA_SHORT, PointerMapping.DATA_INT, PointerMapping.DATA_FLOAT, PointerMapping.DATA_DOUBLE
)..PIXEL_UNPACK_BUFFER..const..void_p.IN("pixels", "")
)
DependsOn("OpenGL13")..void(
"MultiTexSubImage1DEXT",
"",
GLenum.IN("texunit", ""),
GLenum.IN("target", ""),
GLint.IN("level", ""),
GLint.IN("xoffset", ""),
GLsizei.IN("width", ""),
GLenum.IN("format", ""),
GLenum.IN("type", ""),
MultiType(
PointerMapping.DATA_SHORT, PointerMapping.DATA_INT, PointerMapping.DATA_FLOAT, PointerMapping.DATA_DOUBLE
)..PIXEL_UNPACK_BUFFER..const..void_p.IN("pixels", "")
)
DependsOn("OpenGL13")..void(
"MultiTexSubImage2DEXT",
"",
GLenum.IN("texunit", ""),
GLenum.IN("target", ""),
GLint.IN("level", ""),
GLint.IN("xoffset", ""),
GLint.IN("yoffset", ""),
GLsizei.IN("width", ""),
GLsizei.IN("height", ""),
GLenum.IN("format", ""),
GLenum.IN("type", ""),
MultiType(
PointerMapping.DATA_SHORT, PointerMapping.DATA_INT, PointerMapping.DATA_FLOAT, PointerMapping.DATA_DOUBLE
)..PIXEL_UNPACK_BUFFER..const..void_p.IN("pixels", "")
)
DependsOn("OpenGL13")..void(
"CopyMultiTexImage1DEXT",
"",
GLenum.IN("texunit", ""),
GLenum.IN("target", ""),
GLint.IN("level", ""),
GLenum.IN("internalformat", ""),
GLint.IN("x", ""),
GLint.IN("y", ""),
GLsizei.IN("width", ""),
GLint.IN("border", "")
)
DependsOn("OpenGL13")..void(
"CopyMultiTexImage2DEXT",
"",
GLenum.IN("texunit", ""),
GLenum.IN("target", ""),
GLint.IN("level", ""),
GLenum.IN("internalformat", ""),
GLint.IN("x", ""),
GLint.IN("y", ""),
GLsizei.IN("width", ""),
GLsizei.IN("height", ""),
GLint.IN("border", "")
)
DependsOn("OpenGL13")..void(
"CopyMultiTexSubImage1DEXT",
"",
GLenum.IN("texunit", ""),
GLenum.IN("target", ""),
GLint.IN("level", ""),
GLint.IN("xoffset", ""),
GLint.IN("x", ""),
GLint.IN("y", ""),
GLsizei.IN("width", "")
)
DependsOn("OpenGL13")..void(
"CopyMultiTexSubImage2DEXT",
"",
GLenum.IN("texunit", ""),
GLenum.IN("target", ""),
GLint.IN("level", ""),
GLint.IN("xoffset", ""),
GLint.IN("yoffset", ""),
GLint.IN("x", ""),
GLint.IN("y", ""),
GLsizei.IN("width", ""),
GLsizei.IN("height", "")
)
DependsOn("OpenGL13")..void(
"GetMultiTexImageEXT",
"",
GLenum.IN("texunit", ""),
GLenum.IN("target", ""),
GLint.IN("level", ""),
GLenum.IN("format", ""),
GLenum.IN("type", ""),
MultiType(PointerMapping.DATA_SHORT, PointerMapping.DATA_INT, PointerMapping.DATA_FLOAT, PointerMapping.DATA_DOUBLE)..PIXEL_PACK_BUFFER..void_p.OUT("pixels", "")
)
DependsOn("OpenGL13")..void(
"GetMultiTexParameterfvEXT",
"",
GLenum.IN("texunit", ""),
GLenum.IN("target", ""),
GLenum.IN("pname", ""),
Check(1)..ReturnParam..GLfloat_p.OUT("params", "")
)
DependsOn("OpenGL13")..void(
"GetMultiTexParameterivEXT",
"",
GLenum.IN("texunit", ""),
GLenum.IN("target", ""),
GLenum.IN("pname", ""),
Check(1)..ReturnParam..GLint_p.OUT("params", "")
)
DependsOn("OpenGL13")..void(
"GetMultiTexLevelParameterfvEXT",
"",
GLenum.IN("texunit", ""),
GLenum.IN("target", ""),
GLint.IN("level", ""),
GLenum.IN("pname", ""),
Check(1)..ReturnParam..GLfloat_p.OUT("params", "")
)
DependsOn("OpenGL13")..void(
"GetMultiTexLevelParameterivEXT",
"",
GLenum.IN("texunit", ""),
GLenum.IN("target", ""),
GLint.IN("level", ""),
GLenum.IN("pname", ""),
Check(1)..ReturnParam..GLint_p.OUT("params", "")
)
DependsOn("OpenGL13")..void(
"MultiTexImage3DEXT",
"",
GLenum.IN("texunit", ""),
GLenum.IN("target", ""),
GLint.IN("level", ""),
GLint.IN("internalformat", ""),
GLsizei.IN("width", ""),
GLsizei.IN("height", ""),
GLsizei.IN("depth", ""),
GLint.IN("border", ""),
GLenum.IN("format", ""),
GLenum.IN("type", ""),
nullable..MultiType(
PointerMapping.DATA_SHORT, PointerMapping.DATA_INT, PointerMapping.DATA_FLOAT, PointerMapping.DATA_DOUBLE
)..PIXEL_UNPACK_BUFFER..const..void_p.IN("pixels", "")
)
DependsOn("OpenGL13")..void(
"MultiTexSubImage3DEXT",
"",
GLenum.IN("texunit", ""),
GLenum.IN("target", ""),
GLint.IN("level", ""),
GLint.IN("xoffset", ""),
GLint.IN("yoffset", ""),
GLint.IN("zoffset", ""),
GLsizei.IN("width", ""),
GLsizei.IN("height", ""),
GLsizei.IN("depth", ""),
GLenum.IN("format", ""),
GLenum.IN("type", ""),
MultiType(
PointerMapping.DATA_SHORT, PointerMapping.DATA_INT, PointerMapping.DATA_FLOAT, PointerMapping.DATA_DOUBLE
)..PIXEL_UNPACK_BUFFER..const..void_p.IN("pixels", "")
)
DependsOn("OpenGL13")..void(
"CopyMultiTexSubImage3DEXT",
"",
GLenum.IN("texunit", ""),
GLenum.IN("target", ""),
GLint.IN("level", ""),
GLint.IN("xoffset", ""),
GLint.IN("yoffset", ""),
GLint.IN("zoffset", ""),
GLint.IN("x", ""),
GLint.IN("y", ""),
GLsizei.IN("width", ""),
GLsizei.IN("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.IN("array", ""),
GLuint.IN("index", "")
)
DependsOn("OpenGL13")..void(
"DisableClientStateIndexedEXT",
"",
GLenum.IN("array", ""),
GLuint.IN("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.IN("array", ""),
GLuint.IN("index", "")
)
DependsOn("OpenGL30")..IgnoreMissing..void(
"DisableClientStateiEXT",
"",
GLenum.IN("array", ""),
GLuint.IN("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.IN("target", ""),
GLuint.IN("index", ""),
Check(1)..ReturnParam..GLfloat_p.OUT("params", "")
)
DependsOn("OpenGL13")..void(
"GetDoubleIndexedvEXT",
"",
GLenum.IN("target", ""),
GLuint.IN("index", ""),
Check(1)..ReturnParam..GLdouble_p.OUT("params", "")
)
DependsOn("OpenGL13")..void(
"GetPointerIndexedvEXT",
"",
GLenum.IN("target", ""),
GLuint.IN("index", ""),
Check(1)..ReturnParam..void_pp.OUT("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.IN("pname", ""),
GLuint.IN("index", ""),
Check(1)..ReturnParam..GLfloat_p.OUT("params", "")
)
DependsOn("OpenGL30")..IgnoreMissing..void(
"GetDoublei_vEXT",
"",
GLenum.IN("pname", ""),
GLuint.IN("index", ""),
Check(1)..ReturnParam..GLdouble_p.OUT("params", "")
)
DependsOn("OpenGL30")..IgnoreMissing..void(
"GetPointeri_vEXT",
"",
GLenum.IN("pname", ""),
GLuint.IN("index", ""),
Check(1)..ReturnParam..void_pp.OUT("params", "")
)
/*
OpenGL 1.2.1: Extend the functionality of these EXT_draw_buffers2
commands and queries for multitexture
*/
DependsOn("OpenGL13")..void(
"EnableIndexedEXT",
"",
GLenum.IN("cap", ""),
GLuint.IN("index", "")
)
DependsOn("OpenGL13")..void(
"DisableIndexedEXT",
"",
GLenum.IN("cap", ""),
GLuint.IN("index", "")
)
DependsOn("OpenGL13")..GLboolean(
"IsEnabledIndexedEXT",
"",
GLenum.IN("target", ""),
GLuint.IN("index", "")
)
DependsOn("OpenGL13")..void(
"GetIntegerIndexedvEXT",
"",
GLenum.IN("target", ""),
GLuint.IN("index", ""),
Check(1)..ReturnParam..GLint_p.OUT("params", "")
)
DependsOn("OpenGL13")..void(
"GetBooleanIndexedvEXT",
"",
GLenum.IN("target", ""),
GLuint.IN("index", ""),
Check(1)..ReturnParam..GLboolean_p.OUT("params", "")
)
/*
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.IN("program", ""),
GLenum.IN("target", ""),
GLenum.IN("format", ""),
AutoSize("string")..GLsizei.IN("len", ""),
const..void_p.IN("string", "")
)
DependsOn("GL_ARB_vertex_program")..void(
"NamedProgramLocalParameter4dEXT",
"",
GLuint.IN("program", ""),
GLenum.IN("target", ""),
GLuint.IN("index", ""),
GLdouble.IN("x", ""),
GLdouble.IN("y", ""),
GLdouble.IN("z", ""),
GLdouble.IN("w", "")
)
DependsOn("GL_ARB_vertex_program")..void(
"NamedProgramLocalParameter4dvEXT",
"",
GLuint.IN("program", ""),
GLenum.IN("target", ""),
GLuint.IN("index", ""),
Check(4)..const..GLdouble_p.IN("params", "")
)
DependsOn("GL_ARB_vertex_program")..void(
"NamedProgramLocalParameter4fEXT",
"",
GLuint.IN("program", ""),
GLenum.IN("target", ""),
GLuint.IN("index", ""),
GLfloat.IN("x", ""),
GLfloat.IN("y", ""),
GLfloat.IN("z", ""),
GLfloat.IN("w", "")
)
DependsOn("GL_ARB_vertex_program")..void(
"NamedProgramLocalParameter4fvEXT",
"",
GLuint.IN("program", ""),
GLenum.IN("target", ""),
GLuint.IN("index", ""),
Check(4)..const..GLfloat_p.IN("params", "")
)
DependsOn("GL_ARB_vertex_program")..void(
"GetNamedProgramLocalParameterdvEXT",
"",
GLuint.IN("program", ""),
GLenum.IN("target", ""),
GLuint.IN("index", ""),
Check(4)..GLdouble_p.OUT("params", "")
)
DependsOn("GL_ARB_vertex_program")..void(
"GetNamedProgramLocalParameterfvEXT",
"",
GLuint.IN("program", ""),
GLenum.IN("target", ""),
GLuint.IN("index", ""),
Check(4)..GLfloat_p.OUT("params", "")
)
DependsOn("GL_ARB_vertex_program")..void(
"GetNamedProgramivEXT",
"",
GLuint.IN("program", ""),
GLenum.IN("target", ""),
GLenum.IN("pname", ""),
ReturnParam..Check(1)..GLint_p.OUT("params", "")
)
DependsOn("GL_ARB_vertex_program")..void(
"GetNamedProgramStringEXT",
"",
GLuint.IN("program", ""),
GLenum.IN("target", ""),
GLenum.IN("pname", ""),
Check("glGetNamedProgramiEXT(program, target, ARBVertexProgram.GL_PROGRAM_LENGTH_ARB)", debug = true)..void_p.OUT("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.IN("texture", ""),
GLenum.IN("target", ""),
GLint.IN("level", ""),
GLenum.IN("internalformat", ""),
GLsizei.IN("width", ""),
GLsizei.IN("height", ""),
GLsizei.IN("depth", ""),
GLint.IN("border", ""),
AutoSize("data")..GLsizei.IN("imageSize", ""),
PIXEL_UNPACK_BUFFER..nullable..const..void_p.IN("data", "")
)
DependsOn("OpenGL13")..void(
"CompressedTextureImage2DEXT",
"",
GLuint.IN("texture", ""),
GLenum.IN("target", ""),
GLint.IN("level", ""),
GLenum.IN("internalformat", ""),
GLsizei.IN("width", ""),
GLsizei.IN("height", ""),
GLint.IN("border", ""),
AutoSize("data")..GLsizei.IN("imageSize", ""),
PIXEL_UNPACK_BUFFER..nullable..const..void_p.IN("data", "")
)
DependsOn("OpenGL13")..void(
"CompressedTextureImage1DEXT",
"",
GLuint.IN("texture", ""),
GLenum.IN("target", ""),
GLint.IN("level", ""),
GLenum.IN("internalformat", ""),
GLsizei.IN("width", ""),
GLint.IN("border", ""),
AutoSize("data")..GLsizei.IN("imageSize", ""),
PIXEL_UNPACK_BUFFER..nullable..const..void_p.IN("data", "")
)
DependsOn("OpenGL13")..void(
"CompressedTextureSubImage3DEXT",
"",
GLuint.IN("texture", ""),
GLenum.IN("target", ""),
GLint.IN("level", ""),
GLint.IN("xoffset", ""),
GLint.IN("yoffset", ""),
GLint.IN("zoffset", ""),
GLsizei.IN("width", ""),
GLsizei.IN("height", ""),
GLsizei.IN("depth", ""),
GLenum.IN("format", ""),
AutoSize("data")..GLsizei.IN("imageSize", ""),
PIXEL_UNPACK_BUFFER..const..void_p.IN("data", "")
)
DependsOn("OpenGL13")..void(
"CompressedTextureSubImage2DEXT",
"",
GLuint.IN("texture", ""),
GLenum.IN("target", ""),
GLint.IN("level", ""),
GLint.IN("xoffset", ""),
GLint.IN("yoffset", ""),
GLsizei.IN("width", ""),
GLsizei.IN("height", ""),
GLenum.IN("format", ""),
AutoSize("data")..GLsizei.IN("imageSize", ""),
PIXEL_UNPACK_BUFFER..const..void_p.IN("data", "")
)
DependsOn("OpenGL13")..void(
"CompressedTextureSubImage1DEXT",
"",
GLuint.IN("texture", ""),
GLenum.IN("target", ""),
GLint.IN("level", ""),
GLint.IN("xoffset", ""),
GLsizei.IN("width", ""),
GLenum.IN("format", ""),
AutoSize("data")..GLsizei.IN("imageSize", ""),
PIXEL_UNPACK_BUFFER..const..void_p.IN("data", "")
)
DependsOn("OpenGL13")..void(
"GetCompressedTextureImageEXT",
"",
GLuint.IN("texture", ""),
GLenum.IN("target", ""),
GLint.IN("level", ""),
Check(
expression = "glGetTextureLevelParameteriEXT(texture, target, level, GL13.GL_TEXTURE_COMPRESSED_IMAGE_SIZE)", debug = true
)..PIXEL_PACK_BUFFER..void_p.OUT("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.IN("texunit", ""),
GLenum.IN("target", ""),
GLint.IN("level", ""),
GLenum.IN("internalformat", ""),
GLsizei.IN("width", ""),
GLsizei.IN("height", ""),
GLsizei.IN("depth", ""),
GLint.IN("border", ""),
AutoSize("data")..GLsizei.IN("imageSize", ""),
PIXEL_UNPACK_BUFFER..nullable..const..void_p.IN("data", "")
)
DependsOn("OpenGL13")..void(
"CompressedMultiTexImage2DEXT",
"",
GLenum.IN("texunit", ""),
GLenum.IN("target", ""),
GLint.IN("level", ""),
GLenum.IN("internalformat", ""),
GLsizei.IN("width", ""),
GLsizei.IN("height", ""),
GLint.IN("border", ""),
AutoSize("data")..GLsizei.IN("imageSize", ""),
PIXEL_UNPACK_BUFFER..nullable..const..void_p.IN("data", "")
)
DependsOn("OpenGL13")..void(
"CompressedMultiTexImage1DEXT",
"",
GLenum.IN("texunit", ""),
GLenum.IN("target", ""),
GLint.IN("level", ""),
GLenum.IN("internalformat", ""),
GLsizei.IN("width", ""),
GLint.IN("border", ""),
AutoSize("data")..GLsizei.IN("imageSize", ""),
PIXEL_UNPACK_BUFFER..nullable..const..void_p.IN("data", "")
)
DependsOn("OpenGL13")..void(
"CompressedMultiTexSubImage3DEXT",
"",
GLenum.IN("texunit", ""),
GLenum.IN("target", ""),
GLint.IN("level", ""),
GLint.IN("xoffset", ""),
GLint.IN("yoffset", ""),
GLint.IN("zoffset", ""),
GLsizei.IN("width", ""),
GLsizei.IN("height", ""),
GLsizei.IN("depth", ""),
GLenum.IN("format", ""),
AutoSize("data")..GLsizei.IN("imageSize", ""),
PIXEL_UNPACK_BUFFER..const..void_p.IN("data", "")
)
DependsOn("OpenGL13")..void(
"CompressedMultiTexSubImage2DEXT",
"",
GLenum.IN("texunit", ""),
GLenum.IN("target", ""),
GLint.IN("level", ""),
GLint.IN("xoffset", ""),
GLint.IN("yoffset", ""),
GLsizei.IN("width", ""),
GLsizei.IN("height", ""),
GLenum.IN("format", ""),
AutoSize("data")..GLsizei.IN("imageSize", ""),
PIXEL_UNPACK_BUFFER..const..void_p.IN("data", "")
)
DependsOn("OpenGL13")..void(
"CompressedMultiTexSubImage1DEXT",
"",
GLenum.IN("texunit", ""),
GLenum.IN("target", ""),
GLint.IN("level", ""),
GLint.IN("xoffset", ""),
GLsizei.IN("width", ""),
GLenum.IN("format", ""),
AutoSize("data")..GLsizei.IN("imageSize", ""),
PIXEL_UNPACK_BUFFER..const..void_p.IN("data", "")
)
DependsOn("OpenGL13")..void(
"GetCompressedMultiTexImageEXT",
"",
GLenum.IN("texunit", ""),
GLenum.IN("target", ""),
GLint.IN("level", ""),
Check(
expression = "glGetMultiTexLevelParameteriEXT(texunit, target, level, GL13.GL_TEXTURE_COMPRESSED_IMAGE_SIZE)", debug = true
)..PIXEL_PACK_BUFFER..void_p.OUT("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.IN("matrixMode", ""),
Check(16)..const..GLfloat_p.IN("m", "")
)
DependsOn("OpenGL13")..void(
"MatrixLoadTransposedEXT",
"",
GLenum.IN("matrixMode", ""),
Check(16)..const..GLdouble_p.IN("m", "")
)
DependsOn("OpenGL13")..void(
"MatrixMultTransposefEXT",
"",
GLenum.IN("matrixMode", ""),
Check(16)..const..GLfloat_p.IN("m", "")
)
DependsOn("OpenGL13")..void(
"MatrixMultTransposedEXT",
"",
GLenum.IN("matrixMode", ""),
Check(16)..const..GLdouble_p.IN("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.IN("buffer", ""),
AutoSize("data")..GLsizeiptr.IN("size", ""),
optional..MultiType(
PointerMapping.DATA_SHORT,
PointerMapping.DATA_INT,
PointerMapping.DATA_FLOAT,
PointerMapping.DATA_DOUBLE
)..const..void_p.IN("data", ""),
GLenum.IN("usage", "")
)
DependsOn("OpenGL15")..void(
"NamedBufferSubDataEXT",
"",
GLuint.IN("buffer", ""),
GLintptr.IN("offset", ""),
AutoSize("data")..GLsizeiptr.IN("size", ""),
MultiType(
PointerMapping.DATA_SHORT,
PointerMapping.DATA_INT,
PointerMapping.DATA_FLOAT,
PointerMapping.DATA_DOUBLE
)..const..void_p.IN("data", "")
)
DependsOn("OpenGL15")..(MapPointer("glGetNamedBufferParameteriEXT(buffer, GL15.GL_BUFFER_SIZE)")..void_p)(
"MapNamedBufferEXT",
"",
GLuint.IN("buffer", ""),
GLenum.IN("access", "")
)
DependsOn("OpenGL15")..GLboolean(
"UnmapNamedBufferEXT",
"",
GLuint.IN("buffer", "")
)
DependsOn("OpenGL15")..void(
"GetNamedBufferParameterivEXT",
"",
GLuint.IN("buffer", ""),
GLenum.IN("pname", ""),
Check(1)..ReturnParam..GLint_p.OUT("params", "")
)
DependsOn("OpenGL15")..void(
"GetNamedBufferSubDataEXT",
"",
GLuint.IN("buffer", ""),
GLintptr.IN("offset", ""),
AutoSize("data")..GLsizeiptr.IN("size", ""),
MultiType(
PointerMapping.DATA_SHORT,
PointerMapping.DATA_INT,
PointerMapping.DATA_FLOAT,
PointerMapping.DATA_DOUBLE
)..void_p.OUT("data", "")
)
/*
OpenGL 2.0: New uniform commands add "Program" prefix to name and
add initial "uint program" parameter
*/
DependsOn("OpenGL20")..void(
"ProgramUniform1fEXT",
"",
GLuint.IN("program", ""),
GLint.IN("location", ""),
GLfloat.IN("v0", "")
)
DependsOn("OpenGL20")..void(
"ProgramUniform2fEXT",
"",
GLuint.IN("program", ""),
GLint.IN("location", ""),
GLfloat.IN("v0", ""),
GLfloat.IN("v1", "")
)
DependsOn("OpenGL20")..void(
"ProgramUniform3fEXT",
"",
GLuint.IN("program", ""),
GLint.IN("location", ""),
GLfloat.IN("v0", ""),
GLfloat.IN("v1", ""),
GLfloat.IN("v2", "")
)
DependsOn("OpenGL20")..void(
"ProgramUniform4fEXT",
"",
GLuint.IN("program", ""),
GLint.IN("location", ""),
GLfloat.IN("v0", ""),
GLfloat.IN("v1", ""),
GLfloat.IN("v2", ""),
GLfloat.IN("v3", "")
)
DependsOn("OpenGL20")..void(
"ProgramUniform1iEXT",
"",
GLuint.IN("program", ""),
GLint.IN("location", ""),
GLint.IN("v0", "")
)
DependsOn("OpenGL20")..void(
"ProgramUniform2iEXT",
"",
GLuint.IN("program", ""),
GLint.IN("location", ""),
GLint.IN("v0", ""),
GLint.IN("v1", "")
)
DependsOn("OpenGL20")..void(
"ProgramUniform3iEXT",
"",
GLuint.IN("program", ""),
GLint.IN("location", ""),
GLint.IN("v0", ""),
GLint.IN("v1", ""),
GLint.IN("v2", "")
)
DependsOn("OpenGL20")..void(
"ProgramUniform4iEXT",
"",
GLuint.IN("program", ""),
GLint.IN("location", ""),
GLint.IN("v0", ""),
GLint.IN("v1", ""),
GLint.IN("v2", ""),
GLint.IN("v3", "")
)
DependsOn("OpenGL20")..void(
"ProgramUniform1fvEXT",
"",
GLuint.IN("program", ""),
GLint.IN("location", ""),
AutoSize("value")..GLsizei.IN("count", ""),
const..GLfloat_p.IN("value", "")
)
DependsOn("OpenGL20")..void(
"ProgramUniform2fvEXT",
"",
GLuint.IN("program", ""),
GLint.IN("location", ""),
AutoSize(2, "value")..GLsizei.IN("count", ""),
const..GLfloat_p.IN("value", "")
)
DependsOn("OpenGL20")..void(
"ProgramUniform3fvEXT",
"",
GLuint.IN("program", ""),
GLint.IN("location", ""),
AutoSize(3, "value")..GLsizei.IN("count", ""),
const..GLfloat_p.IN("value", "")
)
DependsOn("OpenGL20")..void(
"ProgramUniform4fvEXT",
"",
GLuint.IN("program", ""),
GLint.IN("location", ""),
AutoSize(4, "value")..GLsizei.IN("count", ""),
const..GLfloat_p.IN("value", "")
)
DependsOn("OpenGL20")..void(
"ProgramUniform1ivEXT",
"",
GLuint.IN("program", ""),
GLint.IN("location", ""),
AutoSize("value")..GLsizei.IN("count", ""),
const..GLint_p.IN("value", "")
)
DependsOn("OpenGL20")..void(
"ProgramUniform2ivEXT",
"",
GLuint.IN("program", ""),
GLint.IN("location", ""),
AutoSize(2, "value")..GLsizei.IN("count", ""),
const..GLint_p.IN("value", "")
)
DependsOn("OpenGL20")..void(
"ProgramUniform3ivEXT",
"",
GLuint.IN("program", ""),
GLint.IN("location", ""),
AutoSize(3, "value")..GLsizei.IN("count", ""),
const..GLint_p.IN("value", "")
)
DependsOn("OpenGL20")..void(
"ProgramUniform4ivEXT",
"",
GLuint.IN("program", ""),
GLint.IN("location", ""),
AutoSize(4, "value")..GLsizei.IN("count", ""),
const..GLint_p.IN("value", "")
)
DependsOn("OpenGL20")..void(
"ProgramUniformMatrix2fvEXT",
"",
GLuint.IN("program", ""),
GLint.IN("location", ""),
AutoSize(2 x 2, "value")..GLsizei.IN("count", ""),
GLboolean.IN("transpose", ""),
const..GLfloat_p.IN("value", "")
)
DependsOn("OpenGL20")..void(
"ProgramUniformMatrix3fvEXT",
"",
GLuint.IN("program", ""),
GLint.IN("location", ""),
AutoSize(3 x 3, "value")..GLsizei.IN("count", ""),
GLboolean.IN("transpose", ""),
const..GLfloat_p.IN("value", "")
)
DependsOn("OpenGL20")..void(
"ProgramUniformMatrix4fvEXT",
"",
GLuint.IN("program", ""),
GLint.IN("location", ""),
AutoSize(4 x 4, "value")..GLsizei.IN("count", ""),
GLboolean.IN("transpose", ""),
const..GLfloat_p.IN("value", "")
)
/*
OpenGL 2.1: New uniform matrix commands add "Program" prefix to
name and add initial "uint program" parameter
*/
DependsOn("OpenGL21")..void(
"ProgramUniformMatrix2x3fvEXT",
"",
GLuint.IN("program", ""),
GLint.IN("location", ""),
AutoSize(2 x 3, "value")..GLsizei.IN("count", ""),
GLboolean.IN("transpose", ""),
const..GLfloat_p.IN("value", "")
)
DependsOn("OpenGL21")..void(
"ProgramUniformMatrix3x2fvEXT",
"",
GLuint.IN("program", ""),
GLint.IN("location", ""),
AutoSize(3 x 2, "value")..GLsizei.IN("count", ""),
GLboolean.IN("transpose", ""),
const..GLfloat_p.IN("value", "")
)
DependsOn("OpenGL21")..void(
"ProgramUniformMatrix2x4fvEXT",
"",
GLuint.IN("program", ""),
GLint.IN("location", ""),
AutoSize(2 x 4, "value")..GLsizei.IN("count", ""),
GLboolean.IN("transpose", ""),
const..GLfloat_p.IN("value", "")
)
DependsOn("OpenGL21")..void(
"ProgramUniformMatrix4x2fvEXT",
"",
GLuint.IN("program", ""),
GLint.IN("location", ""),
AutoSize(4 x 2, "value")..GLsizei.IN("count", ""),
GLboolean.IN("transpose", ""),
const..GLfloat_p.IN("value", "")
)
DependsOn("OpenGL21")..void(
"ProgramUniformMatrix3x4fvEXT",
"",
GLuint.IN("program", ""),
GLint.IN("location", ""),
AutoSize(3 x 4, "value")..GLsizei.IN("count", ""),
GLboolean.IN("transpose", ""),
const..GLfloat_p.IN("value", "")
)
DependsOn("OpenGL21")..void(
"ProgramUniformMatrix4x3fvEXT",
"",
GLuint.IN("program", ""),
GLint.IN("location", ""),
AutoSize(4 x 3, "value")..GLsizei.IN("count", ""),
GLboolean.IN("transpose", ""),
const..GLfloat_p.IN("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.IN("texture", ""),
GLenum.IN("target", ""),
GLenum.IN("internalformat", ""),
GLuint.IN("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.IN("texunit", ""),
GLenum.IN("target", ""),
GLenum.IN("internalformat", ""),
GLuint.IN("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.IN("texture", ""),
GLenum.IN("target", ""),
GLenum.IN("pname", ""),
Check(4)..const..GLint_p.IN("params", "")
)
DependsOn("GL_EXT_texture_integer")..void(
"TextureParameterIuivEXT",
"",
GLuint.IN("texture", ""),
GLenum.IN("target", ""),
GLenum.IN("pname", ""),
Check(4)..const..GLuint_p.IN("params", "")
)
DependsOn("GL_EXT_texture_integer")..void(
"GetTextureParameterIivEXT",
"",
GLuint.IN("texture", ""),
GLenum.IN("target", ""),
GLenum.IN("pname", ""),
Check(1)..ReturnParam..GLint_p.OUT("params", "")
)
DependsOn("GL_EXT_texture_integer")..void(
"GetTextureParameterIuivEXT",
"",
GLuint.IN("texture", ""),
GLenum.IN("target", ""),
GLenum.IN("pname", ""),
Check(1)..ReturnParam..GLuint_p.OUT("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.IN("texunit", ""),
GLenum.IN("target", ""),
GLenum.IN("pname", ""),
Check(4)..const..GLint_p.IN("params", "")
)
DependsOn("GL_EXT_texture_integer")..void(
"MultiTexParameterIuivEXT",
"",
GLenum.IN("texunit", ""),
GLenum.IN("target", ""),
GLenum.IN("pname", ""),
Check(4)..const..GLuint_p.IN("params", "")
)
DependsOn("GL_EXT_texture_integer")..void(
"GetMultiTexParameterIivEXT",
"",
GLenum.IN("texunit", ""),
GLenum.IN("target", ""),
GLenum.IN("pname", ""),
Check(1)..ReturnParam..GLint_p.OUT("params", "")
)
DependsOn("GL_EXT_texture_integer")..void(
"GetMultiTexParameterIuivEXT",
"",
GLenum.IN("texunit", ""),
GLenum.IN("target", ""),
GLenum.IN("pname", ""),
Check(1)..ReturnParam..GLuint_p.OUT("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.IN("program", ""),
GLint.IN("location", ""),
GLuint.IN("v0", "")
)
DependsOn("GL_EXT_gpu_shader4")..void(
"ProgramUniform2uiEXT",
"",
GLuint.IN("program", ""),
GLint.IN("location", ""),
GLuint.IN("v0", ""),
GLuint.IN("v1", "")
)
DependsOn("GL_EXT_gpu_shader4")..void(
"ProgramUniform3uiEXT",
"",
GLuint.IN("program", ""),
GLint.IN("location", ""),
GLuint.IN("v0", ""),
GLuint.IN("v1", ""),
GLuint.IN("v2", "")
)
DependsOn("GL_EXT_gpu_shader4")..void(
"ProgramUniform4uiEXT",
"",
GLuint.IN("program", ""),
GLint.IN("location", ""),
GLuint.IN("v0", ""),
GLuint.IN("v1", ""),
GLuint.IN("v2", ""),
GLuint.IN("v3", "")
)
DependsOn("GL_EXT_gpu_shader4")..void(
"ProgramUniform1uivEXT",
"",
GLuint.IN("program", ""),
GLint.IN("location", ""),
AutoSize("value")..GLsizei.IN("count", ""),
const..GLuint_p.IN("value", "")
)
DependsOn("GL_EXT_gpu_shader4")..void(
"ProgramUniform2uivEXT",
"",
GLuint.IN("program", ""),
GLint.IN("location", ""),
AutoSize(2, "value")..GLsizei.IN("count", ""),
const..GLuint_p.IN("value", "")
)
DependsOn("GL_EXT_gpu_shader4")..void(
"ProgramUniform3uivEXT",
"",
GLuint.IN("program", ""),
GLint.IN("location", ""),
AutoSize(3, "value")..GLsizei.IN("count", ""),
const..GLuint_p.IN("value", "")
)
DependsOn("GL_EXT_gpu_shader4")..void(
"ProgramUniform4uivEXT",
"",
GLuint.IN("program", ""),
GLint.IN("location", ""),
AutoSize(4, "value")..GLsizei.IN("count", ""),
const..GLuint_p.IN("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.IN("program", ""),
GLenum.IN("target", ""),
GLuint.IN("index", ""),
AutoSize(4, "params")..GLsizei.IN("count", ""),
const..GLfloat_p.IN("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.IN("program", ""),
GLenum.IN("target", ""),
GLuint.IN("index", ""),
GLint.IN("x", ""),
GLint.IN("y", ""),
GLint.IN("z", ""),
GLint.IN("w", "")
)
DependsOn("GL_NV_gpu_program4")..void(
"NamedProgramLocalParameterI4ivEXT",
"",
GLuint.IN("program", ""),
GLenum.IN("target", ""),
GLuint.IN("index", ""),
Check(4)..const..GLint_p.IN("params", "")
)
DependsOn("GL_NV_gpu_program4")..void(
"NamedProgramLocalParametersI4ivEXT",
"",
GLuint.IN("program", ""),
GLenum.IN("target", ""),
GLuint.IN("index", ""),
AutoSize(4, "params")..GLsizei.IN("count", ""),
const..GLint_p.IN("params", "")
)
DependsOn("GL_NV_gpu_program4")..void(
"NamedProgramLocalParameterI4uiEXT",
"",
GLuint.IN("program", ""),
GLenum.IN("target", ""),
GLuint.IN("index", ""),
GLuint.IN("x", ""),
GLuint.IN("y", ""),
GLuint.IN("z", ""),
GLuint.IN("w", "")
)
DependsOn("GL_NV_gpu_program4")..void(
"NamedProgramLocalParameterI4uivEXT",
"",
GLuint.IN("program", ""),
GLenum.IN("target", ""),
GLuint.IN("index", ""),
Check(4)..const..GLuint_p.IN("params", "")
)
DependsOn("GL_NV_gpu_program4")..void(
"NamedProgramLocalParametersI4uivEXT",
"",
GLuint.IN("program", ""),
GLenum.IN("target", ""),
GLuint.IN("index", ""),
AutoSize(4, "params")..GLsizei.IN("count", ""),
const..GLuint_p.IN("params", "")
)
DependsOn("GL_NV_gpu_program4")..void(
"GetNamedProgramLocalParameterIivEXT",
"",
GLuint.IN("program", ""),
GLenum.IN("target", ""),
GLuint.IN("index", ""),
Check(4)..GLint_p.OUT("params", "")
)
DependsOn("GL_NV_gpu_program4")..void(
"GetNamedProgramLocalParameterIuivEXT",
"",
GLuint.IN("program", ""),
GLenum.IN("target", ""),
GLuint.IN("index", ""),
Check(4)..GLuint_p.OUT("params", "")
)
/*
OpenGL 3.0: New renderbuffer commands add "Named" prefix to name
and replace "enum target" with "uint renderbuffer"
*/
DependsOn("OpenGL30")..void(
"NamedRenderbufferStorageEXT",
"",
GLuint.IN("renderbuffer", ""),
GLenum.IN("internalformat", ""),
GLsizei.IN("width", ""),
GLsizei.IN("height", "")
)
DependsOn("OpenGL30")..void(
"GetNamedRenderbufferParameterivEXT",
"",
GLuint.IN("renderbuffer", ""),
GLenum.IN("pname", ""),
Check(1)..ReturnParam..GLint_p.OUT("params", "")
)
/*
OpenGL 3.0: New renderbuffer commands add "Named"
prefix to name and replace "enum target" with "uint renderbuffer"
*/
DependsOn("OpenGL30")..void(
"NamedRenderbufferStorageMultisampleEXT",
"",
GLuint.IN("renderbuffer", ""),
GLsizei.IN("samples", ""),
GLenum.IN("internalformat", ""),
GLsizei.IN("width", ""),
GLsizei.IN("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.IN("renderbuffer", ""),
GLsizei.IN("coverageSamples", ""),
GLsizei.IN("colorSamples", ""),
GLenum.IN("internalformat", ""),
GLsizei.IN("width", ""),
GLsizei.IN("height", "")
)
/*
OpenGL 3.0: New framebuffer commands add "Named" prefix to name
and replace "enum target" with "uint framebuffer"
*/
DependsOn("OpenGL30")..GLenum(
"CheckNamedFramebufferStatusEXT",
"",
GLuint.IN("framebuffer", ""),
GLenum.IN("target", "")
)
DependsOn("OpenGL30")..void(
"NamedFramebufferTexture1DEXT",
"",
GLuint.IN("framebuffer", ""),
GLenum.IN("attachment", ""),
GLenum.IN("textarget", ""),
GLuint.IN("texture", ""),
GLint.IN("level", "")
)
DependsOn("OpenGL30")..void(
"NamedFramebufferTexture2DEXT",
"",
GLuint.IN("framebuffer", ""),
GLenum.IN("attachment", ""),
GLenum.IN("textarget", ""),
GLuint.IN("texture", ""),
GLint.IN("level", "")
)
DependsOn("OpenGL30")..void(
"NamedFramebufferTexture3DEXT",
"",
GLuint.IN("framebuffer", ""),
GLenum.IN("attachment", ""),
GLenum.IN("textarget", ""),
GLuint.IN("texture", ""),
GLint.IN("level", ""),
GLint.IN("zoffset", "")
)
DependsOn("OpenGL30")..void(
"NamedFramebufferRenderbufferEXT",
"",
GLuint.IN("framebuffer", ""),
GLenum.IN("attachment", ""),
GLenum.IN("renderbuffertarget", ""),
GLuint.IN("renderbuffer", "")
)
DependsOn("OpenGL30")..void(
"GetNamedFramebufferAttachmentParameterivEXT",
"",
GLuint.IN("framebuffer", ""),
GLenum.IN("attachment", ""),
GLenum.IN("pname", ""),
Check(1)..ReturnParam..GLint_p.OUT("params", "")
)
/*
OpenGL 3.0: New texture commands add "Texture" within name and
replace "enum target" with "uint texture"
*/
DependsOn("OpenGL30")..void(
"GenerateTextureMipmapEXT",
"",
GLuint.IN("texture", ""),
GLenum.IN("target", "")
)
/*
OpenGL 3.0: New texture commands add "MultiTex" within name and
replace "enum target" with "enum texunit"
*/
DependsOn("OpenGL30")..void(
"GenerateMultiTexMipmapEXT",
"",
GLenum.IN("texunit", ""),
GLenum.IN("target", "")
)
// OpenGL 3.0: New framebuffer commands
DependsOn("OpenGL30")..void(
"FramebufferDrawBufferEXT",
"",
GLuint.IN("framebuffer", ""),
GLenum.IN("mode", "")
)
DependsOn("OpenGL30")..void(
"FramebufferDrawBuffersEXT",
"",
GLuint.IN("framebuffer", ""),
AutoSize("bufs")..GLsizei.IN("n", ""),
const..GLenum_p.IN("bufs", "")
)
DependsOn("OpenGL30")..void(
"FramebufferReadBufferEXT",
"",
GLuint.IN("framebuffer", ""),
GLenum.IN("mode", "")
)
// OpenGL 3.0: New framebuffer query
DependsOn("OpenGL30")..void(
"GetFramebufferParameterivEXT",
"",
GLuint.IN("framebuffer", ""),
GLenum.IN("pname", ""),
Check(1)..ReturnParam..GLint_p.OUT("param", "")
)
// OpenGL 3.0: New buffer data copy command
DependsOn("OpenGL30")..void(
"NamedCopyBufferSubDataEXT",
"",
GLuint.IN("readBuffer", ""),
GLuint.IN("writeBuffer", ""),
GLintptr.IN("readOffset", ""),
GLintptr.IN("writeOffset", ""),
GLsizeiptr.IN("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.IN("framebuffer", ""),
GLenum.IN("attachment", ""),
GLuint.IN("texture", ""),
GLint.IN("level", "")
)
DependsOn("ext.contains(\"GL_EXT_geometry_shader4\") || ext.contains(\"GL_NV_gpu_program4\")")..void(
"NamedFramebufferTextureLayerEXT",
"",
GLuint.IN("framebuffer", ""),
GLenum.IN("attachment", ""),
GLuint.IN("texture", ""),
GLint.IN("level", ""),
GLint.IN("layer", "")
)
DependsOn("ext.contains(\"GL_EXT_geometry_shader4\") || ext.contains(\"GL_NV_gpu_program4\")")..void(
"NamedFramebufferTextureFaceEXT",
"",
GLuint.IN("framebuffer", ""),
GLenum.IN("attachment", ""),
GLuint.IN("texture", ""),
GLint.IN("level", ""),
GLenum.IN("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.IN("texture", ""),
GLenum.IN("target", ""),
GLuint.IN("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.IN("texunit", ""),
GLenum.IN("target", ""),
GLuint.IN("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.IN("vaobj", ""),
GLuint.IN("buffer", ""),
GLint.IN("size", ""),
GLenum.IN("type", ""),
GLsizei.IN("stride", ""),
GLintptr.IN("offset", "")
)
DependsOn("OpenGL30")..void(
"VertexArrayColorOffsetEXT",
"",
GLuint.IN("vaobj", ""),
GLuint.IN("buffer", ""),
GLint.IN("size", ""),
GLenum.IN("type", ""),
GLsizei.IN("stride", ""),
GLintptr.IN("offset", "")
)
DependsOn("OpenGL30")..void(
"VertexArrayEdgeFlagOffsetEXT",
"",
GLuint.IN("vaobj", ""),
GLuint.IN("buffer", ""),
GLsizei.IN("stride", ""),
GLintptr.IN("offset", "")
)
DependsOn("OpenGL30")..void(
"VertexArrayIndexOffsetEXT",
"",
GLuint.IN("vaobj", ""),
GLuint.IN("buffer", ""),
GLenum.IN("type", ""),
GLsizei.IN("stride", ""),
GLintptr.IN("offset", "")
)
DependsOn("OpenGL30")..void(
"VertexArrayNormalOffsetEXT",
"",
GLuint.IN("vaobj", ""),
GLuint.IN("buffer", ""),
GLenum.IN("type", ""),
GLsizei.IN("stride", ""),
GLintptr.IN("offset", "")
)
DependsOn("OpenGL30")..void(
"VertexArrayTexCoordOffsetEXT",
"",
GLuint.IN("vaobj", ""),
GLuint.IN("buffer", ""),
GLint.IN("size", ""),
GLenum.IN("type", ""),
GLsizei.IN("stride", ""),
GLintptr.IN("offset", "")
)
DependsOn("OpenGL30")..void(
"VertexArrayMultiTexCoordOffsetEXT",
"",
GLuint.IN("vaobj", ""),
GLuint.IN("buffer", ""),
GLenum.IN("texunit", ""),
GLint.IN("size", ""),
GLenum.IN("type", ""),
GLsizei.IN("stride", ""),
GLintptr.IN("offset", "")
)
DependsOn("OpenGL30")..void(
"VertexArrayFogCoordOffsetEXT",
"",
GLuint.IN("vaobj", ""),
GLuint.IN("buffer", ""),
GLenum.IN("type", ""),
GLsizei.IN("stride", ""),
GLintptr.IN("offset", "")
)
DependsOn("OpenGL30")..void(
"VertexArraySecondaryColorOffsetEXT",
"",
GLuint.IN("vaobj", ""),
GLuint.IN("buffer", ""),
GLint.IN("size", ""),
GLenum.IN("type", ""),
GLsizei.IN("stride", ""),
GLintptr.IN("offset", "")
)
DependsOn("OpenGL30")..void(
"VertexArrayVertexAttribOffsetEXT",
"",
GLuint.IN("vaobj", ""),
GLuint.IN("buffer", ""),
GLuint.IN("index", ""),
GLint.IN("size", ""),
GLenum.IN("type", ""),
GLboolean.IN("normalized", ""),
GLsizei.IN("stride", ""),
GLintptr.IN("offset", "")
)
DependsOn("OpenGL30")..void(
"VertexArrayVertexAttribIOffsetEXT",
"",
GLuint.IN("vaobj", ""),
GLuint.IN("buffer", ""),
GLuint.IN("index", ""),
GLint.IN("size", ""),
GLenum.IN("type", ""),
GLsizei.IN("stride", ""),
GLintptr.IN("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.IN("vaobj", ""),
GLenum.IN("array", "")
)
DependsOn("OpenGL30")..void(
"DisableVertexArrayEXT",
"",
GLuint.IN("vaobj", ""),
GLenum.IN("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.IN("vaobj", ""),
GLuint.IN("index", "")
)
DependsOn("OpenGL30")..void(
"DisableVertexArrayAttribEXT",
"",
GLuint.IN("vaobj", ""),
GLuint.IN("index", "")
)
// OpenGL 3.0: New queries for vertex array objects
DependsOn("OpenGL30")..void(
"GetVertexArrayIntegervEXT",
"",
GLuint.IN("vaobj", ""),
GLenum.IN("pname", ""),
Check(1)..ReturnParam..GLint_p.OUT("param", "")
)
DependsOn("OpenGL30")..void(
"GetVertexArrayPointervEXT",
"",
GLuint.IN("vaobj", ""),
GLenum.IN("pname", ""),
Check(1)..ReturnParam..void_pp.OUT("param", "")
)
DependsOn("OpenGL30")..void(
"GetVertexArrayIntegeri_vEXT",
"",
GLuint.IN("vaobj", ""),
GLuint.IN("index", ""),
GLenum.IN("pname", ""),
Check(1)..ReturnParam..GLint_p.OUT("param", "")
)
DependsOn("OpenGL30")..void(
"GetVertexArrayPointeri_vEXT",
"",
GLuint.IN("vaobj", ""),
GLuint.IN("index", ""),
GLenum.IN("pname", ""),
Check(1)..ReturnParam..void_pp.OUT("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")..void_p)(
"MapNamedBufferRangeEXT",
"",
GLuint.IN("buffer", ""),
GLintptr.IN("offset", ""),
GLsizeiptr.IN("length", ""),
GLbitfield.IN("access", "")
)
DependsOn("OpenGL30")..void(
"FlushMappedNamedBufferRangeEXT",
"",
GLuint.IN("buffer", ""),
GLintptr.IN("offset", ""),
GLsizeiptr.IN("length", "")
)
} | bsd-3-clause | 6937bbe886ec7f86be9e1a6571b5e882 | 22.83279 | 163 | 0.627193 | 3.290476 | false | false | false | false |
EmmyLua/IntelliJ-EmmyLua | src/main/java/com/tang/intellij/lua/psi/parser/LuaStatementParser.kt | 2 | 12121 | /*
* Copyright (c) 2017. tangzx([email protected])
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.tang.intellij.lua.psi.parser
import com.intellij.lang.PsiBuilder
import com.intellij.lang.parser.GeneratedParserUtilBase
import com.intellij.psi.tree.IElementType
import com.tang.intellij.lua.psi.LuaParserUtil
import com.tang.intellij.lua.psi.LuaTypes.*
object LuaStatementParser : GeneratedParserUtilBase() {
fun parseStatement(b: PsiBuilder, l: Int): PsiBuilder.Marker? {
return when (b.tokenType) {
DO -> parseDoStatement(b, l)
IF -> parseIfStatement(b, l)
WHILE -> parseWhileStatement(b, l)
REPEAT -> parseRepeatStatement(b, l)
DOUBLE_COLON -> parseLabelStatement(b)
GOTO -> parseGotoStatement(b)
BREAK -> parseBreakStatement(b)
RETURN -> parseReturnStatement(b, l)
LOCAL -> parseLocalDef(b, l)
FOR -> parseForStatement(b, l)
FUNCTION -> parseFunctionStatement(b, l)
SEMI -> parseEmptyStatement(b)
else -> parseOtherStatement(b, l)
}
}
private fun parseDoStatement(b: PsiBuilder, l: Int): PsiBuilder.Marker {
val m = b.mark()
b.advanceLexer() // do
// block
LuaParserUtil.lazyBlock(b, l)
expectError(b, END) { "'end'" } // end
doneStat(b, m, DO_STAT)
return m
}
// 'if' expr 'then' <<lazyBlock>> ('elseif' expr 'then' <<lazyBlock>>)* ('else' <<lazyBlock>>)? 'end'
private fun parseIfStatement(b: PsiBuilder, l: Int): PsiBuilder.Marker? {
val m = b.mark()
b.advanceLexer() // if
// expr
expectExpr(b, l + 1)
// then
expectError(b, THEN) { "'then'" }
// block
LuaParserUtil.lazyBlock(b, l)
// elseif
while (b.tokenType == ELSEIF) {
b.advanceLexer()
expectExpr(b, l + 1)
expectError(b, THEN) { "'then'" }
LuaParserUtil.lazyBlock(b, l)
}
// else
if (b.tokenType == ELSE) {
b.advanceLexer()
LuaParserUtil.lazyBlock(b, l)
}
expectError(b, END) { "'end'" }
doneStat(b, m, IF_STAT)
return m
}
// 'while' expr 'do' <<lazyBlock>> 'end'
private fun parseWhileStatement(b: PsiBuilder, l: Int): PsiBuilder.Marker {
val m = b.mark()
b.advanceLexer() // while
expectExpr(b, l + 1) // expr
expectError(b, DO) { "'do'" }
// block
LuaParserUtil.lazyBlock(b, l)
expectError(b, END) { "'end'" } // end
doneStat(b, m, WHILE_STAT)
return m
}
// 'repeat' <<lazyBlock>> 'until' expr
private fun parseRepeatStatement(b: PsiBuilder, l: Int): PsiBuilder.Marker {
val m = b.mark()
b.advanceLexer() // repeat
// block
LuaParserUtil.lazyBlock(b, l)
expectError(b, UNTIL) { "'until'" }
expectExpr(b, l + 1) // expr
doneStat(b, m, REPEAT_STAT)
return m
}
// '::' ID '::'
private fun parseLabelStatement(b: PsiBuilder): PsiBuilder.Marker {
val m = b.mark()
b.advanceLexer() // ::
expectError(b, ID) { "ID" }
expectError(b, DOUBLE_COLON) { "'::'" } // ::
doneStat(b, m, LABEL_STAT)
return m
}
// forAStat ::= 'for' paramNameDef '=' expr ',' expr (',' expr)? 'do' <<lazyBlock>> 'end'
// forBStat ::= 'for' parList 'in' exprList 'do' <<lazyBlock>> 'end'
private fun parseForStatement(b: PsiBuilder, l: Int): PsiBuilder.Marker {
val m = b.mark()
b.advanceLexer() // for
val nameCount = expectParamNameOrList(b)
val type = if (nameCount > 1 || b.tokenType == IN) { // forBStat
expectError(b, IN) { "'in'" }
expectExprList(b, l)
FOR_B_STAT
} else { // forAStat
expectError(b, ASSIGN) { "'='" }
expectExpr(b, l + 1) // expr
expectError(b, COMMA) { "','" }
expectExpr(b, l + 1) // expr
if (b.tokenType == COMMA) {
b.advanceLexer() // ,
expectExpr(b, l + 1) // expr
}
FOR_A_STAT
}
expectError(b, DO) { "'do'" } // do
LuaParserUtil.lazyBlock(b, l) // block
expectError(b, END) { "'end'" } // do
doneStat(b, m, type)
return m
}
private fun expectParamName(b: PsiBuilder, error: Boolean = true): PsiBuilder.Marker? {
if (b.tokenType == ID) {
val m = b.mark()
b.advanceLexer()
m.done(PARAM_NAME_DEF)
return m
} else if (error) b.error("ID expected")
return null
}
private fun expectParamNameOrList(b: PsiBuilder): Int {
var nameCount = 0
val firstName = expectParamName(b)
if (firstName != null) {
nameCount++
while (b.tokenType == COMMA) {
b.advanceLexer()
expectParamName(b)
nameCount++
}
}
return nameCount
}
private fun parseBreakStatement(b: PsiBuilder): PsiBuilder.Marker {
val m = b.mark()
b.advanceLexer()
doneStat(b, m, BREAK_STAT)
return m
}
private fun parseReturnStatement(b: PsiBuilder, l: Int): PsiBuilder.Marker {
val m = b.mark()
b.advanceLexer()
expectExprList(b, l, false)
doneStat(b, m, RETURN_STAT)
return m
}
private fun parseLocalDef(b: PsiBuilder, l: Int): PsiBuilder.Marker {
return if (b.lookAhead(1) == FUNCTION)
parseLocalFunction(b, l)
else
parseLocal(b, l)
}
private fun parseLocalFunction(b: PsiBuilder, l: Int): PsiBuilder.Marker {
val m = b.mark()
b.advanceLexer() //local
b.advanceLexer() //function
expectError(b, ID) { "ID" }
parseFuncBody(b, l)
doneStat(b, m, LOCAL_FUNC_DEF)
return m
}
// Lua 5.4
private fun parseAttribute(b: PsiBuilder): PsiBuilder.Marker? {
if (b.tokenType == LT) {
val m = b.mark()
b.advanceLexer()
expectError(b, ID) { "ID" }
expectError(b, GT) { ">" }
m.done(ATTRIBUTE)
return m
}
return null
}
private fun parseNameList(b: PsiBuilder): PsiBuilder.Marker? {
var m = b.mark()
if (expectError(b, ID) { "ID" }) {
m.done(NAME_DEF)
parseAttribute(b)
while (b.tokenType == COMMA) {
b.advanceLexer()
val nameDef = b.mark()
if (expectError(b, ID) { "ID" }) {
nameDef.done(NAME_DEF)
parseAttribute(b)
} else nameDef.drop()
}
m = m.precede()
}
m.done(NAME_LIST)
return m
}
private fun parseLocal(b: PsiBuilder, l: Int): PsiBuilder.Marker {
val m = b.mark()
b.advanceLexer() // local
parseNameList(b)
if (b.tokenType == ASSIGN) {
b.advanceLexer()
val exprList = b.mark()
if (LuaExpressionParser.parseExprList(b, l + 1) == null)
b.error("Expression expected")
exprList.done(EXPR_LIST)
}
doneStat(b, m, LOCAL_DEF)
return m
}
fun parseFuncBody(b: PsiBuilder, l: Int): PsiBuilder.Marker {
val m = b.mark()
if (b.tokenType !== LPAREN) {
m.error("'(' expected")
return m
}
b.advanceLexer()
// param list
val def = expectParamName(b, false)
while (def != null) {
if (expect(b, COMMA)) {
if (expectParamName(b, false) == null && !expect(b, ELLIPSIS)) {
b.error("ID or '...' expected")
}
} else break
}
// (...)
if (def == null) {
expect(b, ELLIPSIS)
}
expectError(b, RPAREN) { "')'" }
// block
LuaParserUtil.lazyBlock(b, l)
expectError(b, END) { "'end'" }
m.done(FUNC_BODY)
return m
}
private fun parseGotoStatement(b: PsiBuilder): PsiBuilder.Marker {
val m = b.mark()
b.advanceLexer()
expectError(b, ID) { "ID" }
doneStat(b, m, GOTO_STAT)
return m
}
private fun parseFunctionStatement(b: PsiBuilder, l: Int): PsiBuilder.Marker {
val m = b.mark()
b.advanceLexer() // function
var type = FUNC_DEF
if (b.tokenType == ID) {
val ahead = b.lookAhead(1)
if (ahead != DOT && ahead != COLON) {
type = FUNC_DEF
b.advanceLexer() // ID
} else {
type = CLASS_METHOD_DEF
// name expr
val nameExpr = b.mark()
b.advanceLexer()
nameExpr.done(NAME_EXPR)
var c = nameExpr
// .ID
while (b.tokenType == DOT || b.tokenType == COLON) {
b.advanceLexer()
expectError(b, ID) { "ID" }
val next = b.tokenType
if (next == DOT || next == COLON) {
c = c.precede()
c.done(INDEX_EXPR)
} else break
}
// .ID | :ID
c = c.precede()
c.done(CLASS_METHOD_NAME)
}
} else b.error("ID expected")
parseFuncBody(b, l + 1)
doneStat(b, m, type)
return m
}
private fun parseOtherStatement(b: PsiBuilder, l: Int): PsiBuilder.Marker? {
val expr = LuaExpressionParser.parseExpr(b, l + 1)
if (expr != null) {
// check ass
val last = b.latestDoneMarker
when (last?.tokenType) {
NAME_EXPR, INDEX_EXPR -> {
var c = expr
var isAssignment = false
while (b.tokenType == COMMA) {
isAssignment = true
b.advanceLexer() // ,
expectExpr(b, l + 1)
}
// =
if (isAssignment) {
c = c.precede()
c.done(VAR_LIST)
expectError(b, ASSIGN) { "'='" }
} else if (b.tokenType == ASSIGN) {
c = c.precede()
c.done(VAR_LIST)
b.advanceLexer()
isAssignment = true
}
if (isAssignment) {
expectExprList(b, l + 1)
val m = c.precede()
doneStat(b, m, ASSIGN_STAT)
return m
}
}
}
val m = expr.precede()
doneStat(b, m, EXPR_STAT)
return m
}
return null
}
private fun parseEmptyStatement(b: PsiBuilder): PsiBuilder.Marker? {
val m = b.mark()
while (b.tokenType == SEMI) {
b.advanceLexer() // ;
}
done(m, EMPTY_STAT)
return m
}
private fun doneStat(b:PsiBuilder, m: PsiBuilder.Marker, type: IElementType) {
expect(b, SEMI)
done(m, type)
}
} | apache-2.0 | 95eaf48dffa3cba8a24b635d55f54add | 27.65721 | 105 | 0.490554 | 4.099087 | false | false | false | false |
mirjalal/MickiNet | app/src/main/kotlin/com/talmir/mickinet/screens/main/fragments/DeviceDetailFragment.kt | 1 | 4358 | package com.talmir.mickinet.screens.main.fragments
import android.content.Context
import android.content.DialogInterface
import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.appcompat.app.AlertDialog
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentActivity
import androidx.lifecycle.Observer
import com.google.android.material.snackbar.Snackbar
import com.talmir.mickinet.R
import com.talmir.mickinet.databinding.DeviceNameChangeLayoutBinding
import com.talmir.mickinet.databinding.FragmentDeviceDetailsBinding
import com.talmir.mickinet.helpers.DeviceNameChangerUtil
import com.talmir.mickinet.repository.Repository
/**
* A [Fragment] subclass to show user's device information in main page.
*/
class DeviceDetailFragment : Fragment() {
private lateinit var fragmentActivity: FragmentActivity
private lateinit var binding: FragmentDeviceDetailsBinding
override fun onAttach(context: Context) {
super.onAttach(context)
fragmentActivity = context as FragmentActivity
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
binding = FragmentDeviceDetailsBinding.inflate(inflater, container, false)
/**
* Lines below we set initial values of some properties.
* Otherwise, we will get [NullPointerException]. We'll
* get device's real information just after observer gets
* the data.
*/
binding.deviceName = "---"
binding.deviceStatus = -1
binding.deviceMacAddress = "---"
binding.deviceInfoHolder.setOnClickListener { showDeviceNameChangeDialog() }
// subscribe to deviceInfo changes to get device information
Repository.instance().deviceInfo.observe(fragmentActivity, Observer {
it.run {
binding.deviceName = name
binding.deviceStatus = status
binding.deviceMacAddress = macAddress
}
})
return binding.root
}
private fun showDeviceNameChangeDialog() {
val deviceNameChangeViewBinding = DeviceNameChangeLayoutBinding.inflate(layoutInflater, null, false)
val alert: AlertDialog = AlertDialog.Builder(fragmentActivity).create()
deviceNameChangeViewBinding.newDeviceName.addTextChangedListener(object : TextWatcher {
override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
// nothing special to do
}
override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {
if (s.toString().isEmpty()) {
deviceNameChangeViewBinding.newDeviceNameParent.error = getString(R.string.provide_device_name_error)
alert.getButton(DialogInterface.BUTTON_POSITIVE).isEnabled = false
} else {
deviceNameChangeViewBinding.newDeviceNameParent.error = null
alert.getButton(DialogInterface.BUTTON_POSITIVE).isEnabled = true
}
}
override fun afterTextChanged(s: Editable?) {
// nothing special to do
}
})
alert.setTitle(R.string.change_device_name)
alert.setView(deviceNameChangeViewBinding.root)
alert.setButton(DialogInterface.BUTTON_POSITIVE, getString(R.string.confirm_device_name_change)) { _: DialogInterface?, _: Int ->
alert.dismiss()
/** check if device name changed successfully */
if (DeviceNameChangerUtil.changeDeviceName(fragmentActivity, deviceNameChangeViewBinding.newDeviceName.text.toString()))
Snackbar.make(binding.root, R.string.device_name_change_successful, Snackbar.LENGTH_LONG).show()
else
Snackbar.make(binding.root, R.string.device_name_change_unsuccessful, Snackbar.LENGTH_LONG).show()
}
alert.setButton(DialogInterface.BUTTON_NEGATIVE, getString(R.string.cancel)) { _, _ -> alert.dismiss() }
alert.show()
/** initially disable POSITIVE_BUTTON */
alert.getButton(DialogInterface.BUTTON_POSITIVE).isEnabled = false
}
}
| gpl-3.0 | a68d5efab2d477749bdbc0b1279e0cb1 | 42.58 | 137 | 0.691831 | 4.991982 | false | false | false | false |
kenrube/Fantlab-client | app/src/main/kotlin/ru/fantlab/android/ui/base/BaseDialogFragment.kt | 2 | 3483 | package ru.fantlab.android.ui.base
import android.annotation.SuppressLint
import android.app.Dialog
import android.content.Context
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.annotation.LayoutRes
import androidx.annotation.StringRes
import androidx.appcompat.view.ContextThemeWrapper
import androidx.fragment.app.DialogFragment
import com.evernote.android.state.StateSaver
import net.grandcentrix.thirtyinch.TiDialogFragment
import ru.fantlab.android.R
import ru.fantlab.android.helper.AppHelper
import ru.fantlab.android.ui.base.mvp.BaseMvp
import ru.fantlab.android.ui.base.mvp.presenter.BasePresenter
abstract class BaseDialogFragment<V : BaseMvp.View, P : BasePresenter<V>>
: TiDialogFragment<P, V>(), BaseMvp.View {
protected var callback: BaseMvp.View? = null
@LayoutRes
protected abstract fun fragmentLayout(): Int
protected abstract fun onFragmentCreated(view: View, savedInstanceState: Bundle?)
override fun onAttach(context: Context) {
super.onAttach(context)
if (context is BaseMvp.View) {
callback = context
}
}
override fun onDetach() {
super.onDetach()
callback = null
}
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
StateSaver.saveInstanceState(this, outState)
presenter.onSaveInstanceState(outState)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
if (AppHelper.isNightMode(resources)) {
setStyle(DialogFragment.STYLE_NO_TITLE, R.style.DialogThemeDark)
} else {
setStyle(DialogFragment.STYLE_NO_TITLE, R.style.DialogThemeLight)
}
if (savedInstanceState != null && !savedInstanceState.isEmpty) {
StateSaver.restoreInstanceState(this, savedInstanceState)
presenter.onRestoreInstanceState(savedInstanceState)
}
}
@SuppressLint("RestrictedApi")
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
if (fragmentLayout() != 0) {
val contextThemeWrapper = ContextThemeWrapper(context, context?.theme)
val themeAwareInflater = inflater.cloneInContext(contextThemeWrapper)
return themeAwareInflater.inflate(fragmentLayout(), container, false)
}
return super.onCreateView(inflater, container, savedInstanceState)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
onFragmentCreated(view, savedInstanceState)
}
override fun showProgress(@StringRes resId: Int, cancelable: Boolean) {
callback?.showProgress(resId, cancelable)
}
override fun hideProgress() {
callback?.hideProgress()
}
override fun showMessage(@StringRes titleRes: Int, @StringRes msgRes: Int) {
callback?.showMessage(titleRes, msgRes)
}
override fun showMessage(titleRes: String, msgRes: String?) {
callback?.showMessage(titleRes, msgRes)
}
override fun showErrorMessage(msgRes: String?) {
callback?.showErrorMessage(msgRes)
}
override fun isLoggedIn(): Boolean = callback?.isLoggedIn() ?: false
override fun onRequireLogin() {
callback?.onRequireLogin()
}
override fun onLogoutPressed() {
callback?.onLogoutPressed()
}
override fun onThemeChanged() {
callback?.onThemeChanged()
}
override fun onOpenSettings() {
callback?.onOpenSettings()
}
override fun onOpenUrlInBrowser(url: String) {
callback?.onOpenUrlInBrowser(url)
}
override fun onScrollTop(index: Int) {
}
} | gpl-3.0 | c01d96a3af1cbf8027d399913c567530 | 27.793388 | 113 | 0.7795 | 4.073684 | false | false | false | false |
SiimKinks/sqlitemagic | sqlitemagic-tests/another-submodule/src/main/java/com/siimkinks/sqlitemagic/another/Author.kt | 1 | 733 | package com.siimkinks.sqlitemagic.another
import com.siimkinks.sqlitemagic.Utils
import com.siimkinks.sqlitemagic.annotation.Id
import com.siimkinks.sqlitemagic.annotation.Index
import com.siimkinks.sqlitemagic.annotation.Table
import java.util.*
@Table
data class Author(
@Id val id: Long? = null,
val firstName: String,
@Index
val lastName: String,
val booksWritten: Int,
val active: Boolean
) {
companion object {
fun newRandom(): Author {
val r = Random()
return Author(
id = r.nextLong(),
firstName = Utils.randomTableName(),
lastName = Utils.randomTableName(),
booksWritten = r.nextInt(),
active = r.nextBoolean()
)
}
}
} | apache-2.0 | a63142f88a15ce2ade85fac732497549 | 23.466667 | 49 | 0.6603 | 4.236994 | false | false | false | false |
firebase/snippets-android | dl-invites/app/src/main/java/com/google/firebase/dynamicinvites/kotlin/view/ShareDialogFragment.kt | 1 | 3840 | package com.google.firebase.dynamicinvites.kotlin.view
import android.content.Context
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.google.android.material.bottomsheet.BottomSheetDialogFragment
import com.google.firebase.dynamicinvites.R
import com.google.firebase.dynamicinvites.kotlin.presenter.CopyPresenter
import com.google.firebase.dynamicinvites.kotlin.presenter.EmailPresenter
import com.google.firebase.dynamicinvites.kotlin.presenter.InvitePresenter
import com.google.firebase.dynamicinvites.kotlin.presenter.MessagePresenter
import com.google.firebase.dynamicinvites.kotlin.presenter.MorePresenter
import com.google.firebase.dynamicinvites.kotlin.presenter.SocialPresenter
import com.google.firebase.dynamicinvites.kotlin.util.DynamicLinksUtil
/**
* A fragment that shows a list of items as a modal bottom sheet.
*
*
* You can show this modal bottom sheet from your activity like this:
*
* <pre>
* ShareDialogFragment.newInstance().show(getSupportFragmentManager(), "dialog");
</pre> *
*
*
* You activity (or fragment) needs to implement [ShareDialogFragment.Listener].
*/
class ShareDialogFragment : BottomSheetDialogFragment() {
private var listener: Listener? = null
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return inflater.inflate(R.layout.fragment_item_list_dialog, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
val content = DynamicLinksUtil.generateInviteContent()
val presenters = listOf(
EmailPresenter(true, content),
SocialPresenter(true, content),
MessagePresenter(true, content),
CopyPresenter(true, content),
MorePresenter(true, content)
)
val recycler = view.findViewById<RecyclerView>(R.id.recycler)
recycler.layoutManager = LinearLayoutManager(context)
recycler.adapter = ItemAdapter(presenters)
}
override fun onAttach(context: Context) {
super.onAttach(context)
val parent = parentFragment
listener = (parent ?: context) as Listener
}
override fun onDetach() {
listener = null
super.onDetach()
}
interface Listener {
fun onItemClicked(presenter: InvitePresenter)
}
private inner class ViewHolder(inflater: LayoutInflater, parent: ViewGroup) :
RecyclerView.ViewHolder(inflater.inflate(R.layout.item_share_method, parent, false)) {
fun bind(presenter: InvitePresenter) {
itemView.findViewById<TextView>(R.id.itemName).text = presenter.name
itemView.findViewById<ImageView>(R.id.itemIcon).setImageResource(presenter.icon)
itemView.setOnClickListener {
listener?.onItemClicked(presenter)
dismiss()
}
}
}
private inner class ItemAdapter(private val items: List<InvitePresenter>) :
RecyclerView.Adapter<ViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
return ViewHolder(LayoutInflater.from(parent.context), parent)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val presenter = items[position]
holder.bind(presenter)
}
override fun getItemCount() = items.size
}
companion object {
fun newInstance(): ShareDialogFragment {
return ShareDialogFragment()
}
}
}
| apache-2.0 | 1c6d2bb2f9a29c02e682d360b5fb1571 | 33.594595 | 94 | 0.707031 | 4.954839 | false | false | false | false |
Jire/Arrowhead | src/main/kotlin/org/jire/arrowhead/Keys.kt | 1 | 3012 | /*
* Copyright 2016 Thomas Nappo
*
* 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("Keys")
package org.jire.arrowhead
import com.sun.jna.Platform
import org.jire.arrowhead.windows.User32
/**
* Returns the key state of the specified virtual key code.
*
* @param virtualKeyCode The key code of which to check the state.
* @throws UnsupportedOperationException If the platform is not supported.
*/
fun keyState(virtualKeyCode: Int): Int = when {
Platform.isWindows() || Platform.isWindowsCE() -> User32.GetKeyState(virtualKeyCode).toInt()
else -> throw UnsupportedOperationException("Unsupported platform (osType=${Platform.getOSType()}")
}
/**
* Checks whether or not the key state of the specified virtual key code is pressed.
*
* @param virtualKeyCode The key code of which to check the state.
* @return `true` if the key is pressed, `false` otherwise.
* @throws UnsupportedOperationException If the platform is not supported.
*/
fun keyPressed(virtualKeyCode: Int) = keyState(virtualKeyCode) < 0
/**
* Checks whether or not the key state of the specified virtual key code is pressed,
* then runs the specified action code block.
*
* @param virtualKeyCode The key code of which to check the state.
* @param action The code to run if the key is pressed.
* @return `true` if the key is pressed, `false` otherwise.
* @throws UnsupportedOperationException If the platform is not supported.
*/
inline fun keyPressed(virtualKeyCode: Int, action: () -> Unit) = if (keyPressed(virtualKeyCode)) {
action()
true
} else false
/**
* Checks whether or not the key state of the specified virtual key code is released (not pressed).
*
* @param virtualKeyCode The key code of which to check the state.
* @return `false` if the key is pressed, `true` otherwise.
* @throws UnsupportedOperationException If the platform is not supported.
*/
fun keyReleased(virtualKeyCode: Int) = !keyPressed(virtualKeyCode)
/**
* Checks whether or not the key state of the specified virtual key code is released (not pressed),
* then runs the specified action code block.
*
* @param virtualKeyCode The key code of which to check the state.
* @param action The code to run if the key is released (not pressed).
* @return `false` if the key is pressed, `true` otherwise.
* @throws UnsupportedOperationException If the platform is not supported.
*/
inline fun keyReleased(virtualKeyCode: Int, action: () -> Unit) = if (keyReleased(virtualKeyCode)) {
action()
true
} else false | apache-2.0 | f272db27d8975d76cb099015c6cce089 | 37.139241 | 100 | 0.742696 | 4.097959 | false | false | false | false |
walleth/walleth | app/src/main/java/org/walleth/data/RoomTypeConverters.kt | 1 | 1263 | package org.walleth.data
import androidx.room.TypeConverter
import org.kethereum.model.Address
import org.kethereum.model.ChainId
import java.math.BigInteger
import java.util.*
class RoomTypeConverters {
/** Address */
@TypeConverter
fun addressFromString(value: String?) = if (value == null) null else Address(value)
@TypeConverter
fun addressToString(address: Address?) = address?.hex
/** Date */
@TypeConverter
fun dateFromLong(value: Long?) = if (value == null) null else Date(value)
@TypeConverter
fun dateToLong(date: Date?) = date?.time
/** BigInteger */
@TypeConverter
fun bigintegerFromByteArray(value: ByteArray?) = if (value == null) null else BigInteger(value)
@TypeConverter
fun bigIntegerToByteArray(bigInteger: BigInteger?) = bigInteger?.toByteArray()
/** List<String> */
@TypeConverter
fun stringListFromString(value: String?) = value?.split("%!%")?.filter { it.isNotBlank() }
@TypeConverter
fun stringListToString(value: List<String>?) = value?.joinToString("%!%")
/** List<String> */
@TypeConverter
fun longToChainId(value: Long?) = value?.let { ChainId(it) }
@TypeConverter
fun chainIdToLong(value: ChainId?) = value?.value
} | gpl-3.0 | 385a1ccea8a5f8216e886f56b09e81f4 | 24.795918 | 99 | 0.683294 | 4.168317 | false | false | false | false |
spkingr/50-android-kotlin-projects-in-100-days | ProjectImagePuzzle/app/src/main/java/me/liuqingwen/android/projectimagepuzzle/MainActivity.kt | 1 | 4986 | package me.liuqingwen.android.projectimagepuzzle
import android.Manifest
import android.app.Activity
import android.content.Intent
import android.content.pm.ActivityInfo
import android.content.res.AssetManager
import android.net.Uri
import android.os.Bundle
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.isVisible
import com.zhihu.matisse.Matisse
import com.zhihu.matisse.MimeType
import com.zhihu.matisse.internal.entity.CaptureStrategy
import es.dmoral.toasty.Toasty
import kotlinx.android.synthetic.main.layout_activity_main.*
import me.liuqingwen.android.projectimagepuzzle.util.MyGlideEngine
import org.jetbrains.anko.AnkoLogger
import org.jetbrains.anko.ctx
import pub.devrel.easypermissions.EasyPermissions
class MainActivity() : AppCompatActivity(), EasyPermissions.PermissionCallbacks, FragmentImageList.IFragmentInteractionListener, FragmentImagePuzzle.IFragmentInteractionListener, AnkoLogger
{
companion object
{
const val ASSET_DIRECTORY_NAME = "sampleImages"
const val PROVIDER_AUTHORITY = "me.liuqingwen.fileProvider"
private const val REQUEST_CODE = 100
private const val REQUEST_RESULT = 101
}
override val assetManager: AssetManager? get() = this.assets
private val isHomeFragment get() = this.supportFragmentManager.backStackEntryCount == 0
private val permissions = arrayOf(Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE)
override fun onSelectImagePath(path: String)
{
val fragment = FragmentImagePuzzle.newInstance(path)
this.supportFragmentManager
.beginTransaction()
.addToBackStack(null)
.replace(R.id.container, fragment)
.commit()
}
private fun onSelectImageFromMedia(uri: Uri)
{
val fragment = FragmentImagePuzzle.newInstance(uri)
this.supportFragmentManager
.beginTransaction()
.addToBackStack(null)
.replace(R.id.container, fragment)
.commit()
}
override fun onCreate(savedInstanceState: Bundle?)
{
super.onCreate(savedInstanceState)
this.setContentView(R.layout.layout_activity_main)
this.init()
}
private fun init()
{
this.setSupportActionBar(this.toolbar)
this.supportActionBar?.title = "Image Puzzle"
this.supportActionBar?.hide()
this.buttonImage.setOnClickListener { this.chooseMedia() }
this.buttonCamera.setOnClickListener { this.chooseMedia(true) }
this.supportFragmentManager.addOnBackStackChangedListener {
this.displayButtons(this.isHomeFragment)
}
this.supportFragmentManager
.beginTransaction()
.replace(R.id.container, FragmentImageList.newInstance())
.commit()
}
private fun chooseMedia(isCameraType: Boolean = false)
{
if (EasyPermissions.hasPermissions(this.ctx, *this.permissions))
{
this.onPermissionsGranted(MainActivity.REQUEST_CODE, arrayListOf())
}
else
{
EasyPermissions.requestPermissions(this, "Permissions for next step.", MainActivity.REQUEST_CODE, *this.permissions)
}
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?)
{
super.onActivityResult(requestCode, resultCode, data)
if (requestCode == MainActivity.REQUEST_RESULT && resultCode == Activity.RESULT_OK)
{
val result = Matisse.obtainResult(data)
val uri = result.first()!!
this.onSelectImageFromMedia(uri)
}
}
override fun onPermissionsDenied(requestCode: Int, perms: MutableList<String>)
{
if (requestCode == MainActivity.REQUEST_CODE)
{
Toasty.error(this.ctx, "Permissions denied!", Toast.LENGTH_SHORT, true).show()
}
}
override fun onPermissionsGranted(requestCode: Int, perms: MutableList<String>)
{
if (requestCode == MainActivity.REQUEST_CODE)
{
Matisse.from(this)
.choose(MimeType.of(MimeType.GIF, MimeType.JPEG, MimeType.PNG))
.capture(true)
.captureStrategy(CaptureStrategy(true, MainActivity.PROVIDER_AUTHORITY))
.countable(true)
.maxSelectable(1)
.restrictOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED)
.thumbnailScale(0.75f)
.imageEngine(MyGlideEngine())
.forResult(MainActivity.REQUEST_RESULT)
}
}
private fun displayButtons(show: Boolean = true)
{
this.buttonImage.isVisible = show
this.buttonCamera.isVisible = show
}
} | mit | 6b8cae4e3183ddd93c928b0935118fb0 | 35.137681 | 189 | 0.659647 | 5.006024 | false | false | false | false |
segmentio/analytics-android | analytics/src/test/java/com/segment/analytics/CartographerTest.kt | 1 | 18548 | /**
* The MIT License (MIT)
*
* Copyright (c) 2014 Segment.io, Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.segment.analytics
import com.google.common.collect.ImmutableMap
import java.io.IOException
import java.io.Reader
import java.io.StringWriter
import java.util.UUID
import kotlin.collections.LinkedHashMap
import kotlin.jvm.Throws
import org.assertj.core.api.Assertions.assertThat
import org.assertj.core.api.Assertions.fail
import org.assertj.core.data.MapEntry
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.annotation.Config
@RunWith(RobolectricTestRunner::class)
@Config(manifest = Config.NONE)
class CartographerTest {
lateinit var cartographer: Cartographer
@Before
fun setUp() {
cartographer = Cartographer.Builder().lenient(false).prettyPrint(true).build()
}
@Test
@Throws(IOException::class)
fun encodePrimitives() {
val map = ImmutableMap.builder<String, Any>()
.put("byte", 32.toByte())
.put("boolean", true)
.put("short", 100.toShort())
.put("int", 1)
.put("long", 43L)
.put("float", 23f)
.put("double", Math.PI)
.put("char", 'a')
.put("String", "string")
.build()
assertThat(cartographer.toJson(map))
.isEqualTo(
"""
|{
| "byte": 32,
| "boolean": true,
| "short": 100,
| "int": 1,
| "long": 43,
| "float": 23.0,
| "double": 3.141592653589793,
| "char": "a",
| "String": "string"
|}
""".trimMargin()
)
}
@Test
@Throws(IOException::class)
fun decodesPrimitives() {
val json =
"""
|{
| "byte": 32,
| "boolean": true,
| "short": 100,
| "int": 1,
| "long": 43,
| "float": 23.0,
| "double": 3.141592653589793,
| "char": "a",
| "String": "string"
|}
|""".trimMargin()
val map = cartographer.fromJson(json)
assertThat(map)
.hasSize(9)
.contains(MapEntry.entry("byte", 32.0))
.contains(MapEntry.entry("boolean", true))
.contains(MapEntry.entry("short", 100.0))
.contains(MapEntry.entry("int", 1.0))
.contains(MapEntry.entry("long", 43.0))
.contains(MapEntry.entry("float", 23.0))
.contains(MapEntry.entry("double", Math.PI))
.contains(MapEntry.entry("char", "a"))
.contains(MapEntry.entry("String", "string"))
}
@Test
@Throws(IOException::class)
fun prettyPrintDisabled() {
val cartographer = Cartographer.Builder().prettyPrint(false).build()
val map =
ImmutableMap.builder<String, Any>()
.put(
"a",
ImmutableMap.builder<String, Any>()
.put(
"b",
ImmutableMap.builder<String, Any>()
.put(
"c",
ImmutableMap.builder<String, Any>()
.put(
"d",
ImmutableMap.builder<String, Any>()
.put("e", "f")
.build()
)
.build()
)
.build()
)
.build()
)
.build()
assertThat(cartographer.toJson(map))
.isEqualTo("{\"a\":{\"b\":{\"c\":{\"d\":{\"e\":\"f\"}}}}}")
}
@Test
@Throws(IOException::class)
fun encodesNestedMaps() {
val map =
ImmutableMap.builder<String, Any>()
.put(
"a",
ImmutableMap.builder<String, Any>()
.put(
"b",
ImmutableMap.builder<String, Any>()
.put(
"c",
ImmutableMap.builder<String, Any>()
.put(
"d",
ImmutableMap.builder<String, Any>()
.put("e", "f")
.build()
)
.build()
)
.build()
)
.build()
)
.build()
assertThat(cartographer.toJson(map))
.isEqualTo(
"""
|{
| "a": {
| "b": {
| "c": {
| "d": {
| "e": "f"
| }
| }
| }
| }
|}
""".trimMargin()
)
}
@Test
@Throws(IOException::class)
fun decodesNestedMaps() {
val json =
"""
|{
| "a": {
| "b": {
| "c": {
| "d": {
| "e": "f"
| }
| }
| }
| }
|}
""".trimMargin()
val map = cartographer.fromJson(json)
val expected = ImmutableMap.builder<String, Any>()
.put(
"a",
ImmutableMap.builder<String, Any>()
.put(
"b",
ImmutableMap.builder<String, Any>()
.put(
"c",
ImmutableMap.builder<String, Any>()
.put(
"d",
ImmutableMap.builder<String, Any>()
.put("e", "f")
.build()
)
.build()
)
.build()
)
.build()
)
.build()
assertThat(map).isEqualTo(expected)
}
@Test
@Throws(IOException::class)
fun encodesArraysWithList() {
val map = ImmutableMap.builder<String, Any>().put("a", listOf("b", "c", "d")).build()
assertThat(cartographer.toJson(map))
.isEqualTo(
"""
|{
| "a": [
| "b",
| "c",
| "d"
| ]
|}
""".trimMargin()
)
}
@Test
@Throws(IOException::class)
fun decodesArraysWithList() {
val json =
"""
|{
| "a": [
| "b",
| "c",
| "d"
| ]
|}
""".trimMargin()
val expected =
ImmutableMap.builder<String, Any>().put("a", listOf("b", "c", "d")).build()
assertThat(cartographer.fromJson(json)).isEqualTo(expected)
}
@Test
@Throws(IOException::class)
fun encodesArraysWithArrays() {
val map =
ImmutableMap.builder<String, Any>().put("a", arrayOf("b", "c", "d")).build()
assertThat(cartographer.toJson(map))
.isEqualTo(
"""
|{
| "a": [
| "b",
| "c",
| "d"
| ]
|}
""".trimMargin()
)
}
@Test
@Throws(IOException::class)
fun encodesInfiniteAndNanDoubles() {
val map = ImmutableMap.builder<String, Any>()
.put("nan", Double.NaN)
.put("positive_infinity", Double.POSITIVE_INFINITY)
.put("negative_infinity", Double.NEGATIVE_INFINITY)
.build()
assertThat(cartographer.toJson(map))
.isEqualTo(
"""
|{
| "nan": 0.0,
| "positive_infinity": 0.0,
| "negative_infinity": 0.0
|}
""".trimMargin()
)
}
@Test
@Throws(IOException::class)
fun encodesInfiniteAndNanFloats() {
val map = ImmutableMap.builder<String, Any>()
.put("nan", Float.NaN)
.put("positive_infinity", Float.POSITIVE_INFINITY)
.put("negative_infinity", Float.NEGATIVE_INFINITY)
.build()
assertThat(cartographer.toJson(map))
.isEqualTo(
"""
|{
| "nan": 0.0,
| "positive_infinity": 0.0,
| "negative_infinity": 0.0
|}
""".trimMargin()
)
}
@Test
@Throws(IOException::class)
fun encodesPrimitiveArrays() {
// Exercise a bug where primitive arrays would throw an IOException.
// https://github.com/segmentio/analytics-android/issues/507
val map: Map<String?, Any?> = ImmutableMap.builder<String?, Any?>().put("a", intArrayOf(1, 2)).build()
assertThat(cartographer.toJson(map))
.isEqualTo(
"""
|{
| "a": [
| 1,
| 2
| ]
|}
""".trimMargin()
)
}
@Test
@Throws(IOException::class)
fun decodesArraysAsArraysAsList() {
val json =
"""
|{
| "a": [
| "b",
| "c",
| "d"
| ]
|}
""".trimMargin()
val expected: Map<String, Any> = ImmutableMap.builder<String, Any>()
.put("a", listOf("b", "c", "d"))
.build()
assertThat(cartographer.fromJson(json)).isEqualTo(expected)
}
@Test
@Throws(IOException::class)
fun encodesArrayOfMap() {
val map: Map<String, Any> = ImmutableMap.builder<String, Any>()
.put(
"a",
listOf<ImmutableMap<*, *>>(
ImmutableMap.builder<String, Any>().put("b", "c").build(),
ImmutableMap.builder<String, Any>().put("b", "d").build(),
ImmutableMap.builder<String, Any>().put("b", "e").build()
)
)
.build()
assertThat(cartographer.toJson(map))
.isEqualTo(
"""
|{
| "a": [
| {
| "b": "c"
| },
| {
| "b": "d"
| },
| {
| "b": "e"
| }
| ]
|}
""".trimMargin()
)
}
@Test
@Throws(IOException::class)
fun decodesArrayOfMap() {
val json =
"""
|{
| "a": [
| {
| "b": "c"
| },
| {
| "b": "d"
| },
| {
| "b": "e"
| }
| ]
|}
""".trimMargin()
val expected: Map<String, Any> = ImmutableMap.builder<String, Any>()
.put(
"a",
listOf<ImmutableMap<*, *>>(
ImmutableMap.builder<String, Any>().put("b", "c").build(),
ImmutableMap.builder<String, Any>().put("b", "d").build(),
ImmutableMap.builder<String, Any>().put("b", "e").build()
)
)
.build()
assertThat(cartographer.fromJson(json)).isEqualTo(expected)
}
@Test
@Throws(IOException::class)
fun disallowsEncodingNullMap() {
try {
cartographer.toJson(null, StringWriter())
fail("null map should throw Exception")
} catch (e: IllegalArgumentException) {
assertThat(e).hasMessage("map == null")
}
}
@Test
@Throws(IOException::class)
fun disallowsEncodingToNullWriter() {
try {
cartographer.toJson(LinkedHashMap<Any, Any>(), null)
fail("null writer should throw Exception")
} catch (e: IllegalArgumentException) {
assertThat(e).hasMessage("writer == null")
}
}
@Test
@Throws(IOException::class)
fun disallowsDecodingNullReader() {
try {
cartographer.fromJson(null as Reader?)
fail("null map should throw Exception")
} catch (e: java.lang.IllegalArgumentException) {
assertThat(e).hasMessage("reader == null")
}
}
@Test
@Throws(IOException::class)
fun disallowsDecodingNullString() {
try {
cartographer.fromJson(null as String?)
fail("null map should throw Exception")
} catch (e: java.lang.IllegalArgumentException) {
assertThat(e).hasMessage("json == null")
}
}
@Test
@Throws(IOException::class)
fun disallowsDecodingEmptyString() {
try {
cartographer.fromJson("")
fail("null map should throw Exception")
} catch (e: java.lang.IllegalArgumentException) {
assertThat(e).hasMessage("json empty")
}
}
@Test
@Throws(IOException::class)
fun encodesNumberMax() {
val writer = StringWriter()
val map = LinkedHashMap<String, Any>()
map["byte"] = Byte.MAX_VALUE
map["short"] = Short.MAX_VALUE
map["int"] = Int.MAX_VALUE
map["long"] = Long.MAX_VALUE
map["float"] = Float.MAX_VALUE
map["double"] = Double.MAX_VALUE
map["char"] = Character.MAX_VALUE
cartographer.toJson(map, writer)
assertThat(writer.toString())
.isEqualTo(
"""
|{
| "byte": 127,
| "short": 32767,
| "int": 2147483647,
| "long": 9223372036854775807,
| "float": 3.4028235E38,
| "double": 1.7976931348623157E308,
| "char": ""
|}""".trimMargin()
)
}
@Test
@Throws(IOException::class)
fun encodesNumberMin() {
val writer = StringWriter()
val map: MutableMap<String?, Any?> = java.util.LinkedHashMap()
map["byte"] = Byte.MIN_VALUE
map["short"] = Short.MIN_VALUE
map["int"] = Int.MIN_VALUE
map["long"] = Long.MIN_VALUE
map["float"] = Float.MIN_VALUE
map["double"] = Double.MIN_VALUE
map["char"] = Character.MIN_VALUE
cartographer.toJson(map, writer)
assertThat(writer.toString())
.isEqualTo(
"""
|{
| "byte": -128,
| "short": -32768,
| "int": -2147483648,
| "long": -9223372036854775808,
| "float": 1.4E-45,
| "double": 4.9E-324,
| "char": "\u0000"
|}
""".trimMargin()
)
}
@Test
@Throws(IOException::class)
fun encodesLargeDocuments() {
val map = LinkedHashMap<String, Any>()
for (i in 1 until 100) {
map[UUID.randomUUID().toString()] = UUID.randomUUID().toString()
}
val writer = StringWriter()
cartographer.toJson(map, writer)
}
}
| mit | 541fddffc618c63c6a32351c384d5d97 | 31.253913 | 110 | 0.395881 | 5.065829 | false | false | false | false |
CarlosEsco/tachiyomi | app/src/main/java/eu/kanade/tachiyomi/ui/reader/ReaderSlider.kt | 1 | 740 | package eu.kanade.tachiyomi.ui.reader
import android.content.Context
import android.util.AttributeSet
import com.google.android.material.slider.Slider
/**
* Slider to show current chapter progress.
*/
class ReaderSlider @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
) : Slider(context, attrs) {
init {
stepSize = 1f
setLabelFormatter { value ->
(value.toInt() + 1).toString()
}
}
/**
* Whether the slider should draw from right to left.
*/
var isRTL: Boolean
set(value) {
layoutDirection = if (value) LAYOUT_DIRECTION_RTL else LAYOUT_DIRECTION_LTR
}
get() = layoutDirection == LAYOUT_DIRECTION_RTL
}
| apache-2.0 | 1efae4188181d792c164bd75e2fa5a72 | 23.666667 | 87 | 0.640541 | 4.277457 | false | false | false | false |
Heiner1/AndroidAPS | danars/src/main/java/info/nightscout/androidaps/danars/services/DanaRSService.kt | 1 | 24637 | package info.nightscout.androidaps.danars.services
import android.app.Service
import android.content.Context
import android.content.Intent
import android.os.Binder
import android.os.IBinder
import android.os.SystemClock
import dagger.android.DaggerService
import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.Constants
import info.nightscout.androidaps.activities.ErrorHelperActivity
import info.nightscout.androidaps.dana.DanaPump
import info.nightscout.androidaps.dana.comm.RecordTypes
import info.nightscout.androidaps.dana.events.EventDanaRNewStatus
import info.nightscout.androidaps.danars.DanaRSPlugin
import info.nightscout.androidaps.danars.R
import info.nightscout.androidaps.danars.comm.*
import info.nightscout.androidaps.data.PumpEnactResult
import info.nightscout.androidaps.dialogs.BolusProgressDialog
import info.nightscout.androidaps.events.EventAppExit
import info.nightscout.androidaps.events.EventInitializationChanged
import info.nightscout.androidaps.events.EventProfileSwitchChanged
import info.nightscout.androidaps.events.EventPumpStatusChanged
import info.nightscout.androidaps.interfaces.ActivePlugin
import info.nightscout.androidaps.interfaces.CommandQueue
import info.nightscout.androidaps.interfaces.Profile
import info.nightscout.androidaps.interfaces.ProfileFunction
import info.nightscout.androidaps.interfaces.PumpSync
import info.nightscout.shared.logging.AAPSLogger
import info.nightscout.shared.logging.LTag
import info.nightscout.androidaps.plugins.bus.RxBus
import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker
import info.nightscout.androidaps.plugins.general.overview.events.EventNewNotification
import info.nightscout.androidaps.plugins.general.overview.events.EventOverviewBolusProgress
import info.nightscout.androidaps.plugins.general.overview.notifications.Notification
import info.nightscout.androidaps.plugins.pump.common.bolusInfo.DetailedBolusInfoStorage
import info.nightscout.androidaps.queue.Callback
import info.nightscout.androidaps.queue.commands.Command
import info.nightscout.androidaps.utils.DateUtil
import info.nightscout.androidaps.utils.FabricPrivacy
import info.nightscout.androidaps.utils.T
import info.nightscout.androidaps.interfaces.ResourceHelper
import info.nightscout.androidaps.utils.rx.AapsSchedulers
import info.nightscout.shared.sharedPreferences.SP
import io.reactivex.rxjava3.disposables.CompositeDisposable
import io.reactivex.rxjava3.kotlin.plusAssign
import org.joda.time.DateTime
import org.joda.time.DateTimeZone
import java.util.concurrent.TimeUnit
import javax.inject.Inject
import kotlin.math.abs
import kotlin.math.min
class DanaRSService : DaggerService() {
@Inject lateinit var injector: HasAndroidInjector
@Inject lateinit var aapsLogger: AAPSLogger
@Inject lateinit var aapsSchedulers: AapsSchedulers
@Inject lateinit var rxBus: RxBus
@Inject lateinit var sp: SP
@Inject lateinit var rh: ResourceHelper
@Inject lateinit var profileFunction: ProfileFunction
@Inject lateinit var commandQueue: CommandQueue
@Inject lateinit var context: Context
@Inject lateinit var danaRSPlugin: DanaRSPlugin
@Inject lateinit var danaPump: DanaPump
@Inject lateinit var danaRSMessageHashTable: DanaRSMessageHashTable
@Inject lateinit var activePlugin: ActivePlugin
@Inject lateinit var constraintChecker: ConstraintChecker
@Inject lateinit var detailedBolusInfoStorage: DetailedBolusInfoStorage
@Inject lateinit var bleComm: BLEComm
@Inject lateinit var fabricPrivacy: FabricPrivacy
@Inject lateinit var pumpSync: PumpSync
@Inject lateinit var dateUtil: DateUtil
private val disposable = CompositeDisposable()
private val mBinder: IBinder = LocalBinder()
private var lastApproachingDailyLimit: Long = 0
override fun onCreate() {
super.onCreate()
disposable += rxBus
.toObservable(EventAppExit::class.java)
.observeOn(aapsSchedulers.io)
.subscribe({ stopSelf() }, fabricPrivacy::logException)
}
override fun onDestroy() {
disposable.clear()
super.onDestroy()
}
val isConnected: Boolean
get() = bleComm.isConnected
val isConnecting: Boolean
get() = bleComm.isConnecting
fun connect(from: String, address: String): Boolean {
return bleComm.connect(from, address)
}
fun stopConnecting() {
bleComm.stopConnecting()
}
fun disconnect(from: String) {
bleComm.disconnect(from)
}
fun sendMessage(message: DanaRSPacket) {
bleComm.sendMessage(message)
}
fun readPumpStatus() {
try {
val pump = activePlugin.activePump
rxBus.send(EventPumpStatusChanged(rh.gs(R.string.gettingpumpsettings)))
sendMessage(DanaRSPacketEtcKeepConnection(injector)) // test encryption for v3 & BLE
if (!bleComm.isConnected) return
sendMessage(DanaRSPacketGeneralGetShippingInformation(injector)) // serial no
sendMessage(DanaRSPacketGeneralGetPumpCheck(injector)) // firmware
sendMessage(DanaRSPacketBasalGetProfileNumber(injector))
sendMessage(DanaRSPacketBolusGetBolusOption(injector)) // isExtendedEnabled
sendMessage(DanaRSPacketBasalGetBasalRate(injector)) // basal profile, basalStep, maxBasal
sendMessage(DanaRSPacketBolusGetCalculationInformation(injector)) // target
if (danaPump.profile24) sendMessage(DanaRSPacketBolusGet24CIRCFArray(injector))
else sendMessage(DanaRSPacketBolusGetCIRCFArray(injector))
sendMessage(DanaRSPacketOptionGetUserOption(injector)) // Getting user options
rxBus.send(EventPumpStatusChanged(rh.gs(R.string.gettingpumpstatus)))
sendMessage(DanaRSPacketGeneralInitialScreenInformation(injector))
rxBus.send(EventPumpStatusChanged(rh.gs(R.string.gettingbolusstatus)))
sendMessage(DanaRSPacketBolusGetStepBolusInformation(injector)) // last bolus, bolusStep, maxBolus
danaPump.lastConnection = System.currentTimeMillis()
val profile = profileFunction.getProfile()
if (profile != null && abs(danaPump.currentBasal - profile.getBasal()) >= pump.pumpDescription.basalStep) {
rxBus.send(EventPumpStatusChanged(rh.gs(R.string.gettingpumpsettings)))
if (!pump.isThisProfileSet(profile) && !commandQueue.isRunning(Command.CommandType.BASAL_PROFILE)) {
rxBus.send(EventProfileSwitchChanged())
}
}
rxBus.send(EventPumpStatusChanged(rh.gs(R.string.gettingpumptime)))
if (danaPump.usingUTC) sendMessage(DanaRSPacketOptionGetPumpUTCAndTimeZone(injector))
else sendMessage(DanaRSPacketOptionGetPumpTime(injector))
var timeDiff = (danaPump.getPumpTime() - System.currentTimeMillis()) / 1000L
if (danaPump.getPumpTime() == 0L) {
// initial handshake was not successful
// de-initialize pump
danaPump.reset()
rxBus.send(EventDanaRNewStatus())
rxBus.send(EventInitializationChanged())
return
}
aapsLogger.debug(LTag.PUMPCOMM, "Pump time difference: $timeDiff seconds")
// phone timezone
val tz = DateTimeZone.getDefault()
val instant = DateTime.now().millis
val offsetInMilliseconds = tz.getOffset(instant).toLong()
val offset = TimeUnit.MILLISECONDS.toHours(offsetInMilliseconds).toInt()
if (abs(timeDiff) > 3 || danaPump.usingUTC && offset != danaPump.zoneOffset) {
if (abs(timeDiff) > 60 * 60 * 1.5) {
aapsLogger.debug(LTag.PUMPCOMM, "Pump time difference: $timeDiff seconds - large difference")
//If time-diff is very large, warn user until we can synchronize history readings properly
ErrorHelperActivity.runAlarm(context, rh.gs(R.string.largetimediff), rh.gs(R.string.largetimedifftitle), R.raw.error)
//de-initialize pump
danaPump.reset()
rxBus.send(EventDanaRNewStatus())
rxBus.send(EventInitializationChanged())
return
} else {
when {
danaPump.usingUTC -> {
sendMessage(DanaRSPacketOptionSetPumpUTCAndTimeZone(injector, dateUtil.now(), offset))
}
danaPump.protocol >= 5 -> { // can set seconds
sendMessage(DanaRSPacketOptionSetPumpTime(injector, dateUtil.now()))
}
else -> {
waitForWholeMinute() // Dana can set only whole minute
// add 10sec to be sure we are over minute (will be cut off anyway)
sendMessage(DanaRSPacketOptionSetPumpTime(injector, dateUtil.now() + T.secs(10).msecs()))
}
}
if (danaPump.usingUTC) sendMessage(DanaRSPacketOptionGetPumpUTCAndTimeZone(injector))
else sendMessage(DanaRSPacketOptionGetPumpTime(injector))
timeDiff = (danaPump.getPumpTime() - System.currentTimeMillis()) / 1000L
aapsLogger.debug(LTag.PUMPCOMM, "Pump time difference: $timeDiff seconds")
}
}
rxBus.send(EventPumpStatusChanged(rh.gs(R.string.reading_pump_history)))
loadEvents()
// RS doesn't provide exact timestamp = rely on history
val eb = pumpSync.expectedPumpState().extendedBolus
danaPump.fromExtendedBolus(eb)
val tbr = pumpSync.expectedPumpState().temporaryBasal
danaPump.fromTemporaryBasal(tbr)
rxBus.send(EventDanaRNewStatus())
rxBus.send(EventInitializationChanged())
if (danaPump.dailyTotalUnits > danaPump.maxDailyTotalUnits * Constants.dailyLimitWarning) {
aapsLogger.debug(LTag.PUMPCOMM, "Approaching daily limit: " + danaPump.dailyTotalUnits + "/" + danaPump.maxDailyTotalUnits)
if (System.currentTimeMillis() > lastApproachingDailyLimit + 30 * 60 * 1000) {
val reportFail = Notification(Notification.APPROACHING_DAILY_LIMIT, rh.gs(R.string.approachingdailylimit), Notification.URGENT)
rxBus.send(EventNewNotification(reportFail))
pumpSync.insertAnnouncement(
rh.gs(R.string.approachingdailylimit) + ": " + danaPump.dailyTotalUnits + "/" + danaPump.maxDailyTotalUnits + "U",
null,
danaPump.pumpType(),
danaPump.serialNumber
)
lastApproachingDailyLimit = System.currentTimeMillis()
}
}
} catch (e: Exception) {
aapsLogger.error(LTag.PUMPCOMM, "Unhandled exception", e)
}
aapsLogger.debug(LTag.PUMPCOMM, "Pump status loaded")
}
fun loadEvents(): PumpEnactResult {
if (!danaRSPlugin.isInitialized()) {
val result = PumpEnactResult(injector).success(false)
result.comment = "pump not initialized"
return result
}
SystemClock.sleep(1000)
val msg: DanaRSPacketAPSHistoryEvents
if (danaPump.lastHistoryFetched == 0L) {
msg = DanaRSPacketAPSHistoryEvents(injector, 0)
aapsLogger.debug(LTag.PUMPCOMM, "Loading complete event history")
} else {
msg = DanaRSPacketAPSHistoryEvents(injector, danaPump.lastHistoryFetched)
aapsLogger.debug(LTag.PUMPCOMM, "Loading event history from: " + dateUtil.dateAndTimeString(danaPump.lastHistoryFetched))
}
sendMessage(msg)
while (!danaPump.historyDoneReceived && bleComm.isConnected) {
SystemClock.sleep(100)
}
danaPump.lastHistoryFetched = if (danaPump.lastEventTimeLoaded != 0L) danaPump.lastEventTimeLoaded - T.mins(1).msecs() else 0
aapsLogger.debug(LTag.PUMPCOMM, "Events loaded")
rxBus.send(EventPumpStatusChanged(rh.gs(R.string.gettingpumpstatus)))
sendMessage(DanaRSPacketGeneralInitialScreenInformation(injector))
danaPump.lastConnection = System.currentTimeMillis()
return PumpEnactResult(injector).success(msg.success())
}
fun setUserSettings(): PumpEnactResult {
val message = DanaRSPacketOptionSetUserOption(injector)
sendMessage(message)
return PumpEnactResult(injector).success(message.success())
}
fun bolus(insulin: Double, carbs: Int, carbTime: Long, t: EventOverviewBolusProgress.Treatment): Boolean {
if (!isConnected) return false
if (BolusProgressDialog.stopPressed) return false
rxBus.send(EventPumpStatusChanged(rh.gs(R.string.startingbolus)))
val preferencesSpeed = sp.getInt(R.string.key_danars_bolusspeed, 0)
danaPump.bolusDone = false
danaPump.bolusingTreatment = t
danaPump.bolusAmountToBeDelivered = insulin
danaPump.bolusStopped = false
danaPump.bolusStopForced = false
danaPump.bolusProgressLastTimeStamp = dateUtil.now()
val start = DanaRSPacketBolusSetStepBolusStart(injector, insulin, preferencesSpeed)
if (carbs > 0) {
// MsgSetCarbsEntry msg = new MsgSetCarbsEntry(carbTime, carbs); ####
// sendMessage(msg);
val msgSetHistoryEntryV2 = DanaRSPacketAPSSetEventHistory(injector, DanaPump.HistoryEntry.CARBS.value, carbTime, carbs, 0)
sendMessage(msgSetHistoryEntryV2)
danaPump.lastHistoryFetched = min(danaPump.lastHistoryFetched, carbTime - T.mins(1).msecs())
if (!msgSetHistoryEntryV2.isReceived || msgSetHistoryEntryV2.failed)
ErrorHelperActivity.runAlarm(context, rh.gs(R.string.carbs_store_error), rh.gs(R.string.error), R.raw.boluserror)
}
val bolusStart = System.currentTimeMillis()
if (insulin > 0) {
if (!danaPump.bolusStopped) {
sendMessage(start)
} else {
t.insulin = 0.0
return false
}
while (!danaPump.bolusStopped && !start.failed && !danaPump.bolusDone) {
SystemClock.sleep(100)
if (System.currentTimeMillis() - danaPump.bolusProgressLastTimeStamp > 15 * 1000L) { // if i didn't receive status for more than 20 sec expecting broken comm
danaPump.bolusStopped = true
danaPump.bolusStopForced = true
aapsLogger.debug(LTag.PUMPCOMM, "Communication stopped")
bleComm.disconnect("Communication stopped")
}
}
}
val bolusingEvent = EventOverviewBolusProgress
bolusingEvent.t = t
bolusingEvent.percent = 99
danaPump.bolusingTreatment = null
var speed = 12
when (preferencesSpeed) {
0 -> speed = 12
1 -> speed = 30
2 -> speed = 60
}
val bolusDurationInMSec = (insulin * speed * 1000).toLong()
val expectedEnd = bolusStart + bolusDurationInMSec + 2000
while (System.currentTimeMillis() < expectedEnd) {
val waitTime = expectedEnd - System.currentTimeMillis()
bolusingEvent.status = rh.gs(R.string.waitingforestimatedbolusend, waitTime / 1000)
rxBus.send(bolusingEvent)
SystemClock.sleep(1000)
}
// do not call loadEvents() directly, reconnection may be needed
commandQueue.loadEvents(object : Callback() {
override fun run() {
// reread bolus status
rxBus.send(EventPumpStatusChanged(rh.gs(R.string.gettingbolusstatus)))
sendMessage(DanaRSPacketBolusGetStepBolusInformation(injector)) // last bolus
bolusingEvent.percent = 100
rxBus.send(EventPumpStatusChanged(rh.gs(R.string.disconnecting)))
}
})
return !start.failed
}
fun bolusStop() {
aapsLogger.debug(LTag.PUMPCOMM, "bolusStop >>>>> @ " + if (danaPump.bolusingTreatment == null) "" else danaPump.bolusingTreatment?.insulin)
val stop = DanaRSPacketBolusSetStepBolusStop(injector)
danaPump.bolusStopForced = true
if (isConnected) {
sendMessage(stop)
while (!danaPump.bolusStopped) {
sendMessage(stop)
SystemClock.sleep(200)
}
} else {
danaPump.bolusStopped = true
}
}
fun tempBasal(percent: Int, durationInHours: Int): Boolean {
if (!isConnected) return false
val status = DanaRSPacketGeneralInitialScreenInformation(injector)
sendMessage(status)
if (status.isTempBasalInProgress) {
rxBus.send(EventPumpStatusChanged(rh.gs(R.string.stoppingtempbasal)))
sendMessage(DanaRSPacketBasalSetCancelTemporaryBasal(injector))
SystemClock.sleep(500)
}
rxBus.send(EventPumpStatusChanged(rh.gs(R.string.settingtempbasal)))
val msgTBR = DanaRSPacketBasalSetTemporaryBasal(injector, percent, durationInHours)
sendMessage(msgTBR)
SystemClock.sleep(200)
loadEvents()
SystemClock.sleep(4500)
val tbr = pumpSync.expectedPumpState().temporaryBasal
danaPump.fromTemporaryBasal(tbr)
rxBus.send(EventPumpStatusChanged(EventPumpStatusChanged.Status.DISCONNECTING))
return msgTBR.success()
}
fun highTempBasal(percent: Int): Boolean {
val status = DanaRSPacketGeneralInitialScreenInformation(injector)
sendMessage(status)
if (status.isTempBasalInProgress) {
rxBus.send(EventPumpStatusChanged(rh.gs(R.string.stoppingtempbasal)))
sendMessage(DanaRSPacketBasalSetCancelTemporaryBasal(injector))
SystemClock.sleep(500)
}
rxBus.send(EventPumpStatusChanged(rh.gs(R.string.settingtempbasal)))
val msgTBR = DanaRSPacketAPSBasalSetTemporaryBasal(injector, percent)
sendMessage(msgTBR)
loadEvents()
SystemClock.sleep(4500)
val tbr = pumpSync.expectedPumpState().temporaryBasal
danaPump.fromTemporaryBasal(tbr)
rxBus.send(EventPumpStatusChanged(EventPumpStatusChanged.Status.DISCONNECTING))
return msgTBR.success()
}
fun tempBasalShortDuration(percent: Int, durationInMinutes: Int): Boolean {
if (durationInMinutes != 15 && durationInMinutes != 30) {
aapsLogger.error(LTag.PUMPCOMM, "Wrong duration param")
return false
}
val status = DanaRSPacketGeneralInitialScreenInformation(injector)
sendMessage(status)
if (status.isTempBasalInProgress) {
rxBus.send(EventPumpStatusChanged(rh.gs(R.string.stoppingtempbasal)))
sendMessage(DanaRSPacketBasalSetCancelTemporaryBasal(injector))
SystemClock.sleep(500)
}
rxBus.send(EventPumpStatusChanged(rh.gs(R.string.settingtempbasal)))
val msgTBR = DanaRSPacketAPSBasalSetTemporaryBasal(injector, percent)
sendMessage(msgTBR)
loadEvents()
SystemClock.sleep(4500)
val tbr = pumpSync.expectedPumpState().temporaryBasal
aapsLogger.debug(LTag.PUMPCOMM, "Expected TBR found: $tbr")
danaPump.fromTemporaryBasal(tbr)
rxBus.send(EventPumpStatusChanged(EventPumpStatusChanged.Status.DISCONNECTING))
return msgTBR.success()
}
fun tempBasalStop(): Boolean {
if (!isConnected) return false
rxBus.send(EventPumpStatusChanged(rh.gs(R.string.stoppingtempbasal)))
val msgCancel = DanaRSPacketBasalSetCancelTemporaryBasal(injector)
sendMessage(msgCancel)
loadEvents()
SystemClock.sleep(4500)
val tbr = pumpSync.expectedPumpState().temporaryBasal
danaPump.fromTemporaryBasal(tbr)
rxBus.send(EventPumpStatusChanged(EventPumpStatusChanged.Status.DISCONNECTING))
return msgCancel.success()
}
fun extendedBolus(insulin: Double, durationInHalfHours: Int): Boolean {
if (!isConnected) return false
rxBus.send(EventPumpStatusChanged(rh.gs(R.string.settingextendedbolus)))
val msgExtended = DanaRSPacketBolusSetExtendedBolus(injector, insulin, durationInHalfHours)
sendMessage(msgExtended)
SystemClock.sleep(200)
loadEvents()
SystemClock.sleep(4500)
val eb = pumpSync.expectedPumpState().extendedBolus
danaPump.fromExtendedBolus(eb)
rxBus.send(EventPumpStatusChanged(EventPumpStatusChanged.Status.DISCONNECTING))
return msgExtended.success()
}
fun extendedBolusStop(): Boolean {
if (!isConnected) return false
rxBus.send(EventPumpStatusChanged(rh.gs(R.string.stoppingextendedbolus)))
val msgStop = DanaRSPacketBolusSetExtendedBolusCancel(injector)
sendMessage(msgStop)
loadEvents()
SystemClock.sleep(4500)
val eb = pumpSync.expectedPumpState().extendedBolus
danaPump.fromExtendedBolus(eb)
rxBus.send(EventPumpStatusChanged(EventPumpStatusChanged.Status.DISCONNECTING))
return msgStop.success()
}
fun updateBasalsInPump(profile: Profile): Boolean {
if (!isConnected) return false
rxBus.send(EventPumpStatusChanged(rh.gs(R.string.updatingbasalrates)))
val basal = danaPump.buildDanaRProfileRecord(profile)
val msgSet = DanaRSPacketBasalSetProfileBasalRate(injector, 0, basal)
sendMessage(msgSet)
val msgActivate = DanaRSPacketBasalSetProfileNumber(injector, 0)
sendMessage(msgActivate)
if (danaPump.profile24) {
val msgProfile = DanaRSPacketBolusSet24CIRCFArray(injector, profile)
sendMessage(msgProfile)
}
readPumpStatus()
rxBus.send(EventPumpStatusChanged(EventPumpStatusChanged.Status.DISCONNECTING))
return msgSet.success()
}
fun loadHistory(type: Byte): PumpEnactResult {
val result = PumpEnactResult(injector)
if (!isConnected) return result
var msg: DanaRSPacketHistory? = null
when (type) {
RecordTypes.RECORD_TYPE_ALARM -> msg = DanaRSPacketHistoryAlarm(injector)
RecordTypes.RECORD_TYPE_PRIME -> msg = DanaRSPacketHistoryPrime(injector)
RecordTypes.RECORD_TYPE_BASALHOUR -> msg = DanaRSPacketHistoryBasal(injector)
RecordTypes.RECORD_TYPE_BOLUS -> msg = DanaRSPacketHistoryBolus(injector)
RecordTypes.RECORD_TYPE_CARBO -> msg = DanaRSPacketHistoryCarbohydrate(injector)
RecordTypes.RECORD_TYPE_DAILY -> msg = DanaRSPacketHistoryDaily(injector)
RecordTypes.RECORD_TYPE_GLUCOSE -> msg = DanaRSPacketHistoryBloodGlucose(injector)
RecordTypes.RECORD_TYPE_REFILL -> msg = DanaRSPacketHistoryRefill(injector)
RecordTypes.RECORD_TYPE_SUSPEND -> msg = DanaRSPacketHistorySuspend(injector)
}
if (msg != null) {
sendMessage(DanaRSPacketGeneralSetHistoryUploadMode(injector, 1))
SystemClock.sleep(200)
sendMessage(msg)
while (!msg.done && isConnected) {
SystemClock.sleep(100)
}
SystemClock.sleep(200)
sendMessage(DanaRSPacketGeneralSetHistoryUploadMode(injector, 0))
}
result.success = msg?.success() ?: false
return result
}
inner class LocalBinder : Binder() {
val serviceInstance: DanaRSService
get() = this@DanaRSService
}
override fun onBind(intent: Intent): IBinder {
return mBinder
}
override fun onStartCommand(intent: Intent, flags: Int, startId: Int): Int {
return Service.START_STICKY
}
private fun waitForWholeMinute() {
while (true) {
val time = dateUtil.now()
val timeToWholeMinute = 60000 - time % 60000
if (timeToWholeMinute > 59800 || timeToWholeMinute < 300) break
rxBus.send(EventPumpStatusChanged(rh.gs(R.string.waitingfortimesynchronization, (timeToWholeMinute / 1000).toInt())))
SystemClock.sleep(min(timeToWholeMinute, 100))
}
}
} | agpl-3.0 | 7655e5a55ce33540744c925cfbe22ec0 | 46.933852 | 173 | 0.673296 | 4.961136 | false | false | false | false |
Heiner1/AndroidAPS | automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/InputCarePortalMenu.kt | 1 | 3492 | package info.nightscout.androidaps.plugins.general.automation.elements
import android.view.Gravity
import android.view.View
import android.widget.AdapterView
import android.widget.ArrayAdapter
import android.widget.LinearLayout
import android.widget.Spinner
import androidx.annotation.DrawableRes
import androidx.annotation.StringRes
import info.nightscout.androidaps.automation.R
import info.nightscout.androidaps.database.entities.TherapyEvent
import info.nightscout.androidaps.interfaces.ResourceHelper
class InputCarePortalMenu(private val rh: ResourceHelper) : Element() {
enum class EventType(val therapyEventType: TherapyEvent.Type) {
NOTE(TherapyEvent.Type.NOTE),
EXERCISE(TherapyEvent.Type.EXERCISE),
QUESTION(TherapyEvent.Type.QUESTION),
ANNOUNCEMENT(TherapyEvent.Type.ANNOUNCEMENT);
@get:StringRes val stringResWithValue: Int
get() = when (this) {
NOTE -> R.string.careportal_note_message
EXERCISE -> R.string.careportal_exercise_message
QUESTION -> R.string.careportal_question_message
ANNOUNCEMENT -> R.string.careportal_announcement_message
}
@get:StringRes val stringRes: Int
get() = when (this) {
NOTE -> R.string.careportal_note
EXERCISE -> R.string.careportal_exercise
QUESTION -> R.string.careportal_question
ANNOUNCEMENT -> R.string.careportal_announcement
}
@get:DrawableRes val drawableRes: Int
get() = when (this) {
NOTE -> R.drawable.ic_cp_note
EXERCISE -> R.drawable.ic_cp_exercise
QUESTION -> R.drawable.ic_cp_question
ANNOUNCEMENT -> R.drawable.ic_cp_announcement
}
companion object {
fun labels(rh: ResourceHelper): List<String> {
val list: MutableList<String> = ArrayList()
for (e in values()) {
list.add(rh.gs(e.stringRes))
}
return list
}
}
}
constructor(rh: ResourceHelper, value: EventType) : this(rh) {
this.value = value
}
var value = EventType.NOTE
override fun addToLayout(root: LinearLayout) {
root.addView(
Spinner(root.context).apply {
adapter = ArrayAdapter(root.context, R.layout.spinner_centered, EventType.labels(rh)).apply {
setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
}
layoutParams = LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT).apply {
setMargins(0, rh.dpToPx(4), 0, rh.dpToPx(4))
}
onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
value = EventType.values()[position]
}
override fun onNothingSelected(parent: AdapterView<*>?) {}
}
setSelection(value.ordinal)
gravity = Gravity.CENTER_HORIZONTAL
})
}
fun setValue(eventType: EventType): InputCarePortalMenu {
value = eventType
return this
}
} | agpl-3.0 | 8e42a2e2f8b28f451c8b2a165fb657f0 | 37.811111 | 144 | 0.60252 | 5.010043 | false | false | false | false |
realm/realm-java | realm/realm-annotations-processor/src/main/java/io/realm/processor/RealmProxyMediatorGenerator.kt | 1 | 28784 | /*
* Copyright 2019 Realm 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 io.realm.processor
import com.squareup.javawriter.JavaWriter
import io.realm.annotations.RealmModule
import java.io.BufferedWriter
import java.io.IOException
import java.util.*
import javax.annotation.processing.ProcessingEnvironment
import javax.lang.model.element.Modifier
import javax.tools.JavaFileObject
class RealmProxyMediatorGenerator(private val processingEnvironment: ProcessingEnvironment,
private val className: SimpleClassName,
classesToValidate: Set<ClassMetaData>) {
private val qualifiedModelClasses = ArrayList<QualifiedClassName>()
private val qualifiedProxyClasses = ArrayList<QualifiedClassName>()
private val simpleModelClassNames = ArrayList<SimpleClassName>()
private val internalClassNames = ArrayList<String>()
private val embeddedClass = ArrayList<Boolean>()
private val primaryKeyClasses = mutableListOf<QualifiedClassName>()
init {
// Sort classes to ensure deterministic output. This is relevant when e.g. using Gradle
// Remote Cache since the order is not guaranteed between OS and Java versions.
for (metadata in classesToValidate.toSortedSet(compareByDescending { it.qualifiedClassName.name })) {
qualifiedModelClasses.add(metadata.qualifiedClassName)
val qualifiedProxyClassName = QualifiedClassName("${Constants.REALM_PACKAGE_NAME}.${Utils.getProxyClassName(metadata.qualifiedClassName)}")
qualifiedProxyClasses.add(qualifiedProxyClassName)
simpleModelClassNames.add(metadata.simpleJavaClassName)
internalClassNames.add(metadata.internalClassName)
embeddedClass.add(metadata.embedded)
if(metadata.primaryKey != null) {
primaryKeyClasses.add(metadata.qualifiedClassName)
}
}
}
@Throws(IOException::class)
fun generate() {
val qualifiedGeneratedClassName: String = String.format(Locale.US, "%s.%sMediator", Constants.REALM_PACKAGE_NAME, className)
val sourceFile: JavaFileObject = processingEnvironment.filer.createSourceFile(qualifiedGeneratedClassName)
val imports = ArrayList(Arrays.asList("android.util.JsonReader",
"java.io.IOException",
"java.util.Collections",
"java.util.HashSet",
"java.util.List",
"java.util.Map",
"java.util.HashMap",
"java.util.Set",
"java.util.Iterator",
"java.util.Collection",
"io.realm.ImportFlag",
"io.realm.internal.ColumnInfo",
"io.realm.internal.RealmObjectProxy",
"io.realm.internal.RealmProxyMediator",
"io.realm.internal.Row",
"io.realm.internal.OsSchemaInfo",
"io.realm.internal.OsObjectSchemaInfo",
"org.json.JSONException",
"org.json.JSONObject"))
val writer = JavaWriter(BufferedWriter(sourceFile.openWriter()))
writer.apply {
indent = " "
emitPackage(Constants.REALM_PACKAGE_NAME)
emitEmptyLine()
emitImports(imports)
emitEmptyLine()
emitAnnotation(RealmModule::class.java)
beginType(qualifiedGeneratedClassName, // full qualified name of the item to generate
"class", // the type of the item
emptySet(), // modifiers to apply
"RealmProxyMediator") // class to extend
emitEmptyLine()
emitFields(this)
emitGetExpectedObjectSchemaInfoMap(this)
emitCreateColumnInfoMethod(this)
emitGetSimpleClassNameMethod(this)
emitGetClazzClassNameMethod(this)
emitHasPrimaryKeyMethod(this)
emitNewInstanceMethod(this)
emitGetClassModelList(this)
emitCopyOrUpdateMethod(this)
emitInsertObjectToRealmMethod(this)
emitInsertListToRealmMethod(this)
emitInsertOrUpdateObjectToRealmMethod(this)
emitInsertOrUpdateListToRealmMethod(this)
emitCreteOrUpdateUsingJsonObject(this)
emitCreateUsingJsonStream(this)
emitCreateDetachedCopyMethod(this)
emitIsEmbeddedMethod(this)
emitUpdateEmbeddedObjectMethod(this)
endType()
close()
}
}
@Throws(IOException::class)
private fun emitFields(writer: JavaWriter) {
writer.apply {
emitField("Set<Class<? extends RealmModel>>", "MODEL_CLASSES", EnumSet.of(Modifier.PRIVATE, Modifier.STATIC, Modifier.FINAL))
beginInitializer(true)
emitStatement("Set<Class<? extends RealmModel>> modelClasses = new HashSet<Class<? extends RealmModel>>(%s)", qualifiedModelClasses.size)
for (clazz in qualifiedModelClasses) {
emitStatement("modelClasses.add(%s.class)", clazz)
}
emitStatement("MODEL_CLASSES = Collections.unmodifiableSet(modelClasses)")
endInitializer()
emitEmptyLine()
}
}
@Throws(IOException::class)
private fun emitGetExpectedObjectSchemaInfoMap(writer: JavaWriter) {
writer.apply {
emitAnnotation("Override")
beginMethod("Map<Class<? extends RealmModel>, OsObjectSchemaInfo>","getExpectedObjectSchemaInfoMap", EnumSet.of(Modifier.PUBLIC))
emitStatement("Map<Class<? extends RealmModel>, OsObjectSchemaInfo> infoMap = new HashMap<Class<? extends RealmModel>, OsObjectSchemaInfo>(%s)", qualifiedProxyClasses.size)
for (i in qualifiedProxyClasses.indices) {
emitStatement("infoMap.put(%s.class, %s.getExpectedObjectSchemaInfo())", qualifiedModelClasses[i], qualifiedProxyClasses[i])
}
emitStatement("return infoMap")
endMethod()
emitEmptyLine()
}
}
@Throws(IOException::class)
private fun emitCreateColumnInfoMethod(writer: JavaWriter) {
writer.apply {
emitAnnotation("Override")
beginMethod(
"ColumnInfo",
"createColumnInfo",
EnumSet.of(Modifier.PUBLIC),
"Class<? extends RealmModel>", "clazz", // Argument type & argument name
"OsSchemaInfo", "schemaInfo"
)
emitMediatorShortCircuitSwitch(writer, emitStatement = { i: Int ->
emitStatement("return %s.createColumnInfo(schemaInfo)", qualifiedProxyClasses[i])
})
endMethod()
emitEmptyLine()
}
}
@Throws(IOException::class)
private fun emitGetSimpleClassNameMethod(writer: JavaWriter) {
writer.apply {
emitAnnotation("Override")
beginMethod(
"String",
"getSimpleClassNameImpl",
EnumSet.of(Modifier.PUBLIC),
"Class<? extends RealmModel>", "clazz"
)
emitMediatorShortCircuitSwitch(writer, emitStatement = { i: Int ->
emitStatement("return \"%s\"", internalClassNames[i])
})
endMethod()
emitEmptyLine()
}
}
@Throws(IOException::class)
private fun emitGetClazzClassNameMethod(writer: JavaWriter) {
writer.apply {
emitAnnotation("Override")
beginMethod(
"Class<? extends RealmModel>",
"getClazzImpl",
EnumSet.of(Modifier.PUBLIC),
"String", "className"
)
emitMediatorInverseShortCircuitSwitch(writer, emitStatement = { i: Int ->
emitStatement("return %s.class", qualifiedModelClasses[i])
})
endMethod()
emitEmptyLine()
}
}
@Throws(IOException::class)
private fun emitHasPrimaryKeyMethod(writer: JavaWriter) {
writer.apply {
emitAnnotation("Override")
beginMethod(
"boolean",
"hasPrimaryKeyImpl",
EnumSet.of(Modifier.PUBLIC),
"Class<? extends RealmModel>", "clazz"
)
if (primaryKeyClasses.size == 0) {
emitStatement("return false")
} else {
val primaryKeyCondition = primaryKeyClasses.joinToString(".class.isAssignableFrom(clazz)\n|| ", "", ".class.isAssignableFrom(clazz)")
emitStatement("return %s", primaryKeyCondition)
}
endMethod()
emitEmptyLine()
}
}
@Throws(IOException::class)
private fun emitNewInstanceMethod(writer: JavaWriter) {
writer.apply {
emitAnnotation("Override")
beginMethod(
"<E extends RealmModel> E",
"newInstance",
EnumSet.of(Modifier.PUBLIC),
"Class<E>", "clazz",
"Object", "baseRealm",
"Row", "row",
"ColumnInfo", "columnInfo",
"boolean", "acceptDefaultValue",
"List<String>", "excludeFields"
)
emitStatement("final BaseRealm.RealmObjectContext objectContext = BaseRealm.objectContext.get()")
beginControlFlow("try")
emitStatement("objectContext.set((BaseRealm) baseRealm, row, columnInfo, acceptDefaultValue, excludeFields)")
emitMediatorShortCircuitSwitch(writer, emitStatement = { i: Int ->
emitStatement("return clazz.cast(new %s())", qualifiedProxyClasses[i])
})
nextControlFlow("finally")
emitStatement("objectContext.clear()")
endControlFlow()
endMethod()
emitEmptyLine()
}
}
@Throws(IOException::class)
private fun emitGetClassModelList(writer: JavaWriter) {
writer.apply {
emitAnnotation("Override")
beginMethod("Set<Class<? extends RealmModel>>", "getModelClasses", EnumSet.of(Modifier.PUBLIC))
emitStatement("return MODEL_CLASSES")
endMethod()
emitEmptyLine()
}
}
@Throws(IOException::class)
private fun emitCopyOrUpdateMethod(writer: JavaWriter) {
writer.apply {
emitAnnotation("Override")
beginMethod(
"<E extends RealmModel> E",
"copyOrUpdate",
EnumSet.of(Modifier.PUBLIC),
"Realm", "realm",
"E", "obj",
"boolean", "update",
"Map<RealmModel, RealmObjectProxy>", "cache",
"Set<ImportFlag>", "flags"
)
emitSingleLineComment("This cast is correct because obj is either")
emitSingleLineComment("generated by RealmProxy or the original type extending directly from RealmObject")
emitStatement("@SuppressWarnings(\"unchecked\") Class<E> clazz = (Class<E>) ((obj instanceof RealmObjectProxy) ? obj.getClass().getSuperclass() : obj.getClass())")
emitEmptyLine()
emitMediatorShortCircuitSwitch(writer, false) { i: Int ->
emitStatement("%1\$s columnInfo = (%1\$s) realm.getSchema().getColumnInfo(%2\$s.class)", Utils.getSimpleColumnInfoClassName(qualifiedModelClasses[i]), qualifiedModelClasses[i])
emitStatement("return clazz.cast(%s.copyOrUpdate(realm, columnInfo, (%s) obj, update, cache, flags))", qualifiedProxyClasses[i], qualifiedModelClasses[i])
}
endMethod()
emitEmptyLine()
}
}
@Throws(IOException::class)
private fun emitInsertObjectToRealmMethod(writer: JavaWriter) {
writer.apply {
emitAnnotation("Override")
beginMethod(
"long",
"insert",
EnumSet.of(Modifier.PUBLIC),
"Realm", "realm", "RealmModel", "object", "Map<RealmModel, Long>", "cache")
if (embeddedClass.contains(false)) {
emitSingleLineComment("This cast is correct because obj is either")
emitSingleLineComment("generated by RealmProxy or the original type extending directly from RealmObject")
emitStatement("@SuppressWarnings(\"unchecked\") Class<RealmModel> clazz = (Class<RealmModel>) ((object instanceof RealmObjectProxy) ? object.getClass().getSuperclass() : object.getClass())")
emitEmptyLine()
emitMediatorSwitch(writer, false, { i: Int ->
if (embeddedClass[i]) {
emitEmbeddedObjectsCannotBeCopiedException(writer)
} else {
emitStatement("return %s.insert(realm, (%s) object, cache)", qualifiedProxyClasses[i], qualifiedModelClasses[i])
}
})
} else {
emitEmbeddedObjectsCannotBeCopiedException(writer)
}
endMethod()
emitEmptyLine()
}
}
@Throws(IOException::class)
private fun emitInsertOrUpdateObjectToRealmMethod(writer: JavaWriter) {
writer.apply {
emitAnnotation("Override")
beginMethod(
"long",
"insertOrUpdate",
EnumSet.of(Modifier.PUBLIC),
"Realm", "realm", "RealmModel", "obj", "Map<RealmModel, Long>", "cache")
if (embeddedClass.contains(false)) {
emitSingleLineComment("This cast is correct because obj is either")
emitSingleLineComment("generated by RealmProxy or the original type extending directly from RealmObject")
emitStatement("@SuppressWarnings(\"unchecked\") Class<RealmModel> clazz = (Class<RealmModel>) ((obj instanceof RealmObjectProxy) ? obj.getClass().getSuperclass() : obj.getClass())")
emitEmptyLine()
emitMediatorSwitch(writer, false, { i: Int ->
if (embeddedClass[i]) {
emitEmbeddedObjectsCannotBeCopiedException(writer)
} else {
emitStatement("return %s.insertOrUpdate(realm, (%s) obj, cache)", qualifiedProxyClasses[i], qualifiedModelClasses[i])
}
})
} else {
emitEmbeddedObjectsCannotBeCopiedException(writer)
}
endMethod()
emitEmptyLine()
}
}
@Throws(IOException::class)
private fun emitInsertOrUpdateListToRealmMethod(writer: JavaWriter) {
writer.apply {
emitAnnotation("Override")
beginMethod(
"void",
"insertOrUpdate",
EnumSet.of(Modifier.PUBLIC),
"Realm", "realm", "Collection<? extends RealmModel>", "objects")
if (embeddedClass.contains(false)) {
emitStatement("Iterator<? extends RealmModel> iterator = objects.iterator()")
emitStatement("RealmModel object = null")
emitStatement("Map<RealmModel, Long> cache = new HashMap<RealmModel, Long>(objects.size())")
beginControlFlow("if (iterator.hasNext())")
emitSingleLineComment(" access the first element to figure out the clazz for the routing below")
emitStatement("object = iterator.next()")
emitSingleLineComment("This cast is correct because obj is either")
emitSingleLineComment("generated by RealmProxy or the original type extending directly from RealmObject")
emitStatement("@SuppressWarnings(\"unchecked\") Class<RealmModel> clazz = (Class<RealmModel>) ((object instanceof RealmObjectProxy) ? object.getClass().getSuperclass() : object.getClass())")
emitEmptyLine()
emitMediatorSwitch(writer, false) { i: Int ->
if (embeddedClass[i]) {
emitEmbeddedObjectsCannotBeCopiedException(writer)
} else {
emitStatement("%s.insertOrUpdate(realm, (%s) object, cache)", qualifiedProxyClasses[i], qualifiedModelClasses[i])
}
}
beginControlFlow("if (iterator.hasNext())")
emitMediatorSwitch(writer, false) { i: Int ->
if (embeddedClass[i]) {
emitEmbeddedObjectsCannotBeCopiedException(writer)
} else {
emitStatement("%s.insertOrUpdate(realm, iterator, cache)", qualifiedProxyClasses[i])
}
}
endControlFlow()
endControlFlow()
} else {
emitEmbeddedObjectsCannotBeCopiedException(writer)
}
endMethod()
emitEmptyLine()
}
}
private fun emitEmbeddedObjectsCannotBeCopiedException(writer: JavaWriter) {
writer.apply {
emitStatement("throw new IllegalArgumentException(\"Embedded objects cannot be copied into Realm by themselves. They need to be attached to a parent object\")")
}
}
@Throws(IOException::class)
private fun emitInsertListToRealmMethod(writer: JavaWriter) {
writer.apply {
emitAnnotation("Override")
beginMethod(
"void",
"insert",
EnumSet.of(Modifier.PUBLIC),
"Realm", "realm", "Collection<? extends RealmModel>", "objects")
if (embeddedClass.contains(false)) {
emitStatement("Iterator<? extends RealmModel> iterator = objects.iterator()")
emitStatement("RealmModel object = null")
emitStatement("Map<RealmModel, Long> cache = new HashMap<RealmModel, Long>(objects.size())")
beginControlFlow("if (iterator.hasNext())")
.emitSingleLineComment(" access the first element to figure out the clazz for the routing below")
.emitStatement("object = iterator.next()")
.emitSingleLineComment("This cast is correct because obj is either")
.emitSingleLineComment("generated by RealmProxy or the original type extending directly from RealmObject")
.emitStatement("@SuppressWarnings(\"unchecked\") Class<RealmModel> clazz = (Class<RealmModel>) ((object instanceof RealmObjectProxy) ? object.getClass().getSuperclass() : object.getClass())")
.emitEmptyLine()
emitMediatorSwitch(writer, false, { i: Int ->
if (embeddedClass[i]) {
emitEmbeddedObjectsCannotBeCopiedException(writer)
} else {
emitStatement("%s.insert(realm, (%s) object, cache)", qualifiedProxyClasses[i], qualifiedModelClasses[i])
}
})
beginControlFlow("if (iterator.hasNext())")
emitMediatorSwitch(writer, false, { i: Int ->
if (embeddedClass[i]) {
emitEmbeddedObjectsCannotBeCopiedException(writer)
} else {
emitStatement("%s.insert(realm, iterator, cache)", qualifiedProxyClasses[i])
}
})
endControlFlow()
endControlFlow()
} else {
emitEmbeddedObjectsCannotBeCopiedException(writer)
}
endMethod()
emitEmptyLine()
}
}
@Throws(IOException::class)
private fun emitCreteOrUpdateUsingJsonObject(writer: JavaWriter) {
writer.apply {
emitAnnotation("Override")
beginMethod(
"<E extends RealmModel> E",
"createOrUpdateUsingJsonObject",
EnumSet.of(Modifier.PUBLIC),
Arrays.asList("Class<E>", "clazz", "Realm", "realm", "JSONObject", "json", "boolean", "update"),
Arrays.asList("JSONException")
)
emitMediatorShortCircuitSwitch(writer, emitStatement = { i: Int ->
if (!embeddedClass[i]) {
emitStatement("return clazz.cast(%s.createOrUpdateUsingJsonObject(realm, json, update))", qualifiedProxyClasses[i])
} else {
emitStatement("throw new IllegalArgumentException(\"Importing embedded classes from JSON without a parent is not allowed\")")
}
})
endMethod()
emitEmptyLine()
}
}
@Throws(IOException::class)
private fun emitCreateUsingJsonStream(writer: JavaWriter) {
writer.apply {
emitAnnotation("Override")
beginMethod(
"<E extends RealmModel> E",
"createUsingJsonStream",
EnumSet.of(Modifier.PUBLIC),
Arrays.asList("Class<E>", "clazz", "Realm", "realm", "JsonReader", "reader"),
Arrays.asList("java.io.IOException")
)
emitMediatorShortCircuitSwitch(writer, emitStatement = { i: Int ->
if (!embeddedClass[i]) {
emitStatement("return clazz.cast(%s.createUsingJsonStream(realm, reader))", qualifiedProxyClasses[i])
} else {
emitStatement("throw new IllegalArgumentException(\"Importing embedded classes from JSON without a parent is not allowed\")")
}
})
endMethod()
emitEmptyLine()
}
}
@Throws(IOException::class)
private fun emitCreateDetachedCopyMethod(writer: JavaWriter) {
writer.apply {
emitAnnotation("Override")
beginMethod(
"<E extends RealmModel> E",
"createDetachedCopy",
EnumSet.of(Modifier.PUBLIC),
"E", "realmObject", "int", "maxDepth", "Map<RealmModel, RealmObjectProxy.CacheData<RealmModel>>", "cache"
)
emitSingleLineComment("This cast is correct because obj is either")
emitSingleLineComment("generated by RealmProxy or the original type extending directly from RealmObject")
emitStatement("@SuppressWarnings(\"unchecked\") Class<E> clazz = (Class<E>) realmObject.getClass().getSuperclass()")
emitEmptyLine()
emitMediatorShortCircuitSwitch(writer, false, { i: Int ->
emitStatement("return clazz.cast(%s.createDetachedCopy((%s) realmObject, 0, maxDepth, cache))",
qualifiedProxyClasses[i], qualifiedModelClasses[i])
})
endMethod()
emitEmptyLine()
}
}
@Throws(IOException::class)
private fun emitIsEmbeddedMethod(writer: JavaWriter) {
writer.apply {
emitAnnotation("Override")
beginMethod(
"<E extends RealmModel> boolean",
"isEmbedded",
EnumSet.of(Modifier.PUBLIC),
"Class<E>", "clazz"
)
emitMediatorShortCircuitSwitch(writer, false, { i: Int ->
emitStatement("return %s", if (embeddedClass[i]) "true" else "false")
})
endMethod()
emitEmptyLine()
}
}
@Throws(IOException::class)
private fun emitUpdateEmbeddedObjectMethod(writer: JavaWriter) {
writer.apply {
emitAnnotation("Override")
beginMethod(
"<E extends RealmModel> void",
"updateEmbeddedObject",
EnumSet.of(Modifier.PUBLIC),
"Realm", "realm",
"E", "unmanagedObject",
"E", "managedObject",
"Map<RealmModel, RealmObjectProxy>", "cache",
"Set<ImportFlag>", "flags"
)
emitSingleLineComment("This cast is correct because obj is either")
emitSingleLineComment("generated by RealmProxy or the original type extending directly from RealmObject")
emitStatement("@SuppressWarnings(\"unchecked\") Class<E> clazz = (Class<E>) managedObject.getClass().getSuperclass()")
emitEmptyLine()
emitMediatorSwitch(writer, false) { i: Int ->
if (embeddedClass[i]) {
emitStatement("%1\$s.updateEmbeddedObject(realm, (%2\$s) unmanagedObject, (%2\$s) managedObject, cache, flags)", qualifiedProxyClasses[i], qualifiedModelClasses[i])
} else {
emitStatement("throw getNotEmbeddedClassException(\"%s\")", qualifiedModelClasses[i])
}
}
endMethod()
emitEmptyLine()
}
}
// Emits the control flow for selecting the appropriate proxy class based on the model class
// Currently it is just if..else, which is inefficient for large amounts amounts of model classes.
// Consider switching to HashMap or similar.
@Throws(IOException::class)
private fun emitMediatorSwitch(writer: JavaWriter, nullPointerCheck: Boolean, emitStatement: (index: Int) -> Unit) {
writer.apply {
if (nullPointerCheck) {
emitStatement("checkClass(clazz)")
emitEmptyLine()
}
if (qualifiedModelClasses.isEmpty()) {
emitStatement("throw getMissingProxyClassException(clazz)")
} else {
beginControlFlow("if (clazz.equals(%s.class))", qualifiedModelClasses[0])
emitStatement(0)
for (i in 1 until qualifiedModelClasses.size) {
nextControlFlow("else if (clazz.equals(%s.class))", qualifiedModelClasses[i])
emitStatement(i)
}
nextControlFlow("else")
emitStatement("throw getMissingProxyClassException(clazz)")
endControlFlow()
}
}
}
@Throws(IOException::class)
private fun emitMediatorShortCircuitSwitch(writer: JavaWriter, nullPointerCheck: Boolean = true, emitStatement: (index: Int) -> Unit) {
writer.apply {
if (nullPointerCheck) {
emitStatement("checkClass(clazz)")
emitEmptyLine()
}
for (i in qualifiedModelClasses.indices) {
beginControlFlow("if (clazz.equals(%s.class))", qualifiedModelClasses[i])
emitStatement(i)
endControlFlow()
}
emitStatement("throw getMissingProxyClassException(clazz)")
}
}
@Throws(IOException::class)
private fun emitMediatorInverseShortCircuitSwitch(writer: JavaWriter, nullPointerCheck: Boolean = true, emitStatement: (index: Int) -> Unit) {
writer.apply {
if (nullPointerCheck) {
emitStatement("checkClassName(className)")
emitEmptyLine()
}
for (i in qualifiedModelClasses.indices) {
beginControlFlow("if (className.equals(\"%s\"))", internalClassNames[i])
emitStatement(i)
endControlFlow()
}
emitStatement("throw getMissingProxyClassException(className)")
}
}
}
| apache-2.0 | fa5af3961c4cc3163ac49996369e27cc | 44.400631 | 219 | 0.568093 | 5.376167 | false | false | false | false |
jainsahab/AndroidSnooper | Snooper/src/main/java/com/prateekj/snooper/networksnooper/model/HttpCallRecord.kt | 1 | 1622 | package com.prateekj.snooper.networksnooper.model
import java.util.Date
class HttpCallRecord {
var id: Long = 0
var url: String? = null
var payload: String? = null
var method: String? = null
var responseBody: String? = null
var statusText: String? = null
var statusCode: Int = 0
var date: Date? = null
var error: String? = null
var requestHeaders: List<HttpHeader>? = null
var responseHeaders: List<HttpHeader>? = null
fun getResponseHeader(name: String): HttpHeader? {
return filterFromCollection(name, responseHeaders)
}
fun getRequestHeader(name: String): HttpHeader? {
return filterFromCollection(name, requestHeaders)
}
private fun filterFromCollection(name: String, collection: List<HttpHeader>?): HttpHeader? {
return collection?.firstOrNull { header -> header.name.equals(name, ignoreCase = true) }
}
fun hasError(): Boolean {
return error != null
}
companion object {
fun from(httpCall: HttpCall): HttpCallRecord {
val httpCallRecord = HttpCallRecord()
httpCallRecord.url = httpCall.url
httpCallRecord.payload = httpCall.payload
httpCallRecord.method = httpCall.method
httpCallRecord.responseBody = httpCall.responseBody
httpCallRecord.statusText = httpCall.statusText
httpCallRecord.statusCode = httpCall.statusCode
httpCallRecord.date = httpCall.date
httpCallRecord.error = httpCall.error
httpCallRecord.requestHeaders = HttpHeader.from(httpCall.requestHeaders)
httpCallRecord.responseHeaders = HttpHeader.from(httpCall.responseHeaders)
return httpCallRecord
}
}
}
| apache-2.0 | d09f7eaf7f187f51afc6437a1d7fae55 | 30.803922 | 94 | 0.727497 | 4.756598 | false | false | false | false |
PolymerLabs/arcs | javatests/arcs/core/data/proto/AccessPathProtoDecoderTest.kt | 1 | 4586 | package arcs.core.data.proto
import arcs.core.data.AccessPath
import arcs.core.data.HandleConnectionSpec
import arcs.core.data.HandleMode
import arcs.core.data.ParticleSpec
import arcs.core.data.Recipe
import arcs.core.data.TypeVariable
import com.google.common.truth.Truth.assertThat
import kotlin.test.assertFailsWith
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.JUnit4
@RunWith(JUnit4::class)
class AccessPathProtoDecoderTest {
@Test
fun roundTrip_withoutSelectors() {
val handleConnectionSpec = HandleConnectionSpec(
"input",
HandleMode.Write,
TypeVariable("input")
)
val accessPath = AccessPath("TestSpec", handleConnectionSpec)
val encoded = accessPath.encode()
val decoded = encoded.decode(mapOf("input" to handleConnectionSpec))
assertThat(decoded).isEqualTo(accessPath)
}
@Test
fun roundTrip_withSelectors() {
val handleConnectionSpec = HandleConnectionSpec(
"input",
HandleMode.Write,
TypeVariable("input")
)
val accessPath = AccessPath(
"TestSpec",
handleConnectionSpec,
selectors = listOf(
AccessPath.Selector.Field("address"),
AccessPath.Selector.Field("street")
)
)
val encoded = accessPath.encode()
val decoded = encoded.decode(mapOf("input" to handleConnectionSpec))
assertThat(decoded).isEqualTo(accessPath)
}
@Test
fun roundTrip_storeRoot() {
val accessPath = AccessPath(
AccessPath.Root.Store("store_id"),
listOf(AccessPath.Selector.Field("some_field"))
)
assertThat(accessPath.encode().decode(emptyMap())).isEqualTo(accessPath)
}
@Test
fun encode_handleConnectionSpec() {
val expected = AccessPathProto.newBuilder()
expected.handle = AccessPathProto.HandleRoot.newBuilder()
.setHandleConnection("input")
.setParticleSpec("TestSpec")
.build()
val handleConnectionSpec = HandleConnectionSpec(
"input",
HandleMode.Write,
TypeVariable("input")
)
val accessPath = AccessPath("TestSpec", handleConnectionSpec)
val encoded = accessPath.encode()
assertThat(encoded).isEqualTo(expected.build())
}
@Test
fun encode_handleConnection() {
val expected = AccessPathProto.newBuilder()
expected.handle = AccessPathProto.HandleRoot.newBuilder()
.setHandleConnection("input")
.setParticleSpec("TestSpec")
.build()
val particleSpec = ParticleSpec("TestSpec", emptyMap(), "Location")
val particle = Recipe.Particle(particleSpec, emptyList())
val handleConnectionSpec = HandleConnectionSpec(
"input",
HandleMode.Write,
TypeVariable("input")
)
val accessPath = AccessPath(particle, handleConnectionSpec)
assertThat(accessPath.encode()).isEqualTo(expected.build())
}
@Test
fun encode_handle() {
val expected = AccessPathProto.newBuilder()
expected.handle = AccessPathProto.HandleRoot.newBuilder()
.setHandleConnection("handle1")
.build()
val handle = Recipe.Handle(
"handle1",
Recipe.Handle.Fate.MAP,
TypeVariable("handle1")
)
val accessPath = AccessPath(handle)
assertThat(accessPath.encode()).isEqualTo(expected.build())
}
@Test
fun encode_store() {
val expected = AccessPathProto.newBuilder()
expected.storeId = "store_id"
val accessPath = AccessPath(AccessPath.Root.Store("store_id"))
assertThat(accessPath.encode()).isEqualTo(expected.build())
}
@Test
fun decode_detectsMissingConnections() {
val proto = AccessPathProto.newBuilder()
.setHandle(AccessPathProto.HandleRoot.newBuilder().setHandleConnection("input"))
.build()
val exception = assertFailsWith<IllegalArgumentException> {
proto.decode(emptyMap())
}
assertThat(exception)
.hasMessageThat()
.contains("Connection 'input' not found in connection specs!")
}
@Test
fun decode_emptyRootFails() {
val proto = AccessPathProto.newBuilder().build()
val exception = assertFailsWith<UnsupportedOperationException> {
proto.decode(emptyMap())
}
assertThat(exception)
.hasMessageThat()
.isEqualTo("Unsupported AccessPathProto.Root: ROOT_NOT_SET")
}
@Test
fun decode_selector_emptySelectorFails() {
val proto = AccessPathProto.Selector.newBuilder().build()
val exception = assertFailsWith<UnsupportedOperationException> {
proto.decode()
}
assertThat(exception)
.hasMessageThat()
.isEqualTo("Unsupported AccessPathProto.Selector: SELECTOR_NOT_SET")
}
}
| bsd-3-clause | 559a5af5c37e12f39e693d26cbba9060 | 26.963415 | 86 | 0.701047 | 4.359316 | false | true | false | false |
PolymerLabs/arcs | particles/Blackjack/Card.kt | 2 | 570 | package arcs.tutorials.blackjack
// Describes a card in a deck.
class Card(inputValue: Int = -1) {
val value = inputValue
init {
require(inputValue in -1 until 52)
}
override fun toString() = Card.cardDesc(value)
companion object {
val cardNames = arrayOf("A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K")
var suitNames = arrayOf("♦", "♥", "♠", "♣")
public fun cardDesc(faceValue: Int): String {
if (faceValue == -1) return "Joker"
return cardNames[faceValue % 13] + suitNames[faceValue % 4]
}
}
}
| bsd-3-clause | f232380c2122c5d30d634ff95d7d718b | 25.761905 | 93 | 0.58363 | 3.054348 | false | false | false | false |
PolymerLabs/arcs | java/arcs/core/util/BitVector.kt | 1 | 5425 | /*
* Copyright 2020 Google LLC.
*
* This code may only be used under the BSD style license found at
* http://polymer.github.io/LICENSE.txt
*
* Code distributed by Google as part of this project is also subject to an additional IP rights
* grant found at
* http://polymer.github.io/PATENTS.txt
*/
package arcs.core.util
/**
* Implementation of a bit vector as an array of bytes. Supports iterating over arbitrarily-sized
* windows (of length between 1 and 32).
*/
class BitVector(
/** Backing data for the [BitVector]. */
val bytes: ByteArray,
/** Capacity of the [BitVector]. */
val sizeBits: Int = bytes.size * 8,
usedBits: Int = bytes.size * 8
) {
/** Number of bits used by the [BitVector]. */
var usedBits = usedBits
private set
init {
/* ktlint-disable max-line-length */
require(sizeBits in 0..(bytes.size * 8)) {
"sizeBits must not be larger than the available space in the byte array and greater than 0"
}
require(usedBits in 0..(bytes.size * 8)) {
"usedBits must not be larger than the available space in the byte array and greater than 0"
}
/* ktlint-enable max-line-length */
}
/** Creates an empty (all zeros, with [usedBits] = 0) [BitVector] of length [bitCount]. */
constructor(bitCount: Int) : this(
ByteArray(bitCount / 8 + if (bitCount % 8 > 0) 1 else 0),
sizeBits = bitCount,
usedBits = 0
)
/**
* Adds the masked value of bits to the end of the [BitVector].
*
* @param bitRange range of bits to select from the [byte], where for each value `i` in the
* range: `byte\[i]` is the `i`th bit from the right. E.g. `appendBits(0b01110000, 4..6)`
* would select the 1s.
*/
fun appendBits(byte: Byte, bitRange: IntRange = 0..7) {
val numBits = bitRange.last - bitRange.first + 1
require(
bitRange.first >= 0 && bitRange.last <= 7
) { "bitRange must be a subrange of [0, 8)" }
/* ktlint-disable max-line-length */
require(usedBits + numBits <= sizeBits) {
"Cannot insert $numBits bits. Capacity needs to be ${usedBits + numBits}. (it's $sizeBits)"
}
/* ktlint-enable max-line-length */
val sizedMask = (FULL_MASK ushr (32 - numBits))
// Shift the byte and mask it so we select only the values to inject.
val bits = ((byte.toInt() and 0xFF) ushr bitRange.first) and sizedMask
val currentByte = bytes[usedBits / 8].toInt() and 0xFF
if (8 - usedBits % 8 >= numBits) {
// Our bits to appendBits can fit within the current byte.
val shiftAmount = 8 - usedBits % 8 - numBits
bytes[usedBits / 8] = (currentByte or (bits shl shiftAmount)).toByte()
} else {
// Our bits need to span the current byte and the next byte.
val nextByte = bytes[usedBits / 8 + 1].toInt() and 0xFF
val firstByteBitCount = 8 - usedBits % 8
val secondByteBitCount = numBits - firstByteBitCount
val firstByteMask = (FULL_MASK ushr (32 - firstByteBitCount)) shl secondByteBitCount
val secondByteMask = (FULL_MASK ushr (32 - secondByteBitCount))
bytes[usedBits / 8] =
(currentByte or ((bits and firstByteMask) shr secondByteBitCount)).toByte()
bytes[usedBits / 8 + 1] =
(nextByte or ((bits and secondByteMask) shl (8 - secondByteBitCount))).toByte()
}
usedBits += numBits
}
fun asSequenceOfInts(bitsPerValue: Int): Sequence<Window> {
require(bitsPerValue in 1..32) {
"Invalid `bitsPerValue`, must be between 1 and 32 (inclusive)."
}
return Sequence {
var bitIndex = 0
object : Iterator<Window> {
override fun hasNext(): Boolean = bitIndex < usedBits
override fun next(): Window {
val startPoint = bitIndex
var remainingBits = bitsPerValue
var windowValue = 0
while (remainingBits > 0 && bitIndex < usedBits) {
val currentByte = bytes[bitIndex / 8]
val bitsAchieved = minOf(8 - bitIndex % 8, remainingBits)
val bitMaskLeftShift = (8 - bitIndex % 8) - bitsAchieved
val bitMask = (FULL_MASK ushr 32 - bitsAchieved) shl bitMaskLeftShift
val ourBits = (currentByte.toInt() and 0xFF) and bitMask
val ourBitsShiftedRight = ourBits ushr bitMaskLeftShift
val offset = remainingBits - bitsAchieved
windowValue = windowValue or (ourBitsShiftedRight shl offset)
remainingBits -= bitsAchieved
bitIndex += bitsAchieved
}
return Window(windowValue, remainingBits, bitsPerValue, startPoint)
}
}
}
}
/** Represents a window into a [BitVector]. */
data class Window(
/** Contains [size] bits in the least-significant position (shifted all the way to the right. */
val value: Int,
/**
* Number of padding bits required to fill-out [size] bits when the [BitVector] wasn't a
* multiple of [size].
*/
val paddingBits: Int,
/**
* Number of bits requested from the [BitVector].
*
* **Note:** If this is the last window from a vector whose length is not a multiple of [size],
* the number of bits in [value] is equal to `size - paddingBits`.
*/
val size: Int,
/** Location within the [BitVector] where the [value] can be found. */
val position: Int
)
companion object {
private const val FULL_MASK = -1 // Because 0xFFFFFFFF in kotlin is a Long.
}
}
| bsd-3-clause | 97c584fbffb9d02c53945898bdcc98ec | 33.775641 | 100 | 0.637604 | 3.855721 | false | false | false | false |
AcornUI/Acorn | acornui-core/src/test/kotlin/com/acornui/time/TimerTest.kt | 1 | 1627 | /*
* Copyright 2020 Poly Forest, LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.acornui.time
import com.acornui.async.delay
import com.acornui.test.assertClose
import com.acornui.test.runTest
import kotlinx.coroutines.launch
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.fail
import kotlin.time.seconds
class TimerTest {
@Test fun dispose() = runTest {
val handle = timer(0.5.seconds) {
fail("Disposing handle expected to prevent timer")
}
launch {
delay(0.1.seconds)
handle.dispose()
}
delay(1.seconds)
}
@Test fun disposeOnCallback() = runTest {
var c = 0
timer(0.1.seconds) {
c++
it.dispose()
}
delay(0.5.seconds)
assertEquals(1, c)
}
@Test fun repetitions() = runTest {
var c = 0
timer(0.1.seconds, repetitions = 3) {
c++
}
delay(0.5.seconds)
assertEquals(3, c)
}
@Test fun delay() = runTest {
val start = markNow()
var callTime = -1.0
timer(0.1.seconds, delay = 0.3.seconds) {
callTime = start.elapsedNow().inMilliseconds
}
delay(0.5.seconds)
assertClose(400.0, callTime, 50.0)
}
}
| apache-2.0 | 22b4197df5a946a2ca04f633cf58a741 | 22.242857 | 75 | 0.698832 | 3.215415 | false | true | false | false |
DuncanCasteleyn/DiscordModBot | src/main/kotlin/be/duncanc/discordmodbot/data/services/ScheduledUnmuteService.kt | 1 | 5354 | package be.duncanc.discordmodbot.data.services
import be.duncanc.discordmodbot.bot.services.GuildLogger
import be.duncanc.discordmodbot.bot.services.GuildLogger.LogTypeAction.MODERATOR
import be.duncanc.discordmodbot.bot.utils.nicknameAndUsername
import be.duncanc.discordmodbot.data.entities.MuteRole
import be.duncanc.discordmodbot.data.entities.ScheduledUnmute
import be.duncanc.discordmodbot.data.repositories.jpa.MuteRolesRepository
import be.duncanc.discordmodbot.data.repositories.jpa.ScheduledUnmuteRepository
import net.dv8tion.jda.api.EmbedBuilder
import net.dv8tion.jda.api.JDA
import net.dv8tion.jda.api.entities.Guild
import net.dv8tion.jda.api.entities.Member
import net.dv8tion.jda.api.entities.Role
import org.springframework.context.annotation.Lazy
import org.springframework.scheduling.annotation.Scheduled
import org.springframework.stereotype.Service
import java.awt.Color
import java.time.OffsetDateTime
import javax.transaction.Transactional
@Service
class ScheduledUnmuteService(
private val scheduledUnmuteRepository: ScheduledUnmuteRepository,
private val muteRolesRepository: MuteRolesRepository,
private val guildLogger: GuildLogger,
@Lazy
private val jda: JDA
) {
@Transactional
fun planUnmute(guildId: Long, userId: Long, unmuteDateTime: OffsetDateTime) {
if (unmuteDateTime.isAfter(OffsetDateTime.now().plusYears(1))) {
throw IllegalArgumentException("A mute can't take longer than 1 year")
}
if (unmuteDateTime.isBefore(OffsetDateTime.now())) {
throw IllegalArgumentException("An unmute should not be planned in the past")
}
if (unmuteDateTime.isBefore(OffsetDateTime.now().plusMinutes(30))) {
throw IllegalArgumentException("An unmute should be planned at least more than 30 minutes in the future")
}
val scheduledUnmute = ScheduledUnmute(guildId, userId, unmuteDateTime)
scheduledUnmuteRepository.save(scheduledUnmute)
}
@Scheduled(cron = "0 0/20 * * * *")
@Transactional
fun performUnmute() {
scheduledUnmuteRepository.findAllByUnmuteDateTimeIsBefore(OffsetDateTime.now()).forEach { scheduledUnmute ->
jda.getGuildById(scheduledUnmute.guildId)?.let { guild ->
unmuteMembers(scheduledUnmute, guild)
}
}
}
private fun unmuteMembers(scheduledUnmute: ScheduledUnmute, guild: Guild) {
val member = guild.getMemberById(scheduledUnmute.userId)
if (member != null) {
unmuteMember(guild, scheduledUnmute, member)
} else {
removeMuteFromDb(scheduledUnmute, guild)
}
}
private fun removeMuteFromDb(scheduledUnmute: ScheduledUnmute, guild: Guild) {
muteRolesRepository.findById(guild.idLong).ifPresent { muteRole ->
val userId = scheduledUnmute.userId
muteRole.mutedUsers.remove(userId)
muteRolesRepository.save(muteRole)
scheduledUnmuteRepository.delete(scheduledUnmute)
guild.jda.retrieveUserById(userId).queue { user ->
val logEmbed = EmbedBuilder()
.setColor(Color.green)
.setTitle("User unmuted")
.addField("User", user.name, true)
.addField("Reason", "Mute expired", false)
guildLogger.log(logEmbed, user, guild, actionType = MODERATOR)
}
}
}
private fun unmuteMember(guild: Guild, scheduledUnmute: ScheduledUnmute, member: Member) {
muteRolesRepository.findById(guild.idLong).ifPresent { muteRole ->
removeUserFromMuteRole(guild, muteRole, member, scheduledUnmute)
}
}
private fun removeUserFromMuteRole(
guild: Guild,
muteRole: MuteRole,
member: Member,
scheduledUnmute: ScheduledUnmute
) {
guild.getRoleById(muteRole.roleId)?.let { role ->
removeMute(guild, member, scheduledUnmute, role)
}
}
private fun removeMute(guild: Guild, member: Member, scheduledUnmute: ScheduledUnmute, role: Role) {
guild.removeRoleFromMember(member, role).queue {
scheduledUnmuteRepository.delete(scheduledUnmute)
logUnmute(guild, member)
informUserIsUnmuted(member)
}
}
private fun logUnmute(guild: Guild, member: Member) {
val logEmbed = EmbedBuilder()
.setColor(Color.green)
.setTitle("User unmuted")
.addField("User", member.nicknameAndUsername, true)
.addField("Reason", "Mute expired", false)
guildLogger.log(logEmbed, member.user, guild, actionType = MODERATOR)
}
private fun informUserIsUnmuted(member: Member) {
val selfUser = member.jda.selfUser
val guild = member.guild
val embed = EmbedBuilder()
.setColor(Color.green)
.setAuthor(
guild.getMember(selfUser)?.nicknameAndUsername ?: selfUser.name,
null,
selfUser.effectiveAvatarUrl
)
.setTitle(guild.name + ": Your mute has been removed")
.addField("Reason", "Mute expired", false)
.build()
member.user.openPrivateChannel().queue {
it.sendMessageEmbeds(embed).queue()
}
}
}
| apache-2.0 | 8dc032d580a1517dd3591f7c13414fc1 | 38.367647 | 117 | 0.673328 | 4.738053 | false | false | false | false |
wordpress-mobile/WordPress-Android | WordPress/src/main/java/org/wordpress/android/ui/mediapicker/MediaPickerFragment.kt | 1 | 29788 | package org.wordpress.android.ui.mediapicker
import android.Manifest.permission
import android.app.Activity
import android.content.Intent.ACTION_GET_CONTENT
import android.content.Intent.ACTION_OPEN_DOCUMENT
import android.net.Uri
import android.os.Bundle
import android.os.Parcelable
import android.view.LayoutInflater
import android.view.Menu
import android.view.MenuInflater
import android.view.MenuItem
import android.view.MenuItem.OnActionExpandListener
import android.view.View
import android.view.ViewGroup
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AlertDialog.Builder
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.widget.SearchView
import androidx.core.text.HtmlCompat
import androidx.fragment.app.Fragment
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.viewModelScope
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.GridLayoutManager.SpanSizeLookup
import com.google.android.material.dialog.MaterialAlertDialogBuilder
import com.google.android.material.snackbar.Snackbar
import org.wordpress.android.R
import org.wordpress.android.WordPress
import org.wordpress.android.databinding.MediaPickerFragmentBinding
import org.wordpress.android.fluxc.model.SiteModel
import org.wordpress.android.ui.ActivityLauncher
import org.wordpress.android.ui.media.MediaPreviewActivity
import org.wordpress.android.ui.mediapicker.MediaItem.Identifier
import org.wordpress.android.ui.mediapicker.MediaNavigationEvent.EditMedia
import org.wordpress.android.ui.mediapicker.MediaNavigationEvent.Exit
import org.wordpress.android.ui.mediapicker.MediaNavigationEvent.IconClickEvent
import org.wordpress.android.ui.mediapicker.MediaNavigationEvent.InsertMedia
import org.wordpress.android.ui.mediapicker.MediaNavigationEvent.PreviewMedia
import org.wordpress.android.ui.mediapicker.MediaNavigationEvent.PreviewUrl
import org.wordpress.android.ui.mediapicker.MediaPickerFragment.MediaPickerIconType.ANDROID_CHOOSE_FROM_DEVICE
import org.wordpress.android.ui.mediapicker.MediaPickerFragment.MediaPickerIconType.CAPTURE_PHOTO
import org.wordpress.android.ui.mediapicker.MediaPickerFragment.MediaPickerIconType.SWITCH_SOURCE
import org.wordpress.android.ui.mediapicker.MediaPickerFragment.MediaPickerIconType.WP_STORIES_CAPTURE
import org.wordpress.android.ui.mediapicker.MediaPickerSetup.DataSource
import org.wordpress.android.ui.mediapicker.MediaPickerViewModel.ActionModeUiModel
import org.wordpress.android.ui.mediapicker.MediaPickerViewModel.BrowseMenuUiModel.BrowseAction.DEVICE
import org.wordpress.android.ui.mediapicker.MediaPickerViewModel.BrowseMenuUiModel.BrowseAction.GIF_LIBRARY
import org.wordpress.android.ui.mediapicker.MediaPickerViewModel.BrowseMenuUiModel.BrowseAction.STOCK_LIBRARY
import org.wordpress.android.ui.mediapicker.MediaPickerViewModel.BrowseMenuUiModel.BrowseAction.SYSTEM_PICKER
import org.wordpress.android.ui.mediapicker.MediaPickerViewModel.BrowseMenuUiModel.BrowseAction.WP_MEDIA_LIBRARY
import org.wordpress.android.ui.mediapicker.MediaPickerViewModel.FabUiModel
import org.wordpress.android.ui.mediapicker.MediaPickerViewModel.PermissionsRequested.CAMERA
import org.wordpress.android.ui.mediapicker.MediaPickerViewModel.PermissionsRequested.STORAGE
import org.wordpress.android.ui.mediapicker.MediaPickerViewModel.PhotoListUiModel
import org.wordpress.android.ui.mediapicker.MediaPickerViewModel.ProgressDialogUiModel
import org.wordpress.android.ui.mediapicker.MediaPickerViewModel.ProgressDialogUiModel.Visible
import org.wordpress.android.ui.mediapicker.MediaPickerViewModel.SearchUiModel
import org.wordpress.android.ui.mediapicker.MediaPickerViewModel.SoftAskViewUiModel
import org.wordpress.android.ui.pages.SnackbarMessageHolder
import org.wordpress.android.ui.utils.UiHelpers
import org.wordpress.android.ui.utils.UiString.UiStringRes
import org.wordpress.android.util.AccessibilityUtils
import org.wordpress.android.util.AniUtils
import org.wordpress.android.util.AniUtils.Duration.MEDIUM
import org.wordpress.android.util.SnackbarItem
import org.wordpress.android.util.SnackbarItem.Action
import org.wordpress.android.util.SnackbarItem.Info
import org.wordpress.android.util.SnackbarSequencer
import org.wordpress.android.util.UriWrapper
import org.wordpress.android.util.WPLinkMovementMethod
import org.wordpress.android.util.WPMediaUtils
import org.wordpress.android.util.WPPermissionUtils
import org.wordpress.android.util.WPSwipeToRefreshHelper
import org.wordpress.android.util.image.ImageManager
import org.wordpress.android.viewmodel.observeEvent
import javax.inject.Inject
class MediaPickerFragment : Fragment() {
enum class MediaPickerIconType {
ANDROID_CHOOSE_FROM_DEVICE,
SWITCH_SOURCE,
WP_STORIES_CAPTURE,
CAPTURE_PHOTO;
companion object {
@JvmStatic
fun fromNameString(iconTypeName: String): MediaPickerIconType {
return values().firstOrNull { it.name == iconTypeName }
?: throw IllegalArgumentException("MediaPickerIconType not found with name $iconTypeName")
}
}
}
enum class ChooserContext(
val intentAction: String,
val title: UiStringRes,
val mediaTypeFilter: String
) {
PHOTO(ACTION_GET_CONTENT, UiStringRes(R.string.pick_photo), "image/*"),
VIDEO(ACTION_GET_CONTENT, UiStringRes(R.string.pick_video), "video/*"),
PHOTO_OR_VIDEO(ACTION_GET_CONTENT, UiStringRes(R.string.pick_media), "*/*"),
AUDIO(ACTION_GET_CONTENT, UiStringRes(R.string.pick_audio), "*/*"),
MEDIA_FILE(ACTION_OPEN_DOCUMENT, UiStringRes(R.string.pick_file), "*/*");
}
sealed class MediaPickerAction {
data class OpenSystemPicker(
val chooserContext: ChooserContext,
val mimeTypes: List<String>,
val allowMultipleSelection: Boolean
) : MediaPickerAction()
data class OpenCameraForWPStories(val allowMultipleSelection: Boolean) : MediaPickerAction()
object OpenCameraForPhotos : MediaPickerAction()
data class SwitchMediaPicker(val mediaPickerSetup: MediaPickerSetup) : MediaPickerAction()
}
sealed class MediaPickerIcon(val type: MediaPickerIconType) {
data class ChooseFromAndroidDevice(
val allowedTypes: Set<MediaType>
) : MediaPickerIcon(ANDROID_CHOOSE_FROM_DEVICE)
data class SwitchSource(val dataSource: DataSource) : MediaPickerIcon(SWITCH_SOURCE)
object WpStoriesCapture : MediaPickerIcon(WP_STORIES_CAPTURE)
object CapturePhoto : MediaPickerIcon(CAPTURE_PHOTO)
fun toBundle(bundle: Bundle) {
bundle.putString(KEY_LAST_TAPPED_ICON, type.name)
when (this) {
is ChooseFromAndroidDevice -> {
bundle.putStringArrayList(
KEY_LAST_TAPPED_ICON_ALLOWED_TYPES,
ArrayList(allowedTypes.map { it.name })
)
}
is SwitchSource -> {
bundle.putInt(KEY_LAST_TAPPED_ICON_DATA_SOURCE, this.dataSource.ordinal)
}
is CapturePhoto -> Unit // Do nothing
is WpStoriesCapture -> Unit // Do nothing
}
}
companion object {
@JvmStatic
fun fromBundle(bundle: Bundle): MediaPickerIcon? {
val iconTypeName = bundle.getString(KEY_LAST_TAPPED_ICON) ?: return null
return when (iconTypeName.let { MediaPickerIconType.fromNameString(iconTypeName) }) {
ANDROID_CHOOSE_FROM_DEVICE -> {
val allowedTypes = (bundle.getStringArrayList(KEY_LAST_TAPPED_ICON_ALLOWED_TYPES)
?: listOf<String>()).map {
MediaType.valueOf(
it
)
}.toSet()
ChooseFromAndroidDevice(allowedTypes)
}
WP_STORIES_CAPTURE -> WpStoriesCapture
CAPTURE_PHOTO -> CapturePhoto
SWITCH_SOURCE -> {
val ordinal = bundle.getInt(KEY_LAST_TAPPED_ICON_DATA_SOURCE, -1)
if (ordinal != -1) {
val dataSource = DataSource.values()[ordinal]
SwitchSource(dataSource)
} else {
null
}
}
}
}
}
}
/*
* parent activity must implement this listener
*/
interface MediaPickerListener {
fun onItemsChosen(identifiers: List<Identifier>)
fun onIconClicked(action: MediaPickerAction)
}
private var listener: MediaPickerListener? = null
@Inject lateinit var imageManager: ImageManager
@Inject lateinit var viewModelFactory: ViewModelProvider.Factory
@Inject lateinit var snackbarSequencer: SnackbarSequencer
@Inject lateinit var uiHelpers: UiHelpers
private lateinit var viewModel: MediaPickerViewModel
private var binding: MediaPickerFragmentBinding? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
(requireActivity().application as WordPress).component().inject(this)
viewModel = ViewModelProvider(this, viewModelFactory).get(MediaPickerViewModel::class.java)
setHasOptionsMenu(true)
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return inflater.inflate(
R.layout.media_picker_fragment,
container,
false
)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val mediaPickerSetup = MediaPickerSetup.fromBundle(requireArguments())
val site = requireArguments().getSerializable(WordPress.SITE) as? SiteModel
var selectedIds: List<Identifier>? = null
var lastTappedIcon: MediaPickerIcon? = null
if (savedInstanceState != null) {
lastTappedIcon = MediaPickerIcon.fromBundle(savedInstanceState)
if (savedInstanceState.containsKey(KEY_SELECTED_IDS)) {
selectedIds = savedInstanceState.getParcelableArrayList<Identifier>(KEY_SELECTED_IDS)?.map { it }
}
}
val layoutManager = GridLayoutManager(
activity,
NUM_COLUMNS
)
savedInstanceState?.getParcelable<Parcelable>(KEY_LIST_STATE)?.let {
layoutManager.onRestoreInstanceState(it)
}
with(MediaPickerFragmentBinding.bind(view)) {
setUpRecyclerView(layoutManager)
val swipeToRefreshHelper = WPSwipeToRefreshHelper.buildSwipeToRefreshHelper(pullToRefresh) {
viewModel.onPullToRefresh()
}
var isShowingActionMode = false
viewModel.uiState.observe(viewLifecycleOwner, Observer {
it?.let { uiState ->
setupPhotoList(uiState.photoListUiModel)
setupSoftAskView(uiState.softAskViewUiModel)
if (uiState.actionModeUiModel is ActionModeUiModel.Visible && !isShowingActionMode) {
isShowingActionMode = true
(activity as AppCompatActivity).startSupportActionMode(
MediaPickerActionModeCallback(
viewModel
)
)
} else if (uiState.actionModeUiModel is ActionModeUiModel.Hidden && isShowingActionMode) {
isShowingActionMode = false
}
setupFab(uiState.fabUiModel)
swipeToRefreshHelper.isRefreshing = uiState.isRefreshing
}
})
viewModel.onNavigate.observeEvent(viewLifecycleOwner) { navigationEvent ->
navigateEvent(navigationEvent)
}
viewModel.onPermissionsRequested.observeEvent(viewLifecycleOwner, {
when (it) {
CAMERA -> requestCameraPermission()
STORAGE -> requestStoragePermission()
}
})
viewModel.onSnackbarMessage.observeEvent(viewLifecycleOwner, { messageHolder ->
showSnackbar(messageHolder)
})
setupProgressDialog()
viewModel.start(selectedIds, mediaPickerSetup, lastTappedIcon, site)
}
}
private fun navigateEvent(navigationEvent: MediaNavigationEvent) {
when (navigationEvent) {
is PreviewUrl -> {
MediaPreviewActivity.showPreview(
requireContext(),
null,
navigationEvent.url
)
AccessibilityUtils.setActionModeDoneButtonContentDescription(
activity,
getString(R.string.cancel)
)
}
is PreviewMedia -> MediaPreviewActivity.showPreview(
requireContext(),
null,
navigationEvent.media,
null
)
is EditMedia -> {
val inputData = WPMediaUtils.createListOfEditImageInputData(
requireContext(),
navigationEvent.uris.map { wrapper -> wrapper.uri }
)
ActivityLauncher.openImageEditor(activity, inputData)
}
is InsertMedia -> listener?.onItemsChosen(navigationEvent.identifiers)
is IconClickEvent -> listener?.onIconClicked(navigationEvent.action)
Exit -> {
val activity = requireActivity()
activity.setResult(Activity.RESULT_CANCELED)
activity.finish()
}
}
}
private fun MediaPickerFragmentBinding.setUpRecyclerView(
layoutManager: GridLayoutManager
) {
binding = this
recycler.layoutManager = layoutManager
recycler.setEmptyView(actionableEmptyView)
recycler.setHasFixedSize(true)
}
override fun onDestroyView() {
super.onDestroyView()
binding = null
}
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
super.onCreateOptionsMenu(menu, inflater)
inflater.inflate(R.menu.menu_media_picker, menu)
val searchMenuItem = checkNotNull(menu.findItem(R.id.action_search)) {
"Menu does not contain mandatory search item"
}
val browseMenuItem = checkNotNull(menu.findItem(R.id.mnu_browse_item)) {
"Menu does not contain mandatory browse item"
}
val mediaLibraryMenuItem = checkNotNull(menu.findItem(R.id.mnu_choose_from_media_library)) {
"Menu does not contain mandatory media library item"
}
val deviceMenuItem = checkNotNull(menu.findItem(R.id.mnu_choose_from_device)) {
"Menu does not contain device library item"
}
val stockLibraryMenuItem = checkNotNull(menu.findItem(R.id.mnu_choose_from_stock_library)) {
"Menu does not contain mandatory stock library item"
}
val tenorLibraryMenuItem = checkNotNull(menu.findItem(R.id.mnu_choose_from_tenor_library)) {
"Menu does not contain mandatory tenor library item"
}
initializeSearchView(searchMenuItem)
viewModel.uiState.observe(viewLifecycleOwner, Observer { uiState ->
val searchView = searchMenuItem.actionView as SearchView
if (uiState.searchUiModel is SearchUiModel.Expanded && !searchMenuItem.isActionViewExpanded) {
searchMenuItem.expandActionView()
searchView.maxWidth = Integer.MAX_VALUE
searchView.setQuery(uiState.searchUiModel.filter, true)
searchView.setOnCloseListener { !uiState.searchUiModel.closeable }
} else if (uiState.searchUiModel is SearchUiModel.Collapsed && searchMenuItem.isActionViewExpanded) {
searchMenuItem.collapseActionView()
}
searchMenuItem.isVisible = uiState.searchUiModel !is SearchUiModel.Hidden
val shownActions = uiState.browseMenuUiModel.shownActions
browseMenuItem.isVisible = shownActions.contains(SYSTEM_PICKER)
mediaLibraryMenuItem.isVisible = shownActions.contains(WP_MEDIA_LIBRARY)
deviceMenuItem.isVisible = shownActions.contains(DEVICE)
stockLibraryMenuItem.isVisible = shownActions.contains(STOCK_LIBRARY)
tenorLibraryMenuItem.isVisible = shownActions.contains(GIF_LIBRARY)
})
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
R.id.mnu_browse_item -> {
viewModel.onMenuItemClicked(SYSTEM_PICKER)
}
R.id.mnu_choose_from_media_library -> {
viewModel.onMenuItemClicked(WP_MEDIA_LIBRARY)
}
R.id.mnu_choose_from_device -> {
viewModel.onMenuItemClicked(DEVICE)
}
R.id.mnu_choose_from_stock_library -> {
viewModel.onMenuItemClicked(STOCK_LIBRARY)
}
R.id.mnu_choose_from_tenor_library -> {
viewModel.onMenuItemClicked(GIF_LIBRARY)
}
}
return true
}
fun urisSelectedFromSystemPicker(uris: List<Uri>) {
viewModel.urisSelectedFromSystemPicker(uris.map { UriWrapper(it) })
}
private fun initializeSearchView(actionMenuItem: MenuItem) {
var isExpanding = false
actionMenuItem.setOnActionExpandListener(object : OnActionExpandListener {
override fun onMenuItemActionExpand(item: MenuItem?): Boolean {
viewModel.onSearchExpanded()
isExpanding = true
return true
}
override fun onMenuItemActionCollapse(item: MenuItem?): Boolean {
viewModel.onSearchCollapsed()
return true
}
})
val searchView = actionMenuItem.actionView as SearchView
searchView.setOnQueryTextListener(object : SearchView.OnQueryTextListener {
override fun onQueryTextSubmit(query: String): Boolean {
viewModel.onSearch(query)
return true
}
override fun onQueryTextChange(query: String): Boolean {
if (!isExpanding) {
viewModel.onSearch(query)
}
isExpanding = false
return true
}
})
}
private fun MediaPickerFragmentBinding.setupSoftAskView(uiModel: SoftAskViewUiModel) {
when (uiModel) {
is SoftAskViewUiModel.Visible -> {
softAskView.title.text = HtmlCompat.fromHtml(uiModel.label, HtmlCompat.FROM_HTML_MODE_LEGACY)
softAskView.button.setText(uiModel.allowId.stringRes)
softAskView.button.setOnClickListener {
if (uiModel.isAlwaysDenied) {
WPPermissionUtils.showAppSettings(requireActivity())
} else {
requestStoragePermission()
}
}
softAskView.visibility = View.VISIBLE
}
is SoftAskViewUiModel.Hidden -> {
if (softAskView.visibility == View.VISIBLE) {
AniUtils.fadeOut(softAskView, MEDIUM)
}
}
}
}
private fun MediaPickerFragmentBinding.setupPhotoList(uiModel: PhotoListUiModel) {
loadingView.visibility = if (uiModel == PhotoListUiModel.Loading) View.VISIBLE else View.GONE
actionableEmptyView.visibility = if (uiModel is PhotoListUiModel.Empty) View.VISIBLE else View.GONE
recycler.visibility = if (uiModel is PhotoListUiModel.Data) View.VISIBLE else View.INVISIBLE
when (uiModel) {
is PhotoListUiModel.Data -> {
setupAdapter(uiModel.items)
}
is PhotoListUiModel.Empty -> {
setupAdapter(listOf())
actionableEmptyView.updateLayoutForSearch(uiModel.isSearching, 0)
actionableEmptyView.title.text = uiHelpers.getTextOfUiString(requireContext(), uiModel.title)
actionableEmptyView.subtitle.applyOrHide(uiModel.htmlSubtitle) { htmlSubtitle ->
actionableEmptyView.subtitle.text = HtmlCompat.fromHtml(
uiHelpers.getTextOfUiString(
requireContext(),
htmlSubtitle
).toString(),
HtmlCompat.FROM_HTML_MODE_LEGACY
)
actionableEmptyView.subtitle.movementMethod = WPLinkMovementMethod.getInstance()
}
actionableEmptyView.image.applyOrHide(uiModel.image) { image ->
this.setImageResource(image)
}
actionableEmptyView.bottomImage.applyOrHide(uiModel.bottomImage) { bottomImage ->
this.setImageResource(bottomImage)
if (uiModel.bottomImageDescription != null) {
this.contentDescription = uiHelpers.getTextOfUiString(
requireContext(),
uiModel.bottomImageDescription
).toString()
}
}
actionableEmptyView.button.applyOrHide(uiModel.retryAction) { action ->
this.setOnClickListener {
action()
}
}
}
PhotoListUiModel.Hidden -> Unit // Do nothing
PhotoListUiModel.Loading -> Unit // Do nothing
}
}
private fun <T, U : View> U.applyOrHide(item: T?, action: U.(T) -> Unit) {
if (item != null) {
this.visibility = View.VISIBLE
this.action(item)
} else {
this.visibility = View.GONE
}
}
private fun MediaPickerFragmentBinding.setupAdapter(items: List<MediaPickerUiItem>) {
if (recycler.adapter == null) {
recycler.adapter = MediaPickerAdapter(
imageManager,
viewModel.viewModelScope
)
}
val adapter = recycler.adapter as MediaPickerAdapter
(recycler.layoutManager as? GridLayoutManager)?.spanSizeLookup =
object : SpanSizeLookup() {
override fun getSpanSize(position: Int) = if (items[position].fullWidthItem) {
NUM_COLUMNS
} else {
1
}
}
val recyclerViewState = recycler.layoutManager?.onSaveInstanceState()
adapter.loadData(items)
recycler.layoutManager?.onRestoreInstanceState(recyclerViewState)
}
private fun MediaPickerFragmentBinding.setupFab(fabUiModel: FabUiModel) {
if (fabUiModel.show) {
fabTakePicture.show()
fabTakePicture.setOnClickListener {
fabUiModel.action()
}
} else {
fabTakePicture.hide()
}
}
private fun setupProgressDialog() {
var progressDialog: AlertDialog? = null
viewModel.uiState.observe(viewLifecycleOwner, Observer {
it?.progressDialogUiModel?.apply {
when (this) {
is Visible -> {
if (progressDialog == null || progressDialog?.isShowing == false) {
val builder: Builder = MaterialAlertDialogBuilder(requireContext())
builder.setTitle(this.title)
builder.setView(R.layout.media_picker_progress_dialog)
builder.setNegativeButton(
R.string.cancel
) { _, _ -> this.cancelAction() }
builder.setOnCancelListener { this.cancelAction() }
builder.setCancelable(true)
progressDialog = builder.show()
}
}
ProgressDialogUiModel.Hidden -> {
progressDialog?.let { dialog ->
if (dialog.isShowing) {
dialog.dismiss()
}
}
}
}
}
})
}
private fun MediaPickerFragmentBinding.showSnackbar(holder: SnackbarMessageHolder) {
snackbarSequencer.enqueue(
SnackbarItem(
Info(
view = coordinator,
textRes = holder.message,
duration = Snackbar.LENGTH_LONG
),
holder.buttonTitle?.let {
Action(
textRes = holder.buttonTitle,
clickListener = View.OnClickListener { holder.buttonAction() }
)
},
dismissCallback = { _, event -> holder.onDismissAction(event) }
)
)
}
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
viewModel.lastTappedIcon?.toBundle(outState)
val selectedIds = viewModel.selectedIdentifiers()
if (selectedIds.isNotEmpty()) {
outState.putParcelableArrayList(KEY_SELECTED_IDS, ArrayList<Identifier>(selectedIds))
}
binding!!.recycler.layoutManager?.let {
outState.putParcelable(KEY_LIST_STATE, it.onSaveInstanceState())
}
}
override fun onResume() {
super.onResume()
checkStoragePermission()
}
fun setMediaPickerListener(listener: MediaPickerListener?) {
this.listener = listener
}
private val isStoragePermissionAlwaysDenied: Boolean
get() = WPPermissionUtils.isPermissionAlwaysDenied(
requireActivity(), permission.WRITE_EXTERNAL_STORAGE
)
/*
* load the photos if we have the necessary permission, otherwise show the "soft ask" view
* which asks the user to allow the permission
*/
private fun checkStoragePermission() {
if (!isAdded) {
return
}
viewModel.checkStoragePermission(isStoragePermissionAlwaysDenied)
}
@Suppress("DEPRECATION")
private fun requestStoragePermission() {
val permissions = arrayOf(permission.WRITE_EXTERNAL_STORAGE, permission.READ_EXTERNAL_STORAGE)
requestPermissions(
permissions, WPPermissionUtils.PHOTO_PICKER_STORAGE_PERMISSION_REQUEST_CODE
)
}
@Suppress("DEPRECATION")
private fun requestCameraPermission() {
// in addition to CAMERA permission we also need a storage permission, to store media from the camera
val permissions = arrayOf(
permission.CAMERA,
permission.WRITE_EXTERNAL_STORAGE
)
requestPermissions(permissions, WPPermissionUtils.PHOTO_PICKER_CAMERA_PERMISSION_REQUEST_CODE)
}
@Suppress("OVERRIDE_DEPRECATION")
override fun onRequestPermissionsResult(
requestCode: Int,
permissions: Array<String>,
grantResults: IntArray
) {
val checkForAlwaysDenied = requestCode == WPPermissionUtils.PHOTO_PICKER_CAMERA_PERMISSION_REQUEST_CODE
val allGranted = WPPermissionUtils.setPermissionListAsked(
requireActivity(), requestCode, permissions, grantResults, checkForAlwaysDenied
)
when (requestCode) {
WPPermissionUtils.PHOTO_PICKER_STORAGE_PERMISSION_REQUEST_CODE -> checkStoragePermission()
WPPermissionUtils.PHOTO_PICKER_CAMERA_PERMISSION_REQUEST_CODE -> if (allGranted) {
viewModel.clickOnLastTappedIcon()
}
}
}
companion object {
private const val KEY_LAST_TAPPED_ICON = "last_tapped_icon"
private const val KEY_LAST_TAPPED_ICON_ALLOWED_TYPES = "last_tapped_icon_allowed_types"
private const val KEY_LAST_TAPPED_ICON_DATA_SOURCE = "last_tapped_icon_data_source"
private const val KEY_SELECTED_IDS = "selected_ids"
private const val KEY_LIST_STATE = "list_state"
const val NUM_COLUMNS = 3
@JvmStatic fun newInstance(
listener: MediaPickerListener,
mediaPickerSetup: MediaPickerSetup,
site: SiteModel?
): MediaPickerFragment {
val args = Bundle()
mediaPickerSetup.toBundle(args)
if (site != null) {
args.putSerializable(WordPress.SITE, site)
}
val fragment = MediaPickerFragment()
fragment.setMediaPickerListener(listener)
fragment.arguments = args
return fragment
}
}
}
| gpl-2.0 | 1ec51d4d97560f718c457b8cf8b4aefa | 41.984127 | 114 | 0.622331 | 5.452682 | false | false | false | false |
wordpress-mobile/WordPress-Android | WordPress/src/main/java/org/wordpress/android/ui/plans/PlansListAdapter.kt | 1 | 3033 | package org.wordpress.android.ui.plans
import android.app.Activity
import android.text.TextUtils
import android.view.LayoutInflater
import android.view.ViewGroup
import android.view.accessibility.AccessibilityNodeInfo
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.RecyclerView.Adapter
import org.wordpress.android.R
import org.wordpress.android.WordPress
import org.wordpress.android.fluxc.model.plans.PlanOffersModel
import org.wordpress.android.ui.plans.PlansListAdapter.PlansItemViewHolder
import org.wordpress.android.util.StringUtils
import org.wordpress.android.util.image.ImageManager
import org.wordpress.android.util.image.ImageType
import javax.inject.Inject
class PlansListAdapter(
val activity: Activity,
private val itemClickListener: (PlanOffersModel) -> Unit
) : Adapter<PlansItemViewHolder>() {
private val list = mutableListOf<PlanOffersModel>()
@Inject lateinit var imageManager: ImageManager
init {
(activity.applicationContext as WordPress).component().inject(this)
}
override fun getItemCount(): Int {
return list.size
}
override fun onBindViewHolder(holder: PlansItemViewHolder, position: Int, payloads: List<Any>) {
onBindViewHolder(holder, position)
}
override fun onBindViewHolder(holder: PlansItemViewHolder, position: Int) {
holder.bind(list[position])
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): PlansItemViewHolder {
return PlansItemViewHolder(parent, itemClickListener, imageManager)
}
internal fun updateList(items: List<PlanOffersModel>) {
list.clear()
list.addAll(items)
notifyDataSetChanged()
}
class PlansItemViewHolder(
parent: ViewGroup,
private val itemClickListener: (PlanOffersModel) -> Unit,
val imageManager: ImageManager
) : RecyclerView.ViewHolder(
LayoutInflater.from(parent.context).inflate(R.layout.plans_list_item, parent, false)
) {
private val planImage: ImageView = itemView.findViewById(R.id.plan_image)
private val title: TextView = itemView.findViewById(R.id.plan_title)
private val subtitle: TextView = itemView.findViewById(R.id.plan_subtitle)
fun bind(planOffersModel: PlanOffersModel) {
itemView.setOnClickListener {
itemView.performAccessibilityAction(
AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS, null
)
itemClickListener(planOffersModel)
}
title.text = planOffersModel.name
subtitle.text = planOffersModel.tagline
if (!TextUtils.isEmpty(planOffersModel.iconUrl)) {
imageManager.loadIntoCircle(
planImage, ImageType.PLAN,
StringUtils.notNullStr(planOffersModel.iconUrl)
)
}
}
}
}
| gpl-2.0 | 0720ae1651c5c9285df54ef1befbbab8 | 35.542169 | 100 | 0.705902 | 4.829618 | false | false | false | false |
wordpress-mobile/WordPress-Android | WordPress/src/main/java/org/wordpress/android/ui/engagement/EngagedPeopleAdapterDiffCallback.kt | 1 | 1277 | package org.wordpress.android.ui.engagement
import androidx.recyclerview.widget.DiffUtil
import org.wordpress.android.ui.engagement.EngageItem.LikedItem
import org.wordpress.android.ui.engagement.EngageItem.Liker
import org.wordpress.android.ui.engagement.EngageItem.NextLikesPageLoader
class EngagedPeopleAdapterDiffCallback(
private val oldItems: List<EngageItem>,
private val newItems: List<EngageItem>
) : DiffUtil.Callback() {
override fun getOldListSize(): Int {
return oldItems.size
}
override fun getNewListSize(): Int {
return newItems.size
}
override fun areItemsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean {
val oldItem = oldItems[oldItemPosition]
val newItem = newItems[newItemPosition]
return when {
oldItem is LikedItem && newItem is LikedItem -> oldItem.author == newItem.author
oldItem is Liker && newItem is Liker -> oldItem.userId == newItem.userId
oldItem is NextLikesPageLoader && newItem is NextLikesPageLoader -> true
else -> false
}
}
override fun areContentsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean {
return oldItems[oldItemPosition] == newItems[newItemPosition]
}
}
| gpl-2.0 | 6c121f734dca7a9f4c601b30b2bd4c0e | 36.558824 | 92 | 0.716523 | 4.89272 | false | false | false | false |
ingokegel/intellij-community | platform/workspaceModel/storage/testEntities/gen/com/intellij/workspaceModel/storage/entities/test/api/SampleWithPersistentIdEntityImpl.kt | 1 | 15634 | 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.ModifiableWorkspaceEntity
import com.intellij.workspaceModel.storage.MutableEntityStorage
import com.intellij.workspaceModel.storage.PersistentEntityId
import com.intellij.workspaceModel.storage.WorkspaceEntity
import com.intellij.workspaceModel.storage.impl.ConnectionId
import com.intellij.workspaceModel.storage.impl.EntityLink
import com.intellij.workspaceModel.storage.impl.ModifiableWorkspaceEntityBase
import com.intellij.workspaceModel.storage.impl.UsedClassesCollector
import com.intellij.workspaceModel.storage.impl.WorkspaceEntityBase
import com.intellij.workspaceModel.storage.impl.WorkspaceEntityData
import com.intellij.workspaceModel.storage.impl.containers.MutableWorkspaceList
import com.intellij.workspaceModel.storage.impl.containers.toMutableWorkspaceList
import com.intellij.workspaceModel.storage.impl.extractOneToManyChildren
import com.intellij.workspaceModel.storage.impl.updateOneToManyChildrenOfParent
import com.intellij.workspaceModel.storage.url.VirtualFileUrl
import java.util.*
import org.jetbrains.deft.ObjBuilder
import org.jetbrains.deft.Type
import org.jetbrains.deft.annotations.Child
@GeneratedCodeApiVersion(1)
@GeneratedCodeImplVersion(1)
open class SampleWithPersistentIdEntityImpl : SampleWithPersistentIdEntity, WorkspaceEntityBase() {
companion object {
internal val CHILDREN_CONNECTION_ID: ConnectionId = ConnectionId.create(SampleWithPersistentIdEntity::class.java,
ChildWpidSampleEntity::class.java,
ConnectionId.ConnectionType.ONE_TO_MANY, true)
val connections = listOf<ConnectionId>(
CHILDREN_CONNECTION_ID,
)
}
override var booleanProperty: Boolean = false
@JvmField
var _stringProperty: String? = null
override val stringProperty: String
get() = _stringProperty!!
@JvmField
var _stringListProperty: List<String>? = null
override val stringListProperty: List<String>
get() = _stringListProperty!!
@JvmField
var _stringMapProperty: Map<String, String>? = null
override val stringMapProperty: Map<String, String>
get() = _stringMapProperty!!
@JvmField
var _fileProperty: VirtualFileUrl? = null
override val fileProperty: VirtualFileUrl
get() = _fileProperty!!
override val children: List<ChildWpidSampleEntity>
get() = snapshot.extractOneToManyChildren<ChildWpidSampleEntity>(CHILDREN_CONNECTION_ID, this)!!.toList()
@JvmField
var _nullableData: String? = null
override val nullableData: String?
get() = _nullableData
override fun connectionIdList(): List<ConnectionId> {
return connections
}
class Builder(val result: SampleWithPersistentIdEntityData?) : ModifiableWorkspaceEntityBase<SampleWithPersistentIdEntity>(), SampleWithPersistentIdEntity.Builder {
constructor() : this(SampleWithPersistentIdEntityData())
override fun applyToBuilder(builder: MutableEntityStorage) {
if (this.diff != null) {
if (existsInBuilder(builder)) {
this.diff = builder
return
}
else {
error("Entity SampleWithPersistentIdEntity is already created in a different builder")
}
}
this.diff = builder
this.snapshot = builder
addToBuilder()
this.id = getEntityData().createEntityId()
index(this, "fileProperty", this.fileProperty)
// 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().isStringPropertyInitialized()) {
error("Field SampleWithPersistentIdEntity#stringProperty should be initialized")
}
if (!getEntityData().isStringListPropertyInitialized()) {
error("Field SampleWithPersistentIdEntity#stringListProperty should be initialized")
}
if (!getEntityData().isStringMapPropertyInitialized()) {
error("Field SampleWithPersistentIdEntity#stringMapProperty should be initialized")
}
if (!getEntityData().isFilePropertyInitialized()) {
error("Field SampleWithPersistentIdEntity#fileProperty should be initialized")
}
// Check initialization for list with ref type
if (_diff != null) {
if (_diff.extractOneToManyChildren<WorkspaceEntityBase>(CHILDREN_CONNECTION_ID, this) == null) {
error("Field SampleWithPersistentIdEntity#children should be initialized")
}
}
else {
if (this.entityLinks[EntityLink(true, CHILDREN_CONNECTION_ID)] == null) {
error("Field SampleWithPersistentIdEntity#children 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 SampleWithPersistentIdEntity
this.entitySource = dataSource.entitySource
this.booleanProperty = dataSource.booleanProperty
this.stringProperty = dataSource.stringProperty
this.stringListProperty = dataSource.stringListProperty.toMutableList()
this.stringMapProperty = dataSource.stringMapProperty.toMutableMap()
this.fileProperty = dataSource.fileProperty
this.nullableData = dataSource.nullableData
if (parents != null) {
}
}
override var entitySource: EntitySource
get() = getEntityData().entitySource
set(value) {
checkModificationAllowed()
getEntityData().entitySource = value
changedProperty.add("entitySource")
}
override var booleanProperty: Boolean
get() = getEntityData().booleanProperty
set(value) {
checkModificationAllowed()
getEntityData().booleanProperty = value
changedProperty.add("booleanProperty")
}
override var stringProperty: String
get() = getEntityData().stringProperty
set(value) {
checkModificationAllowed()
getEntityData().stringProperty = value
changedProperty.add("stringProperty")
}
private val stringListPropertyUpdater: (value: List<String>) -> Unit = { value ->
changedProperty.add("stringListProperty")
}
override var stringListProperty: MutableList<String>
get() {
val collection_stringListProperty = getEntityData().stringListProperty
if (collection_stringListProperty !is MutableWorkspaceList) return collection_stringListProperty
collection_stringListProperty.setModificationUpdateAction(stringListPropertyUpdater)
return collection_stringListProperty
}
set(value) {
checkModificationAllowed()
getEntityData().stringListProperty = value
stringListPropertyUpdater.invoke(value)
}
override var stringMapProperty: Map<String, String>
get() = getEntityData().stringMapProperty
set(value) {
checkModificationAllowed()
getEntityData().stringMapProperty = value
changedProperty.add("stringMapProperty")
}
override var fileProperty: VirtualFileUrl
get() = getEntityData().fileProperty
set(value) {
checkModificationAllowed()
getEntityData().fileProperty = value
changedProperty.add("fileProperty")
val _diff = diff
if (_diff != null) index(this, "fileProperty", value)
}
// List of non-abstract referenced types
var _children: List<ChildWpidSampleEntity>? = emptyList()
override var children: List<ChildWpidSampleEntity>
get() {
// Getter of the list of non-abstract referenced types
val _diff = diff
return if (_diff != null) {
_diff.extractOneToManyChildren<ChildWpidSampleEntity>(CHILDREN_CONNECTION_ID, this)!!.toList() + (this.entityLinks[EntityLink(
true, CHILDREN_CONNECTION_ID)] as? List<ChildWpidSampleEntity> ?: emptyList())
}
else {
this.entityLinks[EntityLink(true, CHILDREN_CONNECTION_ID)] as? List<ChildWpidSampleEntity> ?: emptyList()
}
}
set(value) {
// Setter of the list of non-abstract referenced types
checkModificationAllowed()
val _diff = diff
if (_diff != null) {
for (item_value in value) {
if (item_value is ModifiableWorkspaceEntityBase<*> && (item_value as? ModifiableWorkspaceEntityBase<*>)?.diff == null) {
_diff.addEntity(item_value)
}
}
_diff.updateOneToManyChildrenOfParent(CHILDREN_CONNECTION_ID, this, value)
}
else {
for (item_value in value) {
if (item_value is ModifiableWorkspaceEntityBase<*>) {
item_value.entityLinks[EntityLink(false, CHILDREN_CONNECTION_ID)] = this
}
// else you're attaching a new entity to an existing entity that is not modifiable
}
this.entityLinks[EntityLink(true, CHILDREN_CONNECTION_ID)] = value
}
changedProperty.add("children")
}
override var nullableData: String?
get() = getEntityData().nullableData
set(value) {
checkModificationAllowed()
getEntityData().nullableData = value
changedProperty.add("nullableData")
}
override fun getEntityData(): SampleWithPersistentIdEntityData = result ?: super.getEntityData() as SampleWithPersistentIdEntityData
override fun getEntityClass(): Class<SampleWithPersistentIdEntity> = SampleWithPersistentIdEntity::class.java
}
}
class SampleWithPersistentIdEntityData : WorkspaceEntityData.WithCalculablePersistentId<SampleWithPersistentIdEntity>() {
var booleanProperty: Boolean = false
lateinit var stringProperty: String
lateinit var stringListProperty: MutableList<String>
lateinit var stringMapProperty: Map<String, String>
lateinit var fileProperty: VirtualFileUrl
var nullableData: String? = null
fun isStringPropertyInitialized(): Boolean = ::stringProperty.isInitialized
fun isStringListPropertyInitialized(): Boolean = ::stringListProperty.isInitialized
fun isStringMapPropertyInitialized(): Boolean = ::stringMapProperty.isInitialized
fun isFilePropertyInitialized(): Boolean = ::fileProperty.isInitialized
override fun wrapAsModifiable(diff: MutableEntityStorage): ModifiableWorkspaceEntity<SampleWithPersistentIdEntity> {
val modifiable = SampleWithPersistentIdEntityImpl.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): SampleWithPersistentIdEntity {
val entity = SampleWithPersistentIdEntityImpl()
entity.booleanProperty = booleanProperty
entity._stringProperty = stringProperty
entity._stringListProperty = stringListProperty.toList()
entity._stringMapProperty = stringMapProperty
entity._fileProperty = fileProperty
entity._nullableData = nullableData
entity.entitySource = entitySource
entity.snapshot = snapshot
entity.id = createEntityId()
return entity
}
override fun clone(): SampleWithPersistentIdEntityData {
val clonedEntity = super.clone()
clonedEntity as SampleWithPersistentIdEntityData
clonedEntity.stringListProperty = clonedEntity.stringListProperty.toMutableWorkspaceList()
return clonedEntity
}
override fun persistentId(): PersistentEntityId<*> {
return SamplePersistentId(stringProperty)
}
override fun getEntityInterface(): Class<out WorkspaceEntity> {
return SampleWithPersistentIdEntity::class.java
}
override fun serialize(ser: EntityInformation.Serializer) {
}
override fun deserialize(de: EntityInformation.Deserializer) {
}
override fun createDetachedEntity(parents: List<WorkspaceEntity>): WorkspaceEntity {
return SampleWithPersistentIdEntity(booleanProperty, stringProperty, stringListProperty, stringMapProperty, fileProperty,
entitySource) {
this.nullableData = [email protected]
}
}
override fun getRequiredParents(): List<Class<out WorkspaceEntity>> {
val res = mutableListOf<Class<out WorkspaceEntity>>()
return res
}
override fun equals(other: Any?): Boolean {
if (other == null) return false
if (this::class != other::class) return false
other as SampleWithPersistentIdEntityData
if (this.entitySource != other.entitySource) return false
if (this.booleanProperty != other.booleanProperty) return false
if (this.stringProperty != other.stringProperty) return false
if (this.stringListProperty != other.stringListProperty) return false
if (this.stringMapProperty != other.stringMapProperty) return false
if (this.fileProperty != other.fileProperty) return false
if (this.nullableData != other.nullableData) return false
return true
}
override fun equalsIgnoringEntitySource(other: Any?): Boolean {
if (other == null) return false
if (this::class != other::class) return false
other as SampleWithPersistentIdEntityData
if (this.booleanProperty != other.booleanProperty) return false
if (this.stringProperty != other.stringProperty) return false
if (this.stringListProperty != other.stringListProperty) return false
if (this.stringMapProperty != other.stringMapProperty) return false
if (this.fileProperty != other.fileProperty) return false
if (this.nullableData != other.nullableData) return false
return true
}
override fun hashCode(): Int {
var result = entitySource.hashCode()
result = 31 * result + booleanProperty.hashCode()
result = 31 * result + stringProperty.hashCode()
result = 31 * result + stringListProperty.hashCode()
result = 31 * result + stringMapProperty.hashCode()
result = 31 * result + fileProperty.hashCode()
result = 31 * result + nullableData.hashCode()
return result
}
override fun hashCodeIgnoringEntitySource(): Int {
var result = javaClass.hashCode()
result = 31 * result + booleanProperty.hashCode()
result = 31 * result + stringProperty.hashCode()
result = 31 * result + stringListProperty.hashCode()
result = 31 * result + stringMapProperty.hashCode()
result = 31 * result + fileProperty.hashCode()
result = 31 * result + nullableData.hashCode()
return result
}
override fun collectClassUsagesData(collector: UsedClassesCollector) {
this.stringMapProperty?.let { collector.add(it::class.java) }
this.stringListProperty?.let { collector.add(it::class.java) }
this.fileProperty?.let { collector.add(it::class.java) }
collector.sameForAllEntities = false
}
}
| apache-2.0 | 2f5e7617d74c9575e242d73c6a4d2f39 | 38.680203 | 166 | 0.720865 | 5.506869 | false | false | false | false |
DanielGrech/anko | dsl/testData/functional/15s/PropertyTest.kt | 3 | 51034 | public var android.support.v4.view.PagerTitleStrip.textSpacing: Int
get() = getTextSpacing()
set(v) = setTextSpacing(v)
public var android.support.v4.view.ViewPager.adapter: android.support.v4.view.PagerAdapter?
get() = getAdapter()
set(v) = setAdapter(v)
public var android.support.v4.view.ViewPager.currentItem: Int
get() = getCurrentItem()
set(v) = setCurrentItem(v)
public var android.support.v4.view.ViewPager.offscreenPageLimit: Int
get() = getOffscreenPageLimit()
set(v) = setOffscreenPageLimit(v)
public var android.support.v4.view.ViewPager.pageMargin: Int
get() = getPageMargin()
set(v) = setPageMargin(v)
public val android.support.v4.view.ViewPager.fakeDragging: Boolean
get() = isFakeDragging()
public val android.support.v4.widget.DrawerLayout.statusBarBackgroundDrawable: android.graphics.drawable.Drawable?
get() = getStatusBarBackgroundDrawable()
public val android.support.v4.widget.NestedScrollView.maxScrollAmount: Int
get() = getMaxScrollAmount()
public val android.support.v4.widget.NestedScrollView.nestedScrollAxes: Int
get() = getNestedScrollAxes()
public var android.support.v4.widget.NestedScrollView.fillViewport: Boolean
get() = isFillViewport()
set(v) = setFillViewport(v)
public var android.support.v4.widget.NestedScrollView.nestedScrollingEnabled: Boolean
get() = isNestedScrollingEnabled()
set(v) = setNestedScrollingEnabled(v)
public var android.support.v4.widget.NestedScrollView.smoothScrollingEnabled: Boolean
get() = isSmoothScrollingEnabled()
set(v) = setSmoothScrollingEnabled(v)
public var android.support.v4.widget.SlidingPaneLayout.coveredFadeColor: Int
get() = getCoveredFadeColor()
set(v) = setCoveredFadeColor(v)
public var android.support.v4.widget.SlidingPaneLayout.parallaxDistance: Int
get() = getParallaxDistance()
set(v) = setParallaxDistance(v)
public var android.support.v4.widget.SlidingPaneLayout.sliderFadeColor: Int
get() = getSliderFadeColor()
set(v) = setSliderFadeColor(v)
public val android.support.v4.widget.SlidingPaneLayout.open: Boolean
get() = isOpen()
public val android.support.v4.widget.SlidingPaneLayout.slideable: Boolean
get() = isSlideable()
public val android.support.v4.widget.SwipeRefreshLayout.progressCircleDiameter: Int
get() = getProgressCircleDiameter()
public var android.support.v4.widget.SwipeRefreshLayout.refreshing: Boolean
get() = isRefreshing()
set(v) = setRefreshing(v)
public val android.support.v7.widget.ActionMenuView.menu: android.view.Menu?
get() = getMenu()
public var android.support.v7.widget.ActionMenuView.popupTheme: Int
get() = getPopupTheme()
set(v) = setPopupTheme(v)
public val android.support.v7.widget.ActionMenuView.windowAnimations: Int
get() = getWindowAnimations()
public val android.support.v7.widget.ActionMenuView.overflowMenuShowPending: Boolean
get() = isOverflowMenuShowPending()
public val android.support.v7.widget.ActionMenuView.overflowMenuShowing: Boolean
get() = isOverflowMenuShowing()
public var android.support.v7.widget.ActionMenuView.overflowReserved: Boolean
get() = isOverflowReserved()
set(v) = setOverflowReserved(v)
public val android.support.v7.widget.LinearLayoutCompat.baseline: Int
get() = getBaseline()
public var android.support.v7.widget.LinearLayoutCompat.baselineAlignedChildIndex: Int
get() = getBaselineAlignedChildIndex()
set(v) = setBaselineAlignedChildIndex(v)
public var android.support.v7.widget.LinearLayoutCompat.dividerDrawable: android.graphics.drawable.Drawable?
get() = getDividerDrawable()
set(v) = setDividerDrawable(v)
public var android.support.v7.widget.LinearLayoutCompat.dividerPadding: Int
get() = getDividerPadding()
set(v) = setDividerPadding(v)
public val android.support.v7.widget.LinearLayoutCompat.dividerWidth: Int
get() = getDividerWidth()
public var android.support.v7.widget.LinearLayoutCompat.orientation: Int
get() = getOrientation()
set(v) = setOrientation(v)
public var android.support.v7.widget.LinearLayoutCompat.showDividers: Int
get() = getShowDividers()
set(v) = setShowDividers(v)
public var android.support.v7.widget.LinearLayoutCompat.weightSum: Float
get() = getWeightSum()
set(v) = setWeightSum(v)
public var android.support.v7.widget.LinearLayoutCompat.baselineAligned: Boolean
get() = isBaselineAligned()
set(v) = setBaselineAligned(v)
public var android.support.v7.widget.LinearLayoutCompat.measureWithLargestChildEnabled: Boolean
get() = isMeasureWithLargestChildEnabled()
set(v) = setMeasureWithLargestChildEnabled(v)
public var android.support.v7.widget.SearchView.imeOptions: Int
get() = getImeOptions()
set(v) = setImeOptions(v)
public var android.support.v7.widget.SearchView.inputType: Int
get() = getInputType()
set(v) = setInputType(v)
public var android.support.v7.widget.SearchView.maxWidth: Int
get() = getMaxWidth()
set(v) = setMaxWidth(v)
public val android.support.v7.widget.SearchView.query: CharSequence?
get() = getQuery()
public var android.support.v7.widget.SearchView.queryHint: CharSequence?
get() = getQueryHint()
set(v) = setQueryHint(v)
public var android.support.v7.widget.SearchView.suggestionsAdapter: android.support.v4.widget.CursorAdapter?
get() = getSuggestionsAdapter()
set(v) = setSuggestionsAdapter(v)
public val android.support.v7.widget.SearchView.iconfiedByDefault: Boolean
get() = isIconfiedByDefault()
public var android.support.v7.widget.SearchView.iconified: Boolean
get() = isIconified()
set(v) = setIconified(v)
public var android.support.v7.widget.SearchView.queryRefinementEnabled: Boolean
get() = isQueryRefinementEnabled()
set(v) = setQueryRefinementEnabled(v)
public var android.support.v7.widget.SearchView.submitButtonEnabled: Boolean
get() = isSubmitButtonEnabled()
set(v) = setSubmitButtonEnabled(v)
public val android.support.v7.widget.SwitchCompat.compoundPaddingLeft: Int
get() = getCompoundPaddingLeft()
public val android.support.v7.widget.SwitchCompat.compoundPaddingRight: Int
get() = getCompoundPaddingRight()
public var android.support.v7.widget.SwitchCompat.showText: Boolean
get() = getShowText()
set(v) = setShowText(v)
public var android.support.v7.widget.SwitchCompat.splitTrack: Boolean
get() = getSplitTrack()
set(v) = setSplitTrack(v)
public var android.support.v7.widget.SwitchCompat.switchMinWidth: Int
get() = getSwitchMinWidth()
set(v) = setSwitchMinWidth(v)
public var android.support.v7.widget.SwitchCompat.switchPadding: Int
get() = getSwitchPadding()
set(v) = setSwitchPadding(v)
public var android.support.v7.widget.SwitchCompat.textOff: CharSequence?
get() = getTextOff()
set(v) = setTextOff(v)
public var android.support.v7.widget.SwitchCompat.textOn: CharSequence?
get() = getTextOn()
set(v) = setTextOn(v)
public var android.support.v7.widget.SwitchCompat.thumbDrawable: android.graphics.drawable.Drawable?
get() = getThumbDrawable()
set(v) = setThumbDrawable(v)
public var android.support.v7.widget.SwitchCompat.thumbTextPadding: Int
get() = getThumbTextPadding()
set(v) = setThumbTextPadding(v)
public var android.support.v7.widget.SwitchCompat.trackDrawable: android.graphics.drawable.Drawable?
get() = getTrackDrawable()
set(v) = setTrackDrawable(v)
public val android.support.v7.widget.Toolbar.contentInsetEnd: Int
get() = getContentInsetEnd()
public val android.support.v7.widget.Toolbar.contentInsetLeft: Int
get() = getContentInsetLeft()
public val android.support.v7.widget.Toolbar.contentInsetRight: Int
get() = getContentInsetRight()
public val android.support.v7.widget.Toolbar.contentInsetStart: Int
get() = getContentInsetStart()
public var android.support.v7.widget.Toolbar.logo: android.graphics.drawable.Drawable?
get() = getLogo()
set(v) = setLogo(v)
public var android.support.v7.widget.Toolbar.logoResource: Int
get() = throw AnkoException("'android.support.v7.widget.Toolbar.logoResource' property does not have a getter")
set(v) = setLogo(v)
public var android.support.v7.widget.Toolbar.logoDescription: CharSequence?
get() = getLogoDescription()
set(v) = setLogoDescription(v)
public var android.support.v7.widget.Toolbar.logoDescriptionResource: Int
get() = throw AnkoException("'android.support.v7.widget.Toolbar.logoDescriptionResource' property does not have a getter")
set(v) = setLogoDescription(v)
public val android.support.v7.widget.Toolbar.menu: android.view.Menu?
get() = getMenu()
public var android.support.v7.widget.Toolbar.navigationContentDescription: CharSequence?
get() = getNavigationContentDescription()
set(v) = setNavigationContentDescription(v)
public var android.support.v7.widget.Toolbar.navigationContentDescriptionResource: Int
get() = throw AnkoException("'android.support.v7.widget.Toolbar.navigationContentDescriptionResource' property does not have a getter")
set(v) = setNavigationContentDescription(v)
public var android.support.v7.widget.Toolbar.navigationIcon: android.graphics.drawable.Drawable?
get() = getNavigationIcon()
set(v) = setNavigationIcon(v)
public var android.support.v7.widget.Toolbar.navigationIconResource: Int
get() = throw AnkoException("'android.support.v7.widget.Toolbar.navigationIconResource' property does not have a getter")
set(v) = setNavigationIcon(v)
public var android.support.v7.widget.Toolbar.popupTheme: Int
get() = getPopupTheme()
set(v) = setPopupTheme(v)
public var android.support.v7.widget.Toolbar.subtitle: CharSequence?
get() = getSubtitle()
set(v) = setSubtitle(v)
public var android.support.v7.widget.Toolbar.subtitleResource: Int
get() = throw AnkoException("'android.support.v7.widget.Toolbar.subtitleResource' property does not have a getter")
set(v) = setSubtitle(v)
public var android.support.v7.widget.Toolbar.title: CharSequence?
get() = getTitle()
set(v) = setTitle(v)
public var android.support.v7.widget.Toolbar.titleResource: Int
get() = throw AnkoException("'android.support.v7.widget.Toolbar.titleResource' property does not have a getter")
set(v) = setTitle(v)
public val android.support.v7.widget.Toolbar.wrapper: android.support.v7.internal.widget.DecorToolbar?
get() = getWrapper()
public val android.support.v7.widget.Toolbar.overflowMenuShowPending: Boolean
get() = isOverflowMenuShowPending()
public val android.support.v7.widget.Toolbar.overflowMenuShowing: Boolean
get() = isOverflowMenuShowing()
public val android.support.v7.widget.Toolbar.titleTruncated: Boolean
get() = isTitleTruncated()
public val android.view.SurfaceView.holder: android.view.SurfaceHolder?
get() = getHolder()
public val android.view.TextureView.bitmap: android.graphics.Bitmap?
get() = getBitmap()
public val android.view.TextureView.layerType: Int
get() = getLayerType()
public val android.view.TextureView.surfaceTexture: android.graphics.SurfaceTexture?
get() = getSurfaceTexture()
public val android.view.TextureView.available: Boolean
get() = isAvailable()
public var android.view.TextureView.opaque: Boolean
get() = isOpaque()
set(v) = setOpaque(v)
public var android.view.View.alpha: Float
get() = getAlpha()
set(v) = setAlpha(v)
public var android.view.View.animation: android.view.animation.Animation?
get() = getAnimation()
set(v) = setAnimation(v)
public val android.view.View.baseline: Int
get() = getBaseline()
public var android.view.View.bottom: Int
get() = getBottom()
set(v) = setBottom(v)
public var android.view.View.contentDescription: CharSequence?
get() = getContentDescription()
set(v) = setContentDescription(v)
public val android.view.View.drawableState: IntArray
get() = getDrawableState()
public val android.view.View.drawingCache: android.graphics.Bitmap?
get() = getDrawingCache()
public var android.view.View.drawingCacheBackgroundColor: Int
get() = getDrawingCacheBackgroundColor()
set(v) = setDrawingCacheBackgroundColor(v)
public var android.view.View.drawingCacheQuality: Int
get() = getDrawingCacheQuality()
set(v) = setDrawingCacheQuality(v)
public val android.view.View.drawingTime: Long
get() = getDrawingTime()
public var android.view.View.filterTouchesWhenObscured: Boolean
get() = getFilterTouchesWhenObscured()
set(v) = setFilterTouchesWhenObscured(v)
public val android.view.View.height: Int
get() = getHeight()
public val android.view.View.horizontalFadingEdgeLength: Int
get() = getHorizontalFadingEdgeLength()
public var android.view.View.id: Int
get() = getId()
set(v) = setId(v)
public var android.view.View.keepScreenOn: Boolean
get() = getKeepScreenOn()
set(v) = setKeepScreenOn(v)
public val android.view.View.layerType: Int
get() = getLayerType()
public var android.view.View.layoutParams: android.view.ViewGroup.LayoutParams?
get() = getLayoutParams()
set(v) = setLayoutParams(v)
public var android.view.View.left: Int
get() = getLeft()
set(v) = setLeft(v)
public val android.view.View.matrix: android.graphics.Matrix?
get() = getMatrix()
public val android.view.View.measuredHeight: Int
get() = getMeasuredHeight()
public val android.view.View.measuredHeightAndState: Int
get() = getMeasuredHeightAndState()
public val android.view.View.measuredState: Int
get() = getMeasuredState()
public val android.view.View.measuredWidth: Int
get() = getMeasuredWidth()
public val android.view.View.measuredWidthAndState: Int
get() = getMeasuredWidthAndState()
public var android.view.View.overScrollMode: Int
get() = getOverScrollMode()
set(v) = setOverScrollMode(v)
public val android.view.View.parent: android.view.ViewParent?
get() = getParent()
public var android.view.View.pivotX: Float
get() = getPivotX()
set(v) = setPivotX(v)
public var android.view.View.pivotY: Float
get() = getPivotY()
set(v) = setPivotY(v)
public val android.view.View.resources: android.content.res.Resources?
get() = getResources()
public var android.view.View.right: Int
get() = getRight()
set(v) = setRight(v)
public val android.view.View.rootView: android.view.View?
get() = getRootView()
public var android.view.View.rotation: Float
get() = getRotation()
set(v) = setRotation(v)
public var android.view.View.rotationX: Float
get() = getRotationX()
set(v) = setRotationX(v)
public var android.view.View.rotationY: Float
get() = getRotationY()
set(v) = setRotationY(v)
public var android.view.View.scaleX: Float
get() = getScaleX()
set(v) = setScaleX(v)
public var android.view.View.scaleY: Float
get() = getScaleY()
set(v) = setScaleY(v)
public var android.view.View.scrollBarStyle: Int
get() = getScrollBarStyle()
set(v) = setScrollBarStyle(v)
public var android.view.View.scrollX: Int
get() = getScrollX()
set(v) = setScrollX(v)
public var android.view.View.scrollY: Int
get() = getScrollY()
set(v) = setScrollY(v)
public val android.view.View.solidColor: Int
get() = getSolidColor()
public var android.view.View.systemUiVisibility: Int
get() = getSystemUiVisibility()
set(v) = setSystemUiVisibility(v)
public var android.view.View.tag: Any?
get() = getTag()
set(v) = setTag(v)
public var android.view.View.top: Int
get() = getTop()
set(v) = setTop(v)
public var android.view.View.touchDelegate: android.view.TouchDelegate?
get() = getTouchDelegate()
set(v) = setTouchDelegate(v)
public var android.view.View.translationX: Float
get() = getTranslationX()
set(v) = setTranslationX(v)
public var android.view.View.translationY: Float
get() = getTranslationY()
set(v) = setTranslationY(v)
public val android.view.View.verticalFadingEdgeLength: Int
get() = getVerticalFadingEdgeLength()
public var android.view.View.verticalScrollbarPosition: Int
get() = getVerticalScrollbarPosition()
set(v) = setVerticalScrollbarPosition(v)
public val android.view.View.verticalScrollbarWidth: Int
get() = getVerticalScrollbarWidth()
public val android.view.View.viewTreeObserver: android.view.ViewTreeObserver?
get() = getViewTreeObserver()
public var android.view.View.visibility: Int
get() = getVisibility()
set(v) = setVisibility(v)
public val android.view.View.width: Int
get() = getWidth()
public val android.view.View.windowToken: android.os.IBinder?
get() = getWindowToken()
public val android.view.View.windowVisibility: Int
get() = getWindowVisibility()
public var android.view.View.x: Float
get() = getX()
set(v) = setX(v)
public var android.view.View.y: Float
get() = getY()
set(v) = setY(v)
public var android.view.View.activated: Boolean
get() = isActivated()
set(v) = setActivated(v)
public var android.view.View.clickable: Boolean
get() = isClickable()
set(v) = setClickable(v)
public val android.view.View.dirty: Boolean
get() = isDirty()
public var android.view.View.drawingCacheEnabled: Boolean
get() = isDrawingCacheEnabled()
set(v) = setDrawingCacheEnabled(v)
public var android.view.View.duplicateParentStateEnabled: Boolean
get() = isDuplicateParentStateEnabled()
set(v) = setDuplicateParentStateEnabled(v)
public var android.view.View.enabled: Boolean
get() = isEnabled()
set(v) = setEnabled(v)
public var android.view.View.focusable: Boolean
get() = isFocusable()
set(v) = setFocusable(v)
public var android.view.View.focusableInTouchMode: Boolean
get() = isFocusableInTouchMode()
set(v) = setFocusableInTouchMode(v)
public val android.view.View.focused: Boolean
get() = isFocused()
public var android.view.View.hapticFeedbackEnabled: Boolean
get() = isHapticFeedbackEnabled()
set(v) = setHapticFeedbackEnabled(v)
public val android.view.View.hardwareAccelerated: Boolean
get() = isHardwareAccelerated()
public var android.view.View.horizontalFadingEdgeEnabled: Boolean
get() = isHorizontalFadingEdgeEnabled()
set(v) = setHorizontalFadingEdgeEnabled(v)
public var android.view.View.horizontalScrollBarEnabled: Boolean
get() = isHorizontalScrollBarEnabled()
set(v) = setHorizontalScrollBarEnabled(v)
public var android.view.View.hovered: Boolean
get() = isHovered()
set(v) = setHovered(v)
public val android.view.View.inEditMode: Boolean
get() = isInEditMode()
public val android.view.View.inTouchMode: Boolean
get() = isInTouchMode()
public val android.view.View.layoutRequested: Boolean
get() = isLayoutRequested()
public var android.view.View.longClickable: Boolean
get() = isLongClickable()
set(v) = setLongClickable(v)
public val android.view.View.opaque: Boolean
get() = isOpaque()
public var android.view.View.pressed: Boolean
get() = isPressed()
set(v) = setPressed(v)
public var android.view.View.saveEnabled: Boolean
get() = isSaveEnabled()
set(v) = setSaveEnabled(v)
public var android.view.View.saveFromParentEnabled: Boolean
get() = isSaveFromParentEnabled()
set(v) = setSaveFromParentEnabled(v)
public var android.view.View.scrollbarFadingEnabled: Boolean
get() = isScrollbarFadingEnabled()
set(v) = setScrollbarFadingEnabled(v)
public var android.view.View.selected: Boolean
get() = isSelected()
set(v) = setSelected(v)
public val android.view.View.shown: Boolean
get() = isShown()
public var android.view.View.soundEffectsEnabled: Boolean
get() = isSoundEffectsEnabled()
set(v) = setSoundEffectsEnabled(v)
public var android.view.View.verticalFadingEdgeEnabled: Boolean
get() = isVerticalFadingEdgeEnabled()
set(v) = setVerticalFadingEdgeEnabled(v)
public var android.view.View.verticalScrollBarEnabled: Boolean
get() = isVerticalScrollBarEnabled()
set(v) = setVerticalScrollBarEnabled(v)
public var android.view.ViewGroup.descendantFocusability: Int
get() = getDescendantFocusability()
set(v) = setDescendantFocusability(v)
public var android.view.ViewGroup.layoutAnimation: android.view.animation.LayoutAnimationController?
get() = getLayoutAnimation()
set(v) = setLayoutAnimation(v)
public var android.view.ViewGroup.layoutTransition: android.animation.LayoutTransition?
get() = getLayoutTransition()
set(v) = setLayoutTransition(v)
public var android.view.ViewGroup.persistentDrawingCache: Int
get() = getPersistentDrawingCache()
set(v) = setPersistentDrawingCache(v)
public var android.view.ViewGroup.alwaysDrawnWithCacheEnabled: Boolean
get() = isAlwaysDrawnWithCacheEnabled()
set(v) = setAlwaysDrawnWithCacheEnabled(v)
public var android.view.ViewGroup.animationCacheEnabled: Boolean
get() = isAnimationCacheEnabled()
set(v) = setAnimationCacheEnabled(v)
public var android.view.ViewGroup.motionEventSplittingEnabled: Boolean
get() = isMotionEventSplittingEnabled()
set(v) = setMotionEventSplittingEnabled(v)
public var android.view.ViewStub.inflatedId: Int
get() = getInflatedId()
set(v) = setInflatedId(v)
public var android.view.ViewStub.layoutResource: Int
get() = getLayoutResource()
set(v) = setLayoutResource(v)
public val android.webkit.WebView.contentHeight: Int
get() = getContentHeight()
public val android.webkit.WebView.favicon: android.graphics.Bitmap?
get() = getFavicon()
public val android.webkit.WebView.hitTestResult: android.webkit.WebView.HitTestResult?
get() = getHitTestResult()
public val android.webkit.WebView.originalUrl: String?
get() = getOriginalUrl()
public val android.webkit.WebView.progress: Int
get() = getProgress()
public val android.webkit.WebView.scale: Float
get() = getScale()
public val android.webkit.WebView.settings: android.webkit.WebSettings?
get() = getSettings()
public val android.webkit.WebView.title: String?
get() = getTitle()
public val android.webkit.WebView.url: String?
get() = getUrl()
public val android.webkit.WebView.privateBrowsingEnabled: Boolean
get() = isPrivateBrowsingEnabled()
public var android.widget.AbsListView.cacheColorHint: Int
get() = getCacheColorHint()
set(v) = setCacheColorHint(v)
public val android.widget.AbsListView.checkedItemIds: LongArray
get() = getCheckedItemIds()
public var android.widget.AbsListView.choiceMode: Int
get() = getChoiceMode()
set(v) = setChoiceMode(v)
public val android.widget.AbsListView.selectedView: android.view.View?
get() = getSelectedView()
public var android.widget.AbsListView.selector: android.graphics.drawable.Drawable?
get() = getSelector()
set(v) = setSelector(v)
public var android.widget.AbsListView.selectorResource: Int
get() = throw AnkoException("'android.widget.AbsListView.selectorResource' property does not have a getter")
set(v) = setSelector(v)
public var android.widget.AbsListView.transcriptMode: Int
get() = getTranscriptMode()
set(v) = setTranscriptMode(v)
public var android.widget.AbsListView.fastScrollAlwaysVisible: Boolean
get() = isFastScrollAlwaysVisible()
set(v) = setFastScrollAlwaysVisible(v)
public var android.widget.AbsListView.fastScrollEnabled: Boolean
get() = isFastScrollEnabled()
set(v) = setFastScrollEnabled(v)
public var android.widget.AbsListView.scrollingCacheEnabled: Boolean
get() = isScrollingCacheEnabled()
set(v) = setScrollingCacheEnabled(v)
public var android.widget.AbsListView.smoothScrollbarEnabled: Boolean
get() = isSmoothScrollbarEnabled()
set(v) = setSmoothScrollbarEnabled(v)
public var android.widget.AbsListView.stackFromBottom: Boolean
get() = isStackFromBottom()
set(v) = setStackFromBottom(v)
public var android.widget.AbsListView.textFilterEnabled: Boolean
get() = isTextFilterEnabled()
set(v) = setTextFilterEnabled(v)
public var android.widget.AbsSeekBar.keyProgressIncrement: Int
get() = getKeyProgressIncrement()
set(v) = setKeyProgressIncrement(v)
public var android.widget.AbsSeekBar.thumbOffset: Int
get() = getThumbOffset()
set(v) = setThumbOffset(v)
public var android.widget.AdapterView<out android.widget.Adapter?>.emptyView: android.view.View?
get() = getEmptyView()
set(v) = setEmptyView(v)
public val android.widget.AdapterView<out android.widget.Adapter?>.firstVisiblePosition: Int
get() = getFirstVisiblePosition()
public val android.widget.AdapterView<out android.widget.Adapter?>.lastVisiblePosition: Int
get() = getLastVisiblePosition()
public var android.widget.AdapterViewFlipper.autoStart: Boolean
get() = isAutoStart()
set(v) = setAutoStart(v)
public val android.widget.AdapterViewFlipper.flipping: Boolean
get() = isFlipping()
public val android.widget.AutoCompleteTextView.adapter: android.widget.ListAdapter?
get() = getAdapter()
public var android.widget.AutoCompleteTextView.dropDownAnchor: Int
get() = getDropDownAnchor()
set(v) = setDropDownAnchor(v)
public val android.widget.AutoCompleteTextView.dropDownBackground: android.graphics.drawable.Drawable?
get() = getDropDownBackground()
public var android.widget.AutoCompleteTextView.dropDownHeight: Int
get() = getDropDownHeight()
set(v) = setDropDownHeight(v)
public var android.widget.AutoCompleteTextView.dropDownHorizontalOffset: Int
get() = getDropDownHorizontalOffset()
set(v) = setDropDownHorizontalOffset(v)
public var android.widget.AutoCompleteTextView.dropDownVerticalOffset: Int
get() = getDropDownVerticalOffset()
set(v) = setDropDownVerticalOffset(v)
public var android.widget.AutoCompleteTextView.dropDownWidth: Int
get() = getDropDownWidth()
set(v) = setDropDownWidth(v)
public var android.widget.AutoCompleteTextView.listSelection: Int
get() = getListSelection()
set(v) = setListSelection(v)
public var android.widget.AutoCompleteTextView.threshold: Int
get() = getThreshold()
set(v) = setThreshold(v)
public var android.widget.AutoCompleteTextView.validator: android.widget.AutoCompleteTextView.Validator?
get() = getValidator()
set(v) = setValidator(v)
public val android.widget.AutoCompleteTextView.performingCompletion: Boolean
get() = isPerformingCompletion()
public val android.widget.AutoCompleteTextView.popupShowing: Boolean
get() = isPopupShowing()
public var android.widget.CalendarView.date: Long
get() = getDate()
set(v) = setDate(v)
public var android.widget.CalendarView.firstDayOfWeek: Int
get() = getFirstDayOfWeek()
set(v) = setFirstDayOfWeek(v)
public var android.widget.CalendarView.maxDate: Long
get() = getMaxDate()
set(v) = setMaxDate(v)
public var android.widget.CalendarView.minDate: Long
get() = getMinDate()
set(v) = setMinDate(v)
public var android.widget.CalendarView.showWeekNumber: Boolean
get() = getShowWeekNumber()
set(v) = setShowWeekNumber(v)
public var android.widget.CalendarView.enabled: Boolean
get() = isEnabled()
set(v) = setEnabled(v)
public var android.widget.CheckedTextView.checked: Boolean
get() = isChecked()
set(v) = setChecked(v)
public var android.widget.Chronometer.base: Long
get() = getBase()
set(v) = setBase(v)
public var android.widget.Chronometer.format: String?
get() = getFormat()
set(v) = setFormat(v)
public var android.widget.CompoundButton.checked: Boolean
get() = isChecked()
set(v) = setChecked(v)
public val android.widget.DatePicker.calendarView: android.widget.CalendarView?
get() = getCalendarView()
public var android.widget.DatePicker.calendarViewShown: Boolean
get() = getCalendarViewShown()
set(v) = setCalendarViewShown(v)
public val android.widget.DatePicker.dayOfMonth: Int
get() = getDayOfMonth()
public var android.widget.DatePicker.maxDate: Long
get() = getMaxDate()
set(v) = setMaxDate(v)
public var android.widget.DatePicker.minDate: Long
get() = getMinDate()
set(v) = setMinDate(v)
public val android.widget.DatePicker.month: Int
get() = getMonth()
public var android.widget.DatePicker.spinnersShown: Boolean
get() = getSpinnersShown()
set(v) = setSpinnersShown(v)
public val android.widget.DatePicker.year: Int
get() = getYear()
public var android.widget.DatePicker.enabled: Boolean
get() = isEnabled()
set(v) = setEnabled(v)
public val android.widget.DialerFilter.digits: CharSequence?
get() = getDigits()
public val android.widget.DialerFilter.filterText: CharSequence?
get() = getFilterText()
public val android.widget.DialerFilter.letters: CharSequence?
get() = getLetters()
public var android.widget.DialerFilter.mode: Int
get() = getMode()
set(v) = setMode(v)
public val android.widget.DialerFilter.qwertyKeyboard: Boolean
get() = isQwertyKeyboard()
public var android.widget.ExpandableListView.adapter: android.widget.ListAdapter?
get() = getAdapter()
set(v) = setAdapter(v)
public val android.widget.ExpandableListView.expandableListAdapter: android.widget.ExpandableListAdapter?
get() = getExpandableListAdapter()
public val android.widget.ExpandableListView.selectedId: Long
get() = getSelectedId()
public val android.widget.ExpandableListView.selectedPosition: Long
get() = getSelectedPosition()
public val android.widget.FrameLayout.considerGoneChildrenWhenMeasuring: Boolean
get() = getConsiderGoneChildrenWhenMeasuring()
public var android.widget.FrameLayout.foreground: android.graphics.drawable.Drawable?
get() = getForeground()
set(v) = setForeground(v)
public var android.widget.FrameLayout.measureAllChildren: Boolean
get() = getMeasureAllChildren()
set(v) = setMeasureAllChildren(v)
public var android.widget.GridLayout.alignmentMode: Int
get() = getAlignmentMode()
set(v) = setAlignmentMode(v)
public var android.widget.GridLayout.columnCount: Int
get() = getColumnCount()
set(v) = setColumnCount(v)
public var android.widget.GridLayout.orientation: Int
get() = getOrientation()
set(v) = setOrientation(v)
public var android.widget.GridLayout.rowCount: Int
get() = getRowCount()
set(v) = setRowCount(v)
public var android.widget.GridLayout.useDefaultMargins: Boolean
get() = getUseDefaultMargins()
set(v) = setUseDefaultMargins(v)
public var android.widget.GridLayout.columnOrderPreserved: Boolean
get() = isColumnOrderPreserved()
set(v) = setColumnOrderPreserved(v)
public var android.widget.GridLayout.rowOrderPreserved: Boolean
get() = isRowOrderPreserved()
set(v) = setRowOrderPreserved(v)
public var android.widget.GridView.adapter: android.widget.ListAdapter?
get() = getAdapter()
set(v) = setAdapter(v)
public var android.widget.GridView.numColumns: Int
get() = getNumColumns()
set(v) = setNumColumns(v)
public var android.widget.GridView.stretchMode: Int
get() = getStretchMode()
set(v) = setStretchMode(v)
public val android.widget.HorizontalScrollView.maxScrollAmount: Int
get() = getMaxScrollAmount()
public var android.widget.HorizontalScrollView.fillViewport: Boolean
get() = isFillViewport()
set(v) = setFillViewport(v)
public var android.widget.HorizontalScrollView.smoothScrollingEnabled: Boolean
get() = isSmoothScrollingEnabled()
set(v) = setSmoothScrollingEnabled(v)
public var android.widget.ImageView.baseline: Int
get() = getBaseline()
set(v) = setBaseline(v)
public var android.widget.ImageView.baselineAlignBottom: Boolean
get() = getBaselineAlignBottom()
set(v) = setBaselineAlignBottom(v)
public var android.widget.ImageView.imageMatrix: android.graphics.Matrix?
get() = getImageMatrix()
set(v) = setImageMatrix(v)
public var android.widget.ImageView.scaleType: android.widget.ImageView.ScaleType?
get() = getScaleType()
set(v) = setScaleType(v)
public val android.widget.LinearLayout.baseline: Int
get() = getBaseline()
public var android.widget.LinearLayout.baselineAlignedChildIndex: Int
get() = getBaselineAlignedChildIndex()
set(v) = setBaselineAlignedChildIndex(v)
public var android.widget.LinearLayout.dividerPadding: Int
get() = getDividerPadding()
set(v) = setDividerPadding(v)
public var android.widget.LinearLayout.orientation: Int
get() = getOrientation()
set(v) = setOrientation(v)
public var android.widget.LinearLayout.showDividers: Int
get() = getShowDividers()
set(v) = setShowDividers(v)
public var android.widget.LinearLayout.weightSum: Float
get() = getWeightSum()
set(v) = setWeightSum(v)
public var android.widget.LinearLayout.baselineAligned: Boolean
get() = isBaselineAligned()
set(v) = setBaselineAligned(v)
public var android.widget.LinearLayout.measureWithLargestChildEnabled: Boolean
get() = isMeasureWithLargestChildEnabled()
set(v) = setMeasureWithLargestChildEnabled(v)
public var android.widget.ListView.adapter: android.widget.ListAdapter?
get() = getAdapter()
set(v) = setAdapter(v)
public val android.widget.ListView.checkItemIds: LongArray
get() = getCheckItemIds()
public var android.widget.ListView.divider: android.graphics.drawable.Drawable?
get() = getDivider()
set(v) = setDivider(v)
public var android.widget.ListView.dividerHeight: Int
get() = getDividerHeight()
set(v) = setDividerHeight(v)
public val android.widget.ListView.footerViewsCount: Int
get() = getFooterViewsCount()
public val android.widget.ListView.headerViewsCount: Int
get() = getHeaderViewsCount()
public var android.widget.ListView.itemsCanFocus: Boolean
get() = getItemsCanFocus()
set(v) = setItemsCanFocus(v)
public val android.widget.ListView.maxScrollAmount: Int
get() = getMaxScrollAmount()
public var android.widget.ListView.overscrollFooter: android.graphics.drawable.Drawable?
get() = getOverscrollFooter()
set(v) = setOverscrollFooter(v)
public var android.widget.ListView.overscrollHeader: android.graphics.drawable.Drawable?
get() = getOverscrollHeader()
set(v) = setOverscrollHeader(v)
public val android.widget.ListView.opaque: Boolean
get() = isOpaque()
public var android.widget.NumberPicker.displayedValues: Array<String>?
get() = getDisplayedValues()
set(v) = setDisplayedValues(v)
public var android.widget.NumberPicker.maxValue: Int
get() = getMaxValue()
set(v) = setMaxValue(v)
public var android.widget.NumberPicker.minValue: Int
get() = getMinValue()
set(v) = setMinValue(v)
public val android.widget.NumberPicker.solidColor: Int
get() = getSolidColor()
public var android.widget.NumberPicker.value: Int
get() = getValue()
set(v) = setValue(v)
public var android.widget.NumberPicker.wrapSelectorWheel: Boolean
get() = getWrapSelectorWheel()
set(v) = setWrapSelectorWheel(v)
public var android.widget.ProgressBar.indeterminateDrawable: android.graphics.drawable.Drawable?
get() = getIndeterminateDrawable()
set(v) = setIndeterminateDrawable(v)
public var android.widget.ProgressBar.interpolator: android.view.animation.Interpolator?
get() = getInterpolator()
set(v) = setInterpolator(v)
public var android.widget.ProgressBar.max: Int
get() = getMax()
set(v) = setMax(v)
public var android.widget.ProgressBar.progress: Int
get() = getProgress()
set(v) = setProgress(v)
public var android.widget.ProgressBar.progressDrawable: android.graphics.drawable.Drawable?
get() = getProgressDrawable()
set(v) = setProgressDrawable(v)
public var android.widget.ProgressBar.secondaryProgress: Int
get() = getSecondaryProgress()
set(v) = setSecondaryProgress(v)
public var android.widget.ProgressBar.indeterminate: Boolean
get() = isIndeterminate()
set(v) = setIndeterminate(v)
public var android.widget.RatingBar.numStars: Int
get() = getNumStars()
set(v) = setNumStars(v)
public var android.widget.RatingBar.rating: Float
get() = getRating()
set(v) = setRating(v)
public var android.widget.RatingBar.stepSize: Float
get() = getStepSize()
set(v) = setStepSize(v)
public val android.widget.RatingBar.indicator: Boolean
get() = isIndicator()
public val android.widget.RelativeLayout.baseline: Int
get() = getBaseline()
public val android.widget.ScrollView.maxScrollAmount: Int
get() = getMaxScrollAmount()
public var android.widget.ScrollView.fillViewport: Boolean
get() = isFillViewport()
set(v) = setFillViewport(v)
public var android.widget.ScrollView.smoothScrollingEnabled: Boolean
get() = isSmoothScrollingEnabled()
set(v) = setSmoothScrollingEnabled(v)
public val android.widget.SearchView.query: CharSequence?
get() = getQuery()
public var android.widget.SearchView.suggestionsAdapter: android.widget.CursorAdapter?
get() = getSuggestionsAdapter()
set(v) = setSuggestionsAdapter(v)
public val android.widget.SearchView.iconfiedByDefault: Boolean
get() = isIconfiedByDefault()
public var android.widget.SearchView.iconified: Boolean
get() = isIconified()
set(v) = setIconified(v)
public var android.widget.SearchView.queryRefinementEnabled: Boolean
get() = isQueryRefinementEnabled()
set(v) = setQueryRefinementEnabled(v)
public var android.widget.SearchView.submitButtonEnabled: Boolean
get() = isSubmitButtonEnabled()
set(v) = setSubmitButtonEnabled(v)
public val android.widget.SlidingDrawer.content: android.view.View?
get() = getContent()
public val android.widget.SlidingDrawer.handle: android.view.View?
get() = getHandle()
public val android.widget.SlidingDrawer.moving: Boolean
get() = isMoving()
public val android.widget.SlidingDrawer.opened: Boolean
get() = isOpened()
public val android.widget.Spinner.baseline: Int
get() = getBaseline()
public var android.widget.Spinner.prompt: CharSequence?
get() = getPrompt()
set(v) = setPrompt(v)
public val android.widget.Switch.compoundPaddingRight: Int
get() = getCompoundPaddingRight()
public var android.widget.Switch.textOff: CharSequence?
get() = getTextOff()
set(v) = setTextOff(v)
public var android.widget.Switch.textOn: CharSequence?
get() = getTextOn()
set(v) = setTextOn(v)
public var android.widget.TabHost.currentTab: Int
get() = getCurrentTab()
set(v) = setCurrentTab(v)
public val android.widget.TabHost.currentTabTag: String?
get() = getCurrentTabTag()
public val android.widget.TabHost.currentTabView: android.view.View?
get() = getCurrentTabView()
public val android.widget.TabHost.currentView: android.view.View?
get() = getCurrentView()
public val android.widget.TabHost.tabContentView: android.widget.FrameLayout?
get() = getTabContentView()
public val android.widget.TabHost.tabWidget: android.widget.TabWidget?
get() = getTabWidget()
public val android.widget.TabWidget.tabCount: Int
get() = getTabCount()
public var android.widget.TabWidget.stripEnabled: Boolean
get() = isStripEnabled()
set(v) = setStripEnabled(v)
public var android.widget.TableLayout.shrinkAllColumns: Boolean
get() = isShrinkAllColumns()
set(v) = setShrinkAllColumns(v)
public var android.widget.TableLayout.stretchAllColumns: Boolean
get() = isStretchAllColumns()
set(v) = setStretchAllColumns(v)
public val android.widget.TableRow.virtualChildCount: Int
get() = getVirtualChildCount()
public var android.widget.TextView.autoLinkMask: Int
get() = getAutoLinkMask()
set(v) = setAutoLinkMask(v)
public val android.widget.TextView.baseline: Int
get() = getBaseline()
public var android.widget.TextView.compoundDrawablePadding: Int
get() = getCompoundDrawablePadding()
set(v) = setCompoundDrawablePadding(v)
public val android.widget.TextView.compoundDrawables: Array<android.graphics.drawable.Drawable>?
get() = getCompoundDrawables()
public val android.widget.TextView.compoundPaddingBottom: Int
get() = getCompoundPaddingBottom()
public val android.widget.TextView.compoundPaddingLeft: Int
get() = getCompoundPaddingLeft()
public val android.widget.TextView.compoundPaddingRight: Int
get() = getCompoundPaddingRight()
public val android.widget.TextView.compoundPaddingTop: Int
get() = getCompoundPaddingTop()
public val android.widget.TextView.currentHintTextColor: Int
get() = getCurrentHintTextColor()
public val android.widget.TextView.currentTextColor: Int
get() = getCurrentTextColor()
public var android.widget.TextView.customSelectionActionModeCallback: android.view.ActionMode.Callback?
get() = getCustomSelectionActionModeCallback()
set(v) = setCustomSelectionActionModeCallback(v)
public val android.widget.TextView.editableText: android.text.Editable?
get() = getEditableText()
public var android.widget.TextView.ellipsize: android.text.TextUtils.TruncateAt?
get() = getEllipsize()
set(v) = setEllipsize(v)
public var android.widget.TextView.error: CharSequence?
get() = getError()
set(v) = setError(v)
public val android.widget.TextView.extendedPaddingBottom: Int
get() = getExtendedPaddingBottom()
public val android.widget.TextView.extendedPaddingTop: Int
get() = getExtendedPaddingTop()
public var android.widget.TextView.filters: Array<android.text.InputFilter>?
get() = getFilters()
set(v) = setFilters(v)
public var android.widget.TextView.freezesText: Boolean
get() = getFreezesText()
set(v) = setFreezesText(v)
public var android.widget.TextView.gravity: Int
get() = getGravity()
set(v) = setGravity(v)
public var android.widget.TextView.hint: CharSequence?
get() = getHint()
set(v) = setHint(v)
public var android.widget.TextView.hintResource: Int
get() = throw AnkoException("'android.widget.TextView.hintResource' property does not have a getter")
set(v) = setHint(v)
public val android.widget.TextView.hintTextColors: android.content.res.ColorStateList?
get() = getHintTextColors()
public val android.widget.TextView.imeActionId: Int
get() = getImeActionId()
public val android.widget.TextView.imeActionLabel: CharSequence?
get() = getImeActionLabel()
public var android.widget.TextView.imeOptions: Int
get() = getImeOptions()
set(v) = setImeOptions(v)
public var android.widget.TextView.inputType: Int
get() = getInputType()
set(v) = setInputType(v)
public val android.widget.TextView.layout: android.text.Layout?
get() = getLayout()
public val android.widget.TextView.lineCount: Int
get() = getLineCount()
public val android.widget.TextView.lineHeight: Int
get() = getLineHeight()
public val android.widget.TextView.linkTextColors: android.content.res.ColorStateList?
get() = getLinkTextColors()
public var android.widget.TextView.linksClickable: Boolean
get() = getLinksClickable()
set(v) = setLinksClickable(v)
public var android.widget.TextView.movementMethod: android.text.method.MovementMethod?
get() = getMovementMethod()
set(v) = setMovementMethod(v)
public val android.widget.TextView.paint: android.text.TextPaint
get() = getPaint()
public var android.widget.TextView.paintFlags: Int
get() = getPaintFlags()
set(v) = setPaintFlags(v)
public var android.widget.TextView.privateImeOptions: String?
get() = getPrivateImeOptions()
set(v) = setPrivateImeOptions(v)
public val android.widget.TextView.selectionEnd: Int
get() = getSelectionEnd()
public val android.widget.TextView.selectionStart: Int
get() = getSelectionStart()
public var android.widget.TextView.text: CharSequence
get() = getText()
set(v) = setText(v)
public var android.widget.TextView.textResource: Int
get() = throw AnkoException("'android.widget.TextView.textResource' property does not have a getter")
set(v) = setText(v)
public val android.widget.TextView.textColors: android.content.res.ColorStateList?
get() = getTextColors()
public var android.widget.TextView.textScaleX: Float
get() = getTextScaleX()
set(v) = setTextScaleX(v)
public var android.widget.TextView.textSize: Float
get() = getTextSize()
set(v) = setTextSize(v)
public var android.widget.TextView.transformationMethod: android.text.method.TransformationMethod?
get() = getTransformationMethod()
set(v) = setTransformationMethod(v)
public var android.widget.TextView.typeface: android.graphics.Typeface?
get() = getTypeface()
set(v) = setTypeface(v)
public val android.widget.TextView.urls: Array<android.text.style.URLSpan>?
get() = getUrls()
public val android.widget.TextView.inputMethodTarget: Boolean
get() = isInputMethodTarget()
public val android.widget.TextView.suggestionsEnabled: Boolean
get() = isSuggestionsEnabled()
public val android.widget.TimePicker.baseline: Int
get() = getBaseline()
public var android.widget.TimePicker.currentHour: Int?
get() = getCurrentHour()
set(v) = setCurrentHour(v)
public var android.widget.TimePicker.currentMinute: Int?
get() = getCurrentMinute()
set(v) = setCurrentMinute(v)
public var android.widget.TimePicker.enabled: Boolean
get() = isEnabled()
set(v) = setEnabled(v)
public var android.widget.ToggleButton.textOff: CharSequence?
get() = getTextOff()
set(v) = setTextOff(v)
public var android.widget.ToggleButton.textOn: CharSequence?
get() = getTextOn()
set(v) = setTextOn(v)
public val android.widget.TwoLineListItem.text1: android.widget.TextView?
get() = getText1()
public val android.widget.TwoLineListItem.text2: android.widget.TextView?
get() = getText2()
public val android.widget.VideoView.bufferPercentage: Int
get() = getBufferPercentage()
public val android.widget.VideoView.currentPosition: Int
get() = getCurrentPosition()
public val android.widget.VideoView.duration: Int
get() = getDuration()
public val android.widget.VideoView.playing: Boolean
get() = isPlaying()
public val android.widget.ViewAnimator.baseline: Int
get() = getBaseline()
public val android.widget.ViewAnimator.currentView: android.view.View?
get() = getCurrentView()
public var android.widget.ViewAnimator.displayedChild: Int
get() = getDisplayedChild()
set(v) = setDisplayedChild(v)
public var android.widget.ViewAnimator.inAnimation: android.view.animation.Animation?
get() = getInAnimation()
set(v) = setInAnimation(v)
public var android.widget.ViewAnimator.outAnimation: android.view.animation.Animation?
get() = getOutAnimation()
set(v) = setOutAnimation(v)
public var android.widget.ViewFlipper.autoStart: Boolean
get() = isAutoStart()
set(v) = setAutoStart(v)
public val android.widget.ViewFlipper.flipping: Boolean
get() = isFlipping()
public val android.widget.ViewSwitcher.nextView: android.view.View?
get() = getNextView()
public var android.view.View.minimumHeight: Int
get() = throw AnkoException("'android.view.View.minimumHeight' property does not have a getter")
set(v) = setMinimumHeight(v)
public var android.view.View.minimumWidth: Int
get() = throw AnkoException("'android.view.View.minimumWidth' property does not have a getter")
set(v) = setMinimumWidth(v)
public var android.widget.TextView.enabled: Boolean
get() = throw AnkoException("'android.widget.TextView.enabled' property does not have a getter")
set(v) = setEnabled(v)
public var android.widget.TextView.textColor: Int
get() = throw AnkoException("'android.widget.TextView.textColor' property does not have a getter")
set(v) = setTextColor(v)
public var android.widget.TextView.highlightColor: Int
get() = throw AnkoException("'android.widget.TextView.highlightColor' property does not have a getter")
set(v) = setHighlightColor(v)
public var android.widget.TextView.hintTextColor: Int
get() = throw AnkoException("'android.widget.TextView.hintTextColor' property does not have a getter")
set(v) = setHintTextColor(v)
public var android.widget.TextView.linkTextColor: Int
get() = throw AnkoException("'android.widget.TextView.linkTextColor' property does not have a getter")
set(v) = setLinkTextColor(v)
public var android.widget.TextView.minLines: Int
get() = throw AnkoException("'android.widget.TextView.minLines' property does not have a getter")
set(v) = setMinLines(v)
public var android.widget.TextView.maxLines: Int
get() = throw AnkoException("'android.widget.TextView.maxLines' property does not have a getter")
set(v) = setMaxLines(v)
public var android.widget.TextView.lines: Int
get() = throw AnkoException("'android.widget.TextView.lines' property does not have a getter")
set(v) = setLines(v)
public var android.widget.TextView.minEms: Int
get() = throw AnkoException("'android.widget.TextView.minEms' property does not have a getter")
set(v) = setMinEms(v)
public var android.widget.TextView.maxEms: Int
get() = throw AnkoException("'android.widget.TextView.maxEms' property does not have a getter")
set(v) = setMaxEms(v)
public var android.widget.TextView.singleLine: Boolean
get() = throw AnkoException("'android.widget.TextView.singleLine' property does not have a getter")
set(v) = setSingleLine(v)
public var android.widget.TextView.marqueeRepeatLimit: Int
get() = throw AnkoException("'android.widget.TextView.marqueeRepeatLimit' property does not have a getter")
set(v) = setMarqueeRepeatLimit(v)
public var android.widget.TextView.cursorVisible: Boolean
get() = throw AnkoException("'android.widget.TextView.cursorVisible' property does not have a getter")
set(v) = setCursorVisible(v)
public var android.widget.ImageView.imageURI: android.net.Uri?
get() = throw AnkoException("'android.widget.ImageView.imageURI' property does not have a getter")
set(v) = setImageURI(v)
public var android.widget.ImageView.imageBitmap: android.graphics.Bitmap?
get() = throw AnkoException("'android.widget.ImageView.imageBitmap' property does not have a getter")
set(v) = setImageBitmap(v)
public var android.widget.RelativeLayout.gravity: Int
get() = throw AnkoException("'android.widget.RelativeLayout.gravity' property does not have a getter")
set(v) = setGravity(v)
public var android.widget.LinearLayout.gravity: Int
get() = throw AnkoException("'android.widget.LinearLayout.gravity' property does not have a getter")
set(v) = setGravity(v)
public var android.widget.Gallery.gravity: Int
get() = throw AnkoException("'android.widget.Gallery.gravity' property does not have a getter")
set(v) = setGravity(v)
public var android.widget.Spinner.gravity: Int
get() = throw AnkoException("'android.widget.Spinner.gravity' property does not have a getter")
set(v) = setGravity(v)
public var android.widget.GridView.gravity: Int
get() = throw AnkoException("'android.widget.GridView.gravity' property does not have a getter")
set(v) = setGravity(v) | apache-2.0 | b58bc93a3437098db641af8326a60baa | 32.312663 | 139 | 0.745346 | 3.83426 | false | false | false | false |
iPoli/iPoli-android | app/src/main/java/io/ipoli/android/player/usecase/RemoveRewardFromPlayerUseCase.kt | 1 | 2603 | package io.ipoli.android.player.usecase
import io.ipoli.android.achievement.usecase.UnlockAchievementsUseCase
import io.ipoli.android.achievement.usecase.UpdatePlayerStatsUseCase
import io.ipoli.android.common.Reward
import io.ipoli.android.common.UseCase
import io.ipoli.android.player.LevelDownScheduler
import io.ipoli.android.player.data.Player
import io.ipoli.android.player.persistence.PlayerRepository
/**
* Created by Venelin Valkov <[email protected]>
* on 29.11.17.
*/
open class RemoveRewardFromPlayerUseCase(
private val playerRepository: PlayerRepository,
private val levelDownScheduler: LevelDownScheduler,
private val unlockAchievementsUseCase: UnlockAchievementsUseCase
) : UseCase<RemoveRewardFromPlayerUseCase.Params, Player> {
override fun execute(parameters: Params): Player {
val player = parameters.player ?: playerRepository.find()
requireNotNull(player)
val reward = parameters.reward
val p = removeRewardAndUpdateStats(player!!, reward, parameters.rewardType)
val newPlayer = playerRepository.save(p)
if (player.level != newPlayer.level) {
levelDownScheduler.schedule()
}
unlockAchievementsUseCase.execute(
UnlockAchievementsUseCase.Params(
player = newPlayer,
eventType = UpdatePlayerStatsUseCase.Params.EventType.ExperienceDecreased(reward.experience.toLong())
)
)
return newPlayer
}
private fun removeRewardAndUpdateStats(
player: Player,
reward: Reward,
rewardType: Params.RewardType
): Player {
val newPlayer = player.removeReward(reward)
val newStats = when (rewardType) {
Params.RewardType.GOOD_HABIT -> newPlayer.statistics.copy(
habitCompletedCountForDay = newPlayer.statistics.habitCompletedCountForDay.removeValue(
1
)
)
Params.RewardType.QUEST -> newPlayer.statistics.copy(
questCompletedCountForDay = newPlayer.statistics.questCompletedCountForDay.removeValue(
1
),
questCompletedCount = Math.max(newPlayer.statistics.questCompletedCount - 1, 0)
)
else -> newPlayer.statistics
}
return newPlayer.copy(
statistics = newStats
)
}
data class Params(val rewardType: RewardType, val reward: Reward, val player: Player? = null) {
enum class RewardType {
BAD_HABIT, GOOD_HABIT, QUEST
}
}
} | gpl-3.0 | 5f62a66db410aec072187af278515093 | 35.676056 | 117 | 0.669612 | 4.874532 | false | false | false | false |
GunoH/intellij-community | platform/core-api/src/com/intellij/util/messages/impl/MessageBusImpl.kt | 5 | 23294 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
@file:Suppress("ReplaceGetOrSet")
package com.intellij.util.messages.impl
import com.intellij.codeWithMe.ClientId.Companion.withClientId
import com.intellij.diagnostic.PluginException
import com.intellij.openapi.Disposable
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.progress.ProcessCanceledException
import com.intellij.openapi.util.Disposer
import com.intellij.util.ArrayUtilRt
import com.intellij.util.EventDispatcher
import com.intellij.util.concurrency.AppExecutorUtil
import com.intellij.util.lang.CompoundRuntimeException
import com.intellij.util.messages.*
import com.intellij.util.messages.Topic.BroadcastDirection
import org.jetbrains.annotations.ApiStatus.Internal
import org.jetbrains.annotations.VisibleForTesting
import java.lang.invoke.MethodHandle
import java.lang.reflect.InvocationHandler
import java.lang.reflect.Method
import java.lang.reflect.Proxy
import java.util.*
import java.util.concurrent.*
import java.util.concurrent.atomic.AtomicInteger
import java.util.concurrent.atomic.AtomicReference
import java.util.function.Predicate
@Internal
open class MessageBusImpl : MessageBus {
interface MessageHandlerHolder {
val isDisposed: Boolean
fun collectHandlers(topic: Topic<*>, result: MutableList<Any>)
fun disconnectIfNeeded(predicate: Predicate<Class<*>>)
}
companion object {
@JvmField
internal val LOG = Logger.getInstance(MessageBusImpl::class.java)
}
@JvmField
internal val publisherCache: ConcurrentMap<Topic<*>, Any> = ConcurrentHashMap()
@JvmField
internal val subscribers = ConcurrentLinkedQueue<MessageHandlerHolder>()
// caches subscribers for this bus and its children or parent, depending on the topic's broadcast policy
@JvmField
internal val subscriberCache = ConcurrentHashMap<Topic<*>, Array<Any?>>()
@JvmField
internal val parentBus: CompositeMessageBus?
@JvmField
internal val rootBus: RootBus
@JvmField
internal val owner: MessageBusOwner
// 0 active, 1 dispose in progress 2 disposed
private var disposeState = 0
// separate disposable must be used, because container will dispose bus connections in a separate step
private var connectionDisposable: Disposable? = Disposer.newDisposable()
@JvmField
internal var messageDeliveryListener: MessageDeliveryListener? = null
constructor(owner: MessageBusOwner, parentBus: CompositeMessageBus) {
this.owner = owner
this.parentBus = parentBus
rootBus = parentBus.rootBus
@Suppress("LeakingThis")
parentBus.addChild(this)
}
// root message bus constructor
internal constructor(owner: MessageBusOwner) {
this.owner = owner
@Suppress("LeakingThis")
rootBus = this as RootBus
parentBus = null
}
override fun getParent(): MessageBus? = parentBus
override fun toString() = "MessageBus(owner=$owner, disposeState= $disposeState)"
override fun connect() = connect(connectionDisposable!!)
override fun connect(parentDisposable: Disposable): MessageBusConnection {
checkNotDisposed()
val connection = MessageBusConnectionImpl(this)
subscribers.add(connection)
Disposer.register(parentDisposable, connection)
return connection
}
override fun simpleConnect(): SimpleMessageBusConnection {
// avoid registering in Dispose tree, default handler and deliverImmediately are not supported
checkNotDisposed()
val connection = SimpleMessageBusConnectionImpl(this)
subscribers.add(connection)
return connection
}
override fun <L : Any> syncPublisher(topic: Topic<L>): L {
if (isDisposed) {
PluginException.logPluginError(LOG, "Already disposed: $this", null, topic.javaClass)
}
@Suppress("UNCHECKED_CAST")
return publisherCache.computeIfAbsent(topic) { topic1: Topic<*> ->
val aClass = topic1.listenerClass
Proxy.newProxyInstance(aClass.classLoader, arrayOf(aClass), createPublisher(topic1, topic1.broadcastDirection))
} as L
}
internal open fun <L> createPublisher(topic: Topic<L>, direction: BroadcastDirection): MessagePublisher<L> {
return when (direction) {
BroadcastDirection.TO_PARENT -> ToParentMessagePublisher(topic, this)
BroadcastDirection.TO_DIRECT_CHILDREN -> {
throw IllegalArgumentException("Broadcast direction TO_DIRECT_CHILDREN is allowed only for app level message bus. " +
"Please publish to app level message bus or change topic broadcast direction to NONE or TO_PARENT")
}
else -> {
LOG.error("Topic ${topic.listenerClass.name} broadcast direction TO_CHILDREN is not allowed for module level message bus. " +
"Please change to NONE or TO_PARENT")
MessagePublisher(topic, this)
}
}
}
fun disposeConnectionChildren() {
// avoid any work on notifyConnectionTerminated
disposeState = DISPOSE_IN_PROGRESS
Disposer.disposeChildren(connectionDisposable!!) { true }
}
fun disposeConnection() {
Disposer.dispose(connectionDisposable!!)
connectionDisposable = null
}
override fun dispose() {
if (disposeState == DISPOSED_STATE) {
LOG.error("Already disposed: $this")
}
disposeState = DISPOSED_STATE
disposeChildren()
connectionDisposable?.let {
Disposer.dispose(it)
}
rootBus.queue.queue.removeIf { it.bus === this }
parentBus?.onChildBusDisposed(this)
}
protected open fun disposeChildren() {
}
override fun isDisposed() = disposeState == DISPOSED_STATE || owner.isDisposed
override fun hasUndeliveredEvents(topic: Topic<*>): Boolean {
if (isDisposed) {
return false
}
val queue = rootBus.queue
val current = queue.current
if (current != null && current.topic === topic && current.bus === this) {
return true
}
return queue.queue.any { it.topic === topic && it.bus === this }
}
internal fun checkNotDisposed() {
if (isDisposed) {
LOG.error("Already disposed: $this")
}
}
open fun doComputeSubscribers(topic: Topic<*>, result: MutableList<Any>, subscribeLazyListeners: Boolean) {
// todo check that handler implements method (not a default implementation)
for (subscriber in subscribers) {
if (!subscriber.isDisposed) {
subscriber.collectHandlers(topic, result)
}
}
}
open fun computeSubscribers(topic: Topic<*>): Array<Any?> {
val result = mutableListOf<Any>()
doComputeSubscribers(topic = topic, result = result, subscribeLazyListeners = true)
return if (result.isEmpty()) ArrayUtilRt.EMPTY_OBJECT_ARRAY else result.toTypedArray()
}
open fun hasChildren(): Boolean = false
fun notifyOnSubscription(topic: Topic<*>) {
subscriberCache.remove(topic)
if (topic.broadcastDirection != BroadcastDirection.TO_CHILDREN) {
return
}
// Clear parents because parent caches subscribers for TO_CHILDREN direction on it's level and child levels.
// So, on subscription to child bus (this instance) parent cache must be invalidated.
var parentBus = this
while (true) {
parentBus = parentBus.parentBus ?: break
parentBus.subscriberCache.remove(topic)
}
if (hasChildren()) {
notifyOnSubscriptionToTopicToChildren(topic)
}
}
open fun notifyOnSubscriptionToTopicToChildren(topic: Topic<*>) {
}
open fun removeEmptyConnectionsRecursively() {
subscribers.removeIf { it.isDisposed }
}
open fun notifyConnectionTerminated(topicAndHandlerPairs: Array<Any>): Boolean {
if (disposeState != 0) {
return false
}
rootBus.scheduleEmptyConnectionRemoving()
return clearSubscriberCacheOnConnectionTerminated(topicAndHandlerPairs, this)
}
// this method is used only in CompositeMessageBus.notifyConnectionTerminated to clear subscriber cache in children
open fun clearSubscriberCache(topicAndHandlerPairs: Array<Any>) {
var i = 0
while (i < topicAndHandlerPairs.size) {
subscriberCache.remove(topicAndHandlerPairs[i])
i += 2
}
}
internal fun deliverImmediately(connection: MessageBusConnectionImpl) {
if (disposeState == DISPOSED_STATE) {
LOG.error("Already disposed: $this")
}
// light project is not disposed in tests properly, so, connection is not removed
if (owner.isDisposed) {
return
}
val queue = rootBus.queue
val jobs = queue.queue
if (jobs.isEmpty()) {
return
}
val newJobs = deliverImmediately(connection, jobs) ?: return
// add to queue to ensure that hasUndeliveredEvents works correctly
for (i in newJobs.indices.reversed()) {
jobs.addFirst(newJobs[i])
}
var exceptions: MutableList<Throwable>? = null
for (job in newJobs) {
// remove here will be not linear as job should be head (first element) in normal conditions
jobs.removeFirstOccurrence(job)
exceptions = deliverMessage(job, queue, exceptions)
}
exceptions?.let(::throwExceptions)
}
fun setMessageDeliveryListener(listener: MessageDeliveryListener?) {
check(messageDeliveryListener == null || listener == null) { "Already set: $messageDeliveryListener" }
messageDeliveryListener = listener
}
open fun disconnectPluginConnections(predicate: Predicate<Class<*>>) {
for (holder in subscribers) {
holder.disconnectIfNeeded(predicate)
}
subscriberCache.clear()
}
}
@Internal
@VisibleForTesting
class RootBus(owner: MessageBusOwner) : CompositeMessageBus(owner) {
private val compactionFutureRef = AtomicReference<CompletableFuture<*>?>()
private val compactionRequest = AtomicInteger()
private val emptyConnectionCounter = AtomicInteger()
private val queueThreadLocal: ThreadLocal<MessageQueue> = ThreadLocal.withInitial { MessageQueue() }
internal val queue: MessageQueue
get() = queueThreadLocal.get()
fun scheduleEmptyConnectionRemoving() {
val counter = emptyConnectionCounter.incrementAndGet()
if (counter < 128 || !emptyConnectionCounter.compareAndSet(counter, 0)) {
return
}
// The first thread detected a need for compaction schedules a compaction task.
// The task runs until all compaction requests are served.
if (compactionRequest.incrementAndGet() == 1) {
compactionFutureRef.set(CompletableFuture.runAsync({
var request: Int
do {
request = compactionRequest.get()
removeEmptyConnectionsRecursively()
}
while (!compactionRequest.compareAndSet(request, 0))
}, AppExecutorUtil.getAppExecutorService()))
}
}
override fun dispose() {
val compactionFuture = compactionFutureRef.getAndSet(null)
compactionFuture?.cancel(false)
compactionRequest.set(0)
super.dispose()
}
fun removeDisposedHandlers(topic: Topic<*>, handler: Any) {
val queue = queue.queue
if (queue.isEmpty()) {
return
}
queue.removeIf { message ->
for (messageIndex in message.handlers.indices) {
val messageHandler = message.handlers[messageIndex] ?: return@removeIf false
if (message.topic === topic && messageHandler === handler) {
message.handlers[messageIndex] = null
return@removeIf message.handlers.size == 1
}
}
false
}
}
}
internal class MessageQueue {
@JvmField
val queue = ArrayDeque<Message>()
@JvmField
var current: Message? = null
}
private val NA = Any()
private const val DISPOSE_IN_PROGRESS = 1
private const val DISPOSED_STATE = 2
private fun pumpWaiting(jobQueue: MessageQueue) {
var exceptions: MutableList<Throwable>? = null
var job = jobQueue.current
if (job != null) {
if (job.bus.isDisposed) {
MessageBusImpl.LOG.error("Accessing disposed message bus ${job.bus}")
}
else {
exceptions = deliverMessage(job, jobQueue, null)
}
}
while (true) {
job = jobQueue.queue.pollFirst() ?: break
if (job.bus.isDisposed) {
MessageBusImpl.LOG.error("Accessing disposed message bus ${job.bus}")
}
else {
exceptions = deliverMessage(job, jobQueue, exceptions)
}
}
exceptions?.let(::throwExceptions)
}
private fun deliverMessage(job: Message, jobQueue: MessageQueue, prevExceptions: MutableList<Throwable>?): MutableList<Throwable>? {
withClientId(job.clientId).use {
jobQueue.current = job
val handlers = job.handlers
var exceptions = prevExceptions
var index = job.currentHandlerIndex
val size = handlers.size
val lastIndex = size - 1
while (index < size) {
if (index == lastIndex) {
jobQueue.current = null
}
job.currentHandlerIndex++
val handler = handlers[index]
if (handler != null) {
exceptions = invokeListener(methodHandle = job.method,
methodName = job.methodName,
args = job.args,
topic = job.topic,
handler = handler,
messageDeliveryListener = job.bus.messageDeliveryListener,
prevExceptions = exceptions)
}
if (++index != job.currentHandlerIndex) {
// handler published some event and message queue including current job was processed as result, so, stop processing
return exceptions
}
}
return exceptions
}
}
internal open class MessagePublisher<L>(@JvmField protected val topic: Topic<L>,
@JvmField protected val bus: MessageBusImpl) : InvocationHandler {
final override fun invoke(proxy: Any, method: Method, args: Array<Any?>?): Any? {
if (method.declaringClass == Any::class.java) {
return EventDispatcher.handleObjectMethod(proxy, args, method.name)
}
if (topic.isImmediateDelivery) {
bus.checkNotDisposed()
publish(method = method, args = args, queue = null)
return NA
}
val queue = bus.rootBus.queue
if (!queue.queue.isEmpty()) {
pumpWaiting(queue)
}
if (publish(method = method, args = args, queue = queue)) {
// we must deliver messages now even if currently processing message queue, because if published as part of handler invocation,
// handler code expects that message will be delivered immediately after publishing
pumpWaiting(queue)
}
return NA
}
internal open fun publish(method: Method, args: Array<Any?>?, queue: MessageQueue?): Boolean {
val handlers = bus.subscriberCache.computeIfAbsent(topic, bus::computeSubscribers)
if (handlers.isEmpty()) {
return false
}
executeOrAddToQueue(topic = topic,
method = method,
args = args,
handlers = handlers,
jobQueue = queue,
prevExceptions = null,
bus = bus)?.let(::throwExceptions)
return true
}
}
internal fun executeOrAddToQueue(topic: Topic<*>,
method: Method,
args: Array<Any?>?,
handlers: Array<Any?>,
jobQueue: MessageQueue?,
prevExceptions: MutableList<Throwable>?,
bus: MessageBusImpl): MutableList<Throwable>? {
val methodHandle = MethodHandleCache.compute(method, args)
if (jobQueue == null) {
var exceptions = prevExceptions
for (handler in handlers) {
exceptions = invokeListener(methodHandle = methodHandle,
methodName = method.name,
args = args,
topic = topic,
handler = handler ?: continue,
messageDeliveryListener = bus.messageDeliveryListener,
prevExceptions = exceptions)
}
return exceptions
}
else {
jobQueue.queue.offerLast(Message(topic = topic,
method = methodHandle,
methodName = method.name,
args = args,
handlers = handlers,
bus = bus))
return prevExceptions
}
}
internal class ToParentMessagePublisher<L>(topic: Topic<L>, bus: MessageBusImpl) : MessagePublisher<L>(topic, bus), InvocationHandler {
// args not-null
override fun publish(method: Method, args: Array<Any?>?, queue: MessageQueue?): Boolean {
var exceptions: MutableList<Throwable>? = null
var parentBus = bus
var hasHandlers = false
while (true) {
// computeIfAbsent cannot be used here: https://youtrack.jetbrains.com/issue/IDEA-250464
var handlers = parentBus.subscriberCache.get(topic)
if (handlers == null) {
handlers = parentBus.computeSubscribers(topic)
val existing = parentBus.subscriberCache.putIfAbsent(topic, handlers)
if (existing != null) {
handlers = existing
}
}
if (!handlers.isEmpty()) {
hasHandlers = true
exceptions = executeOrAddToQueue(topic, method, args, handlers, queue, exceptions, bus)
}
parentBus = parentBus.parentBus ?: break
}
exceptions?.let(::throwExceptions)
return hasHandlers
}
}
/**
* For TO_DIRECT_CHILDREN broadcast direction we don't need special clean logic because cache is computed per bus, exactly as for
* NONE broadcast direction. And on publish, direct children of bus are queried to get message handlers.
*/
private fun clearSubscriberCacheOnConnectionTerminated(topicAndHandlerPairs: Array<Any>, bus: MessageBusImpl): Boolean {
var isChildClearingNeeded = false
var i = 0
while (i < topicAndHandlerPairs.size) {
val topic = topicAndHandlerPairs[i] as Topic<*>
removeDisposedHandlers(topicAndHandlerPairs, i, topic, bus)
val direction = topic.broadcastDirection
if (direction != BroadcastDirection.TO_CHILDREN) {
i += 2
continue
}
// clear parents
var parentBus = bus
while (true) {
parentBus = parentBus.parentBus ?: break
removeDisposedHandlers(topicAndHandlerPairs, i, topic, parentBus)
}
if (bus.hasChildren()) {
// clear children
isChildClearingNeeded = true
}
i += 2
}
return isChildClearingNeeded
}
private fun removeDisposedHandlers(topicAndHandlerPairs: Array<Any>, index: Int, topic: Topic<*>, bus: MessageBusImpl) {
val cachedHandlers = bus.subscriberCache.remove(topic) ?: return
val handler = topicAndHandlerPairs[index + 1]
// during immediate delivery execution of one handler can lead to dispose of some connection
// and as result other handlers may become obsolete
if (topic.isImmediateDelivery) {
var i = 0
val length = cachedHandlers.size
while (i < length) {
if (cachedHandlers[i] === handler) {
cachedHandlers[i] = null
}
i++
}
}
bus.rootBus.removeDisposedHandlers(topic, handler)
}
private fun deliverImmediately(connection: MessageBusConnectionImpl, jobs: Deque<Message>): List<Message>? {
var newJobs: MutableList<Message>? = null
// do not deliver messages as part of iteration because during delivery another messages maybe posted
val jobIterator = jobs.iterator()
while (jobIterator.hasNext()) {
val job = jobIterator.next()
var connectionHandlers: MutableList<Any>? = null
val allHandlers = job.handlers
var i = 0
val length = allHandlers.size
while (i < length) {
val handler = allHandlers[i]
if (handler != null && connection.bus === job.bus && connection.isMyHandler(job.topic, handler)) {
allHandlers[i] = null
if (connectionHandlers == null) {
connectionHandlers = mutableListOf()
}
connectionHandlers.add(handler)
}
i++
}
if (connectionHandlers == null) {
continue
}
if (allHandlers.size == connectionHandlers.size) {
jobIterator.remove()
}
val filteredJob = Message(topic = job.topic,
method = job.method,
methodName = job.methodName,
args = job.args,
handlers = connectionHandlers.toTypedArray(),
bus = job.bus)
if (newJobs == null) {
newJobs = mutableListOf()
}
newJobs.add(filteredJob)
}
return newJobs
}
private fun invokeListener(methodHandle: MethodHandle,
methodName: String,
args: Array<Any?>?,
topic: Topic<*>,
handler: Any,
messageDeliveryListener: MessageDeliveryListener?,
prevExceptions: MutableList<Throwable>?): MutableList<Throwable>? {
try {
//println("${topic.displayName} ${topic.isImmediateDelivery}: $methodName(${args.contentToString()})")
if (handler is MessageHandler) {
handler.handle(methodHandle, *(args ?: ArrayUtilRt.EMPTY_OBJECT_ARRAY))
}
else if (messageDeliveryListener == null) {
invokeMethod(handler, args, methodHandle)
}
else {
val startTime = System.nanoTime()
invokeMethod(handler, args, methodHandle)
messageDeliveryListener.messageDelivered(topic, methodName, handler, System.nanoTime() - startTime)
}
}
catch (e: AbstractMethodError) {
// do nothing for AbstractMethodError - this listener just does not implement something newly added yet
}
catch (e: Throwable) {
val exceptions = prevExceptions ?: mutableListOf()
// ProcessCanceledException is rethrown only after executing all handlers
if (e is ProcessCanceledException || e is AssertionError || e is CancellationException) {
exceptions.add(e)
}
else {
exceptions.add(RuntimeException("Cannot invoke (" +
"class=${handler::class.java.simpleName}, " +
"method=${methodName}, " +
"topic=${topic.displayName}" +
")", e))
}
return exceptions
}
return prevExceptions
}
private fun invokeMethod(handler: Any, args: Array<Any?>?, methodHandle: MethodHandle) {
if (args == null) {
methodHandle.invoke(handler)
}
else {
methodHandle.bindTo(handler).invokeExact(args)
}
}
internal fun throwExceptions(exceptions: List<Throwable>) {
if (exceptions.size == 1) {
throw exceptions[0]
}
exceptions.firstOrNull { it is ProcessCanceledException || it is CancellationException }?.let { throw it }
throw CompoundRuntimeException(exceptions)
} | apache-2.0 | 11bdb970a10c545fcc959694b04b5d67 | 33.925037 | 138 | 0.650683 | 4.806851 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/jvm-debugger/sequence/src/org/jetbrains/kotlin/idea/debugger/sequence/psi/impl/TerminatedChainBuilder.kt | 4 | 2836 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.debugger.sequence.psi.impl
import com.intellij.debugger.streams.psi.ChainTransformer
import org.jetbrains.kotlin.idea.debugger.sequence.psi.StreamCallChecker
import org.jetbrains.kotlin.idea.debugger.sequence.psi.previousCall
import org.jetbrains.kotlin.psi.KtCallExpression
import java.util.*
open class TerminatedChainBuilder(
transformer: ChainTransformer<KtCallExpression>,
private val callChecker: StreamCallChecker
) : KotlinChainBuilderBase(transformer) {
override val existenceChecker: ExistenceChecker = MyExistenceChecker()
override fun createChainsBuilder(): ChainBuilder = MyBuilderVisitor()
private inner class MyExistenceChecker : ExistenceChecker() {
override fun visitCallExpression(expression: KtCallExpression) {
if (callChecker.isTerminationCall(expression)) {
fireElementFound()
} else {
super.visitCallExpression(expression)
}
}
}
private inner class MyBuilderVisitor : ChainBuilder() {
private val myTerminationCalls = mutableSetOf<KtCallExpression>()
private val myPreviousCalls = mutableMapOf<KtCallExpression, KtCallExpression>()
override fun visitCallExpression(expression: KtCallExpression) {
super.visitCallExpression(expression)
if (!myPreviousCalls.containsKey(expression) && callChecker.isStreamCall(expression)) {
updateCallTree(expression)
}
}
private fun updateCallTree(expression: KtCallExpression) {
if (callChecker.isTerminationCall(expression)) {
myTerminationCalls.add(expression)
}
val parentCall = expression.previousCall()
if (parentCall is KtCallExpression && callChecker.isStreamCall(parentCall)) {
myPreviousCalls[expression] = parentCall
updateCallTree(parentCall)
}
}
override fun chains(): List<List<KtCallExpression>> {
val chains = ArrayList<List<KtCallExpression>>()
for (terminationCall in myTerminationCalls) {
val chain = ArrayList<KtCallExpression>()
var current: KtCallExpression? = terminationCall
while (current != null) {
if (!callChecker.isStreamCall(current)) {
break
}
chain.add(current)
current = myPreviousCalls[current]
}
chain.reverse()
chains.add(chain)
}
return chains
}
}
}
| apache-2.0 | d948d08d3f6842f7cf93589c7de981e2 | 38.388889 | 158 | 0.645275 | 5.350943 | false | false | false | false |
hanks-zyh/MaterialDesign | app/src/main/java/com/hanks/coor/FabAnimateActivity.kt | 1 | 3928 | package com.hanks.coor
import android.os.Bundle
import android.support.design.widget.FloatingActionButton
import android.support.v7.app.AppCompatActivity
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import java.util.*
/**
* Created by hanks on 2015/11/14.
*/
class FabAnimateActivity : AppCompatActivity() {
var contactList = ArrayList<ContactInfo>()
var fab: FloatingActionButton ?= null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_fabanimte)
// add data
contactList.add(ContactInfo("", "Ali Connors", "Bruch this weekend?", "I'll be in your neighborhood doing errands and all that"))
contactList.add(ContactInfo("", "Ali Connors", "Bruch this weekend?", "I'll be in your neighborhood doing errands and all that"))
contactList.add(ContactInfo("", "Ali Connors", "Bruch this weekend?", "I'll be in your neighborhood doing errands and all that"))
contactList.add(ContactInfo("", "Ali Connors", "Bruch this weekend?", "I'll be in your neighborhood doing errands and all that"))
contactList.add(ContactInfo("", "Ali Connors", "Bruch this weekend?", "I'll be in your neighborhood doing errands and all that"))
contactList.add(ContactInfo("", "Ali Connors", "Bruch this weekend?", "I'll be in your neighborhood doing errands and all that"))
contactList.add(ContactInfo("", "Ali Connors", "Bruch this weekend?", "I'll be in your neighborhood doing errands and all that"))
contactList.add(ContactInfo("", "Ali Connors", "Bruch this weekend?", "I'll be in your neighborhood doing errands and all that"))
contactList.add(ContactInfo("", "Ali Connors", "Bruch this weekend?", "I'll be in your neighborhood doing errands and all that"))
fab = findViewById(R.id.fab) as FloatingActionButton
val recyclerView = findViewById(R.id.recycler_view) as RecyclerView
recyclerView.layoutManager = LinearLayoutManager(this)
recyclerView.adapter = ContactAdapter()
recyclerView!!.addOnScrollListener(object : RecyclerScrollListener() {
override fun hide() {
hideFab()
}
override fun show() {
showFab()
}
})
}
fun showFab() {
fab?.animate()?.setDuration(300)?.translationY(0f)?.start()
}
fun hideFab() {
fab?.animate()?.setDuration(300)?.translationY(400f)?.start()
}
inner internal class ContactAdapter : RecyclerView.Adapter<ContactViewHolder>() {
override fun onBindViewHolder(holder: ContactViewHolder?, position: Int) {
val contactInfo = contactList[position]
holder?.tv_title?.text = contactInfo.name
holder?.tv_summary?.text = contactInfo.summary
holder?.tv_content?.text = contactInfo.content
}
override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): ContactViewHolder? {
val view = layoutInflater.inflate(R.layout.item_list_contactinfo, parent, false)
return ContactViewHolder(view)
}
override fun getItemCount() = contactList.size
}
inner internal class ContactViewHolder(itemView: View?) : RecyclerView.ViewHolder(itemView) {
var tv_title: TextView
var tv_summary: TextView
var tv_content: TextView
init {
tv_title = itemView?.findViewById(R.id.tv_title) as TextView
tv_summary = itemView?.findViewById(R.id.tv_summary) as TextView
tv_content = itemView?.findViewById(R.id.tv_content) as TextView
}
}
data class ContactInfo(var avatar: String, var name: String, var summary: String, var content: String) {
}
} | apache-2.0 | d3a6c9e8f2032d3caf638d2045073525 | 42.175824 | 137 | 0.674389 | 4.443439 | false | false | false | false |
dhis2/dhis2-android-sdk | core/src/main/java/org/hisp/dhis/android/core/fileresource/internal/FileResourcePostCall.kt | 1 | 9140 | /*
* Copyright (c) 2004-2022, University of Oslo
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* Neither the name of the HISP project nor the names of its contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.hisp.dhis.android.core.fileresource.internal
import android.content.Context
import android.util.Log
import android.webkit.MimeTypeMap
import dagger.Reusable
import java.io.File
import java.io.IOException
import javax.inject.Inject
import okhttp3.MediaType
import okhttp3.MultipartBody
import okhttp3.RequestBody
import org.hisp.dhis.android.core.arch.api.executors.internal.APICallExecutor
import org.hisp.dhis.android.core.arch.db.querybuilders.internal.WhereClauseBuilder
import org.hisp.dhis.android.core.arch.db.stores.internal.IdentifiableDataObjectStore
import org.hisp.dhis.android.core.arch.handlers.internal.HandlerWithTransformer
import org.hisp.dhis.android.core.arch.json.internal.ObjectMapperFactory.objectMapper
import org.hisp.dhis.android.core.common.State
import org.hisp.dhis.android.core.datavalue.DataValueTableInfo
import org.hisp.dhis.android.core.datavalue.internal.DataValueStore
import org.hisp.dhis.android.core.fileresource.FileResource
import org.hisp.dhis.android.core.maintenance.D2Error
import org.hisp.dhis.android.core.maintenance.D2ErrorCode
import org.hisp.dhis.android.core.systeminfo.internal.PingCall
import org.hisp.dhis.android.core.trackedentity.*
import org.hisp.dhis.android.core.trackedentity.internal.TrackedEntityAttributeValueStore
import org.hisp.dhis.android.core.trackedentity.internal.TrackedEntityDataValueStore
@Reusable
internal class FileResourcePostCall @Inject constructor(
private val fileResourceService: FileResourceService,
private val apiCallExecutor: APICallExecutor,
private val dataValueStore: DataValueStore,
private val trackedEntityAttributeValueStore: TrackedEntityAttributeValueStore,
private val trackedEntityDataValueStore: TrackedEntityDataValueStore,
private val fileResourceStore: IdentifiableDataObjectStore<FileResource>,
private val fileResourceHandler: HandlerWithTransformer<FileResource>,
private val pingCall: PingCall,
private val context: Context
) {
private var alreadyPinged = false
fun uploadFileResource(fileResource: FileResource, value: FileResourceValue): String? {
// Workaround for ANDROSDK-1452 (see comments restricted to Contributors).
if (!alreadyPinged) {
pingCall.getCompletable(true).blockingAwait()
alreadyPinged = true
}
val file = FileResourceUtil.getFile(fileResource)
return if (file != null) {
val filePart = getFilePart(file)
val responseBody = apiCallExecutor.executeObjectCall(fileResourceService.uploadFile(filePart))
handleResponse(responseBody.string(), fileResource, file, value)
} else {
handleMissingFile(fileResource, value)
null
}
}
private fun getFilePart(file: File): MultipartBody.Part {
val extension = MimeTypeMap.getFileExtensionFromUrl(file.path)
val type = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension) ?: "image/*"
return MultipartBody.Part
.createFormData("file", file.name, RequestBody.create(MediaType.parse(type), file))
}
private fun handleResponse(
responseBody: String,
fileResource: FileResource,
file: File,
value: FileResourceValue
): String {
try {
val downloadedFileResource = getDownloadedFileResource(responseBody)
updateValue(fileResource, downloadedFileResource.uid(), value)
val downloadedFile = FileResourceUtil.renameFile(file, downloadedFileResource.uid()!!, context)
updateFileResource(fileResource, downloadedFileResource, downloadedFile)
return downloadedFileResource.uid()!!
} catch (e: IOException) {
Log.v(FileResourcePostCall::class.java.canonicalName, e.message!!)
throw D2Error.builder()
.errorCode(D2ErrorCode.API_UNSUCCESSFUL_RESPONSE)
.errorDescription(e.message!!)
.build()
}
}
private fun handleMissingFile(fileResource: FileResource, value: FileResourceValue) {
if (fileResource.uid() != null) {
updateValue(fileResource, null, value)
fileResourceStore.deleteIfExists(fileResource.uid()!!)
}
}
@Throws(IOException::class)
private fun getDownloadedFileResource(responseBody: String): FileResource {
val fileResourceResponse = objectMapper().readValue(responseBody, FileResourceResponse::class.java)
return fileResourceResponse.response()!!.fileResource()!!
}
private fun updateValue(
fileResource: FileResource,
newUid: String?,
value: FileResourceValue
) {
val updateValueMethod = when (value) {
is FileResourceValue.DataValue -> ::updateAggregatedDataValue
is FileResourceValue.EventValue -> ::updateTrackedEntityDataValue
is FileResourceValue.AttributeValue -> ::updateTrackedEntityAttributeValue
}
updateValueMethod(fileResource, newUid, value.uid)
}
private fun updateAggregatedDataValue(fileResource: FileResource, newUid: String?, elementUid: String) {
val whereClause = WhereClauseBuilder()
.appendKeyStringValue(DataValueTableInfo.Columns.VALUE, fileResource.uid())
.appendKeyStringValue(DataValueTableInfo.Columns.DATA_ELEMENT, elementUid)
.build()
dataValueStore.selectOneWhere(whereClause)?.let { dataValue ->
val newValue =
if (newUid == null) dataValue.toBuilder().deleted(true).build()
else dataValue.toBuilder().value(newUid).build()
dataValueStore.updateWhere(newValue)
}
}
private fun updateTrackedEntityAttributeValue(
fileResource: FileResource,
newUid: String?,
elementUid: String
): Boolean {
val whereClause = WhereClauseBuilder()
.appendKeyStringValue(TrackedEntityAttributeValueTableInfo.Columns.VALUE, fileResource.uid())
.appendKeyStringValue(TrackedEntityAttributeValueTableInfo.Columns.TRACKED_ENTITY_ATTRIBUTE, elementUid)
.build()
return trackedEntityAttributeValueStore.selectOneWhere(whereClause)?.let { attributeValue ->
trackedEntityAttributeValueStore.updateWhere(
attributeValue.toBuilder()
.value(newUid)
.build()
)
true
} ?: false
}
private fun updateTrackedEntityDataValue(fileResource: FileResource, newUid: String?, elementUid: String) {
val whereClause = WhereClauseBuilder()
.appendKeyStringValue(TrackedEntityDataValueTableInfo.Columns.VALUE, fileResource.uid())
.appendKeyStringValue(TrackedEntityDataValueTableInfo.Columns.DATA_ELEMENT, elementUid)
.build()
trackedEntityDataValueStore.selectOneWhere(whereClause)?.let { dataValue ->
trackedEntityDataValueStore.updateWhere(
dataValue.toBuilder()
.value(newUid)
.build()
)
}
}
private fun updateFileResource(
fileResource: FileResource,
downloadedFileResource: FileResource,
file: File
) {
fileResourceStore.delete(fileResource.uid()!!)
fileResourceHandler.handle(
downloadedFileResource.toBuilder()
.syncState(State.UPLOADING)
.path(file.absolutePath)
.build()
)
}
}
| bsd-3-clause | 46cd67a812eeebbcf12f443a667ef762 | 42.317536 | 116 | 0.712363 | 5.123318 | false | false | false | false |
McMoonLakeDev/MoonLake | API/src/main/kotlin/com/mcmoonlake/api/security/Security.kt | 1 | 4515 | /*
* Copyright (C) 2016-Present The MoonLake ([email protected])
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
@file:JvmName("Security")
package com.mcmoonlake.api.security
import java.nio.charset.Charset
import java.security.MessageDigest
import java.security.NoSuchAlgorithmException
import java.util.*
/**
* Base64 Encoder & Decoder
* @see [java.util.Base64]
*/
fun base64E(src: ByteArray): ByteArray
= Base64.getEncoder().encode(src)
fun base64EString(src: ByteArray): String
= Base64.getEncoder().encodeToString(src)
@JvmOverloads
fun base64EString(src: String, charset: Charset = Charsets.ISO_8859_1): String
= Base64.getEncoder().encodeToString(src.toByteArray(charset))
fun base64D(src: ByteArray): ByteArray
= Base64.getDecoder().decode(src)
@JvmOverloads
fun base64DString(src: String, charset: Charset = Charsets.ISO_8859_1): ByteArray
= Base64.getDecoder().decode(src.toByteArray(charset))
/**
* Message Digest
* @see [java.security.MessageDigest]
*/
internal object Digests {
@JvmStatic
@JvmName("getDigest")
@Throws(IllegalArgumentException::class)
fun getDigest(type: String): MessageDigest = try {
MessageDigest.getInstance(type)
} catch (e: NoSuchAlgorithmException) {
throw IllegalArgumentException(e)
}
}
val md5Digest: MessageDigest
get() = Digests.getDigest("MD5")
val sha1Digest: MessageDigest
get() = Digests.getDigest("SHA-1")
val sha256Digest: MessageDigest
get() = Digests.getDigest("SHA-256")
val sha384Digest: MessageDigest
get() = Digests.getDigest("SHA-384")
val sha512Digest: MessageDigest
get() = Digests.getDigest("SHA-512")
fun md5Byte(src: ByteArray): ByteArray
= md5Digest.digest(src)
fun md5(src: ByteArray): String
= Hex.encodeHexString(md5Byte(src))
@JvmOverloads
fun md5(src: String, charset: Charset = Charsets.ISO_8859_1): String
= md5(src.toByteArray(charset))
fun sha1Byte(src: ByteArray): ByteArray
= sha1Digest.digest(src)
fun sha1(src: ByteArray): String
= Hex.encodeHexString(sha1Byte(src))
@JvmOverloads
fun sha1(src: String, charset: Charset = Charsets.ISO_8859_1): String
= sha1(src.toByteArray(charset))
fun sha256Byte(src: ByteArray): ByteArray
= sha256Digest.digest(src)
fun sha256(src: ByteArray): String
= Hex.encodeHexString(sha256Byte(src))
@JvmOverloads
fun sha256(src: String, charset: Charset = Charsets.ISO_8859_1): String
= sha256(src.toByteArray(charset))
fun sha384Byte(src: ByteArray): ByteArray
= sha384Digest.digest(src)
fun sha384(src: ByteArray): String
= Hex.encodeHexString(sha384Byte(src))
@JvmOverloads
fun sha384(src: String, charset: Charset = Charsets.ISO_8859_1): String
= sha384(src.toByteArray(charset))
fun sha512Byte(src: ByteArray): ByteArray
= sha512Digest.digest(src)
fun sha512(src: ByteArray): String
= Hex.encodeHexString(sha512Byte(src))
@JvmOverloads
fun sha512(src: String, charset: Charset = Charsets.ISO_8859_1): String
= sha512(src.toByteArray(charset))
fun hexByte(src: ByteArray): CharArray
= Hex.encodeHex(src)
/**
* Hex Util
*/
internal object Hex {
@JvmStatic
private val TABLE = charArrayOf('0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F')
@JvmStatic
@JvmName("encodeHex")
fun encodeHex(src: ByteArray): CharArray {
val length = src.size
val buffer = CharArray(length shl 1)
var index = 0; var k = 0
while(index < length) {
buffer[k++] = TABLE[(240 and src[index].toInt()).ushr(4)]
buffer[k++] = TABLE[15 and src[index].toInt()]
++index
}
return buffer
}
@JvmStatic
@JvmName("encodeHexString")
fun encodeHexString(src: ByteArray): String
= String(encodeHex(src))
}
| gpl-3.0 | 05ad9d40f026ec115771c45a9ed3e945 | 27.043478 | 115 | 0.683278 | 3.664773 | false | false | false | false |
McMoonLakeDev/MoonLake | API/src/main/kotlin/com/mcmoonlake/api/wrapper/ServerInfo.kt | 1 | 7831 | /*
* Copyright (C) 2016-Present The MoonLake ([email protected])
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.mcmoonlake.api.wrapper
import com.google.gson.Gson
import com.google.gson.JsonArray
import com.google.gson.JsonObject
import com.google.gson.JsonParser
import com.mcmoonlake.api.chat.ChatComponent
import com.mcmoonlake.api.chat.ChatComponentText
import com.mcmoonlake.api.chat.ChatSerializer
import io.netty.buffer.ByteBufInputStream
import io.netty.buffer.ByteBufOutputStream
import io.netty.buffer.Unpooled
import io.netty.handler.codec.base64.Base64
import java.awt.image.BufferedImage
import java.io.IOException
import java.util.*
import javax.imageio.ImageIO
data class ServerInfo(
val version: Version,
val players: Players,
val description: ChatComponent,
val modInfo: ModInfo?,
val favicon: BufferedImage?) {
fun toJson(): String
= Companion.toJson(this)
data class Version(val name: String, val protocol: Int)
data class PlayerSample(val name: String, val id: UUID)
data class Players(val max: Int, val online: Int, val sample: List<PlayerSample>)
data class ModInfo(val type: String, val modList: List<Mod>) {
companion object {
@JvmField
val SAMPLE = ModInfo("FML", listOf(
// Forge Mod List
Mod("mcp", "9.19"),
Mod("FML", "8.0.99.99"),
Mod("Forge", "11.15.1.1722"),
// Other Mod List
Mod("rpcraft", "2.0")
))
}
}
companion object {
@JvmField
val SAMPLE = ServerInfo(Version("1.8.9", 47), Players(20, 0, emptyList()), ChatComponentText("A Minecraft Server"), null, null)
@JvmStatic
@JvmName("toJson")
fun toJson(serverInfo: ServerInfo): String {
val jsonObject = JsonObject()
val jsonVersion = JsonObject()
val jsonPlayers = JsonObject()
jsonVersion.addProperty("name", serverInfo.version.name)
jsonVersion.addProperty("protocol", serverInfo.version.protocol)
jsonPlayers.addProperty("max", serverInfo.players.max)
jsonPlayers.addProperty("online", serverInfo.players.online)
if(serverInfo.players.sample.isNotEmpty()) {
val jsonSamples = JsonArray()
serverInfo.players.sample.forEach {
val jsonSample = JsonObject()
jsonSample.addProperty("id", it.id.toString())
jsonSample.addProperty("name", it.name)
jsonSamples.add(jsonSample)
}
jsonPlayers.add("sample", jsonSamples)
}
jsonObject.add("version", jsonVersion)
jsonObject.add("players", jsonPlayers)
jsonObject.add("description", JsonParser().parse(serverInfo.description.toJson()))
if(serverInfo.modInfo != null) {
val jsonModInfo = JsonObject()
val jsonModList = JsonArray()
serverInfo.modInfo.modList.forEach {
val jsonMod = JsonObject()
jsonMod.addProperty("modid", it.modid)
jsonMod.addProperty("version", it.version)
jsonModList.add(jsonMod)
}
jsonModInfo.addProperty("type", serverInfo.modInfo.type)
jsonModInfo.add("modList", jsonModList)
jsonObject.add("modinfo", jsonModInfo)
}
if(serverInfo.favicon != null)
jsonObject.addProperty("favicon", faviconToString(serverInfo.favicon))
return jsonObject.toString()
}
@JvmStatic
@JvmName("fromJson")
fun fromJson(serverInfo: String): ServerInfo {
val jsonObject = Gson().fromJson<JsonObject>(serverInfo, JsonObject::class.java)
val jsonVersion = jsonObject["version"].asJsonObject
val jsonPlayers = jsonObject["players"].asJsonObject
val version = Version(jsonVersion["name"].asString, jsonVersion["protocol"].asInt)
val sample = ArrayList<PlayerSample>()
if(jsonPlayers.has("sample")) {
val jsonSamples = jsonPlayers["sample"].asJsonArray
jsonSamples.forEach {
val jsonSample = it.asJsonObject
sample.add(PlayerSample(jsonSample["name"].asString, UUID.fromString(jsonSample["id"].asString)))
}
}
val players = Players(jsonPlayers["max"].asInt, jsonPlayers["online"].asInt, sample)
val description = ChatSerializer.fromJsonLenient(jsonObject["description"].toString())
var modInfo: ModInfo? = null
var favicon: BufferedImage? = null
if(jsonObject.has("modinfo")) {
val jsonModInfo = jsonObject["modinfo"].asJsonObject
val modList = ArrayList<Mod>()
if(jsonModInfo.has("modList")) {
val jsonModList = jsonModInfo["modList"].asJsonArray
jsonModList.forEach {
val jsonMod = it.asJsonObject
modList.add(Mod(jsonMod["modid"].asString, jsonMod["version"].asString))
}
}
modInfo = ModInfo(jsonModInfo["type"]?.asString ?: "FML", modList)
}
if(jsonObject.has("favicon"))
favicon = faviconFromString(jsonObject["favicon"].asString)
return ServerInfo(version, players, description, modInfo, favicon)
}
@JvmStatic
@JvmName("faviconToString")
@Throws(IllegalArgumentException::class, IOException::class)
fun faviconToString(favicon: BufferedImage): String {
if(favicon.width != 64 || favicon.height != 64)
throw IllegalArgumentException("图标图片不是 64x64 像素大小.")
val buffer = Unpooled.buffer()
try {
ImageIO.write(favicon, "PNG", ByteBufOutputStream(buffer))
val encoded = Base64.encode(buffer)
return "data:image/png;base64,${encoded.toString(Charsets.UTF_8)}"
} finally {
buffer.release()
}
}
@JvmStatic
@JvmName("faviconFromString")
@Throws(IllegalArgumentException::class, IOException::class)
fun faviconFromString(faviconData: String): BufferedImage {
val data = if(faviconData.startsWith("data:image/png;base64,", true)) faviconData.substring("data:image/png;base64,".length) else faviconData
val buffer = Unpooled.wrappedBuffer(data.toByteArray(Charsets.UTF_8))
try {
val favicon = ImageIO.read(ByteBufInputStream(Base64.decode(buffer))) ?: null
if(favicon == null || (favicon.width != 64 || favicon.height != 64))
throw IllegalArgumentException("图标图片不是 64x64 像素大小.")
return favicon
} finally {
buffer.release()
}
}
}
}
| gpl-3.0 | 8c3a25b0d7b258f5198155d821235ff0 | 43.016949 | 153 | 0.600693 | 4.730419 | false | false | false | false |
imknown/ImkGithub | ZMain/ImkGithubApp/src/main/java/net/imknown/imkgithub/web/RetrofitFactory.kt | 1 | 2253 | package net.imknown.imkgithub.web
import com.facebook.stetho.okhttp3.StethoInterceptor
import com.google.gson.Gson
import com.readystatesoftware.chuck.ChuckInterceptor
import io.reactivex.ObservableTransformer
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import net.imknown.imkgithub.global.MyApplication
import net.imknown.imkgithub.web.converter.StringConverterFactory
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory
import retrofit2.converter.gson.GsonConverterFactory
import retrofit2.create
import java.util.concurrent.TimeUnit
import kotlin.reflect.KClass
object RetrofitFactory {
const val URL_API_GITHUB = "https://api.github.com/"
inline fun <reified T> create(converterFactoryType: KClass<*> = Gson::class) =
createRetrofit(converterFactoryType).create<T>()
fun createRetrofit(converterFactoryType: Any): Retrofit = Retrofit.Builder()
.baseUrl(URL_API_GITHUB)
.client(createOkHttpClient())
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.addConverterFactory(
when (converterFactoryType) {
Gson::class -> GsonConverterFactory.create()
String::class -> StringConverterFactory.create()
else -> throw IllegalArgumentException("ConverterFactory type is not supported now.")
}
)
.build()
private fun createOkHttpClient() = OkHttpClient.Builder()
.addInterceptor(HttpLoggingInterceptor().apply {
level = HttpLoggingInterceptor.Level.BODY
})
.addInterceptor(ChuckInterceptor(MyApplication.application))
.addNetworkInterceptor(StethoInterceptor())
.connectTimeout(15, TimeUnit.SECONDS)
.readTimeout(20, TimeUnit.SECONDS)
.writeTimeout(20, TimeUnit.SECONDS)
.retryOnConnectionFailure(true)
.build()
fun <T> ioToMain(): ObservableTransformer<T, T> = ObservableTransformer { upstream ->
upstream.subscribeOn(Schedulers.io())
.unsubscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
}
}
| apache-2.0 | f37c80ebd80022cd8abe3fb0475fc610 | 39.232143 | 101 | 0.730581 | 4.929978 | false | false | false | false |
iSoron/uhabits | uhabits-android/src/main/java/org/isoron/uhabits/widgets/StreakWidget.kt | 1 | 2271 | /*
* 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.widgets
import android.app.PendingIntent
import android.content.Context
import android.view.View
import android.view.ViewGroup.LayoutParams
import android.view.ViewGroup.LayoutParams.MATCH_PARENT
import org.isoron.platform.gui.toInt
import org.isoron.uhabits.activities.common.views.StreakChart
import org.isoron.uhabits.core.models.Habit
import org.isoron.uhabits.core.ui.views.WidgetTheme
import org.isoron.uhabits.widgets.views.GraphWidgetView
class StreakWidget(
context: Context,
id: Int,
private val habit: Habit,
stacked: Boolean = false,
) : BaseWidget(context, id, stacked) {
override val defaultHeight: Int = 200
override val defaultWidth: Int = 200
override fun getOnClickPendingIntent(context: Context): PendingIntent =
pendingIntentFactory.showHabit(habit)
override fun refreshData(view: View) {
val widgetView = view as GraphWidgetView
widgetView.setBackgroundAlpha(preferedBackgroundAlpha)
if (preferedBackgroundAlpha >= 255) widgetView.setShadowAlpha(0x4f)
(widgetView.dataView as StreakChart).apply {
setColor(WidgetTheme().color(habit.color).toInt())
setStreaks(habit.streaks.getBest(maxStreakCount))
}
}
override fun buildView(): View {
return GraphWidgetView(context, StreakChart(context)).apply {
setTitle(habit.name)
layoutParams = LayoutParams(MATCH_PARENT, MATCH_PARENT)
}
}
}
| gpl-3.0 | b1198a374cce6d05742afc245fb23390 | 36.213115 | 78 | 0.735242 | 4.219331 | false | false | false | false |
dahlstrom-g/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/RedundantLetInspection.kt | 1 | 11982 | // 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.CleanupLocalInspectionTool
import com.intellij.codeInspection.ProblemHighlightType
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiElement
import org.jetbrains.kotlin.descriptors.CallableMemberDescriptor
import org.jetbrains.kotlin.descriptors.impl.ValueParameterDescriptorImpl
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.base.psi.replaced
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.core.util.isMultiLine
import org.jetbrains.kotlin.idea.intentions.*
import org.jetbrains.kotlin.idea.util.textRangeIn
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.*
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.bindingContextUtil.getReferenceTargets
import org.jetbrains.kotlin.resolve.calls.model.VariableAsFunctionResolvedCall
import org.jetbrains.kotlin.resolve.calls.util.getResolvedCall
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
import org.jetbrains.kotlin.types.isNullable
abstract class RedundantLetInspection : AbstractApplicabilityBasedInspection<KtCallExpression>(
KtCallExpression::class.java
) {
override fun inspectionText(element: KtCallExpression) = KotlinBundle.message("redundant.let.call.could.be.removed")
final override fun inspectionHighlightRangeInElement(element: KtCallExpression) = element.calleeExpression?.textRangeIn(element)
final override val defaultFixText get() = KotlinBundle.message("remove.let.call")
final override fun isApplicable(element: KtCallExpression): Boolean {
if (!element.isLetMethodCall()) return false
val lambdaExpression = element.lambdaArguments.firstOrNull()?.getLambdaExpression() ?: return false
val parameterName = lambdaExpression.getParameterName() ?: return false
return isApplicable(
element,
lambdaExpression.bodyExpression?.children?.singleOrNull() ?: return false,
lambdaExpression,
parameterName
)
}
protected abstract fun isApplicable(
element: KtCallExpression,
bodyExpression: PsiElement,
lambdaExpression: KtLambdaExpression,
parameterName: String
): Boolean
final override fun applyTo(element: KtCallExpression, project: Project, editor: Editor?) {
val lambdaExpression = element.lambdaArguments.firstOrNull()?.getLambdaExpression() ?: return
when (val bodyExpression = lambdaExpression.bodyExpression?.children?.singleOrNull() ?: return) {
is KtDotQualifiedExpression -> bodyExpression.applyTo(element)
is KtBinaryExpression -> bodyExpression.applyTo(element)
is KtCallExpression -> bodyExpression.applyTo(element, lambdaExpression.functionLiteral, editor)
is KtSimpleNameExpression -> deleteCall(element)
}
}
}
class SimpleRedundantLetInspection : RedundantLetInspection(), CleanupLocalInspectionTool {
override fun isApplicable(
element: KtCallExpression,
bodyExpression: PsiElement,
lambdaExpression: KtLambdaExpression,
parameterName: String
): Boolean = when (bodyExpression) {
is KtDotQualifiedExpression -> bodyExpression.isApplicable(parameterName)
is KtSimpleNameExpression -> bodyExpression.text == parameterName
else -> false
}
}
class ComplexRedundantLetInspection : RedundantLetInspection(), CleanupLocalInspectionTool {
override fun isApplicable(
element: KtCallExpression,
bodyExpression: PsiElement,
lambdaExpression: KtLambdaExpression,
parameterName: String
): Boolean = when (bodyExpression) {
is KtBinaryExpression ->
element.parent !is KtSafeQualifiedExpression && bodyExpression.isApplicable(parameterName)
is KtCallExpression ->
if (element.parent is KtSafeQualifiedExpression) {
false
} else {
val references = lambdaExpression.functionLiteral.valueParameterReferences(bodyExpression)
val destructuringDeclaration = lambdaExpression.functionLiteral.valueParameters.firstOrNull()?.destructuringDeclaration
references.isEmpty() || (references.singleOrNull()?.takeIf { expression ->
expression.parents.takeWhile { it != lambdaExpression.functionLiteral }.find { it is KtFunction } == null
} != null && destructuringDeclaration == null)
}
else ->
false
}
override fun inspectionHighlightType(element: KtCallExpression): ProblemHighlightType = if (isSingleLine(element))
ProblemHighlightType.GENERIC_ERROR_OR_WARNING
else
ProblemHighlightType.INFORMATION
}
private fun KtBinaryExpression.applyTo(element: KtCallExpression) {
val left = left ?: return
val factory = KtPsiFactory(element.project)
when (val parent = element.parent) {
is KtQualifiedExpression -> {
val receiver = parent.receiverExpression
val newLeft = when (left) {
is KtDotQualifiedExpression -> left.replaceFirstReceiver(factory, receiver, parent is KtSafeQualifiedExpression)
else -> receiver
}
val newExpression = factory.createExpressionByPattern("$0 $1 $2", newLeft, operationReference, right!!)
parent.replace(newExpression)
}
else -> {
val newLeft = when (left) {
is KtDotQualifiedExpression -> left.deleteFirstReceiver()
else -> factory.createThisExpression()
}
val newExpression = factory.createExpressionByPattern("$0 $1 $2", newLeft, operationReference, right!!)
element.replace(newExpression)
}
}
}
private fun KtDotQualifiedExpression.applyTo(element: KtCallExpression) {
when (val parent = element.parent) {
is KtQualifiedExpression -> {
val factory = KtPsiFactory(element.project)
val receiver = parent.receiverExpression
parent.replace(replaceFirstReceiver(factory, receiver, parent is KtSafeQualifiedExpression))
}
else -> {
element.replace(deleteFirstReceiver())
}
}
}
private fun deleteCall(element: KtCallExpression) {
val parent = element.parent as? KtQualifiedExpression
if (parent != null) {
val replacement = parent.selectorExpression?.takeIf { it != element } ?: parent.receiverExpression
parent.replace(replacement)
} else {
element.delete()
}
}
private fun KtCallExpression.applyTo(element: KtCallExpression, functionLiteral: KtFunctionLiteral, editor: Editor?) {
val parent = element.parent as? KtQualifiedExpression
val reference = functionLiteral.valueParameterReferences(this).firstOrNull()
val replaced = if (parent != null) {
reference?.replace(parent.receiverExpression)
parent.replaced(this)
} else {
reference?.replace(KtPsiFactory(this).createThisExpression())
element.replaced(this)
}
editor?.caretModel?.moveToOffset(replaced.startOffset)
}
private fun KtBinaryExpression.isApplicable(parameterName: String, isTopLevel: Boolean = true): Boolean {
val left = left ?: return false
if (isTopLevel) {
when (left) {
is KtNameReferenceExpression -> if (left.text != parameterName) return false
is KtDotQualifiedExpression -> if (!left.isApplicable(parameterName)) return false
else -> return false
}
} else {
if (!left.isApplicable(parameterName)) return false
}
val right = right ?: return false
return right.isApplicable(parameterName)
}
private fun KtExpression.isApplicable(parameterName: String): Boolean = when (this) {
is KtNameReferenceExpression -> text != parameterName
is KtDotQualifiedExpression -> !hasLambdaExpression() && !nameUsed(parameterName)
is KtBinaryExpression -> isApplicable(parameterName, isTopLevel = false)
is KtCallExpression -> isApplicable(parameterName)
is KtConstantExpression -> true
else -> false
}
private fun KtCallExpression.isApplicable(parameterName: String): Boolean = valueArguments.all {
val argumentExpression = it.getArgumentExpression() ?: return@all false
argumentExpression.isApplicable(parameterName)
}
private fun KtDotQualifiedExpression.isApplicable(parameterName: String): Boolean {
val context by lazy { analyze(BodyResolveMode.PARTIAL) }
return !hasLambdaExpression() && getLeftMostReceiverExpression().let { receiver ->
receiver is KtNameReferenceExpression &&
receiver.getReferencedName() == parameterName &&
!nameUsed(parameterName, except = receiver)
} && callExpression?.getResolvedCall(context) !is VariableAsFunctionResolvedCall && !hasNullableReceiverExtensionCall(context)
}
private fun KtDotQualifiedExpression.hasNullableReceiverExtensionCall(context: BindingContext): Boolean {
val descriptor = selectorExpression?.getResolvedCall(context)?.resultingDescriptor as? CallableMemberDescriptor ?: return false
if (descriptor.extensionReceiverParameter?.type?.isNullable() == true) return true
return (KtPsiUtil.deparenthesize(receiverExpression) as? KtDotQualifiedExpression)?.hasNullableReceiverExtensionCall(context) == true
}
private fun KtDotQualifiedExpression.hasLambdaExpression() = selectorExpression?.anyDescendantOfType<KtLambdaExpression>() ?: false
private fun KtCallExpression.isLetMethodCall() = calleeExpression?.text == "let" && isMethodCall("kotlin.let")
private fun KtLambdaExpression.getParameterName(): String? {
val parameters = valueParameters
if (parameters.size > 1) return null
return if (parameters.size == 1) parameters[0].text else "it"
}
private fun KtExpression.nameUsed(name: String, except: KtNameReferenceExpression? = null): Boolean =
anyDescendantOfType<KtNameReferenceExpression> { it != except && it.getReferencedName() == name }
private fun KtFunctionLiteral.valueParameterReferences(callExpression: KtCallExpression): List<KtNameReferenceExpression> {
val context = analyze(BodyResolveMode.PARTIAL)
val parameterDescriptor = context[BindingContext.FUNCTION, this]?.valueParameters?.singleOrNull() ?: return emptyList()
val variableDescriptorByName = if (parameterDescriptor is ValueParameterDescriptorImpl.WithDestructuringDeclaration)
parameterDescriptor.destructuringVariables.associateBy { it.name }
else
mapOf(parameterDescriptor.name to parameterDescriptor)
val callee = (callExpression.calleeExpression as? KtNameReferenceExpression)?.let {
val descriptor = variableDescriptorByName[it.getReferencedNameAsName()]
if (descriptor != null && it.getReferenceTargets(context).singleOrNull() == descriptor) listOf(it) else null
} ?: emptyList()
return callee + callExpression.valueArguments.flatMap { arg ->
arg.collectDescendantsOfType<KtNameReferenceExpression>().filter {
val descriptor = variableDescriptorByName[it.getReferencedNameAsName()]
descriptor != null && it.getResolvedCall(context)?.resultingDescriptor == descriptor
}
}
}
private fun isSingleLine(element: KtCallExpression): Boolean {
val qualifiedExpression = element.getQualifiedExpressionForSelector() ?: return true
var receiver = qualifiedExpression.receiverExpression
if (receiver.isMultiLine()) return false
var count = 1
while (true) {
if (count > 2) return false
receiver = (receiver as? KtQualifiedExpression)?.receiverExpression ?: break
count++
}
return true
}
| apache-2.0 | 5970de94c866a33dbb0a0cb6978bdacd | 45.44186 | 137 | 0.727758 | 5.694867 | false | false | false | false |
dahlstrom-g/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/createCallable/CreateCallableMemberFromUsageFactory.kt | 5 | 2824 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.quickfix.createFromUsage.createCallable
import com.intellij.codeInsight.intention.IntentionAction
import com.intellij.psi.SmartPsiElementPointer
import org.jetbrains.kotlin.diagnostics.Diagnostic
import org.jetbrains.kotlin.idea.quickfix.IntentionActionPriority
import org.jetbrains.kotlin.idea.quickfix.KotlinIntentionActionFactoryWithDelegate
import org.jetbrains.kotlin.idea.quickfix.QuickFixWithDelegateFactory
import org.jetbrains.kotlin.idea.quickfix.createFromUsage.callableBuilder.CallableInfo
import org.jetbrains.kotlin.idea.quickfix.createFromUsage.createVariable.CreateParameterFromUsageFix
import org.jetbrains.kotlin.psi.KtElement
abstract class CreateCallableMemberFromUsageFactory<E : KtElement>(
private val extensionsSupported: Boolean = true
) : KotlinIntentionActionFactoryWithDelegate<E, List<CallableInfo>>() {
private fun newCallableQuickFix(
originalElementPointer: SmartPsiElementPointer<E>,
priority: IntentionActionPriority,
quickFixFactory: (E) -> IntentionAction?
): QuickFixWithDelegateFactory = QuickFixWithDelegateFactory(priority) {
originalElementPointer.element?.let { element -> quickFixFactory(element)}
}
protected open fun createCallableInfo(element: E, diagnostic: Diagnostic): CallableInfo? = null
override fun extractFixData(element: E, diagnostic: Diagnostic): List<CallableInfo> =
listOfNotNull(createCallableInfo(element, diagnostic))
override fun createFixes(
originalElementPointer: SmartPsiElementPointer<E>,
diagnostic: Diagnostic,
quickFixDataFactory: (E) -> List<CallableInfo>?
): List<QuickFixWithDelegateFactory> {
val fixes = ArrayList<QuickFixWithDelegateFactory>(3)
newCallableQuickFix(originalElementPointer, IntentionActionPriority.NORMAL) { element ->
CreateCallableFromUsageFix(element, quickFixDataFactory)
}.let { fixes.add(it) }
newCallableQuickFix(originalElementPointer, IntentionActionPriority.NORMAL) { element->
CreateParameterFromUsageFix.createFixForPrimaryConstructorPropertyParameter(element, quickFixDataFactory)
}.let { fixes.add(it) }
if (extensionsSupported) {
newCallableQuickFix(originalElementPointer, IntentionActionPriority.LOW) { element ->
CreateExtensionCallableFromUsageFix(element) { e ->
quickFixDataFactory(e)?.takeUnless { callableInfos ->
callableInfos.any { it.isAbstract }
}
}
}.let { fixes.add(it) }
}
return fixes
}
} | apache-2.0 | bb75b3156e23caeebc1bce85d44bad8b | 46.083333 | 158 | 0.745751 | 5.537255 | false | false | false | false |
pflammertsma/cryptogram | app/src/main/java/com/pixplicity/cryptogram/utils/ThemeUtils.kt | 1 | 1245 | package com.pixplicity.cryptogram.utils
import android.content.Context
import android.graphics.ColorMatrixColorFilter
import android.util.TypedValue
import android.widget.Button
import android.widget.ImageView
import androidx.annotation.AttrRes
import androidx.annotation.ColorInt
/**
* Color matrix that flips the components (`-1.0f * c + 255 = 255 - c`)
* and keeps the alpha intact.
*/
private val NEGATIVE = ColorMatrixColorFilter(
floatArrayOf(
-1f, 0f, 0f, 0f, 255f, // red
0f, -1f, 0f, 0f, 255f, // green
0f, 0f, -1f, 0f, 255f, // blue
0f, 0f, 0f, 1f, 0f // alpha
)
)
fun Button.invertedTheme() {
val drawables = compoundDrawables
drawables.forEach {
if (it != null) {
it.colorFilter = NEGATIVE
}
}
setCompoundDrawables(drawables[0], drawables[1], drawables[2], drawables[3])
}
fun ImageView.invertedTheme() {
drawable.colorFilter = NEGATIVE
}
@ColorInt
fun Context.getColorFromAttr(
@AttrRes attrColor: Int,
typedValue: TypedValue = TypedValue(),
resolveRefs: Boolean = true
): Int {
theme.resolveAttribute(attrColor, typedValue, resolveRefs)
return typedValue.data
}
| mit | 5750367adb14b9e70b0a9be36c90ebf8 | 26.065217 | 80 | 0.655422 | 3.902821 | false | false | false | false |
awsdocs/aws-doc-sdk-examples | kotlin/services/cloudformation/src/main/kotlin/com/kotlin/cloudformation/GetTemplate.kt | 1 | 1474 | // snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.]
// snippet-sourcedescription:[GetTemplate.kt demonstrates how to retrieve a template.]
// snippet-keyword:[AWS SDK for Kotlin]
// snippet-service:[AWS CloudFormation]
/*
Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
SPDX-License-Identifier: Apache-2.0
*/
package com.kotlin.cloudformation
// snippet-start:[cf.kotlin._template.import]
import aws.sdk.kotlin.services.cloudformation.CloudFormationClient
import aws.sdk.kotlin.services.cloudformation.model.GetTemplateRequest
import kotlin.system.exitProcess
// snippet-end:[cf.kotlin._template.import]
suspend fun main(args: Array<String>) {
val usage = """
Usage:
<stackName>
Where:
stackName - The name of the AWS CloudFormation stack.
"""
if (args.size != 1) {
println(usage)
exitProcess(1)
}
val stackName = args[0]
getSpecificTemplate(stackName)
}
// snippet-start:[cf.kotlin._template.main]
suspend fun getSpecificTemplate(stackNameVal: String) {
val request = GetTemplateRequest {
stackName = stackNameVal
}
CloudFormationClient { region = "us-east-1" }.use { cfClient ->
val response = cfClient.getTemplate(request)
val body = response.templateBody
println(body)
}
}
// snippet-end:[cf.kotlin._template.main]
| apache-2.0 | ac7de5f8fc8ac3e3aa843f417e8c4915 | 26.901961 | 89 | 0.667571 | 4.049451 | false | false | false | false |
PaulWoitaschek/MaterialAudiobookPlayer | app/src/test/java/de/ph1b/audiobook/ChapterFactory.kt | 1 | 631 | package de.ph1b.audiobook
import androidx.collection.SparseArrayCompat
import de.ph1b.audiobook.common.sparseArray.emptySparseArray
import de.ph1b.audiobook.data.Chapter
import java.io.File
import java.util.UUID
internal object ChapterFactory {
fun create(
file: String = "First.mp3",
parent: String = "/root/",
duration: Int = 10000,
lastModified: Long = 12345L,
bookId: UUID,
marks: SparseArrayCompat<String> = emptySparseArray()
) = Chapter(
file = File(parent, file),
name = file,
duration = duration,
fileLastModified = lastModified,
marks = marks,
bookId = bookId
)
}
| lgpl-3.0 | 737485a8524e3dac969fd618abce5d28 | 23.269231 | 60 | 0.70523 | 3.824242 | false | false | false | false |
encircled/Joiner | joiner-kotlin-reactive/src/main/java/cz/encircled/joiner/kotlin/reactive/KtReactiveJoiner.kt | 1 | 835 | package cz.encircled.joiner.kotlin.reactive
import cz.encircled.joiner.query.JoinerQuery
import cz.encircled.joiner.reactive.GenericHibernateReactiveJoiner
import cz.encircled.joiner.reactive.ReactorExtension.getExactlyOne
import kotlinx.coroutines.future.await
import javax.persistence.EntityManagerFactory
class KtReactiveJoiner(emf: EntityManagerFactory) : GenericHibernateReactiveJoiner(emf) {
suspend fun <F, R> find(query: JoinerQuery<F, R>): List<R> = doFind(query).await()
suspend fun <F, R> findOne(query: JoinerQuery<F, R>): R = doFind(query).await().getExactlyOne()
suspend fun <E> persist(entity: E): E = doPersist(entity).await()
suspend fun <E> persist(entities: List<E>): List<E> = doPersistMultiple(entities).await()
suspend fun <E : Any> remove(entity: E): Void = doRemove(entity).await()
} | apache-2.0 | d1e78d19c80d6c229947118dd1d7bf13 | 38.809524 | 99 | 0.760479 | 3.493724 | false | false | false | false |
google/intellij-community | plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/uast/GroovyUastPlugin.kt | 5 | 6787 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.plugins.groovy.lang.psi.uast
import com.intellij.lang.Language
import com.intellij.psi.*
import com.intellij.psi.impl.source.tree.LeafPsiElement
import com.intellij.psi.util.parents
import org.jetbrains.annotations.NonNls
import org.jetbrains.plugins.groovy.GroovyLanguage
import org.jetbrains.plugins.groovy.lang.lexer.GroovyTokenTypes
import org.jetbrains.plugins.groovy.lang.psi.GrQualifiedReference
import org.jetbrains.plugins.groovy.lang.psi.GroovyFile
import org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElement
import org.jetbrains.plugins.groovy.lang.psi.api.auxiliary.modifiers.annotation.GrAnnotation
import org.jetbrains.plugins.groovy.lang.psi.api.auxiliary.modifiers.annotation.GrAnnotationNameValuePair
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.literals.GrLiteral
import org.jetbrains.plugins.groovy.lang.psi.api.statements.params.GrParameter
import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.GrTypeDefinition
import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrMethod
import org.jetbrains.uast.*
import org.jetbrains.uast.expressions.UInjectionHost
import org.jetbrains.uast.util.ClassSet
import org.jetbrains.uast.util.classSetOf
/**
* This is a very limited implementation of UastPlugin for Groovy,
* provided only to make Groovy play with UAST-based reference contributors and spring class annotators
*/
class GroovyUastPlugin : UastLanguagePlugin {
override fun convertElement(element: PsiElement, parent: UElement?, requiredType: Class<out UElement>?): UElement? =
convertElementWithParent(element, { parent }, requiredType)
override fun convertElementWithParent(element: PsiElement, requiredType: Class<out UElement>?): UElement? =
convertElementWithParent(element, { makeUParent(element) }, requiredType)
private fun convertElementWithParent(element: PsiElement,
parentProvider: () -> UElement?,
requiredType: Class<out UElement>?): UElement? =
when (element) {
is GroovyFile -> GrUFile(element, this)
is GrLiteral -> GrULiteral(element, parentProvider)
is GrAnnotationNameValuePair -> GrUNamedExpression(element, parentProvider)
is GrAnnotation -> GrUAnnotation(element, parentProvider)
is GrTypeDefinition -> GrUClass(element, parentProvider)
is GrMethod -> GrUMethod(element, parentProvider)
is GrParameter -> GrUParameter(element, parentProvider)
is GrQualifiedReference<*> -> GrUReferenceExpression(element, parentProvider)
is LeafPsiElement -> if (element.elementType == GroovyTokenTypes.mIDENT) LazyParentUIdentifier(element, null) else null
else -> null
}?.takeIf { requiredType?.isAssignableFrom(it.javaClass) ?: true }
private fun makeUParent(element: PsiElement) =
element.parents(false).mapNotNull { convertElementWithParent(it, null) }.firstOrNull()
override fun getMethodCallExpression(element: PsiElement,
containingClassFqName: String?,
methodName: String): UastLanguagePlugin.ResolvedMethod? = null //not implemented
override fun getConstructorCallExpression(element: PsiElement,
fqName: String): UastLanguagePlugin.ResolvedConstructor? = null //not implemented
override fun isExpressionValueUsed(element: UExpression): Boolean = TODO("not implemented")
override val priority: Int = 0
override fun isFileSupported(fileName: String): Boolean = fileName.endsWith(".groovy", ignoreCase = true)
override val language: Language = GroovyLanguage
override fun getPossiblePsiSourceTypes(vararg uastTypes: Class<out UElement>): ClassSet<PsiElement> =
classSetOf(GroovyPsiElement::class.java)
}
class GrULiteral(val grElement: GrLiteral, val parentProvider: () -> UElement?) : ULiteralExpression, UInjectionHost {
override val value: Any? get() = grElement.value
override fun evaluate(): Any? = value
override val uastParent: UElement? by lazy(parentProvider)
override val psi: PsiElement = grElement
override val uAnnotations: List<UAnnotation> = emptyList() //not implemented
override val isString: Boolean
get() = super<UInjectionHost>.isString
override val psiLanguageInjectionHost: PsiLanguageInjectionHost
get() = grElement
}
class GrUNamedExpression(val grElement: GrAnnotationNameValuePair, val parentProvider: () -> UElement?) : UNamedExpression {
override val name: String?
get() = grElement.name
override val expression: UExpression
get() = grElement.value.toUElementOfType() ?: GrUnknownUExpression(grElement.value, this)
override val uastParent: UElement? by lazy(parentProvider)
override val psi: GrAnnotationNameValuePair = grElement
override val uAnnotations: List<UAnnotation> = emptyList() //not implemented
override fun equals(other: Any?): Boolean {
if (other !is GrUNamedExpression) return false
return grElement == other.grElement
}
override fun hashCode(): Int = grElement.hashCode()
}
class GrUAnnotation(val grElement: GrAnnotation,
val parentProvider: () -> UElement?) : UAnnotationEx, UAnchorOwner, UMultiResolvable {
override val javaPsi: PsiAnnotation = grElement
override val qualifiedName: String?
get() = grElement.qualifiedName
override fun resolve(): PsiClass? = grElement.nameReferenceElement?.resolve() as PsiClass?
override fun multiResolve(): Iterable<ResolveResult> =
grElement.nameReferenceElement?.multiResolve(false)?.asIterable() ?: emptyList()
override val uastAnchor: UIdentifier?
get() = grElement.classReference.referenceNameElement?.let { UIdentifier(it, this) }
override val attributeValues: List<UNamedExpression> by lazy {
grElement.parameterList.attributes.map {
GrUNamedExpression(it, { this })
}
}
override fun findAttributeValue(name: String?): UExpression? = findDeclaredAttributeValue(name)
override fun findDeclaredAttributeValue(name: String?): UExpression? {
return grElement.parameterList.attributes.asSequence()
.find { it.name == name || it.name == null && "value" == name }
?.let { GrUNamedExpression(it) { this } }
}
override val uastParent: UElement? by lazy(parentProvider)
override val psi: PsiElement = grElement
}
class GrUnknownUExpression(override val psi: PsiElement?, override val uastParent: UElement?) : UExpression {
@NonNls
override fun asLogString(): String = "GrUnknownUExpression(grElement)"
override val uAnnotations: List<UAnnotation> = emptyList() //not implemented
} | apache-2.0 | af7355a55be17fc4bcf87953c62b0169 | 45.493151 | 125 | 0.752763 | 4.957633 | false | false | false | false |
google/intellij-community | plugins/gradle/java/src/config/GradleFileType.kt | 7 | 1465 | // 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.plugins.gradle.config
import com.intellij.openapi.fileTypes.FileTypeRegistry
import com.intellij.openapi.fileTypes.LanguageFileType
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.psi.PsiFile
import org.jetbrains.plugins.gradle.util.GradleBundle
import org.jetbrains.plugins.gradle.util.GradleConstants
import org.jetbrains.plugins.groovy.GroovyLanguage
import javax.swing.Icon
object GradleFileType : LanguageFileType(GroovyLanguage, true) {
override fun getIcon(): Icon = icons.GradleIcons.GradleFile
override fun getName(): String = "Gradle"
override fun getDescription(): String = GradleBundle.message("gradle.filetype.description")
override fun getDisplayName(): String = GradleBundle.message("gradle.filetype.display.name")
override fun getDefaultExtension(): String = GradleConstants.EXTENSION
@JvmStatic
fun isGradleFile(file: VirtualFile) = FileTypeRegistry.getInstance().isFileOfType(file, GradleFileType)
@JvmStatic
fun isGradleFile(file: PsiFile): Boolean {
val virtualFile = file.originalFile.virtualFile ?: return false
return isGradleFile(virtualFile)
}
}
fun VirtualFile?.isGradleFile() = this != null && GradleFileType.isGradleFile(this)
fun PsiFile?.isGradleFile() = this != null && GradleFileType.isGradleFile(this)
| apache-2.0 | f52ff194cf2138f522ea129656188c32 | 46.258065 | 158 | 0.799317 | 4.507692 | false | false | false | false |
apollographql/apollo-android | apollo-runtime/src/commonMain/kotlin/com/apollographql/apollo3/network/ws/WebSocketNetworkTransport.kt | 1 | 11826 | package com.apollographql.apollo3.network.ws
import com.apollographql.apollo3.api.ApolloRequest
import com.apollographql.apollo3.api.ApolloResponse
import com.apollographql.apollo3.api.CustomScalarAdapters
import com.apollographql.apollo3.api.Operation
import com.apollographql.apollo3.api.json.jsonReader
import com.apollographql.apollo3.api.parseJsonResponse
import com.apollographql.apollo3.exception.ApolloException
import com.apollographql.apollo3.exception.ApolloNetworkException
import com.apollographql.apollo3.internal.BackgroundDispatcher
import com.apollographql.apollo3.internal.transformWhile
import com.apollographql.apollo3.network.NetworkTransport
import com.apollographql.apollo3.network.ws.internal.Command
import com.apollographql.apollo3.network.ws.internal.Dispose
import com.apollographql.apollo3.network.ws.internal.Event
import com.apollographql.apollo3.network.ws.internal.GeneralError
import com.apollographql.apollo3.network.ws.internal.Message
import com.apollographql.apollo3.network.ws.internal.NetworkError
import com.apollographql.apollo3.network.ws.internal.OperationComplete
import com.apollographql.apollo3.network.ws.internal.OperationError
import com.apollographql.apollo3.network.ws.internal.OperationResponse
import com.apollographql.apollo3.network.ws.internal.StartOperation
import com.apollographql.apollo3.network.ws.internal.StopOperation
import com.benasher44.uuid.Uuid
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.CoroutineStart
import kotlinx.coroutines.Job
import kotlinx.coroutines.cancel
import kotlinx.coroutines.channels.BufferOverflow
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.channels.Channel.Factory.UNLIMITED
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.asSharedFlow
import kotlinx.coroutines.flow.filter
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.onCompletion
import kotlinx.coroutines.flow.onSubscription
import kotlinx.coroutines.launch
/**
* A [NetworkTransport] that works with WebSockets. Usually it is used with subscriptions but some [WsProtocol]s like [GraphQLWsProtocol]
* also support queries and mutations.
*
* @param serverUrl the url to use to establish the WebSocket connection. It can start with 'https://' or 'wss://' (respectively 'http://'
* or 'ws://' for unsecure versions), both are handled the same way by the underlying code.
* @param webSocketEngine a [WebSocketEngine] that can handle the WebSocket
*
*/
class WebSocketNetworkTransport
private constructor(
private val serverUrl: String,
private val webSocketEngine: WebSocketEngine = DefaultWebSocketEngine(),
private val idleTimeoutMillis: Long = 60_000,
private val protocolFactory: WsProtocol.Factory = SubscriptionWsProtocol.Factory(),
private val reconnectWhen: ((Throwable) -> Boolean)?,
) : NetworkTransport {
/**
* Use unlimited buffers so that we never have to suspend when writing a command or an event,
* and we avoid deadlocks. This might be overkill but is most likely never going to be a problem in practice.
*/
private val messages = Channel<Message>(UNLIMITED)
/**
* This takes messages from [messages] and broadcasts the [Event]s
*/
private val mutableEvents = MutableSharedFlow<Event>(0, Int.MAX_VALUE, BufferOverflow.SUSPEND)
private val events = mutableEvents.asSharedFlow()
val subscriptionCount = mutableEvents.subscriptionCount
private val backgroundDispatcher = BackgroundDispatcher()
private val coroutineScope = CoroutineScope(backgroundDispatcher.coroutineDispatcher)
init {
coroutineScope.launch {
supervise(this)
backgroundDispatcher.dispose()
}
}
private val listener = object : WsProtocol.Listener {
override fun operationResponse(id: String, payload: Map<String, Any?>) {
messages.trySend(OperationResponse(id, payload))
}
override fun operationError(id: String, payload: Map<String, Any?>?) {
messages.trySend(OperationError(id, payload))
}
override fun operationComplete(id: String) {
messages.trySend(OperationComplete(id))
}
override fun generalError(payload: Map<String, Any?>?) {
messages.trySend(GeneralError(payload))
}
override fun networkError(cause: Throwable) {
messages.trySend(NetworkError(cause))
}
}
/**
* Long-running method that creates/handles the websocket lifecyle
*/
private suspend fun supervise(scope: CoroutineScope) {
/**
* No need to lock these variables as they are all accessed from the same thread
*/
var idleJob: Job? = null
var connectionJob: Job? = null
var protocol: WsProtocol? = null
val activeMessages = mutableMapOf<Uuid, StartOperation<*>>()
/**
* This happens:
* - when this coroutine receives a [Dispose] message
* - when the idleJob completes
* - when there is an error reading the WebSocket and this coroutine receives a [NetworkError] message
*/
fun closeProtocol() {
protocol?.close()
protocol = null
connectionJob?.cancel()
connectionJob = null
idleJob?.cancel()
idleJob = null
}
while (true) {
val message = messages.receive()
when (message) {
is Event -> {
if (message is NetworkError) {
closeProtocol()
if (reconnectWhen?.invoke(message.cause) == true) {
activeMessages.values.forEach {
// Re-queue all start messages
// This will restart the websocket
messages.trySend(it)
}
} else {
// forward the NetworkError downstream. Active flows will throw
mutableEvents.tryEmit(message)
}
} else {
mutableEvents.tryEmit(message)
}
}
is Command -> {
if (protocol == null) {
if (message !is StartOperation<*>) {
// A stop was received, but we don't have a connection. Ignore it
continue
}
val webSocketConnection = try {
webSocketEngine.open(
url = serverUrl,
headers = mapOf(
"Sec-WebSocket-Protocol" to protocolFactory.name,
)
)
} catch (e: Exception) {
// Error opening the websocket
mutableEvents.emit(NetworkError(e))
continue
}
protocol = protocolFactory.create(
webSocketConnection = webSocketConnection,
listener = listener,
scope = scope,
)
try {
protocol!!.connectionInit()
} catch (e: Exception) {
// Error initializing the connection
protocol = null
mutableEvents.emit(NetworkError(e))
continue
}
/**
* We start as [CoroutineStart.UNDISPATCHED] to make sure protocol.run() is always be called.
* I'm not 100% sure if protocol could be reset before starting to execute the coroutine
* so added this as an extra precaution. Maybe it's not required, but it shouldn't hurt
* so better safe than sorry...
*/
connectionJob = scope.launch(start = CoroutineStart.UNDISPATCHED) {
protocol!!.run()
}
}
when (message) {
is StartOperation<*> -> {
activeMessages[message.request.requestUuid] = message
protocol!!.startOperation(message.request)
}
is StopOperation<*> -> {
activeMessages.remove(message.request.requestUuid)
protocol!!.stopOperation(message.request)
}
is Dispose -> {
closeProtocol()
// Exit the loop and the coroutine scope
return
}
}
if (activeMessages.isEmpty()) {
idleJob = scope.launch {
delay(idleTimeoutMillis)
closeProtocol()
}
} else {
idleJob?.cancel()
idleJob = null
}
}
}
}
}
override fun <D : Operation.Data> execute(
request: ApolloRequest<D>,
): Flow<ApolloResponse<D>> {
return events.onSubscription {
messages.send(StartOperation(request))
}.filter {
it.id == request.requestUuid.toString() || it.id == null
}.transformWhile<Event, Event> {
when (it) {
is OperationComplete -> {
false
}
is NetworkError -> {
emit(it)
false
}
is GeneralError -> {
// The server sends an error without an operation id. This happens when sending an unknown message type
// to https://apollo-fullstack-tutorial.herokuapp.com/ for an example. In that case, this error is not fatal
// and the server will continue honouring other subscriptions, so we just filter the error out and log it.
println("Received general error while executing operation ${request.operation.name()}: ${it.payload}")
true
}
else -> {
emit(it)
true
}
}
}.map {
when (it) {
is OperationResponse -> request.operation
.parseJsonResponse(it.payload.jsonReader(), request.executionContext[CustomScalarAdapters]!!)
.newBuilder()
.requestUuid(request.requestUuid)
.build()
is OperationError -> throw ApolloNetworkException("Operation error ${request.operation.name()}: ${it.payload}")
is NetworkError -> throw ApolloNetworkException("Network error while executing ${request.operation.name()}", it.cause)
// Cannot happen as these events are filtered out upstream
is OperationComplete, is GeneralError -> error("Unexpected event $it")
}
}.onCompletion {
messages.send(StopOperation(request))
}
}
override fun dispose() {
messages.trySend(Dispose)
}
class Builder {
private var serverUrl: String? = null
private var webSocketEngine: WebSocketEngine? = null
private var idleTimeoutMillis: Long? = null
private var protocolFactory: WsProtocol.Factory? = null
private var reconnectWhen: ((Throwable) -> Boolean)? = null
fun serverUrl(serverUrl: String) = apply {
this.serverUrl = serverUrl
}
@Suppress("DEPRECATION")
fun webSocketEngine(webSocketEngine: WebSocketEngine) = apply {
this.webSocketEngine = webSocketEngine
}
fun idleTimeoutMillis(idleTimeoutMillis: Long) = apply {
this.idleTimeoutMillis = idleTimeoutMillis
}
fun protocol(protocolFactory: WsProtocol.Factory) = apply {
this.protocolFactory = protocolFactory
}
/**
* Configure the [WebSocketNetworkTransport] to reconnect the websocket automatically when a network error
* happens
*
* @param reconnectWhen a function taking the error as a parameter and returning 'true' to reconnect
* automatically or 'false' to forward the error to all listening [Flow]
*
*/
fun reconnectWhen(reconnectWhen: ((Throwable) -> Boolean)?) = apply {
this.reconnectWhen = reconnectWhen
}
fun build(): WebSocketNetworkTransport {
@Suppress("DEPRECATION")
return WebSocketNetworkTransport(
serverUrl ?: error("No serverUrl specified"),
webSocketEngine ?: DefaultWebSocketEngine(),
idleTimeoutMillis ?: 60_000,
protocolFactory ?: SubscriptionWsProtocol.Factory(),
reconnectWhen
)
}
}
}
| mit | 2d87e9e22fa0ef58a835d505d649c475 | 35.054878 | 138 | 0.659648 | 4.848708 | false | false | false | false |
SimpleMobileTools/Simple-Gallery | app/src/main/kotlin/com/simplemobiletools/gallery/pro/dialogs/ChangeFileThumbnailStyleDialog.kt | 1 | 3705 | package com.simplemobiletools.gallery.pro.dialogs
import android.content.DialogInterface
import android.view.View
import com.simplemobiletools.commons.activities.BaseSimpleActivity
import com.simplemobiletools.commons.dialogs.RadioGroupDialog
import com.simplemobiletools.commons.extensions.getAlertDialogBuilder
import com.simplemobiletools.commons.extensions.setupDialogStuff
import com.simplemobiletools.commons.models.RadioItem
import com.simplemobiletools.gallery.pro.R
import com.simplemobiletools.gallery.pro.extensions.config
import kotlinx.android.synthetic.main.dialog_change_file_thumbnail_style.view.*
class ChangeFileThumbnailStyleDialog(val activity: BaseSimpleActivity) : DialogInterface.OnClickListener {
private var config = activity.config
private var view: View
private var thumbnailSpacing = config.thumbnailSpacing
init {
view = activity.layoutInflater.inflate(R.layout.dialog_change_file_thumbnail_style, null).apply {
dialog_file_style_rounded_corners.isChecked = config.fileRoundedCorners
dialog_file_style_animate_gifs.isChecked = config.animateGifs
dialog_file_style_show_thumbnail_video_duration.isChecked = config.showThumbnailVideoDuration
dialog_file_style_show_thumbnail_file_types.isChecked = config.showThumbnailFileTypes
dialog_file_style_mark_favorite_items.isChecked = config.markFavoriteItems
dialog_file_style_rounded_corners_holder.setOnClickListener { dialog_file_style_rounded_corners.toggle() }
dialog_file_style_animate_gifs_holder.setOnClickListener { dialog_file_style_animate_gifs.toggle() }
dialog_file_style_show_thumbnail_video_duration_holder.setOnClickListener { dialog_file_style_show_thumbnail_video_duration.toggle() }
dialog_file_style_show_thumbnail_file_types_holder.setOnClickListener { dialog_file_style_show_thumbnail_file_types.toggle() }
dialog_file_style_mark_favorite_items_holder.setOnClickListener { dialog_file_style_mark_favorite_items.toggle() }
dialog_file_style_spacing_holder.setOnClickListener {
val items = arrayListOf(
RadioItem(0, "0x"),
RadioItem(1, "1x"),
RadioItem(2, "2x"),
RadioItem(4, "4x"),
RadioItem(8, "8x"),
RadioItem(16, "16x"),
RadioItem(32, "32x"),
RadioItem(64, "64x")
)
RadioGroupDialog(activity, items, thumbnailSpacing) {
thumbnailSpacing = it as Int
updateThumbnailSpacingText()
}
}
}
updateThumbnailSpacingText()
activity.getAlertDialogBuilder()
.setPositiveButton(R.string.ok, this)
.setNegativeButton(R.string.cancel, null)
.apply {
activity.setupDialogStuff(view, this)
}
}
override fun onClick(dialog: DialogInterface, which: Int) {
config.fileRoundedCorners = view.dialog_file_style_rounded_corners.isChecked
config.animateGifs = view.dialog_file_style_animate_gifs.isChecked
config.showThumbnailVideoDuration = view.dialog_file_style_show_thumbnail_video_duration.isChecked
config.showThumbnailFileTypes = view.dialog_file_style_show_thumbnail_file_types.isChecked
config.markFavoriteItems = view.dialog_file_style_mark_favorite_items.isChecked
config.thumbnailSpacing = thumbnailSpacing
}
private fun updateThumbnailSpacingText() {
view.dialog_file_style_spacing.text = "${thumbnailSpacing}x"
}
}
| gpl-3.0 | 9cea9d4af2a470720391111bda9f1e96 | 49.067568 | 146 | 0.693657 | 4.619701 | false | true | false | false |
vvv1559/intellij-community | plugins/git4idea/src/git4idea/GitApplyChangesProcess.kt | 1 | 21548 | /*
* 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 git4idea
import com.intellij.dvcs.DvcsUtil
import com.intellij.dvcs.DvcsUtil.getShortRepositoryName
import com.intellij.notification.Notification
import com.intellij.notification.NotificationListener
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.ModalityState
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Ref
import com.intellij.openapi.util.text.StringUtil
import com.intellij.openapi.util.text.StringUtil.pluralize
import com.intellij.openapi.vcs.AbstractVcsHelper
import com.intellij.openapi.vcs.FilePath
import com.intellij.openapi.vcs.VcsNotifier
import com.intellij.openapi.vcs.changes.*
import com.intellij.openapi.vcs.history.VcsRevisionNumber
import com.intellij.openapi.vcs.merge.MergeDialogCustomizer
import com.intellij.openapi.vcs.update.RefreshVFsSynchronously
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.util.text.UniqueNameGenerator
import com.intellij.vcs.log.Hash
import com.intellij.vcs.log.VcsFullCommitDetails
import com.intellij.vcs.log.util.VcsUserUtil
import git4idea.commands.*
import git4idea.commands.GitSimpleEventDetector.Event.CHERRY_PICK_CONFLICT
import git4idea.commands.GitSimpleEventDetector.Event.LOCAL_CHANGES_OVERWRITTEN_BY_CHERRY_PICK
import git4idea.merge.GitConflictResolver
import git4idea.repo.GitRepository
import git4idea.repo.GitRepositoryManager
import git4idea.util.GitUntrackedFilesHelper
import java.util.concurrent.CountDownLatch
import java.util.concurrent.Semaphore
import java.util.concurrent.TimeUnit
import java.util.concurrent.atomic.AtomicBoolean
import java.util.concurrent.atomic.AtomicReference
import javax.swing.event.HyperlinkEvent
/**
* Applies the given Git operation (e.g. cherry-pick or revert) to the current working tree,
* waits for the [ChangeListManager] update, shows the commit dialog and removes the changelist after commit,
* if the commit was successful.
*/
class GitApplyChangesProcess(private val project: Project,
private val commits: List<VcsFullCommitDetails>,
private val autoCommit: Boolean,
private val operationName: String,
private val appliedWord: String,
private val command: (GitRepository, Hash, Boolean, List<GitLineHandlerListener>) -> GitCommandResult,
private val emptyCommitDetector: (GitCommandResult) -> Boolean,
private val defaultCommitMessageGenerator: (VcsFullCommitDetails) -> String,
private val findLocalChanges: (Collection<Change>) -> Collection<Change>,
private val preserveCommitMetadata: Boolean,
private val cleanupBeforeCommit: (GitRepository) -> Unit = {}) {
private val LOG = logger<GitApplyChangesProcess>()
private val git = Git.getInstance()
private val repositoryManager = GitRepositoryManager.getInstance(project)
private val vcsNotifier = VcsNotifier.getInstance(project)
private val changeListManager = ChangeListManager.getInstance(project)
private val vcsHelper = AbstractVcsHelper.getInstance(project)
fun execute() {
val commitsInRoots = DvcsUtil.groupCommitsByRoots<GitRepository>(repositoryManager, commits)
LOG.info("${operationName}ing commits: " + toString(commitsInRoots))
val successfulCommits = mutableListOf<VcsFullCommitDetails>()
val skippedCommits = mutableListOf<VcsFullCommitDetails>()
val token = DvcsUtil.workingTreeChangeStarted(project)
try {
for ((repository, value) in commitsInRoots) {
val result = executeForRepo(repository, value, successfulCommits, skippedCommits)
repository.update()
if (!result) {
return
}
}
notifyResult(successfulCommits, skippedCommits)
}
finally {
token.finish()
}
}
// return true to continue with other roots, false to break execution
private fun executeForRepo(repository: GitRepository,
commits: List<VcsFullCommitDetails>,
successfulCommits: MutableList<VcsFullCommitDetails>,
alreadyPicked: MutableList<VcsFullCommitDetails>): Boolean {
for (commit in commits) {
val conflictDetector = GitSimpleEventDetector(CHERRY_PICK_CONFLICT)
val localChangesOverwrittenDetector = GitSimpleEventDetector(LOCAL_CHANGES_OVERWRITTEN_BY_CHERRY_PICK)
val untrackedFilesDetector = GitUntrackedFilesOverwrittenByOperationDetector(repository.root)
val result = command(repository, commit.id, autoCommit,
listOf(conflictDetector, localChangesOverwrittenDetector, untrackedFilesDetector))
if (result.success()) {
if (autoCommit) {
successfulCommits.add(commit)
}
else {
val committed = updateChangeListManagerShowCommitDialogAndRemoveChangeListOnSuccess(repository, commit,
successfulCommits, alreadyPicked)
if (!committed) {
notifyCommitCancelled(commit, successfulCommits)
return false
}
}
}
else if (conflictDetector.hasHappened()) {
val mergeCompleted = ConflictResolver(project, git, repository.root,
commit.id.asString(), VcsUserUtil.getShortPresentation(commit.author),
commit.subject, operationName).merge()
if (mergeCompleted) {
val committed = updateChangeListManagerShowCommitDialogAndRemoveChangeListOnSuccess(repository, commit,
successfulCommits, alreadyPicked)
if (!committed) {
notifyCommitCancelled(commit, successfulCommits)
return false
}
}
else {
updateChangeListManager(commit)
notifyConflictWarning(repository, commit, successfulCommits)
return false
}
}
else if (untrackedFilesDetector.wasMessageDetected()) {
var description = commitDetails(commit) +
"<br/>Some untracked working tree files would be overwritten by $operationName.<br/>" +
"Please move, remove or add them before you can $operationName. <a href='view'>View them</a>"
description += getSuccessfulCommitDetailsIfAny(successfulCommits)
GitUntrackedFilesHelper.notifyUntrackedFilesOverwrittenBy(project, repository.root,
untrackedFilesDetector.relativeFilePaths, operationName, description)
return false
}
else if (localChangesOverwrittenDetector.hasHappened()) {
notifyError("Your local changes would be overwritten by $operationName.<br/>Commit your changes or stash them to proceed.",
commit, successfulCommits)
return false
}
else if (emptyCommitDetector(result)) {
alreadyPicked.add(commit)
}
else {
notifyError(result.errorOutputAsHtmlString, commit, successfulCommits)
return false
}
}
return true
}
private fun updateChangeListManagerShowCommitDialogAndRemoveChangeListOnSuccess(repository: GitRepository,
commit: VcsFullCommitDetails,
successfulCommits: MutableList<VcsFullCommitDetails>,
alreadyPicked: MutableList<VcsFullCommitDetails>): Boolean {
val data = updateChangeListManager(commit)
if (data == null) {
alreadyPicked.add(commit)
return true
}
val committed = showCommitDialogAndWaitForCommit(repository, commit, data.changeList, data.commitMessage)
if (committed) {
changeListManager.removeChangeList(data.changeList)
successfulCommits.add(commit)
return true
}
return false
}
private fun updateChangeListManager(commit: VcsFullCommitDetails): ChangeListData? {
val changes = commit.changes
RefreshVFsSynchronously.updateChanges(changes)
val commitMessage = defaultCommitMessageGenerator(commit)
val paths = ChangesUtil.getPaths(changes)
val changeList = createChangeListAfterUpdate(commit, paths, commitMessage)
return if (changeList == null) null else ChangeListData(changeList, commitMessage)
}
private fun createChangeListAfterUpdate(commit: VcsFullCommitDetails, paths: Collection<FilePath>,
commitMessage: String): LocalChangeList? {
val waiter = CountDownLatch(1)
val changeList = Ref.create<LocalChangeList>()
changeListManager.invokeAfterUpdate({
changeList.set(createChangeListIfThereAreChanges(commit, commitMessage))
waiter.countDown()
}, InvokeAfterUpdateMode.SILENT_CALLBACK_POOLED, operationName.capitalize(),
{ vcsDirtyScopeManager -> vcsDirtyScopeManager.filePathsDirty(paths, null) },
ModalityState.NON_MODAL)
try {
val success = waiter.await(100, TimeUnit.SECONDS)
if (!success) {
LOG.error("Couldn't await for changelist manager refresh")
}
}
catch (e: InterruptedException) {
LOG.error(e)
return null
}
return changeList.get()
}
private fun showCommitDialogAndWaitForCommit(repository: GitRepository, commit: VcsFullCommitDetails,
changeList: LocalChangeList, commitMessage: String): Boolean {
val commitSucceeded = AtomicBoolean()
val sem = Semaphore(0)
ApplicationManager.getApplication().invokeAndWait({
try {
cleanupBeforeCommit(repository)
val changes = commit.changes
val commitNotCancelled = vcsHelper.commitChanges(
changes, changeList, commitMessage,
object : CommitResultHandler {
override fun onSuccess(commitMessage1: String) {
commitSucceeded.set(true)
sem.release()
}
override fun onFailure() {
commitSucceeded.set(false)
sem.release()
}
})
if (!commitNotCancelled) {
commitSucceeded.set(false)
sem.release()
}
}
catch (t: Throwable) {
LOG.error(t)
commitSucceeded.set(false)
sem.release()
}
}, ModalityState.NON_MODAL)
// need additional waiting, because commitChanges is asynchronous
try {
sem.acquire()
}
catch (e: InterruptedException) {
LOG.error(e)
return false
}
return commitSucceeded.get()
}
private fun createChangeListIfThereAreChanges(commit: VcsFullCommitDetails, commitMessage: String): LocalChangeList? {
val originalChanges = commit.changes
if (originalChanges.isEmpty()) {
LOG.info("Empty commit " + commit.id)
return null
}
if (noChangesAfterApply(originalChanges)) {
LOG.info("No changes after executing for commit ${commit.id}")
return null
}
val changeListName = createNameForChangeList(commitMessage)
val createdChangeList = (changeListManager as ChangeListManagerEx).addChangeList(changeListName, commitMessage,
if (preserveCommitMetadata) commit else null)
val actualChangeList = moveChanges(originalChanges, createdChangeList)
if (actualChangeList != null && !actualChangeList.changes.isEmpty()) {
return createdChangeList
}
LOG.warn("No changes were moved to the changelist. Changes from commit: " + originalChanges +
"\nAll changes: " + changeListManager.getAllChanges())
changeListManager.removeChangeList(createdChangeList)
return null
}
private fun noChangesAfterApply(originalChanges: Collection<Change>): Boolean {
return findLocalChanges(originalChanges).isEmpty()
}
private fun moveChanges(originalChanges: Collection<Change>, targetChangeList: LocalChangeList): LocalChangeList? {
val localChanges = findLocalChanges(originalChanges)
// 1. We have to listen to CLM changes, because moveChangesTo is asynchronous
// 2. We have to collect the real target change list, because the original target list (passed to moveChangesTo) is not updated in time.
val moveChangesWaiter = CountDownLatch(1)
val resultingChangeList = AtomicReference<LocalChangeList>()
val listener = object : ChangeListAdapter() {
override fun changesMoved(changes: Collection<Change>, fromList: ChangeList, toList: ChangeList) {
if (toList is LocalChangeList && targetChangeList.id == toList.id) {
resultingChangeList.set(toList)
moveChangesWaiter.countDown()
}
}
}
try {
changeListManager.addChangeListListener(listener)
changeListManager.moveChangesTo(targetChangeList, *localChanges.toTypedArray())
val success = moveChangesWaiter.await(100, TimeUnit.SECONDS)
if (!success) {
LOG.error("Couldn't await for changes move.")
}
return resultingChangeList.get()
}
catch (e: InterruptedException) {
LOG.error(e)
return null
}
finally {
changeListManager.removeChangeListListener(listener)
}
}
private fun createNameForChangeList(commitMessage: String): String {
val proposedName = commitMessage.trim()
.substringBefore('\n')
.trim()
.replace("[ ]{2,}".toRegex(), " ")
return UniqueNameGenerator.generateUniqueName(proposedName, "", "", "-", "", { changeListManager.findChangeList(it) == null })
}
private fun notifyResult(successfulCommits: List<VcsFullCommitDetails>, skipped: List<VcsFullCommitDetails>) {
if (skipped.isEmpty()) {
vcsNotifier.notifySuccess("${operationName.capitalize()} successful", getCommitsDetails(successfulCommits))
}
else if (!successfulCommits.isEmpty()) {
val title = String.format("${operationName.capitalize()}ed %d commits from %d", successfulCommits.size,
successfulCommits.size + skipped.size)
val description = getCommitsDetails(successfulCommits) + "<hr/>" + formSkippedDescription(skipped, true)
vcsNotifier.notifySuccess(title, description)
}
else {
vcsNotifier.notifyImportantWarning("Nothing to $operationName", formSkippedDescription(skipped, false))
}
}
private fun notifyConflictWarning(repository: GitRepository,
commit: VcsFullCommitDetails,
successfulCommits: List<VcsFullCommitDetails>) {
val resolveLinkListener = ResolveLinkListener(repository.root,
commit.id.toShortString(),
VcsUserUtil.getShortPresentation(commit.author),
commit.subject)
var description = commitDetails(commit) + "<br/>Unresolved conflicts remain in the working tree. <a href='resolve'>Resolve them.<a/>"
description += getSuccessfulCommitDetailsIfAny(successfulCommits)
vcsNotifier.notifyImportantWarning("${operationName.capitalize()}ed with conflicts", description, resolveLinkListener)
}
private fun notifyCommitCancelled(commit: VcsFullCommitDetails, successfulCommits: List<VcsFullCommitDetails>) {
if (successfulCommits.isEmpty()) {
// don't notify about cancelled commit. Notify just in the case when there were already successful commits in the queue.
return
}
var description = commitDetails(commit)
description += getSuccessfulCommitDetailsIfAny(successfulCommits)
vcsNotifier.notifyMinorWarning("${operationName.capitalize()} cancelled", description, null)
}
private fun notifyError(content: String,
failedCommit: VcsFullCommitDetails,
successfulCommits: List<VcsFullCommitDetails>) {
var description = commitDetails(failedCommit) + "<br/>" + content
description += getSuccessfulCommitDetailsIfAny(successfulCommits)
vcsNotifier.notifyError("${operationName.capitalize()} Failed", description)
}
private fun getSuccessfulCommitDetailsIfAny(successfulCommits: List<VcsFullCommitDetails>): String {
var description = ""
if (!successfulCommits.isEmpty()) {
description += "<hr/>However ${operationName} succeeded for the following " + pluralize("commit", successfulCommits.size) + ":<br/>"
description += getCommitsDetails(successfulCommits)
}
return description
}
private fun formSkippedDescription(skipped: List<VcsFullCommitDetails>, but: Boolean): String {
val hashes = StringUtil.join(skipped, { commit -> commit.id.toShortString() }, ", ")
if (but) {
val was = if (skipped.size == 1) "was" else "were"
val it = if (skipped.size == 1) "it" else "them"
return String.format("%s %s skipped, because all changes have already been ${appliedWord}.", hashes, was, it)
}
return String.format("All changes from %s have already been ${appliedWord}", hashes)
}
private fun getCommitsDetails(successfulCommits: List<VcsFullCommitDetails>): String {
var description = ""
for (commit in successfulCommits) {
description += commitDetails(commit) + "<br/>"
}
return description.substring(0, description.length - "<br/>".length)
}
private fun commitDetails(commit: VcsFullCommitDetails): String {
return commit.id.toShortString() + " " + commit.subject
}
private fun toString(commitsInRoots: Map<GitRepository, List<VcsFullCommitDetails>>): String {
return commitsInRoots.entries.joinToString("; ") { entry ->
val commits = entry.value.joinToString { it.id.asString() }
getShortRepositoryName(entry.key) + ": [" + commits + "]"
}
}
private inner class ResolveLinkListener(private val root: VirtualFile,
private val hash: String,
private val author: String,
private val message: String) : NotificationListener {
override fun hyperlinkUpdate(notification: Notification, event: HyperlinkEvent) {
if (event.eventType == HyperlinkEvent.EventType.ACTIVATED) {
if (event.description == "resolve") {
GitApplyChangesProcess.ConflictResolver(project, git, root, hash, author, message, operationName).mergeNoProceed()
}
}
}
}
private data class ChangeListData(val changeList: LocalChangeList, val commitMessage: String)
class ConflictResolver(project: Project,
git: Git,
root: VirtualFile,
commitHash: String,
commitAuthor: String,
commitMessage: String,
operationName: String
) : GitConflictResolver(project, git, setOf(root), makeParams(commitHash, commitAuthor, commitMessage, operationName)) {
override fun notifyUnresolvedRemain() {/* we show a [possibly] compound notification after applying all commits.*/
}
}
}
private fun makeParams(commitHash: String, commitAuthor: String, commitMessage: String, operationName: String): GitConflictResolver.Params {
val params = GitConflictResolver.Params()
params.setErrorNotificationTitle("${operationName.capitalize()}ed with conflicts")
params.setMergeDialogCustomizer(MergeDialogCustomizer(commitHash, commitAuthor, commitMessage, operationName))
return params
}
private class MergeDialogCustomizer(private val commitHash: String,
private val commitAuthor: String,
private val commitMessage: String,
private val operationName: String) : MergeDialogCustomizer() {
override fun getMultipleFileMergeDescription(files: Collection<VirtualFile>) =
"<html>Conflicts during ${operationName}ing commit <code>$commitHash</code> " +
"made by $commitAuthor<br/><code>\"$commitMessage\"</code></html>"
override fun getLeftPanelTitle(file: VirtualFile) = "Local changes"
override fun getRightPanelTitle(file: VirtualFile, revisionNumber: VcsRevisionNumber?) =
"<html>Changes from $operationName <code>$commitHash</code>"
}
| apache-2.0 | 2ef32f1f125ecd5667629aee8ccd70b2 | 44.846809 | 142 | 0.666419 | 5.35354 | false | false | false | false |
mr-max/learning-spaces | app/src/main/java/de/maxvogler/learningspaces/fragments/LocationInfoFragment.kt | 1 | 3743 | package de.maxvogler.learningspaces.fragments
import android.os.Bundle
import android.support.v4.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import butterknife.bindView
import com.squareup.otto.Subscribe
import de.maxvogler.learningspaces.R
import de.maxvogler.learningspaces.adapters.OpeningHourAdapter
import de.maxvogler.learningspaces.adapters.SeatDescriptionAdapter
import de.maxvogler.learningspaces.events.LocationFocusChangeEvent
import de.maxvogler.learningspaces.events.UpdateLocationsEvent
import de.maxvogler.learningspaces.helpers.fillWithAdapter
import de.maxvogler.learningspaces.models.Location
import de.maxvogler.learningspaces.services.BusProvider
import de.maxvogler.learningspaces.views.PercentageView
/**
* A Fragment, displaying detailed information about the currently selected [Location]
*/
public class LocationInfoFragment : Fragment() {
private val nameText: TextView by bindView(R.id.name)
private val buildingText: TextView by bindView(R.id.descriptionBuilding)
private val totalSeatsText: TextView by bindView(R.id.descriptionSeatsTotal)
private val hoursLayout: ViewGroup by bindView(R.id.hours)
private val seatsLayout: ViewGroup by bindView(R.id.seats)
private val seatsContainer: ViewGroup by bindView(R.id.seatsContainer)
private val seatsPercentages: PercentageView by bindView(R.id.seatsOverview)
private var location: Location? = null
private val mBus = BusProvider.instance
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View
= inflater.inflate(R.layout.fragment_info, container, false)
override fun onResume() {
super.onResume()
mBus.register(this)
}
override fun onPause() {
mBus.unregister(this)
super.onPause()
}
@Subscribe
public fun onLocationFocusChange(event: LocationFocusChangeEvent) {
// Only update this Fragment, if a new Location is set. If no Location is selected,
// the Fragment will be hidden anyway.
if (event.location != null) {
location = event.location
updateInformation(event.location)
}
}
@Subscribe
public fun onUpdateLocations(event: UpdateLocationsEvent) {
var oldLocation = location
if (oldLocation != null) {
// TODO: Hide InfoFragment or display error if location == null
location = event.locations.get(oldLocation.id)
updateInformation(location!!)
}
}
private fun updateInformation(location: Location) {
nameText.text = location.name
seatsPercentages.setTexts(R.string.closed, R.plurals.seats_free_short, R.plurals.hidden)
seatsPercentages.values = arrayListOf(location.freeSeats, location.occupiedSeats)
seatsPercentages.active = location.openingHours.isOpen()
totalSeatsText.text = resources.getQuantityString(R.plurals.seats_total_long, location.totalSeats, location.totalSeats)
hoursLayout.fillWithAdapter(OpeningHourAdapter(activity, R.layout.view_open_hours, location.openingHours))
val seatsAdapter = SeatDescriptionAdapter(activity, R.layout.view_seat_count, location)
seatsLayout.fillWithAdapter(seatsAdapter)
seatsContainer.visibility = if (seatsAdapter.isEmpty) View.GONE else View.VISIBLE
buildingText.text = getString(R.string.building, location.building)
buildingText.visibility = if (location.building == null) View.GONE else View.VISIBLE
}
companion object {
public fun newInstance(): LocationInfoFragment = LocationInfoFragment()
}
}
| gpl-2.0 | c92316b37bbab93915ccb58b5b697d9b | 38.4 | 127 | 0.745926 | 4.542476 | false | false | false | false |
romannurik/muzei | android-client-common/src/main/java/com/google/android/apps/muzei/sync/ProviderManager.kt | 1 | 11616 | /*
* Copyright 2018 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.muzei.sync
import android.annotation.SuppressLint
import android.content.BroadcastReceiver
import android.content.ContentResolver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.content.pm.PackageManager
import android.database.ContentObserver
import android.net.Uri
import android.os.Build
import android.os.Handler
import android.os.Looper
import android.os.RemoteException
import android.util.Log
import androidx.core.content.edit
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.Observer
import androidx.preference.PreferenceManager
import com.google.android.apps.muzei.api.internal.ProtocolConstants
import com.google.android.apps.muzei.api.provider.ProviderContract
import com.google.android.apps.muzei.room.Artwork
import com.google.android.apps.muzei.room.MuzeiDatabase
import com.google.android.apps.muzei.room.Provider
import com.google.android.apps.muzei.util.ContentProviderClientCompat
import kotlinx.coroutines.DelicateCoroutinesApi
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.Job
import kotlinx.coroutines.asCoroutineDispatcher
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import net.nurik.roman.muzei.androidclientcommon.BuildConfig
import java.util.concurrent.Executors
/**
* Single threaded coroutine context used for all sync operations
*/
internal val syncSingleThreadContext by lazy {
Executors.newSingleThreadExecutor { target ->
Thread(target, "ProviderSync")
}.asCoroutineDispatcher()
}
/**
* Manager which monitors the current Provider
*/
class ProviderManager private constructor(private val context: Context)
: MutableLiveData<Provider?>(), Observer<Provider?> {
companion object {
private const val TAG = "ProviderManager"
private const val PREF_LOAD_FREQUENCY_SECONDS = "loadFrequencySeconds"
private const val DEFAULT_LOAD_FREQUENCY_SECONDS = 3600L
private const val PREF_LOAD_ON_WIFI = "loadOnWifi"
private const val DEFAULT_LOAD_ON_WIFI = false
@SuppressLint("StaticFieldLeak")
@Volatile
private var instance: ProviderManager? = null
fun getInstance(context: Context): ProviderManager =
instance ?: synchronized(this) {
instance ?: ProviderManager(context.applicationContext)
.also { instance = it }
}
suspend fun select(context: Context, authority: String) {
val currentAuthority = getInstance(context).value?.authority
if (authority != currentAuthority) {
MuzeiDatabase.getInstance(context).providerDao().select(authority)
}
}
suspend fun requestLoad(context: Context, contentUri: Uri) {
try {
ContentProviderClientCompat.getClient(context, contentUri)?.call(
ProtocolConstants.METHOD_REQUEST_LOAD)
} catch (e: RemoteException) {
Log.i(TAG, "Provider ${contentUri.authority} crashed while requesting load", e)
}
}
suspend fun getDescription(context: Context, authority: String): String {
val contentUri = Uri.Builder()
.scheme(ContentResolver.SCHEME_CONTENT)
.authority(authority)
.build()
return ContentProviderClientCompat.getClient(context, contentUri)?.use { client ->
return try {
val result = client.call(ProtocolConstants.METHOD_GET_DESCRIPTION)
result?.getString(ProtocolConstants.KEY_DESCRIPTION, "") ?: ""
} catch (e: RemoteException) {
Log.i(TAG, "Provider $authority crashed while retrieving description", e)
""
}
} ?: ""
}
}
private val packageChangeReceiver : BroadcastReceiver = object : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent?) {
val provider = value ?: return
val packageName = intent?.data?.schemeSpecificPart
val changedComponents = intent?.getStringArrayExtra(
Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST) ?: emptyArray()
val pm = context.packageManager
@Suppress("DEPRECATION")
@SuppressLint("InlinedApi")
val providerInfo = pm.resolveContentProvider(provider.authority,
PackageManager.MATCH_DISABLED_COMPONENTS)
val providerComponentName = providerInfo?.name
val wholePackageChanged = changedComponents.any { it == packageName }
val providerChanged = providerInfo != null
&& changedComponents.any { it == providerComponentName }
if (providerInfo == null || (providerInfo.packageName == packageName
&& (wholePackageChanged || providerChanged))) {
// The selected provider changed, so restart loading
startArtworkLoad()
}
}
}
private val contentObserver: ContentObserver
private val providerLiveData by lazy {
MuzeiDatabase.getInstance(context).providerDao().currentProviderLiveData
}
private val artworkLiveData by lazy {
MuzeiDatabase.getInstance(context).artworkDao().currentArtworkLiveData
}
private var nextArtworkJob: Job? = null
@OptIn(DelicateCoroutinesApi::class)
private val artworkObserver = Observer<Artwork?> { artwork ->
if (artwork == null) {
// Can't have no artwork at all,
// try loading the next artwork with a slight delay
nextArtworkJob?.cancel()
nextArtworkJob = GlobalScope.launch {
delay(1000)
if (nextArtworkJob?.isCancelled == false) {
nextArtwork()
}
}
} else {
nextArtworkJob?.cancel()
}
}
var loadFrequencySeconds: Long
set(newLoadFrequency) {
PreferenceManager.getDefaultSharedPreferences(context).edit {
putLong(PREF_LOAD_FREQUENCY_SECONDS, newLoadFrequency)
}
if (newLoadFrequency > 0) {
ArtworkLoadWorker.enqueuePeriodic(context, newLoadFrequency, loadOnWifi)
} else {
ArtworkLoadWorker.cancelPeriodic(context)
}
}
get() = PreferenceManager.getDefaultSharedPreferences(context)
.getLong(PREF_LOAD_FREQUENCY_SECONDS, DEFAULT_LOAD_FREQUENCY_SECONDS)
var loadOnWifi: Boolean
set(newLoadOnWifi) {
PreferenceManager.getDefaultSharedPreferences(context).edit {
putBoolean(PREF_LOAD_ON_WIFI, newLoadOnWifi)
}
if (loadFrequencySeconds > 0) {
ArtworkLoadWorker.enqueuePeriodic(context, loadFrequencySeconds, newLoadOnWifi)
}
}
get() = PreferenceManager.getDefaultSharedPreferences(context)
.getBoolean(PREF_LOAD_ON_WIFI, DEFAULT_LOAD_ON_WIFI)
init {
contentObserver = object : ContentObserver(Handler(Looper.getMainLooper())) {
override fun onChange(selfChange: Boolean, uri: Uri?) {
if (BuildConfig.DEBUG) {
Log.d(TAG, "onChange for $uri")
}
ProviderChangedWorker.enqueueChanged(context)
}
}
}
override fun onActive() {
if (BuildConfig.DEBUG) {
Log.d(TAG, "ProviderManager became active")
}
// Register for package change events
val packageChangeFilter = IntentFilter().apply {
addDataScheme("package")
addAction(Intent.ACTION_PACKAGE_ADDED)
addAction(Intent.ACTION_PACKAGE_CHANGED)
addAction(Intent.ACTION_PACKAGE_REPLACED)
addAction(Intent.ACTION_PACKAGE_REMOVED)
}
context.registerReceiver(packageChangeReceiver, packageChangeFilter)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
ProviderChangedWorker.activeListeningStateChanged(context, true)
}
providerLiveData.observeForever(this)
artworkLiveData.observeForever(artworkObserver)
startArtworkLoad()
}
@OptIn(DelicateCoroutinesApi::class)
private fun runIfValid(provider: Provider?, block: (provider: Provider) -> Unit) {
if (provider != null) {
val pm = context.packageManager
@Suppress("DEPRECATION")
if (pm.resolveContentProvider(provider.authority, 0) != null) {
// resolveContentProvider succeeded, so it is a valid ContentProvider
block(provider)
} else {
// Invalid ContentProvider, remove it from the ProviderDao
GlobalScope.launch {
if (BuildConfig.DEBUG) {
Log.w(TAG, "Invalid provider ${provider.authority}")
}
MuzeiDatabase.getInstance(context).providerDao().delete(provider)
}
}
}
}
private fun startArtworkLoad() {
if (hasActiveObservers()) {
runIfValid(value) { currentSource ->
if (BuildConfig.DEBUG) {
Log.d(TAG, "Starting artwork load")
}
// Listen for MuzeiArtProvider changes
val contentUri = ProviderContract.getContentUri(currentSource.authority)
context.contentResolver.registerContentObserver(
contentUri, true, contentObserver)
ProviderChangedWorker.enqueueSelected(context)
}
}
}
override fun onChanged(newProvider: Provider?) {
val existingProvider = value
value = newProvider
runIfValid(newProvider) { provider ->
if (existingProvider == null || provider.authority != existingProvider.authority) {
if (BuildConfig.DEBUG) {
Log.d(TAG, "Provider changed to ${provider.authority}")
}
startArtworkLoad()
}
}
}
override fun onInactive() {
nextArtworkJob?.cancel()
artworkLiveData.removeObserver(artworkObserver)
providerLiveData.removeObserver(this)
context.contentResolver.unregisterContentObserver(contentObserver)
ArtworkLoadWorker.cancelPeriodic(context)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
ProviderChangedWorker.activeListeningStateChanged(context, false)
}
context.unregisterReceiver(packageChangeReceiver)
if (BuildConfig.DEBUG) {
Log.d(TAG, "ProviderManager is now inactive")
}
}
fun nextArtwork() {
ArtworkLoadWorker.enqueueNext(context)
}
} | apache-2.0 | 4da7290470d1eecb13161f9d5f239a18 | 39.197232 | 95 | 0.636278 | 5.239513 | false | false | false | false |
code-helix/slatekit | src/lib/kotlin/slatekit-entities/src/main/kotlin/slatekit/entities/mapper/EntityEncoder.kt | 1 | 8936 | package slatekit.entities.mapper
import org.threeten.bp.*
import slatekit.common.DateTime
import slatekit.common.EnumLike
import slatekit.common.crypto.Encryptor
import slatekit.common.data.DataAction
import slatekit.common.data.DataType
import slatekit.common.data.Value
import slatekit.common.data.Values
import slatekit.common.ids.UPID
import slatekit.data.core.Meta
import slatekit.data.encoders.Encoders
import slatekit.entities.Consts
import slatekit.meta.kClass
import slatekit.meta.models.Model
import slatekit.meta.models.ModelField
import slatekit.query.QueryEncoder
import kotlin.reflect.full.memberProperties
open class EntityEncoder<TId, T>(val model: Model,
val meta: Meta<TId, T>,
val settings: EntitySettings = EntitySettings(true),
val encryptor: Encryptor? = null,
val encoders: Encoders<TId, T> = Encoders(settings.utcTime)) : Encoder<TId, T> where TId : kotlin.Comparable<TId>, T : Any {
/**
* Gets all the column names mapped to the field names
*/
protected val cols: List<String> by lazy { model.fields.map { it.storedName } }
/**
* Primary Key / identity field
*/
protected val idCol = model.idField!!
/**
* Encodes the item into @see[slatekit.common.data.Values] which
* contains a simple list of key/value pairs
*/
override fun encode(item: T, action: DataAction, enc: Encryptor?): Values {
return mapFields(null, item, model, enc)
}
/**
* 1. is optimized for performance of the model to sql mappings
* 2. is recursive to support embedded objects in a table/model
* 3. handles the construction of sql for both inserts/updates
*
* NOTE: For a simple model, only this 1 function call is required to
* generate the sql for inserts/updates, allowing 1 record = 1 function call
*/
private fun mapFields(prefix: String?, item: Any, model: Model, enc: Encryptor? = null): List<Value> {
val converted = mutableListOf<Value>()
val len = model.fields.size
for (ndx in 0 until len) {
val mapping = model.fields[ndx]
val isIdCol = mapping == model.idField
val isFieldMapped = !isIdCol
if (isFieldMapped) {
// Column name e.g first = 'first'
// Also for sub-objects
// Convert to sql value
val data = toSql(prefix, mapping, item, enc)
// Build up list of values
when (data) {
is Value -> converted.add(data)
is List<*> -> data.forEach {
when (it) {
is Value -> converted.add(it)
else -> {
val col = prefix?.let { meta.encode(composite(it, mapping.storedName)) } ?: meta.encode(mapping.storedName)
converted.add(Value(col, DataType.DTString, buildValue(col, it ?: "", false)))
}
}
}
else -> {
val col = prefix?.let { meta.encode(composite(it, mapping.storedName)) } ?: meta.encode(mapping.storedName)
converted.add(Value(col, mapping.dataTpe, buildValue(col, data, false)))
}
}
}
}
return converted.toList()
}
/**
* Builds the value as either "'john'" or "first='john'"
* which is needed for insert/update
*/
private inline fun buildValue(col: String, data: Any, useKeyValue: Boolean): String {
return if (useKeyValue) "$col=$data" else data.toString()
}
/**
* Converts a single model field value into either:
* 1. a single sql string value
* 2. a list of sql string value ( used for embedded objects )
*/
private inline fun toSql(prefix: String?, mapping: ModelField, item: Any, enc: Encryptor?): Any {
val qualifiedName = prefix?.let { composite(it, mapping.storedName) } ?: mapping.storedName
val columnName = meta.encode(qualifiedName)
// =======================================================
// NOTE: Refactor this to use pattern matching ?
// Similar to the Mapper class but reversed
val data = if (mapping.dataTpe == DataType.DTString) {
val sVal = getValue(item, qualifiedName, mapping) as String?
val sValEnc = when {
!mapping.encrypt -> sVal
sVal == null -> sVal
enc != null -> enc.encrypt(sVal)
encryptor != null -> encryptor?.encrypt(sVal)
else -> sVal
}
encoders.strings.convert(columnName, sValEnc)
} else if (mapping.dataTpe == DataType.DTBool) {
val raw = getValue(item, qualifiedName, mapping) as Boolean?
encoders.bools.convert(columnName, raw)
} else if (mapping.dataTpe == DataType.DTShort) {
val raw = getValue(item, qualifiedName, mapping) as Short?
encoders.shorts.convert(columnName, raw)
} else if (mapping.dataTpe == DataType.DTInt) {
val raw = getValue(item, qualifiedName, mapping) as Int?
encoders.ints.convert(columnName, raw)
} else if (mapping.dataTpe == DataType.DTLong) {
val raw = getValue(item, qualifiedName, mapping) as Long?
encoders.longs.convert(columnName, raw)
} else if (mapping.dataTpe == DataType.DTFloat) {
val raw = getValue(item, qualifiedName, mapping) as Float?
encoders.floats.convert(columnName, raw)
} else if (mapping.dataTpe == DataType.DTDouble) {
val raw = getValue(item, qualifiedName, mapping) as Double?
encoders.doubles.convert(columnName, raw)
} else if (mapping.dataTpe == DataType.DTDateTime) {
val dt = getDateTime(item, mapping, qualifiedName, columnName)
encoders.dateTimes.convert(columnName, dt)
} else if (mapping.dataTpe == DataType.DTLocalDate) {
val raw = getValue(item, qualifiedName, mapping) as LocalDate?
encoders.localDates.convert(columnName, raw)
} else if (mapping.dataTpe == DataType.DTLocalTime) {
val raw = getValue(item, qualifiedName, mapping) as LocalTime?
encoders.localTimes.convert(columnName, raw)
} else if (mapping.dataTpe == DataType.DTLocalDateTime) {
val raw = getValue(item, qualifiedName, mapping) as LocalDateTime?
encoders.localDateTimes.convert(columnName, raw)
} else if (mapping.dataTpe == DataType.DTZonedDateTime) {
val dt = getDateTime(item, mapping, qualifiedName, columnName)
encoders.zonedDateTimes.convert(columnName, dt)
} else if (mapping.dataTpe == DataType.DTInstant) {
val raw = getValue(item, qualifiedName, mapping) as Instant?
encoders.instants.convert(columnName, raw)
} else if (mapping.dataTpe == DataType.DTUUID) {
val raw = getValue(item, qualifiedName, mapping) as java.util.UUID?
encoders.uuids.convert(columnName, raw)
} else if (mapping.dataTpe == DataType.DTUPID) {
val raw = getValue(item, qualifiedName, mapping) as UPID?
encoders.upids.convert(columnName, raw)
} else if (mapping.isEnum) {
val raw = getValue(item, qualifiedName, mapping) as EnumLike
encoders.enums.convert(columnName, raw)
} else if (mapping.model != null) {
val subObject = getValue(item, qualifiedName, mapping)
subObject?.let { mapFields(mapping.name, subObject, mapping.model!!, enc) } ?: Consts.NULL
} else { // other object
val objVal = getValue(item, qualifiedName, mapping)
val data = objVal?.toString() ?: ""
val txtValue = "'" + QueryEncoder.ensureValue(data) + "'"
Value(columnName, DataType.DTString, objVal, txtValue)
}
return data
}
protected open fun getValue(inst:Any, qualifiedName:String, mapping: ModelField): Any? {
return when(val prop = mapping.prop) {
null -> {
val item = inst.kClass.memberProperties.find { it.name == mapping.name }
item?.getter?.call(inst)
}
else -> {
prop.getter.call(inst)
}
}
}
protected open fun getDateTime(item: Any, mapping: ModelField, qualifiedName: String, columnName:String):DateTime? {
val dt = getValue(item, qualifiedName, mapping) as DateTime?
return dt
}
private inline fun composite(prefix:String, name:String):String {
return prefix + "_" + name
}
}
| apache-2.0 | 813db9676377d06959d6f9b836388a25 | 43.457711 | 157 | 0.592211 | 4.447984 | false | false | false | false |
smmribeiro/intellij-community | python/python-psi-impl/src/com/jetbrains/python/inspections/PyDunderSlotsInspection.kt | 2 | 2906 | // Copyright 2000-2017 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.jetbrains.python.inspections
import com.intellij.codeInspection.LocalInspectionToolSession
import com.intellij.codeInspection.ProblemsHolder
import com.intellij.psi.PsiElementVisitor
import com.jetbrains.python.PyNames
import com.jetbrains.python.PyPsiBundle
import com.jetbrains.python.psi.*
import com.jetbrains.python.psi.impl.PyPsiUtils
import com.jetbrains.python.psi.types.PyClassType
import com.jetbrains.python.psi.types.TypeEvalContext
class PyDunderSlotsInspection : PyInspection() {
override fun buildVisitor(holder: ProblemsHolder,
isOnTheFly: Boolean,
session: LocalInspectionToolSession): PsiElementVisitor = Visitor(
holder,PyInspectionVisitor.getContext(session))
private class Visitor(holder: ProblemsHolder, context: TypeEvalContext) : PyInspectionVisitor(holder, context) {
override fun visitPyClass(node: PyClass) {
super.visitPyClass(node)
if (!LanguageLevel.forElement(node).isPython2) {
val slots = findSlotsValue(node)
when (slots) {
is PySequenceExpression -> slots
.elements
.asSequence()
.filterIsInstance<PyStringLiteralExpression>()
.forEach {
processSlot(node, it)
}
is PyStringLiteralExpression -> processSlot(node, slots)
}
}
}
override fun visitPyTargetExpression(node: PyTargetExpression) {
super.visitPyTargetExpression(node)
checkAttributeExpression(node)
}
private fun findSlotsValue(pyClass: PyClass): PyExpression? {
val target = pyClass.findClassAttribute(PyNames.SLOTS, false, myTypeEvalContext)
val value = target?.findAssignedValue()
return PyPsiUtils.flattenParens(value)
}
private fun processSlot(pyClass: PyClass, slot: PyStringLiteralExpression) {
val name = slot.stringValue
val classAttribute = pyClass.findClassAttribute(name, false, myTypeEvalContext)
if (classAttribute != null && classAttribute.hasAssignedValue()) {
registerProblem(slot, PyPsiBundle.message("INSP.dunder.slots.name.in.slots.conflicts.with.class.variable", name))
}
}
private fun checkAttributeExpression(target: PyTargetExpression) {
val targetName = target.name
val qualifier = target.qualifier
if (targetName == null || qualifier == null) {
return
}
val qualifierType = myTypeEvalContext.getType(qualifier)
if (qualifierType is PyClassType && !qualifierType.isAttributeWritable(targetName, myTypeEvalContext)) {
registerProblem(target, PyPsiBundle.message("INSP.dunder.slots.class.object.attribute.read.only", qualifierType.name, targetName))
}
}
}
}
| apache-2.0 | 4434585d48d619aa9d7b67f54c4fea83 | 35.78481 | 140 | 0.711631 | 4.900506 | false | false | false | false |
smmribeiro/intellij-community | platform/configuration-store-impl/src/ProjectSaveSessionProducerManager.kt | 7 | 3449 | // 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.configurationStore
import com.intellij.notification.Notifications
import com.intellij.notification.NotificationsManager
import com.intellij.openapi.application.runWriteAction
import com.intellij.openapi.components.impl.stores.SaveSessionAndFile
import com.intellij.openapi.components.serviceIfCreated
import com.intellij.openapi.project.Project
import com.intellij.openapi.project.impl.ProjectManagerImpl.UnableToSaveProjectNotification
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.util.SmartList
import com.intellij.util.containers.mapSmart
import org.jetbrains.annotations.ApiStatus
@ApiStatus.Internal
open class ProjectSaveSessionProducerManager(protected val project: Project) : SaveSessionProducerManager() {
suspend fun saveWithAdditionalSaveSessions(extraSessions: List<SaveSession>): SaveResult {
val saveSessions = SmartList<SaveSession>()
collectSaveSessions(saveSessions)
if (saveSessions.isEmpty() && extraSessions.isEmpty()) {
return SaveResult.EMPTY
}
val saveResult = withEdtContext(project) {
runWriteAction {
val r = SaveResult()
saveSessions(extraSessions, r)
saveSessions(saveSessions, r)
r
}
}
validate(saveResult)
return saveResult
}
private suspend fun validate(saveResult: SaveResult) {
val notifications = getUnableToSaveNotifications()
val readonlyFiles = saveResult.readonlyFiles
if (readonlyFiles.isEmpty()) {
notifications.forEach { it.expire() }
return
}
if (notifications.isNotEmpty()) {
throw UnresolvedReadOnlyFilesException(readonlyFiles.mapSmart { it.file })
}
val status = ensureFilesWritable(project, getFilesList(readonlyFiles))
if (status.hasReadonlyFiles()) {
val unresolvedReadOnlyFiles = status.readonlyFiles.toList()
dropUnableToSaveProjectNotification(project, unresolvedReadOnlyFiles)
saveResult.addError(UnresolvedReadOnlyFilesException(unresolvedReadOnlyFiles))
return
}
val oldList = readonlyFiles.toTypedArray()
readonlyFiles.clear()
withEdtContext(project) {
runWriteAction {
val r = SaveResult()
for (entry in oldList) {
executeSave(entry.session, r)
}
r
}
}.appendTo(saveResult)
if (readonlyFiles.isNotEmpty()) {
dropUnableToSaveProjectNotification(project, getFilesList(readonlyFiles))
saveResult.addError(UnresolvedReadOnlyFilesException(readonlyFiles.mapSmart { it.file }))
}
}
private fun dropUnableToSaveProjectNotification(project: Project, readOnlyFiles: List<VirtualFile>) {
val notifications = getUnableToSaveNotifications()
if (notifications.isEmpty()) {
Notifications.Bus.notify(UnableToSaveProjectNotification(project, readOnlyFiles), project)
}
else {
notifications[0].setFiles(readOnlyFiles)
}
}
private fun getUnableToSaveNotifications(): Array<out UnableToSaveProjectNotification> {
val notificationManager = serviceIfCreated<NotificationsManager>() ?: return emptyArray()
return notificationManager.getNotificationsOfType(UnableToSaveProjectNotification::class.java, project)
}
}
private fun getFilesList(readonlyFiles: List<SaveSessionAndFile>) = readonlyFiles.mapSmart { it.file } | apache-2.0 | 2bd45813f06300d8da509c97ae62808b | 36.912088 | 140 | 0.757321 | 5.178679 | false | false | false | false |
smmribeiro/intellij-community | platform/script-debugger/backend/src/debugger/values/ValueManager.kt | 16 | 1400 | /*
* 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.debugger.values
import org.jetbrains.concurrency.Obsolescent
import java.util.concurrent.atomic.AtomicInteger
/**
* The main idea of this class - don't create value for remote value handle if already exists. So,
* implementation of this class keep map of value to remote value handle.
* Also, this class maintains cache timestamp.
* Currently WIP implementation doesn't keep such map due to protocol issue. But V8 does.
*/
abstract class ValueManager() : Obsolescent {
private val cacheStamp = AtomicInteger()
@Volatile private var obsolete = false
open fun clearCaches() {
cacheStamp.incrementAndGet()
}
fun getCacheStamp(): Int = cacheStamp.get()
final override fun isObsolete(): Boolean = obsolete
fun markObsolete() {
obsolete = true
}
} | apache-2.0 | 397cd09d1c37a5a9ab0b586481d5e234 | 31.581395 | 98 | 0.744286 | 4.307692 | false | false | false | false |
jotomo/AndroidAPS | app/src/main/java/info/nightscout/androidaps/setupwizard/elements/SWEditUrl.kt | 1 | 2113 | package info.nightscout.androidaps.setupwizard.elements
import android.graphics.Typeface
import android.text.Editable
import android.text.InputType
import android.text.TextWatcher
import android.util.Patterns
import android.view.View
import android.widget.EditText
import android.widget.LinearLayout
import android.widget.TextView
import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.R
import info.nightscout.androidaps.setupwizard.events.EventSWLabel
class SWEditUrl(injector: HasAndroidInjector) : SWItem(injector, Type.URL) {
private var updateDelay = 0L
override fun generateDialog(layout: LinearLayout) {
val context = layout.context
val l = TextView(context)
l.id = View.generateViewId()
label?.let { l.setText(it) }
l.setTypeface(l.typeface, Typeface.BOLD)
layout.addView(l)
val c = TextView(context)
c.id = View.generateViewId()
comment?.let { c.setText(it) }
c.setTypeface(c.typeface, Typeface.ITALIC)
layout.addView(c)
val editText = EditText(context)
editText.id = View.generateViewId()
editText.inputType = InputType.TYPE_CLASS_TEXT
editText.maxLines = 1
editText.setText(sp.getString(preferenceId, ""))
layout.addView(editText)
super.generateDialog(layout)
editText.addTextChangedListener(object : TextWatcher {
override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {}
override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {
if (Patterns.WEB_URL.matcher(s).matches()) save(s.toString(), updateDelay.toLong()) else rxBus.send(EventSWLabel(resourceHelper.gs(R.string.error_url_not_valid)))
}
override fun afterTextChanged(s: Editable) {}
})
}
fun preferenceId(preferenceId: Int): SWEditUrl {
this.preferenceId = preferenceId
return this
}
fun updateDelay(updateDelay: Long): SWEditUrl {
this.updateDelay = updateDelay
return this
}
} | agpl-3.0 | a60150ef67463e183f17952abe4f1021 | 36.087719 | 178 | 0.690961 | 4.347737 | false | false | false | false |
cout970/Modeler | src/main/kotlin/com/cout970/modeler/core/helpers/TransformationHelper.kt | 1 | 15657 | package com.cout970.modeler.core.helpers
import com.cout970.matrix.api.IMatrix4
import com.cout970.modeler.api.model.IModel
import com.cout970.modeler.api.model.ITransformation
import com.cout970.modeler.api.model.`object`.IObject
import com.cout970.modeler.api.model.`object`.IObjectCube
import com.cout970.modeler.api.model.mesh.IMesh
import com.cout970.modeler.api.model.selection.ISelection
import com.cout970.modeler.api.model.selection.SelectionType
import com.cout970.modeler.api.model.selection.toObjectRef
import com.cout970.modeler.core.model.*
import com.cout970.modeler.core.model.mesh.FaceIndex
import com.cout970.modeler.core.model.mesh.Mesh
import com.cout970.modeler.render.tool.Animator
import com.cout970.modeler.util.*
import com.cout970.vector.api.IVector2
import com.cout970.vector.api.IVector3
import com.cout970.vector.extensions.*
import org.joml.Matrix4d
import org.joml.Vector4d
/**
* Created by cout970 on 2017/02/11.
*/
object TransformationHelper {
fun transformLocal(source: IModel, sel: ISelection, animator: Animator, transform: ITransformation): IModel {
return when (sel.selectionType) {
SelectionType.OBJECT -> {
applyTransformation(source, sel, animator) { obj, inv ->
val t = inv.invert() + transform + inv
obj.withTransformation(obj.transformation + t)
}
}
SelectionType.FACE -> {
applyTransformation(source, sel, animator) { obj, inv ->
val indices: Set<Int> = sel.faces
.filter { it.objectId == obj.id }
.map { obj.mesh.faces[it.faceIndex] }
.flatMap { it.pos }
.toSet()
val t = inv.invert() + transform + inv
val local = obj.transformation + t + obj.transformation.invert()
val newMesh = transformMesh(obj, indices, local.matrix)
obj.withMesh(newMesh)
}
}
SelectionType.EDGE -> {
applyTransformation(source, sel, animator) { obj, inv ->
val indices: Set<Int> = sel.edges
.filter { it.objectId == obj.id }
.flatMap { listOf(it.firstIndex, it.secondIndex) }
.toSet()
val t = inv.invert() + transform + inv
val local = obj.transformation + t + obj.transformation.invert()
val newMesh = transformMesh(obj, indices, local.matrix)
obj.withMesh(newMesh)
}
}
SelectionType.VERTEX -> {
applyTransformation(source, sel, animator) { obj, inv ->
val indices: Set<Int> = sel.pos
.filter { it.objectId == obj.id }
.map { it.posIndex }
.toSet()
val t = inv.invert() + transform + inv
val local = obj.transformation + t + obj.transformation.invert()
val newMesh = transformMesh(obj, indices, local.matrix)
obj.withMesh(newMesh)
}
}
}
}
fun scaleLocal(source: IModel, sel: ISelection, animator: Animator, vector: IVector3, offset: Float): IModel {
fun calculateTransform(obj: IObject, inv: ITransformation): ITransformation {
val trs = obj.transformation.toTRS()
val dir = (inv.invert() + TRSTransformation(vector) + inv).toTRS().translation
val local = trs.rotation.invert().transform(dir)
val (scale, translation) = getScaleAndTranslation(local)
val finalTranslation = trs.rotation.transform(translation)
return trs.copy(
translation = trs.translation + finalTranslation * offset,
scale = (trs.scale + scale * offset).max(Vector3.ZERO)
)
}
return when (sel.selectionType) {
SelectionType.OBJECT -> {
applyTransformation(source, sel, animator) { obj, inv ->
obj.withTransformation(calculateTransform(obj, inv))
}
}
SelectionType.FACE -> {
applyTransformation(source, sel, animator) { obj, inv ->
val indices: Set<Int> = sel.faces
.filter { it.objectId == obj.id }
.map { obj.mesh.faces[it.faceIndex] }
.flatMap { it.pos }
.toSet()
val trs = obj.transformation.toTRS()
val transform = calculateTransform(obj, inv) + trs.invert()
val newMesh = transformMesh(obj, indices, transform.matrix)
obj.withMesh(newMesh)
}
}
SelectionType.EDGE -> {
applyTransformation(source, sel, animator) { obj, inv ->
val indices: Set<Int> = sel.edges
.filter { it.objectId == obj.id }
.flatMap { listOf(it.firstIndex, it.secondIndex) }
.toSet()
val trs = obj.transformation.toTRS()
val transform = calculateTransform(obj, inv) + trs.invert()
val newMesh = transformMesh(obj, indices, transform.matrix)
obj.withMesh(newMesh)
}
}
SelectionType.VERTEX -> {
applyTransformation(source, sel, animator) { obj, inv ->
val indices: Set<Int> = sel.pos
.filter { it.objectId == obj.id }
.map { it.posIndex }
.toSet()
val trs = obj.transformation.toTRS()
val transform = calculateTransform(obj, inv) + trs.invert()
val newMesh = transformMesh(obj, indices, transform.matrix)
obj.withMesh(newMesh)
}
}
}
}
fun getScaleAndTranslation(vec: IVector3): Pair<IVector3, IVector3> {
val x = vec.xd >= 0
val y = vec.yd >= 0
val z = vec.zd >= 0
return when {
!x && !y && !z -> vec3Of(-vec.xd, -vec.yd, -vec.zd) to vec3Of(vec.xd, vec.yd, vec.zd)
!x && !y && z -> vec3Of(-vec.xd, -vec.yd, vec.zd) to vec3Of(vec.xd, vec.yd, 0)
!x && y && !z -> vec3Of(-vec.xd, vec.yd, -vec.zd) to vec3Of(vec.xd, 0, vec.zd)
!x && y && z -> vec3Of(-vec.xd, vec.yd, vec.zd) to vec3Of(vec.xd, 0, 0)
x && !y && !z -> vec3Of(vec.xd, -vec.yd, -vec.zd) to vec3Of(0, vec.yd, vec.zd)
x && !y && z -> vec3Of(vec.xd, -vec.yd, vec.zd) to vec3Of(0, vec.yd, 0)
x && y && !z -> vec3Of(vec.xd, vec.yd, -vec.zd) to vec3Of(0, 0, vec.zd)
x && y && z -> vec3Of(vec.xd, vec.yd, vec.zd) to vec3Of(0, 0, 0)
else -> error("x: $x, y: $y, z: $z")
}
}
fun translateTexture(source: IModel, sel: ISelection, translation: IVector2): IModel {
val transform = { it: IVector2 -> it + translation }
return when (sel.selectionType) {
SelectionType.OBJECT -> {
val objRefs = sel.objects.toSet()
return source.modifyObjects(objRefs) { _, obj ->
if (obj is IObjectCube) {
val newOffset = obj.textureOffset + translation * obj.textureSize
obj.withTextureOffset(newOffset)
} else {
val newMesh = transformMeshTexture(obj, obj.mesh.tex.indices.toSet(), transform)
obj.withMesh(newMesh)
}
}
}
SelectionType.FACE -> transformTextureFaces(source, sel, transform)
SelectionType.EDGE -> transformTextureEdges(source, sel, transform)
SelectionType.VERTEX -> transformTextureVertex(source, sel, transform)
}
}
fun rotateTexture(source: IModel, sel: ISelection, pivot: IVector2, rotation: Double): IModel {
val matrix = TRSTransformation.fromRotationPivot(
pivot.toVector3(0.0), vec3Of(0.0, 0.0, rotation)
).matrix.toJOML()
val transform = { it: IVector2 -> matrix.transformVertex(it) }
return when (sel.selectionType) {
SelectionType.OBJECT -> transformTextureObjects(source, sel, transform)
SelectionType.FACE -> transformTextureFaces(source, sel, transform)
SelectionType.EDGE -> transformTextureEdges(source, sel, transform)
SelectionType.VERTEX -> transformTextureVertex(source, sel, transform)
}
}
fun scaleTexture(source: IModel, sel: ISelection, start: IVector2, end: IVector2, translation: IVector2, axis: IVector2): IModel {
val size = end - start
val offset = translation * axis / size
val (_, move) = getScaleAndTranslation(axis.toVector3(0))
val addition = -start + size * move.toVector2()
println("addition: $addition, offset: $offset")
println("ratio1: ${size.xd / size.yd}, ratio2: ${offset.xd / offset.yd}")
val transform = { point: IVector2 ->
point + (point + addition) * offset
}
return when (sel.selectionType) {
SelectionType.OBJECT -> transformTextureObjects(source, sel, transform)
SelectionType.FACE -> transformTextureFaces(source, sel, transform)
SelectionType.EDGE -> transformTextureEdges(source, sel, transform)
SelectionType.VERTEX -> transformTextureVertex(source, sel, transform)
}
}
private fun applyTransformation(source: IModel, sel: ISelection, animator: Animator, func: (IObject, ITransformation) -> IObject): IModel {
val objRefs = when (sel.selectionType) {
SelectionType.OBJECT -> sel.objects.toSet()
SelectionType.FACE -> sel.faces.map { it.toObjectRef() }.toSet()
SelectionType.EDGE -> sel.edges.map { it.toObjectRef() }.toSet()
SelectionType.VERTEX -> sel.pos.map { it.toObjectRef() }.toSet()
}
return source.modifyObjects(objRefs) { _, obj ->
val mat = obj.getParentGlobalTransform(source, animator)
val inv = mat.matrix.toJOML().invert().toIMatrix()
func(obj, TRSTransformation.fromMatrix(inv))
}
}
fun transformTextureObjects(source: IModel, sel: ISelection, transform: (IVector2) -> IVector2): IModel {
val objRefs = sel.objects.toSet()
return source.modifyObjects(objRefs) { _, obj ->
val newMesh = transformMeshTexture(obj, obj.mesh.tex.indices.toSet(), transform)
obj.withMesh(newMesh)
}
}
fun transformTextureFaces(source: IModel, sel: ISelection, transform: (IVector2) -> IVector2): IModel {
val objRefs = sel.faces.map { it.toObjectRef() }.toSet()
return source.modifyObjects(objRefs) { ref, obj ->
val indices: Set<Int> = sel.faces
.filter { it.toObjectRef() == ref }
.map { obj.mesh.faces[it.faceIndex] }
.flatMap { it.tex }
.toSet()
val newMesh = transformMeshTexture(obj, indices, transform)
obj.withMesh(newMesh)
}
}
fun transformTextureEdges(source: IModel, sel: ISelection, transform: (IVector2) -> IVector2): IModel {
val objRefs = sel.edges.map { it.toObjectRef() }.toSet()
return source.modifyObjects(objRefs) { ref, obj ->
val indices: Set<Int> = sel.edges
.filter { it.toObjectRef() == ref }
.flatMap { listOf(it.firstIndex, it.secondIndex) }
.toSet()
val newMesh = transformMeshTexture(obj, indices, transform)
obj.withMesh(newMesh)
}
}
fun transformTextureVertex(source: IModel, sel: ISelection, transform: (IVector2) -> IVector2): IModel {
val objRefs = sel.pos.map { it.toObjectRef() }.toSet()
return source.modifyObjects(objRefs) { ref, obj ->
val indices: Set<Int> = sel.pos
.filter { it.toObjectRef() == ref }
.map { it.posIndex }
.toSet()
val newMesh = transformMeshTexture(obj, indices, transform)
obj.withMesh(newMesh)
}
}
fun transformMesh(obj: IObject, indices: Set<Int>, transform: IMatrix4): IMesh {
val newPos: List<IVector3> = obj.mesh.pos.mapIndexed { index, it ->
if (index in indices) transform.transformVertex(it) else it
}
return Mesh(pos = newPos, tex = obj.mesh.tex, faces = obj.mesh.faces)
}
fun transformMeshTexture(obj: IObject, indices: Set<Int>, transform: (IVector2) -> IVector2): IMesh {
val newTex: List<IVector2> = obj.mesh.tex.mapIndexed { index, it ->
if (index in indices) transform(it) else it
}
return Mesh(pos = obj.mesh.pos, tex = newTex, faces = obj.mesh.faces)
}
fun Matrix4d.transformVertex(it: IVector2): IVector2 {
val vec4 = transform(Vector4d(it.xd, it.yd, 0.0, 1.0))
return vec2Of(vec4.x, vec4.y)
}
fun splitTextures(model: IModel, selection: ISelection): IModel {
return when (selection.selectionType) {
SelectionType.OBJECT -> {
model.modifyObjects(selection::isSelected) { _, obj ->
val faces = obj.mesh.faces
val pos = obj.mesh.pos
val tex = faces.flatMap { face -> face.tex.map { obj.mesh.tex[it] } }
var lastIndex = 0
val newFaces = faces.map { face ->
val startIndex = lastIndex
lastIndex += face.vertexCount
val endIndex = lastIndex
FaceIndex.from(face.pos, (startIndex until endIndex).toList())
}
val newMesh = Mesh(pos, tex, newFaces)
obj.withMesh(newMesh)
}
}
else -> model
}
}
fun scaleTextures(model: IModel, selection: ISelection, scale: Float): IModel {
return when (selection.selectionType) {
SelectionType.OBJECT -> {
model.modifyObjects(selection::isSelected) { _, obj ->
if (obj is IObjectCube) {
obj.withTextureSize(obj.textureSize * scale)
} else {
val tex = obj.mesh.tex.map { it * scale }
val newMesh = Mesh(obj.mesh.pos, tex, obj.mesh.faces)
obj.withMesh(newMesh)
}
}
}
else -> model
}
}
}
fun ITransformation.invert(): TRSTransformation {
return TRSTransformation.fromMatrix(matrix.toJOML().invert().toIMatrix())
}
fun IMatrix4.invert(): IMatrix4 {
return toJOML().invert().toIMatrix()
}
fun IMatrix4.print() {
println("%.2f, %.2f, %.2f, %.2f".format(m00d, m10d, m20d, m30d))
println("%.2f, %.2f, %.2f, %.2f".format(m01d, m11d, m21d, m31d))
println("%.2f, %.2f, %.2f, %.2f".format(m02d, m12d, m22d, m32d))
println("%.2f, %.2f, %.2f, %.2f".format(m03d, m13d, m23d, m33d))
} | gpl-3.0 | 46ff94624da50589acadb02fb4d24b7a | 42.254144 | 143 | 0.546082 | 4.183008 | false | false | false | false |
ex3ndr/telegram-tl | Builder/src/org/telegram/tl/builder/TLSyntax.kt | 1 | 1271 | package org.telegram.tl.builder
/**
* Created with IntelliJ IDEA.
* User: ex3ndr
* Date: 22.10.13
* Time: 19:14
*/
// Main definition
class TLDefinition(
var contructors: List<TLConstructor>,
var methods: List<TLMethod>
)
// Types
abstract class TLType()
class TLTypeRaw(
var name: String
) : TLType()
{
fun toString(): String = name
}
class TLTypeGeneric(
var name: String,
var generics: Array<TLType>) : TLType()
{
fun toString(): String = "Generic<" + name + ">"
}
class TLTypeAny() : TLType()
{
fun toString(): String = "#Any"
}
class TLTypeFunctional(
var name: String
) : TLType()
{
fun toString(): String = "!" + name
}
// Constructors of combined types
class TLConstructor(
var name: String,
var id: Int,
var parameters: List<TLParameter>,
var tlType: TLType
)
{
fun toString(): String = name + "#" + hex(id) + " -> " + tlType.toString();
}
// Methods for RPC calls
class TLMethod(
var name: String,
var id: Int,
var parameters: List<TLParameter>,
var tlType: TLType
)
{
fun toString(): String = name + "#" + hex(id);
}
// Parameters
class TLParameter(
var name: String,
var tlType: TLType
) | mit | 9a8615da68a96a17dbbb2683ea2320dd | 15.736842 | 79 | 0.59166 | 3.435135 | false | false | false | false |
jotomo/AndroidAPS | core/src/main/java/info/nightscout/androidaps/utils/DefaultValueHelper.kt | 1 | 4192 | package info.nightscout.androidaps.utils
import info.nightscout.androidaps.Constants
import info.nightscout.androidaps.core.R
import info.nightscout.androidaps.data.Profile
import info.nightscout.androidaps.interfaces.ProfileFunction
import info.nightscout.androidaps.utils.sharedPreferences.SP
import javax.inject.Inject
import javax.inject.Singleton
@Singleton
open class DefaultValueHelper @Inject constructor(
private val sp: SP,
private val profileFunction: ProfileFunction
) {
/**
* returns the corresponding EatingSoon TempTarget based on the given units (MMOL / MGDL)
*
* @param units
* @return
*/
private fun getDefaultEatingSoonTT(units: String): Double {
return if (Constants.MMOL == units) Constants.defaultEatingSoonTTmmol else Constants.defaultEatingSoonTTmgdl
}
/**
* returns the corresponding Activity TempTarget based on the given units (MMOL / MGDL)
*
* @param units
* @return
*/
private fun getDefaultActivityTT(units: String): Double {
return if (Constants.MMOL == units) Constants.defaultActivityTTmmol else Constants.defaultActivityTTmgdl
}
/**
* returns the corresponding Hypo TempTarget based on the given units (MMOL / MGDL)
*
* @param units
* @return
*/
private fun getDefaultHypoTT(units: String): Double {
return if (Constants.MMOL == units) Constants.defaultHypoTTmmol else Constants.defaultHypoTTmgdl
}
/**
* returns the configured EatingSoon TempTarget, if this is set to 0, the Default-Value is returned.
*
* @return
*/
fun determineEatingSoonTT(): Double {
val units = profileFunction.getUnits()
var value = sp.getDouble(R.string.key_eatingsoon_target, getDefaultEatingSoonTT(units))
value = Profile.toCurrentUnits(profileFunction, value)
return if (value > 0) value else getDefaultEatingSoonTT(units)
}
fun determineEatingSoonTTDuration(): Int {
val value = sp.getInt(R.string.key_eatingsoon_duration, Constants.defaultEatingSoonTTDuration)
return if (value > 0) value else Constants.defaultEatingSoonTTDuration
}
/**
* returns the configured Activity TempTarget, if this is set to 0, the Default-Value is returned.
*
* @return
*/
fun determineActivityTT(): Double {
val units = profileFunction.getUnits()
var value = sp.getDouble(R.string.key_activity_target, getDefaultActivityTT(units))
value = Profile.toCurrentUnits(profileFunction, value)
return if (value > 0) value else getDefaultActivityTT(units)
}
fun determineActivityTTDuration(): Int {
val value = sp.getInt(R.string.key_activity_duration, Constants.defaultActivityTTDuration)
return if (value > 0) value else Constants.defaultActivityTTDuration
}
/**
* returns the configured Hypo TempTarget, if this is set to 0, the Default-Value is returned.
*
* @return
*/
fun determineHypoTT(): Double {
val units = profileFunction.getUnits()
var value = sp.getDouble(R.string.key_hypo_target, getDefaultHypoTT(units))
value = Profile.toCurrentUnits(profileFunction, value)
return if (value > 0) value else getDefaultHypoTT(units)
}
fun determineHypoTTDuration(): Int {
val value = sp.getInt(R.string.key_hypo_duration, Constants.defaultHypoTTDuration)
return if (value > 0) value else Constants.defaultHypoTTDuration
}
var bgTargetLow = 80.0
var bgTargetHigh = 180.0
fun determineHighLine(): Double {
var highLineSetting = sp.getDouble(R.string.key_high_mark, bgTargetHigh)
if (highLineSetting < 1) highLineSetting = Constants.HIGHMARK
highLineSetting = Profile.toCurrentUnits(profileFunction, highLineSetting)
return highLineSetting
}
fun determineLowLine(): Double {
var lowLineSetting = sp.getDouble(R.string.key_low_mark, bgTargetLow)
if (lowLineSetting < 1) lowLineSetting = Constants.LOWMARK
lowLineSetting = Profile.toCurrentUnits(profileFunction, lowLineSetting)
return lowLineSetting
}
} | agpl-3.0 | a5f3c90c3798df3f71d082ba34e5fc35 | 35.780702 | 116 | 0.700382 | 4.142292 | false | false | false | false |
siosio/intellij-community | plugins/kotlin/jvm-debugger/core/src/org/jetbrains/kotlin/idea/debugger/KotlinExceptionFilter.kt | 1 | 9282 | // 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.debugger
import com.intellij.execution.filters.*
import com.intellij.execution.filters.impl.HyperlinkInfoFactoryImpl
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.vfs.LocalFileSystem
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.psi.search.FilenameIndex
import com.intellij.psi.search.GlobalSearchScope
import org.jetbrains.kotlin.idea.debugger.evaluate.KotlinDebuggerCaches
import org.jetbrains.kotlin.idea.util.application.runReadAction
import org.jetbrains.kotlin.resolve.jvm.JvmClassName
import java.lang.Math.max
import java.util.*
import java.util.regex.Pattern
class KotlinExceptionFilterFactory : ExceptionFilterFactory {
override fun create(searchScope: GlobalSearchScope): Filter {
return KotlinExceptionFilter(searchScope)
}
}
class KotlinExceptionFilter(private val searchScope: GlobalSearchScope) : Filter {
private val exceptionFilter = ExceptionFilter(searchScope)
override fun applyFilter(line: String, entireLength: Int): Filter.Result? {
return runReadAction {
val result = exceptionFilter.applyFilter(line, entireLength)
if (result == null) parseNativeStackTraceLine(line, entireLength) else patchResult(result, line)
}
}
private fun patchResult(result: Filter.Result, line: String): Filter.Result {
val newHyperlinkInfo = createHyperlinkInfo(line, result) ?: return result
return Filter.Result(result.resultItems.map {
Filter.ResultItem(it.highlightStartOffset, it.highlightEndOffset, newHyperlinkInfo, it.getHighlightAttributes())
})
}
private fun createHyperlinkInfo(line: String, defaultResult: Filter.Result): HyperlinkInfo? {
val project = searchScope.project ?: return null
val stackTraceElement = parseStackTraceLine(line) ?: return null
// All true classes should be handled correctly in the default ExceptionFilter. Special cases:
// - static facades;
// - package facades / package parts (generated by pre-M13 compiled);
// - local classes (and closures) in top-level function and property declarations.
// - bad line numbers for inline functions
// - already applied smap for inline functions
val fileName = stackTraceElement.fileName ?: return null
if (!DebuggerUtils.isKotlinSourceFile(fileName)) return null
// fullyQualifiedName is of format "package.Class$Inner"
val fullyQualifiedName = stackTraceElement.className
val lineNumber = stackTraceElement.lineNumber - 1
val internalName = fullyQualifiedName.replace('.', '/')
val jvmClassName = JvmClassName.byInternalName(internalName)
val file = DebuggerUtils.findSourceFileForClassIncludeLibrarySources(project, searchScope, jvmClassName, fileName)
if (file == null) {
// File can't be found by class name and file name: this can happen when smap info is already applied.
// Default filter favours looking for file from class name and that can lead to wrong navigation to inline fun call file and
// line from inline function definition.
val defaultLinkFileNames =
defaultResult.resultItems.mapNotNullTo(HashSet()) { (it as? FileHyperlinkInfo)?.descriptor?.file?.name }
if (!defaultLinkFileNames.contains(fileName)) {
val filesByName = FilenameIndex.getFilesByName(project, fileName, searchScope).mapNotNullTo(HashSet()) {
if (!it.isValid) return@mapNotNullTo null
it.virtualFile
}
if (filesByName.isNotEmpty()) {
return if (filesByName.size > 1) {
HyperlinkInfoFactoryImpl.getInstance().createMultipleFilesHyperlinkInfo(filesByName.toList(), lineNumber, project)
} else {
OpenFileHyperlinkInfo(project, filesByName.first(), lineNumber)
}
}
}
return null
}
val virtualFile = file.virtualFile ?: return null
val hyperlinkInfoForInline = createHyperlinks(jvmClassName, virtualFile, lineNumber + 1, project)
if (hyperlinkInfoForInline != null) {
return hyperlinkInfoForInline
}
return OpenFileHyperlinkInfo(project, virtualFile, lineNumber)
}
private fun createHyperlinks(jvmName: JvmClassName, file: VirtualFile, line: Int, project: Project): InlineFunctionHyperLinkInfo? {
if (!isInlineFunctionLineNumber(file, line, project)) return null
val smapData = KotlinDebuggerCaches.getSmapCached(project, jvmName, file) ?: return null
val inlineInfos = arrayListOf<InlineFunctionHyperLinkInfo.InlineInfo>()
val (inlineFunctionBodyFile, inlineFunctionBodyLine) =
mapStacktraceLineToSource(smapData, line, project, SourceLineKind.EXECUTED_LINE, searchScope) ?: return null
inlineInfos.add(
InlineFunctionHyperLinkInfo.InlineInfo.InlineFunctionBodyInfo(
inlineFunctionBodyFile.virtualFile,
inlineFunctionBodyLine
)
)
val inlineFunCallInfo = mapStacktraceLineToSource(smapData, line, project, SourceLineKind.CALL_LINE, searchScope)
if (inlineFunCallInfo != null) {
val (callSiteFile, callSiteLine) = inlineFunCallInfo
inlineInfos.add(InlineFunctionHyperLinkInfo.InlineInfo.CallSiteInfo(callSiteFile.virtualFile, callSiteLine))
}
return InlineFunctionHyperLinkInfo(project, inlineInfos)
}
// Extracts file names from Kotlin Native stacktrace strings like
// "\tat 1 main.kexe\t\t 0x000000010d7cdb4c kfun:package.function(kotlin.Int) + 108 (/Users/user.name/repo_name/file_name.kt:10:27)\n"
// The form is encoded in Kotlin Native code and covered by tests witch are linked here.
private fun parseNativeStackTraceLine(rawLine: String, entireLength: Int): Filter.Result? {
val atPrefix = "at "
val ktExtension = ".kt:"
val project = searchScope.project ?: return null
val line = rawLine.trim()
if (!line.startsWith(atPrefix) && !line.endsWith(')')) {
return null
}
val fileNameBegin = line.lastIndexOf('(') + 1
if (fileNameBegin < 1) { // no parentheses => no file name provided
return null
}
val fileNameEnd = line.indexOf(ktExtension, fileNameBegin) + ktExtension.length - 1
if (fileNameEnd < ktExtension.length - 1) { // no kt file extension => not interested
return null
}
val virtualFile = findFile(line.substring(fileNameBegin, fileNameEnd)) ?: return null
val (lineNumber, columnNumber) = parsLineColumn(line.substring(fileNameEnd + 1, line.lastIndex))
val offset = entireLength - rawLine.length + rawLine.indexOf(atPrefix)
val highlightEndOffset = offset + (if (lineNumber > 0) line.lastIndex else fileNameEnd)
// OpenFileHyperlinkInfo accepts zero-based line number
val hyperLinkInfo = OpenFileHyperlinkInfo(project, virtualFile, max(0, lineNumber - 1), columnNumber)
return Filter.Result(offset + fileNameBegin, highlightEndOffset, hyperLinkInfo)
}
companion object {
// Matches strings like "\tat test.TestPackage$foo$f$1.invoke(a.kt:3)\n"
// or "\tBreakpoint reached at test.TestPackage$foo$f$1.invoke(a.kt:3)\n"
private val STACK_TRACE_ELEMENT_PATTERN = Pattern.compile("^[\\w|\\s]*at\\s+(.+)\\.(.+)\\((.+):(\\d+)\\)\\s*$")
private val LINE_COLUMN_PATTERN = Pattern.compile("(\\d+):(\\d+)")
private fun parseStackTraceLine(line: String): StackTraceElement? {
val matcher = STACK_TRACE_ELEMENT_PATTERN.matcher(line)
if (matcher.matches()) {
val declaringClass = matcher.group(1)
val methodName = matcher.group(2)
val fileName = matcher.group(3)
val lineNumber = matcher.group(4)
//noinspection ConstantConditions
return StackTraceElement(declaringClass, methodName, fileName, Integer.parseInt(lineNumber))
}
return null
}
private fun findFile(fileName: String): VirtualFile? {
if (!DebuggerUtils.isKotlinSourceFile(fileName))
return null
val vfsFileName = FileUtil.toSystemIndependentName(fileName)
return LocalFileSystem.getInstance().findFileByPath(vfsFileName)
}
private fun parsLineColumn(locationLine: String): Pair<Int, Int> {
val matcher = LINE_COLUMN_PATTERN.matcher(locationLine)
if (matcher.matches()) {
val line = Integer.parseInt(matcher.group(1))
val column = Integer.parseInt(matcher.group(2))
return Pair(line, column)
}
return Pair(0, 0)
}
}
}
| apache-2.0 | cc39ba1a7c558ceab61abc7b5b52bb0e | 44.950495 | 158 | 0.67173 | 4.852065 | false | false | false | false |
jwren/intellij-community | plugins/kotlin/gradle/gradle-java/src/org/jetbrains/kotlin/idea/gradleJava/configuration/kpm/KotlinBasicFragmentDataInitializer.kt | 1 | 2974 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.idea.gradleJava.configuration.kpm
import com.intellij.openapi.externalSystem.model.DataNode
import com.intellij.openapi.externalSystem.model.project.ModuleData
import com.intellij.openapi.externalSystem.model.project.ProjectData
import com.intellij.openapi.externalSystem.util.ExternalSystemConstants
import com.intellij.openapi.externalSystem.util.Order
import org.gradle.tooling.model.idea.IdeaModule
import org.jetbrains.kotlin.gradle.kpm.idea.*
import org.jetbrains.kotlin.idea.gradle.configuration.findChildModuleById
import org.jetbrains.kotlin.idea.gradle.configuration.kpm.ModuleDataInitializer
import org.jetbrains.kotlin.idea.projectModel.KotlinPlatform
import org.jetbrains.kotlin.idea.roots.findAll
import org.jetbrains.plugins.gradle.service.project.ProjectResolverContext
@Order(ExternalSystemConstants.UNORDERED + 2)
class KotlinBasicFragmentDataInitializer : ModuleDataInitializer {
override fun initialize(
gradleModule: IdeaModule,
mainModuleNode: DataNode<ModuleData>,
projectDataNode: DataNode<ProjectData>,
resolverCtx: ProjectResolverContext,
initializerContext: ModuleDataInitializer.Context
) {
initializerContext.model?.modules?.flatMap { it.fragments }?.forEach { fragment ->
val moduleId = calculateKotlinFragmentModuleId(gradleModule, fragment.coordinates, resolverCtx)
val fragmentGradleSourceSetDataNode = mainModuleNode.findChildModuleById(moduleId)
?: error("Cannot find GradleSourceSetData node for fragment '$moduleId'")
if (fragmentGradleSourceSetDataNode.findAll(KotlinFragmentData.KEY).isNotEmpty()) return@forEach
val refinesFragmentsIds = fragment.dependencies
.filterIsInstance<IdeaKotlinFragmentDependency>()
.filter { it.type == IdeaKotlinFragmentDependency.Type.Refines }
.map { calculateKotlinFragmentModuleId(gradleModule, it.coordinates, resolverCtx) }
// TODO use platformDetails to calculate more precised platform
KotlinFragmentData(moduleId).apply {
platform = when {
fragment.platforms.all { it.isJvm } -> KotlinPlatform.JVM
fragment.platforms.all { it.isJs } -> KotlinPlatform.JS
fragment.platforms.all { it.isNative } -> KotlinPlatform.NATIVE
else -> platform
}
fragment.platforms.mapNotNullTo(platformDetails) { it.platformDetails }
refinesFragmentIds.addAll(refinesFragmentsIds)
fragmentDependencies.addAll(fragment.dependencies)
languageSettings = fragment.languageSettings
fragmentGradleSourceSetDataNode.createChild(KotlinFragmentData.KEY, this)
}
}
}
} | apache-2.0 | 3ea5843262b4bbb3ed85afd59ef376cb | 54.092593 | 120 | 0.727976 | 5.348921 | false | true | false | false |
vovagrechka/fucking-everything | attic/photlin/src/org/jetbrains/kotlin/js/translate/declaration/EnumTranslator.kt | 1 | 3935 | /*
* Copyright 2010-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.kotlin.js.translate.declaration
import photlinc.*
import org.jetbrains.kotlin.descriptors.ClassDescriptor
import org.jetbrains.kotlin.descriptors.FunctionDescriptor
import org.jetbrains.kotlin.js.backend.ast.*
import org.jetbrains.kotlin.js.translate.context.Namer
import org.jetbrains.kotlin.js.translate.context.TranslationContext
import org.jetbrains.kotlin.js.translate.general.AbstractTranslator
import org.jetbrains.kotlin.js.translate.utils.JsAstUtils
import org.jetbrains.kotlin.resolve.DescriptorUtils
import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameSafe
class EnumTranslator(
context: TranslationContext,
val descriptor: ClassDescriptor,
val entries: List<ClassDescriptor>
) : AbstractTranslator(context) {
fun generateStandardMethods() {
generateValuesFunction()
generateValueOfFunction()
}
private fun generateValuesFunction() {
val function = createFunction(DescriptorUtils.getFunctionByName(descriptor.staticScope, DescriptorUtils.ENUM_VALUES))
val values = entries.map { JsInvocation(JsAstUtils.pureFqn(context().getNameForObjectInstance(it), null)) }
val shit = JsArrayLiteral(values)
val shitVar = JsNameRef("shit").setKind(PHPNameRefKind.VAR)
function.body.statements += JsAstUtils.assignment(shitVar, shit).makeStmt()
function.body.statements += JsReturn(shitVar)
}
private fun generateValueOfFunction() {
val function = createFunction(DescriptorUtils.getFunctionByName(descriptor.staticScope, DescriptorUtils.ENUM_VALUE_OF))
val nameParam = function.scope.declareTemporaryName("name")
function.parameters += JsParameter(nameParam)
val clauses = entries.map { entry ->
JsCase().apply {
caseExpression = context().program().getStringLiteral(entry.name.asString())
statements += JsReturn(JsInvocation(JsAstUtils.pureFqn(context().getNameForObjectInstance(entry), null)))
}
}
val message = JsBinaryOperation(JsBinaryOperator.ADD,
context().program().getStringLiteral("No enum constant ${descriptor.fqNameSafe}."),
nameParam.makeRef())
val throwStatement = JsExpressionStatement(JsInvocation(Namer.throwIllegalStateExceptionFunRef(), message))
if (clauses.isNotEmpty()) {
val defaultCase = JsDefault().apply { statements += throwStatement }
function.body.statements += JsSwitch(nameParam.makeRef(), clauses + defaultCase)
}
else {
function.body.statements += throwStatement
}
}
private fun createFunction(functionDescriptor: FunctionDescriptor): JsFunction {
val function = context().getFunctionObject(functionDescriptor)
function.name = context().getInnerNameForDescriptor(functionDescriptor)
context().addDeclarationStatement(function.makeStmt())
val classRef = context().getInnerReference(descriptor)
val functionRef = function.name.makeRef()
val assignment = JsAstUtils.assignment(JsNameRef(context().getNameForDescriptor(functionDescriptor), classRef), functionRef)
// @possibly-needed
// context().addDeclarationStatement(assignment.makeStmt())
return function
}
} | apache-2.0 | 83c98ce39bc39acfc0b346824e8a4ab7 | 42.252747 | 132 | 0.723253 | 4.840098 | false | false | false | false |
JetBrains/intellij-community | build/tasks/src/org/jetbrains/intellij/build/io/process.kt | 1 | 10330 | // 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", "ReplacePutWithAssignment", "ReplaceGetOrSet")
package org.jetbrains.intellij.build.io
import com.fasterxml.jackson.jr.ob.JSON
import com.intellij.diagnostic.telemetry.useWithScope2
import com.intellij.openapi.util.io.FileUtilRt
import io.opentelemetry.api.common.AttributeKey
import io.opentelemetry.api.trace.Span
import kotlinx.coroutines.*
import org.jetbrains.intellij.build.TraceManager.spanBuilder
import java.io.File
import java.nio.file.Files
import java.nio.file.Path
import kotlin.time.Duration
import kotlin.time.Duration.Companion.milliseconds
import kotlin.time.Duration.Companion.minutes
val DEFAULT_TIMEOUT: Duration = 10.minutes
/**
* Executes a Java class in a forked JVM.
*/
suspend fun runJava(mainClass: String,
args: List<String>,
jvmArgs: List<String> = emptyList(),
classPath: List<String>,
javaExe: Path,
timeout: Duration = DEFAULT_TIMEOUT,
workingDir: Path? = null,
customOutputFile: Path? = null,
onError: (() -> Unit)? = null) {
val jvmArgsWithJson = jvmArgs + "-Dintellij.log.to.json.stdout=true"
spanBuilder("runJava")
.setAttribute("mainClass", mainClass)
.setAttribute(AttributeKey.stringArrayKey("args"), args)
.setAttribute(AttributeKey.stringArrayKey("jvmArgs"), jvmArgsWithJson)
.setAttribute("workingDir", workingDir?.toString() ?: "")
.setAttribute("timeoutMillis", timeout.toString())
.useWithScope2 { span ->
withContext(Dispatchers.IO) {
val toDelete = ArrayList<Path>(3)
var process: Process? = null
try {
val classpathFile = Files.createTempFile("classpath-", ".txt").also(toDelete::add)
val classPathStringBuilder = createClassPathFile(classPath, classpathFile)
val processArgs = createProcessArgs(javaExe = javaExe,
jvmArgs = jvmArgsWithJson,
classpathFile = classpathFile,
mainClass = mainClass,
args = args)
span.setAttribute(AttributeKey.stringArrayKey("processArgs"), processArgs)
val errorOutputFile = Files.createTempFile("error-out-", ".txt").also(toDelete::add)
val outputFile = customOutputFile?.also { customOutputFile.parent?.let { Files.createDirectories(it) } }
?: Files.createTempFile("out-", ".txt").also(toDelete::add)
process = ProcessBuilder(processArgs)
.directory(workingDir?.toFile())
.redirectError(errorOutputFile.toFile())
.redirectOutput(outputFile.toFile())
.start()
span.setAttribute("pid", process.pid())
fun javaRunFailed(reason: String) {
span.setAttribute("classPath", classPathStringBuilder.substring("-classpath".length))
span.setAttribute("output", runCatching { Files.readString(outputFile) }.getOrNull() ?: "output file doesn't exist")
span.setAttribute("errorOutput",
runCatching { Files.readString(errorOutputFile) }.getOrNull() ?: "error output file doesn't exist")
onError?.invoke()
throw RuntimeException("Cannot execute $mainClass: $reason")
}
try {
withTimeout(timeout) {
while (process.isAlive) {
delay(5.milliseconds)
}
}
}
catch (e: TimeoutCancellationException) {
try {
dumpThreads(process.pid())
}
catch (e: Exception) {
span.addEvent("cannot dump threads: ${e.message}")
}
process.destroyForcibly().waitFor()
javaRunFailed(e.message!!)
}
val exitCode = process.exitValue()
if (exitCode != 0) {
javaRunFailed("exitCode=$exitCode")
}
if (customOutputFile == null) {
checkOutput(outputFile = outputFile, span = span, errorConsumer = ::javaRunFailed)
}
}
finally {
process?.waitFor()
toDelete.forEach(FileUtilRt::deleteRecursively)
}
}
}
}
private fun checkOutput(outputFile: Path, span: Span, errorConsumer: (String) -> Unit) {
val out = try {
Files.readString(outputFile)
}
catch (e: NoSuchFieldException) {
span.setAttribute("output", "output file doesn't exist")
return
}
val messages = StringBuilder()
out.lineSequence()
.filter { it.isNotBlank() }
.forEach { line ->
if (line.startsWith('{')) {
val item = JSON.std.mapFrom(line)
val message = (item.get("message") as? String) ?: error("Missing field: 'message' in $line")
val level = (item.get("level") as? String) ?: error("Missing field: 'level' in $line")
messages.append(message).append('\n')
if (level == "SEVERE") {
errorConsumer("Error reported from child process logger: $message")
}
}
else {
messages.append(line).append('\n')
}
}
span.setAttribute("output", messages.toString())
}
private fun createProcessArgs(javaExe: Path,
jvmArgs: List<String>,
classpathFile: Path?,
mainClass: String,
args: List<String>): MutableList<String> {
val processArgs = mutableListOf<String>()
// FIXME: enforce JBR
processArgs.add(javaExe.toString())
processArgs.add("-Djava.awt.headless=true")
processArgs.add("-Dapple.awt.UIElement=true")
processArgs.addAll(jvmArgs)
processArgs.add("@$classpathFile")
processArgs.add(mainClass)
processArgs.addAll(args)
return processArgs
}
private fun createClassPathFile(classPath: List<String>, classpathFile: Path): StringBuilder {
val classPathStringBuilder = StringBuilder()
classPathStringBuilder.append("-classpath").append('\n')
for (s in classPath) {
appendArg(s, classPathStringBuilder)
classPathStringBuilder.append(File.pathSeparator)
}
classPathStringBuilder.setLength(classPathStringBuilder.length - 1)
Files.writeString(classpathFile, classPathStringBuilder)
return classPathStringBuilder
}
fun runProcessBlocking(args: List<String>, workingDir: Path? = null) {
runBlocking {
runProcess(args = args,
workingDir = workingDir,
timeout = DEFAULT_TIMEOUT,
additionalEnvVariables = emptyMap(),
inheritOut = false)
}
}
suspend fun runProcess(args: List<String>,
workingDir: Path? = null,
timeout: Duration = DEFAULT_TIMEOUT,
additionalEnvVariables: Map<String, String> = emptyMap(),
inheritOut: Boolean = false) {
spanBuilder("runProcess")
.setAttribute(AttributeKey.stringArrayKey("args"), args)
.setAttribute("timeoutMillis", timeout.toString())
.useWithScope2 { span ->
withContext(Dispatchers.IO) {
val toDelete = ArrayList<Path>(3)
try {
val errorOutputFile = if (inheritOut) null else Files.createTempFile("error-out-", ".txt").also(toDelete::add)
val outputFile = if (inheritOut) null else Files.createTempFile("out-", ".txt").also(toDelete::add)
val process = ProcessBuilder(args)
.directory(workingDir?.toFile())
.also { builder ->
if (additionalEnvVariables.isNotEmpty()) {
builder.environment().putAll(additionalEnvVariables)
}
if (inheritOut) {
builder.inheritIO()
}
else {
builder.redirectOutput(outputFile!!.toFile())
builder.redirectError(errorOutputFile!!.toFile())
}
}
.start()
val pid = process.pid()
span.setAttribute("pid", pid)
fun errorOccurred() {
if (inheritOut) {
return
}
span.setAttribute("output", runCatching { Files.readString(outputFile) }.getOrNull() ?: "output file doesn't exist")
span.setAttribute("errorOutput",
runCatching { Files.readString(errorOutputFile) }.getOrNull() ?: "error output file doesn't exist")
}
try {
withTimeout(timeout) {
while (process.isAlive) {
delay(5.milliseconds)
}
}
}
catch (e: TimeoutCancellationException) {
process.destroyForcibly().waitFor()
errorOccurred()
throw e
}
val exitCode = process.exitValue()
if (exitCode != 0) {
errorOccurred()
throw RuntimeException("Process $pid finished with exitCode $exitCode)")
}
if (!inheritOut) {
checkOutput(outputFile!!, span) {
errorOccurred()
throw RuntimeException(it)
}
}
}
finally {
toDelete.forEach(FileUtilRt::deleteRecursively)
}
}
}
}
private fun appendArg(value: String, builder: StringBuilder) {
if (!value.any(" #'\"\n\r\t"::contains)) {
builder.append(value)
return
}
for (c in value) {
when (c) {
' ', '#', '\'' -> builder.append('"').append(c).append('"')
'"' -> builder.append("\"\\\"\"")
'\n' -> builder.append("\"\\n\"")
'\r' -> builder.append("\"\\r\"")
'\t' -> builder.append("\"\\t\"")
else -> builder.append(c)
}
}
}
class ProcessRunTimedOut(message: String) : RuntimeException(message)
internal suspend fun dumpThreads(pid: Long) {
val jstack = System.getenv("JAVA_HOME")
?.removeSuffix("/")
?.removeSuffix("\\")
?.let { "$it/bin/jstack" }
?: "jstack"
runProcess(args = listOf(jstack, pid.toString()), inheritOut = true)
} | apache-2.0 | 827e4ecfa0f8bf5bf863ffec85af5dea | 35.896429 | 129 | 0.583543 | 4.847489 | false | false | false | false |
androidx/androidx | lifecycle/lifecycle-livedata-ktx/src/main/java/androidx/lifecycle/FlowLiveData.kt | 3 | 7270 | /*
* Copyright 2019 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
@file:JvmName("FlowLiveDataConversions")
package androidx.lifecycle
import android.os.Build
import androidx.annotation.RequiresApi
import androidx.arch.core.executor.ArchTaskExecutor
import java.time.Duration
import kotlin.coroutines.CoroutineContext
import kotlin.coroutines.EmptyCoroutineContext
import kotlinx.coroutines.DelicateCoroutinesApi
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.channels.awaitClose
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.callbackFlow
import kotlinx.coroutines.flow.conflate
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
/**
* Creates a LiveData that has values collected from the origin [Flow].
*
* If the origin [Flow] is a [StateFlow], then the initial value will be populated
* to the [LiveData]'s value field on the main thread.
*
* The upstream flow collection starts when the returned [LiveData] becomes active
* ([LiveData.onActive]).
* If the [LiveData] becomes inactive ([LiveData.onInactive]) while the flow has not completed,
* the flow collection will be cancelled after [timeoutInMs] milliseconds unless the [LiveData]
* becomes active again before that timeout (to gracefully handle cases like Activity rotation).
*
* After a cancellation, if the [LiveData] becomes active again, the upstream flow collection will
* be re-executed.
*
* If the upstream flow completes successfully *or* is cancelled due to reasons other than
* [LiveData] becoming inactive, it *will not* be re-collected even after [LiveData] goes through
* active inactive cycle.
*
* If flow completes with an exception, then exception will be delivered to the
* [CoroutineExceptionHandler][kotlinx.coroutines.CoroutineExceptionHandler] of provided [context].
* By default [EmptyCoroutineContext] is used to so an exception will be delivered to main's
* thread [UncaughtExceptionHandler][Thread.UncaughtExceptionHandler]. If your flow upstream is
* expected to throw, you can use [catch operator][kotlinx.coroutines.flow.catch] on upstream flow
* to emit a helpful error object.
*
* The [timeoutInMs] can be changed to fit different use cases better, for example increasing it
* will give more time to flow to complete before being canceled and is good for finite flows
* that are costly to restart. Otherwise if a flow is cheap to restart decreasing the [timeoutInMs]
* value will allow to produce less values that aren't consumed by anything.
*
* @param context The CoroutineContext to collect the upstream flow in. Defaults to
* [EmptyCoroutineContext] combined with
* [Dispatchers.Main.immediate][kotlinx.coroutines.MainCoroutineDispatcher.immediate]
* @param timeoutInMs The timeout in ms before cancelling the block if there are no active observers
* ([LiveData.hasActiveObservers]. Defaults to [DEFAULT_TIMEOUT].
*/
@JvmOverloads
public fun <T> Flow<T>.asLiveData(
context: CoroutineContext = EmptyCoroutineContext,
timeoutInMs: Long = DEFAULT_TIMEOUT
): LiveData<T> = liveData(context, timeoutInMs) {
collect {
emit(it)
}
}.also { liveData ->
val flow = this
if (flow is StateFlow<T>) {
if (ArchTaskExecutor.getInstance().isMainThread) {
liveData.value = flow.value
} else {
liveData.postValue(flow.value)
}
}
}
/**
* Creates a [Flow] containing values dispatched by originating [LiveData]: at the start
* a flow collector receives the latest value held by LiveData and then observes LiveData updates.
*
* When a collection of the returned flow starts the originating [LiveData] becomes
* [active][LiveData.onActive]. Similarly, when a collection completes [LiveData] becomes
* [inactive][LiveData.onInactive].
*
* BackPressure: the returned flow is conflated. There is no mechanism to suspend an emission by
* LiveData due to a slow collector, so collector always gets the most recent value emitted.
*/
@OptIn(DelicateCoroutinesApi::class)
public fun <T> LiveData<T>.asFlow(): Flow<T> = callbackFlow {
val observer = Observer<T> {
trySend(it)
}
withContext(Dispatchers.Main.immediate) {
observeForever(observer)
}
awaitClose {
GlobalScope.launch(Dispatchers.Main.immediate) {
removeObserver(observer)
}
}
}.conflate()
/**
* Creates a LiveData that has values collected from the origin [Flow].
*
* The upstream flow collection starts when the returned [LiveData] becomes active
* ([LiveData.onActive]).
* If the [LiveData] becomes inactive ([LiveData.onInactive]) while the flow has not completed,
* the flow collection will be cancelled after [timeout] unless the [LiveData]
* becomes active again before that timeout (to gracefully handle cases like Activity rotation).
*
* After a cancellation, if the [LiveData] becomes active again, the upstream flow collection will
* be re-executed.
*
* If the upstream flow completes successfully *or* is cancelled due to reasons other than
* [LiveData] becoming inactive, it *will not* be re-collected even after [LiveData] goes through
* active inactive cycle.
*
* If flow completes with an exception, then exception will be delivered to the
* [CoroutineExceptionHandler][kotlinx.coroutines.CoroutineExceptionHandler] of provided [context].
* By default [EmptyCoroutineContext] is used to so an exception will be delivered to main's
* thread [UncaughtExceptionHandler][Thread.UncaughtExceptionHandler]. If your flow upstream is
* expected to throw, you can use [catch operator][kotlinx.coroutines.flow.catch] on upstream flow
* to emit a helpful error object.
*
* The [timeout] can be changed to fit different use cases better, for example increasing it
* will give more time to flow to complete before being canceled and is good for finite flows
* that are costly to restart. Otherwise if a flow is cheap to restart decreasing the [timeout]
* value will allow to produce less values that aren't consumed by anything.
*
* @param context The CoroutineContext to collect the upstream flow in. Defaults to
* [EmptyCoroutineContext] combined with
* [Dispatchers.Main.immediate][kotlinx.coroutines.MainCoroutineDispatcher.immediate]
* @param timeout The timeout in ms before cancelling the block if there are no active observers
* ([LiveData.hasActiveObservers]. Defaults to [DEFAULT_TIMEOUT].
*/
@RequiresApi(Build.VERSION_CODES.O)
public fun <T> Flow<T>.asLiveData(
context: CoroutineContext = EmptyCoroutineContext,
timeout: Duration
): LiveData<T> = asLiveData(context, Api26Impl.toMillis(timeout)) | apache-2.0 | 6d94545d8c04cd3bd2fc0a4032d1b6c2 | 44.72956 | 100 | 0.76121 | 4.586751 | false | false | false | false |
androidx/androidx | compose/ui/ui-text/src/commonMain/kotlin/androidx/compose/ui/text/style/TextDirection.kt | 3 | 2788 | /*
* Copyright 2019 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.compose.ui.text.style
/**
* Defines the algorithm to be used while determining the text direction.
*
* @see ResolvedTextDirection
*/
@kotlin.jvm.JvmInline
value class TextDirection internal constructor(internal val value: Int) {
override fun toString(): String {
return when (this) {
Ltr -> "Ltr"
Rtl -> "Rtl"
Content -> "Content"
ContentOrLtr -> "ContentOrLtr"
ContentOrRtl -> "ContentOrRtl"
else -> "Invalid"
}
}
companion object {
/**
* Always sets the text direction to be Left to Right.
*/
val Ltr = TextDirection(1)
/**
* Always sets the text direction to be Right to Left.
*/
val Rtl = TextDirection(2)
/**
* This value indicates that the text direction depends on the first strong directional
* character in the text according to the Unicode Bidirectional Algorithm.
* If no strong directional character is present, then
* [androidx.compose.ui.unit.LayoutDirection] is used to resolve the final TextDirection.
* * if used while creating a Paragraph object, [androidx.compose.ui.text.intl.LocaleList] will
* be used to resolve the direction as a fallback instead of
* [androidx.compose.ui.unit.LayoutDirection].
*/
val Content = TextDirection(3)
/**
* This value indicates that the text direction depends on the first strong directional
* character in the text according to the Unicode Bidirectional Algorithm. If no strong
* directional character is present, then Left to Right will be used as the default direction.
*/
val ContentOrLtr = TextDirection(4)
/**
* This value indicates that the text direction depends on the first strong directional
* character in the text according to the Unicode Bidirectional Algorithm. If no strong
* directional character is present, then Right to Left will be used as the default direction.
*/
val ContentOrRtl = TextDirection(5)
}
}
| apache-2.0 | 025b2ab27684e898a82f239296593d41 | 36.675676 | 103 | 0.658178 | 4.857143 | false | false | false | false |
androidx/androidx | compose/foundation/foundation-layout/src/commonMain/kotlin/androidx/compose/foundation/layout/AlignmentLine.kt | 3 | 12142 | /*
* Copyright 2019 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.compose.foundation.layout
import androidx.compose.runtime.Stable
import androidx.compose.ui.layout.AlignmentLine
import androidx.compose.ui.layout.HorizontalAlignmentLine
import androidx.compose.ui.layout.LayoutModifier
import androidx.compose.ui.layout.Measurable
import androidx.compose.ui.layout.MeasureScope
import androidx.compose.ui.Modifier
import androidx.compose.ui.layout.FirstBaseline
import androidx.compose.ui.layout.LastBaseline
import androidx.compose.ui.layout.MeasureResult
import androidx.compose.ui.platform.InspectorInfo
import androidx.compose.ui.platform.InspectorValueInfo
import androidx.compose.ui.platform.debugInspectorInfo
import androidx.compose.ui.unit.Constraints
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.TextUnit
import androidx.compose.ui.unit.isUnspecified
import kotlin.math.max
/**
* A [Modifier] that can add padding to position the content according to specified distances
* from its bounds to an [alignment line][AlignmentLine]. Whether the positioning is vertical
* or horizontal is defined by the orientation of the given [alignmentLine] (if the line is
* horizontal, [before] and [after] will refer to distances from top and bottom, otherwise they
* will refer to distances from start and end). The opposite axis sizing and positioning will
* remain unaffected.
* The modified layout will try to include the required padding, subject to the incoming max
* layout constraints, such that the distance from its bounds to the [alignmentLine] of the
* content will be [before] and [after], respectively. When the max constraints do not allow
* this, satisfying the [before] requirement will have priority over [after]. When the modified
* layout is min constrained in the affected layout direction and the padded layout is smaller
* than the constraint, the modified layout will satisfy the min constraint and the content will
* be positioned to satisfy the [before] requirement if specified, or the [after] requirement
* otherwise.
*
* @param alignmentLine the alignment line relative to which the padding is defined
* @param before the distance between the container's top edge and the horizontal alignment line, or
* the container's start edge and the vertical alignment line
* @param after the distance between the container's bottom edge and the horizontal alignment line,
* or the container's end edge and the vertical alignment line
*
* @see paddingFromBaseline
*
* Example usage:
* @sample androidx.compose.foundation.layout.samples.PaddingFromSample
*/
@Stable
fun Modifier.paddingFrom(
alignmentLine: AlignmentLine,
before: Dp = Dp.Unspecified,
after: Dp = Dp.Unspecified
): Modifier = this.then(
AlignmentLineOffsetDp(
alignmentLine,
before,
after,
debugInspectorInfo {
name = "paddingFrom"
properties["alignmentLine"] = alignmentLine
properties["before"] = before
properties["after"] = after
}
)
)
/**
* A [Modifier] that can add padding to position the content according to specified distances
* from its bounds to an [alignment line][AlignmentLine]. Whether the positioning is vertical
* or horizontal is defined by the orientation of the given [alignmentLine] (if the line is
* horizontal, [before] and [after] will refer to distances from top and bottom, otherwise they
* will refer to distances from start and end). The opposite axis sizing and positioning will
* remain unaffected.
* The modified layout will try to include the required padding, subject to the incoming max
* layout constraints, such that the distance from its bounds to the [alignmentLine] of the
* content will be [before] and [after], respectively. When the max constraints do not allow
* this, satisfying the [before] requirement will have priority over [after]. When the modified
* layout is min constrained in the affected layout direction and the padded layout is smaller
* than the constraint, the modified layout will satisfy the min constraint and the content will
* be positioned to satisfy the [before] requirement if specified, or the [after] requirement
* otherwise.
*
* @param alignmentLine the alignment line relative to which the padding is defined
* @param before the distance between the container's top edge and the horizontal alignment line, or
* the container's start edge and the vertical alignment line
* @param after the distance between the container's bottom edge and the horizontal alignment line,
* or the container's end edge and the vertical alignment line
*
* @see paddingFromBaseline
*
* Example usage:
* @sample androidx.compose.foundation.layout.samples.PaddingFromSample
*/
@Stable
fun Modifier.paddingFrom(
alignmentLine: AlignmentLine,
before: TextUnit = TextUnit.Unspecified,
after: TextUnit = TextUnit.Unspecified
): Modifier = this.then(
AlignmentLineOffsetTextUnit(
alignmentLine,
before,
after,
debugInspectorInfo {
name = "paddingFrom"
properties["alignmentLine"] = alignmentLine
properties["before"] = before
properties["after"] = after
}
)
)
/**
* A [Modifier] that positions the content in a layout such that the distance from the top
* of the layout to the [baseline of the first line of text in the content][FirstBaseline]
* is [top], and the distance from the
* [baseline of the last line of text in the content][LastBaseline] to the bottom of the layout
* is [bottom].
*
* @see paddingFrom
*
* Example usage:
* @sample androidx.compose.foundation.layout.samples.PaddingFromBaselineSampleDp
*/
@Stable
@Suppress("ModifierInspectorInfo")
fun Modifier.paddingFromBaseline(top: Dp = Dp.Unspecified, bottom: Dp = Dp.Unspecified) = this
.then(if (bottom != Dp.Unspecified) paddingFrom(LastBaseline, after = bottom) else Modifier)
.then(if (top != Dp.Unspecified) paddingFrom(FirstBaseline, before = top) else Modifier)
/**
* A [Modifier] that positions the content in a layout such that the distance from the top
* of the layout to the [baseline of the first line of text in the content][FirstBaseline]
* is [top], and the distance from the
* [baseline of the last line of text in the content][LastBaseline] to the bottom of the layout
* is [bottom].
*
* @see paddingFrom
*
* Example usage:
* @sample androidx.compose.foundation.layout.samples.PaddingFromBaselineSampleTextUnit
*/
@Stable
@Suppress("ModifierInspectorInfo")
fun Modifier.paddingFromBaseline(
top: TextUnit = TextUnit.Unspecified,
bottom: TextUnit = TextUnit.Unspecified
) = this
.then(if (!bottom.isUnspecified) paddingFrom(LastBaseline, after = bottom) else Modifier)
.then(if (!top.isUnspecified) paddingFrom(FirstBaseline, before = top) else Modifier)
private class AlignmentLineOffsetDp(
val alignmentLine: AlignmentLine,
val before: Dp,
val after: Dp,
inspectorInfo: InspectorInfo.() -> Unit
) : LayoutModifier, InspectorValueInfo(inspectorInfo) {
init {
require(
(before.value >= 0f || before == Dp.Unspecified) &&
(after.value >= 0f || after == Dp.Unspecified)
) {
"Padding from alignment line must be a non-negative number"
}
}
override fun MeasureScope.measure(
measurable: Measurable,
constraints: Constraints
): MeasureResult {
return alignmentLineOffsetMeasure(alignmentLine, before, after, measurable, constraints)
}
override fun hashCode(): Int {
var result = alignmentLine.hashCode()
result = 31 * result + before.hashCode()
result = 31 * result + after.hashCode()
return result
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
val otherModifier = other as? AlignmentLineOffsetDp ?: return false
return alignmentLine == otherModifier.alignmentLine &&
before == otherModifier.before &&
after == otherModifier.after
}
override fun toString(): String =
"AlignmentLineOffset(alignmentLine=$alignmentLine, before=$before, after=$after)"
}
private class AlignmentLineOffsetTextUnit(
val alignmentLine: AlignmentLine,
val before: TextUnit,
val after: TextUnit,
inspectorInfo: InspectorInfo.() -> Unit
) : LayoutModifier, InspectorValueInfo(inspectorInfo) {
override fun MeasureScope.measure(
measurable: Measurable,
constraints: Constraints
): MeasureResult {
return alignmentLineOffsetMeasure(
alignmentLine,
if (!before.isUnspecified) before.toDp() else Dp.Unspecified,
if (!after.isUnspecified) after.toDp() else Dp.Unspecified,
measurable,
constraints
)
}
override fun hashCode(): Int {
var result = alignmentLine.hashCode()
result = 31 * result + before.hashCode()
result = 31 * result + after.hashCode()
return result
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
val otherModifier = other as? AlignmentLineOffsetTextUnit ?: return false
return alignmentLine == otherModifier.alignmentLine &&
before == otherModifier.before &&
after == otherModifier.after
}
override fun toString(): String =
"AlignmentLineOffset(alignmentLine=$alignmentLine, before=$before, after=$after)"
}
private fun MeasureScope.alignmentLineOffsetMeasure(
alignmentLine: AlignmentLine,
before: Dp,
after: Dp,
measurable: Measurable,
constraints: Constraints
): MeasureResult {
val placeable = measurable.measure(
// Loose constraints perpendicular on the alignment line.
if (alignmentLine.horizontal) constraints.copy(minHeight = 0)
else constraints.copy(minWidth = 0)
)
val linePosition = placeable[alignmentLine].let {
if (it != AlignmentLine.Unspecified) it else 0
}
val axis = if (alignmentLine.horizontal) placeable.height else placeable.width
val axisMax = if (alignmentLine.horizontal) constraints.maxHeight else constraints.maxWidth
// Compute padding required to satisfy the total before and after offsets.
val paddingBefore =
((if (before != Dp.Unspecified) before.roundToPx() else 0) - linePosition)
.coerceIn(0, axisMax - axis)
val paddingAfter =
((if (after != Dp.Unspecified) after.roundToPx() else 0) - axis + linePosition)
.coerceIn(0, axisMax - axis - paddingBefore)
val width = if (alignmentLine.horizontal) {
placeable.width
} else {
max(paddingBefore + placeable.width + paddingAfter, constraints.minWidth)
}
val height = if (alignmentLine.horizontal) {
max(paddingBefore + placeable.height + paddingAfter, constraints.minHeight)
} else {
placeable.height
}
return layout(width, height) {
val x = when {
alignmentLine.horizontal -> 0
before != Dp.Unspecified -> paddingBefore
else -> width - paddingAfter - placeable.width
}
val y = when {
!alignmentLine.horizontal -> 0
before != Dp.Unspecified -> paddingBefore
else -> height - paddingAfter - placeable.height
}
placeable.placeRelative(x, y)
}
}
private val AlignmentLine.horizontal: Boolean get() = this is HorizontalAlignmentLine
| apache-2.0 | 6d2a5add0ba06227a905ac845ef0a602 | 39.473333 | 100 | 0.711991 | 4.644989 | false | false | false | false |
nrizzio/Signal-Android | app/src/main/java/org/thoughtcrime/securesms/contacts/paged/ContactSearchPagedDataSource.kt | 1 | 12869 | package org.thoughtcrime.securesms.contacts.paged
import android.database.Cursor
import org.signal.paging.PagedDataSource
import org.thoughtcrime.securesms.contacts.paged.collections.ContactSearchCollection
import org.thoughtcrime.securesms.contacts.paged.collections.ContactSearchIterator
import org.thoughtcrime.securesms.contacts.paged.collections.CursorSearchIterator
import org.thoughtcrime.securesms.contacts.paged.collections.StoriesSearchCollection
import org.thoughtcrime.securesms.database.GroupDatabase.GroupRecord
import org.thoughtcrime.securesms.database.model.DistributionListPrivacyMode
import org.thoughtcrime.securesms.dependencies.ApplicationDependencies
import org.thoughtcrime.securesms.keyvalue.StorySend
import org.thoughtcrime.securesms.recipients.Recipient
import org.thoughtcrime.securesms.recipients.RecipientId
import java.util.concurrent.TimeUnit
/**
* Manages the querying of contact information based off a configuration.
*/
class ContactSearchPagedDataSource(
private val contactConfiguration: ContactSearchConfiguration,
private val contactSearchPagedDataSourceRepository: ContactSearchPagedDataSourceRepository = ContactSearchPagedDataSourceRepository(ApplicationDependencies.getApplication())
) : PagedDataSource<ContactSearchKey, ContactSearchData> {
companion object {
private val ACTIVE_STORY_CUTOFF_DURATION = TimeUnit.DAYS.toMillis(1)
}
private val latestStorySends: List<StorySend> = contactSearchPagedDataSourceRepository.getLatestStorySends(ACTIVE_STORY_CUTOFF_DURATION)
private val activeStoryCount = latestStorySends.size
override fun size(): Int {
return contactConfiguration.sections.sumOf {
getSectionSize(it, contactConfiguration.query)
}
}
override fun load(start: Int, length: Int, cancellationSignal: PagedDataSource.CancellationSignal): MutableList<ContactSearchData> {
val sizeMap: Map<ContactSearchConfiguration.Section, Int> = contactConfiguration.sections.associateWith { getSectionSize(it, contactConfiguration.query) }
val startIndex: Index = findIndex(sizeMap, start)
val endIndex: Index = findIndex(sizeMap, start + length)
val indexOfStartSection = contactConfiguration.sections.indexOf(startIndex.category)
val indexOfEndSection = contactConfiguration.sections.indexOf(endIndex.category)
val results: List<List<ContactSearchData>> = contactConfiguration.sections.mapIndexed { index, section ->
if (index in indexOfStartSection..indexOfEndSection) {
getSectionData(
section = section,
query = contactConfiguration.query,
startIndex = if (index == indexOfStartSection) startIndex.offset else 0,
endIndex = if (index == indexOfEndSection) endIndex.offset else sizeMap[section] ?: error("Unknown section")
)
} else {
emptyList()
}
}
return results.flatten().toMutableList()
}
private fun findIndex(sizeMap: Map<ContactSearchConfiguration.Section, Int>, target: Int): Index {
var offset = 0
sizeMap.forEach { (key, size) ->
if (offset + size > target) {
return Index(key, target - offset)
}
offset += size
}
return Index(sizeMap.keys.last(), sizeMap.values.last())
}
data class Index(val category: ContactSearchConfiguration.Section, val offset: Int)
override fun load(key: ContactSearchKey?): ContactSearchData? {
throw UnsupportedOperationException()
}
override fun getKey(data: ContactSearchData): ContactSearchKey {
return data.contactSearchKey
}
private fun getSectionSize(section: ContactSearchConfiguration.Section, query: String?): Int {
return when (section) {
is ContactSearchConfiguration.Section.Individuals -> getNonGroupSearchIterator(section, query).getCollectionSize(section, query, null)
is ContactSearchConfiguration.Section.Groups -> contactSearchPagedDataSourceRepository.getGroupSearchIterator(section, query).getCollectionSize(section, query, this::canSendToGroup)
is ContactSearchConfiguration.Section.Recents -> getRecentsSearchIterator(section, query).getCollectionSize(section, query, null)
is ContactSearchConfiguration.Section.Stories -> getStoriesSearchIterator(query).getCollectionSize(section, query, null)
}
}
private fun <R> ContactSearchIterator<R>.getCollectionSize(section: ContactSearchConfiguration.Section, query: String?, recordsPredicate: ((R) -> Boolean)?): Int {
val extras: List<ContactSearchData> = when (section) {
is ContactSearchConfiguration.Section.Stories -> getFilteredGroupStories(section, query)
else -> emptyList()
}
val collection = createResultsCollection(
section = section,
records = this,
recordsPredicate = recordsPredicate,
extraData = extras,
recordMapper = { error("Unsupported") }
)
return collection.getSize()
}
private fun getFilteredGroupStories(section: ContactSearchConfiguration.Section.Stories, query: String?): List<ContactSearchData> {
return (contactSearchPagedDataSourceRepository.getGroupStories() + section.groupStories)
.filter { contactSearchPagedDataSourceRepository.recipientNameContainsQuery(it.recipient, query) }
}
private fun getSectionData(section: ContactSearchConfiguration.Section, query: String?, startIndex: Int, endIndex: Int): List<ContactSearchData> {
return when (section) {
is ContactSearchConfiguration.Section.Groups -> getGroupContactsData(section, query, startIndex, endIndex)
is ContactSearchConfiguration.Section.Individuals -> getNonGroupContactsData(section, query, startIndex, endIndex)
is ContactSearchConfiguration.Section.Recents -> getRecentsContactData(section, query, startIndex, endIndex)
is ContactSearchConfiguration.Section.Stories -> getStoriesContactData(section, query, startIndex, endIndex)
}
}
private fun getNonGroupSearchIterator(section: ContactSearchConfiguration.Section.Individuals, query: String?): ContactSearchIterator<Cursor> {
return when (section.transportType) {
ContactSearchConfiguration.TransportType.PUSH -> CursorSearchIterator(contactSearchPagedDataSourceRepository.querySignalContacts(query, section.includeSelf))
ContactSearchConfiguration.TransportType.SMS -> CursorSearchIterator(contactSearchPagedDataSourceRepository.queryNonSignalContacts(query))
ContactSearchConfiguration.TransportType.ALL -> CursorSearchIterator(contactSearchPagedDataSourceRepository.queryNonGroupContacts(query, section.includeSelf))
}
}
private fun getNonGroupHeaderLetterMap(section: ContactSearchConfiguration.Section.Individuals, query: String?): Map<RecipientId, String> {
return when (section.transportType) {
ContactSearchConfiguration.TransportType.PUSH -> contactSearchPagedDataSourceRepository.querySignalContactLetterHeaders(query, section.includeSelf)
else -> error("This has only been implemented for push recipients.")
}
}
private fun getStoriesSearchIterator(query: String?): ContactSearchIterator<Cursor> {
return CursorSearchIterator(contactSearchPagedDataSourceRepository.getStories(query))
}
private fun getRecentsSearchIterator(section: ContactSearchConfiguration.Section.Recents, query: String?): ContactSearchIterator<Cursor> {
if (!query.isNullOrEmpty()) {
throw IllegalArgumentException("Searching Recents is not supported")
}
return CursorSearchIterator(contactSearchPagedDataSourceRepository.getRecents(section))
}
private fun <R> readContactData(
records: ContactSearchIterator<R>,
recordsPredicate: ((R) -> Boolean)?,
section: ContactSearchConfiguration.Section,
startIndex: Int,
endIndex: Int,
recordMapper: (R) -> ContactSearchData,
extraData: List<ContactSearchData> = emptyList()
): List<ContactSearchData> {
val results = mutableListOf<ContactSearchData>()
val collection = createResultsCollection(section, records, recordsPredicate, extraData, recordMapper)
results.addAll(collection.getSublist(startIndex, endIndex))
return results
}
private fun getStoriesContactData(section: ContactSearchConfiguration.Section.Stories, query: String?, startIndex: Int, endIndex: Int): List<ContactSearchData> {
return getStoriesSearchIterator(query).use { records ->
readContactData(
records = records,
null,
section = section,
startIndex = startIndex,
endIndex = endIndex,
recordMapper = {
val recipient = contactSearchPagedDataSourceRepository.getRecipientFromDistributionListCursor(it)
val count = contactSearchPagedDataSourceRepository.getDistributionListMembershipCount(recipient)
val privacyMode = contactSearchPagedDataSourceRepository.getPrivacyModeFromDistributionListCursor(it)
ContactSearchData.Story(recipient, count, privacyMode)
},
extraData = getFilteredGroupStories(section, query)
)
}
}
private fun getRecentsContactData(section: ContactSearchConfiguration.Section.Recents, query: String?, startIndex: Int, endIndex: Int): List<ContactSearchData> {
return getRecentsSearchIterator(section, query).use { records ->
readContactData(
records = records,
recordsPredicate = null,
section = section,
startIndex = startIndex,
endIndex = endIndex,
recordMapper = {
ContactSearchData.KnownRecipient(contactSearchPagedDataSourceRepository.getRecipientFromThreadCursor(it))
}
)
}
}
private fun getNonGroupContactsData(section: ContactSearchConfiguration.Section.Individuals, query: String?, startIndex: Int, endIndex: Int): List<ContactSearchData> {
val headerMap: Map<RecipientId, String> = if (section.includeLetterHeaders) {
getNonGroupHeaderLetterMap(section, query)
} else {
emptyMap()
}
return getNonGroupSearchIterator(section, query).use { records ->
readContactData(
records = records,
recordsPredicate = null,
section = section,
startIndex = startIndex,
endIndex = endIndex,
recordMapper = {
val recipient = contactSearchPagedDataSourceRepository.getRecipientFromRecipientCursor(it)
ContactSearchData.KnownRecipient(recipient, headerLetter = headerMap[recipient.id])
}
)
}
}
private fun getGroupContactsData(section: ContactSearchConfiguration.Section.Groups, query: String?, startIndex: Int, endIndex: Int): List<ContactSearchData> {
return contactSearchPagedDataSourceRepository.getGroupSearchIterator(section, query).use { records ->
readContactData(
records = records,
recordsPredicate = this::canSendToGroup,
section = section,
startIndex = startIndex,
endIndex = endIndex,
recordMapper = {
if (section.returnAsGroupStories) {
ContactSearchData.Story(contactSearchPagedDataSourceRepository.getRecipientFromGroupRecord(it), 0, DistributionListPrivacyMode.ALL)
} else {
ContactSearchData.KnownRecipient(contactSearchPagedDataSourceRepository.getRecipientFromGroupRecord(it), shortSummary = section.shortSummary)
}
}
)
}
}
private fun canSendToGroup(groupRecord: GroupRecord): Boolean {
return if (groupRecord.isAnnouncementGroup) {
groupRecord.isAdmin(Recipient.self())
} else {
groupRecord.isActive
}
}
private fun <R> createResultsCollection(
section: ContactSearchConfiguration.Section,
records: ContactSearchIterator<R>,
recordsPredicate: ((R) -> Boolean)?,
extraData: List<ContactSearchData>,
recordMapper: (R) -> ContactSearchData
): ContactSearchCollection<R> {
return when (section) {
is ContactSearchConfiguration.Section.Stories -> StoriesSearchCollection(section, records, extraData, recordMapper, activeStoryCount, StoryComparator(latestStorySends))
else -> ContactSearchCollection(section, records, recordsPredicate, recordMapper, 0)
}
}
/**
* StoryComparator
*/
private class StoryComparator(private val latestStorySends: List<StorySend>) : Comparator<ContactSearchData.Story> {
override fun compare(lhs: ContactSearchData.Story, rhs: ContactSearchData.Story): Int {
val lhsActiveRank = latestStorySends.indexOfFirst { it.identifier.matches(lhs.recipient) }.let { if (it == -1) Int.MAX_VALUE else it }
val rhsActiveRank = latestStorySends.indexOfFirst { it.identifier.matches(rhs.recipient) }.let { if (it == -1) Int.MAX_VALUE else it }
return when {
lhs.recipient.isMyStory && rhs.recipient.isMyStory -> 0
lhs.recipient.isMyStory -> -1
rhs.recipient.isMyStory -> 1
lhsActiveRank < rhsActiveRank -> -1
lhsActiveRank > rhsActiveRank -> 1
else -> 0
}
}
}
}
| gpl-3.0 | b9b3e4bc17dfd3f9238cd614a8583300 | 44.473498 | 187 | 0.751962 | 4.794709 | false | true | false | false |
DSteve595/Put.io | app/src/main/java/com/stevenschoen/putionew/Analytics.kt | 1 | 3008 | package com.stevenschoen.putionew
import android.content.Context
import android.os.Bundle
import androidx.fragment.app.Fragment
import com.google.firebase.analytics.FirebaseAnalytics
import com.stevenschoen.putionew.model.files.PutioFile
class Analytics(context: Context) {
object Event {
const val VIEW_FOLDER = "view_folder"
const val DOWNLOAD_ITEM = "download_item"
const val FINISH_DOWNLOAD = "finish_download"
const val OPEN_DOWNLOADED_FILE = "open_downloaded_file"
const val OPEN_DOWNLOADED_VIDEO = "open_downloaded_video"
const val STREAM_VIDEO = "stream_video"
}
object Param {
const val CONTENT_SIZE = "content_size"
const val IS_VIDEO = "is_video"
const val MP4_SELECTED = "mp4_selected"
}
private val putioApp = putioApp(context)
fun logViewedFile(file: PutioFile) {
makeFileBundle(file)
.logEvent(FirebaseAnalytics.Event.VIEW_ITEM)
}
fun logBrowsedToFolder(folder: PutioFile) {
makeFolderBundle(folder)
.logEvent(Event.VIEW_FOLDER)
}
fun logSearched(query: String) {
Bundle().apply {
putString(FirebaseAnalytics.Param.SEARCH_TERM, query)
}.logEvent(FirebaseAnalytics.Event.SEARCH)
}
fun logStartedFileDownload(file: PutioFile) {
makeFileBundle(file)
.logEvent(Event.DOWNLOAD_ITEM)
}
fun logStartedVideoDownload(video: PutioFile, mp4: Boolean) {
makeFileBundle(video).apply {
putBoolean(Param.MP4_SELECTED, mp4)
}.logEvent(Event.DOWNLOAD_ITEM)
}
fun logDownloadFinished(file: PutioFile) {
makeFileBundle(file)
.logEvent(Event.FINISH_DOWNLOAD)
}
fun logOpenedDownloadedFile(file: PutioFile) {
makeFileBundle(file)
.logEvent(Event.OPEN_DOWNLOADED_FILE)
}
fun logOpenedDownloadedVideo(video: PutioFile, mp4: Boolean) {
makeFileBundle(video).apply {
putBoolean(Param.MP4_SELECTED, mp4)
}.logEvent(Event.OPEN_DOWNLOADED_VIDEO)
}
fun logStreamedVideo(video: PutioFile, mp4: Boolean) {
makeFileBundle(video).apply {
putBoolean(Param.MP4_SELECTED, mp4)
}.logEvent(Event.STREAM_VIDEO)
}
private fun makeFileBundle(file: PutioFile) = Bundle().apply { addBasicFileInfo(file) }
private fun makeFolderBundle(folder: PutioFile) = Bundle().apply { addIdAndName(folder) }
private fun Bundle.addBasicFileInfo(file: PutioFile) {
addIdAndName(file)
putString(FirebaseAnalytics.Param.CONTENT_TYPE, file.contentType)
file.size?.let { putLong(Param.CONTENT_SIZE, it) }
putBoolean(Param.IS_VIDEO, file.isVideo)
}
private fun Bundle.addIdAndName(file: PutioFile) {
putLong(FirebaseAnalytics.Param.ITEM_ID, file.id)
putString(FirebaseAnalytics.Param.ITEM_NAME, file.name.take(100))
}
private fun Bundle.logEvent(event: String) = putioApp.firebaseAnalytics.logEvent(event, this)
}
val Context.analytics
get() = Analytics(this)
val Fragment.analytics
get() = Analytics(context!!)
private val Context.firebaseAnalytics
get() = FirebaseAnalytics.getInstance(this)
| mit | f7f4613d566652a8651e60f96d2e5843 | 28.782178 | 95 | 0.727061 | 3.722772 | false | false | false | false |
GunoH/intellij-community | plugins/stats-collector/src/com/intellij/stats/completion/tracker/LoggerPerformanceTracker.kt | 4 | 2543 | // 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.stats.completion.tracker
import com.intellij.codeInsight.lookup.LookupEvent
import com.intellij.completion.ml.performance.MLCompletionPerformanceTracker
class LoggerPerformanceTracker(
private val delegate: CompletionActionsListener,
private val tracker: MLCompletionPerformanceTracker)
: CompletionActionsListener {
override fun beforeDownPressed() = measureAndLog("beforeDownPressed") {
delegate.beforeDownPressed()
}
override fun downPressed() = measureAndLog("downPressed") {
delegate.downPressed()
}
override fun beforeUpPressed() = measureAndLog("beforeUpPressed") {
delegate.beforeUpPressed()
}
override fun upPressed() = measureAndLog("upPressed") {
delegate.upPressed()
}
override fun beforeBackspacePressed() = measureAndLog("beforeBackspacePressed") {
delegate.beforeBackspacePressed()
}
override fun afterBackspacePressed() = measureAndLog("afterBackspacePressed") {
delegate.afterBackspacePressed()
}
override fun beforeCharTyped(c: Char) = measureAndLog("beforeCharTyped") {
delegate.beforeCharTyped(c)
}
override fun lookupShown(event: LookupEvent) = measureAndLog("lookupShown") {
delegate.lookupShown(event)
}
override fun afterAppend(c: Char) = measureAndLog("afterAppend") {
delegate.afterAppend(c)
}
override fun afterTruncate() = measureAndLog("afterTruncate") {
delegate.afterTruncate()
}
override fun beforeTruncate() = measureAndLog("beforeTruncate") {
delegate.beforeTruncate()
}
override fun beforeAppend(c: Char) = measureAndLog("beforeAppend") {
delegate.beforeAppend(c)
}
override fun beforeItemSelected(event: LookupEvent): Boolean = measureAndLog("beforeItemSelected") {
delegate.beforeItemSelected(event)
}
override fun itemSelected(event: LookupEvent) = measureAndLog("itemSelected") {
delegate.itemSelected(event)
}
override fun lookupCanceled(event: LookupEvent) = measureAndLog("lookupCanceled") {
delegate.lookupCanceled(event)
}
override fun currentItemChanged(event: LookupEvent) = measureAndLog("currentItemChanged") {
delegate.currentItemChanged(event)
}
private inline fun <T> measureAndLog(actionName: String, block: () -> T): T {
val start = System.currentTimeMillis()
val c = block()
tracker.eventLogged(actionName, System.currentTimeMillis() - start)
return c
}
} | apache-2.0 | 4141003486ba4ec4acfc89974f3eb0aa | 30.407407 | 140 | 0.748722 | 4.430314 | false | false | false | false |
JetBrains/xodus | vfs/src/main/kotlin/jetbrains/exodus/vfs/Cluster.kt | 1 | 3399 | /**
* Copyright 2010 - 2022 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
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package jetbrains.exodus.vfs
import jetbrains.exodus.*
import jetbrains.exodus.ByteIterator
import jetbrains.exodus.bindings.IntegerBinding
import jetbrains.exodus.log.BlockByteIterator
import jetbrains.exodus.util.LightOutputStream
import java.io.File
import java.io.IOException
import java.io.RandomAccessFile
internal class Cluster(private val it: ByteIterable) : Iterator<Byte> {
private var iterator: ByteIterator? = null
var startingPosition: Long = 0
var clusterNumber: Long = 0
private var size: Int = 0
fun getSize() = getIterator().run { size }
override fun hasNext() = getSize() > 0
override fun next() = getIterator().next().also { --size }
fun nextBytes(array: ByteArray, off: Int, len: Int): Int {
val iterator = getIterator()
if (iterator is BlockByteIterator) {
return iterator.nextBytes(array, off, len).also { readBytes -> size -= readBytes }
}
val result = kotlin.math.min(len, size)
for (i in 0 until result) {
array[off + i] = iterator.next()
}
size -= result
return result
}
fun skip(length: Long): Long {
val size = getSize()
val skipped = if (length > size) size.toLong() else getIterator().skip(length)
this.size -= skipped.toInt()
return skipped
}
fun copyTo(array: ByteArray) {
var i = 0
while (hasNext()) {
array[i++] = next()
}
}
private fun getIterator(): ByteIterator {
return iterator ?: it.iterator().apply {
iterator = this
size = IntegerBinding.readCompressed(this)
}
}
companion object {
@JvmStatic
fun writeCluster(cluster: ByteArray,
clusterConverter: ClusterConverter?,
size: Int,
accumulateInRAM: Boolean): ByteIterable {
if (accumulateInRAM) {
val output = LightOutputStream(size + 5)
IntegerBinding.writeCompressed(output, size)
output.write(cluster, 0, size)
val result = output.asArrayByteIterable()
return clusterConverter?.onWrite(result) ?: result
}
val bi: ByteIterable
try {
val file = File.createTempFile("~exodus-vfs-output-cluster", ".tmp")
RandomAccessFile(file, "rw").use { out -> out.write(cluster, 0, size) }
bi = FileByteIterable(file)
file.deleteOnExit()
} catch (e: IOException) {
throw ExodusException.toExodusException(e)
}
return CompoundByteIterable(arrayOf(IntegerBinding.intToCompressedEntry(size), bi))
}
}
} | apache-2.0 | 2fbb6857dd65d02ffcaad6d159637767 | 32.663366 | 95 | 0.614004 | 4.550201 | false | false | false | false |
jwren/intellij-community | plugins/kotlin/idea/tests/test/org/jetbrains/kotlin/idea/repl/IdeaJsr223Test.kt | 6 | 1596 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.repl
import com.intellij.testFramework.LightPlatformTestCase
import org.junit.Test
import org.junit.internal.runners.JUnit38ClassRunner
import org.junit.runner.RunWith
import javax.script.ScriptContext
import javax.script.ScriptEngine
import javax.script.ScriptEngineManager
import javax.script.ScriptException
import kotlin.test.assertFails
@RunWith(JUnit38ClassRunner::class)
class IdeaJsr223Test : LightPlatformTestCase() {
@Test
fun testJsr223Engine() {
val semgr = ScriptEngineManager()
val engine = semgr.getEngineByName("kotlin")
assertNotNull(engine)
val res0 = assertFails { engine.eval("val x =") }
assertTrue("Unexpected check results: $res0", (res0 as? ScriptException)?.message?.contains("incomplete code") ?: false)
val res1 = engine.eval("val x = 5\nval y = listOf(x)")
assertNull("Unexpected eval result: $res1", res1)
val res2 = engine.eval("y.first() + 2")
assertEquals(7, res2)
}
@Test
fun testJsr223ScriptWithBindings() {
val semgr = ScriptEngineManager()
val engine = semgr.getEngineByName("kotlin")
val bindings = engine.getBindings(ScriptContext.ENGINE_SCOPE)
bindings.put(ScriptEngine.ARGV, arrayOf("42"))
bindings.put("abc", 13)
val res1 = engine.eval("2 + (bindings[\"abc\"] as Int)")
assertEquals(15, res1)
}
}
| apache-2.0 | 26d13579d8eb8069c6b5d50c0123dd15 | 31.571429 | 158 | 0.699248 | 4.071429 | false | true | false | false |
GunoH/intellij-community | plugins/kotlin/idea/tests/testData/checker/GenericArgumentConsistency.fir.kt | 10 | 2537 | interface A<in T> {}
interface B<T> : A<Int> {}
interface C<T> : <error descr="[INCONSISTENT_TYPE_PARAMETER_VALUES] Type parameter T of 'A' has inconsistent values: kotlin/Int, T">B<T>, A<T></error> {}
interface C1<T> : <error descr="[INCONSISTENT_TYPE_PARAMETER_VALUES] Type parameter T of 'A' has inconsistent values: kotlin/Int, kotlin/Any">B<T>, A<Any></error> {}
interface D : <error descr="[INCONSISTENT_TYPE_PARAMETER_VALUES] Type parameter T of 'A' has inconsistent values: kotlin/Int, kotlin/Boolean"><error descr="[INCONSISTENT_TYPE_PARAMETER_VALUES] Type parameter T of 'B' has inconsistent values: kotlin/Boolean, kotlin/Double">C<Boolean>, B<Double></error></error>{}
interface A1<out T> {}
interface B1 : A1<Int> {}
interface B2 : <error descr="[INCONSISTENT_TYPE_PARAMETER_VALUES] Type parameter T of 'A1' has inconsistent values: kotlin/Any, kotlin/Int">A1<Any>, B1</error> {}
interface BA1<T> {}
interface BB1 : BA1<Int> {}
interface BB2 : <error descr="[INCONSISTENT_TYPE_PARAMETER_VALUES] Type parameter T of 'BA1' has inconsistent values: kotlin/Any, kotlin/Int">BA1<Any>, BB1</error> {}
//package x {
interface xAA1<out T> {}
interface xAB1 : xAA1<Int> {}
interface xAB3 : xAA1<Comparable<Int>> {}
interface xAB2 : <error descr="[INCONSISTENT_TYPE_PARAMETER_VALUES] Type parameter T of 'xAA1' has inconsistent values: kotlin/Number, kotlin/Int, kotlin/Comparable<kotlin/Int>">xAA1<Number>, xAB1, xAB3</error> {}
//}
//package x2 {
interface x2AA1<out T> {}
interface x2AB1 : x2AA1<Any> {}
interface x2AB3 : x2AA1<Comparable<Int>> {}
interface x2AB2 : <error descr="[INCONSISTENT_TYPE_PARAMETER_VALUES] Type parameter T of 'x2AA1' has inconsistent values: kotlin/Number, kotlin/Any, kotlin/Comparable<kotlin/Int>">x2AA1<Number>, x2AB1, x2AB3</error> {}
//}
//package x3 {
interface x3AA1<in T> {}
interface x3AB1 : x3AA1<Any> {}
interface x3AB3 : x3AA1<Comparable<Int>> {}
interface x3AB2 : <error descr="[INCONSISTENT_TYPE_PARAMETER_VALUES] Type parameter T of 'x3AA1' has inconsistent values: kotlin/Number, kotlin/Any, kotlin/Comparable<kotlin/Int>">x3AA1<Number>, x3AB1, x3AB3</error> {}
//}
//package sx2 {
interface sx2AA1<in T> {}
interface sx2AB1 : sx2AA1<Int> {}
interface sx2AB3 : sx2AA1<Comparable<Int>> {}
interface sx2AB2 : <error descr="[INCONSISTENT_TYPE_PARAMETER_VALUES] Type parameter T of 'sx2AA1' has inconsistent values: kotlin/Number, kotlin/Int, kotlin/Comparable<kotlin/Int>">sx2AA1<Number>, sx2AB1, sx2AB3</error> {}
//}
| apache-2.0 | 135bb63f679bfdcadd42fd357f984414 | 59.404762 | 312 | 0.710682 | 3.049279 | false | false | false | false |
smmribeiro/intellij-community | uast/uast-common/src/org/jetbrains/uast/kinds/UastBinaryOperator.kt | 19 | 3804 | /*
* 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
/**
* Kinds of operators in [UBinaryExpression].
*/
open class UastBinaryOperator(override val text: String) : UastOperator {
class LogicalOperator(text: String) : UastBinaryOperator(text)
class ComparisonOperator(text: String) : UastBinaryOperator(text)
class ArithmeticOperator(text: String) : UastBinaryOperator(text)
class BitwiseOperator(text: String) : UastBinaryOperator(text)
class AssignOperator(text: String) : UastBinaryOperator(text)
companion object {
@JvmField
val ASSIGN: AssignOperator = AssignOperator("=")
@JvmField
val PLUS: ArithmeticOperator = ArithmeticOperator("+")
@JvmField
val MINUS: ArithmeticOperator = ArithmeticOperator("-")
@JvmField
val MULTIPLY: ArithmeticOperator = ArithmeticOperator("*")
@JvmField
val DIV: ArithmeticOperator = ArithmeticOperator("/")
@JvmField
val MOD: ArithmeticOperator = ArithmeticOperator("%")
@JvmField
val LOGICAL_OR: LogicalOperator = LogicalOperator("||")
@JvmField
val LOGICAL_AND: LogicalOperator = LogicalOperator("&&")
@JvmField
val BITWISE_OR: BitwiseOperator = BitwiseOperator("|")
@JvmField
val BITWISE_AND: BitwiseOperator = BitwiseOperator("&")
@JvmField
val BITWISE_XOR: BitwiseOperator = BitwiseOperator("^")
@JvmField
val EQUALS: ComparisonOperator = ComparisonOperator("==")
@JvmField
val NOT_EQUALS: ComparisonOperator = ComparisonOperator("!=")
@JvmField
val IDENTITY_EQUALS: ComparisonOperator = ComparisonOperator("===")
@JvmField
val IDENTITY_NOT_EQUALS: ComparisonOperator = ComparisonOperator("!==")
@JvmField
val GREATER: ComparisonOperator = ComparisonOperator(">")
@JvmField
val GREATER_OR_EQUALS: ComparisonOperator = ComparisonOperator(">=")
@JvmField
val LESS: ComparisonOperator = ComparisonOperator("<")
@JvmField
val LESS_OR_EQUALS: ComparisonOperator = ComparisonOperator("<=")
@JvmField
val SHIFT_LEFT: BitwiseOperator = BitwiseOperator("<<")
@JvmField
val SHIFT_RIGHT: BitwiseOperator = BitwiseOperator(">>")
@JvmField
val UNSIGNED_SHIFT_RIGHT: BitwiseOperator = BitwiseOperator(">>>")
@JvmField
val OTHER: UastBinaryOperator = UastBinaryOperator("<other>")
@JvmField
val PLUS_ASSIGN: AssignOperator = AssignOperator("+=")
@JvmField
val MINUS_ASSIGN: AssignOperator = AssignOperator("-=")
@JvmField
val MULTIPLY_ASSIGN: AssignOperator = AssignOperator("*=")
@JvmField
val DIVIDE_ASSIGN: AssignOperator = AssignOperator("/=")
@JvmField
val REMAINDER_ASSIGN: AssignOperator = AssignOperator("%=")
@JvmField
val AND_ASSIGN: AssignOperator = AssignOperator("&=")
@JvmField
val XOR_ASSIGN: AssignOperator = AssignOperator("^=")
@JvmField
val OR_ASSIGN: AssignOperator = AssignOperator("|=")
@JvmField
val SHIFT_LEFT_ASSIGN: AssignOperator = AssignOperator("<<=")
@JvmField
val SHIFT_RIGHT_ASSIGN: AssignOperator = AssignOperator(">>=")
@JvmField
val UNSIGNED_SHIFT_RIGHT_ASSIGN: AssignOperator = AssignOperator(">>>=")
}
override fun toString(): String = text
} | apache-2.0 | e89177b035c2c8bba2c1bc1ed7a082b3 | 27.609023 | 76 | 0.703733 | 4.523187 | false | false | false | false |
smmribeiro/intellij-community | plugins/package-search/src/com/jetbrains/packagesearch/intellij/plugin/data/InstalledPackagesUtils.kt | 1 | 10480 | package com.jetbrains.packagesearch.intellij.plugin.data
import com.intellij.buildsystem.model.unified.UnifiedCoordinates
import com.intellij.buildsystem.model.unified.UnifiedDependency
import com.intellij.openapi.application.readAction
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.text.StringUtil
import com.intellij.util.concurrency.AppExecutorUtil
import com.intellij.util.io.DigestUtil
import com.jetbrains.packagesearch.intellij.plugin.PluginEnvironment
import com.jetbrains.packagesearch.intellij.plugin.extensibility.ProjectModule
import com.jetbrains.packagesearch.intellij.plugin.extensibility.ProjectModuleOperationProvider
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.DependencyUsageInfo
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.InstalledDependency
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.PackageModel
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.PackageScope
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.PackageVersion
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.ProjectDataProvider
import com.jetbrains.packagesearch.intellij.plugin.util.TraceInfo
import com.jetbrains.packagesearch.intellij.plugin.util.lifecycleScope
import com.jetbrains.packagesearch.intellij.plugin.util.logDebug
import com.jetbrains.packagesearch.intellij.plugin.util.packageVersionNormalizer
import com.jetbrains.packagesearch.intellij.plugin.util.parallelMap
import kotlinx.coroutines.Deferred
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.asCoroutineDispatcher
import kotlinx.coroutines.async
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import kotlinx.coroutines.yield
import kotlinx.serialization.KSerializer
import kotlinx.serialization.Serializable
import kotlinx.serialization.SerializationException
import kotlinx.serialization.decodeFromString
import kotlinx.serialization.descriptors.buildClassSerialDescriptor
import kotlinx.serialization.descriptors.element
import kotlinx.serialization.encodeToString
import kotlinx.serialization.encoding.CompositeDecoder.Companion.DECODE_DONE
import kotlinx.serialization.encoding.Decoder
import kotlinx.serialization.encoding.Encoder
import kotlinx.serialization.encoding.decodeStructure
import kotlinx.serialization.encoding.encodeStructure
import kotlinx.serialization.json.Json
import java.io.File
import java.nio.file.Path
import kotlin.io.path.absolutePathString
internal suspend fun installedPackages(
dependenciesByModule: Map<ProjectModule, List<UnifiedDependency>>,
project: Project,
dataProvider: ProjectDataProvider,
traceInfo: TraceInfo
): List<PackageModel.Installed> {
val usageInfoByDependency = mutableMapOf<UnifiedDependency, MutableList<DependencyUsageInfo>>()
for (module in dependenciesByModule.keys) {
dependenciesByModule[module]?.forEach { dependency ->
yield()
// Skip packages we don't know the version for
val rawVersion = dependency.coordinates.version
val usageInfo = DependencyUsageInfo(
projectModule = module,
version = PackageVersion.from(rawVersion),
scope = PackageScope.from(dependency.scope),
userDefinedScopes = module.moduleType.userDefinedScopes(project)
.map { rawScope -> PackageScope.from(rawScope) }
)
val usageInfoList = usageInfoByDependency.getOrPut(dependency) { mutableListOf() }
usageInfoList.add(usageInfo)
}
}
val installedDependencies = dependenciesByModule.values.flatten()
.mapNotNull { InstalledDependency.from(it) }
val dependencyRemoteInfoMap = dataProvider.fetchInfoFor(installedDependencies, traceInfo)
return usageInfoByDependency.parallelMap { (dependency, usageInfo) ->
val installedDependency = InstalledDependency.from(dependency)
val remoteInfo = if (installedDependency != null) {
dependencyRemoteInfoMap[installedDependency]
} else {
null
}
PackageModel.fromInstalledDependency(
unifiedDependency = dependency,
usageInfo = usageInfo,
remoteInfo = remoteInfo,
normalizer = packageVersionNormalizer
)
}.filterNotNull().sortedBy { it.sortKey }
}
internal suspend fun fetchProjectDependencies(
modules: List<ProjectModule>,
cacheDirectory: Path,
json: Json
): Map<ProjectModule, List<UnifiedDependency>> =
coroutineScope {
modules.associateWith { module -> async { module.installedDependencies(cacheDirectory, json) } }
.mapValues { (_, value) -> value.await() }
}
@Suppress("BlockingMethodInNonBlockingContext")
internal suspend fun ProjectModule.installedDependencies(cacheDirectory: Path, json: Json): List<UnifiedDependency> = coroutineScope {
val fileHashCode = buildFile.hashCode()
val cacheFile = File(cacheDirectory.absolutePathString(), "$fileHashCode.json")
if (!cacheFile.exists()) withContext(Dispatchers.IO) {
cacheFile.apply { parentFile.mkdirs() }.createNewFile()
}
val sha256Deferred: Deferred<String> = async(AppExecutorUtil.getAppExecutorService().asCoroutineDispatcher()) {
StringUtil.toHexString(DigestUtil.sha256().digest(buildFile.contentsToByteArray()))
}
val cachedContents = withContext(Dispatchers.IO) { kotlin.runCatching { cacheFile.readText() } }
.onFailure { logDebug("installedDependencies", it) { "Someone messed with our cache file UGH ${cacheFile.absolutePath}" } }
.getOrNull()?.takeIf { it.isNotBlank() }
val cache = if (cachedContents != null) {
// TODO: consider invalidating when ancillary files change (e.g., gradle.properties)
runCatching { json.decodeFromString<InstalledDependenciesCache>(cachedContents) }
.onFailure { logDebug("installedDependencies", it) { "Dependency JSON cache file read failed for ${buildFile.path}" } }
.getOrNull()
} else {
null
}
val sha256 = sha256Deferred.await()
if (cache?.sha256 == sha256 && cache.fileHashCode == fileHashCode && cache.cacheVersion == PluginEnvironment.cachesVersion) {
return@coroutineScope cache.dependencies
}
val dependencies =
readAction {
runCatching {
ProjectModuleOperationProvider.forProjectModuleType(moduleType)
?.listDependenciesInModule(this@installedDependencies)
}
}
.onFailure { logDebug("installedDependencies", it) { "Unable to list dependencies in module $name" } }
.getOrNull()?.toList() ?: emptyList()
nativeModule.project.lifecycleScope.launch {
val jsonText = json.encodeToString(
value = InstalledDependenciesCache(
cacheVersion = PluginEnvironment.cachesVersion,
fileHashCode = fileHashCode,
sha256 = sha256,
projectName = name,
dependencies = dependencies
)
)
withContext(AppExecutorUtil.getAppExecutorService().asCoroutineDispatcher()) {
cacheFile.writeText(jsonText)
}
}
dependencies
}
@Serializable
internal data class InstalledDependenciesCache(
val cacheVersion: Int,
val fileHashCode: Int,
val sha256: String,
val projectName: String,
val dependencies: List<@Serializable(with = UnifiedDependencySerializer::class) UnifiedDependency>
)
internal object UnifiedCoordinatesSerializer : KSerializer<UnifiedCoordinates> {
override val descriptor = buildClassSerialDescriptor(UnifiedCoordinates::class.qualifiedName!!) {
element<String>("groupId", isOptional = true)
element<String>("artifactId", isOptional = true)
element<String>("version", isOptional = true)
}
override fun deserialize(decoder: Decoder) = decoder.decodeStructure(descriptor) {
var groupId: String? = null
var artifactId: String? = null
var version: String? = null
loop@ while (true) {
when (val index = decodeElementIndex(descriptor)) {
DECODE_DONE -> break@loop
0 -> groupId = decodeStringElement(descriptor, 0)
1 -> artifactId = decodeStringElement(descriptor, 1)
2 -> version = decodeStringElement(descriptor, 2)
else -> throw SerializationException("Unexpected index $index")
}
}
UnifiedCoordinates(groupId, artifactId, version)
}
override fun serialize(encoder: Encoder, value: UnifiedCoordinates) = encoder.encodeStructure(descriptor) {
value.groupId?.let { encodeStringElement(descriptor, 0, it) }
value.artifactId?.let { encodeStringElement(descriptor, 1, it) }
value.version?.let { encodeStringElement(descriptor, 2, it) }
}
}
internal object UnifiedDependencySerializer : KSerializer<UnifiedDependency> {
override val descriptor = buildClassSerialDescriptor(UnifiedDependency::class.qualifiedName!!) {
element("coordinates", UnifiedCoordinatesSerializer.descriptor)
element<String>("scope", isOptional = true)
}
override fun deserialize(decoder: Decoder) = decoder.decodeStructure(descriptor) {
var coordinates: UnifiedCoordinates? = null
var scope: String? = null
loop@ while (true) {
when (val index = decodeElementIndex(descriptor)) {
DECODE_DONE -> break@loop
0 -> coordinates = decodeSerializableElement(descriptor, 0, UnifiedCoordinatesSerializer)
1 -> scope = decodeStringElement(descriptor, 1)
else -> throw SerializationException("Unexpected index $index")
}
}
UnifiedDependency(
coordinates = requireNotNull(coordinates) { "coordinates property missing while deserializing ${UnifiedDependency::class.qualifiedName}" },
scope = scope
)
}
override fun serialize(encoder: Encoder, value: UnifiedDependency) = encoder.encodeStructure(descriptor) {
encodeSerializableElement(descriptor, 0, UnifiedCoordinatesSerializer, value.coordinates)
value.scope?.let { encodeStringElement(descriptor, 1, it) }
}
}
| apache-2.0 | b936a226d899631e9ace041baaafac94 | 43.595745 | 151 | 0.722615 | 5.287588 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/idea/tests/testData/structuralsearch/countFilter/maxDestructuringDeclarationEntry.kt | 4 | 514 | data class Foo(val foo1: Int, val foo2: Int)
data class Bar(val bar1: String, val bar2: String, val bar3: String)
fun foo() = Foo(1, 2)
fun bar() = Bar("a", "b", "c")
fun main() {
val (f1, f2) = foo()
val (b1, b2, b3) = bar()
print(f1 + f2)
print(b1 + b2 + b3)
val l1 = listOf(Foo(1, 1))
for ((x1, x2) in l1) { print(x1 + x2) }
val l2 = listOf(Bar("a", "a", "a"))
<warning descr="SSR">for ((x1, x2, x3) in l2) { print(x1 + x2 + x3) }</warning>
for (i in 1..2) { print(i) }
} | apache-2.0 | 95ecf894dce126477bd9f31918af0dda | 26.105263 | 83 | 0.521401 | 2.264317 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/idea/tests/testData/slicer/outflow/varParameter.kt | 13 | 233 | // FLOW: OUT
class A(var <caret>n: Int) {
val x = n
val y: Int
init {
y = n
bar(n)
}
fun bar(m: Int) {
val z = n
n = 1
}
}
fun test() {
val z = A(1).n
A(1).n = 2
} | apache-2.0 | 5ae8e110a77d1642b0f9d9f6bc891009 | 9.173913 | 28 | 0.351931 | 2.617978 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/codeInliner/introduceValue.kt | 2 | 6153 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.codeInliner
import org.jetbrains.kotlin.idea.analysis.computeTypeInContext
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.caches.resolve.getResolutionFacade
import org.jetbrains.kotlin.idea.core.KotlinNameSuggester
import org.jetbrains.kotlin.idea.core.isVisible
import org.jetbrains.kotlin.idea.core.setType
import org.jetbrains.kotlin.idea.util.getAllAccessibleVariables
import org.jetbrains.kotlin.idea.util.getResolutionScope
import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.collectDescendantsOfType
import org.jetbrains.kotlin.psi.psiUtil.getReceiverExpression
import org.jetbrains.kotlin.psi.psiUtil.isAncestor
import org.jetbrains.kotlin.renderer.render
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.bindingContextUtil.getDataFlowInfoBefore
import org.jetbrains.kotlin.resolve.descriptorUtil.isExtension
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
import org.jetbrains.kotlin.resolve.scopes.LexicalScope
import org.jetbrains.kotlin.types.ErrorUtils
import org.jetbrains.kotlin.types.KotlinType
/**
* Modifies [MutableCodeToInline] introducing a variable initialized by [value] and replacing all of [usages] with its use.
* The variable must be initialized (and so the value is calculated) before any other code in [MutableCodeToInline].
* @param value Value to use for variable initialization
* @param valueType Type of the value
* @param usages Usages to be replaced. This collection can be empty and in this case the actual variable is not needed.
* But the expression [value] must be calculated because it may have side effects.
* @param expressionToBeReplaced Expression to be replaced by the [MutableCodeToInline].
* @param nameSuggestion Name suggestion for the variable.
* @param safeCall If true, then the whole code must not be executed if the [value] evaluates to null.
*/
internal fun MutableCodeToInline.introduceValue(
value: KtExpression,
valueType: KotlinType?,
usages: Collection<KtExpression>,
expressionToBeReplaced: KtExpression,
nameSuggestion: String? = null,
safeCall: Boolean = false
) {
assert(usages.all { it in this })
val psiFactory = KtPsiFactory(value)
val bindingContext = expressionToBeReplaced.analyze(BodyResolveMode.FULL)
fun replaceUsages(name: Name) {
val nameInCode = psiFactory.createExpression(name.render())
for (usage in usages) {
// there can be parenthesis around the expression which will become unnecessary
val usageToReplace = (usage.parent as? KtParenthesizedExpression) ?: usage
replaceExpression(usageToReplace, nameInCode)
}
}
fun suggestName(validator: (String) -> Boolean): Name {
val name = if (nameSuggestion != null)
KotlinNameSuggester.suggestNameByName(nameSuggestion, validator)
else
KotlinNameSuggester.suggestNamesByExpressionOnly(value, bindingContext, validator, "t").first()
return Name.identifier(name)
}
// checks that name is used (without receiver) inside code being constructed but not inside usages that will be replaced
fun isNameUsed(name: String) = collectNameUsages(this, name).any { nameUsage -> usages.none { it.isAncestor(nameUsage) } }
if (!safeCall) {
if (usages.isNotEmpty()) {
val resolutionScope = expressionToBeReplaced.getResolutionScope(bindingContext, expressionToBeReplaced.getResolutionFacade())
val name = suggestName { name -> !name.nameHasConflictsInScope(resolutionScope) && !isNameUsed(name) }
val declaration = psiFactory.createDeclarationByPattern<KtVariableDeclaration>("val $0 = $1", name, value)
statementsBefore.add(0, declaration)
valueType?.takeIf {
variableNeedsExplicitType(value, valueType, expressionToBeReplaced, resolutionScope, bindingContext)
}?.let { explicitType ->
addPostInsertionAction(declaration) { it.setType(explicitType) }
}
replaceUsages(name)
} else {
statementsBefore.add(0, value)
}
} else {
val useIt = !isNameUsed("it")
val name = if (useIt) Name.identifier("it") else suggestName { !isNameUsed(it) }
replaceUsages(name)
mainExpression = psiFactory.buildExpression {
appendExpression(value)
if (valueType?.isMarkedNullable != false) {
appendFixedText("?")
}
appendFixedText(".let {")
if (!useIt) {
appendName(name)
appendFixedText("->")
}
appendExpressionsFromCodeToInline()
appendFixedText("}")
}
statementsBefore.clear()
}
}
fun String.nameHasConflictsInScope(lexicalScope: LexicalScope): Boolean = lexicalScope.getAllAccessibleVariables(Name.identifier(this)).any {
!it.isExtension && it.isVisible(lexicalScope.ownerDescriptor)
}
private fun variableNeedsExplicitType(
initializer: KtExpression,
initializerType: KotlinType,
context: KtExpression,
resolutionScope: LexicalScope,
bindingContext: BindingContext
): Boolean {
if (ErrorUtils.containsErrorType(initializerType)) return false
val valueTypeWithoutExpectedType = initializer.computeTypeInContext(
resolutionScope,
context,
dataFlowInfo = bindingContext.getDataFlowInfoBefore(context)
)
return valueTypeWithoutExpectedType == null || ErrorUtils.containsErrorType(valueTypeWithoutExpectedType)
}
private fun collectNameUsages(scope: MutableCodeToInline, name: String): List<KtSimpleNameExpression> {
return scope.expressions.flatMap { expression ->
expression.collectDescendantsOfType { it.getReceiverExpression() == null && it.getReferencedName() == name }
}
}
| apache-2.0 | 6f2a95166ce3c3eacc9e919b668f3938 | 42.330986 | 158 | 0.728588 | 4.994318 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/RedundantUnitExpressionInspection.kt | 4 | 5494 | // 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.*
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiElementVisitor
import org.jetbrains.kotlin.builtins.StandardNames
import org.jetbrains.kotlin.cfg.WhenChecker
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.caches.resolve.resolveToCall
import org.jetbrains.kotlin.idea.intentions.loopToCallChain.previousStatement
import org.jetbrains.kotlin.idea.util.isUnitLiteral
import org.jetbrains.kotlin.js.descriptorUtils.nameIfStandardType
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.getParentOfTypesAndPredicate
import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType
import org.jetbrains.kotlin.psi.psiUtil.lastBlockStatementOrThis
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.DescriptorToSourceUtils
import org.jetbrains.kotlin.resolve.bindingContextUtil.getTargetFunctionDescriptor
import org.jetbrains.kotlin.resolve.calls.model.ArgumentMatch
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
import org.jetbrains.kotlin.types.KotlinType
import org.jetbrains.kotlin.types.isDynamic
import org.jetbrains.kotlin.types.typeUtil.isUnit
class RedundantUnitExpressionInspection : AbstractKotlinInspection(), CleanupLocalInspectionTool {
override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean): PsiElementVisitor = referenceExpressionVisitor(fun(expression) {
if (isRedundantUnit(expression)) {
holder.registerProblem(
expression,
KotlinBundle.message("redundant.unit"),
ProblemHighlightType.LIKE_UNUSED_SYMBOL,
RemoveRedundantUnitFix()
)
}
})
companion object {
fun isRedundantUnit(referenceExpression: KtReferenceExpression): Boolean {
if (!referenceExpression.isUnitLiteral) return false
val parent = referenceExpression.parent ?: return false
if (parent is KtReturnExpression) {
val expectedReturnType = parent.expectedReturnType() ?: return false
return expectedReturnType.nameIfStandardType != StandardNames.FqNames.any.shortName() && !expectedReturnType.isMarkedNullable
}
if (parent is KtBlockExpression) {
if (referenceExpression == parent.lastBlockStatementOrThis()) {
val prev = referenceExpression.previousStatement() ?: return true
if (prev.isUnitLiteral) return true
if (prev is KtDeclaration && isDynamicCall(parent)) return false
val context = prev.analyze(BodyResolveMode.PARTIAL)
val prevType = context.getType(prev)
if (prevType != null) {
return prevType.isUnit() && prev.canBeUsedAsValue(context)
}
if (prev !is KtDeclaration) return false
if (prev !is KtFunction) return true
return parent.getParentOfTypesAndPredicate(
true,
KtIfExpression::class.java,
KtWhenExpression::class.java
) { true } == null
}
return true
}
return false
}
}
}
private fun isDynamicCall(parent: KtBlockExpression): Boolean = parent.getStrictParentOfType<KtFunctionLiteral>()
?.findLambdaReturnType()
?.isDynamic() == true
private fun KtReturnExpression.expectedReturnType(): KotlinType? {
val functionDescriptor = getTargetFunctionDescriptor(analyze()) ?: return null
val functionLiteral = DescriptorToSourceUtils.descriptorToDeclaration(functionDescriptor) as? KtFunctionLiteral
return if (functionLiteral != null)
functionLiteral.findLambdaReturnType()
else
functionDescriptor.returnType
}
private fun KtFunctionLiteral.findLambdaReturnType(): KotlinType? {
val callExpression = getStrictParentOfType<KtCallExpression>() ?: return null
val resolvedCall = callExpression.resolveToCall() ?: return null
val valueArgument = getStrictParentOfType<KtValueArgument>() ?: return null
val mapping = resolvedCall.getArgumentMapping(valueArgument) as? ArgumentMatch ?: return null
return mapping.valueParameter.returnType?.arguments?.lastOrNull()?.type
}
private fun KtExpression.canBeUsedAsValue(context: BindingContext): Boolean {
return when (this) {
is KtIfExpression -> {
val elseExpression = `else`
if (elseExpression is KtIfExpression) elseExpression.canBeUsedAsValue(context) else elseExpression != null
}
is KtWhenExpression ->
entries.lastOrNull()?.elseKeyword != null || WhenChecker.getMissingCases(this, context).isEmpty()
else ->
true
}
}
private class RemoveRedundantUnitFix : LocalQuickFix {
override fun getName() = KotlinBundle.message("remove.redundant.unit.fix.text")
override fun getFamilyName() = name
override fun applyFix(project: Project, descriptor: ProblemDescriptor) {
(descriptor.psiElement as? KtReferenceExpression)?.delete()
}
}
| apache-2.0 | d1483e2d2ca4b7095d2e805dd36a1683 | 44.783333 | 158 | 0.706953 | 5.566363 | false | false | false | false |
Cognifide/gradle-aem-plugin | src/main/kotlin/com/cognifide/gradle/aem/pkg/tasks/sync/CleanerRule.kt | 1 | 1690 | package com.cognifide.gradle.aem.pkg.tasks.sync
import com.cognifide.gradle.common.utils.Patterns
import com.cognifide.gradle.aem.common.pkg.vault.VaultException
import java.io.File
class CleanerRule(value: String) {
private var pattern: String = value
private var excludedPaths: List<String> = listOf()
private var includedPaths: List<String> = listOf()
init {
if (value.contains(PATHS_DELIMITER)) {
val parts = value.split(PATHS_DELIMITER)
if (parts.size == 2) {
pattern = parts[0].trim()
val paths = parts[1].split(PATH_DELIMITER)
excludedPaths = paths.filter { it.contains(EXCLUDE_FLAG) }.map { it.removePrefix(EXCLUDE_FLAG).trim() }
includedPaths = paths.filter { !it.contains(EXCLUDE_FLAG) }.map { it.trim() }
} else {
throw VaultException("Cannot parse VLT content property: '$value'")
}
}
}
private fun isIncluded(file: File) = Patterns.wildcard(file, includedPaths)
private fun isExcluded(file: File) = Patterns.wildcard(file, excludedPaths)
fun match(file: File, value: String): Boolean {
return Patterns.wildcard(value, pattern) && match(file)
}
private fun match(file: File): Boolean {
return (excludedPaths.isEmpty() || !isExcluded(file)) && (includedPaths.isEmpty() || isIncluded(file))
}
companion object {
const val PATHS_DELIMITER = "|"
const val PATH_DELIMITER = ","
const val EXCLUDE_FLAG = "!"
fun manyFrom(props: List<String>): List<CleanerRule> {
return props.map { CleanerRule(it) }
}
}
}
| apache-2.0 | c4bf788018a7ab9019704b51a3ba04df | 31.5 | 119 | 0.62071 | 4.17284 | false | false | false | false |
kravchik/senjin | src/main/java/yk/senjin/shaders/kshader/vec3.kt | 1 | 446 | package yk.senjin.shaders.kshader
/**
* Created by Yuri Kravchik on 10.10.2018
*/
//class vec3 (inX:Float = 0f, inY:Float = 0f, inZ:Float = 0f) {
// var x = inX
// var y = inY
// var z = inZ
//
// operator fun plus(b:vec3): vec3 {
// val result = vec3(x + b.x, y + b.y, z + b.z)
// return result as vec3
// }
//
// override fun toString(): String {
// return "vec3(x=$x, y=$y, z=$z)"
// }
//
//
//}
| mit | ea4b161ad70cac7cf09fe374622703cc | 18.391304 | 63 | 0.504484 | 2.423913 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.