repo_name
stringlengths 7
81
| path
stringlengths 6
242
| copies
stringclasses 55
values | size
stringlengths 2
6
| content
stringlengths 55
737k
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 5.44
99.8
| line_max
int64 15
979
| alpha_frac
float64 0.3
0.91
| ratio
float64 2
9.93
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
Jakeler/UT61E-Toolkit | Application/src/main/java/jk/ut61eTool/UI.kt | 1 | 1432 | package jk.ut61eTool
import android.view.View
import com.jake.UT61e_decoder
import jk.ut61eTool.databinding.LogActivityBinding
class UI(val binding: LogActivityBinding) {
var logger : DataLogger? = null
init {
binding.logSwitch.setOnCheckedChangeListener { _, checked ->
if (checked) {
logger?.startLog()
} else {
logger?.stopLog()
}
}
}
fun update(ut61e: UT61e_decoder) {
binding.dataValue.text = ut61e.toString()
enableTextView(binding.Neg, ut61e.getValue() < 0)
enableTextView(binding.OL, ut61e.isOL)
if (ut61e.isFreq || ut61e.isDuty) {
enableTextView(binding.FreqDuty, true)
enableTextView(binding.ACDC, false)
binding.FreqDuty.text = when {
ut61e.isDuty -> "Duty"
ut61e.isFreq -> "Freq."
else -> ""
}
} else {
enableTextView(binding.FreqDuty, false)
enableTextView(binding.ACDC, true)
binding.ACDC.text = when {
ut61e.isDC -> "DC"
ut61e.isAC -> "AC"
else -> {
enableTextView(binding.ACDC, false)
""
}
}
}
}
private fun enableTextView(v: View, enabled: Boolean) {
v.alpha = if (enabled) 1.0f else 0.2f
}
} | apache-2.0 | f972568ddbe99fded6a720870f89c042 | 27.098039 | 68 | 0.519553 | 4.022472 | false | false | false | false |
laminr/aeroknow | app/src/main/java/biz/eventually/atpl/ui/source/SourceActivity.kt | 1 | 3239 | package biz.eventually.atpl.ui.source
import android.arch.lifecycle.Observer
import android.arch.lifecycle.ViewModelProviders
import android.os.Bundle
import android.support.annotation.StringRes
import android.view.View
import android.widget.AdapterView
import biz.eventually.atpl.AtplApplication
import biz.eventually.atpl.BuildConfig
import biz.eventually.atpl.R
import biz.eventually.atpl.common.IntentIdentifier
import biz.eventually.atpl.data.NetworkStatus
import biz.eventually.atpl.data.db.Source
import biz.eventually.atpl.ui.BaseComponentActivity
import biz.eventually.atpl.ui.ViewModelFactory
import biz.eventually.atpl.ui.subject.SubjectActivity
import kotlinx.android.synthetic.main.activity_source.*
import org.jetbrains.anko.startActivity
import timber.log.Timber
import javax.inject.Inject
class SourceActivity : BaseComponentActivity() {
private var mAdapter: SourceAdapter? = null
@Inject
lateinit var sourceViewModelFactory: ViewModelFactory<SourceRepository>
private lateinit var viewModel: SourceViewModel
private lateinit var menuDecorator: MenuDecorator
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
Timber.i("Starting SourceActivity")
AtplApplication.component.inject(this)
setContentView(R.layout.activity_source)
// handling menu screen
menuDecorator = MenuDecorator(this)
viewModel = ViewModelProviders.of(this, sourceViewModelFactory).get(SourceViewModel::class.java)
app_version.text = "v${BuildConfig.VERSION_APP}"
// font for the title
source_welcome.typeface = AtplApplication.tangerine
viewModel.sources.observe(this, Observer<List<Source>> {
if (it?.isEmpty() == true) {
showHideError(View.VISIBLE)
} else {
showHideError(View.GONE)
displayData(it)
}
})
viewModel.networkStatus.observe(this, Observer<NetworkStatus> {
when (it) {
NetworkStatus.LOADING -> source_rotating.start()
else -> source_rotating.stop()
}
})
source_refresh.setOnClickListener { loadData() }
}
private fun displayData(sources: List<Source>?): Unit {
sources?.apply {
mAdapter = SourceAdapter(this@SourceActivity, sources)
source_listview.adapter = mAdapter
source_listview.onItemClickListener = AdapterView.OnItemClickListener { _, _, position, _ ->
val source = get(position)
source.idWeb?.let {
startActivity<SubjectActivity>(
IntentIdentifier.SOURCE_ID to it,
IntentIdentifier.SOURCE_NAME to source.name
)
}
}
}
}
private fun loadData() {
viewModel.refreshData()
}
private fun showHideError(show: Int) {
source_error.visibility = show
source_refresh.visibility = show
}
private fun onError(@StringRes messageId: Int): Unit {
showHideError(View.VISIBLE)
source_error.text = getString(messageId)
}
}
| mit | 30bc58e07caabcc4413a5cf26d9bf83b | 30.446602 | 104 | 0.665638 | 4.878012 | false | false | false | false |
k9mail/k-9 | app/core/src/main/java/com/fsck/k9/notification/LockScreenNotificationCreator.kt | 2 | 2740 | package com.fsck.k9.notification
import android.app.Notification
import androidx.core.app.NotificationCompat
internal class LockScreenNotificationCreator(
private val notificationHelper: NotificationHelper,
private val resourceProvider: NotificationResourceProvider
) {
fun configureLockScreenNotification(
builder: NotificationCompat.Builder,
baseNotificationData: BaseNotificationData
) {
when (baseNotificationData.lockScreenNotificationData) {
LockScreenNotificationData.None -> {
builder.setVisibility(NotificationCompat.VISIBILITY_SECRET)
}
LockScreenNotificationData.AppName -> {
builder.setVisibility(NotificationCompat.VISIBILITY_PRIVATE)
}
LockScreenNotificationData.Public -> {
builder.setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
}
is LockScreenNotificationData.SenderNames -> {
val publicNotification = createPublicNotificationWithSenderList(baseNotificationData)
builder.setPublicVersion(publicNotification)
}
LockScreenNotificationData.MessageCount -> {
val publicNotification = createPublicNotificationWithNewMessagesCount(baseNotificationData)
builder.setPublicVersion(publicNotification)
}
}
}
private fun createPublicNotificationWithSenderList(baseNotificationData: BaseNotificationData): Notification {
val notificationData = baseNotificationData.lockScreenNotificationData as LockScreenNotificationData.SenderNames
return createPublicNotification(baseNotificationData)
.setContentText(notificationData.senderNames)
.build()
}
private fun createPublicNotificationWithNewMessagesCount(baseNotificationData: BaseNotificationData): Notification {
return createPublicNotification(baseNotificationData)
.setContentText(baseNotificationData.accountName)
.build()
}
private fun createPublicNotification(baseNotificationData: BaseNotificationData): NotificationCompat.Builder {
val account = baseNotificationData.account
val newMessagesCount = baseNotificationData.newMessagesCount
val title = resourceProvider.newMessagesTitle(newMessagesCount)
return notificationHelper.createNotificationBuilder(account, NotificationChannelManager.ChannelType.MESSAGES)
.setSmallIcon(resourceProvider.iconNewMail)
.setColor(baseNotificationData.color)
.setNumber(newMessagesCount)
.setContentTitle(title)
.setCategory(NotificationCompat.CATEGORY_EMAIL)
}
}
| apache-2.0 | 3e175c0a4cdceb25b2766e8488e4c73d | 44.666667 | 120 | 0.725182 | 7.248677 | false | false | false | false |
blindpirate/gradle | subprojects/configuration-cache/src/main/kotlin/org/gradle/configurationcache/serialization/beans/BeanSchema.kt | 1 | 6357 | /*
* Copyright 2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gradle.configurationcache.serialization.beans
import org.gradle.api.DefaultTask
import org.gradle.api.Task
import org.gradle.api.artifacts.Configuration
import org.gradle.api.file.SourceDirectorySet
import org.gradle.api.internal.ConventionTask
import org.gradle.api.internal.IConventionAware
import org.gradle.api.internal.TaskInternal
import org.gradle.configurationcache.problems.DisableConfigurationCacheFieldTypeCheck
import org.gradle.configurationcache.problems.PropertyKind
import org.gradle.configurationcache.serialization.MutableIsolateContext
import org.gradle.configurationcache.serialization.Workarounds
import org.gradle.configurationcache.serialization.logUnsupported
import org.gradle.internal.instantiation.generator.AsmBackedClassGenerator
import org.gradle.internal.reflect.ClassInspector
import java.lang.reflect.AccessibleObject
import java.lang.reflect.Field
import java.lang.reflect.Modifier.isStatic
import java.lang.reflect.Modifier.isTransient
import kotlin.reflect.KClass
internal
val unsupportedFieldDeclaredTypes = listOf(
Configuration::class,
SourceDirectorySet::class
)
internal
fun relevantStateOf(beanType: Class<*>): List<RelevantField> =
when (IConventionAware::class.java.isAssignableFrom(beanType)) {
true -> applyConventionMappingTo(beanType, relevantFieldsOf(beanType))
else -> relevantFieldsOf(beanType)
}
private
fun relevantFieldsOf(beanType: Class<*>) =
relevantTypeHierarchyOf(beanType)
.flatMap(Class<*>::relevantFields)
.onEach(Field::makeAccessible)
.map { RelevantField(it, unsupportedFieldTypeFor(it)) }
.toList()
private
fun applyConventionMappingTo(taskType: Class<*>, relevantFields: List<RelevantField>): List<RelevantField> =
conventionAwareFieldsOf(taskType).toMap().let { flags ->
relevantFields.map { relevantField ->
relevantField.run {
flags[field]?.let { flagField ->
copy(isExplicitValueField = flagField.apply(Field::makeAccessible))
}
} ?: relevantField
}
}
/**
* Returns every property backing field for which a corresponding convention mapping flag field also exists.
*
* The convention mapping flag field is a Boolean field injected by [AsmBackedClassGenerator] in order to capture
* whether a convention mapped property has been explicitly set or not.
*/
private
fun conventionAwareFieldsOf(beanType: Class<*>): Sequence<Pair<Field, Field>> =
ClassInspector.inspect(beanType).let { details ->
details.properties.asSequence().mapNotNull { property ->
property.backingField?.let { backingField ->
val flagFieldName = AsmBackedClassGenerator.propFieldName(backingField.name)
details
.instanceFields
.firstOrNull { field ->
field.declaringClass == beanType
&& field.name == flagFieldName
&& field.type == java.lang.Boolean.TYPE
}?.let { flagField ->
backingField to flagField
}
}
}
}
internal
data class RelevantField(
val field: Field,
val unsupportedFieldType: KClass<*>?,
/**
* Boolean flag field injected by [AsmBackedClassGenerator] to capture
* whether a convention mapped property has been explicitly set or not.
*/
val isExplicitValueField: Field? = null
)
internal
fun MutableIsolateContext.reportUnsupportedFieldType(
unsupportedType: KClass<*>,
action: String,
fieldName: String,
fieldValue: Any? = null
) {
withPropertyTrace(PropertyKind.Field, fieldName) {
if (fieldValue == null) logUnsupported(action, unsupportedType)
else logUnsupported(action, unsupportedType, fieldValue::class.java)
}
}
internal
fun unsupportedFieldTypeFor(field: Field): KClass<*>? =
field.takeUnless {
field.isAnnotationPresent(DisableConfigurationCacheFieldTypeCheck::class.java)
}?.let {
unsupportedFieldDeclaredTypes
.firstOrNull { it.java.isAssignableFrom(field.type) }
}
private
fun relevantTypeHierarchyOf(beanType: Class<*>) = sequence<Class<*>> {
var current: Class<*>? = beanType
while (current != null) {
if (isRelevantDeclaringClass(current)) {
yield(current)
}
current = current.superclass
}
}
private
fun isRelevantDeclaringClass(declaringClass: Class<*>): Boolean =
declaringClass !in irrelevantDeclaringClasses
private
val irrelevantDeclaringClasses = setOf(
Object::class.java,
Task::class.java,
TaskInternal::class.java,
DefaultTask::class.java,
ConventionTask::class.java
)
private
val Class<*>.relevantFields: Sequence<Field>
get() = declaredFields.asSequence()
.filterNot { field ->
field.isStatic
|| field.isTransient
|| Workarounds.isIgnoredBeanField(field)
}.filter { field ->
isNotAbstractTaskField(field)
|| field.name in abstractTaskRelevantFields
}
.sortedBy { it.name }
@Suppress("deprecation")
private
fun isNotAbstractTaskField(field: Field) =
field.declaringClass != org.gradle.api.internal.AbstractTask::class.java
private
val Field.isTransient
get() = isTransient(modifiers)
private
val Field.isStatic
get() = isStatic(modifiers)
private
val abstractTaskRelevantFields = listOf(
"actions",
"enabled",
"timeout",
"onlyIfSpec"
)
internal
fun AccessibleObject.makeAccessible() {
@Suppress("deprecation")
if (!isAccessible) isAccessible = true
}
| apache-2.0 | aaf84d473dc55f8d249d2f170b983ad8 | 29.416268 | 113 | 0.699229 | 4.71238 | false | false | false | false |
JetBrains/ideavim | vim-engine/src/main/kotlin/com/maddyhome/idea/vim/vimscript/model/commands/RepeatCommand.kt | 1 | 1927 | /*
* Copyright 2003-2022 The IdeaVim authors
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE.txt file or at
* https://opensource.org/licenses/MIT.
*/
package com.maddyhome.idea.vim.vimscript.model.commands
import com.maddyhome.idea.vim.api.ExecutionContext
import com.maddyhome.idea.vim.api.VimCaret
import com.maddyhome.idea.vim.api.VimEditor
import com.maddyhome.idea.vim.api.injector
import com.maddyhome.idea.vim.command.OperatorArguments
import com.maddyhome.idea.vim.ex.ExException
import com.maddyhome.idea.vim.ex.ranges.Ranges
import com.maddyhome.idea.vim.vimscript.model.ExecutionResult
/**
* see "h :@"
*/
data class RepeatCommand(val ranges: Ranges, val argument: String) : Command.ForEachCaret(ranges, argument) {
override val argFlags = flags(RangeFlag.RANGE_OPTIONAL, ArgumentFlag.ARGUMENT_REQUIRED, Access.SELF_SYNCHRONIZED)
private var lastArg = ':'
@Throws(ExException::class)
override fun processCommand(
editor: VimEditor,
caret: VimCaret,
context: ExecutionContext,
operatorArguments: OperatorArguments
): ExecutionResult {
var arg = argument[0]
if (arg == '@') arg = lastArg
lastArg = arg
val line = getLine(editor, caret)
caret.moveToOffset(
injector.motion.moveCaretToLineWithSameColumn(editor, line, editor.primaryCaret())
)
if (arg == ':') {
return if (injector.vimscriptExecutor.executeLastCommand(
editor,
context
)
) ExecutionResult.Success else ExecutionResult.Error
}
val reg = injector.registerGroup.getPlaybackRegister(arg) ?: return ExecutionResult.Error
val text = reg.text ?: return ExecutionResult.Error
injector.vimscriptExecutor.execute(
text,
editor,
context,
skipHistory = false,
indicateErrors = true,
this.vimContext
)
return ExecutionResult.Success
}
}
| mit | e76ed1b936cd1b11414f4f003e64d403 | 28.646154 | 115 | 0.720291 | 4.244493 | false | false | false | false |
michaelkourlas/voipms-sms-client | voipms-sms/src/main/kotlin/net/kourlas/voipms_sms/conversations/ConversationsRecyclerViewAdapter.kt | 1 | 26501 | /*
* VoIP.ms SMS
* Copyright (C) 2015-2021 Michael Kourlas
*
* 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 net.kourlas.voipms_sms.conversations
import android.graphics.Bitmap
import android.graphics.Typeface
import android.text.SpannableString
import android.text.SpannableStringBuilder
import android.text.Spanned
import android.text.style.BackgroundColorSpan
import android.text.style.ForegroundColorSpan
import android.text.style.StyleSpan
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.*
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import kotlinx.coroutines.runBlocking
import net.kourlas.voipms_sms.BuildConfig
import net.kourlas.voipms_sms.R
import net.kourlas.voipms_sms.database.Database
import net.kourlas.voipms_sms.demo.getConversationsDemoMessages
import net.kourlas.voipms_sms.preferences.getActiveDid
import net.kourlas.voipms_sms.preferences.getDids
import net.kourlas.voipms_sms.sms.Message
import net.kourlas.voipms_sms.utils.*
import java.util.*
/**
* Recycler view adapter used by [ConversationsActivity] and
* [ConversationsArchivedActivity].
*
* @param activity The source [ConversationsActivity] or
* [ConversationsArchivedActivity].
* @param recyclerView The recycler view used by the activity.
* @param layoutManager The layout manager used by the recycler view.
*/
class ConversationsRecyclerViewAdapter<T>(
private val activity: T,
private val recyclerView: RecyclerView,
private val layoutManager: LinearLayoutManager
) :
RecyclerView.Adapter<ConversationsRecyclerViewAdapter<T>.ConversationViewHolder>(),
Filterable,
Iterable<ConversationsRecyclerViewAdapter<T>.ConversationItem>
where T : AppCompatActivity, T : View.OnClickListener, T : View.OnLongClickListener {
// List of items shown by the adapter; the index of each item
// corresponds to the location of each item in the adapter
private val _conversationItems = mutableListOf<ConversationItem>()
val conversationItems: List<ConversationItem>
get() = _conversationItems
// Current and previous filter constraint
private var currConstraint: String = ""
private var prevConstraint: String = ""
// Caches
private val contactNameCache = mutableMapOf<String, String>()
private val contactBitmapCache = mutableMapOf<String, Bitmap>()
override fun onCreateViewHolder(
parent: ViewGroup,
viewType: Int
): ConversationViewHolder {
// There is only one item view type
val itemView = LayoutInflater.from(parent.context)
.inflate(R.layout.conversations_item, parent, false)
return ConversationViewHolder(itemView)
}
override fun onBindViewHolder(
holder: ConversationViewHolder,
position: Int
) {
// Set up view to match message at position
updateViewHolderContactBadge(holder, position)
updateViewHolderContactText(holder, position)
updateViewHolderMessageText(holder, position)
updateViewHolderDateText(holder, position)
}
/**
* Changes the contact badge to a check mark, a photo, or a material design
* letter.
*
* @param holder The message view holder to use.
* @param position The position of the view in the adapter.
*/
fun updateViewHolderContactBadge(
holder: ConversationViewHolder,
position: Int
) {
val conversationItem = conversationItems[position]
val message = conversationItem.message
holder.viewSwitcher.displayedChild =
if (conversationItem.checked) 1 else 0
if (!conversationItem.checked) {
holder.contactBadge.assignContactFromPhone(message.contact, true)
holder.contactBadge.setImageBitmap(
conversationItem.contactBitmap
)
}
}
/**
* Displays the contact name or phone number associated with the
* conversation on the view holder. Selects and highlights part of the
* text if a filter is configured. Marks text as bold if unread.
*
* @param holder The message view holder to use.
* @param position The position of the view in the adapter.
*/
private fun updateViewHolderContactText(
holder: ConversationViewHolder,
position: Int
) {
val conversationItem = conversationItems[position]
val message = conversationItem.message
val contactTextBuilder = SpannableStringBuilder()
contactTextBuilder.append(
conversationItem.contactName ?: getFormattedPhoneNumber(
conversationItem.message.contact
)
)
// Highlight text that matches filter
if (currConstraint != "") {
val index = contactTextBuilder.toString()
.lowercase(Locale.getDefault())
.indexOf(currConstraint.lowercase(Locale.getDefault()))
if (index != -1) {
contactTextBuilder.setSpan(
BackgroundColorSpan(
ContextCompat.getColor(activity, R.color.highlight)
),
index,
index + currConstraint.length,
SpannableString.SPAN_INCLUSIVE_EXCLUSIVE
)
contactTextBuilder.setSpan(
ForegroundColorSpan(
ContextCompat.getColor(
activity, android.R.color.black
)
),
index,
index + currConstraint.length,
SpannableString.SPAN_INCLUSIVE_EXCLUSIVE
)
}
}
holder.contactTextView.text = contactTextBuilder
// Mark text as bold if unread
if (message.isUnread) {
holder.contactTextView.setTypeface(null, Typeface.BOLD)
} else {
holder.contactTextView.setTypeface(null, Typeface.NORMAL)
}
}
/**
* Displays the text of the displayed message of the conversation on the
* view holder. Selects and highlights part of the text if a filter is
* configured. Marks text as bold if unread.
*
* @param holder The message view holder to use.
* @param position The position of the view in the adapter.
*/
private fun updateViewHolderMessageText(
holder: ConversationViewHolder,
position: Int
) {
val conversationItem = conversationItems[position]
val message = conversationItem.message
val messageTextBuilder = SpannableStringBuilder()
// Highlight text that matches filter
val index = message.text.lowercase(Locale.getDefault()).indexOf(
currConstraint.lowercase(Locale.getDefault())
)
if (currConstraint != "" && index != -1) {
var nonMessageOffset = index
if (message.isOutgoing) {
// Preface with "You: " if outgoing
val youStr = activity.getString(
R.string.conversations_message_you
) + " "
messageTextBuilder.insert(0, youStr)
nonMessageOffset += youStr.length
}
// If match is in the middle of the string, show partial string
var substringOffset = index - 20
if (substringOffset > 0) {
messageTextBuilder.append("…")
nonMessageOffset += 1
while (message.text[substringOffset] != ' '
&& substringOffset < index - 1
) {
substringOffset += 1
}
substringOffset += 1
} else {
substringOffset = 0
}
messageTextBuilder.append(message.text.substring(substringOffset))
messageTextBuilder.setSpan(
BackgroundColorSpan(
ContextCompat.getColor(
activity,
R.color.highlight
)
),
nonMessageOffset - substringOffset,
nonMessageOffset - substringOffset + currConstraint.length,
SpannableString.SPAN_INCLUSIVE_EXCLUSIVE
)
messageTextBuilder.setSpan(
ForegroundColorSpan(
ContextCompat.getColor(
activity, android.R.color.black
)
),
nonMessageOffset - substringOffset,
nonMessageOffset - substringOffset + currConstraint.length,
SpannableString.SPAN_INCLUSIVE_EXCLUSIVE
)
} else {
if (message.isOutgoing) {
// Preface with "You: " if outgoing
messageTextBuilder.append(
activity.getString(
R.string.conversations_message_you
)
)
messageTextBuilder.append(" ")
}
messageTextBuilder.append(message.text)
}
holder.messageTextView.text = messageTextBuilder
// Mark text as bold and supporting additional lines if unread
if (message.isUnread) {
holder.messageTextView.setTypeface(null, Typeface.BOLD)
holder.messageTextView.maxLines = 3
} else {
holder.messageTextView.setTypeface(null, Typeface.NORMAL)
holder.messageTextView.maxLines = 1
}
}
/**
* Displays the date of the displayed message of the conversation
* on the view holder. Shows special text if the message is a draft,
* is sending or is not sent.
*
* @param holder The message view holder to use.
* @param position The position of the view in the adapter.
*/
private fun updateViewHolderDateText(
holder: ConversationViewHolder,
position: Int
) {
val conversationItem = conversationItems[position]
val message = conversationItem.message
if (message.isDraft) {
// Show indication that the first message is a draft
val dateTextBuilder = SpannableStringBuilder()
dateTextBuilder.append(
activity.getString(
R.string.conversations_message_draft
)
)
dateTextBuilder.setSpan(
StyleSpan(Typeface.ITALIC), 0,
dateTextBuilder.length,
Spanned.SPAN_INCLUSIVE_EXCLUSIVE
)
holder.dateTextView.text = dateTextBuilder
} else if (!message.isDelivered) {
if (!message.isDeliveryInProgress) {
// Show indication that the first message has not yet been sent
val dateTextBuilder = SpannableStringBuilder()
dateTextBuilder.append(
activity.getString(
R.string.conversations_message_not_sent
)
)
dateTextBuilder.setSpan(
ForegroundColorSpan(
ContextCompat.getColor(
activity,
android.R.color.holo_red_dark
)
),
0, dateTextBuilder.length,
Spanned.SPAN_INCLUSIVE_EXCLUSIVE
)
dateTextBuilder.setSpan(
StyleSpan(Typeface.BOLD),
0,
dateTextBuilder.length,
Spanned.SPAN_INCLUSIVE_EXCLUSIVE
)
holder.dateTextView.text = dateTextBuilder
} else {
// Show indication that the first message is being sent
holder.dateTextView.text = activity.getString(
R.string.conversations_message_sending
)
}
} else {
// Show date of message
holder.dateTextView.text = getConversationsViewDate(
activity, message.date
)
}
}
override fun getItemCount(): Int = conversationItems.size
/**
* Gets the number of items in the adapter that are checked.
*/
fun getCheckedItemCount(): Int =
conversationItems.filter { it.checked }.size
operator fun get(i: Int): ConversationItem = conversationItems[i]
override fun iterator(): Iterator<ConversationItem> =
conversationItems.iterator()
override fun getFilter(): Filter = object : Filter() {
/**
* Perform filtering using the specified filter constraint.
*/
fun doFiltering(constraint: CharSequence): ConversationsFilter {
val resultsObject = ConversationsFilter()
@Suppress("ConstantConditionIf")
if (!BuildConfig.IS_DEMO) {
val activeDid = getActiveDid(activity)
runBlocking {
resultsObject.messages.addAll(
Database.getInstance(activity)
.getConversationsMessageMostRecentFiltered(
if (activeDid == "")
getDids(
activity,
onlyShowInConversationsView = true
)
else setOf(activeDid),
constraint.toString()
.trim { it <= ' ' }
.lowercase(Locale.getDefault())).filter {
val archived = Database.getInstance(activity)
.isConversationArchived(it.conversationId)
if (activity is ConversationsArchivedActivity) {
archived
} else {
!archived
}
})
}
} else {
resultsObject.messages.addAll(
getConversationsDemoMessages()
)
}
for (message in resultsObject.messages) {
@Suppress("ConstantConditionIf")
val contactName = if (!BuildConfig.IS_DEMO) {
getContactName(
activity,
message.contact,
contactNameCache
)
} else {
net.kourlas.voipms_sms.demo.getContactName(
message.contact
)
}
if (contactName != null) {
resultsObject.contactNames[message.contact] =
contactName
}
val bitmap = getContactPhotoBitmap(
activity,
contactName,
message.contact,
activity.resources.getDimensionPixelSize(
R.dimen.contact_badge
),
contactBitmapCache
)
resultsObject.contactBitmaps[message.contact] = bitmap
}
return resultsObject
}
override fun performFiltering(
constraint: CharSequence
): FilterResults = try {
val resultsObject = doFiltering(constraint)
// Return filtered messages
val results = FilterResults()
results.count = resultsObject.messages.size
results.values = resultsObject
results
} catch (e: Exception) {
logException(e)
FilterResults()
}
override fun publishResults(
constraint: CharSequence,
results: FilterResults?
) {
if (results?.values == null) {
showSnackbar(
activity, R.id.coordinator_layout,
activity.getString(
R.string.conversations_error_refresh
)
)
return
}
// Process new filter string
prevConstraint = currConstraint
currConstraint = constraint.toString().trim { it <= ' ' }
val position = layoutManager.findFirstVisibleItemPosition()
// The Android results interface uses type Any, so we
// have no choice but to use an unchecked cast
val resultsObject = results.values as ConversationsFilter
// Get new messages from results list
val newMessages: List<Message>
if (results.values != null) {
// The Android results interface uses type Any, so we have
// no choice but to use an unchecked cast
@Suppress("UNCHECKED_CAST")
newMessages = resultsObject.messages
} else {
newMessages = emptyList()
}
// Create copy of current messages
val oldMessages = mutableListOf<Message>()
conversationItems.mapTo(oldMessages) { it.message }
// Iterate through messages, determining which messages have
// been added, changed, or removed to show appropriate
// animations and update views
var newIdx = 0
var oldIdx = 0
val messageIndexes = mutableListOf<Int>()
while (oldIdx < oldMessages.size || newIdx < newMessages.size) {
// Positive value indicates deletion, negative value
// indicates addition, zero indicates changed, moved, or
// nothing
val comparison: Int = when {
newIdx >= newMessages.size -> 1
oldIdx >= oldMessages.size -> -1
else -> oldMessages[oldIdx]
.conversationsViewCompareTo(newMessages[newIdx])
}
when {
comparison < 0 -> {
// Add new message
val contact = newMessages[newIdx].contact
_conversationItems.add(
newIdx,
ConversationItem(
newMessages[newIdx],
resultsObject.contactNames[contact],
resultsObject.contactBitmaps[contact]!!
)
)
notifyItemInserted(newIdx)
newIdx += 1
}
comparison > 0 -> {
// Remove old message
_conversationItems.removeAt(newIdx)
notifyItemRemoved(newIdx)
oldIdx += 1
}
else -> {
// Update the underlying message
conversationItems[newIdx].message = newMessages[newIdx]
messageIndexes.add(newIdx)
oldIdx += 1
newIdx += 1
}
}
}
for (idx in messageIndexes) {
recyclerView.findViewHolderForAdapterPosition(idx)?.let {
// Try to update the view holder directly so that we
// don't see the "change" animation
@Suppress("RemoveRedundantQualifierName", "UNCHECKED_CAST")
onBindViewHolder(
it as ConversationsRecyclerViewAdapter<T>
.ConversationViewHolder, idx
)
} ?: run {
// We can't find the view holder (probably because
// it's not actually visible), so we'll just tell
// the adapter to redraw the whole view to be safe
notifyItemChanged(idx)
}
}
// Show message if filter returned no messages
val emptyTextView = activity.findViewById<TextView>(
R.id.empty_text
)
if (conversationItems.isEmpty()) {
if (currConstraint == "") {
when {
getDids(
activity,
onlyShowInConversationsView = true
).isEmpty() ->
emptyTextView.text = activity.getString(
R.string.conversations_no_dids
)
activity is ConversationsArchivedActivity ->
emptyTextView.text = activity.getString(
R.string.conversations_archived_no_messages
)
else -> emptyTextView.text = activity.getString(
R.string.conversations_no_messages
)
}
} else {
emptyTextView.text = activity.getString(
R.string.conversations_no_results, currConstraint
)
}
} else {
emptyTextView.text = ""
}
layoutManager.scrollToPosition(position)
}
}
/**
* Refreshes the adapter using the currently defined filter constraint.
*/
fun refresh() = filter.filter(currConstraint)
/**
* Refreshes the adapter using the specified filter constraint.
*/
fun refresh(constraint: String) = filter.filter(constraint)
/**
* Helper class used to store retrieved contact names and bitmaps in
* addition to messages.
*
* This exists because contact name and photo retrieval needs to
* happen during filtering so that it occurs on a thread other than the
* UI thread.
*/
class ConversationsFilter {
internal val messages = mutableListOf<Message>()
internal val contactNames = mutableMapOf<String, String>()
internal val contactBitmaps = mutableMapOf<String, Bitmap>()
}
/**
* A container for a conversation item in the adapter that also tracks
* whether the item is checked in addition to the conversation itself.
*
* @param message The currently displayed message in the conversation.
* @param contactName The name of the displayed contact.
* @param contactBitmap The photo of the displayed contact.
*/
inner class ConversationItem(
var message: Message, val contactName: String?,
val contactBitmap: Bitmap
) {
private var _checked = false
val checked: Boolean
get() = _checked
/**
* Sets whether or not the conversation item is checked.
*
* @param position The position of the message item in the adapter.
*/
fun setChecked(checked: Boolean, position: Int) {
val previous = _checked
_checked = checked
if ((previous && !_checked) || (!previous && _checked)) {
recyclerView.findViewHolderForAdapterPosition(position)?.let {
@Suppress("RemoveRedundantQualifierName", "UNCHECKED_CAST")
updateViewHolderContactBadge(
it as ConversationsRecyclerViewAdapter<T>
.ConversationViewHolder, position
)
} ?: run {
notifyItemChanged(position)
}
}
}
/**
* Toggles the checked state of this message item.
*
* @param position The position of the message item in the adapter.
*/
fun toggle(position: Int) = setChecked(!_checked, position)
}
/**
* A container for the views associated with a conversation item.
*
* @param itemView The primary view of the conversation item.
*/
inner class ConversationViewHolder internal constructor(itemView: View) :
RecyclerView.ViewHolder(itemView) {
// All configurable views on a message item
internal val viewSwitcher: ViewSwitcher =
itemView.findViewById(R.id.view_switcher)
internal val contactBadge: QuickContactBadge =
itemView.findViewById(R.id.photo)
internal val contactTextView: TextView =
itemView.findViewById(R.id.contact)
internal val messageTextView: TextView =
itemView.findViewById(R.id.message)
internal val dateTextView: TextView =
itemView.findViewById(R.id.date)
init {
// Allow the conversation view itself to be clickable and
// selectable
itemView.isClickable = true
itemView.setOnClickListener(activity)
itemView.isLongClickable = true
itemView.setOnLongClickListener(activity)
// Apply circular mask to and remove overlay from contact badge
// to match Android Messages aesthetic; in addition, set up
// check box image
applyCircularMask(contactBadge)
contactBadge.setOverlay(null)
val contactBadgeChecked = itemView
.findViewById<ImageView>(R.id.conversations_photo_checked)
applyCircularMask(contactBadgeChecked)
}
}
}
| apache-2.0 | 5304648236c361bd0a24d5cc1493fe1f | 37.238095 | 89 | 0.552511 | 6.097331 | false | false | false | false |
hermantai/samples | kotlin/kotlin-and-android-development-featuring-jetpack/chapter-14-part-2/app/src/androidTest/java/dev/mfazio/pennydrop/PennyDropDaoTests.kt | 1 | 3486 | package dev.mfazio.pennydrop
import androidx.arch.core.executor.testing.InstantTaskExecutorRule
import androidx.room.Room
import androidx.test.core.app.ApplicationProvider
import androidx.test.ext.junit.runners.AndroidJUnit4
import dev.mfazio.pennydrop.data.PennyDropDao
import dev.mfazio.pennydrop.data.PennyDropDatabase
import dev.mfazio.pennydrop.game.AI
import dev.mfazio.pennydrop.types.Player
import kotlinx.coroutines.runBlocking
import org.junit.After
import org.junit.Assert.*
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
import java.util.concurrent.Executors
@RunWith(AndroidJUnit4::class)
class PennyDropDaoTests {
@get:Rule
var instantExecutorRule = InstantTaskExecutorRule()
private lateinit var database: PennyDropDatabase
private lateinit var dao: PennyDropDao
@Before
fun initializeDatabaseAndDao() {
this.database = Room.inMemoryDatabaseBuilder(
ApplicationProvider.getApplicationContext(),
PennyDropDatabase::class.java
)
.allowMainThreadQueries()
.setTransactionExecutor(Executors.newSingleThreadExecutor())
.build()
this.dao = this.database.pennyDropDao()
}
@After
fun closeDatabase() = database.close()
@Test
fun testInsertingNewPlayer() = runBlocking {
val player = Player(5, "Hazel")
assertNull(dao.getPlayer(player.playerName))
val insertedPlayerId = dao.insertPlayer(player)
assertEquals(player.playerId, insertedPlayerId)
dao.getPlayer(player.playerName)?.let { newPlayer ->
assertEquals(player.playerId, newPlayer.playerId)
assertEquals(player.playerName, newPlayer.playerName)
assertTrue(player.isHuman)
} ?: fail("New player not found.")
}
@Test
fun testStartGame() = runBlocking {
val players = listOf(
Player(23, "Michael"),
Player(12, "Emily"),
Player(5, "Hazel"),
Player(100, "Even Steven", false, AI.basicAI[4])
)
val pennyCount = 15
val gameId = dao.startGame(players, pennyCount)
dao.getCurrentGameWithPlayers().getOrAwaitValue()?.let { gameWithPlayers ->
with(gameWithPlayers.game) {
assertEquals(gameId, this.gameId)
assertNotNull(startTime)
assertNull(endTime)
assertNull(lastRoll)
assertTrue(canRoll)
assertFalse(canPass)
}
val gamePlayers = gameWithPlayers.players
players.forEach { player ->
assertTrue(gamePlayers.contains(player))
}
} ?: fail("No current game with players found.")
players.map { it.playerName }.forEach { playerName ->
assertNotNull(dao.getPlayer(playerName))
}
val playerIds = players.map { it.playerId }
dao.getCurrentGameStatuses().getOrAwaitValue()?.let { gameStatuses ->
assertTrue(gameStatuses.all { it.gameId == gameId })
assertTrue(gameStatuses.all { playerIds.contains(it.playerId) })
assertTrue(gameStatuses.all { it.pennies == pennyCount })
assertEquals(1, gameStatuses.count { it.isRolling })
assertEquals(players.first().playerId, gameStatuses.first { it.isRolling }.playerId)
} ?: fail("No current game with players found.")
}
} | apache-2.0 | 22fd9cef1a321c8972b1a434ca87cdc6 | 32.209524 | 96 | 0.656913 | 4.660428 | false | true | false | false |
Mystery00/JanYoShare | app/src/main/java/com/janyo/janyoshare/handler/SettingHandler.kt | 1 | 1520 | package com.janyo.janyoshare.handler
import android.content.Context
import android.os.Handler
import android.os.Message
import android.preference.Preference
import android.support.v7.app.AlertDialog
import com.janyo.janyoshare.R
import com.janyo.janyoshare.classes.InstallApp
import com.janyo.janyoshare.util.Settings
import com.zyao89.view.zloading.ZLoadingDialog
class SettingHandler(private val context: Context,
private val spotsDialog: ZLoadingDialog,
private val excludeList: Preference) : Handler()
{
override fun handleMessage(msg: Message)
{
@Suppress("UNCHECKED_CAST")
val list = msg.obj as List<InstallApp>
val settings = Settings.getInstance(context)
val arrays = Array(list.size, { i -> list[i].name })
val checkedItems = BooleanArray(list.size)
val saved = settings.excludeList
list.indices
.filter { saved.contains(list[it].packageName) }
.forEach { checkedItems[it] = true }
spotsDialog.dismiss()
AlertDialog.Builder(context)
.setTitle(R.string.hint_exclude_list_title)
.setMultiChoiceItems(arrays, checkedItems, { _, position, checked ->
checkedItems[position] = checked
})
.setPositiveButton(R.string.action_done, { _, _ ->
val set = HashSet<String>()
checkedItems.indices
.filter { checkedItems[it] }
.forEach { set.add(list[it].packageName!!) }
settings.excludeList = set
settings.imgVersion++
excludeList.summary = context.getString(R.string.summary_exclude_list, set.size)
})
.show()
}
} | gpl-3.0 | be798214909f178bea059d0e557b1069 | 32.8 | 85 | 0.728289 | 3.584906 | false | false | false | false |
hzsweers/CatchUp | services/unsplash/src/main/kotlin/io/sweers/catchup/service/unsplash/UnsplashService.kt | 1 | 5615 | /*
* Copyright (C) 2019. Zac Sweers
*
* 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.sweers.catchup.service.unsplash
import com.squareup.moshi.Moshi
import dagger.Binds
import dagger.Lazy
import dagger.Module
import dagger.Provides
import dagger.Reusable
import dagger.multibindings.IntoMap
import dev.zacsweers.catchup.appconfig.AppConfig
import io.reactivex.rxjava3.core.Single
import io.sweers.catchup.libraries.retrofitconverters.delegatingCallFactory
import io.sweers.catchup.service.api.CatchUpItem
import io.sweers.catchup.service.api.DataRequest
import io.sweers.catchup.service.api.DataResult
import io.sweers.catchup.service.api.ImageInfo
import io.sweers.catchup.service.api.Service
import io.sweers.catchup.service.api.ServiceKey
import io.sweers.catchup.service.api.ServiceMeta
import io.sweers.catchup.service.api.ServiceMetaKey
import io.sweers.catchup.service.api.VisualService
import io.sweers.catchup.service.api.VisualService.SpanConfig
import io.sweers.catchup.serviceregistry.annotations.Meta
import io.sweers.catchup.serviceregistry.annotations.ServiceModule
import io.sweers.catchup.util.data.adapters.ISO8601InstantAdapter
import io.sweers.catchup.util.network.AuthInterceptor
import kotlinx.datetime.Instant
import okhttp3.OkHttpClient
import retrofit2.Retrofit
import retrofit2.adapter.rxjava3.RxJava3CallAdapterFactory
import retrofit2.converter.moshi.MoshiConverterFactory
import javax.inject.Inject
import javax.inject.Qualifier
@Qualifier
private annotation class InternalApi
private const val SERVICE_KEY = "unsplash"
class UnsplashService @Inject constructor(
@InternalApi private val serviceMeta: ServiceMeta,
private val api: UnsplashApi
) :
VisualService {
override fun meta() = serviceMeta
override fun fetchPage(request: DataRequest): Single<DataResult> {
val page = request.pageId.toInt()
return api.getPhotos(page, 50)
.flattenAsObservable { it }
.map {
CatchUpItem(
id = it.id.hashCode().toLong(),
title = "",
score =
"\u2665\uFE0E" // Because lol: https://code.google.com/p/android/issues/detail?id=231068
to it.likes,
timestamp = it.createdAt,
author = it.user.name,
source = null,
tag = null,
itemClickUrl = it.urls.full,
imageInfo = ImageInfo(
url = it.urls.small,
detailUrl = it.urls.raw,
animatable = false,
sourceUrl = it.links.html,
bestSize = null,
imageId = it.id
)
)
}
.toList()
.map { DataResult(it, (page + 1).toString()) }
}
override fun spanConfig() = SpanConfig(3) {
/* emulating https://material-design.storage.googleapis.com/publish/material_v_4/material_ext_publish/0B6Okdz75tqQsck9lUkgxNVZza1U/style_imagery_integration_scale1.png */
when (it % 6) {
5 -> 3
3 -> 2
else -> 1
}
}
override fun marginDecoration() = true
}
@Meta
@ServiceModule
@Module
abstract class UnsplashMetaModule {
@IntoMap
@ServiceMetaKey(SERVICE_KEY)
@Binds
internal abstract fun unsplashServiceMeta(@InternalApi meta: ServiceMeta): ServiceMeta
companion object {
@InternalApi
@Provides
@Reusable
internal fun provideUnsplashServiceMeta(): ServiceMeta = ServiceMeta(
SERVICE_KEY,
R.string.unsplash,
R.color.unsplashAccent,
R.drawable.logo_unsplash,
isVisual = true,
pagesAreNumeric = true,
firstPageKey = "1",
enabled = BuildConfig.UNSPLASH_API_KEY.run { !isNullOrEmpty() && !equals("null") }
)
}
}
@ServiceModule
@Module(includes = [UnsplashMetaModule::class])
abstract class UnsplashModule {
@IntoMap
@ServiceKey(SERVICE_KEY)
@Binds
internal abstract fun unsplashService(unsplashService: UnsplashService): Service
companion object {
@Provides
@InternalApi
internal fun provideUnsplashMoshi(moshi: Moshi): Moshi {
return moshi.newBuilder()
.add(Instant::class.java, ISO8601InstantAdapter())
.build()
}
@Provides
@InternalApi
internal fun provideUnsplashOkHttpClient(client: OkHttpClient): OkHttpClient {
return client.newBuilder()
.addInterceptor {
it.proceed(
it.request().newBuilder()
.addHeader("Accept-Version", "v1")
.build()
)
}
.addInterceptor(AuthInterceptor("Client-ID", BuildConfig.UNSPLASH_API_KEY))
.build()
}
@Provides
internal fun provideUnsplashService(
@InternalApi client: Lazy<OkHttpClient>,
@InternalApi moshi: Moshi,
rxJavaCallAdapterFactory: RxJava3CallAdapterFactory,
appConfig: AppConfig
): UnsplashApi {
return Retrofit.Builder().baseUrl(UnsplashApi.ENDPOINT)
.delegatingCallFactory(client)
.addCallAdapterFactory(rxJavaCallAdapterFactory)
.addConverterFactory(MoshiConverterFactory.create(moshi))
.validateEagerly(appConfig.isDebug)
.build()
.create(UnsplashApi::class.java)
}
}
}
| apache-2.0 | 173b5b3dd2f88711ac2e5511b6da3b2d | 29.68306 | 174 | 0.704898 | 4.221805 | false | true | false | false |
siarhei-luskanau/android-iot-doorbell | data/dataDoorbellApiStub/src/main/kotlin/siarhei/luskanau/iot/doorbell/data/repository/StubUptimeRepository.kt | 1 | 985 | package siarhei.luskanau.iot.doorbell.data.repository
import siarhei.luskanau.iot.doorbell.data.model.Uptime
class StubUptimeRepository : UptimeRepository {
override suspend fun uptimeStartup(
doorbellId: String,
startupTimeMillis: Long,
startupTimeString: String
) = Unit
override suspend fun uptimePing(
doorbellId: String,
pingTimeMillis: Long,
pingTimeString: String
) = Unit
override suspend fun uptimeRebootRequest(
doorbellId: String,
rebootRequestTimeMillis: Long,
rebootRequestTimeString: String
) = Unit
override suspend fun uptimeRebooting(
doorbellId: String,
rebootingTimeMillis: Long,
rebootingTimeString: String
) = Unit
override suspend fun getUptime(doorbellId: String): Uptime? = null
override suspend fun sendIpAddressMap(
doorbellId: String,
ipAddressMap: Map<String, Pair<String, String>>
) = Unit
}
| mit | 8b1c18883a7fa6f5c2cebd9835209298 | 25.621622 | 70 | 0.684264 | 4.852217 | false | false | false | false |
iPoli/iPoli-android | app/src/main/java/io/ipoli/android/quest/schedule/today/TodayViewController.kt | 1 | 43472 | package io.ipoli.android.quest.schedule.today
import android.animation.Animator
import android.animation.AnimatorListenerAdapter
import android.annotation.SuppressLint
import android.content.res.ColorStateList
import android.graphics.PorterDuff
import android.graphics.drawable.GradientDrawable
import android.graphics.drawable.RotateDrawable
import android.os.Bundle
import android.support.annotation.ColorInt
import android.support.annotation.ColorRes
import android.support.annotation.DrawableRes
import android.support.constraint.ConstraintSet
import android.support.design.widget.FloatingActionButton
import android.support.v4.widget.TextViewCompat
import android.support.v7.widget.GridLayoutManager
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.support.v7.widget.helper.ItemTouchHelper
import android.text.SpannableString
import android.text.style.StrikethroughSpan
import android.view.*
import android.view.animation.AccelerateDecelerateInterpolator
import android.widget.ImageView
import android.widget.TextView
import com.bluelinelabs.conductor.changehandler.VerticalChangeHandler
import com.bumptech.glide.Glide
import com.bumptech.glide.request.RequestOptions
import com.mikepenz.google_material_typeface_library.GoogleMaterial
import com.mikepenz.iconics.IconicsDrawable
import com.mikepenz.iconics.typeface.IIcon
import com.mikepenz.ionicons_typeface_library.Ionicons
import io.ipoli.android.Constants
import io.ipoli.android.R
import io.ipoli.android.common.ViewUtils
import io.ipoli.android.common.redux.android.ReduxViewController
import io.ipoli.android.common.text.CalendarFormatter
import io.ipoli.android.common.text.DurationFormatter
import io.ipoli.android.common.text.LongFormatter
import io.ipoli.android.common.text.QuestStartTimeFormatter
import io.ipoli.android.common.view.*
import io.ipoli.android.common.view.recyclerview.*
import io.ipoli.android.dailychallenge.usecase.CheckDailyChallengeProgressUseCase
import io.ipoli.android.event.Event
import io.ipoli.android.pet.AndroidPetAvatar
import io.ipoli.android.pet.AndroidPetMood
import io.ipoli.android.pet.PetItem
import io.ipoli.android.player.data.AndroidAttribute
import io.ipoli.android.player.data.AndroidAvatar
import io.ipoli.android.player.data.AndroidRank
import io.ipoli.android.player.data.Player
import io.ipoli.android.quest.schedule.addquest.AddQuestAnimationHelper
import io.ipoli.android.quest.schedule.today.TodayViewState.StateType.*
import io.ipoli.android.quest.schedule.today.usecase.CreateTodayItemsUseCase
import kotlinx.android.synthetic.main.controller_home.view.*
import kotlinx.android.synthetic.main.controller_today.view.*
import kotlinx.android.synthetic.main.item_agenda_event.view.*
import kotlinx.android.synthetic.main.item_agenda_quest.view.*
import kotlinx.android.synthetic.main.item_today_habit.view.*
import kotlinx.android.synthetic.main.item_today_profile_attribute.view.*
import kotlinx.android.synthetic.main.view_fab.view.*
import kotlinx.android.synthetic.main.view_profile_pet.view.*
import kotlinx.android.synthetic.main.view_today_stats.view.*
import org.threeten.bp.LocalDate
import space.traversal.kapsule.required
class TodayViewController(args: Bundle? = null) :
ReduxViewController<TodayAction, TodayViewState, TodayReducer>(args = args) {
override val reducer = TodayReducer
private lateinit var addQuestAnimationHelper: AddQuestAnimationHelper
private val imageLoader by required { imageLoader }
private var showDataAfterStats = false
constructor(showDataAfterStats: Boolean) : this() {
this.showDataAfterStats = showDataAfterStats
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup,
savedViewState: Bundle?
): View {
setHasOptionsMenu(true)
val view = container.inflate(R.layout.controller_today)
val today = LocalDate.now()
toolbarTitle = CalendarFormatter(view.context).dateWithoutYear(today)
view.questItems.layoutManager = LinearLayoutManager(view.context)
view.questItems.isNestedScrollingEnabled = false
view.questItems.adapter = TodayItemAdapter()
view.habitItems.layoutManager = GridLayoutManager(view.context, 3)
view.habitItems.adapter = HabitAdapter()
view.completedQuests.layoutManager = LinearLayoutManager(view.context)
view.completedQuests.isNestedScrollingEnabled = false
view.completedQuests.adapter = CompletedQuestAdapter()
initIncompleteSwipeHandler(view)
initCompletedSwipeHandler(view)
if (showDataAfterStats) {
view.dataContainer.gone()
} else {
view.dataContainer.visible()
}
return view
}
private fun initCompletedSwipeHandler(view: View) {
val swipeHandler = object : SimpleSwipeCallback(
R.drawable.ic_undo_white_24dp,
R.color.md_amber_500,
R.drawable.ic_delete_white_24dp,
R.color.md_red_500
) {
override fun onSwiped(viewHolder: RecyclerView.ViewHolder, direction: Int) {
val questId = questId(viewHolder)
if (direction == ItemTouchHelper.END) {
dispatch(TodayAction.UndoCompleteQuest(questId(viewHolder)))
view.completedQuests.adapter.notifyItemChanged(viewHolder.adapterPosition)
} else {
dispatch(TodayAction.RemoveQuest(questId))
PetMessagePopup(
stringRes(R.string.remove_quest_undo_message),
{
dispatch(TodayAction.UndoRemoveQuest(questId))
view.completedQuests.adapter.notifyItemChanged(viewHolder.adapterPosition)
},
stringRes(R.string.undo)
).show(view.context)
}
}
private fun questId(holder: RecyclerView.ViewHolder): String {
val a = view.completedQuests.adapter as CompletedQuestAdapter
return a.getItemAt(holder.adapterPosition).id
}
override fun getSwipeDirs(
recyclerView: RecyclerView,
viewHolder: RecyclerView.ViewHolder
) = ItemTouchHelper.END or ItemTouchHelper.START
}
val itemTouchHelper = ItemTouchHelper(swipeHandler)
itemTouchHelper.attachToRecyclerView(view.completedQuests)
}
private fun initIncompleteSwipeHandler(view: View) {
val swipeHandler = object : SimpleSwipeCallback(
R.drawable.ic_done_white_24dp,
R.color.md_green_500,
R.drawable.ic_event_white_24dp,
R.color.md_blue_500
) {
override fun onSwiped(viewHolder: RecyclerView.ViewHolder, direction: Int) {
val questId = questId(viewHolder)
if (direction == ItemTouchHelper.END) {
dispatch(TodayAction.CompleteQuest(questId(viewHolder)))
view.questItems.adapter.notifyItemChanged(viewHolder.adapterPosition)
} else {
view.questItems.adapter.notifyItemChanged(viewHolder.adapterPosition)
navigate()
.toReschedule(
includeToday = false,
listener = { date, time, duration ->
dispatch(TodayAction.RescheduleQuest(questId, date, time, duration))
},
cancelListener = {
}
)
}
}
private fun questId(holder: RecyclerView.ViewHolder): String {
val a = view.questItems.adapter as TodayItemAdapter
val item = a.getItemAt<TodayItemViewModel.QuestViewModel>(holder.adapterPosition)
return item.id
}
override fun getSwipeDirs(
recyclerView: RecyclerView,
viewHolder: RecyclerView.ViewHolder
) = when {
viewHolder.itemViewType == QuestViewType.QUEST.ordinal -> (ItemTouchHelper.END or ItemTouchHelper.START)
else -> 0
}
}
val itemTouchHelper = ItemTouchHelper(swipeHandler)
itemTouchHelper.attachToRecyclerView(view.questItems)
}
private fun initAddQuest(view: View, addQuest: FloatingActionButton, currentDate: LocalDate) {
addQuestAnimationHelper = AddQuestAnimationHelper(
controller = this,
addContainer = view.addContainer,
fab = addQuest,
background = view.addContainerBackground
)
view.addContainerBackground.setOnClickListener {
closeAddIfShown()
}
addQuest.setOnClickListener {
addQuestAnimationHelper.openAddContainer(currentDate)
}
}
private fun closeAddIfShown(endListener: (() -> Unit)? = null) {
if (view == null) return
val containerRouter = addContainerRouter(view!!)
if (containerRouter.hasRootController()) {
containerRouter.popCurrentController()
ViewUtils.hideKeyboard(view!!)
addQuestAnimationHelper.closeAddContainer(endListener)
} else {
endListener?.invoke()
}
}
private var statsContainer: View? = null
private fun addContainerRouter(view: View) =
getChildRouter(view.addContainer, "add-quest")
override fun onCreateLoadAction() = TodayAction.Load(LocalDate.now(), showDataAfterStats)
override fun onAttach(view: View) {
super.onAttach(view)
parentController?.view?.let {
it.levelProgress.gone()
val fab = (view as ViewGroup).inflate(R.layout.view_fab)
(it.rootCoordinator as ViewGroup).addView(fab)
initAddQuest(view, fab as FloatingActionButton, LocalDate.now())
statsContainer = view.inflate(R.layout.view_today_stats)
(it.todayCollapsingToolbarContainer as ViewGroup).addView(
statsContainer,
0
)
val petBgr = statsContainer!!.todayPetAvatar.background as GradientDrawable
petBgr.mutate()
petBgr.setColor(colorRes(R.color.md_grey_50))
}
}
override fun onDetach(view: View) {
parentController?.view?.let {
it.levelProgress.visible()
val fabView = it.rootCoordinator.addQuest
it.rootCoordinator.removeView(fabView)
it.todayCollapsingToolbarContainer.removeView(statsContainer)
}
statsContainer = null
super.onDetach(view)
}
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
super.onCreateOptionsMenu(menu, inflater)
inflater.inflate(R.menu.today_menu, menu)
}
override fun onOptionsItemSelected(item: MenuItem) =
when (item.itemId) {
R.id.actionDailyChallenge -> {
closeAddIfShown {
navigateFromRoot().toDailyChallenge()
}
true
}
else -> super.onOptionsItemSelected(item)
}
private fun loadImage(view: View, state: TodayViewState) {
state.todayImageUrl?.let {
imageLoader.loadTodayImage(
imageUrl = it,
view = view.todayBackdrop,
onReady = {
activity?.let { _ ->
view.todayBackdrop.fadeIn(mediumAnimTime, onComplete = {
dispatch(TodayAction.ImageLoaded)
})
}
},
onError = { _ ->
activity?.let { _ ->
view.todayBackdrop.fadeIn(mediumAnimTime, onComplete = {
dispatch(TodayAction.ImageLoaded)
})
}
}
)
}
}
private fun animateStats(state: TodayViewState, view: View) {
view.backdropTransparentColor.visible()
view.backdropTransparentColor.fadeIn(
shortAnimTime,
to = 0.9f,
delay = longAnimTime,
onComplete = {
activity?.let { _ ->
val animTime = shortAnimTime
view.todayInfoGroup.visible()
val allViews = view.todayInfoGroup.views()
val lastViews = allViews.subList(1, allViews.size)
lastViews.forEach {
it.visible()
it.fadeIn(animTime)
}
allViews.first().let {
it.visible()
renderPlayerStats(state, view)
it.fadeIn(animTime, onComplete = {
dispatch(TodayAction.StatsShown)
})
}
}
})
}
override fun render(state: TodayViewState, view: View) {
when (state.type) {
SHOW_IMAGE ->
statsContainer?.let {
loadImage(it, state)
}
SHOW_SUMMARY_STATS ->
statsContainer?.let {
renderSummaryStats(state, it)
animateStats(state, it)
}
SUMMARY_STATS_CHANGED ->
statsContainer?.let {
renderSummaryStats(state, it)
}
PLAYER_STATS_CHANGED ->
statsContainer?.let {
renderPlayerStats(state, it)
}
SHOW_DATA ->
view.dataContainer.visible()
DATA_CHANGED -> {
renderHabits(view, state)
renderQuests(state, view)
}
HABITS_CHANGED ->
renderHabits(view, state)
QUESTS_CHANGED ->
renderQuests(state, view)
else -> {
}
}
}
@SuppressLint("SetTextI18n")
private fun renderSummaryStats(state: TodayViewState, view: View) {
val focusDuration = DurationFormatter.formatNarrow(state.focusDuration!!.intValue)
view.todayFocusDuration.text = "$focusDuration/${Constants.DAILY_FOCUS_HOURS_GOAL}h"
val dcProgress = state.dailyChallengeProgress!!
val dcText = when (dcProgress) {
is CheckDailyChallengeProgressUseCase.Result.NotScheduledForToday ->
"Inactive"
is CheckDailyChallengeProgressUseCase.Result.Inactive ->
"Inactive"
is CheckDailyChallengeProgressUseCase.Result.Complete ->
"Complete"
is CheckDailyChallengeProgressUseCase.Result.Incomplete ->
"${dcProgress.completeQuestCount}/${Constants.DAILY_CHALLENGE_QUEST_COUNT}"
}
view.todayDailyChallengeProgress.text = dcText
}
@SuppressLint("SetTextI18n")
private fun renderHabitStats(
state: TodayViewState
) {
statsContainer?.let {
it.todayHabitsDone.text = "${state.habitCompleteCount}/${state.habitCount}"
}
}
@SuppressLint("SetTextI18n")
private fun renderQuestStats(
state: TodayViewState
) {
statsContainer?.let {
it.todayQuestsDone.text = "${state.questCompleteCount}/${state.questCount}"
}
}
private fun renderPlayerStats(
state: TodayViewState,
view: View
) {
val androidAvatar = AndroidAvatar.valueOf(state.avatar.name)
Glide.with(view.context).load(androidAvatar.image)
.apply(RequestOptions.circleCropTransform())
.into(view.todayPlayerAvatar)
val background = view.todayPlayerAvatar.background as GradientDrawable
background.mutate()
background.setColor(colorRes(androidAvatar.backgroundColor))
view.todayPlayerAvatar.onDebounceClick {
navigateFromRoot().toProfile()
}
view.todayPlayerRank.setText(AndroidRank.valueOf(state.rank.name).title)
view.todayLevelText.text = state.levelText
view.todayHealthProgress.max = state.maxHealth
view.todayHealthProgress.animateProgressFromCurrentValue(state.health)
view.todayHealthProgressText.text = state.healthProgressText
view.todayLevelProgress.max = state.levelXpMaxProgress
view.todayLevelProgress.animateProgressFromCurrentValue(state.levelXpProgress)
view.todayLevelProgressText.text = state.levelProgressText
view.todayCoins.text = state.lifeCoinsText
view.todayCoins.onDebounceClick {
navigateFromRoot().toCurrencyConverter()
}
view.todayGems.text = state.gemsText
view.todayGems.onDebounceClick {
navigateFromRoot().toCurrencyConverter()
}
state.attributeViewModels.forEach { vm ->
val v = when (vm.type) {
Player.AttributeType.STRENGTH -> view.todayAttrStrength
Player.AttributeType.INTELLIGENCE -> view.todayAttrIntelligence
Player.AttributeType.CHARISMA -> view.todayAttrCharisma
Player.AttributeType.EXPERTISE -> view.todayAttrExpertise
Player.AttributeType.WELL_BEING -> view.todayAttrWellBeing
Player.AttributeType.WILLPOWER -> view.todayAttrWillpower
}
v.attrLevel.text = vm.level
v.attrLevelProgress.max = vm.progressMax
v.attrLevelProgress.animateProgressFromCurrentValue(vm.progress)
val pd = v.attrLevelProgress.progressDrawable as RotateDrawable
pd.mutate()
pd.setColorFilter(vm.progressColor, PorterDuff.Mode.SRC_ATOP)
v.attrIcon.setImageResource(vm.icon)
v.onDebounceClick {
navigateFromRoot().toAttributes(vm.type)
}
}
renderPet(state, view)
}
private fun renderPet(
state: TodayViewState,
view: View
) {
view.todayPetAvatar.onDebounceClick {
navigateFromRoot().toPet(VerticalChangeHandler())
}
val pet = state.pet!!
val avatar = AndroidPetAvatar.valueOf(pet.avatar.name)
view.pet.setImageResource(avatar.image)
view.petState.setImageResource(avatar.stateImage[pet.state]!!)
val setItem: (ImageView, EquipmentItemViewModel?) -> Unit = { iv, vm ->
if (vm == null) iv.invisible()
else iv.setImageResource(vm.image)
}
setItem(view.hat, state.toItemViewModel(pet.equipment.hat))
setItem(view.mask, state.toItemViewModel(pet.equipment.mask))
setItem(view.bodyArmor, state.toItemViewModel(pet.equipment.bodyArmor))
if (pet.equipment.hat == null) {
val set = ConstraintSet()
val layout = view.petContainer
set.clone(layout)
set.connect(R.id.pet, ConstraintSet.START, R.id.petContainer, ConstraintSet.START, 0)
set.connect(R.id.pet, ConstraintSet.END, R.id.petContainer, ConstraintSet.END, 0)
set.connect(R.id.pet, ConstraintSet.TOP, R.id.petContainer, ConstraintSet.TOP, 0)
set.connect(R.id.pet, ConstraintSet.BOTTOM, R.id.petContainer, ConstraintSet.BOTTOM, 0)
set.applyTo(layout)
}
val drawable = view.todayPetMood.background as GradientDrawable
drawable.mutate()
drawable.setColor(colorRes(state.petMoodColor))
view.todayPetName.text = pet.name
}
data class EquipmentItemViewModel(
@DrawableRes val image: Int,
val item: PetItem
)
private fun TodayViewState.toItemViewModel(petItem: PetItem?): EquipmentItemViewModel? {
val petItems = AndroidPetAvatar.valueOf(pet!!.avatar.name).items
return petItem?.let {
EquipmentItemViewModel(petItems[it]!!, it)
}
}
private fun renderQuests(
state: TodayViewState,
view: View
) {
renderQuestStats(state)
val incompleteQuestViewModels = state.incompleteQuestViewModels
val completedQuestVMs = state.completedQuestViewModels
if (incompleteQuestViewModels.isEmpty() && completedQuestVMs.isEmpty()) {
view.questsLabel.visible()
view.questItemsEmpty.visible()
view.questItems.gone()
view.questItemsEmpty.setText(R.string.today_empty_quests)
} else if (incompleteQuestViewModels.isEmpty()) {
view.questsLabel.visible()
view.questItemsEmpty.visible()
view.questItems.gone()
view.questItemsEmpty.setText(R.string.today_all_quests_done)
} else {
view.questsLabel.gone()
view.questItemsEmpty.gone()
view.questItems.visible()
(view.questItems.adapter as TodayItemAdapter).updateAll(
incompleteQuestViewModels
)
}
if (completedQuestVMs.isEmpty()) {
view.completedQuestsLabel.gone()
view.completedQuests.gone()
} else {
view.completedQuestsLabel.visible()
view.completedQuests.visible()
(view.completedQuests.adapter as CompletedQuestAdapter).updateAll(
completedQuestVMs
)
}
}
private fun renderHabits(
view: View,
state: TodayViewState
) {
renderHabitStats(state)
view.habitsLabel.visible()
val habitVMs = state.habitItemViewModels
if (habitVMs.isEmpty()) {
view.habitItemsEmpty.visible()
view.habitItems.gone()
} else {
view.habitItemsEmpty.gone()
view.habitItems.visible()
(view.habitItems.adapter as HabitAdapter).updateAll(habitVMs)
}
}
data class AttributeViewModel(
val type: Player.AttributeType,
val level: String,
@DrawableRes val icon: Int,
val progress: Int,
val progressMax: Int,
@ColorInt val progressColor: Int
)
private val TodayViewState.attributeViewModels: List<AttributeViewModel>
get() = attributes.map {
val attr = AndroidAttribute.valueOf(it.type.name)
AttributeViewModel(
type = it.type,
level = it.level.toString(),
progress = ((it.progressForLevel * 100f) / it.progressForNextLevel).toInt(),
progressMax = 100,
progressColor = colorRes(attr.colorPrimaryDark),
icon = attr.colorIcon
)
}
data class TagViewModel(val name: String, @ColorRes val color: Int)
sealed class TodayItemViewModel(override val id: String) : RecyclerViewViewModel {
data class Section(val text: String) : TodayItemViewModel(text)
data class QuestViewModel(
override val id: String,
val name: String,
val tags: List<TagViewModel>,
val startTime: String,
@ColorRes val color: Int,
val icon: IIcon,
val isRepeating: Boolean,
val isFromChallenge: Boolean
) : TodayItemViewModel(id)
data class EventViewModel(
override val id: String,
val name: String,
val startTime: String,
@ColorInt val color: Int
) : TodayItemViewModel(id)
}
enum class QuestViewType {
SECTION,
QUEST,
EVENT
}
inner class TodayItemAdapter : MultiViewRecyclerViewAdapter<TodayItemViewModel>() {
override fun onRegisterItemBinders() {
registerBinder<TodayItemViewModel.Section>(
QuestViewType.SECTION.ordinal,
R.layout.item_agenda_list_section
) { vm, view, _ ->
(view as TextView).text = vm.text
view.setOnClickListener(null)
}
registerBinder<TodayItemViewModel.QuestViewModel>(
QuestViewType.QUEST.ordinal,
R.layout.item_agenda_quest
) { vm, view, _ ->
view.questName.text = vm.name
view.questIcon.backgroundTintList =
ColorStateList.valueOf(colorRes(vm.color))
view.questIcon.setImageDrawable(smallListItemIcon(vm.icon))
if (vm.tags.isNotEmpty()) {
view.questTagName.visible()
renderTag(view, vm.tags.first())
} else {
view.questTagName.gone()
}
view.questStartTime.text = vm.startTime
view.questRepeatIndicator.visibility =
if (vm.isRepeating) View.VISIBLE else View.GONE
view.questChallengeIndicator.visibility =
if (vm.isFromChallenge) View.VISIBLE else View.GONE
view.onDebounceClick {
navigateFromRoot().toQuest(vm.id, VerticalChangeHandler())
}
}
registerBinder<TodayItemViewModel.EventViewModel>(
QuestViewType.EVENT.ordinal,
R.layout.item_agenda_event
) { vm, view, _ ->
view.eventName.text = vm.name
view.eventStartTime.text = vm.startTime
view.eventIcon.backgroundTintList =
ColorStateList.valueOf(vm.color)
view.setOnClickListener(null)
}
}
private fun renderTag(view: View, tag: TagViewModel) {
view.questTagName.text = tag.name
TextViewCompat.setTextAppearance(
view.questTagName,
R.style.TextAppearance_AppCompat_Caption
)
val indicator = view.questTagName.compoundDrawablesRelative[0] as GradientDrawable
indicator.mutate()
val size = ViewUtils.dpToPx(8f, view.context).toInt()
indicator.setSize(size, size)
indicator.setColor(colorRes(tag.color))
view.questTagName.setCompoundDrawablesRelativeWithIntrinsicBounds(
indicator,
null,
null,
null
)
}
}
data class HabitViewModel(
override val id: String,
val name: String,
val icon: IIcon,
@ColorRes val color: Int,
@ColorRes val secondaryColor: Int,
val streak: Int,
val isBestStreak: Boolean,
val timesADay: Int,
val progress: Int,
val maxProgress: Int,
val isCompleted: Boolean,
val canBeCompletedMoreTimes: Boolean,
val isGood: Boolean,
val completedCount: Int,
val showCompletedCount: Boolean
) : RecyclerViewViewModel
inner class HabitAdapter :
BaseRecyclerViewAdapter<HabitViewModel>(R.layout.item_today_habit) {
override fun onBindViewModel(vm: HabitViewModel, view: View, holder: SimpleViewHolder) {
renderName(view, vm.name, vm.isGood)
if (vm.showCompletedCount) {
view.habitCompletedToday.visible()
view.habitCompletedToday.text = "x${vm.completedCount}"
} else {
view.habitCompletedToday.gone()
}
renderIcon(view, vm.icon, if (vm.isCompleted) R.color.md_white else vm.color)
renderStreak(
view = view,
streak = vm.streak,
isBestStreak = vm.isBestStreak,
color = if (vm.isCompleted) R.color.md_white else vm.color,
textColor = if (vm.isCompleted) R.color.md_white else colorTextPrimaryResource
)
renderCompletedBackground(view, vm.color)
view.habitProgress.setProgressStartColor(colorRes(vm.color))
view.habitProgress.setProgressEndColor(colorRes(vm.color))
view.habitProgress.setProgressBackgroundColor(colorRes(vm.secondaryColor))
view.habitProgress.setProgressFormatter(null)
renderProgress(view, vm.progress, vm.maxProgress)
if (vm.timesADay > 1) {
view.habitTimesADayProgress.visible()
view.habitTimesADayProgress.setProgressStartColor(attrData(android.R.attr.colorBackground))
view.habitTimesADayProgress.setProgressEndColor(attrData(android.R.attr.colorBackground))
view.habitTimesADayProgress.setProgressFormatter(null)
renderTimesADayProgress(view, vm.progress, vm.maxProgress)
} else {
view.habitTimesADayProgress.gone()
}
val habitCompleteBackground = view.habitCompletedBackground
if (vm.isCompleted) {
view.habitProgress.invisible()
habitCompleteBackground.visible()
view.habitCompletedBackground.setOnLongClickListener {
navigateFromRoot().toHabit(vm.id)
return@setOnLongClickListener true
}
view.habitProgress.setOnLongClickListener(null)
} else {
view.habitProgress.visible()
habitCompleteBackground.invisible()
view.habitProgress.setOnLongClickListener {
navigateFromRoot().toHabit(vm.id)
return@setOnLongClickListener true
}
view.habitCompletedBackground.setOnLongClickListener(null)
}
view.habitProgress.onDebounceClick {
val isLastProgress = vm.maxProgress - vm.progress == 1
if (isLastProgress) {
startCompleteAnimation(view, vm)
} else {
dispatch(
if (vm.canBeCompletedMoreTimes) TodayAction.CompleteHabit(vm.id)
else TodayAction.UndoCompleteHabit(vm.id)
)
}
}
view.habitCompletedBackground.onDebounceClick {
if (vm.canBeCompletedMoreTimes) {
dispatch(TodayAction.CompleteHabit(vm.id))
} else {
startUndoCompleteAnimation(view, vm)
}
}
}
private fun renderCompletedBackground(
view: View,
color: Int
): View? {
val habitCompleteBackground = view.habitCompletedBackground
val b = habitCompleteBackground.background as GradientDrawable
b.setColor(colorRes(color))
return habitCompleteBackground
}
private fun renderStreak(
view: View,
streak: Int,
isBestStreak: Boolean,
textColor: Int,
color: Int
) {
view.habitStreak.text = streak.toString()
view.habitStreak.setTextColor(colorRes(textColor))
if (isBestStreak) {
view.habitBestProgressIndicator.visible()
view.habitBestProgressIndicator.setImageDrawable(
IconicsDrawable(view.context).normalIcon(
GoogleMaterial.Icon.gmd_star,
color
)
)
} else {
view.habitBestProgressIndicator.gone()
}
}
private fun renderIcon(
view: View,
icon: IIcon,
color: Int
) {
view.habitIcon.setImageDrawable(
IconicsDrawable(view.context).listItemIcon(icon, color)
)
}
private fun renderName(
view: View,
name: String,
isGood: Boolean
) {
view.habitName.text = if (isGood) name else "\u2205 $name"
}
private fun renderProgress(
view: View,
progress: Int,
maxProgress: Int
) {
view.habitProgress.max = maxProgress
view.habitProgress.progress = progress
}
private fun renderTimesADayProgress(
view: View,
progress: Int,
maxProgress: Int
) {
view.habitTimesADayProgress.max = maxProgress
view.habitTimesADayProgress.setLineCount(maxProgress)
view.habitTimesADayProgress.progress = progress
}
private fun startUndoCompleteAnimation(
view: View,
vm: HabitViewModel
) {
val hcb = view.habitCompletedBackground
val half = hcb.width / 2
val completeAnim = ViewAnimationUtils.createCircularReveal(
hcb,
half, half,
half.toFloat(), 0f
)
completeAnim.duration = shortAnimTime
completeAnim.interpolator = AccelerateDecelerateInterpolator()
completeAnim.addListener(object : AnimatorListenerAdapter() {
override fun onAnimationStart(animation: Animator?) {
view.habitProgress.visible()
}
override fun onAnimationEnd(animation: Animator?) {
hcb.invisible()
view.habitIcon.setImageDrawable(
IconicsDrawable(view.context).normalIcon(vm.icon, vm.color)
)
view.habitStreak.setTextColor(colorRes(colorTextPrimaryResource))
renderProgress(view, vm.progress - 1, vm.maxProgress)
renderTimesADayProgress(view, vm.progress - 1, vm.maxProgress)
dispatch(
if (vm.canBeCompletedMoreTimes)
TodayAction.CompleteHabit(vm.id)
else
TodayAction.UndoCompleteHabit(vm.id)
)
}
})
completeAnim.start()
}
private fun startCompleteAnimation(
view: View,
vm: HabitViewModel
) {
val hcb = view.habitCompletedBackground
val half = hcb.width / 2
val completeAnim = ViewAnimationUtils.createCircularReveal(
hcb,
half, half,
0f, half.toFloat()
)
completeAnim.duration = shortAnimTime
completeAnim.interpolator = AccelerateDecelerateInterpolator()
completeAnim.addListener(object : AnimatorListenerAdapter() {
override fun onAnimationStart(animation: Animator?) {
hcb.visible()
}
override fun onAnimationEnd(animation: Animator?) {
view.habitIcon.setImageDrawable(
IconicsDrawable(view.context).normalIcon(vm.icon, R.color.md_white)
)
view.habitStreak.setTextColor(colorRes(R.color.md_white))
dispatch(
if (vm.canBeCompletedMoreTimes) TodayAction.CompleteHabit(vm.id)
else TodayAction.UndoCompleteHabit(vm.id)
)
}
})
completeAnim.start()
}
}
data class CompletedQuestViewModel(
override val id: String,
val name: String,
val tags: List<TagViewModel>,
val startTime: String,
@ColorRes val color: Int,
val icon: IIcon,
val isRepeating: Boolean,
val isFromChallenge: Boolean
) : RecyclerViewViewModel
inner class CompletedQuestAdapter :
BaseRecyclerViewAdapter<CompletedQuestViewModel>(R.layout.item_agenda_quest) {
override fun onBindViewModel(
vm: CompletedQuestViewModel,
view: View,
holder: SimpleViewHolder
) {
val span = SpannableString(vm.name)
span.setSpan(StrikethroughSpan(), 0, vm.name.length, 0)
view.questName.text = span
view.questIcon.backgroundTintList =
ColorStateList.valueOf(colorRes(vm.color))
view.questIcon.setImageDrawable(smallListItemIcon(vm.icon))
if (vm.tags.isNotEmpty()) {
view.questTagName.visible()
renderTag(view, vm.tags.first())
} else {
view.questTagName.gone()
}
view.questStartTime.text = vm.startTime
view.questRepeatIndicator.visibility =
if (vm.isRepeating) View.VISIBLE else View.GONE
view.questChallengeIndicator.visibility =
if (vm.isFromChallenge) View.VISIBLE else View.GONE
view.onDebounceClick {
navigateFromRoot().toCompletedQuest(vm.id, VerticalChangeHandler())
}
}
private fun renderTag(view: View, tag: TagViewModel) {
view.questTagName.text = tag.name
TextViewCompat.setTextAppearance(
view.questTagName,
R.style.TextAppearance_AppCompat_Caption
)
val indicator = view.questTagName.compoundDrawablesRelative[0] as GradientDrawable
indicator.mutate()
val size = ViewUtils.dpToPx(8f, view.context).toInt()
indicator.setSize(size, size)
indicator.setColor(colorRes(tag.color))
view.questTagName.setCompoundDrawablesRelativeWithIntrinsicBounds(
indicator,
null,
null,
null
)
}
}
private val TodayViewState.levelText
get() = "$level"
private val TodayViewState.levelProgressText
get() = "$levelXpProgress / $levelXpMaxProgress"
private val TodayViewState.healthProgressText
get() = "$health / $maxHealth"
private val TodayViewState.gemsText
get() = LongFormatter.format(activity!!, gems.toLong())
private val TodayViewState.lifeCoinsText
get() = LongFormatter.format(activity!!, coins.toLong())
private val TodayViewState.petMoodColor
get() = AndroidPetMood.valueOf(pet!!.state.name).color
private val TodayViewState.incompleteQuestViewModels: List<TodayItemViewModel>
get() =
quests!!.incomplete.map {
when (it) {
is CreateTodayItemsUseCase.TodayItem.UnscheduledSection ->
TodayItemViewModel.Section(stringRes(R.string.unscheduled))
is CreateTodayItemsUseCase.TodayItem.MorningSection ->
TodayItemViewModel.Section(stringRes(R.string.morning))
is CreateTodayItemsUseCase.TodayItem.AfternoonSection ->
TodayItemViewModel.Section(stringRes(R.string.afternoon))
is CreateTodayItemsUseCase.TodayItem.EveningSection ->
TodayItemViewModel.Section(stringRes(R.string.evening))
is CreateTodayItemsUseCase.TodayItem.QuestItem -> {
val quest = it.quest
TodayItemViewModel.QuestViewModel(
id = quest.id,
name = quest.name,
tags = quest.tags.map { t ->
TagViewModel(
t.name,
AndroidColor.valueOf(t.color.name).color500
)
},
startTime = QuestStartTimeFormatter.formatWithDuration(
quest,
activity!!,
shouldUse24HourFormat
),
color = quest.color.androidColor.color500,
icon = quest.icon?.let { ic -> AndroidIcon.valueOf(ic.name).icon }
?: Ionicons.Icon.ion_checkmark,
isRepeating = quest.isFromRepeatingQuest,
isFromChallenge = quest.isFromChallenge
)
}
is CreateTodayItemsUseCase.TodayItem.EventItem -> {
val event = it.event
TodayItemViewModel.EventViewModel(
id = event.name,
name = event.name,
startTime = formatStartTime(event),
color = event.color
)
}
}
}
private fun formatStartTime(event: Event): String {
val start = event.startTime
val end = start.plus(event.duration.intValue)
return "${start.toString(shouldUse24HourFormat)} - ${end.toString(shouldUse24HourFormat)}"
}
private val TodayViewState.habitItemViewModels: List<HabitViewModel>
get() =
todayHabitItems!!.map {
val habit = it.habit
HabitViewModel(
id = habit.id,
name = habit.name,
color = habit.color.androidColor.color500,
secondaryColor = habit.color.androidColor.color100,
icon = habit.icon.androidIcon.icon,
timesADay = habit.timesADay,
isCompleted = it.isCompleted,
canBeCompletedMoreTimes = it.canBeCompletedMoreTimes,
isGood = habit.isGood,
streak = habit.streak.current,
isBestStreak = it.isBestStreak,
progress = it.completedCount,
maxProgress = if (habit.isUnlimited) 1
else habit.timesADay,
completedCount = it.completedCount,
showCompletedCount = it.habit.isUnlimited && it.completedCount > 1
)
}
private val TodayViewState.completedQuestViewModels: List<CompletedQuestViewModel>
get() =
quests!!.complete.map {
CompletedQuestViewModel(
id = it.id,
name = it.name,
tags = it.tags.map { t ->
TagViewModel(
t.name,
AndroidColor.valueOf(t.color.name).color500
)
},
startTime = QuestStartTimeFormatter.formatWithDuration(
it,
activity!!,
shouldUse24HourFormat
),
color = R.color.md_grey_500,
icon = it.icon?.let { ic -> AndroidIcon.valueOf(ic.name).icon }
?: Ionicons.Icon.ion_checkmark,
isRepeating = it.isFromRepeatingQuest,
isFromChallenge = it.isFromChallenge
)
}
} | gpl-3.0 | 754bccd0ac2c40d56403b4cc1ebac3f2 | 36.220034 | 120 | 0.582582 | 5.498609 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/IntroduceImportAliasIntention.kt | 2 | 2094 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.intentions
import com.intellij.codeInsight.FileModificationService
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.util.TextRange
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.codeinsight.api.classic.intentions.SelfTargetingRangeIntention
import org.jetbrains.kotlin.idea.imports.canBeAddedToImport
import org.jetbrains.kotlin.idea.refactoring.introduce.introduceImportAlias.KotlinIntroduceImportAliasHandler
import org.jetbrains.kotlin.idea.references.mainReference
import org.jetbrains.kotlin.idea.references.resolveMainReferenceToDescriptors
import org.jetbrains.kotlin.psi.KtInstanceExpressionWithLabel
import org.jetbrains.kotlin.psi.KtNameReferenceExpression
class IntroduceImportAliasIntention : SelfTargetingRangeIntention<KtNameReferenceExpression>(
KtNameReferenceExpression::class.java,
KotlinBundle.lazyMessage("introduce.import.alias")
) {
override fun applicabilityRange(element: KtNameReferenceExpression): TextRange? {
if (element.parent is KtInstanceExpressionWithLabel || element.mainReference.getImportAlias() != null) return null
val targets = element.resolveMainReferenceToDescriptors()
if (targets.isEmpty() || targets.any { !it.canBeAddedToImport() }) return null
// It is a workaround: KTIJ-20142 actual FE could not report ambiguous references for alias for a broken reference
if (element.mainReference.resolve() == null) return null
return element.textRange
}
override fun startInWriteAction(): Boolean = false
override fun applyTo(element: KtNameReferenceExpression, editor: Editor?) {
if (editor == null || !FileModificationService.getInstance().preparePsiElementsForWrite(element)) return
val project = element.project
KotlinIntroduceImportAliasHandler.doRefactoring(project, editor, element)
}
} | apache-2.0 | 193cd6c67228224ce8558a6b80497855 | 54.131579 | 158 | 0.80086 | 5.17037 | false | false | false | false |
GunoH/intellij-community | plugins/completion-ml-ranking-models/src/com/jetbrains/completion/ml/ranker/ExperimentPhpMLRankingProvider.kt | 4 | 877 | package com.jetbrains.completion.ml.ranker
import com.intellij.completion.ml.ranker.ExperimentModelProvider
import com.intellij.internal.ml.catboost.CatBoostJarCompletionModelProvider
import com.intellij.internal.ml.completion.DecoratingItemsPolicy
import com.intellij.lang.Language
class ExperimentPhpMLRankingProvider : CatBoostJarCompletionModelProvider(
CompletionRankingModelsBundle.message("ml.completion.experiment.model.php"), "php_features_exp", "php_model_exp"), ExperimentModelProvider {
override fun isLanguageSupported(language: Language): Boolean = language.id.compareTo("PHP", ignoreCase = true) == 0
override fun experimentGroupNumber(): Int = 13
override fun getDecoratingPolicy(): DecoratingItemsPolicy = DecoratingItemsPolicy.Composite(
DecoratingItemsPolicy.ByAbsoluteThreshold(4.0),
DecoratingItemsPolicy.ByRelativeThreshold(2.5)
)
} | apache-2.0 | 13b6841a67f522fb392b15eb78c7a29c | 45.210526 | 142 | 0.827822 | 4.845304 | false | false | false | false |
jk1/intellij-community | platform/dvcs-impl/src/com/intellij/dvcs/ui/RepositoryChangesBrowserNode.kt | 3 | 2451 | // 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.dvcs.ui
import com.intellij.dvcs.DvcsUtil.getShortRepositoryName
import com.intellij.dvcs.repo.Repository
import com.intellij.openapi.project.Project
import com.intellij.openapi.vcs.changes.ui.ChangesBrowserNode
import com.intellij.openapi.vcs.changes.ui.ChangesBrowserNodeRenderer
import com.intellij.openapi.vcs.impl.ProjectLevelVcsManagerImpl
import com.intellij.ui.SimpleTextAttributes.REGULAR_ATTRIBUTES
import com.intellij.util.ui.ColorIcon
import com.intellij.util.ui.JBUI.scale
import com.intellij.util.ui.UIUtil
import com.intellij.vcs.log.impl.VcsLogManager.findLogProviders
import com.intellij.vcs.log.impl.VcsProjectLog
import com.intellij.vcs.log.ui.VcsLogColorManagerImpl
import com.intellij.vcs.log.ui.VcsLogColorManagerImpl.getBackgroundColor
private val ICON_SIZE = scale(14)
class RepositoryChangesBrowserNode(repository: Repository) : ChangesBrowserNode<Repository>(repository) {
private val colorManager = getColorManager(repository.project)
override fun render(renderer: ChangesBrowserNodeRenderer, selected: Boolean, expanded: Boolean, hasFocus: Boolean) {
renderer.icon = ColorIcon(ICON_SIZE, getBackgroundColor(colorManager.getRootColor(getUserObject().root)))
renderer.append(" $textPresentation", REGULAR_ATTRIBUTES)
if (renderer.isShowingLocalChanges) {
val localBranch = getUserObject().currentBranchName
if (localBranch != null) {
renderer.append(" ($localBranch", REGULAR_ATTRIBUTES)
val remoteBranch = getUserObject().currentRemoteBranchName
if (remoteBranch != null) {
renderer.append(" ${UIUtil.rightArrow()} $remoteBranch")
}
renderer.append(")")
}
}
appendCount(renderer)
}
override fun getSortWeight(): Int = REPOSITORY_SORT_WEIGHT
override fun compareUserObjects(o2: Repository): Int = getShortRepositoryName(getUserObject()).compareTo(getShortRepositoryName(o2), true)
override fun getTextPresentation(): String = getShortRepositoryName(getUserObject())
companion object {
fun getColorManager(project: Project): VcsLogColorManagerImpl = VcsProjectLog.getInstance(project).logManager?.colorManager ?: VcsLogColorManagerImpl(
findLogProviders(ProjectLevelVcsManagerImpl.getInstance(project).allVcsRoots.asList(), project).keys)
}
} | apache-2.0 | 12c66bbc7a0df196f6282fc546ab899d | 47.078431 | 154 | 0.787842 | 4.704415 | false | false | false | false |
chrisbanes/snapper | sample/src/main/java/dev/chrisbanes/snapper/sample/MainActivity.kt | 1 | 4098 | /*
* Copyright 2021 Chris Banes
*
* 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 dev.chrisbanes.snapper.sample
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.BackHandler
import androidx.activity.compose.setContent
import androidx.compose.animation.Crossfade
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material.ExperimentalMaterialApi
import androidx.compose.material.Icon
import androidx.compose.material.IconButton
import androidx.compose.material.ListItem
import androidx.compose.material.Scaffold
import androidx.compose.material.Text
import androidx.compose.material.TopAppBar
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ArrowBack
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import dev.chrisbanes.snapper.sample.ui.theme.SnapperTheme
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
Samples(appTitle = title.toString())
}
}
}
@OptIn(ExperimentalMaterialApi::class)
@Composable
private fun Samples(appTitle: String) {
SnapperTheme {
var currentSample by remember { mutableStateOf<Sample?>(null) }
Scaffold(
topBar = {
TopAppBar(
title = { Text(text = currentSample?.title ?: appTitle) },
navigationIcon = {
if (currentSample != null) {
IconButton(onClick = { currentSample = null }) {
Icon(
imageVector = Icons.Default.ArrowBack,
contentDescription = "Navigate back"
)
}
}
},
modifier = Modifier.fillMaxWidth(),
)
},
modifier = Modifier.fillMaxSize()
) { contentPadding ->
BackHandler(enabled = currentSample != null) {
currentSample = null
}
Crossfade(
targetState = currentSample,
modifier = Modifier.padding(contentPadding)
) { sample ->
if (sample != null) {
sample.content()
} else {
LazyColumn(Modifier.fillMaxSize()) {
items(Samples) { sample ->
ListItem(
text = { Text(text = sample.title) },
modifier = Modifier
.fillMaxWidth()
.clickable { currentSample = sample }
)
}
}
}
}
}
}
}
@Preview(showBackground = true)
@Composable
fun DefaultPreview() {
Samples(appTitle = "Snapper Sample")
}
| apache-2.0 | 80858cc67d60a84b341fcd56939b8e3f | 34.947368 | 78 | 0.611274 | 5.363874 | false | false | false | false |
ktorio/ktor | ktor-server/ktor-server-plugins/ktor-server-locations/jvm/test/io/ktor/tests/locations/Verifiers.kt | 1 | 1122 | /*
* Copyright 2014-2019 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license.
*/
package io.ktor.tests.locations
import io.ktor.http.*
import io.ktor.server.testing.*
import kotlin.test.*
fun TestApplicationEngine.urlShouldBeHandled(url: String, content: String? = null) {
on("making get request to $url") {
val result = handleRequest {
uri = url
method = HttpMethod.Get
}
it("should have a response with OK status") {
assertEquals(HttpStatusCode.OK, result.response.status())
}
if (content != null) {
it("should have a response with content '$content'") {
assertEquals(content, result.response.content)
}
}
}
}
fun TestApplicationEngine.urlShouldBeUnhandled(url: String) {
on("making post request to $url") {
val result = handleRequest {
uri = url
method = HttpMethod.Post
}
it("should not be handled") {
assertFalse(result.response.status()!!.isSuccess())
}
}
}
| apache-2.0 | 463f5841a73737574033c7ffa5fd0b5e | 28.526316 | 119 | 0.599822 | 4.4 | false | true | false | false |
carrotengineer/Warren | src/main/kotlin/engineer/carrot/warren/warren/handler/rpl/Rpl473Handler.kt | 2 | 1219 | package engineer.carrot.warren.warren.handler.rpl
import engineer.carrot.warren.kale.IKaleHandler
import engineer.carrot.warren.kale.irc.message.rfc1459.rpl.Rpl473Message
import engineer.carrot.warren.warren.loggerFor
import engineer.carrot.warren.warren.state.CaseMappingState
import engineer.carrot.warren.warren.state.JoiningChannelLifecycle
import engineer.carrot.warren.warren.state.JoiningChannelsState
class Rpl473Handler(val channelsState: JoiningChannelsState, val caseMappingState: CaseMappingState) : IKaleHandler<Rpl473Message> {
private val LOGGER = loggerFor<Rpl473Handler>()
override val messageType = Rpl473Message::class.java
override fun handle(message: Rpl473Message, tags: Map<String, String?>) {
val channel = channelsState[message.channel]
if (channel == null) {
LOGGER.warn("got an invite only channel reply for a channel we don't think we're joining: $message")
LOGGER.trace("channels state: $channelsState")
return
}
LOGGER.warn("channel is invite only, failed to join: $channel")
channel.status = JoiningChannelLifecycle.FAILED
LOGGER.trace("new channels state: $channelsState")
}
}
| isc | 8d21d59b05616eab44c9f22adaa7b000 | 37.09375 | 132 | 0.747334 | 4.448905 | false | false | false | false |
code-disaster/lwjgl3 | modules/lwjgl/glfw/src/templates/kotlin/glfw/templates/GLFWNativeWin32.kt | 4 | 3162 | /*
* Copyright LWJGL. All rights reserved.
* License terms: https://www.lwjgl.org/license
*/
package glfw.templates
import org.lwjgl.generator.*
import glfw.*
import core.windows.*
val GLFWNativeWin32 = "GLFWNativeWin32".nativeClass(Module.GLFW, nativeSubPath = "windows", prefix = "GLFW", binding = GLFW_BINDING_DELEGATE) {
documentation = "Native bindings to the GLFW library's Win32 native access functions."
charUTF8.const.p(
"GetWin32Adapter",
"""
Returns the adapter device name of the specified monitor.
Note: This function may be called from any thread. Access is not synchronized.
""",
GLFWmonitor.p("monitor", "the GLFW monitor"),
returnDoc =
"""
the UTF-8 encoded adapter device name (for example `\\.\DISPLAY1`) of the specified monitor, or #NULL if an error occurred.
Possible errors include #NOT_INITIALIZED.
""",
since = "version 3.1"
)
charUTF8.const.p(
"GetWin32Monitor",
"""
Returns the display device name of the specified monitor.
Note: This function may be called from any thread. Access is not synchronized.
""",
GLFWmonitor.p("monitor", "the GLFW monitor"),
returnDoc =
"""
the UTF-8 encoded display device name (for example `\\.\DISPLAY1\Monitor0`) of the specified monitor, or #NULL if an error occurred.
Possible errors include #NOT_INITIALIZED.
""",
since = "version 3.1"
)
HWND(
"GetWin32Window",
"""
Returns the {@code HWND} of the specified window.
The {@code HDC} associated with the window can be queried with the
${url("https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-getdc", "GetDC")} function.
${code("""
HDC dc = GetDC(glfwGetWin32Window(window));""")}
This DC is private and does not need to be released.
Note: This function may be called from any thread. Access is not synchronized.
""",
GLFWwindow.p("window", "the GLFW window"),
returnDoc =
"""
the {@code HWND} of the specified window, or #NULL if an error occurred.
Possible errors include #NOT_INITIALIZED.
""",
since = "version 3.0"
)
GLFWwindow.p(
"AttachWin32Window",
"""
Wraps an existing {@code HWND} in a new GLFW window object.
This function creates a GLFW window object and its associated OpenGL or OpenGL ES context for an existing {@code HWND}. The {@code HWND} is not
destroyed by GLFW.
This function may be called from any thread.
<b>LWJGL</b>: This functionality is experimental and not officially supported by GLFW yet.
""",
HWND("handle", "the {@code HWND} to attach to the window object"),
nullable..GLFWwindow.p("share", "the window whose context to share resources with, or #NULL to not share resources"),
returnDoc = "the handle of the created window, or #NULL if an error occurred",
since = "version 3.3"
)
} | bsd-3-clause | a905d5c1a9b7773c90635fd3ce2ba39f | 31.947917 | 151 | 0.619228 | 4.517143 | false | false | false | false |
dbrant/apps-android-wikipedia | app/src/main/java/org/wikipedia/notifications/NotificationPollBroadcastReceiver.kt | 1 | 14577 | package org.wikipedia.notifications
import android.annotation.SuppressLint
import android.app.AlarmManager
import android.app.PendingIntent
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.os.SystemClock
import androidx.annotation.StringRes
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers
import io.reactivex.rxjava3.schedulers.Schedulers
import org.wikipedia.Constants
import org.wikipedia.R
import org.wikipedia.WikipediaApp
import org.wikipedia.analytics.NotificationFunnel
import org.wikipedia.auth.AccountUtil
import org.wikipedia.csrf.CsrfTokenClient
import org.wikipedia.dataclient.ServiceFactory
import org.wikipedia.dataclient.WikiSite
import org.wikipedia.dataclient.mwapi.MwException
import org.wikipedia.main.MainActivity
import org.wikipedia.push.WikipediaFirebaseMessagingService
import org.wikipedia.settings.Prefs
import org.wikipedia.util.ReleaseUtil
import org.wikipedia.util.log.L
import java.util.*
import java.util.concurrent.TimeUnit
class NotificationPollBroadcastReceiver : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
when {
Intent.ACTION_BOOT_COMPLETED == intent.action -> {
// To test the BOOT_COMPLETED intent:
// `adb shell am broadcast -a android.intent.action.BOOT_COMPLETED`
// Update our channel name, if needed.
L.d("channel=" + ReleaseUtil.getChannel(context))
startPollTask(context)
}
ACTION_POLL == intent.action -> {
if (!AccountUtil.isLoggedIn) {
return
}
maybeShowLocalNotificationForEditorReactivation(context)
if (!Prefs.notificationPollEnabled()) {
return
}
// If push notifications are active, then don't actually do any polling.
if (WikipediaFirebaseMessagingService.isUsingPush()) {
return
}
LOCALLY_KNOWN_NOTIFICATIONS = Prefs.getLocallyKnownNotifications()
pollNotifications(context)
}
ACTION_CANCEL == intent.action -> {
NotificationFunnel.processIntent(intent)
}
}
}
companion object {
const val ACTION_POLL = "action_notification_poll"
const val ACTION_CANCEL = "action_notification_cancel"
const val TYPE_MULTIPLE = "multiple"
private const val TYPE_LOCAL = "local"
private const val MAX_LOCALLY_KNOWN_NOTIFICATIONS = 32
private const val FIRST_EDITOR_REACTIVATION_NOTIFICATION_SHOW_ON_DAY = 3
private const val SECOND_EDITOR_REACTIVATION_NOTIFICATION_SHOW_ON_DAY = 7
private val DBNAME_WIKI_SITE_MAP = mutableMapOf<String, WikiSite>()
private val DBNAME_WIKI_NAME_MAP = mutableMapOf<String, String>()
private var LOCALLY_KNOWN_NOTIFICATIONS = Prefs.getLocallyKnownNotifications()
@JvmStatic
fun startPollTask(context: Context) {
val alarmManager = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager
try {
alarmManager.setInexactRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,
SystemClock.elapsedRealtime(),
TimeUnit.MINUTES.toMillis((context.resources.getInteger(R.integer.notification_poll_interval_minutes) /
if (Prefs.isSuggestedEditsReactivationTestEnabled() && !ReleaseUtil.isDevRelease) 10 else 1).toLong()),
getAlarmPendingIntent(context))
} catch (e: Exception) {
// There seems to be a Samsung-specific issue where it doesn't update the existing
// alarm correctly and adds it as a new one, and eventually hits the limit of 500
// concurrent alarms, causing a crash.
L.e(e)
}
}
fun stopPollTask(context: Context) {
val alarmManager = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager
alarmManager.cancel(getAlarmPendingIntent(context))
}
private fun getAlarmPendingIntent(context: Context): PendingIntent {
val intent = Intent(context, NotificationPollBroadcastReceiver::class.java)
intent.action = ACTION_POLL
return PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT)
}
fun getCancelNotificationPendingIntent(context: Context, id: Long, type: String?): PendingIntent {
val intent = Intent(context, NotificationPollBroadcastReceiver::class.java)
.setAction(ACTION_CANCEL)
.putExtra(Constants.INTENT_EXTRA_NOTIFICATION_ID, id)
.putExtra(Constants.INTENT_EXTRA_NOTIFICATION_TYPE, type)
return PendingIntent.getBroadcast(context, id.toInt(), intent, 0)
}
@SuppressLint("CheckResult")
@JvmStatic
fun pollNotifications(context: Context) {
ServiceFactory.get(WikipediaApp.getInstance().wikiSite).lastUnreadNotification
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe({ response ->
var lastNotificationTime = ""
if (response.query()!!.notifications()!!.list() != null &&
response.query()!!.notifications()!!.list()!!.size > 0) {
for (n in response.query()!!.notifications()!!.list()!!) {
if (n.utcIso8601 > lastNotificationTime) {
lastNotificationTime = n.utcIso8601
}
}
}
if (lastNotificationTime <= Prefs.getRemoteNotificationsSeenTime()) {
// we're in sync!
return@subscribe
}
Prefs.setRemoteNotificationsSeenTime(lastNotificationTime)
retrieveNotifications(context)
}) { t ->
if (t is MwException && t.error.title == "login-required") {
assertLoggedIn()
}
L.e(t)
}
}
private fun assertLoggedIn() {
// Attempt to get a dummy CSRF token, which should automatically re-log us in explicitly,
// and should automatically log us out if the credentials are no longer valid.
CsrfTokenClient(WikipediaApp.getInstance().wikiSite).token
.subscribeOn(Schedulers.io())
.subscribe()
}
@SuppressLint("CheckResult")
private fun retrieveNotifications(context: Context) {
DBNAME_WIKI_SITE_MAP.clear()
DBNAME_WIKI_NAME_MAP.clear()
ServiceFactory.get(WikipediaApp.getInstance().wikiSite).unreadNotificationWikis
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe({ response ->
val wikiMap = response.query()!!.unreadNotificationWikis()
val wikis = mutableListOf<String>()
wikis.addAll(wikiMap!!.keys)
for (dbName in wikiMap.keys) {
if (wikiMap[dbName]!!.source != null) {
DBNAME_WIKI_SITE_MAP[dbName] = WikiSite(wikiMap[dbName]!!.source!!.base)
DBNAME_WIKI_NAME_MAP[dbName] = wikiMap[dbName]!!.source!!.title
}
}
getFullNotifications(context, wikis)
}) { t -> L.e(t) }
}
private fun getFullNotifications(context: Context, foreignWikis: List<String?>) {
ServiceFactory.get(WikipediaApp.getInstance().wikiSite).getAllNotifications(if (foreignWikis.isEmpty()) "*" else foreignWikis.joinToString("|"), "!read", null)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe({ response -> onNotificationsComplete(context, response.query()!!.notifications()!!.list()!!) }) { t -> L.e(t) }
}
private fun onNotificationsComplete(context: Context, notifications: List<Notification>) {
if (notifications.isEmpty() || Prefs.isSuggestedEditsHighestPriorityEnabled()) {
return
}
var locallyKnownModified = false
val knownNotifications = mutableListOf<Notification>()
val notificationsToDisplay = mutableListOf<Notification>()
for (n in notifications) {
knownNotifications.add(n)
if (LOCALLY_KNOWN_NOTIFICATIONS.contains(n.key())) {
continue
}
LOCALLY_KNOWN_NOTIFICATIONS.add(n.key())
if (LOCALLY_KNOWN_NOTIFICATIONS.size > MAX_LOCALLY_KNOWN_NOTIFICATIONS) {
LOCALLY_KNOWN_NOTIFICATIONS.removeAt(0)
}
notificationsToDisplay.add(n)
locallyKnownModified = true
}
if (notificationsToDisplay.size > 2) {
NotificationPresenter.showMultipleUnread(context, notificationsToDisplay.size)
} else {
for (n in notificationsToDisplay) {
// TODO: remove these conditions when the time is right.
if (n.category().startsWith(Notification.CATEGORY_SYSTEM) && Prefs.notificationWelcomeEnabled() ||
n.category() == Notification.CATEGORY_EDIT_THANK && Prefs.notificationThanksEnabled() ||
n.category() == Notification.CATEGORY_THANK_YOU_EDIT && Prefs.notificationMilestoneEnabled() ||
n.category() == Notification.CATEGORY_REVERTED && Prefs.notificationRevertEnabled() ||
n.category() == Notification.CATEGORY_EDIT_USER_TALK && Prefs.notificationUserTalkEnabled() ||
n.category() == Notification.CATEGORY_LOGIN_FAIL && Prefs.notificationLoginFailEnabled() ||
n.category().startsWith(Notification.CATEGORY_MENTION) && Prefs.notificationMentionEnabled() ||
Prefs.showAllNotifications()) {
NotificationPresenter.showNotification(context, n, (if (DBNAME_WIKI_NAME_MAP.containsKey(n.wiki())) DBNAME_WIKI_NAME_MAP[n.wiki()] else n.wiki())!!)
}
}
}
if (locallyKnownModified) {
Prefs.setLocallyKnownNotifications(LOCALLY_KNOWN_NOTIFICATIONS)
}
if (knownNotifications.size > MAX_LOCALLY_KNOWN_NOTIFICATIONS) {
markItemsAsRead(knownNotifications.subList(0, knownNotifications.size - MAX_LOCALLY_KNOWN_NOTIFICATIONS))
}
}
private fun markItemsAsRead(items: List<Notification>) {
val notificationsPerWiki = mutableMapOf<WikiSite, MutableList<Notification>>()
for (item in items) {
val wiki = if (DBNAME_WIKI_SITE_MAP.containsKey(item.wiki())) DBNAME_WIKI_SITE_MAP[item.wiki()]!! else WikipediaApp.getInstance().wikiSite
if (!notificationsPerWiki.containsKey(wiki)) {
notificationsPerWiki[wiki] = mutableListOf()
}
notificationsPerWiki[wiki]!!.add(item)
}
for (wiki in notificationsPerWiki.keys) {
markRead(wiki, notificationsPerWiki[wiki]!!, false)
}
}
fun markRead(wiki: WikiSite, notifications: List<Notification>, unread: Boolean) {
val idListStr = notifications.joinToString("|")
CsrfTokenClient(wiki, WikipediaApp.getInstance().wikiSite).token
.subscribeOn(Schedulers.io())
.flatMap {
ServiceFactory.get(wiki).markRead(it, if (unread) null else idListStr, if (unread) idListStr else null)
.subscribeOn(Schedulers.io())
}
.subscribe({ }, { L.e(it) })
}
private fun maybeShowLocalNotificationForEditorReactivation(context: Context) {
if (Prefs.getLastDescriptionEditTime() == 0L || WikipediaApp.getInstance().isAnyActivityResumed) {
return
}
var days = TimeUnit.MILLISECONDS.toDays(System.currentTimeMillis() - Prefs.getLastDescriptionEditTime())
if (Prefs.isSuggestedEditsReactivationTestEnabled()) {
days = TimeUnit.MILLISECONDS.toMinutes(System.currentTimeMillis() - Prefs.getLastDescriptionEditTime())
}
if (days in FIRST_EDITOR_REACTIVATION_NOTIFICATION_SHOW_ON_DAY until SECOND_EDITOR_REACTIVATION_NOTIFICATION_SHOW_ON_DAY && !Prefs.isSuggestedEditsReactivationPassStageOne()) {
Prefs.setSuggestedEditsReactivationPassStageOne(true)
showSuggestedEditsLocalNotification(context, R.string.suggested_edits_reactivation_notification_stage_one)
} else if (days >= SECOND_EDITOR_REACTIVATION_NOTIFICATION_SHOW_ON_DAY && Prefs.isSuggestedEditsReactivationPassStageOne()) {
Prefs.setSuggestedEditsReactivationPassStageOne(false)
showSuggestedEditsLocalNotification(context, R.string.suggested_edits_reactivation_notification_stage_two)
}
}
fun showSuggestedEditsLocalNotification(context: Context, @StringRes description: Int) {
val intent = NotificationPresenter.addIntentExtras(MainActivity.newIntent(context).putExtra(Constants.INTENT_EXTRA_GO_TO_SE_TAB, true), 0, TYPE_LOCAL)
NotificationPresenter.showNotification(context, NotificationPresenter.getDefaultBuilder(context, 0, TYPE_LOCAL), 0,
context.getString(R.string.suggested_edits_reactivation_notification_title),
context.getString(description), context.getString(description),
R.drawable.ic_mode_edit_white_24dp, R.color.accent50, false, intent)
}
}
}
| apache-2.0 | a47970f24ffe2d22172f91a235bed4d5 | 52.395604 | 188 | 0.601427 | 5.418959 | false | false | false | false |
songful/PocketHub | app/src/main/java/com/github/pockethub/android/ui/item/news/NewsItem.kt | 1 | 4113 | package com.github.pockethub.android.ui.item.news
import android.text.SpannableStringBuilder
import android.text.TextUtils
import android.util.Log
import androidx.text.bold
import com.github.pockethub.android.R
import com.github.pockethub.android.util.AvatarLoader
import com.github.pockethub.android.util.TimeUtils
import com.meisolsson.githubsdk.model.GitHubEvent
import com.meisolsson.githubsdk.model.GitHubEventType.*
import com.meisolsson.githubsdk.model.User
import com.xwray.groupie.kotlinandroidextensions.Item
import com.xwray.groupie.kotlinandroidextensions.ViewHolder
import kotlinx.android.synthetic.main.news_item.*
open class NewsItem(
private val avatarLoader: AvatarLoader,
val gitHubEvent: GitHubEvent
) : Item(gitHubEvent.id()!!.hashCode().toLong()) {
override fun getLayout(): Int = R.layout.news_item
override fun bind(holder: ViewHolder, position: Int) {
avatarLoader.bind(holder.iv_avatar, gitHubEvent.actor())
holder.tv_event_date.text = TimeUtils.getRelativeTime(gitHubEvent.createdAt())
}
protected fun boldActor(text: SpannableStringBuilder, event: GitHubEvent?) =
boldUser(text, event?.actor())
protected fun boldUser(text: SpannableStringBuilder, user: User?) {
text.bold {
append(user?.login())
}
}
protected fun boldRepo(text: SpannableStringBuilder, event: GitHubEvent?) {
val repo = event?.repo()
text.bold {
append(repo?.repoWithUserName())
}
}
protected fun boldRepoName(text: SpannableStringBuilder, event: GitHubEvent?) {
val repo = event?.repo()
val name = repo?.repoWithUserName()
if (!TextUtils.isEmpty(name)) {
val slash: Int = name!!.indexOf('/')
if (slash != -1 && slash + 1 < name.length) {
text.bold {
append(name.substring(slash + 1))
}
}
}
}
protected fun appendText(text: SpannableStringBuilder, toAppend: String?) {
var textToAppend: String? = toAppend ?: return
textToAppend = textToAppend!!.trim { it <= ' ' }
if (textToAppend.isEmpty()) {
return
}
text.append(textToAppend)
}
companion object {
/**
* Create a instance of the [NewsItem] corresponding to the event type.
*
* @param avatars Avatar image loader
* @param item Event item
* @return Subclass of [NewsItem] corresponding to the event type
*/
@JvmStatic
fun createNewsItem(avatars: AvatarLoader, item: GitHubEvent): NewsItem? =
when (item.type()) {
CommitCommentEvent -> CommitCommentEventItem(avatars, item)
CreateEvent -> CreateEventItem(avatars, item)
DeleteEvent -> DeleteEventItem(avatars, item)
DownloadEvent, ReleaseEvent -> ReleaseEventItem(avatars, item)
FollowEvent -> FollowEventItem(avatars, item)
ForkEvent -> ForkEventItem(avatars, item)
GistEvent -> GistEventItem(avatars, item)
GollumEvent -> GollumEventItem(avatars, item)
IssueCommentEvent -> IssueCommentEventItem(avatars, item)
IssuesEvent -> IssuesEventItem(avatars, item)
MemberEvent -> MemberEventItem(avatars, item)
PublicEvent -> PublicEventItem(avatars, item)
PullRequestEvent -> PullRequestEventItem(avatars, item)
PullRequestReviewCommentEvent ->
PullRequestReviewCommentEventItem(avatars, item)
PushEvent -> PushEventItem(avatars, item)
TeamAddEvent -> TeamAddEventItem(avatars, item)
WatchEvent -> WatchEventItem(avatars, item)
else -> {
Log.d("NewsItem", "Event type not allowed: " + item.type()!!)
null
}
}
}
}
| apache-2.0 | 50af86c4b08a33b12c947ca09c037ebe | 38.548077 | 86 | 0.608072 | 5.021978 | false | false | false | false |
intellij-solidity/intellij-solidity | src/main/kotlin/me/serce/solidity/lang/types/types.kt | 1 | 10918 | package me.serce.solidity.lang.types
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.RecursionManager
import com.intellij.psi.util.CachedValueProvider
import com.intellij.psi.util.CachedValuesManager
import com.intellij.psi.util.PsiModificationTracker
import me.serce.solidity.lang.psi.*
import me.serce.solidity.lang.psi.impl.Linearizable
import me.serce.solidity.lang.resolve.SolResolver
import me.serce.solidity.lang.types.SolInteger.Companion.UINT_160
import java.math.BigInteger
import java.util.*
// http://solidity.readthedocs.io/en/develop/types.html
enum class ContextType {
SUPER,
EXTERNAL
}
enum class Usage {
VARIABLE,
CALLABLE
}
interface SolMember {
fun getName(): String?
fun parseType(): SolType
fun resolveElement(): SolNamedElement?
fun getPossibleUsage(contextType: ContextType): Usage?
}
interface SolType {
fun isAssignableFrom(other: SolType): Boolean
fun getMembers(project: Project): List<SolMember> {
return emptyList()
}
}
interface SolPrimitiveType : SolType
interface SolNumeric : SolPrimitiveType
object SolUnknown : SolPrimitiveType {
override fun isAssignableFrom(other: SolType): Boolean = false
override fun toString() = "<unknown>"
}
object SolBoolean : SolPrimitiveType {
override fun isAssignableFrom(other: SolType): Boolean =
other == SolBoolean
override fun toString() = "bool"
}
object SolString : SolPrimitiveType {
override fun isAssignableFrom(other: SolType): Boolean =
other == SolString
override fun toString() = "string"
}
object SolAddress : SolPrimitiveType {
override fun isAssignableFrom(other: SolType): Boolean =
when (other) {
is SolAddress -> true
is SolContract -> true
else -> UINT_160.isAssignableFrom(other)
}
override fun toString() = "address"
override fun getMembers(project: Project): List<SolMember> {
return SolInternalTypeFactory.of(project).addressType.ref.functionDefinitionList
}
}
data class SolInteger(val unsigned: Boolean, val size: Int) : SolNumeric {
companion object {
val UINT_160 = SolInteger(true, 160)
val UINT_256 = SolInteger(true, 256)
fun parse(name: String): SolInteger {
var unsigned = false
var size = 256
var typeName = name
if (name.startsWith("u")) {
unsigned = true
typeName = typeName.substring(1)
}
if (!typeName.startsWith("int")) {
throw IllegalArgumentException("Incorrect int typename: $name")
}
typeName = typeName.substring(3)
if (typeName.isNotEmpty()) {
try {
size = Integer.parseInt(typeName)
} catch (e: NumberFormatException) {
throw IllegalArgumentException("Incorrect int typename: $name")
}
}
return SolInteger(unsigned, size)
}
fun inferType(numberLiteral: SolNumberLiteral): SolInteger {
return inferIntegerType(numberLiteral.toBigInteger())
}
private fun inferIntegerType(value: BigInteger): SolInteger {
if (value == BigInteger.ZERO) return SolInteger(true, 8)
val positive = value >= BigInteger.ZERO
if (positive) {
var shifts = 0
var current = value
while (current != BigInteger.ZERO) {
shifts++
current = current.shiftRight(8)
}
return SolInteger(positive, shifts * 8)
} else {
var shifts = 1
var current = value.abs().minus(BigInteger.ONE).shiftRight(7)
while (current != BigInteger.ZERO) {
shifts++
current = current.shiftRight(8)
}
return SolInteger(positive, shifts * 8)
}
}
private fun SolNumberLiteral.toBigInteger(): BigInteger {
this.decimalNumber?.let {
return it.text.replace("_", "").toBigInteger()
}
this.hexNumber?.let {
return it.text.removePrefix("0x").toBigInteger(16)
}
this.scientificNumber?.let {
return it.text.replace("_", "").lowercase().toBigDecimal().toBigInteger()
}
//todo
return BigInteger.ZERO
}
}
override fun isAssignableFrom(other: SolType): Boolean =
when (other) {
is SolInteger -> {
if (this.unsigned && !other.unsigned) {
false
} else if (!this.unsigned && other.unsigned) {
this.size - 2 >= other.size
} else {
this.size >= other.size
}
}
else -> false
}
override fun toString() = "${if (unsigned) "u" else ""}int$size"
}
data class SolContract(val ref: SolContractDefinition) : SolType, Linearizable<SolContract> {
override fun linearize(): List<SolContract> {
return RecursionManager.doPreventingRecursion(ref, true) {
CachedValuesManager.getCachedValue(ref) {
CachedValueProvider.Result.create(super.linearize(), PsiModificationTracker.MODIFICATION_COUNT)
}
} ?: emptyList()
}
override fun linearizeParents(): List<SolContract> {
return RecursionManager.doPreventingRecursion(ref, true) {
CachedValuesManager.getCachedValue(ref) {
CachedValueProvider.Result.create(super.linearizeParents(), PsiModificationTracker.MODIFICATION_COUNT)
}
} ?: emptyList()
}
override fun getParents(): List<SolContract> {
return ref.supers
.flatMap { it.reference?.multiResolve() ?: emptyList() }
.filterIsInstance<SolContractDefinition>()
.map { SolContract(it) }
.reversed()
}
override fun isAssignableFrom(other: SolType): Boolean =
when (other) {
is SolContract -> {
other.ref == ref
|| other.ref.collectSupers.flatMap { SolResolver.resolveTypeNameUsingImports(it) }.contains(ref)
}
else -> false
}
override fun getMembers(project: Project): List<SolMember> {
return SolResolver.resolveContractMembers(ref, false)
}
override fun toString() = ref.name ?: ref.text ?: "$ref"
}
data class SolStruct(val ref: SolStructDefinition) : SolType {
override fun isAssignableFrom(other: SolType): Boolean =
other is SolStruct && ref == other.ref
override fun toString() = ref.name ?: ref.text ?: "$ref"
override fun getMembers(project: Project): List<SolMember> {
return ref.variableDeclarationList
.map { SolStructVariableDeclaration(it) }
}
}
data class SolStructVariableDeclaration(
val ref: SolVariableDeclaration
) : SolMember {
override fun getName(): String? = ref.name
override fun parseType(): SolType = getSolType(ref.typeName)
override fun resolveElement(): SolNamedElement? = ref
override fun getPossibleUsage(contextType: ContextType) = Usage.VARIABLE
}
data class SolEnum(val ref: SolEnumDefinition) : SolType {
override fun isAssignableFrom(other: SolType): Boolean =
other is SolEnum && ref == other.ref
override fun toString() = ref.name ?: ref.text ?: "$ref"
override fun getMembers(project: Project): List<SolMember> {
return ref.enumValueList
}
}
data class SolMapping(val from: SolType, val to: SolType) : SolType {
override fun isAssignableFrom(other: SolType): Boolean =
other is SolMapping && from == other.from && to == other.to
override fun toString(): String {
return "mapping($from => $to)"
}
}
data class SolTuple(val types: List<SolType>) : SolType {
override fun isAssignableFrom(other: SolType): Boolean = false
override fun toString(): String {
return "(${types.joinToString(separator = ",") { it.toString() }})"
}
}
sealed class SolArray(val type: SolType) : SolType {
class SolStaticArray(type: SolType, val size: Int) : SolArray(type) {
override fun isAssignableFrom(other: SolType): Boolean =
other is SolStaticArray && other.type == type && other.size == size
override fun toString() = "$type[$size]"
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as SolStaticArray
if (size != other.size) return false
if (type != other.type) return false
return true
}
override fun hashCode(): Int {
return Objects.hash(size, type)
}
}
class SolDynamicArray(type: SolType) : SolArray(type) {
override fun isAssignableFrom(other: SolType): Boolean =
other is SolDynamicArray && type == other.type
override fun toString() = "$type[]"
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as SolDynamicArray
if (type != other.type) return false
return true
}
override fun hashCode(): Int {
return type.hashCode()
}
override fun getMembers(project: Project): List<SolMember> {
return SolInternalTypeFactory.of(project).arrayType.ref
.functionDefinitionList
.map {
val parameters = it.parseParameters()
.map { pair -> pair.first to type }
BuiltinCallable(parameters, it.parseType(), it.name, it) }
}
}
}
object SolBytes : SolPrimitiveType {
override fun isAssignableFrom(other: SolType): Boolean =
other == SolBytes
override fun toString() = "bytes"
}
data class SolFixedBytes(val size: Int): SolPrimitiveType {
override fun toString() = "bytes$size"
override fun isAssignableFrom(other: SolType): Boolean =
other is SolFixedBytes && other.size <= size
companion object {
fun parse(name: String): SolFixedBytes {
return if (name.startsWith("bytes")) {
SolFixedBytes(name.substring(5).toInt())
} else {
throw java.lang.IllegalArgumentException("should start with bytes")
}
}
}
}
private const val INTERNAL_INDICATOR = "_sol1_s"
fun internalise(name: String): String = "$name$INTERNAL_INDICATOR"
fun isInternal(name: String): Boolean = name.endsWith(INTERNAL_INDICATOR)
fun deInternalise(name: String): String = when {
name.endsWith(INTERNAL_INDICATOR) -> name.removeSuffix(INTERNAL_INDICATOR)
else -> name
}
class BuiltinType(
private val name: String,
private val members: List<SolMember>
) : SolType {
override fun isAssignableFrom(other: SolType): Boolean = false
override fun getMembers(project: Project): List<SolMember> = members
override fun toString(): String = name
}
data class BuiltinCallable(
private val parameters: List<Pair<String?, SolType>>,
private val returnType: SolType,
private val memberName: String?,
private val resolvedElement: SolNamedElement?,
private val possibleUsage: Usage = Usage.CALLABLE
) : SolCallable, SolMember {
override val callablePriority: Int
get() = 1000
override fun parseParameters(): List<Pair<String?, SolType>> = parameters
override fun parseType(): SolType = returnType
override fun resolveElement(): SolNamedElement? = resolvedElement
override fun getName(): String? = memberName
override fun getPossibleUsage(contextType: ContextType) = possibleUsage
}
| mit | 53ede99c9c290b28d22193c9173336a2 | 28.588076 | 110 | 0.68007 | 4.423825 | false | false | false | false |
android/privacy-codelab | PhotoLog_End/src/main/java/com/example/photolog_end/ui/theme/Theme.kt | 1 | 2778 | /*
* 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.photolog_end.ui.theme
import android.app.Activity
import android.os.Build
import androidx.compose.foundation.isSystemInDarkTheme
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.darkColorScheme
import androidx.compose.material3.dynamicDarkColorScheme
import androidx.compose.material3.dynamicLightColorScheme
import androidx.compose.material3.lightColorScheme
import androidx.compose.runtime.Composable
import androidx.compose.runtime.SideEffect
import androidx.compose.ui.graphics.toArgb
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalView
import androidx.core.view.ViewCompat
private val DarkColorScheme = darkColorScheme(
primary = Purple80,
secondary = PurpleGrey80,
tertiary = Pink80
)
private val LightColorScheme = lightColorScheme(
primary = Purple40,
secondary = PurpleGrey40,
tertiary = Pink40
/* Other default colors to override
background = Color(0xFFFFFBFE),
surface = Color(0xFFFFFBFE),
onPrimary = Color.White,
onSecondary = Color.White,
onTertiary = Color.White,
onBackground = Color(0xFF1C1B1F),
onSurface = Color(0xFF1C1B1F),
*/
)
@Composable
fun PhotoGoodTheme(
darkTheme: Boolean = isSystemInDarkTheme(),
// Dynamic color is available on Android 12+
dynamicColor: Boolean = true,
content: @Composable () -> Unit
) {
val colorScheme = when {
dynamicColor && Build.VERSION.SDK_INT >= Build.VERSION_CODES.S -> {
val context = LocalContext.current
if (darkTheme) dynamicDarkColorScheme(context) else dynamicLightColorScheme(context)
}
darkTheme -> DarkColorScheme
else -> LightColorScheme
}
val view = LocalView.current
if (!view.isInEditMode) {
SideEffect {
(view.context as Activity).window.statusBarColor = colorScheme.primary.toArgb()
ViewCompat.getWindowInsetsController(view)?.isAppearanceLightStatusBars = darkTheme
}
}
MaterialTheme(
colorScheme = colorScheme,
typography = Typography,
content = content
)
} | apache-2.0 | a95a4a9c58df0bf4661f811786b9269c | 32.083333 | 96 | 0.732541 | 4.554098 | false | false | false | false |
DreierF/MyTargets | app/src/main/java/de/dreier/mytargets/base/db/dao/StandardRoundDAO.kt | 1 | 2632 | /*
* Copyright (C) 2018 Florian Dreier
*
* This file is part of MyTargets.
*
* MyTargets is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2
* as published by the Free Software Foundation.
*
* MyTargets is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
package de.dreier.mytargets.base.db.dao
import androidx.room.*
import de.dreier.mytargets.shared.models.augmented.AugmentedStandardRound
import de.dreier.mytargets.shared.models.db.RoundTemplate
import de.dreier.mytargets.shared.models.db.StandardRound
@Dao
abstract class StandardRoundDAO {
@Query("SELECT * FROM `StandardRound`")
abstract fun loadStandardRounds(): List<StandardRound>
@Query("SELECT * FROM `StandardRound` WHERE `id` = :id")
abstract fun loadStandardRound(id: Long): StandardRound
@Transaction
open fun loadAugmentedStandardRound(id: Long): AugmentedStandardRound =
AugmentedStandardRound(loadStandardRound(id), loadRoundTemplates(id).toMutableList())
@Query("SELECT * FROM `StandardRound` WHERE `id` = :id")
abstract fun loadStandardRoundOrNull(id: Long): StandardRound?
@Query("SELECT * FROM `StandardRound` WHERE `name` LIKE :query AND `club` != 512")
abstract fun getAllSearch(query: String): List<StandardRound>
@Query("SELECT * FROM `RoundTemplate` WHERE `standardRoundId` = :id ORDER BY `index`")
abstract fun loadRoundTemplates(id: Long): List<RoundTemplate>
@Insert
abstract fun insertStandardRound(round: StandardRound): Long
@Update
abstract fun updateStandardRound(round: StandardRound)
@Insert
abstract fun insertRoundTemplate(round: RoundTemplate): Long
@Query("DELETE FROM `RoundTemplate` WHERE `standardRoundId` = (:id)")
abstract fun deleteRoundTemplates(id: Long)
@Transaction
open fun saveStandardRound(standardRound: StandardRound, roundTemplates: List<RoundTemplate>) {
if(standardRound.id == 0L) {
standardRound.id = insertStandardRound(standardRound)
} else {
updateStandardRound(standardRound)
}
deleteRoundTemplates(standardRound.id)
for (roundTemplate in roundTemplates) {
roundTemplate.standardRoundId = standardRound.id
roundTemplate.id = insertRoundTemplate(roundTemplate)
}
}
@Delete
abstract fun deleteStandardRound(standardRound: StandardRound)
}
| gpl-2.0 | 0810546b4dd6c67e387b55f08651b8ec | 35.555556 | 99 | 0.728723 | 4.733813 | false | false | false | false |
DemonWav/MinecraftDevIntelliJ | src/main/kotlin/com/demonwav/mcdev/nbt/lang/NbttParserDefinition.kt | 1 | 2145 | /*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2020 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev.nbt.lang
import com.demonwav.mcdev.nbt.lang.gen.parser.NbttParser
import com.demonwav.mcdev.nbt.lang.gen.psi.NbttTypes
import com.intellij.lang.ASTNode
import com.intellij.lang.LanguageUtil
import com.intellij.lang.ParserDefinition
import com.intellij.openapi.project.Project
import com.intellij.psi.FileViewProvider
import com.intellij.psi.TokenType
import com.intellij.psi.tree.IFileElementType
import com.intellij.psi.tree.TokenSet
class NbttParserDefinition : ParserDefinition {
override fun createParser(project: Project) = NbttParser()
override fun createLexer(project: Project) = NbttLexerAdapter()
override fun createFile(viewProvider: FileViewProvider) = NbttFile(viewProvider)
override fun spaceExistenceTypeBetweenTokens(left: ASTNode, right: ASTNode) =
LanguageUtil.canStickTokensTogetherByLexer(left, right, NbttLexerAdapter())!!
override fun getStringLiteralElements() = STRING_LITERALS
override fun getWhitespaceTokens() = WHITE_SPACES
override fun getFileNodeType() = FILE
override fun createElement(node: ASTNode) = NbttTypes.Factory.createElement(node)!!
override fun getCommentTokens() = TokenSet.EMPTY!!
companion object {
val WHITE_SPACES = TokenSet.create(TokenType.WHITE_SPACE)
val STRING_LITERALS = TokenSet.create(NbttTypes.STRING_LITERAL)
val FILE = IFileElementType(NbttLanguage)
val NBTT_CONTAINERS = TokenSet.create(
NbttTypes.BYTE_ARRAY,
NbttTypes.INT_ARRAY,
NbttTypes.LONG_ARRAY,
NbttTypes.COMPOUND,
NbttTypes.LIST
)
val NBTT_OPEN_BRACES = TokenSet.create(
NbttTypes.LPAREN,
NbttTypes.LBRACE,
NbttTypes.LBRACKET
)
val NBTT_CLOSE_BRACES = TokenSet.create(
NbttTypes.RPAREN,
NbttTypes.RBRACE,
NbttTypes.RBRACKET
)
val NBTT_BRACES = TokenSet.orSet(NBTT_OPEN_BRACES, NBTT_CLOSE_BRACES)
}
}
| mit | 6fb8184ff7b811d50bb7211d2f7e8f18 | 31.014925 | 87 | 0.707692 | 4.603004 | false | false | false | false |
peruukki/SimpleCurrencyConverter | app/src/main/java/com/peruukki/simplecurrencyconverter/fragments/ConvertFragment.kt | 1 | 5778 | package com.peruukki.simplecurrencyconverter.fragments
import android.os.Bundle
import android.support.v4.app.Fragment
import android.text.Editable
import android.text.TextWatcher
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.EditText
import android.widget.TextView
import com.peruukki.simplecurrencyconverter.R
import com.peruukki.simplecurrencyconverter.models.ConversionRate
import com.peruukki.simplecurrencyconverter.utils.Settings
import java.text.DecimalFormat
import java.text.DecimalFormatSymbols
import java.text.ParseException
import java.util.*
/**
* A [Fragment] that contains currency conversion widgets.
*/
/**
* Creates an instance of the fragment.
*/
class ConvertFragment : Fragment() {
private val mInputAmountFormatter = getAmountFormatter("###,###.##")
private val mOutputAmountFormatter = getAmountFormatter("###,##0.00")
private var mAllowAmountUpdate = true
private var mConversionRate: ConversionRate? = null
/**
* Updates the conversion rate and currencies to show from shared preferences.
*/
fun updateConversionRate() {
mConversionRate = Settings.readConversionRate(activity)
val view = view
updateLabels(view!!)
clearAmounts(view)
}
override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?,
savedInstanceState: Bundle?): View? {
val view = inflater!!.inflate(R.layout.fragment_convert, container, false)
mConversionRate = Settings.readConversionRate(activity)
updateLabels(view)
addCurrencyListeners(view)
return view
}
private fun updateLabels(view: View) {
val firstLabel = view.findViewById(R.id.first_currency_label) as TextView
firstLabel.text = mConversionRate!!.variableCurrency
val secondLabel = view.findViewById(R.id.second_currency_label) as TextView
secondLabel.text = mConversionRate!!.fixedCurrency
}
private fun clearAmounts(view: View) {
val firstAmount = view.findViewById(R.id.first_currency_amount) as EditText
firstAmount.setText("")
val secondAmount = view.findViewById(R.id.second_currency_amount) as EditText
secondAmount.setText("")
}
private fun addCurrencyListeners(view: View) {
val firstAmount = view.findViewById(R.id.first_currency_amount) as EditText
val secondAmount = view.findViewById(R.id.second_currency_amount) as EditText
addAmountChangedListeners(firstAmount, secondAmount, false)
addFocusChangedListener(firstAmount)
addAmountChangedListeners(secondAmount, firstAmount, true)
addFocusChangedListener(secondAmount)
}
private fun addAmountChangedListeners(editText: EditText, otherEditText: EditText,
isFixedCurrency: Boolean) {
editText.addTextChangedListener(object : TextWatcher {
override fun afterTextChanged(s: Editable) {
updateOtherAmount(s, otherEditText, isFixedCurrency)
}
override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {}
override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {}
})
}
private fun addFocusChangedListener(editText: EditText) {
editText.setOnFocusChangeListener { v, hasFocus ->
if (!hasFocus) {
updateLostFocusAmount(v as EditText)
}
}
}
private fun updateOtherAmount(changedText: Editable, editTextToChange: EditText,
isFixedCurrency: Boolean) {
if (!mAllowAmountUpdate) {
mAllowAmountUpdate = true
return
}
mAllowAmountUpdate = false
val formattedOutputAmount: String
if (changedText.toString().isEmpty()) {
formattedOutputAmount = ""
} else {
val multiplier = if (isFixedCurrency)
mConversionRate!!.fixedCurrencyInVariableCurrencyRate
else
mConversionRate!!.variableCurrencyInFixedCurrencyRate
val inputAmount = parseDecimal(changedText.toString())
val outputAmount = multiplier * inputAmount
formattedOutputAmount = formatAmount(outputAmount, mOutputAmountFormatter)
}
editTextToChange.setText(formattedOutputAmount)
}
private fun updateLostFocusAmount(editText: EditText) {
val amount = parseDecimal(editText.text.toString())
val formattedOutputAmount = formatAmount(amount, mInputAmountFormatter)
// Empty the other amount too if the amount that lost focus was emptied
mAllowAmountUpdate = formattedOutputAmount.isEmpty()
editText.setText(formattedOutputAmount)
}
private fun parseDecimal(amount: String): Float {
val trimmedAmount = amount.replace(" ".toRegex(), "")
try {
return mInputAmountFormatter.parse(trimmedAmount).toFloat()
} catch (e: NumberFormatException) {
return 0f
} catch (e: ParseException) {
return 0f
}
}
private fun formatAmount(amount: Float, formatter: DecimalFormat): String {
val formattedValue = formatter.format(amount.toDouble())
return if (formattedValue == EMPTY_AMOUNT) "" else formattedValue
}
private fun getAmountFormatter(formatPattern: String): DecimalFormat {
val symbols = DecimalFormatSymbols(Locale.US)
symbols.groupingSeparator = ' '
return DecimalFormat(formatPattern, symbols)
}
companion object {
private const val EMPTY_AMOUNT = "0"
}
}
| mit | 3dd8eeea87488d15199f9226182d34fc | 34.888199 | 98 | 0.678782 | 5.136 | false | false | false | false |
nick-rakoczy/Conductor | database-plugin/src/test/java/urn/conductor/sql/TestPlans.kt | 1 | 296 | package urn.conductor.sql
import org.junit.Test
import urn.conductor.Main
class TestPlans {
@Test fun test() = run("sql-test.xml")
private fun file(name: String) = arrayOf("plugins=.", "file=./src/test/resources/$name")
private fun run(name: String) = file(name).let(Main.Companion::main)
} | gpl-3.0 | 8125f88fbacdbe17d39757f49e138c57 | 26 | 89 | 0.719595 | 3.083333 | false | true | false | false |
jogy/jmoney | src/main/kotlin/name/gyger/jmoney/options/LegacySessionMigrator.kt | 1 | 7566 | package name.gyger.jmoney.options
import name.gyger.jmoney.account.Account
import name.gyger.jmoney.account.AccountRepository
import name.gyger.jmoney.account.Entry
import name.gyger.jmoney.account.EntryRepository
import name.gyger.jmoney.category.CategoryRepository
import name.gyger.jmoney.session.SessionRepository
import net.sf.jmoney.XMLReader
import net.sf.jmoney.model.*
import org.slf4j.LoggerFactory
import org.springframework.stereotype.Component
import java.io.InputStream
import java.util.*
@Component
class LegacySessionMigrator(private val sessionRepository: SessionRepository,
private val accountRepository: AccountRepository,
private val categoryRepository: CategoryRepository,
private val entryRepository: EntryRepository) {
private val session = name.gyger.jmoney.session.Session(name.gyger.jmoney.category.Category(),
name.gyger.jmoney.category.Category(), name.gyger.jmoney.category.Category())
private val oldToNewCategoryMap = HashMap<Category, name.gyger.jmoney.category.Category>()
private val entryToOldCategoryMap = HashMap<Entry, Category>()
private val oldToNewDoubleEntryMap = HashMap<DoubleEntry, Entry>()
lateinit var oldSession: Session
fun importSession(inputStream: InputStream) {
oldSession = XMLReader.readSessionFromInputStream(inputStream)
sessionRepository.save(session)
mapCategoryNode(oldSession.categories.rootNode, null)
mapRootCategoryToSession()
mapCategoryToEntry()
mapDoubleEntries()
}
private fun mapCategoryNode(node: net.sf.jmoney.model.CategoryNode, parent: name.gyger.jmoney.category.Category?) {
val oldCat = node.category
if (oldCat is net.sf.jmoney.model.Account) {
mapAccount(oldCat, parent)
} else {
mapCategory(node, parent)
}
}
private fun mapAccount(oldAcc: net.sf.jmoney.model.Account, parent: name.gyger.jmoney.category.Category?) {
val acc = Account()
acc.abbreviation = oldAcc.abbrevation
acc.accountNumber = oldAcc.accountNumber
acc.bank = oldAcc.bank
acc.name = oldAcc.categoryName
acc.comment = oldAcc.comment
acc.currencyCode = oldAcc.currencyCode
acc.minBalance = oldAcc.minBalance
acc.startBalance = oldAcc.startBalance
acc.session = session
acc.parent = parent
accountRepository.save(acc)
oldToNewCategoryMap.put(oldAcc, acc)
mapEntries(oldAcc, acc)
}
private fun mapCategory(node: net.sf.jmoney.model.CategoryNode,
parent: name.gyger.jmoney.category.Category?) {
val oldCat = node.category
val cat = createCategory(parent, oldCat)
(0 until node.childCount)
.map { node.getChildAt(it) as CategoryNode }
.forEach { mapCategoryNode(it, cat) }
}
private fun mapRootCategoryToSession() {
val oldRootCat = oldSession.categories.rootNode.category
val rootCat = oldToNewCategoryMap[oldRootCat]
session.rootCategory = rootCat!!
}
private fun mapCategoryToEntry() {
for ((e, oldCat) in entryToOldCategoryMap) {
val c = oldToNewCategoryMap[oldCat]
if (c == null) {
val root = session.rootCategory
createCategory(root, oldCat)
}
e.category = c
}
}
private fun mapDoubleEntries() {
for ((oldDe, de) in oldToNewDoubleEntryMap) {
val otherDe = oldToNewDoubleEntryMap[oldDe.other]
if (otherDe == null) {
log.warn("Dangling double entry: " + oldDe.description + ", " + oldDe.fullCategoryName + ", " + oldDe.date)
}
de.other = otherDe
}
}
private fun createCategory(parent: name.gyger.jmoney.category.Category?,
oldCat: net.sf.jmoney.model.Category): name.gyger.jmoney.category.Category {
val cat = name.gyger.jmoney.category.Category()
// Workaround for redundant split category.
when (oldCat) {
is SplitCategory -> {
cat.type = name.gyger.jmoney.category.Category.Type.SPLIT
session.splitCategory = cat
}
is TransferCategory -> {
cat.type = name.gyger.jmoney.category.Category.Type.TRANSFER
session.transferCategory = cat
}
is RootCategory -> {
cat.type = name.gyger.jmoney.category.Category.Type.ROOT
session.transferCategory = cat
}
}
cat.name = oldCat.categoryName
cat.parent = parent
categoryRepository.save(cat)
oldToNewCategoryMap.put(oldCat, cat)
if (oldCat is SplitCategory) {
// Workaround for redundant split category.
val oldCat2 = oldSession.categories.splitNode.category
oldToNewCategoryMap.put(oldCat2, cat)
}
return cat
}
private fun mapEntries(oldAcc: net.sf.jmoney.model.Account, acc: Account) {
oldAcc.entries
.map { it as net.sf.jmoney.model.Entry }
.forEach {
if (it is SplittedEntry) {
mapSplitEntry(acc, it)
} else {
mapEntryOrDoubleEntry(acc, null, it)
}
}
}
private fun mapSplitEntry(acc: Account, oldEntry: net.sf.jmoney.model.Entry) {
val oldSe = oldEntry as net.sf.jmoney.model.SplittedEntry
val splitEntry = Entry()
mapEntry(splitEntry, acc, null, oldSe)
for (o in oldSe.entries) {
val oldSubEntry = o as net.sf.jmoney.model.Entry
oldSubEntry.date = oldSe.date // fix for wrong date from old model
mapEntryOrDoubleEntry(null, splitEntry, oldSubEntry)
}
}
private fun mapEntryOrDoubleEntry(acc: Account?, splitEntry: Entry?, oldEntry: net.sf.jmoney.model.Entry) {
if (oldEntry is net.sf.jmoney.model.DoubleEntry) {
mapDoubleEntry(Entry(), acc, splitEntry, oldEntry)
} else {
mapEntry(Entry(), acc, splitEntry, oldEntry)
}
}
private fun mapDoubleEntry(doubleEntry: Entry, acc: Account?, splitEntry: Entry?, oldDe: net.sf.jmoney.model.DoubleEntry) {
mapEntry(doubleEntry, acc, splitEntry, oldDe)
oldToNewDoubleEntryMap.put(oldDe, doubleEntry)
}
private fun mapEntry(e: Entry, acc: Account?, splitEntry: Entry?, oldEntry: net.sf.jmoney.model.Entry) {
e.account = acc
e.splitEntry = splitEntry
e.amount = oldEntry.amount
e.creation = oldEntry.creation
e.date = oldEntry.date
e.description = oldEntry.description ?: ""
e.memo = oldEntry.memo ?: ""
e.status = entryStates[oldEntry.status]
e.valuta = oldEntry.valuta
// Category might not exist yet, so this is done in a second pass.
val oldCat = oldEntry.category
if (oldCat != null) {
entryToOldCategoryMap.put(e, oldCat)
}
entryRepository.save(e)
}
companion object {
private val log = LoggerFactory.getLogger(OptionsService::class.java)
private val entryStates = mapOf(
Pair(0, null),
Pair(1, Entry.Status.RECONCILING),
Pair(2, Entry.Status.CLEARED)
)
}
}
| mit | 32f5ffc154a84851455dede4a73bcbf1 | 36.270936 | 127 | 0.623447 | 4.546875 | false | false | false | false |
HITGIF/SchoolPower | app/src/main/java/com/carbonylgroup/schoolpower/activities/CategoryActivity.kt | 1 | 9657 | package com.carbonylgroup.schoolpower.activities
import android.app.AlertDialog
import android.graphics.Color
import android.support.v7.widget.LinearLayoutManager
import android.widget.ArrayAdapter
import com.carbonylgroup.schoolpower.R
import com.carbonylgroup.schoolpower.adapter.CourseDetailAdapter
import com.carbonylgroup.schoolpower.data.AssignmentItem
import com.carbonylgroup.schoolpower.data.CategoryWeightData
import com.carbonylgroup.schoolpower.data.Subject
import com.carbonylgroup.schoolpower.utils.CategorySettingsDialog
import com.carbonylgroup.schoolpower.utils.Utils
import com.github.mikephil.charting.animation.Easing
import com.github.mikephil.charting.data.PieData
import com.github.mikephil.charting.data.PieDataSet
import com.github.mikephil.charting.data.PieEntry
import com.github.mikephil.charting.formatter.PercentFormatter
import kotlinx.android.synthetic.main.activity_category.*
import kotlinx.android.synthetic.main.add_assignment_dialog.view.*
import kotlinx.android.synthetic.main.content_category.*
import org.json.JSONObject
import java.util.*
class CategoryActivity : BaseActivity() {
private lateinit var categoriesWeights: CategoryWeightData
override fun initActivity() {
super.initActivity()
setContentView(R.layout.activity_category)
setSupportActionBar(toolbar)
categoriesWeights = CategoryWeightData(utils)
val subject = intent.getSerializableExtra("subject") as Subject
try {
subject.recalculateGrades(categoriesWeights)
initChart(subject)
initRecycler(subject)
} catch (e: Exception) {
utils.errorHandler(e)
}
fab.setOnClickListener {
CategorySettingsDialog(this, categoriesWeights, subject,
subject.grades[subject.getLatestTermName(utils, false, true)]!!) {
categoriesWeights = CategoryWeightData(utils)
subject.recalculateGrades(categoriesWeights)
initChart(subject)
}.show()
}
if(utils.isDeveloperMode()) {
fab.setOnLongClickListener {
val categories = subject.grades[subject.getLatestTermName(utils, false, true)]!!.calculatedGrade.categories.keys.toList()
// construct view
val dialog = [email protected](R.layout.add_assignment_dialog, null)
dialog.categorySpinner.adapter = ArrayAdapter(this@CategoryActivity, R.layout.term_selection_spinner, categories)
// construct dialog
val gpaDialogBuilder = AlertDialog.Builder(this@CategoryActivity)
gpaDialogBuilder.setView(dialog)
gpaDialogBuilder.setTitle("Add Assignment")
gpaDialogBuilder.setPositiveButton(getString(R.string.sweet)) { _, _ ->
val json = JSONObject(
"""
{
"description": "",
"name": "dummy",
"percentage": "86.96",
"letterGrade": "A",
"date": "2017-09-11T16:00:00.000Z",
"weight": "1",
"includeInFinalGrade": "1",
"terms": ["T1","T2","S1","S2","Y1"]
}
""")
json.put("category", categories[dialog.categorySpinner.selectedItemId.toInt()])
json.put("score", dialog.mark.text.toString().toDoubleOrNull() ?: 100)
json.put("pointsPossible", dialog.markPossible.text.toString().toDoubleOrNull()?: 100)
json.put("weight", dialog.weight.text.toString().toDoubleOrNull() ?: 1.0)
subject.assignments.add(AssignmentItem(json))
subject.recalculateGrades(categoriesWeights)
initChart(subject)
}
gpaDialogBuilder.create().show()
true
}
}
}
private fun initRecycler(subject: Subject) {
assignmentsRecycler.layoutManager = LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false)
val name = subject.getLatestTermName(utils, false, true) ?: return
val grades = subject.grades[name] ?: return
val categories = grades.calculatedGrade.categories.keys.toList()
assignmentsRecycler.adapter = CourseDetailAdapter(this, subject, false, categories,
fun(assignments:List<AssignmentItem>, filter:String):List<AssignmentItem> {
return assignments.filter { it.category == filter }
}
)
}
private fun initChart(subject: Subject) {
val name = subject.getLatestTermName(utils, false, true) ?: return
val grade = subject.grades[name] ?: return
toolbar_layout.title = "$name %.2f%%".format(
grade.calculatedGrade.getEstimatedPercentageGrade()*100)
/*
var text = ""
for ((cname, cate) in grade.calculatedGrade.categories){
text += ("\n$cname ${cate.score}/${cate.maxScore} (%.2f%%) weight ${cate.weight} " +
"Contributing a loss of %.2f%%")
.format(cate.getPercentage()*100, cate.weight*(1-cate.getPercentage()))
}
cates.text = text
*/
val entries = ArrayList<PieEntry>()
val percentages = ArrayList<android.util.Pair<Float, Float>>()
val colors = ArrayList<Int>()
var count = 0
for ((cname, cate) in grade.calculatedGrade.categories){
entries.add(PieEntry(cate.weight.toFloat(), cname))
percentages.add(android.util.Pair(cate.score.toFloat(), cate.maxScore.toFloat()))
colors.add(Color.parseColor(Utils.chartColorList[count++ % Utils.chartColorList.size]))
}
setRadarPieChartData(entries, percentages, colors)
val entries2 = ArrayList<PieEntry>()
for ((cname, cate) in grade.calculatedGrade.categories){
if(cate.getPercentage().isNaN()) continue
entries2.add(PieEntry((cate.weight * (1.0f - cate.getPercentage())).toFloat(), cname))
}
setPieChartData(entries2, colors)
}
private fun setRadarPieChartData(entries: ArrayList<PieEntry>,
percentages: ArrayList<android.util.Pair<Float, Float>>,
colors: ArrayList<Int>) {
val primaryColor = utils.getPrimaryTextColor()
pieRadarChart.rotationAngle = 0f
pieRadarChart.isRotationEnabled = true
pieRadarChart.isDrawHoleEnabled = false
pieRadarChart.description.isEnabled = false
pieRadarChart.transparentCircleRadius = 61f
pieRadarChart.isHighlightPerTapEnabled = false
pieRadarChart.dragDecelerationFrictionCoef = 0.95f
pieRadarChart.setUsePercentValues(true)
pieRadarChart.setEntryLabelTextSize(11f)
pieRadarChart.setTransparentCircleAlpha(110)
pieRadarChart.setEntryLabelColor(primaryColor)
pieRadarChart.setEntryInnerLabelColor(Color.WHITE)
pieRadarChart.setTransparentCircleColor(Color.WHITE)
pieRadarChart.setExtraOffsets(15f, 0f, 15f, 0f)
val dataSet = PieDataSet(entries, "Categories")
dataSet.colors = colors
dataSet.sliceSpace = 3f
dataSet.selectionShift = 5f
dataSet.valueLinePart1Length = .4f
dataSet.valueLinePart2Length = .7f
dataSet.valueLineColor = primaryColor
dataSet.valueTextColor = primaryColor
dataSet.valueLinePart1OffsetPercentage = 80f
dataSet.xValuePosition = PieDataSet.ValuePosition.OUTSIDE_SLICE
dataSet.yValuePosition = PieDataSet.ValuePosition.OUTSIDE_SLICE
val data = PieData(dataSet)
data.setValueFormatter(PercentFormatter())
data.setValueTextSize(11f)
pieRadarChart.data = data
pieRadarChart.legend.isEnabled = false
pieRadarChart.invalidate()
pieRadarChart.highlightValues(null)
pieRadarChart.setDrawRadiiPairs(percentages)
pieRadarChart.animateY(1200, Easing.EasingOption.EaseInOutCubic)
}
private fun setPieChartData(entries: ArrayList<PieEntry>,
colors: ArrayList<Int>) {
val primaryColor = utils.getPrimaryTextColor()
pieChart.rotationAngle = 0f
pieChart.isRotationEnabled = true
pieChart.isDrawHoleEnabled = false
pieChart.description.isEnabled = false
pieChart.transparentCircleRadius = 61f
pieChart.isHighlightPerTapEnabled = false
pieChart.dragDecelerationFrictionCoef = 0.95f
pieChart.setUsePercentValues(true)
pieChart.setEntryLabelTextSize(11f)
pieChart.setTransparentCircleAlpha(110)
pieChart.setEntryLabelColor(primaryColor)
pieChart.setTransparentCircleColor(Color.WHITE)
pieChart.setExtraOffsets(5f, 5f, 5f, 5f)
val dataSet = PieDataSet(entries, "Categories")
dataSet.colors = colors
dataSet.sliceSpace = 3f
dataSet.selectionShift = 5f
dataSet.valueLinePart1Length = .4f
dataSet.valueLinePart2Length = .7f
dataSet.valueLineColor = primaryColor
dataSet.valueTextColor = primaryColor
dataSet.valueLinePart1OffsetPercentage = 80f
dataSet.xValuePosition = PieDataSet.ValuePosition.INSIDE_SLICE
dataSet.yValuePosition = PieDataSet.ValuePosition.INSIDE_SLICE
val data = PieData(dataSet)
data.setValueFormatter(PercentFormatter())
data.setValueTextSize(11f)
pieChart.data = data
pieChart.legend.isEnabled = false
pieChart.invalidate()
pieChart.highlightValues(null)
pieChart.animateY(1200, Easing.EasingOption.EaseInOutCubic)
}
}
| apache-2.0 | d1c925f6030374a4c4b65fcc576ce938 | 41.355263 | 137 | 0.668945 | 4.887146 | false | false | false | false |
square/okhttp | okhttp/src/jvmMain/kotlin/okhttp3/internal/connection/ReusePlan.kt | 2 | 1066 | /*
* Copyright (C) 2022 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package okhttp3.internal.connection
/** Reuse a connection from the pool. */
internal class ReusePlan(
val connection: RealConnection,
) : RoutePlanner.Plan {
override val isReady = true
override fun connectTcp() = error("already connected")
override fun connectTlsEtc() = error("already connected")
override fun handleSuccess() = connection
override fun cancel() = error("unexpected cancel")
override fun retry() = error("unexpected retry")
}
| apache-2.0 | 1dc4d665d49c752b0d2726e48c7ac042 | 30.352941 | 75 | 0.731707 | 4.333333 | false | false | false | false |
derkork/spek | spek-tests/src/test/kotlin/org/jetbrains/spek/api/ListenerTest.kt | 1 | 4310 | package org.jetbrains.spek.api
import org.junit.Test as test
import org.junit.Before as before
import org.mockito.*
import org.junit.*
import org.jetbrains.spek.console.ActionStatusReporter
import org.jetbrains.spek.console.WorkflowReporter
import org.jetbrains.spek.console.CompositeWorkflowReporter
public class ListenerTest {
val firstStepListener = Mockito.mock(ActionStatusReporter::class.java)
val firstListener = Mockito.mock(WorkflowReporter::class.java)!!
val secondStepListener = Mockito.mock(ActionStatusReporter::class.java)
val secondListener = Mockito.mock(WorkflowReporter::class.java)!!
val throwable = RuntimeException("Test Exception")
val multicaster = CompositeWorkflowReporter()
@before fun setup() {
multicaster.addListener(firstListener)
multicaster.addListener(secondListener)
}
@test fun givenExecution() {
//given two listener with following conditions.
BDDMockito.given(firstListener.given("Spek", "Test"))!!.willReturn(firstStepListener)
BDDMockito.given(secondListener.given("Spek", "Test"))!!.willReturn(secondStepListener)
val stepListener = multicaster.given("Spek", "Test")
//when execution started.
stepListener.started();
//then "executionStarted" in both step listeners must be called.
Mockito.verify(firstStepListener)!!.started()
Mockito.verify(secondStepListener)!!.started()
//when execution completed.
stepListener.completed()
//then "executionCompleted" in both step listeners must be called.
Mockito.verify(firstStepListener)!!.completed()
Mockito.verify(secondStepListener)!!.completed()
//when execution execution failed.
stepListener.failed(throwable)
//then "executionFailed" in both step listeners must be called.
Mockito.verify(firstStepListener)!!.failed(throwable)
Mockito.verify(secondStepListener)!!.failed(throwable)
}
@test fun onExecution() {
//given two listener with following conditions.
BDDMockito.given(firstListener.on("Spek", "Test", "Test"))!!.willReturn(firstStepListener)
BDDMockito.given(secondListener.on("Spek", "Test", "Test"))!!.willReturn(secondStepListener)
val stepListener = multicaster.on("Spek", "Test", "Test")
//when execution started.
stepListener.started();
//then "executionStarted" in both step listeners must be called.
Mockito.verify(firstStepListener)!!.started()
Mockito.verify(secondStepListener)!!.started()
//when execution completed.
stepListener.completed()
//then "executionCompleted" in both step listeners must be called.
Mockito.verify(firstStepListener)!!.completed()
Mockito.verify(secondStepListener)!!.completed()
//when execution execution failed.
stepListener.failed(throwable)
//then "executionFailed" in both step listeners must be called.
Mockito.verify(firstStepListener)!!.failed(throwable)
Mockito.verify(secondStepListener)!!.failed(throwable)
}
@test fun itExecution() {
//given two listener with following conditions.
BDDMockito.given(firstListener.it("Spek", "Test", "Test", "Test"))!!.willReturn(firstStepListener)
BDDMockito.given(secondListener.it("Spek", "Test", "Test", "Test"))!!.willReturn(secondStepListener)
val stepListener = multicaster.it("Spek", "Test", "Test", "Test")
//when execution started.
stepListener.started();
//then "executionStarted" in both step listeners must be called.
Mockito.verify(firstStepListener)!!.started()
Mockito.verify(secondStepListener)!!.started()
//when execution completed.
stepListener.completed()
//then "executionCompleted" in both step listeners must be called.
Mockito.verify(firstStepListener)!!.completed()
Mockito.verify(secondStepListener)!!.completed()
//when execution execution failed.
stepListener.failed(throwable)
//then "executionFailed" in both step listeners must be called.
Mockito.verify(firstStepListener)!!.failed(throwable)
Mockito.verify(secondStepListener)!!.failed(throwable)
}
}
| bsd-3-clause | 902741569f739c0bee3165ec5868449b | 41.254902 | 108 | 0.696288 | 5.249695 | false | true | false | false |
allotria/intellij-community | platform/platform-tests/testSrc/com/intellij/internal/statistics/logger/FeatureEventLogEscapingTest.kt | 3 | 10474 | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.internal.statistics.logger
import com.google.gson.Gson
import com.google.gson.JsonArray
import com.google.gson.JsonObject
import com.google.gson.JsonPrimitive
import com.intellij.internal.statistic.eventLog.LogEvent
import com.intellij.internal.statistic.eventLog.LogEventSerializer
import com.intellij.internal.statistics.StatisticsTestEventFactory.newEvent
import com.intellij.internal.statistics.StatisticsTestEventValidator.assertLogEventIsValid
import com.intellij.internal.statistics.StatisticsTestEventValidator.isValid
import org.junit.Test
import java.lang.IllegalStateException
import kotlin.test.assertEquals
import kotlin.test.assertNotNull
import kotlin.test.assertTrue
class FeatureEventLogEscapingTest {
@Test
fun testGroupIdEscaping() {
testGroupIdEscaping(newEvent(groupId = "test group"), "test_group")
testGroupIdEscaping(newEvent(groupId = "test\tgroup"), "test_group")
testGroupIdEscaping(newEvent(groupId = "test\"group"), "testgroup")
testGroupIdEscaping(newEvent(groupId = "test\'group"), "testgroup")
testGroupIdEscaping(newEvent(groupId = "test.group"), "test.group")
testGroupIdEscaping(newEvent(groupId = "test-group"), "test-group")
testGroupIdEscaping(newEvent(groupId = "test-group-42"), "test-group-42")
testGroupIdEscaping(newEvent(groupId = "42"), "42")
}
@Test
fun testGroupIdWithUnicodeEscaping() {
testGroupIdEscaping(newEvent(groupId = "group-id\u7A97\u013C"), "group-id??")
testGroupIdEscaping(newEvent(groupId = "\u7A97\u013C"), "??")
testGroupIdEscaping(newEvent(groupId = "group\u5F39id"), "group?id")
testGroupIdEscaping(newEvent(groupId = "group-id\u02BE"), "group-id?")
testGroupIdEscaping(newEvent(groupId = "��group-id"), "??group-id")
}
@Test
fun testEventEventIdAllowedSymbols() {
testEventIdEscaping(newEvent(eventId = "test.event"), "test.event")
testEventIdEscaping(newEvent(eventId = "test-event"), "test-event")
testEventIdEscaping(newEvent(eventId = "42-test-event"), "42-test-event")
testEventIdEscaping(newEvent(eventId = "event-12"), "event-12")
testEventIdEscaping(newEvent(eventId = "event@12"), "event@12")
testEventIdEscaping(newEvent(eventId = "ev$)en(t*-7ty2p#e!"), "ev$)en(t*-7ty2p#e!")
}
@Test
fun testEventEventIdEscaping() {
testEventIdEscaping(newEvent(eventId = "test\tevent"), "test event")
testEventIdEscaping(newEvent(eventId = "test event"), "test event")
testEventIdEscaping(newEvent(eventId = "t est\tevent"), "t est event")
}
@Test
fun testEventEventIdQuotesEscaping() {
testEventIdEscaping(newEvent(eventId = "test\"event"), "testevent")
testEventIdEscaping(newEvent(eventId = "test\'event"), "testevent")
testEventIdEscaping(newEvent(eventId = "42-test\'event"), "42-testevent")
testEventIdEscaping(newEvent(eventId = "t\"est'event"), "testevent")
testEventIdEscaping(newEvent(eventId = "t\"est'event"), "testevent")
}
@Test
fun testEventEventIdSystemSymbolsEscaping() {
testEventIdEscaping(newEvent(eventId = "t:est;ev,ent"), "t:est;ev,ent")
testEventIdEscaping(newEvent(eventId = "t:e'st\"e;v\te,n t"), "t:este;v e,n t")
}
@Test
fun testEventIdLineBreaksEscaping() {
testEventIdEscaping(newEvent(eventId = "e\n\rvent\ntyp\re"), "e vent typ e")
testEventIdEscaping(newEvent(eventId = "e\tve nt\ntyp\re"), "e ve nt typ e")
}
@Test
fun testEventIdUnicodeEscaping() {
testEventIdEscaping(newEvent(eventId = "test\uFFFD\uFFFD\uFFFDevent"), "test???event")
testEventIdEscaping(newEvent(eventId = "\uFFFDevent"), "?event")
testEventIdEscaping(newEvent(eventId = "test\uFFFD"), "test?")
testEventIdEscaping(newEvent(eventId = "\u7A97\uFFFD"), "??")
testEventIdEscaping(newEvent(eventId = "\u7A97\uFFFD\uFFFD\uFFFD"), "????")
testEventIdEscaping(newEvent(eventId = "\u7A97e:v'e\"n\uFFFD\uFFFD\uFFFDt;t\ty,p e"), "?e:ven???t;t y,p e")
testEventIdEscaping(newEvent(eventId = "event\u7A97type"), "event?type")
testEventIdEscaping(newEvent(eventId = "event弹typeʾļ"), "event?type??")
testEventIdEscaping(newEvent(eventId = "eventʾ"), "event?")
testEventIdEscaping(newEvent(eventId = "\uFFFD\uFFFD\uFFFDevent"), "???event")
}
@Test
fun testEventDataWithAllSymbolsToEscapeInName() {
val event = newEvent()
event.event.addData("my.key", "value")
event.event.addData("my:", "value")
event.event.addData(";mykey", "value")
event.event.addData("another'key", "value")
event.event.addData("se\"cond\"", "value")
event.event.addData("a'l\"l;s:y.s,t\tem symbols", "value")
val expected = HashMap<String, Any>()
expected["my_key"] = "value"
expected["my_"] = "value"
expected["_mykey"] = "value"
expected["second"] = "value"
expected["all_s_y_s_t_em_symbols"] = "value"
testEventDataEscaping(event, expected)
}
@Test
fun testEventDataWithAllSymbolsToEscapeInEventDataValue() {
val event = newEvent()
event.event.addData("my.key", "v.alue")
event.event.addData("my:", "valu:e")
event.event.addData(";mykey", ";value")
event.event.addData("another'key", "value'")
event.event.addData("se\"cond\"", "v\"alue")
event.event.addData("a'l\"l;s:y.s,t\tem symbols", "fin\"a'l :v;'a\" l,u\te")
val expected = HashMap<String, Any>()
expected["my_key"] = "v.alue"
expected["my_"] = "valu:e"
expected["_mykey"] = ";value"
expected["anotherkey"] = "value"
expected["second"] = "value"
expected["all_s_y_s_t_em_symbols"] = "final :v;a l,u e"
testEventDataEscaping(event, expected)
}
@Test
fun testEventDataWithTabInNameEscaping() {
val event = newEvent()
event.event.addData("my key", "value")
val data = HashMap<String, Any>()
data["my_key"] = "value"
testEventDataEscaping(event, data)
}
@Test
fun testEventDataWithTabInValueEscaping() {
val event = newEvent()
event.event.addData("key", "my value")
val data = HashMap<String, Any>()
data["key"] = "my value"
testEventDataEscaping(event, data)
}
@Test
fun testEventDataWithUnicodeInNameEscaping() {
val event = newEvent()
event.event.addData("my\uFFFDkey", "value")
event.event.addData("some\u013C\u02BE\u037C", "value")
event.event.addData("\u013C\u037Ckey", "value")
val data = HashMap<String, Any>()
data["my?key"] = "value"
data["some???"] = "value"
data["??key"] = "value"
testEventDataEscaping(event, data)
}
@Test
fun testEventDataWithUnicodeInValueEscaping() {
val event = newEvent()
event.event.addData("first-key", "my\uFFFDvalue")
event.event.addData("second-key", "some\u013C\u02BE\u037C")
event.event.addData("third-key", "\u013C\u037Cvalue")
val data = HashMap<String, Any>()
data["first-key"] = "my?value"
data["second-key"] = "some???"
data["third-key"] = "??value"
testEventDataEscaping(event, data)
}
@Test
fun testEventDataWithUnicodeInListValueEscaping() {
val event = newEvent()
event.event.addData("key", listOf("my\uFFFDvalue", "some\u013C\u02BE\u037Cvalue", "\u013C\u037Cvalue"))
val data = HashMap<String, Any>()
data["key"] = listOf("my?value", "some???value", "??value")
testEventDataEscaping(event, data)
}
@Test
fun testEventDataWithUnicodeInObjectEscaping() {
val event = newEvent()
event.event.addData("key", mapOf("fo\uFFFDo" to "foo\uFFDDValue"))
val data = HashMap<String, Any>()
data["key"] = mapOf("fo?o" to "foo?Value")
testEventDataEscaping(event, data)
}
@Test
fun testEventDataWithUnicodeInObjectListEscaping() {
val event = newEvent()
event.event.addData("key", listOf(mapOf("fo\uFFFDo" to "foo\uFFDDValue"), mapOf("ba\uFFFDr" to "bar\uFFDDValue")))
val data = HashMap<String, Any>()
data["key"] = listOf(mapOf("fo?o" to "foo?Value"), mapOf("ba?r" to "bar?Value"))
testEventDataEscaping(event, data)
}
@Test
fun testEventDataWithUnicodeInNestedObjectEscaping() {
val event = newEvent()
event.event.addData("key", mapOf("fo\uFFFDo" to mapOf("ba\uFFFDr" to "bar\uFFDDValue")))
val data = HashMap<String, Any>()
data["key"] = mapOf("fo?o" to mapOf("ba?r" to "bar?Value"))
testEventDataEscaping(event, data)
}
private fun testEventIdEscaping(event: LogEvent, expectedEventId: String) {
testEventEscaping(event, "group.id", expectedEventId)
}
private fun testGroupIdEscaping(event: LogEvent, expectedGroupId: String) {
testEventEscaping(event, expectedGroupId, "event.id")
}
private fun testEventDataEscaping(event: LogEvent, expectedData: Map<String, Any>) {
testEventEscaping(event, "group.id", "event.id", expectedData)
}
private fun testEventEscaping(event: LogEvent, expectedGroupId: String,
expectedEventId: String,
expectedData: Map<String, Any> = HashMap()) {
val json = Gson().fromJson(LogEventSerializer.toString(event), JsonObject::class.java)
assertLogEventIsValid(json, false)
assertEquals(expectedGroupId, json.getAsJsonObject("group").get("id").asString)
assertEquals(expectedEventId, json.getAsJsonObject("event").get("id").asString)
val obj = json.getAsJsonObject("event").get("data").asJsonObject
validateJsonObject(expectedData.keys, expectedData, obj)
}
private fun validateJsonObject(keys: Set<String>, expectedData: Any?, obj: JsonObject) {
val expectedMap = expectedData as? Map<*, *>
assertNotNull(expectedMap)
for (option in keys) {
assertTrue(isValid(option))
val expectedValue = expectedData[option]
when (val jsonElement = obj.get(option)) {
is JsonPrimitive -> assertEquals(expectedValue, jsonElement.asString)
is JsonArray -> {
for ((dataPart, expected) in jsonElement.zip(expectedValue as Collection<*>)) {
if (dataPart is JsonObject) {
validateJsonObject(dataPart.keySet(), expected, dataPart)
} else {
assertEquals(expected, dataPart.asString)
}
}
}
is JsonObject -> {
validateJsonObject(jsonElement.keySet(), expectedValue, jsonElement)
}
else -> throw IllegalStateException("Unsupported type of event data")
}
}
}
} | apache-2.0 | 221c59e5f8e73a0428c23dd38b98f1db | 37.619926 | 140 | 0.683994 | 3.847426 | false | true | false | false |
deadpixelsociety/roto-ld34 | core/src/com/thedeadpixelsociety/ld34/systems/RenderSystem.kt | 1 | 6744 | package com.thedeadpixelsociety.ld34.systems
import com.badlogic.ashley.core.ComponentMapper
import com.badlogic.ashley.core.Entity
import com.badlogic.ashley.core.Family
import com.badlogic.ashley.systems.SortedIteratingSystem
import com.badlogic.gdx.Gdx
import com.badlogic.gdx.graphics.Color
import com.badlogic.gdx.graphics.GL20
import com.badlogic.gdx.graphics.g2d.SpriteBatch
import com.badlogic.gdx.graphics.glutils.ShapeRenderer
import com.badlogic.gdx.math.Vector2
import com.badlogic.gdx.utils.viewport.Viewport
import com.thedeadpixelsociety.ld34.Fonts
import com.thedeadpixelsociety.ld34.GameServices
import com.thedeadpixelsociety.ld34.components.*
import com.thedeadpixelsociety.ld34.has
import java.util.*
class RenderSystem(private val viewport: Viewport) : SortedIteratingSystem(RenderSystem.FAMILY, ZOrderComparator()) {
companion object {
val FAMILY = Family.all(BoundsComponent::class.java, TransformComponent::class.java, RenderComponent::class.java).get()
}
private val animationMapper = ComponentMapper.getFor(AnimationComponent::class.java)
private val boundsMapper = ComponentMapper.getFor(BoundsComponent::class.java)
private val renderMapper = ComponentMapper.getFor(RenderComponent::class.java)
private val tintMapper = ComponentMapper.getFor(TintComponent::class.java)
private val transformMapper = ComponentMapper.getFor(TransformComponent::class.java)
private val tagMapper = ComponentMapper.getFor(TagComponent::class.java)
private val box2DMapper = ComponentMapper.getFor(Box2DComponent::class.java)
private val groupMapper = ComponentMapper.getFor(GroupComponent::class.java)
private val textMapper = ComponentMapper.getFor(TextComponent::class.java)
private val renderer by lazy { GameServices[ShapeRenderer::class] }
private val batch by lazy { GameServices[SpriteBatch::class] }
private var shadows = false
var rotation = 0f
var angle = 0f
get() = field
set(value) {
field = value
shadowOffset.rotate(value)
}
var shadowOffset = Vector2(2.5f, -2.5f)
override fun checkProcessing() = false
override fun processEntity(entity: Entity?, deltaTime: Float) {
val bounds = boundsMapper.get(entity)
val render = renderMapper.get(entity)
val transform = transformMapper.get(entity)
val tint = tintMapper.get(entity)
val tag = tagMapper.get(entity)
val group = groupMapper.get(entity)
val box2d = box2DMapper.get(entity)
val text = textMapper.get(entity)
val color = Color(tint?.color ?: Color.WHITE)
color.a = .5f
renderer.color = color
val isText = group != null && group.group == "text" && text != null
if (!isText) {
var radius = bounds.rect.width * .5f
val shadowExclude = (tag != null && tag.tag == "player") || (group != null && group.group == "coin")
if (!shadows || (shadows && !shadowExclude)) {
when (render.type) {
RenderType.CIRCLE -> {
if (tag != null && tag.tag == "player" && box2d != null && box2d.body != null) {
val velocity = box2d.body!!.linearVelocity
val r2 = radius * 2f
val t = velocity.len() / 175f
val tmp = Vector2(velocity).nor()
var rx = (r2 + ((r2 * .5f * t) * Math.abs(tmp.x)))
var ry = (r2 + ((r2 * .5f * t) * Math.abs(tmp.y)))
renderer.ellipse(transform.position.x - radius, transform.position.y - radius, rx, ry, 64)
} else {
renderer.circle(transform.position.x, transform.position.y, radius * transform.scale.x, 64)
}
}
RenderType.RECTANGLE -> {
renderer.rect(transform.position.x + (if (shadows) shadowOffset.x else 0f) - bounds.rect.width * .5f,
transform.position.y + (if (shadows) shadowOffset.y else 0f) - bounds.rect.height * .5f,
bounds.rect.width * .5f,
bounds.rect.height * .5f,
bounds.rect.width,
bounds.rect.height,
transform.scale.x,
transform.scale.y,
transform.rotation)
}
RenderType.POLYGON -> {
throw UnsupportedOperationException()
}
RenderType.LINE -> {
renderer.line(transform.position.x + (if (shadows) shadowOffset.x else 0f), transform.position.y + (if (shadows) shadowOffset.y else 0f), bounds.rect.width, bounds.rect.height)
}
else -> {
}
}
}
renderer.color = Color.WHITE
}
}
override fun update(deltaTime: Float) {
Gdx.gl20.glEnable(GL20.GL_BLEND)
Gdx.gl20.glBlendFunc(GL20.GL_SRC_ALPHA, GL20.GL_ONE_MINUS_SRC_ALPHA)
begin()
shadows = true
super.update(deltaTime)
end()
Gdx.gl20.glDisable(GL20.GL_BLEND)
begin()
shadows = false
super.update(deltaTime)
end()
beginBatch()
entities.filter { it.has(TextComponent::class.java) }.forEach {
val bounds = boundsMapper.get(it)
val transform = transformMapper.get(it)
val text = textMapper.get(it)
Fonts.font32.draw(batch,
text.text,
transform.position.x - bounds.rect.width * .5f,
transform.position.y - bounds.rect.height * .5f + Fonts.font32.lineHeight)
}
endBatch()
}
private fun begin() {
viewport.apply()
renderer.projectionMatrix = viewport.camera.combined
renderer.begin(ShapeRenderer.ShapeType.Filled)
}
private fun end() {
renderer.end()
}
private fun beginBatch() {
batch.projectionMatrix = viewport.camera.combined
batch.begin()
}
private fun endBatch() {
batch.end()
}
}
class ZOrderComparator : Comparator<Entity> {
override fun compare(o1: Entity?, o2: Entity?): Int {
val r1 = o1?.getComponent(RenderComponent::class.java)
val r2 = o2?.getComponent(RenderComponent::class.java)
return if (r1 != null && r2 != null) r1.zOrder.compareTo(r2.zOrder) else 0
}
}
| mit | 6eca52ba433db4ff06036dbe6b5f6a83 | 39.872727 | 200 | 0.587782 | 4.367876 | false | false | false | false |
Kotlin/kotlinx.coroutines | reactive/kotlinx-coroutines-reactor/test/FluxContextTest.kt | 1 | 1178 | /*
* Copyright 2016-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
*/
package kotlinx.coroutines.reactor
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.reactive.*
import org.junit.*
import org.junit.Test
import reactor.core.publisher.*
import kotlin.test.*
class FluxContextTest : TestBase() {
private val dispatcher = newSingleThreadContext("FluxContextTest")
@After
fun tearDown() {
dispatcher.close()
}
@Test
fun testFluxCreateAsFlowThread() = runTest {
expect(1)
val mainThread = Thread.currentThread()
val dispatcherThread = withContext(dispatcher) { Thread.currentThread() }
assertTrue(dispatcherThread != mainThread)
Flux.create<String> {
assertEquals(dispatcherThread, Thread.currentThread())
it.next("OK")
it.complete()
}
.asFlow()
.flowOn(dispatcher)
.collect {
expect(2)
assertEquals("OK", it)
assertEquals(mainThread, Thread.currentThread())
}
finish(3)
}
} | apache-2.0 | 8ca76832b3ce7b17ffbc314b8d6796c3 | 26.418605 | 102 | 0.623939 | 4.693227 | false | true | false | false |
leafclick/intellij-community | java/java-analysis-impl/src/com/intellij/codeInspection/dataFlow/inference/preContracts.kt | 1 | 6965 | // 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.codeInspection.dataFlow.inference
import com.intellij.codeInsight.NullableNotNullManager
import com.intellij.codeInspection.dataFlow.ContractReturnValue
import com.intellij.codeInspection.dataFlow.JavaMethodContractUtil
import com.intellij.codeInspection.dataFlow.StandardMethodContract
import com.intellij.codeInspection.dataFlow.StandardMethodContract.ValueConstraint.*
import com.intellij.codeInspection.dataFlow.inference.ContractInferenceInterpreter.withConstraint
import com.intellij.codeInspection.dataFlow.instructions.MethodCallInstruction
import com.intellij.psi.*
import com.intellij.psi.util.PsiUtil
import com.siyeh.ig.psiutils.SideEffectChecker
/**
* @author peter
*/
interface PreContract {
fun toContracts(method: PsiMethod, body: () -> PsiCodeBlock): List<StandardMethodContract>
fun negate(): PreContract? = NegatingContract(
this)
}
internal data class KnownContract(val contract: StandardMethodContract) : PreContract {
override fun toContracts(method: PsiMethod, body: () -> PsiCodeBlock) = listOf(contract)
override fun negate() = negateContract(contract)?.let(::KnownContract)
}
internal data class DelegationContract(internal val expression: ExpressionRange, internal val negated: Boolean) : PreContract {
override fun toContracts(method: PsiMethod, body: () -> PsiCodeBlock): List<StandardMethodContract> {
val call = expression.restoreExpression(body()) as PsiMethodCallExpression? ?: return emptyList()
val result = call.resolveMethodGenerics()
val targetMethod = result.element as PsiMethod? ?: return emptyList()
if (targetMethod == method) return emptyList()
val parameters = targetMethod.parameterList.parameters
val arguments = call.argumentList.expressions
val varArgCall = MethodCallInstruction.isVarArgCall(targetMethod, result.substitutor, arguments, parameters)
val methodContracts = StandardMethodContract.toNonIntersectingStandardContracts(JavaMethodContractUtil.getMethodContracts(targetMethod))
?: return emptyList()
var fromDelegate = methodContracts.mapNotNull { dc ->
convertDelegatedMethodContract(method, parameters, arguments, varArgCall, dc)
}
if (NullableNotNullManager.isNotNull(targetMethod)) {
fromDelegate = fromDelegate.map(this::returnNotNull) + listOf(
StandardMethodContract(emptyConstraints(method), ContractReturnValue.returnNotNull()))
}
return StandardMethodContract.toNonIntersectingStandardContracts(fromDelegate) ?: emptyList()
}
private fun convertDelegatedMethodContract(callerMethod: PsiMethod,
targetParameters: Array<PsiParameter>,
callArguments: Array<PsiExpression>,
varArgCall: Boolean,
targetContract: StandardMethodContract): StandardMethodContract? {
var answer: Array<StandardMethodContract.ValueConstraint>? = emptyConstraints(callerMethod)
for (i in 0 until targetContract.parameterCount) {
if (i >= callArguments.size) return null
val argConstraint = targetContract.getParameterConstraint(i)
if (argConstraint != ANY_VALUE) {
if (varArgCall && i >= targetParameters.size - 1) {
if (argConstraint == NULL_VALUE) {
return null
}
break
}
val argument = PsiUtil.skipParenthesizedExprDown(callArguments[i]) ?: return null
val paramIndex = resolveParameter(callerMethod, argument)
if (paramIndex >= 0) {
answer = withConstraint(answer, paramIndex, argConstraint) ?: return null
}
else if (argConstraint != getLiteralConstraint(argument)) {
return null
}
}
}
var returnValue = targetContract.returnValue
if (negated && returnValue is ContractReturnValue.BooleanReturnValue) returnValue = returnValue.negate()
return answer?.let { StandardMethodContract(it, returnValue) }
}
private fun emptyConstraints(method: PsiMethod) = StandardMethodContract.createConstraintArray(
method.parameterList.parametersCount)
private fun returnNotNull(mc: StandardMethodContract): StandardMethodContract {
return if (mc.returnValue.isFail) mc else mc.withReturnValue(ContractReturnValue.returnNotNull())
}
private fun getLiteralConstraint(argument: PsiExpression) = when (argument) {
is PsiLiteralExpression -> ContractInferenceInterpreter.getLiteralConstraint(
argument.getFirstChild().node.elementType)
is PsiNewExpression, is PsiPolyadicExpression, is PsiFunctionalExpression -> NOT_NULL_VALUE
else -> null
}
private fun resolveParameter(method: PsiMethod, expr: PsiExpression): Int {
val target = if (expr is PsiReferenceExpression && !expr.isQualified) expr.resolve() else null
return if (target is PsiParameter && target.parent === method.parameterList) method.parameterList.getParameterIndex(target) else -1
}
}
internal data class SideEffectFilter(internal val expressionsToCheck: List<ExpressionRange>, internal val contracts: List<PreContract>) : PreContract {
override fun toContracts(method: PsiMethod, body: () -> PsiCodeBlock): List<StandardMethodContract> {
if (expressionsToCheck.any { d -> mayHaveSideEffects(body(), d) }) {
return emptyList()
}
return contracts.flatMap { c -> c.toContracts(method, body) }
}
private fun mayHaveSideEffects(body: PsiCodeBlock, range: ExpressionRange) =
range.restoreExpression(body)?.let { SideEffectChecker.mayHaveSideEffects(it) } ?: false
}
internal data class NegatingContract(internal val negated: PreContract) : PreContract {
override fun toContracts(method: PsiMethod, body: () -> PsiCodeBlock) = negated.toContracts(method, body).mapNotNull(::negateContract)
}
private fun negateContract(c: StandardMethodContract): StandardMethodContract? {
val ret = c.returnValue
return if (ret is ContractReturnValue.BooleanReturnValue) c.withReturnValue(ret.negate())
else null
}
@Suppress("EqualsOrHashCode")
internal data class MethodCallContract(internal val call: ExpressionRange, internal val states: List<List<StandardMethodContract.ValueConstraint>>) : PreContract {
override fun hashCode() = call.hashCode() * 31 + states.flatten().map { it.ordinal }.hashCode()
override fun toContracts(method: PsiMethod, body: () -> PsiCodeBlock): List<StandardMethodContract> {
val target = (call.restoreExpression(body()) as PsiMethodCallExpression?)?.resolveMethod()
if (target != null && target != method && NullableNotNullManager.isNotNull(target)) {
return ContractInferenceInterpreter.toContracts(states.map { it.toTypedArray() }, ContractReturnValue.returnNotNull())
}
return emptyList()
}
}
| apache-2.0 | fe60c8c97199889d16bc3d24ce8d5d45 | 48.75 | 163 | 0.740991 | 5.345357 | false | false | false | false |
zdary/intellij-community | plugins/github/src/org/jetbrains/plugins/github/api/data/pullrequest/timeline/GHPRTimelineItem.kt | 2 | 4335 | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.plugins.github.api.data.pullrequest.timeline
import com.fasterxml.jackson.annotation.JsonSubTypes
import com.fasterxml.jackson.annotation.JsonTypeInfo
import com.intellij.util.ui.codereview.timeline.TimelineItem
import org.jetbrains.plugins.github.api.data.GHIssueComment
import org.jetbrains.plugins.github.api.data.pullrequest.GHPullRequestCommitShort
import org.jetbrains.plugins.github.api.data.pullrequest.GHPullRequestReview
import org.jetbrains.plugins.github.api.data.pullrequest.timeline.GHPRTimelineItem.Unknown
/*REQUIRED
IssueComment
PullRequestCommit (Commit in GHE)
PullRequestReview
RenamedTitleEvent
ClosedEvent | ReopenedEvent | MergedEvent
AssignedEvent | UnassignedEvent
LabeledEvent | UnlabeledEvent
ReviewRequestedEvent | ReviewRequestRemovedEvent
ReviewDismissedEvent
ReadyForReviewEvent
BaseRefChangedEvent | BaseRefForcePushedEvent
HeadRefDeletedEvent | HeadRefForcePushedEvent | HeadRefRestoredEvent
//comment reference
CrossReferencedEvent
//issue will be closed
ConnectedEvent | DisconnectedEvent
*/
/*MAYBE
LockedEvent | UnlockedEvent
MarkedAsDuplicateEvent | UnmarkedAsDuplicateEvent
ConvertToDraftEvent
???PullRequestCommitCommentThread
???PullRequestReviewThread
AddedToProjectEvent
ConvertedNoteToIssueEvent
RemovedFromProjectEvent
MovedColumnsInProjectEvent
TransferredEvent
UserBlockedEvent
PullRequestRevisionMarker
DeployedEvent
DeploymentEnvironmentChangedEvent
PullRequestReviewThread
PinnedEvent | UnpinnedEvent
SubscribedEvent | UnsubscribedEvent
MilestonedEvent | DemilestonedEvent
AutomaticBaseChangeSucceededEvent | AutomaticBaseChangeFailedEvent
*/
/*IGNORE
ReferencedEvent
MentionedEvent
CommentDeletedEvent
*/
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "__typename", visible = true,
defaultImpl = Unknown::class)
@JsonSubTypes(
JsonSubTypes.Type(name = "IssueComment", value = GHIssueComment::class),
JsonSubTypes.Type(name = "PullRequestCommit", value = GHPullRequestCommitShort::class),
JsonSubTypes.Type(name = "PullRequestReview", value = GHPullRequestReview::class),
JsonSubTypes.Type(name = "ReviewDismissedEvent", value = GHPRReviewDismissedEvent::class),
JsonSubTypes.Type(name = "ReadyForReviewEvent", value = GHPRReadyForReviewEvent::class),
/*JsonSubTypes.Type(name = "ConvertToDraftEvent", value = GHPRConvertToDraftEvent::class),*/
JsonSubTypes.Type(name = "RenamedTitleEvent", value = GHPRRenamedTitleEvent::class),
JsonSubTypes.Type(name = "ClosedEvent", value = GHPRClosedEvent::class),
JsonSubTypes.Type(name = "ReopenedEvent", value = GHPRReopenedEvent::class),
JsonSubTypes.Type(name = "MergedEvent", value = GHPRMergedEvent::class),
JsonSubTypes.Type(name = "AssignedEvent", value = GHPRAssignedEvent::class),
JsonSubTypes.Type(name = "UnassignedEvent", value = GHPRUnassignedEvent::class),
JsonSubTypes.Type(name = "LabeledEvent", value = GHPRLabeledEvent::class),
JsonSubTypes.Type(name = "UnlabeledEvent", value = GHPRUnlabeledEvent::class),
JsonSubTypes.Type(name = "ReviewRequestedEvent", value = GHPRReviewRequestedEvent::class),
JsonSubTypes.Type(name = "ReviewRequestRemovedEvent", value = GHPRReviewUnrequestedEvent::class),
JsonSubTypes.Type(name = "BaseRefChangedEvent", value = GHPRBaseRefChangedEvent::class),
JsonSubTypes.Type(name = "BaseRefForcePushedEvent", value = GHPRBaseRefForcePushedEvent::class),
JsonSubTypes.Type(name = "HeadRefDeletedEvent", value = GHPRHeadRefDeletedEvent::class),
JsonSubTypes.Type(name = "HeadRefForcePushedEvent", value = GHPRHeadRefForcePushedEvent::class),
JsonSubTypes.Type(name = "HeadRefRestoredEvent", value = GHPRHeadRefRestoredEvent::class),
JsonSubTypes.Type(name = "CrossReferencedEvent", value = GHPRCrossReferencedEvent::class)/*,
JsonSubTypes.Type(name = "ConnectedEvent", value = GHPRConnectedEvent::class),
JsonSubTypes.Type(name = "DisconnectedEvent", value = GHPRDisconnectedEvent::class)*/
)
interface GHPRTimelineItem : TimelineItem {
class Unknown(val __typename: String) : GHPRTimelineItem
companion object {
val IGNORED_TYPES = setOf("ReferencedEvent", "MentionedEvent", "CommentDeletedEvent")
}
} | apache-2.0 | 22cda84d9cf60534b4cca6da1ffcbef4 | 39.523364 | 140 | 0.812226 | 4.800664 | false | false | false | false |
psenchanka/comant | comant-site/src/main/kotlin/com/psenchanka/comant/controller/LectureController.kt | 1 | 2058 | package com.psenchanka.comant.controller
import com.psenchanka.comant.dto.BasicLectureDto
import com.psenchanka.comant.dto.DetailedLectureDto
import com.psenchanka.comant.service.LectureService
import io.swagger.annotations.ApiOperation
import io.swagger.annotations.ApiParam
import io.swagger.annotations.ApiResponse
import io.swagger.annotations.ApiResponses
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.http.HttpStatus
import org.springframework.transaction.annotation.Transactional
import org.springframework.web.bind.annotation.*
@RestController
@RequestMapping("/api/lectures")
open class LectureController @Autowired constructor(val lectureService: LectureService) {
@ResponseStatus(HttpStatus.NOT_FOUND, reason = "No lecture with given id")
class LectureNotFoundException : RuntimeException()
@RequestMapping("", method = arrayOf(RequestMethod.GET))
@ApiOperation("Search lectures",
notes = "Returns all lectures satisfying given criteria.")
@ApiResponses(
ApiResponse(code = 200, message = "OK")
)
@Transactional
open fun search(
@ApiParam("Search by author") @RequestParam(required = false) author: String?
): List<BasicLectureDto> {
return lectureService.findAll()
.filter { author == null || it.author.username == author }
.map { BasicLectureDto.from(it) }
}
@RequestMapping("/{id}", method = arrayOf(RequestMethod.GET))
@ApiOperation("Get lecture data",
notes = "Returns detailed information about target lecture, including its text.")
@ApiResponses(
ApiResponse(code = 200, message = "OK"),
ApiResponse(code = 404, message = "No lecture with given id")
)
@Transactional
open fun getById(
@ApiParam("Lecture id") @PathVariable id: Int
): DetailedLectureDto {
val lecture = lectureService.findById(id) ?: throw LectureNotFoundException()
return DetailedLectureDto.from(lecture)
}
} | mit | d69462283393a6c9c3959d8c701376ba | 39.372549 | 99 | 0.715743 | 4.830986 | false | false | false | false |
smmribeiro/intellij-community | java/java-impl/src/com/intellij/codeInsight/daemon/problems/ProblemSearcher.kt | 4 | 5495 | // 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.codeInsight.daemon.problems
import com.intellij.codeInsight.daemon.impl.HighlightInfo
import com.intellij.codeInsight.daemon.impl.analysis.HighlightInfoHolder
import com.intellij.codeInsight.daemon.impl.analysis.HighlightVisitorImpl
import com.intellij.lang.annotation.HighlightSeverity
import com.intellij.pom.Navigatable
import com.intellij.psi.*
import com.intellij.psi.util.PsiTreeUtil
class Problem(val reportedElement: PsiElement, val context: PsiElement) {
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as Problem
if (context != other.context) return false
return true
}
override fun hashCode(): Int {
return context.hashCode()
}
}
internal class ProblemSearcher(private val file: PsiFile, private val memberType: MemberType) : JavaElementVisitor() {
private val problems = mutableSetOf<Problem>()
private var seenReference = false
override fun visitElement(element: PsiElement) {
findProblem(element)
element.parent?.accept(this)
}
override fun visitReferenceElement(reference: PsiJavaCodeReferenceElement) {
if (seenReference && reference.resolve() != null && memberType != MemberType.FIELD) return
seenReference = true
super.visitReferenceElement(reference)
}
override fun visitReferenceExpression(expression: PsiReferenceExpression) {
visitReferenceElement(expression)
}
override fun visitCallExpression(callExpression: PsiCallExpression) {
val args = callExpression.argumentList
if (args != null) findProblem(args)
visitElement(callExpression)
}
override fun visitAnnotation(annotation: PsiAnnotation) {
val paramsList = annotation.parameterList
paramsList.attributes.forEach {
val detachedValue = it.detachedValue
if (detachedValue != null) findProblem(detachedValue)
findProblem(it)
}
visitElement(annotation)
}
override fun visitParameter(parameter: PsiParameter) {
val parent = parameter.parent
if (parent is PsiCatchSection) findProblem(parent.tryStatement)
findProblem(parameter)
}
override fun visitVariable(variable: PsiVariable) {
findProblem(variable)
}
override fun visitForeachStatement(statement: PsiForeachStatement) {
visitStatement(statement)
findProblem(statement.iterationParameter)
}
override fun visitStatement(statement: PsiStatement) {
findProblem(statement)
}
override fun visitMethod(method: PsiMethod) {
findProblem(method)
val typeElement = method.returnTypeElement
if (typeElement != null) findProblem(typeElement)
val params = method.parameterList
findProblem(params)
val modifiers = method.modifierList
findProblem(modifiers)
}
override fun visitAnonymousClass(aClass: PsiAnonymousClass) {
visitElement(aClass)
}
override fun visitClass(psiClass: PsiClass) {
val modifiers = psiClass.modifierList
if (modifiers != null) findProblem(modifiers)
val nameIdentifier = psiClass.nameIdentifier
if (nameIdentifier != null) findProblem(nameIdentifier)
findProblem(psiClass)
}
private fun findProblem(element: PsiElement) {
if (element !is Navigatable) return
val problemHolder = ProblemHolder(file)
val visitor = object : HighlightVisitorImpl() {
init {
prepareToRunAsInspection(problemHolder)
}
}
element.accept(visitor)
val reportedElement = problemHolder.reportedElement ?: return
val context = PsiTreeUtil.getNonStrictParentOfType(element, PsiStatement::class.java,
PsiClass::class.java, PsiMethod::class.java, PsiVariable::class.java) ?: element
problems.add(Problem(reportedElement, context))
}
private class ProblemHolder(private val file: PsiFile) : HighlightInfoHolder(file) {
var reportedElement: PsiElement? = null
override fun add(info: HighlightInfo?): Boolean {
if (reportedElement != null || info == null || info.severity != HighlightSeverity.ERROR || info.description == null) return true
reportedElement = file.findElementAt(info.actualStartOffset)
return true
}
override fun hasErrorResults(): Boolean {
return reportedElement != null
}
}
companion object {
internal fun getProblems(usage: PsiElement, targetFile: PsiFile, memberType: MemberType): Set<Problem> {
val startElement = getSearchStartElement(usage, targetFile) ?: return emptySet()
val psiFile = startElement.containingFile
val searcher = ProblemSearcher(psiFile, memberType)
startElement.accept(searcher)
return searcher.problems
}
private fun getSearchStartElement(usage: PsiElement, targetFile: PsiFile): PsiElement? {
when (usage) {
is PsiMethod -> return usage.modifierList.findAnnotation(CommonClassNames.JAVA_LANG_OVERRIDE) ?: usage
is PsiJavaCodeReferenceElement -> {
val resolveResult = usage.advancedResolve(false)
if (resolveResult.isValidResult) {
val containingFile = resolveResult.element?.containingFile
if (containingFile != null && containingFile != targetFile) return null
}
return usage.referenceNameElement
}
else -> return usage
}
}
}
} | apache-2.0 | 8cd06623dcec094a3286d646d4bc23ae | 33.136646 | 140 | 0.725387 | 5.092678 | false | false | false | false |
smmribeiro/intellij-community | plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/typing/DefaultSafeCastTypeCalculator.kt | 14 | 2686 | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.plugins.groovy.lang.typing
import com.intellij.psi.CommonClassNames.JAVA_UTIL_COLLECTION
import com.intellij.psi.JavaPsiFacade
import com.intellij.psi.PsiClassType
import com.intellij.psi.PsiType
import com.intellij.psi.util.InheritanceUtil.isInheritor
import com.intellij.psi.util.PsiUtil.extractIterableTypeParameter
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrSafeCastExpression
import org.jetbrains.plugins.groovy.lang.psi.impl.GrTraitType
import org.jetbrains.plugins.groovy.lang.psi.impl.GrTraitType.createTraitType
import org.jetbrains.plugins.groovy.lang.psi.impl.statements.expressions.TypesUtil.getItemType
import org.jetbrains.plugins.groovy.lang.psi.util.GrTraitUtil.isTrait
class DefaultSafeCastTypeCalculator : GrTypeCalculator<GrSafeCastExpression> {
override fun getType(expression: GrSafeCastExpression): PsiType? {
val typeElement = expression.castTypeElement ?: return null
return getTypeFromRawCollectionCast(expression) ?:
getTraitType(expression) ?:
typeElement.type
}
/**
* Given an expression `expr as List`.
* If expr has an array type, then we want to preserve information about component type of this array.
* For example if expr is of `String[]` type then the type of whole expression will be `List<String>`.
*/
private fun getTypeFromRawCollectionCast(expression: GrSafeCastExpression): PsiType? {
val castType = expression.castTypeElement?.type as? PsiClassType ?: return null
if (!isInheritor(castType, JAVA_UTIL_COLLECTION)) return null
if (extractIterableTypeParameter(castType, false) != null) return null
val resolved = castType.resolve() ?: return null
val typeParameter = resolved.typeParameters.singleOrNull() ?: return null
val itemType = getItemType(expression.operand.type) ?: return null
val substitutionMap = mapOf(typeParameter to itemType)
val factory = JavaPsiFacade.getElementFactory(expression.project)
val substitutor = factory.createSubstitutor(substitutionMap)
return factory.createType(resolved, substitutor)
}
private fun getTraitType(expression: GrSafeCastExpression): PsiType? {
val castType = expression.castTypeElement?.type as? PsiClassType ?: return null
val exprType = expression.operand.type
if (exprType !is PsiClassType && exprType !is GrTraitType) return null
val resolved = castType.resolve() ?: return null
if (!isTrait(resolved)) return null
return createTraitType(exprType, listOf(castType))
}
} | apache-2.0 | 16262357870d41b7b984406d5140ee7b | 46.982143 | 140 | 0.77997 | 4.631034 | false | false | false | false |
charlesng/SampleAppArch | app/src/main/java/com/cn29/aac/ui/shopping/ArtistDetailActivity.kt | 1 | 2098 | package com.cn29.aac.ui.shopping
import android.os.Bundle
import android.view.MenuItem
import android.view.View
import androidx.core.app.NavUtils
import com.cn29.aac.R
import com.cn29.aac.databinding.ActivityArtistDetailBinding
import com.cn29.aac.di.scope.AndroidDataBinding
import com.cn29.aac.di.scope.ViewModel
import com.cn29.aac.repo.itunes.Artist
import com.cn29.aac.ui.base.BaseAppCompatActivity
import com.cn29.aac.ui.shopping.vm.ArtistDetailActivityViewModel
import com.google.android.material.snackbar.Snackbar
import javax.inject.Inject
class ArtistDetailActivity : BaseAppCompatActivity() {
@Inject
@ViewModel
lateinit var viewModel: ArtistDetailActivityViewModel
@Inject
@AndroidDataBinding
lateinit var binding: ActivityArtistDetailBinding
@Inject
lateinit var artist: Artist
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding.toolbar.title = artist.artistName
setSupportActionBar(binding.toolbar)
supportActionBar!!.setDisplayHomeAsUpEnabled(true)
binding.artist = artist
binding.fab.setOnClickListener { view: View ->
addToKart(view)
}
val manager = supportFragmentManager
val fragment = AlbumFragment()
val bundle = Bundle()
artist.artistId.toInt().let { bundle.putInt("artistId", it) }
bundle.putString("entity", "album")
fragment.arguments = bundle
manager.beginTransaction()
.add(binding.container.id, fragment)
.commit()
}
private fun addToKart(view: View) {
Snackbar.make(view,
"Replace with your own action",
Snackbar.LENGTH_LONG)
.setAction("Action", null).show()
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
R.id.home -> {
NavUtils.navigateUpFromSameTask(this)
return true
}
}
return super.onOptionsItemSelected(item)
}
} | apache-2.0 | d4e66b16b4efe49c29e4e14767c221ce | 31.796875 | 69 | 0.673499 | 4.662222 | false | false | false | false |
Pattonville-App-Development-Team/Android-App | app/src/main/java/org/pattonvillecs/pattonvilleapp/preferences/SharedPreferenceLiveData.kt | 1 | 3844 | /*
* Copyright (C) 2017 - 2018 Mitchell Skaggs, Keturah Gadson, Ethan Holtgrieve, Nathan Skelton, Pattonville School District
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.pattonvillecs.pattonvilleapp.preferences
import android.arch.lifecycle.LiveData
import android.content.SharedPreferences
abstract class SharedPreferenceLiveData<T>(private val sharedPrefs: SharedPreferences,
private val key: String,
private val defValue: T) : LiveData<T>() {
private val preferenceChangeListener = SharedPreferences.OnSharedPreferenceChangeListener { _, key ->
if (key == this.key) {
value = getValueFromPreferences(sharedPrefs, key, defValue)
}
}
abstract fun getValueFromPreferences(sharedPrefs: SharedPreferences, key: String, defValue: T): T
override fun onActive() {
super.onActive()
value = getValueFromPreferences(sharedPrefs, key, defValue)
sharedPrefs.registerOnSharedPreferenceChangeListener(preferenceChangeListener)
}
override fun onInactive() {
sharedPrefs.unregisterOnSharedPreferenceChangeListener(preferenceChangeListener)
super.onInactive()
}
}
private class SharedPreferenceLiveDataFunction<T>(sharedPrefs: SharedPreferences,
key: String,
defValue: T,
val function: (SharedPreferences, String, T) -> T) : SharedPreferenceLiveData<T>(sharedPrefs, key, defValue) {
override fun getValueFromPreferences(sharedPrefs: SharedPreferences, key: String, defValue: T): T =
function(sharedPrefs, key, defValue)
}
fun SharedPreferences.intLiveData(key: String, defValue: Int): SharedPreferenceLiveData<Int> =
SharedPreferenceLiveDataFunction(this, key, defValue) { fSharedPrefs, fKey, fDefValue -> fSharedPrefs.getInt(fKey, fDefValue) }
fun SharedPreferences.stringLiveData(key: String, defValue: String): SharedPreferenceLiveData<String> =
SharedPreferenceLiveDataFunction(this, key, defValue) { fSharedPrefs, fKey, fDefValue -> fSharedPrefs.getString(fKey, fDefValue) }
fun SharedPreferences.booleanLiveData(key: String, defValue: Boolean): SharedPreferenceLiveData<Boolean> =
SharedPreferenceLiveDataFunction(this, key, defValue) { fSharedPrefs, fKey, fDefValue -> fSharedPrefs.getBoolean(fKey, fDefValue) }
fun SharedPreferences.floatLiveData(key: String, defValue: Float): SharedPreferenceLiveData<Float> =
SharedPreferenceLiveDataFunction(this, key, defValue) { fSharedPrefs, fKey, fDefValue -> fSharedPrefs.getFloat(fKey, fDefValue) }
fun SharedPreferences.longLiveData(key: String, defValue: Long): SharedPreferenceLiveData<Long> =
SharedPreferenceLiveDataFunction(this, key, defValue) { fSharedPrefs, fKey, fDefValue -> fSharedPrefs.getLong(fKey, fDefValue) }
fun SharedPreferences.stringSetLiveData(key: String, defValue: Set<String>): SharedPreferenceLiveData<Set<String>> =
SharedPreferenceLiveDataFunction(this, key, defValue) { fSharedPrefs, fKey, fDefValue -> fSharedPrefs.getStringSet(fKey, fDefValue) } | gpl-3.0 | 4975f109991b07f5902d91ddab56e333 | 53.15493 | 160 | 0.718002 | 5.398876 | false | false | false | false |
jotomo/AndroidAPS | core/src/main/java/info/nightscout/androidaps/plugins/general/maintenance/formats/PrefsFormat.kt | 1 | 3250 | package info.nightscout.androidaps.plugins.general.maintenance.formats
import android.content.Context
import android.os.Parcelable
import androidx.annotation.DrawableRes
import androidx.annotation.StringRes
import info.nightscout.androidaps.core.R
import kotlinx.parcelize.Parcelize
import java.io.File
enum class PrefsMetadataKey(val key: String, @DrawableRes val icon: Int, @StringRes val label: Int) {
FILE_FORMAT("format", R.drawable.ic_meta_format, R.string.metadata_label_format),
CREATED_AT("created_at", R.drawable.ic_meta_date, R.string.metadata_label_created_at),
AAPS_VERSION("aaps_version", R.drawable.ic_meta_version, R.string.metadata_label_aaps_version),
AAPS_FLAVOUR("aaps_flavour", R.drawable.ic_meta_flavour, R.string.metadata_label_aaps_flavour),
DEVICE_NAME("device_name", R.drawable.ic_meta_name, R.string.metadata_label_device_name),
DEVICE_MODEL("device_model", R.drawable.ic_meta_model, R.string.metadata_label_device_model),
ENCRYPTION("encryption", R.drawable.ic_meta_encryption, R.string.metadata_label_encryption);
companion object {
private val keyToEnumMap = HashMap<String, PrefsMetadataKey>()
init {
for (value in values()) {
keyToEnumMap.put(value.key, value)
}
}
fun fromKey(key: String): PrefsMetadataKey? {
if (keyToEnumMap.containsKey(key)) {
return keyToEnumMap.get(key)
} else {
return null
}
}
}
fun formatForDisplay(context: Context, value: String): String {
return when (this) {
FILE_FORMAT -> when (value) {
ClassicPrefsFormat.FORMAT_KEY -> context.getString(R.string.metadata_format_old)
EncryptedPrefsFormat.FORMAT_KEY_ENC -> context.getString(R.string.metadata_format_new)
EncryptedPrefsFormat.FORMAT_KEY_NOENC -> context.getString(R.string.metadata_format_debug)
else -> context.getString(R.string.metadata_format_other)
}
CREATED_AT -> value.replace("T", " ").replace("Z", " (UTC)")
else -> value
}
}
}
@Parcelize
data class PrefMetadata(var value: String, var status: PrefsStatus, var info: String? = null) : Parcelable
typealias PrefMetadataMap = Map<PrefsMetadataKey, PrefMetadata>
data class Prefs(val values: Map<String, String>, var metadata: PrefMetadataMap)
interface PrefsFormat {
fun savePreferences(file: File, prefs: Prefs, masterPassword: String? = null)
fun loadPreferences(file: File, masterPassword: String? = null): Prefs
fun loadMetadata(contents: String? = null): PrefMetadataMap
fun isPreferencesFile(file: File, preloadedContents: String? = null): Boolean
}
enum class PrefsStatus(@DrawableRes val icon: Int) {
OK(R.drawable.ic_meta_ok),
WARN(R.drawable.ic_meta_warning),
ERROR(R.drawable.ic_meta_error),
UNKNOWN(R.drawable.ic_meta_error),
DISABLED(R.drawable.ic_meta_error)
}
class PrefFileNotFoundError(message: String) : Exception(message)
class PrefIOError(message: String) : Exception(message)
class PrefFormatError(message: String) : Exception(message)
| agpl-3.0 | c79df189963f27cb3d53845490068c7c | 40.139241 | 106 | 0.68 | 4.037267 | false | false | false | false |
siosio/intellij-community | platform/object-serializer/src/MapBinding.kt | 1 | 3901 | // 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.serialization
import com.amazon.ion.IonType
import com.intellij.util.ArrayUtil
import java.lang.reflect.Type
import java.util.*
internal class MapBinding(keyType: Type, valueType: Type, context: BindingInitializationContext) : Binding {
private val keyBinding = createElementBindingByType(keyType, context)
private val valueBinding = createElementBindingByType(valueType, context)
private val isKeyComparable = Comparable::class.java.isAssignableFrom(ClassUtil.typeToClass(keyType))
override fun serialize(obj: Any, context: WriteContext) {
val map = obj as Map<*, *>
val writer = context.writer
if (context.filter.skipEmptyMap && map.isEmpty()) {
writer.writeInt(0)
return
}
fun writeEntry(key: Any?, value: Any?, isStringKey: Boolean) {
if (isStringKey) {
if (key == null) {
throw SerializationException("null string keys not supported")
}
else {
writer.setFieldName(key as String)
}
}
else {
if (key == null) {
writer.writeNull()
}
else {
keyBinding.serialize(key, context)
}
}
if (value == null) {
writer.writeNull()
}
else {
valueBinding.serialize(value, context)
}
}
val isStringKey = keyBinding is StringBinding
writer.stepIn(if (isStringKey) IonType.STRUCT else IonType.LIST)
if (context.configuration.orderMapEntriesByKeys && isKeyComparable && map !is SortedMap<*, *> && map !is LinkedHashMap<*, *>) {
val keys = ArrayUtil.toObjectArray(map.keys)
Arrays.sort(keys) { a, b ->
@Suppress("UNCHECKED_CAST")
when {
a == null -> -1
b == null -> 1
else -> (a as Comparable<Any>).compareTo(b as Comparable<Any>)
}
}
for (key in keys) {
writeEntry(key, map.get(key), isStringKey)
}
}
else {
map.forEach { (key, value) -> writeEntry(key, value, isStringKey) }
}
writer.stepOut()
}
override fun deserialize(hostObject: Any, property: MutableAccessor, context: ReadContext) {
if (context.reader.type == IonType.NULL) {
property.set(hostObject, null)
return
}
@Suppress("UNCHECKED_CAST")
var result = property.readUnsafe(hostObject) as MutableMap<Any?, Any?>?
if (result != null && ClassUtil.isMutableMap(result)) {
result.clear()
}
else {
result = HashMap()
property.set(hostObject, result)
}
readInto(result, context, hostObject)
}
override fun deserialize(context: ReadContext, hostObject: Any?): Any {
val result = HashMap<Any?, Any?>()
readInto(result, context, hostObject)
return result
}
private fun readInto(result: MutableMap<Any?, Any?>, context: ReadContext, hostObject: Any?) {
val reader = context.reader
if (reader.type === IonType.INT) {
LOG.assertTrue(context.reader.intValue() == 0)
return
}
val isStringKeys = reader.type === IonType.STRUCT
reader.stepIn()
while (true) {
if (isStringKeys) {
val type = reader.next() ?: break
val key = reader.fieldName
val value = read(type, valueBinding, context, hostObject)
result.put(key, value)
}
else {
val key = read(reader.next() ?: break, keyBinding, context, hostObject)
val value = read(reader.next() ?: break, valueBinding, context, hostObject)
result.put(key, value)
}
}
reader.stepOut()
}
private fun read(type: IonType, binding: Binding, context: ReadContext, hostObject: Any?): Any? {
return when (type) {
IonType.NULL -> null
else -> binding.deserialize(context, hostObject)
}
}
} | apache-2.0 | b94b230492197f281e0ef41410ee1399 | 29.484375 | 140 | 0.628044 | 4.167735 | false | false | false | false |
JetBrains/xodus | entity-store/src/main/kotlin/jetbrains/exodus/entitystore/iterate/binop/MinusIterable.kt | 1 | 8722 | /**
* Copyright 2010 - 2022 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package jetbrains.exodus.entitystore.iterate.binop
import jetbrains.exodus.entitystore.*
import jetbrains.exodus.entitystore.iterate.EntityIterableBase
import jetbrains.exodus.entitystore.iterate.EntityIteratorBase
import jetbrains.exodus.entitystore.iterate.EntityIteratorFixingDecorator
import jetbrains.exodus.entitystore.iterate.NonDisposableEntityIterator
import jetbrains.exodus.kotlin.notNull
class MinusIterable(
txn: PersistentStoreTransaction?,
minuend: EntityIterableBase,
subtrahend: EntityIterableBase
) : BinaryOperatorEntityIterable(txn, minuend, subtrahend, false) {
init {
// minuend is always equal to iterable1, 'cause we are not commutative
if (minuend.isSortedById) {
depth += SORTED_BY_ID_FLAG
}
}
override fun getIterableType(): EntityIterableType {
return EntityIterableType.MINUS
}
override fun getIteratorImpl(txn: PersistentStoreTransaction): EntityIteratorBase {
val iterable1 = iterable1
val iterable2 = iterable2
return EntityIteratorFixingDecorator(
this,
if (isSortedById && iterable2.isSortedById) SortedIterator(
this,
iterable1,
iterable2
) else UnsortedIterator(this, txn, iterable1, iterable2)
)
}
override fun getReverseIteratorImpl(txn: PersistentStoreTransaction): EntityIterator {
return if (isSortedById && iterable2.isSortedById) {
EntityIteratorFixingDecorator(
this,
SortedReverseIterator(this, txn, iterable1, iterable2)
)
} else super.getReverseIteratorImpl(txn)
}
private abstract class SortedIteratorBase(iterable: EntityIterableBase) : NonDisposableEntityIterator(iterable) {
protected var nextId: EntityId? = null
protected var currentMinuend: EntityId? = null
protected var currentSubtrahend: EntityId? = null
public override fun nextIdImpl(): EntityId? = nextId
}
private class SortedIterator(
iterable: EntityIterableBase, minuend: EntityIterableBase, subtrahend: EntityIterableBase
) : SortedIteratorBase(iterable) {
private val minuend = minuend.iterator() as EntityIteratorBase
private val subtrahend = subtrahend.iterator() as EntityIteratorBase
override fun hasNextImpl(): Boolean {
var currentMinuend = currentMinuend
var currentSubtrahend = currentSubtrahend
while (currentMinuend !== PersistentEntityId.EMPTY_ID) {
if (currentMinuend == null) {
currentMinuend = checkNextId(minuend)
this.currentMinuend = currentMinuend
}
if (currentSubtrahend == null) {
currentSubtrahend = checkNextId(subtrahend)
this.currentSubtrahend = currentSubtrahend
}
// no more ids in minuend
if (currentMinuend.also { nextId = it } === PersistentEntityId.EMPTY_ID) {
break
}
// no more ids subtrahend
if (currentSubtrahend === PersistentEntityId.EMPTY_ID) {
currentMinuend = null
break
}
if (currentMinuend !== currentSubtrahend && (currentMinuend == null || currentSubtrahend == null)) {
break
}
if (currentMinuend === currentSubtrahend) {
currentSubtrahend = null
currentMinuend = null
continue
}
val cmp = currentMinuend?.compareTo(currentSubtrahend) ?: throw throw IllegalStateException("Can't be")
if (cmp < 0) {
currentMinuend = null
break
}
currentSubtrahend = null
if (cmp == 0) {
currentMinuend = null
}
}
this.currentMinuend = currentMinuend
this.currentSubtrahend = currentSubtrahend
return this.currentMinuend !== PersistentEntityId.EMPTY_ID
}
}
private class SortedReverseIterator(
iterable: EntityIterableBase,
txn: PersistentStoreTransaction,
minuend: EntityIterableBase,
subtrahend: EntityIterableBase
) : SortedIteratorBase(iterable) {
private val minuend = minuend.getReverseIteratorImpl(txn) as EntityIteratorBase
private val subtrahend = subtrahend.getReverseIteratorImpl(txn) as EntityIteratorBase
override fun hasNextImpl(): Boolean {
var currentMinuend = currentMinuend
var currentSubtrahend = currentSubtrahend
while (currentMinuend !== PersistentEntityId.EMPTY_ID) {
if (currentMinuend == null) {
currentMinuend = checkNextId(minuend)
this.currentMinuend = currentMinuend
}
if (currentSubtrahend == null) {
currentSubtrahend = checkNextId(subtrahend)
this.currentSubtrahend = currentSubtrahend
}
// no more ids in minuend
if (currentMinuend.also { nextId = it } === PersistentEntityId.EMPTY_ID) {
break
}
// no more ids subtrahend
if (currentSubtrahend === PersistentEntityId.EMPTY_ID) {
currentMinuend = null
break
}
if (currentMinuend !== currentSubtrahend && (currentMinuend == null || currentSubtrahend == null)) {
break
}
if (currentMinuend === currentSubtrahend) {
currentSubtrahend = null
currentMinuend = null
continue
}
val cmp = currentMinuend?.compareTo(currentSubtrahend) ?: throw throw IllegalStateException("Can't be")
if (cmp > 0) {
currentMinuend = null
break
}
currentSubtrahend = null
if (cmp == 0) {
currentMinuend = null
}
}
this.currentMinuend = currentMinuend
this.currentSubtrahend = currentSubtrahend
return this.currentMinuend !== PersistentEntityId.EMPTY_ID
}
}
private class UnsortedIterator constructor(
iterable: EntityIterableBase,
private val txn: PersistentStoreTransaction,
minuend: EntityIterableBase,
subtrahend: EntityIterableBase
) : NonDisposableEntityIterator(iterable) {
private val minuend = minuend.iterator() as EntityIteratorBase
private var subtrahend: EntityIterableBase? = subtrahend
private val exceptSet by lazy(LazyThreadSafetyMode.NONE) {
this.subtrahend.notNull.toSet(txn).also {
// reclaim memory as early as possible
this.subtrahend = null
}
}
private var nextId: EntityId? = null
override fun hasNextImpl(): Boolean {
while (minuend.hasNext()) {
val nextId = minuend.nextId()
if (!exceptSet.contains(nextId)) {
this.nextId = nextId
return true
}
}
nextId = null
return false
}
public override fun nextIdImpl(): EntityId? = nextId
}
companion object {
init {
registerType(EntityIterableType.MINUS) { txn, _, parameters ->
MinusIterable(
txn,
parameters[0] as EntityIterableBase, parameters[1] as EntityIterableBase
)
}
}
}
}
private fun checkNextId(it: EntityIterator): EntityId? = if (it.hasNext()) it.nextId() else PersistentEntityId.EMPTY_ID
| apache-2.0 | 1516efa60fd1c7f182381b8790842130 | 37.9375 | 119 | 0.589314 | 6.181432 | false | false | false | false |
androidx/androidx | compose/ui/ui-test/src/commonMain/kotlin/androidx/compose/ui/test/TouchInjectionScope.kt | 3 | 32018 | /*
* 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.ui.test
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.geometry.lerp
import androidx.compose.ui.platform.ViewConfiguration
import androidx.compose.ui.util.lerp
import kotlin.math.ceil
import kotlin.math.max
import kotlin.math.roundToInt
import kotlin.math.roundToLong
import androidx.compose.ui.test.internal.JvmDefaultWithCompatibility
/**
* The receiver scope of the touch input injection lambda from [performTouchInput].
*
* The functions in [TouchInjectionScope] can roughly be divided into two groups: full gestures
* and individual touch events. The individual touch events are: [down], [move] and friends, [up],
* [cancel] and [advanceEventTime]. Full gestures are all the other functions, like
* [click][TouchInjectionScope.click], [doubleClick][TouchInjectionScope.doubleClick],
* [swipe][TouchInjectionScope.swipe], etc. These are built on top of the individual events and
* serve as a good example on how you can build your own full gesture functions.
*
* A touch gesture is started with a [down] event, followed by a sequence of [move] events and
* finally an [up] event, optionally combined with more sets of [down] and [up] events for
* multi-touch gestures. Most methods accept a pointerId to specify which pointer (finger) the
* event applies to. Movement can be expressed absolutely with [moveTo] and [updatePointerTo], or
* relative to the current pointer position with [moveBy] and [updatePointerBy]. The `moveTo/By`
* methods enqueue an event immediately, while the `updatePointerTo/By` methods don't. This
* allows you to update the position of multiple pointers in a single [move] event for
* multi-touch gestures. Touch gestures can be cancelled with [cancel]. All events, regardless
* the method used, will always contain the current position of _all_ pointers.
*
* The entire event injection state is shared between all `perform.*Input` methods, meaning you
* can continue an unfinished touch gesture in a subsequent invocation of [performTouchInput] or
* [performMultiModalInput]. Note however that while the pointer positions are retained across
* invocation of `perform.*Input` methods, they are always manipulated in the current node's
* local coordinate system. That means that two subsequent invocations of [performTouchInput] on
* different nodes will report a different [currentPosition], even though it is actually the same
* position on the screen.
*
* All events sent by these methods are batched together and sent as a whole after
* [performTouchInput] has executed its code block. Because gestures don't have to be defined all
* in the same [performTouchInput] block, keep in mind that while the gesture is not complete,
* all code you execute in between these blocks will be executed while imaginary fingers are
* actively touching the screen. The events sent as part of the same batch will not be interrupted
* by recomposition, however, if a gesture spans multiple [performTouchInput] blocks it is
* important to remember that recomposition, layout and drawing could take place during the
* gesture, which may lead to events being injected into a moving target. As pointer positions are
* manipulated in the current node's local coordinate system, this could lead to issues caused by
* the fact that part of the gesture will take effect before the rest of the events have been
* enqueued.
*
* Example of performing a click:
* @sample androidx.compose.ui.test.samples.touchInputClick
*
* Example of performing a swipe up:
* @sample androidx.compose.ui.test.samples.touchInputSwipeUp
*
* Example of performing an L-shaped gesture:
* @sample androidx.compose.ui.test.samples.touchInputLShapedGesture
*
* @see InjectionScope
*/
@JvmDefaultWithCompatibility
interface TouchInjectionScope : InjectionScope {
/**
* Returns the current position of the given [pointerId]. The default [pointerId] is 0. The
* position is returned in the local coordinate system of the node with which we're
* interacting. (0, 0) is the top left corner of the node.
*/
fun currentPosition(pointerId: Int = 0): Offset?
/**
* Sends a down event for the pointer with the given [pointerId] at [position] on the
* associated node. The [position] is in the node's local coordinate system, where (0, 0) is
* the top left corner of the node.
*
* If no pointers are down yet, this will start a new touch gesture. If a gesture is already
* in progress, this event is sent at the same timestamp as the last event. If the given
* pointer is already down, an [IllegalArgumentException] will be thrown.
*
* @param pointerId The id of the pointer, can be any number not yet in use by another pointer
* @param position The position of the down event, in the node's local coordinate system
*/
fun down(pointerId: Int, position: Offset)
/**
* Sends a down event for the default pointer at [position] on the associated node. The
* [position] is in the node's local coordinate system, where (0, 0) is the top left corner
* of the node. The default pointer has `pointerId = 0`.
*
* If no pointers are down yet, this will start a new touch gesture. If a gesture is already
* in progress, this event is sent at the same timestamp as the last event. If the default
* pointer is already down, an [IllegalArgumentException] will be thrown.
*
* @param position The position of the down event, in the node's local coordinate system
*/
fun down(position: Offset) {
down(0, position)
}
/**
* Sends a move event [delayMillis] after the last sent event on the associated node, with
* the position of the pointer with the given [pointerId] updated to [position]. The
* [position] is in the node's local coordinate system, where (0, 0) is the top left corner
* of the node.
*
* If the pointer is not yet down, an [IllegalArgumentException] will be thrown.
*
* @param pointerId The id of the pointer to move, as supplied in [down]
* @param position The new position of the pointer, in the node's local coordinate system
* @param delayMillis The time between the last sent event and this event.
* [eventPeriodMillis] by default.
*/
fun moveTo(pointerId: Int, position: Offset, delayMillis: Long = eventPeriodMillis) {
updatePointerTo(pointerId, position)
move(delayMillis)
}
/**
* Sends a move event [delayMillis] after the last sent event on the associated node, with
* the position of the default pointer updated to [position]. The [position] is in the node's
* local coordinate system, where (0, 0) is the top left corner of the node. The default
* pointer has `pointerId = 0`.
*
* If the default pointer is not yet down, an [IllegalArgumentException] will be thrown.
*
* @param position The new position of the pointer, in the node's local coordinate system
* @param delayMillis The time between the last sent event and this event.
* [eventPeriodMillis] by default.
*/
fun moveTo(position: Offset, delayMillis: Long = eventPeriodMillis) {
moveTo(0, position, delayMillis)
}
/**
* Updates the position of the pointer with the given [pointerId] to the given [position], but
* does not send a move event. The move event can be sent with [move]. The [position] is in
* the node's local coordinate system, where (0.px, 0.px) is the top left corner of the
* node.
*
* If the pointer is not yet down, an [IllegalArgumentException] will be thrown.
*
* @param pointerId The id of the pointer to move, as supplied in [down]
* @param position The new position of the pointer, in the node's local coordinate system
*/
fun updatePointerTo(pointerId: Int, position: Offset)
/**
* Sends a move event [delayMillis] after the last sent event on the associated node, with
* the position of the pointer with the given [pointerId] moved by the given [delta].
*
* If the pointer is not yet down, an [IllegalArgumentException] will be thrown.
*
* @param pointerId The id of the pointer to move, as supplied in [down]
* @param delta The position for this move event, relative to the current position of the
* pointer. For example, `delta = Offset(10.px, -10.px) will add 10.px to the pointer's
* x-position, and subtract 10.px from the pointer's y-position.
* @param delayMillis The time between the last sent event and this event.
* [eventPeriodMillis] by default.
*/
fun moveBy(pointerId: Int, delta: Offset, delayMillis: Long = eventPeriodMillis) {
updatePointerBy(pointerId, delta)
move(delayMillis)
}
/**
* Sends a move event [delayMillis] after the last sent event on the associated node, with
* the position of the default pointer moved by the given [delta]. The default pointer has
* `pointerId = 0`.
*
* If the pointer is not yet down, an [IllegalArgumentException] will be thrown.
*
* @param delta The position for this move event, relative to the current position of the
* pointer. For example, `delta = Offset(10.px, -10.px) will add 10.px to the pointer's
* x-position, and subtract 10.px from the pointer's y-position.
* @param delayMillis The time between the last sent event and this event.
* [eventPeriodMillis] by default.
*/
fun moveBy(delta: Offset, delayMillis: Long = eventPeriodMillis) {
moveBy(0, delta, delayMillis)
}
/**
* Updates the position of the pointer with the given [pointerId] by the given [delta], but
* does not send a move event. The move event can be sent with [move].
*
* If the pointer is not yet down, an [IllegalArgumentException] will be thrown.
*
* @param pointerId The id of the pointer to move, as supplied in [down]
* @param delta The position for this move event, relative to the last sent position of the
* pointer. For example, `delta = Offset(10.px, -10.px) will add 10.px to the pointer's
* x-position, and subtract 10.px from the pointer's y-position.
*/
fun updatePointerBy(pointerId: Int, delta: Offset) {
// Ignore currentPosition of null here, let updatePointerTo generate the error
val position = (currentPosition(pointerId) ?: Offset.Zero) + delta
updatePointerTo(pointerId, position)
}
/**
* Sends a move event [delayMillis] after the last sent event without updating any of the
* pointer positions. This can be useful when batching movement of multiple pointers
* together, which can be done with [updatePointerTo] and [updatePointerBy].
*
* @param delayMillis The time between the last sent event and this event.
* [eventPeriodMillis] by default.
*/
fun move(delayMillis: Long = eventPeriodMillis)
/**
* Sends a move event [delayMillis] after the last sent event without updating any of the
* pointer positions.
*
* This overload supports gestures with multiple pointers.
*
* @param relativeHistoricalTimes Time of each historical event, as a millisecond relative to
* the time the actual event is sent. For example, -10L means 10ms earlier.
* @param historicalCoordinates Coordinates of each historical event, in the same coordinate
* space as [moveTo]. The outer list must have the same size as the number of pointers in the
* event, and each inner list must have the same size as [relativeHistoricalTimes].
* @param delayMillis The time between the last sent event and this event.
* [eventPeriodMillis] by default.
*/
@ExperimentalTestApi
fun moveWithHistoryMultiPointer(
relativeHistoricalTimes: List<Long>,
historicalCoordinates: List<List<Offset>>,
delayMillis: Long = eventPeriodMillis
)
/**
* Sends a move event [delayMillis] after the last sent event without updating any of the
* pointer positions.
*
* This overload is a convenience method for the common case where the gesture only has one
* pointer.
*
* @param relativeHistoricalTimes Time of each historical event, as a millisecond relative to
* the time the actual event is sent. For example, -10L means 10ms earlier.
* @param historicalCoordinates Coordinates of each historical event, in the same coordinate
* space as [moveTo]. The list must have the same size as [relativeHistoricalTimes].
* @param delayMillis The time between the last sent event and this event.
* [eventPeriodMillis] by default.
*/
@ExperimentalTestApi
fun moveWithHistory(
relativeHistoricalTimes: List<Long>,
historicalCoordinates: List<Offset>,
delayMillis: Long = eventPeriodMillis
) = moveWithHistoryMultiPointer(
relativeHistoricalTimes,
listOf(historicalCoordinates),
delayMillis
)
/**
* Sends an up event for the pointer with the given [pointerId], or the default pointer if
* [pointerId] is omitted, on the associated node.
*
* @param pointerId The id of the pointer to lift up, as supplied in [down]
*/
fun up(pointerId: Int = 0)
/**
* Sends a cancel event [delayMillis] after the last sent event to cancel the current
* gesture. The cancel event contains the current position of all active pointers.
*
* @param delayMillis The time between the last sent event and this event.
* [eventPeriodMillis] by default.
*/
fun cancel(delayMillis: Long = eventPeriodMillis)
}
internal class TouchInjectionScopeImpl(
private val baseScope: MultiModalInjectionScopeImpl
) : TouchInjectionScope, InjectionScope by baseScope {
private val inputDispatcher get() = baseScope.inputDispatcher
private fun localToRoot(position: Offset) = baseScope.localToRoot(position)
override fun currentPosition(pointerId: Int): Offset? {
val positionInRoot = inputDispatcher.getCurrentTouchPosition(pointerId) ?: return null
return baseScope.rootToLocal(positionInRoot)
}
override fun down(pointerId: Int, position: Offset) {
val positionInRoot = localToRoot(position)
inputDispatcher.enqueueTouchDown(pointerId, positionInRoot)
}
override fun updatePointerTo(pointerId: Int, position: Offset) {
val positionInRoot = localToRoot(position)
inputDispatcher.updateTouchPointer(pointerId, positionInRoot)
}
override fun move(delayMillis: Long) {
advanceEventTime(delayMillis)
inputDispatcher.enqueueTouchMove()
}
@ExperimentalTestApi
override fun moveWithHistoryMultiPointer(
relativeHistoricalTimes: List<Long>,
historicalCoordinates: List<List<Offset>>,
delayMillis: Long
) {
repeat(relativeHistoricalTimes.size) {
check(relativeHistoricalTimes[it] < 0) {
"Relative historical times should be negative, in order to be in the past" +
"(offset $it was: ${relativeHistoricalTimes[it]})"
}
check(relativeHistoricalTimes[it] >= -delayMillis) {
"Relative historical times should not be earlier than the previous event " +
"(offset $it was: ${relativeHistoricalTimes[it]}, ${-delayMillis})"
}
}
advanceEventTime(delayMillis)
inputDispatcher.enqueueTouchMoves(relativeHistoricalTimes, historicalCoordinates)
}
override fun up(pointerId: Int) {
inputDispatcher.enqueueTouchUp(pointerId)
}
override fun cancel(delayMillis: Long) {
advanceEventTime(delayMillis)
inputDispatcher.enqueueTouchCancel()
}
}
/**
* Performs a click gesture (aka a tap) on the associated node.
*
* The click is done at the given [position], or in the [center] if the [position] is omitted.
* The [position] is in the node's local coordinate system, where (0, 0) is the top left corner
* of the node.
*
* @param position The position where to click, in the node's local coordinate system. If
* omitted, the [center] of the node will be used.
*/
fun TouchInjectionScope.click(position: Offset = center) {
down(position)
move()
up()
}
/**
* Performs a long click gesture (aka a long press) on the associated node.
*
* The long click is done at the given [position], or in the [center] if the [position] is
* omitted. By default, the [durationMillis] of the press is 100ms longer than the minimum
* required duration for a long press. The [position] is in the node's local coordinate system,
* where (0, 0) is the top left corner of the node.
*
* @param position The position of the long click, in the node's local coordinate system. If
* omitted, the [center] of the node will be used.
* @param durationMillis The time between the down and the up event
*/
fun TouchInjectionScope.longClick(
position: Offset = center,
durationMillis: Long = viewConfiguration.longPressTimeoutMillis + 100
) {
require(durationMillis >= viewConfiguration.longPressTimeoutMillis) {
"Long click must have a duration of at least ${viewConfiguration.longPressTimeoutMillis}ms"
}
swipe(position, position, durationMillis)
}
// The average of min and max is a safe default
private val ViewConfiguration.defaultDoubleTapDelayMillis: Long
get() = (doubleTapMinTimeMillis + doubleTapTimeoutMillis) / 2
/**
* Performs a double click gesture (aka a double tap) on the associated node.
*
* The double click is done at the given [position] or in the [center] if the [position] is
* omitted. By default, the [delayMillis] between the first and the second click is half way in
* between the minimum and maximum required delay for a double click. The [position] is in the
* node's local coordinate system, where (0, 0) is the top left corner of the node.
*
* @param position The position of the double click, in the node's local coordinate system.
* If omitted, the [center] position will be used.
* @param delayMillis The time between the up event of the first click and the down event of the
* second click
*/
fun TouchInjectionScope.doubleClick(
position: Offset = center,
delayMillis: Long = viewConfiguration.defaultDoubleTapDelayMillis
) {
require(delayMillis >= viewConfiguration.doubleTapMinTimeMillis) {
"Time between clicks in double click must be at least " +
"${viewConfiguration.doubleTapMinTimeMillis}ms"
}
require(delayMillis < viewConfiguration.doubleTapTimeoutMillis) {
"Time between clicks in double click must be smaller than " +
"${viewConfiguration.doubleTapTimeoutMillis}ms"
}
click(position)
advanceEventTime(delayMillis)
click(position)
}
/**
* Performs a swipe gesture on the associated node.
*
* The motion events are linearly interpolated between [start] and [end]. The coordinates are in
* the node's local coordinate system, where (0, 0) is the top left corner of the node. The
* default duration is 200 milliseconds.
*
* @param start The start position of the gesture, in the node's local coordinate system
* @param end The end position of the gesture, in the node's local coordinate system
* @param durationMillis The duration of the gesture
*/
fun TouchInjectionScope.swipe(
start: Offset,
end: Offset,
durationMillis: Long = 200
) {
val durationFloat = durationMillis.toFloat()
swipe(
curve = { lerp(start, end, it / durationFloat) },
durationMillis = durationMillis
)
}
/**
* Performs a swipe gesture on the associated node.
*
* The swipe follows the [curve] from 0 till [durationMillis]. Will force sampling of an event at
* all times defined in [keyTimes]. The time between events is kept as close to
* [eventPeriodMillis][InjectionScope.eventPeriodMillis] as possible, given the constraints. The
* coordinates are in the node's local coordinate system, where (0, 0) is the top left corner of
* the node. The default duration is 200 milliseconds.
*
* @param curve The function that defines the position of the gesture over time
* @param durationMillis The duration of the gesture
* @param keyTimes An optional list of timestamps in milliseconds at which a move event must
* be sampled
*/
fun TouchInjectionScope.swipe(
curve: (Long) -> Offset,
durationMillis: Long,
keyTimes: List<Long> = emptyList()
) {
@OptIn(ExperimentalTestApi::class)
multiTouchSwipe(listOf(curve), durationMillis, keyTimes)
}
/**
* Performs a multi touch swipe gesture on the associated node.
*
* Each pointer follows [curves][i] from 0 till [durationMillis]. Sampling of an event is
* forced at all times defined in [keyTimes]. The time between events is kept as close to
* [eventPeriodMillis][InjectionScope.eventPeriodMillis] as possible, given the constraints. The
* coordinates are in the node's local coordinate system, where (0, 0) is the top left corner of
* the node. The default duration is 200 milliseconds.
*
* Will stay experimental until support has been added to start and end each pointer at
* different times.
*
* @param curves The functions that define the position of the gesture over time
* @param durationMillis The duration of the gesture
* @param keyTimes An optional list of timestamps in milliseconds at which a move event must
* be sampled
*/
@ExperimentalTestApi
fun TouchInjectionScope.multiTouchSwipe(
curves: List<(Long) -> Offset>,
durationMillis: Long,
keyTimes: List<Long> = emptyList()
) {
val startTime = 0L
val endTime = durationMillis
// Validate input
require(durationMillis >= 1) {
"duration must be at least 1 millisecond, not $durationMillis"
}
val validRange = startTime..endTime
require(keyTimes.all { it in validRange }) {
"keyTimes contains timestamps out of range [$startTime..$endTime]: $keyTimes"
}
require(keyTimes.asSequence().zipWithNext { a, b -> a <= b }.all { it }) {
"keyTimes must be sorted: $keyTimes"
}
// Send down events
curves.forEachIndexed { i, curve ->
down(i, curve(startTime))
}
// Send move events between each consecutive pair in [t0, ..keyTimes, tN]
var currTime = startTime
var key = 0
while (currTime < endTime) {
// advance key
while (key < keyTimes.size && keyTimes[key] <= currTime) {
key++
}
// send events between t and next keyTime
val tNext = if (key < keyTimes.size) keyTimes[key] else endTime
sendMultiTouchSwipeSegment(curves, currTime, tNext)
currTime = tNext
}
// And end with up events
repeat(curves.size) {
up(it)
}
}
/**
* Generates move events between `f([t0])` and `f([tN])` during the time window `(t0, tN]`, for
* each `f` in [fs], following the curves defined by each `f`. The number of events sent
* (#numEvents) is such that the time between each event is as close to
* [eventPeriodMillis][InputDispatcher.eventPeriodMillis] as possible, but at least 1. The first
* event is sent at time `downTime + (tN - t0) / #numEvents`, the last event is sent at time tN.
*
* @param fs The functions that define the coordinates of the respective gestures over time
* @param t0 The start time of this segment of the swipe, in milliseconds relative to downTime
* @param tN The end time of this segment of the swipe, in milliseconds relative to downTime
*/
private fun TouchInjectionScope.sendMultiTouchSwipeSegment(
fs: List<(Long) -> Offset>,
t0: Long,
tN: Long
) {
var step = 0
// How many steps will we take between t0 and tN? At least 1, and a number that will
// bring as as close to eventPeriod as possible
val steps = max(1, ((tN - t0) / eventPeriodMillis.toFloat()).roundToInt())
var tPrev = t0
while (step++ < steps) {
val progress = step / steps.toFloat()
val t = lerp(t0, tN, progress)
fs.forEachIndexed { i, f ->
updatePointerTo(i, f(t))
}
move(t - tPrev)
tPrev = t
}
}
/**
* Performs a pinch gesture on the associated node.
*
* For each pair of start and end [Offset]s, the motion events are linearly interpolated. The
* coordinates are in the node's local coordinate system where (0, 0) is the top left corner of
* the node. The default duration is 400 milliseconds.
*
* @param start0 The start position of the first gesture in the node's local coordinate system
* @param end0 The end position of the first gesture in the node's local coordinate system
* @param start1 The start position of the second gesture in the node's local coordinate system
* @param end1 The end position of the second gesture in the node's local coordinate system
* @param durationMillis the duration of the gesture
*/
fun TouchInjectionScope.pinch(
start0: Offset,
end0: Offset,
start1: Offset,
end1: Offset,
durationMillis: Long = 400
) {
val durationFloat = durationMillis.toFloat()
@OptIn(ExperimentalTestApi::class)
multiTouchSwipe(
listOf(
{ lerp(start0, end0, it / durationFloat) },
{ lerp(start1, end1, it / durationFloat) }
),
durationMillis
)
}
/**
* Performs a swipe gesture on the associated node such that it ends with the given [endVelocity].
*
* The swipe will go through [start] at t=0 and through [end] at t=[durationMillis]. In between,
* the swipe will go monotonically from [start] and [end], but not strictly. Due to imprecision,
* no guarantees can be made for the actual velocity at the end of the gesture, but generally it
* is within 0.1 of the desired velocity.
*
* When a swipe cannot be created that results in the desired velocity (because the input is too
* restrictive), an exception will be thrown with suggestions to fix the input.
*
* The coordinates are in the node's local coordinate system, where (0, 0) is the top left corner
* of the node. The default duration is calculated such that a feasible swipe can be created that
* ends in the given velocity.
*
* @param start The start position of the gesture, in the node's local coordinate system
* @param end The end position of the gesture, in the node's local coordinate system
* @param endVelocity The velocity of the gesture at the moment it ends in px/second. Must be
* positive.
* @param durationMillis The duration of the gesture in milliseconds. Must be long enough that at
* least 3 input events are generated, which happens with a duration of 40ms or more. If omitted,
* a duration is calculated such that a valid swipe with velocity can be created.
*
* @throws IllegalArgumentException When no swipe can be generated that will result in the desired
* velocity. The error message will suggest changes to the input parameters such that a swipe
* will become feasible.
*/
fun TouchInjectionScope.swipeWithVelocity(
start: Offset,
end: Offset,
/*@FloatRange(from = 0.0)*/
endVelocity: Float,
durationMillis: Long = VelocityPathFinder.calculateDefaultDuration(start, end, endVelocity)
) {
require(endVelocity >= 0f) {
"Velocity cannot be $endVelocity, it must be positive"
}
require(eventPeriodMillis < 40) {
"InputDispatcher.eventPeriod must be smaller than 40ms in order to generate velocities"
}
val minimumDuration = ceil(2.5f * eventPeriodMillis).roundToLong()
require(durationMillis >= minimumDuration) {
"Duration must be at least ${minimumDuration}ms because " +
"velocity requires at least 3 input events"
}
val pathFinder = VelocityPathFinder(start, end, endVelocity, durationMillis)
swipe(pathFinder.generateFunction(), durationMillis)
}
/**
* Performs a swipe up gesture along `x = [centerX]` of the associated node, from [startY] till
* [endY], taking [durationMillis] milliseconds.
*
* @param startY The y-coordinate of the start of the swipe. Must be greater than or equal to the
* [endY]. By default the [bottom] of the node.
* @param endY The y-coordinate of the end of the swipe. Must be less than or equal to the
* [startY]. By default the [top] of the node.
* @param durationMillis The duration of the swipe. By default 200 milliseconds.
*/
fun TouchInjectionScope.swipeUp(
startY: Float = bottom,
endY: Float = top,
durationMillis: Long = 200
) {
require(startY >= endY) {
"startY=$startY needs to be greater than or equal to endY=$endY"
}
val start = Offset(centerX, startY)
val end = Offset(centerX, endY)
swipe(start, end, durationMillis)
}
/**
* Performs a swipe down gesture along `x = [centerX]` of the associated node, from [startY] till
* [endY], taking [durationMillis] milliseconds.
*
* @param startY The y-coordinate of the start of the swipe. Must be less than or equal to the
* [endY]. By default the [top] of the node.
* @param endY The y-coordinate of the end of the swipe. Must be greater than or equal to the
* [startY]. By default the [bottom] of the node.
* @param durationMillis The duration of the swipe. By default 200 milliseconds.
*/
fun TouchInjectionScope.swipeDown(
startY: Float = top,
endY: Float = bottom,
durationMillis: Long = 200
) {
require(startY <= endY) {
"startY=$startY needs to be less than or equal to endY=$endY"
}
val start = Offset(centerX, startY)
val end = Offset(centerX, endY)
swipe(start, end, durationMillis)
}
/**
* Performs a swipe left gesture along `y = [centerY]` of the associated node, from [startX] till
* [endX], taking [durationMillis] milliseconds.
*
* @param startX The x-coordinate of the start of the swipe. Must be greater than or equal to the
* [endX]. By default the [right] of the node.
* @param endX The x-coordinate of the end of the swipe. Must be less than or equal to the
* [startX]. By default the [left] of the node.
* @param durationMillis The duration of the swipe. By default 200 milliseconds.
*/
fun TouchInjectionScope.swipeLeft(
startX: Float = right,
endX: Float = left,
durationMillis: Long = 200
) {
require(startX >= endX) {
"startX=$startX needs to be greater than or equal to endX=$endX"
}
val start = Offset(startX, centerY)
val end = Offset(endX, centerY)
swipe(start, end, durationMillis)
}
/**
* Performs a swipe right gesture along `y = [centerY]` of the associated node, from [startX]
* till [endX], taking [durationMillis] milliseconds.
*
* @param startX The x-coordinate of the start of the swipe. Must be less than or equal to the
* [endX]. By default the [left] of the node.
* @param endX The x-coordinate of the end of the swipe. Must be greater than or equal to the
* [startX]. By default the [right] of the node.
* @param durationMillis The duration of the swipe. By default 200 milliseconds.
*/
fun TouchInjectionScope.swipeRight(
startX: Float = left,
endX: Float = right,
durationMillis: Long = 200
) {
require(startX <= endX) {
"startX=$startX needs to be less than or equal to endX=$endX"
}
val start = Offset(startX, centerY)
val end = Offset(endX, centerY)
swipe(start, end, durationMillis)
}
| apache-2.0 | 24731b56f77e477214f6c573c31da42f | 42.680764 | 99 | 0.705697 | 4.434012 | false | false | false | false |
androidx/androidx | camera/integration-tests/avsynctestapp/src/main/java/androidx/camera/integration/avsync/model/AudioGenerator.kt | 3 | 6101 | /*
* 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.camera.integration.avsync.model
import android.content.Context
import android.media.AudioAttributes
import android.media.AudioFormat
import android.media.AudioManager
import android.media.AudioTrack
import androidx.annotation.VisibleForTesting
import androidx.camera.core.Logger
import androidx.core.util.Preconditions.checkArgument
import androidx.core.util.Preconditions.checkArgumentNonnegative
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import kotlin.math.pow
import kotlin.math.sin
private const val TAG = "AudioGenerator"
private const val DEFAULT_SAMPLE_RATE: Int = 44100
private const val SAMPLE_WIDTH: Int = 2
private const val MAGNITUDE = 0.5
private const val ENCODING: Int = AudioFormat.ENCODING_PCM_16BIT
private const val CHANNEL = AudioFormat.CHANNEL_OUT_MONO
class AudioGenerator(private val isEnabled: Boolean = true) {
@VisibleForTesting
var audioTrack: AudioTrack? = null
fun start() {
if (isEnabled) {
startInternal()
} else {
Logger.i(TAG, "Will not start audio generation, since AudioGenerator is disabled.")
}
}
private fun startInternal() {
Logger.i(TAG, "start audio generation")
audioTrack!!.play()
}
fun stop() {
if (isEnabled) {
stopInternal()
} else {
Logger.i(TAG, "Will not stop audio generation, since AudioGenerator is disabled.")
}
}
private fun stopInternal() {
Logger.i(TAG, "stop audio generation")
Logger.i(TAG, "playState before stopped: ${audioTrack!!.playState}")
Logger.i(TAG, "playbackHeadPosition before stopped: ${audioTrack!!.playbackHeadPosition}")
audioTrack!!.stop()
audioTrack!!.reloadStaticData()
}
suspend fun initial(
context: Context,
frequency: Int,
beepLengthInSec: Double,
): Boolean {
checkArgumentNonnegative(frequency, "The input frequency should not be negative.")
checkArgument(beepLengthInSec >= 0, "The beep length should not be negative.")
return if (isEnabled) {
initAudioTrackInternal(context, frequency, beepLengthInSec)
} else {
Logger.i(TAG, "Will not initial audio track, since AudioGenerator is disabled.")
true
}
}
private suspend fun initAudioTrackInternal(
context: Context,
frequency: Int,
beepLengthInSec: Double,
): Boolean {
val sampleRate = getOutputSampleRate(context)
val samples = generateSineSamples(frequency, beepLengthInSec, SAMPLE_WIDTH, sampleRate)
val bufferSize = samples.size
Logger.i(TAG, "initAudioTrack with sample rate: $sampleRate")
Logger.i(TAG, "initAudioTrack with beep frequency: $frequency")
Logger.i(TAG, "initAudioTrack with buffer size: $bufferSize")
val audioAttributes = AudioAttributes.Builder()
.setUsage(AudioAttributes.USAGE_MEDIA)
.setContentType(AudioAttributes.CONTENT_TYPE_MUSIC)
.build()
val audioFormat = AudioFormat.Builder()
.setSampleRate(sampleRate)
.setEncoding(ENCODING)
.setChannelMask(CHANNEL)
.build()
audioTrack = AudioTrack(
audioAttributes,
audioFormat,
bufferSize,
AudioTrack.MODE_STATIC,
AudioManager.AUDIO_SESSION_ID_GENERATE
)
audioTrack!!.write(samples, 0, samples.size)
return true
}
private fun getOutputSampleRate(context: Context): Int {
val audioManager = context.getSystemService(Context.AUDIO_SERVICE) as AudioManager
val sampleRate: String? = audioManager.getProperty(AudioManager.PROPERTY_OUTPUT_SAMPLE_RATE)
return sampleRate?.toInt() ?: DEFAULT_SAMPLE_RATE
}
@VisibleForTesting
suspend fun generateSineSamples(
frequency: Int,
beepLengthInSec: Double,
sampleWidth: Int,
sampleRate: Int
): ByteArray {
val waveData = generateSineData(frequency, beepLengthInSec, sampleRate)
val samples = toSamples(waveData, sampleWidth)
return samples.toByteArray()
}
/**
* magnitude is expected to be from 0 to 1
*/
@VisibleForTesting
suspend fun generateSineData(
frequency: Int,
lengthInSec: Double,
sampleRate: Int,
magnitude: Double = MAGNITUDE
): List<Double> = withContext(Dispatchers.Default) {
val n = (lengthInSec * sampleRate).toInt()
val angularFrequency = 2.0 * Math.PI * frequency
val res = mutableListOf<Double>()
for (i in 0 until n) {
val x = i * lengthInSec / n
val y = magnitude * sin(angularFrequency * x)
res.add(y)
}
res
}
@VisibleForTesting
suspend fun toSamples(
data: List<Double>,
sampleWidth: Int
): List<Byte> = withContext(Dispatchers.Default) {
val scaleFactor = 2.toDouble().pow(8 * sampleWidth - 1) - 1
data.flatMap {
(it * scaleFactor).toInt().toBytes(sampleWidth)
}
}
@VisibleForTesting
fun Int.toBytes(sampleWidth: Int): List<Byte> {
val res = mutableListOf<Byte>()
for (i in 0 until sampleWidth) {
val byteValue = (this shr (8 * i)).toByte()
res.add(byteValue)
}
return res
}
} | apache-2.0 | 0c091ed3a51fee6d42fa9bef6ae59d6c | 30.947644 | 100 | 0.652352 | 4.722136 | false | false | false | false |
androidx/androidx | room/room-compiler/src/main/kotlin/androidx/room/writer/TypeWriter.kt | 3 | 6960 | /*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.room.writer
import androidx.room.RoomProcessor
import androidx.room.compiler.codegen.CodeLanguage
import androidx.room.compiler.codegen.VisibilityModifier
import androidx.room.compiler.codegen.XFunSpec
import androidx.room.compiler.codegen.XPropertySpec
import androidx.room.compiler.codegen.XTypeName
import androidx.room.compiler.codegen.XTypeSpec
import androidx.room.compiler.codegen.XTypeSpec.Builder.Companion.apply
import androidx.room.compiler.processing.XProcessingEnv
import androidx.room.compiler.processing.writeTo
import androidx.room.ext.S
import androidx.room.solver.CodeGenScope
import com.squareup.kotlinpoet.javapoet.JAnnotationSpec
import com.squareup.kotlinpoet.javapoet.JClassName
import com.squareup.kotlinpoet.javapoet.KAnnotationSpec
import com.squareup.kotlinpoet.javapoet.KClassName
import kotlin.reflect.KClass
/**
* Base class for all writers that can produce a class.
*/
abstract class TypeWriter(val codeLanguage: CodeLanguage) {
private val sharedFieldSpecs = mutableMapOf<String, XPropertySpec>()
private val sharedMethodSpecs = mutableMapOf<String, XFunSpec>()
private val sharedFieldNames = mutableSetOf<String>()
private val sharedMethodNames = mutableSetOf<String>()
private val metadata = mutableMapOf<KClass<*>, Any>()
abstract fun createTypeSpecBuilder(): XTypeSpec.Builder
/**
* Read additional metadata that can be put by sub code generators.
*
* @see set for more details.
*/
operator fun <T> get(key: KClass<*>): T? {
@Suppress("UNCHECKED_CAST")
return metadata[key] as? T
}
/**
* Add additional metadata to the TypeWriter that can be read back later.
* This is useful for additional functionality where a sub code generator needs to bubble up
* information to the main TypeWriter without copying it in every intermediate step.
*
* @see get
*/
operator fun set(key: KClass<*>, value: Any) {
metadata[key] = value
}
fun write(processingEnv: XProcessingEnv) {
val builder = createTypeSpecBuilder()
sharedFieldSpecs.values.forEach { builder.addProperty(it) }
sharedMethodSpecs.values.forEach { builder.addFunction(it) }
addGeneratedAnnotationIfAvailable(builder, processingEnv)
addSuppressWarnings(builder)
builder.build().writeTo(processingEnv.filer)
}
private fun addSuppressWarnings(builder: XTypeSpec.Builder) {
builder.apply(
javaTypeBuilder = {
addAnnotation(
com.squareup.javapoet.AnnotationSpec.builder(SuppressWarnings::class.java)
.addMember("value", "{$S, $S}", "unchecked", "deprecation")
.build()
)
},
kotlinTypeBuilder = {
addAnnotation(
com.squareup.kotlinpoet.AnnotationSpec.builder(Suppress::class)
.addMember("names = [%S, %S]", "UNCHECKED_CAST", "DEPRECATION")
.build()
)
}
)
}
private fun addGeneratedAnnotationIfAvailable(
adapterTypeSpecBuilder: XTypeSpec.Builder,
processingEnv: XProcessingEnv
) {
processingEnv.findGeneratedAnnotation()?.let {
val annotationName = it.asClassName().canonicalName
val memberValue = RoomProcessor::class.java.canonicalName
adapterTypeSpecBuilder.apply(
javaTypeBuilder = {
addAnnotation(
JAnnotationSpec.builder(JClassName.bestGuess(annotationName))
.addMember("value", "$S", memberValue)
.build()
)
},
kotlinTypeBuilder = {
addAnnotation(
KAnnotationSpec.builder(KClassName.bestGuess(annotationName))
.addMember("value = [%S]", memberValue)
.build()
)
}
)
}
}
private fun makeUnique(set: MutableSet<String>, value: String): String {
if (!value.startsWith(CodeGenScope.CLASS_PROPERTY_PREFIX)) {
return makeUnique(set, "${CodeGenScope.CLASS_PROPERTY_PREFIX}$value")
}
if (set.add(value)) {
return value
}
var index = 1
while (true) {
if (set.add("${value}_$index")) {
return "${value}_$index"
}
index++
}
}
fun getOrCreateProperty(sharedProperty: SharedPropertySpec): XPropertySpec {
return sharedFieldSpecs.getOrPut(sharedProperty.getUniqueKey()) {
sharedProperty.build(this, makeUnique(sharedFieldNames, sharedProperty.baseName))
}
}
fun getOrCreateFunction(sharedFunction: SharedFunctionSpec): XFunSpec {
return sharedMethodSpecs.getOrPut(sharedFunction.getUniqueKey()) {
sharedFunction.build(this, makeUnique(sharedMethodNames, sharedFunction.baseName))
}
}
abstract class SharedPropertySpec(val baseName: String, val type: XTypeName) {
open val isMutable = false
abstract fun getUniqueKey(): String
abstract fun prepare(writer: TypeWriter, builder: XPropertySpec.Builder)
fun build(classWriter: TypeWriter, name: String): XPropertySpec {
val builder = XPropertySpec.builder(
language = classWriter.codeLanguage,
name = name,
typeName = type,
visibility = VisibilityModifier.PRIVATE,
isMutable = isMutable
)
prepare(classWriter, builder)
return builder.build()
}
}
abstract class SharedFunctionSpec(val baseName: String) {
abstract fun getUniqueKey(): String
abstract fun prepare(
methodName: String,
writer: TypeWriter,
builder: XFunSpec.Builder
)
fun build(writer: TypeWriter, name: String): XFunSpec {
val builder = XFunSpec.builder(writer.codeLanguage, name, VisibilityModifier.PRIVATE)
prepare(name, writer, builder)
return builder.build()
}
}
}
| apache-2.0 | b94e1956687ed813c62b5de9716d480e | 35.631579 | 97 | 0.634914 | 5.121413 | false | false | false | false |
GunoH/intellij-community | platform/lang-impl/src/com/intellij/codeInsight/hints/presentation/ScaleAwarePresentationFactory.kt | 3 | 7386 | // 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.codeInsight.hints.presentation
import com.intellij.codeInsight.hints.InlayPresentationFactory
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.editor.markup.TextAttributes
import com.intellij.ui.scale.JBUIScale
import com.intellij.ui.scale.ScaleContext
import com.intellij.ui.scale.ScaleContextAware
import com.intellij.util.IconUtil
import org.jetbrains.annotations.ApiStatus
import java.awt.AlphaComposite
import java.awt.Color
import java.awt.Graphics2D
import java.awt.Point
import java.awt.event.MouseEvent
import javax.swing.Icon
import kotlin.math.roundToInt
import kotlin.reflect.KProperty
/**
* Presentation factory, which handles presentation mode and scales Icons and Insets
*/
@ApiStatus.Experimental
class ScaleAwarePresentationFactory(
val editor: Editor,
private val delegate: PresentationFactory
) : InlayPresentationFactory by delegate {
fun lineCentered(presentation: InlayPresentation): InlayPresentation {
return LineCenteredInset(presentation, editor)
}
override fun container(presentation: InlayPresentation,
padding: InlayPresentationFactory.Padding?,
roundedCorners: InlayPresentationFactory.RoundedCorners?,
background: Color?,
backgroundAlpha: Float): InlayPresentation {
return ScaledContainerPresentation(presentation, editor, padding, roundedCorners, background, backgroundAlpha)
}
override fun icon(icon: Icon): InlayPresentation {
return ScaleAwareIconPresentation(icon, editor, fontShift = 0)
}
fun icon(icon: Icon, debugName: String, fontShift: Int): InlayPresentation {
return ScaleAwareIconPresentation(icon, editor, debugName, fontShift)
}
fun inset(base: InlayPresentation, left: Int = 0, right: Int = 0, top: Int = 0, down: Int = 0): InlayPresentation {
return ScaledInsetPresentation(
base,
left = left,
right = right,
top = top,
down = down,
editor = editor
)
}
fun seq(vararg presentations: InlayPresentation): InlayPresentation {
return delegate.seq(*presentations)
}
}
@ApiStatus.Internal
class ScaledInsetPresentation(
val presentation: InlayPresentation,
val left: Int,
val right: Int,
val top: Int,
val down: Int,
val editor: Editor
) : ScaledDelegatedPresentation() {
override val delegate: InsetPresentation by valueOf<InsetPresentation, Float> { fontSize ->
InsetPresentation(
presentation,
scaleByFont(left, fontSize),
scaleByFont(right, fontSize),
scaleByFont(top, fontSize),
scaleByFont(down, fontSize)
)
}.withState {
editor.colorsScheme.editorFontSize2D
}
}
@ApiStatus.Internal
class ScaledContainerPresentation(
val presentation: InlayPresentation,
val editor: Editor,
val padding: InlayPresentationFactory.Padding? = null,
val roundedCorners: InlayPresentationFactory.RoundedCorners? = null,
val background: Color? = null,
val backgroundAlpha: Float = 0.55f
) : ScaledDelegatedPresentation() {
override val delegate: ContainerInlayPresentation by valueOf<ContainerInlayPresentation, Float> { fontSize ->
ContainerInlayPresentation(
presentation,
scaleByFont(padding, fontSize),
scaleByFont(roundedCorners, fontSize),
background,
backgroundAlpha
)
}.withState {
editor.colorsScheme.editorFontSize2D
}
}
@ApiStatus.Internal
abstract class ScaledDelegatedPresentation : BasePresentation() {
protected abstract val delegate: InlayPresentation
override val width: Int
get() = delegate.width
override val height: Int
get() = delegate.height
override fun paint(g: Graphics2D, attributes: TextAttributes) {
delegate.paint(g, attributes)
}
override fun toString(): String {
return delegate.toString()
}
override fun mouseClicked(event: MouseEvent, translated: Point) {
delegate.mouseExited()
}
override fun mouseMoved(event: MouseEvent, translated: Point) {
delegate.mouseMoved(event, translated)
}
override fun mouseExited() {
delegate.mouseExited()
}
}
@ApiStatus.Internal
class LineCenteredInset(
val presentation: InlayPresentation,
val editor: Editor
) : ScaledDelegatedPresentation() {
override val delegate: InlayPresentation by valueOf<InlayPresentation, Int> { lineHeight ->
val innerHeight = presentation.height
InsetPresentation(presentation, top = (lineHeight - innerHeight) / 2)
}.withState {
editor.lineHeight
}
}
@ApiStatus.Internal
class ScaleAwareIconPresentation(val icon: Icon,
private val editor: Editor,
private val debugName: String = "image",
val fontShift: Int) : BasePresentation() {
override val width: Int
get() = scaledIcon.iconWidth
override val height: Int
get() = scaledIcon.iconHeight
override fun paint(g: Graphics2D, attributes: TextAttributes) {
val graphics = g.create() as Graphics2D
graphics.composite = AlphaComposite.SrcAtop.derive(1.0f)
scaledIcon.paintIcon(editor.component, graphics, 0, 0)
graphics.dispose()
}
override fun toString(): String = "<$debugName>"
private val scaledIcon by valueOf<Icon, Float> { fontSize ->
(icon as? ScaleContextAware)?.updateScaleContext(ScaleContext.create(editor.component))
IconUtil.scaleByFont(icon, editor.component, fontSize)
}.withState {
editor.colorsScheme.editorFontSize2D - fontShift
}
}
private class StateDependantValue<TData : Any, TState : Any>(
private val valueProvider: (TState) -> TData,
private val stateProvider: () -> TState
) {
private var currentState: TState? = null
private lateinit var cachedValue: TData
operator fun getValue(thisRef: Any?, property: KProperty<*>): TData {
val state = stateProvider()
if (state != currentState) {
currentState = state
cachedValue = valueProvider(state)
}
return cachedValue
}
}
private fun <TData : Any, TState : Any> valueOf(dataProvider: (TState) -> TData): StateDependantValueBuilder<TData, TState> {
return StateDependantValueBuilder(dataProvider)
}
private class StateDependantValueBuilder<TData : Any, TState : Any>(private val dataProvider: (TState) -> TData) {
fun withState(stateProvider: () -> TState): StateDependantValue<TData, TState> {
return StateDependantValue(dataProvider, stateProvider)
}
}
fun scaleByFont(sizeFor12: Int, fontSize: Float) = (JBUIScale.getFontScale(fontSize) * sizeFor12).roundToInt()
private fun scaleByFont(paddingFor12: InlayPresentationFactory.Padding?, fontSize: Float) =
paddingFor12?.let { (left, right, top, bottom) ->
InlayPresentationFactory.Padding(
left = scaleByFont(left, fontSize),
right = scaleByFont(right, fontSize),
top = scaleByFont(top, fontSize),
bottom = scaleByFont(bottom, fontSize)
)
}
private fun scaleByFont(roundedCornersFor12: InlayPresentationFactory.RoundedCorners?, fontSize: Float) =
roundedCornersFor12?.let { (arcWidth, arcHeight) ->
InlayPresentationFactory.RoundedCorners(
arcWidth = scaleByFont(arcWidth, fontSize),
arcHeight = scaleByFont(arcHeight, fontSize)
)
} | apache-2.0 | d1bfa5c1ea6ef8f6b4372ebeec0de015 | 31.831111 | 140 | 0.727187 | 4.713465 | false | false | false | false |
GunoH/intellij-community | platform/projectModel-impl/src/com/intellij/configurationStore/JbXmlOutputter.kt | 7 | 19620 | // 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.configurationStore
import com.intellij.application.options.ReplacePathToMacroMap
import com.intellij.openapi.application.PathMacroFilter
import com.intellij.openapi.components.ComponentManager
import com.intellij.openapi.components.PathMacroManager
import com.intellij.openapi.components.impl.stores.FileStorageCoreUtil
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.util.JDOMUtil
import com.intellij.openapi.util.SystemInfoRt
import com.intellij.openapi.util.io.FileUtilRt
import com.intellij.util.SystemProperties
import com.intellij.util.xmlb.Constants
import org.jdom.*
import org.jdom.output.Format
import java.io.IOException
import java.io.StringWriter
import java.io.Writer
import java.util.*
import javax.xml.transform.Result
private val DEFAULT_FORMAT = JDOMUtil.createFormat("\n")
// expandEmptyElements is ignored
open class JbXmlOutputter @JvmOverloads constructor(lineSeparator: String = "\n",
private val elementFilter: JDOMUtil.ElementOutputFilter? = null,
private val macroMap: ReplacePathToMacroMap? = null,
private val macroFilter: PathMacroFilter? = null,
private val isForbidSensitiveData: Boolean = true,
private val storageFilePathForDebugPurposes: String? = null) : BaseXmlOutputter(lineSeparator) {
companion object {
@JvmStatic
@Throws(IOException::class)
fun collapseMacrosAndWrite(element: Element, project: ComponentManager, writer: Writer) {
createOutputter(project).output(element, writer)
}
@JvmStatic
fun createOutputter(project: ComponentManager): JbXmlOutputter {
val macroManager = PathMacroManager.getInstance(project)
return JbXmlOutputter(macroMap = macroManager.replacePathMap, macroFilter = macroManager.macroFilter)
}
@JvmStatic
@Throws(IOException::class)
fun collapseMacrosAndWrite(element: Element, project: ComponentManager): String {
val writer = StringWriter()
collapseMacrosAndWrite(element, project, writer)
return writer.toString()
}
fun escapeElementEntities(str: String?): String {
return JDOMUtil.escapeText(str!!, false, false)
}
private val reportedSensitiveProblems = Collections.synchronizedSet(HashSet<String>())
}
// For normal output
private val format = if (DEFAULT_FORMAT.lineSeparator == lineSeparator) DEFAULT_FORMAT else JDOMUtil.createFormat(lineSeparator)
@Throws(IOException::class)
fun output(doc: Document, out: Writer) {
printDeclaration(out, format.encoding)
// Print out root element, as well as any root level comments and processing instructions, starting with no indentation
val content = doc.content
for (obj in content) {
when (obj) {
is Element -> printElement(out, doc.rootElement, 0)
is Comment -> printComment(out, obj)
is ProcessingInstruction -> printProcessingInstruction(out, obj)
is DocType -> {
printDocType(out, doc.docType)
// Always print line separator after declaration, helps the
// output look better and is semantically inconsequential
writeLineSeparator(out)
}
}
newline(out)
indent(out, 0)
}
writeLineSeparator(out)
out.flush()
}
@Throws(IOException::class)
private fun writeLineSeparator(out: Writer) {
if (format.lineSeparator != null) {
out.write(format.lineSeparator)
}
}
/**
* Print out the `[DocType]`.
*
* @param doctype `DocType` to output.
* @param out `Writer` to use.
*/
@Throws(IOException::class)
fun output(doctype: DocType, out: Writer) {
printDocType(out, doctype)
out.flush()
}
@Throws(IOException::class)
fun output(element: Element, out: Writer) {
printElement(out, element, 0)
}
/**
* This will handle printing of the declaration.
* Assumes XML version 1.0 since we don't directly know.
*
* @param out `Writer` to use.
* @param encoding The encoding to add to the declaration
*/
@Throws(IOException::class)
private fun printDeclaration(out: Writer, encoding: String) {
// Only print the declaration if it's not being omitted
if (!format.omitDeclaration) {
// Assume 1.0 version
out.write("<?xml version=\"1.0\"")
if (!format.omitEncoding) {
out.write(" encoding=\"$encoding\"")
}
out.write("?>")
// Print new line after decl always, even if no other new lines
// Helps the output look better and is semantically
// inconsequential
writeLineSeparator(out)
}
}
/**
* This will handle printing of processing instructions.
*
* @param pi `ProcessingInstruction` to write.
* @param out `Writer` to use.
*/
@Throws(IOException::class)
private fun printProcessingInstruction(out: Writer, pi: ProcessingInstruction) {
val target = pi.target
var piProcessed = false
if (!format.ignoreTrAXEscapingPIs) {
if (target == Result.PI_DISABLE_OUTPUT_ESCAPING) {
piProcessed = true
}
else if (target == Result.PI_ENABLE_OUTPUT_ESCAPING) {
piProcessed = true
}
}
if (!piProcessed) {
writeProcessingInstruction(out, pi, target)
}
}
/**
* This will handle printing of `[CDATA]` text.
*
* @param cdata `CDATA` to output.
* @param out `Writer` to use.
*/
@Throws(IOException::class)
private fun printCDATA(out: Writer, cdata: CDATA) {
var str: String
if (format.textMode == Format.TextMode.NORMALIZE) {
str = cdata.textNormalize
}
else {
str = cdata.text
if (format.textMode == Format.TextMode.TRIM) {
str = str.trim()
}
}
out.write("<![CDATA[")
out.write(str)
out.write("]]>")
}
/**
* This will handle printing a string. Escapes the element entities,
* trims interior whitespace, etc. if necessary.
*/
@Throws(IOException::class)
private fun printString(out: Writer, str: String) {
var normalizedString = str
if (format.textMode == Format.TextMode.NORMALIZE) {
normalizedString = Text.normalizeString(normalizedString)
}
else if (format.textMode == Format.TextMode.TRIM) {
normalizedString = normalizedString.trim()
}
if (macroMap != null) {
normalizedString = macroMap.substitute(normalizedString, SystemInfoRt.isFileSystemCaseSensitive)
}
out.write(escapeElementEntities(normalizedString))
}
/**
* This will handle printing of a `[Element]`,
* its `[Attribute]`s, and all contained (child)
* elements, etc.
*
* @param element `Element` to output.
* @param out `Writer` to use.
* @param level `int` level of indention.
*/
@Throws(IOException::class)
fun printElement(out: Writer, element: Element, level: Int) {
if (elementFilter != null && !elementFilter.accept(element, level)) {
return
}
// Print the beginning of the tag plus attributes and any
// necessary namespace declarations
out.write('<'.code)
printQualifiedName(out, element)
if (element.hasAttributes()) {
printAttributes(out, element.attributes)
}
// depending on the settings (newlines, textNormalize, etc.), we may or may not want to print all the content,
// so determine the index of the start of the content we're interested in based on the current settings.
if (!writeContent(out, element, level)) {
return
}
out.write("</")
printQualifiedName(out, element)
out.write('>'.code)
}
@Throws(IOException::class)
protected open fun writeContent(out: Writer, element: Element, level: Int): Boolean {
if (isForbidSensitiveData) {
checkIsElementContainsSensitiveInformation(element)
}
val content = element.content
val start = skipLeadingWhite(content, 0)
val size = content.size
if (start >= size) {
// content is empty or all insignificant whitespace
out.write(" />")
return false
}
out.write('>'.code)
// for a special case where the content is only CDATA or Text we don't want to indent after the start or before the end tag
if (nextNonText(content, start) < size) {
// case Mixed Content - normal indentation
newline(out)
printContentRange(out, content, start, size, level + 1)
newline(out)
indent(out, level)
}
else {
// case all CDATA or Text - no indentation
printTextRange(out, content, start, size)
}
return true
}
/**
* This will handle printing of content within a given range.
* The range to print is specified in typical Java fashion; the
* starting index is inclusive, while the ending index is
* exclusive.
*
* @param content `List` of content to output
* @param start index of first content node (inclusive.
* @param end index of last content node (exclusive).
* @param out `Writer` to use.
* @param level `int` level of indentation.
*/
@Throws(IOException::class)
private fun printContentRange(out: Writer, content: List<Content>, start: Int, end: Int, level: Int) {
var firstNode: Boolean // Flag for 1st node in content
var next: Content // Node we're about to print
var first: Int
var index: Int // Indexes into the list of content
index = start
while (index < end) {
firstNode = index == start
next = content[index]
// Handle consecutive CDATA, Text, and EntityRef nodes all at once
if (next is Text || next is EntityRef) {
first = skipLeadingWhite(content, index)
// Set index to next node for loop
index = nextNonText(content, first)
// If it's not all whitespace - print it!
if (first < index) {
if (!firstNode) {
newline(out)
}
indent(out, level)
printTextRange(out, content, first, index)
}
continue
}
// Handle other nodes
if (!firstNode) {
newline(out)
}
indent(out, level)
when (next) {
is Comment -> printComment(out, next)
is Element -> printElement(out, next, level)
is ProcessingInstruction -> printProcessingInstruction(out, next)
else -> {
// XXX if we get here then we have an illegal content, for now we'll just ignore it (probably should throw an exception)
}
}
index++
}
}
/**
* This will handle printing of a sequence of `[CDATA]`
* or `[Text]` nodes. It is an error to have any other
* pass this method any other type of node.
*
* @param content `List` of content to output
* @param start index of first content node (inclusive).
* @param end index of last content node (exclusive).
* @param out `Writer` to use.
*/
@Throws(IOException::class)
private fun printTextRange(out: Writer, content: List<Content>, start: Int, end: Int) {
@Suppress("NAME_SHADOWING")
val start = skipLeadingWhite(content, start)
if (start >= content.size) {
return
}
// and remove trialing whitespace-only nodes
@Suppress("NAME_SHADOWING")
val end = skipTrailingWhite(content, end)
var previous: String? = null
for (i in start until end) {
val node = content[i]
// get the unmangled version of the text we are about to print
val next: String?
when (node) {
is Text -> next = node.text
is EntityRef -> next = "&" + node.getValue() + ";"
else -> throw IllegalStateException("Should see only CDATA, Text, or EntityRef")
}
if (next.isNullOrEmpty()) {
continue
}
// determine if we need to pad the output (padding is only need in trim or normalizing mode)
if (previous != null && (format.textMode == Format.TextMode.NORMALIZE || format.textMode == Format.TextMode.TRIM)) {
if (endsWithWhite(previous) || startsWithWhite(next)) {
out.write(' '.code)
}
}
// print the node
when (node) {
is CDATA -> printCDATA(out, node)
is EntityRef -> printEntityRef(out, node)
else -> printString(out, next)
}
previous = next
}
}
/**
* This will handle printing of a `[Attribute]` list.
*
* @param attributes `List` of Attribute objects
* @param out `Writer` to use
*/
@Throws(IOException::class)
private fun printAttributes(out: Writer, attributes: List<Attribute>) {
for (attribute in attributes) {
out.write(' '.code)
printQualifiedName(out, attribute)
out.write('='.code)
out.write('"'.code)
val value = if (macroMap != null && (macroFilter == null || !macroFilter.skipPathMacros(attribute))) {
macroMap.getAttributeValue(attribute, macroFilter, SystemInfoRt.isFileSystemCaseSensitive, false)
}
else {
attribute.value
}
if (isForbidSensitiveData && doesNameSuggestSensitiveInformation(attribute.name)) {
logSensitiveInformationError("@${attribute.name}", "Attribute", attribute.parent)
}
out.write(escapeAttributeEntities(value))
out.write('"'.code)
}
}
/**
* This will print a newline only if indent is not null.
*
* @param out `Writer` to use
*/
@Throws(IOException::class)
private fun newline(out: Writer) {
if (format.indent != null) {
writeLineSeparator(out)
}
}
/**
* This will print indents only if indent is not null or the empty string.
*
* @param out `Writer` to use
* @param level current indent level
*/
@Throws(IOException::class)
private fun indent(out: Writer, level: Int) {
if (format.indent.isNullOrEmpty()) {
return
}
for (i in 0 until level) {
out.write(format.indent)
}
}
// Returns the index of the first non-all-whitespace CDATA or Text,
// index = content.size() is returned if content contains
// all whitespace.
// @param start index to begin search (inclusive)
private fun skipLeadingWhite(content: List<Content>, start: Int): Int {
var index = start
if (index < 0) {
index = 0
}
val size = content.size
val textMode = format.textMode
if (textMode == Format.TextMode.TRIM_FULL_WHITE || textMode == Format.TextMode.NORMALIZE || textMode == Format.TextMode.TRIM) {
while (index < size) {
if (!isAllWhitespace(content[index])) {
return index
}
index++
}
}
return index
}
// Return the index + 1 of the last non-all-whitespace CDATA or
// Text node, index < 0 is returned
// if content contains all whitespace.
// @param start index to begin search (exclusive)
private fun skipTrailingWhite(content: List<Content>, start: Int): Int {
var index = start
val size = content.size
if (index > size) {
index = size
}
val textMode = format.textMode
if (textMode == Format.TextMode.TRIM_FULL_WHITE || textMode == Format.TextMode.NORMALIZE || textMode == Format.TextMode.TRIM) {
while (index >= 0) {
if (!isAllWhitespace(content[index - 1])) {
break
}
--index
}
}
return index
}
private fun checkIsElementContainsSensitiveInformation(element: Element) {
var name: String? = element.name
if (!shouldCheckElement(element)) return
if (doesNameSuggestSensitiveInformation(name!!)) {
logSensitiveInformationError(name, "Element", element.parentElement)
}
// checks only option tag
name = element.getAttributeValue(Constants.NAME)
if (name != null && doesNameSuggestSensitiveInformation(name) && element.getAttribute("value") != null) {
logSensitiveInformationError("@name=$name", "Element", element /* here not parentElement because it is attributed */)
}
}
private fun shouldCheckElement(element: Element): Boolean {
//any user-provided name-value
if ("property" == element.name && element.parentElement?.name.let { it == "driver-properties" || it == "driver"}) {
return false
}
return true
}
private fun logSensitiveInformationError(name: String, elementKind: String, parentElement: Element?) {
val parentPath: String?
if (parentElement == null) {
parentPath = null
}
else {
val ids = ArrayList<String>()
var parent = parentElement
while (parent != null) {
var parentId = parent.name
if (parentId == FileStorageCoreUtil.COMPONENT) {
val componentName = parent.getAttributeValue(FileStorageCoreUtil.NAME)
if (componentName != null) {
parentId += "@$componentName"
}
}
ids.add(parentId)
parent = parent.parentElement
}
if (ids.isEmpty()) {
parentPath = null
}
else {
ids.reverse()
parentPath = ids.joinToString(".")
}
}
var message = "$elementKind ${if (parentPath == null) "" else "$parentPath."}$name probably contains sensitive information"
if (storageFilePathForDebugPurposes != null) {
message += " (file: ${storageFilePathForDebugPurposes.replace(FileUtilRt.toSystemIndependentName(SystemProperties.getUserHome()), "~")})"
}
if (reportedSensitiveProblems.add(message)) {
Logger.getInstance(JbXmlOutputter::class.java).error(message)
}
}
}
// Return the next non-CDATA, non-Text, or non-EntityRef node,
// index = content.size() is returned if there is no more non-CDATA,
// non-Text, or non-EntryRef nodes
// @param start index to begin search (inclusive)
private fun nextNonText(content: List<Content>, start: Int): Int {
var index = start
if (index < 0) {
index = 0
}
val size = content.size
while (index < size) {
val node = content[index]
if (!(node is Text || node is EntityRef)) {
return index
}
index++
}
return size
}
private fun printEntityRef(out: Writer, entity: EntityRef) {
out.write("&")
out.write(entity.name)
out.write(";")
}
private fun printComment(out: Writer, comment: Comment) {
out.write("<!--")
out.write(comment.text)
out.write("-->")
}
private fun isAllWhitespace(obj: Content): Boolean {
val str = (obj as? Text ?: return false).text
for (element in str) {
if (!Verifier.isXMLWhitespace(element)) {
return false
}
}
return true
}
private fun startsWithWhite(str: String): Boolean {
return !str.isEmpty() && Verifier.isXMLWhitespace(str[0])
}
// Determine if a string ends with an XML whitespace.
private fun endsWithWhite(str: String): Boolean {
return !str.isEmpty() && Verifier.isXMLWhitespace(str[str.length - 1])
}
private fun escapeAttributeEntities(str: String): String {
return JDOMUtil.escapeText(str, false, true)
}
private fun printQualifiedName(out: Writer, e: Element) {
if (!e.namespace.prefix.isEmpty()) {
out.write(e.namespace.prefix)
out.write(':'.code)
}
out.write(e.name)
}
// Support method to print a name without using att.getQualifiedName()
// and thus avoiding a StringBuffer creation and memory churn
private fun printQualifiedName(out: Writer, a: Attribute) {
val prefix = a.namespace.prefix
if (!prefix.isNullOrEmpty()) {
out.write(prefix)
out.write(':'.code)
}
out.write(a.name)
} | apache-2.0 | 803d88b39f7e6fa72052ec3684285722 | 29.99684 | 148 | 0.645973 | 4.272648 | false | false | false | false |
GunoH/intellij-community | plugins/grazie/src/main/kotlin/com/intellij/grazie/ide/fus/GrazieFUSCounter.kt | 5 | 3816 | // Copyright 2000-2022 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.grazie.ide.fus
import ai.grazie.nlp.langs.Language
import ai.grazie.nlp.langs.LanguageISO
import com.intellij.grazie.text.Rule
import com.intellij.grazie.text.TextProblem
import com.intellij.internal.statistic.collectors.fus.PluginInfoValidationRule
import com.intellij.internal.statistic.eventLog.EventLogGroup
import com.intellij.internal.statistic.eventLog.events.EventFields
import com.intellij.internal.statistic.service.fus.collectors.CounterUsagesCollector
import com.intellij.internal.statistic.utils.getPluginInfo
import com.intellij.openapi.project.Project
internal object GrazieFUSCounter : CounterUsagesCollector() {
override fun getGroup(): EventLogGroup = GROUP
private val GROUP = EventLogGroup("grazie.count", 6)
private val actionsInfo = listOf("accept.suggestion",
"add.exception",
"rule.settings:canceled",
"rule.settings:unmodified",
"rule.settings:changes:languages,domains,rules",
"rule.settings:changes:languages,rules",
"rule.settings:changes:languages,domains",
"rule.settings:changes:domains,rules",
"rule.settings:changes:languages",
"rule.settings:changes:rules",
"rule.settings:changes:domains",
"rule.settings:changes:unclassified")
private val RULE_FIELD = EventFields.StringValidatedByCustomRule("id", PluginInfoValidationRule::class.java)
private val FIXES_FIELD = EventFields.Int("fixes")
private val ACTION_INFO_FIELD = EventFields.String("info", actionsInfo)
private val languageSuggestedEvent = GROUP.registerEvent("language.suggested",
EventFields.Enum("language", LanguageISO::class.java),
EventFields.Enabled)
private val typoFoundEvent = GROUP.registerEvent("typo.found",
RULE_FIELD,
FIXES_FIELD,
EventFields.PluginInfo)
private val quickFixInvokedEvent = GROUP.registerEvent("quick.fix.invoked",
RULE_FIELD,
ACTION_INFO_FIELD,
EventFields.PluginInfo)
fun languagesSuggested(languages: Collection<Language>, isEnabled: Boolean) {
for (language in languages) {
languageSuggestedEvent.log(language.iso, isEnabled)
}
}
fun typoFound(problem: TextProblem) = typoFoundEvent.log(problem.text.containingFile.project,
problem.rule.globalId,
problem.suggestions.size,
getPluginInfo(problem.rule.javaClass))
fun quickFixInvoked(rule: Rule, project: Project, actionInfo: String) = quickFixInvokedEvent.log(project,
rule.globalId,
actionInfo,
getPluginInfo(rule.javaClass))
} | apache-2.0 | b22161cc8a90953581b2b8a9c772d1f3 | 58.640625 | 140 | 0.531447 | 6.174757 | false | false | false | false |
ThePreviousOne/Untitled | app/src/main/java/eu/kanade/tachiyomi/data/source/online/english/dynasty/DynastyDoujins.kt | 1 | 2121 | /*
* This file is part of TachiyomiEX.
*
* TachiyomiEX 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.
*
* TachiyomiEX 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 TachiyomiEX. If not, see <http://www.gnu.org/licenses/>.
*/
package eu.kanade.tachiyomi.data.source.online.english.dynasty
import android.content.Context
import eu.kanade.tachiyomi.data.database.models.Manga
import eu.kanade.tachiyomi.data.source.Sources
import eu.kanade.tachiyomi.data.source.model.MangasPage
import eu.kanade.tachiyomi.util.asJsoup
import okhttp3.CacheControl
import okhttp3.Headers
import okhttp3.Request
import okhttp3.Response
import org.jsoup.nodes.Document
import java.util.concurrent.TimeUnit
class DynastyDoujins(override val source: Sources) : DynastyScans() {
override fun popularMangaInitialUrl() = "$baseUrl/doujins?view=cover"
override fun popularMangaParse(response: Response, page: MangasPage) {
val document = response.asJsoup()
for (element in document.select(popularMangaSelector())) {
Manga.create(id).apply {
popularMangaFromElement(element, this)
page.mangas.add(this)
}
}
}
override fun searchMangaInitialUrl(query: String, filters: List<Filter>) =
"$baseUrl/search?q=$query&classes[]=Doujin&sort="
override fun mangaDetailsParse(document: Document, manga: Manga) {
super.mangaDetailsParse(document, manga)
parseThumbnail(manga)
manga.author = ".."
manga.status = Manga.UNKNOWN
parseGenres(document, manga)
}
override fun chapterListSelector() = "div.span9 > dl.chapter-list > dd"
}
| gpl-3.0 | 7cc26971d28210795a99dd10cce2da15 | 35.568966 | 78 | 0.722301 | 4.302231 | false | false | false | false |
jwren/intellij-community | plugins/github/src/org/jetbrains/plugins/github/api/GithubApiRequestExecutorManager.kt | 1 | 2353 | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.plugins.github.api
import com.intellij.openapi.components.service
import com.intellij.openapi.project.Project
import com.intellij.util.concurrency.annotations.RequiresEdt
import org.jetbrains.plugins.github.authentication.GithubAuthenticationManager
import org.jetbrains.plugins.github.authentication.accounts.GHAccountManager
import org.jetbrains.plugins.github.authentication.accounts.GithubAccount
import org.jetbrains.plugins.github.exceptions.GithubMissingTokenException
import java.awt.Component
/**
* Allows to acquire API executor without exposing the auth token to external code
*/
class GithubApiRequestExecutorManager {
private val executors = mutableMapOf<GithubAccount, GithubApiRequestExecutor.WithTokenAuth>()
companion object {
@JvmStatic
fun getInstance(): GithubApiRequestExecutorManager = service()
}
internal fun tokenChanged(account: GithubAccount) {
val token = service<GHAccountManager>().findCredentials(account)
if (token == null) executors.remove(account)
else executors[account]?.token = token
}
@RequiresEdt
fun getExecutor(account: GithubAccount, project: Project): GithubApiRequestExecutor? {
return getOrTryToCreateExecutor(account) { GithubAuthenticationManager.getInstance().requestNewToken(account, project) }
}
@RequiresEdt
fun getExecutor(account: GithubAccount, parentComponent: Component): GithubApiRequestExecutor? {
return getOrTryToCreateExecutor(account) { GithubAuthenticationManager.getInstance().requestNewToken(account, null, parentComponent) }
}
@RequiresEdt
@Throws(GithubMissingTokenException::class)
fun getExecutor(account: GithubAccount): GithubApiRequestExecutor {
return getOrTryToCreateExecutor(account) { throw GithubMissingTokenException(account) }!!
}
private fun getOrTryToCreateExecutor(account: GithubAccount,
missingTokenHandler: () -> String?): GithubApiRequestExecutor? {
return executors.getOrPut(account) {
(GithubAuthenticationManager.getInstance().getTokenForAccount(account) ?: missingTokenHandler())
?.let(GithubApiRequestExecutor.Factory.getInstance()::create) ?: return null
}
}
} | apache-2.0 | 8cd942d35642c1c6cd1e3465092ee52a | 42.592593 | 140 | 0.784955 | 5.311512 | false | false | false | false |
GunoH/intellij-community | plugins/junit/src/com/intellij/execution/junit2/properties/JUnitPropertiesModel.kt | 5 | 2527 | // 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.junit2.properties
import com.intellij.codeInsight.JavaLibraryModificationTracker
import com.intellij.openapi.module.ModuleUtilCore
import com.intellij.psi.JavaPsiFacade
import com.intellij.psi.PsiAnchor
import com.intellij.psi.PsiExpression
import com.intellij.psi.PsiFile
import com.intellij.psi.impl.PsiExpressionEvaluator
import com.intellij.psi.search.GlobalSearchScope.moduleRuntimeScope
import com.intellij.psi.search.ProjectScope.getLibrariesScope
import com.intellij.psi.util.CachedValueProvider
import com.intellij.psi.util.CachedValueProvider.Result
import com.intellij.psi.util.CachedValuesManager
internal const val JUNIT_PLATFORM_PROPERTIES_CONFIG: String = "junit-platform.properties"
internal const val JUNIT_CONSTANTS_CLASS: String = "org.junit.jupiter.engine.Constants"
internal const val JUNIT_PROPERTY_NAME_SUFFIX: String = "_PROPERTY_NAME"
internal const val JUNIT_DEFAULT_PARALLEL_EXECUTION_MODE_FIELD: String = "DEFAULT_PARALLEL_EXECUTION_MODE"
internal data class JUnitPlatformProperty(
val key: String,
val declaration: PsiAnchor
)
internal fun getJUnitPlatformProperties(file: PsiFile): Map<String, JUnitPlatformProperty> {
return CachedValuesManager.getManager(file.project).getCachedValue(file, CachedValueProvider {
val module = ModuleUtilCore.findModuleForFile(file)
val javaPsi = JavaPsiFacade.getInstance(file.project)
val constantsClass = module?.let { javaPsi.findClass(JUNIT_CONSTANTS_CLASS, moduleRuntimeScope(it, false)) }
?: javaPsi.findClass(JUNIT_CONSTANTS_CLASS, getLibrariesScope(file.project))
val psiEvaluator = PsiExpressionEvaluator()
val properties = (constantsClass?.fields ?: emptyArray())
.filter { it.name.endsWith(JUNIT_PROPERTY_NAME_SUFFIX) || it.name == JUNIT_DEFAULT_PARALLEL_EXECUTION_MODE_FIELD }
.mapNotNull { field ->
computePropertyName(psiEvaluator, field.initializer)
?.let { key -> JUnitPlatformProperty(key, PsiAnchor.create(field)) }
}
Result.create(properties.associateBy { it.key },
JavaLibraryModificationTracker.getInstance(file.project))
})
}
internal fun computePropertyName(psiEvaluator: PsiExpressionEvaluator, nameInitializer: PsiExpression?): String? {
if (nameInitializer == null) return null
return psiEvaluator.computeConstantExpression(nameInitializer, true) as? String
}
| apache-2.0 | a42b85765bc3cf5b7cd5ddf1c721ae30 | 46.679245 | 120 | 0.786308 | 4.45679 | false | false | false | false |
treelzebub/pizarro | explorer/src/main/java/net/treelzebub/pizarro/explorer/model/FileTreeModelImpl.kt | 1 | 2907 | package net.treelzebub.pizarro.explorer.model
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Environment
import android.util.Log
import android.webkit.MimeTypeMap
import net.treelzebub.kapsule.extensions.TAG
import net.treelzebub.kapsule.extensions.safePeek
import net.treelzebub.pizarro.explorer.entities.FileMetadata
import java.io.File
import java.util.*
/**
* Created by Tre Murillo on 3/19/16
*/
class FileTreeModelImpl : FileTreeModel {
private val rootDir: File get() = Environment.getExternalStorageDirectory()
private var currentDir: File = rootDir
override val stack: Stack<File> = Stack()
override fun ls(dir: File?): List<FileMetadata> {
val safeDir = dir ?: rootDir
currentDir = safeDir
val parentDirList = if (currentDir != rootDir) {
arrayListOf(FileMetadata(currentDir.parentFile, true))
} else {
arrayListOf()
}
return parentDirList +
safeDir.listFiles()
.sortedWith(FileComparator())
.map { FileMetadata(it) }
}
override fun reload(): List<FileMetadata> {
return ls(currentDir)
}
override fun cd(oldDir: File, newDir: File): List<FileMetadata> {
stack.push(oldDir)
return ls(newDir)
}
override fun exec(c: Context, uri: Uri) {
val file = File(uri.path)
val mimeType = MimeTypeMap.getSingleton()
.getMimeTypeFromExtension(file.extension)
val intent = Intent(Intent.ACTION_VIEW, uri).apply {
type = mimeType ?: "*/*"
setDataAndType(uri, type)
}
c.startActivity(intent)
}
override fun mkDir(name: String): Boolean {
return File(currentDir.path + "/$name").mkdir()
}
override fun rm(file: File): Boolean {
val absFile = File(file.toURI())
if (!absFile.isDirectory) {
return absFile.delete()
}
Log.d(TAG, if (!absFile.exists()) "${file.absolutePath} deleted" else "${file.absolutePath} not deleted")
return false
}
override fun canGoBack(): Boolean {
return stack.safePeek() != null
}
override fun back(): List<FileMetadata>? {
return if (stack.isNotEmpty()) {
ls(stack.pop())
} else null
}
private inner class FileComparator : Comparator<File> {
override fun compare(o1: File, o2: File): Int {
if (o1.isDirectory && !o2.isDirectory) {
// Directory before non-directory
return -1
} else if (!o1.isDirectory && o2.isDirectory) {
// Non-directory after directory
return 1
} else {
// Alphabetic order otherwise
return o1.compareTo(o2)
}
}
}
}
| gpl-3.0 | 1196e1fa18424e40706e292348cc64ee | 29.28125 | 113 | 0.598555 | 4.472308 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/project-wizard/idea/src/org/jetbrains/kotlin/tools/projectWizard/wizard/ui/secondStep/modulesEditor/TargetsModel.kt | 5 | 4599 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.tools.projectWizard.wizard.ui.secondStep.modulesEditor
import org.jetbrains.kotlin.idea.projectWizard.WizardStatsService
import org.jetbrains.kotlin.idea.projectWizard.WizardStatsService.UiEditorUsageStats
import org.jetbrains.kotlin.tools.projectWizard.core.Context
import org.jetbrains.kotlin.tools.projectWizard.settings.buildsystem.Module
import org.jetbrains.kotlin.tools.projectWizard.settings.buildsystem.ModuleKind
import org.jetbrains.kotlin.utils.addToStdlib.safeAs
import javax.swing.tree.DefaultMutableTreeNode
import javax.swing.tree.TreePath
import kotlin.reflect.KMutableProperty0
class TargetsModel(
private val tree: ModulesEditorTree,
private val value: KMutableProperty0<List<Module>?>,
private val context: Context,
private val uiEditorUsagesStats: UiEditorUsageStats?
) {
private val root get() = tree.model.root as DefaultMutableTreeNode
private fun addToTheTree(module: Module, modifyValue: Boolean, parent: DefaultMutableTreeNode = root) {
val pathsToExpand = mutableListOf<TreePath>()
fun add(moduleToAdd: Module, parentToAdd: DefaultMutableTreeNode) {
DefaultMutableTreeNode(moduleToAdd).apply {
val userObject = parentToAdd.userObject
when {
userObject is Module && userObject.kind == ModuleKind.singlePlatformJvm -> {
val indexOfLastModule = parentToAdd.children()
.toList()
.indexOfLast {
it.safeAs<DefaultMutableTreeNode>()?.userObject is Module
}
if (indexOfLastModule == -1) parentToAdd.insert(this, 0)
else parentToAdd.insert(this, indexOfLastModule)
}
else -> parentToAdd.add(this)
}
pathsToExpand += TreePath(path)
moduleToAdd.subModules.forEach { subModule ->
add(subModule, this)
}
// sourcesets for now does not provide functionality except storing dependencies
// so, there is no reason for now to show them for user
/* moduleToAdd.sourcesets.forEach { sourceset ->
val sourcesetNode = DefaultMutableTreeNode(sourceset)
add(sourcesetNode)
pathsToExpand += TreePath(sourcesetNode.path)
}*/
}
}
add(module, parent)
if (modifyValue) {
when (val parentModule = parent.userObject) {
ModulesEditorTree.PROJECT_USER_OBJECT -> value.set(value.get().orEmpty() + module)
is Module -> parentModule.subModules += module
}
}
tree.reload()
pathsToExpand.forEach(tree::expandPath)
}
fun add(module: Module) {
WizardStatsService.logOnModuleCreated(context.contextComponents.get(), module.configurator.id)
uiEditorUsagesStats?.let { it.modulesCreated++ }
addToTheTree(module, modifyValue = true, parent = tree.selectedNode ?: root)
context.writeSettings {
module.apply { initDefaultValuesForSettings() }
}
}
fun update() {
root.removeAllChildren()
value.get()?.forEach { addToTheTree(it, modifyValue = false) }
if (value.get()?.isEmpty() == true) {
tree.reload()
}
}
fun removeSelected() {
val selectedNode = tree.selectedNode?.takeIf { it.userObject is Module } ?: return
val module = selectedNode.userObject as Module
WizardStatsService.logOnModuleRemoved(context.contextComponents.get(), module.configurator.id)
uiEditorUsagesStats?.let { it.modulesRemoved++ }
when (val parent = selectedNode.parent.safeAs<DefaultMutableTreeNode>()?.userObject) {
ModulesEditorTree.PROJECT_USER_OBJECT -> {
val index = selectedNode.parent.getIndex(selectedNode)
selectedNode.removeFromParent()
value.set(value.get()?.toMutableList().also { it?.removeAt(index) })
}
is Module -> {
parent.subModules = parent.subModules.filterNot { it === selectedNode.userObject }
selectedNode.removeFromParent()
}
}
tree.reload()
}
} | apache-2.0 | ed39caaba031e90901083fce99f98d51 | 42.809524 | 158 | 0.626658 | 5.19661 | false | false | false | false |
smmribeiro/intellij-community | plugins/filePrediction/src/com/intellij/filePrediction/candidates/FilePredictionCandidateProvider.kt | 12 | 2596 | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.filePrediction.candidates
import com.intellij.openapi.extensions.ExtensionPointName
import com.intellij.openapi.project.Project
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.testFramework.LightVirtualFile
import org.jetbrains.annotations.ApiStatus
private val EP_NAME = ExtensionPointName<FilePredictionCandidateProvider>("com.intellij.filePrediction.candidateProvider")
@ApiStatus.Internal
interface FilePredictionCandidateProvider {
fun getWeight(): Int
fun provideCandidates(project: Project, file: VirtualFile?, refs: Set<VirtualFile>, limit: Int): Collection<FilePredictionCandidateFile>
}
internal abstract class FilePredictionBaseCandidateProvider(private val weight: Int) : FilePredictionCandidateProvider {
override fun getWeight(): Int = weight
internal fun addWithLimit(from: Iterator<VirtualFile>,
to: MutableSet<FilePredictionCandidateFile>,
source: FilePredictionCandidateSource,
skip: VirtualFile?, limit: Int) {
while (to.size < limit && from.hasNext()) {
val next = from.next()
if (!next.isDirectory && skip != next && next !is LightVirtualFile) {
to.add(FilePredictionCandidateFile(next, source))
}
}
}
}
open class CompositeCandidateProvider : FilePredictionCandidateProvider {
override fun getWeight(): Int {
return 0
}
open fun getProviders() : List<FilePredictionCandidateProvider> {
return EP_NAME.extensionList.sortedBy { it.getWeight() }
}
override fun provideCandidates(project: Project, file: VirtualFile?, refs: Set<VirtualFile>, limit: Int): Collection<FilePredictionCandidateFile> {
val result = HashSet<FilePredictionCandidateFile>()
val providers = getProviders()
for ((index, provider) in providers.withIndex()) {
val providerLimit = (limit - result.size) / (providers.size - index)
result.addAll(provider.provideCandidates(project, file, refs, providerLimit))
}
return result
}
}
data class FilePredictionCandidateFile(val file: VirtualFile, val source: FilePredictionCandidateSource) {
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as FilePredictionCandidateFile
if (file != other.file) return false
return true
}
override fun hashCode(): Int {
return file.hashCode()
}
} | apache-2.0 | d66af0a223b6a9a4d5c2aa16dec120be | 36.1 | 149 | 0.730354 | 4.907372 | false | false | false | false |
angelolloqui/SwiftKotlin | Assets/Tests/plugins/CommentsAdditionTransformPlugin.kt | 1 | 705 | //
// Header comments
// Multiple lines together
//
// Created by Angel Garcia on 14/10/2017.
//
internal class MyClass {
//Public properties
internal var a: Int? = null
internal var b: String? = null
//Public method
internal fun aMethod() {
// A comment inside aMethod
b = "method run"
b = b + "more"
}
/*
Multiline comments
are also supported
*/
internal fun anotherMethod() {
val a = this.a
if (a != null) {
// Inside if
this.a = a + 1
} else {
// Inside else
this.a = 1
}
}
}
// Other comments before structs
internal data class MyStruct {}
| mit | be8f80dc309102b82ff298892f560427 | 17.552632 | 42 | 0.521986 | 4.122807 | false | false | false | false |
simonnorberg/dmach | app/src/main/java/net/simno/dmach/machine/PanFader.kt | 1 | 7926 | package net.simno.dmach.machine
import android.animation.ValueAnimator
import android.view.animation.DecelerateInterpolator
import androidx.compose.foundation.gestures.awaitFirstDown
import androidx.compose.foundation.gestures.forEachGesture
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.layout.wrapContentSize
import androidx.compose.material3.MaterialTheme
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.drawBehind
import androidx.compose.ui.geometry.CornerRadius
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.geometry.Size
import androidx.compose.ui.graphics.drawscope.Stroke
import androidx.compose.ui.input.pointer.changedToDown
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.input.pointer.positionChanged
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import net.simno.dmach.R
import net.simno.dmach.core.DarkLargeText
import net.simno.dmach.core.DrawableRect
import net.simno.dmach.core.draw
import net.simno.dmach.theme.AppTheme
@Composable
fun PanFader(
panId: Int,
pan: Float?,
modifier: Modifier = Modifier,
onPan: (Float) -> Unit
) {
val rectHeight = AppTheme.dimens.RectHeight
Box(
modifier = modifier
.width(AppTheme.dimens.ButtonMedium)
.fillMaxHeight()
) {
Box(
modifier = Modifier
.fillMaxWidth()
.height(rectHeight)
.align(Alignment.TopCenter)
.padding(top = 2.dp)
) {
DarkLargeText(
text = stringResource(R.string.pan_right),
textAlign = TextAlign.Center,
modifier = Modifier
.wrapContentSize()
.align(Alignment.Center)
)
}
Box(
modifier = Modifier
.fillMaxWidth()
.height(rectHeight)
.align(Alignment.BottomCenter)
.padding(bottom = 2.dp)
) {
DarkLargeText(
text = stringResource(R.string.pan_left),
textAlign = TextAlign.Center,
modifier = Modifier
.wrapContentSize()
.align(Alignment.Center)
)
}
Fader(
panId = panId,
pan = pan,
onPan = onPan,
modifier = modifier
)
}
}
@Composable
private fun Fader(
panId: Int,
pan: Float?,
onPan: (Float) -> Unit,
modifier: Modifier = Modifier
) {
val color = MaterialTheme.colorScheme.secondary
val rectHeight = AppTheme.dimens.RectHeight
val cornerShape = MaterialTheme.shapes.small
val paddingSmall = AppTheme.dimens.PaddingSmall
var rect by remember { mutableStateOf<DrawableRect?>(null) }
Box(
modifier = modifier
.fillMaxSize()
.pointerInput(panId) {
val strokeWidth = paddingSmall.toPx()
val rectHeightPx = rectHeight.toPx()
val rectSize = Size(size.width.toFloat(), rectHeightPx)
val offset = rectHeightPx / 2f
val radius = cornerShape.topStart.toPx(rectSize, this)
val cornerRadius = CornerRadius(radius, radius)
val stroke = Stroke(width = strokeWidth)
val minX = strokeWidth / 2f
val minY = offset - (strokeWidth / 2f)
val maxY = size.height - minY
var centerAnimator: ValueAnimator? = null
var isCentered = true
val center = size.height / 2f
val left = center + (offset / 2f)
val right = center - (offset / 2f)
fun notifyPosition(y: Float, notifyCenter: Boolean = false) {
// Convert pixels to a position value [0.0-1.0]
val pos = if (notifyCenter) {
// Pixel conversion is not exact. Set y to 0.5 if we know it is centered.
0.5f
} else {
1 - ((y - minY) / (maxY - minY)).coerceIn(0f, 1f)
}
onPan(pos)
}
fun getDrawableRect(y: Float): DrawableRect {
val newY = y
.coerceAtLeast(minY)
.coerceAtMost(maxY)
return DrawableRect(
color = color,
topLeft = Offset(minX, newY - offset),
size = rectSize,
cornerRadius = cornerRadius,
style = stroke,
alpha = 0.94f
)
}
fun animateToCenter(y: Float, center: Float) {
centerAnimator?.cancel()
centerAnimator = ValueAnimator
.ofFloat(y, center)
.apply {
duration = 100L
interpolator = DecelerateInterpolator()
addUpdateListener { animation ->
(animation.animatedValue as Float).let {
rect = getDrawableRect(it)
notifyPosition(it, notifyCenter = it == center)
}
}
start()
}
}
fun onPointerDownOrMove(y: Float) {
if (y < left && y > right) {
if (!isCentered) {
isCentered = true
animateToCenter(y, center)
}
} else {
isCentered = false
rect = getDrawableRect(y)
notifyPosition(y)
}
}
if (pan != null) {
// Convert position value [0.0-1.0] to pixels.
val newY = if (pan == 0.5f) size.height / 2f else (1 - pan) * (maxY - minY) + minY
rect = getDrawableRect(newY)
}
forEachGesture {
awaitPointerEventScope {
val firstPointer = awaitFirstDown()
if (firstPointer.changedToDown()) {
firstPointer.consume()
}
onPointerDownOrMove(firstPointer.position.y)
do {
val event = awaitPointerEvent()
event.changes.forEach { pointer ->
if (pointer.positionChanged()) {
pointer.consume()
}
onPointerDownOrMove(pointer.position.y)
}
} while (event.changes.any { it.pressed })
}
}
}
.drawBehind {
rect?.let(::draw)
}
)
}
| gpl-3.0 | 82e3a770ec25b017f6116f6e1287e1c5 | 36.386792 | 102 | 0.516906 | 5.330195 | false | false | false | false |
NlRVANA/Unity | app/src/main/java/com/zwq65/unity/ui/activity/ImageActivity.kt | 1 | 8893 | /*
* Copyright [2017] [NIRVANA PRIVATE LIMITED]
*
* 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.zwq65.unity.ui.activity
import android.Manifest
import android.content.Intent
import android.content.pm.PackageManager.PERMISSION_GRANTED
import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.view.ViewGroup
import androidx.appcompat.widget.AppCompatCheckBox
import androidx.viewpager.widget.PagerAdapter
import androidx.viewpager.widget.ViewPager
import com.bumptech.glide.Glide
import com.github.chrisbanes.photoview.PhotoView
import com.gyf.barlibrary.ImmersionBar
import com.zwq65.unity.R
import com.zwq65.unity.data.network.retrofit.response.enity.Image
import com.zwq65.unity.ui._base.BaseDaggerActivity
import com.zwq65.unity.ui.contract.ImageContract
import com.zwq65.unity.utils.LogUtils
import kotlinx.android.synthetic.main.activity_image.*
import pub.devrel.easypermissions.AppSettingsDialog
import pub.devrel.easypermissions.EasyPermissions
/**
* ================================================
* 查看大图
*
* Created by NIRVANA on 2017/09/27
* Contact with <[email protected]>
* ================================================
*/
class ImageActivity : BaseDaggerActivity<ImageContract.View, ImageContract.Presenter<ImageContract.View>>(), ImageContract.View, EasyPermissions.PermissionCallbacks {
private var cbLove: AppCompatCheckBox? = null
internal var currentPosition: Int = 0
private var pageSize: Int = 0
internal var imageList: List<Image> = ArrayList()
override val layoutId: Int
get() = R.layout.activity_image
override fun initBaseTooBar(): Boolean {
return false
}
override fun dealIntent(intent: Intent) {
val bundle = intent.extras
if (bundle != null) {
currentPosition = bundle.getInt(POSITION)
imageList = bundle.getParcelableArrayList(IMAGE_LIST)
}
pageSize = imageList.size
}
override fun initView() {
initToolbar()
initViewPager()
setCurrentPage()
}
override fun initData() {
//empty
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
menuInflater.inflate(R.menu.menu_meizhi, menu)
//找到checkbox设置下样式
cbLove = menu.findItem(R.id.menu_cb_love).actionView as AppCompatCheckBox
cbLove?.setButtonDrawable(R.drawable.selector_ic_love)
cbLove?.setOnCheckedChangeListener { _, isChecked ->
if (isChecked) {
mPresenter.collectPicture(imageList[currentPosition])
} else {
mPresenter.cancelCollectPicture(imageList[currentPosition])
}
}
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
android.R.id.home -> onBackPressed()
R.id.action_save -> {
//保存大图
if (!EasyPermissions.hasPermissions(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
//未获取权限
LogUtils.e("未获取权限")
val perms = ArrayList<String>()
perms.add(Manifest.permission.WRITE_EXTERNAL_STORAGE)
if (EasyPermissions.somePermissionPermanentlyDenied(this, perms)) {
LogUtils.e("不再提醒")
AppSettingsDialog.Builder(this).build().show()
} else {
EasyPermissions.requestPermissions(this, "請求存儲權限", SAVE_MEIZHI,
Manifest.permission.WRITE_EXTERNAL_STORAGE)
}
} else {
LogUtils.i("已获取权限")
savePicture()
}
requestPermissionsSafely(Manifest.permission.WRITE_EXTERNAL_STORAGE, SAVE_MEIZHI)
}
else -> {
}
}
return true
}
private fun savePicture() {
mPresenter.savePicture(this, imageList[currentPosition])
}
/**
* 回调中判断权限是否申请成功
*
* @param requestCode The request code passed in [.requestPermissions].
* @param permissions The requested permissions. Never null.
* @param grantResults The grant results for the corresponding permissions
* which is either [android.content.pm.PackageManager.PERMISSION_GRANTED]
* or [android.content.pm.PackageManager.PERMISSION_DENIED]. Never null.
*/
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String>, grantResults: IntArray) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this)
if (requestCode == SAVE_MEIZHI) {
if (grantResults.isNotEmpty() && grantResults[0] == PERMISSION_GRANTED) {
LogUtils.i("SAVE SUCCESS")
} else {
LogUtils.e("SAVE FAIL")
}
}
}
private fun initToolbar() {
//setup toolbar
setSupportActionBar(toolbar)
//添加‘<--’返回功能
supportActionBar?.setDisplayHomeAsUpEnabled(true)
supportActionBar?.setHomeAsUpIndicator(R.drawable.ic_arrow_white_24dp)
//添加了toolbar,重新设置沉浸式状态栏
ImmersionBar.with(this).titleBar(toolbar!!).init()
}
/**
* 设置当前页数
*/
private fun setCurrentPage() {
//改变toolbar标题为图片desc
if (supportActionBar != null) {
if (imageList[currentPosition].desc != null) {
supportActionBar?.title = imageList[currentPosition].desc
}
}
//当前页码
if (pageSize <= 1) {
tv_current_page?.visibility = View.GONE
} else {
tv_current_page?.text = resources.getString(R.string.placeholder_divider, (currentPosition + 1).toString(), pageSize.toString())
}
//当前图片是否已被用户收藏
mPresenter.isPictureCollect(imageList[currentPosition])
.compose(bindUntilStopEvent())
.subscribe { aBoolean ->
cbLove?.isChecked = aBoolean
}
}
private fun initViewPager() {
//预加载2个item
vp_images?.offscreenPageLimit = 2
val mAdapter = MyAdapter()
vp_images?.adapter = mAdapter
//设置当前加载的资源为点击进入的图片
vp_images?.currentItem = currentPosition
vp_images?.addOnPageChangeListener(object : ViewPager.SimpleOnPageChangeListener() {
override fun onPageSelected(position: Int) {
//滑动改变当前页数
currentPosition = position
setCurrentPage()
}
})
}
override fun onPermissionsGranted(requestCode: Int, perms: List<String>) {
LogUtils.i("SAVE SUCCESS!!!!")
}
override fun onPermissionsDenied(requestCode: Int, perms: List<String>) {
LogUtils.e("SAVE FAIL!!!")
}
/**
* 显示大图viewpager's adapter
*/
private inner class MyAdapter : PagerAdapter() {
override fun getCount(): Int {
return imageList.size
}
override fun isViewFromObject(view: View, `object`: Any): Boolean {
return view === `object`
}
override fun instantiateItem(container: ViewGroup, position: Int): Any {
//显示大图view
val view = layoutInflater.inflate(R.layout.item_image, container, false)
val ivImage = view.findViewById<PhotoView>(R.id.iv_image)
val image = imageList[position]
Glide.with(this@ImageActivity).load(image.url).into(ivImage)
container.addView(view, 0)
return view
}
override fun destroyItem(container: ViewGroup, position: Int, `object`: Any) {
val view = `object` as View
container.removeView(view)
}
}
companion object {
const val POSITION = "POSITION"
const val IMAGE_LIST = "IMAGE_LIST"
private const val SAVE_MEIZHI = 1
}
}
| apache-2.0 | 2d3d6244a41fd4e2eede1848de691858 | 34.290984 | 166 | 0.619789 | 4.744353 | false | false | false | false |
Waboodoo/HTTP-Shortcuts | HTTPShortcuts/app/src/main/kotlin/ch/rmy/android/http_shortcuts/activities/main/ShortcutGridAdapter.kt | 1 | 2175 | package ch.rmy.android.http_shortcuts.activities.main
import android.content.res.ColorStateList
import android.graphics.Color
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.core.view.isVisible
import ch.rmy.android.framework.extensions.consume
import ch.rmy.android.framework.extensions.context
import ch.rmy.android.framework.extensions.zoomToggle
import ch.rmy.android.http_shortcuts.databinding.GridItemShortcutBinding
class ShortcutGridAdapter : BaseShortcutAdapter() {
override fun createViewHolder(parent: ViewGroup, layoutInflater: LayoutInflater) =
ShortcutViewHolder(GridItemShortcutBinding.inflate(layoutInflater, parent, false))
inner class ShortcutViewHolder(
private val binding: GridItemShortcutBinding,
) : BaseShortcutViewHolder(binding.root) {
init {
binding.root.setOnClickListener {
userEventChannel.trySend(UserEvent.ShortcutClicked(shortcutId))
}
binding.root.setOnLongClickListener {
if (isLongClickingEnabled) {
consume {
userEventChannel.trySend(UserEvent.ShortcutLongClicked(shortcutId))
}
} else {
false
}
}
}
override fun setItem(item: ShortcutListItem.Shortcut, isUpdate: Boolean) {
binding.name.text = item.name
binding.icon.setIcon(item.icon, animated = isUpdate)
if (isUpdate) {
binding.waitingIcon.zoomToggle(item.isPending)
} else {
binding.waitingIcon.isVisible = item.isPending
}
val primaryColor = getPrimaryTextColor(context, item.textColor)
binding.waitingIcon.imageTintList = ColorStateList.valueOf(primaryColor)
binding.name.setTextColor(primaryColor)
if (item.useTextShadow) {
binding.name.setShadowLayer(1f, 2f, 2f, getTextShadowColor(context, item.textColor))
} else {
binding.name.setShadowLayer(0f, 0f, 0f, Color.TRANSPARENT)
}
}
}
}
| mit | 149478bc9ae01504858240a828134093 | 38.545455 | 100 | 0.652874 | 5.046404 | false | false | false | false |
MediaArea/MediaInfo | Source/GUI/Android/app/src/main/java/net/mediaarea/mediainfo/ReportDetailActivity.kt | 1 | 3615 | /* Copyright (c) MediaArea.net SARL. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license that can
* be found in the License.html file in the root of the source tree.
*/
package net.mediaarea.mediainfo
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.ViewModelProvider
import android.content.Intent
import android.app.Activity
import android.os.Bundle
import android.os.Build
import android.view.MenuItem
import android.content.res.AssetManager
import androidx.viewpager.widget.ViewPager
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.schedulers.Schedulers
import io.reactivex.android.schedulers.AndroidSchedulers
import kotlinx.android.synthetic.main.activity_report_detail.*
class ReportDetailActivity : AppCompatActivity(), ReportActivityListener {
private inner class PageChangeListener(private val reports: List<Report>) : ViewPager.SimpleOnPageChangeListener() {
override fun onPageSelected(position: Int) {
super.onPageSelected(position)
title = reports.elementAt(position).filename
intent.putExtra(Core.ARG_REPORT_ID, reports.elementAt(position).id)
}
}
private var disposable: CompositeDisposable = CompositeDisposable()
private lateinit var reportModel: ReportViewModel
override fun getReportViewModel(): ReportViewModel {
return reportModel
}
// BUG: appcompat-1.1.0 returns resource that breaks old WebView implementations
override fun getAssets(): AssetManager {
if (Build.VERSION.SDK_INT in 21..25) {
return resources.assets
}
return super.getAssets()
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_report_detail)
setSupportActionBar(detail_toolbar)
// Show the Up button in the action bar.
supportActionBar?.setDisplayHomeAsUpEnabled(true)
if (resources.getBoolean(R.bool.has_two_pane)) {
finish()
return
}
val viewModelFactory = Injection.provideViewModelFactory(this)
reportModel = ViewModelProvider(this, viewModelFactory).get(ReportViewModel::class.java)
disposable.add(reportModel.getAllReports()
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe { reports: List<Report> ->
pager.addOnPageChangeListener(PageChangeListener(reports))
pager.adapter = PagerAdapter(supportFragmentManager, reports)
val id = intent.getIntExtra(Core.ARG_REPORT_ID, -1)
if (id!=-1) {
val index = reports.indexOfFirst { it.id == id }
if (index!=-1) {
title = reports.elementAt(index).filename
pager.setCurrentItem(index, false)
}
}
})
}
override fun onStop() {
super.onStop()
// clear all the subscription
disposable.clear()
}
override fun finish() {
val id = intent.getIntExtra(Core.ARG_REPORT_ID, -1)
val result = Intent()
result.putExtra(Core.ARG_REPORT_ID, id)
setResult(Activity.RESULT_OK, result)
super.finish()
}
override fun onOptionsItemSelected(item: MenuItem) = when (item.itemId) {
android.R.id.home -> {
finish()
true
}
else -> super.onOptionsItemSelected(item)
}
}
| bsd-2-clause | 22e2450c82dcfeb17b45e27c6b25d0dd | 32.165138 | 120 | 0.657815 | 4.86541 | false | false | false | false |
Waboodoo/HTTP-Shortcuts | HTTPShortcuts/app/src/main/kotlin/ch/rmy/android/http_shortcuts/data/domains/QueryExtensions.kt | 1 | 4148 | package ch.rmy.android.http_shortcuts.data.domains
import ch.rmy.android.framework.data.RealmContext
import ch.rmy.android.framework.extensions.runIfNotNull
import ch.rmy.android.http_shortcuts.data.domains.categories.CategoryId
import ch.rmy.android.http_shortcuts.data.domains.pending_executions.ExecutionId
import ch.rmy.android.http_shortcuts.data.domains.shortcuts.ShortcutId
import ch.rmy.android.http_shortcuts.data.domains.shortcuts.ShortcutNameOrId
import ch.rmy.android.http_shortcuts.data.domains.variables.VariableId
import ch.rmy.android.http_shortcuts.data.domains.variables.VariableKeyOrId
import ch.rmy.android.http_shortcuts.data.models.AppLockModel
import ch.rmy.android.http_shortcuts.data.models.BaseModel
import ch.rmy.android.http_shortcuts.data.models.CategoryModel
import ch.rmy.android.http_shortcuts.data.models.PendingExecutionModel
import ch.rmy.android.http_shortcuts.data.models.ShortcutModel
import ch.rmy.android.http_shortcuts.data.models.VariableModel
import ch.rmy.android.http_shortcuts.data.models.WidgetModel
import io.realm.Case
import io.realm.RealmQuery
import io.realm.kotlin.where
fun RealmContext.getBase(): RealmQuery<BaseModel> =
realmInstance
.where()
fun RealmContext.getCategoryById(categoryId: CategoryId): RealmQuery<CategoryModel> =
realmInstance
.where<CategoryModel>()
.equalTo(CategoryModel.FIELD_ID, categoryId)
fun RealmContext.getShortcutById(shortcutId: ShortcutId): RealmQuery<ShortcutModel> =
realmInstance
.where<ShortcutModel>()
.equalTo(ShortcutModel.FIELD_ID, shortcutId)
fun RealmContext.getTemporaryShortcut(): RealmQuery<ShortcutModel> =
getShortcutById(ShortcutModel.TEMPORARY_ID)
fun RealmContext.getShortcutByNameOrId(shortcutNameOrId: ShortcutNameOrId): RealmQuery<ShortcutModel> =
realmInstance
.where<ShortcutModel>()
.equalTo(ShortcutModel.FIELD_ID, shortcutNameOrId)
.or()
.equalTo(ShortcutModel.FIELD_NAME, shortcutNameOrId, Case.INSENSITIVE)
fun RealmContext.getVariableById(variableId: VariableId): RealmQuery<VariableModel> =
realmInstance
.where<VariableModel>()
.equalTo(VariableModel.FIELD_ID, variableId)
fun RealmContext.getVariableByKeyOrId(keyOrId: VariableKeyOrId): RealmQuery<VariableModel> =
realmInstance
.where<VariableModel>()
.beginGroup()
.equalTo(VariableModel.FIELD_KEY, keyOrId)
.and()
.notEqualTo(VariableModel.FIELD_ID, VariableModel.TEMPORARY_ID)
.endGroup()
.or()
.equalTo(VariableModel.FIELD_ID, keyOrId)
fun RealmContext.getTemporaryVariable(): RealmQuery<VariableModel> =
realmInstance
.where<VariableModel>()
.equalTo(VariableModel.FIELD_ID, VariableModel.TEMPORARY_ID)
fun RealmContext.getPendingExecutions(shortcutId: ShortcutId? = null, waitForNetwork: Boolean? = null): RealmQuery<PendingExecutionModel> =
realmInstance
.where<PendingExecutionModel>()
.runIfNotNull(shortcutId) {
equalTo(PendingExecutionModel.FIELD_SHORTCUT_ID, it)
}
.runIfNotNull(waitForNetwork) {
equalTo(PendingExecutionModel.FIELD_WAIT_FOR_NETWORK, it)
}
.sort(PendingExecutionModel.FIELD_ENQUEUED_AT)
fun RealmContext.getPendingExecution(id: ExecutionId): RealmQuery<PendingExecutionModel> =
realmInstance
.where<PendingExecutionModel>()
.equalTo(PendingExecutionModel.FIELD_ID, id)
fun RealmContext.getAppLock(): RealmQuery<AppLockModel> =
realmInstance
.where()
fun RealmContext.getWidgetsByIds(widgetIds: List<Int>): RealmQuery<WidgetModel> =
realmInstance
.where<WidgetModel>()
.`in`(WidgetModel.FIELD_WIDGET_ID, widgetIds.toTypedArray())
fun RealmContext.getDeadWidgets(): RealmQuery<WidgetModel> =
realmInstance
.where<WidgetModel>()
.isNull(WidgetModel.FIELD_SHORTCUT)
fun RealmContext.getWidgetsForShortcut(shortcutId: ShortcutId): RealmQuery<WidgetModel> =
realmInstance
.where<WidgetModel>()
.equalTo("${WidgetModel.FIELD_SHORTCUT}.${ShortcutModel.FIELD_ID}", shortcutId)
| mit | aef69675dd47b3681f00a8aa5e07022c | 40.48 | 139 | 0.757473 | 4.494041 | false | false | false | false |
chiken88/passnotes | app/src/main/kotlin/com/ivanovsky/passnotes/data/crypto/keyprovider/KeyStoreSecretKeyProvider.kt | 1 | 3421 | package com.ivanovsky.passnotes.data.crypto.keyprovider
import android.annotation.TargetApi
import android.security.keystore.KeyGenParameterSpec
import android.security.keystore.KeyProperties
import com.ivanovsky.passnotes.data.crypto.DataCipherConstants
import com.ivanovsky.passnotes.data.crypto.DataCipherConstants.ANDROID_KEY_STORE
import com.ivanovsky.passnotes.data.crypto.DataCipherConstants.KEY_ALGORITHM
import com.ivanovsky.passnotes.data.crypto.DataCipherConstants.KEY_ALIAS
import com.ivanovsky.passnotes.data.crypto.DataCipherConstants.KEY_SIZE
import com.ivanovsky.passnotes.util.Logger
import java.lang.Exception
import java.security.GeneralSecurityException
import java.security.KeyStore
import java.security.KeyStore.getInstance
import javax.crypto.KeyGenerator
import javax.crypto.SecretKey
@TargetApi(23)
class KeyStoreSecretKeyProvider : SecretKeyProvider {
private var keyStore: KeyStore? = null
override fun getSecretKey(isCreateIfNeed: Boolean): SecretKey? {
var key: SecretKey?
val keyStore = getKeyStore() ?: return null
key = obtainSecretKeyFromKeyStore(keyStore)
if (key == null && isCreateIfNeed) {
val generatedKey = generateNewSecretKey()
if (generatedKey != null && refreshKeyStore()) {
key = generatedKey
}
}
return key
}
private fun getKeyStore(): KeyStore? {
if (keyStore != null) return keyStore
try {
val store = getInstance(ANDROID_KEY_STORE)
store?.load(null)
keyStore = store
} catch (e: Exception) {
Logger.printStackTrace(e)
}
return keyStore
}
private fun refreshKeyStore(): Boolean {
// just reload AndroidKeyStore because new key is automatically stored in it immediately
// after it was generated
keyStore = null
return getKeyStore() != null
}
private fun obtainSecretKeyFromKeyStore(keyStore: KeyStore): SecretKey? {
var key: SecretKey? = null
try {
val entry = keyStore.getEntry(DataCipherConstants.KEY_ALIAS, null)
if (entry is KeyStore.SecretKeyEntry) {
key = entry.secretKey
}
} catch (e: Exception) {
Logger.printStackTrace(e)
}
Logger.d(TAG, "Load secret key from key store with algorithm: " + key?.algorithm)
return key
}
private fun generateNewSecretKey(): SecretKey? {
var key: SecretKey? = null
try {
val keyGenerator = KeyGenerator.getInstance(KEY_ALGORITHM, ANDROID_KEY_STORE)
val purposes = KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT
val keyParams = KeyGenParameterSpec.Builder(KEY_ALIAS, purposes)
.setKeySize(KEY_SIZE)
.setBlockModes(KeyProperties.BLOCK_MODE_CBC)
.setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_PKCS7)
.build()
keyGenerator?.init(keyParams)
key = keyGenerator?.generateKey()
} catch (e: GeneralSecurityException) {
Logger.printStackTrace(e)
}
Logger.d(TAG, "Generate new secret key with algorithm: " + key?.algorithm)
return key
}
companion object {
private val TAG = KeyStoreSecretKeyProvider::class.simpleName
}
}
| gpl-2.0 | 90fca47b080aa03a599b8b108c2bb9a7 | 31.273585 | 96 | 0.664718 | 4.908178 | false | false | false | false |
breadwallet/breadwallet-android | app/src/main/java/com/breadwallet/ui/send/SendSheetController.kt | 1 | 27646 | /**
* BreadWallet
*
* Created by Drew Carlson <[email protected]> on 9/25/19.
* Copyright (c) 2019 breadwallet LLC
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.breadwallet.ui.send
import android.content.Context
import android.graphics.Paint
import android.os.Bundle
import android.view.KeyEvent
import android.view.View
import android.view.inputmethod.EditorInfo
import android.widget.EditText
import android.widget.TextView
import androidx.core.os.bundleOf
import androidx.core.view.isVisible
import com.bluelinelabs.conductor.RouterTransaction
import com.breadwallet.R
import com.breadwallet.breadbox.TransferSpeed
import com.breadwallet.breadbox.formatCryptoForUi
import com.breadwallet.databinding.ControllerSendSheetBinding
import com.breadwallet.effecthandler.metadata.MetaDataEffectHandler
import com.breadwallet.ui.formatFiatForUi
import com.breadwallet.legacy.presenter.customviews.BRKeyboard
import com.breadwallet.logger.logError
import com.breadwallet.tools.animation.SlideDetector
import com.breadwallet.tools.animation.UiUtils
import com.breadwallet.tools.manager.BRSharedPrefs
import com.breadwallet.tools.util.BRConstants
import com.breadwallet.tools.util.Link
import com.breadwallet.tools.util.Utils
import com.breadwallet.ui.BaseMobiusController
import com.breadwallet.ui.auth.AuthenticationController
import com.breadwallet.ui.auth.AuthMode
import com.breadwallet.ui.changehandlers.BottomSheetChangeHandler
import com.breadwallet.ui.controllers.AlertDialogController
import com.breadwallet.ui.flowbind.clicks
import com.breadwallet.ui.flowbind.focusChanges
import com.breadwallet.ui.flowbind.textChanges
import com.breadwallet.ui.scanner.ScannerController
import com.breadwallet.ui.send.SendSheet.E
import com.breadwallet.ui.send.SendSheet.E.OnAmountChange
import com.breadwallet.ui.send.SendSheet.F
import com.breadwallet.ui.send.SendSheet.M
import com.breadwallet.util.isErc20
import com.breadwallet.util.isEthereum
import kotlinx.coroutines.channels.awaitClose
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.callbackFlow
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.merge
import org.kodein.di.direct
import org.kodein.di.erased.instance
import java.math.BigDecimal
import java.text.DecimalFormat
import java.text.NumberFormat
import java.util.Locale
import java.util.concurrent.TimeUnit
private const val CURRENCY_CODE = "CURRENCY_CODE"
private const val CRYPTO_REQUEST_LINK = "CRYPTO_REQUEST_LINK"
private const val RESOLVED_ADDRESS_CHARS = 10
private const val FEE_TIME_PADDING = 1
/** A BottomSheet for sending crypto from the user's wallet to a specified target. */
@Suppress("TooManyFunctions")
class SendSheetController(args: Bundle? = null) :
BaseMobiusController<M, E, F>(args),
AuthenticationController.Listener,
ConfirmTxController.Listener,
AlertDialogController.Listener,
ScannerController.Listener {
companion object {
const val DIALOG_NO_ETH_FOR_TOKEN_TRANSFER = "adjust_for_fee"
const val DIALOG_PAYMENT_ERROR = "payment_error"
}
/** An empty [SendSheetController] for [currencyCode]. */
constructor(currencyCode: String) : this(
bundleOf(CURRENCY_CODE to currencyCode)
)
/** A [SendSheetController] to fulfill the provided [Link.CryptoRequestUrl]. */
constructor(link: Link.CryptoRequestUrl) : this(
bundleOf(
CURRENCY_CODE to link.currencyCode,
CRYPTO_REQUEST_LINK to link
)
)
init {
overridePushHandler(BottomSheetChangeHandler())
overridePopHandler(BottomSheetChangeHandler())
}
private val currencyCode = arg<String>(CURRENCY_CODE)
private val cryptoRequestLink = argOptional<Link.CryptoRequestUrl>(CRYPTO_REQUEST_LINK)
override val init = SendSheetInit
override val update = SendSheetUpdate
override val defaultModel: M
get() {
val fiatCode = BRSharedPrefs.getPreferredFiatIso()
return cryptoRequestLink?.asSendSheetModel(fiatCode)
?: M.createDefault(currencyCode, fiatCode)
}
override val flowEffectHandler
get() = SendSheetHandler.create(
checkNotNull(applicationContext),
breadBox = direct.instance(),
uriParser = direct.instance(),
userManager = direct.instance(),
apiClient = direct.instance(),
ratesRepository = direct.instance(),
metaDataEffectHandler = {
MetaDataEffectHandler(it, direct.instance(), direct.instance())
},
addressServiceLocator = direct.instance()
)
private val binding by viewBinding(ControllerSendSheetBinding::inflate)
override fun onCreateView(view: View) {
super.onCreateView(view)
with(binding) {
keyboard.setBRButtonBackgroundResId(R.drawable.keyboard_white_button)
keyboard.setBRKeyboardColor(R.color.white)
keyboard.setDeleteImage(R.drawable.ic_delete_black)
showKeyboard(false)
textInputAmount.showSoftInputOnFocus = false
layoutSheetBody.layoutTransition = UiUtils.getDefaultTransition()
layoutSheetBody.setOnTouchListener(SlideDetector(router, layoutSheetBody))
}
}
override fun onDestroyView(view: View) {
binding.layoutSheetBody.setOnTouchListener(null)
super.onDestroyView(view)
}
override fun onDetach(view: View) {
super.onDetach(view)
Utils.hideKeyboard(activity)
}
override fun bindView(modelFlow: Flow<M>): Flow<E> {
return with(binding) {
merge(
keyboard.bindInput(),
textInputMemo.bindFocusChanged(),
textInputMemo.bindActionComplete(E.OnSendClicked),
textInputMemo.clicks().map { E.OnAmountEditDismissed },
textInputMemo.textChanges().map { E.OnMemoChanged(it) },
textInputAddress.focusChanges().map { hasFocus ->
if (hasFocus) {
E.OnAmountEditDismissed
} else {
Utils.hideKeyboard(activity)
E.OnTargetStringEntered
}
},
textInputAddress.clicks().map { E.OnAmountEditDismissed },
textInputAddress.textChanges().map { E.OnTargetStringChanged(it) },
textInputDestinationTag.textChanges().map {
E.TransferFieldUpdate.Value(TransferField.DESTINATION_TAG, it)
},
textInputHederaMemo.textChanges().map {
E.TransferFieldUpdate.Value(TransferField.HEDERA_MEMO, it)
},
buttonFaq.clicks().map { E.OnFaqClicked },
buttonScan.clicks().map { E.OnScanClicked },
buttonSend.clicks().map { E.OnSendClicked },
buttonClose.clicks().map { E.OnCloseClicked },
buttonPaste.clicks().map { E.OnPasteClicked },
layoutSendSheet.clicks().map { E.OnCloseClicked },
textInputAmount.clicks().map { E.OnAmountEditClicked },
textInputAmount.focusChanges().map { hasFocus ->
if (hasFocus) {
E.OnAmountEditClicked
} else {
E.OnAmountEditDismissed
}
},
buttonCurrencySelect.clicks().map { E.OnToggleCurrencyClicked },
buttonRegular.clicks().map { E.OnTransferSpeedChanged(TransferSpeedInput.REGULAR) },
buttonEconomy.clicks().map { E.OnTransferSpeedChanged(TransferSpeedInput.ECONOMY) },
buttonPriority.clicks().map { E.OnTransferSpeedChanged(TransferSpeedInput.PRIORITY) },
labelBalanceValue.clicks().map { E.OnSendMaxClicked }
)
}
}
private fun EditText.bindActionComplete(output: E) =
callbackFlow<E> {
setOnEditorActionListener { _, actionId, event ->
if (event?.keyCode == KeyEvent.KEYCODE_ENTER
|| actionId == EditorInfo.IME_ACTION_DONE
|| actionId == EditorInfo.IME_ACTION_NEXT
) {
offer(output)
Utils.hideKeyboard(activity)
true
} else false
}
awaitClose { setOnEditorActionListener(null) }
}
private fun EditText.bindFocusChanged() =
callbackFlow<E> {
View.OnFocusChangeListener { _, hasFocus ->
if (hasFocus) {
offer(E.OnAmountEditDismissed)
} else {
Utils.hideKeyboard(activity)
}
}
awaitClose { onFocusChangeListener = null }
}
private fun BRKeyboard.bindInput() =
callbackFlow<E> {
setOnInsertListener { key ->
when {
key.isEmpty() -> offer(OnAmountChange.Delete)
key[0] == '.' -> offer(OnAmountChange.AddDecimal)
Character.isDigit(key[0]) -> offer(OnAmountChange.AddDigit(key.toInt()))
else -> return@setOnInsertListener
}
}
awaitClose { setOnInsertListener(null) }
}
@Suppress("ComplexMethod", "LongMethod")
override fun M.render() {
val res = checkNotNull(resources)
with(binding) {
ifChanged(M::addressType, M::isResolvingAddress) {
addressProgressBar.isVisible = isResolvingAddress
if (addressType is AddressType.Resolvable) {
inputLayoutAddress.hint = res.getString(
if (addressType is AddressType.Resolvable.PayId) R.string.Send_payId_toLabel else R.string.Send_fio_toLabel
)
inputLayoutAddress.helperText = if (isResolvingAddress) null else {
val first = targetAddress.take(RESOLVED_ADDRESS_CHARS)
val last = targetAddress.takeLast(RESOLVED_ADDRESS_CHARS)
"$first...$last"
}
} else {
inputLayoutAddress.helperText = null
inputLayoutAddress.hint = res.getString(R.string.Send_toLabel)
}
}
ifChanged(M::targetInputError) {
inputLayoutAddress.isErrorEnabled = targetInputError != null
inputLayoutAddress.error = when (targetInputError) {
is M.InputError.Empty ->
res.getString(R.string.Send_noAddress)
is M.InputError.Invalid ->
res.getString(R.string.Send_invalidAddressMessage, currencyCode.toUpperCase())
is M.InputError.ClipboardInvalid ->
res.getString(
R.string.Send_invalidAddressOnPasteboard,
currencyCode.toUpperCase()
)
is M.InputError.ClipboardEmpty ->
res.getString(R.string.Send_emptyPasteboard)
is M.InputError.PayIdInvalid -> res.getString(R.string.Send_payId_invalid)
is M.InputError.PayIdNoAddress -> res.getString(
R.string.Send_payId_noAddress,
currencyCode.toUpperCase(Locale.ROOT)
)
is M.InputError.PayIdRetrievalError -> res.getString(R.string.Send_payId_retrievalError)
is M.InputError.FioInvalid -> res.getString(R.string.Send_fio_invalid)
is M.InputError.FioNoAddress -> res.getString(
R.string.Send_fio_noAddress,
currencyCode.toUpperCase(Locale.ROOT)
)
is M.InputError.FioRetrievalError -> res.getString(R.string.Send_fio_retrievalError)
else -> null
}
}
ifChanged(M::amountInputError) {
inputLayoutAmount.isErrorEnabled = amountInputError != null
inputLayoutAmount.error = when (amountInputError) {
is M.InputError.Empty ->
res.getString(R.string.Send_noAmount)
is M.InputError.BalanceTooLow ->
res.getString(R.string.Send_insufficientFunds)
is M.InputError.FailedToEstimateFee ->
res.getString(R.string.Send_noFeesError)
else -> null
}
}
ifChanged(
M::currencyCode,
M::fiatCode,
M::isAmountCrypto
) {
val sendTitle = res.getString(R.string.Send_title)
val upperCaseCurrencyCode = currencyCode.toUpperCase(Locale.getDefault())
labelTitle.text = "%s %s".format(sendTitle, upperCaseCurrencyCode)
buttonCurrencySelect.text = when {
isAmountCrypto -> upperCaseCurrencyCode
else -> {
val currency = java.util.Currency.getInstance(fiatCode)
"$fiatCode (${currency.symbol})".toUpperCase(Locale.getDefault())
}
}
}
ifChanged(M::isAmountEditVisible, ::showKeyboard)
ifChanged(
M::rawAmount,
M::isAmountCrypto,
M::fiatCode
) {
val formattedAmount = if (isAmountCrypto || rawAmount.isBlank()) {
rawAmount
} else {
rawAmount.formatFiatForInputUi(fiatCode)
}
textInputAmount.setText(formattedAmount)
}
ifChanged(
M::networkFee,
M::fiatNetworkFee,
M::feeCurrencyCode,
M::isAmountCrypto
) {
labelNetworkFee.isVisible = networkFee != BigDecimal.ZERO
labelNetworkFee.text = res.getString(
R.string.Send_fee,
when {
isAmountCrypto ->
networkFee.formatCryptoForUi(feeCurrencyCode, MAX_DIGITS)
else -> fiatNetworkFee.formatFiatForUi(fiatCode)
}
)
}
ifChanged(
M::balance,
M::fiatBalance,
M::isAmountCrypto,
M::isSendingMax
) {
labelBalanceValue.text = when {
isAmountCrypto -> balance.formatCryptoForUi(currencyCode)
else -> fiatBalance.formatFiatForUi(fiatCode)
}
if (isSendingMax) {
labelBalanceValue.paintFlags = 0
labelBalanceValue.setTextColor(res.getColor(R.color.light_gray, activity!!.theme))
labelBalance.setText(R.string.Send_sendingMax)
} else {
labelBalance.setText(R.string.Send_balanceString)
labelBalanceValue.setTextColor(res.getColor(R.color.blue_button_text, activity!!.theme))
labelBalanceValue.paintFlags = labelBalanceValue.paintFlags or Paint.UNDERLINE_TEXT_FLAG
}
}
ifChanged(M::targetString) {
if (textInputAddress.text.toString() != targetString) {
textInputAddress.setText(targetString, TextView.BufferType.EDITABLE)
}
}
ifChanged(M::memo) {
if (textInputMemo.text.toString() != memo) {
textInputMemo.setText(memo, TextView.BufferType.EDITABLE)
}
}
ifChanged(
M::showFeeSelect,
M::transferSpeed
) {
layoutFeeOption.isVisible = showFeeSelect
setFeeOption(transferSpeed)
}
ifChanged(M::showFeeSelect) {
layoutFeeOption.isVisible = showFeeSelect
}
ifChanged(M::isConfirmingTx) {
val isConfirmVisible =
router.backstack.lastOrNull()?.controller is ConfirmTxController
if (isConfirmingTx && !isConfirmVisible) {
val controller = ConfirmTxController(
currencyCode,
fiatCode,
feeCurrencyCode,
targetAddress,
transferSpeed,
amount,
fiatAmount,
fiatTotalCost,
fiatNetworkFee,
transferFields
)
controller.targetController = this@SendSheetController
router.pushController(RouterTransaction.with(controller))
}
}
ifChanged(M::isAuthenticating) {
val isAuthVisible =
router.backstack.lastOrNull()?.controller is AuthenticationController
if (isAuthenticating && !isAuthVisible) {
val authenticationMode = if (isFingerprintAuthEnable) {
AuthMode.USER_PREFERRED
} else {
AuthMode.PIN_REQUIRED
}
val controller = AuthenticationController(
mode = authenticationMode,
title = res.getString(R.string.VerifyPin_touchIdMessage),
message = res.getString(R.string.VerifyPin_authorize)
)
controller.targetController = this@SendSheetController
router.pushController(RouterTransaction.with(controller))
}
}
ifChanged(M::isBitpayPayment) {
textInputAddress.isEnabled = !isBitpayPayment
textInputAmount.isEnabled = !isBitpayPayment
buttonScan.isVisible = !isBitpayPayment
buttonPaste.isVisible = !isBitpayPayment
}
ifChanged(M::isFetchingPayment, M::isSendingTransaction) {
loadingView.root.isVisible = isFetchingPayment || isSendingTransaction
}
ifChanged(M::destinationTag) {
if (destinationTag != null) {
groupDestinationTag.isVisible = true
inputLayoutDestinationTag.error = if (destinationTag.invalid) {
res.getString(R.string.Send_destinationTag_required_error)
} else null
inputLayoutDestinationTag.hint = res.getString(
when {
destinationTag.required ->
R.string.Send_destinationTag_required
else -> R.string.Send_destinationTag_optional
}
)
if (destinationTag.value.isNullOrBlank() &&
!textInputDestinationTag.text.isNullOrBlank() ||
(!destinationTag.value.isNullOrBlank() &&
textInputDestinationTag.text.isNullOrBlank()) || isDestinationTagFromResolvedAddress
) {
textInputDestinationTag.setText(currentModel.destinationTag?.value)
}
textInputDestinationTag.isEnabled = !isDestinationTagFromResolvedAddress
}
}
ifChanged(M::hederaMemo) {
if (hederaMemo != null) {
groupHederaMemo.isVisible = true
if (!hederaMemo.value.isNullOrBlank() &&
textInputHederaMemo.text.isNullOrBlank()
) {
textInputHederaMemo.setText(currentModel.hederaMemo?.value)
}
}
}
}
}
private fun showKeyboard(show: Boolean) {
binding.groupAmountSection.isVisible = show
if (show) {
Utils.hideKeyboard(activity)
}
}
override fun onLinkScanned(link: Link) {
if (link is Link.CryptoRequestUrl) {
eventConsumer.accept(E.OnRequestScanned(link))
}
}
override fun onAuthenticationSuccess() {
eventConsumer.accept(E.OnAuthSuccess)
}
override fun onAuthenticationCancelled() {
eventConsumer.accept(E.OnAuthCancelled)
}
override fun onPositiveClicked(
dialogId: String,
controller: AlertDialogController,
result: AlertDialogController.DialogInputResult
) {
when (dialogId) {
DIALOG_NO_ETH_FOR_TOKEN_TRANSFER -> {
eventConsumer.accept(E.GoToEthWallet)
}
}
}
override fun onPositiveClicked(controller: ConfirmTxController) {
eventConsumer
.accept(E.ConfirmTx.OnConfirmClicked)
}
override fun onNegativeClicked(controller: ConfirmTxController) {
eventConsumer
.accept(E.ConfirmTx.OnCancelClicked)
}
private fun setFeeOption(feeOption: TransferSpeed) {
val context = applicationContext!!
// TODO: Redo using a toggle button and a selector
with(binding) {
when (feeOption) {
is TransferSpeed.Regular -> {
buttonRegular.setTextColor(context.getColor(R.color.white))
buttonRegular.setBackgroundResource(R.drawable.b_blue_square)
buttonEconomy.setTextColor(context.getColor(R.color.dark_blue))
buttonEconomy.setBackgroundResource(R.drawable.b_half_left_blue_stroke)
buttonPriority.setTextColor(context.getColor(R.color.dark_blue))
buttonPriority.setBackgroundResource(R.drawable.b_half_right_blue_stroke)
labelFeeDescription.text = when {
feeOption.currencyCode.run {
isEthereum() || isErc20()
} -> ethFeeEstimateString(context, feeOption.targetTime)
else -> context.getString(R.string.FeeSelector_estimatedDeliver)
.format(context.getString(R.string.FeeSelector_regularTime))
}
labelFeeWarning.visibility = View.GONE
}
is TransferSpeed.Economy -> {
buttonRegular.setTextColor(context.getColor(R.color.dark_blue))
buttonRegular.setBackgroundResource(R.drawable.b_blue_square_stroke)
buttonEconomy.setTextColor(context.getColor(R.color.white))
buttonEconomy.setBackgroundResource(R.drawable.b_half_left_blue)
buttonPriority.setTextColor(context.getColor(R.color.dark_blue))
buttonPriority.setBackgroundResource(R.drawable.b_half_right_blue_stroke)
labelFeeDescription.text = when {
feeOption.currencyCode.run {
isEthereum() || isErc20()
} -> ethFeeEstimateString(context, feeOption.targetTime)
else -> context.getString(R.string.FeeSelector_estimatedDeliver)
.format(context.getString(R.string.FeeSelector_economyTime))
}
labelFeeWarning.visibility = View.VISIBLE
}
is TransferSpeed.Priority -> {
buttonRegular.setTextColor(context.getColor(R.color.dark_blue))
buttonRegular.setBackgroundResource(R.drawable.b_blue_square_stroke)
buttonEconomy.setTextColor(context.getColor(R.color.dark_blue))
buttonEconomy.setBackgroundResource(R.drawable.b_half_left_blue_stroke)
buttonPriority.setTextColor(context.getColor(R.color.white))
buttonPriority.setBackgroundResource(R.drawable.b_half_right_blue)
labelFeeDescription.text = when {
feeOption.currencyCode.run {
isEthereum() || isErc20()
} -> ethFeeEstimateString(context, feeOption.targetTime)
else -> context.getString(R.string.FeeSelector_estimatedDeliver)
.format(context.getString(R.string.FeeSelector_priorityTime))
}
labelFeeWarning.visibility = View.GONE
}
}
}
}
private fun ethFeeEstimateString(context: Context, time: Long): String {
val minutes = TimeUnit.MILLISECONDS.toMinutes(time) + FEE_TIME_PADDING
return context.getString(R.string.FeeSelector_estimatedDeliver)
.format(context.getString(R.string.FeeSelector_lessThanMinutes, minutes))
}
}
fun String.formatFiatForInputUi(currencyCode: String): String {
// Ensure decimal displayed when string has not fraction digits
val forceSeparator = contains('.')
// Ensure all fraction digits are displayed, even if they are all zero
val minFractionDigits = substringAfter('.', "").count()
val amount = toBigDecimalOrNull()
val currencyFormat = NumberFormat.getCurrencyInstance(Locale.getDefault()) as DecimalFormat
val decimalFormatSymbols = currencyFormat.decimalFormatSymbols
currencyFormat.isGroupingUsed = true
currencyFormat.roundingMode = BRConstants.ROUNDING_MODE
currencyFormat.isDecimalSeparatorAlwaysShown = forceSeparator
try {
val currency = java.util.Currency.getInstance(currencyCode)
val symbol = currency.symbol
decimalFormatSymbols.currencySymbol = symbol
currencyFormat.decimalFormatSymbols = decimalFormatSymbols
currencyFormat.negativePrefix = "-$symbol"
currencyFormat.maximumFractionDigits = MAX_DIGITS
currencyFormat.minimumFractionDigits = minFractionDigits
} catch (e: IllegalArgumentException) {
logError("Illegal Currency code: $currencyCode")
}
return currencyFormat.format(amount)
}
| mit | 54fc23e44d339c1d180cee914e4bf3de | 41.995334 | 131 | 0.590212 | 5.45286 | false | false | false | false |
fossasia/rp15 | app/src/main/java/org/fossasia/openevent/general/favorite/FavoriteEventsViewModel.kt | 1 | 3294 | package org.fossasia.openevent.general.favorite
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.rxkotlin.plusAssign
import org.fossasia.openevent.general.utils.extensions.withDefaultSchedulers
import org.fossasia.openevent.general.R
import org.fossasia.openevent.general.auth.AuthHolder
import org.fossasia.openevent.general.common.SingleLiveEvent
import org.fossasia.openevent.general.data.Resource
import org.fossasia.openevent.general.event.Event
import org.fossasia.openevent.general.event.EventId
import org.fossasia.openevent.general.event.EventService
import timber.log.Timber
class FavoriteEventsViewModel(
private val eventService: EventService,
private val resource: Resource,
private val authHolder: AuthHolder
) : ViewModel() {
private val compositeDisposable = CompositeDisposable()
private val mutableProgress = MutableLiveData<Boolean>()
val progress: LiveData<Boolean> = mutableProgress
private val mutableMessage = SingleLiveEvent<String>()
val message: LiveData<String> = mutableMessage
private val mutableEvents = MutableLiveData<List<Event>>()
val events: LiveData<List<Event>> = mutableEvents
fun isLoggedIn() = authHolder.isLoggedIn()
fun loadFavoriteEvents() {
compositeDisposable +=
eventService.getFavoriteEvents()
.withDefaultSchedulers()
.subscribe({
mutableEvents.value = it
mutableProgress.value = false
}, {
Timber.e(it, "Error fetching favorite events")
mutableMessage.value = resource.getString(R.string.fetch_favorite_events_error_message)
})
}
fun setFavorite(event: Event, favorite: Boolean) {
if (favorite) {
addFavorite(event)
} else {
removeFavorite(event)
}
}
private fun addFavorite(event: Event) {
val favoriteEvent = FavoriteEvent(authHolder.getId(), EventId(event.id))
compositeDisposable += eventService.addFavorite(favoriteEvent, event)
.withDefaultSchedulers()
.subscribe({
mutableMessage.value = resource.getString(R.string.add_event_to_shortlist_message)
}, {
mutableMessage.value = resource.getString(R.string.out_bad_try_again)
Timber.d(it, "Fail on adding like for event ID ${event.id}")
})
}
private fun removeFavorite(event: Event) {
val favoriteEventId = event.favoriteEventId ?: return
val favoriteEvent = FavoriteEvent(favoriteEventId, EventId(event.id))
compositeDisposable += eventService.removeFavorite(favoriteEvent, event)
.withDefaultSchedulers()
.subscribe({
mutableMessage.value = resource.getString(R.string.remove_event_from_shortlist_message)
}, {
mutableMessage.value = resource.getString(R.string.out_bad_try_again)
Timber.d(it, "Fail on removing like for event ID ${event.id}")
})
}
override fun onCleared() {
super.onCleared()
compositeDisposable.clear()
}
}
| apache-2.0 | 09171bf4f3abefe36a86a1d4d76fd617 | 37.302326 | 107 | 0.682757 | 4.975831 | false | false | false | false |
seventhroot/elysium | bukkit/rpk-chat-bukkit/src/main/kotlin/com/rpkit/chat/bukkit/chatchannel/directed/RadiusFilterComponent.kt | 1 | 3358 | /*
* Copyright 2020 Ren Binden
*
* 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.rpkit.chat.bukkit.chatchannel.directed
import com.rpkit.chat.bukkit.chatchannel.pipeline.DirectedChatChannelPipelineComponent
import com.rpkit.chat.bukkit.context.DirectedChatChannelMessageContext
import org.bukkit.Bukkit
import org.bukkit.configuration.serialization.ConfigurationSerializable
import org.bukkit.configuration.serialization.SerializableAs
/**
* Radius filter component.
* Filters out messages if they are beyond the radius of the channel.
*/
@SerializableAs("RadiusFilterComponent")
class RadiusFilterComponent: DirectedChatChannelPipelineComponent, ConfigurationSerializable {
override fun process(context: DirectedChatChannelMessageContext): DirectedChatChannelMessageContext {
if (context.isCancelled) return context
val senderMinecraftProfile = context.senderMinecraftProfile
if (senderMinecraftProfile != null) {
val senderBukkitPlayer = Bukkit.getOfflinePlayer(senderMinecraftProfile.minecraftUUID)
val receiverBukkitPlayer = Bukkit.getOfflinePlayer(context.receiverMinecraftProfile.minecraftUUID)
val senderBukkitOnlinePlayer = senderBukkitPlayer.player
val receiverBukkitOnlinePlayer = receiverBukkitPlayer.player
if (senderBukkitOnlinePlayer != null && receiverBukkitOnlinePlayer != null) {
val senderLocation = senderBukkitOnlinePlayer.location
val receiverLocation = receiverBukkitOnlinePlayer.location
if (senderLocation.world == receiverLocation.world) {
if (senderLocation.distanceSquared(receiverLocation) > context.chatChannel.radius * context.chatChannel.radius) {
context.isCancelled = true
}
// If there is a radius filter in place, the only situation where the message is not cancelled
// is both players having a Minecraft player online AND the players being in the same world,
// within the chat channel's radius.
// If any of these conditions fail, the message is cancelled, otherwise it maintains the same
// cancelled state as before reaching the component.
} else {
context.isCancelled = true
}
} else {
context.isCancelled = true
}
} else {
context.isCancelled = true
}
return context
}
override fun serialize(): MutableMap<String, Any> {
return mutableMapOf()
}
companion object {
@JvmStatic
fun deserialize(serialized: MutableMap<String, Any>): RadiusFilterComponent {
return RadiusFilterComponent()
}
}
} | apache-2.0 | a79cd38a5b8ead98812b42f3f056645f | 43.786667 | 133 | 0.689994 | 5.615385 | false | true | false | false |
badoualy/kotlogram | mtproto/src/main/kotlin/com/github/badoualy/telegram/mtproto/tl/auth/ServerDhFailure.kt | 1 | 1280 | package com.github.badoualy.telegram.mtproto.tl.auth
import com.github.badoualy.telegram.tl.StreamUtils.readBytes
import com.github.badoualy.telegram.tl.StreamUtils.writeByteArray
import com.github.badoualy.telegram.tl.TLContext
import java.io.IOException
import java.io.InputStream
import java.io.OutputStream
class ServerDhFailure @JvmOverloads constructor(var nonce: ByteArray = ByteArray(0), var serverNonce: ByteArray = ByteArray(0),
var newNonceHash: ByteArray = ByteArray(0)) : ServerDhParams() {
override fun getConstructorId(): Int {
return CONSTRUCTOR_ID
}
@Throws(IOException::class)
override fun serializeBody(stream: OutputStream) {
writeByteArray(nonce, stream)
writeByteArray(serverNonce, stream)
writeByteArray(newNonceHash, stream)
}
@Throws(IOException::class)
override fun deserializeBody(stream: InputStream, context: TLContext) {
nonce = readBytes(16, stream)
serverNonce = readBytes(16, stream)
newNonceHash = readBytes(16, stream)
}
override fun toString(): String {
return "server_DH_params_fail#79cb045d"
}
companion object {
@JvmField
val CONSTRUCTOR_ID = 2043348061
}
}
| mit | e4c3918eab8bf5b45f96098a2a70938c | 31.820513 | 127 | 0.692188 | 4.368601 | false | false | false | false |
EMResearch/EvoMaster | core/src/main/kotlin/org/evomaster/core/problem/external/service/rpc/RPCExternalServiceAction.kt | 1 | 2586 | package org.evomaster.core.problem.external.service.rpc
import org.evomaster.core.problem.api.service.param.Param
import org.evomaster.core.problem.external.service.ApiExternalServiceAction
import org.evomaster.core.problem.external.service.rpc.parm.RPCResponseParam
import org.evomaster.core.search.gene.Gene
class RPCExternalServiceAction(
/**
* the interface name
*/
val interfaceName: String,
/**
* the method name
*/
val functionName: String,
/**
* descriptive info for the external service if needed
* eg, app key for identifying the external service
*/
val descriptiveInfo : String? = null,
/**
* response might be decided based on requests
* such as x > 1 return A, otherwise return B (could exist in the seeded test)
* this property provides an identifier for such rules (eg, x>1) if exists.
* the rule is provided by the user (eg, with customization) and it is immutable.
*
* note that null represents that it accepts any request
*/
val requestRuleIdentifier: String?,
responseParam: RPCResponseParam,
active : Boolean = false,
used : Boolean = false
) : ApiExternalServiceAction(responseParam, active, used) {
companion object{
private const val RPC_EX_NAME_SEPARATOR =":::"
fun getRPCExternalServiceActionName(interfaceName: String, functionName: String, requestRuleIdentifier: String?, responseClassType: String) = "$interfaceName$RPC_EX_NAME_SEPARATOR$functionName$RPC_EX_NAME_SEPARATOR${requestRuleIdentifier?:"ANY"}$RPC_EX_NAME_SEPARATOR$responseClassType"
}
override fun getName(): String {
return getRPCExternalServiceActionName(interfaceName, functionName, requestRuleIdentifier, (response as RPCResponseParam).className)
}
override fun seeTopGenes(): List<out Gene> {
return response.genes
}
override fun shouldCountForFitnessEvaluations(): Boolean {
return false
}
override fun copyContent(): RPCExternalServiceAction {
return RPCExternalServiceAction(interfaceName, functionName, descriptiveInfo, requestRuleIdentifier, response.copy() as RPCResponseParam, active, used)
}
/**
* @return a copy of this and release its restricted request identifier
*/
fun getUnrestrictedRPCExternalServiceAction(): RPCExternalServiceAction{
return RPCExternalServiceAction(interfaceName, functionName, descriptiveInfo, null, response.copy() as RPCResponseParam)
}
fun addUpdateForParam(param: Param){
addChild(param)
}
} | lgpl-3.0 | 58d091b1bcbda402657b0ce05889432d | 35.43662 | 294 | 0.721964 | 4.815642 | false | false | false | false |
juanavelez/crabzilla | crabzilla-web-pg-client/src/main/java/io/github/crabzilla/webpgc/UowHandlerVerticle.kt | 1 | 1037 | package io.github.crabzilla.webpgc
import io.github.crabzilla.framework.Entity
import io.github.crabzilla.framework.EntityJsonAware
import io.vertx.core.AbstractVerticle
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import java.lang.management.ManagementFactory
abstract class UowHandlerVerticle : AbstractVerticle() {
companion object {
val log: Logger = LoggerFactory.getLogger(UowHandlerVerticle::class.java)
val processId: String = ManagementFactory.getRuntimeMXBean().name // TODO does this work with AOT?
}
private val jsonFunctions: MutableMap<String, EntityJsonAware<out Entity>> = mutableMapOf()
override fun start() {
val implClazz = this::class.java.name
vertx.eventBus().consumer<String>(implClazz) { msg ->
if (log.isTraceEnabled) log.trace("received " + msg.body())
msg.reply("$implClazz is already running here: $processId")
}
}
fun addEntityJsonAware(entityName: String, jsonAware: EntityJsonAware<out Entity>) {
jsonFunctions[entityName] = jsonAware
}
}
| apache-2.0 | 0e0d2f6fdef45d24f665afe5b024dc34 | 32.451613 | 102 | 0.757956 | 4.164659 | false | false | false | false |
dmitryustimov/weather-kotlin | app/src/main/java/ru/ustimov/weather/ui/MainActivity.kt | 1 | 2824 | package ru.ustimov.weather.ui
import android.os.Bundle
import android.support.v4.app.FragmentTransaction
import android.support.v7.app.AppCompatActivity
import android.view.MenuItem
import kotlinx.android.extensions.CacheImplementation
import kotlinx.android.extensions.ContainerOptions
import kotlinx.android.synthetic.main.activity_main.*
import ru.ustimov.weather.R
import ru.ustimov.weather.ui.favorites.FavoritesFragment
import ru.ustimov.weather.ui.forecast.ForecastFragment
import ru.ustimov.weather.ui.search.SearchFragment
@ContainerOptions(CacheImplementation.SPARSE_ARRAY)
class MainActivity : AppCompatActivity(), FavoritesFragment.Callbacks {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
bottomNavigationBar.setOnNavigationItemSelectedListener(this::onBottomNavigationItemSelected)
bottomNavigationBar.setOnNavigationItemReselectedListener({})
if (savedInstanceState == null) {
bottomNavigationBar.selectedItemId = R.id.action_my_location
showForecast()
}
}
private fun onBottomNavigationItemSelected(menuItem: MenuItem): Boolean =
when (menuItem.itemId) {
R.id.action_my_location -> {
showForecast()
true
}
R.id.action_favorites -> {
showFavorites()
true
}
R.id.action_search -> {
showSearch()
true
}
R.id.action_settings -> {
showNotImplemented()
true
}
else -> false
}
private fun showForecast() = supportFragmentManager.beginTransaction()
.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE)
.replace(R.id.content, ForecastFragment.create())
.commit()
private fun showFavorites() = supportFragmentManager.beginTransaction()
.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE)
.replace(R.id.content, FavoritesFragment.create())
.commit()
private fun showSearch() = supportFragmentManager.beginTransaction()
.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE)
.replace(R.id.content, SearchFragment.create())
.commit()
private fun showNotImplemented() = supportFragmentManager.beginTransaction()
.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE)
.replace(R.id.content, NotImplementedFragment.create())
.commit()
override fun onFindCityClick() {
bottomNavigationBar.selectedItemId = R.id.action_search
}
} | apache-2.0 | 2dbad9174e2766df1261ab457880534d | 36.666667 | 101 | 0.65262 | 5.399618 | false | false | false | false |
vjache/klips | src/test/java/org/klips/engine/Model.kt | 1 | 7273 | @file:Suppress("unused")
package org.klips.engine
import org.klips.dsl.Facet
import org.klips.dsl.Facet.ConstFacet
import org.klips.dsl.Facet.IntFacet
import org.klips.dsl.Fact
import org.klips.dsl.facet
import org.klips.dsl.ref
import java.util.concurrent.atomic.AtomicInteger
/////////////////////////////////////////////////////////////////////////////////
data class CellId(val id: Int) : Comparable<CellId> {
override fun compareTo(other: CellId): Int = id.compareTo(other.id)
}
data class ActorId(val id: Int) : Comparable<ActorId> {
companion object {
val clock = AtomicInteger()
var last : ActorId? = null
}
constructor() : this(clock.andIncrement) {
last = this
}
override fun compareTo(other: ActorId): Int = id.compareTo(other.id)
}
data class PlayerId(val id: Int) : Comparable<PlayerId> {
override fun compareTo(other: PlayerId): Int = id.compareTo(other.id)
}
/////////////////////////////////////////////////////////////////////////////////
enum class ActorKind {
Aim,
Worker,
Solar,
Guard,
Comm
}
enum class PlayerColor {
Green,
Blue,
Red,
Yellow
}
enum class LandKind {
SandDesert,
DirtDesert,
Mountain,
Water
}
enum class ResourceType {
Mushroom,
Crystal,
Plant
}
enum class State {
OnMarch,
Deployed
}
data class Level(val value: Float, val maxValue: Float) : Comparable<Level> {
override fun compareTo(other: Level) = value.compareTo(other.value)
constructor(value: Float) : this(value, 100f)
constructor() : this(100f, 100f)
fun inc(dL: Float): Level {
val newValue = value + dL
return when {
newValue < 0f -> Level(0f, maxValue)
newValue > maxValue -> Level(maxValue, maxValue)
else -> Level(newValue, maxValue)
}
}
}
/////////////////////////////////////////////////////////////////////////////////
class Turn(val pid: Facet<PlayerId> = ref()) : Fact() {
constructor(pid:PlayerId) : this(pid.facet)
}
class Adjacent(val cid1: Facet<CellId> = ref(), val cid2: Facet<CellId> = ref()) : Fact() {
constructor(cid1: Int, cid2: Int) :
this(ConstFacet(CellId(cid1)), ConstFacet(CellId(cid2)))
}
class At(val aid: Facet<ActorId> = ref(), val cid: Facet<CellId> = ref()) : Fact() {
constructor(aid: Int, cid: Int) :
this(ConstFacet(ActorId(aid)), ConstFacet(CellId(cid)))
}
class CommField(val aid: Facet<ActorId> = ref(), val cid: Facet<CellId> = ref()) : Fact() {
constructor(aid: Int, cid: Int) :
this(ConstFacet(ActorId(aid)), ConstFacet(CellId(cid)))
}
class Land(val cid: Facet<CellId> = ref(), val type: Facet<LandKind> = ref()) : Fact() {
constructor(cid: Int, type: LandKind) :
this(ConstFacet(CellId(cid)), ConstFacet(type))
}
class Resource(val cid: Facet<CellId> = ref(),
val type: Facet<ResourceType> = ref(),
val amount: Facet<Int> = ref()) : Fact() {
constructor(cid: Int,
type: ResourceType,
amount: Int) :
this(ConstFacet(CellId(cid)), ConstFacet(type), IntFacet(amount))
}
class CargoBay(val aid: Facet<ActorId> = ref(),
val type: Facet<ResourceType> = ref(),
val capacity: Facet<Level> = ref()): Fact()
class Actor(val aid: Facet<ActorId> = ref(),
val pid: Facet<PlayerId> = ref(),
val type: Facet<ActorKind> = ref(),
val energy: Facet<Level> = ref(),
val health: Facet<Level> = ref(),
val state: Facet<State> = ref()) : Fact() {
constructor(id: Int, pid: Int, type: ActorKind) :
this(id, pid, type, 100f, 100f, State.OnMarch)
constructor(aid: ActorId, pid: PlayerId, type: ActorKind) :
this(aid.facet, pid.facet, type.facet, Level(100f).facet, Level(100f).facet, State.OnMarch.facet)
constructor(aid: ActorId, pid: PlayerId, type: ActorKind, state:State) :
this(aid.facet, pid.facet, type.facet, Level(100f).facet, Level(100f).facet, state.facet)
constructor(id: Int, pid: Int, type: ActorKind, energy: Float, health: Float, state: State) :
this(ConstFacet(ActorId(id)),
ConstFacet(PlayerId(pid)),
ConstFacet(type),
ConstFacet(Level(energy)),
ConstFacet(Level(health)),
ConstFacet(state))
}
class Player(val pid: Facet<PlayerId> = ref(), val color: Facet<PlayerColor> = ref()) :
Fact() {
constructor(pid: Int, color: PlayerColor) :
this(ConstFacet(PlayerId(pid)), ConstFacet(color))
}
/////////////////////////////////////////////////////////////////////////////////
// UI events
/////////////////////////////////////////////////////////////////////////////////
class TapCell(val cid: Facet<CellId> = ref()) :
Fact() {
constructor(cid: Int) :
this(ConstFacet(CellId(cid)))
}
class TapActor(val aid: Facet<ActorId> = ref()) :
Fact() {
constructor(aid: Int) :
this(ConstFacet(ActorId(aid)))
}
class ActorSelected(val aid: Facet<ActorId> = ref()) :
Fact() {
constructor(aid: Int) :
this(ConstFacet(ActorId(aid)))
}
/////////////////////////////////////////////////////////////////////////////////
// Command events
/////////////////////////////////////////////////////////////////////////////////
open class UnaryCommand(
val actingAgent: Facet<ActorId> = ref()) : Fact()
open class AgentToAgentCommand(
actingAgent: Facet<ActorId> = ref(),
val passiveAgentId: Facet<ActorId> = ref()) : UnaryCommand(actingAgent)
class MoveCommand(
actingAgent: Facet<ActorId> = ref(),
val targetCell: Facet<CellId> = ref()) :
UnaryCommand(actingAgent)
class CreateAgentCommand(
actingAgent : Facet<ActorId> = ref(),
val cellId : Facet<CellId> = ref(),
val agentType : Facet<ActorKind> = ref()) :
UnaryCommand( actingAgent ){
constructor(aid:ActorId, cid:CellId, type:ActorKind):this(aid.facet, cid.facet, type.facet)
}
class DeployCommand(
actingAgent : Facet<ActorId> = ref()) :
UnaryCommand(actingAgent)
class UndeployCommand(
actingAgent : Facet<ActorId> = ref()) :
UnaryCommand(actingAgent)
class AttackCommand(
actingAgent: Facet<ActorId> = ref(),
passiveAgentId: Facet<ActorId> = ref()) :
AgentToAgentCommand(
actingAgent,
passiveAgentId)
class ChargeCommand(
actingAgent: Facet<ActorId> = ref(),
passiveAgentId: Facet<ActorId> = ref()) :
AgentToAgentCommand(
actingAgent,
passiveAgentId)
class FeedAimCommand(
actingAgent: Facet<ActorId> = ref(),
passiveAgentId: Facet<ActorId> = ref()) :
AgentToAgentCommand(
actingAgent,
passiveAgentId)
class RepairCommand(
actingAgent: Facet<ActorId> = ref(),
passiveAgentId: Facet<ActorId> = ref()) :
AgentToAgentCommand(
actingAgent,
passiveAgentId)
class ScrapCommand(
actingAgent: Facet<ActorId> = ref(),
passiveAgentId: Facet<ActorId> = ref()) :
AgentToAgentCommand(
actingAgent,
passiveAgentId) | apache-2.0 | da633df7b3707208bdee532a1b3ed855 | 28.934156 | 101 | 0.569229 | 4.165521 | false | false | false | false |
vjache/klips | src/test/java/org/klips/engine/rete/ReteTestGraphBuilder.kt | 1 | 3541 | package org.klips.engine.rete
import org.klips.dsl.Facet.FacetRef
import org.klips.dsl.Fact
import org.klips.engine.*
import org.klips.engine.rete.builder.RuleClause
import org.klips.engine.rete.mem.StrategyOneMem
import org.klips.engine.rete.builder.Trigger
import org.jgrapht.DirectedGraph
import org.jgrapht.graph.SimpleDirectedGraph
import org.klips.dsl.ActivationFilter
import org.klips.engine.util.Log
class ReteTestGraphBuilder {
val pattern1 = mutableSetOf<Fact>().apply {
add(Player(ref("pid"), ref("color")))
add(Actor(ref("aid"), ref("pid"), ref("kind"), ref("nrgy"), ref("hlth"), ref("state")))
}
val pattern2 = mutableSetOf<Fact>().apply {
add(Actor(ref("aid"), ref("pid"), ref("kind"), ref("nrgy"), ref("hlth"), ref("state")) )
add(Land(ref("cid"), ref("land")))
add(At(ref("aid"), ref("cid")))
}
val pattern3 = mutableSetOf<Fact>().apply {
add(Actor(ref("aid"), ref("pid"), ref("kind"), ref("nrgy"), ref("hlth"), ref("state")))
add(At(ref("aid"), ref("cid")))
add(Resource(ref("cid"), ref("type"), ref("amount")))
}
val pattern4 = mutableSetOf<Fact>().apply {
add(Actor(ref("aid"), ref("pid"), ref("kind"), ref("nrgy"), ref("hlth"), ref("state")))
add(At(ref("aid"), ref("cid")))
add(Actor(ref("aid1"), ref("pid1"), ref("land1"), ref("nrgy1"), ref("hlth1"), ref("state1")))
add(At(ref("aid1"), ref("cid1")))
add(Adjacent(ref("cid"), ref("cid1")))
}
val stdTrigger = object : Trigger {
override fun checkGuard(cache: MutableMap<Any, Any>, solution: Modification<Binding>) = true
override fun filter() = ActivationFilter.AssertOnly
override fun fire(cache: MutableMap<Any, Any>,solution: Modification<Binding>, addEffect: (Modification<Fact>) -> Unit) {
println(solution)
}
}
fun create(): DirectedGraph<Node, MyEdge<Node, Node, String>> {
val g = SimpleDirectedGraph<Node, MyEdge<Node, Node, String>> {
n1, n2 ->
when (n1) {
is BetaNode -> {
MyEdge(n1, n2, when (n2) {
n1.left -> "left"
n1.right -> "right"
else -> throw IllegalArgumentException()
})
}
is ProxyNode -> {
MyEdge(n1, n2, "renames")
}
else -> throw IllegalArgumentException()
}
}
val allNodes = StrategyOneMem(mutableListOf<RuleClause>().apply {
add(RuleClause(pattern4, stdTrigger))
add(RuleClause(pattern3, stdTrigger))
add(RuleClause(pattern2, stdTrigger))
add(RuleClause(pattern1, stdTrigger))
// add(Pair(pattern4, stdTrigger))
}).allNodes
fun addRecursive(n:Node){
if (n !in g.vertexSet()) g.addVertex(n)
when (n)
{
is BetaNode -> {
addRecursive(n.left)
addRecursive(n.right)
g.addEdge(n, n.left)
g.addEdge(n, n.right)
}
is ProxyNode ->
{
addRecursive(n.node)
g.addEdge(n, n.node)
}
}
}
allNodes.forEach { n ->
addRecursive(n)
}
return g
}
fun <T : Comparable<T>> ref(id:String) = FacetRef<T>(id)
} | apache-2.0 | 7dc7e4e414c683b5d93236014465f442 | 31.796296 | 129 | 0.526123 | 4.065442 | false | false | false | false |
jayrave/falkon | falkon-dao/src/main/kotlin/com/jayrave/falkon/dao/query/QueryBuilderExtn.kt | 1 | 789 | package com.jayrave.falkon.dao.query
import com.jayrave.falkon.mapper.ReadOnlyColumnOfTable
import java.sql.SQLException
/**
* A convenience function to select multiple columns in one go
*
* @param [columns] to be selected
* @param [aliaser] used to compute the alias to be used for the selected columns
*
* @throws [SQLException] if [columns] is empty
*/
fun <T : Any, Z : AdderOrEnder<T, Z>> AdderOrEnder<T, Z>.select(
columns: Iterable<ReadOnlyColumnOfTable<T, *>>,
aliaser: ((ReadOnlyColumnOfTable<T, *>) -> String)? = null): Z {
var result: Z? = null
columns.forEach { column ->
result = select(column, aliaser?.invoke(column))
}
if (result == null) {
throw SQLException("Columns can't be empty")
}
return result!!
} | apache-2.0 | d9abcb677f8fdd9983786becf16e2f86 | 27.214286 | 81 | 0.664132 | 3.704225 | false | false | false | false |
joseph-roque/BowlingCompanion | app/src/main/java/ca/josephroque/bowlingcompanion/statistics/impl/firstball/LeftSplitsSparedStatistic.kt | 1 | 1618 | package ca.josephroque.bowlingcompanion.statistics.impl.firstball
import android.content.SharedPreferences
import android.os.Parcel
import ca.josephroque.bowlingcompanion.R
import ca.josephroque.bowlingcompanion.common.interfaces.parcelableCreator
import ca.josephroque.bowlingcompanion.games.lane.Deck
import ca.josephroque.bowlingcompanion.games.lane.arePinsCleared
import ca.josephroque.bowlingcompanion.games.lane.isLeftSplit
import ca.josephroque.bowlingcompanion.settings.Settings
/**
* Copyright (C) 2018 Joseph Roque
*
* Percentage of possible left splits which the user successfully spared.
*/
class LeftSplitsSparedStatistic(numerator: Int = 0, denominator: Int = 0) : SecondBallStatistic(numerator, denominator) {
companion object {
@Suppress("unused")
@JvmField val CREATOR = parcelableCreator(::LeftSplitsSparedStatistic)
const val Id = R.string.statistic_left_splits_spared
}
override val titleId = Id
override val id = Id.toLong()
override val secondaryGraphDataLabelId = R.string.statistic_total_left_splits
private var countS2asS: Boolean = Settings.BooleanSetting.CountS2AsS.default
// MARK: Statistic
override fun isModifiedByFirstBall(deck: Deck) = deck.isLeftSplit(countS2asS)
override fun isModifiedBySecondBall(deck: Deck) = deck.arePinsCleared
override fun updatePreferences(preferences: SharedPreferences) {
countS2asS = Settings.BooleanSetting.CountS2AsS.getValue(preferences)
}
// MARK: Constructors
private constructor(p: Parcel): this(numerator = p.readInt(), denominator = p.readInt())
}
| mit | b0258105a73dbe8390210650d4f861c2 | 34.955556 | 121 | 0.775649 | 4.481994 | false | false | false | false |
AlmasB/FXGL | fxgl-samples/src/main/kotlin/sandbox/view/DestructibleApp.kt | 1 | 4333 | /*
* FXGL - JavaFX Game Library. The MIT License (MIT).
* Copyright (c) AlmasB ([email protected]).
* See LICENSE for details.
*/
package sandbox.view
import com.almasb.fxgl.app.GameApplication
import com.almasb.fxgl.app.GameSettings
import com.almasb.fxgl.core.math.FXGLMath
import com.almasb.fxgl.dsl.*
import com.almasb.fxgl.dsl.components.ExpireCleanComponent
import com.almasb.fxgl.dsl.components.ProjectileComponent
import com.almasb.fxgl.entity.Entity
import com.almasb.fxgl.physics.PhysicsComponent
import com.almasb.fxgl.physics.box2d.dynamics.BodyDef
import com.almasb.fxgl.physics.box2d.dynamics.BodyType
import com.almasb.fxgl.physics.box2d.dynamics.FixtureDef
import com.almasb.fxgl.texture.Texture
import javafx.geometry.Point2D
import javafx.geometry.Rectangle2D
import javafx.scene.input.KeyCode
import javafx.scene.paint.Color
import javafx.util.Duration
/**
*
* @author Almas Baimagambetov ([email protected])
*/
class DestructibleApp : GameApplication() {
private enum class Type {
PROJ, BRICK, SMALL
}
override fun initSettings(settings: GameSettings) {
settings.setHeightFromRatio(16/9.0)
}
override fun initInput() {
onKeyDown(KeyCode.F) {
println(getGameWorld().entitiesCopy.size)
}
onKeyDown(KeyCode.G) {
shoot()
}
}
private fun shoot() {
val physics = PhysicsComponent()
physics.setBodyType(BodyType.DYNAMIC)
physics.setOnPhysicsInitialized {
physics.linearVelocity = Point2D(1.0, 0.0).multiply(1750.0)
}
entityBuilder()
.type(Type.PROJ)
.at(getInput().mousePositionWorld)
.viewWithBBox(texture("rocket.png", 15.0 * 2, 4.0 * 2))
//.with(ProjectileComponent(Point2D(1.0, 0.0), 1400.0))
.with(physics)
.with(ExpireCleanComponent(Duration.seconds(1.0)))
.collidable()
.buildAndAttach()
}
override fun initGame() {
getGameScene().setBackgroundColor(Color.BLACK)
run({ shoot() }, Duration.seconds(0.05))
for (y in 0..6) {
for (x in 8..11) {
getGameWorld().addEntity(makeBrick(x * 64.0, y * 64.0))
}
}
entityBuilder().buildScreenBoundsAndAttach(20.0)
getPhysicsWorld().setGravity(0.0, 10.0 * getSettings().pixelsPerMeter)
onCollisionBegin(Type.PROJ, Type.BRICK) { bullet, brick ->
bullet.removeFromWorld()
destroy(brick)
}
onCollisionBegin(Type.PROJ, Type.SMALL) { bullet, brick ->
bullet.removeFromWorld()
brick.removeFromWorld()
}
}
private fun destroy(e: Entity) {
val texture = e.viewComponent.children[0] as Texture
val size = 8.0
val rects = AASubdivision.divide(Rectangle2D(0.0, 0.0, 64.0, 64.0), 22, 8)
rects.forEach {
val sub = texture.subTexture(it)
val physics = PhysicsComponent()
physics.setBodyType(BodyType.DYNAMIC)
val bd = BodyDef().also {
it.isFixedRotation = false
it.type = if (FXGLMath.randomBoolean(0.75)) BodyType.DYNAMIC else BodyType.STATIC
}
physics.setFixtureDef(FixtureDef().density(0.05f).restitution(0.05f))
physics.setBodyDef(bd)
physics.setOnPhysicsInitialized {
physics.linearVelocity = FXGLMath.randomPoint2D().multiply(1000.0)
}
entityBuilder()
.at(e.position.add(it.minX, it.minY))
.type(Type.SMALL)
.viewWithBBox(sub)
.with(physics)
.collidable()
.buildAndAttach()
}
e.removeFromWorld()
}
private fun makeBrick(x: Double, y: Double): Entity {
return entityBuilder()
.at(x, y)
.type(Type.BRICK)
.viewWithBBox("brick.png")
.with(PhysicsComponent())
.collidable()
.build()
}
companion object {
@JvmStatic
fun main(args: Array<String>) {
launch(DestructibleApp::class.java, args)
}
}
} | mit | b4dc6d6402a98034dddf93c5371266ac | 28.482993 | 97 | 0.591738 | 4.134542 | false | false | false | false |
DimaKoz/meat-grinder | appKotlin/src/main/java/com/kozhevin/rootchecks/ui/ResultItemHolder.kt | 1 | 1291 | package com.kozhevin.rootchecks.ui
import android.view.View
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.kozhevin.rootchecks.R
import com.kozhevin.rootchecks.data.CheckInfo
import com.kozhevin.rootchecks.util.ChecksHelper
import com.kozhevin.rootchecks.util.ChecksHelper.getFound
import com.kozhevin.rootchecks.util.ChecksHelper.getNonCheck
import com.kozhevin.rootchecks.util.ChecksHelper.getOk
class ResultItemHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
private val title: TextView = itemView.findViewById(R.id.item_check_description_text_view)
private val icon: ImageView = itemView.findViewById(R.id.item_check_icon_image_view)
private var mCheckInfo: CheckInfo? = null
fun onBind(checkInfo: CheckInfo) {
mCheckInfo = checkInfo
mCheckInfo?.let {
title.text = itemView.resources.getString(ChecksHelper.getCheckStringId(it.typeCheck))
when {
it.state == null -> icon.setImageBitmap(getNonCheck(itemView.context))
it.state === java.lang.Boolean.TRUE -> icon.setImageBitmap(getFound(itemView.context))
else -> icon.setImageBitmap(getOk(itemView.context))
}
}
}
}
| mit | 0191b7f370d33fdc922cbbc4901578f4 | 39.34375 | 102 | 0.738187 | 4.289037 | false | false | false | false |
industrial-data-space/trusted-connector | example-route-builder/src/main/kotlin/de/fhg/aisec/ids/ExampleIdscpServer.kt | 1 | 1701 | /*-
* ========================LICENSE_START=================================
* example-route-builder
* %%
* Copyright (C) 2021 Fraunhofer AISEC
* %%
* 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.
* =========================LICENSE_END==================================
*/
package de.fhg.aisec.ids
import org.apache.camel.RoutesBuilder
import org.apache.camel.builder.RouteBuilder
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
@Configuration
open class ExampleIdscpServer {
@Bean("serverSslContext")
open fun createSSLContext() = ExampleConnector.getSslContext()
@Bean
open fun server(): RoutesBuilder {
return object : RouteBuilder() {
override fun configure() {
from("idscp2server://0.0.0.0:29292?sslContextParameters=#serverSslContext")
.log("Server received: \${body} (Header: \${headers[idscp2-header]})")
.setBody().simple("PONG")
.setHeader("idscp2-header").simple("pong")
.log("Server response: \${body} (Header: \${headers[idscp2-header]})")
}
}
}
}
| apache-2.0 | 609846a349565000ca79f9fd77e5ce22 | 36.8 | 91 | 0.625514 | 4.45288 | false | true | false | false |
RP-Kit/RPKit | bukkit/rpk-chat-bukkit/src/main/kotlin/com/rpkit/chat/bukkit/chatchannel/format/part/SenderPrefixPart.kt | 1 | 3475 | /*
* Copyright 2022 Ren Binden
*
* 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.rpkit.chat.bukkit.chatchannel.format.part
import com.rpkit.chat.bukkit.RPKChatBukkit
import com.rpkit.chat.bukkit.chatchannel.format.click.ClickAction
import com.rpkit.chat.bukkit.chatchannel.format.hover.HoverAction
import com.rpkit.chat.bukkit.context.DirectedPreFormatMessageContext
import com.rpkit.chat.bukkit.prefix.RPKPrefixService
import com.rpkit.core.service.Services
import com.rpkit.players.bukkit.profile.RPKProfile
import org.bukkit.Bukkit
import org.bukkit.configuration.serialization.ConfigurationSerializable
import org.bukkit.configuration.serialization.SerializableAs
import java.util.concurrent.CompletableFuture.supplyAsync
import java.util.logging.Level
@SerializableAs("SenderPrefixPart")
class SenderPrefixPart(
private val plugin: RPKChatBukkit,
font: String? = null,
color: String? = null,
isBold: Boolean? = null,
isItalic: Boolean? = null,
isUnderlined: Boolean? = null,
isStrikethrough: Boolean? = null,
isObfuscated: Boolean? = null,
insertion: String? = null,
hover: HoverAction? = null,
click: ClickAction? = null
) : GenericTextPart(
plugin,
font,
color,
isBold,
isItalic,
isUnderlined,
isStrikethrough,
isObfuscated,
insertion,
hover,
click
), ConfigurationSerializable {
override fun getText(context: DirectedPreFormatMessageContext) = supplyAsync {
val prefixService = Services[RPKPrefixService::class.java] ?: return@supplyAsync ""
val profile = context.senderProfile
if (profile is RPKProfile) {
return@supplyAsync prefixService.getPrefix(profile).join()
}
return@supplyAsync ""
}.exceptionally { exception ->
plugin.logger.log(Level.SEVERE, "Failed to get sender prefix", exception)
throw exception
}
override fun serialize() = mutableMapOf(
"font" to font,
"color" to color,
"bold" to isBold,
"italic" to isItalic,
"underlined" to isUnderlined,
"strikethrough" to isStrikethrough,
"obfuscated" to isObfuscated,
"insertion" to insertion,
"hover" to hover,
"click" to click
)
companion object {
@JvmStatic
fun deserialize(serialized: Map<String, Any>) = SenderPrefixPart(
Bukkit.getPluginManager().getPlugin("rpk-chat-bukkit") as RPKChatBukkit,
serialized["font"] as? String,
serialized["color"] as? String,
serialized["bold"] as? Boolean,
serialized["italic"] as? Boolean,
serialized["underlined"] as? Boolean,
serialized["strikethrough"] as? Boolean,
serialized["obfuscated"] as? Boolean,
serialized["insertion"] as? String,
serialized["hover"] as? HoverAction,
serialized["click"] as? ClickAction
)
}
} | apache-2.0 | 31ed235017e95112bae203efad9d6c0c | 33.76 | 91 | 0.688633 | 4.512987 | false | false | false | false |
DSilence/pylint-idea | src/main/kotlin/com/sleepymaniac/pylint/annotator/PyLintExternalAnnotator.kt | 1 | 7120 | package com.sleepymaniac.pylint.annotator
import com.intellij.lang.annotation.AnnotationHolder
import com.intellij.lang.annotation.ExternalAnnotator
import com.intellij.lang.annotation.HighlightSeverity
import com.intellij.openapi.components.PathMacroManager
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.editor.Document
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.util.SystemInfo
import com.intellij.openapi.util.text.StringUtil
import com.intellij.psi.PsiDocumentManager
import com.intellij.psi.PsiFile
import com.intellij.psi.util.PsiUtil
import com.sleepymaniac.pylint.PyLintInspectionType
import com.sleepymaniac.pylint.annotator.inspection.PyLintInspectionResult
import com.sleepymaniac.pylint.annotator.inspection.PyLintOutputResult
import com.sleepymaniac.pylint.annotator.inspection.PyLintResult
import com.sleepymaniac.pylint.annotator.inspection.PyLintStatisticsResult
import com.sleepymaniac.pylint.settings.PyLintSettings
import java.io.BufferedReader
import java.io.File
import java.io.InputStreamReader
import java.util.*
class PyLintExternalAnnotator : ExternalAnnotator<PyLintParameters, PyLintResult>(){
companion object {
val severityMapping = hashMapOf<PyLintInspectionType, HighlightSeverity>(
PyLintInspectionType.Refactor to HighlightSeverity.INFORMATION,
PyLintInspectionType.Convention to HighlightSeverity.WEAK_WARNING,
PyLintInspectionType.Warning to HighlightSeverity.WARNING,
PyLintInspectionType.Error to HighlightSeverity.ERROR,
PyLintInspectionType.Fatal to HighlightSeverity.ERROR
)
}
val logger = Logger.getInstance(PyLintExternalAnnotator::class.java.name)
override fun collectInformation(file: PsiFile): PyLintParameters? {
val settings = PyLintSettings.getInstance(file.project)
if(settings!!.isEnabled) {
val manager = PathMacroManager.getInstance(file.project)
val pyLintPath = manager.expandPath(settings.pyLintPath)
val workingDirectory = manager.expandPath(settings.pyLintWorkingDir)
return PyLintParameters(pyLintPath, file.name, workingDirectory)
}
return null
}
override fun collectInformation(file: PsiFile, editor: Editor, hasErrors: Boolean): PyLintParameters? {
return collectInformation(file)
}
override fun doAnnotate(collectedInfo: PyLintParameters?): PyLintResult? {
if(collectedInfo == null){
return null
}
val pyLintPath = collectedInfo.pylintPath
val workingDir = File(collectedInfo.workingDir)
val process = ProcessBuilder(formatWindowsParameters(pyLintPath), formatWindowsParameters(collectedInfo.messageTemplate), formatWindowsParameters(collectedInfo.filePath))
.directory(workingDir)
.redirectOutput(ProcessBuilder.Redirect.PIPE)
.redirectError(ProcessBuilder.Redirect.PIPE)
.start()
val stream = process.inputStream
val input = BufferedReader(InputStreamReader(stream))
try {
val inspectionResults = ArrayList<PyLintInspectionResult>()
var statisticsResult = PyLintStatisticsResult(0f, 10f)
val result = PyLintResult(inspectionResults, statisticsResult)
while (true){
val line = input.readLine() ?: break
val output = processLine(line)
when(output){
is PyLintInspectionResult -> inspectionResults.add(output)
is PyLintStatisticsResult -> result.statisticsResult = output
}
}
process.waitFor()
return result
}
catch (e : Exception){
process.destroyForcibly()
logger.error(e)
}
finally {
input.close()
stream.close()
}
return null
}
override fun apply(file: PsiFile, annotationResult: PyLintResult?, holder: AnnotationHolder) {
for (issue in annotationResult!!.inspectionResults){
val document = PsiDocumentManager.getInstance(file.project).getDocument(file)
createAnnotation(file, document!!, issue, holder)
}
}
private fun createAnnotation(file: PsiFile, document: Document, inspectionResult: PyLintInspectionResult, holder: AnnotationHolder){
val line = inspectionResult.line
val column = inspectionResult.column
if (line < 0 || line >= document.lineCount) {
return
}
val errorLineStartOffset = StringUtil.lineColToOffset(document.charsSequence, line, column)
if (errorLineStartOffset == -1) {
return
}
val lit = PsiUtil.getElementAtOffset(file, errorLineStartOffset)
holder.createAnnotation(severityMapping[inspectionResult.type]!!, lit.textRange, inspectionResult.message)
}
private fun formatWindowsParameters(parameter: String) : String{
//If windows
if(SystemInfo.isWindows) {
return "\"" + parameter + "\""
}
return parameter
}
private fun getMessageType(messageTypeString: String) : PyLintInspectionType{
when(messageTypeString) {
"R" -> return PyLintInspectionType.Refactor
"C" -> return PyLintInspectionType.Convention
"W" -> return PyLintInspectionType.Warning
"E" -> return PyLintInspectionType.Error
"F" -> return PyLintInspectionType.Fatal
}
throw IllegalArgumentException("Message type string is invalid or unrecognized")
}
private fun processLine(outputLine: String) : PyLintOutputResult? {
if(outputLine == "" || outputLine.startsWith("*") || outputLine.startsWith("------")){
return null
}
if(outputLine.startsWith("Your code has been rated at ")){
val rate = outputLine.removePrefix("Your code has been rated at ")
val nextSpaceIndex = rate.indexOf(' ')
val rateWithTotal = rate.subSequence(0, nextSpaceIndex)
val splitValues = rateWithTotal.split('/')
if(splitValues.size != 2){
logger.error("Invalid pylint string received => " + outputLine)
}
val currentRate = splitValues[0].toFloat()
val maxRate = splitValues[1].toFloat()
return PyLintStatisticsResult(currentRate, maxRate)
}
val parameters = outputLine.split(':')
if(parameters.count() != 7){
logger.error("Invalid pylint string received => " + outputLine)
}
val messageType = parameters[0]
val line = parameters[1].toInt()
val column = parameters[2].toInt()
val messageId = parameters[3]
val symbol = parameters[4]
val obj = parameters[5]
val message = parameters[6]
return PyLintInspectionResult(getMessageType(messageType), line, column, messageId, symbol, obj, message)
}
} | mit | 43fc6b43dba45fd6a88c52634ad16179 | 40.888235 | 178 | 0.67177 | 5.277984 | false | false | false | false |
zhengjiong/ZJ_KotlinStudy | src/main/kotlin/com/zj/example/kotlin/basicsknowledge/37.InnerClassExample内部类.kt | 1 | 1176 | package com.zj.example.kotlin.basicsknowledge
/**
* Created by zhengjiong
* date: 2017/9/21 21:26
*/
fun main(args: Array<String>) {
var outter = Outter()
//默认是静态内部类
var inner = Outter.Inner()
//Inner2是非静态内部类
var inner2 = Outter().Inner2()
}
class Outter {
val a: Int = 0
val b: Int = 0
/**
* kotlin中的内部类默认就是静态的, 相当于java中的static内部类
*/
class Inner {
fun print() {
//println(a) //这样是错误的,静态内部类没有持有外部类的引用!
}
}
/**
* 加了inner就非静态内部类,内部类是持有外部类的引用的
*/
inner class Inner2 {
val b: Int = 0
fun print() {
/**
* 完整的写法是这样
*/
println([email protected])
/**
* 如果没有名字冲突的情况下,可以直接用a,比如b就不能这样写
* 因为外部类和内部类都有一个b
*/
println(a)
println([email protected])
println([email protected])
}
}
} | mit | 32c66a3752ab5666a771e11ebe961d23 | 16.203704 | 50 | 0.487069 | 3.267606 | false | false | false | false |
j2ghz/tachiyomi-extensions | src/en/dynasty/src/eu/kanade/tachiyomi/extension/en/dynasty/DynastyDoujins.kt | 1 | 969 | package eu.kanade.tachiyomi.extension.en.dynasty
import eu.kanade.tachiyomi.network.GET
import eu.kanade.tachiyomi.source.model.FilterList
import eu.kanade.tachiyomi.source.model.SManga
import okhttp3.Request
import org.jsoup.nodes.Document
class DynastyDoujins : DynastyScans() {
override val name = "Dynasty-Doujins"
override fun popularMangaInitialUrl() = "$baseUrl/doujins?view=cover"
override fun searchMangaRequest(page: Int, query: String, filters: FilterList): Request {
return GET("$baseUrl/search?q=$query&classes%5B%5D=Doujin&sort=", headers)
}
override fun mangaDetailsParse(document: Document): SManga {
val manga = SManga.create()
super.mangaDetailsParse(document)
parseThumbnail(manga)
manga.author = ".."
manga.status = SManga.UNKNOWN
parseGenres(document, manga)
return manga
}
override fun chapterListSelector() = "div.span9 > dl.chapter-list > dd"
}
| apache-2.0 | 81121307f8b32246d8b0d878a0668798 | 30.258065 | 93 | 0.713106 | 4.088608 | false | false | false | false |
LorittaBot/Loritta | web/spicy-morenitta/src/main/kotlin/net/perfectdreams/spicymorenitta/routes/guilds/dashboard/AuditLogRoute.kt | 1 | 5387 | package net.perfectdreams.spicymorenitta.routes.guilds.dashboard
import io.ktor.client.request.*
import io.ktor.client.statement.*
import kotlinx.browser.document
import kotlinx.browser.window
import kotlinx.html.*
import kotlinx.html.dom.append
import net.perfectdreams.spicymorenitta.SpicyMorenitta
import net.perfectdreams.spicymorenitta.application.ApplicationCall
import net.perfectdreams.spicymorenitta.http
import net.perfectdreams.spicymorenitta.locale
import net.perfectdreams.spicymorenitta.routes.UpdateNavbarSizePostRender
import net.perfectdreams.spicymorenitta.utils.ActionType
import net.perfectdreams.spicymorenitta.utils.locale.buildAsHtml
import net.perfectdreams.spicymorenitta.utils.select
import net.perfectdreams.spicymorenitta.views.dashboard.ServerConfig
import org.w3c.dom.HTMLDivElement
import utils.Moment
class AuditLogRoute(val m: SpicyMorenitta) : UpdateNavbarSizePostRender("/guild/{guildid}/configure/audit-log") {
override val keepLoadingScreen: Boolean
get() = true
override fun onRender(call: ApplicationCall) {
Moment.locale("pt-br")
m.showLoadingScreen()
SpicyMorenitta.INSTANCE.launch {
val result = http.get {
url("${window.location.origin}/api/v1/guilds/${call.parameters["guildid"]}/audit-log")
}.bodyAsText()
val list = kotlinx.serialization.json.JSON.nonstrict.decodeFromString(ServerConfig.WebAuditLogWrapper.serializer(), result)
fixDummyNavbarHeight(call)
m.fixLeftSidebarScroll {
switchContent(call)
}
val entriesDiv = document.select<HTMLDivElement>("#audit-log-entries")
for (entry in list.entries) {
val user = list.users.first { it.id == entry.id }
entriesDiv.append {
div {
createAuditLogEntry(user, entry)
}
}
}
m.hideLoadingScreen()
}
}
fun DIV.createAuditLogEntry(selfMember: ServerConfig.SelfMember, entry: ServerConfig.WebAuditLogEntry) {
val type = ActionType.valueOf(entry.type)
this.div(classes = "discord-generic-entry timer-entry") {
img(classes = "amino-small-image") {
style = "width: 6%; height: auto; border-radius: 999999px; float: left; position: relative; bottom: 8px;"
src = selfMember.effectiveAvatarUrl
}
div(classes = "pure-g") {
div(classes = "pure-u-1 pure-u-md-18-24") {
div {
style = "margin-left: 10px; margin-right: 10px;"
val updateString = locale["modules.auditLog.${type.updateType}"]
div(classes = "amino-title entry-title") {
style = "font-family: Lato,Helvetica Neue,Helvetica,Arial,sans-serif;"
locale.buildAsHtml(updateString, { num ->
if (num == 0) {
+ selfMember.name
span {
style = "font-size: 0.8em; opacity: 0.6;"
+ "#${selfMember.discriminator}"
}
}
if (num == 1) {
span {
val sectionName = when (type) {
ActionType.UPDATE_YOUTUBE -> "YouTube"
ActionType.UPDATE_TWITCH -> "Twitch"
ActionType.UPDATE_MISCELLANEOUS -> locale["commands.category.misc.name"]
else -> locale["modules.sectionNames.${type.sectionName}"]
}
+ sectionName
}
}
}) { str ->
span {
style = "opacity: 0.8;"
+ str
}
}
}
div(classes = "amino-title toggleSubText") {
+ (Moment.unix(entry.executedAt / 1000).calendar())
}
}
}
/* div(classes = "pure-u-1 pure-u-md-6-24 vertically-centered-right-aligned") {
button(classes="button-discord button-discord-edit pure-button edit-timer-button") {
onClickFunction = {
println("Saving!")
SaveUtils.prepareSave("premium", {
it["keyId"] = donationKey.id
}, onFinish = {
val guild = JSON.nonstrict.parse(ServerConfig.Guild.serializer(), it.body)
PremiumKeyView.generateStuff(guild)
})
}
+ "Ativar"
}
} */
}
}
}
} | agpl-3.0 | 5d774a15d0d5c0abe07b410a56d6706c | 40.446154 | 135 | 0.485428 | 5.376248 | false | false | false | false |
angcyo/RLibrary | uiview/src/main/java/com/angcyo/uiview/widget/SearchEditText.kt | 1 | 4576 | package com.angcyo.uiview.widget
import android.content.Context
import android.graphics.Canvas
import android.graphics.Paint
import android.graphics.drawable.Drawable
import android.text.TextUtils
import android.util.AttributeSet
import com.angcyo.uiview.R
import com.angcyo.uiview.kotlin.*
/**
* Copyright (C) 2016,深圳市红鸟网络科技股份有限公司 All rights reserved.
* 项目名称:
* 类的描述:模仿IOS的搜索输入框
* 创建人员:Robi
* 创建时间:2017/09/20 10:17
* 修改人员:Robi
* 修改时间:2017/09/20 10:17
* 修改备注:
* Version: 1.0.0
*/
class SearchEditText(context: Context, attributeSet: AttributeSet? = null) : ExEditText(context, attributeSet) {
private var rawPaddingLeft = 0
var searchDrawable: Drawable? = null
var searchTipText = ""
var searchTipTextSize = 14 * density
var searchTipTextColor = getColor(R.color.base_text_color_dark2)
/**文本偏移searchDrawable的距离*/
var searchTipTextLeftOffset = 0f
init {
val typedArray = context.obtainStyledAttributes(attributeSet, R.styleable.SearchEditText)
val string = typedArray.getString(R.styleable.SearchEditText_r_search_tip_text)
searchTipText = string ?: "搜索一下"
typedArray.recycle()
}
override fun initView(context: Context, attrs: AttributeSet?) {
super.initView(context, attrs)
setSingleLine(true)
maxLines = 1
rawPaddingLeft = paddingLeft
val typedArray = context.obtainStyledAttributes(attrs, R.styleable.SearchEditText)
val drawable = typedArray.getDrawable(R.styleable.SearchEditText_r_search_drawable)
if (drawable == null) {
if (isInEditMode) {
searchDrawable = getDrawable(R.drawable.base_search)
} else {
searchDrawable = getDrawable(R.drawable.base_search)
}
} else {
searchDrawable = drawable
}
searchDrawable?.let {
it.setBounds(0, 0, it.intrinsicWidth, it.intrinsicHeight)
}
searchTipTextLeftOffset = 4 * density
searchTipTextSize = typedArray.getDimensionPixelOffset(R.styleable.SearchEditText_r_search_tip_text_size, searchTipTextSize.toInt()).toFloat()
searchTipTextLeftOffset = typedArray.getDimensionPixelOffset(R.styleable.SearchEditText_r_search_tip_text_left_offset, searchTipTextLeftOffset.toInt()).toFloat()
searchTipTextColor = typedArray.getColor(R.styleable.SearchEditText_r_search_tip_text_color, searchTipTextColor)
typedArray.recycle()
setPadding((rawPaddingLeft + (searchDrawable?.intrinsicWidth ?: 0) + searchTipTextLeftOffset).toInt(),
paddingTop, paddingRight, paddingBottom)
}
override fun onAttachedToWindow() {
super.onAttachedToWindow()
clearFocus()
}
private val paint by lazy {
Paint(Paint.ANTI_ALIAS_FLAG)
}
private val drawWidth: Float
get() {
paint.textSize = searchTipTextSize
return (searchDrawable?.intrinsicWidth ?: 0) + searchTipTextLeftOffset + textWidth(paint, searchTipText)
}
private val drawHeight: Float
get() {
paint.textSize = searchTipTextSize
return textHeight(paint).minValue(searchDrawable?.intrinsicHeight ?: 0)
}
override fun onDraw(canvas: Canvas) {
super.onDraw(canvas)
//canvas.drawColor(Color.BLUE)
var left = 0
val top = paddingTop.toFloat() + (viewDrawHeight - drawHeight) / 2
searchDrawable?.let {
canvas.save()
if (isFocused || !isEmpty) {
canvas.translate(rawPaddingLeft.toFloat() + scrollX, top)
it.draw(canvas)
} else {
canvas.translate(rawPaddingLeft + (viewDrawWith - drawWidth) / 2, top)
it.draw(canvas)
}
left = it.intrinsicWidth
canvas.restore()
}
if (!TextUtils.isEmpty(searchTipText) && isEmpty && !isFocused) {
canvas.save()
canvas.translate(rawPaddingLeft + (viewDrawWith - drawWidth) / 2, top)
paint.color = searchTipTextColor
paint.textSize = searchTipTextSize
canvas.drawText(searchTipText, left + searchTipTextLeftOffset, -paint.ascent(), paint)
canvas.restore()
}
}
} | apache-2.0 | 4c63cada842eb6ba789cae8e957b2d2f | 32.418605 | 169 | 0.631365 | 4.834423 | false | false | false | false |
christophpickl/kpotpourri | test4k/src/main/kotlin/com/github/christophpickl/kpotpourri/test4k/hamkrest_matcher/map.kt | 1 | 2663 | @file:Suppress("KDocMissingDocumentation")
package com.github.christophpickl.kpotpourri.test4k.hamkrest_matcher
import com.natpryce.hamkrest.MatchResult
import com.natpryce.hamkrest.Matcher
import com.natpryce.hamkrest.describe
/**
* Checks if the given map contains the key.
*/
fun <K, V> mapContainsKey(key: K): Matcher<Map<K, V>> = object : Matcher.Primitive<Map<K, V>>() {
override fun invoke(actual: Map<K, V>): MatchResult {
return if (actual.containsKey(key)) {
MatchResult.Match
} else {
MatchResult.Mismatch("was ${describe(actual)}")
}
}
override val description: String get() = "contains ${describe(key)}"
override val negatedDescription: String get() = "does not contain ${describe(key)}"
}
/**
* Checks if the actual Map contains at least the given entry.
*/
fun <K, V> mapContains(entry: Pair<K, V>): Matcher<Map<K, V>> = object : Matcher.Primitive<Map<K, V>>() {
override fun invoke(actual: Map<K, V>): MatchResult {
return if (actual.containsKey(entry.first) && actual[entry.first] == entry.second) {
MatchResult.Match
} else {
MatchResult.Mismatch("was ${describe(actual)}")
}
}
override val description: String get() = "contains ${describe(entry)}"
override val negatedDescription: String get() = "does not contain ${describe(entry)}"
}
/**
* Checks if the actual Map contains _exactly_ the given entries, ignoring the order.
*/
fun <K, V> mapContainsExactly(vararg entries: Pair<K, V>): Matcher<Map<K, V>> = object : Matcher.Primitive<Map<K, V>>() {
private val entriesDescribed: String by lazy { describe(entries.joinToString(", ")) }
private val expectedEntries: Map<K, V> by lazy { entries.toMap() }
override fun invoke(actual: Map<K, V>): MatchResult {
return if (actual.size == entries.size && actual.containsExact(expectedEntries)) {
MatchResult.Match
} else {
MatchResult.Mismatch("was ${describe(actual)}")
}
}
override val description: String get() = "contains exactly $entriesDescribed"
override val negatedDescription: String get() = "does not contain exactly $entriesDescribed"
}
/**
* Should actually be in common4k but that would introduce a cyclic dependency.
*/
private fun <K, V> Map<K, V>.containsExact(other: Map<K, V>): Boolean {
this.entries.forEach { (k, v) ->
if (!other.contains(k) || other[k] != v) {
return false
}
}
other.entries.forEach { (k, v) ->
if (!this.contains(k) || this[k] != v) {
return false
}
}
return true
}
| apache-2.0 | 65417f6f8abef16c89ebb913e625e602 | 34.039474 | 121 | 0.638378 | 3.921944 | false | false | false | false |
RyanAndroidTaylor/Rapido | rapidocommon/src/main/java/com/izeni/rapidocommon/recycler/SectionManager.kt | 1 | 6224 | package com.izeni.rapidocommon.recycler
import android.util.SparseArray
import android.util.SparseIntArray
import android.view.ViewGroup
import com.izeni.rapidocommon.e
/**
* Created by ner on 1/11/17.
*/
class SectionManager(private val adapter: MultiTypeSectionedAdapter, private val sections: List<MultiTypeSectionedAdapter.Section<*>>) {
private val sectionSpans = SparseArray<SectionSpan>()
private val headers = SparseIntArray()
val count: Int
get() = sections.sumBy { it.count + it.headerCount }
init {
updatePositions()
val set = mutableSetOf<Int>()
sections.forEach {
if (set.contains(it.type))
throw IllegalStateException("Two of your sections have a matching type. Types must be unique")
else
set.add(it.type)
}
}
private fun adjustPosition(position: Int): Int {
var offset = (0..headers.size() - 1).count { headers.valueAt(it) < position }
(0..sectionSpans.size() - 1)
.map { sectionSpans.valueAt(it) }
.filter { it.isBefore(position) }
.forEach { offset += it.count }
return position - offset
}
private fun bindSectionHeader(type: Int) {
headers.get(type, -1).let {
if (it != -1)
adapter.notifyItemChanged(it)
}
}
private fun getSectionForType(sectionType: Int): MultiTypeSectionedAdapter.Section<*> {
return sections.first { it.type == sectionType }
}
private fun updatePositions() {
var offset = 0
sections.forEach { section ->
if (section.hasHeader)
headers.put(section.type, 0 + offset)
sectionSpans.put(section.type, SectionSpan(section.headerCount + offset, (section.count - 1) + section.headerCount + offset))
offset += section.headerCount
if (!section.isCollapsed)
offset += section.count
}
}
fun getViewHolderType(position: Int): Int {
var viewHolderType = getSectionType(position)
if (viewHolderType == -1) {
(0..headers.size() - 1)
.filter { position == headers.valueAt(it) }
.forEach { viewHolderType = MultiTypeSectionedAdapter.HEADER }
}
return viewHolderType
}
fun createViewHolder(parent: ViewGroup, sectionType: Int): SectionedViewHolder<*> {
return getSectionForType(sectionType).viewHolderData.createViewHolder(parent)
}
fun getSectionType(position: Int): Int {
for (i in 0..sectionSpans.size() - 1) {
sectionSpans.valueAt(i).let {
if (it.contains(position))
return sectionSpans.keyAt(i)
}
}
e("No type found for position $position")
return -1
}
fun getHeaderSectionType(position: Int): Int {
(0..headers.size() - 1)
.filter { position == headers.valueAt(it) }
.forEach { return headers.keyAt(it) }
e("No header type found for position $position")
return -1
}
fun hasHeaders(): Boolean {
sections.forEach {
if (it.hasHeader)
return true
}
return false
}
fun bind(viewHolder: SectionedViewHolder<*>, position: Int) {
getSectionForType(getSectionType(position)).bind(viewHolder, adjustPosition(position))
}
fun bindHeader(viewHolder: SectionedViewHolder<*>, position: Int) {
getSectionForType(getHeaderSectionType(position)).bindHeader(viewHolder)
}
fun collapseSection(sectionType: Int) {
sections.firstOrNull { it.type == sectionType }?.isCollapsed = true
sectionSpans.get(sectionType)?.let {
updatePositions()
//TODO When using notifyItemRangeRemoved the sections are not being marked as collapsed
// adapter.notifyItemRangeRemoved(it.start, it.end - it.start + 1)
adapter.notifyDataSetChanged()
}
}
fun expandSection(sectionType: Int) {
sections.firstOrNull { it.type == sectionType }?.isCollapsed = false
sectionSpans.get(sectionType)?.let {
updatePositions()
// adapter.notifyItemRangeInserted(it.start, it.end - it.start)
adapter.notifyDataSetChanged()
}
}
fun addItem(sectionType: Int, item: Any) {
getSectionForType(sectionType).let {
it.addItem(item)
updatePositions()
adapter.notifyItemInserted(sectionSpans.get(sectionType).end)
bindSectionHeader(sectionType)
}
}
fun addItemAt(index: Int, sectionType: Int, item: Any) {
getSectionForType(sectionType).let {
val listStart = sectionSpans.get(sectionType).start
it.addItemAt(index, item)
updatePositions()
adapter.notifyItemInserted(listStart + index)
bindSectionHeader(sectionType)
}
}
fun addItems(sectionType: Int, items: List<Any>) {
getSectionForType(sectionType).let {
val listEnd = sectionSpans.get(sectionType).end
it.addItems(items)
updatePositions()
adapter.notifyItemRangeChanged(listEnd + 1, listEnd + 1 + items.size)
bindSectionHeader(sectionType)
}
}
fun removeItem(sectionType: Int, item: Any) {
getSectionForType(sectionType).let {
val listStart = sectionSpans.get(sectionType).start
val index = it.removeItem(item)
updatePositions()
adapter.notifyItemRemoved(listStart + index)
bindSectionHeader(sectionType)
}
}
class SectionData(val type: Int, val sectionCount: Int, val isCollapsed: Boolean)
private class SectionSpan(val start: Int, val end: Int) {
val count: Int
get() = end - start + 1
fun contains(position: Int): Boolean = position in start..end
fun isBefore(position: Int): Boolean = end < position
fun isAfter(position: Int): Boolean = start > position
}
} | mit | 0a46e6cba021c1eaf93a552369ff2044 | 28.225352 | 137 | 0.60106 | 4.931854 | false | false | false | false |
Shynixn/PetBlocks | petblocks-core/src/main/kotlin/com/github/shynixn/petblocks/core/logic/business/service/PetServiceImpl.kt | 1 | 6834 | package com.github.shynixn.petblocks.core.logic.business.service
import com.github.shynixn.petblocks.api.business.enumeration.Permission
import com.github.shynixn.petblocks.api.business.proxy.PetProxy
import com.github.shynixn.petblocks.api.business.service.*
import com.github.shynixn.petblocks.api.persistence.entity.Position
import com.github.shynixn.petblocks.core.logic.persistence.entity.PetPostSpawnEntity
import com.github.shynixn.petblocks.core.logic.persistence.entity.PetPreSpawnEntity
import com.google.inject.Inject
import java.util.*
import kotlin.collections.HashMap
/**
* Created by Shynixn 2018.
* <p>
* Version 1.2
* <p>
* MIT License
* <p>
* Copyright (c) 2018 by Shynixn
* <p>
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
* <p>
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
* <p>
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
class PetServiceImpl @Inject constructor(
private val concurrencyService: ConcurrencyService,
private val petMetaService: PersistencePetMetaService,
private val loggingService: LoggingService,
private val configurationService: ConfigurationService,
private val proxyService: ProxyService,
private val entityService: EntityService,
private val eventService: EventService
) : PetService {
private val pets = HashMap<String, PetProxy>()
/**
* Gets or spawns the pet of the given player.
* An empty optional gets returned if the pet cannot spawn by one of the following reasons:
* Current world, player has not got permission, region is disabled for pets, PreSpawnEvent was cancelled or Pet is not available due to Ai State.
* For example HealthAI defines pet ai as 0 which results into impossibility to spawn.
*/
override fun <P> getOrSpawnPetFromPlayer(player: P): Optional<PetProxy> {
val playerUUID = proxyService.getPlayerUUID(player)
if (hasPet(player)) {
return Optional.of(pets[playerUUID]!!)
}
if (!petMetaService.hasPetMeta(player)) {
return Optional.empty()
}
val petMeta = petMetaService.getPetMetaFromPlayer(player)
val cancelled = eventService.callEvent(PetPreSpawnEntity(player as Any, petMeta))
if (cancelled) {
return Optional.empty()
}
val playerLocation = proxyService.getPlayerLocation<Any, P>(player)
val petProxy: PetProxy
try {
petProxy = entityService.spawnPetProxy(playerLocation, petMeta)
} catch (e: Exception) {
loggingService.warn("Failed to spawn pet.", e)
return Optional.empty()
}
pets[playerUUID] = petProxy
petMeta.enabled = true
eventService.callEvent(PetPostSpawnEntity(player as Any, petProxy))
concurrencyService.runTaskSync(1L) {
petProxy.triggerTick()
}
return Optional.of(petProxy)
}
/**
* Gets if the given [player] has got an active pet.
*/
override fun <P> hasPet(player: P): Boolean {
val playerUUID = proxyService.getPlayerUUID(player)
if (!pets.containsKey(playerUUID)) {
return false
}
if (!petMetaService.hasPetMeta(player)) {
return false
}
val petAllowed = isPetAllowedToBeInSpawnState(player)
val pet = pets[playerUUID]!!
if (!petAllowed) {
if (!pet.isDead) {
pet.remove()
}
val petMeta = petMetaService.getPetMetaFromPlayer(player)
petMeta.enabled = false
this.pets.remove(playerUUID)
return false
}
if (pet.isDead) {
val petMeta = petMetaService.getPetMetaFromPlayer(player)
petMeta.enabled = false
this.pets.remove(playerUUID)
return false
}
return true
}
/**
* Clears the allocated player resources.
* Should not be called by external plugins.
*/
override fun <P> clearPlayerResources(player: P) {
val playerUUID = proxyService.getPlayerUUID(player)
if (this.pets.containsKey(playerUUID)) {
this.pets.remove(playerUUID)
}
}
/**
* Tries to find the pet from the given entity.
*/
override fun <E> findPetByEntity(entity: E): PetProxy? {
for (pet in pets.values) {
if (pet.getHeadArmorstand<Any>() == entity || (pet.getHitBoxLivingEntity<Any>().isPresent && pet.getHitBoxLivingEntity<Any>()
.get() == entity)
) {
val owner = pet.getPlayer<Any>()
if (hasPet(owner)) {
return pet
}
}
}
return null
}
/**
* Is the pet allowed to be spawned.
*/
private fun <P> isPetAllowedToBeInSpawnState(player: P): Boolean {
if (!proxyService.hasPermission(player, Permission.CALL)) {
return false
}
val playerLocation = proxyService.getPlayerLocation<Any, P>(player)
val playerPosition = proxyService.toPosition(playerLocation)
return isAllowedToSpawnAtPosition(playerPosition)
}
/**
* Gets if the pet is allowed to spawn at the given position.
*/
private fun isAllowedToSpawnAtPosition(position: Position): Boolean {
val includedWorlds = configurationService.findValue<List<String>>("world.included")
val excludedWorlds = configurationService.findValue<List<String>>("world.excluded")
when {
includedWorlds.contains("all") -> return !excludedWorlds.contains(position.worldName)
excludedWorlds.contains("all") -> return includedWorlds.contains(position.worldName)
else -> loggingService.warn("Please add 'all' to excluded or included worlds inside of the config.yml")
}
return true
}
} | apache-2.0 | 498a2c22538fd12673a699565342aeb7 | 34.231959 | 150 | 0.661838 | 4.63322 | false | false | false | false |
JetBrains/resharper-unity | rider/src/main/kotlin/com/jetbrains/rider/plugins/unity/explorer/MetaTracker.kt | 1 | 10317 | @file:Suppress("UnstableApiUsage")
package com.jetbrains.rider.plugins.unity.explorer
import com.intellij.openapi.Disposable
import com.intellij.openapi.command.CommandProcessor
import com.intellij.openapi.command.undo.UndoManager
import com.intellij.openapi.components.serviceIfCreated
import com.intellij.openapi.project.Project
import com.intellij.openapi.project.ProjectManager
import com.intellij.openapi.vcs.VcsBundle
import com.intellij.openapi.vfs.LocalFileSystem
import com.intellij.openapi.vfs.VfsUtil
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.openapi.vfs.newvfs.BulkFileListener
import com.intellij.openapi.vfs.newvfs.events.*
import com.intellij.util.PathUtil
import com.intellij.util.application
import com.intellij.workspaceModel.ide.WorkspaceModel
import com.jetbrains.rd.platform.util.getLogger
import com.jetbrains.rider.plugins.unity.explorer.UnityExplorerFileSystemNode.Companion.isHiddenAsset
import com.jetbrains.rider.plugins.unity.isUnityProjectFolder
import com.jetbrains.rider.plugins.unity.workspace.getPackages
import com.jetbrains.rider.projectDir
import com.jetbrains.rider.projectView.VfsBackendRequester
import org.jetbrains.annotations.Nls
import java.nio.file.Path
import java.nio.file.Paths
import java.time.LocalDateTime
import java.time.ZoneOffset
import java.util.*
import kotlin.io.path.name
class MetaTracker : BulkFileListener, VfsBackendRequester, Disposable {
companion object {
private val logger = getLogger<MetaTracker>()
}
override fun after(events: MutableList<out VFileEvent>) {
if (!isValidCommand()) return
val projectManager = serviceIfCreated<ProjectManager>() ?: return
val openedUnityProjects = projectManager.openProjects.filter { !it.isDisposed && it.isUnityProjectFolder() && !isUndoRedoInProgress(it)}.toList()
val actions = MetaActionList()
for (event in events) {
if (!isValidEvent(event)) continue
for (project in openedUnityProjects) {
if (isApplicableForProject(event, project)) {
if (isMetaFile(event)) // Collect modified meta files at first (usually there is no such files, but still)
actions.addInitialSetOfChangedMetaFiles(Paths.get(event.path))
else {
try {
when (event) {
is VFileCreateEvent -> {
val metaFileName = getMetaFileName(event.childName)
val metaFile = event.parent.toNioPath().resolve(metaFileName)
val ls = event.file?.detectedLineSeparator
?: "\n" // from what I see, Unity 2020.3 always uses "\n", but lets use same as the main file.
actions.add(metaFile, project) {
createMetaFile(event.file, event.parent, metaFileName, ls)
}
}
is VFileDeleteEvent -> {
val metaFile = getMetaFile(event.path) ?: continue
actions.add(metaFile, project) {
VfsUtil.findFile(metaFile, true)?.delete(this)
}
}
is VFileCopyEvent -> {
val metaFile = getMetaFile(event.file.path) ?: continue
val ls = event.file.detectedLineSeparator ?: "\n"
actions.add(metaFile, project) {
createMetaFile(event.file, event.newParent, getMetaFileName(event.newChildName), ls)
}
}
is VFileMoveEvent -> {
val metaFile = getMetaFile(event.oldPath) ?: continue
actions.add(metaFile, project) {
VfsUtil.findFile(metaFile, true)?.move(this, event.newParent)
}
}
is VFilePropertyChangeEvent -> {
if (!event.isRename) continue
val metaFile = getMetaFile(event.oldPath) ?: continue
actions.add(metaFile, project) {
val target = getMetaFileName(event.newValue as String)
val origin = VfsUtil.findFile(metaFile, true)
val conflictingMeta = origin?.parent?.findChild(target)
if (conflictingMeta != null) {
logger.warn("Removing conflicting meta $conflictingMeta")
conflictingMeta.delete(this)
}
origin?.rename(this, target)
}
}
}
} catch (t: Throwable) {
logger.error(t)
continue
}
}
}
}
}
if (actions.isEmpty()) return
actions.execute()
}
private fun isValidCommand():Boolean {
val currentCommandName = CommandProcessor.getInstance().currentCommandName
val res = currentCommandName == VcsBundle.message("patch.apply.command")
if (res)
logger.trace("Avoid MetaTracker functionality for the $currentCommandName. See RIDER-77123.")
return !res
}
private fun isValidEvent(event: VFileEvent):Boolean{
if (event.isFromRefresh) return false
if (event.fileSystem !is LocalFileSystem) return false
return CommandProcessor.getInstance().currentCommand != null
}
private fun isUndoRedoInProgress(project: Project): Boolean {
return UndoManager.getInstance(project).isUndoOrRedoInProgress
}
private fun isMetaFile(event: VFileEvent): Boolean {
val extension = event.file?.extension ?: PathUtil.getFileExtension(event.path)
return "meta".equals(extension, true)
}
private fun isApplicableForProject(event: VFileEvent, project: Project): Boolean {
val file = event.file ?: return false
val assets = project.projectDir.findChild("Assets") ?: return false
if (VfsUtil.isAncestor(assets, file, false))
return true
val editablePackages = WorkspaceModel.getInstance(project).getPackages().filter { it.isEditable() }
for (pack in editablePackages) {
val packageFolder = pack.packageFolder ?: continue
if (VfsUtil.isAncestor(packageFolder, file, false)) return true
}
return false
}
private fun getMetaFile(path: String?): Path? {
path ?: return null
val file = Paths.get(path)
val metaFileName = getMetaFileName(file.name)
return file.parent.resolve(metaFileName)
}
private fun getMetaFileName(fileName: String) = "$fileName.meta"
private fun createMetaFile(assetFile: VirtualFile?, parent: VirtualFile, metaFileName: String, ls: String) {
if (assetFile != null && isHiddenAsset(assetFile)) return // not that children of a hidden folder (like `Documentation~`), would still pass this check. I think it is fine.
val metaFile = parent.createChildData(this, metaFileName)
val guid = UUID.randomUUID().toString().replace("-", "").substring(0, 32)
val timestamp = LocalDateTime.now(ZoneOffset.UTC).atZone(ZoneOffset.UTC).toEpochSecond() // LocalDateTime to epoch seconds
val content = "fileFormatVersion: 2${ls}guid: ${guid}${ls}timeCreated: $timestamp"
VfsUtil.saveText(metaFile, content)
}
override fun dispose() = Unit
private class MetaActionList {
private val changedMetaFiles = HashSet<Path>()
private val actions = mutableListOf<MetaAction>()
private var nextGroupIdIndex = 0
fun addInitialSetOfChangedMetaFiles(path: Path) {
changedMetaFiles.add(path)
}
fun add(metaFile: Path, project:Project, action: () -> Unit) {
if (changedMetaFiles.contains(metaFile)) return
actions.add(MetaAction(metaFile, project, action))
}
fun isEmpty() = actions.isEmpty()
fun execute() {
val commandProcessor = CommandProcessor.getInstance()
var groupId = commandProcessor.currentCommandGroupId
if (groupId == null) {
groupId = MetaGroupId(nextGroupIdIndex++)
commandProcessor.currentCommandGroupId = groupId
}
application.invokeLater {
commandProcessor.allowMergeGlobalCommands {
actions.forEach {
commandProcessor.executeCommand(it.project, {
application.runWriteAction {
it.execute()
}
}, getCommandName(), groupId)
}
}
}
}
@Nls
fun getCommandName(): String {
return if (actions.count() == 1)
UnityPluginExplorerBundle.message("process.one.meta.file", actions.single().metaFile.name)
else
UnityPluginExplorerBundle.message("process.several.meta.files", actions.count())
}
}
private class MetaAction(val metaFile: Path, val project:Project, private val action: () -> Unit) {
fun execute() {
try {
action()
}
catch (ex: Throwable) {
logger.error(ex)
}
}
}
private class MetaGroupId(val index: Int) {
override fun toString() = "MetaGroupId$index"
}
} | apache-2.0 | add8377eae110746ee3f82da2b57f6be | 44.254386 | 179 | 0.563924 | 5.582792 | false | false | false | false |
spark/photon-tinker-android | commonui/src/main/java/io/particle/commonui/DeviceNotesDelegate.kt | 1 | 2887 | package io.particle.commonui
import android.text.InputType
import android.view.Gravity
import androidx.annotation.MainThread
import androidx.appcompat.app.AppCompatActivity
import com.afollestad.materialdialogs.MaterialDialog
import com.afollestad.materialdialogs.Theme
import com.google.android.material.snackbar.Snackbar
import io.particle.android.sdk.cloud.ParticleDevice
import io.particle.mesh.setup.flow.Scopes
import android.view.ViewGroup
import androidx.core.view.updateLayoutParams
import androidx.fragment.app.FragmentActivity
import androidx.lifecycle.Lifecycle.State
import androidx.lifecycle.MutableLiveData
class DeviceNotesDelegate private constructor(
private val activity: FragmentActivity,
private val device: ParticleDevice,
private val scopes: Scopes,
private val newNoteDataLD: MutableLiveData<String>
) {
companion object {
@JvmStatic
@MainThread
fun editDeviceNotes(
activity: FragmentActivity,
device: ParticleDevice,
scopes: Scopes,
newNoteDataLD: MutableLiveData<String>
) {
DeviceNotesDelegate(activity, device, scopes, newNoteDataLD).showDialog()
}
}
private fun showDialog() {
val md = MaterialDialog.Builder(activity)
.title("Notes")
.theme(Theme.LIGHT)
.inputType(InputType.TYPE_TEXT_FLAG_MULTI_LINE)
.input("Use this space to keep notes on this device",
if (device.notes.isNullOrBlank()) null else device.notes,
false) { _, _ -> }
.positiveText("Save")
.negativeText("Cancel")
.onPositive(MaterialDialog.SingleButtonCallback { dialog, _ ->
val inputText = dialog.inputEditText ?: return@SingleButtonCallback
updateDeviceNotes(inputText.text.toString())
})
.show()
md.inputEditText!!.updateLayoutParams {
height = dpToPx(250, md.context)
}
md.inputEditText!!.gravity = Gravity.START or Gravity.TOP
md.inputEditText!!.setSingleLine(false)
}
private fun updateDeviceNotes(newNotes: String?) {
newNoteDataLD.postValue(newNotes)
scopes.onWorker {
try {
device.notes = newNotes
} catch (ex: Exception) {
scopes.onMain {
showErrorSnackBar()
}
}
}
}
private fun showErrorSnackBar() {
if (!activity.lifecycle.currentState.isAtLeast(State.STARTED)) {
return
}
val contentRoot = (activity.findViewById(android.R.id.content) as ViewGroup)
val myRoot = contentRoot.getChildAt(0)
val msg = "An error occurred. Device notes not updated"
Snackbar.make(myRoot, msg, Snackbar.LENGTH_SHORT).show()
}
} | apache-2.0 | b07551b81208fe177313c79324911595 | 32.195402 | 85 | 0.646346 | 4.960481 | false | false | false | false |
robinverduijn/gradle | subprojects/kotlin-dsl/src/main/kotlin/org/gradle/kotlin/dsl/execution/ResidualProgramCompiler.kt | 1 | 23815 | /*
* Copyright 2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gradle.kotlin.dsl.execution
import org.gradle.api.Project
import org.gradle.internal.classpath.ClassPath
import org.gradle.internal.hash.HashCode
import org.gradle.internal.hash.Hashing
import org.gradle.kotlin.dsl.KotlinBuildScript
import org.gradle.kotlin.dsl.KotlinInitScript
import org.gradle.kotlin.dsl.KotlinSettingsScript
import org.gradle.kotlin.dsl.execution.ResidualProgram.Dynamic
import org.gradle.kotlin.dsl.execution.ResidualProgram.Instruction
import org.gradle.kotlin.dsl.execution.ResidualProgram.Static
import org.gradle.kotlin.dsl.support.KotlinBuildscriptAndPluginsBlock
import org.gradle.kotlin.dsl.support.KotlinBuildscriptBlock
import org.gradle.kotlin.dsl.support.KotlinInitscriptBlock
import org.gradle.kotlin.dsl.support.KotlinPluginsBlock
import org.gradle.kotlin.dsl.support.KotlinScriptHost
import org.gradle.kotlin.dsl.support.KotlinSettingsBuildscriptBlock
import org.gradle.kotlin.dsl.support.bytecode.ACONST_NULL
import org.gradle.kotlin.dsl.support.bytecode.ALOAD
import org.gradle.kotlin.dsl.support.bytecode.ARETURN
import org.gradle.kotlin.dsl.support.bytecode.ASTORE
import org.gradle.kotlin.dsl.support.bytecode.CHECKCAST
import org.gradle.kotlin.dsl.support.bytecode.DUP
import org.gradle.kotlin.dsl.support.bytecode.GETSTATIC
import org.gradle.kotlin.dsl.support.bytecode.INVOKEINTERFACE
import org.gradle.kotlin.dsl.support.bytecode.INVOKESPECIAL
import org.gradle.kotlin.dsl.support.bytecode.INVOKESTATIC
import org.gradle.kotlin.dsl.support.bytecode.INVOKEVIRTUAL
import org.gradle.kotlin.dsl.support.bytecode.InternalName
import org.gradle.kotlin.dsl.support.bytecode.LDC
import org.gradle.kotlin.dsl.support.bytecode.NEW
import org.gradle.kotlin.dsl.support.bytecode.RETURN
import org.gradle.kotlin.dsl.support.bytecode.TRY_CATCH
import org.gradle.kotlin.dsl.support.bytecode.internalName
import org.gradle.kotlin.dsl.support.bytecode.loadByteArray
import org.gradle.kotlin.dsl.support.bytecode.publicClass
import org.gradle.kotlin.dsl.support.bytecode.publicDefaultConstructor
import org.gradle.kotlin.dsl.support.bytecode.publicMethod
import org.gradle.kotlin.dsl.support.compileKotlinScriptToDirectory
import org.gradle.kotlin.dsl.support.messageCollectorFor
import org.gradle.plugin.management.internal.DefaultPluginRequests
import org.gradle.plugin.use.internal.PluginRequestCollector
import org.jetbrains.kotlin.scripting.definitions.ScriptDefinition
import org.jetbrains.org.objectweb.asm.ClassVisitor
import org.jetbrains.org.objectweb.asm.ClassWriter
import org.jetbrains.org.objectweb.asm.MethodVisitor
import org.jetbrains.org.objectweb.asm.Type
import org.slf4j.Logger
import java.io.File
import kotlin.reflect.KClass
import kotlin.script.experimental.api.ScriptCompilationConfiguration
import kotlin.script.experimental.api.baseClass
import kotlin.script.experimental.api.defaultImports
import kotlin.script.experimental.api.hostConfiguration
import kotlin.script.experimental.jvm.defaultJvmScriptingHostConfiguration
internal
typealias CompileBuildOperationRunner = (String, String, () -> String) -> String
/**
* Compiles the given [residual program][ResidualProgram] to an [ExecutableProgram] subclass named `Program`
* stored in the given [outputDir].
*/
internal
class ResidualProgramCompiler(
private val outputDir: File,
private val classPath: ClassPath = ClassPath.EMPTY,
private val originalSourceHash: HashCode,
private val programKind: ProgramKind,
private val programTarget: ProgramTarget,
private val implicitImports: List<String> = emptyList(),
private val logger: Logger = interpreterLogger,
private val compileBuildOperationRunner: CompileBuildOperationRunner = { _, _, action -> action() },
private val pluginAccessorsClassPath: ClassPath = ClassPath.EMPTY,
private val packageName: String? = null
) {
fun compile(program: ResidualProgram) = when (program) {
is Static -> emitStaticProgram(program)
is Dynamic -> emitDynamicProgram(program)
}
private
fun emitStaticProgram(program: Static) {
program<ExecutableProgram> {
overrideExecute {
emit(program.instructions)
}
}
}
private
fun emitDynamicProgram(program: Dynamic) {
program<ExecutableProgram.StagedProgram> {
overrideExecute {
emit(program.prelude.instructions)
emitEvaluateSecondStageOf()
}
overrideGetSecondStageScriptText(program.source.text)
overrideLoadSecondStageFor()
}
}
private
fun ClassWriter.overrideGetSecondStageScriptText(secondStageScriptText: String) {
publicMethod(
"getSecondStageScriptText",
"()Ljava/lang/String;",
"()Ljava/lang/String;"
) {
if (mightBeLargerThan64KB(secondStageScriptText)) {
// Large scripts are stored as a resource to overcome
// the 64KB string constant limitation
val resourcePath = storeStringToResource(secondStageScriptText)
ALOAD(0)
LDC(resourcePath)
INVOKEVIRTUAL(
ExecutableProgram.StagedProgram::class.internalName,
ExecutableProgram.StagedProgram::loadScriptResource.name,
"(Ljava/lang/String;)Ljava/lang/String;"
)
} else {
LDC(secondStageScriptText)
}
ARETURN()
}
}
private
fun mightBeLargerThan64KB(secondStageScriptText: String) =
// We use a simple heuristic to avoid converting the string to bytes
// if all code points were in UTF32, 16K code points would require 64K bytes
secondStageScriptText.length >= 16 * 1024
private
fun storeStringToResource(secondStageScriptText: String): String {
val hash = Hashing.hashString(secondStageScriptText)
val resourcePath = "scripts/$hash.gradle.kts"
writeResourceFile(resourcePath, secondStageScriptText)
return resourcePath
}
private
fun writeResourceFile(resourcePath: String, resourceText: String) {
outputFile(resourcePath).apply {
parentFile.mkdir()
writeText(resourceText)
}
}
private
fun MethodVisitor.emit(instructions: List<Instruction>) {
instructions.forEach {
emit(it)
}
}
private
fun MethodVisitor.emit(instruction: Instruction) = when (instruction) {
is Instruction.SetupEmbeddedKotlin -> emitSetupEmbeddedKotlinFor()
is Instruction.CloseTargetScope -> emitCloseTargetScopeOf()
is Instruction.Eval -> emitEval(instruction.script)
is Instruction.ApplyBasePlugins -> emitApplyBasePluginsTo()
is Instruction.ApplyDefaultPluginRequests -> emitApplyEmptyPluginRequestsTo()
is Instruction.ApplyPluginRequestsOf -> {
val program = instruction.program
when (program) {
is Program.Plugins -> emitPrecompiledPluginsBlock(program)
is Program.Stage1Sequence -> emitStage1Sequence(program.buildscript, program.plugins)
else -> throw IllegalStateException("Expecting a residual program with plugins, got `$program'")
}
}
}
private
fun MethodVisitor.emitSetupEmbeddedKotlinFor() {
// programHost.setupEmbeddedKotlinFor(scriptHost)
ALOAD(Vars.ProgramHost)
ALOAD(Vars.ScriptHost)
invokeHost("setupEmbeddedKotlinFor", kotlinScriptHostToVoid)
}
private
fun MethodVisitor.emitEval(source: ProgramSource) {
val precompiledScriptClass = compileStage1(source, stage1ScriptDefinition)
emitInstantiationOfPrecompiledScriptClass(precompiledScriptClass)
}
private
fun MethodVisitor.emitStage1Sequence(buildscript: Program.Buildscript, plugins: Program.Plugins) {
val precompiledBuildscriptWithPluginsBlock =
compileStage1(
plugins.fragment.source.map {
it.preserve(
buildscript.fragment.range,
plugins.fragment.range)
},
buildscriptWithPluginsScriptDefinition,
pluginsBlockClassPath
)
precompiledScriptClassInstantiation(precompiledBuildscriptWithPluginsBlock) {
emitPluginRequestCollectorInstantiation()
NEW(precompiledBuildscriptWithPluginsBlock)
ALOAD(Vars.ScriptHost)
// ${plugins}(temp.createSpec(lineNumber))
emitPluginRequestCollectorCreateSpecFor(plugins)
INVOKESPECIAL(
precompiledBuildscriptWithPluginsBlock,
"<init>",
"(Lorg/gradle/kotlin/dsl/support/KotlinScriptHost;Lorg/gradle/plugin/use/PluginDependenciesSpec;)V")
emitApplyPluginsTo()
}
}
/**
* programHost.applyPluginsTo(scriptHost, collector.getPluginRequests())
*/
private
fun MethodVisitor.emitApplyPluginsTo() {
ALOAD(Vars.ProgramHost)
ALOAD(Vars.ScriptHost)
emitPluginRequestCollectorGetPluginRequests()
invokeApplyPluginsTo()
}
private
fun MethodVisitor.emitApplyBasePluginsTo() {
ALOAD(Vars.ProgramHost)
ALOAD(Vars.ScriptHost)
INVOKEVIRTUAL(
KotlinScriptHost::class.internalName,
"getTarget",
"()Ljava/lang/Object;")
CHECKCAST(Project::class.internalName)
invokeHost(
"applyBasePluginsTo",
"(Lorg/gradle/api/Project;)V")
}
private
fun MethodVisitor.emitApplyEmptyPluginRequestsTo() {
ALOAD(Vars.ProgramHost)
ALOAD(Vars.ScriptHost)
GETSTATIC(
DefaultPluginRequests::class.internalName,
"EMPTY",
"Lorg/gradle/plugin/management/internal/PluginRequests;")
invokeApplyPluginsTo()
}
fun emitStage2ProgramFor(scriptFile: File, originalPath: String) {
val precompiledScriptClass = compileScript(
scriptFile,
originalPath,
stage2ScriptDefinition,
StableDisplayNameFor.stage2
)
program<ExecutableProgram> {
overrideExecute {
emitInstantiationOfPrecompiledScriptClass(precompiledScriptClass)
}
}
}
private
fun MethodVisitor.emitPrecompiledPluginsBlock(program: Program.Plugins) {
val precompiledPluginsBlock = compilePlugins(program)
precompiledScriptClassInstantiation(precompiledPluginsBlock) {
// val collector = PluginRequestCollector(scriptSource)
emitPluginRequestCollectorInstantiation()
// ${precompiledPluginsBlock}(collector.createSpec(lineNumber))
NEW(precompiledPluginsBlock)
emitPluginRequestCollectorCreateSpecFor(program)
INVOKESPECIAL(
precompiledPluginsBlock,
"<init>",
"(Lorg/gradle/plugin/use/PluginDependenciesSpec;)V")
emitApplyPluginsTo()
}
}
/**
* val collector = PluginRequestCollector(scriptSource)
*/
private
fun MethodVisitor.emitPluginRequestCollectorInstantiation() {
NEW(pluginRequestCollectorType)
DUP()
ALOAD(Vars.ScriptHost)
INVOKEVIRTUAL(
KotlinScriptHost::class.internalName,
"getScriptSource",
"()Lorg/gradle/groovy/scripts/ScriptSource;")
INVOKESPECIAL(
pluginRequestCollectorType,
"<init>",
"(Lorg/gradle/groovy/scripts/ScriptSource;)V")
ASTORE(Vars.PluginRequestCollector)
}
private
fun MethodVisitor.emitPluginRequestCollectorGetPluginRequests() {
ALOAD(Vars.PluginRequestCollector)
INVOKEVIRTUAL(
pluginRequestCollectorType,
"getPluginRequests",
"()Lorg/gradle/plugin/management/internal/PluginRequests;")
}
private
fun MethodVisitor.emitPluginRequestCollectorCreateSpecFor(plugins: Program.Plugins) {
ALOAD(Vars.PluginRequestCollector)
LDC(plugins.fragment.lineNumber)
INVOKEVIRTUAL(
pluginRequestCollectorType,
"createSpec",
"(I)Lorg/gradle/plugin/use/PluginDependenciesSpec;")
}
private
val pluginRequestCollectorType = PluginRequestCollector::class.internalName
private
fun MethodVisitor.invokeApplyPluginsTo() {
invokeHost(
"applyPluginsTo",
"(Lorg/gradle/kotlin/dsl/support/KotlinScriptHost;Lorg/gradle/plugin/management/internal/PluginRequests;)V")
}
private
fun ClassWriter.overrideLoadSecondStageFor() {
publicMethod(
name = "loadSecondStageFor",
desc = "(" +
"Lorg/gradle/kotlin/dsl/execution/ExecutableProgram\$Host;" +
"Lorg/gradle/kotlin/dsl/support/KotlinScriptHost;" +
"Ljava/lang/String;" +
"Lorg/gradle/internal/hash/HashCode;" +
"Lorg/gradle/internal/classpath/ClassPath;" +
")Ljava/lang/Class;",
signature = "(" +
"Lorg/gradle/kotlin/dsl/execution/ExecutableProgram\$Host;" +
"Lorg/gradle/kotlin/dsl/support/KotlinScriptHost<*>;" +
"Ljava/lang/String;" +
"Lorg/gradle/internal/hash/HashCode;" +
"Lorg/gradle/internal/classpath/ClassPath;" +
")Ljava/lang/Class<*>;"
) {
ALOAD(Vars.ProgramHost)
ALOAD(0)
ALOAD(Vars.ScriptHost)
ALOAD(3)
ALOAD(4)
GETSTATIC(programKind)
GETSTATIC(programTarget)
ALOAD(5)
invokeHost(
ExecutableProgram.Host::compileSecondStageOf.name,
"(" +
stagedProgramType +
"Lorg/gradle/kotlin/dsl/support/KotlinScriptHost;" +
"Ljava/lang/String;Lorg/gradle/internal/hash/HashCode;" +
"Lorg/gradle/kotlin/dsl/execution/ProgramKind;" +
"Lorg/gradle/kotlin/dsl/execution/ProgramTarget;" +
"Lorg/gradle/internal/classpath/ClassPath;" +
")Ljava/lang/Class;"
)
ARETURN()
}
}
private
fun MethodVisitor.emitEvaluateSecondStageOf() {
// programHost.evaluateSecondStageOf(...)
ALOAD(Vars.ProgramHost)
ALOAD(Vars.Program)
ALOAD(Vars.ScriptHost)
LDC(programTarget.name + "/" + programKind.name + "/stage2")
// Move HashCode value to a static field so it's cached across invocations
loadHashCode(originalSourceHash)
if (requiresAccessors()) emitAccessorsClassPathForScriptHost() else ACONST_NULL()
invokeHost(
ExecutableProgram.Host::evaluateSecondStageOf.name,
"(" +
stagedProgramType +
"Lorg/gradle/kotlin/dsl/support/KotlinScriptHost;" +
"Ljava/lang/String;" +
"Lorg/gradle/internal/hash/HashCode;" +
"Lorg/gradle/internal/classpath/ClassPath;" +
")V")
}
private
val stagedProgramType = "Lorg/gradle/kotlin/dsl/execution/ExecutableProgram\$StagedProgram;"
private
fun requiresAccessors() =
requiresAccessors(programTarget, programKind)
private
fun MethodVisitor.emitAccessorsClassPathForScriptHost() {
ALOAD(Vars.ProgramHost)
ALOAD(Vars.ScriptHost)
invokeHost(
"accessorsClassPathFor",
"(Lorg/gradle/kotlin/dsl/support/KotlinScriptHost;)Lorg/gradle/internal/classpath/ClassPath;"
)
}
private
fun ClassVisitor.overrideExecute(methodBody: MethodVisitor.() -> Unit) {
publicMethod("execute", programHostToKotlinScriptHostToVoid, "(Lorg/gradle/kotlin/dsl/execution/ExecutableProgram\$Host;Lorg/gradle/kotlin/dsl/support/KotlinScriptHost<*>;)V") {
methodBody()
RETURN()
}
}
private
fun compilePlugins(program: Program.Plugins) =
compileStage1(
program.fragment.source.map { it.preserve(program.fragment.range) },
pluginsScriptDefinition,
pluginsBlockClassPath
)
private
val pluginsBlockClassPath
get() = classPath + pluginAccessorsClassPath
private
fun MethodVisitor.loadHashCode(hashCode: HashCode) {
loadByteArray(hashCode.toByteArray())
INVOKESTATIC(
HashCode::class.internalName,
"fromBytes",
"([B)Lorg/gradle/internal/hash/HashCode;")
}
private
fun MethodVisitor.emitInstantiationOfPrecompiledScriptClass(precompiledScriptClass: InternalName) {
precompiledScriptClassInstantiation(precompiledScriptClass) {
// ${precompiledScriptClass}(scriptHost)
NEW(precompiledScriptClass)
ALOAD(Vars.ScriptHost)
INVOKESPECIAL(precompiledScriptClass, "<init>", kotlinScriptHostToVoid)
}
}
private
fun MethodVisitor.precompiledScriptClassInstantiation(precompiledScriptClass: InternalName, instantiation: MethodVisitor.() -> Unit) {
TRY_CATCH<Throwable>(
tryBlock = {
instantiation()
},
catchBlock = {
emitOnScriptException(precompiledScriptClass)
})
}
private
fun MethodVisitor.emitOnScriptException(precompiledScriptClass: InternalName) {
// Exception is on the stack
ASTORE(4)
ALOAD(Vars.ProgramHost)
ALOAD(4)
LDC(Type.getType("L$precompiledScriptClass;"))
ALOAD(Vars.ScriptHost)
invokeHost(
"handleScriptException",
"(Ljava/lang/Throwable;Ljava/lang/Class;Lorg/gradle/kotlin/dsl/support/KotlinScriptHost;)V")
}
private
fun MethodVisitor.emitCloseTargetScopeOf() {
// programHost.closeTargetScopeOf(scriptHost)
ALOAD(Vars.ProgramHost)
ALOAD(Vars.ScriptHost)
invokeHost("closeTargetScopeOf", kotlinScriptHostToVoid)
}
private
fun MethodVisitor.invokeHost(name: String, desc: String) {
INVOKEINTERFACE(ExecutableProgram.Host::class.internalName, name, desc)
}
private
object Vars {
const val Program = 0
const val ProgramHost = 1
const val ScriptHost = 2
// Only valid within the context of `overrideExecute`
const val PluginRequestCollector = 3
}
private
val programHostToKotlinScriptHostToVoid =
"(Lorg/gradle/kotlin/dsl/execution/ExecutableProgram\$Host;Lorg/gradle/kotlin/dsl/support/KotlinScriptHost;)V"
private
val kotlinScriptHostToVoid =
"(Lorg/gradle/kotlin/dsl/support/KotlinScriptHost;)V"
private
inline fun <reified T : ExecutableProgram> program(noinline classBody: ClassWriter.() -> Unit = {}) {
program(T::class.internalName, classBody)
}
private
fun program(superName: InternalName, classBody: ClassWriter.() -> Unit = {}) {
writeFile("Program.class",
publicClass(InternalName("Program"), superName, null) {
publicDefaultConstructor(superName)
classBody()
})
}
private
fun writeFile(relativePath: String, bytes: ByteArray) {
outputFile(relativePath).writeBytes(bytes)
}
private
fun outputFile(relativePath: String) =
outputDir.resolve(relativePath)
private
fun compileStage1(
source: ProgramSource,
scriptDefinition: ScriptDefinition,
compileClassPath: ClassPath = classPath
): InternalName =
withTemporaryScriptFileFor(source.path, source.text) { scriptFile ->
val originalScriptPath = source.path
compileScript(
scriptFile,
originalScriptPath,
scriptDefinition,
StableDisplayNameFor.stage1,
compileClassPath
)
}
private
fun compileScript(
scriptFile: File,
originalPath: String,
scriptDefinition: ScriptDefinition,
stage: String,
compileClassPath: ClassPath = classPath
) = InternalName.from(
compileBuildOperationRunner(originalPath, stage) {
compileKotlinScriptToDirectory(
outputDir,
scriptFile,
scriptDefinition,
compileClassPath.asFiles,
messageCollectorFor(logger) { path ->
if (path == scriptFile.path) originalPath
else path
}
)
}.let { compiledScriptClassName ->
packageName
?.let { "$it.$compiledScriptClassName" }
?: compiledScriptClassName
}
)
/**
* Stage descriptions for build operations.
*
* Changes to these constants must be coordinated with the GE team.
*/
private
object StableDisplayNameFor {
const val stage1 = "CLASSPATH"
const val stage2 = "BODY"
}
private
val stage1ScriptDefinition
get() = scriptDefinitionFromTemplate(
when (programTarget) {
ProgramTarget.Project -> KotlinBuildscriptBlock::class
ProgramTarget.Settings -> KotlinSettingsBuildscriptBlock::class
ProgramTarget.Gradle -> KotlinInitscriptBlock::class
})
private
val stage2ScriptDefinition
get() = scriptDefinitionFromTemplate(
when (programTarget) {
ProgramTarget.Project -> KotlinBuildScript::class
ProgramTarget.Settings -> KotlinSettingsScript::class
ProgramTarget.Gradle -> KotlinInitScript::class
})
private
val pluginsScriptDefinition
get() = scriptDefinitionFromTemplate(KotlinPluginsBlock::class)
private
val buildscriptWithPluginsScriptDefinition
get() = scriptDefinitionFromTemplate(KotlinBuildscriptAndPluginsBlock::class)
private
fun scriptDefinitionFromTemplate(template: KClass<out Any>) =
scriptDefinitionFromTemplate(template, implicitImports)
}
fun scriptDefinitionFromTemplate(
template: KClass<out Any>,
implicitImports: List<String>
): ScriptDefinition {
val hostConfiguration = defaultJvmScriptingHostConfiguration
return ScriptDefinition.FromConfigurations(
hostConfiguration = hostConfiguration,
compilationConfiguration = ScriptCompilationConfiguration {
baseClass(template)
defaultImports(implicitImports)
hostConfiguration(hostConfiguration)
},
evaluationConfiguration = null
)
}
internal
fun requiresAccessors(programTarget: ProgramTarget, programKind: ProgramKind) =
programTarget == ProgramTarget.Project && programKind == ProgramKind.TopLevel
| apache-2.0 | f6eb56dc4119c08798629a472ea2703b | 33.167862 | 185 | 0.662398 | 5.45465 | false | false | false | false |
mozilla-mobile/focus-android | app/src/main/java/org/mozilla/focus/settings/permissions/permissionoptions/SitePermissionOptionsStorage.kt | 1 | 9933 | /* 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.settings.permissions.permissionoptions
import android.content.Context
import androidx.annotation.StringRes
import androidx.annotation.VisibleForTesting
import androidx.preference.PreferenceManager
import mozilla.components.feature.sitepermissions.SitePermissionsRules
import mozilla.components.support.ktx.android.content.isPermissionGranted
import org.mozilla.focus.R
import org.mozilla.focus.settings.permissions.AutoplayOption
import org.mozilla.focus.settings.permissions.SitePermissionOption
@Suppress("TooManyFunctions")
class SitePermissionOptionsStorage(private val context: Context) {
/**
* Return the label for Site Permission Option selected that will
* appear in Site Permissions Screen
*/
fun getSitePermissionOptionSelectedLabel(sitePermission: SitePermission): String {
return if (isAndroidPermissionGranted(sitePermission)) {
context.getString(permissionSelectedOption(sitePermission).titleId)
} else {
context.getString(R.string.phone_feature_blocked_by_android)
}
}
fun isAndroidPermissionGranted(sitePermission: SitePermission): Boolean {
return context.isPermissionGranted(sitePermission.androidPermissionsList.asIterable())
}
fun getSitePermissionLabel(sitePermission: SitePermission): String {
return when (sitePermission) {
SitePermission.CAMERA -> context.getString(R.string.preference_phone_feature_camera)
SitePermission.LOCATION -> context.getString(R.string.preference_phone_feature_location)
SitePermission.MICROPHONE -> context.getString(R.string.preference_phone_feature_microphone)
SitePermission.NOTIFICATION -> context.getString(R.string.preference_phone_feature_notification)
SitePermission.MEDIA_KEY_SYSTEM_ACCESS -> context.getString(
R.string.preference_phone_feature_media_key_system_access,
)
SitePermission.AUTOPLAY, SitePermission.AUTOPLAY_AUDIBLE, SitePermission.AUTOPLAY_INAUDIBLE ->
context.getString(R.string.preference_autoplay)
}
}
/**
* Return the available Options for a Site Permission
*/
fun getSitePermissionOptions(sitePermission: SitePermission): List<SitePermissionOption> {
return when (sitePermission) {
SitePermission.CAMERA -> listOf(
SitePermissionOption.AskToAllow(),
SitePermissionOption.Blocked(),
)
SitePermission.LOCATION -> listOf(
SitePermissionOption.AskToAllow(),
SitePermissionOption.Blocked(),
)
SitePermission.MICROPHONE -> listOf(
SitePermissionOption.AskToAllow(),
SitePermissionOption.Blocked(),
)
SitePermission.NOTIFICATION -> listOf(
SitePermissionOption.AskToAllow(),
SitePermissionOption.Blocked(),
)
SitePermission.MEDIA_KEY_SYSTEM_ACCESS -> listOf(
SitePermissionOption.AskToAllow(),
SitePermissionOption.Blocked(),
SitePermissionOption.Allowed(),
)
SitePermission.AUTOPLAY, SitePermission.AUTOPLAY_AUDIBLE, SitePermission.AUTOPLAY_INAUDIBLE ->
listOf(
AutoplayOption.AllowAudioVideo(),
AutoplayOption.BlockAudioOnly(),
AutoplayOption.BlockAudioVideo(),
)
}
}
/**
* Return the default Option for a Site Permission if the user doesn't select nothing
*/
@VisibleForTesting
internal fun getSitePermissionDefaultOption(sitePermission: SitePermission): SitePermissionOption {
return when (sitePermission) {
SitePermission.CAMERA -> SitePermissionOption.AskToAllow()
SitePermission.LOCATION -> SitePermissionOption.AskToAllow()
SitePermission.MICROPHONE -> SitePermissionOption.AskToAllow()
SitePermission.NOTIFICATION -> SitePermissionOption.AskToAllow()
SitePermission.MEDIA_KEY_SYSTEM_ACCESS -> SitePermissionOption.AskToAllow()
SitePermission.AUTOPLAY, SitePermission.AUTOPLAY_AUDIBLE, SitePermission.AUTOPLAY_INAUDIBLE ->
AutoplayOption.BlockAudioOnly()
}
}
/**
* Return the user selected Option for a Site Permission or the default one if the user doesn't
* select one
*/
internal fun permissionSelectedOption(sitePermission: SitePermission) =
when (permissionSelectedOptionByKey(getSitePermissionPreferenceId(sitePermission))) {
context.getString(R.string.pref_key_allow_autoplay_audio_video) -> AutoplayOption.AllowAudioVideo()
context.getString(R.string.pref_key_block_autoplay_audio_video) -> AutoplayOption.BlockAudioVideo()
context.getString(R.string.pref_key_allowed) -> SitePermissionOption.Allowed()
context.getString(R.string.pref_key_blocked) -> SitePermissionOption.Blocked()
context.getString(R.string.pref_key_ask_to_allow) -> SitePermissionOption.AskToAllow()
context.getString(R.string.pref_key_block_autoplay_audio_only) -> AutoplayOption.BlockAudioOnly()
else -> {
getSitePermissionDefaultOption(sitePermission)
}
}
/**
* Returns Site Permission corresponding resource ID from preference_keys
*/
@StringRes
fun getSitePermissionPreferenceId(sitePermission: SitePermission): Int {
return when (sitePermission) {
SitePermission.CAMERA -> R.string.pref_key_phone_feature_camera
SitePermission.LOCATION -> R.string.pref_key_phone_feature_location
SitePermission.MICROPHONE -> R.string.pref_key_phone_feature_microphone
SitePermission.NOTIFICATION -> R.string.pref_key_phone_feature_notification
SitePermission.AUTOPLAY -> R.string.pref_key_autoplay
SitePermission.AUTOPLAY_AUDIBLE -> R.string.pref_key_allow_autoplay_audio_video
SitePermission.AUTOPLAY_INAUDIBLE -> R.string.pref_key_block_autoplay_audio_video
SitePermission.MEDIA_KEY_SYSTEM_ACCESS -> R.string.pref_key_browser_feature_media_key_system_access
}
}
/**
* Saves the current Site Permission Option
*
* @param sitePermissionOption to be Saved
* @param sitePermission the corresponding Site Permission
*/
fun saveCurrentSitePermissionOptionInSharePref(
sitePermissionOption: SitePermissionOption,
sitePermission: SitePermission,
) {
val sharedPref = PreferenceManager.getDefaultSharedPreferences(context)
with(sharedPref.edit()) {
putString(
context.getString(getSitePermissionPreferenceId(sitePermission)),
context.getString(sitePermissionOption.prefKeyId),
)
apply()
}
}
@VisibleForTesting
internal fun permissionSelectedOptionByKey(
sitePermissionKey: Int,
): String {
val sharedPref = PreferenceManager.getDefaultSharedPreferences(context)
return sharedPref.getString(context.getString(sitePermissionKey), "") ?: ""
}
private fun getAutoplayRules(): Pair<SitePermissionsRules.AutoplayAction, SitePermissionsRules.AutoplayAction> {
return when (permissionSelectedOption(SitePermission.AUTOPLAY)) {
is AutoplayOption.AllowAudioVideo -> Pair(
SitePermissionsRules.AutoplayAction.ALLOWED,
SitePermissionsRules.AutoplayAction.ALLOWED,
)
is AutoplayOption.BlockAudioVideo -> Pair(
SitePermissionsRules.AutoplayAction.BLOCKED,
SitePermissionsRules.AutoplayAction.BLOCKED,
)
else -> Pair(
SitePermissionsRules.AutoplayAction.BLOCKED,
SitePermissionsRules.AutoplayAction.ALLOWED,
)
}
}
fun getSitePermissionsSettingsRules() = SitePermissionsRules(
notification = getSitePermissionRules(SitePermission.NOTIFICATION),
microphone = getSitePermissionRules(SitePermission.MICROPHONE),
location = getSitePermissionRules(SitePermission.LOCATION),
camera = getSitePermissionRules(SitePermission.CAMERA),
autoplayAudible = getAutoplayRules().first,
autoplayInaudible = getAutoplayRules().second,
persistentStorage = SitePermissionsRules.Action.BLOCKED,
mediaKeySystemAccess = getSitePermissionRules(SitePermission.MEDIA_KEY_SYSTEM_ACCESS),
crossOriginStorageAccess = SitePermissionsRules.Action.ASK_TO_ALLOW,
)
private fun getSitePermissionRules(sitePermission: SitePermission): SitePermissionsRules.Action {
return when (permissionSelectedOption(sitePermission)) {
is SitePermissionOption.Allowed -> SitePermissionsRules.Action.ALLOWED
is SitePermissionOption.AskToAllow -> SitePermissionsRules.Action.ASK_TO_ALLOW
is SitePermissionOption.Blocked -> SitePermissionsRules.Action.BLOCKED
else -> {
SitePermissionsRules.Action.BLOCKED
}
}
}
fun isSitePermissionNotBlocked(permissionsList: Array<String>): Boolean {
SitePermission.values().forEach { sitePermission ->
if (
sitePermission.androidPermissionsList.intersect(permissionsList.toSet()).isNotEmpty() &&
getSitePermissionRules(sitePermission) != SitePermissionsRules.Action.BLOCKED
) {
return true
}
}
return false
}
}
| mpl-2.0 | 409bf6e434940603102d951658fceb85 | 45.2 | 116 | 0.682573 | 5.768293 | false | false | false | false |
Dreamersoul/FastHub | app/src/main/java/com/fastaccess/ui/widgets/ButterKnife.kt | 1 | 3747 | package com.fastaccess.ui.widgets
import android.app.Activity
import android.app.Dialog
import android.support.v7.widget.RecyclerView.ViewHolder
import android.view.View
import kotlin.properties.ReadOnlyProperty
import kotlin.reflect.KProperty
fun <V : View> View.bindView(id: Int)
: ReadOnlyProperty<View, V> = required(id, viewFinder)
fun <V : View> Activity.bindView(id: Int)
: ReadOnlyProperty<Activity, V> = required(id, viewFinder)
fun <V : View> Dialog.bindView(id: Int)
: ReadOnlyProperty<Dialog, V> = required(id, viewFinder)
fun <V : View> ViewHolder.bindView(id: Int)
: ReadOnlyProperty<ViewHolder, V> = required(id, viewFinder)
fun <V : View> View.bindOptionalView(id: Int)
: ReadOnlyProperty<View, V?> = optional(id, viewFinder)
fun <V : View> Activity.bindOptionalView(id: Int)
: ReadOnlyProperty<Activity, V?> = optional(id, viewFinder)
fun <V : View> Dialog.bindOptionalView(id: Int)
: ReadOnlyProperty<Dialog, V?> = optional(id, viewFinder)
fun <V : View> ViewHolder.bindOptionalView(id: Int)
: ReadOnlyProperty<ViewHolder, V?> = optional(id, viewFinder)
fun <V : View> View.bindViews(vararg ids: Int)
: ReadOnlyProperty<View, List<V>> = required(ids, viewFinder)
fun <V : View> Activity.bindViews(vararg ids: Int)
: ReadOnlyProperty<Activity, List<V>> = required(ids, viewFinder)
fun <V : View> Dialog.bindViews(vararg ids: Int)
: ReadOnlyProperty<Dialog, List<V>> = required(ids, viewFinder)
fun <V : View> ViewHolder.bindViews(vararg ids: Int)
: ReadOnlyProperty<ViewHolder, List<V>> = required(ids, viewFinder)
fun <V : View> View.bindOptionalViews(vararg ids: Int)
: ReadOnlyProperty<View, List<V>> = optional(ids, viewFinder)
fun <V : View> Activity.bindOptionalViews(vararg ids: Int)
: ReadOnlyProperty<Activity, List<V>> = optional(ids, viewFinder)
fun <V : View> Dialog.bindOptionalViews(vararg ids: Int)
: ReadOnlyProperty<Dialog, List<V>> = optional(ids, viewFinder)
fun <V : View> ViewHolder.bindOptionalViews(vararg ids: Int)
: ReadOnlyProperty<ViewHolder, List<V>> = optional(ids, viewFinder)
private val View.viewFinder: View.(Int) -> View?
get() = { findViewById(it) }
private val Activity.viewFinder: Activity.(Int) -> View?
get() = { findViewById(it) }
private val Dialog.viewFinder: Dialog.(Int) -> View?
get() = { findViewById(it) }
private val ViewHolder.viewFinder: ViewHolder.(Int) -> View?
get() = { itemView.findViewById(it) }
private fun viewNotFound(id:Int, desc: KProperty<*>): Nothing =
throw IllegalStateException("View ID $id for '${desc.name}' not found.")
@Suppress("UNCHECKED_CAST")
private fun <T, V : View> required(id: Int, finder: T.(Int) -> View?)
= Lazy { t: T, desc -> t.finder(id) as V? ?: viewNotFound(id, desc) }
@Suppress("UNCHECKED_CAST")
private fun <T, V : View> optional(id: Int, finder: T.(Int) -> View?)
= Lazy { t: T, desc -> t.finder(id) as V? }
@Suppress("UNCHECKED_CAST")
private fun <T, V : View> required(ids: IntArray, finder: T.(Int) -> View?)
= Lazy { t: T, desc -> ids.map { t.finder(it) as V? ?: viewNotFound(it, desc) } }
@Suppress("UNCHECKED_CAST")
private fun <T, V : View> optional(ids: IntArray, finder: T.(Int) -> View?)
= Lazy { t: T, desc -> ids.map { t.finder(it) as V? }.filterNotNull() }
// Like Kotlin's lazy delegate but the initializer gets the target and metadata passed to it
private class Lazy<T, V>(private val initializer: (T, KProperty<*>) -> V) : ReadOnlyProperty<T, V> {
private object EMPTY
private var value: Any? = EMPTY
override fun getValue(thisRef: T, property: KProperty<*>): V {
if (value == EMPTY) {
value = initializer(thisRef, property)
}
@Suppress("UNCHECKED_CAST")
return value as V
}
}
| gpl-3.0 | a0ac30be169a7f5faf114c2da5fb9584 | 41.579545 | 100 | 0.692554 | 3.551659 | false | false | false | false |
EyeBody/EyeBody | EyeBody2/app/src/main/java/com/example/android/eyebody/management/main/FullscreenGraphViewActivity.kt | 1 | 8633 | package com.example.android.eyebody.management.main
import android.content.Intent
import android.graphics.Color
import android.graphics.DashPathEffect
import android.graphics.Paint
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import com.example.android.eyebody.R
import com.example.android.eyebody.management.main.MainManagementAdapter.Companion.stringToCalendar
import com.jjoe64.graphview.helper.DateAsXAxisLabelFormatter
import com.jjoe64.graphview.series.BarGraphSeries
import com.jjoe64.graphview.series.DataPoint
import com.jjoe64.graphview.series.LineGraphSeries
import kotlinx.android.synthetic.main.activity_fullscreen_graphview.*
import org.apache.commons.math3.analysis.MultivariateFunction
import org.apache.commons.math3.analysis.function.Abs
import org.apache.commons.math3.analysis.function.Exp
import org.apache.commons.math3.analysis.function.Pow
import org.apache.commons.math3.optim.InitialGuess
import org.apache.commons.math3.optim.MaxEval
import org.apache.commons.math3.optim.nonlinear.scalar.GoalType
import org.apache.commons.math3.optim.nonlinear.scalar.ObjectiveFunction
import org.apache.commons.math3.optim.nonlinear.scalar.noderiv.NelderMeadSimplex
import org.apache.commons.math3.optim.nonlinear.scalar.noderiv.SimplexOptimizer
import java.util.*
/**
* Created by YOON on 2017-12-10
*/
class FullscreenGraphViewActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_fullscreen_graphview)
val item = intent.extras.get("item") as MainManagementContent
val contentGraph = graphView
val weightArray = arrayListOf<DataPoint>()
var minWeight = 200.0
var maxWeight = 0.0
for (i in item.dateDataList) {
if (i.date.length == 8) {
val calendar = stringToCalendar(i.date)
val yWeight = i.weight
val uri = i.imageUri
if (calendar != null && yWeight != null) {
if (i.weight!! < minWeight)
minWeight = i.weight!!
if (i.weight!! > maxWeight)
maxWeight = i.weight!!
weightArray.add(DataPoint(calendar.time, yWeight))
}
}
}
var calendar = Calendar.getInstance()
val weightSeries = LineGraphSeries<DataPoint>(weightArray.toTypedArray())
val foodSeries = BarGraphSeries<DataPoint>(arrayOf()/*TODO DB에서 가져옴*/)
weightSeries.isDrawDataPoints = true
contentGraph.removeAllSeries()
contentGraph.addSeries(weightSeries)
//contentGraph.addSeries(foodSeries)
val arr = arrayOf(DataPoint(calendar.time, 300.0))
if (item.isInProgress) {
calendar = Calendar.getInstance()
val todayIndicatorSeries = LineGraphSeries<DataPoint>(arrayOf(DataPoint(calendar.time, 0.0)))
calendar.add(Calendar.SECOND, 1)
todayIndicatorSeries.appendData(DataPoint(calendar.time, 200.0), false, 3)
//todayIndicatorSeries.color = Color.RED
val paint = Paint()
paint.style = Paint.Style.STROKE
paint.strokeWidth = 5f
paint.pathEffect = DashPathEffect(floatArrayOf(5f, 3f), 0f)
paint.color = Color.RED
todayIndicatorSeries.isDrawAsPath = true
todayIndicatorSeries.setCustomPaint(paint)
contentGraph.addSeries(todayIndicatorSeries)
/*val nowDaySeries = BarGraphSeries<DataPoint>(a)
nowDaySeries.color = Color.RED
contentGraph.addSeries(nowDaySeries)
nowDaySeries.spacing = 1000*/
// --------------------------- estimate ===================================================================================================================
/*
(비선형 회귀)
오차함수 = y-(c/(1+e^(ax+b)))+d
(추측값)
초기값 : a = 0.01
b = -0.01 * 첫 몸무게
c = 몸무게첫날,현재날 차이 * 1/기간진행률 * 2
d = 첫값 - c/2
nelder-mead simplex 알고리즘 사용.
*/
calendar = Calendar.getInstance()
var wholeProgress = stringToCalendar(item.desireDate)!!.time.time - stringToCalendar(item.startDate)!!.time.time
var nowProgress = calendar.time.time - stringToCalendar(item.startDate)!!.time.time
if (nowProgress == 0L) nowProgress = 1
if (wholeProgress == 0L) wholeProgress = 1
val realXY = arrayOf(Pair(1, 80.0), Pair(2, 79.0), Pair(3, 78.7), Pair(4, 79.0), Pair(5, 76.2))
val guessA = 0.01
val guessB = -0.01 * item.startWeight
val guessC = (maxWeight - minWeight) / (wholeProgress/nowProgress) * 2
val guessD = item.startWeight - guessC / 2
class MyErrorFunction : MultivariateFunction {
fun realFunction(x: Int, point: DoubleArray): Double {
val a = point[0]
val b = point[1]
val c = point[2]
val d = point[3]
return (c / (1 + Exp().value(a * x + b))) + d
}
override fun value(point: DoubleArray?): Double {
point!!
val a = point[0]
val b = point[1]
val c = point[2]
val d = point[3]
var sum = 0.0
for (xy in realXY) {
val x = xy.first.toDouble()
val y = xy.second
sum += Pow().value((y - (c / (1 + Exp().value(a * x + b)))), 2.0)
}
return sum
}
}
val optimum = SimplexOptimizer(1e-1, 1e-3)
.optimize(
MaxEval(100000000),
ObjectiveFunction(MyErrorFunction()),
GoalType.MINIMIZE,
InitialGuess(
doubleArrayOf(guessA, guessB, guessC, guessD)
),
NelderMeadSimplex(4)
)
val ref = optimum.point
/*for(i in 1 until 10){
Log.d(TAG, "$i : ${MyErrorFunction().realFunction(i, ref)} when ${ref[0]} ${ref[1]} ${ref[2]} ${ref[3]}")
}*/
val estimateWeightArray = arrayListOf<DataPoint>()
var count = 1
calendar = stringToCalendar(item.startDate)
val desireCal = stringToCalendar(item.desireDate)!!
while (calendar.timeInMillis <= desireCal.timeInMillis) {
estimateWeightArray.add(DataPoint(calendar.time, MyErrorFunction().realFunction(count, ref)))
calendar.add(Calendar.DATE, 1)
count++
}
val weightEstimateSeries = LineGraphSeries<DataPoint>(estimateWeightArray.toTypedArray())
weightEstimateSeries.color = Color.YELLOW
contentGraph.addSeries(weightEstimateSeries)
// --------------------------- estimate ===================================================================================================================
}
contentGraph.gridLabelRenderer.labelFormatter = DateAsXAxisLabelFormatter(this)
contentGraph.gridLabelRenderer.numHorizontalLabels = 4
val startTime = stringToCalendar(item.startDate)
startTime?.add(Calendar.HOUR, -6)
contentGraph.viewport.setMinX(startTime?.time?.time?.toDouble() ?: -10.0)
val endTime = stringToCalendar(item.desireDate)
startTime?.add(Calendar.HOUR, +1)
contentGraph.viewport.setMaxX(endTime?.time?.time?.toDouble() ?: 10.0)
if (minWeight < maxWeight) {
maxWeight = (maxWeight.toInt() - maxWeight.toInt() % 10).toDouble() + 10
minWeight = (minWeight.toInt() - minWeight.toInt() % 10).toDouble() - 10
} else {
minWeight = 30.0
maxWeight = 100.0
}
contentGraph.viewport.setMinY(minWeight)
contentGraph.viewport.setMaxY(maxWeight)
contentGraph.viewport.isXAxisBoundsManual = true
contentGraph.viewport.isYAxisBoundsManual = true
contentGraph.gridLabelRenderer.isHumanRounding = false
}
} | mit | cc138ae28af92b78bbf088c745ec8db7 | 40.456311 | 167 | 0.568216 | 4.544439 | false | false | false | false |
MichBogus/PINZ-ws | src/main/kotlin/utils/WSRegex.kt | 1 | 576 | package utils
enum class WSRegex(val regex: String) {
/*
^ # start-of-string
(?=.*[0-9]) # a digit must occur at least once
(?=.*[a-z]) # a lower case letter must occur at least once
(?=.*[A-Z]) # an upper case letter must occur at least once
(?=\S+$) # no whitespace allowed in the entire string
.{8,} # anything, at least eight places though
$ # end-of-string
*/
PASSWORD_REGEX("^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])(?=\\S+\$).{8,}\$")
} | apache-2.0 | 4ef861cf1469bbdd20686a289fb3b997 | 40.214286 | 73 | 0.454861 | 3.622642 | false | false | false | false |
ModerateFish/component | framework/src/main/java/com/thornbirds/frameworkext/component/page/BasePageController.kt | 1 | 3387 | package com.thornbirds.frameworkext.component.page
import androidx.annotation.CallSuper
import androidx.annotation.IdRes
import com.thornbirds.component.IEventController
import com.thornbirds.frameworkext.component.route.*
/**
* @author YangLi [email protected]
*/
abstract class BasePageController(
eventController: IEventController?
) : RouterController(eventController) {
private var mActivityController: BaseActivityController? = null
private var mPageParams: IPageParams? = null
private var mPage: BasePage<*, BasePageController>? = null
private val mSubPageRouter = FramePageRouter(this)
protected fun <T> findViewById(@IdRes idRes: Int): T {
return mActivityController?.findViewById(idRes) ?: throw NullPointerException()
}
protected fun registerSubRoute(path: String, creator: (params: IPageParams?) -> BasePageEntry) {
mSubPageRouter.registerRoute(path, object : PageCreator {
override fun create(params: IPageParams?): PageEntry {
return creator(params) as PageEntry
}
})
}
fun setActivityController(controller: BaseActivityController?, params: IPageParams?) {
mActivityController = controller
mPageParams = params
}
protected abstract fun onSetupRouters()
override val router: IPageRouter<RouterController>? = mSubPageRouter
override val parentRouter: IPageRouter<RouterController>?
get() = mActivityController?.router
override fun exitRouter(): Boolean {
return parentRouter?.popPage(this) == true
}
protected abstract fun onCreatePage(pageParams: IPageParams?): BasePage<*, *>?
@CallSuper
override fun onCreate() {
onSetupRouters()
mPage = onCreatePage(mPageParams) as BasePage<*, BasePageController>
mPage!!.setController(this)
mPage!!.setupView()
}
@CallSuper
override fun onStart() {
mPage!!.startView()
mSubPageRouter.dispatchStart()
}
@CallSuper
override fun onStop() {
mPage!!.stopView()
mSubPageRouter.dispatchStop()
}
@CallSuper
override fun onDestroy() {
mPage?.release()
mSubPageRouter.dispatchDestroy()
}
override fun onBackPressed(): Boolean {
if (mSubPageRouter.dispatchBackPress()) {
return true
}
return mPage!!.onBackPressed()
}
protected class BasePageEntry(
private val controller: BasePageController,
private val pageParams: IPageParams?
) : IPageEntry<BasePageController> {
override fun matchController(controller: IRouterController): Boolean {
return this.controller == controller
}
override fun performCreate(parentController: BasePageController) {
controller.setActivityController(parentController.mActivityController, pageParams)
controller.performCreate()
}
override fun performStart() {
controller.performStart()
}
override fun performStop() {
controller.performStop()
}
override fun performDestroy() {
controller.performDestroy()
controller.setActivityController(null, null)
}
override fun performBackPress(): Boolean {
return controller.performBackPressed()
}
}
} | apache-2.0 | 91d7808ecb971afca115f10a99927d57 | 28.46087 | 100 | 0.666962 | 5.36767 | false | false | false | false |
pyamsoft/home-button | app/src/main/java/com/pyamsoft/homebutton/settings/AppSettings.kt | 1 | 9882 | /*
* Copyright 2021 Peter Kenji Yamanaka
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.pyamsoft.homebutton.settings
import android.content.Intent
import android.os.Build
import android.os.Bundle
import android.provider.Settings
import android.view.View
import androidx.annotation.CheckResult
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.material.*
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Home
import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import androidx.fragment.app.Fragment
import androidx.lifecycle.lifecycleScope
import com.pyamsoft.homebutton.R
import com.pyamsoft.homebutton.main.MainComponent
import com.pyamsoft.homebutton.main.MainPage
import com.pyamsoft.homebutton.main.ToolbarViewModeler
import com.pyamsoft.homebutton.main.TopLevelMainPage
import com.pyamsoft.pydroid.core.requireNotNull
import com.pyamsoft.pydroid.inject.Injector
import com.pyamsoft.pydroid.theme.keylines
import com.pyamsoft.pydroid.ui.navigator.FragmentNavigator
import com.pyamsoft.pydroid.ui.preference.*
import com.pyamsoft.pydroid.ui.settings.SettingsFragment
import com.pyamsoft.pydroid.util.PermissionRequester
import javax.inject.Inject
import timber.log.Timber
class AppSettings : SettingsFragment(), FragmentNavigator.Screen<MainPage> {
override val hideClearAll: Boolean = false
override val hideUpgradeInformation: Boolean = false
@JvmField @Inject internal var toolbarViewModel: ToolbarViewModeler? = null
@JvmField @Inject internal var viewModel: SettingsViewModel? = null
@JvmField @Inject internal var notificationPermissions: PermissionRequester? = null
private var permissionRequester: PermissionRequester.Requester? = null
private fun syncPermissionState() {
viewModel.requireNotNull().handleSyncPermissionState(scope = viewLifecycleOwner.lifecycleScope)
}
private fun openNotificationSettings(channelId: String) {
if (Build.VERSION.SDK_INT >= 26) {
val act = requireActivity()
val settingsIntent =
Intent(Settings.ACTION_CHANNEL_NOTIFICATION_SETTINGS).apply {
putExtra(Settings.EXTRA_APP_PACKAGE, act.packageName)
if (channelId.isNotBlank()) {
putExtra(Settings.EXTRA_CHANNEL_ID, channelId)
}
}
act.startActivity(settingsIntent)
} else {
Timber.w("We are not 26, what are you doing here?")
}
}
private fun handleOpenSettings() {
viewModel
.requireNotNull()
.handleOpenSettings(
scope = viewLifecycleOwner.lifecycleScope,
onOpenSettings = { openNotificationSettings(it) },
)
}
private fun handleNotificationChanged(enabled: Boolean) {
viewModel
.requireNotNull()
.handleNotificationChanged(
scope = viewLifecycleOwner.lifecycleScope,
enabled = enabled,
)
}
@Composable
private fun settingsWithPermission(
state: SettingsViewState,
): List<Preferences.Item> {
return listOf(
if (Build.VERSION.SDK_INT >= 26) {
preference(
name = stringResource(R.string.priority_title),
summary = stringResource(R.string.priority_summary_on),
icon = Icons.Filled.Home,
onClick = { handleOpenSettings() },
)
} else {
val isChecked = state.isNotificationEnabled
switchPreference(
name = stringResource(R.string.priority_title),
summary =
stringResource(
if (isChecked) R.string.priority_summary_on
else R.string.priority_summary_off,
),
icon = Icons.Filled.Home,
checked = isChecked,
onCheckedChanged = { handleNotificationChanged(it) },
)
},
)
}
@Composable
private fun settingsWithoutPermission(
onRequestPermission: () -> Unit,
): List<Preferences.Item> {
val appName = stringResource(R.string.app_name)
return listOf(
customPreference(
isEnabled = true,
) { isEnabled ->
Column(
modifier =
Modifier.fillMaxWidth().padding(horizontal = MaterialTheme.keylines.content),
) {
Text(
modifier = Modifier.padding(bottom = MaterialTheme.keylines.baseline),
text =
// Break the long string up this way so it all fits on screen
"You must allow Notification permissions." +
" " +
"This will allow $appName to create an entry" +
" " +
"in your Notification Pull-Down menu that will take you back to the" +
" " +
"Home screen whenever you click it.",
style =
MaterialTheme.typography.body2.copy(
color =
MaterialTheme.colors.onBackground.copy(
alpha = ContentAlpha.medium,
)),
)
Box(
modifier = Modifier.fillMaxWidth(),
contentAlignment = Alignment.Center,
) {
Button(
onClick = { onRequestPermission() },
enabled = isEnabled,
) {
Text(
text = "Allow $appName Notifications",
)
}
}
}
},
)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
Injector.obtainFromActivity<MainComponent>(requireActivity())
.plusAppSettings()
.create()
.inject(this)
// Do this as early as possible because of Android Lifecycle requirements
permissionRequester?.unregister()
permissionRequester =
notificationPermissions.requireNotNull().registerRequester(this) { granted ->
Timber.d("Notification permission granted: $granted")
syncPermissionState()
}
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
toolbarViewModel.requireNotNull().restoreState(savedInstanceState)
viewModel.requireNotNull().also { vm ->
vm.restoreState(savedInstanceState)
vm.bind(scope = viewLifecycleOwner.lifecycleScope)
}
}
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
toolbarViewModel?.saveState(outState)
viewModel?.saveState(outState)
}
override fun onResume() {
super.onResume()
syncPermissionState()
}
override fun onDestroyView() {
super.onDestroyView()
toolbarViewModel = null
viewModel = null
notificationPermissions = null
permissionRequester?.unregister()
permissionRequester = null
}
@Composable
override fun customPostPreferences(): List<Preferences> {
return emptyList()
}
@Composable
override fun customPrePreferences(): List<Preferences> {
val state = viewModel.requireNotNull().state()
val hasPermission = state.hasNotificationPermission
return if (hasPermission == null) {
// Show a loading spinner while we are deciding if we need permission or not
listOf(
customPreference {
Box(
modifier = Modifier.padding(MaterialTheme.keylines.baseline),
) {
CircularProgressIndicator()
}
},
)
} else {
listOf(
preferenceGroup(
name = "Notification Settings",
preferences =
if (hasPermission) settingsWithPermission(state)
else
settingsWithoutPermission(
onRequestPermission = {
Timber.d("Request notification permissions")
permissionRequester.requireNotNull().requestPermissions()
},
),
),
)
}
}
@Composable
override fun customBottomItemMargin(): Dp {
// No additional bottom padding
return 0.dp
}
@Composable
override fun customTopItemMargin(): Dp {
// Additional top padding based on the size of the measured Top App Bar
val state = toolbarViewModel.requireNotNull().state()
val density = LocalDensity.current
val topBarHeight = state.topBarHeight
return remember(topBarHeight) { density.run { topBarHeight.toDp() } }
}
override fun getScreenId(): MainPage {
return TopLevelMainPage.Home
}
companion object {
@JvmStatic
@CheckResult
internal fun newInstance(): Fragment {
return AppSettings().apply { arguments = Bundle().apply {} }
}
}
}
| apache-2.0 | e0b85a89523d2f943825f4e1aec2ca88 | 31.94 | 99 | 0.643594 | 5.225806 | false | false | false | false |
clhols/zapr | app/src/main/java/dk/youtec/zapr/backend/OkHttpClientFactory.kt | 1 | 3174 | package dk.youtec.zapr.backend
import android.content.Context
import android.util.Log
import java.io.File
import java.io.IOException
import java.util.concurrent.TimeUnit
import okhttp3.Cache
import okhttp3.Interceptor
import okhttp3.OkHttpClient
import okhttp3.Response
object OkHttpClientFactory {
private val TAG = OkHttpClientFactory::class.java.simpleName
private val OK_HTTP_CACHE_DIR = "dk.youtec.zapr.okhttp.cache"
private val SIZE_OF_CACHE = (32 * 1024 * 1024).toLong() // 32 MiB
private var mClient: OkHttpClient? = null
/**
* It is an error to have multiple caches accessing the same cache directory simultaneously.
* Most applications should call new OkHttpClient() exactly once, configure it with their cache,
* and use that same instance everywhere. Otherwise the two cache instances will stomp on each other,
* corrupt the response cache, and possibly crash your program.
*
*
* https://github.com/square/okhttp/wiki/Recipes#response-caching
* @return singleTon instance of the OkHttpClient.
*/
fun getInstance(context: Context): OkHttpClient {
if (mClient == null) {
val builder = OkHttpClient.Builder()
builder.connectTimeout(30, TimeUnit.SECONDS)
builder.writeTimeout(30, TimeUnit.SECONDS)
builder.readTimeout(30, TimeUnit.SECONDS)
builder.addNetworkInterceptor(LoggingInterceptor())
//enableCache(context, builder, OK_HTTP_CACHE_DIR)
mClient = builder.build()
return mClient as OkHttpClient
} else {
return mClient as OkHttpClient
}
}
private fun enableCache(context: Context, builder: OkHttpClient.Builder, nameOfCacheDir: String) {
try {
val cacheDirectory = File(context.cacheDir.absolutePath, nameOfCacheDir)
val responseCache = Cache(cacheDirectory, SIZE_OF_CACHE)
builder.cache(responseCache)
} catch (e: Exception) {
Log.d(TAG, "Unable to set http cache", e)
}
}
fun clearCache() {
if (mClient != null) {
try {
(mClient as OkHttpClient).cache().evictAll()
} catch (e: IOException) {
Log.e(TAG, e.message, e)
}
}
}
private class LoggingInterceptor : Interceptor {
@Throws(IOException::class)
override fun intercept(chain: Interceptor.Chain): Response {
val request = chain.request()
val t1 = System.nanoTime()
//L.v(TAG, String.format("Sending request %s on %s%n%s", request.url(), chain.connection(), request.headers()));
Log.v(TAG, String.format("Sending request %s", request.url()))
val response = chain.proceed(request)
val t2 = System.nanoTime()
//L.v(TAG, String.format("Received response for %s in %.1fms%n%s", response.request().url(), (t2 - t1) / 1e6d, response.headers()));
Log.v(TAG, String.format("Received response for %s in %.1fms%n", response.request().url(), (t2 - t1) / 1e6))
return response
}
}
}
| mit | e5369de58552f73bd4abcdf4cb7dde3d | 33.879121 | 144 | 0.632325 | 4.353909 | false | false | false | false |
android/architecture-samples | app/src/main/java/com/example/android/architecture/blueprints/todoapp/addedittask/AddEditTaskViewModel.kt | 1 | 4964 | /*
* Copyright (C) 2019 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.architecture.blueprints.todoapp.addedittask
import androidx.lifecycle.SavedStateHandle
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.android.architecture.blueprints.todoapp.R
import com.example.android.architecture.blueprints.todoapp.TodoDestinationsArgs
import com.example.android.architecture.blueprints.todoapp.data.Result.Success
import com.example.android.architecture.blueprints.todoapp.data.Task
import com.example.android.architecture.blueprints.todoapp.data.source.TasksRepository
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
import javax.inject.Inject
/**
* UiState for the Add/Edit screen
*/
data class AddEditTaskUiState(
val title: String = "",
val description: String = "",
val isTaskCompleted: Boolean = false,
val isLoading: Boolean = false,
val userMessage: Int? = null,
val isTaskSaved: Boolean = false
)
/**
* ViewModel for the Add/Edit screen.
*/
@HiltViewModel
class AddEditTaskViewModel @Inject constructor(
private val tasksRepository: TasksRepository,
savedStateHandle: SavedStateHandle
) : ViewModel() {
private val taskId: String? = savedStateHandle[TodoDestinationsArgs.TASK_ID_ARG]
// A MutableStateFlow needs to be created in this ViewModel. The source of truth of the current
// editable Task is the ViewModel, we need to mutate the UI state directly in methods such as
// `updateTitle` or `updateDescription`
private val _uiState = MutableStateFlow(AddEditTaskUiState())
val uiState: StateFlow<AddEditTaskUiState> = _uiState.asStateFlow()
init {
if (taskId != null) {
loadTask(taskId)
}
}
// Called when clicking on fab.
fun saveTask() {
if (uiState.value.title.isEmpty() || uiState.value.description.isEmpty()) {
_uiState.update {
it.copy(userMessage = R.string.empty_task_message)
}
return
}
if (taskId == null) {
createNewTask()
} else {
updateTask()
}
}
fun snackbarMessageShown() {
_uiState.update {
it.copy(userMessage = null)
}
}
fun updateTitle(newTitle: String) {
_uiState.update {
it.copy(title = newTitle)
}
}
fun updateDescription(newDescription: String) {
_uiState.update {
it.copy(description = newDescription)
}
}
private fun createNewTask() = viewModelScope.launch {
val newTask = Task(uiState.value.title, uiState.value.description)
tasksRepository.saveTask(newTask)
_uiState.update {
it.copy(isTaskSaved = true)
}
}
private fun updateTask() {
if (taskId == null) {
throw RuntimeException("updateTask() was called but task is new.")
}
viewModelScope.launch {
val updatedTask = Task(
title = uiState.value.title,
description = uiState.value.description,
isCompleted = uiState.value.isTaskCompleted,
id = taskId
)
tasksRepository.saveTask(updatedTask)
_uiState.update {
it.copy(isTaskSaved = true)
}
}
}
private fun loadTask(taskId: String) {
_uiState.update {
it.copy(isLoading = true)
}
viewModelScope.launch {
tasksRepository.getTask(taskId).let { result ->
if (result is Success) {
val task = result.data
_uiState.update {
it.copy(
title = task.title,
description = task.description,
isTaskCompleted = task.isCompleted,
isLoading = false
)
}
} else {
_uiState.update {
it.copy(isLoading = false)
}
}
}
}
}
}
| apache-2.0 | fa09b44755b1c5bdaa4dc4b6fa1d3e1b | 31.233766 | 99 | 0.619662 | 4.805421 | false | false | false | false |
Vavassor/Tusky | app/src/main/java/com/keylesspalace/tusky/view/EditTextTyped.kt | 1 | 2786 | /* Copyright 2018 Conny Duck
*
* This file is a part of Tusky.
*
* 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.
*
* Tusky 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 Tusky; if not,
* see <http://www.gnu.org/licenses>. */
package com.keylesspalace.tusky.view
import android.content.Context
import androidx.emoji.widget.EmojiEditTextHelper
import androidx.core.view.inputmethod.EditorInfoCompat
import androidx.core.view.inputmethod.InputConnectionCompat
import androidx.appcompat.widget.AppCompatMultiAutoCompleteTextView
import android.text.InputType
import android.text.method.KeyListener
import android.util.AttributeSet
import android.view.inputmethod.EditorInfo
import android.view.inputmethod.InputConnection
class EditTextTyped @JvmOverloads constructor(context: Context,
attributeSet: AttributeSet? = null)
: AppCompatMultiAutoCompleteTextView(context, attributeSet) {
private var onCommitContentListener: InputConnectionCompat.OnCommitContentListener? = null
private val emojiEditTextHelper: EmojiEditTextHelper = EmojiEditTextHelper(this)
init {
//fix a bug with autocomplete and some keyboards
val newInputType = inputType and (inputType xor InputType.TYPE_TEXT_FLAG_AUTO_COMPLETE)
inputType = newInputType
super.setKeyListener(getEmojiEditTextHelper().getKeyListener(keyListener))
}
override fun setKeyListener(input: KeyListener) {
super.setKeyListener(getEmojiEditTextHelper().getKeyListener(input))
}
fun setOnCommitContentListener(listener: InputConnectionCompat.OnCommitContentListener) {
onCommitContentListener = listener
}
override fun onCreateInputConnection(editorInfo: EditorInfo): InputConnection {
val connection = super.onCreateInputConnection(editorInfo)
return if (onCommitContentListener != null) {
EditorInfoCompat.setContentMimeTypes(editorInfo, arrayOf("image/*"))
getEmojiEditTextHelper().onCreateInputConnection(InputConnectionCompat.createWrapper(connection, editorInfo,
onCommitContentListener!!), editorInfo)!!
} else {
connection
}
}
private fun getEmojiEditTextHelper(): EmojiEditTextHelper {
return emojiEditTextHelper
}
}
| gpl-3.0 | 92e9c70ed23fb0bd2b0e098e2ff406ac | 41.861538 | 120 | 0.751615 | 5.378378 | false | false | false | false |
mixitconf/mixit | src/main/kotlin/mixit/ticket/handler/TicketDto.kt | 1 | 1201 | package mixit.ticket.handler
import mixit.security.model.Cryptographer
import mixit.ticket.model.Ticket
import mixit.ticket.model.TicketType
import java.time.Instant
data class TicketDto(
val email: String,
val number: String,
val firstname: String?,
val lastname: String,
val lotteryRank: Int?,
val login: String?,
val externalId: String?,
val type: TicketType,
val createdAt: Instant
) {
constructor(ticket: Ticket, cryptographer: Cryptographer) : this(
number = ticket.number.isNotBlank().let { cryptographer.decrypt(ticket.number)!! },
email = ticket.encryptedEmail.isNotBlank().let { cryptographer.decrypt(ticket.encryptedEmail)!! },
firstname = ticket.firstname?.isNotBlank().let { cryptographer.decrypt(ticket.firstname) },
lastname = ticket.lastname.isNotBlank().let { cryptographer.decrypt(ticket.lastname)!! },
lotteryRank = ticket.lotteryRank,
login = ticket.login?.isNotBlank().let { cryptographer.decrypt(ticket.login) },
externalId = ticket.externalId?.isNotBlank().let { cryptographer.decrypt(ticket.externalId) },
createdAt = ticket.createdAt,
type = ticket.type
)
}
| apache-2.0 | 69f39b490c51877d4613f76c723b5bd6 | 39.033333 | 106 | 0.705246 | 4.464684 | false | false | false | false |
NooAn/bytheway | app/src/main/java/ru/a1024bits/bytheway/viewmodel/DisplayUsersViewModel.kt | 1 | 11238 | package ru.a1024bits.bytheway.viewmodel
import android.arch.lifecycle.MutableLiveData
import android.util.Log
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.crash.FirebaseCrash
import com.google.firebase.firestore.QuerySnapshot
import io.reactivex.Single
import ru.a1024bits.bytheway.algorithm.SearchTravelers
import ru.a1024bits.bytheway.model.FireBaseNotification
import ru.a1024bits.bytheway.model.Response
import ru.a1024bits.bytheway.model.User
import ru.a1024bits.bytheway.model.contains
import ru.a1024bits.bytheway.repository.Filter
import ru.a1024bits.bytheway.repository.MAX_AGE
import ru.a1024bits.bytheway.repository.UserRepository
import ru.a1024bits.bytheway.util.Constants.END_DATE
import ru.a1024bits.bytheway.util.Constants.FIRST_INDEX_CITY
import ru.a1024bits.bytheway.util.Constants.LAST_INDEX_CITY
import ru.a1024bits.bytheway.util.Constants.START_DATE
import java.util.*
import javax.inject.Inject
import kotlin.collections.ArrayList
/**
* Created by andrey.gusenkov on 25/09/2017.
*/
class DisplayUsersViewModel @Inject constructor(private var userRepository: UserRepository?) : BaseViewModel(), FilterAndInstallListener {
val response: MutableLiveData<Response<List<User>>> = MutableLiveData()
val liveData = MutableLiveData<Int>()
var yearsOldUsers = (0..MAX_AGE).mapTo(ArrayList()) { it.toString() }
override var filter = Filter()
companion object {
const val TAG = "LOG UserRepository"
const val MIN_LIMIT = 1
}
fun getAllUsers(f: Filter?) {
try {
this.filter = f ?: filter
if (users.size != 0 && filter.isNotDefault()) {
response.postValue(Response.success(users))
} else
userRepository?.installAllUsers(this)
} catch (e: Exception) {
e.printStackTrace()
FirebaseCrash.report(e)
loadingStatus.postValue(false)
}
}
val TWO_MONTHS_IN_MLSECONDS: Long = 5270400000
override fun filterAndInstallUsers(vararg snapshots: QuerySnapshot) {
disposables.add(Single.create<MutableList<User>> { stream ->
try {
val result: MutableList<User> = ArrayList()
snapshots.map {
for (document in it) {
try {
//FIXME надо попытаться вынести это в условие запроса для сервера.
if (document.exists()) {
val user = document.toObject(User::class.java)
if (user.cities.size > 0
&& user.id != FirebaseAuth.getInstance().currentUser?.uid) {
result.add(user)
}
}
} catch (e: Exception) {
e.printStackTrace()
FirebaseCrash.report(e)
}
}
}
filterUsersByOptions(result, filter)
stream.onSuccess(result)
} catch (exp: Exception) {
stream.onError(exp)
}
}
.subscribeOn(getBackgroundScheduler())
.timeout(TIMEOUT_SECONDS, timeoutUnit, getBackgroundScheduler())
.retry(2)
.doOnSubscribe({ loadingStatus.postValue(true) })
.doAfterTerminate({ loadingStatus.postValue(false) })
.subscribe({ resultUsers ->
Log.e("LOG", "count users: ${resultUsers.size}")
if (users.size == 0)
users.addAll(resultUsers)
response.postValue(Response.success(resultUsers))
},
{ throwable -> response.postValue(Response.error(throwable)) }))
}
var users: ArrayList<User> = ArrayList<User>()
override fun onFailure(e: Throwable) {
response.postValue(Response.error(e))
}
fun sendUserData(map: HashMap<String, Any>, id: String) {
userRepository?.let {
loadingStatus.value = true
disposables.add(it.changeUserProfile(map, id)
.timeout(TIMEOUT_SECONDS, timeoutUnit, getBackgroundScheduler())
.retry(2)
.doAfterTerminate({ loadingStatus.postValue(false) })
.subscribe(
{ },
{ t ->
response.postValue(Response.error(t))
}
))
}
}
fun getSearchUsers(paramSearch: Filter) {
userRepository?.let {
loadingStatus.value = true
disposables.add(it.getRealUsers()
.subscribeOn(getBackgroundScheduler())
.timeout(TIMEOUT_SECONDS, timeoutUnit, getBackgroundScheduler())
.retry(2)
.cache()
.filter { user -> user.cities.size > 0 }
.map { user ->
// run search algorithm.
val search = SearchTravelers(filter = paramSearch, user = user)
user.percentsSimilarTravel = search.getEstimation()
user
}
.filter { user ->
user.percentsSimilarTravel > MIN_LIMIT && user.id != FirebaseAuth.getInstance().currentUser?.uid
}
.toSortedList(compareByDescending { l -> l.percentsSimilarTravel }) // перед отправкой сортируем по степени похожести маршрута.
.observeOn(getMainThreadScheduler())
.doOnSuccess { Log.e("LOG 2", Thread.currentThread().name) }
.doAfterTerminate({ loadingStatus.postValue(false) })
.subscribe(
{ list ->
response.postValue(Response.success(list))
},
{ throwable -> response.postValue(Response.error(throwable)) }
)
)
}
}
fun getTextFromDates(date: Long?, months: Array<String>): String {
val calendarStartDate = Calendar.getInstance()
calendarStartDate.timeInMillis = date ?: 0L
return getTextDateDayAndMonth(calendarStartDate, months)
}
fun getTextFromDates(startDate: Long?, endDate: Long?, months: Array<String>): String {
val toWord = " - "
val calendarStartDate = Calendar.getInstance()
calendarStartDate.timeInMillis = startDate ?: 0L
val calendarEndDate = Calendar.getInstance()
calendarEndDate.timeInMillis = endDate ?: 0L
if (calendarEndDate.timeInMillis == 0L)
return getTextDateDayAndMonth(calendarStartDate, months)
if (calendarStartDate.timeInMillis == 0L)
return getTextDateDayAndMonth(calendarEndDate, months)
var yearStart = ""
var yearEnd = ""
if (calendarStartDate.get(Calendar.YEAR) != calendarEndDate.get(Calendar.YEAR)) {
yearStart = calendarStartDate.get(Calendar.YEAR).toString()
yearEnd = calendarEndDate.get(Calendar.YEAR).toString()
}
return getTextDate(calendarStartDate, yearStart, months) + toWord + getTextDate(calendarEndDate, yearEnd, months)
}
fun filterUsersByString(primaryQuery: String = "", primaryList: MutableList<User>): MutableList<User> {
return primaryList.filterTo(ArrayList()) {
it.contains(primaryQuery)
}
}
private fun getTextDate(calendarStartDate: Calendar, yearStart: String, months: Array<String>): String {
return StringBuilder("").append(getTextDateDayAndMonth(calendarStartDate, months))
.append(" ")
.append(yearStart)
.toString()
}
private fun getTextDateDayAndMonth(calendarStartDate: Calendar, months: Array<String>): String {
return StringBuilder("").append(calendarStartDate.get(Calendar.DAY_OF_MONTH))
.append(" ")
.append(months[calendarStartDate.get(Calendar.MONTH)])
.toString()
}
fun filterUsersByOptions(resultUsers: MutableList<User>, filter: Filter) {
resultUsers.retainAll {
checkBudget(filter, it) && checkAge(filter, it) && checkSex(filter, it) && checkFirstCity(filter, it)
&& checkEndCity(filter, it) && checkMethod(filter, it) && checkStartDate(filter, it) && checkEndDate(filter, it)
}
}
private fun checkEndCity(filter: Filter, user: User) =
((filter.endCity.isEmpty()) || (user.cities[LAST_INDEX_CITY]?.contains(filter.endCity, true) == true))
private fun checkFirstCity(filter: Filter, user: User) =
((filter.startCity.isEmpty()) || (user.cities[FIRST_INDEX_CITY]?.contains(filter.startCity, true) == true))
private fun checkSex(filter: Filter, user: User) =
((filter.sex == 0) || (user.sex == filter.sex))
private fun checkAge(filter: Filter, user: User) =
((user.age >= filter.startAge && user.age <= filter.endAge))
private fun checkBudget(filter: Filter, user: User) =
(!((filter.startBudget >= 0) && (filter.endBudget > 0)) ||
(user.budget >= filter.startBudget && user.budget <= filter.endBudget))
private fun checkMethod(filter: Filter, user: User) =
(filter.method.count { it.value } == 0) || (filter.method.count { it.value && user.method[it.key] == true } > 0)
private fun checkEndDate(filter: Filter, user: User) =
(filter.endDate == 0L || (user.dates[END_DATE] != null && user.dates[END_DATE] != 0L &&
user.dates[END_DATE] ?: 0 <= filter.endDate))
private fun checkStartDate(filter: Filter, user: User) =
(filter.startDate == 0L || (user.dates[START_DATE] != null && user.dates[START_DATE] != 0L &&
user.dates[START_DATE] ?: 0L >= filter.startDate))
fun sendNotifications(ids: String, notification: FireBaseNotification) {
FirebaseCrash.log("send Notification")
userRepository?.let {
disposables.add(it.sendNotifications(ids, notification)
.timeout(TIMEOUT_SECONDS, timeoutUnit)
.retry(2)
.subscribeOn(getBackgroundScheduler())
.subscribe(
{ Log.e("LOG", "notify complete") },
{ t ->
FirebaseCrash.report(t)
Log.e("LOG view model", "notify", t)
}
)
)
}
}
}
private fun Filter.isNotDefault(): Boolean = (this == Filter())
interface FilterAndInstallListener {
var filter: Filter
fun filterAndInstallUsers(vararg snapshots: QuerySnapshot)
fun onFailure(e: Throwable)
} | mit | a067b057ad98638ad7d38eced60038f9 | 41.685824 | 147 | 0.571454 | 4.818339 | false | false | false | false |
alyphen/guildford-game-jam-2016 | core/src/main/kotlin/com/seventh_root/guildfordgamejam/system/FinishSystem.kt | 1 | 4782 | package com.seventh_root.guildfordgamejam.system
import com.badlogic.ashley.core.Entity
import com.badlogic.ashley.core.Family
import com.badlogic.ashley.systems.IteratingSystem
import com.badlogic.gdx.graphics.Color
import com.badlogic.gdx.utils.Timer
import com.seventh_root.guildfordgamejam.GuildfordGameJam
import com.seventh_root.guildfordgamejam.component.*
import java.util.*
class FinishSystem(val game: GuildfordGameJam): IteratingSystem(Family.all(PlayerComponent::class.java, VelocityComponent::class.java, GravityComponent::class.java, PositionComponent::class.java, CollectedColorsComponent::class.java).get()) {
val grappleFamily: Family = Family.all(GrappleComponent::class.java, ColorComponent::class.java).get()
val finishFamily: Family = Family.all(FinishComponent::class.java, PositionComponent::class.java).get()
var finishEffectCounter: Float = 5F
override fun processEntity(entity: Entity, deltaTime: Float) {
val finishEntity = engine.getEntitiesFor(finishFamily).firstOrNull()
if (finishEntity != null) {
if (!finish.get(finishEntity).finished) {
if (position.get(finishEntity).x == position.get(entity).x && position.get(finishEntity).y == position.get(entity).y) {
val colorsNotCollected = mutableListOf<Color>()
for (grapple in engine.getEntitiesFor(grappleFamily).filter { grapple -> color.get(grapple).color != Color.WHITE }) {
colorsNotCollected.add(color.get(grapple).color)
}
colorsNotCollected.removeAll(collectedColors.get(entity).colors)
if (colorsNotCollected.isEmpty()) {
game.highScoreEntryScreen.time = timer.get(entity).time
finish(finishEntity)
finish.get(finishEntity).finished = true
}
} else {
val colorsNotCollected = mutableListOf<Color>()
for (grapple in engine.getEntitiesFor(grappleFamily).filter { grapple -> color.get(grapple).color != Color.WHITE }) {
colorsNotCollected.add(color.get(grapple).color)
}
colorsNotCollected.removeAll(collectedColors.get(entity).colors)
if (colorsNotCollected.isEmpty()) {
if (finishEffectCounter > 5F) {
finishEffectCounter = 5F
}
finishEffectCounter -= deltaTime
if (finishEffectCounter <= 0) {
val ef = Entity()
ef.add(RadiusComponent(1F))
ef.add(PositionComponent(position.get(finishEntity).x, position.get(finishEntity).y))
ef.add(RadiusScalingComponent(300F))
ef.add(FinishEffectComponent())
ef.add(ColorComponent(Color.WHITE))
engine.addEntity(ef)
finishEffectCounter = 5F
}
}
}
}
}
}
fun finish(finish: Entity) {
finishEffectCounter = Float.MAX_VALUE
var delay = 0F
val random = Random()
for (grapple in engine.getEntitiesFor(grappleFamily).filter { grapple -> color.get(grapple).color != Color.WHITE }) {
Timer.schedule(object: Timer.Task() {
override fun run() {
val ef = Entity()
ef.add(RadiusComponent(1F))
ef.add(PositionComponent(position.get(finish).x, position.get(finish).y))
ef.add(RadiusScalingComponent(600F))
ef.add(FinishEffectComponent())
ef.add(ColorComponent(color.get(grapple).color))
engine.addEntity(ef)
when (random.nextInt(4)) {
0 -> game.mainScreen.pluck1Sound.play()
1 -> game.mainScreen.pluck2Sound.play()
2 -> game.mainScreen.pluck3Sound.play()
3 -> game.mainScreen.pluck4Sound.play()
}
}
}, delay)
delay += 0.2F
}
Timer.schedule(object: Timer.Task() {
override fun run() {
game.mainScreen.levelCompletePlucks.play()
}
}, delay)
delay += 2F
Timer.schedule(object: Timer.Task() {
override fun run() {
game.menuScreen.reloadLevels()
game.screen = game.highScoreEntryScreen
}
}, delay)
}
} | apache-2.0 | 5fd6af5cad515adeb3b067af3add05d2 | 49.347368 | 242 | 0.554789 | 5.07105 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.