repo_name
stringlengths 7
81
| path
stringlengths 6
242
| copies
stringclasses 55
values | size
stringlengths 2
6
| content
stringlengths 55
737k
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 5.44
99.8
| line_max
int64 15
979
| alpha_frac
float64 0.3
0.91
| ratio
float64 2
9.93
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
VKCOM/vk-android-sdk | api/src/main/java/com/vk/sdk/api/account/dto/AccountOffer.kt | 1 | 3103 | /**
* The MIT License (MIT)
*
* Copyright (c) 2019 vk.com
*
* 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.
*/
// *********************************************************************
// THIS FILE IS AUTO GENERATED!
// DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING.
// *********************************************************************
package com.vk.sdk.api.account.dto
import com.google.gson.annotations.SerializedName
import kotlin.Float
import kotlin.Int
import kotlin.String
/**
* @param description - Offer description
* @param id - Offer ID
* @param img - URL of the preview image
* @param instruction - Instruction how to process the offer
* @param instructionHtml - Instruction how to process the offer (HTML format)
* @param price - Offer price
* @param shortDescription - Offer short description
* @param tag - Offer tag
* @param title - Offer title
* @param currencyAmount - Currency amount
* @param linkId - Link id
* @param linkType - Link type
*/
data class AccountOffer(
@SerializedName("description")
val description: String? = null,
@SerializedName("id")
val id: Int? = null,
@SerializedName("img")
val img: String? = null,
@SerializedName("instruction")
val instruction: String? = null,
@SerializedName("instruction_html")
val instructionHtml: String? = null,
@SerializedName("price")
val price: Int? = null,
@SerializedName("short_description")
val shortDescription: String? = null,
@SerializedName("tag")
val tag: String? = null,
@SerializedName("title")
val title: String? = null,
@SerializedName("currency_amount")
val currencyAmount: Float? = null,
@SerializedName("link_id")
val linkId: Int? = null,
@SerializedName("link_type")
val linkType: AccountOffer.LinkType? = null
) {
enum class LinkType(
val value: String
) {
@SerializedName("profile")
PROFILE("profile"),
@SerializedName("group")
GROUP("group"),
@SerializedName("app")
APP("app");
}
}
| mit | 2b84d6b7f0bcdca43d7942df5b86f093 | 34.666667 | 81 | 0.668063 | 4.458333 | false | false | false | false |
Hentioe/BloggerMini | app/src/main/kotlin/io/bluerain/tweets/ui/ShowCommentsActivity.kt | 1 | 7360 | package io.bluerain.tweets.ui
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.support.v7.widget.LinearLayoutManager
import android.view.MenuItem
import android.view.View
import android.view.WindowManager
import android.widget.TextView
import com.facebook.drawee.view.SimpleDraweeView
import io.bluerain.tweets.R
import io.bluerain.tweets.adapter.BaseRecyclerViewAdapter
import io.bluerain.tweets.adapter.BaseRecyclerViewHolder
import io.bluerain.tweets.base.BaseActivity
import io.bluerain.tweets.data.models.*
import io.bluerain.tweets.presenter.ShowCommentsPresenter
import io.bluerain.tweets.utils.HtmlUtil
import io.bluerain.tweets.view.IShowCommentsView
import kotlinx.android.synthetic.main.activity_show_comments_main.*
/**
* Created by hentioe on 17-5-9.
* 查看评论 Activity
*/
class ShowCommentsActivity : BaseActivity<ShowCommentsPresenter, IShowCommentsView>(), IShowCommentsView {
override fun clearInput() {
edt_show_comments_content.setText("")
}
override fun initHintContent(face: String, info: String, content: String) {
show_comments_attach_info.text = info
show_comments_hint_content.text = HtmlUtil.fromHtml(content)
show_comments_attach_face.setImageURI(face)
}
override fun getIntentExtra(): IntentExtra {
return IntentExtra(id = resId, type = resType, content = resContent)
}
override fun providePresenter(): ShowCommentsPresenter {
return ShowCommentsPresenter()
}
companion object {
val RES_TYPE_KEY = "RES_TYPE_KEY"
val RES_ID_KEY = "RES_ID_KEY"
fun launch(context: Context, resType: Int, resId: Long) {
val intent = Intent(context, ShowCommentsActivity::class.java)
intent.putExtra(ShowCommentsActivity.RES_TYPE_KEY, resType)
intent.putExtra(ShowCommentsActivity.RES_ID_KEY, resId)
context.startActivity(intent)
}
var DATA_LIST: List<CommentModel> = arrayListOf()
}
data class IntentExtra(
val id: Long = 0,
val type: Int = 0,
val content: String = ""
)
var currentReplyResId = 0L
var currentReplyTo = -1L
override fun initEvent() {
refresh_show_comments.setOnRefreshListener {
presenter.updateList(resType, resId)
}
btn_show_comments_publisher.setOnClickListener {
val id = if (currentReplyResId == 0L) resId else currentReplyResId
val type = if (currentReplyResId == 0L) resType else 1
presenter.publish(currentReplyTo, type, id, edt_show_comments_content.text.toString())
}
show_comments_hint_content.setOnClickListener {
when (resType) {
0 -> ArticleInfoActivity.launch(this, (presenter.resData as ArticleModel).query)
1 -> {
val comment = presenter.resData as CommentModel
ShowCommentsActivity.launch(this, comment.resType, comment.resId)
}
}
}
}
override fun initListView(list: List<CommentModel>) {
show_comment_recycler_view.setHasFixedSize(true)
show_comment_recycler_view.layoutManager = LinearLayoutManager(this)
show_comment_recycler_view.adapter = ShowCommentRecyclerAdapter(list, this)
if (show_comment_recycler_view.adapter.itemCount == 0){
}
DATA_LIST = list
}
override fun clearContent() {
edt_show_comments_content.setText("")
}
override fun stopRefreshing() {
refresh_show_comments.isRefreshing = false
}
var resType = 0
get
var resId = 0L
get
var resContent = ""
get
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
resType = intent.getIntExtra(RES_TYPE_KEY, 0)
resId = intent.getLongExtra(RES_ID_KEY, 10000L)
setContentView(R.layout.activity_show_comments_main)
val actionBar = supportActionBar
if (actionBar != null) {
actionBar.setHomeButtonEnabled(true)
actionBar.setDisplayHomeAsUpEnabled(true)
actionBar.title = if (resType == 1) "查看回复" else "查看评论"
}
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
android.R.id.home -> {
this.finish()
}
}
return super.onOptionsItemSelected(item)
}
}
class ShowCommentRecyclerViewHolder(items: View) : BaseRecyclerViewHolder(items) {
val faceView = find(R.id.show_comments_recycler_item_face) as SimpleDraweeView
val infoView = find(R.id.show_comments_recycler_item_info) as TextView
val contentView = find(R.id.show_comments_recycler_item_content) as TextView
val timeView = find(R.id.show_comments_recycler_item_time) as TextView
val statusView = find(R.id.show_comments_recycler_item_status) as TextView
val topView = find(R.id.show_comments_recycler_item_top) as TextView
}
open class ShowCommentRecyclerAdapter(items: List<CommentModel>, var activity: ShowCommentsActivity?) :
BaseRecyclerViewAdapter<ShowCommentRecyclerViewHolder, CommentModel>(items, R.layout.recycler_item_show_comments) {
override fun onCreateViewHolderByView(itemView: View): ShowCommentRecyclerViewHolder {
return ShowCommentRecyclerViewHolder(itemView)
}
override fun onBindViewHolder(holder: ShowCommentRecyclerViewHolder, position: Int) {
val model = getModel(position)
holder.infoView.text = model.nickname
holder.contentView.text = model.content
holder.faceView.setImageURI(model.face)
holder.timeView.text = model.timeToString()
if (!model.isNormal()) {
holder.statusView.text = model.statusToString()
holder.statusView.visibility = View.VISIBLE
} else {
holder.statusView.visibility = View.GONE
}
if (model.isTop())
holder.topView.visibility = View.VISIBLE
else
holder.topView.visibility = View.GONE
super.onBindViewHolder(holder, position)
}
override fun onBindEvent(holder: ShowCommentRecyclerViewHolder, position: Int) {
val comment = ShowCommentsActivity.DATA_LIST[position]
if (activity != null) {
val act = activity!!
holder.faceView.setOnClickListener {
if (act.edt_show_comments_content.requestFocus()) {
act.window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE)
}
act.edt_show_comments_content.setText("${act.edt_show_comments_content.text}@${comment.nickname} ")
act.edt_show_comments_content.setSelection(act.edt_show_comments_content.length())
act.currentReplyResId = if (act.resType == 1) act.resId else comment.id
act.currentReplyTo = comment.id
}
holder.contentView.setOnClickListener {
if (comment.resType == 1) {
act.showText("已经是子评论了,没有下级评论!")
}
ShowCommentsActivity.launch(act, 1, comment.id)
}
}
}
} | gpl-3.0 | 3d773a020e2ccce3237603d3561412c8 | 34.299517 | 123 | 0.660279 | 4.504316 | false | false | false | false |
czyzby/ktx | app/src/test/kotlin/ktx/app/gameTest.kt | 2 | 6845 | package ktx.app
import com.badlogic.gdx.Gdx
import com.badlogic.gdx.Screen
import com.badlogic.gdx.graphics.GL20
import com.badlogic.gdx.utils.GdxRuntimeException
import com.nhaarman.mockitokotlin2.any
import com.nhaarman.mockitokotlin2.argThat
import com.nhaarman.mockitokotlin2.doReturn
import com.nhaarman.mockitokotlin2.doThrow
import com.nhaarman.mockitokotlin2.eq
import com.nhaarman.mockitokotlin2.mock
import com.nhaarman.mockitokotlin2.never
import com.nhaarman.mockitokotlin2.times
import com.nhaarman.mockitokotlin2.verify
import org.junit.After
import org.junit.Assert.assertFalse
import org.junit.Assert.assertNull
import org.junit.Assert.assertSame
import org.junit.Assert.assertTrue
import org.junit.Before
import org.junit.Test
/**
* Tests [KtxGame]: KTX equivalent of [com.badlogic.gdx.Game].
*/
class KtxGameTest {
@Before
fun `set up OpenGL`() {
Gdx.gl20 = mock()
Gdx.gl = Gdx.gl20
}
@Test
fun `should display firstScreen without registration`() {
val screen = mock<Screen>()
val game = KtxGame(firstScreen = screen)
Gdx.graphics = mock {
on(it.width) doReturn 800
on(it.height) doReturn 600
}
game.create()
assertSame(screen, game.shownScreen)
verify(screen).resize(800, 600)
verify(screen).show()
// addScreen must be called manually to keep firstScreen in context - should not contain initial Screen:
assertFalse(game.containsScreen<Screen>())
}
@Test
fun `should clear screen on render`() {
val game = KtxGame(firstScreen = MockScreen())
Gdx.graphics = mock()
game.render()
verify(Gdx.gl).glClearColor(0f, 0f, 0f, 1f)
verify(Gdx.gl).glClear(GL20.GL_COLOR_BUFFER_BIT or GL20.GL_DEPTH_BUFFER_BIT)
}
@Test
fun `should not clear screen on render if screen clearing is turned off`() {
val game = KtxGame(clearScreen = false, firstScreen = MockScreen())
Gdx.graphics = mock()
game.render()
verify(Gdx.gl, never()).glClearColor(any(), any(), any(), any())
verify(Gdx.gl, never()).glClear(any())
}
@Test
fun `should delegate resize call to current screen`() {
val screen = mock<Screen>()
val game = KtxGame(screen)
game.resize(100, 200)
verify(screen).resize(100, 200)
}
@Test
fun `should delegate pause call to current screen`() {
val screen = mock<Screen>()
val game = KtxGame(screen)
game.pause()
verify(screen).pause()
}
@Test
fun `should delegate resume call to current screen`() {
val screen = mock<Screen>()
val game = KtxGame(screen)
game.resume()
verify(screen).resume()
}
@Test(expected = GdxRuntimeException::class)
fun `should fail to provide non-registered Screen`() {
val game = KtxGame<Screen>()
game.getScreen<KtxScreen>()
}
@Test
fun `should register Screen instance`() {
val screen = mock<KtxScreen>()
val game = KtxGame<Screen>()
game.addScreen(screen)
assertTrue(game.containsScreen<KtxScreen>())
assertSame(screen, game.getScreen<KtxScreen>())
}
@Test(expected = GdxRuntimeException::class)
fun `should fail to register Screen instance to same type multiple times`() {
val game = KtxGame<Screen>()
game.addScreen(mock<KtxScreen>())
game.addScreen(mock<KtxScreen>())
}
@Test
fun `should not throw exception when trying to remove unregistered Screen`() {
val game = KtxGame<Screen>()
val removed = game.removeScreen<KtxScreen>()
assertNull(removed)
assertFalse(game.containsScreen<KtxScreen>())
}
@Test
fun `should remove Screen`() {
val screen = mock<KtxScreen>()
val game = KtxGame<Screen>()
game.addScreen(screen)
val removed = game.removeScreen<KtxScreen>()
assertSame(screen, removed)
assertFalse(game.containsScreen<KtxScreen>())
verify(screen, never()).dispose() // Should not dispose of Screen upon removal.
}
@Test
fun `should reassign Screen`() {
val game = KtxGame<Screen>()
val initialScreen = mock<KtxScreen>()
val replacement = mock<KtxScreen>()
game.addScreen(initialScreen)
game.removeScreen<KtxScreen>()
game.addScreen(replacement)
assertTrue(game.containsScreen<KtxScreen>())
assertSame(replacement, game.getScreen<KtxScreen>())
verify(initialScreen, never()).dispose() // Should not dispose of previous KtxScreen upon removal.
}
@Test
fun `should set current Screen`() {
val firstScreen = mock<Screen>()
val secondScreen = mock<KtxScreen>()
val game = KtxGame(firstScreen)
game.addScreen(secondScreen)
Gdx.graphics = mock {
on(it.width) doReturn 800
on(it.height) doReturn 600
}
game.setScreen<KtxScreen>()
assertSame(secondScreen, game.shownScreen)
verify(firstScreen).hide()
verify(secondScreen).resize(800, 600)
verify(secondScreen).show()
}
@Test(expected = GdxRuntimeException::class)
fun `should fail to set unregistered Screen`() {
val game = KtxGame<Screen>()
game.setScreen<MockScreen>()
}
@Test
fun `should dispose of all registered Screen instances`() {
val screen = mock<Screen>()
val ktxScreen = mock<KtxScreen>()
val game = KtxGame<Screen>()
game.addScreen(screen)
game.addScreen(ktxScreen)
game.dispose()
verify(screen).dispose()
verify(ktxScreen).dispose()
}
@Test
fun `should dispose of all registered Screen instances with error handling`() {
Gdx.app = mock()
val screen = mock<Screen>()
val ktxScreen = mock<KtxScreen> {
on(it.dispose()) doThrow GdxRuntimeException("Expected.")
}
val mockScreen = mock<MockScreen> {
on(it.dispose()) doThrow GdxRuntimeException("Expected.")
}
val game = KtxGame<Screen>()
game.addScreen(screen)
game.addScreen(ktxScreen)
game.addScreen(mockScreen)
game.dispose()
verify(screen).dispose()
verify(ktxScreen).dispose()
// Ensures exceptions were logged:
verify(Gdx.app, times(2)).error(eq("KTX"), any(), argThat { this is GdxRuntimeException })
}
@After
fun `clear static libGDX variables`() {
Gdx.graphics = null
Gdx.gl = null
Gdx.gl20 = null
Gdx.app = null
}
/** [Screen] implementation that tracks how many times it was rendered. */
open class MockScreen : KtxScreen {
private var rendered = false
private var renderedTimes = 0
override fun render(delta: Float) {
rendered = true
renderedTimes++
}
}
}
/**
* Tests [Screen] utilities.
*/
class KtxScreenTest {
@Test
fun `should provide mock-up screen instance`() {
val screen = emptyScreen()
assertTrue(Screen::class.isInstance(screen))
}
@Suppress("unused", "ClassName")
class `should implement KtxScreen with no methods overridden` : KtxScreen {
// Guarantees all KtxScreen methods are optional to implement.
}
}
| cc0-1.0 | 5b78e6321495fe4407a9c77a0c199d90 | 24.733083 | 108 | 0.684149 | 4.084129 | false | true | false | false |
HabitRPG/habitica-android | Habitica/src/main/java/com/habitrpg/android/habitica/ui/views/promo/PromoMenuView.kt | 1 | 2237 | package com.habitrpg.android.habitica.ui.views.promo
import android.content.Context
import android.graphics.drawable.Drawable
import android.util.AttributeSet
import android.view.View
import android.widget.ImageView
import android.widget.RelativeLayout
import android.widget.TextView
import androidx.core.content.ContextCompat
import com.habitrpg.android.habitica.R
import com.habitrpg.android.habitica.databinding.PromoMenuBinding
import com.habitrpg.common.habitica.extensions.layoutInflater
class PromoMenuView @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
defStyleAttr: Int = 0
) : RelativeLayout(context, attrs, defStyleAttr) {
var canClose: Boolean = false
set(value) {
field = value
binding.closeButton.visibility = if (value) View.VISIBLE else View.GONE
}
var binding: PromoMenuBinding = PromoMenuBinding.inflate(context.layoutInflater, this)
init {
setBackgroundColor(ContextCompat.getColor(context, R.color.window_background))
clipToPadding = false
clipChildren = false
clipToOutline = false
}
fun setTitleText(title: String?) {
setText(binding.titleTextView, title)
}
fun setSubtitleText(subtitle: String?) {
setText(binding.descriptionView, subtitle)
}
fun setTitleImage(title: Drawable?) {
setImage(binding.titleImageView, title)
}
fun setSubtitleImage(subtitle: Drawable?) {
setImage(binding.descriptionImageView, subtitle)
}
fun setDecoration(leftDrawable: Drawable?, rightDrawable: Drawable?) {
binding.leftImageView.setImageDrawable(leftDrawable)
binding.rightImageView.setImageDrawable(rightDrawable)
}
private fun setImage(view: ImageView, drawable: Drawable?) {
if (drawable != null) {
view.setImageDrawable(drawable)
view.visibility = View.VISIBLE
} else {
view.visibility = View.GONE
}
}
private fun setText(view: TextView, text: String?) {
if (text != null) {
view.text = text
view.visibility = View.VISIBLE
} else {
view.visibility = View.GONE
}
}
}
| gpl-3.0 | f30417c8211b74e1f1ee41236ceace94 | 29.643836 | 90 | 0.686187 | 4.660417 | false | false | false | false |
rhdunn/xquery-intellij-plugin | src/intellij-test/main/uk/co/reecedunn/intellij/plugin/core/tests/psi/MockPsiManager.kt | 1 | 4134 | /*
* Copyright (C) 2016-2021 Reece H. Dunn
*
* 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 uk.co.reecedunn.intellij.plugin.core.tests.psi
import com.intellij.compat.psi.impl.PsiManagerEx
import com.intellij.lang.LanguageUtil
import com.intellij.mock.MockFileManager
import com.intellij.openapi.Disposable
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Comparing
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.openapi.vfs.VirtualFileFilter
import com.intellij.psi.*
import com.intellij.psi.impl.PsiModificationTrackerImpl
import com.intellij.psi.impl.PsiTreeChangeEventImpl
import com.intellij.psi.impl.file.impl.FileManager
import com.intellij.psi.util.PsiModificationTracker
import uk.co.reecedunn.intellij.plugin.core.vfs.decode
import java.io.IOException
// NOTE: The IntelliJ version of MockPsiManager is final in IntelliJ 2020.2, so
// it cannot be used as the base class.
class MockPsiManager(private val project: Project) : PsiManagerEx() {
// region PsiManager
private val myModificationTracker: PsiModificationTracker by lazy { PsiModificationTrackerImpl(project) }
override fun getProject(): Project = project
override fun findFile(file: VirtualFile): PsiFile? {
try {
val language = LanguageUtil.getLanguageForPsi(project, file) ?: return null
return PsiFileFactory.getInstance(project).createFileFromText(
file.name, language, file.decode() ?: return null, true, false, false, file
)
} catch (e: IOException) {
return null
}
}
override fun findViewProvider(file: VirtualFile): FileViewProvider? = null
override fun findDirectory(file: VirtualFile): PsiDirectory? = null
override fun areElementsEquivalent(element1: PsiElement?, element2: PsiElement?): Boolean {
return Comparing.equal(element1, element2)
}
override fun reloadFromDisk(file: PsiFile) {
}
override fun addPsiTreeChangeListener(listener: PsiTreeChangeListener) {
}
override fun addPsiTreeChangeListener(listener: PsiTreeChangeListener, parentDisposable: Disposable) {
}
override fun removePsiTreeChangeListener(listener: PsiTreeChangeListener) {
}
override fun getModificationTracker(): PsiModificationTracker = myModificationTracker
override fun startBatchFilesProcessingMode() {
}
override fun finishBatchFilesProcessingMode() {
}
override fun isDisposed(): Boolean = false
override fun dropResolveCaches(): Unit = fileManager.cleanupForNextTest()
override fun dropPsiCaches(): Unit = dropResolveCaches()
override fun isInProject(element: PsiElement): Boolean = false
// endregion
// region PsiManagerEx
private val myFileManager: FileManager by lazy { MockFileManager(this) }
override fun isBatchFilesProcessingMode(): Boolean = false
override fun setAssertOnFileLoadingFilter(filter: VirtualFileFilter, parentDisposable: Disposable) {
}
override fun isAssertOnFileLoading(file: VirtualFile): Boolean = false
override fun getFileManager(): FileManager = myFileManager
override fun beforeChildAddition(event: PsiTreeChangeEventImpl) {
}
override fun beforeChildRemoval(event: PsiTreeChangeEventImpl) {
}
override fun beforeChildReplacement(event: PsiTreeChangeEventImpl) {
}
override fun beforeChange(isPhysical: Boolean) {
throw UnsupportedOperationException()
}
override fun afterChange(isPhysical: Boolean) {
throw UnsupportedOperationException()
}
// endregion
}
| apache-2.0 | 3349dd79eea0adc215b8ee78b62a4d76 | 32.885246 | 109 | 0.746976 | 4.880756 | false | false | false | false |
StepicOrg/stepic-android | app/src/main/java/org/stepik/android/view/step_quiz_sorting/ui/delegate/SortingStepQuizFormDelegate.kt | 1 | 3199 | package org.stepik.android.view.step_quiz_sorting.ui.delegate
import android.view.View
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.SimpleItemAnimator
import kotlinx.android.synthetic.main.fragment_step_quiz.view.*
import kotlinx.android.synthetic.main.layout_step_quiz_sorting.view.*
import org.stepic.droid.R
import org.stepik.android.model.Reply
import org.stepik.android.presentation.step_quiz.StepQuizFeature
import org.stepik.android.presentation.step_quiz.model.ReplyResult
import org.stepik.android.view.step_quiz.resolver.StepQuizFormResolver
import org.stepik.android.view.step_quiz.ui.delegate.StepQuizFormDelegate
import org.stepik.android.view.step_quiz_sorting.ui.adapter.delegate.SortingOptionAdapterDelegate
import org.stepik.android.view.step_quiz_sorting.ui.mapper.SortingOptionMapper
import org.stepik.android.view.step_quiz_sorting.ui.model.SortingOption
import ru.nobird.android.core.model.swap
import ru.nobird.android.ui.adapters.DefaultDelegateAdapter
class SortingStepQuizFormDelegate(
containerView: View,
private val onQuizChanged: (ReplyResult) -> Unit
) : StepQuizFormDelegate {
private val quizDescription = containerView.stepQuizDescription
private val optionsAdapter = DefaultDelegateAdapter<SortingOption>()
private val sortingOptionMapper = SortingOptionMapper()
init {
quizDescription.setText(R.string.step_quiz_sorting_description)
optionsAdapter += SortingOptionAdapterDelegate(optionsAdapter, ::moveSortingOption)
with(containerView.sortingRecycler) {
adapter = optionsAdapter
isNestedScrollingEnabled = false
layoutManager = LinearLayoutManager(context)
(itemAnimator as? SimpleItemAnimator)
?.supportsChangeAnimations = false
}
}
private fun moveSortingOption(position: Int, direction: SortingOptionAdapterDelegate.SortingDirection) {
val targetPosition =
when (direction) {
SortingOptionAdapterDelegate.SortingDirection.UP ->
position - 1
SortingOptionAdapterDelegate.SortingDirection.DOWN ->
position + 1
}
optionsAdapter.items = optionsAdapter.items.swap(position, targetPosition)
optionsAdapter.notifyItemChanged(position)
optionsAdapter.notifyItemChanged(targetPosition)
onQuizChanged(createReply())
}
override fun setState(state: StepQuizFeature.State.AttemptLoaded) {
val sortingOptions = sortingOptionMapper
.mapToSortingOptions(state.attempt, StepQuizFormResolver.isQuizEnabled(state))
optionsAdapter.items =
if (state.submissionState is StepQuizFeature.SubmissionState.Loaded) {
val ordering = state.submissionState.submission.reply?.ordering ?: emptyList()
sortingOptions.sortedBy { ordering.indexOf(it.id) }
} else {
sortingOptions
}
}
override fun createReply(): ReplyResult =
ReplyResult(Reply(ordering = optionsAdapter.items.map(SortingOption::id)), ReplyResult.Validation.Success)
} | apache-2.0 | 43c5a22395fabd0c71ffb04d4f764147 | 41.105263 | 114 | 0.73648 | 5.184765 | false | false | false | false |
Jesterovskiy/FrameworkBenchmarks | frameworks/Kotlin/hexagon/src/main/kotlin/co/there4/hexagon/Benchmark.kt | 1 | 2821 | package co.there4.hexagon
import co.there4.hexagon.serialization.convertToMap
import co.there4.hexagon.serialization.serialize
import co.there4.hexagon.server.*
import co.there4.hexagon.server.engine.servlet.JettyServletEngine
import co.there4.hexagon.server.engine.servlet.ServletServer
import co.there4.hexagon.settings.SettingsManager.settings
import java.lang.System.getenv
import java.net.InetAddress.getByName as address
import java.util.concurrent.ThreadLocalRandom
import javax.servlet.annotation.WebListener
// DATA CLASSES
internal data class Message(val message: String)
internal data class Fortune(val _id: Int, val message: String)
internal data class World(val _id: Int, val id: Int, val randomNumber: Int)
// CONSTANTS
private const val TEXT_MESSAGE: String = "Hello, World!"
private const val CONTENT_TYPE_JSON = "application/json"
private const val QUERIES_PARAM = "queries"
internal var server: Server? = null
// UTILITIES
internal fun randomWorld() = ThreadLocalRandom.current().nextInt(WORLD_ROWS) + 1
private fun Call.returnWorlds(worldsList: List<World>) {
val worlds = worldsList.map { it.convertToMap() - "_id" }
val result = if (worlds.size == 1) worlds.first().serialize() else worlds.serialize()
ok(result, CONTENT_TYPE_JSON)
}
private fun Call.getWorldsCount() = (request[QUERIES_PARAM]?.toIntOrNull() ?: 1).let {
when {
it < 1 -> 1
it > 500 -> 500
else -> it
}
}
// HANDLERS
private fun Call.listFortunes(store: Store) {
val fortunes = store.findAllFortunes() + Fortune(0, "Additional fortune added at request time.")
response.contentType = "text/html; charset=utf-8"
template("fortunes.html", "fortunes" to fortunes.sortedBy { it.message })
}
private fun Call.getWorlds(store: Store) {
returnWorlds(store.findWorlds(getWorldsCount()))
}
private fun Call.updateWorlds(store: Store) {
returnWorlds(store.replaceWorlds(getWorldsCount()))
}
private fun router(store: Store): Router = router {
before {
response.addHeader("Server", "Servlet/3.1")
response.addHeader("Transfer-Encoding", "chunked")
response.addHeader("Date", httpDate())
}
get("/plaintext") { ok(TEXT_MESSAGE, "text/plain") }
get("/json") { ok(Message(TEXT_MESSAGE).serialize(), CONTENT_TYPE_JSON) }
get("/fortunes") { listFortunes(store) }
get("/db") { getWorlds(store) }
get("/query") { getWorlds(store) }
get("/update") { updateWorlds(store) }
}
@WebListener class Web : ServletServer () {
override fun createRouter() = router (createStore(getenv("DBSTORE") ?: "mongodb"))
}
fun main(vararg args: String) {
val store = createStore(if (args.isEmpty()) getenv("DBSTORE") ?: "mongodb" else args[0])
server = Server(JettyServletEngine(), settings, router(store))
server?.run()
}
| bsd-3-clause | c660477ca43c83ab658b40d844f247ed | 32.987952 | 100 | 0.711804 | 3.731481 | false | false | false | false |
da1z/intellij-community | uast/uast-common/src/org/jetbrains/uast/baseElements/UExpression.kt | 1 | 3032 | /*
* 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
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiType
import org.jetbrains.uast.internal.log
import org.jetbrains.uast.visitor.UastTypedVisitor
import org.jetbrains.uast.visitor.UastVisitor
/**
* Represents an expression or statement (which is considered as an expression in Uast).
*/
interface UExpression : UElement, UAnnotated {
/**
* Returns the expression value or null if the value can't be calculated.
*/
fun evaluate(): Any? = null
/**
* Returns expression type, or null if type can not be inferred, or if this expression is a statement.
*/
fun getExpressionType(): PsiType? = null
override fun accept(visitor: UastVisitor) {
visitor.visitElement(this)
visitor.afterVisitElement(this)
}
override fun <D, R> accept(visitor: UastTypedVisitor<D, R>, data: D) = visitor.visitExpression(this, data)
}
/**
* Represents an annotated element.
*/
interface UAnnotated : UElement {
/**
* Returns the list of annotations applied to the current element.
*/
val annotations: List<UAnnotation>
/**
* Looks up for annotation element using the annotation qualified name.
*
* @param fqName the qualified name to search
* @return the first annotation element with the specified qualified name, or null if there is no annotation with such name.
*/
fun findAnnotation(fqName: String): UAnnotation? = annotations.firstOrNull { it.qualifiedName == fqName }
}
/**
* Represents a labeled element.
*/
interface ULabeled : UElement {
/**
* Returns the label name, or null if the label is empty.
*/
val label: String?
/**
* Returns the label identifier, or null if the label is empty.
*/
val labelIdentifier: UIdentifier?
}
/**
* In some cases (user typing, syntax error) elements, which are supposed to exist, are missing.
* The obvious example - the lack of the condition expression in [UIfExpression], e.g. 'if () return'.
* [UIfExpression.condition] is required to return not-null values,
* and Uast implementation should return something instead of 'null' in this case.
*
* Use [UastEmptyExpression] in this case.
*/
object UastEmptyExpression : UExpression, JvmDeclarationUElement {
override val uastParent: UElement?
get() = null
override val annotations: List<UAnnotation>
get() = emptyList()
override val psi: PsiElement?
get() = null
override fun asLogString() = log()
} | apache-2.0 | a953517c7b71899993b0f990ded61b16 | 29.94898 | 126 | 0.722625 | 4.264416 | false | false | false | false |
exponentjs/exponent | android/expoview/src/main/java/versioned/host/exp/exponent/modules/universal/notifications/ScopedNotificationScheduler.kt | 2 | 5484 | package versioned.host.exp.exponent.modules.universal.notifications
import android.content.Context
import android.os.Bundle
import android.os.ResultReceiver
import expo.modules.core.Promise
import expo.modules.notifications.notifications.NotificationSerializer
import expo.modules.notifications.notifications.interfaces.NotificationTrigger
import expo.modules.notifications.notifications.model.NotificationContent
import expo.modules.notifications.notifications.model.NotificationRequest
import expo.modules.notifications.notifications.scheduling.NotificationScheduler
import expo.modules.notifications.service.NotificationsService
import host.exp.exponent.kernel.ExperienceKey
import host.exp.exponent.notifications.ScopedNotificationsUtils
import host.exp.exponent.notifications.model.ScopedNotificationRequest
import host.exp.exponent.utils.ScopedContext
import java.util.*
class ScopedNotificationScheduler(context: Context, private val experienceKey: ExperienceKey) :
NotificationScheduler(context) {
private val scopedNotificationsUtils: ScopedNotificationsUtils = ScopedNotificationsUtils(context)
override fun getSchedulingContext(): Context {
return if (context is ScopedContext) {
(context as ScopedContext).baseContext
} else context
}
override fun createNotificationRequest(
identifier: String,
content: NotificationContent,
notificationTrigger: NotificationTrigger?
): NotificationRequest {
return ScopedNotificationRequest(identifier, content, notificationTrigger, experienceKey.scopeKey)
}
override fun serializeScheduledNotificationRequests(requests: Collection<NotificationRequest>): Collection<Bundle> {
val serializedRequests: MutableCollection<Bundle> = ArrayList(requests.size)
for (request in requests) {
if (scopedNotificationsUtils.shouldHandleNotification(request, experienceKey)) {
serializedRequests.add(NotificationSerializer.toBundle(request))
}
}
return serializedRequests
}
override fun cancelScheduledNotificationAsync(identifier: String, promise: Promise) {
NotificationsService.getScheduledNotification(
schedulingContext,
identifier,
object : ResultReceiver(HANDLER) {
override fun onReceiveResult(resultCode: Int, resultData: Bundle?) {
super.onReceiveResult(resultCode, resultData)
if (resultCode == NotificationsService.SUCCESS_CODE) {
val request = resultData?.getParcelable<NotificationRequest>(NotificationsService.NOTIFICATION_REQUESTS_KEY)
if (request == null || !scopedNotificationsUtils.shouldHandleNotification(request, experienceKey)) {
promise.resolve(null)
}
doCancelScheduledNotificationAsync(identifier, promise)
} else {
val e = resultData!!.getSerializable(NotificationsService.EXCEPTION_KEY) as Exception
promise.reject(
"ERR_NOTIFICATIONS_FAILED_TO_FETCH",
"Failed to fetch scheduled notifications.",
e
)
}
}
}
)
}
override fun cancelAllScheduledNotificationsAsync(promise: Promise) {
NotificationsService.getAllScheduledNotifications(
schedulingContext,
object : ResultReceiver(HANDLER) {
override fun onReceiveResult(resultCode: Int, resultData: Bundle?) {
super.onReceiveResult(resultCode, resultData)
if (resultCode == NotificationsService.SUCCESS_CODE) {
val requests = resultData?.getParcelableArrayList<NotificationRequest>(
NotificationsService.NOTIFICATION_REQUESTS_KEY
)
if (requests == null) {
promise.resolve(null)
return
}
val toRemove = mutableListOf<String>()
for (request in requests) {
if (scopedNotificationsUtils.shouldHandleNotification(request, experienceKey)) {
toRemove.add(request.identifier)
}
}
if (toRemove.size == 0) {
promise.resolve(null)
return
}
cancelSelectedNotificationsAsync(toRemove.toTypedArray(), promise)
} else {
val e = resultData!!.getSerializable(NotificationsService.EXCEPTION_KEY) as Exception
promise.reject(
"ERR_NOTIFICATIONS_FAILED_TO_CANCEL",
"Failed to cancel all notifications.",
e
)
}
}
}
)
}
private fun doCancelScheduledNotificationAsync(identifier: String, promise: Promise) {
super.cancelScheduledNotificationAsync(identifier, promise)
}
private fun cancelSelectedNotificationsAsync(identifiers: Array<String>, promise: Promise) {
NotificationsService.removeScheduledNotifications(
schedulingContext,
identifiers.toList(),
object : ResultReceiver(HANDLER) {
override fun onReceiveResult(resultCode: Int, resultData: Bundle?) {
super.onReceiveResult(resultCode, resultData)
if (resultCode == NotificationsService.SUCCESS_CODE) {
promise.resolve(null)
} else {
val e = resultData!!.getSerializable(NotificationsService.EXCEPTION_KEY) as Exception
promise.reject(
"ERR_NOTIFICATIONS_FAILED_TO_CANCEL",
"Failed to cancel all notifications.",
e
)
}
}
}
)
}
}
| bsd-3-clause | bc5d1f152c25452334813f59247585c9 | 38.171429 | 120 | 0.695478 | 5.624615 | false | false | false | false |
Saketme/JRAW | lib/src/main/kotlin/net/dean/jraw/pagination/DefaultPaginator.kt | 2 | 3377 | package net.dean.jraw.pagination
import net.dean.jraw.RedditClient
import net.dean.jraw.http.HttpRequest
import net.dean.jraw.models.Sorting
import net.dean.jraw.models.TimePeriod
import net.dean.jraw.models.UniquelyIdentifiable
import net.dean.jraw.pagination.DefaultPaginator.Builder
/**
* This Paginator is for paginated API endpoints that support not only limits, but sortings and time periods
* (e.g. /top).
*/
open class DefaultPaginator<T : UniquelyIdentifiable> protected constructor(
reddit: RedditClient,
baseUrl: String,
/** See [Builder.sortingAlsoInPath] */
private val sortingAlsoInPath: Boolean,
/** See [Builder.timePeriod] */
val timePeriod: TimePeriod,
/** See [Builder.sorting] */
val sorting: Sorting,
limit: Int,
clazz: Class<T>
) : Paginator<T>(reddit, baseUrl, limit, clazz) {
override fun createNextRequest(): HttpRequest.Builder {
val sortingString = sorting.name.toLowerCase()
val args: MutableMap<String, String> = mutableMapOf(
"limit" to limit.toString(radix = 10),
"sort" to sortingString
)
if (sorting.requiresTimePeriod)
args.put("t", timePeriod.name.toLowerCase())
if (current?.nextName != null)
args.put("after", current!!.nextName!!)
val path = if (sortingAlsoInPath) "$baseUrl/$sortingString" else baseUrl
return reddit.requestStub()
.path(path)
.query(args)
}
/** Builder pattern for this class */
open class Builder<T : UniquelyIdentifiable, S : Sorting>(
reddit: RedditClient,
baseUrl: String,
/**
* If true, the sorting will be included as a query parameter instead of a path parameter. Most endpoints
* support (and require) specifying the sorting as a path parameter like this: `/r/pics/top?sort=top`. However,
* other endpoints 404 when given a path like this, in which case the sorting will need to be specified via
* query parameter only
*/
private var sortingAlsoInPath: Boolean = false,
clazz: Class<T>
) : Paginator.Builder<T>(reddit, baseUrl, clazz) {
private var limit: Int = Paginator.DEFAULT_LIMIT
private var timePeriod: TimePeriod = Paginator.DEFAULT_TIME_PERIOD
private var sorting: S? = null
/** Sets the limit */
fun limit(limit: Int): Builder<T, S> { this.limit = limit; return this }
/** Sets the sorting */
fun sorting(sorting: S): Builder<T, S> { this.sorting = sorting; return this }
/** Sets the time period */
fun timePeriod(timePeriod: TimePeriod): Builder<T, S> { this.timePeriod = timePeriod; return this }
override fun build(): DefaultPaginator<T> =
DefaultPaginator(reddit, baseUrl, sortingAlsoInPath, timePeriod, sorting ?: Paginator.DEFAULT_SORTING, limit, clazz)
/** */
companion object {
/** Convenience factory function using reified generics */
inline fun <reified T : UniquelyIdentifiable, S : Sorting> create(
reddit: RedditClient,
baseUrl: String,
sortingAlsoInPath: Boolean = false
): Builder<T, S> {
return Builder(reddit, baseUrl, sortingAlsoInPath, T::class.java)
}
}
}
}
| mit | 29b1c2f299a6e92ad715bfb813cf7ccd | 36.522222 | 128 | 0.639325 | 4.563514 | false | false | false | false |
ligi/PassAndroid | android/src/main/java/org/ligi/passandroid/model/pass/PassField.kt | 1 | 780 | package org.ligi.passandroid.model.pass
import android.content.res.Resources
import androidx.annotation.StringRes
import com.squareup.moshi.JsonClass
@JsonClass(generateAdapter = true)
class PassField(var key: String?, var label: String?, var value: String?, var hide: Boolean) {
fun toHtmlSnippet(): String {
val result = StringBuilder()
label?.let { result.append("<b>$label</b> ") }
value?.let { result.append(value) }
if (label != null || value != null) {
result.append("<br/>")
}
return "$result"
}
companion object {
fun create(@StringRes label: Int, @StringRes value: Int, res: Resources, hide: Boolean = false) = PassField(null, res.getString(label), res.getString(value), hide)
}
} | gpl-3.0 | 6412e5df9887687a9732d5016c2310fd | 30.24 | 171 | 0.647436 | 4.020619 | false | false | false | false |
pyamsoft/pydroid | util/src/main/java/com/pyamsoft/pydroid/util/internal/DefaultPermissionRequester.kt | 1 | 3271 | /*
* Copyright 2022 Peter Kenji Yamanaka
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.pyamsoft.pydroid.util.internal
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import androidx.annotation.CheckResult
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentActivity
import com.pyamsoft.pydroid.core.Logger
import com.pyamsoft.pydroid.util.PermissionRequester
internal class DefaultPermissionRequester
internal constructor(
private val permissions: Array<String>,
) : PermissionRequester {
@CheckResult
private fun createRequester(
launcher: ActivityResultLauncher<Array<String>>,
onResponse: (Boolean) -> Unit
): PermissionRequester.Requester {
return object : PermissionRequester.Requester {
private var theLauncher: ActivityResultLauncher<Array<String>>? = launcher
private var responseCallback: ((Boolean) -> Unit)? = onResponse
override fun requestPermissions() {
// If this is already unregistered, this does nothing
if (permissions.isEmpty()) {
Logger.d("No permissions requested, API level differences? Fallback => true")
responseCallback?.invoke(true)
} else {
theLauncher?.launch(permissions)
}
}
override fun unregister() {
theLauncher?.unregister()
// Clear memory to avoid leaks
theLauncher = null
responseCallback = null
}
}
}
private inline fun handlePermissionResults(
onResponse: (Boolean) -> Unit,
results: Map<String, Boolean>
) {
val ungrantedPermissions = results.filterNot { it.value }.map { it.key }
val allPermissionsGranted = ungrantedPermissions.isEmpty()
if (allPermissionsGranted) {
Logger.d("All permissions were granted $permissions")
} else {
Logger.w("Not all permissions were granted $ungrantedPermissions")
}
onResponse(allPermissionsGranted)
}
override fun registerRequester(
activity: FragmentActivity,
onResponse: (Boolean) -> Unit
): PermissionRequester.Requester {
val launcher =
activity.registerForActivityResult(ActivityResultContracts.RequestMultiplePermissions()) {
handlePermissionResults(onResponse, it)
}
return createRequester(launcher, onResponse)
}
override fun registerRequester(
fragment: Fragment,
onResponse: (Boolean) -> Unit
): PermissionRequester.Requester {
val launcher =
fragment.registerForActivityResult(ActivityResultContracts.RequestMultiplePermissions()) {
handlePermissionResults(onResponse, it)
}
return createRequester(launcher, onResponse)
}
}
| apache-2.0 | 652b9848424298e8658cc7e57d5f361c | 31.386139 | 98 | 0.717823 | 5.087092 | false | false | false | false |
wordpress-mobile/WordPress-Android | WordPress/src/test/java/org/wordpress/android/ui/posts/PublishSettingsViewModelTest.kt | 1 | 16226 | package org.wordpress.android.ui.posts
import org.assertj.core.api.Assertions.assertThat
import org.junit.Before
import org.junit.Test
import org.mockito.Mock
import org.mockito.kotlin.any
import org.mockito.kotlin.whenever
import org.wordpress.android.BaseUnitTest
import org.wordpress.android.R
import org.wordpress.android.fluxc.model.PostImmutableModel
import org.wordpress.android.fluxc.model.PostModel
import org.wordpress.android.fluxc.model.SiteModel
import org.wordpress.android.fluxc.model.post.PostStatus
import org.wordpress.android.fluxc.store.PostSchedulingNotificationStore
import org.wordpress.android.fluxc.store.PostSchedulingNotificationStore.SchedulingReminderModel
import org.wordpress.android.fluxc.store.PostSchedulingNotificationStore.SchedulingReminderModel.Period.OFF
import org.wordpress.android.fluxc.store.PostSchedulingNotificationStore.SchedulingReminderModel.Period.ONE_HOUR
import org.wordpress.android.fluxc.store.SiteStore
import org.wordpress.android.models.Person
import org.wordpress.android.ui.people.utils.PeopleUtils.FetchUsersCallback
import org.wordpress.android.ui.people.utils.PeopleUtilsWrapper
import org.wordpress.android.ui.posts.EditPostRepository.UpdatePostResult
import org.wordpress.android.ui.posts.PublishSettingsViewModel.CalendarEvent
import org.wordpress.android.ui.posts.PublishSettingsViewModel.PublishUiModel
import org.wordpress.android.util.DateTimeUtils
import org.wordpress.android.util.LocaleManagerWrapper
import org.wordpress.android.viewmodel.Event
import org.wordpress.android.viewmodel.ResourceProvider
import java.util.Calendar
import java.util.Locale
import java.util.TimeZone
class PublishSettingsViewModelTest : BaseUnitTest() {
@Mock lateinit var resourceProvider: ResourceProvider
@Mock lateinit var postSettingsUtils: PostSettingsUtils
@Mock lateinit var peopleUtilsWrapper: PeopleUtilsWrapper
@Mock lateinit var localeManagerWrapper: LocaleManagerWrapper
@Mock lateinit var postSchedulingNotificationStore: PostSchedulingNotificationStore
@Mock lateinit var siteStore: SiteStore
@Mock lateinit var editPostRepository: EditPostRepository
private lateinit var viewModel: EditPostPublishSettingsViewModel
private lateinit var post: PostModel
private val dateCreated = "2019-05-05T14:33:20+0000"
private val currentCalendar = Calendar.getInstance(Locale.US)
private val dateLabel = "Updated date"
@Before
fun setUp() {
viewModel = EditPostPublishSettingsViewModel(
resourceProvider,
postSettingsUtils,
peopleUtilsWrapper,
localeManagerWrapper,
postSchedulingNotificationStore,
siteStore
)
currentCalendar.set(2019, 6, 6, 10, 20)
whenever(localeManagerWrapper.getCurrentCalendar()).thenReturn(currentCalendar)
whenever(localeManagerWrapper.getTimeZone()).thenReturn(TimeZone.getTimeZone("GMT"))
whenever(postSettingsUtils.getPublishDateLabel(any())).thenReturn(dateLabel)
whenever(resourceProvider.getString(R.string.immediately)).thenReturn("Immediately")
whenever(postSchedulingNotificationStore.getSchedulingReminderPeriod(any())).thenReturn(OFF)
whenever(editPostRepository.dateCreated).thenReturn("")
post = PostModel()
whenever(editPostRepository.updateAsync(any(), any())).then {
val action: (PostModel) -> Boolean = it.getArgument(0)
val onCompleted: (PostImmutableModel, UpdatePostResult) -> Unit = it.getArgument(1)
action(post)
onCompleted(post, UpdatePostResult.Updated)
null
}
whenever(editPostRepository.getPost()).thenReturn(post)
}
@Test
fun `on start sets values and builds formatted label`() {
whenever(editPostRepository.dateCreated).thenReturn(dateCreated)
val expectedLabel = "Scheduled for 2019"
whenever(postSettingsUtils.getPublishDateLabel(post)).thenReturn(expectedLabel)
var uiModel: PublishUiModel? = null
viewModel.onUiModel.observeForever {
uiModel = it
}
viewModel.start(editPostRepository)
assertThat(viewModel.year).isEqualTo(2019)
assertThat(viewModel.month).isEqualTo(4)
assertThat(viewModel.day).isEqualTo(5)
assertThat(viewModel.hour).isEqualTo(14)
assertThat(viewModel.minute).isEqualTo(33)
assertThat(uiModel!!.publishDateLabel).isEqualTo(expectedLabel)
}
@Test
fun `on start sets current date when post not present`() {
var uiModel: PublishUiModel? = null
viewModel.onUiModel.observeForever {
uiModel = it
}
viewModel.start(null)
assertThat(viewModel.year).isEqualTo(2019)
assertThat(viewModel.month).isEqualTo(6)
assertThat(viewModel.day).isEqualTo(6)
assertThat(viewModel.hour).isEqualTo(10)
assertThat(viewModel.minute).isEqualTo(20)
assertThat(uiModel!!.publishDateLabel).isEqualTo("Immediately")
}
@Test
fun `on start sets authors`() {
val localSiteId = 2
whenever(editPostRepository.localSiteId).thenReturn(localSiteId)
val site = SiteModel()
val siteTitle = "Site title"
site.name = siteTitle
site.hasCapabilityListUsers = true
whenever(siteStore.getSiteByLocalId(localSiteId)).thenReturn(site)
val peopleList = listOf(Person(1, 1), Person(2, 1))
whenever(peopleUtilsWrapper.fetchAuthors(any(), any(), any()))
.then { it.getArgument<FetchUsersCallback>(2).onSuccess(peopleList, true) }
var authors = listOf<Person>()
viewModel.authors.observeForever { authors = it }
viewModel.start(editPostRepository)
assertThat(authors).isEqualTo(peopleList)
}
@Test
fun `on publishNow updates published date`() {
var publishedDate: Event<Calendar>? = null
viewModel.onPublishedDateChanged.observeForever {
publishedDate = it
}
viewModel.publishNow()
assertThat(publishedDate?.peekContent()).isEqualTo(currentCalendar)
}
@Test
fun `onDateSelected updates date and triggers onDatePicked`() {
var datePicked: Unit? = null
viewModel.onDatePicked.observeForever {
datePicked = it?.getContentIfNotHandled()
}
val updatedYear = 2018
val updatedMonth = 1
val updatedDay = 5
viewModel.onDateSelected(updatedYear, updatedMonth, updatedDay)
assertThat(viewModel.year).isEqualTo(updatedYear)
assertThat(viewModel.month).isEqualTo(updatedMonth)
assertThat(viewModel.day).isEqualTo(updatedDay)
assertThat(datePicked).isNotNull
}
@Test
fun `onTimeSelected updates time and triggers onPublishedDateChanged`() {
viewModel.start(null)
var publishedDate: Event<Calendar>? = null
viewModel.onPublishedDateChanged.observeForever {
publishedDate = it
}
val updatedHour = 15
val updatedMinute = 15
viewModel.onTimeSelected(updatedHour, updatedMinute)
assertThat(viewModel.hour).isEqualTo(updatedHour)
assertThat(viewModel.minute).isEqualTo(updatedMinute)
assertThat(publishedDate?.peekContent()).isNotNull()
}
@Test
fun `updatePost updates post status from DRAFT to PUBLISHED to published when date in the future`() {
whenever(editPostRepository.status).thenReturn(PostStatus.DRAFT)
val futureDate = Calendar.getInstance()
futureDate.add(Calendar.MINUTE, 15)
val updatedDate = DateTimeUtils.iso8601FromDate(futureDate.time)
var updatedStatus: PostStatus? = null
viewModel.onPostStatusChanged.observeForever {
updatedStatus = it
}
var uiModel: PublishUiModel? = null
viewModel.onUiModel.observeForever {
uiModel = it
}
viewModel.updatePost(futureDate, editPostRepository)
assertThat(post.status).isEqualTo(PostStatus.SCHEDULED.toString())
assertThat(post.dateCreated).isEqualTo(updatedDate)
assertThat(updatedStatus).isEqualTo(PostStatus.SCHEDULED)
uiModel?.apply {
assertThat(this.publishDateLabel).isEqualTo("Updated date")
assertThat(this.notificationLabel).isEqualTo(R.string.post_notification_off)
assertThat(this.notificationEnabled).isTrue()
assertThat(this.notificationVisible).isTrue()
}
}
@Test
fun `updatePost updates post status from PUBLISHED to DRAFT for local draft`() {
whenever(editPostRepository.status).thenReturn(PostStatus.PUBLISHED)
whenever(editPostRepository.isLocalDraft).thenReturn(true)
var updatedStatus: PostStatus? = null
viewModel.onPostStatusChanged.observeForever {
updatedStatus = it
}
var uiModel: PublishUiModel? = null
viewModel.onUiModel.observeForever {
uiModel = it
}
viewModel.updatePost(currentCalendar, editPostRepository)
assertThat(post.status).isEqualTo(PostStatus.DRAFT.toString())
assertThat(post.dateCreated).isNotNull()
assertThat(updatedStatus).isEqualTo(PostStatus.DRAFT)
uiModel?.apply {
assertThat(this.publishDateLabel).isEqualTo("Updated date")
assertThat(this.notificationLabel).isEqualTo(R.string.post_notification_off)
assertThat(this.notificationEnabled).isFalse()
assertThat(this.notificationVisible).isTrue()
}
}
@Test
fun `updatePost updates post status from SCHEDULED to DRAFT when published date in past`() {
val expectedToastMessage = "Message"
whenever(resourceProvider.getString(R.string.editor_post_converted_back_to_draft)).thenReturn(
expectedToastMessage
)
whenever(editPostRepository.status).thenReturn(PostStatus.SCHEDULED)
val pastDate = Calendar.getInstance()
pastDate.add(Calendar.MINUTE, -100)
var updatedStatus: PostStatus? = null
viewModel.onPostStatusChanged.observeForever {
updatedStatus = it
}
var uiModel: PublishUiModel? = null
viewModel.onUiModel.observeForever {
uiModel = it
}
var toastMessage: String? = null
viewModel.onToast.observeForever {
toastMessage = it?.getContentIfNotHandled()
}
viewModel.updatePost(currentCalendar, editPostRepository)
assertThat(post.status).isEqualTo(PostStatus.DRAFT.toString())
assertThat(post.dateCreated).isNotNull()
assertThat(updatedStatus).isEqualTo(PostStatus.DRAFT)
uiModel?.apply {
assertThat(this.publishDateLabel).isEqualTo("Updated date")
assertThat(this.notificationLabel).isEqualTo(R.string.post_notification_off)
assertThat(this.notificationEnabled).isFalse()
assertThat(this.notificationVisible).isTrue()
}
assertThat(toastMessage).isEqualTo(expectedToastMessage)
}
@Test
fun `hides notification when publish date in the past`() {
val postId = 1
post.setId(postId)
post.setDateCreated("2019-05-05T14:33:20+0000")
val pastDate = Calendar.getInstance()
pastDate.set(2019, 6, 6, 10, 10, 10)
whenever(localeManagerWrapper.getCurrentCalendar()).thenReturn(pastDate)
var uiModel: PublishUiModel? = null
viewModel.onUiModel.observeForever {
uiModel = it
}
whenever(postSchedulingNotificationStore.getSchedulingReminderPeriod(postId)).thenReturn(ONE_HOUR)
viewModel.updateUiModel(post)
uiModel?.apply {
assertThat(this.publishDateLabel).isEqualTo("Updated date")
assertThat(this.notificationLabel).isEqualTo(R.string.post_notification_off)
assertThat(this.notificationEnabled).isFalse()
assertThat(this.notificationVisible).isFalse()
}
}
@Test
fun `DISABLES notification when publish date in NOW`() {
val postId = 1
post.setId(postId)
post.setDateCreated("2019-05-05T14:33:20+0000")
val pastDate = Calendar.getInstance(Locale.US)
pastDate.timeZone = TimeZone.getTimeZone("GMT")
pastDate.set(2019, 4, 5, 14, 33, 20)
whenever(localeManagerWrapper.getCurrentCalendar()).thenReturn(pastDate)
var uiModel: PublishUiModel? = null
viewModel.onUiModel.observeForever {
uiModel = it
}
whenever(postSchedulingNotificationStore.getSchedulingReminderPeriod(postId)).thenReturn(ONE_HOUR)
viewModel.updateUiModel(post)
uiModel?.apply {
assertThat(this.publishDateLabel).isEqualTo("Updated date")
assertThat(this.notificationEnabled).isFalse()
assertThat(this.notificationVisible).isTrue()
assertThat(this.notificationLabel).isEqualTo(R.string.post_notification_off)
}
}
@Test
fun `DISABLES notification when publish date in missing`() {
val postId = 1
post.setId(postId)
post.setDateCreated("2019-05-05T14:33:20+0000")
val pastDate = Calendar.getInstance(Locale.US)
pastDate.timeZone = TimeZone.getTimeZone("GMT")
pastDate.set(2019, 4, 5, 14, 33, 20)
whenever(localeManagerWrapper.getCurrentCalendar()).thenReturn(pastDate)
var uiModel: PublishUiModel? = null
viewModel.onUiModel.observeForever {
uiModel = it
}
whenever(postSchedulingNotificationStore.getSchedulingReminderPeriod(postId)).thenReturn(ONE_HOUR)
viewModel.updateUiModel(post)
uiModel?.apply {
assertThat(this.publishDateLabel).isEqualTo("Updated date")
assertThat(this.notificationEnabled).isFalse()
assertThat(this.notificationVisible).isTrue()
assertThat(this.notificationLabel).isEqualTo(R.string.post_notification_off)
}
}
@Test
fun `onAddToCalendar adds a calendar event`() {
val postTitle = "Post title"
val localSiteId = 2
val postLink = "link.com"
whenever(editPostRepository.dateCreated).thenReturn("2019-05-05T14:33:20+0000")
whenever(editPostRepository.title).thenReturn(postTitle)
whenever(editPostRepository.localSiteId).thenReturn(localSiteId)
whenever(editPostRepository.link).thenReturn(postLink)
val site = SiteModel()
val siteTitle = "Site title"
site.name = siteTitle
whenever(siteStore.getSiteByLocalId(localSiteId)).thenReturn(site)
var calendarEvent: CalendarEvent? = null
viewModel.onAddToCalendar.observeForever {
calendarEvent = it?.getContentIfNotHandled()
}
val appName = "App name"
whenever(resourceProvider.getString(R.string.app_name)).thenReturn(appName)
val eventTitle = "Event title"
val eventDescription = "Event description"
whenever(resourceProvider.getString(
R.string.calendar_scheduled_post_title,
postTitle
)).thenReturn(eventTitle)
whenever(resourceProvider.getString(
R.string.calendar_scheduled_post_description,
postTitle,
siteTitle,
appName,
postLink
)).thenReturn(eventDescription)
viewModel.onAddToCalendar(editPostRepository)
assertThat(calendarEvent!!.startTime).isEqualTo(1557066800000L)
assertThat(calendarEvent!!.title).isEqualTo(eventTitle)
assertThat(calendarEvent!!.description).isEqualTo(eventDescription)
}
@Test
fun `onNotificationCreated updates notification`() {
var schedulingReminderPeriod: SchedulingReminderModel.Period? = null
viewModel.onNotificationTime.observeForever {
schedulingReminderPeriod = it
}
viewModel.onNotificationCreated(ONE_HOUR)
assertThat(schedulingReminderPeriod).isEqualTo(ONE_HOUR)
}
}
| gpl-2.0 | fe8121de0ce712ba420d80bcce15be6b | 37.089202 | 112 | 0.691791 | 5.184026 | false | true | false | false |
ingokegel/intellij-community | platform/workspaceModel/storage/gen/com/intellij/workspaceModel/storage/bridgeEntities/api/ContentRootEntityImpl.kt | 1 | 18776 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.workspaceModel.storage.bridgeEntities.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.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.extractOneToManyParent
import com.intellij.workspaceModel.storage.impl.extractOneToOneChild
import com.intellij.workspaceModel.storage.impl.updateOneToManyChildrenOfParent
import com.intellij.workspaceModel.storage.impl.updateOneToManyParentOfChild
import com.intellij.workspaceModel.storage.impl.updateOneToOneChildOfParent
import com.intellij.workspaceModel.storage.url.VirtualFileUrl
import org.jetbrains.deft.ObjBuilder
import org.jetbrains.deft.Type
import org.jetbrains.deft.annotations.Child
@GeneratedCodeApiVersion(1)
@GeneratedCodeImplVersion(1)
open class ContentRootEntityImpl : ContentRootEntity, WorkspaceEntityBase() {
companion object {
internal val MODULE_CONNECTION_ID: ConnectionId = ConnectionId.create(ModuleEntity::class.java, ContentRootEntity::class.java,
ConnectionId.ConnectionType.ONE_TO_MANY, false)
internal val SOURCEROOTS_CONNECTION_ID: ConnectionId = ConnectionId.create(ContentRootEntity::class.java, SourceRootEntity::class.java,
ConnectionId.ConnectionType.ONE_TO_MANY, false)
internal val SOURCEROOTORDER_CONNECTION_ID: ConnectionId = ConnectionId.create(ContentRootEntity::class.java,
SourceRootOrderEntity::class.java,
ConnectionId.ConnectionType.ONE_TO_ONE, false)
val connections = listOf<ConnectionId>(
MODULE_CONNECTION_ID,
SOURCEROOTS_CONNECTION_ID,
SOURCEROOTORDER_CONNECTION_ID,
)
}
override val module: ModuleEntity
get() = snapshot.extractOneToManyParent(MODULE_CONNECTION_ID, this)!!
@JvmField
var _url: VirtualFileUrl? = null
override val url: VirtualFileUrl
get() = _url!!
@JvmField
var _excludedUrls: List<VirtualFileUrl>? = null
override val excludedUrls: List<VirtualFileUrl>
get() = _excludedUrls!!
@JvmField
var _excludedPatterns: List<String>? = null
override val excludedPatterns: List<String>
get() = _excludedPatterns!!
override val sourceRoots: List<SourceRootEntity>
get() = snapshot.extractOneToManyChildren<SourceRootEntity>(SOURCEROOTS_CONNECTION_ID, this)!!.toList()
override val sourceRootOrder: SourceRootOrderEntity?
get() = snapshot.extractOneToOneChild(SOURCEROOTORDER_CONNECTION_ID, this)
override fun connectionIdList(): List<ConnectionId> {
return connections
}
class Builder(val result: ContentRootEntityData?) : ModifiableWorkspaceEntityBase<ContentRootEntity>(), ContentRootEntity.Builder {
constructor() : this(ContentRootEntityData())
override fun applyToBuilder(builder: MutableEntityStorage) {
if (this.diff != null) {
if (existsInBuilder(builder)) {
this.diff = builder
return
}
else {
error("Entity ContentRootEntity is already created in a different builder")
}
}
this.diff = builder
this.snapshot = builder
addToBuilder()
this.id = getEntityData().createEntityId()
index(this, "url", this.url)
index(this, "excludedUrls", this.excludedUrls.toHashSet())
// 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 (_diff != null) {
if (_diff.extractOneToManyParent<WorkspaceEntityBase>(MODULE_CONNECTION_ID, this) == null) {
error("Field ContentRootEntity#module should be initialized")
}
}
else {
if (this.entityLinks[EntityLink(false, MODULE_CONNECTION_ID)] == null) {
error("Field ContentRootEntity#module should be initialized")
}
}
if (!getEntityData().isUrlInitialized()) {
error("Field ContentRootEntity#url should be initialized")
}
if (!getEntityData().isExcludedUrlsInitialized()) {
error("Field ContentRootEntity#excludedUrls should be initialized")
}
if (!getEntityData().isExcludedPatternsInitialized()) {
error("Field ContentRootEntity#excludedPatterns should be initialized")
}
// Check initialization for list with ref type
if (_diff != null) {
if (_diff.extractOneToManyChildren<WorkspaceEntityBase>(SOURCEROOTS_CONNECTION_ID, this) == null) {
error("Field ContentRootEntity#sourceRoots should be initialized")
}
}
else {
if (this.entityLinks[EntityLink(true, SOURCEROOTS_CONNECTION_ID)] == null) {
error("Field ContentRootEntity#sourceRoots 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 ContentRootEntity
this.entitySource = dataSource.entitySource
this.url = dataSource.url
this.excludedUrls = dataSource.excludedUrls.toMutableList()
this.excludedPatterns = dataSource.excludedPatterns.toMutableList()
if (parents != null) {
this.module = parents.filterIsInstance<ModuleEntity>().single()
}
}
override var entitySource: EntitySource
get() = getEntityData().entitySource
set(value) {
checkModificationAllowed()
getEntityData().entitySource = value
changedProperty.add("entitySource")
}
override var module: ModuleEntity
get() {
val _diff = diff
return if (_diff != null) {
_diff.extractOneToManyParent(MODULE_CONNECTION_ID, this) ?: this.entityLinks[EntityLink(false,
MODULE_CONNECTION_ID)]!! as ModuleEntity
}
else {
this.entityLinks[EntityLink(false, MODULE_CONNECTION_ID)]!! as ModuleEntity
}
}
set(value) {
checkModificationAllowed()
val _diff = diff
if (_diff != null && value is ModifiableWorkspaceEntityBase<*> && value.diff == null) {
// Setting backref of the list
if (value is ModifiableWorkspaceEntityBase<*>) {
val data = (value.entityLinks[EntityLink(true, MODULE_CONNECTION_ID)] as? List<Any> ?: emptyList()) + this
value.entityLinks[EntityLink(true, MODULE_CONNECTION_ID)] = data
}
// else you're attaching a new entity to an existing entity that is not modifiable
_diff.addEntity(value)
}
if (_diff != null && (value !is ModifiableWorkspaceEntityBase<*> || value.diff != null)) {
_diff.updateOneToManyParentOfChild(MODULE_CONNECTION_ID, this, value)
}
else {
// Setting backref of the list
if (value is ModifiableWorkspaceEntityBase<*>) {
val data = (value.entityLinks[EntityLink(true, MODULE_CONNECTION_ID)] as? List<Any> ?: emptyList()) + this
value.entityLinks[EntityLink(true, MODULE_CONNECTION_ID)] = data
}
// else you're attaching a new entity to an existing entity that is not modifiable
this.entityLinks[EntityLink(false, MODULE_CONNECTION_ID)] = value
}
changedProperty.add("module")
}
override var url: VirtualFileUrl
get() = getEntityData().url
set(value) {
checkModificationAllowed()
getEntityData().url = value
changedProperty.add("url")
val _diff = diff
if (_diff != null) index(this, "url", value)
}
private val excludedUrlsUpdater: (value: List<VirtualFileUrl>) -> Unit = { value ->
val _diff = diff
if (_diff != null) index(this, "excludedUrls", value.toHashSet())
changedProperty.add("excludedUrls")
}
override var excludedUrls: MutableList<VirtualFileUrl>
get() {
val collection_excludedUrls = getEntityData().excludedUrls
if (collection_excludedUrls !is MutableWorkspaceList) return collection_excludedUrls
collection_excludedUrls.setModificationUpdateAction(excludedUrlsUpdater)
return collection_excludedUrls
}
set(value) {
checkModificationAllowed()
getEntityData().excludedUrls = value
excludedUrlsUpdater.invoke(value)
}
private val excludedPatternsUpdater: (value: List<String>) -> Unit = { value ->
changedProperty.add("excludedPatterns")
}
override var excludedPatterns: MutableList<String>
get() {
val collection_excludedPatterns = getEntityData().excludedPatterns
if (collection_excludedPatterns !is MutableWorkspaceList) return collection_excludedPatterns
collection_excludedPatterns.setModificationUpdateAction(excludedPatternsUpdater)
return collection_excludedPatterns
}
set(value) {
checkModificationAllowed()
getEntityData().excludedPatterns = value
excludedPatternsUpdater.invoke(value)
}
// List of non-abstract referenced types
var _sourceRoots: List<SourceRootEntity>? = emptyList()
override var sourceRoots: List<SourceRootEntity>
get() {
// Getter of the list of non-abstract referenced types
val _diff = diff
return if (_diff != null) {
_diff.extractOneToManyChildren<SourceRootEntity>(SOURCEROOTS_CONNECTION_ID, this)!!.toList() + (this.entityLinks[EntityLink(true,
SOURCEROOTS_CONNECTION_ID)] as? List<SourceRootEntity>
?: emptyList())
}
else {
this.entityLinks[EntityLink(true, SOURCEROOTS_CONNECTION_ID)] as? List<SourceRootEntity> ?: 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(SOURCEROOTS_CONNECTION_ID, this, value)
}
else {
for (item_value in value) {
if (item_value is ModifiableWorkspaceEntityBase<*>) {
item_value.entityLinks[EntityLink(false, SOURCEROOTS_CONNECTION_ID)] = this
}
// else you're attaching a new entity to an existing entity that is not modifiable
}
this.entityLinks[EntityLink(true, SOURCEROOTS_CONNECTION_ID)] = value
}
changedProperty.add("sourceRoots")
}
override var sourceRootOrder: SourceRootOrderEntity?
get() {
val _diff = diff
return if (_diff != null) {
_diff.extractOneToOneChild(SOURCEROOTORDER_CONNECTION_ID, this) ?: this.entityLinks[EntityLink(true,
SOURCEROOTORDER_CONNECTION_ID)] as? SourceRootOrderEntity
}
else {
this.entityLinks[EntityLink(true, SOURCEROOTORDER_CONNECTION_ID)] as? SourceRootOrderEntity
}
}
set(value) {
checkModificationAllowed()
val _diff = diff
if (_diff != null && value is ModifiableWorkspaceEntityBase<*> && value.diff == null) {
if (value is ModifiableWorkspaceEntityBase<*>) {
value.entityLinks[EntityLink(false, SOURCEROOTORDER_CONNECTION_ID)] = this
}
// else you're attaching a new entity to an existing entity that is not modifiable
_diff.addEntity(value)
}
if (_diff != null && (value !is ModifiableWorkspaceEntityBase<*> || value.diff != null)) {
_diff.updateOneToOneChildOfParent(SOURCEROOTORDER_CONNECTION_ID, this, value)
}
else {
if (value is ModifiableWorkspaceEntityBase<*>) {
value.entityLinks[EntityLink(false, SOURCEROOTORDER_CONNECTION_ID)] = this
}
// else you're attaching a new entity to an existing entity that is not modifiable
this.entityLinks[EntityLink(true, SOURCEROOTORDER_CONNECTION_ID)] = value
}
changedProperty.add("sourceRootOrder")
}
override fun getEntityData(): ContentRootEntityData = result ?: super.getEntityData() as ContentRootEntityData
override fun getEntityClass(): Class<ContentRootEntity> = ContentRootEntity::class.java
}
}
class ContentRootEntityData : WorkspaceEntityData<ContentRootEntity>() {
lateinit var url: VirtualFileUrl
lateinit var excludedUrls: MutableList<VirtualFileUrl>
lateinit var excludedPatterns: MutableList<String>
fun isUrlInitialized(): Boolean = ::url.isInitialized
fun isExcludedUrlsInitialized(): Boolean = ::excludedUrls.isInitialized
fun isExcludedPatternsInitialized(): Boolean = ::excludedPatterns.isInitialized
override fun wrapAsModifiable(diff: MutableEntityStorage): ModifiableWorkspaceEntity<ContentRootEntity> {
val modifiable = ContentRootEntityImpl.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): ContentRootEntity {
val entity = ContentRootEntityImpl()
entity._url = url
entity._excludedUrls = excludedUrls.toList()
entity._excludedPatterns = excludedPatterns.toList()
entity.entitySource = entitySource
entity.snapshot = snapshot
entity.id = createEntityId()
return entity
}
override fun clone(): ContentRootEntityData {
val clonedEntity = super.clone()
clonedEntity as ContentRootEntityData
clonedEntity.excludedUrls = clonedEntity.excludedUrls.toMutableWorkspaceList()
clonedEntity.excludedPatterns = clonedEntity.excludedPatterns.toMutableWorkspaceList()
return clonedEntity
}
override fun getEntityInterface(): Class<out WorkspaceEntity> {
return ContentRootEntity::class.java
}
override fun serialize(ser: EntityInformation.Serializer) {
}
override fun deserialize(de: EntityInformation.Deserializer) {
}
override fun createDetachedEntity(parents: List<WorkspaceEntity>): WorkspaceEntity {
return ContentRootEntity(url, excludedUrls, excludedPatterns, entitySource) {
this.module = parents.filterIsInstance<ModuleEntity>().single()
}
}
override fun getRequiredParents(): List<Class<out WorkspaceEntity>> {
val res = mutableListOf<Class<out WorkspaceEntity>>()
res.add(ModuleEntity::class.java)
return res
}
override fun equals(other: Any?): Boolean {
if (other == null) return false
if (this::class != other::class) return false
other as ContentRootEntityData
if (this.entitySource != other.entitySource) return false
if (this.url != other.url) return false
if (this.excludedUrls != other.excludedUrls) return false
if (this.excludedPatterns != other.excludedPatterns) return false
return true
}
override fun equalsIgnoringEntitySource(other: Any?): Boolean {
if (other == null) return false
if (this::class != other::class) return false
other as ContentRootEntityData
if (this.url != other.url) return false
if (this.excludedUrls != other.excludedUrls) return false
if (this.excludedPatterns != other.excludedPatterns) return false
return true
}
override fun hashCode(): Int {
var result = entitySource.hashCode()
result = 31 * result + url.hashCode()
result = 31 * result + excludedUrls.hashCode()
result = 31 * result + excludedPatterns.hashCode()
return result
}
override fun hashCodeIgnoringEntitySource(): Int {
var result = javaClass.hashCode()
result = 31 * result + url.hashCode()
result = 31 * result + excludedUrls.hashCode()
result = 31 * result + excludedPatterns.hashCode()
return result
}
override fun equalsByKey(other: Any?): Boolean {
if (other == null) return false
if (this::class != other::class) return false
other as ContentRootEntityData
if (this.url != other.url) return false
return true
}
override fun hashCodeByKey(): Int {
var result = javaClass.hashCode()
result = 31 * result + url.hashCode()
return result
}
override fun collectClassUsagesData(collector: UsedClassesCollector) {
this.excludedUrls?.let { collector.add(it::class.java) }
this.url?.let { collector.add(it::class.java) }
this.excludedPatterns?.let { collector.add(it::class.java) }
collector.sameForAllEntities = false
}
}
| apache-2.0 | ce0d22017189a3182895619036b3b0a4 | 39.906318 | 188 | 0.673253 | 5.440742 | false | false | false | false |
Turbo87/intellij-emberjs | src/main/kotlin/com/emberjs/EmberXmlElementDescriptor.kt | 1 | 3409 | package com.emberjs
import com.emberjs.index.EmberNameIndex
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiManager
import com.intellij.psi.impl.source.html.dtd.HtmlNSDescriptorImpl
import com.intellij.psi.impl.source.xml.XmlDescriptorUtil
import com.intellij.psi.search.ProjectScope
import com.intellij.psi.xml.XmlAttribute
import com.intellij.psi.xml.XmlTag
import com.intellij.xml.XmlAttributeDescriptor
import com.intellij.xml.XmlElementDescriptor
import com.intellij.xml.XmlElementsGroup
import com.intellij.xml.XmlNSDescriptor
import com.intellij.xml.impl.schema.AnyXmlAttributeDescriptor
class EmberXmlElementDescriptor(private val tag: XmlTag, private val declaration: PsiElement) : XmlElementDescriptor {
val project = tag.project
companion object {
fun forTag(tag: XmlTag?): EmberXmlElementDescriptor? {
if (tag == null) return null
val project = tag.project
val scope = ProjectScope.getAllScope(project)
val psiManager: PsiManager by lazy { PsiManager.getInstance(project) }
val componentTemplate =
EmberNameIndex.getFilteredFiles(scope) { it.isComponentTemplate && it.angleBracketsName == tag.name }
.mapNotNull { psiManager.findFile(it) }
.firstOrNull()
if (componentTemplate != null) return EmberXmlElementDescriptor(tag, componentTemplate)
val component =
EmberNameIndex.getFilteredFiles(scope) { it.type == "component" && it.angleBracketsName == tag.name }
.mapNotNull { psiManager.findFile(it) }
.firstOrNull()
if (component != null) return EmberXmlElementDescriptor(tag, component)
return null
}
}
override fun getDeclaration(): PsiElement = declaration
override fun getName(context: PsiElement?): String = (context as? XmlTag)?.name ?: name
override fun getName(): String = tag.localName
override fun init(element: PsiElement?) {}
override fun getQualifiedName(): String = name
override fun getDefaultName(): String = name
override fun getElementsDescriptors(context: XmlTag): Array<XmlElementDescriptor> {
return XmlDescriptorUtil.getElementsDescriptors(context)
}
override fun getElementDescriptor(childTag: XmlTag, contextTag: XmlTag): XmlElementDescriptor? {
return XmlDescriptorUtil.getElementDescriptor(childTag, contextTag)
}
override fun getAttributesDescriptors(context: XmlTag?): Array<out XmlAttributeDescriptor> {
val result = mutableListOf<XmlAttributeDescriptor>()
val commonHtmlAttributes = HtmlNSDescriptorImpl.getCommonAttributeDescriptors(context)
result.addAll(commonHtmlAttributes)
return result.toTypedArray()
}
override fun getAttributeDescriptor(attributeName: String?, context: XmlTag?): XmlAttributeDescriptor? {
return AnyXmlAttributeDescriptor(attributeName)
}
override fun getAttributeDescriptor(attribute: XmlAttribute?): XmlAttributeDescriptor?
= getAttributeDescriptor(attribute?.name, attribute?.parent)
override fun getNSDescriptor(): XmlNSDescriptor? = null
override fun getTopGroup(): XmlElementsGroup? = null
override fun getContentType(): Int = XmlElementDescriptor.CONTENT_TYPE_ANY
override fun getDefaultValue(): String? = null
}
| apache-2.0 | 03f0b5ae1f130327de62182892876752 | 42.705128 | 118 | 0.724259 | 5.118619 | false | false | false | false |
iPoli/iPoli-android | app/src/main/java/io/ipoli/android/habit/widget/HabitWidgetViewFactory.kt | 1 | 6716 | package io.ipoli.android.habit.widget
import android.content.Context
import android.content.Intent
import android.graphics.drawable.GradientDrawable
import android.os.Bundle
import android.support.v4.content.ContextCompat
import android.view.LayoutInflater
import android.view.View
import android.widget.ImageView
import android.widget.RemoteViews
import android.widget.RemoteViewsService
import com.mikepenz.iconics.IconicsDrawable
import io.ipoli.android.Constants
import io.ipoli.android.MyPoliApp
import io.ipoli.android.R
import io.ipoli.android.common.di.BackgroundModule
import io.ipoli.android.common.view.*
import io.ipoli.android.common.view.widget.CircleProgressBar
import io.ipoli.android.habit.data.Habit
import org.threeten.bp.LocalDate
import space.traversal.kapsule.Injects
import space.traversal.kapsule.inject
import space.traversal.kapsule.required
import java.util.concurrent.CopyOnWriteArrayList
/**
* Created by Polina Zhelyazkova <[email protected]>
* on 7/27/18.
*/
class HabitWidgetViewsFactory(private val context: Context) :
RemoteViewsService.RemoteViewsFactory, Injects<BackgroundModule> {
private val habitRepository by required { habitRepository }
private var items = CopyOnWriteArrayList<Habit>()
override fun onCreate() {
inject(MyPoliApp.backgroundModule(context))
}
override fun getLoadingView() =
RemoteViews(context.packageName, R.layout.item_widget_habit_loading)
override fun getItemId(position: Int): Long = position.toLong()
override fun onDataSetChanged() {
items.clear()
val today = LocalDate.now()
items.addAll(habitRepository.findAllNotRemoved()
.filter { it.shouldBeDoneOn(today) }
.sortedWith(
compareBy<Habit> { it.isCompletedForDate(today) }
.thenByDescending { it.timesADay }
.thenByDescending { it.isGood }
))
}
override fun hasStableIds() = true
override fun getViewAt(position: Int): RemoteViews {
val today = LocalDate.now()
return items[position].let {
RemoteViews(context.packageName, R.layout.item_widget_habit).apply {
val progress = it.completedCountForDate(today)
val maxProgress = it.timesADay
val isCompletedFor = it.isCompletedForDate(today)
val isCompleted = if (it.isGood) isCompletedFor else !isCompletedFor
val px = context.resources.getDimensionPixelSize(R.dimen.habit_widget_item_size)
val icon = it.icon.let { i -> AndroidIcon.valueOf(i.name).icon }
val iconColor =
if (isCompleted) R.color.md_white else AndroidColor.valueOf(it.color.name).color500
val iconDrawable =
IconicsDrawable(context).normalIcon(icon, iconColor)
val habitColor = ContextCompat.getColor(
context,
AndroidColor.valueOf(it.color.name).color500
)
val whiteColor = ContextCompat.getColor(
context,
R.color.md_white
)
val myView =
LayoutInflater.from(context).inflate(R.layout.item_widget_habit_progress, null)
myView.measure(px, px)
myView.layout(0, 0, px, px)
val habitProgress = myView.findViewById<CircleProgressBar>(R.id.habitProgress)
val habitTimesADayProgress =
myView.findViewById<CircleProgressBar>(R.id.habitTimesADayProgress)
habitProgress.setProgressStartColor(habitColor)
habitProgress.setProgressEndColor(habitColor)
habitProgress.setProgressBackgroundColor(
ContextCompat.getColor(
context,
AndroidColor.valueOf(it.color.name).color100
)
)
habitProgress.setProgressFormatter(null)
habitProgress.max = maxProgress
habitProgress.progress = progress
if (it.timesADay > 1) {
habitTimesADayProgress.visible()
habitTimesADayProgress.setProgressStartColor(whiteColor)
habitTimesADayProgress.setProgressEndColor(whiteColor)
habitTimesADayProgress.setProgressFormatter(null)
habitTimesADayProgress.max = maxProgress
habitTimesADayProgress.setLineCount(maxProgress)
habitTimesADayProgress.progress = progress
} else {
habitTimesADayProgress.gone()
}
val habitCompleteBackground =
myView.findViewById<View>(R.id.habitCompletedBackground)
if (isCompleted) {
habitCompleteBackground.visible()
val b = habitCompleteBackground.background as GradientDrawable
b.mutate()
b.setColor(habitColor)
habitCompleteBackground.background = b
} else {
habitCompleteBackground.gone()
}
myView.findViewById<ImageView>(R.id.habitIcon).setImageDrawable(iconDrawable)
myView.isDrawingCacheEnabled = true
val bitmap = myView.drawingCache
setImageViewBitmap(R.id.habitProgressContainer, bitmap)
setOnClickFillInIntent(
R.id.habitProgressContainer,
if (it.canCompleteMoreForDate(today)) createCompleteHabitIntent(it.id)
else createUndoCompleteHabitIntent(it.id)
)
}
}
}
override fun getCount() = items.size
override fun getViewTypeCount() = 1
override fun onDestroy() {
}
private fun createCompleteHabitIntent(habitId: String): Intent {
val b = Bundle().apply {
putInt(
HabitWidgetProvider.HABIT_ACTION_EXTRA_KEY,
HabitWidgetProvider.HABIT_ACTION_COMPLETE
)
putString(Constants.HABIT_ID_EXTRA_KEY, habitId)
}
return Intent().putExtras(b)
}
private fun createUndoCompleteHabitIntent(habitId: String): Intent {
val b = Bundle().apply {
putInt(
HabitWidgetProvider.HABIT_ACTION_EXTRA_KEY,
HabitWidgetProvider.HABIT_ACTION_UNDO_COMPLETE
)
putString(Constants.HABIT_ID_EXTRA_KEY, habitId)
}
return Intent().putExtras(b)
}
} | gpl-3.0 | 5b5008590d69d8a3d613133e1b5fc7b3 | 36.52514 | 103 | 0.618076 | 5.446878 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/code-insight/postfix-templates/src/org/jetbrains/kotlin/idea/codeInsight/postfix/KotlinWrapIntoCollectionPostfixTemplate.kt | 3 | 1428 | // 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.codeInsight.postfix
import com.intellij.codeInsight.template.postfix.templates.StringBasedPostfixTemplate
import com.intellij.psi.PsiElement
internal class KotlinWrapIntoListPostfixTemplate(provider: KotlinPostfixTemplateProvider)
: KotlinWrapIntoCollectionPostfixTemplate("listOf", provider)
internal class KotlinWrapIntoSetPostfixTemplate(provider: KotlinPostfixTemplateProvider)
: KotlinWrapIntoCollectionPostfixTemplate("setOf", provider)
internal class KotlinWrapIntoSequencePostfixTemplate(provider: KotlinPostfixTemplateProvider)
: KotlinWrapIntoCollectionPostfixTemplate("sequenceOf", provider)
internal abstract class KotlinWrapIntoCollectionPostfixTemplate : StringBasedPostfixTemplate {
private val functionName: String
@Suppress("ConvertSecondaryConstructorToPrimary")
constructor(functionName: String, provider: KotlinPostfixTemplateProvider) : super(
/* name = */ functionName,
/* example = */ "$functionName(expr)",
/* selector = */ allExpressions(ValuedFilter),
/* provider = */ provider
) {
this.functionName = functionName
}
override fun getTemplateString(element: PsiElement) = "$functionName(\$expr$)\$END$"
override fun getElementToRemove(expr: PsiElement) = expr
} | apache-2.0 | fa8bebae0b4b46288393cce4c09f85a3 | 45.096774 | 120 | 0.783613 | 5.471264 | false | false | false | false |
Qase/KotlinLogger | kotlinlog/src/main/kotlin/quanti/com/kotlinlog/utils/DateUtils.kt | 1 | 784 | package quanti.com.kotlinlog.utils
import java.text.SimpleDateFormat
import java.util.*
val sdf1 = SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS", Locale.ENGLISH)
val sdf2 = SimpleDateFormat("yyyy_MMdd_HHmm_ss", Locale.ENGLISH)
val sdf3 = SimpleDateFormat("yyyy_MMdd_HHmm", Locale.ENGLISH)
val sdf4 = SimpleDateFormat("yyyy_MMdd", Locale.ENGLISH)
/**
* MM-dd HH:mm:ss.SS
*/
fun getFormattedNow() = sdf1.formatActualTime()
/**
* yyyy_MMdd_HHmm_ss
*/
fun getFormattedFileNameDayNowWithSeconds() = sdf2.formatActualTime()
/**
* yyyy_MMdd_HHmm
*/
fun getFormattedFileNameDayNow() = sdf3.formatActualTime()
/**
* yyyy_MMdd
*/
fun getFormattedFileNameForDayTemp() = sdf4.formatActualTime()
fun SimpleDateFormat.formatActualTime(): String = this.format(ActualTime.currentDate()) | mit | dc9d0d0eadc27cbcd9913285f43bffc6 | 22.787879 | 87 | 0.748724 | 3.579909 | false | false | false | false |
Philip-Trettner/GlmKt | GlmKt/src/glm/vec/Byte/ByteVec4.kt | 1 | 37668 | package glm
data class ByteVec4(val x: Byte, val y: Byte, val z: Byte, val w: Byte) {
// Initializes each element by evaluating init from 0 until 3
constructor(init: (Int) -> Byte) : this(init(0), init(1), init(2), init(3))
operator fun get(idx: Int): Byte = when (idx) {
0 -> x
1 -> y
2 -> z
3 -> w
else -> throw IndexOutOfBoundsException("index $idx is out of bounds")
}
// Operators
operator fun inc(): ByteVec4 = ByteVec4(x.inc(), y.inc(), z.inc(), w.inc())
operator fun dec(): ByteVec4 = ByteVec4(x.dec(), y.dec(), z.dec(), w.dec())
operator fun unaryPlus(): IntVec4 = IntVec4(+x, +y, +z, +w)
operator fun unaryMinus(): IntVec4 = IntVec4(-x, -y, -z, -w)
operator fun plus(rhs: ByteVec4): IntVec4 = IntVec4(x + rhs.x, y + rhs.y, z + rhs.z, w + rhs.w)
operator fun minus(rhs: ByteVec4): IntVec4 = IntVec4(x - rhs.x, y - rhs.y, z - rhs.z, w - rhs.w)
operator fun times(rhs: ByteVec4): IntVec4 = IntVec4(x * rhs.x, y * rhs.y, z * rhs.z, w * rhs.w)
operator fun div(rhs: ByteVec4): IntVec4 = IntVec4(x / rhs.x, y / rhs.y, z / rhs.z, w / rhs.w)
operator fun rem(rhs: ByteVec4): IntVec4 = IntVec4(x % rhs.x, y % rhs.y, z % rhs.z, w % rhs.w)
operator fun plus(rhs: Byte): IntVec4 = IntVec4(x + rhs, y + rhs, z + rhs, w + rhs)
operator fun minus(rhs: Byte): IntVec4 = IntVec4(x - rhs, y - rhs, z - rhs, w - rhs)
operator fun times(rhs: Byte): IntVec4 = IntVec4(x * rhs, y * rhs, z * rhs, w * rhs)
operator fun div(rhs: Byte): IntVec4 = IntVec4(x / rhs, y / rhs, z / rhs, w / rhs)
operator fun rem(rhs: Byte): IntVec4 = IntVec4(x % rhs, y % rhs, z % rhs, w % rhs)
inline fun map(func: (Byte) -> Byte): ByteVec4 = ByteVec4(func(x), func(y), func(z), func(w))
fun toList(): List<Byte> = listOf(x, y, z, w)
// Predefined vector constants
companion object Constants {
val zero: ByteVec4 = ByteVec4(0.toByte(), 0.toByte(), 0.toByte(), 0.toByte())
val ones: ByteVec4 = ByteVec4(1.toByte(), 1.toByte(), 1.toByte(), 1.toByte())
val unitX: ByteVec4 = ByteVec4(1.toByte(), 0.toByte(), 0.toByte(), 0.toByte())
val unitY: ByteVec4 = ByteVec4(0.toByte(), 1.toByte(), 0.toByte(), 0.toByte())
val unitZ: ByteVec4 = ByteVec4(0.toByte(), 0.toByte(), 1.toByte(), 0.toByte())
val unitW: ByteVec4 = ByteVec4(0.toByte(), 0.toByte(), 0.toByte(), 1.toByte())
}
// Conversions to Float
fun toVec(): Vec4 = Vec4(x.toFloat(), y.toFloat(), z.toFloat(), w.toFloat())
inline fun toVec(conv: (Byte) -> Float): Vec4 = Vec4(conv(x), conv(y), conv(z), conv(w))
fun toVec2(): Vec2 = Vec2(x.toFloat(), y.toFloat())
inline fun toVec2(conv: (Byte) -> Float): Vec2 = Vec2(conv(x), conv(y))
fun toVec3(): Vec3 = Vec3(x.toFloat(), y.toFloat(), z.toFloat())
inline fun toVec3(conv: (Byte) -> Float): Vec3 = Vec3(conv(x), conv(y), conv(z))
fun toVec4(): Vec4 = Vec4(x.toFloat(), y.toFloat(), z.toFloat(), w.toFloat())
inline fun toVec4(conv: (Byte) -> Float): Vec4 = Vec4(conv(x), conv(y), conv(z), conv(w))
// Conversions to Float
fun toMutableVec(): MutableVec4 = MutableVec4(x.toFloat(), y.toFloat(), z.toFloat(), w.toFloat())
inline fun toMutableVec(conv: (Byte) -> Float): MutableVec4 = MutableVec4(conv(x), conv(y), conv(z), conv(w))
fun toMutableVec2(): MutableVec2 = MutableVec2(x.toFloat(), y.toFloat())
inline fun toMutableVec2(conv: (Byte) -> Float): MutableVec2 = MutableVec2(conv(x), conv(y))
fun toMutableVec3(): MutableVec3 = MutableVec3(x.toFloat(), y.toFloat(), z.toFloat())
inline fun toMutableVec3(conv: (Byte) -> Float): MutableVec3 = MutableVec3(conv(x), conv(y), conv(z))
fun toMutableVec4(): MutableVec4 = MutableVec4(x.toFloat(), y.toFloat(), z.toFloat(), w.toFloat())
inline fun toMutableVec4(conv: (Byte) -> Float): MutableVec4 = MutableVec4(conv(x), conv(y), conv(z), conv(w))
// Conversions to Double
fun toDoubleVec(): DoubleVec4 = DoubleVec4(x.toDouble(), y.toDouble(), z.toDouble(), w.toDouble())
inline fun toDoubleVec(conv: (Byte) -> Double): DoubleVec4 = DoubleVec4(conv(x), conv(y), conv(z), conv(w))
fun toDoubleVec2(): DoubleVec2 = DoubleVec2(x.toDouble(), y.toDouble())
inline fun toDoubleVec2(conv: (Byte) -> Double): DoubleVec2 = DoubleVec2(conv(x), conv(y))
fun toDoubleVec3(): DoubleVec3 = DoubleVec3(x.toDouble(), y.toDouble(), z.toDouble())
inline fun toDoubleVec3(conv: (Byte) -> Double): DoubleVec3 = DoubleVec3(conv(x), conv(y), conv(z))
fun toDoubleVec4(): DoubleVec4 = DoubleVec4(x.toDouble(), y.toDouble(), z.toDouble(), w.toDouble())
inline fun toDoubleVec4(conv: (Byte) -> Double): DoubleVec4 = DoubleVec4(conv(x), conv(y), conv(z), conv(w))
// Conversions to Double
fun toMutableDoubleVec(): MutableDoubleVec4 = MutableDoubleVec4(x.toDouble(), y.toDouble(), z.toDouble(), w.toDouble())
inline fun toMutableDoubleVec(conv: (Byte) -> Double): MutableDoubleVec4 = MutableDoubleVec4(conv(x), conv(y), conv(z), conv(w))
fun toMutableDoubleVec2(): MutableDoubleVec2 = MutableDoubleVec2(x.toDouble(), y.toDouble())
inline fun toMutableDoubleVec2(conv: (Byte) -> Double): MutableDoubleVec2 = MutableDoubleVec2(conv(x), conv(y))
fun toMutableDoubleVec3(): MutableDoubleVec3 = MutableDoubleVec3(x.toDouble(), y.toDouble(), z.toDouble())
inline fun toMutableDoubleVec3(conv: (Byte) -> Double): MutableDoubleVec3 = MutableDoubleVec3(conv(x), conv(y), conv(z))
fun toMutableDoubleVec4(): MutableDoubleVec4 = MutableDoubleVec4(x.toDouble(), y.toDouble(), z.toDouble(), w.toDouble())
inline fun toMutableDoubleVec4(conv: (Byte) -> Double): MutableDoubleVec4 = MutableDoubleVec4(conv(x), conv(y), conv(z), conv(w))
// Conversions to Int
fun toIntVec(): IntVec4 = IntVec4(x.toInt(), y.toInt(), z.toInt(), w.toInt())
inline fun toIntVec(conv: (Byte) -> Int): IntVec4 = IntVec4(conv(x), conv(y), conv(z), conv(w))
fun toIntVec2(): IntVec2 = IntVec2(x.toInt(), y.toInt())
inline fun toIntVec2(conv: (Byte) -> Int): IntVec2 = IntVec2(conv(x), conv(y))
fun toIntVec3(): IntVec3 = IntVec3(x.toInt(), y.toInt(), z.toInt())
inline fun toIntVec3(conv: (Byte) -> Int): IntVec3 = IntVec3(conv(x), conv(y), conv(z))
fun toIntVec4(): IntVec4 = IntVec4(x.toInt(), y.toInt(), z.toInt(), w.toInt())
inline fun toIntVec4(conv: (Byte) -> Int): IntVec4 = IntVec4(conv(x), conv(y), conv(z), conv(w))
// Conversions to Int
fun toMutableIntVec(): MutableIntVec4 = MutableIntVec4(x.toInt(), y.toInt(), z.toInt(), w.toInt())
inline fun toMutableIntVec(conv: (Byte) -> Int): MutableIntVec4 = MutableIntVec4(conv(x), conv(y), conv(z), conv(w))
fun toMutableIntVec2(): MutableIntVec2 = MutableIntVec2(x.toInt(), y.toInt())
inline fun toMutableIntVec2(conv: (Byte) -> Int): MutableIntVec2 = MutableIntVec2(conv(x), conv(y))
fun toMutableIntVec3(): MutableIntVec3 = MutableIntVec3(x.toInt(), y.toInt(), z.toInt())
inline fun toMutableIntVec3(conv: (Byte) -> Int): MutableIntVec3 = MutableIntVec3(conv(x), conv(y), conv(z))
fun toMutableIntVec4(): MutableIntVec4 = MutableIntVec4(x.toInt(), y.toInt(), z.toInt(), w.toInt())
inline fun toMutableIntVec4(conv: (Byte) -> Int): MutableIntVec4 = MutableIntVec4(conv(x), conv(y), conv(z), conv(w))
// Conversions to Long
fun toLongVec(): LongVec4 = LongVec4(x.toLong(), y.toLong(), z.toLong(), w.toLong())
inline fun toLongVec(conv: (Byte) -> Long): LongVec4 = LongVec4(conv(x), conv(y), conv(z), conv(w))
fun toLongVec2(): LongVec2 = LongVec2(x.toLong(), y.toLong())
inline fun toLongVec2(conv: (Byte) -> Long): LongVec2 = LongVec2(conv(x), conv(y))
fun toLongVec3(): LongVec3 = LongVec3(x.toLong(), y.toLong(), z.toLong())
inline fun toLongVec3(conv: (Byte) -> Long): LongVec3 = LongVec3(conv(x), conv(y), conv(z))
fun toLongVec4(): LongVec4 = LongVec4(x.toLong(), y.toLong(), z.toLong(), w.toLong())
inline fun toLongVec4(conv: (Byte) -> Long): LongVec4 = LongVec4(conv(x), conv(y), conv(z), conv(w))
// Conversions to Long
fun toMutableLongVec(): MutableLongVec4 = MutableLongVec4(x.toLong(), y.toLong(), z.toLong(), w.toLong())
inline fun toMutableLongVec(conv: (Byte) -> Long): MutableLongVec4 = MutableLongVec4(conv(x), conv(y), conv(z), conv(w))
fun toMutableLongVec2(): MutableLongVec2 = MutableLongVec2(x.toLong(), y.toLong())
inline fun toMutableLongVec2(conv: (Byte) -> Long): MutableLongVec2 = MutableLongVec2(conv(x), conv(y))
fun toMutableLongVec3(): MutableLongVec3 = MutableLongVec3(x.toLong(), y.toLong(), z.toLong())
inline fun toMutableLongVec3(conv: (Byte) -> Long): MutableLongVec3 = MutableLongVec3(conv(x), conv(y), conv(z))
fun toMutableLongVec4(): MutableLongVec4 = MutableLongVec4(x.toLong(), y.toLong(), z.toLong(), w.toLong())
inline fun toMutableLongVec4(conv: (Byte) -> Long): MutableLongVec4 = MutableLongVec4(conv(x), conv(y), conv(z), conv(w))
// Conversions to Short
fun toShortVec(): ShortVec4 = ShortVec4(x.toShort(), y.toShort(), z.toShort(), w.toShort())
inline fun toShortVec(conv: (Byte) -> Short): ShortVec4 = ShortVec4(conv(x), conv(y), conv(z), conv(w))
fun toShortVec2(): ShortVec2 = ShortVec2(x.toShort(), y.toShort())
inline fun toShortVec2(conv: (Byte) -> Short): ShortVec2 = ShortVec2(conv(x), conv(y))
fun toShortVec3(): ShortVec3 = ShortVec3(x.toShort(), y.toShort(), z.toShort())
inline fun toShortVec3(conv: (Byte) -> Short): ShortVec3 = ShortVec3(conv(x), conv(y), conv(z))
fun toShortVec4(): ShortVec4 = ShortVec4(x.toShort(), y.toShort(), z.toShort(), w.toShort())
inline fun toShortVec4(conv: (Byte) -> Short): ShortVec4 = ShortVec4(conv(x), conv(y), conv(z), conv(w))
// Conversions to Short
fun toMutableShortVec(): MutableShortVec4 = MutableShortVec4(x.toShort(), y.toShort(), z.toShort(), w.toShort())
inline fun toMutableShortVec(conv: (Byte) -> Short): MutableShortVec4 = MutableShortVec4(conv(x), conv(y), conv(z), conv(w))
fun toMutableShortVec2(): MutableShortVec2 = MutableShortVec2(x.toShort(), y.toShort())
inline fun toMutableShortVec2(conv: (Byte) -> Short): MutableShortVec2 = MutableShortVec2(conv(x), conv(y))
fun toMutableShortVec3(): MutableShortVec3 = MutableShortVec3(x.toShort(), y.toShort(), z.toShort())
inline fun toMutableShortVec3(conv: (Byte) -> Short): MutableShortVec3 = MutableShortVec3(conv(x), conv(y), conv(z))
fun toMutableShortVec4(): MutableShortVec4 = MutableShortVec4(x.toShort(), y.toShort(), z.toShort(), w.toShort())
inline fun toMutableShortVec4(conv: (Byte) -> Short): MutableShortVec4 = MutableShortVec4(conv(x), conv(y), conv(z), conv(w))
// Conversions to Byte
fun toByteVec(): ByteVec4 = ByteVec4(x, y, z, w)
inline fun toByteVec(conv: (Byte) -> Byte): ByteVec4 = ByteVec4(conv(x), conv(y), conv(z), conv(w))
fun toByteVec2(): ByteVec2 = ByteVec2(x, y)
inline fun toByteVec2(conv: (Byte) -> Byte): ByteVec2 = ByteVec2(conv(x), conv(y))
fun toByteVec3(): ByteVec3 = ByteVec3(x, y, z)
inline fun toByteVec3(conv: (Byte) -> Byte): ByteVec3 = ByteVec3(conv(x), conv(y), conv(z))
fun toByteVec4(): ByteVec4 = ByteVec4(x, y, z, w)
inline fun toByteVec4(conv: (Byte) -> Byte): ByteVec4 = ByteVec4(conv(x), conv(y), conv(z), conv(w))
// Conversions to Byte
fun toMutableByteVec(): MutableByteVec4 = MutableByteVec4(x, y, z, w)
inline fun toMutableByteVec(conv: (Byte) -> Byte): MutableByteVec4 = MutableByteVec4(conv(x), conv(y), conv(z), conv(w))
fun toMutableByteVec2(): MutableByteVec2 = MutableByteVec2(x, y)
inline fun toMutableByteVec2(conv: (Byte) -> Byte): MutableByteVec2 = MutableByteVec2(conv(x), conv(y))
fun toMutableByteVec3(): MutableByteVec3 = MutableByteVec3(x, y, z)
inline fun toMutableByteVec3(conv: (Byte) -> Byte): MutableByteVec3 = MutableByteVec3(conv(x), conv(y), conv(z))
fun toMutableByteVec4(): MutableByteVec4 = MutableByteVec4(x, y, z, w)
inline fun toMutableByteVec4(conv: (Byte) -> Byte): MutableByteVec4 = MutableByteVec4(conv(x), conv(y), conv(z), conv(w))
// Conversions to Char
fun toCharVec(): CharVec4 = CharVec4(x.toChar(), y.toChar(), z.toChar(), w.toChar())
inline fun toCharVec(conv: (Byte) -> Char): CharVec4 = CharVec4(conv(x), conv(y), conv(z), conv(w))
fun toCharVec2(): CharVec2 = CharVec2(x.toChar(), y.toChar())
inline fun toCharVec2(conv: (Byte) -> Char): CharVec2 = CharVec2(conv(x), conv(y))
fun toCharVec3(): CharVec3 = CharVec3(x.toChar(), y.toChar(), z.toChar())
inline fun toCharVec3(conv: (Byte) -> Char): CharVec3 = CharVec3(conv(x), conv(y), conv(z))
fun toCharVec4(): CharVec4 = CharVec4(x.toChar(), y.toChar(), z.toChar(), w.toChar())
inline fun toCharVec4(conv: (Byte) -> Char): CharVec4 = CharVec4(conv(x), conv(y), conv(z), conv(w))
// Conversions to Char
fun toMutableCharVec(): MutableCharVec4 = MutableCharVec4(x.toChar(), y.toChar(), z.toChar(), w.toChar())
inline fun toMutableCharVec(conv: (Byte) -> Char): MutableCharVec4 = MutableCharVec4(conv(x), conv(y), conv(z), conv(w))
fun toMutableCharVec2(): MutableCharVec2 = MutableCharVec2(x.toChar(), y.toChar())
inline fun toMutableCharVec2(conv: (Byte) -> Char): MutableCharVec2 = MutableCharVec2(conv(x), conv(y))
fun toMutableCharVec3(): MutableCharVec3 = MutableCharVec3(x.toChar(), y.toChar(), z.toChar())
inline fun toMutableCharVec3(conv: (Byte) -> Char): MutableCharVec3 = MutableCharVec3(conv(x), conv(y), conv(z))
fun toMutableCharVec4(): MutableCharVec4 = MutableCharVec4(x.toChar(), y.toChar(), z.toChar(), w.toChar())
inline fun toMutableCharVec4(conv: (Byte) -> Char): MutableCharVec4 = MutableCharVec4(conv(x), conv(y), conv(z), conv(w))
// Conversions to Boolean
fun toBoolVec(): BoolVec4 = BoolVec4(x != 0.toByte(), y != 0.toByte(), z != 0.toByte(), w != 0.toByte())
inline fun toBoolVec(conv: (Byte) -> Boolean): BoolVec4 = BoolVec4(conv(x), conv(y), conv(z), conv(w))
fun toBoolVec2(): BoolVec2 = BoolVec2(x != 0.toByte(), y != 0.toByte())
inline fun toBoolVec2(conv: (Byte) -> Boolean): BoolVec2 = BoolVec2(conv(x), conv(y))
fun toBoolVec3(): BoolVec3 = BoolVec3(x != 0.toByte(), y != 0.toByte(), z != 0.toByte())
inline fun toBoolVec3(conv: (Byte) -> Boolean): BoolVec3 = BoolVec3(conv(x), conv(y), conv(z))
fun toBoolVec4(): BoolVec4 = BoolVec4(x != 0.toByte(), y != 0.toByte(), z != 0.toByte(), w != 0.toByte())
inline fun toBoolVec4(conv: (Byte) -> Boolean): BoolVec4 = BoolVec4(conv(x), conv(y), conv(z), conv(w))
// Conversions to Boolean
fun toMutableBoolVec(): MutableBoolVec4 = MutableBoolVec4(x != 0.toByte(), y != 0.toByte(), z != 0.toByte(), w != 0.toByte())
inline fun toMutableBoolVec(conv: (Byte) -> Boolean): MutableBoolVec4 = MutableBoolVec4(conv(x), conv(y), conv(z), conv(w))
fun toMutableBoolVec2(): MutableBoolVec2 = MutableBoolVec2(x != 0.toByte(), y != 0.toByte())
inline fun toMutableBoolVec2(conv: (Byte) -> Boolean): MutableBoolVec2 = MutableBoolVec2(conv(x), conv(y))
fun toMutableBoolVec3(): MutableBoolVec3 = MutableBoolVec3(x != 0.toByte(), y != 0.toByte(), z != 0.toByte())
inline fun toMutableBoolVec3(conv: (Byte) -> Boolean): MutableBoolVec3 = MutableBoolVec3(conv(x), conv(y), conv(z))
fun toMutableBoolVec4(): MutableBoolVec4 = MutableBoolVec4(x != 0.toByte(), y != 0.toByte(), z != 0.toByte(), w != 0.toByte())
inline fun toMutableBoolVec4(conv: (Byte) -> Boolean): MutableBoolVec4 = MutableBoolVec4(conv(x), conv(y), conv(z), conv(w))
// Conversions to String
fun toStringVec(): StringVec4 = StringVec4(x.toString(), y.toString(), z.toString(), w.toString())
inline fun toStringVec(conv: (Byte) -> String): StringVec4 = StringVec4(conv(x), conv(y), conv(z), conv(w))
fun toStringVec2(): StringVec2 = StringVec2(x.toString(), y.toString())
inline fun toStringVec2(conv: (Byte) -> String): StringVec2 = StringVec2(conv(x), conv(y))
fun toStringVec3(): StringVec3 = StringVec3(x.toString(), y.toString(), z.toString())
inline fun toStringVec3(conv: (Byte) -> String): StringVec3 = StringVec3(conv(x), conv(y), conv(z))
fun toStringVec4(): StringVec4 = StringVec4(x.toString(), y.toString(), z.toString(), w.toString())
inline fun toStringVec4(conv: (Byte) -> String): StringVec4 = StringVec4(conv(x), conv(y), conv(z), conv(w))
// Conversions to String
fun toMutableStringVec(): MutableStringVec4 = MutableStringVec4(x.toString(), y.toString(), z.toString(), w.toString())
inline fun toMutableStringVec(conv: (Byte) -> String): MutableStringVec4 = MutableStringVec4(conv(x), conv(y), conv(z), conv(w))
fun toMutableStringVec2(): MutableStringVec2 = MutableStringVec2(x.toString(), y.toString())
inline fun toMutableStringVec2(conv: (Byte) -> String): MutableStringVec2 = MutableStringVec2(conv(x), conv(y))
fun toMutableStringVec3(): MutableStringVec3 = MutableStringVec3(x.toString(), y.toString(), z.toString())
inline fun toMutableStringVec3(conv: (Byte) -> String): MutableStringVec3 = MutableStringVec3(conv(x), conv(y), conv(z))
fun toMutableStringVec4(): MutableStringVec4 = MutableStringVec4(x.toString(), y.toString(), z.toString(), w.toString())
inline fun toMutableStringVec4(conv: (Byte) -> String): MutableStringVec4 = MutableStringVec4(conv(x), conv(y), conv(z), conv(w))
// Conversions to T2
inline fun <T2> toTVec(conv: (Byte) -> T2): TVec4<T2> = TVec4<T2>(conv(x), conv(y), conv(z), conv(w))
inline fun <T2> toTVec2(conv: (Byte) -> T2): TVec2<T2> = TVec2<T2>(conv(x), conv(y))
inline fun <T2> toTVec3(conv: (Byte) -> T2): TVec3<T2> = TVec3<T2>(conv(x), conv(y), conv(z))
inline fun <T2> toTVec4(conv: (Byte) -> T2): TVec4<T2> = TVec4<T2>(conv(x), conv(y), conv(z), conv(w))
// Conversions to T2
inline fun <T2> toMutableTVec(conv: (Byte) -> T2): MutableTVec4<T2> = MutableTVec4<T2>(conv(x), conv(y), conv(z), conv(w))
inline fun <T2> toMutableTVec2(conv: (Byte) -> T2): MutableTVec2<T2> = MutableTVec2<T2>(conv(x), conv(y))
inline fun <T2> toMutableTVec3(conv: (Byte) -> T2): MutableTVec3<T2> = MutableTVec3<T2>(conv(x), conv(y), conv(z))
inline fun <T2> toMutableTVec4(conv: (Byte) -> T2): MutableTVec4<T2> = MutableTVec4<T2>(conv(x), conv(y), conv(z), conv(w))
// Allows for swizzling, e.g. v.swizzle.xzx
inner class Swizzle {
val xx: ByteVec2 get() = ByteVec2(x, x)
val xy: ByteVec2 get() = ByteVec2(x, y)
val xz: ByteVec2 get() = ByteVec2(x, z)
val xw: ByteVec2 get() = ByteVec2(x, w)
val yx: ByteVec2 get() = ByteVec2(y, x)
val yy: ByteVec2 get() = ByteVec2(y, y)
val yz: ByteVec2 get() = ByteVec2(y, z)
val yw: ByteVec2 get() = ByteVec2(y, w)
val zx: ByteVec2 get() = ByteVec2(z, x)
val zy: ByteVec2 get() = ByteVec2(z, y)
val zz: ByteVec2 get() = ByteVec2(z, z)
val zw: ByteVec2 get() = ByteVec2(z, w)
val wx: ByteVec2 get() = ByteVec2(w, x)
val wy: ByteVec2 get() = ByteVec2(w, y)
val wz: ByteVec2 get() = ByteVec2(w, z)
val ww: ByteVec2 get() = ByteVec2(w, w)
val xxx: ByteVec3 get() = ByteVec3(x, x, x)
val xxy: ByteVec3 get() = ByteVec3(x, x, y)
val xxz: ByteVec3 get() = ByteVec3(x, x, z)
val xxw: ByteVec3 get() = ByteVec3(x, x, w)
val xyx: ByteVec3 get() = ByteVec3(x, y, x)
val xyy: ByteVec3 get() = ByteVec3(x, y, y)
val xyz: ByteVec3 get() = ByteVec3(x, y, z)
val xyw: ByteVec3 get() = ByteVec3(x, y, w)
val xzx: ByteVec3 get() = ByteVec3(x, z, x)
val xzy: ByteVec3 get() = ByteVec3(x, z, y)
val xzz: ByteVec3 get() = ByteVec3(x, z, z)
val xzw: ByteVec3 get() = ByteVec3(x, z, w)
val xwx: ByteVec3 get() = ByteVec3(x, w, x)
val xwy: ByteVec3 get() = ByteVec3(x, w, y)
val xwz: ByteVec3 get() = ByteVec3(x, w, z)
val xww: ByteVec3 get() = ByteVec3(x, w, w)
val yxx: ByteVec3 get() = ByteVec3(y, x, x)
val yxy: ByteVec3 get() = ByteVec3(y, x, y)
val yxz: ByteVec3 get() = ByteVec3(y, x, z)
val yxw: ByteVec3 get() = ByteVec3(y, x, w)
val yyx: ByteVec3 get() = ByteVec3(y, y, x)
val yyy: ByteVec3 get() = ByteVec3(y, y, y)
val yyz: ByteVec3 get() = ByteVec3(y, y, z)
val yyw: ByteVec3 get() = ByteVec3(y, y, w)
val yzx: ByteVec3 get() = ByteVec3(y, z, x)
val yzy: ByteVec3 get() = ByteVec3(y, z, y)
val yzz: ByteVec3 get() = ByteVec3(y, z, z)
val yzw: ByteVec3 get() = ByteVec3(y, z, w)
val ywx: ByteVec3 get() = ByteVec3(y, w, x)
val ywy: ByteVec3 get() = ByteVec3(y, w, y)
val ywz: ByteVec3 get() = ByteVec3(y, w, z)
val yww: ByteVec3 get() = ByteVec3(y, w, w)
val zxx: ByteVec3 get() = ByteVec3(z, x, x)
val zxy: ByteVec3 get() = ByteVec3(z, x, y)
val zxz: ByteVec3 get() = ByteVec3(z, x, z)
val zxw: ByteVec3 get() = ByteVec3(z, x, w)
val zyx: ByteVec3 get() = ByteVec3(z, y, x)
val zyy: ByteVec3 get() = ByteVec3(z, y, y)
val zyz: ByteVec3 get() = ByteVec3(z, y, z)
val zyw: ByteVec3 get() = ByteVec3(z, y, w)
val zzx: ByteVec3 get() = ByteVec3(z, z, x)
val zzy: ByteVec3 get() = ByteVec3(z, z, y)
val zzz: ByteVec3 get() = ByteVec3(z, z, z)
val zzw: ByteVec3 get() = ByteVec3(z, z, w)
val zwx: ByteVec3 get() = ByteVec3(z, w, x)
val zwy: ByteVec3 get() = ByteVec3(z, w, y)
val zwz: ByteVec3 get() = ByteVec3(z, w, z)
val zww: ByteVec3 get() = ByteVec3(z, w, w)
val wxx: ByteVec3 get() = ByteVec3(w, x, x)
val wxy: ByteVec3 get() = ByteVec3(w, x, y)
val wxz: ByteVec3 get() = ByteVec3(w, x, z)
val wxw: ByteVec3 get() = ByteVec3(w, x, w)
val wyx: ByteVec3 get() = ByteVec3(w, y, x)
val wyy: ByteVec3 get() = ByteVec3(w, y, y)
val wyz: ByteVec3 get() = ByteVec3(w, y, z)
val wyw: ByteVec3 get() = ByteVec3(w, y, w)
val wzx: ByteVec3 get() = ByteVec3(w, z, x)
val wzy: ByteVec3 get() = ByteVec3(w, z, y)
val wzz: ByteVec3 get() = ByteVec3(w, z, z)
val wzw: ByteVec3 get() = ByteVec3(w, z, w)
val wwx: ByteVec3 get() = ByteVec3(w, w, x)
val wwy: ByteVec3 get() = ByteVec3(w, w, y)
val wwz: ByteVec3 get() = ByteVec3(w, w, z)
val www: ByteVec3 get() = ByteVec3(w, w, w)
val xxxx: ByteVec4 get() = ByteVec4(x, x, x, x)
val xxxy: ByteVec4 get() = ByteVec4(x, x, x, y)
val xxxz: ByteVec4 get() = ByteVec4(x, x, x, z)
val xxxw: ByteVec4 get() = ByteVec4(x, x, x, w)
val xxyx: ByteVec4 get() = ByteVec4(x, x, y, x)
val xxyy: ByteVec4 get() = ByteVec4(x, x, y, y)
val xxyz: ByteVec4 get() = ByteVec4(x, x, y, z)
val xxyw: ByteVec4 get() = ByteVec4(x, x, y, w)
val xxzx: ByteVec4 get() = ByteVec4(x, x, z, x)
val xxzy: ByteVec4 get() = ByteVec4(x, x, z, y)
val xxzz: ByteVec4 get() = ByteVec4(x, x, z, z)
val xxzw: ByteVec4 get() = ByteVec4(x, x, z, w)
val xxwx: ByteVec4 get() = ByteVec4(x, x, w, x)
val xxwy: ByteVec4 get() = ByteVec4(x, x, w, y)
val xxwz: ByteVec4 get() = ByteVec4(x, x, w, z)
val xxww: ByteVec4 get() = ByteVec4(x, x, w, w)
val xyxx: ByteVec4 get() = ByteVec4(x, y, x, x)
val xyxy: ByteVec4 get() = ByteVec4(x, y, x, y)
val xyxz: ByteVec4 get() = ByteVec4(x, y, x, z)
val xyxw: ByteVec4 get() = ByteVec4(x, y, x, w)
val xyyx: ByteVec4 get() = ByteVec4(x, y, y, x)
val xyyy: ByteVec4 get() = ByteVec4(x, y, y, y)
val xyyz: ByteVec4 get() = ByteVec4(x, y, y, z)
val xyyw: ByteVec4 get() = ByteVec4(x, y, y, w)
val xyzx: ByteVec4 get() = ByteVec4(x, y, z, x)
val xyzy: ByteVec4 get() = ByteVec4(x, y, z, y)
val xyzz: ByteVec4 get() = ByteVec4(x, y, z, z)
val xyzw: ByteVec4 get() = ByteVec4(x, y, z, w)
val xywx: ByteVec4 get() = ByteVec4(x, y, w, x)
val xywy: ByteVec4 get() = ByteVec4(x, y, w, y)
val xywz: ByteVec4 get() = ByteVec4(x, y, w, z)
val xyww: ByteVec4 get() = ByteVec4(x, y, w, w)
val xzxx: ByteVec4 get() = ByteVec4(x, z, x, x)
val xzxy: ByteVec4 get() = ByteVec4(x, z, x, y)
val xzxz: ByteVec4 get() = ByteVec4(x, z, x, z)
val xzxw: ByteVec4 get() = ByteVec4(x, z, x, w)
val xzyx: ByteVec4 get() = ByteVec4(x, z, y, x)
val xzyy: ByteVec4 get() = ByteVec4(x, z, y, y)
val xzyz: ByteVec4 get() = ByteVec4(x, z, y, z)
val xzyw: ByteVec4 get() = ByteVec4(x, z, y, w)
val xzzx: ByteVec4 get() = ByteVec4(x, z, z, x)
val xzzy: ByteVec4 get() = ByteVec4(x, z, z, y)
val xzzz: ByteVec4 get() = ByteVec4(x, z, z, z)
val xzzw: ByteVec4 get() = ByteVec4(x, z, z, w)
val xzwx: ByteVec4 get() = ByteVec4(x, z, w, x)
val xzwy: ByteVec4 get() = ByteVec4(x, z, w, y)
val xzwz: ByteVec4 get() = ByteVec4(x, z, w, z)
val xzww: ByteVec4 get() = ByteVec4(x, z, w, w)
val xwxx: ByteVec4 get() = ByteVec4(x, w, x, x)
val xwxy: ByteVec4 get() = ByteVec4(x, w, x, y)
val xwxz: ByteVec4 get() = ByteVec4(x, w, x, z)
val xwxw: ByteVec4 get() = ByteVec4(x, w, x, w)
val xwyx: ByteVec4 get() = ByteVec4(x, w, y, x)
val xwyy: ByteVec4 get() = ByteVec4(x, w, y, y)
val xwyz: ByteVec4 get() = ByteVec4(x, w, y, z)
val xwyw: ByteVec4 get() = ByteVec4(x, w, y, w)
val xwzx: ByteVec4 get() = ByteVec4(x, w, z, x)
val xwzy: ByteVec4 get() = ByteVec4(x, w, z, y)
val xwzz: ByteVec4 get() = ByteVec4(x, w, z, z)
val xwzw: ByteVec4 get() = ByteVec4(x, w, z, w)
val xwwx: ByteVec4 get() = ByteVec4(x, w, w, x)
val xwwy: ByteVec4 get() = ByteVec4(x, w, w, y)
val xwwz: ByteVec4 get() = ByteVec4(x, w, w, z)
val xwww: ByteVec4 get() = ByteVec4(x, w, w, w)
val yxxx: ByteVec4 get() = ByteVec4(y, x, x, x)
val yxxy: ByteVec4 get() = ByteVec4(y, x, x, y)
val yxxz: ByteVec4 get() = ByteVec4(y, x, x, z)
val yxxw: ByteVec4 get() = ByteVec4(y, x, x, w)
val yxyx: ByteVec4 get() = ByteVec4(y, x, y, x)
val yxyy: ByteVec4 get() = ByteVec4(y, x, y, y)
val yxyz: ByteVec4 get() = ByteVec4(y, x, y, z)
val yxyw: ByteVec4 get() = ByteVec4(y, x, y, w)
val yxzx: ByteVec4 get() = ByteVec4(y, x, z, x)
val yxzy: ByteVec4 get() = ByteVec4(y, x, z, y)
val yxzz: ByteVec4 get() = ByteVec4(y, x, z, z)
val yxzw: ByteVec4 get() = ByteVec4(y, x, z, w)
val yxwx: ByteVec4 get() = ByteVec4(y, x, w, x)
val yxwy: ByteVec4 get() = ByteVec4(y, x, w, y)
val yxwz: ByteVec4 get() = ByteVec4(y, x, w, z)
val yxww: ByteVec4 get() = ByteVec4(y, x, w, w)
val yyxx: ByteVec4 get() = ByteVec4(y, y, x, x)
val yyxy: ByteVec4 get() = ByteVec4(y, y, x, y)
val yyxz: ByteVec4 get() = ByteVec4(y, y, x, z)
val yyxw: ByteVec4 get() = ByteVec4(y, y, x, w)
val yyyx: ByteVec4 get() = ByteVec4(y, y, y, x)
val yyyy: ByteVec4 get() = ByteVec4(y, y, y, y)
val yyyz: ByteVec4 get() = ByteVec4(y, y, y, z)
val yyyw: ByteVec4 get() = ByteVec4(y, y, y, w)
val yyzx: ByteVec4 get() = ByteVec4(y, y, z, x)
val yyzy: ByteVec4 get() = ByteVec4(y, y, z, y)
val yyzz: ByteVec4 get() = ByteVec4(y, y, z, z)
val yyzw: ByteVec4 get() = ByteVec4(y, y, z, w)
val yywx: ByteVec4 get() = ByteVec4(y, y, w, x)
val yywy: ByteVec4 get() = ByteVec4(y, y, w, y)
val yywz: ByteVec4 get() = ByteVec4(y, y, w, z)
val yyww: ByteVec4 get() = ByteVec4(y, y, w, w)
val yzxx: ByteVec4 get() = ByteVec4(y, z, x, x)
val yzxy: ByteVec4 get() = ByteVec4(y, z, x, y)
val yzxz: ByteVec4 get() = ByteVec4(y, z, x, z)
val yzxw: ByteVec4 get() = ByteVec4(y, z, x, w)
val yzyx: ByteVec4 get() = ByteVec4(y, z, y, x)
val yzyy: ByteVec4 get() = ByteVec4(y, z, y, y)
val yzyz: ByteVec4 get() = ByteVec4(y, z, y, z)
val yzyw: ByteVec4 get() = ByteVec4(y, z, y, w)
val yzzx: ByteVec4 get() = ByteVec4(y, z, z, x)
val yzzy: ByteVec4 get() = ByteVec4(y, z, z, y)
val yzzz: ByteVec4 get() = ByteVec4(y, z, z, z)
val yzzw: ByteVec4 get() = ByteVec4(y, z, z, w)
val yzwx: ByteVec4 get() = ByteVec4(y, z, w, x)
val yzwy: ByteVec4 get() = ByteVec4(y, z, w, y)
val yzwz: ByteVec4 get() = ByteVec4(y, z, w, z)
val yzww: ByteVec4 get() = ByteVec4(y, z, w, w)
val ywxx: ByteVec4 get() = ByteVec4(y, w, x, x)
val ywxy: ByteVec4 get() = ByteVec4(y, w, x, y)
val ywxz: ByteVec4 get() = ByteVec4(y, w, x, z)
val ywxw: ByteVec4 get() = ByteVec4(y, w, x, w)
val ywyx: ByteVec4 get() = ByteVec4(y, w, y, x)
val ywyy: ByteVec4 get() = ByteVec4(y, w, y, y)
val ywyz: ByteVec4 get() = ByteVec4(y, w, y, z)
val ywyw: ByteVec4 get() = ByteVec4(y, w, y, w)
val ywzx: ByteVec4 get() = ByteVec4(y, w, z, x)
val ywzy: ByteVec4 get() = ByteVec4(y, w, z, y)
val ywzz: ByteVec4 get() = ByteVec4(y, w, z, z)
val ywzw: ByteVec4 get() = ByteVec4(y, w, z, w)
val ywwx: ByteVec4 get() = ByteVec4(y, w, w, x)
val ywwy: ByteVec4 get() = ByteVec4(y, w, w, y)
val ywwz: ByteVec4 get() = ByteVec4(y, w, w, z)
val ywww: ByteVec4 get() = ByteVec4(y, w, w, w)
val zxxx: ByteVec4 get() = ByteVec4(z, x, x, x)
val zxxy: ByteVec4 get() = ByteVec4(z, x, x, y)
val zxxz: ByteVec4 get() = ByteVec4(z, x, x, z)
val zxxw: ByteVec4 get() = ByteVec4(z, x, x, w)
val zxyx: ByteVec4 get() = ByteVec4(z, x, y, x)
val zxyy: ByteVec4 get() = ByteVec4(z, x, y, y)
val zxyz: ByteVec4 get() = ByteVec4(z, x, y, z)
val zxyw: ByteVec4 get() = ByteVec4(z, x, y, w)
val zxzx: ByteVec4 get() = ByteVec4(z, x, z, x)
val zxzy: ByteVec4 get() = ByteVec4(z, x, z, y)
val zxzz: ByteVec4 get() = ByteVec4(z, x, z, z)
val zxzw: ByteVec4 get() = ByteVec4(z, x, z, w)
val zxwx: ByteVec4 get() = ByteVec4(z, x, w, x)
val zxwy: ByteVec4 get() = ByteVec4(z, x, w, y)
val zxwz: ByteVec4 get() = ByteVec4(z, x, w, z)
val zxww: ByteVec4 get() = ByteVec4(z, x, w, w)
val zyxx: ByteVec4 get() = ByteVec4(z, y, x, x)
val zyxy: ByteVec4 get() = ByteVec4(z, y, x, y)
val zyxz: ByteVec4 get() = ByteVec4(z, y, x, z)
val zyxw: ByteVec4 get() = ByteVec4(z, y, x, w)
val zyyx: ByteVec4 get() = ByteVec4(z, y, y, x)
val zyyy: ByteVec4 get() = ByteVec4(z, y, y, y)
val zyyz: ByteVec4 get() = ByteVec4(z, y, y, z)
val zyyw: ByteVec4 get() = ByteVec4(z, y, y, w)
val zyzx: ByteVec4 get() = ByteVec4(z, y, z, x)
val zyzy: ByteVec4 get() = ByteVec4(z, y, z, y)
val zyzz: ByteVec4 get() = ByteVec4(z, y, z, z)
val zyzw: ByteVec4 get() = ByteVec4(z, y, z, w)
val zywx: ByteVec4 get() = ByteVec4(z, y, w, x)
val zywy: ByteVec4 get() = ByteVec4(z, y, w, y)
val zywz: ByteVec4 get() = ByteVec4(z, y, w, z)
val zyww: ByteVec4 get() = ByteVec4(z, y, w, w)
val zzxx: ByteVec4 get() = ByteVec4(z, z, x, x)
val zzxy: ByteVec4 get() = ByteVec4(z, z, x, y)
val zzxz: ByteVec4 get() = ByteVec4(z, z, x, z)
val zzxw: ByteVec4 get() = ByteVec4(z, z, x, w)
val zzyx: ByteVec4 get() = ByteVec4(z, z, y, x)
val zzyy: ByteVec4 get() = ByteVec4(z, z, y, y)
val zzyz: ByteVec4 get() = ByteVec4(z, z, y, z)
val zzyw: ByteVec4 get() = ByteVec4(z, z, y, w)
val zzzx: ByteVec4 get() = ByteVec4(z, z, z, x)
val zzzy: ByteVec4 get() = ByteVec4(z, z, z, y)
val zzzz: ByteVec4 get() = ByteVec4(z, z, z, z)
val zzzw: ByteVec4 get() = ByteVec4(z, z, z, w)
val zzwx: ByteVec4 get() = ByteVec4(z, z, w, x)
val zzwy: ByteVec4 get() = ByteVec4(z, z, w, y)
val zzwz: ByteVec4 get() = ByteVec4(z, z, w, z)
val zzww: ByteVec4 get() = ByteVec4(z, z, w, w)
val zwxx: ByteVec4 get() = ByteVec4(z, w, x, x)
val zwxy: ByteVec4 get() = ByteVec4(z, w, x, y)
val zwxz: ByteVec4 get() = ByteVec4(z, w, x, z)
val zwxw: ByteVec4 get() = ByteVec4(z, w, x, w)
val zwyx: ByteVec4 get() = ByteVec4(z, w, y, x)
val zwyy: ByteVec4 get() = ByteVec4(z, w, y, y)
val zwyz: ByteVec4 get() = ByteVec4(z, w, y, z)
val zwyw: ByteVec4 get() = ByteVec4(z, w, y, w)
val zwzx: ByteVec4 get() = ByteVec4(z, w, z, x)
val zwzy: ByteVec4 get() = ByteVec4(z, w, z, y)
val zwzz: ByteVec4 get() = ByteVec4(z, w, z, z)
val zwzw: ByteVec4 get() = ByteVec4(z, w, z, w)
val zwwx: ByteVec4 get() = ByteVec4(z, w, w, x)
val zwwy: ByteVec4 get() = ByteVec4(z, w, w, y)
val zwwz: ByteVec4 get() = ByteVec4(z, w, w, z)
val zwww: ByteVec4 get() = ByteVec4(z, w, w, w)
val wxxx: ByteVec4 get() = ByteVec4(w, x, x, x)
val wxxy: ByteVec4 get() = ByteVec4(w, x, x, y)
val wxxz: ByteVec4 get() = ByteVec4(w, x, x, z)
val wxxw: ByteVec4 get() = ByteVec4(w, x, x, w)
val wxyx: ByteVec4 get() = ByteVec4(w, x, y, x)
val wxyy: ByteVec4 get() = ByteVec4(w, x, y, y)
val wxyz: ByteVec4 get() = ByteVec4(w, x, y, z)
val wxyw: ByteVec4 get() = ByteVec4(w, x, y, w)
val wxzx: ByteVec4 get() = ByteVec4(w, x, z, x)
val wxzy: ByteVec4 get() = ByteVec4(w, x, z, y)
val wxzz: ByteVec4 get() = ByteVec4(w, x, z, z)
val wxzw: ByteVec4 get() = ByteVec4(w, x, z, w)
val wxwx: ByteVec4 get() = ByteVec4(w, x, w, x)
val wxwy: ByteVec4 get() = ByteVec4(w, x, w, y)
val wxwz: ByteVec4 get() = ByteVec4(w, x, w, z)
val wxww: ByteVec4 get() = ByteVec4(w, x, w, w)
val wyxx: ByteVec4 get() = ByteVec4(w, y, x, x)
val wyxy: ByteVec4 get() = ByteVec4(w, y, x, y)
val wyxz: ByteVec4 get() = ByteVec4(w, y, x, z)
val wyxw: ByteVec4 get() = ByteVec4(w, y, x, w)
val wyyx: ByteVec4 get() = ByteVec4(w, y, y, x)
val wyyy: ByteVec4 get() = ByteVec4(w, y, y, y)
val wyyz: ByteVec4 get() = ByteVec4(w, y, y, z)
val wyyw: ByteVec4 get() = ByteVec4(w, y, y, w)
val wyzx: ByteVec4 get() = ByteVec4(w, y, z, x)
val wyzy: ByteVec4 get() = ByteVec4(w, y, z, y)
val wyzz: ByteVec4 get() = ByteVec4(w, y, z, z)
val wyzw: ByteVec4 get() = ByteVec4(w, y, z, w)
val wywx: ByteVec4 get() = ByteVec4(w, y, w, x)
val wywy: ByteVec4 get() = ByteVec4(w, y, w, y)
val wywz: ByteVec4 get() = ByteVec4(w, y, w, z)
val wyww: ByteVec4 get() = ByteVec4(w, y, w, w)
val wzxx: ByteVec4 get() = ByteVec4(w, z, x, x)
val wzxy: ByteVec4 get() = ByteVec4(w, z, x, y)
val wzxz: ByteVec4 get() = ByteVec4(w, z, x, z)
val wzxw: ByteVec4 get() = ByteVec4(w, z, x, w)
val wzyx: ByteVec4 get() = ByteVec4(w, z, y, x)
val wzyy: ByteVec4 get() = ByteVec4(w, z, y, y)
val wzyz: ByteVec4 get() = ByteVec4(w, z, y, z)
val wzyw: ByteVec4 get() = ByteVec4(w, z, y, w)
val wzzx: ByteVec4 get() = ByteVec4(w, z, z, x)
val wzzy: ByteVec4 get() = ByteVec4(w, z, z, y)
val wzzz: ByteVec4 get() = ByteVec4(w, z, z, z)
val wzzw: ByteVec4 get() = ByteVec4(w, z, z, w)
val wzwx: ByteVec4 get() = ByteVec4(w, z, w, x)
val wzwy: ByteVec4 get() = ByteVec4(w, z, w, y)
val wzwz: ByteVec4 get() = ByteVec4(w, z, w, z)
val wzww: ByteVec4 get() = ByteVec4(w, z, w, w)
val wwxx: ByteVec4 get() = ByteVec4(w, w, x, x)
val wwxy: ByteVec4 get() = ByteVec4(w, w, x, y)
val wwxz: ByteVec4 get() = ByteVec4(w, w, x, z)
val wwxw: ByteVec4 get() = ByteVec4(w, w, x, w)
val wwyx: ByteVec4 get() = ByteVec4(w, w, y, x)
val wwyy: ByteVec4 get() = ByteVec4(w, w, y, y)
val wwyz: ByteVec4 get() = ByteVec4(w, w, y, z)
val wwyw: ByteVec4 get() = ByteVec4(w, w, y, w)
val wwzx: ByteVec4 get() = ByteVec4(w, w, z, x)
val wwzy: ByteVec4 get() = ByteVec4(w, w, z, y)
val wwzz: ByteVec4 get() = ByteVec4(w, w, z, z)
val wwzw: ByteVec4 get() = ByteVec4(w, w, z, w)
val wwwx: ByteVec4 get() = ByteVec4(w, w, w, x)
val wwwy: ByteVec4 get() = ByteVec4(w, w, w, y)
val wwwz: ByteVec4 get() = ByteVec4(w, w, w, z)
val wwww: ByteVec4 get() = ByteVec4(w, w, w, w)
}
val swizzle: Swizzle get() = Swizzle()
}
fun vecOf(x: Byte, y: Byte, z: Byte, w: Byte): ByteVec4 = ByteVec4(x, y, z, w)
operator fun Byte.plus(rhs: ByteVec4): IntVec4 = IntVec4(this + rhs.x, this + rhs.y, this + rhs.z, this + rhs.w)
operator fun Byte.minus(rhs: ByteVec4): IntVec4 = IntVec4(this - rhs.x, this - rhs.y, this - rhs.z, this - rhs.w)
operator fun Byte.times(rhs: ByteVec4): IntVec4 = IntVec4(this * rhs.x, this * rhs.y, this * rhs.z, this * rhs.w)
operator fun Byte.div(rhs: ByteVec4): IntVec4 = IntVec4(this / rhs.x, this / rhs.y, this / rhs.z, this / rhs.w)
operator fun Byte.rem(rhs: ByteVec4): IntVec4 = IntVec4(this % rhs.x, this % rhs.y, this % rhs.z, this % rhs.w)
| mit | 75cdb59a1d66fdbe0b5afc3a4b08ba36 | 62.844068 | 133 | 0.598466 | 3.052018 | false | false | false | false |
code-disaster/lwjgl3 | modules/lwjgl/vulkan/src/templates/kotlin/vulkan/VKBase.kt | 4 | 1164 | /*
* Copyright LWJGL. All rights reserved.
* License terms: https://www.lwjgl.org/license
*/
package vulkan
import org.lwjgl.generator.*
fun VK_DEFINE_HANDLE(name: String) = WrappedPointerType(name)
fun VK_DEFINE_NON_DISPATCHABLE_HANDLE(name: String) = typedef(uint64_t, name) // TODO: not a pointer, but implement nullability?
val VkBool32 = PrimitiveType("VkBool32", PrimitiveMapping.BOOLEAN4)
val VkDeviceAddress = typedef(uint64_t, "VkDeviceAddress")
val VkDeviceSize = typedef(uint64_t, "VkDeviceSize")
val VkFlags = typedef(uint32_t, "VkFlags")
val VkFlags64 = typedef(uint64_t, "VkFlags64")
val VkSampleMask = typedef(uint32_t, "VkSampleMask")
val PFN_vkVoidFunction = "PFN_vkVoidFunction".handle
val PFN_vkGetInstanceProcAddr = "PFN_vkGetInstanceProcAddr".handle
val VkRemoteAddressNV = "VkRemoteAddressNV".handle
// Metal interop types
val CAMetalLayer = "CAMetalLayer".handle
val MTLDevice_id = "MTLDevice_id".handle
val MTLCommandQueue_id = "MTLCommandQueue_id".handle
val MTLBuffer_id = "MTLBuffer_id".handle
val MTLTexture_id = "MTLTexture_id".handle
val MTLSharedEvent_id = "MTLSharedEvent_id".handle
val IOSurfaceRef = "IOSurfaceRef".handle | bsd-3-clause | 176380e3300a50a3213bdd084004f35c | 36.580645 | 128 | 0.777491 | 3.383721 | false | false | false | false |
google/android-fhir | engine/src/main/java/com/google/android/fhir/impl/FhirEngineImpl.kt | 1 | 7202 | /*
* Copyright 2022 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.fhir.impl
import android.content.Context
import com.google.android.fhir.DatastoreUtil
import com.google.android.fhir.FhirEngine
import com.google.android.fhir.LocalChange
import com.google.android.fhir.SyncDownloadContext
import com.google.android.fhir.db.Database
import com.google.android.fhir.db.impl.dao.LocalChangeToken
import com.google.android.fhir.db.impl.dao.toLocalChange
import com.google.android.fhir.db.impl.entities.SyncedResourceEntity
import com.google.android.fhir.logicalId
import com.google.android.fhir.search.Search
import com.google.android.fhir.search.count
import com.google.android.fhir.search.execute
import com.google.android.fhir.sync.ConflictResolver
import com.google.android.fhir.sync.Resolved
import com.google.android.fhir.toTimeZoneString
import java.time.OffsetDateTime
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.collect
import org.hl7.fhir.r4.model.Bundle
import org.hl7.fhir.r4.model.Resource
import org.hl7.fhir.r4.model.ResourceType
import timber.log.Timber
/** Implementation of [FhirEngine]. */
internal class FhirEngineImpl(private val database: Database, private val context: Context) :
FhirEngine {
override suspend fun create(vararg resource: Resource): List<String> {
return database.insert(*resource)
}
override suspend fun get(type: ResourceType, id: String): Resource {
return database.select(type, id)
}
override suspend fun update(vararg resource: Resource) {
database.update(*resource)
}
override suspend fun delete(type: ResourceType, id: String) {
database.delete(type, id)
}
override suspend fun <R : Resource> search(search: Search): List<R> {
return search.execute(database)
}
override suspend fun count(search: Search): Long {
return search.count(database)
}
override suspend fun getLastSyncTimeStamp(): OffsetDateTime? {
return DatastoreUtil(context).readLastSyncTimestamp()
}
override suspend fun clearDatabase() {
database.clearDatabase()
}
override suspend fun getLocalChange(type: ResourceType, id: String): LocalChange? {
return database.getLocalChange(type, id)?.toLocalChange()
}
override suspend fun purge(type: ResourceType, id: String, forcePurge: Boolean) {
database.purge(type, id, forcePurge)
}
override suspend fun syncDownload(
conflictResolver: ConflictResolver,
download: suspend (SyncDownloadContext) -> Flow<List<Resource>>
) {
download(
object : SyncDownloadContext {
override suspend fun getLatestTimestampFor(type: ResourceType) = database.lastUpdate(type)
}
)
.collect { resources ->
database.withTransaction {
val resolved =
resolveConflictingResources(
resources,
getConflictingResourceIds(resources),
conflictResolver
)
saveRemoteResourcesToDatabase(resources)
saveResolvedResourcesToDatabase(resolved)
}
}
}
private suspend fun saveResolvedResourcesToDatabase(resolved: List<Resource>?) {
resolved?.let {
database.deleteUpdates(it)
database.update(*it.toTypedArray())
}
}
private suspend fun saveRemoteResourcesToDatabase(resources: List<Resource>) {
val timeStamps =
resources.groupBy { it.resourceType }.entries.map {
SyncedResourceEntity(it.key, it.value.maxOf { it.meta.lastUpdated }.toTimeZoneString())
}
database.insertSyncedResources(timeStamps, resources)
}
private suspend fun resolveConflictingResources(
resources: List<Resource>,
conflictingResourceIds: Set<String>,
conflictResolver: ConflictResolver
) =
resources
.filter { conflictingResourceIds.contains(it.logicalId) }
.map { conflictResolver.resolve(database.select(it.resourceType, it.logicalId), it) }
.filterIsInstance<Resolved>()
.map { it.resolved }
.takeIf { it.isNotEmpty() }
private suspend fun getConflictingResourceIds(resources: List<Resource>) =
resources
.map { it.logicalId }
.toSet()
.intersect(database.getAllLocalChanges().map { it.localChange.resourceId }.toSet())
override suspend fun syncUpload(
upload: suspend (List<LocalChange>) -> Flow<Pair<LocalChangeToken, Resource>>
) {
val localChanges = database.getAllLocalChanges()
if (localChanges.isNotEmpty()) {
upload(localChanges.map { it.toLocalChange() }).collect {
database.deleteUpdates(it.first)
when (it.second) {
is Bundle -> updateVersionIdAndLastUpdated(it.second as Bundle)
else -> updateVersionIdAndLastUpdated(it.second)
}
}
}
}
private suspend fun updateVersionIdAndLastUpdated(bundle: Bundle) {
when (bundle.type) {
Bundle.BundleType.TRANSACTIONRESPONSE -> {
bundle.entry.forEach {
when {
it.hasResource() -> updateVersionIdAndLastUpdated(it.resource)
it.hasResponse() -> updateVersionIdAndLastUpdated(it.response)
}
}
}
else -> {
// Leave it for now.
Timber.i("Received request to update meta values for ${bundle.type}")
}
}
}
private suspend fun updateVersionIdAndLastUpdated(response: Bundle.BundleEntryResponseComponent) {
if (response.hasEtag() && response.hasLastModified() && response.hasLocation()) {
response.resourceIdAndType?.let { (id, type) ->
database.updateVersionIdAndLastUpdated(
id,
type,
response.etag,
response.lastModified.toInstant()
)
}
}
}
private suspend fun updateVersionIdAndLastUpdated(resource: Resource) {
if (resource.hasMeta() && resource.meta.hasVersionId() && resource.meta.hasLastUpdated()) {
database.updateVersionIdAndLastUpdated(
resource.id,
resource.resourceType,
resource.meta.versionId,
resource.meta.lastUpdated.toInstant()
)
}
}
/**
* May return a Pair of versionId and resource type extracted from the
* [Bundle.BundleEntryResponseComponent.location].
*
* [Bundle.BundleEntryResponseComponent.location] may be:
*
* 1. absolute path: `<server-path>/<resource-type>/<resource-id>/_history/<version>`
*
* 2. relative path: `<resource-type>/<resource-id>/_history/<version>`
*/
private val Bundle.BundleEntryResponseComponent.resourceIdAndType: Pair<String, ResourceType>?
get() =
location?.split("/")?.takeIf { it.size > 3 }?.let {
it[it.size - 3] to ResourceType.fromCode(it[it.size - 4])
}
}
| apache-2.0 | ffe2dd6e6566004519cc90e7859fb506 | 32.812207 | 100 | 0.703138 | 4.362205 | false | false | false | false |
mdanielwork/intellij-community | plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/impl/synthetic/DefaultConstructor.kt | 4 | 3948 | // Copyright 2000-2017 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.plugins.groovy.lang.psi.impl.synthetic
import com.intellij.psi.*
import com.intellij.psi.impl.PsiSuperMethodImplUtil.getHierarchicalMethodSignature
import com.intellij.psi.impl.light.LightElement
import com.intellij.psi.impl.light.LightModifierList
import com.intellij.psi.impl.light.LightParameter
import com.intellij.psi.impl.light.LightParameterListBuilder
import com.intellij.psi.javadoc.PsiDocComment
import com.intellij.psi.util.MethodSignatureBackedByPsiMethod
import com.intellij.util.IncorrectOperationException
import kotlin.LazyThreadSafetyMode.PUBLICATION
class DefaultConstructor(
private val myConstructedClass: PsiClass
) : LightElement(myConstructedClass.manager, myConstructedClass.language), PsiMethod {
override fun getNavigationElement(): PsiElement = myConstructedClass
override fun getName(): String = myConstructedClass.name!!
override fun getNameIdentifier(): PsiIdentifier? = null
override fun hasModifierProperty(name: String): Boolean = false
private val myModifierList by lazy(PUBLICATION) { LightModifierList(manager, language) }
override fun getModifierList(): PsiModifierList = myModifierList
private val myParameterList by lazy(PUBLICATION) {
LightParameterListBuilder(manager, language).apply {
if (myConstructedClass.hasModifierProperty(PsiModifier.STATIC)) return@apply
val enclosingClass = myConstructedClass.containingClass ?: return@apply
// at this point myConstructedClass is an inner class
// and it will have single parameter of enclosing class type
val factory = JVMElementFactories.requireFactory(language, project)
val type = factory.createType(enclosingClass)
val parameter = LightParameter("enclosing", type, this@DefaultConstructor)
addParameter(parameter)
}
}
override fun getParameterList(): PsiParameterList = myParameterList
override fun getContainingClass(): PsiClass? = myConstructedClass
override fun getReturnType(): PsiType? = null
override fun getReturnTypeElement(): PsiTypeElement? = null
override fun getTypeParameterList(): PsiTypeParameterList? = null
override fun getTypeParameters(): Array<PsiTypeParameter> = PsiTypeParameter.EMPTY_ARRAY
private val myThrowsList by lazy(PUBLICATION) { LightReferenceList(manager) }
override fun getThrowsList(): PsiReferenceList = myThrowsList
override fun hasTypeParameters(): Boolean = false
override fun getBody(): PsiCodeBlock? = null
override fun isConstructor(): Boolean = true
override fun isVarArgs(): Boolean = false
override fun getSignature(substitutor: PsiSubstitutor): MethodSignatureBackedByPsiMethod = MethodSignatureBackedByPsiMethod.create(this, substitutor)
override fun getHierarchicalMethodSignature(): HierarchicalMethodSignature = getHierarchicalMethodSignature(this)
override fun isDeprecated(): Boolean = myConstructedClass.isDeprecated
override fun toString(): String = "Default constructor for ${myConstructedClass.name}"
// --
override fun findSuperMethods(): Array<PsiMethod> = PsiMethod.EMPTY_ARRAY
override fun findSuperMethods(checkAccess: Boolean): Array<PsiMethod> = PsiMethod.EMPTY_ARRAY
override fun findSuperMethods(parentClass: PsiClass?): Array<PsiMethod> = PsiMethod.EMPTY_ARRAY
override fun findSuperMethodSignaturesIncludingStatic(checkAccess: Boolean): List<MethodSignatureBackedByPsiMethod> = emptyList<MethodSignatureBackedByPsiMethod>()
override fun findDeepestSuperMethods(): Array<PsiMethod> = PsiMethod.EMPTY_ARRAY
override fun getDocComment(): PsiDocComment? = null
@Suppress("OverridingDeprecatedMember")
override fun findDeepestSuperMethod(): PsiMethod? = null
override fun setName(name: String): PsiElement = throw IncorrectOperationException("setName() isn't supported")
} | apache-2.0 | c96740f5679863d040ff3c0e6ce747ef | 41.010638 | 165 | 0.800405 | 5.460581 | false | false | false | false |
mdanielwork/intellij-community | platform/platform-impl/src/com/intellij/internal/heatmap/actions/ShowHeatMapAction.kt | 1 | 21489 | // Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.internal.heatmap.actions
import com.intellij.internal.heatmap.fus.*
import com.intellij.internal.heatmap.settings.ClickMapSettingsDialog
import com.intellij.internal.statistic.beans.ConvertUsagesUtil
import com.intellij.openapi.actionSystem.*
import com.intellij.openapi.actionSystem.ex.ActionButtonLook
import com.intellij.openapi.actionSystem.ex.CustomComponentAction
import com.intellij.openapi.actionSystem.impl.ActionButton
import com.intellij.openapi.actionSystem.impl.ActionMenu
import com.intellij.openapi.actionSystem.impl.ActionMenuItem
import com.intellij.openapi.actionSystem.impl.ActionToolbarImpl
import com.intellij.openapi.application.ApplicationInfo
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.progress.Task
import com.intellij.openapi.project.DumbAware
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.JBPopupMenu
import com.intellij.openapi.util.text.StringUtil
import com.intellij.openapi.wm.ex.WindowManagerEx
import com.intellij.openapi.wm.impl.IdeFrameImpl
import com.intellij.ui.JBColor
import com.intellij.ui.PopupMenuListenerAdapter
import com.intellij.util.PlatformUtils
import com.intellij.util.ui.UIUtil
import java.awt.Color
import java.awt.Graphics
import java.awt.Graphics2D
import java.awt.event.MouseAdapter
import java.awt.event.MouseEvent
import java.text.DecimalFormat
import java.text.SimpleDateFormat
import java.util.*
import javax.swing.JComponent
import javax.swing.MenuSelectionManager
import javax.swing.event.PopupMenuEvent
private val BUTTON_EMPTY_STATS_COLOR: Color = JBColor.GRAY.brighter()
val LOG = Logger.getInstance(ShowHeatMapAction::class.java)
class ShowHeatMapAction : AnAction(), DumbAware {
companion object MetricsCache {
private val toolbarsAllMetrics = mutableListOf<MetricEntity>()
private val mainMenuAllMetrics = mutableListOf<MetricEntity>()
private val toolbarsMetrics = hashMapOf<String, List<MetricEntity>>()
private val mainMenuMetrics = hashMapOf<String, List<MetricEntity>>()
private val toolbarsTotalMetricsUsers = hashMapOf<String, Int>()
private val mainMenuTotalMetricsUsers = hashMapOf<String, Int>()
//settings
private var myEndStartDate: Pair<Date, Date>? = null
private var myShareType: ShareType? = null
private var myServiceUrl: String? = null
private val myBuilds = mutableListOf<String>()
private var myIncludeEap = false
private var myColor = Color.RED
private val ourIdeBuildInfos = mutableListOf<ProductBuildInfo>()
fun getOurIdeBuildInfos(): List<ProductBuildInfo> = ourIdeBuildInfos
fun getSelectedServiceUrl(): String = (myServiceUrl ?: DEFAULT_SERVICE_URLS.first()).trimEnd('/')
}
@Volatile
private var myToolBarProgress = false
@Volatile
private var myMainMenuProgress = false
private val ourBlackList = HashMap<String, String>()
private val PRODUCT_CODE = getProductCode()
init {
ourBlackList["com.intellij.ide.ReopenProjectAction"] = "Reopen Project"
}
override fun update(e: AnActionEvent) {
e.presentation.isEnabledAndVisible = isInProgress().not()
super.update(e)
}
private fun isInProgress(): Boolean = myToolBarProgress || myMainMenuProgress
override fun actionPerformed(e: AnActionEvent) {
val project = e.project ?: return
if (ourIdeBuildInfos.isEmpty()) ourIdeBuildInfos.addAll(getProductBuildInfos(PRODUCT_CODE))
askSettingsAndPaintUI(project)
}
private fun askSettingsAndPaintUI(project: Project) {
val frame = WindowManagerEx.getInstance().getIdeFrame(project)
if (frame == null) return
val askSettings = ClickMapSettingsDialog(project)
val ok = askSettings.showAndGet()
if (ok.not()) return
val serviceUrl = askSettings.getServiceUrl()
if (serviceUrl == null) {
showWarnNotification("Statistics fetch failed", "Statistic Service url is not specified", project)
return
}
val startEndDate = askSettings.getStartEndDate()
val shareType = askSettings.getShareType()
val ideBuilds = askSettings.getBuilds()
val isIncludeEap = askSettings.getIncludeEap()
if (settingsChanged(startEndDate, shareType, serviceUrl, ideBuilds, isIncludeEap)) {
clearCache()
}
myServiceUrl = serviceUrl
myBuilds.clear()
myBuilds.addAll(ideBuilds)
myEndStartDate = startEndDate
myIncludeEap = isIncludeEap
myShareType = shareType
myColor = askSettings.getColor()
if (toolbarsAllMetrics.isNotEmpty()) {
paintVisibleToolBars(project, frame.component, shareType, toolbarsAllMetrics)
}
else {
val accessToken = askSettings.getAccessToken()
if (StringUtil.isEmpty(accessToken)) {
showWarnNotification("Statistics fetch failed", "access token is not specified", project)
return
}
val startDate = getDateString(startEndDate.first)
val endDate = getDateString(startEndDate.second)
ProgressManager.getInstance().run(object : Task.Backgroundable(project, "Fetching statistics for toolbar clicks", false) {
override fun run(indicator: ProgressIndicator) {
myToolBarProgress = true
val toolBarAllStats = fetchStatistics(startDate, endDate, PRODUCT_CODE, myBuilds, arrayListOf(TOOLBAR_GROUP), accessToken!!)
LOG.debug("\nGot Tool bar clicks stat: ${toolBarAllStats.size} rows:")
toolBarAllStats.forEach {
LOG.debug("Entity: $it")
}
if (toolBarAllStats.isNotEmpty()) toolbarsAllMetrics.addAll(toolBarAllStats)
paintVisibleToolBars(project, frame.component, shareType, toolBarAllStats)
myToolBarProgress = false
}
})
}
if (frame is IdeFrameImpl) {
if (mainMenuAllMetrics.isNotEmpty()) {
groupStatsByMenus(frame, mainMenuAllMetrics)
addMenusPopupListener(frame, shareType)
}
else {
val accessToken = askSettings.getAccessToken()
if (StringUtil.isEmpty(accessToken)) {
showWarnNotification("Statistics fetch failed", "access token is not specified", project)
return
}
ProgressManager.getInstance().run(object : Task.Backgroundable(project, "Fetching statistics for Main menu", false) {
override fun run(indicator: ProgressIndicator) {
myMainMenuProgress = true
val startDate = getDateString(startEndDate.first)
val endDate = getDateString(startEndDate.second)
val menuAllStats = fetchStatistics(startDate, endDate, PRODUCT_CODE, myBuilds, arrayListOf(MAIN_MENU_GROUP), accessToken!!)
if (menuAllStats.isNotEmpty()) {
mainMenuAllMetrics.addAll(menuAllStats)
groupStatsByMenus(frame, mainMenuAllMetrics)
addMenusPopupListener(frame, shareType)
}
myMainMenuProgress = false
}
})
}
}
}
private fun groupStatsByMenus(frame: IdeFrameImpl, mainMenuAllStats: List<MetricEntity>) {
val menus = frame.rootPane.jMenuBar.components
for (menu in menus) {
if (menu is ActionMenu) {
val menuName = menu.text
if (mainMenuMetrics[menuName] == null) {
val menuStats = filterByMenuName(mainMenuAllStats, menuName)
if (menuStats.isNotEmpty()) mainMenuMetrics[menuName] = menuStats
var menuAllUsers = 0
menuStats.forEach { menuAllUsers += it.users }
if (menuAllUsers > 0) mainMenuTotalMetricsUsers[menuName] = menuAllUsers
}
}
}
}
private fun paintActionMenu(menu: ActionMenu, allUsers: Int, level: Float) {
val menuName = menu.text
val menuAllUsers = mainMenuTotalMetricsUsers[menuName]
menu.component.background = tuneColor(myColor, level)
menu.addMouseListener(object : MouseAdapter() {
override fun mouseEntered(e: MouseEvent?) {
ActionMenu.showDescriptionInStatusBar(true, menu.component, "$menuName: $menuAllUsers usages of total $allUsers")
}
override fun mouseExited(e: MouseEvent?) {
ActionMenu.showDescriptionInStatusBar(true, menu.component, "")
}
})
}
private fun addMenusPopupListener(frame: IdeFrameImpl, shareType: ShareType) {
val menus = frame.rootPane.jMenuBar.components
var mainMenuAllUsers = 0
mainMenuTotalMetricsUsers.values.forEach { mainMenuAllUsers += it }
for (menu in menus) {
if (menu is ActionMenu) {
paintMenuAndAddPopupListener(mutableListOf(menu.text), menu, mainMenuAllUsers, shareType)
}
}
}
private fun paintMenuAndAddPopupListener(menuGroupNames: MutableList<String>, menu: ActionMenu, menuAllUsers: Int, shareType: ShareType) {
val level = if (menuGroupNames.size == 1) {
val subMenuAllUsers = mainMenuTotalMetricsUsers[menuGroupNames[0]] ?: 0
subMenuAllUsers / menuAllUsers.toFloat()
}
else {
val subItemsStas: List<MetricEntity> = getMenuSubItemsStat(menuGroupNames)
val maxUsers = subItemsStas.maxBy { m -> m.users }
if (maxUsers != null) getLevel(shareType, maxUsers, MetricGroup.MAIN_MENU) else 0.001f
}
paintActionMenu(menu, menuAllUsers, level)
val popupMenu = menu.popupMenu as? JBPopupMenu ?: return
popupMenu.addPopupMenuListener(object : PopupMenuListenerAdapter() {
override fun popupMenuWillBecomeVisible(e: PopupMenuEvent) {
val source = e.source as? JBPopupMenu ?: return
val menuStats = mainMenuMetrics[menuGroupNames[0]] ?: return
for (c in source.components) {
if (c is ActionMenuItem) {
paintMenuItem(c, menuGroupNames, menuStats, shareType)
}
else if (c is ActionMenu) {
val newMenuGroup = menuGroupNames.toMutableList()
newMenuGroup.add(newMenuGroup.lastIndex + 1, c.text)
paintMenuAndAddPopupListener(newMenuGroup, c, menuAllUsers, shareType)
}
}
}
})
}
private fun getMenuSubItemsStat(menuGroupNames: MutableList<String>): List<MetricEntity> {
val menuStat = mainMenuMetrics[menuGroupNames[0]] ?: emptyList()
val pathPrefix = convertMenuItemsToKey(menuGroupNames)
val result = mutableListOf<MetricEntity>()
menuStat.forEach { if (it.id.startsWith(pathPrefix)) result.add(it) }
return result
}
private fun paintMenuItem(menuItem: ActionMenuItem, menuGroupNames: List<String>, menuStats: List<MetricEntity>, shareType: ShareType) {
val pathPrefix = convertMenuItemsToKey(menuGroupNames)
val metricId = pathPrefix + MENU_ITEM_SEPARATOR + menuItem.text
val menuItemMetric: MetricEntity? = findMetric(menuStats, metricId)
if (menuItemMetric != null) {
val color = calcColorForMetric(shareType, menuItemMetric, MetricGroup.MAIN_MENU)
menuItem.isOpaque = true
menuItem.text = menuItem.text + " (${menuItemMetric.users} / ${getMetricPlaceTotalUsersCache(menuItemMetric, MetricGroup.MAIN_MENU)})"
menuItem.component.background = color
}
menuItem.addMouseListener(object : MouseAdapter() {
override fun mouseEntered(e: MouseEvent) {
//adds text to status bar and searching metrics if it was not found (using the path from MenuSelectionManager)
val actionMenuItem = e.source
if (actionMenuItem is ActionMenuItem) {
val placeText = menuGroupNames.first()
val action = actionMenuItem.anAction
if (menuItemMetric != null) {
val textWithStat = getTextWithStat(menuItemMetric, shareType,
getMetricPlaceTotalUsersCache(menuItemMetric, MetricGroup.MAIN_MENU), placeText)
val actionText = StringUtil.notNullize(menuItem.anAction.templatePresentation.text)
ActionMenu.showDescriptionInStatusBar(true, menuItem, "$actionText: $textWithStat")
}
else {
val pathStr = getPathFromMenuSelectionManager(action)
if (pathStr != null) {
val metric = findMetric(menuStats, pathStr)
if (metric != null) {
actionMenuItem.isOpaque = true
actionMenuItem.component.background = calcColorForMetric(shareType, metric, MetricGroup.MAIN_MENU)
val textWithStat = getTextWithStat(metric, shareType, getMetricPlaceTotalUsersCache(metric, MetricGroup.MAIN_MENU),
placeText)
val actionText = StringUtil.notNullize(menuItem.anAction.templatePresentation.text)
ActionMenu.showDescriptionInStatusBar(true, menuItem, "$actionText: $textWithStat")
}
}
}
}
}
override fun mouseExited(e: MouseEvent?) {
ActionMenu.showDescriptionInStatusBar(true, menuItem, "")
}
})
}
private fun getPathFromMenuSelectionManager(action: AnAction): String? {
val groups = MenuSelectionManager.defaultManager().selectedPath.filterIsInstance<ActionMenu>().map { o -> o.text }.toMutableList()
if (groups.size > 0) {
val text = getActionText(action)
groups.add(text)
return convertMenuItemsToKey(groups)
}
return null
}
private fun convertMenuItemsToKey(menuItems: List<String>): String {
return menuItems.joinToString(MENU_ITEM_SEPARATOR)
}
private fun getActionText(action: AnAction): String {
return ourBlackList[action.javaClass.name] ?: action.templatePresentation.text
}
private fun settingsChanged(startEndDate: Pair<Date, Date>,
shareType: ShareType,
currentServiceUrl: String,
ideBuilds: List<String>,
includeEap: Boolean): Boolean {
if (currentServiceUrl != myServiceUrl) return true
if (includeEap != myIncludeEap) return true
if (ideBuilds.size != myBuilds.size) return true
for (build in ideBuilds) {
if (!myBuilds.contains(build)) return true
}
val prevStartEndDate = myEndStartDate
if (prevStartEndDate != null) {
if (!isSameDay(prevStartEndDate.first, startEndDate.first) || !isSameDay(prevStartEndDate.second, startEndDate.second)) {
return true
}
}
val prevShareType = myShareType
if (prevShareType != null && prevShareType != shareType) {
return true
}
return false
}
private fun isSameDay(date1: Date, date2: Date): Boolean {
val c1 = Calendar.getInstance()
val c2 = Calendar.getInstance()
c1.time = date1
c2.time = date2
return c1.get(Calendar.YEAR) == c2.get(Calendar.YEAR) && c1.get(Calendar.DAY_OF_YEAR) == c2.get(Calendar.DAY_OF_YEAR)
}
private fun paintVisibleToolBars(project: Project, component: JComponent, shareType: ShareType, toolBarStats: List<MetricEntity>) {
if (component is ActionToolbarImpl) paintToolBarButtons(component, shareType, toolBarStats)
for (c in component.components) {
when (c) {
is ActionToolbarImpl -> paintToolBarButtons(c, shareType, toolBarStats)
is JComponent -> paintVisibleToolBars(project, c, shareType, toolBarStats)
else -> {
LOG.debug("Unknown component: ${c.name}")
}
}
}
}
private fun paintToolBarButtons(toolbar: ActionToolbarImpl, shareType: ShareType, toolBarAllStats: List<MetricEntity>) {
val place = ConvertUsagesUtil.escapeDescriptorName(toolbar.place).replace(' ', '.')
val toolBarStat = toolbarsMetrics[place] ?: filterByPlaceToolbar(toolBarAllStats, place)
var toolbarAllUsers = 0
toolBarStat.forEach { toolbarAllUsers += it.users }
if (toolBarStat.isNotEmpty()) toolbarsMetrics[place] = toolBarStat
if (toolbarAllUsers > 0) toolbarsTotalMetricsUsers[place] = toolbarAllUsers
for (button in toolbar.components) {
val action = (button as? ActionButton)?.action
?: UIUtil.getClientProperty(button, CustomComponentAction.ACTION_KEY) ?: continue
val id = getActionId(action)
val buttonMetric = findMetric(toolBarStat, "$id@$place")
val buttonColor = if (buttonMetric != null) calcColorForMetric(shareType, buttonMetric, MetricGroup.TOOLBAR)
else BUTTON_EMPTY_STATS_COLOR
val textWithStats = if (buttonMetric != null) getTextWithStat(buttonMetric, shareType, toolbarAllUsers, place) else ""
val tooltipText = StringUtil.notNullize(action.templatePresentation.text) + textWithStats
if (button is ActionButton) {
(button as JComponent).toolTipText = tooltipText
button.setLook(createButtonLook(buttonColor))
}
else if (button is JComponent) {
button.toolTipText = tooltipText
button.isOpaque = true
button.background = buttonColor
}
LOG.debug("Place: $place action id: [$id]")
}
}
private fun getTextWithStat(buttonMetric: MetricEntity, shareType: ShareType, placeAllUsers: Int, place: String): String {
val totalUsers = if (shareType == ShareType.BY_GROUP) buttonMetric.sampleSize else placeAllUsers
return "\nClicks: Unique:${buttonMetric.users} / Avg:${DecimalFormat("####.#").format(
buttonMetric.usagesPerUser)} / ${place.capitalize()} total:$totalUsers"
}
private fun clearCache() {
toolbarsAllMetrics.clear()
toolbarsMetrics.clear()
mainMenuAllMetrics.clear()
mainMenuMetrics.clear()
toolbarsTotalMetricsUsers.clear()
mainMenuTotalMetricsUsers.clear()
}
private fun getActionId(action: AnAction): String {
return ActionManager.getInstance().getId(action) ?: if (action is ActionWithDelegate<*>) {
(action as ActionWithDelegate<*>).presentableName
}
else {
action.javaClass.name
}
}
private fun getDateString(date: Date): String = SimpleDateFormat(DATE_PATTERN).format(date)
private fun findMetric(list: List<MetricEntity>, key: String): MetricEntity? {
val metricId = ConvertUsagesUtil.escapeDescriptorName(key)
list.forEach { if (it.id == metricId) return it }
return null
}
private fun createButtonLook(color: Color): ActionButtonLook {
return object : ActionButtonLook() {
override fun paintBorder(g: Graphics, c: JComponent, state: Int) {
g.drawLine(c.width - 1, 0, c.width - 1, c.height)
}
override fun paintBackground(g: Graphics, component: JComponent, state: Int) {
if (state == ActionButtonComponent.PUSHED) {
g.color = component.background.brighter()
(g as Graphics2D).fill(g.getClip())
}
else {
g.color = color
(g as Graphics2D).fill(g.getClip())
}
}
}
}
private fun getMetricPlaceTotalUsersCache(metricEntity: MetricEntity, group: MetricGroup): Int {
return when (group) {
MetricGroup.TOOLBAR -> toolbarsTotalMetricsUsers[getToolBarButtonPlace(metricEntity)] ?: -1
MetricGroup.MAIN_MENU -> mainMenuTotalMetricsUsers[getMenuName(metricEntity)] ?: -1
}
}
private fun calcColorForMetric(shareType: ShareType, metricEntity: MetricEntity, group: MetricGroup): Color {
val level = getLevel(shareType, metricEntity, group)
return tuneColor(myColor, level)
}
fun getLevel(shareType: ShareType, metricEntity: MetricEntity, group: MetricGroup): Float {
return if (shareType == ShareType.BY_GROUP) {
Math.max(metricEntity.share, 0.0001f) / 100.0f
}
else {
val toolbarUsers = getMetricPlaceTotalUsersCache(metricEntity, group)
if (toolbarUsers != -1) metricEntity.users / toolbarUsers.toFloat() else Math.max(metricEntity.share, 0.0001f) / 100.0f
}
}
private fun tuneColor(default: Color, level: Float): Color {
val r = default.red
val g = default.green
val b = default.blue
val hsb = FloatArray(3)
Color.RGBtoHSB(r, g, b, hsb)
hsb[1] *= level
val hsbBkg = FloatArray(3)
val background = UIUtil.getLabelBackground()
Color.RGBtoHSB(background.red, background.green, background.blue, hsbBkg)
return JBColor.getHSBColor(hsb[0], hsb[1], hsbBkg[2])
}
private fun getProductCode(): String {
val code = ApplicationInfo.getInstance().build.productCode
return if (StringUtil.isNotEmpty(code)) code else getProductCodeFromPlatformPrefix()
}
private fun getProductCodeFromPlatformPrefix(): String {
return when {
PlatformUtils.isGoIde() -> "GO"
PlatformUtils.isRider() -> "RD"
else -> ""
}
}
}
enum class ShareType {
BY_PLACE, BY_GROUP
}
private const val MENU_ITEM_SEPARATOR = " -> "
private const val MAIN_MENU_GROUP = "statistics.actions.main.menu"
private const val TOOLBAR_GROUP = "statistics.ui.toolbar.clicks"
private const val DATE_PATTERN = "YYYY-MM-dd"
enum class MetricGroup(val groupId: String) {
TOOLBAR(TOOLBAR_GROUP), MAIN_MENU(MAIN_MENU_GROUP)
}
data class MetricEntity(val id: String,
val sampleSize: Int,
val groupSize: Int,
val users: Int,
val usages: Int,
val usagesPerUser: Float,
val share: Float)
data class ProductBuildInfo(val code: String, val type: String, val version: String, val majorVersion: String, val build: String) {
fun isEap(): Boolean = type.equals("eap", true)
} | apache-2.0 | 5cb4dc671c80cefa2bc2593c5a65e00c | 39.700758 | 140 | 0.696915 | 4.66645 | false | false | false | false |
dhis2/dhis2-android-sdk | core/src/main/java/org/hisp/dhis/android/core/program/programindicatorengine/internal/ProgramIndicatorSQLUtils.kt | 1 | 9630 | /*
* 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.program.programindicatorengine.internal
import org.hisp.dhis.android.core.common.AnalyticsType
import org.hisp.dhis.android.core.common.ValueType
import org.hisp.dhis.android.core.enrollment.EnrollmentTableInfo
import org.hisp.dhis.android.core.event.EventTableInfo
import org.hisp.dhis.android.core.parser.internal.service.dataitem.DimensionalItemId
import org.hisp.dhis.android.core.parser.internal.service.dataitem.DimensionalItemType
import org.hisp.dhis.android.core.program.ProgramIndicator
import org.hisp.dhis.android.core.trackedentity.TrackedEntityAttributeValueTableInfo
import org.hisp.dhis.android.core.trackedentity.TrackedEntityDataValueTableInfo
@Suppress("TooManyFunctions")
internal object ProgramIndicatorSQLUtils {
const val event = "eventAlias"
const val enrollment = "enrollmentAlias"
fun getEventColumnForEnrollmentWhereClause(column: String, programStageId: String? = null): String {
return "(SELECT $column FROM ${EventTableInfo.TABLE_INFO.name()} " +
"WHERE ${EventTableInfo.Columns.ENROLLMENT} = $enrollment.${EnrollmentTableInfo.Columns.UID} " +
"AND $column IS NOT NULL " +
(
programStageId?.let {
"AND ${EventTableInfo.Columns.PROGRAM_STAGE} = '$it' "
} ?: ""
) +
"ORDER BY ${EventTableInfo.Columns.EVENT_DATE} DESC LIMIT 1)"
}
fun getExistsEventForEnrollmentWhere(programStageUid: String, whereClause: String): String {
return "EXISTS(SELECT 1 FROM ${EventTableInfo.TABLE_INFO.name()} " +
"WHERE ${EventTableInfo.Columns.ENROLLMENT} = $enrollment.${EnrollmentTableInfo.Columns.UID} " +
"AND ${EventTableInfo.Columns.PROGRAM_STAGE} = '$programStageUid' " +
"AND (${EventTableInfo.Columns.DELETED} IS NULL OR ${EventTableInfo.Columns.DELETED} = 0)" +
"AND $whereClause)"
}
fun getEnrollmentColumnForEventWhereClause(column: String): String {
return "(SELECT $column " +
"FROM ${EnrollmentTableInfo.TABLE_INFO.name()} " +
"WHERE ${EnrollmentTableInfo.Columns.UID} = $event.${EventTableInfo.Columns.ENROLLMENT}" +
")"
}
fun getTrackerDataValueWhereClause(
column: String,
programStageUid: String,
dataElementUid: String,
programIndicator: ProgramIndicator
): String {
return "(SELECT $column " +
"FROM ${TrackedEntityDataValueTableInfo.TABLE_INFO.name()} " +
"INNER JOIN ${EventTableInfo.TABLE_INFO.name()} " +
"ON ${TrackedEntityDataValueTableInfo.Columns.EVENT} = ${EventTableInfo.Columns.UID} " +
"WHERE ${TrackedEntityDataValueTableInfo.Columns.DATA_ELEMENT} = '$dataElementUid' " +
"AND ${EventTableInfo.Columns.PROGRAM_STAGE} = '$programStageUid' " +
"AND ${getDataValueEventWhereClause(programIndicator)} " +
"AND ${TrackedEntityDataValueTableInfo.Columns.VALUE} IS NOT NULL " +
"ORDER BY ${EventTableInfo.Columns.EVENT_DATE} DESC LIMIT 1" +
")"
}
fun getAttributeWhereClause(
column: String,
attributeUid: String,
programIndicator: ProgramIndicator
): String {
return "(SELECT $column " +
"FROM ${TrackedEntityAttributeValueTableInfo.TABLE_INFO.name()} " +
"WHERE ${TrackedEntityAttributeValueTableInfo.Columns.TRACKED_ENTITY_ATTRIBUTE} = '$attributeUid' " +
"AND ${getAttributeValueTEIWhereClause(programIndicator)} " +
")"
}
fun getDataValueEventWhereClause(programIndicator: ProgramIndicator): String {
return when (programIndicator.analyticsType()) {
AnalyticsType.EVENT ->
"${EventTableInfo.TABLE_INFO.name()}.${EventTableInfo.Columns.UID} = " +
"$event.${EventTableInfo.Columns.UID}"
AnalyticsType.ENROLLMENT, null ->
"${EventTableInfo.TABLE_INFO.name()}.${EventTableInfo.Columns.ENROLLMENT} = " +
"$enrollment.${EventTableInfo.Columns.UID}"
}
}
private fun getAttributeValueTEIWhereClause(programIndicator: ProgramIndicator): String {
val enrollmentSelector = getEnrollmentWhereClause(programIndicator)
return "${TrackedEntityAttributeValueTableInfo.Columns.TRACKED_ENTITY_INSTANCE} IN (" +
"SELECT ${EnrollmentTableInfo.Columns.TRACKED_ENTITY_INSTANCE} " +
"FROM ${EnrollmentTableInfo.TABLE_INFO.name()} " +
"WHERE ${EnrollmentTableInfo.Columns.UID} = $enrollmentSelector " +
")"
}
fun getEnrollmentWhereClause(programIndicator: ProgramIndicator): String {
return when (programIndicator.analyticsType()) {
AnalyticsType.EVENT -> "$event.${EventTableInfo.Columns.ENROLLMENT}"
AnalyticsType.ENROLLMENT, null -> "$enrollment.${EnrollmentTableInfo.Columns.UID}"
}
}
fun getColumnValueCast(
column: String,
valueType: ValueType?
): String {
return when {
valueType?.isNumeric == true ->
"CAST($column AS NUMERIC)"
valueType?.isBoolean == true ->
"CASE WHEN $column = 'true' THEN 1 ELSE 0 END"
else ->
column
}
}
fun getDefaultValue(
valueType: ValueType?
): String {
return if (valueType?.isNumeric == true || valueType?.isBoolean == true)
"CAST(0 AS NUMERIC)"
else
"''"
}
fun valueCountExpression(
itemIds: Set<DimensionalItemId>,
programIndicator: ProgramIndicator,
conditionalValueExpression: String? = null
): String {
val stageElementItems = itemIds.filter {
it.dimensionalItemType() == DimensionalItemType.TRACKED_ENTITY_DATA_VALUE
}
val attributeItems = itemIds.filter {
it.dimensionalItemType() == DimensionalItemType.TRACKED_ENTITY_ATTRIBUTE
}
val stageElementsSql = if (!stageElementItems.isNullOrEmpty()) {
val stageElementWhereClause = stageElementItems.joinToString(" OR ") {
"(${EventTableInfo.Columns.PROGRAM_STAGE} = '${it.id0()}' " +
"AND " +
"${TrackedEntityDataValueTableInfo.Columns.DATA_ELEMENT} = '${it.id1()}')"
}
"SELECT COUNT(*) " +
"FROM ${TrackedEntityDataValueTableInfo.TABLE_INFO.name()} " +
"INNER JOIN ${EventTableInfo.TABLE_INFO.name()} " +
"ON ${TrackedEntityDataValueTableInfo.Columns.EVENT} = ${EventTableInfo.Columns.UID} " +
"WHERE ($stageElementWhereClause) " +
"AND ${getDataValueEventWhereClause(programIndicator)} " +
"AND ${TrackedEntityDataValueTableInfo.Columns.VALUE} IS NOT NULL " +
(
conditionalValueExpression?.let {
"AND CAST(${TrackedEntityDataValueTableInfo.Columns.VALUE} AS NUMERIC) $it"
} ?: ""
)
} else {
"0"
}
val attributesSql = if (!attributeItems.isNullOrEmpty()) {
val attributesWhereClause = "${TrackedEntityAttributeValueTableInfo.Columns.TRACKED_ENTITY_ATTRIBUTE} IN " +
"(${attributeItems.joinToString(",") { "'${it.id0()}'" }})"
"SELECT COUNT(*) " +
"FROM ${TrackedEntityAttributeValueTableInfo.TABLE_INFO.name()} " +
"WHERE $attributesWhereClause " +
"AND ${getAttributeValueTEIWhereClause(programIndicator)} " +
(
conditionalValueExpression?.let {
"AND CAST(${TrackedEntityAttributeValueTableInfo.Columns.VALUE} AS NUMERIC) $it"
} ?: ""
)
} else {
"0"
}
return "(($stageElementsSql) + ($attributesSql))"
}
}
| bsd-3-clause | 28e8dade4c4e9297a12e15414a2b71f6 | 45.521739 | 120 | 0.641537 | 5.063091 | false | false | false | false |
dahlstrom-g/intellij-community | plugins/kotlin/frontend-independent/src/org/jetbrains/kotlin/idea/search/ideaExtensions/KotlinTargetElementEvaluator.kt | 8 | 3902 | // 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.search.ideaExtensions
import com.intellij.codeInsight.JavaTargetElementEvaluator
import com.intellij.codeInsight.TargetElementEvaluatorEx
import com.intellij.codeInsight.TargetElementUtil
import com.intellij.codeInsight.TargetElementUtilExtender
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
import com.intellij.psi.PsiReference
import com.intellij.util.BitUtil
import org.jetbrains.kotlin.idea.references.KtDestructuringDeclarationReference
import org.jetbrains.kotlin.idea.references.KtSimpleNameReference
import org.jetbrains.kotlin.idea.references.mainReference
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.*
abstract class KotlinTargetElementEvaluator : TargetElementEvaluatorEx, TargetElementUtilExtender {
companion object {
const val DO_NOT_UNWRAP_LABELED_EXPRESSION = 0x100
const val BYPASS_IMPORT_ALIAS = 0x200
}
// Place caret after the open curly brace in lambda for generated 'it'
abstract fun findLambdaOpenLBraceForGeneratedIt(ref: PsiReference): PsiElement?
// Navigate to receiver element for this in extension declaration
abstract fun findReceiverForThisInExtensionFunction(ref: PsiReference): PsiElement?
override fun getAdditionalDefinitionSearchFlags() = 0
override fun getAdditionalReferenceSearchFlags() = DO_NOT_UNWRAP_LABELED_EXPRESSION or BYPASS_IMPORT_ALIAS
override fun getAllAdditionalFlags() = additionalDefinitionSearchFlags + additionalReferenceSearchFlags
override fun includeSelfInGotoImplementation(element: PsiElement): Boolean = !(element is KtClass && element.isAbstract())
override fun getElementByReference(ref: PsiReference, flags: Int): PsiElement? {
if (ref is KtSimpleNameReference && ref.expression is KtLabelReferenceExpression) {
val refTarget = ref.resolve() as? KtExpression ?: return null
if (!BitUtil.isSet(flags, DO_NOT_UNWRAP_LABELED_EXPRESSION)) {
return refTarget.getLabeledParent(ref.expression.getReferencedName()) ?: refTarget
}
return refTarget
}
if (!BitUtil.isSet(flags, BYPASS_IMPORT_ALIAS)) {
(ref.element as? KtSimpleNameExpression)?.mainReference?.getImportAlias()?.let { return it }
}
// prefer destructing declaration entry to its target if element name is accepted
if (ref is KtDestructuringDeclarationReference && BitUtil.isSet(flags, TargetElementUtil.ELEMENT_NAME_ACCEPTED)) {
return ref.element
}
val refExpression = ref.element as? KtSimpleNameExpression
val calleeExpression = refExpression?.getParentOfTypeAndBranch<KtCallElement> { calleeExpression }
if (calleeExpression != null) {
(ref.resolve() as? KtConstructor<*>)?.let {
return if (flags and JavaTargetElementEvaluator().additionalReferenceSearchFlags != 0) it else it.containingClassOrObject
}
}
if (BitUtil.isSet(flags, TargetElementUtil.REFERENCED_ELEMENT_ACCEPTED)) {
return findLambdaOpenLBraceForGeneratedIt(ref)
?: findReceiverForThisInExtensionFunction(ref)
}
return null
}
override fun isIdentifierPart(file: PsiFile, text: CharSequence, offset: Int): Boolean {
val elementAtCaret = file.findElementAt(offset)
if (elementAtCaret?.node?.elementType == KtTokens.IDENTIFIER) return true
// '(' is considered identifier part if it belongs to primary constructor without 'constructor' keyword
return elementAtCaret?.getNonStrictParentOfType<KtPrimaryConstructor>()?.textOffset == offset
}
}
| apache-2.0 | 9a4eff95fe360f522183ce8bd6b571d7 | 47.17284 | 158 | 0.744234 | 5.209613 | false | false | false | false |
chromeos/video-decode-encode-demo | app/src/main/java/dev/hadrosaur/videodecodeencodedemo/VideoHelpers/VideoFrameLedger.kt | 1 | 3716 | /*
* Copyright (c) 2021 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dev.hadrosaur.videodecodeencodedemo.VideoHelpers
import android.media.MediaFormat
import com.google.android.exoplayer2.Format
import com.google.android.exoplayer2.video.VideoFrameMetadataListener
import java.util.concurrent.ConcurrentHashMap
import java.util.concurrent.atomic.AtomicBoolean
import java.util.concurrent.atomic.AtomicInteger
/**
* There is an issue decoding via Surface prior to Android Q. The Surface can silently drop frames
* if the decode speed is faster than realtime. This is generally desirable for video editing.
*
* The FrameLedger keeps track of frames sent for decode and those actually decoded and rendered.
* In addition, it provides an atomic lock to ensure frames do not get overwritten before they can
* be rendered.
*
* The decodeLedger records the release and presentation time of each frame as it is about to be rendered
* to the Surface so it can be checked when it is actually rendered. releaseTimeNs is really just
* used as an ID for the frame.
*
* The encodeLedger counts frames received from the decoder rendered and records their presentation
* time for use in encoding.
*/
class VideoFrameLedger : VideoFrameMetadataListener {
val decodeLedger = ConcurrentHashMap<Long, Long>() // < ReleaseTimeUs, presentationTimeUs >
val encodeLedger = ConcurrentHashMap<Int, Long>() // < frameCount, presentationTimeUs >
private var framesEntered = AtomicInteger(0)
var framesRendered = AtomicInteger(0)
private var encodingCounter = AtomicInteger(0)
// Atomic lock to block the pipeline to prevent frame drops
private var eglLockRenderer = AtomicBoolean(false)
var lastVideoBufferPresentationTimeUs = 0L
// Check if the lock render flag is engaged.
fun isRenderLocked() : Boolean {
return eglLockRenderer.get()
}
fun engageRenderLock() {
eglLockRenderer.set(true)
}
fun releaseRenderLock() {
eglLockRenderer.set(false)
}
// The encode ledger just counts frames (1 -> last frame) and records proper presentation time
fun addEncodePresentationTime(presentationTimeUs: Long) {
encodeLedger.put(encodingCounter.incrementAndGet(), presentationTimeUs)
}
/**
* This is the VideoFrameMetadataListener called by ExoPlayer right before a frame is about to
* be sent to be rendered. To prevent overloading the surface and dropping frames, it is here
* that we set an atomic lock in the render pipeline to be released after updateTexImage for
* this frame has been called.
*
* The lock is released in InternalSurfaceTextureRenderer's onFrameAvailable call.
*/
override fun onVideoFrameAboutToBeRendered(
presentationTimeUs: Long, releaseTimeNs: Long, format: Format, mediaFormat: MediaFormat?) {
// Block pipeline until updateTexSurface has been called
engageRenderLock()
decodeLedger.put(releaseTimeNs, presentationTimeUs)
// Record frame presentation time in the encode ledger
addEncodePresentationTime(presentationTimeUs)
framesEntered.incrementAndGet()
}
} | apache-2.0 | e9abeeca92bade38886b4adab4d30180 | 40.3 | 105 | 0.748116 | 4.733758 | false | false | false | false |
dahlstrom-g/intellij-community | plugins/search-everywhere-ml/src/com/intellij/ide/actions/searcheverywhere/ml/actions/OpenFeaturesInScratchFileAction.kt | 2 | 5484 | package com.intellij.ide.actions.searcheverywhere.ml.actions
import com.fasterxml.jackson.annotation.JsonPropertyOrder
import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper
import com.intellij.ide.actions.searcheverywhere.SearchEverywhereManager
import com.intellij.ide.actions.searcheverywhere.SearchEverywhereUI
import com.intellij.ide.actions.searcheverywhere.ml.SearchEverywhereFoundElementInfoWithMl
import com.intellij.ide.actions.searcheverywhere.ml.SearchEverywhereMlSessionService
import com.intellij.ide.actions.searcheverywhere.ml.features.SearchEverywhereContributorFeaturesProvider
import com.intellij.ide.scratch.ScratchFileCreationHelper
import com.intellij.ide.scratch.ScratchFileService
import com.intellij.ide.scratch.ScratchRootType
import com.intellij.json.JsonFileType
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.fileEditor.FileEditorManager
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.text.StringUtil
import com.intellij.openapi.vfs.VirtualFile
class OpenFeaturesInScratchFileAction : AnAction() {
companion object {
private const val SHOULD_ORDER_BY_ML_KEY = "shouldOrderByMl"
private const val CONTEXT_INFO_KEY = "contextInfo"
private const val SEARCH_STATE_FEATURES_KEY = "searchStateFeatures"
private const val CONTRIBUTORS_KEY = "contributors"
private const val FOUND_ELEMENTS_KEY = "foundElements"
}
override fun update(e: AnActionEvent) {
e.presentation.isEnabled = shouldActionBeEnabled(e)
}
private fun shouldActionBeEnabled(e: AnActionEvent): Boolean {
val seManager = SearchEverywhereManager.getInstance(e.project)
val session = SearchEverywhereMlSessionService.getService()?.getCurrentSession()
return e.project != null
&& seManager.isShown
&& session != null
&& session.getCurrentSearchState() != null
}
override fun actionPerformed(e: AnActionEvent) {
val searchEverywhereUI = SearchEverywhereManager.getInstance(e.project).currentlyShownUI
val report = getFeaturesReport(searchEverywhereUI)
val json = jacksonObjectMapper().writerWithDefaultPrettyPrinter().writeValueAsString(report)
val context = createScratchFileContext(json)
val scratchFile = createNewJsonScratchFile(e.project!!, context)
openScratchFile(scratchFile, e.project!!)
}
private fun getFeaturesReport(searchEverywhereUI: SearchEverywhereUI): Map<String, Any> {
val mlSessionService = SearchEverywhereMlSessionService.getService() ?: return emptyMap()
val searchSession = mlSessionService.getCurrentSession()!!
val state = searchSession.getCurrentSearchState()!!
val features = searchEverywhereUI.foundElementsInfo
.map { SearchEverywhereFoundElementInfoWithMl.from(it) }
.map { info ->
val rankingWeight = info.priority
val contributor = info.contributor.searchProviderId
val elementName = StringUtil.notNullize(info.element.toString(), "undefined")
val mlWeight = info.mlWeight
val mlFeatures: Map<String, Any> = info.mlFeatures.associate { it.field.name to it.data as Any }
val elementId = searchSession.itemIdProvider.getId(info.element)
return@map ElementFeatures(
elementId,
elementName,
mlWeight,
rankingWeight,
contributor,
mlFeatures.toSortedMap()
)
}
val contributors = searchEverywhereUI.foundElementsInfo.map { info -> info.contributor }.toHashSet()
val contributorFeaturesProvider = SearchEverywhereContributorFeaturesProvider()
val contributorFeatures = contributors.map { contributorFeaturesProvider.getFeatures(it, searchSession.mixedListInfo)}
return mapOf(
SHOULD_ORDER_BY_ML_KEY to state.orderByMl,
CONTEXT_INFO_KEY to searchSession.cachedContextInfo.features.associate { it.field.name to it.data },
SEARCH_STATE_FEATURES_KEY to state.searchStateFeatures.associate { it.field.name to it.data },
CONTRIBUTORS_KEY to contributorFeatures.map { c -> c.associate { it.field.name to it.data }.toSortedMap() },
FOUND_ELEMENTS_KEY to features
)
}
private fun createScratchFileContext(json: String) = ScratchFileCreationHelper.Context().apply {
text = json
fileExtension = JsonFileType.DEFAULT_EXTENSION
createOption = ScratchFileService.Option.create_if_missing
}
private fun createNewJsonScratchFile(project: Project, context: ScratchFileCreationHelper.Context): VirtualFile {
val fileName = "search-everywhere-features.${context.fileExtension}"
return ScratchRootType.getInstance().createScratchFile(project, fileName, context.language, context.text, context.createOption)!!
}
private fun openScratchFile(file: VirtualFile, project: Project) {
FileEditorManager.getInstance(project).openFile(file, true)
}
@JsonPropertyOrder("id", "name", "mlWeight", "rankingWeight", "contributor", "features")
private data class ElementFeatures(val id: Int?,
val name: String,
val mlWeight: Double?,
val rankingWeight: Int,
val contributor: String,
val features: Map<String, Any>)
@JsonPropertyOrder("id", "weight")
private data class ContributorInfo(val id: String, val weight: Int)
} | apache-2.0 | de7b4aa1d91cbda79f7224c9d2fde686 | 45.880342 | 133 | 0.742524 | 4.931655 | false | false | false | false |
dahlstrom-g/intellij-community | platform/build-scripts/icons/src/org/jetbrains/intellij/build/images/sync/dotnet/DotnetIconsTransformation.kt | 9 | 2661 | // 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 org.jetbrains.intellij.build.images.sync.dotnet
import com.intellij.util.io.isFile
import org.jetbrains.intellij.build.images.isImage
import java.io.File
import java.io.IOException
import java.nio.file.FileVisitResult
import java.nio.file.Files
import java.nio.file.Path
import java.nio.file.SimpleFileVisitor
internal object DotnetIconsTransformation {
internal const val ideaDarkSuffix = "_dark"
/**
* First icon with one of the suffices (according to order) corresponds to Idea light icon
*/
internal val dotnetLightSuffices = listOf("RiderLight", "Gray", "Color", "SymbolsVs11Gray", "")
/**
* First icon with one of the suffices (according to order) corresponds to Idea dark icon
*/
internal val dotnetDarkSuffices = listOf("RiderDark", "GrayDark", "SymbolsVs11GrayDark")
private val dotnetLightComparator = comparator(dotnetLightSuffices)
private val dotnetDarkComparator = comparator(dotnetDarkSuffices)
fun transformToIdeaFormat(path: Path) {
Files.walkFileTree(path, object : SimpleFileVisitor<Path>() {
override fun postVisitDirectory(dir: Path, exc: IOException?): FileVisitResult {
if (exc != null) throw exc
(dir.toFile().listFiles() ?: emptyArray())
.asSequence().map(File::toPath)
.filter { it.isFile() && isImage(it) }
.map(::DotnetIcon).groupBy(DotnetIcon::name)
.forEach { (_, icons) ->
transform(icons)
}
return FileVisitResult.CONTINUE
}
})
}
private fun transform(icons: List<DotnetIcon>) {
val transformed = ArrayList<DotnetIcon>(2)
icons.filterOnly(dotnetLightSuffices).minWithOrNull(dotnetLightComparator)?.changeSuffix("")?.also {
transformed += it
}
if (hasRiderDarkPart(icons)) {
icons.filterOnly(dotnetDarkSuffices).minWithOrNull(dotnetDarkComparator)?.changeSuffix(ideaDarkSuffix)?.also {
transformed += it
}
}
(icons - transformed).forEach(DotnetIcon::delete)
}
private fun hasRiderDarkPart(icons: List<DotnetIcon>): Boolean {
return icons.any { it.suffix == "RiderLight" }.not()
|| (icons.any { it.suffix == "RiderLight" } && icons.any { it.suffix == "RiderDark" })
}
private fun comparator(suffices: List<String>) = Comparator<DotnetIcon> { i1, i2 ->
suffices.indexOf(i1.suffix).compareTo(suffices.indexOf(i2.suffix))
}
private fun List<DotnetIcon>.filterOnly(suffices: List<String>) = asSequence().filter {
suffices.contains(it.suffix)
}
} | apache-2.0 | 5e6684c61cace603bf1d69701290dd0b | 38.731343 | 140 | 0.699737 | 4.14486 | false | false | false | false |
dkandalov/katas | kotlin/src/katas/kotlin/leetcode/add_and_search_word/AddAndSearchWord2.kt | 1 | 1087 | package katas.kotlin.leetcode.add_and_search_word
class AddAndSearchWord2 {
private class Node(
val value: Char,
val nodes: MutableMap<Char, Node> = mutableMapOf(),
var isEndOfTheWord: Boolean = false
) {
fun add(word: String) {
if (word.isEmpty()) {
isEndOfTheWord = true
return
}
val child: Node = this.nodes.getOrPut(word.first()) { Node(word.first()) }
child.add(word.drop(1))
}
fun search(word: String): Boolean {
if (word.isEmpty()) return isEndOfTheWord
if (word.first() == '.') {
return nodes.values.any { it.search(word.drop(1)) }
} else {
val childNode = this.nodes[word.first()] ?: return false
return childNode.search(word.drop(1))
}
}
}
private val root = Node('0')
fun addWord(word: String) {
root.add(word.toLowerCase())
}
fun search(word: String): Boolean {
return root.search(word)
}
} | unlicense | 3d8c4f6ad795864487a35a50a0f0de99 | 27.631579 | 86 | 0.523459 | 4.148855 | false | false | false | false |
DreierF/MyTargets | app/src/main/java/de/dreier/mytargets/views/selector/BowSelector.kt | 1 | 2027 | /*
* Copyright (C) 2018 Florian Dreier
*
* This file is part of MyTargets.
*
* MyTargets is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2
* as published by the Free Software Foundation.
*
* MyTargets 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.
*/
package de.dreier.mytargets.views.selector
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.util.AttributeSet
import de.dreier.mytargets.R
import de.dreier.mytargets.app.ApplicationInstance
import de.dreier.mytargets.databinding.SelectorItemImageDetailsBinding
import de.dreier.mytargets.shared.models.db.Bow
class BowSelector @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null
) : SelectorBase<Bow, SelectorItemImageDetailsBinding>(
context,
attrs,
R.layout.selector_item_image_details,
BOW_REQUEST_CODE
) {
private val database = ApplicationInstance.db
private val bowDAO = database.bowDAO()
override fun bindView(item: Bow) {
view.name.text = item.name
view.image.setImageDrawable(item.thumbnail!!.roundDrawable)
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (resultCode == Activity.RESULT_OK && requestCode == BOW_ADD_REQUEST_CODE) {
setItemId(null)
}
}
fun setItemId(bow: Long?) {
var item: Bow? = null
if (bow != null) {
item = bowDAO.loadBowOrNull(bow)
}
if (item == null) {
item = bowDAO.loadBows().firstOrNull()
}
setItem(item)
}
companion object {
const val BOW_REQUEST_CODE = 7
const val BOW_ADD_REQUEST_CODE = 8
}
}
| gpl-2.0 | 60e6c0001b643a5a042613f97483c43e | 29.253731 | 86 | 0.693143 | 4.214137 | false | false | false | false |
securityfirst/Umbrella_android | app/src/main/java/org/secfirst/umbrella/feature/difficulty/view/DifficultyAdapter.kt | 1 | 2207 | package org.secfirst.umbrella.feature.difficulty.view
import android.annotation.SuppressLint
import android.graphics.Color
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import kotlinx.android.synthetic.main.difficulty_item_view.view.*
import org.jetbrains.anko.backgroundColor
import org.secfirst.umbrella.R
import org.secfirst.umbrella.data.database.difficulty.Difficulty
class DifficultyAdapter(private val onClickDiff: (Int) -> Unit) : RecyclerView.Adapter<DifficultyAdapter.DifficultHolder>() {
private val difficulties = mutableListOf<Difficulty>()
fun clear() = difficulties.clear()
fun getItem(position: Int) = difficulties[position]
fun addAll(difficulties: List<Difficulty>) {
this.difficulties.addAll(difficulties)
notifyDataSetChanged()
}
override fun getItemCount() = difficulties.size
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): DifficultHolder {
val view = LayoutInflater.from(parent.context)
.inflate(R.layout.difficulty_item_view, parent, false)
return DifficultHolder(view)
}
override fun onBindViewHolder(holder: DifficultHolder, position: Int) {
holder.bind(difficulties[position], clickListener = { onClickDiff(position) })
}
fun getItems(position: Int): List<Difficulty> {
val sortItems = mutableListOf<Difficulty>()
sortItems.add(difficulties[position])
difficulties.forEach {
if (difficulties[position].id != it.id)
sortItems.add(it)
}
return sortItems
}
class DifficultHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
@SuppressLint("Range")
fun bind(difficulty: Difficulty, clickListener: (DifficultHolder) -> Unit) {
itemView.setOnClickListener { clickListener(this) }
with(difficulty) {
itemView.difficultTitle.text = title
itemView.difficultDescription.text = description
itemView.difficultLayout.backgroundColor = Color.parseColor(layoutColor)
}
}
}
} | gpl-3.0 | ffc4abeda3fddce69598e2a023bcb711 | 35.196721 | 125 | 0.704123 | 4.808279 | false | false | false | false |
Vektah/CodeGlance | src/main/java/net/vektah/codeglance/EditorPanelInjector.kt | 1 | 5218 | package net.vektah.codeglance
import com.intellij.openapi.components.ServiceManager
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.fileEditor.*
import com.intellij.openapi.project.Project
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.ui.JBSplitter
import net.vektah.codeglance.config.Config
import net.vektah.codeglance.config.ConfigService
import net.vektah.codeglance.render.TaskRunner
import javax.swing.*
import java.awt.*
import java.util.*
/**
* Injects a panel into any newly created editors.
*/
class EditorPanelInjector(private val project: Project, private val runner: TaskRunner) : FileEditorManagerListener {
private val logger = Logger.getInstance(javaClass)
private val panels = HashMap<FileEditor, GlancePanel>()
private val configService = ServiceManager.getService(ConfigService::class.java)
private var config: Config = configService.state!!
override fun fileOpened(fem: FileEditorManager, virtualFile: VirtualFile) {
// Seems there is a case where multiple split panes can have the same file open and getSelectedEditor, and even
// getEditors(virtualVile) return only one of them... So shotgun approach here.
val editors = fem.allEditors
for (editor in editors) {
inject(editor)
}
freeUnusedPanels(fem)
}
/**
* Here be dragons. No Seriously. Run!
*
* We are digging way down into the editor layout. This lets the codeglance panel be right next to the scroll bar.
* In an ideal world it would be inside the scroll bar... maybe one day.
*
* vsch: added handling when the editor is even deeper, inside firstComponent of a JBSplitter, used by idea-multimarkdown
* and Markdown Support to show split preview. Missed this plugin while editing markdown. These changes got it back.
*
* @param editor A text editor to inject into.
*/
private fun getPanel(editor: FileEditor): JPanel? {
if (editor !is TextEditor) {
logger.debug("I01: Injection failed, only text editors are supported currently.")
return null
}
try {
val outerPanel = editor.component as JPanel
val outerLayout = outerPanel.layout as BorderLayout
var layoutComponent = outerLayout.getLayoutComponent(BorderLayout.CENTER)
if (layoutComponent is JBSplitter) {
// editor is inside firstComponent of a JBSplitter
val editorComp = layoutComponent.firstComponent as JPanel
layoutComponent = (editorComp.layout as BorderLayout).getLayoutComponent(BorderLayout.CENTER)
}
val pane = layoutComponent as JLayeredPane
val panel = if (pane.componentCount > 1) pane.getComponent(1) as JPanel else pane.getComponent(0) as JPanel
// Assert ahead of time that we have the expected layout, so the caller dosent need to
panel.layout as BorderLayout
return panel
} catch (e: ClassCastException) {
logger.warn("Injection failed")
e.printStackTrace()
return null
}
}
private fun inject(editor: FileEditor) {
val panel = getPanel(editor) ?: return
val innerLayout = panel.layout as BorderLayout
val where = if (config.isRightAligned) BorderLayout.LINE_END else BorderLayout.LINE_START
if (innerLayout.getLayoutComponent(where) == null) {
val glancePanel = GlancePanel(project, editor, panel, runner)
panel.add(glancePanel, where)
panels.put(editor, glancePanel)
}
}
private fun uninject(editor: FileEditor) {
val panel = getPanel(editor) ?: return
val innerLayout = panel.layout as BorderLayout
// Ok we finally found the actual editor layout. Now make sure we have already injected into this editor.
val rightPanel = innerLayout.getLayoutComponent(BorderLayout.LINE_END)
if (rightPanel != null) {
panel.remove(rightPanel)
}
val leftPanel = innerLayout.getLayoutComponent(BorderLayout.LINE_START)
if (leftPanel != null) {
panel.remove(leftPanel)
}
}
override fun fileClosed(fem: FileEditorManager, virtualFile: VirtualFile) {
freeUnusedPanels(fem)
}
/**
* On close we dont know which (if any) editor was closed, just the file. And in configurations we dont even
* get a fileClosed event. Lets just scan all of the open penels and make sure they are still being used by
* at least one of the open editors.
*/
private fun freeUnusedPanels(fem: FileEditorManager) {
val unseen = HashSet(panels.keys)
for (editor in fem.allEditors) {
if (unseen.contains(editor)) {
unseen.remove(editor)
}
}
var panel: GlancePanel
for (editor in unseen) {
panel = panels[editor]!!
panel.onClose()
uninject(editor)
panels.remove(editor)
}
}
override fun selectionChanged(fileEditorManagerEvent: FileEditorManagerEvent) {
}
}
| bsd-2-clause | ad5c41e2bdb03dbf6793237c490dde4b | 37.367647 | 125 | 0.666539 | 4.800368 | false | true | false | false |
StephenVinouze/AdvancedRecyclerView | section/src/main/kotlin/com/github/stephenvinouze/advancedrecyclerview/section/adapters/RecyclerSectionAdapter.kt | 1 | 6091 | package com.github.stephenvinouze.advancedrecyclerview.section.adapters
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.github.stephenvinouze.advancedrecyclerview.core.adapters.RecyclerAdapter
import com.github.stephenvinouze.advancedrecyclerview.core.views.BaseViewHolder
/**
* Created by Stephen Vinouze on 09/11/2015.
*/
abstract class RecyclerSectionAdapter<SECTION : Comparable<SECTION>, MODEL>(var section: (MODEL) -> SECTION) : RecyclerAdapter<MODEL>() {
companion object {
private const val SECTION_VIEW_TYPE = 222
}
val sectionCount: Int
get() = sectionItems.size
val sections: List<SECTION>
get() = sectionItems.keys.toList()
private var sectionItems: Map<SECTION, List<MODEL>> = mapOf()
override var items: MutableList<MODEL> = mutableListOf()
set(value) {
buildSections(value, section)
field = sectionItems.values.flatten().toMutableList()
notifyDataSetChanged()
}
final override fun addItemsInternal(items: MutableList<MODEL>, position: Int) {
super.addItemsInternal(items, relativePosition(position))
buildSections(items, section)
notifyDataSetChanged()
}
final override fun addItemInternal(item: MODEL, position: Int) {
super.addItemInternal(item, relativePosition(position))
buildSections(items, section)
notifyDataSetChanged()
}
final override fun removeItemInternal(position: Int) {
super.removeItemInternal(relativePosition(position))
buildSections(items, section)
notifyDataSetChanged()
}
final override fun moveItemInternal(from: Int, to: Int) {
super.moveItemInternal(relativePosition(from), relativePosition(to))
}
final override fun handleClick(viewHolder: BaseViewHolder, clickPosition: (BaseViewHolder) -> Int) {
super.handleClick(viewHolder) { relativePosition(it.layoutPosition) }
}
final override fun toggleItemView(position: Int) {
getSelectedItemViews().forEach {
notifyItemChanged(absolutePosition(it))
}
super.toggleItemView(position)
notifyItemChanged(absolutePosition(position))
}
override fun getItemViewType(position: Int): Int =
if (isSectionAt(position)) SECTION_VIEW_TYPE else super.getItemViewType(relativePosition(position))
override fun getItemId(position: Int): Long =
if (isSectionAt(position)) Long.MAX_VALUE - sectionPosition(position) else super.getItemId(relativePosition(position))
override fun getItemCount(): Int = super.getItemCount() + sectionCount
final override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): BaseViewHolder =
when (viewType) {
SECTION_VIEW_TYPE -> BaseViewHolder(onCreateSectionItemView(parent, viewType))
else -> super.onCreateViewHolder(parent, viewType)
}
final override fun onBindViewHolder(holder: BaseViewHolder, position: Int) {
if (isSectionAt(position)) {
onBindSectionItemView(holder.view, sectionPosition(position))
} else {
super.onBindViewHolder(holder, relativePosition(position))
}
}
fun itemCountInSection(section: Int): Int = sectionItems[sectionAt(section)]?.size ?: 0
fun sectionAt(position: Int): SECTION? = sections[position]
fun buildSections(items: List<MODEL>, section: (MODEL) -> SECTION) {
sectionItems = items.groupBy(section).toSortedMap()
}
/**
* Check that the given position in the list matches with a section position
* @param position: The absolute position in the list
* @return True if this is a section
*/
fun isSectionAt(position: Int): Boolean {
var absoluteSectionPosition = 0
(0 until sectionCount).forEach {
if (position == absoluteSectionPosition) {
return true
} else if (position < absoluteSectionPosition) {
return false
}
absoluteSectionPosition += itemCountInSection(it) + 1
}
return false
}
/**
* Compute the relative section position in the list depending on the number of items in each section
* @param position: The absolute position in the list
* @return The relative section position of the given position
*/
fun sectionPosition(position: Int): Int {
var sectionPosition = 0
var absoluteSectionPosition = 0
(0 until sectionCount).forEach {
absoluteSectionPosition += itemCountInSection(it)
if (position <= absoluteSectionPosition) {
return sectionPosition
}
sectionPosition++
absoluteSectionPosition++
}
return sectionPosition
}
/**
* Compute the relative position in the list that omits the sections
* @param position: The absolute position in the list
* @return The relative position without sections or NO_POSITION if matches section position
*/
fun relativePosition(position: Int): Int {
if (isSectionAt(position)) {
return RecyclerView.NO_POSITION
}
var relativePosition = position
(0..position).forEach {
if (isSectionAt(it)) {
relativePosition--
}
}
return relativePosition
}
/**
* Compute the absolute position in the list that includes the sections
* @param position: The relative position in the list
* @return The absolute position with sections
*/
fun absolutePosition(position: Int): Int {
var offset = 0
(0..position).forEach {
if (isSectionAt(it + offset)) {
offset++
}
}
return position + offset
}
protected abstract fun onCreateSectionItemView(parent: ViewGroup, viewType: Int): View
protected abstract fun onBindSectionItemView(sectionView: View, sectionPosition: Int)
} | apache-2.0 | 98f88c3d8ff93c50f669fff76fd059ef | 34.418605 | 137 | 0.664259 | 5.250862 | false | false | false | false |
google/intellij-community | platform/platform-impl/src/com/intellij/openapi/wm/impl/customFrameDecorations/header/titleLabel/SelectedEditorFilePath.kt | 2 | 12461 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
@file:Suppress("JAVA_MODULE_DOES_NOT_EXPORT_PACKAGE")
package com.intellij.openapi.wm.impl.customFrameDecorations.header.titleLabel
import com.intellij.ide.HelpTooltip
import com.intellij.ide.ui.UISettings
import com.intellij.ide.ui.UISettingsListener
import com.intellij.openapi.Disposable
import com.intellij.openapi.application.*
import com.intellij.openapi.fileEditor.FileEditorManager
import com.intellij.openapi.fileEditor.FileEditorManagerEvent
import com.intellij.openapi.fileEditor.FileEditorManagerListener
import com.intellij.openapi.fileEditor.ex.FileEditorManagerEx
import com.intellij.openapi.project.Project
import com.intellij.openapi.project.displayUrlRelativeToProject
import com.intellij.openapi.util.CheckedDisposable
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.openapi.vfs.VirtualFileManager
import com.intellij.openapi.vfs.newvfs.BulkFileListener
import com.intellij.openapi.vfs.newvfs.VfsPresentationUtil
import com.intellij.openapi.vfs.newvfs.events.VFileEvent
import com.intellij.openapi.wm.impl.FrameTitleBuilder
import com.intellij.openapi.wm.impl.PlatformFrameTitleBuilder
import com.intellij.openapi.wm.impl.TitleInfoProvider.Companion.getProviders
import com.intellij.ui.AncestorListenerAdapter
import com.intellij.util.ui.JBUI
import kotlinx.coroutines.*
import kotlinx.coroutines.channels.BufferOverflow
import kotlinx.coroutines.flow.*
import net.miginfocom.swing.MigLayout
import sun.swing.SwingUtilities2
import java.awt.Color
import java.awt.Dimension
import java.awt.Graphics
import java.awt.Graphics2D
import java.awt.event.ComponentAdapter
import java.awt.event.ComponentEvent
import javax.swing.JComponent
import javax.swing.JLabel
import javax.swing.JPanel
import javax.swing.event.AncestorEvent
import kotlin.coroutines.coroutineContext
import kotlin.math.min
import kotlin.time.Duration.Companion.milliseconds
@OptIn(FlowPreview::class)
internal open class SelectedEditorFilePath {
var onBoundsChanged: (() -> Unit)? = null
private val projectTitle = ProjectTitlePane()
private val classTitle = ClassTitlePane()
private var simplePaths: List<TitlePart>? = null
private var basePaths = listOf<TitlePart>(projectTitle, classTitle)
protected var components = basePaths
private val updatePathRequests = MutableSharedFlow<Unit>(replay=1, onBufferOverflow = BufferOverflow.DROP_OLDEST)
private val updateViewRequests = MutableSharedFlow<Unit>(replay=1, onBufferOverflow = BufferOverflow.DROP_OLDEST)
protected open val captionInTitle: Boolean
get() = true
init {
val scope = ApplicationManager.getApplication().coroutineScope
scope.launch {
updatePathRequests
.debounce(100.milliseconds)
.collectLatest {
updatePath()
}
}
scope.launch {
updateViewRequests
.debounce(70.milliseconds)
.collectLatest {
withContext(Dispatchers.EDT) {
update()
}
}
}
}
protected fun updateProjectPath() {
updateTitlePaths()
updateProject()
}
protected fun updatePaths() {
updateTitlePaths()
scheduleViewUpdate()
}
protected val label = object : JLabel() {
override fun getMinimumSize(): Dimension {
return Dimension(projectTitle.shortWidth, super.getMinimumSize().height)
}
override fun getPreferredSize(): Dimension {
val fm = getFontMetrics(font)
val w = SwingUtilities2.stringWidth(this, fm, titleString) + JBUI.scale(5)
return Dimension(min(parent.width, w), super.getPreferredSize().height)
}
override fun paintComponent(g: Graphics) {
val fm = getFontMetrics(font)
g as Graphics2D
UISettings.setupAntialiasing(g)
g.drawString(titleString, 0, fm.ascent)
}
}
@Suppress("SpellCheckingInspection")
private var pane = object : JPanel(MigLayout("ins 0, novisualpadding, gap 0", "[]push")) {
override fun addNotify() {
super.addNotify()
installListeners()
}
override fun removeNotify() {
super.removeNotify()
unInstallListeners()
}
override fun getMinimumSize(): Dimension {
return Dimension(projectTitle.shortWidth, super.getMinimumSize().height)
}
override fun setForeground(fg: Color?) {
super.setForeground(fg)
label.foreground = fg
}
}.apply {
isOpaque = false
add(label)
}
private fun updateTitlePaths() {
val uiSettings = UISettings.getInstance()
projectTitle.active = uiSettings.fullPathsInWindowHeader || multipleSameNamed
classTitle.active = captionInTitle || classPathNeeded
classTitle.fullPath = uiSettings.fullPathsInWindowHeader || classPathNeeded
schedulePathUpdate()
}
open val view: JComponent
get() = pane
private var disposable: CheckedDisposable? = null
var project: Project? = null
set(value) {
if (field === value) {
return
}
field = value
installListeners()
}
var multipleSameNamed = false
set(value) {
if (field == value) {
return
}
field = value
updateProjectPath()
}
var classPathNeeded = false
set(value) {
if (field == value) {
return
}
field = value
updatePaths()
}
protected open fun addAdditionalListeners(disp: Disposable) {
}
protected open fun installListeners() {
val project = project ?: return
if (disposable != null) {
unInstallListeners()
}
val disposable = Disposer.newCheckedDisposable()
Disposer.register(project, disposable)
Disposer.register(disposable) {
HelpTooltip.dispose(label)
unInstallListeners()
}
this.disposable = disposable
val busConnection = project.messageBus.connect(disposable)
busConnection.subscribe(UISettingsListener.TOPIC, UISettingsListener {
updateProjectPath()
})
simplePaths = getProviders().map { titleInfoProvider ->
val partTitle = DefaultPartTitle(titleInfoProvider.borderlessPrefix, titleInfoProvider.borderlessSuffix)
titleInfoProvider.addUpdateListener(project, disposable) {
partTitle.active = it.isActive(project)
partTitle.longText = it.getValue(project)
scheduleViewUpdate()
}
partTitle
}
val shrinkingPaths = mutableListOf<TitlePart>(projectTitle, classTitle)
simplePaths?.let(shrinkingPaths::addAll)
components = shrinkingPaths
updateTitlePaths()
busConnection.subscribe(FileEditorManagerListener.FILE_EDITOR_MANAGER, object : FileEditorManagerListener {
override fun fileOpened(source: FileEditorManager, file: VirtualFile) {
schedulePathUpdate()
}
override fun fileClosed(source: FileEditorManager, file: VirtualFile) {
schedulePathUpdate()
}
override fun selectionChanged(event: FileEditorManagerEvent) {
schedulePathUpdate()
}
})
busConnection.subscribe(VirtualFileManager.VFS_CHANGES, object : BulkFileListener {
override fun after(events: List<VFileEvent>) {
schedulePathUpdate()
}
})
addAdditionalListeners(disposable)
updateProject()
schedulePathUpdate()
view.addComponentListener(resizedListener)
label.addAncestorListener(ancestorListener)
}
protected fun schedulePathUpdate() {
check(updatePathRequests.tryEmit(Unit))
}
protected open fun unInstallListeners() {
disposable?.let {
if (!it.isDisposed) {
Disposer.dispose(it)
}
disposable = null
}
pane.invalidate()
view.removeComponentListener(resizedListener)
label.removeAncestorListener(ancestorListener)
}
private val resizedListener = object : ComponentAdapter() {
override fun componentResized(e: ComponentEvent?) {
scheduleViewUpdate()
}
}
private val ancestorListener = object : AncestorListenerAdapter() {
override fun ancestorMoved(event: AncestorEvent?) {
HelpTooltip.hide(label)
}
}
private suspend fun updatePath() {
val project = project
if (project == null || project.isDisposed) {
return
}
val fileEditorManager = FileEditorManager.getInstance(project)
val file = withContext(Dispatchers.EDT) {
val file = (fileEditorManager as? FileEditorManagerEx)?.getSplittersFor(view)?.currentFile ?: fileEditorManager?.selectedEditor?.file
if (file == null) {
classTitle.classPath = ""
classTitle.longText = ""
scheduleViewUpdate()
}
file
} ?: return
val result = readAction {
val titleBuilder = FrameTitleBuilder.getInstance()
val baseTitle = titleBuilder.getFileTitle(project, file)
Pair(
(titleBuilder as? PlatformFrameTitleBuilder)?.run {
val fileTitle = VfsPresentationUtil.getPresentableNameForUI(project, file)
if (!fileTitle.endsWith(file.presentableName) || file.parent == null) {
fileTitle
}
else {
displayUrlRelativeToProject(file = file,
url = file.presentableUrl,
project = project,
isIncludeFilePath = true,
moduleOnTheLeft = false)
}
} ?: baseTitle, baseTitle)
}
withContext(Dispatchers.EDT) {
classTitle.classPath = result.first
classTitle.longText = if (classTitle.fullPath) result.first else result.second
scheduleViewUpdate()
}
}
private fun scheduleViewUpdate() {
check(updateViewRequests.tryEmit(Unit))
}
private fun updateProject() {
project?.let {
projectTitle.project = it
scheduleViewUpdate()
}
}
val toolTipNeeded: Boolean
get() = basePaths.firstOrNull{!it.active} != null || isClipped
open fun getCustomTitle(): String? = null
private var isClipped = false
var titleString = ""
data class Pattern(val preferredWidth: Int, val createTitle: () -> String)
private suspend fun update() {
val insets = view.getInsets(null)
val width: Int = view.width - (insets.right + insets.left)
val fm = label.getFontMetrics(label.font)
components.forEach { it.refresh(label, fm) }
isClipped = true
val shrankSimplePaths = simplePaths?.let { shrinkSimplePaths(it, width - (projectTitle.longWidth + classTitle.longWidth)) }
val pathPatterns = listOf(
Pattern(projectTitle.longWidth + classTitle.shortWidth) {
projectTitle.getLong() +
classTitle.shrink(label, fm, width - projectTitle.longWidth)
},
Pattern(projectTitle.shortWidth + classTitle.shortWidth) {
projectTitle.shrink(label, fm, width - classTitle.shortWidth) +
classTitle.getShort()
},
Pattern(0) {
projectTitle.getShort()
})
titleString = shrankSimplePaths?.let {
projectTitle.getLong() +
classTitle.getLong() + it
} ?: pathPatterns.firstOrNull { it.preferredWidth < width }?.let { it.createTitle() } ?: ""
getCustomTitle()?.let {
titleString = it
}
label.text = titleString
HelpTooltip.dispose(label)
(if (isClipped || basePaths.firstOrNull{!it.active} != null) {
components.filter { it.active || basePaths.contains(it) }.joinToString(separator = "", transform = { it.toolTipPart })
} else null)?.let {
HelpTooltip().setTitle(it).installOn(label)
}
coroutineContext.ensureActive()
label.revalidate()
label.repaint()
onBoundsChanged?.invoke()
}
private fun shrinkSimplePaths(simplePaths: List<TitlePart>, simpleWidth: Int): String? {
isClipped = simplePaths.sumOf { it.longWidth } > simpleWidth
for (i in simplePaths.size - 1 downTo 0) {
var beforeWidth = 0
var beforeString = ""
for (j in 0 until i) {
val titlePart = simplePaths[j]
beforeWidth += titlePart.longWidth
beforeString += titlePart.getLong()
}
val testWidth = simpleWidth - beforeWidth
val path = simplePaths[i]
if (testWidth < 0) continue
return when {
testWidth > path.longWidth -> beforeString + path.getLong()
testWidth > path.shortWidth -> beforeString + path.getShort()
else -> beforeString
}
}
return null
}
} | apache-2.0 | dc49569eb86cf916244997af7399708a | 28.813397 | 139 | 0.690956 | 4.846752 | false | false | false | false |
google/intellij-community | platform/workspaceModel/storage/gen/com/intellij/workspaceModel/storage/bridgeEntities/api/ModuleSourcePackagingElementEntityImpl.kt | 1 | 11405 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.workspaceModel.storage.bridgeEntities.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.SoftLinkable
import com.intellij.workspaceModel.storage.impl.UsedClassesCollector
import com.intellij.workspaceModel.storage.impl.WorkspaceEntityBase
import com.intellij.workspaceModel.storage.impl.WorkspaceEntityData
import com.intellij.workspaceModel.storage.impl.extractOneToAbstractManyParent
import com.intellij.workspaceModel.storage.impl.indices.WorkspaceMutableIndex
import com.intellij.workspaceModel.storage.impl.updateOneToAbstractManyParentOfChild
import com.intellij.workspaceModel.storage.url.VirtualFileUrl
import org.jetbrains.deft.ObjBuilder
import org.jetbrains.deft.Type
import org.jetbrains.deft.annotations.Abstract
import org.jetbrains.deft.annotations.Child
@GeneratedCodeApiVersion(1)
@GeneratedCodeImplVersion(1)
open class ModuleSourcePackagingElementEntityImpl(val dataSource: ModuleSourcePackagingElementEntityData) : ModuleSourcePackagingElementEntity, WorkspaceEntityBase() {
companion object {
internal val PARENTENTITY_CONNECTION_ID: ConnectionId = ConnectionId.create(CompositePackagingElementEntity::class.java,
PackagingElementEntity::class.java,
ConnectionId.ConnectionType.ONE_TO_ABSTRACT_MANY, true)
val connections = listOf<ConnectionId>(
PARENTENTITY_CONNECTION_ID,
)
}
override val parentEntity: CompositePackagingElementEntity?
get() = snapshot.extractOneToAbstractManyParent(PARENTENTITY_CONNECTION_ID, this)
override val module: ModuleId?
get() = dataSource.module
override fun connectionIdList(): List<ConnectionId> {
return connections
}
class Builder(val result: ModuleSourcePackagingElementEntityData?) : ModifiableWorkspaceEntityBase<ModuleSourcePackagingElementEntity>(), ModuleSourcePackagingElementEntity.Builder {
constructor() : this(ModuleSourcePackagingElementEntityData())
override fun applyToBuilder(builder: MutableEntityStorage) {
if (this.diff != null) {
if (existsInBuilder(builder)) {
this.diff = builder
return
}
else {
error("Entity ModuleSourcePackagingElementEntity is already created in a different builder")
}
}
this.diff = builder
this.snapshot = builder
addToBuilder()
this.id = getEntityData().createEntityId()
// Process linked entities that are connected without a builder
processLinkedEntities(builder)
checkInitialization() // TODO uncomment and check failed tests
}
fun checkInitialization() {
val _diff = diff
if (!getEntityData().isEntitySourceInitialized()) {
error("Field WorkspaceEntity#entitySource 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 ModuleSourcePackagingElementEntity
this.entitySource = dataSource.entitySource
this.module = dataSource.module
if (parents != null) {
this.parentEntity = parents.filterIsInstance<CompositePackagingElementEntity>().singleOrNull()
}
}
override var entitySource: EntitySource
get() = getEntityData().entitySource
set(value) {
checkModificationAllowed()
getEntityData().entitySource = value
changedProperty.add("entitySource")
}
override var parentEntity: CompositePackagingElementEntity?
get() {
val _diff = diff
return if (_diff != null) {
_diff.extractOneToAbstractManyParent(PARENTENTITY_CONNECTION_ID, this) ?: this.entityLinks[EntityLink(false,
PARENTENTITY_CONNECTION_ID)] as? CompositePackagingElementEntity
}
else {
this.entityLinks[EntityLink(false, PARENTENTITY_CONNECTION_ID)] as? CompositePackagingElementEntity
}
}
set(value) {
checkModificationAllowed()
val _diff = diff
if (_diff != null && value is ModifiableWorkspaceEntityBase<*> && value.diff == null) {
// Setting backref of the list
if (value is ModifiableWorkspaceEntityBase<*>) {
val data = (value.entityLinks[EntityLink(true, PARENTENTITY_CONNECTION_ID)] as? List<Any> ?: emptyList()) + this
value.entityLinks[EntityLink(true, PARENTENTITY_CONNECTION_ID)] = data
}
// else you're attaching a new entity to an existing entity that is not modifiable
_diff.addEntity(value)
}
if (_diff != null && (value !is ModifiableWorkspaceEntityBase<*> || value.diff != null)) {
_diff.updateOneToAbstractManyParentOfChild(PARENTENTITY_CONNECTION_ID, this, value)
}
else {
// Setting backref of the list
if (value is ModifiableWorkspaceEntityBase<*>) {
val data = (value.entityLinks[EntityLink(true, PARENTENTITY_CONNECTION_ID)] as? List<Any> ?: emptyList()) + this
value.entityLinks[EntityLink(true, PARENTENTITY_CONNECTION_ID)] = data
}
// else you're attaching a new entity to an existing entity that is not modifiable
this.entityLinks[EntityLink(false, PARENTENTITY_CONNECTION_ID)] = value
}
changedProperty.add("parentEntity")
}
override var module: ModuleId?
get() = getEntityData().module
set(value) {
checkModificationAllowed()
getEntityData().module = value
changedProperty.add("module")
}
override fun getEntityData(): ModuleSourcePackagingElementEntityData = result
?: super.getEntityData() as ModuleSourcePackagingElementEntityData
override fun getEntityClass(): Class<ModuleSourcePackagingElementEntity> = ModuleSourcePackagingElementEntity::class.java
}
}
class ModuleSourcePackagingElementEntityData : WorkspaceEntityData<ModuleSourcePackagingElementEntity>(), SoftLinkable {
var module: ModuleId? = null
override fun getLinks(): Set<PersistentEntityId<*>> {
val result = HashSet<PersistentEntityId<*>>()
val optionalLink_module = module
if (optionalLink_module != null) {
result.add(optionalLink_module)
}
return result
}
override fun index(index: WorkspaceMutableIndex<PersistentEntityId<*>>) {
val optionalLink_module = module
if (optionalLink_module != null) {
index.index(this, optionalLink_module)
}
}
override fun updateLinksIndex(prev: Set<PersistentEntityId<*>>, index: WorkspaceMutableIndex<PersistentEntityId<*>>) {
// TODO verify logic
val mutablePreviousSet = HashSet(prev)
val optionalLink_module = module
if (optionalLink_module != null) {
val removedItem_optionalLink_module = mutablePreviousSet.remove(optionalLink_module)
if (!removedItem_optionalLink_module) {
index.index(this, optionalLink_module)
}
}
for (removed in mutablePreviousSet) {
index.remove(this, removed)
}
}
override fun updateLink(oldLink: PersistentEntityId<*>, newLink: PersistentEntityId<*>): Boolean {
var changed = false
var module_data_optional = if (module != null) {
val module___data = if (module!! == oldLink) {
changed = true
newLink as ModuleId
}
else {
null
}
module___data
}
else {
null
}
if (module_data_optional != null) {
module = module_data_optional
}
return changed
}
override fun wrapAsModifiable(diff: MutableEntityStorage): ModifiableWorkspaceEntity<ModuleSourcePackagingElementEntity> {
val modifiable = ModuleSourcePackagingElementEntityImpl.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): ModuleSourcePackagingElementEntity {
return getCached(snapshot) {
val entity = ModuleSourcePackagingElementEntityImpl(this)
entity.entitySource = entitySource
entity.snapshot = snapshot
entity.id = createEntityId()
entity
}
}
override fun getEntityInterface(): Class<out WorkspaceEntity> {
return ModuleSourcePackagingElementEntity::class.java
}
override fun serialize(ser: EntityInformation.Serializer) {
}
override fun deserialize(de: EntityInformation.Deserializer) {
}
override fun createDetachedEntity(parents: List<WorkspaceEntity>): WorkspaceEntity {
return ModuleSourcePackagingElementEntity(entitySource) {
this.module = [email protected]
this.parentEntity = parents.filterIsInstance<CompositePackagingElementEntity>().singleOrNull()
}
}
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 ModuleSourcePackagingElementEntityData
if (this.entitySource != other.entitySource) return false
if (this.module != other.module) return false
return true
}
override fun equalsIgnoringEntitySource(other: Any?): Boolean {
if (other == null) return false
if (this::class != other::class) return false
other as ModuleSourcePackagingElementEntityData
if (this.module != other.module) return false
return true
}
override fun hashCode(): Int {
var result = entitySource.hashCode()
result = 31 * result + module.hashCode()
return result
}
override fun hashCodeIgnoringEntitySource(): Int {
var result = javaClass.hashCode()
result = 31 * result + module.hashCode()
return result
}
override fun collectClassUsagesData(collector: UsedClassesCollector) {
collector.add(ModuleId::class.java)
collector.sameForAllEntities = true
}
}
| apache-2.0 | 9abb0c8fec8dc1da1e88b073e5c947a8 | 36.764901 | 184 | 0.705217 | 5.668489 | false | false | false | false |
vhromada/Catalog | core/src/test/kotlin/com/github/vhromada/catalog/utils/PictureUtils.kt | 1 | 8611 | package com.github.vhromada.catalog.utils
import com.github.vhromada.catalog.entity.ChangePictureRequest
import com.github.vhromada.catalog.entity.Picture
import org.assertj.core.api.Assertions.assertThat
import org.assertj.core.api.SoftAssertions.assertSoftly
import javax.persistence.EntityManager
/**
* Updates picture fields.
*
* @return updated picture
*/
fun com.github.vhromada.catalog.domain.Picture.updated(): com.github.vhromada.catalog.domain.Picture {
content = PictureUtils.CONTENT.toByteArray()
return this
}
/**
* Updates picture fields.
*
* @return updated picture
*/
fun Picture.updated(): Picture {
return copy(content = PictureUtils.CONTENT.toByteArray())
}
/**
* A class represents utility class for pictures.
*
* @author Vladimir Hromada
*/
object PictureUtils {
/**
* Count of pictures
*/
const val PICTURES_COUNT = 6
/**
* Picture content
*/
const val CONTENT = "Picture"
/**
* Returns pictures.
*
* @return pictures
*/
fun getDomainPictures(): List<com.github.vhromada.catalog.domain.Picture> {
val pictures = mutableListOf<com.github.vhromada.catalog.domain.Picture>()
for (i in 1..PICTURES_COUNT) {
pictures.add(getDomainPicture(index = i))
}
return pictures
}
/**
* Returns pictures.
*
* @return pictures
*/
fun getPictures(): List<Picture> {
val pictures = mutableListOf<Picture>()
for (i in 1..PICTURES_COUNT) {
pictures.add(getPicture(index = i))
}
return pictures
}
/**
* Returns picture for index.
*
* @param index index
* @return picture for index
*/
fun getDomainPicture(index: Int): com.github.vhromada.catalog.domain.Picture {
return com.github.vhromada.catalog.domain.Picture(
id = index,
uuid = getUuid(index = index),
content = getContent(index = index)
).fillAudit(audit = AuditUtils.getAudit())
}
/**
* Returns UUID for index.
*
* @param index index
* @return UUID for index
*/
private fun getUuid(index: Int): String {
return when (index) {
1 -> "93d2c748-c60a-44ba-a5ca-98a090c4ab93"
2 -> "3321434e-7dcd-4471-abf9-72141f02f433"
3 -> "2ee97c4f-2de7-4783-bf8c-3a3186f6a570"
4 -> "d0e5fca5-5b80-4f78-b56c-f81509812ca1"
5 -> "64a96352-c0ee-42bd-9e20-0d4dff484c42"
6 -> "49ec0625-3143-4fbc-8da1-81ebd543c143"
else -> throw IllegalArgumentException("Bad index")
}
}
/**
* Returns content for index.
*
* @param index index
* @return content for index
*/
private fun getContent(index: Int): ByteArray {
val value = (10 + index).toString().toInt(16)
return byteArrayOf(value.toByte())
}
/**
* Returns picture.
*
* @param entityManager entity manager
* @param id picture ID
* @return picture
*/
fun getDomainPicture(entityManager: EntityManager, id: Int): com.github.vhromada.catalog.domain.Picture? {
return entityManager.find(com.github.vhromada.catalog.domain.Picture::class.java, id)
}
/**
* Returns picture for index.
*
* @param index index
* @return picture for index
*/
fun getPicture(index: Int): Picture {
return Picture(
uuid = getUuid(index = index),
content = getContent(index = index)
)
}
/**
* Returns count of pictures.
*
* @param entityManager entity manager
* @return count of pictures
*/
fun getPicturesCount(entityManager: EntityManager): Int {
return entityManager.createQuery("SELECT COUNT(p.id) FROM Picture p", java.lang.Long::class.java).singleResult.toInt()
}
/**
* Returns picture.
*
* @param id ID
* @return picture
*/
fun newDomainPicture(id: Int?): com.github.vhromada.catalog.domain.Picture {
return com.github.vhromada.catalog.domain.Picture(
id = id,
uuid = TestConstants.UUID,
content = ByteArray(0)
).updated()
}
/**
* Returns picture.
*
* @return picture
*/
fun newPicture(): Picture {
return Picture(
uuid = TestConstants.UUID,
content = ByteArray(0)
).updated()
}
/**
* Returns request for changing picture.
*
* @return request for changing picture
*/
fun newRequest(): ChangePictureRequest {
return ChangePictureRequest(content = CONTENT.toByteArray())
}
/**
* Asserts list of pictures deep equals.
*
* @param expected expected list of pictures
* @param actual actual list of pictures
*/
fun assertDomainPicturesDeepEquals(expected: List<com.github.vhromada.catalog.domain.Picture>, actual: List<com.github.vhromada.catalog.domain.Picture>) {
assertThat(expected.size).isEqualTo(actual.size)
if (expected.isNotEmpty()) {
for (i in expected.indices) {
assertPictureDeepEquals(expected = expected[i], actual = actual[i])
}
}
}
/**
* Asserts picture deep equals.
*
* @param expected expected picture
* @param actual actual picture
*/
fun assertPictureDeepEquals(expected: com.github.vhromada.catalog.domain.Picture?, actual: com.github.vhromada.catalog.domain.Picture?) {
if (expected == null) {
assertThat(actual).isNull()
} else {
assertThat(actual).isNotNull
assertSoftly {
it.assertThat(actual!!.id).isEqualTo(expected.id)
it.assertThat(actual.uuid).isEqualTo(expected.uuid)
it.assertThat(actual.content).isEqualTo(expected.content)
}
AuditUtils.assertAuditDeepEquals(expected = expected, actual = actual!!)
}
}
/**
* Asserts list of pictures deep equals.
*
* @param expected expected list of pictures
* @param actual actual list of pictures
*/
fun assertPicturesDeepEquals(expected: List<com.github.vhromada.catalog.domain.Picture>, actual: List<String>) {
assertThat(expected.size).isEqualTo(actual.size)
if (expected.isNotEmpty()) {
for (i in expected.indices) {
assertThat(actual[i]).isEqualTo(expected[i].uuid)
}
}
}
/**
* Asserts picture deep equals.
*
* @param expected expected picture
* @param actual actual picture
*/
fun assertPictureDeepEquals(expected: com.github.vhromada.catalog.domain.Picture, actual: Picture) {
assertSoftly {
it.assertThat(actual.uuid).isEqualTo(expected.uuid)
it.assertThat(actual.content).isEqualTo(expected.content)
}
}
/**
* Asserts list of pictures deep equals.
*
* @param expected expected list of pictures
* @param actual actual list of pictures
*/
fun assertPictureListDeepEquals(expected: List<Picture>, actual: List<String>) {
assertThat(expected.size).isEqualTo(actual.size)
if (expected.isNotEmpty()) {
for (i in expected.indices) {
assertThat(actual[i]).isEqualTo(expected[i].uuid)
}
}
}
/**
* Asserts picture deep equals.
*
* @param expected expected picture
* @param actual actual picture
*/
fun assertPictureDeepEquals(expected: Picture, actual: Picture) {
assertSoftly {
it.assertThat(actual.uuid).isEqualTo(expected.uuid)
it.assertThat(actual.content).isEqualTo(expected.content)
}
}
/**
* Asserts request and picture deep equals.
*
* @param expected expected request for changing picture
* @param actual actual picture
* @param uuid UUID
*/
fun assertRequestDeepEquals(expected: ChangePictureRequest, actual: com.github.vhromada.catalog.domain.Picture, uuid: String) {
assertSoftly {
it.assertThat(actual.id).isNull()
it.assertThat(actual.uuid).isEqualTo(uuid)
it.assertThat(actual.content).isEqualTo(expected.content)
it.assertThat(actual.createdUser).isNull()
it.assertThat(actual.createdTime).isNull()
it.assertThat(actual.updatedUser).isNull()
it.assertThat(actual.updatedTime).isNull()
}
}
}
| mit | c4e93b625c4dc0345a97e05d693e10d8 | 28.189831 | 158 | 0.607595 | 4.303348 | false | false | false | false |
allotria/intellij-community | python/python-features-trainer/src/com/jetbrains/python/ift/PythonLearningCourse.kt | 2 | 6292 | // 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.jetbrains.python.ift
import com.jetbrains.python.PythonLanguage
import com.jetbrains.python.ift.lesson.assistance.PythonEditorCodingAssistanceLesson
import com.jetbrains.python.ift.lesson.basic.PythonContextActionsLesson
import com.jetbrains.python.ift.lesson.basic.PythonSelectLesson
import com.jetbrains.python.ift.lesson.basic.PythonSurroundAndUnwrapLesson
import com.jetbrains.python.ift.lesson.completion.*
import com.jetbrains.python.ift.lesson.essensial.PythonOnboardingTour
import com.jetbrains.python.ift.lesson.navigation.PythonDeclarationAndUsagesLesson
import com.jetbrains.python.ift.lesson.navigation.PythonFileStructureLesson
import com.jetbrains.python.ift.lesson.navigation.PythonRecentFilesLesson
import com.jetbrains.python.ift.lesson.navigation.PythonSearchEverywhereLesson
import com.jetbrains.python.ift.lesson.refactorings.PythonInPlaceRefactoringLesson
import com.jetbrains.python.ift.lesson.refactorings.PythonQuickFixesRefactoringLesson
import com.jetbrains.python.ift.lesson.refactorings.PythonRefactorMenuLesson
import com.jetbrains.python.ift.lesson.refactorings.PythonRenameLesson
import com.jetbrains.python.ift.lesson.run.PythonDebugLesson
import com.jetbrains.python.ift.lesson.run.PythonRunConfigurationLesson
import training.dsl.LessonUtil
import training.learn.LessonsBundle
import training.learn.course.LearningCourseBase
import training.learn.course.LearningModule
import training.learn.course.LessonType
import training.learn.lesson.general.*
import training.learn.lesson.general.assistance.CodeFormatLesson
import training.learn.lesson.general.assistance.ParameterInfoLesson
import training.learn.lesson.general.assistance.QuickPopupsLesson
import training.learn.lesson.general.navigation.FindInFilesLesson
import training.learn.lesson.general.refactorings.ExtractMethodCocktailSortLesson
import training.learn.lesson.general.refactorings.ExtractVariableFromBubbleLesson
import training.util.switchOnExperimentalLessons
class PythonLearningCourse : LearningCourseBase(PythonLanguage.INSTANCE.id) {
override fun modules() = (if (switchOnExperimentalLessons) experimentalModules() else emptyList()) + stableModules()
private fun experimentalModules() = listOf(
LearningModule(name = PythonLessonsBundle.message("python.onboarding.module.name"),
description = PythonLessonsBundle.message("python.onboarding.module.description", LessonUtil.productName),
primaryLanguage = langSupport,
moduleType = LessonType.PROJECT) {
listOf(
PythonOnboardingTour(),
)
},
)
private fun stableModules() = listOf(
LearningModule(name = LessonsBundle.message("editor.basics.module.name"),
description = LessonsBundle.message("editor.basics.module.description"),
primaryLanguage = langSupport,
moduleType = LessonType.SCRATCH) {
fun ls(sampleName: String) = loadSample("EditorBasics/$sampleName")
listOf(
PythonContextActionsLesson(),
GotoActionLesson(ls("Actions.py.sample")),
PythonSelectLesson(),
SingleLineCommentLesson(ls("Comment.py.sample")),
DuplicateLesson(ls("Duplicate.py.sample")),
MoveLesson("accelerate", ls("Move.py.sample")),
CollapseLesson(ls("Collapse.py.sample")),
PythonSurroundAndUnwrapLesson(),
MultipleSelectionHtmlLesson(),
)
},
LearningModule(name = LessonsBundle.message("code.completion.module.name"),
description = LessonsBundle.message("code.completion.module.description"),
primaryLanguage = langSupport,
moduleType = LessonType.SCRATCH) {
listOf(
PythonBasicCompletionLesson(),
PythonTabCompletionLesson(),
PythonPostfixCompletionLesson(),
PythonSmartCompletionLesson(),
FStringCompletionLesson(),
)
},
LearningModule(name = LessonsBundle.message("refactorings.module.name"),
description = LessonsBundle.message("refactorings.module.description"),
primaryLanguage = langSupport,
moduleType = LessonType.SCRATCH) {
fun ls(sampleName: String) = loadSample("Refactorings/$sampleName")
listOf(
PythonRefactorMenuLesson(),
PythonRenameLesson(),
ExtractVariableFromBubbleLesson(ls("ExtractVariable.py.sample")),
ExtractMethodCocktailSortLesson(ls("ExtractMethod.py.sample")),
PythonQuickFixesRefactoringLesson(),
PythonInPlaceRefactoringLesson(),
)
},
LearningModule(name = LessonsBundle.message("code.assistance.module.name"),
description = LessonsBundle.message("code.assistance.module.description"),
primaryLanguage = langSupport,
moduleType = LessonType.SINGLE_EDITOR) {
fun ls(sampleName: String) = loadSample("CodeAssistance/$sampleName")
listOf(
CodeFormatLesson(ls("CodeFormat.py.sample"), true),
ParameterInfoLesson(ls("ParameterInfo.py.sample")),
QuickPopupsLesson(ls("QuickPopups.py.sample")),
PythonEditorCodingAssistanceLesson(ls("EditorCodingAssistance.py.sample")),
)
},
LearningModule(name = LessonsBundle.message("navigation.module.name"),
description = LessonsBundle.message("navigation.module.description"),
primaryLanguage = langSupport,
moduleType = LessonType.PROJECT) {
listOf(
PythonSearchEverywhereLesson(),
FindInFilesLesson("src/warehouse/find_in_files_sample.py"),
PythonDeclarationAndUsagesLesson(),
PythonFileStructureLesson(),
PythonRecentFilesLesson(),
)
},
LearningModule(name = LessonsBundle.message("run.debug.module.name"),
description = LessonsBundle.message("run.debug.module.description"),
primaryLanguage = langSupport,
moduleType = LessonType.SINGLE_EDITOR) {
listOf(
PythonRunConfigurationLesson(),
PythonDebugLesson(),
)
},
)
} | apache-2.0 | 31628bb81ef326a9bacf4890872acb08 | 48.551181 | 140 | 0.727114 | 5.157377 | false | false | false | false |
genonbeta/TrebleShot | app/src/main/java/org/monora/uprotocol/client/android/util/Time.kt | 1 | 4076 | /*
* Copyright (C) 2019 Veli Tasalı
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.monora.uprotocol.client.android.util
import android.content.Context
import android.text.format.DateUtils
import com.genonbeta.android.framework.util.ElapsedTime
import org.monora.uprotocol.client.android.R
import java.util.*
/**
* created by: Veli
* date: 12.11.2017 10:53
*/
object Time {
fun formatDateTime(context: Context, millis: Long): CharSequence {
return DateUtils.formatDateTime(
context,
millis,
DateUtils.FORMAT_SHOW_TIME or DateUtils.FORMAT_SHOW_DATE
)
}
fun formatDuration(time: Long, divideMilliseconds: Boolean = true): String {
val string = StringBuilder()
val calculator = ElapsedTime.Calculator(if (divideMilliseconds) time / 1000 else time)
val hours: Long = calculator.crop(3600)
val minutes: Long = calculator.crop(60)
val seconds: Long = calculator.time
if (hours > 0) {
if (hours < 10) string.append("0")
string.append(hours)
string.append(":")
}
if (minutes < 10) string.append("0")
string.append(minutes)
string.append(":")
if (seconds < 10) string.append("0")
string.append(seconds)
return string.toString()
}
fun formatRelativeTime(context: Context, time: Long): String {
val differ = ((System.currentTimeMillis() - time) / 1000).toInt()
return when {
differ == 0 -> context.getString(R.string.just_now)
differ < 60 -> context.resources.getQuantityString(R.plurals.seconds_ago, differ, differ)
differ < 3600 -> {
val minutes = differ / 60
return context.resources.getQuantityString(R.plurals.minutes_ago, minutes, minutes)
}
else -> context.getString(R.string.long_ago)
}
}
fun formatElapsedTime(context: Context, estimatedTime: Long): String {
val elapsedTime = ElapsedTime.from(estimatedTime)
val list: MutableList<String> = ArrayList()
if (elapsedTime.years > 0) list.add(context.getString(R.string.count_years_short, elapsedTime.years))
if (elapsedTime.months > 0) list.add(context.getString(R.string.count_months_short, elapsedTime.months))
if (elapsedTime.years == 0L) {
if (elapsedTime.days > 0) list.add(context.getString(R.string.count_days_short, elapsedTime.days))
if (elapsedTime.months == 0L) {
if (elapsedTime.hours > 0) list.add(context.getString(R.string.count_hours_short, elapsedTime.hours))
if (elapsedTime.days == 0L) {
if (elapsedTime.minutes > 0) {
list.add(context.getString(R.string.count_minutes_short, elapsedTime.minutes))
}
if (elapsedTime.hours == 0L) {
// always applied
list.add(context.getString(R.string.count_seconds_short, elapsedTime.seconds))
}
}
}
}
val stringBuilder = StringBuilder()
for (appendItem in list) {
if (stringBuilder.isNotEmpty()) stringBuilder.append(" ")
stringBuilder.append(appendItem)
}
return stringBuilder.toString()
}
}
| gpl-2.0 | 1f937d71d239e7e85142bfe1160c5702 | 38.95098 | 117 | 0.627485 | 4.335106 | false | false | false | false |
code-helix/slatekit | src/lib/kotlin/slatekit-requests/src/main/kotlin/slatekit/requests/InputArgs.kt | 1 | 2699 | /**
* <slate_header>
* url: www.slatekit.com
* git: www.github.com/code-helix/slatekit
* org: www.codehelix.co
* author: Kishore Reddy
* copyright: 2016 CodeHelix Solutions Inc.
* license: refer to website and/or github
* about: A tool-kit, utility library and server-backend
* mantra: Simplicity above all else
* </slate_header>
*/
package slatekit.requests
import slatekit.common.*
//import java.time.*
import org.threeten.bp.*
import slatekit.common.convert.Conversions
import slatekit.common.values.Inputs
import slatekit.common.values.InputsUpdateable
import slatekit.common.values.Metadata
/**
* Created by kishorereddy on 5/25/17.
*/
open class InputArgs(
val map: Map<String, Any>,
private val decryptor: ((String) -> String)? = null
) : Metadata, InputsUpdateable {
override val raw: Any = map
override fun toMap(): Map<String, Any> = map
override fun getString(key: String): String = Strings.decrypt(map[key].toString(), decryptor)
override fun getBool(key: String): Boolean = Conversions.toBool(map[key].toString())
override fun getShort(key: String): Short = Conversions.toShort(map[key].toString())
override fun getInt(key: String): Int = Conversions.toInt(map[key].toString())
override fun getLong(key: String): Long = Conversions.toLong(map[key].toString())
override fun getFloat(key: String): Float = Conversions.toFloat(map[key].toString())
override fun getDouble(key: String): Double = Conversions.toDouble(map[key].toString())
override fun getInstant(key: String): Instant = Conversions.toInstant(map[key].toString())
override fun getDateTime(key: String): DateTime = Conversions.toDateTime(map[key].toString())
override fun getLocalDate(key: String): LocalDate = Conversions.toLocalDate(map[key].toString())
override fun getLocalTime(key: String): LocalTime = Conversions.toLocalTime(map[key].toString())
override fun getLocalDateTime(key: String): LocalDateTime = Conversions.toLocalDateTime(map[key].toString())
override fun getZonedDateTime(key: String): ZonedDateTime = Conversions.toZonedDateTime(map[key].toString())
override fun getZonedDateTimeUtc(key: String): ZonedDateTime = Conversions.toZonedDateTimeUtc(map[key].toString())
override fun get(key: String): Any? = if (map.contains(key)) map[key] else null
//override fun getObject(key: String): Any? = if (_map.contains(key)) _map[key] else null
override fun containsKey(key: String): Boolean = map.contains(key)
override fun size(): Int = map.size
override fun add(key: String, value: Any): Inputs {
val newMap = map.plus(key to value)
return InputArgs(newMap, decryptor)
}
}
| apache-2.0 | 90e22a6fa4ee0c2bcd6a9ee19faa7d8b | 44.745763 | 118 | 0.724342 | 4.046477 | false | false | false | false |
zdary/intellij-community | plugins/filePrediction/src/com/intellij/filePrediction/features/history/FilePredictionHistory.kt | 2 | 1485 | // 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.filePrediction.features.history
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.components.service
import com.intellij.openapi.components.serviceIfCreated
import com.intellij.openapi.project.Project
class FilePredictionHistory(project: Project) {
companion object {
private const val MAX_NGRAM_SEQUENCE = 3
private const val RECENT_FILES_LIMIT = 50
internal fun getInstanceIfCreated(project: Project) = project.serviceIfCreated<FilePredictionHistory>()
fun getInstance(project: Project) = project.service<FilePredictionHistory>()
}
private var manager: FileHistoryManager
init {
val model = FileHistoryPersistence.loadNGrams(project, MAX_NGRAM_SEQUENCE)
manager = FileHistoryManager(model, FileHistoryPersistence.loadFileHistory(project), RECENT_FILES_LIMIT)
}
fun saveFilePredictionHistory(project: Project) {
ApplicationManager.getApplication().executeOnPooledThread {
manager.saveFileHistory(project)
}
}
fun onFileSelected(fileUrl: String) = manager.onFileOpened(fileUrl)
fun calcHistoryFeatures(fileUrl: String) = manager.calcHistoryFeatures(fileUrl)
fun batchCalculateNGrams(candidates: List<String>) = manager.calcNGramFeatures(candidates)
fun size() = manager.size()
fun cleanup() = manager.cleanup()
} | apache-2.0 | c15d8f27600e065aefe6bcab8564acfb | 35.243902 | 140 | 0.786532 | 4.597523 | false | false | false | false |
JuliusKunze/kotlin-native | backend.native/tests/external/codegen/box/bridges/manyTypeArgumentsSubstitutedSuccessively.kt | 5 | 587 | open class A<T, U, V> {
open fun foo(t: T, u: U, v: V) = "A"
}
open class B<T, V> : A<T, Int, V>()
open class C<V> : B<String, V>()
class Z : C<Double>() {
override fun foo(t: String, u: Int, v: Double) = "Z"
}
fun box(): String {
val z = Z()
val c: C<Double> = z
val b: B<String, Double> = z
val a: A<String, Int, Double> = z
return when {
z.foo("", 0, 0.0) != "Z" -> "Fail #1"
c.foo("", 0, 0.0) != "Z" -> "Fail #2"
b.foo("", 0, 0.0) != "Z" -> "Fail #3"
a.foo("", 0, 0.0) != "Z" -> "Fail #4"
else -> "OK"
}
}
| apache-2.0 | 88d88fafd60eae0231815f5cf08c8ceb | 21.576923 | 56 | 0.424191 | 2.35743 | false | false | false | false |
JuliusKunze/kotlin-native | backend.native/tests/external/codegen/box/multiDecl/SimpleVals.kt | 5 | 175 | class A {
operator fun component1() = 1
operator fun component2() = 2
}
fun box() : String {
val (a, b) = A()
return if (a == 1 && b == 2) "OK" else "fail"
}
| apache-2.0 | 9b8219016603db91db17c883fcb03ff5 | 18.444444 | 49 | 0.514286 | 2.868852 | false | false | false | false |
smmribeiro/intellij-community | plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/resolve/GrCodeReferenceResolver.kt | 5 | 10692 | // 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 org.jetbrains.plugins.groovy.lang.resolve
import com.intellij.psi.*
import com.intellij.psi.scope.PsiScopeProcessor
import com.intellij.psi.util.parentOfType
import org.jetbrains.plugins.groovy.lang.psi.GrReferenceElement
import org.jetbrains.plugins.groovy.lang.psi.GroovyFile
import org.jetbrains.plugins.groovy.lang.psi.api.GroovyResolveResult
import org.jetbrains.plugins.groovy.lang.psi.api.auxiliary.modifiers.annotation.GrAnnotation
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrNewExpression
import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.GrAnonymousClassDefinition
import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.GrExtendsClause
import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.GrImplementsClause
import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.GrTypeDefinition
import org.jetbrains.plugins.groovy.lang.psi.api.toplevel.imports.GrImportStatement
import org.jetbrains.plugins.groovy.lang.psi.api.types.CodeReferenceKind.*
import org.jetbrains.plugins.groovy.lang.psi.api.types.GrCodeReferenceElement
import org.jetbrains.plugins.groovy.lang.psi.api.types.GrTypeParameter
import org.jetbrains.plugins.groovy.lang.psi.impl.explicitTypeArguments
import org.jetbrains.plugins.groovy.lang.psi.util.contexts
import org.jetbrains.plugins.groovy.lang.psi.util.skipSameTypeParents
import org.jetbrains.plugins.groovy.lang.psi.util.treeWalkUp
import org.jetbrains.plugins.groovy.lang.resolve.imports.GroovyImport
import org.jetbrains.plugins.groovy.lang.resolve.imports.StarImport
import org.jetbrains.plugins.groovy.lang.resolve.imports.StaticImport
import org.jetbrains.plugins.groovy.lang.resolve.processors.ClassProcessor
import org.jetbrains.plugins.groovy.lang.resolve.processors.CollectElementsProcessor
import org.jetbrains.plugins.groovy.lang.resolve.processors.TypeParameterProcessor
// https://issues.apache.org/jira/browse/GROOVY-8358
// https://issues.apache.org/jira/browse/GROOVY-8359
// https://issues.apache.org/jira/browse/GROOVY-8361
// https://issues.apache.org/jira/browse/GROOVY-8362
// https://issues.apache.org/jira/browse/GROOVY-8364
// https://issues.apache.org/jira/browse/GROOVY-8365
internal object GrCodeReferenceResolver : GroovyResolver<GrCodeReferenceElement> {
override fun resolve(ref: GrCodeReferenceElement, incomplete: Boolean): Collection<GroovyResolveResult> {
return when (ref.kind) {
PACKAGE_REFERENCE -> ref.resolveAsPackageReference()
IMPORT_REFERENCE -> ref.resolveAsImportReference()
REFERENCE -> ref.resolveAsReference()
}
}
}
private fun GrCodeReferenceElement.resolveAsPackageReference(): Collection<GroovyResolveResult> {
val aPackage = resolvePackageFqn() ?: return emptyList()
return listOf(ElementResolveResult(aPackage))
}
private fun GrCodeReferenceElement.resolveAsImportReference(): Collection<GroovyResolveResult> {
val file = containingFile as? GroovyFile ?: return emptyList()
val statement = parentOfType<GrImportStatement>() ?: return emptyList()
val topLevelReference = statement.importReference ?: return emptyList()
val import = statement.import ?: return emptyList()
if (this === topLevelReference) {
return if (import is StaticImport) {
resolveStaticImportReference(file, import)
}
else {
resolveImportReference(file, import)
}
}
if (parent === topLevelReference && import is StaticImport) {
return resolveImportReference(file, import)
}
if (import is StarImport) {
// reference inside star import
return resolveAsPackageReference()
}
val clazz = import.resolveImport(file) as? PsiClass
val classReference = if (import is StaticImport) topLevelReference.qualifier else topLevelReference
if (clazz == null || classReference == null) return resolveAsPackageReference()
return resolveAsPartOfFqn(classReference, clazz)
}
private fun resolveStaticImportReference(file: GroovyFile, import: StaticImport): Collection<GroovyResolveResult> {
val processor = CollectElementsProcessor()
import.processDeclarations(processor, ResolveState.initial(), file, file)
return processor.results.collapseReflectedMethods().collapseAccessors().map(::ElementResolveResult)
}
private fun resolveImportReference(file: GroovyFile, import: GroovyImport): Collection<GroovyResolveResult> {
val resolved = import.resolveImport(file) ?: return emptyList()
return listOf(ElementResolveResult(resolved))
}
private fun GrCodeReferenceElement.resolveAsReference(): Collection<GroovyResolveResult> {
val name = referenceName ?: return emptyList()
if (canResolveToTypeParameter()) {
val typeParameters = resolveToTypeParameter(this, name)
if (typeParameters.isNotEmpty()) return typeParameters
}
val (_, outerMostReference) = skipSameTypeParents()
if (outerMostReference !== this) {
val fqnReferencedClass = outerMostReference.resolveClassFqn()
if (fqnReferencedClass != null) {
return resolveAsPartOfFqn(outerMostReference, fqnReferencedClass)
}
}
else if (isQualified) {
val clazz = resolveClassFqn()
if (clazz != null) {
return listOf(ClassProcessor.createResult(clazz, this, ResolveState.initial(), explicitTypeArguments))
}
}
val processor = ClassProcessor(name, this, explicitTypeArguments, isAnnotationReference())
val state = ResolveState.initial()
processClasses(processor, state)
val classes = processor.results
if (classes.isNotEmpty()) return classes
if (canResolveToPackage()) {
val packages = resolveAsPackageReference()
if (packages.isNotEmpty()) return packages
}
return emptyList()
}
private fun GrReferenceElement<*>.canResolveToTypeParameter(): Boolean {
if (isQualified) return false
val parent = parent
return when (parent) {
is GrReferenceElement<*>,
is GrExtendsClause,
is GrImplementsClause,
is GrAnnotation,
is GrImportStatement,
is GrNewExpression,
is GrAnonymousClassDefinition,
is GrCodeReferenceElement -> false
else -> true
}
}
private fun resolveToTypeParameter(place: PsiElement, name: String): Collection<GroovyResolveResult> {
val processor = TypeParameterProcessor(name)
place.treeWalkUp(processor)
return processor.results
}
private fun GrReferenceElement<*>.canResolveToPackage(): Boolean = parent is GrReferenceElement<*>
private fun GrCodeReferenceElement.resolveAsPartOfFqn(reference: GrCodeReferenceElement, clazz: PsiClass): Collection<GroovyResolveResult> {
var currentReference = reference
var currentElement: PsiNamedElement = clazz
while (currentReference !== this) {
currentReference = currentReference.qualifier ?: return emptyList()
val e: PsiNamedElement? = when (currentElement) {
is PsiClass -> currentElement.containingClass ?: currentElement.getPackage()
is PsiPackage -> currentElement.parentPackage
else -> null
}
currentElement = e ?: return emptyList()
}
return listOf(BaseGroovyResolveResult(currentElement, this))
}
private fun PsiClass.getPackage(): PsiPackage? {
val file = containingFile
val name = (file as? PsiClassOwner)?.packageName ?: return null
return JavaPsiFacade.getInstance(file.project).findPackage(name)
}
fun GrCodeReferenceElement.processClasses(processor: PsiScopeProcessor, state: ResolveState): Boolean {
val qualifier = qualifier
if (qualifier == null) {
return processUnqualified(processor, state)
}
else {
return processQualifier(qualifier, processor, state)
}
}
fun PsiElement.processUnqualified(processor: PsiScopeProcessor, state: ResolveState): Boolean {
return processInnerClasses(processor, state) &&
processFileLevelDeclarations(processor, state)
}
/**
* @see org.codehaus.groovy.control.ResolveVisitor.resolveNestedClass
*/
private fun PsiElement.processInnerClasses(processor: PsiScopeProcessor, state: ResolveState): Boolean {
val currentClass = getCurrentClass() ?: return true
if (this !is GrCodeReferenceElement || canResolveToInnerClassOfCurrentClass()) {
if (!currentClass.processInnerInHierarchy(processor, state, this)) return false
}
return currentClass.processInnersInOuters(processor, state, this)
}
/**
* @see org.codehaus.groovy.control.ResolveVisitor.resolveFromModule
* @see org.codehaus.groovy.control.ResolveVisitor.resolveFromDefaultImports
*/
private fun PsiElement.processFileLevelDeclarations(processor: PsiScopeProcessor, state: ResolveState): Boolean {
// There is no point in processing imports in dummy files.
val file = containingFile.skipDummies() ?: return true
return file.treeWalkUp(processor, state, this)
}
private fun GrCodeReferenceElement.processQualifier(qualifier: GrCodeReferenceElement,
processor: PsiScopeProcessor,
state: ResolveState): Boolean {
for (result in qualifier.multiResolve(false)) {
val clazz = result.element as? PsiClass ?: continue
if (!clazz.processDeclarations(processor, state.put(PsiSubstitutor.KEY, result.substitutor), null, this)) return false
}
return true
}
private fun GrCodeReferenceElement.canResolveToInnerClassOfCurrentClass(): Boolean {
val (_, outerMostReference) = skipSameTypeParents()
val parent = outerMostReference.getActualParent()
return parent !is GrExtendsClause &&
parent !is GrImplementsClause &&
(parent !is GrAnnotation || parent.classReference != this) // annotation's can't be inner classes of current class
}
/**
* Reference element may be created from stub. In this case containing file will be dummy, and its context will be reference parent
*/
private fun GrCodeReferenceElement.getActualParent(): PsiElement? {
val parent = parent
return (parent as? PsiFile)?.context ?: parent
}
/**
* @see org.codehaus.groovy.control.ResolveVisitor.currentClass
*/
private fun PsiElement.getCurrentClass(): GrTypeDefinition? {
for (context in contexts()) {
if (context !is GrTypeDefinition) {
continue
}
else if (context is GrTypeParameter) {
continue
}
else if (context is GrAnonymousClassDefinition && this === context.baseClassReferenceGroovy) {
continue
}
else {
return context
}
}
return null
}
private fun PsiFile?.skipDummies(): PsiFile? {
var file: PsiFile? = this
while (file != null && !file.isPhysical) {
val context = file.context
if (context == null) return file
file = context.containingFile
}
return file
}
| apache-2.0 | c84b0a5802b4755f0d705a756624d11b | 38.895522 | 140 | 0.765806 | 4.783893 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/branchedTransformations/intentions/UnfoldFunctionCallToIfIntention.kt | 4 | 3153 | // Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.intentions.branchedTransformations.intentions
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.util.TextRange
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.intentions.SelfTargetingIntention
import org.jetbrains.kotlin.idea.intentions.SelfTargetingRangeIntention
import org.jetbrains.kotlin.idea.intentions.callExpression
import org.jetbrains.kotlin.idea.util.reformatted
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.getQualifiedExpressionForSelectorOrThis
class UnfoldFunctionCallToIfIntention : SelfTargetingRangeIntention<KtCallExpression>(
KtCallExpression::class.java,
KotlinBundle.lazyMessage("replace.function.call.with.if"),
) {
override fun applicabilityRange(element: KtCallExpression): TextRange? =
if (canUnFoldToIf<KtIfExpression>(element)) element.calleeExpression?.textRange else null
override fun applyTo(element: KtCallExpression, editor: Editor?) {
unFoldToIf<KtIfExpression>(element)
}
companion object {
private inline fun <reified T: KtExpression> canUnFoldToIf(element: KtCallExpression): Boolean {
if (element.calleeExpression == null) return false
val (argument, _) = element.argumentOfType<T>() ?: return false
val branches = FoldIfToFunctionCallIntention.branches(argument) ?: return false
return branches.all { it.singleExpression() != null }
}
private inline fun <reified T: KtExpression> unFoldToIf(element: KtCallExpression) {
val (argument, argumentIndex) = element.argumentOfType<T>() ?: return
val branches = FoldIfToFunctionCallIntention.branches(argument) ?: return
val qualifiedOrCall = element.getQualifiedExpressionForSelectorOrThis()
branches.forEach {
val branchExpression = it.singleExpression() ?: return@forEach
val copied = qualifiedOrCall.copy()
val valueArguments = when (copied) {
is KtCallExpression -> copied.valueArguments
is KtQualifiedExpression -> copied.callExpression?.valueArguments
else -> null
} ?: return@forEach
valueArguments[argumentIndex]?.getArgumentExpression()?.replace(branchExpression)
branchExpression.replace(copied)
}
qualifiedOrCall.replace(argument).reformatted()
}
private inline fun <reified T: KtExpression> KtCallExpression.argumentOfType(): Pair<T, Int>? =
valueArguments.mapIndexedNotNull { index, argument ->
val expression = argument.getArgumentExpression() as? T ?: return@mapIndexedNotNull null
expression to index
}.singleOrNull()
private fun KtExpression?.singleExpression(): KtExpression? =
if (this is KtBlockExpression) this.statements.singleOrNull() else this
}
}
| apache-2.0 | 45dc087de1587f716e995c61e83b3e63 | 51.55 | 140 | 0.704726 | 5.473958 | false | false | false | false |
romannurik/muzei | main/src/main/java/com/google/android/apps/muzei/settings/AboutActivity.kt | 1 | 4063 | /*
* Copyright 2014 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.settings
import android.content.ActivityNotFoundException
import android.os.Bundle
import android.text.method.LinkMovementMethod
import android.view.View
import android.view.ViewPropertyAnimator
import androidx.appcompat.app.AppCompatActivity
import androidx.browser.customtabs.CustomTabColorSchemeParams
import androidx.browser.customtabs.CustomTabsIntent
import androidx.core.content.ContextCompat
import androidx.core.net.toUri
import androidx.core.text.HtmlCompat
import androidx.fragment.app.commit
import com.google.android.apps.muzei.render.MuzeiRendererFragment
import com.google.android.apps.muzei.util.AnimatedMuzeiLogoFragment
import net.nurik.roman.muzei.BuildConfig
import net.nurik.roman.muzei.R
import net.nurik.roman.muzei.databinding.AboutActivityBinding
class AboutActivity : AppCompatActivity() {
private lateinit var binding: AboutActivityBinding
private var animator: ViewPropertyAnimator? = null
public override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = AboutActivityBinding.inflate(layoutInflater)
setContentView(binding.root)
@Suppress("DEPRECATION")
window.decorView.systemUiVisibility = (View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
or View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
or View.SYSTEM_UI_FLAG_LAYOUT_STABLE)
binding.toolbar.setNavigationOnClickListener { onNavigateUp() }
if (savedInstanceState == null) {
supportFragmentManager.commit {
setReorderingAllowed(true)
add(R.id.demo_view_container,
MuzeiRendererFragment.createInstance(true))
}
}
// Build the about body view and append the link to see OSS licenses
binding.content.appVersion.apply {
text = getString(R.string.about_version_template, BuildConfig.VERSION_NAME)
}
binding.content.body.apply {
text = HtmlCompat.fromHtml(getString(R.string.about_body), 0)
movementMethod = LinkMovementMethod()
}
binding.content.androidExperimentLink.setOnClickListener {
val cti = CustomTabsIntent.Builder()
.setShowTitle(true)
.setDefaultColorSchemeParams(CustomTabColorSchemeParams.Builder()
.setToolbarColor(ContextCompat.getColor(this, R.color.theme_primary))
.build())
.build()
try {
cti.launchUrl(this,
"https://www.androidexperiments.com/experiment/muzei".toUri())
} catch (ignored: ActivityNotFoundException) {
}
}
}
override fun onPostCreate(savedInstanceState: Bundle?) {
super.onPostCreate(savedInstanceState)
val demoContainerView = binding.demoViewContainer.apply {
alpha = 0f
}
animator = demoContainerView.animate()
.alpha(1f)
.setStartDelay(250)
.setDuration(1000)
.withEndAction {
val logoFragment = binding.content.animatedLogoFragment
.getFragment<AnimatedMuzeiLogoFragment?>()
logoFragment?.start()
}
}
override fun onDestroy() {
animator?.cancel()
super.onDestroy()
}
} | apache-2.0 | 1d969e882659a204c4b6ac9d7c3d54a4 | 36.981308 | 97 | 0.668964 | 5.034696 | false | false | false | false |
leafclick/intellij-community | plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/codeInspection/type/highlighting/ParameterCastFix.kt | 1 | 1301 | // 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 org.jetbrains.plugins.groovy.codeInspection.type.highlighting
import com.intellij.codeInspection.ProblemDescriptor
import com.intellij.model.Pointer
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiType
import com.intellij.psi.util.createSmartPointer
import org.jetbrains.plugins.groovy.GroovyBundle
import org.jetbrains.plugins.groovy.codeInspection.GroovyFix
import org.jetbrains.plugins.groovy.codeInspection.assignment.GrCastFix
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrExpression
class ParameterCastFix(
expression: GrExpression,
position: Int,
private val myType: PsiType
) : GroovyFix() {
private val myName: String = GroovyBundle.message("parameter.cast.fix", position + 1, myType.presentableText)
override fun getName(): String = myName
override fun getFamilyName(): String = "Add parameter cast"
private val myExpression: Pointer<GrExpression> = expression.createSmartPointer()
override fun doFix(project: Project, descriptor: ProblemDescriptor) {
val expression = myExpression.dereference() ?: return
GrCastFix.doSafeCast(project, myType, expression)
}
}
| apache-2.0 | b67f4f243770c7bd0711029ff9d85e14 | 42.366667 | 140 | 0.805534 | 4.380471 | false | false | false | false |
JetBrains/intellij-community | plugins/markdown/core/src/org/intellij/plugins/markdown/fileActions/export/MarkdownExportAction.kt | 1 | 1091 | // Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.intellij.plugins.markdown.fileActions.export
import com.intellij.openapi.actionSystem.*
import com.intellij.openapi.vfs.VirtualFile
import org.intellij.plugins.markdown.lang.MarkdownFileType
internal class MarkdownExportAction: AnAction() {
override fun actionPerformed(event: AnActionEvent) {
val project = event.project ?: return
val virtualFile = getFileToConvert(event) ?: return
MarkdownExportDialog(virtualFile, virtualFile.path, project).show()
}
override fun update(event: AnActionEvent) {
event.presentation.isEnabled = getFileToConvert(event) != null
}
override fun getActionUpdateThread(): ActionUpdateThread {
return ActionUpdateThread.BGT
}
private fun getFileToConvert(event: AnActionEvent): VirtualFile? {
val file = event.getData(PlatformDataKeys.FILE_EDITOR)?.file ?: event.getData(CommonDataKeys.VIRTUAL_FILE)
return file?.takeIf { it.fileType is MarkdownFileType }
}
}
| apache-2.0 | 7e85c840b255ca4743ecc74e673c0ff0 | 37.964286 | 140 | 0.772686 | 4.564854 | false | false | false | false |
oldcwj/iPing | app/src/main/java/com/wpapper/iping/ui/folder/ItemsFragment.kt | 1 | 10545 | package com.wpapper.iping.ui.folder
import android.net.Uri
import android.os.Bundle
import android.os.Parcelable
import android.support.v4.app.Fragment
import android.support.v7.widget.DividerItemDecoration
import android.support.v7.widget.LinearLayoutManager
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.simplemobiletools.commons.dialogs.StoragePickerDialog
import com.simplemobiletools.commons.extensions.deleteFiles
import com.simplemobiletools.commons.extensions.getFilenameFromPath
import com.simplemobiletools.commons.extensions.toast
import com.simplemobiletools.commons.extensions.updateTextColors
import com.simplemobiletools.commons.models.FileDirItem
import com.simplemobiletools.commons.views.Breadcrumbs
import com.simplemobiletools.commons.views.MyScalableRecyclerView
import com.stericson.RootTools.RootTools
import com.wpapper.iping.R
import com.wpapper.iping.model.DataSave
import com.wpapper.iping.ui.dialogs.CreateNewItemDialog
import com.wpapper.iping.ui.utils.SSHManager
import com.wpapper.iping.ui.utils.exts.config
import com.wpapper.iping.ui.utils.exts.isPathOnRoot
import com.wpapper.iping.ui.utils.exts.openFile
import com.wpapper.iping.ui.utils.hub.SimpleHUD
import kotlinx.android.synthetic.main.items_fragment.*
import kotlinx.android.synthetic.main.items_fragment.view.*
import java.io.File
import java.util.HashMap
import kotlin.collections.ArrayList
class ItemsFragment : Fragment(), ItemsAdapter.ItemOperationsListener, Breadcrumbs.BreadcrumbsListener {
var currentPath = "/"
var isGetContentIntent = false
var isPickMultipleIntent = false
private var storedTextColor = 0
private var showHidden = false
private var storedItems = ArrayList<FileDirItem>()
private var scrollStates = HashMap<String, Parcelable>()
private lateinit var mView: View
var host = ""
override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View {
mView = inflater!!.inflate(R.layout.items_fragment, container, false)!!
storeConfigVariables()
return mView
}
override fun onViewCreated(view: View?, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
mView.apply {
items_swipe_refresh.setOnRefreshListener({ refreshItems() })
items_fab.setOnClickListener { createNewItem() }
breadcrumbs.listener = this@ItemsFragment
}
}
override fun onResume() {
super.onResume()
context.updateTextColors(mView as ViewGroup)
items_fab.setBackgroundColor(resources.getColor(R.color.colorPrimary))
mView.items_fastscroller.updateHandleColor()
val newColor = context.config.textColor
if (storedTextColor != newColor) {
storedItems = ArrayList()
(items_list.adapter as ItemsAdapter).updateTextColor(newColor)
mView.breadcrumbs.updateColor(newColor)
storedTextColor = newColor
}
refreshItems()
}
override fun onPause() {
super.onPause()
storeConfigVariables()
}
private fun storeConfigVariables() {
storedTextColor = context.config.textColor
}
fun openPath(path: String) {
val isRemote = (activity as FolderActivity).isRemote
if (!isAdded) {
return
}
activity.runOnUiThread {
SimpleHUD.show(activity, "Loading", true)
}
var realPath = path.trimEnd('/')
if (realPath.isEmpty())
realPath = "/"
scrollStates.put(currentPath, getScrollState())
currentPath = realPath
showHidden = context.config.shouldShowHidden
getItems(currentPath, isRemote) {
if (!isAdded)
return@getItems
FileDirItem.sorting = context.config.getFolderSorting(currentPath)
it.sort()
activity.runOnUiThread {
SimpleHUD.dismiss()
addItems(it)
}
}
}
private fun addItems(items: ArrayList<FileDirItem>) {
mView.apply {
activity?.runOnUiThread {
items_swipe_refresh?.isRefreshing = false
if (items.hashCode() == storedItems.hashCode()) {
return@runOnUiThread
}
mView.breadcrumbs.setBreadcrumb(currentPath)
storedItems = items
val currAdapter = items_list.adapter
if (currAdapter == null) {
items_list.apply {
this.adapter = ItemsAdapter(activity as SimpleActivity, storedItems, this@ItemsFragment, isPickMultipleIntent) {
itemClicked(it)
}
DividerItemDecoration(context, DividerItemDecoration.VERTICAL).apply {
setDrawable(context.resources.getDrawable(com.simplemobiletools.commons.R.drawable.divider))
addItemDecoration(this)
}
isDragSelectionEnabled = true
}
items_fastscroller.setViews(items_list, items_swipe_refresh)
setupRecyclerViewListener()
} else {
(currAdapter as ItemsAdapter).updateItems(storedItems)
val savedState = scrollStates[currentPath]
if (savedState != null) {
getRecyclerLayoutManager().onRestoreInstanceState(savedState)
} else {
getRecyclerLayoutManager().scrollToPosition(0)
}
}
}
}
}
private fun setupRecyclerViewListener() {
mView.items_list?.listener = object : MyScalableRecyclerView.MyScalableRecyclerViewListener {
override fun zoomIn() {
}
override fun zoomOut() {
}
override fun selectItem(position: Int) {
getRecyclerAdapter().selectItem(position)
}
override fun selectRange(initialSelection: Int, lastDraggedIndex: Int, minReached: Int, maxReached: Int) {
getRecyclerAdapter().selectRange(initialSelection, lastDraggedIndex, minReached, maxReached)
}
}
}
private fun getRecyclerAdapter() = (items_list.adapter as ItemsAdapter)
fun getScrollState() = getRecyclerLayoutManager().onSaveInstanceState()
private fun getRecyclerLayoutManager() = (mView.items_list.layoutManager as LinearLayoutManager)
private fun getItems(path: String, isRemote: Boolean = true, callback: (items: ArrayList<FileDirItem>) -> Unit) {
Thread({
if (!isRemote) {
// if (!context.config.enableRootAccess || !context.isPathOnRoot(path)) {
// getRegularItemsOf(path, callback)
// } else {
// RootHelpers().getFiles(activity as SimpleActivity, path, callback)
// }
getRegularItemsOf(path, callback)
} else {
Log.i("path=====", path)
host = (activity as FolderActivity).host
var sshInfo = DataSave(activity).getData(host)
if (sshInfo != null) {
callback(SSHManager.newInstance().sshLs(sshInfo, path))
}
}
}).start()
}
private fun getRegularItemsOf(path: String, callback: (items: ArrayList<FileDirItem>) -> Unit) {
val items = ArrayList<FileDirItem>()
val files = File(path).listFiles()
if (files != null) {
for (file in files) {
val curPath = file.absolutePath
val curName = curPath.getFilenameFromPath()
if (!showHidden && curName.startsWith("."))
continue
val children = getChildren(file)
val size = file.length()
items.add(FileDirItem(curPath, curName, file.isDirectory, children, size))
}
}
callback(items)
}
private fun getChildren(file: File): Int {
val fileList: Array<out String>? = file.list() ?: return 0
if (file.isDirectory) {
return if (showHidden) {
fileList!!.size
} else {
fileList!!.count { fileName -> fileName[0] != '.' }
}
}
return 0
}
private fun itemClicked(item: FileDirItem) {
if (item.isDirectory) {
openPath(item.path)
} else {
val path = item.path
if (isGetContentIntent) {
(activity as FolderActivity).pickedPath(path)
} else {
val file = File(path)
activity.openFile(Uri.fromFile(file), false)
}
}
}
private fun createNewItem() {
CreateNewItemDialog(activity as SimpleActivity, currentPath) {
if (it) {
refreshItems()
}
}
}
override fun breadcrumbClicked(id: Int) {
if (id == 0) {
StoragePickerDialog(activity, currentPath) {
index, path ->
(activity as FolderActivity).isRemote = index != 0
openPath(path)
}
} else {
val item = breadcrumbs.getChildAt(id).tag as FileDirItem
openPath(item.path)
}
}
override fun refreshItems() {
openPath(currentPath)
}
override fun deleteFiles(files: ArrayList<File>) {
val hasFolder = files.any { it.isDirectory }
if (context.isPathOnRoot(files.firstOrNull()?.absolutePath ?: context.config.internalStoragePath)) {
files.forEach {
RootTools.deleteFileOrDirectory(it.path, false)
}
} else {
(activity as SimpleActivity).deleteFiles(files, hasFolder) {
if (!it) {
activity.runOnUiThread {
activity.toast(R.string.unknown_error_occurred)
}
}
}
}
}
override fun itemLongClicked(position: Int) {
items_list.setDragSelectActive(position)
}
override fun selectedPaths(paths: ArrayList<String>) {
(activity as FolderActivity).pickedPaths(paths)
}
}
| gpl-3.0 | fed12b70ece10952509fa7a740800c76 | 33.57377 | 136 | 0.600948 | 5.220297 | false | false | false | false |
nrizzio/Signal-Android | app/src/main/java/org/thoughtcrime/securesms/conversation/quotes/MessageQuotesBottomSheet.kt | 1 | 10358 | package org.thoughtcrime.securesms.conversation.quotes
import android.annotation.SuppressLint
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.view.doOnNextLayout
import androidx.fragment.app.FragmentManager
import androidx.fragment.app.viewModels
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import org.thoughtcrime.securesms.R
import org.thoughtcrime.securesms.components.FixedRoundedCornerBottomSheetDialogFragment
import org.thoughtcrime.securesms.components.recyclerview.SmoothScrollingLinearLayoutManager
import org.thoughtcrime.securesms.conversation.ConversationAdapter
import org.thoughtcrime.securesms.conversation.colors.Colorizer
import org.thoughtcrime.securesms.conversation.colors.RecyclerViewColorizer
import org.thoughtcrime.securesms.conversation.mutiselect.MultiselectPart
import org.thoughtcrime.securesms.database.model.MessageId
import org.thoughtcrime.securesms.database.model.MessageRecord
import org.thoughtcrime.securesms.database.model.MmsMessageRecord
import org.thoughtcrime.securesms.dependencies.ApplicationDependencies
import org.thoughtcrime.securesms.giph.mp4.GiphyMp4ItemDecoration
import org.thoughtcrime.securesms.giph.mp4.GiphyMp4PlaybackController
import org.thoughtcrime.securesms.giph.mp4.GiphyMp4PlaybackPolicy
import org.thoughtcrime.securesms.giph.mp4.GiphyMp4ProjectionPlayerHolder
import org.thoughtcrime.securesms.giph.mp4.GiphyMp4ProjectionRecycler
import org.thoughtcrime.securesms.groups.GroupId
import org.thoughtcrime.securesms.groups.GroupMigrationMembershipChange
import org.thoughtcrime.securesms.linkpreview.LinkPreview
import org.thoughtcrime.securesms.mms.GlideApp
import org.thoughtcrime.securesms.recipients.Recipient
import org.thoughtcrime.securesms.recipients.RecipientId
import org.thoughtcrime.securesms.util.BottomSheetUtil
import org.thoughtcrime.securesms.util.LifecycleDisposable
import org.thoughtcrime.securesms.util.StickyHeaderDecoration
import org.thoughtcrime.securesms.util.fragments.findListener
import java.util.Locale
class MessageQuotesBottomSheet : FixedRoundedCornerBottomSheetDialogFragment() {
override val peekHeightPercentage: Float = 0.66f
override val themeResId: Int = R.style.Widget_Signal_FixedRoundedCorners_Messages
private lateinit var messageAdapter: ConversationAdapter
private val viewModel: MessageQuotesViewModel by viewModels(
factoryProducer = {
val messageId = MessageId.deserialize(arguments?.getString(KEY_MESSAGE_ID, null) ?: throw IllegalArgumentException())
val conversationRecipientId = RecipientId.from(arguments?.getString(KEY_CONVERSATION_RECIPIENT_ID, null) ?: throw IllegalArgumentException())
MessageQuotesViewModel.Factory(ApplicationDependencies.getApplication(), messageId, conversationRecipientId)
}
)
private val disposables: LifecycleDisposable = LifecycleDisposable()
private var firstRender: Boolean = true
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
val view = inflater.inflate(R.layout.message_quotes_bottom_sheet, container, false)
disposables.bindTo(viewLifecycleOwner)
return view
}
@SuppressLint("WrongThread")
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
val conversationRecipientId = RecipientId.from(arguments?.getString(KEY_CONVERSATION_RECIPIENT_ID, null) ?: throw IllegalArgumentException())
val conversationRecipient = Recipient.resolved(conversationRecipientId)
val colorizer = Colorizer()
messageAdapter = ConversationAdapter(requireContext(), viewLifecycleOwner, GlideApp.with(this), Locale.getDefault(), ConversationAdapterListener(), conversationRecipient, colorizer).apply {
setCondensedMode(true)
}
val list: RecyclerView = view.findViewById<RecyclerView>(R.id.quotes_list).apply {
layoutManager = SmoothScrollingLinearLayoutManager(requireContext(), true)
adapter = messageAdapter
itemAnimator = null
addItemDecoration(MessageQuoteHeaderDecoration(context))
doOnNextLayout {
// Adding this without waiting for a layout pass would result in an indeterminate amount of padding added to the top of the view
addItemDecoration(StickyHeaderDecoration(messageAdapter, false, false, ConversationAdapter.HEADER_TYPE_INLINE_DATE))
}
}
val recyclerViewColorizer = RecyclerViewColorizer(list)
disposables += viewModel.getMessages().subscribe { messages ->
if (messages.isEmpty()) {
dismiss()
}
messageAdapter.submitList(messages) {
if (firstRender) {
(list.layoutManager as LinearLayoutManager).scrollToPositionWithOffset(messages.size - 1, 100)
firstRender = false
} else if (!list.canScrollVertically(1)) {
list.layoutManager?.scrollToPosition(0)
}
}
recyclerViewColorizer.setChatColors(conversationRecipient.chatColors)
}
disposables += viewModel.getNameColorsMap().subscribe { map ->
colorizer.onNameColorsChanged(map)
messageAdapter.notifyItemRangeChanged(0, messageAdapter.itemCount, ConversationAdapter.PAYLOAD_NAME_COLORS)
}
initializeGiphyMp4(view.findViewById(R.id.video_container) as ViewGroup, list)
}
private fun initializeGiphyMp4(videoContainer: ViewGroup, list: RecyclerView): GiphyMp4ProjectionRecycler {
val maxPlayback = GiphyMp4PlaybackPolicy.maxSimultaneousPlaybackInConversation()
val holders = GiphyMp4ProjectionPlayerHolder.injectVideoViews(
requireContext(),
viewLifecycleOwner.lifecycle,
videoContainer,
maxPlayback
)
val callback = GiphyMp4ProjectionRecycler(holders)
GiphyMp4PlaybackController.attach(list, callback, maxPlayback)
list.addItemDecoration(GiphyMp4ItemDecoration(callback) {}, 0)
return callback
}
private fun getCallback(): Callback {
return findListener<Callback>() ?: throw IllegalStateException("Parent must implement callback interface!")
}
private fun getAdapterListener(): ConversationAdapter.ItemClickListener {
return getCallback().getConversationAdapterListener()
}
private inner class ConversationAdapterListener : ConversationAdapter.ItemClickListener by getAdapterListener() {
override fun onItemClick(item: MultiselectPart) {
dismiss()
getCallback().jumpToMessage(item.getMessageRecord())
}
override fun onItemLongClick(itemView: View, item: MultiselectPart) {
onItemClick(item)
}
override fun onQuoteClicked(messageRecord: MmsMessageRecord) {
dismiss()
getCallback().jumpToMessage(messageRecord)
}
override fun onLinkPreviewClicked(linkPreview: LinkPreview) {
dismiss()
getAdapterListener().onLinkPreviewClicked(linkPreview)
}
override fun onQuotedIndicatorClicked(messageRecord: MessageRecord) {
dismiss()
getAdapterListener().onQuotedIndicatorClicked(messageRecord)
}
override fun onReactionClicked(multiselectPart: MultiselectPart, messageId: Long, isMms: Boolean) {
dismiss()
getCallback().jumpToMessage(multiselectPart.conversationMessage.messageRecord)
}
override fun onGroupMemberClicked(recipientId: RecipientId, groupId: GroupId) {
dismiss()
getAdapterListener().onGroupMemberClicked(recipientId, groupId)
}
override fun onMessageWithRecaptchaNeededClicked(messageRecord: MessageRecord) {
dismiss()
getAdapterListener().onMessageWithRecaptchaNeededClicked(messageRecord)
}
override fun onGroupMigrationLearnMoreClicked(membershipChange: GroupMigrationMembershipChange) {
dismiss()
getAdapterListener().onGroupMigrationLearnMoreClicked(membershipChange)
}
override fun onChatSessionRefreshLearnMoreClicked() {
dismiss()
getAdapterListener().onChatSessionRefreshLearnMoreClicked()
}
override fun onBadDecryptLearnMoreClicked(author: RecipientId) {
dismiss()
getAdapterListener().onBadDecryptLearnMoreClicked(author)
}
override fun onSafetyNumberLearnMoreClicked(recipient: Recipient) {
dismiss()
getAdapterListener().onSafetyNumberLearnMoreClicked(recipient)
}
override fun onJoinGroupCallClicked() {
dismiss()
getAdapterListener().onJoinGroupCallClicked()
}
override fun onInviteFriendsToGroupClicked(groupId: GroupId.V2) {
dismiss()
getAdapterListener().onInviteFriendsToGroupClicked(groupId)
}
override fun onEnableCallNotificationsClicked() {
dismiss()
getAdapterListener().onEnableCallNotificationsClicked()
}
override fun onCallToAction(action: String) {
dismiss()
getAdapterListener().onCallToAction(action)
}
override fun onDonateClicked() {
dismiss()
getAdapterListener().onDonateClicked()
}
override fun onRecipientNameClicked(target: RecipientId) {
dismiss()
getAdapterListener().onRecipientNameClicked(target)
}
override fun onViewGiftBadgeClicked(messageRecord: MessageRecord) {
dismiss()
getAdapterListener().onViewGiftBadgeClicked(messageRecord)
}
override fun onActivatePaymentsClicked() {
dismiss()
getAdapterListener().onActivatePaymentsClicked()
}
override fun onSendPaymentClicked(recipientId: RecipientId) {
dismiss()
getAdapterListener().onSendPaymentClicked(recipientId)
}
}
interface Callback {
fun getConversationAdapterListener(): ConversationAdapter.ItemClickListener
fun jumpToMessage(messageRecord: MessageRecord)
}
companion object {
private const val KEY_MESSAGE_ID = "message_id"
private const val KEY_CONVERSATION_RECIPIENT_ID = "conversation_recipient_id"
@JvmStatic
fun show(fragmentManager: FragmentManager, messageId: MessageId, conversationRecipientId: RecipientId) {
val args = Bundle().apply {
putString(KEY_MESSAGE_ID, messageId.serialize())
putString(KEY_CONVERSATION_RECIPIENT_ID, conversationRecipientId.serialize())
}
val fragment = MessageQuotesBottomSheet().apply {
arguments = args
}
fragment.show(fragmentManager, BottomSheetUtil.STANDARD_BOTTOM_SHEET_FRAGMENT_TAG)
}
}
}
| gpl-3.0 | 1f30014353c9f6baedb97879206a7468 | 37.93985 | 193 | 0.775053 | 5.352972 | false | false | false | false |
androidx/androidx | compose/material/material/src/commonMain/kotlin/androidx/compose/material/TouchTarget.kt | 3 | 3965 | /*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.compose.material
import androidx.compose.runtime.ProvidableCompositionLocal
import androidx.compose.runtime.staticCompositionLocalOf
import androidx.compose.ui.Modifier
import androidx.compose.ui.composed
import androidx.compose.ui.layout.LayoutModifier
import androidx.compose.ui.layout.Measurable
import androidx.compose.ui.layout.MeasureResult
import androidx.compose.ui.layout.MeasureScope
import androidx.compose.ui.platform.LocalViewConfiguration
import androidx.compose.ui.platform.debugInspectorInfo
import androidx.compose.ui.unit.Constraints
import androidx.compose.ui.unit.DpSize
import kotlin.math.roundToInt
@OptIn(ExperimentalMaterialApi::class)
@Suppress("ModifierInspectorInfo")
internal fun Modifier.minimumTouchTargetSize(): Modifier = composed(
inspectorInfo = debugInspectorInfo {
name = "minimumTouchTargetSize"
// TODO: b/214589635 - surface this information through the layout inspector in a better way
// - for now just add some information to help developers debug what this size represents.
properties["README"] = "Adds outer padding to measure at least 48.dp (default) in " +
"size to disambiguate touch interactions if the element would measure smaller"
}
) {
if (LocalMinimumTouchTargetEnforcement.current) {
// TODO: consider using a hardcoded value of 48.dp instead to avoid inconsistent UI if the
// LocalViewConfiguration changes across devices / during runtime.
val size = LocalViewConfiguration.current.minimumTouchTargetSize
MinimumTouchTargetModifier(size)
} else {
Modifier
}
}
/**
* CompositionLocal that configures whether Material components that have a visual size that is
* lower than the minimum touch target size for accessibility (such as [Button]) will include
* extra space outside the component to ensure that they are accessible. If set to false there
* will be no extra space, and so it is possible that if the component is placed near the edge of
* a layout / near to another component without any padding, there will not be enough space for
* an accessible touch target.
*/
@Suppress("OPT_IN_MARKER_ON_WRONG_TARGET")
@get:ExperimentalMaterialApi
@ExperimentalMaterialApi
val LocalMinimumTouchTargetEnforcement: ProvidableCompositionLocal<Boolean> =
staticCompositionLocalOf { true }
private class MinimumTouchTargetModifier(val size: DpSize) : LayoutModifier {
override fun MeasureScope.measure(
measurable: Measurable,
constraints: Constraints
): MeasureResult {
val placeable = measurable.measure(constraints)
// Be at least as big as the minimum dimension in both dimensions
val width = maxOf(placeable.width, size.width.roundToPx())
val height = maxOf(placeable.height, size.height.roundToPx())
return layout(width, height) {
val centerX = ((width - placeable.width) / 2f).roundToInt()
val centerY = ((height - placeable.height) / 2f).roundToInt()
placeable.place(centerX, centerY)
}
}
override fun equals(other: Any?): Boolean {
val otherModifier = other as? MinimumTouchTargetModifier ?: return false
return size == otherModifier.size
}
override fun hashCode(): Int {
return size.hashCode()
}
}
| apache-2.0 | 2e58e50bdbe839b62e88d88435a60eaf | 40.736842 | 100 | 0.741488 | 4.81774 | false | false | false | false |
androidx/androidx | paging/paging-common/src/test/kotlin/androidx/paging/PagingConfigTest.kt | 3 | 1776 | /*
* Copyright 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.paging
import androidx.paging.PagingConfig.Companion.MAX_SIZE_UNBOUNDED
import org.junit.Assert.assertEquals
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.JUnit4
import kotlin.test.assertFailsWith
@RunWith(JUnit4::class)
class PagingConfigTest {
@Test
fun defaults() {
val config = PagingConfig(10)
assertEquals(10, config.pageSize)
assertEquals(30, config.initialLoadSize)
assertEquals(true, config.enablePlaceholders)
assertEquals(10, config.prefetchDistance)
assertEquals(MAX_SIZE_UNBOUNDED, config.maxSize)
}
@Test
fun requirePlaceholdersOrPrefetch() {
assertFailsWith<IllegalArgumentException> {
PagingConfig(
pageSize = 10,
enablePlaceholders = false,
prefetchDistance = 0
)
}
}
@Test
fun prefetchWindowMustFitInMaxSize() {
assertFailsWith<IllegalArgumentException> {
PagingConfig(
pageSize = 3,
prefetchDistance = 4,
maxSize = 10
)
}
}
}
| apache-2.0 | cdad43ba0adaad373340d3d43d002336 | 29.101695 | 75 | 0.667793 | 4.710875 | false | true | false | false |
androidx/androidx | compose/ui/ui/integration-tests/ui-demos/src/main/java/androidx/compose/ui/demos/viewinterop/ViewInterop.kt | 3 | 4266 | /*
* Copyright 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.compose.ui.demos.viewinterop
import android.content.Context
import android.graphics.Canvas
import android.graphics.Paint
import android.graphics.Rect
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Column
import androidx.compose.material.Button
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.demos.databinding.TestLayoutBinding
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.toArgb
import androidx.compose.ui.node.Ref
import androidx.compose.ui.viewinterop.AndroidView
import androidx.compose.ui.viewinterop.AndroidViewBinding
@Composable
fun ViewInteropDemo() {
Column {
// This is a collection of multiple ways to include Android Views in Compose UI hierarchies
// and Compose in Android ViewGroups. Note that these APIs are subject to change.
// Compose and inflate a layout with ViewBinding.
AndroidViewBinding(TestLayoutBinding::inflate) {
text1.text = "Text updated"
}
// Compose Android View.
AndroidView({ context -> TextView(context).apply { text = "This is a TextView" } })
// Compose Android View and update its size based on state. The AndroidView takes modifiers.
var size by remember { mutableStateOf(20) }
AndroidView(::View, Modifier.clickable { size += 20 }.background(Color.Blue)) { view ->
view.layoutParams = ViewGroup.LayoutParams(size, size)
}
AndroidView(::TextView) {
it.text = "This is a text in a TextView"
}
// Compose custom Android View and do remeasurements and invalidates.
val squareRef = Ref<ColoredSquareView>()
AndroidView({ ColoredSquareView(it).also { squareRef.value = it } }) {
it.size = 200
it.color = Color.Cyan
}
Button(onClick = { squareRef.value!!.size += 50 }) {
Text("Increase size of Android view")
}
val colorIndex = remember { mutableStateOf(0) }
Button(
onClick = {
colorIndex.value = (colorIndex.value + 1) % 4
squareRef.value!!.color = arrayOf(
Color.Blue, Color.LightGray, Color.Yellow, Color.Cyan
)[colorIndex.value]
}
) {
Text("Change color of Android view")
}
}
}
private class ColoredSquareView(context: Context) : View(context) {
var size: Int = 100
set(value) {
if (value != field) {
field = value
rect.set(0, 0, value, value)
requestLayout()
}
}
var color: Color = Color.Blue
set(value) {
if (value != field) {
field = value
paint.color = value.toArgb()
invalidate()
}
}
override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec)
setMeasuredDimension(size, size)
}
private var rect = Rect(0, 0, 0, 0)
private val paint = Paint()
override fun draw(canvas: Canvas) {
super.draw(canvas)
canvas.drawRect(rect, paint)
}
}
| apache-2.0 | fd5f9d96058d7c271ffa1e16f641a79d | 33.967213 | 100 | 0.66151 | 4.557692 | false | false | false | false |
iceboundrock/nextday-for-android | app/src/main/kotlin/li/ruoshi/nextday/views/DayViewHolder.kt | 1 | 8734 | package li.ruoshi.nextday.views
import android.content.Context
import android.graphics.Color
import android.graphics.Point
import android.text.TextUtils
import android.util.Log
import android.view.GestureDetector
import android.view.MotionEvent
import android.view.View
import android.view.WindowManager
import android.view.animation.AlphaAnimation
import android.view.animation.Animation
import android.view.animation.TranslateAnimation
import android.widget.ImageView
import android.widget.ProgressBar
import android.widget.TextView
import com.bumptech.glide.Glide
import li.ruoshi.nextday.NextDayApp
import li.ruoshi.nextday.R
import li.ruoshi.nextday.models.DailyInfo
import li.ruoshi.nextday.models.DayViewTextsVisibilityChangedEvent
import li.ruoshi.nextday.models.Music
import li.ruoshi.nextday.models.SongPlayer
import li.ruoshi.nextday.utils.RxBus
import org.threeten.bp.LocalDate
import org.threeten.bp.format.TextStyle
import java.util.*
import javax.inject.Inject
class DayViewHolder(val context: Context, val view: View) : IDayView {
private lateinit var dailyInfo: DailyInfo
private lateinit var dayOfMonthText: TextView
private lateinit var monthAndDayOfWeekText: TextView
private lateinit var locationText: TextView
private lateinit var artistText: TextView
private lateinit var songNameText: TextView
private lateinit var textText: TextView
private lateinit var imageOfDay: ImageView
private lateinit var authorText: TextView
private lateinit var textContainer: View
private lateinit var progressBar: ProgressBar
private lateinit var musicContainer: View
@Inject
protected lateinit var songPlayer: SongPlayer
override fun setData(dailyInfo: DailyInfo) {
this.dailyInfo = dailyInfo
updateView()
}
fun getData(): DailyInfo {
return dailyInfo
}
fun onShow() {
val anim = TranslateAnimation(-1f * view.width, 0f, 0f, 0f)
anim.duration = 100
anim.setAnimationListener(object : Animation.AnimationListener {
override fun onAnimationEnd(animation: Animation?) {
}
override fun onAnimationRepeat(animation: Animation?) {
}
override fun onAnimationStart(animation: Animation?) {
textContainer.visibility = View.VISIBLE
RxBus.default.post(DayViewTextsVisibilityChangedEvent.Visible)
}
})
textContainer.startAnimation(anim)
}
private fun updateView() {
if (dailyInfo.author != null && !TextUtils.isEmpty(dailyInfo.author!!.name)) {
authorText.text = "@${dailyInfo.author!!.name}"
}
val wm = context.getSystemService(Context.WINDOW_SERVICE) as WindowManager
val screenSize = Point()
val defaultDisplay = wm.defaultDisplay
defaultDisplay.getSize(screenSize)
val wtoh = screenSize.x.toFloat() / screenSize.y.toFloat()
val url = if (Math.abs(wtoh - (320f / 480f)) < Math.abs(wtoh - (1080f / 1920f))) {
when (screenSize.y / 480) {
0 -> dailyInfo.images.small
1 -> dailyInfo.images.big
else -> dailyInfo.images.big2x
}
} else {
when (screenSize.y / 568) {
0 or 1 -> dailyInfo.images.small568h2x
2 -> dailyInfo.images.big568h2x
else -> dailyInfo.images.big568h3x
}
}
Glide.with(context)
.load(url)
.placeholder(R.drawable.bg_placeholder)
.centerCrop()
.into(imageOfDay)
val date = LocalDate.of(
dailyInfo.dateKey / 10000,
(dailyInfo.dateKey % 10000) / 100,
dailyInfo.dateKey % 100)
this.dayOfMonthText.text = java.lang.String.format ("%02d", date.dayOfMonth)
val enUS = Locale("en", "US")
val mon = date.month.getDisplayName(TextStyle.SHORT, enUS)
val dayOfWeek = date.dayOfWeek.getDisplayName(TextStyle.SHORT, enUS)
this.monthAndDayOfWeekText.text = "$mon. $dayOfWeek".toUpperCase()
locationText.text = dailyInfo.geo.reverse
if (!dailyInfo.text.short.isNullOrEmpty()) {
textText.text = dailyInfo.text.short!!
} else {
val c1 = dailyInfo.text.comment1
val c2 = dailyInfo.text.comment2
textText.text = "$c1\n$c2"
}
textText.setBackgroundColor(Color.parseColor (dailyInfo.colors.background))
if (songPlayer.isPlaying()) {
Log.d(TAG, "song player is playing.")
updateMusicText(dailyInfo.music!!)
musicContainer.setOnClickListener({
songPlayer.stop()
})
} else {
Log.d(TAG, "song player stopped.")
if (dailyInfo.music != null) {
updateMusicText(dailyInfo.music!!)
musicContainer.setOnClickListener({
Log.d(TAG, "music container onclick.")
songPlayer.play(dailyInfo.music!!)
})
} else {
musicContainer.visibility = View.INVISIBLE
musicContainer.setOnClickListener(null)
}
}
}
private fun updateMusicText(music: Music) {
artistText.text = music.artist
songNameText.text = music.title
}
init {
NextDayApp.getObjGraph().inject(this)
dayOfMonthText = view.findViewById(R.id.dayOfMonthText) as TextView
monthAndDayOfWeekText = view.findViewById(R.id.monthAndDayOfWeekText) as TextView
locationText = view.findViewById(R.id.locationText) as TextView
artistText = view.findViewById(R.id.artistText) as TextView
songNameText = view.findViewById(R.id.songNameText) as TextView
textText = view.findViewById(R.id.textText) as TextView
imageOfDay = view.findViewById(R.id.image_of_day) as ImageView
authorText = view.findViewById(R.id.authorText) as TextView
textContainer = view.findViewById(R.id.textContainer)
progressBar = view.findViewById(R.id.progress_bar) as ProgressBar
musicContainer = view.findViewById(R.id.music_container)
RxBus.default.register(SongPlayer::class.java, context).subscribe({
if (it.isPlaying()) {
updateMusicText(it.getMusic())
if (it.getMusic().url.equals(dailyInfo.music!!.url)) {
} else {
}
} else if (dailyInfo != null && dailyInfo.music != null) {
updateMusicText(dailyInfo.music!!)
}
})
val gd = GestureDetector(context, object : GestureDetector.SimpleOnGestureListener() {
override fun onDown(e: MotionEvent?): Boolean {
return true
}
override fun onSingleTapUp(e: MotionEvent?): Boolean {
if (textContainer.visibility == View.VISIBLE) {
onHide()
} else {
RxBus.default.post(DayViewTextsVisibilityChangedEvent.Visible)
val anim = AlphaAnimation(0f, 1f)
anim.duration = 200
anim.setAnimationListener(object : Animation.AnimationListener {
override fun onAnimationEnd(animation: Animation?) {
}
override fun onAnimationRepeat(animation: Animation?) {
}
override fun onAnimationStart(animation: Animation?) {
textContainer.visibility = android.view.View.VISIBLE
}
})
textContainer.startAnimation(anim)
}
return true
}
})
imageOfDay.setOnTouchListener({ v, motionEvent -> gd.onTouchEvent(motionEvent) })
}
companion object {
const val TAG = "DayViewHolder"
}
fun onHide(shouldNotify: Boolean = true) {
if (shouldNotify) {
RxBus.default.post(DayViewTextsVisibilityChangedEvent.Gone)
}
val anim = AlphaAnimation(1f, 0f)
anim.duration = 200
anim.setAnimationListener(object : Animation.AnimationListener {
override fun onAnimationEnd(animation: Animation?) {
textContainer.visibility = android.view.View.GONE
}
override fun onAnimationRepeat(animation: Animation?) {
}
override fun onAnimationStart(animation: Animation?) {
}
})
textContainer.startAnimation(anim)
}
} | apache-2.0 | 7511502377d651ea7dc0d1e493a9253b | 33.525692 | 94 | 0.616441 | 4.937253 | false | false | false | false |
androidx/androidx | compose/foundation/foundation/src/commonMain/kotlin/androidx/compose/foundation/lazy/LazyListMeasure.kt | 3 | 21521 | /*
* Copyright 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.compose.foundation.lazy
import androidx.compose.foundation.fastFilter
import androidx.compose.foundation.gestures.Orientation
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.ui.layout.MeasureResult
import androidx.compose.ui.layout.Placeable
import androidx.compose.ui.unit.Constraints
import androidx.compose.ui.unit.Density
import androidx.compose.ui.unit.LayoutDirection
import androidx.compose.ui.unit.constrainHeight
import androidx.compose.ui.unit.constrainWidth
import androidx.compose.ui.util.fastForEach
import kotlin.math.abs
import kotlin.math.min
import kotlin.math.roundToInt
import kotlin.math.sign
/**
* Measures and calculates the positions for the requested items. The result is produced
* as a [LazyListMeasureResult] which contains all the calculations.
*/
internal fun measureLazyList(
itemsCount: Int,
itemProvider: LazyMeasuredItemProvider,
mainAxisAvailableSize: Int,
beforeContentPadding: Int,
afterContentPadding: Int,
spaceBetweenItems: Int,
firstVisibleItemIndex: DataIndex,
firstVisibleItemScrollOffset: Int,
scrollToBeConsumed: Float,
constraints: Constraints,
isVertical: Boolean,
headerIndexes: List<Int>,
verticalArrangement: Arrangement.Vertical?,
horizontalArrangement: Arrangement.Horizontal?,
reverseLayout: Boolean,
density: Density,
placementAnimator: LazyListItemPlacementAnimator,
beyondBoundsInfo: LazyListBeyondBoundsInfo,
beyondBoundsItemCount: Int,
layout: (Int, Int, Placeable.PlacementScope.() -> Unit) -> MeasureResult
): LazyListMeasureResult {
require(beforeContentPadding >= 0)
require(afterContentPadding >= 0)
if (itemsCount <= 0) {
// empty data set. reset the current scroll and report zero size
return LazyListMeasureResult(
firstVisibleItem = null,
firstVisibleItemScrollOffset = 0,
canScrollForward = false,
consumedScroll = 0f,
measureResult = layout(constraints.minWidth, constraints.minHeight) {},
visibleItemsInfo = emptyList(),
viewportStartOffset = -beforeContentPadding,
viewportEndOffset = mainAxisAvailableSize + afterContentPadding,
totalItemsCount = 0,
reverseLayout = reverseLayout,
orientation = if (isVertical) Orientation.Vertical else Orientation.Horizontal,
afterContentPadding = afterContentPadding
)
} else {
var currentFirstItemIndex = firstVisibleItemIndex
var currentFirstItemScrollOffset = firstVisibleItemScrollOffset
if (currentFirstItemIndex.value >= itemsCount) {
// the data set has been updated and now we have less items that we were
// scrolled to before
currentFirstItemIndex = DataIndex(itemsCount - 1)
currentFirstItemScrollOffset = 0
}
// represents the real amount of scroll we applied as a result of this measure pass.
var scrollDelta = scrollToBeConsumed.roundToInt()
// applying the whole requested scroll offset. we will figure out if we can't consume
// all of it later
currentFirstItemScrollOffset -= scrollDelta
// if the current scroll offset is less than minimally possible
if (currentFirstItemIndex == DataIndex(0) && currentFirstItemScrollOffset < 0) {
scrollDelta += currentFirstItemScrollOffset
currentFirstItemScrollOffset = 0
}
// this will contain all the MeasuredItems representing the visible items
val visibleItems = mutableListOf<LazyMeasuredItem>()
// define min and max offsets
val minOffset = -beforeContentPadding + if (spaceBetweenItems < 0) spaceBetweenItems else 0
val maxOffset = mainAxisAvailableSize
// include the start padding so we compose items in the padding area and neutralise item
// spacing (if the spacing is negative this will make sure the previous item is composed)
// before starting scrolling forward we will remove it back
currentFirstItemScrollOffset += minOffset
// max of cross axis sizes of all visible items
var maxCrossAxis = 0
// we had scrolled backward or we compose items in the start padding area, which means
// items before current firstItemScrollOffset should be visible. compose them and update
// firstItemScrollOffset
while (currentFirstItemScrollOffset < 0 && currentFirstItemIndex > DataIndex(0)) {
val previous = DataIndex(currentFirstItemIndex.value - 1)
val measuredItem = itemProvider.getAndMeasure(previous)
visibleItems.add(0, measuredItem)
maxCrossAxis = maxOf(maxCrossAxis, measuredItem.crossAxisSize)
currentFirstItemScrollOffset += measuredItem.sizeWithSpacings
currentFirstItemIndex = previous
}
// if we were scrolled backward, but there were not enough items before. this means
// not the whole scroll was consumed
if (currentFirstItemScrollOffset < minOffset) {
scrollDelta += currentFirstItemScrollOffset
currentFirstItemScrollOffset = minOffset
}
// neutralize previously added padding as we stopped filling the before content padding
currentFirstItemScrollOffset -= minOffset
var index = currentFirstItemIndex
val maxMainAxis = (maxOffset + afterContentPadding).coerceAtLeast(0)
var currentMainAxisOffset = -currentFirstItemScrollOffset
// first we need to skip items we already composed while composing backward
visibleItems.fastForEach {
index++
currentMainAxisOffset += it.sizeWithSpacings
}
// then composing visible items forward until we fill the whole viewport.
// we want to have at least one item in visibleItems even if in fact all the items are
// offscreen, this can happen if the content padding is larger than the available size.
while (index.value < itemsCount &&
(currentMainAxisOffset < maxMainAxis ||
currentMainAxisOffset <= 0 || // filling beforeContentPadding area
visibleItems.isEmpty())
) {
val measuredItem = itemProvider.getAndMeasure(index)
currentMainAxisOffset += measuredItem.sizeWithSpacings
if (currentMainAxisOffset <= minOffset && index.value != itemsCount - 1) {
// this item is offscreen and will not be placed. advance firstVisibleItemIndex
currentFirstItemIndex = index + 1
currentFirstItemScrollOffset -= measuredItem.sizeWithSpacings
} else {
maxCrossAxis = maxOf(maxCrossAxis, measuredItem.crossAxisSize)
visibleItems.add(measuredItem)
}
index++
}
// we didn't fill the whole viewport with items starting from firstVisibleItemIndex.
// lets try to scroll back if we have enough items before firstVisibleItemIndex.
if (currentMainAxisOffset < maxOffset) {
val toScrollBack = maxOffset - currentMainAxisOffset
currentFirstItemScrollOffset -= toScrollBack
currentMainAxisOffset += toScrollBack
while (currentFirstItemScrollOffset < beforeContentPadding &&
currentFirstItemIndex > DataIndex(0)
) {
val previousIndex = DataIndex(currentFirstItemIndex.value - 1)
val measuredItem = itemProvider.getAndMeasure(previousIndex)
visibleItems.add(0, measuredItem)
maxCrossAxis = maxOf(maxCrossAxis, measuredItem.crossAxisSize)
currentFirstItemScrollOffset += measuredItem.sizeWithSpacings
currentFirstItemIndex = previousIndex
}
scrollDelta += toScrollBack
if (currentFirstItemScrollOffset < 0) {
scrollDelta += currentFirstItemScrollOffset
currentMainAxisOffset += currentFirstItemScrollOffset
currentFirstItemScrollOffset = 0
}
}
// report the amount of pixels we consumed. scrollDelta can be smaller than
// scrollToBeConsumed if there were not enough items to fill the offered space or it
// can be larger if items were resized, or if, for example, we were previously
// displaying the item 15, but now we have only 10 items in total in the data set.
val consumedScroll = if (scrollToBeConsumed.roundToInt().sign == scrollDelta.sign &&
abs(scrollToBeConsumed.roundToInt()) >= abs(scrollDelta)
) {
scrollDelta.toFloat()
} else {
scrollToBeConsumed
}
// the initial offset for items from visibleItems list
require(currentFirstItemScrollOffset >= 0)
val visibleItemsScrollOffset = -currentFirstItemScrollOffset
var firstItem = visibleItems.first()
// even if we compose items to fill before content padding we should ignore items fully
// located there for the state's scroll position calculation (first item + first offset)
if (beforeContentPadding > 0 || spaceBetweenItems < 0) {
for (i in visibleItems.indices) {
val size = visibleItems[i].sizeWithSpacings
if (currentFirstItemScrollOffset != 0 && size <= currentFirstItemScrollOffset &&
i != visibleItems.lastIndex
) {
currentFirstItemScrollOffset -= size
firstItem = visibleItems[i + 1]
} else {
break
}
}
}
// Compose extra items before
val extraItemsBefore = createItemsBeforeList(
beyondBoundsInfo = beyondBoundsInfo,
currentFirstItemIndex = currentFirstItemIndex,
itemProvider = itemProvider,
itemsCount = itemsCount,
beyondBoundsItemCount = beyondBoundsItemCount
)
// Update maxCrossAxis with extra items
extraItemsBefore.fastForEach {
maxCrossAxis = maxOf(maxCrossAxis, it.crossAxisSize)
}
// Compose items after last item
val extraItemsAfter = createItemsAfterList(
beyondBoundsInfo = beyondBoundsInfo,
visibleItems = visibleItems,
itemProvider = itemProvider,
itemsCount = itemsCount,
beyondBoundsItemCount = beyondBoundsItemCount
)
// Update maxCrossAxis with extra items
extraItemsAfter.fastForEach {
maxCrossAxis = maxOf(maxCrossAxis, it.crossAxisSize)
}
val noExtraItems = firstItem == visibleItems.first() &&
extraItemsBefore.isEmpty() &&
extraItemsAfter.isEmpty()
val layoutWidth =
constraints.constrainWidth(if (isVertical) maxCrossAxis else currentMainAxisOffset)
val layoutHeight =
constraints.constrainHeight(if (isVertical) currentMainAxisOffset else maxCrossAxis)
val positionedItems = calculateItemsOffsets(
items = visibleItems,
extraItemsBefore = extraItemsBefore,
extraItemsAfter = extraItemsAfter,
layoutWidth = layoutWidth,
layoutHeight = layoutHeight,
finalMainAxisOffset = currentMainAxisOffset,
maxOffset = maxOffset,
itemsScrollOffset = visibleItemsScrollOffset,
isVertical = isVertical,
verticalArrangement = verticalArrangement,
horizontalArrangement = horizontalArrangement,
reverseLayout = reverseLayout,
density = density,
)
placementAnimator.onMeasured(
consumedScroll = consumedScroll.toInt(),
layoutWidth = layoutWidth,
layoutHeight = layoutHeight,
reverseLayout = reverseLayout,
positionedItems = positionedItems,
itemProvider = itemProvider
)
val headerItem = if (headerIndexes.isNotEmpty()) {
findOrComposeLazyListHeader(
composedVisibleItems = positionedItems,
itemProvider = itemProvider,
headerIndexes = headerIndexes,
beforeContentPadding = beforeContentPadding,
layoutWidth = layoutWidth,
layoutHeight = layoutHeight
)
} else {
null
}
return LazyListMeasureResult(
firstVisibleItem = firstItem,
firstVisibleItemScrollOffset = currentFirstItemScrollOffset,
canScrollForward = index.value < itemsCount || currentMainAxisOffset > maxOffset,
consumedScroll = consumedScroll,
measureResult = layout(layoutWidth, layoutHeight) {
positionedItems.fastForEach {
if (it !== headerItem) {
it.place(this)
}
}
// the header item should be placed (drawn) after all other items
headerItem?.place(this)
},
viewportStartOffset = -beforeContentPadding,
viewportEndOffset = maxOffset + afterContentPadding,
visibleItemsInfo = if (noExtraItems) positionedItems else positionedItems.fastFilter {
(it.index >= visibleItems.first().index && it.index <= visibleItems.last().index) ||
it === headerItem
},
totalItemsCount = itemsCount,
reverseLayout = reverseLayout,
orientation = if (isVertical) Orientation.Vertical else Orientation.Horizontal,
afterContentPadding = afterContentPadding
)
}
}
private fun createItemsAfterList(
beyondBoundsInfo: LazyListBeyondBoundsInfo,
visibleItems: MutableList<LazyMeasuredItem>,
itemProvider: LazyMeasuredItemProvider,
itemsCount: Int,
beyondBoundsItemCount: Int
): List<LazyMeasuredItem> {
fun LazyListBeyondBoundsInfo.endIndex() = min(end, itemsCount - 1)
fun addItemsAfter(startIndex: Int, endIndex: Int): List<LazyMeasuredItem> {
return mutableListOf<LazyMeasuredItem>().apply {
for (i in startIndex until endIndex) {
val item = itemProvider.getAndMeasure(DataIndex(i + 1))
add(item)
}
}
}
val (startNonVisibleItems, endNonVisibleItems) = if (beyondBoundsItemCount != 0 &&
visibleItems.last().index + beyondBoundsItemCount <= itemsCount - 1
) {
visibleItems.last().index to visibleItems.last().index + beyondBoundsItemCount
} else {
EmptyRange
}
val (startBeyondBoundItems, endBeyondBoundItems) = if (beyondBoundsInfo.hasIntervals() &&
visibleItems.last().index < beyondBoundsInfo.endIndex()
) {
val start = (visibleItems.last().index + beyondBoundsItemCount).coerceAtMost(itemsCount - 1)
val end =
(beyondBoundsInfo.endIndex() + beyondBoundsItemCount).coerceAtMost(itemsCount - 1)
start to end
} else {
EmptyRange
}
return if (startNonVisibleItems.notInEmptyRange && startBeyondBoundItems.notInEmptyRange) {
addItemsAfter(
startNonVisibleItems,
endBeyondBoundItems
)
} else if (startNonVisibleItems.notInEmptyRange) {
addItemsAfter(startNonVisibleItems, endNonVisibleItems)
} else if (startBeyondBoundItems.notInEmptyRange) {
addItemsAfter(startBeyondBoundItems, endBeyondBoundItems)
} else {
emptyList()
}
}
private fun createItemsBeforeList(
beyondBoundsInfo: LazyListBeyondBoundsInfo,
currentFirstItemIndex: DataIndex,
itemProvider: LazyMeasuredItemProvider,
itemsCount: Int,
beyondBoundsItemCount: Int
): List<LazyMeasuredItem> {
fun LazyListBeyondBoundsInfo.startIndex() = min(start, itemsCount - 1)
fun addItemsBefore(startIndex: Int, endIndex: Int): List<LazyMeasuredItem> {
return mutableListOf<LazyMeasuredItem>().apply {
for (i in startIndex downTo endIndex) {
val item = itemProvider.getAndMeasure(DataIndex(i))
add(item)
}
}
}
val (startNonVisibleItems, endNonVisibleItems) =
if (beyondBoundsItemCount != 0 && currentFirstItemIndex.value - beyondBoundsItemCount > 0) {
currentFirstItemIndex.value - 1 to currentFirstItemIndex.value - beyondBoundsItemCount
} else {
EmptyRange
}
val (startBeyondBoundItems, endBeyondBoundItems) = if (beyondBoundsInfo.hasIntervals() &&
currentFirstItemIndex.value > beyondBoundsInfo.startIndex()
) {
val start =
(currentFirstItemIndex.value - beyondBoundsItemCount - 1).coerceAtLeast(0)
val end = (beyondBoundsInfo.startIndex() - beyondBoundsItemCount).coerceAtLeast(0)
start to end
} else {
EmptyRange
}
return if (startNonVisibleItems.notInEmptyRange && startBeyondBoundItems.notInEmptyRange) {
addItemsBefore(
startNonVisibleItems,
endBeyondBoundItems
)
} else if (startNonVisibleItems.notInEmptyRange) {
addItemsBefore(startNonVisibleItems, endNonVisibleItems)
} else if (startBeyondBoundItems.notInEmptyRange) {
addItemsBefore(startBeyondBoundItems, endBeyondBoundItems)
} else {
emptyList()
}
}
/**
* Calculates [LazyMeasuredItem]s offsets.
*/
private fun calculateItemsOffsets(
items: List<LazyMeasuredItem>,
extraItemsBefore: List<LazyMeasuredItem>,
extraItemsAfter: List<LazyMeasuredItem>,
layoutWidth: Int,
layoutHeight: Int,
finalMainAxisOffset: Int,
maxOffset: Int,
itemsScrollOffset: Int,
isVertical: Boolean,
verticalArrangement: Arrangement.Vertical?,
horizontalArrangement: Arrangement.Horizontal?,
reverseLayout: Boolean,
density: Density,
): MutableList<LazyListPositionedItem> {
val mainAxisLayoutSize = if (isVertical) layoutHeight else layoutWidth
val hasSpareSpace = finalMainAxisOffset < minOf(mainAxisLayoutSize, maxOffset)
if (hasSpareSpace) {
check(itemsScrollOffset == 0)
}
val positionedItems =
ArrayList<LazyListPositionedItem>(items.size + extraItemsBefore.size + extraItemsAfter.size)
if (hasSpareSpace) {
require(extraItemsBefore.isEmpty() && extraItemsAfter.isEmpty())
val itemsCount = items.size
fun Int.reverseAware() =
if (!reverseLayout) this else itemsCount - this - 1
val sizes = IntArray(itemsCount) { index ->
items[index.reverseAware()].size
}
val offsets = IntArray(itemsCount) { 0 }
if (isVertical) {
with(requireNotNull(verticalArrangement)) {
density.arrange(mainAxisLayoutSize, sizes, offsets)
}
} else {
with(requireNotNull(horizontalArrangement)) {
// Enforces Ltr layout direction as it is mirrored with placeRelative later.
density.arrange(mainAxisLayoutSize, sizes, LayoutDirection.Ltr, offsets)
}
}
val reverseAwareOffsetIndices =
if (!reverseLayout) offsets.indices else offsets.indices.reversed()
for (index in reverseAwareOffsetIndices) {
val absoluteOffset = offsets[index]
// when reverseLayout == true, offsets are stored in the reversed order to items
val item = items[index.reverseAware()]
val relativeOffset = if (reverseLayout) {
// inverse offset to align with scroll direction for positioning
mainAxisLayoutSize - absoluteOffset - item.size
} else {
absoluteOffset
}
positionedItems.add(item.position(relativeOffset, layoutWidth, layoutHeight))
}
} else {
var currentMainAxis = itemsScrollOffset
extraItemsBefore.fastForEach {
currentMainAxis -= it.sizeWithSpacings
positionedItems.add(it.position(currentMainAxis, layoutWidth, layoutHeight))
}
currentMainAxis = itemsScrollOffset
items.fastForEach {
positionedItems.add(it.position(currentMainAxis, layoutWidth, layoutHeight))
currentMainAxis += it.sizeWithSpacings
}
extraItemsAfter.fastForEach {
positionedItems.add(it.position(currentMainAxis, layoutWidth, layoutHeight))
currentMainAxis += it.sizeWithSpacings
}
}
return positionedItems
}
private val EmptyRange = Int.MIN_VALUE to Int.MIN_VALUE
private val Int.notInEmptyRange
get() = this != Int.MIN_VALUE | apache-2.0 | 6068665af71a59af2abacbd162c3f112 | 40.309021 | 100 | 0.660332 | 6.147101 | false | false | false | false |
androidx/androidx | wear/compose/integration-tests/demos/src/main/java/androidx/wear/compose/integration/demos/ChipDemo.kt | 3 | 30387 | /*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.wear.compose.integration.demos
import android.widget.Toast
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.BoxScope
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.layout.wrapContentSize
import androidx.compose.foundation.layout.wrapContentWidth
import androidx.compose.foundation.shape.CutCornerShape
import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.Shape
import androidx.compose.ui.graphics.compositeOver
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalLayoutDirection
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.LayoutDirection
import androidx.compose.ui.unit.dp
import androidx.wear.compose.material.Chip
import androidx.wear.compose.material.ChipColors
import androidx.wear.compose.material.ChipDefaults
import androidx.wear.compose.material.CompactChip
import androidx.wear.compose.material.Icon
import androidx.wear.compose.material.ListHeader
import androidx.wear.compose.material.LocalContentColor
import androidx.wear.compose.material.MaterialTheme
import androidx.wear.compose.material.OutlinedChip
import androidx.wear.compose.material.OutlinedCompactChip
import androidx.wear.compose.material.ScalingLazyColumn
import androidx.wear.compose.material.Text
import androidx.wear.compose.material.ToggleButton
import androidx.wear.compose.material.ToggleChip
import androidx.wear.compose.material.ToggleChipDefaults
@Composable
fun StandardChips() {
var enabled by remember { mutableStateOf(true) }
var chipStyle by remember { mutableStateOf(ChipStyle.Primary) }
ScalingLazyColumnWithRSB(
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.spacedBy(4.dp, Alignment.CenterVertically),
) {
item {
Text(
text = "Chip with Label",
textAlign = TextAlign.Center,
style = MaterialTheme.typography.caption1,
color = Color.White
)
}
item {
DemoLabelChip(
style = chipStyle,
label = "Single Label",
colors = chipColors(chipStyle),
enabled = enabled,
)
}
item {
DemoLabelChip(
style = chipStyle,
label = "Standard chip with long label to show truncation which does not fit into" +
" 2 lines",
colors = chipColors(chipStyle),
enabled = enabled,
)
}
item {
Text(
"Chip with icon",
textAlign = TextAlign.Center,
style = MaterialTheme.typography.caption1
)
}
item {
DemoIconChip(
style = chipStyle,
colors = chipColors(chipStyle),
label = "Label with icon",
enabled = enabled,
) { DemoIcon(resourceId = R.drawable.ic_accessibility_24px) }
}
item {
DemoIconChip(
style = chipStyle,
colors = chipColors(chipStyle),
label = "Long label to show truncation which does not fit into" +
" 2 lines",
enabled = enabled,
) { DemoIcon(resourceId = R.drawable.ic_accessibility_24px) }
}
item {
Text(
"Main + Secondary label",
textAlign = TextAlign.Center,
style = MaterialTheme.typography.caption1
)
}
item {
DemoLabelChip(
style = chipStyle,
label = "Main label and",
secondaryLabel = "Secondary label",
colors = chipColors(chipStyle),
enabled = enabled,
)
}
item {
DemoLabelChip(
style = chipStyle,
label = "Long label to show truncation which does not fit into" +
" 1 line",
secondaryLabel = "Secondary Label",
colors = chipColors(chipStyle),
enabled = enabled,
)
}
item {
DemoIconChip(
style = chipStyle,
colors = chipColors(chipStyle),
label = "Label with icon and",
secondaryLabel = "Secondary Label",
enabled = enabled,
) { DemoIcon(resourceId = R.drawable.ic_accessibility_24px) }
}
item {
DemoIconChip(
style = chipStyle,
colors = chipColors(chipStyle),
label = "Long label with truncation",
secondaryLabel = "Long secondary label to show truncation which does not fit into" +
"1 line",
enabled = enabled,
) { DemoIcon(resourceId = R.drawable.ic_accessibility_24px) }
}
item {
DemoLabelChip(
style = chipStyle,
label = "Chip with custom shape",
colors = chipColors(chipStyle),
enabled = enabled,
shape = CutCornerShape(4.dp)
)
}
item {
ChipCustomizer(
enabled = enabled,
chipStyle = chipStyle,
onChipStyleChanged = { chipStyle = it },
onEnabledChanged = { enabled = it },
)
}
}
}
@Composable
fun SmallChips() {
var enabled by remember { mutableStateOf(true) }
var chipStyle by remember { mutableStateOf(ChipStyle.Primary) }
ScalingLazyColumn(
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.spacedBy(4.dp, Alignment.CenterVertically),
contentPadding = PaddingValues(
start = 8.dp,
end = 8.dp,
top = 15.dp,
bottom = 50.dp
)
) {
item {
Text(
text = "Compact Chip",
textAlign = TextAlign.Center,
style = MaterialTheme.typography.body2,
color = Color.White
)
}
item {
DemoIconCompactChip(
onClick = {},
colors = chipColors(chipStyle),
label = "Label",
enabled = enabled,
style = chipStyle
)
}
item {
DemoIconCompactChip(
onClick = {},
colors = chipColors(chipStyle),
label = "Long label to show truncation which does not fit into 1 line",
enabled = enabled,
style = chipStyle
)
}
item {
DemoIconCompactChip(
onClick = {},
colors = chipColors(chipStyle),
label = "Label with icon",
enabled = enabled,
style = chipStyle
) {
DemoIcon(
resourceId = R.drawable.ic_accessibility_24px,
modifier = Modifier
.size(ChipDefaults.SmallIconSize)
.wrapContentSize(align = Alignment.Center)
)
}
}
item {
DemoIconCompactChip(
onClick = {},
colors = chipColors(chipStyle),
label =
"Label with icon to show truncation which does not fit into 1 line",
enabled = enabled,
style = chipStyle
) {
DemoIcon(
resourceId = R.drawable.ic_accessibility_24px,
modifier = Modifier
.size(ChipDefaults.SmallIconSize)
.wrapContentSize(align = Alignment.Center)
)
}
}
item {
DemoIconCompactChip(
onClick = {},
colors = chipColors(chipStyle),
label = "Compact Chip with custom shape",
enabled = enabled,
style = chipStyle,
shape = CutCornerShape(4.dp)
)
}
item {
ChipCustomizer(
enabled = enabled,
chipStyle = chipStyle,
onChipStyleChanged = { chipStyle = it },
onEnabledChanged = { enabled = it },
)
}
}
}
@Composable
fun AvatarChips() {
var enabled by remember { mutableStateOf(true) }
ScalingLazyColumn(
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.spacedBy(4.dp, Alignment.CenterVertically),
) {
item {
ListHeader {
Text(text = "Chips with avatars")
}
}
item {
DemoIconChip(
style = ChipStyle.Secondary,
label = "Chip with text icon",
colors = ChipDefaults.secondaryChipColors(),
enabled = enabled,
) {
TextIcon(
text = "M",
size = ChipDefaults.LargeIconSize,
style = MaterialTheme.typography.title3
)
}
}
item {
DemoIconChip(
style = ChipStyle.Secondary,
label = "Chip with text icon",
secondaryLabel = "And secondary label",
colors = ChipDefaults.secondaryChipColors(),
enabled = enabled,
) {
TextIcon(
text = "M",
size = ChipDefaults.LargeIconSize,
style = MaterialTheme.typography.title3
)
}
}
item {
ListHeader {
Text(text = "Small Avatar Chips")
}
}
item {
DemoIconChip(
style = ChipStyle.Secondary,
label = "App Title",
secondaryLabel = "Defaults",
colors = ChipDefaults.secondaryChipColors(),
enabled = enabled,
) {
DemoImage(resourceId = R.drawable.ic_maps_icon)
}
}
item {
DemoIconChip(
style = ChipStyle.Secondary,
label = "App title",
secondaryLabel = "Default gradient",
colors = ChipDefaults.gradientBackgroundChipColors(),
enabled = enabled,
) {
DemoImage(resourceId = R.drawable.ic_maps_icon)
}
}
item {
DemoIconChip(
style = ChipStyle.Secondary,
label = "Custom Gradient Color",
secondaryLabel = "Matching Secondary Label Color",
secondaryLabelColor = AlternatePrimaryColor3,
colors = ChipDefaults.gradientBackgroundChipColors(
startBackgroundColor = AlternatePrimaryColor3.copy(alpha = 0.325f)
.compositeOver(MaterialTheme.colors.surface.copy(alpha = 0.75f)),
),
enabled = enabled,
) {
DemoImage(resourceId = R.drawable.ic_maps_icon)
}
}
item {
ToggleChip(
checked = enabled,
onCheckedChange = { enabled = it },
label = {
Text("Chips enabled")
},
// For Switch toggle controls the Wear Material UX guidance is to set the
// unselected toggle control color to ToggleChipDefaults.switchUncheckedIconColor()
// rather than the default.
colors = ToggleChipDefaults.toggleChipColors(
uncheckedToggleControlColor = ToggleChipDefaults.SwitchUncheckedIconColor
),
toggleControl = {
Icon(
imageVector = ToggleChipDefaults.switchIcon(checked = enabled),
contentDescription = if (enabled) "On" else "Off"
)
}
)
}
}
}
@Composable
fun RtlChips() {
CompositionLocalProvider(LocalLayoutDirection provides LayoutDirection.Rtl) {
ScalingLazyColumn(
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.spacedBy(4.dp, Alignment.CenterVertically),
contentPadding = PaddingValues(
start = 8.dp,
end = 8.dp,
top = 15.dp,
bottom = 50.dp
)
) {
item {
Text(
text = "Right to left chips",
textAlign = TextAlign.Center,
style = MaterialTheme.typography.caption1,
color = Color.White
)
}
item {
DemoLabelChip(
style = ChipStyle.Primary,
label = "Standard chip",
colors = ChipDefaults.primaryChipColors(),
)
}
item {
DemoLabelChip(
style = ChipStyle.Primary,
label = "Standard chip with long label to show truncation " +
"which does not fit into 2 lines",
colors = ChipDefaults.primaryChipColors(),
)
}
item {
DemoIconChip(
style = ChipStyle.Primary,
colors = ChipDefaults.primaryChipColors(),
label = "Standard chip with ",
secondaryLabel = "Secondary Label",
) { DemoIcon(resourceId = R.drawable.ic_accessibility_24px) }
}
item {
CompactChip(
onClick = {},
colors = ChipDefaults.primaryChipColors(),
label = {
Text(
"Compact chip with label & icon", maxLines = 1,
overflow = TextOverflow.Ellipsis
)
},
icon = {
DemoIcon(
resourceId = R.drawable.ic_accessibility_24px,
modifier = Modifier.size(ChipDefaults.SmallIconSize)
)
},
)
}
item {
DemoIconChip(
style = ChipStyle.Secondary,
label = "Chip with text icon",
colors = ChipDefaults.secondaryChipColors(),
) {
TextIcon(
text = "M",
size = ChipDefaults.LargeIconSize,
style = MaterialTheme.typography.title3
)
}
}
item {
DemoIconChip(
style = ChipStyle.Secondary,
label = "Standard chip with",
secondaryLabel = "Default gradient color",
colors = ChipDefaults.gradientBackgroundChipColors(),
) {
DemoImage(resourceId = R.drawable.ic_maps_icon)
}
}
}
}
}
@Composable
fun CustomChips() {
val applicationContext = LocalContext.current
var enabled by remember { mutableStateOf(true) }
ScalingLazyColumn(
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.spacedBy(4.dp, Alignment.CenterVertically),
contentPadding = PaddingValues(
start = 8.dp,
end = 8.dp,
top = 15.dp,
bottom = 50.dp
)
) {
item {
MaterialTheme(colors = MaterialTheme.colors.copy(primary = AlternatePrimaryColor1)) {
DemoIconChip(
style = ChipStyle.Primary,
label = "Overridden Theme Primary + Icon",
colors = ChipDefaults.primaryChipColors(),
enabled = enabled,
) { DemoIcon(resourceId = R.drawable.ic_accessibility_24px) }
}
}
item {
Row(
modifier = Modifier
.fillMaxWidth()
.wrapContentWidth(Alignment.CenterHorizontally)
) {
CompactChip(
onClick = {
Toast.makeText(
applicationContext, "Compact chip with custom color",
Toast.LENGTH_LONG
).show()
},
colors = ChipDefaults.secondaryChipColors(
contentColor = AlternatePrimaryColor2
),
icon = {
DemoIcon(
resourceId = R.drawable.ic_accessibility_24px,
modifier = Modifier.size(ChipDefaults.IconSize)
)
},
enabled = enabled,
)
}
}
item {
Row(
modifier = Modifier
.fillMaxWidth()
.wrapContentWidth(Alignment.CenterHorizontally)
) {
CompactChip(
onClick = {
Toast.makeText(
applicationContext, "Fixed width chip with custom icon color",
Toast.LENGTH_LONG
).show()
},
modifier = Modifier.width(100.dp),
colors = ChipDefaults.secondaryChipColors(
contentColor = AlternatePrimaryColor3
),
icon = {
DemoIcon(
resourceId = R.drawable.ic_accessibility_24px,
modifier = Modifier.size(ChipDefaults.IconSize)
)
},
enabled = enabled,
)
}
}
item {
ToggleChip(
checked = enabled,
onCheckedChange = { enabled = it },
label = {
Text("Chips enabled")
},
// For Switch toggle controls the Wear Material UX guidance is to set the
// unselected toggle control color to ToggleChipDefaults.switchUncheckedIconColor()
// rather than the default.
colors = ToggleChipDefaults.toggleChipColors(
uncheckedToggleControlColor = ToggleChipDefaults.SwitchUncheckedIconColor
),
toggleControl = {
Icon(
imageVector = ToggleChipDefaults.switchIcon(checked = enabled),
contentDescription = if (enabled) "On" else "Off"
)
}
)
}
}
}
@Composable
fun ImageBackgroundChips() {
var enabled by remember { mutableStateOf(true) }
ScalingLazyColumn(
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.spacedBy(4.dp, Alignment.CenterVertically),
contentPadding = PaddingValues(
start = 8.dp,
end = 8.dp,
top = 15.dp,
bottom = 50.dp
)
) {
item {
DemoLabelChip(
style = ChipStyle.Secondary,
label = "Custom background image",
colors = ChipDefaults.imageBackgroundChipColors(
backgroundImagePainter = painterResource(id = R.drawable.backgroundimage1),
),
enabled = enabled,
)
}
item {
DemoLabelChip(
style = ChipStyle.Secondary,
label = "Custom background image",
secondaryLabel = "with secondary label",
colors = ChipDefaults.imageBackgroundChipColors(
backgroundImagePainter = painterResource(id = R.drawable.backgroundimage1),
),
enabled = enabled,
)
}
item {
ToggleChip(
checked = enabled,
onCheckedChange = { enabled = it },
label = {
Text("Chips enabled")
},
// For Switch toggle controls the Wear Material UX guidance is to set the
// unselected toggle control color to ToggleChipDefaults.switchUncheckedIconColor()
// rather than the default.
colors = ToggleChipDefaults.toggleChipColors(
uncheckedToggleControlColor = ToggleChipDefaults.SwitchUncheckedIconColor
),
toggleControl = {
Icon(
imageVector = ToggleChipDefaults.switchIcon(checked = enabled),
contentDescription = if (enabled) "On" else "Off"
)
}
)
}
}
}
@Composable
private fun ChipCustomizer(
enabled: Boolean,
chipStyle: ChipStyle,
onEnabledChanged: ((enabled: Boolean) -> Unit),
onChipStyleChanged: ((chipStyle: ChipStyle) -> Unit),
) {
Column(
verticalArrangement = Arrangement.spacedBy(8.dp, Alignment.CenterVertically)
) {
Text(
text = "Chip color",
style = MaterialTheme.typography.body2,
modifier = Modifier.align(Alignment.CenterHorizontally),
color = Color.White
)
var i = 0
while (i < ChipStyle.values().size) {
Row(
horizontalArrangement = Arrangement.spacedBy(4.dp, Alignment.CenterHorizontally),
modifier = Modifier
.align(Alignment.CenterHorizontally)
.height(35.dp),
) {
ChipStyleChip(
chipStyle = ChipStyle.values()[i],
selectedChipStyle = chipStyle,
onChipStyleChanged = onChipStyleChanged
)
if (++i < ChipStyle.values().size) {
ChipStyleChip(
chipStyle = ChipStyle.values()[i],
selectedChipStyle = chipStyle,
onChipStyleChanged = onChipStyleChanged
)
i++
}
}
}
ToggleChip(
checked = enabled,
onCheckedChange = onEnabledChanged,
label = {
Text("Chips enabled")
},
// For Switch toggle controls the Wear Material UX guidance is to set the
// unselected toggle control color to ToggleChipDefaults.switchUncheckedIconColor()
// rather than the default.
colors = ToggleChipDefaults.toggleChipColors(
uncheckedToggleControlColor = ToggleChipDefaults.SwitchUncheckedIconColor
),
toggleControl = {
Icon(
imageVector = ToggleChipDefaults.switchIcon(checked = enabled),
contentDescription = if (enabled) "On" else "Off"
)
}
)
}
}
@Composable
private fun ChipStyleChip(
chipStyle: ChipStyle,
selectedChipStyle: ChipStyle,
onChipStyleChanged: ((chipStyle: ChipStyle) -> Unit),
) {
ToggleButton(
checked = selectedChipStyle == chipStyle,
onCheckedChange = {
onChipStyleChanged(chipStyle)
},
) {
Text(
style = MaterialTheme.typography.caption2,
modifier = Modifier.padding(4.dp),
text = chipStyle.toString(),
)
}
}
@Composable
private fun chipColors(chipStyle: ChipStyle) =
when (chipStyle) {
ChipStyle.Primary -> ChipDefaults.primaryChipColors()
ChipStyle.Secondary -> ChipDefaults.secondaryChipColors()
ChipStyle.Child -> ChipDefaults.childChipColors()
ChipStyle.Outlined -> ChipDefaults.outlinedChipColors()
}
enum class ChipStyle {
Primary,
Secondary,
Child,
Outlined
}
@Composable
internal fun DemoIconCompactChip(
colors: ChipColors,
label: String,
style: ChipStyle,
modifier: Modifier = Modifier,
enabled: Boolean = true,
onClick: (() -> Unit) = {},
shape: Shape = MaterialTheme.shapes.small,
content: @Composable (BoxScope.() -> Unit)? = null
) {
val maxLabelLines = 1
if (style != ChipStyle.Outlined) {
CompactChip(
onClick = onClick,
modifier = modifier,
colors = colors,
label = {
Text(
text = label, maxLines = maxLabelLines,
overflow = TextOverflow.Ellipsis
)
},
icon = content,
shape = shape,
enabled = enabled,
)
} else {
OutlinedCompactChip(
onClick = onClick,
modifier = modifier,
colors = colors,
label = {
Text(
text = label, maxLines = maxLabelLines,
overflow = TextOverflow.Ellipsis
)
},
icon = content,
shape = shape,
enabled = enabled,
)
}
}
@Composable
internal fun DemoIconChip(
colors: ChipColors,
label: String,
style: ChipStyle,
modifier: Modifier = Modifier,
secondaryLabel: String? = null,
secondaryLabelColor: Color? = null,
enabled: Boolean = true,
onClick: (() -> Unit) = {},
shape: Shape = MaterialTheme.shapes.small,
content: @Composable (BoxScope.() -> Unit)? = null
) {
val maxLabelLines = if (secondaryLabel != null) 1 else 2
if (style != ChipStyle.Outlined) {
Chip(
onClick = onClick,
modifier = modifier,
colors = colors,
label = {
Text(
text = label, maxLines = maxLabelLines,
overflow = TextOverflow.Ellipsis
)
},
secondaryLabel = secondaryLabel?.let {
{
CompositionLocalProvider(
LocalContentColor provides
(secondaryLabelColor ?: colors.contentColor(enabled = enabled).value)
) {
Text(
text = secondaryLabel,
maxLines = 1, overflow = TextOverflow.Ellipsis
)
}
}
},
icon = content,
shape = shape,
enabled = enabled,
)
} else {
OutlinedChip(
onClick = onClick,
modifier = modifier,
colors = colors,
label = {
Text(
text = label, maxLines = maxLabelLines,
overflow = TextOverflow.Ellipsis
)
},
secondaryLabel = secondaryLabel?.let {
{
CompositionLocalProvider(
LocalContentColor provides
(secondaryLabelColor ?: colors.contentColor(enabled = enabled).value)
) {
Text(
text = secondaryLabel,
maxLines = 1, overflow = TextOverflow.Ellipsis
)
}
}
},
icon = content,
shape = shape,
enabled = enabled,
)
}
}
@Composable
private fun DemoLabelChip(
colors: ChipColors,
label: String,
modifier: Modifier = Modifier,
secondaryLabel: String? = null,
onClick: (() -> Unit) = {},
enabled: Boolean = true,
shape: Shape = MaterialTheme.shapes.small,
style: ChipStyle
) {
DemoIconChip(
colors = colors,
label = label,
modifier = modifier,
secondaryLabel = secondaryLabel,
enabled = enabled,
onClick = onClick,
style = style,
shape = shape,
content = null
)
} | apache-2.0 | 4a5a4a2682a8f62734a52e36afac8500 | 33.531818 | 100 | 0.505084 | 6.030363 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/j2k/new/src/org/jetbrains/kotlin/nj2k/types/JKTypeFactory.kt | 1 | 6496 | // 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.nj2k.types
import com.intellij.psi.*
import org.jetbrains.kotlin.builtins.StandardNames
import org.jetbrains.kotlin.descriptors.TypeParameterDescriptor
import org.jetbrains.kotlin.j2k.ast.Nullability
import org.jetbrains.kotlin.js.descriptorUtils.getJetTypeFqName
import org.jetbrains.kotlin.js.resolve.diagnostics.findPsi
import org.jetbrains.kotlin.name.FqNameUnsafe
import org.jetbrains.kotlin.nj2k.JKSymbolProvider
import org.jetbrains.kotlin.nj2k.symbols.JKClassSymbol
import org.jetbrains.kotlin.nj2k.symbols.JKTypeParameterSymbol
import org.jetbrains.kotlin.nj2k.symbols.JKUnresolvedClassSymbol
import org.jetbrains.kotlin.psi.KtTypeParameter
import org.jetbrains.kotlin.resolve.jvm.JvmPrimitiveType
import org.jetbrains.kotlin.types.KotlinType
import org.jetbrains.kotlin.types.isNullable
class JKTypeFactory(val symbolProvider: JKSymbolProvider) {
fun fromPsiType(type: PsiType): JKType = createPsiType(type)
fun fromKotlinType(type: KotlinType): JKType = createKotlinType(type)
inner class DefaultTypes {
private fun typeByFqName(
fqName: FqNameUnsafe,
typeArguments: List<JKType> = emptyList(),
nullability: Nullability = Nullability.NotNull
) = JKClassType(
symbolProvider.provideClassSymbol(fqName),
typeArguments,
nullability
)
val boolean = typeByFqName(StandardNames.FqNames._boolean)
val char = typeByFqName(StandardNames.FqNames._char)
val byte = typeByFqName(StandardNames.FqNames._byte)
val short = typeByFqName(StandardNames.FqNames._short)
val int = typeByFqName(StandardNames.FqNames._int)
val float = typeByFqName(StandardNames.FqNames._float)
val long = typeByFqName(StandardNames.FqNames._long)
val double = typeByFqName(StandardNames.FqNames._double)
val string = typeByFqName(StandardNames.FqNames.string)
val possiblyNullString = typeByFqName(StandardNames.FqNames.string, nullability = Nullability.Default)
val unit = typeByFqName(StandardNames.FqNames.unit)
val nothing = typeByFqName(StandardNames.FqNames.nothing)
val nullableAny = typeByFqName(StandardNames.FqNames.any, nullability = Nullability.Nullable)
}
fun fromPrimitiveType(primitiveType: JKJavaPrimitiveType) = when (primitiveType.jvmPrimitiveType) {
JvmPrimitiveType.BOOLEAN -> types.boolean
JvmPrimitiveType.CHAR -> types.char
JvmPrimitiveType.BYTE -> types.byte
JvmPrimitiveType.SHORT -> types.short
JvmPrimitiveType.INT -> types.int
JvmPrimitiveType.FLOAT -> types.float
JvmPrimitiveType.LONG -> types.long
JvmPrimitiveType.DOUBLE -> types.double
}
val types by lazy(LazyThreadSafetyMode.NONE) { DefaultTypes() }
private fun createPsiType(type: PsiType): JKType = when (type) {
is PsiClassType -> {
val target = type.resolve()
val parameters = type.parameters.map { fromPsiType(it) }
when (target) {
null ->
JKClassType(JKUnresolvedClassSymbol(type.rawType().canonicalText, this), parameters)
is PsiTypeParameter ->
JKTypeParameterType(symbolProvider.provideDirectSymbol(target) as JKTypeParameterSymbol)
is PsiAnonymousClass -> {
/*
If anonymous class is declared inside the converting code, we will not be able to access JKUniverseClassSymbol's target
And get UninitializedPropertyAccessException exception, so it is ok to use base class for now
*/
createPsiType(target.baseClassType)
}
else -> {
JKClassType(
target.let { symbolProvider.provideDirectSymbol(it) as JKClassSymbol },
parameters
)
}
}
}
is PsiArrayType -> JKJavaArrayType(fromPsiType(type.componentType))
is PsiPrimitiveType -> JKJavaPrimitiveType.fromPsi(type)
is PsiDisjunctionType ->
JKJavaDisjunctionType(type.disjunctions.map { fromPsiType(it) })
is PsiWildcardType ->
when {
type.isExtends ->
JKVarianceTypeParameterType(
JKVarianceTypeParameterType.Variance.OUT,
fromPsiType(type.extendsBound)
)
type.isSuper ->
JKVarianceTypeParameterType(
JKVarianceTypeParameterType.Variance.IN,
fromPsiType(type.superBound)
)
else -> JKStarProjectionTypeImpl
}
is PsiCapturedWildcardType ->
JKCapturedType(fromPsiType(type.wildcard) as JKWildCardType)
is PsiIntersectionType -> // TODO what to do with intersection types? old j2k just took the first conjunct
fromPsiType(type.representative)
is PsiLambdaParameterType -> // Probably, means that we have erroneous Java code
JKNoType
is PsiLambdaExpressionType -> type.expression.functionalInterfaceType?.let(::createPsiType) ?: JKNoType
is PsiMethodReferenceType -> type.expression.functionalInterfaceType?.let(::createPsiType) ?: JKNoType
else -> JKNoType
}
private fun createKotlinType(type: KotlinType): JKType {
return when (val descriptor = type.constructor.declarationDescriptor) {
is TypeParameterDescriptor ->
JKTypeParameterType(
symbolProvider.provideDirectSymbol(
descriptor.findPsi() as? KtTypeParameter ?: return JKNoType
) as JKTypeParameterSymbol
)
else -> JKClassType(
symbolProvider.provideClassSymbol(type.getJetTypeFqName(false)), //TODO constructor fqName
type.arguments.map { typeArgument ->
if (typeArgument.isStarProjection) JKStarProjectionTypeImpl
else fromKotlinType(typeArgument.type)
},
if (type.isNullable()) Nullability.Nullable else Nullability.NotNull
)
}
}
}
| apache-2.0 | e7892881ff065f892e253f1d8be5ded2 | 42.597315 | 140 | 0.652709 | 5.668412 | false | false | false | false |
GunoH/intellij-community | platform/platform-impl/src/com/intellij/ui/colorpicker/SaturationBrightnessComponent.kt | 2 | 6176 | /*
* Copyright (C) 2018 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
@file:Suppress("JAVA_MODULE_DOES_NOT_EXPORT_PACKAGE")
package com.intellij.ui.colorpicker
import com.intellij.openapi.util.registry.Registry
import com.intellij.ui.ColorUtil
import com.intellij.ui.picker.ColorListener
import com.intellij.util.ui.GraphicsUtil
import com.intellij.util.ui.JBUI
import com.intellij.util.ui.UIUtil
import sun.awt.image.ToolkitImage
import java.awt.*
import java.awt.event.MouseAdapter
import java.awt.event.MouseEvent
import java.awt.image.ColorModel
import java.awt.image.MemoryImageSource
import javax.swing.JComponent
import kotlin.math.ceil
private val KNOB_COLOR = Color.WHITE
private const val KNOB_RADIUS = 4
class SaturationBrightnessComponent(private val myModel: ColorPickerModel) : JComponent(), ColorListener, ColorPipette.Callback {
var brightness = 1f
private set
var hue = 1f
private set
var saturation = 0f
private set
var alpha: Int = 255
private set
var pipetteMode = false
val robot = Robot()
init {
isOpaque = false
background = Color.WHITE
val mouseAdapter = object : MouseAdapter() {
override fun mousePressed(e: MouseEvent) {
handleMouseEvent(e)
}
override fun mouseDragged(e: MouseEvent) {
handleMouseEvent(e)
}
}
addMouseListener(mouseAdapter)
addMouseMotionListener(mouseAdapter)
myModel.addListener(this)
if (Registry.`is`("ide.color.picker.new.pipette")) {
myModel.addPipetteListener(this)
}
}
private fun handleMouseEvent(e: MouseEvent) {
myModel.setColor(getColorByPoint(e.point), this)
}
public fun getColorByPoint(p: Point): Color {
val x = Math.max(0, Math.min(p.x, size.width))
val y = Math.max(0, Math.min(p.y, size.height))
val saturation = x.toFloat() / size.width
val brightness = 1.0f - y.toFloat() / size.height
val argb = ahsbToArgb(alpha, hue, saturation, brightness)
val newColor = Color(argb, true)
return newColor
}
override fun getPreferredSize(): Dimension = JBUI.size(PICKER_PREFERRED_WIDTH, 150)
override fun getMinimumSize(): Dimension = JBUI.size(150, 140)
private fun paintPipetteMode(graphics: Graphics) {
graphics.color = parent.background
graphics.fillRect(0,0, width, height)
val g = graphics.create() as Graphics2D
val p = MouseInfo.getPointerInfo().location
val size = width / 21.0
val img = robot.createMultiResolutionScreenCapture(Rectangle(p.x - 10, p.y - 5, 21, 11))
val image = img.resolutionVariants.last()
val iW = image.getWidth(null)
val iH = image.getHeight(null)
g.scale(width / 21.0, width / 21.0)
g.drawImage(image, -((iW - 21) / 2.0).toInt(), -ceil((iH - 11) / 2.0).toInt(), null)
g.dispose()
val xx = ceil(size * 10).toInt()
val yy = ceil(size * 5).toInt()
graphics.color = Color.white
graphics.drawRect(xx, yy, (size - 1).toInt(), (size - 1).toInt())
graphics.color = Color.black
graphics.drawRect(xx+1, yy+1, (size - 3).toInt(), (size - 3).toInt())
}
override fun paintComponent(g: Graphics) {
if (Registry.`is`("ide.color.picker.new.pipette") && pipetteMode) {
paintPipetteMode(g)
return
}
val component = Rectangle(0, 0, size.width, size.height)
val image = createImage(SaturationBrightnessImageProducer(size.width, size.height, hue))
g.color = UIUtil.getPanelBackground()
g.fillRect(0, 0, width, height)
g.drawImage(image, component.x, component.y, null)
val knobX = Math.round(saturation * component.width)
val knobY = Math.round(component.height * (1.0f - brightness))
if (image is ToolkitImage && image.bufferedImage.width > knobX && image.bufferedImage.height > knobY) {
val rgb = image.bufferedImage.getRGB(knobX, knobY)
g.color = if (ColorUtil.isDark(Color(rgb))) Color.WHITE else Color.BLACK
} else {
g.color = KNOB_COLOR
}
val config = GraphicsUtil.setupAAPainting(g)
g.drawOval(knobX - JBUI.scale(KNOB_RADIUS),
knobY - JBUI.scale(KNOB_RADIUS),
JBUI.scale(KNOB_RADIUS * 2),
JBUI.scale(KNOB_RADIUS * 2))
config.restore()
}
override fun colorChanged(color: Color, source: Any?) {
val hsbValues = Color.RGBtoHSB(color.red, color.green, color.blue, null)
setHSBAValue(hsbValues[0], hsbValues[1], hsbValues[2], color.alpha)
}
private fun setHSBAValue(h: Float, s: Float, b: Float, a: Int) {
hue = h
saturation = s
brightness = b
alpha = a
repaint()
}
override fun picked(pickedColor: Color) {
pipetteMode = false
}
override fun update(updatedColor: Color) {
pipetteMode = true
repaint()
}
override fun cancel() {
pipetteMode = false
}
}
private class SaturationBrightnessImageProducer(imageWidth: Int, imageHeight: Int, hue: Float)
: MemoryImageSource(imageWidth, imageHeight, null, 0, imageWidth) {
init {
val saturation = FloatArray(imageWidth * imageHeight)
val brightness = FloatArray(imageWidth * imageHeight)
// create lookup tables
for (x in 0 until imageWidth) {
for (y in 0 until imageHeight) {
val index = x + y * imageWidth
saturation[index] = x.toFloat() / imageWidth
brightness[index] = 1.0f - y.toFloat() / imageHeight
}
}
val pixels = IntArray(imageWidth * imageHeight)
newPixels(pixels, ColorModel.getRGBdefault(), 0, imageWidth)
setAnimated(true)
for (index in pixels.indices) {
pixels[index] = Color.HSBtoRGB(hue, saturation[index], brightness[index])
}
newPixels()
}
}
| apache-2.0 | a579fdf9a72885e67e773ed29591eb72 | 30.835052 | 129 | 0.684262 | 3.8147 | false | false | false | false |
GunoH/intellij-community | plugins/package-search/src/com/jetbrains/packagesearch/intellij/plugin/ui/toolwindow/panels/management/packages/PackagesListPanel.kt | 2 | 32994 | /*******************************************************************************
* Copyright 2000-2022 JetBrains s.r.o. and contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.panels.management.packages
import com.intellij.ide.BrowserUtil
import com.intellij.openapi.actionSystem.ActionManager
import com.intellij.openapi.actionSystem.DefaultActionGroup
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.EDT
import com.intellij.openapi.project.Project
import com.intellij.openapi.wm.IdeFocusManager
import com.intellij.ui.DocumentAdapter
import com.intellij.ui.SearchTextField
import com.intellij.ui.SimpleTextAttributes
import com.intellij.ui.components.JBPanelWithEmptyText
import com.intellij.ui.components.JBScrollPane
import com.intellij.util.ui.JBUI
import com.jetbrains.packagesearch.intellij.plugin.PackageSearchBundle
import com.jetbrains.packagesearch.intellij.plugin.data.PackageUpgradeCandidates
import com.jetbrains.packagesearch.intellij.plugin.fus.FUSGroupIds
import com.jetbrains.packagesearch.intellij.plugin.fus.PackageSearchEventsLogger
import com.jetbrains.packagesearch.intellij.plugin.ui.ComponentActionWrapper
import com.jetbrains.packagesearch.intellij.plugin.ui.PackageSearchUI
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.FilterOptions
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.InstalledDependency
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.KnownRepositories
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.OperationExecutor
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.PackageIdentifier
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.PackagesToUpgrade
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.ProjectDataProvider
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.SearchResultUiState
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.TargetModules
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.UiPackageModel
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.matchesCoordinates
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.toUiPackageModel
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.versions.NormalizedPackageVersion
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.panels.PackageSearchPanelBase
import com.jetbrains.packagesearch.intellij.plugin.ui.updateAndRepaint
import com.jetbrains.packagesearch.intellij.plugin.ui.util.emptyBorder
import com.jetbrains.packagesearch.intellij.plugin.ui.util.onOpacityChanged
import com.jetbrains.packagesearch.intellij.plugin.ui.util.onVisibilityChanged
import com.jetbrains.packagesearch.intellij.plugin.ui.util.scaled
import com.jetbrains.packagesearch.intellij.plugin.util.CoroutineLRUCache
import com.jetbrains.packagesearch.intellij.plugin.util.FeatureFlags
import com.jetbrains.packagesearch.intellij.plugin.util.KotlinPluginStatus
import com.jetbrains.packagesearch.intellij.plugin.util.PowerSaveModeState
import com.jetbrains.packagesearch.intellij.plugin.util.hasKotlinModules
import com.jetbrains.packagesearch.intellij.plugin.util.kotlinPluginStatusFlow
import com.jetbrains.packagesearch.intellij.plugin.util.lifecycleScope
import com.jetbrains.packagesearch.intellij.plugin.util.logDebug
import com.jetbrains.packagesearch.intellij.plugin.util.logTrace
import com.jetbrains.packagesearch.intellij.plugin.util.logWarn
import com.jetbrains.packagesearch.intellij.plugin.util.lookAndFeelFlow
import com.jetbrains.packagesearch.intellij.plugin.util.moduleChangesSignalFlow
import com.jetbrains.packagesearch.intellij.plugin.util.onEach
import com.jetbrains.packagesearch.intellij.plugin.util.packageSearchProjectCachesService
import com.jetbrains.packagesearch.intellij.plugin.util.packageSearchProjectService
import com.jetbrains.packagesearch.intellij.plugin.util.packageVersionNormalizer
import com.jetbrains.packagesearch.intellij.plugin.util.parallelFilterNot
import com.jetbrains.packagesearch.intellij.plugin.util.parallelMap
import com.jetbrains.packagesearch.intellij.plugin.util.parallelMapNotNull
import com.jetbrains.packagesearch.intellij.plugin.util.timer
import com.jetbrains.packagesearch.intellij.plugin.util.uiStateSource
import com.jetbrains.packagesearch.intellij.plugin.util.whileLoading
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.combineTransform
import kotlinx.coroutines.flow.consumeAsFlow
import kotlinx.coroutines.flow.debounce
import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.flow.filterNot
import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.mapLatest
import kotlinx.coroutines.flow.onEach
import kotlinx.coroutines.flow.shareIn
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import net.miginfocom.swing.MigLayout
import org.jetbrains.packagesearch.api.v2.ApiPackagesResponse
import org.jetbrains.packagesearch.api.v2.ApiStandardPackage
import java.awt.BorderLayout
import java.awt.Dimension
import java.awt.event.ItemEvent
import javax.swing.BorderFactory
import javax.swing.Box
import javax.swing.BoxLayout
import javax.swing.JCheckBox
import javax.swing.JPanel
import javax.swing.JScrollPane
import javax.swing.JViewport
import javax.swing.event.DocumentEvent
import kotlin.time.Duration
import kotlin.time.Duration.Companion.milliseconds
import kotlin.time.Duration.Companion.minutes
import kotlin.time.measureTime
import kotlin.time.measureTimedValue
internal class PackagesListPanel(
private val project: Project,
private val searchCache: CoroutineLRUCache<SearchCommandModel, ApiPackagesResponse<ApiStandardPackage, ApiStandardPackage.ApiStandardVersion>> =
project.packageSearchProjectCachesService.searchCache,
private val searchPackageModelCache: CoroutineLRUCache<UiPackageModelCacheKey, UiPackageModel.SearchResult> =
project.packageSearchProjectCachesService.searchPackageModelCache,
operationExecutor: OperationExecutor,
viewModelFlow: Flow<ViewModel>,
private val dataProvider: ProjectDataProvider
) : PackageSearchPanelBase(PackageSearchBundle.message("packagesearch.ui.toolwindow.tab.packages.title")) {
private val searchFieldFocus = Channel<Unit>()
private val packagesTable = PackagesTable(project, operationExecutor, ::onSearchResultStateChanged)
private val onlyStableMutableStateFlow = MutableStateFlow(true)
val onlyStableStateFlow: StateFlow<Boolean> = onlyStableMutableStateFlow
val selectedPackageStateFlow: StateFlow<UiPackageModel<*>?> = packagesTable.selectedPackageStateFlow
private val onlyMultiplatformStateFlow = MutableStateFlow(false)
private val searchQueryStateFlow = MutableStateFlow("")
private val isSearchingStateFlow = MutableStateFlow(false)
private val isLoadingStateFlow = MutableStateFlow(false)
private val searchResultsUiStateOverridesState: MutableStateFlow<Map<PackageIdentifier, SearchResultUiState>> =
MutableStateFlow(emptyMap())
private val searchTextField = PackagesSmartSearchField(searchFieldFocus.consumeAsFlow(), project)
.apply {
goToTable = {
if (packagesTable.hasInstalledItems) {
packagesTable.selectedIndex = packagesTable.firstPackageIndex
IdeFocusManager.getInstance(project).requestFocus(packagesTable, false)
true
} else {
false
}
}
fieldClearedListener = {
PackageSearchEventsLogger.logSearchQueryClear()
}
}
private val packagesPanel = PackageSearchUI.borderPanel {
layout = BoxLayout(this, BoxLayout.Y_AXIS)
}
private val onlyStableCheckBox = PackageSearchUI.checkBox(PackageSearchBundle.message("packagesearch.ui.toolwindow.packages.filter.onlyStable"))
.apply {
isOpaque = false
border = emptyBorder(left = 6)
isSelected = true
}
private val onlyMultiplatformCheckBox =
PackageSearchUI.checkBox(PackageSearchBundle.message("packagesearch.ui.toolwindow.packages.filter.onlyMpp")) {
isOpaque = false
border = emptyBorder(left = 6)
isSelected = false
}
private val searchFiltersToolbar = ActionManager.getInstance()
.createActionToolbar("Packages.Manage", createActionGroup(), true)
.apply {
component.background = if (PackageSearchUI.isNewUI) {
PackageSearchUI.Colors.panelBackground
} else {
PackageSearchUI.Colors.headerBackground
}
component.border = JBUI.Borders.customLineLeft(PackageSearchUI.Colors.panelBackground)
}
private fun createActionGroup() = DefaultActionGroup().apply {
add(ComponentActionWrapper { onlyStableCheckBox })
add(ComponentActionWrapper { onlyMultiplatformCheckBox })
}
private val searchPanel = PackageSearchUI.headerPanel {
PackageSearchUI.setHeightPreScaled(this, PackageSearchUI.mediumHeaderHeight.get())
border = BorderFactory.createEmptyBorder()
addToCenter(object : JPanel() {
init {
layout = MigLayout("ins 0, fill", "[left, fill, grow][right]", "fill")
add(searchTextField)
add(searchFiltersToolbar.component)
searchFiltersToolbar.targetComponent = this
if (PackageSearchUI.isNewUI) {
project.coroutineScope.launch {
// This is a hack — the ActionToolbar will reset its own background colour,
// so we need to wait for the next frame to set it
delay(16.milliseconds)
withContext(Dispatchers.EDT) {
searchFiltersToolbar.component.background = PackageSearchUI.Colors.panelBackground
}
}
}
border = JBUI.Borders.customLineBottom(PackageSearchUI.Colors.separator)
}
override fun getBackground() = PackageSearchUI.Colors.panelBackground
})
}
private val headerPanel = HeaderPanel {
logDebug("PackagesListPanel.headerPanel#onUpdateAllLinkClicked()") {
"The user has clicked the update all link. This will cause many operation(s) to be executed."
}
operationExecutor.executeOperations(it)
}.apply {
border = JBUI.Borders.customLineTop(PackageSearchUI.Colors.separator)
}
private val tableScrollPane = JBScrollPane(
packagesPanel.apply {
add(packagesTable)
add(Box.createVerticalGlue())
},
JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
JScrollPane.HORIZONTAL_SCROLLBAR_NEVER
).apply {
border = emptyBorder()
viewportBorder = emptyBorder()
viewport.scrollMode = JViewport.SIMPLE_SCROLL_MODE
verticalScrollBar.apply {
headerPanel.adjustForScrollbar(isVisible, isOpaque)
// Here, we should make sure we set IGNORE_SCROLLBAR_IN_INSETS, but alas, it doesn't work with JTables
// as of IJ 2022.3 (see JBViewport#updateBorder()). If it did, we could just set:
// UIUtil.putClientProperty(this, JBScrollPane.IGNORE_SCROLLBAR_IN_INSETS, false)
// Instead, we have to work around the issue, inferring if the scrollbar is "floating" by looking at
// its isOpaque property — since Swing maps the opacity of scrollbars to whether they're "floating"
// (e.g., on macOS, System Preferences > General > Show scroll bars: "When scrolling")
onOpacityChanged { newIsOpaque ->
headerPanel.adjustForScrollbar(isVisible, newIsOpaque)
}
onVisibilityChanged { newIsVisible ->
headerPanel.adjustForScrollbar(newIsVisible, isOpaque)
}
}
}
private val listPanel = JBPanelWithEmptyText().apply {
emptyText.text = PackageSearchBundle.message("packagesearch.ui.toolwindow.packages.empty.base")
layout = BorderLayout()
add(tableScrollPane, BorderLayout.CENTER)
background = PackageSearchUI.Colors.panelBackground
border = JBUI.Borders.customLineTop(PackageSearchUI.Colors.separator)
}
internal data class SearchCommandModel(
val onlyStable: Boolean,
val onlyMultiplatform: Boolean,
val searchQuery: String,
)
internal data class SearchResultsModel(
val onlyStable: Boolean,
val onlyMultiplatform: Boolean,
val searchQuery: String,
val apiSearchResults: ApiPackagesResponse<ApiStandardPackage, ApiStandardPackage.ApiStandardVersion>?
)
private data class ViewModels(
val targetModules: TargetModules,
val headerData: PackagesHeaderData,
val viewModel: PackagesTable.ViewModel
)
init {
registerForUiEvents()
val searchResultsFlow =
combine(onlyStableStateFlow, onlyMultiplatformStateFlow, searchQueryStateFlow) { onlyStable, onlyMultiplatform, searchQuery ->
SearchCommandModel(onlyStable, onlyMultiplatform, searchQuery)
}
.debounce(150)
.mapLatest { searchCommand ->
val (result, time) = isSearchingStateFlow.whileLoading {
val results = searchCache.getOrTryPutDefault(searchCommand) {
dataProvider.doSearch(
searchCommand.searchQuery,
FilterOptions(searchCommand.onlyStable, searchCommand.onlyMultiplatform)
)
}
SearchResultsModel(
searchCommand.onlyStable,
searchCommand.onlyMultiplatform,
searchCommand.searchQuery,
results
)
}
logTrace("PackagesListPanel main flow") { "Search took $time" }
result
}
.shareIn(project.lifecycleScope, SharingStarted.Eagerly, 1)
combine(
viewModelFlow,
searchResultsFlow,
searchResultsUiStateOverridesState
) { viewModel, searchResults, overrides ->
Triple(viewModel, searchResults, overrides)
}.mapLatest { (viewModel, searchResults, searchResultsUiStateOverrides) ->
val (
targetModules, installedPackages, packagesUpdateCandidates,
knownRepositoriesInTargetModules
) = viewModel
val (onlyStable, onlyMultiplatform, searchQuery, apiSearchResults) = searchResults
isLoadingStateFlow.emit(true)
val (result, time) = measureTimedValue {
val (result, time) = measureTimedValue {
val packagesToUpgrade = packagesUpdateCandidates.getPackagesToUpgrade(onlyStable)
val filteredPackageUpgrades = when (targetModules) {
is TargetModules.All -> packagesToUpgrade.allUpdates
is TargetModules.One -> packagesToUpgrade.getUpdatesForModule(targetModules.module)
TargetModules.None -> emptyList()
}
val filteredInstalledPackages = installedPackages.filterByTargetModules(targetModules)
filteredPackageUpgrades to filteredInstalledPackages
}
logTrace("PackagesListPanel main flow") { "Initial computation took $time" }
val (filteredPackageUpgrades, filteredInstalledPackages) = result
fun onComplete(computationName: String): (Duration) -> Unit =
{ time -> logTrace("PackagesListPanel main flow") { "Took $time for \"$computationName\"" } }
val filteredInstalledPackagesUiModels = computeFilteredInstalledPackagesUiModels(
packages = filteredInstalledPackages,
onlyMultiplatform = onlyMultiplatform,
targetModules = targetModules,
knownRepositoriesInTargetModules = knownRepositoriesInTargetModules,
onlyStable = onlyStable,
searchQuery = searchQuery,
project = project,
onComplete = onComplete("filteredInstalledPackagesUiModelsTime"),
)
val searchResultModels = computeSearchResultModels(
searchResults = apiSearchResults,
installedPackages = filteredInstalledPackagesUiModels,
onlyStable = onlyStable,
targetModules = targetModules,
searchResultsUiStateOverrides = searchResultsUiStateOverrides,
knownRepositoriesInTargetModules = knownRepositoriesInTargetModules,
project = project,
cache = searchPackageModelCache,
onComplete = onComplete("searchResultModels")
)
val tableItems = computePackagesTableItems(
packages = filteredInstalledPackagesUiModels + searchResultModels,
targetModules = targetModules,
onComplete = onComplete("tableItemsTime")
)
val headerData = computeHeaderData(
totalItemsCount = tableItems.size,
packageUpdateInfos = filteredPackageUpgrades,
hasSearchResults = apiSearchResults?.packages?.isNotEmpty() ?: false,
targetModules = targetModules,
onComplete = onComplete("headerDataTime")
)
ViewModels(
targetModules = targetModules,
headerData = headerData,
viewModel = PackagesTable.ViewModel(
items = tableItems,
onlyStable = onlyStable,
targetModules = targetModules,
knownRepositoriesInTargetModules = knownRepositoriesInTargetModules
)
)
}
logTrace("PackagesListPanel main flow") { "Total elaboration took $time" }
result
}
.flowOn(project.lifecycleScope.coroutineDispatcher)
.onEach { (targetModules, headerData, packagesTableViewModel) ->
val renderingTime = measureTime {
updateListEmptyState(targetModules, project.packageSearchProjectService.isLoadingFlow.value)
headerPanel.display(headerData)
packagesTable.display(packagesTableViewModel)
tableScrollPane.isVisible = packagesTableViewModel.items.isNotEmpty()
listPanel.updateAndRepaint()
packagesTable.updateAndRepaint()
packagesPanel.updateAndRepaint()
}
logTrace("PackagesListPanel main flow") {
"Rendering took $renderingTime for ${packagesTableViewModel.items.size} items"
}
isLoadingStateFlow.emit(false)
}
.flowOn(Dispatchers.EDT)
.catch { logWarn("Error in PackagesListPanel main flow", it) }
.launchIn(project.lifecycleScope)
combineTransform(
isLoadingStateFlow,
isSearchingStateFlow,
project.packageSearchProjectService.isLoadingFlow
) { booleans -> emit(booleans.any { it }) }
.debounce(150)
.onEach { headerPanel.showBusyIndicator(it) }
.flowOn(Dispatchers.EDT)
.launchIn(project.lifecycleScope)
project.lookAndFeelFlow.onEach { updateUiOnLafChange() }
.launchIn(project.lifecycleScope)
// The results may have changed server-side. Better clear caches...
timer(10.minutes)
.onEach {
searchPackageModelCache.clear()
searchCache.clear()
}
.launchIn(project.lifecycleScope)
searchResultsFlow.map { it.searchQuery }
.debounce(500)
.distinctUntilChanged()
.filterNot { it.isBlank() }
.onEach { PackageSearchEventsLogger.logSearchRequest(it) }
.launchIn(project.lifecycleScope)
combine(
ApplicationManager.getApplication().kotlinPluginStatusFlow,
FeatureFlags.smartKotlinMultiplatformCheckboxEnabledFlow,
project.moduleChangesSignalFlow,
) { kotlinPluginStatus, useSmartCheckbox, _ ->
val isKotlinPluginAvailable = kotlinPluginStatus == KotlinPluginStatus.AVAILABLE
isKotlinPluginAvailable && (!useSmartCheckbox || project.hasKotlinModules())
}
.onEach(Dispatchers.EDT) { onlyMultiplatformCheckBox.isVisible = it }
.launchIn(project.lifecycleScope)
}
private fun updateListEmptyState(targetModules: TargetModules, loading: Boolean) {
listPanel.emptyText.clear()
when {
PowerSaveModeState.getCurrentState() == PowerSaveModeState.ENABLED -> {
listPanel.emptyText.appendLine(
PackageSearchBundle.message("packagesearch.ui.toolwindow.packages.empty.powerSaveMode")
)
}
isSearching() -> {
listPanel.emptyText.text = PackageSearchBundle.message("packagesearch.ui.toolwindow.packages.empty.searching")
}
project.packageSearchProjectService.isComputationAllowed -> when {
targetModules is TargetModules.None -> {
listPanel.emptyText.text = PackageSearchBundle.message("packagesearch.ui.toolwindow.packages.empty.noModule")
}
!loading -> {
val targetModuleNames = when (targetModules) {
is TargetModules.All -> PackageSearchBundle.message("packagesearch.ui.toolwindow.packages.empty.allModules")
is TargetModules.One -> targetModules.module.projectModule.name
is TargetModules.None -> error("No module selected empty state should be handled separately")
}
listPanel.emptyText.appendLine(
PackageSearchBundle.message("packagesearch.ui.toolwindow.packages.empty.packagesOnly", targetModuleNames)
)
listPanel.emptyText.appendLine(
PackageSearchBundle.message("packagesearch.ui.toolwindow.packages.empty.learnMore"),
SimpleTextAttributes.LINK_ATTRIBUTES
) {
BrowserUtil.browse("https://www.jetbrains.com/help/idea/package-search-build-system-support-limitations.html")
}
}
else -> listPanel.emptyText.appendLine(
PackageSearchBundle.message("packagesearch.ui.toolwindow.packages.empty.loading")
)
}
else -> {
listPanel.emptyText.appendLine(
PackageSearchBundle.message("packagesearch.ui.toolwindow.packages.empty.interrupted")
)
listPanel.emptyText.appendLine(
PackageSearchBundle.message("packagesearch.ui.toolwindow.packages.empty.interrupted.restart"),
SimpleTextAttributes.LINK_ATTRIBUTES
) {
project.packageSearchProjectService.resumeComputation()
}
}
}
}
private fun isSearching() = !searchTextField.text.isNullOrBlank()
internal data class ViewModel(
val targetModules: TargetModules,
val installedPackages: List<PackageModel.Installed>,
val packagesUpdateCandidates: PackageUpgradeCandidates,
val knownRepositoriesInTargetModules: KnownRepositories.InTargetModules
)
private fun registerForUiEvents() {
packagesTable.transferFocusUp = {
IdeFocusManager.getInstance(project).requestFocus(searchTextField, false)
}
searchTextField.addOnTextChangedListener { text ->
searchQueryStateFlow.tryEmit(text)
}
onlyStableCheckBox.addSelectionChangedListener { selected ->
onlyStableMutableStateFlow.tryEmit(selected)
PackageSearchEventsLogger.logToggle(FUSGroupIds.ToggleTypes.OnlyStable, selected)
}
onlyMultiplatformCheckBox.addSelectionChangedListener { selected ->
onlyMultiplatformStateFlow.tryEmit(selected)
PackageSearchEventsLogger.logToggle(FUSGroupIds.ToggleTypes.OnlyKotlinMp, selected)
}
project.uiStateSource.searchQueryFlow.onEach { searchTextField.text = it }
.flowOn(Dispatchers.EDT)
.launchIn(project.lifecycleScope)
}
private suspend fun updateUiOnLafChange() = withContext(Dispatchers.EDT) {
@Suppress("MagicNumber") // Dimension constants
with(searchTextField) {
textEditor.putClientProperty("JTextField.Search.Gap", 6.scaled())
textEditor.putClientProperty("JTextField.Search.GapEmptyText", (-1).scaled())
textEditor.border = emptyBorder(left = 6)
textEditor.isOpaque = true
textEditor.background = PackageSearchUI.Colors.headerBackground
}
}
override fun build() = PackageSearchUI.boxPanel {
add(searchPanel)
add(headerPanel)
add(listPanel)
@Suppress("MagicNumber") // Dimension constants
minimumSize = Dimension(200.scaled(), minimumSize.height)
}
override fun getData(dataId: String) = null
private fun onSearchResultStateChanged(
searchResult: PackageModel.SearchResult,
overrideVersion: NormalizedPackageVersion<*>?,
overrideScope: PackageScope?
) {
project.lifecycleScope.launch {
val uiStates = searchResultsUiStateOverridesState.value.toMutableMap()
uiStates[searchResult.identifier] = SearchResultUiState(overrideVersion, overrideScope)
searchResultsUiStateOverridesState.emit(uiStates)
}
}
}
@Suppress("FunctionName")
private fun SearchTextFieldTextChangedListener(action: (DocumentEvent) -> Unit) =
object : DocumentAdapter() {
override fun textChanged(e: DocumentEvent) = action(e)
}
private fun SearchTextField.addOnTextChangedListener(action: (String) -> Unit) =
SearchTextFieldTextChangedListener { action(text) }.also { addDocumentListener(it) }
internal fun JCheckBox.addSelectionChangedListener(action: (Boolean) -> Unit) =
addItemListener { e -> action(e.stateChange == ItemEvent.SELECTED) }
private fun computeHeaderData(
totalItemsCount: Int,
packageUpdateInfos: List<PackagesToUpgrade.PackageUpgradeInfo>,
hasSearchResults: Boolean,
targetModules: TargetModules,
onComplete: (Duration) -> Unit = {}
): PackagesHeaderData {
val (result, time) = measureTimedValue {
val moduleNames = if (targetModules is TargetModules.One) {
targetModules.module.projectModule.name
} else {
PackageSearchBundle.message("packagesearch.ui.toolwindow.allModules").lowercase()
}
val title = if (hasSearchResults) {
PackageSearchBundle.message("packagesearch.ui.toolwindow.tab.packages.searchResults")
} else {
PackageSearchBundle.message("packagesearch.ui.toolwindow.tab.packages.installedPackages.addedIn", moduleNames)
}
PackagesHeaderData(
labelText = title,
count = totalItemsCount.coerceAtLeast(0),
availableUpdatesCount = packageUpdateInfos.distinctBy { it.packageModel.identifier }.size,
updateOperations = packageUpdateInfos.flatMap { it.computeUpgradeOperationsForSingleModule }
)
}
onComplete(time)
return result
}
private fun List<PackageModel.Installed>.filterByTargetModules(
targetModules: TargetModules
) = when (targetModules) {
is TargetModules.All -> this
is TargetModules.One -> mapNotNull { installedPackage ->
val filteredUsages = installedPackage.usageInfo.filter {
it.projectModule == targetModules.module.projectModule
}
if (filteredUsages.isEmpty()) return@mapNotNull null
installedPackage.copyWithUsages(filteredUsages)
}
TargetModules.None -> emptyList()
}
private suspend fun computeSearchResultModels(
searchResults: ApiPackagesResponse<ApiStandardPackage, ApiStandardPackage.ApiStandardVersion>?,
installedPackages: List<UiPackageModel.Installed>,
onlyStable: Boolean,
targetModules: TargetModules,
searchResultsUiStateOverrides: Map<PackageIdentifier, SearchResultUiState>,
knownRepositoriesInTargetModules: KnownRepositories.InTargetModules,
project: Project,
onComplete: (Duration) -> Unit = {},
cache: CoroutineLRUCache<UiPackageModelCacheKey, UiPackageModel.SearchResult>
): List<UiPackageModel.SearchResult> {
val (result, time) = measureTimedValue {
if (searchResults == null || searchResults.packages.isEmpty()) return@measureTimedValue emptyList()
val installedDependencies = installedPackages
.map { InstalledDependency(it.packageModel.groupId, it.packageModel.artifactId) }
val index = searchResults.packages.parallelMap { "${it.groupId}:${it.artifactId}" }
searchResults.packages
.parallelFilterNot { installedDependencies.any { installed -> installed.matchesCoordinates(it) } }
.parallelMapNotNull { PackageModel.fromSearchResult(it, packageVersionNormalizer) }
.parallelMap {
val uiState = searchResultsUiStateOverrides[it.identifier]
cache.getOrPut(UiPackageModelCacheKey(targetModules, uiState, onlyStable, it)) {
it.toUiPackageModel(targetModules, project, uiState, knownRepositoriesInTargetModules, onlyStable)
}
}
.sortedBy { index.indexOf(it.identifier.rawValue) }
}
onComplete(time)
return result
}
private suspend fun computeFilteredInstalledPackagesUiModels(
packages: List<PackageModel.Installed>,
onlyMultiplatform: Boolean,
targetModules: TargetModules,
knownRepositoriesInTargetModules: KnownRepositories.InTargetModules,
onlyStable: Boolean,
searchQuery: String,
project: Project,
onComplete: (Duration) -> Unit = {}
): List<UiPackageModel.Installed> {
val (result, time) = measureTimedValue {
packages.let { list -> if (onlyMultiplatform) list.filter { it.isKotlinMultiplatform } else list }
.parallelMap { it.toUiPackageModel(targetModules, project, knownRepositoriesInTargetModules, onlyStable) }
.filter { it.sortedVersions.isNotEmpty() && it.packageModel.searchableInfo.contains(searchQuery) }
}
onComplete(time)
return result
}
internal data class UiPackageModelCacheKey(
val targetModules: TargetModules,
val uiState: SearchResultUiState?,
val onlyStable: Boolean,
val searchResult: PackageModel.SearchResult
)
| apache-2.0 | 167afe3e9472569a0c9f87d94deb9fa1 | 45.794326 | 148 | 0.68448 | 5.797891 | false | false | false | false |
siosio/intellij-community | plugins/kotlin/gradle/gradle-tooling/src/KotlinCocoaPodsModelBuilder.kt | 1 | 1485 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.gradle
import org.gradle.api.Project
import org.jetbrains.plugins.gradle.tooling.AbstractModelBuilderService
import org.jetbrains.plugins.gradle.tooling.ErrorMessageBuilder
import org.jetbrains.plugins.gradle.tooling.ModelBuilderContext
private const val POD_IMPORT_TASK_NAME = "podImport"
interface EnablePodImportTask
class KotlinCocoaPodsModelBuilder : AbstractModelBuilderService() {
override fun canBuild(modelName: String?): Boolean {
return EnablePodImportTask::class.java.name == modelName
}
override fun buildAll(modelName: String, project: Project, context: ModelBuilderContext): Any? {
val startParameter = project.gradle.startParameter
val taskNames = mutableListOf<String>()
taskNames.addAll(startParameter.taskNames)
if (project.tasks.findByPath(POD_IMPORT_TASK_NAME) != null && POD_IMPORT_TASK_NAME !in taskNames) {
taskNames.add(POD_IMPORT_TASK_NAME)
startParameter.setTaskNames(taskNames)
}
return null
}
override fun getErrorMessageBuilder(project: Project, e: Exception): ErrorMessageBuilder {
return ErrorMessageBuilder.create(
project, e, "EnablePodImportTask error"
).withDescription("Unable to create $POD_IMPORT_TASK_NAME task.")
}
} | apache-2.0 | 717c557e6d6e1dd5588fec6b646ff4ce | 40.277778 | 158 | 0.740741 | 4.655172 | false | false | false | false |
siosio/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/codeInliner/CallableUsageReplacementStrategy.kt | 1 | 3418 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.codeInliner
import com.intellij.openapi.diagnostic.Logger
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.intentions.OperatorToFunctionIntention
import org.jetbrains.kotlin.idea.intentions.isInvokeOperator
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.getElementTextWithContext
import org.jetbrains.kotlin.psi.psiUtil.getPossiblyQualifiedCallExpression
import org.jetbrains.kotlin.resolve.calls.callUtil.getResolvedCall
import org.jetbrains.kotlin.resolve.calls.model.VariableAsFunctionResolvedCall
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
import org.jetbrains.kotlin.utils.KotlinExceptionWithAttachments
private val LOG = Logger.getInstance(CallableUsageReplacementStrategy::class.java)
class CallableUsageReplacementStrategy(
private val replacement: CodeToInline,
private val inlineSetter: Boolean = false
) : UsageReplacementStrategy {
override fun createReplacer(usage: KtReferenceExpression): (() -> KtElement?)? {
val bindingContext = usage.analyze(BodyResolveMode.PARTIAL_WITH_CFA)
val resolvedCall = usage.getResolvedCall(bindingContext) ?: return null
if (!resolvedCall.status.isSuccess) return null
val callElement = when (resolvedCall) {
is VariableAsFunctionResolvedCall -> {
val callElement = resolvedCall.variableCall.call.callElement
if (resolvedCall.resultingDescriptor.isInvokeOperator &&
replacement.mainExpression?.getPossiblyQualifiedCallExpression() != null
) {
callElement.parent as? KtCallExpression ?: callElement
} else {
callElement
}
}
else -> resolvedCall.call.callElement
}
if (!CodeInliner.canBeReplaced(callElement)) return null
//TODO: precheck pattern correctness for annotation entry
return when {
usage is KtArrayAccessExpression || usage is KtCallExpression -> {
{
val nameExpression = OperatorToFunctionIntention.convert(usage).second
createReplacer(nameExpression)?.invoke()
}
}
usage is KtOperationReferenceExpression && usage.getReferencedNameElementType() != KtTokens.IDENTIFIER -> {
{
val nameExpression = OperatorToFunctionIntention.convert(usage.parent as KtExpression).second
createReplacer(nameExpression)?.invoke()
}
}
usage is KtSimpleNameExpression -> {
{
CodeInliner(usage, bindingContext, resolvedCall, callElement, inlineSetter, replacement).doInline()
}
}
else -> {
val exceptionWithAttachments = KotlinExceptionWithAttachments("Unsupported usage")
.withAttachment("type", usage)
.withAttachment("usage", usage.getElementTextWithContext())
LOG.error(exceptionWithAttachments)
null
}
}
}
}
| apache-2.0 | b7d9730469b574879fe0b6d55e13b060 | 43.973684 | 158 | 0.669982 | 6.049558 | false | false | false | false |
jwren/intellij-community | platform/lang-impl/src/com/intellij/codeInsight/codeVision/ui/popup/CodeVisionPopupWrapper.kt | 4 | 3123 | package com.intellij.codeInsight.codeVision.ui.popup
import com.intellij.codeInsight.codeVision.ui.popup.layouter.DockingLayouter
import com.intellij.codeInsight.codeVision.ui.popup.layouter.location
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.ui.popup.JBPopupListener
import com.intellij.openapi.ui.popup.LightweightWindowEvent
import com.intellij.ui.awt.RelativePoint
import com.intellij.ui.popup.AbstractPopup
import com.jetbrains.rd.swing.escPressedSource
import com.jetbrains.rd.swing.mouseOrKeyReleased
import com.jetbrains.rd.util.getLogger
import com.jetbrains.rd.util.lifetime.Lifetime
import com.jetbrains.rd.util.lifetime.LifetimeDefinition
import com.jetbrains.rd.util.lifetime.isAlive
import com.jetbrains.rd.util.lifetime.onTermination
import com.jetbrains.rd.util.reactive.IProperty
import com.jetbrains.rd.util.warn
import java.awt.Dimension
class CodeVisionPopupWrapper(
val mainLTD: LifetimeDefinition,
val editor: Editor,
val popupFactory: (Lifetime) -> AbstractPopup,
val popupLayouter: DockingLayouter,
val lensPopupActive: IProperty<Boolean>
) {
private val logger = getLogger<CodeVisionPopupWrapper>()
var popup: AbstractPopup? = null
var ltd: LifetimeDefinition? = null
var processing = false
init {
escPressedSource().advise(mainLTD) {
mainLTD.terminate()
}
mainLTD.onTermination {
close()
}
}
fun show() {
if (mainLTD.isAlive) {
createPopup(mainLTD.createNested())
}
}
fun hide(lt: Lifetime) {
processing = true
close()
mouseOrKeyReleased().advise(lt) {
mainLTD.terminate()
}
}
private fun close() {
ltd?.terminate()
ltd = null
lensPopupActive.set(false)
}
private fun createPopup(lifetimeDefinition: LifetimeDefinition) {
lensPopupActive.set(true)
ltd = lifetimeDefinition
val pp = popupFactory(lifetimeDefinition)
popup = pp
pp.pack(true, true)
val listener = object : JBPopupListener {
override fun onClosed(event: LightweightWindowEvent) {
if (event.isOk || !processing) {
mainLTD.terminate(true)
}
processing = false
}
}
pp.addListener(listener)
lifetimeDefinition.onTermination {
val cancelingPopup = popup ?: return@onTermination
if (cancelingPopup.canClose()) {
if (cancelingPopup.isDisposed)
cancelingPopup.removeListener(listener)
cancelingPopup.cancel()
}
popup = null
}
val possibleSize = pp.sizeForPositioning
val probablyRealSize = Dimension(possibleSize.width, possibleSize.height - pp.headerPreferredSize.height)
popupLayouter.size.set(probablyRealSize)
val location = popupLayouter.layout.value?.location
popupLayouter.layout.advise(lifetimeDefinition) {
if (it != null) {
pp.setLocation(it.location)
}
}
if (location != null) {
pp.show(RelativePoint(location))
}
else {
logger.warn { "location == null, this can't be right" }
pp.showInBestPositionFor(editor)
popupLayouter.size.set(pp.size)
}
}
}
| apache-2.0 | 1b219adc1cf745d14c02393303719a7f | 25.243697 | 109 | 0.713417 | 4.225981 | false | false | false | false |
SimpleMobileTools/Simple-Calendar | app/src/main/kotlin/com/simplemobiletools/calendar/pro/adapters/MyWeekPagerAdapter.kt | 1 | 1658 | package com.simplemobiletools.calendar.pro.adapters
import android.os.Bundle
import android.util.SparseArray
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import androidx.fragment.app.FragmentStatePagerAdapter
import com.simplemobiletools.calendar.pro.fragments.WeekFragment
import com.simplemobiletools.calendar.pro.helpers.WEEK_START_TIMESTAMP
import com.simplemobiletools.calendar.pro.interfaces.WeekFragmentListener
class MyWeekPagerAdapter(fm: FragmentManager, private val mWeekTimestamps: List<Long>, private val mListener: WeekFragmentListener) :
FragmentStatePagerAdapter(fm) {
private val mFragments = SparseArray<WeekFragment>()
override fun getCount() = mWeekTimestamps.size
override fun getItem(position: Int): Fragment {
val bundle = Bundle()
val weekTimestamp = mWeekTimestamps[position]
bundle.putLong(WEEK_START_TIMESTAMP, weekTimestamp)
val fragment = WeekFragment()
fragment.arguments = bundle
fragment.listener = mListener
mFragments.put(position, fragment)
return fragment
}
fun updateScrollY(pos: Int, y: Int) {
mFragments[pos - 1]?.updateScrollY(y)
mFragments[pos + 1]?.updateScrollY(y)
}
fun updateCalendars(pos: Int) {
for (i in -1..1) {
mFragments[pos + i]?.updateCalendar()
}
}
fun updateNotVisibleScaleLevel(pos: Int) {
mFragments[pos - 1]?.updateNotVisibleViewScaleLevel()
mFragments[pos + 1]?.updateNotVisibleViewScaleLevel()
}
fun togglePrintMode(pos: Int) {
mFragments[pos].togglePrintMode()
}
}
| gpl-3.0 | 9f59a4d5b7002fc5d9680ff21ccc6918 | 32.16 | 133 | 0.718335 | 4.530055 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/completion/src/org/jetbrains/kotlin/idea/completion/smart/SmartCompletion.kt | 1 | 23358 | // 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.completion.smart
import com.intellij.codeInsight.completion.EmptyDeclarativeInsertHandler
import com.intellij.codeInsight.completion.InsertHandler
import com.intellij.codeInsight.completion.OffsetKey
import com.intellij.codeInsight.completion.PrefixMatcher
import com.intellij.codeInsight.lookup.*
import com.intellij.openapi.progress.ProgressManager
import com.intellij.psi.PsiElement
import com.intellij.psi.search.GlobalSearchScope
import com.intellij.util.SmartList
import org.jetbrains.kotlin.config.LanguageFeature
import org.jetbrains.kotlin.descriptors.*
import org.jetbrains.kotlin.idea.KotlinIcons
import org.jetbrains.kotlin.idea.caches.resolve.resolveToDescriptorIfAny
import org.jetbrains.kotlin.idea.completion.*
import org.jetbrains.kotlin.idea.completion.handlers.WithTailInsertHandler
import org.jetbrains.kotlin.idea.core.*
import org.jetbrains.kotlin.idea.project.languageVersionSettings
import org.jetbrains.kotlin.idea.resolve.ResolutionFacade
import org.jetbrains.kotlin.idea.util.CallTypeAndReceiver
import org.jetbrains.kotlin.idea.util.isAlmostEverything
import org.jetbrains.kotlin.idea.util.toFuzzyType
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.renderer.render
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.DescriptorUtils
import org.jetbrains.kotlin.types.KotlinType
import org.jetbrains.kotlin.types.TypeUtils
import org.jetbrains.kotlin.types.isError
import org.jetbrains.kotlin.types.typeUtil.isBooleanOrNullableBoolean
import org.jetbrains.kotlin.types.typeUtil.makeNotNullable
import org.jetbrains.kotlin.utils.addIfNotNull
interface InheritanceItemsSearcher {
fun search(nameFilter: (String) -> Boolean, consumer: (LookupElement) -> Unit)
}
class SmartCompletion(
private val expression: KtExpression,
private val resolutionFacade: ResolutionFacade,
private val bindingContext: BindingContext,
private val moduleDescriptor: ModuleDescriptor,
private val visibilityFilter: (DeclarationDescriptor) -> Boolean,
private val indicesHelper: KotlinIndicesHelper,
private val prefixMatcher: PrefixMatcher,
private val inheritorSearchScope: GlobalSearchScope,
private val toFromOriginalFileMapper: ToFromOriginalFileMapper,
private val callTypeAndReceiver: CallTypeAndReceiver<*, *>,
private val isJvmModule: Boolean,
private val forBasicCompletion: Boolean = false
) {
private val expressionWithType = when (callTypeAndReceiver) {
is CallTypeAndReceiver.DEFAULT ->
expression
is CallTypeAndReceiver.DOT,
is CallTypeAndReceiver.SAFE,
is CallTypeAndReceiver.SUPER_MEMBERS,
is CallTypeAndReceiver.INFIX,
is CallTypeAndReceiver.CALLABLE_REFERENCE ->
expression.parent as KtExpression
else -> // actually no smart completion for such places
expression
}
val expectedInfos: Collection<ExpectedInfo> = calcExpectedInfos(expressionWithType)
private val callableTypeExpectedInfo = expectedInfos.filterCallableExpected()
val smartCastCalculator: SmartCastCalculator by lazy(LazyThreadSafetyMode.NONE) {
SmartCastCalculator(
bindingContext,
resolutionFacade.moduleDescriptor,
expression,
callTypeAndReceiver.receiver as? KtExpression,
resolutionFacade
)
}
val descriptorFilter: ((DeclarationDescriptor, AbstractLookupElementFactory) -> Collection<LookupElement>)? =
{ descriptor: DeclarationDescriptor, factory: AbstractLookupElementFactory ->
filterDescriptor(descriptor, factory).map { postProcess(it) }
}.takeIf { expectedInfos.isNotEmpty() }
fun additionalItems(lookupElementFactory: LookupElementFactory): Pair<Collection<LookupElement>, InheritanceItemsSearcher?> {
val (items, inheritanceSearcher) = additionalItemsNoPostProcess(lookupElementFactory)
val postProcessedItems = items.map { postProcess(it) }
//TODO: could not use "let" because of KT-8754
val postProcessedSearcher = if (inheritanceSearcher != null)
object : InheritanceItemsSearcher {
override fun search(nameFilter: (String) -> Boolean, consumer: (LookupElement) -> Unit) {
inheritanceSearcher.search(nameFilter) { consumer(postProcess(it)) }
}
}
else
null
return postProcessedItems to postProcessedSearcher
}
val descriptorsToSkip: Set<DeclarationDescriptor> by lazy<Set<DeclarationDescriptor>> {
val parent = expressionWithType.parent
when (parent) {
is KtBinaryExpression -> {
if (parent.right == expressionWithType) {
val operationToken = parent.operationToken
if (operationToken == KtTokens.EQ || operationToken in COMPARISON_TOKENS) {
val left = parent.left
if (left is KtReferenceExpression) {
return@lazy bindingContext[BindingContext.REFERENCE_TARGET, left]?.let(::setOf).orEmpty()
}
}
}
}
is KtWhenConditionWithExpression -> {
val entry = parent.parent as KtWhenEntry
val whenExpression = entry.parent as KtWhenExpression
val subject = whenExpression.subjectExpression ?: return@lazy emptySet()
val descriptorsToSkip = HashSet<DeclarationDescriptor>()
if (subject is KtSimpleNameExpression) {
val variable = bindingContext[BindingContext.REFERENCE_TARGET, subject] as? VariableDescriptor
if (variable != null) {
descriptorsToSkip.add(variable)
}
}
val subjectType = bindingContext.getType(subject) ?: return@lazy emptySet()
val classDescriptor = TypeUtils.getClassDescriptor(subjectType)
if (classDescriptor != null && DescriptorUtils.isEnumClass(classDescriptor)) {
val conditions =
whenExpression.entries.flatMap { it.conditions.toList() }.filterIsInstance<KtWhenConditionWithExpression>()
for (condition in conditions) {
val selectorExpr =
(condition.expression as? KtDotQualifiedExpression)?.selectorExpression as? KtReferenceExpression ?: continue
val target = bindingContext[BindingContext.REFERENCE_TARGET, selectorExpr] as? ClassDescriptor ?: continue
if (DescriptorUtils.isEnumEntry(target)) {
descriptorsToSkip.add(target)
}
}
}
return@lazy descriptorsToSkip
}
}
return@lazy emptySet()
}
private fun filterDescriptor(
descriptor: DeclarationDescriptor,
lookupElementFactory: AbstractLookupElementFactory
): Collection<LookupElement> {
ProgressManager.checkCanceled()
if (descriptor in descriptorsToSkip) return emptyList()
val result = SmartList<LookupElement>()
val types = descriptor.fuzzyTypesForSmartCompletion(smartCastCalculator, callTypeAndReceiver, resolutionFacade, bindingContext)
val infoMatcher = { expectedInfo: ExpectedInfo -> types.matchExpectedInfo(expectedInfo) }
result.addLookupElements(
descriptor,
expectedInfos,
infoMatcher,
noNameSimilarityForReturnItself = callTypeAndReceiver is CallTypeAndReceiver.DEFAULT
) { declarationDescriptor ->
lookupElementFactory.createStandardLookupElementsForDescriptor(declarationDescriptor, useReceiverTypes = true)
}
if (callTypeAndReceiver is CallTypeAndReceiver.DEFAULT) {
result.addCallableReferenceLookupElements(descriptor, lookupElementFactory)
}
return result
}
private fun additionalItemsNoPostProcess(lookupElementFactory: LookupElementFactory): Pair<Collection<LookupElement>, InheritanceItemsSearcher?> {
val asTypePositionItems = buildForAsTypePosition(lookupElementFactory.basicFactory)
if (asTypePositionItems != null) {
assert(expectedInfos.isEmpty())
return Pair(asTypePositionItems, null)
}
val items = ArrayList<LookupElement>()
val inheritanceSearchers = ArrayList<InheritanceItemsSearcher>()
if (!forBasicCompletion) { // basic completion adds keyword values on its own
val keywordValueConsumer = object : KeywordValues.Consumer {
override fun consume(
lookupString: String,
expectedInfoMatcher: (ExpectedInfo) -> ExpectedInfoMatch,
suitableOnPsiLevel: PsiElement.() -> Boolean,
priority: SmartCompletionItemPriority,
factory: () -> LookupElement
) {
items.addLookupElements(null, expectedInfos, expectedInfoMatcher) {
val lookupElement = factory()
lookupElement.putUserData(SMART_COMPLETION_ITEM_PRIORITY_KEY, priority)
listOf(lookupElement)
}
}
}
KeywordValues.process(
keywordValueConsumer,
callTypeAndReceiver,
bindingContext,
resolutionFacade,
moduleDescriptor,
isJvmModule
)
}
if (expectedInfos.isNotEmpty()) {
items.addArrayLiteralsInAnnotationsCompletions()
if (!forBasicCompletion && (callTypeAndReceiver is CallTypeAndReceiver.DEFAULT || callTypeAndReceiver is CallTypeAndReceiver.UNKNOWN /* after this@ */)) {
items.addThisItems(expression, expectedInfos, smartCastCalculator)
}
if (callTypeAndReceiver is CallTypeAndReceiver.DEFAULT) {
TypeInstantiationItems(
resolutionFacade,
bindingContext,
visibilityFilter,
toFromOriginalFileMapper,
inheritorSearchScope,
lookupElementFactory,
forBasicCompletion,
indicesHelper
).addTo(items, inheritanceSearchers, expectedInfos)
if (expression is KtSimpleNameExpression) {
StaticMembers(bindingContext, lookupElementFactory, resolutionFacade, moduleDescriptor).addToCollection(
items,
expectedInfos,
expression,
descriptorsToSkip
)
}
ClassLiteralItems.addToCollection(items, expectedInfos, lookupElementFactory.basicFactory, isJvmModule)
items.addNamedArgumentsWithLiteralValueItems(expectedInfos)
LambdaSignatureItems.addToCollection(items, expressionWithType, bindingContext, resolutionFacade)
if (!forBasicCompletion) {
LambdaItems.addToCollection(items, expectedInfos)
val whenCondition = expressionWithType.parent as? KtWhenConditionWithExpression
if (whenCondition != null) {
val entry = whenCondition.parent as KtWhenEntry
val whenExpression = entry.parent as KtWhenExpression
val entries = whenExpression.entries
if (whenExpression.elseExpression == null && entry == entries.last() && entries.size != 1) {
val lookupElement = LookupElementBuilder.create("else")
.bold()
.withTailText(" ->")
.withInsertHandler(
WithTailInsertHandler("->", spaceBefore = true, spaceAfter = true).asPostInsertHandler
)
items.add(lookupElement)
}
}
}
MultipleArgumentsItemProvider(bindingContext, smartCastCalculator, resolutionFacade).addToCollection(
items,
expectedInfos,
expression
)
}
}
val inheritanceSearcher = if (inheritanceSearchers.isNotEmpty())
object : InheritanceItemsSearcher {
override fun search(nameFilter: (String) -> Boolean, consumer: (LookupElement) -> Unit) {
inheritanceSearchers.forEach { it.search(nameFilter, consumer) }
}
}
else
null
return Pair(items, inheritanceSearcher)
}
private fun postProcess(item: LookupElement): LookupElement {
if (forBasicCompletion) return item
return if (item.getUserData(KEEP_OLD_ARGUMENT_LIST_ON_TAB_KEY) == null) {
LookupElementDecorator.withDelegateInsertHandler(
item,
InsertHandler { context, element ->
if (context.completionChar == Lookup.REPLACE_SELECT_CHAR) {
val offset = context.offsetMap.tryGetOffset(OLD_ARGUMENTS_REPLACEMENT_OFFSET)
if (offset != null) {
context.document.deleteString(context.tailOffset, offset)
}
}
element.handleInsert(context)
}
)
} else {
item
}
}
private fun MutableCollection<LookupElement>.addThisItems(
place: KtExpression,
expectedInfos: Collection<ExpectedInfo>,
smartCastCalculator: SmartCastCalculator
) {
if (shouldCompleteThisItems(prefixMatcher)) {
val items = thisExpressionItems(bindingContext, place, prefixMatcher.prefix, resolutionFacade)
for (item in items) {
val types = smartCastCalculator.types(item.receiverParameter).map { it.toFuzzyType(emptyList()) }
val matcher = { expectedInfo: ExpectedInfo -> types.matchExpectedInfo(expectedInfo) }
addLookupElements(null, expectedInfos, matcher) {
listOf(item.createLookupElement().assignSmartCompletionPriority(SmartCompletionItemPriority.THIS))
}
}
}
}
private fun MutableCollection<LookupElement>.addNamedArgumentsWithLiteralValueItems(expectedInfos: Collection<ExpectedInfo>) {
data class NameAndValue(val name: Name, val value: String, val priority: SmartCompletionItemPriority)
val nameAndValues = HashMap<NameAndValue, MutableList<ExpectedInfo>>()
fun addNameAndValue(name: Name, value: String, priority: SmartCompletionItemPriority, expectedInfo: ExpectedInfo) {
nameAndValues.getOrPut(NameAndValue(name, value, priority)) { ArrayList() }.add(expectedInfo)
}
for (expectedInfo in expectedInfos) {
val argumentData = expectedInfo.additionalData as? ArgumentPositionData.Positional ?: continue
if (argumentData.namedArgumentCandidates.isEmpty()) continue
val parameters = argumentData.function.valueParameters
if (argumentData.argumentIndex >= parameters.size) continue
val parameterName = parameters[argumentData.argumentIndex].name
if (expectedInfo.fuzzyType?.type?.isBooleanOrNullableBoolean() == true) {
addNameAndValue(parameterName, "true", SmartCompletionItemPriority.NAMED_ARGUMENT_TRUE, expectedInfo)
addNameAndValue(parameterName, "false", SmartCompletionItemPriority.NAMED_ARGUMENT_FALSE, expectedInfo)
}
if (expectedInfo.fuzzyType?.type?.isMarkedNullable == true) {
addNameAndValue(parameterName, "null", SmartCompletionItemPriority.NAMED_ARGUMENT_NULL, expectedInfo)
}
}
for ((nameAndValue, infos) in nameAndValues) {
var lookupElement = createNamedArgumentWithValueLookupElement(nameAndValue.name, nameAndValue.value, nameAndValue.priority)
lookupElement = lookupElement.addTail(mergeTails(infos.map { it.tail }))
add(lookupElement)
}
}
private fun createNamedArgumentWithValueLookupElement(name: Name, value: String, priority: SmartCompletionItemPriority): LookupElement {
val lookupElement = LookupElementBuilder.create("${name.asString()} = $value")
.withIcon(KotlinIcons.PARAMETER)
.withInsertHandler { context, _ ->
context.document.replaceString(context.startOffset, context.tailOffset, "${name.render()} = $value")
}
lookupElement.putUserData(SmartCompletionInBasicWeigher.NAMED_ARGUMENT_KEY, Unit)
lookupElement.assignSmartCompletionPriority(priority)
return lookupElement
}
private fun calcExpectedInfos(expression: KtExpression): Collection<ExpectedInfo> {
// if our expression is initializer of implicitly typed variable - take type of variable from original file (+ the same for function)
val declaration = implicitlyTypedDeclarationFromInitializer(expression)
if (declaration != null) {
val originalDeclaration = toFromOriginalFileMapper.toOriginalFile(declaration)
if (originalDeclaration != null) {
val originalDescriptor = originalDeclaration.resolveToDescriptorIfAny() as? CallableDescriptor
val returnType = originalDescriptor?.returnType
if (returnType != null && !returnType.isError) {
return listOf(ExpectedInfo(returnType, declaration.name, null))
}
}
}
// if expected types are too general, try to use expected type from outer calls
var count = 0
while (true) {
val infos =
ExpectedInfos(bindingContext, resolutionFacade, indicesHelper, useOuterCallsExpectedTypeCount = count).calculate(expression)
if (count == 2 /* use two outer calls maximum */ || infos.none { it.fuzzyType?.isAlmostEverything() ?: false }) {
return if (forBasicCompletion)
infos.map { it.copy(tail = null) }
else
infos
}
count++
}
//TODO: we could always give higher priority to results with outer call expected type used
}
private fun implicitlyTypedDeclarationFromInitializer(expression: KtExpression): KtDeclaration? {
val parent = expression.parent
when (parent) {
is KtVariableDeclaration -> if (expression == parent.initializer && parent.typeReference == null) return parent
is KtNamedFunction -> if (expression == parent.initializer && parent.typeReference == null) return parent
}
return null
}
private fun MutableCollection<LookupElement>.addCallableReferenceLookupElements(
descriptor: DeclarationDescriptor,
lookupElementFactory: AbstractLookupElementFactory
) {
if (callableTypeExpectedInfo.isEmpty()) return
fun toLookupElement(descriptor: CallableDescriptor): LookupElement? {
val callableReferenceType = descriptor.callableReferenceType(resolutionFacade, null) ?: return null
val matchedExpectedInfos = callableTypeExpectedInfo.filter { it.matchingSubstitutor(callableReferenceType) != null }
if (matchedExpectedInfos.isEmpty()) return null
var lookupElement =
lookupElementFactory.createLookupElement(descriptor, useReceiverTypes = false, parametersAndTypeGrayed = true)
?: return null
lookupElement = object : LookupElementDecorator<LookupElement>(lookupElement) {
override fun getLookupString() = "::" + delegate.lookupString
override fun getAllLookupStrings() = setOf(lookupString)
override fun renderElement(presentation: LookupElementPresentation) {
super.renderElement(presentation)
presentation.itemText = "::" + presentation.itemText
}
override fun getDelegateInsertHandler() = EmptyDeclarativeInsertHandler
}
return lookupElement.assignSmartCompletionPriority(SmartCompletionItemPriority.CALLABLE_REFERENCE)
.addTailAndNameSimilarity(matchedExpectedInfos)
}
when (descriptor) {
is CallableDescriptor -> {
// members and extensions are not supported after "::" currently
if (descriptor.dispatchReceiverParameter == null && descriptor.extensionReceiverParameter == null) {
addIfNotNull(toLookupElement(descriptor))
}
}
is ClassDescriptor -> {
if (descriptor.modality != Modality.ABSTRACT && !descriptor.isInner) {
descriptor.constructors.filter(visibilityFilter).mapNotNullTo(this, ::toLookupElement)
}
}
}
}
private fun buildForAsTypePosition(lookupElementFactory: BasicLookupElementFactory): Collection<LookupElement>? {
val binaryExpression =
((expression.parent as? KtUserType)?.parent as? KtTypeReference)?.parent as? KtBinaryExpressionWithTypeRHS ?: return null
val elementType = binaryExpression.operationReference.getReferencedNameElementType()
if (elementType != KtTokens.AS_KEYWORD && elementType != KtTokens.AS_SAFE) return null
val expectedInfos = calcExpectedInfos(binaryExpression)
val expectedInfosGrouped: Map<KotlinType?, List<ExpectedInfo>> = expectedInfos.groupBy { it.fuzzyType?.type?.makeNotNullable() }
val items = ArrayList<LookupElement>()
for ((type, infos) in expectedInfosGrouped) {
if (type == null) continue
val lookupElement = lookupElementFactory.createLookupElementForType(type) ?: continue
items.add(lookupElement.addTailAndNameSimilarity(infos))
}
return items
}
private fun MutableCollection<LookupElement>.addArrayLiteralsInAnnotationsCompletions() {
if (expression.languageVersionSettings.supportsFeature(LanguageFeature.ArrayLiteralsInAnnotations)) {
this.addAll(ArrayLiteralsInAnnotationItems.collect(expectedInfos, expression))
}
}
companion object {
val OLD_ARGUMENTS_REPLACEMENT_OFFSET: OffsetKey = OffsetKey.create("nonFunctionReplacementOffset")
val MULTIPLE_ARGUMENTS_REPLACEMENT_OFFSET: OffsetKey = OffsetKey.create("multipleArgumentsReplacementOffset")
}
}
| apache-2.0 | 6a9f8562965d37c4a2e4273c416f3db1 | 46.766871 | 166 | 0.649542 | 6.245455 | false | false | false | false |
mglukhikh/intellij-community | uast/uast-java/src/org/jetbrains/uast/java/expressions/javaUCallExpressions.kt | 1 | 7720 | /*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.uast.java
import com.intellij.psi.*
import com.intellij.psi.util.PsiTreeUtil
import com.intellij.psi.util.PsiTypesUtil
import org.jetbrains.uast.*
import org.jetbrains.uast.psi.UElementWithLocation
class JavaUCallExpression(
override val psi: PsiMethodCallExpression,
givenParent: UElement?
) : JavaAbstractUExpression(givenParent), UCallExpressionEx, UElementWithLocation {
override val kind: UastCallKind
get() = UastCallKind.METHOD_CALL
override val methodIdentifier by lz {
val methodExpression = psi.methodExpression
val nameElement = methodExpression.referenceNameElement ?: return@lz null
UIdentifier(nameElement, this)
}
override val classReference: UReferenceExpression?
get() = null
override val valueArgumentCount by lz { psi.argumentList.expressions.size }
override val valueArguments by lz { psi.argumentList.expressions.map { JavaConverter.convertOrEmpty(it, this) } }
override fun getArgumentForParameter(i: Int): UExpression? = valueArguments.getOrNull(i)
override val typeArgumentCount by lz { psi.typeArguments.size }
override val typeArguments: List<PsiType>
get() = psi.typeArguments.toList()
override val returnType: PsiType?
get() = psi.type
override val methodName: String?
get() = psi.methodExpression.referenceName
override fun resolve() = psi.resolveMethod()
override fun getStartOffset(): Int =
psi.methodExpression.referenceNameElement?.textOffset ?: psi.methodExpression.textOffset
override fun getEndOffset() = psi.textRange.endOffset
override val receiver: UExpression?
get() {
uastParent.let { uastParent ->
return if (uastParent is UQualifiedReferenceExpression && uastParent.selector == this)
uastParent.receiver
else
null
}
}
override val receiverType: PsiType?
get() {
val qualifierType = psi.methodExpression.qualifierExpression?.type
if (qualifierType != null) {
return qualifierType
}
val method = resolve() ?: return null
if (method.hasModifierProperty(PsiModifier.STATIC)) return null
val psiManager = psi.manager
val containingClassForMethod = method.containingClass ?: return null
val containingClass = PsiTreeUtil.getParentOfType(psi, PsiClass::class.java)
val containingClassSequence = generateSequence(containingClass) {
if (it.hasModifierProperty(PsiModifier.STATIC))
null
else
PsiTreeUtil.getParentOfType(it, PsiClass::class.java)
}
val receiverClass = containingClassSequence.find { containingClassForExpression ->
psiManager.areElementsEquivalent(containingClassForMethod, containingClassForExpression) ||
containingClassForExpression.isInheritor(containingClassForMethod, true)
}
return receiverClass?.let { PsiTypesUtil.getClassType(it) }
}
}
class JavaConstructorUCallExpression(
override val psi: PsiNewExpression,
givenParent: UElement?
) : JavaAbstractUExpression(givenParent), UCallExpressionEx {
override val kind by lz {
when {
psi.arrayInitializer != null -> UastCallKind.NEW_ARRAY_WITH_INITIALIZER
psi.arrayDimensions.isNotEmpty() -> UastCallKind.NEW_ARRAY_WITH_DIMENSIONS
else -> UastCallKind.CONSTRUCTOR_CALL
}
}
override val receiver: UExpression?
get() = null
override val receiverType: PsiType?
get() = null
override val methodIdentifier: UIdentifier?
get() = null
override val classReference by lz {
psi.classReference?.let { ref ->
JavaConverter.convertReference(ref, this, null) as? UReferenceExpression
}
}
override val valueArgumentCount: Int
get() {
val initializer = psi.arrayInitializer
return when {
initializer != null -> initializer.initializers.size
psi.arrayDimensions.isNotEmpty() -> psi.arrayDimensions.size
else -> psi.argumentList?.expressions?.size ?: 0
}
}
override val valueArguments by lz {
val initializer = psi.arrayInitializer
when {
initializer != null -> initializer.initializers.map { JavaConverter.convertOrEmpty(it, this) }
psi.arrayDimensions.isNotEmpty() -> psi.arrayDimensions.map { JavaConverter.convertOrEmpty(it, this) }
else -> psi.argumentList?.expressions?.map { JavaConverter.convertOrEmpty(it, this) } ?: emptyList()
}
}
override fun getArgumentForParameter(i: Int): UExpression? = valueArguments.getOrNull(i)
override val typeArgumentCount by lz { psi.classReference?.typeParameters?.size ?: 0 }
override val typeArguments: List<PsiType>
get() = psi.classReference?.typeParameters?.toList() ?: emptyList()
override val returnType: PsiType?
get() = (psi.classReference?.resolve() as? PsiClass)?.let { PsiTypesUtil.getClassType(it) } ?: psi.type
override val methodName: String?
get() = null
override fun resolve() = psi.resolveMethod()
}
class JavaArrayInitializerUCallExpression(
override val psi: PsiArrayInitializerExpression,
givenParent: UElement?
) : JavaAbstractUExpression(givenParent), UCallExpressionEx {
override val methodIdentifier: UIdentifier?
get() = null
override val classReference: UReferenceExpression?
get() = null
override val methodName: String?
get() = null
override val valueArgumentCount by lz { psi.initializers.size }
override val valueArguments by lz { psi.initializers.map { JavaConverter.convertOrEmpty(it, this) } }
override fun getArgumentForParameter(i: Int): UExpression? = valueArguments.getOrNull(i)
override val typeArgumentCount: Int
get() = 0
override val typeArguments: List<PsiType>
get() = emptyList()
override val returnType: PsiType?
get() = psi.type
override val kind: UastCallKind
get() = UastCallKind.NESTED_ARRAY_INITIALIZER
override fun resolve() = null
override val receiver: UExpression?
get() = null
override val receiverType: PsiType?
get() = null
}
class JavaAnnotationArrayInitializerUCallExpression(
override val psi: PsiArrayInitializerMemberValue,
givenParent: UElement?
) : JavaAbstractUExpression(givenParent), UCallExpressionEx {
override fun getArgumentForParameter(i: Int): UExpression? = valueArguments.getOrNull(i)
override val kind: UastCallKind
get() = UastCallKind.NESTED_ARRAY_INITIALIZER
override val methodIdentifier: UIdentifier?
get() = null
override val classReference: UReferenceExpression?
get() = null
override val methodName: String?
get() = null
override val valueArgumentCount by lz { psi.initializers.size }
override val valueArguments by lz {
psi.initializers.map {
JavaConverter.convertPsiElement(it, this) as? UExpression ?: UnknownJavaExpression(it, this)
}
}
override val typeArgumentCount: Int
get() = 0
override val typeArguments: List<PsiType>
get() = emptyList()
override val returnType: PsiType?
get() = null
override fun resolve() = null
override val receiver: UExpression?
get() = null
override val receiverType: PsiType?
get() = null
} | apache-2.0 | 6f699a448b9370d3f0e9b58d0150624a | 30.259109 | 115 | 0.72772 | 4.990304 | false | false | false | false |
smmribeiro/intellij-community | platform/configuration-store-impl/testSrc/CodeStyleTest.kt | 5 | 8274 | // 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.configurationStore
import com.intellij.application.options.CodeStyle
import com.intellij.openapi.util.JDOMUtil
import com.intellij.psi.codeStyle.CodeStyleSettings
import com.intellij.psi.codeStyle.CodeStyleSettingsProvider
import com.intellij.psi.codeStyle.CustomCodeStyleSettings
import com.intellij.testFramework.DisposableRule
import com.intellij.testFramework.ExtensionTestUtil
import com.intellij.testFramework.ProjectRule
import com.intellij.testFramework.assertions.Assertions.assertThat
import com.intellij.util.containers.ContainerUtil
import org.jdom.Element
import org.junit.ClassRule
import org.junit.Rule
import org.junit.Test
internal class CodeStyleTest {
companion object {
@JvmField
@ClassRule
val projectRule = ProjectRule(runPostStartUpActivities = false)
}
@JvmField
@Rule
val disposableRule = DisposableRule()
@Test
fun `do not remove unknown`() {
val settings = CodeStyle.createTestSettings()
val loaded = """
<code_scheme name="testSchemeName" version="${CodeStyleSettings.CURR_VERSION}">
<UnknownDoNotRemoveMe>
<option name="ALIGN_OBJECT_PROPERTIES" value="2" />
</UnknownDoNotRemoveMe>
<codeStyleSettings language="CoffeeScript">
<option name="KEEP_SIMPLE_METHODS_IN_ONE_LINE" value="true" />
</codeStyleSettings>
<codeStyleSettings language="DB2">
<option name="KEEP_LINE_BREAKS" value="false" />
</codeStyleSettings>
<codeStyleSettings language="Derby">
<option name="KEEP_LINE_BREAKS" value="false" />
</codeStyleSettings>
<codeStyleSettings language="Gherkin">
<indentOptions>
<option name="USE_TAB_CHARACTER" value="true" />
</indentOptions>
</codeStyleSettings>
<codeStyleSettings language="H2">
<option name="KEEP_LINE_BREAKS" value="false" />
</codeStyleSettings>
<codeStyleSettings language="HSQLDB">
<option name="KEEP_LINE_BREAKS" value="false" />
</codeStyleSettings>
<codeStyleSettings language="MySQL">
<option name="KEEP_LINE_BREAKS" value="false" />
</codeStyleSettings>
<codeStyleSettings language="Oracle">
<option name="KEEP_LINE_BREAKS" value="false" />
</codeStyleSettings>
<codeStyleSettings language="PostgreSQL">
<option name="KEEP_LINE_BREAKS" value="false" />
</codeStyleSettings>
<codeStyleSettings language="SQL">
<option name="KEEP_LINE_BREAKS" value="false" />
</codeStyleSettings>
<codeStyleSettings language="SQLite">
<option name="KEEP_LINE_BREAKS" value="false" />
</codeStyleSettings>
<codeStyleSettings language="Sybase">
<option name="KEEP_LINE_BREAKS" value="false" />
</codeStyleSettings>
<codeStyleSettings language="TSQL">
<option name="KEEP_LINE_BREAKS" value="false" />
</codeStyleSettings>
</code_scheme>""".trimIndent()
settings.readExternal(JDOMUtil.load(loaded))
val serialized = Element("code_scheme").setAttribute("name", "testSchemeName")
settings.writeExternal(serialized)
assertThat(serialized).isEqualTo(loaded)
}
@Test fun `do not duplicate known extra sections`() {
val newProvider: CodeStyleSettingsProvider = object : CodeStyleSettingsProvider() {
override fun createCustomSettings(settings: CodeStyleSettings?): CustomCodeStyleSettings {
return object : CustomCodeStyleSettings("NewComponent", settings) {
override fun getKnownTagNames(): List<String> {
return ContainerUtil.concat(super.getKnownTagNames(), listOf("NewComponent-extra"))
}
override fun writeExternal(parentElement: Element?, parentSettings: CustomCodeStyleSettings) {
super.writeExternal(parentElement, parentSettings)
writeMain(parentElement)
writeExtra(parentElement)
}
private fun writeMain(parentElement: Element?) {
var extra = parentElement!!.getChild(tagName)
if (extra == null) {
extra = Element(tagName)
parentElement.addContent(extra)
}
val option = Element("option")
option.setAttribute("name", "MAIN")
option.setAttribute("value", "3")
extra.addContent(option)
}
private fun writeExtra(parentElement: Element?) {
val extra = Element("NewComponent-extra")
val option = Element("option")
option.setAttribute("name", "EXTRA")
option.setAttribute("value", "3")
extra.addContent(option)
parentElement!!.addContent(extra)
}
}
}
}
ExtensionTestUtil.maskExtensions(CodeStyleSettingsProvider.EXTENSION_POINT_NAME, listOf(newProvider), disposableRule.disposable)
val settings = CodeStyle.createTestSettings()
fun text(param: String): String {
return """
<code_scheme name="testSchemeName" version="${CodeStyleSettings.CURR_VERSION}">
<NewComponent>
<option name="MAIN" value="${param}" />
</NewComponent>
<NewComponent-extra>
<option name="EXTRA" value="${param}" />
</NewComponent-extra>
<codeStyleSettings language="CoffeeScript">
<option name="KEEP_SIMPLE_METHODS_IN_ONE_LINE" value="true" />
</codeStyleSettings>
<codeStyleSettings language="DB2">
<option name="KEEP_LINE_BREAKS" value="false" />
</codeStyleSettings>
<codeStyleSettings language="Derby">
<option name="KEEP_LINE_BREAKS" value="false" />
</codeStyleSettings>
<codeStyleSettings language="Gherkin">
<indentOptions>
<option name="USE_TAB_CHARACTER" value="true" />
</indentOptions>
</codeStyleSettings>
<codeStyleSettings language="H2">
<option name="KEEP_LINE_BREAKS" value="false" />
</codeStyleSettings>
<codeStyleSettings language="HSQLDB">
<option name="KEEP_LINE_BREAKS" value="false" />
</codeStyleSettings>
<codeStyleSettings language="MySQL">
<option name="KEEP_LINE_BREAKS" value="false" />
</codeStyleSettings>
<codeStyleSettings language="Oracle">
<option name="KEEP_LINE_BREAKS" value="false" />
</codeStyleSettings>
<codeStyleSettings language="PostgreSQL">
<option name="KEEP_LINE_BREAKS" value="false" />
</codeStyleSettings>
<codeStyleSettings language="SQL">
<option name="KEEP_LINE_BREAKS" value="false" />
</codeStyleSettings>
<codeStyleSettings language="SQLite">
<option name="KEEP_LINE_BREAKS" value="false" />
</codeStyleSettings>
<codeStyleSettings language="Sybase">
<option name="KEEP_LINE_BREAKS" value="false" />
</codeStyleSettings>
<codeStyleSettings language="TSQL">
<option name="KEEP_LINE_BREAKS" value="false" />
</codeStyleSettings>
</code_scheme>""".trimIndent()
}
settings.readExternal(JDOMUtil.load(text("2")))
val serialized = Element("code_scheme").setAttribute("name", "testSchemeName")
settings.writeExternal(serialized)
assertThat(serialized).isEqualTo(text("3"))
}
@Test fun `reset deprecations`() {
val settings = CodeStyle.createTestSettings()
val initial = """
<code_scheme name="testSchemeName" version="${CodeStyleSettings.CURR_VERSION}">
<option name="RIGHT_MARGIN" value="64" />
<option name="USE_FQ_CLASS_NAMES_IN_JAVADOC" value="false" />
</code_scheme>""".trimIndent()
val expected = """
<code_scheme name="testSchemeName" version="${CodeStyleSettings.CURR_VERSION}">
<option name="RIGHT_MARGIN" value="64" />
</code_scheme>""".trimIndent()
settings.readExternal(JDOMUtil.load(initial))
settings.resetDeprecatedFields()
val serialized = Element("code_scheme").setAttribute("name", "testSchemeName")
settings.writeExternal(serialized)
assertThat(serialized).isEqualTo(expected)
}
} | apache-2.0 | de1fadc24806b056f8acad10ced0e257 | 39.169903 | 140 | 0.66014 | 4.913302 | false | true | false | false |
BenWoodworth/FastCraft | fastcraft-bukkit/bukkit-1.8/src/main/kotlin/net/benwoodworth/fastcraft/bukkit/gui/FcGuiButton_Bukkit_1_8.kt | 1 | 2367 | package net.benwoodworth.fastcraft.bukkit.gui
import net.benwoodworth.fastcraft.bukkit.util.updateMeta
import net.benwoodworth.fastcraft.platform.gui.FcGuiButton
import net.benwoodworth.fastcraft.platform.text.FcText
import net.benwoodworth.fastcraft.platform.text.FcTextConverter
import net.benwoodworth.fastcraft.platform.world.FcItem
import net.benwoodworth.fastcraft.platform.world.FcItemStack
import org.bukkit.inventory.Inventory
import org.bukkit.inventory.ItemFlag
import java.util.*
import javax.inject.Inject
import javax.inject.Singleton
open class FcGuiButton_Bukkit_1_8(
inventory: Inventory,
slotIndex: Int,
locale: Locale,
fcTextFactory: FcText.Factory,
fcTextConverter: FcTextConverter,
fcItemOperations: FcItem.Operations,
fcItemStackOperations: FcItemStack.Operations,
) : FcGuiButton_Bukkit_1_7(
inventory = inventory,
slotIndex = slotIndex,
locale = locale,
fcTextFactory = fcTextFactory,
fcTextConverter = fcTextConverter,
fcItemOperations = fcItemOperations,
fcItemStackOperations = fcItemStackOperations,
) {
override fun updateItemDetails() {
if (hideItemDetails) {
itemStack.updateMeta {
addItemFlags(
ItemFlag.HIDE_ENCHANTS,
ItemFlag.HIDE_ATTRIBUTES,
ItemFlag.HIDE_UNBREAKABLE,
ItemFlag.HIDE_DESTROYS,
ItemFlag.HIDE_PLACED_ON,
ItemFlag.HIDE_POTION_EFFECTS,
)
}
}
}
@Singleton
class Factory @Inject constructor(
private val fcTextFactory: FcText.Factory,
private val fcTextConverter: FcTextConverter,
private val fcItemOperations: FcItem.Operations,
private val fcItemStackOperations: FcItemStack.Operations,
) : FcGuiButton_Bukkit.Factory {
override fun create(inventory: Inventory, slotIndex: Int, locale: Locale): FcGuiButton {
return FcGuiButton_Bukkit_1_8(
inventory = inventory,
slotIndex = slotIndex,
locale = locale,
fcTextFactory = fcTextFactory,
fcTextConverter = fcTextConverter,
fcItemOperations = fcItemOperations,
fcItemStackOperations = fcItemStackOperations,
)
}
}
}
| gpl-3.0 | 6f3667287a332a06a2b26a398bb40ca5 | 34.863636 | 96 | 0.670046 | 5.225166 | false | false | false | false |
srodrigo/Kotlin-Wars | app/src/main/kotlin/me/srodrigo/kotlinwars/infrastructure/view/ViewStateHandler.kt | 1 | 419 | package me.srodrigo.kotlinwars.infrastructure.view
import android.view.View
import java.util.*
class ViewStateHandler<T : Enum<T>> {
private val states: MutableMap<T, View> = HashMap()
fun bind(state: T, view: View) {
states[state] = view
}
fun show(state: T) {
states.forEach {
if (it.key == state) {
it.value.visibility = View.VISIBLE
} else {
it.value.visibility = View.GONE
}
}
}
}
| mit | 813b07f2479a93580207304da2aa9d32 | 17.217391 | 52 | 0.658711 | 2.93007 | false | false | false | false |
marverenic/Paper | app/src/main/java/com/marverenic/reader/utils/ParcelableUtils.kt | 1 | 656 | package com.marverenic.reader.utils
import android.os.Parcel
import android.os.Parcelable
fun Parcel.writeBoolean(`val`: Boolean) = writeByte(if (`val`) 1 else 0)
fun Parcel.readBoolean() = readByte() != 0.toByte()
fun Parcel.writeOptionalLong(`val`: Long?) {
writeBoolean(`val` != null)
`val`?.let { writeLong(it) }
}
fun Parcel.readOptionalLong(): Long? = if (readBoolean()) readLong() else null
inline fun <reified T: Any> Parcel.readList()
= mutableListOf<T>().apply { readList(this, T::class.java.classLoader) }
inline fun <reified T: Parcelable> Parcel.readParcelable(): T?
= readParcelable(T::class.java.classLoader)
| apache-2.0 | 1356e5a46c647f1071ac0d357ce33338 | 28.818182 | 80 | 0.699695 | 3.685393 | false | false | false | false |
egf2-guide/guide-android | app/src/main/kotlin/com/eigengraph/egf2/guide/ui/fragment/LoginFragment.kt | 1 | 4514 | package com.eigengraph.egf2.guide.ui.fragment
import android.os.Bundle
import android.support.v4.app.Fragment
import android.support.v7.app.AlertDialog
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.EditText
import com.eigengraph.egf2.framework.EGF2
import com.eigengraph.egf2.framework.LoginModel
import com.eigengraph.egf2.framework.RegisterModel
import com.eigengraph.egf2.guide.ui.MainActivity
import com.eigengraph.egf2.guide.ui.anko.ForgotUI
import com.eigengraph.egf2.guide.ui.anko.LoginFragmentLayout
import com.eigengraph.egf2.guide.ui.anko.RegistrationUI
import com.eigengraph.egf2.guide.util.parseError
import com.eigengraph.egf2.guide.util.snackbar
import com.jakewharton.rxbinding.widget.RxTextView
import com.wdullaer.materialdatetimepicker.date.DatePickerDialog
import org.jetbrains.anko.defaultSharedPreferences
import org.jetbrains.anko.startActivity
import org.joda.time.DateTime
import rx.Observable
import java.util.*
class LoginFragment : Fragment() {
companion object {
fun newInstance() = LoginFragment()
}
private var layout = LoginFragmentLayout()
private var dobDate = DateTime.now()
override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? {
return layout.bind(this)
}
internal fun login(email: EditText?, pass: EditText?) {
EGF2.login(LoginModel(email?.text.toString(), pass?.text.toString()))
.subscribe({
val pref = activity.defaultSharedPreferences
pref.edit().putString("token", it).apply()
activity.startActivity<MainActivity>()
activity.finishAffinity()
}, {
view?.snackbar(parseError(it.message.toString()))
})
}
override fun onDestroyView() {
layout.unbind(this)
super.onDestroyView()
}
var fname: EditText? = null
var lname: EditText? = null
var email: EditText? = null
var dob: EditText? = null
var pass: EditText? = null
var pass2: EditText? = null
fun register() {
val dialog = AlertDialog.Builder(activity)
.setTitle("Register")
.setView(RegistrationUI().bind(this))
.setPositiveButton("OK", { dialogInterface, i -> })
.setNegativeButton("CANCEL", { dialogInterface, i -> })
.create()
dialog.show()
dob?.setOnFocusChangeListener { view, b ->
if (b) showBDateDialog()
}
dob?.setOnClickListener {
showBDateDialog()
}
val btn = dialog.getButton(AlertDialog.BUTTON_POSITIVE)
btn.setOnClickListener {
EGF2.register(
RegisterModel(fname?.text.toString(),
lname?.text.toString(),
email?.text.toString(),
dobDate.toString(),
pass?.text.toString()))
.subscribe({
dialog.dismiss()
val pref = activity.defaultSharedPreferences
pref.edit().putString("token", it).apply()
activity.startActivity<MainActivity>()
activity.finishAffinity()
}, {
view?.snackbar(parseError(it.message.toString()))
})
}
Observable.combineLatest(
RxTextView.textChanges(pass as EditText),
RxTextView.textChanges(pass2 as EditText),
{ pass, pass2 ->
dob?.text.toString().isNotEmpty() && pass.isNotEmpty() && pass.toString() == pass2.toString()
})
.subscribe {
btn.isEnabled = it
}
}
private fun showBDateDialog() {
val now = Calendar.getInstance()
val dpd = DatePickerDialog.newInstance(
{
view, year, monthOfYear, dayOfMonth ->
dob?.setText("${(monthOfYear + 1).toString()}/${dayOfMonth.toString()}/${year.toString()}")
dobDate = DateTime(year, monthOfYear + 1, dayOfMonth, 0, 0)
},
now.get(Calendar.YEAR),
now.get(Calendar.MONTH),
now.get(Calendar.DAY_OF_MONTH)
)
dpd.isThemeDark = false
dpd.vibrate(false)
dpd.dismissOnPause(true)
dpd.showYearPickerFirst(true)
dpd.setTitle("Birthday")
dpd.show(activity.fragmentManager, "Datepickerdialog")
}
fun forgot() {
val dialog = AlertDialog.Builder(activity)
.setTitle("Forgot Password")
.setView(ForgotUI().bind(this))
.setPositiveButton("OK", { dialogInterface, i -> })
.setNegativeButton("CANCEL", { dialogInterface, i -> })
.create()
dialog.show()
val btn = dialog.getButton(AlertDialog.BUTTON_POSITIVE)
btn.setOnClickListener {
EGF2.forgotPassword(email?.text.toString().trim())
.subscribe({
dialog.dismiss()
}, {
view?.snackbar(parseError(it.message.toString()))
})
}
RxTextView.textChanges(email as EditText).subscribe({
btn.isEnabled = it.isNotEmpty()
}, {})
}
} | mit | 4c7819f5d85ee12bd6aed73a2d20cd4a | 27.757962 | 114 | 0.708684 | 3.69697 | false | false | false | false |
sksamuel/ktest | kotest-framework/kotest-framework-engine/src/jvmTest/kotlin/com/sksamuel/kotest/engine/active/SeverityPropertyOverrideTest.kt | 1 | 2978 | package com.sksamuel.kotest.engine.active
import io.kotest.core.internal.KotestEngineProperties
import io.kotest.core.spec.Isolate
import io.kotest.core.spec.style.WordSpec
import io.kotest.core.test.TestCaseSeverityLevel
import io.kotest.matchers.booleans.shouldBeFalse
import io.kotest.matchers.booleans.shouldBeTrue
@Isolate
class SeverityPropertyOverrideTest : WordSpec({
"Default severity without override, prefix normal" should {
var run = false
System.setProperty(KotestEngineProperties.testSeverity, "NORMAL")
"allow this test to run" {
run = true
}
System.getProperties().remove(KotestEngineProperties.testSeverity)
run.shouldBeTrue()
}
"Default severity without override, prefix higher" should {
var run = false
System.setProperty(KotestEngineProperties.testSeverity, "CRITICAL")
"allow this test to run" {
run = true
}
System.getProperties().remove(KotestEngineProperties.testSeverity)
run.shouldBeFalse()
}
"Default severity without override, prefix lower" should {
var run = false
System.setProperty(KotestEngineProperties.testSeverity, "MINOR")
"allow this test to run" {
run = true
}
System.getProperties().remove(KotestEngineProperties.testSeverity)
run.shouldBeTrue()
}
"Critical severity, prefix NORMAL" should {
var run = false
System.setProperty(KotestEngineProperties.testSeverity, "NORMAL")
"allow this test to run".config(severity = TestCaseSeverityLevel.CRITICAL) {
run = true
}
System.getProperties().remove(KotestEngineProperties.testSeverity)
run.shouldBeTrue()
}
"Critical severity, prefix BLOCKER" should {
var run = false
System.setProperty(KotestEngineProperties.testSeverity, "BLOCKER")
"not allow this test to run".config(severity = TestCaseSeverityLevel.CRITICAL) {
run = true
}
System.getProperties().remove(KotestEngineProperties.testSeverity)
run.shouldBeFalse()
}
"MINOR severity, prefix TRIVIAL" should {
var run = false
System.setProperty(KotestEngineProperties.testSeverity, "TRIVIAL")
"allow this test to run".config(severity = TestCaseSeverityLevel.MINOR) {
run = true
}
System.getProperties().remove(KotestEngineProperties.testSeverity)
run.shouldBeTrue()
}
"MINOR severity, prefix NORMAL" should {
var run = false
System.setProperty(KotestEngineProperties.testSeverity, "NORMAL")
"allow this test to run".config(severity = TestCaseSeverityLevel.MINOR) {
run = true
}
System.getProperties().remove(KotestEngineProperties.testSeverity)
run.shouldBeFalse()
}
"MINOR severity, prefix default" should {
var run = false
"allow this test to run".config(severity = TestCaseSeverityLevel.MINOR) {
run = true
}
run.shouldBeTrue()
}
})
| mit | 7953b44678685b308658d8250cb135dc | 31.725275 | 86 | 0.693754 | 4.914191 | false | true | false | false |
h3xstream/find-sec-bugs | findsecbugs-samples-kotlin/src/test/kotlin/com/h3xstream/findsecbugs/jackson/UnsafeJacksonObjectDeserialization.kt | 2 | 1345 | package com.h3xstream.findsecbugs.jackson
import com.fasterxml.jackson.annotation.JsonTypeInfo
import com.fasterxml.jackson.databind.ObjectMapper
class UnsafeJacksonObjectDeserialization {
internal class ABean {
var id: Int = 0
var obj: Any? = null
}
internal class AnotherBean {
@JsonTypeInfo(use = JsonTypeInfo.Id.CLASS)
var obj: Any? = null
}
internal class YetAnotherBean {
@JsonTypeInfo(use = JsonTypeInfo.Id.MINIMAL_CLASS)
var obj: Any? = null
}
@Throws(Exception::class)
fun exampleOne(JSON: String) {
val mapper = ObjectMapper()
mapper.enableDefaultTyping()
val obj = mapper.readValue(JSON, ABean::class.java)
}
@Throws(Exception::class)
fun exampleTwo(JSON: String) {
val mapper = ObjectMapper()
mapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_CONCRETE_AND_ARRAYS)
val obj = mapper.readValue(JSON, ABean::class.java)
}
@Throws(Exception::class)
fun exampleThree(JSON: String) {
val mapper = ObjectMapper()
val obj = mapper.readValue(JSON, AnotherBean::class.java)
}
@Throws(Exception::class)
fun exampleFour(JSON: String) {
val mapper = ObjectMapper()
val obj = mapper.readValue(JSON, YetAnotherBean::class.java)
}
} | lgpl-3.0 | 2e9dc8e432e5a762ea7630b0fc88b619 | 26.469388 | 86 | 0.657993 | 4.039039 | false | false | false | false |
luhaoaimama1/JavaZone | JavaTest_Zone/src/算法/算法书籍/图/有向图/TopolDFS.kt | 1 | 586 | package 算法.算法书籍.图.有向图
import java.util.*
class TopolDFS(val g: Diagraph) {
private var marked = BooleanArray(g.v) { false }
private var topolStack = Stack<Int>()
init {
for (i in 0 until g.v) {
if (!marked[i]) {
dfs(i)
}
}
}
fun dfs(v: Int) {
marked[v] = true
for (nextV in g.adj(v)) {
if (!marked[nextV]) {
dfs(nextV)
}
}
topolStack.push(v)
}
fun marked(v: Int) = marked[v]
fun topol() = topolStack
} | epl-1.0 | 66983146a20f6f32f646c3959a3f3a38 | 18.551724 | 52 | 0.459364 | 3.215909 | false | false | false | false |
yuttadhammo/BodhiTimer | app/src/main/java/org/yuttadhammo/BodhiTimer/SettingsActivity.kt | 1 | 3754 | package org.yuttadhammo.BodhiTimer
import android.content.Intent
import android.content.SharedPreferences
import android.media.RingtoneManager
import android.net.Uri
import android.os.Bundle
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.widget.Toolbar
import androidx.preference.PreferenceManager
import org.yuttadhammo.BodhiTimer.Util.Settings
import org.yuttadhammo.BodhiTimer.Util.Themes
import timber.log.Timber
class SettingsActivity : AppCompatActivity() {
private var prefs: SharedPreferences? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
Themes.applyTheme(this)
setContentView(R.layout.settings_activity)
val toolbar = findViewById<Toolbar>(R.id.toolbar)
setSupportActionBar(toolbar)
val actionBar = supportActionBar
if (actionBar != null) {
actionBar.setDisplayHomeAsUpEnabled(true)
actionBar.title = getString(R.string.preferences)
toolbar.setNavigationOnClickListener { v: View? -> onBackPressed() }
}
supportFragmentManager
.beginTransaction()
.replace(R.id.settings, SettingsFragment())
.commit()
prefs = PreferenceManager.getDefaultSharedPreferences(baseContext)
}
public override fun onActivityResult(requestCode: Int, resultCode: Int, intent: Intent?) {
super.onActivityResult(requestCode, resultCode, intent)
if (resultCode == RESULT_OK) {
var uri = intent!!.data
val uriString = intent.dataString
when (requestCode) {
SELECT_RINGTONE -> {
uri = intent.getParcelableExtra(RingtoneManager.EXTRA_RINGTONE_PICKED_URI)
if (uri != null) {
Timber.i("Got ringtone $uri")
Settings.systemUri = uri.toString()
}
}
SELECT_PRE_RINGTONE -> {
uri = intent.getParcelableExtra(RingtoneManager.EXTRA_RINGTONE_PICKED_URI)
if (uri != null) {
Timber.i("Got ringtone $uri")
Settings.preSystemUri = uri.toString()
}
}
SELECT_FILE -> // Get the Uri of the selected file
if (uriString != null) {
getPersistablePermission(uri)
Timber.i("File Path: " + uri.toString())
Settings.fileUri = uri.toString()
}
SELECT_PRE_FILE -> // Get the Uri of the selected file
if (uriString != null) {
getPersistablePermission(uri)
Timber.i("File Path: " + uri.toString())
Settings.preFileUri = uri.toString()
}
SELECT_PHOTO -> if (uri != null) {
getPersistablePermission(uri)
Settings.bmpUri = uri.toString()
}
}
}
}
private fun getPersistablePermission(uri: Uri?) {
try {
contentResolver.takePersistableUriPermission(
uri!!,
Intent.FLAG_GRANT_READ_URI_PERMISSION
)
} catch (e: Exception) {
Timber.e(e.toString())
}
}
companion object {
private const val SELECT_RINGTONE = 0
private const val SELECT_FILE = 1
private const val SELECT_PRE_RINGTONE = 2
private const val SELECT_PRE_FILE = 3
private const val SELECT_PHOTO = 4
}
} | gpl-3.0 | f9d3eb0f340f3db4e175367c24726b14 | 36.929293 | 94 | 0.564997 | 5.424855 | false | false | false | false |
hhariri/mark-code | src/main/kotlin/com/hadihariri/markcode/Synthetics.kt | 1 | 348 | package com.hadihariri.markcode
import java.io.File
object Synthetics {
val imports = File("./imports.txt").readLines().map {
Pair(it.substringBefore("="), it.substringAfter("="))
}.toMap()
val prefixes = File("./prefixes.txt").readLines().map {
Pair(it.substringBefore("="), it.substringAfter("="))
}.toMap()
}
| mit | 33f31ac41009755498506782523094d0 | 23.857143 | 61 | 0.626437 | 4.094118 | false | false | false | false |
chrisdoc/kotlin-koans | src/i_introduction/_1_Java_To_Kotlin_Converter/JavaToKotlinConverter.kt | 10 | 760 | package i_introduction._1_Java_To_Kotlin_Converter
import util.TODO
fun todoTask1(collection: Collection<Int>): Nothing = TODO(
"""
Task 1.
Rewrite JavaCode1.task1 in Kotlin.
In IntelliJ IDEA, you can just copy-paste the code and agree to automatically convert it to Kotlin,
but only for this task!
""",
references = { JavaCode1().task1(collection) })
fun task1(collection: Collection<Int>): String {
val sb = StringBuilder()
sb.append("{")
val iterator = collection.iterator()
while (iterator.hasNext()) {
val element = iterator.next()
sb.append(element)
if (iterator.hasNext()) {
sb.append(", ")
}
}
sb.append("}")
return sb.toString()
}
| mit | dec5eaab55d0cd6df0abd2f1d6f66e2b | 26.142857 | 107 | 0.613158 | 4.130435 | false | false | false | false |
crunchersaspire/worshipsongs | app/src/main/java/org/worshipsongs/service/FavouriteService.kt | 1 | 8676 | package org.worshipsongs.service
import android.content.Context
import android.content.SharedPreferences
import android.preference.PreferenceManager
import android.util.Base64
import android.util.Log
import org.apache.commons.lang3.StringUtils
import org.worshipsongs.CommonConstants
import org.worshipsongs.WorshipSongApplication
import org.worshipsongs.domain.Favourite
import org.worshipsongs.domain.Song
import org.worshipsongs.domain.SongDragDrop
import org.worshipsongs.utils.PropertyUtils
import java.io.File
import java.util.ArrayList
import java.util.Collections
import java.util.HashSet
/**
* Author : Madasamy
* Version : 3.x.x
*/
class FavouriteService
{
private var sharedPreferences: SharedPreferences? = null
private var songService: SongService? = null
constructor()
{
sharedPreferences = PreferenceManager.getDefaultSharedPreferences(WorshipSongApplication.context)
songService = SongService(WorshipSongApplication.context!!)
}
constructor(context: Context?)
{
sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context
?: WorshipSongApplication.context)
}
fun migration(context: Context)
{
Log.i(FavouriteService::class.java.simpleName, "Preparing to migrate...")
val sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context)
val serviceFileName = PropertyUtils.getPropertyFile(context, CommonConstants.SERVICE_PROPERTY_TEMP_FILENAME)
val services = PropertyUtils.getServices(serviceFileName!!)
val favouriteList = ArrayList<Favourite>()
for (i in services.indices)
{
val songTitleString = PropertyUtils.getProperty(services[i], serviceFileName)
val songTitles = songTitleString.split(";".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()
val dragDrops = ArrayList<SongDragDrop>()
for (j in songTitles.indices)
{
val songDragDrop = SongDragDrop(j.toLong(), songTitles[j], false)
songDragDrop.tamilTitle = ""
dragDrops.add(songDragDrop)
Log.i(FavouriteService::class.java.simpleName, "No. of songs " + dragDrops.size)
}
favouriteList.add(Favourite(i, services[i], dragDrops))
}
Log.i(FavouriteService::class.java.simpleName, "No. of services " + favouriteList.size)
sharedPreferences.edit().putString(CommonConstants.FAVOURITES_KEY, Favourite.toJson(favouriteList)).apply()
}
fun save(serviceName: String, songDragDrop: SongDragDrop)
{
val favouriteString = sharedPreferences!!.getString(CommonConstants.FAVOURITES_KEY, "")
val favourites = Favourite.toArrays(favouriteString!!)
val existingFavourite = find(favourites, serviceName)
val favouriteSet = HashSet<Favourite>()
favouriteSet.addAll(favourites)
if (StringUtils.isNotBlank(existingFavourite.name))
{
val dragDrops = existingFavourite.dragDrops
dragDrops!!.add(songDragDrop)
existingFavourite.dragDrops = dragDrops
favouriteSet.add(existingFavourite)
} else
{
val dragDrops = ArrayList<SongDragDrop>()
dragDrops.add(songDragDrop)
favouriteSet.add(Favourite(getFavouritesNewOrderNumber(favourites), serviceName, dragDrops))
}
val uniqueFavourites = ArrayList(favouriteSet)
sharedPreferences!!.edit().putString(CommonConstants.FAVOURITES_KEY, Favourite.toJson(uniqueFavourites)).apply()
}
fun getFavouritesNewOrderNumber(favourites: List<Favourite>): Int
{
if (favourites.isEmpty())
{
return 0
} else
{
Collections.sort(favourites)
return favourites[0].orderId + 1
}
}
fun save(name: String, dragDrops: MutableList<SongDragDrop>)
{
val favouriteString = sharedPreferences!!.getString(CommonConstants.FAVOURITES_KEY, "")
val favourites = Favourite.toArrays(favouriteString!!)
var existingFavourite = find(favourites, name)
val favouriteSet = HashSet<Favourite>()
favouriteSet.addAll(favourites)
if (StringUtils.isNotBlank(existingFavourite.name))
{
existingFavourite.dragDrops = dragDrops
} else
{
existingFavourite = Favourite(getFavouritesNewOrderNumber(favourites), name, dragDrops)
}
favouriteSet.add(existingFavourite)
val uniqueFavourites = ArrayList(favouriteSet)
sharedPreferences!!.edit().putString(CommonConstants.FAVOURITES_KEY, Favourite.toJson(uniqueFavourites)).apply()
}
fun find(name: String): Favourite
{
val favourites = Favourite.toArrays(sharedPreferences!!.getString(CommonConstants.FAVOURITES_KEY, "")!!)
return find(favourites, name)
}
private fun find(favourites: List<Favourite>, favouriteName: String): Favourite
{
for (favourite in favourites)
{
if (favourite.name!!.equals(favouriteName, ignoreCase = true))
{
return favourite
}
}
return Favourite()
}
fun findNames(): MutableList<String>
{
val favourites = Favourite.toArrays(sharedPreferences!!.getString(CommonConstants.FAVOURITES_KEY, "")!!)
Collections.sort(favourites)
val names = mutableListOf<String>()
for (favourite in favourites)
{
names.add(favourite.name!!)
}
return names
}
fun buildShareFavouriteFormat(name: String): String
{
val favourite = find(name)
val linkBuilder = StringBuilder()
linkBuilder.append(name).append(";")
val builder = StringBuilder()
builder.append(name).append("\n\n")
val dragDrops = favourite.dragDrops
for (i in dragDrops!!.indices)
{
val songDragDrop = dragDrops[i]
builder.append(i + 1).append(". ").append(if (StringUtils.isNotBlank(songDragDrop.tamilTitle)) songDragDrop.tamilTitle!! + "\n"
else "").append(songDragDrop.title).append("\n\n")
if (songDragDrop.id > 0)
{
linkBuilder.append(songDragDrop.id).append(";")
} else
{
val song = songService!!.findByTitle(songDragDrop.title!!)
linkBuilder.append(song!!.id).append(";")
}
}
val base64String = Base64.encodeToString(linkBuilder.toString().toByteArray(), 0)
builder.append("\n").append("https://mcruncher.github.io/worshipsongs/?").append(base64String)
return builder.toString()
}
fun findSongsByFavouriteName(name: String): List<Song>
{
val songs = ArrayList<Song>()
val favourite = find(name)
for (songDragDrop in favourite.dragDrops!!)
{
val song = songService!!.findContentsByTitle(songDragDrop.title!!)
if (song != null)
{
songs.add(song)
}
}
return songs
}
fun remove(name: String)
{
val favouriteString = sharedPreferences!!.getString(CommonConstants.FAVOURITES_KEY, "")
val favourites = Favourite.toArrays(favouriteString!!)
val favourite = find(favourites, name)
favourites.remove(favourite)
sharedPreferences!!.edit().putString(CommonConstants.FAVOURITES_KEY, Favourite.toJson(favourites)).apply()
}
fun removeSong(name: String, songName: String)
{
val favouriteString = sharedPreferences!!.getString(CommonConstants.FAVOURITES_KEY, "")
val favourites = Favourite.toArrays(favouriteString!!)
val existingFavourite = find(favourites, name)
val dragDrops = ArrayList<SongDragDrop>()
for (dragDrop in existingFavourite.dragDrops!!)
{
if (!songName.equals(dragDrop.title!!, ignoreCase = true))
{
dragDrops.add(dragDrop)
}
}
existingFavourite.dragDrops = dragDrops
val favouriteSet = HashSet<Favourite>()
favouriteSet.add(existingFavourite)
favouriteSet.addAll(favourites)
sharedPreferences!!.edit().putString(CommonConstants.FAVOURITES_KEY, Favourite.toJson(ArrayList(favouriteSet))).apply()
}
fun setSharedPreferences(sharedPreferences: SharedPreferences)
{
this.sharedPreferences = sharedPreferences
}
fun setSongService(songService: SongService)
{
this.songService = songService
}
}
| apache-2.0 | 2741a9c481db5f37c36d7f00ea8855e2 | 36.076923 | 139 | 0.652835 | 5.213942 | false | false | false | false |
Tenkiv/Tekdaqc-JVM-Library | src/test/kotlin/com/tenkiv/tekdaqc/communication/message/MessageBroadcasterSpec.kt | 2 | 6087 | package com.tenkiv.tekdaqc.communication.message
import com.tenkiv.tekdaqc.TEST_ERROR_MESSAGE_DATA
import com.tenkiv.tekdaqc.communication.ascii.message.parsing.ASCIIErrorMessage
import com.tenkiv.tekdaqc.communication.data_points.AnalogInputCountData
import com.tenkiv.tekdaqc.communication.data_points.DigitalInputData
import com.tenkiv.tekdaqc.communication.data_points.PWMInputData
import com.tenkiv.tekdaqc.hardware.ATekdaqc
import com.tenkiv.tekdaqc.hardware.DigitalInput
import com.tenkiv.tekdaqc.hardware.Tekdaqc_RevD
import com.tenkiv.tekdaqc.locator.getSimulatedLocatorResponse
import io.kotlintest.matchers.shouldBe
import io.kotlintest.specs.ShouldSpec
import java.lang.Thread.sleep
/**
* Class to test sending commands through MessageBroadcaster
*/
class MessageBroadcasterSpec : ShouldSpec({
"Message Broadcaster Spec"{
val simulatedTekdaqc = Tekdaqc_RevD(getSimulatedLocatorResponse())
val messageBroadcaster = simulatedTekdaqc.messageBroadcaster
var analogCountTrigger = false
val analogCountListener = ICountListener { _, _ ->
analogCountTrigger = true
}
var analogVoltageTrigger = false
val analogVolatgeListener = IVoltageListener { _, _ ->
analogVoltageTrigger = true
}
var digitalTrigger = false
val digitalListener = IDigitalChannelListener { _, _ ->
digitalTrigger = true
}
var digitalPwmTrigger = false
val digitalPwmListener = object : IPWMChannelListener {
override fun onPWMDataReceived(input: DigitalInput, data: PWMInputData) {
digitalPwmTrigger = true
}
}
var networkTrigger = false
val networkListener = object : INetworkListener {
override fun onNetworkConditionDetected(tekdaqc: ATekdaqc, message: ABoardMessage) {
networkTrigger = true
}
}
var fullMessageAnalogTrigger = false
var fullMessageDigitalTrigger = false
val fullListener = object : IMessageListener {
override fun onErrorMessageReceived(tekdaqc: ATekdaqc?, message: ABoardMessage?) {
}
override fun onStatusMessageReceived(tekdaqc: ATekdaqc?, message: ABoardMessage?) {
}
override fun onDebugMessageReceived(tekdaqc: ATekdaqc?, message: ABoardMessage?) {
}
override fun onCommandDataMessageReceived(tekdaqc: ATekdaqc?, message: ABoardMessage?) {
}
override fun onAnalogInputDataReceived(tekdaqc: ATekdaqc?, data: AnalogInputCountData?) {
fullMessageAnalogTrigger = true
}
override fun onDigitalInputDataReceived(tekdaqc: ATekdaqc?, data: DigitalInputData?) {
fullMessageDigitalTrigger = true
}
override fun onDigitalOutputDataReceived(tekdaqc: ATekdaqc?, data: BooleanArray?) {
}
}
messageBroadcaster.addMessageListener(
simulatedTekdaqc,
fullListener
)
messageBroadcaster.addNetworkListener(
simulatedTekdaqc,
networkListener
)
messageBroadcaster.addAnalogChannelListener(
simulatedTekdaqc,
simulatedTekdaqc.getAnalogInput(0),
analogCountListener)
messageBroadcaster.addAnalogVoltageListener(
simulatedTekdaqc,
simulatedTekdaqc.getAnalogInput(0),
analogVolatgeListener)
messageBroadcaster.addDigitalChannelListener(
simulatedTekdaqc,
simulatedTekdaqc.getDigitalInput(0),
digitalListener)
messageBroadcaster.addPWMChannelListener(simulatedTekdaqc,
simulatedTekdaqc.getDigitalInput(0),
digitalPwmListener)
should("Receive updates") {
messageBroadcaster.broadcastAnalogInputDataPoint(
simulatedTekdaqc,
AnalogInputCountData(0, "", 1000L, 1000))
messageBroadcaster.broadcastDigitalInputDataPoint(
simulatedTekdaqc,
DigitalInputData(0, "", 1000L, false))
messageBroadcaster.broadcastPWMInputDataPoint(
simulatedTekdaqc,
PWMInputData(0, "", 1000L, 0.0, 100)
)
messageBroadcaster.broadcastNetworkError(simulatedTekdaqc,ASCIIErrorMessage(TEST_ERROR_MESSAGE_DATA))
messageBroadcaster.broadcastMessage(simulatedTekdaqc,ASCIIErrorMessage(TEST_ERROR_MESSAGE_DATA))
sleep(2000)
fullMessageAnalogTrigger shouldBe true
fullMessageDigitalTrigger shouldBe true
analogCountTrigger shouldBe true
analogVoltageTrigger shouldBe true
digitalTrigger shouldBe true
digitalPwmTrigger shouldBe true
networkTrigger shouldBe true
}
should("Remove listeners") {
messageBroadcaster.removeListener(
simulatedTekdaqc,
fullListener)
messageBroadcaster.removeNetworkListener(
simulatedTekdaqc,
networkListener)
messageBroadcaster.removeAnalogCountListener(
simulatedTekdaqc,
simulatedTekdaqc.getAnalogInput(0),
analogCountListener)
messageBroadcaster.removeAnalogVoltageListener(
simulatedTekdaqc,
simulatedTekdaqc.getAnalogInput(0),
analogVolatgeListener)
messageBroadcaster.removeDigitalChannelListener(
simulatedTekdaqc,
simulatedTekdaqc.getDigitalInput(0),
digitalListener)
messageBroadcaster.removePWMChannelListener(simulatedTekdaqc,
simulatedTekdaqc.getDigitalInput(0),
digitalPwmListener)
}
}
}) | apache-2.0 | 20878d940ad6b884f485ef0e9807a674 | 35.674699 | 113 | 0.638574 | 6.373822 | false | false | false | false |
Doist/TodoistModels | src/main/java/com/todoist/pojo/Item.kt | 1 | 1795 | package com.todoist.pojo
open class Item<D : Due> @JvmOverloads constructor(
id: Long,
open var content: String,
open var description: String? = null,
open var projectId: Long,
priority: Int,
due: D?,
open var sectionId: Long?,
open var parentId: Long?,
open var childOrder: Int = MIN_CHILD_ORDER,
open var dayOrder: Int = DEF_DAY_ORDER,
open var isChecked: Boolean = false,
open var isCollapsed: Boolean = false,
open var assignedByUid: Long?,
open var responsibleUid: Long?,
open var labels: Set<String> = emptySet(),
open var dateAdded: Long,
open var addedByUid: Long?,
open var dateCompleted: Long? = null,
isDeleted: Boolean = false
) : Model(id, isDeleted) {
/**
* Returns the priority within the bounds defined by [MIN_PRIORITY] and [MAX_PRIORITY].
*/
open var priority: Int = priority
get() = field.coerceIn(MIN_PRIORITY, MAX_PRIORITY)
set(value) {
if (field != value) {
field = value
dayOrder = DEF_DAY_ORDER
}
}
/**
* Sets the due date, with the side effect of resetting the day order to its default value of
* [DEF_DAY_ORDER].
*/
open var due: D? = due
set(value) {
if (field != value) {
field = value
dayOrder = DEF_DAY_ORDER
}
}
companion object {
const val MIN_CHILD_ORDER = 1
const val MIN_DEPTH = 0
const val MAX_DEPTH = 4
const val MIN_PRIORITY = 1
const val MAX_PRIORITY = 4
const val DEF_DAY_ORDER = -1
const val MAX_LABEL_COUNT = 100
const val MAX_CONTENT_CHAR_COUNT = 500
const val MAX_DESCRIPTION_CHAR_COUNT = 1000
}
}
| mit | 72816fadd8e118c0693d9452933c77e6 | 28.916667 | 97 | 0.579387 | 4.070295 | false | false | false | false |
rethumb/rethumb-examples | examples-resize-by-height/example-kotlin.kt | 1 | 692 | import java.io.FileOutputStream
import java.net.URL
import java.nio.channels.Channels
object KotlinRethumbHeightExample {
@Throws(Exception::class)
@JvmStatic fun main(args: Array<String>) {
val paramOperation = "height"
val paramValue = 100 // New height in pixels.
val imageURL = "http://images.rethumb.com/image_coimbra_600x300.jpg"
val imageFilename = "resized-image.jpg"
val url = URL(String.format("http://api.rethumb.com/v1/%s/%s/%s", paramOperation, paramValue, imageURL))
val fos = FileOutputStream(imageFilename)
fos.channel.transferFrom(Channels.newChannel(url.openStream()), 0, java.lang.Long.MAX_VALUE)
}
} | unlicense | a5cd97cdc746906e5bbcac7c1c311d5d | 33.65 | 112 | 0.693642 | 3.585492 | false | false | false | false |
MaibornWolff/codecharta | analysis/import/SVNLogParser/src/test/kotlin/de/maibornwolff/codecharta/importer/svnlogparser/ParserDialogTest.kt | 1 | 2026 | package de.maibornwolff.codecharta.importer.svnlogparser
import com.github.kinquirer.KInquirer
import com.github.kinquirer.components.promptConfirm
import com.github.kinquirer.components.promptInput
import io.mockk.every
import io.mockk.mockkStatic
import io.mockk.unmockkAll
import org.assertj.core.api.Assertions
import org.junit.jupiter.api.AfterAll
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.TestInstance
import picocli.CommandLine
import java.io.File
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
class ParserDialogTest {
@AfterAll
fun afterTest() {
unmockkAll()
}
@Test
fun `should output correct arguments that can be parsed`() {
val fileName = "svn.log"
val outputFileName = "codecharta.cc.json"
val isCompressed = false
val isSilent = false
val addAuthor = false
mockkStatic("com.github.kinquirer.components.InputKt")
every {
KInquirer.promptInput(any(), any(), any())
} returns fileName andThen outputFileName
mockkStatic("com.github.kinquirer.components.ConfirmKt")
every {
KInquirer.promptConfirm(any(), any())
} returns isCompressed andThen isSilent andThen addAuthor
val parserArguments = ParserDialog.collectParserArgs()
val cmdLine = CommandLine(SVNLogParser())
val parseResult = cmdLine.parseArgs(*parserArguments.toTypedArray())
Assertions.assertThat(parseResult.matchedOption("output-file").getValue<String>())
.isEqualTo(outputFileName)
Assertions.assertThat(parseResult.matchedOption("not-compressed").getValue<Boolean>()).isEqualTo(isCompressed)
Assertions.assertThat(parseResult.matchedOption("silent").getValue<Boolean>()).isEqualTo(isSilent)
Assertions.assertThat(parseResult.matchedOption("add-author").getValue<Boolean>()).isEqualTo(addAuthor)
Assertions.assertThat(parseResult.matchedPositional(0).getValue<File>().name).isEqualTo(fileName)
}
}
| bsd-3-clause | a09e452a61ba3258fc291be0496a5ca1 | 37.961538 | 118 | 0.727048 | 4.767059 | false | true | false | false |
ruben69695/domo-meteo | Android_Client/DomoMeteo/app/src/main/java/com/educem/ruben/domo_meteo/LoginActivity.kt | 1 | 7367 | package com.educem.ruben.domo_meteo
import android.app.ProgressDialog
import android.content.Context
import android.content.Intent
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.support.design.widget.Snackbar
import android.support.v4.widget.DrawerLayout
import android.util.Log
import android.view.inputmethod.InputMethodManager
import android.widget.Button
import android.widget.EditText
import android.widget.Toolbar
import com.android.volley.Request
import com.android.volley.RequestQueue
import com.android.volley.Response
import com.android.volley.toolbox.StringRequest
import com.android.volley.toolbox.Volley
import com.educem.ruben.domo_meteo.CLASES.Error
import com.educem.ruben.domo_meteo.CLASES.User
import com.educem.ruben.domo_meteo.CLASES.UserK
import org.json.JSONArray
import org.json.JSONObject
import java.util.HashMap
class LoginActivity : AppCompatActivity() {
private var inputUsername : EditText? = null
private var inputPassword : EditText? = null
private var btLogin : Button? = null
private var btToRegister : Button? = null
private var pDialog : ProgressDialog? = null
private var drawerLayout : DrawerLayout? = null
private var LOGIN_URL : String = "http://192.168.1.36/API/Android/login_android.php"
private var queue : RequestQueue? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_login)
// CASTING DE VIEWS A OBJETOS KOTLIN
inputUsername = findViewById(R.id.loginUsername) as EditText
inputPassword = findViewById(R.id.loginPassword) as EditText
btLogin = findViewById(R.id.btLogin) as Button
btToRegister = findViewById(R.id.btnLinkToRegisterScreen) as Button
drawerLayout = findViewById(R.id.drawer_layout_login) as DrawerLayout
// Creamos la cola para las peticiones de la libreria Volley de google 'this' is the Context
queue = Volley.newRequestQueue(this)
// Dialogo de progreso
pDialog = ProgressDialog(this)
pDialog?.setCancelable(false)
// Evento click del botón para ir a registrarse
btToRegister?.setOnClickListener {
startActivity(Intent(applicationContext, RegistrarseActivity::class.java))
}
btLogin?.setOnClickListener {
// Escondemos el teclado
hideKeyboard()
// Obtenemos los datos del formulario
var user = inputUsername?.text.toString().trim()
var pass = inputPassword?.text.toString().trim()
// Comprobamos qe haya datos introducidos en ambas variables
if(!user.isEmpty() && !pass.isEmpty())
{
try
{
checkLogin(user, pass)
}
catch (excp : Exception)
{
excp.printStackTrace()
}
}
else
{
// Lanzamos mensaje al usuario
lanzarSnack(R.id.drawer_layout_login, getString(R.string.errorFaltanDatos), Snackbar.LENGTH_LONG)
}
}
}
private fun checkLogin(user: String, pass: String)
{
// tag para cancelar la petición http por la libreria volley
val tag_string_req = "req_login"
// Mostramos el dialogo
pDialog?.setMessage(getString(R.string.iniciandoLogin))
pDialog?.show()
// Creamos la peticion con HTTP con la libreria Volley de Google
val myReq = object : StringRequest(Request.Method.POST,
LOGIN_URL,
requestSuccess(),
requestError()) {
@Throws(com.android.volley.AuthFailureError::class)
override fun getParams(): Map<String, String> {
val params = HashMap<String, String>()
params.put("username", user)
params.put("password", pass)
return params
}
}
// Añadimos la petición HTTP a la cola para que se ejecute
queue?.add(myReq)
}
private fun requestSuccess(): Response.Listener<String>? {
return Response.Listener { response ->
Log.d("Volley", response.toString())
try
{
// Obtenemos la respuesta que es un JSON Array
val jsonArray : JSONArray = JSONArray(response)
// De esa array obtenemos el unico Objeto que hay
val jsonObject : JSONObject = jsonArray.getJSONObject(0)
// Creamos un objeto Error
val error : Error = Error(jsonObject.getBoolean("error"), jsonObject.getInt("num"), jsonObject.getString("descr"))
// Comprobamos que no haya error
if(!error.error)
{
// Creamos un objeto User
val user : UserK = UserK()
// Rellenamos los datos de la clase User a partir de un objeto JSON
user.convertJson_toUser(jsonObject.getJSONObject("user"))
startActivity(Intent(applicationContext, MainActivity::class.java))
}
else
{
// Mostramos el error por pantalla al usuario
var mensajeError = obtenerError(error.numero)
lanzarSnack(R.id.drawer_layout_login, mensajeError, Snackbar.LENGTH_LONG)
}
}
catch (excp : Exception)
{
excp.printStackTrace()
}
// Quitamos el dialogo de progreso
pDialog?.hide()
}
}
private fun requestError(): Response.ErrorListener {
return Response.ErrorListener { error ->
// Mostramos el error y quitamos el dialogo
Log.d("Volley", error.toString())
pDialog?.hide()
lanzarSnack(R.id.drawer_layout_login, getString(R.string.noHayConexionServidor), Snackbar.LENGTH_LONG)
}
}
/**
* Metodo para esoncder el teclado cuando no lo necesites
*/
private fun hideKeyboard() {
// Check if no view has focus:
val view = this.currentFocus
if (view != null) {
val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
imm.hideSoftInputFromWindow(view.windowToken, 0)
}
}
/**
* Lanzar mensaje en forma de SnackBar
* @param layoutID : identificador del DrawerLayout
* *
* @param message : mensaje que mostrar
* *
* @param duration : duracion del SnackBar
*/
private fun lanzarSnack(layoutID: Int, message: String, duration: Int) {
Snackbar.make(findViewById(layoutID)!!, message, duration).show()
}
/**
* A partir de un numero de error obtenemos el mensaje
* @param numError
* *
* @return
*/
private fun obtenerError(numError: Int): String {
var mensaje = ""
when (numError) {
1 -> mensaje = getString(R.string.userNotEnabled)
2 -> mensaje = getString(R.string.incorrectPassword)
3 -> mensaje = getString(R.string.usernameNotExist)
}
return mensaje
}
}
| gpl-3.0 | c36ae1e0cc1817e0e80bf08df75a51cb | 32.316742 | 130 | 0.60804 | 4.486898 | false | false | false | false |
elmozgo/PortalMirror | portalmirror-twitterfeed-core/src/test/kotlin/org/portalmirror/twitterfeed/core/TestStatuses.kt | 1 | 19825 | package org.portalmirror.twitterfeed.core
import twitter4j.Status
import twitter4j.TwitterObjectFactory
val rootStatus1: Status = TwitterObjectFactory.createStatus(
"""
{
"created_at": "Thu Apr 06 10:00:00 +0000 2017",
"id": 850007368138018001,
"id_str": "850007368138018001",
"text": "rootStatus1",
"truncated": false,
"entities": {
"hashtags": [],
"symbols": [],
"user_mentions": [],
"urls": []
},
"source": "<a href=\"http://twitter.com\" rel=\"nofollow\">Twitter Web Client</a>",
"in_reply_to_status_id": null,
"in_reply_to_status_id_str": null,
"in_reply_to_user_id": null,
"in_reply_to_user_id_str": null,
"in_reply_to_screen_name": null,
"user": {
"id": 6253282,
"id_str": "6253282",
"name": "Twitter API",
"screen_name": "twitterapi",
"location": "San Francisco, CA",
"description": "The Real Twitter API. I tweet about API changes, service issues and happily answer questions about Twitter and our API. Don't get an answer? It's on my website.",
"url": "http://t.co/78pYTvWfJd",
"entities": {
"url": {
"urls": [
{
"url": "http://t.co/78pYTvWfJd",
"expanded_url": "https://dev.twitter.com",
"display_url": "dev.twitter.com",
"indices": [
0,
22
]
}
]
},
"description": {
"urls": []
}
},
"protected": false,
"followers_count": 6172353,
"friends_count": 46,
"listed_count": 13091,
"created_at": "Wed May 23 06:01:13 +0000 2007",
"favourites_count": 26,
"utc_offset": -25200,
"time_zone": "Pacific Time (US & Canada)",
"geo_enabled": true,
"verified": true,
"statuses_count": 3583,
"lang": "en",
"contributors_enabled": false,
"is_translator": false,
"is_translation_enabled": false,
"profile_background_color": "C0DEED",
"profile_background_image_url": "http://pbs.twimg.com/profile_background_images/656927849/miyt9dpjz77sc0w3d4vj.png",
"profile_background_image_url_https": "https://pbs.twimg.com/profile_background_images/656927849/miyt9dpjz77sc0w3d4vj.png",
"profile_background_tile": true,
"profile_image_url": "http://pbs.twimg.com/profile_images/2284174872/7df3h38zabcvjylnyfe3_normal.png",
"profile_image_url_https": "https://pbs.twimg.com/profile_images/2284174872/7df3h38zabcvjylnyfe3_normal.png",
"profile_banner_url": "https://pbs.twimg.com/profile_banners/6253282/1431474710",
"profile_link_color": "0084B4",
"profile_sidebar_border_color": "C0DEED",
"profile_sidebar_fill_color": "DDEEF6",
"profile_text_color": "333333",
"profile_use_background_image": true,
"has_extended_profile": false,
"default_profile": false,
"default_profile_image": false,
"following": true,
"follow_request_sent": false,
"notifications": false,
"translator_type": "regular"
},
"geo": null,
"coordinates": null,
"place": null,
"contributors": null,
"retweeted_status": null,
"is_quote_status": false,
"retweet_count": 0,
"favorite_count": 0,
"favorited": false,
"retweeted": false,
"possibly_sensitive": false,
"lang": "en"
}
""")
val rootStatus2: Status = TwitterObjectFactory.createStatus(
"""
{
"created_at": "Thu Apr 06 15:28:43 +0000 2017",
"id": 850007368138018002,
"id_str": "850007368138018002",
"text": "rootStatus2",
"truncated": false,
"entities": {
"hashtags": [],
"symbols": [],
"user_mentions": [],
"urls": []
},
"source": "<a href=\"http://twitter.com\" rel=\"nofollow\">Twitter Web Client</a>",
"in_reply_to_status_id": null,
"in_reply_to_status_id_str": null,
"in_reply_to_user_id": null,
"in_reply_to_user_id_str": null,
"in_reply_to_screen_name": null,
"user": {
"id": 6253282,
"id_str": "6253282",
"name": "Twitter API",
"screen_name": "twitterapi",
"location": "San Francisco, CA",
"description": "The Real Twitter API. I tweet about API changes, service issues and happily answer questions about Twitter and our API. Don't get an answer? It's on my website.",
"url": "http://t.co/78pYTvWfJd",
"entities": {
"url": {
"urls": [
{
"url": "http://t.co/78pYTvWfJd",
"expanded_url": "https://dev.twitter.com",
"display_url": "dev.twitter.com",
"indices": [
0,
22
]
}
]
},
"description": {
"urls": []
}
},
"protected": false,
"followers_count": 6172353,
"friends_count": 46,
"listed_count": 13091,
"created_at": "Wed May 23 06:01:13 +0000 2007",
"favourites_count": 26,
"utc_offset": -25200,
"time_zone": "Pacific Time (US & Canada)",
"geo_enabled": true,
"verified": true,
"statuses_count": 3583,
"lang": "en",
"contributors_enabled": false,
"is_translator": false,
"is_translation_enabled": false,
"profile_background_color": "C0DEED",
"profile_background_image_url": "http://pbs.twimg.com/profile_background_images/656927849/miyt9dpjz77sc0w3d4vj.png",
"profile_background_image_url_https": "https://pbs.twimg.com/profile_background_images/656927849/miyt9dpjz77sc0w3d4vj.png",
"profile_background_tile": true,
"profile_image_url": "http://pbs.twimg.com/profile_images/2284174872/7df3h38zabcvjylnyfe3_normal.png",
"profile_image_url_https": "https://pbs.twimg.com/profile_images/2284174872/7df3h38zabcvjylnyfe3_normal.png",
"profile_banner_url": "https://pbs.twimg.com/profile_banners/6253282/1431474710",
"profile_link_color": "0084B4",
"profile_sidebar_border_color": "C0DEED",
"profile_sidebar_fill_color": "DDEEF6",
"profile_text_color": "333333",
"profile_use_background_image": true,
"has_extended_profile": false,
"default_profile": false,
"default_profile_image": false,
"following": true,
"follow_request_sent": false,
"notifications": false,
"translator_type": "regular"
},
"geo": null,
"coordinates": null,
"place": null,
"contributors": null,
"retweeted_status": null,
"is_quote_status": false,
"retweet_count": 0,
"favorite_count": 0,
"favorited": false,
"retweeted": false,
"possibly_sensitive": false,
"lang": "en"
}
""")
val rootStatus3: Status = TwitterObjectFactory.createStatus(
"""
{
"created_at": "Thu Apr 06 15:28:43 +0000 2017",
"id": 850007368138018003,
"id_str": "850007368138018003",
"text": "rootStatus3",
"truncated": false,
"entities": {
"hashtags": [],
"symbols": [],
"user_mentions": [],
"urls": []
},
"source": "<a href=\"http://twitter.com\" rel=\"nofollow\">Twitter Web Client</a>",
"in_reply_to_status_id": null,
"in_reply_to_status_id_str": null,
"in_reply_to_user_id": null,
"in_reply_to_user_id_str": null,
"in_reply_to_screen_name": null,
"user": {
"id": 6253282,
"id_str": "6253282",
"name": "Twitter API",
"screen_name": "twitterapi",
"location": "San Francisco, CA",
"description": "The Real Twitter API. I tweet about API changes, service issues and happily answer questions about Twitter and our API. Don't get an answer? It's on my website.",
"url": "http://t.co/78pYTvWfJd",
"entities": {
"url": {
"urls": [
{
"url": "http://t.co/78pYTvWfJd",
"expanded_url": "https://dev.twitter.com",
"display_url": "dev.twitter.com",
"indices": [
0,
22
]
}
]
},
"description": {
"urls": []
}
},
"protected": false,
"followers_count": 6172353,
"friends_count": 46,
"listed_count": 13091,
"created_at": "Wed May 23 06:01:13 +0000 2007",
"favourites_count": 26,
"utc_offset": -25200,
"time_zone": "Pacific Time (US & Canada)",
"geo_enabled": true,
"verified": true,
"statuses_count": 3583,
"lang": "en",
"contributors_enabled": false,
"is_translator": false,
"is_translation_enabled": false,
"profile_background_color": "C0DEED",
"profile_background_image_url": "http://pbs.twimg.com/profile_background_images/656927849/miyt9dpjz77sc0w3d4vj.png",
"profile_background_image_url_https": "https://pbs.twimg.com/profile_background_images/656927849/miyt9dpjz77sc0w3d4vj.png",
"profile_background_tile": true,
"profile_image_url": "http://pbs.twimg.com/profile_images/2284174872/7df3h38zabcvjylnyfe3_normal.png",
"profile_image_url_https": "https://pbs.twimg.com/profile_images/2284174872/7df3h38zabcvjylnyfe3_normal.png",
"profile_banner_url": "https://pbs.twimg.com/profile_banners/6253282/1431474710",
"profile_link_color": "0084B4",
"profile_sidebar_border_color": "C0DEED",
"profile_sidebar_fill_color": "DDEEF6",
"profile_text_color": "333333",
"profile_use_background_image": true,
"has_extended_profile": false,
"default_profile": false,
"default_profile_image": false,
"following": true,
"follow_request_sent": false,
"notifications": false,
"translator_type": "regular"
},
"geo": null,
"coordinates": null,
"place": null,
"contributors": null,
"retweeted_status": null,
"is_quote_status": false,
"retweet_count": 0,
"favorite_count": 0,
"favorited": false,
"retweeted": false,
"possibly_sensitive": false,
"lang": "en"
}
""")
val replyTo_rootStatus1: Status = TwitterObjectFactory.createStatus(
"""
{
"created_at": "Thu Apr 06 10:01:00 +0000 2017",
"id": 850007368138018011,
"id_str": "850007368138018011",
"text": "reply to rootStatus1",
"truncated": false,
"entities": {
"hashtags": [],
"symbols": [],
"user_mentions": [
],
"urls": [
]
},
"source": "<a href=\"http://twitter.com\" rel=\"nofollow\">Twitter Web Client</a>",
"in_reply_to_status_id": 850007368138018001,
"in_reply_to_status_id_str": "850007368138018001",
"in_reply_to_user_id": 6253282,
"in_reply_to_user_id_str": "6253282",
"in_reply_to_screen_name": "twitterapi",
"user": {
"id": 6253001,
"id_str": "6253001",
"name": "replier 1",
"screen_name": "replier1",
"location": "San Francisco, CA",
"description": "replier1",
"url": "http://t.co/78pYTvWfJd",
"entities": {
"url": {
"urls": [
{
"url": "http://t.co/78pYTvWfJd",
"expanded_url": "https://dev.twitter.com",
"display_url": "dev.twitter.com",
"indices": [
0,
22
]
}
]
},
"description": {
"urls": []
}
},
"protected": false,
"followers_count": 6172353,
"friends_count": 46,
"listed_count": 13091,
"created_at": "Wed May 23 06:01:13 +0000 2007",
"favourites_count": 26,
"utc_offset": -25200,
"time_zone": "Pacific Time (US & Canada)",
"geo_enabled": true,
"verified": true,
"statuses_count": 3583,
"lang": "en",
"contributors_enabled": false,
"is_translator": false,
"is_translation_enabled": false,
"profile_background_color": "C0DEED",
"profile_background_image_url": "http://pbs.twimg.com/profile_background_images/656927849/miyt9dpjz77sc0w3d4vj.png",
"profile_background_image_url_https": "https://pbs.twimg.com/profile_background_images/656927849/miyt9dpjz77sc0w3d4vj.png",
"profile_background_tile": true,
"profile_image_url": "http://pbs.twimg.com/profile_images/2284174872/7df3h38zabcvjylnyfe3_normal.png",
"profile_image_url_https": "https://pbs.twimg.com/profile_images/2284174872/7df3h38zabcvjylnyfe3_normal.png",
"profile_banner_url": "https://pbs.twimg.com/profile_banners/6253282/1431474710",
"profile_link_color": "0084B4",
"profile_sidebar_border_color": "C0DEED",
"profile_sidebar_fill_color": "DDEEF6",
"profile_text_color": "333333",
"profile_use_background_image": true,
"has_extended_profile": false,
"default_profile": false,
"default_profile_image": false,
"following": true,
"follow_request_sent": false,
"notifications": false,
"translator_type": "regular"
},
"geo": null,
"coordinates": null,
"place": null,
"contributors": null,
"retweeted_status": null,
"is_quote_status": false,
"retweet_count": 284,
"favorite_count": 0,
"favorited": false,
"retweeted": false,
"possibly_sensitive": false,
"lang": "en"
}
""")
val replyTo_replyTo_rootStatus1: Status = TwitterObjectFactory.createStatus(
"""
{
"created_at": "Thu Apr 06 10:02:00 +0000 2017",
"id": 850007368138018021,
"id_str": "850007368138018021",
"text": "reply to reply to rootStatus1",
"truncated": false,
"entities": {
"hashtags": [],
"symbols": [],
"user_mentions": [
],
"urls": [
]
},
"source": "<a href=\"http://twitter.com\" rel=\"nofollow\">Twitter Web Client</a>",
"in_reply_to_status_id": 850007368138018011,
"in_reply_to_status_id_str": "850007368138018011",
"in_reply_to_user_id": 6253001,
"in_reply_to_user_id_str": "6253001",
"in_reply_to_screen_name": "replier1",
"user": {
"id": 6253282,
"id_str": "6253282",
"name": "Twitter",
"screen_name": "twitterapi",
"location": "San Francisco, CA",
"description": "replier1",
"url": "http://t.co/78pYTvWfJd",
"entities": {
"url": {
"urls": [
{
"url": "http://t.co/78pYTvWfJd",
"expanded_url": "https://dev.twitter.com",
"display_url": "dev.twitter.com",
"indices": [
0,
22
]
}
]
},
"description": {
"urls": []
}
},
"protected": false,
"followers_count": 6172353,
"friends_count": 46,
"listed_count": 13091,
"created_at": "Wed May 23 06:01:13 +0000 2007",
"favourites_count": 26,
"utc_offset": -25200,
"time_zone": "Pacific Time (US & Canada)",
"geo_enabled": true,
"verified": true,
"statuses_count": 3583,
"lang": "en",
"contributors_enabled": false,
"is_translator": false,
"is_translation_enabled": false,
"profile_background_color": "C0DEED",
"profile_background_image_url": "http://pbs.twimg.com/profile_background_images/656927849/miyt9dpjz77sc0w3d4vj.png",
"profile_background_image_url_https": "https://pbs.twimg.com/profile_background_images/656927849/miyt9dpjz77sc0w3d4vj.png",
"profile_background_tile": true,
"profile_image_url": "http://pbs.twimg.com/profile_images/2284174872/7df3h38zabcvjylnyfe3_normal.png",
"profile_image_url_https": "https://pbs.twimg.com/profile_images/2284174872/7df3h38zabcvjylnyfe3_normal.png",
"profile_banner_url": "https://pbs.twimg.com/profile_banners/6253282/1431474710",
"profile_link_color": "0084B4",
"profile_sidebar_border_color": "C0DEED",
"profile_sidebar_fill_color": "DDEEF6",
"profile_text_color": "333333",
"profile_use_background_image": true,
"has_extended_profile": false,
"default_profile": false,
"default_profile_image": false,
"following": true,
"follow_request_sent": false,
"notifications": false,
"translator_type": "regular"
},
"geo": null,
"coordinates": null,
"place": null,
"contributors": null,
"retweeted_status": null,
"is_quote_status": false,
"retweet_count": 284,
"favorite_count": 0,
"favorited": false,
"retweeted": false,
"possibly_sensitive": false,
"lang": "en"
}
""")
val replyTo_replyTo_replyTo_rootStatus1: Status = TwitterObjectFactory.createStatus(
"""
{
"created_at": "Thu Apr 06 10:03:00 +0000 2017",
"id": 850007368138018031,
"id_str": "850007368138018031",
"text": "reply to reply to reply to rootStatus1",
"truncated": false,
"entities": {
"hashtags": [],
"symbols": [],
"user_mentions": [
],
"urls": [
]
},
"source": "<a href=\"http://twitter.com\" rel=\"nofollow\">Twitter Web Client</a>",
"in_reply_to_status_id": 850007368138018021,
"in_reply_to_status_id_str": "850007368138018021",
"in_reply_to_user_id": 6253282,
"in_reply_to_user_id_str": "6253282",
"in_reply_to_screen_name": "twitterapi",
"user": {
"id": 6253001,
"id_str": "6253001",
"name": "replier 1",
"screen_name": "replier1",
"location": "San Francisco, CA",
"description": "replier1",
"url": "http://t.co/78pYTvWfJd",
"entities": {
"url": {
"urls": [
{
"url": "http://t.co/78pYTvWfJd",
"expanded_url": "https://dev.twitter.com",
"display_url": "dev.twitter.com",
"indices": [
0,
22
]
}
]
},
"description": {
"urls": []
}
},
"protected": false,
"followers_count": 6172353,
"friends_count": 46,
"listed_count": 13091,
"created_at": "Wed May 23 06:01:13 +0000 2007",
"favourites_count": 26,
"utc_offset": -25200,
"time_zone": "Pacific Time (US & Canada)",
"geo_enabled": true,
"verified": true,
"statuses_count": 3583,
"lang": "en",
"contributors_enabled": false,
"is_translator": false,
"is_translation_enabled": false,
"profile_background_color": "C0DEED",
"profile_background_image_url": "http://pbs.twimg.com/profile_background_images/656927849/miyt9dpjz77sc0w3d4vj.png",
"profile_background_image_url_https": "https://pbs.twimg.com/profile_background_images/656927849/miyt9dpjz77sc0w3d4vj.png",
"profile_background_tile": true,
"profile_image_url": "http://pbs.twimg.com/profile_images/2284174872/7df3h38zabcvjylnyfe3_normal.png",
"profile_image_url_https": "https://pbs.twimg.com/profile_images/2284174872/7df3h38zabcvjylnyfe3_normal.png",
"profile_banner_url": "https://pbs.twimg.com/profile_banners/6253282/1431474710",
"profile_link_color": "0084B4",
"profile_sidebar_border_color": "C0DEED",
"profile_sidebar_fill_color": "DDEEF6",
"profile_text_color": "333333",
"profile_use_background_image": true,
"has_extended_profile": false,
"default_profile": false,
"default_profile_image": false,
"following": true,
"follow_request_sent": false,
"notifications": false,
"translator_type": "regular"
},
"geo": null,
"coordinates": null,
"place": null,
"contributors": null,
"retweeted_status": null,
"is_quote_status": false,
"retweet_count": 284,
"favorite_count": 0,
"favorited": false,
"retweeted": false,
"possibly_sensitive": false,
"lang": "en"
}
""")
| gpl-3.0 | 64c62455c11862423065bf279c9a3f07 | 32.152174 | 184 | 0.570895 | 3.51819 | false | false | false | false |
VladRassokhin/intellij-hcl | src/kotlin/org/intellij/plugins/hcl/terraform/config/watchers/consumers/TerraformToolTaskConsumer.kt | 1 | 1658 | /*
* 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.intellij.plugins.hcl.terraform.config.watchers.consumers
import com.intellij.plugins.watcher.config.BackgroundTaskConsumer
import com.intellij.plugins.watcher.model.TaskOptions
import com.intellij.psi.PsiBundle
import com.intellij.psi.PsiFile
import org.intellij.plugins.hcl.terraform.config.TerraformFileType
abstract class TerraformToolTaskConsumer : BackgroundTaskConsumer() {
override fun isAvailable(file: PsiFile): Boolean {
return false
}
companion object {
fun createDefaultOptions(): TaskOptions {
val options = TaskOptions()
options.output = ""
options.isImmediateSync = false
options.exitCodeBehavior = TaskOptions.ExitCodeBehavior.ERROR
options.fileExtension = TerraformFileType.defaultExtension
// Unnecessary
// options.setEnvData(EnvironmentVariablesData.create(new HashMap<String,String>(), true));
options.scopeName = PsiBundle.message("psi.search.scope.project")
// 2017.3
// options.setRunOnExternalChanges(false);
return options
}
}
}
| apache-2.0 | 50492dfc4eef947badccd4f68ba35232 | 35.844444 | 97 | 0.750905 | 4.421333 | false | true | false | false |
STUDIO-apps/GeoShare_Android | mobile/src/main/java/uk/co/appsbystudio/geoshare/utils/TimeUtils.kt | 1 | 1961 | package uk.co.appsbystudio.geoshare.utils
import java.text.SimpleDateFormat
import java.util.Calendar
import java.util.Date
import java.util.Locale
private const val SECOND_MILLIS = 1000
private const val MINUTE_MILLIS = 60 * SECOND_MILLIS
private const val HOUR_MILLIS = 60 * MINUTE_MILLIS
fun Long.convertDate(): String {
var dateMilli = this
if (this < 1000000000000L) {
//Timestamp is in seconds
dateMilli *= 1000
}
val currentTime = System.currentTimeMillis()
if (dateMilli > currentTime || dateMilli <= 0) {
return ""
}
val date = Date(dateMilli)
val currentDate = Date(currentTime)
val lessThanSevenDays = SimpleDateFormat("EEEE", Locale.getDefault())
val moreThanSevenDays = SimpleDateFormat("MMM dd", Locale.getDefault())
return getString(dateMilli, currentTime, date, currentDate, lessThanSevenDays, moreThanSevenDays)
}
private fun getString(dateMilli: Long?, currentTime: Long, date: Date, currentDate: Date, lessThanSevenDays: SimpleDateFormat, moreThanSevenDays: SimpleDateFormat): String {
val diff = currentTime - dateMilli!!
when {
diff < MINUTE_MILLIS -> return "Just now"
diff < 2 * MINUTE_MILLIS -> return "a minute ago"
diff < 50 * MINUTE_MILLIS -> return (diff / MINUTE_MILLIS).toString() + " mins ago"
diff < 90 * MINUTE_MILLIS -> return "an hour ago"
diff < 24 * HOUR_MILLIS -> return (diff / HOUR_MILLIS).toString() + " hours ago"
diff < 48 * HOUR_MILLIS -> return "Yesterday"
else -> {
val calendar = Calendar.getInstance()
calendar.time = date
calendar.add(Calendar.DATE, 7)
val formattedDate: String
formattedDate = if (calendar.time < currentDate) {
moreThanSevenDays.format(date)
} else {
lessThanSevenDays.format(date)
}
return formattedDate
}
}
}
| apache-2.0 | 885d9372126081476cbbdb34ce81facb | 33.403509 | 173 | 0.646609 | 4.528868 | false | false | false | false |
sakebook/NexusTimer | app/src/main/java/com/sakebook/android/nexustimer/ui/ScheduleCreateStepActivity.kt | 1 | 8155 | package com.sakebook.android.nexustimer.ui
import android.app.Activity
import android.app.TimePickerDialog
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.support.v17.leanback.app.GuidedStepFragment
import android.support.v17.leanback.widget.*
import android.text.InputType
import android.util.Log
import android.widget.Toast
import com.sakebook.android.nexustimer.R
import com.sakebook.android.nexustimer.model.Week
class ScheduleCreateStepActivity : Activity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
if (null == savedInstanceState) {
GuidedStepFragment.addAsRoot(this, WeekFragment(), android.R.id.content)
}
}
companion object {
private val CONTINUE = 0
private val BACK = 1
private val TIME_PICKER = 10
@JvmStatic
fun addAction(context: Context, actions: MutableList<GuidedAction>, id: Long, title: String, desc: String) {
actions.add(GuidedAction.Builder(context).id(id).title(title).description(desc).build())
}
}
class WeekFragment : GuidedStepFragment() {
val weeks = Week.values()
override fun onCreateGuidance(savedInstanceState: Bundle?): GuidanceStylist.Guidance {
val title = getString(R.string.schedule_title)
val description = getString(R.string.schedule_description)
val icon = activity.getDrawable(R.mipmap.ic_launcher)
return GuidanceStylist.Guidance(title, description, "Step: 1/2", icon)
}
override fun onCreateActions(actions: MutableList<GuidedAction>, savedInstanceState: Bundle?) {
Log.d("TAG", "WeekFragment#onCreateActions")
weeks.forEachIndexed { i, week ->
val weekAction = GuidedAction.Builder(activity)
.id(week.id)
.title(week.name)
.description(week.label())
.build()
val onAction = GuidedAction.Builder(activity).title("ON").description("有効にします").checkSetId(GuidedAction.DEFAULT_CHECK_SET_ID).id(i.toLong()).build()
val offAction = GuidedAction.Builder(activity).title("OFF").description("無効にします").checkSetId(GuidedAction.DEFAULT_CHECK_SET_ID).id(i.toLong()).build()
weekAction.subActions = listOf(onAction, offAction)
actions.add(weekAction)
}
}
override fun onCreateButtonActions(actions: MutableList<GuidedAction>, savedInstanceState: Bundle?) {
Log.d("TAG", "WeekFragment#onCreateButtonActions")
val nextAction = GuidedAction.Builder(activity).title("next").description("nextだよ").id(0).build()
val cancelAction = GuidedAction.Builder(activity).title("cancel").description("cancelだよ").id(1).build()
actions.add(nextAction)
actions.add(cancelAction)
}
override fun onGuidedActionClicked(action: GuidedAction) {
Log.d("TAG", "WeekFragment#onGuidedActionClicked: ${action.id}, ${action.title}")
when(action.id.toInt()) {
CONTINUE -> {
when(weeks.any { it.enable }) {
true -> GuidedStepFragment.add(fragmentManager, TimeFragment().newInstance(weeks))
false -> Toast.makeText(activity, "最低どれかはONにしないと。。", Toast.LENGTH_SHORT).show()
}
}
BACK -> activity.finishAfterTransition()
else -> expandSubActions(action)
}
}
override fun onSubGuidedActionClicked(action: GuidedAction): Boolean {
Log.d("TAG", "WeekFragment#onSubGuidedActionClicked: ${action.title}, ${action.description}, ${action.id}, ${action.checkSetId}")
val index = action.id.toInt()
if (action.title == "ON") {
weeks[index].enable = true
} else {
weeks[index].enable = false
}
this.actions[index].description = action.title
this.notifyActionChanged(index)
return super.onSubGuidedActionClicked(action)
}
}
class TimeFragment : GuidedStepFragment() {
private val ARG_WEEKS = "arg_weeks"
private val ARG_HOUR = "arg_hour"
private val ARG_MINUTE = "arg_minute"
private var hour = 0
private var minute = 0
fun newInstance(weeks: Array<Week>): TimeFragment {
return TimeFragment().apply {
val args = Bundle()
args.putSerializable(ARG_WEEKS, weeks)
arguments = args
}
}
override fun onCreateGuidance(savedInstanceState: Bundle?): GuidanceStylist.Guidance {
val title = getString(R.string.schedule_title)
val weeks = arguments.getSerializable(ARG_WEEKS) as Array<Week>
val description = weeks.filter { it.enable }
.map { it.name }
.reduce { s1, s2 -> "$s1, $s2" }
val icon = activity.getDrawable(R.mipmap.ic_launcher)
return GuidanceStylist.Guidance(title, description, "Step: 2/2", icon)
}
override fun onCreateActions(actions: MutableList<GuidedAction>, savedInstanceState: Bundle?) {
Log.d("TAG", "TimeFragment#onCreateActions")
val action = GuidedAction.Builder(activity)
.title("時間")
.description("00:00")
.id(10)
.editInputType(InputType.TYPE_CLASS_NUMBER and InputType.TYPE_MASK_CLASS)
.build()
actions.add(action)
}
override fun onCreateButtonActions(actions: MutableList<GuidedAction>, savedInstanceState: Bundle?) {
Log.d("TAG", "TimeFragment#onCreateButtonActions")
val nextAction = GuidedAction.Builder(activity).title("create").description("createだよ").id(0).build()
val cancelAction = GuidedAction.Builder(activity).title("back").description("backだよ").id(1).build()
actions.add(nextAction)
actions.add(cancelAction)
}
override fun onGuidedActionClicked(action: GuidedAction) {
val actionPosition = this.actions.indexOf(action)
Log.d("TAG", "TimeFragment#onGuidedActionClicked: ${action.id}, ${action.title}, index: ${actionPosition}")
when(action.id.toInt()) {
CONTINUE -> {
val data = Intent();
val bundle = Bundle();
bundle.putSerializable(ARG_WEEKS, arguments.getSerializable(ARG_WEEKS))
bundle.putInt(ARG_HOUR, hour)
bundle.putInt(ARG_MINUTE, minute)
data.putExtras(bundle);
activity.setResult(Activity.RESULT_OK, data)
activity.finishAfterTransition()
}
TIME_PICKER -> {
showTimeDialog(TimePickerDialog.OnTimeSetListener { timePicker, hour, minute ->
val h = if (hour < 10) "0$hour" else hour.toString()
val m = if (minute < 10) "0$minute" else minute.toString()
this.actions[0].description = "$h:$m"
this.hour = hour
this.minute = minute
this.notifyActionChanged(0)
})
}
else -> fragmentManager.popBackStack()
}
}
private fun showTimeDialog(listener: TimePickerDialog.OnTimeSetListener) {
val timeDialog = TimePickerDialog(activity,
android.R.style.Theme_Material_Dialog_Alert,
listener,
0,
0,
true);
timeDialog.setCancelable(false)
timeDialog.show()
}
}
}
| apache-2.0 | 5ba2fe4c8de9e6057da2351f6f212b4c | 42.940217 | 166 | 0.581571 | 4.88815 | false | false | false | false |
collinx/susi_android | app/src/main/java/org/fossasia/susi/ai/helper/LocationHelper.kt | 3 | 4555 | package org.fossasia.susi.ai.helper
import android.Manifest
import android.app.Service
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.location.Location
import android.location.LocationListener
import android.location.LocationManager
import android.os.Bundle
import android.os.IBinder
import android.support.v4.app.ActivityCompat
import java.lang.ref.WeakReference
/**
* <h1>Helper class to get location of using network and GPS.</h1>
* Created by chiragw15 on 10/12/16.
*/
class LocationHelper
/**
* Instantiates a new Location helper.
* @param context the context
*/
(context: Context) : Service(), LocationListener {
private var canGetLocation = false
private val weakContext: WeakReference<Context>
/**
* Gets latitude.
* @return the latitude
*/
var latitude: Double = 0.toDouble()
private set
/**
* Gets longitude.
* @return the longitude
*/
var longitude: Double = 0.toDouble()
private set
/**
* Gets source.
* @return the source
*/
var source: String = "network"
private set
protected var locationManager: LocationManager? = null
init {
weakContext = WeakReference(context)
}
/**
* Gets location.
*/
fun getLocation() {
val mContext = weakContext.get()
var location: Location?
if (mContext == null) {
return
}
try {
locationManager = mContext
.getSystemService(Context.LOCATION_SERVICE) as LocationManager
if (ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
if (locationManager != null) {
locationManager!!.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, (5 * 60 * 1000).toLong(), 10f, this)
location = locationManager!!.getLastKnownLocation(LocationManager.NETWORK_PROVIDER)
if (location != null) {
source = "network"
canGetLocation = true
latitude = location.latitude
longitude = location.longitude
}
}
}
if (ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
if (locationManager != null) {
locationManager!!.requestLocationUpdates(LocationManager.GPS_PROVIDER, (5 * 60 * 1000).toLong(), 10f, this)
location = locationManager!!.getLastKnownLocation(LocationManager.GPS_PROVIDER)
if (location != null) {
source = "gps"
canGetLocation = true
latitude = location.latitude
longitude = location.longitude
}
}
}
} catch (e: Exception) {
e.printStackTrace()
}
}
/**
* Can get location boolean.
* @return the boolean
*/
fun canGetLocation(): Boolean {
return canGetLocation
}
/**
* Remove listener.
*/
fun removeListener() {
val mContext = weakContext.get()
if (mContext != null && locationManager != null) {
if (ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED || ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
locationManager!!.removeUpdates(this)
}
}
}
override fun onLocationChanged(location: Location?) {
if (location != null) {
latitude = location.latitude
longitude = location.longitude
source = location.provider
canGetLocation = true
}
}
override fun onProviderDisabled(provider: String) {
// This method is intentionally empty
}
override fun onProviderEnabled(provider: String) {
// This method is intentionally empty
}
override fun onStatusChanged(provider: String, status: Int, extras: Bundle) {
// This method is intentionally empty
}
override fun onBind(arg0: Intent): IBinder? {
// This method is intentionally empty
return null
}
}
| apache-2.0 | fc3846481e56a292349c46be0628c7bd | 29.165563 | 271 | 0.602415 | 5.346244 | false | false | false | false |
robinverduijn/gradle | buildSrc/subprojects/packaging/src/main/kotlin/org/gradle/gradlebuild/packaging/ShadeClasses.kt | 1 | 3895 | /*
* Copyright 2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gradle.gradlebuild.packaging
import com.google.gson.Gson
import org.gradle.api.artifacts.transform.CacheableTransform
import org.gradle.api.artifacts.transform.InputArtifact
import org.gradle.api.artifacts.transform.TransformAction
import org.gradle.api.artifacts.transform.TransformOutputs
import org.gradle.api.artifacts.transform.TransformParameters
import org.gradle.api.file.FileSystemLocation
import org.gradle.api.provider.Provider
import org.gradle.api.tasks.Classpath
import org.gradle.api.tasks.Input
private
const val classTreeFileName = "classTree.json"
private
const val entryPointsFileName = "entryPoints.json"
private
const val relocatedClassesDirName = "classes"
private
const val manifestFileName = "MANIFEST.MF"
@CacheableTransform
abstract class ShadeClasses : TransformAction<ShadeClasses.Parameters> {
interface Parameters : TransformParameters {
@get:Input
var shadowPackage: String
@get:Input
var keepPackages: Set<String>
@get:Input
var unshadedPackages: Set<String>
@get:Input
var ignoredPackages: Set<String>
}
@get:Classpath
@get:InputArtifact
abstract val input: Provider<FileSystemLocation>
override fun transform(outputs: TransformOutputs) {
val outputDirectory = outputs.dir("shadedClasses")
val classesDir = outputDirectory.resolve(relocatedClassesDirName)
classesDir.mkdir()
val manifestFile = outputDirectory.resolve(manifestFileName)
val classGraph = JarAnalyzer(parameters.shadowPackage, parameters.keepPackages, parameters.unshadedPackages, parameters.ignoredPackages).analyze(input.get().asFile, classesDir, manifestFile)
outputDirectory.resolve(classTreeFileName).bufferedWriter().use {
Gson().toJson(classGraph.getDependencies(), it)
}
outputDirectory.resolve(entryPointsFileName).bufferedWriter().use {
Gson().toJson(classGraph.entryPoints.map { it.outputClassFilename }, it)
}
}
}
abstract class FindClassTrees : TransformAction<TransformParameters.None> {
@get:InputArtifact
abstract val input: Provider<FileSystemLocation>
override fun transform(outputs: TransformOutputs) {
outputs.file(input.get().asFile.resolve(classTreeFileName))
}
}
abstract class FindEntryPoints : TransformAction<TransformParameters.None> {
@get:InputArtifact
abstract val input: Provider<FileSystemLocation>
override fun transform(outputs: TransformOutputs) {
outputs.file(input.get().asFile.resolve(entryPointsFileName))
}
}
abstract class FindRelocatedClasses : TransformAction<TransformParameters.None> {
@get:InputArtifact
abstract val input: Provider<FileSystemLocation>
override fun transform(outputs: TransformOutputs) {
outputs.dir(input.get().asFile.resolve(relocatedClassesDirName))
}
}
abstract class FindManifests : TransformAction<TransformParameters.None> {
@get:InputArtifact
abstract val input: Provider<FileSystemLocation>
override fun transform(outputs: TransformOutputs) {
val manifest = input.get().asFile.resolve(manifestFileName)
if (manifest.exists()) {
outputs.file(manifest)
}
}
}
| apache-2.0 | 275af695d9020f670701bfec98999ce3 | 30.666667 | 198 | 0.744031 | 4.68149 | false | false | false | false |
7hens/KDroid | core/src/main/java/cn/thens/kdroid/core/vadapter/VAdapter.kt | 1 | 2092 | package cn.thens.kdroid.core.vadapter
import androidx.annotation.LayoutRes
import androidx.fragment.app.FragmentManager
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
interface VAdapter<D> : MutableList<D> {
fun getItemCount(): Int = size
fun getItemId(position: Int): Long = position.toLong()
fun getItemViewType(position: Int): Int = 0
fun createHolder(viewGroup: ViewGroup, viewType: Int): Holder<D>
fun bindHolder(holder: Holder<D>, position: Int) {
holder.inject(this[position], position)
}
fun notifyChanged()
fun refill(elements: Iterable<D>) {
if (this != elements) {
clear()
addAll(elements)
}
notifyChanged()
}
interface Holder<in D> {
val view: View
fun inject(data: D, position: Int)
}
companion object {
fun <D> recycler(@LayoutRes layoutRes: Int, bind: View.(data: D, position: Int) -> Unit): Lazy<VRecyclerAdapter<D>> {
return lazy { VRecyclerAdapter.create(layoutRes, bind) }
}
fun <D> pager(@LayoutRes layoutRes: Int, bind: View.(data: D, position: Int) -> Unit): Lazy<VPagerAdapter<D>> {
return lazy { VPagerAdapter.create(layoutRes, false, bind) }
}
fun pager(fm: FragmentManager, boundless: Boolean = false): Lazy<VFragmentPagerAdapter> {
return lazy { VFragmentPagerAdapter(fm, boundless) }
}
fun <D> list(@LayoutRes layoutRes: Int, bind: View.(data: D, position: Int) -> Unit): Lazy<VListAdapter<D>> {
return lazy { VListAdapter.create(layoutRes, bind) }
}
}
}
fun ViewGroup.inflate(@LayoutRes layoutRes: Int): View {
return LayoutInflater.from(context).inflate(layoutRes, this, false)
}
fun <V : View, D> V.toHolder(bind: V.(data: D, position: Int) -> Unit): VAdapter.Holder<D> {
return object : VAdapter.Holder<D> {
override val view = this@toHolder
override fun inject(data: D, position: Int) {
bind(data, position)
}
}
}
| apache-2.0 | d745b3588206d3c64d5a192a09f7fa01 | 28.885714 | 125 | 0.633365 | 3.992366 | false | false | false | false |
spinnaker/echo | echo-telemetry/src/main/java/com/netflix/spinnaker/echo/telemetry/SpinnakerInstanceDataProvider.kt | 1 | 3122 | /*
* Copyright 2020 Google, LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.spinnaker.echo.telemetry
import com.netflix.spinnaker.echo.api.events.Event as EchoEvent
import com.netflix.spinnaker.echo.config.TelemetryConfig.TelemetryConfigProps
import com.netflix.spinnaker.kork.proto.stats.Application
import com.netflix.spinnaker.kork.proto.stats.DeploymentMethod
import com.netflix.spinnaker.kork.proto.stats.Event as StatsEvent
import com.netflix.spinnaker.kork.proto.stats.SpinnakerInstance
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty
import org.springframework.stereotype.Component
@Component
@ConditionalOnProperty(value = ["stats.enabled"], matchIfMissing = true)
class SpinnakerInstanceDataProvider(private val config: TelemetryConfigProps, private val instanceIdSupplier: InstanceIdSupplier) : TelemetryEventDataProvider {
override fun populateData(echoEvent: EchoEvent, statsEvent: StatsEvent): StatsEvent {
// TelemetryEventListener should ensure this is set
val applicationId: String = echoEvent.details?.application
?: throw IllegalStateException("application not set")
val instanceId: String = instanceIdSupplier.uniqueId
val hashedInstanceId: String = hash(instanceId)
// We want to ensure it's really hard to guess the application name. Using the instance ID (a
// ULID) provides a good level of randomness as a salt, and is not easily guessable.
val hashedApplicationId: String = hash(applicationId, instanceId)
val application = Application.newBuilder().setId(hashedApplicationId).build()
val spinnakerInstance: SpinnakerInstance = SpinnakerInstance.newBuilder()
.setId(hashedInstanceId)
.setVersion(config.spinnakerVersion)
.setDeploymentMethod(config.deploymentMethod.toProto())
.build()
val updatedEvent = statsEvent.toBuilder()
updatedEvent.spinnakerInstanceBuilder.mergeFrom(spinnakerInstance)
updatedEvent.applicationBuilder.mergeFrom(application)
return updatedEvent.build()
}
private fun TelemetryConfigProps.DeploymentMethod.toProto(): DeploymentMethod {
val deploymentType = type
if (deploymentType == null || version == null) {
return DeploymentMethod.getDefaultInstance()
}
return DeploymentMethod.newBuilder()
.setType(getProtoDeploymentType(deploymentType))
.setVersion(version)
.build()
}
private fun getProtoDeploymentType(type: String): DeploymentMethod.Type =
DeploymentMethod.Type.valueOf(
DeploymentMethod.Type.getDescriptor().findMatchingValue(type)
)
}
| apache-2.0 | 5f751aa55ce13c31e89c99dbed7b41d1 | 41.767123 | 160 | 0.776105 | 4.694737 | false | true | false | false |
inorichi/tachiyomi | app/src/main/java/eu/kanade/tachiyomi/data/track/shikimori/Shikimori.kt | 1 | 4737 | package eu.kanade.tachiyomi.data.track.shikimori
import android.content.Context
import android.graphics.Color
import androidx.annotation.StringRes
import eu.kanade.tachiyomi.R
import eu.kanade.tachiyomi.data.database.models.Track
import eu.kanade.tachiyomi.data.track.TrackService
import eu.kanade.tachiyomi.data.track.model.TrackSearch
import kotlinx.serialization.decodeFromString
import kotlinx.serialization.encodeToString
import kotlinx.serialization.json.Json
import uy.kohesive.injekt.injectLazy
class Shikimori(private val context: Context, id: Int) : TrackService(id) {
companion object {
const val READING = 1
const val COMPLETED = 2
const val ON_HOLD = 3
const val DROPPED = 4
const val PLANNING = 5
const val REPEATING = 6
}
private val json: Json by injectLazy()
private val interceptor by lazy { ShikimoriInterceptor(this) }
private val api by lazy { ShikimoriApi(client, interceptor) }
@StringRes
override fun nameRes() = R.string.tracker_shikimori
override fun getScoreList(): List<String> {
return IntRange(0, 10).map(Int::toString)
}
override fun displayScore(track: Track): String {
return track.score.toInt().toString()
}
private suspend fun add(track: Track): Track {
return api.addLibManga(track, getUsername())
}
override suspend fun update(track: Track, didReadChapter: Boolean): Track {
if (track.status != COMPLETED) {
if (didReadChapter) {
if (track.last_chapter_read.toInt() == track.total_chapters && track.total_chapters > 0) {
track.status = COMPLETED
} else if (track.status != REPEATING) {
track.status = READING
}
}
}
return api.updateLibManga(track, getUsername())
}
override suspend fun bind(track: Track, hasReadChapters: Boolean): Track {
val remoteTrack = api.findLibManga(track, getUsername())
return if (remoteTrack != null) {
track.copyPersonalFrom(remoteTrack)
track.library_id = remoteTrack.library_id
if (track.status != COMPLETED) {
val isRereading = track.status == REPEATING
track.status = if (isRereading.not() && hasReadChapters) READING else track.status
}
update(track)
} else {
// Set default fields if it's not found in the list
track.status = if (hasReadChapters) READING else PLANNING
track.score = 0F
add(track)
}
}
override suspend fun search(query: String): List<TrackSearch> {
return api.search(query)
}
override suspend fun refresh(track: Track): Track {
api.findLibManga(track, getUsername())?.let { remoteTrack ->
track.copyPersonalFrom(remoteTrack)
track.total_chapters = remoteTrack.total_chapters
}
return track
}
override fun getLogo() = R.drawable.ic_tracker_shikimori
override fun getLogoColor() = Color.rgb(40, 40, 40)
override fun getStatusList(): List<Int> {
return listOf(READING, COMPLETED, ON_HOLD, DROPPED, PLANNING, REPEATING)
}
override fun getStatus(status: Int): String = with(context) {
when (status) {
READING -> getString(R.string.reading)
COMPLETED -> getString(R.string.completed)
ON_HOLD -> getString(R.string.on_hold)
DROPPED -> getString(R.string.dropped)
PLANNING -> getString(R.string.plan_to_read)
REPEATING -> getString(R.string.repeating)
else -> ""
}
}
override fun getReadingStatus(): Int = READING
override fun getRereadingStatus(): Int = REPEATING
override fun getCompletionStatus(): Int = COMPLETED
override suspend fun login(username: String, password: String) = login(password)
suspend fun login(code: String) {
try {
val oauth = api.accessToken(code)
interceptor.newAuth(oauth)
val user = api.getCurrentUser()
saveCredentials(user.toString(), oauth.access_token)
} catch (e: Throwable) {
logout()
}
}
fun saveToken(oauth: OAuth?) {
preferences.trackToken(this).set(json.encodeToString(oauth))
}
fun restoreToken(): OAuth? {
return try {
json.decodeFromString<OAuth>(preferences.trackToken(this).get())
} catch (e: Exception) {
null
}
}
override fun logout() {
super.logout()
preferences.trackToken(this).delete()
interceptor.newAuth(null)
}
}
| apache-2.0 | a989627761b7bb0c927c4b0d9f33b0e4 | 30.791946 | 106 | 0.623813 | 4.585673 | false | false | false | false |
Deletescape-Media/Lawnchair | lawnchair/src/app/lawnchair/ui/preferences/components/TopBar.kt | 1 | 3753 | /*
* Copyright 2021, Lawnchair
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package app.lawnchair.ui.preferences.components
import androidx.activity.compose.LocalOnBackPressedDispatcherOwner
import androidx.compose.foundation.layout.*
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.rounded.ArrowBack
import androidx.compose.material.icons.rounded.ArrowForward
import androidx.compose.material3.*
import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.runtime.getValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.platform.LocalLayoutDirection
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.LayoutDirection
import androidx.compose.ui.unit.dp
@Composable
fun TopBar(
backArrowVisible: Boolean,
floating: Boolean,
label: String,
actions: @Composable RowScope.() -> Unit = {},
) {
val backDispatcher = LocalOnBackPressedDispatcherOwner.current?.onBackPressedDispatcher
val scrollFraction = if (floating) 1f else 0f
val colors = TopAppBarDefaults.smallTopAppBarColors()
val appBarContainerColor by colors.containerColor(scrollFraction)
val navigationIconContentColor = colors.navigationIconContentColor(scrollFraction)
val titleContentColor = colors.titleContentColor(scrollFraction)
val actionIconContentColor = colors.actionIconContentColor(scrollFraction)
Surface(color = appBarContainerColor) {
Row(
verticalAlignment = Alignment.CenterVertically,
modifier = Modifier
.statusBarsPadding()
.fillMaxWidth()
.height(topBarSize)
.padding(horizontal = 4.dp),
) {
if (backArrowVisible) {
CompositionLocalProvider(LocalContentColor provides navigationIconContentColor.value) {
ClickableIcon(
imageVector = backIcon(),
onClick = { backDispatcher?.onBackPressed() },
)
}
}
Text(
text = label,
style = MaterialTheme.typography.titleLarge,
color = titleContentColor.value,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
modifier = Modifier
.padding(horizontal = if (backArrowVisible) 4.dp else 12.dp)
.weight(weight = 1f),
)
CompositionLocalProvider(LocalContentColor provides actionIconContentColor.value) {
Row(
modifier = Modifier.fillMaxHeight(),
horizontalArrangement = Arrangement.End,
verticalAlignment = Alignment.CenterVertically,
content = actions,
)
}
}
}
}
@Composable
fun backIcon(): ImageVector =
if (LocalLayoutDirection.current == LayoutDirection.Ltr) {
Icons.Rounded.ArrowBack
} else {
Icons.Rounded.ArrowForward
}
val topBarSize = 64.dp
| gpl-3.0 | 0aff17d8c7fbe8a41e697052c8e36d34 | 36.909091 | 103 | 0.673328 | 5.23431 | false | false | false | false |
yshrsmz/monotweety | app/src/main/java/net/yslibrary/monotweety/status/adapter/EditorAdapterDelegate.kt | 1 | 3355 | package net.yslibrary.monotweety.status.adapter
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.RecyclerView
import com.google.android.material.textfield.TextInputEditText
import com.hannesdorfmann.adapterdelegates4.AdapterDelegate
import com.jakewharton.rxbinding3.widget.textChanges
import io.reactivex.disposables.SerialDisposable
import net.yslibrary.monotweety.R
import net.yslibrary.monotweety.base.findById
import net.yslibrary.monotweety.base.inflate
import net.yslibrary.monotweety.base.setTo
import net.yslibrary.monotweety.base.showKeyboard
class EditorAdapterDelegate(
private val listener: Listener
) : AdapterDelegate<List<ComposeStatusAdapter.Item>>() {
val statusInputDisposable = SerialDisposable()
override fun isForViewType(items: List<ComposeStatusAdapter.Item>, position: Int): Boolean {
return items[position].viewType == ComposeStatusAdapter.ViewType.EDITOR
}
override fun onBindViewHolder(
items: List<ComposeStatusAdapter.Item>,
position: Int,
holder: RecyclerView.ViewHolder,
payloads: MutableList<Any>
) {
if (holder is ViewHolder) {
val item = items[position] as Item
val shouldUpdateStatus =
item.clear || item.initialValue || holder.statusInput.text.isNullOrBlank()
if (shouldUpdateStatus) {
holder.statusInput.setText(item.status, TextView.BufferType.EDITABLE)
}
val counterColor = if (item.valid) R.color.colorTextSecondary else R.color.red
holder.statusCounter.setTextColor(
ContextCompat.getColor(
holder.itemView.context,
counterColor
)
)
holder.statusCounter.text = holder.itemView.context.getString(
R.string.label_status_counter,
item.statusLength,
item.maxLength
)
}
}
override fun onCreateViewHolder(parent: ViewGroup): RecyclerView.ViewHolder {
val holder = ViewHolder.create(parent)
holder.statusInput.textChanges()
.skip(1)
.subscribe { listener.onStatusChanged(it.toString()) }
.setTo(statusInputDisposable)
holder.statusInput.post {
holder.statusInput.showKeyboard()
}
return holder
}
data class Item(
val status: String,
val statusLength: Int,
val maxLength: Int,
val valid: Boolean,
val clear: Boolean,
val initialValue: Boolean = false,
override val viewType: ComposeStatusAdapter.ViewType = ComposeStatusAdapter.ViewType.EDITOR
) : ComposeStatusAdapter.Item
class ViewHolder(view: View) : RecyclerView.ViewHolder(view) {
val statusInput = view.findById<TextInputEditText>(R.id.status_input)
val statusCounter = view.findById<TextView>(R.id.status_counter)
companion object {
fun create(parent: ViewGroup): ViewHolder {
val view = parent.inflate(R.layout.vh_editor)
return ViewHolder(view)
}
}
}
interface Listener {
fun onStatusChanged(status: String)
}
}
| apache-2.0 | e968f687c10fa938c4fe9de0c72fc114 | 32.55 | 99 | 0.665872 | 4.99256 | false | false | false | false |
xfournet/intellij-community | plugins/settings-repository/src/upstreamEditor.kt | 1 | 3794 | // Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.settingsRepository
import com.intellij.ide.actions.ActionsCollector
import com.intellij.notification.NotificationType
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.Messages
import com.intellij.openapi.ui.TextFieldWithBrowseButton
import com.intellij.openapi.util.SystemInfo
import com.intellij.openapi.util.text.StringUtil
import com.intellij.util.text.nullize
import org.jetbrains.settingsRepository.actions.NOTIFICATION_GROUP
import java.awt.Container
import java.awt.event.ActionEvent
import javax.swing.AbstractAction
import javax.swing.Action
fun validateUrl(url: String?, project: Project?): Boolean {
if (url == null) {
Messages.showErrorDialog(project, "URL is empty", "")
return false
}
if (!icsManager.repositoryService.checkUrl(url, project)) {
return false
}
return true
}
fun createMergeActions(project: Project?, urlTextField: TextFieldWithBrowseButton, dialogParent: Container, okAction: (() -> Unit)): Array<Action> {
var syncTypes = SyncType.values()
if (SystemInfo.isMac) {
syncTypes = syncTypes.reversedArray()
}
val icsManager = icsManager
return Array(3) {
val syncType = syncTypes[it]
object : AbstractAction(icsMessage("action.${if (syncType == SyncType.MERGE) "Merge" else (if (syncType == SyncType.OVERWRITE_LOCAL) "ResetToTheirs" else "ResetToMy")}Settings.text")) {
private fun saveRemoteRepositoryUrl(): Boolean {
val url = urlTextField.text.nullize(true)
if (!validateUrl(url, project)) {
return false
}
val repositoryManager = icsManager.repositoryManager
repositoryManager.createRepositoryIfNeed()
repositoryManager.setUpstream(url, null)
return true
}
override fun actionPerformed(event: ActionEvent) {
ActionsCollector.getInstance().record("Ics.${getValue(Action.NAME)}")
val repositoryWillBeCreated = !icsManager.repositoryManager.isRepositoryExists()
var upstreamSet = false
try {
if (!saveRemoteRepositoryUrl()) {
if (repositoryWillBeCreated) {
// remove created repository
icsManager.repositoryManager.deleteRepository()
}
return
}
upstreamSet = true
if (repositoryWillBeCreated) {
icsManager.setApplicationLevelStreamProvider()
}
if (repositoryWillBeCreated && syncType != SyncType.OVERWRITE_LOCAL) {
ApplicationManager.getApplication().saveSettings()
icsManager.sync(syncType, project, { copyLocalConfig() })
}
else {
icsManager.sync(syncType, project, null)
}
}
catch (e: Throwable) {
if (repositoryWillBeCreated) {
// remove created repository
icsManager.repositoryManager.deleteRepository()
}
LOG.warn(e)
if (!upstreamSet || e is NoRemoteRepositoryException) {
Messages.showErrorDialog(dialogParent, icsMessage("set.upstream.failed.message", e.message), icsMessage("set.upstream.failed.title"))
}
else {
Messages.showErrorDialog(dialogParent, StringUtil.notNullize(e.message, "Internal error"), icsMessage(if (e is AuthenticationException) "sync.not.authorized.title" else "sync.rejected.title"))
}
return
}
NOTIFICATION_GROUP.createNotification(icsMessage("sync.done.message"), NotificationType.INFORMATION).notify(project)
okAction()
}
}
}
} | apache-2.0 | 393535ea9d20bf9374640fe3e22964be | 35.142857 | 204 | 0.683711 | 4.90815 | false | false | false | false |
Zhuinden/simple-stack | samples/advanced-samples/extensions-example/src/main/java/com/zhuinden/simplestackextensionsample/features/registration/RegistrationViewModel.kt | 1 | 2950 | package com.zhuinden.simplestackextensionsample.features.registration
import com.jakewharton.rxrelay2.BehaviorRelay
import com.zhuinden.rxvalidatebykt.validateBy
import com.zhuinden.simplestack.*
import com.zhuinden.simplestackextensionsample.app.AuthenticationManager
import com.zhuinden.simplestackextensionsample.features.profile.ProfileKey
import com.zhuinden.simplestackextensionsample.utils.get
import com.zhuinden.simplestackextensionsample.utils.observe
import com.zhuinden.simplestackextensionsample.utils.set
import com.zhuinden.statebundle.StateBundle
import io.reactivex.Observable
import io.reactivex.disposables.CompositeDisposable
class RegistrationViewModel(
private val authenticationManager: AuthenticationManager,
private val backstack: Backstack
) : Bundleable, ScopedServices.Registered {
private val compositeDisposable = CompositeDisposable()
val fullName = BehaviorRelay.createDefault("")
val bio = BehaviorRelay.createDefault("")
val username = BehaviorRelay.createDefault("")
val password = BehaviorRelay.createDefault("")
private val isRegisterAndLoginEnabledRelay = BehaviorRelay.createDefault(false)
val isRegisterAndLoginEnabled: Observable<Boolean> = isRegisterAndLoginEnabledRelay
private val isEnterProfileNextEnabledRelay = BehaviorRelay.createDefault(false)
val isEnterProfileNextEnabled: Observable<Boolean> = isEnterProfileNextEnabledRelay
override fun onServiceRegistered() {
validateBy(
fullName.map { it.isNotBlank() },
bio.map { it.isNotBlank() },
).observe(compositeDisposable) {
isEnterProfileNextEnabledRelay.set(it)
}
validateBy(
username.map { it.isNotBlank() },
password.map { it.isNotBlank() },
).observe(compositeDisposable) {
isRegisterAndLoginEnabledRelay.set(it)
}
}
override fun onServiceUnregistered() {
compositeDisposable.clear()
}
fun onRegisterAndLoginClicked() {
if (isRegisterAndLoginEnabledRelay.get()) {
authenticationManager.saveRegistration(username.get())
backstack.setHistory(History.of(ProfileKey(username.get())), StateChange.FORWARD)
}
}
fun onEnterProfileNextClicked() {
if (isEnterProfileNextEnabledRelay.get()) {
backstack.goTo(CreateLoginCredentialsKey)
}
}
override fun toBundle(): StateBundle = StateBundle().apply {
putString("username", username.get())
putString("password", password.get())
putString("fullName", fullName.get())
putString("bio", bio.get())
}
override fun fromBundle(bundle: StateBundle?) {
bundle?.run {
username.set(getString("username", ""))
password.set(getString("password", ""))
fullName.set(getString("fullName", ""))
bio.set(getString("bio", ""))
}
}
} | apache-2.0 | 4f0e76d1d5654a8e24f384f936b3e2da | 35.432099 | 93 | 0.709492 | 5.334539 | false | false | false | false |
FredJul/TaskGame | TaskGame/src/main/java/net/fred/taskgame/utils/KeyboardUtils.kt | 1 | 2469 | /*
* Copyright (c) 2012-2017 Frederic Julian
*
* 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:></http:>//www.gnu.org/licenses/>.
*/
package net.fred.taskgame.utils
import android.content.Context
import android.view.View
import android.view.WindowManager
import android.view.inputmethod.InputMethodManager
import net.fred.taskgame.activities.MainActivity
object KeyboardUtils {
fun showKeyboard(view: View?) {
if (view == null) {
return
}
view.requestFocus()
val inputManager = view.context.getSystemService(
Context.INPUT_METHOD_SERVICE) as InputMethodManager
inputManager.showSoftInput(view, InputMethodManager.SHOW_IMPLICIT)
(view.context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager).showSoftInput(view, 0)
if (!isKeyboardShowed(view)) {
inputManager.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0)
}
}
fun isKeyboardShowed(view: View?): Boolean {
if (view == null) {
return false
}
val inputManager = view.context.getSystemService(
Context.INPUT_METHOD_SERVICE) as InputMethodManager
return inputManager.isActive(view)
}
fun hideKeyboard(view: View?) {
if (view == null) {
return
}
val imm = view.context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
if (!imm.isActive) {
return
}
imm.hideSoftInputFromWindow(view.windowToken, 0)
// if (!isKeyboardShowed(view)) {
// imm.toggleSoftInput(InputMethodManager.HIDE_NOT_ALWAYS, InputMethodManager.RESULT_HIDDEN);
// }
}
fun hideKeyboard(activity: MainActivity) {
activity.window.setSoftInputMode(
WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN)
}
}
| gpl-3.0 | eed9a9373597bdc389067a5ef117afcd | 31.486842 | 114 | 0.676792 | 4.572222 | false | false | false | false |
andycondon/pathfinder-gps | src/test/kotlin/test/TestAssertions.kt | 1 | 379 | package test
import kotlin.test.assertTrue
fun <T : Number> assertBetween(expectedFloor: T, expectedCeiling: T, actual: T): Unit
{
val floor = expectedFloor.toDouble()
val ceiling = expectedCeiling.toDouble()
val test = actual.toDouble()
return assertTrue(((floor <= test) && (test <= ceiling)), "$actual is not between $expectedFloor and $expectedCeiling.")
} | mit | 226199b6ec628e6822b1608e20fb2982 | 30.666667 | 124 | 0.709763 | 4.075269 | false | true | false | false |
petrbalat/jlib | src/main/java/cz/softdeluxe/jlib/entity/utils.kt | 1 | 634 | package cz.softdeluxe.jlib.entity
import java.util.*
/**
* Created by Petr on 20. 12. 2014.
*/
inline fun <reified E> getEnumByKod(kod: Int): E? where E : KodAccessor, E : Enum<E> {
return enumValues<E>().firstOrNull { it.kod == kod }
}
inline fun <reified E> getEnumByText(text: String): E? where E : Describe, E : Enum<E> {
return enumValues<E>().firstOrNull { it.text == text }
}
val CS_LOCALE = Locale("cs")
fun <T, Id> Iterable<T>.findById(id: Id): T? where T : EntityTrait<Id> = singleOrNull { it.id == id }
fun <T, Id> Iterable<T>.findById(id: Id): T? where T : EntityTraitNN<Id> = singleOrNull { it.id == id } | apache-2.0 | 56fa71dbf53617d20e150fd2ab5c00b7 | 29.238095 | 103 | 0.648265 | 3.004739 | false | false | false | false |
quarkusio/quarkus | integration-tests/mongodb-panache-kotlin/src/main/kotlin/io/quarkus/it/mongodb/panache/reactive/person/resources/ReactivePersonRepositoryResource.kt | 1 | 3312 | package io.quarkus.it.mongodb.panache.reactive.person.resources
import com.mongodb.ReadPreference
import io.quarkus.it.mongodb.panache.person.Person
import io.quarkus.it.mongodb.panache.person.PersonName
import io.quarkus.it.mongodb.panache.reactive.person.ReactivePersonRepository
import io.quarkus.panache.common.Sort
import io.smallrye.mutiny.Uni
import java.net.URI
import javax.inject.Inject
import javax.ws.rs.DELETE
import javax.ws.rs.GET
import javax.ws.rs.PATCH
import javax.ws.rs.POST
import javax.ws.rs.PUT
import javax.ws.rs.Path
import javax.ws.rs.PathParam
import javax.ws.rs.QueryParam
import javax.ws.rs.core.Response
@Path("/reactive/persons/repository")
class ReactivePersonRepositoryResource {
@Inject
lateinit var reactivePersonRepository: ReactivePersonRepository
@GET
fun getPersons(@QueryParam("sort") sort: String?): Uni<List<Person>> {
return if (sort != null) {
reactivePersonRepository.listAll(Sort.ascending(sort))
} else reactivePersonRepository.listAll()
}
@GET
@Path("/search/{name}")
fun searchPersons(@PathParam("name") name: String): Set<PersonName> {
val uniqueNames = mutableSetOf<PersonName>()
val lastnames: List<PersonName> = reactivePersonRepository.find("lastname", name)
.project(PersonName::class.java)
.withReadPreference(ReadPreference.primaryPreferred())
.list()
.await()
.indefinitely()
lastnames.forEach { p -> uniqueNames.add(p) } // this will throw if it's not the right type
return uniqueNames
}
@POST
fun addPerson(person: Person): Uni<Response> {
return reactivePersonRepository.persist(person).map {
// the ID is populated before sending it to the database
Response.created(URI.create("/persons/entity${person.id}")).build()
}
}
@POST
@Path("/multiple")
fun addPersons(persons: List<Person>): Uni<Void> = reactivePersonRepository.persist(persons)
@PUT
fun updatePerson(person: Person): Uni<Response> =
reactivePersonRepository.update(person).map { Response.accepted().build() }
// PATCH is not correct here but it allows to test persistOrUpdate without a specific subpath
@PATCH
fun upsertPerson(person: Person): Uni<Response> =
reactivePersonRepository.persistOrUpdate(person).map { Response.accepted().build() }
@DELETE
@Path("/{id}")
fun deletePerson(@PathParam("id") id: String): Uni<Void> {
return reactivePersonRepository.findById(id.toLong())
.flatMap { person -> person?.let { reactivePersonRepository.delete(it) } }
}
@GET
@Path("/{id}")
fun getPerson(@PathParam("id") id: String) = reactivePersonRepository.findById(id.toLong())
@GET
@Path("/count")
fun countAll(): Uni<Long> = reactivePersonRepository.count()
@DELETE
fun deleteAll(): Uni<Void> = reactivePersonRepository.deleteAll().map { null }
@POST
@Path("/rename")
fun rename(@QueryParam("previousName") previousName: String, @QueryParam("newName") newName: String): Uni<Response> {
return reactivePersonRepository.update("lastname", newName).where("lastname", previousName)
.map { count -> Response.ok().build() }
}
}
| apache-2.0 | 1f0d3faddc03780b7c26a5391408d6ea | 35 | 121 | 0.688708 | 4.301299 | false | false | false | false |
blackbbc/Tucao | app/src/main/kotlin/me/sweetll/tucao/extension/BlockListHelpers.kt | 1 | 1671 | package me.sweetll.tucao.extension
import com.squareup.moshi.Moshi
import com.squareup.moshi.Types
object BlockListHelpers {
private val BLOCK_LIST_FILE_NAME = "block_list"
private val KEY_S_BLOCK_LIST = "block_list"
private val KEY_B_BLOCK_ENABLE = "block_enable"
private val adapter by lazy {
val moshi = Moshi.Builder()
.build()
val type = Types.newParameterizedType(MutableList::class.java, String::class.java)
moshi.adapter<MutableList<String>>(type)
}
fun loadBlockList(): MutableList<String> {
val sp = BLOCK_LIST_FILE_NAME.getSharedPreference()
val jsonString = sp.getString(KEY_S_BLOCK_LIST, "[\"http\"]") // 内置http
return adapter.fromJson(jsonString)!!
}
private fun save(blockList: MutableList<String>) {
val jsonString = adapter.toJson(blockList)
val sp = BLOCK_LIST_FILE_NAME.getSharedPreference()
sp.edit {
putString(KEY_S_BLOCK_LIST, jsonString)
}
}
fun add(keyword: String) {
val blockList = loadBlockList()
blockList.remove(keyword)
blockList.add(0, keyword)
save(blockList)
}
fun remove(keyword: String) {
val blockList = loadBlockList()
blockList.remove(keyword)
save(blockList)
}
fun isEnabled(): Boolean {
val sp = BLOCK_LIST_FILE_NAME.getSharedPreference()
return sp.getBoolean(KEY_B_BLOCK_ENABLE, true)
}
fun setEnabled(enabled: Boolean) {
val sp = BLOCK_LIST_FILE_NAME.getSharedPreference()
sp.edit {
putBoolean(KEY_B_BLOCK_ENABLE, enabled)
}
}
}
| mit | fdc6235226d2d9da8958f17a9fac234f | 27.254237 | 90 | 0.628674 | 4.105911 | false | false | false | false |
RyotaMurohoshi/KotLinq | src/main/kotlin/com/muhron/kotlinq/orderBy.kt | 1 | 3757 | package com.muhron.kotlinq
import java.util.Comparator
import kotlin.comparisons.compareBy
// orderBy with keySelector
fun <TSource, TKey : Comparable<TKey>> Sequence<TSource>.orderBy(keySelector: (TSource) -> TKey): OrderedEnumerable<TSource>
= OrderedEnumerableInternal(this, compareBy(keySelector))
fun <TSource, TKey : Comparable<TKey>> Iterable<TSource>.orderBy(keySelector: (TSource) -> TKey): OrderedEnumerable<TSource>
= asSequence().orderBy(keySelector)
fun <TSource, TKey : Comparable<TKey>> Array<TSource>.orderBy(keySelector: (TSource) -> TKey): OrderedEnumerable<TSource>
= asSequence().orderBy(keySelector)
fun <TSourceK, TSourceV, TKey : Comparable<TKey>> Map<TSourceK, TSourceV>.orderBy(keySelector: (Map.Entry<TSourceK, TSourceV>) -> TKey): OrderedEnumerable<Map.Entry<TSourceK, TSourceV>>
= asSequence().orderBy(keySelector)
// orderBy with keySelector and comparer
fun <TSource, TKey : Comparable<TKey>> Sequence<TSource>.orderBy(keySelector: (TSource) -> TKey, comparer: Comparator<TKey>): OrderedEnumerable<TSource>
= OrderedEnumerableInternal(this, compareBy(comparer, keySelector))
fun <TSource, TKey : Comparable<TKey>> Iterable<TSource>.orderBy(keySelector: (TSource) -> TKey, comparer: Comparator<TKey>): OrderedEnumerable<TSource>
= asSequence().orderBy(keySelector, comparer)
fun <TSource, TKey : Comparable<TKey>> Array<TSource>.orderBy(keySelector: (TSource) -> TKey, comparer: Comparator<TKey>): OrderedEnumerable<TSource>
= asSequence().orderBy(keySelector, comparer)
fun <TSourceK, TSourceV, TKey : Comparable<TKey>> Map<TSourceK, TSourceV>.orderBy(keySelector: (Map.Entry<TSourceK, TSourceV>) -> TKey, comparer: Comparator<TKey>): OrderedEnumerable<Map.Entry<TSourceK, TSourceV>>
= asSequence().orderBy(keySelector, comparer)
// orderByDescending with keySelector
fun <TSource, TKey : Comparable<TKey>> Sequence<TSource>.orderByDescending(keySelector: (TSource) -> TKey): OrderedEnumerable<TSource>
= OrderedEnumerableInternal(this, compareBy(keySelector).reversed())
fun <TSource, TKey : Comparable<TKey>> Iterable<TSource>.orderByDescending(keySelector: (TSource) -> TKey): OrderedEnumerable<TSource>
= asSequence().orderByDescending (keySelector)
fun <TSource, TKey : Comparable<TKey>> Array<TSource>.orderByDescending(keySelector: (TSource) -> TKey): OrderedEnumerable<TSource>
= asSequence().orderByDescending(keySelector)
fun <TSourceK, TSourceV, TKey : Comparable<TKey>> Map<TSourceK, TSourceV>.orderByDescending(keySelector: (Map.Entry<TSourceK, TSourceV>) -> TKey): OrderedEnumerable<Map.Entry<TSourceK, TSourceV>>
= asSequence().orderByDescending(keySelector)
// orderByDescending with keySelector and comparer
fun <TSource, TKey : Comparable<TKey>> Sequence<TSource>.orderByDescending(keySelector: (TSource) -> TKey, comparer: Comparator<TKey>): OrderedEnumerable<TSource>
= OrderedEnumerableInternal(this, compareBy(comparer, keySelector).reversed())
fun <TSource, TKey : Comparable<TKey>> Iterable<TSource>.orderByDescending(keySelector: (TSource) -> TKey, comparer: Comparator<TKey>): OrderedEnumerable<TSource>
= asSequence().orderByDescending(keySelector, comparer)
fun <TSource, TKey : Comparable<TKey>> Array<TSource>.orderByDescending(keySelector: (TSource) -> TKey, comparer: Comparator<TKey>): OrderedEnumerable<TSource>
= asSequence().orderByDescending(keySelector, comparer)
fun <TSourceK, TSourceV, TKey : Comparable<TKey>> Map<TSourceK, TSourceV>.orderByDescending(keySelector: (Map.Entry<TSourceK, TSourceV>) -> TKey, comparer: Comparator<TKey>): OrderedEnumerable<Map.Entry<TSourceK, TSourceV>>
= asSequence().orderByDescending(keySelector, comparer)
| mit | eca53dde82acbcbaaf3ea6af232f28f7 | 66.089286 | 223 | 0.758318 | 4.684539 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.