repo_name
stringlengths 7
79
| path
stringlengths 8
206
| copies
stringclasses 36
values | size
stringlengths 2
6
| content
stringlengths 55
523k
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 7.18
99.5
| line_max
int64 16
979
| alpha_frac
float64 0.3
0.87
| ratio
float64 2.01
8.07
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
goodwinnk/intellij-community | platform/testGuiFramework/src/com/intellij/testGuiFramework/remote/IdeProcessControlManager.kt | 1 | 1323 | // 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.testGuiFramework.remote
import java.io.InputStream
import java.util.concurrent.TimeUnit
object IdeProcessControlManager {
@Volatile
private var currentIdeProcess: Process? = null
/**
* returns current Ide process
*/
private fun getIdeProcess(): Process {
return currentIdeProcess ?: throw Exception("Current IDE process is not initialised or already been killed")
}
/**
* adds a new IDE process to control
*/
fun submitIdeProcess(ideProcess: Process) {
currentIdeProcess = ideProcess
}
fun waitForCurrentProcess(): Int = getIdeProcess().waitFor()
fun waitForCurrentProcess(timeout: Long, timeUnit: TimeUnit): Boolean = getIdeProcess().waitFor(timeout, timeUnit)
fun exitValue(): Int = getIdeProcess().exitValue()
fun getErrorStream(): InputStream = getIdeProcess().errorStream
fun getInputStream(): InputStream = getIdeProcess().inputStream
/**
* kills IDE java process if the pipeline for sockets has been crashed or IDE doesn't respond
*/
fun killIdeProcess() {
currentIdeProcess?.destroyForcibly() ?: throw Exception("Current IDE process is not initialised or already been killed")
}
} | apache-2.0 | 12751bce1640eb2414c9f2cf88125cbd | 30.52381 | 140 | 0.742252 | 4.658451 | false | false | false | false |
gameofbombs/kt-postgresql-async | postgresql-async/src/main/kotlin/com/github/mauricio/async/db/postgresql/codec/PostgreSQLConnectionHandler.kt | 2 | 12429 | /*
* Copyright 2013 Maurício Linhares
*
* Maurício Linhares licenses this file to you under the Apache License,
* version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package com.github.mauricio.async.db.postgresql.codec
import com.github.mauricio.async.db.Configuration
import com.github.mauricio.async.db.SSLConfiguration.*
import com.github.mauricio.async.db.column.ColumnDecoderRegistry
import com.github.mauricio.async.db.column.ColumnEncoderRegistry
import com.github.mauricio.async.db.postgresql.exceptions.*
import com.github.mauricio.async.db.postgresql.messages.backend.*
import com.github.mauricio.async.db.postgresql.messages.frontend.*
import com.github.mauricio.async.db.util.*
import java.net.InetSocketAddress
import io.netty.channel.*
import io.netty.bootstrap.Bootstrap
import com.github.mauricio.async.db.postgresql.messages.backend.DataRowMessage
import com.github.mauricio.async.db.postgresql.messages.backend.CommandCompleteMessage
import com.github.mauricio.async.db.postgresql.messages.backend.ProcessData
import com.github.mauricio.async.db.postgresql.messages.backend.RowDescriptionMessage
import com.github.mauricio.async.db.postgresql.messages.backend.ParameterStatusMessage
import io.netty.channel.socket.nio.NioSocketChannel
import io.netty.handler.codec.CodecException
import io.netty.handler.ssl.SslContextBuilder
import io.netty.handler.ssl.SslHandler
import io.netty.handler.ssl.util.InsecureTrustManagerFactory
import io.netty.util.concurrent.FutureListener
import mu.KLogging
import javax.net.ssl.TrustManagerFactory
import java.security.KeyStore
import java.io.FileInputStream
import kotlin.coroutines.Continuation
import kotlin.coroutines.ContinuationDispatcher
import kotlin.coroutines.suspendCoroutine
//TODO: there was implicit toFuture, we'll need somehow convert netty stuff to continuations
class PostgreSQLConnectionHandler
(
val configuration: Configuration,
val encoderRegistry: ColumnEncoderRegistry,
val decoderRegistry: ColumnDecoderRegistry,
val connectionDelegate: PostgreSQLConnectionDelegate,
val group: EventLoopGroup,
val executionService: ContinuationDispatcher
)
: SimpleChannelInboundHandler<Any>() {
companion object : KLogging()
private
val properties = mapOf(
"user" to configuration.username,
"database" to configuration.database,
"client_encoding" to configuration.charset.name(),
"DateStyle" to "ISO",
"extra_float_digits" to "2")
private val bootstrap = Bootstrap()
private var connectionContinuation: Continuation<PostgreSQLConnectionHandler>? = null
private var disconnectionContinuation: Continuation<PostgreSQLConnectionHandler>? = null
private var processData: ProcessData? = null
private var currentContext: ChannelHandlerContext? = null
suspend fun connect(): PostgreSQLConnectionHandler = suspendCoroutine {
cont ->
connectionContinuation = cont
bootstrap.group(this.group)
bootstrap.channel(NioSocketChannel::class.java)
bootstrap.handler(object : ChannelInitializer<Channel>() {
override fun initChannel(ch: Channel) {
ch.pipeline().addLast(
MessageDecoder(configuration.ssl.mode != SSLConfiguration.Mode.Disable, configuration.charset, configuration.maximumMessageSize),
MessageEncoder(configuration.charset, encoderRegistry),
this@PostgreSQLConnectionHandler)
}
})
bootstrap.option<Boolean>(ChannelOption.SO_KEEPALIVE, true)
bootstrap.option(ChannelOption.ALLOCATOR, configuration.allocator)
bootstrap.connect(InetSocketAddress(configuration.host, configuration.port)).addListener {
channelFuture ->
if (!channelFuture.isSuccess) {
connectionContinuation?.resumeWithException(channelFuture.cause())
}
}
}
suspend fun disconnect(): PostgreSQLConnectionHandler = suspendCoroutine {
cont ->
disconnectionContinuation = cont
if (isConnected()) {
this.currentContext!!.channel().writeAndFlush(CloseMessage).addClosure {
writeFuture ->
if (writeFuture.isSuccess) {
writeFuture.channel().close().addClosure {
closeFuture ->
if (closeFuture.isSuccess) {
executionService.dispatchResume(this, disconnectionContinuation!!)
} else {
executionService.dispatchResumeWithException(closeFuture.cause(), disconnectionContinuation!!)
}
}
} else {
executionService.dispatchResumeWithException(writeFuture.cause(), disconnectionContinuation!!)
}
}
}
// case Success (writeFuture) => writeFuture.channel.close().onComplete {
// case Success (closeFuture) => this.disconnectionPromise.trySuccess(this)
// case Failure (e) => this.disconnectionPromise.tryFailure(e)
// }
// case Failure (e) => this.disconnectionPromise.tryFailure(e)
}
fun isConnected(): Boolean =
currentContext?.channel()?.isActive ?: false
override fun channelActive(ctx: ChannelHandlerContext) {
if (configuration.ssl.mode == SSLConfiguration.Mode.Disable)
ctx.writeAndFlush(StartupMessage(properties))
else
ctx.writeAndFlush(SSLRequestMessage)
}
override fun channelRead0(ctx: ChannelHandlerContext, msg: Any) {
when (msg) {
is SSLResponseMessage ->
if (msg.supported) {
val ctxBuilder = SslContextBuilder.forClient()
if (configuration.ssl.mode >= SSLConfiguration.Mode.VerifyCA) {
val cert = configuration.ssl.rootCert
if (cert == null) {
val tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm())
val ks = KeyStore.getInstance(KeyStore.getDefaultType())
val cacerts = FileInputStream(System.getProperty("java.home") + "/lib/security/cacerts")
try {
ks.load(cacerts, "changeit".toCharArray())
} finally {
cacerts.close()
}
tmf.init(ks)
ctxBuilder.trustManager(tmf)
} else {
ctxBuilder.trustManager(cert)
}
} else {
ctxBuilder.trustManager(InsecureTrustManagerFactory.INSTANCE)
}
val sslContext = ctxBuilder.build()
val sslEngine = sslContext.newEngine(ctx.alloc(), configuration.host, configuration.port)
if (configuration.ssl.mode >= SSLConfiguration.Mode.VerifyFull) {
val sslParams = sslEngine.getSSLParameters()
sslParams.setEndpointIdentificationAlgorithm("HTTPS")
sslEngine.setSSLParameters(sslParams)
}
val handler = SslHandler(sslEngine)
ctx.pipeline().addFirst(handler)
handler.handshakeFuture().addListener(FutureListener<io.netty.channel.Channel>() {
future ->
if (future.isSuccess()) {
ctx.writeAndFlush(StartupMessage(properties))
} else {
connectionDelegate.onError(future.cause())
}
})
} else if (configuration.ssl.mode < SSLConfiguration.Mode.Require) {
ctx.writeAndFlush(StartupMessage(properties))
} else {
connectionDelegate.onError(IllegalArgumentException("SSL is not supported on server"))
}
is ServerMessage -> {
when (msg.kind) {
ServerMessage.BackendKeyData -> {
this.processData = msg as ProcessData
}
ServerMessage.BindComplete -> {
}
ServerMessage.Authentication -> {
logger.debug("Authentication response received {}", msg)
connectionDelegate.onAuthenticationResponse(msg as AuthenticationMessage)
}
ServerMessage.CommandComplete -> {
connectionDelegate.onCommandComplete(msg as CommandCompleteMessage)
}
ServerMessage.CloseComplete -> {
}
ServerMessage.DataRow -> {
connectionDelegate.onDataRow(msg as DataRowMessage)
}
ServerMessage.Error -> {
connectionDelegate.onError(msg as ErrorMessage)
}
ServerMessage.EmptyQueryString -> {
val exception = QueryMustNotBeNullOrEmptyException(null)
exception.fillInStackTrace()
connectionDelegate.onError(exception)
}
ServerMessage.NoData -> {
}
ServerMessage.Notice -> {
logger.info("Received notice {}", msg)
}
ServerMessage.NotificationResponse -> {
connectionDelegate.onNotificationResponse(msg as NotificationResponse)
}
ServerMessage.ParameterStatus -> {
connectionDelegate.onParameterStatus(msg as ParameterStatusMessage)
}
ServerMessage.ParseComplete -> {
}
ServerMessage.ReadyForQuery -> {
connectionDelegate.onReadyForQuery()
}
ServerMessage.RowDescription -> {
connectionDelegate.onRowDescription(msg as RowDescriptionMessage)
}
else -> {
val exception = IllegalStateException("Handler not implemented for message %s".format(msg.kind))
exception.fillInStackTrace()
connectionDelegate.onError(exception)
}
}
}
else -> {
logger.error("Unknown message type - {}", msg)
val exception = IllegalArgumentException("Unknown message type - %s".format(msg))
exception.fillInStackTrace()
connectionDelegate.onError(exception)
}
}
}
override fun exceptionCaught(ctx: ChannelHandlerContext, cause: Throwable) =
// unwrap CodecException if needed
when (cause) {
is CodecException -> connectionDelegate.onError(cause.cause!!)
else -> connectionDelegate.onError(cause)
}
override fun channelInactive(ctx: ChannelHandlerContext) {
logger.info("Connection disconnected - {}", ctx.channel().remoteAddress())
}
override fun handlerAdded(ctx: ChannelHandlerContext) {
this.currentContext = ctx
}
fun write(message: ClientMessage) {
this.currentContext!!.writeAndFlush(message).addClosure {
future ->
if (!future.isSuccess) connectionDelegate.onError(future.cause())
}
}
}
| apache-2.0 | 49163fbc3178ec29703e215b6a9151ef | 43.862816 | 153 | 0.596282 | 5.617993 | false | true | false | false |
matejdro/WearMusicCenter | common/src/main/java/com/matejdro/wearmusiccenter/common/ScreenQuadrant.kt | 1 | 282 | package com.matejdro.wearmusiccenter.common
class ScreenQuadrant {
companion object {
val QUADRANT_NAMES = arrayOf("Left", "Top", "Right", "Bottom")
const val LEFT = 0
const val TOP = 1
const val RIGHT = 2
const val BOTTOM = 3
}
} | gpl-3.0 | 2ae4147c5008136050095a80e6a87bb3 | 19.214286 | 70 | 0.595745 | 4.208955 | false | false | false | false |
vanita5/twittnuker | twittnuker/src/main/kotlin/de/vanita5/twittnuker/util/notification/NotificationChannelsManager.kt | 1 | 5072 | /*
* Twittnuker - Twitter client for Android
*
* Copyright (C) 2013-2017 vanita5 <[email protected]>
*
* This program incorporates a modified version of Twidere.
* Copyright (C) 2012-2017 Mariotaku Lee <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package de.vanita5.twittnuker.util.notification
import android.accounts.AccountManager
import android.annotation.TargetApi
import android.app.NotificationChannel
import android.app.NotificationChannelGroup
import android.app.NotificationManager
import android.content.Context
import android.os.Build
import org.mariotaku.kpreferences.get
import de.vanita5.twittnuker.constant.nameFirstKey
import de.vanita5.twittnuker.extension.model.notificationChannelGroupId
import de.vanita5.twittnuker.extension.model.notificationChannelId
import de.vanita5.twittnuker.model.notification.NotificationChannelSpec
import de.vanita5.twittnuker.model.util.AccountUtils
import de.vanita5.twittnuker.util.dagger.DependencyHolder
object NotificationChannelsManager {
fun initialize(context: Context) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) return
NotificationChannelManagerImpl.initialize(context)
}
fun updateAccountChannelsAndGroups(context: Context) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) return
NotificationChannelManagerImpl.updateAccountChannelsAndGroups(context)
}
@TargetApi(Build.VERSION_CODES.O)
private object NotificationChannelManagerImpl {
fun initialize(context: Context) {
val nm = context.getSystemService(NotificationManager::class.java)
val addedChannels = mutableListOf<String>()
for (spec in NotificationChannelSpec.values()) {
if (spec.grouped) continue
val channel = NotificationChannel(spec.id, context.getString(spec.nameRes), spec.importance)
if (spec.descriptionRes != 0) {
channel.description = context.getString(spec.descriptionRes)
}
channel.setShowBadge(spec.showBadge)
nm.createNotificationChannel(channel)
addedChannels.add(channel.id)
}
nm.notificationChannels.forEach {
if (it.id !in addedChannels && it.group == null) {
nm.deleteNotificationChannel(it.id)
}
}
}
fun updateAccountChannelsAndGroups(context: Context) {
val holder = DependencyHolder.get(context)
val am = AccountManager.get(context)
val nm = context.getSystemService(NotificationManager::class.java)
val pref = holder.preferences
val ucnm = holder.userColorNameManager
val accounts = AccountUtils.getAllAccountDetails(am, false)
val specs = NotificationChannelSpec.values()
val addedChannels = mutableListOf<String>()
val addedGroups = mutableListOf<String>()
accounts.forEach { account ->
val group = NotificationChannelGroup(account.key.notificationChannelGroupId(),
ucnm.getDisplayName(account.user, pref[nameFirstKey]))
addedGroups.add(group.id)
nm.createNotificationChannelGroup(group)
for (spec in specs) {
if (!spec.grouped) continue
val channel = NotificationChannel(account.key.notificationChannelId(spec.id),
context.getString(spec.nameRes), spec.importance)
if (spec.descriptionRes != 0) {
channel.description = context.getString(spec.descriptionRes)
}
channel.group = group.id
channel.setShowBadge(spec.showBadge)
nm.createNotificationChannel(channel)
addedChannels.add(channel.id)
}
}
// Delete all channels and groups of non-existing accounts
nm.notificationChannels.forEach {
if (it.id !in addedChannels && it.group != null) {
nm.deleteNotificationChannel(it.id)
}
}
nm.notificationChannelGroups.forEach {
if (it.id !in addedGroups) {
nm.deleteNotificationChannelGroup(it.id)
}
}
}
}
} | gpl-3.0 | f227d89c1bc0d70fc5d5d041cf700113 | 38.325581 | 108 | 0.650039 | 5.026759 | false | false | false | false |
wikimedia/apps-android-wikipedia | app/src/main/java/org/wikipedia/views/UserMentionInputView.kt | 1 | 5651 | package org.wikipedia.views
import android.content.Context
import android.util.AttributeSet
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.LinearLayout
import android.widget.TextView
import androidx.core.view.isVisible
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers
import io.reactivex.rxjava3.core.Observable
import io.reactivex.rxjava3.disposables.CompositeDisposable
import io.reactivex.rxjava3.schedulers.Schedulers
import org.wikipedia.R
import org.wikipedia.WikipediaApp
import org.wikipedia.databinding.ViewUserMentionInputBinding
import org.wikipedia.dataclient.ServiceFactory
import org.wikipedia.page.PageTitle
import org.wikipedia.util.StringUtil
import java.util.concurrent.TimeUnit
class UserMentionInputView : LinearLayout, UserMentionEditText.Listener {
interface Listener {
fun onUserMentionListUpdate()
fun onUserMentionComplete()
}
constructor(context: Context) : super(context)
constructor(context: Context, attrs: AttributeSet?) : super(context, attrs)
constructor(context: Context, attrs: AttributeSet?, defStyle: Int) : super(context, attrs, defStyle)
val editText get() = binding.inputEditText
val textInputLayout get() = binding.inputTextLayout
var wikiSite = WikipediaApp.instance.wikiSite
var listener: Listener? = null
var userNameHints: Set<String> = emptySet()
private val binding = ViewUserMentionInputBinding.inflate(LayoutInflater.from(context), this)
private val disposables = CompositeDisposable()
private val userNameList = mutableListOf<String>()
init {
orientation = VERTICAL
binding.inputEditText.listener = this
binding.userListRecycler.layoutManager = LinearLayoutManager(context)
binding.userListRecycler.adapter = UserNameAdapter()
binding.inputEditText.isTextInputLayoutFocusedRectEnabled = false
}
override fun onDetachedFromWindow() {
super.onDetachedFromWindow()
disposables.clear()
}
override fun onStartUserNameEntry() {
userNameList.clear()
binding.userListRecycler.adapter?.notifyDataSetChanged()
}
override fun onCancelUserNameEntry() {
disposables.clear()
binding.userListRecycler.isVisible = false
listener?.onUserMentionComplete()
}
override fun onUserNameChanged(userName: String) {
var userNamePrefix = userName
if (userNamePrefix.startsWith("@") && userNamePrefix.length > 1) {
userNamePrefix = userNamePrefix.substring(1)
if (userNamePrefix.isNotEmpty()) {
searchForUserName(userNamePrefix)
}
}
}
fun maybePrepopulateUserName(currentUserName: String, currentPageTitle: PageTitle) {
if (binding.inputEditText.text.isNullOrEmpty() && userNameHints.isNotEmpty()) {
val candidateName = userNameHints.first()
if (candidateName != currentUserName &&
StringUtil.addUnderscores(candidateName.lowercase()) != StringUtil.addUnderscores(currentPageTitle.text.lowercase())) {
binding.inputEditText.prepopulateUserName(candidateName)
}
}
}
private fun searchForUserName(prefix: String) {
disposables.clear()
disposables.add(Observable.timer(200, TimeUnit.MILLISECONDS)
.flatMap { ServiceFactory.get(wikiSite).prefixSearchUsers(prefix, 10) }
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe({ response ->
userNameList.clear()
userNameList.addAll(userNameHints.filter { it.startsWith(prefix, ignoreCase = true) })
response.query?.allUsers?.forEach {
if (!userNameList.contains(it.name)) {
userNameList.add(it.name)
}
}
onSearchResults()
}, {
onSearchError(it)
})
)
}
private fun onSearchResults() {
binding.userListRecycler.isVisible = true
binding.userListRecycler.adapter?.notifyDataSetChanged()
listener?.onUserMentionListUpdate()
}
private fun onSearchError(t: Throwable) {
t.printStackTrace()
binding.userListRecycler.isVisible = false
}
private inner class UserNameViewHolder constructor(itemView: View) : RecyclerView.ViewHolder(itemView), OnClickListener {
private lateinit var userName: String
fun bindItem(position: Int) {
userName = userNameList[position]
itemView.setOnClickListener(this)
(itemView as TextView).text = userName
}
override fun onClick(v: View) {
binding.inputEditText.onCommitUserName(userName)
listener?.onUserMentionComplete()
}
}
private inner class UserNameAdapter : RecyclerView.Adapter<UserNameViewHolder>() {
override fun getItemCount(): Int {
return userNameList.size
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): UserNameViewHolder {
return UserNameViewHolder(LayoutInflater.from(parent.context).inflate(R.layout.item_search_recent, parent, false))
}
override fun onBindViewHolder(holder: UserNameViewHolder, pos: Int) {
holder.bindItem(pos)
}
}
}
| apache-2.0 | cdf701c30e31018b3e8c118e4463aa47 | 36.673333 | 139 | 0.680057 | 5.232407 | false | false | false | false |
vanita5/twittnuker | twittnuker/src/main/kotlin/de/vanita5/twittnuker/task/twitter/GetSavedSearchesTask.kt | 1 | 2573 | /*
* Twittnuker - Twitter client for Android
*
* Copyright (C) 2013-2017 vanita5 <[email protected]>
*
* This program incorporates a modified version of Twidere.
* Copyright (C) 2012-2017 Mariotaku Lee <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package de.vanita5.twittnuker.task.twitter
import android.content.Context
import org.mariotaku.abstask.library.AbstractTask
import de.vanita5.microblog.library.MicroBlogException
import org.mariotaku.sqliteqb.library.Expression
import de.vanita5.twittnuker.TwittnukerConstants.LOGTAG
import de.vanita5.twittnuker.model.SingleResponse
import de.vanita5.twittnuker.model.UserKey
import de.vanita5.twittnuker.provider.TwidereDataStore.SavedSearches
import de.vanita5.twittnuker.util.ContentValuesCreator
import de.vanita5.twittnuker.util.DebugLog
import de.vanita5.twittnuker.util.MicroBlogAPIFactory
import de.vanita5.twittnuker.util.content.ContentResolverUtils
class GetSavedSearchesTask(
private val context: Context
) : AbstractTask<Array<UserKey>, SingleResponse<Unit>, Any?>() {
override fun doLongOperation(params: Array<UserKey>): SingleResponse<Unit> {
val cr = context.contentResolver
for (accountKey in params) {
val twitter = MicroBlogAPIFactory.getInstance(context, accountKey) ?: continue
try {
val searches = twitter.savedSearches
val values = ContentValuesCreator.createSavedSearches(searches,
accountKey)
val where = Expression.equalsArgs(SavedSearches.ACCOUNT_KEY)
val whereArgs = arrayOf(accountKey.toString())
cr.delete(SavedSearches.CONTENT_URI, where.sql, whereArgs)
ContentResolverUtils.bulkInsert(cr, SavedSearches.CONTENT_URI, values)
} catch (e: MicroBlogException) {
DebugLog.w(LOGTAG, tr = e)
}
}
return SingleResponse(Unit)
}
} | gpl-3.0 | b30e1581bb5c5dcef05cb68ec584c250 | 41.9 | 90 | 0.726001 | 4.521968 | false | false | false | false |
stripe/stripe-android | payments-core/src/main/java/com/stripe/android/view/CardBrandSpinner.kt | 1 | 4277 | package com.stripe.android.view
import android.content.Context
import android.graphics.drawable.Drawable
import android.util.AttributeSet
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ArrayAdapter
import androidx.annotation.ColorInt
import androidx.appcompat.widget.AppCompatSpinner
import androidx.core.content.ContextCompat
import androidx.core.graphics.drawable.DrawableCompat
import com.stripe.android.R
import com.stripe.android.databinding.CardBrandSpinnerDropdownBinding
import com.stripe.android.databinding.CardBrandSpinnerMainBinding
import com.stripe.android.model.CardBrand
internal class CardBrandSpinner @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
defStyleAttr: Int = androidx.appcompat.R.attr.spinnerStyle
) : AppCompatSpinner(context, attrs, defStyleAttr, MODE_DROPDOWN) {
private val cardBrandsAdapter = Adapter(context)
private var defaultBackground: Drawable? = null
init {
adapter = cardBrandsAdapter
dropDownWidth = resources.getDimensionPixelSize(R.dimen.card_brand_spinner_dropdown_width)
}
val cardBrand: CardBrand?
get() {
return selectedItem as CardBrand?
}
override fun onFinishInflate() {
super.onFinishInflate()
defaultBackground = background
setCardBrands(
listOf(CardBrand.Unknown)
)
}
fun setTintColor(@ColorInt tintColor: Int) {
cardBrandsAdapter.tintColor = tintColor
}
@JvmSynthetic
fun setCardBrands(cardBrands: List<CardBrand>) {
cardBrandsAdapter.clear()
cardBrandsAdapter.addAll(cardBrands)
cardBrandsAdapter.notifyDataSetChanged()
setSelection(0)
// enable dropdown selector if there are multiple card brands, disable otherwise
if (cardBrands.size > 1) {
isClickable = true
isEnabled = true
background = defaultBackground
} else {
isClickable = false
isEnabled = false
setBackgroundColor(
ContextCompat.getColor(context, android.R.color.transparent)
)
}
}
internal class Adapter(
context: Context
) : ArrayAdapter<CardBrand>(
context,
0
) {
private val layoutInflater = LayoutInflater.from(context)
@ColorInt
internal var tintColor: Int = 0
override fun getView(position: Int, convertView: View?, parent: ViewGroup): View {
val viewBinding = convertView?.let {
CardBrandSpinnerMainBinding.bind(it)
} ?: CardBrandSpinnerMainBinding.inflate(layoutInflater, parent, false)
val cardBrand = requireNotNull(getItem(position))
viewBinding.image.also {
it.setImageDrawable(createCardBrandDrawable(cardBrand))
it.contentDescription = cardBrand.displayName
}
return viewBinding.root
}
override fun getDropDownView(position: Int, convertView: View?, parent: ViewGroup): View {
val viewBinding = convertView?.let {
CardBrandSpinnerDropdownBinding.bind(it)
} ?: CardBrandSpinnerDropdownBinding.inflate(layoutInflater, parent, false)
val cardBrand = requireNotNull(getItem(position))
viewBinding.textView.also {
it.text = cardBrand.displayName
it.setCompoundDrawablesRelativeWithIntrinsicBounds(
createCardBrandDrawable(cardBrand),
null,
null,
null
)
}
return viewBinding.root
}
private fun createCardBrandDrawable(cardBrand: CardBrand): Drawable {
val icon = requireNotNull(
ContextCompat.getDrawable(context, cardBrand.icon)
)
return if (cardBrand == CardBrand.Unknown) {
val compatIcon = DrawableCompat.wrap(icon)
DrawableCompat.setTint(compatIcon.mutate(), tintColor)
DrawableCompat.unwrap(compatIcon)
} else {
icon
}
}
}
}
| mit | 2875c0a7e805865965df5b4f01294293 | 32.155039 | 98 | 0.644377 | 5.235006 | false | false | false | false |
altamic/Obliterator | app/src/main/kotlin/it/convergent/obliterator/utils.kt | 1 | 5678 | package it.convergent.obliterator
import android.nfc.tech.NfcA
import java.text.SimpleDateFormat
import java.util.*
/**
* Created by altamic on 08/04/16.
*/
sealed class Maybe<out T> {
object None: Maybe<Nothing>()
// object Unknown: Maybe<Nothing>()
// object Invalid: Maybe<Nothing>()
class Just<T>(val value: T): Maybe<T>()
}
inline fun Int.times(block: (index: Int) -> Unit): Int {
if (this > 0) {
for (item: Int in 0.rangeTo(this.minus(1))) {
block.invoke(item)
}
}
return this
}
fun Int.isEven(): Boolean {
return this % 2 == 0
}
fun Int.isOdd(): Boolean {
return this % 2 == 1
}
fun Int.toByteArray(): ByteArray {
val byteArray = ByteArray(size = 4)
val byteBits = 8
val mask = 0x000000FF
byteArray.size.times { index ->
val offset = byteBits * byteArray.size.minus(1).minus(index)
byteArray[index] = this.ushr(bitCount = offset).and(mask).toByte()
}
return byteArray
}
fun Long.toByteArray(): ByteArray {
val byteArray = ByteArray(size = 8)
val byteBits = 8
val mask = 0x000000FF
byteArray.size.times { index ->
val offset = byteBits * byteArray.size.minus(1).minus(index)
byteArray[index] = this.ushr(bitCount = offset).and(mask.toLong()).toByte()
}
return byteArray
}
fun ByteArray.getShort(index: Int): Int {
val byte1Mask = 0x000000FF
val byte0Mask = 0x0000FF00
val byte1 = this[index + 1].toInt().shl(bitCount = 0)
val byte0 = this[index + 0].toInt().shl(bitCount = 8)
return ((byte0 and byte0Mask) or (byte1 and byte1Mask))
}
fun ByteArray.getInt(index: Int): Long {
val byte3Mask: Long = 0x000000FF
val byte2Mask: Long = 0x0000FF00
val byte1Mask: Long = 0x00FF0000
val byte0Mask: Long = 0xFF000000
val byte3: Long = this[index + 3].toLong().shl(bitCount = 0)
val byte2: Long = this[index + 2].toLong().shl(bitCount = 8)
val byte1: Long = this[index + 1].toLong().shl(bitCount = 16)
val byte0: Long = this[index + 0].toLong().shl(bitCount = 24)
return ((byte0 and byte0Mask) or
(byte1 and byte1Mask ) or
(byte2 and byte2Mask ) or
(byte3 and byte3Mask))
}
fun ByteArray.toHexString(): String {
val hexArray = "0123456789ABCDEF".toCharArray()
val hexChars = CharArray(size = this.size * 2)
this.size.toInt().times { index ->
val int = this[index].toInt() and 0xFF
hexChars[index * 2 + 0] = hexArray[int shr 4]
hexChars[index * 2 + 1] = hexArray[int and 0x0F]
}
return StringBuilder()
.append(hexChars)
.toString()
}
fun hexStringToByteArray(hex: String): ByteArray {
val size = hex.length
if (size.isOdd()) {
throw IllegalArgumentException("Hex string must have even number of characters")
}
if (!hex.matches("[0-9a-fA-F]+".toRegex())) {
throw IllegalArgumentException("Hex string must have only digits " +
"or case insensitive " +
"letters from 'A' until 'F'")
}
val data = ByteArray(size / 2)
size.times { index ->
if (index.isEven()) {
// Convert each character into a integer (base-16), then bit-shift into place
data[index / 2] = (((Character.digit(hex.codePointAt(index + 0), 16)) shl 4)
+ Character.digit(hex.codePointAt(index + 1), 16)).toByte()
}
}
return data
}
fun Set<Carnet>.toJson(): String {
return this.map { carnet -> "\"${carnet.toString()}\"" }
.joinToString(separator = ", ", prefix = "[", postfix = "]")
}
fun String.toCarnetSet(): Set<Carnet> {
val regex = "\\A\\[\\s*((\"[0-9A-F]{128}\")(,\\s(\"[0-9A-F]{128}\"))*)+\\]\\z".toRegex()
return if (this.matches(regex)) {
this.removeSurrounding(prefix = "[", suffix = "]")
.split(", ")
.map { it.removeSurrounding(delimiter = "\"")}
.map { Carnet(hexStringToByteArray(it))}
.toSet()
} else {
emptySet<Carnet>()
}
}
fun ebgGuvegrra(input: String): String {
val sb = StringBuilder()
input.length.times { index ->
var c: Char = input[index]
if (c >= 'a' && c <= 'm') c += 13
else if (c >= 'A' && c <= 'M') c += 13
else if (c >= 'n' && c <= 'z') c -= 13
else if (c >= 'N' && c <= 'Z') c -= 13
sb.append(c)
}
return sb.toString()
}
fun NfcA.readPages(pageOffset: Int): ByteArray {
val cmd = byteArrayOf(0x30, pageOffset.toByte())
return transceive(cmd)
}
fun NfcA.writePage(pageOffset: Int, data: ByteArray) {
val cmd = ByteArray(data.size + 2)
cmd[0] = 0xA2.toByte()
cmd[1] = pageOffset.toByte()
System.arraycopy(data, 0, cmd, 2, data.size)
transceive(cmd)
}
object GttEpoch {
fun calendar(minutesSinceGttEpoch: Int): Calendar {
val GTT_EPOCH = "01/01/2005 00:00"
val formatter = SimpleDateFormat("dd/MM/yyyy HH:mm", Locale.ITALY)
val calendar = Calendar.getInstance()
calendar.time = formatter.parse(GTT_EPOCH)
calendar.add(Calendar.MINUTE, minutesSinceGttEpoch)
return calendar
}
fun currentTime(fromCalendar: Calendar = Calendar.getInstance()): Int {
val millisToMinutesFactor = (1000 * 60)
val gttCalendar = calendar(minutesSinceGttEpoch = 0) // gtt epoch
val minutesSinceGttEpoch = ((fromCalendar.timeInMillis -
gttCalendar.timeInMillis) / millisToMinutesFactor).toInt()
return minutesSinceGttEpoch
}
} | gpl-3.0 | 8bf60fbb7fb29cc839eb2fa967fa7b0d | 27.537688 | 92 | 0.585417 | 3.598226 | false | false | false | false |
exponent/exponent | android/expoview/src/main/java/host/exp/exponent/experience/ExperienceActivity.kt | 2 | 27025 | // Copyright 2015-present 650 Industries. All rights reserved.
package host.exp.exponent.experience
import android.app.AlertDialog
import android.app.Notification
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.text.TextUtils
import android.view.KeyEvent
import android.view.View
import android.view.ViewGroup
import android.view.animation.AccelerateInterpolator
import android.view.animation.AlphaAnimation
import android.view.animation.Animation
import android.widget.RemoteViews
import androidx.core.app.NotificationCompat
import androidx.core.content.ContextCompat
import com.facebook.react.ReactPackage
import com.facebook.react.bridge.UiThreadUtil
import com.facebook.soloader.SoLoader
import de.greenrobot.event.EventBus
import expo.modules.core.interfaces.Package
import expo.modules.splashscreen.singletons.SplashScreen
import expo.modules.manifests.core.Manifest
import host.exp.exponent.*
import host.exp.exponent.ExpoUpdatesAppLoader.AppLoaderCallback
import host.exp.exponent.ExpoUpdatesAppLoader.AppLoaderStatus
import host.exp.exponent.analytics.Analytics
import host.exp.exponent.analytics.EXL
import host.exp.exponent.branch.BranchManager
import host.exp.exponent.di.NativeModuleDepsProvider
import host.exp.exponent.experience.loading.LoadingProgressPopupController
import host.exp.exponent.experience.splashscreen.ManagedAppSplashScreenConfiguration
import host.exp.exponent.experience.splashscreen.ManagedAppSplashScreenViewController
import host.exp.exponent.experience.splashscreen.ManagedAppSplashScreenViewProvider
import host.exp.exponent.kernel.*
import host.exp.exponent.kernel.Kernel.KernelStartedRunningEvent
import host.exp.exponent.kernel.KernelConstants.ExperienceOptions
import host.exp.exponent.notifications.*
import host.exp.exponent.storage.ExponentDB
import host.exp.exponent.storage.ExponentDBObject
import host.exp.exponent.utils.AsyncCondition
import host.exp.exponent.utils.AsyncCondition.AsyncConditionListener
import host.exp.exponent.utils.ExperienceActivityUtils
import host.exp.exponent.utils.ExpoActivityIds
import host.exp.expoview.Exponent
import host.exp.expoview.Exponent.StartReactInstanceDelegate
import host.exp.expoview.R
import org.json.JSONArray
import org.json.JSONException
import org.json.JSONObject
import versioned.host.exp.exponent.ExponentPackageDelegate
import versioned.host.exp.exponent.ReactUnthemedRootView
import java.lang.ref.WeakReference
import javax.inject.Inject
open class ExperienceActivity : BaseExperienceActivity(), StartReactInstanceDelegate {
open fun expoPackages(): List<Package>? {
// Experience must pick its own modules in ExponentPackage
return null
}
open fun reactPackages(): List<ReactPackage>? {
return null
}
override val exponentPackageDelegate: ExponentPackageDelegate? = null
private var nuxOverlayView: ReactUnthemedRootView? = null
private var notification: ExponentNotification? = null
private var tempNotification: ExponentNotification? = null
private var isShellApp = false
protected var intentUri: String? = null
private var isReadyForBundle = false
private var notificationRemoteViews: RemoteViews? = null
private var notificationBuilder: NotificationCompat.Builder? = null
private var isLoadExperienceAllowedToRun = false
private var shouldShowLoadingViewWithOptimisticManifest = false
/**
* Controls loadingProgressPopupWindow that is shown above whole activity.
*/
lateinit var loadingProgressPopupController: LoadingProgressPopupController
var managedAppSplashScreenViewProvider: ManagedAppSplashScreenViewProvider? = null
var managedAppSplashScreenViewController: ManagedAppSplashScreenViewController? = null
@Inject
lateinit var exponentManifest: ExponentManifest
@Inject
lateinit var devMenuManager: DevMenuManager
private val devBundleDownloadProgressListener: DevBundleDownloadProgressListener =
object : DevBundleDownloadProgressListener {
override fun onProgress(status: String?, done: Int?, total: Int?) {
UiThreadUtil.runOnUiThread {
loadingProgressPopupController.updateProgress(
status,
done,
total
)
}
}
override fun onSuccess() {
UiThreadUtil.runOnUiThread {
loadingProgressPopupController.hide()
managedAppSplashScreenViewController?.startSplashScreenWarningTimer()
finishLoading()
}
}
override fun onFailure(error: Exception) {
UiThreadUtil.runOnUiThread {
loadingProgressPopupController.hide()
interruptLoading()
}
}
}
/*
*
* Lifecycle
*
*/
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
isLoadExperienceAllowedToRun = true
shouldShowLoadingViewWithOptimisticManifest = true
loadingProgressPopupController = LoadingProgressPopupController(this)
NativeModuleDepsProvider.instance.inject(ExperienceActivity::class.java, this)
EventBus.getDefault().registerSticky(this)
activityId = ExpoActivityIds.getNextAppActivityId()
// TODO: audit this now that kernel logic is on the native side in Kotlin
var shouldOpenImmediately = true
// If our activity was killed for memory reasons or because of "Don't keep activities",
// try to reload manifest using the savedInstanceState
if (savedInstanceState != null) {
val manifestUrl = savedInstanceState.getString(KernelConstants.MANIFEST_URL_KEY)
if (manifestUrl != null) {
this.manifestUrl = manifestUrl
}
}
// On cold boot to experience, we're given this information from the Kotlin kernel, instead of
// the JS kernel.
val bundle = intent.extras
if (bundle != null && this.manifestUrl == null) {
val manifestUrl = bundle.getString(KernelConstants.MANIFEST_URL_KEY)
if (manifestUrl != null) {
this.manifestUrl = manifestUrl
}
// Don't want to get here if savedInstanceState has manifestUrl. Only care about
// IS_OPTIMISTIC_KEY the first time onCreate is called.
val isOptimistic = bundle.getBoolean(KernelConstants.IS_OPTIMISTIC_KEY)
if (isOptimistic) {
shouldOpenImmediately = false
}
}
if (this.manifestUrl != null && shouldOpenImmediately) {
val forceCache = intent.getBooleanExtra(KernelConstants.LOAD_FROM_CACHE_KEY, false)
ExpoUpdatesAppLoader(
this.manifestUrl!!,
object : AppLoaderCallback {
override fun onOptimisticManifest(optimisticManifest: Manifest) {
Exponent.instance.runOnUiThread { setOptimisticManifest(optimisticManifest) }
}
override fun onManifestCompleted(manifest: Manifest) {
Exponent.instance.runOnUiThread {
try {
val bundleUrl = ExponentUrls.toHttp(manifest.getBundleURL())
setManifest([email protected]!!, manifest, bundleUrl)
} catch (e: JSONException) {
kernel.handleError(e)
}
}
}
override fun onBundleCompleted(localBundlePath: String) {
Exponent.instance.runOnUiThread { setBundle(localBundlePath) }
}
override fun emitEvent(params: JSONObject) {
emitUpdatesEvent(params)
}
override fun updateStatus(status: AppLoaderStatus) {
setLoadingProgressStatusIfEnabled(status)
}
override fun onError(e: Exception) {
Exponent.instance.runOnUiThread { kernel.handleError(e) }
}
},
forceCache
).start(this)
}
kernel.setOptimisticActivity(this, taskId)
}
override fun onResume() {
super.onResume()
currentActivity = this
// Resume home's host if needed.
devMenuManager.maybeResumeHostWithActivity(this)
soLoaderInit()
addNotification()
Analytics.logEventWithManifestUrl(Analytics.AnalyticsEvent.EXPERIENCE_APPEARED, manifestUrl)
}
override fun onWindowFocusChanged(hasFocus: Boolean) {
super.onWindowFocusChanged(hasFocus)
// Check for manifest to avoid calling this when first loading an experience
if (hasFocus && manifest != null) {
runOnUiThread { ExperienceActivityUtils.setNavigationBar(manifest!!, this@ExperienceActivity) }
}
}
private fun soLoaderInit() {
if (detachSdkVersion != null) {
SoLoader.init(this, false)
}
}
open fun shouldCheckOptions() {
if (manifestUrl != null && kernel.hasOptionsForManifestUrl(manifestUrl)) {
handleOptions(kernel.popOptionsForManifestUrl(manifestUrl)!!)
}
}
override fun onPause() {
super.onPause()
if (currentActivity === this) {
currentActivity = null
}
removeNotification()
Analytics.clearTimedEvents()
}
public override fun onSaveInstanceState(savedInstanceState: Bundle) {
savedInstanceState.putString(KernelConstants.MANIFEST_URL_KEY, manifestUrl)
super.onSaveInstanceState(savedInstanceState)
}
override fun onNewIntent(intent: Intent) {
super.onNewIntent(intent)
val uri = intent.data
if (uri != null) {
handleUri(uri.toString())
}
}
fun toggleDevMenu(): Boolean {
if (reactInstanceManager.isNotNull && !isCrashed) {
devMenuManager.toggleInActivity(this)
return true
}
return false
}
/**
* Handles command line command `adb shell input keyevent 82` that toggles the dev menu on the current experience activity.
*/
override fun onKeyUp(keyCode: Int, event: KeyEvent): Boolean {
if (keyCode == KeyEvent.KEYCODE_MENU && reactInstanceManager.isNotNull && !isCrashed) {
devMenuManager.toggleInActivity(this)
return true
}
return super.onKeyUp(keyCode, event)
}
/**
* Closes the dev menu when pressing back button when it is visible on this activity.
*/
override fun onBackPressed() {
if (currentActivity === this && devMenuManager.isShownInActivity(this)) {
devMenuManager.requestToClose(this)
return
}
super.onBackPressed()
}
fun onEventMainThread(event: KernelStartedRunningEvent?) {
AsyncCondition.notify(KERNEL_STARTED_RUNNING_KEY)
}
override fun onDoneLoading() {
Analytics.markEvent(Analytics.TimedEvent.FINISHED_LOADING_REACT_NATIVE)
Analytics.sendTimedEvents(manifestUrl)
}
fun onEvent(event: ExperienceDoneLoadingEvent) {
if (event.activity === this) {
loadingProgressPopupController.hide()
}
if (!Constants.isStandaloneApp()) {
val appLoader = kernel.getAppLoaderForManifestUrl(manifestUrl)
if (appLoader != null && !appLoader.isUpToDate && appLoader.shouldShowAppLoaderStatus) {
AlertDialog.Builder(this@ExperienceActivity)
.setTitle("Using a cached project")
.setMessage("Expo was unable to fetch the latest update to this app. A previously downloaded version has been launched. If you did not intend to use a cached project, check your network connection and reload the app.")
.setPositiveButton("Use cache", null)
.setNegativeButton("Reload") { _, _ ->
kernel.reloadVisibleExperience(
manifestUrl!!, false
)
}
.show()
}
}
}
/*
*
* Experience Loading
*
*/
fun startLoading() {
isLoading = true
showOrReconfigureManagedAppSplashScreen(manifest)
setLoadingProgressStatusIfEnabled()
}
/**
* This method is being called twice:
* - first time for optimistic manifest
* - seconds time for real manifest
*/
protected fun showOrReconfigureManagedAppSplashScreen(manifest: Manifest?) {
if (!shouldCreateLoadingView()) {
return
}
hideLoadingView()
if (managedAppSplashScreenViewProvider == null) {
val config = ManagedAppSplashScreenConfiguration.parseManifest(
manifest!!
)
managedAppSplashScreenViewProvider = ManagedAppSplashScreenViewProvider(config)
val splashScreenView = managedAppSplashScreenViewProvider!!.createSplashScreenView(this)
managedAppSplashScreenViewController = ManagedAppSplashScreenViewController(
this,
getRootViewClass(
manifest
),
splashScreenView
)
SplashScreen.show(this, managedAppSplashScreenViewController!!, true)
} else {
managedAppSplashScreenViewProvider!!.updateSplashScreenViewWithManifest(this, manifest!!)
}
}
fun setLoadingProgressStatusIfEnabled() {
val appLoader = kernel.getAppLoaderForManifestUrl(manifestUrl)
if (appLoader != null) {
setLoadingProgressStatusIfEnabled(appLoader.status)
}
}
fun setLoadingProgressStatusIfEnabled(status: AppLoaderStatus?) {
if (Constants.isStandaloneApp()) {
return
}
if (status == null) {
return
}
val appLoader = kernel.getAppLoaderForManifestUrl(manifestUrl)
if (appLoader != null && appLoader.shouldShowAppLoaderStatus) {
UiThreadUtil.runOnUiThread { loadingProgressPopupController.setLoadingProgressStatus(status) }
} else {
UiThreadUtil.runOnUiThread { loadingProgressPopupController.hide() }
}
}
fun setOptimisticManifest(optimisticManifest: Manifest) {
runOnUiThread {
if (!isInForeground) {
return@runOnUiThread
}
if (!shouldShowLoadingViewWithOptimisticManifest) {
return@runOnUiThread
}
ExperienceActivityUtils.configureStatusBar(optimisticManifest, this@ExperienceActivity)
ExperienceActivityUtils.setNavigationBar(optimisticManifest, this@ExperienceActivity)
ExperienceActivityUtils.setTaskDescription(
exponentManifest,
optimisticManifest,
this@ExperienceActivity
)
showOrReconfigureManagedAppSplashScreen(optimisticManifest)
setLoadingProgressStatusIfEnabled()
}
}
fun setManifest(
manifestUrl: String,
manifest: Manifest,
bundleUrl: String
) {
if (!isInForeground) {
return
}
if (!isLoadExperienceAllowedToRun) {
return
}
// Only want to run once per onCreate. There are some instances with ShellAppActivity where this would be called
// twice otherwise. Turn on "Don't keep activities", trigger a notification, background the app, and then
// press on the notification in a shell app to see this happen.
isLoadExperienceAllowedToRun = false
isReadyForBundle = false
this.manifestUrl = manifestUrl
this.manifest = manifest
exponentSharedPreferences.removeLegacyManifest(this.manifestUrl!!)
// Notifications logic uses this to determine which experience to route a notification to
ExponentDB.saveExperience(ExponentDBObject(this.manifestUrl!!, manifest, bundleUrl))
ExponentNotificationManager(this).maybeCreateNotificationChannelGroup(this.manifest!!)
val task = kernel.getExperienceActivityTask(this.manifestUrl!!)
task.taskId = taskId
task.experienceActivity = WeakReference(this)
task.activityId = activityId
task.bundleUrl = bundleUrl
sdkVersion = manifest.getSDKVersion()
isShellApp = this.manifestUrl == Constants.INITIAL_URL
// Sometime we want to release a new version without adding a new .aar. Use TEMPORARY_ABI_VERSION
// to point to the unversioned code in ReactAndroid.
if (Constants.TEMPORARY_ABI_VERSION != null && Constants.TEMPORARY_ABI_VERSION == sdkVersion) {
sdkVersion = RNObject.UNVERSIONED
}
// In detach/shell, we always use UNVERSIONED as the ABI.
detachSdkVersion = if (Constants.isStandaloneApp()) RNObject.UNVERSIONED else sdkVersion
if (RNObject.UNVERSIONED != sdkVersion) {
var isValidVersion = false
for (version in Constants.SDK_VERSIONS_LIST) {
if (version == sdkVersion) {
isValidVersion = true
break
}
}
if (!isValidVersion) {
KernelProvider.instance.handleError(
sdkVersion + " is not a valid SDK version. Options are " +
TextUtils.join(", ", Constants.SDK_VERSIONS_LIST) + ", " + RNObject.UNVERSIONED + "."
)
return
}
}
soLoaderInit()
try {
experienceKey = ExperienceKey.fromManifest(manifest)
AsyncCondition.notify(KernelConstants.EXPERIENCE_ID_SET_FOR_ACTIVITY_KEY)
} catch (e: JSONException) {
KernelProvider.instance.handleError("No ID found in manifest.")
return
}
isCrashed = false
Analytics.logEventWithManifestUrlSdkVersion(Analytics.AnalyticsEvent.LOAD_EXPERIENCE, manifestUrl, sdkVersion)
ExperienceActivityUtils.updateOrientation(this.manifest!!, this)
ExperienceActivityUtils.updateSoftwareKeyboardLayoutMode(this.manifest!!, this)
ExperienceActivityUtils.overrideUiMode(this.manifest!!, this)
addNotification()
var notificationObject: ExponentNotification? = null
// Activity could be restarted due to Dark Mode change, only pop options if that will not happen
if (kernel.hasOptionsForManifestUrl(manifestUrl)) {
val options = kernel.popOptionsForManifestUrl(manifestUrl)
// if the kernel has an intent for our manifest url, that's the intent that triggered
// the loading of this experience.
if (options!!.uri != null) {
intentUri = options.uri
}
notificationObject = options.notificationObject
}
BranchManager.handleLink(this, intentUri, detachSdkVersion)
runOnUiThread {
if (!isInForeground) {
return@runOnUiThread
}
if (reactInstanceManager.isNotNull) {
reactInstanceManager.onHostDestroy()
reactInstanceManager.assign(null)
}
reactRootView = RNObject("host.exp.exponent.ReactUnthemedRootView")
reactRootView.loadVersion(detachSdkVersion!!).construct(this@ExperienceActivity)
setReactRootView((reactRootView.get() as View))
if (isDebugModeEnabled) {
notification = notificationObject
jsBundlePath = ""
startReactInstance()
} else {
tempNotification = notificationObject
isReadyForBundle = true
AsyncCondition.notify(READY_FOR_BUNDLE)
}
ExperienceActivityUtils.configureStatusBar(manifest, this@ExperienceActivity)
ExperienceActivityUtils.setNavigationBar(manifest, this@ExperienceActivity)
ExperienceActivityUtils.setTaskDescription(
exponentManifest,
manifest,
this@ExperienceActivity
)
showOrReconfigureManagedAppSplashScreen(manifest)
setLoadingProgressStatusIfEnabled()
}
}
fun setBundle(localBundlePath: String) {
// by this point, setManifest should have also been called, so prevent
// setOptimisticManifest from showing a rogue splash screen
shouldShowLoadingViewWithOptimisticManifest = false
if (!isDebugModeEnabled) {
val finalIsReadyForBundle = isReadyForBundle
AsyncCondition.wait(
READY_FOR_BUNDLE,
object : AsyncConditionListener {
override fun isReady(): Boolean {
return finalIsReadyForBundle
}
override fun execute() {
notification = tempNotification
tempNotification = null
jsBundlePath = localBundlePath
startReactInstance()
AsyncCondition.remove(READY_FOR_BUNDLE)
}
}
)
}
}
fun onEventMainThread(event: ReceivedNotificationEvent) {
// TODO(wschurman): investigate removal, this probably is no longer used
if (experienceKey != null && event.experienceScopeKey == experienceKey!!.scopeKey) {
try {
val rctDeviceEventEmitter =
RNObject("com.facebook.react.modules.core.DeviceEventManagerModule\$RCTDeviceEventEmitter")
rctDeviceEventEmitter.loadVersion(detachSdkVersion!!)
reactInstanceManager.callRecursive("getCurrentReactContext")!!
.callRecursive("getJSModule", rctDeviceEventEmitter.rnClass())!!
.call("emit", "Exponent.notification", event.toWriteableMap(detachSdkVersion, "received"))
} catch (e: Throwable) {
EXL.e(TAG, e)
}
}
}
fun handleOptions(options: ExperienceOptions) {
try {
val uri = options.uri
if (uri !== null) {
handleUri(uri)
val rctDeviceEventEmitter =
RNObject("com.facebook.react.modules.core.DeviceEventManagerModule\$RCTDeviceEventEmitter")
rctDeviceEventEmitter.loadVersion(detachSdkVersion!!)
reactInstanceManager.callRecursive("getCurrentReactContext")!!
.callRecursive("getJSModule", rctDeviceEventEmitter.rnClass())!!
.call("emit", "Exponent.openUri", uri)
BranchManager.handleLink(this, uri, detachSdkVersion)
}
if ((options.notification != null || options.notificationObject != null) && detachSdkVersion != null) {
val rctDeviceEventEmitter =
RNObject("com.facebook.react.modules.core.DeviceEventManagerModule\$RCTDeviceEventEmitter")
rctDeviceEventEmitter.loadVersion(detachSdkVersion!!)
reactInstanceManager.callRecursive("getCurrentReactContext")!!
.callRecursive("getJSModule", rctDeviceEventEmitter.rnClass())!!
.call(
"emit",
"Exponent.notification",
options.notificationObject!!.toWriteableMap(detachSdkVersion, "selected")
)
}
} catch (e: Throwable) {
EXL.e(TAG, e)
}
}
private fun handleUri(uri: String) {
// Emits a "url" event to the Linking event emitter
val intent = Intent(Intent.ACTION_VIEW, Uri.parse(uri))
super.onNewIntent(intent)
}
fun emitUpdatesEvent(params: JSONObject) {
KernelProvider.instance.addEventForExperience(
manifestUrl!!,
KernelConstants.ExperienceEvent(ExpoUpdatesAppLoader.UPDATES_EVENT_NAME, params.toString())
)
}
override val isDebugModeEnabled: Boolean
get() = manifest?.isDevelopmentMode() ?: false
override fun startReactInstance() {
Exponent.instance
.testPackagerStatus(
isDebugModeEnabled, manifest!!,
object : Exponent.PackagerStatusCallback {
override fun onSuccess() {
reactInstanceManager = startReactInstance(
this@ExperienceActivity,
intentUri,
detachSdkVersion,
notification,
isShellApp,
reactPackages(),
expoPackages(),
devBundleDownloadProgressListener
)
}
override fun onFailure(errorMessage: String) {
KernelProvider.instance.handleError(errorMessage)
}
}
)
}
override fun handleUnreadNotifications(unreadNotifications: JSONArray) {
PushNotificationHelper.instance.removeNotifications(this, unreadNotifications)
}
/*
*
* Notification
*
*/
private fun addNotification() {
if (isShellApp || manifestUrl == null || manifest == null) {
return
}
val name = manifest!!.getName() ?: return
val remoteViews = RemoteViews(packageName, R.layout.notification)
remoteViews.setCharSequence(R.id.home_text_button, "setText", name)
// Home
val homeIntent = Intent(this, LauncherActivity::class.java)
remoteViews.setOnClickPendingIntent(
R.id.home_image_button,
PendingIntent.getActivity(
this, 0,
homeIntent, 0
)
)
// Reload
remoteViews.setOnClickPendingIntent(
R.id.reload_button,
PendingIntent.getService(
this, 0,
ExponentIntentService.getActionReloadExperience(this, manifestUrl!!), PendingIntent.FLAG_UPDATE_CURRENT
)
)
notificationRemoteViews = remoteViews
// Build the actual notification
val notificationManager = getSystemService(NOTIFICATION_SERVICE) as NotificationManager
notificationManager.cancel(PERSISTENT_EXPONENT_NOTIFICATION_ID)
ExponentNotificationManager(this).maybeCreateExpoPersistentNotificationChannel()
notificationBuilder =
NotificationCompat.Builder(this, NotificationConstants.NOTIFICATION_EXPERIENCE_CHANNEL_ID)
.setContent(notificationRemoteViews)
.setSmallIcon(R.drawable.notification_icon)
.setShowWhen(false)
.setOngoing(true)
.setPriority(Notification.PRIORITY_MAX)
.setColor(ContextCompat.getColor(this, R.color.colorPrimary))
notificationManager.notify(PERSISTENT_EXPONENT_NOTIFICATION_ID, notificationBuilder!!.build())
}
fun removeNotification() {
notificationRemoteViews = null
notificationBuilder = null
removeNotification(this)
}
fun onNotificationAction() {
dismissNuxViewIfVisible(true)
}
/**
* @param isFromNotification true if this is the result of the user taking an
* action in the notification view.
*/
fun dismissNuxViewIfVisible(isFromNotification: Boolean) {
if (nuxOverlayView == null) {
return
}
runOnUiThread {
val fadeOut: Animation = AlphaAnimation(1f, 0f).apply {
interpolator = AccelerateInterpolator()
duration = 500
setAnimationListener(object : Animation.AnimationListener {
override fun onAnimationEnd(animation: Animation) {
if (nuxOverlayView!!.parent != null) {
(nuxOverlayView!!.parent as ViewGroup).removeView(nuxOverlayView)
}
nuxOverlayView = null
val eventProperties = JSONObject()
try {
eventProperties.put("IS_FROM_NOTIFICATION", isFromNotification)
} catch (e: JSONException) {
EXL.e(TAG, e.message)
}
Analytics.logEvent(Analytics.AnalyticsEvent.NUX_EXPERIENCE_OVERLAY_DISMISSED, eventProperties)
}
override fun onAnimationRepeat(animation: Animation) {}
override fun onAnimationStart(animation: Animation) {}
})
}
nuxOverlayView!!.startAnimation(fadeOut)
}
}
/*
*
* Errors
*
*/
override fun onError(intent: Intent) {
if (manifestUrl != null) {
intent.putExtra(ErrorActivity.MANIFEST_URL_KEY, manifestUrl)
}
}
companion object {
private val TAG = ExperienceActivity::class.java.simpleName
private const val KERNEL_STARTED_RUNNING_KEY = "experienceActivityKernelDidLoad"
const val PERSISTENT_EXPONENT_NOTIFICATION_ID = 10101
private const val READY_FOR_BUNDLE = "readyForBundle"
/**
* Returns the currently active ExperienceActivity, that is the one that is currently being used by the user.
*/
var currentActivity: ExperienceActivity? = null
private set
@JvmStatic fun removeNotification(context: Context) {
val notificationManager =
context.getSystemService(NOTIFICATION_SERVICE) as NotificationManager
notificationManager.cancel(PERSISTENT_EXPONENT_NOTIFICATION_ID)
}
}
}
| bsd-3-clause | 7b5ef76d0db81fddb11281faafefabc5 | 33.252218 | 228 | 0.706716 | 5.044801 | false | false | false | false |
cauchymop/goblob | goblob/src/main/java/com/cauchymop/goblob/ui/AndroidGameRepository.kt | 1 | 15015 | package com.cauchymop.goblob.ui
import android.app.Activity
import android.content.Intent
import android.content.SharedPreferences
import android.os.Bundle
import android.util.Log
import com.cauchymop.goblob.model.*
import com.cauchymop.goblob.proto.PlayGameData
import com.cauchymop.goblob.proto.PlayGameData.GameData
import com.cauchymop.goblob.proto.PlayGameData.GameData.Phase
import com.cauchymop.goblob.proto.PlayGameData.GameList
import com.crashlytics.android.Crashlytics
import com.google.android.gms.games.Games
import com.google.android.gms.games.TurnBasedMultiplayerClient
import com.google.android.gms.games.multiplayer.Multiplayer
import com.google.android.gms.games.multiplayer.realtime.RoomConfig
import com.google.android.gms.games.multiplayer.turnbased.LoadMatchesResponse
import com.google.android.gms.games.multiplayer.turnbased.TurnBasedMatch
import com.google.android.gms.games.multiplayer.turnbased.TurnBasedMatchConfig
import com.google.android.gms.games.multiplayer.turnbased.TurnBasedMatchUpdateCallback
import com.google.common.base.Strings
import com.google.common.collect.ImmutableMap
import com.google.protobuf.InvalidProtocolBufferException
import com.google.protobuf.TextFormat
import dagger.Lazy
import java.util.*
import javax.inject.Inject
import javax.inject.Named
import javax.inject.Provider
import javax.inject.Singleton
/**
* Class to persist games.
*/
private const val GAME_DATA = "gameData"
private const val GAMES = "games"
private const val TAG = "AndroidGameRepository"
private const val IGNORED_VALUE = ""
@Singleton
class AndroidGameRepository @Inject
constructor(private val prefs: SharedPreferences, gameDatas: GameDatas,
private val googleAccountManager: GoogleAccountManager,
private val turnBasedClientProvider: Provider<TurnBasedMultiplayerClient>,
private val avatarManager: AvatarManager, analytics: Analytics,
@Named("PlayerOneDefaultName") playerOneDefaultName: Lazy<String>,
@Named("PlayerTwoDefaultName") playerTwoDefaultName: String) : GameRepository(analytics, playerOneDefaultName, playerTwoDefaultName, gameDatas, gameCache = loadGameCache(prefs)) {
init {
loadLegacyLocalGame()
fireGameListChanged()
googleAccountManager.addAccountStateListener(object : AccountStateListener {
override fun accountStateChanged(isSignInComplete: Boolean) {
if (isSignInComplete) {
initTurnBasedUpdateListeners()
}
}
})
}
private fun initTurnBasedUpdateListeners() {
val turnBasedClient = turnBasedClientProvider.get()
turnBasedClient.registerTurnBasedMatchUpdateCallback(object : TurnBasedMatchUpdateCallback() {
override fun onTurnBasedMatchReceived(turnBasedMatch: TurnBasedMatch) {
Crashlytics.log(Log.DEBUG, TAG, "onTurnBasedMatchReceived")
val gameData = getGameData(turnBasedMatch)
if (gameData != null) {
if (saveToCache(gameData)) {
forceCacheRefresh()
}
}
}
override fun onTurnBasedMatchRemoved(matchId: String) {
Crashlytics.log(Log.DEBUG, TAG, "onTurnBasedMatchRemoved: $matchId")
removeFromCache(matchId)
}
})
}
override fun forceCacheRefresh() {
Crashlytics.log(Log.DEBUG, TAG, "forceCacheRefresh")
persistCache()
fireGameListChanged()
}
private fun persistCache() {
val editor = prefs.edit()
editor.putString(GAMES, TextFormat.printToString(gameCache))
editor.apply()
}
override fun publishRemoteGameState(gameData: GameData): Boolean {
if (googleAccountManager.signInComplete) {
Crashlytics.log(Log.DEBUG, TAG, "publishRemoteGameState: $gameData")
val turnParticipantId = gameDatas.getCurrentPlayer(gameData).id
val gameDataBytes = gameData.toByteArray()
Crashlytics.log(Log.DEBUG, TAG, "takeTurn $turnParticipantId")
val turnBasedClient = turnBasedClientProvider.get()
turnBasedClient.takeTurn(gameData.matchId, gameDataBytes, turnParticipantId)
if (gameData.phase == Phase.FINISHED) {
turnBasedClient.finishMatch(gameData.matchId)
fireGameSelected(gameData)
}
return true
} else {
gameCache.putUnpublished(gameData.matchId, IGNORED_VALUE)
return false
}
}
override fun log(message: String) {
Crashlytics.log(Log.DEBUG, TAG, message)
}
private fun loadLegacyLocalGame() {
val gameDataString = prefs.getString(GAME_DATA, null) ?: return
log("loadLegacyLocalGame")
val gameDataBuilder = GameData.newBuilder()
try {
TextFormat.merge(gameDataString, gameDataBuilder)
} catch (e: TextFormat.ParseException) {
Crashlytics.log(Log.ERROR, TAG, "Error parsing local GameData: ${e.message}")
}
val localGame = gameDataBuilder.build()
if (saveToCache(localGame)) {
forceCacheRefresh()
}
prefs.edit().remove(GAME_DATA).apply()
}
fun refreshRemoteGameListFromServer() {
Crashlytics.log(Log.DEBUG, TAG, "refreshRemoteGameListFromServer - currentMatchId = $currentMatchId")
val requestId = System.currentTimeMillis()
val turnBasedClient = turnBasedClientProvider.get()
val matchListResult = turnBasedClient.loadMatchesByStatus(Multiplayer.SORT_ORDER_SOCIAL_AGGREGATION,
intArrayOf(TurnBasedMatch.MATCH_TURN_STATUS_MY_TURN, TurnBasedMatch.MATCH_TURN_STATUS_THEIR_TURN, TurnBasedMatch.MATCH_TURN_STATUS_COMPLETE))
matchListResult.addOnCompleteListener { task ->
task.result?.get()?.let { matchResponseCallback(requestId, it) }
}
}
private fun matchResponseCallback(requestId: Long, loadMatchesResponse: LoadMatchesResponse) {
Crashlytics.log(Log.DEBUG, TAG, String.format("matchResult: requestId = %d, latency = %d ms", requestId, System.currentTimeMillis() - requestId))
val allMatches = with(loadMatchesResponse) { myTurnMatches.asSequence() + theirTurnMatches.asSequence() + completedMatches.asSequence() }
val games = HashSet<GameData>()
for (match in allMatches) {
updateAvatars(match)
val gameData = getGameData(match)
if (gameData != null) {
games.add(gameData)
}
}
val removedMatchIds = clearRemoteGamesIfAbsent(games)
Crashlytics.log(Log.DEBUG, TAG, "removedMatchIds: $removedMatchIds")
val selectedIsGone = removedMatchIds.contains(currentMatchId)
Crashlytics.log(Log.DEBUG, TAG, "selectedIsGone is $selectedIsGone")
val changedCount = removedMatchIds.size + games.filter { saveToCache(it) }.count()
Crashlytics.log(Log.DEBUG, TAG, "changedCount is $changedCount")
if (changedCount > 0) {
forceCacheRefresh()
}
// Select invitation if one has arrived
pendingMatchId?.let {
pendingMatchId = null
selectGame(it)
}
if (selectedIsGone) {
// selected game was removed, we select new game instead
selectGame(NO_MATCH_ID)
}
loadMatchesResponse.release()
}
private fun clearRemoteGamesIfAbsent(games: Set<GameData>): List<String> {
val keysToRemove = gameCache.gamesMap.filter { gameDatas.isRemoteGame(it.value) && !games.contains(it.value) }.map { it.key }
keysToRemove.forEach { gameCache.removeGames(it) }
return keysToRemove
}
private fun updateAvatars(match: TurnBasedMatch) {
for (participant in match.participants) {
val player = participant.player
avatarManager.setAvatarUri(player.displayName, player.iconImageUri)
}
}
private fun getGameData(turnBasedMatch: TurnBasedMatch): GameData? {
val data = turnBasedMatch.data
?: // When a crash happens during game creation, the TurnBasedMatch contains a null game
// that can't be recovered, and would prevent starting the app.
return null
handleMatchStatusComplete(turnBasedMatch)
try {
var gameData: GameData = GameData.parseFrom(data)
gameData = handleBackwardCompatibility(turnBasedMatch, gameData)
return gameData
} catch (exception: InvalidProtocolBufferException) {
throw RuntimeException(exception)
}
}
private fun handleMatchStatusComplete(turnBasedMatch: TurnBasedMatch) {
val myTurn = turnBasedMatch.turnStatus == TurnBasedMatch.MATCH_TURN_STATUS_MY_TURN
if (myTurn && turnBasedMatch.status == TurnBasedMatch.MATCH_STATUS_COMPLETE) {
val turnBasedClient = turnBasedClientProvider.get()
turnBasedClient.finishMatch(turnBasedMatch.matchId)
}
}
private fun createNewGameData(turnBasedMatch: TurnBasedMatch): GameData {
val myId = getMyId(turnBasedMatch)
val opponentId = getOpponentId(turnBasedMatch)
val blackPlayer = createGoPlayer(turnBasedMatch, myId, true)
val whitePlayer = createGoPlayer(turnBasedMatch, opponentId, false)
val gameData = gameDatas.createNewGameData(turnBasedMatch.matchId,
PlayGameData.GameType.REMOTE, blackPlayer, whitePlayer)
analytics.gameCreated(gameData)
commitGameChanges(gameData)
return gameData
}
@Suppress("DEPRECATION")
private fun handleBackwardCompatibility(turnBasedMatch: TurnBasedMatch,
initialGameData: GameData): GameData {
val gameData = initialGameData.toBuilder()
// No players
if (!gameData.gameConfiguration.hasBlack() || !gameData.gameConfiguration.hasWhite()) {
val myId = getMyId(turnBasedMatch)
val opponentId = getOpponentId(turnBasedMatch)
val goPlayers = ImmutableMap.of(
myId, createGoPlayer(turnBasedMatch, myId, true),
opponentId, createGoPlayer(turnBasedMatch, opponentId, false))
val gameConfiguration = gameData.gameConfiguration
val blackPlayer = goPlayers[gameConfiguration.blackId]
val whitePlayer = goPlayers[gameConfiguration.whiteId]
gameData.gameConfigurationBuilder
.setBlack(blackPlayer)
.setWhite(whitePlayer)
}
// No match Id
if (Strings.isNullOrEmpty(gameData.matchId)) {
gameData.matchId = turnBasedMatch.matchId
}
// No phase (version < 2)
if (gameData.phase == Phase.UNKNOWN) {
gameData.phase = if (gameData.hasMatchEndStatus()) {
if (gameData.matchEndStatus.gameFinished) {
Phase.FINISHED
} else {
Phase.DEAD_STONE_MARKING
}
} else {
Phase.IN_GAME
}
}
// No turn (version < 2)
if (!gameData.hasTurn()) {
if (gameData.hasMatchEndStatus()) {
gameData.turn = gameData.matchEndStatus.turn
} else {
val currentTurn = gameDatas.computeInGameTurn(gameData.gameConfiguration, gameData.moveCount)
gameData.turn = currentTurn
}
}
return fillLocalStates(turnBasedMatch, gameData).build()
}
private fun fillLocalStates(turnBasedMatch: TurnBasedMatch, gameData: GameData.Builder): GameData.Builder {
val isMyTurn = turnBasedMatch.turnStatus == TurnBasedMatch.MATCH_TURN_STATUS_MY_TURN
val turnIsBlack = gameData.turn == PlayGameData.Color.BLACK
val iAmBlack = isMyTurn && turnIsBlack || !isMyTurn && !turnIsBlack
val gameConfiguration = gameData.gameConfigurationBuilder
val blackPlayer = gameConfiguration.blackBuilder
val whitePlayer = gameConfiguration.whiteBuilder
blackPlayer.isLocal = iAmBlack
whitePlayer.isLocal = !iAmBlack
Crashlytics.log(Log.DEBUG, TAG, String.format("black: %s", blackPlayer))
Crashlytics.log(Log.DEBUG, TAG, String.format("white %s", whitePlayer))
return gameData
}
private fun getOpponentId(turnBasedMatch: TurnBasedMatch): String {
val myId = getMyId(turnBasedMatch)
for (participantId in turnBasedMatch.participantIds) {
if (participantId != myId) {
return participantId
}
}
throw RuntimeException("Our TurnBasedMatch should contain 2 players!")
}
private fun getMyId(turnBasedMatch: TurnBasedMatch) =
turnBasedMatch.getParticipantId(googleAccountManager.currentPlayerId)
private fun createGoPlayer(match: TurnBasedMatch, participantId: String,
isLocal: Boolean): PlayGameData.GoPlayer {
val goPlayer: PlayGameData.GoPlayer
val player = match.getParticipant(participantId).player
goPlayer = gameDatas.createGamePlayer(participantId, player.displayName, isLocal)
avatarManager.setAvatarUri(player.displayName, player.iconImageUri)
return goPlayer
}
fun handlePlayersSelected(intent: Intent) {
Crashlytics.log(Log.DEBUG, TAG, "handlePlayersSelected")
// get the invitee list
val invitees = intent.getStringArrayListExtra(Games.EXTRA_PLAYER_IDS)
Crashlytics.log(Log.DEBUG, TAG, "Invitees: $invitees")
// get the automatch criteria
var autoMatchCriteria: Bundle? = null
val minAutoMatchPlayers = intent.getIntExtra(Multiplayer.EXTRA_MIN_AUTOMATCH_PLAYERS, 0)
val maxAutoMatchPlayers = intent.getIntExtra(Multiplayer.EXTRA_MAX_AUTOMATCH_PLAYERS, 0)
if (minAutoMatchPlayers > 0 || maxAutoMatchPlayers > 0) {
autoMatchCriteria = RoomConfig.createAutoMatchCriteria(
minAutoMatchPlayers, maxAutoMatchPlayers, 0)
Crashlytics.log(Log.DEBUG, TAG, "Automatch criteria: " + autoMatchCriteria!!)
}
// create game
val turnBasedMatchConfig = TurnBasedMatchConfig.builder()
.addInvitedPlayers(invitees)
.setVariant(TurnBasedMatch.MATCH_VARIANT_DEFAULT)
.setAutoMatchCriteria(autoMatchCriteria).build()
// kick the match off
val turnBasedClient = turnBasedClientProvider.get()
turnBasedClient.createMatch(turnBasedMatchConfig).addOnCompleteListener { initiateMatchResult ->
Crashlytics.log(Log.DEBUG, TAG, "InitiateMatchResult $initiateMatchResult")
if (!initiateMatchResult.isSuccessful) {
return@addOnCompleteListener
}
initiateMatchResult.result?.let {
createNewGameData(it)
Crashlytics.log(Log.DEBUG, TAG, "Game created...")
selectGame(it.matchId)
}
}
}
fun handleCheckMatchesResult(responseCode: Int, intent: Intent?) {
Crashlytics.log(Log.DEBUG, TAG, "handleCheckMatchesResult")
// Refresh is done in all cases as games can be dismissed for the Check Matches Screen if we then
// do not select a game and press back
refreshRemoteGameListFromServer()
if (responseCode == Activity.RESULT_OK && intent != null) {
val match = intent.getParcelableExtra<TurnBasedMatch>(Multiplayer.EXTRA_TURN_BASED_MATCH)
selectGame(match.matchId)
}
}
}
private fun loadGameCache(sharedPreferences: SharedPreferences): GameList.Builder {
Crashlytics.log(Log.DEBUG, TAG, "loadGameList")
val gameListString = sharedPreferences.getString(GAMES, "")
val gameListBuilder = GameList.newBuilder()
try {
TextFormat.merge(gameListString, gameListBuilder)
} catch (e: TextFormat.ParseException) {
Crashlytics.log(Log.ERROR, TAG, "Error parsing local GameList: " + e.message)
}
Crashlytics.log(Log.DEBUG, TAG, "loadGameList: " + gameListBuilder.gamesCount + " games loaded.")
return gameListBuilder
}
| apache-2.0 | b378b2d388711d8f69eff00432296886 | 37.5 | 191 | 0.728938 | 4.205882 | false | false | false | false |
charleskorn/batect | app/src/main/kotlin/batect/execution/CancellationContext.kt | 1 | 1365 | /*
Copyright 2017-2020 Charles Korn.
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 batect.execution
import java.util.concurrent.ConcurrentLinkedQueue
typealias CancellationCallback = () -> Unit
class CancellationContext {
private var cancelled = false
private val callbacks = ConcurrentLinkedQueue<CancellationCallback>()
fun addCancellationCallback(callback: CancellationCallback): AutoCloseable {
callbacks.add(callback)
if (cancelled) {
cancel()
return AutoCloseable { }
}
return AutoCloseable { callbacks.remove(callback) }
}
fun cancel() {
cancelled = true
while (true) {
val callback = callbacks.poll()
if (callback == null) {
return
}
callback.invoke()
}
}
}
| apache-2.0 | c75a7beb3b6a5110c7064152617dc9c9 | 25.764706 | 80 | 0.663736 | 5.11236 | false | false | false | false |
androidx/androidx | compose/foundation/foundation/src/test/kotlin/androidx/compose/foundation/text/selection/SelectionTest.kt | 3 | 6979 | /*
* 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.foundation.text.selection
import androidx.compose.ui.text.TextRange
import androidx.compose.ui.text.style.ResolvedTextDirection
import com.google.common.truth.Truth.assertThat
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.JUnit4
@RunWith(JUnit4::class)
class SelectionTest {
@Test
fun anchorInfo_constructor() {
val direction = ResolvedTextDirection.Ltr
val offset = 0
val anchor = Selection.AnchorInfo(
direction = direction,
offset = offset,
selectableId = 1L
)
assertThat(anchor.direction).isEqualTo(direction)
assertThat(anchor.offset).isEqualTo(offset)
assertThat(anchor.selectableId).isEqualTo(1L)
}
@Test
fun selection_constructor() {
val startOffset = 0
val endOffset = 6
val startAnchor = Selection.AnchorInfo(
direction = ResolvedTextDirection.Ltr,
offset = startOffset,
selectableId = 1L
)
val endAnchor = Selection.AnchorInfo(
direction = ResolvedTextDirection.Ltr,
offset = endOffset,
selectableId = 1L
)
val handleCrossed = false
val selection = Selection(
start = startAnchor,
end = endAnchor,
handlesCrossed = handleCrossed
)
assertThat(selection.start).isEqualTo(startAnchor)
assertThat(selection.end).isEqualTo(endAnchor)
assertThat(selection.handlesCrossed).isEqualTo(handleCrossed)
}
@Test
fun selection_merge_handles_not_cross() {
val startOffset1 = 9
val endOffset1 = 20
val selectableKey1 = 1L
val startAnchor1 = Selection.AnchorInfo(
direction = ResolvedTextDirection.Ltr,
offset = startOffset1,
selectableId = selectableKey1
)
val endAnchor1 = Selection.AnchorInfo(
direction = ResolvedTextDirection.Ltr,
offset = endOffset1,
selectableId = selectableKey1
)
val selection1 = Selection(
start = startAnchor1,
end = endAnchor1,
handlesCrossed = false
)
val startOffset2 = 0
val endOffset2 = 30
val selectableKey2 = 2L
val startAnchor2 = Selection.AnchorInfo(
direction = ResolvedTextDirection.Ltr,
offset = startOffset2,
selectableId = selectableKey2
)
val endAnchor2 = Selection.AnchorInfo(
direction = ResolvedTextDirection.Ltr,
offset = endOffset2,
selectableId = selectableKey2
)
val selection2 = Selection(
start = startAnchor2,
end = endAnchor2,
handlesCrossed = false
)
val selection = selection1.merge(selection2)
assertThat(selection.start.offset).isEqualTo(startOffset1)
assertThat(selection.end.offset).isEqualTo(endOffset2)
assertThat(selection.start.selectableId).isEqualTo(selectableKey1)
assertThat(selection.end.selectableId).isEqualTo(selectableKey2)
assertThat(selection.handlesCrossed).isFalse()
}
@Test
fun selection_merge_handles_cross() {
val startOffset1 = 20
val endOffset1 = 9
val selectableKey1 = 1L
val startAnchor1 = Selection.AnchorInfo(
direction = ResolvedTextDirection.Ltr,
offset = startOffset1,
selectableId = selectableKey1
)
val endAnchor1 = Selection.AnchorInfo(
direction = ResolvedTextDirection.Ltr,
offset = endOffset1,
selectableId = selectableKey1
)
val selection1 = Selection(
start = startAnchor1,
end = endAnchor1,
handlesCrossed = true
)
val startOffset2 = 30
val endOffset2 = 0
val selectableKey2 = 2L
val startAnchor2 = Selection.AnchorInfo(
direction = ResolvedTextDirection.Ltr,
offset = startOffset2,
selectableId = selectableKey2
)
val endAnchor2 = Selection.AnchorInfo(
direction = ResolvedTextDirection.Ltr,
offset = endOffset2,
selectableId = selectableKey2
)
val selection2 = Selection(
start = startAnchor2,
end = endAnchor2,
handlesCrossed = true
)
val selection = selection1.merge(selection2)
assertThat(selection.start.offset).isEqualTo(startOffset2)
assertThat(selection.end.offset).isEqualTo(endOffset1)
assertThat(selection.start.selectableId).isEqualTo(selectableKey2)
assertThat(selection.end.selectableId).isEqualTo(selectableKey1)
assertThat(selection.handlesCrossed).isTrue()
}
@Test
fun selection_toTextRange_handles_not_cross() {
val startOffset = 0
val endOffset = 6
val startAnchor = Selection.AnchorInfo(
direction = ResolvedTextDirection.Ltr,
offset = startOffset,
selectableId = 1L
)
val endAnchor = Selection.AnchorInfo(
direction = ResolvedTextDirection.Ltr,
offset = endOffset,
selectableId = 1L
)
val selection = Selection(
start = startAnchor,
end = endAnchor,
handlesCrossed = false
)
val textRange = selection.toTextRange()
assertThat(textRange).isEqualTo(TextRange(startOffset, endOffset))
}
@Test
fun selection_toTextRange_handles_cross() {
val startOffset = 6
val endOffset = 0
val startAnchor = Selection.AnchorInfo(
direction = ResolvedTextDirection.Ltr,
offset = startOffset,
selectableId = 1L
)
val endAnchor = Selection.AnchorInfo(
direction = ResolvedTextDirection.Ltr,
offset = endOffset,
selectableId = 1L
)
val selection = Selection(
start = startAnchor,
end = endAnchor,
handlesCrossed = false
)
val textRange = selection.toTextRange()
assertThat(textRange).isEqualTo(TextRange(startOffset, endOffset))
}
}
| apache-2.0 | f13ec3dc4dac34fb2dfbcbcdb84d74be | 31.310185 | 75 | 0.619 | 4.939137 | false | false | false | false |
percolate/percolate-java-sdk | auth/src/test/java/com/percolate/sdk/auth/AuthParamCreatorTest.kt | 1 | 1784 | package com.percolate.sdk.auth
import net.iharder.Base64
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNotNull
import org.junit.Before
import org.junit.Test
/**
* TODO
*/
class AuthParamCreatorTest {
private var authParamCreator: AuthParamCreator? = null
private var authData: AuthData? = null
@Before
fun setUp() {
authData = AuthData(CLIENT_ID, CLIENT_SECRET).apply {
username = USERNAME
password = PASSWORD
twoFactorAuthCode = TWO_FACTOR_CODE
ssoPayload = SSO_PAYLOAD
}
authParamCreator = AuthParamCreator(authData)
}
@Test
@Throws(Exception::class)
fun authData() {
val data = authParamCreator!!.authData()
with(data) {
assertEquals(USERNAME, email)
assertEquals(PASSWORD, password)
assertEquals(TWO_FACTOR_CODE, twoFactorAuthCode)
assertEquals(SSO_PAYLOAD, ssoPayload)
assertEquals(USERNAME, email)
assertEquals("token", type)
assertNotNull(ext)
assertEquals(ext.clientId, CLIENT_ID)
}
}
@Test
@Throws(Exception::class)
fun tokenParams() {
val data = authParamCreator!!.tokenParams();
val expected = "Basic " + Base64.encodeBytes(
(CLIENT_ID + ":" + CLIENT_SECRET).toByteArray()
);
assertEquals(expected, data.tokenAuthHeader())
}
companion object {
private val CLIENT_ID = "client:123"
private val CLIENT_SECRET = "12345abcde"
private val USERNAME = "[email protected]"
private val PASSWORD = "password"
private val TWO_FACTOR_CODE = "123456"
private val SSO_PAYLOAD = "{\"data\":\"payload\"}"
}
}
| bsd-3-clause | af3e9d191aff3dedbea1c7fa3b322e9e | 27.31746 | 63 | 0.61435 | 4.394089 | false | true | false | false |
klazuka/intellij-elm | src/main/kotlin/org/elm/lang/core/psi/elements/ElmInfixDeclaration.kt | 1 | 1868 | package org.elm.lang.core.psi.elements
import com.intellij.lang.ASTNode
import com.intellij.psi.PsiElement
import com.intellij.psi.stubs.IStubElementType
import org.elm.lang.core.psi.*
import org.elm.lang.core.stubs.ElmInfixDeclarationStub
/**
* A top-level declaration that describes the associativity and the precedence
* of a binary operator.
*
* For example, `infix right 5 (++) = append` means that the operator `++` has right associativity
* at precedence level of 5.
*
* As of Elm 0.19, these are now restricted to packages owned by elm-lang (and elm-explorations?)
*/
class ElmInfixDeclaration : ElmStubbedNamedElementImpl<ElmInfixDeclarationStub>, ElmExposableTag {
constructor(node: ASTNode) :
super(node, IdentifierCase.OPERATOR)
constructor(stub: ElmInfixDeclarationStub, stubType: IStubElementType<*, *>) :
super(stub, stubType, IdentifierCase.OPERATOR)
val operatorIdentifier: PsiElement
get() = findNotNullChildByType(ElmTypes.OPERATOR_IDENTIFIER)
val precedenceElement: PsiElement
get() = findNotNullChildByType(ElmTypes.NUMBER_LITERAL)
val precedence: Int?
get() = stub?.precedence ?: precedenceElement.text.toIntOrNull()
val associativityElement: PsiElement
get() = findNotNullChildByType(ElmTypes.LOWER_CASE_IDENTIFIER)
val associativity: OperatorAssociativity
get() = when (stub?.associativity ?: associativityElement.text) {
"left" -> OperatorAssociativity.LEFT
"right" -> OperatorAssociativity.RIGHT
else -> OperatorAssociativity.NON
}
/**
* A ref to the function which implements the infix operator.
*
* This will be non-null in a well-formed program.
*/
val funcRef: ElmInfixFuncRef?
get() = stubDirectChildrenOfType<ElmInfixFuncRef>().singleOrNull()
}
| mit | ebe35da3c1cf14145eb157b058e5833f | 34.245283 | 98 | 0.713062 | 4.344186 | false | false | false | false |
InfiniteSoul/ProxerAndroid | src/main/kotlin/me/proxer/app/util/compat/MenuPopupCompat.kt | 2 | 711 | package me.proxer.app.util.compat
import android.annotation.SuppressLint
import android.content.Context
import android.view.Menu
import android.view.View
import androidx.appcompat.view.menu.MenuBuilder
import androidx.appcompat.view.menu.MenuPopupHelper
/**
* @author Ruben Gees
*/
class MenuPopupCompat(private val context: Context, private val menu: Menu, private val anchorView: View) {
private var forceShowIcon: Boolean = false
fun forceShowIcon() = this.apply { forceShowIcon = true }
@SuppressLint("RestrictedApi")
fun show(x: Int = 0, y: Int = 0) = MenuPopupHelper(context, menu as MenuBuilder, anchorView)
.apply { setForceShowIcon(forceShowIcon) }
.show(x, y)
}
| gpl-3.0 | 90db7fa7d0c045f62900a631d2863e91 | 29.913043 | 107 | 0.744023 | 3.822581 | false | false | false | false |
anlun/haskell-idea-plugin | plugin/src/org/jetbrains/haskell/external/ghcfs/RamVirtualFileSystem.kt | 1 | 3635 | package org.jetbrains.haskell.external.ghcfs
import com.intellij.openapi.vfs.newvfs.NewVirtualFileSystem
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.openapi.util.io.FileAttributes
import java.io.OutputStream
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.vfs.LocalFileSystem
/**
* Created by atsky on 09/05/14.
*/
public class RamVirtualFileSystem() : NewVirtualFileSystem() {
fun getTarGzRootForLocalFile(entryVFile : VirtualFile) : VirtualFile {
throw UnsupportedOperationException()
}
override fun exists(file: VirtualFile): Boolean {
return file.exists()
}
override fun list(file: VirtualFile): Array<String> {
throw UnsupportedOperationException()
}
override fun isDirectory(file: VirtualFile) = file.isDirectory()
override fun getTimeStamp(file: VirtualFile): Long = file.getTimeStamp()
override fun setTimeStamp(file: VirtualFile, timeStamp: Long) {
throw UnsupportedOperationException()
}
override fun isWritable(file: VirtualFile) = false
override fun setWritable(file: VirtualFile, writableFlag: Boolean) {
throw UnsupportedOperationException()
}
override fun contentsToByteArray(file: VirtualFile): ByteArray {
val stream = file.getInputStream()!!
return FileUtil.loadBytes(stream, file.getLength().toInt())
}
override fun getInputStream(file: VirtualFile) = file.getInputStream()!!
override fun getOutputStream(file: VirtualFile,
requestor: Any?,
modStamp: Long,
timeStamp: Long): OutputStream {
throw UnsupportedOperationException()
}
override fun getLength(file: VirtualFile) = file.getLength()
override fun getProtocol(): String = "ghci"
override fun findFileByPath(path: String): VirtualFile? {
throw UnsupportedOperationException()
}
override fun refresh(asynchronous: Boolean) {
throw UnsupportedOperationException()
}
override fun refreshAndFindFileByPath(path: String): VirtualFile? {
throw UnsupportedOperationException()
}
override fun findFileByPathIfCached(path: String): VirtualFile? {
return null
}
override fun extractRootPath(path: String): String {
throw UnsupportedOperationException()
}
override fun getRank(): Int = 2
override fun copyFile(requestor: Any?,
file: VirtualFile,
newParent: VirtualFile,
copyName: String): VirtualFile {
throw UnsupportedOperationException()
}
override fun createChildDirectory(requestor: Any?, parent: VirtualFile, dir: String): VirtualFile {
throw UnsupportedOperationException()
}
override fun createChildFile(requestor: Any?, parent: VirtualFile, file: String): VirtualFile {
throw UnsupportedOperationException()
}
override fun deleteFile(requestor: Any?, file: VirtualFile) {
throw UnsupportedOperationException()
}
override fun moveFile(requestor: Any?, file: VirtualFile, newParent: VirtualFile) {
throw UnsupportedOperationException()
}
override fun renameFile(requestor: Any?, file: VirtualFile, newName: String) {
throw UnsupportedOperationException()
}
override fun getAttributes(file: VirtualFile): FileAttributes? {
throw UnsupportedOperationException()
}
companion object {
public val INSTANCE : RamVirtualFileSystem = RamVirtualFileSystem()
}
}
| apache-2.0 | 8807c1a26b530080cf7e920d2cc019ca | 29.805085 | 103 | 0.681706 | 5.532725 | false | false | false | false |
TCA-Team/TumCampusApp | app/src/main/java/de/tum/in/tumcampusapp/component/tumui/calendar/CreateEventActivity.kt | 1 | 16849 | package de.tum.`in`.tumcampusapp.component.tumui.calendar
import android.app.Activity
import android.app.DatePickerDialog
import android.app.TimePickerDialog
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import android.view.MenuItem
import android.view.View
import android.view.inputmethod.InputMethodManager
import android.widget.LinearLayout
import android.widget.Toast
import androidx.appcompat.app.AlertDialog
import androidx.core.content.ContextCompat
import de.tum.`in`.tumcampusapp.R
import de.tum.`in`.tumcampusapp.api.tumonline.exception.RequestLimitReachedException
import de.tum.`in`.tumcampusapp.component.other.generic.activity.ActivityForAccessingTumOnline
import de.tum.`in`.tumcampusapp.component.tumui.calendar.model.CalendarItem
import de.tum.`in`.tumcampusapp.component.tumui.calendar.model.CreateEventResponse
import de.tum.`in`.tumcampusapp.component.tumui.calendar.model.DeleteEventResponse
import de.tum.`in`.tumcampusapp.component.tumui.calendar.model.EventSeriesMapping
import de.tum.`in`.tumcampusapp.database.TcaDb
import de.tum.`in`.tumcampusapp.utils.Const
import de.tum.`in`.tumcampusapp.utils.Utils
import kotlinx.android.synthetic.main.activity_create_event.*
import org.joda.time.DateTime
import org.joda.time.LocalDate
import org.joda.time.format.DateTimeFormat
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import java.net.UnknownHostException
import java.util.*
import kotlin.collections.ArrayList
/**
* Allows the user to create (and edit) a private event in TUMonline.
*/
class CreateEventActivity : ActivityForAccessingTumOnline<CreateEventResponse>(R.layout.activity_create_event) {
private lateinit var start: DateTime
private lateinit var end: DateTime
private lateinit var last: DateTime
private var repeats: Boolean = false
private var isEditing: Boolean = false
private var event: CalendarItem? = null
private var events: List<CalendarItem>? = null
private var apiCallsFetched = 0
private var apiCallsFailed = 0
private lateinit var seriesId: String
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val closeIcon = ContextCompat.getDrawable(this, R.drawable.ic_clear)
val color = ContextCompat.getColor(this, R.color.color_primary)
if (closeIcon != null) {
closeIcon.setTint(color)
supportActionBar?.setHomeAsUpIndicator(closeIcon)
}
// We only use the SwipeRefreshLayout to indicate progress, not to allow
// the user to pull to refresh.
swipeRefreshLayout?.isEnabled = false
eventTitleView.addTextChangedListener(object : TextWatcher {
override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {}
override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {
val isEmpty = s.toString().isEmpty()
val alpha = if (isEmpty) 0.5f else 1.0f
createEventButton.isEnabled = !isEmpty
createEventButton.alpha = alpha
}
override fun afterTextChanged(s: Editable) {}
})
val extras = intent.extras
if (extras != null) {
// an event with extras can either be editing an existing event
// or adding a new event from Tickets & Events
isEditing = extras.getBoolean(Const.EVENT_EDIT)
if (isEditing) {
createEventButton.setText(R.string.event_save_edit_button)
}
eventTitleView.setText(extras.getString(Const.EVENT_TITLE))
eventDescriptionView.setText(extras.getString(Const.EVENT_COMMENT))
} else {
eventTitleView.requestFocus()
showKeyboard()
}
initStartEndDates(extras)
setDateAndTimeListeners()
createEventButton.setOnClickListener {
if (end.isBefore(start) || (repeats && last.isBefore(start))) {
showErrorDialog(getString(R.string.create_event_time_error))
return@setOnClickListener
}
if (repeats) {
if (endAfterRadioBtn.isChecked && (eventRepeatsTimes.text.toString() == "" ||
eventRepeatsTimes.text.toString().toInt() < 2)) {
showErrorDialog(getString(R.string.create_event_too_little_error))
return@setOnClickListener
}
// Don't allow too many requests
if ((endOnRadioBtn.isChecked && start.plusMonths(6).isBefore(last)) ||
(endAfterRadioBtn.isChecked && eventRepeatsTimes.text.toString().toInt() > 25)) {
showErrorDialog(getString(R.string.create_event_too_many_error))
return@setOnClickListener
}
}
if (isEditing) {
editEvent()
} else {
createEvent()
}
}
// edited events cannot repeat
if (isEditing) {
repeatingSwitch.visibility = View.GONE
} else {
repeatingSwitch.setOnCheckedChangeListener { _, isChecked ->
if (isChecked) {
repeats = true
repeatingSettings.layoutParams.height = LinearLayout.LayoutParams.WRAP_CONTENT
repeatingSettings.requestLayout()
} else {
repeats = false
repeatingSettings.layoutParams.height = 0
repeatingSettings.requestLayout()
}
}
}
}
private fun initStartEndDates(extras: Bundle?) {
val initialDate = extras?.getSerializable(Const.DATE) as LocalDate?
val startTime = extras?.getSerializable(Const.EVENT_START) as DateTime?
val endTime = extras?.getSerializable(Const.EVENT_END) as DateTime?
if (startTime == null || endTime == null) {
if (initialDate == null) {
throw IllegalStateException("No date provided for CreateEventActivity")
}
// We’re creating a new event, so we set the start and end time to the next full hour
start = initialDate.toDateTimeAtCurrentTime()
.plusHours(1)
.withMinuteOfHour(0)
.withSecondOfMinute(0)
.withMillisOfSecond(0)
end = start.plusHours(1)
last = end.plusWeeks(1)
} else {
start = startTime
end = endTime
last = end.plusWeeks(1)
}
updateDateViews()
updateTimeViews()
}
private fun setDateAndTimeListeners() {
// DATE
// Month +/- 1 is needed because the date picker uses zero-based month values while DateTime
// starts counting months at 1.
eventStartDateView.setOnClickListener {
hideKeyboard()
DatePickerDialog(this, { _, year, month, dayOfMonth ->
start = start.withDate(year, month + 1, dayOfMonth)
if (end.isBefore(start)) {
end = end.withDate(year, month + 1, dayOfMonth)
}
updateDateViews()
}, start.year, start.monthOfYear - 1, start.dayOfMonth).show()
}
eventEndDateView.setOnClickListener {
hideKeyboard()
DatePickerDialog(this, { _, year, month, dayOfMonth ->
end = end.withDate(year, month + 1, dayOfMonth)
updateDateViews()
}, start.year, start.monthOfYear - 1, start.dayOfMonth).show()
}
eventLastDateView.setOnClickListener {
hideKeyboard()
DatePickerDialog(this, { _, year, month, dayOfMonth ->
last = last.withDate(year, month + 1, dayOfMonth)
updateDateViews()
}, last.year, last.monthOfYear - 1, last.dayOfMonth).show()
}
// TIME
eventStartTimeView.setOnClickListener { view ->
hideKeyboard()
TimePickerDialog(this, { timePicker, hour, minute ->
val eventLength = end.millis - start.millis
start = start.withHourOfDay(hour)
.withMinuteOfHour(minute)
end = end.withMillis(start.millis + eventLength)
updateTimeViews()
}, start.hourOfDay, start.minuteOfHour, true).show()
}
eventEndTimeView.setOnClickListener { view ->
hideKeyboard()
TimePickerDialog(this, { timePicker, hour, minute ->
end = end.withHourOfDay(hour)
.withMinuteOfHour(minute)
updateTimeViews()
}, end.hourOfDay, end.minuteOfHour, true).show()
}
}
private fun updateTimeViews() {
val format = DateTimeFormat.forPattern("HH:mm")
.withLocale(Locale.getDefault())
eventStartTimeView.text = format.print(start)
eventEndTimeView.text = format.print(end)
}
private fun updateDateViews() {
val format = DateTimeFormat.forPattern("EEE, dd.MM.yyyy")
.withLocale(Locale.getDefault())
eventStartDateView.text = format.print(start)
eventEndDateView.text = format.print(end)
eventLastDateView.text = format.print(last)
}
private fun editEvent() {
val eventId = intent.getStringExtra(Const.EVENT_NR) ?: return
// Because we don't show a loading screen for the delete request (only for the create
// request), we use a short Toast to let the user know that something is happening.
Toast.makeText(this, R.string.updating_event, Toast.LENGTH_SHORT).show()
apiClient
.deleteEvent(eventId)
.enqueue(object : Callback<DeleteEventResponse> {
override fun onResponse(
call: Call<DeleteEventResponse>,
response: Response<DeleteEventResponse>
) {
if (response.isSuccessful) {
Utils.log("Event successfully deleted (now creating the edited version)")
TcaDb.getInstance(this@CreateEventActivity).calendarDao().delete(eventId)
createEvent()
} else {
Utils.showToast(this@CreateEventActivity, R.string.error_unknown)
}
}
override fun onFailure(
call: Call<DeleteEventResponse>,
t: Throwable
) {
Utils.log(t)
displayErrorMessage(t)
}
})
}
private fun displayErrorMessage(throwable: Throwable) {
val messageResId: Int = when (throwable) {
is UnknownHostException -> R.string.error_no_internet_connection
is RequestLimitReachedException -> R.string.error_request_limit_reached
else -> R.string.error_unknown
}
Utils.showToast(this, messageResId)
}
private fun createEvent() {
val event = CalendarItem()
event.dtstart = start
event.dtend = end
var title = eventTitleView.text.toString()
if (title.length > 255) {
title = title.substring(0, 255)
}
event.title = title
var description = eventDescriptionView.text.toString()
if (description.length > 4000) {
description = description.substring(0, 4000)
}
event.description = description
this.event = event
events = generateEvents()
for (curEvent in events!!) {
val apiCall = apiClient.createEvent(curEvent, null)
fetch(apiCall)
}
}
/**
* generates a list of events that are added to the calendar
* depending on the repeat-setting
*/
private fun generateEvents(): List<CalendarItem> {
if (!repeats) {
return listOf(this.event!!)
}
val items = ArrayList<CalendarItem>()
seriesId = UUID.randomUUID().toString()
// event ends after n times
if (endAfterRadioBtn.isChecked) {
val numberOfEvents = eventRepeatsTimes.text.toString().toInt()
for (i in 0 until numberOfEvents) {
val item = CalendarItem()
item.title = event!!.title
item.description = event!!.description
item.dtstart = event!!.dtstart.plusWeeks(i)
item.dtend = event!!.dtend.plusWeeks(i)
items.add(item)
}
// event ends after "last" date
} else {
var curDateStart = event!!.dtstart
var curDateEnd = event!!.dtend
last.plusDays(1)
while (curDateStart.isBefore(last)) {
val item = CalendarItem()
item.title = event!!.title
item.description = event!!.description
item.dtstart = curDateStart
item.dtend = curDateEnd
curDateStart = curDateStart.plusWeeks(1)
curDateEnd = curDateEnd.plusWeeks(1)
items.add(item)
}
}
return items
}
@Synchronized
override fun onDownloadSuccessful(response: CreateEventResponse) {
events?.get(apiCallsFetched++)?.let {
it.nr = response.eventId
TcaDb.getInstance(this).calendarDao().insert(it)
if (repeats) {
TcaDb.getInstance(this).calendarDao().insert(EventSeriesMapping(seriesId, response.eventId))
}
}
//finish when all events have been created
if (apiCallsFetched == events?.size) {
setResult(Activity.RESULT_OK)
finish()
}
if (apiCallsFetched + apiCallsFailed == events?.size) {
finishWithError()
}
}
@Synchronized
override fun onDownloadFailure(throwable: Throwable) {
Utils.log(throwable)
apiCallsFailed++
if (apiCallsFetched + apiCallsFailed == events?.size) {
finishWithError()
}
}
private fun finishWithError() {
val i = Intent()
i.putExtra("failed", apiCallsFailed.toString())
i.putExtra("sum", (apiCallsFetched + apiCallsFailed).toString())
setResult(CalendarFragment.RESULT_ERROR, i)
finish()
}
override fun onBackPressed() {
hideKeyboard()
val handled = handleOnBackPressed()
if (handled) {
finish()
} else {
displayCloseDialog()
}
}
private fun showKeyboard() {
val inputManager = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
inputManager.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0)
}
private fun hideKeyboard() {
val inputManager = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
inputManager.hideSoftInputFromWindow(eventTitleView.windowToken, 0)
}
private fun handleOnBackPressed(): Boolean {
val title = eventTitleView.text.toString()
val description = eventDescriptionView.text.toString()
// TODO: If the user is in edit mode, check whether any data was changed.
return title.isEmpty() && description.isEmpty()
}
private fun displayCloseDialog() {
val dialog = AlertDialog.Builder(this)
.setMessage(R.string.discard_changes_question)
.setNegativeButton(R.string.discard) { dialogInterface, which -> finish() }
.setPositiveButton(R.string.keep_editing, null)
.create()
dialog.window?.setBackgroundDrawableResource(R.drawable.rounded_corners_background)
dialog.show()
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
if (item.itemId == android.R.id.home) {
onBackPressed()
return true
}
return super.onOptionsItemSelected(item)
}
private fun showErrorDialog(message: String) {
val dialog = AlertDialog.Builder(this)
.setTitle(R.string.error)
.setMessage(message)
.setIcon(R.drawable.ic_error_outline)
.setPositiveButton(R.string.ok, null)
.create()
dialog.window?.setBackgroundDrawableResource(R.drawable.rounded_corners_background)
dialog.show()
}
}
| gpl-3.0 | 51c8be43168b87ceffcc32392ddbb6b1 | 37.201814 | 112 | 0.598029 | 4.985795 | false | false | false | false |
saki4510t/libcommon | common/src/main/java/com/serenegiant/view/Event.kt | 1 | 1609 | package com.serenegiant.view
/*
* libcommon
* utility/helper classes for myself
*
* Copyright (c) 2014-2022 saki [email protected]
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import androidx.annotation.MainThread
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.Observer
interface Event<T> {
val value: T
}
private data class EventImpl<T>(override val value: T) : Event<T> {
var consumed = false
}
typealias LiveDataEvent<T> = LiveData<Event<T>>
typealias MutableLiveDataEvent<T> = MutableLiveData<Event<T>>
fun <T> LiveData<Event<T>>.observeEvent(owner: LifecycleOwner, observer: Observer<in T>) {
observe(owner) {
check(it is EventImpl)
if (!it.consumed) {
it.consumed = true
observer.onChanged(it.value)
}
}
}
@MainThread
fun <T> MutableLiveData<Event<T>>.setValue(value: T) {
this.value = EventImpl(value)
}
fun <T> MutableLiveData<Event<T>>.postValue(value: T) {
this.postValue(EventImpl(value))
}
| apache-2.0 | 8b6768275f13e98253ceb7fb525324cb | 28.254545 | 90 | 0.717837 | 3.794811 | false | false | false | false |
luanalbineli/popularmovies | app/src/main/java/com/themovielist/ui/RequestStatusView.kt | 1 | 2418 | package com.themovielist.ui
import android.content.Context
import android.support.annotation.StringRes
import android.util.AttributeSet
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup.LayoutParams.MATCH_PARENT
import android.view.ViewGroup.LayoutParams.WRAP_CONTENT
import android.widget.FrameLayout
import com.themovielist.R
import com.themovielist.enums.RequestStatusDescriptor
import kotlinx.android.synthetic.main.request_status.view.*
class RequestStatusView(context: Context, attrs: AttributeSet?) : FrameLayout(context, attrs) {
@RequestStatusDescriptor.RequestStatus
private var mRequestStatus: Int = 0
private var mTryAgainClickListener: (() -> Unit)? = null
init {
initializeViews(context)
}
private fun initializeViews(context: Context) {
val inflater = context.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater
inflater.inflate(R.layout.request_status, this)
}
fun setRequestStatus(requestStatus: Int, matchParentHeight: Boolean = false) {
this.mRequestStatus = requestStatus
redrawStatus(matchParentHeight)
}
fun setEmptyMessage(@StringRes messageResId: Int) {
tvRequestStatusEmptyMessage.setText(messageResId)
}
private fun redrawStatus(matchParentHeight: Boolean) {
toggleStatus(mRequestStatus == RequestStatusDescriptor.LOADING,
mRequestStatus == RequestStatusDescriptor.ERROR,
mRequestStatus == RequestStatusDescriptor.EMPTY,
if (matchParentHeight) MATCH_PARENT else WRAP_CONTENT)
}
private fun toggleStatus(loadingVisible: Boolean, errorVisible: Boolean, emptyMessageVisible: Boolean, viewHeight: Int) {
pbRequestStatusLoading.visibility = if (loadingVisible) View.VISIBLE else View.INVISIBLE
llRequestStatusError.visibility = if (errorVisible) View.VISIBLE else View.INVISIBLE
tvRequestStatusEmptyMessage.visibility = if (emptyMessageVisible) View.VISIBLE else View.INVISIBLE
btRequestStatusRetry.setOnClickListener {
mTryAgainClickListener?.invoke()
}
val layoutParams = this.layoutParams
layoutParams.height = viewHeight
this.layoutParams = layoutParams
}
fun setTryAgainClickListener(tryAgainClick: (() -> Unit)?) {
mTryAgainClickListener = tryAgainClick
}
}
| apache-2.0 | 2ada8109fdba610a648df585efebc0fe | 36.78125 | 125 | 0.741108 | 4.865191 | false | false | false | false |
elect86/jAssimp | src/main/kotlin/assimp/format/md5/MD5Parser.kt | 2 | 14260 | /*
Open Asset Import Library (assimp)
----------------------------------------------------------------------
Copyright (c) 2006-2017, assimp team
All rights reserved.
Redistribution and use of this software 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 assimp team, nor the names of its
contributors may be used to endorse or promote products
derived from this software without specific prior
written permission of the assimp team.
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 assimp.format.md5
import assimp.*
import glm_.f
import glm_.i
/** @file MD5Parser.h
* @brief Definition of the .MD5 parser class.
* http://www.modwiki.net/wiki/MD5_(file_format)
*/
/** Represents a single element in a MD5 file
*
* Elements are always contained in sections.
*/
class Element {
/** Points to the starting point of the element
* Whitespace at the beginning and at the end have been removed,
* Elements are terminated with \0 */
var szStart = ""
/** Original line number (can be used in error messages if a parsing error occurs) */
var iLineNumber = 0
}
/** Represents a section of a MD5 file (such as the mesh or the joints section)
*
* A section is always enclosed in { and } brackets. */
class Section {
/** Original line number (can be used in error messages if a parsing error occurs) */
var iLineNumber = 0
/** List of all elements which have been parsed in this section. */
val elements = ArrayList<Element>()
/** Name of the section */
var name = ""
/** For global elements: the value of the element as string
* if isEmpty() the section is not a global element */
var globalValue = ""
}
/** Basic information about a joint */
open class BaseJointDescription {
/** Name of the bone */
var name = ""
/** Parent index of the bone */
var parentIndex = 0
}
/** Represents a bone (joint) descriptor in a MD5Mesh file */
class BoneDesc : BaseJointDescription() {
/** Absolute position of the bone */
val positionXYZ = AiVector3D()
/** Absolute rotation of the bone */
val rotationQuat = AiVector3D()
val rotationQuatConverted = AiQuaternion()
/** Absolute transformation of the bone (temporary) */
val transform = AiMatrix4x4()
/* Inverse transformation of the bone (temporary) */
val invTransform = AiMatrix4x4()
/** Internal */
var map = 0
}
/** Represents a bone (joint) descriptor in a MD5Anim file */
class AnimBoneDesc : BaseJointDescription() {
/** Flags (AI_MD5_ANIMATION_FLAG_xxx) */
var flags = 0
/** Index of the first key that corresponds to this anim bone */
var firstKeyIndex = 0
}
/** Represents a base frame descriptor in a MD5Anim file */
open class BaseFrameDesc {
val positionXYZ = AiVector3D()
val rotationQuat = AiVector3D()
}
/** Represents a camera animation frame in a MDCamera file */
class CameraAnimFrameDesc : BaseFrameDesc() {
var fov = 0f
}
/** Represents a frame descriptor in a MD5Anim file */
class FrameDesc {
/** Index of the frame */
var index = 0
/** Animation keyframes - a large blob of data at first */
val values = ArrayList<Float>()
}
/** Represents a vertex descriptor in a MD5 file */
class VertexDesc {
/** UV cordinate of the vertex */
val uv = AiVector2D()
/** Index of the first weight of the vertex in the vertex weight list */
var firstWeight = 0
/** Number of weights assigned to this vertex */
var numWeights = 0
}
/** Represents a vertex weight descriptor in a MD5 file */
class WeightDesc {
/** Index of the bone to which this weight refers */
var bone = 0
/** The weight value */
var weight = 0f
/** The offset position of this weight (in the coordinate system defined by the parent bone) */
val offsetPosition = AiVector3D()
}
/** Represents a mesh in a MD5 file */
class MeshDesc {
/** Weights of the mesh */
val weights = ArrayList<WeightDesc>()
/** Vertices of the mesh */
val vertices = ArrayList<VertexDesc>()
/** Faces of the mesh */
val faces = ArrayList<AiFace>()
/** Name of the shader (=texture) to be assigned to the mesh */
var shader = ""
}
// Convert a quaternion to its usual representation
//inline void ConvertQuaternion(const aiVector3D & in , aiQuaternion& out ) {
//
// out.x = in.x
// out.y = in.y
// out.z = in.z
//
// const float t = 1.0f - ( in . x * in . x)-( in .y* in .y)-( in .z* in .z)
//
// if (t < 0.0f)
// out.w = 0.0f
// else out.w = std::sqrt (t)
//
// // Assimp convention.
// out.w *= -1.f
//}
/** Parses the data sections of a MD5 mesh file */
class MD5MeshParser
/** Constructs a new MD5MeshParser instance from an existing preparsed list of file sections.
*
* @param mSections List of file sections (output of MD5Parser) */
constructor(sections: ArrayList<Section>) {
/** List of all meshes */
val meshes = ArrayList<MeshDesc>()
/** List of all joints */
val joints = ArrayList<BoneDesc>()
init {
logger.debug { "MD5MeshParser begin" }
// now parse all sections
sections.forEach {
when (it.name) {
"numMeshes" -> meshes.ensureCapacity(it.globalValue.i)
"numJoints" -> joints.ensureCapacity(it.globalValue.i)
"joints" -> {
// "origin" -1 ( -0.000000 0.016430 -0.006044 ) ( 0.707107 0.000000 0.707107 )
it.elements.forEach {
val desc = BoneDesc()
joints.add(desc.apply {
val words = it.szStart.words
name = words[0].trim('"')
// negative values, at least -1, is allowed here
parentIndex = words[1].i
READ_TRIPLE(positionXYZ, words, 2, it.iLineNumber)
READ_TRIPLE(rotationQuat, words, 7, it.iLineNumber) // normalized quaternion, so w is not there
})
}
}
"mesh" -> {
val desc = MeshDesc()
meshes.add(desc)
for (elem in it.elements) {
val sz = elem.szStart.words
when (sz[0]) {
// shader attribute
"shader" -> desc.shader = sz[1].trim('"')
// numverts attribute
"numverts" -> for (i in 0 until sz[1].i) desc.vertices.add(VertexDesc())
// numtris attribute
"numtris" -> for (i in 0 until sz[1].i) desc.faces.add(mutableListOf())
// numweights attribute
"numweights" -> for (i in 0 until sz[1].i) desc.weights.add(WeightDesc())
// vert attribute, ex: "vert 0 ( 0.394531 0.513672 ) 0 1"
"vert" -> with(desc.vertices[sz[1].i]) {
if ("(" != sz[2]) MD5Parser.reportWarning("Unexpected token: ( was expected", elem.iLineNumber)
uv.put(sz, 3)
if (")" != sz[5]) MD5Parser.reportWarning("Unexpected token: ) was expected", elem.iLineNumber)
firstWeight = sz[6].i
numWeights = sz[7].i
}
// tri attribute, ex: "tri 0 15 13 12"
"tri" -> with(desc.faces[sz[1].i]) { for (i in 0..2) add(sz[2 + i].i) }
// weight attribute, ex: "weight 362 5 0.500000 ( -3.553583 11.893474 9.719339 )"
"weight" -> with(desc.weights[sz[1].i]) {
bone = sz[2].i
weight = sz[3].f
READ_TRIPLE(offsetPosition, sz, 4, it.iLineNumber)
}
}
}
}
}
}
logger.debug { "MD5MeshParser end" }
}
}
/** Parses the data sections of a MD5 animation file */
class MD5AnimParser {
/** Constructs a new MD5AnimParser instance from an existing preparsed list of file sections.
*
* @param mSections List of file sections (output of MD5Parser) */
// explicit MD5AnimParser(SectionList& mSections)
/** Output frame rate */
var frameRate = 0f
/** List of animation bones */
val animatedBones = ArrayList<AnimBoneDesc>()
/** List of base frames */
val baseFrames = ArrayList<BaseFrameDesc>()
/** List of animation frames */
val frames = ArrayList<FrameDesc>()
/** Number of animated components */
var numAnimatedComponents = 0
}
/** Parses the data sections of a MD5 camera animation file */
class MD5CameraParser {
/** Constructs a new MD5CameraParser instance from an existing preparsed list of file sections.
*
* @param mSections List of file sections (output of MD5Parser) */
// explicit MD5CameraParser(SectionList& mSections)
/** Output frame rate */
var frameRate = 0f
/** List of cuts */
val cuts = ArrayList<Int>()
/** Frames */
val frames = ArrayList<CameraAnimFrameDesc>()
}
/** Parses the block structure of MD5MESH and MD5ANIM files (but does no further processing) */
class MD5Parser(val lines: ArrayList<String>) {
var lineNumber = 0
var line = ""
/** List of all sections which have been read */
val sections = ArrayList<Section>()
init {
assert(lines.isNotEmpty())
logger.debug { "MD5Parser begin" }
// parse the file header
parseHeader()
// and read all sections until we're finished
while (true) {
val sec = Section()
sections.add(sec)
if (!sec.parse()) break
}
logger.debug("MD5Parser end. Parsed ${sections.size} sections")
}
fun reportError(error: String): Nothing = reportError(error, lineNumber)
fun reportWarning(warn: String) = reportWarning(warn, lineNumber)
/** Parses a file section. The current file pointer must be outside of a section.
* @param out Receives the section data
* @return true if the end of the file has been reached
* @throws ImportErrorException if an error occurs
*/
fun Section.parse(): Boolean {
if (lineNumber >= lines.size) return true
// store the current line number for use in error messages
iLineNumber = lineNumber
line = lines[lineNumber++]
val words = line.words
// first parse the name of the section
name = words[0]
when (words[1]) {
"{" -> { // it is a normal section so read all lines
line = lines[lineNumber++]
while (line[0] != '}') {
elements.add(Element().apply {
iLineNumber = lineNumber
szStart = line
})
line = lines[lineNumber++]
}
}
else -> globalValue = words[1] // it is an element at global scope. Parse its value and go on
}
return lineNumber < lines.size
}
/** Parses the file header
* @throws ImportErrorException if an error occurs */
fun parseHeader() {
// parse and validate the file version
val words = lines[lineNumber++].words
if (!words[0].startsWith("MD5Version")) reportError("Invalid MD5 file: MD5Version tag has not been found")
val iVer = words[1].i
if (10 != iVer) reportError("MD5 version tag is unknown (10 is expected)")
skipLine()
// print the command line options to the console
// FIX: can break the log length limit, so we need to be careful
logger.info { line }
}
fun skipLine() {
line = lines[lineNumber++]
}
companion object {
/** Report a specific error message and throw an exception
* @param error Error message to be reported
* @param line Index of the line where the error occurred */
fun reportError(error: String, line: Int): Nothing = throw Exception("[MD5] Line $line: $error")
/** Report a specific warning
* @param warn Warn message to be reported
* @param line Index of the line where the error occurred */
fun reportWarning(warn: String, line: Int) = logger.warn { "[MD5] Line $line: $warn" }
}
}
/** read a triple float in brackets: (1.0 1.0 1.0) */
private fun READ_TRIPLE(vec: AiVector3D, words: List<String>, index: Int, lineNumber: Int) {
if ("(" != words[index]) MD5Parser.reportWarning("Unexpected token: ( was expected", lineNumber)
vec.put(words, index + 1)
if (")" != words[index + 4]) MD5Parser.reportWarning("Unexpected token: ) was expected", lineNumber)
} | mit | 2f4f8d940ed332676446e3b9c325e237 | 36.528947 | 127 | 0.590112 | 4.302957 | false | false | false | false |
btimofeev/UniPatcher | app/src/main/java/org/emunix/unipatcher/ui/fragment/CreatePatchFragment.kt | 1 | 5687 | /*
Copyright (C) 2017, 2020, 2022 Boris Timofeev
This file is part of UniPatcher.
UniPatcher 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.
UniPatcher 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 UniPatcher. If not, see <http://www.gnu.org/licenses/>.
*/
package org.emunix.unipatcher.ui.fragment
import android.content.ActivityNotFoundException
import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.activity.result.ActivityResultLauncher
import androidx.core.view.isVisible
import androidx.fragment.app.viewModels
import dagger.hilt.android.AndroidEntryPoint
import org.emunix.unipatcher.MIME_TYPE_ALL_FILES
import org.emunix.unipatcher.MIME_TYPE_OCTET_STREAM
import org.emunix.unipatcher.R
import org.emunix.unipatcher.databinding.CreatePatchFragmentBinding
import org.emunix.unipatcher.utils.registerActivityResult
import org.emunix.unipatcher.viewmodels.ActionIsRunningViewModel
import org.emunix.unipatcher.viewmodels.CreatePatchViewModel
@AndroidEntryPoint
class CreatePatchFragment : ActionFragment(), View.OnClickListener {
private val viewModel by viewModels<CreatePatchViewModel>()
private val actionIsRunningViewModel by viewModels<ActionIsRunningViewModel>()
private lateinit var activitySourceFile: ActivityResultLauncher<Intent>
private lateinit var activityModifiedFile: ActivityResultLauncher<Intent>
private lateinit var activityPatchFile: ActivityResultLauncher<Intent>
private var _binding: CreatePatchFragmentBinding? = null
private val binding get() = _binding!!
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
_binding = CreatePatchFragmentBinding.inflate(inflater, container, false)
return binding.root
}
override fun onDestroyView() {
super.onDestroyView()
_binding = null
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
activity?.setTitle(R.string.nav_create_patch)
activitySourceFile = registerActivityResult(viewModel::sourceSelected)
activityModifiedFile = registerActivityResult(viewModel::modifiedSelected)
activityPatchFile = registerActivityResult(viewModel::patchSelected)
viewModel.getSourceName().observe(viewLifecycleOwner) {
binding.sourceFileNameTextView.text = it
}
viewModel.getModifiedName().observe(viewLifecycleOwner) {
binding.modifiedFileNameTextView.text = it
}
viewModel.getPatchName().observe(viewLifecycleOwner) {
binding.patchFileNameTextView.text = it
}
viewModel.getMessage().observe(viewLifecycleOwner) { event ->
event.getContentIfNotHandled()?.let { message ->
Toast.makeText(requireContext(), message, Toast.LENGTH_LONG).show()
}
}
viewModel.getActionIsRunning().observe(viewLifecycleOwner) { isRunning ->
actionIsRunningViewModel.createPatch(isRunning)
binding.progressBar.isVisible = isRunning
}
binding.sourceFileCardView.setOnClickListener(this)
binding.modifiedFileCardView.setOnClickListener(this)
binding.patchFileCardView.setOnClickListener(this)
}
override fun onClick(view: View) {
when (view.id) {
R.id.sourceFileCardView -> {
val intent = Intent(Intent.ACTION_GET_CONTENT).apply {
addCategory(Intent.CATEGORY_OPENABLE)
type = MIME_TYPE_ALL_FILES
}
try {
activitySourceFile.launch(intent)
} catch (e: ActivityNotFoundException) {
Toast.makeText(requireContext(), R.string.error_file_picker_app_is_no_installed, Toast.LENGTH_SHORT).show()
}
}
R.id.modifiedFileCardView -> {
val intent = Intent(Intent.ACTION_GET_CONTENT).apply {
addCategory(Intent.CATEGORY_OPENABLE)
type = MIME_TYPE_ALL_FILES
}
try {
activityModifiedFile.launch(intent)
} catch (e: ActivityNotFoundException) {
Toast.makeText(requireContext(), R.string.error_file_picker_app_is_no_installed, Toast.LENGTH_SHORT).show()
}
}
R.id.patchFileCardView -> {
val intent = Intent(Intent.ACTION_CREATE_DOCUMENT).apply {
addCategory(Intent.CATEGORY_OPENABLE)
type = MIME_TYPE_OCTET_STREAM
putExtra(Intent.EXTRA_TITLE, "patch.xdelta")
}
try {
activityPatchFile.launch(intent)
} catch (e: ActivityNotFoundException) {
Toast.makeText(requireContext(), R.string.error_file_picker_app_is_no_installed, Toast.LENGTH_SHORT).show()
}
}
}
}
override fun runAction() {
viewModel.runActionClicked()
}
} | gpl-3.0 | 01c50de08531f47824bef2ac1772e0fa | 40.518248 | 127 | 0.680148 | 4.997364 | false | false | false | false |
rhdunn/xquery-intellij-plugin | src/plugin-saxon/main/uk/co/reecedunn/intellij/plugin/saxon/query/s9api/proxy/TraceListener.kt | 1 | 3014 | /*
* Copyright (C) 2019-2020 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.saxon.query.s9api.proxy
import uk.co.reecedunn.intellij.plugin.core.reflection.loadClassOrNull
import uk.co.reecedunn.intellij.plugin.saxon.query.s9api.binding.expr.XPathContext
import uk.co.reecedunn.intellij.plugin.saxon.query.s9api.binding.trace.InstructionInfo
import java.lang.reflect.Proxy
interface TraceListener {
fun setOutputDestination(logger: Any)
fun open(controller: Any?)
fun close()
fun enter(instruction: InstructionInfo, properties: Map<String, Any>, context: XPathContext)
fun leave(instruction: InstructionInfo)
fun startCurrentItem(currentItem: Any)
fun endCurrentItem(currentItem: Any)
fun startRuleSearch()
fun endRuleSearch(rule: Any, mode: Any, item: Any)
}
fun TraceListener.proxy(vararg classes: Class<*>): Any {
val classLoader = classes[0].classLoader
val traceableClass = classLoader.loadClassOrNull("net.sf.saxon.trace.Traceable")
val instructionInfoClass = traceableClass ?: classLoader.loadClass("net.sf.saxon.trace.InstructionInfo")
val xpathContextClass = classLoader.loadClass("net.sf.saxon.expr.XPathContext")
return Proxy.newProxyInstance(classLoader, classes) { _, method, params ->
when (method.name) {
"setOutputDestination" -> setOutputDestination(params[0])
"open" -> open(params?.getOrNull(0))
"close" -> close()
"enter" -> {
val instructionInfo = InstructionInfo(params[0], instructionInfoClass)
if (params.size == 2) { // Saxon < 10
val context = XPathContext(params[1], xpathContextClass)
enter(instructionInfo, emptyMap(), context)
} else { // Saxon >= 10
val context = XPathContext(params[2], xpathContextClass)
@Suppress("UNCHECKED_CAST") val properties = params[1] as Map<String, Any>
enter(instructionInfo, properties, context)
}
}
"leave" -> leave(InstructionInfo(params[0], instructionInfoClass))
"startCurrentItem" -> startCurrentItem(params[0])
"endCurrentItem" -> endCurrentItem(params[0])
// TraceListener2 (Saxon 9.7+)
"startRuleSearch" -> startRuleSearch()
"endRuleSearch" -> endRuleSearch(params[0], params[1], params[2])
}
}
}
| apache-2.0 | 83bb4f7daa81021e02e98dd5a7d5d8ff | 40.861111 | 108 | 0.67286 | 4.2391 | false | false | false | false |
jiaminglu/kotlin-native | backend.native/tests/external/codegen/box/annotations/annotatedEnumEntry.kt | 2 | 902 | // TODO: muted automatically, investigate should it be ran for JS or not
// IGNORE_BACKEND: JS, NATIVE
// WITH_RUNTIME
// KT-5665
@Retention(AnnotationRetention.RUNTIME)
annotation class First
@Retention(AnnotationRetention.RUNTIME)
annotation class Second(val value: String)
enum class E {
@First
E1 {
fun foo() = "something"
},
@Second("OK")
E2
}
fun box(): String {
val e = E::class.java
val e1 = e.getDeclaredField(E.E1.toString()).getAnnotations()
if (e1.size != 1) return "Fail E1 size: ${e1.toList()}"
if (e1[0].annotationClass.java != First::class.java) return "Fail E1: ${e1.toList()}"
val e2 = e.getDeclaredField(E.E2.toString()).getAnnotations()
if (e2.size != 1) return "Fail E2 size: ${e2.toList()}"
if (e2[0].annotationClass.java != Second::class.java) return "Fail E2: ${e2.toList()}"
return (e2[0] as Second).value
}
| apache-2.0 | 9522c8398b5168d3a6e65575d758c2b3 | 24.771429 | 90 | 0.649667 | 3.28 | false | false | false | false |
marius-m/racer_test | core/src/main/java/lt/markmerkk/app/entities/PlayerClientImpl.kt | 1 | 1190 | package lt.markmerkk.app.entities
import com.badlogic.gdx.Gdx
import com.badlogic.gdx.graphics.Texture
import com.badlogic.gdx.graphics.g2d.Sprite
import com.badlogic.gdx.graphics.g2d.SpriteBatch
import lt.markmerkk.app.screens.GameScreen
class PlayerClientImpl(
override val id: Int = -1,
override val name: String
) : PlayerClient {
private val texture: Texture = Texture(Gdx.files.internal("data/car_small.png"))
private val sprite: Sprite = Sprite(texture)
init {
val width = sprite.width / GameScreen.PIXELS_PER_METER
val height = sprite.height / GameScreen.PIXELS_PER_METER
sprite.setSize(width, height)
sprite.setOrigin(width / 2, height / 2)
}
override fun update(
positionX: Float,
positionY: Float,
angle: Float
) {
sprite.setPosition(
positionX / GameScreen.PIXELS_PER_METER - sprite.width / 2,
positionY / GameScreen.PIXELS_PER_METER - sprite.height / 2
)
sprite.rotation = angle
}
override fun draw(spriteBatch: SpriteBatch) {
sprite.draw(spriteBatch)
}
override fun destroy() { }
} | apache-2.0 | 0e5d36421beb58865bea4f24b9e58fd6 | 28.04878 | 84 | 0.64958 | 4.061433 | false | false | false | false |
spkingr/50-android-kotlin-projects-in-100-days | ProjectSimpleGame/core/src/me/liuqingwen/game/Constants.kt | 1 | 519 | package me.liuqingwen.game
/**
* Created by Qingwen on 2018-2018-7-15, project: ProjectGDXGame.
*
* @Author: Qingwen
* @DateTime: 2018-7-15
* @Package: me.liuqingwen.game in project: ProjectGDXGame
*
* Notice: If you are using this class or file, check it and do some modification.
*/
/*
const val SCREEN_WIDTH = 1200.0f
const val SCREEN_HEIGHT = 800.0f
*/
const val PPM = 100
const val SCALE = 1.0f
const val GAME_TIME = 60
const val PREFERENCE_NAME = "gdx_game_pref"
const val PREFERENCE_SEPARATOR = "|"
| mit | bad5af270ceac6d467685d894a517ac6 | 20.625 | 82 | 0.707129 | 3.164634 | false | false | false | false |
da1z/intellij-community | platform/credential-store/src/macOsKeychainLibrary.kt | 3 | 10059 | /*
* Copyright 2000-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.credentialStore
import com.intellij.openapi.util.SystemInfo
import com.intellij.util.ArrayUtilRt
import com.sun.jna.*
import com.sun.jna.ptr.IntByReference
import com.sun.jna.ptr.PointerByReference
import gnu.trove.TIntObjectHashMap
val isMacOsCredentialStoreSupported: Boolean
get() = SystemInfo.isMacIntel64 && SystemInfo.isMacOSLeopard
private val LIBRARY by lazy { Native.loadLibrary("Security", MacOsKeychainLibrary::class.java) }
private const val errSecSuccess = 0
private const val errSecItemNotFound = -25300
private const val errSecInvalidRecord = -67701
// or if Deny clicked on access dialog
private const val errUserNameNotCorrect = -25293
private const val kSecFormatUnknown = 0
private const val kSecAccountItemAttr = (('a'.toInt() shl 8 or 'c'.toInt()) shl 8 or 'c'.toInt()) shl 8 or 't'.toInt()
internal class KeyChainCredentialStore() : CredentialStore {
override fun get(attributes: CredentialAttributes): Credentials? {
return findGenericPassword(attributes.serviceName.toByteArray(), attributes.userName)
}
override fun set(attributes: CredentialAttributes, credentials: Credentials?) {
val serviceName = attributes.serviceName.toByteArray()
if (credentials.isEmpty()) {
val itemRef = PointerByReference()
val userName = attributes.userName?.toByteArray()
val code = LIBRARY.SecKeychainFindGenericPassword(null, serviceName.size, serviceName, userName?.size ?: 0, userName, null, null, itemRef)
if (code == errSecItemNotFound || code == errSecInvalidRecord) {
return
}
checkForError("find (for delete)", code)
itemRef.value?.let {
checkForError("delete", LIBRARY.SecKeychainItemDelete(it))
LIBRARY.CFRelease(it)
}
return
}
val userName = (attributes.userName ?: credentials!!.userName)?.toByteArray()
val searchUserName = if (attributes.serviceName == SERVICE_NAME_PREFIX) userName else null
val itemRef = PointerByReference()
val library = LIBRARY
checkForError("find (for save)", library.SecKeychainFindGenericPassword(null, serviceName.size, serviceName, searchUserName?.size ?: 0, searchUserName, null, null, itemRef))
val password = if (attributes.isPasswordMemoryOnly || credentials!!.password == null) null else credentials.password!!.toByteArray(false)
val pointer = itemRef.value
if (pointer == null) {
checkForError("save (new)", library.SecKeychainAddGenericPassword(null, serviceName.size, serviceName, userName?.size ?: 0, userName, password?.size ?: 0, password))
}
else {
val attribute = SecKeychainAttribute()
attribute.tag = kSecAccountItemAttr
attribute.length = userName?.size ?: 0
if (userName != null) {
val userNamePointer = Memory(userName.size.toLong())
userNamePointer.write(0, userName, 0, userName.size)
attribute.data = userNamePointer
}
val attributeList = SecKeychainAttributeList()
attributeList.count = 1
attribute.write()
attributeList.attr = attribute.pointer
checkForError("save (update)", library.SecKeychainItemModifyContent(pointer, attributeList, password?.size ?: 0, password ?: ArrayUtilRt.EMPTY_BYTE_ARRAY))
library.CFRelease(pointer)
}
password?.fill(0)
}
}
fun findGenericPassword(serviceName: ByteArray, accountName: String?): Credentials? {
val accountNameBytes = accountName?.toByteArray()
val passwordSize = IntArray(1)
val passwordRef = PointerByReference()
val itemRef = PointerByReference()
checkForError("find", LIBRARY.SecKeychainFindGenericPassword(null, serviceName.size, serviceName, accountNameBytes?.size ?: 0, accountNameBytes, passwordSize, passwordRef, itemRef))
val pointer = passwordRef.value ?: return null
val password = OneTimeString(pointer.getByteArray(0, passwordSize.get(0)))
LIBRARY.SecKeychainItemFreeContent(null, pointer)
var effectiveAccountName = accountName
if (effectiveAccountName == null) {
val attributes = PointerByReference()
checkForError("SecKeychainItemCopyAttributesAndData", LIBRARY.SecKeychainItemCopyAttributesAndData(itemRef.value!!, SecKeychainAttributeInfo(kSecAccountItemAttr), null, attributes, null, null))
val attributeList = SecKeychainAttributeList(attributes.value)
try {
attributeList.read()
effectiveAccountName = readAttributes(attributeList).get(kSecAccountItemAttr)
}
finally {
LIBRARY.SecKeychainItemFreeAttributesAndData(attributeList, null)
}
}
return Credentials(effectiveAccountName, password)
}
// https://developer.apple.com/library/mac/documentation/Security/Reference/keychainservices/index.html
// It is very, very important to use CFRelease/SecKeychainItemFreeContent You must do it, otherwise you can get "An invalid record was encountered."
private interface MacOsKeychainLibrary : Library {
fun SecKeychainAddGenericPassword(keychain: Pointer?, serviceNameLength: Int, serviceName: ByteArray, accountNameLength: Int, accountName: ByteArray?, passwordLength: Int, passwordData: ByteArray?, itemRef: Pointer? = null): Int
fun SecKeychainItemModifyContent(itemRef: Pointer, /*SecKeychainAttributeList**/ attrList: Any?, length: Int, data: ByteArray?): Int
fun SecKeychainFindGenericPassword(keychainOrArray: Pointer?,
serviceNameLength: Int,
serviceName: ByteArray,
accountNameLength: Int,
accountName: ByteArray?,
passwordLength: IntArray?,
passwordData: PointerByReference?,
itemRef: PointerByReference?): Int
fun SecKeychainItemCopyAttributesAndData(itemRef: Pointer,
info: SecKeychainAttributeInfo,
itemClass: IntByReference?,
attrList: PointerByReference,
length: IntByReference?,
outData: PointerByReference?): Int
fun SecKeychainItemFreeAttributesAndData(attrList: SecKeychainAttributeList, data: Pointer?): Int
fun SecKeychainItemDelete(itemRef: Pointer): Int
fun /*CFString*/ SecCopyErrorMessageString(status: Int, reserved: Pointer?): Pointer?
// http://developer.apple.com/library/mac/#documentation/CoreFoundation/Reference/CFStringRef/Reference/reference.html
fun /*CFIndex*/ CFStringGetLength(/*CFStringRef*/ theString: Pointer): Long
fun /*UniChar*/ CFStringGetCharacterAtIndex(/*CFStringRef*/ theString: Pointer, /*CFIndex*/ idx: Long): Char
fun CFRelease(/*CFTypeRef*/ cf: Pointer)
fun SecKeychainItemFreeContent(/*SecKeychainAttributeList*/attrList: Pointer?, data: Pointer?)
}
internal class SecKeychainAttributeInfo : Structure() {
@JvmField
var count: Int = 0
@JvmField
var tag: Pointer? = null
@JvmField
var format: Pointer? = null
override fun getFieldOrder() = listOf("count", "tag", "format")
}
private fun checkForError(message: String, code: Int) {
if (code == errSecSuccess || code == errSecItemNotFound) {
return
}
val translated = LIBRARY.SecCopyErrorMessageString(code, null)
val builder = StringBuilder(message).append(": ")
if (translated == null) {
builder.append(code)
}
else {
val buf = CharArray(LIBRARY.CFStringGetLength(translated).toInt())
for (i in 0..buf.size - 1) {
buf[i] = LIBRARY.CFStringGetCharacterAtIndex(translated, i.toLong())
}
LIBRARY.CFRelease(translated)
builder.append(buf).append(" (").append(code).append(')')
}
if (code == errUserNameNotCorrect || code == -25299 /* The specified item already exists in the keychain */) {
LOG.warn(builder.toString())
}
else {
LOG.error(builder.toString())
}
}
internal fun SecKeychainAttributeInfo(vararg ids: Int): SecKeychainAttributeInfo {
val info = SecKeychainAttributeInfo()
val length = ids.size
info.count = length
val size = length shl 2
val tag = Memory((size shl 1).toLong())
val format = tag.share(size.toLong(), size.toLong())
info.tag = tag
info.format = format
var offset = 0
for (id in ids) {
tag.setInt(offset.toLong(), id)
format.setInt(offset.toLong(), kSecFormatUnknown)
offset += 4
}
return info
}
internal class SecKeychainAttributeList : Structure {
@JvmField
var count = 0
@JvmField
var attr: Pointer? = null
constructor(p: Pointer) : super(p) {
}
constructor() : super() {
}
override fun getFieldOrder() = listOf("count", "attr")
}
internal class SecKeychainAttribute : Structure, Structure.ByReference {
@JvmField
var tag = 0
@JvmField
var length = 0
@JvmField
var data: Pointer? = null
internal constructor(p: Pointer) : super(p) {
}
internal constructor() : super() {
}
override fun getFieldOrder() = listOf("tag", "length", "data")
}
private fun readAttributes(list: SecKeychainAttributeList): TIntObjectHashMap<String> {
val map = TIntObjectHashMap<String>()
val attrList = SecKeychainAttribute(list.attr!!)
attrList.read()
@Suppress("UNCHECKED_CAST")
for (attr in attrList.toArray(list.count) as Array<SecKeychainAttribute>) {
val data = attr.data ?: continue
map.put(attr.tag, String(data.getByteArray(0, attr.length)))
}
return map
} | apache-2.0 | b09e5f9a43a47839cb95355ed3aaef4c | 37.841699 | 230 | 0.702456 | 4.377285 | false | false | false | false |
esqr/WykopMobilny | app/src/main/kotlin/io/github/feelfreelinux/wykopmobilny/utils/textview/TextViewExtensions.kt | 1 | 728 | package io.github.feelfreelinux.wykopmobilny.utils.textview
import android.text.SpannableStringBuilder
import android.text.method.LinkMovementMethod
import android.text.style.URLSpan
import android.widget.TextView
import io.github.feelfreelinux.wykopmobilny.utils.wykop_link_handler.WykopLinkHandlerApi
fun TextView.prepareBody(html: String, urlClickedCallback : (String) -> Unit) {
val sequence = html.toSpannable()
val strBuilder = SpannableStringBuilder(sequence)
val urls = strBuilder.getSpans(0, strBuilder.length, URLSpan::class.java)
urls.forEach {
span -> strBuilder.makeLinkClickable(span, urlClickedCallback)
}
text = strBuilder
movementMethod = LinkMovementMethod.getInstance()
} | mit | 3c309148217867b3069f54fd697dbaa5 | 39.5 | 88 | 0.791209 | 4.521739 | false | false | false | false |
treelzebub/zinepress | app/src/main/java/net/treelzebub/zinepress/db/articles/ArticleWriter.kt | 1 | 1293 | package net.treelzebub.zinepress.db.articles
import android.content.ContentValues
import android.net.Uri
import net.treelzebub.zinepress.db.IWriter
import net.treelzebub.zinepress.net.api.model.PocketArticle
import net.treelzebub.zinepress.util.extensions.maybePut
/**
* Created by Tre Murillo on 1/28/16
*/
class ArticleWriter(override val parent: DbArticles) : IWriter<IArticle> {
private val context = parent.context
fun insertAll(uri: Uri, list: List<PocketArticle>): Boolean {
return bulkInsert(uri, *list.toTypedArray())
}
override fun bulkInsert(uri: Uri, vararg items: IArticle): Boolean {
val cvs = items.map { toContentValues(it) }
return context.contentResolver.bulkInsert(uri, cvs.toTypedArray()) == items.size
}
override fun addOrUpdate(vararg items: IArticle): Boolean {
if (items.isEmpty()) return false
return bulkInsert(parent.uri(), *items)
}
override fun toContentValues(item: IArticle): ContentValues {
val retval = ContentValues()
retval.maybePut(ArticleCols.ID, item.id)
retval.maybePut(ArticleCols.DATE, item.date)
retval.maybePut(ArticleCols.TITLE, item.title)
retval.maybePut(ArticleCols.URL, item.originalUrl)
return retval
}
}
| gpl-2.0 | 99f3f2733f23eadf4aa8cda51455b1ba | 33.026316 | 88 | 0.70843 | 4.066038 | false | false | false | false |
realm/realm-java | realm-transformer/src/main/kotlin/io/realm/transformer/Stopwatch.kt | 1 | 1929 | /*
* Copyright 2018 Realm Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.realm.transformer
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import java.util.concurrent.TimeUnit
class Stopwatch {
val logger: Logger = LoggerFactory.getLogger("realm-stopwatch")
var start: Long = -1L
var lastSplit: Long = -1L
lateinit var label: String
/*
* Start the stopwatch.
*/
fun start(label: String) {
if (start != -1L) {
throw IllegalStateException("Stopwatch was already started");
}
this.label = label
start = System.nanoTime();
lastSplit = start;
}
/*
* Reports the split time.
*
* @param label Label to use when printing split time
* @param reportDiffFromLastSplit if `true` report the time from last split instead of the start
*/
fun splitTime(label: String, reportDiffFromLastSplit: Boolean = true) {
val split = System.nanoTime()
val diff = if (reportDiffFromLastSplit) { split - lastSplit } else { split - start }
lastSplit = split;
logger.debug("$label: ${TimeUnit.NANOSECONDS.toMillis(diff)} ms.")
}
/**
* Stops the timer and report the result.
*/
fun stop() {
val stop = System.nanoTime()
val diff = stop - start
logger.debug("$label: ${TimeUnit.NANOSECONDS.toMillis(diff)} ms.")
}
} | apache-2.0 | 7a393352d02521bcf5b26d2e758b349b | 29.634921 | 100 | 0.656817 | 4.21179 | false | false | false | false |
Maccimo/intellij-community | platform/platform-impl/src/com/intellij/openapi/actionSystem/impl/MoreActionGroup.kt | 1 | 983 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.openapi.actionSystem.impl
import com.intellij.icons.AllIcons
import com.intellij.idea.ActionsBundle
import com.intellij.openapi.actionSystem.ActionUpdateThread
import com.intellij.openapi.actionSystem.DefaultActionGroup
open class MoreActionGroup @JvmOverloads constructor(
horizontal: Boolean = true
) : DefaultActionGroup({ ActionsBundle.groupText("MoreActionGroup") }, true) {
init {
templatePresentation.icon = if (horizontal) AllIcons.Actions.More else AllIcons.Actions.MoreHorizontal
templatePresentation.putClientProperty(ActionButton.HIDE_DROPDOWN_ICON, true)
}
override fun isDumbAware() = true
override fun hideIfNoVisibleChildren() = true
override fun getActionUpdateThread(): ActionUpdateThread =
if (this::class == MoreActionGroup::class) ActionUpdateThread.BGT else super.getActionUpdateThread()
} | apache-2.0 | 7e994fab041df9164d79aa397b2b1190 | 40 | 120 | 0.803662 | 4.866337 | false | false | false | false |
google/identity-credential | appholder/src/main/java/com/android/mdl/app/MainActivity.kt | 1 | 4595 | package com.android.mdl.app
import android.app.PendingIntent
import android.content.Intent
import android.net.Uri
import android.nfc.NfcAdapter
import android.os.Build
import android.os.Bundle
import android.util.Log
import android.view.WindowManager.LayoutParams.*
import androidx.activity.viewModels
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.GravityCompat
import androidx.navigation.Navigation
import androidx.navigation.findNavController
import androidx.navigation.ui.NavigationUI
import androidx.navigation.ui.NavigationUI.setupActionBarWithNavController
import androidx.navigation.ui.setupWithNavController
import com.android.identity.OriginInfo
import com.android.identity.OriginInfoWebsite
import com.android.mdl.app.databinding.ActivityMainBinding
import com.android.mdl.app.viewmodel.ShareDocumentViewModel
import com.google.android.material.elevation.SurfaceColors
class MainActivity : AppCompatActivity() {
companion object {
private const val LOG_TAG = "MainActivity"
}
private val viewModel: ShareDocumentViewModel by viewModels()
private lateinit var binding: ActivityMainBinding
private lateinit var pendingIntent: PendingIntent
private var nfcAdapter: NfcAdapter? = null
private val navController by lazy {
Navigation.findNavController(this, R.id.nav_host_fragment)
}
override fun onCreate(savedInstanceState: Bundle?) {
showWhenLockedAndTurnScreenOn()
super.onCreate(savedInstanceState)
val color = SurfaceColors.SURFACE_2.getColor(this)
window.statusBarColor = color
window.navigationBarColor = color
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
setupDrawerLayout()
setupNfc()
}
private fun setupNfc() {
nfcAdapter = NfcAdapter.getDefaultAdapter(this)
// Create a generic PendingIntent that will be deliver to this activity. The NFC stack
// will fill in the intent with the details of the discovered tag before delivering to
// this activity.
val intent = Intent(this, javaClass).apply {
addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP)
}
pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_IMMUTABLE)
}
private fun setupDrawerLayout() {
binding.nvSideDrawer.setupWithNavController(navController)
setupActionBarWithNavController(this, navController, binding.dlMainDrawer)
}
private fun showWhenLockedAndTurnScreenOn() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O_MR1) {
setShowWhenLocked(true)
setTurnScreenOn(true)
} else {
window.addFlags(FLAG_SHOW_WHEN_LOCKED or FLAG_TURN_SCREEN_ON)
}
}
override fun onResume() {
super.onResume()
nfcAdapter?.enableForegroundDispatch(this, pendingIntent, null, null)
}
override fun onPause() {
super.onPause()
nfcAdapter?.disableForegroundDispatch(this)
}
override fun onNewIntent(intent: Intent?) {
super.onNewIntent(intent)
Log.d(LOG_TAG, "New intent on Activity $intent")
if (intent == null) {
return
}
var mdocUri: String? = null
var mdocReferrerUri: String? = null
if (intent.scheme.equals("mdoc")) {
val uri = Uri.parse(intent.toUri(0))
mdocUri = "mdoc://" + uri.authority
mdocReferrerUri = intent.extras?.get(Intent.EXTRA_REFERRER)?.toString()
}
if (mdocUri == null) {
Log.e(LOG_TAG, "No mdoc:// URI")
return
}
if (mdocReferrerUri == null) {
Log.e(LOG_TAG, "No referrer URI")
return
}
Log.i(LOG_TAG, "uri: $mdocUri")
Log.i(LOG_TAG, "referrer: $mdocReferrerUri")
val originInfos = ArrayList<OriginInfo>()
originInfos.add(OriginInfoWebsite(1, mdocReferrerUri))
viewModel.startPresentationReverseEngagement(mdocUri, originInfos)
val navController = findNavController(R.id.nav_host_fragment)
navController.navigate(R.id.transferDocumentFragment)
}
override fun onSupportNavigateUp(): Boolean {
return NavigationUI.navigateUp(navController, binding.dlMainDrawer)
}
override fun onBackPressed() {
if (binding.dlMainDrawer.isDrawerOpen(GravityCompat.START)) {
binding.dlMainDrawer.closeDrawer(GravityCompat.START)
} else {
super.onBackPressed()
}
}
} | apache-2.0 | ff7e10262c5fbf82c01fb26daad10459 | 33.298507 | 96 | 0.690098 | 4.627392 | false | false | false | false |
NCBSinfo/NCBSinfo | app/src/main/java/com/rohitsuratekar/NCBSinfo/fragments/SelectTripDayFragment.kt | 2 | 7391 | package com.rohitsuratekar.NCBSinfo.fragments
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import com.rohitsuratekar.NCBSinfo.R
import com.rohitsuratekar.NCBSinfo.adapters.SelectTripDayAdapter
import com.rohitsuratekar.NCBSinfo.common.Constants
import com.rohitsuratekar.NCBSinfo.database.TripData
import com.rohitsuratekar.NCBSinfo.models.EditFragment
import com.rohitsuratekar.NCBSinfo.models.Route
import com.rohitsuratekar.NCBSinfo.viewmodels.SelectTripDayViewModel
import kotlinx.android.synthetic.main.fragment_select_trip_day.*
import java.util.*
class SelectTripDayFragment : EditFragment(), SelectTripDayAdapter.OnDaySelected {
data class SelectTripDayModel(
val title: Int,
val subtitle: Int,
val note: String,
val id: Int,
val freq: MutableList<Int>,
val trip: TripData
)
private lateinit var viewModel: SelectTripDayViewModel
private lateinit var adapter: SelectTripDayAdapter
private var itemList = mutableListOf<SelectTripDayModel>()
private var currentRoute: Route? = null
private var currentFrequency = mutableListOf<Int>()
private val dayList = mutableListOf(
Calendar.SUNDAY, Calendar.MONDAY, Calendar.TUESDAY,
Calendar.WEDNESDAY, Calendar.THURSDAY, Calendar.FRIDAY, Calendar.SATURDAY
)
private val stringList = mutableListOf(
R.string.sunday,
R.string.monday,
R.string.tuesday,
R.string.wednesday,
R.string.thursday,
R.string.friday,
R.string.saturday
)
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_select_trip_day, container, false)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
viewModel = ViewModelProvider(this).get(SelectTripDayViewModel::class.java)
}
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
callback?.setFragmentTitle(R.string.et_select_day)
subscribe()
adapter = SelectTripDayAdapter(itemList, this)
et_sd_recycler.adapter = adapter
et_sd_recycler.layoutManager = LinearLayoutManager(context)
et_sd_new.setOnClickListener {
sharedModel.clearAllAttributes()
sharedModel.setInputRouteID(-1)
callback?.navigate(Constants.EDIT_START_EDITING)
}
}
private fun subscribe() {
sharedModel.inputRouteID.observe(viewLifecycleOwner, Observer {
if (it == -1) {
callback?.navigate(Constants.EDIT_START_EDITING)
} else {
viewModel.extractRoute(repository, it)
}
})
viewModel.currentRoute.observe(viewLifecycleOwner, Observer {
currentRoute = it
sharedModel.setRoute(it)
updateSharedModel()
})
}
private fun getType(type: String): Int {
return when (type) {
"shuttle" -> R.id.et_type_option1
"ttc" -> R.id.et_type_option2
"buggy" -> R.id.et_type_option3
else -> R.id.et_type_option4
}
}
private fun updateSharedModel() {
val frequencyDetails = mutableListOf(0, 0, 0, 0, 0, 0, 0)
currentRoute?.let {
sharedModel.setOrigin(it.routeData.origin!!.toUpperCase(Locale.getDefault()))
sharedModel.setDestination(it.routeData.destination!!.toUpperCase(Locale.getDefault()))
sharedModel.setType(getType(it.routeData.type!!))
for (t in it.tripData) {
frequencyDetails[dayList.indexOf(t.day)] = 1
}
sharedModel.setFrequencyData(frequencyDetails)
currentFrequency.addAll(frequencyDetails)
sharedModel.updateTripSelection(true)
if (frequencyDetails.sum() == 1) {
sharedModel.setFrequency(R.id.et_fq_all_days)
sharedModel.updateTrips(it.tripData[0].trips!!)
callback?.navigate(Constants.EDIT_START_EDITING)
} else {
updateUI()
}
}
}
private fun updateUI() {
itemList.clear()
currentRoute?.let {
et_sd_route.text = getString(
R.string.tp_route_name,
it.routeData.origin!!.toUpperCase(Locale.getDefault()),
it.routeData.destination!!.toUpperCase(Locale.getDefault())
)
et_sd_type.text = it.routeData.type
if ((currentFrequency.sum() == 2) and (currentFrequency[0] == 1)) {
for (t in it.tripData) {
if (t.day == Calendar.SUNDAY) {
itemList.add(
SelectTripDayModel(
R.string.sunday,
R.string.et_select_single_day,
getString(R.string.et_sd_trips, t.trips?.size),
R.id.et_fq_select_specific,
mutableListOf(1, 0, 0, 0, 0, 0, 0),
t
)
)
} else {
itemList.add(
SelectTripDayModel(
R.string.et_select_weekday,
R.string.et_select_weekday_details,
getString(R.string.et_sd_trips, t.trips?.size),
R.id.et_fq_mon_sat,
mutableListOf(0, 1, 1, 1, 1, 1, 1),
t
)
)
}
}
} else {
for (t in it.tripData) {
val e = mutableListOf(0, 0, 0, 0, 0, 0, 0)
e[dayList.indexOf(t.day)] = 1
itemList.add(
SelectTripDayModel(
stringList[dayList.indexOf(t.day)],
R.string.et_select_single_day,
getString(R.string.et_sd_trips, t.trips?.size),
R.id.et_fq_select_specific,
e,
t
)
)
}
}
}
adapter.notifyDataSetChanged()
callback?.hideProgress()
}
override fun daySelected(dayModel: SelectTripDayModel) {
sharedModel.setFrequencyData(dayModel.freq)
sharedModel.setFrequency(dayModel.id)
sharedModel.setSelectedTrip(dayModel.trip)
sharedModel.updateTrips(dayModel.trip.trips!!)
callback?.navigate(Constants.EDIT_START_EDITING)
}
}
| mit | 8f4ed39243a51ee7e7f97a3c8928fd24 | 36.295337 | 99 | 0.550805 | 4.868906 | false | false | false | false |
mdaniel/intellij-community | plugins/package-search/src/com/jetbrains/packagesearch/intellij/plugin/util/CoroutinesUtils.kt | 1 | 14653 | /*******************************************************************************
* 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.util
import com.intellij.buildsystem.model.unified.UnifiedDependencyRepository
import com.intellij.openapi.application.EDT
import com.intellij.openapi.module.Module
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.progress.Task
import com.intellij.openapi.progress.impl.ProgressManagerImpl
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.UserDataHolder
import com.intellij.psi.PsiFile
import com.intellij.util.flow.throttle
import com.jetbrains.packagesearch.intellij.plugin.extensibility.AsyncModuleTransformer
import com.jetbrains.packagesearch.intellij.plugin.extensibility.AsyncProjectModuleOperationProvider
import com.jetbrains.packagesearch.intellij.plugin.extensibility.CoroutineModuleTransformer
import com.jetbrains.packagesearch.intellij.plugin.extensibility.CoroutineProjectModuleOperationProvider
import com.jetbrains.packagesearch.intellij.plugin.extensibility.DependencyOperationMetadata
import com.jetbrains.packagesearch.intellij.plugin.extensibility.FlowModuleChangesSignalProvider
import com.jetbrains.packagesearch.intellij.plugin.extensibility.ModuleChangesSignalProvider
import com.jetbrains.packagesearch.intellij.plugin.extensibility.ModuleTransformer
import com.jetbrains.packagesearch.intellij.plugin.extensibility.ProjectModule
import com.jetbrains.packagesearch.intellij.plugin.extensibility.ProjectModuleOperationProvider
import com.jetbrains.packagesearch.intellij.plugin.extensibility.ProjectModuleType
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.async
import kotlinx.coroutines.awaitAll
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.channels.SendChannel
import kotlinx.coroutines.channels.awaitClose
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.callbackFlow
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.channelFlow
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.mapLatest
import kotlinx.coroutines.flow.merge
import kotlinx.coroutines.flow.onEach
import kotlinx.coroutines.flow.toList
import kotlinx.coroutines.future.await
import kotlinx.coroutines.job
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.selects.select
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import kotlinx.coroutines.withContext
import org.jetbrains.annotations.Nls
import kotlin.coroutines.CoroutineContext
import kotlin.coroutines.coroutineContext
import kotlin.time.Duration
import kotlin.time.TimedValue
import kotlin.time.measureTimedValue
internal fun <T> Flow<T>.onEach(context: CoroutineContext, action: suspend (T) -> Unit) =
onEach { withContext(context) { action(it) } }
internal fun <T, R> Flow<T>.map(context: CoroutineContext, action: suspend (T) -> R) =
map { withContext(context) { action(it) } }
internal fun <T> Flow<T>.replayOnSignals(vararg signals: Flow<Any>) = channelFlow {
var lastValue: T? = null
onEach { send(it) }
.onEach { lastValue = it }
.launchIn(this)
merge(*signals)
.onEach { lastValue?.let { send(it) } }
.launchIn(this)
}
suspend fun <T, R> Iterable<T>.parallelMap(transform: suspend CoroutineScope.(T) -> R) = coroutineScope {
map { async { transform(it) } }.awaitAll()
}
internal suspend fun <T> Iterable<T>.parallelFilterNot(transform: suspend (T) -> Boolean) =
channelFlow { parallelForEach { if (!transform(it)) send(it) } }.toList()
internal suspend fun <T, R> Iterable<T>.parallelMapNotNull(transform: suspend (T) -> R?) =
channelFlow { parallelForEach { transform(it)?.let { send(it) } } }.toList()
internal suspend fun <T> Iterable<T>.parallelForEach(action: suspend CoroutineScope.(T) -> Unit) = coroutineScope {
forEach { launch { action(it) } }
}
internal suspend fun <T, R, K> Map<T, R>.parallelMap(transform: suspend (Map.Entry<T, R>) -> K) = coroutineScope {
map { async { transform(it) } }.awaitAll()
}
internal suspend fun <T, R> Iterable<T>.parallelFlatMap(transform: suspend (T) -> Iterable<R>) = coroutineScope {
map { async { transform(it) } }.flatMap { it.await() }
}
internal suspend inline fun <K, V> Map<K, V>.parallelUpdatedKeys(keys: Iterable<K>, crossinline action: suspend (K) -> V): Map<K, V> {
val map = toMutableMap()
keys.parallelForEach { map[it] = action(it) }
return map
}
internal fun timer(each: Duration, emitAtStartup: Boolean = true) = flow {
if (emitAtStartup) emit(Unit)
while (true) {
delay(each)
emit(Unit)
}
}
internal fun <T> Flow<T>.throttle(time: Duration) =
throttle(time.inWholeMilliseconds)
internal inline fun <reified T, reified R> Flow<T>.modifiedBy(
modifierFlow: Flow<R>,
crossinline transform: suspend (T, R) -> T
): Flow<T> = flow {
coroutineScope {
val queue = Channel<Any?>(capacity = 1)
val mutex = Mutex(locked = true)
[email protected] {
queue.send(it)
if (mutex.isLocked) mutex.unlock()
}.launchIn(this)
mutex.lock()
modifierFlow.onEach { queue.send(it) }.launchIn(this)
var currentState: T = queue.receive() as T
emit(currentState)
for (e in queue) {
when (e) {
is T -> currentState = e
is R -> currentState = transform(currentState, e)
else -> continue
}
emit(currentState)
}
}
}
internal fun <T, R> Flow<T>.mapLatestTimedWithLoading(
loggingContext: String,
loadingFlow: MutableStateFlow<Boolean>? = null,
transform: suspend CoroutineScope.(T) -> R
) =
mapLatest {
measureTimedValue {
loadingFlow?.emit(true)
val result = try {
coroutineScope { transform(it) }
} finally {
loadingFlow?.emit(false)
}
result
}
}.map {
logDebug(loggingContext) { "Took ${it.duration.absoluteValue} to process" }
it.value
}
internal fun <T> Flow<T>.catchAndLog(context: String, message: String, fallbackValue: T, retryChannel: SendChannel<Unit>? = null) =
catch {
logWarn(context, it) { message }
retryChannel?.send(Unit)
emit(fallbackValue)
}
internal suspend inline fun <R> MutableStateFlow<Boolean>.whileLoading(action: () -> R): TimedValue<R> {
emit(true)
val r = measureTimedValue { action() }
emit(false)
return r
}
internal inline fun <reified T> Flow<T>.batchAtIntervals(duration: Duration) = channelFlow {
val mutex = Mutex()
val buffer = mutableListOf<T>()
var job: Job? = null
collect {
mutex.withLock { buffer.add(it) }
if (job == null || job?.isCompleted == true) {
job = launch {
delay(duration)
mutex.withLock {
send(buffer.toTypedArray())
buffer.clear()
}
}
}
}
}
internal suspend fun showBackgroundLoadingBar(
project: Project,
@Nls title: String,
@Nls upperMessage: String,
cancellable: Boolean = false,
isSafe: Boolean = true
): BackgroundLoadingBarController {
val syncSignal = Mutex(true)
val cancellationRequested = Channel<Unit>()
val externalScopeJob = coroutineContext.job
val progressManager = ProgressManager.getInstance()
progressManager.run(object : Task.Backgroundable(project, title, cancellable) {
override fun run(indicator: ProgressIndicator) {
if (isSafe && progressManager is ProgressManagerImpl && indicator is UserDataHolder) {
progressManager.markProgressSafe(indicator)
}
indicator.text = upperMessage // ??? why does it work?
runBlocking {
indicator.text = upperMessage // ??? why does it work?
val indicatorCancelledPollingJob = launch {
while (true) {
if (indicator.isCanceled) {
cancellationRequested.send(Unit)
break
}
delay(50)
}
}
val internalJob = launch {
syncSignal.lock()
}
select {
internalJob.onJoin { }
externalScopeJob.onJoin { internalJob.cancel() }
}
indicatorCancelledPollingJob.cancel()
}
}
})
return BackgroundLoadingBarController(syncSignal)
}
internal class BackgroundLoadingBarController(private val syncMutex: Mutex) {
fun clear() {
runCatching { syncMutex.unlock() }
}
}
suspend fun <R> writeAction(action: () -> R): R = withContext(Dispatchers.EDT) { action() }
internal fun ModuleTransformer.asCoroutine() = object : CoroutineModuleTransformer {
override suspend fun transformModules(project: Project, nativeModules: List<Module>): List<ProjectModule> =
[email protected](project, nativeModules)
}
internal fun AsyncModuleTransformer.asCoroutine() = object : CoroutineModuleTransformer {
override suspend fun transformModules(project: Project, nativeModules: List<Module>): List<ProjectModule> =
[email protected](project, nativeModules).await()
}
internal fun ModuleChangesSignalProvider.asCoroutine() = object : FlowModuleChangesSignalProvider {
override fun registerModuleChangesListener(project: Project) = callbackFlow {
val sub = registerModuleChangesListener(project) { trySend(Unit) }
awaitClose { sub.unsubscribe() }
}
}
internal fun ProjectModuleOperationProvider.asCoroutine() = object : CoroutineProjectModuleOperationProvider {
override fun hasSupportFor(project: Project, psiFile: PsiFile?) = [email protected](project, psiFile)
override fun hasSupportFor(projectModuleType: ProjectModuleType) = [email protected](projectModuleType)
override suspend fun addDependencyToModule(operationMetadata: DependencyOperationMetadata, module: ProjectModule) =
[email protected](operationMetadata, module).toList()
override suspend fun removeDependencyFromModule(operationMetadata: DependencyOperationMetadata, module: ProjectModule) =
[email protected](operationMetadata, module).toList()
override suspend fun updateDependencyInModule(operationMetadata: DependencyOperationMetadata, module: ProjectModule) =
[email protected](operationMetadata, module).toList()
override suspend fun declaredDependenciesInModule(module: ProjectModule) =
[email protected](module).toList()
override suspend fun resolvedDependenciesInModule(module: ProjectModule, scopes: Set<String>) =
[email protected](module, scopes).toList()
override suspend fun addRepositoryToModule(repository: UnifiedDependencyRepository, module: ProjectModule) =
[email protected](repository, module).toList()
override suspend fun removeRepositoryFromModule(repository: UnifiedDependencyRepository, module: ProjectModule) =
[email protected](repository, module).toList()
override suspend fun listRepositoriesInModule(module: ProjectModule) =
[email protected](module).toList()
}
internal fun AsyncProjectModuleOperationProvider.asCoroutine() = object : CoroutineProjectModuleOperationProvider {
override fun hasSupportFor(project: Project, psiFile: PsiFile?) = [email protected](project, psiFile)
override fun hasSupportFor(projectModuleType: ProjectModuleType) = [email protected](projectModuleType)
override suspend fun addDependencyToModule(operationMetadata: DependencyOperationMetadata, module: ProjectModule) =
[email protected](operationMetadata, module).await().toList()
override suspend fun removeDependencyFromModule(operationMetadata: DependencyOperationMetadata, module: ProjectModule) =
[email protected](operationMetadata, module).await().toList()
override suspend fun updateDependencyInModule(operationMetadata: DependencyOperationMetadata, module: ProjectModule) =
[email protected](operationMetadata, module).await().toList()
override suspend fun declaredDependenciesInModule(module: ProjectModule) =
[email protected](module).await().toList()
override suspend fun resolvedDependenciesInModule(module: ProjectModule, scopes: Set<String>) =
[email protected](module, scopes).await().toList()
override suspend fun addRepositoryToModule(repository: UnifiedDependencyRepository, module: ProjectModule) =
[email protected](repository, module).await().toList()
override suspend fun removeRepositoryFromModule(repository: UnifiedDependencyRepository, module: ProjectModule) =
[email protected](repository, module).await().toList()
override suspend fun listRepositoriesInModule(module: ProjectModule) =
[email protected](module).await().toList()
}
| apache-2.0 | d6702b0e0991a8372998796a293fcd38 | 41.59593 | 134 | 0.716509 | 4.963753 | false | false | false | false |
mdaniel/intellij-community | platform/platform-impl/src/com/intellij/openapi/fileEditor/impl/OpenFilesActivity.kt | 1 | 2519 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.openapi.fileEditor.impl
import com.intellij.ide.IdeBundle
import com.intellij.ide.util.RunOnceUtil
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.EDT
import com.intellij.openapi.application.ModalityState
import com.intellij.openapi.application.asContextElement
import com.intellij.openapi.fileEditor.FileEditorManager
import com.intellij.openapi.fileEditor.TextEditorWithPreview
import com.intellij.openapi.options.advanced.AdvancedSettings
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.project.Project
import com.intellij.openapi.project.ex.ProjectEx
import com.intellij.openapi.project.guessProjectDir
import com.intellij.openapi.project.isNotificationSilentMode
import com.intellij.openapi.startup.InitProjectActivity
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
internal class OpenFilesActivity : InitProjectActivity {
override suspend fun run(project: Project) {
ProgressManager.getInstance().progressIndicator?.text = IdeBundle.message("progress.text.reopening.files")
val fileEditorManager = FileEditorManager.getInstance(project) as? FileEditorManagerImpl ?: return
withContext(Dispatchers.EDT) {
fileEditorManager.init()
}
val editorSplitters = fileEditorManager.mainSplitters
val panel = editorSplitters.restoreEditors()
(project as ProjectEx).coroutineScope.launch(Dispatchers.EDT + ModalityState.NON_MODAL.asContextElement()) {
panel?.let(editorSplitters::doOpenFiles)
fileEditorManager.initDockableContentFactory()
EditorsSplitters.stopOpenFilesActivity(project)
if (!fileEditorManager.hasOpenFiles() && !isNotificationSilentMode(project)) {
project.putUserData(FileEditorManagerImpl.NOTHING_WAS_OPENED_ON_START, true)
if (AdvancedSettings.getBoolean("ide.open.readme.md.on.startup")) {
RunOnceUtil.runOnceForProject(project, "ShowReadmeOnStart") {
findAndOpenReadme(project)
}
}
}
}
}
}
private fun findAndOpenReadme(project: Project) {
val readme = project.guessProjectDir()?.findChild("README.md") ?: return
if (!readme.isDirectory) {
ApplicationManager.getApplication().invokeLater({ TextEditorWithPreview.openPreviewForFile(project, readme) }, project.disposed)
}
} | apache-2.0 | 23ebe02f37960a3fc97ffa9def8f8e64 | 44.818182 | 132 | 0.793966 | 4.690875 | false | false | false | false |
hsson/card-balance-app | app/src/main/java/se/creotec/chscardbalance2/util/NotificationsHelper.kt | 1 | 3271 | // Copyright (c) 2017 Alexander Håkansson
//
// This software is released under the MIT License.
// https://opensource.org/licenses/MIT
package se.creotec.chscardbalance2.util
import android.app.Notification
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.graphics.BitmapFactory
import android.support.v4.app.NotificationCompat
import android.support.v4.app.TaskStackBuilder
import se.creotec.chscardbalance2.Constants
import se.creotec.chscardbalance2.GlobalState
import se.creotec.chscardbalance2.R
import se.creotec.chscardbalance2.controller.MainActivity
object NotificationsHelper {
fun maybeNotify(context: Context, global: GlobalState) {
val roundedBalance = Math.round(global.model.cardData.cardBalance).toInt()
val limit = global.model.notifications.lowBalanceNotificationLimit
val lastNotifiedBalance = global.model.notifications.lowBalanceLastNotifiedBalance
val enabled = global.model.notifications.isLowBalanceNotificationsEnabled
if (enabled && roundedBalance <= limit && roundedBalance != lastNotifiedBalance) {
global.model.notifications.lowBalanceLastNotifiedBalance = roundedBalance
global.saveNotificationData()
showLowBalanceNotification(context, roundedBalance)
}
}
fun cancelAll(context: Context) {
val manager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
manager.cancelAll()
}
private fun showLowBalanceNotification(context: Context, roundedBalance: Int) {
val primaryColor = context.getColor(R.color.color_primary)
val largeIcon = BitmapFactory.decodeResource(context.resources, R.mipmap.ic_launcher)
val wearableBkg = BitmapFactory.decodeResource(context.resources, R.drawable.bkg_wearable)
val contentText = context.getString(R.string.notification_text, roundedBalance.toString())
val wearableExtended = NotificationCompat.WearableExtender().setBackground(wearableBkg)
val notificationBuilder = NotificationCompat.Builder(context, Constants.NOTIFICATION_CHANNEL_BALANCE)
.setSmallIcon(R.drawable.ic_app_notification)
.setLargeIcon(largeIcon)
.setContentTitle(context.getString(R.string.notification_title))
.setContentText(contentText)
.setAutoCancel(true)
.setDefaults(Notification.DEFAULT_SOUND or Notification.DEFAULT_VIBRATE)
.setColor(primaryColor)
.setLights(primaryColor, 1500, 1000)
.extend(wearableExtended)
val mainActivityIntent = Intent(context, MainActivity::class.java)
val stackBuilder = TaskStackBuilder.create(context)
stackBuilder.addParentStack(MainActivity::class.java)
stackBuilder.addNextIntent(mainActivityIntent)
val pendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT)
notificationBuilder.setContentIntent(pendingIntent)
val manager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
manager.notify(0, notificationBuilder.build())
}
} | mit | 05abf39b5c15bd154a9240658049e6b7 | 46.405797 | 109 | 0.746483 | 5.07764 | false | false | false | false |
GunoH/intellij-community | platform/vcs-log/impl/src/com/intellij/vcs/log/data/MiniDetailsGetter.kt | 4 | 7114 | // 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.vcs.log.data
import com.github.benmanes.caffeine.cache.Caffeine
import com.intellij.openapi.Disposable
import com.intellij.openapi.diagnostic.thisLogger
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.registry.Registry
import com.intellij.openapi.vcs.VcsException
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.util.Consumer
import com.intellij.util.concurrency.annotations.RequiresBackgroundThread
import com.intellij.util.concurrency.annotations.RequiresEdt
import com.intellij.vcs.log.VcsCommitMetadata
import com.intellij.vcs.log.VcsLogObjectsFactory
import com.intellij.vcs.log.VcsLogProvider
import com.intellij.vcs.log.data.index.IndexedDetails
import com.intellij.vcs.log.data.index.VcsLogIndex
import com.intellij.vcs.log.runInEdt
import com.intellij.vcs.log.util.SequentialLimitedLifoExecutor
import it.unimi.dsi.fastutil.ints.*
import java.awt.EventQueue
class MiniDetailsGetter internal constructor(project: Project,
storage: VcsLogStorage,
logProviders: Map<VirtualFile, VcsLogProvider>,
private val topCommitsDetailsCache: TopCommitsCache,
private val index: VcsLogIndex,
parentDisposable: Disposable) :
AbstractDataGetter<VcsCommitMetadata>(storage, logProviders, parentDisposable) {
private val factory = project.getService(VcsLogObjectsFactory::class.java)
private val cache = Caffeine.newBuilder().maximumSize(10000).build<Int, VcsCommitMetadata>()
private val loader = SequentialLimitedLifoExecutor(this, MAX_LOADING_TASKS) { task: TaskDescriptor ->
doLoadCommitsData(task.commits, this::saveInCache)
notifyLoaded()
}
/**
* The sequence number of the current "loading" task.
*/
private var currentTaskIndex: Long = 0
private val loadingFinishedListeners = ArrayList<Runnable>()
override fun getCommitData(commit: Int): VcsCommitMetadata {
return getCommitData(commit, emptySet())
}
fun getCommitData(commit: Int, commitsToLoad: Iterable<Int>): VcsCommitMetadata {
val details = getCommitDataIfAvailable(commit)
if (details != null) return details
if (!EventQueue.isDispatchThread()) {
thisLogger().assertTrue(commitsToLoad.none(), "Requesting loading commits in background thread is not supported.")
return createPlaceholderCommit(commit, 0 /*not used as this commit is not cached*/)
}
val toLoad = IntOpenHashSet(commitsToLoad.iterator())
val taskNumber = currentTaskIndex++
toLoad.forEach(IntConsumer { cacheCommit(it, taskNumber) })
loader.queue(TaskDescriptor(toLoad))
return cache.getIfPresent(commit) ?: createPlaceholderCommit(commit, taskNumber)
}
override fun getCommitDataIfAvailable(commit: Int): VcsCommitMetadata? {
if (!EventQueue.isDispatchThread()) {
return cache.getIfPresent(commit) ?: topCommitsDetailsCache[commit]
}
val details = cache.getIfPresent(commit)
if (details != null) {
if (details is LoadingDetailsImpl) {
if (details.loadingTaskIndex <= currentTaskIndex - MAX_LOADING_TASKS) {
// don't let old "loading" requests stay in the cache forever
cache.asMap().remove(commit, details)
return null
}
}
return details
}
return topCommitsDetailsCache[commit]
}
override fun getCommitDataIfAvailable(commits: List<Int>): Int2ObjectMap<VcsCommitMetadata> {
val detailsFromCache = commits.associateNotNull {
val details = getCommitDataIfAvailable(it)
if (details is LoadingDetails) {
return@associateNotNull null
}
details
}
return detailsFromCache
}
override fun saveInCache(commit: Int, details: VcsCommitMetadata) = cache.put(commit, details)
@RequiresEdt
private fun cacheCommit(commitId: Int, taskNumber: Long) {
// fill the cache with temporary "Loading" values to avoid producing queries for each commit that has not been cached yet,
// even if it will be loaded within a previous query
if (cache.getIfPresent(commitId) == null) {
cache.put(commitId, createPlaceholderCommit(commitId, taskNumber))
}
}
@RequiresEdt
override fun cacheCommits(commits: IntOpenHashSet) {
val taskNumber = currentTaskIndex++
commits.forEach(IntConsumer { commit -> cacheCommit(commit, taskNumber) })
}
@RequiresBackgroundThread
@Throws(VcsException::class)
override fun doLoadCommitsData(commits: IntSet, consumer: Consumer<in VcsCommitMetadata>) {
val dataGetter = index.dataGetter
if (dataGetter == null) {
super.doLoadCommitsData(commits, consumer)
return
}
val notIndexed = IntOpenHashSet()
commits.forEach(IntConsumer { commit: Int ->
val metadata = IndexedDetails.createMetadata(commit, dataGetter, storage, factory)
if (metadata == null) {
notIndexed.add(commit)
}
else {
consumer.consume(metadata)
}
})
if (!notIndexed.isEmpty()) {
super.doLoadCommitsData(notIndexed, consumer)
}
}
@RequiresBackgroundThread
@Throws(VcsException::class)
override fun doLoadCommitsDataFromProvider(logProvider: VcsLogProvider,
root: VirtualFile,
hashes: List<String>,
consumer: Consumer<in VcsCommitMetadata>) {
logProvider.readMetadata(root, hashes, consumer)
}
private fun createPlaceholderCommit(commit: Int, taskNumber: Long): VcsCommitMetadata {
val dataGetter = index.dataGetter
return if (dataGetter != null && Registry.`is`("vcs.log.use.indexed.details")) {
IndexedDetails(dataGetter, storage, commit, taskNumber)
}
else {
LoadingDetailsImpl(storage, commit, taskNumber)
}
}
/**
* This listener will be notified when any details loading process finishes.
* The notification will happen in the EDT.
*/
fun addDetailsLoadedListener(runnable: Runnable) {
loadingFinishedListeners.add(runnable)
}
fun removeDetailsLoadedListener(runnable: Runnable) {
loadingFinishedListeners.remove(runnable)
}
override fun notifyLoaded() {
runInEdt(disposableFlag) {
for (loadingFinishedListener in loadingFinishedListeners) {
loadingFinishedListener.run()
}
}
}
override fun dispose() {
loadingFinishedListeners.clear()
}
private class TaskDescriptor(val commits: IntSet)
companion object {
private const val MAX_LOADING_TASKS = 10
private inline fun <V> Iterable<Int>.associateNotNull(transform: (Int) -> V?): Int2ObjectMap<V> {
val result = Int2ObjectOpenHashMap<V>()
for (element in this) {
val value = transform(element) ?: continue
result[element] = value
}
return result
}
}
} | apache-2.0 | 1bd738c587700124bfd5d28dee878c4b | 36.251309 | 126 | 0.698341 | 4.745831 | false | false | false | false |
AsamK/TextSecure | app/src/main/java/org/thoughtcrime/securesms/components/settings/app/subscription/errors/DonationErrorDialogs.kt | 2 | 2830 | package org.thoughtcrime.securesms.components.settings.app.subscription.errors
import android.content.Context
import android.content.DialogInterface
import com.google.android.material.dialog.MaterialAlertDialogBuilder
import org.thoughtcrime.securesms.R
import org.thoughtcrime.securesms.components.settings.app.AppSettingsActivity
import org.thoughtcrime.securesms.help.HelpFragment
import org.thoughtcrime.securesms.util.CommunicationActions
/**
* Donation Error Dialogs.
*/
object DonationErrorDialogs {
/**
* Displays a dialog, and returns a handle to it for dismissal.
*/
fun show(context: Context, throwable: Throwable?, callback: DialogCallback): DialogInterface {
val builder = MaterialAlertDialogBuilder(context)
builder.setOnDismissListener { callback.onDialogDismissed() }
val params = DonationErrorParams.create(context, throwable, callback)
builder.setTitle(params.title)
.setMessage(params.message)
if (params.positiveAction != null) {
builder.setPositiveButton(params.positiveAction.label) { _, _ -> params.positiveAction.action() }
}
if (params.negativeAction != null) {
builder.setNegativeButton(params.negativeAction.label) { _, _ -> params.negativeAction.action() }
}
return builder.show()
}
open class DialogCallback : DonationErrorParams.Callback<Unit> {
override fun onCancel(context: Context): DonationErrorParams.ErrorAction<Unit>? {
return DonationErrorParams.ErrorAction(
label = android.R.string.cancel,
action = {}
)
}
override fun onOk(context: Context): DonationErrorParams.ErrorAction<Unit>? {
return DonationErrorParams.ErrorAction(
label = android.R.string.ok,
action = {}
)
}
override fun onGoToGooglePay(context: Context): DonationErrorParams.ErrorAction<Unit>? {
return DonationErrorParams.ErrorAction(
label = R.string.DeclineCode__go_to_google_pay,
action = {
CommunicationActions.openBrowserLink(context, context.getString(R.string.google_pay_url))
}
)
}
override fun onLearnMore(context: Context): DonationErrorParams.ErrorAction<Unit>? {
return DonationErrorParams.ErrorAction(
label = R.string.DeclineCode__learn_more,
action = {
CommunicationActions.openBrowserLink(context, context.getString(R.string.donation_decline_code_error_url))
}
)
}
override fun onContactSupport(context: Context): DonationErrorParams.ErrorAction<Unit> {
return DonationErrorParams.ErrorAction(
label = R.string.Subscription__contact_support,
action = {
context.startActivity(AppSettingsActivity.help(context, HelpFragment.DONATION_INDEX))
}
)
}
open fun onDialogDismissed() = Unit
}
}
| gpl-3.0 | 898f42c8f8c175ec16c816c4112989d4 | 32.690476 | 116 | 0.714841 | 4.484945 | false | false | false | false |
ktorio/ktor | ktor-server/ktor-server-plugins/ktor-server-locations/jvm/src/io/ktor/server/locations/Locations.kt | 1 | 5941 | /*
* Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license.
*/
package io.ktor.server.locations
import io.ktor.http.*
import io.ktor.server.application.*
import io.ktor.server.routing.*
import io.ktor.util.*
import kotlin.reflect.*
/**
* Ktor plugin that allows to handle and construct routes in a typed way.
*
* You have to create data classes/objects representing parameterized routes and annotate them with [Location].
* Then you can register sub-routes and handlers for those locations and create links to them
* using [Locations.href].
*/
@Suppress("unused")
@KtorExperimentalLocationsAPI
@KtorDsl
public open class Locations constructor(
application: Application,
routeService: LocationRouteService
) {
/**
* Creates Locations service extracting path information from @Location annotation
*/
@OptIn(KtorExperimentalLocationsAPI::class)
public constructor(application: Application) : this(application, LocationAttributeRouteService())
private val implementation: LocationsImpl = BackwardCompatibleImpl(application, routeService)
/**
* All locations registered at the moment (Immutable list).
*/
@KtorExperimentalLocationsAPI
public val registeredLocations: List<LocationInfo>
get() = implementation.registeredLocations
/**
* Resolves parameters in a [call] to an instance of specified [locationClass].
*/
@Suppress("UNCHECKED_CAST")
public fun <T : Any> resolve(locationClass: KClass<*>, call: ApplicationCall): T {
return resolve(locationClass, call.parameters)
}
/**
* Resolves [parameters] to an instance of specified [locationClass].
*/
@Suppress("UNCHECKED_CAST")
public fun <T : Any> resolve(locationClass: KClass<*>, parameters: Parameters): T {
val info = implementation.getOrCreateInfo(locationClass)
return implementation.instantiate(info, parameters) as T
}
/**
* Resolves [parameters] to an instance of specified [T].
*/
@KtorExperimentalLocationsAPI
public inline fun <reified T : Any> resolve(parameters: Parameters): T {
return resolve(T::class, parameters) as T
}
/**
* Resolves parameters in a [call] to an instance of specified [T].
*/
@KtorExperimentalLocationsAPI
public inline fun <reified T : Any> resolve(call: ApplicationCall): T {
return resolve(T::class, call)
}
/**
* Constructs the url for [location].
*
* The class of [location] instance **must** be annotated with [Location].
*/
public fun href(location: Any): String = implementation.href(location)
internal fun href(location: Any, builder: URLBuilder) {
implementation.href(location, builder)
}
@OptIn(KtorExperimentalLocationsAPI::class)
private fun createEntry(parent: Route, info: LocationInfo): Route {
val hierarchyEntry = info.parent?.let { createEntry(parent, it) } ?: parent
return hierarchyEntry.createRouteFromPath(info.path)
}
/**
* Creates all necessary routing entries to match specified [locationClass].
*/
public fun createEntry(parent: Route, locationClass: KClass<*>): Route {
val info = implementation.getOrCreateInfo(locationClass)
val pathRoute = createEntry(parent, info)
return info.queryParameters.fold(pathRoute) { entry, query ->
val selector = if (query.isOptional) {
OptionalParameterRouteSelector(query.name)
} else {
ParameterRouteSelector(query.name)
}
entry.createChild(selector)
}
}
/**
* Configuration for [Locations].
*/
@KtorDsl
public class Configuration {
/**
* Specifies an alternative routing service. Default is [LocationAttributeRouteService].
*/
@KtorExperimentalLocationsAPI
public var routeService: LocationRouteService? = null
}
/**
* Installable plugin for [Locations].
*/
public companion object Plugin : BaseApplicationPlugin<Application, Configuration, Locations> {
override val key: AttributeKey<Locations> = AttributeKey("Locations")
@OptIn(KtorExperimentalLocationsAPI::class)
override fun install(pipeline: Application, configure: Configuration.() -> Unit): Locations {
val configuration = Configuration().apply(configure)
val routeService = configuration.routeService ?: LocationAttributeRouteService()
return Locations(pipeline, routeService)
}
}
}
/**
* Provides services for extracting routing information from a location class.
*/
@KtorExperimentalLocationsAPI
public interface LocationRouteService {
/**
* Retrieves routing information from a given [locationClass].
* @return routing pattern, or null if a given class doesn't represent a route.
*/
public fun findRoute(locationClass: KClass<*>): String?
}
/**
* Implements [LocationRouteService] by extracting routing information from a [Location] annotation.
*/
@KtorExperimentalLocationsAPI
public class LocationAttributeRouteService : LocationRouteService {
private inline fun <reified T : Annotation> KAnnotatedElement.annotation(): T? {
return annotations.singleOrNull { it.annotationClass == T::class } as T?
}
override fun findRoute(locationClass: KClass<*>): String? = locationClass.annotation<Location>()?.path
}
/**
* Exception indicating that route parameters in curly brackets do not match class properties.
*/
@KtorExperimentalLocationsAPI
public class LocationRoutingException(message: String) : Exception(message)
@KtorExperimentalLocationsAPI
internal class LocationPropertyInfoImpl(
name: String,
val kGetter: KProperty1.Getter<Any, Any?>,
isOptional: Boolean
) : LocationPropertyInfo(name, isOptional)
| apache-2.0 | f52e16db7a01354e17b82ba171b9ace8 | 33.74269 | 119 | 0.696011 | 4.733865 | false | true | false | false |
Philip-Trettner/GlmKt | GlmKt/src/glm/vec/Short/ShortVec3.kt | 1 | 25475 | package glm
data class ShortVec3(val x: Short, val y: Short, val z: Short) {
// Initializes each element by evaluating init from 0 until 2
constructor(init: (Int) -> Short) : this(init(0), init(1), init(2))
operator fun get(idx: Int): Short = when (idx) {
0 -> x
1 -> y
2 -> z
else -> throw IndexOutOfBoundsException("index $idx is out of bounds")
}
// Operators
operator fun inc(): ShortVec3 = ShortVec3(x.inc(), y.inc(), z.inc())
operator fun dec(): ShortVec3 = ShortVec3(x.dec(), y.dec(), z.dec())
operator fun unaryPlus(): IntVec3 = IntVec3(+x, +y, +z)
operator fun unaryMinus(): IntVec3 = IntVec3(-x, -y, -z)
operator fun plus(rhs: ShortVec3): IntVec3 = IntVec3(x + rhs.x, y + rhs.y, z + rhs.z)
operator fun minus(rhs: ShortVec3): IntVec3 = IntVec3(x - rhs.x, y - rhs.y, z - rhs.z)
operator fun times(rhs: ShortVec3): IntVec3 = IntVec3(x * rhs.x, y * rhs.y, z * rhs.z)
operator fun div(rhs: ShortVec3): IntVec3 = IntVec3(x / rhs.x, y / rhs.y, z / rhs.z)
operator fun rem(rhs: ShortVec3): IntVec3 = IntVec3(x % rhs.x, y % rhs.y, z % rhs.z)
operator fun plus(rhs: Short): IntVec3 = IntVec3(x + rhs, y + rhs, z + rhs)
operator fun minus(rhs: Short): IntVec3 = IntVec3(x - rhs, y - rhs, z - rhs)
operator fun times(rhs: Short): IntVec3 = IntVec3(x * rhs, y * rhs, z * rhs)
operator fun div(rhs: Short): IntVec3 = IntVec3(x / rhs, y / rhs, z / rhs)
operator fun rem(rhs: Short): IntVec3 = IntVec3(x % rhs, y % rhs, z % rhs)
inline fun map(func: (Short) -> Short): ShortVec3 = ShortVec3(func(x), func(y), func(z))
fun toList(): List<Short> = listOf(x, y, z)
// Predefined vector constants
companion object Constants {
val zero: ShortVec3 = ShortVec3(0.toShort(), 0.toShort(), 0.toShort())
val ones: ShortVec3 = ShortVec3(1.toShort(), 1.toShort(), 1.toShort())
val unitX: ShortVec3 = ShortVec3(1.toShort(), 0.toShort(), 0.toShort())
val unitY: ShortVec3 = ShortVec3(0.toShort(), 1.toShort(), 0.toShort())
val unitZ: ShortVec3 = ShortVec3(0.toShort(), 0.toShort(), 1.toShort())
}
// Conversions to Float
fun toVec(): Vec3 = Vec3(x.toFloat(), y.toFloat(), z.toFloat())
inline fun toVec(conv: (Short) -> Float): Vec3 = Vec3(conv(x), conv(y), conv(z))
fun toVec2(): Vec2 = Vec2(x.toFloat(), y.toFloat())
inline fun toVec2(conv: (Short) -> Float): Vec2 = Vec2(conv(x), conv(y))
fun toVec3(): Vec3 = Vec3(x.toFloat(), y.toFloat(), z.toFloat())
inline fun toVec3(conv: (Short) -> Float): Vec3 = Vec3(conv(x), conv(y), conv(z))
fun toVec4(w: Float = 0f): Vec4 = Vec4(x.toFloat(), y.toFloat(), z.toFloat(), w)
inline fun toVec4(w: Float = 0f, conv: (Short) -> Float): Vec4 = Vec4(conv(x), conv(y), conv(z), w)
// Conversions to Float
fun toMutableVec(): MutableVec3 = MutableVec3(x.toFloat(), y.toFloat(), z.toFloat())
inline fun toMutableVec(conv: (Short) -> Float): MutableVec3 = MutableVec3(conv(x), conv(y), conv(z))
fun toMutableVec2(): MutableVec2 = MutableVec2(x.toFloat(), y.toFloat())
inline fun toMutableVec2(conv: (Short) -> Float): MutableVec2 = MutableVec2(conv(x), conv(y))
fun toMutableVec3(): MutableVec3 = MutableVec3(x.toFloat(), y.toFloat(), z.toFloat())
inline fun toMutableVec3(conv: (Short) -> Float): MutableVec3 = MutableVec3(conv(x), conv(y), conv(z))
fun toMutableVec4(w: Float = 0f): MutableVec4 = MutableVec4(x.toFloat(), y.toFloat(), z.toFloat(), w)
inline fun toMutableVec4(w: Float = 0f, conv: (Short) -> Float): MutableVec4 = MutableVec4(conv(x), conv(y), conv(z), w)
// Conversions to Double
fun toDoubleVec(): DoubleVec3 = DoubleVec3(x.toDouble(), y.toDouble(), z.toDouble())
inline fun toDoubleVec(conv: (Short) -> Double): DoubleVec3 = DoubleVec3(conv(x), conv(y), conv(z))
fun toDoubleVec2(): DoubleVec2 = DoubleVec2(x.toDouble(), y.toDouble())
inline fun toDoubleVec2(conv: (Short) -> Double): DoubleVec2 = DoubleVec2(conv(x), conv(y))
fun toDoubleVec3(): DoubleVec3 = DoubleVec3(x.toDouble(), y.toDouble(), z.toDouble())
inline fun toDoubleVec3(conv: (Short) -> Double): DoubleVec3 = DoubleVec3(conv(x), conv(y), conv(z))
fun toDoubleVec4(w: Double = 0.0): DoubleVec4 = DoubleVec4(x.toDouble(), y.toDouble(), z.toDouble(), w)
inline fun toDoubleVec4(w: Double = 0.0, conv: (Short) -> Double): DoubleVec4 = DoubleVec4(conv(x), conv(y), conv(z), w)
// Conversions to Double
fun toMutableDoubleVec(): MutableDoubleVec3 = MutableDoubleVec3(x.toDouble(), y.toDouble(), z.toDouble())
inline fun toMutableDoubleVec(conv: (Short) -> Double): MutableDoubleVec3 = MutableDoubleVec3(conv(x), conv(y), conv(z))
fun toMutableDoubleVec2(): MutableDoubleVec2 = MutableDoubleVec2(x.toDouble(), y.toDouble())
inline fun toMutableDoubleVec2(conv: (Short) -> Double): MutableDoubleVec2 = MutableDoubleVec2(conv(x), conv(y))
fun toMutableDoubleVec3(): MutableDoubleVec3 = MutableDoubleVec3(x.toDouble(), y.toDouble(), z.toDouble())
inline fun toMutableDoubleVec3(conv: (Short) -> Double): MutableDoubleVec3 = MutableDoubleVec3(conv(x), conv(y), conv(z))
fun toMutableDoubleVec4(w: Double = 0.0): MutableDoubleVec4 = MutableDoubleVec4(x.toDouble(), y.toDouble(), z.toDouble(), w)
inline fun toMutableDoubleVec4(w: Double = 0.0, conv: (Short) -> Double): MutableDoubleVec4 = MutableDoubleVec4(conv(x), conv(y), conv(z), w)
// Conversions to Int
fun toIntVec(): IntVec3 = IntVec3(x.toInt(), y.toInt(), z.toInt())
inline fun toIntVec(conv: (Short) -> Int): IntVec3 = IntVec3(conv(x), conv(y), conv(z))
fun toIntVec2(): IntVec2 = IntVec2(x.toInt(), y.toInt())
inline fun toIntVec2(conv: (Short) -> Int): IntVec2 = IntVec2(conv(x), conv(y))
fun toIntVec3(): IntVec3 = IntVec3(x.toInt(), y.toInt(), z.toInt())
inline fun toIntVec3(conv: (Short) -> Int): IntVec3 = IntVec3(conv(x), conv(y), conv(z))
fun toIntVec4(w: Int = 0): IntVec4 = IntVec4(x.toInt(), y.toInt(), z.toInt(), w)
inline fun toIntVec4(w: Int = 0, conv: (Short) -> Int): IntVec4 = IntVec4(conv(x), conv(y), conv(z), w)
// Conversions to Int
fun toMutableIntVec(): MutableIntVec3 = MutableIntVec3(x.toInt(), y.toInt(), z.toInt())
inline fun toMutableIntVec(conv: (Short) -> Int): MutableIntVec3 = MutableIntVec3(conv(x), conv(y), conv(z))
fun toMutableIntVec2(): MutableIntVec2 = MutableIntVec2(x.toInt(), y.toInt())
inline fun toMutableIntVec2(conv: (Short) -> Int): MutableIntVec2 = MutableIntVec2(conv(x), conv(y))
fun toMutableIntVec3(): MutableIntVec3 = MutableIntVec3(x.toInt(), y.toInt(), z.toInt())
inline fun toMutableIntVec3(conv: (Short) -> Int): MutableIntVec3 = MutableIntVec3(conv(x), conv(y), conv(z))
fun toMutableIntVec4(w: Int = 0): MutableIntVec4 = MutableIntVec4(x.toInt(), y.toInt(), z.toInt(), w)
inline fun toMutableIntVec4(w: Int = 0, conv: (Short) -> Int): MutableIntVec4 = MutableIntVec4(conv(x), conv(y), conv(z), w)
// Conversions to Long
fun toLongVec(): LongVec3 = LongVec3(x.toLong(), y.toLong(), z.toLong())
inline fun toLongVec(conv: (Short) -> Long): LongVec3 = LongVec3(conv(x), conv(y), conv(z))
fun toLongVec2(): LongVec2 = LongVec2(x.toLong(), y.toLong())
inline fun toLongVec2(conv: (Short) -> Long): LongVec2 = LongVec2(conv(x), conv(y))
fun toLongVec3(): LongVec3 = LongVec3(x.toLong(), y.toLong(), z.toLong())
inline fun toLongVec3(conv: (Short) -> Long): LongVec3 = LongVec3(conv(x), conv(y), conv(z))
fun toLongVec4(w: Long = 0L): LongVec4 = LongVec4(x.toLong(), y.toLong(), z.toLong(), w)
inline fun toLongVec4(w: Long = 0L, conv: (Short) -> Long): LongVec4 = LongVec4(conv(x), conv(y), conv(z), w)
// Conversions to Long
fun toMutableLongVec(): MutableLongVec3 = MutableLongVec3(x.toLong(), y.toLong(), z.toLong())
inline fun toMutableLongVec(conv: (Short) -> Long): MutableLongVec3 = MutableLongVec3(conv(x), conv(y), conv(z))
fun toMutableLongVec2(): MutableLongVec2 = MutableLongVec2(x.toLong(), y.toLong())
inline fun toMutableLongVec2(conv: (Short) -> Long): MutableLongVec2 = MutableLongVec2(conv(x), conv(y))
fun toMutableLongVec3(): MutableLongVec3 = MutableLongVec3(x.toLong(), y.toLong(), z.toLong())
inline fun toMutableLongVec3(conv: (Short) -> Long): MutableLongVec3 = MutableLongVec3(conv(x), conv(y), conv(z))
fun toMutableLongVec4(w: Long = 0L): MutableLongVec4 = MutableLongVec4(x.toLong(), y.toLong(), z.toLong(), w)
inline fun toMutableLongVec4(w: Long = 0L, conv: (Short) -> Long): MutableLongVec4 = MutableLongVec4(conv(x), conv(y), conv(z), w)
// Conversions to Short
fun toShortVec(): ShortVec3 = ShortVec3(x, y, z)
inline fun toShortVec(conv: (Short) -> Short): ShortVec3 = ShortVec3(conv(x), conv(y), conv(z))
fun toShortVec2(): ShortVec2 = ShortVec2(x, y)
inline fun toShortVec2(conv: (Short) -> Short): ShortVec2 = ShortVec2(conv(x), conv(y))
fun toShortVec3(): ShortVec3 = ShortVec3(x, y, z)
inline fun toShortVec3(conv: (Short) -> Short): ShortVec3 = ShortVec3(conv(x), conv(y), conv(z))
fun toShortVec4(w: Short = 0.toShort()): ShortVec4 = ShortVec4(x, y, z, w)
inline fun toShortVec4(w: Short = 0.toShort(), conv: (Short) -> Short): ShortVec4 = ShortVec4(conv(x), conv(y), conv(z), w)
// Conversions to Short
fun toMutableShortVec(): MutableShortVec3 = MutableShortVec3(x, y, z)
inline fun toMutableShortVec(conv: (Short) -> Short): MutableShortVec3 = MutableShortVec3(conv(x), conv(y), conv(z))
fun toMutableShortVec2(): MutableShortVec2 = MutableShortVec2(x, y)
inline fun toMutableShortVec2(conv: (Short) -> Short): MutableShortVec2 = MutableShortVec2(conv(x), conv(y))
fun toMutableShortVec3(): MutableShortVec3 = MutableShortVec3(x, y, z)
inline fun toMutableShortVec3(conv: (Short) -> Short): MutableShortVec3 = MutableShortVec3(conv(x), conv(y), conv(z))
fun toMutableShortVec4(w: Short = 0.toShort()): MutableShortVec4 = MutableShortVec4(x, y, z, w)
inline fun toMutableShortVec4(w: Short = 0.toShort(), conv: (Short) -> Short): MutableShortVec4 = MutableShortVec4(conv(x), conv(y), conv(z), w)
// Conversions to Byte
fun toByteVec(): ByteVec3 = ByteVec3(x.toByte(), y.toByte(), z.toByte())
inline fun toByteVec(conv: (Short) -> Byte): ByteVec3 = ByteVec3(conv(x), conv(y), conv(z))
fun toByteVec2(): ByteVec2 = ByteVec2(x.toByte(), y.toByte())
inline fun toByteVec2(conv: (Short) -> Byte): ByteVec2 = ByteVec2(conv(x), conv(y))
fun toByteVec3(): ByteVec3 = ByteVec3(x.toByte(), y.toByte(), z.toByte())
inline fun toByteVec3(conv: (Short) -> Byte): ByteVec3 = ByteVec3(conv(x), conv(y), conv(z))
fun toByteVec4(w: Byte = 0.toByte()): ByteVec4 = ByteVec4(x.toByte(), y.toByte(), z.toByte(), w)
inline fun toByteVec4(w: Byte = 0.toByte(), conv: (Short) -> Byte): ByteVec4 = ByteVec4(conv(x), conv(y), conv(z), w)
// Conversions to Byte
fun toMutableByteVec(): MutableByteVec3 = MutableByteVec3(x.toByte(), y.toByte(), z.toByte())
inline fun toMutableByteVec(conv: (Short) -> Byte): MutableByteVec3 = MutableByteVec3(conv(x), conv(y), conv(z))
fun toMutableByteVec2(): MutableByteVec2 = MutableByteVec2(x.toByte(), y.toByte())
inline fun toMutableByteVec2(conv: (Short) -> Byte): MutableByteVec2 = MutableByteVec2(conv(x), conv(y))
fun toMutableByteVec3(): MutableByteVec3 = MutableByteVec3(x.toByte(), y.toByte(), z.toByte())
inline fun toMutableByteVec3(conv: (Short) -> Byte): MutableByteVec3 = MutableByteVec3(conv(x), conv(y), conv(z))
fun toMutableByteVec4(w: Byte = 0.toByte()): MutableByteVec4 = MutableByteVec4(x.toByte(), y.toByte(), z.toByte(), w)
inline fun toMutableByteVec4(w: Byte = 0.toByte(), conv: (Short) -> Byte): MutableByteVec4 = MutableByteVec4(conv(x), conv(y), conv(z), w)
// Conversions to Char
fun toCharVec(): CharVec3 = CharVec3(x.toChar(), y.toChar(), z.toChar())
inline fun toCharVec(conv: (Short) -> Char): CharVec3 = CharVec3(conv(x), conv(y), conv(z))
fun toCharVec2(): CharVec2 = CharVec2(x.toChar(), y.toChar())
inline fun toCharVec2(conv: (Short) -> Char): CharVec2 = CharVec2(conv(x), conv(y))
fun toCharVec3(): CharVec3 = CharVec3(x.toChar(), y.toChar(), z.toChar())
inline fun toCharVec3(conv: (Short) -> Char): CharVec3 = CharVec3(conv(x), conv(y), conv(z))
fun toCharVec4(w: Char): CharVec4 = CharVec4(x.toChar(), y.toChar(), z.toChar(), w)
inline fun toCharVec4(w: Char, conv: (Short) -> Char): CharVec4 = CharVec4(conv(x), conv(y), conv(z), w)
// Conversions to Char
fun toMutableCharVec(): MutableCharVec3 = MutableCharVec3(x.toChar(), y.toChar(), z.toChar())
inline fun toMutableCharVec(conv: (Short) -> Char): MutableCharVec3 = MutableCharVec3(conv(x), conv(y), conv(z))
fun toMutableCharVec2(): MutableCharVec2 = MutableCharVec2(x.toChar(), y.toChar())
inline fun toMutableCharVec2(conv: (Short) -> Char): MutableCharVec2 = MutableCharVec2(conv(x), conv(y))
fun toMutableCharVec3(): MutableCharVec3 = MutableCharVec3(x.toChar(), y.toChar(), z.toChar())
inline fun toMutableCharVec3(conv: (Short) -> Char): MutableCharVec3 = MutableCharVec3(conv(x), conv(y), conv(z))
fun toMutableCharVec4(w: Char): MutableCharVec4 = MutableCharVec4(x.toChar(), y.toChar(), z.toChar(), w)
inline fun toMutableCharVec4(w: Char, conv: (Short) -> Char): MutableCharVec4 = MutableCharVec4(conv(x), conv(y), conv(z), w)
// Conversions to Boolean
fun toBoolVec(): BoolVec3 = BoolVec3(x != 0.toShort(), y != 0.toShort(), z != 0.toShort())
inline fun toBoolVec(conv: (Short) -> Boolean): BoolVec3 = BoolVec3(conv(x), conv(y), conv(z))
fun toBoolVec2(): BoolVec2 = BoolVec2(x != 0.toShort(), y != 0.toShort())
inline fun toBoolVec2(conv: (Short) -> Boolean): BoolVec2 = BoolVec2(conv(x), conv(y))
fun toBoolVec3(): BoolVec3 = BoolVec3(x != 0.toShort(), y != 0.toShort(), z != 0.toShort())
inline fun toBoolVec3(conv: (Short) -> Boolean): BoolVec3 = BoolVec3(conv(x), conv(y), conv(z))
fun toBoolVec4(w: Boolean = false): BoolVec4 = BoolVec4(x != 0.toShort(), y != 0.toShort(), z != 0.toShort(), w)
inline fun toBoolVec4(w: Boolean = false, conv: (Short) -> Boolean): BoolVec4 = BoolVec4(conv(x), conv(y), conv(z), w)
// Conversions to Boolean
fun toMutableBoolVec(): MutableBoolVec3 = MutableBoolVec3(x != 0.toShort(), y != 0.toShort(), z != 0.toShort())
inline fun toMutableBoolVec(conv: (Short) -> Boolean): MutableBoolVec3 = MutableBoolVec3(conv(x), conv(y), conv(z))
fun toMutableBoolVec2(): MutableBoolVec2 = MutableBoolVec2(x != 0.toShort(), y != 0.toShort())
inline fun toMutableBoolVec2(conv: (Short) -> Boolean): MutableBoolVec2 = MutableBoolVec2(conv(x), conv(y))
fun toMutableBoolVec3(): MutableBoolVec3 = MutableBoolVec3(x != 0.toShort(), y != 0.toShort(), z != 0.toShort())
inline fun toMutableBoolVec3(conv: (Short) -> Boolean): MutableBoolVec3 = MutableBoolVec3(conv(x), conv(y), conv(z))
fun toMutableBoolVec4(w: Boolean = false): MutableBoolVec4 = MutableBoolVec4(x != 0.toShort(), y != 0.toShort(), z != 0.toShort(), w)
inline fun toMutableBoolVec4(w: Boolean = false, conv: (Short) -> Boolean): MutableBoolVec4 = MutableBoolVec4(conv(x), conv(y), conv(z), w)
// Conversions to String
fun toStringVec(): StringVec3 = StringVec3(x.toString(), y.toString(), z.toString())
inline fun toStringVec(conv: (Short) -> String): StringVec3 = StringVec3(conv(x), conv(y), conv(z))
fun toStringVec2(): StringVec2 = StringVec2(x.toString(), y.toString())
inline fun toStringVec2(conv: (Short) -> String): StringVec2 = StringVec2(conv(x), conv(y))
fun toStringVec3(): StringVec3 = StringVec3(x.toString(), y.toString(), z.toString())
inline fun toStringVec3(conv: (Short) -> String): StringVec3 = StringVec3(conv(x), conv(y), conv(z))
fun toStringVec4(w: String = ""): StringVec4 = StringVec4(x.toString(), y.toString(), z.toString(), w)
inline fun toStringVec4(w: String = "", conv: (Short) -> String): StringVec4 = StringVec4(conv(x), conv(y), conv(z), w)
// Conversions to String
fun toMutableStringVec(): MutableStringVec3 = MutableStringVec3(x.toString(), y.toString(), z.toString())
inline fun toMutableStringVec(conv: (Short) -> String): MutableStringVec3 = MutableStringVec3(conv(x), conv(y), conv(z))
fun toMutableStringVec2(): MutableStringVec2 = MutableStringVec2(x.toString(), y.toString())
inline fun toMutableStringVec2(conv: (Short) -> String): MutableStringVec2 = MutableStringVec2(conv(x), conv(y))
fun toMutableStringVec3(): MutableStringVec3 = MutableStringVec3(x.toString(), y.toString(), z.toString())
inline fun toMutableStringVec3(conv: (Short) -> String): MutableStringVec3 = MutableStringVec3(conv(x), conv(y), conv(z))
fun toMutableStringVec4(w: String = ""): MutableStringVec4 = MutableStringVec4(x.toString(), y.toString(), z.toString(), w)
inline fun toMutableStringVec4(w: String = "", conv: (Short) -> String): MutableStringVec4 = MutableStringVec4(conv(x), conv(y), conv(z), w)
// Conversions to T2
inline fun <T2> toTVec(conv: (Short) -> T2): TVec3<T2> = TVec3<T2>(conv(x), conv(y), conv(z))
inline fun <T2> toTVec2(conv: (Short) -> T2): TVec2<T2> = TVec2<T2>(conv(x), conv(y))
inline fun <T2> toTVec3(conv: (Short) -> T2): TVec3<T2> = TVec3<T2>(conv(x), conv(y), conv(z))
inline fun <T2> toTVec4(w: T2, conv: (Short) -> T2): TVec4<T2> = TVec4<T2>(conv(x), conv(y), conv(z), w)
// Conversions to T2
inline fun <T2> toMutableTVec(conv: (Short) -> T2): MutableTVec3<T2> = MutableTVec3<T2>(conv(x), conv(y), conv(z))
inline fun <T2> toMutableTVec2(conv: (Short) -> T2): MutableTVec2<T2> = MutableTVec2<T2>(conv(x), conv(y))
inline fun <T2> toMutableTVec3(conv: (Short) -> T2): MutableTVec3<T2> = MutableTVec3<T2>(conv(x), conv(y), conv(z))
inline fun <T2> toMutableTVec4(w: T2, conv: (Short) -> T2): MutableTVec4<T2> = MutableTVec4<T2>(conv(x), conv(y), conv(z), w)
// Allows for swizzling, e.g. v.swizzle.xzx
inner class Swizzle {
val xx: ShortVec2 get() = ShortVec2(x, x)
val xy: ShortVec2 get() = ShortVec2(x, y)
val xz: ShortVec2 get() = ShortVec2(x, z)
val yx: ShortVec2 get() = ShortVec2(y, x)
val yy: ShortVec2 get() = ShortVec2(y, y)
val yz: ShortVec2 get() = ShortVec2(y, z)
val zx: ShortVec2 get() = ShortVec2(z, x)
val zy: ShortVec2 get() = ShortVec2(z, y)
val zz: ShortVec2 get() = ShortVec2(z, z)
val xxx: ShortVec3 get() = ShortVec3(x, x, x)
val xxy: ShortVec3 get() = ShortVec3(x, x, y)
val xxz: ShortVec3 get() = ShortVec3(x, x, z)
val xyx: ShortVec3 get() = ShortVec3(x, y, x)
val xyy: ShortVec3 get() = ShortVec3(x, y, y)
val xyz: ShortVec3 get() = ShortVec3(x, y, z)
val xzx: ShortVec3 get() = ShortVec3(x, z, x)
val xzy: ShortVec3 get() = ShortVec3(x, z, y)
val xzz: ShortVec3 get() = ShortVec3(x, z, z)
val yxx: ShortVec3 get() = ShortVec3(y, x, x)
val yxy: ShortVec3 get() = ShortVec3(y, x, y)
val yxz: ShortVec3 get() = ShortVec3(y, x, z)
val yyx: ShortVec3 get() = ShortVec3(y, y, x)
val yyy: ShortVec3 get() = ShortVec3(y, y, y)
val yyz: ShortVec3 get() = ShortVec3(y, y, z)
val yzx: ShortVec3 get() = ShortVec3(y, z, x)
val yzy: ShortVec3 get() = ShortVec3(y, z, y)
val yzz: ShortVec3 get() = ShortVec3(y, z, z)
val zxx: ShortVec3 get() = ShortVec3(z, x, x)
val zxy: ShortVec3 get() = ShortVec3(z, x, y)
val zxz: ShortVec3 get() = ShortVec3(z, x, z)
val zyx: ShortVec3 get() = ShortVec3(z, y, x)
val zyy: ShortVec3 get() = ShortVec3(z, y, y)
val zyz: ShortVec3 get() = ShortVec3(z, y, z)
val zzx: ShortVec3 get() = ShortVec3(z, z, x)
val zzy: ShortVec3 get() = ShortVec3(z, z, y)
val zzz: ShortVec3 get() = ShortVec3(z, z, z)
val xxxx: ShortVec4 get() = ShortVec4(x, x, x, x)
val xxxy: ShortVec4 get() = ShortVec4(x, x, x, y)
val xxxz: ShortVec4 get() = ShortVec4(x, x, x, z)
val xxyx: ShortVec4 get() = ShortVec4(x, x, y, x)
val xxyy: ShortVec4 get() = ShortVec4(x, x, y, y)
val xxyz: ShortVec4 get() = ShortVec4(x, x, y, z)
val xxzx: ShortVec4 get() = ShortVec4(x, x, z, x)
val xxzy: ShortVec4 get() = ShortVec4(x, x, z, y)
val xxzz: ShortVec4 get() = ShortVec4(x, x, z, z)
val xyxx: ShortVec4 get() = ShortVec4(x, y, x, x)
val xyxy: ShortVec4 get() = ShortVec4(x, y, x, y)
val xyxz: ShortVec4 get() = ShortVec4(x, y, x, z)
val xyyx: ShortVec4 get() = ShortVec4(x, y, y, x)
val xyyy: ShortVec4 get() = ShortVec4(x, y, y, y)
val xyyz: ShortVec4 get() = ShortVec4(x, y, y, z)
val xyzx: ShortVec4 get() = ShortVec4(x, y, z, x)
val xyzy: ShortVec4 get() = ShortVec4(x, y, z, y)
val xyzz: ShortVec4 get() = ShortVec4(x, y, z, z)
val xzxx: ShortVec4 get() = ShortVec4(x, z, x, x)
val xzxy: ShortVec4 get() = ShortVec4(x, z, x, y)
val xzxz: ShortVec4 get() = ShortVec4(x, z, x, z)
val xzyx: ShortVec4 get() = ShortVec4(x, z, y, x)
val xzyy: ShortVec4 get() = ShortVec4(x, z, y, y)
val xzyz: ShortVec4 get() = ShortVec4(x, z, y, z)
val xzzx: ShortVec4 get() = ShortVec4(x, z, z, x)
val xzzy: ShortVec4 get() = ShortVec4(x, z, z, y)
val xzzz: ShortVec4 get() = ShortVec4(x, z, z, z)
val yxxx: ShortVec4 get() = ShortVec4(y, x, x, x)
val yxxy: ShortVec4 get() = ShortVec4(y, x, x, y)
val yxxz: ShortVec4 get() = ShortVec4(y, x, x, z)
val yxyx: ShortVec4 get() = ShortVec4(y, x, y, x)
val yxyy: ShortVec4 get() = ShortVec4(y, x, y, y)
val yxyz: ShortVec4 get() = ShortVec4(y, x, y, z)
val yxzx: ShortVec4 get() = ShortVec4(y, x, z, x)
val yxzy: ShortVec4 get() = ShortVec4(y, x, z, y)
val yxzz: ShortVec4 get() = ShortVec4(y, x, z, z)
val yyxx: ShortVec4 get() = ShortVec4(y, y, x, x)
val yyxy: ShortVec4 get() = ShortVec4(y, y, x, y)
val yyxz: ShortVec4 get() = ShortVec4(y, y, x, z)
val yyyx: ShortVec4 get() = ShortVec4(y, y, y, x)
val yyyy: ShortVec4 get() = ShortVec4(y, y, y, y)
val yyyz: ShortVec4 get() = ShortVec4(y, y, y, z)
val yyzx: ShortVec4 get() = ShortVec4(y, y, z, x)
val yyzy: ShortVec4 get() = ShortVec4(y, y, z, y)
val yyzz: ShortVec4 get() = ShortVec4(y, y, z, z)
val yzxx: ShortVec4 get() = ShortVec4(y, z, x, x)
val yzxy: ShortVec4 get() = ShortVec4(y, z, x, y)
val yzxz: ShortVec4 get() = ShortVec4(y, z, x, z)
val yzyx: ShortVec4 get() = ShortVec4(y, z, y, x)
val yzyy: ShortVec4 get() = ShortVec4(y, z, y, y)
val yzyz: ShortVec4 get() = ShortVec4(y, z, y, z)
val yzzx: ShortVec4 get() = ShortVec4(y, z, z, x)
val yzzy: ShortVec4 get() = ShortVec4(y, z, z, y)
val yzzz: ShortVec4 get() = ShortVec4(y, z, z, z)
val zxxx: ShortVec4 get() = ShortVec4(z, x, x, x)
val zxxy: ShortVec4 get() = ShortVec4(z, x, x, y)
val zxxz: ShortVec4 get() = ShortVec4(z, x, x, z)
val zxyx: ShortVec4 get() = ShortVec4(z, x, y, x)
val zxyy: ShortVec4 get() = ShortVec4(z, x, y, y)
val zxyz: ShortVec4 get() = ShortVec4(z, x, y, z)
val zxzx: ShortVec4 get() = ShortVec4(z, x, z, x)
val zxzy: ShortVec4 get() = ShortVec4(z, x, z, y)
val zxzz: ShortVec4 get() = ShortVec4(z, x, z, z)
val zyxx: ShortVec4 get() = ShortVec4(z, y, x, x)
val zyxy: ShortVec4 get() = ShortVec4(z, y, x, y)
val zyxz: ShortVec4 get() = ShortVec4(z, y, x, z)
val zyyx: ShortVec4 get() = ShortVec4(z, y, y, x)
val zyyy: ShortVec4 get() = ShortVec4(z, y, y, y)
val zyyz: ShortVec4 get() = ShortVec4(z, y, y, z)
val zyzx: ShortVec4 get() = ShortVec4(z, y, z, x)
val zyzy: ShortVec4 get() = ShortVec4(z, y, z, y)
val zyzz: ShortVec4 get() = ShortVec4(z, y, z, z)
val zzxx: ShortVec4 get() = ShortVec4(z, z, x, x)
val zzxy: ShortVec4 get() = ShortVec4(z, z, x, y)
val zzxz: ShortVec4 get() = ShortVec4(z, z, x, z)
val zzyx: ShortVec4 get() = ShortVec4(z, z, y, x)
val zzyy: ShortVec4 get() = ShortVec4(z, z, y, y)
val zzyz: ShortVec4 get() = ShortVec4(z, z, y, z)
val zzzx: ShortVec4 get() = ShortVec4(z, z, z, x)
val zzzy: ShortVec4 get() = ShortVec4(z, z, z, y)
val zzzz: ShortVec4 get() = ShortVec4(z, z, z, z)
}
val swizzle: Swizzle get() = Swizzle()
}
fun vecOf(x: Short, y: Short, z: Short): ShortVec3 = ShortVec3(x, y, z)
operator fun Short.plus(rhs: ShortVec3): IntVec3 = IntVec3(this + rhs.x, this + rhs.y, this + rhs.z)
operator fun Short.minus(rhs: ShortVec3): IntVec3 = IntVec3(this - rhs.x, this - rhs.y, this - rhs.z)
operator fun Short.times(rhs: ShortVec3): IntVec3 = IntVec3(this * rhs.x, this * rhs.y, this * rhs.z)
operator fun Short.div(rhs: ShortVec3): IntVec3 = IntVec3(this / rhs.x, this / rhs.y, this / rhs.z)
operator fun Short.rem(rhs: ShortVec3): IntVec3 = IntVec3(this % rhs.x, this % rhs.y, this % rhs.z)
| mit | 45117280c34e5e69415fbcac203157ea | 68.03794 | 148 | 0.63423 | 3.300726 | false | false | false | false |
DemonWav/MinecraftDev | src/main/kotlin/com/demonwav/mcdev/platform/mcp/at/AtCommenter.kt | 1 | 533 | /*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2018 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev.platform.mcp.at
import com.intellij.lang.Commenter
class AtCommenter : Commenter {
override fun getLineCommentPrefix() = "#"
override fun getBlockCommentPrefix(): String? = null
override fun getBlockCommentSuffix(): String? = null
override fun getCommentedBlockCommentPrefix(): String? = null
override fun getCommentedBlockCommentSuffix(): String? = null
}
| mit | c2b065b1f0b2af89a49c352b7fc5daeb | 23.227273 | 65 | 0.726079 | 4.478992 | false | false | false | false |
dahlstrom-g/intellij-community | plugins/kotlin/base/plugin/src/org/jetbrains/kotlin/idea/base/plugin/artifacts/KotlinArtifacts.kt | 2 | 5029 | // 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.base.plugin.artifacts
import com.intellij.openapi.application.PathManager
import com.intellij.openapi.util.NlsSafe
import org.jetbrains.annotations.ApiStatus
import org.jetbrains.kotlin.idea.compiler.configuration.KotlinPluginLayout
import java.io.File
@ApiStatus.Internal
object KotlinArtifactConstants {
@NlsSafe
const val KOTLIN_MAVEN_GROUP_ID = "org.jetbrains.kotlin"
@Deprecated(
"Deprecated because new \"meta pom\" format (KOTLIN_DIST_FOR_JPS_META_ARTIFACT_ID) should be used. " +
"This constant should be used only for being possible to compile intellij repo"
)
@NlsSafe
const val OLD_KOTLIN_DIST_ARTIFACT_ID = "kotlin-dist-for-ide"
@NlsSafe
const val KOTLIN_DIST_FOR_JPS_META_ARTIFACT_ID = "kotlin-dist-for-jps-meta"
@Deprecated(
"Deprecated because new KOTLIN_JPS_PLUGIN_PLUGIN_ARTIFACT_ID should be used. " +
"This constant should be used only for being possible to compile intellij repo"
)
@NlsSafe
const val OLD_FAT_JAR_KOTLIN_JPS_PLUGIN_CLASSPATH_ARTIFACT_ID = "kotlin-jps-plugin-classpath"
@NlsSafe
const val KOTLIN_JPS_PLUGIN_PLUGIN_ARTIFACT_ID = "kotlin-jps-plugin"
val KOTLIN_DIST_LOCATION_PREFIX: File = File(PathManager.getSystemPath(), "kotlin-dist-for-ide")
}
object KotlinArtifacts {
private val kotlincLibDirectory: File = File(KotlinPluginLayout.kotlinc, "lib")
@JvmStatic
val jetbrainsAnnotations: File = File(kotlincLibDirectory, KotlinArtifactNames.JETBRAINS_ANNOTATIONS)
@JvmStatic
val kotlinStdlib: File = File(kotlincLibDirectory, KotlinArtifactNames.KOTLIN_STDLIB)
@JvmStatic
val kotlinStdlibSources: File = File(kotlincLibDirectory, KotlinArtifactNames.KOTLIN_STDLIB_SOURCES)
@JvmStatic
val kotlinStdlibJdk7: File = File(kotlincLibDirectory, KotlinArtifactNames.KOTLIN_STDLIB_JDK7)
@JvmStatic
val kotlinStdlibJdk7Sources: File = File(kotlincLibDirectory, KotlinArtifactNames.KOTLIN_STDLIB_JDK7_SOURCES)
@JvmStatic
val kotlinStdlibJdk8: File = File(kotlincLibDirectory, KotlinArtifactNames.KOTLIN_STDLIB_JDK8)
@JvmStatic
val kotlinStdlibJdk8Sources: File = File(kotlincLibDirectory, KotlinArtifactNames.KOTLIN_STDLIB_JDK8_SOURCES)
@JvmStatic
val kotlinReflect: File = File(kotlincLibDirectory, KotlinArtifactNames.KOTLIN_REFLECT)
@JvmStatic
val kotlinStdlibJs: File = File(kotlincLibDirectory, KotlinArtifactNames.KOTLIN_STDLIB_JS)
@JvmStatic
val kotlinTest: File = File(kotlincLibDirectory, KotlinArtifactNames.KOTLIN_TEST)
@JvmStatic
val kotlinTestJunit: File = File(kotlincLibDirectory, KotlinArtifactNames.KOTLIN_TEST_JUNIT)
@JvmStatic
val kotlinTestJs: File = File(kotlincLibDirectory, KotlinArtifactNames.KOTLIN_TEST_JS)
@JvmStatic
val kotlinMainKts: File = File(kotlincLibDirectory, KotlinArtifactNames.KOTLIN_MAIN_KTS)
@JvmStatic
val kotlinScriptRuntime: File = File(kotlincLibDirectory, KotlinArtifactNames.KOTLIN_SCRIPT_RUNTIME)
@JvmStatic
val kotlinScriptingCommon: File = File(kotlincLibDirectory, KotlinArtifactNames.KOTLIN_SCRIPTING_COMMON)
@JvmStatic
val kotlinScriptingJvm: File = File(kotlincLibDirectory, KotlinArtifactNames.KOTLIN_SCRIPTING_JVM)
@JvmStatic
val kotlinCompiler: File = File(kotlincLibDirectory, KotlinArtifactNames.KOTLIN_COMPILER)
@JvmStatic
val lombokCompilerPlugin: File = File(kotlincLibDirectory, KotlinArtifactNames.LOMBOK_COMPILER_PLUGIN)
@JvmStatic
val kotlinAnnotationsJvm: File = File(kotlincLibDirectory, KotlinArtifactNames.KOTLIN_ANNOTATIONS_JVM)
@JvmStatic
val trove4j: File = File(kotlincLibDirectory, KotlinArtifactNames.TROVE4J)
@JvmStatic
val kotlinDaemon: File = File(kotlincLibDirectory, KotlinArtifactNames.KOTLIN_DAEMON)
@JvmStatic
val kotlinScriptingCompiler: File = File(kotlincLibDirectory, KotlinArtifactNames.KOTLIN_SCRIPTING_COMPILER)
@JvmStatic
val kotlinScriptingCompilerImpl: File = File(kotlincLibDirectory, KotlinArtifactNames.KOTLIN_SCRIPTING_COMPILER_IMPL)
@JvmStatic
val allopenCompilerPlugin: File = File(kotlincLibDirectory, KotlinArtifactNames.ALLOPEN_COMPILER_PLUGIN)
@JvmStatic
val noargCompilerPlugin: File = File(kotlincLibDirectory, KotlinArtifactNames.NOARG_COMPILER_PLUGIN)
@JvmStatic
val samWithReceiverCompilerPlugin: File = File(kotlincLibDirectory, KotlinArtifactNames.SAM_WITH_RECEIVER_COMPILER_PLUGIN)
@JvmStatic
val kotlinxSerializationCompilerPlugin: File = File(kotlincLibDirectory, KotlinArtifactNames.KOTLINX_SERIALIZATION_COMPILER_PLUGIN)
@JvmStatic
val parcelizeRuntime: File = File(kotlincLibDirectory, KotlinArtifactNames.PARCELIZE_RUNTIME)
@JvmStatic
val androidExtensionsRuntime: File = File(kotlincLibDirectory, KotlinArtifactNames.ANDROID_EXTENSIONS_RUNTIME)
}
| apache-2.0 | 5d369ac1a2932f5e899d27f95b2e2348 | 38.289063 | 135 | 0.77411 | 4.215423 | false | false | false | false |
CesarValiente/KUnidirectional | persistence/src/androidTest/kotlin/com/cesarvaliente/kunidirectional/persistence/TestUtils.kt | 1 | 2267 | /**
* Copyright (C) 2017 Cesar Valiente & Corey Shaw
*
* https://github.com/CesarValiente
* https://github.com/coshaw
*
* 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.cesarvaliente.kunidirectional.persistence
import org.junit.Assert.assertThat
import com.cesarvaliente.kunidirectional.persistence.Color as PersistenceColor
import com.cesarvaliente.kunidirectional.persistence.Item as PersistenceItem
import com.cesarvaliente.kunidirectional.store.Color as StoreColor
import com.cesarvaliente.kunidirectional.store.Item as StoreItem
import org.hamcrest.core.Is.`is` as iz
const val LOCAL_ID_VALUE = "localId"
const val TEXT_VALUE = "text"
const val POSITION_VALUE = 1L
val COLOR_VALUE = com.cesarvaliente.kunidirectional.store.Color.RED
const val FAVORITE_VALUE = false
fun createPersistenceItem(index: Int): PersistenceItem =
createStoreItem(index).toPersistenceItem()
fun createStoreItem(index: Int): StoreItem =
StoreItem(
localId = LOCAL_ID_VALUE + index,
text = TEXT_VALUE + index,
favorite = FAVORITE_VALUE,
color = COLOR_VALUE,
position = POSITION_VALUE + index)
/**
This function asserts that the current item is the same the given item.
We can not use equals() from Item, since a result from Realm is not a real Item, but
a proxy that matches our Item, so equals() always fails since we are comparing Item with a ProxyItem */
fun PersistenceItem.assertIsEqualsTo(otherItem: PersistenceItem) {
assertThat(localId, iz(otherItem.localId))
assertThat(text, iz(otherItem.text))
assertThat(color, iz(otherItem.color))
assertThat(favorite, iz(otherItem.favorite))
assertThat(position, iz(otherItem.position))
}
| apache-2.0 | f6622e287cc2ff08f482e3d4911f1039 | 37.423729 | 103 | 0.739744 | 4.144424 | false | false | false | false |
paplorinc/intellij-community | platform/testGuiFramework/src/com/intellij/testGuiFramework/cellReader/ExtendedCellReaders.kt | 4 | 5620 | /*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.testGuiFramework.cellReader
import com.intellij.ide.util.treeView.NodeRenderer
import com.intellij.testGuiFramework.framework.GuiTestUtil
import com.intellij.testGuiFramework.impl.GuiTestUtilKt.computeOnEdt
import com.intellij.testGuiFramework.impl.GuiTestUtilKt.findAllWithBFS
import com.intellij.ui.MultilineTreeCellRenderer
import com.intellij.ui.SimpleColoredComponent
import com.intellij.ui.components.JBList
import org.fest.swing.cell.JComboBoxCellReader
import org.fest.swing.cell.JListCellReader
import org.fest.swing.cell.JTableCellReader
import org.fest.swing.cell.JTreeCellReader
import org.fest.swing.driver.BasicJComboBoxCellReader
import org.fest.swing.driver.BasicJListCellReader
import org.fest.swing.driver.BasicJTableCellReader
import org.fest.swing.driver.BasicJTreeCellReader
import org.fest.swing.edt.GuiActionRunner
import org.fest.swing.edt.GuiQuery
import org.fest.swing.exception.ComponentLookupException
import java.awt.Component
import java.awt.Container
import java.lang.Error
import java.util.*
import javax.annotation.Nonnull
import javax.annotation.Nullable
import javax.swing.*
import javax.swing.tree.DefaultMutableTreeNode
/**
* @author Sergey Karashevich
*/
class ExtendedJTreeCellReader : BasicJTreeCellReader(), JTreeCellReader {
override fun valueAt(tree: JTree, modelValue: Any?): String? = valueAtExtended(tree, modelValue, false)
fun valueAtExtended(tree: JTree, modelValue: Any?, isExtended: Boolean = true): String? {
if (modelValue == null) return null
val isLeaf: Boolean = try {
modelValue is DefaultMutableTreeNode && modelValue.isLeaf
}
catch (e: Error) {
false
}
return computeOnEdt {
val cellRendererComponent = tree.cellRenderer.getTreeCellRendererComponent(tree, modelValue, false, false, isLeaf, 0, false)
getValueWithCellRenderer(cellRendererComponent, isExtended)
}
}
}
class ExtendedJListCellReader : BasicJListCellReader(), JListCellReader {
@Nullable
override fun valueAt(@Nonnull list: JList<*>, index: Int): String? {
val element = list.model.getElementAt(index) ?: return null
val cellRendererComponent = GuiTestUtil.getListCellRendererComponent(list, element, index)
return getValueWithCellRenderer(cellRendererComponent)
}
}
class ExtendedJTableCellReader : BasicJTableCellReader(), JTableCellReader {
override fun valueAt(table: JTable, row: Int, column: Int): String? {
val cellRendererComponent = table.prepareRenderer(table.getCellRenderer(row, column), row, column)
return super.valueAt(table, row, column) ?: getValueWithCellRenderer(cellRendererComponent)
}
}
class ExtendedJComboboxCellReader : BasicJComboBoxCellReader(), JComboBoxCellReader {
private val REFERENCE_JLIST = newJList()
override fun valueAt(comboBox: JComboBox<*>, index: Int): String? {
val item: Any? = comboBox.getItemAt(index)
val listCellRenderer: ListCellRenderer<Any?> = comboBox.renderer as ListCellRenderer<Any?>
val cellRendererComponent = listCellRenderer.getListCellRendererComponent(REFERENCE_JLIST, item, index, true, true)
return getValueWithCellRenderer(cellRendererComponent)
}
@Nonnull
private fun newJList(): JList<out Any?> {
return GuiActionRunner.execute(object : GuiQuery<JList<out Any?>>() {
override fun executeInEDT(): JList<out Any?> = JBList()
})!!
}
}
private fun getValueWithCellRenderer(cellRendererComponent: Component, isExtended: Boolean = true): String? {
val result = when (cellRendererComponent) {
is JLabel -> cellRendererComponent.text
is NodeRenderer -> {
if (isExtended) cellRendererComponent.getFullText()
else cellRendererComponent.getFirstText()
} //should stands before SimpleColoredComponent because it is more specific
is SimpleColoredComponent -> cellRendererComponent.getFullText()
is MultilineTreeCellRenderer -> cellRendererComponent.text
else -> cellRendererComponent.findText()
}
return result?.trimEnd()
}
private fun SimpleColoredComponent.getFullText(): String? {
return computeOnEdt {
this.getCharSequence(false).toString()
}
}
private fun SimpleColoredComponent.getFirstText(): String? {
return computeOnEdt {
this.getCharSequence(true).toString()
}
}
private fun Component.findText(): String? {
try {
assert(this is Container)
val container = this as Container
val resultList = ArrayList<String>()
resultList.addAll(
findAllWithBFS(container, JLabel::class.java)
.asSequence()
.filter { !it.text.isNullOrEmpty() }
.map { it.text }
.toList()
)
resultList.addAll(
findAllWithBFS(container, SimpleColoredComponent::class.java)
.asSequence()
.filter {
!it.getFullText().isNullOrEmpty()
}
.map {
it.getFullText()!!
}
.toList()
)
return resultList.firstOrNull { !it.isEmpty() }
}
catch (ignored: ComponentLookupException) {
return null
}
}
| apache-2.0 | 1324050ddf1a834c47ea5b79c7957d3b | 33.268293 | 130 | 0.749644 | 4.580277 | false | false | false | false |
cd1/motofretado | app/src/main/java/com/gmail/cristiandeives/motofretado/BusSpinnerAdapter.kt | 1 | 2267 | package com.gmail.cristiandeives.motofretado
import android.content.Context
import android.support.annotation.LayoutRes
import android.support.annotation.MainThread
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ArrayAdapter
import android.widget.TextView
import com.gmail.cristiandeives.motofretado.http.Bus
@MainThread
internal class BusSpinnerAdapter(context: Context) : ArrayAdapter<Bus>(context, ITEM_RESOURCE) {
companion object {
private val TAG = BusSpinnerAdapter::class.java.simpleName
@LayoutRes
private val ITEM_RESOURCE = android.R.layout.simple_spinner_item
@LayoutRes
private val DROPDOWN_ITEM_RESOURCE = android.R.layout.simple_spinner_dropdown_item
}
private val mInflater: LayoutInflater
private var mErrorMessage: String? = null
init {
setDropDownViewResource(DROPDOWN_ITEM_RESOURCE)
mInflater = context.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater
}
override fun getCount(): Int {
Log.v(TAG, "> getCount()")
val count = maxOf(super.getCount(), 1)
Log.v(TAG, "< getCount(): $count")
return count
}
override fun getView(position: Int, convertView: View?, parent: ViewGroup): View {
Log.v(TAG, "> getView(position=$position, convertView=$convertView, parent=$parent)")
val view = if (!hasActualBusData()) {
val myConvertView = convertView ?: mInflater.inflate(ITEM_RESOURCE, parent, false)
val textView = myConvertView as TextView
textView.text = if (!mErrorMessage.isNullOrEmpty()) {
textView.error = ""
mErrorMessage
} else {
context.getString(R.string.loading_bus_numbers)
}
textView
} else {
super.getView(position, convertView, parent)
}
Log.v(TAG, "> getView(position=$position, convertView=$convertView, parent=$parent): $view")
return view
}
internal fun setErrorMessage(message: String) {
mErrorMessage = message
clear()
}
internal fun hasActualBusData() = super.getCount() > 0
} | gpl-3.0 | 932ebf613d0c3a896ac895c7c522667a | 31.4 | 100 | 0.669607 | 4.489109 | false | false | false | false |
google/intellij-community | platform/workspaceModel/jps/src/com/intellij/workspaceModel/ide/impl/jps/serialization/FacetEntitiesSerializer.kt | 3 | 6780 | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.workspaceModel.ide.impl.jps.serialization
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.util.JDOMUtil
import com.intellij.openapi.util.io.FileUtil
import com.intellij.util.xmlb.XmlSerializer
import com.intellij.workspaceModel.ide.JpsFileEntitySource
import com.intellij.workspaceModel.ide.JpsImportedEntitySource
import com.intellij.workspaceModel.storage.MutableEntityStorage
import com.intellij.workspaceModel.storage.bridgeEntities.addFacetEntity
import com.intellij.workspaceModel.storage.bridgeEntities.api.*
import com.intellij.workspaceModel.storage.url.VirtualFileUrl
import org.jetbrains.jps.model.serialization.JDomSerializationUtil
import org.jetbrains.jps.model.serialization.facet.FacetManagerState
import org.jetbrains.jps.model.serialization.facet.FacetState
import com.intellij.workspaceModel.storage.bridgeEntities.api.modifyEntity
internal class FacetEntitiesSerializer(private val imlFileUrl: VirtualFileUrl,
private val internalSource: JpsFileEntitySource,
private val componentName: String,
private val baseModuleDirPath: String?,
private val externalStorage: Boolean) {
/**
* This function should return void (Unit)
* The current result value is a temporal solution to find the root cause of https://ea.jetbrains.com/browser/ea_problems/239676
*/
internal fun loadFacetEntities(builder: MutableEntityStorage, moduleEntity: ModuleEntity, reader: JpsFileContentReader) {
val facetManagerTag = reader.loadComponent(imlFileUrl.url, componentName, baseModuleDirPath) ?: return
val facetManagerState = XmlSerializer.deserialize(facetManagerTag, FacetManagerState::class.java)
val orderOfFacets = ArrayList<String>()
loadFacetEntities(facetManagerState.facets, builder, moduleEntity, null, orderOfFacets)
if (orderOfFacets.size > 1 && !externalStorage) {
val entity = moduleEntity.facetOrder
if (entity != null) {
builder.modifyEntity(entity) {
this.orderOfFacets = orderOfFacets
}
}
else {
builder.addEntity(FacetsOrderEntity(orderOfFacets, internalSource) {
this.moduleEntity = moduleEntity
})
}
}
}
private fun loadFacetEntities(facetStates: List<FacetState>, builder: MutableEntityStorage, moduleEntity: ModuleEntity,
underlyingFacet: FacetEntity?, orderOfFacets: MutableList<String>) {
for (facetState in facetStates) {
orderOfFacets.add(facetState.name)
val configurationXmlTag = facetState.configuration?.let { JDOMUtil.write(it) }
val externalSystemId = facetState.externalSystemId ?: facetState.externalSystemIdInInternalStorage
val source = if (externalSystemId == null) internalSource else JpsImportedEntitySource(internalSource, externalSystemId, externalStorage)
// Check for existing facet
val newFacetId = FacetId(facetState.name, facetState.facetType, moduleEntity.persistentId)
var facetEntity: FacetEntity? = null
val existingFacet = builder.resolve(newFacetId)
if (existingFacet != null && configurationXmlTag != null) {
if (existingFacet.configurationXmlTag == null) {
facetEntity = builder.modifyEntity(existingFacet) { this.configurationXmlTag = configurationXmlTag }
facetEntity = builder.modifyEntity(facetEntity) { this.entitySource = source }
}
}
if (existingFacet == null) {
facetEntity = builder.addFacetEntity(facetState.name, facetState.facetType, configurationXmlTag, moduleEntity, underlyingFacet, source)
}
if (facetEntity != null && externalSystemId != null && !externalStorage) {
builder.addEntity(FacetExternalSystemIdEntity(externalSystemId, source) {
this.facet = facetEntity
})
}
loadFacetEntities(facetState.subFacets, builder, moduleEntity, facetEntity, orderOfFacets)
}
}
internal fun saveFacetEntities(facets: List<FacetEntity>, writer: JpsFileContentWriter) {
val fileUrl = imlFileUrl.url
if (facets.isEmpty()) {
writer.saveComponent(fileUrl, componentName, null)
return
}
val facetManagerState = FacetManagerState()
val facetStates = HashMap<String, FacetState>()
val facetsByName = facets.groupByTo(HashMap()) { it.name }
val orderOfFacets = facets.first().module.facetOrder?.orderOfFacets ?: emptyList()
for (facetName in orderOfFacets) {
facetsByName.remove(facetName)?.forEach {
saveFacet(it, facetStates, facetManagerState.facets)
}
}
facetsByName.values.forEach {
it.forEach {
saveFacet(it, facetStates, facetManagerState.facets)
}
}
val componentTag = JDomSerializationUtil.createComponentElement(componentName)
XmlSerializer.serializeInto(facetManagerState, componentTag)
if (externalStorage && FileUtil.extensionEquals(fileUrl, "iml")) {
// Trying to catch https://ea.jetbrains.com/browser/ea_problems/239676
logger<FacetEntitiesSerializer>().error("""Incorrect file for the serializer
|externalStorage: $externalStorage
|file path: $fileUrl
|componentName: $componentName
""".trimMargin())
}
writer.saveComponent(fileUrl, componentName, componentTag)
}
private fun saveFacet(facetEntity: FacetEntity, facetStates: MutableMap<String, FacetState>, rootFacets: MutableList<FacetState>) {
val state = getOrCreateFacetState(facetEntity, facetStates, rootFacets)
state.configuration = facetEntity.configurationXmlTag?.let { JDOMUtil.load(it) }
}
private fun getOrCreateFacetState(facetEntity: FacetEntity, facetStates: MutableMap<String, FacetState>, rootFacets: MutableList<FacetState>): FacetState {
val existing = facetStates[facetEntity.name]
if (existing != null) return existing
val state = FacetState().apply {
name = facetEntity.name
facetType = facetEntity.facetType
if (externalStorage) {
externalSystemId = (facetEntity.entitySource as? JpsImportedEntitySource)?.externalSystemId
}
else {
externalSystemIdInInternalStorage = facetEntity.facetExternalSystemIdEntity?.externalSystemId
}
}
facetStates[state.name] = state
val underlyingFacet = facetEntity.underlyingFacet
val targetList =
if (underlyingFacet != null) getOrCreateFacetState(underlyingFacet, facetStates, rootFacets).subFacets
else rootFacets
targetList += state
return state
}
}
| apache-2.0 | 762dd30bc16a0db82a2fd8bd2fc746e3 | 46.412587 | 157 | 0.727729 | 5.059701 | false | true | false | false |
vhromada/Catalog | web/src/main/kotlin/com/github/vhromada/catalog/web/security/AccountAuthenticationProvider.kt | 1 | 2731 | package com.github.vhromada.catalog.web.security
import com.github.vhromada.catalog.web.connector.AccountConnector
import com.github.vhromada.catalog.web.connector.entity.Credentials
import com.github.vhromada.catalog.web.service.PasswordEncoder
import org.springframework.security.authentication.AuthenticationProvider
import org.springframework.security.authentication.BadCredentialsException
import org.springframework.security.authentication.InternalAuthenticationServiceException
import org.springframework.security.authentication.LockedException
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken
import org.springframework.security.core.Authentication
import org.springframework.security.core.authority.SimpleGrantedAuthority
import org.springframework.security.core.userdetails.UsernameNotFoundException
/**
* A class represents authentication provider for account.
*
* @author Vladimir Hromada
*/
class AccountAuthenticationProvider(
/**
* Connector for accounts
*/
private val connector: AccountConnector,
/**
* Encoder for password
*/
private val passwordEncoder: PasswordEncoder
) : AuthenticationProvider {
override fun authenticate(authentication: Authentication?): Authentication {
val username = authentication!!.principal.toString()
val password = authentication.credentials.toString()
val encodedPassword = passwordEncoder.encode(password = password)
val response = connector.checkCredentials(credentials = Credentials(username = username, password = encodedPassword))
if (response.exception != null) {
val events = response.result!!.events()
if (events.firstOrNull { it.key == "ACCOUNT_NOT_EXIST" } != null) {
throw UsernameNotFoundException("Account not found [username=$username]")
}
if (events.firstOrNull { it.key == "INVALID_CREDENTIALS" } != null) {
throw BadCredentialsException("Invalid credentials [username=$username]")
}
throw InternalAuthenticationServiceException("Can't authorize [username=$username]")
}
val account = response.get()
if (account.locked) {
throw LockedException("Account is locked [username=$username]")
}
val result = Account(uuid = account.uuid, username = account.username, roles = account.roles)
return UsernamePasswordAuthenticationToken(result, null, account.roles.map { SimpleGrantedAuthority(it) })
}
override fun supports(authentication: Class<*>?): Boolean {
return authentication != null && authentication == UsernamePasswordAuthenticationToken::class.java
}
}
| mit | 84eaa807f019526b99ce33218ba7b87e | 45.288136 | 125 | 0.738923 | 5.407921 | false | false | false | false |
chrislo27/RhythmHeavenRemixEditor2 | core/src/main/kotlin/io/github/chrislo27/rhre3/util/JsonHandler.kt | 2 | 2570 | package io.github.chrislo27.rhre3.util
import com.fasterxml.jackson.annotation.JsonAutoDetect
import com.fasterxml.jackson.annotation.PropertyAccessor
import com.fasterxml.jackson.core.JsonGenerator
import com.fasterxml.jackson.core.JsonParser
import com.fasterxml.jackson.databind.DeserializationFeature
import com.fasterxml.jackson.databind.MapperFeature
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.databind.SerializationFeature
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule
import com.fasterxml.jackson.module.afterburner.AfterburnerModule
import com.fasterxml.jackson.module.kotlin.KotlinModule
import java.io.OutputStream
object JsonHandler {
val OBJECT_MAPPER: ObjectMapper = createObjectMapper(false)
// val GSON: Gson = createObjectMapper()
@JvmStatic
fun createObjectMapper(failOnUnknown: Boolean = false, prettyPrinted: Boolean = true): ObjectMapper {
val mapper = ObjectMapper()
.enable(SerializationFeature.USE_EQUALITY_FOR_OBJECT_ID)
.enable(MapperFeature.USE_ANNOTATIONS)
.enable(JsonParser.Feature.ALLOW_COMMENTS)
.disable(JsonGenerator.Feature.AUTO_CLOSE_TARGET)
.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS)
.disable(MapperFeature.ALLOW_COERCION_OF_SCALARS)
.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.NONE)
.setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY)
.registerModule(AfterburnerModule())
.registerModule(KotlinModule())
.registerModule(JavaTimeModule())
if (!failOnUnknown) {
mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)
}
if (prettyPrinted) {
mapper.enable(SerializationFeature.INDENT_OUTPUT)
}
return mapper
}
@JvmStatic
inline fun <reified T> fromJson(json: String): T {
return OBJECT_MAPPER.readValue(json, T::class.java)
}
@JvmStatic
fun <T> fromJson(json: String, clazz: Class<T>): T {
return OBJECT_MAPPER.readValue(json, clazz)
}
@JvmStatic
fun toJson(obj: Any, stream: OutputStream) {
OBJECT_MAPPER.writeValue(stream, obj)
}
@JvmStatic
fun toJson(obj: Any): String {
return OBJECT_MAPPER.writeValueAsString(obj)
}
@JvmStatic
fun <T> toJson(obj: Any, clazz: Class<T>): String {
return OBJECT_MAPPER.writeValueAsString(clazz.cast(obj))
}
}
| gpl-3.0 | 347bb1b7830ed8d4fb44a41b5dcbdfb0 | 34.205479 | 105 | 0.701556 | 4.524648 | false | false | false | false |
allotria/intellij-community | platform/external-system-impl/src/com/intellij/openapi/externalSystem/action/task/ExternalSystemTaskMenu.kt | 7 | 2544 | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.openapi.externalSystem.action.task
import com.intellij.execution.Executor
import com.intellij.openapi.actionSystem.*
import com.intellij.openapi.externalSystem.model.ExternalSystemDataKeys
import com.intellij.openapi.externalSystem.statistics.ExternalSystemActionsCollector
import com.intellij.openapi.project.DumbAware
class ExternalSystemTaskMenu : DefaultActionGroup(), DumbAware {
private val actionManager = ActionManager.getInstance()
override fun update(e: AnActionEvent) {
val project = AnAction.getEventProject(e) ?: return
childActionsOrStubs
.filter { it is MyDelegatingAction }
.forEach { remove(it) }
Executor.EXECUTOR_EXTENSION_NAME.extensionList
.filter { it.isApplicable(project) }
.reversed()
.forEach {
val contextAction = actionManager.getAction(it.contextActionId)
if (contextAction != null) {
add(wrap(contextAction, it), Constraints.FIRST)
}
}
}
private interface MyDelegatingAction
private class DelegatingActionGroup internal constructor(action: ActionGroup, private val executor: Executor) :
EmptyAction.MyDelegatingActionGroup(action), MyDelegatingAction {
override fun getChildren(e: AnActionEvent?): Array<AnAction> {
val children = super.getChildren(e)
return children.map { wrap(it, executor) }.toTypedArray()
}
override fun actionPerformed(e: AnActionEvent) {
reportUsage(e, executor)
super.actionPerformed(e)
}
}
private class DelegatingAction internal constructor(action: AnAction, private val executor: Executor) :
EmptyAction.MyDelegatingAction(action), MyDelegatingAction {
override fun actionPerformed(e: AnActionEvent) {
reportUsage(e, executor)
super.actionPerformed(e)
}
}
companion object {
private fun wrap(action: AnAction, executor: Executor): AnAction = if (action is ActionGroup) DelegatingActionGroup(action, executor)
else DelegatingAction(action, executor)
private fun reportUsage(e: AnActionEvent, executor: Executor) {
val project = e.project
val systemId = ExternalSystemDataKeys.EXTERNAL_SYSTEM_ID.getData(e.dataContext)
ExternalSystemActionsCollector.trigger(project, systemId, ExternalSystemActionsCollector.ActionId.RunExternalSystemTaskAction, e,
executor)
}
}
} | apache-2.0 | 7ccbebf25935669c5df1402472de0b2e | 36.426471 | 140 | 0.73467 | 4.901734 | false | false | false | false |
allotria/intellij-community | platform/platform-impl/src/com/intellij/openapi/project/impl/ProjectFrameAllocator.kt | 1 | 13219 | // Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.openapi.project.impl
import com.intellij.configurationStore.saveSettings
import com.intellij.conversion.CannotConvertException
import com.intellij.diagnostic.PluginException
import com.intellij.diagnostic.runActivity
import com.intellij.diagnostic.runMainActivity
import com.intellij.ide.RecentProjectsManager
import com.intellij.ide.RecentProjectsManagerBase
import com.intellij.ide.SaveAndSyncHandler
import com.intellij.ide.impl.OpenProjectTask
import com.intellij.ide.plugins.StartupAbortedException
import com.intellij.idea.SplashManager
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.impl.ApplicationImpl
import com.intellij.openapi.application.invokeAndWaitIfNeeded
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.progress.ProcessCanceledException
import com.intellij.openapi.progress.impl.ProgressResult
import com.intellij.openapi.progress.impl.ProgressRunner
import com.intellij.openapi.project.Project
import com.intellij.openapi.project.ProjectManager
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.util.NlsContexts
import com.intellij.openapi.util.registry.Registry
import com.intellij.openapi.wm.WindowManager
import com.intellij.openapi.wm.ex.ToolWindowManagerEx
import com.intellij.openapi.wm.ex.WindowManagerEx
import com.intellij.openapi.wm.impl.*
import com.intellij.platform.ProjectSelfieUtil
import com.intellij.ui.ComponentUtil
import com.intellij.ui.IdeUICustomization
import com.intellij.ui.ScreenUtil
import com.intellij.ui.scale.ScaleContext
import kotlinx.coroutines.runBlocking
import org.jetbrains.annotations.ApiStatus
import java.awt.Dimension
import java.awt.Frame
import java.awt.Image
import java.io.EOFException
import java.nio.file.Path
import java.util.concurrent.CompletableFuture
import java.util.function.Function
import javax.swing.JComponent
import kotlin.math.min
internal open class ProjectFrameAllocator(private val options: OpenProjectTask) {
open fun <T : Any> run(task: () -> T?): CompletableFuture<T?> {
if (options.isNewProject && options.useDefaultProjectAsTemplate && options.project == null) {
runBlocking {
saveSettings(ProjectManager.getInstance().defaultProject, forceSavingAllSettings = true)
}
}
return CompletableFuture.completedFuture(task())
}
/**
* Project is loaded and is initialized, project services and components can be accessed.
*/
open fun projectLoaded(project: Project) {}
open fun projectNotLoaded(error: CannotConvertException?) {
error?.let { throw error }
}
open fun projectOpened(project: Project) {}
}
internal class ProjectUiFrameAllocator(val options: OpenProjectTask, val projectStoreBaseDir: Path) : ProjectFrameAllocator(options) {
// volatile not required because created in run (before executing run task)
var frameManager: ProjectUiFrameManager? = null
@Volatile
var cancelled = false
private set
override fun <T : Any> run(task: () -> T?): CompletableFuture<T?> {
if (options.isNewProject && options.useDefaultProjectAsTemplate && options.project == null) {
invokeAndWaitIfNeeded {
SaveAndSyncHandler.getInstance().saveSettingsUnderModalProgress(ProjectManager.getInstance().defaultProject)
}
}
frameManager = createFrameManager()
val progress = (ApplicationManager.getApplication() as ApplicationImpl)
.createProgressWindowAsyncIfNeeded(getProgressTitle(), true, true, null, frameManager!!.getComponent(), null)
val progressRunner = ProgressRunner<T?>(Function {
frameManager!!.init(this@ProjectUiFrameAllocator)
try {
task()
}
catch (e: ProcessCanceledException) {
throw e
}
catch (e: Exception) {
if (e is StartupAbortedException || e is PluginException) {
StartupAbortedException.logAndExit(e)
}
else {
logger<ProjectFrameAllocator>().error(e)
projectNotLoaded(e as? CannotConvertException)
}
null
}
})
.onThread(ProgressRunner.ThreadToUse.POOLED)
.modal()
.withProgress(progress)
val progressResultFuture: CompletableFuture<ProgressResult<T?>>
if (ApplicationManager.getApplication().isDispatchThread) {
progressResultFuture = CompletableFuture.completedFuture(progressRunner.submitAndGet())
}
else {
progressResultFuture = progressRunner.submit()
}
return progressResultFuture.thenCompose { result ->
when (result.throwable) {
null -> CompletableFuture.completedFuture(result.result)
is ProcessCanceledException -> CompletableFuture.completedFuture(null)
else -> CompletableFuture.failedFuture(result.throwable)
}
}
}
@NlsContexts.ProgressTitle
private fun getProgressTitle(): String {
val projectName = options.projectName ?: (projectStoreBaseDir.fileName ?: projectStoreBaseDir).toString()
return IdeUICustomization.getInstance().projectMessage("progress.title.project.loading.name", projectName)
}
private fun createFrameManager(): ProjectUiFrameManager {
if (options.frameManager is ProjectUiFrameManager) {
return options.frameManager
}
return invokeAndWaitIfNeeded {
val freeRootFrame = (WindowManager.getInstance() as WindowManagerImpl).removeAndGetRootFrame()
if (freeRootFrame != null) {
return@invokeAndWaitIfNeeded DefaultProjectUiFrameManager(frame = freeRootFrame.frame!!, frameHelper = freeRootFrame)
}
runMainActivity("create a frame") {
val preAllocated = SplashManager.getAndUnsetProjectFrame() as IdeFrameImpl?
if (preAllocated == null) {
if (options.frameManager is FrameInfo) {
SingleProjectUiFrameManager(options.frameManager, createNewProjectFrame(forceDisableAutoRequestFocus = false, frameInfo = options.frameManager))
}
else {
DefaultProjectUiFrameManager(frame = createNewProjectFrame(forceDisableAutoRequestFocus = false, frameInfo = null), frameHelper = null)
}
}
else {
SplashProjectUiFrameManager(preAllocated)
}
}
}
}
override fun projectLoaded(project: Project) {
ApplicationManager.getApplication().invokeLater(Runnable {
val frameHelper = frameManager?.frameHelper ?: return@Runnable
val windowManager = WindowManager.getInstance() as WindowManagerImpl
runActivity("project frame assigning") {
windowManager.assignFrame(frameHelper, project)
}
runActivity("tool window pane creation") {
ToolWindowManagerEx.getInstanceEx(project).init(frameHelper)
}
}, project.disposed)
}
override fun projectNotLoaded(error: CannotConvertException?) {
cancelled = true
ApplicationManager.getApplication().invokeLater {
val frameHelper = frameManager?.frameHelper
frameManager = null
if (error != null) {
ProjectManagerImpl.showCannotConvertMessage(error, frameHelper?.frame)
}
if (frameHelper != null) {
// projectLoaded was called, but then due to some error, say cancellation, still projectNotLoaded is called
if (frameHelper.project == null) {
Disposer.dispose(frameHelper)
}
else {
WindowManagerEx.getInstanceEx().releaseFrame(frameHelper)
}
}
}
}
override fun projectOpened(project: Project) {
frameManager!!.projectOpened(project)
}
}
private fun restoreFrameState(frameHelper: ProjectFrameHelper, frameInfo: FrameInfo) {
val bounds = frameInfo.bounds?.let { FrameBoundsConverter.convertFromDeviceSpaceAndFitToScreen(it) }
val frame = frameHelper.frame!!
if (bounds != null && FrameInfoHelper.isMaximized(frameInfo.extendedState) && frame.extendedState == Frame.NORMAL) {
frame.rootPane.putClientProperty(IdeFrameImpl.NORMAL_STATE_BOUNDS, bounds)
}
if (bounds != null) {
frame.bounds = bounds
}
frame.extendedState = frameInfo.extendedState
if (frameInfo.fullScreen && FrameInfoHelper.isFullScreenSupportedInCurrentOs()) {
frameHelper.toggleFullScreen(true)
}
}
@ApiStatus.Internal
internal fun createNewProjectFrame(forceDisableAutoRequestFocus: Boolean, frameInfo: FrameInfo?): IdeFrameImpl {
val frame = IdeFrameImpl()
SplashManager.hideBeforeShow(frame)
val deviceBounds = frameInfo?.bounds
if (deviceBounds == null) {
val size = ScreenUtil.getMainScreenBounds().size
size.width = min(1400, size.width - 20)
size.height = min(1000, size.height - 40)
frame.size = size
frame.setLocationRelativeTo(null)
}
else {
val bounds = FrameBoundsConverter.convertFromDeviceSpaceAndFitToScreen(deviceBounds)
val state = frameInfo.extendedState
val isMaximized = FrameInfoHelper.isMaximized(state)
if (isMaximized && frame.extendedState == Frame.NORMAL) {
frame.rootPane.putClientProperty(IdeFrameImpl.NORMAL_STATE_BOUNDS, bounds)
}
frame.bounds = bounds
frame.extendedState = state
}
if (forceDisableAutoRequestFocus || (!ApplicationManager.getApplication().isActive && ComponentUtil.isDisableAutoRequestFocus())) {
frame.isAutoRequestFocus = false
}
frame.minimumSize = Dimension(340, frame.minimumSize.height)
return frame
}
internal interface ProjectUiFrameManager {
val frameHelper: ProjectFrameHelper?
fun init(allocator: ProjectUiFrameAllocator)
fun getComponent(): JComponent
fun projectOpened(project: Project) {
}
}
private class SplashProjectUiFrameManager(private val frame: IdeFrameImpl) : ProjectUiFrameManager {
override var frameHelper: ProjectFrameHelper? = null
private set
override fun getComponent(): JComponent = frame.rootPane
override fun init(allocator: ProjectUiFrameAllocator) {
assert(frameHelper == null)
ApplicationManager.getApplication().invokeLater {
if (allocator.cancelled) {
return@invokeLater
}
assert(frameHelper == null)
runActivity("project frame initialization") {
val frameHelper = ProjectFrameHelper(frame, null)
frameHelper.init()
// otherwise not painted if frame is already visible
frame.validate()
this.frameHelper = frameHelper
}
}
}
}
private class DefaultProjectUiFrameManager(private val frame: IdeFrameImpl, frameHelper: ProjectFrameHelper?) : ProjectUiFrameManager {
override var frameHelper: ProjectFrameHelper? = frameHelper
private set
override fun getComponent(): JComponent = frame.rootPane
override fun init(allocator: ProjectUiFrameAllocator) {
if (frameHelper != null) {
return
}
ApplicationManager.getApplication().invokeLater {
if (allocator.cancelled) {
return@invokeLater
}
runActivity("project frame initialization") {
doInit(allocator)
}
}
}
private fun doInit(allocator: ProjectUiFrameAllocator) {
val info = (RecentProjectsManager.getInstance() as? RecentProjectsManagerBase)?.getProjectMetaInfo(allocator.projectStoreBaseDir)
val frameInfo = info?.frame
val frameHelper = ProjectFrameHelper(frame, readProjectSelfie(info?.projectWorkspaceId, frame))
// must be after preInit (frame decorator is required to set full screen mode)
if (frameInfo?.bounds == null) {
(WindowManager.getInstance() as WindowManagerImpl).defaultFrameInfoHelper.info?.let {
restoreFrameState(frameHelper, it)
}
}
else {
restoreFrameState(frameHelper, frameInfo)
}
frame.isVisible = true
frameHelper.init()
this.frameHelper = frameHelper
}
}
private class SingleProjectUiFrameManager(private val frameInfo: FrameInfo, private val frame: IdeFrameImpl) : ProjectUiFrameManager {
override var frameHelper: ProjectFrameHelper? = null
private set
override fun getComponent(): JComponent = frame.rootPane
override fun init(allocator: ProjectUiFrameAllocator) {
ApplicationManager.getApplication().invokeLater {
if (allocator.cancelled) {
return@invokeLater
}
runActivity("project frame initialization") {
doInit(allocator)
}
}
}
private fun doInit(allocator: ProjectUiFrameAllocator) {
val options = allocator.options
val frameHelper = ProjectFrameHelper(frame, readProjectSelfie(options.projectWorkspaceId, frame))
if (frameInfo.fullScreen && FrameInfoHelper.isFullScreenSupportedInCurrentOs()) {
frameHelper.toggleFullScreen(true)
}
frame.isVisible = true
frameHelper.init()
this.frameHelper = frameHelper
}
}
private fun readProjectSelfie(projectWorkspaceId: String?, frame: IdeFrameImpl): Image? {
if (projectWorkspaceId != null && Registry.`is`("ide.project.loading.show.last.state", false)) {
try {
return ProjectSelfieUtil.readProjectSelfie(projectWorkspaceId, ScaleContext.create(frame))
}
catch (e: Throwable) {
if (e.cause !is EOFException) {
logger<ProjectFrameAllocator>().warn(e)
}
}
}
return null
} | apache-2.0 | 3184b746ed002f8f24e0ef145b5accbf | 33.973545 | 156 | 0.736137 | 4.843899 | false | false | false | false |
genonbeta/TrebleShot | app/src/main/java/org/monora/uprotocol/client/android/fragment/TextEditorFragment.kt | 1 | 12282 | /*
* Copyright (C) 2021 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.fragment
import android.content.ClipData
import android.content.ClipboardManager
import android.content.Intent
import android.graphics.Bitmap
import android.os.Bundle
import android.view.LayoutInflater
import android.view.Menu
import android.view.MenuInflater
import android.view.MenuItem
import android.view.View
import android.view.ViewGroup
import android.widget.EditText
import android.widget.ImageView
import android.widget.Toast
import androidx.activity.OnBackPressedCallback
import androidx.appcompat.app.AppCompatActivity
import androidx.core.widget.addTextChangedListener
import androidx.fragment.app.Fragment
import androidx.fragment.app.activityViewModels
import androidx.fragment.app.viewModels
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.liveData
import androidx.lifecycle.viewModelScope
import androidx.navigation.fragment.findNavController
import androidx.navigation.fragment.navArgs
import com.genonbeta.android.framework.ui.callback.SnackbarPlacementProvider
import com.google.android.material.bottomsheet.BottomSheetDialog
import com.google.android.material.snackbar.BaseTransientBottomBar
import com.google.android.material.snackbar.Snackbar
import com.google.zxing.BarcodeFormat
import com.google.zxing.MultiFormatWriter
import com.google.zxing.WriterException
import com.google.zxing.common.BitMatrix
import dagger.hilt.android.AndroidEntryPoint
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import org.monora.android.codescanner.BarcodeEncoder
import org.monora.uprotocol.client.android.GlideApp
import org.monora.uprotocol.client.android.R
import org.monora.uprotocol.client.android.database.model.SharedText
import org.monora.uprotocol.client.android.util.CommonErrors
import org.monora.uprotocol.client.android.viewmodel.ClientPickerViewModel
import org.monora.uprotocol.client.android.viewmodel.SharedTextsViewModel
import org.monora.uprotocol.core.CommunicationBridge
import org.monora.uprotocol.core.protocol.ClipboardType
import javax.inject.Inject
@AndroidEntryPoint
class TextEditorFragment : Fragment(R.layout.layout_text_editor), SnackbarPlacementProvider {
private val viewModel: SharedTextsViewModel by viewModels()
private val textEditorViewModel: TextEditorViewModel by viewModels()
private val args: TextEditorFragmentArgs by navArgs()
private val clientPickerViewModel: ClientPickerViewModel by activityViewModels()
private var sharedText: SharedText? = null
get() = field ?: args.sharedText
private val text
get() = requireView().findViewById<EditText>(R.id.editText).text.toString()
private var shareButton: MenuItem? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setHasOptionsMenu(true)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val editText = view.findViewById<EditText>(R.id.editText)
val text = args.text ?: args.sharedText?.text
val backPressedDispatcher = requireActivity().onBackPressedDispatcher
val snackbar = createSnackbar(R.string.sending)
val backPressedCallback = object : OnBackPressedCallback(true) {
override fun handleOnBackPressed() {
// Capture back press events when there is unsaved changes that should be handled first.
val hasObject = sharedText != null
val eventListener = object : BaseTransientBottomBar.BaseCallback<Snackbar>() {
override fun onDismissed(transientBottomBar: Snackbar?, event: Int) {
super.onDismissed(transientBottomBar, event)
isEnabled = true
}
override fun onShown(transientBottomBar: Snackbar?) {
super.onShown(transientBottomBar)
isEnabled = false
}
}
when {
checkDeletionNeeded() -> {
createSnackbar(R.string.delete_empty_text_question)
.addCallback(eventListener)
.setAction(R.string.delete) {
removeText()
backPressedDispatcher.onBackPressed()
}
.show()
}
checkSaveNeeded() -> {
createSnackbar(if (hasObject) R.string.update_clipboard_notice else R.string.save_clipboard_notice)
.addCallback(eventListener)
.setAction(if (hasObject) R.string.update else R.string.save) {
saveText()
backPressedDispatcher.onBackPressed()
}
.show()
}
else -> {
isEnabled = false
backPressedDispatcher.onBackPressed()
}
}
}
}
editText.addTextChangedListener {
backPressedCallback.isEnabled = checkDeletionNeeded() || checkSaveNeeded()
updateShareButton()
}
backPressedDispatcher.addCallback(viewLifecycleOwner, backPressedCallback)
text?.let {
editText.text.apply {
clear()
append(text)
}
}
textEditorViewModel.state.observe(viewLifecycleOwner) {
when (it) {
is SendTextState.Sending -> snackbar.setText(R.string.sending).show()
is SendTextState.Success -> snackbar.setText(R.string.send_success).show()
is SendTextState.Error -> snackbar.setText(CommonErrors.messageOf(view.context, it.exception)).show()
}
}
clientPickerViewModel.bridge.observe(viewLifecycleOwner) { bridge ->
textEditorViewModel.consume(bridge, [email protected])
}
}
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
super.onCreateOptionsMenu(menu, inflater)
inflater.inflate(R.menu.text_editor, menu)
shareButton = menu.findItem(R.id.menu_action_share_trebleshot)
}
override fun onPrepareOptionsMenu(menu: Menu) {
super.onPrepareOptionsMenu(menu)
menu.findItem(R.id.menu_action_save)
.setVisible(!checkDeletionNeeded()).isEnabled = checkSaveNeeded()
menu.findItem(R.id.menu_action_remove).isVisible = sharedText != null
menu.findItem(R.id.menu_action_show_as_qr_code).isEnabled = (text.length in 1..1200)
updateShareButton()
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
val id = item.itemId
if (id == R.id.menu_action_save) {
saveText()
createSnackbar(R.string.save_text_success).show()
} else if (id == R.id.menu_action_copy) {
(requireContext().getSystemService(AppCompatActivity.CLIPBOARD_SERVICE) as ClipboardManager)
.setPrimaryClip(ClipData.newPlainText("copiedText", text))
createSnackbar(R.string.copy_text_to_clipboard_success).show()
} else if (id == R.id.menu_action_share) {
val shareIntent: Intent = Intent(Intent.ACTION_SEND)
.putExtra(Intent.EXTRA_TEXT, text)
.setType("text/*")
startActivity(Intent.createChooser(shareIntent, getString(R.string.choose_sharing_app)))
} else if (id == R.id.menu_action_share_trebleshot) {
findNavController().navigate(TextEditorFragmentDirections.pickClient())
} else if (id == R.id.menu_action_show_as_qr_code) {
if (text.length in 1..1200) {
val formatWriter = MultiFormatWriter()
try {
val bitMatrix: BitMatrix = formatWriter.encode(text, BarcodeFormat.QR_CODE, 800, 800)
val encoder = BarcodeEncoder()
val bitmap: Bitmap = encoder.createBitmap(bitMatrix)
val dialog = BottomSheetDialog(requireActivity())
val view = LayoutInflater.from(requireActivity()).inflate(
R.layout.layout_show_text_as_qr_code, null
)
val qrImage = view.findViewById<ImageView>(R.id.layout_show_text_as_qr_code_image)
GlideApp.with(this)
.load(bitmap)
.into(qrImage)
val params = ViewGroup.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT
)
dialog.setTitle(R.string.show_as_qr_code)
dialog.setContentView(view, params)
dialog.show()
} catch (e: WriterException) {
Toast.makeText(requireContext(), R.string.unknown_failure, Toast.LENGTH_SHORT).show()
}
}
} else if (id == R.id.menu_action_remove) {
removeText()
} else return super.onOptionsItemSelected(item)
return true
}
private fun removeText() {
sharedText?.let {
viewModel.remove(it)
sharedText = null
}
}
override fun createSnackbar(resId: Int, vararg objects: Any?): Snackbar {
return Snackbar.make(requireView(), getString(resId, *objects), Snackbar.LENGTH_LONG)
}
private fun checkDeletionNeeded(): Boolean {
val editorText: String = text
return editorText.isEmpty() && !sharedText?.text.isNullOrEmpty()
}
private fun checkSaveNeeded(): Boolean {
val editorText: String = text
return editorText.isNotEmpty() && editorText != sharedText?.text
}
private fun updateShareButton() {
shareButton?.isEnabled = [email protected]()
}
private fun saveText() {
val date = System.currentTimeMillis()
var update = false
val item = sharedText?.also {
it.modified = date
it.text = text
update = true
} ?: SharedText(0, null, text, date).also {
this.sharedText = it
}
viewModel.save(item, update)
}
}
@HiltViewModel
class TextEditorViewModel @Inject internal constructor() : ViewModel() {
private val _state = MutableLiveData<SendTextState>()
val state = liveData {
emitSource(_state)
}
fun consume(bridge: CommunicationBridge, text: String) {
viewModelScope.launch(Dispatchers.IO) {
_state.postValue(SendTextState.Sending)
try {
bridge.use {
if (it.requestClipboard(text, ClipboardType.Text)) {
_state.postValue(SendTextState.Success)
}
}
} catch (e: Exception) {
_state.postValue(SendTextState.Error(e))
}
}
}
}
sealed class SendTextState {
object Sending : SendTextState()
object Success : SendTextState()
class Error(val exception: Exception) : SendTextState()
}
| gpl-2.0 | 56fb7d5eb36f19a3d33ddf4b8f4992be | 39.265574 | 123 | 0.637407 | 4.95002 | false | false | false | false |
Raizlabs/DBFlow | processor/src/main/kotlin/com/dbflow5/processor/ClassNames.kt | 1 | 5276 | package com.dbflow5.processor
import com.dbflow5.annotation.ConflictAction
import com.squareup.javapoet.ClassName
/**
* Description: The static FQCN string file to assist in providing class names for imports and more in the Compiler
*/
object ClassNames {
val BASE_PACKAGE = "com.dbflow5"
val FLOW_MANAGER_PACKAGE = "$BASE_PACKAGE.config"
val DATABASE_HOLDER_STATIC_CLASS_NAME = "GeneratedDatabaseHolder"
val CONVERTER = "$BASE_PACKAGE.converter"
val ADAPTER = "$BASE_PACKAGE.adapter"
val QUERY_PACKAGE = "$BASE_PACKAGE.query"
val STRUCTURE = "$BASE_PACKAGE.structure"
val DATABASE = "$BASE_PACKAGE.database"
val QUERIABLE = "$ADAPTER.queriable"
val PROPERTY_PACKAGE = "$QUERY_PACKAGE.property"
val CONFIG = "$BASE_PACKAGE.config"
val RUNTIME = "$BASE_PACKAGE.runtime"
val SAVEABLE = "$ADAPTER.saveable"
val PROVIDER = "$BASE_PACKAGE.provider"
val DATABASE_HOLDER: ClassName = ClassName.get(CONFIG, "DatabaseHolder")
val FLOW_MANAGER: ClassName = ClassName.get(CONFIG, "FlowManager")
val BASE_DATABASE_DEFINITION_CLASSNAME: ClassName = ClassName.get(CONFIG, "DBFlowDatabase")
val CONTENT_PROVIDER_DATABASE: ClassName = ClassName.get(PROVIDER, "ContentProviderDatabase")
val URI: ClassName = ClassName.get("android.net", "Uri")
val URI_MATCHER: ClassName = ClassName.get("android.content", "UriMatcher")
val CURSOR: ClassName = ClassName.get("android.database", "Cursor")
val FLOW_CURSOR: ClassName = ClassName.get(DATABASE, "FlowCursor")
val DATABASE_UTILS: ClassName = ClassName.get("android.database", "DatabaseUtils")
val CONTENT_VALUES: ClassName = ClassName.get("android.content", "ContentValues")
val CONTENT_URIS: ClassName = ClassName.get("android.content", "ContentUris")
val MODEL_ADAPTER: ClassName = ClassName.get(ADAPTER, "ModelAdapter")
val RETRIEVAL_ADAPTER: ClassName = ClassName.get(ADAPTER, "RetrievalAdapter")
val MODEL: ClassName = ClassName.get(STRUCTURE, "Model")
val MODEL_VIEW_ADAPTER: ClassName = ClassName.get(ADAPTER, "ModelViewAdapter")
val OBJECT_TYPE: ClassName = ClassName.get(ADAPTER, "ObjectType")
val DATABASE_STATEMENT: ClassName = ClassName.get(DATABASE, "DatabaseStatement")
val QUERY: ClassName = ClassName.get(QUERY_PACKAGE, "Query")
val TYPE_CONVERTER: ClassName = ClassName.get(CONVERTER, "TypeConverter")
val TYPE_CONVERTER_GETTER: ClassName = ClassName.get(PROPERTY_PACKAGE,
"TypeConvertedProperty.TypeConverterGetter")
val CONFLICT_ACTION: ClassName = ClassName.get(ConflictAction::class.java)
val CONTENT_VALUES_LISTENER: ClassName = ClassName.get(QUERY_PACKAGE, "ContentValuesListener")
val LOAD_FROM_CURSOR_LISTENER: ClassName = ClassName.get(QUERY_PACKAGE, "LoadFromCursorListener")
val SQLITE_STATEMENT_LISTENER: ClassName = ClassName.get(QUERY_PACKAGE, "SQLiteStatementListener")
val PROPERTY: ClassName = ClassName.get(PROPERTY_PACKAGE, "Property")
val TYPE_CONVERTED_PROPERTY: ClassName = ClassName.get(PROPERTY_PACKAGE, "TypeConvertedProperty")
val WRAPPER_PROPERTY: ClassName = ClassName.get(PROPERTY_PACKAGE, "WrapperProperty")
val IPROPERTY: ClassName = ClassName.get(PROPERTY_PACKAGE, "IProperty")
val INDEX_PROPERTY: ClassName = ClassName.get(PROPERTY_PACKAGE, "IndexProperty")
val OPERATOR_GROUP: ClassName = ClassName.get(QUERY_PACKAGE, "OperatorGroup")
val ICONDITIONAL: ClassName = ClassName.get(QUERY_PACKAGE, "IConditional")
val BASE_CONTENT_PROVIDER: ClassName = ClassName.get(PROVIDER, "BaseContentProvider")
val BASE_MODEL: ClassName = ClassName.get(STRUCTURE, "BaseModel")
val MODEL_CACHE: ClassName = ClassName.get("$QUERY_PACKAGE.cache", "ModelCache")
val MULTI_KEY_CACHE_CONVERTER: ClassName = ClassName.get("$QUERY_PACKAGE.cache", "MultiKeyCacheConverter")
val SIMPLE_MAP_CACHE: ClassName = ClassName.get("$QUERY_PACKAGE.cache", "SimpleMapCache")
val CACHEABLE_MODEL_LOADER: ClassName = ClassName.get(QUERIABLE, "CacheableModelLoader")
val SINGLE_MODEL_LOADER: ClassName = ClassName.get(QUERIABLE, "SingleModelLoader")
val CACHEABLE_LIST_MODEL_LOADER: ClassName = ClassName.get(QUERIABLE, "CacheableListModelLoader")
val LIST_MODEL_LOADER: ClassName = ClassName.get(QUERIABLE, "ListModelLoader")
val CACHE_ADAPTER: ClassName = ClassName.get(ADAPTER, "CacheAdapter")
val DATABASE_WRAPPER: ClassName = ClassName.get(DATABASE, "DatabaseWrapper")
val SQLITE: ClassName = ClassName.get(QUERY_PACKAGE, "SQLite")
val CACHEABLE_LIST_MODEL_SAVER: ClassName = ClassName.get(SAVEABLE, "CacheableListModelSaver")
val SINGLE_MODEL_SAVER: ClassName = ClassName.get(SAVEABLE, "ModelSaver")
val SINGLE_KEY_CACHEABLE_MODEL_LOADER: ClassName = ClassName.get(QUERIABLE, "SingleKeyCacheableModelLoader")
val SINGLE_KEY_CACHEABLE_LIST_MODEL_LOADER: ClassName = ClassName.get(QUERIABLE, "SingleKeyCacheableListModelLoader")
val NON_NULL: ClassName = ClassName.get("android.support.annotation", "NonNull")
val NON_NULL_X: ClassName = ClassName.get("androidx.annotation", "NonNull")
val GENERATED: ClassName = ClassName.get("javax.annotation", "Generated")
val STRING_UTILS: ClassName = ClassName.get(BASE_PACKAGE, "StringUtils")
}
| mit | dcfcffca209d5a9eeb949896b2562298 | 51.76 | 121 | 0.747915 | 4.138039 | false | true | false | false |
leafclick/intellij-community | java/java-tests/testSrc/com/intellij/codeInsight/externalAnnotation/location/JBBundledAnnotationsProviderTest.kt | 1 | 2494 | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.codeInsight.externalAnnotation.location
import com.intellij.openapi.application.WriteAction
import com.intellij.openapi.roots.libraries.Library
import com.intellij.openapi.roots.libraries.LibraryTablesRegistrar
import com.intellij.testFramework.LightPlatformTestCase
import org.assertj.core.api.Assertions.assertThat
import org.junit.Test
class JBBundledAnnotationsProviderTest : LightPlatformTestCase() {
@Test
fun `test missing annotation is not provided`() {
val provider = JBBundledAnnotationsProvider()
val lib = createLibrary()
val locations = provider.getLocations(project, lib, "myGroup", "missing-artifact", "1.0")
assertThat(locations).hasSize(0)
}
@Test
fun `test available annotation provided`() {
val provider = JBBundledAnnotationsProvider()
val lib = createLibrary()
val locations = provider.getLocations(project, lib, "junit", "junit", "4.12")
assertThat(locations)
.hasSize(1)
.usingElementComparatorIgnoringFields("myRepositoryUrls")
.containsOnly(AnnotationsLocation("org.jetbrains.externalAnnotations.junit", "junit", "4.12-an1"))
}
@Test
fun `test compatible version choice`() {
val provider = JBBundledAnnotationsProvider()
val lib = createLibrary()
assertThat(provider.getLocations(project, lib, "junit", "junit", "4.1"))
.hasSize(1)
.usingElementComparatorIgnoringFields("myRepositoryUrls")
.containsOnly(AnnotationsLocation("org.jetbrains.externalAnnotations.junit", "junit", "4.12-an1"))
assertThat(provider.getLocations(project, lib, "junit", "junit", "4.9"))
.hasSize(1)
.usingElementComparatorIgnoringFields("myRepositoryUrls")
.containsOnly(AnnotationsLocation("org.jetbrains.externalAnnotations.junit", "junit", "4.12-an1"))
}
@Test
fun `test incompatible version skipped`() {
val provider = JBBundledAnnotationsProvider()
val lib = createLibrary()
assertThat(provider.getLocations(project, lib, "junit", "junit", "3.9")).hasSize(0)
assertThat(provider.getLocations(project, lib, "junit", "junit", "5.0")).hasSize(0)
}
private fun createLibrary(): Library {
val libraryTable = LibraryTablesRegistrar.getInstance().libraryTable
return WriteAction.compute<Library, RuntimeException> { libraryTable.createLibrary("test-library") }
}
} | apache-2.0 | 08feff29aab9bffd1a13161bbe5a79e6 | 36.238806 | 140 | 0.739374 | 4.367776 | false | true | false | false |
faceofcat/Tesla-Core-Lib | src/main/kotlin/net/ndrei/teslacorelib/config/configutils.kt | 1 | 2957 | @file:Suppress("unused")
package net.ndrei.teslacorelib.config
import com.google.gson.JsonElement
import com.google.gson.JsonObject
import com.google.gson.JsonSyntaxException
import net.minecraft.item.Item
import net.minecraft.item.ItemStack
import net.minecraft.util.JsonUtils
import net.minecraft.util.ResourceLocation
import net.minecraftforge.fluids.FluidRegistry
import net.minecraftforge.fluids.FluidStack
import net.minecraftforge.oredict.OreDictionary
import net.ndrei.teslacorelib.utils.copyWithSize
fun JsonObject.readFluidStack(memberName: String) =
if (this.has(memberName)) JsonUtils.getJsonObject(this, memberName)?.readFluidStack() else null
fun JsonObject.readFluidStack(): FluidStack? {
val fluid = JsonUtils.getString(this, "name", "")
.let { FluidRegistry.getFluid(it) } ?: return null
val amount = JsonUtils.getInt(this, "quantity", 0)
return if (amount <= 0) null else FluidStack(fluid, amount)
}
fun JsonObject.readItemStacks(memberName: String): List<ItemStack> =
if (this.has(memberName)) JsonUtils.getJsonObject(this, memberName).readItemStacks() else listOf()
fun JsonObject.readItemStacks(): List<ItemStack> {
val item = JsonUtils.getString(this, "name", "")
.let {
val registryName = if (it.isNullOrEmpty()) null else ResourceLocation(it)
if ((registryName != null) && Item.REGISTRY.containsKey(registryName))
Item.REGISTRY.getObject(registryName)
else null
}
if (item != null) {
val meta = JsonUtils.getInt(this, "meta", 0)
val amount = JsonUtils.getInt(this, "quantity", 1)
return listOf(ItemStack(item, amount, meta))
}
else {
val ore = JsonUtils.getString(this, "ore", "")
if (!ore.isNullOrEmpty()) {
val amount = JsonUtils.getInt(this, "quantity", 1)
return OreDictionary.getOres(ore)
.map { it.copyWithSize(amount) }
}
}
return listOf()
}
fun JsonObject.readItemStack(memberName: String) = this.readItemStacks(memberName).firstOrNull()
fun JsonObject.readItemStack() = this.readItemStacks().firstOrNull()
fun JsonElement.getMember(memberName: String, throwError: Boolean = false): JsonElement? =
if ((this is JsonObject) && this.has(memberName))
this.get(memberName)
else if (this.isJsonPrimitive)
this // assume this is the member one was looking for
else if (throwError)
throw JsonSyntaxException("Missing $memberName.")
else
null
fun JsonElement.getLong(memberName: String, fallback: Long = 0L, throwError: Boolean = false): Long {
val member = this.getMember(memberName, throwError)
if (member?.isJsonPrimitive == true) {
return member.asJsonPrimitive.asLong
}
else if (throwError) {
throw JsonSyntaxException("Missing $memberName, expected to find a Long.")
}
return fallback
}
| mit | 1c48c1432b9101529675bbab0ce67943 | 36.43038 | 102 | 0.68955 | 4.38724 | false | false | false | false |
kpi-ua/ecampus-client-android | app/src/main/java/com/goldenpiedevs/schedule/app/ui/view/LessonItemView.kt | 1 | 1437 | package com.goldenpiedevs.schedule.app.ui.view
import android.content.Context
import android.util.AttributeSet
import android.view.LayoutInflater
import android.view.View
import android.widget.LinearLayout
import com.goldenpiedevs.schedule.app.R
import kotlinx.android.synthetic.main.lesson_item_view_layout.view.*
class LessonItemView constructor(
context: Context,
attrs: AttributeSet? = null) : LinearLayout(context, attrs) {
var subText: String? = null
set(value) {
field = value
subTitle.text = field
if (!isInEditMode)
value?.let {
when {
it.isNotEmpty() -> subTitle.visibility = View.VISIBLE
it.isEmpty() -> subTitle.visibility = View.GONE
}
}
}
init {
val inflater = context.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater
inflater.inflate(R.layout.lesson_item_view_layout, this)
attrs?.let {
with(context.obtainStyledAttributes(it, R.styleable.LessonItemView, 0, 0)) {
title.text = getString(R.styleable.LessonItemView_liv_title)
subText = getString(R.styleable.LessonItemView_liv_subtitle)
icon.setImageDrawable(getDrawable(R.styleable.LessonItemView_liv_icon))
recycle()
}
}
}
} | apache-2.0 | ecb2d9e3a44d37bd5c779888e328441c | 31.681818 | 98 | 0.614475 | 4.680782 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/idea/tests/test/org/jetbrains/kotlin/findUsages/KotlinFindUsageConfigurator.kt | 5 | 1723 | // 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.findUsages
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.module.Module
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
import com.intellij.testFramework.fixtures.JavaCodeInsightTestFixture
interface KotlinFindUsageConfigurator {
val project: Project
val file: PsiFile
val module: Module
val editor: Editor?
val elementAtCaret: PsiElement
fun configureByFile(filePath: String)
fun configureByFiles(filePaths: List<String>)
fun renameElement(element: PsiElement, newName: String)
companion object {
fun fromFixture(fixture: JavaCodeInsightTestFixture): KotlinFindUsageConfigurator = object : KotlinFindUsageConfigurator {
override val project: Project get() = fixture.project
override val file: PsiFile get() = fixture.file
override val module: Module get() = fixture.module
override val editor: Editor? get() = fixture.editor
override val elementAtCaret: PsiElement get() = fixture.elementAtCaret
override fun configureByFile(filePath: String) {
fixture.configureByFile(filePath)
}
override fun configureByFiles(filePaths: List<String>) {
fixture.configureByFiles(*filePaths.toTypedArray())
}
override fun renameElement(element: PsiElement, newName: String) {
fixture.renameElement(element, newName)
}
}
}
}
| apache-2.0 | 0d8bbe64203b4e7143789cfd6217beb2 | 41.02439 | 158 | 0.704585 | 5.158683 | false | true | false | false |
fabmax/kool | kool-physics/src/jsMain/kotlin/de/fabmax/kool/physics/RigidBody.kt | 1 | 4155 | package de.fabmax.kool.physics
import de.fabmax.kool.math.MutableVec3f
import de.fabmax.kool.math.Vec3f
import physx.*
actual abstract class RigidBody : RigidActor() {
@Suppress("UNCHECKED_CAST_TO_EXTERNAL_INTERFACE")
internal val pxRigidBody: PxRigidBody
get() = pxRigidActor as PxRigidBody
actual var mass: Float
get() = pxRigidBody.mass
set(value) { pxRigidBody.mass = value }
private var isInertiaSet = false
actual var inertia: Vec3f
get() = pxRigidBody.massSpaceInertiaTensor.toVec3f(bufInertia)
set(value) {
pxRigidBody.massSpaceInertiaTensor = value.toPxVec3(pxTmpVec)
isInertiaSet = true
}
actual var linearVelocity: Vec3f
get() = pxRigidBody.linearVelocity.toVec3f(bufLinVelocity)
set(value) { pxRigidBody.linearVelocity = value.toPxVec3(pxTmpVec) }
actual var angularVelocity: Vec3f
get() = pxRigidBody.angularVelocity.toVec3f(bufAngVelocity)
set(value) { pxRigidBody.angularVelocity = value.toPxVec3(pxTmpVec) }
actual var maxLinearVelocity: Float
get() = pxRigidBody.maxLinearVelocity
set(value) { pxRigidBody.maxLinearVelocity = value }
actual var maxAngularVelocity: Float
get() = pxRigidBody.maxAngularVelocity
set(value) { pxRigidBody.maxAngularVelocity = value }
actual var linearDamping: Float
get() = pxRigidBody.linearDamping
set(value) { pxRigidBody.linearDamping = value }
actual var angularDamping: Float
get() = pxRigidBody.angularDamping
set(value) { pxRigidBody.angularDamping = value }
private val bufInertia = MutableVec3f()
private val bufLinVelocity = MutableVec3f()
private val bufAngVelocity = MutableVec3f()
private val tmpVec = MutableVec3f()
private val pxTmpVec = PxVec3()
override fun attachShape(shape: Shape) {
super.attachShape(shape)
if (!isInertiaSet) {
inertia = shape.geometry.estimateInertiaForMass(mass)
}
}
override fun release() {
super.release()
pxTmpVec.destroy()
}
actual fun updateInertiaFromShapesAndMass() {
Physics.PxRigidBodyExt.setMassAndUpdateInertia(pxRigidBody, mass)
}
actual fun addForceAtPos(force: Vec3f, pos: Vec3f, isLocalForce: Boolean, isLocalPos: Boolean) {
MemoryStack.stackPush().use { mem ->
val pxForce = force.toPxVec3(mem.createPxVec3())
val pxPos = pos.toPxVec3(mem.createPxVec3())
when {
isLocalForce && isLocalPos -> Physics.PxRigidBodyExt.addLocalForceAtLocalPos(pxRigidBody, pxForce, pxPos)
isLocalForce && !isLocalPos -> Physics.PxRigidBodyExt.addLocalForceAtPos(pxRigidBody, pxForce, pxPos)
!isLocalForce && isLocalPos -> Physics.PxRigidBodyExt.addForceAtLocalPos(pxRigidBody, pxForce, pxPos)
else -> Physics.PxRigidBodyExt.addForceAtPos(pxRigidBody, pxForce, pxPos)
}
}
}
actual fun addImpulseAtPos(impulse: Vec3f, pos: Vec3f, isLocalImpulse: Boolean, isLocalPos: Boolean) {
MemoryStack.stackPush().use { mem ->
val pxImpulse = impulse.toPxVec3(mem.createPxVec3())
val pxPos = pos.toPxVec3(mem.createPxVec3())
when {
isLocalImpulse && isLocalPos -> Physics.PxRigidBodyExt.addLocalForceAtLocalPos(pxRigidBody, pxImpulse, pxPos, PxForceModeEnum.eIMPULSE)
isLocalImpulse && !isLocalPos -> Physics.PxRigidBodyExt.addLocalForceAtPos(pxRigidBody, pxImpulse, pxPos, PxForceModeEnum.eIMPULSE)
!isLocalImpulse && isLocalPos -> Physics.PxRigidBodyExt.addForceAtLocalPos(pxRigidBody, pxImpulse, pxPos, PxForceModeEnum.eIMPULSE)
else -> Physics.PxRigidBodyExt.addForceAtPos(pxRigidBody, pxImpulse, pxPos, PxForceModeEnum.eIMPULSE)
}
}
}
actual fun addTorque(torque: Vec3f, isLocalTorque: Boolean) {
tmpVec.set(torque)
if (isLocalTorque) {
transform.transform(tmpVec, 0f)
}
pxRigidBody.addTorque(tmpVec.toPxVec3(pxTmpVec))
}
} | apache-2.0 | 818f23cac88416093c1cccd0b63dcd88 | 38.961538 | 151 | 0.675331 | 3.872321 | false | false | false | false |
kickstarter/android-oss | app/src/main/java/com/kickstarter/mock/factories/CommentFactory.kt | 1 | 6092 | package com.kickstarter.mock.factories
import com.kickstarter.models.Avatar
import com.kickstarter.models.Comment
import com.kickstarter.models.User
import com.kickstarter.ui.data.CommentCardData
import org.joda.time.DateTime
class CommentFactory {
companion object {
// - Comment created on the app that has not yet being send to the backend
fun commentToPostWithUser(user: User): Comment {
return Comment.builder()
.id(-1)
.author(user)
.body("Some text here")
.parentId(-1)
.repliesCount(0)
.cursor("")
.authorBadges(listOf())
.deleted(false)
.authorCanceledPledge(false)
.createdAt(DateTime.now())
.build()
}
fun commentWithCanceledPledgeAuthor(user: User): Comment {
return Comment.builder()
.id(-1)
.author(user)
.body("Some text here")
.parentId(-1)
.repliesCount(0)
.cursor("")
.authorBadges(listOf())
.deleted(false)
.authorCanceledPledge(true)
.createdAt(DateTime.now())
.build()
}
fun commentFromCurrentUser(user: User, authorBadges: List<String>): Comment {
return Comment.builder()
.id(1)
.author(user)
.body("Some text here")
.parentId(1)
.repliesCount(0)
.cursor("")
.authorBadges(authorBadges)
.authorCanceledPledge(false)
.deleted(false)
.createdAt(DateTime.now())
.build()
}
fun comment(
avatar: Avatar = AvatarFactory.avatar(),
name: String = "joe",
body: String = "Some Comment",
repliesCount: Int = 0,
isDelete: Boolean = false,
): Comment {
return Comment.builder()
.id(1)
.author(
UserFactory.user()
.toBuilder()
.id(1L).name(name).avatar(avatar)
.build()
)
.parentId(-1)
.repliesCount(repliesCount)
.cursor("")
.authorBadges(listOf())
.authorCanceledPledge(false)
.deleted(isDelete)
.createdAt(DateTime.parse("2021-01-01T00:00:00Z"))
.body(body)
.build()
}
fun liveComment(comment: String = "Some Comment", createdAt: DateTime): Comment {
return Comment.builder()
.body(comment)
.parentId(-1)
.authorBadges(listOf())
.createdAt(createdAt)
.cursor("")
.deleted(false)
.authorCanceledPledge(false)
.id(-1)
.repliesCount(0)
.author(
UserFactory.user()
.toBuilder()
.id(1L)
.avatar(AvatarFactory.avatar())
.build()
)
.build()
}
fun reply(comment: String = "Some Comment", createdAt: DateTime): Comment {
return Comment.builder()
.body(comment)
.parentId(1)
.authorBadges(listOf())
.createdAt(createdAt)
.cursor("")
.deleted(false)
.id(-1L)
.repliesCount(0)
.authorCanceledPledge(false)
.author(
UserFactory.user()
.toBuilder()
.id(1L)
.avatar(AvatarFactory.avatar())
.build()
)
.build()
}
fun liveCommentCardData(comment: String = "Some Comment", createdAt: DateTime, currentUser: User, isDelete: Boolean = false, hasFlaggings: Boolean = false, sustained: Boolean = false, repliesCount: Int = 0): CommentCardData {
val project = ProjectFactory.project().toBuilder().creator(UserFactory.creator().toBuilder().id(278438049L).build()).build()
return CommentCardData(
Comment.builder()
.body(comment)
.parentId(-1)
.authorBadges(listOf())
.createdAt(createdAt)
.cursor("")
.deleted(isDelete)
.hasFlaggings(hasFlaggings)
.sustained(sustained)
.id(-1)
.repliesCount(repliesCount)
.author(currentUser)
.authorCanceledPledge(false)
.build(),
0,
project.id().toString(),
project
)
}
fun liveCanceledPledgeCommentCardData(comment: String = "Some Comment", createdAt: DateTime, currentUser: User, isDelete: Boolean = false, repliesCount: Int = 0): CommentCardData {
val project = ProjectFactory.project().toBuilder().creator(UserFactory.creator().toBuilder().id(278438049L).build()).build()
return CommentCardData(
Comment.builder()
.body(comment)
.parentId(-1)
.authorBadges(listOf())
.createdAt(createdAt)
.cursor("")
.deleted(isDelete)
.id(-1)
.authorCanceledPledge(true)
.repliesCount(repliesCount)
.author(currentUser)
.build(),
0,
project.id().toString(),
project
)
}
}
}
| apache-2.0 | fd0a1043b7e0f2eee178b440c178be5b | 34.213873 | 233 | 0.452725 | 5.329834 | false | false | false | false |
fabmax/kool | kool-core/src/commonMain/kotlin/de/fabmax/kool/modules/ui2/Sizes.kt | 1 | 2603 | package de.fabmax.kool.modules.ui2
import de.fabmax.kool.util.Font
import de.fabmax.kool.util.MsdfFont
data class Sizes(
val normalText: Font,
val largeText: Font,
val sliderHeight: Dp,
val checkboxSize: Dp,
val radioButtonSize: Dp,
val switchSize: Dp,
val gap: Dp,
val smallGap: Dp,
val largeGap: Dp,
val borderWidth: Dp,
) {
companion object {
val small = small()
val medium = medium()
val large = large()
fun small(
normalText: Font = MsdfFont(sizePts = 12f),
largeText: Font = MsdfFont(sizePts = 16f),
sliderHeight: Dp = Dp(14f),
checkboxSize: Dp = Dp(14f),
radioButtonSize: Dp = Dp(14f),
switchSize: Dp = Dp(14f),
gap: Dp = Dp(8f),
smallGap: Dp = Dp(4f),
largeGap: Dp = Dp(16f),
borderWidth: Dp = Dp(1f)
): Sizes = Sizes(
normalText,
largeText,
sliderHeight,
checkboxSize,
radioButtonSize,
switchSize,
gap,
smallGap,
largeGap,
borderWidth
)
fun medium(
normalText: Font = MsdfFont(sizePts = 15f),
largeText: Font = MsdfFont(sizePts = 20f),
sliderHeight: Dp = Dp(17f),
checkboxSize: Dp = Dp(17f),
radioButtonSize: Dp = Dp(17f),
switchSize: Dp = Dp(17f),
gap: Dp = Dp(10f),
smallGap: Dp = Dp(5f),
largeGap: Dp = Dp(20f),
borderWidth: Dp = Dp(1.25f)
): Sizes = Sizes(
normalText,
largeText,
sliderHeight,
checkboxSize,
radioButtonSize,
switchSize,
gap,
smallGap,
largeGap,
borderWidth
)
fun large(
normalText: Font = MsdfFont(sizePts = 18f),
largeText: Font = MsdfFont(sizePts = 24f),
sliderHeight: Dp = Dp(20f),
checkboxSize: Dp = Dp(20f),
radioButtonSize: Dp = Dp(20f),
switchSize: Dp = Dp(20f),
gap: Dp = Dp(12f),
smallGap: Dp = Dp(6f),
largeGap: Dp = Dp(24f),
borderWidth: Dp = Dp(1.5f)
): Sizes = Sizes(
normalText,
largeText,
sliderHeight,
checkboxSize,
radioButtonSize,
switchSize,
gap,
smallGap,
largeGap,
borderWidth
)
}
} | apache-2.0 | 18b036295c471c4aecf8edc39ead347f | 26.125 | 55 | 0.478678 | 4.041925 | false | false | false | false |
kickstarter/android-oss | app/src/main/java/com/kickstarter/ui/adapters/DiscoveryPagerAdapter.kt | 1 | 3879 | package com.kickstarter.ui.adapters
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import androidx.fragment.app.FragmentPagerAdapter
import com.kickstarter.libs.utils.extensions.positionFromSort
import com.kickstarter.models.Category
import com.kickstarter.services.DiscoveryParams
import com.kickstarter.ui.ArgumentsKey
import com.kickstarter.ui.fragments.DiscoveryFragment
import rx.Observable
class DiscoveryPagerAdapter(
fragmentManager: FragmentManager,
private val fragments: MutableList<DiscoveryFragment>,
private val pageTitles: List<String>,
private val delegate: Delegate
) : FragmentPagerAdapter(fragmentManager, BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT) {
interface Delegate {
fun discoveryPagerAdapterSetPrimaryPage(adapter: DiscoveryPagerAdapter, position: Int)
}
override fun setPrimaryItem(container: ViewGroup, position: Int, `object`: Any) {
super.setPrimaryItem(container, position, `object`)
delegate.discoveryPagerAdapterSetPrimaryPage(this, position)
}
override fun instantiateItem(container: ViewGroup, position: Int): Any {
val fragment = super.instantiateItem(container, position) as DiscoveryFragment
fragments[position] = fragment
return fragment
}
override fun getItem(position: Int): Fragment {
return fragments[position]
}
override fun getCount(): Int {
return DiscoveryParams.Sort.defaultSorts.size
}
override fun getPageTitle(position: Int): CharSequence? {
return pageTitles[position]
}
/**
* Passes along root categories to its fragment position to help fetch appropriate projects.
*/
fun takeCategoriesForPosition(categories: List<Category>, position: Int) {
Observable.from(fragments)
.filter(DiscoveryFragment::isInstantiated)
.filter(DiscoveryFragment::isAttached)
.filter { frag: DiscoveryFragment ->
val fragmentPosition = frag.arguments?.getInt(ArgumentsKey.DISCOVERY_SORT_POSITION)
fragmentPosition == position
}
.subscribe { frag: DiscoveryFragment -> frag.takeCategories(categories) }
}
/**
* Take current params from activity and pass to the appropriate fragment.
*/
fun takeParams(params: DiscoveryParams) {
Observable.from(fragments)
.filter(DiscoveryFragment::isInstantiated)
.filter(DiscoveryFragment::isAttached)
.filter { frag: DiscoveryFragment ->
val fragmentPosition = frag.arguments?.getInt(ArgumentsKey.DISCOVERY_SORT_POSITION)
params.sort().positionFromSort() == fragmentPosition
}
.subscribe { frag: DiscoveryFragment -> frag.updateParams(params) }
}
/**
* Call when the view model tells us to clear specific pages.
*/
fun clearPages(pages: List<Int?>) {
Observable.from(fragments)
.filter(DiscoveryFragment::isInstantiated)
.filter(DiscoveryFragment::isAttached)
.filter { frag: DiscoveryFragment ->
val fragmentPosition = frag.arguments?.getInt(ArgumentsKey.DISCOVERY_SORT_POSITION)
pages.contains(fragmentPosition)
}
.subscribe { obj: DiscoveryFragment -> obj.clearPage() }
}
fun scrollToTop(position: Int) {
Observable.from(fragments)
.filter(DiscoveryFragment::isInstantiated)
.filter(DiscoveryFragment::isAttached)
.filter { frag: DiscoveryFragment ->
val fragmentPosition = frag.arguments?.getInt(ArgumentsKey.DISCOVERY_SORT_POSITION)
position == fragmentPosition
}
.subscribe { obj: DiscoveryFragment -> obj.scrollToTop() }
}
}
| apache-2.0 | b1fbbab25ce6b5c39e315e9d97d770cc | 38.181818 | 99 | 0.683166 | 5.144562 | false | false | false | false |
jotomo/AndroidAPS | core/src/main/java/info/nightscout/androidaps/utils/JsonHelper.kt | 1 | 4091 | package info.nightscout.androidaps.utils
import org.json.JSONException
import org.json.JSONObject
object JsonHelper {
@JvmStatic
fun safeGetObject(json: JSONObject?, fieldName: String, defaultValue: Any): Any {
var result = defaultValue
if (json != null && json.has(fieldName)) {
try {
result = json[fieldName]
} catch (ignored: JSONException) {
}
}
return result
}
@JvmStatic
fun safeGetJSONObject(json: JSONObject?, fieldName: String, defaultValue: JSONObject?): JSONObject? {
var result = defaultValue
if (json != null && json.has(fieldName)) {
try {
result = json.getJSONObject(fieldName)
} catch (ignored: JSONException) {
}
}
return result
}
@JvmStatic
fun safeGetString(json: JSONObject?, fieldName: String): String? {
var result: String? = null
if (json != null && json.has(fieldName)) {
try {
result = json.getString(fieldName)
} catch (ignored: JSONException) {
}
}
return result
}
@JvmStatic
fun safeGetString(json: JSONObject?, fieldName: String, defaultValue: String): String {
var result = defaultValue
if (json != null && json.has(fieldName)) {
try {
result = json.getString(fieldName)
} catch (ignored: JSONException) {
}
}
return result
}
@JvmStatic
fun safeGetStringAllowNull(json: JSONObject?, fieldName: String, defaultValue: String?): String? {
var result = defaultValue
if (json != null && json.has(fieldName)) {
try {
result = json.getString(fieldName)
} catch (ignored: JSONException) {
}
}
return result
}
@JvmStatic
fun safeGetDouble(json: JSONObject?, fieldName: String): Double {
var result = 0.0
if (json != null && json.has(fieldName)) {
try {
result = json.getDouble(fieldName)
} catch (ignored: JSONException) {
}
}
return result
}
@JvmStatic
fun safeGetDoubleAllowNull(json: JSONObject?, fieldName: String): Double? {
var result: Double? = null
if (json != null && json.has(fieldName)) {
try {
result = json.getDouble(fieldName)
} catch (ignored: JSONException) {
}
}
return result
}
@JvmStatic
fun safeGetDouble(json: JSONObject?, fieldName: String, defaultValue: Double): Double {
var result = defaultValue
if (json != null && json.has(fieldName)) {
try {
result = json.getDouble(fieldName)
} catch (ignored: JSONException) {
}
}
return result
}
@JvmStatic
fun safeGetInt(json: JSONObject?, fieldName: String): Int =
safeGetInt(json, fieldName, 0)
@JvmStatic
fun safeGetInt(json: JSONObject?, fieldName: String, defaultValue: Int): Int {
var result = defaultValue
if (json != null && json.has(fieldName)) {
try {
result = json.getInt(fieldName)
} catch (ignored: JSONException) {
}
}
return result
}
@JvmStatic
fun safeGetLong(json: JSONObject?, fieldName: String): Long {
var result: Long = 0
if (json != null && json.has(fieldName)) {
try {
result = json.getLong(fieldName)
} catch (ignored: JSONException) {
}
}
return result
}
@JvmStatic
fun safeGetBoolean(json: JSONObject?, fieldName: String): Boolean {
var result = false
if (json != null && json.has(fieldName)) {
try {
result = json.getBoolean(fieldName)
} catch (ignored: JSONException) {
}
}
return result
}
} | agpl-3.0 | 9f5434baaf69f0a81b76501ca3392e0a | 27.615385 | 105 | 0.534833 | 4.911164 | false | false | false | false |
kelsos/mbrc | app/src/main/kotlin/com/kelsos/mbrc/data/DiscoveryMessage.kt | 1 | 549 | package com.kelsos.mbrc.data
import com.fasterxml.jackson.annotation.JsonIgnoreProperties
import com.fasterxml.jackson.annotation.JsonProperty
@JsonIgnoreProperties(ignoreUnknown = true)
class DiscoveryMessage {
@JsonProperty("name")
var name: String? = null
@JsonProperty("address")
var address: String? = null
@JsonProperty("port")
var port: Int = 0
@JsonProperty("context")
var context: String? = null
override fun toString(): String {
return "{name='$name', address='$address', port=$port, context='$context'}"
}
}
| gpl-3.0 | 633d25a32757aecbeb0a95bf394f5761 | 22.869565 | 79 | 0.723133 | 4.159091 | false | false | false | false |
ReplayMod/ReplayMod | src/main/kotlin/com/replaymod/core/gui/common/input/UIDecimalInput.kt | 1 | 2303 | package com.replaymod.core.gui.common.input
import java.math.BigDecimal
import java.math.MathContext
import java.text.DecimalFormat
class UIDecimalInput(
precision: Int = 5,
) : UIAdvancedTextInput() {
private val mathContext = MathContext(precision)
private val format = DecimalFormat("0." + "0".repeat(precision)).apply {
minimumFractionDigits = precision
maximumFractionDigits = precision
}
private fun BigDecimal.formatString() = format.format(this)
private fun String.parseDecimal(): BigDecimal? = try {
BigDecimal(this, mathContext)
} catch (e: NumberFormatException) {
null
}
var value: BigDecimal
get() = getText().parseDecimal() ?: BigDecimal.ZERO
set(value) {
val str = value.formatString()
if (getText() != str) {
setText(str)
}
}
override fun shouldReplaceExistingText(add: AddTextOperation): Boolean =
super.shouldReplaceExistingText(add) &&
(add.newText.length != 1 || getText()[add.startPos.column] != '.' || add.newText == ".")
override fun fixText(): TextOperation? {
val unformatted = getText()
val duration = getText().parseDecimal() ?: return null
val formatted = duration.formatString()
if (formatted != unformatted) {
val start = LinePosition(0, 0, false)
return ReplaceTextOperation(
AddTextOperation(formatted, start),
RemoveTextOperation(start, LinePosition(0, unformatted.length, false), false)
)
}
return NoOperation()
}
override fun commitTextOperation(operation: TextOperation) {
var op = operation
// If they try to delete the separator, move the cursor before it instead
if (op is RemoveTextOperation && op.text == ".") {
cursor = op.startPos
otherSelectionEnd = cursor
return
}
// If they add the final digit before a separator, move the cursor past the separator as well
if (op is AddTextOperation && getText().drop(op.endPos.column).startsWith(".")) {
op = AddTextOperation(op.newText + ".", op.startPos)
}
super.commitTextOperation(op)
}
} | gpl-3.0 | ba9d7645df5d5cb452db00da8dab2160 | 31.914286 | 104 | 0.61485 | 4.652525 | false | false | false | false |
jwren/intellij-community | platform/diff-impl/src/com/intellij/diff/tools/combined/CombinedLazyDiffViewer.kt | 1 | 1424 | // 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.diff.tools.combined
import com.intellij.diff.FrameDiffTool
import com.intellij.diff.FrameDiffTool.DiffViewer
import com.intellij.diff.chains.DiffRequestProducer
import com.intellij.ui.components.JBLoadingPanel
import com.intellij.util.ui.JBUI
import com.intellij.util.ui.JBValue
import com.intellij.util.ui.UIUtil
import java.awt.BorderLayout
import java.awt.Dimension
import javax.swing.JComponent
internal class CombinedLazyDiffViewer(val requestProducer: DiffRequestProducer, size: Dimension? = null) : DiffViewer {
private val loadingPanel = JBLoadingPanel(BorderLayout(), this)
.apply {
add(JBUI.Panels.simplePanel()
.apply {
background = UIUtil.getListBackground()
preferredSize = if (size != null) size else HEIGHT.get().let { height -> Dimension(height, height) }
})
}
override fun getComponent(): JComponent = loadingPanel
override fun getPreferredFocusedComponent(): JComponent = loadingPanel
override fun init(): FrameDiffTool.ToolbarComponents {
loadingPanel.startLoading()
return FrameDiffTool.ToolbarComponents()
}
override fun dispose() {
loadingPanel.stopLoading()
}
companion object {
val HEIGHT = JBValue.UIInteger("CombinedLazyDiffViewer.height", 50)
}
}
| apache-2.0 | 8d461f56248b1fa69e5966a72203674a | 32.904762 | 120 | 0.747191 | 4.549521 | false | false | false | false |
jwren/intellij-community | plugins/kotlin/fir/src/org/jetbrains/kotlin/idea/fir/api/AbstractHLIntention.kt | 1 | 2857 | // 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.fir.api
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import org.jetbrains.kotlin.idea.api.applicator.HLApplicator
import org.jetbrains.kotlin.idea.api.applicator.HLApplicatorInput
import org.jetbrains.kotlin.idea.fir.api.applicator.HLApplicabilityRange
import org.jetbrains.kotlin.idea.fir.api.applicator.HLApplicatorInputProvider
import org.jetbrains.kotlin.analysis.api.tokens.HackToForceAllowRunningAnalyzeOnEDT
import org.jetbrains.kotlin.analysis.api.analyseWithReadAction
import org.jetbrains.kotlin.analysis.api.tokens.hackyAllowRunningOnEdt
import org.jetbrains.kotlin.idea.intentions.SelfTargetingIntention
import org.jetbrains.kotlin.psi.KtElement
import kotlin.reflect.KClass
abstract class AbstractHLIntention<PSI : KtElement, INPUT : HLApplicatorInput>(
elementType: KClass<PSI>,
val applicator: HLApplicator<PSI, INPUT>
) : SelfTargetingIntention<PSI>(elementType.java, applicator::getFamilyName) {
final override fun isApplicableTo(element: PSI, caretOffset: Int): Boolean {
val project = element.project// TODO expensive operation, may require traversing the tree up to containing PsiFile
if (!applicator.isApplicableByPsi(element, project)) return false
val ranges = applicabilityRange.getApplicabilityRanges(element)
if (ranges.isEmpty()) return false
// An HLApplicabilityRange should be relative to the element, while `caretOffset` is absolute
val relativeCaretOffset = caretOffset - element.textRange.startOffset
if (ranges.none { it.containsOffset(relativeCaretOffset) }) return false
val input = getInput(element)
if (input != null && input.isValidFor(element)) {
setFamilyNameGetter(applicator::getFamilyName)
setTextGetter { applicator.getActionName(element, input) }
return true
}
return false
}
final override fun applyTo(element: PSI, project: Project, editor: Editor?) {
val input = getInput(element) ?: return
if (input.isValidFor(element)) {
applicator.applyTo(element, input, project, editor)
}
}
final override fun applyTo(element: PSI, editor: Editor?) {
applyTo(element, element.project, editor)
}
@OptIn(HackToForceAllowRunningAnalyzeOnEDT::class)
private fun getInput(element: PSI): INPUT? = hackyAllowRunningOnEdt {
analyseWithReadAction(element) {
with(inputProvider) { provideInput(element) }
}
}
abstract val applicabilityRange: HLApplicabilityRange<PSI>
abstract val inputProvider: HLApplicatorInputProvider<PSI, INPUT>
}
| apache-2.0 | 7e5e52f0180d2e8240f79fa1b1360c8a | 44.349206 | 158 | 0.746237 | 4.615509 | false | false | false | false |
jwren/intellij-community | platform/usageView/src/com/intellij/usages/impl/UsageViewStatisticsCollector.kt | 1 | 7570 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.usages.impl
import com.intellij.find.FindSettings
import com.intellij.ide.util.scopeChooser.ScopeIdMapper
import com.intellij.internal.statistic.eventLog.EventLogGroup
import com.intellij.internal.statistic.eventLog.events.EventFields
import com.intellij.internal.statistic.eventLog.validator.ValidationResultType
import com.intellij.internal.statistic.eventLog.validator.rules.EventContext
import com.intellij.internal.statistic.eventLog.validator.rules.impl.CustomValidationRule
import com.intellij.internal.statistic.service.fus.collectors.CounterUsagesCollector
import com.intellij.lang.Language
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiElement
import com.intellij.psi.search.SearchScope
import com.intellij.usageView.UsageInfo
import com.intellij.usages.Usage
import com.intellij.usages.rules.PsiElementUsage
import org.jetbrains.annotations.Nls
import java.util.concurrent.atomic.AtomicInteger
enum class CodeNavigateSource {
ShowUsagesPopup,
FindToolWindow
}
enum class TooManyUsagesUserAction {
Shown,
Aborted,
Continued
}
class UsageViewStatisticsCollector : CounterUsagesCollector() {
override fun getGroup() = GROUP
companion object {
val GROUP = EventLogGroup("usage.view", 5)
private var sessionId = AtomicInteger(0)
private val SESSION_ID = EventFields.Int("id")
private val REFERENCE_CLASS = EventFields.Class("reference_class")
private val USAGE_SHOWN = GROUP.registerEvent("usage.shown", SESSION_ID, REFERENCE_CLASS, EventFields.Language)
private val USAGE_NAVIGATE = GROUP.registerEvent("usage.navigate", SESSION_ID, REFERENCE_CLASS, EventFields.Language)
private val UI_LOCATION = EventFields.Enum("ui_location", CodeNavigateSource::class.java)
private val itemChosen = GROUP.registerEvent("item.chosen", SESSION_ID, UI_LOCATION, EventFields.Language)
const val SCOPE_RULE_ID = "scopeRule"
private val SYMBOL_CLASS = EventFields.Class("symbol")
private val SEARCH_SCOPE = EventFields.StringValidatedByCustomRule("scope", ScopeRuleValidator::class.java)
private val RESULTS_TOTAL = EventFields.Int("results_total")
private val FIRST_RESULT_TS = EventFields.Long("duration_first_results_ms")
private val TOO_MANY_RESULTS = EventFields.Boolean("too_many_result_warning")
private val searchStarted = GROUP.registerVarargEvent("started", SESSION_ID)
private val searchFinished = GROUP.registerVarargEvent("finished",
SESSION_ID,
SYMBOL_CLASS,
SEARCH_SCOPE,
EventFields.Language,
RESULTS_TOTAL,
FIRST_RESULT_TS,
EventFields.DurationMs,
TOO_MANY_RESULTS,
UI_LOCATION)
private val tabSwitched = GROUP.registerEvent("switch.tab", SESSION_ID)
private val PREVIOUS_SCOPE = EventFields.StringValidatedByCustomRule("previous", ScopeRuleValidator::class.java)
private val NEW_SCOPE = EventFields.StringValidatedByCustomRule("new", ScopeRuleValidator::class.java)
private val scopeChanged = GROUP.registerVarargEvent("scope.changed", SESSION_ID, PREVIOUS_SCOPE, NEW_SCOPE, SYMBOL_CLASS)
private val OPEN_IN_FIND_TOOL_WINDOW = GROUP.registerEvent("open.in.tool.window", SESSION_ID)
private val USER_ACTION = EventFields.Enum("userAction", TooManyUsagesUserAction::class.java)
private val tooManyUsagesDialog = GROUP.registerVarargEvent("tooManyResultsDialog",
SESSION_ID,
USER_ACTION,
SYMBOL_CLASS,
SEARCH_SCOPE,
EventFields.Language
)
@JvmStatic
fun logSearchStarted(project: Project?) {
searchStarted.log(project, SESSION_ID.with(sessionId.incrementAndGet()))
}
@JvmStatic
fun logUsageShown(project: Project?, referenceClass: Class<out Any>, language: Language?) {
USAGE_SHOWN.log(project, getSessionId(), referenceClass, language)
}
@JvmStatic
fun logUsageNavigate(project: Project?, usage: Usage) {
UsageReferenceClassProvider.getReferenceClass(usage)?.let {
USAGE_NAVIGATE.log(
project,
getSessionId(),
it,
(usage as? PsiElementUsage)?.element?.language,
)
}
}
@JvmStatic
fun logUsageNavigate(project: Project?, usage: UsageInfo) {
usage.referenceClass?.let {
USAGE_NAVIGATE.log(
project,
getSessionId(),
it,
usage.element?.language,
)
}
}
@JvmStatic
fun logItemChosen(project: Project?, source: CodeNavigateSource, language: Language) = itemChosen.log(project, getSessionId(), source, language)
@JvmStatic
fun logSearchFinished(
project: Project?,
targetClass: Class<*>,
scope: SearchScope?,
language: Language?,
results: Int,
durationFirstResults: Long,
duration: Long,
tooManyResult: Boolean,
source: CodeNavigateSource,
) {
searchFinished.log(project,
SESSION_ID.with(getSessionId()),
SYMBOL_CLASS.with(targetClass),
SEARCH_SCOPE.with(scope?.let { ScopeIdMapper.instance.getScopeSerializationId(it.displayName) }),
EventFields.Language.with(language),
RESULTS_TOTAL.with(results),
FIRST_RESULT_TS.with(durationFirstResults),
EventFields.DurationMs.with(duration),
TOO_MANY_RESULTS.with(tooManyResult),
UI_LOCATION.with(source))
}
@JvmStatic
fun logTabSwitched(project: Project?) = tabSwitched.log(project, getSessionId())
@JvmStatic
fun logScopeChanged(
project: Project?,
previousScope: SearchScope?,
newScope: SearchScope?,
symbolClass: Class<*>,
) {
val scopeIdMapper = ScopeIdMapper.instance
scopeChanged.log(project, SESSION_ID.with(getSessionId()),
PREVIOUS_SCOPE.with(previousScope?.let { scopeIdMapper.getScopeSerializationId(it.displayName) }),
NEW_SCOPE.with(newScope?.let { scopeIdMapper.getScopeSerializationId(it.displayName) }),
SYMBOL_CLASS.with(symbolClass))
}
@JvmStatic
fun logTooManyDialog(
project: Project?,
action: TooManyUsagesUserAction,
targetClass: Class<out PsiElement>?,
@Nls scope: String,
language: Language?,
) {
tooManyUsagesDialog.log(project,
SESSION_ID.with(getSessionId()),
USER_ACTION.with(action),
SYMBOL_CLASS.with(targetClass ?: String::class.java),
SEARCH_SCOPE.with(ScopeIdMapper.instance.getScopeSerializationId(scope)),
EventFields.Language.with(language))
}
@JvmStatic
fun logOpenInFindToolWindow(project: Project?) =
OPEN_IN_FIND_TOOL_WINDOW.log(project, getSessionId())
private fun getSessionId() = if (FindSettings.getInstance().isShowResultsInSeparateView) -1 else sessionId.get()
}
}
class ScopeRuleValidator : CustomValidationRule() {
@Suppress("HardCodedStringLiteral")
override fun doValidate(data: String, context: EventContext): ValidationResultType =
if (ScopeIdMapper.standardNames.contains(data)) ValidationResultType.ACCEPTED else ValidationResultType.REJECTED
override fun getRuleId(): String = UsageViewStatisticsCollector.SCOPE_RULE_ID
} | apache-2.0 | 37287a44dcb4735f2b3fe712294ba0d3 | 38.227979 | 148 | 0.696301 | 4.62149 | false | false | false | false |
allotria/intellij-community | java/java-tests/testSrc/com/intellij/projectView/CustomScopePaneTest.kt | 1 | 11988 | // 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.projectView
import com.intellij.ide.projectView.ProjectViewNode
import com.intellij.ide.projectView.impl.ProjectViewState
import com.intellij.openapi.actionSystem.LangDataKeys
import com.intellij.openapi.roots.ProjectFileIndex
import com.intellij.psi.JavaDirectoryService
import com.intellij.psi.search.scope.packageSet.FilePatternPackageSet
import com.intellij.psi.search.scope.packageSet.NamedScope
import com.intellij.psi.search.scope.packageSet.NamedScopeManager
import com.intellij.psi.search.scope.packageSet.PackageSet
import com.intellij.testFramework.PlatformTestUtil
import com.intellij.testFramework.PsiTestUtil
import com.intellij.util.io.directoryContent
import com.intellij.util.io.generateInVirtualTempDir
class CustomScopePaneTest : AbstractProjectViewTest() {
override fun tearDown() {
NamedScopeManager.getInstance(project).removeAllSets()
super.tearDown()
}
private fun allowed(any: Any?): Boolean {
val node = any as? ProjectViewNode<*> ?: return true
val file = node.virtualFile ?: return true
return ProjectFileIndex.getInstance(project).isInContent(file)
}
private fun selectNewFilePattern(filePattern: String) {
selectNewCustomScope(filePattern, FilePatternPackageSet(null, filePattern))
}
private fun selectNewCustomScope(id: String, packages: PackageSet) {
selectProjectFilesPane()
val scope = NamedScope(id, packages)
NamedScopeManager.getInstance(project).addScope(scope)
PlatformTestUtil.waitForAlarm(20)
selectScopeViewPane(scope)
}
private fun prepareProjectContent123() {
val root = directoryContent {
dir("src") {
dir("package1") {
dir("package2") {
dir("package3") {
file("Test3.java", """
package package1.package2.package3;
class Test3 {
}""")
}
}
file("Test1.java", """
package package1;
class Test1 {
}""")
}
file("Test.java", """
class Test {
}""")
}
}.generateInVirtualTempDir()
PsiTestUtil.addSourceRoot(module, root.findChild("src")!!)
}
fun `test default selection via IDE_VIEW`() {
selectProjectFilesPane()
with(ProjectViewState.getInstance(project)) {
showModules = false
}
prepareProjectContent123()
val test = createTreeTest().withSelection().setFilter { allowed(it.lastPathComponent) }
val class3 = javaFacade.findClass("package1.package2.package3.Test3")!!
LangDataKeys.IDE_VIEW.getData(currentPane)?.selectElement(class3)
test.assertStructure(" -src\n" +
" -package1\n" +
" -package2\n" +
" -package3\n" +
" [Test3]\n" +
" Test1\n" +
" Test\n")
}
fun `test default scope with compact packages`() {
selectProjectFilesPane()
with(ProjectViewState.getInstance(project)) {
hideEmptyMiddlePackages = true
compactDirectories = true
showModules = false
}
prepareProjectContent123()
val test = createTreeTest().setFilter { allowed(it.lastPathComponent) }
val class1 = javaFacade.findClass("package1.Test1")!!
val class3 = javaFacade.findClass("package1.package2.package3.Test3")!!
selectElement(class3)
test.assertStructure(" -directory-by-spec/src\n" +
" -package1\n" +
" -package2.package3\n" +
" Test3\n" +
" Test1\n" +
" Test\n")
deleteElement(class1)
selectElement(class3)
test.assertStructure(" -directory-by-spec/src\n" +
" -package1.package2.package3\n" +
" Test3\n" +
" Test\n")
val class111 = javaFacade.findClass("Test")!!
renameElement(class111, "Test111")
test.assertStructure(" -directory-by-spec/src\n" +
" -package1.package2.package3\n" +
" Test3\n" +
" Test111\n")
val package2 = javaFacade.findPackage("package1.package2")!!
val classNew = JavaDirectoryService.getInstance().createClass(package2.directories[0], "Class")
selectElement(classNew)
test.assertStructure(" -directory-by-spec/src\n" +
" -package1.package2\n" +
" +package3\n" +
" Class\n" +
" Test111\n")
projectView.setFlattenPackages(currentPane.id, true)
selectElement(classNew)
test.assertStructure(" -directory-by-spec/src\n" +
" -package1.package2\n" +
" Class\n" +
" +package1.package2.package3\n" +
" Test111\n")
}
fun `test default scope with flatten packages`() {
selectProjectFilesPane()
with(ProjectViewState.getInstance(project)) {
hideEmptyMiddlePackages = true
flattenPackages = true
showModules = false
}
prepareProjectContent123()
val test = createTreeTest().setFilter { allowed(it.lastPathComponent) }
val class1 = javaFacade.findClass("package1.Test1")!!
val class3 = javaFacade.findClass("package1.package2.package3.Test3")!!
selectElement(class3)
test.assertStructure(" -src\n" +
" +package1\n" +
" -package1.package2.package3\n" +
" Test3\n" +
" Test\n")
deleteElement(class1)
selectElement(class3)
test.assertStructure(" -src\n" +
" -package1.package2.package3\n" +
" Test3\n" +
" Test\n")
val class111 = javaFacade.findClass("Test")!!
renameElement(class111, "Test111")
test.assertStructure(" -src\n" +
" -package1.package2.package3\n" +
" Test3\n" +
" Test111\n")
val package3 = javaFacade.findPackage("package1.package2.package3")!!
val classNew = JavaDirectoryService.getInstance().createClass(package3.directories[0], "Class")
selectElement(classNew)
test.assertStructure(" -src\n" +
" -package1.package2.package3\n" +
" Class\n" +
" Test3\n" +
" Test111\n")
projectView.setHideEmptyPackages(currentPane.id, false)
selectElement(classNew)
test.assertStructure(" -src\n" +
" package1\n" +
" package1.package2\n" +
" -package1.package2.package3\n" +
" Class\n" +
" Test3\n" +
" Test111\n")
}
fun `test custom scope with compact packages`() {
selectNewFilePattern("*/Test3*")
with(ProjectViewState.getInstance(project)) {
compactDirectories = true
showModules = false
}
prepareProjectContent123()
val test = createTreeTest().setFilter { allowed(it.lastPathComponent) }
val class3 = javaFacade.findClass("package1.package2.package3.Test3")!!
selectElement(class3)
test.assertStructure(" -directory-by-spec/src\n" +
" -package1.package2.package3\n" +
" Test3\n")
renameElement(class3, "ATest3") //exclude from scope
test.assertStructure("")
renameElement(class3, "Test3") //restore in scope
selectElement(class3)
test.assertStructure(" -directory-by-spec/src\n" +
" -package1.package2.package3\n" +
" Test3\n")
movePackageToPackage("package1.package2.package3", "package1")
selectElement(class3)
test.assertStructure(" -directory-by-spec/src\n" +
" -package1.package3\n" +
" Test3\n")
movePackageToPackage("package1.package3", "package1.package2")
selectElement(class3)
test.assertStructure(" -directory-by-spec/src\n" +
" -package1.package2.package3\n" +
" Test3\n")
}
fun `test custom scope without compact packages`() {
selectNewFilePattern("*/Test3*")
with(ProjectViewState.getInstance(project)) {
showModules = false
}
prepareProjectContent123()
val test = createTreeTest().setFilter { allowed(it.lastPathComponent) }
val class3 = javaFacade.findClass("package1.package2.package3.Test3")!!
selectElement(class3)
test.assertStructure(" -src\n" +
" -package1\n" +
" -package2\n" +
" -package3\n" +
" Test3\n")
renameElement(class3, "ATest3") //exclude from scope
test.assertStructure("")
renameElement(class3, "Test3") //restore in scope
selectElement(class3)
test.assertStructure(" -src\n" +
" -package1\n" +
" -package2\n" +
" -package3\n" +
" Test3\n")
movePackageToPackage("package1.package2.package3", "package1")
selectElement(class3)
test.assertStructure(" -src\n" +
" -package1\n" +
" -package3\n" +
" Test3\n")
movePackageToPackage("package1.package3", "package1.package2")
selectElement(class3)
test.assertStructure(" -src\n" +
" -package1\n" +
" -package2\n" +
" -package3\n" +
" Test3\n")
}
fun `test custom scope structure`() {
selectNewFilePattern("*/Test*")
with(ProjectViewState.getInstance(project)) {
showModules = false
}
prepareProjectContent123()
val test = createTreeTest().setFilter { allowed(it.lastPathComponent) }
val class1 = javaFacade.findClass("package1.Test1")!!
val class3 = javaFacade.findClass("package1.package2.package3.Test3")!!
selectElement(class3)
test.assertStructure(" -src\n" +
" -package1\n" +
" -package2\n" +
" -package3\n" +
" Test3\n" +
" Test1\n")
deleteElement(class3)
selectElement(class1)
test.assertStructure(" -src\n" +
" -package1\n" +
" Test1\n")
renameElement(class1, "Test111")
test.assertStructure(" -src\n" +
" -package1\n" +
" Test111\n")
val package1 = javaFacade.findPackage("package1")!!
val classNew = JavaDirectoryService.getInstance().createClass(package1.directories[0], "Test222")
selectElement(classNew)
test.assertStructure(" -src\n" +
" -package1\n" +
" Test111\n" +
" Test222\n")
moveElementToPackage(classNew, "package1.package2.package3")
selectElement(classNew)
test.assertStructure(" -src\n" +
" -package1\n" +
" -package2\n" +
" -package3\n" +
" Test222\n" +
" Test111\n")
}
}
| apache-2.0 | 919dc9b5cf0a8ec23d0e80e666fc4103 | 36.114551 | 140 | 0.545629 | 4.261642 | false | true | false | false |
androidx/androidx | wear/compose/compose-foundation/src/androidAndroidTest/kotlin/androidx/wear/compose/foundation/CurvedPaddingTest.kt | 3 | 4380 | /*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.wear.compose.foundation
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.test.junit4.createComposeRule
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import org.junit.Rule
import org.junit.Test
class CurvedPaddingTest {
@get:Rule
val rule = createComposeRule()
@Test
fun padding_all_works() =
check_padding_result(
3.dp,
3.dp,
3.dp,
3.dp,
CurvedModifier.padding(3.dp)
)
@Test
fun padding_angular_and_radial_works() =
check_padding_result(
outerPadding = 4.dp,
innerPadding = 4.dp,
beforePadding = 6.dp,
afterPadding = 6.dp,
CurvedModifier.padding(radial = 4.dp, angular = 6.dp)
)
@Test
fun basic_padding_works() =
check_padding_result(
outerPadding = 3.dp,
innerPadding = 4.dp,
beforePadding = 5.dp,
afterPadding = 6.dp,
CurvedModifier.padding(
outer = 3.dp,
inner = 4.dp,
before = 5.dp,
after = 6.dp
)
)
@Test
fun nested_padding_works() =
check_padding_result(
11.dp,
14.dp,
18.dp,
25.dp,
CurvedModifier
.padding(3.dp, 4.dp, 5.dp, 6.dp)
.padding(8.dp, 10.dp, 13.dp, 19.dp)
)
private fun check_padding_result(
outerPadding: Dp,
innerPadding: Dp,
beforePadding: Dp,
afterPadding: Dp,
modifier: CurvedModifier
) {
val paddedCapturedInfo = CapturedInfo()
val componentCapturedInfo = CapturedInfo()
val componentThickness = 10.dp
val componentSweepDegrees = 90f
var outerPaddingPx = 0f
var innerPaddingPx = 0f
var beforePaddingPx = 0f
var afterPaddingPx = 0f
var componentThicknessPx = 0f
rule.setContent {
with(LocalDensity.current) {
outerPaddingPx = outerPadding.toPx()
innerPaddingPx = innerPadding.toPx()
beforePaddingPx = beforePadding.toPx()
afterPaddingPx = afterPadding.toPx()
componentThicknessPx = componentThickness.toPx()
}
CurvedLayout {
curvedRow(modifier = CurvedModifier
.spy(paddedCapturedInfo)
.then(modifier)
.spy(componentCapturedInfo)
.size(
sweepDegrees = componentSweepDegrees,
thickness = componentThickness
)
) { }
}
}
rule.runOnIdle {
val measureRadius = componentCapturedInfo.lastLayoutInfo!!.measureRadius
val beforePaddingAsAngle = beforePaddingPx / measureRadius
val afterPaddingAsAngle = afterPaddingPx / measureRadius
// Check sizes.
val paddingAsAngle = (beforePaddingAsAngle + afterPaddingAsAngle).toDegrees()
paddedCapturedInfo.checkDimensions(
componentSweepDegrees + paddingAsAngle,
componentThicknessPx + outerPaddingPx + innerPaddingPx
)
componentCapturedInfo.checkDimensions(componentSweepDegrees, componentThicknessPx)
// Check its position.
componentCapturedInfo.checkPositionRelativeTo(
paddedCapturedInfo,
expectedAngularPositionDegrees = beforePaddingAsAngle,
expectedRadialPositionPx = outerPaddingPx,
)
}
}
}
| apache-2.0 | 6014acff88d6963a5a05ebed4009b21c | 30.285714 | 94 | 0.57968 | 4.74026 | false | false | false | false |
GunoH/intellij-community | plugins/laf/macos/src/com/intellij/laf/macos/MacIntelliJOptionButtonUI.kt | 8 | 1215 | // 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.laf.macos
import com.intellij.ide.ui.laf.darcula.ui.DarculaOptionButtonUI
import com.intellij.laf.macos.MacIntelliJTextBorder.LW
import com.intellij.util.ui.JBUI.scale
import java.awt.Dimension
import java.awt.Graphics2D
import java.awt.geom.Rectangle2D
import javax.swing.JComponent
// TODO replace arrow with specific icon when it's ready
internal class MacIntelliJOptionButtonUI : DarculaOptionButtonUI() {
override val arrowButtonPreferredSize: Dimension get() = Dimension(scale(21), optionButton.preferredSize.height)
override val showPopupXOffset: Int = scale(3)
override fun paintSeparator(g: Graphics2D, c: JComponent) {
val insets = mainButton.insets
val lw = LW(g)
g.paint = MacIntelliJButtonUI.getBorderPaint(c)
g.fill(Rectangle2D.Float(mainButton.width.toFloat(), insets.top + lw, lw, mainButton.height - (insets.top + insets.bottom + 2 * lw)))
}
companion object {
@Suppress("UNUSED_PARAMETER")
@JvmStatic
fun createUI(c: JComponent): MacIntelliJOptionButtonUI = MacIntelliJOptionButtonUI()
}
} | apache-2.0 | 047fda81b7b55ed3115b3f0d375cf311 | 38.225806 | 140 | 0.77037 | 3.919355 | false | false | false | false |
GunoH/intellij-community | platform/editor-ui-api/src/com/intellij/ide/ui/UISettings.kt | 1 | 22464 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.ide.ui
import com.intellij.diagnostic.LoadingState
import com.intellij.openapi.Disposable
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.components.PersistentStateComponentWithModificationTracker
import com.intellij.openapi.components.SettingsCategory
import com.intellij.openapi.components.State
import com.intellij.openapi.components.Storage
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.options.advanced.AdvancedSettings
import com.intellij.openapi.util.IconLoader
import com.intellij.openapi.util.NlsSafe
import com.intellij.openapi.util.SystemInfo
import com.intellij.openapi.util.SystemInfoRt
import com.intellij.openapi.util.registry.Registry
import com.intellij.openapi.util.registry.RegistryManager
import com.intellij.serviceContainer.NonInjectable
import com.intellij.ui.JreHiDpiUtil
import com.intellij.ui.scale.JBUIScale
import com.intellij.util.ComponentTreeEventDispatcher
import com.intellij.util.ui.GraphicsUtil
import com.intellij.util.ui.UIUtil
import com.intellij.util.xmlb.annotations.Transient
import org.jetbrains.annotations.ApiStatus.ScheduledForRemoval
import java.awt.Graphics
import java.awt.Graphics2D
import java.awt.RenderingHints
import javax.swing.JComponent
import javax.swing.SwingConstants
private val LOG = logger<UISettings>()
@State(name = "UISettings", storages = [(Storage("ui.lnf.xml"))], useLoadedStateAsExisting = false, category = SettingsCategory.UI)
class UISettings @NonInjectable constructor(private val notRoamableOptions: NotRoamableUiSettings) : PersistentStateComponentWithModificationTracker<UISettingsState> {
constructor() : this(ApplicationManager.getApplication().getService(NotRoamableUiSettings::class.java))
private var state = UISettingsState()
private val treeDispatcher = ComponentTreeEventDispatcher.create(UISettingsListener::class.java)
var ideAAType: AntialiasingType
get() = notRoamableOptions.state.ideAAType
set(value) {
notRoamableOptions.state.ideAAType = value
}
var editorAAType: AntialiasingType
get() = notRoamableOptions.state.editorAAType
set(value) {
notRoamableOptions.state.editorAAType = value
}
val allowMergeButtons: Boolean
get() = Registry.`is`("ide.allow.merge.buttons", true)
val animateWindows: Boolean
get() = Registry.`is`("ide.animate.toolwindows", false)
var colorBlindness: ColorBlindness?
get() = state.colorBlindness
set(value) {
state.colorBlindness = value
}
var useContrastScrollbars: Boolean
get() = state.useContrastScrollBars
set(value) {
state.useContrastScrollBars = value
}
var hideToolStripes: Boolean
get() = state.hideToolStripes
set(value) {
state.hideToolStripes = value
}
val hideNavigationOnFocusLoss: Boolean
get() = Registry.`is`("ide.hide.navigation.on.focus.loss", false)
var reuseNotModifiedTabs: Boolean
get() = state.reuseNotModifiedTabs
set(value) {
state.reuseNotModifiedTabs = value
}
var openTabsInMainWindow: Boolean
get() = state.openTabsInMainWindow
set(value) {
state.openTabsInMainWindow = value
}
var openInPreviewTabIfPossible: Boolean
get() = state.openInPreviewTabIfPossible
set(value) {
state.openInPreviewTabIfPossible = value
}
var disableMnemonics: Boolean
get() = state.disableMnemonics
set(value) {
state.disableMnemonics = value
}
var disableMnemonicsInControls: Boolean
get() = state.disableMnemonicsInControls
set(value) {
state.disableMnemonicsInControls = value
}
var dndWithPressedAltOnly: Boolean
get() = state.dndWithPressedAltOnly
set(value) {
state.dndWithPressedAltOnly = value
}
var separateMainMenu: Boolean
get() = (SystemInfoRt.isWindows || SystemInfoRt.isXWindow) && state.separateMainMenu
set(value) {
state.separateMainMenu = value
}
var useSmallLabelsOnTabs: Boolean
get() = state.useSmallLabelsOnTabs
set(value) {
state.useSmallLabelsOnTabs = value
}
var smoothScrolling: Boolean
get() = state.smoothScrolling
set(value) {
state.smoothScrolling = value
}
val animatedScrolling: Boolean
get() = state.animatedScrolling
val animatedScrollingDuration: Int
get() = state.animatedScrollingDuration
val animatedScrollingCurvePoints: Int
get() = state.animatedScrollingCurvePoints
val closeTabButtonOnTheRight: Boolean
get() = state.closeTabButtonOnTheRight
val cycleScrolling: Boolean
get() = AdvancedSettings.getBoolean("ide.cycle.scrolling")
val scrollTabLayoutInEditor: Boolean
get() = state.scrollTabLayoutInEditor
var showToolWindowsNumbers: Boolean
get() = state.showToolWindowsNumbers
set(value) {
state.showToolWindowsNumbers = value
}
var showEditorToolTip: Boolean
get() = state.showEditorToolTip
set(value) {
state.showEditorToolTip = value
}
var showNavigationBar: Boolean
get() = state.showNavigationBar
set(value) {
state.showNavigationBar = value
}
var navBarLocation : NavBarLocation
get() = state.navigationBarLocation
set(value) {
state.navigationBarLocation = value
}
val showNavigationBarInBottom : Boolean
get() = showNavigationBar && navBarLocation == NavBarLocation.BOTTOM
var showMembersInNavigationBar: Boolean
get() = state.showMembersInNavigationBar
set(value) {
state.showMembersInNavigationBar = value
}
var showStatusBar: Boolean
get() = state.showStatusBar
set(value) {
state.showStatusBar = value
}
var showMainMenu: Boolean
get() = state.showMainMenu
set(value) {
state.showMainMenu = value
}
val showIconInQuickNavigation: Boolean
get() = Registry.`is`("ide.show.icons.in.quick.navigation", false)
var showTreeIndentGuides: Boolean
get() = state.showTreeIndentGuides
set(value) {
state.showTreeIndentGuides = value
}
var compactTreeIndents: Boolean
get() = state.compactTreeIndents
set(value) {
state.compactTreeIndents = value
}
var showMainToolbar: Boolean
get() = if (RegistryManager.getInstance().`is`("ide.experimental.ui")) separateMainMenu else state.showMainToolbar
set(value) {
state.showMainToolbar = value
val toolbarSettingsState = ToolbarSettings.getInstance().state!!
toolbarSettingsState.showNewMainToolbar = !value && toolbarSettingsState.showNewMainToolbar
}
var showIconsInMenus: Boolean
get() = state.showIconsInMenus
set(value) {
state.showIconsInMenus = value
}
var sortLookupElementsLexicographically: Boolean
get() = state.sortLookupElementsLexicographically
set(value) {
state.sortLookupElementsLexicographically = value
}
val hideTabsIfNeeded: Boolean
get() = state.hideTabsIfNeeded || editorTabPlacement == SwingConstants.LEFT || editorTabPlacement == SwingConstants.RIGHT
var showFileIconInTabs: Boolean
get() = state.showFileIconInTabs
set(value) {
state.showFileIconInTabs = value
}
var hideKnownExtensionInTabs: Boolean
get() = state.hideKnownExtensionInTabs
set(value) {
state.hideKnownExtensionInTabs = value
}
var leftHorizontalSplit: Boolean
get() = state.leftHorizontalSplit
set(value) {
state.leftHorizontalSplit = value
}
var rightHorizontalSplit: Boolean
get() = state.rightHorizontalSplit
set(value) {
state.rightHorizontalSplit = value
}
var wideScreenSupport: Boolean
get() = state.wideScreenSupport
set(value) {
state.wideScreenSupport = value
}
var sortBookmarks: Boolean
get() = state.sortBookmarks
set(value) {
state.sortBookmarks = value
}
val showCloseButton: Boolean
get() = state.showCloseButton
var presentationMode: Boolean
get() = state.presentationMode
set(value) {
state.presentationMode = value
}
var presentationModeFontSize: Int
get() = state.presentationModeFontSize
set(value) {
state.presentationModeFontSize = value
}
var editorTabPlacement: Int
get() = state.editorTabPlacement
set(value) {
state.editorTabPlacement = value
}
var editorTabLimit: Int
get() = state.editorTabLimit
set(value) {
state.editorTabLimit = value
}
var recentFilesLimit: Int
get() = state.recentFilesLimit
set(value) {
state.recentFilesLimit = value
}
var recentLocationsLimit: Int
get() = state.recentLocationsLimit
set(value) {
state.recentLocationsLimit = value
}
var maxLookupWidth: Int
get() = state.maxLookupWidth
set(value) {
state.maxLookupWidth = value
}
var maxLookupListHeight: Int
get() = state.maxLookupListHeight
set(value) {
state.maxLookupListHeight = value
}
var overrideLafFonts: Boolean
get() = state.overrideLafFonts
set(value) {
state.overrideLafFonts = value
}
var fontFace: @NlsSafe String?
get() = notRoamableOptions.state.fontFace
set(value) {
notRoamableOptions.state.fontFace = value
}
var fontSize: Int
get() = (notRoamableOptions.state.fontSize + 0.5).toInt()
set(value) {
notRoamableOptions.state.fontSize = value.toFloat()
}
var fontSize2D: Float
get() = notRoamableOptions.state.fontSize
set(value) {
notRoamableOptions.state.fontSize = value
}
var fontScale: Float
get() = notRoamableOptions.state.fontScale
set(value) {
notRoamableOptions.state.fontScale = value
}
var showDirectoryForNonUniqueFilenames: Boolean
get() = state.showDirectoryForNonUniqueFilenames
set(value) {
state.showDirectoryForNonUniqueFilenames = value
}
var pinFindInPath: Boolean
get() = state.pinFindInPath
set(value) {
state.pinFindInPath = value
}
var activeRightEditorOnClose: Boolean
get() = state.activeRightEditorOnClose
set(value) {
state.activeRightEditorOnClose = value
}
var showTabsTooltips: Boolean
get() = state.showTabsTooltips
set(value) {
state.showTabsTooltips = value
}
var markModifiedTabsWithAsterisk: Boolean
get() = state.markModifiedTabsWithAsterisk
set(value) {
state.markModifiedTabsWithAsterisk = value
}
var overrideConsoleCycleBufferSize: Boolean
get() = state.overrideConsoleCycleBufferSize
set(value) {
state.overrideConsoleCycleBufferSize = value
}
var consoleCycleBufferSizeKb: Int
get() = state.consoleCycleBufferSizeKb
set(value) {
state.consoleCycleBufferSizeKb = value
}
var consoleCommandHistoryLimit: Int
get() = state.consoleCommandHistoryLimit
set(value) {
state.consoleCommandHistoryLimit = value
}
var sortTabsAlphabetically: Boolean
get() = state.sortTabsAlphabetically
set(value) {
state.sortTabsAlphabetically = value
}
var alwaysKeepTabsAlphabeticallySorted: Boolean
get() = state.alwaysKeepTabsAlphabeticallySorted
set(value) {
state.alwaysKeepTabsAlphabeticallySorted = value
}
var openTabsAtTheEnd: Boolean
get() = state.openTabsAtTheEnd
set(value) {
state.openTabsAtTheEnd = value
}
var showInplaceComments: Boolean
get() = state.showInplaceComments
set(value) {
state.showInplaceComments = value
}
val showInplaceCommentsInternal: Boolean
get() = showInplaceComments && ApplicationManager.getApplication()?.isInternal ?: false
var fullPathsInWindowHeader: Boolean
get() = state.fullPathsInWindowHeader
set(value) {
state.fullPathsInWindowHeader = value
}
var mergeMainMenuWithWindowTitle: Boolean
get() = state.mergeMainMenuWithWindowTitle
set(value) {
state.mergeMainMenuWithWindowTitle = value
}
var showVisualFormattingLayer: Boolean
get() = state.showVisualFormattingLayer
set(value) {
state.showVisualFormattingLayer = value
}
companion object {
init {
if (JBUIScale.SCALE_VERBOSE) {
LOG.info(String.format("defFontSize=%.1f, defFontScale=%.2f", defFontSize, defFontScale))
}
}
const val ANIMATION_DURATION = 300 // Milliseconds
/** Not tabbed pane. */
const val TABS_NONE = 0
@Volatile
private var cachedInstance: UISettings? = null
@JvmStatic
fun getInstance(): UISettings {
var result = cachedInstance
if (result == null) {
LoadingState.CONFIGURATION_STORE_INITIALIZED.checkOccurred()
result = ApplicationManager.getApplication().getService(UISettings::class.java)!!
cachedInstance = result
}
return result
}
@JvmStatic
val instanceOrNull: UISettings?
get() {
val result = cachedInstance
if (result == null && LoadingState.CONFIGURATION_STORE_INITIALIZED.isOccurred) {
return getInstance()
}
return result
}
/**
* Use this method if you are not sure whether the application is initialized.
* @return persisted UISettings instance or default values.
*/
@JvmStatic
val shadowInstance: UISettings
get() = instanceOrNull ?: UISettings(NotRoamableUiSettings())
private fun calcFractionalMetricsHint(registryKey: String, defaultValue: Boolean): Any {
val hint: Boolean
if (LoadingState.APP_STARTED.isOccurred) {
val registryValue = Registry.get(registryKey)
if (registryValue.isMultiValue) {
val option = registryValue.selectedOption
if (option.equals("Enabled")) hint = true
else if (option.equals("Disabled")) hint = false
else hint = defaultValue
}
else {
hint = if (registryValue.isBoolean && registryValue.asBoolean()) true else defaultValue
}
}
else hint = defaultValue
return if (hint) RenderingHints.VALUE_FRACTIONALMETRICS_ON else RenderingHints.VALUE_FRACTIONALMETRICS_OFF
}
fun getPreferredFractionalMetricsValue(): Any {
val enableByDefault = SystemInfo.isMacOSCatalina || (FontSubpixelResolution.ENABLED
&& AntialiasingType.getKeyForCurrentScope(false) ==
RenderingHints.VALUE_TEXT_ANTIALIAS_ON)
return calcFractionalMetricsHint("ide.text.fractional.metrics", enableByDefault)
}
@JvmStatic
val editorFractionalMetricsHint: Any
get() {
val enableByDefault = FontSubpixelResolution.ENABLED
&& AntialiasingType.getKeyForCurrentScope(true) == RenderingHints.VALUE_TEXT_ANTIALIAS_ON
return calcFractionalMetricsHint("editor.text.fractional.metrics", enableByDefault)
}
@JvmStatic
fun setupFractionalMetrics(g2d: Graphics2D) {
g2d.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS, getPreferredFractionalMetricsValue())
}
/**
* This method must not be used for set up antialiasing for editor components. To make sure antialiasing settings are taken into account
* when preferred size of component is calculated, [.setupComponentAntialiasing] method should be called from
* `updateUI()` or `setUI()` method of component.
*/
@JvmStatic
fun setupAntialiasing(g: Graphics) {
g as Graphics2D
g.setRenderingHint(RenderingHints.KEY_TEXT_LCD_CONTRAST, UIUtil.getLcdContrastValue())
if (!LoadingState.COMPONENTS_REGISTERED.isOccurred) {
// cannot use services while Application has not been loaded yet, so let's apply the default hints
GraphicsUtil.applyRenderingHints(g)
return
}
g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, AntialiasingType.getKeyForCurrentScope(false))
setupFractionalMetrics(g)
}
@JvmStatic
fun setupComponentAntialiasing(component: JComponent) {
GraphicsUtil.setAntialiasingType(component, AntialiasingType.getAAHintForSwingComponent())
}
@JvmStatic
fun setupEditorAntialiasing(component: JComponent) {
GraphicsUtil.setAntialiasingType(component, getInstance().editorAAType.textInfo)
}
/**
* Returns the default font scale, which depends on the HiDPI mode (see [com.intellij.ui.scale.ScaleType]).
* <p>
* The font is represented:
* - in relative (dpi-independent) points in the JRE-managed HiDPI mode, so the method returns 1.0f
* - in absolute (dpi-dependent) points in the IDE-managed HiDPI mode, so the method returns the default screen scale
*
* @return the system font scale
*/
@JvmStatic
val defFontScale: Float
get() = when {
JreHiDpiUtil.isJreHiDPIEnabled() -> 1f
else -> JBUIScale.sysScale()
}
/**
* Returns the default font size scaled by #defFontScale
*
* @return the default scaled font size
*/
@JvmStatic
val defFontSize: Float
get() = UISettingsState.defFontSize
@JvmStatic
fun restoreFontSize(readSize: Float, readScale: Float?): Float {
var size = readSize
if (readScale == null || readScale <= 0) {
if (JBUIScale.SCALE_VERBOSE) LOG.info("Reset font to default")
// Reset font to default on switch from IDE-managed HiDPI to JRE-managed HiDPI. Doesn't affect OSX.
if (!SystemInfoRt.isMac && JreHiDpiUtil.isJreHiDPIEnabled()) {
size = UISettingsState.defFontSize
}
}
else if (readScale != defFontScale) {
size = (readSize / readScale) * defFontScale
}
if (JBUIScale.SCALE_VERBOSE) LOG.info("Loaded: fontSize=$readSize, fontScale=$readScale; restored: fontSize=$size, fontScale=$defFontScale")
return size
}
const val MERGE_MAIN_MENU_WITH_WINDOW_TITLE_PROPERTY = "ide.win.frame.decoration"
@JvmStatic
val mergeMainMenuWithWindowTitleOverrideValue = System.getProperty(MERGE_MAIN_MENU_WITH_WINDOW_TITLE_PROPERTY)?.toBoolean()
val isMergeMainMenuWithWindowTitleOverridden = mergeMainMenuWithWindowTitleOverrideValue != null
}
@Suppress("DeprecatedCallableAddReplaceWith")
@Deprecated("Please use {@link UISettingsListener#TOPIC}")
@ScheduledForRemoval
fun addUISettingsListener(listener: UISettingsListener, parentDisposable: Disposable) {
ApplicationManager.getApplication().messageBus.connect(parentDisposable).subscribe(UISettingsListener.TOPIC, listener)
}
/**
* Notifies all registered listeners that UI settings has been changed.
*/
fun fireUISettingsChanged() {
updateDeprecatedProperties()
// todo remove when all old properties will be converted
state._incrementModificationCount()
IconLoader.setFilter(ColorBlindnessSupport.get(state.colorBlindness)?.filter)
// if this is the main UISettings instance (and not on first call to getInstance) push event to bus and to all current components
if (this === cachedInstance) {
treeDispatcher.multicaster.uiSettingsChanged(this)
ApplicationManager.getApplication().messageBus.syncPublisher(UISettingsListener.TOPIC).uiSettingsChanged(this)
}
}
@Suppress("DEPRECATION")
private fun updateDeprecatedProperties() {
OVERRIDE_NONIDEA_LAF_FONTS = overrideLafFonts
FONT_SIZE = fontSize
FONT_FACE = fontFace
EDITOR_TAB_LIMIT = editorTabLimit
}
override fun getState() = state
override fun loadState(state: UISettingsState) {
this.state = state
updateDeprecatedProperties()
migrateOldSettings()
if (migrateOldFontSettings()) {
notRoamableOptions.fixFontSettings()
}
// Check tab placement in editor
val editorTabPlacement = state.editorTabPlacement
if (editorTabPlacement != TABS_NONE &&
editorTabPlacement != SwingConstants.TOP &&
editorTabPlacement != SwingConstants.LEFT &&
editorTabPlacement != SwingConstants.BOTTOM &&
editorTabPlacement != SwingConstants.RIGHT) {
state.editorTabPlacement = SwingConstants.TOP
}
// Check that alpha delay and ratio are valid
if (state.alphaModeDelay < 0) {
state.alphaModeDelay = 1500
}
if (state.alphaModeRatio < 0.0f || state.alphaModeRatio > 1.0f) {
state.alphaModeRatio = 0.5f
}
fireUISettingsChanged()
}
override fun getStateModificationCount(): Long {
return state.modificationCount
}
@Suppress("DEPRECATION")
private fun migrateOldSettings() {
if (state.ideAAType != AntialiasingType.SUBPIXEL) {
ideAAType = state.ideAAType
state.ideAAType = AntialiasingType.SUBPIXEL
}
if (state.editorAAType != AntialiasingType.SUBPIXEL) {
editorAAType = state.editorAAType
state.editorAAType = AntialiasingType.SUBPIXEL
}
if (!state.allowMergeButtons) {
Registry.get("ide.allow.merge.buttons").setValue(false)
state.allowMergeButtons = true
}
}
@Suppress("DEPRECATION")
private fun migrateOldFontSettings(): Boolean {
var migrated = false
if (state.fontSize != 0) {
fontSize2D = restoreFontSize(state.fontSize.toFloat(), state.fontScale)
state.fontSize = 0
migrated = true
}
if (state.fontScale != 0f) {
fontScale = state.fontScale
state.fontScale = 0f
migrated = true
}
if (state.fontFace != null) {
fontFace = state.fontFace
state.fontFace = null
migrated = true
}
return migrated
}
//<editor-fold desc="Deprecated stuff.">
@Suppress("PropertyName")
@Deprecated("Use fontFace", replaceWith = ReplaceWith("fontFace"))
@JvmField
@Transient
@ScheduledForRemoval
var FONT_FACE: String? = null
@Suppress("PropertyName")
@Deprecated("Use fontSize", replaceWith = ReplaceWith("fontSize"))
@JvmField
@Transient
@ScheduledForRemoval
var FONT_SIZE: Int? = 0
@Suppress("PropertyName", "SpellCheckingInspection")
@Deprecated("Use overrideLafFonts", replaceWith = ReplaceWith("overrideLafFonts"))
@JvmField
@Transient
@ScheduledForRemoval
var OVERRIDE_NONIDEA_LAF_FONTS = false
@Suppress("PropertyName")
@Deprecated("Use editorTabLimit", replaceWith = ReplaceWith("editorTabLimit"))
@JvmField
@Transient
@ScheduledForRemoval
var EDITOR_TAB_LIMIT = editorTabLimit
//</editor-fold>
}
| apache-2.0 | f32f3fd3270e5010440f4cc83d8bbd43 | 29.234186 | 167 | 0.706286 | 4.948018 | false | false | false | false |
GunoH/intellij-community | platform/vcs-log/impl/src/com/intellij/vcs/log/graph/DefaultColorGenerator.kt | 8 | 1226 | // 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.vcs.log.graph
import com.intellij.ui.JBColor
import com.intellij.vcs.log.paint.ColorGenerator
import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap
import java.awt.Color
import java.util.function.IntFunction
import kotlin.math.abs
/**
* @author erokhins
*/
class DefaultColorGenerator : ColorGenerator {
override fun getColor(colorId: Int): JBColor {
return ourColorMap.computeIfAbsent(colorId, IntFunction { calcColor(it) })
}
companion object {
private val ourColorMap = Int2ObjectOpenHashMap<JBColor>().apply {
put(GraphColorManagerImpl.DEFAULT_COLOR, JBColor.BLACK)
}
private fun calcColor(colorId: Int): JBColor {
val r = colorId * 200 + 30
val g = colorId * 130 + 50
val b = colorId * 90 + 100
return try {
val color = Color(rangeFix(r), rangeFix(g), rangeFix(b))
JBColor(color, color)
}
catch (a: IllegalArgumentException) {
throw IllegalArgumentException("Color: $colorId ${r % 256} ${g % 256} ${b % 256}")
}
}
private fun rangeFix(n: Int) = abs(n % 100) + 70
}
} | apache-2.0 | 11c3977bfee89bda615e252fc577157a | 30.461538 | 120 | 0.685971 | 3.819315 | false | false | false | false |
Briseus/Lurker | app/src/main/java/torille/fi/lurkforreddit/comments/CommentActivity.kt | 1 | 3827 | package torille.fi.lurkforreddit.comments
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.support.v4.app.Fragment
import android.view.View
import dagger.android.support.DaggerAppCompatActivity
import kotlinx.android.synthetic.main.activity_comments.*
import kotlinx.coroutines.experimental.android.UI
import kotlinx.coroutines.experimental.launch
import timber.log.Timber
import torille.fi.lurkforreddit.R
import torille.fi.lurkforreddit.customTabs.CustomTabActivityHelper
import torille.fi.lurkforreddit.data.models.view.Post
import torille.fi.lurkforreddit.media.FullscreenActivity
import torille.fi.lurkforreddit.utils.MediaHelper
import javax.inject.Inject
class CommentActivity : DaggerAppCompatActivity() {
@Inject
lateinit var post: Post
private val customTabActivityHelper: CustomTabActivityHelper = CustomTabActivityHelper()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_comments)
setSupportActionBar(appBarLayout)
val actionBar = supportActionBar
if (actionBar != null) {
val icon = resources.getDrawable(R.drawable.ic_arrow_back_white_24px, null)
actionBar.title = ""
actionBar.setHomeAsUpIndicator(icon)
actionBar.setDisplayHomeAsUpEnabled(true)
}
setupImage()
val commentFragment: CommentFragment? = supportFragmentManager
.findFragmentById(R.id.contentFrame) as? CommentFragment
if (commentFragment == null) {
initFragment(CommentFragment())
}
}
private fun setupImage() {
val parallaxImageUrl = post.previewImage
Timber.d("Got previewImage url = $parallaxImageUrl")
if (parallaxImageUrl.isNotEmpty()) {
parallaxImage.setOnClickListener {
val postUrl = post.url
if (MediaHelper.isContentMedia(postUrl, post.domain)) {
val intent = Intent(this, FullscreenActivity::class.java)
intent.putExtra(FullscreenActivity.EXTRA_POST, post)
startActivity(intent)
} else {
val activity = this
launch(UI) {
CustomTabActivityHelper.openCustomTab(
activity,
MediaHelper.createCustomTabIntentAsync(
activity,
customTabActivityHelper.session
).await(),
postUrl
) { _, _ ->
val intent = Intent(Intent.ACTION_VIEW, Uri.parse(postUrl))
startActivity(intent)
}
}
}
}
parallaxImage.setImageURI(parallaxImageUrl)
} else {
parallaxImage.visibility = View.GONE
}
}
private fun initFragment(commentFragment: Fragment) {
// Add the NotesDetailFragment to the layout
val fragmentManager = supportFragmentManager
val transaction = fragmentManager.beginTransaction()
transaction.add(R.id.contentFrame, commentFragment)
transaction.commit()
}
override fun onSupportNavigateUp(): Boolean {
onBackPressed()
return true
}
override fun onStart() {
super.onStart()
customTabActivityHelper.bindCustomTabsService(this)
}
override fun onStop() {
super.onStop()
customTabActivityHelper.unbindCustomTabsService(this)
}
companion object {
val EXTRA_CLICKED_POST = "post"
val IS_SINGLE_COMMENT_THREAD = "single"
}
}
| mit | 3dc3106f5cbda902c40538231586bcba | 31.991379 | 92 | 0.623987 | 5.344972 | false | false | false | false |
siosio/intellij-community | plugins/markdown/src/org/intellij/plugins/markdown/editor/lists/MarkdownListItemCreatingTypedHandlerDelegate.kt | 1 | 2261 | package org.intellij.plugins.markdown.editor.lists
import com.intellij.codeInsight.editorActions.TypedHandlerDelegate
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiDocumentManager
import com.intellij.psi.PsiFile
import com.intellij.psi.util.elementType
import com.intellij.psi.util.parentOfType
import com.intellij.refactoring.suggested.endOffset
import com.intellij.util.text.CharArrayUtil
import org.intellij.plugins.markdown.editor.lists.ListRenumberUtils.renumberInBulk
import org.intellij.plugins.markdown.editor.lists.ListUtils.getLineIndentRange
import org.intellij.plugins.markdown.lang.MarkdownTokenTypeSets
import org.intellij.plugins.markdown.lang.psi.impl.MarkdownFile
import org.intellij.plugins.markdown.lang.psi.impl.MarkdownListImpl
/**
* This handler renumbers the current list when you hit Enter after the number of some list item.
*/
internal class MarkdownListItemCreatingTypedHandlerDelegate : TypedHandlerDelegate() {
override fun charTyped(c: Char, project: Project, editor: Editor, file: PsiFile): Result {
if (file !is MarkdownFile || c != ' ') return Result.CONTINUE
val document = editor.document
PsiDocumentManager.getInstance(project).commitDocument(document)
val caret = editor.caretModel.currentCaret
val element = file.findElementAt(caret.offset - 1)
if (element == null || element.elementType !in MarkdownTokenTypeSets.LIST_MARKERS) {
return Result.CONTINUE
}
if (caret.offset <= document.getLineIndentRange(caret.logicalPosition.line).endOffset) {
// so that entering a space before a list item won't renumber it
return Result.CONTINUE
}
val markerEnd = element.endOffset - 1
if (CharArrayUtil.shiftBackward(document.charsSequence, markerEnd, " ") < markerEnd - 1) {
// so that entering a space after a marker won't turn children-items into siblings
return Result.CONTINUE
}
element.parentOfType<MarkdownListImpl>()!!.renumberInBulk(document, recursive = false, restart = false)
PsiDocumentManager.getInstance(project).commitDocument(document)
caret.moveToOffset(file.findElementAt(caret.offset - 1)?.endOffset ?: caret.offset)
return Result.STOP
}
}
| apache-2.0 | 6161d9f69673203b3baab189f7d61d21 | 42.480769 | 107 | 0.78107 | 4.522 | false | false | false | false |
jwren/intellij-community | platform/execution-impl/src/com/intellij/execution/runToolbar/DraggablePane.kt | 3 | 3897 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
// 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.execution.runToolbar
import com.intellij.util.ui.JBDimension
import com.intellij.util.ui.UIUtil
import com.intellij.util.ui.update.MergingUpdateQueue
import com.intellij.util.ui.update.Update
import java.awt.*
import java.awt.event.AWTEventListener
import java.awt.event.MouseAdapter
import java.awt.event.MouseEvent
import javax.swing.JPanel
open class DraggablePane : JPanel() {
private var listener: DragListener? = null
private var startPoint: Point? = null
private val myUpdateQueue = MergingUpdateQueue("draggingQueue", 50, true, MergingUpdateQueue.ANY_COMPONENT)
private val awtDragListener = AWTEventListener {
when (it.id) {
MouseEvent.MOUSE_RELEASED -> {
it as MouseEvent
getOffset(it.locationOnScreen)?.let { offset ->
listener?.dragStopped(it.locationOnScreen, offset)
}
removeAWTListener()
}
MouseEvent.MOUSE_DRAGGED -> {
it as MouseEvent
getOffset(it.locationOnScreen)?.let { offset ->
myUpdateQueue.queue(object : Update("draggingUpdate", false, 1) {
override fun run() {
listener?.dragged(it.locationOnScreen, offset)
}
})
}
}
}
}
fun setListener(listener: DragListener) {
this.listener = listener
}
private fun getOffset(locationOnScreen: Point): Dimension? {
return startPoint?.let{
val offsetX = locationOnScreen.x - it.x
val offsetY = locationOnScreen.y - it.y
Dimension(offsetX, offsetY)
}
}
private val startDragListener = object : MouseAdapter() {
override fun mouseEntered(e: MouseEvent?) {
setCursor()
}
override fun mouseExited(e: MouseEvent?) {
startPoint ?: run {
resetCursor()
}
}
override fun mousePressed(e: MouseEvent) {
startPoint = e.locationOnScreen
listener?.dragStarted(e.locationOnScreen)
setCursor()
Toolkit.getDefaultToolkit().addAWTEventListener(
awtDragListener, AWTEvent.MOUSE_EVENT_MASK or AWTEvent.MOUSE_MOTION_EVENT_MASK)
}
}
private fun setCursor() {
UIUtil.getRootPane(this)?.layeredPane?.cursor = Cursor.getPredefinedCursor(Cursor.W_RESIZE_CURSOR)
}
private fun resetCursor() {
UIUtil.getRootPane(this)?.layeredPane?.cursor = Cursor.getDefaultCursor()
}
override fun addNotify() {
super.addNotify()
addMouseListener(startDragListener)
}
override fun removeNotify() {
removeListeners()
super.removeNotify()
}
private fun removeAWTListener() {
Toolkit.getDefaultToolkit().removeAWTEventListener(awtDragListener)
resetCursor()
startPoint = null
}
private fun removeListeners() {
removeMouseListener(startDragListener)
removeAWTListener()
}
init {
isOpaque = false
//background = Color.RED
preferredSize = JBDimension(7, 21)
minimumSize = JBDimension(7, 21)
setListener(object : DragListener {
override fun dragStarted(locationOnScreen: Point) {
RunWidgetResizeController.getInstance().dragStarted(locationOnScreen)
}
override fun dragged(locationOnScreen: Point, offset: Dimension) {
RunWidgetResizeController.getInstance().dragged(locationOnScreen, offset)
}
override fun dragStopped(locationOnScreen: Point, offset: Dimension) {
RunWidgetResizeController.getInstance().dragStopped(locationOnScreen, offset)
}
})
}
interface DragListener {
fun dragStarted(locationOnScreen: Point)
fun dragged(locationOnScreen: Point, offset: Dimension)
fun dragStopped(locationOnScreen: Point, offset: Dimension)
}
} | apache-2.0 | e8ec8b53deb23507ee115a7cde98651a | 27.874074 | 120 | 0.696433 | 4.644815 | false | false | false | false |
jwren/intellij-community | java/java-tests/testSrc/com/intellij/codeInspection/ex/ProjectInspectionManagerTest.kt | 2 | 11047 | // 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.codeInspection.ex
import com.intellij.codeHighlighting.HighlightDisplayLevel
import com.intellij.configurationStore.LISTEN_SCHEME_VFS_CHANGES_IN_TEST_MODE
import com.intellij.configurationStore.StoreReloadManager
import com.intellij.ide.highlighter.ProjectFileType
import com.intellij.openapi.project.Project
import com.intellij.openapi.vfs.LocalFileSystem
import com.intellij.profile.codeInspection.PROFILE_DIR
import com.intellij.profile.codeInspection.ProjectInspectionProfileManager
import com.intellij.project.stateStore
import com.intellij.testFramework.*
import com.intellij.testFramework.assertions.Assertions.assertThat
import com.intellij.util.io.*
import kotlinx.coroutines.runBlocking
import org.junit.ClassRule
import org.junit.Rule
import org.junit.Test
import java.nio.file.Path
import java.nio.file.Paths
class ProjectInspectionManagerTest {
companion object {
@JvmField
@ClassRule
val appRule = ApplicationRule()
}
@Rule
@JvmField
val tempDirManager = TemporaryDirectory()
@Rule
@JvmField
val initInspectionRule = InitInspectionRule()
private fun doTest(task: suspend (Project) -> Unit) {
runBlocking {
loadAndUseProjectInLoadComponentStateMode(tempDirManager, { Paths.get(it.path) }, task)
}
}
@Test
fun component() {
doTest { project ->
val projectInspectionProfileManager = ProjectInspectionProfileManager.getInstance(project)
assertThat(projectInspectionProfileManager.state).isEmpty()
projectInspectionProfileManager.currentProfile
assertThat(projectInspectionProfileManager.state).isEmpty()
// cause to use app profile
projectInspectionProfileManager.setRootProfile(null)
val doNotUseProjectProfileState = """
<state>
<settings>
<option name="USE_PROJECT_PROFILE" value="false" />
<version value="1.0" />
</settings>
</state>""".trimIndent()
assertThat(projectInspectionProfileManager.state).isEqualTo(doNotUseProjectProfileState)
val inspectionDir = project.stateStore.directoryStorePath!!.resolve(PROFILE_DIR)
val file = inspectionDir.resolve("profiles_settings.xml")
project.stateStore.save()
assertThat(file).exists()
val doNotUseProjectProfileData = """
<component name="InspectionProjectProfileManager">
<settings>
<option name="USE_PROJECT_PROFILE" value="false" />
<version value="1.0" />
</settings>
</component>""".trimIndent()
assertThat(file.readText()).isEqualTo(doNotUseProjectProfileData)
// test load
file.delete()
refreshProjectConfigDir(project)
StoreReloadManager.getInstance().reloadChangedStorageFiles()
assertThat(projectInspectionProfileManager.state).isEmpty()
file.write(doNotUseProjectProfileData)
refreshProjectConfigDir(project)
StoreReloadManager.getInstance().reloadChangedStorageFiles()
assertThat(projectInspectionProfileManager.state).isEqualTo(doNotUseProjectProfileState)
}
}
@Test
fun `do not save default project profile`() {
doTest { project ->
val inspectionDir = project.stateStore.directoryStorePath!!.resolve(PROFILE_DIR)
val profileFile = inspectionDir.resolve("Project_Default.xml")
assertThat(profileFile).doesNotExist()
val projectInspectionProfileManager = ProjectInspectionProfileManager.getInstance(project)
assertThat(projectInspectionProfileManager.state).isEmpty()
projectInspectionProfileManager.currentProfile
assertThat(projectInspectionProfileManager.state).isEmpty()
project.stateStore.save()
assertThat(profileFile).doesNotExist()
}
}
@Test
fun profiles() {
doTest { project ->
project.putUserData(LISTEN_SCHEME_VFS_CHANGES_IN_TEST_MODE, true)
val projectInspectionProfileManager = ProjectInspectionProfileManager.getInstance(project)
projectInspectionProfileManager.forceLoadSchemes()
assertThat(projectInspectionProfileManager.state).isEmpty()
// cause to use app profile
val currentProfile = projectInspectionProfileManager.currentProfile
assertThat(currentProfile.isProjectLevel).isTrue()
currentProfile.setToolEnabled("Convert2Diamond", false)
project.stateStore.save()
val inspectionDir = project.stateStore.directoryStorePath!!.resolve(PROFILE_DIR)
val file = inspectionDir.resolve("profiles_settings.xml")
assertThat(file).doesNotExist()
val profileFile = inspectionDir.resolve("Project_Default.xml")
assertThat(profileFile.readText()).isEqualTo("""
<component name="InspectionProjectProfileManager">
<profile version="1.0">
<option name="myName" value="Project Default" />
<inspection_tool class="Convert2Diamond" enabled="false" level="WARNING" enabled_by_default="false" editorAttributes="NOT_USED_ELEMENT_ATTRIBUTES" />
</profile>
</component>""".trimIndent())
profileFile.write("""
<component name="InspectionProjectProfileManager">
<profile version="1.0">
<option name="myName" value="Project Default" />
<inspection_tool class="Convert2Diamond" enabled="false" level="ERROR" enabled_by_default="false" />
</profile>
</component>""".trimIndent())
refreshProjectConfigDir(project)
StoreReloadManager.getInstance().reloadChangedStorageFiles()
assertThat(projectInspectionProfileManager.currentProfile.getToolDefaultState("Convert2Diamond", project).level).isEqualTo(
HighlightDisplayLevel.ERROR)
}
}
@Test
fun `detect externally added profiles`() {
doTest { project ->
project.putUserData(LISTEN_SCHEME_VFS_CHANGES_IN_TEST_MODE, true)
val profileManager = ProjectInspectionProfileManager.getInstance(project)
profileManager.forceLoadSchemes()
assertThat(profileManager.profiles.joinToString { it.name }).isEqualTo("Project Default")
assertThat(profileManager.currentProfile.isProjectLevel).isTrue()
assertThat(profileManager.currentProfile.name).isEqualTo("Project Default")
val projectConfigDir = project.stateStore.directoryStorePath!!
// test creation of .idea/inspectionProfiles dir, not .idea itself
projectConfigDir.createDirectories()
LocalFileSystem.getInstance().refreshAndFindFileByPath(projectConfigDir.toString())
val profileDir = projectConfigDir.resolve(PROFILE_DIR)
profileDir.writeChild("profiles_settings.xml", """<component name="InspectionProjectProfileManager">
<settings>
<option name="PROJECT_PROFILE" value="idea.default" />
<version value="1.0" />
<info color="eb9904">
<option name="FOREGROUND" value="0" />
<option name="BACKGROUND" value="eb9904" />
<option name="ERROR_STRIPE_COLOR" value="eb9904" />
<option name="myName" value="Strong Warning" />
<option name="myVal" value="50" />
<option name="myExternalName" value="Strong Warning" />
<option name="myDefaultAttributes">
<option name="ERROR_STRIPE_COLOR" value="eb9904" />
</option>
</info>
</settings>
</component>""")
writeDefaultProfile(profileDir)
profileDir.writeChild("idea_default_teamcity.xml", """
<component name="InspectionProjectProfileManager">
<profile version="1.0">
<option name="myName" value="idea.default.teamcity" />
<inspection_tool class="AbsoluteAlignmentInUserInterface" enabled="false" level="WARNING" enabled_by_default="false">
<scope name="android" level="WARNING" enabled="false" />
</inspection_tool>
</profile>
</component>""")
refreshProjectConfigDir(project)
StoreReloadManager.getInstance().reloadChangedStorageFiles()
assertThat(profileManager.currentProfile.isProjectLevel).isTrue()
assertThat(profileManager.currentProfile.name).isEqualTo("Project Default")
assertThat(profileManager.profiles.joinToString { it.name }).isEqualTo("Project Default, idea.default.teamcity")
profileDir.delete()
writeDefaultProfile(profileDir)
refreshProjectConfigDir(project)
StoreReloadManager.getInstance().reloadChangedStorageFiles()
assertThat(profileManager.currentProfile.name).isEqualTo("Project Default")
project.stateStore.save()
assertThat(profileDir.resolve("Project_Default.xml")).isEqualTo(DEFAULT_PROJECT_PROFILE_CONTENT)
}
}
@Test
fun ipr() = runBlocking {
val emptyProjectFile = """
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
</project>""".trimIndent()
loadAndUseProjectInLoadComponentStateMode(tempDirManager, {
Paths.get(it.writeChild("test${ProjectFileType.DOT_DEFAULT_EXTENSION}", emptyProjectFile).path)
}) { project ->
val projectInspectionProfileManager = ProjectInspectionProfileManager.getInstance(project)
projectInspectionProfileManager.forceLoadSchemes()
assertThat(projectInspectionProfileManager.state).isEmpty()
val currentProfile = projectInspectionProfileManager.currentProfile
assertThat(currentProfile.isProjectLevel).isTrue()
currentProfile.setToolEnabled("Convert2Diamond", false)
currentProfile.profileChanged()
project.stateStore.save()
val projectFile = project.stateStore.projectFilePath
assertThat(projectFile.parent.resolve(".inspectionProfiles")).doesNotExist()
val expected = """
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="InspectionProjectProfileManager">
<profile version="1.0">
<option name="myName" value="Project Default" />
<inspection_tool class="Convert2Diamond" enabled="false" level="WARNING" enabled_by_default="false" editorAttributes="NOT_USED_ELEMENT_ATTRIBUTES" />
</profile>
<version value="1.0" />
</component>
</project>""".trimIndent()
assertThat(projectFile.readText()).isEqualTo(expected)
currentProfile.disableAllTools()
currentProfile.profileChanged()
project.stateStore.save()
assertThat(projectFile.readText()).isNotEqualTo(expected)
assertThat(projectFile.parent.resolve(".inspectionProfiles")).doesNotExist()
}
}
}
private val DEFAULT_PROJECT_PROFILE_CONTENT = """
<component name="InspectionProjectProfileManager">
<profile version="1.0">
<option name="myName" value="Project Default" />
<inspection_tool class="ActionCableChannelNotFound" enabled="false" level="WARNING" enabled_by_default="false" />
</profile>
</component>""".trimIndent()
private fun writeDefaultProfile(profileDir: Path) {
profileDir.writeChild("Project_Default.xml", DEFAULT_PROJECT_PROFILE_CONTENT)
} | apache-2.0 | cc966b567e1c7c2e898d59207f257fa9 | 38.457143 | 161 | 0.716575 | 5.060467 | false | true | false | false |
smmribeiro/intellij-community | platform/execution-impl/src/com/intellij/execution/runToolbar/RunToolbarExtraSlotPane.kt | 1 | 6784 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.execution.runToolbar
import com.intellij.icons.AllIcons
import com.intellij.ide.DataManager
import com.intellij.lang.LangBundle
import com.intellij.openapi.actionSystem.*
import com.intellij.openapi.actionSystem.impl.segmentedActionBar.SegmentedActionToolbarComponent
import com.intellij.openapi.options.ShowSettingsUtil
import com.intellij.openapi.project.Project
import com.intellij.ui.Gray
import com.intellij.ui.JBColor
import com.intellij.ui.components.labels.LinkLabel
import com.intellij.ui.components.panels.VerticalLayout
import com.intellij.util.ui.JBUI
import com.intellij.util.ui.UIUtil
import net.miginfocom.swing.MigLayout
import java.awt.Dimension
import java.awt.Font
import java.awt.event.MouseAdapter
import java.awt.event.MouseEvent
import javax.swing.JComponent
import javax.swing.JLabel
import javax.swing.JPanel
import javax.swing.SwingUtilities
class RunToolbarExtraSlotPane(val project: Project, val baseWidth: () -> Int?): ActiveListener {
private val manager = RunToolbarSlotManager.getInstance(project)
val slotPane = JPanel(VerticalLayout(JBUI.scale(3))).apply {
isOpaque = false
border = JBUI.Borders.empty()
}
private val components = mutableListOf<SlotComponent>()
private val managerListener = object : SlotListener {
override fun slotAdded() {
addSingleSlot()
}
override fun slotRemoved(index: Int) {
if (index >= 0 && index < components.size) {
removeSingleComponent(components[index])
}
else {
rebuild()
}
}
override fun rebuildPopup() {
rebuild()
}
}
init {
manager.addListener(this)
}
override fun enabled() {
manager.addListener(managerListener)
}
override fun disabled() {
manager.removeListener(managerListener)
}
private var added = false
val newSlotDetails = object : JLabel(LangBundle.message("run.toolbar.add.slot.details")){
override fun getFont(): Font {
return JBUI.Fonts.toolbarFont()
}
}.apply {
border = JBUI.Borders.empty()
isEnabled = false
}
private val pane = object : JPanel(VerticalLayout(JBUI.scale(2))) {
override fun addNotify() {
build()
added = true
super.addNotify()
SwingUtilities.invokeLater {
pack()
}
}
override fun removeNotify() {
added = false
super.removeNotify()
}
}.apply {
border = JBUI.Borders.empty(3, 0, 0, 3)
background = JBColor.namedColor("Panel.background", Gray.xCD)
add(slotPane)
val bottomPane = object : JPanel(MigLayout("fillx, ins 0, novisualpadding, gap 0, hidemode 2, wrap 3", "[][]push[]")) {
override fun getPreferredSize(): Dimension {
val preferredSize = super.getPreferredSize()
baseWidth()?.let {
preferredSize.width = it
}
return preferredSize
}
}.apply {
isOpaque = false
border = JBUI.Borders.empty(5, 0, 7, 5)
add(JLabel(AllIcons.Toolbar.AddSlot).apply {
val d = preferredSize
d.width = FixWidthSegmentedActionToolbarComponent.ARROW_WIDTH
preferredSize = d
addMouseListener(object : MouseAdapter() {
override fun mouseClicked(e: MouseEvent) {
manager.addAndSaveSlot()
}
})
})
add(LinkLabel<Unit>(LangBundle.message("run.toolbar.add.slot"), null).apply {
setListener(
{_, _ ->
manager.addAndSaveSlot()
}, null)
})
add(JLabel(AllIcons.General.GearPlain).apply {
addMouseListener(object : MouseAdapter() {
override fun mouseClicked(e: MouseEvent) {
ShowSettingsUtil.getInstance().showSettingsDialog(project, RunToolbarSettingsConfigurable::class.java)
}
})
isVisible = RunToolbarProcess.isSettingsAvailable
})
add(newSlotDetails, "skip")
}
add(bottomPane)
}
internal fun getView(): JComponent = pane
private fun rebuild() {
build()
pack()
}
private fun build() {
val count = manager.slotsCount()
slotPane.removeAll()
components.clear()
repeat(count) { addNewSlot() }
}
private fun addSingleSlot() {
addNewSlot()
pack()
}
private fun removeSingleComponent(component: SlotComponent) {
removeComponent(component)
pack()
}
private fun addNewSlot() {
val slot = createComponent()
slot.minus.addMouseListener(object : MouseAdapter() {
override fun mouseClicked(e: MouseEvent) {
getData(slot)?.let {
manager.removeSlot(it.id)
}
}
})
slotPane.add(slot.view)
components.add(slot)
}
private fun pack() {
newSlotDetails.isVisible = manager.slotsCount() == 0
slotPane.revalidate()
pane.revalidate()
slotPane.repaint()
pane.repaint()
UIUtil.getWindow(pane)?.let {
if (it.isShowing) {
it.pack()
}
}
}
private fun removeComponent(component: SlotComponent) {
slotPane.remove(component.view)
components.remove(component)
}
private fun getData(component: SlotComponent): SlotDate? {
val index = components.indexOf(component)
if(index < 0) return null
return manager.getData(index)
}
private fun createComponent(): SlotComponent {
val group = DefaultActionGroup()
val bar = FixWidthSegmentedActionToolbarComponent(ActionPlaces.MAIN_TOOLBAR, group)
val component = SlotComponent(bar, JLabel(AllIcons.Toolbar.RemoveSlot).apply {
val d = preferredSize
d.width = FixWidthSegmentedActionToolbarComponent.ARROW_WIDTH
preferredSize = d
})
bar.targetComponent = bar
DataManager.registerDataProvider(bar, DataProvider {
key ->
if(RunToolbarData.RUN_TOOLBAR_DATA_KEY.`is`(key)) {
getData(component)
}
else
null
})
val runToolbarActionsGroup = ActionManager.getInstance().getAction(
"RunToolbarActionsGroup") as DefaultActionGroup
val dataContext = DataManager.getInstance().getDataContext(bar)
val event = AnActionEvent.createFromDataContext("RunToolbarActionsGroup", null, dataContext)
for (action in runToolbarActionsGroup.getChildren(event)) {
if (action is ActionGroup && !action.isPopup) {
group.addAll(*action.getChildren(event))
}
else {
group.addAction(action)
}
}
return component
}
internal data class SlotComponent(val bar: SegmentedActionToolbarComponent, val minus: JComponent) {
val view = JPanel(MigLayout("ins 0, gap 0, novisualpadding")).apply {
add(minus)
add(bar)
}
}
} | apache-2.0 | 123704e9072ddb70a89509ec0abd43e2 | 26.14 | 158 | 0.671728 | 4.501659 | false | false | false | false |
smmribeiro/intellij-community | uast/uast-common/src/org/jetbrains/uast/evaluation/MapBasedEvaluationContext.kt | 13 | 3657 | /*
* 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.evaluation
import com.intellij.openapi.progress.ProcessCanceledException
import org.jetbrains.uast.*
import org.jetbrains.uast.values.UUndeterminedValue
import org.jetbrains.uast.values.UValue
import org.jetbrains.uast.visitor.UastVisitor
import java.lang.ref.SoftReference
import java.util.*
class MapBasedEvaluationContext(
override val uastContext: UastLanguagePlugin,
override val extensions: List<UEvaluatorExtension>
) : UEvaluationContext {
data class UEvaluatorWithStamp(val evaluator: UEvaluator, val stamp: Long)
private val evaluators = WeakHashMap<UDeclaration, SoftReference<UEvaluatorWithStamp>>()
override fun analyzeAll(file: UFile, state: UEvaluationState): UEvaluationContext {
file.accept(object : UastVisitor {
override fun visitElement(node: UElement) = false
override fun visitMethod(node: UMethod): Boolean {
analyze(node, state)
return true
}
override fun visitVariable(node: UVariable): Boolean {
if (node is UField) {
analyze(node, state)
return true
}
else return false
}
})
return this
}
@Throws(ProcessCanceledException::class)
private fun getOrCreateEvaluator(declaration: UDeclaration, state: UEvaluationState? = null): UEvaluator {
val containingFile = declaration.getContainingUFile()
val modificationStamp = containingFile?.sourcePsi?.modificationStamp ?: -1L
val evaluatorWithStamp = evaluators[declaration]?.get()
if (evaluatorWithStamp != null && evaluatorWithStamp.stamp == modificationStamp) {
return evaluatorWithStamp.evaluator
}
return createEvaluator(uastContext, extensions).apply {
when (declaration) {
is UMethod -> this.analyze(declaration, state ?: declaration.createEmptyState())
is UField -> this.analyze(declaration, state ?: declaration.createEmptyState())
}
evaluators[declaration] = SoftReference(UEvaluatorWithStamp(this, modificationStamp))
}
}
override fun analyze(declaration: UDeclaration, state: UEvaluationState): UEvaluator = getOrCreateEvaluator(declaration, state)
override fun getEvaluator(declaration: UDeclaration): UEvaluator = getOrCreateEvaluator(declaration)
private fun getEvaluator(expression: UExpression): UEvaluator? {
var containingElement = expression.uastParent
while (containingElement != null) {
if (containingElement is UDeclaration) {
val evaluator = evaluators[containingElement]?.get()?.evaluator
if (evaluator != null) {
return evaluator
}
}
containingElement = containingElement.uastParent
}
return null
}
fun cachedValueOf(expression: UExpression): UValue? =
(getEvaluator(expression) as? TreeBasedEvaluator)?.getCached(expression)
override fun valueOf(expression: UExpression): UValue =
valueOfIfAny(expression) ?: UUndeterminedValue
override fun valueOfIfAny(expression: UExpression): UValue? =
getEvaluator(expression)?.evaluate(expression)
} | apache-2.0 | eae20484f0bbbd8b3381116a2ba84365 | 36.326531 | 129 | 0.736943 | 4.889037 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/j2k/new/src/org/jetbrains/kotlin/nj2k/conversions/DefaultArgumentsConversion.kt | 1 | 9467 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.nj2k.conversions
import com.intellij.psi.PsiMethod
import org.jetbrains.kotlin.load.java.propertyNameByGetMethodName
import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.nj2k.*
import org.jetbrains.kotlin.nj2k.symbols.JKSymbol
import org.jetbrains.kotlin.nj2k.symbols.JKUniverseMethodSymbol
import org.jetbrains.kotlin.nj2k.tree.*
import org.jetbrains.kotlin.nj2k.types.JKNoType
import org.jetbrains.kotlin.utils.addToStdlib.safeAs
class DefaultArgumentsConversion(context: NewJ2kConverterContext) : RecursiveApplicableConversionBase(context) {
private fun JKMethod.canBeGetterOrSetter() =
name.value.asGetterName() != null
|| name.value.asSetterName() != null
private fun JKMethod.canNotBeMerged(): Boolean =
modality == Modality.ABSTRACT
|| hasOtherModifier(OtherModifier.OVERRIDE)
|| hasOtherModifier(OtherModifier.NATIVE)
|| hasOtherModifier(OtherModifier.SYNCHRONIZED)
|| psi<PsiMethod>()?.let { context.converter.converterServices.oldServices.referenceSearcher.hasOverrides(it) } == true
|| annotationList.annotations.isNotEmpty()
|| canBeGetterOrSetter()
override fun applyToElement(element: JKTreeElement): JKTreeElement {
if (element !is JKClassBody) return recurse(element)
val methods = element.declarations.filterIsInstance<JKMethod>().sortedBy { it.parameters.size }
checkMethod@ for (method in methods) {
val block = method.block as? JKBlock ?: continue
val singleStatement = block.statements.singleOrNull() ?: continue
if (method.canNotBeMerged()) continue
val call = lookupCall(singleStatement) ?: continue
val callee = call.identifier as? JKUniverseMethodSymbol ?: continue
val calledMethod = callee.target
if (calledMethod.parent != method.parent
|| callee.name != method.name.value
|| calledMethod.returnType.type != method.returnType.type
|| call.arguments.arguments.size <= method.parameters.size
|| call.arguments.arguments.size < calledMethod.parameters.size //calledMethod has varargs param or call expr has errors
|| calledMethod.parameters.any(JKParameter::isVarArgs)
) {
continue
}
if (calledMethod.visibility != method.visibility) continue@checkMethod
if (calledMethod.canNotBeMerged()) continue
for (i in method.parameters.indices) {
val parameter = method.parameters[i]
val targetParameter = calledMethod.parameters[i]
val argument = call.arguments.arguments[i].value
if (parameter.name.value != targetParameter.name.value) continue@checkMethod
if (parameter.type.type != targetParameter.type.type) continue@checkMethod
if (argument !is JKFieldAccessExpression || argument.identifier.target != parameter) continue@checkMethod
if (parameter.initializer !is JKStubExpression
&& targetParameter.initializer !is JKStubExpression
&& !areTheSameExpressions(targetParameter.initializer, parameter.initializer)
) continue@checkMethod
}
for (i in method.parameters.indices) {
val parameter = method.parameters[i]
val targetParameter = calledMethod.parameters[i]
if (parameter.initializer !is JKStubExpression
&& targetParameter.initializer is JKStubExpression
) {
targetParameter.initializer = parameter.initializer.copyTreeAndDetach()
}
}
for (index in (method.parameters.lastIndex + 1)..calledMethod.parameters.lastIndex) {
val calleeExpression = call.arguments.arguments[index].value
val defaultArgument = calledMethod.parameters[index].initializer.takeIf { it !is JKStubExpression } ?: continue
if (!areTheSameExpressions(calleeExpression, defaultArgument)) continue@checkMethod
}
call.arguments.invalidate()
val defaults = call.arguments.arguments
.map { it::value.detached() }
.zip(calledMethod.parameters)
.drop(method.parameters.size)
fun JKSymbol.isNeedThisReceiver(): Boolean {
val parameters = defaults.map { it.second }
val declarations = element.declarations
val propertyNameByGetMethodName = propertyNameByGetMethodName(Name.identifier(this.name))?.asString()
return parameters.any { it.name.value == this.name || it.name.value == propertyNameByGetMethodName }
&& declarations.any { it == this.target }
}
fun remapParameterSymbol(on: JKTreeElement): JKTreeElement {
if (on is JKQualifiedExpression && on.receiver is JKThisExpression) {
return on
}
if (on is JKFieldAccessExpression) {
val target = on.identifier.target
if (target is JKParameter && target.parent == method) {
val newSymbol =
symbolProvider.provideUniverseSymbol(calledMethod.parameters[method.parameters.indexOf(target)])
return JKFieldAccessExpression(newSymbol)
}
if (on.identifier.isNeedThisReceiver()) {
return JKQualifiedExpression(JKThisExpression(JKLabelEmpty(), JKNoType), JKFieldAccessExpression(on.identifier))
}
}
if (on is JKCallExpression && on.identifier.isNeedThisReceiver()) {
return JKQualifiedExpression(JKThisExpression(JKLabelEmpty(), JKNoType), applyRecursive(on, ::remapParameterSymbol))
}
return applyRecursive(on, ::remapParameterSymbol)
}
for ((defaultValue, parameter) in defaults) {
parameter.initializer = remapParameterSymbol(defaultValue) as JKExpression
}
element.declarations -= method
calledMethod.withFormattingFrom(method)
}
if (element.parentOfType<JKClass>()?.classKind != JKClass.ClassKind.ANNOTATION) {
for (method in element.declarations) {
if (method !is JKMethod) continue
if (method.hasParametersWithDefaultValues()
&& (method.visibility == Visibility.PUBLIC || method.visibility == Visibility.INTERNAL)
) {
method.annotationList.annotations += jvmAnnotation("JvmOverloads", symbolProvider)
}
}
}
return recurse(element)
}
private fun areTheSameExpressions(first: JKElement, second: JKElement): Boolean {
if (first::class != second::class) return false
if (first is JKNameIdentifier && second is JKNameIdentifier) return first.value == second.value
if (first is JKLiteralExpression && second is JKLiteralExpression) return first.literal == second.literal
if (first is JKFieldAccessExpression && second is JKFieldAccessExpression && first.identifier != second.identifier) return false
if (first is JKCallExpression && second is JKCallExpression && first.identifier != second.identifier) return false
return if (first is JKTreeElement && second is JKTreeElement) {
first.children.zip(second.children) { childOfFirst, childOfSecond ->
when {
childOfFirst is JKTreeElement && childOfSecond is JKTreeElement -> {
areTheSameExpressions(
childOfFirst,
childOfSecond
)
}
childOfFirst is List<*> && childOfSecond is List<*> -> {
childOfFirst.zip(childOfSecond) { child1, child2 ->
areTheSameExpressions(
child1 as JKElement,
child2 as JKElement
)
}.fold(true, Boolean::and)
}
else -> false
}
}.fold(true, Boolean::and)
} else false
}
private fun JKMethod.hasParametersWithDefaultValues() =
parameters.any { it.initializer !is JKStubExpression }
private fun lookupCall(statement: JKStatement): JKCallExpression? {
val expression = when (statement) {
is JKExpressionStatement -> statement.expression
is JKReturnStatement -> statement.expression
else -> null
}
return when (expression) {
is JKCallExpression -> expression
is JKQualifiedExpression -> {
if (expression.receiver !is JKThisExpression) return null
expression.selector.safeAs()
}
else -> null
}
}
}
| apache-2.0 | 4edc49f38eb5bb0355a131ced3cc1b23 | 48.307292 | 158 | 0.60769 | 5.615065 | false | false | false | false |
tlaukkan/kotlin-web-vr | client/src/lib/threejs/Renderers.kt | 1 | 1386 | package lib.threejs
import org.w3c.dom.Element
@native("THREE.WebGLRenderer")
open class WebGLRenderer(parameters: Any) {
@native var domElement: Element = noImpl
@native var sortObjects: Boolean = noImpl
@native var physicallyCorrectLights: Boolean = noImpl
@native var gammaInput: Boolean = noImpl
@native var gammaOutput: Boolean = noImpl
@native var shadowMapWidth: Int = noImpl
@native var shadowMapHeight: Int = noImpl
@native var shadowMapEnabled: Boolean = noImpl
@native var shadowMap: dynamic = noImpl
//Functions
fun setSize(innerWidth: Double, innerHeight: Double): Unit = noImpl
fun setClearColor(color: Int): Unit = noImpl
@native fun render(scene: Scene, camera: PerspectiveCamera): Unit = noImpl
@native fun clear(): Unit = noImpl
@native fun clearDepth(): Unit = noImpl
@native fun setViewport(x: Number, y: Number, width: Number, height: Number): Unit = noImpl
@native fun setScissor(x: Number, y: Number, width: Number, height: Number): Unit = noImpl
@native fun setScissorTest(enable: Boolean): Unit = noImpl
@native fun getPixelRatio(): Number = noImpl
@native fun setPixelRatio(value: Number): Unit = noImpl
}
@native("THREE.BasicShadowMap") var BasicShadowMap: dynamic = noImpl
@native("THREE.PCFSoftShadowMap") var PCFSoftShadowMap: dynamic = noImpl
@native("THREE.PCFShadowMap") var PCFShadowMap: dynamic = noImpl | mit | 1b89ea6c5701366d97107721dd442e53 | 37.527778 | 93 | 0.746753 | 4.02907 | false | false | false | false |
adriangl/Dev-QuickSettings | app/src/main/kotlin/com/adriangl/devquicktiles/tiles/DevelopmentTileService.kt | 1 | 2693 | /*
* Copyright (C) 2017 Adrián García
*
* 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.adriangl.devquicktiles.tiles
import android.graphics.drawable.Icon
import android.service.quicksettings.Tile
import android.service.quicksettings.TileService
import android.widget.Toast
import com.adriangl.devquicktiles.R
import timber.log.Timber
abstract class DevelopmentTileService<T : Any> : TileService() {
lateinit var value: T
override fun onStartListening() {
Timber.d("Tile started listening: {label=%s, state=%s}", qsTile.label, qsTile.state)
value = queryValue()
updateState()
}
override fun onClick() {
Timber.d("Tile clicked: {label=%s, state=%s}", qsTile.label, qsTile.state)
setNextValue()
}
private fun setNextValue() {
val newIndex = ((getValueList().indexOf(value) + 1) % getValueList().size)
val newValue = getValueList()[newIndex]
Timber.d("New value: %s, Tile: {label=%s, state=%s}", value, qsTile.label, qsTile.state)
// Disable tile while setting the value
qsTile.state = Tile.STATE_UNAVAILABLE
qsTile.updateTile()
try {
if (saveValue(newValue)) {
value = newValue
}
} catch (e: Exception) {
val permissionNotGrantedString = getString(R.string.qs_permissions_not_granted)
Toast.makeText(applicationContext, permissionNotGrantedString, Toast.LENGTH_LONG)
.show()
Timber.e(e, permissionNotGrantedString)
}
updateState()
}
private fun updateState() {
qsTile.state = if (isActive(value)) Tile.STATE_ACTIVE else Tile.STATE_INACTIVE
qsTile.label = getLabel(value)
qsTile.icon = getIcon(value)
qsTile.updateTile()
Timber.d("Tile updated: {label=%s, state=%s}", qsTile.label, qsTile.state)
}
abstract fun isActive(value: T): Boolean
abstract fun getValueList(): List<T>
abstract fun queryValue(): T
abstract fun saveValue(value: T): Boolean
abstract fun getIcon(value: T): Icon?
abstract fun getLabel(value: T): CharSequence?
}
| apache-2.0 | f0ba2a9dc30fb2701070589dd13d1e6e | 30.290698 | 96 | 0.664809 | 4.211268 | false | false | false | false |
erdo/asaf-project | example-kt-02coroutine/src/main/java/foo/bar/example/forecoroutine/feature/counter/Counter.kt | 1 | 1667 | package foo.bar.example.forecoroutine.feature.counter
import co.early.fore.core.WorkMode
import co.early.fore.kt.core.logging.Logger
import co.early.fore.core.observer.Observable
import co.early.fore.kt.core.coroutine.awaitDefault
import co.early.fore.kt.core.coroutine.launchMain
import co.early.fore.kt.core.delegate.Fore
import co.early.fore.kt.core.observer.ObservableImp
import kotlinx.coroutines.delay
/**
* Copyright © 2019 early.co. All rights reserved.
*/
class Counter(
private val logger: Logger
) : Observable by ObservableImp(logger = logger) {
var isBusy = false
private set
var count: Int = 0
private set
fun increaseBy20() {
logger.i("increaseBy20() t:" + Thread.currentThread())
if (isBusy) {
return
}
isBusy = true
notifyObservers()
launchMain {
val result = awaitDefault {
doStuffInBackground(20)
}
doThingsWithTheResult(result)
}
}
private suspend fun doStuffInBackground(countTo: Int): Int {
logger.i("doStuffInBackground() t:" + Thread.currentThread())
var totalIncrease = 0
for (ii in 1..countTo) {
delay((if (Fore.getWorkMode() == WorkMode.SYNCHRONOUS) 1 else 100).toLong())
++totalIncrease
logger.i("-tick- t:" + Thread.currentThread())
}
return totalIncrease
}
private fun doThingsWithTheResult(result: Int) {
logger.i("doThingsWithTheResult() t:" + Thread.currentThread())
count += result
isBusy = false
notifyObservers()
}
}
| apache-2.0 | 97854ee73a64e796f95d83523bcaf812 | 20.636364 | 88 | 0.62425 | 4.175439 | false | false | false | false |
testIT-LivingDoc/livingdoc2 | livingdoc-converters/src/main/kotlin/org/livingdoc/converters/number/ByteConverter.kt | 2 | 809 | package org.livingdoc.converters.number
import java.math.BigDecimal
/**
* This converter converts a BigDecimal to a Byte
*/
open class ByteConverter : AbstractNumberConverter<Byte>() {
override val lowerBound: Byte = Byte.MIN_VALUE
override val upperBound: Byte = Byte.MAX_VALUE
/**
* This function returns the Byte representation of the given BigDecimal value.
*
* @param number the BigDecimal containing the value that should be converted
*/
override fun convertToTarget(number: BigDecimal): Byte = number.toByte()
override fun canConvertTo(targetType: Class<*>): Boolean {
val isJavaObjectType = Byte::class.javaObjectType == targetType
val isKotlinType = Byte::class.java == targetType
return isJavaObjectType || isKotlinType
}
}
| apache-2.0 | 86f86dfea6c2874de03f4cebb89a7f8b | 31.36 | 83 | 0.71199 | 4.873494 | false | false | false | false |
MartinStyk/AndroidApkAnalyzer | app/src/main/java/sk/styk/martin/apkanalyzer/ui/statistics/StatisticsFragment.kt | 1 | 5643 | package sk.styk.martin.apkanalyzer.ui.statistics
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.content.ContextCompat
import androidx.databinding.DataBindingUtil
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import com.github.mikephil.charting.components.XAxis
import com.github.mikephil.charting.components.YAxis
import com.github.mikephil.charting.data.Entry
import com.github.mikephil.charting.highlight.Highlight
import com.github.mikephil.charting.listener.OnChartValueSelectedListener
import com.github.mikephil.charting.utils.MPPointF
import dagger.hilt.android.AndroidEntryPoint
import sk.styk.martin.apkanalyzer.R
import sk.styk.martin.apkanalyzer.databinding.FragmentStatisticsBinding
import sk.styk.martin.apkanalyzer.ui.appdetail.page.activity.ARROW_ANIMATION_DURATION
import sk.styk.martin.apkanalyzer.ui.appdetail.page.activity.ROTATION_FLIPPED
import sk.styk.martin.apkanalyzer.ui.appdetail.page.activity.ROTATION_STANDARD
import sk.styk.martin.apkanalyzer.ui.applist.packagename.AppListFromPackageNamesDialog
import sk.styk.martin.apkanalyzer.util.components.toDialog
@AndroidEntryPoint
class StatisticsFragment : Fragment() {
private lateinit var binding: FragmentStatisticsBinding
private val viewModel: StatisticsFragmentViewModel by viewModels()
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
binding = DataBindingUtil.inflate(inflater, R.layout.fragment_statistics, container, false)
binding.lifecycleOwner = viewLifecycleOwner
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
setupCharts()
binding.viewModel = viewModel
with(viewModel) {
showDialog.observe(viewLifecycleOwner) {
it.toDialog().show(parentFragmentManager, "description dialog")
}
showAppList.observe(viewLifecycleOwner) {
AppListFromPackageNamesDialog.newInstance(it)
.show(parentFragmentManager, "AppListDialog")
}
analysisResultsExpanded.observe(viewLifecycleOwner) {
animateArrowExpanded(
binding.analysisResultsToggleArrow,
it
)
}
minSdkExpanded.observe(viewLifecycleOwner) {
animateArrowExpanded(
binding.minSdkToggleArrow,
it
)
}
targetSdkExpanded.observe(viewLifecycleOwner) {
animateArrowExpanded(
binding.targetSdkToggleArrow,
it
)
}
installLocationExpanded.observe(viewLifecycleOwner) {
animateArrowExpanded(
binding.installLocationToggleArrow,
it
)
}
signAlgorithmExpanded.observe(viewLifecycleOwner) {
animateArrowExpanded(
binding.signAlgorithmToggleArrow,
it
)
}
appSourceExpanded.observe(viewLifecycleOwner) {
animateArrowExpanded(
binding.appSourceToggleArrow,
it
)
}
}
}
private fun animateArrowExpanded(view: View, expanded: Boolean) {
view.animate().apply {
cancel()
setDuration(ARROW_ANIMATION_DURATION).rotation(if (expanded) ROTATION_FLIPPED else ROTATION_STANDARD)
}
}
private fun setupCharts() {
listOf(
binding.chartMinSdk,
binding.chartTargetSdk,
binding.chartAppSource,
binding.chartSignAlgorithm,
binding.chartInstallLocation
).forEach {
it.apply {
isDragEnabled = true
isScaleXEnabled = true
isScaleYEnabled = false
setDrawValueAboveBar(true)
setDrawGridBackground(false)
setPinchZoom(false)
description.apply {
isEnabled = false
}
xAxis.apply {
isGranularityEnabled = true
position = XAxis.XAxisPosition.BOTTOM
setDrawGridLines(false)
textColor = ContextCompat.getColor(context, R.color.graph_bar)
}
axisLeft.apply {
setDrawZeroLine(false)
setPosition(YAxis.YAxisLabelPosition.OUTSIDE_CHART)
setDrawLimitLinesBehindData(true)
textColor = ContextCompat.getColor(context, R.color.graph_bar)
}
axisRight.apply {
isEnabled = false
}
legend.apply {
isEnabled = false
}
setOnChartValueSelectedListener(object : OnChartValueSelectedListener {
override fun onValueSelected(e: Entry?, h: Highlight?) {
e ?: return
val position = binding.chartAppSource.getPosition(e, YAxis.AxisDependency.RIGHT)
MPPointF.recycleInstance(position)
}
override fun onNothingSelected() {}
})
}
}
}
}
| gpl-3.0 | 872c43f2f159ebb87137026f16e314da | 36.872483 | 115 | 0.604466 | 5.609344 | false | false | false | false |
sksamuel/ktest | kotest-assertions/kotest-assertions-shared/src/commonMain/kotlin/io/kotest/assertions/throwables/AnyThrowableHandling.kt | 1 | 4923 | package io.kotest.assertions.throwables
import io.kotest.assertions.assertionCounter
import io.kotest.assertions.failure
import io.kotest.assertions.show.StringShow
import io.kotest.assertions.show.show
/**
* Verifies that a block of code throws any [Throwable]
*
* Use function to wrap a block of code that you want to verify that throws any kind of [Throwable], where using
* [shouldThrowAny] can't be used for any reason, such as an assignment of a variable (assignments are statements,
* therefore has no return value).
*
* If you want to verify a specific [Throwable], use [shouldThrowExactlyUnit].
*
* If you want to verify a [Throwable] and any subclass, use [shouldThrowUnit].
*
* @see [shouldThrowAny]
*/
inline fun shouldThrowAnyUnit(block: () -> Unit) = shouldThrowAny(block)
/**
* Verifies that a block of code does NOT throw any [Throwable]
*
* Use function to wrap a block of code that you want to make sure doesn't throw any [Throwable],
* where using [shouldNotThrowAny] can't be used for any reason, such as an assignment of a variable (assignments are
* statements, therefore has no return value).
*
* Note that executing this code is no different to executing [block] itself, as any uncaught exception will
* be propagated up anyways.
*
* @see [shouldNotThrowAny]
* @see [shouldNotThrowExactlyUnit]
* @see [shouldNotThrowUnit]
*
*/
inline fun shouldNotThrowAnyUnit(block: () -> Unit) = shouldNotThrowAny(block)
/**
* Verifies that a block of code throws any [Throwable]
*
* Use function to wrap a block of code that you want to verify that throws any kind of [Throwable].
*
* If you want to verify a specific [Throwable], use [shouldThrowExactly].
*
* If you want to verify a [Throwable] and any subclasses, use [shouldThrow]
*
*
* **Attention to assignment operations:**
*
* When doing an assignment to a variable, the code won't compile, because an assignment is not of type [Any], as required
* by [block]. If you need to test that an assignment throws a [Throwable], use [shouldThrowAnyUnit] or it's variations.
*
* ```
* val thrownThrowable: Throwable = shouldThrowAny {
* throw FooException() // This is a random Throwable, could be anything
* }
* ```
*
* @see [shouldThrowAnyUnit]
*/
inline fun shouldThrowAny(block: () -> Any?): Throwable {
assertionCounter.inc()
val thrownException = try {
block()
null
} catch (e: Throwable) {
e
}
return thrownException ?: throw failure("Expected a throwable, but nothing was thrown.")
}
/**
* Verifies that a block of code does NOT throw any [Throwable]
*
* Use function to wrap a block of code that you want to make sure doesn't throw any [Throwable].
*
* Note that executing this code is no different to executing [block] itself, as any uncaught exception will
* be propagated up anyways.
*
* **Attention to assignment operations:**
*
* When doing an assignment to a variable, the code won't compile, because an assignment is not of type [Any], as required
* by [block]. If you need to test that an assignment doesn't throw a [Throwable], use [shouldNotThrowAnyUnit] or it's
* variations.
*
* @see [shouldNotThrowAnyUnit]
* @see [shouldNotThrowExactly]
* @see [shouldNotThrow]
*
*/
inline fun <T> shouldNotThrowAny(block: () -> T): T {
assertionCounter.inc()
val thrownException = try {
return block()
} catch (e: Throwable) {
e
}
throw failure(
"No exception expected, but a ${thrownException::class.simpleName} was thrown.",
thrownException
)
}
/**
* Verifies that a block of code throws any [Throwable] with given [message].
*
* @see [shouldNotThrowMessage]
* */
inline fun <T> shouldThrowMessage(message: String, block: () -> T) {
assertionCounter.inc()
val thrownException = try {
block()
null
} catch (e: Throwable) {
e
}
thrownException ?: throw failure(
"Expected a throwable with message ${StringShow.show(message).value} but nothing was thrown".trimMargin()
)
if (thrownException.message != message) {
throw failure(
"Expected a throwable with message ${StringShow.show(message).value} but got a throwable with message ${thrownException.message.show().value}".trimMargin(),
thrownException
)
}
}
/**
* Verifies that a block of code does not throws any [Throwable] with given [message].
* */
inline fun <T> shouldNotThrowMessage(message: String, block: () -> T) {
assertionCounter.inc()
val thrownException = try {
block()
null
} catch (e: Throwable) {
e
}
if (thrownException != null && thrownException.message == message)
throw failure(
"""Expected no exception with message: "$message"
|but a ${thrownException::class.simpleName} was thrown with given message""".trimMargin(),
thrownException
)
}
| mit | da1dbc3a7d31c7c2f27ec89dd03ab8a9 | 30.158228 | 165 | 0.687386 | 4.105922 | false | false | false | false |
agrawalsuneet/FourFoldLoader | fourfoldloader/src/main/java/com/agrawalsuneet/fourfoldloader/loaders/FourFoldLoader.kt | 1 | 13814 | package com.agrawalsuneet.fourfoldloader.loaders
import android.animation.Animator
import android.animation.AnimatorInflater
import android.animation.AnimatorSet
import android.content.Context
import android.util.AttributeSet
import android.view.Gravity
import android.view.View
import android.view.animation.AlphaAnimation
import android.view.animation.Animation
import com.agrawalsuneet.fourfoldloader.R
import com.agrawalsuneet.fourfoldloader.basicviews.FourSquaresBaseLayout
import java.util.*
/**
* Created by ballu on 13/05/17.
*/
class FourFoldLoader : FourSquaresBaseLayout, Animator.AnimatorListener {
var overridePadding = false
var disappearAnimationDuration = 100
private var noOfSquareVisible = 4
private var mainSquare = 1
private var isClosing = true
private var mainAnimatorSet: AnimatorSet? = null
private var anotherSet: AnimatorSet? = null
private var disappearAlphaAnim: AlphaAnimation? = null
private var viewsToHide: MutableList<View>? = null
constructor(context: Context) : super(context) {
initView()
}
constructor(context: Context, squareLenght: Int, firstSquareColor: Int,
secondSquareColor: Int, thirdSquareColor: Int,
forthSquareColor: Int, startLoadingDefault: Boolean)
: super(context, squareLenght, firstSquareColor,
secondSquareColor, thirdSquareColor,
forthSquareColor, startLoadingDefault) {
}
constructor(context: Context, attrs: AttributeSet) : super(context, attrs) {
initAttributes(attrs)
initView()
}
constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int) : super(context, attrs, defStyleAttr) {
initAttributes(attrs)
initView()
}
override fun initAttributes(attrs: AttributeSet) {
super.initAttributes(attrs)
val typedArray = context.obtainStyledAttributes(attrs, R.styleable.FourFoldLoader, 0, 0)
disappearAnimationDuration = typedArray.getInteger(R.styleable.FourFoldLoader_fourfold_disappearAnimDuration, 100)
overridePadding = typedArray.getBoolean(R.styleable.FourFoldLoader_fourfold_overridePadding, false)
typedArray.recycle()
}
override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec)
if (!overridePadding) {
val padding = (squareLenght * 0.8f).toInt()
setPadding(padding, padding,
padding, padding)
}
setMeasuredDimension(2 * squareLenght + paddingLeft + paddingRight,
2 * squareLenght + paddingTop + paddingBottom)
}
override fun initView() {
super.initView()
//set initial values
noOfSquareVisible = 4
mainSquare = 1
//set pivot of squares
firstSquare!!.pivotX = squareLenght.toFloat()
firstSquare!!.pivotY = squareLenght.toFloat()
secondSquare.pivotX = 0f
secondSquare.pivotY = squareLenght.toFloat()
thirdSquare.pivotX = 0f
thirdSquare.pivotY = 0f
forthSquare.pivotX = squareLenght.toFloat()
forthSquare.pivotY = 0f
}
override fun startLoading() {
viewsToHide = ArrayList()
if (noOfSquareVisible == 4) {
when (mainSquare) {
1, 2 -> {
this.overlay.add(thirdSquare)
this.overlay.add(forthSquare)
mainAnimatorSet = AnimatorInflater.loadAnimator(context, R.animator.bottom_close_up) as AnimatorSet
mainAnimatorSet!!.setTarget(thirdSquare)
mainAnimatorSet!!.duration = animationDuration.toLong()
mainAnimatorSet!!.interpolator = interpolator
mainAnimatorSet!!.start()
anotherSet = AnimatorInflater.loadAnimator(context, R.animator.bottom_close_up) as AnimatorSet
anotherSet!!.setTarget(forthSquare)
anotherSet!!.duration = animationDuration.toLong()
anotherSet!!.interpolator = interpolator
anotherSet!!.start()
viewsToHide!!.add(thirdSquare)
viewsToHide!!.add(forthSquare)
}
3, 4 -> {
this.overlay.add(firstSquare)
this.overlay.add(secondSquare)
mainAnimatorSet = AnimatorInflater.loadAnimator(context, R.animator.top_close_down) as AnimatorSet
mainAnimatorSet!!.setTarget(firstSquare)
mainAnimatorSet!!.duration = animationDuration.toLong()
mainAnimatorSet!!.interpolator = interpolator
mainAnimatorSet!!.start()
anotherSet = AnimatorInflater.loadAnimator(context, R.animator.top_close_down) as AnimatorSet
anotherSet!!.setTarget(secondSquare)
anotherSet!!.duration = animationDuration.toLong()
anotherSet!!.interpolator = interpolator
anotherSet!!.start()
viewsToHide!!.add(firstSquare!!)
viewsToHide!!.add(secondSquare)
}
}
isClosing = true
noOfSquareVisible = 2
} else if (noOfSquareVisible == 2) {
if (isClosing) {
//fold is closing
when (mainSquare) {
1, 4 -> {
//if mainSquare is 1 than 2 should close
//or if main square is 4 than 3 should close
val targetView: View? = if (mainSquare == 1) secondSquare else thirdSquare
topLinearLayout.gravity = Gravity.START
bottomLinearLayout.gravity = Gravity.START
this.overlay.add(targetView!!)
mainAnimatorSet = AnimatorInflater.loadAnimator(context, R.animator.right_close_left) as AnimatorSet
mainAnimatorSet!!.setTarget(targetView)
mainAnimatorSet!!.duration = animationDuration.toLong()
mainAnimatorSet!!.interpolator = interpolator
mainAnimatorSet!!.start()
viewsToHide!!.add(targetView)
}
2, 3 -> {
//if mainSquare is 2 than 1 should close
//or if main square is 3 than 4 should close
val targetView = if (mainSquare == 2) firstSquare else forthSquare
topLinearLayout.gravity = Gravity.END
bottomLinearLayout.gravity = Gravity.END
this.overlay.add(targetView)
mainAnimatorSet = AnimatorInflater.loadAnimator(context, R.animator.left_close_right) as AnimatorSet
mainAnimatorSet!!.setTarget(targetView)
mainAnimatorSet!!.duration = animationDuration.toLong()
mainAnimatorSet!!.interpolator = interpolator
mainAnimatorSet!!.start()
viewsToHide!!.add(targetView!!)
}
}
noOfSquareVisible = 1
} else {
// fold is opening
when (mainSquare) {
1, 3 -> {
this.overlay.add(secondSquare)
this.overlay.add(thirdSquare)
secondSquare.visibility = View.VISIBLE
thirdSquare.visibility = View.VISIBLE
mainAnimatorSet = AnimatorInflater.loadAnimator(context, R.animator.right_open_right) as AnimatorSet
mainAnimatorSet!!.setTarget(secondSquare)
mainAnimatorSet!!.duration = animationDuration.toLong()
mainAnimatorSet!!.interpolator = interpolator
mainAnimatorSet!!.start()
anotherSet = AnimatorInflater.loadAnimator(context, R.animator.right_open_right) as AnimatorSet
anotherSet!!.setTarget(thirdSquare)
anotherSet!!.duration = animationDuration.toLong()
anotherSet!!.interpolator = interpolator
anotherSet!!.start()
}
2, 4 -> {
this.overlay.add(firstSquare)
this.overlay.add(forthSquare)
firstSquare!!.visibility = View.VISIBLE
forthSquare.visibility = View.VISIBLE
mainAnimatorSet = AnimatorInflater.loadAnimator(context, R.animator.left_open_left) as AnimatorSet
mainAnimatorSet!!.setTarget(firstSquare)
mainAnimatorSet!!.duration = animationDuration.toLong()
mainAnimatorSet!!.interpolator = interpolator
mainAnimatorSet!!.start()
anotherSet = AnimatorInflater.loadAnimator(context, R.animator.left_open_left) as AnimatorSet
anotherSet!!.setTarget(forthSquare)
anotherSet!!.duration = animationDuration.toLong()
anotherSet!!.interpolator = interpolator
anotherSet!!.start()
}
}
noOfSquareVisible = 4
}
} else if (noOfSquareVisible == 1) {
when (mainSquare) {
1, 2 -> {
val targetView: View? = if (mainSquare == 1) forthSquare else thirdSquare
this.overlay.add(targetView!!)
targetView.visibility = View.VISIBLE
mainAnimatorSet = AnimatorInflater.loadAnimator(context, R.animator.bottom_open_down) as AnimatorSet
mainAnimatorSet!!.setTarget(targetView)
mainAnimatorSet!!.duration = animationDuration.toLong()
mainAnimatorSet!!.interpolator = interpolator
mainAnimatorSet!!.start()
mainSquare += 2
}
3, 4 -> {
val targetView = if (mainSquare == 3) secondSquare else firstSquare
this.overlay.add(targetView)
targetView!!.visibility = View.VISIBLE
mainAnimatorSet = AnimatorInflater.loadAnimator(context, R.animator.top_open_up) as AnimatorSet
mainAnimatorSet!!.setTarget(targetView)
mainAnimatorSet!!.duration = animationDuration.toLong()
mainAnimatorSet!!.interpolator = interpolator
mainAnimatorSet!!.start()
mainSquare = if (mainSquare == 3) 2 else 1
}
}
noOfSquareVisible = 2
isClosing = false
}
mainAnimatorSet!!.addListener(this)
isLoading = true
}
override fun onAnimationEnd(animation: Animator) {
if (isLoading) {
if (viewsToHide != null && viewsToHide!!.size > 0) {
disappearAlphaAnim = AlphaAnimation(R.dimen.fourfold_to_alpha.toFloat(), 0f)
disappearAlphaAnim!!.duration = disappearAnimationDuration.toLong()
disappearAlphaAnim!!.setAnimationListener(object : Animation.AnimationListener {
override fun onAnimationEnd(animation: Animation) {
if (isLoading) {
for (view in viewsToHide!!) {
view.visibility = View.INVISIBLE
view.rotationX = 0f
view.rotationY = 0f
}
isLoading = false
startLoading()
}
}
override fun onAnimationStart(animation: Animation) {}
override fun onAnimationRepeat(animation: Animation) {}
})
for (view in viewsToHide!!) {
view.startAnimation(disappearAlphaAnim)
}
} else {
isLoading = false
startLoading()
}
}
}
override fun stopLoading() {
isLoading = false
if (mainAnimatorSet != null) {
mainAnimatorSet!!.cancel()
mainAnimatorSet!!.removeListener(this)
mainAnimatorSet = null
}
if (anotherSet != null) {
anotherSet!!.cancel()
anotherSet = null
}
if (disappearAlphaAnim != null) {
disappearAlphaAnim!!.cancel()
disappearAlphaAnim!!.setAnimationListener(null)
disappearAlphaAnim = null
}
firstSquare!!.visibility = View.GONE
secondSquare.visibility = View.GONE
thirdSquare.visibility = View.GONE
forthSquare.visibility = View.GONE
this.removeView(firstSquare)
this.removeView(secondSquare)
this.removeView(thirdSquare)
this.removeView(forthSquare)
topLinearLayout.visibility = View.GONE
bottomLinearLayout.visibility = View.GONE
this.removeView(topLinearLayout)
this.removeView(bottomLinearLayout)
initView()
}
override fun onAnimationStart(animation: Animator) {}
override fun onAnimationCancel(animation: Animator) {}
override fun onAnimationRepeat(animation: Animator) {}
}
| apache-2.0 | 5b2cd72c012b5266fe7f9929a050f867 | 35.935829 | 124 | 0.561966 | 5.727197 | false | false | false | false |
AVnetWS/Hentoid | app/src/main/java/me/devsaki/hentoid/fragments/tools/DuplicateDetailsFragment.kt | 1 | 10463 | package me.devsaki.hentoid.fragments.tools
import android.content.Context
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.view.LayoutInflater
import android.view.MenuItem
import android.view.View
import android.view.ViewGroup
import androidx.activity.OnBackPressedCallback
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.annimon.stream.Stream
import com.google.android.material.switchmaterial.SwitchMaterial
import com.mikepenz.fastadapter.FastAdapter
import com.mikepenz.fastadapter.adapters.ItemAdapter
import com.mikepenz.fastadapter.diff.DiffCallback
import com.mikepenz.fastadapter.diff.FastAdapterDiffUtil.set
import com.mikepenz.fastadapter.listeners.ClickEventHook
import me.devsaki.hentoid.R
import me.devsaki.hentoid.activities.DuplicateDetectorActivity
import me.devsaki.hentoid.activities.bundles.DuplicateItemBundle
import me.devsaki.hentoid.database.domains.Content
import me.devsaki.hentoid.database.domains.DuplicateEntry
import me.devsaki.hentoid.databinding.FragmentDuplicateDetailsBinding
import me.devsaki.hentoid.enums.StatusContent
import me.devsaki.hentoid.events.CommunicationEvent
import me.devsaki.hentoid.fragments.ProgressDialogFragment
import me.devsaki.hentoid.fragments.library.MergeDialogFragment
import me.devsaki.hentoid.util.ContentHelper
import me.devsaki.hentoid.util.ToastHelper
import me.devsaki.hentoid.viewholders.DuplicateItem
import me.devsaki.hentoid.viewmodels.DuplicateViewModel
import me.devsaki.hentoid.viewmodels.ViewModelFactory
import me.zhanghai.android.fastscroll.FastScrollerBuilder
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import timber.log.Timber
import java.lang.ref.WeakReference
@Suppress("PrivatePropertyName")
class DuplicateDetailsFragment : Fragment(R.layout.fragment_duplicate_details),
MergeDialogFragment.Parent {
private var _binding: FragmentDuplicateDetailsBinding? = null
private val binding get() = _binding!!
// Communication
private var callback: OnBackPressedCallback? = null
private lateinit var activity: WeakReference<DuplicateDetectorActivity>
lateinit var viewModel: DuplicateViewModel
// UI
private val itemAdapter = ItemAdapter<DuplicateItem>()
private val fastAdapter = FastAdapter.with(itemAdapter)
// Vars
private var enabled = true
private val ITEM_DIFF_CALLBACK: DiffCallback<DuplicateItem> =
object : DiffCallback<DuplicateItem> {
override fun areItemsTheSame(oldItem: DuplicateItem, newItem: DuplicateItem): Boolean {
return oldItem.identifier == newItem.identifier
}
override fun areContentsTheSame(
oldItem: DuplicateItem,
newItem: DuplicateItem
): Boolean {
return (oldItem.keep == newItem.keep)
&& (oldItem.isBeingDeleted == newItem.isBeingDeleted)
}
override fun getChangePayload(
oldItem: DuplicateItem,
oldItemPosition: Int,
newItem: DuplicateItem,
newItemPosition: Int
): Any? {
val diffBundleBuilder = DuplicateItemBundle.Builder()
if (oldItem.keep != newItem.keep) {
diffBundleBuilder.setKeep(newItem.keep)
}
if (oldItem.isBeingDeleted != newItem.isBeingDeleted) {
diffBundleBuilder.setIsBeingDeleted(newItem.isBeingDeleted)
}
return if (diffBundleBuilder.isEmpty) null else diffBundleBuilder.bundle
}
}
override fun onAttach(context: Context) {
super.onAttach(context)
check(requireActivity() is DuplicateDetectorActivity) { "Parent activity has to be a DuplicateDetectorActivity" }
activity =
WeakReference<DuplicateDetectorActivity>(requireActivity() as DuplicateDetectorActivity)
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
_binding = FragmentDuplicateDetailsBinding.inflate(inflater, container, false)
addCustomBackControl()
activity.get()?.initFragmentToolbars(this::onToolbarItemClicked)
return binding.root
}
override fun onStart() {
super.onStart()
if (!EventBus.getDefault().isRegistered(this)) EventBus.getDefault().register(this)
}
override fun onStop() {
if (EventBus.getDefault().isRegistered(this)) EventBus.getDefault().unregister(this)
super.onStop()
}
override fun onDestroyView() {
super.onDestroyView()
_binding = null
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
val vmFactory = ViewModelFactory(requireActivity().application)
viewModel = ViewModelProvider(requireActivity(), vmFactory)[DuplicateViewModel::class.java]
// List
binding.list.layoutManager =
LinearLayoutManager(requireContext(), LinearLayoutManager.VERTICAL, false)
FastScrollerBuilder(binding.list).build()
binding.list.adapter = fastAdapter
viewModel.selectedDuplicates.observe(
viewLifecycleOwner,
{ l: List<DuplicateEntry>? -> this.onDuplicatesChanged(l) })
// Item click listener
fastAdapter.onClickListener = { _, _, item, _ ->
onItemClick(item)
false
}
// "Keep/delete" switch click listener
fastAdapter.addEventHook(object : ClickEventHook<DuplicateItem>() {
override fun onClick(
v: View,
position: Int,
fastAdapter: FastAdapter<DuplicateItem>,
item: DuplicateItem
) {
onBookChoice(item.content, (v as SwitchMaterial).isChecked)
}
override fun onBind(viewHolder: RecyclerView.ViewHolder): View? {
return if (viewHolder is DuplicateItem.ContentViewHolder) {
viewHolder.keepDeleteSwitch
} else super.onBind(viewHolder)
}
})
binding.applyBtn.setOnClickListener {
binding.applyBtn.isEnabled = false
viewModel.applyChoices {
binding.applyBtn.isEnabled = true
activity.get()?.goBackToMain()
}
}
}
private fun addCustomBackControl() {
if (callback != null) callback?.remove()
callback = object : OnBackPressedCallback(true) {
override fun handleOnBackPressed() {
onCustomBackPress()
}
}
activity.get()!!.onBackPressedDispatcher.addCallback(activity.get()!!, callback!!)
}
private fun onCustomBackPress() {
Handler(Looper.getMainLooper()).postDelayed({ activity.get()?.goBackToMain() }, 100)
}
private fun onItemClick(item: DuplicateItem) {
val c: Content? = item.content
// Process the click
if (null == c) {
ToastHelper.toast(R.string.err_no_content)
return
}
if (!ContentHelper.openHentoidViewer(requireContext(), c, -1, null, false))
ToastHelper.toast(R.string.err_no_content)
}
private fun onBookChoice(item: Content?, choice: Boolean) {
if (item != null)
viewModel.setBookChoice(item, choice)
}
@Synchronized
private fun onDuplicatesChanged(duplicates: List<DuplicateEntry>?) {
if (null == duplicates) return
Timber.i(">> New selected duplicates ! Size=%s", duplicates.size)
// TODO update UI title
activity.get()?.updateTitle(duplicates.size)
val contentStream =
duplicates.map(DuplicateEntry::duplicateContent)
val localCount = contentStream.map { return@map Content::getStatus }
.filter { s -> !s.equals(StatusContent.EXTERNAL) }.count()
val externaCount = duplicates.size - localCount
val streamedCount = contentStream.map { return@map Content::getDownloadMode }
.filter { mode -> mode.equals(Content.DownloadMode.STREAM) }.count()
// streamed, external
activity.get()?.updateToolbar(localCount, externaCount, streamedCount)
// Order by relevance desc and transforms to DuplicateItem
val items = duplicates.sortedByDescending { it.calcTotalScore() }
.map { DuplicateItem(it, DuplicateItem.ViewType.DETAILS) }.toMutableList()
set(itemAdapter, items, ITEM_DIFF_CALLBACK)
}
@Subscribe(threadMode = ThreadMode.MAIN)
fun onActivityEvent(event: CommunicationEvent) {
if (event.recipient != CommunicationEvent.RC_DUPLICATE_DETAILS) return
when (event.type) {
CommunicationEvent.EV_ENABLE -> onEnable()
CommunicationEvent.EV_DISABLE -> onDisable()
}
}
private fun onToolbarItemClicked(menuItem: MenuItem): Boolean {
when (menuItem.itemId) {
R.id.action_merge -> {
MergeDialogFragment.invoke(
this,
Stream.of(itemAdapter.adapterItems)
.map<Content> { obj: DuplicateItem -> obj.content }
.toList(), true
)
}
}
return true
}
private fun onEnable() {
enabled = true
callback?.isEnabled = true
}
private fun onDisable() {
enabled = false
callback?.isEnabled = false
}
override fun mergeContents(
contentList: MutableList<Content>,
newTitle: String,
deleteAfterMerging: Boolean
) {
viewModel.mergeContents(
contentList,
newTitle,
deleteAfterMerging,
) {
ToastHelper.toast(R.string.merge_success)
activity.get()?.goBackToMain()
}
ProgressDialogFragment.invoke(
parentFragmentManager,
resources.getString(R.string.merge_progress),
resources.getString(R.string.pages)
)
}
override fun leaveSelectionMode() {
// Not applicable to this screen
}
} | apache-2.0 | d2f232e88b660e8cc2b790ed683b2786 | 35.207612 | 121 | 0.658129 | 5.076662 | false | false | false | false |
spinnaker/kork | kork-plugins/src/main/kotlin/com/netflix/spinnaker/kork/plugins/pluginref/PluginRef.kt | 3 | 3962 | /*
* Copyright 2019 Netflix, 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.netflix.spinnaker.kork.plugins.pluginref
import com.fasterxml.jackson.annotation.JsonIgnore
import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper
import com.netflix.spinnaker.kork.exceptions.UserException
import java.io.IOException
import java.nio.file.Files
import java.nio.file.Path
import java.nio.file.Paths
import org.pf4j.Plugin
import org.pf4j.PluginDescriptor
/**
* A [PluginRef] is a type of [Plugin] that exists as a pointer to an actual Plugin for use
* during Plugin development.
*
* This class includes helper methods via its companion object to support this as a JSON
* document with a .plugin-ref extension.
*
* The intention of [PluginRef] is to allow a runtime experience similar to dropping a fully
* packaged plugin into the host application, without requiring the packaging and deployment
* step (aside from a one time generation and copy/link of the [PluginRef] file).
*
* @param pluginPath The path to the concrete [Plugin] implementation.
* @param classesDirs A list of directories containing compiled class-files for the [Plugin].
* @param libsDirs A list of directories containing jars scoped to the [Plugin].
*/
data class PluginRef(
/**
* The path to the concrete [Plugin] implementation.
*
* This path will be used to locate a [PluginDescriptor] for the [Plugin].
*/
val pluginPath: String,
/**
* A list of directories containing compiled class-files for the [Plugin].
*
* These directories should match the build output directories in the [Plugin]'s
* development workspace or IDE.
*/
val classesDirs: List<String>,
/**
* A list of directories containing jars scoped to the [Plugin].
*
* These jars should be referenced from the [Plugin]'s development workspace or IDE.
*/
val libsDirs: List<String>
) {
companion object {
/**
* The PluginRef file extension name.
*/
const val EXTENSION = ".plugin-ref"
private val mapper = jacksonObjectMapper()
/**
* Returns whether or not the provided [path] is a valid [PluginRef].
*/
fun isPluginRef(path: Path?): Boolean =
path != null && Files.isRegularFile(path) && path.toString().toLowerCase().endsWith(EXTENSION)
/**
* Loads the given [path] as a [PluginRef].
*/
fun loadPluginRef(path: Path?): PluginRef {
if (!isPluginRef(path)) {
throw InvalidPluginRefException(path)
}
try {
val ref = mapper.readValue(path!!.toFile(), PluginRef::class.java)
return if (ref.refPath.isAbsolute) {
ref
} else {
ref.copy(pluginPath = path.parent.resolve(ref.refPath).toAbsolutePath().toString())
}
} catch (ex: IOException) {
throw MalformedPluginRefException(path!!, ex)
}
}
}
/**
* The path to the plugin ref file.
*/
val refPath: Path
@JsonIgnore
get() = Paths.get(pluginPath)
}
/**
* Thrown when a given plugin ref cannot be found at the given path.
*/
class InvalidPluginRefException(path: Path?) :
UserException(path?.let { "${it.fileName} is not a plugin-ref file" } ?: "Null path passed as plugin-ref")
/**
* Thrown when a valid plugin ref path contains a malformed body.
*/
class MalformedPluginRefException(path: Path, cause: Throwable) :
UserException("${path.fileName} is not a valid plugin-ref", cause)
| apache-2.0 | ea1998a6e3e020eb8236e1c83c1f1305 | 32.016667 | 108 | 0.699647 | 4.127083 | false | false | false | false |
syrop/Wiktor-Navigator | navigator/src/main/kotlin/pl/org/seva/navigator/profile/LoggedInUser.kt | 1 | 1600 | /*
* Copyright (C) 2017 Wiktor Nizio
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* If you like this program, consider donating bitcoin: bc1qncxh5xs6erq6w4qz3a7xl7f50agrgn3w58dsfp
*/
package pl.org.seva.navigator.profile
import com.google.firebase.auth.FirebaseUser
import pl.org.seva.navigator.contact.Contact
import pl.org.seva.navigator.main.init.instance
val loggedInUser by instance<LoggedInUser>()
fun FirebaseUser.setCurrent() = loggedInUser setCurrentUser this
val isLoggedIn get() = loggedInUser.isLoggedIn
class LoggedInUser {
val isLoggedIn get() = name != null && email != null
var email: String? = null
private var name: String? = null
val loggedInContact get() = Contact(checkNotNull(email), checkNotNull(name))
infix fun setCurrentUser(user: FirebaseUser?) {
if (user != null) {
email = user.email
name = user.displayName
}
else {
email = null
name = null
}
}
}
| gpl-3.0 | 5f8f6ebe9e67b9330b93adddfefd845a | 31 | 98 | 0.70625 | 4.134367 | false | false | false | false |
EMResearch/EvoMaster | core/src/main/kotlin/org/evomaster/core/utils/ReportWriter.kt | 1 | 1527 | package org.evomaster.core.utils
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import java.nio.ByteBuffer
import java.nio.channels.FileChannel
import java.nio.file.Files
import java.nio.file.Path
import java.nio.file.StandardOpenOption
/**
* handle outputted reports, e.g., mutation log, sql log
*/
object ReportWriter {
private val log: Logger = LoggerFactory.getLogger(ReportWriter::class.java)
/**
* write/append [value] to a specified [path]
*/
fun writeByChannel(path : Path, value :String, doAppend : Boolean = false){
if (!doAppend){
if (path.parent != null && !Files.exists(path.parent)) Files.createDirectories(path.parent)
if (Files.exists(path))
log.warn("existing file ${path.toFile().absolutePath} will be replaced")
Files.deleteIfExists(path)
Files.createFile(path)
}
val options = if (!doAppend) setOf(StandardOpenOption.WRITE, StandardOpenOption.CREATE)
else setOf(StandardOpenOption.APPEND)
val buffer = ByteBuffer.wrap(value.toByteArray())
FileChannel.open(path, options).run {
writeToChannel(this, buffer)
}
}
/**
* @return a value wrapped with Quotation
*/
fun wrapWithQuotation(value: String) = "\"$value\""
private fun writeToChannel(channel: FileChannel, buffer: ByteBuffer) {
while (buffer.hasRemaining()) {
channel.write(buffer)
}
channel.close()
}
} | lgpl-3.0 | 23f6441bb8567dba8e5d584c45b55255 | 28.960784 | 103 | 0.645711 | 4.289326 | false | false | false | false |
Bluexin/dungeon-generator | src/main/kotlin/be/bluexin/generation/ColorHelper.kt | 1 | 785 | package be.bluexin.generation
import sun.management.ManagementFactoryHelper
/**
* Part of dungeon-generator by Bluexin, released under GNU GPLv3.
*
* @author Bluexin
*/
object ColorHelper {
val SUPPORTS_COLOR = "win" !in System.getProperty("os.name").toLowerCase() ||
ManagementFactoryHelper.getRuntimeMXBean().inputArguments.any { "idea" in it.toLowerCase() }
const val RESET = "\u001B[0m"
const val RED = "\u001B[31m"
const val GREEN = "\u001B[32m"
const val YELLOW = "\u001B[33m"
const val BLUE = "\u001B[34m"
fun getColor(tile: Tile, connected: Boolean) = if (SUPPORTS_COLOR) when (tile) {
is Room -> if (connected) GREEN else RED
is Corridor -> if (connected) YELLOW else BLUE
else -> RESET
} else ""
}
| gpl-3.0 | 57d77fcd0670002b3587a9c2516590f5 | 29.192308 | 104 | 0.658599 | 3.568182 | false | false | false | false |
daemontus/Distributed-CTL-Model-Checker | src/main/kotlin/com/github/sybila/checker/map/mutable/ContinuousStateMap.kt | 3 | 1833 | package com.github.sybila.checker.map.mutable
import com.github.sybila.checker.MutableStateMap
/**
* A map implementation with backing array of objects.
*
* Suitable for maps that require as little overhead as possible or are expected to have a high load factor on
* a predictable interval.
*/
class ContinuousStateMap<Params : Any>(
private val from: Int,
private val to: Int,
private val default: Params
) : MutableStateMap<Params> {
private val data = arrayOfNulls<Any?>(to - from)
private var size = 0
override fun states(): Iterator<Int> = data.indices.asSequence().filter { data[it] != null }.iterator()
override fun entries(): Iterator<Pair<Int, Params>>
= data.indices.asSequence().filter {
data[it] != null
}.map {
@Suppress("UNCHECKED_CAST") //only params objects are inserted and nulls are filtered out
it.toState() to (data[it] as Params)
}.iterator()
override fun get(state: Int): Params {
@Suppress("UNCHECKED_CAST") //only params objects are inserted and contains checks for null
return if (state in this) data[state.toKey()] as Params else default
}
override fun contains(state: Int): Boolean {
val key = state.toKey()
return key >= 0 && key < data.size && data[state.toKey()] != null
}
override val sizeHint: Int
get() = size
override fun set(state: Int, value: Params) {
val key = state.toKey()
if (key < 0 || key >= data.size) throw IndexOutOfBoundsException("Map holds values [$from, $to), but index $state was given.")
if (data[key] == null) size += 1
data[key] = value
}
private fun Int.toKey(): Int = this - from
private fun Int.toState(): Int = this + from
} | gpl-3.0 | 20d0babdf108d87e3ebdc08aa2b0163c | 32.345455 | 134 | 0.624659 | 4.156463 | false | false | false | false |
AlmasB/FXGL | fxgl-gameplay/src/main/kotlin/com/almasb/fxgl/cutscene/CutsceneScene.kt | 1 | 7079 | /*
* FXGL - JavaFX Game Library. The MIT License (MIT).
* Copyright (c) AlmasB ([email protected]).
* See LICENSE for details.
*/
package com.almasb.fxgl.cutscene
import com.almasb.fxgl.animation.Animation
import com.almasb.fxgl.animation.AnimationBuilder
import com.almasb.fxgl.core.asset.AssetLoaderService
import com.almasb.fxgl.core.asset.AssetType
import com.almasb.fxgl.input.UserAction
import com.almasb.fxgl.input.view.KeyView
import com.almasb.fxgl.logging.Logger
import com.almasb.fxgl.scene.SceneService
import com.almasb.fxgl.scene.SubScene
import javafx.geometry.Point2D
import javafx.scene.image.Image
import javafx.scene.image.ImageView
import javafx.scene.input.KeyCode
import javafx.scene.paint.Color
import javafx.scene.shape.Rectangle
import javafx.scene.text.Font
import javafx.scene.text.Text
import javafx.util.Duration
import java.util.*
/**
*
* @author Almas Baimagambetov ([email protected])
*/
class CutsceneScene(private val sceneService: SceneService) : SubScene() {
private val log = Logger.get<CutsceneScene>()
private val speakers = arrayListOf<Speaker>()
private val animation: Animation<*>
private val animation2: Animation<*>
private val speakerImageView = ImageView()
private val textRPG = Text()
internal lateinit var assetLoader: AssetLoaderService
private lateinit var cutscene: Cutscene
private lateinit var onFinished: Runnable
init {
val topLine = Rectangle(sceneService.prefWidth, 150.0)
topLine.translateY = -150.0
val botLine = Rectangle(sceneService.prefWidth, 220.0)
botLine.translateY = sceneService.prefHeight
animation = AnimationBuilder()
.duration(Duration.seconds(0.5))
.translate(topLine)
.from(Point2D(0.0, -150.0))
.to(Point2D.ZERO)
.build()
animation2 = AnimationBuilder()
.duration(Duration.seconds(0.5))
.translate(botLine)
.from(Point2D(0.0, sceneService.prefHeight))
.to(Point2D(0.0, sceneService.prefHeight - 220.0))
.build()
speakerImageView.translateX = 25.0
speakerImageView.translateY = sceneService.prefHeight - 220.0 + 10
speakerImageView.opacity = 0.0
textRPG.fill = Color.WHITE
textRPG.font = Font.font(18.0)
textRPG.wrappingWidth = sceneService.prefWidth - 155.0 - 200
textRPG.translateX = 250.0
textRPG.translateY = sceneService.prefHeight - 160.0
textRPG.opacity = 0.0
val keyView = KeyView(KeyCode.ENTER, Color.GREENYELLOW, 18.0)
keyView.translateX = sceneService.prefWidth - 80.0
keyView.translateY = sceneService.prefHeight - 40.0
keyView.opacityProperty().bind(textRPG.opacityProperty())
contentRoot.children.addAll(topLine, botLine, speakerImageView, textRPG, keyView)
input.addAction(object : UserAction("Next RPG Line") {
override fun onActionBegin() {
nextLine()
}
}, KeyCode.ENTER)
}
override fun onCreate() {
animation2.onFinished = Runnable {
onOpen()
}
animation.start()
animation2.start()
}
override fun onUpdate(tpf: Double) {
animation.onUpdate(tpf)
animation2.onUpdate(tpf)
if (message.isNotEmpty()) {
textRPG.text += message.poll()
}
}
private fun endCutscene() {
speakerImageView.image = null
speakerImageView.opacity = 0.0
textRPG.opacity = 0.0
animation2.onFinished = Runnable {
sceneService.popSubScene()
onClose()
onFinished.run()
}
animation.startReverse()
animation2.startReverse()
}
fun start(cutscene: Cutscene, onFinished: Runnable) {
this.cutscene = cutscene
this.onFinished = onFinished
nextLine()
sceneService.pushSubScene(this)
}
private var currentLine = 0
private val message = ArrayDeque<Char>()
private fun nextLine() {
// do not allow to move to next line while the text animation is going
if (message.isNotEmpty())
return
if (currentLine == cutscene.lines.size) {
endCutscene()
return
}
val line = cutscene.lines[currentLine].trim()
currentLine++
try {
parseLine(line)
} catch (e: Exception) {
log.warning("Cannot parse, skipping: $line", e)
nextLine()
}
}
private fun parseLine(line: String) {
if (line.startsWith("//") || line.startsWith("#") || line.isEmpty()) {
// skip line if comment
nextLine()
return
}
for (i in line.indices) {
val c = line[i]
if (c == '.') {
// parse init
val id = line.substring(0, i)
val speaker = speakers.find { it.id == id }
?: Speaker(id).also { speakers += it }
val subLine = line.substring(i+1)
val indexEquals = subLine.indexOf('=')
val varName = subLine.substring(0, indexEquals).trim()
val varValue = subLine.substring(indexEquals+1).trim()
when (varName) {
"name" -> { speaker.name = varValue }
"image" -> { speaker.imageName = varValue }
}
nextLine()
return
}
if (c == ':') {
// parse line of text
val id = line.substring(0, i)
val text = line.substring(i+1)
text.forEach { message.addLast(it) }
val speaker = speakers.find { it.id == id }
?: Speaker(id).also { speakers += it }
textRPG.text = "${speaker.name}: "
if (speaker.imageName.isEmpty()) {
speakerImageView.image = null
} else {
val image = assetLoader.load<Image>(AssetType.IMAGE, speaker.imageName)
speakerImageView.image = image
}
return
}
}
}
private fun onOpen() {
speakerImageView.opacity = 1.0
textRPG.opacity = 1.0
}
private fun onClose() {
currentLine = 0
message.clear()
}
}
private class Speaker(
val id: String,
var name: String = "",
var imageName: String = ""
)
/**
* A cutscene is constructed using a list of lines either read from a .txt file
* or produced dynamically. The format is defined in
* https://github.com/AlmasB/FXGL/wiki/Narrative-and-Dialogue-System-(FXGL-11)#cutscenes
*/
class Cutscene(val lines: List<String>)
interface CutsceneCallback {
// fun onNextLine()
fun onCutsceneEnded() {
}
}
internal class CutsceneParser(val cutscene: Cutscene) {
} | mit | 350fd87d03d4131ed16151fb48a5cd2c | 27.207171 | 91 | 0.585393 | 4.313833 | false | false | false | false |
ethauvin/kobalt | modules/kobalt-plugin-api/src/main/kotlin/com/beust/kobalt/api/ICompilerContributor.kt | 2 | 2222 | package com.beust.kobalt.api
import com.beust.kobalt.TaskResult
interface ICompilerDescription : Comparable<ICompilerDescription> {
/**
* The name of the language compiled by this compiler.
*/
val name: String
/**
* The suffixes handled by this compiler (without the dot, e.g. "java" or "kt").
*/
val sourceSuffixes: List<String>
/**
* The trailing end of the source directory (e.g. "kotlin" in "src/main/kotlin")
*/
val sourceDirectory: String
/**
* Run the compilation based on the info.
*/
fun compile(project: Project, context: KobaltContext, info: CompilerActionInfo) : TaskResult
companion object {
val DEFAULT_PRIORITY: Int = 10
}
/**
* The priority of this compiler. Lower priority compilers are run first.
*/
val priority: Int get() = DEFAULT_PRIORITY
override fun compareTo(other: ICompilerDescription) = priority.compareTo(other.priority)
/**
* Can this compiler be passed directories or does it need individual source files?
*/
val canCompileDirectories: Boolean get() = false
}
interface ICompilerContributor : IProjectAffinity, IContributor {
fun compilersFor(project: Project, context: KobaltContext): List<ICompilerDescription>
}
interface ICompiler {
fun compile(project: Project, context: KobaltContext, info: CompilerActionInfo): TaskResult
}
class CompilerDescription(override val name: String, override val sourceDirectory: String,
override val sourceSuffixes: List<String>, val compiler: ICompiler,
override val priority: Int = ICompilerDescription.DEFAULT_PRIORITY,
override val canCompileDirectories: Boolean = false) : ICompilerDescription {
override fun compile(project: Project, context: KobaltContext, info: CompilerActionInfo): TaskResult {
val result =
if (info.sourceFiles.isNotEmpty()) {
compiler.compile(project, context, info)
} else {
context.logger.log(project.name, 2, "$name couldn't find any source files to compile")
TaskResult()
}
return result
}
override fun toString() = name + " compiler"
}
| apache-2.0 | e3efeec6a966a6d6ac5f80c776c1c864 | 31.676471 | 106 | 0.675068 | 4.600414 | false | false | false | false |
android/user-interface-samples | Haptics/app/src/main/java/com/example/android/haptics/samples/ui/HapticSamplerApp.kt | 1 | 5226 | /*
* Copyright (C) 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.haptics.samples.ui
import android.app.Application
import androidx.compose.animation.core.animateDpAsState
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.rememberScrollState
import androidx.compose.material.Icon
import androidx.compose.material.IconButton
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Scaffold
import androidx.compose.material.ScaffoldState
import androidx.compose.material.SnackbarHostState
import androidx.compose.material.TopAppBar
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Menu
import androidx.compose.material.rememberScaffoldState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.SideEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import androidx.navigation.compose.currentBackStackEntryAsState
import androidx.navigation.compose.rememberNavController
import com.example.android.haptics.samples.R
import com.example.android.haptics.samples.ui.theme.DrawerShape
import com.example.android.haptics.samples.ui.theme.HapticSamplerTheme
import com.example.android.haptics.samples.ui.theme.topAppBarBackgroundColor
import com.google.accompanist.systemuicontroller.rememberSystemUiController
import kotlinx.coroutines.launch
@Composable
fun HapticSamplerApp(application: Application) {
HapticSamplerTheme {
val navController = rememberNavController()
val navigationActions = remember(navController) {
HapticSamplerNavigation(navController)
}
val scrollState = rememberScrollState()
val coroutineScope = rememberCoroutineScope()
val systemUiController = rememberSystemUiController()
val isScrolled = scrollState.value > 0
val systemAndTopBarColor = if (isScrolled) MaterialTheme.colors.topAppBarBackgroundColor else MaterialTheme.colors.background
SideEffect {
systemUiController.setSystemBarsColor(systemAndTopBarColor)
}
val navBackStackEntry by navController.currentBackStackEntryAsState()
val currentRoute =
navBackStackEntry?.destination?.route ?: HapticSamplerDestinations.HOME_ROUTE
val snackbarHostState = remember { SnackbarHostState() }
val scaffoldState = rememberScaffoldState(snackbarHostState = snackbarHostState)
Scaffold(
scaffoldState = scaffoldState,
topBar = {
TopAppBar(
title = {},
elevation = animateDpAsState(if (isScrolled) 4.dp else 0.dp).value,
backgroundColor = systemAndTopBarColor,
navigationIcon = {
IconButton(onClick = {
coroutineScope.launch {
toggleDrawer(scaffoldState)
}
}) {
Icon(
Icons.Filled.Menu,
contentDescription = stringResource(R.string.drawer_content_description)
)
}
}
)
},
drawerShape = DrawerShape,
drawerContent = {
AppDrawer(
currentRoute = currentRoute,
navigateToHome = navigationActions.navigateToHome,
navigateToResist = navigationActions.navigateToResist,
navigateToExpand = navigationActions.navigateToExpand,
navigateToBounce = navigationActions.navigateToBounce,
navigateToWobble = navigationActions.navigateToWobble,
closeDrawer = {
coroutineScope.launch {
toggleDrawer(scaffoldState)
}
},
)
}
) {
Box() {
HapticSamplerNavGraph(
application = application,
navController = navController,
scaffoldState = scaffoldState,
scrollState = scrollState,
)
}
}
}
}
private suspend fun toggleDrawer(scaffoldState: ScaffoldState) {
scaffoldState.drawerState.apply {
if (isClosed) open() else close()
}
}
| apache-2.0 | b84c33f38bc4d675a3b03c9e5dbc3080 | 40.47619 | 133 | 0.657482 | 5.643629 | false | false | false | false |
jitsi/jibri | src/main/kotlin/org/jitsi/jibri/service/impl/SipGatewayJibriService.kt | 1 | 6384 | /*
* Copyright @ 2018 Atlassian Pty Ltd
*
* 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.jitsi.jibri.service.impl
import org.jitsi.jibri.config.XmppCredentials
import org.jitsi.jibri.selenium.CallParams
import org.jitsi.jibri.selenium.JibriSelenium
import org.jitsi.jibri.selenium.JibriSeleniumOptions
import org.jitsi.jibri.selenium.SIP_GW_URL_OPTIONS
import org.jitsi.jibri.service.ErrorSettingPresenceFields
import org.jitsi.jibri.service.JibriService
import org.jitsi.jibri.service.JibriServiceFinalizer
import org.jitsi.jibri.sipgateway.SipClientParams
import org.jitsi.jibri.sipgateway.getSipAddress
import org.jitsi.jibri.sipgateway.getSipScheme
import org.jitsi.jibri.sipgateway.pjsua.PjsuaClient
import org.jitsi.jibri.sipgateway.pjsua.PjsuaClientParams
import org.jitsi.jibri.status.ComponentState
import org.jitsi.jibri.util.ProcessFactory
import org.jitsi.jibri.util.whenever
import java.time.Duration
import java.util.concurrent.ScheduledFuture
data class SipGatewayServiceParams(
/**
* The params needed to join the web call
*/
val callParams: CallParams,
/**
* The login information needed to use when establishing the call
*/
val callLoginParams: XmppCredentials?,
/**
* The params needed for bringing a SIP client into
* the call
*/
val sipClientParams: SipClientParams
)
private const val FINALIZE_SCRIPT_LOCATION = "/opt/jitsi/jibri/finalize_sip.sh"
/**
* A [JibriService] responsible for joining both a web call
* and a SIP call, capturing the audio and video from each, and
* forwarding them to the other side.
*/
class SipGatewayJibriService(
private val sipGatewayServiceParams: SipGatewayServiceParams,
jibriSelenium: JibriSelenium? = null,
pjsuaClient: PjsuaClient? = null,
processFactory: ProcessFactory = ProcessFactory(),
private val jibriServiceFinalizer: JibriServiceFinalizer = JibriServiceFinalizeCommandRunner(
processFactory,
listOf(FINALIZE_SCRIPT_LOCATION)
)
) : StatefulJibriService("SIP gateway") {
/**
* Used for the selenium interaction
*/
private val jibriSelenium = jibriSelenium ?: JibriSelenium(
logger,
JibriSeleniumOptions(
displayName = if (sipGatewayServiceParams.callParams.displayName.isNotBlank()) {
sipGatewayServiceParams.callParams.displayName
} else if (sipGatewayServiceParams.sipClientParams.sipAddress.isNotBlank()) {
sipGatewayServiceParams.sipClientParams.sipAddress.substringBeforeLast("@")
} else {
sipGatewayServiceParams.sipClientParams.displayName
},
email = sipGatewayServiceParams.callParams.email,
callStatsUsernameOverride = sipGatewayServiceParams.callParams.callStatsUsernameOverride,
// by default we wait 30 minutes alone in the call before deciding to hangup
emptyCallTimeout = Duration.ofMinutes(30),
extraChromeCommandLineFlags = listOf("--alsa-input-device=plughw:1,1"),
enableLocalParticipantStatusChecks = true
)
)
/**
* The SIP client we'll use to connect to the SIP call (currently only a
* pjsua implementation exists)
*/
private val pjsuaClient = pjsuaClient ?: PjsuaClient(
logger,
PjsuaClientParams(sipGatewayServiceParams.sipClientParams)
)
/**
* The handle to the scheduled process monitor task, which we use to
* cancel the task
*/
private var processMonitorTask: ScheduledFuture<*>? = null
init {
registerSubComponent(JibriSelenium.COMPONENT_ID, this.jibriSelenium)
registerSubComponent(PjsuaClient.COMPONENT_ID, this.pjsuaClient)
}
/**
* Starting a [SipGatewayServiceParams] involves the following steps:
* 1) Start selenium and join the web call on display :0
* 2) Start the SIP client to join the SIP call on display :1
* There are already ffmpeg daemons running which are capturing from
* each of the displays and writing to video devices which selenium
* and pjsua will use
*/
override fun start() {
jibriSelenium.joinCall(
sipGatewayServiceParams.callParams.callUrlInfo.copy(urlParams = SIP_GW_URL_OPTIONS),
sipGatewayServiceParams.callLoginParams,
sipGatewayServiceParams.callParams.passcode
)
// when in auto-answer mode we want to start as quick as possible as
// we will be waiting for a sip call to come
if (sipGatewayServiceParams.sipClientParams.autoAnswer) {
pjsuaClient.start()
whenever(jibriSelenium).transitionsTo(ComponentState.Running) {
logger.info("Selenium joined the call")
addSipMetadataToPresence()
}
} else {
whenever(jibriSelenium).transitionsTo(ComponentState.Running) {
logger.info("Selenium joined the call, starting pjsua")
pjsuaClient.start()
addSipMetadataToPresence()
}
}
}
private fun addSipMetadataToPresence() {
try {
val sipAddress = sipGatewayServiceParams.sipClientParams.sipAddress.getSipAddress()
val sipScheme = sipGatewayServiceParams.sipClientParams.sipAddress.getSipScheme()
jibriSelenium.addToPresence("sip_address", "$sipScheme:$sipAddress")
jibriSelenium.sendPresence()
} catch (t: Throwable) {
logger.error("Error while setting fields in presence", t)
publishStatus(ComponentState.Error(ErrorSettingPresenceFields))
}
}
override fun stop() {
processMonitorTask?.cancel(false)
pjsuaClient.stop()
jibriSelenium.leaveCallAndQuitBrowser()
jibriServiceFinalizer.doFinalize()
}
}
| apache-2.0 | 9ff77a0512774e5b8f587e13074cb4f3 | 37.926829 | 101 | 0.701754 | 4.244681 | false | false | false | false |
LorittaBot/Loritta | discord/loritta-bot-common/src/main/kotlin/net/perfectdreams/loritta/morenitta/commands/vanilla/images/KnuxThrowCommand.kt | 1 | 1648 | package net.perfectdreams.loritta.morenitta.commands.vanilla.images
import net.perfectdreams.loritta.morenitta.commands.AbstractCommand
import net.perfectdreams.loritta.morenitta.commands.CommandContext
import net.perfectdreams.loritta.morenitta.gifs.KnucklesThrowGIF
import net.perfectdreams.loritta.morenitta.utils.Constants
import net.perfectdreams.loritta.morenitta.utils.MiscUtils
import net.perfectdreams.loritta.morenitta.api.commands.Command
import net.perfectdreams.loritta.common.locale.BaseLocale
import net.perfectdreams.loritta.common.locale.LocaleKeyData
import net.perfectdreams.loritta.morenitta.utils.OutdatedCommandUtils
import net.perfectdreams.loritta.morenitta.LorittaBot
class KnuxThrowCommand(loritta: LorittaBot) : AbstractCommand(loritta, "knuxthrow", listOf("knucklesthrow", "throwknux", "throwknuckles", "knucklesjogar", "knuxjogar", "jogarknuckles", "jogarknux"), category = net.perfectdreams.loritta.common.commands.CommandCategory.IMAGES) {
override fun getDescriptionKey() = LocaleKeyData("commands.command.knuxthrow.description")
override fun getExamplesKey() = Command.SINGLE_IMAGE_EXAMPLES_KEY
// TODO: Fix Usage
override fun needsToUploadFiles() = true
override suspend fun run(context: CommandContext,locale: BaseLocale) {
OutdatedCommandUtils.sendOutdatedCommandMessage(context, locale, "sonic knuxthrow")
val contextImage = context.getImageAt(0) ?: run { Constants.INVALID_IMAGE_REPLY.invoke(context); return; }
val file = KnucklesThrowGIF.getGIF(contextImage)
loritta.gifsicle.optimizeGIF(file, 50)
context.sendFile(file, "knuxthrow.gif", context.getAsMention(true))
file.delete()
}
} | agpl-3.0 | 859ac1608f9853d1b680b37a941daf11 | 50.53125 | 277 | 0.824636 | 3.952038 | false | false | false | false |
gatheringhallstudios/MHGenDatabase | app/src/main/java/com/ghstudios/android/features/armor/detail/ArmorSetDetailViewModel.kt | 1 | 3899 | package com.ghstudios.android.features.armor.detail
import android.app.Application
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.MutableLiveData
import com.ghstudios.android.data.classes.*
import com.ghstudios.android.data.classes.meta.ArmorMetadata
import com.ghstudios.android.data.DataManager
import com.ghstudios.android.util.loggedThread
import com.ghstudios.android.util.toList
/**
* A viewmodel binded to the activity containing all armor pieces,
* as well as the armor set summary itself.
*
* The armor piece tabs each have their own ArmorDetailViewModel independent of this one.
* TODO: They shouldn't, they should all use the same viewmodel to save data. Consider refactor.
*/
class ArmorSetDetailViewModel(app: Application) : AndroidViewModel(app) {
private val dataManager = DataManager.get()
var familyId = -1L
private set
val familyName get() = metadata.firstOrNull()?.familyName ?: ""
private var armorId = -1L
lateinit var metadata: List<ArmorMetadata>
/**
* A livedata containing all armor in this set paired with their piece skills
*/
var armors = MutableLiveData<List<ArmorSkillPoints>>()
/**
* A livedata containing all skills used by this set
*/
var setSkills = MutableLiveData<List<SkillTreePoints>>()
/**
* A livedata containing all setComponents required to craft this set
*/
var setComponents = MutableLiveData<List<Component>>()
/**
* Initialize this viewmodel using an armor set's family.
* Used when navigating to an armor set.
*/
fun initByFamily(familyId: Long): List<ArmorMetadata> {
if (this.familyId == familyId) {
return metadata
}
this.metadata = dataManager.getArmorSetMetadataByFamily(familyId)
this.familyId = familyId
loadArmorData()
return metadata
}
/**
* Initialize this viewmodel using an armor id, using that armor to retrieve the family.
* Used when navigating to a piece of armor.
*/
fun initByArmor(armorId: Long): List<ArmorMetadata> {
if (this.armorId == armorId) {
return metadata
}
this.metadata = dataManager.getArmorSetMetadataByArmor(armorId)
this.familyId = metadata.firstOrNull()?.family ?: -1L
loadArmorData()
return metadata
}
/**
* Internal helper that starts the data loading.
* Exists because there are multiple ways to load an armor set
*/
private fun loadArmorData(){
loggedThread("ArmorFamily Data") {
val family = metadata.first().family
// load prerequisite armor/skill data
val armorPieces = dataManager.getArmorByFamily(family)
val skillsByArmor = dataManager.queryItemToSkillTreeArrayByArmorFamily(family)
// Populate armor/skill pairs
val armorSkillPairs = armorPieces.map {
ArmorSkillPoints(armor = it, skills = skillsByArmor[it.id] ?: emptyList())
}
// Send the armor pieces so that the fragment gets it
armors.postValue(armorSkillPairs)
// Calculating skill totals to make a flat list of skill totals
val allSkillsUnmerged = skillsByArmor.values.flatten()
val mergedSkills = allSkillsUnmerged.groupBy { it.skillTree.id }.map {
val skillsToMerge = it.value
val points = skillsToMerge.sumBy { it.points }
SkillTreePoints(skillsToMerge.first().skillTree, points)
}
// Populate set skill total results so the fragment gets it
setSkills.postValue(mergedSkills)
// Load components and send to the fragment
setComponents.postValue(dataManager.queryComponentCreateByArmorFamily(family).toList { it.component })
}
}
} | mit | 191c6cc9da4d64d05e7fd82efa6fc694 | 33.513274 | 114 | 0.669659 | 4.67506 | false | false | false | false |
DevCharly/kotlin-ant-dsl | src/main/kotlin/com/devcharly/kotlin/ant/taskdefs/replace.kt | 1 | 8013 | /*
* Copyright 2016 Karl Tauber
*
* 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.devcharly.kotlin.ant
import org.apache.tools.ant.taskdefs.Replace
import org.apache.tools.ant.types.Resource
import org.apache.tools.ant.types.ResourceCollection
import org.apache.tools.ant.types.selectors.AndSelector
import org.apache.tools.ant.types.selectors.ContainsRegexpSelector
import org.apache.tools.ant.types.selectors.ContainsSelector
import org.apache.tools.ant.types.selectors.DateSelector
import org.apache.tools.ant.types.selectors.DependSelector
import org.apache.tools.ant.types.selectors.DepthSelector
import org.apache.tools.ant.types.selectors.DifferentSelector
import org.apache.tools.ant.types.selectors.ExtendSelector
import org.apache.tools.ant.types.selectors.FileSelector
import org.apache.tools.ant.types.selectors.FilenameSelector
import org.apache.tools.ant.types.selectors.MajoritySelector
import org.apache.tools.ant.types.selectors.NoneSelector
import org.apache.tools.ant.types.selectors.NotSelector
import org.apache.tools.ant.types.selectors.OrSelector
import org.apache.tools.ant.types.selectors.PresentSelector
import org.apache.tools.ant.types.selectors.SelectSelector
import org.apache.tools.ant.types.selectors.SizeSelector
import org.apache.tools.ant.types.selectors.TypeSelector
import org.apache.tools.ant.types.selectors.modifiedselector.ModifiedSelector
/******************************************************************************
DO NOT EDIT - this file was generated
******************************************************************************/
fun Ant.replace(
file: String? = null,
dir: String? = null,
encoding: String? = null,
token: String? = null,
value: String? = null,
summary: Boolean? = null,
replacefilterfile: String? = null,
replacefilterresource: String? = null,
propertyfile: String? = null,
propertyresource: String? = null,
preservelastmodified: Boolean? = null,
failonnoreplacements: Boolean? = null,
includes: String? = null,
excludes: String? = null,
defaultexcludes: Boolean? = null,
includesfile: String? = null,
excludesfile: String? = null,
casesensitive: Boolean? = null,
followsymlinks: Boolean? = null,
nested: (KReplace.() -> Unit)? = null)
{
Replace().execute("replace") { task ->
if (file != null)
task.setFile(project.resolveFile(file))
if (dir != null)
task.setDir(project.resolveFile(dir))
if (encoding != null)
task.setEncoding(encoding)
if (token != null)
task.setToken(token)
if (value != null)
task.setValue(value)
if (summary != null)
task.setSummary(summary)
if (replacefilterfile != null)
task.setReplaceFilterFile(project.resolveFile(replacefilterfile))
if (replacefilterresource != null)
task.setReplaceFilterResource(Resource(replacefilterresource))
if (propertyfile != null)
task.setPropertyFile(project.resolveFile(propertyfile))
if (propertyresource != null)
task.setPropertyResource(Resource(propertyresource))
if (preservelastmodified != null)
task.setPreserveLastModified(preservelastmodified)
if (failonnoreplacements != null)
task.setFailOnNoReplacements(failonnoreplacements)
if (includes != null)
task.setIncludes(includes)
if (excludes != null)
task.setExcludes(excludes)
if (defaultexcludes != null)
task.setDefaultexcludes(defaultexcludes)
if (includesfile != null)
task.setIncludesfile(project.resolveFile(includesfile))
if (excludesfile != null)
task.setExcludesfile(project.resolveFile(excludesfile))
if (casesensitive != null)
task.setCaseSensitive(casesensitive)
if (followsymlinks != null)
task.setFollowSymlinks(followsymlinks)
if (nested != null)
nested(KReplace(task))
}
}
class KReplace(override val component: Replace) :
IFileSelectorNested,
IResourceCollectionNested,
ISelectSelectorNested,
IAndSelectorNested,
IOrSelectorNested,
INotSelectorNested,
INoneSelectorNested,
IMajoritySelectorNested,
IDateSelectorNested,
ISizeSelectorNested,
IFilenameSelectorNested,
IExtendSelectorNested,
IContainsSelectorNested,
IPresentSelectorNested,
IDepthSelectorNested,
IDependSelectorNested,
IContainsRegexpSelectorNested,
IDifferentSelectorNested,
ITypeSelectorNested,
IModifiedSelectorNested
{
fun replacetoken(expandproperties: Boolean? = null, nested: (KNestedString.() -> Unit)? = null) {
component.createReplaceToken().apply {
_init(expandproperties, nested)
}
}
fun replacevalue(expandproperties: Boolean? = null, nested: (KNestedString.() -> Unit)? = null) {
component.createReplaceValue().apply {
_init(expandproperties, nested)
}
}
fun replacefilter(token: String? = null, value: String? = null, property: String? = null, nested: (KReplacefilter.() -> Unit)? = null) {
component.createReplacefilter().apply {
_init(token, value, property, nested)
}
}
fun include(name: String? = null, If: String? = null, unless: String? = null) {
component.createInclude().apply {
_init(name, If, unless)
}
}
fun includesfile(name: String? = null, If: String? = null, unless: String? = null) {
component.createIncludesFile().apply {
_init(name, If, unless)
}
}
fun exclude(name: String? = null, If: String? = null, unless: String? = null) {
component.createExclude().apply {
_init(name, If, unless)
}
}
fun excludesfile(name: String? = null, If: String? = null, unless: String? = null) {
component.createExcludesFile().apply {
_init(name, If, unless)
}
}
fun patternset(includes: String? = null, excludes: String? = null, includesfile: String? = null, excludesfile: String? = null, nested: (KPatternSet.() -> Unit)? = null) {
component.createPatternSet().apply {
component.project.setProjectReference(this)
_init(includes, excludes, includesfile, excludesfile, nested)
}
}
override fun _addFileSelector(value: FileSelector) = component.add(value)
override fun _addResourceCollection(value: ResourceCollection) = component.addConfigured(value)
override fun _addSelectSelector(value: SelectSelector) = component.addSelector(value)
override fun _addAndSelector(value: AndSelector) = component.addAnd(value)
override fun _addOrSelector(value: OrSelector) = component.addOr(value)
override fun _addNotSelector(value: NotSelector) = component.addNot(value)
override fun _addNoneSelector(value: NoneSelector) = component.addNone(value)
override fun _addMajoritySelector(value: MajoritySelector) = component.addMajority(value)
override fun _addDateSelector(value: DateSelector) = component.addDate(value)
override fun _addSizeSelector(value: SizeSelector) = component.addSize(value)
override fun _addFilenameSelector(value: FilenameSelector) = component.addFilename(value)
override fun _addExtendSelector(value: ExtendSelector) = component.addCustom(value)
override fun _addContainsSelector(value: ContainsSelector) = component.addContains(value)
override fun _addPresentSelector(value: PresentSelector) = component.addPresent(value)
override fun _addDepthSelector(value: DepthSelector) = component.addDepth(value)
override fun _addDependSelector(value: DependSelector) = component.addDepend(value)
override fun _addContainsRegexpSelector(value: ContainsRegexpSelector) = component.addContainsRegexp(value)
override fun _addDifferentSelector(value: DifferentSelector) = component.addDifferent(value)
override fun _addTypeSelector(value: TypeSelector) = component.addType(value)
override fun _addModifiedSelector(value: ModifiedSelector) = component.addModified(value)
}
| apache-2.0 | bdd380615d60d23b7b9dc922e113e34f | 40.092308 | 171 | 0.755148 | 3.740896 | false | false | false | false |
mastizada/focus-android | app/src/main/java/org/mozilla/focus/architecture/NonNullLiveData.kt | 4 | 1351 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
package org.mozilla.focus.architecture
import android.arch.lifecycle.LiveData
/**
* A LiveData implementation with an initial value and that does not allow null values.
*/
open class NonNullLiveData<T>(initialValue: T) : LiveData<T>() {
init {
value = initialValue
}
/**
* Returns the current (non-null) value. Note that calling this method on a background thread
* does not guarantee that the latest value set will be received.
*/
override fun getValue(): T = super.getValue() ?: throw IllegalStateException("Value is null")
/**
* Posts a task to a main thread to set the given (non null) value.
*/
override fun postValue(value: T?) {
if (value == null) {
throw IllegalArgumentException("Value cannot be null")
}
super.postValue(value)
}
/**
* Sets the (non-null) value. If there are active observers, the value will be dispatched to them.
*/
override fun setValue(value: T?) {
if (value == null) {
throw IllegalArgumentException("Value cannot be null")
}
super.setValue(value)
}
}
| mpl-2.0 | 88525055b69c7d11cf0283977e5db504 | 31.166667 | 102 | 0.643227 | 4.288889 | false | false | false | false |
Magneticraft-Team/Magneticraft | src/main/kotlin/com/cout970/magneticraft/features/computers/TileEntities.kt | 2 | 6151 | package com.cout970.magneticraft.features.computers
import com.cout970.magneticraft.api.internal.energy.ElectricNode
import com.cout970.magneticraft.misc.*
import com.cout970.magneticraft.misc.block.get
import com.cout970.magneticraft.misc.block.getOrientation
import com.cout970.magneticraft.misc.inventory.Inventory
import com.cout970.magneticraft.misc.inventory.InventoryCapabilityFilter
import com.cout970.magneticraft.misc.tileentity.DoNotRemove
import com.cout970.magneticraft.systems.computer.*
import com.cout970.magneticraft.systems.config.Config
import com.cout970.magneticraft.systems.tileentities.TileBase
import com.cout970.magneticraft.systems.tilemodules.*
import net.minecraft.block.state.IBlockState
import net.minecraft.nbt.NBTTagCompound
import net.minecraft.util.EnumFacing
import net.minecraft.util.ITickable
import net.minecraft.util.math.BlockPos
import net.minecraft.world.World
/**
* Created by cout970 on 2017/07/07.
*/
@RegisterTileEntity("computer")
class TileComputer : TileBase(), ITickable {
val facing: EnumFacing get() = getBlockState().getOrientation()
val inventory = Inventory(2)
val invModule = ModuleInventory(inventory)
val monitor = DeviceMonitor()
val keyboard = DeviceKeyboard()
val floppyDrive1Module = ModuleFloppyDrive(ref, inventory, 0)
val floppyDrive2Module = ModuleFloppyDrive(ref, inventory, 1)
val networkCard = DeviceNetworkCard(ref)
val redstoneSensor = DeviceRedstoneSensor(ref)
val computerParts = ModuleComputerDevices(monitor, keyboard, networkCard, redstoneSensor)
val computerModule = ModuleComputer(
internalDevices = mutableMapOf(
0x00 to monitor,
0x01 to floppyDrive1Module.drive,
0x02 to keyboard,
0x03 to networkCard,
0x04 to redstoneSensor,
0x05 to floppyDrive2Module.drive
)
)
init {
initModules(computerModule, invModule, computerParts, floppyDrive1Module, floppyDrive2Module)
}
@DoNotRemove
override fun update() {
super.update()
}
override fun saveToPacket(): NBTTagCompound {
val moduleNbts = container.modules.filter { it !is ModuleComputer }.map { it.serializeNBT() }
if (moduleNbts.isNotEmpty()) {
return newNbt {
list("_modules") {
moduleNbts.forEach { appendTag(it) }
}
}
}
return NBTTagCompound()
}
override fun loadFromPacket(nbt: NBTTagCompound) {
if (nbt.hasKey("_modules")) {
val list = nbt.getList("_modules")
container.modules.filter { it !is ModuleComputer }.forEachIndexed { index, module ->
module.deserializeNBT(list.getTagCompound(index))
}
}
}
}
@RegisterTileEntity("mining_robot")
class TileMiningRobot : TileBase(), ITickable {
val orientation
get() = getBlockState()[Blocks.PROPERTY_ROBOT_ORIENTATION] ?: Blocks.RobotOrientation.NORTH
val inventory = Inventory(18)
val node = ElectricNode(ref, capacity = 0.5)
val storageInventory = InventoryCapabilityFilter(
inventory = inventory,
inputSlots = (0..15).toList(),
outputSlots = (0..15).toList()
)
val invModule = ModuleInventory(
inventory = inventory,
capabilityFilter = { storageInventory })
val energyModule = ModuleElectricity(listOf(node))
val energyStorage = ModuleInternalStorage(
mainNode = node,
initialCapacity = 50_000,
initialMaxChargeSpeed = 50.0,
initialUpperVoltageLimit = ElectricConstants.TIER_1_MACHINES_MIN_VOLTAGE + 5
)
val itemChargeModule = ModuleChargeItems(
inventory = inventory,
storage = energyStorage,
chargeSlot = -1,
dischargeSlot = 17,
transferRate = Config.blockBatteryTransferRate
)
val floppyDriveModule = ModuleFloppyDrive(ref = ref, inventory = inventory, slot = 16)
val keyboard = DeviceKeyboard()
val monitor = DeviceMonitor()
val networkCard = DeviceNetworkCard(ref)
val redstoneSensor = DeviceRedstoneSensor(ref)
val inventorySensor = DeviceInventorySensor(ref, inventory)
val computerParts = ModuleComputerDevices(monitor, keyboard, networkCard, redstoneSensor, inventorySensor)
val robotControlModule = ModuleRobotControl(
ref = ref,
inventory = storageInventory,
storage = energyStorage,
node = node,
orientationGetter = { orientation },
orientationSetter = { world.setBlockState(pos, it.getBlockState(Blocks.miningRobot)) }
)
val computerModule = ModuleComputer(
internalDevices = mutableMapOf(
0x00 to monitor,
0x01 to floppyDriveModule.drive,
0x02 to keyboard,
0x03 to networkCard,
0x04 to robotControlModule.device,
0x05 to redstoneSensor,
0x06 to inventorySensor
)
)
init {
initModules(computerModule, invModule, computerParts, floppyDriveModule, robotControlModule,
energyModule, energyStorage, itemChargeModule)
}
@DoNotRemove
override fun update() {
super.update()
}
override fun shouldRefresh(world: World, pos: BlockPos, oldState: IBlockState, newSate: IBlockState): Boolean {
return oldState.block != newSate.block
}
override fun saveToPacket(): NBTTagCompound {
val moduleNbts = container.modules.filter { it !is ModuleComputer }.map { it.serializeNBT() }
if (moduleNbts.isNotEmpty()) {
return newNbt {
list("_modules") {
moduleNbts.forEach { appendTag(it) }
}
}
}
return NBTTagCompound()
}
override fun loadFromPacket(nbt: NBTTagCompound) {
if (nbt.hasKey("_modules")) {
val list = nbt.getList("_modules")
container.modules.filter { it !is ModuleComputer }.forEachIndexed { index, module ->
module.deserializeNBT(list.getTagCompound(index))
}
}
}
}
| gpl-2.0 | 56cd552f5fbff043f12375bacc248abb | 32.796703 | 115 | 0.668509 | 4.399857 | false | false | false | false |
WillFK/fuckoffer | app/src/main/java/com/fk/fuckoffer/ui/main/MainActivity.kt | 1 | 1893 | package com.fk.fuckoffer.ui.main
import android.content.Intent
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.support.v7.widget.LinearLayoutManager
import com.fk.fuckoffer.R
import com.fk.fuckoffer.domain.model.Operation
import com.fk.fuckoffer.injection.InjectionHelper
import com.fk.fuckoffer.ui.field.FieldFormActivity
import io.reactivex.android.schedulers.AndroidSchedulers
import kotlinx.android.synthetic.main.activity_main.*
import javax.inject.Inject
class MainActivity : AppCompatActivity(), MainView {
@Inject
lateinit var presenter: MainPresenter
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
setup()
}
private fun setup() {
InjectionHelper.buildViewComponent().inject(this)
presenter.attach(this)
setupUi()
presenter.loadOperations()
}
private fun setupUi() {
setTitle(R.string.offences)
mainRecycler.layoutManager = LinearLayoutManager(this)
val adapter = MainAdapter(emptyList())
adapter.operationObservable()
.observeOn(AndroidSchedulers.mainThread())
.subscribe { gotoFieldForm(it) }
mainRecycler.adapter = adapter
}
private fun gotoFieldForm(operation: Operation) {
val intent = Intent(this, FieldFormActivity::class.java)
intent.putExtra(FieldFormActivity.PARAM_OPERATION_NAME, operation.name)
intent.putExtra(FieldFormActivity.PARAM_FIELD_INDEX, 0)
startActivity(intent)
}
private fun getAdapter() = mainRecycler.adapter as? MainAdapter
override fun displayOperations(displayables: List<MainDisplayable>) {
getAdapter()?.let {
it.displayables = displayables
it.notifyDataSetChanged()
}
}
}
| mit | 8e8d8d9bcc66bb37eef373968da675fa | 31.637931 | 79 | 0.711569 | 4.685644 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.