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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
facebook/litho | litho-core-kotlin/src/main/kotlin/com/facebook/litho/KState.kt | 1 | 7207 | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* 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.facebook.litho
import com.facebook.litho.annotations.Hook
/**
* Declares a state variable within a Component. The initializer will provide the initial value if
* it hasn't already been initialized in a previous render of the Component.
*
* Assignments to the state variables are allowed only in [updateState] block to batch updates and
* trigger a UI layout only once per batch.
*/
@Hook
fun <T> ComponentScope.useState(initializer: () -> T): State<T> {
val globalKey = context.globalKey
val hookIndex = useStateIndex++
val treeState: TreeState =
renderStateContext?.treeState
?: throw IllegalStateException("Cannot create state outside of layout calculation")
val isNestedTreeContext = context.isNestedTreeContext
val kState = treeState.getStateContainer(globalKey, isNestedTreeContext) as KStateContainer?
if (kState == null || kState.mStates.size <= hookIndex) {
// The initial state was not computed yet. let's create it and put it in the state
val state =
treeState.createOrGetInitialHookState(
globalKey, hookIndex, initializer, isNestedTreeContext)
treeState.addStateContainer(globalKey, state, isNestedTreeContext)
context.scopedComponentInfo.stateContainer = state
return State(context, hookIndex, state.mStates[hookIndex] as T)
} else {
context.scopedComponentInfo.stateContainer = kState
}
// Only need to mark this global key as seen once
if (hookIndex == 0) {
treeState.keepStateContainerForGlobalKey(globalKey, isNestedTreeContext)
}
return State(context, hookIndex, kState.mStates[hookIndex] as T)
}
/** Interface with which a component gets the value from a state or updates it. */
class State<T>
internal constructor(
private val context: ComponentContext,
private val hookStateIndex: Int,
val value: T
) {
/**
* Updates this state value and enqueues a new layout calculation reflecting it to execute in the
* background.
*/
fun update(newValue: T) {
if (canSkip(newValue)) {
return
}
context.updateHookStateAsync(context.globalKey, HookUpdaterValue(newValue))
}
/**
* Uses [newValueFunction] to update this state value using the previous state value, and enqueues
* a new layout calculation reflecting it to execute in the background.
*
* [newValueFunction] receives the current state value and can use it to compute the update: this
* is useful when there could be other enqueued updates that may not have been applied yet.
*
* For example, if your state update should increment a counter, using the function version of
* [update] with `count -> count + 1` will allow you to account for updates that are in flight but
* not yet applied (e.g. if the user has tapped a button triggering the update multiple times in
* succession).
*/
fun update(newValueFunction: (T) -> T) {
if (canSkip(newValueFunction)) {
return
}
context.updateHookStateAsync(context.globalKey, HookUpdaterLambda(newValueFunction))
}
/**
* Updates this state value and enqueues a new layout calculation reflecting it to execute on the
* current thread. If called on the main thread, this means that the UI will be updated for the
* current frame.
*
* Note: If [updateSync] is used on the main thread, it can easily cause dropped frames and
* degrade user experience. Therefore it should only be used in exceptional circumstances or when
* it's known to be executed off the main thread.
*/
fun updateSync(newValue: T) {
if (canSkip(newValue)) {
return
}
context.updateHookStateSync(context.globalKey, HookUpdaterValue(newValue))
}
/**
* Uses [newValueFunction] to update this state value using the previous state value, and enqueues
* a new layout calculation reflecting it to execute on the current thread.
*
* [newValueFunction] receives the current state value and can use it to compute the update: this
* is useful when there could be other enqueued updates that may not have been applied yet.
*
* For example, if your state update should increment a counter, using the function version of
* [update] with `count -> count + 1` will allow you to account for updates that are in flight but
* not yet applied (e.g. if the user has tapped a button triggering the update multiple times in
* succession).
*
* Note: If [updateSync] is used on the main thread, it can easily cause dropped frames and
* degrade user experience. Therefore it should only be used in exceptional circumstances or when
* it's known to be executed off the main thread.
*/
fun updateSync(newValueFunction: (T) -> T) {
if (canSkip(newValueFunction)) {
return
}
context.updateHookStateSync(context.globalKey, HookUpdaterLambda(newValueFunction))
}
inner class HookUpdaterValue(val newValue: T) : HookUpdater {
override fun getUpdatedStateContainer(currentState: KStateContainer?): KStateContainer? {
return currentState?.copyAndMutate(hookStateIndex, newValue)
}
}
inner class HookUpdaterLambda(val newValueFunction: (T) -> T) : HookUpdater {
override fun getUpdatedStateContainer(currentState: KStateContainer?): KStateContainer? {
return currentState?.copyAndMutate(
hookStateIndex, newValueFunction(currentState.mStates[hookStateIndex] as T))
}
}
private fun canSkip(newValue: T): Boolean {
return context.componentTree.treeState?.canSkipStateUpdate(
context.globalKey, hookStateIndex, newValue, context.isNestedTreeContext())
?: false
}
private fun canSkip(newValueFunction: (T) -> T): Boolean {
val treeState = context.componentTree.treeState
return treeState?.canSkipStateUpdate(
newValueFunction, context.globalKey, hookStateIndex, context.isNestedTreeContext())
?: false
}
/**
* We consider two state objects equal if they 1) belong to the same ComponentTree, 2) have the
* same global key and hook index, and 3) have the same value (according to its own .equals check)
*/
override fun equals(other: Any?): Boolean {
if (this === other) {
return true
}
if (other !is State<*>) {
return false
}
return context.componentTree === other.context.componentTree &&
context.globalKey == other.context.globalKey &&
hookStateIndex == other.hookStateIndex &&
value == other.value
}
override fun hashCode(): Int {
return context.globalKey.hashCode() * 17 + (value?.hashCode() ?: 0) * 11 + hookStateIndex
}
}
| apache-2.0 | 433719dfec27534c3961cddc102e2699 | 36.931579 | 100 | 0.719439 | 4.584606 | false | false | false | false |
facebook/litho | sample/src/main/java/com/facebook/samples/litho/kotlin/documentation/UseCachedWithDependencyComponent.kt | 1 | 1596 | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* 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.facebook.samples.litho.kotlin.documentation
import com.facebook.litho.Column
import com.facebook.litho.Component
import com.facebook.litho.ComponentScope
import com.facebook.litho.KComponent
import com.facebook.litho.Style
import com.facebook.litho.kotlin.widget.Text
import com.facebook.litho.useCached
import com.facebook.litho.useState
import com.facebook.litho.view.onClick
// start_example
class UseCachedWithDependencyComponent : KComponent() {
override fun ComponentScope.render(): Component? {
val number = useState { 1 }
val expensiveValue = useCached(number) { expensiveRepeatFunc("hello", number.value) }
return Column(style = Style.onClick { number.update { n -> n + 1 } }) {
child(Text(text = expensiveValue))
}
}
companion object {
private fun expensiveRepeatFunc(prefix: String, num: Int = 20): String {
return StringBuilder().apply { repeat(num) { append(prefix) } }.toString()
}
}
}
// end_example
| apache-2.0 | d5c6d204f0e5ab27d4742954e8ba76dc | 32.957447 | 89 | 0.738095 | 4 | false | false | false | false |
facebook/litho | sample/src/main/java/com/facebook/samples/litho/kotlin/collection/CollectionKComponent.kt | 1 | 1408 | // (c) Facebook, Inc. and its affiliates. Confidential and proprietary.
package com.facebook.samples.litho.kotlin.collection
/*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import com.facebook.litho.Component
import com.facebook.litho.ComponentScope
import com.facebook.litho.KComponent
import com.facebook.litho.Style
import com.facebook.litho.flexbox.flex
import com.facebook.litho.kotlin.widget.Text
import com.facebook.litho.widget.collection.LazyList
class CollectionKComponent : KComponent() {
private val friends = listOf("Ross", "Rachel", "Joey", "Phoebe", "Monica", "Chandler")
override fun ComponentScope.render(): Component =
LazyList(style = Style.flex(grow = 1f)) {
child(Text(text = "Header"))
children(items = friends, id = { it }) { Text(it) }
child(Text(text = "Footer"))
}
}
| apache-2.0 | 83517b5d04db527a1f593de0724a8d3c | 35.102564 | 88 | 0.727273 | 3.889503 | false | false | false | false |
epabst/kotlin-showcase | src/commonMain/kotlin/todo/ToDo.kt | 1 | 1231 | package todo
import util.PlatformProvider
import util.ProviderDate
import util.ID
import util.Entity
import util.Revision
/**
* The core model classes.
* @author Eric Pabst ([email protected])
* Date: 6/9/16
* Time: 6:27 AM
*/
data class ToDo(
val name: String,
val dueDateString: String? = null,
val notes: String? = null,
val createDateString: String,
val _id: String? = null,
val _rev: String? = null
) : Entity<ToDo> {
constructor(name: String, dueDate: ProviderDate? = null, notes: String? = null, createDate: ProviderDate = PlatformProvider.now(), id: ID<ToDo>? = null, rev: Revision<ToDo>? = null) :
this(name, dueDate?.toIsoTimestampString(), notes, createDate.toIsoTimestampString(), id?._id, rev?._rev)
val dueDate: ProviderDate? get() = dueDateString?.let { PlatformProvider.toDate(it) }
val createDate: ProviderDate? get() = PlatformProvider.toDate(createDateString)
override val id: ID<ToDo>? get() = _id?.let { ID(it) }
override fun withID(id: ID<ToDo>): ToDo = copy(_id = id._id)
override val rev: Revision<ToDo>? get() = _rev?.let { Revision(it) }
override fun withRevision(revision: Revision<ToDo>): ToDo = copy(_rev = revision._rev)
}
| apache-2.0 | 6d0104102783f139560990e86b826f21 | 30.564103 | 187 | 0.672624 | 3.497159 | false | true | false | false |
Commit451/LabCoat | app/src/main/java/com/commit451/gitlab/viewHolder/SnippetViewHolder.kt | 2 | 1123 | package com.commit451.gitlab.viewHolder
import androidx.recyclerview.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import com.commit451.addendum.recyclerview.bindView
import com.commit451.gitlab.R
import com.commit451.gitlab.model.api.Snippet
/**
* Snippet
*/
class SnippetViewHolder(view: View) : RecyclerView.ViewHolder(view) {
companion object {
fun inflate(parent: ViewGroup): SnippetViewHolder {
val view = LayoutInflater.from(parent.context)
.inflate(R.layout.item_snippet, parent, false)
return SnippetViewHolder(view)
}
}
private val textTitle: TextView by bindView(R.id.title)
private val textFileName: TextView by bindView(R.id.file_name)
fun bind(snippet: Snippet) {
textTitle.text = snippet.title
if (snippet.fileName != null) {
textFileName.visibility = View.VISIBLE
textFileName.text = snippet.fileName
} else {
textFileName.visibility = View.GONE
}
}
}
| apache-2.0 | 1e3943ad23db5e7f21194a9a574e3cfd | 28.552632 | 69 | 0.691006 | 4.386719 | false | false | false | false |
herbeth1u/VNDB-Android | app/src/main/java/com/booboot/vndbandroid/dao/UserListDao.kt | 1 | 1825 | package com.booboot.vndbandroid.dao
import com.booboot.vndbandroid.extensions.removeRelations
import com.booboot.vndbandroid.model.vndb.UserList
import io.objectbox.BoxStore
import io.objectbox.annotation.Entity
import io.objectbox.annotation.Id
import io.objectbox.kotlin.boxFor
import io.objectbox.relation.ToMany
@Entity
class UserListDao() {
@Id(assignable = true) var vn: Long = 0
var added: Long = 0
var lastmod: Long = 0
var voted: Long? = null
var vote: Int? = null
var notes: String? = null
var started: String? = null
var finished: String? = null
lateinit var labels: ToMany<LabelDao>
constructor(userList: UserList, boxStore: BoxStore) : this() {
vn = userList.vn
added = userList.added
lastmod = userList.lastmod
voted = userList.voted
vote = userList.vote
notes = userList.notes
started = userList.started
finished = userList.finished
/**
* attach() is mandatory because of self-assigned IDs, but also retrieves the ToMany relations from the DB.
* If we simply add() new relations, they will be stacking up with the old ones; we don't want that, so we have to remove these relations.
* /!\ Don't call clear() because it removes the related entities! Call remove() to only remove relations.
* See https://docs.objectbox.io/relations#updating-tomany
*/
boxStore.boxFor<UserListDao>().attach(this)
labels.removeRelations()
userList.labels.forEach { labels.add(LabelDao(it)) }
boxStore.boxFor<LabelDao>().put(labels)
}
fun toBo() = UserList(
vn,
added,
lastmod,
voted,
vote,
notes,
started,
finished,
labels.map { it.toBo() }.toSet()
)
} | gpl-3.0 | 599add6563626158741d73e8501e4af4 | 31.035088 | 146 | 0.648219 | 4.224537 | false | false | false | false |
JimSeker/ui | Advanced/BottomNavigationViewDemo_kt/app/src/main/java/edu/cs4730/bottomnavigationviewdemo_kt/MainActivity.kt | 1 | 3065 | package edu.cs4730.bottomnavigationviewdemo_kt
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.navigation.fragment.NavHostFragment
import androidx.navigation.ui.AppBarConfiguration
import androidx.navigation.ui.NavigationUI
import com.google.android.material.bottomnavigation.BottomNavigationView
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val navView = findViewById<BottomNavigationView>(R.id.nav_view)
/* if not using arch navigation, then you need to implement this.
navView.setOnItemSelectedListener(
NavigationBarView.OnItemSelectedListener { item -> //setup the fragments here.
val id = item.itemId
if (id == R.id.action_first) {
supportFragmentManager.beginTransaction().replace(R.id.container, OneFragment())
.commit()
item.isChecked = true
return@OnItemSelectedListener true
} else if (id == R.id.action_second) {
supportFragmentManager.beginTransaction().replace(R.id.container, TwoFragment())
.commit()
item.isChecked = true
} else if (id == R.id.action_third) {
supportFragmentManager.beginTransaction()
.replace(R.id.container, threeFragment()).commit()
item.isChecked = true
}
false
}
)*/
// Passing each menu ID as a set of Ids because each menu should be considered as top level destinations.
//Note for this to work with arch Navigation, these id must be the same id in menu.xml and the nav_graph.
val appBarConfiguration = AppBarConfiguration.Builder(
R.id.action_first, R.id.action_second, R.id.action_third
)
.build()
//val navController = Navigation.findNavController(this, R.id.nav_host_fragment)
//NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
val navHostFragment =
supportFragmentManager.findFragmentById(R.id.nav_host_fragment) as NavHostFragment?
val navController = navHostFragment!!.navController
NavigationUI.setupActionBarWithNavController(this, navController, appBarConfiguration)
NavigationUI.setupWithNavController(navView, navController)
//In order to have badges, you need to use the Theme.MaterialComponents.DayNight (doesn't have to be daynight, but MaterialComponents).
//In order to have badges, you need to use the Theme.MaterialComponents.DayNight (doesn't have to be daynight, but MaterialComponents).
val badge = navView.getOrCreateBadge(R.id.action_second)
badge.number = 12 //should show a 12 in the "badge" for the second one.
badge.isVisible = true
}
} | apache-2.0 | 00ca0a463d8e6de098cf800c7c630b1a | 49.262295 | 144 | 0.66199 | 5.177365 | false | true | false | false |
sangcomz/FishBun | FishBun/src/main/java/com/sangcomz/fishbun/FishBun.kt | 1 | 2219 | package com.sangcomz.fishbun
import android.app.Activity
import android.content.Context
import android.content.Intent
import androidx.activity.result.ActivityResultLauncher
import androidx.fragment.app.Fragment
import com.sangcomz.fishbun.adapter.image.ImageAdapter
import java.lang.ref.WeakReference
class FishBun private constructor(activity: Activity?, fragment: Fragment?) {
private val _activity: WeakReference<Activity?> = WeakReference(activity)
private val _fragment: WeakReference<Fragment?> = WeakReference(fragment)
val fishBunContext: FishBunContext get() = FishBunContext()
fun setImageAdapter(imageAdapter: ImageAdapter): FishBunCreator {
val fishton = Fishton.apply {
refresh()
this.imageAdapter = imageAdapter
}
return FishBunCreator(this, fishton)
}
companion object {
@Deprecated("To be deleted along with the startAlbum function")
const val FISHBUN_REQUEST_CODE = 27
const val INTENT_PATH = "intent_path"
@JvmStatic
fun with(activity: Activity) = FishBun(activity, null)
@JvmStatic
fun with(fragment: Fragment) = FishBun(null, fragment)
}
inner class FishBunContext {
private val activity = _activity.get()
private val fragment = _fragment.get()
fun getContext(): Context =
activity ?: fragment?.context ?: throw NullPointerException("Activity or Fragment Null")
fun startActivityForResult(intent: Intent, requestCode: Int) {
when {
activity != null -> activity.startActivityForResult(intent, requestCode)
fragment != null -> fragment.startActivityForResult(intent, requestCode)
else -> throw NullPointerException("Activity or Fragment Null")
}
}
fun startWithRegisterForActivityResult(
activityResultLauncher: ActivityResultLauncher<Intent>,
intent: Intent
) {
when {
activity != null || fragment != null -> activityResultLauncher.launch(intent)
else -> throw NullPointerException("Activity or Fragment Null")
}
}
}
}
| apache-2.0 | 6d3b54e14473b8a6f94bbe575b117f66 | 33.671875 | 100 | 0.66201 | 5.359903 | false | false | false | false |
google/kiosk-app-reference-implementation | app/src/main/java/com/ape/apps/sample/baypilot/data/creditplan/CreditPlanInfo.kt | 1 | 2140 | /*
* Copyright 2022 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.ape.apps.sample.baypilot.data.creditplan
import com.google.gson.Gson
enum class CreditPlanType {
MONTHLY, WEEKLY, DAILY;
companion object {
fun toString(creditPlanType: CreditPlanType?): String? {
return when (creditPlanType) {
MONTHLY -> "MONTHLY"
WEEKLY -> "WEEKLY"
DAILY -> "DAILY"
else -> null
}
}
fun toCreditPlanType(planType: String?): CreditPlanType? {
return when (planType) {
"DAILY" -> DAILY
"WEEKLY" -> WEEKLY
"MONTHLY" -> MONTHLY
else -> null
}
}
}
}
// Class to store all details related to device credit plan.
// TODO: Currently it has only few essential members for testing, add others.
class CreditPlanInfo(
val totalAmount: Int? = 0,
val totalPaidAmount: Int? = 0,
val dueDate: String? = null,
val nextDueAmount: Int? = 0,
val planType: CreditPlanType? = null
) {
companion object {
// Serialize a single object.
fun serializeToJson(cpi: CreditPlanInfo?): String? {
val gson = Gson()
return gson.toJson(cpi)
}
// Deserialize to single object.
fun deserializeFromJson(jsonString: String?): CreditPlanInfo? {
val gson = Gson()
return gson.fromJson(jsonString, CreditPlanInfo::class.java)
}
}
fun toDebugString(): String {
return "Credit Plan details: Due Date = $dueDate, Total device cost = $totalAmount, " +
"Amount paid till now: $totalPaidAmount Next installment due = $nextDueAmount, Plan type = $planType"
}
} | apache-2.0 | 104325b3975d7cb022707e50f56dd09b | 27.932432 | 113 | 0.668224 | 4.045369 | false | false | false | false |
cemrich/zapp | app/src/main/java/de/christinecoenen/code/zapp/app/settings/ui/SettingsFragment.kt | 1 | 2103 | package de.christinecoenen.code.zapp.app.settings.ui
import android.content.Context
import android.os.Bundle
import androidx.appcompat.app.AppCompatDelegate
import androidx.preference.ListPreference
import androidx.preference.Preference
import androidx.preference.PreferenceFragmentCompat
import de.christinecoenen.code.zapp.R
import de.christinecoenen.code.zapp.app.settings.helper.ShortcutPreference
import de.christinecoenen.code.zapp.app.settings.repository.SettingsRepository
/**
* Use the [SettingsFragment.newInstance] factory method to
* create an instance of this fragment.
*/
class SettingsFragment : PreferenceFragmentCompat() {
companion object {
private const val PREF_SHORTCUTS = "pref_shortcuts"
private const val PREF_UI_MODE = "pref_ui_mode"
/**
* Use this factory method to create a new instance of
* this fragment.
*/
@JvmStatic
fun newInstance(): SettingsFragment {
return SettingsFragment()
}
}
private lateinit var settingsRepository: SettingsRepository
private lateinit var shortcutPreference: ShortcutPreference
private lateinit var uiModePreference: ListPreference
private val uiModeChangeListener = Preference.OnPreferenceChangeListener { _, newValue ->
val uiMode = settingsRepository.prefValueToUiMode(newValue as String?)
AppCompatDelegate.setDefaultNightMode(uiMode)
true
}
override fun onAttach(context: Context) {
super.onAttach(context)
settingsRepository = SettingsRepository(context)
}
override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) {
addPreferencesFromResource(R.xml.preferences)
shortcutPreference = preferenceScreen.findPreference(PREF_SHORTCUTS)!!
uiModePreference = preferenceScreen.findPreference(PREF_UI_MODE)!!
}
override fun onResume() {
super.onResume()
shortcutPreference.onPreferenceChangeListener = shortcutPreference
uiModePreference.onPreferenceChangeListener = uiModeChangeListener
}
override fun onPause() {
super.onPause()
shortcutPreference.onPreferenceChangeListener = null
uiModePreference.onPreferenceChangeListener = null
}
}
| mit | 5d87abfe84c66fb04c3f54c547705231 | 28.619718 | 90 | 0.803614 | 4.736486 | false | false | false | false |
udevbe/westmalle | compositor/src/main/kotlin/org/westford/compositor/wlshell/ShellSurface.kt | 3 | 12906 | /*
* Westford Wayland Compositor.
* Copyright (C) 2016 Erik De Rijcke
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.westford.compositor.wlshell
import com.google.auto.factory.AutoFactory
import com.google.auto.factory.Provided
import org.freedesktop.wayland.server.*
import org.freedesktop.wayland.shared.WlShellSurfaceResize
import org.freedesktop.wayland.shared.WlShellSurfaceTransient
import org.freedesktop.wayland.util.Fixed
import org.westford.compositor.core.*
import org.westford.compositor.core.calc.Mat4
import org.westford.compositor.core.events.KeyboardFocusGained
import org.westford.compositor.core.events.PointerGrab
import org.westford.compositor.protocol.WlKeyboard
import org.westford.compositor.protocol.WlPointer
import org.westford.compositor.protocol.WlSurface
@AutoFactory(className = "PrivateShellSurfaceFactory",
allowSubclasses = true) class ShellSurface(@Provided display: Display,
@param:Provided private val compositor: Compositor,
@param:Provided private val scene: Scene,
private val surfaceView: SurfaceView,
private val pingSerial: Int) : Role {
private val timerEventSource: EventSource
private var keyboardFocusListener: ((KeyboardFocusGained) -> Unit)? = null
var isActive = true
private set
var clazz: String? = null
set(value) {
field = value
this.compositor.requestRender()
}
var title: String? = null
set(value) {
field = value
this.compositor.requestRender()
}
init {
this.timerEventSource = display.eventLoop.addTimer {
this.isActive = false
0
}
}
fun pong(wlShellSurfaceResource: WlShellSurfaceResource,
pingSerial: Int) {
if (this.pingSerial == pingSerial) {
this.isActive = true
wlShellSurfaceResource.ping(pingSerial)
this.timerEventSource.updateTimer(5000)
}
}
fun move(wlSurfaceResource: WlSurfaceResource,
wlPointerResource: WlPointerResource,
grabSerial: Int) {
val wlSurface = wlSurfaceResource.implementation as WlSurface
val surface = wlSurface.surface
val wlPointer = wlPointerResource.implementation as WlPointer
val pointerDevice = wlPointer.pointerDevice
val pointerPosition = pointerDevice.position
pointerDevice.grab?.takeIf {
surface.views.contains(it)
}?.let {
val surfacePosition = it.global(Point(0,
0))
val pointerOffset = pointerPosition - surfacePosition
//FIXME pick a surface view based on the pointer position
pointerDevice.grabMotion(wlSurfaceResource,
grabSerial) { motion ->
it.updatePosition(motion.point - pointerOffset)
}
}
}
fun resize(wlShellSurfaceResource: WlShellSurfaceResource,
wlSurfaceResource: WlSurfaceResource,
wlPointerResource: WlPointerResource,
buttonPressSerial: Int,
edges: Int) {
val wlSurface = wlSurfaceResource.implementation as WlSurface
val surface = wlSurface.surface
val wlPointer = wlPointerResource.implementation as WlPointer
val pointerDevice = wlPointer.pointerDevice
val pointerStartPos = pointerDevice.position
pointerDevice.grab?.takeIf {
surface.views.contains(it)
}?.let {
val local = it.local(pointerStartPos)
val size = surface.size
val quadrant = quadrant(edges)
val transform = transform(quadrant,
size,
local)
val inverseTransform = it.inverseTransform
val grabMotionSuccess = pointerDevice.grabMotion(wlSurfaceResource,
buttonPressSerial) {
val motionLocal = inverseTransform * it.point.toVec4()
val resize = transform * motionLocal
val width = resize.x.toInt()
val height = resize.y.toInt()
wlShellSurfaceResource.configure(quadrant.value,
if (width < 1) 1 else width,
if (height < 1) 1 else height)
}
if (grabMotionSuccess) {
wlPointerResource.leave(pointerDevice.nextLeaveSerial(),
wlSurfaceResource)
pointerDevice.pointerGrabSignal.connect(object : (PointerGrab) -> Unit {
override fun invoke(event: PointerGrab) {
if (pointerDevice.grab == null) {
pointerDevice.pointerGrabSignal.disconnect(this)
wlPointerResource.enter(pointerDevice.nextEnterSerial(),
wlSurfaceResource,
Fixed.create(local.x),
Fixed.create(local.y))
}
}
})
}
}
}
private fun quadrant(edges: Int): WlShellSurfaceResize {
when (edges) {
0 -> return WlShellSurfaceResize.NONE
1 -> return WlShellSurfaceResize.TOP
2 -> return WlShellSurfaceResize.BOTTOM
4 -> return WlShellSurfaceResize.LEFT
5 -> return WlShellSurfaceResize.TOP_LEFT
6 -> return WlShellSurfaceResize.BOTTOM_LEFT
8 -> return WlShellSurfaceResize.RIGHT
9 -> return WlShellSurfaceResize.TOP_RIGHT
10 -> return WlShellSurfaceResize.BOTTOM_RIGHT
else -> return WlShellSurfaceResize.NONE
}
}
private fun transform(quadrant: WlShellSurfaceResize,
size: Rectangle,
pointerLocal: Point): Mat4 {
val width = size.width
val height = size.height
val transformation: Mat4
val pointerdx: Float
val pointerdy: Float
when (quadrant) {
WlShellSurfaceResize.TOP -> {
transformation = Transforms._180.copy(m00 = 0f,
m30 = width.toFloat())
val pointerLocalTransformed = transformation * pointerLocal.toVec4()
pointerdx = 0f
pointerdy = height - pointerLocalTransformed.y
}
WlShellSurfaceResize.TOP_LEFT -> {
transformation = Transforms._180.copy(m30 = width.toFloat(),
m31 = height.toFloat())
val localTransformed = transformation * pointerLocal.toVec4()
pointerdx = width - localTransformed.x
pointerdy = height - localTransformed.y
}
WlShellSurfaceResize.LEFT -> {
transformation = Transforms.FLIPPED.copy(m11 = 0f,
m31 = height.toFloat())
val localTransformed = transformation * pointerLocal.toVec4()
pointerdx = width - localTransformed.x
pointerdy = 0f
}
WlShellSurfaceResize.BOTTOM_LEFT -> {
transformation = Transforms.FLIPPED.copy(m30 = width.toFloat())
val localTransformed = transformation * pointerLocal.toVec4()
pointerdx = width - localTransformed.x
pointerdy = height - localTransformed.y
}
WlShellSurfaceResize.RIGHT -> {
transformation = Transforms.NORMAL.copy(m11 = 0f,
m31 = height.toFloat())
val localTransformed = transformation * pointerLocal.toVec4()
pointerdx = width - localTransformed.x
pointerdy = 0f
}
WlShellSurfaceResize.TOP_RIGHT -> {
transformation = Transforms.FLIPPED_180.copy(m31 = height.toFloat())
val localTransformed = transformation * pointerLocal.toVec4()
pointerdx = width - localTransformed.x
pointerdy = height - localTransformed.y
}
WlShellSurfaceResize.BOTTOM -> {
transformation = Transforms.NORMAL.copy(m00 = 0f,
m30 = width.toFloat())
val pointerLocalTransformed = transformation * pointerLocal.toVec4()
pointerdx = 0f
pointerdy = height - pointerLocalTransformed.y
}
WlShellSurfaceResize.BOTTOM_RIGHT -> {
transformation = Transforms.NORMAL
val localTransformed = pointerLocal.toVec4()
pointerdx = width - localTransformed.x
pointerdy = height - localTransformed.y
}
else -> {
transformation = Transforms.NORMAL
pointerdx = 0f
pointerdy = 0f
}
}
return transformation.copy(m30 = (transformation.m30 + pointerdx),
m31 = (transformation.m31 + pointerdy))
}
fun setTransient(wlSurfaceResource: WlSurfaceResource,
parent: WlSurfaceResource,
x: Int,
y: Int,
flags: Int) {
val wlSurface = wlSurfaceResource.implementation as WlSurface
val surface = wlSurface.surface
this.keyboardFocusListener?.let {
surface.keyboardFocusGainedSignal.disconnect(it)
}
if ((flags and WlShellSurfaceTransient.INACTIVE.value) != 0) {
val slot: (KeyboardFocusGained) -> Unit = {
//clean collection of focuses, so they don't get notify of keyboard related events
surface.keyboardFocuses.clear()
}
surface.keyboardFocusGainedSignal.connect(slot)
//first time focus clearing, also send out leave events
val keyboardFocuses = surface.keyboardFocuses
keyboardFocuses.forEach {
val wlKeyboard = it.implementation as WlKeyboard
val keyboardDevice = wlKeyboard.keyboardDevice
it.leave(keyboardDevice.nextKeyboardSerial(),
wlSurfaceResource)
}
keyboardFocuses.clear()
this.keyboardFocusListener = slot
}
val parentWlSurface = parent.implementation as WlSurface
val parentSurface = parentWlSurface.surface
this.scene.removeView(this.surfaceView)
parentSurface.views.forEach {
this.surfaceView.parent = it
}
parentSurface.addSibling(Sibling(Point(x,
y),
wlSurfaceResource))
}
override fun accept(roleVisitor: RoleVisitor) = roleVisitor.visit(this)
fun setTopLevel(wlSurfaceResource: WlSurfaceResource) {
val wlSurface = wlSurfaceResource.implementation as WlSurface
val surface = wlSurface.surface
surface.views.forEach {
it.parent?.let {
val parentWlSurfaceResource = it.wlSurfaceResource
val parentWlSurface = parentWlSurfaceResource.implementation as WlSurface
val parentSurface = parentWlSurface.surface
parentSurface.removeSibling(Sibling(wlSurfaceResource))
}
}
this.scene.removeView(this.surfaceView)
this.scene.applicationLayer.surfaceViews.add(this.surfaceView)
}
}
| agpl-3.0 | 3947708936a3149b26f6686d297f0eb5 | 40.76699 | 107 | 0.563381 | 5.939254 | false | false | false | false |
ebraminio/DroidPersianCalendar | PersianCalendar/src/main/java/com/byagowi/persiancalendar/ui/calendar/dialogs/ShiftWorkDialog.kt | 1 | 10551 | package com.byagowi.persiancalendar.ui.calendar.dialogs
import android.app.Dialog
import android.os.Bundle
import android.text.Editable
import android.text.InputFilter
import android.text.Spanned
import android.text.TextWatcher
import android.view.View
import android.view.ViewGroup
import android.view.WindowManager
import android.widget.AdapterView
import android.widget.ArrayAdapter
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatDialogFragment
import androidx.core.content.edit
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.byagowi.persiancalendar.PREF_SHIFT_WORK_RECURS
import com.byagowi.persiancalendar.PREF_SHIFT_WORK_SETTING
import com.byagowi.persiancalendar.PREF_SHIFT_WORK_STARTING_JDN
import com.byagowi.persiancalendar.R
import com.byagowi.persiancalendar.databinding.ShiftWorkItemBinding
import com.byagowi.persiancalendar.databinding.ShiftWorkSettingsBinding
import com.byagowi.persiancalendar.entities.ShiftWorkRecord
import com.byagowi.persiancalendar.ui.MainActivity
import com.byagowi.persiancalendar.utils.*
class ShiftWorkDialog : AppCompatDialogFragment() {
private var jdn: Long = -1L
private var selectedJdn: Long = -1L
var onSuccess = fun() {}
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
val mainActivity = activity as MainActivity
applyAppLanguage(mainActivity)
updateStoredPreference(mainActivity)
selectedJdn = arguments?.getLong(BUNDLE_KEY, -1L) ?: -1L
if (selectedJdn == -1L) selectedJdn = getTodayJdn()
jdn = shiftWorkStartingJdn
var isFirstSetup = false
if (jdn == -1L) {
isFirstSetup = true
jdn = selectedJdn
}
val binding = ShiftWorkSettingsBinding.inflate(mainActivity.layoutInflater, null, false)
binding.recyclerView.layoutManager = LinearLayoutManager(mainActivity)
val shiftWorkItemAdapter = ItemsAdapter(
if (shiftWorks.isEmpty()) listOf(ShiftWorkRecord("d", 0)) else shiftWorks,
binding
)
binding.recyclerView.adapter = shiftWorkItemAdapter
binding.description.text = getString(
if (isFirstSetup) R.string.shift_work_starting_date
else R.string.shift_work_starting_date_edit
).format(formatDate(getDateFromJdnOfCalendar(mainCalendar, jdn)))
binding.resetLink.setOnClickListener {
jdn = selectedJdn
binding.description.text = getString(R.string.shift_work_starting_date)
.format(formatDate(getDateFromJdnOfCalendar(mainCalendar, jdn)))
shiftWorkItemAdapter.reset()
}
binding.recurs.isChecked = shiftWorkRecurs
return AlertDialog.Builder(mainActivity)
.setView(binding.root)
.setTitle(null)
.setPositiveButton(R.string.accept) { _, _ ->
val result = shiftWorkItemAdapter.rows.filter { it.length != 0 }.joinToString(",") {
"${it.type.replace("=", "").replace(",", "")}=${it.length}"
}
mainActivity.appPrefs.edit {
putLong(PREF_SHIFT_WORK_STARTING_JDN, if (result.isEmpty()) -1 else jdn)
putString(PREF_SHIFT_WORK_SETTING, result.toString())
putBoolean(PREF_SHIFT_WORK_RECURS, binding.recurs.isChecked)
}
onSuccess()
}
.setCancelable(true)
.setNegativeButton(R.string.cancel, null)
.create()
}
override fun onResume() {
super.onResume()
// https://stackoverflow.com/a/46248107
dialog?.window?.run {
clearFlags(WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE or WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM)
setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE)
}
}
private inner class ItemsAdapter internal constructor(
var rows: List<ShiftWorkRecord> = emptyList(),
private val binding: ShiftWorkSettingsBinding
) : RecyclerView.Adapter<ItemsAdapter.ViewHolder>() {
init {
updateShiftWorkResult()
}
fun shiftWorkKeyToString(type: String): String = shiftWorkTitles[type] ?: type
private fun updateShiftWorkResult() =
rows.filter { it.length != 0 }.joinToString(spacedComma) {
getString(R.string.shift_work_record_title)
.format(formatNumber(it.length), shiftWorkKeyToString(it.type))
}.also {
binding.result.text = it
binding.result.visibility = if (it.isEmpty()) View.GONE else View.VISIBLE
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) = ViewHolder(
ShiftWorkItemBinding.inflate(parent.context.layoutInflater, parent, false)
)
override fun onBindViewHolder(holder: ViewHolder, position: Int) = holder.bind(position)
override fun getItemCount(): Int = rows.size + 1
internal fun reset() {
rows = listOf(ShiftWorkRecord("d", 0))
notifyDataSetChanged()
updateShiftWorkResult()
}
internal inner class ViewHolder(private val binding: ShiftWorkItemBinding) :
RecyclerView.ViewHolder(binding.root) {
init {
val context = binding.root.context
binding.lengthSpinner.adapter = ArrayAdapter(
context,
android.R.layout.simple_spinner_dropdown_item,
(0..7).map {
if (it == 0) getString(R.string.shift_work_days_head) else formatNumber(it)
}
)
binding.typeAutoCompleteTextView.run {
val adapter = ArrayAdapter(
context,
android.R.layout.simple_spinner_dropdown_item,
resources.getStringArray(R.array.shift_work)
)
setAdapter(adapter)
setOnClickListener {
if (text.toString().isNotEmpty()) adapter.filter.filter(null)
showDropDown()
}
onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
override fun onItemSelected(
parent: AdapterView<*>, view: View, position: Int, id: Long
) {
rows = rows.mapIndexed { i, x ->
if (i == adapterPosition) ShiftWorkRecord(
text.toString(), rows[adapterPosition].length
)
else x
}
updateShiftWorkResult()
}
override fun onNothingSelected(parent: AdapterView<*>) {}
}
addTextChangedListener(object : TextWatcher {
override fun afterTextChanged(s: Editable?) {}
override fun beforeTextChanged(
s: CharSequence?, start: Int, count: Int, after: Int
) = Unit
override fun onTextChanged(
s: CharSequence?, start: Int, before: Int, count: Int
) {
rows = rows.mapIndexed { i, x ->
if (i == adapterPosition) ShiftWorkRecord(
text.toString(),
rows[adapterPosition].length
)
else x
}
updateShiftWorkResult()
}
})
filters = arrayOf(object : InputFilter {
override fun filter(
source: CharSequence?, start: Int, end: Int,
dest: Spanned?, dstart: Int, dend: Int
) = if ("[=,]".toRegex() in (source ?: "")) "" else null
})
}
binding.remove.setOnClickListener { remove() }
binding.lengthSpinner.onItemSelectedListener =
object : AdapterView.OnItemSelectedListener {
override fun onNothingSelected(parent: AdapterView<*>) {}
override fun onItemSelected(
parent: AdapterView<*>, view: View, position: Int, id: Long
) {
rows = rows.mapIndexed { i, x ->
if (i == adapterPosition) ShiftWorkRecord(x.type, position)
else x
}
updateShiftWorkResult()
}
}
binding.addButton.setOnClickListener {
rows = rows + ShiftWorkRecord("r", 0)
notifyDataSetChanged()
updateShiftWorkResult()
}
}
fun remove() {
rows = rows.filterIndexed { i, _ -> i != adapterPosition }
notifyDataSetChanged()
updateShiftWorkResult()
}
fun bind(position: Int) = if (position < rows.size) {
val shiftWorkRecord = rows[position]
binding.rowNumber.text = "%s:".format(formatNumber(position + 1))
binding.lengthSpinner.setSelection(shiftWorkRecord.length)
binding.typeAutoCompleteTextView.setText(shiftWorkKeyToString(shiftWorkRecord.type))
binding.detail.visibility = View.VISIBLE
binding.addButton.visibility = View.GONE
} else {
binding.detail.visibility = View.GONE
binding.addButton.visibility = if (rows.size < 20) View.VISIBLE else View.GONE
}
}
}
companion object {
private const val BUNDLE_KEY = "jdn"
fun newInstance(jdn: Long) = ShiftWorkDialog().apply {
arguments = Bundle().apply {
putLong(BUNDLE_KEY, jdn)
}
}
}
}
| gpl-3.0 | e586af371fdc2686f71625e443a9f8ae | 39.895349 | 121 | 0.554071 | 5.657373 | false | false | false | false |
wordpress-mobile/WordPress-Stores-Android | plugins/woocommerce/src/main/kotlin/org/wordpress/android/fluxc/store/WCProductStore.kt | 1 | 71804 | package org.wordpress.android.fluxc.store
import com.google.gson.Gson
import com.google.gson.JsonObject
import com.google.gson.JsonPrimitive
import kotlinx.coroutines.flow.Flow
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import org.wordpress.android.fluxc.Dispatcher
import org.wordpress.android.fluxc.Payload
import org.wordpress.android.fluxc.action.WCProductAction
import org.wordpress.android.fluxc.annotations.action.Action
import org.wordpress.android.fluxc.domain.Addon
import org.wordpress.android.fluxc.model.SiteModel
import org.wordpress.android.fluxc.model.WCProductCategoryModel
import org.wordpress.android.fluxc.model.WCProductImageModel
import org.wordpress.android.fluxc.model.WCProductModel
import org.wordpress.android.fluxc.model.WCProductReviewModel
import org.wordpress.android.fluxc.model.WCProductShippingClassModel
import org.wordpress.android.fluxc.model.WCProductTagModel
import org.wordpress.android.fluxc.model.WCProductVariationModel
import org.wordpress.android.fluxc.model.WCProductVariationModel.ProductVariantOption
import org.wordpress.android.fluxc.model.addons.RemoteAddonDto
import org.wordpress.android.fluxc.network.BaseRequest.BaseNetworkError
import org.wordpress.android.fluxc.network.BaseRequest.GenericErrorType
import org.wordpress.android.fluxc.network.BaseRequest.GenericErrorType.UNKNOWN
import org.wordpress.android.fluxc.network.rest.wpcom.wc.WooError
import org.wordpress.android.fluxc.network.rest.wpcom.wc.WooErrorType
import org.wordpress.android.fluxc.network.rest.wpcom.wc.WooErrorType.INVALID_RESPONSE
import org.wordpress.android.fluxc.network.rest.wpcom.wc.WooPayload
import org.wordpress.android.fluxc.network.rest.wpcom.wc.WooResult
import org.wordpress.android.fluxc.network.rest.wpcom.wc.addons.mappers.MappingRemoteException
import org.wordpress.android.fluxc.network.rest.wpcom.wc.addons.mappers.RemoteAddonMapper
import org.wordpress.android.fluxc.network.rest.wpcom.wc.product.BatchProductVariationsUpdateApiResponse
import org.wordpress.android.fluxc.network.rest.wpcom.wc.product.CoreProductStockStatus
import org.wordpress.android.fluxc.network.rest.wpcom.wc.product.ProductRestClient
import org.wordpress.android.fluxc.persistence.ProductSqlUtils
import org.wordpress.android.fluxc.persistence.dao.AddonsDao
import org.wordpress.android.fluxc.store.WCProductStore.ProductCategorySorting.NAME_ASC
import org.wordpress.android.fluxc.store.WCProductStore.ProductErrorType.GENERIC_ERROR
import org.wordpress.android.fluxc.store.WCProductStore.ProductSorting.TITLE_ASC
import org.wordpress.android.fluxc.tools.CoroutineEngine
import org.wordpress.android.fluxc.utils.AppLogWrapper
import org.wordpress.android.util.AppLog
import org.wordpress.android.util.AppLog.T
import org.wordpress.android.util.AppLog.T.API
import java.util.Locale
import javax.inject.Inject
import javax.inject.Singleton
@Suppress("LargeClass")
@Singleton
class WCProductStore @Inject constructor(
dispatcher: Dispatcher,
private val wcProductRestClient: ProductRestClient,
private val coroutineEngine: CoroutineEngine,
private val addonsDao: AddonsDao,
private val logger: AppLogWrapper
) : Store(dispatcher) {
companion object {
const val NUM_REVIEWS_PER_FETCH = 25
const val DEFAULT_PRODUCT_PAGE_SIZE = 25
const val DEFAULT_PRODUCT_CATEGORY_PAGE_SIZE = 100
const val DEFAULT_PRODUCT_VARIATIONS_PAGE_SIZE = 25
const val DEFAULT_PRODUCT_SHIPPING_CLASS_PAGE_SIZE = 25
const val DEFAULT_PRODUCT_TAGS_PAGE_SIZE = 100
val DEFAULT_PRODUCT_SORTING = TITLE_ASC
val DEFAULT_CATEGORY_SORTING = NAME_ASC
}
/**
* Defines the filter options currently supported in the app
*/
enum class ProductFilterOption {
STOCK_STATUS, STATUS, TYPE, CATEGORY;
override fun toString() = name.toLowerCase(Locale.US)
}
class FetchProductSkuAvailabilityPayload(
var site: SiteModel,
var sku: String
) : Payload<BaseNetworkError>()
class FetchSingleProductPayload(
var site: SiteModel,
var remoteProductId: Long
) : Payload<BaseNetworkError>()
class FetchProductsPayload(
var site: SiteModel,
var pageSize: Int = DEFAULT_PRODUCT_PAGE_SIZE,
var offset: Int = 0,
var sorting: ProductSorting = DEFAULT_PRODUCT_SORTING,
var remoteProductIds: List<Long>? = null,
var filterOptions: Map<ProductFilterOption, String>? = null,
var excludedProductIds: List<Long>? = null
) : Payload<BaseNetworkError>()
class SearchProductsPayload(
var site: SiteModel,
var searchQuery: String,
var isSkuSearch: Boolean = false,
var pageSize: Int = DEFAULT_PRODUCT_PAGE_SIZE,
var offset: Int = 0,
var sorting: ProductSorting = DEFAULT_PRODUCT_SORTING,
var excludedProductIds: List<Long>? = null
) : Payload<BaseNetworkError>()
class FetchProductVariationsPayload(
var site: SiteModel,
var remoteProductId: Long,
var pageSize: Int = DEFAULT_PRODUCT_VARIATIONS_PAGE_SIZE,
var offset: Int = 0
) : Payload<BaseNetworkError>()
class FetchProductShippingClassListPayload(
var site: SiteModel,
var pageSize: Int = DEFAULT_PRODUCT_SHIPPING_CLASS_PAGE_SIZE,
var offset: Int = 0
) : Payload<BaseNetworkError>()
class FetchSingleProductShippingClassPayload(
var site: SiteModel,
var remoteShippingClassId: Long
) : Payload<BaseNetworkError>()
class FetchProductReviewsPayload(
var site: SiteModel,
var offset: Int = 0,
var reviewIds: List<Long>? = null,
var productIds: List<Long>? = null,
var filterByStatus: List<String>? = null
) : Payload<BaseNetworkError>()
class FetchSingleProductReviewPayload(
var site: SiteModel,
var remoteReviewId: Long
) : Payload<BaseNetworkError>()
class FetchProductPasswordPayload(
var site: SiteModel,
var remoteProductId: Long
) : Payload<BaseNetworkError>()
class UpdateProductPasswordPayload(
var site: SiteModel,
var remoteProductId: Long,
var password: String
) : Payload<BaseNetworkError>()
class UpdateProductReviewStatusPayload(
var site: SiteModel,
var remoteReviewId: Long,
var newStatus: String
) : Payload<BaseNetworkError>()
class UpdateProductImagesPayload(
var site: SiteModel,
var remoteProductId: Long,
var imageList: List<WCProductImageModel>
) : Payload<BaseNetworkError>()
class UpdateProductPayload(
var site: SiteModel,
val product: WCProductModel
) : Payload<BaseNetworkError>()
class UpdateVariationPayload(
var site: SiteModel,
val variation: WCProductVariationModel
) : Payload<BaseNetworkError>()
/**
* Payload used by [batchUpdateVariations] function.
*
* @param remoteProductId Id of the product.
* @param remoteVariationsIds Ids of variations that are going to be updated.
* @param modifiedProperties Map of the properties of variation that are going to be updated.
* Keys correspond to the names of variation properties. Values are the updated properties values.
*/
class BatchUpdateVariationsPayload(
val site: SiteModel,
val remoteProductId: Long,
val remoteVariationsIds: Collection<Long>,
val modifiedProperties: Map<String, Any>
) : Payload<BaseNetworkError>() {
/**
* Builder class used for instantiating [BatchUpdateVariationsPayload].
*/
class Builder(
private val site: SiteModel,
private val remoteProductId: Long,
private val variationsIds: Collection<Long>
) {
private val variationsModifications = mutableMapOf<String, Any>()
fun regularPrice(regularPrice: String) = apply {
variationsModifications["regular_price"] = regularPrice
}
fun salePrice(salePrice: String) = apply {
variationsModifications["sale_price"] = salePrice
}
fun startOfSale(startOfSale: String) = apply {
variationsModifications["date_on_sale_from"] = startOfSale
}
fun endOfSale(endOfSale: String) = apply {
variationsModifications["date_on_sale_to"] = endOfSale
}
fun stockQuantity(stockQuantity: Int) = apply {
variationsModifications["stock_quantity"] = stockQuantity
}
fun stockStatus(stockStatus: CoreProductStockStatus) = apply {
variationsModifications["stock_status"] = stockStatus
}
fun weight(weight: String) = apply {
variationsModifications["weight"] = weight
}
fun dimensions(length: String, width: String, height: String) = apply {
val dimensions = JsonObject().apply {
add("length", JsonPrimitive(length))
add("width", JsonPrimitive(width))
add("height", JsonPrimitive(height))
}
variationsModifications["dimensions"] = dimensions
}
fun shippingClassId(shippingClassId: String) = apply {
variationsModifications["shipping_class_id"] = shippingClassId
}
fun shippingClassSlug(shippingClassSlug: String) = apply {
variationsModifications["shipping_class"] = shippingClassSlug
}
fun build() = BatchUpdateVariationsPayload(
site,
remoteProductId,
variationsIds,
variationsModifications
)
}
}
class FetchProductCategoriesPayload(
var site: SiteModel,
var pageSize: Int = DEFAULT_PRODUCT_CATEGORY_PAGE_SIZE,
var offset: Int = 0,
var productCategorySorting: ProductCategorySorting = DEFAULT_CATEGORY_SORTING
) : Payload<BaseNetworkError>()
class AddProductCategoryPayload(
val site: SiteModel,
val category: WCProductCategoryModel
) : Payload<BaseNetworkError>()
class FetchProductTagsPayload(
var site: SiteModel,
var pageSize: Int = DEFAULT_PRODUCT_TAGS_PAGE_SIZE,
var offset: Int = 0,
var searchQuery: String? = null
) : Payload<BaseNetworkError>()
class AddProductTagsPayload(
val site: SiteModel,
val tags: List<String>
) : Payload<BaseNetworkError>()
class AddProductPayload(
var site: SiteModel,
val product: WCProductModel
) : Payload<BaseNetworkError>()
class DeleteProductPayload(
var site: SiteModel,
val remoteProductId: Long,
val forceDelete: Boolean = false
) : Payload<BaseNetworkError>()
enum class ProductErrorType {
INVALID_PRODUCT_ID,
INVALID_PARAM,
INVALID_REVIEW_ID,
INVALID_IMAGE_ID,
DUPLICATE_SKU,
// indicates duplicate term name. Currently only used when adding product categories
TERM_EXISTS,
// Happens if a store is running Woo 4.6 and below and tries to delete the product image
// from a variation. See this PR for more detail:
// https://github.com/woocommerce/woocommerce/pull/27299
INVALID_VARIATION_IMAGE_ID,
GENERIC_ERROR;
companion object {
private val reverseMap = values().associateBy(ProductErrorType::name)
fun fromString(type: String) = reverseMap[type.toUpperCase(Locale.US)] ?: GENERIC_ERROR
}
}
class ProductError(val type: ProductErrorType = GENERIC_ERROR, val message: String = "") : OnChangedError
enum class ProductSorting {
TITLE_ASC,
TITLE_DESC,
DATE_ASC,
DATE_DESC
}
enum class ProductCategorySorting {
NAME_ASC,
NAME_DESC
}
class RemoteProductSkuAvailabilityPayload(
val site: SiteModel,
var sku: String,
val available: Boolean
) : Payload<ProductError>() {
constructor(
error: ProductError,
site: SiteModel,
sku: String,
available: Boolean
) : this(site, sku, available) {
this.error = error
}
}
class RemoteProductPayload(
val product: WCProductModel,
val site: SiteModel
) : Payload<ProductError>() {
constructor(
error: ProductError,
product: WCProductModel,
site: SiteModel
) : this(product, site) {
this.error = error
}
}
class RemoteVariationPayload(
val variation: WCProductVariationModel,
val site: SiteModel
) : Payload<ProductError>() {
constructor(
error: ProductError,
variation: WCProductVariationModel,
site: SiteModel
) : this(variation, site) {
this.error = error
}
}
class RemoteProductPasswordPayload(
val remoteProductId: Long,
val site: SiteModel,
val password: String
) : Payload<ProductError>() {
constructor(
error: ProductError,
remoteProductId: Long,
site: SiteModel,
password: String
) : this(remoteProductId, site, password) {
this.error = error
}
}
class RemoteUpdatedProductPasswordPayload(
val remoteProductId: Long,
val site: SiteModel,
val password: String
) : Payload<ProductError>() {
constructor(
error: ProductError,
remoteProductId: Long,
site: SiteModel,
password: String
) : this(remoteProductId, site, password) {
this.error = error
}
}
class RemoteProductListPayload(
val site: SiteModel,
val products: List<WCProductModel> = emptyList(),
var offset: Int = 0,
var loadedMore: Boolean = false,
var canLoadMore: Boolean = false,
val remoteProductIds: List<Long>? = null,
val excludedProductIds: List<Long>? = null
) : Payload<ProductError>() {
constructor(
error: ProductError,
site: SiteModel
) : this(site) {
this.error = error
}
}
class RemoteSearchProductsPayload(
var site: SiteModel,
var searchQuery: String?,
var isSkuSearch: Boolean = false,
var products: List<WCProductModel> = emptyList(),
var offset: Int = 0,
var loadedMore: Boolean = false,
var canLoadMore: Boolean = false
) : Payload<ProductError>() {
constructor(error: ProductError, site: SiteModel, query: String?, skuSearch: Boolean) : this(
site = site,
searchQuery = query,
isSkuSearch = skuSearch
) {
this.error = error
}
}
class RemoteUpdateProductImagesPayload(
var site: SiteModel,
val product: WCProductModel
) : Payload<ProductError>() {
constructor(
error: ProductError,
site: SiteModel,
product: WCProductModel
) : this(site, product) {
this.error = error
}
}
class RemoteUpdateProductPayload(
var site: SiteModel,
val product: WCProductModel
) : Payload<ProductError>() {
constructor(
error: ProductError,
site: SiteModel,
product: WCProductModel
) : this(site, product) {
this.error = error
}
}
class RemoteUpdateVariationPayload(
var site: SiteModel,
val variation: WCProductVariationModel
) : Payload<ProductError>() {
constructor(
error: ProductError,
site: SiteModel,
variation: WCProductVariationModel
) : this(site, variation) {
this.error = error
}
}
class RemoteProductVariationsPayload(
val site: SiteModel,
val remoteProductId: Long,
val variations: List<WCProductVariationModel> = emptyList(),
var offset: Int = 0,
var loadedMore: Boolean = false,
var canLoadMore: Boolean = false
) : Payload<ProductError>() {
constructor(
error: ProductError,
site: SiteModel,
remoteProductId: Long
) : this(site, remoteProductId) {
this.error = error
}
}
class RemoteProductShippingClassListPayload(
val site: SiteModel,
val shippingClassList: List<WCProductShippingClassModel> = emptyList(),
var offset: Int = 0,
var loadedMore: Boolean = false,
var canLoadMore: Boolean = false
) : Payload<ProductError>() {
constructor(
error: ProductError,
site: SiteModel
) : this(site) {
this.error = error
}
}
class RemoteProductShippingClassPayload(
val productShippingClassModel: WCProductShippingClassModel,
val site: SiteModel
) : Payload<ProductError>() {
constructor(
error: ProductError,
productShippingClassModel: WCProductShippingClassModel,
site: SiteModel
) : this(productShippingClassModel, site) {
this.error = error
}
}
class RemoteProductReviewPayload(
val site: SiteModel,
val productReview: WCProductReviewModel? = null
) : Payload<ProductError>() {
constructor(
error: ProductError,
site: SiteModel
) : this(site) {
this.error = error
}
}
class FetchProductReviewsResponsePayload(
val site: SiteModel,
val reviews: List<WCProductReviewModel> = emptyList(),
val filterProductIds: List<Long>? = null,
val filterByStatus: List<String>? = null,
val loadedMore: Boolean = false,
val canLoadMore: Boolean = false
) : Payload<ProductError>() {
constructor(error: ProductError, site: SiteModel) : this(site) {
this.error = error
}
}
class RemoteProductCategoriesPayload(
val site: SiteModel,
val categories: List<WCProductCategoryModel> = emptyList(),
var offset: Int = 0,
var loadedMore: Boolean = false,
var canLoadMore: Boolean = false
) : Payload<ProductError>() {
constructor(
error: ProductError,
site: SiteModel
) : this(site) {
this.error = error
}
}
class RemoteAddProductCategoryResponsePayload(
val site: SiteModel,
val category: WCProductCategoryModel?
) : Payload<ProductError>() {
constructor(
error: ProductError,
site: SiteModel,
category: WCProductCategoryModel?
) : this(site, category) {
this.error = error
}
}
class RemoteProductTagsPayload(
val site: SiteModel,
val tags: List<WCProductTagModel> = emptyList(),
var offset: Int = 0,
var loadedMore: Boolean = false,
var canLoadMore: Boolean = false,
var searchQuery: String? = null
) : Payload<ProductError>() {
constructor(
error: ProductError,
site: SiteModel
) : this(site) {
this.error = error
}
}
class RemoteAddProductTagsResponsePayload(
val site: SiteModel,
val tags: List<WCProductTagModel> = emptyList()
) : Payload<ProductError>() {
constructor(
error: ProductError,
site: SiteModel,
addedTags: List<WCProductTagModel> = emptyList()
) : this(site, addedTags) {
this.error = error
}
}
class RemoteAddProductPayload(
var site: SiteModel,
val product: WCProductModel
) : Payload<ProductError>() {
constructor(
error: ProductError,
site: SiteModel,
product: WCProductModel
) : this(site, product) {
this.error = error
}
}
class RemoteDeleteProductPayload(
var site: SiteModel,
val remoteProductId: Long
) : Payload<ProductError>() {
constructor(
error: ProductError,
site: SiteModel,
remoteProductId: Long
) : this(site, remoteProductId) {
this.error = error
}
}
// OnChanged events
class OnProductChanged(
var rowsAffected: Int,
var remoteProductId: Long = 0L, // only set for fetching or deleting a single product
var canLoadMore: Boolean = false
) : OnChanged<ProductError>() {
var causeOfChange: WCProductAction? = null
}
class OnVariationChanged(
var remoteProductId: Long = 0L,
var remoteVariationId: Long = 0L
) : OnChanged<ProductError>()
class OnProductSkuAvailabilityChanged(
var sku: String,
var available: Boolean
) : OnChanged<ProductError>() {
var causeOfChange: WCProductAction? = null
}
class OnProductsSearched(
var searchQuery: String?,
var isSkuSearch: Boolean = false,
var searchResults: List<WCProductModel> = emptyList(),
var canLoadMore: Boolean = false
) : OnChanged<ProductError>()
class OnProductReviewChanged(
var rowsAffected: Int,
var canLoadMore: Boolean = false
) : OnChanged<ProductError>() {
var causeOfChange: WCProductAction? = null
}
class OnProductShippingClassesChanged(
var rowsAffected: Int,
var canLoadMore: Boolean = false
) : OnChanged<ProductError>() {
var causeOfChange: WCProductAction? = null
}
class OnProductImagesChanged(
var rowsAffected: Int,
var remoteProductId: Long
) : OnChanged<ProductError>() {
var causeOfChange: WCProductAction? = null
}
class OnProductPasswordChanged(
var remoteProductId: Long,
var password: String?
) : OnChanged<ProductError>() {
var causeOfChange: WCProductAction? = null
}
class OnProductUpdated(
var rowsAffected: Int,
var remoteProductId: Long
) : OnChanged<ProductError>() {
var causeOfChange: WCProductAction? = null
}
class OnVariationUpdated(
var rowsAffected: Int,
var remoteProductId: Long,
var remoteVariationId: Long
) : OnChanged<ProductError>() {
var causeOfChange: WCProductAction? = null
}
class OnProductCategoryChanged(
var rowsAffected: Int,
var canLoadMore: Boolean = false
) : OnChanged<ProductError>() {
var causeOfChange: WCProductAction? = null
}
class OnProductTagChanged(
var rowsAffected: Int,
var canLoadMore: Boolean = false
) : OnChanged<ProductError>() {
var causeOfChange: WCProductAction? = null
}
class OnProductCreated(
var rowsAffected: Int,
var remoteProductId: Long = 0L
) : OnChanged<ProductError>() {
var causeOfChange: WCProductAction? = null
}
/**
* returns the corresponding product from the database as a [WCProductModel].
*/
fun getProductByRemoteId(site: SiteModel, remoteProductId: Long): WCProductModel? =
ProductSqlUtils.getProductByRemoteId(site, remoteProductId)
/**
* returns the corresponding variation from the database as a [WCProductVariationModel].
*/
fun getVariationByRemoteId(
site: SiteModel,
remoteProductId: Long,
remoteVariationId: Long
): WCProductVariationModel? =
ProductSqlUtils.getVariationByRemoteId(site, remoteProductId, remoteVariationId)
/**
* returns true if the corresponding product exists in the database
*/
fun geProductExistsByRemoteId(site: SiteModel, remoteProductId: Long) =
ProductSqlUtils.geProductExistsByRemoteId(site, remoteProductId)
/**
* returns true if the product exists with this [sku] in the database
*/
fun geProductExistsBySku(site: SiteModel, sku: String) =
ProductSqlUtils.getProductExistsBySku(site, sku)
/**
* returns a list of variations for a specific product in the database
*/
fun getVariationsForProduct(site: SiteModel, remoteProductId: Long): List<WCProductVariationModel> =
ProductSqlUtils.getVariationsForProduct(site, remoteProductId)
/**
* returns a list of shipping classes for a specific site in the database
*/
fun getShippingClassListForSite(site: SiteModel): List<WCProductShippingClassModel> =
ProductSqlUtils.getProductShippingClassListForSite(site.id)
/**
* returns the corresponding product shipping class from the database as a [WCProductShippingClassModel].
*/
fun getShippingClassByRemoteId(site: SiteModel, remoteShippingClassId: Long): WCProductShippingClassModel? =
ProductSqlUtils.getProductShippingClassByRemoteId(remoteShippingClassId, site.id)
/**
* returns a list of [WCProductModel] for the give [SiteModel] and [remoteProductIds]
* if it exists in the database
*/
fun getProductsByRemoteIds(site: SiteModel, remoteProductIds: List<Long>): List<WCProductModel> =
ProductSqlUtils.getProductsByRemoteIds(site, remoteProductIds)
/**
* returns a list of [WCProductModel] for the given [SiteModel] and [filterOptions]
* if it exists in the database. To filter by category, make sure the [filterOptions] value
* is the category ID in String.
*/
fun getProductsByFilterOptions(
site: SiteModel,
filterOptions: Map<ProductFilterOption, String>,
sortType: ProductSorting = DEFAULT_PRODUCT_SORTING,
excludedProductIds: List<Long>? = null
): List<WCProductModel> =
ProductSqlUtils.getProductsByFilterOptions(site, filterOptions, sortType, excludedProductIds)
fun getProductsForSite(site: SiteModel, sortType: ProductSorting = DEFAULT_PRODUCT_SORTING) =
ProductSqlUtils.getProductsForSite(site, sortType)
fun deleteProductsForSite(site: SiteModel) = ProductSqlUtils.deleteProductsForSite(site)
fun getProductReviewsForSite(site: SiteModel): List<WCProductReviewModel> =
ProductSqlUtils.getProductReviewsForSite(site)
fun getProductReviewsForProductAndSiteId(localSiteId: Int, remoteProductId: Long): List<WCProductReviewModel> =
ProductSqlUtils.getProductReviewsForProductAndSiteId(localSiteId, remoteProductId)
/**
* returns the count of products for the given [SiteModel] and [remoteProductIds]
* if it exists in the database
*/
fun getProductCountByRemoteIds(site: SiteModel, remoteProductIds: List<Long>): Int =
ProductSqlUtils.getProductCountByRemoteIds(site, remoteProductIds)
/**
* returns the count of virtual products for the given [SiteModel] and [remoteProductIds]
* if it exists in the database
*/
fun getVirtualProductCountByRemoteIds(site: SiteModel, remoteProductIds: List<Long>): Int =
ProductSqlUtils.getVirtualProductCountByRemoteIds(site, remoteProductIds)
/**
* returns a list of tags for a specific site in the database
*/
fun getTagsForSite(site: SiteModel): List<WCProductTagModel> =
ProductSqlUtils.getProductTagsForSite(site.id)
fun getProductTagsByNames(site: SiteModel, tagNames: List<String>) =
ProductSqlUtils.getProductTagsByNames(site.id, tagNames)
fun getProductTagByName(site: SiteModel, tagName: String) =
ProductSqlUtils.getProductTagByName(site.id, tagName)
fun getProductReviewByRemoteId(
localSiteId: Int,
remoteReviewId: Long
): WCProductReviewModel? = ProductSqlUtils
.getProductReviewByRemoteId(localSiteId, remoteReviewId)
fun deleteProductReviewsForSite(site: SiteModel) = ProductSqlUtils.deleteAllProductReviewsForSite(site)
fun deleteAllProductReviews() = ProductSqlUtils.deleteAllProductReviews()
fun deleteProductImage(site: SiteModel, remoteProductId: Long, remoteMediaId: Long) =
ProductSqlUtils.deleteProductImage(site, remoteProductId, remoteMediaId)
fun getProductCategoriesForSite(site: SiteModel, sortType: ProductCategorySorting = DEFAULT_CATEGORY_SORTING) =
ProductSqlUtils.getProductCategoriesForSite(site, sortType)
fun getProductCategoryByRemoteId(site: SiteModel, remoteId: Long) =
ProductSqlUtils.getProductCategoryByRemoteId(site.id, remoteId)
fun getProductCategoryByNameAndParentId(
site: SiteModel,
categoryName: String,
parentId: Long = 0L
) = ProductSqlUtils.getProductCategoryByNameAndParentId(site.id, categoryName, parentId)
@Suppress("LongMethod", "ComplexMethod")
@Subscribe(threadMode = ThreadMode.ASYNC)
override fun onAction(action: Action<*>) {
val actionType = action.type as? WCProductAction ?: return
when (actionType) {
// remote actions
WCProductAction.FETCH_PRODUCT_SKU_AVAILABILITY ->
fetchProductSkuAvailability(action.payload as FetchProductSkuAvailabilityPayload)
WCProductAction.FETCH_PRODUCTS ->
fetchProducts(action.payload as FetchProductsPayload)
WCProductAction.SEARCH_PRODUCTS ->
searchProducts(action.payload as SearchProductsPayload)
WCProductAction.UPDATE_PRODUCT_IMAGES ->
updateProductImages(action.payload as UpdateProductImagesPayload)
WCProductAction.UPDATE_PRODUCT ->
updateProduct(action.payload as UpdateProductPayload)
WCProductAction.FETCH_SINGLE_PRODUCT_SHIPPING_CLASS ->
fetchProductShippingClass(action.payload as FetchSingleProductShippingClassPayload)
WCProductAction.FETCH_PRODUCT_SHIPPING_CLASS_LIST ->
fetchProductShippingClasses(action.payload as FetchProductShippingClassListPayload)
WCProductAction.FETCH_PRODUCT_PASSWORD ->
fetchProductPassword(action.payload as FetchProductPasswordPayload)
WCProductAction.UPDATE_PRODUCT_PASSWORD ->
updateProductPassword(action.payload as UpdateProductPasswordPayload)
WCProductAction.FETCH_PRODUCT_CATEGORIES ->
fetchProductCategories(action.payload as FetchProductCategoriesPayload)
WCProductAction.ADD_PRODUCT_CATEGORY ->
addProductCategory(action.payload as AddProductCategoryPayload)
WCProductAction.FETCH_PRODUCT_TAGS ->
fetchProductTags(action.payload as FetchProductTagsPayload)
WCProductAction.ADD_PRODUCT_TAGS ->
addProductTags(action.payload as AddProductTagsPayload)
WCProductAction.ADD_PRODUCT ->
addProduct(action.payload as AddProductPayload)
WCProductAction.DELETE_PRODUCT ->
deleteProduct(action.payload as DeleteProductPayload)
// remote responses
WCProductAction.FETCHED_PRODUCT_SKU_AVAILABILITY ->
handleFetchProductSkuAvailabilityCompleted(action.payload as RemoteProductSkuAvailabilityPayload)
WCProductAction.FETCHED_PRODUCTS ->
handleFetchProductsCompleted(action.payload as RemoteProductListPayload)
WCProductAction.SEARCHED_PRODUCTS ->
handleSearchProductsCompleted(action.payload as RemoteSearchProductsPayload)
WCProductAction.UPDATED_PRODUCT_IMAGES ->
handleUpdateProductImages(action.payload as RemoteUpdateProductImagesPayload)
WCProductAction.UPDATED_PRODUCT ->
handleUpdateProduct(action.payload as RemoteUpdateProductPayload)
WCProductAction.FETCHED_PRODUCT_SHIPPING_CLASS_LIST ->
handleFetchProductShippingClassesCompleted(action.payload as RemoteProductShippingClassListPayload)
WCProductAction.FETCHED_SINGLE_PRODUCT_SHIPPING_CLASS ->
handleFetchProductShippingClassCompleted(action.payload as RemoteProductShippingClassPayload)
WCProductAction.FETCHED_PRODUCT_PASSWORD ->
handleFetchProductPasswordCompleted(action.payload as RemoteProductPasswordPayload)
WCProductAction.UPDATED_PRODUCT_PASSWORD ->
handleUpdatedProductPasswordCompleted(action.payload as RemoteUpdatedProductPasswordPayload)
WCProductAction.FETCHED_PRODUCT_CATEGORIES ->
handleFetchProductCategories(action.payload as RemoteProductCategoriesPayload)
WCProductAction.ADDED_PRODUCT_CATEGORY ->
handleAddProductCategory(action.payload as RemoteAddProductCategoryResponsePayload)
WCProductAction.FETCHED_PRODUCT_TAGS ->
handleFetchProductTagsCompleted(action.payload as RemoteProductTagsPayload)
WCProductAction.ADDED_PRODUCT_TAGS ->
handleAddProductTags(action.payload as RemoteAddProductTagsResponsePayload)
WCProductAction.ADDED_PRODUCT ->
handleAddNewProduct(action.payload as RemoteAddProductPayload)
WCProductAction.DELETED_PRODUCT ->
handleDeleteProduct(action.payload as RemoteDeleteProductPayload)
}
}
fun observeProducts(
site: SiteModel,
sortType: ProductSorting = DEFAULT_PRODUCT_SORTING,
filterOptions: Map<ProductFilterOption, String> = emptyMap()
): Flow<List<WCProductModel>> =
ProductSqlUtils.observeProducts(site, sortType, filterOptions)
fun observeVariations(site: SiteModel, productId: Long): Flow<List<WCProductVariationModel>> =
ProductSqlUtils.observeVariations(site, productId)
fun observeCategories(
site: SiteModel,
sortType: ProductCategorySorting = DEFAULT_CATEGORY_SORTING
): Flow<List<WCProductCategoryModel>> =
ProductSqlUtils.observeCategories(site, sortType)
suspend fun submitProductAttributeChanges(
site: SiteModel,
productId: Long,
attributes: List<WCProductModel.ProductAttribute>
): WooResult<WCProductModel> =
coroutineEngine.withDefaultContext(API, this, "submitProductAttributes") {
wcProductRestClient.updateProductAttributes(site, productId, Gson().toJson(attributes))
.asWooResult()
.model?.asProductModel()
?.apply {
localSiteId = site.id
ProductSqlUtils.insertOrUpdateProduct(this)
}
?.let { WooResult(it) }
} ?: WooResult(WooError(WooErrorType.GENERIC_ERROR, UNKNOWN))
suspend fun submitVariationAttributeChanges(
site: SiteModel,
productId: Long,
variationId: Long,
attributes: List<WCProductModel.ProductAttribute>
): WooResult<WCProductVariationModel> =
coroutineEngine.withDefaultContext(API, this, "submitVariationAttributes") {
wcProductRestClient.updateVariationAttributes(site, productId, variationId, Gson().toJson(attributes))
.asWooResult()
.model?.asProductVariationModel()
?.apply {
ProductSqlUtils.insertOrUpdateProductVariation(this)
}
?.let { WooResult(it) }
} ?: WooResult(WooError(WooErrorType.GENERIC_ERROR, UNKNOWN))
suspend fun generateEmptyVariation(
site: SiteModel,
product: WCProductModel
): WooResult<WCProductVariationModel> =
coroutineEngine.withDefaultContext(API, this, "generateEmptyVariation") {
product.attributeList
.filter { it.variation }
.map { ProductVariantOption(it.id, it.name, "") }
.let { Gson().toJson(it) }
.let { wcProductRestClient.generateEmptyVariation(site, product.remoteProductId, it) }
.asWooResult()
.model?.asProductVariationModel()
?.apply {
ProductSqlUtils.insertOrUpdateProductVariation(this)
}
?.let { WooResult(it) }
?: WooResult(WooError(INVALID_RESPONSE, GenericErrorType.INVALID_RESPONSE))
}
suspend fun deleteVariation(
site: SiteModel,
productId: Long,
variationId: Long
): WooResult<WCProductVariationModel> =
coroutineEngine.withDefaultContext(API, this, "deleteVariation") {
wcProductRestClient.deleteVariation(site, productId, variationId)
.asWooResult()
.model?.asProductVariationModel()
?.apply {
ProductSqlUtils.deleteVariationsForProduct(site, productId)
}
?.let { WooResult(it) }
?: WooResult(WooError(INVALID_RESPONSE, GenericErrorType.INVALID_RESPONSE))
}
override fun onRegister() = AppLog.d(API, "WCProductStore onRegister")
@Suppress("ForbiddenComment")
suspend fun fetchSingleProduct(payload: FetchSingleProductPayload): OnProductChanged {
return coroutineEngine.withDefaultContext(API, this, "fetchSingleProduct") {
val result = with(payload) { wcProductRestClient.fetchSingleProduct(site, remoteProductId) }
return@withDefaultContext if (result.isError) {
OnProductChanged(0).also {
it.error = result.error
it.remoteProductId = result.product.remoteProductId
}
} else {
val rowsAffected = ProductSqlUtils.insertOrUpdateProduct(result.product)
// TODO: 18/08/2021 @wzieba add tests
coroutineEngine.launch(T.DB, this, "cacheProductAddons") {
val domainAddons = mapProductAddonsToDomain(result.product.addons)
addonsDao.cacheProductAddons(
productRemoteId = result.product.remoteProductId,
siteRemoteId = result.site.siteId,
addons = domainAddons
)
}
OnProductChanged(rowsAffected).also {
it.remoteProductId = result.product.remoteProductId
}
}
}
}
suspend fun fetchSingleVariation(
site: SiteModel,
remoteProductId: Long,
remoteVariationId: Long
): OnVariationChanged {
return coroutineEngine.withDefaultContext(T.API, this, "fetchSingleVariation") {
val result = wcProductRestClient
.fetchSingleVariation(site, remoteProductId, remoteVariationId)
return@withDefaultContext if (result.isError) {
OnVariationChanged().also {
it.error = result.error
it.remoteProductId = result.variation.remoteProductId
it.remoteVariationId = result.variation.remoteVariationId
}
} else {
ProductSqlUtils.insertOrUpdateProductVariation(result.variation)
OnVariationChanged().also {
it.remoteProductId = result.variation.remoteProductId
it.remoteVariationId = result.variation.remoteVariationId
}
}
}
}
private fun fetchProductSkuAvailability(payload: FetchProductSkuAvailabilityPayload) {
with(payload) { wcProductRestClient.fetchProductSkuAvailability(site, sku) }
}
private fun fetchProducts(payload: FetchProductsPayload) {
with(payload) {
wcProductRestClient.fetchProducts(
site = site,
pageSize = pageSize,
offset = offset,
sortType = sorting,
includedProductIds = remoteProductIds,
filterOptions = filterOptions,
excludedProductIds = excludedProductIds
)
}
}
suspend fun fetchProductListSynced(site: SiteModel, productIds: List<Long>): List<WCProductModel>? {
return coroutineEngine.withDefaultContext(API, this, "fetchProductList") {
wcProductRestClient.fetchProductsWithSyncRequest(site = site, includedProductIds = productIds).result
}?.also {
ProductSqlUtils.insertOrUpdateProducts(it)
}
}
suspend fun fetchProductCategoryListSynced(
site: SiteModel,
categoryIds: List<Long>
): List<WCProductCategoryModel>? {
return coroutineEngine.withDefaultContext(API, this, "fetchProductCategoryList") {
wcProductRestClient.fetchProductsCategoriesWithSyncRequest(
site = site,
includedCategoryIds = categoryIds
).result
}?.also {
ProductSqlUtils.insertOrUpdateProductCategories(it)
}
}
private fun searchProducts(payload: SearchProductsPayload) {
with(payload) {
wcProductRestClient.searchProducts(
site = site,
searchQuery = searchQuery,
isSkuSearch = isSkuSearch,
pageSize = pageSize,
offset = offset,
sorting = sorting,
excludedProductIds = excludedProductIds
)
}
}
suspend fun fetchProductVariations(payload: FetchProductVariationsPayload): OnProductChanged {
return coroutineEngine.withDefaultContext(API, this, "fetchProductVariations") {
val result = with(payload) {
wcProductRestClient.fetchProductVariations(site, remoteProductId, pageSize, offset)
}
return@withDefaultContext if (result.isError) {
OnProductChanged(0, payload.remoteProductId).also { it.error = result.error }
} else {
// delete product variations for site if this is the first page of results, otherwise
// product variations deleted outside of the app will persist
if (result.offset == 0) {
ProductSqlUtils.deleteVariationsForProduct(result.site, result.remoteProductId)
}
val rowsAffected = ProductSqlUtils.insertOrUpdateProductVariations(
result.variations
)
OnProductChanged(rowsAffected, payload.remoteProductId, canLoadMore = result.canLoadMore)
}
}
}
private fun fetchProductShippingClass(payload: FetchSingleProductShippingClassPayload) {
with(payload) { wcProductRestClient.fetchSingleProductShippingClass(site, remoteShippingClassId) }
}
private fun fetchProductShippingClasses(payload: FetchProductShippingClassListPayload) {
with(payload) { wcProductRestClient.fetchProductShippingClassList(site, pageSize, offset) }
}
suspend fun fetchProductReviews(payload: FetchProductReviewsPayload): OnProductReviewChanged {
return coroutineEngine.withDefaultContext(API, this, "fetchProductReviews") {
val response = with(payload) {
wcProductRestClient.fetchProductReviews(site, offset, reviewIds, productIds, filterByStatus)
}
val onProductReviewChanged = if (response.isError) {
OnProductReviewChanged(0).also { it.error = response.error }
} else {
// Clear existing product reviews if this is a fresh fetch (loadMore = false).
// This is the simplest way to keep our local reviews in sync with remote reviews
// in case of deletions.
if (!response.loadedMore) {
ProductSqlUtils.deleteAllProductReviewsForSite(response.site)
}
val rowsAffected = ProductSqlUtils.insertOrUpdateProductReviews(response.reviews)
OnProductReviewChanged(rowsAffected, canLoadMore = response.canLoadMore)
}
onProductReviewChanged
}
}
suspend fun fetchSingleProductReview(payload: FetchSingleProductReviewPayload): OnProductReviewChanged {
return coroutineEngine.withDefaultContext(API, this, "fetchSingleProductReview") {
val result = wcProductRestClient.fetchProductReviewById(payload.site, payload.remoteReviewId)
return@withDefaultContext if (result.isError) {
OnProductReviewChanged(0).also { it.error = result.error }
} else {
val rowsAffected = result.productReview?.let {
ProductSqlUtils.insertOrUpdateProductReview(it)
} ?: 0
OnProductReviewChanged(rowsAffected)
}
}
}
private fun fetchProductPassword(payload: FetchProductPasswordPayload) {
with(payload) { wcProductRestClient.fetchProductPassword(site, remoteProductId) }
}
private fun updateProductPassword(payload: UpdateProductPasswordPayload) {
with(payload) { wcProductRestClient.updateProductPassword(site, remoteProductId, password) }
}
suspend fun updateProductReviewStatus(site: SiteModel, reviewId: Long, newStatus: String) =
coroutineEngine.withDefaultContext(API, this, "updateProductReviewStatus") {
val result = wcProductRestClient.updateProductReviewStatus(site, reviewId, newStatus)
return@withDefaultContext if (result.isError) {
WooResult(result.error)
} else {
result.result?.let { review ->
if (review.status == "spam" || review.status == "trash") {
// Delete this review from the database
ProductSqlUtils.deleteProductReview(review)
} else {
// Insert or update in the database
ProductSqlUtils.insertOrUpdateProductReview(review)
}
}
WooResult(result.result)
}
}
private fun updateProductImages(payload: UpdateProductImagesPayload) {
with(payload) { wcProductRestClient.updateProductImages(site, remoteProductId, imageList) }
}
private fun fetchProductCategories(payloadProduct: FetchProductCategoriesPayload) {
with(payloadProduct) {
wcProductRestClient.fetchProductCategories(
site, pageSize, offset, productCategorySorting
)
}
}
private fun addProductCategory(payload: AddProductCategoryPayload) {
with(payload) { wcProductRestClient.addProductCategory(site, category) }
}
private fun fetchProductTags(payload: FetchProductTagsPayload) {
with(payload) { wcProductRestClient.fetchProductTags(site, pageSize, offset, searchQuery) }
}
private fun addProductTags(payload: AddProductTagsPayload) {
with(payload) { wcProductRestClient.addProductTags(site, tags) }
}
private fun updateProduct(payload: UpdateProductPayload) {
with(payload) {
val storedProduct = getProductByRemoteId(site, product.remoteProductId)
wcProductRestClient.updateProduct(site, storedProduct, product)
}
}
suspend fun updateVariation(payload: UpdateVariationPayload): OnVariationUpdated {
return coroutineEngine.withDefaultContext(API, this, "updateVariation") {
with(payload) {
val storedVariation = getVariationByRemoteId(
site,
variation.remoteProductId,
variation.remoteVariationId
)
val result: RemoteUpdateVariationPayload = wcProductRestClient.updateVariation(
site,
storedVariation,
variation
)
return@withDefaultContext if (result.isError) {
OnVariationUpdated(
0,
result.variation.remoteProductId,
result.variation.remoteVariationId
).also { it.error = result.error }
} else {
val rowsAffected = ProductSqlUtils.insertOrUpdateProductVariation(
result.variation
)
OnVariationUpdated(
rowsAffected,
result.variation.remoteProductId,
result.variation.remoteVariationId
)
}
}
}
}
/**
* Batch updates variations on the backend and updates variations locally after successful request.
*
* @param payload Instance of [BatchUpdateVariationsPayload]. It can be produced using
* [BatchUpdateVariationsPayload.Builder] class.
*/
suspend fun batchUpdateVariations(payload: BatchUpdateVariationsPayload):
WooResult<BatchProductVariationsUpdateApiResponse> =
coroutineEngine.withDefaultContext(API, this, "batchUpdateVariations") {
with(payload) {
val result: WooPayload<BatchProductVariationsUpdateApiResponse> =
wcProductRestClient.batchUpdateVariations(
site,
remoteProductId,
remoteVariationsIds,
modifiedProperties
)
return@withDefaultContext if (result.isError) {
WooResult(result.error)
} else {
val updatedVariations = result.result?.updatedVariations?.map { response ->
response.asProductVariationModel().apply {
remoteProductId = payload.remoteProductId
localSiteId = payload.site.id
}
} ?: emptyList()
ProductSqlUtils.insertOrUpdateProductVariations(updatedVariations)
WooResult(result.result)
}
}
}
suspend fun fetchProductCategories(
site: SiteModel,
offset: Int = 0,
pageSize: Int = DEFAULT_PRODUCT_CATEGORY_PAGE_SIZE,
sortType: ProductCategorySorting = DEFAULT_CATEGORY_SORTING,
includedCategoryIds: List<Long> = emptyList(),
excludedCategoryIds: List<Long> = emptyList()
): WooResult<Boolean> {
return coroutineEngine.withDefaultContext(API, this, "fetchProductCategories") {
val response = wcProductRestClient.fetchProductsCategoriesWithSyncRequest(
site = site,
offset = offset,
pageSize = pageSize,
productCategorySorting = sortType,
includedCategoryIds = includedCategoryIds,
excludedCategoryIds = excludedCategoryIds
)
when {
response.isError -> WooResult(response.error)
response.result != null -> {
if (offset == 0 && includedCategoryIds.isEmpty() && excludedCategoryIds.isEmpty()) {
ProductSqlUtils.deleteAllProductCategories()
}
ProductSqlUtils.insertOrUpdateProductCategories(response.result)
val canLoadMore = response.result.size == pageSize
WooResult(canLoadMore)
}
else -> WooResult(WooError(WooErrorType.GENERIC_ERROR, UNKNOWN))
}
}
}
// Returns a boolean indicating whether more coupons can be fetched
@Suppress("ComplexCondition")
suspend fun fetchProducts(
site: SiteModel,
offset: Int = 0,
pageSize: Int = DEFAULT_PRODUCT_PAGE_SIZE,
sortType: ProductSorting = DEFAULT_PRODUCT_SORTING,
includedProductIds: List<Long> = emptyList(),
excludedProductIds: List<Long> = emptyList(),
filterOptions: Map<ProductFilterOption, String> = emptyMap()
): WooResult<Boolean> {
return coroutineEngine.withDefaultContext(API, this, "fetchProducts") {
val response = wcProductRestClient.fetchProductsWithSyncRequest(
site = site,
offset = offset,
pageSize = pageSize,
sortType = sortType,
includedProductIds = includedProductIds,
excludedProductIds = excludedProductIds,
filterOptions = filterOptions
)
when {
response.isError -> WooResult(response.error)
response.result != null -> {
if (offset == 0 &&
includedProductIds.isEmpty() &&
excludedProductIds.isEmpty() &&
filterOptions.isEmpty()
) {
ProductSqlUtils.deleteProductsForSite(site)
}
ProductSqlUtils.insertOrUpdateProducts(response.result)
val canLoadMore = response.result.size == pageSize
WooResult(canLoadMore)
}
else -> WooResult(WooError(WooErrorType.GENERIC_ERROR, UNKNOWN))
}
}
}
suspend fun searchProducts(
site: SiteModel,
searchString: String,
isSkuSearch: Boolean = false,
offset: Int = 0,
pageSize: Int = DEFAULT_PRODUCT_PAGE_SIZE
): WooResult<ProductSearchResult> {
return coroutineEngine.withDefaultContext(API, this, "searchProducts") {
val response = wcProductRestClient.fetchProductsWithSyncRequest(
site = site,
offset = offset,
pageSize = pageSize,
searchQuery = searchString,
isSkuSearch = isSkuSearch
)
when {
response.isError -> WooResult(response.error)
response.result != null -> {
ProductSqlUtils.insertOrUpdateProducts(response.result)
val productIds = response.result.map { it.remoteProductId }
val products = if (productIds.isNotEmpty()) {
ProductSqlUtils.getProductsByRemoteIds(site, productIds)
} else {
emptyList()
}
val canLoadMore = response.result.size == pageSize
WooResult(ProductSearchResult(products, canLoadMore))
}
else -> WooResult(WooError(WooErrorType.GENERIC_ERROR, UNKNOWN))
}
}
}
suspend fun searchProductCategories(
site: SiteModel,
searchString: String,
offset: Int = 0,
pageSize: Int = DEFAULT_PRODUCT_CATEGORY_PAGE_SIZE
): WooResult<ProductCategorySearchResult> {
return coroutineEngine.withDefaultContext(
API,
this,
"searchProductCategories"
) {
val response = wcProductRestClient.fetchProductsCategoriesWithSyncRequest(
site = site,
offset = offset,
pageSize = pageSize,
searchQuery = searchString
)
when {
response.isError -> WooResult(response.error)
response.result != null -> {
ProductSqlUtils.insertOrUpdateProductCategories(response.result)
val categoryIds = response.result.map { it.remoteCategoryId }
val categories = if (categoryIds.isNotEmpty()) {
ProductSqlUtils.getProductCategoriesByRemoteIds(site, categoryIds)
} else {
emptyList()
}
val canLoadMore = response.result.size == pageSize
WooResult(ProductCategorySearchResult(categories, canLoadMore))
}
else -> WooResult(WooError(WooErrorType.GENERIC_ERROR, UNKNOWN))
}
}
}
// Returns a boolean indicating whether more coupons can be fetched
suspend fun fetchProductVariations(
site: SiteModel,
productId: Long,
offset: Int = 0,
pageSize: Int = DEFAULT_PRODUCT_VARIATIONS_PAGE_SIZE,
includedVariationIds: List<Long> = emptyList(),
excludedVariationIds: List<Long> = emptyList()
): WooResult<Boolean> {
return coroutineEngine.withDefaultContext(API, this, "fetchProductVariations") {
val response = wcProductRestClient.fetchProductVariationsWithSyncRequest(
site = site,
productId = productId,
offset = offset,
pageSize = pageSize,
includedVariationIds = includedVariationIds,
excludedVariationIds = excludedVariationIds
)
when {
response.isError -> WooResult(response.error)
response.result != null -> {
if (offset == 0 &&
includedVariationIds.isEmpty() &&
excludedVariationIds.isEmpty()
) {
ProductSqlUtils.deleteVariationsForProduct(site, productId)
}
ProductSqlUtils.insertOrUpdateProductVariations(response.result)
val canLoadMore = response.result.size == pageSize
WooResult(canLoadMore)
}
else -> WooResult(WooError(WooErrorType.GENERIC_ERROR, UNKNOWN))
}
}
}
private fun addProduct(payload: AddProductPayload) {
with(payload) {
wcProductRestClient.addProduct(site, product)
}
}
private fun deleteProduct(payload: DeleteProductPayload) {
with(payload) {
wcProductRestClient.deleteProduct(site, remoteProductId, forceDelete)
}
}
private fun mapProductAddonsToDomain(remoteAddons: Array<RemoteAddonDto>?): List<Addon> {
return remoteAddons.orEmpty()
.toList()
.mapNotNull { remoteAddonDto ->
try {
RemoteAddonMapper.toDomain(remoteAddonDto)
} catch (exception: MappingRemoteException) {
logger.e(API, "Exception while parsing $remoteAddonDto: ${exception.message}")
null
}
}
}
private fun handleFetchProductSkuAvailabilityCompleted(payload: RemoteProductSkuAvailabilityPayload) {
val onProductSkuAvailabilityChanged = OnProductSkuAvailabilityChanged(payload.sku, payload.available)
if (payload.isError) {
onProductSkuAvailabilityChanged.also { it.error = payload.error }
}
onProductSkuAvailabilityChanged.causeOfChange = WCProductAction.FETCH_PRODUCT_SKU_AVAILABILITY
emitChange(onProductSkuAvailabilityChanged)
}
@Suppress("ForbiddenComment")
private fun handleFetchProductsCompleted(payload: RemoteProductListPayload) {
coroutineEngine.launch(T.DB, this, "handleFetchProductsCompleted") {
val onProductChanged: OnProductChanged
if (payload.isError) {
onProductChanged = OnProductChanged(0).also { it.error = payload.error }
} else {
// remove the existing products for this site if this is the first page of results
// or if the remoteProductIds or excludedProductIds are null, otherwise
// products deleted outside of the app will persist
if (payload.offset == 0 && payload.remoteProductIds == null && payload.excludedProductIds == null) {
ProductSqlUtils.deleteProductsForSite(payload.site)
}
val rowsAffected = ProductSqlUtils.insertOrUpdateProducts(payload.products)
onProductChanged = OnProductChanged(rowsAffected, canLoadMore = payload.canLoadMore)
// TODO: 18/08/2021 @wzieba add tests
coroutineEngine.launch(T.DB, this, "cacheProductsAddons") {
payload.products.forEach { product ->
val domainAddons = mapProductAddonsToDomain(product.addons)
addonsDao.cacheProductAddons(
productRemoteId = product.remoteProductId,
siteRemoteId = payload.site.siteId,
addons = domainAddons
)
}
}
}
onProductChanged.causeOfChange = WCProductAction.FETCH_PRODUCTS
emitChange(onProductChanged)
}
}
private fun handleSearchProductsCompleted(payload: RemoteSearchProductsPayload) {
if (payload.isError) {
emitChange(
OnProductsSearched(
searchQuery = payload.searchQuery,
isSkuSearch = payload.isSkuSearch
)
)
} else {
coroutineEngine.launch(T.DB, this, "handleSearchProductsCompleted") {
ProductSqlUtils.insertOrUpdateProducts(payload.products)
emitChange(
OnProductsSearched(
searchQuery = payload.searchQuery,
isSkuSearch = payload.isSkuSearch,
searchResults = payload.products,
canLoadMore = payload.canLoadMore
)
)
}
}
}
private fun handleFetchProductShippingClassesCompleted(payload: RemoteProductShippingClassListPayload) {
val onProductShippingClassesChanged = if (payload.isError) {
OnProductShippingClassesChanged(0).also { it.error = payload.error }
} else {
// delete product shipping class list for site if this is the first page of results, otherwise
// shipping class list deleted outside of the app will persist
if (payload.offset == 0) {
ProductSqlUtils.deleteProductShippingClassListForSite(payload.site)
}
val rowsAffected = ProductSqlUtils.insertOrUpdateProductShippingClassList(payload.shippingClassList)
OnProductShippingClassesChanged(rowsAffected, canLoadMore = payload.canLoadMore)
}
onProductShippingClassesChanged.causeOfChange = WCProductAction.FETCH_PRODUCT_SHIPPING_CLASS_LIST
emitChange(onProductShippingClassesChanged)
}
private fun handleFetchProductShippingClassCompleted(payload: RemoteProductShippingClassPayload) {
val onProductShippingClassesChanged = if (payload.isError) {
OnProductShippingClassesChanged(0).also { it.error = payload.error }
} else {
val rowsAffected = ProductSqlUtils.insertOrUpdateProductShippingClass(payload.productShippingClassModel)
OnProductShippingClassesChanged(rowsAffected)
}
onProductShippingClassesChanged.causeOfChange = WCProductAction.FETCH_SINGLE_PRODUCT_SHIPPING_CLASS
emitChange(onProductShippingClassesChanged)
}
private fun handleFetchProductPasswordCompleted(payload: RemoteProductPasswordPayload) {
val onProductPasswordChanged = if (payload.isError) {
OnProductPasswordChanged(payload.remoteProductId, "").also { it.error = payload.error }
} else {
OnProductPasswordChanged(payload.remoteProductId, payload.password)
}
onProductPasswordChanged.causeOfChange = WCProductAction.FETCH_PRODUCT_PASSWORD
emitChange(onProductPasswordChanged)
}
private fun handleUpdatedProductPasswordCompleted(payload: RemoteUpdatedProductPasswordPayload) {
val onProductPasswordUpdated = if (payload.isError) {
OnProductPasswordChanged(payload.remoteProductId, null).also { it.error = payload.error }
} else {
OnProductPasswordChanged(payload.remoteProductId, payload.password)
}
onProductPasswordUpdated.causeOfChange = WCProductAction.UPDATE_PRODUCT_PASSWORD
emitChange(onProductPasswordUpdated)
}
private fun handleUpdateProductImages(payload: RemoteUpdateProductImagesPayload) {
coroutineEngine.launch(T.DB, this, "handleUpdateProductImages") {
val onProductImagesChanged: OnProductImagesChanged
if (payload.isError) {
onProductImagesChanged = OnProductImagesChanged(
0,
payload.product.remoteProductId
).also {
it.error = payload.error
}
} else {
val rowsAffected = ProductSqlUtils.insertOrUpdateProduct(payload.product)
onProductImagesChanged = OnProductImagesChanged(
rowsAffected,
payload.product.remoteProductId
)
}
onProductImagesChanged.causeOfChange = WCProductAction.UPDATED_PRODUCT_IMAGES
emitChange(onProductImagesChanged)
}
}
private fun handleUpdateProduct(payload: RemoteUpdateProductPayload) {
coroutineEngine.launch(T.DB, this, "handleUpdateProduct") {
val onProductUpdated: OnProductUpdated
if (payload.isError) {
onProductUpdated = OnProductUpdated(0, payload.product.remoteProductId)
.also { it.error = payload.error }
} else {
val rowsAffected = ProductSqlUtils.insertOrUpdateProduct(payload.product)
onProductUpdated = OnProductUpdated(rowsAffected, payload.product.remoteProductId)
}
onProductUpdated.causeOfChange = WCProductAction.UPDATED_PRODUCT
emitChange(onProductUpdated)
}
}
private fun handleFetchProductCategories(payload: RemoteProductCategoriesPayload) {
coroutineEngine.launch(T.DB, this, "handleFetchProductCategories") {
val onProductCategoryChanged: OnProductCategoryChanged
if (payload.isError) {
onProductCategoryChanged = OnProductCategoryChanged(0).also { it.error = payload.error }
} else {
// Clear existing product categories if this is a fresh fetch (loadMore = false).
// This is the simplest way to keep our local categories in sync with remote categories
// in case of deletions.
if (!payload.loadedMore) {
ProductSqlUtils.deleteAllProductCategoriesForSite(payload.site)
}
val rowsAffected = ProductSqlUtils.insertOrUpdateProductCategories(
payload.categories
)
onProductCategoryChanged = OnProductCategoryChanged(
rowsAffected,
canLoadMore = payload.canLoadMore
)
}
onProductCategoryChanged.causeOfChange = WCProductAction.FETCH_PRODUCT_CATEGORIES
emitChange(onProductCategoryChanged)
}
}
private fun handleAddProductCategory(payload: RemoteAddProductCategoryResponsePayload) {
coroutineEngine.launch(T.DB, this, "handleAddProductCategory") {
val onProductCategoryChanged: OnProductCategoryChanged
if (payload.isError) {
onProductCategoryChanged = OnProductCategoryChanged(0).also { it.error = payload.error }
} else {
val rowsAffected = payload.category?.let {
ProductSqlUtils.insertOrUpdateProductCategory(it)
} ?: 0
onProductCategoryChanged = OnProductCategoryChanged(rowsAffected)
}
onProductCategoryChanged.causeOfChange = WCProductAction.ADDED_PRODUCT_CATEGORY
emitChange(onProductCategoryChanged)
}
}
private fun handleFetchProductTagsCompleted(payload: RemoteProductTagsPayload) {
val onProductTagsChanged = if (payload.isError) {
OnProductTagChanged(0).also { it.error = payload.error }
} else {
// delete product tags for site if this is the first page of results, otherwise
// tags deleted outside of the app will persist
if (payload.offset == 0 && payload.searchQuery.isNullOrEmpty()) {
ProductSqlUtils.deleteProductTagsForSite(payload.site)
}
val rowsAffected = ProductSqlUtils.insertOrUpdateProductTags(payload.tags)
OnProductTagChanged(rowsAffected, canLoadMore = payload.canLoadMore)
}
onProductTagsChanged.causeOfChange = WCProductAction.FETCH_PRODUCT_TAGS
emitChange(onProductTagsChanged)
}
private fun handleAddProductTags(payload: RemoteAddProductTagsResponsePayload) {
val onProductTagsChanged: OnProductTagChanged
if (payload.isError) {
onProductTagsChanged = OnProductTagChanged(0).also { it.error = payload.error }
} else {
val rowsAffected = ProductSqlUtils.insertOrUpdateProductTags(payload.tags.filter { it.name.isNotEmpty() })
onProductTagsChanged = OnProductTagChanged(rowsAffected)
}
onProductTagsChanged.causeOfChange = WCProductAction.ADDED_PRODUCT_TAGS
emitChange(onProductTagsChanged)
}
private fun handleAddNewProduct(payload: RemoteAddProductPayload) {
coroutineEngine.launch(T.DB, this, "handleAddNewProduct") {
val onProductCreated: OnProductCreated
if (payload.isError) {
onProductCreated = OnProductCreated(
0,
payload.product.remoteProductId
).also { it.error = payload.error }
} else {
val rowsAffected = ProductSqlUtils.insertOrUpdateProduct(payload.product)
onProductCreated = OnProductCreated(rowsAffected, payload.product.remoteProductId)
}
onProductCreated.causeOfChange = WCProductAction.ADDED_PRODUCT
emitChange(onProductCreated)
}
}
private fun handleDeleteProduct(payload: RemoteDeleteProductPayload) {
coroutineEngine.launch(T.DB, this, "handleDeleteProduct") {
val onProductChanged: OnProductChanged
if (payload.isError) {
onProductChanged = OnProductChanged(0).also { it.error = payload.error }
} else {
val rowsAffected = ProductSqlUtils.deleteProduct(
payload.site,
payload.remoteProductId
)
onProductChanged = OnProductChanged(rowsAffected, payload.remoteProductId)
}
onProductChanged.causeOfChange = WCProductAction.DELETED_PRODUCT
emitChange(onProductChanged)
}
}
data class ProductSearchResult(
val products: List<WCProductModel>,
val canLoadMore: Boolean
)
data class ProductCategorySearchResult(
val categories: List<WCProductCategoryModel>,
val canLoadMore: Boolean
)
}
| gpl-2.0 | c0cdaaa8b3a41071ff992e05ba759c3d | 39.248879 | 118 | 0.631135 | 5.947979 | false | false | false | false |
LanternPowered/LanternServer | src/main/kotlin/org/lanternpowered/server/registry/type/effect/particle/ParticleOptionRegistry.kt | 1 | 2211 | /*
* Lantern
*
* Copyright (c) LanternPowered <https://www.lanternpowered.org>
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* This work is licensed under the terms of the MIT License (MIT). For
* a copy, see 'LICENSE.txt' or <https://opensource.org/licenses/MIT>.
*/
package org.lanternpowered.server.registry.type.effect.particle
import org.lanternpowered.api.effect.firework.FireworkEffect
import org.lanternpowered.api.registry.CatalogTypeRegistry
import org.lanternpowered.api.registry.CatalogTypeRegistryBuilder
import org.lanternpowered.api.registry.catalogTypeRegistry
import org.lanternpowered.server.effect.particle.LanternParticleOption
import org.lanternpowered.api.key.NamespacedKey
import org.spongepowered.api.block.BlockState
import org.spongepowered.api.data.type.NotePitch
import org.spongepowered.api.effect.particle.ParticleOption
import org.spongepowered.api.effect.potion.PotionEffectType
import org.spongepowered.api.item.inventory.ItemStackSnapshot
import org.spongepowered.api.util.Color
import org.spongepowered.api.util.Direction
import org.spongepowered.math.vector.Vector3d
val ParticleOptionRegistry: CatalogTypeRegistry<ParticleOption<*>> = catalogTypeRegistry {
register<BlockState>("block_state")
register<Color>("color")
register<Direction>("direction")
register<List<FireworkEffect>>("firework_effects") { value -> check(value.isNotEmpty()) { "The firework effects list may not be empty" } }
register<Int>("quantity") { value -> check(value >= 1) { "Quantity must be at least 1" } }
register<ItemStackSnapshot>("item_stack_snapshot")
register<NotePitch>("note")
register<Vector3d>("offset")
register<PotionEffectType>("potion_effect_type")
register<Double>("scale") { value -> check(value >= 0) { "Scale may not be negative" } }
register<Vector3d>("velocity")
register<Boolean>("slow_horizontal_velocity")
}
private inline fun <reified V> CatalogTypeRegistryBuilder<ParticleOption<*>>.register(
id: String, noinline valueValidator: (V) -> Unit = {}
): ParticleOption<*> = register(LanternParticleOption(NamespacedKey.sponge(id), V::class.java, valueValidator))
| mit | e24c0926fa8d556c317e86b7d625bd47 | 48.133333 | 142 | 0.772049 | 4.219466 | false | false | false | false |
LanternPowered/LanternServer | src/main/kotlin/org/lanternpowered/server/profile/LanternGameProfileCache.kt | 1 | 4180 | /*
* Lantern
*
* Copyright (c) LanternPowered <https://www.lanternpowered.org>
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* This work is licensed under the terms of the MIT License (MIT). For
* a copy, see 'LICENSE.txt' or <https://opensource.org/licenses/MIT>.
*/
package org.lanternpowered.server.profile
import org.lanternpowered.api.profile.GameProfile
import org.lanternpowered.api.service.profile.GameProfileService
import org.lanternpowered.api.util.optional.asOptional
import org.lanternpowered.api.util.optional.orNull
import org.spongepowered.api.profile.GameProfileCache
import java.time.Instant
import java.util.Optional
import java.util.UUID
import java.util.concurrent.CompletableFuture
import java.util.concurrent.ConcurrentHashMap
import java.util.stream.Stream
class LanternGameProfileCache(
private val service: GameProfileService
) : GameProfileCache {
private val byUniqueId = ConcurrentHashMap<UUID, GameProfile>()
override fun getProfiles(): Collection<GameProfile> {
TODO("Not yet implemented")
}
override fun getOrLookupByName(name: String): Optional<GameProfile> {
TODO("Not yet implemented")
}
fun getOrLookupByNameAsync(name: String): CompletableFuture<GameProfile?> {
val cachedProfile = this.getByName(name).orNull()
if (cachedProfile != null)
return CompletableFuture.completedFuture(cachedProfile)
return this.service.getBasicProfile(name).thenApply { profile ->
if (profile != null)
this.add(profile)
profile
}
}
fun lookupByNameAsync(name: String): CompletableFuture<GameProfile?> =
this.service.getBasicProfile(name)
override fun clear() {
TODO("Not yet implemented")
}
override fun getById(uniqueId: UUID): Optional<GameProfile> {
TODO("Not yet implemented")
}
override fun lookupByIds(uniqueIds: Iterable<UUID>): Map<UUID, Optional<GameProfile>> {
TODO("Not yet implemented")
}
override fun getByNames(names: Iterable<String>): Map<String, Optional<GameProfile>> {
TODO("Not yet implemented")
}
override fun lookupByName(name: String): Optional<GameProfile> =
this.lookupByNameAsync(name).get().asOptional()
override fun streamProfiles(): Stream<GameProfile> {
TODO("Not yet implemented")
}
override fun remove(profile: GameProfile): Boolean {
TODO("Not yet implemented")
}
override fun remove(profiles: Iterable<GameProfile>): Collection<GameProfile> {
TODO("Not yet implemented")
}
override fun getByIds(uniqueIds: Iterable<UUID>): Map<UUID, Optional<GameProfile>> {
TODO("Not yet implemented")
}
override fun lookupByNames(names: Iterable<String>): Map<String, Optional<GameProfile>> {
TODO("Not yet implemented")
}
override fun getByName(name: String?): Optional<GameProfile> {
TODO("Not yet implemented")
}
override fun getOrLookupByIds(uniqueIds: Iterable<UUID>): Map<UUID, Optional<GameProfile>> {
TODO("Not yet implemented")
}
override fun add(profile: GameProfile, overwrite: Boolean, expiry: Instant?): Boolean {
TODO("Not yet implemented")
}
override fun getOrLookupByNames(names: Iterable<String>): Map<String, Optional<GameProfile>> {
TODO("Not yet implemented")
}
override fun fillProfile(profile: GameProfile, signed: Boolean): Optional<GameProfile> {
TODO("Not yet implemented")
}
override fun match(name: String): Collection<GameProfile> {
TODO("Not yet implemented")
}
override fun streamOfMatches(name: String): Stream<GameProfile> {
TODO("Not yet implemented")
}
override fun lookupById(uniqueId: UUID): Optional<GameProfile> {
TODO("Not yet implemented")
}
override fun getOrLookupById(uniqueId: UUID): Optional<GameProfile> {
TODO("Not yet implemented")
}
fun getOrLookupByIdAsync(uniqueId: UUID): CompletableFuture<GameProfile?> {
TODO("Not yet implemented")
}
}
| mit | 753728340e2ca19202b4427bdf2cc475 | 30.908397 | 98 | 0.689234 | 4.613687 | false | false | false | false |
LanternPowered/LanternServer | src/main/kotlin/org/lanternpowered/api/util/gson/Gson.kt | 1 | 1939 | /*
* Lantern
*
* Copyright (c) LanternPowered <https://www.lanternpowered.org>
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* This work is licensed under the terms of the MIT License (MIT). For
* a copy, see 'LICENSE.txt' or <https://opensource.org/licenses/MIT>.
*/
@file:Suppress("NOTHING_TO_INLINE")
package org.lanternpowered.api.util.gson
import com.google.gson.Gson
import com.google.gson.JsonElement
import com.google.gson.JsonNull
import org.lanternpowered.api.util.type.TypeToken
import java.io.Reader
import kotlin.reflect.KClass
import kotlin.reflect.KType
import kotlin.reflect.jvm.javaType
fun Gson.fromJson(json: String, type: KType): Any = fromJson(json, type.javaType)
fun Gson.fromJson(json: Reader, type: KType): Any = fromJson(json, type.javaType)
fun Gson.fromJson(json: JsonElement, type: KType): Any = fromJson(json, type.javaType)
fun <T : Any> Gson.fromJson(json: String, type: KClass<T>): T = fromJson(json, type.java)
fun <T : Any> Gson.fromJson(json: Reader, type: KClass<T>): T = fromJson(json, type.java)
fun <T : Any> Gson.fromJson(json: JsonElement, type: KClass<T>): T = fromJson(json, type.java)
fun <T> Gson.fromJson(json: String, type: TypeToken<T>): T = fromJson(json, type.type)
fun <T> Gson.fromJson(json: Reader, type: TypeToken<T>): T = fromJson(json, type.type)
fun <T> Gson.fromJson(json: JsonElement, type: TypeToken<T>): T = fromJson(json, type.type)
inline fun <reified T> Gson.fromJson(json: String): T = fromJson(json, object : TypeToken<T>() {})
inline fun <reified T> Gson.fromJson(json: Reader): T = fromJson(json, object : TypeToken<T>() {})
inline fun <reified T> Gson.fromJson(json: JsonElement): T = fromJson(json, object : TypeToken<T>() {})
private val gson = Gson()
/**
* Parses the [String] as a [JsonElement].
*/
fun String?.parseJson(): JsonElement = if (this == null) JsonNull.INSTANCE else gson.fromJson(this)
| mit | 759bf8bd9407dc8dd3c6b5d3a1928635 | 42.088889 | 103 | 0.723569 | 3.378049 | false | false | false | false |
ratabb/Hishoot2i | app/src/main/java/org/illegaller/ratabb/hishoot2i/ui/main/MainViewModel.kt | 1 | 4943 | package org.illegaller.ratabb.hishoot2i.ui.main
import androidx.annotation.ColorInt
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.SavedStateHandle
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import core.CoreProcess
import dagger.hilt.android.lifecycle.HiltViewModel
import entity.BackgroundMode
import entity.ImageOption
import entity.ImageSourcePath
import kotlinx.coroutines.Dispatchers.IO
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.filter
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.merge
import kotlinx.coroutines.flow.onEach
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import org.illegaller.ratabb.hishoot2i.data.pref.BackgroundToolPref
import org.illegaller.ratabb.hishoot2i.data.pref.BadgeToolPref
import org.illegaller.ratabb.hishoot2i.data.pref.ScreenToolPref
import org.illegaller.ratabb.hishoot2i.data.pref.TemplateToolPref
import org.illegaller.ratabb.hishoot2i.data.source.TemplateSource
import org.illegaller.ratabb.hishoot2i.ui.ARG_BACKGROUND_PATH
import org.illegaller.ratabb.hishoot2i.ui.ARG_SCREEN1_PATH
import org.illegaller.ratabb.hishoot2i.ui.ARG_SCREEN2_PATH
import template.Template
import javax.inject.Inject
@ExperimentalCoroutinesApi
@HiltViewModel
class MainViewModel @Inject constructor(
private val coreProcess: CoreProcess,
private val templateSource: TemplateSource,
private val backgroundToolPref: BackgroundToolPref,
private val badgeToolPref: BadgeToolPref,
private val screenToolPref: ScreenToolPref,
private val templateToolPref: TemplateToolPref,
private val savedStateHandle: SavedStateHandle
) : ViewModel() {
private var lastTemplateId: String? = null
private var lastTemplate: Template? = null
private val isHaveLastTemplate: Boolean
get() = lastTemplateId != null && lastTemplate != null &&
lastTemplateId == templateToolPref.templateCurrentId
private val _uiState = MutableLiveData<MainView>()
internal val uiState: LiveData<MainView>
get() = _uiState
private val sourcePath = ImageSourcePath()
init {
preferenceChanges() //
sourcePath.background = savedStateHandle.get(ARG_BACKGROUND_PATH)
sourcePath.screen1 = savedStateHandle.get(ARG_SCREEN1_PATH)
sourcePath.screen2 = savedStateHandle.get(ARG_SCREEN2_PATH)
}
override fun onCleared() {
lastTemplate = null
lastTemplateId = null
}
fun resume() {
lastTemplateId?.let {
if (it != templateToolPref.templateCurrentId) {
render()
}
}
}
private fun currentTemplate(): Template = if (isHaveLastTemplate) lastTemplate!! else {
templateSource.findByIdOrDefault(templateToolPref.templateCurrentId).also {
lastTemplate = it
lastTemplateId = it.id
}
}
fun render() {
viewModelScope.launch {
_uiState.value = Loading(false)
runCatching { withContext(IO) { coreProcess.preview(currentTemplate(), sourcePath) } }
.fold({ _uiState.value = Success(it) }, { _uiState.value = Fail(it, false) })
}
}
fun save() {
viewModelScope.launch {
_uiState.value = Loading(true)
runCatching { withContext(IO) { coreProcess.save(currentTemplate(), sourcePath) } }
.fold({ _uiState.value = Success(it) }, { _uiState.value = Fail(it, true) })
}
}
fun backgroundColorPipette(@ColorInt color: Int) {
if (backgroundToolPref.backgroundColorInt != color) {
backgroundToolPref.backgroundColorInt = color
}
}
fun changeScreen1(path: String?) {
if (path == null) return
sourcePath.screen1 = path
savedStateHandle.set(ARG_SCREEN1_PATH, path)
render()
}
fun changeScreen2(path: String?) {
if (path == null) return
sourcePath.screen2 = path
savedStateHandle.set(ARG_SCREEN2_PATH, path)
render()
}
fun changeBackground(path: String?) {
if (path == null) return
sourcePath.background = path
savedStateHandle.set(ARG_BACKGROUND_PATH, path)
if (backgroundToolPref.backgroundMode.isImage) render()
else backgroundToolPref.backgroundMode = BackgroundMode.IMAGE
}
@ExperimentalCoroutinesApi
private fun preferenceChanges() {
(
screenToolPref.mainFlow + badgeToolPref.mainFlow +
templateToolPref.mainFlow + backgroundToolPref.mainFlow
)
.merge()
.filter { (it as? ImageOption)?.isManualCrop != true }
.onEach { render() }
.catch { _uiState.value = Fail(it, false) }
.launchIn(viewModelScope)
}
}
| apache-2.0 | 8b6363e4a1bf4df390c72e018b8fa17b | 34.307143 | 98 | 0.697147 | 4.619626 | false | false | false | false |
orhanobut/dialogplus | dialogplus/src/test/java/com/orhanobut/android/dialogplus/ListHolderTest.kt | 2 | 3816 | package com.orhanobut.android.dialogplus
import android.app.Activity
import android.view.LayoutInflater
import android.view.View
import android.widget.ArrayAdapter
import android.widget.LinearLayout
import android.widget.ListView
import com.orhanobut.dialogplus.HolderAdapter
import com.orhanobut.dialogplus.ListHolder
import com.orhanobut.dialogplus.R
import org.assertj.core.api.Assertions.assertThat
import org.assertj.core.api.Assertions.fail
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.Robolectric
import org.robolectric.RobolectricTestRunner
@RunWith(RobolectricTestRunner::class)
class ListHolderTest {
private val context = Robolectric.setupActivity(Activity::class.java)
private val listHolder: ListHolder
get() {
val holder = ListHolder()
val layoutInflater = LayoutInflater.from(context)
holder.getView(layoutInflater, LinearLayout(context))
return holder
}
@Test fun init() {
assertThat(listHolder).isInstanceOf(HolderAdapter::class.java)
assertThat(listHolder).isNotNull()
}
@Test fun testViewInflation() {
val holder = ListHolder()
val layoutInflater = LayoutInflater.from(context)
val view = holder.getView(layoutInflater, LinearLayout(context))
assertThat(view).isNotNull()
assertThat(holder.inflatedView.id).isEqualTo(R.id.dialogplus_list)
val listView = holder.inflatedView as ListView
assertThat(listView.onItemClickListener).isInstanceOf(ListHolder::class.java)
}
@Test fun testFooter() {
val holder = listHolder
assertThat(holder.footer).isNull()
val footer = LinearLayout(context)
holder.addFooter(footer)
assertThat(holder.footer).isEqualTo(footer)
}
@Test fun testHeader() {
val holder = listHolder
assertThat(holder.header).isNull()
val header = LinearLayout(context)
holder.addHeader(header)
assertThat(holder.header).isEqualTo(header)
}
@Test fun testOnItemClickWithoutItemListenerAndAdapter() {
val holder = listHolder
val listView = holder.inflatedView as ListView
try {
listView.performItemClick(null, 0, 0)
} catch (e: Exception) {
fail("it should not crash")
}
}
@Test fun testOnItemClickWithoutItemListenerOnly() {
val holder = listHolder
val listView = holder.inflatedView as ListView
//with adapter set
val adapter = ArrayAdapter(
context, android.R.layout.simple_list_item_1,
arrayOf("test")
)
holder.setAdapter(adapter)
try {
listView.performItemClick(null, 0, 0)
} catch (e: Exception) {
fail("it should not crash")
}
}
@Test fun testOnItemClick() {
val holder = listHolder
val listView = holder.inflatedView as ListView
//with adapter set
val adapter = ArrayAdapter(
context, android.R.layout.simple_list_item_1,
arrayOf("test")
)
holder.setAdapter(adapter)
//set listener
holder.setOnItemClickListener { item, view, position ->
assertThat(item.toString()).isEqualTo("test")
assertThat(position).isEqualTo(0)
assertThat(view).isEqualTo(listView)
}
listView.performItemClick(listView, 0, 0)
}
@Test fun doNotCountHeaderForPositionCalculation() {
val holder = listHolder
holder.addHeader(View(context))
val listView = holder.inflatedView as ListView
//with adapter set
val adapter = ArrayAdapter(
context, android.R.layout.simple_list_item_1,
arrayOf("test")
)
holder.setAdapter(adapter)
//set listener
holder.setOnItemClickListener { item, view, position ->
assertThat(item.toString()).isEqualTo("test")
assertThat(position).isEqualTo(0)
assertThat(view).isEqualTo(listView)
}
listView.performItemClick(listView, 1, 0)
}
}
| apache-2.0 | b7e0efb5be337cc2b5da69864a46b064 | 25.685315 | 81 | 0.714623 | 4.447552 | false | true | false | false |
PKRoma/github-android | app/src/main/java/com/github/pockethub/android/ui/gist/GistsViewActivity.kt | 5 | 7903 | /*
* Copyright (c) 2015 PocketHub
*
* 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.github.pockethub.android.ui.gist
import android.content.Intent
import android.content.Intent.FLAG_ACTIVITY_CLEAR_TOP
import android.content.Intent.FLAG_ACTIVITY_SINGLE_TOP
import android.os.Bundle
import android.util.Log
import android.view.MenuItem
import com.github.pockethub.android.Intents.Builder
import com.github.pockethub.android.Intents.EXTRA_GIST
import com.github.pockethub.android.Intents.EXTRA_GIST_ID
import com.github.pockethub.android.Intents.EXTRA_GIST_IDS
import com.github.pockethub.android.Intents.EXTRA_POSITION
import com.github.pockethub.android.R
import com.github.pockethub.android.core.OnLoadListener
import com.github.pockethub.android.core.gist.GistStore
import com.github.pockethub.android.rx.AutoDisposeUtils
import com.github.pockethub.android.rx.RxProgress
import com.github.pockethub.android.ui.base.BaseActivity
import com.github.pockethub.android.ui.ConfirmDialogFragment
import com.github.pockethub.android.ui.DialogResultListener
import com.github.pockethub.android.ui.MainActivity
import com.github.pockethub.android.ui.helpers.PagerHandler
import com.github.pockethub.android.ui.item.gist.GistItem
import com.github.pockethub.android.ui.user.UriLauncherActivity
import com.github.pockethub.android.util.ToastUtils
import com.meisolsson.githubsdk.core.ServiceGenerator
import com.meisolsson.githubsdk.model.Gist
import com.meisolsson.githubsdk.service.gists.GistService
import com.xwray.groupie.Item
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import kotlinx.android.synthetic.main.activity_pager.*
import java.io.Serializable
import javax.inject.Inject
/**
* Activity to display a collection of Gists in a pager
*/
class GistsViewActivity : BaseActivity(), DialogResultListener, OnLoadListener<Gist> {
@Inject
lateinit var store: GistStore
private var gists: Array<String>? = null
private var gist: Gist? = null
private var initialPosition: Int = 0
private var pagerHandler: PagerHandler<GistsPagerAdapter>? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_pager)
gists = intent.getStringArrayExtra(EXTRA_GIST_IDS)
gist = intent.getParcelableExtra(EXTRA_GIST)
initialPosition = intent.getIntExtra(EXTRA_POSITION, -1)
supportActionBar!!.setDisplayHomeAsUpEnabled(true)
// Support opening this activity with a single Gist that may be present
// in the intent but not currently present in the store
if (gists == null && gist != null) {
if (gist!!.createdAt() != null) {
val stored = store.getGist(gist!!.id())
if (stored == null) {
store.addGist(gist)
}
}
gists = arrayOf(gist!!.id()!!)
}
val adapter = GistsPagerAdapter(this, gists)
pagerHandler = PagerHandler(this, vp_pages, adapter)
lifecycle.addObserver(pagerHandler!!)
pagerHandler!!.onPagedChanged = this::onPageChanged
vp_pages.scheduleSetItem(initialPosition, pagerHandler)
}
override fun onDestroy() {
super.onDestroy()
lifecycle.removeObserver(pagerHandler!!)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
android.R.id.home -> {
finish()
val intent = Intent(this, MainActivity::class.java)
intent.addFlags(FLAG_ACTIVITY_CLEAR_TOP or FLAG_ACTIVITY_SINGLE_TOP)
startActivity(intent)
return true
}
R.id.m_delete -> {
val gistId = gists!![vp_pages.currentItem]
val args = Bundle()
args.putString(EXTRA_GIST_ID, gistId)
ConfirmDialogFragment.show(this, REQUEST_CONFIRM_DELETE,
getString(R.string.confirm_gist_delete_title),
getString(R.string.confirm_gist_delete_message), args)
return true
}
else -> return super.onOptionsItemSelected(item)
}
}
override fun onDialogResult(requestCode: Int, resultCode: Int, arguments: Bundle) {
if (REQUEST_CONFIRM_DELETE == requestCode && RESULT_OK == resultCode) {
val gistId = arguments.getString(EXTRA_GIST_ID)
ServiceGenerator.createService(this, GistService::class.java)
.deleteGist(gistId)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.compose(RxProgress.bindToLifecycle(this, R.string.deleting_gist))
.`as`(AutoDisposeUtils.bindToLifecycle(this))
.subscribe({ response ->
setResult(RESULT_OK)
finish()
}, { e ->
Log.d(TAG, "Exception deleting Gist", e)
ToastUtils.show(this, e.message)
})
return
}
pagerHandler!!.adapter
.onDialogResult(vp_pages.currentItem, requestCode, resultCode, arguments)
}
private fun onPageChanged(position: Int) {
val gistId = gists!![position]
val gist = store.getGist(gistId)
updateActionBar(gist, gistId)
}
override fun startActivity(intent: Intent) {
val converted = UriLauncherActivity.convert(intent)
if (converted != null) {
super.startActivity(converted)
} else {
super.startActivity(intent)
}
}
private fun updateActionBar(gist: Gist?, gistId: String) {
val actionBar = supportActionBar!!
when {
gist == null -> {
actionBar.subtitle = null
actionBar.setLogo(null)
}
gist.owner() != null -> {
actionBar.subtitle = gist.owner()!!.login()
}
else -> {
actionBar.setSubtitle(R.string.anonymous)
actionBar.setLogo(null)
}
}
actionBar.title = getString(R.string.gist_title) + gistId
}
override fun loaded(gist: Gist) {
if (gists!![vp_pages.currentItem] == gist.id()) {
updateActionBar(gist, gist.id()!!)
}
}
companion object {
private val REQUEST_CONFIRM_DELETE = 1
private val TAG = "GistsViewActivity"
/**
* Create an intent to show a single gist
*
* @param gist
* @return intent
*/
fun createIntent(gist: Gist): Intent {
return Builder("gists.VIEW").gist(gist).add(EXTRA_POSITION, 0)
.toIntent()
}
/**
* Create an intent to show gists with an initial selected Gist
*
* @param items
* @param position
* @return intent
*/
fun createIntent(items: List<Item<*>>, position: Int): Intent {
val ids = items.map { (it as GistItem).gist.id() }.toTypedArray()
return Builder("gists.VIEW")
.add(EXTRA_GIST_IDS, ids as Serializable)
.add(EXTRA_POSITION, position).toIntent()
}
}
}
| apache-2.0 | ab3b5f8e680e806b76c0a18309670917 | 35.419355 | 87 | 0.63672 | 4.600116 | false | false | false | false |
world-federation-of-advertisers/cross-media-measurement | src/main/kotlin/org/wfanet/measurement/kingdom/service/api/v2alpha/AccountAuthenticationServerInterceptor.kt | 1 | 4751 | // Copyright 2021 The Cross-Media Measurement 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.wfanet.measurement.kingdom.service.api.v2alpha
import io.grpc.BindableService
import io.grpc.Context
import io.grpc.Contexts
import io.grpc.Metadata
import io.grpc.ServerCall
import io.grpc.ServerCallHandler
import io.grpc.ServerInterceptor
import io.grpc.ServerInterceptors
import io.grpc.ServerServiceDefinition
import io.grpc.Status
import io.grpc.StatusException
import java.security.GeneralSecurityException
import kotlin.coroutines.CoroutineContext
import kotlin.coroutines.EmptyCoroutineContext
import org.wfanet.measurement.api.AccountConstants
import org.wfanet.measurement.api.v2alpha.AccountKey
import org.wfanet.measurement.api.v2alpha.AccountPrincipal
import org.wfanet.measurement.api.v2alpha.withPrincipal
import org.wfanet.measurement.common.grpc.SuspendableServerInterceptor
import org.wfanet.measurement.common.identity.externalIdToApiId
import org.wfanet.measurement.internal.kingdom.Account
import org.wfanet.measurement.internal.kingdom.AccountsGrpcKt.AccountsCoroutineStub
import org.wfanet.measurement.internal.kingdom.authenticateAccountRequest
/** gRPC [ServerInterceptor] to check [Account] credentials coming in from a request. */
class AccountAuthenticationServerInterceptor(
private val internalAccountsClient: AccountsCoroutineStub,
private val redirectUri: String,
coroutineContext: CoroutineContext = EmptyCoroutineContext
) : SuspendableServerInterceptor(coroutineContext) {
override suspend fun <ReqT : Any, RespT : Any> interceptCallSuspending(
call: ServerCall<ReqT, RespT>,
headers: Metadata,
next: ServerCallHandler<ReqT, RespT>
): ServerCall.Listener<ReqT> {
var context = Context.current()
val idToken =
headers.get(AccountConstants.ID_TOKEN_METADATA_KEY)
?: return Contexts.interceptCall(context, call, headers, next)
context = context.withValue(AccountConstants.CONTEXT_ID_TOKEN_KEY, idToken)
try {
val account = authenticateAccountCredentials(idToken)
context =
context
.withPrincipal(AccountPrincipal(AccountKey(externalIdToApiId(account.externalAccountId))))
.withValue(AccountConstants.CONTEXT_ACCOUNT_KEY, account)
} catch (e: GeneralSecurityException) {
call.close(Status.UNAUTHENTICATED.withCause(e), headers)
} catch (e: StatusException) {
val status =
when (e.status.code) {
Status.Code.NOT_FOUND -> {
// The request might not require authentication, so this is fine.
Status.OK
}
Status.Code.CANCELLED -> Status.CANCELLED
Status.Code.DEADLINE_EXCEEDED -> Status.DEADLINE_EXCEEDED
else -> Status.UNKNOWN
}
if (!status.isOk) {
call.close(status, headers)
}
}
return Contexts.interceptCall(context, call, headers, next)
}
private suspend fun authenticateAccountCredentials(idToken: String): Account {
val openIdConnectIdentity =
AccountsService.validateIdToken(
idToken = idToken,
redirectUri = redirectUri,
internalAccountsStub = internalAccountsClient
)
return internalAccountsClient.authenticateAccount(
authenticateAccountRequest { identity = openIdConnectIdentity }
)
}
}
fun BindableService.withAccountAuthenticationServerInterceptor(
internalAccountsClient: AccountsCoroutineStub,
redirectUri: String
): ServerServiceDefinition =
ServerInterceptors.intercept(
this,
AccountAuthenticationServerInterceptor(internalAccountsClient, redirectUri)
)
fun ServerServiceDefinition.withAccountAuthenticationServerInterceptor(
internalAccountsClient: AccountsCoroutineStub,
redirectUri: String
): ServerServiceDefinition =
ServerInterceptors.intercept(
this,
AccountAuthenticationServerInterceptor(internalAccountsClient, redirectUri)
)
/** Executes [block] with [Account] installed in a new [Context]. */
fun <T> withAccount(account: Account, block: () -> T): T {
return Context.current().withAccount(account).call(block)
}
fun Context.withAccount(account: Account): Context {
return withValue(AccountConstants.CONTEXT_ACCOUNT_KEY, account)
}
| apache-2.0 | 0c878b5f1ea08c22546499f898bcfaf1 | 37.008 | 100 | 0.765102 | 4.833164 | false | false | false | false |
Ruben-Sten/TeXiFy-IDEA | src/nl/hannahsten/texifyidea/completion/pathcompletion/LatexGraphicsPathProvider.kt | 1 | 4961 | package nl.hannahsten.texifyidea.completion.pathcompletion
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.psi.PsiFile
import nl.hannahsten.texifyidea.index.LatexIncludesIndex
import nl.hannahsten.texifyidea.lang.commands.LatexGenericRegularCommand
import nl.hannahsten.texifyidea.psi.LatexCommands
import nl.hannahsten.texifyidea.psi.LatexNormalText
import nl.hannahsten.texifyidea.util.childrenOfType
import nl.hannahsten.texifyidea.util.files.*
import nl.hannahsten.texifyidea.util.magic.cmd
import java.io.File
/**
* Autocompletion roots based on graphicspaths.
*/
class LatexGraphicsPathProvider : LatexPathProviderBase() {
override fun selectScanRoots(file: PsiFile): ArrayList<VirtualFile> {
val paths = getProjectRoots()
val rootDirectory = file.findRootFile().containingDirectory.virtualFile
getGraphicsPathsInFileSet(file).forEach {
paths.add(rootDirectory.findVirtualFileByAbsoluteOrRelativePath(it) ?: return@forEach)
}
return paths
}
/**
* When using \includegraphics from graphicx package, a path prefix can be set with \graphicspath.
* @return Graphicspaths defined in the fileset.
*/
fun getGraphicsPathsInFileSet(file: PsiFile): List<String> {
val graphicsPaths = mutableListOf<String>()
val graphicsPathCommands = file.commandsInFileSet().filter { it.name == LatexGenericRegularCommand.GRAPHICSPATH.cmd }
// Is a graphicspath defined?
if (graphicsPathCommands.isNotEmpty()) {
// Only last defined one counts
graphicsPathCommands.last().getGraphicsPaths().forEach { graphicsPaths.add(it) }
}
return graphicsPaths
}
/**
* This function is used in [InputFileReference#resolve], which is also used to create the file set, so we should
* not use the file set here (to avoid an infinite loop). Instead, we start searching the file of the given command
* for graphics paths. Then look at all commands that include the file of the given command and check the files of
* those commands for graphics paths.
*/
fun getGraphicsPathsWithoutFileSet(command: LatexCommands): List<String> {
fun graphicsPathsInFile(file: PsiFile): List<String> = file.commandsInFile()
.filter { it.name == "\\graphicspath" }
.flatMap { it.getGraphicsPaths() }
// First find all graphicspaths commands in the file of the given command
val graphicsPaths = graphicsPathsInFile(command.containingFile).toMutableList()
val allIncludeCommands = LatexIncludesIndex.getItems(command.project)
// Commands which may include the current file (this is an overestimation, better would be to check for RequiredFileArguments)
var includingCommands = allIncludeCommands.filter { includeCommand -> includeCommand.requiredParameters.any { it.contains(command.containingFile.name.removeFileExtension()) } }
// Avoid endless loop (in case of a file inclusion loop)
val maxDepth = allIncludeCommands.size
var counter = 0
// I think it's a kind of reversed BFS
while (includingCommands.isNotEmpty() && counter < maxDepth) {
val handledFiles = mutableListOf<PsiFile>()
val newIncludingCommands = mutableListOf<LatexCommands>()
for (includingCommand in includingCommands) {
// Search the file of the command that includes the current file for graphics paths.
graphicsPaths.addAll(graphicsPathsInFile(includingCommand.containingFile))
// Find files/commands to search next
val file = includingCommand.containingFile
if (file !in handledFiles) {
val commandsIncludingThisFile = allIncludeCommands.filter { includeCommand -> includeCommand.requiredParameters.any { it.contains(file.name) } }
newIncludingCommands.addAll(commandsIncludingThisFile)
handledFiles.add(file)
}
}
includingCommands = newIncludingCommands
counter++
}
return graphicsPaths
}
/**
* Get all the graphics paths defined by one \graphicspaths command.
*/
private fun LatexCommands.getGraphicsPaths(): List<String> {
if (name != "\\graphicspath") return emptyList()
return parameterList.mapNotNull { it.requiredParam }.first()
// Each graphics path is in a group.
.childrenOfType(LatexNormalText::class)
.map { it.text }
// Relative paths (not starting with /) have to be appended to the directory of the file of the given command.
.map { if (it.startsWith('/')) it else containingFile.containingDirectory.virtualFile.path + File.separator + it }
}
override fun searchFolders(): Boolean = true
override fun searchFiles(): Boolean = true
} | mit | 52f813764c11459f47fc4f1e9c0303a0 | 44.109091 | 184 | 0.691594 | 5.041667 | false | false | false | false |
mgolokhov/dodroid | app/src/main/java/doit/study/droid/data/local/entity/QuestionTagJoin.kt | 1 | 779 | package doit.study.droid.data.local.entity
import androidx.room.Entity
import androidx.room.ForeignKey
import androidx.room.Index
import androidx.room.PrimaryKey
@Entity(
foreignKeys = [
ForeignKey(
entity = Question::class,
parentColumns = ["id"],
childColumns = ["questionId"]
),
ForeignKey(
entity = Tag::class,
parentColumns = ["id"],
childColumns = ["tagId"]
)
],
indices = [
Index("questionId"),
Index("tagId")
]
)
data class QuestionTagJoin(
@PrimaryKey(autoGenerate = true)
val id: Int = 0,
val questionId: Int,
val tagId: Int
)
| mit | c04d66a8d5dc47a5d6acebad6ebfef61 | 24.129032 | 49 | 0.508344 | 5.025806 | false | false | false | false |
FHannes/intellij-community | platform/build-scripts/icons/src/org/jetbrains/intellij/build/images/ImageCollector.kt | 11 | 7484 | /*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.intellij.build.images
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.util.io.FileUtilRt
import com.intellij.openapi.util.text.StringUtil
import org.jetbrains.jps.model.java.JavaModuleSourceRootTypes
import org.jetbrains.jps.model.module.JpsModule
import org.jetbrains.jps.model.module.JpsModuleSourceRoot
import java.io.File
import java.util.*
import java.util.regex.Matcher
import java.util.regex.Pattern
internal class ImagePaths(val id: String, val sourceRoot: JpsModuleSourceRoot, val used: Boolean, val deprecated: Boolean) {
var files: MutableMap<ImageType, File> = HashMap()
var ambiguous: Boolean = false
val file: File? get() = files[ImageType.BASIC]
val presentablePath: File get() = file ?: files.values.first() ?: File("<unknown>")
}
internal class ImageCollector(val projectHome: File, val iconsOnly: Boolean = true, val ignoreSkipTag: Boolean = false) {
private val result = HashMap <String, ImagePaths>()
private val usedIconsRobots: MutableSet<File> = HashSet()
fun collect(module: JpsModule): List<ImagePaths> {
module.sourceRoots.forEach {
processRoot(it)
}
return result.values.toList()
}
fun printUsedIconRobots() {
usedIconsRobots.forEach {
println("Found icon-robots: $it")
}
}
private fun processRoot(sourceRoot: JpsModuleSourceRoot) {
val root = sourceRoot.file
if (!root.exists()) return
if (!JavaModuleSourceRootTypes.PRODUCTION.contains(sourceRoot.rootType)) return
val iconsRoot = downToRoot(root)
if (iconsRoot == null) return
val rootRobotData = upToProjectHome(root)
if (rootRobotData.isSkipped(root)) return
val robotData = rootRobotData.fork(iconsRoot, root)
processDirectory(iconsRoot, sourceRoot, robotData, emptyList<String>())
}
private fun processDirectory(dir: File, sourceRoot: JpsModuleSourceRoot, robotData: IconRobotsData, prefix: List<String>) {
dir.children.forEach { file ->
if (robotData.isSkipped(file)) return@forEach
if (file.isDirectory) {
val root = sourceRoot.file
val childRobotData = robotData.fork(file, root)
val childPrefix = prefix + file.name
processDirectory(file, sourceRoot, childRobotData, childPrefix)
}
else if (isImage(file, iconsOnly)) {
processImageFile(file, sourceRoot, robotData, prefix)
}
}
}
private fun processImageFile(file: File, sourceRoot: JpsModuleSourceRoot, robotData: IconRobotsData, prefix: List<String>) {
val nameWithoutExtension = FileUtil.getNameWithoutExtension(file.name)
val type = ImageType.fromName(nameWithoutExtension)
val id = type.getBasicName((prefix + nameWithoutExtension).joinToString("/"))
val skipped = robotData.isSkipped(file)
val used = robotData.isUsed(file)
val deprecated = robotData.isDeprecated(file)
if (skipped) return
val iconPaths = result.computeIfAbsent(id, { ImagePaths(id, sourceRoot, used, deprecated) })
if (type !in iconPaths.files) {
iconPaths.files[type] = file
}
else {
iconPaths.ambiguous = true
}
}
private fun upToProjectHome(dir: File): IconRobotsData {
if (FileUtil.filesEqual(dir, projectHome)) return IconRobotsData()
val parent = dir.parentFile ?: return IconRobotsData()
return upToProjectHome(parent).fork(parent, projectHome)
}
private fun downToRoot(dir: File): File? {
val answer = downToRoot(dir, dir, null, IconRobotsData())
return if (answer == null || answer.isDirectory) answer else answer.parentFile
}
private fun downToRoot(root: File, file: File, common: File?, robotData: IconRobotsData): File? {
if (robotData.isSkipped(file)) return common
if (file.isDirectory) {
val childRobotData = robotData.fork(file, root)
var childCommon = common
file.children.forEach {
childCommon = downToRoot(root, it, childCommon, childRobotData)
}
return childCommon
}
else if (isImage(file, iconsOnly)) {
if (common == null) return file
return FileUtil.findAncestor(common, file)
}
else {
return common
}
}
private inner class IconRobotsData(private val parent: IconRobotsData? = null) {
private val skip: MutableSet<Matcher> = HashSet()
private val used: MutableSet<Matcher> = HashSet()
private val deprecated: MutableSet<Matcher> = HashSet()
fun isSkipped(file: File): Boolean = !ignoreSkipTag && (matches(file, skip) || parent?.isSkipped(file) ?: false)
fun isUsed(file: File): Boolean = matches(file, used) || parent?.isUsed(file) ?: false
fun isDeprecated(file: File): Boolean = matches(file, deprecated) || parent?.isDeprecated(file) ?: false
fun fork(dir: File, root: File): IconRobotsData {
val robots = File(dir, "icon-robots.txt")
if (!robots.exists()) return this
usedIconsRobots.add(robots)
val answer = IconRobotsData(this)
parse(robots,
Pair("skip:", { value -> compilePattern(answer.skip, dir, root, value) }),
Pair("used:", { value -> compilePattern(answer.used, dir, root, value) }),
Pair("deprecated:", { value -> compilePattern(answer.deprecated, dir, root, value) }),
Pair("name:", { value -> }), // ignore
Pair("#", { value -> }) // comment
)
return answer
}
private fun parse(robots: File, vararg handlers: Pair<String, (String) -> Unit>) {
robots.forEachLine { line ->
if (line.isBlank()) return@forEachLine
for (h in handlers) {
if (line.startsWith(h.first)) {
h.second(StringUtil.trimStart(line, h.first))
return@forEachLine
}
}
throw Exception("Can't parse $robots. Line: $line")
}
}
private fun compilePattern(set: MutableSet<Matcher>, dir: File, root: File, value: String) {
var pattern = value.trim()
if (pattern.startsWith("/")) {
pattern = root.absolutePath + pattern
}
else {
pattern = dir.absolutePath + '/' + pattern
}
val regExp = FileUtil.convertAntToRegexp(pattern, false)
try {
set.add(Pattern.compile(regExp).matcher(""))
}
catch (e: Exception) {
throw Exception("Cannot compile pattern: $pattern. Built on based in $dir/icon-robots.txt")
}
}
private fun matches(file: File, matcher: Set<Matcher>): Boolean {
val path = file.absolutePath.replace('\\', '/')
val pathWithoutExtension = FileUtilRt.getNameWithoutExtension(path)
val extension = FileUtilRt.getExtension(path)
val basicPathWithoutExtension = ImageType.stripSuffix(pathWithoutExtension)
val basicPath = basicPathWithoutExtension + if (extension.isNotEmpty()) "." + extension else ""
return matcher.any { it.reset(basicPath).matches() }
}
}
} | apache-2.0 | d94825544fe628a5da92915eb829375a | 35.15942 | 126 | 0.681855 | 4.402353 | false | false | false | false |
valerio-bozzolan/bus-torino | src/it/reyboz/bustorino/data/gtfs/MatoPattern.kt | 1 | 4221 | /*
BusTO - Data components
Copyright (C) 2022 Fabio Mazza
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 it.reyboz.bustorino.data.gtfs
import androidx.room.*
import it.reyboz.bustorino.backend.Stop
@Entity(tableName = MatoPattern.TABLE_NAME,
foreignKeys = [
ForeignKey(entity = GtfsRoute::class,
parentColumns = [GtfsRoute.COL_ROUTE_ID],
childColumns = [MatoPattern.COL_ROUTE_ID],
onDelete = ForeignKey.CASCADE,
)
]
)
data class MatoPattern(
@ColumnInfo(name= COL_NAME)
val name: String,
@ColumnInfo(name= COL_CODE)
@PrimaryKey
val code: String,
@ColumnInfo(name= COL_SEMANTIC_HASH)
val semanticHash: String,
@ColumnInfo(name= COL_DIRECTION_ID)
val directionId: Int,
@ColumnInfo(name= COL_ROUTE_ID)
val routeGtfsId: String,
@ColumnInfo(name= COL_HEADSIGN)
var headsign: String?,
@ColumnInfo(name= COL_GEOMETRY_POLY)
val patternGeometryPoly: String,
@ColumnInfo(name= COL_GEOMETRY_LENGTH)
val patternGeometryLength: Int,
@Ignore
val stopsGtfsIDs: ArrayList<String>
):GtfsTable{
@Ignore
val servingStops= ArrayList<Stop>(4)
constructor(
name: String, code:String,
semanticHash: String, directionId: Int,
routeGtfsId: String, headsign: String?,
patternGeometryPoly: String, patternGeometryLength: Int
): this(name, code, semanticHash, directionId, routeGtfsId, headsign, patternGeometryPoly, patternGeometryLength, ArrayList<String>(4))
companion object{
const val TABLE_NAME="mato_patterns"
const val COL_NAME="pattern_name"
const val COL_CODE="pattern_code"
const val COL_ROUTE_ID="pattern_route_id"
const val COL_SEMANTIC_HASH="pattern_hash"
const val COL_DIRECTION_ID="pattern_direction_id"
const val COL_HEADSIGN="pattern_headsign"
const val COL_GEOMETRY_POLY="pattern_polyline"
const val COL_GEOMETRY_LENGTH="pattern_polylength"
val COLUMNS = arrayOf(
COL_NAME,
COL_CODE,
COL_ROUTE_ID,
COL_SEMANTIC_HASH,
COL_DIRECTION_ID,
COL_HEADSIGN,
COL_GEOMETRY_POLY,
COL_GEOMETRY_LENGTH
)
}
override fun getColumns(): Array<String> {
return COLUMNS
}
}
//DO NOT USE EMBEDDED!!! -> copies all data
@Entity(tableName=PatternStop.TABLE_NAME,
primaryKeys = [
PatternStop.COL_PATTERN_ID,
PatternStop.COL_STOP_GTFS,
PatternStop.COL_ORDER
],
foreignKeys = [
ForeignKey(entity = MatoPattern::class,
parentColumns = [MatoPattern.COL_CODE],
childColumns = [PatternStop.COL_PATTERN_ID],
onDelete = ForeignKey.CASCADE
)
]
)
data class PatternStop(
@ColumnInfo(name= COL_PATTERN_ID)
val patternId: String,
@ColumnInfo(name=COL_STOP_GTFS)
val stopGtfsId: String,
@ColumnInfo(name=COL_ORDER)
val order: Int,
){
companion object{
const val TABLE_NAME="patterns_stops"
const val COL_PATTERN_ID="pattern_gtfs_id"
const val COL_STOP_GTFS="stop_gtfs_id"
const val COL_ORDER="stop_order"
}
}
data class MatoPatternWithStops(
@Embedded val pattern: MatoPattern,
@Relation(
parentColumn = MatoPattern.COL_CODE,
entityColumn = PatternStop.COL_PATTERN_ID,
)
var stopsIndices: List<PatternStop>)
{
init {
stopsIndices = stopsIndices.sortedBy { p-> p.order }
}
} | gpl-3.0 | 252218df67803775badc5dd2c414d6a9 | 29.157143 | 139 | 0.646766 | 4.1261 | false | false | false | false |
NextFaze/dev-fun | devfun-compiler/src/main/java/com/nextfaze/devfun/compiler/AptUtil.kt | 1 | 8933 | package com.nextfaze.devfun.compiler
import com.squareup.kotlinpoet.CodeBlock
import com.squareup.kotlinpoet.ParameterizedTypeName.Companion.parameterizedBy
import com.squareup.kotlinpoet.TypeName
import com.squareup.kotlinpoet.WildcardTypeName.Companion.STAR
import com.squareup.kotlinpoet.WildcardTypeName.Companion.subtypeOf
import com.squareup.kotlinpoet.WildcardTypeName.Companion.supertypeOf
import com.squareup.kotlinpoet.asTypeName
import javax.lang.model.element.AnnotationMirror
import javax.lang.model.element.AnnotationValue
import javax.lang.model.element.Element
import javax.lang.model.element.Modifier
import javax.lang.model.element.Name
import javax.lang.model.element.TypeElement
import javax.lang.model.type.ArrayType
import javax.lang.model.type.DeclaredType
import javax.lang.model.type.ExecutableType
import javax.lang.model.type.NoType
import javax.lang.model.type.NullType
import javax.lang.model.type.PrimitiveType
import javax.lang.model.type.TypeMirror
import javax.lang.model.type.TypeVariable
import javax.lang.model.type.WildcardType
import javax.lang.model.util.Elements
import kotlin.reflect.KCallable
import kotlin.reflect.KClass
internal inline val Element.isPublic get() = modifiers.contains(Modifier.PUBLIC)
internal inline val Element.isStatic get() = modifiers.contains(Modifier.STATIC)
internal inline val Element.isProperty get() = isStatic && simpleName.endsWith("\$annotations")
internal inline val TypeMirror.isPrimitive get() = kind.isPrimitive
internal val TypeMirror.isClassPublic: Boolean
get() {
return when (this) {
is PrimitiveType -> true
is DeclaredType -> (asElement() as TypeElement).isClassPublic && typeArguments.all { it.isClassPublic } && asElement().enclosingElement.asType().isClassPublic
is ExecutableType -> returnType.isClassPublic && parameterTypes.all { it.isClassPublic } && typeVariables.all { it.isClassPublic }
is ArrayType -> componentType.isClassPublic
is WildcardType -> extendsBound?.isClassPublic != false && superBound?.isClassPublic != false
is TypeVariable -> upperBound?.isClassPublic != false && lowerBound?.isClassPublic != false
is NoType -> true
is NullType -> true
else -> throw RuntimeException("isClassPublic not implemented for $this (${this::class})")
}
}
internal inline val TypeElement.isClassPublic: Boolean
get() {
var element = this
while (true) {
if (!element.isPublic) return false
element = element.enclosingElement as? TypeElement ?: return true // hit package
}
}
internal inline operator fun <reified T : Any> AnnotationMirror.get(callable: KCallable<T>) =
elementValues.filter { it.key.simpleName.toString() == callable.name }.values.singleOrNull()?.value as T?
internal inline operator fun <reified T : Any> AnnotationMirror.get(name: String): T? {
val v = elementValues.filter { it.key.simpleName.toString() == name }.values.singleOrNull()?.value
return if (v is List<*>) {
when {
T::class == IntArray::class -> v.map { (it as AnnotationValue).value as Int }.toTypedArray().toIntArray() as T
T::class == Array<String>::class -> v.map { (it as AnnotationValue).value as String }.toTypedArray() as T
else -> throw NotImplementedError("$this.get($name) for ${T::class} not implemented.")
}
} else {
v as T?
}
}
internal inline operator fun <reified T : Annotation> AnnotationMirror.get(callable: KCallable<T>) =
elementValues.filter { it.key.simpleName.toString() == callable.name }.values.singleOrNull()?.value as AnnotationMirror?
internal operator fun <K : KClass<*>> AnnotationMirror.get(
callable: KCallable<K>,
orDefault: (() -> DeclaredType?)? = null
): DeclaredType? {
val entry = elementValues.filter { it.key.simpleName.toString() == callable.name }.entries.singleOrNull() ?: return orDefault?.invoke()
return (entry.value.value ?: orDefault?.invoke()) as DeclaredType?
}
internal fun Name.stripInternal() = toString().substringBefore("\$")
internal fun CharSequence.escapeDollar() = toString().replace("\$", "\\\$")
internal val TypeMirror.isPublic: Boolean
get() = when (this) {
is PrimitiveType -> true
is ArrayType -> this.componentType.isPublic
is TypeVariable -> this.upperBound.isPublic
is DeclaredType -> this.asElement().isPublic && this.typeArguments.all { it.isPublic } && this.asElement().enclosingElement.asType().isPublic
is WildcardType -> this.extendsBound?.isPublic ?: true && this.superBound?.isPublic ?: true
is ExecutableType -> returnType.isPublic && parameterTypes.all { it.isPublic } && typeVariables.all { it.isPublic }
is NoType -> true
else -> throw NotImplementedError("TypeMirror.isPublic not implemented for this=$this (${this::class})")
}
internal fun Element.getAnnotation(typeElement: TypeElement): AnnotationMirror? =
annotationMirrors.singleOrNull { it.annotationType.toString() == typeElement.qualifiedName.toString() }
internal fun TypeMirror.toKClassBlock(
kotlinClass: Boolean = true,
isKtFile: Boolean = false,
castIfNotPublic: TypeName? = null,
elements: Elements
): CodeBlock {
if (!isKtFile && isClassPublic) {
val suffix = when {
kotlinClass -> ""
isPrimitiveObject -> ".javaObjectType"
else -> ".java"
}
fun TypeMirror.toType(): TypeName =
when (this) {
is PrimitiveType -> asTypeName()
is DeclaredType -> className
is ArrayType -> when {
componentType.isPrimitive -> (componentType as PrimitiveType).arrayTypeName
else -> TypeNames.array.parameterizedBy(componentType.toType())
}
else -> throw NotImplementedError("TypeMirror.toTypeName not implemented for this=$this (${this::class})")
}
return CodeBlock.of("%T::class$suffix", toType())
}
return when (this) {
is DeclaredType -> {
val suffix = if (kotlinClass) ".kotlin" else ""
val type = asElement() as TypeElement
val binaryName = elements.getBinaryName(type).escapeDollar()
if (castIfNotPublic != null) {
CodeBlock.of("Class.forName(\"$binaryName\")$suffix as %T", castIfNotPublic)
} else {
CodeBlock.of("Class.forName(\"$binaryName\")$suffix")
}
}
is ArrayType -> CodeBlock.of(
"java.lang.reflect.Array.newInstance(%L, 0)::class",
componentType.toKClassBlock(kotlinClass = false, elements = elements)
)
else -> throw NotImplementedError("TypeMirror.toCodeBlock not implemented for this=$this (${this::class})")
}
}
private val TypeMirror.isPrimitiveObject
get() = this is DeclaredType &&
when (toString()) {
"java.lang.Boolean",
"java.lang.Character",
"java.lang.Byte",
"java.lang.Short",
"java.lang.Integer",
"java.lang.Float",
"java.lang.Long",
"java.lang.Double",
"java.lang.Void" -> true
else -> false
}
internal fun TypeMirror.toTypeName(subtypeArrayVariance: Boolean = false): TypeName = when (this) {
is PrimitiveType -> asTypeName()
is ArrayType -> when {
componentType.isPrimitive -> (componentType as PrimitiveType).arrayTypeName
// We need this when getting the typeName for use as a property return type as we can't actually know the
// variance because we see it as Java "ArrayType[]", not Kotlin "Array<VARIANCE Type>".
// Thus by using "out" in the property's return type, it will always be accepted (though could technically be wrong under certain circumstances)
subtypeArrayVariance -> TypeNames.array.parameterizedBy(subtypeOf(componentType.toTypeName(subtypeArrayVariance)))
else -> TypeNames.array.parameterizedBy(componentType.toTypeName(subtypeArrayVariance))
}
is DeclaredType -> when {
typeArguments.isEmpty() -> className
else -> className.parameterizedBy(*typeArguments.map { it.toTypeName(subtypeArrayVariance) }.toTypedArray())
}
is WildcardType -> extendsBound?.toTypeName(subtypeArrayVariance)?.let { subtypeOf(it) }
?: superBound?.toTypeName(subtypeArrayVariance)?.let { supertypeOf(it) }
?: STAR
is TypeVariable -> upperBound?.toTypeName(subtypeArrayVariance) ?: lowerBound?.toTypeName(subtypeArrayVariance) ?: STAR
else -> throw NotImplementedError("TypeMirror.toTypeName not implemented for this=$this (${this::class})")
}
internal fun TypeName.toCodeBlock() = CodeBlock.of("%T", this)
| apache-2.0 | 4a663214a54937d46ba2c46fd8ec16e0 | 47.286486 | 170 | 0.676704 | 4.860174 | false | false | false | false |
andrei-heidelbacher/metanalysis | analyzers/chronolens-coupling/src/main/kotlin/org/chronolens/coupling/DivergentChangeCommand.kt | 1 | 4985 | /*
* Copyright 2018-2021 Andrei Heidelbacher <[email protected]>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.chronolens.coupling
import org.chronolens.core.cli.Subcommand
import org.chronolens.core.cli.restrictTo
import org.chronolens.core.model.sourcePath
import org.chronolens.core.repository.Transaction
import org.chronolens.core.serialization.JsonModule
import org.chronolens.coupling.Graph.Subgraph
import java.io.File
internal class DivergentChangeCommand : Subcommand() {
override val help: String get() = """
Loads the persisted repository, builds the temporal coupling graphs for
the analyzed source files, detects the Divergent Change instances,
reports the results to the standard output and dumps the coupling graphs
for each source file in the '.chronolens/divergent-change' directory.
"""
private val maxChangeSet by option<Int>()
.help("the maximum number of changed files in a revision")
.defaultValue(100).restrictTo(min = 1)
private val minRevisions by option<Int>().help(
"the minimum number of revisions of a method or coupling relation"
).defaultValue(5).restrictTo(min = 1)
private val minCoupling by option<Double>()
.help("the minimum temporal coupling between two methods")
.defaultValue(0.1).restrictTo(min = 0.0)
private val minBlobDensity by option<Double>().help(
"the minimum average degree (sum of coupling) of methods in a blob"
).defaultValue(2.5).restrictTo(min = 0.0)
private val maxAntiCoupling by option<Double>().help(
"the maximum degree (sum of coupling) of a method in an anti-blob"
).defaultValue(0.5).restrictTo(min = 0.0)
private val minAntiBlobSize by option<Int>()
.help("the minimum size of an anti-blob")
.defaultValue(10).restrictTo(min = 1)
private val minMetricValue by option<Int>().help(
"""ignore source files that have less blobs / anti-blobs than the
specified limit"""
).defaultValue(0).restrictTo(min = 0)
private fun TemporalContext.aggregateGraphs(): List<Graph> {
val idsByFile = ids.groupBy(String::sourcePath)
return idsByFile.keys.map { path ->
val ids = idsByFile[path].orEmpty().toSet()
buildGraphFrom(path, ids)
}
}
private fun analyze(history: Sequence<Transaction>): Report {
val analyzer = HistoryAnalyzer(maxChangeSet, minRevisions, minCoupling)
val temporalContext = analyzer.analyze(history)
val graphs = temporalContext.aggregateGraphs()
val coloredGraphs = mutableListOf<ColoredGraph>()
val files = mutableListOf<FileReport>()
for (graph in graphs) {
val blobs = graph.findBlobs(minBlobDensity)
val antiBlob = graph.findAntiBlob(maxAntiCoupling, minAntiBlobSize)
coloredGraphs += graph.colorNodes(blobs, antiBlob)
files += FileReport(graph.label, blobs, antiBlob)
}
files.sortByDescending(FileReport::value)
return Report(files, coloredGraphs)
}
override fun run() {
val repository = load()
val report = analyze(repository.getHistory())
val files = report.files.filter { it.value >= minMetricValue }
JsonModule.serialize(System.out, files)
val directory = File(".chronolens", "divergent-change")
for (coloredGraph in report.coloredGraphs) {
val graphDirectory = File(directory, coloredGraph.graph.label)
graphDirectory.mkdirs()
val graphFile = File(graphDirectory, "graph.json")
graphFile.outputStream().use { out ->
JsonModule.serialize(out, coloredGraph)
}
}
}
data class Report(
val files: List<FileReport>,
val coloredGraphs: List<ColoredGraph>,
)
data class FileReport(
val file: String,
val blobs: List<Subgraph>,
val antiBlob: Subgraph?,
) {
val responsibilities: Int = blobs.size + if (antiBlob != null) 1 else 0
val category: String = "SOLID Breakers"
val name: String = "Single Responsibility Breakers"
val value: Int = responsibilities
}
}
private fun Graph.colorNodes(
blobs: List<Subgraph>,
antiBlob: Subgraph?,
): ColoredGraph {
val groups = blobs.map(Subgraph::nodes) + listOfNotNull(antiBlob?.nodes)
return colorNodes(groups)
}
| apache-2.0 | f55a11832a076b040e64a08a24622054 | 37.643411 | 80 | 0.678435 | 4.36133 | false | false | false | false |
Commit451/GeoTune | app/src/main/java/com/jawnnypoo/geotune/viewHolder/GeoTuneViewHolder.kt | 1 | 1703 | package com.jawnnypoo.geotune.viewHolder
import android.support.v7.widget.RecyclerView
import android.support.v7.widget.SwitchCompat
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.PopupMenu
import android.widget.TextView
import com.commit451.addendum.recyclerview.bindView
import com.jawnnypoo.geotune.R
import com.jawnnypoo.geotune.data.GeoTune
class GeoTuneViewHolder(view: View) : RecyclerView.ViewHolder(view) {
companion object {
fun inflate(parent: ViewGroup): GeoTuneViewHolder {
val view = LayoutInflater.from(parent.context)
.inflate(R.layout.item_geofence, parent, false)
return GeoTuneViewHolder(view)
}
}
val card: View by bindView(R.id.card_view)
val name: TextView by bindView(R.id.geotune_name)
val tune: TextView by bindView(R.id.geotune_tune)
val datSwitch: SwitchCompat by bindView(R.id.geotune_switch)
val overflow: ImageView by bindView(R.id.geotune_overflow)
val popupMenu=PopupMenu(view.context, overflow)
init {
popupMenu.menuInflater.inflate(R.menu.geotune_menu, popupMenu.menu)
overflow.setOnClickListener { popupMenu.show() }
}
fun bind(geoTune: GeoTune) {
name.text = geoTune.name
if (geoTune.tuneUri == null) {
tune.text = itemView.context.getString(R.string.default_notification_tone)
} else {
if (geoTune.tuneName == null) {
tune.text = ""
} else {
tune.text = geoTune.tuneName
}
}
datSwitch.isChecked = geoTune.isActive
}
}
| apache-2.0 | 0fc6abb85cceb7caeb50faf348753df4 | 32.392157 | 86 | 0.682913 | 4.184275 | false | false | false | false |
andela-kogunde/CheckSmarter | app/src/main/kotlin/com/andela/checksmarter/utilities/Exchange.kt | 1 | 1966 | package com.andela.checksmarter.utilities
import com.andela.checksmarter.model.CheckSmarterDup
import com.andela.checksmarter.model.CheckSmarterJava
import com.andela.checksmarter.model.CheckSmarterTaskDup
import com.andela.checksmarter.model.CheckSmarterTaskJava
import io.realm.Realm
/**
* Created by CodeKenn on 21/04/16.
*/
class Exchange {
fun getParcelableCheckSmarter(checkSmarter: CheckSmarterJava): CheckSmarterDup {
var newCheckSmarter = CheckSmarterDup()
newCheckSmarter.id = checkSmarter.id
newCheckSmarter.title = checkSmarter.title
newCheckSmarter.isCheck = checkSmarter.isCheck
newCheckSmarter.isAlarm = checkSmarter.isAlarm
newCheckSmarter.alarmValue = checkSmarter.alarmValue
newCheckSmarter.timeValue = checkSmarter.timeValue
checkSmarter.tasks.forEach {
var newCheckSmarterTask = CheckSmarterTaskDup()
newCheckSmarterTask.id = it.id
newCheckSmarterTask.title = it.title
newCheckSmarterTask.isCheck = it.isCheck
newCheckSmarter.tasks.add(newCheckSmarterTask)
}
return newCheckSmarter
}
fun getRealmCheckSmarter(checkSmarter: CheckSmarterDup): CheckSmarterJava {
var newCheckSmarter = CheckSmarterJava()
newCheckSmarter.id = checkSmarter.id
newCheckSmarter.title = checkSmarter.title
newCheckSmarter.isCheck = checkSmarter.isCheck
newCheckSmarter.isAlarm = checkSmarter.isAlarm
newCheckSmarter.alarmValue = checkSmarter.alarmValue
newCheckSmarter.timeValue = checkSmarter.timeValue
checkSmarter.tasks.forEach {
var newCheckSmarterTask = CheckSmarterTaskJava()
newCheckSmarterTask.id = it.id
newCheckSmarterTask.title = it.title
newCheckSmarterTask.isCheck = it.isCheck
newCheckSmarter.tasks.add(newCheckSmarterTask)
}
return newCheckSmarter
}
} | mit | 815eafaf5c275b2704014562abfe0f7d | 36.826923 | 84 | 0.721261 | 5.665706 | false | false | false | false |
jereksel/LibreSubstratum | app/src/main/kotlin/com/jereksel/libresubstratum/views/ColorView.kt | 1 | 2439 | /*
* Copyright (C) 2017 Andrzej Ressel ([email protected])
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.jereksel.libresubstratum.views
import android.content.Context
import android.graphics.*
import android.util.AttributeSet
import android.view.DragEvent
import android.view.MotionEvent
import android.view.View
import android.widget.SeekBar
class ColorView: View {
constructor(context: Context?) : super(context)
constructor(context: Context?, attrs: AttributeSet?) : super(context, attrs)
constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr)
constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int, defStyleRes: Int) : super(context, attrs, defStyleAttr, defStyleRes)
val paint = Paint()
var colors = listOf<Int>()
//For edit mode
val rainbow = listOf(
Color.RED,
Color.parseColor("#FF7F00"),
Color.YELLOW,
Color.GREEN,
Color.BLUE,
Color.parseColor("#4B0082"),
Color.parseColor("#8F00FF")
)
override fun onDraw(canvas: Canvas) {
super.onDraw(canvas)
val colors = if (isInEditMode) {
rainbow
} else if(!colors.isEmpty()) {
colors
} else {
listOf(Color.TRANSPARENT)
}
val blockSize = width/colors.size.toFloat()
colors.forEachIndexed { index, color ->
val start = index*blockSize
val end = (index + 1)*blockSize
paint.color = color
canvas.drawRect(start, 0f, end, height.toFloat(), paint)
}
//
// SeekBar(context).draw(canvas)
}
override fun onTouchEvent(event: MotionEvent) = true
override fun onDragEvent(event: DragEvent?) = true
} | mit | 1efad5122db88c87a3258f4a2a2043f2 | 28.756098 | 144 | 0.661747 | 4.386691 | false | false | false | false |
pgutkowski/KGraphQL | src/main/kotlin/com/github/pgutkowski/kgraphql/schema/dsl/UnionPropertyDSL.kt | 1 | 2340 | package com.github.pgutkowski.kgraphql.schema.dsl
import com.github.pgutkowski.kgraphql.Context
import com.github.pgutkowski.kgraphql.schema.model.FunctionWrapper
import com.github.pgutkowski.kgraphql.schema.model.InputValueDef
import com.github.pgutkowski.kgraphql.schema.model.PropertyDef
import com.github.pgutkowski.kgraphql.schema.model.TypeDef
import java.lang.IllegalArgumentException
class UnionPropertyDSL<T : Any>(val name : String, block: UnionPropertyDSL<T>.() -> Unit) : LimitedAccessItemDSL<T>(), ResolverDSL.Target {
init {
block()
}
internal lateinit var functionWrapper : FunctionWrapper<Any?>
lateinit var returnType : TypeID
private val inputValues = mutableListOf<InputValueDef<*>>()
private fun resolver(function: FunctionWrapper<Any?>): ResolverDSL {
functionWrapper = function
return ResolverDSL(this)
}
fun resolver(function: (T) -> Any?) = resolver(FunctionWrapper.on(function, true))
fun <E>resolver(function: (T, E) -> Any?) = resolver(FunctionWrapper.on(function, true))
fun <E, W>resolver(function: (T, E, W) -> Any?) = resolver(FunctionWrapper.on(function, true))
fun <E, W, Q>resolver(function: (T, E, W, Q) -> Any?) = resolver(FunctionWrapper.on(function, true))
fun <E, W, Q, A>resolver(function: (T, E, W, Q, A) -> Any?) = resolver(FunctionWrapper.on(function, true))
fun <E, W, Q, A, S>resolver(function: (T, E, W, Q, A, S) -> Any?) = resolver(FunctionWrapper.on(function, true))
fun accessRule(rule: (T, Context) -> Exception?){
val accessRuleAdapter: (T?, Context) -> Exception? = { parent, ctx ->
if (parent != null) rule(parent, ctx) else IllegalArgumentException("Unexpected null parent of kotlin property")
}
this.accessRuleBlock = accessRuleAdapter
}
fun toKQLProperty(union : TypeDef.Union) = PropertyDef.Union<T> (
name = name,
resolver = functionWrapper,
union = union,
description = description,
isDeprecated = isDeprecated,
deprecationReason = deprecationReason,
inputValues = inputValues,
accessRule = accessRuleBlock
)
override fun addInputValues(inputValues: Collection<InputValueDef<*>>) {
this.inputValues.addAll(inputValues)
}
} | mit | dbaf54fc1dc3d2d038c5ed396c63478f | 36.15873 | 139 | 0.676496 | 4.223827 | false | false | false | false |
nemerosa/ontrack | ontrack-service/src/main/java/net/nemerosa/ontrack/service/RunInfoRestorationJob.kt | 1 | 1249 | package net.nemerosa.ontrack.service
import net.nemerosa.ontrack.job.*
import net.nemerosa.ontrack.model.metrics.MetricsReexportJobProvider
import net.nemerosa.ontrack.model.structure.RunInfoService
import net.nemerosa.ontrack.model.support.JobProvider
import net.nemerosa.ontrack.model.support.RestorationJobs
import org.springframework.stereotype.Component
/**
* Job used to re-export all run infos into registered listeners.
*/
@Component
class RunInfoRestorationJob(
private val runInfoService: RunInfoService
): JobProvider, Job, MetricsReexportJobProvider {
override fun getStartingJobs(): Collection<JobRegistration> =
listOf(
JobRegistration(
this,
Schedule.NONE // Manually only
)
)
override fun isDisabled(): Boolean = false
override fun getReexportJobKey(): JobKey = key
override fun getKey(): JobKey =
RestorationJobs.RESTORATION_JOB_TYPE.getKey("run-info-restoration")
override fun getDescription(): String = "Run Info Restoration"
override fun getTask() = JobRun { listener ->
runInfoService.restore {
listener.message(it)
}
}
} | mit | 13f205af6991268ae1a8387547be8e39 | 29.487805 | 79 | 0.678143 | 4.859922 | false | false | false | false |
rieonke/idea-auto-switch-im | src/main/java/cn/rieon/idea/plugin/AutoSwitchIm/util/InputSourceUtil.kt | 1 | 3221 | package cn.rieon.idea.plugin.AutoSwitchIm.util
import com.intellij.openapi.diagnostic.Logger
import java.awt.SystemColor.text
import java.io.*
import java.util.*
/**
* @author Rieon Ke <rieon></rieon>@rieon.cn>
* *
* @version 1.0.0
* *
* @since 2017/5/19
*/
object InputSourceUtil {
private var inputSources: ArrayList<Pair<String, String>>? = null
private val LOG = Logger.getInstance(InputSourceUtil::class.java)
private var EXEC_PATH: String? = null
private val EXCLUDE_IME = Arrays.asList(
"com.apple.inputmethod.EmojiFunctionRowItem",
"com.baidu.inputmethod.BaiduIM"
)
init {
try {
val execPath = NativeUtil.getLibPath("/native/ImSelect")
if (execPath == null) {
LOG.error("GET EXEC PATH FAILED")
} else {
EXEC_PATH = execPath
LOG.info("LOADED FORM NATIVE UTILS")
LOG.info("CURRENT EXEC PATH " + execPath)
}
} catch (e: IOException) {
e.printStackTrace()
}
}
private fun nativeGetCurrentInputSource(): String {
return execImSelect("c")
}
private fun nativeSwitchToInputSource(inputSourceName: String): Boolean {
execImSelect("s " + inputSourceName)
return true
}
private fun nativeGetAllInputSources(): String {
return execImSelect("l")
}
internal fun execImSelect(command: String): String {
var c: String? = EXEC_PATH;
if (command.isNotEmpty()) {
c = EXEC_PATH + " -" + command
}
LOG.info("EXEC COMMAND " + c)
var result: Process? = null
try {
result = Runtime.getRuntime().exec(c)
} catch (e: IOException) {
LOG.error("EXEC FAILED!")
e.printStackTrace()
}
if (result != null) {
val text = result.inputStream.bufferedReader().use(BufferedReader::readText)
LOG.info("GET EXEC RESULT " + text)
return text
}
return ""
}
val currentInputSource: String
get() {
LOG.info("GET CURRENT INPUT SOURCE")
return nativeGetCurrentInputSource()
}
fun switchTo(source: String): Boolean {
LOG.info("SWITCH TO INPUT SOURCE " + source)
return nativeSwitchToInputSource(source)
}
internal fun filterInputSource(source: String): Boolean {
return !EXCLUDE_IME.contains(source)
}
val allInputSources: ArrayList<Pair<String, String>>
get() {
LOG.info("GET ALL INPUT SOURCES")
val originalStr = nativeGetAllInputSources()
val pairStrArr = originalStr.split("\\|".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()
inputSources = ArrayList<Pair<String, String>>()
pairStrArr
.map { x -> x.split(":".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray() }
.filter { filterInputSource(it[0]) }
.forEach { inputSources!!.add(Pair(it[0], it[1])) }
return inputSources as ArrayList<Pair<String, String>>
}
}
| gpl-3.0 | 1ce0d81d0aa42760330feebbd10e7d08 | 22.172662 | 109 | 0.570941 | 4.424451 | false | false | false | false |
nickbutcher/plaid | designernews/src/main/java/io/plaidapp/designernews/data/users/UserRepository.kt | 1 | 1868 | /*
* Copyright 2018 Google LLC.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.plaidapp.designernews.data.users
import io.plaidapp.core.data.Result
import io.plaidapp.core.designernews.data.users.model.User
import java.io.IOException
/**
* Class that requests users from the remote data source and caches them, in memory.
*/
class UserRepository(private val dataSource: UserRemoteDataSource) {
private val cachedUsers = mutableMapOf<Long, User>()
suspend fun getUsers(ids: Set<Long>): Result<Set<User>> {
// find the ids in the cached users first and only request the ones that we don't have yet
val notCachedUsers = ids.filterNot { cachedUsers.containsKey(it) }
if (notCachedUsers.isNotEmpty()) {
getAndCacheUsers(notCachedUsers)
}
// compute the list of users requested
val users = ids.mapNotNull { cachedUsers[it] }.toSet()
if (users.isNotEmpty()) {
return Result.Success(users)
}
return Result.Error(IOException("Unable to get users"))
}
private suspend fun getAndCacheUsers(userIds: List<Long>) {
val result = dataSource.getUsers(userIds)
// save the new users in the cachedUsers
if (result is Result.Success) {
result.data.forEach { cachedUsers[it.id] = it }
}
}
}
| apache-2.0 | b2bf0b115c18b8ed68ea9946d3a1e1b2 | 34.245283 | 98 | 0.689507 | 4.324074 | false | false | false | false |
mockk/mockk | modules/mockk/src/jvmMain/kotlin/io/mockk/impl/recording/JvmSignatureValueGenerator.kt | 1 | 2156 | package io.mockk.impl.recording
import io.mockk.impl.instantiation.AbstractInstantiator
import io.mockk.impl.instantiation.AnyValueGenerator
import io.mockk.core.ValueClassSupport.boxedClass
import java.util.*
import kotlin.reflect.KClass
import kotlin.reflect.full.cast
import kotlin.reflect.full.primaryConstructor
import kotlin.reflect.jvm.isAccessible
class JvmSignatureValueGenerator(val rnd: Random) : SignatureValueGenerator {
override fun <T : Any> signatureValue(
cls: KClass<T>,
anyValueGeneratorProvider: () -> AnyValueGenerator,
instantiator: AbstractInstantiator,
): T {
if (cls.isValue) {
val valueCls = cls.boxedClass
val valueSig = signatureValue(valueCls, anyValueGeneratorProvider, instantiator)
val constructor = cls.primaryConstructor!!.apply { isAccessible = true }
return constructor.call(valueSig)
}
return cls.cast(instantiate(cls, anyValueGeneratorProvider, instantiator))
}
private fun <T : Any> instantiate(
cls: KClass<T>,
anyValueGeneratorProvider: () -> AnyValueGenerator,
instantiator: AbstractInstantiator
): Any = when (cls) {
Boolean::class -> rnd.nextBoolean()
Byte::class -> rnd.nextInt().toByte()
Short::class -> rnd.nextInt().toShort()
Character::class -> rnd.nextInt().toChar()
Integer::class -> rnd.nextInt()
Long::class -> rnd.nextLong()
Float::class -> rnd.nextFloat()
Double::class -> rnd.nextDouble()
String::class -> rnd.nextLong().toString(16)
else ->
if (cls.isSealed) {
cls.sealedSubclasses.firstNotNullOfOrNull {
instantiate(it, anyValueGeneratorProvider, instantiator)
} ?: error("Unable to create proxy for sealed class $cls, available subclasses: ${cls.sealedSubclasses}")
} else {
@Suppress("UNCHECKED_CAST")
anyValueGeneratorProvider().anyValue(cls, isNullable = false) {
instantiator.instantiate(cls)
} as T
}
}
}
| apache-2.0 | fcd2d742cb0381a0173a8969bdc263af | 36.824561 | 121 | 0.640538 | 4.990741 | false | false | false | false |
DemonWav/IntelliJBukkitSupport | src/main/kotlin/platform/fabric/reference/EntryPointReference.kt | 1 | 6598 | /*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2021 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev.platform.fabric.reference
import com.demonwav.mcdev.util.manipulator
import com.demonwav.mcdev.util.reference.InspectionReference
import com.intellij.json.psi.JsonStringLiteral
import com.intellij.openapi.util.TextRange
import com.intellij.psi.JavaPsiFacade
import com.intellij.psi.PsiClass
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiElementResolveResult
import com.intellij.psi.PsiMethod
import com.intellij.psi.PsiModifier
import com.intellij.psi.PsiPolyVariantReference
import com.intellij.psi.PsiReference
import com.intellij.psi.PsiReferenceBase
import com.intellij.psi.PsiReferenceProvider
import com.intellij.psi.ResolveResult
import com.intellij.util.IncorrectOperationException
import com.intellij.util.ProcessingContext
object EntryPointReference : PsiReferenceProvider() {
override fun getReferencesByElement(element: PsiElement, context: ProcessingContext): Array<PsiReference> {
if (element !is JsonStringLiteral) {
return PsiReference.EMPTY_ARRAY
}
val manipulator = element.manipulator ?: return PsiReference.EMPTY_ARRAY
val range = manipulator.getRangeInElement(element)
val text = element.text.substring(range.startOffset, range.endOffset)
val methodParts = text.split("::", limit = 2)
val clazzParts = methodParts[0].split("$", limit = 0)
val references = mutableListOf<Reference>()
var cursor = -1
var innerClassDepth = -1
for (clazzPart in clazzParts) {
cursor++
innerClassDepth++
references.add(
Reference(
element,
range.cutOut(TextRange.from(cursor, clazzPart.length)),
innerClassDepth,
false
)
)
cursor += clazzPart.length
}
if (methodParts.size == 2) {
cursor += 2
references.add(
Reference(
element,
range.cutOut(TextRange.from(cursor, methodParts[1].length)),
innerClassDepth,
true
)
)
}
return references.toTypedArray()
}
private fun resolveReference(
element: JsonStringLiteral,
innerClassDepth: Int,
isMethodReference: Boolean
): Array<PsiElement> {
val strReference = element.value
val methodParts = strReference.split("::", limit = 2)
// split at dollar sign for inner class evaluation
val clazzParts = methodParts[0].split("$", limit = 0)
// this case should only happen if someone misuses the method, better protect against it anyways
if (innerClassDepth >= clazzParts.size ||
innerClassDepth + 1 < clazzParts.size &&
isMethodReference
) throw IncorrectOperationException("Invalid reference")
var clazz = JavaPsiFacade.getInstance(element.project).findClass(clazzParts[0], element.resolveScope)
?: return PsiElement.EMPTY_ARRAY
// if class is inner class, then a dot "." was used as separator instead of a dollar sign "$", this does not work to reference an inner class
if (clazz.parent is PsiClass) return PsiElement.EMPTY_ARRAY
// walk inner classes
for (inner in clazzParts.drop(1).take(innerClassDepth)) {
// we don't want any dots "." in the names of the inner classes
if (inner.contains('.')) return PsiElement.EMPTY_ARRAY
clazz = clazz.findInnerClassByName(inner, false) ?: return PsiElement.EMPTY_ARRAY
}
return if (isMethodReference) {
if (methodParts.size == 1) {
throw IncorrectOperationException("Invalid reference")
}
clazz.methods.filter { method ->
method.name == methodParts[1] &&
method.hasModifierProperty(PsiModifier.PUBLIC) &&
method.hasModifierProperty(PsiModifier.STATIC)
}.toTypedArray()
} else {
arrayOf(clazz)
}
}
fun isEntryPointReference(reference: PsiReference) = reference is Reference
private class Reference(
element: JsonStringLiteral,
range: TextRange,
private val innerClassDepth: Int,
private val isMethodReference: Boolean
) :
PsiReferenceBase<JsonStringLiteral>(element, range),
PsiPolyVariantReference,
InspectionReference {
override val description = "entry point '%s'"
override val unresolved = resolve() == null
override fun multiResolve(incompleteCode: Boolean): Array<ResolveResult> {
return resolveReference(element, innerClassDepth, isMethodReference)
.map { PsiElementResolveResult(it) }.toTypedArray()
}
override fun resolve(): PsiElement? {
val results = multiResolve(false)
return if (results.size == 1) {
results[0].element
} else {
null
}
}
override fun bindToElement(newTarget: PsiElement): PsiElement? {
val manipulator = element.manipulator ?: return null
val range = manipulator.getRangeInElement(element)
val text = element.text.substring(range.startOffset, range.endOffset)
val parts = text.split("::", limit = 2)
if (isMethodReference) {
val targetMethod = newTarget as? PsiMethod
?: throw IncorrectOperationException("Cannot target $newTarget")
if (parts.size == 1) {
throw IncorrectOperationException("Invalid reference")
}
val methodRange = range.cutOut(TextRange.from(parts[0].length + 2, parts[1].length))
return manipulator.handleContentChange(element, methodRange, targetMethod.name)
} else {
val targetClass = newTarget as? PsiClass
?: throw IncorrectOperationException("Cannot target $newTarget")
val classRange = if (parts.size == 1) {
range
} else {
range.cutOut(TextRange.from(0, parts[0].length))
}
return manipulator.handleContentChange(element, classRange, targetClass.qualifiedName)
}
}
}
}
| mit | 69f92fbdf331feeae410529a5166d597 | 38.987879 | 149 | 0.617915 | 5.390523 | false | false | false | false |
dewarder/Android-Kotlin-Commons | akommons/src/main/java/com/dewarder/akommons/database/SQLiteDatabase.kt | 1 | 2092 | /*
* Copyright (C) 2017 Artem Hluhovskyi
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
@file:JvmName("SQLiteDatabaseUtils")
package com.dewarder.akommons.database
import android.content.ContentValues
import android.database.Cursor
import android.database.sqlite.SQLiteDatabase
inline fun <R> SQLiteDatabase.use(block: (SQLiteDatabase) -> R): R {
var closed = false
try {
return block(this)
} catch (e: Exception) {
closed = true
try {
close()
} catch (closeException: Exception) {
}
throw e
} finally {
if (!closed) {
close()
}
}
}
fun SQLiteDatabase.executeQuery(
table: String,
columns: Array<String>? = null,
selection: String? = null,
selectionArgs: Array<String>? = null,
groupBy: String? = null,
having: String? = null,
orderBy: String? = null,
limit: String? = null
): Cursor = query(table, columns, selection, selectionArgs, groupBy, having, orderBy, limit)
fun SQLiteDatabase.executeInsert(
table: String,
nullColumnHack: String? = null,
values: ContentValues
): Long = insert(table, nullColumnHack, values)
fun SQLiteDatabase.executeUpdate(
table: String,
values: ContentValues,
whereClause: String? = null,
whereArgs: Array<String>? = null
): Long = update(table, values, whereClause, whereArgs).toLong()
fun SQLiteDatabase.executeDelete(
table: String,
whereClause: String? = null,
whereArgs: Array<String>? = null
): Long = delete(table, whereClause, whereArgs).toLong() | apache-2.0 | 592b63062e32e004d628dabb0bffe0ec | 28.069444 | 92 | 0.678298 | 4.167331 | false | false | false | false |
lare96/luna | plugins/world/player/skill/crafting/battlestaffCrafting/Battlestaff.kt | 1 | 1193 | package world.player.skill.crafting.battlestaffCrafting
import io.luna.game.model.item.Item
/**
* An enum representing battlestaves that can be made.
*/
enum class Battlestaff(val staff: Int,
val level: Int,
val orb: Int,
val exp: Double) {
WATER(staff = 1395,
level = 54,
orb = 571,
exp = 100.0),
EARTH(staff = 1399,
level = 58,
orb = 575,
exp = 112.5),
FIRE(staff = 1393,
level = 62,
orb = 569,
exp = 125.0),
AIR(staff = 1397,
level = 66,
orb = 573,
exp = 137.5);
companion object {
/**
* The battlestaff identifier.
*/
const val BATTLESTAFF = 1391
/**
* The battlestaff item.
*/
val BATTLESTAFF_ITEM = Item(BATTLESTAFF)
/**
* Mappings of [Battlestaff.orb] to [Battlestaff].
*/
val ORB_TO_BATTLESTAFF = values().associateBy { it.orb }
}
/**
* The staff item.
*/
val staffItem = Item(staff)
/**
* The orb item.
*/
val orbItem = Item(orb)
} | mit | 694495c8bf51ef668df93bb13ed7f92a | 19.947368 | 64 | 0.476949 | 3.836013 | false | false | false | false |
vondear/RxTools | RxDemo/src/main/java/com/tamsiree/rxdemo/activity/ActivityLoadingDetail.kt | 1 | 3695 | package com.tamsiree.rxdemo.activity
import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.viewpager.widget.PagerAdapter
import androidx.viewpager.widget.ViewPager
import com.tamsiree.rxdemo.R
import com.tamsiree.rxdemo.tools.EvaluatorARGB.Companion.instance
import com.tamsiree.rxkit.RxDeviceTool
import com.tamsiree.rxui.activity.ActivityBase
import com.tamsiree.rxui.view.loadingview.SpinKitView
import com.tamsiree.rxui.view.loadingview.SpriteFactory
import com.tamsiree.rxui.view.loadingview.Style
/**
* @author tamsiree
*/
class ActivityLoadingDetail : ActivityBase() {
var colors = intArrayOf(
Color.parseColor("#D55400"),
Color.parseColor("#2B3E51"),
Color.parseColor("#00BD9C"),
Color.parseColor("#227FBB"),
Color.parseColor("#7F8C8D"),
Color.parseColor("#FFCC5C"),
Color.parseColor("#D55400"),
Color.parseColor("#1AAF5D"))
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_loading_detail)
RxDeviceTool.setPortrait(this)
}
override fun initView() {
val viewPager = findViewById<ViewPager>(R.id.view_pager)
viewPager.offscreenPageLimit = 0
viewPager.adapter = object : PagerAdapter() {
override fun getCount(): Int {
return Style.values().size
}
override fun isViewFromObject(view: View, `object`: Any): Boolean {
return view === `object`
}
override fun instantiateItem(container: ViewGroup, position: Int): Any {
@SuppressLint("InflateParams") val view = LayoutInflater.from(container.context).inflate(R.layout.item_pager, null)
val spinKitView: SpinKitView = view.findViewById(R.id.spin_kit)
val name = view.findViewById<TextView>(R.id.name)
val style = Style.values()[position]
name.text = style.name
val drawable = SpriteFactory.create(style)
spinKitView.setIndeterminateDrawable(drawable!!)
container.addView(view)
return view
}
override fun destroyItem(container: ViewGroup, position: Int, `object`: Any) {
container.removeView(`object` as View)
}
}
viewPager.addOnPageChangeListener(object : ViewPager.OnPageChangeListener {
override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) {
val color = instance.evaluate(positionOffset,
colors[position % colors.size],
colors[(position + 1) % colors.size]) as Int
window.decorView.setBackgroundColor(color)
}
override fun onPageSelected(position: Int) {
window.decorView.setBackgroundColor(colors[position % colors.size])
}
override fun onPageScrollStateChanged(state: Int) {}
})
viewPager.currentItem = intent.getIntExtra("position", 0)
}
override fun initData() {
}
companion object {
fun start(context: Context, position: Int) {
val intent = Intent(context, ActivityLoadingDetail::class.java)
intent.putExtra("position", position)
context.startActivity(intent)
}
}
} | apache-2.0 | f4771fdf8e44dfdcdd1bd3f50582d172 | 36.333333 | 131 | 0.643572 | 4.87467 | false | false | false | false |
SapuSeven/BetterUntis | app/src/main/java/com/sapuseven/untis/dialogs/WeekRangePickerPreferenceDialog.kt | 1 | 4996 | package com.sapuseven.untis.dialogs
import android.app.Dialog
import android.content.Context
import android.os.Bundle
import android.view.View
import androidx.preference.PreferenceDialogFragmentCompat
import ca.antonious.materialdaypicker.MaterialDayPicker
import ca.antonious.materialdaypicker.SelectionMode
import ca.antonious.materialdaypicker.SelectionState
import com.google.android.material.dialog.MaterialAlertDialogBuilder
import com.sapuseven.untis.R
import com.sapuseven.untis.preferences.WeekRangePickerPreference
class WeekRangePickerPreferenceDialog(private val onCloseListener: ((positiveResult: Boolean, selectedDays: Int) -> Unit)? = null) : PreferenceDialogFragmentCompat() {
private lateinit var picker: MaterialDayPicker
companion object {
fun newInstance(key: String, onCloseListener: ((positiveResult: Boolean, selectedDays: Int) -> Unit)?): WeekRangePickerPreferenceDialog {
val fragment = WeekRangePickerPreferenceDialog(onCloseListener)
val bundle = Bundle(1)
bundle.putString(ARG_KEY, key)
fragment.arguments = bundle
return fragment
}
}
override fun onCreateDialogView(context: Context?): View {
val root = super.onCreateDialogView(context)
picker = root.findViewById(R.id.day_picker)
picker.apply {
selectionMode = RangeSelectionMode(this)
val savedDays = preference.getPersistedStringSet(emptySet()).toList().map { MaterialDayPicker.Weekday.valueOf(it) }
setSelectedDays(if (savedDays.size == 1) listOf(savedDays.first()) else listOfNotNull(savedDays.minOrNull(), savedDays.maxOrNull()))
}
return root
}
override fun onDialogClosed(positiveResult: Boolean) {
if (positiveResult) preference.persistStringSet(picker.selectedDays.map { it.name }.toSet())
(preference as? WeekRangePickerPreference)?.refreshSummary()
onCloseListener?.invoke(positiveResult, picker.selectedDays.size)
}
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
val builder = MaterialAlertDialogBuilder(requireContext())
.setTitle(preference.dialogTitle)
.setView(onCreateDialogView(context))
.setPositiveButton(preference.positiveButtonText, this)
.setNegativeButton(preference.negativeButtonText, this)
.setNeutralButton(R.string.all_reset) { dialog, _ ->
preference.persistStringSet(emptySet())
onCloseListener?.invoke(true, 0)
dialog.dismiss()
}
return builder.create()
}
class RangeSelectionMode(private val materialDayPicker: MaterialDayPicker) : SelectionMode {
override fun getSelectionStateAfterSelecting(lastSelectionState: SelectionState, dayToSelect: MaterialDayPicker.Weekday): SelectionState {
return createRangedSelectionState(
lastSelectionState = lastSelectionState,
dayPressed = dayToSelect
)
}
override fun getSelectionStateAfterDeselecting(lastSelectionState: SelectionState, dayToDeselect: MaterialDayPicker.Weekday): SelectionState {
return createRangedSelectionState(
lastSelectionState = lastSelectionState,
dayPressed = dayToDeselect
)
}
private fun createRangedSelectionState(lastSelectionState: SelectionState, dayPressed: MaterialDayPicker.Weekday): SelectionState {
val previouslySelectedDays = lastSelectionState.selectedDays
val orderedWeekdays = MaterialDayPicker.Weekday.getOrderedDaysOfWeek(materialDayPicker.locale)
val ordinalsOfPreviouslySelectedDays = previouslySelectedDays.map { orderedWeekdays.indexOf(it) }
val ordinalOfFirstDayInPreviousRange = ordinalsOfPreviouslySelectedDays.minOrNull()
val ordinalOfLastDayInPreviousRange = ordinalsOfPreviouslySelectedDays.maxOrNull()
val ordinalOfSelectedDay = orderedWeekdays.indexOf(dayPressed)
return when {
ordinalOfFirstDayInPreviousRange == null || ordinalOfLastDayInPreviousRange == null -> {
// We had no previous selection so just return the day pressed as the selection.
SelectionState.withSingleDay(dayPressed)
}
ordinalOfFirstDayInPreviousRange == ordinalOfLastDayInPreviousRange && ordinalOfFirstDayInPreviousRange == ordinalOfSelectedDay -> {
// User pressed the only day in the range selection. Return an empty selection.
SelectionState()
}
ordinalOfSelectedDay == ordinalOfFirstDayInPreviousRange || ordinalOfSelectedDay == ordinalOfLastDayInPreviousRange -> {
// User pressed the first or last item in range. Just deselect that item.
lastSelectionState.withDayDeselected(dayPressed)
}
ordinalOfSelectedDay < ordinalOfFirstDayInPreviousRange -> {
// User pressed a day on the left of the previous date range. Grow the starting point of the range to that.
SelectionState(selectedDays = orderedWeekdays.subList(ordinalOfSelectedDay, ordinalOfLastDayInPreviousRange + 1))
}
else -> {
// User pressed a day on the right of the start of the date range. Update the ending point to that position.
SelectionState(selectedDays = orderedWeekdays.subList(ordinalOfFirstDayInPreviousRange, ordinalOfSelectedDay + 1))
}
}
}
}
}
| gpl-3.0 | e223fc65ecb3a25560e445622d56a088 | 44.834862 | 167 | 0.790032 | 4.878906 | false | false | false | false |
BilledTrain380/sporttag-psa | app/psa-runtime-service/psa-service-standard/src/main/kotlin/ch/schulealtendorf/psa/service/standard/entity/CoachEntity.kt | 1 | 2106 | /*
* Copyright (c) 2017 by Nicolas Märchy
*
* This file is part of Sporttag PSA.
*
* Sporttag PSA 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.
*
* Sporttag PSA 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 Sporttag PSA. If not, see <http://www.gnu.org/licenses/>.
*
* Diese Datei ist Teil von Sporttag PSA.
*
* Sporttag PSA ist Freie Software: Sie können es unter den Bedingungen
* der GNU General Public License, wie von der Free Software Foundation,
* Version 3 der Lizenz oder (nach Ihrer Wahl) jeder späteren
* veröffentlichten Version, weiterverbreiten und/oder modifizieren.
*
* Sporttag PSA wird in der Hoffnung, dass es nützlich sein wird, aber
* OHNE JEDE GEWÄHRLEISTUNG, bereitgestellt; sogar ohne die implizite
* Gewährleistung der MARKTFÄHIGKEIT oder EIGNUNG FÜR EINEN BESTIMMTEN ZWECK.
* Siehe die GNU General Public License für weitere Details.
*
* Sie sollten eine Kopie der GNU General Public License zusammen mit diesem
* Programm erhalten haben. Wenn nicht, siehe <http://www.gnu.org/licenses/>.
*
*
*/
package ch.schulealtendorf.psa.service.standard.entity
import javax.persistence.Entity
import javax.persistence.GeneratedValue
import javax.persistence.GenerationType
import javax.persistence.Id
import javax.persistence.Table
import javax.validation.constraints.NotNull
import javax.validation.constraints.Size
/**
* @author nmaerchy
* @since 1.0.0
*/
@Entity
@Table(name = "COACH")
data class CoachEntity(
@Id
@NotNull
@GeneratedValue(strategy = GenerationType.IDENTITY)
var id: Int? = null,
@NotNull
@Size(min = 1, max = 100)
var name: String = ""
)
| gpl-3.0 | d2abb0f802a0f407869c45f18cda51f2 | 32.269841 | 77 | 0.748569 | 4.225806 | false | false | false | false |
AndroidX/androidx | compose/ui/ui/integration-tests/ui-demos/src/main/java/androidx/compose/ui/demos/focus/CancelFocusDemo.kt | 3 | 3342 | /*
* 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.compose.ui.demos.focus
import android.annotation.SuppressLint
import androidx.compose.foundation.border
import androidx.compose.foundation.focusable
import androidx.compose.foundation.layout.Arrangement.SpaceEvenly
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.size
import androidx.compose.material.Switch
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.ExperimentalComposeUiApi
import androidx.compose.ui.Modifier
import androidx.compose.ui.composed
import androidx.compose.ui.focus.FocusRequester.Companion.Cancel
import androidx.compose.ui.focus.FocusRequester.Companion.Default
import androidx.compose.ui.focus.focusProperties
import androidx.compose.ui.focus.onFocusChanged
import androidx.compose.ui.graphics.Color.Companion.Black
import androidx.compose.ui.graphics.Color.Companion.Red
import androidx.compose.ui.unit.dp
@OptIn(ExperimentalComposeUiApi::class)
@Composable
fun CancelFocusDemo() {
Column {
Text("Use the arrow keys to move focus left/right/up/down.")
}
Column(Modifier.fillMaxSize(), SpaceEvenly) {
var blockFocusMove by remember { mutableStateOf(false) }
Row {
Text("Cancel focus moves between 3 and 4")
Switch(checked = blockFocusMove, onCheckedChange = { blockFocusMove = !blockFocusMove })
}
Row(Modifier.fillMaxWidth(), SpaceEvenly) {
Text("1", Modifier.focusableWithBorder())
Text("2", Modifier.focusableWithBorder())
}
Row(Modifier.fillMaxWidth(), SpaceEvenly) {
Text(
text = "3",
modifier = Modifier
.focusProperties { if (blockFocusMove) { right = Cancel } }
.focusableWithBorder()
)
Text(
text = "4",
modifier = Modifier
.focusProperties { left = if (blockFocusMove) Cancel else Default }
.focusableWithBorder()
)
}
}
}
@SuppressLint("ModifierInspectorInfo")
private fun Modifier.focusableWithBorder() = composed {
var color by remember { mutableStateOf(Black) }
Modifier
.size(50.dp)
.border(1.dp, color)
.onFocusChanged { color = if (it.isFocused) Red else Black }
.focusable()
}
| apache-2.0 | 83c55e0b50848ba983a0a0abf04afb7c | 37.413793 | 100 | 0.713944 | 4.648122 | false | false | false | false |
Gnat008/NovusBroadcast | src/main/kotlin/me/ebonjaeger/novusbroadcast/commands/ListCommand.kt | 1 | 2598 | package me.ebonjaeger.novusbroadcast.commands
import co.aikar.commands.BaseCommand
import co.aikar.commands.annotation.CommandAlias
import co.aikar.commands.annotation.CommandCompletion
import co.aikar.commands.annotation.CommandPermission
import co.aikar.commands.annotation.Default
import co.aikar.commands.annotation.Description
import co.aikar.commands.annotation.Subcommand
import me.ebonjaeger.novusbroadcast.MessageList
import me.ebonjaeger.novusbroadcast.NovusBroadcast
import org.bukkit.ChatColor
import org.bukkit.command.CommandSender
@CommandAlias("novusbroadcast|nb")
class ListCommand(private val plugin: NovusBroadcast) : BaseCommand()
{
private val PAGE_SIZE = 5
@Subcommand("list")
@CommandCompletion("@messageLists")
@CommandPermission("novusbroadcast.list")
@Description("Shows all messages in a list.")
fun onListMessages(sender: CommandSender, listName: String, @Default("1") page: Int)
{
val messageList = plugin.messageLists[listName]
if (messageList == null)
{
sender.sendMessage("${ChatColor.RED}» ${ChatColor.GRAY}No list with name '$listName' found!")
return
}
if (messageList.messages.isNullOrEmpty())
{
sender.sendMessage("${ChatColor.RED}» ${ChatColor.GRAY}This list has no messages in it!")
return
}
val pages = (messageList.messages.size + PAGE_SIZE - 1) / PAGE_SIZE
if (page < 1 || page > pages)
{
sender.sendMessage("${ChatColor.RED}» ${ChatColor.GRAY}Page '$page' does not exist!")
return
}
val list = buildList(messageList, page, pages)
sender.sendMessage(list)
}
private fun buildList(messageList: MessageList, page: Int, totalPages: Int): String
{
val startIndex = (page - 1) * PAGE_SIZE
var endIndex = startIndex + PAGE_SIZE
if (endIndex >= messageList.messages.size)
{
endIndex = messageList.messages.size - 1
}
val sb = StringBuilder()
sb.append("${ChatColor.GRAY}${ChatColor.STRIKETHROUGH} ---------------${ChatColor.BLUE} Page ${ChatColor.WHITE}$page/$totalPages ${ChatColor.GRAY}${ChatColor.STRIKETHROUGH}--------------- \n")
for (i in startIndex..endIndex)
{
sb.append("${ChatColor.WHITE}$i${ChatColor.GRAY}: ${ChatColor.WHITE}${messageList.messages[i]}\n")
}
sb.append("${ChatColor.GRAY}${ChatColor.STRIKETHROUGH} ---------------------------------------------------- \n")
return sb.toString()
}
} | mit | d9b7c3214685586f2a68844670bcf97c | 34.561644 | 200 | 0.645087 | 4.59292 | false | false | false | false |
fdeitylink/bagel | kbagel/src/main/kotlin/io/fdeitylink/kbagel/KBagel.kt | 1 | 2281 | package io.fdeitylink.kbagel
import java.util.stream.Collectors
import java.nio.file.Paths
import java.nio.file.Files
import java.nio.charset.Charset
import java.io.IOException
import kotlin.system.exitProcess
internal object KBagel {
private const val scanParseErrorCode = 65
private const val runtimeErrorCode = 70
private val interpreter = Interpreter(Reporter)
@JvmStatic
fun main(args: Array<String>) = when {
args.size > 1 -> println("Usage: kbagel [script]")
args.size == 1 -> runFile(args[0])
else -> runPrompt()
}
@Throws(IOException::class)
private fun runFile(path: String) {
run(Files.lines(Paths.get(path), Charset.defaultCharset()).use { it.collect(Collectors.joining("\n")) })
if (Reporter.hadScanParseError) {
exitProcess(scanParseErrorCode)
}
if (Reporter.hadRuntimeError) {
exitProcess(runtimeErrorCode)
}
}
@Throws(IOException::class)
private fun runPrompt() {
print("> ")
System.`in`.reader().buffered().use {
it.lines().forEach {
run(it)
//Even if the user made an error, it shouldn't kill the REPL session
Reporter.hadScanParseError = false
print("> ")
}
}
}
private fun run(source: String) {
val stmts = Parser(Scanner(source, Reporter).tokens, Reporter).parsed
if (Reporter.hadScanParseError) {
return
}
interpreter.interpret(stmts)
}
private object Reporter : ErrorReporter() {
//The setter visibility modifiers allows the KBagel object to access the member variables
@Suppress("RedundantVisibilityModifier", "RedundantSetter")
override var hadScanParseError = false
public set
override var hadRuntimeError = false
override fun report(line: Int, message: String, location: String) {
System.err.println("[line $line] Error $location: $message")
hadScanParseError = true
}
override fun report(err: BagelRuntimeError) {
System.err.println("${err.message}\n[line ${err.token.line}]")
hadRuntimeError = true
}
}
} | apache-2.0 | 80cdfaa21d249e6a2e7524ca5d29f431 | 28.25641 | 112 | 0.615081 | 4.481336 | false | false | false | false |
TeamWizardry/LibrarianLib | modules/core/src/main/kotlin/com/teamwizardry/librarianlib/core/util/Shorthand.kt | 1 | 8263 | /**
* Shorthands for creating common objects like vectors and resource locations. These functions are available in Java
* as static members of the `Shorthand` class. e.g.
*
* ```java
* import com.teamwizardry.librarianlib.core.util.Shorthand.vec
* ```
*/
@file:JvmName("Shorthand")
package com.teamwizardry.librarianlib.core.util
import com.teamwizardry.librarianlib.math.Rect2d
import com.teamwizardry.librarianlib.math.Vec2d
import com.teamwizardry.librarianlib.math.Vec2i
import net.minecraft.util.Identifier
import net.minecraft.util.math.BlockPos
import net.minecraft.util.math.Vec3d
import net.minecraft.util.math.Vec3i
// Vec2d:
/**
* Get [Vec2d] instances, selecting from a pool of small integer instances when possible. This can vastly reduce the
* number of Vec2d allocations when they are used as intermediates, e.g. when adding one Vec2d to another to offset
* it, this allocates no objects: `Shorthand.vec(1, 0)`
*/
public fun vec(x: Double, y: Double): Vec2d = Vec2d.getPooled(x, y)
/**
* Get [Vec2d] instances, selecting from a pool of small integer instances when possible. This can vastly reduce the
* number of Vec2d allocations when they are used as intermediates, e.g. when adding one Vec2d to another to offset it,
* this allocates no objects: `vec(1, 0)`
*
* This method exists for ease of use in kotlin, where numbers aren't implicitly coerced.
*/
@JvmSynthetic
@Suppress("NOTHING_TO_INLINE")
public inline fun vec(x: Number, y: Number): Vec2d = vec(x.toDouble(), y.toDouble())
// Vec2i:
/**
* Get [Vec2i] instances, selecting from a pool of small value instances when possible. This can vastly reduce the
* number of Vec2i allocations when they are used as intermediates, e.g. when adding one Vec2i to another to offset
* it, this allocates no objects: `Shorthand.ivec(1, 0)`
*/
public fun ivec(x: Int, y: Int): Vec2i = Vec2i.getPooled(x, y)
// Vec3d:
/**
* Get [Vec3d] instances, selecting from a pool of small integer instances when possible. This can vastly reduce the
* number of Vec3d allocations when they are used as intermediates, e.g. when adding one Vec3d to another to offset
* it, this allocates no objects: `Shorthand.vec(1, 0, 0)`
*/
public fun vec(x: Double, y: Double, z: Double): Vec3d = Vec3dPool.getPooled(x, y, z)
/**
* Get [Vec3d] instances, selecting from a pool of small integer instances when possible. This can vastly reduce the
* number of Vec3d allocations when they are used as intermediates, e.g. when adding one Vec3d to another to offset
* it, this allocates no objects: `Shorthand.vec(1, 0, 0)`
*/
public fun vec(pos: BlockPos): Vec3d = vec(pos.x.toDouble(), pos.y.toDouble(), pos.z.toDouble())
/**
* Get [Vec3d] instances, selecting from a pool of small integer instances when possible. This can vastly reduce the
* number of Vec3d allocations when they are used as intermediates, e.g. when adding one Vec3d to another to offset it,
* this allocates no objects: `vec(1, 0, 0)`
*
* This method exists for ease of use in kotlin, where numbers aren't implicitly coerced.
*/
@JvmSynthetic
@Suppress("NOTHING_TO_INLINE")
public inline fun vec(x: Number, y: Number, z: Number): Vec3d = vec(x.toDouble(), y.toDouble(), z.toDouble())
// Vec3i:
/**
* Get [Vec3i] instances, selecting from a pool of small integer instances when possible. This can vastly reduce the
* number of Vec3i allocations when they are used as intermediates, e.g. when adding one Vec3i to another to offset
* it, this allocates no objects: `Shorthand.ivec(1, 0, 0)`
*/
public fun ivec(x: Int, y: Int, z: Int): Vec3i = Vec3iPool.getPooled(x, y, z)
// BlockPos:
/**
* Get [BlockPos] instances, selecting from a pool of small integer instances when possible. This can vastly reduce
* the number of BlockPos allocations when they are used as intermediates, e.g. when adding one BlockPos to another
* to offset it, this allocates no objects: `Shorthand.block(1, 0, 0)`
*/
public fun block(x: Int, y: Int, z: Int): BlockPos = BlockPosPool.getPooled(x, y, z)
/**
* Get [BlockPos] instances, selecting from a pool of small integer instances when possible. This can vastly reduce
* the number of BlockPos allocations when they are used as intermediates, e.g. when adding one BlockPos to another
* to offset it, this allocates no objects: `Shorthand.block(1, 0, 0)`
*/
public fun block(vec: Vec3d): BlockPos = BlockPosPool.getPooled(vec.x.toInt(), vec.y.toInt(), vec.z.toInt())
/**
* Get [BlockPos] instances, selecting from a pool of small integer instances when possible. This can vastly reduce
* the number of BlockPos allocations when they are used as intermediates, e.g. when adding one BlockPos to another
* to offset it, this allocates no objects: `Shorthand.block(1, 0, 0)`
*/
public fun block(vec: Vec3i): BlockPos = BlockPosPool.getPooled(vec.x, vec.y, vec.z)
// Rect2d:
/**
* Convenience method for creating a [Rect2d] instance. This does not do any pooling like the vectors do, but is
* more convenient than `new Rect2d(...)`
*/
public fun rect(x: Double, y: Double, width: Double, height: Double): Rect2d = Rect2d(x, y, width, height)
/**
* Convenience method for creating a [Rect2d] instance. This does not do any pooling like the vectors do, but is
* more convenient than `new Rect2d(...)`
*/
public fun rect(pos: Vec2d, size: Vec2d): Rect2d = Rect2d(pos, size)
/**
* Convenience function for creating [Rect2d]s in Kotlin without needing to explicitly convert parameters to doubles.
*/
@JvmSynthetic
@Suppress("NOTHING_TO_INLINE")
public inline fun rect(x: Number, y: Number, width: Number, height: Number): Rect2d = rect(x.toDouble(), y.toDouble(), width.toDouble(), height.toDouble())
// Internal:
private object Vec3dPool {
private val poolBits = 5
private val poolMask = (1 shl poolBits) - 1
private val poolMax = (1 shl poolBits - 1) - 1
private val poolMin = -(1 shl poolBits - 1)
private val pool = Array(1 shl poolBits * 3) {
val x = (it shr poolBits * 2) + poolMin
val y = (it shr poolBits and poolMask) + poolMin
val z = (it and poolMask) + poolMin
Vec3d(x.toDouble(), y.toDouble(), z.toDouble())
}
@JvmStatic
fun getPooled(x: Double, y: Double, z: Double): Vec3d {
val xi = x.toInt()
val yi = y.toInt()
val zi = z.toInt()
if (xi.toDouble() == x && xi in poolMin..poolMax &&
yi.toDouble() == y && yi in poolMin..poolMax &&
zi.toDouble() == z && zi in poolMin..poolMax) {
return pool[
((xi - poolMin) shl poolBits * 2) or ((yi - poolMin) shl poolBits) or (zi - poolMin)
]
}
return Vec3d(x, y, z)
}
}
private object Vec3iPool {
private val poolBits = 5
private val poolMask = (1 shl poolBits) - 1
private val poolMax = (1 shl poolBits - 1) - 1
private val poolMin = -(1 shl poolBits - 1)
private val pool = Array(1 shl poolBits * 3) {
val x = (it shr poolBits * 2) + poolMin
val y = (it shr poolBits and poolMask) + poolMin
val z = (it and poolMask) + poolMin
Vec3i(x, y, z)
}
@JvmStatic
fun getPooled(x: Int, y: Int, z: Int): Vec3i {
if (x in poolMin..poolMax &&
y in poolMin..poolMax &&
z in poolMin..poolMax) {
return pool[
((x - poolMin) shl poolBits * 2) or ((y - poolMin) shl poolBits) or (z - poolMin)
]
}
return Vec3i(x, y, z)
}
}
private object BlockPosPool {
private val poolBits = 5
private val poolMask = (1 shl poolBits) - 1
private val poolMax = (1 shl poolBits - 1) - 1
private val poolMin = -(1 shl poolBits - 1)
private val pool = Array(1 shl poolBits * 3) {
val x = (it shr poolBits * 2) + poolMin
val y = (it shr poolBits and poolMask) + poolMin
val z = (it and poolMask) + poolMin
BlockPos(x, y, z)
}
@JvmStatic
fun getPooled(x: Int, y: Int, z: Int): BlockPos {
if (x in poolMin..poolMax &&
y in poolMin..poolMax &&
z in poolMin..poolMax) {
return pool[
((x - poolMin) shl poolBits * 2) or ((y - poolMin) shl poolBits) or (z - poolMin)
]
}
return BlockPos(x, y, z)
}
} | lgpl-3.0 | e77822c296fc85b69d1d854fa1fe9e4f | 38.922705 | 155 | 0.673968 | 3.591047 | false | false | false | false |
adam-arold/hexameter | mixite.core/core/src/main/kotlin/org/hexworks/mixite/core/internal/impl/layoutstrategy/HexagonalGridLayoutStrategy.kt | 1 | 1659 | package org.hexworks.mixite.core.internal.impl.layoutstrategy
import org.hexworks.mixite.core.api.CubeCoordinate
import org.hexworks.mixite.core.api.HexagonOrientation
import org.hexworks.mixite.core.api.HexagonalGridBuilder
import org.hexworks.mixite.core.api.contract.SatelliteData
import kotlin.math.abs
import kotlin.math.floor
import kotlin.math.max
import kotlin.math.round
class HexagonalGridLayoutStrategy : GridLayoutStrategy() {
override fun fetchGridCoordinates(builder: HexagonalGridBuilder<out SatelliteData>): Iterable<CubeCoordinate> {
val coords = ArrayList<CubeCoordinate>()
val gridSize = builder.getGridHeight()
var startX = if (HexagonOrientation.FLAT_TOP.equals(builder.getOrientation())) floor(gridSize / 2.0).toInt() else round(gridSize / 4.0).toInt()
val hexRadius = floor(gridSize / 2.0).toInt()
val minX = startX - hexRadius
var y = 0
while (y < gridSize) {
val distanceFromMid = abs(hexRadius - y)
for (x in max(startX, minX)..max(startX, minX) + hexRadius + hexRadius - distanceFromMid) {
val gridZ = if (HexagonOrientation.FLAT_TOP.equals(builder.getOrientation())) y - floor(gridSize / 4.0).toInt() else y
coords.add(CubeCoordinate.fromCoordinates(x, gridZ))
}
startX--
y++
}
return coords
}
override fun checkParameters(gridHeight: Int, gridWidth: Int): Boolean {
val superResult = checkCommonCase(gridHeight, gridWidth)
val result = gridHeight == gridWidth && abs(gridHeight % 2) == 1
return result && superResult
}
}
| mit | 8426c92dacb666ac10ebb32bde15a08a | 41.538462 | 151 | 0.684147 | 4.2 | false | false | false | false |
google/playhvz | Android/ghvzApp/app/src/main/java/com/app/playhvz/firebase/classmodels/Group.kt | 1 | 1252 | /*
* Copyright 2020 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.app.playhvz.firebase.classmodels
/** Android data model representing Firebase Group documents. */
class Group {
var id: String? = null
// Name of group
var name: String? = null
var managed: Boolean = false
var owners = listOf<String>()
var settings: Settings = Settings()
var members = listOf<String>()
class Settings {
var canAddSelf: Boolean = true
var canAddOthers: Boolean = true
var canRemoveSelf: Boolean = true
var canRemoveOthers: Boolean = true
var autoAdd: Boolean = false
var autoRemove: Boolean = false
var allegianceFilter: String = ""
}
} | apache-2.0 | 80abc974f7fcac039f18a1c5cc5ebf0f | 30.325 | 75 | 0.689297 | 4.392982 | false | false | false | false |
bsmr-java/lwjgl3 | modules/templates/src/main/kotlin/org/lwjgl/system/templates/MemoryAccessJNI.kt | 1 | 2169 | /*
* Copyright LWJGL. All rights reserved.
* License terms: https://www.lwjgl.org/license
*/
package org.lwjgl.system.templates
import org.lwjgl.generator.*
val MemoryAccessJNI = "MemoryAccessJNI".nativeClass(packageName = "org.lwjgl.system") {
nativeImport(
"<stdlib.h>",
"<stdint.h>"
)
val primitives = arrayOf(
Triple(int8_t, "Byte", "a byte value"),
Triple(int16_t, "Short", "a short value"),
Triple(int32_t, "Int", "an int value"),
Triple(int64_t, "Long", "a long value"),
Triple(float, "Float", "a float value"),
Triple(double, "Double", "a double value"),
Triple(intptr_t, "Address", "a pointer address")
)
nativeDirective(
"""#ifdef LWJGL_WINDOWS
__pragma(warning(disable : 4711))
static void* aligned_alloc(size_t alignment, size_t size) {
return _aligned_malloc(size, alignment);
}
#define aligned_free _aligned_free
#else
#ifndef __USE_ISOC11
static void* aligned_alloc(size_t alignment, size_t size) {
void *p = NULL;
posix_memalign(&p, alignment, size);
return p;
}
#endif
#define aligned_free free
#endif
// -----------
${primitives
.asSequence()
.map {
val (type, name) = it
"static inline ${type.name} get$name(void *ptr) { return *(${type.name} *)ptr; }"
}
.joinToString("\n")}
// -----------
${primitives
.asSequence()
.map {
val (type, name) = it
"static inline void put$name(void *ptr, ${type.name} value) { *(${type.name} *)ptr = value; }"
}
.joinToString("\n")}
// -----------""")
access = Access.INTERNAL
documentation = "Memory access utilities."
arrayOf(
"malloc",
"calloc",
"realloc",
"free",
"aligned_alloc",
"aligned_free"
).forEach {
macro..(Address..voidptr)(
it,
"Returns the address of the stdlib $it function."
)
}
for ((type, name, msg) in primitives)
type(
"get$name",
"Reads $msg from the specified memory address.",
voidptr.IN("ptr", "the memory address to read")
)
for ((type, name, msg) in primitives)
void(
"put$name",
"Writes $msg to the specified memory address.",
voidptr.IN("ptr", "the memory address to write"),
type.IN("value", "the value to write")
)
} | bsd-3-clause | 44a7465763deb5718c9b37d0a5d68c0e | 20.485149 | 98 | 0.623329 | 3.02933 | false | false | false | false |
codehz/container | app/src/main/java/one/codehz/container/VLoadingActivity.kt | 1 | 1869 | package one.codehz.container
import android.app.Activity
import android.os.Bundle
import android.os.Handler
import android.widget.ImageView
import android.widget.TextView
import android.widget.Toast
import one.codehz.container.ext.get
import one.codehz.container.ext.vActivityManager
import one.codehz.container.ext.virtualCore
import one.codehz.container.models.AppModel
class VLoadingActivity : Activity() {
val iconView by lazy<ImageView> { this[R.id.icon] }
val titleView by lazy<TextView> { this[R.id.title] }
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.loading_page)
val package_name = intent.data.path.substring(1)
val userId = intent.data.fragment?.toInt() ?: 0
val model = AppModel(this, virtualCore.findApp(package_name))
iconView.setImageDrawable(model.icon)
titleView.text = model.name
val target = virtualCore.getLaunchIntent(package_name, userId)
if (target == null) {
Toast.makeText(this, getString(R.string.null_launch_intent), Toast.LENGTH_SHORT).show()
return finishAfterTransition()
}
virtualCore.setLoadingPage(target, this)
if (intent.data.getQueryParameter("delay") != null)
Handler().postDelayed({
vActivityManager.startActivity(target, userId)
overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out)
}, 50)
else if (!virtualCore.isAppRunning(package_name, userId))
Handler().postDelayed({
vActivityManager.startActivity(target, userId)
overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out)
}, 100)
else
vActivityManager.startActivity(target, userId)
}
} | gpl-3.0 | 08baf91663317a0301a98ee62f53f30b | 36.4 | 99 | 0.682718 | 4.387324 | false | false | false | false |
kenrube/Fantlab-client | app/src/main/kotlin/ru/fantlab/android/ui/modules/bookcases/selector/BookcasesSelectorPresenter.kt | 2 | 4012 | package ru.fantlab.android.ui.modules.bookcases.selector
import android.os.Bundle
import android.view.View
import io.reactivex.Single
import io.reactivex.functions.Consumer
import ru.fantlab.android.data.dao.model.*
import ru.fantlab.android.data.dao.response.*
import ru.fantlab.android.helper.BundleConstant
import ru.fantlab.android.provider.rest.DataManager
import ru.fantlab.android.provider.rest.getBookcaseInclusionsPath
import ru.fantlab.android.provider.storage.DbProvider
import ru.fantlab.android.ui.base.mvp.presenter.BasePresenter
class BookcasesSelectorPresenter : BasePresenter<BookcasesSelectorMvp.View>(),
BookcasesSelectorMvp.Presenter {
private var bookcaseType: String = ""
private var entityId: Int = 0
override fun onFragmentCreated(bundle: Bundle) {
bookcaseType = bundle.getString(BundleConstant.EXTRA_TWO)
entityId = bundle.getInt(BundleConstant.EXTRA_THREE)
getBookcases(bookcaseType, entityId, false)
}
override fun getBookcases(bookcaseType: String, entityId: Int, force: Boolean) {
makeRestCall(
getBookcasesInternal(bookcaseType, entityId, force).toObservable(),
Consumer { bookcasesInclusions ->
sendToView {
val inclusions: ArrayList<BookcaseSelection> = ArrayList()
bookcasesInclusions!!.map { inclusions.add(BookcaseSelection(it, it.itemAdded == 1)) }
it.onInitViews(inclusions)
}
}
)
}
private fun getBookcasesInternal(bookcaseType: String, entityId: Int, force: Boolean) =
getBookcasesFromServer(bookcaseType, entityId)
.onErrorResumeNext { throwable ->
if (!force) {
getBookcasesFromDb(bookcaseType, entityId)
} else {
throw throwable
}
}
private fun getBookcasesFromServer(bookcaseType: String, entityId: Int): Single<ArrayList<BookcaseInclusion>> =
DataManager.getBookcaseInclusions(bookcaseType, entityId)
.map { getBookcases(it) }
private fun getBookcasesFromDb(bookcaseType: String, entityId: Int): Single<ArrayList<BookcaseInclusion>> =
DbProvider.mainDatabase
.responseDao()
.get(getBookcaseInclusionsPath(bookcaseType, entityId))
.map { it.response }
.map { BookcaseInclusionResponse.Deserializer().deserialize(it) }
.map { getBookcases(it) }
private fun getBookcases(response: BookcaseInclusionResponse): ArrayList<BookcaseInclusion> {
val inclusions = ArrayList<BookcaseInclusion>()
response.items.map { inclusions.add(BookcaseInclusion(it.bookcaseId, it.bookcaseName, it.itemAdded, bookcaseType)) }
return inclusions
}
override fun onItemClick(position: Int, v: View?, item: BookcaseSelection) {
sendToView { it.onItemClicked(item, position) }
}
override fun onItemLongClick(position: Int, v: View?, item: BookcaseSelection) {
// TODO("not implemented")
}
override fun onItemSelected(position: Int, v: View?, item: BookcaseSelection) {
sendToView { it.onItemSelected(item, position) }
}
override fun includeItem(bookcaseId: Int, entityId: Int, include: Boolean) {
makeRestCall(
DataManager.includeItemToBookcase(bookcaseId, entityId, if (include) "add" else "delete").toObservable(),
Consumer { response ->
val result = BookcaseItemIncludedResponse.Parser().parse(response)
if (result == null) {
sendToView { it.showErrorMessage(response) }
} else {
sendToView { it.onItemSelectionUpdated() }
}
}
)
}
} | gpl-3.0 | 18b101422d05d9f0a800911a34a0abff | 41.691489 | 124 | 0.63011 | 5.21039 | false | false | false | false |
kenrube/Fantlab-client | app/src/main/kotlin/ru/fantlab/android/ui/modules/search/awards/SearchAwardsFragment.kt | 2 | 4182 | package ru.fantlab.android.ui.modules.search.awards
import android.content.Context
import android.os.Bundle
import android.view.View
import androidx.annotation.StringRes
import com.evernote.android.state.State
import kotlinx.android.synthetic.main.micro_grid_refresh_list.*
import kotlinx.android.synthetic.main.state_layout.*
import ru.fantlab.android.R
import ru.fantlab.android.data.dao.model.SearchAward
import ru.fantlab.android.helper.InputHelper
import ru.fantlab.android.provider.rest.loadmore.OnLoadMore
import ru.fantlab.android.ui.adapter.SearchAwardsAdapter
import ru.fantlab.android.ui.base.BaseFragment
import ru.fantlab.android.ui.modules.award.AwardPagerActivity
import ru.fantlab.android.ui.modules.search.SearchMvp
class SearchAwardsFragment : BaseFragment<SearchAwardsMvp.View, SearchAwardsPresenter>(),
SearchAwardsMvp.View {
@State var searchQuery = ""
private val onLoadMore: OnLoadMore<String> by lazy { OnLoadMore(presenter, searchQuery) }
private val adapter: SearchAwardsAdapter by lazy { SearchAwardsAdapter(arrayListOf()) }
private var countCallback: SearchMvp.View? = null
override fun onFragmentCreated(view: View, savedInstanceState: Bundle?) {
if (savedInstanceState == null) {
stateLayout.hideProgress()
}
stateLayout.setEmptyText(R.string.no_search_results)
getLoadMore().initialize(presenter.getCurrentPage() - 1, presenter.getPreviousTotal())
stateLayout.setOnReloadListener(this)
refresh.setOnRefreshListener(this)
recycler.setEmptyView(stateLayout, refresh)
adapter.listener = presenter
recycler.adapter = adapter
recycler.addKeyLineDivider()
recycler.addOnScrollListener(getLoadMore())
if (!InputHelper.isEmpty(searchQuery)) {
onRefresh()
}
if (InputHelper.isEmpty(searchQuery)) {
stateLayout.showEmptyState()
}
fastScroller.attachRecyclerView(recycler)
}
override fun onAttach(context: Context) {
super.onAttach(context)
if (context is SearchMvp.View) {
countCallback = context
}
}
override fun onDetach() {
countCallback = null
super.onDetach()
}
override fun onDestroyView() {
recycler.removeOnScrollListener(getLoadMore())
super.onDestroyView()
}
override fun providePresenter(): SearchAwardsPresenter = SearchAwardsPresenter()
override fun onNotifyAdapter(items: ArrayList<SearchAward>, page: Int) {
hideProgress()
if (items.isEmpty()) {
adapter.clear()
stateLayout.showEmptyState()
return
}
if (page <= 1) {
adapter.insertItems(items)
} else {
adapter.addItems(items)
}
}
override fun onSetTabCount(count: Int) {
countCallback?.onSetCount(count, 3)
}
override fun onSetSearchQuery(query: String) {
this.searchQuery = query
getLoadMore().reset()
adapter.clear()
if (!InputHelper.isEmpty(query)) {
recycler.removeOnScrollListener(getLoadMore())
recycler.addOnScrollListener(getLoadMore())
onRefresh()
}
}
override fun onQueueSearch(query: String) {
onSetSearchQuery(query)
}
override fun getLoadMore(): OnLoadMore<String> {
onLoadMore.parameter = searchQuery
return onLoadMore
}
override fun onItemClicked(item: SearchAward) {
val name = if (item.rusName.isNotEmpty()) {
if (item.name.isNotEmpty()) {
String.format("%s / %s", item.rusName, item.name)
} else {
item.name
}
} else {
item.name
}
AwardPagerActivity.startActivity(context!!, item.id, name, 0)
}
override fun fragmentLayout(): Int = R.layout.micro_grid_refresh_list
override fun onRefresh() {
if (searchQuery.isEmpty()) {
refresh.isRefreshing = false
return
}
presenter.onCallApi(1, searchQuery)
}
override fun onClick(v: View?) {
onRefresh()
}
override fun hideProgress() {
refresh.isRefreshing = false
stateLayout.hideProgress()
}
override fun showProgress(@StringRes resId: Int, cancelable: Boolean) {
refresh.isRefreshing = true
stateLayout.showProgress()
}
override fun showErrorMessage(msgRes: String?) {
callback?.showErrorMessage(msgRes)
}
override fun showMessage(titleRes: Int, msgRes: Int) {
showReload()
super.showMessage(titleRes, msgRes)
}
private fun showReload() {
hideProgress()
stateLayout.showReload(adapter.itemCount)
}
} | gpl-3.0 | debecd4f080c97b81f889009424d2ea9 | 25.643312 | 90 | 0.752511 | 3.781193 | false | false | false | false |
luanalbineli/popularmovies | app/src/main/java/com/themovielist/ui/movieimageview/MovieImageView.kt | 1 | 4386 | package com.themovielist.ui.movieimageview
import android.content.Context
import android.support.design.widget.Snackbar
import android.util.AttributeSet
import android.view.LayoutInflater
import android.widget.FrameLayout
import com.themovielist.PopularMovieApplication
import com.themovielist.R
import com.themovielist.event.FavoriteMovieEvent
import com.themovielist.injector.components.DaggerFragmentComponent
import com.themovielist.model.MovieModel
import com.themovielist.model.view.MovieImageViewModel
import com.themovielist.moviedetail.MovieDetailActivity
import com.themovielist.util.setDisplay
import kotlinx.android.synthetic.main.movie_image_view.view.*
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import timber.log.Timber
import javax.inject.Inject
class MovieImageView constructor(context: Context, attributeSet: AttributeSet) : FrameLayout(context, attributeSet), MovieImageViewContract.View {
@Inject
lateinit var mPresenter: MovieImageViewPresenter
private var mIsFavoritingManually = false
init {
injectDependencies()
/*
* For some F3cking unknown reason, I was unable to change the SimpleDraweeView width/height/aspectRatio on runtime, turning this component useless.
* I had to pass the layout by parameter (changing the width/height/aspectRatio of the SimpleDraweeView on the XML. Sad :/
* */
val simpleDraweeViewLayout = getSimpleDraweeView(attributeSet)
LayoutInflater.from(context).inflate(simpleDraweeViewLayout, this)
mfbMovieImageViewFavorite.setOnFavoriteChangeListener { _, _ ->
if (mIsFavoritingManually) {
return@setOnFavoriteChangeListener
}
mPresenter.toggleMovieFavorite()
}
sdvMovieImageView.setOnClickListener { mPresenter.showMovieDetail() }
}
private fun getSimpleDraweeView(attributeSet: AttributeSet): Int {
val typedArray = context.obtainStyledAttributes(attributeSet, R.styleable.MovieImageView)
val layoutResId = typedArray.getResourceId(R.styleable.MovieImageView_simpleDraweeView, R.layout.movie_image_view)
typedArray.recycle()
return layoutResId
}
private fun injectDependencies() {
val applicationComponent = PopularMovieApplication.getApplicationComponent(context)
DaggerFragmentComponent.builder()
.applicationComponent(applicationComponent)
.build()
.inject(this)
mPresenter.setView(this)
}
fun setImageURI(posterUrl: String?) {
sdvMovieImageView.setImageURI(posterUrl)
ivMovieItemEmptyImage.setDisplay(posterUrl == null)
}
fun setMovieImageViewModel(movieImageViewModel: MovieImageViewModel) {
mPresenter.setMovieImageViewModel(movieImageViewModel)
}
override fun openMovieDetail(movieModel: MovieModel) {
val intent = MovieDetailActivity.getDefaultIntent(context, movieModel)
context.startActivity(intent)
}
override fun onAttachedToWindow() {
super.onAttachedToWindow()
EventBus.getDefault().register(this)
}
override fun onDetachedFromWindow() {
super.onDetachedFromWindow()
EventBus.getDefault().unregister(this)
}
@Subscribe(threadMode = ThreadMode.MAIN)
fun onFavoriteMovieEvent(favoriteMovieEvent: FavoriteMovieEvent) {
mPresenter.onFavoriteMovieEvent(favoriteMovieEvent.movie, favoriteMovieEvent.favorite)
}
override fun toggleMovieFavorite(favourite: Boolean) {
mIsFavoritingManually = true
mfbMovieImageViewFavorite.isFavorite = favourite
mIsFavoritingManually = false
}
override fun showErrorFavoriteMovie(error: Throwable) {
Timber.e(error, "An error occurred while tried to favorite the movie: ${error.message}")
Snackbar.make(rootView, context.getString(R.string.error_add_favorite_movie), Snackbar.LENGTH_LONG)
}
override fun toggleMovieFavouriteEnabled(enabled: Boolean) {
mfbMovieImageViewFavorite.isEnabled = enabled
}
override fun showMovieInfo(movieImageViewModel: MovieImageViewModel) {
tvMovieImageViewName.text = movieImageViewModel.movieModel.title
toggleMovieFavorite(movieImageViewModel.isFavorite)
}
}
| apache-2.0 | f41d8bfbca0cb40dcd49fefa3323a6d0 | 35.857143 | 155 | 0.746238 | 5.21522 | false | false | false | false |
robfletcher/orca | orca-queue/src/main/kotlin/com/netflix/spinnaker/orca/q/handler/AbortStageHandler.kt | 4 | 2337 | /*
* Copyright 2017 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License")
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.spinnaker.orca.q.handler
import com.netflix.spinnaker.orca.api.pipeline.models.ExecutionStatus.NOT_STARTED
import com.netflix.spinnaker.orca.api.pipeline.models.ExecutionStatus.RUNNING
import com.netflix.spinnaker.orca.api.pipeline.models.ExecutionStatus.TERMINAL
import com.netflix.spinnaker.orca.events.StageComplete
import com.netflix.spinnaker.orca.ext.parent
import com.netflix.spinnaker.orca.pipeline.persistence.ExecutionRepository
import com.netflix.spinnaker.orca.q.AbortStage
import com.netflix.spinnaker.orca.q.CancelStage
import com.netflix.spinnaker.orca.q.CompleteExecution
import com.netflix.spinnaker.orca.q.CompleteStage
import com.netflix.spinnaker.q.Queue
import java.time.Clock
import org.springframework.beans.factory.annotation.Qualifier
import org.springframework.context.ApplicationEventPublisher
import org.springframework.stereotype.Component
@Component
class AbortStageHandler(
override val queue: Queue,
override val repository: ExecutionRepository,
@Qualifier("queueEventPublisher") private val publisher: ApplicationEventPublisher,
private val clock: Clock
) : OrcaMessageHandler<AbortStage> {
override fun handle(message: AbortStage) {
message.withStage { stage ->
if (stage.status in setOf(RUNNING, NOT_STARTED)) {
stage.status = TERMINAL
stage.endTime = clock.millis()
repository.storeStage(stage)
queue.push(CancelStage(message))
if (stage.parentStageId == null) {
queue.push(CompleteExecution(message))
} else {
queue.push(CompleteStage(stage.parent()))
}
publisher.publishEvent(StageComplete(this, stage))
}
}
}
override val messageType = AbortStage::class.java
}
| apache-2.0 | d632ec1028eb24fac0b5346df133dd9f | 37.311475 | 85 | 0.765511 | 4.288073 | false | false | false | false |
NerdNumber9/TachiyomiEH | app/src/main/java/exh/source/DelegatedHttpSource.kt | 1 | 8540 | package exh.source
import eu.kanade.tachiyomi.source.model.*
import eu.kanade.tachiyomi.source.online.HttpSource
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.Response
import rx.Observable
import java.lang.RuntimeException
abstract class DelegatedHttpSource(val delegate: HttpSource): HttpSource() {
/**
* Returns the request for the popular manga given the page.
*
* @param page the page number to retrieve.
*/
override fun popularMangaRequest(page: Int)
= throw UnsupportedOperationException("Should never be called!")
/**
* Parses the response from the site and returns a [MangasPage] object.
*
* @param response the response from the site.
*/
override fun popularMangaParse(response: Response)
= throw UnsupportedOperationException("Should never be called!")
/**
* Returns the request for the search manga given the page.
*
* @param page the page number to retrieve.
* @param query the search query.
* @param filters the list of filters to apply.
*/
override fun searchMangaRequest(page: Int, query: String, filters: FilterList)
= throw UnsupportedOperationException("Should never be called!")
/**
* Parses the response from the site and returns a [MangasPage] object.
*
* @param response the response from the site.
*/
override fun searchMangaParse(response: Response)
= throw UnsupportedOperationException("Should never be called!")
/**
* Returns the request for latest manga given the page.
*
* @param page the page number to retrieve.
*/
override fun latestUpdatesRequest(page: Int)
= throw UnsupportedOperationException("Should never be called!")
/**
* Parses the response from the site and returns a [MangasPage] object.
*
* @param response the response from the site.
*/
override fun latestUpdatesParse(response: Response)
= throw UnsupportedOperationException("Should never be called!")
/**
* Parses the response from the site and returns the details of a manga.
*
* @param response the response from the site.
*/
override fun mangaDetailsParse(response: Response)
= throw UnsupportedOperationException("Should never be called!")
/**
* Parses the response from the site and returns a list of chapters.
*
* @param response the response from the site.
*/
override fun chapterListParse(response: Response)
= throw UnsupportedOperationException("Should never be called!")
/**
* Parses the response from the site and returns a list of pages.
*
* @param response the response from the site.
*/
override fun pageListParse(response: Response)
= throw UnsupportedOperationException("Should never be called!")
/**
* Parses the response from the site and returns the absolute url to the source image.
*
* @param response the response from the site.
*/
override fun imageUrlParse(response: Response)
= throw UnsupportedOperationException("Should never be called!")
/**
* Base url of the website without the trailing slash, like: http://mysite.com
*/
override val baseUrl get() = delegate.baseUrl
/**
* Whether the source has support for latest updates.
*/
override val supportsLatest get() = delegate.supportsLatest
/**
* Name of the source.
*/
final override val name get() = delegate.name
// ===> OPTIONAL FIELDS
/**
* Id of the source. By default it uses a generated id using the first 16 characters (64 bits)
* of the MD5 of the string: sourcename/language/versionId
* Note the generated id sets the sign bit to 0.
*/
override val id get() = delegate.id
/**
* Default network client for doing requests.
*/
final override val client get() = delegate.client
/**
* You must NEVER call super.client if you override this!
*/
open val baseHttpClient: OkHttpClient? = null
open val networkHttpClient: OkHttpClient get() = network.client
open val networkCloudflareClient: OkHttpClient get() = network.cloudflareClient
/**
* Visible name of the source.
*/
override fun toString() = delegate.toString()
/**
* Returns an observable containing a page with a list of manga. Normally it's not needed to
* override this method.
*
* @param page the page number to retrieve.
*/
override fun fetchPopularManga(page: Int): Observable<MangasPage> {
ensureDelegateCompatible()
return delegate.fetchPopularManga(page)
}
/**
* Returns an observable containing a page with a list of manga. Normally it's not needed to
* override this method.
*
* @param page the page number to retrieve.
* @param query the search query.
* @param filters the list of filters to apply.
*/
override fun fetchSearchManga(page: Int, query: String, filters: FilterList): Observable<MangasPage> {
ensureDelegateCompatible()
return delegate.fetchSearchManga(page, query, filters)
}
/**
* Returns an observable containing a page with a list of latest manga updates.
*
* @param page the page number to retrieve.
*/
override fun fetchLatestUpdates(page: Int): Observable<MangasPage> {
ensureDelegateCompatible()
return delegate.fetchLatestUpdates(page)
}
/**
* Returns an observable with the updated details for a manga. Normally it's not needed to
* override this method.
*
* @param manga the manga to be updated.
*/
override fun fetchMangaDetails(manga: SManga): Observable<SManga> {
ensureDelegateCompatible()
return delegate.fetchMangaDetails(manga)
}
/**
* Returns the request for the details of a manga. Override only if it's needed to change the
* url, send different headers or request method like POST.
*
* @param manga the manga to be updated.
*/
override fun mangaDetailsRequest(manga: SManga): Request {
ensureDelegateCompatible()
return delegate.mangaDetailsRequest(manga)
}
/**
* Returns an observable with the updated chapter list for a manga. Normally it's not needed to
* override this method. If a manga is licensed an empty chapter list observable is returned
*
* @param manga the manga to look for chapters.
*/
override fun fetchChapterList(manga: SManga): Observable<List<SChapter>> {
ensureDelegateCompatible()
return delegate.fetchChapterList(manga)
}
/**
* Returns an observable with the page list for a chapter.
*
* @param chapter the chapter whose page list has to be fetched.
*/
override fun fetchPageList(chapter: SChapter): Observable<List<Page>> {
ensureDelegateCompatible()
return delegate.fetchPageList(chapter)
}
/**
* Returns an observable with the page containing the source url of the image. If there's any
* error, it will return null instead of throwing an exception.
*
* @param page the page whose source image has to be fetched.
*/
override fun fetchImageUrl(page: Page): Observable<String> {
ensureDelegateCompatible()
return delegate.fetchImageUrl(page)
}
/**
* Called before inserting a new chapter into database. Use it if you need to override chapter
* fields, like the title or the chapter number. Do not change anything to [manga].
*
* @param chapter the chapter to be added.
* @param manga the manga of the chapter.
*/
override fun prepareNewChapter(chapter: SChapter, manga: SManga) {
ensureDelegateCompatible()
return delegate.prepareNewChapter(chapter, manga)
}
/**
* Returns the list of filters for the source.
*/
override fun getFilterList() = delegate.getFilterList()
private fun ensureDelegateCompatible() {
if(versionId != delegate.versionId
|| lang != delegate.lang) {
throw IncompatibleDelegateException("Delegate source is not compatible (versionId: $versionId <=> ${delegate.versionId}, lang: $lang <=> ${delegate.lang})!")
}
}
class IncompatibleDelegateException(message: String) : RuntimeException(message)
init {
delegate.bindDelegate(this)
}
} | apache-2.0 | 077ae3ccf096d3dc897fed71a616c07d | 33.164 | 169 | 0.664637 | 5 | false | false | false | false |
google/filament | android/samples/sample-textured-object/src/main/java/com/google/android/filament/textured/MeshLoader.kt | 1 | 9523 | /*
* Copyright (C) 2018 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.filament.textured
import android.content.res.AssetManager
import android.util.Log
import com.google.android.filament.*
import com.google.android.filament.VertexBuffer.AttributeType.*
import com.google.android.filament.VertexBuffer.VertexAttribute.*
import java.io.InputStream
import java.nio.charset.Charset
import java.nio.ByteBuffer
import java.nio.ByteOrder
import java.nio.channels.Channels
import java.nio.channels.ReadableByteChannel
data class Mesh(
@Entity val renderable: Int,
val indexBuffer: IndexBuffer,
val vertexBuffer: VertexBuffer,
val aabb: Box)
fun destroyMesh(engine: Engine, mesh: Mesh) {
engine.destroyEntity(mesh.renderable)
engine.destroyIndexBuffer(mesh.indexBuffer)
engine.destroyVertexBuffer(mesh.vertexBuffer)
EntityManager.get().destroy(mesh.renderable)
}
fun loadMesh(assets: AssetManager, name: String,
materials: Map<String, MaterialInstance>, engine: Engine): Mesh {
// See tools/filamesh/README.md for a description of the filamesh file format
assets.open(name).use { input ->
val header = readHeader(input)
val channel = Channels.newChannel(input)
val vertexBufferData = readSizedData(channel, header.verticesSizeInBytes)
val indexBufferData = readSizedData(channel, header.indicesSizeInBytes)
val parts = readParts(header, input)
val definedMaterials = readMaterials(input)
val indexBuffer = createIndexBuffer(engine, header, indexBufferData)
val vertexBuffer = createVertexBuffer(engine, header, vertexBufferData)
val renderable = createRenderable(
engine, header, indexBuffer, vertexBuffer, parts, definedMaterials, materials)
return Mesh(renderable, indexBuffer, vertexBuffer, header.aabb)
}
}
private const val FILAMESH_FILE_IDENTIFIER = "FILAMESH"
private const val MAX_UINT32 = 4294967295
private const val HEADER_FLAG_INTERLEAVED = 0x1L
private const val HEADER_FLAG_SNORM16_UV = 0x2L
private const val HEADER_FLAG_COMPRESSED = 0x4L
private class Header {
var valid = false
var versionNumber = 0L
var parts = 0L
var aabb = Box()
var flags = 0L
var posOffset = 0L
var positionStride = 0L
var tangentOffset = 0L
var tangentStride = 0L
var colorOffset = 0L
var colorStride = 0L
var uv0Offset = 0L
var uv0Stride = 0L
var uv1Offset = 0L
var uv1Stride = 0L
var totalVertices = 0L
var verticesSizeInBytes = 0L
var indices16Bit = 0L
var totalIndices = 0L
var indicesSizeInBytes = 0L
}
private class Part {
var offset = 0L
var indexCount = 0L
var minIndex = 0L
var maxIndex = 0L
var materialID = 0L
var aabb = Box()
}
private fun readMagicNumber(input: InputStream): Boolean {
val temp = ByteArray(FILAMESH_FILE_IDENTIFIER.length)
input.read(temp)
val tempS = String(temp, Charset.forName("UTF-8"))
return tempS == FILAMESH_FILE_IDENTIFIER
}
private fun readHeader(input: InputStream): Header {
val header = Header()
if (!readMagicNumber(input)) {
Log.e("Filament", "Invalid filamesh file.")
return header
}
header.versionNumber = readUIntLE(input)
header.parts = readUIntLE(input)
header.aabb = Box(
readFloat32LE(input), readFloat32LE(input), readFloat32LE(input),
readFloat32LE(input), readFloat32LE(input), readFloat32LE(input))
header.flags = readUIntLE(input)
header.posOffset = readUIntLE(input)
header.positionStride = readUIntLE(input)
header.tangentOffset = readUIntLE(input)
header.tangentStride = readUIntLE(input)
header.colorOffset = readUIntLE(input)
header.colorStride = readUIntLE(input)
header.uv0Offset = readUIntLE(input)
header.uv0Stride = readUIntLE(input)
header.uv1Offset = readUIntLE(input)
header.uv1Stride = readUIntLE(input)
header.totalVertices = readUIntLE(input)
header.verticesSizeInBytes = readUIntLE(input)
header.indices16Bit = readUIntLE(input)
header.totalIndices = readUIntLE(input)
header.indicesSizeInBytes = readUIntLE(input)
header.valid = true
return header
}
private fun readSizedData(channel: ReadableByteChannel, sizeInBytes: Long): ByteBuffer {
val buffer = ByteBuffer.allocateDirect(sizeInBytes.toInt())
buffer.order(ByteOrder.LITTLE_ENDIAN)
channel.read(buffer)
buffer.flip()
return buffer
}
private fun readParts(header: Header, input: InputStream): List<Part> {
return List(header.parts.toInt()) {
val p = Part()
p.offset = readUIntLE(input)
p.indexCount = readUIntLE(input)
p.minIndex = readUIntLE(input)
p.maxIndex = readUIntLE(input)
p.materialID = readUIntLE(input)
p.aabb = Box(
readFloat32LE(input), readFloat32LE(input), readFloat32LE(input),
readFloat32LE(input), readFloat32LE(input), readFloat32LE(input))
p
}
}
private fun readMaterials(input: InputStream): List<String> {
return List(readUIntLE(input).toInt()) {
val data = ByteArray(readUIntLE(input).toInt())
input.read(data)
// Skip null terminator
input.skip(1)
data.toString(Charset.forName("UTF-8"))
}
}
private fun createIndexBuffer(engine: Engine, header: Header, data: ByteBuffer): IndexBuffer {
val indexType = if (header.indices16Bit != 0L) {
IndexBuffer.Builder.IndexType.USHORT
} else {
IndexBuffer.Builder.IndexType.UINT
}
return IndexBuffer.Builder()
.bufferType(indexType)
.indexCount(header.totalIndices.toInt())
.build(engine)
.apply { setBuffer(engine, data) }
}
private fun uvNormalized(header: Header) = header.flags and HEADER_FLAG_SNORM16_UV != 0L
private fun createVertexBuffer(engine: Engine, header: Header, data: ByteBuffer): VertexBuffer {
val uvType = if (!uvNormalized(header)) {
HALF2
} else {
SHORT2
}
val vertexBufferBuilder = VertexBuffer.Builder()
.bufferCount(1)
.vertexCount(header.totalVertices.toInt())
// We store colors as unsigned bytes (0..255) but the shader wants values in the 0..1
// range so we must mark this attribute normalized
.normalized(COLOR)
// The same goes for the tangent frame: we store it as a signed short, but we want
// values in 0..1 in the shader
.normalized(TANGENTS)
.attribute(POSITION, 0, HALF4, header.posOffset.toInt(), header.positionStride.toInt())
.attribute(TANGENTS, 0, SHORT4, header.tangentOffset.toInt(), header.tangentStride.toInt())
.attribute(COLOR, 0, UBYTE4, header.colorOffset.toInt(), header.colorStride.toInt())
// UV coordinates are stored as normalized 16-bit integers or half-floats depending on
// the range they span. When stored as half-float, there is only enough precision for
// sub-pixel addressing in textures that are <= 1024x1024
.attribute(UV0, 0, uvType, header.uv0Offset.toInt(), header.uv0Stride.toInt())
// When UV coordinates are stored as 16-bit integers we must normalize them (we want
// values in the range -1..1)
.normalized(UV0, uvNormalized(header))
if (header.uv1Offset != MAX_UINT32 && header.uv1Stride != MAX_UINT32) {
vertexBufferBuilder
.attribute(UV1, 0, uvType, header.uv1Offset.toInt(), header.uv1Stride.toInt())
.normalized(UV1, uvNormalized(header))
}
return vertexBufferBuilder.build(engine).apply { setBufferAt(engine, 0, data) }
}
private fun createRenderable(
engine: Engine,
header: Header,
indexBuffer: IndexBuffer,
vertexBuffer: VertexBuffer,
parts: List<Part>,
definedMaterials: List<String>,
materials: Map<String, MaterialInstance>): Int {
val builder = RenderableManager.Builder(header.parts.toInt()).boundingBox(header.aabb)
repeat(header.parts.toInt()) { i ->
builder.geometry(i,
RenderableManager.PrimitiveType.TRIANGLES,
vertexBuffer,
indexBuffer,
parts[i].offset.toInt(),
parts[i].minIndex.toInt(),
parts[i].maxIndex.toInt(),
parts[i].indexCount.toInt())
// Find a material in the supplied material map, otherwise we fall back to
// the default material named "DefaultMaterial"
val material = materials[definedMaterials[parts[i].materialID.toInt()]]
material?.let {
builder.material(i, material)
} ?: builder.material(i, materials["DefaultMaterial"]!!)
}
return EntityManager.get().create().apply { builder.build(engine, this) }
}
| apache-2.0 | d1015aefeb4cba76dbac7acee71947d2 | 35.07197 | 103 | 0.677518 | 4.211853 | false | false | false | false |
square/wire | wire-library/wire-grpc-server-generator/src/test/golden/ServiceDescriptor.kt | 1 | 3094 | package routeguide
import com.google.protobuf.DescriptorProtos
import com.google.protobuf.Descriptors
import io.grpc.ServiceDescriptor
import io.grpc.ServiceDescriptor.newBuilder
import kotlin.Array
import kotlin.String
import kotlin.collections.Map
import kotlin.collections.Set
import kotlin.jvm.Volatile
public class RouteGuideWireGrpc {
public val SERVICE_NAME: String = "routeguide.RouteGuide"
@Volatile
private var serviceDescriptor: ServiceDescriptor? = null
private val descriptorMap: Map<String, DescriptorProtos.FileDescriptorProto> = mapOf(
"src/test/proto/RouteGuideProto.proto" to descriptorFor(arrayOf(
"CiRzcmMvdGVzdC9wcm90by9Sb3V0ZUd1aWRlUHJvdG8ucHJvdG8SCnJvdXRlZ3VpZGUiLAoFUG9pbnQS",
"EAoIbGF0aXR1ZGUYASABKAUSEQoJbG9uZ2l0dWRlGAIgASgFIkkKCVJlY3RhbmdsZRIdCgJsbxgBIAEo",
"CzIRLnJvdXRlZ3VpZGUuUG9pbnQSHQoCaGkYAiABKAsyES5yb3V0ZWd1aWRlLlBvaW50IjwKB0ZlYXR1",
"cmUSDAoEbmFtZRgBIAEoCRIjCghsb2NhdGlvbhgCIAEoCzIRLnJvdXRlZ3VpZGUuUG9pbnQiNwoPRmVh",
"dHVyZURhdGFiYXNlEiQKB2ZlYXR1cmUYASADKAsyEy5yb3V0ZWd1aWRlLkZlYXR1cmUiQQoJUm91dGVO",
"b3RlEiMKCGxvY2F0aW9uGAEgASgLMhEucm91dGVndWlkZS5Qb2ludBIPCgdtZXNzYWdlGAIgASgJImIK",
"DFJvdXRlU3VtbWFyeRITCgtwb2ludF9jb3VudBgBIAEoBRIVCg1mZWF0dXJlX2NvdW50GAIgASgFEhAK",
"CGRpc3RhbmNlGAMgASgFEhQKDGVsYXBzZWRfdGltZRgEIAEoBTL9AQoKUm91dGVHdWlkZRI0CgpHZXRG",
"ZWF0dXJlEhEucm91dGVndWlkZS5Qb2ludBoTLnJvdXRlZ3VpZGUuRmVhdHVyZRI8CgxMaXN0RmVhdHVy",
"ZXMSFS5yb3V0ZWd1aWRlLlJlY3RhbmdsZRoTLnJvdXRlZ3VpZGUuRmVhdHVyZTABEjwKC1JlY29yZFJv",
"dXRlEhEucm91dGVndWlkZS5Qb2ludBoYLnJvdXRlZ3VpZGUuUm91dGVTdW1tYXJ5KAESPQoJUm91dGVD",
"aGF0EhUucm91dGVndWlkZS5Sb3V0ZU5vdGUaFS5yb3V0ZWd1aWRlLlJvdXRlTm90ZSgBMAE=",
)),
)
private fun descriptorFor(`data`: Array<String>): DescriptorProtos.FileDescriptorProto {
val str = data.fold(java.lang.StringBuilder()) { b, s -> b.append(s) }.toString()
val bytes = java.util.Base64.getDecoder().decode(str)
return DescriptorProtos.FileDescriptorProto.parseFrom(bytes)
}
private fun fileDescriptor(path: String, visited: Set<String>): Descriptors.FileDescriptor {
val proto = descriptorMap[path]!!
val deps = proto.dependencyList.filter { !visited.contains(it) }.map { fileDescriptor(it,
visited + path) }
return Descriptors.FileDescriptor.buildFrom(proto, deps.toTypedArray())
}
public fun getServiceDescriptor(): ServiceDescriptor? {
var result = serviceDescriptor
if (result == null) {
synchronized(RouteGuideWireGrpc::class) {
result = serviceDescriptor
if (result == null) {
result = newBuilder(SERVICE_NAME)
.addMethod(getGetFeatureMethod())
.addMethod(getListFeaturesMethod())
.addMethod(getRecordRouteMethod())
.addMethod(getRouteChatMethod())
.setSchemaDescriptor(io.grpc.protobuf.ProtoFileDescriptorSupplier {
fileDescriptor("src/test/proto/RouteGuideProto.proto", emptySet())
})
.build()
serviceDescriptor = result
}
}
}
return result
}
}
| apache-2.0 | fc24277693538db7cb188e36c0c43a9e | 42.577465 | 94 | 0.771493 | 3.122099 | false | false | false | false |
xiprox/Tensuu | app/src/main/java/tr/xip/scd/tensuu/ui/common/adapter/PointsAdapter.kt | 1 | 5125 | package tr.xip.scd.tensuu.ui.common.adapter
import android.annotation.SuppressLint
import android.support.v7.widget.PopupMenu
import android.support.v7.widget.RecyclerView
import android.view.Gravity
import android.view.View
import android.view.View.GONE
import android.view.View.VISIBLE
import android.view.ViewGroup
import android.view.animation.DecelerateInterpolator
import io.realm.OrderedRealmCollection
import io.realm.RealmRecyclerViewAdapter
import kotlinx.android.synthetic.main.item_point.view.*
import tr.xip.scd.tensuu.App.Companion.context
import tr.xip.scd.tensuu.R
import tr.xip.scd.tensuu.realm.model.Point
import tr.xip.scd.tensuu.local.Credentials
import tr.xip.scd.tensuu.ui.student.StudentActivity
import tr.xip.scd.tensuu.realm.util.RealmUtils.syncedRealm
import tr.xip.scd.tensuu.common.ext.getLayoutInflater
import tr.xip.scd.tensuu.common.ext.isToday
import tr.xip.scd.tensuu.common.ext.isYesterday
import java.text.SimpleDateFormat
class PointsAdapter(data: OrderedRealmCollection<Point>) : RealmRecyclerViewAdapter<Point, PointsAdapter.ViewHolder>(data, true) {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val v = parent.context.getLayoutInflater().inflate(R.layout.item_point, parent, false)
return ViewHolder(v)
}
@SuppressLint("SimpleDateFormat")
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val item = data?.get(position) ?: return
/* 60% alpha if my point and older than a week */
val now = System.currentTimeMillis()
val weekInMillis: Long = 7 * 24 * 60 * 60 * 1000
val olderThanWeek = item.from?.email == Credentials.email &&
(now - (item.timestamp ?: 0)) > weekInMillis
holder.itemView.alpha = if (olderThanWeek) 0.6f else 1f
/* Amount */
holder.itemView.amount.text = "${item.amount ?: ""}"
if ((item.amount ?: 0) < 0) {
holder.itemView.amount.setBackgroundResource(R.drawable.oval_minus)
} else {
holder.itemView.amount.setBackgroundResource(R.drawable.oval_plus)
}
/* To */
holder.itemView.to.text = item.to?.fullName ?: "?"
/* From */
holder.itemView.from.text = item.from?.name ?: "?"
/* Time */
val timestamp = item.timestamp ?: 0
var timeText: String? = null
if (timestamp != 0.toLong()) {
if (timestamp.isToday()) {
timeText = context.getString(R.string.today)
} else if (timestamp.isYesterday()) {
timeText = context.getString(R.string.yesterday)
} else {
timeText = SimpleDateFormat("MMM d, yyyy").format(timestamp)
}
}
if (timeText != null) {
holder.itemView.time.text = timeText
holder.itemView.time.visibility = VISIBLE
} else {
holder.itemView.time.visibility = GONE
}
/* Reason */
if (item.reason != null) {
holder.itemView.reason.text = item.reason
holder.itemView.root.setOnClickListener(reasonClickListener)
holder.itemView.expandIndicator.visibility = VISIBLE
} else {
holder.itemView.root.setOnClickListener(null)
holder.itemView.expandIndicator.visibility = GONE
}
/*
* Options
*/
val menu = PopupMenu(holder.itemView.context, holder.itemView.more, Gravity.BOTTOM)
menu.menuInflater.inflate(R.menu.point, menu.menu)
/*
* - Owners SHOULD be able to edit IF they (still) have modification rights
* - Admins SHOULD be able to edit no matter what
*/
val canEdit =
(item.from?.email == Credentials.email && Credentials.canModify)
|| Credentials.isAdmin
val deleteItem = menu.menu.findItem(R.id.delete)
deleteItem.isVisible = canEdit
deleteItem.isEnabled = canEdit
menu.setOnMenuItemClickListener {
when (it.itemId) {
R.id.go_to_student -> {
StudentActivity.start(context, item.to?.ssid)
}
R.id.delete -> {
syncedRealm().use {
it.executeTransaction {
item.deleteFromRealm()
}
}
}
}
true
}
holder.itemView.more.setOnClickListener {
menu.show()
}
}
class ViewHolder(v: View) : RecyclerView.ViewHolder(v)
private object reasonClickListener : View.OnClickListener {
override fun onClick(v: View) {
val expand = v.reasonContainer.visibility == GONE
v.reasonContainer.visibility = if (expand) VISIBLE else GONE
v.expandIndicator.animate()
.rotation(if (expand) 180f else 0f)
.setInterpolator(DecelerateInterpolator())
.setDuration(200)
.start()
}
}
} | gpl-3.0 | b213e247ca09f0dccd68e51d68e0a915 | 36.144928 | 130 | 0.610732 | 4.55151 | false | false | false | false |
xiprox/Tensuu | app/src/main/java/tr/xip/scd/tensuu/ui/lists/add/ListAddPresenter.kt | 1 | 3655 | package tr.xip.scd.tensuu.ui.lists.add
import android.text.Editable
import io.realm.Case
import tr.xip.scd.tensuu.local.Credentials
import tr.xip.scd.tensuu.realm.model.*
import tr.xip.scd.tensuu.common.ui.mvp.RealmPresenter
import tr.xip.scd.tensuu.ui.lists.StudentsAddingAdapter
import tr.xip.scd.tensuu.ui.mypoints.StudentsAutoCompleteAdapter
class ListAddPresenter : RealmPresenter<ListAddView>() {
private var list = StudentList()
private var isEditMode = false
fun init() {
setAdapter()
view?.setAutoCompleteAdapter(
StudentsAutoCompleteAdapter(realm, realm.where(Student::class.java).findAll())
)
}
fun loadList(listName: String) {
isEditMode = true
realm.where(StudentList::class.java).equalTo(StudentListFields.NAME, listName).findFirst()?.let {
list = it
setAdapter()
view?.showExitButton(false)
view?.setName(list.name ?: "")
view?.setPrivate(!list.public)
}
}
private fun setAdapter() {
view?.setAdapter(StudentsAddingAdapter(list.students,
removeClickedListener = {
onStudentRemoveClicked(it)
}
))
}
fun onNameChanged(name: String) {
view?.runOnUi {
realm.executeTransaction {
list.name = if (name.isBlank()) null else name
}
}
}
fun onPrivateChanged(private: Boolean) {
view?.runOnUi {
realm.executeTransaction {
list.public = !private
}
}
}
fun onDoneClicked() {
if (!isEditMode) {
realm.executeTransaction {
// Append a number to the name if a list with the same name already exists
val existing = realm.where(StudentList::class.java).equalTo(StudentListFields.NAME, list.name).findAll()
if (existing.size != 0) list.name = "${list.name} ${existing.size + 1}"
list.owner = it.where(User::class.java)
.equalTo(UserFields.EMAIL, Credentials.email).findFirst()
it.copyToRealm(list)
}
}
view?.die()
}
fun onNewStudentSelected(student: Student) {
if (!list.students.contains(student)) {
view?.runOnUi {
realm.executeTransaction {
list.students.add(student)
}
}
view?.getAdapter()?.notifyItemInserted(list.students.indexOf(student))
}
}
private fun onStudentRemoveClicked(position: Int) {
val adapter = view?.getAdapter() ?: return
val lastIndex = adapter.itemCount - 1
realm.executeTransaction {
adapter.data?.removeAt(position)
}
adapter.notifyItemRemoved(position)
adapter.notifyItemRangeChanged(position, lastIndex)
}
fun onSearchTextChangedInstant(s: Editable?) {
view?.setSearchClearVisible(s?.toString()?.isNotEmpty() ?: false)
}
fun onSearchTextChanged(s: Editable?) {
val q = s?.toString() ?: return
view?.runOnUi {
view?.getAutoCompleteAdapter()?.updateData(
realm.where(Student::class.java)
.beginGroup()
.contains(StudentFields.FULL_NAME, q, Case.INSENSITIVE)
.or()
.contains(StudentFields.FULL_NAME_SIMPLIFIED, q, Case.INSENSITIVE)
.endGroup()
.findAll()
)
}
}
} | gpl-3.0 | b35f7c8180bac936bc7a4fb131c21042 | 30.517241 | 120 | 0.564706 | 4.746753 | false | false | false | false |
k9mail/k-9 | app/k9mail/src/main/java/com/fsck/k9/widget/unread/UnreadWidgetConfigurationFragment.kt | 1 | 9100 | package com.fsck.k9.widget.unread
import android.app.Activity
import android.appwidget.AppWidgetManager
import android.content.Intent
import android.os.Bundle
import android.view.Menu
import android.view.MenuInflater
import android.view.MenuItem
import android.widget.Toast
import androidx.core.os.bundleOf
import androidx.preference.CheckBoxPreference
import androidx.preference.Preference
import com.fsck.k9.Preferences
import com.fsck.k9.R
import com.fsck.k9.activity.ChooseAccount
import com.fsck.k9.search.SearchAccount
import com.fsck.k9.ui.choosefolder.ChooseFolderActivity
import com.takisoft.preferencex.PreferenceFragmentCompat
import org.koin.android.ext.android.inject
class UnreadWidgetConfigurationFragment : PreferenceFragmentCompat() {
private val preferences: Preferences by inject()
private val repository: UnreadWidgetRepository by inject()
private val unreadWidgetUpdater: UnreadWidgetUpdater by inject()
private var appWidgetId: Int = AppWidgetManager.INVALID_APPWIDGET_ID
private lateinit var unreadAccount: Preference
private lateinit var unreadFolderEnabled: CheckBoxPreference
private lateinit var unreadFolder: Preference
private var selectedAccountUuid: String? = null
private var selectedFolderId: Long? = null
private var selectedFolderDisplayName: String? = null
override fun onCreatePreferencesFix(savedInstanceState: Bundle?, rootKey: String?) {
setHasOptionsMenu(true)
setPreferencesFromResource(R.xml.unread_widget_configuration, rootKey)
appWidgetId = arguments?.getInt(ARGUMENT_APP_WIDGET_ID) ?: error("Missing argument '$ARGUMENT_APP_WIDGET_ID'")
unreadAccount = findPreference(PREFERENCE_UNREAD_ACCOUNT)!!
unreadAccount.onPreferenceClickListener = Preference.OnPreferenceClickListener {
val intent = Intent(requireContext(), ChooseAccount::class.java)
startActivityForResult(intent, REQUEST_CHOOSE_ACCOUNT)
false
}
unreadFolderEnabled = findPreference(PREFERENCE_UNREAD_FOLDER_ENABLED)!!
unreadFolderEnabled.onPreferenceChangeListener = Preference.OnPreferenceChangeListener { _, _ ->
unreadFolder.summary = getString(R.string.unread_widget_folder_summary)
selectedFolderId = null
selectedFolderDisplayName = null
true
}
unreadFolder = findPreference(PREFERENCE_UNREAD_FOLDER)!!
unreadFolder.onPreferenceClickListener = Preference.OnPreferenceClickListener {
val intent = ChooseFolderActivity.buildLaunchIntent(
context = requireContext(),
action = ChooseFolderActivity.Action.CHOOSE,
accountUuid = selectedAccountUuid!!,
showDisplayableOnly = true
)
startActivityForResult(intent, REQUEST_CHOOSE_FOLDER)
false
}
if (savedInstanceState != null) {
restoreInstanceState(savedInstanceState)
}
}
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
outState.putString(STATE_SELECTED_ACCOUNT_UUID, selectedAccountUuid)
outState.putLongIfPresent(STATE_SELECTED_FOLDER_ID, selectedFolderId)
outState.putString(STATE_SELECTED_FOLDER_DISPLAY_NAME, selectedFolderDisplayName)
}
private fun restoreInstanceState(savedInstanceState: Bundle) {
val accountUuid = savedInstanceState.getString(STATE_SELECTED_ACCOUNT_UUID)
if (accountUuid != null) {
handleChooseAccount(accountUuid)
val folderId = savedInstanceState.getLongOrNull(STATE_SELECTED_FOLDER_ID)
val folderSummary = savedInstanceState.getString(STATE_SELECTED_FOLDER_DISPLAY_NAME)
if (folderId != null && folderSummary != null) {
handleChooseFolder(folderId, folderSummary)
}
}
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
if (resultCode == Activity.RESULT_OK && data != null) {
when (requestCode) {
REQUEST_CHOOSE_ACCOUNT -> {
val accountUuid = data.getStringExtra(ChooseAccount.EXTRA_ACCOUNT_UUID)!!
handleChooseAccount(accountUuid)
}
REQUEST_CHOOSE_FOLDER -> {
val folderId = data.getLongExtra(ChooseFolderActivity.RESULT_SELECTED_FOLDER_ID, -1L)
val folderDisplayName = data.getStringExtra(ChooseFolderActivity.RESULT_FOLDER_DISPLAY_NAME)!!
handleChooseFolder(folderId, folderDisplayName)
}
}
}
super.onActivityResult(requestCode, resultCode, data)
}
private fun handleChooseAccount(accountUuid: String) {
val userSelectedSameAccount = accountUuid == selectedAccountUuid
if (userSelectedSameAccount) {
return
}
selectedAccountUuid = accountUuid
selectedFolderId = null
selectedFolderDisplayName = null
unreadFolder.summary = getString(R.string.unread_widget_folder_summary)
if (SearchAccount.UNIFIED_INBOX == selectedAccountUuid) {
handleSearchAccount()
} else {
handleRegularAccount()
}
}
private fun handleSearchAccount() {
if (SearchAccount.UNIFIED_INBOX == selectedAccountUuid) {
unreadAccount.setSummary(R.string.unread_widget_unified_inbox_account_summary)
}
unreadFolderEnabled.isEnabled = false
unreadFolderEnabled.isChecked = false
unreadFolder.isEnabled = false
selectedFolderId = null
selectedFolderDisplayName = null
}
private fun handleRegularAccount() {
val selectedAccount = preferences.getAccount(selectedAccountUuid!!)
?: error("Account $selectedAccountUuid not found")
unreadAccount.summary = selectedAccount.displayName
unreadFolderEnabled.isEnabled = true
unreadFolder.isEnabled = true
}
private fun handleChooseFolder(folderId: Long, folderDisplayName: String) {
selectedFolderId = folderId
selectedFolderDisplayName = folderDisplayName
unreadFolder.summary = folderDisplayName
}
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
inflater.inflate(R.menu.unread_widget_option, menu)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
return when (item.itemId) {
R.id.done -> {
if (validateWidget()) {
updateWidgetAndExit()
}
true
}
else -> super.onOptionsItemSelected(item)
}
}
private fun validateWidget(): Boolean {
if (selectedAccountUuid == null) {
Toast.makeText(requireContext(), R.string.unread_widget_account_not_selected, Toast.LENGTH_LONG).show()
return false
} else if (unreadFolderEnabled.isChecked && selectedFolderId == null) {
Toast.makeText(requireContext(), R.string.unread_widget_folder_not_selected, Toast.LENGTH_LONG).show()
return false
}
return true
}
private fun updateWidgetAndExit() {
val configuration = UnreadWidgetConfiguration(appWidgetId, selectedAccountUuid!!, selectedFolderId)
repository.saveWidgetConfiguration(configuration)
unreadWidgetUpdater.update(appWidgetId)
// Let the caller know that the configuration was successful
val resultValue = Intent()
resultValue.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId)
val activity = requireActivity()
activity.setResult(Activity.RESULT_OK, resultValue)
activity.finish()
}
private fun Bundle.putLongIfPresent(key: String, value: Long?) {
if (value != null) {
putLong(key, value)
}
}
private fun Bundle.getLongOrNull(key: String): Long? {
return if (containsKey(key)) getLong(key) else null
}
companion object {
private const val ARGUMENT_APP_WIDGET_ID = "app_widget_id"
private const val PREFERENCE_UNREAD_ACCOUNT = "unread_account"
private const val PREFERENCE_UNREAD_FOLDER_ENABLED = "unread_folder_enabled"
private const val PREFERENCE_UNREAD_FOLDER = "unread_folder"
private const val REQUEST_CHOOSE_ACCOUNT = 1
private const val REQUEST_CHOOSE_FOLDER = 2
private const val STATE_SELECTED_ACCOUNT_UUID = "com.fsck.k9.widget.unread.selectedAccountUuid"
private const val STATE_SELECTED_FOLDER_ID = "com.fsck.k9.widget.unread.selectedFolderId"
private const val STATE_SELECTED_FOLDER_DISPLAY_NAME = "com.fsck.k9.widget.unread.selectedFolderDisplayName"
fun create(appWidgetId: Int): UnreadWidgetConfigurationFragment {
return UnreadWidgetConfigurationFragment().apply {
arguments = bundleOf(ARGUMENT_APP_WIDGET_ID to appWidgetId)
}
}
}
}
| apache-2.0 | 518ed5c56ba3e938536dbd8309188a49 | 39.444444 | 118 | 0.681648 | 5.390995 | false | false | false | false |
livefront/bridge | bridgesample/src/main/java/com/livefront/bridgesample/common/view/BitmapGeneratorView.kt | 1 | 2907 | package com.livefront.bridgesample.common.view
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.graphics.Bitmap
import android.util.AttributeSet
import android.widget.RelativeLayout
import androidx.annotation.StringRes
import com.livefront.bridgesample.R
import com.livefront.bridgesample.scenario.activity.SuccessActivity
import com.livefront.bridgesample.util.generateNoisyStripedBitmap
import kotlinx.android.synthetic.main.view_bitmap_generator_content.view.generateDataButton
import kotlinx.android.synthetic.main.view_bitmap_generator_content.view.headerText
import kotlinx.android.synthetic.main.view_bitmap_generator_content.view.imageView
import kotlinx.android.synthetic.main.view_bitmap_generator_content.view.navigateButton
import kotlinx.android.synthetic.main.view_bitmap_generator_content.view.statusText
/**
* A view that generates a [Bitmap] when clicking on a button. This `Bitmap` can then be retrieved
* as the [generatedBitmap] in order to test saving / restoring it. The
* [onNavigateButtonClickListener] may be set to provide some action when the corresponding button
* is clicked. If no such listener is set, the default behavior is to navigate to the
* [SuccessActivity].
*/
class BitmapGeneratorView @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
defStyleAttr: Int = 0,
defStyleRes: Int = 0
) : RelativeLayout(context, attrs, defStyleAttr, defStyleRes) {
var generatedBitmap: Bitmap? = null
/**
* Sets the [Bitmap] to display in this view. This will be considered as "restored" from a
* saved state.
*/
set(value) {
field = value
value?.let {
imageView.setImageBitmap(it)
statusText.setText(R.string.restored_from_saved_state)
}
}
var onBitmapGeneratedListener: ((Bitmap) -> Unit)? = null
var onNavigateButtonClickListener: (() -> Unit)? = null
init {
inflate(context, R.layout.view_bitmap_generator_content, this)
navigateButton.setOnClickListener {
onNavigateButtonClickListener
?.invoke()
?: (context as Activity).startActivity(
Intent(context, SuccessActivity::class.java)
)
}
generateDataButton.setOnClickListener {
generateDataButton.isEnabled = false
generateNoisyStripedBitmap { bitmap ->
generatedBitmap = bitmap
generateDataButton.isEnabled = true
imageView.setImageBitmap(bitmap)
statusText.setText(R.string.image_generated)
onBitmapGeneratedListener?.invoke(bitmap)
}
}
}
fun setHeaderText(@StringRes textRes: Int) {
headerText.setText(textRes)
}
}
| apache-2.0 | eaaa3cd42e1e5ef74320959d852b9469 | 39.375 | 98 | 0.690402 | 4.804959 | false | false | false | false |
just-4-fun/holomorph | src/main/kotlin/just4fun/holomorph/forms/sequence.kt | 1 | 4588 | package just4fun.holomorph.forms
import just4fun.holomorph.*
import just4fun.holomorph.types.*
import just4fun.holomorph.types.*
/* RAW ARRAY factory */
/** The factory for Array<Any?> serialization form. */
object ArrayFactory: ProduceFactory<Array<*>, Array<*>> {
@Suppress("UNCHECKED_CAST")
val seqType = ArrayType(AnyType, Array<Any>::class) as SequenceType<Array<*>, Any>
override fun invoke(input: Array<*>): EntryProvider<Array<*>> = SequenceProvider(input, seqType)
override fun invoke(): EntryConsumer<Array<*>> = SequenceConsumer(seqType)
}
/* SEQUENCE */
/* Provider */
class SequenceProvider<T: Any, E: Any>(override val input: T, private val seqType: SequenceType<T, E>, private var initial: Boolean = true): EntryProvider<T> {
private val iterator = seqType.iterator(input)
override fun provideNextEntry(entryBuilder: EntryBuilder, provideName: Boolean): Entry {
return if (initial) run { initial = false; entryBuilder.StartEntry(null, false) }
else if (!iterator.hasNext()) entryBuilder.EndEntry()
else {
val v = iterator.next()
seqType.elementType.toEntry(v, null, entryBuilder)
}
}
}
/* Consumer */
class SequenceConsumer<T: Any, E: Any>(private val seqType: SequenceType<T, E>, private var initial: Boolean = true): EntryConsumer<T> {
private var instance: T = seqType.newInstance()
private var size = 0
override fun output(): T = seqType.onComplete(instance, size)
private fun addElement(value: Any?) {
val v = seqType.elementType.asInstance(value, true)
instance = seqType.addElement(v, size, instance)
size++
}
override fun consumeEntries(name: String?, subEntries: EnclosedEntries, expectNames: Boolean) {
if (initial) run { initial = false; subEntries.consume(); return }
addElement(seqType.elementType.fromEntries(subEntries, expectNames))
}
override fun consumeEntry(name: String?, value: ByteArray): Unit = addElement(value)
override fun consumeEntry(name: String?, value: String): Unit = addElement(value)
override fun consumeEntry(name: String?, value: Long): Unit = addElement(value)
override fun consumeEntry(name: String?, value: Int): Unit = addElement(value)
override fun consumeEntry(name: String?, value: Double): Unit = addElement(value)
override fun consumeEntry(name: String?, value: Float): Unit = addElement(value)
override fun consumeEntry(name: String?, value: Boolean): Unit = addElement(value)
override fun consumeNullEntry(name: String?): Unit = addElement(null)
}
/* RAW COLLECTION */
/* Provider */
class RawCollectionProvider(override val input: Collection<Any?>, private var initial: Boolean = true): EntryProvider<Collection<Any?>> {
private val iterator = input.iterator()
override fun provideNextEntry(entryBuilder: EntryBuilder, provideName: Boolean): Entry {
return if (initial) run { initial = false; entryBuilder.StartEntry(null, false) }
else if (!iterator.hasNext()) entryBuilder.EndEntry()
else {
val v = iterator.next()
if (v == null) entryBuilder.NullEntry()
else {
val type = AnyType.detectType(v)
if (type == null) StringType.toEntry(v.toString(), null, entryBuilder)
else type.toEntry(v, null, entryBuilder)
}
}
}
}
/* Consumer */
// todo typeUtils detect type?
class RawCollectionConsumer(private var initial: Boolean = true): EntryConsumer<Collection<Any?>> {
var instance: Collection<Any?> = RawCollectionType.newInstance()
override fun output(): Collection<Any?> {
return RawCollectionType.onComplete(instance, instance.size)
}
override fun consumeEntries(name: String?, subEntries: EnclosedEntries, expectNames: Boolean) {
if (initial) run { initial = false; subEntries.consume(); return }
val v = subEntries.intercept(if (expectNames) RawMapConsumer(false) else RawCollectionConsumer(false))
addElement(v)
}
private fun addElement(value: Any?) {
instance = RawCollectionType.addElement(value, instance.size, instance)
}
override fun consumeEntry(name: String?, value: ByteArray): Unit = addElement(value)
override fun consumeEntry(name: String?, value: String): Unit = addElement(value)
override fun consumeEntry(name: String?, value: Long): Unit = addElement(value)
override fun consumeEntry(name: String?, value: Int): Unit = addElement(value)
override fun consumeEntry(name: String?, value: Double): Unit = addElement(value)
override fun consumeEntry(name: String?, value: Float): Unit = addElement(value)
override fun consumeEntry(name: String?, value: Boolean): Unit = addElement(value)
override fun consumeNullEntry(name: String?): Unit = addElement(null)
}
| apache-2.0 | 26347ea3dc4883eb78e092cd6e7b9b61 | 35.704 | 159 | 0.735179 | 3.875 | false | false | false | false |
Tiofx/semester_6 | TRPSV/src/main/kotlin/task1/RootProcess.kt | 1 | 998 | package task1
import mpi.MPI
open class RootProcess(val hyperCubeSize: Int, var array: IntArray) {
val p = (2 pow hyperCubeSize).toInt()
private var n = array.size
val elementsOPerProcess = n / p
fun beginProcess() {
sendOutArray()
// collectArray()
}
fun resetArray() {
shuffle(array)
}
fun sendOutArray() {
for (i in 0..p - 1) {
MPI.COMM_WORLD.Isend(array, elementsOPerProcess * (i), elementsOPerProcess,
MPI.INT, i, Operation.INIT_ARRAY_SEND.ordinal)
}
}
fun collectArray() {
var offset = 0
for (i in 0..p - 1) {
val probeStatus = MPI.COMM_WORLD.Probe(i, Operation.COLLECT_ARRAY.ordinal)
var receiveElementNumber = probeStatus.Get_count(MPI.INT)
MPI.COMM_WORLD.Recv(array, offset, n - offset,
MPI.INT, i, Operation.COLLECT_ARRAY.ordinal)
offset += receiveElementNumber
}
}
} | gpl-3.0 | f1a4d77544ee1114723a46ebf46d711a | 23.975 | 87 | 0.572144 | 3.737828 | false | false | false | false |
ligi/PassAndroid | android/src/main/java/org/ligi/passandroid/ui/pass_view_holder/CondensedPassViewHolder.kt | 1 | 881 | package org.ligi.passandroid.ui.pass_view_holder
import android.app.Activity
import androidx.cardview.widget.CardView
import android.view.View
import kotlinx.android.synthetic.main.pass_list_item.view.*
import kotlinx.android.synthetic.main.time_and_nav.view.*
import org.ligi.passandroid.model.PassStore
import org.ligi.passandroid.model.pass.Pass
class CondensedPassViewHolder(view: CardView) : PassViewHolder(view) {
override fun apply(pass: Pass, passStore: PassStore, activity: Activity) {
super.apply(pass, passStore, activity)
val extraString = getExtraString(pass)
if (extraString.isNullOrBlank()) {
view.date.visibility = View.GONE
} else {
view.date.text = extraString
view.date.visibility = View.VISIBLE
}
view.timeAndNavBar.timeButton.text = getTimeInfoString(pass)
}
}
| gpl-3.0 | e1dd4003e6be39b1ce77d72a1addc50e | 30.464286 | 78 | 0.717367 | 3.933036 | false | false | false | false |
wordpress-mobile/WordPress-Android | WordPress/src/main/java/org/wordpress/android/ui/compose/theme/JetpackColors.kt | 1 | 1594 | package org.wordpress.android.ui.compose.theme
import android.annotation.SuppressLint
import androidx.compose.foundation.isSystemInDarkTheme
import androidx.compose.material.darkColors
import androidx.compose.material.lightColors
import androidx.compose.runtime.Composable
import androidx.compose.ui.graphics.Color
private val green40 = Color(0xff069e08)
private val green50 = Color(0xff008710)
private val red50 = Color(0xffd63638)
private val red30 = Color(0xfff86368)
private val white = Color(0xffffffff)
private val black = Color(0xff000000)
private val darkGray = Color(0xff121212)
@SuppressLint("ConflictingOnColor")
val JpLightColorPalette = lightColors(
primary = green50,
primaryVariant = green40,
secondary = green50,
secondaryVariant = green40,
background = white,
surface = white,
error = red50,
onPrimary = white,
onSecondary = white,
onBackground = black,
onSurface = black,
onError = white
)
@SuppressLint("ConflictingOnColor")
val JpDarkColorPalette = darkColors(
primary = green40,
primaryVariant = green50,
secondary = green40,
secondaryVariant = green50,
background = darkGray,
surface = darkGray,
error = red30,
onPrimary = black,
onSecondary = white,
onBackground = white,
onSurface = white,
onError = black
)
@Composable
fun JpColorPalette(isDarkTheme: Boolean = isSystemInDarkTheme()) = when (isDarkTheme) {
true -> JpDarkColorPalette
else -> JpLightColorPalette
}
| gpl-2.0 | 696e4b529239d6a8aea8bea6de0f9aa9 | 28.518519 | 87 | 0.700753 | 4.464986 | false | false | false | false |
mdaniel/intellij-community | java/idea-ui/src/com/intellij/ide/starters/local/wizard/StarterInitialStep.kt | 8 | 9606 | // 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.ide.starters.local.wizard
import com.intellij.ide.starters.JavaStartersBundle
import com.intellij.ide.starters.local.*
import com.intellij.ide.starters.shared.*
import com.intellij.ide.wizard.withVisualPadding
import com.intellij.openapi.Disposable
import com.intellij.openapi.application.PathManager
import com.intellij.openapi.application.impl.ApplicationInfoImpl
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.roots.ui.configuration.validateJavaVersion
import com.intellij.openapi.ui.DialogPanel
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.util.JDOMUtil
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.util.registry.Registry
import com.intellij.ui.SimpleListCellRenderer
import com.intellij.ui.dsl.builder.*
import com.intellij.util.concurrency.AppExecutorUtil
import com.intellij.util.concurrency.annotations.RequiresBackgroundThread
import com.intellij.util.io.HttpRequests
import com.intellij.util.io.exists
import com.intellij.util.text.nullize
import com.intellij.util.ui.UIUtil.invokeLaterIfNeeded
import org.jdom.Element
import java.io.File
import java.net.SocketTimeoutException
import java.nio.file.Files
import java.nio.file.Path
import javax.swing.DefaultComboBoxModel
import javax.swing.JComponent
open class StarterInitialStep(contextProvider: StarterContextProvider) : CommonStarterInitialStep(
contextProvider.wizardContext,
contextProvider.starterContext,
contextProvider.moduleBuilder,
contextProvider.parentDisposable,
contextProvider.settings
) {
protected val moduleBuilder: StarterModuleBuilder = contextProvider.moduleBuilder
protected val starterContext: StarterContext = contextProvider.starterContext
private val starterPackProvider: () -> StarterPack = contextProvider.starterPackProvider
private val contentPanel: DialogPanel by lazy { createComponent() }
protected lateinit var languageRow: Row
@Volatile
private var isDisposed: Boolean = false
override fun getHelpId(): String? = moduleBuilder.getHelpId()
init {
Disposer.register(parentDisposable, Disposable {
isDisposed = true
})
}
override fun updateDataModel() {
starterContext.projectType = projectTypeProperty.get()
starterContext.language = languageProperty.get()
starterContext.group = groupId
starterContext.artifact = artifactId
starterContext.testFramework = testFrameworkProperty.get()
starterContext.includeExamples = exampleCodeProperty.get()
starterContext.gitIntegration = gitProperty.get()
wizardContext.projectName = entityName
wizardContext.setProjectFileDirectory(FileUtil.join(location, entityName))
val sdk = sdkProperty.get()
moduleBuilder.moduleJdk = sdk
if (wizardContext.project == null) {
wizardContext.projectJdk = sdk
}
}
override fun getComponent(): JComponent {
return contentPanel
}
private fun createComponent(): DialogPanel {
entityNameProperty.dependsOn(artifactIdProperty) { artifactId }
artifactIdProperty.dependsOn(entityNameProperty) { entityName }
// query dependencies from builder, called only once
val starterPack = starterPackProvider.invoke()
starterContext.starterPack = starterPack
updateStartersDependencies(starterPack)
return panel {
addProjectLocationUi()
addFieldsBefore(this)
if (starterSettings.applicationTypes.isNotEmpty()) {
row(JavaStartersBundle.message("title.project.app.type.label")) {
val applicationTypesModel = DefaultComboBoxModel<StarterAppType>()
applicationTypesModel.addAll(starterSettings.applicationTypes)
comboBox(applicationTypesModel, SimpleListCellRenderer.create("", StarterAppType::title))
.bindItem(applicationTypeProperty)
.columns(COLUMNS_MEDIUM)
bottomGap(BottomGap.SMALL)
}
}
if (starterSettings.languages.size > 1) {
row(JavaStartersBundle.message("title.project.language.label")) {
languageRow = this
segmentedButton(starterSettings.languages, StarterLanguage::title)
.bind(languageProperty)
bottomGap(BottomGap.SMALL)
}
}
if (starterSettings.projectTypes.isNotEmpty()) {
val messages = starterSettings.customizedMessages
row(messages?.projectTypeLabel ?: JavaStartersBundle.message("title.project.build.system.label")) {
segmentedButton(starterSettings.projectTypes, StarterProjectType::title)
.bind(projectTypeProperty)
bottomGap(BottomGap.SMALL)
}
}
if (starterSettings.testFrameworks.size > 1) {
row(JavaStartersBundle.message("title.project.test.framework.label")) {
segmentedButton(starterSettings.testFrameworks, StarterTestRunner::title)
.bind(testFrameworkProperty)
bottomGap(BottomGap.SMALL)
}
}
addGroupArtifactUi()
addSdkUi()
addSampleCodeUi()
addFieldsAfter(this)
}.withVisualPadding(topField = true)
}
override fun validate(): Boolean {
if (!validateFormFields(component, contentPanel, validatedTextComponents)) {
return false
}
if (!validateJavaVersion(sdkProperty, moduleBuilder.getMinJavaVersionInternal()?.toFeatureString(), moduleBuilder.presentableName)) {
return false
}
return true
}
private fun updateStartersDependencies(starterPack: StarterPack) {
val starters = starterPack.starters
AppExecutorUtil.getAppExecutorService().submit {
checkDependencyUpdates(starters)
}
}
@RequiresBackgroundThread
private fun checkDependencyUpdates(starters: List<Starter>) {
for (starter in starters) {
val localUpdates = loadStarterDependencyUpdatesFromFile(starter.id)
if (localUpdates != null) {
setStarterDependencyUpdates(starter.id, localUpdates)
return
}
val externalUpdates = loadStarterDependencyUpdatesFromNetwork(starter.id) ?: return
val (dependencyUpdates, resourcePath) = externalUpdates
if (isDisposed) return
val dependencyConfig = StarterUtils.parseDependencyConfig(dependencyUpdates, resourcePath)
if (isDisposed) return
saveStarterDependencyUpdatesToFile(starter.id, dependencyUpdates)
setStarterDependencyUpdates(starter.id, dependencyConfig)
}
}
@RequiresBackgroundThread
private fun loadStarterDependencyUpdatesFromFile(starterId: String): DependencyConfig? {
val configUpdateDir = File(PathManager.getTempPath(), getDependencyConfigUpdatesDirLocation(starterId))
val configUpdateFile = File(configUpdateDir, getPatchFileName(starterId))
if (!configUpdateFile.exists()
|| StarterUtils.isDependencyUpdateFileExpired(configUpdateFile)) {
return null
}
val resourcePath = configUpdateFile.absolutePath
return try {
StarterUtils.parseDependencyConfig(JDOMUtil.load(configUpdateFile), resourcePath)
}
catch (e: Exception) {
logger<StarterInitialStep>().warn("Failed to load starter dependency updates from file: $resourcePath. The file will be deleted.")
FileUtil.delete(configUpdateFile)
null
}
}
@RequiresBackgroundThread
private fun loadStarterDependencyUpdatesFromNetwork(starterId: String): Pair<Element, String>? {
val url = buildStarterPatchUrl(starterId) ?: return null
return try {
val content = HttpRequests.request(url)
.accept("application/xml")
.readString()
return JDOMUtil.load(content) to url
}
catch (e: Exception) {
if (e is HttpRequests.HttpStatusException
&& (e.statusCode == 403 || e.statusCode == 404)) {
logger<StarterInitialStep>().debug("No updates for $starterId: $url")
}
else if (e is SocketTimeoutException) {
logger<StarterInitialStep>().debug("Socket timeout for $starterId: $url")
}
else {
logger<StarterInitialStep>().warn("Unable to load external starter $starterId dependency updates from: $url", e)
}
null
}
}
@RequiresBackgroundThread
private fun saveStarterDependencyUpdatesToFile(starterId: String, dependencyConfigUpdate: Element) {
val configUpdateDir = Path.of(PathManager.getTempPath(), getDependencyConfigUpdatesDirLocation(starterId))
if (!configUpdateDir.exists()) {
Files.createDirectories(configUpdateDir)
}
val configUpdateFile = configUpdateDir.resolve(getPatchFileName(starterId))
JDOMUtil.write(dependencyConfigUpdate, configUpdateFile)
}
private fun setStarterDependencyUpdates(starterId: String, dependencyConfigUpdate: DependencyConfig) {
invokeLaterIfNeeded {
if (isDisposed) return@invokeLaterIfNeeded
starterContext.startersDependencyUpdates[starterId] = dependencyConfigUpdate
}
}
private fun buildStarterPatchUrl(starterId: String): String? {
val host = Registry.stringValue("starters.dependency.update.host").nullize(true) ?: return null
val ideVersion = ApplicationInfoImpl.getShadowInstance().let { "${it.majorVersion}.${it.minorVersion}" }
val patchFileName = getPatchFileName(starterId)
return "$host/starter/$starterId/$ideVersion/$patchFileName"
}
private fun getDependencyConfigUpdatesDirLocation(starterId: String): String = "framework-starters/$starterId/"
private fun getPatchFileName(starterId: String): String = "${starterId}_patch.pom"
} | apache-2.0 | 58363f9261c4009543fbbd5ff1c33a38 | 35.390152 | 140 | 0.747137 | 5.206504 | false | true | false | false |
elpassion/cloud-timer-android | app/src/androidTest/java/pl/elpassion/cloudtimer/AlarmServiceTest.kt | 1 | 1947 | package pl.elpassion.cloudtimer
import android.app.PendingIntent
import android.app.PendingIntent.*
import android.content.Intent
import android.support.test.espresso.Espresso.closeSoftKeyboard
import android.support.test.runner.AndroidJUnit4
import org.junit.Assert.assertNotNull
import org.junit.Assert.assertNull
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
import pl.elpassion.cloudtimer.ComponentsTestsUtils.pressButton
import pl.elpassion.cloudtimer.alarm.AlarmReceiver
import pl.elpassion.cloudtimer.alarm.AlarmReceiver.Companion.REQUEST_CODE
import pl.elpassion.cloudtimer.timer.TimerActivity
@RunWith(AndroidJUnit4::class)
class AlarmServiceTest {
@Rule @JvmField
val rule = rule<TimerActivity>{}
private val alarmReceiverClass = AlarmReceiver::class.java
@Test
fun alarmSchedulerNoPendingIntentsAtStart() {
clearIntent()
val alarmUp = getPendingIntent()
assertNull(alarmUp)
}
@Test
fun alarmSchedulerCreatesPendingIntent() {
clearIntent()
closeSoftKeyboard()
pressButton(R.id.start_timer_button)
val alarmUp = getPendingIntent()
assertNotNull(alarmUp)
}
@Test
fun alarmSchedulerNoRandomIntentType() {
clearIntent()
val requestCodeToTry = 123
closeSoftKeyboard()
pressButton(R.id.start_timer_button)
val alarmUp = getPendingIntent(requestCodeToTry)
assertNull(alarmUp)
}
private fun clearIntent() {
val intent = Intent(rule.activity, alarmReceiverClass)
getBroadcast(rule.activity, REQUEST_CODE, intent, FLAG_CANCEL_CURRENT).cancel()
}
private fun getPendingIntent() = getPendingIntent(REQUEST_CODE)
private fun getPendingIntent(reqCode: Int): PendingIntent? {
val intent = Intent(rule.activity, alarmReceiverClass)
return getBroadcast(rule.activity, reqCode, intent, FLAG_NO_CREATE)
}
}
| apache-2.0 | aa1e6d25a895158f6aa34092bcb6b0aa | 31.45 | 87 | 0.737545 | 4.506944 | false | true | false | false |
micolous/metrodroid | src/commonMain/kotlin/au/id/micolous/metrodroid/transit/tfi_leap/LeapTripPoint.kt | 1 | 1981 | /*
* LeapTransitData.kt
*
* Copyright 2018-2019 Google
*
* 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 au.id.micolous.metrodroid.transit.tfi_leap
import au.id.micolous.metrodroid.multi.Parcelable
import au.id.micolous.metrodroid.multi.Parcelize
import au.id.micolous.metrodroid.time.TimestampFull
internal fun<T> valuesCompatible(a: T?, b: T?): Boolean =
(a == null || b == null || a == b)
@Parcelize
internal class LeapTripPoint (val mTimestamp: TimestampFull?,
val mAmount: Int?,
private val mEventCode: Int?,
val mStation: Int?): Parcelable {
fun isMergeable(other: LeapTripPoint?): Boolean =
other == null || (
valuesCompatible(mAmount, other.mAmount) &&
valuesCompatible(mTimestamp, other.mTimestamp) &&
valuesCompatible(mEventCode, other.mEventCode) &&
valuesCompatible(mStation, other.mStation)
)
companion object {
fun merge(a: LeapTripPoint?, b: LeapTripPoint?) = LeapTripPoint(
mAmount = a?.mAmount ?: b?.mAmount,
mTimestamp = a?.mTimestamp ?: b?.mTimestamp,
mEventCode = a?.mEventCode ?: b?.mEventCode,
mStation = a?.mStation ?: b?.mStation
)
}
}
| gpl-3.0 | 6e3e6e8308297166ca62afae0a64fc3c | 38.62 | 73 | 0.630994 | 4.392461 | false | false | false | false |
micolous/metrodroid | src/commonMain/kotlin/au/id/micolous/metrodroid/key/ClassicStaticKeys.kt | 1 | 3549 | /*
* ClassicStaticKeys.kt
*
* Copyright 2018-2019 Google
*
* 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 au.id.micolous.metrodroid.key
import au.id.micolous.metrodroid.multi.Localizer
import au.id.micolous.metrodroid.multi.Log
import au.id.micolous.metrodroid.multi.R
import kotlinx.serialization.json.JsonObject
import kotlinx.serialization.json.json
/**
* Helper for access to static MIFARE Classic keys. This can be used for keys that should be
* attempted on multiple cards.
*
* This is only really useful when a transit agency doesn't implement key diversification.
*
* See https://github.com/micolous/metrodroid/wiki/Importing-MIFARE-Classic-keys#static-json for
* a file format description.
*/
class ClassicStaticKeys private constructor(override val description: String?,
override val keys: Map<Int, List<ClassicSectorAlgoKey>>,
override val sourceDataLength: Int)
: ClassicKeysImpl() {
internal operator fun plus(other: ClassicStaticKeys): ClassicStaticKeys {
return ClassicStaticKeys(description = description,
keys = flattenKeys(listOf(this, other)),
sourceDataLength = sourceDataLength + other.sourceDataLength)
}
override fun toJSON(): JsonObject {
if (description == null)
return baseJson
return JsonObject(baseJson + json {
JSON_TAG_ID_DESC to description
})
}
val allBundles get() = keys.values.flatten().map { it.bundle }.toSet()
override val type = CardKeys.TYPE_MFC_STATIC
override val uid = CardKeys.CLASSIC_STATIC_TAG_ID
override val fileType: String
get() = Localizer.localizePlural(R.plurals.keytype_mfc_static, keyCount, keyCount)
companion object {
private const val JSON_TAG_ID_DESC = "Description"
fun fallback() = ClassicStaticKeys(description = "fallback",
keys = mapOf(), sourceDataLength = 0)
fun flattenKeys(lst: List<ClassicStaticKeys>): Map<Int, List<ClassicSectorAlgoKey>> {
val keys = mutableMapOf<Int, MutableList<ClassicSectorAlgoKey>>()
for (who in lst)
for ((key, value) in who.keys) {
if (!keys.containsKey(key))
keys[key] = mutableListOf()
keys[key]?.addAll(value)
}
return keys
}
fun fromJSON(jsonRoot: JsonObject, defaultBundle: String) = try {
ClassicStaticKeys(
description = jsonRoot.getPrimitiveOrNull(JSON_TAG_ID_DESC)?.contentOrNull,
keys = ClassicKeysImpl.keysFromJSON(jsonRoot, false, defaultBundle),
sourceDataLength = jsonRoot.toString().length)
} catch (e: Exception) {
Log.e("ClassicStaticKeys", "parsing failed", e)
null
}
}
}
| gpl-3.0 | 6281374eae2f1ff7492195da7667214e | 37.576087 | 100 | 0.653142 | 4.639216 | false | false | false | false |
florent37/Flutter-AssetsAudioPlayer | android/src/main/kotlin/com/github/florent37/assets_audio_player/playerimplem/PlayerImplemExoPlayer.kt | 1 | 14959 | package com.github.florent37.assets_audio_player.playerimplem
import android.content.Context
import android.net.Uri
import android.os.Build
import android.util.Log
import com.github.florent37.assets_audio_player.AssetAudioPlayerThrowable
import com.github.florent37.assets_audio_player.AssetsAudioPlayerPlugin
import com.github.florent37.assets_audio_player.Player
import com.google.android.exoplayer2.*
import com.google.android.exoplayer2.C.AUDIO_SESSION_ID_UNSET
import com.google.android.exoplayer2.Player.REPEAT_MODE_ALL
import com.google.android.exoplayer2.Player.REPEAT_MODE_OFF
import com.google.android.exoplayer2.drm.*
import com.google.android.exoplayer2.extractor.DefaultExtractorsFactory
import com.google.android.exoplayer2.extractor.ts.AdtsExtractor
import com.google.android.exoplayer2.source.MediaSource
import com.google.android.exoplayer2.source.ProgressiveMediaSource
import com.google.android.exoplayer2.source.dash.DashMediaSource
import com.google.android.exoplayer2.source.hls.HlsMediaSource
import com.google.android.exoplayer2.source.smoothstreaming.SsMediaSource
import com.google.android.exoplayer2.upstream.*
import io.flutter.embedding.engine.plugins.FlutterPlugin
import java.io.File
import kotlin.coroutines.resume
import kotlin.coroutines.resumeWithException
import kotlin.coroutines.suspendCoroutine
class IncompatibleException(val audioType: String, val type: PlayerImplemTesterExoPlayer.Type) : Throwable()
class PlayerImplemTesterExoPlayer(private val type: Type) : PlayerImplemTester {
enum class Type {
Default,
HLS,
DASH,
SmoothStreaming
}
override suspend fun open(configuration: PlayerFinderConfiguration): PlayerFinder.PlayerWithDuration {
if (AssetsAudioPlayerPlugin.displayLogs) {
Log.d("PlayerImplem", "trying to open with exoplayer($type)")
}
//some type are only for web
if (configuration.audioType != Player.AUDIO_TYPE_LIVESTREAM && configuration.audioType != Player.AUDIO_TYPE_LIVESTREAM) {
if (type == Type.HLS || type == Type.DASH || type == Type.SmoothStreaming) {
throw IncompatibleException(configuration.audioType, type)
}
}
val mediaPlayer = PlayerImplemExoPlayer(
onFinished = {
configuration.onFinished?.invoke()
//stop(pingListener = false)
},
onBuffering = {
configuration.onBuffering?.invoke(it)
},
onError = { t ->
configuration.onError?.invoke(t)
},
type = this.type
)
try {
val durationMS = mediaPlayer.open(
context = configuration.context,
assetAudioPath = configuration.assetAudioPath,
audioType = configuration.audioType,
assetAudioPackage = configuration.assetAudioPackage,
networkHeaders = configuration.networkHeaders,
flutterAssets = configuration.flutterAssets,
drmConfiguration = configuration.drmConfiguration
)
return PlayerFinder.PlayerWithDuration(
player = mediaPlayer,
duration = durationMS
)
} catch (t: Throwable) {
if (AssetsAudioPlayerPlugin.displayLogs) {
Log.d("PlayerImplem", "failed to open with exoplayer($type)")
}
mediaPlayer.release()
throw t
}
}
}
class PlayerImplemExoPlayer(
onFinished: (() -> Unit),
onBuffering: ((Boolean) -> Unit),
onError: ((AssetAudioPlayerThrowable) -> Unit),
val type: PlayerImplemTesterExoPlayer.Type
) : PlayerImplem(
onFinished = onFinished,
onBuffering = onBuffering,
onError = onError
) {
private var mediaPlayer: ExoPlayer? = null
override var loopSingleAudio: Boolean
get() = mediaPlayer?.repeatMode == REPEAT_MODE_ALL
set(value) {
mediaPlayer?.repeatMode = if (value) REPEAT_MODE_ALL else REPEAT_MODE_OFF
}
override val isPlaying: Boolean
get() = mediaPlayer?.isPlaying ?: false
override val currentPositionMs: Long
get() = mediaPlayer?.currentPosition ?: 0
override fun stop() {
mediaPlayer?.stop()
}
override fun play() {
mediaPlayer?.playWhenReady = true
}
override fun pause() {
mediaPlayer?.playWhenReady = false
}
private fun getDataSource(context: Context,
flutterAssets: FlutterPlugin.FlutterAssets,
assetAudioPath: String?,
audioType: String,
networkHeaders: Map<*, *>?,
assetAudioPackage: String?,
drmConfiguration: Map<*, *>?
): MediaSource {
try {
mediaPlayer?.stop()
when (audioType) {
Player.AUDIO_TYPE_NETWORK, Player.AUDIO_TYPE_LIVESTREAM -> {
val uri = Uri.parse(assetAudioPath)
val mediaItem: MediaItem = MediaItem.fromUri(uri)
val userAgent = "assets_audio_player"
val factory = DataSource.Factory {
val allowCrossProtocol = true
val dataSource = DefaultHttpDataSource.Factory().setUserAgent(userAgent).setAllowCrossProtocolRedirects(allowCrossProtocol).createDataSource()
networkHeaders?.forEach {
it.key?.let { key ->
it.value?.let { value ->
dataSource.setRequestProperty(key.toString(), value.toString())
}
}
}
dataSource
}
return when (type) {
PlayerImplemTesterExoPlayer.Type.HLS -> HlsMediaSource.Factory(factory).setAllowChunklessPreparation(true)
PlayerImplemTesterExoPlayer.Type.DASH -> DashMediaSource.Factory(factory)
PlayerImplemTesterExoPlayer.Type.SmoothStreaming -> SsMediaSource.Factory(factory)
else -> ProgressiveMediaSource.Factory(factory, DefaultExtractorsFactory().setAdtsExtractorFlags(AdtsExtractor.FLAG_ENABLE_CONSTANT_BITRATE_SEEKING))
}.createMediaSource(mediaItem)
}
Player.AUDIO_TYPE_FILE -> {
val uri = Uri.parse(assetAudioPath)
var mediaItem: MediaItem = MediaItem.fromUri(uri)
val factory = ProgressiveMediaSource
.Factory(DefaultDataSource.Factory(context), DefaultExtractorsFactory())
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
val key = drmConfiguration?.get("clearKey")?.toString()
if (key != null) {
val mediaItemDrmConfiguration: MediaItem.DrmConfiguration = MediaItem.DrmConfiguration.Builder(C.CLEARKEY_UUID).setKeySetId(key.toByteArray()).build()
mediaItem = mediaItem.buildUpon().setDrmConfiguration(mediaItemDrmConfiguration).build()
factory.setDrmSessionManagerProvider(DefaultDrmSessionManagerProvider())
}
}
return factory.createMediaSource(mediaItem)
}
else -> { //asset$
val p = assetAudioPath!!.replace(" ", "%20")
val path = if (assetAudioPackage.isNullOrBlank()) {
flutterAssets.getAssetFilePathByName(p)
} else {
flutterAssets.getAssetFilePathByName(p, assetAudioPackage)
}
val assetDataSource = AssetDataSource(context)
assetDataSource.open(DataSpec(Uri.fromFile(File(path))))
val factory = DataSource.Factory { assetDataSource }
return ProgressiveMediaSource
.Factory(factory, DefaultExtractorsFactory())
.createMediaSource(MediaItem.fromUri(assetDataSource.uri!!))
}
}
} catch (e: Exception) {
throw e
}
}
private fun ExoPlayer.Builder.incrementBufferSize(audioType: String): ExoPlayer.Builder {
if (audioType == Player.AUDIO_TYPE_NETWORK || audioType == Player.AUDIO_TYPE_LIVESTREAM) {
/* Instantiate a DefaultLoadControl.Builder. */
val loadControlBuilder = DefaultLoadControl.Builder()
/*How many milliseconds of media data to buffer at any time. */
val loadControlBufferMs = DefaultLoadControl.DEFAULT_MAX_BUFFER_MS /* This is 50000 milliseconds in ExoPlayer 2.9.6 */
/* Configure the DefaultLoadControl to use the same value for */
loadControlBuilder.setBufferDurationsMs(
loadControlBufferMs,
loadControlBufferMs,
DefaultLoadControl.DEFAULT_BUFFER_FOR_PLAYBACK_MS,
DefaultLoadControl.DEFAULT_BUFFER_FOR_PLAYBACK_AFTER_REBUFFER_MS)
return this.setLoadControl(loadControlBuilder.build())
}
return this
}
fun mapError(t: Throwable): AssetAudioPlayerThrowable {
return when {
t is ExoPlaybackException -> {
(t.cause as? HttpDataSource.InvalidResponseCodeException)?.takeIf { it.responseCode >= 400 }?.let {
AssetAudioPlayerThrowable.UnreachableException(t)
} ?: let {
AssetAudioPlayerThrowable.NetworkError(t)
}
}
t.message?.contains("unable to connect", true) == true -> {
AssetAudioPlayerThrowable.NetworkError(t)
}
else -> {
AssetAudioPlayerThrowable.PlayerError(t)
}
}
}
override suspend fun open(
context: Context,
flutterAssets: FlutterPlugin.FlutterAssets,
assetAudioPath: String?,
audioType: String,
networkHeaders: Map<*, *>?,
assetAudioPackage: String?,
drmConfiguration: Map<*, *>?
) = suspendCoroutine<DurationMS> { continuation ->
var onThisMediaReady = false
try {
mediaPlayer = ExoPlayer.Builder(context)
.incrementBufferSize(audioType)
.build()
val mediaSource = getDataSource(
context = context,
flutterAssets = flutterAssets,
assetAudioPath = assetAudioPath,
audioType = audioType,
networkHeaders = networkHeaders,
assetAudioPackage = assetAudioPackage,
drmConfiguration = drmConfiguration
)
var lastState: Int? = null
this.mediaPlayer?.addListener(object : com.google.android.exoplayer2.Player.Listener {
override fun onPlayerError(error: PlaybackException) {
val errorMapped = mapError(error)
if (!onThisMediaReady) {
continuation.resumeWithException(errorMapped)
} else {
onError(errorMapped)
}
}
override fun onPlaybackStateChanged(playbackState: Int) {
if (lastState != playbackState) {
when (playbackState) {
ExoPlayer.STATE_ENDED -> {
pause()
onFinished.invoke()
onBuffering.invoke(false)
}
ExoPlayer.STATE_BUFFERING -> {
onBuffering.invoke(true)
}
ExoPlayer.STATE_READY -> {
onBuffering.invoke(false)
if (!onThisMediaReady) {
onThisMediaReady = true
//retrieve duration in seconds
if (audioType == Player.AUDIO_TYPE_LIVESTREAM) {
continuation.resume(0) //no duration for livestream
} else {
val duration = mediaPlayer?.duration ?: 0
continuation.resume(duration)
}
}
}
else -> {
}
}
}
lastState = playbackState
}
})
mediaPlayer?.setMediaSource(mediaSource)
mediaPlayer?.prepare()
} catch (error: Throwable) {
if (!onThisMediaReady) {
continuation.resumeWithException(error)
} else {
onBuffering.invoke(false)
onError(mapError(error))
}
}
}
override fun release() {
mediaPlayer?.release()
}
override fun seekTo(to: Long) {
mediaPlayer?.seekTo(to)
}
override fun setVolume(volume: Float) {
mediaPlayer?.volume = volume
}
override fun setPlaySpeed(playSpeed: Float) {
val params: PlaybackParameters? = mediaPlayer?.playbackParameters
if (params != null) {
mediaPlayer?.playbackParameters = PlaybackParameters(playSpeed, params.pitch)
}
}
override fun setPitch(pitch: Float) {
val params: PlaybackParameters? = mediaPlayer?.playbackParameters
if (params != null) {
mediaPlayer?.playbackParameters = PlaybackParameters(params.speed, pitch)
}
}
override fun getSessionId(listener: (Int) -> Unit) {
val id = mediaPlayer?.audioSessionId?.takeIf { it != AUDIO_SESSION_ID_UNSET }
if (id != null) {
listener(id)
} else {
val listener = object : com.google.android.exoplayer2.Player.Listener {
override fun onAudioSessionIdChanged(audioSessionId: Int) {
listener(audioSessionId)
mediaPlayer?.removeListener(this)
}
}
mediaPlayer?.addListener(listener)
}
//return
}
} | apache-2.0 | 7918900cc353ab521d844fb583724017 | 39.762943 | 178 | 0.553713 | 5.914986 | false | true | false | false |
GunoH/intellij-community | plugins/git4idea/src/git4idea/config/GitExecutableSelectorPanel.kt | 2 | 6371 | // 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 git4idea.config
import com.intellij.ide.impl.isTrusted
import com.intellij.openapi.Disposable
import com.intellij.openapi.application.ModalityState
import com.intellij.openapi.application.invokeAndWaitIfNeeded
import com.intellij.openapi.application.runInEdt
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.progress.Task
import com.intellij.openapi.progress.runBackgroundableTask
import com.intellij.openapi.progress.util.BackgroundTaskUtil
import com.intellij.openapi.project.Project
import com.intellij.openapi.vcs.changes.VcsDirtyScopeManager
import com.intellij.ui.dsl.builder.AlignX
import com.intellij.ui.dsl.builder.Panel
import com.intellij.util.application
import com.intellij.util.ui.VcsExecutablePathSelector
import git4idea.GitVcs
import git4idea.i18n.GitBundle
import org.jetbrains.annotations.CalledInAny
internal class GitExecutableSelectorPanel(val project: Project, val disposable: Disposable) {
companion object {
fun Panel.createGitExecutableSelectorRow(project: Project, disposable: Disposable) {
val panel = GitExecutableSelectorPanel(project, disposable)
with(panel) {
createRow()
}
}
}
private val applicationSettings get() = GitVcsApplicationSettings.getInstance()
private val projectSettings get() = GitVcsSettings.getInstance(project)
private val pathSelector = VcsExecutablePathSelector(GitVcs.DISPLAY_NAME.get(), disposable, GitExecutableHandler())
@Volatile
private var versionCheckRequested = false
init {
application.messageBus.connect(disposable).subscribe(GitExecutableManager.TOPIC,
GitExecutableListener { runInEdt(getModalityState()) { resetPathSelector() } })
BackgroundTaskUtil.executeOnPooledThread(disposable) {
GitExecutableManager.getInstance().getDetectedExecutable(project, true) // detect executable if needed
}
}
private fun Panel.createRow() = row {
cell(pathSelector.mainPanel)
.align(AlignX.FILL)
.onReset {
resetPathSelector()
}
.onIsModified {
pathSelector.isModified(
applicationSettings.savedPathToGit,
projectSettings.pathToGit != null,
projectSettings.pathToGit)
}
.onApply {
val currentPath = pathSelector.currentPath
if (pathSelector.isOverridden) {
projectSettings.pathToGit = currentPath
}
else {
applicationSettings.setPathToGit(currentPath)
projectSettings.pathToGit = null
}
validateExecutableOnceAfterClose()
VcsDirtyScopeManager.getInstance(project).markEverythingDirty()
}
}
private fun resetPathSelector() {
pathSelector.setAutoDetectedPath(GitExecutableManager.getInstance().getDetectedExecutable(project, false))
pathSelector.reset(
applicationSettings.savedPathToGit,
projectSettings.pathToGit != null,
projectSettings.pathToGit)
}
private fun testGitExecutable(pathToGit: String) {
val modalityState = getModalityState()
val errorNotifier = InlineErrorNotifierFromSettings(
GitExecutableInlineComponent(pathSelector.errorComponent, modalityState, null),
modalityState, disposable
)
if (!project.isDefault && !project.isTrusted()) {
errorNotifier.showError(GitBundle.message("git.executable.validation.cant.run.in.safe.mode"), null)
return
}
object : Task.Modal(project, GitBundle.message("git.executable.version.progress.title"), true) {
private lateinit var gitVersion: GitVersion
override fun run(indicator: ProgressIndicator) {
val executableManager = GitExecutableManager.getInstance()
val executable = executableManager.getExecutable(pathToGit)
executableManager.dropVersionCache(executable)
gitVersion = executableManager.identifyVersion(executable)
}
override fun onThrowable(error: Throwable) {
val problemHandler = findGitExecutableProblemHandler(project)
problemHandler.showError(error, errorNotifier)
}
override fun onSuccess() {
if (gitVersion.isSupported) {
errorNotifier.showMessage(GitBundle.message("git.executable.version.is", gitVersion.presentation))
}
else {
showUnsupportedVersionError(project, gitVersion, errorNotifier)
}
}
}.queue()
}
/**
* Special method to check executable after it has been changed through settings
*/
private fun validateExecutableOnceAfterClose() {
if (versionCheckRequested) return
versionCheckRequested = true
runInEdt(ModalityState.NON_MODAL) {
versionCheckRequested = false
runBackgroundableTask(GitBundle.message("git.executable.version.progress.title"), project, true) {
GitExecutableManager.getInstance().testGitExecutableVersionValid(project)
}
}
}
private fun getModalityState() = ModalityState.stateForComponent(pathSelector.mainPanel)
private inner class InlineErrorNotifierFromSettings(inlineComponent: InlineComponent,
private val modalityState: ModalityState,
disposable: Disposable)
: InlineErrorNotifier(inlineComponent, modalityState, disposable) {
@CalledInAny
override fun showError(text: String, description: String?, fixOption: ErrorNotifier.FixOption?) {
if (fixOption is ErrorNotifier.FixOption.Configure) {
super.showError(text, description, null)
}
else {
super.showError(text, description, fixOption)
}
}
override fun resetGitExecutable() {
super.resetGitExecutable()
GitExecutableManager.getInstance().getDetectedExecutable(project, true) // populate cache
invokeAndWaitIfNeeded(modalityState) {
resetPathSelector()
}
}
}
private inner class GitExecutableHandler : VcsExecutablePathSelector.ExecutableHandler {
override fun patchExecutable(executable: String): String? {
return GitExecutableDetector.patchExecutablePath(executable)
}
override fun testExecutable(executable: String) {
testGitExecutable(executable)
}
}
} | apache-2.0 | 09658dd2563c8bcd81bd5879f6e3f813 | 35.62069 | 158 | 0.728614 | 5.408319 | false | false | false | false |
GunoH/intellij-community | notebooks/visualization/src/org/jetbrains/plugins/notebooks/visualization/NotebookCellLines.kt | 2 | 2902 | package org.jetbrains.plugins.notebooks.visualization
import com.intellij.openapi.actionSystem.DataKey
import com.intellij.openapi.editor.Document
import com.intellij.openapi.editor.Editor
import com.intellij.util.EventDispatcher
import java.util.*
val NOTEBOOK_CELL_LINES_INTERVAL_DATA_KEY = DataKey.create<NotebookCellLines.Interval>("NOTEBOOK_CELL_LINES_INTERVAL")
/**
* Incrementally iterates over Notebook document, calculates line ranges of cells using lexer.
* Fast enough for running in EDT, but could be used in any other thread.
*
* Note: there's a difference between this model and the PSI model.
* If a document starts not with a cell marker, this class treat the text before the first cell marker as a raw cell.
* PSI model treats such cell as a special "stem" cell which is not a Jupyter cell at all.
* We haven't decided which model is correct and which should be fixed. So, for now avoid using stem cells in tests,
* while UI of PyCharm DS doesn't allow to create a stem cell at all.
*/
interface NotebookCellLines {
enum class CellType {
CODE, MARKDOWN, RAW
}
data class Marker(
val ordinal: Int,
val type: CellType,
val offset: Int,
val length: Int
) : Comparable<Marker> {
override fun compareTo(other: Marker): Int = offset - other.offset
}
enum class MarkersAtLines(val hasTopLine: Boolean, val hasBottomLine: Boolean) {
NO(false, false),
TOP(true, false),
BOTTOM(false, true),
TOP_AND_BOTTOM(true, true)
}
data class Interval(
val ordinal: Int,
val type: CellType,
val lines: IntRange,
val markers: MarkersAtLines,
) : Comparable<Interval> {
override fun compareTo(other: Interval): Int = lines.first - other.lines.first
}
interface IntervalListener : EventListener {
/**
* Called each time when document is changed, even if intervals are the same.
* Contains DocumentEvent and additional information about intervals.
* Components which work with intervals can simply listen for NotebookCellLinesEvent and don't subscribe for DocumentEvent.
*/
fun documentChanged(event: NotebookCellLinesEvent)
fun beforeDocumentChange(event: NotebookCellLinesEventBeforeChange) {}
}
fun intervalsIterator(startLine: Int = 0): ListIterator<Interval>
val intervals: List<Interval>
val intervalListeners: EventDispatcher<IntervalListener>
val modificationStamp: Long
companion object {
fun get(document: Document): NotebookCellLines =
NotebookCellLinesProvider.get(document)?.create(document)
?: error("Can't get NotebookCellLinesProvider for document ${document}")
fun hasSupport(document: Document): Boolean =
NotebookCellLinesProvider.get(document) != null
fun get(editor: Editor): NotebookCellLines =
get(editor.document)
fun hasSupport(editor: Editor): Boolean =
hasSupport(editor.document)
}
} | apache-2.0 | cc240aabf52882ab36ba43185ab37974 | 33.559524 | 127 | 0.737078 | 4.506211 | false | false | false | false |
GunoH/intellij-community | build/launch/src/com/intellij/tools/launch/Launcher.kt | 4 | 5417 | package com.intellij.tools.launch
import com.intellij.tools.launch.impl.ClassPathBuilder
import com.intellij.util.JavaModuleOptions
import com.intellij.util.system.OS
import org.jetbrains.intellij.build.dependencies.TeamCityHelper
import java.io.File
import java.net.InetAddress
import java.net.ServerSocket
import java.nio.file.Files
import java.util.logging.Logger
object Launcher {
private const val defaultDebugPort = 5050
private val logger = Logger.getLogger(Launcher::class.java.name)
fun launch(paths: PathsProvider,
modules: ModulesProvider,
options: LauncherOptions,
logClasspath: Boolean): Process {
val classPathBuilder = ClassPathBuilder(paths, modules)
logger.info("Building classpath")
val classPathArgFile = classPathBuilder.build(logClasspath)
logger.info("Done building classpath")
return launch(paths, classPathArgFile, options)
}
fun launch(paths: PathsProvider,
classPathArgFile: File,
options: LauncherOptions): Process {
// We should create config folder to avoid import settings dialog.
Files.createDirectories(paths.configFolder.toPath())
val cmd = mutableListOf(
paths.javaExecutable.canonicalPath,
"-ea",
"-Dapple.laf.useScreenMenuBar=true",
"-Dfus.internal.test.mode=true",
"-Djb.privacy.policy.text=\"<!--999.999-->\"",
"-Djb.consents.confirmation.enabled=false",
"-Didea.suppress.statistics.report=true",
"-Drsch.send.usage.stat=false",
"-Duse.linux.keychain=false",
"-Didea.initially.ask.config=never",
"-Dide.show.tips.on.startup.default.value=false",
"-Didea.config.path=${paths.configFolder.canonicalPath}",
"-Didea.system.path=${paths.systemFolder.canonicalPath}",
"-Didea.log.path=${paths.logFolder.canonicalPath}",
"-Didea.is.internal=true",
"-Didea.debug.mode=true",
"-Didea.jre.check=true",
"-Didea.fix.mac.env=true",
"-Djdk.attach.allowAttachSelf",
"-Djdk.module.illegalAccess.silent=true",
"-Djava.system.class.loader=com.intellij.util.lang.PathClassLoader",
"-Dkotlinx.coroutines.debug=off",
"-Dsun.awt.disablegrab=true",
"-Dsun.io.useCanonCaches=false",
"-Dteamcity.build.tempDir=${paths.tempFolder.canonicalPath}",
"-Xmx${options.xmx}m",
"-XX:+UseG1GC",
"-XX:-OmitStackTraceInFastThrow",
"-XX:CICompilerCount=2",
"-XX:HeapDumpPath=${paths.tempFolder.canonicalPath}",
"-XX:MaxJavaStackTraceDepth=10000",
"-XX:ReservedCodeCacheSize=240m",
"-XX:SoftRefLRUPolicyMSPerMB=50",
"-XX:+UnlockDiagnosticVMOptions",
"-XX:+BytecodeVerificationLocal",
"-Dshared.indexes.download.auto.consent=true"
)
val optionsOpenedFile = paths.communityRootFolder.resolve("plugins/devkit/devkit-core/src/run/OpenedPackages.txt")
val optionsOpenedPackages = JavaModuleOptions.readOptions(optionsOpenedFile.toPath(), OS.CURRENT)
cmd.addAll(optionsOpenedPackages)
if (options.platformPrefix != null) {
cmd.add("-Didea.platform.prefix=${options.platformPrefix}")
}
if (!TeamCityHelper.isUnderTeamCity) {
val suspendOnStart = if (options.debugSuspendOnStart) "y" else "n"
val port = if (options.debugPort > 0) options.debugPort else findFreeDebugPort()
// changed in Java 9, now we have to use *: to listen on all interfaces
val host = if (options.runInDocker) "*:" else ""
cmd.add("-agentlib:jdwp=transport=dt_socket,server=y,suspend=$suspendOnStart,address=$host$port")
}
for (arg in options.javaArguments) {
cmd.add(arg.trim('"'))
}
cmd.add("@${classPathArgFile.canonicalPath}")
cmd.add("com.intellij.idea.Main")
for (arg in options.ideaArguments) {
cmd.add(arg.trim('"'))
}
/*
println("Starting cmd:")
for (arg in cmd) {
println(" $arg")
}
println("-- END")
*/
return if (options.runInDocker) {
val docker = DockerLauncher(paths, options as DockerLauncherOptions)
docker.assertCanRun()
docker.runInContainer(cmd)
}
else {
val processBuilder = ProcessBuilder(cmd)
processBuilder.affixIO(options.redirectOutputIntoParentProcess, paths.logFolder)
processBuilder.environment().putAll(options.environment)
options.beforeProcessStart.invoke(processBuilder)
processBuilder.start()
}
}
fun ProcessBuilder.affixIO(redirectOutputIntoParentProcess: Boolean, logFolder: File) {
if (redirectOutputIntoParentProcess) {
this.inheritIO()
}
else {
logFolder.mkdirs()
// TODO: test logs overwrite launcher logs
this.redirectOutput(logFolder.resolve("out.log"))
this.redirectError(logFolder.resolve("err.log"))
}
}
fun findFreeDebugPort(): Int {
if (isDefaultPortFree()) {
return defaultDebugPort
}
val socket = ServerSocket(0, 0, InetAddress.getByName("127.0.0.1"))
val result = socket.localPort
socket.reuseAddress = true
socket.close()
return result
}
private fun isDefaultPortFree(): Boolean {
var socket: ServerSocket? = null
try {
socket = ServerSocket(defaultDebugPort, 0, InetAddress.getByName("127.0.0.1"))
socket.reuseAddress = true
return true
}
catch (e: Exception) {
return false
}
finally {
socket?.close()
}
}
} | apache-2.0 | 76e0401849b9c77d20768ac7bc1132e9 | 31.443114 | 118 | 0.678974 | 4.13196 | false | false | false | false |
santaevpavel/ClipboardTranslator | domain/src/main/java/com/example/santaev/domain/repository/LanguageRepository.kt | 1 | 1910 | package com.example.santaev.domain.repository
import com.example.santaev.domain.api.IApiService
import com.example.santaev.domain.api.LanguagesResponseDto
import com.example.santaev.domain.database.ILanguageDao
import com.example.santaev.domain.dto.LanguageDto
import com.example.santaev.domain.repository.ILanguageRepository.LanguagesState
import io.reactivex.Flowable
import io.reactivex.Observable
import io.reactivex.schedulers.Schedulers
import io.reactivex.subjects.PublishSubject
internal class LanguageRepository(
private val languageDao: ILanguageDao,
private val apiService: IApiService
) : ILanguageRepository {
private var languagesLoadingStatus: LanguagesState? = null
set(value) {
field = value
if (value != null) languagesStatusSubject.onNext(value)
}
private val languagesStatusSubject = PublishSubject.create<LanguagesState>()
override fun requestLanguages(): Observable<LanguagesState> {
loadLanguages()
return languagesStatusSubject
}
override fun getLanguages(): Flowable<List<LanguageDto>> {
loadLanguages()
return languageDao.getLanguages()
}
private fun loadLanguages() {
if (languagesLoadingStatus == LanguagesState.LOADING) return
languagesLoadingStatus = LanguagesState.LOADING
apiService.getLanguages()
.subscribeOn(Schedulers.io())
.subscribe(
this::onLoadLanguages,
{ error ->
error.printStackTrace()
languagesLoadingStatus = LanguagesState.ERROR
}
)
}
private fun onLoadLanguages(languagesResponse: LanguagesResponseDto) {
languagesLoadingStatus = LanguagesState.SUCCESS
languageDao.insertAll(languagesResponse.languages)
}
}
| apache-2.0 | 7b6c28d94463620abe9f23d9966cf9c4 | 33.107143 | 80 | 0.68377 | 5.701493 | false | false | false | false |
marius-m/wt4 | remote/src/test/java/lt/markmerkk/worklogs/WorklogUploadValidatorKtTest.kt | 1 | 2794 | package lt.markmerkk.worklogs
import lt.markmerkk.Mocks
import lt.markmerkk.TimeProviderTest
import org.assertj.core.api.Assertions.assertThat
import org.junit.Test
class WorklogUploadValidatorKtTest {
private val timeProvider = TimeProviderTest()
@Test
fun localLog() {
val now = timeProvider.now()
val log = Mocks.createLog(
timeProvider,
id = 1,
start = now,
end = now.plusMinutes(1),
code = "WT-66",
comment = "valid_comment",
remoteData = null
)
val result = log.isEligibleForUpload()
assertThat(result).isInstanceOf(WorklogValid::class.java)
}
@Test
fun noComment() {
val now = timeProvider.now()
val log = Mocks.createLog(
timeProvider,
id = 1,
start = now,
end = now.plusMinutes(5),
code = "WT-66",
comment = "",
remoteData = null
)
val result = log.isEligibleForUpload()
assertThat(result).isInstanceOf(WorklogInvalidNoComment::class.java)
}
@Test
fun notValidTicket() {
val now = timeProvider.now()
val log = Mocks.createLog(
timeProvider,
id = 1,
start = now,
end = now.plusMinutes(5),
code = "invalid_ticket",
comment = "valid_comment",
remoteData = null
)
val result = log.isEligibleForUpload()
assertThat(result).isInstanceOf(WorklogInvalidNoTicketCode::class.java)
}
@Test
fun durationLessThanOneMinute() {
val now = timeProvider.now()
val log = Mocks.createLog(
timeProvider,
id = 1,
start = now,
end = now.plusSeconds(59),
code = "WT-66",
comment = "valid_comment",
remoteData = null
)
val result = log.isEligibleForUpload()
assertThat(result).isInstanceOf(WorklogInvalidDurationTooLittle::class.java)
}
@Test
fun remoteLog() {
val now = timeProvider.now()
val log = Mocks.createLog(
timeProvider,
id = 1,
start = now,
end = now.plusMinutes(5),
code = "WT-66",
comment = "valid_comment",
remoteData = Mocks.createRemoteData(
timeProvider,
remoteId = 2
)
)
val result = log.isEligibleForUpload()
assertThat(result).isInstanceOf(WorklogInvalidAlreadyRemote::class.java)
}
} | apache-2.0 | f170ae80fdda4d6622bbc7cbbc904a3c | 25.875 | 84 | 0.509306 | 5.145488 | false | true | false | false |
Philip-Trettner/GlmKt | GlmKt/src/glm/vec/Double/DoubleVec3.kt | 1 | 25623 | package glm
data class DoubleVec3(val x: Double, val y: Double, val z: Double) {
// Initializes each element by evaluating init from 0 until 2
constructor(init: (Int) -> Double) : this(init(0), init(1), init(2))
operator fun get(idx: Int): Double = when (idx) {
0 -> x
1 -> y
2 -> z
else -> throw IndexOutOfBoundsException("index $idx is out of bounds")
}
// Operators
operator fun inc(): DoubleVec3 = DoubleVec3(x.inc(), y.inc(), z.inc())
operator fun dec(): DoubleVec3 = DoubleVec3(x.dec(), y.dec(), z.dec())
operator fun unaryPlus(): DoubleVec3 = DoubleVec3(+x, +y, +z)
operator fun unaryMinus(): DoubleVec3 = DoubleVec3(-x, -y, -z)
operator fun plus(rhs: DoubleVec3): DoubleVec3 = DoubleVec3(x + rhs.x, y + rhs.y, z + rhs.z)
operator fun minus(rhs: DoubleVec3): DoubleVec3 = DoubleVec3(x - rhs.x, y - rhs.y, z - rhs.z)
operator fun times(rhs: DoubleVec3): DoubleVec3 = DoubleVec3(x * rhs.x, y * rhs.y, z * rhs.z)
operator fun div(rhs: DoubleVec3): DoubleVec3 = DoubleVec3(x / rhs.x, y / rhs.y, z / rhs.z)
operator fun rem(rhs: DoubleVec3): DoubleVec3 = DoubleVec3(x % rhs.x, y % rhs.y, z % rhs.z)
operator fun plus(rhs: Double): DoubleVec3 = DoubleVec3(x + rhs, y + rhs, z + rhs)
operator fun minus(rhs: Double): DoubleVec3 = DoubleVec3(x - rhs, y - rhs, z - rhs)
operator fun times(rhs: Double): DoubleVec3 = DoubleVec3(x * rhs, y * rhs, z * rhs)
operator fun div(rhs: Double): DoubleVec3 = DoubleVec3(x / rhs, y / rhs, z / rhs)
operator fun rem(rhs: Double): DoubleVec3 = DoubleVec3(x % rhs, y % rhs, z % rhs)
inline fun map(func: (Double) -> Double): DoubleVec3 = DoubleVec3(func(x), func(y), func(z))
fun toList(): List<Double> = listOf(x, y, z)
// Predefined vector constants
companion object Constants {
val zero: DoubleVec3 = DoubleVec3(0.0, 0.0, 0.0)
val ones: DoubleVec3 = DoubleVec3(1.0, 1.0, 1.0)
val unitX: DoubleVec3 = DoubleVec3(1.0, 0.0, 0.0)
val unitY: DoubleVec3 = DoubleVec3(0.0, 1.0, 0.0)
val unitZ: DoubleVec3 = DoubleVec3(0.0, 0.0, 1.0)
}
// Conversions to Float
fun toVec(): Vec3 = Vec3(x.toFloat(), y.toFloat(), z.toFloat())
inline fun toVec(conv: (Double) -> Float): Vec3 = Vec3(conv(x), conv(y), conv(z))
fun toVec2(): Vec2 = Vec2(x.toFloat(), y.toFloat())
inline fun toVec2(conv: (Double) -> Float): Vec2 = Vec2(conv(x), conv(y))
fun toVec3(): Vec3 = Vec3(x.toFloat(), y.toFloat(), z.toFloat())
inline fun toVec3(conv: (Double) -> Float): Vec3 = Vec3(conv(x), conv(y), conv(z))
fun toVec4(w: Float = 0f): Vec4 = Vec4(x.toFloat(), y.toFloat(), z.toFloat(), w)
inline fun toVec4(w: Float = 0f, conv: (Double) -> Float): Vec4 = Vec4(conv(x), conv(y), conv(z), w)
// Conversions to Float
fun toMutableVec(): MutableVec3 = MutableVec3(x.toFloat(), y.toFloat(), z.toFloat())
inline fun toMutableVec(conv: (Double) -> Float): MutableVec3 = MutableVec3(conv(x), conv(y), conv(z))
fun toMutableVec2(): MutableVec2 = MutableVec2(x.toFloat(), y.toFloat())
inline fun toMutableVec2(conv: (Double) -> Float): MutableVec2 = MutableVec2(conv(x), conv(y))
fun toMutableVec3(): MutableVec3 = MutableVec3(x.toFloat(), y.toFloat(), z.toFloat())
inline fun toMutableVec3(conv: (Double) -> Float): MutableVec3 = MutableVec3(conv(x), conv(y), conv(z))
fun toMutableVec4(w: Float = 0f): MutableVec4 = MutableVec4(x.toFloat(), y.toFloat(), z.toFloat(), w)
inline fun toMutableVec4(w: Float = 0f, conv: (Double) -> Float): MutableVec4 = MutableVec4(conv(x), conv(y), conv(z), w)
// Conversions to Double
fun toDoubleVec(): DoubleVec3 = DoubleVec3(x, y, z)
inline fun toDoubleVec(conv: (Double) -> Double): DoubleVec3 = DoubleVec3(conv(x), conv(y), conv(z))
fun toDoubleVec2(): DoubleVec2 = DoubleVec2(x, y)
inline fun toDoubleVec2(conv: (Double) -> Double): DoubleVec2 = DoubleVec2(conv(x), conv(y))
fun toDoubleVec3(): DoubleVec3 = DoubleVec3(x, y, z)
inline fun toDoubleVec3(conv: (Double) -> Double): DoubleVec3 = DoubleVec3(conv(x), conv(y), conv(z))
fun toDoubleVec4(w: Double = 0.0): DoubleVec4 = DoubleVec4(x, y, z, w)
inline fun toDoubleVec4(w: Double = 0.0, conv: (Double) -> Double): DoubleVec4 = DoubleVec4(conv(x), conv(y), conv(z), w)
// Conversions to Double
fun toMutableDoubleVec(): MutableDoubleVec3 = MutableDoubleVec3(x, y, z)
inline fun toMutableDoubleVec(conv: (Double) -> Double): MutableDoubleVec3 = MutableDoubleVec3(conv(x), conv(y), conv(z))
fun toMutableDoubleVec2(): MutableDoubleVec2 = MutableDoubleVec2(x, y)
inline fun toMutableDoubleVec2(conv: (Double) -> Double): MutableDoubleVec2 = MutableDoubleVec2(conv(x), conv(y))
fun toMutableDoubleVec3(): MutableDoubleVec3 = MutableDoubleVec3(x, y, z)
inline fun toMutableDoubleVec3(conv: (Double) -> Double): MutableDoubleVec3 = MutableDoubleVec3(conv(x), conv(y), conv(z))
fun toMutableDoubleVec4(w: Double = 0.0): MutableDoubleVec4 = MutableDoubleVec4(x, y, z, w)
inline fun toMutableDoubleVec4(w: Double = 0.0, conv: (Double) -> Double): MutableDoubleVec4 = MutableDoubleVec4(conv(x), conv(y), conv(z), w)
// Conversions to Int
fun toIntVec(): IntVec3 = IntVec3(x.toInt(), y.toInt(), z.toInt())
inline fun toIntVec(conv: (Double) -> Int): IntVec3 = IntVec3(conv(x), conv(y), conv(z))
fun toIntVec2(): IntVec2 = IntVec2(x.toInt(), y.toInt())
inline fun toIntVec2(conv: (Double) -> Int): IntVec2 = IntVec2(conv(x), conv(y))
fun toIntVec3(): IntVec3 = IntVec3(x.toInt(), y.toInt(), z.toInt())
inline fun toIntVec3(conv: (Double) -> Int): IntVec3 = IntVec3(conv(x), conv(y), conv(z))
fun toIntVec4(w: Int = 0): IntVec4 = IntVec4(x.toInt(), y.toInt(), z.toInt(), w)
inline fun toIntVec4(w: Int = 0, conv: (Double) -> Int): IntVec4 = IntVec4(conv(x), conv(y), conv(z), w)
// Conversions to Int
fun toMutableIntVec(): MutableIntVec3 = MutableIntVec3(x.toInt(), y.toInt(), z.toInt())
inline fun toMutableIntVec(conv: (Double) -> Int): MutableIntVec3 = MutableIntVec3(conv(x), conv(y), conv(z))
fun toMutableIntVec2(): MutableIntVec2 = MutableIntVec2(x.toInt(), y.toInt())
inline fun toMutableIntVec2(conv: (Double) -> Int): MutableIntVec2 = MutableIntVec2(conv(x), conv(y))
fun toMutableIntVec3(): MutableIntVec3 = MutableIntVec3(x.toInt(), y.toInt(), z.toInt())
inline fun toMutableIntVec3(conv: (Double) -> Int): MutableIntVec3 = MutableIntVec3(conv(x), conv(y), conv(z))
fun toMutableIntVec4(w: Int = 0): MutableIntVec4 = MutableIntVec4(x.toInt(), y.toInt(), z.toInt(), w)
inline fun toMutableIntVec4(w: Int = 0, conv: (Double) -> Int): MutableIntVec4 = MutableIntVec4(conv(x), conv(y), conv(z), w)
// Conversions to Long
fun toLongVec(): LongVec3 = LongVec3(x.toLong(), y.toLong(), z.toLong())
inline fun toLongVec(conv: (Double) -> Long): LongVec3 = LongVec3(conv(x), conv(y), conv(z))
fun toLongVec2(): LongVec2 = LongVec2(x.toLong(), y.toLong())
inline fun toLongVec2(conv: (Double) -> Long): LongVec2 = LongVec2(conv(x), conv(y))
fun toLongVec3(): LongVec3 = LongVec3(x.toLong(), y.toLong(), z.toLong())
inline fun toLongVec3(conv: (Double) -> Long): LongVec3 = LongVec3(conv(x), conv(y), conv(z))
fun toLongVec4(w: Long = 0L): LongVec4 = LongVec4(x.toLong(), y.toLong(), z.toLong(), w)
inline fun toLongVec4(w: Long = 0L, conv: (Double) -> Long): LongVec4 = LongVec4(conv(x), conv(y), conv(z), w)
// Conversions to Long
fun toMutableLongVec(): MutableLongVec3 = MutableLongVec3(x.toLong(), y.toLong(), z.toLong())
inline fun toMutableLongVec(conv: (Double) -> Long): MutableLongVec3 = MutableLongVec3(conv(x), conv(y), conv(z))
fun toMutableLongVec2(): MutableLongVec2 = MutableLongVec2(x.toLong(), y.toLong())
inline fun toMutableLongVec2(conv: (Double) -> Long): MutableLongVec2 = MutableLongVec2(conv(x), conv(y))
fun toMutableLongVec3(): MutableLongVec3 = MutableLongVec3(x.toLong(), y.toLong(), z.toLong())
inline fun toMutableLongVec3(conv: (Double) -> Long): MutableLongVec3 = MutableLongVec3(conv(x), conv(y), conv(z))
fun toMutableLongVec4(w: Long = 0L): MutableLongVec4 = MutableLongVec4(x.toLong(), y.toLong(), z.toLong(), w)
inline fun toMutableLongVec4(w: Long = 0L, conv: (Double) -> Long): MutableLongVec4 = MutableLongVec4(conv(x), conv(y), conv(z), w)
// Conversions to Short
fun toShortVec(): ShortVec3 = ShortVec3(x.toShort(), y.toShort(), z.toShort())
inline fun toShortVec(conv: (Double) -> Short): ShortVec3 = ShortVec3(conv(x), conv(y), conv(z))
fun toShortVec2(): ShortVec2 = ShortVec2(x.toShort(), y.toShort())
inline fun toShortVec2(conv: (Double) -> Short): ShortVec2 = ShortVec2(conv(x), conv(y))
fun toShortVec3(): ShortVec3 = ShortVec3(x.toShort(), y.toShort(), z.toShort())
inline fun toShortVec3(conv: (Double) -> Short): ShortVec3 = ShortVec3(conv(x), conv(y), conv(z))
fun toShortVec4(w: Short = 0.toShort()): ShortVec4 = ShortVec4(x.toShort(), y.toShort(), z.toShort(), w)
inline fun toShortVec4(w: Short = 0.toShort(), conv: (Double) -> Short): ShortVec4 = ShortVec4(conv(x), conv(y), conv(z), w)
// Conversions to Short
fun toMutableShortVec(): MutableShortVec3 = MutableShortVec3(x.toShort(), y.toShort(), z.toShort())
inline fun toMutableShortVec(conv: (Double) -> Short): MutableShortVec3 = MutableShortVec3(conv(x), conv(y), conv(z))
fun toMutableShortVec2(): MutableShortVec2 = MutableShortVec2(x.toShort(), y.toShort())
inline fun toMutableShortVec2(conv: (Double) -> Short): MutableShortVec2 = MutableShortVec2(conv(x), conv(y))
fun toMutableShortVec3(): MutableShortVec3 = MutableShortVec3(x.toShort(), y.toShort(), z.toShort())
inline fun toMutableShortVec3(conv: (Double) -> Short): MutableShortVec3 = MutableShortVec3(conv(x), conv(y), conv(z))
fun toMutableShortVec4(w: Short = 0.toShort()): MutableShortVec4 = MutableShortVec4(x.toShort(), y.toShort(), z.toShort(), w)
inline fun toMutableShortVec4(w: Short = 0.toShort(), conv: (Double) -> Short): MutableShortVec4 = MutableShortVec4(conv(x), conv(y), conv(z), w)
// Conversions to Byte
fun toByteVec(): ByteVec3 = ByteVec3(x.toByte(), y.toByte(), z.toByte())
inline fun toByteVec(conv: (Double) -> Byte): ByteVec3 = ByteVec3(conv(x), conv(y), conv(z))
fun toByteVec2(): ByteVec2 = ByteVec2(x.toByte(), y.toByte())
inline fun toByteVec2(conv: (Double) -> Byte): ByteVec2 = ByteVec2(conv(x), conv(y))
fun toByteVec3(): ByteVec3 = ByteVec3(x.toByte(), y.toByte(), z.toByte())
inline fun toByteVec3(conv: (Double) -> Byte): ByteVec3 = ByteVec3(conv(x), conv(y), conv(z))
fun toByteVec4(w: Byte = 0.toByte()): ByteVec4 = ByteVec4(x.toByte(), y.toByte(), z.toByte(), w)
inline fun toByteVec4(w: Byte = 0.toByte(), conv: (Double) -> Byte): ByteVec4 = ByteVec4(conv(x), conv(y), conv(z), w)
// Conversions to Byte
fun toMutableByteVec(): MutableByteVec3 = MutableByteVec3(x.toByte(), y.toByte(), z.toByte())
inline fun toMutableByteVec(conv: (Double) -> Byte): MutableByteVec3 = MutableByteVec3(conv(x), conv(y), conv(z))
fun toMutableByteVec2(): MutableByteVec2 = MutableByteVec2(x.toByte(), y.toByte())
inline fun toMutableByteVec2(conv: (Double) -> Byte): MutableByteVec2 = MutableByteVec2(conv(x), conv(y))
fun toMutableByteVec3(): MutableByteVec3 = MutableByteVec3(x.toByte(), y.toByte(), z.toByte())
inline fun toMutableByteVec3(conv: (Double) -> Byte): MutableByteVec3 = MutableByteVec3(conv(x), conv(y), conv(z))
fun toMutableByteVec4(w: Byte = 0.toByte()): MutableByteVec4 = MutableByteVec4(x.toByte(), y.toByte(), z.toByte(), w)
inline fun toMutableByteVec4(w: Byte = 0.toByte(), conv: (Double) -> Byte): MutableByteVec4 = MutableByteVec4(conv(x), conv(y), conv(z), w)
// Conversions to Char
fun toCharVec(): CharVec3 = CharVec3(x.toChar(), y.toChar(), z.toChar())
inline fun toCharVec(conv: (Double) -> Char): CharVec3 = CharVec3(conv(x), conv(y), conv(z))
fun toCharVec2(): CharVec2 = CharVec2(x.toChar(), y.toChar())
inline fun toCharVec2(conv: (Double) -> Char): CharVec2 = CharVec2(conv(x), conv(y))
fun toCharVec3(): CharVec3 = CharVec3(x.toChar(), y.toChar(), z.toChar())
inline fun toCharVec3(conv: (Double) -> Char): CharVec3 = CharVec3(conv(x), conv(y), conv(z))
fun toCharVec4(w: Char): CharVec4 = CharVec4(x.toChar(), y.toChar(), z.toChar(), w)
inline fun toCharVec4(w: Char, conv: (Double) -> Char): CharVec4 = CharVec4(conv(x), conv(y), conv(z), w)
// Conversions to Char
fun toMutableCharVec(): MutableCharVec3 = MutableCharVec3(x.toChar(), y.toChar(), z.toChar())
inline fun toMutableCharVec(conv: (Double) -> Char): MutableCharVec3 = MutableCharVec3(conv(x), conv(y), conv(z))
fun toMutableCharVec2(): MutableCharVec2 = MutableCharVec2(x.toChar(), y.toChar())
inline fun toMutableCharVec2(conv: (Double) -> Char): MutableCharVec2 = MutableCharVec2(conv(x), conv(y))
fun toMutableCharVec3(): MutableCharVec3 = MutableCharVec3(x.toChar(), y.toChar(), z.toChar())
inline fun toMutableCharVec3(conv: (Double) -> Char): MutableCharVec3 = MutableCharVec3(conv(x), conv(y), conv(z))
fun toMutableCharVec4(w: Char): MutableCharVec4 = MutableCharVec4(x.toChar(), y.toChar(), z.toChar(), w)
inline fun toMutableCharVec4(w: Char, conv: (Double) -> Char): MutableCharVec4 = MutableCharVec4(conv(x), conv(y), conv(z), w)
// Conversions to Boolean
fun toBoolVec(): BoolVec3 = BoolVec3(x != 0.0, y != 0.0, z != 0.0)
inline fun toBoolVec(conv: (Double) -> Boolean): BoolVec3 = BoolVec3(conv(x), conv(y), conv(z))
fun toBoolVec2(): BoolVec2 = BoolVec2(x != 0.0, y != 0.0)
inline fun toBoolVec2(conv: (Double) -> Boolean): BoolVec2 = BoolVec2(conv(x), conv(y))
fun toBoolVec3(): BoolVec3 = BoolVec3(x != 0.0, y != 0.0, z != 0.0)
inline fun toBoolVec3(conv: (Double) -> Boolean): BoolVec3 = BoolVec3(conv(x), conv(y), conv(z))
fun toBoolVec4(w: Boolean = false): BoolVec4 = BoolVec4(x != 0.0, y != 0.0, z != 0.0, w)
inline fun toBoolVec4(w: Boolean = false, conv: (Double) -> Boolean): BoolVec4 = BoolVec4(conv(x), conv(y), conv(z), w)
// Conversions to Boolean
fun toMutableBoolVec(): MutableBoolVec3 = MutableBoolVec3(x != 0.0, y != 0.0, z != 0.0)
inline fun toMutableBoolVec(conv: (Double) -> Boolean): MutableBoolVec3 = MutableBoolVec3(conv(x), conv(y), conv(z))
fun toMutableBoolVec2(): MutableBoolVec2 = MutableBoolVec2(x != 0.0, y != 0.0)
inline fun toMutableBoolVec2(conv: (Double) -> Boolean): MutableBoolVec2 = MutableBoolVec2(conv(x), conv(y))
fun toMutableBoolVec3(): MutableBoolVec3 = MutableBoolVec3(x != 0.0, y != 0.0, z != 0.0)
inline fun toMutableBoolVec3(conv: (Double) -> Boolean): MutableBoolVec3 = MutableBoolVec3(conv(x), conv(y), conv(z))
fun toMutableBoolVec4(w: Boolean = false): MutableBoolVec4 = MutableBoolVec4(x != 0.0, y != 0.0, z != 0.0, w)
inline fun toMutableBoolVec4(w: Boolean = false, conv: (Double) -> Boolean): MutableBoolVec4 = MutableBoolVec4(conv(x), conv(y), conv(z), w)
// Conversions to String
fun toStringVec(): StringVec3 = StringVec3(x.toString(), y.toString(), z.toString())
inline fun toStringVec(conv: (Double) -> String): StringVec3 = StringVec3(conv(x), conv(y), conv(z))
fun toStringVec2(): StringVec2 = StringVec2(x.toString(), y.toString())
inline fun toStringVec2(conv: (Double) -> String): StringVec2 = StringVec2(conv(x), conv(y))
fun toStringVec3(): StringVec3 = StringVec3(x.toString(), y.toString(), z.toString())
inline fun toStringVec3(conv: (Double) -> String): StringVec3 = StringVec3(conv(x), conv(y), conv(z))
fun toStringVec4(w: String = ""): StringVec4 = StringVec4(x.toString(), y.toString(), z.toString(), w)
inline fun toStringVec4(w: String = "", conv: (Double) -> String): StringVec4 = StringVec4(conv(x), conv(y), conv(z), w)
// Conversions to String
fun toMutableStringVec(): MutableStringVec3 = MutableStringVec3(x.toString(), y.toString(), z.toString())
inline fun toMutableStringVec(conv: (Double) -> String): MutableStringVec3 = MutableStringVec3(conv(x), conv(y), conv(z))
fun toMutableStringVec2(): MutableStringVec2 = MutableStringVec2(x.toString(), y.toString())
inline fun toMutableStringVec2(conv: (Double) -> String): MutableStringVec2 = MutableStringVec2(conv(x), conv(y))
fun toMutableStringVec3(): MutableStringVec3 = MutableStringVec3(x.toString(), y.toString(), z.toString())
inline fun toMutableStringVec3(conv: (Double) -> String): MutableStringVec3 = MutableStringVec3(conv(x), conv(y), conv(z))
fun toMutableStringVec4(w: String = ""): MutableStringVec4 = MutableStringVec4(x.toString(), y.toString(), z.toString(), w)
inline fun toMutableStringVec4(w: String = "", conv: (Double) -> String): MutableStringVec4 = MutableStringVec4(conv(x), conv(y), conv(z), w)
// Conversions to T2
inline fun <T2> toTVec(conv: (Double) -> T2): TVec3<T2> = TVec3<T2>(conv(x), conv(y), conv(z))
inline fun <T2> toTVec2(conv: (Double) -> T2): TVec2<T2> = TVec2<T2>(conv(x), conv(y))
inline fun <T2> toTVec3(conv: (Double) -> T2): TVec3<T2> = TVec3<T2>(conv(x), conv(y), conv(z))
inline fun <T2> toTVec4(w: T2, conv: (Double) -> T2): TVec4<T2> = TVec4<T2>(conv(x), conv(y), conv(z), w)
// Conversions to T2
inline fun <T2> toMutableTVec(conv: (Double) -> T2): MutableTVec3<T2> = MutableTVec3<T2>(conv(x), conv(y), conv(z))
inline fun <T2> toMutableTVec2(conv: (Double) -> T2): MutableTVec2<T2> = MutableTVec2<T2>(conv(x), conv(y))
inline fun <T2> toMutableTVec3(conv: (Double) -> T2): MutableTVec3<T2> = MutableTVec3<T2>(conv(x), conv(y), conv(z))
inline fun <T2> toMutableTVec4(w: T2, conv: (Double) -> T2): MutableTVec4<T2> = MutableTVec4<T2>(conv(x), conv(y), conv(z), w)
// Allows for swizzling, e.g. v.swizzle.xzx
inner class Swizzle {
val xx: DoubleVec2 get() = DoubleVec2(x, x)
val xy: DoubleVec2 get() = DoubleVec2(x, y)
val xz: DoubleVec2 get() = DoubleVec2(x, z)
val yx: DoubleVec2 get() = DoubleVec2(y, x)
val yy: DoubleVec2 get() = DoubleVec2(y, y)
val yz: DoubleVec2 get() = DoubleVec2(y, z)
val zx: DoubleVec2 get() = DoubleVec2(z, x)
val zy: DoubleVec2 get() = DoubleVec2(z, y)
val zz: DoubleVec2 get() = DoubleVec2(z, z)
val xxx: DoubleVec3 get() = DoubleVec3(x, x, x)
val xxy: DoubleVec3 get() = DoubleVec3(x, x, y)
val xxz: DoubleVec3 get() = DoubleVec3(x, x, z)
val xyx: DoubleVec3 get() = DoubleVec3(x, y, x)
val xyy: DoubleVec3 get() = DoubleVec3(x, y, y)
val xyz: DoubleVec3 get() = DoubleVec3(x, y, z)
val xzx: DoubleVec3 get() = DoubleVec3(x, z, x)
val xzy: DoubleVec3 get() = DoubleVec3(x, z, y)
val xzz: DoubleVec3 get() = DoubleVec3(x, z, z)
val yxx: DoubleVec3 get() = DoubleVec3(y, x, x)
val yxy: DoubleVec3 get() = DoubleVec3(y, x, y)
val yxz: DoubleVec3 get() = DoubleVec3(y, x, z)
val yyx: DoubleVec3 get() = DoubleVec3(y, y, x)
val yyy: DoubleVec3 get() = DoubleVec3(y, y, y)
val yyz: DoubleVec3 get() = DoubleVec3(y, y, z)
val yzx: DoubleVec3 get() = DoubleVec3(y, z, x)
val yzy: DoubleVec3 get() = DoubleVec3(y, z, y)
val yzz: DoubleVec3 get() = DoubleVec3(y, z, z)
val zxx: DoubleVec3 get() = DoubleVec3(z, x, x)
val zxy: DoubleVec3 get() = DoubleVec3(z, x, y)
val zxz: DoubleVec3 get() = DoubleVec3(z, x, z)
val zyx: DoubleVec3 get() = DoubleVec3(z, y, x)
val zyy: DoubleVec3 get() = DoubleVec3(z, y, y)
val zyz: DoubleVec3 get() = DoubleVec3(z, y, z)
val zzx: DoubleVec3 get() = DoubleVec3(z, z, x)
val zzy: DoubleVec3 get() = DoubleVec3(z, z, y)
val zzz: DoubleVec3 get() = DoubleVec3(z, z, z)
val xxxx: DoubleVec4 get() = DoubleVec4(x, x, x, x)
val xxxy: DoubleVec4 get() = DoubleVec4(x, x, x, y)
val xxxz: DoubleVec4 get() = DoubleVec4(x, x, x, z)
val xxyx: DoubleVec4 get() = DoubleVec4(x, x, y, x)
val xxyy: DoubleVec4 get() = DoubleVec4(x, x, y, y)
val xxyz: DoubleVec4 get() = DoubleVec4(x, x, y, z)
val xxzx: DoubleVec4 get() = DoubleVec4(x, x, z, x)
val xxzy: DoubleVec4 get() = DoubleVec4(x, x, z, y)
val xxzz: DoubleVec4 get() = DoubleVec4(x, x, z, z)
val xyxx: DoubleVec4 get() = DoubleVec4(x, y, x, x)
val xyxy: DoubleVec4 get() = DoubleVec4(x, y, x, y)
val xyxz: DoubleVec4 get() = DoubleVec4(x, y, x, z)
val xyyx: DoubleVec4 get() = DoubleVec4(x, y, y, x)
val xyyy: DoubleVec4 get() = DoubleVec4(x, y, y, y)
val xyyz: DoubleVec4 get() = DoubleVec4(x, y, y, z)
val xyzx: DoubleVec4 get() = DoubleVec4(x, y, z, x)
val xyzy: DoubleVec4 get() = DoubleVec4(x, y, z, y)
val xyzz: DoubleVec4 get() = DoubleVec4(x, y, z, z)
val xzxx: DoubleVec4 get() = DoubleVec4(x, z, x, x)
val xzxy: DoubleVec4 get() = DoubleVec4(x, z, x, y)
val xzxz: DoubleVec4 get() = DoubleVec4(x, z, x, z)
val xzyx: DoubleVec4 get() = DoubleVec4(x, z, y, x)
val xzyy: DoubleVec4 get() = DoubleVec4(x, z, y, y)
val xzyz: DoubleVec4 get() = DoubleVec4(x, z, y, z)
val xzzx: DoubleVec4 get() = DoubleVec4(x, z, z, x)
val xzzy: DoubleVec4 get() = DoubleVec4(x, z, z, y)
val xzzz: DoubleVec4 get() = DoubleVec4(x, z, z, z)
val yxxx: DoubleVec4 get() = DoubleVec4(y, x, x, x)
val yxxy: DoubleVec4 get() = DoubleVec4(y, x, x, y)
val yxxz: DoubleVec4 get() = DoubleVec4(y, x, x, z)
val yxyx: DoubleVec4 get() = DoubleVec4(y, x, y, x)
val yxyy: DoubleVec4 get() = DoubleVec4(y, x, y, y)
val yxyz: DoubleVec4 get() = DoubleVec4(y, x, y, z)
val yxzx: DoubleVec4 get() = DoubleVec4(y, x, z, x)
val yxzy: DoubleVec4 get() = DoubleVec4(y, x, z, y)
val yxzz: DoubleVec4 get() = DoubleVec4(y, x, z, z)
val yyxx: DoubleVec4 get() = DoubleVec4(y, y, x, x)
val yyxy: DoubleVec4 get() = DoubleVec4(y, y, x, y)
val yyxz: DoubleVec4 get() = DoubleVec4(y, y, x, z)
val yyyx: DoubleVec4 get() = DoubleVec4(y, y, y, x)
val yyyy: DoubleVec4 get() = DoubleVec4(y, y, y, y)
val yyyz: DoubleVec4 get() = DoubleVec4(y, y, y, z)
val yyzx: DoubleVec4 get() = DoubleVec4(y, y, z, x)
val yyzy: DoubleVec4 get() = DoubleVec4(y, y, z, y)
val yyzz: DoubleVec4 get() = DoubleVec4(y, y, z, z)
val yzxx: DoubleVec4 get() = DoubleVec4(y, z, x, x)
val yzxy: DoubleVec4 get() = DoubleVec4(y, z, x, y)
val yzxz: DoubleVec4 get() = DoubleVec4(y, z, x, z)
val yzyx: DoubleVec4 get() = DoubleVec4(y, z, y, x)
val yzyy: DoubleVec4 get() = DoubleVec4(y, z, y, y)
val yzyz: DoubleVec4 get() = DoubleVec4(y, z, y, z)
val yzzx: DoubleVec4 get() = DoubleVec4(y, z, z, x)
val yzzy: DoubleVec4 get() = DoubleVec4(y, z, z, y)
val yzzz: DoubleVec4 get() = DoubleVec4(y, z, z, z)
val zxxx: DoubleVec4 get() = DoubleVec4(z, x, x, x)
val zxxy: DoubleVec4 get() = DoubleVec4(z, x, x, y)
val zxxz: DoubleVec4 get() = DoubleVec4(z, x, x, z)
val zxyx: DoubleVec4 get() = DoubleVec4(z, x, y, x)
val zxyy: DoubleVec4 get() = DoubleVec4(z, x, y, y)
val zxyz: DoubleVec4 get() = DoubleVec4(z, x, y, z)
val zxzx: DoubleVec4 get() = DoubleVec4(z, x, z, x)
val zxzy: DoubleVec4 get() = DoubleVec4(z, x, z, y)
val zxzz: DoubleVec4 get() = DoubleVec4(z, x, z, z)
val zyxx: DoubleVec4 get() = DoubleVec4(z, y, x, x)
val zyxy: DoubleVec4 get() = DoubleVec4(z, y, x, y)
val zyxz: DoubleVec4 get() = DoubleVec4(z, y, x, z)
val zyyx: DoubleVec4 get() = DoubleVec4(z, y, y, x)
val zyyy: DoubleVec4 get() = DoubleVec4(z, y, y, y)
val zyyz: DoubleVec4 get() = DoubleVec4(z, y, y, z)
val zyzx: DoubleVec4 get() = DoubleVec4(z, y, z, x)
val zyzy: DoubleVec4 get() = DoubleVec4(z, y, z, y)
val zyzz: DoubleVec4 get() = DoubleVec4(z, y, z, z)
val zzxx: DoubleVec4 get() = DoubleVec4(z, z, x, x)
val zzxy: DoubleVec4 get() = DoubleVec4(z, z, x, y)
val zzxz: DoubleVec4 get() = DoubleVec4(z, z, x, z)
val zzyx: DoubleVec4 get() = DoubleVec4(z, z, y, x)
val zzyy: DoubleVec4 get() = DoubleVec4(z, z, y, y)
val zzyz: DoubleVec4 get() = DoubleVec4(z, z, y, z)
val zzzx: DoubleVec4 get() = DoubleVec4(z, z, z, x)
val zzzy: DoubleVec4 get() = DoubleVec4(z, z, z, y)
val zzzz: DoubleVec4 get() = DoubleVec4(z, z, z, z)
}
val swizzle: Swizzle get() = Swizzle()
}
fun vecOf(x: Double, y: Double, z: Double): DoubleVec3 = DoubleVec3(x, y, z)
operator fun Double.plus(rhs: DoubleVec3): DoubleVec3 = DoubleVec3(this + rhs.x, this + rhs.y, this + rhs.z)
operator fun Double.minus(rhs: DoubleVec3): DoubleVec3 = DoubleVec3(this - rhs.x, this - rhs.y, this - rhs.z)
operator fun Double.times(rhs: DoubleVec3): DoubleVec3 = DoubleVec3(this * rhs.x, this * rhs.y, this * rhs.z)
operator fun Double.div(rhs: DoubleVec3): DoubleVec3 = DoubleVec3(this / rhs.x, this / rhs.y, this / rhs.z)
operator fun Double.rem(rhs: DoubleVec3): DoubleVec3 = DoubleVec3(this % rhs.x, this % rhs.y, this % rhs.z)
| mit | 83cc77e33b4fd9e07ef4966d41efa21c | 68.439024 | 149 | 0.63923 | 3.319902 | false | false | false | false |
jk1/Intellij-idea-mail | src/main/kotlin/github/jk1/smtpidea/store/InboxFolder.kt | 1 | 1863 | package github.jk1.smtpidea.store
import javax.mail.internet.MimeMessage
import javax.swing.SwingUtilities
import java.util.ArrayList
import javax.mail.Flags.Flag
/**
*
*/
public object InboxFolder : MessageFolder<MimeMessage>(){
private val columns = array("Index", "Subject", "Seen", "Deleted")
private val mails: MutableList<MimeMessage> = ArrayList();
override fun getMessages(): List<MimeMessage> {
return mails;
}
override fun messageCount(): Int {
return mails.size;
}
override fun get(i: Int): MimeMessage {
return mails[i]
}
public override fun add(message: MimeMessage) {
SwingUtilities.invokeAndWait({
InboxFolder.mails.add(message)
InboxFolder.fireTableDataChanged()
})
}
public override fun clear() {
SwingUtilities.invokeAndWait({
InboxFolder.mails.clear()
InboxFolder.fireTableDataChanged()
})
}
/**
* @return - sum of octet size of all messages in this folder
*/
fun totalSize(): Int {
return mails.fold(0, {(sum, item) -> sum + item.getSize()})
}
override fun getColumnCount(): Int = 4
public override fun getRowCount() : Int = messageCount();
override fun getColumnName(column: Int): String = columns[column]
override fun getColumnClass(columnIndex: Int) = if (columnIndex > 1) javaClass<Boolean>() else javaClass<String>()
override fun getValueAt(rowIndex: Int, columnIndex: Int): Any? {
when(columnIndex) {
0 -> return rowIndex
1 -> return this[rowIndex].getSubject();
2 -> return this[rowIndex].isSet(Flag.SEEN)
3 -> return this[rowIndex].isSet(Flag.DELETED)
}
throw IllegalArgumentException("No data available for column index $columnIndex")
}
}
| gpl-2.0 | 5a52241cc511917026139400cf3cf7e5 | 26.80597 | 118 | 0.635534 | 4.752551 | false | false | false | false |
pureal-code/pureal-os | traits/src/net/pureal/traits/interaction/Button.kt | 1 | 695 | package net.pureal.traits.interaction
import net.pureal.traits.*
import net.pureal.traits.graphics.*
import net.pureal.traits.math.*
trait Button : Clickable<Trigger<Unit>>, ColoredElement<Trigger<Unit>> {
override fun onClick(pointerKey: PointerKey) = content()
}
fun button(
trigger: Trigger<Unit> = trigger<Unit>(),
shape: Shape,
fill: Fill,
changed: Observable<Unit> = observable(),
onClick: () -> Unit = {}) = object : Button {
override val content = trigger
override val shape = shape
override val fill = fill
override val changed = changed
init {
content addObserver { onClick() }
}
} | bsd-3-clause | 3e1f53e99c9915817ecc1915c04b79b1 | 25.88 | 72 | 0.630216 | 4.237805 | false | false | false | false |
cmzy/okhttp | okhttp/src/main/kotlin/okhttp3/internal/platform/android/Android10SocketAdapter.kt | 4 | 2880 | /*
* Copyright (C) 2019 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.platform.android
import android.annotation.SuppressLint
import android.net.ssl.SSLSockets
import android.os.Build
import java.io.IOException
import java.lang.IllegalArgumentException
import javax.net.ssl.SSLSocket
import okhttp3.Protocol
import okhttp3.internal.SuppressSignatureCheck
import okhttp3.internal.platform.Platform
import okhttp3.internal.platform.Platform.Companion.isAndroid
/**
* Simple non-reflection SocketAdapter for Android Q+.
*
* These API assumptions make it unsuitable for use on earlier Android versions.
*/
@SuppressLint("NewApi")
@SuppressSignatureCheck
class Android10SocketAdapter : SocketAdapter {
override fun matchesSocket(sslSocket: SSLSocket): Boolean = SSLSockets.isSupportedSocket(sslSocket)
override fun isSupported(): Boolean = Companion.isSupported()
@SuppressLint("NewApi")
override fun getSelectedProtocol(sslSocket: SSLSocket): String? {
return try {
// SSLSocket.getApplicationProtocol returns "" if application protocols values will not
// be used. Observed if you didn't specify SSLParameters.setApplicationProtocols
when (val protocol = sslSocket.applicationProtocol) {
null, "" -> null
else -> protocol
}
} catch (e: UnsupportedOperationException) {
// https://docs.oracle.com/javase/9/docs/api/javax/net/ssl/SSLSocket.html#getApplicationProtocol--
null
}
}
@SuppressLint("NewApi")
override fun configureTlsExtensions(
sslSocket: SSLSocket,
hostname: String?,
protocols: List<Protocol>
) {
try {
SSLSockets.setUseSessionTickets(sslSocket, true)
val sslParameters = sslSocket.sslParameters
// Enable ALPN.
sslParameters.applicationProtocols = Platform.alpnProtocolNames(protocols).toTypedArray()
sslSocket.sslParameters = sslParameters
} catch (iae: IllegalArgumentException) {
// probably java.lang.IllegalArgumentException: Invalid input to toASCII from IDN.toASCII
throw IOException("Android internal error", iae)
}
}
@SuppressSignatureCheck
companion object {
fun buildIfSupported(): SocketAdapter? =
if (isSupported()) Android10SocketAdapter() else null
fun isSupported() = isAndroid && Build.VERSION.SDK_INT >= 29
}
}
| apache-2.0 | 0862046c239fa33b71109f105a73b42e | 33.285714 | 104 | 0.742708 | 4.521193 | false | false | false | false |
fwcd/kotlin-language-server | server/src/test/kotlin/org/javacs/kt/ClassPathTest.kt | 1 | 1421 | package org.javacs.kt
import org.hamcrest.Matchers.*
import org.javacs.kt.classpath.*
import org.junit.Assert.assertThat
import org.junit.Assert.assertTrue
import org.junit.Test
import org.junit.BeforeClass
import java.nio.file.Files
class ClassPathTest {
companion object {
@JvmStatic @BeforeClass fun setupLogger() {
LOG.connectStdioBackend()
}
}
@Test fun `find gradle classpath`() {
val workspaceRoot = testResourcesRoot().resolve("additionalWorkspace")
val buildFile = workspaceRoot.resolve("build.gradle")
assertTrue(Files.exists(buildFile))
val resolvers = defaultClassPathResolver(listOf(workspaceRoot))
print(resolvers)
val classPath = resolvers.classpathOrEmpty.map { it.toString() }
assertThat(classPath, hasItem(containsString("junit")))
}
@Test fun `find maven classpath`() {
val workspaceRoot = testResourcesRoot().resolve("mavenWorkspace")
val buildFile = workspaceRoot.resolve("pom.xml")
assertTrue(Files.exists(buildFile))
val resolvers = defaultClassPathResolver(listOf(workspaceRoot))
print(resolvers)
val classPath = resolvers.classpathOrEmpty.map { it.toString() }
assertThat(classPath, hasItem(containsString("junit")))
}
@Test fun `find kotlin stdlib`() {
assertThat(findKotlinStdlib(), notNullValue())
}
}
| mit | 32d6d9c5570ca10fa61ff89cc0010c89 | 29.234043 | 78 | 0.687544 | 4.72093 | false | true | false | false |
intellij-solidity/intellij-solidity | src/main/kotlin/me/serce/solidity/ide/search.kt | 1 | 1219 | package me.serce.solidity.ide
import com.intellij.lang.HelpID
import com.intellij.lang.cacheBuilder.DefaultWordsScanner
import com.intellij.lang.cacheBuilder.WordsScanner
import com.intellij.lang.findUsages.FindUsagesProvider
import com.intellij.psi.PsiElement
import com.intellij.psi.tree.TokenSet
import me.serce.solidity.lang.core.SolidityLexer
import me.serce.solidity.lang.core.SolidityParserDefinition
import me.serce.solidity.lang.core.SolidityTokenTypes.IDENTIFIER
import me.serce.solidity.lang.core.SolidityTokenTypes.STRINGLITERAL
import me.serce.solidity.lang.psi.SolNamedElement
class SolFindUsagesProvider : FindUsagesProvider {
override fun getWordsScanner(): WordsScanner = SolWordScanner()
override fun canFindUsagesFor(element: PsiElement) = element is SolNamedElement
override fun getHelpId(element: PsiElement) = HelpID.FIND_OTHER_USAGES
override fun getType(element: PsiElement) = ""
override fun getDescriptiveName(element: PsiElement) = ""
override fun getNodeText(element: PsiElement, useFullName: Boolean) = ""
}
class SolWordScanner : DefaultWordsScanner(
SolidityLexer(),
TokenSet.create(IDENTIFIER),
SolidityParserDefinition.COMMENTS,
TokenSet.create(STRINGLITERAL)
)
| mit | 83220cae3306ca52b405407db96ae2fe | 39.633333 | 81 | 0.827728 | 4.384892 | false | false | false | false |
dahlstrom-g/intellij-community | platform/platform-api/src/com/intellij/util/ui/scroll/BoundedRangeModelThresholdListener.kt | 7 | 1430 | // 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.util.ui.scroll
import javax.swing.BoundedRangeModel
import javax.swing.JScrollBar
import javax.swing.event.ChangeEvent
import javax.swing.event.ChangeListener
abstract class BoundedRangeModelThresholdListener(
private val model: BoundedRangeModel,
private val thresholdPercent: Float
) : ChangeListener {
init {
require(thresholdPercent > 0 && thresholdPercent < 1) { "Threshold should be a value greater than 0 and lesser than 1" }
}
override fun stateChanged(e: ChangeEvent) {
if (model.valueIsAdjusting) return
if (isAtThreshold()) {
onThresholdReached()
}
}
abstract fun onThresholdReached()
private fun isAtThreshold(): Boolean {
val visibleAmount = model.extent
val value = model.value
val maximum = model.maximum
if (maximum == 0) return false
val scrollFraction = (visibleAmount + value) / maximum.toFloat()
if (scrollFraction < thresholdPercent) return false
return true
}
companion object {
@JvmStatic
@JvmOverloads
fun install(scrollBar: JScrollBar, threshold: Float = 0.5f, listener: () -> Unit) {
scrollBar.model.addChangeListener(object : BoundedRangeModelThresholdListener(scrollBar.model, threshold) {
override fun onThresholdReached() = listener()
})
}
}
} | apache-2.0 | ef921f096ae95f6c2922d04210a4d6ab | 30.108696 | 124 | 0.725874 | 4.4 | false | false | false | false |
DreierF/MyTargets | shared/src/main/java/de/dreier/mytargets/shared/targets/models/NFAAAnimal.kt | 1 | 2366 | /*
* 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.shared.targets.models
import de.dreier.mytargets.shared.R
import de.dreier.mytargets.shared.models.Diameter
import de.dreier.mytargets.shared.models.ETargetType
import de.dreier.mytargets.shared.targets.scoringstyle.ArrowAwareScoringStyle
import de.dreier.mytargets.shared.targets.scoringstyle.ScoringStyle
import de.dreier.mytargets.shared.targets.zone.CircularZone
import de.dreier.mytargets.shared.targets.zone.EllipseZone
import de.dreier.mytargets.shared.utils.Color.BLACK
import de.dreier.mytargets.shared.utils.Color.GRAY
import de.dreier.mytargets.shared.utils.Color.LIGHTER_GRAY
import de.dreier.mytargets.shared.utils.Color.ORANGE
import de.dreier.mytargets.shared.utils.Color.TURBO_YELLOW
class NFAAAnimal : TargetModelBase(
id = ID,
nameRes = R.string.nfaa_animal,
diameters = listOf(Diameter.SMALL, Diameter.MEDIUM, Diameter.LARGE, Diameter.XLARGE),
zones = listOf(
CircularZone(0.162f, TURBO_YELLOW, BLACK, 5),
EllipseZone(1.0f, 0.0f, 0.0f, ORANGE, BLACK, 4),
CircularZone(1.0f, LIGHTER_GRAY, GRAY, 3)
),
scoringStyles = listOf(
ArrowAwareScoringStyle(false, arrayOf(intArrayOf(21, 20, 18), intArrayOf(17, 16, 14), intArrayOf(13, 12, 10))),
ScoringStyle(false, 20, 16, 10),
ScoringStyle(false, 15, 12, 7),
ArrowAwareScoringStyle(false, arrayOf(intArrayOf(20, 18, 16), intArrayOf(14, 12, 10), intArrayOf(8, 6, 4))),
ArrowAwareScoringStyle(false, arrayOf(intArrayOf(20, 18, 16), intArrayOf(12, 10, 8), intArrayOf(6, 4, 2))),
ArrowAwareScoringStyle(false, arrayOf(intArrayOf(15, 10, 5), intArrayOf(12, 7, 2)))
),
type = ETargetType.THREE_D
) {
companion object {
const val ID = 21L
}
}
| gpl-2.0 | 8a6a926c5a5bc23fad1c5f6528a9cc6d | 44.5 | 127 | 0.702029 | 3.828479 | false | false | false | false |
DemonWav/MinecraftDevIntelliJ | src/main/kotlin/com/demonwav/mcdev/facet/MinecraftFacetDetector.kt | 1 | 6076 | /*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2020 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev.facet
import com.demonwav.mcdev.platform.PlatformType
import com.demonwav.mcdev.platform.sponge.framework.SPONGE_LIBRARY_KIND
import com.demonwav.mcdev.util.AbstractProjectComponent
import com.demonwav.mcdev.util.ifEmpty
import com.demonwav.mcdev.util.runWriteTaskLater
import com.intellij.ProjectTopics
import com.intellij.facet.FacetManager
import com.intellij.facet.impl.ui.libraries.LibrariesValidatorContextImpl
import com.intellij.openapi.module.Module
import com.intellij.openapi.module.ModuleManager
import com.intellij.openapi.project.Project
import com.intellij.openapi.roots.ModuleRootEvent
import com.intellij.openapi.roots.ModuleRootListener
import com.intellij.openapi.roots.libraries.LibraryKind
import com.intellij.openapi.roots.ui.configuration.libraries.LibraryPresentationManager
import com.intellij.openapi.startup.StartupManager
class MinecraftFacetDetector(project: Project) : AbstractProjectComponent(project) {
override fun projectOpened() {
val manager = StartupManager.getInstance(project)
val connection = project.messageBus.connect()
manager.registerStartupActivity {
MinecraftModuleRootListener.doCheck(project)
}
// Register a module root listener to check when things change
manager.registerPostStartupActivity {
connection.subscribe(ProjectTopics.PROJECT_ROOTS, MinecraftModuleRootListener)
}
}
private object MinecraftModuleRootListener : ModuleRootListener {
override fun rootsChanged(event: ModuleRootEvent) {
if (event.isCausedByFileTypesChange) {
return
}
val project = event.source as? Project ?: return
doCheck(project)
}
fun doCheck(project: Project) {
val moduleManager = ModuleManager.getInstance(project)
for (module in moduleManager.modules) {
val facetManager = FacetManager.getInstance(module)
val minecraftFacet = facetManager.getFacetByType(MinecraftFacet.ID)
if (minecraftFacet == null) {
checkNoFacet(module)
} else {
checkExistingFacet(module, minecraftFacet)
}
}
}
private fun checkNoFacet(module: Module) {
val platforms = autoDetectTypes(module).ifEmpty { return }
val facetManager = FacetManager.getInstance(module)
val configuration = MinecraftFacetConfiguration()
configuration.state.autoDetectTypes.addAll(platforms)
val facet = facetManager.createFacet(MinecraftFacet.facetType, "Minecraft", configuration, null)
runWriteTaskLater {
// Only add the new facet if there isn't a Minecraft facet already - double check here since this
// task may run much later
if (module.isDisposed || facet.isDisposed) {
// Module may be disposed before we run
return@runWriteTaskLater
}
if (facetManager.getFacetByType(MinecraftFacet.ID) == null) {
val model = facetManager.createModifiableModel()
model.addFacet(facet)
model.commit()
}
}
}
private fun checkExistingFacet(module: Module, facet: MinecraftFacet) {
val platforms = autoDetectTypes(module).ifEmpty { return }
val types = facet.configuration.state.autoDetectTypes
types.clear()
types.addAll(platforms)
if (facet.configuration.state.forgePatcher) {
// make sure Forge and MCP are present
types.add(PlatformType.FORGE)
types.add(PlatformType.MCP)
}
facet.refresh()
}
private fun autoDetectTypes(module: Module): Set<PlatformType> {
val presentationManager = LibraryPresentationManager.getInstance()
val context = LibrariesValidatorContextImpl(module)
val platformKinds = mutableSetOf<LibraryKind>()
context.rootModel
.orderEntries()
.using(context.modulesProvider)
.recursively()
.librariesOnly()
.forEachLibrary forEach@{ library ->
MINECRAFT_LIBRARY_KINDS.forEach { kind ->
if (presentationManager.isLibraryOfKind(library, context.librariesContainer, setOf(kind))) {
platformKinds.add(kind)
}
}
return@forEach true
}
context.rootModel
.orderEntries()
.using(context.modulesProvider)
.recursively()
.withoutLibraries()
.withoutSdk()
.forEachModule forEach@{ m ->
if (m.name.startsWith("SpongeAPI")) {
// We don't want want to add parent modules in module groups
val moduleManager = ModuleManager.getInstance(m.project)
val groupPath = moduleManager.getModuleGroupPath(m)
if (groupPath == null) {
platformKinds.add(SPONGE_LIBRARY_KIND)
return@forEach true
}
val name = groupPath.lastOrNull() ?: return@forEach true
if (m.name == name) {
return@forEach true
}
platformKinds.add(SPONGE_LIBRARY_KIND)
}
return@forEach true
}
return platformKinds.mapNotNull { kind -> PlatformType.fromLibraryKind(kind) }.toSet()
}
}
}
| mit | eb7c3754fd2b3df2558786bcb17c5c39 | 37.700637 | 116 | 0.595787 | 5.64684 | false | false | false | false |
paplorinc/intellij-community | plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/codeInspection/type/highlighting.kt | 1 | 3600 | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.plugins.groovy.codeInspection.type
import com.intellij.codeInspection.LocalQuickFix
import com.intellij.codeInspection.ProblemHighlightType
import com.intellij.psi.JavaPsiFacade
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiType
import com.intellij.util.containers.toArray
import org.jetbrains.plugins.groovy.GroovyBundle.message
import org.jetbrains.plugins.groovy.highlighting.HighlightSink
import org.jetbrains.plugins.groovy.lang.psi.api.GroovyMethodResult
import org.jetbrains.plugins.groovy.lang.psi.api.statements.arguments.GrArgumentList
import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrGdkMethod
import org.jetbrains.plugins.groovy.lang.psi.impl.signatures.GrClosureSignatureUtil.createSignature
import org.jetbrains.plugins.groovy.lang.psi.impl.synthetic.DefaultConstructor
import org.jetbrains.plugins.groovy.lang.resolve.api.Argument
import org.jetbrains.plugins.groovy.lang.resolve.api.Arguments
fun HighlightSink.highlightUnknownArgs(highlightElement: PsiElement) {
registerProblem(highlightElement, ProblemHighlightType.WEAK_WARNING, message("cannot.infer.argument.types"))
}
fun HighlightSink.highlightCannotApplyError(invokedText: String, typesString: String, highlightElement: PsiElement) {
registerError(highlightElement, message("cannot.apply.method.or.closure", invokedText, typesString))
}
fun HighlightSink.highlightAmbiguousMethod(highlightElement: PsiElement) {
registerError(highlightElement, message("constructor.call.is.ambiguous"))
}
fun HighlightSink.highlightInapplicableMethod(result: GroovyMethodResult,
arguments: List<Argument>,
argumentList: GrArgumentList?,
highlightElement: PsiElement) {
val method = result.element
val containingClass = if (method is GrGdkMethod) method.staticMethod.containingClass else method.containingClass
val argumentString = argumentsString(arguments)
val methodName = method.name
if (containingClass == null) {
highlightCannotApplyError(methodName, argumentString, highlightElement)
return
}
val message: String
if (method is DefaultConstructor) {
message = message("cannot.apply.default.constructor", methodName)
}
else {
val factory = JavaPsiFacade.getElementFactory(method.project)
val containingType = factory.createType(containingClass, result.substitutor)
val canonicalText = containingType.internalCanonicalText
if (method.isConstructor) {
message = message("cannot.apply.constructor", methodName, canonicalText, argumentString)
}
else {
message = message("cannot.apply.method1", methodName, canonicalText, argumentString)
}
}
val fixes = generateCastFixes(result, arguments, argumentList)
registerProblem(highlightElement, ProblemHighlightType.GENERIC_ERROR, message, *fixes)
}
private fun argumentsString(arguments: List<Argument>): String {
return arguments.joinToString(", ", "(", ")") {
it.type?.internalCanonicalText ?: "?"
}
}
private fun generateCastFixes(result: GroovyMethodResult, arguments: Arguments, argumentList: GrArgumentList?): Array<out LocalQuickFix> {
val signature = createSignature(result.element, result.substitutor)
return GroovyTypeCheckVisitorHelper.genCastFixes(signature, arguments.map(Argument::type).toArray(PsiType.EMPTY_ARRAY), argumentList)
}
| apache-2.0 | 081fcd1a88390d8e71b215e4f350b5b2 | 47.648649 | 140 | 0.778611 | 4.806409 | false | false | false | false |
JetBrains/intellij-community | plugins/kotlin/jvm-debugger/core-fe10/src/org/jetbrains/kotlin/idea/debugger/KotlinFrameExtraVariablesProvider.kt | 1 | 7285 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.idea.debugger
import com.intellij.debugger.SourcePosition
import com.intellij.debugger.engine.FrameExtraVariablesProvider
import com.intellij.debugger.engine.evaluation.CodeFragmentKind
import com.intellij.debugger.engine.evaluation.EvaluationContext
import com.intellij.debugger.engine.evaluation.TextWithImports
import com.intellij.debugger.engine.evaluation.TextWithImportsImpl
import com.intellij.debugger.settings.DebuggerSettings
import com.intellij.openapi.application.runReadAction
import com.intellij.openapi.editor.Document
import com.intellij.openapi.fileEditor.FileDocumentManager
import com.intellij.openapi.util.TextRange
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
import com.intellij.psi.util.PsiTreeUtil
import com.intellij.util.text.CharArrayUtil
import org.jetbrains.kotlin.descriptors.PropertyDescriptor
import org.jetbrains.kotlin.idea.KotlinFileType
import org.jetbrains.kotlin.idea.base.psi.getLineEndOffset
import org.jetbrains.kotlin.idea.base.psi.getLineStartOffset
import org.jetbrains.kotlin.idea.base.psi.getTopmostElementAtOffset
import org.jetbrains.kotlin.idea.caches.resolve.analyzeWithAllCompilerChecks
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.resolve.BindingContext
import java.util.*
import kotlin.math.max
import kotlin.math.min
class KotlinFrameExtraVariablesProvider : FrameExtraVariablesProvider {
override fun isAvailable(sourcePosition: SourcePosition, evalContext: EvaluationContext): Boolean {
if (runReadAction { sourcePosition.line } < 0) return false
return sourcePosition.file.fileType == KotlinFileType.INSTANCE && DebuggerSettings.getInstance().AUTO_VARIABLES_MODE
}
override fun collectVariables(
sourcePosition: SourcePosition, evalContext: EvaluationContext, alreadyCollected: MutableSet<String>
): Set<TextWithImports> = runReadAction { findAdditionalExpressions(sourcePosition) }
}
private fun findAdditionalExpressions(position: SourcePosition): Set<TextWithImports> {
val line = position.line
val file = position.file
val vFile = file.virtualFile
val doc = if (vFile != null) FileDocumentManager.getInstance().getDocument(vFile) else null
if (doc == null || doc.lineCount == 0 || line > (doc.lineCount - 1)) {
return emptySet()
}
val offset = file.getLineStartOffset(line)?.takeIf { it > 0 } ?: return emptySet()
val elem = file.findElementAt(offset) ?: return emptySet()
val containingElement = getContainingElement(elem) ?: elem
val limit = getLineRangeForElement(containingElement, doc)
var startLine = max(limit.startOffset, line)
while (startLine - 1 > limit.startOffset && shouldSkipLine(file, doc, startLine - 1)) {
startLine--
}
var endLine = min(limit.endOffset, line)
while (endLine + 1 < limit.endOffset && shouldSkipLine(file, doc, endLine + 1)) {
endLine++
}
val startOffset = file.getLineStartOffset(startLine) ?: return emptySet()
val endOffset = file.getLineEndOffset(endLine) ?: return emptySet()
if (startOffset >= endOffset) return emptySet()
val lineRange = TextRange(startOffset, endOffset)
if (lineRange.isEmpty) return emptySet()
val expressions = LinkedHashSet<TextWithImports>()
val variablesCollector = VariablesCollector(lineRange, expressions)
containingElement.accept(variablesCollector)
return expressions
}
private fun getContainingElement(element: PsiElement): KtElement? {
val contElement =
PsiTreeUtil.getParentOfType(element, KtDeclaration::class.java) ?: PsiTreeUtil.getParentOfType(element, KtElement::class.java)
if (contElement is KtProperty && contElement.isLocal) {
val parent = contElement.parent
return getContainingElement(parent)
}
if (contElement is KtDeclarationWithBody) {
return contElement.bodyExpression
}
return contElement
}
private fun getLineRangeForElement(containingElement: PsiElement, doc: Document): TextRange {
val elemRange = containingElement.textRange
return TextRange(doc.getLineNumber(elemRange.startOffset), doc.getLineNumber(elemRange.endOffset))
}
private fun shouldSkipLine(file: PsiFile, doc: Document, line: Int): Boolean {
val start = CharArrayUtil.shiftForward(doc.charsSequence, doc.getLineStartOffset(line), " \n\t")
val end = doc.getLineEndOffset(line)
if (start >= end) {
return true
}
val elemAtOffset = file.findElementAt(start)
val topmostElementAtOffset = getTopmostElementAtOffset(elemAtOffset!!, start)
return topmostElementAtOffset !is KtDeclaration
}
private class VariablesCollector(
private val myLineRange: TextRange,
private val myExpressions: MutableSet<TextWithImports>
) : KtTreeVisitorVoid() {
override fun visitKtElement(element: KtElement) {
if (element.isInRange()) {
super.visitKtElement(element)
}
}
override fun visitQualifiedExpression(expression: KtQualifiedExpression) {
if (expression.isInRange()) {
val selector = expression.selectorExpression
if (selector is KtReferenceExpression) {
if (isRefToProperty(selector)) {
myExpressions.add(expression.createText())
return
}
}
}
super.visitQualifiedExpression(expression)
}
private fun isRefToProperty(expression: KtReferenceExpression): Boolean {
// NB: analyze() cannot be called here, because DELEGATED_PROPERTY_RESOLVED_CALL will be always null
// Looks like a bug
@Suppress("DEPRECATION")
val context = expression.analyzeWithAllCompilerChecks().bindingContext
val descriptor = context[BindingContext.REFERENCE_TARGET, expression]
if (descriptor is PropertyDescriptor) {
val getter = descriptor.getter
return (getter == null || context[BindingContext.DELEGATED_PROPERTY_RESOLVED_CALL, getter] == null) && descriptor.compileTimeInitializer == null
}
return false
}
override fun visitReferenceExpression(expression: KtReferenceExpression) {
if (expression.isInRange()) {
if (isRefToProperty(expression)) {
myExpressions.add(expression.createText())
}
}
super.visitReferenceExpression(expression)
}
private fun KtElement.isInRange(): Boolean = myLineRange.intersects(this.textRange)
private fun KtElement.createText(): TextWithImports = TextWithImportsImpl(CodeFragmentKind.EXPRESSION, this.text)
override fun visitClass(klass: KtClass) {
// Do not show expressions used in local classes
}
override fun visitNamedFunction(function: KtNamedFunction) {
// Do not show expressions used in local functions
}
override fun visitObjectLiteralExpression(expression: KtObjectLiteralExpression) {
// Do not show expressions used in anonymous objects
}
override fun visitLambdaExpression(lambdaExpression: KtLambdaExpression) {
// Do not show expressions used in lambdas
}
} | apache-2.0 | c7a02a0a0cda46cc483fd448388427bb | 39.254144 | 156 | 0.735896 | 5.055517 | false | false | false | false |
allotria/intellij-community | plugins/ide-features-trainer/src/training/actions/RestartLessonAction.kt | 2 | 1086 | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package training.actions
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.AnActionEvent
import icons.FeaturesTrainerIcons
import training.learn.CourseManager
import training.learn.lesson.LessonManager
import training.statistic.StatisticBase
import training.ui.LearningUiManager
class RestartLessonAction : AnAction(FeaturesTrainerIcons.Img.ResetLesson) {
override fun actionPerformed(e: AnActionEvent) {
val activeToolWindow = LearningUiManager.activeToolWindow ?: return
val lesson = LessonManager.instance.currentLesson ?: return
StatisticBase.logLessonStopped(StatisticBase.LessonStopReason.RESTART)
CourseManager.instance.openLesson(activeToolWindow.project, lesson)
}
override fun update(e: AnActionEvent) {
val activeToolWindow = LearningUiManager.activeToolWindow
e.presentation.isEnabled = activeToolWindow != null && activeToolWindow.project == e.project
}
}
| apache-2.0 | 8a4f127e4c2a0d17fbc41351519c3988 | 44.25 | 140 | 0.816759 | 4.914027 | false | false | false | false |
allotria/intellij-community | plugins/github/src/org/jetbrains/plugins/github/ui/util/JListHoveredRowMaterialiser.kt | 2 | 3914 | // 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.ui.util
import com.intellij.ui.ExpandedItemListCellRendererWrapper
import java.awt.Component
import java.awt.event.*
import javax.swing.JList
import javax.swing.ListCellRenderer
import javax.swing.event.ListDataEvent
import javax.swing.event.ListDataListener
import javax.swing.event.ListSelectionEvent
import javax.swing.event.ListSelectionListener
import kotlin.properties.Delegates
/**
* Materializes a concrete component in a hovered list cell that matches the ones painted by the renderer
*/
class JListHoveredRowMaterialiser<T> private constructor(private val list: JList<T>,
private val cellRenderer: ListCellRenderer<T>) {
private var hoveredIndex: Int by Delegates.observable(-1) { _, oldValue, newValue ->
if (newValue != oldValue)
materialiseRendererAt(newValue)
}
private var rendererComponent: Component? = null
private val listRowHoverListener = object : MouseMotionAdapter() {
override fun mouseMoved(e: MouseEvent) {
val point = e.point
val idx = list.locationToIndex(point)
if (idx >= 0 && list.getCellBounds(idx, idx).contains(point)) {
hoveredIndex = idx
}
else {
hoveredIndex = -1
}
}
}
private val listDataListener = object : ListDataListener {
override fun contentsChanged(e: ListDataEvent) {
if (hoveredIndex in e.index0..e.index1) materialiseRendererAt(hoveredIndex)
}
override fun intervalRemoved(e: ListDataEvent) {
if (hoveredIndex > e.index0 || hoveredIndex > e.index1) hoveredIndex = -1
}
override fun intervalAdded(e: ListDataEvent) {
if (hoveredIndex > e.index0 || hoveredIndex > e.index1) hoveredIndex = -1
}
}
private val listPresentationListener = object : FocusListener,
ListSelectionListener,
ComponentAdapter() {
override fun focusLost(e: FocusEvent) = materialiseRendererAt(hoveredIndex)
override fun focusGained(e: FocusEvent) = materialiseRendererAt(hoveredIndex)
override fun valueChanged(e: ListSelectionEvent) = materialiseRendererAt(hoveredIndex)
override fun componentResized(e: ComponentEvent) = materialiseRendererAt(hoveredIndex)
}
private fun materialiseRendererAt(index: Int) {
if (index < 0 || index > list.model.size - 1) {
rendererComponent?.let { list.remove(it) }
rendererComponent = null
return
}
val cellValue = list.model.getElementAt(index)
val selected = list.isSelectedIndex(index)
val focused = list.hasFocus() && selected
rendererComponent = cellRenderer.getListCellRendererComponent(list, cellValue, index, selected, focused).apply {
list.add(this)
bounds = list.getCellBounds(index, index)
validate()
repaint()
}
}
companion object {
/**
* [cellRenderer] should be an instance different from one in the list
*/
fun <T> install(list: JList<T>, cellRenderer: ListCellRenderer<T>): JListHoveredRowMaterialiser<T> {
if (list.cellRenderer === cellRenderer
|| (list.cellRenderer as? ExpandedItemListCellRendererWrapper)?.wrappee === cellRenderer)
error("cellRenderer should be an instance different from list cell renderer")
return JListHoveredRowMaterialiser(list, cellRenderer).also {
with(list) {
addMouseMotionListener(it.listRowHoverListener)
addFocusListener(it.listPresentationListener)
addComponentListener(it.listPresentationListener)
addListSelectionListener(it.listPresentationListener)
model.addListDataListener(it.listDataListener)
}
}
}
}
} | apache-2.0 | cc361c5f2cb378d78f1d3be2d15c0d67 | 36.285714 | 140 | 0.692897 | 4.935687 | false | false | false | false |
genonbeta/TrebleShot | app/src/main/java/org/monora/uprotocol/client/android/receiver/BgBroadcastReceiver.kt | 1 | 5730 | /*
* Copyright (C) 2021 Veli Tasalı
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.monora.uprotocol.client.android.receiver
import android.content.BroadcastReceiver
import android.content.ClipData
import android.content.ClipboardManager
import android.content.Context
import android.content.Intent
import android.widget.Toast
import androidx.lifecycle.LifecycleService
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import org.monora.uprotocol.client.android.R
import org.monora.uprotocol.client.android.backend.Backend
import org.monora.uprotocol.client.android.data.ClientRepository
import org.monora.uprotocol.client.android.data.TransferRepository
import org.monora.uprotocol.client.android.data.TransferTaskRepository
import org.monora.uprotocol.client.android.database.model.SharedText
import org.monora.uprotocol.client.android.database.model.Transfer
import org.monora.uprotocol.client.android.database.model.UClient
import org.monora.uprotocol.client.android.util.NotificationBackend
import org.monora.uprotocol.core.TransportSeat
import org.monora.uprotocol.core.persistence.PersistenceProvider
import org.monora.uprotocol.core.protocol.ConnectionFactory
import javax.inject.Inject
@AndroidEntryPoint
class BgBroadcastReceiver : BroadcastReceiver() {
@Inject
lateinit var backend: Backend
@Inject
lateinit var clientRepository: ClientRepository
@Inject
lateinit var connectionFactory: ConnectionFactory
@Inject
lateinit var persistenceProvider: PersistenceProvider
@Inject
lateinit var transferRepository: TransferRepository
@Inject
lateinit var transferTaskRepository: TransferTaskRepository
@Inject
lateinit var transportSeat: TransportSeat
override fun onReceive(context: Context, intent: Intent) {
when (intent.action) {
ACTION_FILE_TRANSFER -> {
val client: UClient? = intent.getParcelableExtra(EXTRA_CLIENT)
val transfer: Transfer? = intent.getParcelableExtra(EXTRA_TRANSFER)
val notificationId = intent.getIntExtra(NotificationBackend.EXTRA_NOTIFICATION_ID, -1)
val isAccepted = intent.getBooleanExtra(EXTRA_ACCEPTED, false)
backend.services.notifications.backend.cancel(notificationId)
if (client != null && transfer != null) {
if (isAccepted) backend.applicationScope.launch(Dispatchers.IO) {
transferRepository.getTransferDetailDirect(transfer.id)?.let { transferDetail ->
transferTaskRepository.toggleTransferOperation(transfer, client, transferDetail)
}
} else {
transferTaskRepository.rejectTransfer(transfer, client)
}
}
}
ACTION_DEVICE_KEY_CHANGE_APPROVAL -> {
val client: UClient? = intent.getParcelableExtra(EXTRA_CLIENT)
val notificationId = intent.getIntExtra(NotificationBackend.EXTRA_NOTIFICATION_ID, -1)
backend.services.notifications.backend.cancel(notificationId)
if (client != null && intent.getBooleanExtra(EXTRA_ACCEPTED, false)) {
persistenceProvider.approveInvalidationOfCredentials(client)
}
}
ACTION_CLIPBOARD_COPY -> {
val notificationId = intent.getIntExtra(NotificationBackend.EXTRA_NOTIFICATION_ID, -1)
val sharedText: SharedText? = intent.getParcelableExtra(EXTRA_SHARED_TEXT)
backend.services.notifications.backend.cancel(notificationId)
if (sharedText != null) {
val cbManager = context.applicationContext.getSystemService(
LifecycleService.CLIPBOARD_SERVICE
) as ClipboardManager
cbManager.setPrimaryClip(ClipData.newPlainText("receivedText", sharedText.text))
Toast.makeText(context, R.string.copy_text_to_clipboard_success, Toast.LENGTH_SHORT).show()
}
}
ACTION_STOP_ALL_TASKS -> backend.cancelAllTasks()
}
}
companion object {
const val ACTION_CLIPBOARD_COPY = "org.monora.uprotocol.client.android.action.CLIPBOARD_COPY"
const val ACTION_DEVICE_KEY_CHANGE_APPROVAL = "org.monora.uprotocol.client.android.action.DEVICE_APPROVAL"
const val ACTION_FILE_TRANSFER = "org.monora.uprotocol.client.android.action.FILE_TRANSFER"
const val ACTION_PIN_USED = "org.monora.uprotocol.client.android.transaction.action.PIN_USED"
const val ACTION_STOP_ALL_TASKS = "org.monora.uprotocol.client.android.transaction.action.STOP_ALL_TASKS"
const val EXTRA_SHARED_TEXT = "extraText"
const val EXTRA_CLIENT = "extraClient"
const val EXTRA_TRANSFER = "extraTransfer"
const val EXTRA_ACCEPTED = "extraAccepted"
}
}
| gpl-2.0 | 76bec4355a0e4f2c39faaaed54b17a04 | 41.437037 | 114 | 0.702391 | 4.863328 | false | false | false | false |
leafclick/intellij-community | platform/built-in-server/testSrc/org/jetbrains/ide/BuiltInWebServerTest.kt | 1 | 4970 | // 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.ide
import com.google.common.net.UrlEscapers
import com.intellij.openapi.application.AppUIExecutor
import com.intellij.openapi.application.impl.coroutineDispatchingContext
import com.intellij.openapi.application.impl.inWriteAction
import com.intellij.openapi.module.EmptyModuleType
import com.intellij.openapi.module.ModuleManager
import com.intellij.openapi.project.Project
import com.intellij.openapi.roots.ModuleRootModificationUtil
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.util.text.StringUtil
import com.intellij.openapi.vfs.LocalFileSystem
import com.intellij.openapi.vfs.refreshVfs
import com.intellij.testFramework.ApplicationRule
import com.intellij.testFramework.TemporaryDirectory
import com.intellij.testFramework.createHeavyProject
import com.intellij.testFramework.use
import com.intellij.util.io.createDirectories
import com.intellij.util.io.systemIndependentPath
import com.intellij.util.io.write
import com.intellij.util.io.writeChild
import io.netty.handler.codec.http.HttpResponseStatus
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.withContext
import org.assertj.core.api.Assertions.assertThat
import org.junit.BeforeClass
import org.junit.ClassRule
import org.junit.Rule
import org.junit.Test
internal class BuiltInWebServerTest : BuiltInServerTestCase() {
override val urlPathPrefix: String
get() = "/${projectRule.project.name}"
@Test
@TestManager.TestDescriptor(filePath = "foo/index.html", doNotCreate = true, status = 200)
fun `get only dir without end slash`() {
testIndex("foo")
}
@Test
@TestManager.TestDescriptor(filePath = "foo/index.html", doNotCreate = true, status = 200)
fun `get only dir with end slash`() {
testIndex("foo/")
}
@Test
@TestManager.TestDescriptor(filePath = "foo/index.html", doNotCreate = true, status = 200)
fun `get index file and then dir`() {
testIndex("foo/index.html", "foo")
}
private fun testIndex(vararg paths: String) = runBlocking {
val project = projectRule.project
val newPath = tempDirManager.newPath()
newPath.writeChild(manager.filePath!!, "hello")
newPath.refreshVfs()
createModule(newPath.systemIndependentPath, project)
for (path in paths) {
doTest(path) {
assertThat(it.inputStream.reader().readText()).isEqualTo("hello")
}
}
}
}
private suspend fun createModule(systemIndependentPath: String, project: Project) {
withContext(AppUIExecutor.onUiThread().inWriteAction().coroutineDispatchingContext()) {
val module = ModuleManager.getInstance(project).newModule("$systemIndependentPath/test.iml", EmptyModuleType.EMPTY_MODULE)
ModuleRootModificationUtil.addContentRoot(module, systemIndependentPath)
}
}
internal class HeavyBuiltInWebServerTest {
companion object {
@JvmField
@ClassRule
val appRule = ApplicationRule()
@BeforeClass
@JvmStatic
fun runServer() {
BuiltInServerManager.getInstance().waitForStart()
}
}
@Rule
@JvmField
val tempDirManager = TemporaryDirectory()
@Test
fun `path outside of project`() = runBlocking {
val projectDir = tempDirManager.newPath().resolve("foo/bar")
createHeavyProject(projectDir.resolve("test.ipr")).use { project ->
projectDir.createDirectories()
val projectDirPath = projectDir.systemIndependentPath
LocalFileSystem.getInstance().refreshAndFindFileByPath(projectDirPath)
createModule(projectDirPath, project)
val path = tempDirManager.newPath("doNotExposeMe.txt").write("doNotExposeMe").systemIndependentPath
val relativePath = FileUtil.getRelativePath(project.basePath!!, path, '/')
val webPath = StringUtil.replace(UrlEscapers.urlPathSegmentEscaper().escape("${project.name}/$relativePath"), "%2F", "/")
testUrl("http://localhost:${BuiltInServerManager.getInstance().port}/$webPath", HttpResponseStatus.NOT_FOUND)
}
}
@Test
fun `file in hidden folder`() = runBlocking {
val projectDir = tempDirManager.newPath().resolve("foo/bar")
createHeavyProject(projectDir.resolve("test.ipr")).use { project ->
projectDir.createDirectories()
val projectDirPath = projectDir.systemIndependentPath
LocalFileSystem.getInstance().refreshAndFindFileByPath(projectDirPath)
createModule(projectDirPath, project)
val dir = projectDir.resolve(".coverage")
dir.createDirectories()
val path = dir.resolve("foo").write("exposeMe").systemIndependentPath
val relativePath = FileUtil.getRelativePath(project.basePath!!, path, '/')
val webPath = StringUtil.replace(UrlEscapers.urlPathSegmentEscaper().escape("${project.name}/$relativePath"), "%2F", "/")
testUrl("http://localhost:${BuiltInServerManager.getInstance().port}/$webPath", HttpResponseStatus.OK)
}
}
} | apache-2.0 | 394e13cdeeb41da4e9685e78a4942f00 | 37.835938 | 140 | 0.757948 | 4.71537 | false | true | false | false |
leafclick/intellij-community | plugins/github/src/org/jetbrains/plugins/github/authentication/ui/GithubLoginPanel.kt | 1 | 5764 | // 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.github.authentication.ui
import com.intellij.openapi.application.runInEdt
import com.intellij.openapi.components.service
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.ValidationInfo
import com.intellij.ui.AnimatedIcon
import com.intellij.ui.components.fields.ExtendableTextComponent
import com.intellij.ui.components.fields.ExtendableTextField
import com.intellij.ui.components.panels.Wrapper
import org.jetbrains.plugins.github.api.GithubApiRequestExecutor
import org.jetbrains.plugins.github.api.GithubServerPath
import org.jetbrains.plugins.github.authentication.util.GHSecurityUtil
import org.jetbrains.plugins.github.ui.util.DialogValidationUtils
import org.jetbrains.plugins.github.ui.util.Validator
import org.jetbrains.plugins.github.util.GithubAsyncUtil
import org.jetbrains.plugins.github.util.submitBackgroundTask
import java.awt.event.ActionListener
import java.util.concurrent.CompletableFuture
import javax.swing.JTextField
class GithubLoginPanel(executorFactory: GithubApiRequestExecutor.Factory,
isAccountUnique: (name: String, server: GithubServerPath) -> Boolean,
val project: Project?,
isDialogMode: Boolean = true) : Wrapper() {
private var clientName: String = GHSecurityUtil.DEFAULT_CLIENT_NAME
private val serverTextField = ExtendableTextField(GithubServerPath.DEFAULT_HOST, 0)
private var tokenAcquisitionError: ValidationInfo? = null
private lateinit var currentUi: GithubCredentialsUI
private var passwordUi = GithubCredentialsUI.PasswordUI(serverTextField, clientName, ::switchToTokenUI, executorFactory, isAccountUnique,
isDialogMode)
private var tokenUi = GithubCredentialsUI.TokenUI(executorFactory, isAccountUnique, serverTextField, ::switchToPasswordUI, isDialogMode)
private val progressIcon = AnimatedIcon.Default()
private val progressExtension = ExtendableTextComponent.Extension { progressIcon }
init {
applyUi(passwordUi)
}
private fun switchToPasswordUI() {
applyUi(passwordUi)
}
private fun switchToTokenUI() {
applyUi(tokenUi)
}
private fun applyUi(ui: GithubCredentialsUI) {
currentUi = ui
setContent(currentUi.getPanel())
currentUi.getPreferredFocus().requestFocus()
tokenAcquisitionError = null
}
fun getPreferredFocus() = currentUi.getPreferredFocus()
fun doValidateAll(): List<ValidationInfo> {
return listOf(DialogValidationUtils.chain(
DialogValidationUtils.chain(
{ DialogValidationUtils.notBlank(serverTextField, "Server cannot be empty") },
serverPathValidator(serverTextField)),
currentUi.getValidator()),
{ tokenAcquisitionError })
.mapNotNull { it() }
}
private fun serverPathValidator(textField: JTextField): Validator {
return {
val text = textField.text
try {
GithubServerPath.from(text)
null
}
catch (e: Exception) {
ValidationInfo("$text is not a valid server path:\n${e.message}", textField)
}
}
}
private fun setBusy(busy: Boolean) {
if (busy) {
if (!serverTextField.extensions.contains(progressExtension))
serverTextField.addExtension(progressExtension)
}
else {
serverTextField.removeExtension(progressExtension)
}
serverTextField.isEnabled = !busy
currentUi.setBusy(busy)
}
fun acquireLoginAndToken(progressIndicator: ProgressIndicator): CompletableFuture<Pair<String, String>> {
setBusy(true)
tokenAcquisitionError = null
val server = getServer()
val executor = currentUi.createExecutor()
return service<ProgressManager>()
.submitBackgroundTask(project, "Not Visible", true, progressIndicator) {
currentUi.acquireLoginAndToken(server, executor, it)
}.whenComplete { _, throwable ->
runInEdt {
setBusy(false)
if (throwable != null && !GithubAsyncUtil.isCancellation(throwable)) {
tokenAcquisitionError = currentUi.handleAcquireError(throwable)
}
}
}
}
fun getServer(): GithubServerPath = GithubServerPath.from(
serverTextField.text.trim())
fun setServer(path: String, editable: Boolean = true) {
serverTextField.apply {
text = path
isEditable = editable
}
}
fun setCredentials(login: String? = null, password: String? = null, editableLogin: Boolean = true) {
if (login != null) {
passwordUi.setLogin(login, editableLogin)
tokenUi.setFixedLogin(if (editableLogin) null else login)
}
if (password != null) passwordUi.setPassword(password)
applyUi(passwordUi)
}
fun setToken(token: String? = null) {
if (token != null) tokenUi.setToken(token)
applyUi(tokenUi)
}
fun setError(exception: Throwable) {
tokenAcquisitionError = currentUi.handleAcquireError(exception)
}
fun setLoginListener(listener: ActionListener) {
passwordUi.setLoginAction(listener)
tokenUi.setLoginAction(listener)
}
fun setCancelListener(listener: ActionListener) {
passwordUi.setCancelAction(listener)
tokenUi.setCancelAction(listener)
}
fun setLoginButtonVisible(visible: Boolean) {
passwordUi.setLoginButtonVisible(visible)
tokenUi.setLoginButtonVisible(visible)
}
fun setCancelButtonVisible(visible: Boolean) {
passwordUi.setCancelButtonVisible(visible)
tokenUi.setCancelButtonVisible(visible)
}
} | apache-2.0 | 36b33beda670b6cfed456dfedaabce84 | 34.152439 | 140 | 0.732304 | 4.843697 | false | false | false | false |
code-helix/slatekit | src/lib/kotlin/slatekit-meta/src/main/kotlin/slatekit/meta/KTypes.kt | 1 | 7154 | package slatekit.meta
import slatekit.common.*
import slatekit.common.crypto.EncDouble
import slatekit.common.crypto.EncInt
import slatekit.common.crypto.EncLong
import slatekit.common.crypto.EncString
import slatekit.common.ids.UPID
import slatekit.common.types.Content
import slatekit.common.types.ContentFile
//import java.time.*
import org.threeten.bp.*
import slatekit.common.ext.toStringNumeric
import slatekit.common.ext.toStringTime
import slatekit.common.ext.toStringYYYYMMDD
import slatekit.common.ids.ULID
import slatekit.utils.smartvalues.SmartValue
import slatekit.utils.smartvalues.SmartValued
import slatekit.common.values.Vars
import kotlin.reflect.KClass
import kotlin.reflect.KType
import kotlin.reflect.full.createType
object KTypes {
val KStringClass = String::class
val KBoolClass = Boolean::class
val KShortClass = Short::class
val KIntClass = Int::class
val KLongClass = Long::class
val KFloatClass = Float::class
val KDoubleClass = Double::class
val KDateTimeClass = DateTime::class
val KLocalDateClass = LocalDate::class
val KLocalTimeClass = LocalTime::class
val KLocalDateTimeClass = LocalDateTime::class
val KZonedDateTimeClass = ZonedDateTime::class
val KInstantClass = Instant::class
val KUUIDClass = java.util.UUID::class
val KUPIDClass = UPID::class
val KDocClass = ContentFile::class
val KVarsClass = Vars::class
val KSmartValueClass = SmartValue::class
val KEnumLikeClass = EnumLike::class
val KContentClass = Content::class
val KDecStringClass = EncString::class
val KDecIntClass = EncInt::class
val KDecLongClass = EncLong::class
val KDecDoubleClass = EncDouble::class
val KAnyClass = EncDouble::class
val KStringType = String::class.createType()
val KBoolType = Boolean::class.createType()
val KShortType = Short::class.createType()
val KIntType = Int::class.createType()
val KLongType = Long::class.createType()
val KFloatType = Float::class.createType()
val KDoubleType = Double::class.createType()
val KDateTimeType = DateTime::class.createType()
val KLocalDateType = LocalDate::class.createType()
val KLocalTimeType = LocalTime::class.createType()
val KLocalDateTimeType = LocalDateTime::class.createType()
val KZonedDateTimeType = ZonedDateTime::class.createType()
val KInstantType = Instant::class.createType()
val KUUIDType = java.util.UUID::class.createType()
val KULIDType = ULID::class.createType()
val KUPIDType = UPID::class.createType()
val KDocType = ContentFile::class.createType()
val KVarsType = Vars::class.createType()
val KSmartValueType = SmartValue::class.createType()
val KSmartValuedType = SmartValued::class.createType()
val KEnumLikeType = EnumLike::class.createType()
val KContentType = Content::class.createType()
val KDecStringType = EncString::class.createType()
val KDecIntType = EncInt::class.createType()
val KDecLongType = EncLong::class.createType()
val KDecDoubleType = EncDouble::class.createType()
val KAnyType = Any::class.createType()
fun getClassFromType(tpe: KType): KClass<*> {
return when (tpe) {
// Basic types
KStringType -> KStringClass
KBoolType -> KBoolClass
KShortType -> KShortClass
KIntType -> KIntClass
KLongType -> KLongClass
KFloatType -> KFloatClass
KDoubleType -> KDoubleClass
KDateTimeType -> KDateTimeClass
KLocalDateType -> KLocalDateClass
KLocalTimeType -> KLocalTimeClass
KLocalDateTimeType -> KLocalDateTimeClass
KZonedDateTimeType -> KZonedDateTimeClass
KInstantType -> KInstantClass
KUUIDType -> KUUIDClass
KUPIDType -> KUPIDClass
KDocType -> KDocClass
KVarsType -> KVarsClass
KSmartValueType -> KSmartValueClass
KContentType -> KContentClass
KDecStringType -> KDecStringClass
KDecIntType -> KDecIntClass
KDecLongType -> KDecLongClass
KDecDoubleType -> KDecDoubleClass
else -> tpe.classifier as KClass<*>
}
}
fun getTypeExample(name: String, tpe: KType, textSample: String = "'abc'"): String {
return when (tpe) {
// Basic types
KStringType -> textSample
KBoolType -> "true"
KShortType -> "0"
KIntType -> "10"
KLongType -> "100"
KFloatType -> "10.0"
KDoubleType -> "10.00"
KDateTimeType -> DateTime.now().toStringNumeric("")
KLocalDateType -> DateTime.now().toStringYYYYMMDD("")
KLocalTimeType -> DateTime.now().toStringTime("")
KLocalDateTimeType -> DateTime.now().toStringNumeric()
KZonedDateTimeType -> DateTime.now().toStringNumeric()
KInstantType -> DateTime.now().toStringNumeric()
KUUIDType -> "782d1a4a-9223-4c49-96ee-cecb4c368a61"
KUPIDType -> "prefix:782d1a4a-9223-4c49-96ee-cecb4c368a61"
KDocType -> "user://myapp/conf/abc.conf"
KVarsType -> "a=1,b=2,c=3"
KSmartValueType -> "123-456-7890"
KContentType -> "[email protected]"
KDecStringType -> "ALK342481SFA"
KDecIntType -> "ALK342481SFA"
KDecLongType -> "ALK342481SFA"
KDecDoubleType -> "ALK342481SFA"
else -> name
}
}
fun isBasicType(tpe: KType): Boolean {
return when (tpe) {
// Basic types
KStringType -> true
KBoolType -> true
KShortType -> true
KIntType -> true
KLongType -> true
KFloatType -> true
KDoubleType -> true
KDateTimeType -> true
KLocalDateType -> true
KLocalTimeType -> true
KLocalDateTimeType -> true
KZonedDateTimeType -> true
KInstantType -> true
KUUIDType -> true
KUPIDType -> true
KSmartValueType -> true
KDecStringType -> true
KDecIntType -> true
KDecLongType -> true
KDecDoubleType -> true
else -> false
}
}
fun isBasicType(cls: KClass<*>): Boolean {
return when (cls) {
// Basic types
KStringClass -> true
KBoolClass -> true
KShortClass -> true
KIntClass -> true
KLongClass -> true
KFloatClass -> true
KDoubleClass -> true
KDateTimeClass -> true
KLocalDateClass -> true
KLocalTimeClass -> true
KLocalDateTimeClass -> true
KZonedDateTimeClass -> true
KInstantClass -> true
KUUIDClass -> true
KUPIDClass -> true
KSmartValueClass -> true
KDecStringClass -> true
KDecIntClass -> true
KDecLongClass -> true
KDecDoubleClass -> true
else -> false
}
}
}
| apache-2.0 | 75e639c310b0ec255461704b9dccf5aa | 36.067358 | 88 | 0.627621 | 4.889952 | false | false | false | false |
zdary/intellij-community | plugins/package-search/src/com/jetbrains/packagesearch/intellij/plugin/extensibility/ProjectModule.kt | 1 | 1826 | package com.jetbrains.packagesearch.intellij.plugin.extensibility
import com.intellij.openapi.module.Module
import com.intellij.openapi.util.NlsSafe
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.pom.Navigatable
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.PackageVersion
internal data class ProjectModule(
val name: String,
val nativeModule: Module,
val parent: ProjectModule?,
val buildFile: VirtualFile,
val buildSystemType: BuildSystemType,
val moduleType: ProjectModuleType
) {
var getNavigatableDependency: (groupId: String, artifactId: String, version: PackageVersion) -> Navigatable? =
{ _, _, _ -> null }
@NlsSafe
fun getFullName(): String {
if (parent != null) {
return parent.getFullName() + ":$name"
}
return name
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is ProjectModule) return false
if (name != other.name) return false
if (nativeModule.moduleFilePath != other.nativeModule.moduleFilePath) return false // This can't be automated
if (parent != other.parent) return false
if (buildFile.path != other.buildFile.path) return false
if (buildSystemType != other.buildSystemType) return false
if (moduleType != other.moduleType) return false
return true
}
override fun hashCode(): Int {
var result = name.hashCode()
result = 31 * result + nativeModule.moduleFilePath.hashCode()
result = 31 * result + (parent?.hashCode() ?: 0)
result = 31 * result + buildFile.path.hashCode()
result = 31 * result + buildSystemType.hashCode()
result = 31 * result + moduleType.hashCode()
return result
}
}
| apache-2.0 | 069aa686e37319626a92ccb0daf3e1fc | 34.115385 | 117 | 0.66977 | 4.742857 | false | false | false | false |
faceofcat/Tesla-Core-Lib | src/main/kotlin/net/ndrei/teslacorelib/energy/systems/ForgeEnergySystem.kt | 1 | 3043 | package net.ndrei.teslacorelib.energy.systems
import net.minecraft.item.ItemStack
import net.minecraft.tileentity.TileEntity
import net.minecraft.util.EnumFacing
import net.minecraftforge.common.capabilities.Capability
import net.minecraftforge.energy.CapabilityEnergy
import net.minecraftforge.energy.IEnergyStorage
import net.modcrafters.mclib.energy.IGenericEnergyStorage
import net.ndrei.teslacorelib.energy.IEnergySystem
object ForgeEnergySystem : IEnergySystem {
const val MODID = "minecraft"
override val ModId: String get() = MODID
override fun hasCapability(capability: Capability<*>)
= (capability == CapabilityEnergy.ENERGY)
@Suppress("UNCHECKED_CAST")
override fun <T> wrapCapability(capability: Capability<T>, energy: IGenericEnergyStorage): T?
= if (capability == CapabilityEnergy.ENERGY) (Wrapper(energy) as? T) else null
class Wrapper(val energy: IGenericEnergyStorage) : IEnergyStorage {
override fun canExtract() = this.energy.canTake
override fun getMaxEnergyStored() = this.energy.capacity.toInt()
override fun getEnergyStored() = this.energy.stored.toInt()
override fun canReceive() = this.energy.canGive
override fun extractEnergy(maxExtract: Int, simulate: Boolean)
= this.energy.takePower(maxExtract.toLong(), simulate).toInt()
override fun receiveEnergy(maxReceive: Int, simulate: Boolean)
= this.energy.givePower(maxReceive.toLong(), simulate).toInt()
}
override fun wrapTileEntity(te: TileEntity, side: EnumFacing): IGenericEnergyStorage? {
if (te is IEnergyStorage) {
// maybe someone didn't understand capabilities too well
return ReverseWrapper(te)
}
if (te.hasCapability(CapabilityEnergy.ENERGY, side)) {
val energy = te.getCapability(CapabilityEnergy.ENERGY, side)
if (energy != null) {
return ReverseWrapper(energy)
}
}
return null
}
override fun wrapItemStack(stack: ItemStack): IGenericEnergyStorage? {
if (!stack.isEmpty && stack.hasCapability(CapabilityEnergy.ENERGY, null)) {
val energy = stack.getCapability(CapabilityEnergy.ENERGY, null)
if (energy != null) {
return ReverseWrapper(energy)
}
}
return null
}
class ReverseWrapper(val energy: IEnergyStorage) : IGenericEnergyStorage {
override val capacity get() = this.energy.maxEnergyStored.toLong()
override val stored get() = this.energy.energyStored.toLong()
override val canGive get() = this.energy.canReceive()
override fun givePower(power: Long, simulated: Boolean)
= this.energy.receiveEnergy(power.toInt(), simulated).toLong()
override val canTake get() = this.energy.canExtract()
override fun takePower(power: Long, simulated: Boolean)
= this.energy.extractEnergy(power.toInt(), simulated).toLong()
}
}
| mit | 6aa81c30086ab9b293eef02bbc5779d4 | 40.121622 | 97 | 0.68255 | 4.784591 | false | false | false | false |
JuliusKunze/kotlin-native | backend.native/tests/codegen/coroutines/controlFlow_tryCatch1.kt | 1 | 1015 | package codegen.coroutines.controlFlow_tryCatch1
import kotlin.test.*
import kotlin.coroutines.experimental.*
import kotlin.coroutines.experimental.intrinsics.*
open class EmptyContinuation(override val context: CoroutineContext = EmptyCoroutineContext) : Continuation<Any?> {
companion object : EmptyContinuation()
override fun resume(value: Any?) {}
override fun resumeWithException(exception: Throwable) { throw exception }
}
suspend fun s1(): Int = suspendCoroutineOrReturn { x ->
println("s1")
x.resume(42)
COROUTINE_SUSPENDED
}
fun f1(): Int {
println("f1")
return 117
}
fun f2(): Int {
println("f2")
return 1
}
fun f3(x: Int, y: Int): Int {
println("f3")
return x + y
}
fun builder(c: suspend () -> Unit) {
c.startCoroutine(EmptyContinuation)
}
@Test fun runTest() {
var result = 0
builder {
val x = try {
s1()
} catch (t: Throwable) {
f2()
}
result = x
}
println(result)
} | apache-2.0 | a90f845b4851a38ea25a28e384bba03a | 18.538462 | 115 | 0.633498 | 3.888889 | false | true | false | false |
samirma/MeteoriteLandings | app/src/main/java/com/antonio/samir/meteoritelandingsspots/features/list/MeteoriteListFragment.kt | 1 | 11669 | package com.antonio.samir.meteoritelandingsspots.features.list
import android.Manifest.permission.ACCESS_FINE_LOCATION
import android.content.pm.PackageManager
import android.os.Bundle
import android.util.Log
import android.view.*
import android.view.View.*
import androidx.annotation.NonNull
import androidx.appcompat.widget.SearchView
import androidx.fragment.app.Fragment
import androidx.navigation.fragment.findNavController
import androidx.paging.PagedList
import androidx.recyclerview.widget.GridLayoutManager
import com.antonio.samir.meteoritelandingsspots.R
import com.antonio.samir.meteoritelandingsspots.data.Result
import com.antonio.samir.meteoritelandingsspots.data.Result.InProgress
import com.antonio.samir.meteoritelandingsspots.data.Result.Success
import com.antonio.samir.meteoritelandingsspots.data.repository.model.Meteorite
import com.antonio.samir.meteoritelandingsspots.databinding.FragmentMeteoriteListBinding
import com.antonio.samir.meteoritelandingsspots.features.detail.MeteoriteDetailFragment
import com.antonio.samir.meteoritelandingsspots.features.list.MeteoriteListFragmentDirections.Companion.toDetail
import com.antonio.samir.meteoritelandingsspots.features.list.MeteoriteListViewModel.ContentStatus.*
import com.antonio.samir.meteoritelandingsspots.features.list.recyclerView.MeteoriteAdapter
import com.antonio.samir.meteoritelandingsspots.features.list.recyclerView.SpacesItemDecoration
import com.antonio.samir.meteoritelandingsspots.ui.extension.isLandscape
import com.antonio.samir.meteoritelandingsspots.ui.extension.showActionBar
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.FlowPreview
import org.koin.androidx.viewmodel.ext.android.viewModel
import java.util.concurrent.atomic.AtomicBoolean
@FlowPreview
@ExperimentalCoroutinesApi
class MeteoriteListFragment : Fragment() {
private var layoutManager: GridLayoutManager? = null
private var meteoriteAdapter = MeteoriteAdapter().apply {
setHasStableIds(false)
}
private var meteoriteDetailFragment: MeteoriteDetailFragment? = null
private val viewModel: MeteoriteListViewModel by viewModel()
private var _binding: FragmentMeteoriteListBinding? = null
private val binding get() = _binding!!
private val shouldOpenMeteorite = AtomicBoolean(true)
private val redirectedToPortrait = AtomicBoolean(false)
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?,
): View {
_binding = FragmentMeteoriteListBinding.inflate(inflater, container, false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
showActionBar(getString(R.string.title))
meteoriteAdapter.clearSelectedMeteorite()
binding.meteoriteRV.adapter = meteoriteAdapter
binding.meteoriteRV.addItemDecoration(SpacesItemDecoration(
context = requireContext(),
verticalMargin = R.dimen.spacing,
horizontalMargin = R.dimen.horizontal_spacing
))
setupGridLayout()
observeLiveData()
setupLocation()
setHasOptionsMenu(true)
if (viewModel.filter.isBlank()) {
viewModel.loadMeteorites()
}
redirectedToPortrait.set(false)
}
private fun observeLiveData() {
observeMeteorites()
observeRecoveryAddressStatus()
observeNetworkLoadingStatus()
meteoriteAdapter.openMeteorite.observe(viewLifecycleOwner) {
shouldOpenMeteorite.set(true)
viewModel.selectMeteorite(it)
}
viewModel.selectedMeteorite.observe(viewLifecycleOwner) { meteorite ->
if (meteorite != null) {
if (isLandscape()) {
showMeteoriteLandscape(meteorite)
meteoriteAdapter.updateListUI(meteorite)
val position = meteoriteAdapter.getPosition(meteorite)
position?.let { binding.meteoriteRV.smoothScrollToPosition(it) }
} else {
if (shouldOpenMeteorite.get()) {
showMeteoritePortrait(meteorite)
} else {
//Should clean the selected meteorite when it is not shown
viewModel.clearSelectedMeteorite()
}
shouldOpenMeteorite.set(false)
}
}
}
}
private fun setupLocation() {
viewModel.isAuthorizationRequested().observe(viewLifecycleOwner, {
if (it) {
requestPermissions(arrayOf(ACCESS_FINE_LOCATION), LOCATION_REQUEST_CODE)
}
})
viewModel.updateLocation()
viewModel.getLocation().observe(viewLifecycleOwner, {
meteoriteAdapter.location = it
})
}
private fun observeMeteorites() {
viewModel.getContentStatus().observe(viewLifecycleOwner) { contentStatus ->
when (contentStatus) {
ShowContent -> showContent()
NoContent -> noResult()
Loading -> showProgressLoader()
}
}
viewModel.getMeteorites().observe(viewLifecycleOwner) { meteorites ->
onSuccess(meteorites)
}
}
private fun onSuccess(meteorites: PagedList<Meteorite>) {
if (meteorites.isEmpty()) {
noResult()
} else {
meteoriteAdapter.submitList(meteorites)
}
}
private fun observeRecoveryAddressStatus() {
viewModel.getRecoverAddressStatus().observe(viewLifecycleOwner, { status ->
when (status) {
is InProgress -> showAddressLoading(status.data)
is Success -> hideAddressLoading()
is Result.Error -> error(getString(R.string.general_error))
}
})
}
private fun observeNetworkLoadingStatus() {
viewModel.getNetworkLoadingStatus().observe(viewLifecycleOwner, {
when (it) {
is InProgress -> networkLoadingStarted()
is Success -> networkLoadingStopped()
else -> unableToFetch()
}
})
}
private fun noResult() {
error(getString(R.string.no_result_found))
hideContent()
}
private fun showAddressLoading(progress: Float?) {
val addressRecoverProgress = binding.addressRecoverProgress
progress?.let {
addressRecoverProgress.progress = it
addressRecoverProgress.secondaryProgress = it + 10
}
addressRecoverProgress.progressText = getString(R.string.loading_addresses)
addressRecoverProgress.visibility = VISIBLE
}
private fun hideAddressLoading() {
binding.addressRecoverProgress.visibility = GONE
}
private fun unableToFetch() {
error(getString(R.string.no_network))
}
private fun error(messageString: String) {
hideContent()
binding.progressLoader.visibility = INVISIBLE
binding.messageTV.visibility = VISIBLE
binding.messageTV.text = messageString
}
private fun showMeteoriteLandscape(meteorite: Meteorite) {
layoutManager?.spanCount = 1
if (meteoriteDetailFragment == null) {
binding.fragment?.visibility = VISIBLE
parentFragmentManager.beginTransaction()
.setCustomAnimations(
R.anim.fragment_slide_left_enter,
R.anim.fragment_slide_left_exit).apply {
val meteoriteId: String = meteorite.id.toString()
meteoriteDetailFragment = MeteoriteDetailFragment.newInstance(meteoriteId)
replace(R.id.fragment, meteoriteDetailFragment!!)
commit()
}
} else {
meteoriteDetailFragment?.setCurrentMeteorite(meteorite.id.toString())
}
}
private fun showMeteoritePortrait(meteorite: Meteorite) {
redirectedToPortrait.set(true)
findNavController().navigate(toDetail(meteorite.id.toString()))
}
private fun setupGridLayout() {
val columnCount = resources.getInteger(R.integer.list_column_count)
layoutManager = GridLayoutManager(requireContext(), columnCount)
binding.meteoriteRV.layoutManager = layoutManager
}
private fun networkLoadingStarted() {
try {
showContent()
} catch (e: Exception) {
Log.e(TAG, e.message, e)
}
}
private fun networkLoadingStopped() {
try {
binding.networkStatusLoading.visibility = INVISIBLE
showContent()
} catch (e: Exception) {
Log.e(TAG, e.message, e)
}
}
private fun showContent() {
binding.progressLoader.visibility = INVISIBLE
binding.container?.visibility = VISIBLE
binding.meteoriteRV.visibility = VISIBLE
binding.messageTV.visibility = INVISIBLE
}
private fun hideContent() {
binding.container?.visibility = INVISIBLE
binding.meteoriteRV.visibility = INVISIBLE
}
private fun showProgressLoader() {
binding.progressLoader.visibility = VISIBLE
binding.messageTV.visibility = INVISIBLE
hideContent()
}
override fun onRequestPermissionsResult(
requestCode: Int,
@NonNull permissions: Array<String>,
@NonNull grantResults: IntArray,
) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
if (requestCode == LOCATION_REQUEST_CODE) {
for (grantResult in grantResults) {
val isPermitted = grantResult == PackageManager.PERMISSION_GRANTED
if (isPermitted) {
viewModel.updateLocation()
}
}
}
}
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
inflater.inflate(R.menu.main, menu)
val searchView = menu.findItem(R.id.action_search).actionView as SearchView
setup(searchView)
super.onCreateOptionsMenu(menu, inflater)
}
private fun setup(searchView: SearchView?) {
if (searchView != null) {
with(searchView) {
isActivated = true
onActionViewExpanded()
isIconified = false
setQuery(viewModel.filter, false)
setOnQueryTextListener(object : SearchView.OnQueryTextListener {
override fun onQueryTextChange(query: String): Boolean {
if (!redirectedToPortrait.get() && query.isBlank()) {
onQueryTextSubmit(query)
}
return false
}
override fun onQueryTextSubmit(query: String): Boolean {
loadMeteorites(query)
return true
}
private fun loadMeteorites(query: String) {
viewModel.loadMeteorites(query)
}
})
}
}
}
override fun onDestroyView() {
super.onDestroyView()
_binding = null
}
companion object {
private val TAG = MeteoriteListFragment::class.java.simpleName
const val LOCATION_REQUEST_CODE = 11111
}
}
| mit | 2dd824f981896f8a748c863df41a21a3 | 31.77809 | 112 | 0.636387 | 5.631757 | false | false | false | false |
codeka/wwmmo | server/src/main/kotlin/au/com/codeka/warworlds/server/world/NotificationManager.kt | 1 | 1628 | package au.com.codeka.warworlds.server.world
import au.com.codeka.warworlds.common.Log
import au.com.codeka.warworlds.common.proto.DeviceInfo
import au.com.codeka.warworlds.common.proto.Empire
import au.com.codeka.warworlds.common.proto.Notification
import au.com.codeka.warworlds.server.store.DataStore
import com.google.firebase.messaging.FirebaseMessaging
import com.google.firebase.messaging.FirebaseMessagingException
import com.google.firebase.messaging.Message
import java.util.*
class NotificationManager {
fun start() {}
/**
* Sends the given [Notification] to the given [Empire].
* @param empire The [Empire] to send to.
* @param notification The [Notification] to send.
*/
fun sendNotification(empire: Empire, notification: Notification) {
val notificationBase64 = Base64.getEncoder().encodeToString(notification.encode())
val devices: List<DeviceInfo> = DataStore.i.empires().getDevicesForEmpire(empire.id)
for (device in devices) {
sendNotification(device, notificationBase64)
}
}
private fun sendNotification(device: DeviceInfo, notificationBase64: String) {
val msg = Message.builder()
.putData("notification", notificationBase64)
.setToken(device.fcm_device_info!!.token)
.build()
try {
val resp = FirebaseMessaging.getInstance().send(msg)
log.info("Firebase message sent: %s", resp)
} catch (e: FirebaseMessagingException) {
log.error("Error sending firebase notification: %s", e.errorCode, e)
}
}
companion object {
private val log = Log("EmpireManager")
val i = NotificationManager()
}
}
| mit | 9ff4dc386385b6a4738cb711c5d46c41 | 34.391304 | 88 | 0.733415 | 4.13198 | false | false | false | false |
fabmax/kool | buildSrc/src/main/java/PhysxJsGenerator.kt | 1 | 1140 | import de.fabmax.webidl.generator.js.JsInterfaceGenerator
import de.fabmax.webidl.parser.WebIdlParser
import org.gradle.api.DefaultTask
import org.gradle.api.tasks.Input
import org.gradle.api.tasks.TaskAction
import java.io.File
import java.io.FileNotFoundException
open class PhysxJsGenerator : DefaultTask() {
@Input
var idlSource = ""
@Input
var generatorOutput = "./generated"
@TaskAction
fun generate() {
val idlFile = File(idlSource)
if (!idlFile.exists()) {
throw FileNotFoundException("PhysX WebIDL definition not found!")
}
val model = WebIdlParser().parse(idlFile.path)
JsInterfaceGenerator().apply {
outputDirectory = generatorOutput
packagePrefix = "physx"
moduleName = "physx-js-webidl"
nullableAttributes += "PxBatchQueryDesc.preFilterShader"
nullableAttributes += "PxBatchQueryDesc.postFilterShader"
nullableParameters += "PxArticulationBase.createLink" to "parent"
nullableReturnValues += "PxArticulationLink.getInboundJoint"
}.generate(model)
}
}
| apache-2.0 | 108c8febb685d10cc18f0d82cb166a3e | 32.529412 | 77 | 0.682456 | 4.384615 | false | false | false | false |
Peekazoo/Peekazoo-Android | app/src/main/java/com/tofi/peekazoo/activities/SubmissionsActivity.kt | 1 | 2530 | package com.tofi.peekazoo.activities
import android.os.Bundle
import android.support.v7.widget.LinearLayoutManager
import com.tofi.peekazoo.R
import com.tofi.peekazoo.SharedPreferencesManager
import com.tofi.peekazoo.api.InkbunnyApi
import com.tofi.peekazoo.api.SubmissionRequestHelper
import com.tofi.peekazoo.api.WeasylApi
import com.tofi.peekazoo.di.components.ActivityComponent
import com.tofi.peekazoo.lists.adapters.SubmissionResultsAdapter
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import kotlinx.android.synthetic.main.activity_submissions.*
import javax.inject.Inject
class SubmissionsActivity : BaseActivity() {
@Inject
lateinit var sharedPreferencesManager: SharedPreferencesManager
@Inject
lateinit var inkbunnyApi: InkbunnyApi
@Inject
lateinit var weasylApi: WeasylApi
private lateinit var submissionRequestHelper: SubmissionRequestHelper
private var adapter: SubmissionResultsAdapter? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_submissions)
submissionRequestHelper = SubmissionRequestHelper(activityComponent)
val sid = sharedPreferencesManager.getStringPreference(SharedPreferencesManager.SESSION_ID, "")
if (sid.isBlank()) {
inkbunnyApi.login("guest", "")
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe({(sid, _, _) ->
sharedPreferencesManager.writeStringPreference(SharedPreferencesManager.SESSION_ID, sid)
startSearchRequest()
}, {})
} else {
startSearchRequest()
}
}
override fun inject(component: ActivityComponent) {
activityComponent.inject(this)
}
private fun startSearchRequest() {
submissionRequestHelper.fetchSubmissions()
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe({submissions ->
if (adapter == null) {
adapter = SubmissionResultsAdapter(activityComponent, submissions)
listSearchResults.adapter = adapter
listSearchResults.layoutManager = LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false)
}
})
}
}
| apache-2.0 | 0476555c069b6743d6342d1c05757217 | 35.142857 | 120 | 0.681818 | 5.511983 | false | false | false | false |
siosio/intellij-community | plugins/kotlin/completion/tests/testData/basic/common/shadowing/PreferMemberToExtension.kt | 4 | 611 | package ppp
class C {
val xxx = ""
fun xxx() = ""
fun xxx(p: Int) = ""
fun foo() {
xx<caret>
}
}
val C.xxx: Int
get() = 1
fun C.xxx() = 1
fun C.xxx(p: Int) = 1
fun C.xxx(p: String) = 1
// EXIST: { lookupString: "xxx", itemText: "xxx", tailText: null, typeText: "String" }
// EXIST: { lookupString: "xxx", itemText: "xxx", tailText: "()", typeText: "String" }
// EXIST: { lookupString: "xxx", itemText: "xxx", tailText: "(p: Int)", typeText: "String" }
// EXIST: { lookupString: "xxx", itemText: "xxx", tailText: "(p: String) for C in ppp", typeText: "Int" }
// NOTHING_ELSE
| apache-2.0 | 9a3ac57d13656006f5110b6eae356e61 | 24.458333 | 105 | 0.563011 | 2.980488 | false | false | false | false |
jwren/intellij-community | plugins/markdown/core/src/org/intellij/plugins/markdown/ui/actions/styling/CreateOrChangeListActionGroup.kt | 1 | 7704 | package org.intellij.plugins.markdown.ui.actions.styling
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.CommonDataKeys
import com.intellij.openapi.actionSystem.DefaultActionGroup
import com.intellij.openapi.actionSystem.ToggleAction
import com.intellij.openapi.application.runWriteAction
import com.intellij.openapi.command.executeCommand
import com.intellij.openapi.editor.Caret
import com.intellij.openapi.editor.Document
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.component1
import com.intellij.openapi.util.component2
import com.intellij.psi.PsiElement
import com.intellij.psi.util.siblings
import org.intellij.plugins.markdown.MarkdownBundle.messagePointer
import org.intellij.plugins.markdown.MarkdownIcons
import org.intellij.plugins.markdown.editor.lists.ListUtils.getListItemAt
import org.intellij.plugins.markdown.editor.lists.ListUtils.items
import org.intellij.plugins.markdown.editor.lists.ListUtils.list
import org.intellij.plugins.markdown.lang.MarkdownTokenTypes
import org.intellij.plugins.markdown.lang.psi.MarkdownPsiElementFactory
import org.intellij.plugins.markdown.lang.psi.impl.MarkdownFile
import org.intellij.plugins.markdown.lang.psi.impl.MarkdownList
import org.intellij.plugins.markdown.lang.psi.impl.MarkdownListItem
import org.intellij.plugins.markdown.util.hasType
import org.jetbrains.annotations.Nls
import java.util.function.Supplier
import javax.swing.Icon
/**
* Not expected to be used directly.
* Check [CreateOrChangeListPopupAction].
*/
internal class CreateOrChangeListActionGroup: DefaultActionGroup(
UnorderedList(),
OrderedList(),
CheckmarkList()
) {
override fun isPopup(): Boolean = true
class OrderedList: CreateListImpl(
text = messagePointer("markdown.create.list.popup.ordered.action.text"),
icon = MarkdownIcons.EditorActions.NumberedList
) {
override fun isSameMarker(markerElement: PsiElement): Boolean {
return !hasCheckbox(markerElement) && obtainMarkerText(markerElement)?.toIntOrNull() != null
}
override fun createMarkerText(index: Int): String {
return "${index + 1}."
}
}
class UnorderedList: CreateListImpl(
text = messagePointer("markdown.create.list.popup.unordered.action.text"),
icon = MarkdownIcons.EditorActions.BulletList
) {
override fun isSameMarker(markerElement: PsiElement): Boolean {
return !hasCheckbox(markerElement) && obtainMarkerText(markerElement) == "*"
}
override fun createMarkerText(index: Int): String {
return "*"
}
}
class CheckmarkList: CreateListImpl(
text = messagePointer("markdown.create.list.popup.checkmark.action.text"),
icon = MarkdownIcons.EditorActions.CheckmarkList
) {
override fun isSameMarker(markerElement: PsiElement): Boolean {
return hasCheckbox(markerElement)
}
override fun createMarkerText(index: Int): String {
return "${index + 1}. [ ]"
}
override fun processListElement(originalChild: MarkdownListItem, index: Int): PsiElement {
val (marker, checkbox) = MarkdownPsiElementFactory.createListMarkerWithCheckbox(
originalChild.project,
"${index + 1}.",
true
)
val addedMarker = originalChild.markerElement!!.replace(marker)
originalChild.addAfter(checkbox, addedMarker)
return originalChild
}
}
abstract class CreateListImpl(
text: Supplier<@Nls String>,
description: Supplier<@Nls String> = text,
icon: Icon
): ToggleAction(text, description, icon) {
override fun setSelected(event: AnActionEvent, state: Boolean) {
val project = event.project ?: return
val editor = event.getData(CommonDataKeys.EDITOR) ?: return
val caret = event.getData(CommonDataKeys.CARET) ?: return
val file = event.getData(CommonDataKeys.PSI_FILE) as? MarkdownFile ?: return
val caretOffset = caret.selectionStart
val document = editor.document
val list = findList(file, document, caretOffset)
runWriteAction {
executeCommand(project) {
when {
state && list == null -> createListFromText(project, document, caret)
state && list != null -> replaceList(list)
!state && list != null -> replaceListWithText(document, list)
}
}
}
}
override fun isSelected(event: AnActionEvent): Boolean {
val file = event.getData(CommonDataKeys.PSI_FILE) as? MarkdownFile ?: return false
val editor = event.getData(CommonDataKeys.EDITOR) ?: return false
val caretOffset = editor.caretModel.currentCaret.offset
val document = editor.document
val list = findList(file, document, caretOffset) ?: return false
val marker = list.items.firstOrNull()?.markerElement ?: return false
return isSameMarker(marker)
}
abstract fun isSameMarker(markerElement: PsiElement): Boolean
abstract fun createMarkerText(index: Int): String
open fun processListElement(originalChild: MarkdownListItem, index: Int): PsiElement {
val marker = MarkdownPsiElementFactory.createListMarker(originalChild.project, createMarkerText(index))
val originalMarker = originalChild.markerElement ?: return originalChild
if (hasCheckbox(originalMarker)) {
originalMarker.nextSibling?.delete()
}
originalMarker.replace(marker)
return originalChild
}
private fun replaceList(list: MarkdownList): MarkdownList {
val resultList = MarkdownPsiElementFactory.createEmptyList(list.project, true)
val children = list.firstChild?.siblings(forward = true, withSelf = true) ?: return list
var itemIndex = 0
for (child in children) {
when (child) {
is MarkdownListItem -> {
resultList.add(processListElement(child, itemIndex))
itemIndex += 1
}
else -> resultList.add(child)
}
}
return list.replace(resultList) as MarkdownList
}
private fun createListFromText(project: Project, document: Document, caret: Caret) {
val startLine = document.getLineNumber(caret.selectionStart)
val endLine = document.getLineNumber(caret.selectionEnd)
val text = document.charsSequence
val lines = (startLine..endLine).asSequence().map {
text.substring(document.getLineStartOffset(it), document.getLineEndOffset(it))
}
val list = MarkdownPsiElementFactory.createList(project, lines.asIterable(), ::createMarkerText)
document.replaceString(document.getLineStartOffset(startLine), document.getLineEndOffset(endLine), list.text)
}
companion object {
private fun findList(file: MarkdownFile, document: Document, offset: Int): MarkdownList? {
return file.getListItemAt(offset, document)?.list
}
private fun replaceListWithText(document: Document, list: MarkdownList) {
val firstItem = list.items.firstOrNull() ?: return
val builder = StringBuilder()
for (element in firstItem.siblings(forward = true)) {
val text = when (element) {
is MarkdownListItem -> element.itemText ?: ""
else -> element.text
}
builder.append(text)
}
val range = list.textRange
document.replaceString(range.startOffset, range.endOffset, builder.toString())
}
}
}
companion object {
private fun obtainMarkerText(markerElement: PsiElement): String? {
return markerElement.text?.trimEnd('.', ')', ' ')
}
private fun hasCheckbox(element: PsiElement): Boolean {
return element.nextSibling?.hasType(MarkdownTokenTypes.CHECK_BOX) == true
}
}
}
| apache-2.0 | 0e03c5bd84548014e566ee93ec43c953 | 38.106599 | 115 | 0.717549 | 4.802993 | false | false | false | false |
JetBrains/intellij-community | plugins/kotlin/kotlin.searching/src/org/jetbrains/kotlin/idea/searching/inheritors/DirectKotlinOverridingCallableSearch.kt | 1 | 4968 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.idea.searching.inheritors
import com.intellij.model.search.SearchService
import com.intellij.model.search.Searcher
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiMethod
import com.intellij.psi.search.SearchScope
import com.intellij.psi.search.searches.OverridingMethodsSearch
import com.intellij.util.*
import com.intellij.util.concurrency.annotations.RequiresReadLock
import org.jetbrains.kotlin.analysis.api.analyze
import org.jetbrains.kotlin.analysis.api.symbols.KtClassOrObjectSymbol
import org.jetbrains.kotlin.asJava.toLightMethods
import org.jetbrains.kotlin.idea.search.ideaExtensions.JavaOverridingMethodsSearcherFromKotlinParameters
import org.jetbrains.kotlin.idea.searching.inheritors.DirectKotlinOverridingCallableSearch.SearchParameters
import org.jetbrains.kotlin.psi.KtCallableDeclaration
import org.jetbrains.kotlin.psi.KtClass
import org.jetbrains.kotlin.psi.KtClassOrObject
import org.jetbrains.kotlin.psi.psiUtil.containingClassOrObject
object DirectKotlinOverridingCallableSearch {
data class SearchParameters(
val ktCallableDeclaration: KtCallableDeclaration,
val searchScope: SearchScope
) : com.intellij.model.search.SearchParameters<PsiElement> {
override fun getProject(): Project {
return ktCallableDeclaration.project
}
override fun areValid(): Boolean {
return ktCallableDeclaration.isValid
}
}
fun search(ktFunction: KtCallableDeclaration): Query<PsiElement> {
return search(ktFunction, ktFunction.useScope)
}
fun search(ktFunction: KtCallableDeclaration, searchScope: SearchScope): Query<PsiElement> {
return search(SearchParameters(ktFunction, searchScope))
}
fun search(parameters: SearchParameters): Query<PsiElement> {
return SearchService.getInstance().searchParameters(parameters)
}
}
class DirectKotlinOverridingMethodSearcher : Searcher<SearchParameters, PsiElement> {
@RequiresReadLock
override fun collectSearchRequest(parameters: SearchParameters): Query<out PsiElement>? {
val klass = parameters.ktCallableDeclaration.containingClassOrObject
if (klass !is KtClass) return null
return DirectKotlinClassInheritorsSearch.search(klass, parameters.searchScope)
.flatMapping { ktClassOrObject ->
if (ktClassOrObject !is KtClassOrObject) EmptyQuery.getEmptyQuery()
else object : AbstractQuery<PsiElement>() {
override fun processResults(consumer: Processor<in PsiElement>): Boolean {
val superFunction = analyze(parameters.ktCallableDeclaration) {
parameters.ktCallableDeclaration.getSymbol()
}
analyze(ktClassOrObject) {
(ktClassOrObject.getSymbol() as KtClassOrObjectSymbol).getDeclaredMemberScope()
.getCallableSymbols { it == parameters.ktCallableDeclaration.nameAsName }
.forEach { overridingSymbol ->
val function = overridingSymbol.psi
if (function != null &&
overridingSymbol.getAllOverriddenSymbols().any { it == superFunction } &&
!consumer.process(function)) {
return false
}
}
return true
}
}
}
}
}
}
private val oldSearchers = setOf(
"org.jetbrains.kotlin.idea.search.ideaExtensions.KotlinOverridingMethodsWithFlexibleTypesSearcher",
"org.jetbrains.kotlin.idea.search.ideaExtensions.KotlinOverridingMethodsWithGenericsSearcher"
)
private val EVERYTHING_BUT_KOTLIN = object : QueryFactory<PsiMethod, OverridingMethodsSearch.SearchParameters>() {
init {
OverridingMethodsSearch.EP_NAME.extensionList
.filterNot { oldSearchers.contains(it::class.java.name) }
.forEach { registerExecutor(it) }
}
}
internal class DirectKotlinOverridingMethodDelegatedSearcher : Searcher<SearchParameters, PsiElement> {
@RequiresReadLock
override fun collectSearchRequests(parameters: SearchParameters): Collection<Query<out PsiElement>> {
val baseFunction = parameters.ktCallableDeclaration
val methods = baseFunction.toLightMethods()
val queries = methods.map { it ->
EVERYTHING_BUT_KOTLIN.createQuery(JavaOverridingMethodsSearcherFromKotlinParameters(it, parameters.searchScope, false))
}
return queries
}
}
| apache-2.0 | c7f68119771f9ae3baacc4deb52d2c39 | 44.577982 | 131 | 0.683374 | 5.723502 | false | false | false | false |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.