repo_name
stringlengths 7
81
| path
stringlengths 6
242
| copies
stringclasses 53
values | size
stringlengths 2
6
| content
stringlengths 73
737k
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 5.44
99.8
| line_max
int64 15
977
| 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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
vanniktech/Emoji | app/src/main/kotlin/com/vanniktech/emoji/sample/MainDialog.kt | 1 | 3719 | /*
* Copyright (C) 2016 - Niklas Baudy, Ruben Gees, Mario Đanić and contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.vanniktech.emoji.sample
import android.app.Dialog
import android.graphics.PorterDuff
import android.os.Bundle
import android.view.View
import android.widget.EditText
import android.widget.ImageButton
import android.widget.ImageView
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat
import androidx.fragment.app.DialogFragment
import androidx.recyclerview.widget.RecyclerView
import com.vanniktech.emoji.Emoji
import com.vanniktech.emoji.EmojiPopup
import com.vanniktech.emoji.material.MaterialEmojiLayoutFactory
import timber.log.Timber
// We don't care about duplicated code in the sample.
class MainDialog : DialogFragment() {
override fun onCreate(savedInstanceState: Bundle?) {
layoutInflater.factory2 = MaterialEmojiLayoutFactory(null)
super.onCreate(savedInstanceState)
}
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
return AlertDialog.Builder(requireContext())
.setView(buildView())
.create()
}
private fun buildView(): View? {
val context = requireContext()
val result = View.inflate(context, R.layout.dialog_main, null)
val editText = result.findViewById<EditText>(R.id.main_dialog_chat_bottom_message_edittext)
val rootView = result.findViewById<View>(R.id.main_dialog_root_view)
val emojiButton = result.findViewById<ImageButton>(R.id.main_dialog_emoji)
val sendButton = result.findViewById<ImageView>(R.id.main_dialog_send)
val emojiPopup = EmojiPopup(
rootView = rootView,
editText = editText,
onEmojiBackspaceClickListener = { Timber.d(TAG, "Clicked on Backspace") },
onEmojiClickListener = { emoji: Emoji -> Timber.d(TAG, "Clicked on Emoji " + emoji.unicode) },
onEmojiPopupShownListener = { emojiButton.setImageResource(R.drawable.ic_keyboard) },
onSoftKeyboardOpenListener = { px -> Timber.d(TAG, "Opened soft keyboard with height $px") },
onEmojiPopupDismissListener = { emojiButton.setImageResource(R.drawable.ic_emojis) },
onSoftKeyboardCloseListener = { Timber.d(TAG, "Closed soft keyboard") },
keyboardAnimationStyle = R.style.emoji_fade_animation_style,
)
emojiButton.setColorFilter(ContextCompat.getColor(context, R.color.colorPrimary), PorterDuff.Mode.SRC_IN)
sendButton.setColorFilter(ContextCompat.getColor(context, R.color.colorPrimary), PorterDuff.Mode.SRC_IN)
val chatAdapter = ChatAdapter()
emojiButton.setOnClickListener { emojiPopup.toggle() }
sendButton.setOnClickListener {
val text = editText.text.toString().trim { it <= ' ' }
if (text.isNotEmpty()) {
chatAdapter.add(text)
editText.setText("")
}
}
val recyclerView: RecyclerView = result.findViewById(R.id.main_dialog_recycler_view)
recyclerView.adapter = chatAdapter
return rootView
}
internal companion object {
const val TAG = "MainDialog"
fun show(activity: AppCompatActivity) {
MainDialog().show(activity.supportFragmentManager, TAG)
}
}
}
| apache-2.0 | 967f4ed5ff767d22ff49b195f770c471 | 39.402174 | 109 | 0.745494 | 4.378092 | false | false | false | false |
eugeis/ee | task/task/src-gen/main/kotlin/ee/task/shared/SharedApiBase.kt | 1 | 4440 | package ee.task.shared
import ee.lang.CompilationUnit
import java.nio.file.Path
import java.nio.file.Paths
import java.util.concurrent.TimeUnit
open class ExecConfig {
val home: Path
val cmd: List<String>
val env: Map<String, String>
val filterPattern: Unit
val failOnError: Boolean
val filter: Boolean
val noConsole: Boolean
val wait: Boolean
val timeout: Long
val timeoutUnit: TimeUnit
constructor(home: Path = Paths.get(""), cmd: List<String> = arrayListOf(), env: Map<String, String> = emptyMap(),
filterPattern: Unit =, failOnError: Boolean = false, filter: Boolean = false, noConsole: Boolean = false,
wait: Boolean = true, timeout: Long = ee.lang.Attribute@6ebc05a6,
timeoutUnit: TimeUnit = TimeUnit.SECONDS)
{
this.home = home
this.cmd = cmd
this.env = env
this.filterPattern = filterPattern
this.failOnError = failOnError
this.filter = filter
this.noConsole = noConsole
this.wait = wait
this.timeout = timeout
this.timeoutUnit = timeoutUnit
}
companion object {
val EMPTY = ExecConfig()
}
}
open class PathResolver {
val home: Path
val itemToHome: Map<String, String>
constructor(home: Path = Paths.get(""), itemToHome: Map<String, String> = emptyMap()) {
this.home = home
this.itemToHome = itemToHome
}
open fun <T : CompilationUnit> resolve()Path
{
throw IllegalAccessException("Not implemented yet.")
}
companion object {
val EMPTY = PathResolver()
}
}
open class Result {
val action: Unit
val ok: Boolean
val failure: Unit
val info: Unit
val error: Throwable?
val results: List<Result>
constructor(action: Unit =, ok: Boolean = true, failure: Unit =, info: Unit =, error: Throwable? = null,
results: List<Result> = arrayListOf()) {
this.action = action
this.ok = ok
this.failure = failure
this.info = info
this.error = error
this.results = results
}
companion object {
val EMPTY = Result()
}
}
open class Task {
val name: Unit
val group: Unit
constructor(name: Unit =, group: Unit =) {
this.name = name
this.group = group
}
open fun execute()Result
{
throw IllegalAccessException("Not implemented yet.")
}
companion object {
val EMPTY = Task()
}
}
open class TaskFactory {
val name: Unit
val group: Unit
constructor(name: Unit =, group: Unit =) {
this.name = name
this.group = group
}
open fun supports()Boolean
{
throw IllegalAccessException("Not implemented yet.")
}
open fun create()List<Task>
{
throw IllegalAccessException("Not implemented yet.")
}
companion object {
val EMPTY = TaskFactory()
}
}
open class TaskGroup {
val taskFactories: List<TaskFactory<Task>>
val tasks: List<Task>
constructor(taskFactories: List<TaskFactory<Task>> = arrayListOf(), tasks: List<Task> = arrayListOf()) {
this.taskFactories = taskFactories
this.tasks = tasks
}
companion object {
val EMPTY = TaskGroup()
}
}
open class TaskRegistry {
val pathResolver: PathResolver
constructor(pathResolver: PathResolver = PathResolver()) {
this.pathResolver = pathResolver
}
open fun register()Unit
{
throw IllegalAccessException("Not implemented yet.")
}
companion object {
val EMPTY = TaskRegistry()
}
}
open class TaskRepository {
val typeFactories: List<TaskFactory<Task>>
constructor(typeFactories: List<TaskFactory<Task>> = arrayListOf()) {
this.typeFactories = typeFactories
}
open fun <V : TaskFactory<Task>> register()Unit
{
throw IllegalAccessException("Not implemented yet.")
}
open fun <T : CompilationUnit> find()List<TaskFactory<Task>>
{
throw IllegalAccessException("Not implemented yet.")
}
companion object {
val EMPTY = TaskRepository()
}
}
open class TaskResult {
val task: Task
val result: Result
constructor(task: Task = Task(), result: Result = Result()) {
this.task = task
this.result = result
}
companion object {
val EMPTY = TaskResult()
}
}
| apache-2.0 | f734163eaef07f12fa5611eae63e38f4 | 19.366972 | 117 | 0.615991 | 4.457831 | false | false | false | false |
YounesRahimi/java-utils | src/main/java/ir/iais/utilities/javautils/_K.kt | 2 | 2908 | @file:JvmName("K")
package ir.iais.utilities.javautils
import com.fasterxml.jackson.annotation.JsonIgnore
import com.fasterxml.jackson.databind.ObjectMapper
import ir.iais.utilities.javautils.utils.InjectorService
import ir.iais.utilities.javautils.utils.Jackson
import ir.iais.utilities.javautils.utils.ShortUUID
import org.apache.commons.lang3.exception.ExceptionUtils
import org.slf4j.Logger
import org.slf4j.LoggerFactory
//import org.apache.logging.log4j.LogManager
//import org.apache.logging.log4j.Logger
import java.util.*
import kotlin.reflect.KClass
/** static helper methods Created by yoones on 8/21/2016 AD. */
fun ObjectMapper.config(): ObjectMapper = Jackson.objectMapperConfigurer(this)
/**
* logging with Log4j2 without hassles
*/
inline val KClass<*>.logger: Logger
inline get() = LoggerFactory.getLogger(this.java)
inline val Class<*>.logger: Logger
inline get() = LoggerFactory.getLogger(this)
interface IQ {
@get:JsonIgnore
val logger: Logger
get() = LoggerFactory.getLogger(this.javaClass)
// fun Any.toJson(): String = Jackson.toJson(this)
}
inline fun <reified T : Any> fromJson(json: String): T = Jackson.fromJson(json, T::class.java)
fun <T : Enum<*>> T.isOneOf(vararg enums: T): Boolean = listOf(*enums).contains(this)
fun <T : Throwable> Throwable.contains(exClass: KClass<T>): Boolean =
ExceptionUtils.indexOfType(this, exClass.java) >= 0
operator inline fun <reified T : Throwable> Throwable.get(exClass: KClass<T>): T {
val i = ExceptionUtils.indexOfType(this, exClass.java)
return if (i >= 0) ExceptionUtils.getThrowables(this)[i] as T
else throw Error("'${this.localizedMessage}' doesn't have error cause of type ${T::class.qualifiedName}")
}
inline fun <reified T : Throwable> Throwable.rootCause(): T {
var throwable = this
while (throwable.cause != null) throwable = throwable.cause as Throwable
return throwable as T
}
/** Get instance with [InjectorService] */
@Suppress("DeprecatedCallableAddReplaceWith")
@Deprecated("Use constructor injection")
fun <OBJ : Any> Class<OBJ>.inject(): OBJ = InjectorService.instance(this)
/** Get instance with [InjectorService] */
@Suppress("DeprecatedCallableAddReplaceWith")
@Deprecated("Use constructor injection")
fun <OBJ : Any> KClass<OBJ>.inject(): OBJ = InjectorService.instance(this.java)
inline fun <reified T : Any> Array<T>.randomItem(): T {
if (this.isEmpty()) throw Error("Array<${T::class.simpleName}> is empty")
val rnd = Random().nextInt(this.size)
return this[rnd]
}
inline fun <reified T : Any> Collection<T>.randomItem(): T = this.toTypedArray().randomItem()
fun <T> T.println(toString: (T) -> Any? = { it }): T {
println(toString(this))
return this
}
fun shortUUID(): String = ShortUUID.next()
fun uuid(): String = UUID.randomUUID().toString()
fun <T> T?.toOptional(): Optional<T> = Optional.ofNullable(this)
| gpl-3.0 | c696cb7d3b005233dba99c76af766558 | 33.211765 | 109 | 0.729023 | 3.704459 | false | false | false | false |
Bombe/Sone | src/main/kotlin/net/pterodactylus/sone/web/page/FreenetTemplatePage.kt | 1 | 4092 | /*
* Sone - FreenetTemplatePage.kt - Copyright © 2010–2020 David Roden
*
* 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 net.pterodactylus.sone.web.page
import freenet.clients.http.*
import net.pterodactylus.sone.main.*
import net.pterodactylus.util.template.*
import net.pterodactylus.util.web.*
import java.lang.String.*
import java.net.*
import java.util.logging.*
import java.util.logging.Logger.*
/**
* Base class for all [Page]s that are rendered with [Template]s and
* fit into Freenet’s web interface.
*/
open class FreenetTemplatePage(
private val templateRenderer: TemplateRenderer,
loaders: Loaders,
private val invalidFormPasswordRedirectTarget: String
) : FreenetPage, LinkEnabledCallback {
private val pageMakerInteractionFactory: PageMakerInteractionFactory = DefaultPageMakerInteractionFactory()
open val styleSheets: Collection<String> = emptySet()
open val shortcutIcon: String? get() = null
open val isFullAccessOnly get() = false
override fun getPath() = toadletPath
open fun getPageTitle(request: FreenetRequest) = ""
override fun isPrefixPage() = false
open fun getRedirectTarget(request: FreenetRequest): String? = null
open fun getAdditionalLinkNodes(request: FreenetRequest): List<Map<String, String>> = emptyList()
override fun isLinkExcepted(link: URI) = false
override fun isEnabled(toadletContext: ToadletContext) = !isFullAccessOnly
private val template = templatePath?.let(loaders::loadTemplate) ?: Template()
override fun handleRequest(request: FreenetRequest, response: Response): Response {
getRedirectTarget(request)?.let { redirectTarget -> return RedirectResponse(redirectTarget) }
if (isFullAccessOnly && !request.toadletContext.isAllowedFullAccess) {
return response.setStatusCode(401).setStatusText("Not authorized").setContentType("text/html")
}
val toadletContext = request.toadletContext
if (request.method == Method.POST) {
/* require form password. */
val formPassword = request.httpRequest.getPartAsStringFailsafe("formPassword", 32)
if (formPassword != toadletContext.container.formPassword) {
return RedirectResponse(invalidFormPasswordRedirectTarget)
}
}
val pageMakerInteraction = pageMakerInteractionFactory.createPageMaker(toadletContext, getPageTitle(request))
styleSheets.forEach(pageMakerInteraction::addStyleSheet)
getAdditionalLinkNodes(request).forEach(pageMakerInteraction::addLinkNode)
shortcutIcon?.let(pageMakerInteraction::addShortcutIcon)
val output = try {
val start = System.nanoTime()
templateRenderer.render(template) { templateContext ->
processTemplate(request, templateContext)
}.also {
val finish = System.nanoTime()
logger.log(Level.FINEST, format("Template was rendered in %.2fms.", (finish - start) / 1000000.0))
}
} catch (re1: RedirectException) {
return RedirectResponse(re1.target ?: "")
}
pageMakerInteraction.setContent(output)
return response.setStatusCode(200).setStatusText("OK").setContentType("text/html").write(pageMakerInteraction.renderPage())
}
open fun processTemplate(request: FreenetRequest, templateContext: TemplateContext) {
/* do nothing. */
}
fun redirectTo(target: String?): Nothing =
throw RedirectException(target)
class RedirectException(val target: String?) : Exception() {
override fun toString(): String = format("RedirectException{target='%s'}", target)
}
}
private val logger: Logger = getLogger(FreenetTemplatePage::class.java.name)
| gpl-3.0 | 1b3ddbd7f75a7527e82ce8bac499077a | 36.154545 | 125 | 0.765354 | 4.248441 | false | false | false | false |
mozilla-mobile/focus-android | app/src/androidTest/java/org/mozilla/focus/activity/robots/SettingsSearchMenuRobot.kt | 1 | 5827 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
package org.mozilla.focus.activity.robots
import androidx.test.espresso.Espresso
import androidx.test.espresso.Espresso.onView
import androidx.test.espresso.action.ViewActions.click
import androidx.test.espresso.action.ViewActions.typeText
import androidx.test.espresso.assertion.ViewAssertions.matches
import androidx.test.espresso.matcher.ViewMatchers.isDisplayed
import androidx.test.espresso.matcher.ViewMatchers.withId
import androidx.test.espresso.matcher.ViewMatchers.withText
import androidx.test.uiautomator.UiObject
import androidx.test.uiautomator.UiScrollable
import androidx.test.uiautomator.UiSelector
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.mozilla.focus.R
import org.mozilla.focus.helpers.TestHelper.getStringResource
import org.mozilla.focus.helpers.TestHelper.getTargetContext
import org.mozilla.focus.helpers.TestHelper.mDevice
import org.mozilla.focus.helpers.TestHelper.packageName
import org.mozilla.focus.helpers.TestHelper.waitingTime
class SearchSettingsRobot {
fun verifySearchSettingsItems() {
assertTrue(searchEngineSubMenu.exists())
assertTrue(searchEngineDefaultOption.exists())
assertTrue(searchSuggestionsHeading.exists())
assertTrue(searchSuggestionDescription.exists())
verifySearchSuggestionsSwitchState()
assertTrue(searchSuggestionLearnMoreLink.exists())
assertTrue(urlAutocompleteSubMenu.exists())
assertTrue(urlAutocompleteDefaultOption.exists())
}
fun openSearchEngineSubMenu() {
searchEngineSubMenu.waitForExists(waitingTime)
searchEngineSubMenu.click()
}
fun selectSearchEngine(engineName: String) {
searchEngineList.waitForExists(waitingTime)
searchEngineList
.getChild(UiSelector().text(engineName))
.click()
}
fun clickSearchSuggestionsSwitch() {
searchSuggestionsSwitch.waitForExists(waitingTime)
searchSuggestionsSwitch.click()
}
fun verifySearchSuggestionsSwitchState(enabled: Boolean = false) {
if (enabled) {
assertTrue(searchSuggestionsSwitch.isChecked)
} else {
assertFalse(searchSuggestionsSwitch.isChecked)
}
}
fun openUrlAutocompleteSubMenu() {
urlAutocompleteSubMenu.waitForExists(waitingTime)
urlAutocompleteSubMenu.click()
}
fun openManageSitesSubMenu() {
manageSitesSubMenu.check(matches(isDisplayed()))
manageSitesSubMenu.perform(click())
}
fun openAddCustomUrlDialog() {
addCustomUrlButton.check(matches(isDisplayed()))
addCustomUrlButton.perform(click())
}
fun enterCustomUrl(url: String) {
customUrlText.check(matches(isDisplayed()))
customUrlText.perform(typeText(url))
}
fun saveCustomUrl() = saveButton.perform(click())
fun verifySavedCustomURL(url: String) {
customUrlText.check(matches(withText(url)))
}
fun removeCustomUrl() {
Espresso.openActionBarOverflowOrOptionsMenu(getTargetContext)
onView(withText(R.string.preference_autocomplete_menu_remove)).perform(click())
customUrlText.perform(click())
onView(withId(R.id.remove)).perform(click())
}
fun verifyCustomUrlDialogNotClosed() {
saveButton.check(matches(isDisplayed()))
}
fun toggleCustomAutocomplete() {
onView(withText(R.string.preference_switch_autocomplete_user_list)).perform(click())
}
fun toggleTopSitesAutocomplete() {
onView(withText(R.string.preference_switch_autocomplete_topsites)).perform(click())
}
class Transition
}
private val searchEngineSubMenu =
UiScrollable(UiSelector().resourceId("$packageName:id/recycler_view"))
.getChild(UiSelector().text(getStringResource(R.string.preference_search_engine_label)))
private val searchEngineDefaultOption =
mDevice.findObject(UiSelector().textContains("Google"))
private val searchEngineList = UiScrollable(
UiSelector()
.resourceId("$packageName:id/search_engine_group").enabled(true),
)
private val searchSuggestionsHeading: UiObject =
mDevice.findObject(
UiSelector()
.textContains(getStringResource(R.string.preference_show_search_suggestions)),
)
private val searchSuggestionDescription: UiObject =
mDevice.findObject(
UiSelector()
.textContains(getStringResource(R.string.preference_show_search_suggestions_summary)),
)
private val searchSuggestionLearnMoreLink: UiObject =
mDevice.findObject(
UiSelector()
.resourceId("$packageName:id/link"),
)
private val searchSuggestionsSwitch: UiObject =
mDevice.findObject(
UiSelector()
.resourceId("$packageName:id/switchWidget"),
)
private val urlAutocompleteSubMenu =
UiScrollable(UiSelector().resourceId("$packageName:id/recycler_view"))
.getChildByText(
UiSelector().text(getStringResource(R.string.preference_subitem_autocomplete)),
getStringResource(R.string.preference_subitem_autocomplete),
true,
)
private val urlAutocompleteDefaultOption =
mDevice.findObject(
UiSelector()
.textContains(getStringResource(R.string.preference_state_on)),
)
private val manageSitesSubMenu = onView(withText(R.string.preference_autocomplete_subitem_manage_sites))
private val addCustomUrlButton = onView(withText(R.string.preference_autocomplete_action_add))
private val customUrlText = onView(withId(R.id.domainView))
private val saveButton = onView(withId(R.id.save))
| mpl-2.0 | 0e8604e0c4fb5f7e07da5ffa9f59ae34 | 33.47929 | 104 | 0.732624 | 4.835685 | false | true | false | false |
youlookwhat/CloudReader | app/src/main/java/com/example/jingbin/cloudreader/ui/wan/child/WendaFragment.kt | 1 | 2933 | package com.example.jingbin.cloudreader.ui.wan.child
import android.app.Activity
import android.content.Context
import android.os.Bundle
import androidx.lifecycle.Observer
import com.example.jingbin.cloudreader.R
import com.example.jingbin.cloudreader.adapter.WanAndroidAdapter
import com.example.jingbin.cloudreader.databinding.FragmentAndroidBinding
import com.example.jingbin.cloudreader.utils.RefreshHelper
import com.example.jingbin.cloudreader.viewmodel.wan.WanCenterViewModel
import me.jingbin.bymvvm.base.BaseFragment
/**
* 问答
*/
class WendaFragment : BaseFragment<WanCenterViewModel, FragmentAndroidBinding>() {
private var isFirst = true
private lateinit var activity: Activity
private lateinit var mAdapter: WanAndroidAdapter
override fun setContent(): Int = R.layout.fragment_android
companion object {
fun newInstance(): WendaFragment {
return WendaFragment()
}
}
override fun onAttach(context: Context) {
super.onAttach(context)
activity = context as Activity
}
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
}
override fun onResume() {
super.onResume()
if (isFirst) {
showLoading()
initRv()
getWendaData()
isFirst = false
}
}
private fun initRv() {
RefreshHelper.initLinear(bindingView.xrvAndroid, true, 1)
mAdapter = WanAndroidAdapter(activity)
mAdapter.isNoShowChapterName = true
mAdapter.isNoImage = false
mAdapter.isShowDesc = true
bindingView.xrvAndroid.adapter = mAdapter
bindingView.xrvAndroid.setOnRefreshListener {
viewModel.mPage = 1
getWendaData()
}
bindingView.xrvAndroid.setOnLoadMoreListener(true) {
++viewModel.mPage
getWendaData()
}
}
private fun getWendaData() {
viewModel.getWendaList().observe(this, Observer {
bindingView.xrvAndroid.isRefreshing = false
if (it != null && it.isNotEmpty()) {
showContentView()
if (viewModel.mPage == 1) {
mAdapter.setNewData(it)
} else {
mAdapter.addData(it)
bindingView.xrvAndroid.loadMoreComplete()
}
} else {
if (viewModel.mPage == 1) {
if (it != null) {
showEmptyView("没找到问答的内容~")
} else {
showError()
if (viewModel.mPage > 1) viewModel.mPage--
}
} else {
bindingView.xrvAndroid.loadMoreEnd()
}
}
})
}
override fun onRefresh() {
getWendaData()
}
} | apache-2.0 | da8014405404ae50e764954083374569 | 28.434343 | 82 | 0.594233 | 5.146643 | false | false | false | false |
jdinkla/groovy-java-ray-tracer | src/main/kotlin/net/dinkla/raytracer/objects/acceleration/kdtree/Simple2Builder.kt | 1 | 5456 | package net.dinkla.raytracer.objects.acceleration.kdtree
import net.dinkla.raytracer.math.Axis
import net.dinkla.raytracer.math.BBox
import net.dinkla.raytracer.math.Point3D
import net.dinkla.raytracer.objects.GeometricObject
import net.dinkla.raytracer.utilities.Counter
import org.slf4j.LoggerFactory
import java.util.*
class Simple2Builder : IKDTreeBuilder {
override var maxDepth = 10
var minChildren = 4
override fun build(tree: KDTree, voxel: BBox): AbstractNode {
return build(tree.objects, tree.boundingBox, 0)
}
/**
*
* @param objects
* @param voxel
* @param depth
* @return
*/
fun build(objects: List<GeometricObject>, voxel: BBox, depth: Int): AbstractNode {
Counter.count("KDtree.build")
var node: AbstractNode?
var voxelL: BBox?
var voxelR: BBox?
if (objects.size < minChildren || depth >= maxDepth) {
Counter.count("KDtree.build.leaf")
node = Leaf(objects)
return node
}
Counter.count("KDtree.build.node")
val half = voxel.q!!.minus(voxel.p!!).times(0.5)
val mid = voxel.p.plus(half)
var split: Double? = null
var objectsL: List<GeometricObject>
var objectsR: List<GeometricObject>
var voxelLx: BBox?
var voxelRx: BBox?
var voxelLy: BBox?
var voxelRy: BBox?
var voxelLz: BBox?
var voxelRz: BBox?
val objectsLx = ArrayList<GeometricObject>()
val objectsRx = ArrayList<GeometricObject>()
val objectsLy = ArrayList<GeometricObject>()
val objectsRy = ArrayList<GeometricObject>()
val objectsLz = ArrayList<GeometricObject>()
val objectsRz = ArrayList<GeometricObject>()
split = mid.x
val q1 = Point3D(mid.x, voxel.q.y, voxel.q.z)
voxelLx = BBox(voxel.p, q1)
val p2 = Point3D(mid.x, voxel.p.y, voxel.p.z)
voxelRx = BBox(p2, voxel.q)
var bothX = 0
var bothY = 0
var bothZ = 0
for (`object` in objects) {
val bbox = `object`.boundingBox
var isBoth = false
if (bbox.p.x <= split) {
objectsLx.add(`object`)
isBoth = true
}
if (bbox.q.x >= split) {
objectsRx.add(`object`)
if (isBoth) {
bothX++
}
}
}
split = mid.y
val q1y = Point3D(voxel.q.x, mid.y, voxel.q.z)
voxelLy = BBox(voxel.p, q1y)
val p2y = Point3D(voxel.p.x, mid.y, voxel.p.z)
voxelRy = BBox(p2y, voxel.q)
for (`object` in objects) {
val bbox = `object`.boundingBox
var isBoth = false
if (bbox.p.y <= split) {
objectsLy.add(`object`)
isBoth = true
}
if (bbox.q.y >= split) {
objectsRy.add(`object`)
if (isBoth) {
bothY++
}
}
}
split = mid.z
val q1z = Point3D(voxel.q.x, voxel.q.y, mid.z)
voxelLz = BBox(voxel.p, q1z)
val p2z = Point3D(voxel.p.x, voxel.p.y, mid.z)
voxelRz = BBox(p2z, voxel.q)
for (`object` in objects) {
val bbox = `object`.boundingBox
var isBoth = false
if (bbox.p.z <= split) {
objectsLz.add(`object`)
isBoth = true
}
if (bbox.q.z >= split) {
objectsRz.add(`object`)
if (isBoth) {
bothZ++
}
}
}
val n = objects.size
val diffX = Math.abs(objectsLx.size - objectsRx.size) + bothX * 3 + (objectsLx.size + objectsRx.size - n) * 5
val diffY = Math.abs(objectsLy.size - objectsRy.size) + bothY * 3 + (objectsLy.size + objectsRy.size - n) * 5
val diffZ = Math.abs(objectsLz.size - objectsRz.size) + bothZ * 3 + (objectsLz.size + objectsRz.size - n) * 5
if (diffX < diffY) {
if (diffX < diffZ) {
objectsL = objectsLx
objectsR = objectsRx
voxelL = voxelLx
voxelR = voxelRx
} else {
objectsL = objectsLz
objectsR = objectsRz
voxelL = voxelLz
voxelR = voxelRz
}
} else {
if (diffY < diffZ) {
objectsL = objectsLy
objectsR = objectsRy
voxelL = voxelLy
voxelR = voxelRy
} else {
objectsL = objectsLz
objectsR = objectsRz
voxelL = voxelLz
voxelR = voxelRz
}
}
if (objectsL.size + objectsR.size > n * 1.5) {
node = Leaf(objects)
} else {
LOGGER.info("Splitting " + objects.size + " objects into " + objectsL.size + " and " + objectsR.size + " objects at " + split + " with depth " + depth)
val left = build(objectsL, voxelL, depth + 1)
val right = build(objectsR, voxelR, depth + 1)
node = InnerNode(left, right, voxel, split, Axis.fromInt(depth % 3))
}
return node
}
companion object {
internal val LOGGER = LoggerFactory.getLogger(this::class.java)
}
}
| apache-2.0 | 3e33e8f2d4ffdd7616a07468e597973b | 27.715789 | 163 | 0.51063 | 4.102256 | false | false | false | false |
mrebollob/LoteriadeNavidad | shared/src/commonMain/kotlin/com/mrebollob/loteria/data/TicketsRepositoryImp.kt | 1 | 1216 | package com.mrebollob.loteria.data
import com.mrebollob.loteria.data.mapper.TicketMapper
import com.mrebollob.loteria.di.LotteryDatabaseWrapper
import com.mrebollob.loteria.domain.entity.Ticket
import com.mrebollob.loteria.domain.repository.TicketsRepository
class TicketsRepositoryImp(
lotteryDatabaseWrapper: LotteryDatabaseWrapper,
private val ticketMapper: TicketMapper
) : TicketsRepository {
private val lotteryQueries = lotteryDatabaseWrapper.instance?.lotteryQueries
override suspend fun getTickets(): Result<List<Ticket>> {
val dbTickets = lotteryQueries?.selectAll()?.executeAsList() ?: emptyList()
return Result.success(dbTickets.map { ticketMapper.toDomain(it) })
}
override suspend fun createTicket(
name: String,
number: Int,
bet: Float
): Result<Unit> {
lotteryQueries?.insertItem(
id = null,
name = name,
number = number.toLong(),
bet = bet.toDouble()
)
return Result.success(Unit)
}
override suspend fun deleteTicket(ticket: Ticket): Result<Unit> {
lotteryQueries?.deleteById(id = ticket.id)
return Result.success(Unit)
}
}
| apache-2.0 | 24e03f0d8f4b348f29208644c3014e11 | 30.179487 | 83 | 0.689145 | 4.606061 | false | false | false | false |
SUPERCILEX/Robot-Scouter | library/core-ui/src/main/java/com/supercilex/robotscouter/core/ui/RecyclerView.kt | 1 | 3417 | package com.supercilex.robotscouter.core.ui
import android.os.Bundle
import android.os.Parcelable
import androidx.core.view.postOnAnimationDelayed
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.SimpleItemAnimator
import com.firebase.ui.firestore.FirestoreRecyclerAdapter
import com.firebase.ui.firestore.FirestoreRecyclerOptions
import kotlin.math.max
private val defaultMaxAnimationDuration: Long by lazy {
DefaultItemAnimator().maxAnimationDuration()
}
fun RecyclerView.isItemInRange(position: Int): Boolean {
val manager = layoutManager as LinearLayoutManager
val adapter = checkNotNull(adapter)
val first = manager.findFirstCompletelyVisibleItemPosition()
// Only compute findLastCompletelyVisibleItemPosition if necessary
return position in first until adapter.itemCount &&
position in first..manager.findLastCompletelyVisibleItemPosition()
}
inline fun RecyclerView.notifyItemsNoChangeAnimation(
payload: Any? = null,
update: RecyclerView.Adapter<*>.() -> Unit = {
notifyItemRangeChanged(0, itemCount, payload)
}
) {
val animator = itemAnimator as? SimpleItemAnimator
animator?.supportsChangeAnimations = false
checkNotNull(adapter).update()
postOnAnimationDelayed(animator.maxAnimationDuration()) {
animator?.supportsChangeAnimations = true
}
}
fun RecyclerView.ItemAnimator?.maxAnimationDuration() = this?.let {
max(max(addDuration, removeDuration), changeDuration)
} ?: defaultMaxAnimationDuration
inline fun RecyclerView.Adapter<*>.swap(
viewHolder: RecyclerView.ViewHolder,
target: RecyclerView.ViewHolder,
swap: (Int, Int) -> Unit
) {
val fromPos = viewHolder.adapterPosition
val toPos = target.adapterPosition
if (fromPos < toPos) {
for (i in fromPos until toPos) swap(i, i + 1) // Swap down
} else {
for (i in fromPos downTo toPos + 1) swap(i, i - 1) // Swap up
}
notifyItemMoved(fromPos, toPos)
}
/**
* A [FirestoreRecyclerAdapter] whose state can be saved regardless of database connection
* instability.
*
* This adapter will save its state across basic stop/start listening lifecycles, config changes,
* and even full blown process death. Extenders _must_ call [SavedStateAdapter.onSaveInstanceState]
* in the Activity/Fragment holding the adapter.
*/
abstract class SavedStateAdapter<T, VH : RecyclerView.ViewHolder>(
options: FirestoreRecyclerOptions<T>,
savedInstanceState: Bundle?,
protected val recyclerView: RecyclerView
) : FirestoreRecyclerAdapter<T, VH>(options) {
private var state: Parcelable?
private val RecyclerView.state get() = layoutManager?.onSaveInstanceState()
init {
state = savedInstanceState?.getParcelable(SAVED_STATE_KEY)
}
fun onSaveInstanceState(outState: Bundle) {
outState.putParcelable(SAVED_STATE_KEY, recyclerView.state)
}
override fun stopListening() {
state = recyclerView.state
super.stopListening()
}
override fun onDataChanged() {
recyclerView.layoutManager?.onRestoreInstanceState(state)
state = null
}
private companion object {
const val SAVED_STATE_KEY = "layout_manager_saved_state"
}
}
| gpl-3.0 | 941f7b707eb290312053e95efd4ac52f | 32.5 | 99 | 0.734855 | 4.96657 | false | false | false | false |
SUPERCILEX/Robot-Scouter | feature/trash/src/main/java/com/supercilex/robotscouter/feature/trash/TrashFragment.kt | 1 | 6647 | package com.supercilex.robotscouter.feature.trash
import android.os.Bundle
import android.view.KeyEvent
import android.view.Menu
import android.view.MenuInflater
import android.view.MenuItem
import android.view.View
import androidx.activity.addCallback
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.content.res.AppCompatResources
import androidx.core.view.isVisible
import androidx.fragment.app.viewModels
import androidx.lifecycle.MutableLiveData
import androidx.recyclerview.selection.SelectionTracker
import androidx.recyclerview.selection.StorageStrategy
import androidx.recyclerview.widget.DividerItemDecoration
import com.google.android.gms.tasks.Task
import com.supercilex.robotscouter.common.DeletionType
import com.supercilex.robotscouter.common.FIRESTORE_DELETION_QUEUE
import com.supercilex.robotscouter.core.data.model.untrashTeam
import com.supercilex.robotscouter.core.data.model.untrashTemplate
import com.supercilex.robotscouter.core.longToast
import com.supercilex.robotscouter.core.ui.AllChangesSelectionObserver
import com.supercilex.robotscouter.core.ui.FragmentBase
import com.supercilex.robotscouter.core.ui.KeyboardShortcutListener
import com.supercilex.robotscouter.core.ui.animatePopReveal
import com.supercilex.robotscouter.core.ui.longSnackbar
import kotlinx.android.synthetic.main.fragment_trash.*
import com.supercilex.robotscouter.R as RC
internal class TrashFragment : FragmentBase(R.layout.fragment_trash), View.OnClickListener,
KeyboardShortcutListener {
private val holder by viewModels<TrashHolder>()
private val allItems get() = holder.trashListener.value.orEmpty()
private lateinit var selectionTracker: SelectionTracker<String>
private lateinit var menuHelper: TrashMenuHelper
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setHasOptionsMenu(true)
holder.init()
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
actionEmptyTrash.setOnClickListener(this)
(activity as AppCompatActivity).apply {
setSupportActionBar(findViewById(RC.id.toolbar))
checkNotNull(supportActionBar).setDisplayHomeAsUpEnabled(true)
}
val divider = DividerItemDecoration(requireContext(), DividerItemDecoration.VERTICAL)
divider.setDrawable(checkNotNull(AppCompatResources.getDrawable(
requireContext(), R.drawable.trash_item_divider)))
trashList.addItemDecoration(divider)
val adapter = TrashListAdapter()
trashList.adapter = adapter
selectionTracker = SelectionTracker.Builder(
FIRESTORE_DELETION_QUEUE,
trashList,
TrashKeyProvider(holder.trashListener),
TrashDetailsLookup(trashList),
StorageStrategy.createStringStorage()
).build().apply {
adapter.selectionTracker = this
addObserver(TrashMenuHelper(this@TrashFragment, this).also { menuHelper = it })
val backPressedCallback = requireActivity().onBackPressedDispatcher
.addCallback(viewLifecycleOwner, false) { clearSelection() }
addObserver(object : AllChangesSelectionObserver<String>() {
override fun onSelectionChanged() {
backPressedCallback.isEnabled = hasSelection()
}
})
onRestoreInstanceState(savedInstanceState)
}
holder.trashListener.observe(viewLifecycleOwner) {
val hasTrash = it.orEmpty().isNotEmpty()
noTrashHint.animatePopReveal(!hasTrash)
notice.isVisible = hasTrash
menuHelper.onTrashCountUpdate(hasTrash)
if (it != null) for (i in 0 until adapter.itemCount) {
// Unselect deleted items
val item = adapter.getItem(i)
if (!it.contains(item)) selectionTracker.deselect(item.id)
}
adapter.submitList(it)
}
}
override fun onSaveInstanceState(outState: Bundle) {
selectionTracker.onSaveInstanceState(outState)
}
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
menuHelper.onCreateOptionsMenu(menu, inflater)
menuHelper.onTrashCountUpdate(holder.trashListener.value.orEmpty().isNotEmpty())
}
override fun onOptionsItemSelected(item: MenuItem) = menuHelper.onOptionsItemSelected(item)
override fun onShortcut(keyCode: Int, event: KeyEvent): Boolean {
when (keyCode) {
KeyEvent.KEYCODE_DEL, KeyEvent.KEYCODE_FORWARD_DEL ->
if (selectionTracker.hasSelection()) emptySelected() else emptyAll()
else -> return false
}
return true
}
override fun onClick(v: View) {
emptyAll()
}
fun restoreItems() {
val all = allItems
val restored = selectionTracker.selection.toList().map { key ->
all.single { it.id == key }
}.ifEmpty { all }.onEach { (id, _, type) ->
when (type) {
DeletionType.TEAM -> untrashTeam(id)
DeletionType.TEMPLATE -> untrashTemplate(id)
else -> error("Unsupported type: $type")
}
}
if (restored.isNotEmpty()) {
requireView().longSnackbar(resources.getQuantityString(
R.plurals.trash_restored_message, restored.size, restored.size))
}
}
fun emptySelected() {
showEmptyTrashDialog(selectionTracker.selection.toList())
}
fun onEmptyTrashConfirmed(deleted: List<String>, emptyTrashResult: Task<*>) {
requireView().longSnackbar(resources.getQuantityString(
R.plurals.trash_emptied_message, deleted.size, deleted.size))
// Visual hack to pretend items were deleted really fast (usually takes a few seconds)
val data = holder.trashListener as MutableLiveData
val prev = data.value
data.value = prev.orEmpty().filter { !deleted.contains(it.id) }
emptyTrashResult.addOnFailureListener(requireActivity()) {
longToast(R.string.trash_empty_failed_message)
data.value = prev
}
}
private fun emptyAll() {
showEmptyTrashDialog(allItems.map { it.id }, true)
}
private fun showEmptyTrashDialog(ids: List<String>, emptyAll: Boolean = false) {
EmptyTrashDialog.show(childFragmentManager, ids, emptyAll)
}
companion object {
const val TAG = "TrashFragment"
fun newInstance() = TrashFragment()
}
}
| gpl-3.0 | d8b2c2f56634d68f04a748a425eaa9fc | 37.645349 | 95 | 0.68813 | 5.124904 | false | false | false | false |
bachhuberdesign/deck-builder-gwent | app/src/main/java/com/bachhuberdesign/deckbuildergwent/database/DatabaseHelper.kt | 1 | 6337 | package com.bachhuberdesign.deckbuildergwent.database
import android.content.ContentValues
import android.content.Context
import android.database.sqlite.SQLiteDatabase
import android.database.sqlite.SQLiteDatabase.CONFLICT_REPLACE
import android.database.sqlite.SQLiteOpenHelper
import android.util.Log
import com.bachhuberdesign.deckbuildergwent.features.deckbuild.Deck
import com.bachhuberdesign.deckbuildergwent.features.shared.model.Card
import com.bachhuberdesign.deckbuildergwent.features.shared.model.Faction
import com.bachhuberdesign.deckbuildergwent.features.stattrack.Match
import com.google.gson.Gson
/**
* @author Eric Bachhuber
* @version 1.0.0
* @since 1.0.0
*/
class DatabaseHelper(var context: Context) : SQLiteOpenHelper(context, DB_NAME, null, DB_VERSION) {
companion object {
@JvmStatic val TAG: String = DatabaseHelper::class.java.name
const val DB_NAME = "deck_builder.db"
const val DB_VERSION: Int = 1
const val CREATE_TABLE_CARDS: String =
"CREATE TABLE ${Card.TABLE} (" +
"${Card.ID} INTEGER NOT NULL PRIMARY KEY, " +
"${Card.NAME} TEXT NOT NULL, " +
"${Card.DESCRIPTION} TEXT NOT NULL, " +
"${Card.FLAVOR_TEXT} TEXT NOT NULL, " +
"${Card.ICON_URL} TEXT NOT NULL, " +
"${Card.MILL} INTEGER NOT NULL DEFAULT 0, " +
"${Card.MILL_PREMIUM} INTEGER NOT NULL DEFAULT 0, " +
"${Card.SCRAP} INTEGER NOT NULL DEFAULT 0, " +
"${Card.SCRAP_PREMIUM} INTEGER NOT NULL DEFAULT 0, " +
"${Card.POWER} INTEGER NOT NULL DEFAULT 0, " +
"${Card.FACTION} INTEGER NOT NULL, " +
"${Card.LANE} INTEGER NOT NULL, " +
"${Card.LOYALTY} INTEGER NOT NULL DEFAULT 0, " +
"${Card.RARITY} INTEGER NOT NULL, " +
"${Card.TYPE} INTEGER NOT NULL" +
")"
const val CREATE_TABLE_USER_DECKS: String =
"CREATE TABLE ${Deck.TABLE} (" +
"${Deck.ID} INTEGER NOT NULL PRIMARY KEY, " +
"${Deck.NAME} TEXT NOT NULL, " +
"${Deck.FACTION} INTEGER NOT NULL, " +
"${Deck.LEADER_ID} INTEGER NOT NULL, " +
"${Deck.FAVORITED} INTEGER NOT NULL DEFAULT 0, " +
"${Deck.CREATED_DATE} INTEGER NOT NULL, " +
"${Deck.LAST_UPDATE} INTEGER NOT NULL" +
")"
const val CREATE_TABLE_USER_DECKS_CARDS: String =
"CREATE TABLE ${Deck.JOIN_CARD_TABLE} (" +
"join_id INTEGER NOT NULL PRIMARY KEY," +
"deck_id INTEGER NOT NULL, " +
"card_id INTEGER NOT NULL, " +
"${Card.SELECTED_LANE} INTEGER NOT NULL" +
")"
const val CREATE_TABLE_FACTIONS: String =
"CREATE TABLE ${Faction.TABLE} (" +
"${Faction.ID} INTEGER NOT NULL PRIMARY KEY, " +
"${Faction.NAME} TEXT NOT NULL, " +
"${Faction.EFFECT} TEXT NOT NULL," +
"${Faction.ICON_URL} TEXT NOT NULL" +
")"
const val CREATE_TABLE_MATCHES: String =
"CREATE TABLE ${Match.TABLE} (" +
"${Match.ID} INTEGER NOT NULL PRIMARY KEY, " +
"${Match.DECK_ID} INTEGER NOT NULL, " +
"${Match.OUTCOME} INTEGER NOT NULL, " +
"${Match.OPPONENT_FACTION} INTEGER NOT NULL, " +
"${Match.OPPONENT_LEADER} INTEGER DEFAULT 0, " +
"${Match.NOTES} TEXT, " +
"${Match.PLAYED_DATE} INTEGER, " +
"${Match.CREATED_DATE} INTEGER, " +
"${Match.LAST_UPDATE} INTEGER" +
")"
}
override fun onCreate(database: SQLiteDatabase) {
database.execSQL(CREATE_TABLE_CARDS)
database.execSQL(CREATE_TABLE_USER_DECKS)
database.execSQL(CREATE_TABLE_USER_DECKS_CARDS)
database.execSQL(CREATE_TABLE_FACTIONS)
database.execSQL(CREATE_TABLE_MATCHES)
val cards = Gson().fromJson(loadJsonFromAssets("card_list.json"), Array<Card>::class.java)
val factions = Gson().fromJson(loadJsonFromAssets("faction_list.json"), Array<Faction>::class.java)
cards.forEach { (id, name, description, flavorText, iconUrl, mill, millPremium, scrap,
scrapPremium, power, faction, lane, loyalty, rarity, cardType) ->
val cv = ContentValues()
cv.put(Card.NAME, name)
cv.put(Card.DESCRIPTION, description)
cv.put(Card.FLAVOR_TEXT, flavorText)
cv.put(Card.ICON_URL, iconUrl)
cv.put(Card.MILL, mill)
cv.put(Card.MILL_PREMIUM, millPremium)
cv.put(Card.SCRAP, scrap)
cv.put(Card.SCRAP_PREMIUM, scrapPremium)
cv.put(Card.POWER, power)
cv.put(Card.FACTION, faction)
cv.put(Card.LANE, lane)
cv.put(Card.LOYALTY, loyalty)
cv.put(Card.RARITY, rarity)
cv.put(Card.TYPE, cardType)
database.insertWithOnConflict(Card.TABLE, null, cv, CONFLICT_REPLACE)
}
factions.forEach { (id, name, effect, iconUrl) ->
val cv = ContentValues()
cv.put(Faction.ID, id)
cv.put(Faction.NAME, name)
cv.put(Faction.EFFECT, effect)
cv.put(Faction.ICON_URL, iconUrl)
database.insertWithOnConflict(Faction.TABLE, null, cv, CONFLICT_REPLACE)
}
}
override fun onUpgrade(database: SQLiteDatabase, oldVersion: Int, newVersion: Int) {
Log.d(TAG, "onUpgrade()")
}
private fun loadJsonFromAssets(fileName: String): String {
val stream = context.assets.open(fileName)
val buffer = ByteArray(stream.available())
stream.use { stream.read(buffer) }
return String(buffer).format("UTF-8")
}
}
| apache-2.0 | eaaf2bfb757151b690d696ff017c816b | 45.940741 | 107 | 0.539214 | 4.503909 | false | false | false | false |
Shynixn/BlockBall | blockball-core/src/main/java/com/github/shynixn/blockball/core/logic/persistence/entity/SoundEntity.kt | 1 | 2171 | package com.github.shynixn.blockball.core.logic.persistence.entity
import com.github.shynixn.blockball.api.business.annotation.YamlSerialize
import com.github.shynixn.blockball.api.business.enumeration.EffectTargetType
import com.github.shynixn.blockball.api.persistence.entity.Sound
/**
* Created by Shynixn 2018.
* <p>
* Version 1.2
* <p>
* MIT License
* <p>
* Copyright (c) 2018 by Shynixn
* <p>
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
* <p>
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
* <p>
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
class SoundEntity(
/**
* Name of the sound.
*/
@YamlSerialize(value = "name", orderNumber = 1)
override var name: String = "none",
/**
* Pitch of the sound.
*/
@YamlSerialize(value = "pitch", orderNumber = 2)
override var pitch: Double = 1.0,
/**
* Volume of the sound.
*/
@YamlSerialize(value = "volume", orderNumber = 3)
override var volume: Double = 1.0) : Sound {
/**
* Which players are effected.
*/
@YamlSerialize(value = "effecting", orderNumber = 4)
override var effectingType: EffectTargetType = EffectTargetType.NOBODY
} | apache-2.0 | 75a4a3275ea928df7d34b19c0ec8cf1a | 38.490909 | 81 | 0.695993 | 4.290514 | false | false | false | false |
HendraAnggrian/kota | kota-appcompat-v7/src/dialogs/DialogsV7.kt | 1 | 2277 | @file:JvmMultifileClass
@file:JvmName("DialogsV7Kt")
@file:Suppress("NOTHING_TO_INLINE", "UNUSED")
package kota
import android.content.DialogInterface
import android.content.DialogInterface.*
import android.support.annotation.StringRes
import android.support.v7.app.AlertDialog
@JvmOverloads
inline fun AlertDialog.setPositiveButton(
text: CharSequence,
noinline action: ((dialog: DialogInterface) -> Unit)? = null
) = setButton(BUTTON_POSITIVE, text) { dialog, _ -> action?.invoke(dialog) }
@JvmOverloads
inline fun AlertDialog.setPositiveButton(
@StringRes textId: Int,
noinline action: ((dialog: DialogInterface) -> Unit)? = null
) = setPositiveButton(getText(textId), action)
@JvmOverloads
inline fun AlertDialog.setNegativeButton(
text: CharSequence,
noinline action: ((dialog: DialogInterface) -> Unit)? = null
) = setButton(BUTTON_NEGATIVE, text) { dialog, _ -> action?.invoke(dialog) }
@JvmOverloads
inline fun AlertDialog.setNegativeButton(
@StringRes textId: Int,
noinline action: ((dialog: DialogInterface) -> Unit)? = null
) = setNegativeButton(getText(textId), action)
@JvmOverloads
inline fun AlertDialog.setNeutralButton(
text: CharSequence,
noinline action: ((dialog: DialogInterface) -> Unit)? = null
) = setButton(BUTTON_NEUTRAL, text) { dialog, _ -> action?.invoke(dialog) }
@JvmOverloads
inline fun AlertDialog.setNeutralButton(
@StringRes textId: Int,
noinline action: ((dialog: DialogInterface) -> Unit)? = null
) = setNeutralButton(getText(textId), action)
@JvmOverloads
inline fun AlertDialog.setOKButton(
noinline action: ((dialog: DialogInterface) -> Unit)? = null
) = setPositiveButton(android.R.string.ok, action)
@JvmOverloads
inline fun AlertDialog.setCancelButton(
noinline action: ((dialog: DialogInterface) -> Unit)? = null
) = setNegativeButton(android.R.string.cancel, action)
@JvmOverloads
inline fun AlertDialog.setYesButton(
noinline action: ((dialog: DialogInterface) -> Unit)? = null
) = setPositiveButton(android.R.string.yes, action)
@JvmOverloads
inline fun AlertDialog.setNoButton(
noinline action: ((dialog: DialogInterface) -> Unit)? = null
) = setNegativeButton(android.R.string.no, action) | apache-2.0 | ae0a4df4dda830481f454cca91f5e529 | 33.515152 | 76 | 0.725955 | 4.328897 | false | false | false | false |
noties/Markwon | app-sample/src/main/java/io/noties/markwon/app/samples/ToastDynamicContentSample.kt | 1 | 2002 | package io.noties.markwon.app.samples
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import android.widget.Toast
import io.noties.markwon.Markwon
import io.noties.markwon.app.BuildConfig
import io.noties.markwon.app.sample.ui.MarkwonTextViewSample
import io.noties.markwon.image.ImagesPlugin
import io.noties.markwon.sample.annotations.MarkwonArtifact
import io.noties.markwon.sample.annotations.MarkwonSampleInfo
import io.noties.markwon.sample.annotations.Tag
@MarkwonSampleInfo(
id = "20200627074017",
title = "Markdown in Toast (with dynamic content)",
description = "Display markdown in a `android.widget.Toast` with dynamic content (image)",
artifacts = [MarkwonArtifact.CORE, MarkwonArtifact.IMAGE],
tags = [Tag.toast, Tag.hack]
)
class ToastDynamicContentSample : MarkwonTextViewSample() {
override fun render() {
val md = """
# Head!
![alt](${BuildConfig.GIT_REPOSITORY}/raw/master/art/markwon_logo.png)
Do you see an image? ☝️
""".trimIndent()
val markwon = Markwon.builder(context)
.usePlugin(ImagesPlugin.create())
.build()
val markdown = markwon.toMarkdown(md)
val toast = Toast.makeText(context, markdown, Toast.LENGTH_LONG)
// try to obtain textView
val textView = toast.textView
if (textView != null) {
markwon.setParsedMarkdown(textView, markdown)
}
// finally show toast (at this point, if we didn't find TextView it will still
// present markdown, just without dynamic content (image))
toast.show()
}
}
private val Toast.textView: TextView?
get() {
fun find(view: View?): TextView? {
if (view is TextView) {
return view
}
if (view is ViewGroup) {
for (i in 0 until view.childCount) {
val textView = find(view.getChildAt(i))
if (textView != null) {
return textView
}
}
}
return null
}
return find(view)
} | apache-2.0 | 211c24506bd606a66cbbd28814e4c786 | 26.013514 | 92 | 0.67968 | 4.111111 | false | false | false | false |
ntemplon/legends-of-omterra | core/src/com/jupiter/europa/entity/Mappers.kt | 1 | 2969 | /*
* The MIT License
*
* Copyright 2015 Nathan Templon.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
*/
package com.jupiter.europa.entity
import com.badlogic.ashley.core.ComponentMapper
import com.jupiter.europa.entity.component.*
/**
* @author Nathan Templon
*/
public object Mappers {
// Constants
public val abilities: ComponentMapper<AbilityComponent> = ComponentMapper.getFor(javaClass<AbilityComponent>())
public val attributes: ComponentMapper<AttributesComponent> = ComponentMapper.getFor(javaClass<AttributesComponent>())
public val characterClass: ComponentMapper<CharacterClassComponent> = ComponentMapper.getFor(javaClass<CharacterClassComponent>())
public val collision: ComponentMapper<CollisionComponent> = ComponentMapper.getFor(javaClass<CollisionComponent>())
public val effects: ComponentMapper<EffectsComponent> = ComponentMapper.getFor(javaClass<EffectsComponent>())
public val moveTexture: ComponentMapper<MovementResourceComponent> = ComponentMapper.getFor(javaClass<MovementResourceComponent>())
public val name: ComponentMapper<NameComponent> = ComponentMapper.getFor(javaClass<NameComponent>())
public val position: ComponentMapper<PositionComponent> = ComponentMapper.getFor(javaClass<PositionComponent>())
public val race: ComponentMapper<RaceComponent> = ComponentMapper.getFor(javaClass<RaceComponent>())
public val render: ComponentMapper<RenderComponent> = ComponentMapper.getFor(javaClass<RenderComponent>())
public val resources: ComponentMapper<ResourceComponent> = ComponentMapper.getFor(javaClass<ResourceComponent>())
public val size: ComponentMapper<SizeComponent> = ComponentMapper.getFor(javaClass<SizeComponent>())
public val skills: ComponentMapper<SkillsComponent> = ComponentMapper.getFor(javaClass<SkillsComponent>())
public val walk: ComponentMapper<WalkComponent> = ComponentMapper.getFor(javaClass<WalkComponent>())
}
| mit | 8f52e7c76fd9db627d4ad3366d64e073 | 56.096154 | 135 | 0.790502 | 5.127807 | false | false | false | false |
alashow/music-android | modules/common-ui-components/src/main/java/tm/alashow/ui/components/Placeholder.kt | 1 | 959 | /*
* Copyright (C) 2021, Alashov Berkeli
* All rights reserved.
*/
package tm.alashow.ui.components
import androidx.annotation.FloatRange
import androidx.compose.animation.core.InfiniteRepeatableSpec
import androidx.compose.material.MaterialTheme
import androidx.compose.runtime.Composable
import androidx.compose.ui.graphics.Color
import com.google.accompanist.placeholder.PlaceholderDefaults
import com.google.accompanist.placeholder.PlaceholderHighlight
import com.google.accompanist.placeholder.shimmer
@Composable
fun shimmer(
highlightColor: Color = MaterialTheme.colors.secondary.copy(alpha = .15f),
animationSpec: InfiniteRepeatableSpec<Float> = PlaceholderDefaults.shimmerAnimationSpec,
@FloatRange(from = 0.0, to = 1.0) progressForMaxAlpha: Float = 0.6f,
): PlaceholderHighlight = PlaceholderHighlight.shimmer(
highlightColor = highlightColor,
animationSpec = animationSpec,
progressForMaxAlpha = progressForMaxAlpha,
)
| apache-2.0 | 48d56a179a7e03e401b7e0fe837b8561 | 37.36 | 92 | 0.813347 | 4.523585 | false | false | false | false |
valich/intellij-markdown | src/commonMain/kotlin/org/intellij/markdown/flavours/commonmark/CommonMarkMarkerProcessor.kt | 1 | 3725 | package org.intellij.markdown.flavours.commonmark
import org.intellij.markdown.MarkdownTokenTypes
import org.intellij.markdown.parser.LookaheadText
import org.intellij.markdown.parser.MarkerProcessor
import org.intellij.markdown.parser.MarkerProcessorFactory
import org.intellij.markdown.parser.ProductionHolder
import org.intellij.markdown.parser.constraints.CommonMarkdownConstraints
import org.intellij.markdown.parser.constraints.MarkdownConstraints
import org.intellij.markdown.parser.constraints.getCharsEaten
import org.intellij.markdown.parser.markerblocks.MarkerBlock
import org.intellij.markdown.parser.markerblocks.MarkerBlockProvider
import org.intellij.markdown.parser.markerblocks.providers.*
import org.intellij.markdown.parser.sequentialparsers.SequentialParser
import kotlin.math.min
open class CommonMarkMarkerProcessor(productionHolder: ProductionHolder, constraintsBase: MarkdownConstraints)
: MarkerProcessor<MarkerProcessor.StateInfo>(productionHolder, constraintsBase) {
override var stateInfo: MarkerProcessor.StateInfo = MarkerProcessor.StateInfo(startConstraints,
startConstraints,
markersStack)
private val markerBlockProviders = listOf(
CodeBlockProvider(),
HorizontalRuleProvider(),
CodeFenceProvider(),
SetextHeaderProvider(),
BlockQuoteProvider(),
ListMarkerProvider(),
AtxHeaderProvider(),
HtmlBlockProvider(),
LinkReferenceDefinitionProvider()
)
override fun getMarkerBlockProviders(): List<MarkerBlockProvider<MarkerProcessor.StateInfo>> {
return markerBlockProviders
}
override fun updateStateInfo(pos: LookaheadText.Position) {
if (pos.offsetInCurrentLine == -1) {
stateInfo = MarkerProcessor.StateInfo(startConstraints,
topBlockConstraints.applyToNextLine(pos),
markersStack)
} else if (MarkerBlockProvider.isStartOfLineWithConstraints(pos, stateInfo.nextConstraints)) {
stateInfo = MarkerProcessor.StateInfo(stateInfo.nextConstraints,
stateInfo.nextConstraints.addModifierIfNeeded(pos) ?: stateInfo.nextConstraints,
markersStack)
}
}
override fun populateConstraintsTokens(pos: LookaheadText.Position,
constraints: MarkdownConstraints,
productionHolder: ProductionHolder) {
if (constraints.indent == 0) {
return
}
val startOffset = pos.offset
val endOffset = min(pos.offset - pos.offsetInCurrentLine + constraints.getCharsEaten(pos.currentLine),
pos.nextLineOrEofOffset)
val type = when (constraints.types.lastOrNull()) {
'>' ->
MarkdownTokenTypes.BLOCK_QUOTE
'.', ')' ->
MarkdownTokenTypes.LIST_NUMBER
else ->
MarkdownTokenTypes.LIST_BULLET
}
productionHolder.addProduction(listOf(SequentialParser.Node(startOffset..endOffset, type)))
}
override fun createNewMarkerBlocks(pos: LookaheadText.Position,
productionHolder: ProductionHolder): List<MarkerBlock> {
if (pos.offsetInCurrentLine == -1) {
return NO_BLOCKS
}
return super.createNewMarkerBlocks(pos, productionHolder)
}
object Factory : MarkerProcessorFactory {
override fun createMarkerProcessor(productionHolder: ProductionHolder): MarkerProcessor<*> {
return CommonMarkMarkerProcessor(productionHolder, CommonMarkdownConstraints.BASE)
}
}
}
| apache-2.0 | 8a807b27404e119c6af4c1b92f936a95 | 41.816092 | 110 | 0.689664 | 5.912698 | false | false | false | false |
matkoniecz/StreetComplete | app/src/main/java/de/westnordost/streetcomplete/view/VerticalLabelView.kt | 2 | 3380 | package de.westnordost.streetcomplete.view
import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint.Align
import android.graphics.Rect
import android.text.TextPaint
import android.util.AttributeSet
import android.view.View
import de.westnordost.streetcomplete.R
import de.westnordost.streetcomplete.ktx.toPx
import kotlin.math.min
/** A very basic text view whose text is displayed vertically. No line break is possible */
class VerticalLabelView @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
defStyleAttr: Int = 0
) : View(context, attrs, defStyleAttr) {
private val textPaint = TextPaint()
private var text: String? = null
private val textBounds = Rect()
private val orientationRight: Boolean
init {
textPaint.isAntiAlias = true
textPaint.textAlign = Align.CENTER
val a = context.obtainStyledAttributes(attrs, R.styleable.VerticalLabelView)
setText(a.getString(R.styleable.VerticalLabelView_android_text))
setTextSize(a.getDimensionPixelSize(R.styleable.VerticalLabelView_android_textSize, 16f.toPx(context).toInt()))
setTextColor(a.getColor(R.styleable.VerticalLabelView_android_textColor, Color.BLACK))
orientationRight = a.getBoolean(R.styleable.VerticalLabelView_orientationRight, false)
a.recycle()
}
fun setText(text: String?) {
if (this.text == text) return
this.text = text
requestLayout()
invalidate()
}
fun setTextSize(size: Int) {
if (textPaint.textSize == size.toFloat()) return
textPaint.textSize = size.toFloat()
requestLayout()
invalidate()
}
fun setTextColor(color: Int) {
if (textPaint.color == color) return
textPaint.color = color
invalidate()
}
override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
text.let {
textPaint.getTextBounds(it.orEmpty(), 0, text?.length ?: 0, textBounds)
}
val desiredWidth = textBounds.height() + paddingLeft + paddingRight
val desiredHeight = textBounds.width() + paddingTop + paddingBottom
val width = reconcileSize(desiredWidth, widthMeasureSpec)
val height = reconcileSize(desiredHeight, heightMeasureSpec)
setMeasuredDimension(width, height)
}
private fun reconcileSize(contentSize: Int, measureSpec: Int): Int {
val mode = MeasureSpec.getMode(measureSpec)
val size = MeasureSpec.getSize(measureSpec)
return when (mode) {
MeasureSpec.EXACTLY -> size
MeasureSpec.AT_MOST -> min(contentSize, size)
else -> contentSize
}
}
override fun onDraw(canvas: Canvas) {
super.onDraw(canvas)
text?.let {
val originY = paddingTop + textBounds.width() / 2f
if (orientationRight) {
val originX = paddingLeft - textBounds.height() - textPaint.ascent()
canvas.translate(originX, originY)
canvas.rotate(90f)
} else {
val originX = paddingLeft - textPaint.ascent()
canvas.translate(originX, originY)
canvas.rotate(-90f)
}
canvas.drawText(it, 0f, 0f, textPaint)
}
}
}
| gpl-3.0 | 4932c9d0131490ee840095d3763b5d39 | 33.141414 | 119 | 0.657692 | 4.807966 | false | false | false | false |
naosim/rtmjava | src/main/java/com/naosim/someapp/infra/api/task/complete/TaskCompleteApi.kt | 1 | 1589 | package com.naosim.someapp.infra.api.task.complete
import com.naosim.rtm.domain.model.auth.Token
import com.naosim.someapp.domain.タスクEntity
import com.naosim.someapp.domain.タスクID
import com.naosim.someapp.domain.タスク名
import com.naosim.someapp.domain.タスク消化予定日Optional
import com.naosim.someapp.infra.MapConverter
import com.naosim.someapp.infra.RepositoryFactory
import com.naosim.someapp.infra.api.lib.Api
import com.naosim.someapp.infra.api.lib.ApiRequestParams
import com.naosim.someapp.infra.api.lib.RequiredParam
import com.naosim.someapp.infra.api.task.add.TaskAddRequest
import java.util.function.Function
class TaskCompleteApi(val repositoryFactory: RepositoryFactory): Api<TaskCompleteRequest> {
val mapConvertor = MapConverter()
override val description = "タスク完了"
override val path = "/task/complete"
override val requestParams = TaskCompleteRequest()
override val ok: (TaskCompleteRequest) -> Any = {
val タスクEntity: タスクEntity = completeTask(it.token.get(), it.taskId.get())
mapConvertor.apiOkResult(listOf(mapConvertor.toMap(タスクEntity)))
}
fun completeTask(token: Token, タスクID: タスクID): タスクEntity {
return repositoryFactory.createタスクRepository(token).完了(タスクID)
}
}
class TaskCompleteRequest : ApiRequestParams<TaskCompleteRequest>() {
@JvmField
val taskId = RequiredParam<タスクID>("task_id", Function { タスクID(it) })
@JvmField
val token = RequiredParam<Token>("token", Function { Token(it) })
} | mit | 544b53a8ac844e7983b73a963e1ef8af | 37.947368 | 91 | 0.768087 | 3.892105 | false | false | false | false |
ccomeaux/boardgamegeek4android | app/src/main/java/com/boardgamegeek/provider/BggDatabase.kt | 1 | 57791 | package com.boardgamegeek.provider
import android.content.Context
import android.content.SharedPreferences
import android.database.SQLException
import android.database.sqlite.SQLiteDatabase
import android.database.sqlite.SQLiteOpenHelper
import android.os.Environment
import android.provider.BaseColumns
import com.boardgamegeek.pref.SyncPrefs
import com.boardgamegeek.pref.clearCollection
import com.boardgamegeek.pref.clearPlaysTimestamps
import com.boardgamegeek.provider.BggContract.*
import com.boardgamegeek.provider.BggContract.Collection
import com.boardgamegeek.service.SyncService
import com.boardgamegeek.util.FileUtils.deleteContents
import com.boardgamegeek.util.TableBuilder
import com.boardgamegeek.util.TableBuilder.ColumnType
import com.boardgamegeek.util.TableBuilder.ConflictResolution
import timber.log.Timber
import java.io.File
import java.io.IOException
import java.util.*
class BggDatabase(private val context: Context?) : SQLiteOpenHelper(context, DATABASE_NAME, null, DATABASE_VERSION) {
var syncPrefs: SharedPreferences = SyncPrefs.getPrefs(context!!)
object GamesDesigners {
const val GAME_ID = Games.Columns.GAME_ID
const val DESIGNER_ID = Designers.Columns.DESIGNER_ID
}
object GamesArtists {
const val GAME_ID = Games.Columns.GAME_ID
const val ARTIST_ID = Artists.Columns.ARTIST_ID
}
object GamesPublishers {
const val GAME_ID = Games.Columns.GAME_ID
const val PUBLISHER_ID = Publishers.Columns.PUBLISHER_ID
}
object GamesMechanics {
const val GAME_ID = Games.Columns.GAME_ID
const val MECHANIC_ID = Mechanics.Columns.MECHANIC_ID
}
object GamesCategories {
const val GAME_ID = Games.Columns.GAME_ID
const val CATEGORY_ID = Categories.Columns.CATEGORY_ID
}
object Tables {
const val DESIGNERS = "designers"
const val ARTISTS = "artists"
const val PUBLISHERS = "publishers"
const val MECHANICS = "mechanics"
const val CATEGORIES = "categories"
const val GAMES = "games"
const val GAME_RANKS = "game_ranks"
const val GAMES_DESIGNERS = "games_designers"
const val GAMES_ARTISTS = "games_artists"
const val GAMES_PUBLISHERS = "games_publishers"
const val GAMES_MECHANICS = "games_mechanics"
const val GAMES_CATEGORIES = "games_categories"
const val GAMES_EXPANSIONS = "games_expansions"
const val COLLECTION = "collection"
const val BUDDIES = "buddies"
const val GAME_POLLS = "game_polls"
const val GAME_POLL_RESULTS = "game_poll_results"
const val GAME_POLL_RESULTS_RESULT = "game_poll_results_result"
const val GAME_SUGGESTED_PLAYER_COUNT_POLL_RESULTS = "game_suggested_player_count_poll_results"
const val GAME_COLORS = "game_colors"
const val PLAYS = "plays"
const val PLAY_PLAYERS = "play_players"
const val COLLECTION_VIEWS = "collection_filters"
const val COLLECTION_VIEW_FILTERS = "collection_filters_details"
const val PLAYER_COLORS = "player_colors"
val GAMES_JOIN_COLLECTION = createJoin(GAMES, COLLECTION, Games.Columns.GAME_ID)
val GAMES_DESIGNERS_JOIN_DESIGNERS = createJoin(GAMES_DESIGNERS, DESIGNERS, Designers.Columns.DESIGNER_ID)
val GAMES_ARTISTS_JOIN_ARTISTS = createJoin(GAMES_ARTISTS, ARTISTS, Artists.Columns.ARTIST_ID)
val GAMES_PUBLISHERS_JOIN_PUBLISHERS = createJoin(GAMES_PUBLISHERS, PUBLISHERS, Publishers.Columns.PUBLISHER_ID)
val GAMES_MECHANICS_JOIN_MECHANICS = createJoin(GAMES_MECHANICS, MECHANICS, Mechanics.Columns.MECHANIC_ID)
val GAMES_CATEGORIES_JOIN_CATEGORIES = createJoin(GAMES_CATEGORIES, CATEGORIES, Categories.Columns.CATEGORY_ID)
val GAMES_EXPANSIONS_JOIN_EXPANSIONS = createJoin(GAMES_EXPANSIONS, GAMES, GamesExpansions.Columns.EXPANSION_ID, Games.Columns.GAME_ID)
val GAMES_RANKS_JOIN_GAMES = createJoin(GAME_RANKS, GAMES, GameRanks.Columns.GAME_ID, Games.Columns.GAME_ID)
val POLLS_JOIN_POLL_RESULTS = createJoin(GAME_POLLS, GAME_POLL_RESULTS, BaseColumns._ID, GamePollResults.Columns.POLL_ID)
val POLLS_JOIN_GAMES = createJoin(GAMES, GAME_SUGGESTED_PLAYER_COUNT_POLL_RESULTS, Games.Columns.GAME_ID, GameSuggestedPlayerCountPollPollResults.Columns.GAME_ID)
val POLL_RESULTS_JOIN_POLL_RESULTS_RESULT =
createJoin(GAME_POLL_RESULTS, GAME_POLL_RESULTS_RESULT, BaseColumns._ID, GamePollResultsResult.Columns.POLL_RESULTS_ID)
val COLLECTION_JOIN_GAMES = createJoin(COLLECTION, GAMES, Games.Columns.GAME_ID)
val GAMES_JOIN_PLAYS = GAMES + createJoinSuffix(GAMES, PLAYS, Games.Columns.GAME_ID, Plays.Columns.OBJECT_ID)
val PLAYS_JOIN_GAMES = PLAYS + createJoinSuffix(PLAYS, GAMES, Plays.Columns.OBJECT_ID, Games.Columns.GAME_ID)
val PLAY_PLAYERS_JOIN_PLAYS = createJoin(PLAY_PLAYERS, PLAYS, PlayPlayers.Columns._PLAY_ID, BaseColumns._ID)
val PLAY_PLAYERS_JOIN_PLAYS_JOIN_USERS = PLAY_PLAYERS +
createJoinSuffix(PLAY_PLAYERS, PLAYS, PlayPlayers.Columns._PLAY_ID, BaseColumns._ID) +
createJoinSuffix(PLAY_PLAYERS, BUDDIES, PlayPlayers.Columns.USER_NAME, Buddies.Columns.BUDDY_NAME)
val PLAY_PLAYERS_JOIN_PLAYS_JOIN_GAMES = PLAY_PLAYERS +
createJoinSuffix(PLAY_PLAYERS, PLAYS, PlayPlayers.Columns._PLAY_ID, BaseColumns._ID) +
createJoinSuffix(PLAYS, GAMES, Plays.Columns.OBJECT_ID, Games.Columns.GAME_ID)
val COLLECTION_VIEW_FILTERS_JOIN_COLLECTION_VIEWS =
createJoin(COLLECTION_VIEWS, COLLECTION_VIEW_FILTERS, BaseColumns._ID, CollectionViewFilters.Columns.VIEW_ID)
val POLLS_RESULTS_RESULT_JOIN_POLLS_RESULTS_JOIN_POLLS =
createJoin(GAME_POLL_RESULTS_RESULT, GAME_POLL_RESULTS, GamePollResultsResult.Columns.POLL_RESULTS_ID, BaseColumns._ID) +
createJoinSuffix(GAME_POLL_RESULTS, GAME_POLLS, GamePollResults.Columns.POLL_ID, BaseColumns._ID)
val ARTIST_JOIN_GAMES_JOIN_COLLECTION =
createJoin(GAMES_ARTISTS, GAMES, Games.Columns.GAME_ID) + createJoinSuffix(GAMES, COLLECTION, Games.Columns.GAME_ID, Collection.Columns.GAME_ID)
val DESIGNER_JOIN_GAMES_JOIN_COLLECTION =
createJoin(GAMES_DESIGNERS, GAMES, Games.Columns.GAME_ID) + createJoinSuffix(GAMES, COLLECTION, Games.Columns.GAME_ID, Collection.Columns.GAME_ID)
val PUBLISHER_JOIN_GAMES_JOIN_COLLECTION =
createJoin(GAMES_PUBLISHERS, GAMES, Games.Columns.GAME_ID) + createJoinSuffix(GAMES, COLLECTION, Games.Columns.GAME_ID, Collection.Columns.GAME_ID)
val MECHANIC_JOIN_GAMES_JOIN_COLLECTION =
createJoin(GAMES_MECHANICS, GAMES, Games.Columns.GAME_ID) + createJoinSuffix(GAMES, COLLECTION, Games.Columns.GAME_ID, Collection.Columns.GAME_ID)
val CATEGORY_JOIN_GAMES_JOIN_COLLECTION =
createJoin(GAMES_CATEGORIES, GAMES, Games.Columns.GAME_ID) + createJoinSuffix(GAMES, COLLECTION, Games.Columns.GAME_ID, Collection.Columns.GAME_ID)
val ARTISTS_JOIN_COLLECTION = createJoin(ARTISTS, GAMES_ARTISTS, Artists.Columns.ARTIST_ID) +
createInnerJoinSuffix(GAMES_ARTISTS, COLLECTION, GamesArtists.GAME_ID, Collection.Columns.GAME_ID)
val DESIGNERS_JOIN_COLLECTION = createJoin(DESIGNERS, GAMES_DESIGNERS, Designers.Columns.DESIGNER_ID) +
createInnerJoinSuffix(GAMES_DESIGNERS, COLLECTION, GamesDesigners.GAME_ID, Collection.Columns.GAME_ID)
val PUBLISHERS_JOIN_COLLECTION = createJoin(PUBLISHERS, GAMES_PUBLISHERS, Publishers.Columns.PUBLISHER_ID) +
createInnerJoinSuffix(GAMES_PUBLISHERS, COLLECTION, GamesPublishers.GAME_ID, Collection.Columns.GAME_ID)
val MECHANICS_JOIN_COLLECTION = createJoin(MECHANICS, GAMES_MECHANICS, Mechanics.Columns.MECHANIC_ID) +
createInnerJoinSuffix(GAMES_MECHANICS, COLLECTION, GamesMechanics.GAME_ID, Collection.Columns.GAME_ID)
val CATEGORIES_JOIN_COLLECTION = createJoin(CATEGORIES, GAMES_CATEGORIES, Categories.Columns.CATEGORY_ID) +
createInnerJoinSuffix(GAMES_CATEGORIES, COLLECTION, GamesCategories.GAME_ID, Collection.Columns.GAME_ID)
private fun createJoin(table1: String, table2: String, column: String) = table1 + createJoinSuffix(table1, table2, column, column)
private fun createJoin(table1: String, table2: String, column1: String, column2: String) =
table1 + createJoinSuffix(table1, table2, column1, column2)
private fun createJoinSuffix(table1: String, table2: String, column1: String, column2: String) =
" LEFT OUTER JOIN $table2 ON $table1.$column1=$table2.$column2"
private fun createInnerJoinSuffix(table1: String, table2: String, column1: String, column2: String) =
" INNER JOIN $table2 ON $table1.$column1=$table2.$column2"
}
override fun onCreate(db: SQLiteDatabase?) {
db?.let {
buildDesignersTable().create(it)
buildArtistsTable().create(it)
buildPublishersTable().create(it)
buildMechanicsTable().create(it)
buildCategoriesTable().create(it)
buildGamesTable().create(it)
buildGameRanksTable().create(it)
buildGamesDesignersTable().create(it)
buildGamesArtistsTable().create(it)
buildGamesPublishersTable().create(it)
buildGamesMechanicsTable().create(it)
buildGamesCategoriesTable().create(it)
buildGameExpansionsTable().create(it)
buildGamePollsTable().create(it)
buildGamePollResultsTable().create(it)
buildGamePollResultsResultTable().create(it)
buildGameSuggestedPlayerCountPollResultsTable().create(it)
buildGameColorsTable().create(it)
buildPlaysTable().create(it)
buildPlayPlayersTable().create(it)
buildCollectionTable().create(it)
buildBuddiesTable().create(it)
buildPlayerColorsTable().create(it)
buildCollectionViewsTable().create(it)
buildCollectionViewFiltersTable().create(it)
}
}
override fun onUpgrade(db: SQLiteDatabase?, oldVersion: Int, newVersion: Int) {
Timber.d("Upgrading database from $oldVersion to $newVersion")
try {
for (version in oldVersion..newVersion) {
db?.let {
when (version + 1) {
VER_INITIAL -> {}
VER_WISHLIST_PRIORITY -> addColumn(it, Tables.COLLECTION, Collection.Columns.STATUS_WISHLIST_PRIORITY, ColumnType.INTEGER)
VER_GAME_COLORS -> buildGameColorsTable().create(it)
VER_EXPANSIONS -> buildGameExpansionsTable().create(it)
VER_VARIOUS -> {
addColumn(it, Tables.COLLECTION, Collection.Columns.LAST_MODIFIED, ColumnType.INTEGER)
addColumn(it, Tables.GAMES, Games.Columns.LAST_VIEWED, ColumnType.INTEGER)
addColumn(it, Tables.GAMES, Games.Columns.STARRED, ColumnType.INTEGER)
}
VER_PLAYS -> {
buildPlaysTable().create(it)
buildPlayPlayersTable().create(it)
}
VER_PLAY_NICKNAME -> addColumn(it, Tables.BUDDIES, Buddies.Columns.PLAY_NICKNAME, ColumnType.TEXT)
VER_PLAY_SYNC_STATUS -> {
addColumn(it, Tables.PLAYS, "sync_status", ColumnType.INTEGER)
addColumn(it, Tables.PLAYS, "updated", ColumnType.INTEGER)
}
VER_COLLECTION_VIEWS -> {
buildCollectionViewsTable().create(it)
buildCollectionViewFiltersTable().create(it)
}
VER_COLLECTION_VIEWS_SORT -> addColumn(it, Tables.COLLECTION_VIEWS, CollectionViews.Columns.SORT_TYPE, ColumnType.INTEGER)
VER_CASCADING_DELETE -> {
buildGameRanksTable().replace(it)
buildGamesDesignersTable().replace(it)
buildGamesArtistsTable().replace(it)
buildGamesPublishersTable().replace(it)
buildGamesMechanicsTable().replace(it)
buildGamesCategoriesTable().replace(it)
buildGameExpansionsTable().replace(it)
buildGamePollsTable().replace(it)
buildGamePollResultsTable().replace(it)
buildGamePollResultsResultTable().replace(it)
buildGameColorsTable().replace(it)
buildPlayPlayersTable().replace(it)
buildCollectionViewFiltersTable().replace(it)
}
VER_IMAGE_CACHE -> {
try {
@Suppress("DEPRECATION")
val oldCacheDirectory = File(Environment.getExternalStorageDirectory(), BggContract.CONTENT_AUTHORITY)
deleteContents(oldCacheDirectory)
if (!oldCacheDirectory.delete()) Timber.i("Unable to delete old cache directory")
} catch (e: IOException) {
Timber.e(e, "Error clearing the cache")
}
}
VER_GAMES_UPDATED_PLAYS -> addColumn(it, Tables.GAMES, Games.Columns.UPDATED_PLAYS, ColumnType.INTEGER)
VER_COLLECTION -> {
addColumn(it, Tables.COLLECTION, Collection.Columns.CONDITION, ColumnType.TEXT)
addColumn(it, Tables.COLLECTION, Collection.Columns.HASPARTS_LIST, ColumnType.TEXT)
addColumn(it, Tables.COLLECTION, Collection.Columns.WANTPARTS_LIST, ColumnType.TEXT)
addColumn(it, Tables.COLLECTION, Collection.Columns.WISHLIST_COMMENT, ColumnType.TEXT)
addColumn(it, Tables.COLLECTION, Collection.Columns.COLLECTION_YEAR_PUBLISHED, ColumnType.INTEGER)
addColumn(it, Tables.COLLECTION, Collection.Columns.RATING, ColumnType.REAL)
addColumn(it, Tables.COLLECTION, Collection.Columns.COLLECTION_THUMBNAIL_URL, ColumnType.TEXT)
addColumn(it, Tables.COLLECTION, Collection.Columns.COLLECTION_IMAGE_URL, ColumnType.TEXT)
buildCollectionTable().replace(it)
}
VER_GAME_COLLECTION_CONFLICT -> {
addColumn(it, Tables.GAMES, Games.Columns.SUBTYPE, ColumnType.TEXT)
addColumn(it, Tables.GAMES, Games.Columns.CUSTOM_PLAYER_SORT, ColumnType.INTEGER)
addColumn(it, Tables.GAMES, Games.Columns.GAME_RANK, ColumnType.INTEGER)
buildGamesTable().replace(it)
it.dropTable(Tables.COLLECTION)
buildCollectionTable().create(it)
syncPrefs.clearCollection()
SyncService.sync(context, SyncService.FLAG_SYNC_COLLECTION)
}
VER_PLAYS_START_TIME -> addColumn(it, Tables.PLAYS, Plays.Columns.START_TIME, ColumnType.INTEGER)
VER_PLAYS_PLAYER_COUNT -> {
addColumn(it, Tables.PLAYS, Plays.Columns.PLAYER_COUNT, ColumnType.INTEGER)
it.execSQL(
"UPDATE ${Tables.PLAYS} SET ${Plays.Columns.PLAYER_COUNT}=(SELECT COUNT(${PlayPlayers.Columns.USER_ID}) FROM ${Tables.PLAY_PLAYERS} WHERE ${Tables.PLAYS}.${Plays.Columns.PLAY_ID}=${Tables.PLAY_PLAYERS}.${Plays.Columns.PLAY_ID})"
)
}
VER_GAMES_SUBTYPE -> addColumn(it, Tables.GAMES, Games.Columns.SUBTYPE, ColumnType.TEXT)
VER_COLLECTION_ID_NULLABLE -> buildCollectionTable().replace(it)
VER_GAME_CUSTOM_PLAYER_SORT -> addColumn(it, Tables.GAMES, Games.Columns.CUSTOM_PLAYER_SORT, ColumnType.INTEGER)
VER_BUDDY_FLAG -> addColumn(it, Tables.BUDDIES, Buddies.Columns.BUDDY_FLAG, ColumnType.INTEGER)
VER_GAME_RANK -> addColumn(it, Tables.GAMES, Games.Columns.GAME_RANK, ColumnType.INTEGER)
VER_BUDDY_SYNC_HASH_CODE -> addColumn(it, Tables.BUDDIES, Buddies.Columns.SYNC_HASH_CODE, ColumnType.INTEGER)
VER_PLAY_SYNC_HASH_CODE -> addColumn(it, Tables.PLAYS, Plays.Columns.SYNC_HASH_CODE, ColumnType.INTEGER)
VER_PLAYER_COLORS -> buildPlayerColorsTable().create(it)
VER_RATING_DIRTY_TIMESTAMP -> addColumn(it, Tables.COLLECTION, Collection.Columns.RATING_DIRTY_TIMESTAMP, ColumnType.INTEGER)
VER_COMMENT_DIRTY_TIMESTAMP -> addColumn(it, Tables.COLLECTION, Collection.Columns.COMMENT_DIRTY_TIMESTAMP, ColumnType.INTEGER)
VER_PRIVATE_INFO_DIRTY_TIMESTAMP -> addColumn(db, Tables.COLLECTION, Collection.Columns.PRIVATE_INFO_DIRTY_TIMESTAMP, ColumnType.INTEGER)
VER_STATUS_DIRTY_TIMESTAMP -> addColumn(it, Tables.COLLECTION, Collection.Columns.STATUS_DIRTY_TIMESTAMP, ColumnType.INTEGER)
VER_COLLECTION_DIRTY_TIMESTAMP -> addColumn(it, Tables.COLLECTION, Collection.Columns.COLLECTION_DIRTY_TIMESTAMP, ColumnType.INTEGER)
VER_COLLECTION_DELETE_TIMESTAMP -> addColumn(db, Tables.COLLECTION, Collection.Columns.COLLECTION_DELETE_TIMESTAMP, ColumnType.INTEGER)
VER_COLLECTION_TIMESTAMPS -> {
addColumn(it, Tables.COLLECTION, Collection.Columns.WISHLIST_COMMENT_DIRTY_TIMESTAMP, ColumnType.INTEGER)
addColumn(it, Tables.COLLECTION, Collection.Columns.TRADE_CONDITION_DIRTY_TIMESTAMP, ColumnType.INTEGER)
addColumn(it, Tables.COLLECTION, Collection.Columns.WANT_PARTS_DIRTY_TIMESTAMP, ColumnType.INTEGER)
addColumn(it, Tables.COLLECTION, Collection.Columns.HAS_PARTS_DIRTY_TIMESTAMP, ColumnType.INTEGER)
}
VER_PLAY_ITEMS_COLLAPSE -> {
addColumn(it, Tables.PLAYS, Plays.Columns.ITEM_NAME, ColumnType.TEXT)
addColumn(it, Tables.PLAYS, Plays.Columns.OBJECT_ID, ColumnType.INTEGER)
it.execSQL("UPDATE ${Tables.PLAYS} SET ${Plays.Columns.OBJECT_ID} = (SELECT play_items.object_id FROM play_items WHERE play_items.${Plays.Columns.PLAY_ID} = ${Tables.PLAYS}.${Plays.Columns.PLAY_ID}), ${Plays.Columns.ITEM_NAME} = (SELECT play_items.name FROM play_items WHERE play_items.${Plays.Columns.PLAY_ID} = ${Tables.PLAYS}.${Plays.Columns.PLAY_ID})")
it.dropTable("play_items")
}
VER_PLAY_PLAYERS_KEY -> {
val columnMap: MutableMap<String, String> = HashMap()
columnMap[PlayPlayers.Columns._PLAY_ID] = "${Tables.PLAYS}.${BaseColumns._ID}"
buildPlayPlayersTable().replace(it, columnMap, Tables.PLAYS, Plays.Columns.PLAY_ID)
}
VER_PLAY_DELETE_TIMESTAMP -> {
addColumn(it, Tables.PLAYS, Plays.Columns.DELETE_TIMESTAMP, ColumnType.INTEGER)
it.execSQL("UPDATE ${Tables.PLAYS} SET ${Plays.Columns.DELETE_TIMESTAMP}=${System.currentTimeMillis()}, sync_status=0 WHERE sync_status=3") // 3 = deleted sync status
}
VER_PLAY_UPDATE_TIMESTAMP -> {
addColumn(it, Tables.PLAYS, Plays.Columns.UPDATE_TIMESTAMP, ColumnType.INTEGER)
it.execSQL("UPDATE ${Tables.PLAYS} SET ${Plays.Columns.UPDATE_TIMESTAMP}=${System.currentTimeMillis()}, sync_status=0 WHERE sync_status=1") // 1 = update sync status
}
VER_PLAY_DIRTY_TIMESTAMP -> {
addColumn(it, Tables.PLAYS, Plays.Columns.DIRTY_TIMESTAMP, ColumnType.INTEGER)
it.execSQL("UPDATE ${Tables.PLAYS} SET ${Plays.Columns.DIRTY_TIMESTAMP}=${System.currentTimeMillis()}, sync_status=0 WHERE sync_status=2") // 2 = in progress
}
VER_PLAY_PLAY_ID_NOT_REQUIRED -> {
buildPlaysTable().replace(it)
it.execSQL("UPDATE ${Tables.PLAYS} SET ${Plays.Columns.PLAY_ID}=null WHERE ${Plays.Columns.PLAY_ID}>=100000000 AND (${Plays.Columns.DIRTY_TIMESTAMP}>0 OR ${Plays.Columns.UPDATE_TIMESTAMP}>0 OR ${Plays.Columns.DELETE_TIMESTAMP}>0)")
it.execSQL("UPDATE ${Tables.PLAYS} SET ${Plays.Columns.DIRTY_TIMESTAMP}=${System.currentTimeMillis()}, ${Plays.Columns.PLAY_ID}=null WHERE ${Plays.Columns.PLAY_ID}>=100000000")
}
VER_PLAYS_RESET -> {
syncPrefs.clearPlaysTimestamps()
it.execSQL("UPDATE ${Tables.PLAYS} SET ${Plays.Columns.SYNC_HASH_CODE}=0")
SyncService.sync(context!!, SyncService.FLAG_SYNC_PLAYS)
}
VER_PLAYS_HARD_RESET -> {
it.dropTable(Tables.PLAYS)
it.dropTable(Tables.PLAY_PLAYERS)
buildPlaysTable().create(it)
buildPlayPlayersTable().create(it)
syncPrefs.clearPlaysTimestamps()
SyncService.sync(context, SyncService.FLAG_SYNC_PLAYS)
}
VER_COLLECTION_VIEWS_SELECTED_COUNT -> {
addColumn(it, Tables.COLLECTION_VIEWS, CollectionViews.Columns.SELECTED_COUNT, ColumnType.INTEGER)
addColumn(it, Tables.COLLECTION_VIEWS, CollectionViews.Columns.SELECTED_TIMESTAMP, ColumnType.INTEGER)
}
VER_SUGGESTED_PLAYER_COUNT_POLL -> {
addColumn(it, Tables.GAMES, Games.Columns.SUGGESTED_PLAYER_COUNT_POLL_VOTE_TOTAL, ColumnType.INTEGER)
buildGameSuggestedPlayerCountPollResultsTable().create(it)
}
VER_SUGGESTED_PLAYER_COUNT_RECOMMENDATION -> addColumn(
db,
Tables.GAME_SUGGESTED_PLAYER_COUNT_POLL_RESULTS,
GameSuggestedPlayerCountPollPollResults.Columns.RECOMMENDATION,
ColumnType.INTEGER
)
VER_MIN_MAX_PLAYING_TIME -> {
addColumn(it, Tables.GAMES, Games.Columns.MIN_PLAYING_TIME, ColumnType.INTEGER)
addColumn(it, Tables.GAMES, Games.Columns.MAX_PLAYING_TIME, ColumnType.INTEGER)
}
VER_SUGGESTED_PLAYER_COUNT_RE_SYNC -> {
it.execSQL("UPDATE ${Tables.GAMES} SET ${Games.Columns.UPDATED_LIST}=0, ${Games.Columns.UPDATED}=0, ${Games.Columns.UPDATED_PLAYS}=0")
SyncService.sync(context, SyncService.FLAG_SYNC_GAMES)
}
VER_GAME_HERO_IMAGE_URL -> addColumn(it, Tables.GAMES, Games.Columns.HERO_IMAGE_URL, ColumnType.TEXT)
VER_COLLECTION_HERO_IMAGE_URL -> addColumn(it, Tables.COLLECTION, Collection.Columns.COLLECTION_HERO_IMAGE_URL, ColumnType.TEXT)
VER_GAME_PALETTE_COLORS -> {
addColumn(it, Tables.GAMES, Games.Columns.ICON_COLOR, ColumnType.INTEGER)
addColumn(it, Tables.GAMES, Games.Columns.DARK_COLOR, ColumnType.INTEGER)
addColumn(it, Tables.GAMES, Games.Columns.WINS_COLOR, ColumnType.INTEGER)
addColumn(it, Tables.GAMES, Games.Columns.WINNABLE_PLAYS_COLOR, ColumnType.INTEGER)
addColumn(it, Tables.GAMES, Games.Columns.ALL_PLAYS_COLOR, ColumnType.INTEGER)
}
VER_PRIVATE_INFO_INVENTORY_LOCATION -> addColumn(db, Tables.COLLECTION, Collection.Columns.PRIVATE_INFO_INVENTORY_LOCATION, ColumnType.TEXT)
VER_ARTIST_IMAGES -> {
addColumn(it, Tables.ARTISTS, Artists.Columns.ARTIST_IMAGE_URL, ColumnType.TEXT)
addColumn(it, Tables.ARTISTS, Artists.Columns.ARTIST_THUMBNAIL_URL, ColumnType.TEXT)
addColumn(it, Tables.ARTISTS, Artists.Columns.ARTIST_HERO_IMAGE_URL, ColumnType.TEXT)
addColumn(it, Tables.ARTISTS, Artists.Columns.ARTIST_IMAGES_UPDATED_TIMESTAMP, ColumnType.INTEGER)
}
VER_DESIGNER_IMAGES -> {
addColumn(it, Tables.DESIGNERS, Designers.Columns.DESIGNER_IMAGE_URL, ColumnType.TEXT)
addColumn(it, Tables.DESIGNERS, Designers.Columns.DESIGNER_THUMBNAIL_URL, ColumnType.TEXT)
addColumn(it, Tables.DESIGNERS, Designers.Columns.DESIGNER_HERO_IMAGE_URL, ColumnType.TEXT)
addColumn(it, Tables.DESIGNERS, Designers.Columns.DESIGNER_IMAGES_UPDATED_TIMESTAMP, ColumnType.INTEGER)
}
VER_PUBLISHER_IMAGES -> {
addColumn(it, Tables.PUBLISHERS, Publishers.Columns.PUBLISHER_IMAGE_URL, ColumnType.TEXT)
addColumn(it, Tables.PUBLISHERS, Publishers.Columns.PUBLISHER_THUMBNAIL_URL, ColumnType.TEXT)
addColumn(it, Tables.PUBLISHERS, Publishers.Columns.PUBLISHER_HERO_IMAGE_URL, ColumnType.TEXT)
addColumn(it, Tables.PUBLISHERS, Publishers.Columns.PUBLISHER_SORT_NAME, ColumnType.INTEGER)
}
VER_WHITMORE_SCORE -> {
addColumn(it, Tables.DESIGNERS, Designers.Columns.WHITMORE_SCORE, ColumnType.INTEGER)
addColumn(it, Tables.ARTISTS, Artists.Columns.WHITMORE_SCORE, ColumnType.INTEGER)
addColumn(it, Tables.PUBLISHERS, Publishers.Columns.WHITMORE_SCORE, ColumnType.INTEGER)
}
VER_DAP_STATS_UPDATED_TIMESTAMP -> {
addColumn(it, Tables.DESIGNERS, Designers.Columns.DESIGNER_STATS_UPDATED_TIMESTAMP, ColumnType.INTEGER)
addColumn(it, Tables.ARTISTS, Artists.Columns.ARTIST_STATS_UPDATED_TIMESTAMP, ColumnType.INTEGER)
addColumn(it, Tables.PUBLISHERS, Publishers.Columns.PUBLISHER_STATS_UPDATED_TIMESTAMP, ColumnType.INTEGER)
}
VER_RECOMMENDED_PLAYER_COUNTS -> {
addColumn(it, Tables.GAMES, Games.Columns.PLAYER_COUNTS_BEST, ColumnType.TEXT)
addColumn(it, Tables.GAMES, Games.Columns.PLAYER_COUNTS_RECOMMENDED, ColumnType.TEXT)
addColumn(it, Tables.GAMES, Games.Columns.PLAYER_COUNTS_NOT_RECOMMENDED, ColumnType.TEXT)
it.execSQL("UPDATE ${Tables.GAMES} SET ${Games.Columns.UPDATED_LIST}=0, ${Games.Columns.UPDATED}=0, ${Games.Columns.UPDATED_PLAYS}=0")
SyncService.sync(context, SyncService.FLAG_SYNC_GAMES)
}
}
}
}
} catch (e: Exception) {
Timber.e(e)
recreateDatabase(db)
}
}
override fun onOpen(db: SQLiteDatabase?) {
super.onOpen(db)
if (db?.isReadOnly == false) {
db.execSQL("PRAGMA foreign_keys=ON;")
}
}
private fun buildDesignersTable() = TableBuilder()
.setTable(Tables.DESIGNERS)
.useDefaultPrimaryKey()
.addColumn(Designers.Columns.UPDATED, ColumnType.INTEGER)
.addColumn(Designers.Columns.DESIGNER_ID, ColumnType.INTEGER, notNull = true, unique = true)
.addColumn(Designers.Columns.DESIGNER_NAME, ColumnType.TEXT, true)
.addColumn(Designers.Columns.DESIGNER_DESCRIPTION, ColumnType.TEXT)
.addColumn(Designers.Columns.DESIGNER_IMAGE_URL, ColumnType.TEXT)
.addColumn(Designers.Columns.DESIGNER_THUMBNAIL_URL, ColumnType.TEXT)
.addColumn(Designers.Columns.DESIGNER_HERO_IMAGE_URL, ColumnType.TEXT)
.addColumn(Designers.Columns.DESIGNER_IMAGES_UPDATED_TIMESTAMP, ColumnType.INTEGER)
.addColumn(Designers.Columns.WHITMORE_SCORE, ColumnType.INTEGER)
.addColumn(Designers.Columns.DESIGNER_STATS_UPDATED_TIMESTAMP, ColumnType.INTEGER)
private fun buildArtistsTable() = TableBuilder()
.setTable(Tables.ARTISTS)
.useDefaultPrimaryKey()
.addColumn(Artists.Columns.UPDATED, ColumnType.INTEGER)
.addColumn(Artists.Columns.ARTIST_ID, ColumnType.INTEGER, notNull = true, unique = true)
.addColumn(Artists.Columns.ARTIST_NAME, ColumnType.TEXT, true)
.addColumn(Artists.Columns.ARTIST_DESCRIPTION, ColumnType.TEXT)
.addColumn(Artists.Columns.ARTIST_IMAGE_URL, ColumnType.TEXT)
.addColumn(Artists.Columns.ARTIST_THUMBNAIL_URL, ColumnType.TEXT)
.addColumn(Artists.Columns.ARTIST_HERO_IMAGE_URL, ColumnType.TEXT)
.addColumn(Artists.Columns.ARTIST_IMAGES_UPDATED_TIMESTAMP, ColumnType.INTEGER)
.addColumn(Artists.Columns.WHITMORE_SCORE, ColumnType.INTEGER)
.addColumn(Artists.Columns.ARTIST_STATS_UPDATED_TIMESTAMP, ColumnType.INTEGER)
private fun buildPublishersTable() = TableBuilder()
.setTable(Tables.PUBLISHERS)
.useDefaultPrimaryKey()
.addColumn(Publishers.Columns.UPDATED, ColumnType.INTEGER)
.addColumn(Publishers.Columns.PUBLISHER_ID, ColumnType.INTEGER, true, unique = true)
.addColumn(Publishers.Columns.PUBLISHER_NAME, ColumnType.TEXT, true)
.addColumn(Publishers.Columns.PUBLISHER_DESCRIPTION, ColumnType.TEXT)
.addColumn(Publishers.Columns.PUBLISHER_IMAGE_URL, ColumnType.TEXT)
.addColumn(Publishers.Columns.PUBLISHER_THUMBNAIL_URL, ColumnType.TEXT)
.addColumn(Publishers.Columns.PUBLISHER_HERO_IMAGE_URL, ColumnType.TEXT)
.addColumn(Publishers.Columns.PUBLISHER_SORT_NAME, ColumnType.TEXT)
.addColumn(Publishers.Columns.WHITMORE_SCORE, ColumnType.INTEGER)
.addColumn(Publishers.Columns.PUBLISHER_STATS_UPDATED_TIMESTAMP, ColumnType.INTEGER)
private fun buildMechanicsTable() = TableBuilder()
.setTable(Tables.MECHANICS)
.useDefaultPrimaryKey()
.addColumn(Mechanics.Columns.MECHANIC_ID, ColumnType.INTEGER, notNull = true, unique = true)
.addColumn(Mechanics.Columns.MECHANIC_NAME, ColumnType.TEXT, true)
private fun buildCategoriesTable() = TableBuilder()
.setTable(Tables.CATEGORIES)
.useDefaultPrimaryKey()
.addColumn(Categories.Columns.CATEGORY_ID, ColumnType.INTEGER, notNull = true, unique = true)
.addColumn(Categories.Columns.CATEGORY_NAME, ColumnType.TEXT, true)
private fun buildGamesTable() = TableBuilder()
.setTable(Tables.GAMES)
.useDefaultPrimaryKey()
.addColumn(Games.Columns.UPDATED, ColumnType.INTEGER)
.addColumn(Games.Columns.UPDATED_LIST, ColumnType.INTEGER, true)
.addColumn(Games.Columns.GAME_ID, ColumnType.INTEGER, notNull = true, unique = true)
.addColumn(Games.Columns.GAME_NAME, ColumnType.TEXT, true)
.addColumn(Games.Columns.GAME_SORT_NAME, ColumnType.TEXT, true)
.addColumn(Games.Columns.YEAR_PUBLISHED, ColumnType.INTEGER)
.addColumn(Games.Columns.IMAGE_URL, ColumnType.TEXT)
.addColumn(Games.Columns.THUMBNAIL_URL, ColumnType.TEXT)
.addColumn(Games.Columns.MIN_PLAYERS, ColumnType.INTEGER)
.addColumn(Games.Columns.MAX_PLAYERS, ColumnType.INTEGER)
.addColumn(Games.Columns.PLAYING_TIME, ColumnType.INTEGER)
.addColumn(Games.Columns.MIN_PLAYING_TIME, ColumnType.INTEGER)
.addColumn(Games.Columns.MAX_PLAYING_TIME, ColumnType.INTEGER)
.addColumn(Games.Columns.NUM_PLAYS, ColumnType.INTEGER, true, 0)
.addColumn(Games.Columns.MINIMUM_AGE, ColumnType.INTEGER)
.addColumn(Games.Columns.DESCRIPTION, ColumnType.TEXT)
.addColumn(Games.Columns.SUBTYPE, ColumnType.TEXT)
.addColumn(Games.Columns.STATS_USERS_RATED, ColumnType.INTEGER)
.addColumn(Games.Columns.STATS_AVERAGE, ColumnType.REAL)
.addColumn(Games.Columns.STATS_BAYES_AVERAGE, ColumnType.REAL)
.addColumn(Games.Columns.STATS_STANDARD_DEVIATION, ColumnType.REAL)
.addColumn(Games.Columns.STATS_MEDIAN, ColumnType.INTEGER)
.addColumn(Games.Columns.STATS_NUMBER_OWNED, ColumnType.INTEGER)
.addColumn(Games.Columns.STATS_NUMBER_TRADING, ColumnType.INTEGER)
.addColumn(Games.Columns.STATS_NUMBER_WANTING, ColumnType.INTEGER)
.addColumn(Games.Columns.STATS_NUMBER_WISHING, ColumnType.INTEGER)
.addColumn(Games.Columns.STATS_NUMBER_COMMENTS, ColumnType.INTEGER)
.addColumn(Games.Columns.STATS_NUMBER_WEIGHTS, ColumnType.INTEGER)
.addColumn(Games.Columns.STATS_AVERAGE_WEIGHT, ColumnType.REAL)
.addColumn(Games.Columns.LAST_VIEWED, ColumnType.INTEGER)
.addColumn(Games.Columns.STARRED, ColumnType.INTEGER)
.addColumn(Games.Columns.UPDATED_PLAYS, ColumnType.INTEGER)
.addColumn(Games.Columns.CUSTOM_PLAYER_SORT, ColumnType.INTEGER)
.addColumn(Games.Columns.GAME_RANK, ColumnType.INTEGER)
.addColumn(Games.Columns.SUGGESTED_PLAYER_COUNT_POLL_VOTE_TOTAL, ColumnType.INTEGER)
.addColumn(Games.Columns.HERO_IMAGE_URL, ColumnType.TEXT)
.addColumn(Games.Columns.ICON_COLOR, ColumnType.INTEGER)
.addColumn(Games.Columns.DARK_COLOR, ColumnType.INTEGER)
.addColumn(Games.Columns.WINS_COLOR, ColumnType.INTEGER)
.addColumn(Games.Columns.WINNABLE_PLAYS_COLOR, ColumnType.INTEGER)
.addColumn(Games.Columns.ALL_PLAYS_COLOR, ColumnType.INTEGER)
.addColumn(Games.Columns.PLAYER_COUNTS_BEST, ColumnType.TEXT)
.addColumn(Games.Columns.PLAYER_COUNTS_RECOMMENDED, ColumnType.TEXT)
.addColumn(Games.Columns.PLAYER_COUNTS_NOT_RECOMMENDED, ColumnType.TEXT)
.setConflictResolution(ConflictResolution.ABORT)
private fun buildGameRanksTable() = TableBuilder()
.setTable(Tables.GAME_RANKS)
.useDefaultPrimaryKey()
.addColumn(
GameRanks.Columns.GAME_ID, ColumnType.INTEGER,
notNull = true,
unique = true,
referenceTable = Tables.GAMES,
referenceColumn = Games.Columns.GAME_ID,
onCascadeDelete = true
)
.addColumn(GameRanks.Columns.GAME_RANK_ID, ColumnType.INTEGER, notNull = true, unique = true)
.addColumn(GameRanks.Columns.GAME_RANK_TYPE, ColumnType.TEXT, true)
.addColumn(GameRanks.Columns.GAME_RANK_NAME, ColumnType.TEXT, true)
.addColumn(GameRanks.Columns.GAME_RANK_FRIENDLY_NAME, ColumnType.TEXT, true)
.addColumn(GameRanks.Columns.GAME_RANK_VALUE, ColumnType.INTEGER, true)
.addColumn(GameRanks.Columns.GAME_RANK_BAYES_AVERAGE, ColumnType.REAL, true)
.setConflictResolution(ConflictResolution.REPLACE)
private fun buildGamesDesignersTable() = TableBuilder()
.setTable(Tables.GAMES_DESIGNERS)
.useDefaultPrimaryKey()
.addColumn(
GamesDesigners.GAME_ID, ColumnType.INTEGER,
notNull = true,
unique = true,
referenceTable = Tables.GAMES,
referenceColumn = Games.Columns.GAME_ID,
onCascadeDelete = true
)
.addColumn(
GamesDesigners.DESIGNER_ID, ColumnType.INTEGER, true,
unique = true,
referenceTable = Tables.DESIGNERS,
referenceColumn = Designers.Columns.DESIGNER_ID
)
private fun buildGamesArtistsTable() = TableBuilder().setTable(Tables.GAMES_ARTISTS).useDefaultPrimaryKey()
.addColumn(
GamesArtists.GAME_ID,
ColumnType.INTEGER,
notNull = true,
unique = true,
referenceTable = Tables.GAMES,
referenceColumn = Games.Columns.GAME_ID,
onCascadeDelete = true
)
.addColumn(
GamesArtists.ARTIST_ID,
ColumnType.INTEGER,
notNull = true,
unique = true,
referenceTable = Tables.ARTISTS,
referenceColumn = Artists.Columns.ARTIST_ID
)
private fun buildGamesPublishersTable() = TableBuilder()
.setTable(Tables.GAMES_PUBLISHERS)
.useDefaultPrimaryKey()
.addColumn(
GamesPublishers.GAME_ID,
ColumnType.INTEGER,
notNull = true,
unique = true,
referenceTable = Tables.GAMES,
referenceColumn = Games.Columns.GAME_ID,
onCascadeDelete = true
)
.addColumn(
GamesPublishers.PUBLISHER_ID,
ColumnType.INTEGER,
notNull = true,
unique = true,
referenceTable = Tables.PUBLISHERS,
referenceColumn = Publishers.Columns.PUBLISHER_ID
)
private fun buildGamesMechanicsTable() = TableBuilder()
.setTable(Tables.GAMES_MECHANICS)
.useDefaultPrimaryKey()
.addColumn(
GamesMechanics.GAME_ID,
ColumnType.INTEGER,
notNull = true,
unique = true,
referenceTable = Tables.GAMES,
referenceColumn = Games.Columns.GAME_ID,
onCascadeDelete = true
)
.addColumn(
GamesMechanics.MECHANIC_ID,
ColumnType.INTEGER,
notNull = true,
unique = true,
referenceTable = Tables.MECHANICS,
referenceColumn = Mechanics.Columns.MECHANIC_ID
)
private fun buildGamesCategoriesTable() = TableBuilder()
.setTable(Tables.GAMES_CATEGORIES)
.useDefaultPrimaryKey()
.addColumn(
GamesCategories.GAME_ID,
ColumnType.INTEGER,
true,
unique = true,
referenceTable = Tables.GAMES,
referenceColumn = Games.Columns.GAME_ID,
onCascadeDelete = true
)
.addColumn(
GamesCategories.CATEGORY_ID,
ColumnType.INTEGER,
true,
unique = true,
referenceTable = Tables.CATEGORIES,
referenceColumn = Categories.Columns.CATEGORY_ID
)
private fun buildGameExpansionsTable() = TableBuilder()
.setTable(Tables.GAMES_EXPANSIONS)
.useDefaultPrimaryKey()
.addColumn(
GamesExpansions.Columns.GAME_ID, ColumnType.INTEGER,
notNull = true,
unique = true,
referenceTable = Tables.GAMES,
referenceColumn = Games.Columns.GAME_ID,
onCascadeDelete = true
)
.addColumn(GamesExpansions.Columns.EXPANSION_ID, ColumnType.INTEGER, notNull = true, unique = true)
.addColumn(GamesExpansions.Columns.EXPANSION_NAME, ColumnType.TEXT, true)
.addColumn(GamesExpansions.Columns.INBOUND, ColumnType.INTEGER)
private fun buildGamePollsTable() = TableBuilder()
.setTable(Tables.GAME_POLLS)
.useDefaultPrimaryKey()
.addColumn(
GamePolls.Columns.GAME_ID,
ColumnType.INTEGER,
notNull = true,
unique = true,
referenceTable = Tables.GAMES,
referenceColumn = Games.Columns.GAME_ID,
onCascadeDelete = true
)
.addColumn(GamePolls.Columns.POLL_NAME, ColumnType.TEXT, notNull = true, unique = true)
.addColumn(GamePolls.Columns.POLL_TITLE, ColumnType.TEXT, true)
.addColumn(GamePolls.Columns.POLL_TOTAL_VOTES, ColumnType.INTEGER, true)
private fun buildGamePollResultsTable() = TableBuilder()
.setTable(Tables.GAME_POLL_RESULTS)
.useDefaultPrimaryKey()
.addColumn(
GamePollResults.Columns.POLL_ID,
ColumnType.INTEGER,
notNull = true,
unique = true,
referenceTable = Tables.GAME_POLLS,
referenceColumn = BaseColumns._ID,
onCascadeDelete = true
)
.addColumn(GamePollResults.Columns.POLL_RESULTS_KEY, ColumnType.TEXT, notNull = true, unique = true)
.addColumn(GamePollResults.Columns.POLL_RESULTS_PLAYERS, ColumnType.TEXT)
.addColumn(GamePollResults.Columns.POLL_RESULTS_SORT_INDEX, ColumnType.INTEGER, true)
private fun buildGamePollResultsResultTable() = TableBuilder()
.setTable(Tables.GAME_POLL_RESULTS_RESULT)
.useDefaultPrimaryKey()
.addColumn(
GamePollResultsResult.Columns.POLL_RESULTS_ID,
ColumnType.INTEGER,
notNull = true,
unique = true,
referenceTable = Tables.GAME_POLL_RESULTS,
referenceColumn = BaseColumns._ID,
onCascadeDelete = true
)
.addColumn(GamePollResultsResult.Columns.POLL_RESULTS_RESULT_KEY, ColumnType.TEXT, notNull = true, unique = true)
.addColumn(GamePollResultsResult.Columns.POLL_RESULTS_RESULT_LEVEL, ColumnType.INTEGER)
.addColumn(GamePollResultsResult.Columns.POLL_RESULTS_RESULT_VALUE, ColumnType.TEXT, true)
.addColumn(GamePollResultsResult.Columns.POLL_RESULTS_RESULT_VOTES, ColumnType.INTEGER, true)
.addColumn(GamePollResultsResult.Columns.POLL_RESULTS_RESULT_SORT_INDEX, ColumnType.INTEGER, true)
private fun buildGameSuggestedPlayerCountPollResultsTable() = TableBuilder()
.setTable(Tables.GAME_SUGGESTED_PLAYER_COUNT_POLL_RESULTS)
.useDefaultPrimaryKey()
.addColumn(
GameSuggestedPlayerCountPollPollResults.Columns.GAME_ID,
ColumnType.INTEGER,
notNull = true,
unique = true,
referenceTable = Tables.GAMES,
referenceColumn = Games.Columns.GAME_ID,
onCascadeDelete = true
)
.addColumn(GameSuggestedPlayerCountPollPollResults.Columns.PLAYER_COUNT, ColumnType.INTEGER, notNull = true, unique = true)
.addColumn(GameSuggestedPlayerCountPollPollResults.Columns.SORT_INDEX, ColumnType.INTEGER)
.addColumn(GameSuggestedPlayerCountPollPollResults.Columns.BEST_VOTE_COUNT, ColumnType.INTEGER)
.addColumn(GameSuggestedPlayerCountPollPollResults.Columns.RECOMMENDED_VOTE_COUNT, ColumnType.INTEGER)
.addColumn(GameSuggestedPlayerCountPollPollResults.Columns.NOT_RECOMMENDED_VOTE_COUNT, ColumnType.INTEGER)
.addColumn(GameSuggestedPlayerCountPollPollResults.Columns.RECOMMENDATION, ColumnType.INTEGER)
private fun buildGameColorsTable() = TableBuilder()
.setTable(Tables.GAME_COLORS)
.useDefaultPrimaryKey()
.addColumn(
GameColors.Columns.GAME_ID,
ColumnType.INTEGER,
notNull = true,
unique = true,
referenceTable = Tables.GAMES,
referenceColumn = Games.Columns.GAME_ID,
onCascadeDelete = true
)
.addColumn(GameColors.Columns.COLOR, ColumnType.TEXT, notNull = true, unique = true)
private fun buildPlaysTable() = TableBuilder()
.setTable(Tables.PLAYS)
.useDefaultPrimaryKey()
.addColumn(Plays.Columns.SYNC_TIMESTAMP, ColumnType.INTEGER, true)
.addColumn(Plays.Columns.PLAY_ID, ColumnType.INTEGER)
.addColumn(Plays.Columns.DATE, ColumnType.TEXT, true)
.addColumn(Plays.Columns.QUANTITY, ColumnType.INTEGER, true)
.addColumn(Plays.Columns.LENGTH, ColumnType.INTEGER, true)
.addColumn(Plays.Columns.INCOMPLETE, ColumnType.INTEGER, true)
.addColumn(Plays.Columns.NO_WIN_STATS, ColumnType.INTEGER, true)
.addColumn(Plays.Columns.LOCATION, ColumnType.TEXT)
.addColumn(Plays.Columns.COMMENTS, ColumnType.TEXT)
.addColumn(Plays.Columns.START_TIME, ColumnType.INTEGER)
.addColumn(Plays.Columns.PLAYER_COUNT, ColumnType.INTEGER)
.addColumn(Plays.Columns.SYNC_HASH_CODE, ColumnType.INTEGER)
.addColumn(Plays.Columns.ITEM_NAME, ColumnType.TEXT, true)
.addColumn(Plays.Columns.OBJECT_ID, ColumnType.INTEGER, true)
.addColumn(Plays.Columns.DELETE_TIMESTAMP, ColumnType.INTEGER)
.addColumn(Plays.Columns.UPDATE_TIMESTAMP, ColumnType.INTEGER)
.addColumn(Plays.Columns.DIRTY_TIMESTAMP, ColumnType.INTEGER)
private fun buildPlayPlayersTable() = TableBuilder()
.setTable(Tables.PLAY_PLAYERS)
.useDefaultPrimaryKey()
.addColumn(
PlayPlayers.Columns._PLAY_ID,
ColumnType.INTEGER,
notNull = true,
unique = false,
referenceTable = Tables.PLAYS,
referenceColumn = BaseColumns._ID,
onCascadeDelete = true
)
.addColumn(PlayPlayers.Columns.USER_NAME, ColumnType.TEXT)
.addColumn(PlayPlayers.Columns.USER_ID, ColumnType.INTEGER)
.addColumn(PlayPlayers.Columns.NAME, ColumnType.TEXT)
.addColumn(PlayPlayers.Columns.START_POSITION, ColumnType.TEXT)
.addColumn(PlayPlayers.Columns.COLOR, ColumnType.TEXT)
.addColumn(PlayPlayers.Columns.SCORE, ColumnType.TEXT)
.addColumn(PlayPlayers.Columns.NEW, ColumnType.INTEGER)
.addColumn(PlayPlayers.Columns.RATING, ColumnType.REAL)
.addColumn(PlayPlayers.Columns.WIN, ColumnType.INTEGER)
private fun buildCollectionTable(): TableBuilder = TableBuilder()
.setTable(Tables.COLLECTION)
.useDefaultPrimaryKey()
.addColumn(Collection.Columns.UPDATED, ColumnType.INTEGER)
.addColumn(Collection.Columns.UPDATED_LIST, ColumnType.INTEGER)
.addColumn(
Collection.Columns.GAME_ID,
ColumnType.INTEGER,
notNull = true,
unique = false,
referenceTable = Tables.GAMES,
referenceColumn = Games.Columns.GAME_ID,
onCascadeDelete = true
)
.addColumn(Collection.Columns.COLLECTION_ID, ColumnType.INTEGER)
.addColumn(Collection.Columns.COLLECTION_NAME, ColumnType.TEXT, true)
.addColumn(Collection.Columns.COLLECTION_SORT_NAME, ColumnType.TEXT, true)
.addColumn(Collection.Columns.STATUS_OWN, ColumnType.INTEGER, true, 0)
.addColumn(Collection.Columns.STATUS_PREVIOUSLY_OWNED, ColumnType.INTEGER, true, 0)
.addColumn(Collection.Columns.STATUS_FOR_TRADE, ColumnType.INTEGER, true, 0)
.addColumn(Collection.Columns.STATUS_WANT, ColumnType.INTEGER, true, 0)
.addColumn(Collection.Columns.STATUS_WANT_TO_PLAY, ColumnType.INTEGER, true, 0)
.addColumn(Collection.Columns.STATUS_WANT_TO_BUY, ColumnType.INTEGER, true, 0)
.addColumn(Collection.Columns.STATUS_WISHLIST_PRIORITY, ColumnType.INTEGER)
.addColumn(Collection.Columns.STATUS_WISHLIST, ColumnType.INTEGER, true, 0)
.addColumn(Collection.Columns.STATUS_PREORDERED, ColumnType.INTEGER, true, 0)
.addColumn(Collection.Columns.COMMENT, ColumnType.TEXT)
.addColumn(Collection.Columns.LAST_MODIFIED, ColumnType.INTEGER)
.addColumn(Collection.Columns.PRIVATE_INFO_PRICE_PAID_CURRENCY, ColumnType.TEXT)
.addColumn(Collection.Columns.PRIVATE_INFO_PRICE_PAID, ColumnType.REAL)
.addColumn(Collection.Columns.PRIVATE_INFO_CURRENT_VALUE_CURRENCY, ColumnType.TEXT)
.addColumn(Collection.Columns.PRIVATE_INFO_CURRENT_VALUE, ColumnType.REAL)
.addColumn(Collection.Columns.PRIVATE_INFO_QUANTITY, ColumnType.INTEGER)
.addColumn(Collection.Columns.PRIVATE_INFO_ACQUISITION_DATE, ColumnType.TEXT)
.addColumn(Collection.Columns.PRIVATE_INFO_ACQUIRED_FROM, ColumnType.TEXT)
.addColumn(Collection.Columns.PRIVATE_INFO_COMMENT, ColumnType.TEXT)
.addColumn(Collection.Columns.CONDITION, ColumnType.TEXT)
.addColumn(Collection.Columns.HASPARTS_LIST, ColumnType.TEXT)
.addColumn(Collection.Columns.WANTPARTS_LIST, ColumnType.TEXT)
.addColumn(Collection.Columns.WISHLIST_COMMENT, ColumnType.TEXT)
.addColumn(Collection.Columns.COLLECTION_YEAR_PUBLISHED, ColumnType.INTEGER)
.addColumn(Collection.Columns.RATING, ColumnType.REAL)
.addColumn(Collection.Columns.COLLECTION_THUMBNAIL_URL, ColumnType.TEXT)
.addColumn(Collection.Columns.COLLECTION_IMAGE_URL, ColumnType.TEXT)
.addColumn(Collection.Columns.STATUS_DIRTY_TIMESTAMP, ColumnType.INTEGER)
.addColumn(Collection.Columns.RATING_DIRTY_TIMESTAMP, ColumnType.INTEGER)
.addColumn(Collection.Columns.COMMENT_DIRTY_TIMESTAMP, ColumnType.INTEGER)
.addColumn(Collection.Columns.PRIVATE_INFO_DIRTY_TIMESTAMP, ColumnType.INTEGER)
.addColumn(Collection.Columns.COLLECTION_DIRTY_TIMESTAMP, ColumnType.INTEGER)
.addColumn(Collection.Columns.COLLECTION_DELETE_TIMESTAMP, ColumnType.INTEGER)
.addColumn(Collection.Columns.WISHLIST_COMMENT_DIRTY_TIMESTAMP, ColumnType.INTEGER)
.addColumn(Collection.Columns.TRADE_CONDITION_DIRTY_TIMESTAMP, ColumnType.INTEGER)
.addColumn(Collection.Columns.WANT_PARTS_DIRTY_TIMESTAMP, ColumnType.INTEGER)
.addColumn(Collection.Columns.HAS_PARTS_DIRTY_TIMESTAMP, ColumnType.INTEGER)
.addColumn(Collection.Columns.COLLECTION_HERO_IMAGE_URL, ColumnType.TEXT)
.addColumn(Collection.Columns.PRIVATE_INFO_INVENTORY_LOCATION, ColumnType.TEXT)
.setConflictResolution(ConflictResolution.ABORT)
private fun buildBuddiesTable() = TableBuilder().setTable(Tables.BUDDIES).useDefaultPrimaryKey()
.addColumn(Buddies.Columns.UPDATED, ColumnType.INTEGER)
.addColumn(Buddies.Columns.UPDATED_LIST, ColumnType.INTEGER, true)
.addColumn(Buddies.Columns.BUDDY_ID, ColumnType.INTEGER, notNull = true, unique = true)
.addColumn(Buddies.Columns.BUDDY_NAME, ColumnType.TEXT, true)
.addColumn(Buddies.Columns.BUDDY_FIRSTNAME, ColumnType.TEXT)
.addColumn(Buddies.Columns.BUDDY_LASTNAME, ColumnType.TEXT)
.addColumn(Buddies.Columns.AVATAR_URL, ColumnType.TEXT)
.addColumn(Buddies.Columns.PLAY_NICKNAME, ColumnType.TEXT)
.addColumn(Buddies.Columns.BUDDY_FLAG, ColumnType.INTEGER)
.addColumn(Buddies.Columns.SYNC_HASH_CODE, ColumnType.INTEGER)
private fun buildPlayerColorsTable() = TableBuilder().setTable(Tables.PLAYER_COLORS)
.setConflictResolution(ConflictResolution.REPLACE)
.useDefaultPrimaryKey()
.addColumn(PlayerColors.Columns.PLAYER_TYPE, ColumnType.INTEGER, notNull = true, unique = true)
.addColumn(PlayerColors.Columns.PLAYER_NAME, ColumnType.TEXT, notNull = true, unique = true)
.addColumn(PlayerColors.Columns.PLAYER_COLOR, ColumnType.TEXT, notNull = true, unique = true)
.addColumn(PlayerColors.Columns.PLAYER_COLOR_SORT_ORDER, ColumnType.INTEGER, true)
private fun buildCollectionViewsTable() = TableBuilder()
.setTable(Tables.COLLECTION_VIEWS)
.useDefaultPrimaryKey()
.addColumn(CollectionViews.Columns.NAME, ColumnType.TEXT)
.addColumn(CollectionViews.Columns.STARRED, ColumnType.INTEGER)
.addColumn(CollectionViews.Columns.SORT_TYPE, ColumnType.INTEGER)
.addColumn(CollectionViews.Columns.SELECTED_COUNT, ColumnType.INTEGER)
.addColumn(CollectionViews.Columns.SELECTED_TIMESTAMP, ColumnType.INTEGER)
private fun buildCollectionViewFiltersTable() = TableBuilder()
.setTable(Tables.COLLECTION_VIEW_FILTERS)
.useDefaultPrimaryKey()
.addColumn(
CollectionViewFilters.Columns.VIEW_ID, ColumnType.INTEGER,
notNull = true,
unique = false,
referenceTable = Tables.COLLECTION_VIEWS,
referenceColumn = BaseColumns._ID,
onCascadeDelete = true
)
.addColumn(CollectionViewFilters.Columns.TYPE, ColumnType.INTEGER)
.addColumn(CollectionViewFilters.Columns.DATA, ColumnType.TEXT)
private fun recreateDatabase(db: SQLiteDatabase?) {
if (db == null) return
db.dropTable(Tables.DESIGNERS)
db.dropTable(Tables.ARTISTS)
db.dropTable(Tables.PUBLISHERS)
db.dropTable(Tables.MECHANICS)
db.dropTable(Tables.CATEGORIES)
db.dropTable(Tables.GAMES)
db.dropTable(Tables.GAME_RANKS)
db.dropTable(Tables.GAMES_DESIGNERS)
db.dropTable(Tables.GAMES_ARTISTS)
db.dropTable(Tables.GAMES_PUBLISHERS)
db.dropTable(Tables.GAMES_MECHANICS)
db.dropTable(Tables.GAMES_CATEGORIES)
db.dropTable(Tables.GAMES_EXPANSIONS)
db.dropTable(Tables.COLLECTION)
db.dropTable(Tables.BUDDIES)
db.dropTable(Tables.GAME_POLLS)
db.dropTable(Tables.GAME_POLL_RESULTS)
db.dropTable(Tables.GAME_POLL_RESULTS_RESULT)
db.dropTable(Tables.GAME_SUGGESTED_PLAYER_COUNT_POLL_RESULTS)
db.dropTable(Tables.GAME_COLORS)
db.dropTable(Tables.PLAYS)
db.dropTable(Tables.PLAY_PLAYERS)
db.dropTable(Tables.COLLECTION_VIEWS)
db.dropTable(Tables.COLLECTION_VIEW_FILTERS)
db.dropTable(Tables.PLAYER_COLORS)
onCreate(db)
}
private fun SQLiteDatabase.dropTable(tableName: String) = this.execSQL("DROP TABLE IF EXISTS $tableName")
private fun addColumn(db: SQLiteDatabase, table: String, column: String, type: ColumnType) {
try {
db.execSQL("ALTER TABLE $table ADD COLUMN $column $type")
} catch (e: SQLException) {
Timber.w(e, "Probably just trying to add an existing column.")
}
}
companion object {
private const val DATABASE_NAME = "bgg.db"
private const val VER_INITIAL = 1
private const val VER_WISHLIST_PRIORITY = 2
private const val VER_GAME_COLORS = 3
private const val VER_EXPANSIONS = 4
private const val VER_VARIOUS = 5
private const val VER_PLAYS = 6
private const val VER_PLAY_NICKNAME = 7
private const val VER_PLAY_SYNC_STATUS = 8
private const val VER_COLLECTION_VIEWS = 9
private const val VER_COLLECTION_VIEWS_SORT = 10
private const val VER_CASCADING_DELETE = 11
private const val VER_IMAGE_CACHE = 12
private const val VER_GAMES_UPDATED_PLAYS = 13
private const val VER_COLLECTION = 14
private const val VER_GAME_COLLECTION_CONFLICT = 15
private const val VER_PLAYS_START_TIME = 16
private const val VER_PLAYS_PLAYER_COUNT = 17
private const val VER_GAMES_SUBTYPE = 18
private const val VER_COLLECTION_ID_NULLABLE = 19
private const val VER_GAME_CUSTOM_PLAYER_SORT = 20
private const val VER_BUDDY_FLAG = 21
private const val VER_GAME_RANK = 22
private const val VER_BUDDY_SYNC_HASH_CODE = 23
private const val VER_PLAY_SYNC_HASH_CODE = 24
private const val VER_PLAYER_COLORS = 25
private const val VER_RATING_DIRTY_TIMESTAMP = 27
private const val VER_COMMENT_DIRTY_TIMESTAMP = 28
private const val VER_PRIVATE_INFO_DIRTY_TIMESTAMP = 29
private const val VER_STATUS_DIRTY_TIMESTAMP = 30
private const val VER_COLLECTION_DIRTY_TIMESTAMP = 31
private const val VER_COLLECTION_DELETE_TIMESTAMP = 32
private const val VER_COLLECTION_TIMESTAMPS = 33
private const val VER_PLAY_ITEMS_COLLAPSE = 34
private const val VER_PLAY_PLAYERS_KEY = 36
private const val VER_PLAY_DELETE_TIMESTAMP = 37
private const val VER_PLAY_UPDATE_TIMESTAMP = 38
private const val VER_PLAY_DIRTY_TIMESTAMP = 39
private const val VER_PLAY_PLAY_ID_NOT_REQUIRED = 40
private const val VER_PLAYS_RESET = 41
private const val VER_PLAYS_HARD_RESET = 42
private const val VER_COLLECTION_VIEWS_SELECTED_COUNT = 43
private const val VER_SUGGESTED_PLAYER_COUNT_POLL = 44
private const val VER_SUGGESTED_PLAYER_COUNT_RECOMMENDATION = 45
private const val VER_MIN_MAX_PLAYING_TIME = 46
private const val VER_SUGGESTED_PLAYER_COUNT_RE_SYNC = 47
private const val VER_GAME_HERO_IMAGE_URL = 48
private const val VER_COLLECTION_HERO_IMAGE_URL = 49
private const val VER_GAME_PALETTE_COLORS = 50
private const val VER_PRIVATE_INFO_INVENTORY_LOCATION = 51
private const val VER_ARTIST_IMAGES = 52
private const val VER_DESIGNER_IMAGES = 53
private const val VER_PUBLISHER_IMAGES = 54
private const val VER_WHITMORE_SCORE = 55
private const val VER_DAP_STATS_UPDATED_TIMESTAMP = 56
private const val VER_RECOMMENDED_PLAYER_COUNTS = 57
private const val DATABASE_VERSION = VER_RECOMMENDED_PLAYER_COUNTS
}
}
| gpl-3.0 | edf86d84efd8167989ca0edde5486e6f | 58.887047 | 384 | 0.648232 | 4.756069 | false | false | false | false |
Kotlin/kotlinx.serialization | core/commonMain/src/kotlinx/serialization/encoding/AbstractDecoder.kt | 1 | 3909 | /*
* Copyright 2017-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
*/
package kotlinx.serialization.encoding
import kotlinx.serialization.*
import kotlinx.serialization.descriptors.*
/**
* A skeleton implementation of both [Decoder] and [CompositeDecoder] that can be used
* for simple formats and for testability purpose.
* Most of the `decode*` methods have default implementation that delegates `decodeValue(value: Any) as TargetType`.
* See [Decoder] documentation for information about each particular `decode*` method.
*/
@ExperimentalSerializationApi
public abstract class AbstractDecoder : Decoder, CompositeDecoder {
/**
* Invoked to decode a value when specialized `decode*` method was not overridden.
*/
public open fun decodeValue(): Any = throw SerializationException("${this::class} can't retrieve untyped values")
override fun decodeNotNullMark(): Boolean = true
override fun decodeNull(): Nothing? = null
override fun decodeBoolean(): Boolean = decodeValue() as Boolean
override fun decodeByte(): Byte = decodeValue() as Byte
override fun decodeShort(): Short = decodeValue() as Short
override fun decodeInt(): Int = decodeValue() as Int
override fun decodeLong(): Long = decodeValue() as Long
override fun decodeFloat(): Float = decodeValue() as Float
override fun decodeDouble(): Double = decodeValue() as Double
override fun decodeChar(): Char = decodeValue() as Char
override fun decodeString(): String = decodeValue() as String
override fun decodeEnum(enumDescriptor: SerialDescriptor): Int = decodeValue() as Int
override fun decodeInline(descriptor: SerialDescriptor): Decoder = this
// overwrite by default
public open fun <T : Any?> decodeSerializableValue(
deserializer: DeserializationStrategy<T>,
previousValue: T? = null
): T = decodeSerializableValue(deserializer)
override fun beginStructure(descriptor: SerialDescriptor): CompositeDecoder = this
override fun endStructure(descriptor: SerialDescriptor) {
}
final override fun decodeBooleanElement(descriptor: SerialDescriptor, index: Int): Boolean = decodeBoolean()
final override fun decodeByteElement(descriptor: SerialDescriptor, index: Int): Byte = decodeByte()
final override fun decodeShortElement(descriptor: SerialDescriptor, index: Int): Short = decodeShort()
final override fun decodeIntElement(descriptor: SerialDescriptor, index: Int): Int = decodeInt()
final override fun decodeLongElement(descriptor: SerialDescriptor, index: Int): Long = decodeLong()
final override fun decodeFloatElement(descriptor: SerialDescriptor, index: Int): Float = decodeFloat()
final override fun decodeDoubleElement(descriptor: SerialDescriptor, index: Int): Double = decodeDouble()
final override fun decodeCharElement(descriptor: SerialDescriptor, index: Int): Char = decodeChar()
final override fun decodeStringElement(descriptor: SerialDescriptor, index: Int): String = decodeString()
override fun decodeInlineElement(
descriptor: SerialDescriptor,
index: Int
): Decoder = decodeInline(descriptor.getElementDescriptor(index))
override fun <T> decodeSerializableElement(
descriptor: SerialDescriptor,
index: Int,
deserializer: DeserializationStrategy<T>,
previousValue: T?
): T = decodeSerializableValue(deserializer, previousValue)
final override fun <T : Any> decodeNullableSerializableElement(
descriptor: SerialDescriptor,
index: Int,
deserializer: DeserializationStrategy<T?>,
previousValue: T?
): T? {
val isNullabilitySupported = deserializer.descriptor.isNullable
return if (isNullabilitySupported || decodeNotNullMark()) decodeSerializableValue(deserializer, previousValue) else decodeNull()
}
}
| apache-2.0 | ec0316325d708c2ec6fe21ea73385a7c | 47.259259 | 136 | 0.740854 | 5.49789 | false | false | false | false |
ursjoss/scipamato | public/public-web/src/main/kotlin/ch/difty/scipamato/publ/web/paper/browse/PublicPage.kt | 1 | 11199 | package ch.difty.scipamato.publ.web.paper.browse
import ch.difty.scipamato.common.entity.CodeClassId
import ch.difty.scipamato.common.web.LABEL_RESOURCE_TAG
import ch.difty.scipamato.common.web.LABEL_TAG
import ch.difty.scipamato.common.web.TITLE_RESOURCE_TAG
import ch.difty.scipamato.common.web.component.SerializableConsumer
import ch.difty.scipamato.common.web.component.table.column.ClickablePropertyColumn
import ch.difty.scipamato.publ.entity.Code
import ch.difty.scipamato.publ.entity.CodeClass
import ch.difty.scipamato.publ.entity.PublicPaper
import ch.difty.scipamato.publ.entity.filter.PublicPaperFilter
import ch.difty.scipamato.publ.web.common.BasePage
import ch.difty.scipamato.publ.web.model.CodeClassModel
import ch.difty.scipamato.publ.web.model.CodeModel
import com.giffing.wicket.spring.boot.context.scan.WicketHomePage
import de.agilecoders.wicket.core.markup.html.bootstrap.button.BootstrapButton
import de.agilecoders.wicket.core.markup.html.bootstrap.button.BootstrapExternalLink
import de.agilecoders.wicket.core.markup.html.bootstrap.button.Buttons
import de.agilecoders.wicket.core.markup.html.bootstrap.table.TableBehavior
import de.agilecoders.wicket.core.markup.html.bootstrap.tabs.BootstrapTabbedPanel
import de.agilecoders.wicket.extensions.markup.html.bootstrap.form.select.BootstrapMultiSelect
import de.agilecoders.wicket.extensions.markup.html.bootstrap.form.select.BootstrapSelectConfig
import de.agilecoders.wicket.extensions.markup.html.bootstrap.table.BootstrapDefaultDataTable
import org.apache.wicket.AttributeModifier
import org.apache.wicket.extensions.markup.html.repeater.data.table.IColumn
import org.apache.wicket.extensions.markup.html.repeater.data.table.PropertyColumn
import org.apache.wicket.extensions.markup.html.repeater.data.table.filter.FilterForm
import org.apache.wicket.extensions.markup.html.tabs.AbstractTab
import org.apache.wicket.extensions.markup.html.tabs.ITab
import org.apache.wicket.markup.html.basic.Label
import org.apache.wicket.markup.html.form.ChoiceRenderer
import org.apache.wicket.markup.html.form.Form
import org.apache.wicket.markup.html.panel.Panel
import org.apache.wicket.model.IModel
import org.apache.wicket.model.Model
import org.apache.wicket.model.PropertyModel
import org.apache.wicket.model.StringResourceModel
import org.apache.wicket.request.mapper.parameter.PageParameters
import org.wicketstuff.annotation.mount.MountPath
@WicketHomePage
@MountPath("/")
@Suppress("SameParameterValue", "UnnecessaryAbstractClass", "TooManyFunctions")
class PublicPage(parameters: PageParameters) : BasePage<Void>(parameters) {
private val filter: PublicPaperFilter = PublicPaperFilter()
private val dataProvider = PublicPaperProvider(filter, RESULT_PAGE_SIZE)
private var isQueryingInitialized = false
override fun onInitialize() {
super.onInitialize()
makeAndQueueFilterForm("searchForm")
makeAndQueueResultTable("results")
}
private fun makeAndQueueFilterForm(id: String) {
object : FilterForm<PublicPaperFilter>(id, dataProvider) {
override fun onSubmit() {
super.onSubmit()
updateNavigateable()
}
}.also {
queue(it)
addTabPanel(it, "tabs")
queueQueryButton("query", it)
}
queueClearSearchButton("clear")
queueHelpLink("help")
}
private fun addTabPanel(
filterForm: FilterForm<PublicPaperFilter>,
tabId: String,
) {
mutableListOf<ITab>().apply {
add(object : AbstractTab(StringResourceModel("tab1$LABEL_RESOURCE_TAG", this@PublicPage, null)) {
override fun getPanel(panelId: String): Panel = TabPanel1(panelId, Model.of(filter))
})
add(object : AbstractTab(StringResourceModel("tab2$LABEL_RESOURCE_TAG", this@PublicPage, null)) {
override fun getPanel(panelId: String): Panel = TabPanel2(panelId, Model.of(filter))
})
}.also {
filterForm.add(BootstrapTabbedPanel(tabId, it))
}
}
private inner class TabPanel1(
id: String,
model: IModel<PublicPaperFilter>,
) : AbstractTabPanel(id, model) {
override fun onInitialize() {
super.onInitialize()
queue(Form<Any>("tab1Form"))
queue(SimpleFilterPanel("simpleFilterPanel", Model.of(filter), languageCode))
}
}
private inner class TabPanel2(
id: String,
model: IModel<PublicPaperFilter>,
) : AbstractTabPanel(id, model) {
override fun onInitialize() {
super.onInitialize()
val form = Form<Any>("tab2Form")
queue(form)
queue(SimpleFilterPanel("simpleFilterPanel", Model.of(filter), languageCode))
CodeClassModel(languageCode).getObject().apply {
makeCodeClassComplex(form, CodeClassId.CC1, this)
makeCodeClassComplex(form, CodeClassId.CC2, this)
makeCodeClassComplex(form, CodeClassId.CC3, this)
makeCodeClassComplex(form, CodeClassId.CC4, this)
makeCodeClassComplex(form, CodeClassId.CC5, this)
makeCodeClassComplex(form, CodeClassId.CC6, this)
makeCodeClassComplex(form, CodeClassId.CC7, this)
makeCodeClassComplex(form, CodeClassId.CC8, this)
}
}
private fun makeCodeClassComplex(
form: Form<Any>,
codeClassId: CodeClassId,
codeClasses: List<CodeClass>,
) {
val id = codeClassId.id
val componentId = "$CODES_CLASS_BASE_NAME$id"
val className = codeClasses
.filter { it.codeClassId == id }
.map { it.name }
.firstOrNull() ?: codeClassId.name
val model = PropertyModel.of<List<Code>>(filter, componentId)
val choices = CodeModel(codeClassId, languageCode)
val choiceRenderer = ChoiceRenderer<Code>("displayValue", "code")
val config = BootstrapSelectConfig()
.withMultiple(true)
.withActionsBox(choices.getObject().size > properties.multiSelectBoxActionBoxWithMoreEntriesThan)
.withSelectAllText(StringResourceModel(SELECT_ALL_RESOURCE_TAG, this, null).string)
.withDeselectAllText(StringResourceModel(DESELECT_ALL_RESOURCE_TAG, this, null).string)
.withNoneSelectedText(StringResourceModel(CODES_NONE_SELECT_RESOURCE_TAG, this, null).string)
.withLiveSearch(true)
.withLiveSearchStyle("startsWith")
form.add(Label("$componentId$LABEL_TAG", Model.of(className)))
form.add(BootstrapMultiSelect(componentId, model, choices, choiceRenderer).with(config))
}
}
private abstract class AbstractTabPanel(id: String, model: IModel<*>?) : Panel(id, model) {
companion object {
private const val serialVersionUID = 1L
}
}
private fun queueQueryButton(
id: String,
filterForm: FilterForm<PublicPaperFilter>,
) {
val labelModel = StringResourceModel("$BUTTON_RESOURCE_PREFIX$id$LABEL_RESOURCE_TAG", this, null)
object : BootstrapButton(id, labelModel, Buttons.Type.Primary) {
override fun onSubmit() {
super.onSubmit()
isQueryingInitialized = true
}
}.also {
queue(it)
filterForm.defaultButton = it
}
}
private fun queueClearSearchButton(id: String) {
val labelModel = StringResourceModel("$BUTTON_RESOURCE_PREFIX$id$LABEL_RESOURCE_TAG", this, null)
val titleModel = StringResourceModel("$BUTTON_RESOURCE_PREFIX$id$TITLE_RESOURCE_TAG", this, null)
object : BootstrapButton(id, labelModel, Buttons.Type.Default) {
override fun onSubmit() {
super.onSubmit()
setResponsePage(PublicPage(pageParameters))
}
}.apply { add(AttributeModifier("title", titleModel)) }
.also { queue(it) }
}
private fun queueHelpLink(id: String) {
object : BootstrapExternalLink(id, StringResourceModel("$id.url", this, null)) {
}.apply {
setTarget(BootstrapExternalLink.Target.blank)
setLabel(StringResourceModel(id + LABEL_RESOURCE_TAG, this, null))
}.also {
queue(it)
}
}
private fun makeAndQueueResultTable(id: String) {
object : BootstrapDefaultDataTable<PublicPaper, String>(id, makeTableColumns(), dataProvider,
dataProvider.rowsPerPage.toLong()) {
override fun onConfigure() {
super.onConfigure()
isVisible = isQueryingInitialized
}
override fun onAfterRender() {
super.onAfterRender()
paperIdManager.initialize([email protected]())
}
}.apply {
outputMarkupId = true
add(TableBehavior().striped().hover())
}.also {
queue(it)
}
}
private fun makeTableColumns() = mutableListOf<IColumn<PublicPaper, String>>().apply {
add(makePropertyColumn("authorsAbbreviated", "authors"))
add(makeClickableColumn("title", this@PublicPage::onTitleClick))
add(makePropertyColumn("journal", "location"))
add(makePropertyColumn("publicationYear", "publicationYear"))
}
private fun makePropertyColumn(fieldType: String, sortField: String) = PropertyColumn<PublicPaper, String>(
StringResourceModel("$COLUMN_HEADER${fieldType}", this, null),
sortField,
fieldType,
)
private fun makeClickableColumn(
fieldType: String,
consumer: SerializableConsumer<IModel<PublicPaper>>,
) = ClickablePropertyColumn(
displayModel = StringResourceModel("$COLUMN_HEADER$fieldType", this, null),
property = fieldType,
action = consumer,
sort = fieldType,
inNewTab = true,
)
/*
* Note: The PaperIdManger manages the number in scipamato-public, not the id
*/
private fun onTitleClick(m: IModel<PublicPaper>) {
m.getObject().number?.let { paperIdManager.setFocusToItem(it) }
setResponsePage(PublicPaperDetailPage(m, page.pageReference, showBackButton = false))
}
/**
* Have the provider provide a list of all paper numbers (business key) matching the current filter.
* Construct a navigateable with this list and set it into the session
*/
private fun updateNavigateable() {
paperIdManager.initialize(dataProvider.findAllPaperNumbersByFilter())
}
companion object {
private const val serialVersionUID = 1L
private const val RESULT_PAGE_SIZE = 20
private const val COLUMN_HEADER = "column.header."
private const val CODES_CLASS_BASE_NAME = "codesOfClass"
private const val CODES_NONE_SELECT_RESOURCE_TAG = "codes.noneSelected"
private const val BUTTON_RESOURCE_PREFIX = "button."
}
}
| bsd-3-clause | a673f73b623b074e5b044a4ad9341064 | 41.744275 | 113 | 0.674167 | 4.650748 | false | false | false | false |
LISTEN-moe/android-app | app/src/main/kotlin/me/echeung/moemoekyun/client/RadioClient.kt | 1 | 1090 | package me.echeung.moemoekyun.client
import me.echeung.moemoekyun.client.api.Library
import me.echeung.moemoekyun.client.api.socket.Socket
import me.echeung.moemoekyun.client.stream.Stream
import me.echeung.moemoekyun.util.PreferenceUtil
class RadioClient(
private val preferenceUtil: PreferenceUtil,
private val stream: Stream,
private val socket: Socket,
) {
init {
setLibrary(preferenceUtil.libraryMode().get())
}
fun changeLibrary(newLibrary: Library) {
// Avoid unnecessary changes
if (preferenceUtil.libraryMode().get() == newLibrary) {
return
}
setLibrary(newLibrary)
socket.reconnect()
// Force it to play with new stream
if (stream.isPlaying) {
stream.play()
}
}
private fun setLibrary(newLibrary: Library) {
preferenceUtil.libraryMode().set(newLibrary)
library = newLibrary
}
companion object {
var library: Library = Library.JPOP
private set
fun isKpop() = library == Library.KPOP
}
}
| mit | 9ef38408593fe59462038061b7b46143 | 23.222222 | 63 | 0.648624 | 4.504132 | false | false | false | false |
Ruben-Sten/TeXiFy-IDEA | src/nl/hannahsten/texifyidea/lang/commands/LatexNatbibCommand.kt | 1 | 3333 | package nl.hannahsten.texifyidea.lang.commands
import nl.hannahsten.texifyidea.lang.LatexPackage
import nl.hannahsten.texifyidea.lang.LatexPackage.Companion.NATBIB
/**
* @author Hannah Schellekens
*/
enum class LatexNatbibCommand(
override val command: String,
override vararg val arguments: Argument = emptyArray(),
override val dependency: LatexPackage = LatexPackage.DEFAULT,
override val display: String? = null,
override val isMathMode: Boolean = false,
val collapse: Boolean = false
) : LatexCommand {
CITEP("citep", "before".asOptional(), "after".asOptional(), "keys".asRequired(), dependency = NATBIB),
CITEP_STAR("citep*", "before".asOptional(), "after".asOptional(), "keys".asRequired(), dependency = NATBIB),
CITET("citet", "before".asOptional(), "after".asOptional(), "keys".asRequired(), dependency = NATBIB),
CITET_STAR("citet*", "before".asOptional(), "after".asOptional(), "keys".asRequired(), dependency = NATBIB),
CITEP_CAPITALIZED("Citep", "before".asOptional(), "after".asOptional(), "keys".asRequired(), dependency = NATBIB),
CITEP_STAR_CAPITALIZED("Citep*", "before".asOptional(), "after".asOptional(), "keys".asRequired(), dependency = NATBIB),
CITET_CAPITALIZED("Citet", "before".asOptional(), "after".asOptional(), "keys".asRequired(), dependency = NATBIB),
CITET_STAR_CAPITALIZED("Citet*", "before".asOptional(), "after".asOptional(), "keys".asRequired(), dependency = NATBIB),
CITEALP("citealp", "before".asOptional(), "after".asOptional(), "keys".asRequired(), dependency = NATBIB),
CITEALP_STAR("citealp*", "before".asOptional(), "after".asOptional(), "keys".asRequired(), dependency = NATBIB),
CITEALT("citealt", "before".asOptional(), "after".asOptional(), "keys".asRequired(), dependency = NATBIB),
CITEALT_STAR("citealt*", "before".asOptional(), "after".asOptional(), "keys".asRequired(), dependency = NATBIB),
CITEALP_CAPITALIZED("Citealp", "before".asOptional(), "after".asOptional(), "keys".asRequired(), dependency = NATBIB),
CITEALP_STAR_CAPITALIZED("Citealp*", "before".asOptional(), "after".asOptional(), "keys".asRequired(), dependency = NATBIB),
CITEALT_CAPITALIZED("Citealt", "before".asOptional(), "after".asOptional(), "keys".asRequired(), dependency = NATBIB),
CITEALT_STAR_CAPITALIZED("Citealt*", "before".asOptional(), "after".asOptional(), "keys".asRequired(), dependency = NATBIB),
CITEAUTHOR("citeauthor", "keys".asRequired(), dependency = NATBIB),
CITEAUTHOR_STAR("citeauthor*", "keys".asRequired(), dependency = NATBIB),
CITEAUTHOR_CAPITALIZED("Citeauthor", "keys".asRequired(), dependency = NATBIB),
CITEAUTHOR_STAR_CAPITALIZED("Citeauthor*", "keys".asRequired(), dependency = NATBIB),
CITEYEAR("citeyear", "keys".asRequired(), dependency = NATBIB),
CITEYEAR_STAR("citeyear*", "keys".asRequired(), dependency = NATBIB),
CITEYEARPAR("citeyearpar", "keys".asRequired(), dependency = NATBIB),
CITETITLE("citetitle", "keys".asRequired(), dependency = NATBIB),
CITETITLE_STAR("citetitle*", "keys".asRequired(), dependency = NATBIB),
CITENUM("citenum", "key".asRequired(), dependency = NATBIB),
CITETEXT("citetext", "text".asRequired(), dependency = NATBIB),
;
override val identifier: String
get() = name
} | mit | 724fbd26a1daf3ac4e5e3feba118dd11 | 67.040816 | 128 | 0.689769 | 4.41457 | false | false | false | false |
mopsalarm/Pr0 | app/src/main/java/com/pr0gramm/app/ui/AdService.kt | 1 | 5886 | package com.pr0gramm.app.ui
import android.content.Context
import com.google.android.gms.ads.*
import com.google.android.gms.ads.initialization.OnInitializationCompleteListener
import com.google.android.gms.ads.interstitial.InterstitialAd
import com.google.android.gms.ads.interstitial.InterstitialAdLoadCallback
import com.pr0gramm.app.BuildConfig
import com.pr0gramm.app.Duration
import com.pr0gramm.app.Instant
import com.pr0gramm.app.Settings
import com.pr0gramm.app.model.config.Config
import com.pr0gramm.app.services.Track
import com.pr0gramm.app.services.UserService
import com.pr0gramm.app.services.config.ConfigService
import com.pr0gramm.app.util.AndroidUtility
import com.pr0gramm.app.util.Holder
import com.pr0gramm.app.util.ignoreAllExceptions
import kotlinx.coroutines.CompletableDeferred
import kotlinx.coroutines.channels.awaitClose
import kotlinx.coroutines.flow.*
import java.util.concurrent.TimeUnit
/**
* Utility methods for ads.
*/
class AdService(private val configService: ConfigService, private val userService: UserService) {
private var lastInterstitialAdShown: Instant? = null
/**
* Loads an ad into this view. This method also registers a listener to track the view.
* The resulting completable completes once the ad finishes loading.
*/
fun load(view: AdView?, type: Config.AdType): Flow<AdLoadState> {
if (view == null) {
return emptyFlow()
}
return channelFlow {
view.adListener = object : TrackingAdListener("b") {
override fun onAdLoaded() {
super.onAdLoaded()
if (!isClosedForSend) {
[email protected](AdLoadState.SUCCESS).isSuccess
}
}
override fun onAdFailedToLoad(p0: LoadAdError) {
super.onAdFailedToLoad(p0)
if (!isClosedForSend) {
[email protected](AdLoadState.FAILURE).isSuccess
}
}
override fun onAdClosed() {
super.onAdClosed()
if (!isClosedForSend) {
[email protected](AdLoadState.CLOSED).isSuccess
}
}
}
view.loadAd(AdRequest.Builder().build())
awaitClose()
}
}
fun enabledForTypeNow(type: Config.AdType): Boolean {
if (Settings.alwaysShowAds) {
// If the user opted in to ads, we always show the feed ad.
return type == Config.AdType.FEED
}
if (userService.userIsPremium) {
return false
}
if (userService.isAuthorized) {
return type in configService.config().adTypesLoggedIn
} else {
return type in configService.config().adTypesLoggedOut
}
}
fun enabledForType(type: Config.AdType): Flow<Boolean> {
return userService.loginStates
.map { enabledForTypeNow(type) }
.distinctUntilChanged()
}
fun shouldShowInterstitialAd(): Boolean {
if (!enabledForTypeNow(Config.AdType.FEED_TO_POST_INTERSTITIAL)) {
return false
}
val lastAdShown = lastInterstitialAdShown ?: return true
val interval = configService.config().interstitialAdIntervalInSeconds
return Duration.since(lastAdShown).convertTo(TimeUnit.SECONDS) > interval
}
fun interstitialAdWasShown() {
this.lastInterstitialAdShown = Instant.now()
}
fun newAdView(context: Context): AdView {
val view = AdView(context)
view.adUnitId = bannerUnitId
val backgroundColor = AndroidUtility.resolveColorAttribute(context, android.R.attr.windowBackground)
view.setBackgroundColor(backgroundColor)
return view
}
fun buildInterstitialAd(context: Context): Holder<InterstitialAd?> {
return if (enabledForTypeNow(Config.AdType.FEED_TO_POST_INTERSTITIAL)) {
val value = CompletableDeferred<InterstitialAd?>()
InterstitialAd.load(context, interstitialUnitId, AdRequest.Builder().build(), object : InterstitialAdLoadCallback() {
override fun onAdLoaded(p0: InterstitialAd) {
value.complete(p0)
}
override fun onAdFailedToLoad(p0: LoadAdError) {
value.complete(null)
}
})
Holder { value.await() }
} else {
return Holder { null }
}
}
companion object {
private val interstitialUnitId: String = if (BuildConfig.DEBUG) {
"ca-app-pub-3940256099942544/1033173712"
} else {
"ca-app-pub-2308657767126505/4231980510"
}
private val bannerUnitId: String = if (BuildConfig.DEBUG) {
"ca-app-pub-3940256099942544/6300978111"
} else {
"ca-app-pub-2308657767126505/5614778874"
}
fun initializeMobileAds(context: Context) {
// for some reason an internal getVersionString returns null,
// and the result is not checked. We ignore the error in that case
ignoreAllExceptions {
val listener = OnInitializationCompleteListener { }
MobileAds.initialize(context, listener)
MobileAds.setAppVolume(0f)
MobileAds.setAppMuted(true)
}
}
}
enum class AdLoadState {
SUCCESS, FAILURE, CLOSED
}
open class TrackingAdListener(private val prefix: String) : AdListener() {
override fun onAdImpression() {
Track.adEvent("${prefix}_impression")
}
override fun onAdOpened() {
Track.adEvent("${prefix}_opened")
}
}
}
| mit | 8eb770fda16824bc2fd7a47df309dbc4 | 32.067416 | 129 | 0.619436 | 4.769854 | false | true | false | false |
Flank/fladle | buildSrc/src/test/java/com/osacky/flank/gradle/integration/AndroidTestUtil.kt | 1 | 1380 | package com.osacky.flank.gradle.integration
/*
* Copyright (C) 2016 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.
*/
import java.io.File
import java.util.Properties
internal fun androidHome(): String {
val env = System.getenv("ANDROID_HOME")
if (env != null) {
return env.withInvariantPathSeparators()
}
val localProp = File(File(System.getProperty("user.dir")).parentFile, "local.properties")
if (localProp.exists()) {
val prop = Properties()
localProp.inputStream().use {
prop.load(it)
}
val sdkHome = prop.getProperty("sdk.dir")
if (sdkHome != null) {
return sdkHome.withInvariantPathSeparators()
}
}
throw IllegalStateException(
"Missing 'ANDROID_HOME' environment variable or local.properties with 'sdk.dir'"
)
}
internal fun String.withInvariantPathSeparators() = replace("\\", "/")
| apache-2.0 | fd66101f267d7aa69e819cef1bbdedbe | 31.857143 | 91 | 0.710145 | 4.046921 | false | false | false | false |
lancastersoftware/bef-main | src/interface/main/kotlin/lss/bef/core/Log.kt | 1 | 4413 | /* Copyright (c) 2017 Lancaster Software & Service
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following
* conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*/
/* ------------------------------------------------------------------------ */
package lss.bef.core
import java.io.PrintStream;
class LogDefines {
companion object {
// LOG LEVELS
const val ALL : Int = Int.MIN_VALUE; //Level.ALL.intValue();
const val EXCEPTION : Int = 1100; //Level.SEVERE.intValue() + 100;
const val ERROR : Int = 1000; //Level.SEVERE.intValue();
const val WARNING : Int = 900; //Level.WARNING.intValue();
const val INFO : Int = 800; //Level.INFO.intValue();
const val CONFIG : Int = 700; //Level.CONFIG.intValue();
const val DEBUG : Int = 500; //Level.FINE.intValue();
const val PERFORMANCE : Int = 400; //Level.FINER.intValue();
const val VERBOSE : Int = 300; //Level.FINEST.intValue();
const val OFF : Int = Integer.MAX_VALUE; //Level.OFF.intValue();
}
}
interface Log {
fun attachFileHandler( filenamePattern : String, maxFileSize : Int, numberOfRotatingFiles : Int, append : Boolean ) : Boolean
fun attachFileHandlerFor( loggerName : String, filename : String ) : Boolean
fun detachFileHandlerFor( loggerName : String ) : Boolean
fun getCurrentGlobalLogLevel() : Int
fun setCurrentGlobalLogLevel( level : Int ) : Unit
fun getOriginalStderr() : PrintStream
fun getOriginalStdout() : PrintStream
fun logEnableLevel( level : Int ) : Unit
fun logEnableTargetDisplay( flag : Boolean ) : Unit
fun logIsLevelEnabled( level : Int ) : Boolean;
fun log( level : Int, msg : String ) : Unit
fun log( level : Int, format : String, vararg vars : Object ) : Unit
fun log( level : Int, resourceId : Long, vararg vars : Object ) : Unit
fun redirectStderrToLog() : Unit
fun redirectStdoutToLog() : Unit
fun resetStderrToOriginal() : Unit
fun resetStdoutToOriginal() : Unit
// CONVENIENCE METHODS
fun logException( msg : String ) : Unit;
fun logException( format : String, vararg vars : Object ) : Unit
fun logException( resourceId : Long, vararg vars : Object ) : Unit
fun logError( msg : String ) : Unit
fun logError( format : String, vararg vars : Object ) : Unit
fun logError( resourceId : Long, vararg vars : Object ) : Unit
fun logWarning( msg : String ) : Unit
fun logWarning( format : String, vararg vars : Object ) : Unit
fun logWarning( resourceId : Long, vararg vars : Object ) : Unit
fun logInfo( msg : String ) : Unit
fun logInfo( format : String, vararg vars : Object ) : Unit
fun logInfo( resourceId : Long, vararg vars : Object ) : Unit
fun logDebug( msg : String ) : Unit
fun logDebug( format : String, vararg vars : Object ) : Unit
fun logDebug( resourceId : Long, vararg vars : Object ) : Unit
fun logPerformance( msg : String ) : Long
fun logPerformance( format : String, vararg vars : Object ) : Long
fun logPerformance( resourceId : Long, vararg vars : Object ) : Long
fun logPerformance( startTime : Long, msg : String ) : Unit
fun logPerformance( startTime : Long, format : String, vararg vars : Object ) : Unit
fun logPerformance( startTime : Long, resourceId : Long, vararg vars : Object ) : Unit
}
| apache-2.0 | 4fa54c365c7a2aaa1fefb1b0e089eeca | 41.84466 | 129 | 0.661908 | 4.313783 | false | false | false | false |
ansman/okhttp | okhttp/src/main/kotlin/okhttp3/internal/hostnames.kt | 3 | 7924 | /*
* Copyright (C) 2012 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 okhttp3.internal
import java.net.IDN
import java.net.InetAddress
import java.util.Arrays
import java.util.Locale
import okio.Buffer
/**
* If this is an IP address, this returns the IP address in canonical form.
*
* Otherwise this performs IDN ToASCII encoding and canonicalize the result to lowercase. For
* example this converts `☃.net` to `xn--n3h.net`, and `WwW.GoOgLe.cOm` to `www.google.com`.
* `null` will be returned if the host cannot be ToASCII encoded or if the result contains
* unsupported ASCII characters.
*/
fun String.toCanonicalHost(): String? {
val host: String = this
// If the input contains a :, it’s an IPv6 address.
if (":" in host) {
// If the input is encased in square braces "[...]", drop 'em.
val inetAddress = (if (host.startsWith("[") && host.endsWith("]")) {
decodeIpv6(host, 1, host.length - 1)
} else {
decodeIpv6(host, 0, host.length)
}) ?: return null
val address = inetAddress.address
if (address.size == 16) return inet6AddressToAscii(address)
if (address.size == 4) return inetAddress.hostAddress // An IPv4-mapped IPv6 address.
throw AssertionError("Invalid IPv6 address: '$host'")
}
try {
val result = IDN.toASCII(host).toLowerCase(Locale.US)
if (result.isEmpty()) return null
// Confirm that the IDN ToASCII result doesn't contain any illegal characters.
return if (result.containsInvalidHostnameAsciiCodes()) {
null
} else {
result // TODO: implement all label limits.
}
} catch (_: IllegalArgumentException) {
return null
}
}
private fun String.containsInvalidHostnameAsciiCodes(): Boolean {
for (i in 0 until length) {
val c = this[i]
// The WHATWG Host parsing rules accepts some character codes which are invalid by
// definition for OkHttp's host header checks (and the WHATWG Host syntax definition). Here
// we rule out characters that would cause problems in host headers.
if (c <= '\u001f' || c >= '\u007f') {
return true
}
// Check for the characters mentioned in the WHATWG Host parsing spec:
// U+0000, U+0009, U+000A, U+000D, U+0020, "#", "%", "/", ":", "?", "@", "[", "\", and "]"
// (excluding the characters covered above).
if (" #%/:?@[\\]".indexOf(c) != -1) {
return true
}
}
return false
}
/** Decodes an IPv6 address like 1111:2222:3333:4444:5555:6666:7777:8888 or ::1. */
private fun decodeIpv6(input: String, pos: Int, limit: Int): InetAddress? {
val address = ByteArray(16)
var b = 0
var compress = -1
var groupOffset = -1
var i = pos
while (i < limit) {
if (b == address.size) return null // Too many groups.
// Read a delimiter.
if (i + 2 <= limit && input.startsWith("::", startIndex = i)) {
// Compression "::" delimiter, which is anywhere in the input, including its prefix.
if (compress != -1) return null // Multiple "::" delimiters.
i += 2
b += 2
compress = b
if (i == limit) break
} else if (b != 0) {
// Group separator ":" delimiter.
if (input.startsWith(":", startIndex = i)) {
i++
} else if (input.startsWith(".", startIndex = i)) {
// If we see a '.', rewind to the beginning of the previous group and parse as IPv4.
if (!decodeIpv4Suffix(input, groupOffset, limit, address, b - 2)) return null
b += 2 // We rewound two bytes and then added four.
break
} else {
return null // Wrong delimiter.
}
}
// Read a group, one to four hex digits.
var value = 0
groupOffset = i
while (i < limit) {
val hexDigit = input[i].parseHexDigit()
if (hexDigit == -1) break
value = (value shl 4) + hexDigit
i++
}
val groupLength = i - groupOffset
if (groupLength == 0 || groupLength > 4) return null // Group is the wrong size.
// We've successfully read a group. Assign its value to our byte array.
address[b++] = (value.ushr(8) and 0xff).toByte()
address[b++] = (value and 0xff).toByte()
}
// All done. If compression happened, we need to move bytes to the right place in the
// address. Here's a sample:
//
// input: "1111:2222:3333::7777:8888"
// before: { 11, 11, 22, 22, 33, 33, 00, 00, 77, 77, 88, 88, 00, 00, 00, 00 }
// compress: 6
// b: 10
// after: { 11, 11, 22, 22, 33, 33, 00, 00, 00, 00, 00, 00, 77, 77, 88, 88 }
//
if (b != address.size) {
if (compress == -1) return null // Address didn't have compression or enough groups.
System.arraycopy(address, compress, address, address.size - (b - compress), b - compress)
Arrays.fill(address, compress, compress + (address.size - b), 0.toByte())
}
return InetAddress.getByAddress(address)
}
/** Decodes an IPv4 address suffix of an IPv6 address, like 1111::5555:6666:192.168.0.1. */
private fun decodeIpv4Suffix(
input: String,
pos: Int,
limit: Int,
address: ByteArray,
addressOffset: Int
): Boolean {
var b = addressOffset
var i = pos
while (i < limit) {
if (b == address.size) return false // Too many groups.
// Read a delimiter.
if (b != addressOffset) {
if (input[i] != '.') return false // Wrong delimiter.
i++
}
// Read 1 or more decimal digits for a value in 0..255.
var value = 0
val groupOffset = i
while (i < limit) {
val c = input[i]
if (c < '0' || c > '9') break
if (value == 0 && groupOffset != i) return false // Reject unnecessary leading '0's.
value = value * 10 + c.toInt() - '0'.toInt()
if (value > 255) return false // Value out of range.
i++
}
val groupLength = i - groupOffset
if (groupLength == 0) return false // No digits.
// We've successfully read a byte.
address[b++] = value.toByte()
}
// Check for too few groups. We wanted exactly four.
return b == addressOffset + 4
}
/** Encodes an IPv6 address in canonical form according to RFC 5952. */
private fun inet6AddressToAscii(address: ByteArray): String {
// Go through the address looking for the longest run of 0s. Each group is 2-bytes.
// A run must be longer than one group (section 4.2.2).
// If there are multiple equal runs, the first one must be used (section 4.2.3).
var longestRunOffset = -1
var longestRunLength = 0
run {
var i = 0
while (i < address.size) {
val currentRunOffset = i
while (i < 16 && address[i].toInt() == 0 && address[i + 1].toInt() == 0) {
i += 2
}
val currentRunLength = i - currentRunOffset
if (currentRunLength > longestRunLength && currentRunLength >= 4) {
longestRunOffset = currentRunOffset
longestRunLength = currentRunLength
}
i += 2
}
}
// Emit each 2-byte group in hex, separated by ':'. The longest run of zeroes is "::".
val result = Buffer()
var i = 0
while (i < address.size) {
if (i == longestRunOffset) {
result.writeByte(':'.toInt())
i += longestRunLength
if (i == 16) result.writeByte(':'.toInt())
} else {
if (i > 0) result.writeByte(':'.toInt())
val group = address[i] and 0xff shl 8 or (address[i + 1] and 0xff)
result.writeHexadecimalUnsignedLong(group.toLong())
i += 2
}
}
return result.readUtf8()
}
| apache-2.0 | dbd1cb85e819e1f322a1d5b3ebe0eba9 | 33.137931 | 95 | 0.623864 | 3.755334 | false | false | false | false |
DSolyom/ViolinDS | ViolinDS/app/src/main/java/ds/violin/v1/app/ViolinRecyclerViewFragment.kt | 1 | 2178 | /*
Copyright 2016 Dániel Sólyom
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 ds.violin.v1.app
import android.os.Bundle
import android.os.Parcelable
import android.view.View
import ds.violin.v1.app.violin.*
import ds.violin.v1.model.entity.SelfLoadable
import ds.violin.v1.widget.IRecyclerView
import java.util.*
abstract class ViolinRecyclerViewFragment : ViolinFragment(), RecyclerViewViolin {
override lateinit var recyclerView: IRecyclerView
override val emptyViewID: Int? = null
override var emptyView: View? = null
override var layoutManagerState: Parcelable? = null
override var adapter: AbsRecyclerViewAdapter? = null
override var adapterViewBinder: RecyclerViewAdapterBinder? = null
override val parentCanHoldHeader: Boolean = true
override val parentCanHoldFooter: Boolean = true
override fun onViewCreated(view: View?, savedInstanceState: Bundle?) {
super<RecyclerViewViolin>.onViewCreated(view, savedInstanceState)
super<ViolinFragment>.onViewCreated(view, savedInstanceState)
}
override fun play() {
/** create your [adapter] and [adapterViewBinder] before calling super */
super<RecyclerViewViolin>.play()
super<ViolinFragment>.play()
}
override fun saveInstanceState(outState: Bundle) {
super<ViolinFragment>.saveInstanceState(outState)
super<RecyclerViewViolin>.saveInstanceState(outState)
}
override fun restoreInstanceState(savedInstanceState: Bundle) {
super<ViolinFragment>.restoreInstanceState(savedInstanceState)
super<RecyclerViewViolin>.restoreInstanceState(savedInstanceState)
}
} | apache-2.0 | 76e6b34a9a123da61f4c7cc7da8e85ed | 35.283333 | 82 | 0.750919 | 4.835556 | false | false | false | false |
michaelgallacher/intellij-community | platform/configuration-store-impl/src/DirectoryBasedStorage.kt | 1 | 8961 | /*
* Copyright 2000-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.configurationStore
import com.intellij.openapi.application.runWriteAction
import com.intellij.openapi.components.StateSplitter
import com.intellij.openapi.components.StateSplitterEx
import com.intellij.openapi.components.StateStorage
import com.intellij.openapi.components.TrackingPathMacroSubstitutor
import com.intellij.openapi.components.impl.stores.DirectoryStorageUtil
import com.intellij.openapi.components.impl.stores.FileStorageCoreUtil
import com.intellij.openapi.util.Pair
import com.intellij.openapi.vfs.LocalFileSystem
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.util.LineSeparator
import com.intellij.util.SmartList
import com.intellij.util.SystemProperties
import com.intellij.util.containers.SmartHashSet
import com.intellij.util.io.systemIndependentPath
import com.intellij.util.isEmpty
import gnu.trove.THashMap
import org.jdom.Element
import java.io.IOException
import java.nio.ByteBuffer
import java.nio.file.Path
abstract class DirectoryBasedStorageBase(@Suppress("DEPRECATION") protected val splitter: StateSplitter,
protected val pathMacroSubstitutor: TrackingPathMacroSubstitutor? = null) : StateStorageBase<StateMap>() {
protected var componentName: String? = null
protected abstract val virtualFile: VirtualFile?
override fun loadData() = StateMap.fromMap(DirectoryStorageUtil.loadFrom(virtualFile, pathMacroSubstitutor))
override fun startExternalization(): StateStorage.ExternalizationSession? = null
override fun analyzeExternalChangesAndUpdateIfNeed(componentNames: MutableSet<String>) {
// todo reload only changed file, compute diff
val newData = loadData()
storageDataRef.set(newData)
if (componentName != null) {
componentNames.add(componentName!!)
}
}
override fun getSerializedState(storageData: StateMap, component: Any?, componentName: String, archive: Boolean): Element? {
this.componentName = componentName
if (storageData.isEmpty()) {
return null
}
val state = Element(FileStorageCoreUtil.COMPONENT)
if (splitter is StateSplitterEx) {
for (fileName in storageData.keys()) {
val subState = storageData.getState(fileName, archive) ?: return null
splitter.mergeStateInto(state, subState)
}
}
else {
val subElements = SmartList<Element>()
for (fileName in storageData.keys()) {
val subState = storageData.getState(fileName, archive) ?: return null
subElements.add(subState)
}
if (!subElements.isEmpty()) {
splitter.mergeStatesInto(state, subElements.toTypedArray())
}
}
return state
}
override fun hasState(storageData: StateMap, componentName: String) = storageData.hasStates()
}
open class DirectoryBasedStorage(private val dir: Path,
@Suppress("DEPRECATION") splitter: StateSplitter,
pathMacroSubstitutor: TrackingPathMacroSubstitutor? = null) : DirectoryBasedStorageBase(splitter, pathMacroSubstitutor) {
private @Volatile var cachedVirtualFile: VirtualFile? = null
override val virtualFile: VirtualFile?
get() {
var result = cachedVirtualFile
if (result == null) {
result = LocalFileSystem.getInstance().findFileByPath(dir.systemIndependentPath)
cachedVirtualFile = result
}
return result
}
internal fun setVirtualDir(dir: VirtualFile?) {
cachedVirtualFile = dir
}
override fun startExternalization(): StateStorage.ExternalizationSession? = if (checkIsSavingDisabled()) null else MySaveSession(this, getStorageData())
private class MySaveSession(private val storage: DirectoryBasedStorage, private val originalStates: StateMap) : SaveSessionBase() {
private var copiedStorageData: MutableMap<String, Any>? = null
private val dirtyFileNames = SmartHashSet<String>()
private var someFileRemoved = false
override fun setSerializedState(componentName: String, element: Element?) {
storage.componentName = componentName
if (element.isEmpty()) {
if (copiedStorageData != null) {
copiedStorageData!!.clear()
}
else if (!originalStates.isEmpty()) {
copiedStorageData = THashMap<String, Any>()
}
}
else {
val stateAndFileNameList = storage.splitter.splitState(element!!)
for (pair in stateAndFileNameList) {
doSetState(pair.second, pair.first)
}
outerLoop@
for (key in originalStates.keys()) {
for (pair in stateAndFileNameList) {
if (pair.second == key) {
continue@outerLoop
}
}
if (copiedStorageData == null) {
copiedStorageData = originalStates.toMutableMap()
}
someFileRemoved = true
copiedStorageData!!.remove(key)
}
}
}
private fun doSetState(fileName: String, subState: Element) {
if (copiedStorageData == null) {
copiedStorageData = setStateAndCloneIfNeed(fileName, subState, originalStates)
if (copiedStorageData != null) {
dirtyFileNames.add(fileName)
}
}
else if (updateState(copiedStorageData!!, fileName, subState)) {
dirtyFileNames.add(fileName)
}
}
override fun createSaveSession() = if (storage.checkIsSavingDisabled() || copiedStorageData == null) null else this
override fun save() {
val stateMap = StateMap.fromMap(copiedStorageData!!)
var dir = storage.virtualFile
if (copiedStorageData!!.isEmpty()) {
if (dir != null && dir.exists()) {
deleteFile(this, dir)
}
storage.setStorageData(stateMap)
return
}
if (dir == null || !dir.isValid) {
dir = createDir(storage.dir, this)
storage.cachedVirtualFile = dir
}
if (!dirtyFileNames.isEmpty) {
saveStates(dir, stateMap)
}
if (someFileRemoved && dir.exists()) {
deleteFiles(dir)
}
storage.setStorageData(stateMap)
}
private fun saveStates(dir: VirtualFile, states: StateMap) {
val storeElement = Element(FileStorageCoreUtil.COMPONENT)
for (fileName in states.keys()) {
if (!dirtyFileNames.contains(fileName)) {
continue
}
var element: Element? = null
try {
element = states.getElement(fileName) ?: continue
storage.pathMacroSubstitutor?.collapsePaths(element)
storeElement.setAttribute(FileStorageCoreUtil.NAME, storage.componentName!!)
storeElement.addContent(element)
val file = getFile(fileName, dir, this)
// we don't write xml prolog due to historical reasons (and should not in any case)
writeFile(null, this, file, storeElement, LineSeparator.fromString(if (file.exists()) loadFile(file).second else SystemProperties.getLineSeparator()), false)
}
catch (e: IOException) {
LOG.error(e)
}
finally {
if (element != null) {
element.detach()
}
}
}
}
private fun deleteFiles(dir: VirtualFile) {
runWriteAction {
for (file in dir.children) {
val fileName = file.name
if (fileName.endsWith(FileStorageCoreUtil.DEFAULT_EXT) && !copiedStorageData!!.containsKey(fileName)) {
if (file.isWritable) {
file.delete(this)
}
else {
throw ReadOnlyModificationException(file, null)
}
}
}
}
}
}
private fun setStorageData(newStates: StateMap) {
storageDataRef.set(newStates)
}
}
private val NON_EXISTENT_FILE_DATA = Pair.create<ByteArray, String>(null, SystemProperties.getLineSeparator())
/**
* @return pair.first - file contents (null if file does not exist), pair.second - file line separators
*/
private fun loadFile(file: VirtualFile?): Pair<ByteArray, String> {
if (file == null || !file.exists()) {
return NON_EXISTENT_FILE_DATA
}
val bytes = file.contentsToByteArray()
val lineSeparator = file.detectedLineSeparator ?: detectLineSeparators(Charsets.UTF_8.decode(ByteBuffer.wrap(bytes)), null).separatorString
return Pair.create<ByteArray, String>(bytes, lineSeparator)
} | apache-2.0 | 7bced0316a827e3b5e50b6a19af82bf2 | 33.871595 | 167 | 0.67883 | 4.997769 | false | false | false | false |
SpectraLogic/ds3_autogen | ds3-autogen-go/src/main/kotlin/com/spectralogic/ds3autogen/go/generators/parser/BaseTypeParserGenerator.kt | 2 | 9287 | /*
* ******************************************************************************
* Copyright 2014-2017 Spectra Logic Corporation. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use
* this file except in compliance with the License. A copy of the License is located at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* or in the "license" file accompanying this file.
* This file 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.spectralogic.ds3autogen.go.generators.parser
import com.google.common.collect.ImmutableList
import com.google.common.collect.ImmutableMap
import com.spectralogic.ds3autogen.api.models.apispec.Ds3Element
import com.spectralogic.ds3autogen.api.models.apispec.Ds3Type
import com.spectralogic.ds3autogen.go.models.parser.*
import com.spectralogic.ds3autogen.go.utils.toGoResponseType
import com.spectralogic.ds3autogen.go.utils.toGoType
import com.spectralogic.ds3autogen.utils.ConverterUtil
import com.spectralogic.ds3autogen.utils.Ds3ElementUtil
import com.spectralogic.ds3autogen.utils.NormalizingContractNamesUtil
import com.spectralogic.ds3autogen.utils.collections.GuavaCollectors
open class BaseTypeParserGenerator : TypeParserModelGenerator<TypeParser>, TypeParserGeneratorUtil {
override fun generate(ds3Type: Ds3Type, typeMap: ImmutableMap<String, Ds3Type>): TypeParser {
val modelName = NormalizingContractNamesUtil.removePath(ds3Type.name)
val name = modelName + "Parser"
val attributes = toAttributeList(ds3Type.elements, modelName)
val childNodes = toChildNodeList(ds3Type.elements, modelName, typeMap)
return TypeParser(name, modelName, attributes, childNodes)
}
/**
* Converts all non-attribute elements within a Ds3Element list into ParsingElements, which
* contain the Go code for parsing the Ds3Elements as child nodes.
*/
override fun toChildNodeList(
ds3Elements: ImmutableList<Ds3Element>?,
typeName: String,
typeMap: ImmutableMap<String, Ds3Type>): ImmutableList<ParseElement> {
if (ConverterUtil.isEmpty(ds3Elements)) {
return ImmutableList.of()
}
return ds3Elements!!.stream()
.filter { ds3Element -> !Ds3ElementUtil.isAttribute(ds3Element.ds3Annotations) }
.map { ds3Element -> toChildNode(ds3Element, typeName, typeMap) }
.collect(GuavaCollectors.immutableList())
}
/**
* Converts a Ds3Element into a ParsingElements.There are no special-cased Ds3Elements within
* the BaseTypeParserGenerator.
*/
override fun toChildNode(ds3Element: Ds3Element, typeName: String, typeMap: ImmutableMap<String, Ds3Type>): ParseElement {
return toStandardChildNode(ds3Element, typeName, typeMap)
}
/**
* Converts a Ds3Element into a ParsingElement, which contains the Go code for parsing the
* specified Ds3Element as a child node. This assumes that the specified Ds3Element is not an attribute.
*/
fun toStandardChildNode(ds3Element: Ds3Element, typeName: String, typeMap: ImmutableMap<String, Ds3Type>): ParseElement {
val xmlTag = getXmlTagName(ds3Element)
val modelName = typeName.decapitalize()
val paramName = ds3Element.name.capitalize()
// Handle case if there is an encapsulating tag around a list of elements
if (Ds3ElementUtil.hasWrapperAnnotations(ds3Element.ds3Annotations)) {
val encapsulatingTag = Ds3ElementUtil.getEncapsulatingTagAnnotations(ds3Element.ds3Annotations).capitalize()
val childType = NormalizingContractNamesUtil.removePath(ds3Element.componentType)
// Handle if the slice is common prefixes
if (encapsulatingTag == "CommonPrefixes") {
return ParseChildNodeAsCommonPrefix(modelName, paramName)
}
return ParseChildNodeAsSlice(encapsulatingTag, xmlTag, modelName, paramName, childType)
}
// Handle case if there is a slice to be parsed (no encapsulating tag)
if (ds3Element.type.equals("array")) {
val childType = toGoType(ds3Element.componentType!!)
// Handle if the slice is a string
if (childType == "string") {
return ParseChildNodeAddStringToSlice(xmlTag, modelName, paramName)
}
// Handle if the slice is a Ds3Type defined enum
if (isElementEnum(ds3Element.componentType!!, typeMap)) {
return ParseChildNodeAddEnumToSlice(xmlTag, modelName, paramName, childType)
}
return ParseChildNodeAddToSlice(xmlTag, modelName, paramName, childType)
}
// Handle case if the element is an enum
if (isElementEnum(ds3Element.type!!, typeMap)) {
if (ds3Element.nullable) {
return ParseChildNodeAsNullableEnum(xmlTag, modelName, paramName, toGoType(ds3Element.type!!))
}
return ParseChildNodeAsEnum(xmlTag, modelName, paramName)
}
val goType = toGoResponseType(ds3Element.type, ds3Element.componentType, ds3Element.nullable)
val parserNamespace = getPrimitiveTypeParserNamespace(ds3Element.type!!, ds3Element.nullable)
when (goType) {
"bool", "*bool", "int", "*int", "int64", "*int64", "float64", "*float64" ->
return ParseChildNodeAsPrimitiveType(xmlTag, modelName, paramName, parserNamespace)
"string", "*string" ->
return ParseChildNodeAsString(xmlTag, modelName, paramName, parserNamespace)
else -> {
// All remaining elements represent Ds3Types
if (goType.first() == '*') {
return ParseChildNodeAsNullableDs3Type(xmlTag, modelName, paramName, goType.drop(1))
}
return ParseChildNodeAsDs3Type(xmlTag, modelName, paramName)
}
}
}
/**
* Determines if the specified type is an enum.
*/
fun isElementEnum(elementType: String, typeMap: ImmutableMap<String, Ds3Type>): Boolean {
if (ConverterUtil.isEmpty(typeMap)) {
return false
}
val ds3Type = typeMap[elementType] ?: return false
return ConverterUtil.isEnum(ds3Type)
}
/**
* Converts all attributes within a Ds3Element list into ParsingElements which contain the
* Go code for parsing the attributes.
*/
fun toAttributeList(ds3Elements: ImmutableList<Ds3Element>?, typeName: String): ImmutableList<ParseElement> {
if (ConverterUtil.isEmpty(ds3Elements)) {
return ImmutableList.of()
}
return ds3Elements!!.stream()
.filter { ds3Element -> Ds3ElementUtil.isAttribute(ds3Element.ds3Annotations) }
.map { ds3Element -> toAttribute(ds3Element, typeName) }
.collect(GuavaCollectors.immutableList())
}
/**
* Converts a Ds3Element into a ParsingElement, which contains the Go code for parsing the
* specified Ds3Element attribute. This assumes that the specified Ds3Element is an attribute.
*/
fun toAttribute(ds3Element: Ds3Element, typeName: String): ParseElement {
val xmlName = getXmlTagName(ds3Element)
val goType = toGoResponseType(ds3Element.type, ds3Element.componentType, ds3Element.nullable)
val modelName = typeName.decapitalize()
val paramName = ds3Element.name.capitalize()
when (goType) {
"bool", "*bool", "int", "*int", "int64", "*int64", "float64", "*float64" -> {
val parserNamespace = getPrimitiveTypeParserNamespace(ds3Element.type!!, ds3Element.nullable)
return ParseSimpleAttr(xmlName, modelName, paramName, parserNamespace)
}
"string" ->
return ParseStringAttr(xmlName, modelName, paramName)
"*string" ->
return ParseNullableStringAttr(xmlName, modelName, paramName)
else -> {
if (ds3Element.nullable) {
return ParseNullableEnumAttr(xmlName, modelName, paramName)
}
return ParseEnumAttr(xmlName, modelName, paramName)
}
}
}
/**
* Retrieves the xml tag name for the specified Ds3Element. The result is capitalized.
*/
fun getXmlTagName(ds3Element: Ds3Element): String {
return Ds3ElementUtil.getXmlTagName(ds3Element).capitalize()
}
/**
* Gets the namespace of the required primitive type parser used to parse
* the specified type. Assumes that the provided type is a Go primitive, or
* a pointer to a Go primitive type.
*/
fun getPrimitiveTypeParserNamespace(type: String, nullable: Boolean): String {
val parserPrefix = toGoType(type).capitalize()
if (nullable) {
return "Nullable$parserPrefix"
}
return parserPrefix
}
} | apache-2.0 | 908057f7bed1f600d46b1c4e4e48a288 | 44.087379 | 126 | 0.660601 | 4.711821 | false | false | false | false |
nemerosa/ontrack | ontrack-ui-graphql/src/main/java/net/nemerosa/ontrack/graphql/schema/GraphqlSchemaServiceImpl.kt | 1 | 5274 | package net.nemerosa.ontrack.graphql.schema
import graphql.schema.*
import graphql.schema.GraphQLObjectType.newObject
import net.nemerosa.ontrack.common.UserException
import net.nemerosa.ontrack.graphql.support.MutationInputValidationException
import org.springframework.stereotype.Service
@Service
class GraphqlSchemaServiceImpl(
private val types: List<GQLType>,
private val inputTypes: List<GQLInputType<*>>,
private val interfaces: List<GQLInterface>,
private val enums: List<GQLEnum>,
private val rootQueries: List<GQLRootQuery>,
private val mutationProviders: List<MutationProvider>
) : GraphqlSchemaService {
override val schema: GraphQLSchema by lazy {
createSchema()
}
private fun createSchema(): GraphQLSchema {
// All types
val cache = GQLTypeCache()
val dictionary = mutableSetOf<GraphQLType>()
dictionary.addAll(types.map { it.createType(cache) })
dictionary.addAll(interfaces.map { it.createInterface() })
dictionary.addAll(enums.map { it.createEnum() })
dictionary.addAll(inputTypes.map { it.createInputType(dictionary) })
val mutationType = createMutationType(dictionary)
return GraphQLSchema.newSchema()
.additionalTypes(dictionary)
.query(createQueryType())
.mutation(mutationType)
.build()
}
private fun createQueryType(): GraphQLObjectType {
return newObject()
.name(QUERY)
// Root queries
.fields(
rootQueries.map { it.fieldDefinition }
)
// OK
.build()
}
private fun createMutationType(dictionary: MutableSet<GraphQLType>): GraphQLObjectType {
return newObject()
.name(MUTATION)
// Root mutations
.fields(
mutationProviders.flatMap { provider ->
provider.mutations.map { mutation -> createMutation(mutation, dictionary) }
}
)
// OK
.build()
}
private fun createMutation(mutation: Mutation, dictionary: MutableSet<GraphQLType>): GraphQLFieldDefinition {
// Create the mutation input type
val inputType = createMutationInputType(mutation, dictionary)
// Create the mutation output type
val outputType = createMutationOutputType(mutation, dictionary)
// Create the mutation field
return GraphQLFieldDefinition.newFieldDefinition()
.name(mutation.name)
.description(mutation.description)
.argument {
it.name("input")
.description("Input for the mutation")
.type(inputType)
}
.type(outputType)
.dataFetcher { env -> mutationFetcher(mutation, env) }
.build()
}
private fun mutationFetcher(mutation: Mutation, env: DataFetchingEnvironment): Any {
return try {
mutation.fetch(env)
} catch (ex: Exception) {
when (ex) {
is MutationInputValidationException -> {
mapOf("errors" to ex.violations.map { cv ->
MutationInputValidationException.asUserError(cv)
})
}
is UserException -> {
val exception = ex::class.java.name
val error = UserError(
message = ex.message ?: exception,
exception = exception
)
mapOf("errors" to listOf(error))
}
else -> {
throw ex
}
}
}
}
private fun createMutationOutputType(mutation: Mutation, dictionary: MutableSet<GraphQLType>): GraphQLObjectType =
newObject()
.name("${mutation.typePrefix}Payload")
.description("Output type for the ${mutation.name} mutation.")
.fields(mutation.outputFields)
// All mutation payloads inherit from the Payload type
.withInterface(GraphQLTypeReference(GQLInterfacePayload.PAYLOAD))
// Errors field
.field(GQLInterfacePayload.payloadErrorsField())
// OK
.build()
.apply { dictionary.add(this) }
private fun createMutationInputType(mutation: Mutation, dictionary: MutableSet<GraphQLType>): GraphQLInputType =
GraphQLInputObjectType.newInputObject()
.name("${mutation.typePrefix}Input")
.description("Input type for the ${mutation.name} mutation.")
.fields(mutation.inputFields(dictionary))
.build()
.apply { dictionary.add(this) }
private val Mutation.typePrefix: String get() = name.capitalize()
companion object {
const val QUERY = "Query"
const val MUTATION = "Mutation"
}
}
| mit | d9269ca8a360a58e2defecfb05b1dc60 | 38.066667 | 118 | 0.559348 | 5.776561 | false | false | false | false |
openHPI/android-app | app/src/main/java/de/xikolo/controllers/section/VideoPreviewFragment.kt | 1 | 9625 | package de.xikolo.controllers.section
import android.content.res.Configuration
import android.graphics.Point
import android.os.Bundle
import android.text.TextUtils
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.FrameLayout
import android.widget.LinearLayout
import android.widget.TextView
import androidx.core.content.ContextCompat
import butterknife.BindView
import com.yatatsu.autobundle.AutoBundleField
import de.xikolo.R
import de.xikolo.config.GlideApp
import de.xikolo.controllers.base.ViewModelFragment
import de.xikolo.controllers.helper.DownloadViewHelper
import de.xikolo.controllers.video.VideoItemPlayerActivityAutoBundle
import de.xikolo.extensions.observe
import de.xikolo.models.DownloadAsset
import de.xikolo.models.Item
import de.xikolo.models.Video
import de.xikolo.utils.LanalyticsUtil
import de.xikolo.utils.LanguageUtil
import de.xikolo.utils.extensions.cast
import de.xikolo.utils.extensions.isCastConnected
import de.xikolo.utils.extensions.setMarkdownText
import de.xikolo.utils.extensions.videoThumbnailSize
import de.xikolo.viewmodels.section.VideoPreviewViewModel
import de.xikolo.views.CustomSizeImageView
import java.util.concurrent.TimeUnit
const val MAX_DESCRIPTION_LINES = 4
class VideoPreviewFragment : ViewModelFragment<VideoPreviewViewModel>() {
companion object {
val TAG: String = VideoPreviewFragment::class.java.simpleName
}
@AutoBundleField
lateinit var courseId: String
@AutoBundleField
lateinit var sectionId: String
@AutoBundleField
lateinit var itemId: String
@BindView(R.id.textTitle)
lateinit var textTitle: TextView
@BindView(R.id.textSubtitles)
lateinit var textSubtitles: TextView
@BindView(R.id.textPreviewDescription)
lateinit var textDescription: TextView
@BindView(R.id.showDescriptionButton)
lateinit var showDescriptionButton: Button
@BindView(R.id.videoDescriptionContainer)
lateinit var videoDescriptionContainer: FrameLayout
@BindView(R.id.durationText)
lateinit var textDuration: TextView
@BindView(R.id.videoThumbnail)
lateinit var imageVideoThumbnail: CustomSizeImageView
@BindView(R.id.containerDownloads)
lateinit var linearLayoutDownloads: LinearLayout
@BindView(R.id.refresh_layout)
lateinit var viewContainer: View
@BindView(R.id.playButton)
lateinit var viewPlay: View
@BindView(R.id.videoMetadata)
lateinit var videoMetadata: ViewGroup
private var downloadViewHelpers: MutableList<DownloadViewHelper> = ArrayList()
private var video: Video? = null
override val layoutResource = R.layout.fragment_video_preview
override fun createViewModel(): VideoPreviewViewModel {
return VideoPreviewViewModel(itemId)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setHasOptionsMenu(true)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
this.viewContainer.visibility = View.GONE
activity?.let {
val thumbnailSize: Point = it.videoThumbnailSize
imageVideoThumbnail.setDimensions(thumbnailSize.x, thumbnailSize.y)
if (it.resources?.configuration?.orientation != Configuration.ORIENTATION_PORTRAIT) {
val paramsMeta = videoMetadata.layoutParams
paramsMeta.width = thumbnailSize.x
videoMetadata.layoutParams = paramsMeta
}
}
viewModel.item
.observe(viewLifecycleOwner) { item ->
this.video = viewModel.video
video?.let { video ->
updateView(item, video)
showContent()
}
}
}
private fun updateView(item: Item, video: Video) {
viewContainer.visibility = View.VISIBLE
GlideApp.with(this)
.load(video.thumbnailUrl)
.override(imageVideoThumbnail.forcedWidth, imageVideoThumbnail.forcedHeight)
.into(imageVideoThumbnail)
textTitle.text = item.title
if (video.isSummaryAvailable) {
textDescription.setMarkdownText(video.summary?.trim())
displayCollapsedDescription()
showDescriptionButton.setOnClickListener {
if (textDescription.maxLines == MAX_DESCRIPTION_LINES) {
displayFullDescription()
} else {
displayCollapsedDescription()
}
}
} else {
hideDescription()
}
displayAvailableSubtitles()
linearLayoutDownloads.removeAllViews()
downloadViewHelpers.clear()
activity?.let { activity ->
if (video.streamToPlay?.hdUrl != null) {
val dvh = DownloadViewHelper(
activity,
DownloadAsset.Course.Item.VideoHD(item, video),
activity.getText(R.string.video_hd_as_mp4)
)
dvh.onOpenFileClick(R.string.play) { play() }
linearLayoutDownloads.addView(dvh.view)
downloadViewHelpers.add(dvh)
}
if (video.streamToPlay?.sdUrl != null) {
val dvh = DownloadViewHelper(
activity,
DownloadAsset.Course.Item.VideoSD(item, video),
activity.getText(R.string.video_sd_as_mp4)
)
dvh.onOpenFileClick(R.string.play) { play() }
linearLayoutDownloads.addView(dvh.view)
downloadViewHelpers.add(dvh)
}
if (video.slidesUrl != null) {
val dvh = DownloadViewHelper(
activity,
DownloadAsset.Course.Item.Slides(item, video),
activity.getText(R.string.slides_as_pdf)
)
linearLayoutDownloads.addView(dvh.view)
downloadViewHelpers.add(dvh)
}
if (video.transcriptUrl != null) {
val dvh = DownloadViewHelper(
activity,
DownloadAsset.Course.Item.Transcript(item, video),
activity.getText(R.string.transcript_as_pdf)
)
linearLayoutDownloads.addView(dvh.view)
downloadViewHelpers.add(dvh)
}
}
val minutes = TimeUnit.SECONDS.toMinutes(video.duration.toLong())
val seconds =
video.duration - TimeUnit.MINUTES.toSeconds(
TimeUnit.SECONDS.toMinutes(video.duration.toLong())
)
textDuration.text = getString(R.string.duration, minutes, seconds)
viewPlay.setOnClickListener { play() }
}
private fun play() {
video?.let { video ->
if (activity?.isCastConnected == true) {
LanalyticsUtil.trackVideoPlay(
itemId,
courseId,
sectionId,
video.progress,
1.0f,
Configuration.ORIENTATION_LANDSCAPE,
"hd",
"cast"
)
activity?.let {
video.cast(it, true)
}
} else {
activity?.let {
val intent = video.id?.let { videoId ->
VideoItemPlayerActivityAutoBundle
.builder(courseId, sectionId, itemId, videoId)
.parentIntent(it.intent)
.build(it)
}
startActivity(intent)
}
}
}
}
private fun displayAvailableSubtitles() {
video?.subtitles?.let { subtitles ->
if (subtitles.isNotEmpty()) {
textSubtitles.text =
subtitles.map {
LanguageUtil.toLocaleName(it.language)
}.joinToString(", ", getString(R.string.video_settings_subtitles) + ": ")
textSubtitles.visibility = View.VISIBLE
} else {
textSubtitles.visibility = View.GONE
}
}
}
private fun displayCollapsedDescription() {
videoDescriptionContainer.visibility = View.VISIBLE
videoDescriptionContainer.foreground = null
showDescriptionButton.visibility = View.GONE
textDescription.ellipsize = TextUtils.TruncateAt.END
textDescription.maxLines = MAX_DESCRIPTION_LINES
showDescriptionButton.text = getString(R.string.show_more)
textDescription.post {
if (textDescription.lineCount > MAX_DESCRIPTION_LINES) {
showDescriptionButton.visibility = View.VISIBLE
videoDescriptionContainer.foreground = ContextCompat.getDrawable(
requireContext(),
R.drawable.gradient_light_to_transparent_from_bottom
)
}
}
}
private fun displayFullDescription() {
textDescription.ellipsize = null
textDescription.maxLines = Integer.MAX_VALUE
videoDescriptionContainer.foreground = null
showDescriptionButton.text = getString(R.string.show_less)
}
private fun hideDescription() {
videoDescriptionContainer.visibility = View.GONE
showDescriptionButton.visibility = View.GONE
}
}
| bsd-3-clause | f4ca3d80d975636553c3eb20c148e133 | 32.77193 | 97 | 0.615896 | 5.320619 | false | false | false | false |
cashapp/sqldelight | sqldelight-compiler/src/main/kotlin/app/cash/sqldelight/core/GradleCompatibility.kt | 1 | 2330 | package app.cash.sqldelight.core
import app.cash.sqldelight.VERSION
object GradleCompatibility {
fun validate(propertiesFile: SqlDelightPropertiesFile): CompatibilityReport {
val (minimumIdeVersion, currentGradleVersion) = try {
SemVer(propertiesFile.minimumSupportedVersion) to SemVer(propertiesFile.currentVersion)
} catch (e: Throwable) {
// If we can't even read the properties file version, it is not compatibile
return CompatibilityReport.Incompatible(
reason = "Plugin 'SQLDelight' is incompatible with the current version of the SQLDelight Gradle plugin. Upgrade the version of app.cash.sqldelight:gradle-plugin.",
)
}
val currentVersion = SemVer(VERSION)
if (currentVersion < minimumIdeVersion) {
return CompatibilityReport.Incompatible(
reason = "Plugin 'SQLDelight' is no longer compatible with the current version of the SQLDelight Gradle plugin. Use version $minimumIdeVersion or later.",
)
}
val minimumGradleVersion = SemVer(MINIMUM_SUPPORTED_VERSION)
if (currentGradleVersion < minimumGradleVersion) {
return CompatibilityReport.Incompatible(
reason = "Gradle plugin 'app.cash.sqldelight:gradle-plugin' is incompatible with the current SQLDelight IntelliJ Plugin version. Use version $minimumGradleVersion or later.",
)
}
return CompatibilityReport.Compatible
}
private data class SemVer(
val major: Int,
val minor: Int,
val patch: Int,
val snapshot: Boolean,
) {
constructor(semVerText: String) : this(
major = semVerText.split('.')[0].toInt(),
minor = semVerText.split('.')[1].toInt(),
patch = semVerText.split('.')[2].filter { it.isDigit() }.toInt(),
snapshot = semVerText.endsWith("-SNAPSHOT"),
)
operator fun compareTo(other: SemVer): Int {
val majorCompare = major.compareTo(other.major)
if (majorCompare != 0) return majorCompare
val minorCompare = minor.compareTo(other.minor)
if (minorCompare != 0) return minorCompare
return patch.compareTo(other.patch)
}
override fun toString() = "$major.$minor.$patch"
}
sealed class CompatibilityReport {
object Compatible : CompatibilityReport()
data class Incompatible(
val reason: String,
) : CompatibilityReport()
}
}
| apache-2.0 | 1f3b01ccab91368923b9ad992f0ad358 | 34.846154 | 182 | 0.704292 | 4.745418 | false | false | false | false |
martin-nordberg/KatyDOM | Katydid-VDOM-JVM/src/test/kotlin/jvm/katydid/vdom/builders/forms/FieldSetTests.kt | 1 | 1417 | //
// (C) Copyright 2018-2019 Martin E. Nordberg III
// Apache 2.0 License
//
package jvm.katydid.vdom.builders.forms
import jvm.katydid.vdom.api.checkBuild
import o.katydid.vdom.application.katydid
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.assertThrows
@Suppress("RemoveRedundantBackticks")
class FieldSetTests {
@Test
fun `A fieldset element produces correct HTML`() {
val vdomNode = katydid<Unit> {
fieldset(disabled=true,form="SomeForm",name="bunch o'fields") {
legend {
text("This is the field set")
}
}
}
val html = """<fieldset disabled="" form="SomeForm" name="bunch o'fields">
| <legend>
| This is the field set
| </legend>
|</fieldset>""".trimMargin()
checkBuild(html, vdomNode)
}
@Test
fun `A fieldset may not have two legends`() {
assertThrows<IllegalStateException> {
katydid<Unit> {
fieldset {
legend {}
legend {}
}
}
}
}
@Test
fun `A legend must be nested inside a fieldset`() {
assertThrows<IllegalStateException> {
katydid<Unit> {
legend {}
}
}
}
} | apache-2.0 | 50ac7ee01abe813e0d4a5f11c5cbed2e | 17.415584 | 82 | 0.506704 | 4.771044 | false | true | false | false |
mix-it/mixit | src/main/kotlin/mixit/repository/UserRepository.kt | 1 | 3752 | package mixit.repository
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.module.kotlin.readValue
import mixit.model.Role
import mixit.model.User
import mixit.util.Cryptographer
import mixit.util.encodeToMd5
import org.slf4j.LoggerFactory
import org.springframework.core.io.ClassPathResource
import org.springframework.data.mongodb.core.ReactiveMongoTemplate
import org.springframework.data.mongodb.core.count
import org.springframework.data.mongodb.core.find
import org.springframework.data.mongodb.core.findAll
import org.springframework.data.mongodb.core.findById
import org.springframework.data.mongodb.core.findOne
import org.springframework.data.mongodb.core.query.Criteria.where
import org.springframework.data.mongodb.core.query.Query
import org.springframework.data.mongodb.core.query.TextCriteria
import org.springframework.data.mongodb.core.query.TextQuery
import org.springframework.data.mongodb.core.query.inValues
import org.springframework.data.mongodb.core.query.isEqualTo
import org.springframework.data.mongodb.core.remove
import org.springframework.stereotype.Repository
import reactor.core.publisher.Flux
import reactor.core.publisher.Mono
@Repository
class UserRepository(
private val template: ReactiveMongoTemplate,
private val objectMapper: ObjectMapper,
private val cryptographer: Cryptographer
) {
private val logger = LoggerFactory.getLogger(this.javaClass)
fun initData() {
// We delete all users to recreate them since next MEP
deleteAll()
if (count().block() == 0L) {
val usersResource = ClassPathResource("data/users.json")
val users: List<User> = objectMapper.readValue(usersResource.inputStream)
users.forEach { save(it).block() }
logger.info("Users data initialization complete")
}
}
fun findFullText(criteria: List<String>): Flux<User> {
val textCriteria = TextCriteria()
criteria.forEach { textCriteria.matching(it) }
val query = TextQuery(textCriteria).sortByScore()
return template.find(query)
}
fun count() = template.count<User>()
fun findByYear(year: Int) =
template.find<User>(Query(where("year").isEqualTo(year)))
fun findByNonEncryptedEmail(email: String) = template.findOne<User>(
Query(
where("role").inValues(Role.STAFF, Role.STAFF_IN_PAUSE, Role.USER, Role.VOLUNTEER)
.orOperator(where("email").isEqualTo(cryptographer.encrypt(email)), where("emailHash").isEqualTo(email.encodeToMd5()))
)
)
fun findByName(firstname: String, lastname: String) =
template.find<User>(Query(where("firstname").isEqualTo(firstname).and("lastname").isEqualTo(lastname)))
fun findByRoles(roles: List<Role>) =
template.find<User>(Query(where("role").inValues(roles)))
fun findByRoleAndEvent(role: Role, event: String) =
template.find<User>(Query(where("role").isEqualTo(role).and("events").inValues(event)))
fun findOneByRoles(login: String, roles: List<Role>) =
template.findOne<User>(Query(where("role").inValues(roles).and("_id").isEqualTo(login)))
fun findAll() = template.findAll<User>()
fun findOne(login: String) = template.findById<User>(login)
fun findMany(logins: List<String>) = template.find<User>(Query(where("_id").inValues(logins)))
fun findByLegacyId(id: Long) =
template.findOne<User>(Query(where("legacyId").isEqualTo(id)))
fun deleteAll() = template.remove<User>(Query())
fun deleteOne(login: String) = template.remove<User>(Query(where("_id").isEqualTo(login)))
fun save(user: User) = template.save(user)
fun save(user: Mono<User>) = template.save(user)
}
| apache-2.0 | 6607a5c0750e328f5c8ee227b3108dca | 38.083333 | 134 | 0.728145 | 4.069414 | false | false | false | false |
isuPatches/WiseFy | wisefy/src/androidTest/java/com/isupatches/wisefy/internal/mock/MockNetworkUtil.kt | 1 | 26303 | package com.isupatches.wisefy.internal.mock
import android.net.ConnectivityManager
import android.net.NetworkInfo
import android.net.wifi.ScanResult
import android.net.wifi.WifiConfiguration
import android.net.wifi.WifiInfo
import android.net.wifi.WifiManager
import com.isupatches.wisefy.TEST_IP_ADDRESS_INT
import com.isupatches.wisefy.TEST_RSSI_LEVEL
import com.isupatches.wisefy.TEST_RSSI_LEVEL_HIGH
import com.isupatches.wisefy.TEST_RSSI_LEVEL_LOW
import com.isupatches.wisefy.TEST_SSID
import com.isupatches.wisefy.TEST_SSID2
import com.isupatches.wisefy.TEST_SSID3
import com.isupatches.wisefy.WiseFy.Companion.WIFI_MANAGER_FAILURE
import com.isupatches.wisefy.internal.createMockAccessPointWithSSID
import com.isupatches.wisefy.internal.createMockAccessPointWithSSIDAndRSSI
import com.isupatches.wisefy.internal.createSavedNetwork
import org.mockito.ArgumentMatchers.any
import org.mockito.ArgumentMatchers.anyInt
import org.mockito.Mockito.`when`
import org.mockito.Mockito.mock
/**
* A class that mocks lower level returns from ConnectivityManager and WifiManager.
*
* @see ConnectivityManager
* @see WifiManager
*
* @author Patches
* @since 3.0
*/
@Suppress("LargeClass")
internal class MockNetworkUtil internal constructor(
private val mockConnectivityManager: ConnectivityManager,
private val mockWifiManager: WifiManager
) {
private var expectedNearbyAccessPoint: ScanResult? = null
private var expectedNearbyAccessPoints: MutableList<ScanResult>? = null
private var expectedSavedNetwork: WifiConfiguration? = null
private var expectedSavedNetworks: MutableList<WifiConfiguration>? = null
private var expectedSSIDs: MutableList<String>? = null
/**
* To mock a device having active network info.
*
* @see ConnectivityManager.getActiveNetworkInfo
*
* @author Patches
* @since 3.0
*/
internal fun activeNetwork() {
`when`(mockConnectivityManager.activeNetworkInfo).thenReturn(mock(NetworkInfo::class.java))
}
/**
* To mock a failure adding a network.
*
* @see WifiManager.addNetwork
*
* @author Patches
* @since 3.0
*/
internal fun addNetwork_failure() {
`when`(mockWifiManager.addNetwork(any(WifiConfiguration::class.java))).thenReturn(WIFI_MANAGER_FAILURE)
}
/**
* To mock a success adding a network.
*
* @see WifiManager.addNetwork
*
* @author Patches
* @since 3.0
*/
internal fun addNetwork_success() {
`when`(mockWifiManager.addNetwork(any(WifiConfiguration::class.java))).thenReturn(0)
}
/**
* To mock a device having an active network.
*
* @param ssid The SSID for the mocked network
*
* @return WifiInfo - The mock active network
*
* @see WifiInfo
* @see WifiManager.getConnectionInfo
*
* @author Patches
* @since 3.0
*/
internal fun currentNetwork(ssid: String?): WifiInfo {
val mockCurrentNetwork = mock(WifiInfo::class.java)
`when`(mockCurrentNetwork.ssid).thenReturn(ssid)
`when`(mockWifiManager.connectionInfo).thenReturn(mockCurrentNetwork)
return mockCurrentNetwork
}
/**
* To mock a current connection status.
*
* @param isAvailable Whether the network is available or not
* @param isConnected Whether the network is connected or not
* @param type The network type
*
* @see NetworkInfo.isAvailable
* @see NetworkInfo.isConnected
* @see NetworkInfo.getTypeName
* @see ConnectivityManager.getActiveNetworkInfo
*
* @author Patches
* @since 3.0
*/
@Suppress("deprecation")
internal fun currentNetworkConnectionStatus(isAvailable: Boolean, isConnected: Boolean, type: String?) {
val networkInfo = mock(NetworkInfo::class.java)
`when`(networkInfo.isAvailable).thenReturn(isAvailable)
`when`(networkInfo.isConnected).thenReturn(isConnected)
if (type != null) {
`when`(networkInfo.typeName).thenReturn(type)
}
`when`(mockConnectivityManager.activeNetworkInfo).thenReturn(networkInfo)
}
/**
* To mock no current network.
*
* @see WifiManager.getConnectionInfo
*
* @author Patches
* @since 4.0
*/
internal fun currentNetwork_null() {
`when`(mockWifiManager.connectionInfo).thenReturn(null)
}
/**
* To mock a failure disabling Wifi.
*
* @see WifiManager.setWifiEnabled
*
* @author Patches
* @since 3.0
*/
internal fun disableWifi_failure() {
`when`(mockWifiManager.setWifiEnabled(false)).thenReturn(false)
}
/**
* To mock a success disabling Wifi.
*
* @see WifiManager.setWifiEnabled
*
* @author Patches
* @since 3.0
*/
internal fun disableWifi_success() {
`when`(mockWifiManager.setWifiEnabled(false)).thenReturn(true)
}
/**
* To mock a failure disconnecting from current network.
*
* @see WifiManager.disconnect
*
* @author Patches
* @since 3.0
*/
internal fun disconnectFromCurrentNetwork_failure() {
`when`(mockWifiManager.disconnect()).thenReturn(false)
}
/**
* To mock a success disconnecting from current network.
*
* @see WifiManager.disconnect
*
* @author Patches
* @since 3.0
*/
internal fun disconnectFromCurrentNetwork_success() {
`when`(mockWifiManager.disconnect()).thenReturn(true)
}
/**
* To mock a failure enabling Wifi.
*
* @see WifiManager.setWifiEnabled
*
* @author Patches
* @since 3.0
*/
internal fun enableWifi_failure() {
`when`(mockWifiManager.setWifiEnabled(true)).thenReturn(false)
}
/**
* To mock a success enabling Wifi.
*
* @see WifiManager.setWifiEnabled
*
* @author Patches
* @since 3.0
*/
internal fun enableWifi_success() {
`when`(mockWifiManager.setWifiEnabled(true)).thenReturn(true)
}
/**
* To return the expected access point for testing.
*
* @return List of ScanResult - The expected access point for test
*
* @see ScanResult
*
* @author Patches
* @since 3.0
*/
internal fun getExpectedNearbyAccessPoint(): ScanResult? = expectedNearbyAccessPoint
/**
* To return the list of expected access points for testing.
*
* @return List of ScanResult - The expected access points for test
*
* @see ScanResult
*
* @author Patches
* @since 3.0
*/
internal fun getExpectedNearbyAccessPoints(): List<ScanResult>? = expectedNearbyAccessPoints
/**
* To return the expected saved network for testing.
*
* @return List of Strings - The expected saved network for test
*
* @see WifiConfiguration
*
* @author Patches
* @since 3.0
*/
internal fun getExpectedSavedNetwork(): WifiConfiguration? = expectedSavedNetwork
/**
* To return the expected list of saved networks for testing.
*
* @return List of WifiConfiguration - The expected saved networks for test
*
* @see WifiConfiguration
*
* @author Patches
* @since 3.0
*/
internal fun getExpectedSavedNetworks(): List<WifiConfiguration>? = expectedSavedNetworks
/**
* To return the expected list of SSIDs for testing.
*
* @return List of Strings - The expected SSIDS for test
*
* @author Patches
* @since 3.0
*/
internal fun getExpectedSSIDs(): List<String>? = expectedSSIDs
/**
* To mock if a device is roaming.
*
* @param roaming Whether the device is roaming or not
*
* @see NetworkInfo.isRoaming
* @see ConnectivityManager.getActiveNetworkInfo
*
* @author Patches
* @since 3.0
*/
@Suppress("deprecation")
internal fun isDeviceRoaming(roaming: Boolean) {
val networkInfo = mock(NetworkInfo::class.java)
`when`(networkInfo.isRoaming).thenReturn(roaming)
`when`(mockConnectivityManager.activeNetworkInfo).thenReturn(networkInfo)
}
/**
* To mock if Wifi is enabled or not.
*
* @param wifiEnabled Whether the device has Wifi enabled or not
*
* @see WifiManager.isWifiEnabled
*
* @author Patches
* @since 3.0
*/
internal fun isWifiEnabled(wifiEnabled: Boolean) {
`when`(mockWifiManager.isWifiEnabled).thenReturn(wifiEnabled)
}
/**
* To mock a network with a given frequency.
*
* @param frequency The frequency for the network
*
* @see WifiInfo.getFrequency
* @see WifiManager.getConnectionInfo
*
* @author Patches
* @since 3.0
*/
internal fun networkWithFrequency(frequency: Int): WifiInfo {
val mockWifiInfo = mock(WifiInfo::class.java)
`when`(mockWifiInfo.frequency).thenReturn(frequency)
`when`(mockWifiManager.connectionInfo).thenReturn(mockWifiInfo)
return mockWifiInfo
}
/**
* To mock a failure getting the IP of a device.
*
* @see WifiInfo.getIpAddress
* @see WifiManager.getConnectionInfo
*
* @author Patches
* @since 3.0
*/
internal fun ip_failure() {
val wifiInfo = mock(WifiInfo::class.java)
`when`(wifiInfo.ipAddress).thenReturn(0)
`when`(mockWifiManager.connectionInfo).thenReturn(wifiInfo)
}
/**
* To mock a success getting the IP of a device.
*
* @see WifiInfo.getIpAddress
* @see WifiManager.getConnectionInfo
*
* @author Patches
* @since 3.0
*/
internal fun ip_success() {
val wifiInfo = mock(WifiInfo::class.java)
`when`(wifiInfo.ipAddress).thenReturn(TEST_IP_ADDRESS_INT)
`when`(mockWifiManager.connectionInfo).thenReturn(wifiInfo)
}
/**
* To mock an empty list of access points.
*
* @see WifiManager.getScanResults
*
* @author Patches
* @since 3.0
*/
internal fun nearbyAccessPoints_emptyList() {
`when`(mockWifiManager.scanResults).thenReturn(ArrayList())
}
/**
* To mock a list of access points with one that has a matching SSID.
*
* @see addToExpectedNearbyAccessPoints
* @see addToExpectedSSIDs
* @see ScanResult
* @see WifiManager.getScanResults
*
* @author Patches
* @since 3.0
*/
internal fun nearbyAccessPoints_matchingSSID() {
val accessPoint = createMockAccessPointWithSSID(TEST_SSID)
val accessPoints = ArrayList<ScanResult>()
accessPoints.add(accessPoint)
addToExpectedNearbyAccessPoints(accessPoint)
addToExpectedSSIDs(accessPoint)
`when`(mockWifiManager.scanResults).thenReturn(accessPoints)
}
/**
* To mock a list of access points with multiple access points that have the same SSID.
* Access point 1 will have the higher RSSI level.
*
* @param takeHighest If the search is going to take the access point with the highest RSSI
*
* @see createMockAccessPointWithSSIDAndRSSI
* @see ScanResult
* @see addToExpectedNearbyAccessPoints
* @see addToExpectedSSIDs
* @see WifiManager.getScanResults
*
* @author Patches
* @since 3.0
*/
internal fun nearbyAccessPoints_multipleMatchingSSIDs_accessPoint1HasHigherRSSI(takeHighest: Boolean) {
val accessPoint1 = createMockAccessPointWithSSIDAndRSSI(TEST_SSID, TEST_RSSI_LEVEL_HIGH)
val accessPoint2 = createMockAccessPointWithSSIDAndRSSI(TEST_SSID, TEST_RSSI_LEVEL_LOW)
val accessPoints = ArrayList<ScanResult>()
accessPoints.add(accessPoint1)
accessPoints.add(accessPoint2)
if (takeHighest) {
addToExpectedNearbyAccessPoints(accessPoint1)
} else {
addToExpectedNearbyAccessPoints(accessPoint1, accessPoint2)
}
addToExpectedSSIDs(accessPoint1)
`when`(mockWifiManager.scanResults).thenReturn(accessPoints)
}
/**
* To mock a list of access points with multiple access points that have the same SSID.
* Access point 2 will have the higher RSSI level.
*
* @param takeHighest If the search is going to take the access point with the highest RSSI
*
* @see createMockAccessPointWithSSIDAndRSSI
* @see ScanResult
* @see addToExpectedNearbyAccessPoints
* @see addToExpectedSSIDs
* @see WifiManager.getScanResults
*
* @author Patches
* @since 3.0
*/
internal fun nearbyAccessPoints_multipleMatchingSSIDs_accessPoint2HasHigherRSSI(takeHighest: Boolean) {
val accessPoint1 = createMockAccessPointWithSSIDAndRSSI(TEST_SSID, TEST_RSSI_LEVEL_LOW)
val accessPoint2 = createMockAccessPointWithSSIDAndRSSI(TEST_SSID, TEST_RSSI_LEVEL_HIGH)
val accessPoints = ArrayList<ScanResult>()
accessPoints.add(accessPoint1)
accessPoints.add(accessPoint2)
if (takeHighest) {
addToExpectedNearbyAccessPoints(accessPoint2)
} else {
addToExpectedNearbyAccessPoints(accessPoint1, accessPoint2)
}
addToExpectedSSIDs(accessPoint1)
`when`(mockWifiManager.scanResults).thenReturn(accessPoints)
}
/**
* To mock a list of access points with one access point that has a matching SSID and
* another one that does not a matching SSID. Both will that have the same RSSI.
*
* @param addSecondNetwork If the second network should be added to the expected network
* list for testing
*
* @see createMockAccessPointWithSSIDAndRSSI
* @see ScanResult
* @see addToExpectedNearbyAccessPoints
* @see addToExpectedSSIDs
* @see WifiManager.getScanResults
*
* @author Patches
* @since 3.0
*/
internal fun nearbyAccessPoints_multipleSSIDs_sameRSSI(addSecondNetwork: Boolean) {
val accessPoint1 = createMockAccessPointWithSSIDAndRSSI(TEST_SSID, TEST_RSSI_LEVEL)
val accessPoint2 = createMockAccessPointWithSSIDAndRSSI(TEST_SSID2, TEST_RSSI_LEVEL)
val accessPoints = ArrayList<ScanResult>()
accessPoints.add(accessPoint1)
accessPoints.add(accessPoint2)
if (addSecondNetwork) {
addToExpectedNearbyAccessPoints(accessPoint1, accessPoint2)
} else {
addToExpectedNearbyAccessPoints(accessPoint1)
}
if (addSecondNetwork) {
addToExpectedSSIDs(accessPoint1, accessPoint2)
} else {
addToExpectedSSIDs(accessPoint1)
}
`when`(mockWifiManager.scanResults).thenReturn(accessPoints)
}
/**
* To mock a list of access points with multiple access points that have the same SSID and
* the same RSSI level.
*
* @param addSecondNetwork If the second network should be added to the expected network
* list for testing
*
* @see createMockAccessPointWithSSIDAndRSSI
* @see ScanResult
* @see addToExpectedNearbyAccessPoints
* @see addToExpectedSSIDs
* @see WifiManager.getScanResults
*
* @author Patches
* @since 3.0
*/
internal fun nearbyAccessPoints_multipleMatchingSSIDs_sameRSSI(addSecondNetwork: Boolean) {
val accessPoint1 = createMockAccessPointWithSSIDAndRSSI(TEST_SSID, TEST_RSSI_LEVEL)
val accessPoint2 = createMockAccessPointWithSSIDAndRSSI(TEST_SSID, TEST_RSSI_LEVEL)
val accessPoints = ArrayList<ScanResult>()
accessPoints.add(accessPoint1)
accessPoints.add(accessPoint2)
if (addSecondNetwork) {
addToExpectedNearbyAccessPoints(accessPoint1, accessPoint2)
} else {
addToExpectedNearbyAccessPoints(accessPoint1)
}
addToExpectedSSIDs(accessPoint1)
`when`(mockWifiManager.scanResults).thenReturn(accessPoints)
}
/**
* To mock a list of access points with multiple non-matching SSIDs.
*
* @see createMockAccessPointWithSSID
* @see ScanResult
* @see WifiManager.getScanResults
*
* @author Patches
* @since 3.0
*/
internal fun nearbyAccessPoints_multipleNonMatchingSSIDs() {
val accessPoint1 = createMockAccessPointWithSSID(TEST_SSID2)
val accessPoint2 = createMockAccessPointWithSSID(TEST_SSID3)
val accessPoints = ArrayList<ScanResult>()
accessPoints.add(accessPoint1)
accessPoints.add(accessPoint2)
`when`(mockWifiManager.scanResults).thenReturn(accessPoints)
}
/**
* To mock a list of access points with a non-matching SSID.
*
* @see createMockAccessPointWithSSID
* @see ScanResult
* @see WifiManager.getScanResults
*
* @author Patches
* @since 3.0
*/
internal fun nearbyAccessPoints_nonMatchingSSID() {
val accessPoint = createMockAccessPointWithSSID(TEST_SSID2)
val accessPoints = ArrayList<ScanResult>()
accessPoints.add(accessPoint)
`when`(mockWifiManager.scanResults).thenReturn(accessPoints)
}
/**
* To mock a list of access points with a null configuration.
*
* @see ScanResult
* @see WifiManager.getScanResults
*
* @author Patches
* @since 3.0
*/
internal fun nearbyAccessPoints_nullAccessPoint() {
val accessPoints = arrayListOf<ScanResult?>(null)
`when`(mockWifiManager.scanResults).thenReturn(accessPoints)
}
/**
* To mock a null list of access points.
*
* @see WifiManager.getScanResults
*
* @author Patches
* @since 3.0
*/
internal fun nearbyAccessPoints_nullList() {
`when`(mockWifiManager.scanResults).thenReturn(null)
}
/**
* To mock a list of access points with a configuration that has a null SSID.
*
* @see createMockAccessPointWithSSID
* @see ScanResult
* @see WifiManager.getScanResults
*
* @author Patches
* @since 3.0
*/
internal fun nearbyAccessPoints_nullSSID() {
val accessPoint = createMockAccessPointWithSSID(null)
val accessPoints = ArrayList<ScanResult>()
accessPoints.add(accessPoint)
`when`(mockWifiManager.scanResults).thenReturn(accessPoints)
}
/**
* To mock if removing a network is successful or not.
*
* @param removed Whether or not the network was successfully removed
*
* @see WifiManager.removeNetwork
*
* @author Patches
* @since 3.0
*/
internal fun removeNetwork(removed: Boolean) {
`when`(mockWifiManager.removeNetwork(anyInt())).thenReturn(removed)
}
/**
* To mock a list of saved networks.
*
* @return The list of saved networks for testing
*
* @see createSavedNetwork
* @see WifiConfiguration
* @see WifiManager.getConfiguredNetworks
*
* @author Patches
* @since 3.0
*/
internal fun savedNetworks(): List<WifiConfiguration> {
val savedNetworks = ArrayList<WifiConfiguration>()
val wiFiConfiguration = createSavedNetwork(TEST_SSID)
savedNetworks.add(wiFiConfiguration)
`when`(mockWifiManager.configuredNetworks).thenReturn(savedNetworks)
return savedNetworks
}
/**
* To mock an empty list of saved networks.
*
* @see WifiManager.getConfiguredNetworks
*
* @author Patches
* @since 3.0
*/
internal fun savedNetworks_emptyList() {
`when`(mockWifiManager.configuredNetworks).thenReturn(ArrayList())
}
/**
* To mock a list of saved networks with a null configuration.
*
* @see WifiManager.getConfiguredNetworks
*
* @author Patches
* @since 3.0
*/
internal fun savedNetworks_listWithNull() {
val savedNetworks = arrayListOf<WifiConfiguration?>(null)
`when`(mockWifiManager.configuredNetworks).thenReturn(savedNetworks)
}
/**
* To mock a list of saved networks with a configuration that has a matching SSID.
*
* @see addToExpectedSavedNetworks
* @see createSavedNetwork
* @see WifiConfiguration
* @see WifiManager.getConfiguredNetworks
*
* @author Patches
* @since 3.0
*/
internal fun savedNetworks_matchingSSID() {
val savedNetwork = createSavedNetwork(TEST_SSID)
val savedNetworks = ArrayList<WifiConfiguration>()
savedNetworks.add(savedNetwork)
addToExpectedSavedNetworks(savedNetwork)
`when`(mockWifiManager.configuredNetworks).thenReturn(savedNetworks)
}
/**
* To mock a list of saved networks with multiple configurations that have a matching SSID.
*
* @see addToExpectedSavedNetworks
* @see createSavedNetwork
* @see WifiConfiguration
* @see WifiManager.getConfiguredNetworks
*
* @author Patches
* @since 3.0
*/
internal fun savedNetworks_multipleMatchingSSIDs() {
val savedNetwork1 = createSavedNetwork(TEST_SSID)
val savedNetwork2 = createSavedNetwork(TEST_SSID)
val savedNetworks = ArrayList<WifiConfiguration>()
savedNetworks.add(savedNetwork1)
savedNetworks.add(savedNetwork2)
addToExpectedSavedNetworks(savedNetwork1, savedNetwork2)
`when`(mockWifiManager.configuredNetworks).thenReturn(savedNetworks)
}
/**
* To mock a list of saved networks with multiple configurations that have non-matching SSIDs.
*
* @see createSavedNetwork
* @see WifiConfiguration
* @see WifiManager.getConfiguredNetworks
*
* @author Patches
* @since 3.0
*/
internal fun savedNetworks_multipleNonMatchingSSIDs() {
val savedNetwork1 = createSavedNetwork(TEST_SSID2)
val savedNetwork2 = createSavedNetwork(TEST_SSID3)
val savedNetworks = ArrayList<WifiConfiguration>()
savedNetworks.add(savedNetwork1)
savedNetworks.add(savedNetwork2)
`when`(mockWifiManager.configuredNetworks).thenReturn(savedNetworks)
}
/**
* To mock a list of saved networks with one matching and one non-matching SSID.
*
* @param addSecondNetwork If the second network should be added to the expected network
* list for testing
*
* @see addToExpectedSavedNetworks
* @see createSavedNetwork
* @see WifiConfiguration
* @see WifiManager.getConfiguredNetworks
*
* @author Patches
* @since 3.0
*/
internal fun savedNetworks_multipleSSIDs(addSecondNetwork: Boolean) {
val savedNetwork1 = createSavedNetwork(TEST_SSID)
val savedNetwork2 = createSavedNetwork(TEST_SSID2)
val savedNetworks = ArrayList<WifiConfiguration>()
savedNetworks.add(savedNetwork1)
savedNetworks.add(savedNetwork2)
if (addSecondNetwork) {
addToExpectedSavedNetworks(savedNetwork1, savedNetwork2)
} else {
addToExpectedSavedNetworks(savedNetwork1)
}
`when`(mockWifiManager.configuredNetworks).thenReturn(savedNetworks)
}
/**
* To mock a list of saved networks with a configuration that has a non-matching SSID.
*
* @see createSavedNetwork
* @see WifiConfiguration
* @see WifiManager.getConfiguredNetworks
*
* @author Patches
* @since 3.0
*/
internal fun savedNetworks_nonMatchingSSID() {
val savedNetwork = createSavedNetwork(TEST_SSID2)
val savedNetworks = ArrayList<WifiConfiguration>()
savedNetworks.add(savedNetwork)
`when`(mockWifiManager.configuredNetworks).thenReturn(savedNetworks)
}
/**
* To mock a null list of saved networks.
*
* @see WifiManager.getConfiguredNetworks
*
* @author Patches
* @since 3.0
*/
internal fun savedNetworks_nullList() {
`when`(mockWifiManager.configuredNetworks).thenReturn(null)
}
/**
* To mock a list of saved networks with a configuration that has a null SSID.
*
* @see createSavedNetwork
* @see WifiConfiguration
* @see WifiManager.getConfiguredNetworks
*
* @author Patches
* @since 3.0
*/
internal fun savedNetworks_nullSSID() {
val savedNetwork = createSavedNetwork(null)
val savedNetworks = ArrayList<WifiConfiguration>()
savedNetworks.add(savedNetwork)
`when`(mockWifiManager.configuredNetworks).thenReturn(savedNetworks)
}
/*
* HELPERS
*/
private fun addToExpectedNearbyAccessPoints(accessPoint: ScanResult) {
expectedNearbyAccessPoint = accessPoint
val accessPoints = ArrayList<ScanResult>()
accessPoints.add(accessPoint)
expectedNearbyAccessPoints = accessPoints
}
private fun addToExpectedNearbyAccessPoints(accessPoint1: ScanResult, accessPoint2: ScanResult) {
expectedNearbyAccessPoint = accessPoint1
val accessPoints = ArrayList<ScanResult>()
accessPoints.add(accessPoint1)
accessPoints.add(accessPoint2)
expectedNearbyAccessPoints = accessPoints
}
private fun addToExpectedSavedNetworks(savedNetwork: WifiConfiguration) {
expectedSavedNetwork = savedNetwork
val savedNetworks = ArrayList<WifiConfiguration>()
savedNetworks.add(savedNetwork)
expectedSavedNetworks = savedNetworks
}
private fun addToExpectedSavedNetworks(savedNetwork1: WifiConfiguration, savedNetwork2: WifiConfiguration) {
expectedSavedNetwork = savedNetwork1
expectedSavedNetworks = ArrayList()
val savedNetworks = ArrayList<WifiConfiguration>()
savedNetworks.add(savedNetwork1)
savedNetworks.add(savedNetwork2)
expectedSavedNetworks = savedNetworks
}
private fun addToExpectedSSIDs(accessPoint: ScanResult) {
val ssids = ArrayList<String>()
ssids.add(accessPoint.SSID)
expectedSSIDs = ssids
}
private fun addToExpectedSSIDs(accessPoint1: ScanResult, accessPoint2: ScanResult) {
val ssids = ArrayList<String>()
ssids.add(accessPoint1.SSID)
ssids.add(accessPoint2.SSID)
expectedSSIDs = ssids
}
}
| apache-2.0 | 9bbeb316d50e5b3bff8b15d7d6d53d5b | 29.233333 | 112 | 0.664487 | 5.096493 | false | true | false | false |
freundTech/OneSlotServer | src/main/kotlin/com/freundtech/minecraft/oneslotserver/handler/event/ServerListPingListener.kt | 1 | 1205 | package com.freundtech.minecraft.oneslotserver.handler.event
import com.freundtech.minecraft.oneslotserver.OneSlotServer
import com.freundtech.minecraft.oneslotserver.extension.format
import com.freundtech.minecraft.oneslotserver.extension.oneSlotServer
import org.bukkit.Bukkit
import org.bukkit.event.EventHandler
import org.bukkit.event.Listener
import org.bukkit.event.server.ServerListPingEvent
class ServerListPingListener(private val plugin: OneSlotServer) : Listener{
private var iconEmpty = Bukkit.loadServerIcon(plugin.iconEmpty)
private var iconFull = Bukkit.loadServerIcon(plugin.iconFull)
@EventHandler
fun onServerListPing(event: ServerListPingEvent) {
event.maxPlayers = 1
event.removeAll { player -> Boolean
player.uniqueId != plugin.activePlayer?.uniqueId
}
plugin.activePlayer?.let {
val waitLeft = it.oneSlotServer.timeLeft
event.motd = "A player is currently playing. Please wait ${waitLeft.format()}."
event.setServerIcon(iconFull)
} ?: run {
event.motd = "Nobody is playing. You can join the server."
event.setServerIcon(iconEmpty)
}
}
} | mit | 5de266c7081e5f0d589784ec34ae81c9 | 35.545455 | 91 | 0.724481 | 4.112628 | false | false | false | false |
panpf/sketch | sketch-extensions/src/main/java/com/github/panpf/sketch/viewability/MimeTypeLogoAbility.kt | 1 | 4527 | /*
* Copyright (C) 2022 panpf <[email protected]>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.panpf.sketch.viewability
import android.content.Context
import android.graphics.Canvas
import android.graphics.drawable.Animatable
import android.graphics.drawable.Drawable
import androidx.appcompat.content.res.AppCompatResources
import com.github.panpf.sketch.util.findLastSketchDrawable
/**
* Display the MimeType logo in the lower right corner of the View
*/
fun ViewAbilityContainer.showMimeTypeLogoWithDrawable(
mimeTypeIconMap: Map<String, Drawable>,
margin: Int = 0
) {
removeMimeTypeLogo()
addViewAbility(
MimeTypeLogoAbility(
mimeTypeIconMap.mapValues { MimeTypeLogo(it.value) },
margin
)
)
}
/**
* Display the MimeType logo in the lower right corner of the View
*/
fun ViewAbilityContainer.showMimeTypeLogoWithRes(
mimeTypeIconMap: Map<String, Int>,
margin: Int = 0
) {
removeMimeTypeLogo()
addViewAbility(
MimeTypeLogoAbility(
mimeTypeIconMap.mapValues { MimeTypeLogo(it.value) },
margin
)
)
}
/**
* Remove MimeType logo
*/
fun ViewAbilityContainer.removeMimeTypeLogo() {
viewAbilityList
.find { it is MimeTypeLogoAbility }
?.let { removeViewAbility(it) }
}
/**
* Returns true if MimeType logo feature is enabled
*/
val ViewAbilityContainer.isShowMimeTypeLogo: Boolean
get() = viewAbilityList.find { it is MimeTypeLogoAbility } != null
class MimeTypeLogoAbility(
private val mimeTypeIconMap: Map<String, MimeTypeLogo>,
private val margin: Int = 0
) : ViewAbility, AttachObserver, DrawObserver, LayoutObserver, DrawableObserver {
override var host: Host? = null
private var logoDrawable: Drawable? = null
override fun onAttachedToWindow() {
reset()
host?.view?.invalidate()
}
override fun onDetachedFromWindow() {
}
override fun onDrawableChanged(oldDrawable: Drawable?, newDrawable: Drawable?) {
reset()
host?.view?.invalidate()
}
override fun onLayout(changed: Boolean, left: Int, top: Int, right: Int, bottom: Int) {
reset()
host?.view?.invalidate()
}
override fun onDrawBefore(canvas: Canvas) {
}
override fun onDraw(canvas: Canvas) {
logoDrawable?.draw(canvas)
}
private fun reset() {
logoDrawable = null
val host = host ?: return
val view = host.view
val lastDrawable = host.container.getDrawable()?.findLastSketchDrawable() ?: return
val mimeType = lastDrawable.imageInfo.mimeType
val mimeTypeLogo = mimeTypeIconMap[mimeType] ?: return
if (mimeTypeLogo.hiddenWhenAnimatable && lastDrawable is Animatable) return
val logoDrawable = mimeTypeLogo.getDrawable(host.context)
logoDrawable.setBounds(
view.right - view.paddingRight - margin - logoDrawable.intrinsicWidth,
view.bottom - view.paddingBottom - margin - logoDrawable.intrinsicHeight,
view.right - view.paddingRight - margin,
view.bottom - view.paddingBottom - margin
)
this.logoDrawable = logoDrawable
}
}
class MimeTypeLogo {
private val data: Any
private var _drawable: Drawable? = null
val hiddenWhenAnimatable: Boolean
constructor(drawable: Drawable, hiddenWhenAnimatable: Boolean = false) {
this.data = drawable
this.hiddenWhenAnimatable = hiddenWhenAnimatable
}
constructor(drawableResId: Int, hiddenWhenAnimatable: Boolean = false) {
this.data = drawableResId
this.hiddenWhenAnimatable = hiddenWhenAnimatable
}
fun getDrawable(context: Context): Drawable {
return _drawable
?: if (data is Drawable) {
data
} else {
AppCompatResources.getDrawable(context, data as Int)!!
}.apply {
_drawable = this
}
}
} | apache-2.0 | 7c684da95b8c95eeb4cdb2d411a592f1 | 28.402597 | 91 | 0.67484 | 4.836538 | false | false | false | false |
exponent/exponent | android/versioned-abis/expoview-abi43_0_0/src/main/java/abi43_0_0/host/exp/exponent/VersionedUtils.kt | 2 | 13099 | // Copyright 2015-present 650 Industries. All rights reserved.
package abi43_0_0.host.exp.exponent
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.provider.Settings
import android.util.Log
import com.facebook.common.logging.FLog
import abi43_0_0.com.facebook.hermes.reactexecutor.HermesExecutorFactory
import abi43_0_0.com.facebook.react.ReactInstanceManager
import abi43_0_0.com.facebook.react.ReactInstanceManagerBuilder
import abi43_0_0.com.facebook.react.bridge.JavaScriptContextHolder
import abi43_0_0.com.facebook.react.bridge.JavaScriptExecutorFactory
import abi43_0_0.com.facebook.react.bridge.ReactApplicationContext
import abi43_0_0.com.facebook.react.common.LifecycleState
import abi43_0_0.com.facebook.react.common.ReactConstants
import abi43_0_0.com.facebook.react.jscexecutor.JSCExecutorFactory
import abi43_0_0.com.facebook.react.modules.systeminfo.AndroidInfoHelpers
import abi43_0_0.com.facebook.react.packagerconnection.NotificationOnlyHandler
import abi43_0_0.com.facebook.react.packagerconnection.RequestHandler
import abi43_0_0.com.facebook.react.shell.MainReactPackage
import expo.modules.jsonutils.getNullable
import host.exp.exponent.Constants
import host.exp.exponent.RNObject
import host.exp.exponent.experience.ExperienceActivity
import host.exp.exponent.experience.ReactNativeActivity
import host.exp.exponent.kernel.KernelProvider
import host.exp.expoview.Exponent
import host.exp.expoview.Exponent.InstanceManagerBuilderProperties
import org.json.JSONObject
import abi43_0_0.host.exp.exponent.modules.api.reanimated.ReanimatedJSIModulePackage
import java.io.File
import java.io.FileInputStream
import java.io.FileNotFoundException
import java.io.IOException
import java.util.*
object VersionedUtils {
// Update this value when hermes-engine getting updated.
// Currently there is no way to retrieve Hermes bytecode version from Java,
// as an alternative, we maintain the version by hand.
private const val HERMES_BYTECODE_VERSION = 76
private fun toggleExpoDevMenu() {
val currentActivity = Exponent.instance.currentActivity
if (currentActivity is ExperienceActivity) {
currentActivity.toggleDevMenu()
} else {
FLog.e(
ReactConstants.TAG,
"Unable to toggle the Expo dev menu because the current activity could not be found."
)
}
}
private fun reloadExpoApp() {
val currentActivity = Exponent.instance.currentActivity as? ReactNativeActivity ?: return run {
FLog.e(
ReactConstants.TAG,
"Unable to reload the app because the current activity could not be found."
)
}
val devSupportManager = currentActivity.devSupportManager ?: return run {
FLog.e(
ReactConstants.TAG,
"Unable to get the DevSupportManager from current activity."
)
}
devSupportManager.callRecursive("reloadExpoApp")
}
private fun toggleElementInspector() {
val currentActivity = Exponent.instance.currentActivity as? ReactNativeActivity ?: return run {
FLog.e(
ReactConstants.TAG,
"Unable to toggle the element inspector because the current activity could not be found."
)
}
val devSupportManager = currentActivity.devSupportManager ?: return run {
FLog.e(
ReactConstants.TAG,
"Unable to get the DevSupportManager from current activity."
)
}
devSupportManager.callRecursive("toggleElementInspector")
}
private fun requestOverlayPermission(context: Context) {
// From the unexposed DebugOverlayController static helper
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
// Get permission to show debug overlay in dev builds.
if (!Settings.canDrawOverlays(context)) {
val intent = Intent(
Settings.ACTION_MANAGE_OVERLAY_PERMISSION,
Uri.parse("package:" + context.packageName)
).apply {
flags = Intent.FLAG_ACTIVITY_NEW_TASK
}
FLog.w(
ReactConstants.TAG,
"Overlay permissions needs to be granted in order for React Native apps to run in development mode"
)
if (intent.resolveActivity(context.packageManager) != null) {
context.startActivity(intent)
}
}
}
}
private fun togglePerformanceMonitor() {
val currentActivity = Exponent.instance.currentActivity as? ReactNativeActivity ?: return run {
FLog.e(
ReactConstants.TAG,
"Unable to toggle the performance monitor because the current activity could not be found."
)
}
val devSupportManager = currentActivity.devSupportManager ?: return run {
FLog.e(
ReactConstants.TAG,
"Unable to get the DevSupportManager from current activity."
)
}
val devSettings = devSupportManager.callRecursive("getDevSettings")
if (devSettings != null) {
val isFpsDebugEnabled = devSettings.call("isFpsDebugEnabled") as Boolean
if (!isFpsDebugEnabled) {
// Request overlay permission if needed when "Show Perf Monitor" option is selected
requestOverlayPermission(currentActivity)
}
devSettings.call("setFpsDebugEnabled", !isFpsDebugEnabled)
}
}
private fun toggleRemoteJSDebugging() {
val currentActivity = Exponent.instance.currentActivity as? ReactNativeActivity ?: return run {
FLog.e(
ReactConstants.TAG,
"Unable to toggle remote JS debugging because the current activity could not be found."
)
}
val devSupportManager = currentActivity.devSupportManager ?: return run {
FLog.e(
ReactConstants.TAG,
"Unable to get the DevSupportManager from current activity."
)
}
val devSettings = devSupportManager.callRecursive("getDevSettings")
if (devSettings != null) {
val isRemoteJSDebugEnabled = devSettings.call("isRemoteJSDebugEnabled") as Boolean
devSettings.call("setRemoteJSDebugEnabled", !isRemoteJSDebugEnabled)
}
}
private fun createPackagerCommandHelpers(): Map<String, RequestHandler> {
// Attach listeners to the bundler's dev server web socket connection.
// This enables tools to automatically reload the client remotely (i.e. in expo-cli).
val packagerCommandHandlers = mutableMapOf<String, RequestHandler>()
// Enable a lot of tools under the same command namespace
packagerCommandHandlers["sendDevCommand"] = object : NotificationOnlyHandler() {
override fun onNotification(params: Any?) {
if (params != null && params is JSONObject) {
when (params.getNullable<String>("name")) {
"reload" -> reloadExpoApp()
"toggleDevMenu" -> toggleExpoDevMenu()
"toggleRemoteDebugging" -> {
toggleRemoteJSDebugging()
// Reload the app after toggling debugging, this is based on what we do in DevSupportManagerBase.
reloadExpoApp()
}
"toggleElementInspector" -> toggleElementInspector()
"togglePerformanceMonitor" -> togglePerformanceMonitor()
}
}
}
}
// These commands (reload and devMenu) are here to match RN dev tooling.
// Reload the app on "reload"
packagerCommandHandlers["reload"] = object : NotificationOnlyHandler() {
override fun onNotification(params: Any?) {
reloadExpoApp()
}
}
// Open the dev menu on "devMenu"
packagerCommandHandlers["devMenu"] = object : NotificationOnlyHandler() {
override fun onNotification(params: Any?) {
toggleExpoDevMenu()
}
}
return packagerCommandHandlers
}
@JvmStatic fun getReactInstanceManagerBuilder(instanceManagerBuilderProperties: InstanceManagerBuilderProperties): ReactInstanceManagerBuilder {
// Build the instance manager
var builder = ReactInstanceManager.builder()
.setApplication(instanceManagerBuilderProperties.application)
.setJSIModulesPackage { reactApplicationContext: ReactApplicationContext, jsContext: JavaScriptContextHolder? ->
val devSupportManager = getDevSupportManager(reactApplicationContext)
if (devSupportManager == null) {
Log.e(
"Exponent",
"Couldn't get the `DevSupportManager`. JSI modules won't be initialized."
)
return@setJSIModulesPackage emptyList()
}
val devSettings = devSupportManager.callRecursive("getDevSettings")
val isRemoteJSDebugEnabled = devSettings != null && devSettings.call("isRemoteJSDebugEnabled") as Boolean
if (!isRemoteJSDebugEnabled) {
return@setJSIModulesPackage ReanimatedJSIModulePackage().getJSIModules(
reactApplicationContext,
jsContext
)
}
emptyList()
}
.addPackage(MainReactPackage())
.addPackage(
ExponentPackage(
instanceManagerBuilderProperties.experienceProperties,
instanceManagerBuilderProperties.manifest,
null, null,
instanceManagerBuilderProperties.singletonModules
)
)
.addPackage(
ExpoTurboPackage(
instanceManagerBuilderProperties.experienceProperties,
instanceManagerBuilderProperties.manifest
)
)
.setInitialLifecycleState(LifecycleState.BEFORE_CREATE)
.setCustomPackagerCommandHandlers(createPackagerCommandHelpers())
.setJavaScriptExecutorFactory(createJSExecutorFactory(instanceManagerBuilderProperties))
if (instanceManagerBuilderProperties.jsBundlePath != null && instanceManagerBuilderProperties.jsBundlePath!!.isNotEmpty()) {
builder = builder.setJSBundleFile(instanceManagerBuilderProperties.jsBundlePath)
}
return builder
}
private fun getDevSupportManager(reactApplicationContext: ReactApplicationContext): RNObject? {
val currentActivity = Exponent.instance.currentActivity
return if (currentActivity != null) {
if (currentActivity is ReactNativeActivity) {
currentActivity.devSupportManager
} else {
null
}
} else try {
val devSettingsModule = reactApplicationContext.catalystInstance.getNativeModule("DevSettings")
val devSupportManagerField = devSettingsModule!!.javaClass.getDeclaredField("mDevSupportManager")
devSupportManagerField.isAccessible = true
RNObject.wrap(devSupportManagerField[devSettingsModule]!!)
} catch (e: Throwable) {
e.printStackTrace()
null
}
}
private fun createJSExecutorFactory(
instanceManagerBuilderProperties: InstanceManagerBuilderProperties
): JavaScriptExecutorFactory? {
val appName = instanceManagerBuilderProperties.manifest.getName() ?: ""
val deviceName = AndroidInfoHelpers.getFriendlyDeviceName()
if (Constants.isStandaloneApp()) {
return JSCExecutorFactory(appName, deviceName)
}
val hermesBundlePair = parseHermesBundleHeader(instanceManagerBuilderProperties.jsBundlePath)
if (hermesBundlePair.first && hermesBundlePair.second != HERMES_BYTECODE_VERSION) {
val message = String.format(
Locale.US,
"Unable to load unsupported Hermes bundle.\n\tsupportedBytecodeVersion: %d\n\ttargetBytecodeVersion: %d",
HERMES_BYTECODE_VERSION, hermesBundlePair.second
)
KernelProvider.instance.handleError(RuntimeException(message))
return null
}
val jsEngineFromManifest = instanceManagerBuilderProperties.manifest.getAndroidJsEngine()
return if (jsEngineFromManifest == "hermes") HermesExecutorFactory() else JSCExecutorFactory(
appName,
deviceName
)
}
private fun parseHermesBundleHeader(jsBundlePath: String?): Pair<Boolean, Int> {
if (jsBundlePath == null || jsBundlePath.isEmpty()) {
return Pair(false, 0)
}
// https://github.com/facebook/hermes/blob/release-v0.5/include/hermes/BCGen/HBC/BytecodeFileFormat.h#L24-L25
val HERMES_MAGIC_HEADER = byteArrayOf(
0xc6.toByte(), 0x1f.toByte(), 0xbc.toByte(), 0x03.toByte(),
0xc1.toByte(), 0x03.toByte(), 0x19.toByte(), 0x1f.toByte()
)
val file = File(jsBundlePath)
try {
FileInputStream(file).use { inputStream ->
val bytes = ByteArray(12)
inputStream.read(bytes, 0, bytes.size)
// Magic header
for (i in HERMES_MAGIC_HEADER.indices) {
if (bytes[i] != HERMES_MAGIC_HEADER[i]) {
return Pair(false, 0)
}
}
// Bytecode version
val bundleBytecodeVersion: Int =
(bytes[11].toInt() shl 24) or (bytes[10].toInt() shl 16) or (bytes[9].toInt() shl 8) or bytes[8].toInt()
return Pair(true, bundleBytecodeVersion)
}
} catch (e: FileNotFoundException) {
} catch (e: IOException) {
}
return Pair(false, 0)
}
internal fun isHermesBundle(jsBundlePath: String?): Boolean {
return parseHermesBundleHeader(jsBundlePath).first
}
internal fun getHermesBundleBytecodeVersion(jsBundlePath: String?): Int {
return parseHermesBundleHeader(jsBundlePath).second
}
}
| bsd-3-clause | 6b207e5a40e66c890eca844da2b80e66 | 37.754438 | 146 | 0.710894 | 5.138878 | false | false | false | false |
AndroidX/androidx | compose/material3/material3/samples/src/main/java/androidx/compose/material3/samples/MenuSamples.kt | 3 | 3315 | /*
* 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.material3.samples
import androidx.annotation.Sampled
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.wrapContentSize
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.MoreVert
import androidx.compose.material.icons.outlined.Edit
import androidx.compose.material.icons.outlined.Email
import androidx.compose.material.icons.outlined.Settings
import androidx.compose.material3.Divider
import androidx.compose.material3.DropdownMenu
import androidx.compose.material3.DropdownMenuItem
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.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.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.tooling.preview.Preview
@Preview
@Sampled
@Composable
fun MenuSample() {
var expanded by remember { mutableStateOf(false) }
Box(modifier = Modifier.fillMaxSize().wrapContentSize(Alignment.TopStart)) {
IconButton(onClick = { expanded = true }) {
Icon(Icons.Default.MoreVert, contentDescription = "Localized description")
}
DropdownMenu(
expanded = expanded,
onDismissRequest = { expanded = false }
) {
DropdownMenuItem(
text = { Text("Edit") },
onClick = { /* Handle edit! */ },
leadingIcon = {
Icon(
Icons.Outlined.Edit,
contentDescription = null
)
})
DropdownMenuItem(
text = { Text("Settings") },
onClick = { /* Handle settings! */ },
leadingIcon = {
Icon(
Icons.Outlined.Settings,
contentDescription = null
)
})
Divider()
DropdownMenuItem(
text = { Text("Send Feedback") },
onClick = { /* Handle send feedback! */ },
leadingIcon = {
Icon(
Icons.Outlined.Email,
contentDescription = null
)
},
trailingIcon = { Text("F11", textAlign = TextAlign.Center) })
}
}
}
| apache-2.0 | 4bb6dbae8e4b91b07010ac73c5b51b52 | 36.247191 | 86 | 0.641629 | 5.030349 | false | false | false | false |
deva666/anko | anko/library/static/commons/src/dialogs/Selectors.kt | 2 | 1754 | /*
* Copyright 2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
@file:Suppress("NOTHING_TO_INLINE", "unused")
package org.jetbrains.anko
import android.app.Fragment
import android.content.Context
import android.content.DialogInterface
inline fun <D : DialogInterface> AnkoContext<*>.selector(
noinline factory: AlertBuilderFactory<D>,
title: CharSequence? = null,
items: List<CharSequence>,
noinline onClick: (DialogInterface, CharSequence, Int) -> Unit
): Unit = ctx.selector(factory, title, items, onClick)
inline fun <D : DialogInterface> Fragment.selector(
noinline factory: AlertBuilderFactory<D>,
title: CharSequence? = null,
items: List<CharSequence>,
noinline onClick: (DialogInterface, CharSequence, Int) -> Unit
): Unit = activity.selector(factory, title, items, onClick)
fun <D : DialogInterface> Context.selector(
factory: AlertBuilderFactory<D>,
title: CharSequence? = null,
items: List<CharSequence>,
onClick: (DialogInterface, CharSequence, Int) -> Unit
) {
with(factory(this)) {
if (title != null) {
this.title = title
}
items(items, onClick)
show()
}
} | apache-2.0 | 761f928e6e6dd40e82a12a24cebdf286 | 33.411765 | 75 | 0.688712 | 4.320197 | false | false | false | false |
pokk/SSFM | app/src/main/kotlin/taiwan/no1/app/ssfm/internal/di/modules/fragment/dependency/UseCaseModule.kt | 1 | 9002 | package taiwan.no1.app.ssfm.internal.di.modules.fragment.dependency
import dagger.Module
import dagger.Provides
import taiwan.no1.app.ssfm.internal.di.annotations.scopes.PerFragment
import taiwan.no1.app.ssfm.models.data.repositories.DataRepository
import taiwan.no1.app.ssfm.models.usecases.AddPlaylistCase
import taiwan.no1.app.ssfm.models.usecases.AddPlaylistItemCase
import taiwan.no1.app.ssfm.models.usecases.AddPlaylistItemUsecase
import taiwan.no1.app.ssfm.models.usecases.AddPlaylistUsecase
import taiwan.no1.app.ssfm.models.usecases.DeleteSearchHistoryCase
import taiwan.no1.app.ssfm.models.usecases.EditPlaylistCase
import taiwan.no1.app.ssfm.models.usecases.EditPlaylistUsecase
import taiwan.no1.app.ssfm.models.usecases.EditRankChartCase
import taiwan.no1.app.ssfm.models.usecases.EditRankChartUsecase
import taiwan.no1.app.ssfm.models.usecases.FetchAlbumInfoCase
import taiwan.no1.app.ssfm.models.usecases.FetchArtistInfoCase
import taiwan.no1.app.ssfm.models.usecases.FetchHotPlaylistCase
import taiwan.no1.app.ssfm.models.usecases.FetchMusicDetailCase
import taiwan.no1.app.ssfm.models.usecases.FetchMusicRankCase
import taiwan.no1.app.ssfm.models.usecases.FetchPlaylistCase
import taiwan.no1.app.ssfm.models.usecases.FetchPlaylistDetailCase
import taiwan.no1.app.ssfm.models.usecases.FetchPlaylistItemCase
import taiwan.no1.app.ssfm.models.usecases.FetchRankChartCase
import taiwan.no1.app.ssfm.models.usecases.FetchSearchHistoryCase
import taiwan.no1.app.ssfm.models.usecases.FetchTagInfoCase
import taiwan.no1.app.ssfm.models.usecases.FetchTopAlbumOfArtistCase
import taiwan.no1.app.ssfm.models.usecases.FetchTopAlbumOfTagCase
import taiwan.no1.app.ssfm.models.usecases.FetchTopArtistCase
import taiwan.no1.app.ssfm.models.usecases.FetchTopArtistOfTagCase
import taiwan.no1.app.ssfm.models.usecases.FetchTopTagCase
import taiwan.no1.app.ssfm.models.usecases.FetchTopTrackCase
import taiwan.no1.app.ssfm.models.usecases.FetchTopTrackOfArtistCase
import taiwan.no1.app.ssfm.models.usecases.FetchTopTrackOfTagCase
import taiwan.no1.app.ssfm.models.usecases.GetAlbumInfoUsecase
import taiwan.no1.app.ssfm.models.usecases.GetArtistInfoUsecase
import taiwan.no1.app.ssfm.models.usecases.GetArtistTopAlbumsUsecase
import taiwan.no1.app.ssfm.models.usecases.GetArtistTopTracksUsecase
import taiwan.no1.app.ssfm.models.usecases.GetDetailMusicUsecase
import taiwan.no1.app.ssfm.models.usecases.GetKeywordHistoriesUsecase
import taiwan.no1.app.ssfm.models.usecases.GetPlaylistItemsUsecase
import taiwan.no1.app.ssfm.models.usecases.GetPlaylistsUsecase
import taiwan.no1.app.ssfm.models.usecases.GetTagInfoUsecase
import taiwan.no1.app.ssfm.models.usecases.GetTagTopAlbumsUsecase
import taiwan.no1.app.ssfm.models.usecases.GetTagTopArtistsUsecase
import taiwan.no1.app.ssfm.models.usecases.GetTagTopTracksUsecase
import taiwan.no1.app.ssfm.models.usecases.GetTopArtistsUsecase
import taiwan.no1.app.ssfm.models.usecases.GetTopChartsUsecase
import taiwan.no1.app.ssfm.models.usecases.GetTopTagsUsecase
import taiwan.no1.app.ssfm.models.usecases.GetTopTracksUsecase
import taiwan.no1.app.ssfm.models.usecases.RemoveKeywordHistoriesUsecase
import taiwan.no1.app.ssfm.models.usecases.RemovePlaylistCase
import taiwan.no1.app.ssfm.models.usecases.RemovePlaylistItemCase
import taiwan.no1.app.ssfm.models.usecases.RemovePlaylistItemUsecase
import taiwan.no1.app.ssfm.models.usecases.RemovePlaylistUsecase
import taiwan.no1.app.ssfm.models.usecases.SearchMusicUsecase
import taiwan.no1.app.ssfm.models.usecases.SearchMusicV1Case
import taiwan.no1.app.ssfm.models.usecases.SearchMusicV2Case
import taiwan.no1.app.ssfm.models.usecases.v2.GetHotPlaylistUsecase
import taiwan.no1.app.ssfm.models.usecases.v2.GetMusicRankUsecase
import taiwan.no1.app.ssfm.models.usecases.v2.GetSongListUsecase
import javax.inject.Named
/**
* @author jieyi
* @since 10/21/17
*/
@Module
class UseCaseModule {
//region Chart top
@Provides
@PerFragment
fun provideTopArtistsUsecase(dataRepository: DataRepository): FetchTopArtistCase =
GetTopArtistsUsecase(dataRepository)
@Provides
@PerFragment
fun provideTopTracksUsecase(dataRepository: DataRepository): FetchTopTrackCase = GetTopTracksUsecase(dataRepository)
@Provides
@PerFragment
fun provideTopTagsUsecase(dataRepository: DataRepository): FetchTopTagCase = GetTopTagsUsecase(dataRepository)
@Provides
@PerFragment
fun provideRankChartUsecase(dataRepository: DataRepository): FetchRankChartCase = GetTopChartsUsecase(dataRepository)
@Provides
@PerFragment
fun provideEditRankChartUsecase(dataRepository: DataRepository): EditRankChartCase = EditRankChartUsecase(
dataRepository)
//endregion
//region Artist
@Provides
@PerFragment
fun provideArtistInfoUsecase(dataRepository: DataRepository): FetchArtistInfoCase =
GetArtistInfoUsecase(dataRepository)
@Provides
@PerFragment
fun provideArtistTopAlbumUsecase(dataRepository: DataRepository): FetchTopAlbumOfArtistCase =
GetArtistTopAlbumsUsecase(dataRepository)
@Provides
@PerFragment
fun provideArtistTopTrackUsecase(dataRepository: DataRepository): FetchTopTrackOfArtistCase =
GetArtistTopTracksUsecase(dataRepository)
//endregion
//region Album
@Provides
@PerFragment
fun provideAlbumInfoUsecase(dataRepository: DataRepository): FetchAlbumInfoCase = GetAlbumInfoUsecase(dataRepository)
//endregion
//region Tag
@Provides
@PerFragment
fun provideTagInfoUsecase(dataRepository: DataRepository): FetchTagInfoCase = GetTagInfoUsecase(dataRepository)
@Provides
@PerFragment
fun provideTagTopAlbumUsecase(dataRepository: DataRepository): FetchTopAlbumOfTagCase =
GetTagTopAlbumsUsecase(dataRepository)
@Provides
@PerFragment
fun provideTagTopArtistUsecase(dataRepository: DataRepository): FetchTopArtistOfTagCase =
GetTagTopArtistsUsecase(dataRepository)
@Provides
@PerFragment
fun provideTagTopTrackUsecase(dataRepository: DataRepository): FetchTopTrackOfTagCase =
GetTagTopTracksUsecase(dataRepository)
//endregion
//region Search music V1
@Provides
@PerFragment
fun provideGetKeywordHistoryUsecase(dataRepository: DataRepository): FetchSearchHistoryCase =
GetKeywordHistoriesUsecase(dataRepository)
@Provides
@PerFragment
fun provideSearchMusicUsecase(dataRepository: DataRepository): SearchMusicV1Case =
SearchMusicUsecase(dataRepository)
@Provides
@PerFragment
fun provideGetDetailMusicUsecase(dataRepository: DataRepository): FetchMusicDetailCase =
GetDetailMusicUsecase(dataRepository)
// endregion
//region Search music V2
@Provides
@PerFragment
fun provideSearchMusicV2Usecase(dataRepository: DataRepository): SearchMusicV2Case =
taiwan.no1.app.ssfm.models.usecases.v2.SearchMusicUsecase(dataRepository)
@Provides
@PerFragment
fun provideMusicRankUsecase(dataRepository: DataRepository): FetchMusicRankCase =
GetMusicRankUsecase(dataRepository)
@Provides
@PerFragment
fun provideHotPlaylistUsecase(dataRepository: DataRepository): FetchHotPlaylistCase =
GetHotPlaylistUsecase(dataRepository)
@Provides
@PerFragment
fun provideHotPlaylistDetailUsecase(dataRepository: DataRepository): FetchPlaylistDetailCase =
GetSongListUsecase(dataRepository)
//endregion
//region For Database
@Provides
@PerFragment
fun provideDeleteUsecase(dataRepository: DataRepository): DeleteSearchHistoryCase =
RemoveKeywordHistoriesUsecase(dataRepository)
@Provides
@PerFragment
@Named("add_playlist_item")
fun provideAddPlaylistItemUsecase(dataRepository: DataRepository): AddPlaylistItemCase =
AddPlaylistItemUsecase(dataRepository)
@Provides
@PerFragment
fun provideAddPlaylistUsecase(dataRepository: DataRepository): AddPlaylistCase =
AddPlaylistUsecase(dataRepository)
@Provides
@PerFragment
fun provideGetPlaylistsUsecase(dataRepository: DataRepository): FetchPlaylistCase =
GetPlaylistsUsecase(dataRepository)
@Provides
@PerFragment
fun provideGetPlaylistItemsUsecase(dataRepository: DataRepository): FetchPlaylistItemCase =
GetPlaylistItemsUsecase(dataRepository)
@Provides
@PerFragment
@Named("remove_playlist")
fun provideRemovePlaylistUsecase(dataRepository: DataRepository): RemovePlaylistCase =
RemovePlaylistUsecase(dataRepository)
@Provides
@PerFragment
@Named("remove_playlist_item")
fun provideRemovePlaylistItemUsecase(dataRepository: DataRepository): RemovePlaylistItemCase =
RemovePlaylistItemUsecase(dataRepository)
@Provides
@PerFragment
@Named("edit_playlist")
fun provideEditPlaylistUsecase(dataRepository: DataRepository): EditPlaylistCase =
EditPlaylistUsecase(dataRepository)
//endregion
} | apache-2.0 | 6dfa6e34ac72a7cacb585d5211c60d26 | 39.554054 | 121 | 0.810598 | 4.609319 | false | false | false | false |
pthomain/SharedPreferenceStore | lib/src/main/java/uk/co/glass_software/android/shared_preferences/persistence/preferences/StoreModule.kt | 1 | 2917 | /*
* Copyright (C) 2017 Glass Software Ltd
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package uk.co.glass_software.android.shared_preferences.persistence.preferences
import android.content.Context
import dagger.Module
import dagger.Provides
import io.reactivex.subjects.PublishSubject
import uk.co.glass_software.android.boilerplate.core.utils.delegates.Prefs
import uk.co.glass_software.android.boilerplate.core.utils.log.Logger
import uk.co.glass_software.android.shared_preferences.persistence.base.KeyValueStore
import uk.co.glass_software.android.shared_preferences.persistence.serialisation.SerialisationModule
import uk.co.glass_software.android.shared_preferences.persistence.serialisation.SerialisationModule.Companion.BASE_64
import uk.co.glass_software.android.shared_preferences.persistence.serialisation.SerialisationModule.Companion.CUSTOM
import uk.co.glass_software.android.shared_preferences.persistence.serialisation.Serialiser
import javax.inject.Named
import javax.inject.Singleton
@Module(includes = [SerialisationModule::class])
internal class StoreModule(private val context: Context,
private val prefs: Prefs,
private val logger: Logger,
private val isMemoryCacheEnabled: Boolean) {
@Provides
@Singleton
fun provideContext() = context
@Provides
@Singleton
fun provideSharedPreferenceStore(@Named(BASE_64) base64Serialiser: Serialiser,
@Named(CUSTOM) customSerialiser: Serialiser?,
logger: Logger): SharedPreferenceStore =
SharedPreferenceStore(
prefs,
base64Serialiser,
customSerialiser,
PublishSubject.create(),
logger,
isMemoryCacheEnabled
)
@Provides
@Singleton
fun provideStore(store: SharedPreferenceStore): KeyValueStore = store
@Provides
@Singleton
fun provideLogger() = logger
companion object {
internal const val MAX_FILE_NAME_LENGTH = 127
}
}
| apache-2.0 | 3f832553c0b91d322d0b4c00075cfeff | 37.893333 | 118 | 0.70929 | 4.781967 | false | false | false | false |
CruGlobal/android-gto-support | gto-support-material-components/src/main/kotlin/org/ccci/gto/android/common/material/bottomsheet/BindingBottomSheetDialogFragment.kt | 2 | 2060 | package org.ccci.gto.android.common.material.bottomsheet
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.annotation.LayoutRes
import androidx.databinding.DataBindingUtil
import androidx.databinding.ViewDataBinding
import androidx.viewbinding.ViewBinding
import com.google.android.material.bottomsheet.BottomSheetDialogFragment
import org.ccci.gto.android.common.base.Constants.INVALID_LAYOUT_RES
abstract class BindingBottomSheetDialogFragment<B : ViewBinding>(
@LayoutRes private val contentLayoutId: Int
) : BottomSheetDialogFragment() {
constructor() : this(INVALID_LAYOUT_RES)
private var binding: B? = null
// region Lifecycle
final override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
binding = onCreateBinding(inflater, container, savedInstanceState)?.also {
if (it is ViewDataBinding && it.lifecycleOwner == null) it.lifecycleOwner = viewLifecycleOwner
}
return binding?.root ?: super.onCreateView(inflater, container, savedInstanceState)
}
@Suppress("UNCHECKED_CAST")
protected open fun onCreateBinding(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): B? {
if (contentLayoutId != INVALID_LAYOUT_RES)
return DataBindingUtil.inflate<ViewDataBinding>(inflater, contentLayoutId, container, false) as? B
return null
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
binding?.let { onBindingCreated(it, savedInstanceState) }
}
open fun onBindingCreated(binding: B, savedInstanceState: Bundle?) = Unit
override fun onDestroyView() {
binding?.let { onDestroyBinding(it) }
binding = null
super.onDestroyView()
}
open fun onDestroyBinding(binding: B) = Unit
// endregion Lifecycle
}
| mit | e7361e0b742503fb4b467c29b6ac0001 | 33.915254 | 110 | 0.721845 | 5.09901 | false | false | false | false |
ligee/kotlin-jupyter | build-plugin/common-dependencies/src/org/jetbrains/kotlinx/jupyter/common/httpUtil.kt | 1 | 2545 | package org.jetbrains.kotlinx.jupyter.common
import kotlinx.serialization.decodeFromString
import kotlinx.serialization.encodeToString
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.JsonArray
import kotlinx.serialization.json.JsonElement
import kotlinx.serialization.json.JsonObject
import org.http4k.asString
import org.http4k.client.ApacheClient
import org.http4k.client.PreCannedApacheHttpClients
import org.http4k.core.Method
import org.http4k.core.Request
import org.http4k.core.Response
import org.http4k.core.then
import org.http4k.filter.ClientFilters
import java.io.IOException
import java.util.Base64
class ResponseWrapper(
response: Response,
val url: String,
) : Response by response
fun httpRequest(request: Request): ResponseWrapper {
PreCannedApacheHttpClients.defaultApacheHttpClient().use { closeableHttpClient ->
val apacheClient = ApacheClient(client = closeableHttpClient)
val client = ClientFilters.FollowRedirects().then(apacheClient)
val response = client(request)
return ResponseWrapper(response, request.uri.toString())
}
}
fun getHttp(url: String) = httpRequest(Request(Method.GET, url))
fun Request.withBasicAuth(username: String, password: String): Request {
val b64 = Base64.getEncoder().encode("$username:$password".toByteArray()).toString(Charsets.UTF_8)
return this.header("Authorization", "Basic $b64")
}
fun Request.withJson(json: JsonElement): Request {
return this
.body(Json.encodeToString(json))
.header("Content-Type", "application/json")
}
val Response.text: String get() {
return body.payload.asString()
}
fun ResponseWrapper.assertSuccessful() {
if (!status.successful) {
throw IOException("Http request failed. Url = $url. Response = $text")
}
}
inline fun <reified T> ResponseWrapper.decodeJson(): T {
assertSuccessful()
return Json.decodeFromString(text)
}
val ResponseWrapper.json: JsonElement get() = decodeJson()
val ResponseWrapper.jsonObject: JsonObject get() = decodeJson()
val ResponseWrapper.jsonArray: JsonArray get() = decodeJson()
inline fun <reified T> ResponseWrapper.decodeJsonIfSuccessfulOrNull(): T? {
return if (!status.successful) null
else Json.decodeFromString(text)
}
val ResponseWrapper.jsonOrNull: JsonElement? get() = decodeJsonIfSuccessfulOrNull()
val ResponseWrapper.jsonObjectOrNull: JsonObject? get() = decodeJsonIfSuccessfulOrNull()
val ResponseWrapper.jsonArrayOrNull: JsonArray? get() = decodeJsonIfSuccessfulOrNull()
| apache-2.0 | 7085158562ab06e5f86c91310036a130 | 33.391892 | 102 | 0.77053 | 4.284512 | false | false | false | false |
HabitRPG/habitica-android | Habitica/src/main/java/com/habitrpg/android/habitica/ui/views/tasks/form/ReminderItemFormView.kt | 1 | 6914 | package com.habitrpg.android.habitica.ui.views.tasks.form
import android.app.DatePickerDialog
import android.app.TimePickerDialog
import android.content.Context
import android.util.AttributeSet
import android.view.Gravity
import android.view.View
import android.view.ViewGroup
import android.view.animation.Animation
import android.view.animation.LinearInterpolator
import android.view.animation.RotateAnimation
import android.widget.DatePicker
import android.widget.LinearLayout
import android.widget.TimePicker
import androidx.core.content.ContextCompat
import com.habitrpg.android.habitica.R
import com.habitrpg.android.habitica.databinding.TaskFormReminderItemBinding
import com.habitrpg.android.habitica.models.tasks.RemindersItem
import com.habitrpg.common.habitica.extensions.dpToPx
import com.habitrpg.common.habitica.extensions.getThemeColor
import com.habitrpg.common.habitica.extensions.layoutInflater
import com.habitrpg.shared.habitica.models.tasks.TaskType
import java.text.DateFormat
import java.time.ZonedDateTime
import java.time.format.DateTimeFormatter
import java.util.Date
import java.util.Locale
class ReminderItemFormView @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
defStyleAttr: Int = 0
) : LinearLayout(context, attrs, defStyleAttr), TimePickerDialog.OnTimeSetListener, DatePickerDialog.OnDateSetListener {
private val formattedTime: CharSequence?
get() {
return if (item.time != null) {
val time = Date.from(item.getLocalZonedDateTimeInstant())
formatter.format(time)
} else {
""
}
}
private val binding = TaskFormReminderItemBinding.inflate(context.layoutInflater, this)
private val formatter: DateFormat
get() {
return if (taskType == TaskType.DAILY) {
DateFormat.getTimeInstance(DateFormat.SHORT, Locale.getDefault())
} else {
DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT, Locale.getDefault())
}
}
var taskType = TaskType.DAILY
var item: RemindersItem = RemindersItem()
set(value) {
field = value
binding.textView.text = formattedTime
}
var firstDayOfWeek: Int? = null
var tintColor: Int = context.getThemeColor(R.attr.taskFormTint)
var valueChangedListener: ((Date) -> Unit)? = null
var animDuration = 0L
var isAddButton: Boolean = true
set(value) {
field = value
binding.textView.text = if (value) context.getString(R.string.new_reminder) else formattedTime
if (value) {
val rotate = RotateAnimation(135f, 0f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f)
rotate.duration = animDuration
rotate.interpolator = LinearInterpolator()
rotate.fillAfter = true
binding.button.startAnimation(rotate)
// This button is not clickable in this state, so make screen readers skip it.
binding.button.importantForAccessibility = View.IMPORTANT_FOR_ACCESSIBILITY_NO
} else {
val rotate = RotateAnimation(0f, 135f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f)
rotate.duration = animDuration
rotate.interpolator = LinearInterpolator()
rotate.fillAfter = true
binding.button.startAnimation(rotate)
// This button IS now clickable, so allow screen readers to focus it.
binding.button.importantForAccessibility = View.IMPORTANT_FOR_ACCESSIBILITY_YES
}
}
init {
minimumHeight = 38.dpToPx(context)
background = ContextCompat.getDrawable(context, R.drawable.layout_rounded_bg_task_form)
background.mutate().setTint(ContextCompat.getColor(context, R.color.taskform_gray))
gravity = Gravity.CENTER_VERTICAL
binding.button.setOnClickListener {
if (!isAddButton) {
(parent as? ViewGroup)?.removeView(this)
}
}
// It's ok to make the description always be 'Delete Reminder' because when this button is
// a plus button we set it as 'unimportant for accessibility' so it can't be focused.
binding.button.contentDescription = context.getString(R.string.delete_reminder)
binding.button.drawable.mutate().setTint(tintColor)
binding.textView.setOnClickListener {
if (taskType == TaskType.DAILY) {
val timePickerDialog = TimePickerDialog(
context, this,
item.getZonedDateTime()?.hour ?: ZonedDateTime.now().hour,
item.getZonedDateTime()?.minute ?: ZonedDateTime.now().minute,
android.text.format.DateFormat.is24HourFormat(context)
)
timePickerDialog.show()
} else {
val zonedDateTime = (item.getZonedDateTime() ?: ZonedDateTime.now())
val timePickerDialog = DatePickerDialog(
context, this,
zonedDateTime.year,
zonedDateTime.monthValue - 1,
zonedDateTime.dayOfMonth
)
if ((firstDayOfWeek ?: -1) >= 0) {
timePickerDialog.datePicker.firstDayOfWeek = firstDayOfWeek ?: 0
}
timePickerDialog.show()
}
}
binding.textView.labelFor = binding.button.id
}
override fun onTimeSet(view: TimePicker?, hourOfDay: Int, minute: Int) {
valueChangedListener?.let {
val zonedDateTime = (item.getZonedDateTime() ?: ZonedDateTime.now())
.withHour(hourOfDay)
.withMinute(minute)
item.time = zonedDateTime.format(DateTimeFormatter.ISO_LOCAL_DATE_TIME)
binding.textView.text = formattedTime
it(Date.from(item.getLocalZonedDateTimeInstant()))
}
}
override fun onDateSet(view: DatePicker?, year: Int, month: Int, dayOfMonth: Int) {
valueChangedListener?.let {
val zonedDateTime = ZonedDateTime.now()
.withYear(year)
.withMonth(month + 1)
.withDayOfMonth(dayOfMonth)
item.time = zonedDateTime.format(DateTimeFormatter.ISO_LOCAL_DATE_TIME)
binding.textView.text = formattedTime
it(Date.from(item.getLocalZonedDateTimeInstant()))
val timePickerDialog = TimePickerDialog(
context, this,
ZonedDateTime.now().hour,
ZonedDateTime.now().minute,
android.text.format.DateFormat.is24HourFormat(context)
)
timePickerDialog.show()
}
}
}
| gpl-3.0 | 7b9b4e72e740f60a4c14e751f52149b5 | 41.679012 | 122 | 0.640006 | 5.065201 | false | false | false | false |
HabitRPG/habitica-android | Habitica/src/androidTest/java/com/habitrpg/android/habitica/ui/activities/TaskFormActivityTest.kt | 1 | 12624 | package com.habitrpg.android.habitica.ui.activities
import android.content.Intent
import android.os.Bundle
import androidx.test.core.app.ActivityScenario
import androidx.test.core.app.ApplicationProvider
import androidx.test.core.app.launchActivity
import androidx.test.espresso.assertion.ViewAssertions
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.filters.LargeTest
import com.habitrpg.android.habitica.HabiticaBaseApplication
import com.habitrpg.android.habitica.R
import com.habitrpg.android.habitica.components.UserComponent
import com.habitrpg.shared.habitica.models.tasks.Frequency
import com.habitrpg.android.habitica.models.tasks.Task
import com.habitrpg.shared.habitica.models.tasks.TaskType
import io.github.kakaocup.kakao.common.assertions.BaseAssertions
import io.github.kakaocup.kakao.common.matchers.ChildCountMatcher
import io.github.kakaocup.kakao.common.views.KView
import io.github.kakaocup.kakao.edit.KEditText
import io.github.kakaocup.kakao.picker.date.KDatePickerDialog
import io.github.kakaocup.kakao.screen.Screen
import io.github.kakaocup.kakao.spinner.KSpinner
import io.github.kakaocup.kakao.spinner.KSpinnerItem
import io.github.kakaocup.kakao.text.KButton
import io.github.kakaocup.kakao.toolbar.KToolbar
import io.mockk.every
import io.mockk.justRun
import io.mockk.mockk
import io.mockk.mockkObject
import io.mockk.slot
import io.mockk.verify
import io.reactivex.rxjava3.core.Flowable
import java.util.Date
import java.util.UUID
import org.junit.After
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
class TaskFormScreen : Screen<TaskFormScreen>() {
val toolbar = KToolbar { withId(R.id.toolbar) }
val textEditText = KEditText { withId(R.id.text_edit_text) }
val notesEditText = KEditText { withId(R.id.notes_edit_text) }
val taskDifficultyButtons = KView { withId(R.id.task_difficulty_buttons) }
val tagsWrapper = KView { withId(R.id.tags_wrapper) }
}
@LargeTest
@RunWith(AndroidJUnit4::class)
class TaskFormActivityTest : ActivityTestCase() {
val screen = TaskFormScreen()
lateinit var scenario: ActivityScenario<TaskFormActivity>
val taskSlot = slot<Task>()
@After
fun cleanup() {
scenario.close()
}
@Before
fun setup() {
every { sharedPreferences.getString("FirstDayOfTheWeek", any()) } returns "-1"
val mockComponent: UserComponent = mockk(relaxed = true)
every { mockComponent.inject(any<TaskFormActivity>()) } answers { initializeInjects(this.args.first()) }
mockkObject(HabiticaBaseApplication)
every { HabiticaBaseApplication.userComponent } returns mockComponent
}
private fun hasBasicTaskEditingViews() {
screen {
textEditText.isVisible()
notesEditText.isVisible()
taskDifficultyButtons.isVisible()
tagsWrapper.isVisible()
}
}
@Test
fun showsHabitForm() {
val bundle = Bundle()
bundle.putString(TaskFormActivity.TASK_TYPE_KEY, TaskType.HABIT.value)
val intent = Intent(ApplicationProvider.getApplicationContext(), TaskFormActivity::class.java)
intent.putExtras(bundle)
scenario = launchActivity(intent)
screen {
device.activities.isCurrent(TaskFormActivity::class.java)
toolbar.hasTitle("Create Habit")
hasBasicTaskEditingViews()
KView { withId(R.id.habit_scoring_buttons) }.isVisible()
KView { withId(R.id.habit_reset_streak_buttons) }.isVisible()
}
}
@Test
fun showsDailyForm() {
val bundle = Bundle()
bundle.putString(TaskFormActivity.TASK_TYPE_KEY, TaskType.DAILY.value)
val intent = Intent(ApplicationProvider.getApplicationContext(), TaskFormActivity::class.java)
intent.putExtras(bundle)
scenario = launchActivity(intent)
screen {
device.activities.isCurrent(TaskFormActivity::class.java)
toolbar.hasTitle("Create Daily")
hasBasicTaskEditingViews()
KView { withId(R.id.checklist_container) }.isVisible()
KView { withId(R.id.task_scheduling_controls) }.isVisible()
KView { withId(R.id.reminders_container) }.isVisible()
}
}
@Test
fun showsToDoForm() {
val bundle = Bundle()
bundle.putString(TaskFormActivity.TASK_TYPE_KEY, TaskType.TODO.value)
val intent = Intent(ApplicationProvider.getApplicationContext(), TaskFormActivity::class.java)
intent.putExtras(bundle)
scenario = launchActivity(intent)
screen {
device.activities.isCurrent(TaskFormActivity::class.java)
toolbar.hasTitle("Create To Do")
hasBasicTaskEditingViews()
KView { withId(R.id.checklist_container) }.isVisible()
KView { withId(R.id.task_scheduling_controls) }.isVisible()
KView { withId(R.id.reminders_container) }.isVisible()
}
}
@Test
fun showsRewardForm() {
val bundle = Bundle()
bundle.putString(TaskFormActivity.TASK_TYPE_KEY, TaskType.REWARD.value)
val intent = Intent(ApplicationProvider.getApplicationContext(), TaskFormActivity::class.java)
intent.putExtras(bundle)
scenario = launchActivity(intent)
screen {
device.activities.isCurrent(TaskFormActivity::class.java)
toolbar.hasTitle("Create Reward")
textEditText.isVisible()
notesEditText.isVisible()
tagsWrapper.isVisible()
KView { withId(R.id.reward_value) }.isVisible()
}
}
@Test
fun savesNewTask() {
val bundle = Bundle()
bundle.putString(TaskFormActivity.TASK_TYPE_KEY, TaskType.HABIT.value)
val intent = Intent(ApplicationProvider.getApplicationContext(), TaskFormActivity::class.java)
intent.putExtras(bundle)
scenario = launchActivity(intent)
screen {
device.activities.isCurrent(TaskFormActivity::class.java)
textEditText.typeText("New Habit")
KButton { withId(R.id.action_save) }.click()
verify(exactly = 1) { taskRepository.createTaskInBackground(any()) }
}
}
@Test
fun savesExistingTask() {
val task = Task()
task.id = UUID.randomUUID().toString()
task.text = "Task text"
task.type = TaskType.HABIT
task.priority = 1.0f
val bundle = Bundle()
bundle.putString(TaskFormActivity.TASK_TYPE_KEY, TaskType.HABIT.value)
bundle.putString(TaskFormActivity.TASK_ID_KEY, task.id!!)
every { taskRepository.getUnmanagedTask(any()) } returns Flowable.just(task)
val intent = Intent(ApplicationProvider.getApplicationContext(), TaskFormActivity::class.java)
intent.putExtras(bundle)
scenario = launchActivity(intent)
screen {
toolbar {
KView { withId(R.id.action_save) }.click()
verify(exactly = 1) { taskRepository.updateTaskInBackground(any()) }
}
}
}
@Test
fun deletesExistingTask() {
val task = Task()
task.id = UUID.randomUUID().toString()
task.text = "Task text"
task.type = TaskType.DAILY
task.priority = 1.0f
val bundle = Bundle()
bundle.putString(TaskFormActivity.TASK_TYPE_KEY, TaskType.DAILY.value)
bundle.putString(TaskFormActivity.TASK_TYPE_KEY, TaskType.DAILY.value)
bundle.putString(TaskFormActivity.TASK_ID_KEY, task.id!!)
every { taskRepository.getUnmanagedTask(any()) } returns Flowable.just(task)
val intent = Intent(ApplicationProvider.getApplicationContext(), TaskFormActivity::class.java)
intent.putExtras(bundle)
scenario = launchActivity(intent)
screen {
device.activities.isCurrent(TaskFormActivity::class.java)
KButton { withId(R.id.action_delete) }.click()
KButton { withText(R.string.delete_task) }.click()
verify(exactly = 1) { taskRepository.deleteTask(task.id!!) }
}
}
/* TODO: Revisit this. For some reason the matchers can't find the checklist add button
@Test
fun testChecklistItems() {
before {
val bundle = Bundle()
bundle.putString(TaskFormActivity.TASK_TYPE_KEY, TaskType.DAILY.value)
val intent = Intent(ApplicationProvider.getApplicationContext(), TaskFormActivity::class.java)
intent.putExtras(bundle)
scenario = launchActivity(intent)
justRun { taskRepository.createTaskInBackground(capture(taskSlot)) }
}.after { }.run {
screen {
KView { withId(R.id.checklist_container) } perform {
val container = this
step("Add new Checklist Item") {
hasChildCount(1)
KView {
withIndex(0) { withParent { this.getViewMatcher() } }
} perform {
click()
KEditText { withId(R.id.edit_text) }.typeText("test")
container.hasChildCount(2)
}
KEditText {
withIndex(1) { withId(R.id.edit_text) }
} perform {
click()
typeText("test2")
container.hasChildCount(3)
}
}
step("Edit Checklist Item") {
container.hasChildCount(3)
KEditText {
withIndex(0) { withId(R.id.edit_text) }
} perform {
clearText()
typeText("Test Text")
hasText("Test Text")
}
}
step("Remove Checklist Item") {
container.hasChildCount(3)
KView { withContentDescription(R.string.delete_checklist_entry) }.click()
container.hasChildCount(2)
}
step("Save Checklist") {
KButton { withId(R.id.action_save) }.click()
verify { taskRepository.createTaskInBackground(any()) }
assert(taskSlot.captured.checklist!!.size == 1)
assert(taskSlot.captured.checklist!!.first()!!.text == "Test Text")
}
}
}
}
}*/
@Test
fun changesScheduling() {
val task = Task()
task.id = UUID.randomUUID().toString()
task.text = "Task text"
task.type = TaskType.DAILY
task.priority = 1.0f
task.everyX = 1
task.frequency = Frequency.DAILY
task.startDate = Date()
val bundle = Bundle()
bundle.putString(TaskFormActivity.TASK_TYPE_KEY, TaskType.DAILY.value)
bundle.putString(TaskFormActivity.TASK_ID_KEY, task.id!!)
every { taskRepository.getUnmanagedTask(any()) } returns Flowable.just(task)
justRun { taskRepository.updateTaskInBackground(capture(taskSlot)) }
val intent = Intent(ApplicationProvider.getApplicationContext(), TaskFormActivity::class.java)
intent.putExtras(bundle)
scenario = launchActivity(intent)
screen {
KView { withId(R.id.start_date_wrapper) }.click()
KDatePickerDialog() perform {
datePicker.setDate(2021, 10, 2)
okButton.click()
}
KSpinner(
builder = { withId(R.id.repeats_every_spinner) },
itemTypeBuilder = { itemType(::KSpinnerItem) }
) perform {
open()
childAt<KSpinnerItem>(1) {
click()
}
}
KEditText { withId(R.id.repeats_every_edittext) } perform {
clearText()
typeText("3")
}
KButton { withId(R.id.action_save) }.click()
verify { taskRepository.updateTaskInBackground(any()) }
assert(taskSlot.captured.everyX == 3)
assert(taskSlot.captured.frequency == Frequency.WEEKLY)
}
}
}
private fun BaseAssertions.hasChildCount(count: Int) {
matches { ViewAssertions.matches(ChildCountMatcher(count)) }
}
| gpl-3.0 | 8c51ade3f0ff254b4b3be7cd3a2e46c7 | 37.843077 | 112 | 0.61185 | 4.809143 | false | true | false | false |
elect86/jAssimp | src/main/kotlin/assimp/Importer.kt | 2 | 39270 | /*
---------------------------------------------------------------------------
Open Asset Import Library (assimp)
---------------------------------------------------------------------------
Copyright (c) 2006-2017, assimp team
All rights reserved.
Redistribution and use of this software in source and binary forms,
with or without modification, are permitted provided that the following
conditions are met:
* Redistributions of source code must retain the above
copyright notice, this list of conditions and the
following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the
following disclaimer in the documentation and/or other
materials provided with the distribution.
* Neither the name of the assimp team, nor the names of its
contributors may be used to endorse or promote products
derived from this software without specific prior
written permission of the assimp team.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
---------------------------------------------------------------------------
*/
package assimp
import assimp.format.ProgressHandler
import assimp.postProcess.OptimizeMeshes
import assimp.postProcess.ValidateDSProcess
import glm_.i
import kool.BYTES
import kool.rem
import java.net.URI
import java.net.URL
import java.nio.ByteBuffer
import java.nio.file.Path
import java.nio.file.Paths
import kotlin.reflect.KMutableProperty0
import assimp.AiPostProcessStep as Pps
/** CPP-API: The Importer class forms an C++ interface to the functionality of the Open Asset Import Library.
*
* Create an object of this class and call ReadFile() to import a file.
* If the import succeeds, the function returns a pointer to the imported data.
* The data remains property of the object, it is intended to be accessed read-only. The imported data will be destroyed
* along with the Importer object. If the import fails, ReadFile() returns a NULL pointer. In this case you can retrieve
* a human-readable error description be calling GetErrorString(). You can call ReadFile() multiple times with a single
* Importer instance. Actually, constructing Importer objects involves quite many allocations and may take some time, so
* it's better to reuse them as often as possible.
*
* If you need the Importer to do custom file handling to access the files, implement IOSystem and IOStream and supply
* an instance of your custom IOSystem implementation by calling SetIOHandler() before calling ReadFile().
* If you do not assign a custion IO handler, a default handler using the standard C++ IO logic will be used.
*
* @note One Importer instance is not thread-safe. If you use multiple threads for loading, each thread should maintain
* its own Importer instance.
*/
class Importer
/** Constructor. Creates an empty importer object.
*
* Call readFile() to start the import process. The configuration property table is initially empty.
*/
constructor() {
// Just because we don't want you to know how we're hacking around.
internal val impl = ImporterPimpl() // allocate the pimpl first
fun impl() = impl
/** Copy constructor.
*
* This copies the configuration properties of another Importer.
* If this Importer owns a scene it won't be copied.
* Call readFile() to start the import process.
*/
constructor(other: Importer) : this() {
impl.properties += other.impl.properties
}
/** Registers a new loader.
*
* @param imp Importer to be added. The Importer instance takes ownership of the pointer, so it will be
* automatically deleted with the Importer instance.
* @return AI_SUCCESS if the loader has been added. The registration fails if there is already a loader for a
* specific file extension.
*/
fun registerLoader(imp: BaseImporter): AiReturn {
/* --------------------------------------------------------------------
Check whether we would have two loaders for the same file extension
This is absolutely OK, but we should warn the developer of the new loader that his code will probably never
be called if the first loader is a bit too lazy in his file checking.
-------------------------------------------------------------------- */
val st = imp.extensionList
var baked = ""
st.forEach {
if (ASSIMP.DEBUG && isExtensionSupported(it))
logger.warn { "The file extension $it is already in use" }
baked += "$it "
}
// add the loader
impl.importer.add(imp)
logger.info { "Registering custom importer for these file extensions: $baked" }
return AiReturn.SUCCESS
}
/** Unregisters a loader.
*
* @param imp Importer to be unregistered.
* @return AI_SUCCESS if the loader has been removed. The function fails if the loader is currently in use (this
* could happen if the Importer instance is used by more than one thread) or if it has not yet been registered.
*/
fun unregisterLoader(imp: BaseImporter) = when (impl.importer.remove(imp)) {
true -> logger.info { "Unregistering custom importer: " }.let { AiReturn.SUCCESS }
else -> logger.warn { "Unable to remove custom importer: I can't find you ..." }.let { AiReturn.FAILURE }
}
/** Registers a new post-process step.
*
* At the moment, there's a small limitation: new post processing steps are added to end of the list, or in other
* words, executed last, after all built-in steps.
* @param imp Post-process step to be added. The Importer instance takes ownership of the pointer, so it will be
* automatically deleted with the Importer instance.
* @return AI_SUCCESS if the step has been added correctly.
*/
fun registerPPStep(imp: BaseProcess): AiReturn {
impl.postProcessingSteps.add(imp)
logger.info { "Registering custom post-processing step" }
return AiReturn.SUCCESS
}
/** Unregisters a post-process step.
*
* @param imp Step to be unregistered.
* @return AI_SUCCESS if the step has been removed. The function fails if the step is currently in use (this could happen
* if the #Importer instance is used by more than one thread) or
* if it has not yet been registered.
*/
fun unregisterPPStep(imp: BaseProcess) = when (impl.postProcessingSteps.remove(imp)) {
true -> logger.info { "Unregistering custom post-processing step" }.let { AiReturn.SUCCESS }
else -> logger.warn { "Unable to remove custom post-processing step: I can't find you .." }.let { AiReturn.FAILURE }
}
operator fun <T : Any> set(szName: String, value: T) = impl.properties.put(superFastHash(szName), value)
inline operator fun <reified T> get(szName: String): T? = impl().properties[superFastHash(szName)] as? T
var prograssHandler: ProgressHandler?
/** Retrieves the progress handler that is currently set.
* You can use #IsDefaultProgressHandler() to check whether the returned interface is the default handler
* provided by ASSIMP. The default handler is active as long the application doesn't supply its own custom
* handler via setProgressHandler().
* @return A valid ProgressHandler interface, never null.
*/
get() = impl.progressHandler
/** Supplies a custom progress handler to the importer. This interface exposes a update() callback, which is
* called more or less periodically (please don't sue us if it isn't as periodically as you'd like it to have
* ...).
* This can be used to implement progress bars and loading timeouts.
* @param value Progress callback interface. Pass null to disable progress reporting.
* @note Progress handlers can be used to abort the loading at almost any time.*/
set(value) { // If the new handler is zero, allocate a default implementation.
if (value == null) { // Release pointer in the possession of the caller
impl.progressHandler = DefaultProgressHandler()
impl.isDefaultProgressHandler = true
} else if (impl.progressHandler != value) { // Otherwise register the custom handler
impl.progressHandler = value
impl.isDefaultProgressHandler = false
}
}
var ioHandler: IOSystem
get() = impl.ioSystem
set(value) {
impl.ioSystem = value
}
/** Checks whether a default progress handler is active
* A default handler is active as long the application doesn't supply its own custom progress handler via
* setProgressHandler().
* @return true by default
*/
val isDefaultProgressHandler get() = impl.isDefaultProgressHandler
/** @brief Check whether a given set of post-processing flags is supported.
*
* Some flags are mutually exclusive, others are probably not available because your excluded them from your
* Assimp builds. Calling this function is recommended if you're unsure.
*
* @param pFlags Bitwise combination of the aiPostProcess flags.
* @return true if this flag combination is fine.
*/
fun validateFlags(flags: Int) = when {
flags has Pps.GenSmoothNormals && flags has Pps.GenNormals -> {
logger.error { "#aiProcess_GenSmoothNormals and #aiProcess_GenNormals are incompatible" }
false
}
flags has Pps.OptimizeGraph && flags has Pps.PreTransformVertices -> {
logger.error { "#aiProcess_OptimizeGraph and #aiProcess_PreTransformVertices are incompatible" }
false
}
else -> true
}
/** Get the currently set progress handler */
val progressHandler get() = impl.progressHandler
@JvmOverloads
fun readFile(url: URL, flags: AiPostProcessStepsFlags = 0) = readFile(url.toURI(), flags)
@JvmOverloads
fun readFile(uri: URI, flags: AiPostProcessStepsFlags = 0) = readFile(Paths.get(uri), flags)
@JvmOverloads
fun readFile(path: Path, flags: AiPostProcessStepsFlags = 0) = readFile(path.toAbsolutePath().toString(), flags)
fun readFile(file: String, flags: AiPostProcessStepsFlags = 0) = readFile(file, ioHandler, flags)
/** Reads the given file and returns its contents if successful.
*
* If the call succeeds, the contents of the file are returned as a pointer to an AiScene object. The returned data
* is intended to be read-only, the importer object keeps ownership of the data and will destroy it upon
* destruction. If the import fails, null is returned.
* A human-readable error description can be retrieved by accessing errorString. The previous scene will be deleted
* during this call.
* @param file Path and filename to the file to be imported.
* @param flags Optional post processing steps to be executed after a successful import. Provide a bitwise
* combination of the AiPostProcessSteps flags. If you wish to inspect the imported scene first in order to
* fine-tune your post-processing setup, consider to use applyPostProcessing().
* @return A pointer to the imported data, null if the import failed.
* The pointer to the scene remains in possession of the Importer instance. Use getOrphanedScene() to take
* ownership of it.
*
* @note Assimp is able to determine the file format of a file automatically.
*/
@JvmOverloads
fun readFile(file: String, ioSystem: IOSystem = this.ioHandler, flags: AiPostProcessStepsFlags = 0): AiScene? {
writeLogOpening(file)
// Check whether this Importer instance has already loaded a scene. In this case we need to delete the old one
if (impl.scene != null) {
logger.debug { "(Deleting previous scene)" }
freeScene()
}
// First check if the file is accessible at all
// handled by exception in IOSystem
/*if (!file.exists()) {
impl.errorString = "Unable to open file \"$file\"."
logger.error { impl.errorString }
return null
}*/
// TODO std::unique_ptr<Profiler> profiler(GetPropertyInteger(AI_CONFIG_GLOB_MEASURE_TIME,0)?new Profiler():NULL);
// if (profiler) {
// profiler->BeginRegion("total");
// }
// Find an worker class which can handle the file
val imp = impl.importer.find { it.canRead(file, ioHandler, false) }
if (imp == null) {
logger.error { "Assimp could not find an importer for the file!" }
return null
// not so bad yet ... try format auto detection.
// TODO()
// const std::string::size_type s = pFile.find_last_of('.');
// if (s != std::string::npos) {
// DefaultLogger::get()->info("File extension not known, trying signature-based detection");
// for( unsigned int a = 0; a < pimpl->mImporter.size(); a++) {
//
// if( pimpl->mImporter[a]->CanRead( pFile, pimpl->mIOHandler, true)) {
// imp = pimpl->mImporter[a];
// break;
// }
// }
// }
// // Put a proper error message if no suitable importer was found
// if( !imp) {
// pimpl->mErrorString = "No suitable reader found for the file format of file \"" + pFile + "\".";
// DefaultLogger::get()->error(pimpl->mErrorString);
// return NULL;
// }
}
// Get file size for progress handler
val fileSize = ioSystem.open(file).length.i
// Dispatch the reading to the worker class for this format
val desc = imp.info
val ext = desc.name
logger.info { "Found a matching importer for this file format: $ext." }
impl.progressHandler.updateFileRead(0, fileSize)
// if (profiler) { TODO
// profiler->BeginRegion("import");
// }
impl.scene = imp.readFile(this, ioHandler, file)
impl.progressHandler.updateFileRead(fileSize, fileSize)
// if (profiler) { TODO
// profiler->EndRegion("import");
// }
// If successful, apply all active post processing steps to the imported data
if (impl.scene != null) {
if (!ASSIMP.NO.VALIDATEDS_PROCESS)
// The ValidateDS process is an exception. It is executed first, even before ScenePreprocessor is called.
if (flags has Pps.ValidateDataStructure) {
ValidateDSProcess().executeOnScene(this)
if (impl.scene == null) return null
}
// Preprocess the scene and prepare it for post-processing
// if (profiler) profiler.BeginRegion("preprocess")
ScenePreprocessor.processScene(impl.scene!!)
// if (profiler) profiler.EndRegion("preprocess")
// Ensure that the validation process won't be called twice
applyPostProcessing(flags wo Pps.ValidateDataStructure)
}
// if failed, extract the error string
else if (impl.scene == null)
impl.errorString = imp.errorText
// if (profiler) { profiler ->
// EndRegion("total");
// }
return impl.scene
}
/** Reads the given file from a memory buffer and returns its contents if successful.
*
* If the call succeeds, the contents of the file are returned as a pointer to an AiScene object. The returned data
* is intended to be read-only, the importer object keeps ownership of the data and will destroy it upon
* destruction. If the import fails, null is returned.
* A human-readable error description can be retrieved by accessing errorString. The previous scene will be deleted
* during this call.
* Calling this method doesn't affect the active IOSystem.
* @param buffer Pointer to the file data
* @param flags Optional post processing steps to be executed after a successful import. Provide a bitwise
* combination of the AiPostProcessSteps flags. If you wish to inspect the imported scene first in order to
* fine-tune your post-processing setup, consider to use applyPostProcessing().
* @param hint An additional hint to the library. If this is a non empty string, the library looks for a loader to
* support the file extension specified by hint and passes the file to the first matching loader. If this loader is
* unable to completely the request, the library continues and tries to determine the file format on its own, a
* task that may or may not be successful.
* Check the return value, and you'll know ...
* @return A pointer to the imported data, null if the import failed.
* The pointer to the scene remains in possession of the Importer instance. Use getOrphanedScene() to take
* ownership of it.
*
* @note This is a straightforward way to decode models from memory buffers, but it doesn't handle model formats
* that spread their data across multiple files or even directories. Examples include OBJ or MD3, which outsource
* parts of their material info into external scripts. If you need full functionality you can use [readFilesFromMemory]
*/
fun readFileFromMemory(buffer: ByteBuffer, flags: Int, name: String = AI_MEMORYIO_MAGIC_FILENAME,
hint: String = ""): AiScene? {
if (buffer.rem == 0 || hint.length > MaxLenHint) {
impl.errorString = "Invalid parameters passed to ReadFileFromMemory()"
return null
}
// prevent deletion of previous IOSystem
val io = impl.ioSystem
val fileName = "$name.$hint"
ioHandler = MemoryIOSystem(fileName to buffer)
readFile(fileName, flags)
impl.ioSystem = io
return impl.scene
}
/**Reads the given file from a memory buffer and returns its contents if successful.
*
* If the call succeeds, the contents of the file are returned as a pointer to an AiScene object. The returned data
* is intended to be read-only, the importer object keeps ownership of the data and will destroy it upon
* destruction. If the import fails, null is returned.
* A human-readable error description can be retrieved by accessing errorString. The previous scene will be deleted
* during this call.
* Calling this method doesn't affect the active IOSystem.
*
* @param fileName name of the base file
* @param files a map containing the names and all the files required to read the scene (base file, materials,
* textures, etc).
* @param flags Optional post processing steps to be executed after a successful import. Provide a bitwise
* combination of the AiPostProcessSteps flags. If you wish to inspect the imported scene first in order to
* fine-tune your post-processing setup, consider to use applyPostProcessing().
* @return A pointer to the imported data, null if the import failed.
* The pointer to the scene remains in possession of the Importer instance. Use getOrphanedScene() to take
* ownership of it.
*/
fun readFilesFromMemory(fileName: String, files: Map<String, ByteBuffer>, flags: Int): AiScene? {
for((name, buffer) in files) {
if(buffer.rem == 0){
impl.errorString = "buffer $name is empty"
return null
}
}
if(!files.containsKey(fileName)){
impl.errorString = "fileName ($fileName) not in files"
return null
}
val io = impl.ioSystem
ioHandler = MemoryIOSystem(files)
readFile(fileName, flags)
impl.ioSystem = io
return impl.scene
}
/**Reads the given file from a memory buffer and returns its contents if successful.
*
* If the call succeeds, the contents of the file are returned as a pointer to an AiScene object. The returned data
* is intended to be read-only, the importer object keeps ownership of the data and will destroy it upon
* destruction. If the import fails, null is returned.
* A human-readable error description can be retrieved by accessing errorString. The previous scene will be deleted
* during this call.
* Calling this method doesn't affect the active IOSystem.
*
* @param fileName name of the base file
* @param flags Optional post processing steps to be executed after a successful import. Provide a bitwise
* combination of the AiPostProcessSteps flags. If you wish to inspect the imported scene first in order to
* fine-tune your post-processing setup, consider to use applyPostProcessing().
* @param files the files required to read the scene (base file, materials, textures, etc) as a pair with their name.
* @return A pointer to the imported data, null if the import failed.
* The pointer to the scene remains in possession of the Importer instance. Use getOrphanedScene() to take
* ownership of it.
*/
fun readFilesFromMemory(fileName: String, vararg files: Pair<String, ByteBuffer>, flags: Int = 0): AiScene? {
return readFilesFromMemory(fileName, files.toMap(), flags)
}
/** Apply post-processing to an already-imported scene.
*
* This is strictly equivalent to calling readFile() with the same flags. However, you can use this separate
* function to inspect the imported scene first to fine-tune your post-processing setup.
* @param flags_ Provide a bitwise combination of the AiPostProcessSteps flags.
* @return A pointer to the post-processed data. This is still the same as the pointer returned by readFile().
* However, if post-processing fails, the scene could now be null.
* That's quite a rare case, post processing steps are not really designed to 'fail'. To be exact, the
* AiProcess_ValidateDS flag is currently the only post processing step which can actually cause the scene to be
* reset to null.
*
* @note The method does nothing if no scene is currently bound to the Importer instance. */
fun applyPostProcessing(flags_: Int): AiScene? {
// Return immediately if no scene is active
if (impl.scene == null) return null
// If no flags are given, return the current scene with no further action
if (flags_ == 0) return impl.scene
// In debug builds: run basic flag validation
assert(_validateFlags(flags_))
logger.info("Entering post processing pipeline")
if (!ASSIMP.NO.VALIDATEDS_PROCESS)
/* The ValidateDS process plays an exceptional role. It isn't contained in the global list of post-processing
steps, so we need to call it manually. */
if (flags_ has Pps.ValidateDataStructure) {
ValidateDSProcess().executeOnScene(this)
if (impl.scene == null) return null
}
if (flags_ has Pps.OptimizeMeshes) {
OptimizeMeshes().executeOnScene(this)
if (impl.scene == null) return null
}
var flags = flags_
if (ASSIMP.DEBUG) {
if (impl.extraVerbose) {
if (ASSIMP.NO.VALIDATEDS_PROCESS)
logger.error { "Verbose Import is not available due to build settings" }
flags = flags or Pps.ValidateDataStructure
}
} else if (impl.extraVerbose)
logger.warn("Not a debug build, ignoring extra verbose setting")
// std::unique_ptr<Profiler> profiler (GetPropertyInteger(AI_CONFIG_GLOB_MEASURE_TIME, 0)?new Profiler():NULL); TODO
for (a in impl.postProcessingSteps.indices) {
val process = impl.postProcessingSteps[a]
impl.progressHandler.updatePostProcess(a, impl.postProcessingSteps.size)
if (process.isActive(flags)) {
// if (profiler) { profiler -> TODO
// BeginRegion("postprocess")
// }
process.executeOnScene(this)
// if (profiler) { profiler ->
// EndRegion("postprocess")
// }
}
if (impl.scene == null) break
if (ASSIMP.DEBUG) {
if (ASSIMP.NO.VALIDATEDS_PROCESS) continue
// If the extra verbose mode is active, execute the ValidateDataStructureStep again - after each step
if (impl.extraVerbose) {
logger.debug { "Verbose Import: revalidating data structures" }
ValidateDSProcess().executeOnScene(this)
if (impl.scene == null) {
logger.error { "Verbose Import: failed to revalidate data structures" }
break
}
}
}
}
impl.progressHandler.updatePostProcess(impl.postProcessingSteps.size, impl.postProcessingSteps.size)
// update private scene flags
if (impl.scene != null)
// scenePriv(pimpl->mScene)->mPPStepsApplied | = pFlags TODO
logger.info { "Leaving post processing pipeline" }
return impl.scene
}
fun applyCustomizedPostProcessing(rootProcess: BaseProcess?, requestValidation: Boolean): AiScene? {
// Return immediately if no scene is active
if (null == impl.scene) return null
// If no flags are given, return the current scene with no further action
if (null == rootProcess) return impl.scene
// In debug builds: run basic flag validation
logger.info { "Entering customized post processing pipeline" }
if (!ASSIMP.NO.VALIDATEDS_PROCESS) {
// The ValidateDS process plays an exceptional role. It isn't contained in the global
// list of post-processing steps, so we need to call it manually.
if (requestValidation) {
ValidateDSProcess().executeOnScene(this)
if (impl.scene == null) return null
}
}
if (ASSIMP.DEBUG && impl.extraVerbose && ASSIMP.NO.VALIDATEDS_PROCESS)
logger.error { "Verbose Import is not available due to build settings" }
else if (impl.extraVerbose)
logger.warn { "Not a debug build, ignoring extra verbose setting" }
// std::unique_ptr<Profiler> profiler (GetPropertyInteger(AI_CONFIG_GLOB_MEASURE_TIME, 0) ? new Profiler() : NULL);
// if (profiler) { profiler ->
// BeginRegion("postprocess");
// }
rootProcess.executeOnScene(this)
// if (profiler) { profiler ->
// EndRegion("postprocess")
// }
// If the extra verbose mode is active, execute the ValidateDataStructureStep again - after each step
if (impl.extraVerbose || requestValidation) {
logger.debug { "Verbose Import: revalidating data structures" }
ValidateDSProcess().executeOnScene(this)
if (impl.scene == null)
logger.error { "Verbose Import: failed to revalidate data structures" }
}
logger.info { "Leaving customized post processing pipeline" }
return impl.scene
}
/** Frees the current scene.
*
* The function does nothing if no scene has previously been read via readFile(). freeScene() is called
* automatically by the destructor and readFile() itself. */
fun freeScene() {
impl.scene = null
impl.errorString = ""
}
/** Returns an error description of an error that occurred in ReadFile().
*
* Returns an empty string if no error occurred.
* @return A description of the last error, an empty string if no error occurred. The string is never null.
*
* @note The returned function remains valid until one of the following methods is called: readFile(),
* freeScene(). */
val errorString get() = impl.errorString
/** Returns the scene loaded by the last successful call to readFile()
*
* @return Current scene or null if there is currently no scene loaded */
val scene get() = impl.scene
/** Returns the scene loaded by the last successful call to readFile() and releases the scene from the ownership of
* the Importer instance. The application is now responsible for deleting the scene. Any further calls to `scene`
* or `orphanedScene` will return null - until a new scene has been loaded via readFile().
*
* @return Current scene or null if there is currently no scene loaded
* @note Use this method with maximal caution, and only if you have to.
* By design, AiScene's are exclusively maintained, allocated and deallocated by Assimp and no one else. The
* reasoning behind this is the golden rule that deallocations should always be done by the module that did the
* original allocation because heaps are not necessarily shared. `orphanedScene` enforces you to delete the
* returned scene by yourself, but this will only be fine if and only if you're using the same heap as assimp.
* On Windows, it's typically fine provided everything is linked against the multithreaded-dll version of the
* runtime library.
* It will work as well for static linkage with Assimp. */
val orphanedScene: AiScene?
get() {
val s = impl.scene
impl.scene = null
impl.errorString = "" /* reset error string */
return s
}
/** Returns whether a given file extension is supported by ASSIMP.
*
* @param szExtension Extension to be checked.
* Must include a trailing dot '.'. Example: ".3ds", ".md3". Cases-insensitive.
* @return true if the extension is supported, false otherwise */
fun isExtensionSupported(szExtension: String) = null != getImporter(szExtension)
/** Get a full list of all file extensions supported by ASSIMP.
*
* If a file extension is contained in the list this does of course not mean that ASSIMP is able to load all files
* with this extension --- it simply means there is an importer loaded which claims to handle files with this
* file extension.
* @return String containing the extension list.
* Format of the list: "*.3ds;*.obj;*.dae". This is useful for use with the WinAPI call GetOpenFileName(Ex). */
val extensionList get() = impl.importer.joinToString("", "*.", ";").substringBeforeLast(';')
/** Get the number of importers currently registered with Assimp. */
val importerCount get() = impl.importer.size
/** Get meta data for the importer corresponding to a specific index..
*
* @param index Index to query, must be within [0, importerCount)
* @return Importer meta data structure, null if the index does not exist or if the importer doesn't offer meta
* information (importers may do this at the cost of being hated by their peers). TODO JVM DOESNT ALLOW THIS */
fun getImporterInfo(index: Int) = impl.importer[index].info
/** Find the importer corresponding to a specific index.
*
* @param index Index to query, must be within [0, importerCount)
* @return Importer instance. null if the index does not exist. */
fun getImporter(index: Int) = impl.importer.getOrNull(index)
/** Find the importer corresponding to a specific file extension.
*
* This is quite similar to `isExtensionSupported` except a BaseImporter instance is returned.
* @param szExtension Extension to check for. The following formats are recognized (BAH being the file extension):
* "BAH" (comparison is case-insensitive), ".bah", "*.bah" (wild card and dot characters at the beginning of the
* extension are skipped).
* @return null if no importer is found*/
fun getImporter(szExtension: String) = getImporter(getImporterIndex(szExtension))
/** Find the importer index corresponding to a specific file extension.
*
* @param szExtension Extension to check for. The following formats are recognized (BAH being the file extension):
* "BAH" (comparison is case-insensitive), ".bah", "*.bah" (wild card and dot characters at the beginning of the
* extension are skipped).
* @return -1 if no importer is found */
fun getImporterIndex(szExtension: String): Int {
assert(szExtension.isNotEmpty())
// skip over wildcard and dot characters at string head --
var p = 0
while (szExtension[p] == '*' || szExtension[p] == '.') ++p
var ext = szExtension.substring(p)
if (ext.isEmpty()) return -1
ext = ext.toLowerCase()
impl.importer.forEach { i ->
i.extensionList.forEach {
if (ext == it) return impl.importer.indexOf(i)
}
}
return -1
}
/** Returns the storage allocated by ASSIMP to hold the scene data in memory.
*
* This refers to the currently loaded file, see readFile().
* @param in Data structure to be filled.
* @note The returned memory statistics refer to the actual size of the use data of the AiScene. Heap-related
* overhead is (naturally) not included.*/
val memoryRequirements: AiMemoryInfo
get() {
val mem = AiMemoryInfo()
val scene = impl.scene ?: return mem
// return if we have no scene loaded
mem.total = AiScene.size
// add all meshes
repeat(scene.numMeshes) { i ->
mem.meshes += AiMesh.size
if (scene.meshes[i].hasPositions)
mem.meshes += AiVector3D.size * scene.meshes[i].numVertices
if (scene.meshes[i].hasNormals)
mem.meshes += AiVector3D.size * scene.meshes[i].numVertices
if (scene.meshes[i].hasTangentsAndBitangents)
mem.meshes += AiVector3D.size * scene.meshes[i].numVertices * 2
for (a in 0 until AI_MAX_NUMBER_OF_COLOR_SETS)
if (scene.meshes[i].hasVertexColors(a))
mem.meshes += AiColor4D.size * scene.meshes[i].numVertices
else break
for (a in 0 until AI_MAX_NUMBER_OF_TEXTURECOORDS)
if (scene.meshes[i].hasTextureCoords(a))
mem.meshes += AiVector3D.size * scene.meshes[i].numVertices
else break
if (scene.meshes[i].hasBones) {
for (p in 0 until scene.meshes[i].numBones) {
mem.meshes += AiBone.size
mem.meshes += scene.meshes[i].bones[p].numWeights * AiVertexWeight.size
}
}
mem.meshes += (3 * Int.BYTES) * scene.meshes[i].numFaces
}
mem.total += mem.meshes
// add all embedded textures
for (i in 0 until scene.numTextures) {
val pc = scene.textures.values.elementAt(i)
mem.textures += AiTexture.size
mem.textures += with(pc.extent()) { if (y != 0) 4 * y * x else x }
}
mem.total += mem.textures
// add all animations
for (i in 0 until scene.numAnimations) {
val pc = scene.animations[i]
mem.animations += AiAnimation.size
// add all bone anims
for (a in 0 until pc.numChannels) {
val pc2 = pc.channels[i]!!
mem.animations += AiNodeAnim.size
mem.animations += pc2.numPositionKeys * AiVectorKey.size
mem.animations += pc2.numScalingKeys * AiVectorKey.size
mem.animations += pc2.numRotationKeys * AiQuatKey.size
}
}
mem.total += mem.animations
// add all cameras and all lights
mem.cameras = AiCamera.size * scene.numCameras
mem.total += mem.cameras
mem.lights = AiLight.size * scene.numLights
mem.total += mem.lights
// add all nodes
addNodeWeight(mem::nodes, scene.rootNode)
mem.total += mem.nodes
// add all materials
for (i in 0 until scene.numMaterials)
mem.materials += AiMaterial.size
mem.total += mem.materials
return mem
}
/** Enables "extra verbose" mode.
*
* 'Extra verbose' means the data structure is validated after *every* single post processing step to make sure
* everyone modifies the data structure in a well-defined manner. This is a debug feature and not intended for
* use in production environments. */
fun setExtraVerbose(verbose: Boolean) {
impl.extraVerbose = verbose
}
private fun writeLogOpening(file: String) {
logger.info { "Load $file" }
/* print a full version dump. This is nice because we don't need to ask the authors of incoming bug reports for
the library version they're using - a log dump is sufficient. */
val flags = compileFlags
logger.debug {
val message = "Assimp $versionMajor.$versionMinor.$versionRevision"
if (ASSIMP.DEBUG) "$message debug" else message
}
}
private fun _validateFlags(flags: Int) = when {
flags has Pps.GenSmoothNormals && flags has Pps.GenNormals -> {
logger.error { "AiProcess_GenSmoothNormals and AiProcess_GenNormals are incompatible" }
false
}
flags has Pps.OptimizeGraph && flags has Pps.PreTransformVertices -> {
logger.error { "AiProcess_OptimizeGraph and AiProcess_PreTransformVertices are incompatible" }
false
}
else -> true
}
/** Get the memory requirements of a single node */
private fun addNodeWeight(scene: KMutableProperty0<Int>, node: AiNode) {
scene.set(scene() + AiNode.size)
scene.set(scene() + Int.BYTES * node.numMeshes)
for (i in 0 until node.numChildren)
addNodeWeight(scene, node.children[i])
}
companion object {
/** The upper limit for hints. */
val MaxLenHint = 200
}
}
| mit | ebf69b29a45695a3bcb48403806aa8ea | 47.843284 | 126 | 0.640973 | 4.710327 | false | false | false | false |
StepicOrg/stepic-android | app/src/main/java/org/stepic/droid/util/FragmentManagerExtensions.kt | 2 | 2619 | package org.stepic.droid.util
import androidx.fragment.app.FragmentManager
import androidx.fragment.app.FragmentTransaction
/**
* Run [body] in a [FragmentTransaction] which is automatically committed if it completes without
* exception.
*
* The transaction will be completed by calling [FragmentTransaction.commit] unless [allowStateLoss]
* is set to `true` in which case [FragmentTransaction.commitAllowingStateLoss] will be used.
*/
inline fun FragmentManager.commit(
allowStateLoss: Boolean = false,
body: FragmentTransaction.() -> Unit
) {
val transaction = beginTransaction()
transaction.body()
if (allowStateLoss) {
transaction.commitAllowingStateLoss()
} else {
transaction.commit()
}
}
/**
* Run [body] in a [FragmentTransaction] which is automatically committed if it completes without
* exception.
*
* The transaction will be completed by calling [FragmentTransaction.commitNow] unless
* [allowStateLoss] is set to `true` in which case [FragmentTransaction.commitNowAllowingStateLoss]
* will be used.
*/
inline fun FragmentManager.commitNow(
allowStateLoss: Boolean = false,
body: FragmentTransaction.() -> Unit
) {
val transaction = beginTransaction()
transaction.body()
if (allowStateLoss) {
transaction.commitNowAllowingStateLoss()
} else {
transaction.commitNow()
}
}
/**
* Run [body] in a [FragmentTransaction] which is automatically committed if it completes without
* exception.
*
* One of four commit functions will be used based on the values of `now` and `allowStateLoss`:
*
* | now | allowStateLoss | Method |
* | ----- | ---------------- | ------------------------------ |
* | false | false | commit() |
* | false | true | commitAllowingStateLoss() |
* | true | false | commitNow() |
* | true | true | commitNowAllowingStateLoss() |
*/
@Deprecated("Use commit { .. } or commitNow { .. } extensions")
inline fun FragmentManager.transaction(
now: Boolean = false,
allowStateLoss: Boolean = false,
body: FragmentTransaction.() -> Unit
) {
val transaction = beginTransaction()
transaction.body()
if (now) {
if (allowStateLoss) {
transaction.commitNowAllowingStateLoss()
} else {
transaction.commitNow()
}
} else {
if (allowStateLoss) {
transaction.commitAllowingStateLoss()
} else {
transaction.commit()
}
}
} | apache-2.0 | 5bf7a432e9c62b13db360a22a300cab3 | 32.164557 | 100 | 0.625048 | 4.877095 | false | false | false | false |
jiaminglu/kotlin-native | backend.native/tests/runtime/workers/worker2.kt | 1 | 1212 | import konan.worker.*
data class WorkerArgument(val intParam: Int, val stringParam: String)
data class WorkerResult(val intResult: Int, val stringResult: String)
fun main(args: Array<String>) {
val COUNT = 5
val workers = Array(COUNT, { _ -> startWorker()})
for (attempt in 1 .. 3) {
val futures = Array(workers.size, { workerIndex -> workers[workerIndex].schedule(TransferMode.CHECKED, {
WorkerArgument(workerIndex, "attempt $attempt") }) { input ->
var sum = 0
for (i in 0..input.intParam * 1000) {
sum += i
}
WorkerResult(sum, input.stringParam + " result")
}
})
val futureSet = futures.toSet()
var consumed = 0
while (consumed < futureSet.size) {
val ready = futureSet.waitForMultipleFutures(10000)
ready.forEach {
it.consume { result ->
if (result.stringResult != "attempt $attempt result") throw Error("Unexpected $result")
consumed++ }
}
}
}
workers.forEach {
it.requestTermination().consume { _ -> }
}
println("OK")
} | apache-2.0 | d4864250a769f5cc5c98cf817ca51059 | 33.657143 | 112 | 0.546205 | 4.43956 | false | false | false | false |
BloodWorkXGaming/ExNihiloCreatio | src/main/java/exnihilocreatio/compatibility/crafttweaker/Compost.kt | 1 | 1832 | package exnihilocreatio.compatibility.crafttweaker
import crafttweaker.IAction
import crafttweaker.annotations.ZenRegister
import crafttweaker.api.item.IIngredient
import crafttweaker.api.item.IItemStack
import crafttweaker.api.minecraft.CraftTweakerMC
import exnihilocreatio.compatibility.crafttweaker.prefab.ENCRemoveAll
import exnihilocreatio.registries.manager.ExNihiloRegistryManager
import exnihilocreatio.registries.types.Compostable
import exnihilocreatio.texturing.Color
import exnihilocreatio.util.BlockInfo
import net.minecraft.item.ItemStack
import net.minecraft.item.crafting.Ingredient
import stanhebben.zenscript.annotations.ZenClass
import stanhebben.zenscript.annotations.ZenMethod
@ZenClass("mods.exnihilocreatio.Compost")
@ZenRegister
object Compost {
@ZenMethod
@JvmStatic
fun removeAll() {
CrTIntegration.removeActions += ENCRemoveAll(ExNihiloRegistryManager.COMPOST_REGISTRY, "Compost")
}
@ZenMethod
@JvmStatic
fun addRecipe(input: IIngredient, value: Float, color: String, block: IItemStack) {
CrTIntegration.addActions += AddRecipe(input, value, color, block)
}
private class AddRecipe(
input: IIngredient,
private val value: Float,
color: String,
block: IItemStack
) : IAction {
private val input: Ingredient = CraftTweakerMC.getIngredient(input)
private val color: Color = Color(color)
private val block: BlockInfo = BlockInfo(block.internal as ItemStack)
override fun apply() {
ExNihiloRegistryManager.COMPOST_REGISTRY.register(input, Compostable(value, color, block))
}
override fun describe() = "Adding Compost recipe for ${input.matchingStacks.joinToString(prefix = "[", postfix = "]")} with value $value and Color $color"
}
}
| mit | 65611be27fadc85dcd90f58696b08772 | 35.64 | 162 | 0.75 | 4.479218 | false | false | false | false |
kazhida/kotos2d | src/jp/kazhida/kotos2d/Kotos2dTextInputWrapper.kt | 1 | 2682 | package jp.kazhida.kotos2d
import android.text.TextWatcher
import android.widget.TextView.OnEditorActionListener
import android.text.Editable
import android.widget.TextView
import android.view.KeyEvent
import android.content.Context
import android.view.inputmethod.InputMethodManager
import android.view.inputmethod.EditorInfo
/**
*
* Created by kazhida on 2013/07/29.
*/
public class Kotos2dTextInputWrapper(val surfaceView: Kotos2dGLSurfaceView): TextWatcher, OnEditorActionListener {
class object {
private val TAG : String? = javaClass<Kotos2dTextInputWrapper>().getSimpleName()
}
private val isFullScreenEdit: Boolean
get() {
val textField: TextView? = surfaceView.editText
val imm : InputMethodManager? = textField?.getContext()?.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager?
return imm?.isFullscreenMode()!!
}
private var text: String? = null
private var originText: String? = null
public fun setOriginText(pOriginText : String?) : Unit {
this.originText = pOriginText
}
public override fun afterTextChanged(s: Editable?) {
if (! isFullScreenEdit && s != null) {
var nModified : Int = s.length() - (this.text?.length())!!
if (nModified > 0) {
val insertText : String? = s.subSequence((text?.length())!!, s.length()).toString()
surfaceView.insertText(insertText)
} else {
while (nModified < 0) {
surfaceView.deleteBackward()
++nModified
}
}
text = s.toString()
}
}
public override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
text = s?.toString()
}
public override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {}
public override fun onEditorAction(v: TextView?, actionId: Int, event: KeyEvent?): Boolean {
if (surfaceView.editText == v && isFullScreenEdit) {
var i : Int = originText?.length() ?: 0
while (i > 0) {
surfaceView.deleteBackward()
i--
}
var s : String = v?.getText()?.toString()!!
if ((s.compareTo("")) == 0) {
s = "\n"
}
if ('\n' != s.charAt((s.length()) - 1)) {
s += '\n'
}
val insertText : String = s
surfaceView.insertText(insertText)
}
if (actionId == EditorInfo.IME_ACTION_DONE) {
surfaceView.requestFocus()
}
return false
}
} | mit | a47c121c8c01d97c8fffeba1a5309efe | 30.564706 | 134 | 0.58874 | 4.592466 | false | false | false | false |
andrewoma/kwery | mapper/src/test/kotlin/com/github/andrewoma/kwery/mappertest/example/DaoListenerPreCommitTest.kt | 1 | 6839 | /*
* Copyright (c) 2015 Andrew O'Malley
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.github.andrewoma.kwery.mappertest.example
import com.github.andrewoma.kwery.core.Session
import com.github.andrewoma.kwery.mapper.Table
import com.github.andrewoma.kwery.mapper.listener.*
import com.github.andrewoma.kwery.mappertest.AbstractSessionTest
import com.github.andrewoma.kwery.mappertest.example.test.initialiseFilmSchema
import org.junit.Test
import kotlin.properties.Delegates
import kotlin.test.assertEquals
/**
* Demonstrates a pre commit listener the saves audit records of all changes
*/
class DaoListenerPreCommitTest : AbstractSessionTest() {
var dao: ActorDao by Delegates.notNull()
var nextTransactionId = 0
override var startTransactionByDefault = false
override fun afterSessionSetup() {
initialise("filmSchema") { initialiseFilmSchema(it) }
initialise("audit") {
it.update("""
create table audit(
id identity,
transaction numeric(10),
table_name varchar(255),
key numeric(10),
operation varchar(255),
changes varchar(4000)
)
""")
}
super.afterSessionSetup()
dao = ActorDao(session, FilmActorDao(session))
dao.addListener(AuditHandler())
session.update("delete from actor where actor_id > -1000")
session.update("delete from audit")
}
@Test fun `Audit rows should be created for each transaction`() {
val transactionId = nextTransactionId + 1
val (bruce, brandon) = session.transaction {
val bruce = dao.insert(Actor(Name("Bruce", "Lee")))
val brandon = dao.insert(Actor(Name("Brandon", "Lee")))
dao.update(brandon, brandon.copy(name = (Name("Tex", "Lee"))))
bruce to brandon
}
// Generates:
// Audit(transactionId=1, table=actor, id=0, operation=Insert, changes=last_name: 'Lee', first_name: 'Bruce', last_update: '2015-02-26 05:44:49.796')
// Audit(transactionId=1, table=actor, id=1, operation=Insert, changes=last_name: 'Lee', first_name: 'Brandon', last_update: '2015-02-26 05:44:49.796')
// Audit(transactionId=1, table=actor, id=1, operation=Update, changes=first_name: 'Brandon' -> 'Tex', last_update: '2015-02-26 05:44:49.796' -> '2015-02-26 05:44:49.938')
session.transaction {
dao.delete(bruce.id)
}
// Generates:
// Audit(transactionId=2, table=actor, id=0, operation=Delete, changes=)
// This should have no effect as audits will be rolled back in the transaction too
session.transaction {
session.currentTransaction?.rollbackOnly = true
dao.delete(brandon.id)
}
val audits = session.select("select transaction, count(*) as \"count\" from audit group by transaction") { row ->
row.int("transaction") to row.int("count")
}.toMap()
assertEquals(2, audits.size)
assertEquals(6, audits[transactionId])
assertEquals(1, audits[transactionId + 1])
}
data class Audit(val transactionId: Int, val table: String, val id: Int, val operation: String, val changes: String)
inner class AuditHandler : DeferredListener(false) {
override fun onCommit(committed: Boolean, events: List<Event>) {
println("AuditHandler invoked")
val transactionId = ++nextTransactionId
val audits = events.map { event ->
@Suppress("UNCHECKED_CAST") // TODO ... grok projections, why is casting needed?
val table = event.table as Table<Any, Any>
val operation = event::class.java.simpleName.replace("Event$".toRegex(), "")
Audit(transactionId, event.table.name, event.id as Int, operation, calculateChanges(event, session, table))
}
println(audits.joinToString("\n"))
saveAudits(audits, session)
}
private fun calculateChanges(event: Event, session: Session, table: Table<Any, Any>) = when (event) {
is InsertEvent -> {
table.objectMap(session, event.value, table.dataColumns).entries.map {
"${it.key}: ${session.dialect.bind(it.value!!, -1)}"
}.joinToString(", ")
}
is UpdateEvent -> {
val old = table.objectMap(session, event.old!!, table.dataColumns)
val new = table.objectMap(session, event.new, table.dataColumns)
old.mapValues { it.value to new[it.key] }.filter { it.value.first != it.value.second }.map {
"${it.key}: ${session.dialect.bind(it.value.first!!, -1)} -> ${session.dialect.bind(it.value.second!!, -1)}"
}.joinToString(", ")
}
is DeleteEvent -> ""
is PreInsertEvent -> ""
is PreUpdateEvent -> ""
else -> throw UnsupportedOperationException("Unknown event: $event")
}
private fun saveAudits(audits: List<Audit>, session: Session) {
val insert = """
insert into audit(transaction, table_name, key, operation, changes)
values (:transaction, :table_name, :key, :operation, :changes)
"""
val params = audits.map {
mapOf("transaction" to it.transactionId,
"table_name" to it.table,
"key" to it.id,
"operation" to it.operation,
"changes" to it.changes)
}
session.batchUpdate(insert, params)
}
}
}
| mit | 6e84580db7d7497e132dbcebce4ff44f | 43.409091 | 181 | 0.616464 | 4.389602 | false | true | false | false |
Tait4198/hi_pixiv | app/src/main/java/info/hzvtc/hipixiv/vm/MainViewModel.kt | 1 | 18990 | package info.hzvtc.hipixiv.vm
import android.databinding.DataBindingUtil
import android.support.design.widget.TabLayout
import android.support.v4.app.Fragment
import android.support.v4.content.ContextCompat
import android.support.v7.widget.LinearLayoutManager
import android.util.Log
import android.view.View
import android.widget.AdapterView
import android.widget.ArrayAdapter
import com.afollestad.materialdialogs.MaterialDialog
import info.hzvtc.hipixiv.R
import info.hzvtc.hipixiv.adapter.BookmarkTagAdapter
import info.hzvtc.hipixiv.adapter.IllustAdapter
import info.hzvtc.hipixiv.adapter.SimplePagerAdapter
import info.hzvtc.hipixiv.adapter.events.TagItemClick
import info.hzvtc.hipixiv.data.Account
import info.hzvtc.hipixiv.data.UserPreferences
import info.hzvtc.hipixiv.data.ViewPagerBundle
import info.hzvtc.hipixiv.databinding.*
import info.hzvtc.hipixiv.net.ApiService
import info.hzvtc.hipixiv.util.AppUtil
import info.hzvtc.hipixiv.view.MainActivity
import info.hzvtc.hipixiv.view.fragment.*
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import javax.inject.Inject
class MainViewModel @Inject constructor(val userPreferences: UserPreferences,val account: Account,val apiService: ApiService)
: BaseViewModel<MainActivity,ActivityMainBinding>() {
private var nowIdentifier = -1
//关注者
//restricts position
private var restrictPos = 0
//collect restrict position
private var collectRestrictPos = 0
//item[3]-> all public private
private lateinit var restricts: Array<out String>
//标签过滤
//item[2]-> public private
private lateinit var doubleRestricts: Array<out String>
private var lastPosition = 0
private var isPublicPage = true
private var dialog : MaterialDialog? = null
private lateinit var obsToken : Observable<String>
private lateinit var newestFollowBundle : ViewPagerBundle<BaseFragment<*>>
private lateinit var newestNewBundle : ViewPagerBundle<BaseFragment<*>>
private lateinit var userPageBundle : ViewPagerBundle<BaseFragment<*>>
private lateinit var pixivisionPageBundle : ViewPagerBundle<BaseFragment<*>>
private lateinit var homeIllustFragment : IllustFragment
private lateinit var homeMangaFragment : IllustFragment
private lateinit var followVpFragment : ViewPagerFragment
private lateinit var newVpFragment : ViewPagerFragment
private lateinit var pixivisionVpFragment : ViewPagerFragment
private lateinit var myPixivFragment : IllustFragment
private lateinit var collectFragment : IllustFragment
private lateinit var historyFragment : IllustFragment
private lateinit var userVpFragment : ViewPagerFragment
override fun initViewModel() {
obsToken = account.obsToken(mView)
restricts = mView.resources.getStringArray(R.array.restrict_parameters)
doubleRestricts = mView.resources.getStringArray(R.array.double_restrict_parameters)
//newest -> follow -> bundle
newestFollowBundle = object : ViewPagerBundle<BaseFragment<*>>() {
init {
titles = mView.resources.getStringArray(R.array.newest_follow_tab)
pagers = arrayOf(
IllustLazyFragment(obsToken.flatMap({ token -> apiService.getFollowIllusts(token,restricts[0])}),account,IllustAdapter.Type.ILLUST),
UserLazyFragment(obsToken.flatMap({ token -> apiService.getUserRecommended(token)}),account))
}
override fun fabClick() {
when(nowPosition) {
0 -> {
showSingleFilterDialog(mView.resources.getStringArray(R.array.newest_follow_illust_items),object : Action{
override fun doAction() {
(pagers[0] as IllustLazyFragment).viewModel.getData(obsToken.
flatMap({token -> apiService.getFollowIllusts(token,restricts[restrictPos])}))
}
})
}
}
}
override fun fabShow(position: Int) {
super.fabShow(position)
if(position != 1)
mView.setFabVisible(true,true)
else
mView.setFabVisible(false,false)
}
}
//newest -> new -> bundle
newestNewBundle = object : ViewPagerBundle<BaseFragment<*>>(){
init {
titles = mView.resources.getStringArray(R.array.newest_new_tab)
pagers = arrayOf(
IllustLazyFragment(obsToken.flatMap({ token -> apiService.getNewIllust(token,"illust")}),account,IllustAdapter.Type.ILLUST),
IllustLazyFragment(obsToken.flatMap({ token -> apiService.getNewIllust(token,"manga")}),account,IllustAdapter.Type.MANGA))
}
}
//user
userPageBundle = object : ViewPagerBundle<BaseFragment<*>>(){
init {
titles = mView.resources.getStringArray(R.array.user_tab)
pagers = arrayOf(
UserLazyFragment(obsToken.flatMap({ token ->
apiService.getUserFollowing(token,userPreferences.id?:0,doubleRestricts[0])}),account),
UserLazyFragment(obsToken.flatMap({ token ->
apiService.getUserFollower(token,userPreferences.id?:0)}),account),
UserLazyFragment(obsToken.flatMap({ token ->
apiService.getUserMyPixiv(token,userPreferences.id?:0)}),account)
)
}
override fun fabClick() {
super.fabClick()
when(nowPosition){
0 ->{
showSingleFilterDialog(mView.resources.getStringArray(R.array.filter_items),object : Action{
override fun doAction() {
(pagers[0] as UserLazyFragment).viewModel.getData(obsToken.
flatMap({token -> apiService.getUserFollowing(token,userPreferences.id?:0,doubleRestricts[restrictPos])}))
}
})
}
}
}
override fun fabShow(position: Int) {
super.fabShow(position)
if(position == 0)
mView.setFabVisible(true,true)
else
mView.setFabVisible(false,false)
}
}
//Pixivision
pixivisionPageBundle = object : ViewPagerBundle<BaseFragment<*>>(){
init {
titles = mView.resources.getStringArray(R.array.newest_new_tab)
pagers = arrayOf(
PixivisionLazyFragment(obsToken.flatMap({ token -> apiService.getPixivisionArticles(token,"illust")}),account),
PixivisionLazyFragment(obsToken.flatMap({ token -> apiService.getPixivisionArticles(token,"manga")}),account)
)
}
}
homeIllustFragment = IllustFragment(obsToken.flatMap({ token -> apiService.getRecommendedIllusts(token, true) }),account,IllustAdapter.Type.ILLUST)
homeMangaFragment = IllustFragment(obsToken.flatMap({ token -> apiService.getRecommendedMangaList(token, true) }),account,IllustAdapter.Type.MANGA)
followVpFragment = ViewPagerFragment(newestFollowBundle)
newVpFragment = ViewPagerFragment(newestNewBundle)
pixivisionVpFragment = ViewPagerFragment(pixivisionPageBundle)
myPixivFragment = IllustFragment(obsToken.flatMap({ token -> apiService.getMyPixivIllusts(token)}),account,IllustAdapter.Type.ILLUST)
collectFragment = IllustFragment(obsToken.flatMap({ token -> apiService
.getLikeIllust(token,userPreferences.id?:0,doubleRestricts[0])}),account,IllustAdapter.Type.ILLUST)
historyFragment = IllustFragment(obsToken.flatMap({ token -> apiService.getIllustBrowsingHistory(token)}),account,IllustAdapter.Type.ILLUST)
userVpFragment = ViewPagerFragment(userPageBundle)
}
fun switchPage(identifier : Int){
if(identifier != nowIdentifier){
nowIdentifier = identifier
userPreferences.pageIdentifier = identifier.toLong()
when(identifier){
//主页插画
MainActivity.Identifier.HOME_ILLUSTRATIONS.value -> {
replaceFragment(homeIllustFragment)
mView.setFabVisible(false,false)
}
//主页漫画
MainActivity.Identifier.HOME_MANGA.value -> {
replaceFragment(homeMangaFragment)
mView.setFabVisible(false,false)
}
//关注者
MainActivity.Identifier.NEWEST_FOLLOW.value -> {
replaceFragment(followVpFragment)
restrictPos = 0
mBind.fab.setImageDrawable(ContextCompat.getDrawable(mView,R.drawable.ic_filter))
mBind.fab.setOnClickListener({ newestFollowBundle.fabClick() })
mView.setFabVisible(true,true)
}
//最新
MainActivity.Identifier.NEWEST_NEW.value -> {
replaceFragment(newVpFragment)
mView.setFabVisible(false,false)
}
//Pixivision
MainActivity.Identifier.PIXIVISION.value ->{
replaceFragment(pixivisionVpFragment)
mView.setFabVisible(false,false)
}
//My Pixiv
MainActivity.Identifier.NEWEST_MY_PIXIV.value ->{
replaceFragment(myPixivFragment)
mView.setFabVisible(false,false)
}
//收集
MainActivity.Identifier.COLLECT.value ->{
replaceFragment(collectFragment)
lastPosition = 0
isPublicPage = true
dialog = null
mBind.fab.setImageDrawable(ContextCompat.getDrawable(mView,R.drawable.ic_filter))
mBind.fab.setOnClickListener({ showTagViewPagerDialog()})
mView.setFabVisible(true,true)
}
//浏览历史
MainActivity.Identifier.BROWSING_HISTORY.value ->{
replaceFragment(historyFragment)
mView.setFabVisible(false,false)
}
//用户
MainActivity.Identifier.USER.value ->{
replaceFragment(userVpFragment)
restrictPos = 0
mBind.fab.setImageDrawable(ContextCompat.getDrawable(mView,R.drawable.ic_filter))
mBind.fab.setOnClickListener({ userPageBundle.fabClick() })
mView.setFabVisible(true,true)
}
}
}
}
private fun replaceFragment(fragment : Fragment){
val transaction = mView.supportFragmentManager.beginTransaction()
transaction.replace(R.id.contentFrame,fragment)
transaction.addToBackStack(null)
transaction.commit()
}
private fun showSingleFilterDialog(items: Array<String>, action : Action){
val dialog = MaterialDialog.Builder(mView)
.title(getString(R.string.newest_follow_illust_name))
.customView(R.layout.dialog_single_filter, true)
.positiveText(getString(R.string.app_dialog_ok))
.negativeText(getString(R.string.app_dialog_cancel))
.onPositive({ _, _ -> action.doAction()})
.build()
val bind = DataBindingUtil.bind<DialogSingleFilterBinding>(dialog.customView!!)
bind?.restrict?.adapter = ArrayAdapter<String>(mView,android.R.layout.simple_list_item_1,items)
bind?.restrict?.setSelection(restrictPos)
bind?.restrict?.onItemSelectedListener = object : AdapterView.OnItemSelectedListener{
override fun onNothingSelected(parent: AdapterView<*>?) {
//
}
override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
restrictPos = position
}
}
dialog.show()
}
//标签过滤
private fun showTagViewPagerDialog(){
if(dialog == null){
dialog = MaterialDialog.Builder(mView)
.title(getString(R.string.collect_filter_name))
.negativeText(getString(R.string.app_dialog_cancel))
.customView(R.layout.dialog_view_pager, false)
.build()
val bind = DataBindingUtil.bind<DialogViewPagerBinding>(dialog?.customView!!)
val publicPage = DataBindingUtil.bind<FragmentListBinding>(View.inflate(mView,R.layout.fragment_list,null))
val privatePage = DataBindingUtil.bind<FragmentListBinding>(View.inflate(mView,R.layout.fragment_list,null))
val adapter = SimplePagerAdapter(arrayOf(publicPage!!.root,privatePage!!.root),
mView.resources.getStringArray(R.array.filter_items))
val publicPageAdapter = BookmarkTagAdapter(mView)
val privatePageAdapter = BookmarkTagAdapter(mView)
publicPage.recyclerView.adapter = publicPageAdapter
publicPage.recyclerView.layoutManager = LinearLayoutManager(mView)
publicPage.srLayout.setColorSchemeColors(ContextCompat.getColor(mView, R.color.primary))
publicPage.srLayout.setOnRefreshListener({ initPageData(publicPage,publicPageAdapter,true) })
privatePage.recyclerView.adapter = privatePageAdapter
privatePage.recyclerView.layoutManager = LinearLayoutManager(mView)
privatePage.srLayout.setColorSchemeColors(ContextCompat.getColor(mView, R.color.primary))
privatePage.srLayout.setOnRefreshListener({ initPageData(privatePage,privatePageAdapter,false) })
publicPageAdapter.setTagItemClick(object : TagItemClick {
override fun itemClick(position: Int,tag : String) {
if(!isPublicPage){
privatePageAdapter.updateLastPositionItem(lastPosition)
}else{
publicPageAdapter.updateLastPositionItem(lastPosition)
}
publicPageAdapter.updatePositionItem(position)
lastPosition = position
isPublicPage = true
when(position){
0 ->{
collectFragment.viewModel.getData(obsToken.flatMap({ token -> apiService
.getLikeIllust(token,userPreferences.id?:0,doubleRestricts[0])}))
}
1 ->{
collectFragment.viewModel.getData(obsToken.flatMap({ token -> apiService
.getLikeIllust(token,userPreferences.id?:0,doubleRestricts[0],"未分類")}))
}
else->{
collectFragment.viewModel.getData(obsToken.flatMap({ token -> apiService
.getLikeIllust(token,userPreferences.id?:0,doubleRestricts[0],tag)}))
}
}
dialog?.hide()
}
})
privatePageAdapter.setTagItemClick(object : TagItemClick {
override fun itemClick(position: Int,tag : String) {
if(isPublicPage){
publicPageAdapter.updateLastPositionItem(lastPosition)
}else {
privatePageAdapter.updateLastPositionItem(lastPosition)
}
privatePageAdapter.updatePositionItem(position)
when(position){
0 ->{
collectFragment.viewModel.getData(obsToken.flatMap({ token -> apiService
.getLikeIllust(token,userPreferences.id?:0,doubleRestricts[1])}))
}
1 ->{
collectFragment.viewModel.getData(obsToken.flatMap({ token -> apiService
.getLikeIllust(token,userPreferences.id?:0,doubleRestricts[1],"未分類")}))
}
else->{
collectFragment.viewModel.getData(obsToken.flatMap({ token -> apiService
.getLikeIllust(token,userPreferences.id?:0,doubleRestricts[1],tag)}))
}
}
lastPosition = position
isPublicPage = false
dialog?.hide()
}
})
bind?.viewPager?.adapter = adapter
bind?.viewPager?.currentItem = collectRestrictPos
bind?.tab?.setupWithViewPager(bind.viewPager)
bind?.tab?.tabMode = TabLayout.MODE_FIXED
initPageData(publicPage,publicPageAdapter,true)
initPageData(privatePage,privatePageAdapter,false)
}
dialog?.show()
}
//加载标签选择页面数据
private fun initPageData(page : FragmentListBinding,pageAdapter : BookmarkTagAdapter?,isPublic : Boolean){
val restrict = if(isPublic) doubleRestricts[0] else doubleRestricts[1]
val mPos = if(isPublic){ if(isPublicPage) lastPosition else -1 }else{ if(isPublicPage) -1 else lastPosition }
val isNetConnected = AppUtil.isNetworkConnected(mView)
Observable.just(isNetConnected)
.filter({connected -> connected})
.observeOn(AndroidSchedulers.mainThread())
.doOnNext({ page.srLayout.isRefreshing = true})
.observeOn(Schedulers.io())
.flatMap({ account.obsToken(mView) })
.flatMap({
token -> apiService.getIllustBookmarkTags(token,userPreferences.id?:0,restrict)
})
.observeOn(AndroidSchedulers.mainThread())
.subscribe({
response -> pageAdapter?.initNewData(response,mPos)
},{
error -> Log.d("Error",error.printStackTrace().toString())
page.srLayout.isRefreshing = false
},{
if(!isNetConnected) pageAdapter?.initNewData(null,mPos)
page.srLayout.isRefreshing = false
})
}
interface Action{
fun doAction()
}
} | mit | 5bd599fabd50ef392bc3e95641ba0ea7 | 48.334204 | 156 | 0.594422 | 5.673874 | false | false | false | false |
michalfaber/android-drawer-template | app/src/main/kotlin/views/adapters/drawer/drawerViewHolders.kt | 1 | 1822 | package com.michalfaber.drawertemplate.views.adapters.drawer
import android.support.v7.widget.RecyclerView
import android.view.View
import android.widget.ImageView
import android.widget.TextView
import com.michalfaber.drawertemplate.R
import com.michalfaber.drawertemplate.views.adapters.AdapterItem
import com.michalfaber.drawertemplate.views.adapters.AdapterItemsSupervisor
class ViewHolderMedium(drawerItemView: View) : RecyclerView.ViewHolder(drawerItemView) {
val icon: ImageView = drawerItemView.findViewById(R.id.icon) as ImageView
val label: TextView = drawerItemView.findViewById(R.id.label) as TextView
}
class ViewHolderSmall(drawerItemView: View) : RecyclerView.ViewHolder(drawerItemView) {
val icon: ImageView = drawerItemView.findViewById(R.id.icon) as ImageView
val label: TextView = drawerItemView.findViewById(R.id.label) as TextView
}
class ViewHolderSeparator(drawerItemView: View) : RecyclerView.ViewHolder(drawerItemView)
class ViewHolderHeader(drawerItemView: View) : RecyclerView.ViewHolder(drawerItemView) {
val label: TextView = drawerItemView.findViewById(R.id.label) as TextView
}
class ViewHolderSpinner(drawerItemView: View, val supervisor: AdapterItemsSupervisor<AdapterItem>) : RecyclerView.ViewHolder(drawerItemView) {
val icon: ImageView = drawerItemView.findViewById(R.id.icon) as ImageView
val label: TextView = drawerItemView.findViewById(R.id.label) as TextView
val action: ImageView = drawerItemView.findViewById(R.id.action) as ImageView
}
class ViewHolderSpinnerItem(drawerItemView: View, val supervisor: AdapterItemsSupervisor<AdapterItem>) : RecyclerView.ViewHolder(drawerItemView) {
val icon: ImageView = drawerItemView.findViewById(R.id.icon) as ImageView
val label: TextView = drawerItemView.findViewById(R.id.label) as TextView
} | apache-2.0 | 3eac2f7e919eb69e39d6755350691043 | 49.638889 | 146 | 0.815587 | 4.577889 | false | false | false | false |
Heiner1/AndroidAPS | core/src/main/java/info/nightscout/androidaps/plugins/constraints/versionChecker/AllowedVersions.kt | 1 | 1497 | package info.nightscout.androidaps.plugins.constraints.versionChecker
import org.joda.time.LocalDate
import org.json.JSONArray
import org.json.JSONException
import org.json.JSONObject
class AllowedVersions {
fun findByApi(definition: String?, api: Int): JSONObject? {
if (definition == null) return null
try {
val array = JSONArray(definition)
for (i in 0 until array.length()) {
val record = array[i] as JSONObject
if (record.has("minAndroid") && record.has("maxAndroid"))
if (api in record.getInt("minAndroid")..record.getInt("maxAndroid")) return record
}
} catch (e: JSONException) {
}
return null
}
fun findByVersion(definition: String?, version: String): JSONObject? {
if (definition == null) return null
try {
val array = JSONArray(definition)
for (i in 0 until array.length()) {
val record = array[i] as JSONObject
if (record.has("endDate") && record.has("version"))
if (version == record.getString("version")) return record
}
} catch (e: JSONException) {
}
return null
}
fun endDateToMilliseconds(endDate: String): Long? {
try {
val dateTime = LocalDate.parse(endDate)
return dateTime.toDate().time
} catch (ignored: Exception) {
}
return null
}
} | agpl-3.0 | b4b66314aa724dc235ffe0b58624591b | 31.565217 | 102 | 0.574482 | 4.69279 | false | false | false | false |
timmutton/redex-plugin | src/main/kotlin/au/com/timmutton/redexplugin/DexFile.kt | 1 | 5058 | /*
* Copyright (C) 2015-2016 KeepSafe Software
*
* 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 au.com.timmutton.redexplugin
import com.android.dexdeps.DexData
import java.io.File
import java.io.RandomAccessFile
import java.util.*
import java.util.Collections.emptyList
import java.util.zip.ZipEntry
import java.util.zip.ZipException
import java.util.zip.ZipFile
/**
* A physical file and the {@link DexData} contained therein.
*
* A DexFile contains an open file, possibly a temp file. When consumers are
* finished with the DexFile, it should be cleaned up with
* {@link DexFile#dispose()}.
*/
class DexFile(val file: File, val isTemp: Boolean, val isInstantRun: Boolean = false) {
val data: DexData
val raf: RandomAccessFile = RandomAccessFile(file, "r")
init {
data = DexData(raf)
data.load()
}
fun dispose() {
raf.close()
if (isTemp) {
file.delete()
}
}
companion object {
/**
* Extracts a list of {@link DexFile} instances from the given file.
*
* DexFiles can be extracted either from an Android APK file, or from a raw
* {@code classes.dex} file.
*
* @param file the APK or dex file.
* @return a list of DexFile objects representing data in the given file.
*/
fun extractDexData(file: File?): List<DexFile> {
if (file == null || !file.exists()) {
return emptyList()
}
try {
return extractDexFromZip(file)
} catch (e: ZipException) {
// not a zip, no problem
}
return listOf(DexFile(file, false))
}
/**
* Attempts to unzip the file and extract all dex files inside of it.
*
* It is assumed that {@code file} is an APK file resulting from an Android
* build, containing one or more appropriately-named classes.dex files.
*
* @param file the APK file from which to extract dex data.
* @return a list of contained dex files.
* @throws ZipException if {@code file} is not a zip file.
*/
fun extractDexFromZip(file: File): List<DexFile> = ZipFile(file).use { zipfile ->
val entries = zipfile.entries().toList()
val mainDexFiles = entries.filter { it.name.matches(Regex("classes.*\\.dex")) }.map { entry ->
val temp = File.createTempFile("dexcount", ".dex")
temp.deleteOnExit()
zipfile.getInputStream(entry).use { input ->
IOUtil.drainToFile(input, temp)
}
DexFile(temp, true)
}.toMutableList()
mainDexFiles.addAll(extractIncrementalDexFiles(zipfile, entries))
return mainDexFiles
}
/**
* Attempts to extract dex files embedded in a nested instant-run.zip file
* produced by Android Studio 2.0. If present, such files are extracted to
* temporary files on disk and returned as a list. If not, an empty mutable
* list is returned.
*
* @param apk the APK file from which to extract dex data.
* @param zipEntries a list of ZipEntry objects inside of the APK.
* @return a list, possibly empty, of instant-run dex data.
*/
fun extractIncrementalDexFiles(apk: ZipFile, zipEntries: List<ZipEntry>): List<DexFile> {
val incremental = zipEntries.filter { (it.name == "instant-run.zip") }
if (incremental.size != 1) {
return emptyList()
}
val instantRunFile = File.createTempFile("instant-run", ".zip")
instantRunFile.deleteOnExit()
apk.getInputStream(incremental[0]).use { input ->
IOUtil.drainToFile(input, instantRunFile)
}
ZipFile(instantRunFile).use { instantRunZip ->
val entries = Collections.list(instantRunZip.entries())
val dexEntries = entries.filter { it.name.endsWith(".dex") }
return dexEntries.map { entry ->
val temp = File.createTempFile("dexcount", ".dex")
temp.deleteOnExit()
instantRunZip.getInputStream(entry).use { input ->
IOUtil.drainToFile(input, temp)
}
DexFile(temp, true, true)
}
}
}
}
}
| mit | cf9f61f34a34e0e865c62b05c29a6c94 | 34.125 | 106 | 0.589759 | 4.552655 | false | false | false | false |
square/wire | wire-library/wire-runtime/src/nativeMain/kotlin/com/squareup/wire/internal/-Platform.kt | 2 | 1581 | /*
* Copyright 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 com.squareup.wire.internal
import okio.IOException
actual interface Serializable
actual abstract class ObjectStreamException : IOException()
actual class ProtocolException actual constructor(host: String) : IOException(host)
@Suppress("NOTHING_TO_INLINE") // Syntactic sugar.
actual inline fun <T> MutableList<T>.toUnmodifiableList(): List<T> = this
@Suppress("NOTHING_TO_INLINE") // Syntactic sugar.
actual inline fun <K, V> MutableMap<K, V>.toUnmodifiableMap(): Map<K, V> = this
// TODO: Use code points to process each char.
actual fun camelCase(string: String, upperCamel: Boolean): String {
return buildString(string.length) {
var index = 0
var uppercase = upperCamel
while (index < string.length) {
var char = string[index]
index++
if (char == '_') {
uppercase = true
continue
}
if (uppercase) {
if (char in 'a'..'z') char += 'A' - 'a'
}
append(char)
uppercase = false
}
}
}
| apache-2.0 | 6bbb06e724e0e799eaca32cbd2f64799 | 28.830189 | 83 | 0.69007 | 4.033163 | false | false | false | false |
lordtao/android-tao-core | lib/src/main/java/ua/at/tsvetkov/files/FileDownloader.kt | 1 | 5787 | /**
* ****************************************************************************
* Copyright (c) 2014 Alexandr Tsvetkov.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Lesser General Public License
* which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/lgpl.html
*
*
* Contributors:
* Alexandr Tsvetkov - initial API and implementation
*
*
* Project:
* TAO Core
*
*
* License agreement:
*
*
* 1. This code is published AS IS. Author is not responsible for any damage that can be
* caused by any application that uses this code.
* 2. Author does not give a garantee, that this code is error free.
* 3. This code can be used in NON-COMMERCIAL applications AS IS without any special
* permission from author.
* 4. This code can be modified without any special permission from author IF AND ONLY IF
* this license agreement will remain unchanged.
* ****************************************************************************
*/
package ua.at.tsvetkov.files
import ua.at.tsvetkov.util.Log
import java.io.*
import java.net.HttpURLConnection
import java.net.URL
import java.net.URLEncoder
/**
* Methods for downloading files from the Internet
*
* @author A.Tsvetkov 2013 http://tsvetkov.at.ua mailto:[email protected]
*/
class FileDownloader {
abstract inner class CompleteListener {
abstract fun complete(fileName: String, result: Boolean)
}
companion object {
val TIMEOUT = 10000
val BUFFER = 8192
/**
* Returns the content length in bytes specified by the response header field content-length or -1 if this field is not set.
*
* @param url url path to file
* @return the value of the response header field content-length
*/
@JvmStatic
fun getFileLength(url: String): Int {
var conn: HttpURLConnection? = null
var length = 0
try {
conn = URL(url).openConnection() as HttpURLConnection
conn.setRequestProperty("keep-alive", "false")
conn.doInput = true
conn.connectTimeout = TIMEOUT
conn.connect()
length = conn.contentLength
} catch (e: Exception) {
Log.e(e)
} finally {
if (conn != null)
conn.disconnect()
}
return length
}
/**
* Async downloads a remote file and stores it locally.
*
* @param url Remote URL of the file to download
* @param pathAndFileName Local path with file name where to store the file
* @param rewrite If TRUE and file exist - rewrite the file. If FALSE and file exist and his length > 0 - not download and rewrite the
* file.
*/
@JvmStatic
fun download(url: String, pathAndFileName: String, rewrite: Boolean, listener: CompleteListener) {
Thread(Runnable {
val result = download(url, pathAndFileName, rewrite)
listener.complete(url, result)
}, "Download thread: $url").start()
}
/**
* Downloads a remote file and stores it locally.
*
* @param url Remote URL of the file to download. If the string contains spaces, they are replaced by "%20".
* @param pathAndFileName Local path with file name where to store the file
* @param rewrite If TRUE and file exist - rewrite the file. If FALSE and file exist and his length > 0 - not download and rewrite the file.
* @return true if success
*/
@JvmOverloads
@JvmStatic
fun download(url: String, pathAndFileName: String, rewrite: Boolean = true): Boolean {
var urlEnc: String? = null
var conn: HttpURLConnection? = null
val input: InputStream
var output: FileOutputStream? = null
try {
urlEnc = URLEncoder.encode(url, "UTF-8")
} catch (e: UnsupportedEncodingException) {
Log.e("Wrong url", e)
}
val f = File(pathAndFileName)
if (!rewrite && f.exists() && f.length() > 0) {
Log.w("File exist: $pathAndFileName")
return true
}
try {
conn = URL(urlEnc).openConnection() as HttpURLConnection
conn.setRequestProperty("keep-alive", "false")
conn.doInput = true
conn.connectTimeout = TIMEOUT
conn.connect()
val fileLength = conn.contentLength
if (fileLength == 0) {
Log.v("File is empty, length = 0 > $url")
}
input = conn.inputStream
output = FileOutputStream(pathAndFileName)
val buffer = ByteArray(BUFFER)
var bytesRead: Int
while (true) {
bytesRead = input.read(buffer)
if (bytesRead < 0) break
output.write(buffer, 0, bytesRead)
}
output.flush()
} catch (e: IOException) {
Log.w("Download error $url", e)
return false
} finally {
if (conn != null)
conn.disconnect()
try {
output!!.close()
} catch (e: IOException) {
Log.e("Error closing file > $pathAndFileName", e)
return false
}
}
return true
}
}
}
| gpl-3.0 | ba1b574ecd2088c40e3c0422efcf5c6d | 34.503067 | 156 | 0.539658 | 5.01039 | false | false | false | false |
k9mail/k-9 | app/storage/src/test/java/com/fsck/k9/storage/messages/FolderHelpers.kt | 2 | 3315 | package com.fsck.k9.storage.messages
import android.content.ContentValues
import android.database.sqlite.SQLiteDatabase
import com.fsck.k9.helper.getIntOrNull
import com.fsck.k9.helper.getLongOrNull
import com.fsck.k9.helper.getStringOrNull
import com.fsck.k9.helper.map
fun SQLiteDatabase.createFolder(
name: String = "irrelevant",
type: String = "regular",
serverId: String? = null,
isLocalOnly: Boolean = true,
integrate: Boolean = false,
inTopGroup: Boolean = false,
displayClass: String = "NO_CLASS",
syncClass: String? = "INHERITED",
notifyClass: String? = "INHERITED",
pushClass: String? = "SECOND_CLASS",
lastUpdated: Long = 0L,
unreadCount: Int = 0,
visibleLimit: Int = 25,
status: String? = null,
flaggedCount: Int = 0,
moreMessages: String = "unknown",
): Long {
val values = ContentValues().apply {
put("name", name)
put("type", type)
put("server_id", serverId)
put("local_only", isLocalOnly)
put("integrate", integrate)
put("top_group", inTopGroup)
put("display_class", displayClass)
put("poll_class", syncClass)
put("notify_class", notifyClass)
put("push_class", pushClass)
put("last_updated", lastUpdated)
put("unread_count", unreadCount)
put("visible_limit", visibleLimit)
put("status", status)
put("flagged_count", flaggedCount)
put("more_messages", moreMessages)
}
return insert("folders", null, values)
}
fun SQLiteDatabase.readFolders(): List<FolderEntry> {
val cursor = rawQuery("SELECT * FROM folders", null)
return cursor.use {
cursor.map {
FolderEntry(
id = cursor.getLongOrNull("id"),
name = cursor.getStringOrNull("name"),
type = cursor.getStringOrNull("type"),
serverId = cursor.getStringOrNull("server_id"),
isLocalOnly = cursor.getIntOrNull("local_only"),
integrate = cursor.getIntOrNull("integrate"),
inTopGroup = cursor.getIntOrNull("top_group"),
displayClass = cursor.getStringOrNull("display_class"),
syncClass = cursor.getStringOrNull("poll_class"),
notifyClass = cursor.getStringOrNull("notify_class"),
pushClass = cursor.getStringOrNull("push_class"),
lastUpdated = cursor.getLongOrNull("last_updated"),
unreadCount = cursor.getIntOrNull("unread_count"),
visibleLimit = cursor.getIntOrNull("visible_limit"),
status = cursor.getStringOrNull("status"),
flaggedCount = cursor.getIntOrNull("flagged_count"),
moreMessages = cursor.getStringOrNull("more_messages")
)
}
}
}
data class FolderEntry(
val id: Long?,
val name: String?,
val type: String?,
val serverId: String?,
val isLocalOnly: Int?,
val integrate: Int?,
val inTopGroup: Int?,
val displayClass: String?,
val syncClass: String?,
val notifyClass: String?,
val pushClass: String?,
val lastUpdated: Long?,
val unreadCount: Int?,
val visibleLimit: Int?,
val status: String?,
val flaggedCount: Int?,
val moreMessages: String?
)
| apache-2.0 | 3b0dd348b45cf26d803dc3ca7f299010 | 33.894737 | 71 | 0.618703 | 4.585062 | false | false | false | false |
Maccimo/intellij-community | plugins/git4idea/src/git4idea/pull/GitPullDialog.kt | 3 | 14624 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package git4idea.pull
import com.intellij.codeInsight.hint.HintUtil
import com.intellij.dvcs.DvcsUtil.sortRepositories
import com.intellij.ide.actions.RefreshAction
import com.intellij.ide.ui.laf.darcula.DarculaUIUtil.BW
import com.intellij.openapi.actionSystem.*
import com.intellij.openapi.components.service
import com.intellij.openapi.keymap.KeymapUtil
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.progress.Task.Backgroundable
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.ComboBox
import com.intellij.openapi.ui.DialogWrapper
import com.intellij.openapi.ui.ValidationInfo
import com.intellij.openapi.util.SystemInfo
import com.intellij.openapi.util.text.HtmlChunk
import com.intellij.openapi.util.text.HtmlChunk.Element.html
import com.intellij.openapi.vcs.VcsNotifier
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.ui.MutableCollectionComboBoxModel
import com.intellij.ui.SimpleListCellRenderer
import com.intellij.ui.components.DropDownLink
import com.intellij.util.ui.JBDimension
import com.intellij.util.ui.JBUI
import git4idea.GitNotificationIdsHolder.Companion.FETCH_ERROR
import git4idea.GitRemoteBranch
import git4idea.GitUtil
import git4idea.GitVcs
import git4idea.branch.GitBranchUtil
import git4idea.config.GitExecutableManager
import git4idea.config.GitPullSettings
import git4idea.config.GitVersionSpecialty.NO_VERIFY_SUPPORTED
import git4idea.fetch.GitFetchSupport
import git4idea.i18n.GitBundle
import git4idea.merge.GIT_REF_PROTOTYPE_VALUE
import git4idea.merge.createRepositoryField
import git4idea.merge.createSouthPanelWithOptionsDropDown
import git4idea.merge.dialog.*
import git4idea.merge.validateBranchExists
import git4idea.repo.GitRemote
import git4idea.repo.GitRepository
import git4idea.repo.GitRepositoryManager
import git4idea.ui.ComboBoxWithAutoCompletion
import net.miginfocom.layout.AC
import net.miginfocom.layout.CC
import net.miginfocom.layout.LC
import net.miginfocom.swing.MigLayout
import java.awt.Insets
import java.awt.event.ItemEvent
import java.awt.event.KeyEvent
import javax.swing.JComponent
import javax.swing.JPanel
import javax.swing.KeyStroke
import javax.swing.SwingConstants
class GitPullDialog(private val project: Project,
private val roots: List<VirtualFile>,
private val defaultRoot: VirtualFile) : DialogWrapper(project) {
val selectedOptions = mutableSetOf<GitPullOption>()
private val fetchSupport = project.service<GitFetchSupport>()
private val pullSettings = project.service<GitPullSettings>()
private val repositories = sortRepositories(GitRepositoryManager.getInstance(project).repositories)
private val branches = collectBranches().toMutableMap()
private val optionInfos = mutableMapOf<GitPullOption, OptionInfo<GitPullOption>>()
private val popupBuilder = createPopupBuilder()
private val repositoryField = createRepoField()
private val remoteField = createRemoteField()
private val branchField = createBranchField()
private val commandPanel = createCommandPanel()
private val optionsPanel = GitOptionsPanel(::optionChosen, ::getOptionInfo)
private val panel = createPanel()
private val isNoVerifySupported = NO_VERIFY_SUPPORTED.existsIn(GitExecutableManager.getInstance().getVersion(project))
init {
updateTitle()
setOKButtonText(GitBundle.message("pull.button"))
loadSettings()
updateRemotesField()
init()
updateUi()
}
override fun createCenterPanel() = panel
override fun getPreferredFocusedComponent() = branchField
override fun createSouthPanel() = createSouthPanelWithOptionsDropDown(super.createSouthPanel(), createOptionsDropDown())
override fun getHelpId() = "reference.VersionControl.Git.Pull"
override fun doValidateAll() = listOf(::validateRepositoryField, ::validateRemoteField, ::validateBranchField).mapNotNull { it() }
override fun doOKAction() {
try {
saveSettings()
}
finally {
super.doOKAction()
}
}
fun gitRoot() = getSelectedRepository()?.root ?: error("No selected repository found")
fun getSelectedRemote(): GitRemote = remoteField.item ?: error("No selected remote found")
fun getSelectedBranch(): GitRemoteBranch {
val repository = getSelectedRepository() ?: error("No selected repository found")
val remote = getSelectedRemote()
val branchName = "${remote.name}/${branchField.item}"
return repository.branches.findRemoteBranch(branchName)
?: error("Unable to find remote branch: $branchName")
}
fun isCommitAfterMerge() = GitPullOption.NO_COMMIT !in selectedOptions
private fun getRemote(): GitRemote? = remoteField.item
private fun loadSettings() {
selectedOptions += pullSettings.options
}
private fun saveSettings() {
pullSettings.options = selectedOptions
}
private fun collectBranches() = repositories.associateWith { repository -> getBranchesInRepo(repository) }
private fun getBranchesInRepo(repository: GitRepository) = repository.branches.remoteBranches
.sortedBy { branch -> branch.nameForRemoteOperations }
.groupBy { branch -> branch.remote }
private fun validateRepositoryField(): ValidationInfo? {
return if (getSelectedRepository() != null)
null
else
ValidationInfo(GitBundle.message("pull.repository.not.selected.error"), repositoryField)
}
private fun validateRemoteField(): ValidationInfo? {
return if (getRemote() != null)
null
else
ValidationInfo(GitBundle.message("pull.remote.not.selected"), remoteField)
}
private fun validateBranchField() = validateBranchExists(branchField, GitBundle.message("pull.branch.not.selected.error"))
private fun getSelectedRepository(): GitRepository? = repositoryField.item
private fun updateRemotesField() {
val repository = getSelectedRepository()
val model = remoteField.model as MutableCollectionComboBoxModel
model.update(repository?.remotes?.toList() ?: emptyList())
model.selectedItem = getCurrentOrDefaultRemote(repository)
}
private fun updateBranchesField() {
var branchToSelect = branchField.item
val repository = getSelectedRepository() ?: return
val remote = getRemote() ?: return
val branches = GitBranchUtil.sortBranchNames(getRemoteBranches(repository, remote))
val model = branchField.model as MutableCollectionComboBoxModel
model.update(branches)
if (branchToSelect == null || branchToSelect !in branches) {
branchToSelect = repository.currentBranch?.findTrackedBranch(repository)?.nameForRemoteOperations
?: branches.find { branch -> branch == repository.currentBranchName }
?: ""
}
if (branchToSelect.isEmpty()) {
startTrackingValidation()
}
branchField.selectedItem = branchToSelect
}
private fun getRemoteBranches(repository: GitRepository, remote: GitRemote): List<String> {
return branches[repository]?.get(remote)?.map { it.nameForRemoteOperations } ?: emptyList()
}
private fun getCurrentOrDefaultRemote(repository: GitRepository?): GitRemote? {
val remotes = repository?.remotes ?: return null
if (remotes.isEmpty()) {
return null
}
return GitUtil.getTrackInfoForCurrentBranch(repository)?.remote
?: GitUtil.getDefaultOrFirstRemote(remotes)
}
private fun optionChosen(option: GitPullOption) {
if (option !in selectedOptions) {
selectedOptions += option
}
else {
selectedOptions -= option
}
updateUi()
}
private fun performFetch() {
if (fetchSupport.isFetchRunning) {
return
}
val repository = getSelectedRepository()
val remote = getRemote()
if (repository == null || remote == null) {
VcsNotifier.getInstance(project).notifyError(FETCH_ERROR,
GitBundle.message("pull.fetch.failed.notification.title"),
GitBundle.message("pull.fetch.failed.notification.text"))
return
}
GitVcs.runInBackground(getFetchTask(repository, remote))
}
private fun getFetchTask(repository: GitRepository, remote: GitRemote) = object : Backgroundable(project,
GitBundle.message("fetching"),
true) {
override fun run(indicator: ProgressIndicator) {
fetchSupport.fetch(repository, remote)
}
override fun onSuccess() {
branches[repository] = getBranchesInRepo(repository)
if (getSelectedRepository() == repository && getRemote() == remote) {
updateBranchesField()
}
}
}
private fun createPopupBuilder() = GitOptionsPopupBuilder(
project,
GitBundle.message("pull.options.modify.popup.title"),
::getOptions, ::getOptionInfo, ::isOptionSelected, ::isOptionEnabled, ::optionChosen
)
private fun isOptionSelected(option: GitPullOption) = option in selectedOptions
private fun createOptionsDropDown() = DropDownLink(GitBundle.message("merge.options.modify")) {
popupBuilder.createPopup()
}.apply {
mnemonic = KeyEvent.VK_M
}
private fun getOptionInfo(option: GitPullOption) = optionInfos.computeIfAbsent(option) {
OptionInfo(option, option.option, option.description)
}
private fun getOptions(): List<GitPullOption> = GitPullOption.values().toMutableList().apply {
if (!isNoVerifySupported) {
remove(GitPullOption.NO_VERIFY)
}
}
private fun updateUi() {
optionsPanel.rerender(selectedOptions)
rerender()
}
private fun rerender() {
window.pack()
window.revalidate()
pack()
repaint()
}
private fun isOptionEnabled(option: GitPullOption) = selectedOptions.all { it.isOptionSuitable(option) }
private fun updateTitle() {
val currentBranchName = getSelectedRepository()?.currentBranchName
title = (if (currentBranchName.isNullOrEmpty())
GitBundle.message("pull.dialog.title")
else
GitBundle.message("pull.dialog.with.branch.title", currentBranchName))
}
private fun createPanel() = JPanel().apply {
layout = MigLayout(LC().insets("0").hideMode(3), AC().grow())
add(commandPanel, CC().growX())
add(optionsPanel, CC().newline().width("100%").alignY("top"))
}
private fun showRootField() = roots.size > 1
private fun createCommandPanel() = JPanel().apply {
val colConstraints = if (showRootField())
AC().grow(100f, 0, 3)
else
AC().grow(100f, 2)
layout = MigLayout(
LC()
.fillX()
.insets("0")
.gridGap("0", "0")
.noVisualPadding(),
colConstraints)
if (showRootField()) {
add(repositoryField,
CC()
.gapAfter("0")
.minWidth("${JBUI.scale(115)}px")
.growX())
}
add(createCmdLabel(),
CC()
.gapAfter("0")
.alignY("top")
.minWidth("${JBUI.scale(85)}px"))
add(remoteField,
CC()
.alignY("top")
.minWidth("${JBUI.scale(90)}px"))
add(branchField,
CC()
.alignY("top")
.minWidth("${JBUI.scale(250)}px")
.growX())
}
private fun createCmdLabel() = CmdLabel("git pull",
Insets(1, if (showRootField()) 0 else 1, 1, 0),
JBDimension(JBUI.scale(85), branchField.preferredSize.height, true))
private fun createRepoField() = createRepositoryField(repositories, defaultRoot).apply {
addActionListener {
updateTitle()
updateRemotesField()
}
}
private fun createRemoteField() = ComboBox<GitRemote>(MutableCollectionComboBoxModel()).apply {
isSwingPopup = false
renderer = SimpleListCellRenderer.create(
HtmlChunk.text(GitBundle.message("util.remote.renderer.none")).italic().wrapWith(html()).toString()
) { it.name }
setUI(FlatComboBoxUI(
outerInsets = Insets(BW.get(), 0, BW.get(), 0),
popupEmptyText = GitBundle.message("pull.branch.no.matching.remotes")))
item = getCurrentOrDefaultRemote(getSelectedRepository())
addItemListener { e ->
if (e.stateChange == ItemEvent.SELECTED) {
updateBranchesField()
}
}
}
private fun createBranchField() = ComboBoxWithAutoCompletion(MutableCollectionComboBoxModel(mutableListOf<String>()),
project).apply {
prototypeDisplayValue = GIT_REF_PROTOTYPE_VALUE
setPlaceholder(GitBundle.message("pull.branch.field.placeholder"))
object : RefreshAction() {
override fun actionPerformed(e: AnActionEvent) {
popup?.hide()
performFetch()
}
override fun update(e: AnActionEvent) {
e.presentation.isEnabled = true
}
}.registerCustomShortcutSet(getFetchActionShortcut(), this)
setUI(FlatComboBoxUI(
Insets(1, 0, 1, 1),
Insets(BW.get(), 0, BW.get(), BW.get()),
GitBundle.message("pull.branch.nothing.to.pull"),
this@GitPullDialog::createBranchFieldPopupComponent))
}
private fun createBranchFieldPopupComponent(content: JComponent) = JPanel().apply {
layout = MigLayout(LC().insets("0"))
add(content, CC().width("100%"))
val hintLabel = HintUtil.createAdComponent(
GitBundle.message("pull.dialog.fetch.shortcuts.hint", getFetchActionShortcutText()),
JBUI.CurrentTheme.BigPopup.advertiserBorder(),
SwingConstants.LEFT)
hintLabel.preferredSize = JBDimension.create(hintLabel.preferredSize, true)
.withHeight(17)
add(hintLabel, CC().newline().width("100%"))
}
private fun getFetchActionShortcut(): ShortcutSet {
val refreshActionShortcut = ActionManager.getInstance().getAction(IdeActions.ACTION_REFRESH).shortcutSet
if (refreshActionShortcut.shortcuts.isNotEmpty()) {
return refreshActionShortcut
}
else {
return FETCH_ACTION_SHORTCUT
}
}
private fun getFetchActionShortcutText() = KeymapUtil.getPreferredShortcutText(getFetchActionShortcut().shortcuts)
companion object {
private val FETCH_ACTION_SHORTCUT = if (SystemInfo.isMac)
CustomShortcutSet(KeyStroke.getKeyStroke(KeyEvent.VK_R, KeyEvent.META_DOWN_MASK))
else
CustomShortcutSet(KeyStroke.getKeyStroke(KeyEvent.VK_F5, KeyEvent.CTRL_DOWN_MASK))
}
} | apache-2.0 | fa5a4307be07488d30421a7f27f39a1b | 33.011628 | 132 | 0.702954 | 4.847199 | false | false | false | false |
JetBrains/ideavim | src/main/java/com/maddyhome/idea/vim/ui/ex/ExEditorKit.kt | 1 | 4175 | /*
* Copyright 2003-2022 The IdeaVim authors
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE.txt file or at
* https://opensource.org/licenses/MIT.
*/
package com.maddyhome.idea.vim.ui.ex
import com.intellij.openapi.diagnostic.debug
import com.intellij.openapi.diagnostic.logger
import com.maddyhome.idea.vim.KeyHandler
import com.maddyhome.idea.vim.helper.EditorDataContext
import com.maddyhome.idea.vim.newapi.vim
import org.jetbrains.annotations.NonNls
import java.awt.event.ActionEvent
import java.awt.event.KeyEvent
import javax.swing.Action
import javax.swing.KeyStroke
import javax.swing.text.DefaultEditorKit
import javax.swing.text.Document
import javax.swing.text.TextAction
object ExEditorKit : DefaultEditorKit() {
@NonNls
val CancelEntry: String = "cancel-entry"
@NonNls
val CompleteEntry: String = "complete-entry"
@NonNls
val EscapeChar: String = "escape"
@NonNls
val DeleteToCursor: String = "delete-to-cursor"
@NonNls
val ToggleInsertReplace: String = "toggle-insert"
@NonNls
val InsertRegister: String = "insert-register"
@NonNls
val HistoryUp: String = "history-up"
@NonNls
val HistoryDown: String = "history-down"
@NonNls
val HistoryUpFilter: String = "history-up-filter"
@NonNls
val HistoryDownFilter: String = "history-down-filter"
@NonNls
val StartDigraph: String = "start-digraph"
@NonNls
val StartLiteral: String = "start-literal"
private val logger = logger<ExEditorKit>()
/**
* Gets the MIME type of the data that this
* kit represents support for.
*
* @return the type
*/
@NonNls
override fun getContentType(): String {
return "text/ideavim"
}
/**
* Fetches the set of commands that can be used
* on a text component that is using a model and
* view produced by this kit.
*
* @return the set of actions
*/
override fun getActions(): Array<Action> {
val res = TextAction.augmentList(super.getActions(), exActions)
logger.debug { "res.length=${res.size}" }
return res
}
/**
* Creates an uninitialized text storage model
* that is appropriate for this type of editor.
*
* @return the model
*/
override fun createDefaultDocument(): Document {
return ExDocument()
}
private val exActions = arrayOf<Action>(
CancelEntryAction(),
CompleteEntryAction(),
EscapeCharAction(),
DeleteNextCharAction(),
DeletePreviousCharAction(),
DeletePreviousWordAction(),
DeleteToCursorAction(),
HistoryUpAction(),
HistoryDownAction(),
HistoryUpFilterAction(),
HistoryDownFilterAction(),
ToggleInsertReplaceAction(),
InsertRegisterAction()
)
class DefaultExKeyHandler : DefaultKeyTypedAction() {
override fun actionPerformed(e: ActionEvent) {
val target = getTextComponent(e) as ExTextField
val currentAction = target.currentAction
if (currentAction != null) {
currentAction.actionPerformed(e)
} else {
val key = convert(e)
if (key != null) {
val c = key.keyChar
if (c.code > 0) {
if (target.useHandleKeyFromEx) {
val entry = ExEntryPanel.getInstance().entry
val editor = entry.editor
KeyHandler.getInstance().handleKey(editor.vim, key, EditorDataContext.init(editor, entry.context).vim)
} else {
val event = ActionEvent(e.source, e.id, c.toString(), e.getWhen(), e.modifiers)
super.actionPerformed(event)
}
target.saveLastEntry()
}
} else {
super.actionPerformed(e)
target.saveLastEntry()
}
}
}
}
fun convert(event: ActionEvent): KeyStroke? {
val cmd = event.actionCommand
val mods = event.modifiers
if (cmd != null && cmd.isNotEmpty()) {
val ch = cmd[0]
if (ch < ' ') {
if (mods and ActionEvent.CTRL_MASK != 0) {
return KeyStroke.getKeyStroke(KeyEvent.VK_A + ch.code - 1, mods)
}
} else {
return KeyStroke.getKeyStroke(Character.valueOf(ch), mods)
}
}
return null
}
}
| mit | 461b0d71be0e8bb0ecd3d4549565be6c | 25.424051 | 116 | 0.663473 | 4.117357 | false | false | false | false |
ligi/PassAndroid | android/src/main/java/org/ligi/passandroid/model/comparator/PassByTimeComparator.kt | 1 | 1313 | package org.ligi.passandroid.model.comparator
import org.ligi.passandroid.model.pass.Pass
import org.threeten.bp.ZonedDateTime
import java.util.*
open class PassByTimeComparator : Comparator<Pass> {
override fun compare(lhs: Pass, rhs: Pass): Int {
return calculateCompareForNullValues(lhs, rhs) { leftDate: ZonedDateTime, rightDate: ZonedDateTime ->
return@calculateCompareForNullValues leftDate.compareTo(rightDate)
}
}
protected fun calculateCompareForNullValues(lhs: Pass, rhs: Pass, foo: (leftDate: ZonedDateTime, rightDate: ZonedDateTime) -> Int): Int {
val leftDate = extractPassDate(lhs)
val rightDate = extractPassDate(rhs)
if (leftDate == rightDate) {
return 0
}
if (leftDate == null) {
return 1
}
if (rightDate == null) {
return -1
}
return foo(leftDate, rightDate)
}
private fun extractPassDate(pass: Pass): ZonedDateTime? {
if (pass.calendarTimespan != null && pass.calendarTimespan!!.from != null) {
return pass.calendarTimespan!!.from
}
if (pass.validTimespans != null && pass.validTimespans!!.isNotEmpty()) {
return pass.validTimespans!![0].from
}
return null
}
}
| gpl-3.0 | a852e15bc546812bd7467be72ddd3eb9 | 29.534884 | 141 | 0.630617 | 4.319079 | false | false | false | false |
wordpress-mobile/WordPress-Android | WordPress/src/main/java/org/wordpress/android/ui/pages/SearchListFragment.kt | 1 | 3685 | package org.wordpress.android.ui.pages
import android.os.Bundle
import android.os.Parcelable
import android.view.View
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentActivity
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import org.wordpress.android.R
import org.wordpress.android.WordPress
import org.wordpress.android.databinding.PagesListFragmentBinding
import org.wordpress.android.ui.utils.UiHelpers
import org.wordpress.android.util.DisplayUtils
import org.wordpress.android.viewmodel.pages.PagesViewModel
import org.wordpress.android.viewmodel.pages.SearchListViewModel
import org.wordpress.android.widgets.RecyclerItemDecoration
import javax.inject.Inject
class SearchListFragment : Fragment(R.layout.pages_list_fragment) {
@Inject lateinit var viewModelFactory: ViewModelProvider.Factory
private lateinit var viewModel: SearchListViewModel
private var linearLayoutManager: LinearLayoutManager? = null
@Inject lateinit var uiHelper: UiHelpers
private val listStateKey = "list_state"
companion object {
fun newInstance(): SearchListFragment {
return SearchListFragment()
}
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val nonNullActivity = requireActivity()
(nonNullActivity.application as? WordPress)?.component()?.inject(this)
with(PagesListFragmentBinding.bind(view)) {
initializeViews(savedInstanceState)
initializeViewModels(nonNullActivity)
}
}
override fun onSaveInstanceState(outState: Bundle) {
linearLayoutManager?.let {
outState.putParcelable(listStateKey, it.onSaveInstanceState())
}
super.onSaveInstanceState(outState)
}
private fun PagesListFragmentBinding.initializeViewModels(activity: FragmentActivity) {
val pagesViewModel = ViewModelProvider(activity, viewModelFactory).get(PagesViewModel::class.java)
viewModel = ViewModelProvider(this@SearchListFragment, viewModelFactory).get(SearchListViewModel::class.java)
viewModel.start(pagesViewModel)
setupObservers()
}
private fun PagesListFragmentBinding.initializeViews(savedInstanceState: Bundle?) {
val layoutManager = LinearLayoutManager(activity, RecyclerView.VERTICAL, false)
savedInstanceState?.getParcelable<Parcelable>(listStateKey)?.let {
layoutManager.onRestoreInstanceState(it)
}
linearLayoutManager = layoutManager
recyclerView.layoutManager = linearLayoutManager
recyclerView.addItemDecoration(RecyclerItemDecoration(0, DisplayUtils.dpToPx(activity, 1)))
recyclerView.id = R.id.pages_search_recycler_view_id
}
private fun PagesListFragmentBinding.setupObservers() {
viewModel.searchResult.observe(viewLifecycleOwner, Observer { data ->
data?.let { setSearchResult(data) }
})
}
private fun PagesListFragmentBinding.setSearchResult(pages: List<PageItem>) {
val adapter: PageSearchAdapter
if (recyclerView.adapter == null) {
adapter = PageSearchAdapter(
{ action, page -> viewModel.onMenuAction(action, page, requireContext()) },
{ page -> viewModel.onItemTapped(page) }, uiHelper)
recyclerView.adapter = adapter
} else {
adapter = recyclerView.adapter as PageSearchAdapter
}
adapter.update(pages)
}
}
| gpl-2.0 | 24d7d40b75020eb4d91ffeb6e3969372 | 38.202128 | 117 | 0.734328 | 5.356105 | false | false | false | false |
ingokegel/intellij-community | plugins/kotlin/idea/tests/testData/multiplatform/languageConstructions/common/common.kt | 9 | 411 | package sample
expect class <!LINE_MARKER("descr='Has actuals in jvm module'")!>A<!> {
fun <!LINE_MARKER("descr='Has actuals in jvm module'")!>commonFun<!>()
val <!LINE_MARKER("descr='Has actuals in jvm module'")!>x<!>: Int
val <!LINE_MARKER("descr='Has actuals in jvm module'")!>y<!>: Double
val <!LINE_MARKER("descr='Has actuals in jvm module'")!>z<!>: String
}
fun getCommonA(): A = null!!
| apache-2.0 | 0ec42161a358e4a4c567899fb4b514e0 | 40.1 | 74 | 0.63747 | 3.877358 | false | false | false | false |
android/nowinandroid | feature/author/src/main/java/com/google/samples/apps/nowinandroid/feature/author/navigation/AuthorNavigation.kt | 1 | 1883 | /*
* 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
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.samples.apps.nowinandroid.feature.author.navigation
import android.net.Uri
import androidx.annotation.VisibleForTesting
import androidx.lifecycle.SavedStateHandle
import androidx.navigation.NavController
import androidx.navigation.NavGraphBuilder
import androidx.navigation.NavType
import androidx.navigation.compose.composable
import androidx.navigation.navArgument
import com.google.samples.apps.nowinandroid.core.decoder.StringDecoder
import com.google.samples.apps.nowinandroid.feature.author.AuthorRoute
@VisibleForTesting
internal const val authorIdArg = "authorId"
internal class AuthorArgs(val authorId: String) {
constructor(savedStateHandle: SavedStateHandle, stringDecoder: StringDecoder) :
this(stringDecoder.decodeString(checkNotNull(savedStateHandle[authorIdArg])))
}
fun NavController.navigateToAuthor(authorId: String) {
val encodedString = Uri.encode(authorId)
this.navigate("author_route/$encodedString")
}
fun NavGraphBuilder.authorScreen(
onBackClick: () -> Unit
) {
composable(
route = "author_route/{$authorIdArg}",
arguments = listOf(
navArgument(authorIdArg) { type = NavType.StringType }
)
) {
AuthorRoute(onBackClick = onBackClick)
}
}
| apache-2.0 | e101e55092b2b3cf4898aa301e8a9e0e | 33.87037 | 85 | 0.765799 | 4.472684 | false | false | false | false |
iPoli/iPoli-android | app/src/main/java/io/ipoli/android/planday/job/PlanDayScheduler.kt | 1 | 7461 | package io.ipoli.android.planday.job
import android.app.NotificationManager
import android.content.Context
import android.graphics.BitmapFactory
import android.net.Uri
import android.widget.Toast
import com.evernote.android.job.Job
import com.evernote.android.job.JobRequest
import io.ipoli.android.Constants
import io.ipoli.android.MyPoliApp
import io.ipoli.android.R
import io.ipoli.android.common.IntentUtil
import io.ipoli.android.common.datetime.Duration
import io.ipoli.android.common.datetime.Minute
import io.ipoli.android.common.datetime.minutes
import io.ipoli.android.common.di.BackgroundModule
import io.ipoli.android.common.job.FixedDailyJob
import io.ipoli.android.common.job.FixedDailyJobScheduler
import io.ipoli.android.common.notification.NotificationUtil
import io.ipoli.android.common.notification.ScreenUtil
import io.ipoli.android.common.view.asThemedWrapper
import io.ipoli.android.dailychallenge.data.DailyChallenge
import io.ipoli.android.pet.AndroidPetAvatar
import io.ipoli.android.pet.Pet
import io.ipoli.android.player.data.Player
import io.ipoli.android.player.data.Player.Preferences.NotificationStyle
import io.ipoli.android.quest.reminder.PetNotificationPopup
import kotlinx.coroutines.experimental.Dispatchers
import kotlinx.coroutines.experimental.GlobalScope
import kotlinx.coroutines.experimental.launch
import org.threeten.bp.LocalDate
import space.traversal.kapsule.Kapsule
import java.util.*
/**
* Created by Venelin Valkov <[email protected]>
* on 05/18/2018.
*/
object PlanDayNotification {
fun show(
context: Context,
player: Player,
planDayScheduler: PlanDayScheduler
) {
val pet = player.pet
val c = context.asThemedWrapper()
ScreenUtil.awakeScreen(c)
val notificationManager =
c.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
val style = player.preferences.planDayNotificationStyle
var notificationId: Int? = showNotification(c, pet, notificationManager)
if (!(style == NotificationStyle.NOTIFICATION || style == NotificationStyle.ALL)) {
notificationManager.cancel(notificationId!!)
notificationId = null
}
if (style == NotificationStyle.POPUP || style == NotificationStyle.ALL) {
val vm = PetNotificationPopup.ViewModel(
headline = "Time to plan your day",
title = null,
body = null,
petAvatar = pet.avatar,
petState = pet.state,
doTextRes = R.string.start,
doImageRes = R.drawable.ic_play_arrow_white_32dp
)
showPetPopup(vm, notificationId, notificationManager, planDayScheduler, c).show(c)
}
}
private fun showPetPopup(
vm: PetNotificationPopup.ViewModel,
notificationId: Int?,
notificationManager: NotificationManager,
planDayScheduler: PlanDayScheduler,
context: Context
) =
PetNotificationPopup(
vm,
onDismiss = {
notificationId?.let {
notificationManager.cancel(it)
}
},
onSnooze = {
notificationId?.let {
notificationManager.cancel(it)
}
GlobalScope.launch(Dispatchers.IO) {
planDayScheduler.scheduleAfter(15.minutes)
}
Toast
.makeText(context, context.getString(R.string.remind_in_15), Toast.LENGTH_SHORT)
.show()
},
onDo = {
notificationId?.let {
notificationManager.cancel(it)
}
context.startActivity(IntentUtil.startPlanDay(context))
})
private fun showNotification(
context: Context,
pet: Pet,
notificationManager: NotificationManager
): Int {
val icon = BitmapFactory.decodeResource(
context.resources,
AndroidPetAvatar.valueOf(pet.avatar.name).headImage
)
val sound =
Uri.parse("android.resource://" + context.packageName + "/" + R.raw.notification)
val notification = NotificationUtil.createDefaultNotification(
context = context,
icon = icon,
title = "Time to plan your day",
message = "Amazing new day ahead!",
sound = sound,
channelId = Constants.PLAN_DAY_NOTIFICATION_CHANNEL_ID,
contentIntent = IntentUtil.getActivityPendingIntent(
context,
IntentUtil.startPlanDay(context)
)
)
val notificationId = Random().nextInt()
notificationManager.notify(notificationId, notification)
return notificationId
}
}
class SnoozedPlanDayJob : Job() {
override fun onRunJob(params: Params): Result {
val kap = Kapsule<BackgroundModule>()
val playerRepository by kap.required { playerRepository }
val planDayScheduler by kap.required { planDayScheduler }
kap.inject(MyPoliApp.backgroundModule(context))
val p = playerRepository.find()
requireNotNull(p)
GlobalScope.launch(Dispatchers.Main) {
PlanDayNotification.show(context, p!!, planDayScheduler)
}
return Result.SUCCESS
}
companion object {
const val TAG = "job_snoozed_plan_day_tag"
}
}
class PlanDayJob : FixedDailyJob(PlanDayJob.TAG) {
override fun doRunJob(params: Params): Result {
val kap = Kapsule<BackgroundModule>()
val playerRepository by kap.required { playerRepository }
val planDayScheduler by kap.required { planDayScheduler }
val dailyChallengeRepository by kap.required { dailyChallengeRepository }
kap.inject(MyPoliApp.backgroundModule(context))
val p = playerRepository.find()
requireNotNull(p)
if (!p!!.preferences.planDays.contains(LocalDate.now().dayOfWeek)) {
return Job.Result.SUCCESS
}
dailyChallengeRepository.findForDate(LocalDate.now())
?: dailyChallengeRepository.save(DailyChallenge(date = LocalDate.now()))
GlobalScope.launch(Dispatchers.Main) {
PlanDayNotification.show(context, p, planDayScheduler)
}
return Job.Result.SUCCESS
}
companion object {
const val TAG = "job_plan_day_tag"
}
}
interface PlanDayScheduler {
fun scheduleAfter(minutes: Duration<Minute>)
fun schedule()
}
class AndroidPlanDayScheduler(private val context: Context) : PlanDayScheduler {
override fun scheduleAfter(minutes: Duration<Minute>) {
JobRequest.Builder(SnoozedPlanDayJob.TAG)
.setUpdateCurrent(true)
.setExact(minutes.millisValue)
.build()
.schedule()
}
override fun schedule() {
GlobalScope.launch(Dispatchers.IO) {
val kap = Kapsule<BackgroundModule>()
val playerRepository by kap.required { playerRepository }
kap.inject(MyPoliApp.backgroundModule([email protected]))
val p = playerRepository.find()
requireNotNull(p)
val pTime = p!!.preferences.planDayTime
FixedDailyJobScheduler.schedule(PlanDayJob.TAG, pTime)
}
}
} | gpl-3.0 | 74c32df46ca97b43455e2b3ad386c29c | 31.163793 | 100 | 0.649377 | 4.905325 | false | false | false | false |
GunoH/intellij-community | notebooks/notebook-ui/src/org/jetbrains/plugins/notebooks/ui/editor/actions/command/mode/NotebookEditorMode.kt | 2 | 4424 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.plugins.notebooks.ui.editor.actions.command.mode
import com.intellij.openapi.actionSystem.ex.ActionUtil
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.editor.CaretVisualAttributes
import com.intellij.openapi.editor.event.CaretEvent
import com.intellij.openapi.editor.event.CaretListener
import com.intellij.openapi.editor.ex.EditorEx
import com.intellij.openapi.editor.ex.MarkupModelEx
import com.intellij.openapi.editor.ex.RangeHighlighterEx
import com.intellij.openapi.fileEditor.TextEditor
import com.intellij.util.concurrency.annotations.RequiresEdt
import com.intellij.util.messages.Topic
import org.jetbrains.annotations.CalledInAny
import java.awt.Color
/**
* The Jupyter Notebook has a modal user interface.
* This means that the keyboard does different things depending on which mode the Notebook is in.
* There are two modes: edit mode and command mode.
*
* @see <a href="https://jupyter-notebook.readthedocs.io/en/stable/examples/Notebook/Notebook%20Basics.html#Modal-editor">
* Notebook Modal Editor
* </a>
*/
enum class NotebookEditorMode {
EDIT,
COMMAND
}
val NOTEBOOK_EDITOR_MODE: Topic<NotebookEditorModeListener> = Topic.create("Notebook Editor Mode",
NotebookEditorModeListener::class.java)
@FunctionalInterface
interface NotebookEditorModeListener {
fun onModeChange(mode: NotebookEditorMode)
}
abstract class NotebookEditorModeListenerAdapter : TextEditor, NotebookEditorModeListener, CaretListener {
private var currentEditorMode: NotebookEditorMode? = null
private fun getCaretAttributes(mode: NotebookEditorMode): CaretVisualAttributes {
return when (mode) {
NotebookEditorMode.EDIT -> CaretVisualAttributes.DEFAULT
NotebookEditorMode.COMMAND -> INVISIBLE_CARET
}
}
private fun isCaretRowShown(mode: NotebookEditorMode): Boolean =
when (mode) {
NotebookEditorMode.EDIT -> true
NotebookEditorMode.COMMAND -> false
}
private fun handleCarets(mode: NotebookEditorMode) {
when (mode) {
NotebookEditorMode.EDIT -> {
// selection of multiple cells leads to multiple invisible carets, remove them
editor.caretModel.removeSecondaryCarets()
}
NotebookEditorMode.COMMAND -> {
// text selection shouldn't be visible in command mode
for (caret in editor.caretModel.allCarets) {
caret.removeSelection()
}
}
}
}
override fun onModeChange(mode: NotebookEditorMode) {
val modeWasChanged = currentEditorMode != mode
currentEditorMode = mode
editor.apply {
(markupModel as MarkupModelEx).apply {
allHighlighters.filterIsInstance<RangeHighlighterEx>().forEach {
fireAttributesChanged(it, true, false)
}
}
if (modeWasChanged) {
handleCarets(mode)
editor.settings.isCaretRowShown = isCaretRowShown(mode)
}
caretModel.allCarets.forEach { caret ->
caret.visualAttributes = getCaretAttributes(mode)
}
editor.contentComponent.putClientProperty(ActionUtil.ALLOW_PlAIN_LETTER_SHORTCUTS, when (mode) {
NotebookEditorMode.EDIT -> false
NotebookEditorMode.COMMAND -> true
})
}
}
override fun caretAdded(event: CaretEvent) {
val mode = currentEditorMode ?: return
event.caret?.visualAttributes = getCaretAttributes(mode)
(editor as EditorEx).gutterComponentEx.repaint()
}
override fun caretRemoved(event: CaretEvent) {
(editor as EditorEx).gutterComponentEx.repaint()
}
}
@CalledInAny
fun currentMode(): NotebookEditorMode = currentMode_
@RequiresEdt
fun setMode(mode: NotebookEditorMode) {
// Although LAB-50 is marked as closed, the checks still aren't added to classes written in Kotlin.
ApplicationManager.getApplication().assertIsDispatchThread()
currentMode_ = mode
// may be call should be skipped if mode == currentMode_
ApplicationManager.getApplication().messageBus.syncPublisher(NOTEBOOK_EDITOR_MODE).onModeChange(mode)
}
@Volatile
private var currentMode_: NotebookEditorMode = NotebookEditorMode.EDIT
private val INVISIBLE_CARET = CaretVisualAttributes(
Color(0, 0, 0, 0),
CaretVisualAttributes.Weight.NORMAL)
| apache-2.0 | d25ece7c0fc82afb3433d2b0c11216be | 32.014925 | 122 | 0.737342 | 4.746781 | false | false | false | false |
GunoH/intellij-community | plugins/terminal/src/com/intellij/ide/actions/runAnything/RunAnythingTerminalBridge.kt | 5 | 3702 | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.ide.actions.runAnything
import com.intellij.execution.Executor
import com.intellij.ide.actions.runAnything.activity.RunAnythingCommandProvider
import com.intellij.ide.actions.runAnything.activity.RunAnythingProvider
import com.intellij.ide.actions.runAnything.activity.RunAnythingRecentProjectProvider
import com.intellij.internal.statistic.collectors.fus.ClassNameRuleValidator
import com.intellij.internal.statistic.collectors.fus.TerminalFusAwareHandler
import com.intellij.internal.statistic.eventLog.events.EventFields
import com.intellij.internal.statistic.eventLog.events.EventPair
import com.intellij.openapi.actionSystem.CommonDataKeys
import com.intellij.openapi.actionSystem.DataContext
import com.intellij.openapi.actionSystem.impl.SimpleDataContext
import com.intellij.openapi.project.Project
import com.intellij.openapi.vfs.LocalFileSystem
import com.intellij.terminal.TerminalShellCommandHandler
private class RunAnythingTerminalBridge : TerminalShellCommandHandler, TerminalFusAwareHandler {
override fun matches(project: Project, workingDirectory: String?, localSession: Boolean, command: String): Boolean {
val dataContext = createDataContext(project, localSession, workingDirectory)
return RunAnythingProvider.EP_NAME.extensionList
.asSequence()
.filter { checkForCLI(it) }
.any { provider -> provider.findMatchingValue(dataContext, command) != null }
}
override fun execute(project: Project, workingDirectory: String?, localSession: Boolean, command: String, executor: Executor): Boolean {
val dataContext = createDataContext(project, localSession, workingDirectory, executor)
return RunAnythingProvider.EP_NAME.extensionList
.asSequence()
.filter { checkForCLI(it) }
.any { provider ->
provider.findMatchingValue(dataContext, command)?.let { provider.execute(dataContext, it); return true } ?: false
}
}
companion object {
private fun createDataContext(project: Project, localSession: Boolean, workingDirectory: String?, executor: Executor? = null): DataContext {
val virtualFile = if (localSession && workingDirectory != null)
LocalFileSystem.getInstance().findFileByPath(workingDirectory) else null
return SimpleDataContext.builder()
.add(CommonDataKeys.PROJECT, project)
.add(RunAnythingAction.EXECUTOR_KEY, executor)
.apply {
if (virtualFile != null) {
add(CommonDataKeys.VIRTUAL_FILE, virtualFile)
add(RunAnythingProvider.EXECUTING_CONTEXT, RunAnythingContext.RecentDirectoryContext(virtualFile.path))
}
}
.build()
}
private fun checkForCLI(it: RunAnythingProvider<*>?): Boolean {
return (it !is RunAnythingCommandProvider
&& it !is RunAnythingRecentProjectProvider
&& it !is RunAnythingRunConfigurationProvider)
}
}
override fun fillData(project: Project, workingDirectory: String?, localSession: Boolean, command: String, data: MutableList<EventPair<*>>) {
val dataContext = createDataContext(project, localSession, workingDirectory)
val runAnythingProvider = RunAnythingProvider.EP_NAME.extensionList
.filter { checkForCLI(it) }
.ifEmpty { return }
.first { provider -> provider.findMatchingValue(dataContext, command) != null }
data.add(EventFields.StringValidatedByCustomRule("runAnythingProvider",
ClassNameRuleValidator::class.java).with(runAnythingProvider::class.java.name))
}
} | apache-2.0 | 288380ed556c5d2e2120b112f6ecaee9 | 50.430556 | 144 | 0.753377 | 5.184874 | false | false | false | false |
evanchooly/kobalt | modules/kobalt-plugin-api/src/main/kotlin/com/beust/kobalt/misc/GithubApi2.kt | 1 | 6662 | package com.beust.kobalt.misc
import com.beust.kobalt.KobaltException
import com.beust.kobalt.internal.DocUrl
import com.beust.kobalt.internal.KobaltSettings
import com.beust.kobalt.maven.Http
import com.google.gson.Gson
import com.google.gson.annotations.SerializedName
import com.google.inject.Inject
import okhttp3.OkHttpClient
import retrofit2.Call
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import retrofit2.http.*
import rx.Observable
import java.io.File
import java.util.*
import java.util.concurrent.Callable
import java.util.concurrent.Future
class GithubApi2 @Inject constructor(
val executors: KobaltExecutors, val localProperties: LocalProperties, val http: Http, val settings:KobaltSettings) {
companion object {
const val PROPERTY_ACCESS_TOKEN = "github.accessToken"
const val PROPERTY_USERNAME = "github.username"
}
private val DOC_URL = DocUrl.PUBLISH_PLUGIN_URL
//
// JSON mapped classes that get sent up and down
//
class CreateRelease(@SerializedName("tag_name") var tagName: String? = null,
var name: String? = tagName)
class CreateReleaseResponse(var id: String? = null, @SerializedName("upload_url") var uploadUrl: String?)
class UploadAssetResponse(var id: String? = null, val name: String? = null)
class ReleasesResponse(@SerializedName("tag_name") var tagName: String? = null,
var name: String? = tagName)
interface Api {
@POST("/repos/{owner}/{repo}/releases")
fun createRelease(@Path("owner") owner: String,
@Path("repo") repo: String,
@Query("access_token") accessToken: String,
@Body createRelease: CreateRelease): Call<CreateReleaseResponse>
@GET("/repos/{owner}/{repo}/releases")
fun getReleases(@Path("owner") owner: String,
@Path("repo") repo: String,
@Query("access_token") accessToken: String): Call<List<ReleasesResponse>>
@GET("/repos/{owner}/{repo}/releases")
fun getReleasesNoAuth(@Path("owner") owner: String,
@Path("repo") repo: String): Call<List<ReleasesResponse>>
}
//
// Read only Api
//
private val service = Retrofit.Builder()
.client(OkHttpClient.Builder().proxy(settings.proxyConfig?.toProxy()).build())
.baseUrl("https://api.github.com")
.addConverterFactory(GsonConverterFactory.create())
.build()
.create(Api::class.java)
// JSON Retrofit error
class Error(val code: String)
class RetrofitError(var message: String = "", var errors : List<Error> = arrayListOf())
fun uploadRelease(packageName: String, tagName: String, zipFile: File) {
log(1, "Uploading release ${zipFile.name}")
val username = localProperties.get(PROPERTY_USERNAME, DOC_URL)
val accessToken = localProperties.get(PROPERTY_ACCESS_TOKEN, DOC_URL)
val response = service.createRelease(username, packageName, accessToken, CreateRelease(tagName))
.execute()
val code = response.code()
if (code != Http.CREATED) {
val error = Gson().fromJson(response.errorBody().string(), RetrofitError::class.java)
throw KobaltException("Couldn't upload release, ${error.message}: " + error.errors[0].code)
} else {
val body = response.body()
uploadAsset(accessToken, body.uploadUrl!!, Http.TypedFile("application/zip", zipFile), tagName)
.toBlocking()
.forEach { action ->
log(1, "\n${zipFile.name} successfully uploaded")
}
}
}
private fun uploadAsset(token: String, uploadUrl: String, typedFile: Http.TypedFile, tagName: String)
: Observable<UploadAssetResponse> {
val strippedUrl = uploadUrl.substring(0, uploadUrl.indexOf("{"))
val fileName = typedFile.file.name
val url = "$strippedUrl?name=$fileName&label=$fileName"
val headers = okhttp3.Headers.of("Authorization", "token $token")
val totalSize = typedFile.file.length()
http.uploadFile(url = url, file = typedFile, headers = headers, post = true, // Github requires POST
progressCallback = http.percentProgressCallback(totalSize))
return Observable.just(UploadAssetResponse(tagName, tagName))
}
val latestKobaltVersion: Future<String>
get() {
val callable = Callable<String> {
var result = "0"
val username = localProperties.getNoThrows(PROPERTY_USERNAME, DOC_URL)
val accessToken = localProperties.getNoThrows(PROPERTY_ACCESS_TOKEN, DOC_URL)
try {
val req =
if (username != null && accessToken != null) {
service.getReleases(username, "kobalt", accessToken)
} else {
service.getReleasesNoAuth("cbeust", "kobalt")
}
val releases = req.execute().body()
if (releases != null) {
releases.firstOrNull()?.let {
try {
result = listOf(it.name, it.tagName).filterNotNull().first { !it.isBlank() }
} catch(ex: NoSuchElementException) {
throw KobaltException("Couldn't find the latest release")
}
}
} else {
warn("Didn't receive any body in the response to GitHub.getReleases()")
}
} catch(e: Exception) {
log(1, "Couldn't retrieve releases from github: " + e.message)
e.printStackTrace()
// val error = parseRetrofitError(e)
// val details = if (error.errors != null) {
// error.errors[0]
// } else {
// null
// }
// // TODO: If the credentials didn't work ("bad credentials"), should start again
// // using cbeust/kobalt, like above. Right now, just bailing.
// log(2, "Couldn't retrieve releases from github, ${error.message ?: e}: "
// + details?.code + " field: " + details?.field)
}
result
}
return executors.miscExecutor.submit(callable)
}
} | apache-2.0 | f8fa3e352f351f2ce6d54458b4a9f296 | 42.835526 | 124 | 0.580907 | 4.813584 | false | false | false | false |
ktorio/ktor | ktor-http/ktor-http-cio/common/src/io/ktor/http/cio/internals/Tokenizer.kt | 1 | 1277 | /*
* Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license.
*/
package io.ktor.http.cio.internals
internal fun nextToken(text: CharSequence, range: MutableRange): CharSequence {
val spaceOrEnd = findSpaceOrEnd(text, range)
val s = text.subSequence(range.start, spaceOrEnd)
range.start = spaceOrEnd
return s
}
internal fun skipSpacesAndHorizontalTabs(
text: CharArrayBuilder,
start: Int,
end: Int
): Int {
var index = start
while (index < end) {
val ch = text[index]
if (!ch.isWhitespace() && ch != HTAB) break
index++
}
return index
}
internal fun skipSpaces(text: CharSequence, range: MutableRange) {
var idx = range.start
val end = range.end
if (idx >= end || !text[idx].isWhitespace()) return
idx++
while (idx < end) {
if (!text[idx].isWhitespace()) break
idx++
}
range.start = idx
}
internal fun findSpaceOrEnd(text: CharSequence, range: MutableRange): Int {
var idx = range.start
val end = range.end
if (idx >= end || text[idx].isWhitespace()) return idx
idx++
while (idx < end) {
if (text[idx].isWhitespace()) return idx
idx++
}
return idx
}
| apache-2.0 | 9c1429a653e945d37b83cb2af43e77af | 21.803571 | 118 | 0.628818 | 3.846386 | false | false | false | false |
AntonovAlexander/activecore | kernelip/reordex/src/dispatch_buffer.kt | 1 | 11265 | /*
* dispatch_buffer.kt
*
* Created on: 24.12.2020
* Author: Alexander Antonov <[email protected]>
* License: See LICENSE file for details
*/
package reordex
import hwast.*
internal open class dispatch_buffer(cyclix_gen : cyclix.Generic,
name_prefix : String,
TRX_BUF_SIZE : Int,
MultiExu_CFG : Reordex_CFG,
ExecUnits_size : Int,
cdb_num : Int,
val IQ_insts : ArrayList<iq_buffer>,
val control_structures: __control_structures) : uop_buffer(cyclix_gen, name_prefix, TRX_BUF_SIZE, MultiExu_CFG.DataPath_width, MultiExu_CFG, cdb_num) {
var exu_id = AdduStageVar("exu_id", GetWidthToContain(ExecUnits_size), 0, "0")
var rds_ctrl = ArrayList<ROB_rd_ctrl>()
var cf_can_alter = AdduStageVar("cf_can_alter", 0, 0, "0")
val io_req = AdduStageVar("io_req", 0, 0, "0")
var mem_we = AdduStageVar("mem_we",0, 0, "1")
var dispatch_active = cyclix_gen.ulocal("gendispatch_dispatch_active", 0, 0, "1")
var entry_toproc_mask = cyclix_gen.uglobal("gendispatch_entry_toproc_mask", TRX_BUF_MULTIDIM-1, 0, hw_imm_ones(TRX_BUF_MULTIDIM))
var iq_free_mask = cyclix_gen.ulocal("gendispatch_iq_free_mask", IQ_insts.size-1, 0, hw_imm_ones(IQ_insts.size))
var store_iq_free_mask = cyclix_gen.ulocal("gendispatch_store_iq_free_mask", 0, 0, "1")
init {
Fill_ROB_rds_ctrl_StageVars(this, MultiExu_CFG.rds.size, rds_ctrl, MultiExu_CFG.PRF_addr_width)
control_structures.states_toRollBack.add(entry_toproc_mask)
}
fun Process(rob : rob, PRF_src : hw_var, store_iq : iq_buffer, ExecUnits : MutableMap<String, Exu_CFG>, CDB_RISC_LSU_POS : Int) {
cyclix_gen.MSG_COMMENT("sending new operations to IQs...")
preinit_ctrls()
init_locals()
var rob_push_trx_total = rob.GetPushTrx()
var store_push_trx = store_iq.GetPushTrx()
cyclix_gen.begif(cyclix_gen.band(ctrl_active, rob.ctrl_rdy))
run {
for (entry_num in 0 until MultiExu_CFG.DataPath_width) {
cyclix_gen.begif(TRX_LOCAL_PARALLEL.GetFracRef(entry_num).GetFracRef("enb"))
run {
switch_to_local(entry_num)
var rob_push_trx = rob_push_trx_total.GetFracRef(entry_num)
cyclix_gen.begif(cyclix_gen.band(dispatch_active, entry_toproc_mask.GetFracRef(entry_num), enb))
run {
for (rsrv in src_rsrv) {
cyclix_gen.assign(rsrv.src_src, PRF_src.GetFracRef(rsrv.src_tag))
}
cyclix_gen.assign(dispatch_active, 0)
cyclix_gen.begif(io_req)
run {
cyclix_gen.begif(cyclix_gen.band(store_iq_free_mask, store_iq.ctrl_rdy))
run {
// pushing trx to IQ
cyclix_gen.assign(store_iq.push, 1)
cyclix_gen.assign_subStructs(store_push_trx, TRX_LOCAL)
cyclix_gen.assign(store_push_trx.GetFracRef("trx_id"), rob.TRX_ID_COUNTER)
store_iq.push_trx(store_push_trx)
// marking rd src
cyclix_gen.begif(!mem_we)
run {
cyclix_gen.assign(PRF_src.GetFracRef(rds_ctrl[0].tag), CDB_RISC_LSU_POS)
}; cyclix_gen.endif()
// marking RRB for ROB
cyclix_gen.assign(rob_push_trx.GetFracRef("cdb_id"), store_iq.CDB_index)
// marking op as scheduled
cyclix_gen.assign(entry_toproc_mask.GetFracRef(entry_num), 0)
// marking IQ as busy
cyclix_gen.assign(store_iq_free_mask, 0)
// marking ready to schedule next trx
cyclix_gen.assign(dispatch_active, 1)
}; cyclix_gen.endif()
}; cyclix_gen.endif()
cyclix_gen.begelse()
run {
for (IQ_inst_idx in 0 until IQ_insts.size-1) {
var IQ_inst = IQ_insts[IQ_inst_idx]
cyclix_gen.begif(cyclix_gen.band(entry_toproc_mask.GetFracRef(entry_num), iq_free_mask.GetFracRef(IQ_inst_idx)))
run {
cyclix_gen.begif(cyclix_gen.eq2(exu_id, IQ_inst.exu_id_num))
run {
cyclix_gen.begif(IQ_inst.ctrl_rdy)
run {
// pushing trx to IQ
cyclix_gen.assign(IQ_inst.push, 1)
var iq_push_trx = IQ_inst.GetPushTrx()
cyclix_gen.assign_subStructs(iq_push_trx, TRX_LOCAL)
cyclix_gen.assign(iq_push_trx.GetFracRef("trx_id"), rob.TRX_ID_COUNTER)
IQ_inst.push_trx(iq_push_trx)
// marking rd src
cyclix_gen.assign(PRF_src.GetFracRef(rds_ctrl[0].tag), IQ_inst.CDB_index)
// marking RRB for ROB
cyclix_gen.assign(rob_push_trx.GetFracRef("cdb_id"), IQ_inst.CDB_index)
// marking op as scheduled
cyclix_gen.assign(entry_toproc_mask.GetFracRef(entry_num), 0)
// marking IQ as busy
cyclix_gen.assign(iq_free_mask.GetFracRef(IQ_inst_idx), 0)
// marking ready to schedule next trx
cyclix_gen.assign(dispatch_active, 1)
}; cyclix_gen.endif()
}; cyclix_gen.endif()
}; cyclix_gen.endif()
}
}; cyclix_gen.endif()
cyclix_gen.begif(dispatch_active)
run {
// pushing to ROB
cyclix_gen.assign_subStructs(rob_push_trx, TRX_LOCAL)
cyclix_gen.assign(rob_push_trx.GetFracRef("trx_id"), rob.TRX_ID_COUNTER)
cyclix_gen.assign(rob_push_trx.GetFracRef("rdy"), 0)
cyclix_gen.add_gen(rob.TRX_ID_COUNTER, rob.TRX_ID_COUNTER, 1)
cyclix_gen.assign(rob.push, 1)
}; cyclix_gen.endif()
}; cyclix_gen.endif()
}; cyclix_gen.endif()
}
cyclix_gen.begif(dispatch_active)
run {
cyclix_gen.assign(pop, 1)
}; cyclix_gen.endif()
}; cyclix_gen.endif()
cyclix_gen.begif(rob.push)
run {
rob.push_trx(rob_push_trx_total)
}; cyclix_gen.endif()
cyclix_gen.begif(pop)
run {
pop_trx()
cyclix_gen.assign(entry_toproc_mask, hw_imm_ones(TRX_BUF_MULTIDIM))
}; cyclix_gen.endif()
finalize_ctrls() // TODO: cleanup
cyclix_gen.MSG_COMMENT("sending new operation to IQs: done")
}
}
internal class dispatch_buffer_risc(cyclix_gen : cyclix.Generic,
name_prefix : String,
TRX_BUF_SIZE : Int,
MultiExu_CFG : Reordex_CFG,
ExecUnits_size : Int,
cdb_num : Int,
IQ_insts : ArrayList<iq_buffer>,
control_structures: __control_structures) : dispatch_buffer(cyclix_gen, name_prefix, TRX_BUF_SIZE, MultiExu_CFG, ExecUnits_size, cdb_num, IQ_insts, control_structures) {
var curinstr_addr = AdduStageVar("curinstr_addr", 31, 0, "0")
var nextinstr_addr = AdduStageVar("nextinstr_addr", 31, 0, "0")
var rss = ArrayList<RISCDecoder_rs>()
var rds = ArrayList<RISCDecoder_rd>()
var csr_rdata = AdduStageVar("csr_rdata", 31, 0, "0")
var immediate = AdduStageVar("immediate", 31, 0, "0")
var fencereq = AdduStageVar("fencereq", 0, 0, "0")
var pred = AdduStageVar("pred", 3, 0, "0")
var succ = AdduStageVar("succ", 3, 0, "0")
var ecallreq = AdduStageVar("ecallreq", 0, 0, "0")
var ebreakreq = AdduStageVar("ebreakreq", 0, 0, "0")
var csrreq = AdduStageVar("csrreq", 0, 0, "0")
var csrnum = AdduStageVar("csrnum", 11, 0, "0")
var zimm = AdduStageVar("zimm", 4, 0, "0")
var op1_source = AdduStageVar("op1_source", 1, 0, "0")
var op2_source = AdduStageVar("op2_source", 1, 0, "0")
// ALU control
var alu_req = AdduStageVar("alu_req", 0, 0, "0")
var alu_op1 = AdduStageVar("alu_op1", 31, 0, "0")
var alu_op2 = AdduStageVar("alu_op2", 31, 0, "0")
var alu_op1_wide = AdduStageVar("alu_op1_wide", 32, 0, "0")
var alu_op2_wide = AdduStageVar("alu_op2_wide", 32, 0, "0")
var alu_result_wide = AdduStageVar("alu_result_wide", 32, 0, "0")
var alu_result = AdduStageVar("alu_result", 31, 0, "0")
var alu_CF = AdduStageVar("alu_CF", 0, 0, "0")
var alu_SF = AdduStageVar("alu_SF", 0, 0, "0")
var alu_ZF = AdduStageVar("alu_ZF", 0, 0, "0")
var alu_OF = AdduStageVar("alu_OF", 0, 0, "0")
var alu_overflow = AdduStageVar("alu_overflow", 0, 0, "0")
// data memory control
var mem_req = AdduStageVar("mem_req", 0, 0, "0")
//var mem_cmd = AdduStageVar("mem_cmd", 0, 0, "0")
var mem_addr = AdduStageVar("mem_addr", 31, 0, "0")
var mem_be = AdduStageVar("mem_be", 3, 0, "0")
var mem_wdata = AdduStageVar("mem_wdata", 31, 0, "0")
var mem_rdata = AdduStageVar("mem_rdata", 31, 0, "0")
var mem_rshift = AdduStageVar("mem_rshift", 0, 0, "0")
var mem_load_signext = AdduStageVar("mem_load_signext", 0, 0, "0")
var mret_req = AdduStageVar("mret_req", 0, 0, "0")
init {
Fill_RISCDecoder_rss_StageVars(this, MultiExu_CFG.srcs.size, rss, MultiExu_CFG.ARF_addr_width, MultiExu_CFG.RF_width)
Fill_RISCDecoder_rds_StageVars(this, MultiExu_CFG.rds.size, rds, MultiExu_CFG.ARF_addr_width)
}
} | apache-2.0 | 3c6d6225bbebbc1a95aa38e845f6e297 | 44.427419 | 194 | 0.478917 | 4.024652 | false | false | false | false |
inorichi/mangafeed | app/src/main/java/eu/kanade/tachiyomi/source/model/SMangaImpl.kt | 2 | 449 | package eu.kanade.tachiyomi.source.model
class SMangaImpl : SManga {
override lateinit var url: String
override lateinit var title: String
override var artist: String? = null
override var author: String? = null
override var description: String? = null
override var genre: String? = null
override var status: Int = 0
override var thumbnail_url: String? = null
override var initialized: Boolean = false
}
| apache-2.0 | d757f4dd672308d123ac4b1207a0e946 | 19.409091 | 46 | 0.699332 | 4.628866 | false | false | false | false |
dahlstrom-g/intellij-community | plugins/kotlin/gradle/gradle-java/src/org/jetbrains/kotlin/idea/gradleJava/scripting/GradleImportHelper.kt | 2 | 6435 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.idea.gradleJava.scripting
import com.intellij.diff.util.DiffUtil
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.CommonDataKeys
import com.intellij.openapi.components.service
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.externalSystem.importing.ImportSpecBuilder
import com.intellij.openapi.externalSystem.util.ExternalSystemUtil
import com.intellij.openapi.fileEditor.FileDocumentManager
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.registry.Registry
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.testFramework.LightVirtualFileBase
import org.gradle.tooling.model.kotlin.dsl.KotlinDslModelsParameters
import org.gradle.util.GradleVersion
import org.jetbrains.annotations.Nls
import org.jetbrains.kotlin.idea.KotlinIcons
import org.jetbrains.kotlin.idea.core.script.settings.KotlinScriptingSettings
import org.jetbrains.kotlin.idea.gradle.KotlinIdeaGradleBundle
import org.jetbrains.kotlin.idea.gradleJava.scripting.importing.KotlinDslScriptModelResolver
import org.jetbrains.kotlin.idea.gradleJava.scripting.roots.GradleBuildRoot
import org.jetbrains.kotlin.idea.gradleJava.scripting.roots.GradleBuildRootsManager
import org.jetbrains.kotlin.idea.util.isKotlinFileType
import org.jetbrains.kotlin.scripting.definitions.ScriptDefinitionProvider
import org.jetbrains.kotlin.scripting.definitions.findScriptDefinition
import org.jetbrains.plugins.gradle.service.GradleInstallationManager
import org.jetbrains.plugins.gradle.service.project.GradlePartialResolverPolicy
import org.jetbrains.plugins.gradle.settings.GradleProjectSettings
import org.jetbrains.plugins.gradle.util.GradleConstants
val scriptConfigurationsNeedToBeUpdatedBalloon
get() = Registry.`is`("kotlin.gradle.scripts.scriptConfigurationsNeedToBeUpdatedFloatingNotification", true)
fun runPartialGradleImportForAllRoots(project: Project) {
GradleBuildRootsManager.getInstance(project)?.getAllRoots()?.forEach { root ->
runPartialGradleImport(project, root)
}
}
fun runPartialGradleImport(project: Project, root: GradleBuildRoot) {
if (root.isImportingInProgress()) return
ExternalSystemUtil.refreshProject(
root.pathPrefix,
ImportSpecBuilder(project, GradleConstants.SYSTEM_ID)
.withVmOptions(
"-D${KotlinDslModelsParameters.PROVIDER_MODE_SYSTEM_PROPERTY_NAME}=" +
KotlinDslModelsParameters.CLASSPATH_MODE_SYSTEM_PROPERTY_VALUE
)
.projectResolverPolicy(
GradlePartialResolverPolicy { it is KotlinDslScriptModelResolver }
)
)
}
@Nls fun configurationsAreMissingRequestNeeded() = KotlinIdeaGradleBundle.message("notification.wasNotImportedAfterCreation.text")
@Nls fun getConfigurationsActionText() = KotlinIdeaGradleBundle.message("action.text.load.script.configurations")
@Nls fun configurationsAreMissingRequestNeededHelp(): String = KotlinIdeaGradleBundle.message("notification.wasNotImportedAfterCreation.help")
@Nls fun configurationsAreMissingAfterRequest(): String = KotlinIdeaGradleBundle.message("notification.notEvaluatedInLastImport.text")
fun autoReloadScriptConfigurations(project: Project, file: VirtualFile): Boolean {
val definition = file.findScriptDefinition(project) ?: return false
return KotlinScriptingSettings.getInstance(project).autoReloadConfigurations(definition)
}
fun scriptConfigurationsNeedToBeUpdated(project: Project, file: VirtualFile) {
if (autoReloadScriptConfigurations(project, file)) {
GradleBuildRootsManager.getInstance(project)?.getScriptInfo(file)?.buildRoot?.let {
runPartialGradleImport(project, it)
}
} else {
// notification is shown in LoadConfigurationAction
}
}
fun scriptConfigurationsAreUpToDate(project: Project): Boolean = true
class LoadConfigurationAction : AnAction(
KotlinIdeaGradleBundle.message("action.text.load.script.configurations"),
KotlinIdeaGradleBundle.message("action.description.load.script.configurations"),
KotlinIcons.LOAD_SCRIPT_CONFIGURATION
) {
override fun actionPerformed(e: AnActionEvent) {
val project = e.project ?: return
val editor = e.getData(CommonDataKeys.EDITOR) ?: return
val file = getKotlinScriptFile(editor) ?: return
val root = GradleBuildRootsManager.getInstance(project)?.getScriptInfo(file)?.buildRoot ?: return
runPartialGradleImport(project, root)
}
override fun update(e: AnActionEvent) {
ensureValidActionVisibility(e)
}
private fun ensureValidActionVisibility(e: AnActionEvent) {
val editor = e.getData(CommonDataKeys.EDITOR) ?: return
e.presentation.isVisible = getNotificationVisibility(editor)
}
private fun getNotificationVisibility(editor: Editor): Boolean {
if (!scriptConfigurationsNeedToBeUpdatedBalloon) return false
if (DiffUtil.isDiffEditor(editor)) return false
val project = editor.project ?: return false
// prevent services initialization
// (all services actually initialized under the ScriptDefinitionProvider during startup activity)
if (ScriptDefinitionProvider.getServiceIfCreated(project) == null) return false
val file = getKotlinScriptFile(editor) ?: return false
if (autoReloadScriptConfigurations(project, file)) {
return false
}
return GradleBuildRootsManager.getInstance(project)?.isConfigurationOutOfDate(file) ?: false
}
private fun getKotlinScriptFile(editor: Editor): VirtualFile? {
return FileDocumentManager.getInstance()
.getFile(editor.document)
?.takeIf {
it !is LightVirtualFileBase
&& it.isValid
&& it.isKotlinFileType()
&& isGradleKotlinScript(it)
}
}
}
fun getGradleVersion(project: Project, settings: GradleProjectSettings): String {
return GradleInstallationManager.getGradleVersion(
service<GradleInstallationManager>().getGradleHome(project, settings.externalProjectPath)?.path
) ?: GradleVersion.current().version
}
| apache-2.0 | 10f9abca531e7261123166345fa77385 | 44.316901 | 142 | 0.768765 | 5.181159 | false | true | false | false |
harningt/atomun-core | src/main/kotlin/us/eharning/atomun/core/ec/internal/BouncyCastleECSigner.kt | 1 | 6483 | /*
* Copyright 2016, 2017 Thomas Harning Jr. <[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 us.eharning.atomun.core.ec.internal
import org.bouncycastle.asn1.ASN1Integer
import org.bouncycastle.asn1.ASN1Sequence
import org.bouncycastle.asn1.DERSequenceGenerator
import org.bouncycastle.crypto.digests.SHA256Digest
import org.bouncycastle.crypto.params.ECPrivateKeyParameters
import org.bouncycastle.crypto.params.ECPublicKeyParameters
import org.bouncycastle.crypto.signers.ECDSASigner
import org.bouncycastle.math.ec.ECPoint
import us.eharning.atomun.core.ec.ECDSA
import us.eharning.atomun.core.ec.ECKey
import us.eharning.atomun.core.ec.internal.BouncyCastleECKeyConstants.CURVE
import us.eharning.atomun.core.ec.internal.BouncyCastleECKeyConstants.DOMAIN
import java.io.ByteArrayOutputStream
import java.io.IOException
import java.math.BigInteger
import javax.annotation.concurrent.Immutable
/**
* Signature implementation using exposed secret exponent / public ECPoint.
*/
@Immutable
internal class BouncyCastleECSigner
/**
* Construct a signature operation with the given key material.
*
* @param privateExponent
* Private exponent from EC key - if present, signatures are allowed.
* @param publicPoint
* Public point on the Elliptical Curve, verification is dependent on this.
* @param canonicalize
* If true, then the signature point is canonicalized.
*/
@JvmOverloads constructor(
private val privateExponent: BigInteger?,
private val publicPoint: ECPoint,
private val canonicalize: Boolean = true
) : ECDSA {
/**
* Obtain an ECDSA instance with the given canonicalization bit set.
*
* @param canonicalize
* If true, then the signature point is canonicalized.
*
* @return
* ECDSA instance with canonicalization set to the given value.
*/
fun withCanonicalize(canonicalize: Boolean): BouncyCastleECSigner {
if (this.canonicalize == canonicalize) {
return this
}
return BouncyCastleECSigner(privateExponent, publicPoint, canonicalize)
}
/**
* Perform an ECDSA signature using the private key.
*
* @param hash
* byte array to sign.
*
* @return ASN.1 representation of the signature.
*/
override fun sign(hash: ByteArray): ByteArray {
if (null == privateExponent) {
throw UnsupportedOperationException("Cannot sign with public key")
}
/* The HMacDSAKCalculator is what makes this signer RFC 6979 compliant. */
val signer = ECDSASigner(RFC6979KCalculator(SHA256Digest()))
signer.init(true, ECPrivateKeyParameters(privateExponent, DOMAIN))
val signature = signer.generateSignature(hash)
/* Need to canonicalize signature up front ... */
if (canonicalize && signature[1] > HALF_CURVE_ORDER) {
/* BOP does not do this */
signature[1] = CURVE.n - signature[1]
}
return calculateSignature(signature)
}
/**
* Convert the DSA signature-parts into a byte array.
*
* @param signature
* ECDSA signature to convert.
*
* @return
* byte[] for of signature.
*/
@Throws(IOException::class)
fun calculateSignature(signature: Array<BigInteger>): ByteArray {
val stream = ByteArrayOutputStream()
val seq = DERSequenceGenerator(stream)
seq.addObject(ASN1Integer(signature[0]))
seq.addObject(ASN1Integer(signature[1]))
seq.close()
return stream.toByteArray()
}
/**
* Verify an ECDSA signature using the public key.
*
* @param hash
* byte array of the hash to verify.
* @param signature
* ASN.1 representation of the signature to verify hash with.
*
* @return true if the signature matches, else false.
*/
@SuppressWarnings("checkstyle:localvariablename")
override fun verify(hash: ByteArray, signature: ByteArray): Boolean {
try {
val signer = ECDSASigner()
signer.init(false, ECPublicKeyParameters(publicPoint, DOMAIN))
val seq = ASN1Sequence.getInstance(signature)
val r = seq.getObjectAt(0)
val s = seq.getObjectAt(1)
if (r !is ASN1Integer || s !is ASN1Integer) {
return false
}
return signer.verifySignature(hash, r.positiveValue, s.positiveValue)
} catch (e: Throwable) {
// treat format errors as invalid signatures
return false
}
}
companion object {
private val HALF_CURVE_ORDER = CURVE.n.shiftRight(1)
/**
* Obtain a signer given a private key - specifically a BouncyCastleECKeyPair.
*
* @param privateKey
* Key instance to collect data for signing from.
*
* @return
* ECDSA instance capable of signature and verification.
*/
@JvmStatic
fun fromPrivateKey(privateKey: ECKey): BouncyCastleECSigner {
assert(privateKey is BouncyCastleECKeyPair)
val publicPoint = CURVE.curve.decodePoint(privateKey.exportPublic())
val privateExponent = (privateKey as BouncyCastleECKeyPair).privateExponent
return BouncyCastleECSigner(privateExponent, publicPoint)
}
/**
* Obtain a signer given any public key.
*
* @param publicKey
* Key instance to collect data for verification from.
*
* @return
* ECDSA instance capable of verification.
*/
@JvmStatic
fun fromPublicKey(publicKey: ECKey): BouncyCastleECSigner {
val publicPoint = CURVE.curve.decodePoint(publicKey.exportPublic())
return BouncyCastleECSigner(null, publicPoint)
}
}
}
| apache-2.0 | e99bf5e0571c686e0f013f1fd4e960e7 | 35.217877 | 87 | 0.658646 | 4.745974 | false | false | false | false |
DemonWav/MinecraftDevIntelliJ | src/main/kotlin/com/demonwav/mcdev/nbt/lang/colors/NbttSyntaxHighlighter.kt | 1 | 3116 | /*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2020 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev.nbt.lang.colors
import com.demonwav.mcdev.nbt.lang.NbttLexerAdapter
import com.demonwav.mcdev.nbt.lang.gen.psi.NbttTypes
import com.intellij.openapi.editor.DefaultLanguageHighlighterColors
import com.intellij.openapi.editor.colors.TextAttributesKey
import com.intellij.openapi.fileTypes.SyntaxHighlighterBase
import com.intellij.psi.tree.IElementType
class NbttSyntaxHighlighter : SyntaxHighlighterBase() {
override fun getHighlightingLexer() = NbttLexerAdapter()
override fun getTokenHighlights(tokenType: IElementType): Array<TextAttributesKey> {
return when (tokenType) {
NbttTypes.BYTES, NbttTypes.INTS, NbttTypes.LONGS -> KEYWORD_KEYS
NbttTypes.STRING_LITERAL -> STRING_KEYS
NbttTypes.UNQUOTED_STRING_LITERAL -> UNQUOTED_STRING_KEYS
NbttTypes.BYTE_LITERAL -> BYTE_KEYS
NbttTypes.SHORT_LITERAL -> SHORT_KEYS
NbttTypes.INT_LITERAL -> INT_KEYS
NbttTypes.LONG_LITERAL -> LONG_KEYS
NbttTypes.FLOAT_LITERAL -> FLOAT_KEYS
NbttTypes.DOUBLE_LITERAL -> DOUBLE_KEYS
else -> EMPTY_KEYS
}
}
companion object {
val KEYWORD =
TextAttributesKey.createTextAttributesKey("NBTT_KEYWORD", DefaultLanguageHighlighterColors.KEYWORD)
val STRING = TextAttributesKey.createTextAttributesKey("NBTT_STRING", DefaultLanguageHighlighterColors.STRING)
val UNQUOTED_STRING = TextAttributesKey.createTextAttributesKey("NBTT_UNQUOTED_STRING", STRING)
val STRING_NAME = TextAttributesKey.createTextAttributesKey("NBTT_STRING_NAME", STRING)
val UNQUOTED_STRING_NAME = TextAttributesKey.createTextAttributesKey("NBTT_UNQUOTED_STRING_NAME", STRING_NAME)
val BYTE = TextAttributesKey.createTextAttributesKey("NBTT_BYTE", DefaultLanguageHighlighterColors.NUMBER)
val SHORT = TextAttributesKey.createTextAttributesKey("NBTT_SHORT", DefaultLanguageHighlighterColors.NUMBER)
val INT = TextAttributesKey.createTextAttributesKey("NBTT_INT", DefaultLanguageHighlighterColors.NUMBER)
val LONG = TextAttributesKey.createTextAttributesKey("NBTT_LONG", DefaultLanguageHighlighterColors.NUMBER)
val FLOAT = TextAttributesKey.createTextAttributesKey("NBTT_FLOAT", DefaultLanguageHighlighterColors.NUMBER)
val DOUBLE = TextAttributesKey.createTextAttributesKey("NBTT_DOUBLE", DefaultLanguageHighlighterColors.NUMBER)
val MATERIAL = TextAttributesKey.createTextAttributesKey("NBTT_MATERIAL", STRING)
val KEYWORD_KEYS = arrayOf(KEYWORD)
val STRING_KEYS = arrayOf(STRING)
val UNQUOTED_STRING_KEYS = arrayOf(UNQUOTED_STRING)
val BYTE_KEYS = arrayOf(BYTE)
val SHORT_KEYS = arrayOf(SHORT)
val INT_KEYS = arrayOf(INT)
val LONG_KEYS = arrayOf(LONG)
val FLOAT_KEYS = arrayOf(FLOAT)
val DOUBLE_KEYS = arrayOf(DOUBLE)
val EMPTY_KEYS = emptyArray<TextAttributesKey>()
}
}
| mit | b50521070dde87d4c01a072112def028 | 46.938462 | 118 | 0.731065 | 5.254637 | false | false | false | false |
paplorinc/intellij-community | platform/configuration-store-impl/src/defaultProjectElementNormalizer.kt | 2 | 6276 | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.configurationStore
import com.intellij.openapi.components.PersistentStateComponent
import com.intellij.openapi.components.StoragePathMacros
import com.intellij.openapi.components.impl.ComponentManagerImpl
import com.intellij.openapi.components.impl.ServiceManagerImpl
import com.intellij.openapi.diagnostic.runAndLogException
import com.intellij.openapi.module.impl.ModuleManagerImpl
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.JDOMUtil
import com.intellij.openapi.util.io.FileUtil
import com.intellij.util.*
import com.intellij.util.containers.forEachGuaranteed
import com.intellij.util.io.exists
import com.intellij.util.io.outputStream
import gnu.trove.THashSet
import org.jdom.Element
import java.nio.file.FileSystems
import java.nio.file.Path
internal fun normalizeDefaultProjectElement(defaultProject: Project, element: Element, projectConfigDir: Path) {
LOG.runAndLogException {
moveComponentConfiguration(defaultProject, element) { projectConfigDir.resolve(it) }
}
val iterator = element.getChildren("component").iterator()
for (component in iterator) {
val componentName = component.getAttributeValue("name")
fun writeProfileSettings(schemeDir: Path) {
component.removeAttribute("name")
if (component.isEmpty()) {
return
}
val wrapper = Element("component").setAttribute("name", componentName)
component.name = "settings"
wrapper.addContent(component)
val file = schemeDir.resolve("profiles_settings.xml")
if (file.fileSystem == FileSystems.getDefault()) {
// VFS must be used to write workspace.xml and misc.xml to ensure that project files will be not reloaded on external file change event
writeFile(file, fakeSaveSession, null, createDataWriterForElement(wrapper, "default project"), LineSeparator.LF,
prependXmlProlog = false)
}
else {
file.outputStream().use {
wrapper.write(it)
}
}
}
when (componentName) {
"InspectionProjectProfileManager" -> {
iterator.remove()
val schemeDir = projectConfigDir.resolve("inspectionProfiles")
convertProfiles(component.getChildren("profile").iterator(), componentName, schemeDir)
component.removeChild("version")
writeProfileSettings(schemeDir)
}
"CopyrightManager" -> {
iterator.remove()
val schemeDir = projectConfigDir.resolve("copyright")
convertProfiles(component.getChildren("copyright").iterator(), componentName, schemeDir)
writeProfileSettings(schemeDir)
}
ModuleManagerImpl.COMPONENT_NAME -> {
iterator.remove()
}
}
}
}
private fun convertProfiles(profileIterator: MutableIterator<Element>, componentName: String, schemeDir: Path) {
for (profile in profileIterator) {
val schemeName = profile.getChildren("option").find { it.getAttributeValue("name") == "myName" }?.getAttributeValue("value") ?: continue
profileIterator.remove()
val wrapper = Element("component").setAttribute("name", componentName)
wrapper.addContent(profile)
val path = schemeDir.resolve("${FileUtil.sanitizeFileName(schemeName, true)}.xml")
JDOMUtil.write(wrapper, path.outputStream(), "\n")
}
}
internal fun moveComponentConfiguration(defaultProject: Project, element: Element, fileResolver: (name: String) -> Path) {
val componentElements = element.getChildren("component")
if (componentElements.isEmpty()) {
return
}
val workspaceComponentNames = THashSet(listOf("GradleLocalSettings"))
val compilerComponentNames = THashSet<String>()
fun processComponents(aClass: Class<*>) {
val stateAnnotation = getStateSpec(aClass)
if (stateAnnotation == null || stateAnnotation.name.isEmpty()) {
return
}
val storage = stateAnnotation.storages.sortByDeprecated().firstOrNull() ?: return
when {
storage.path == StoragePathMacros.WORKSPACE_FILE -> workspaceComponentNames.add(stateAnnotation.name)
storage.path == "compiler.xml" -> compilerComponentNames.add(stateAnnotation.name)
}
}
@Suppress("DEPRECATION")
val projectComponents = defaultProject.getComponents(PersistentStateComponent::class.java)
projectComponents.forEachGuaranteed {
processComponents(it.javaClass)
}
ServiceManagerImpl.processAllImplementationClasses(defaultProject as ComponentManagerImpl) { aClass, _ ->
processComponents(aClass)
true
}
@Suppress("RemoveExplicitTypeArguments")
val elements = mapOf(compilerComponentNames to SmartList<Element>(), workspaceComponentNames to SmartList<Element>())
val iterator = componentElements.iterator()
for (componentElement in iterator) {
val name = componentElement.getAttributeValue("name") ?: continue
for ((names, list) in elements) {
if (names.contains(name)) {
iterator.remove()
list.add(componentElement)
}
}
}
for ((names, list) in elements) {
writeConfigFile(list, fileResolver(if (names === workspaceComponentNames) "workspace.xml" else "compiler.xml"))
}
}
private fun writeConfigFile(elements: List<Element>, file: Path) {
if (elements.isEmpty()) {
return
}
var wrapper = Element("project").setAttribute("version", "4")
if (file.exists()) {
try {
wrapper = loadElement(file)
}
catch (e: Exception) {
LOG.warn(e)
}
}
elements.forEach { wrapper.addContent(it) }
// .idea component configuration files uses XML prolog due to historical reasons
if (file.fileSystem == FileSystems.getDefault()) {
// VFS must be used to write workspace.xml and misc.xml to ensure that project files will be not reloaded on external file change event
writeFile(file, fakeSaveSession, null, createDataWriterForElement(wrapper, "default project"), LineSeparator.LF, prependXmlProlog = true)
}
else {
file.outputStream().use {
it.write(XML_PROLOG)
it.write(LineSeparator.LF.separatorBytes)
wrapper.write(it)
}
}
}
private val fakeSaveSession = object : SaveSession {
override fun save() {
}
} | apache-2.0 | b3ea1379ba50a0f5c2cd08cffe02c4cf | 35.283237 | 143 | 0.72355 | 4.850077 | false | true | false | false |
bclifton-exp/Accessiboard | Accessiboard/app/src/main/java/boomcity/accessiboard/MainActivity.kt | 1 | 8831 | package boomcity.accessiboard
import android.app.AlertDialog
import android.content.Context
import android.support.design.widget.TabLayout
import android.support.v7.app.AppCompatActivity
import android.support.v7.widget.Toolbar
import android.support.v4.app.Fragment
import android.support.v4.app.FragmentManager
import android.support.v4.app.FragmentPagerAdapter
import android.support.v4.view.ViewPager
import android.os.Bundle
import android.view.Menu
import android.view.MenuItem
import android.view.View
import com.github.clans.fab.FloatingActionButton
import com.github.clans.fab.FloatingActionMenu
import android.content.Intent
import android.app.Activity
import android.net.Uri
import android.speech.tts.TextToSpeech
import android.support.v7.widget.RecyclerView
import com.google.gson.*
import android.support.design.widget.AppBarLayout
class MainActivity : AppCompatActivity(), TabLayout.OnTabSelectedListener, TextToSpeech.OnInitListener {
private var mSectionsPagerAdapter: SectionsPagerAdapter? = null
lateinit var tts: TextToSpeech
lateinit var mViewPager: ViewPager
lateinit var mToolBar: Toolbar
lateinit var tabLayout: TabLayout
lateinit var tabFAM: FloatingActionMenu
lateinit var renameTabFab: FloatingActionButton
lateinit var deleteTabFab: FloatingActionButton
companion object {
val READ_REQUEST_CODE = 42
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
tts = TextToSpeech(this, this)
mToolBar = findViewById(R.id.toolbar) as Toolbar
setSupportActionBar(mToolBar)
getStoredTabData()
mSectionsPagerAdapter = SectionsPagerAdapter(supportFragmentManager)
mViewPager = findViewById(R.id.container) as ViewPager
mViewPager.adapter = mSectionsPagerAdapter
mViewPager.setOffscreenPageLimit(10) //10 max tabs
DataService.setViewpager(mViewPager)
tabLayout = findViewById(R.id.tabs) as TabLayout
tabLayout.setupWithViewPager(mViewPager)
tabLayout.addOnTabSelectedListener(this)
tabFAM = findViewById(R.id.tab_FAM) as FloatingActionMenu
renameTabFab = findViewById(R.id.floating_menu_rename) as FloatingActionButton
deleteTabFab = findViewById(R.id.floating_menu_delete) as FloatingActionButton
tabFAM.visibility = View.INVISIBLE
renameTabFab.setOnClickListener({
renameTab()
})
deleteTabFab.setOnClickListener({
deleteTab()
})
}
private fun getStoredTabData() {
val sharedPrefs = getPreferences(Context.MODE_PRIVATE)
val gson = Gson()
val json = sharedPrefs.getString("TabsDataInfo", "")
var tabsData = gson.fromJson<TabsData>(json, TabsData::class.java)
if (tabsData == null) {
//first startup
val defaultTabSounds = mutableListOf<TtsObject>(TtsObject("Default TTS Object","Some tts phrase here"))
tabsData = TabsData(mutableListOf(TabDataInfo("All",0, defaultTabSounds),TabDataInfo("Favorites", 1, mutableListOf())))
}
DataService.init(tabsData,sharedPrefs)
}
fun addNewTab(tabName: String) {
tabLayout.addTab(tabLayout.newTab())
mSectionsPagerAdapter!!.addNewTab(tabName)
}
fun renameTab() {
val newFragment = EditDialogFragment(this)
newFragment.show(fragmentManager, tabLayout.selectedTabPosition.toString())
tabFAM.close(true)
}
fun deleteTab() {
val selectedTabIndex = tabLayout.selectedTabPosition
if (selectedTabIndex > 1) {
mSectionsPagerAdapter!!.removeTab(selectedTabIndex)
val tab = tabLayout.getTabAt(selectedTabIndex - 1)
tab!!.select()
tabFAM.close(true)
}
}
fun newSoundClipName(ttsObjectName: String, audioUri: String) {
if (DataService.getTabsData().getTab(0)!!.ttsObjects.any { tts -> tts.Title.toLowerCase() == ttsObjectName.toLowerCase() }) {
val errorBuilder = AlertDialog.Builder(this, R.style.DankAlertDialogStyle)
errorBuilder.setTitle(R.string.tab_name_in_use)
errorBuilder.setNegativeButton(R.string.dialog_aight, { dialog, which ->
dialog.dismiss()
})
errorBuilder.show()
}
else {
val newTtsObject = TtsObject(ttsObjectName, "Default phrase text" ,System.currentTimeMillis().toInt()) //TODO set the textbox text in here
DataService.addTtsObjectToTab(newTtsObject, 0)
goToNewlyCreatedTtsObject()
}
}
private fun goToNewlyCreatedTtsObject() {
tabLayout.getTabAt(0)!!.select()
val recyclerView = mViewPager.getChildAt(0).findViewById(R.id.recycler_view) as RecyclerView
val check = recyclerView.adapter.itemCount
recyclerView.verticalScrollbarPosition = check
recyclerView.smoothScrollToPosition(check - 1)
if (mToolBar.getParent() is AppBarLayout) {
(mToolBar.getParent() as AppBarLayout).setExpanded(false,true)
}
}
override fun onTabReselected(tab: TabLayout.Tab?) {
}
override fun onTabUnselected(tab: TabLayout.Tab?) {
}
override fun onTabSelected(tab: TabLayout.Tab?) {
if (tab!!.position != 0){
tabFAM.visibility = View.VISIBLE
}
else {
tabFAM.visibility = View.INVISIBLE
}
deleteTabFab.isEnabled = tab.position > 1
tabFAM.close(true)
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
menuInflater.inflate(R.menu.menu_main, menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
val id = item.itemId
if (id == R.id.action_new_tab) {
if (tabLayout.tabCount < 8) {
val newFragment = EditDialogFragment(this)
newFragment.show(fragmentManager, null)
return true
}
else {
val errorBuilder = AlertDialog.Builder(this, R.style.DankAlertDialogStyle)
errorBuilder.setTitle("Ya'll got too many tabs dawg.")
errorBuilder.setNegativeButton(R.string.dialog_aight, { dialog, which ->
dialog.dismiss()
})
errorBuilder.show()
}
}
if (id == R.id.action_new_sound) {
val intent = Intent(Intent.ACTION_OPEN_DOCUMENT)
intent.addCategory(Intent.CATEGORY_OPENABLE)
intent.type = "audio/*"
startActivityForResult(intent, READ_REQUEST_CODE)
}
if (id == R.id.action_new_speech_clip) {
tts.speak("This is some text yolo", TextToSpeech.QUEUE_FLUSH, null)
//TODO this is it here for TTS
//dont forget to call shutdown on this...maybe we dont need to do that at all actually since..well its TTS app..
}
return super.onOptionsItemSelected(item)
}
override fun onInit(status: Int) {
if (status == TextToSpeech.SUCCESS) {
val language = tts.language
val result = tts.setLanguage(language)
if (result == TextToSpeech.LANG_MISSING_DATA || result == TextToSpeech.LANG_NOT_SUPPORTED) {
//fuck
}
}
}
public override fun onActivityResult(requestCode: Int, resultCode: Int, resultData: Intent?) {
if (requestCode == READ_REQUEST_CODE && resultCode == Activity.RESULT_OK) {
val audioUri: Uri
if (resultData != null) {
audioUri = resultData.data
val newSoundNameFragment = NewSoundClipDialogFragment(this)
newSoundNameFragment.show(fragmentManager,audioUri.toString())
}
}
}
inner class SectionsPagerAdapter(fm: FragmentManager) : FragmentPagerAdapter(fm) {
private var tabCount: Int = DataService.getTabsData().tabsList!!.size
override fun getItem(position: Int): Fragment {
return TabFragment.newInstance(position)
}
override fun getCount(): Int {
return tabCount
}
override fun getPageTitle(position: Int): CharSequence? {
when (position) {
0 -> return "All"
}
return DataService.getTabsData().tabsList!![position].name
}
fun addNewTab(tabName: String) {
DataService.addNewTab(tabName, tabCount)
tabCount++
notifyDataSetChanged()
}
fun removeTab(tabIndex: Int) {
DataService.deleteTab(tabIndex)
tabCount--
notifyDataSetChanged()
}
}
}
| gpl-3.0 | 15dde7366ff1955998d700d9c3602b4e | 34.608871 | 150 | 0.647832 | 4.900666 | false | false | false | false |
google/intellij-community | python/ide/impl/src/com/jetbrains/python/sdk/configuration/PyPoetrySdkConfiguration.kt | 6 | 5705 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.jetbrains.python.sdk.configuration
import com.intellij.codeInspection.util.IntentionName
import com.intellij.execution.ExecutionException
import com.intellij.ide.util.PropertiesComponent
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.module.Module
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.projectRoots.ProjectJdkTable
import com.intellij.openapi.projectRoots.Sdk
import com.intellij.openapi.projectRoots.impl.SdkConfigurationUtil
import com.intellij.openapi.ui.DialogWrapper
import com.intellij.openapi.ui.ValidationInfo
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.vfs.LocalFileSystem
import com.intellij.openapi.vfs.StandardFileSystems
import com.intellij.ui.IdeBorderFactory
import com.intellij.ui.components.JBLabel
import com.intellij.util.ui.JBUI
import com.jetbrains.python.PyCharmCommunityCustomizationBundle
import com.jetbrains.python.sdk.*
import com.jetbrains.python.sdk.poetry.*
import java.awt.BorderLayout
import java.awt.Insets
import javax.swing.JComponent
import javax.swing.JPanel
/**
* This source code is created by @koxudaxi Koudai Aono <[email protected]>
*/
class PyPoetrySdkConfiguration : PyProjectSdkConfigurationExtension {
private val LOGGER = Logger.getInstance(PyPoetrySdkConfiguration::class.java)
override fun createAndAddSdkForConfigurator(module: Module): Sdk? = createAndAddSDk(module, false)
override fun getIntention(module: Module): @IntentionName String? =
module.pyProjectToml?.let { PyCharmCommunityCustomizationBundle.message("sdk.create.poetry.environment", it.name) }
override fun createAndAddSdkForInspection(module: Module): Sdk? = createAndAddSDk(module, true)
private fun createAndAddSDk(module: Module, inspection: Boolean): Sdk? {
val poetryEnvExecutable = askForEnvData(module, inspection) ?: return null
PropertiesComponent.getInstance().poetryPath = poetryEnvExecutable.poetryPath
return createPoetry(module)
}
private fun askForEnvData(module: Module, inspection: Boolean): PyAddNewPoetryFromFilePanel.Data? {
val poetryExecutable = getPoetryExecutable()?.absolutePath
if (inspection && validatePoetryExecutable(poetryExecutable) == null) {
return PyAddNewPoetryFromFilePanel.Data(poetryExecutable!!)
}
var permitted = false
var envData: PyAddNewPoetryFromFilePanel.Data? = null
ApplicationManager.getApplication().invokeAndWait {
val dialog = Dialog(module)
permitted = dialog.showAndGet()
envData = dialog.envData
LOGGER.debug("Dialog exit code: ${dialog.exitCode}, $permitted")
}
return if (permitted) envData else null
}
private fun createPoetry(module: Module): Sdk? {
ProgressManager.progress(PyCharmCommunityCustomizationBundle.message("sdk.progress.text.setting.up.poetry.environment"))
LOGGER.debug("Creating poetry environment")
val basePath = module.basePath ?: return null
val poetry = try {
val init = StandardFileSystems.local().findFileByPath(basePath)?.findChild(PY_PROJECT_TOML)?.let {
getPyProjectTomlForPoetry(it)
} == null
setupPoetry(FileUtil.toSystemDependentName(basePath), null, true, init)
}
catch (e: ExecutionException) {
LOGGER.warn("Exception during creating poetry environment", e)
showSdkExecutionException(null, e,
PyCharmCommunityCustomizationBundle.message("sdk.dialog.title.failed.to.create.poetry.environment"))
return null
}
val path = PythonSdkUtil.getPythonExecutable(poetry).also {
if (it == null) {
LOGGER.warn("Python executable is not found: $poetry")
}
} ?: return null
val file = LocalFileSystem.getInstance().refreshAndFindFileByPath(path).also {
if (it == null) {
LOGGER.warn("Python executable file is not found: $path")
}
} ?: return null
LOGGER.debug("Setting up associated poetry environment: $path, $basePath")
val sdk = SdkConfigurationUtil.setupSdk(
ProjectJdkTable.getInstance().allJdks,
file,
PythonSdkType.getInstance(),
false,
null,
suggestedSdkName(basePath)
) ?: return null
ApplicationManager.getApplication().invokeAndWait {
LOGGER.debug("Adding associated poetry environment: $path, $basePath")
SdkConfigurationUtil.addSdk(sdk)
sdk.isPoetry = true
sdk.associateWithModule(module, null)
}
return sdk
}
private class Dialog(module: Module) : DialogWrapper(module.project, false, IdeModalityType.PROJECT) {
private val panel = PyAddNewPoetryFromFilePanel(module)
val envData
get() = panel.envData
init {
title = PyCharmCommunityCustomizationBundle.message("sdk.dialog.title.setting.up.poetry.environment")
init()
}
override fun createCenterPanel(): JComponent {
return JPanel(BorderLayout()).apply {
val border = IdeBorderFactory.createEmptyBorder(Insets(4, 0, 6, 0))
val message = PyCharmCommunityCustomizationBundle.message("sdk.notification.label.create.poetry.environment.from.pyproject.toml.dependencies")
add(
JBUI.Panels.simplePanel(JBLabel(message)).withBorder(border),
BorderLayout.NORTH
)
add(panel, BorderLayout.CENTER)
}
}
override fun postponeValidation(): Boolean = false
override fun doValidateAll(): List<ValidationInfo> = panel.validateAll()
}
} | apache-2.0 | db319cc72ade8e9d15a5168d576def3b | 36.294118 | 158 | 0.744961 | 4.695473 | false | true | false | false |
JetBrains/intellij-community | platform/build-scripts/dev-server/src/DevIdeaBuildServer.kt | 1 | 7415 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
@file:Suppress("ReplaceGetOrSet", "ReplacePutWithAssignment")
package org.jetbrains.intellij.build.devServer
import com.intellij.openapi.util.io.NioFiles
import com.sun.net.httpserver.HttpContext
import com.sun.net.httpserver.HttpExchange
import com.sun.net.httpserver.HttpServer
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.runBlocking
import java.net.HttpURLConnection
import java.net.InetAddress
import java.net.InetSocketAddress
import java.net.URI
import java.nio.file.Files
import java.nio.file.Path
import java.util.concurrent.CountDownLatch
import java.util.concurrent.Executors
import java.util.concurrent.Semaphore
import kotlin.system.exitProcess
private enum class DevIdeaBuildServerStatus {
OK,
FAILED,
IN_PROGRESS,
UNDEFINED
}
object DevIdeaBuildServer {
private const val SERVER_PORT = 20854
private val buildQueueLock = Semaphore(1, true)
private val doneSignal = CountDownLatch(1)
// <product / DevIdeaBuildServerStatus>
private var productBuildStatus = HashMap<String, DevIdeaBuildServerStatus>()
@JvmStatic
fun main(args: Array<String>) {
initLog()
try {
start()
}
catch (e: ConfigurationException) {
e.printStackTrace()
exitProcess(1)
}
}
private fun start() {
val additionalModules = getAdditionalModules()?.toList()
val homePath = getHomePath()
val productionClassOutput = (System.getenv("CLASSES_DIR")?.let { Path.of(it).toAbsolutePath().normalize() }
?: homePath.resolve("out/classes/production"))
val httpServer = createHttpServer(
buildServer = BuildServer(
homePath = homePath,
productionClassOutput = productionClassOutput
),
requestTemplate = BuildRequest(
platformPrefix = "",
additionalModules = additionalModules ?: emptyList(),
homePath = homePath,
productionClassOutput = productionClassOutput,
)
)
println("Listening on ${httpServer.address.hostString}:${httpServer.address.port}")
println(
"Custom plugins: ${additionalModules?.joinToString() ?: "not set (use VM property `additional.modules` to specify additional module ids)"}")
println(
"Run IDE on module intellij.platform.bootstrap with VM properties -Didea.use.dev.build.server=true -Djava.system.class.loader=com.intellij.util.lang.PathClassLoader")
httpServer.start()
// wait for ctrl-c
Runtime.getRuntime().addShutdownHook(Thread {
doneSignal.countDown()
})
try {
doneSignal.await()
}
catch (ignore: InterruptedException) {
}
println("Server stopping...")
httpServer.stop(10)
exitProcess(0)
}
private fun HttpExchange.getPlatformPrefix() = parseQuery(this.requestURI).get("platformPrefix")?.first() ?: "idea"
private fun createBuildEndpoint(httpServer: HttpServer,
buildServer: BuildServer,
requestTemplate: BuildRequest): HttpContext? {
return httpServer.createContext("/build") { exchange ->
val platformPrefix = exchange.getPlatformPrefix()
var statusMessage: String
var statusCode = HttpURLConnection.HTTP_OK
productBuildStatus.put(platformPrefix, DevIdeaBuildServerStatus.UNDEFINED)
try {
productBuildStatus.put(platformPrefix, DevIdeaBuildServerStatus.IN_PROGRESS)
buildQueueLock.acquire()
exchange.responseHeaders.add("Content-Type", "text/plain")
runBlocking(Dispatchers.Default) {
val ideBuilder = buildServer.checkOrCreateIdeBuilder(requestTemplate.copy(platformPrefix = platformPrefix))
statusMessage = ideBuilder.pluginBuilder.buildChanged()
}
println(statusMessage)
}
catch (e: ConfigurationException) {
statusCode = HttpURLConnection.HTTP_BAD_REQUEST
productBuildStatus.put(platformPrefix, DevIdeaBuildServerStatus.FAILED)
statusMessage = e.message!!
}
catch (e: Throwable) {
productBuildStatus.put(platformPrefix, DevIdeaBuildServerStatus.FAILED)
exchange.sendResponseHeaders(HttpURLConnection.HTTP_UNAVAILABLE, -1)
System.err.println("Cannot handle build request: ")
e.printStackTrace()
return@createContext
}
finally {
buildQueueLock.release()
}
productBuildStatus.put(platformPrefix, if (statusCode == HttpURLConnection.HTTP_OK) {
DevIdeaBuildServerStatus.OK
}
else {
DevIdeaBuildServerStatus.FAILED
})
val response = statusMessage.encodeToByteArray()
exchange.sendResponseHeaders(statusCode, response.size.toLong())
exchange.responseBody.apply {
this.write(response)
this.flush()
this.close()
}
}
}
private fun createStatusEndpoint(httpServer: HttpServer): HttpContext? {
return httpServer.createContext("/status") { exchange ->
val platformPrefix = exchange.getPlatformPrefix()
val buildStatus = productBuildStatus.getOrDefault(platformPrefix, DevIdeaBuildServerStatus.UNDEFINED)
exchange.responseHeaders.add("Content-Type", "text/plain")
val response = buildStatus.toString().encodeToByteArray()
exchange.sendResponseHeaders(HttpURLConnection.HTTP_OK, response.size.toLong())
exchange.responseBody.apply {
this.write(response)
this.flush()
this.close()
}
}
}
private fun createStopEndpoint(httpServer: HttpServer): HttpContext? {
return httpServer.createContext("/stop") { exchange ->
exchange.responseHeaders.add("Content-Type", "text/plain")
val response = "".encodeToByteArray()
exchange.sendResponseHeaders(HttpURLConnection.HTTP_OK, response.size.toLong())
exchange.responseBody.apply {
this.write(response)
this.flush()
this.close()
}
doneSignal.countDown()
}
}
private fun createHttpServer(buildServer: BuildServer, requestTemplate: BuildRequest): HttpServer {
val httpServer = HttpServer.create()
httpServer.bind(InetSocketAddress(InetAddress.getLoopbackAddress(), SERVER_PORT), 2)
createBuildEndpoint(httpServer, buildServer, requestTemplate)
createStatusEndpoint(httpServer)
createStopEndpoint(httpServer)
// Serve requests in parallel. Though, there is no guarantee, that 2 requests will be served for different endpoints
httpServer.executor = Executors.newFixedThreadPool(2)
return httpServer
}
}
private fun parseQuery(url: URI): Map<String, List<String?>> {
val query = url.query ?: return emptyMap()
return query.splitToSequence("&")
.map {
val index = it.indexOf('=')
val key = if (index > 0) it.substring(0, index) else it
val value = if (index > 0 && it.length > index + 1) it.substring(index + 1) else null
java.util.Map.entry(key, value)
}
.groupBy(keySelector = { it.key }, valueTransform = { it.value })
}
internal fun doClearDirContent(child: Path) {
Files.newDirectoryStream(child).use { stream ->
for (child in stream) {
NioFiles.deleteRecursively(child)
}
}
}
internal fun clearDirContent(dir: Path): Boolean {
if (!Files.isDirectory(dir)) {
return false
}
doClearDirContent(dir)
return true
} | apache-2.0 | a6c9654e27eb78345cb82683635b58c2 | 32.556561 | 172 | 0.698314 | 4.840078 | false | false | false | false |
StephaneBg/ScoreIt | data/src/main/kotlin/com/sbgapps/scoreit/data/repository/BillingRepo.kt | 1 | 1209 | /*
* Copyright 2020 Stéphane Baiget
*
* 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.sbgapps.scoreit.data.repository
import android.app.Activity
import com.android.billingclient.api.SkuDetails
interface BillingRepo {
fun getDonationSkus(): List<SkuDetails>?
fun startBillingFlow(activity: Activity, skuDetails: SkuDetails, callback: () -> Unit)
companion object {
const val COFFEE = "com.sbgapps.scoreit.coffee"
const val BEER = "com.sbgapps.scoreit.beer"
}
}
fun List<SkuDetails>.getBeerSku(): SkuDetails? = firstOrNull { it.sku == BillingRepo.BEER }
fun List<SkuDetails>.getCoffeeSku(): SkuDetails? = firstOrNull { it.sku == BillingRepo.COFFEE }
| apache-2.0 | 235cea5afbf7168a8cbae7f7c4d7f5a1 | 34.529412 | 95 | 0.737583 | 4.108844 | false | false | false | false |
allotria/intellij-community | platform/lang-impl/src/com/intellij/workspaceModel/ide/impl/legacyBridge/module/roots/ModuleRootComponentBridge.kt | 2 | 8380 | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.workspaceModel.ide.impl.legacyBridge.module.roots
import com.intellij.openapi.Disposable
import com.intellij.openapi.extensions.ExtensionPointListener
import com.intellij.openapi.extensions.PluginDescriptor
import com.intellij.openapi.module.Module
import com.intellij.openapi.projectRoots.Sdk
import com.intellij.openapi.roots.*
import com.intellij.openapi.roots.impl.ModuleOrderEnumerator
import com.intellij.openapi.roots.impl.OrderRootsCache
import com.intellij.openapi.roots.impl.RootConfigurationAccessor
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.workspaceModel.ide.impl.legacyBridge.RootConfigurationAccessorForWorkspaceModel
import com.intellij.workspaceModel.ide.legacyBridge.ModuleBridge
import com.intellij.workspaceModel.storage.CachedValue
import com.intellij.workspaceModel.storage.WorkspaceEntityStorage
import com.intellij.workspaceModel.storage.WorkspaceEntityStorageBuilder
import com.intellij.workspaceModel.storage.url.VirtualFileUrl
import com.intellij.workspaceModel.storage.impl.DisposableCachedValue
import com.intellij.workspaceModel.ide.impl.legacyBridge.module.CompilerModuleExtensionBridge
import com.intellij.workspaceModel.ide.impl.legacyBridge.module.ModuleManagerComponentBridge.Companion.findModuleEntity
import org.jetbrains.jps.model.module.JpsModuleSourceRoot
import org.jetbrains.jps.model.module.JpsModuleSourceRootType
class ModuleRootComponentBridge(
private val currentModule: Module
) : ModuleRootManagerEx(), Disposable, ModuleRootModelBridge {
override val moduleBridge = currentModule as ModuleBridge
private val orderRootsCache = OrderRootsCacheBridge(currentModule.project, currentModule)
private val modelValue = DisposableCachedValue(
{ moduleBridge.entityStorage },
CachedValue { storage ->
RootModelBridgeImpl(
moduleEntity = storage.findModuleEntity(moduleBridge),
storage = storage,
itemUpdater = null,
// TODO
rootModel = this,
updater = null
)
}).also { Disposer.register(this, it) }
internal val moduleLibraryTable: ModuleLibraryTableBridgeImpl = ModuleLibraryTableBridgeImpl(moduleBridge)
fun getModuleLibraryTable(): ModuleLibraryTableBridge {
return moduleLibraryTable
}
init {
MODULE_EXTENSION_NAME.getPoint(moduleBridge).addExtensionPointListener(object : ExtensionPointListener<ModuleExtension?> {
override fun extensionAdded(extension: ModuleExtension, pluginDescriptor: PluginDescriptor) {
dropRootModelCache()
}
override fun extensionRemoved(extension: ModuleExtension, pluginDescriptor: PluginDescriptor) {
dropRootModelCache()
}
}, false, null)
}
private val model: RootModelBridgeImpl
get() = modelValue.value
override val storage: WorkspaceEntityStorage
get() = moduleBridge.entityStorage.current
override val accessor: RootConfigurationAccessor
get() = RootConfigurationAccessor.DEFAULT_INSTANCE
override fun getOrCreateJpsRootProperties(sourceRootUrl: VirtualFileUrl, creator: () -> JpsModuleSourceRoot): JpsModuleSourceRoot {
return creator()
}
override fun removeCachedJpsRootProperties(sourceRootUrl: VirtualFileUrl) {
}
override fun dispose() = Unit
override fun dropCaches() {
orderRootsCache.clearCache()
dropRootModelCache()
}
internal fun dropRootModelCache() {
modelValue.dropCache()
}
override fun getModificationCountForTests(): Long = moduleBridge.entityStorage.version
override fun getExternalSource(): ProjectModelExternalSource? =
ExternalProjectSystemRegistry.getInstance().getExternalSource(module)
override fun getFileIndex(): ModuleFileIndex = currentModule.getService(ModuleFileIndex::class.java)!!
override fun getModifiableModel(): ModifiableRootModel = getModifiableModel(RootConfigurationAccessor.DEFAULT_INSTANCE)
override fun getModifiableModel(accessor: RootConfigurationAccessor): ModifiableRootModel = ModifiableRootModelBridgeImpl(
WorkspaceEntityStorageBuilder.from(moduleBridge.entityStorage.current),
moduleBridge,
moduleBridge.entityStorage.current, accessor)
/**
* This method is used in Project Structure dialog to ensure that changes made in {@link ModifiableModuleModel} after creation
* of this {@link ModifiableRootModel} are available in its storage and references in its {@link OrderEntry} can be resolved properly.
*/
override fun getModifiableModelForMultiCommit(accessor: RootConfigurationAccessor): ModifiableRootModel = ModifiableRootModelBridgeImpl(
(moduleBridge.diff as? WorkspaceEntityStorageBuilder) ?: (accessor as? RootConfigurationAccessorForWorkspaceModel)?.actualDiffBuilder
?: WorkspaceEntityStorageBuilder.from(moduleBridge.entityStorage.current),
moduleBridge,
moduleBridge.entityStorage.current, accessor)
fun getModifiableModel(diff: WorkspaceEntityStorageBuilder,
initialStorage: WorkspaceEntityStorage,
accessor: RootConfigurationAccessor): ModifiableRootModel = ModifiableRootModelBridgeImpl(diff, moduleBridge,
initialStorage, accessor,
false)
override fun getDependencies(): Array<Module> = moduleDependencies
override fun getDependencies(includeTests: Boolean): Array<Module> = getModuleDependencies(includeTests = includeTests)
override fun isDependsOn(module: Module): Boolean = orderEntries.any { it is ModuleOrderEntry && it.module == module }
override fun getExcludeRoots(): Array<VirtualFile> = model.excludeRoots
override fun orderEntries(): OrderEnumerator = ModuleOrderEnumerator(this, orderRootsCache)
private val compilerModuleExtension by lazy {
CompilerModuleExtensionBridge(moduleBridge, entityStorage = moduleBridge.entityStorage, diff = null)
}
private val compilerModuleExtensionClass = CompilerModuleExtension::class.java
override fun <T : Any?> getModuleExtension(klass: Class<T>): T? {
if (compilerModuleExtensionClass.isAssignableFrom(klass)) {
@Suppress("UNCHECKED_CAST")
return compilerModuleExtension as T
}
return model.getModuleExtension(klass)
}
override fun getDependencyModuleNames(): Array<String> = model.dependencyModuleNames
override fun getModule(): Module = currentModule
override fun isSdkInherited(): Boolean = model.isSdkInherited
override fun getOrderEntries(): Array<OrderEntry> = model.orderEntries
override fun getSourceRootUrls(): Array<String> = model.sourceRootUrls
override fun getSourceRootUrls(includingTests: Boolean): Array<String> = model.getSourceRootUrls(includingTests)
override fun getContentEntries(): Array<ContentEntry> = model.contentEntries
override fun getExcludeRootUrls(): Array<String> = model.excludeRootUrls
override fun <R : Any?> processOrder(policy: RootPolicy<R>, initialValue: R): R = model.processOrder(policy, initialValue)
override fun getSdk(): Sdk? = model.sdk
override fun getSourceRoots(): Array<VirtualFile> = model.sourceRoots
override fun getSourceRoots(includingTests: Boolean): Array<VirtualFile> = model.getSourceRoots(includingTests)
override fun getSourceRoots(rootType: JpsModuleSourceRootType<*>): MutableList<VirtualFile> = model.getSourceRoots(rootType)
override fun getSourceRoots(rootTypes: MutableSet<out JpsModuleSourceRootType<*>>): MutableList<VirtualFile> = model.getSourceRoots(
rootTypes)
override fun getContentRoots(): Array<VirtualFile> = model.contentRoots
override fun getContentRootUrls(): Array<String> = model.contentRootUrls
override fun getModuleDependencies(): Array<Module> = model.moduleDependencies
override fun getModuleDependencies(includeTests: Boolean): Array<Module> = model.getModuleDependencies(includeTests)
companion object {
@JvmStatic
fun getInstance(module: Module): ModuleRootComponentBridge = ModuleRootManager.getInstance(module) as ModuleRootComponentBridge
}
}
| apache-2.0 | b92e2c943f35cceb834d8376e2a851fb | 48.005848 | 140 | 0.770883 | 5.876578 | false | true | false | false |
allotria/intellij-community | platform/diagnostic/src/startUpPerformanceReporter/IdeIdeaFormatWriter.kt | 1 | 8070 | // 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.diagnostic.startUpPerformanceReporter
import com.fasterxml.jackson.core.JsonGenerator
import com.intellij.diagnostic.ActivityImpl
import com.intellij.diagnostic.StartUpMeasurer
import com.intellij.diagnostic.ThreadNameManager
import com.intellij.ide.plugins.IdeaPluginDescriptorImpl
import com.intellij.ide.plugins.PluginManagerCore
import com.intellij.ide.plugins.cl.PluginAwareClassLoader
import com.intellij.openapi.application.ApplicationInfo
import com.intellij.openapi.diagnostic.Logger
import com.intellij.ui.icons.IconLoadMeasurer
import com.intellij.util.io.jackson.array
import com.intellij.util.io.jackson.obj
import com.intellij.util.lang.ClassPath
import it.unimi.dsi.fastutil.objects.Object2IntOpenHashMap
import it.unimi.dsi.fastutil.objects.Object2LongOpenHashMap
import org.bouncycastle.crypto.generators.Argon2BytesGenerator
import org.bouncycastle.crypto.params.Argon2Parameters
import java.lang.invoke.MethodHandles
import java.lang.invoke.MethodType
import java.lang.management.ManagementFactory
import java.time.ZoneId
import java.time.ZonedDateTime
import java.time.format.DateTimeFormatter
import java.util.*
import java.util.concurrent.TimeUnit
internal class IdeIdeaFormatWriter(activities: Map<String, MutableList<ActivityImpl>>,
private val pluginCostMap: MutableMap<String, Object2LongOpenHashMap<String>>,
threadNameManager: ThreadNameManager) : IdeaFormatWriter(activities, threadNameManager, StartUpPerformanceReporter.VERSION) {
val publicStatMetrics = Object2IntOpenHashMap<String>()
init {
publicStatMetrics.defaultReturnValue(-1)
}
fun writeToLog(log: Logger) {
stringWriter.write("\n=== Stop: StartUp Measurement ===")
log.info(stringWriter.toString())
}
override fun writeAppInfo(writer: JsonGenerator) {
val appInfo = ApplicationInfo.getInstance()
writer.writeStringField("build", appInfo.build.asStringWithoutProductCode())
writer.writeStringField("buildDate", ZonedDateTime.ofInstant(appInfo.buildDate.toInstant(), ZoneId.systemDefault()).format(DateTimeFormatter.RFC_1123_DATE_TIME))
writer.writeStringField("productCode", appInfo.build.productCode)
// see CDSManager from platform-impl
@Suppress("SpellCheckingInspection")
if (ManagementFactory.getRuntimeMXBean().inputArguments.any { it == "-Xshare:auto" || it == "-Xshare:on" }) {
writer.writeBooleanField("cds", true)
}
}
override fun writeProjectName(writer: JsonGenerator, projectName: String) {
writer.writeStringField("project", System.getProperty("idea.performanceReport.projectName") ?: safeHashValue(projectName))
}
override fun writeExtraData(writer: JsonGenerator) {
val stats = getClassAndResourceLoadingStats()
writer.obj("classLoading") {
val time = stats.getValue("classLoadingTime")
writer.writeNumberField("time", TimeUnit.NANOSECONDS.toMillis(time))
val defineTime = stats.getValue("classDefineTime")
writer.writeNumberField("searchTime", TimeUnit.NANOSECONDS.toMillis(time - defineTime))
writer.writeNumberField("defineTime", TimeUnit.NANOSECONDS.toMillis(defineTime))
writer.writeNumberField("count", stats.getValue("classRequests"))
}
writer.obj("resourceLoading") {
writer.writeNumberField("time", TimeUnit.NANOSECONDS.toMillis(stats.getValue("resourceLoadingTime")))
writer.writeNumberField("count", stats.getValue("resourceRequests"))
}
writeServiceStats(writer)
writeIcons(writer)
}
private fun getClassAndResourceLoadingStats(): Map<String, Long> {
// data from bootstrap classloader
val classLoader = IdeIdeaFormatWriter::class.java.classLoader
@Suppress("UNCHECKED_CAST")
val stats = MethodHandles.lookup()
.findVirtual(classLoader::class.java, "getLoadingStats", MethodType.methodType(Map::class.java))
.bindTo(classLoader).invokeExact() as MutableMap<String, Long>
// data from core classloader
val coreStats = ClassPath.getLoadingStats()
if (coreStats.get("identity") != stats.get("identity")) {
for (entry in coreStats.entries) {
val v1 = stats.getValue(entry.key)
if (v1 != entry.value) {
stats.put(entry.key, v1 + entry.value)
}
}
}
return stats
}
override fun writeItemTimeInfo(item: ActivityImpl, duration: Long, offset: Long, writer: JsonGenerator) {
if (item.name == "bootstrap" || item.name == "app initialization") {
publicStatMetrics.put(item.name, TimeUnit.NANOSECONDS.toMillis(duration).toInt())
}
super.writeItemTimeInfo(item, duration, offset, writer)
}
override fun writeTotalDuration(writer: JsonGenerator, totalDuration: Long, end: Long, timeOffset: Long): Long {
val totalDurationActual = super.writeTotalDuration(writer, totalDuration, end, timeOffset)
publicStatMetrics.put("totalDuration", totalDurationActual.toInt())
return totalDurationActual
}
override fun beforeActivityWrite(item: ActivityImpl, ownOrTotalDuration: Long, fieldName: String) {
item.pluginId?.let {
StartUpMeasurer.doAddPluginCost(it, item.category?.name ?: "unknown", ownOrTotalDuration, pluginCostMap)
}
if (fieldName == "prepareAppInitActivities" && item.name == "splash initialization") {
publicStatMetrics.put("splash", TimeUnit.NANOSECONDS.toMillis(ownOrTotalDuration).toInt())
}
}
}
private fun writeIcons(writer: JsonGenerator) {
writer.array("icons") {
for (stat in IconLoadMeasurer.getStats()) {
writer.obj {
writer.writeStringField("name", stat.name)
writer.writeNumberField("count", stat.count)
writer.writeNumberField("time", TimeUnit.NANOSECONDS.toMillis(stat.totalDuration))
}
}
}
}
private fun safeHashValue(value: String): String {
val generator = Argon2BytesGenerator()
generator.init(Argon2Parameters.Builder(Argon2Parameters.ARGON2_id).build())
// 160 bit is enough for uniqueness
val result = ByteArray(20)
generator.generateBytes(value.toByteArray(), result, 0, result.size)
return Base64.getEncoder().withoutPadding().encodeToString(result)
}
private fun writeServiceStats(writer: JsonGenerator) {
class StatItem(val name: String) {
var app = 0
var project = 0
var module = 0
}
// components can be inferred from data, but to verify that items reported correctly (and because for items threshold is applied (not all are reported))
val component = StatItem("component")
val service = StatItem("service")
val plugins = PluginManagerCore.getLoadedPlugins(null).sortedBy { it.pluginId }
for (plugin in plugins) {
service.app += (plugin as IdeaPluginDescriptorImpl).app.services.size
service.project += plugin.project.services.size
service.module += plugin.module.services.size
component.app += plugin.app.components?.size ?: 0
component.project += plugin.project.components?.size ?: 0
component.module += plugin.module.components?.size ?: 0
}
writer.obj("stats") {
writer.writeNumberField("plugin", plugins.size)
for (statItem in listOf(component, service)) {
writer.obj(statItem.name) {
writer.writeNumberField("app", statItem.app)
writer.writeNumberField("project", statItem.project)
writer.writeNumberField("module", statItem.module)
}
}
}
writer.array("plugins") {
for (plugin in plugins) {
val classLoader = plugin.pluginClassLoader as? PluginAwareClassLoader ?: continue
writer.obj {
writer.writeStringField("id", plugin.pluginId.idString)
writer.writeNumberField("classCount", classLoader.loadedClassCount)
writer.writeNumberField("classLoadingEdtTime", TimeUnit.NANOSECONDS.toMillis(classLoader.edtTime))
writer.writeNumberField("classLoadingBackgroundTime", TimeUnit.NANOSECONDS.toMillis(classLoader.backgroundTime))
}
}
}
} | apache-2.0 | 160f8b3049815c0aa74ea9c3862a51c2 | 41.256545 | 165 | 0.742007 | 4.554176 | false | false | false | false |
android/wear-os-samples | RuntimePermissionsWear/Wearable/src/main/java/com/example/android/wearable/runtimepermissions/RequestPermissionOnPhoneActivity.kt | 1 | 2147 | /*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.wearable.runtimepermissions
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.os.Bundle
import androidx.activity.result.contract.ActivityResultContract
import androidx.appcompat.app.AppCompatActivity
import com.example.android.wearable.runtimepermissions.databinding.ActivityRequestPermissionOnPhoneBinding
/**
* Asks user if they want to open permission screen on their remote device (phone).
*/
class RequestPermissionOnPhoneActivity : AppCompatActivity() {
private lateinit var binding: ActivityRequestPermissionOnPhoneBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityRequestPermissionOnPhoneBinding.inflate(layoutInflater)
setContentView(binding.root)
binding.openOnPhoneContainer.setOnClickListener {
setResult(RESULT_OK)
finish()
}
}
companion object {
/**
* An [ActivityResultContract] for checking that the user wants to request permission on
* their phone.
*/
object RequestPermissionOnPhone : ActivityResultContract<Unit, Boolean>() {
override fun createIntent(context: Context, input: Unit): Intent =
Intent(context, RequestPermissionOnPhoneActivity::class.java)
override fun parseResult(resultCode: Int, intent: Intent?): Boolean =
resultCode == Activity.RESULT_OK
}
}
}
| apache-2.0 | 56a64ca8eaca701708136ca6b6010a8a | 36.017241 | 106 | 0.729856 | 5.028103 | false | false | false | false |
fluidsonic/fluid-json | annotation-processor/test-cases/1/output-expected/json/decoding/AutomaticSecondaryConstructorPrimaryExcludedJsonCodec.kt | 1 | 2226 | package json.decoding
import codecProvider.CustomCodingContext
import io.fluidsonic.json.AbstractJsonCodec
import io.fluidsonic.json.JsonCodingType
import io.fluidsonic.json.JsonDecoder
import io.fluidsonic.json.JsonEncoder
import io.fluidsonic.json.missingPropertyError
import io.fluidsonic.json.readBooleanOrNull
import io.fluidsonic.json.readByteOrNull
import io.fluidsonic.json.readCharOrNull
import io.fluidsonic.json.readDoubleOrNull
import io.fluidsonic.json.readFloatOrNull
import io.fluidsonic.json.readFromMapByElementValue
import io.fluidsonic.json.readIntOrNull
import io.fluidsonic.json.readLongOrNull
import io.fluidsonic.json.readShortOrNull
import io.fluidsonic.json.readStringOrNull
import io.fluidsonic.json.readValueOfType
import io.fluidsonic.json.readValueOfTypeOrNull
import io.fluidsonic.json.writeBooleanOrNull
import io.fluidsonic.json.writeByteOrNull
import io.fluidsonic.json.writeCharOrNull
import io.fluidsonic.json.writeDoubleOrNull
import io.fluidsonic.json.writeFloatOrNull
import io.fluidsonic.json.writeIntOrNull
import io.fluidsonic.json.writeIntoMap
import io.fluidsonic.json.writeLongOrNull
import io.fluidsonic.json.writeMapElement
import io.fluidsonic.json.writeShortOrNull
import io.fluidsonic.json.writeStringOrNull
import io.fluidsonic.json.writeValueOrNull
import kotlin.Unit
internal object AutomaticSecondaryConstructorPrimaryExcludedJsonCodec :
AbstractJsonCodec<AutomaticSecondaryConstructorPrimaryExcluded, CustomCodingContext>() {
public override
fun JsonDecoder<CustomCodingContext>.decode(valueType: JsonCodingType<AutomaticSecondaryConstructorPrimaryExcluded>):
AutomaticSecondaryConstructorPrimaryExcluded {
var _value = 0
var value_isPresent = false
readFromMapByElementValue { key ->
when (key) {
"value" -> {
_value = readInt()
value_isPresent = true
}
else -> skipValue()
}
}
value_isPresent || missingPropertyError("value")
return AutomaticSecondaryConstructorPrimaryExcluded(
`value` = _value
)
}
public override
fun JsonEncoder<CustomCodingContext>.encode(`value`: AutomaticSecondaryConstructorPrimaryExcluded):
Unit {
writeIntoMap {
writeMapElement("value", string = value.`value`)
}
}
}
| apache-2.0 | 224816c6fbcd47318e90f2863c3de5f0 | 32.223881 | 120 | 0.827942 | 4.828633 | false | false | false | false |
zdary/intellij-community | platform/platform-tests/testSrc/com/intellij/featureStatistics/fusCollectors/EventsIdentityThrottleTest.kt | 13 | 2440 | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.featureStatistics.fusCollectors
import org.junit.Test
import kotlin.test.assertFalse
import kotlin.test.assertTrue
class EventsIdentityThrottleTest {
private val ONE = -67834
private val TWO = 908542
private val THREE = 12314
private val FOUR = 482309581
@Test
fun `test throttling`() {
val timer = Timer()
val throttle = EventsIdentityThrottle(2, 10)
assertTrue(throttle.tryPass(ONE, timer.tick()))
assertTrue(throttle.tryPass(TWO, timer.tick()))
assert(throttle.size(timer.now()) == 2)
assert(throttle.getOldest(timer.now()) == ONE)
assertFalse(throttle.tryPass(ONE, timer.tick()))
assert(throttle.size(timer.now()) == 2)
assert(throttle.getOldest(timer.now()) == ONE)
assertFalse(throttle.tryPass(TWO, timer.tick()))
assert(throttle.size(timer.now()) == 2)
assert(throttle.getOldest(timer.now()) == ONE)
}
@Test
fun `test max size`() {
val timer = Timer()
val throttle = EventsIdentityThrottle(2, 10)
assertTrue(throttle.tryPass(ONE, timer.tick()))
assertTrue(throttle.tryPass(TWO, timer.tick()))
assertTrue(throttle.tryPass(THREE, timer.tick()))
assert(throttle.size(timer.now()) == 2)
assert(throttle.getOldest(timer.now()) == TWO)
assertTrue(throttle.tryPass(FOUR, timer.tick()))
assert(throttle.size(timer.now()) == 2)
assert(throttle.getOldest(timer.now()) == THREE)
}
@Test
fun `test timeout`() {
val timer = Timer()
val throttle = EventsIdentityThrottle(2, 10)
assertTrue(throttle.tryPass(ONE, timer.tick()))
assertTrue(throttle.tryPass(TWO, timer.tick()))
assert(throttle.size(timer.bigTick(9)) == 1)
assert(throttle.getOldest(timer.now()) == TWO)
assertTrue(throttle.tryPass(ONE, timer.tick()))
assert(throttle.size(timer.now()) == 1)
assert(throttle.getOldest(timer.now()) == ONE)
assertTrue(throttle.tryPass(TWO, timer.tick()))
assert(throttle.size(timer.now()) == 2)
assert(throttle.getOldest(timer.now()) == ONE)
}
private class Timer {
private var time: Long = -572893L
fun now(): Long {
return time
}
fun tick(): Long {
time += 1
return time
}
fun bigTick(value: Long): Long {
time += value
return time
}
}
} | apache-2.0 | 6343d1249680dd8df7d283aeaaf5b175 | 24.427083 | 140 | 0.662295 | 3.753846 | false | true | false | false |
grover-ws-1/http4k | http4k-core/src/test/kotlin/org/http4k/filter/ClientFiltersTest.kt | 1 | 5473 | package org.http4k.filter
import com.natpryce.hamkrest.and
import com.natpryce.hamkrest.assertion.assertThat
import com.natpryce.hamkrest.equalTo
import com.natpryce.hamkrest.present
import com.natpryce.hamkrest.should.shouldMatch
import org.http4k.core.Method.GET
import org.http4k.core.Method.POST
import org.http4k.core.Method.PUT
import org.http4k.core.Request
import org.http4k.core.Response
import org.http4k.core.Status
import org.http4k.core.Status.Companion.OK
import org.http4k.core.Uri
import org.http4k.core.then
import org.http4k.core.toBody
import org.http4k.hamkrest.hasBody
import org.http4k.hamkrest.hasHeader
import org.junit.Assert.fail
import org.junit.Before
import org.junit.Test
class ClientFiltersTest {
val server = { request: Request ->
when (request.uri.path) {
"/redirect" -> Response(Status.FOUND).header("location", "/ok")
"/loop" -> Response(Status.FOUND).header("location", "/loop")
"/absolute-target" -> if (request.uri.host == "example.com") Response(Status.OK).body("absolute") else Response(Status.INTERNAL_SERVER_ERROR)
"/absolute-redirect" -> Response(Status.MOVED_PERMANENTLY).header("location", "http://example.com/absolute-target")
"/redirect-with-charset" -> Response(Status.MOVED_PERMANENTLY).header("location", "/destination; charset=utf8")
"/destination" -> Response(OK).body("destination")
else -> Response(Status.OK).let { if (request.query("foo") != null) it.body("with query") else it }
}
}
val followRedirects = ClientFilters.FollowRedirects().then(server)
@Test
fun `does not follow redirect by default`() {
val defaultClient = server
assertThat(defaultClient(Request(GET, "/redirect")), equalTo(Response(Status.FOUND).header("location", "/ok")))
}
@Test
fun `follows redirect for temporary redirect response`() {
assertThat(followRedirects(Request(GET, "/redirect")), equalTo(Response(Status.OK)))
}
@Test
fun `does not follow redirect for post`() {
assertThat(followRedirects(Request(POST, "/redirect")), equalTo(Response(Status.FOUND).header("location", "/ok")))
}
@Test
fun `does not follow redirect for put`() {
assertThat(followRedirects(Request(PUT, "/redirect")), equalTo(Response(Status.FOUND).header("location", "/ok")))
}
@Test
fun `supports absolute redirects`() {
assertThat(followRedirects(Request(GET, "/absolute-redirect")), equalTo(Response(Status.OK).body("absolute")))
}
@Test
fun `discards query parameters in relative redirects`() {
assertThat(followRedirects(Request(GET, "/redirect?foo=bar")), equalTo(Response(Status.OK)))
}
@Test
fun `discards charset from location header`() {
assertThat(followRedirects(Request(GET, "/redirect-with-charset")), equalTo(Response(Status.OK).body("destination")))
}
@Test
fun `prevents redirection loop after 10 redirects`() {
try {
followRedirects(Request(GET, "/loop"))
fail("should have looped")
} catch (e: IllegalStateException) {
assertThat(e.message, equalTo("Too many redirection"))
}
}
@Before
fun before() {
ZipkinTraces.THREAD_LOCAL.remove()
}
@Test
fun `adds request tracing to outgoing request when already present`() {
val zipkinTraces = ZipkinTraces(TraceId.new(), TraceId.new(), TraceId.new())
ZipkinTraces.THREAD_LOCAL.set(zipkinTraces)
var start: Pair<Request, ZipkinTraces>? = null
var end: Triple<Request, Response, ZipkinTraces>? = null
val svc = ClientFilters.RequestTracing(
{ req, trace -> start = req to trace },
{ req, resp, trace -> end = Triple(req, resp, trace) }
).then { it ->
assertThat(ZipkinTraces(it), equalTo(zipkinTraces))
Response(OK)
}
svc(Request(GET, "")) shouldMatch equalTo(Response(OK))
assertThat(start, equalTo(Request(GET, "") to zipkinTraces))
assertThat(end, equalTo(Triple(Request(GET, ""), Response(OK), zipkinTraces)))
}
@Test
fun `adds new request tracing to outgoing request when not present`() {
val svc = ClientFilters.RequestTracing().then { it ->
assertThat(ZipkinTraces(it), present())
Response(OK)
}
svc(Request(GET, "")) shouldMatch equalTo(Response(OK))
}
@Test
fun `set host on client`() {
val handler = ClientFilters.SetHostFrom(Uri.of("http://localhost:8080")).then { Response(OK).header("Host", it.header("Host")).body(it.uri.toString()) }
handler(Request(GET, "/loop")) shouldMatch hasBody("http://localhost:8080/loop").and(hasHeader("Host", "localhost"))
}
@Test
fun `gzip request and gunzip response`() {
val handler = ClientFilters.GZip().then {
it shouldMatch hasHeader("transfer-encoding", "gzip").and(hasBody(equalTo("hello".toBody().gzipped())))
Response(OK).header("transfer-encoding", "gzip").body(it.body)
}
handler(Request(GET, "/").body("hello")) shouldMatch hasBody("hello")
}
@Test
fun `passes through non-gzipped response`() {
val handler = ClientFilters.GZip().then {
Response(OK).body("hello")
}
handler(Request(GET, "/").body("hello")) shouldMatch hasBody("hello")
}
} | apache-2.0 | 1f12196df518d02665b1a662ab42c52f | 36.493151 | 160 | 0.649187 | 4.177863 | false | true | false | false |
code-helix/slatekit | src/lib/kotlin/slatekit-common/src/main/kotlin/slatekit/common/info/ApiLogin.kt | 1 | 1058 | /**
* <slate_header>
* url: www.slatekit.com
* git: www.github.com/code-helix/slatekit
* org: www.codehelix.co
* author: Kishore Reddy
* copyright: 2016 CodeHelix Solutions Inc.
* license: refer to website and/or github
* about: A tool-kit, utility library and server-backend
* mantra: Simplicity above all else
* </slate_header>
*/
package slatekit.common.info
/**
* Represents credentials for accessing an API. This is useful for representing credentials
* for other systems such as AWS keys, Twilio, SendGrid, etc.
* @param account : The account for the API
* @param key : The key for the API
* @param pass : The password for the API ( optional )
* @param env : Optional environment of the API ( e.g. dev, qa )
* @param tag : Optional tag
*/
data class ApiLogin(
@JvmField val account: String = "",
@JvmField val key: String = "",
@JvmField val pass: String = "",
@JvmField val env: String = "",
@JvmField val tag: String = ""
) {
companion object {
@JvmStatic
val empty = ApiLogin()
}
}
| apache-2.0 | 709e0feb378b2de4d9b6c166f5ff2cd1 | 27.594595 | 91 | 0.664461 | 3.751773 | false | false | false | false |
walkingice/MomoDict | app/src/main/java/org/zeroxlab/momodict/model/Entry.kt | 1 | 407 | package org.zeroxlab.momodict.model
import androidx.room.Entity
import androidx.room.PrimaryKey
// TODO: null safety
@Entity(tableName = "entries")
data class Entry(
var wordStr: String,
var data: String? = null,
// Name of the sourceBook of this entry, usually is a dictionary
var source: String? = null
) {
@PrimaryKey(autoGenerate = true)
var entryId: Int = 0
}
| mit | 5b173faa05da88ec729d8cc134e71bab | 24.4375 | 72 | 0.675676 | 3.913462 | false | false | false | false |
JuliusKunze/kotlin-native | backend.native/tests/external/stdlib/ranges/RangeIterationTest/oneElementDownTo.kt | 2 | 2801 | import kotlin.test.*
fun <T> compare(expected: T, actual: T, block: CompareContext<T>.() -> Unit) {
CompareContext(expected, actual).block()
}
class CompareContext<out T>(public val expected: T, public val actual: T) {
public fun equals(message: String = "") {
assertEquals(expected, actual, message)
}
public fun <P> propertyEquals(message: String = "", getter: T.() -> P) {
assertEquals(expected.getter(), actual.getter(), message)
}
public fun propertyFails(getter: T.() -> Unit) {
assertFailEquals({ expected.getter() }, { actual.getter() })
}
public fun <P> compareProperty(getter: T.() -> P, block: CompareContext<P>.() -> Unit) {
compare(expected.getter(), actual.getter(), block)
}
private fun assertFailEquals(expected: () -> Unit, actual: () -> Unit) {
val expectedFail = assertFails(expected)
val actualFail = assertFails(actual)
//assertEquals(expectedFail != null, actualFail != null)
assertTypeEquals(expectedFail, actualFail)
}
}
fun <T> CompareContext<Iterator<T>>.iteratorBehavior() {
propertyEquals { hasNext() }
while (expected.hasNext()) {
propertyEquals { next() }
propertyEquals { hasNext() }
}
propertyFails { next() }
}
public fun <N : Any> doTest(
sequence: Iterable<N>,
expectedFirst: N,
expectedLast: N,
expectedIncrement: Number,
expectedElements: List<N>
) {
val first: Any
val last: Any
val increment: Number
when (sequence) {
is IntProgression -> {
first = sequence.first
last = sequence.last
increment = sequence.step
}
is LongProgression -> {
first = sequence.first
last = sequence.last
increment = sequence.step
}
is CharProgression -> {
first = sequence.first
last = sequence.last
increment = sequence.step
}
else -> throw IllegalArgumentException("Unsupported sequence type: $sequence")
}
assertEquals(expectedFirst, first)
assertEquals(expectedLast, last)
assertEquals(expectedIncrement, increment)
if (expectedElements.isEmpty())
assertTrue(sequence.none())
else
assertEquals(expectedElements, sequence.toList())
compare(expectedElements.iterator(), sequence.iterator()) {
iteratorBehavior()
}
}
fun box() {
doTest(5 downTo 5, 5, 5, -1, listOf(5))
doTest(5.toByte() downTo 5.toByte(), 5, 5, -1, listOf(5))
doTest(5.toShort() downTo 5.toShort(), 5, 5, -1, listOf(5))
doTest(5.toLong() downTo 5.toLong(), 5.toLong(), 5.toLong(), -1.toLong(), listOf(5.toLong()))
doTest('k' downTo 'k', 'k', 'k', -1, listOf('k'))
}
| apache-2.0 | dd886e4a31460ec6f2e7b5f4022e23d3 | 29.11828 | 97 | 0.602285 | 4.282875 | false | true | false | false |
smmribeiro/intellij-community | plugins/kotlin/idea/tests/testData/formatter/callChain/CallChainWrapping.after.inv.kt | 5 | 1810 | val x = foo
.bar()
.baz()
.quux()
val x2 = foo()
.bar()
.baz()
.quux()
val x3 = ((foo().bar()))
.baz()
.quux()
val x4 = (foo()
.bar()
.baz()).quux()
val x5 = (foo())
.bar()
.baz()
.quux()
val x6 = foo!!
.bar()
.baz()!!
.quux()!!
val x7 = foo!!
.bar()
.baz()!!
.quux()!!
val x8 = foo!!!!!!!!
.bar()
.baz()!!
.quux()!!
val x9 = ((b!!)!!!!)!!.f
val x10 = a()!!.a()
val x11 = a()!!!!.a()
val x12 = a()!!
.a()!!
.a()
val x13 = a()!!!!
.a()
.a()
val x14 = a().a()
val x15 = (a()).a()
val x16 = (a())
.a()
.a()
val x17 = (a().a()).a()
val x18 = (a().a())
.a()
.a()
val x18 = (a()
.a()
.a())
.a()
.a()
val x19 = (a()
.a()
.a()).a()
val x20 = foo!!.foo
.baz()!!
.quux()!!.foo.foo.foo.baz().foo
.baz()
.baz()
val y = xyzzy(foo
.bar()
.baz()
.quux())
fun foo() {
foo
.bar()
.baz()
.quux()
z = foo
.bar()
.baz()
.quux()
z += foo
.bar()
.baz()
.quux()
return foo
.bar()
.baz()
.quux()
}
fun top() = ""
.plus("")
.plus("")
class C {
fun member() = ""
.plus("")
.plus("")
}
fun foo() {
fun local() = ""
.plus("")
.plus("")
val anonymous = fun() = ""
.plus("")
.plus("")
}
// SET_INT: METHOD_CALL_CHAIN_WRAP = 2
// SET_FALSE: WRAP_FIRST_METHOD_IN_CALL_CHAIN
// SET_TRUE: ALLOW_TRAILING_COMMA
| apache-2.0 | fdc69192c3a751dca77442a9809cb440 | 12.712121 | 45 | 0.300552 | 3.136915 | false | false | false | false |
MyPureCloud/platform-client-sdk-common | resources/sdk/purecloudkotlin/extensions/extensions/notifications/NotificationHandler.kt | 1 | 12372 | package com.mypurecloud.sdk.v2.extensions.notifications
import com.fasterxml.jackson.databind.ObjectMapper
import com.mypurecloud.sdk.v2.ApiClient
import com.mypurecloud.sdk.v2.ApiException
import com.mypurecloud.sdk.v2.Configuration.defaultApiClient
import com.mypurecloud.sdk.v2.api.NotificationsApi
import com.mypurecloud.sdk.v2.api.request.PostNotificationsChannelsRequest
import com.mypurecloud.sdk.v2.model.Channel
import com.mypurecloud.sdk.v2.model.ChannelTopic
import com.mypurecloud.sdk.v2.model.SystemMessageSystemMessage
import com.neovisionaries.ws.client.*
import org.slf4j.LoggerFactory
import java.io.IOException
import java.util.*
class NotificationHandler private constructor(builder: Builder) : Any() {
private var notificationsApi: NotificationsApi? = NotificationsApi()
private var webSocket: WebSocket?
var channel: Channel? = null
private val typeMap: MutableMap<String?, NotificationListener<*>> = mutableMapOf()
private var webSocketListener: WebSocketListener? = null
private var objectMapper: ObjectMapper? = null
constructor() : this(Builder.standard()) {}
class Builder {
var notificationListeners: MutableList<NotificationListener<*>>? = null
var webSocketListener: WebSocketListener? = null
var channel: Channel? = null
var connectAsync: Boolean? = null
var apiClient: ApiClient? = null
var notificationsApi: NotificationsApi? = null
var objectMapper: ObjectMapper? = null
var proxyHost: String? = null
fun withNotificationListener(notificationListener: NotificationListener<*>): Builder {
notificationListeners!!.add(notificationListener)
return this
}
fun withNotificationListeners(notificationListeners: List<NotificationListener<*>>): Builder {
this.notificationListeners!!.addAll(notificationListeners)
return this
}
fun withWebSocketListener(webSocketListener: WebSocketListener?): Builder {
this.webSocketListener = webSocketListener
return this
}
fun withChannel(channel: Channel?): Builder {
this.channel = channel
return this
}
fun withAutoConnect(connectAsync: Boolean?): Builder {
this.connectAsync = connectAsync
return this
}
fun withApiClient(apiClient: ApiClient?): Builder {
this.apiClient = apiClient
return this
}
fun withNotificationsApi(notificationsApi: NotificationsApi?): Builder {
this.notificationsApi = notificationsApi
return this
}
fun withObjectMapper(objectMapper: ObjectMapper?): Builder {
this.objectMapper = objectMapper
return this
}
fun withProxyHost(proxyHost: String?): Builder {
this.proxyHost = proxyHost
return this
}
@Throws(IOException::class, ApiException::class, WebSocketException::class)
fun build(): NotificationHandler {
return NotificationHandler(this)
}
companion object {
fun standard(): Builder {
val builder = Builder()
builder.notificationListeners = mutableListOf()
builder.webSocketListener = null
builder.channel = null
builder.connectAsync = null
builder.apiClient = null
builder.notificationsApi = null
builder.objectMapper = null
builder.proxyHost = null
return builder
}
}
}
fun sendPing() {
webSocket!!.sendText("{\"message\":\"ping\"}")
}
fun setWebSocketListener(webSocketListener: WebSocketListener?) {
this.webSocketListener = webSocketListener
}
@Throws(IOException::class, ApiException::class)
fun <T> addSubscription(listener: NotificationListener<T>) {
addSubscriptions(listOf<NotificationListener<*>>(listener))
}
@Throws(IOException::class, ApiException::class)
fun addSubscriptions(listeners: List<NotificationListener<*>>?) {
val topics: MutableList<ChannelTopic> = LinkedList()
for (listener in listeners!!) {
typeMap[listener.getTopic()] = listener
if ("channel.metadata" != listener.getTopic() && !listener.getTopic()?.startsWith("v2.system")!!) {
val channelTopic = ChannelTopic()
channelTopic.id = listener.getTopic()
topics.add(channelTopic)
}
}
notificationsApi!!.postNotificationsChannelSubscriptions(channel!!.id!!, topics)
}
fun <T> addHandlerNoSubscribe(listener: NotificationListener<T>) {
addHandlersNoSubscribe(listOf<NotificationListener<*>>(listener))
}
fun addHandlersNoSubscribe(listeners: List<NotificationListener<*>>?) {
for (listener in listeners!!) {
typeMap[listener.getTopic()] = listener
}
}
@Throws(IOException::class, ApiException::class)
fun RemoveSubscription(topic: String?) {
val channels = notificationsApi!!.getNotificationsChannelSubscriptions(channel!!.id!!)
var match: ChannelTopic? = null
for (channelTopic in channels!!.entities!!) {
if (channelTopic.id.equals(topic, ignoreCase = true)) {
match = channelTopic
break
}
}
if (match == null) return
channels.entities!!.remove(match)
notificationsApi!!.putNotificationsChannelSubscriptions(channel!!.id!!, channels.entities!!)
typeMap.remove(topic)
}
@Throws(IOException::class, ApiException::class)
fun RemoveAllSubscriptions() {
notificationsApi!!.deleteNotificationsChannelSubscriptions(channel!!.id!!)
typeMap.clear()
}
@Throws(WebSocketException::class)
fun connect(async: Boolean) {
if (async) webSocket!!.connectAsynchronously() else webSocket!!.connect()
}
fun disconnect() {
if (webSocket != null && webSocket?.isOpen!!) webSocket?.disconnect()
}
@Throws(Throwable::class)
protected fun finalize() {
try { // Ensure socket is closed on GC
disconnect()
} catch (ex: Exception) {
LOGGER.error(ex.message, ex)
}
}
companion object {
private val LOGGER = LoggerFactory.getLogger(NotificationHandler::class.java)
}
init {
// Construct notifications API
notificationsApi = when {
builder.notificationsApi != null -> {
builder.notificationsApi
}
builder.apiClient != null -> {
NotificationsApi(builder.apiClient)
}
else -> {
NotificationsApi()
}
}
// Set object mapper
objectMapper = when {
builder.objectMapper != null -> {
builder.objectMapper
}
builder.apiClient != null -> {
builder.apiClient!!.objectMapper
}
else -> {
defaultApiClient!!.objectMapper
}
}
// Set channel
channel = when (builder.channel) {
null -> {
notificationsApi!!.postNotificationsChannels(PostNotificationsChannelsRequest.builder().build())
}
else -> {
builder.channel
}
}
// Set notification listeners
addSubscriptions(builder.notificationListeners)
// Add handler for socket closing event
addHandlerNoSubscribe(SocketClosingHandler())
// Set web socket listener
setWebSocketListener(builder.webSocketListener)
// Initialize web socket
val factory = WebSocketFactory()
if (builder.proxyHost != null) factory.proxySettings.setServer(builder.proxyHost)
webSocket = factory
.createSocket(channel!!.connectUri)
.addListener(object : WebSocketAdapter() {
@Throws(Exception::class)
override fun onStateChanged(websocket: WebSocket, newState: WebSocketState) {
if (webSocketListener != null) webSocketListener!!.onStateChanged(newState)
}
@Throws(Exception::class)
override fun onConnected(websocket: WebSocket, headers: Map<String, List<String>>) {
if (webSocketListener != null) webSocketListener!!.onConnected()
}
@Throws(Exception::class)
override fun onConnectError(websocket: WebSocket, exception: WebSocketException) {
if (webSocketListener != null) webSocketListener!!.onConnectError(exception)
}
@Throws(Exception::class)
override fun onDisconnected(websocket: WebSocket, serverCloseFrame: WebSocketFrame, clientCloseFrame: WebSocketFrame, closedByServer: Boolean) {
if (webSocketListener != null) webSocketListener!!.onDisconnected(closedByServer)
}
override fun onTextMessage(websocket: WebSocket, message: String) {
try {
if (LOGGER.isDebugEnabled) {
LOGGER.debug("---WEBSOCKET MESSAGE---\n$message")
}
// Deserialize without knowing body type to figure out topic name
val genericEventType = objectMapper!!.typeFactory.constructParametricType(NotificationEvent::class.java, Any::class.java)
val genericEventData = objectMapper!!.readValue<NotificationEvent<Any>>(message, genericEventType)
// Look up Listener based on topic name
val specificType = typeMap[genericEventData.getTopicName()]
if (specificType != null) { // Deserialize to specific type provided by listener
val specificEventType = objectMapper!!.typeFactory.constructParametricType(NotificationEvent::class.java, specificType.getEventBodyClass())
val notificationEvent = objectMapper!!.readValue<Any>(message, specificEventType) as NotificationEvent<*>
// Set raw body
notificationEvent.setEventBodyRaw(message)
// Raise event
specificType.onEvent(notificationEvent)
} else { // Unhandled topic
if (webSocketListener != null) webSocketListener!!.onUnhandledEvent(message)
}
} catch (ex: Exception) {
LOGGER.error(ex.message, ex)
}
}
@Throws(Exception::class)
override fun onError(websocket: WebSocket, cause: WebSocketException) {
if (webSocketListener != null) webSocketListener!!.onError(cause)
}
@Throws(Exception::class)
override fun handleCallbackError(websocket: WebSocket, cause: Throwable) {
if (webSocketListener != null) webSocketListener!!.onCallbackError(cause)
}
})
if (builder.connectAsync != null) connect(builder.connectAsync!!)
}
inner class SocketClosingHandler : NotificationListener<SystemMessageSystemMessage?> {
private val topic: String = "v2.system.socket_closing"
override fun getTopic(): String? {
return topic
}
override fun getEventBodyClass(): Class<SystemMessageSystemMessage>? {
return SystemMessageSystemMessage::class.java
}
override fun onEvent(event: NotificationEvent<*>?) {
try {
webSocket = webSocket!!.recreate()
} catch (ex: Exception) {
LOGGER.error(ex.message, ex)
}
}
}
}
| mit | d71d5b62ab3fba277ffa092af5dbd2c0 | 38.527157 | 171 | 0.593356 | 5.922451 | false | false | false | false |
mbrlabs/Mundus | editor/src/main/com/mbrlabs/mundus/editor/ui/modules/inspector/components/terrain/TerrainGenTab.kt | 1 | 5863 | /*
* Copyright (c) 2016. See AUTHORS file.
*
* 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.mbrlabs.mundus.editor.ui.modules.inspector.components.terrain
import com.badlogic.gdx.files.FileHandle
import com.badlogic.gdx.graphics.Pixmap
import com.badlogic.gdx.scenes.scene2d.InputEvent
import com.badlogic.gdx.scenes.scene2d.ui.Table
import com.badlogic.gdx.scenes.scene2d.utils.ClickListener
import com.badlogic.gdx.utils.Align
import com.kotcrab.vis.ui.util.dialog.Dialogs
import com.kotcrab.vis.ui.widget.VisLabel
import com.kotcrab.vis.ui.widget.VisTable
import com.kotcrab.vis.ui.widget.VisTextButton
import com.kotcrab.vis.ui.widget.tabbedpane.Tab
import com.mbrlabs.mundus.editor.Mundus
import com.mbrlabs.mundus.editor.core.project.ProjectManager
import com.mbrlabs.mundus.editor.history.CommandHistory
import com.mbrlabs.mundus.editor.history.commands.TerrainHeightCommand
import com.mbrlabs.mundus.editor.terrain.Terraformer
import com.mbrlabs.mundus.editor.ui.UI
import com.mbrlabs.mundus.editor.ui.widgets.FileChooserField
import com.mbrlabs.mundus.editor.ui.widgets.FloatFieldWithLabel
import com.mbrlabs.mundus.editor.ui.widgets.IntegerFieldWithLabel
import com.mbrlabs.mundus.editor.utils.isImage
/**
* @author Marcus Brummer
* @version 04-03-2016
*/
class TerrainGenTab(private val parent: TerrainComponentWidget) : Tab(false, false) {
private val root = VisTable()
private val hmInput = FileChooserField()
private val loadHeightMapBtn = VisTextButton("Load heightmap")
private val perlinNoiseBtn = VisTextButton("Generate Perlin noise")
private val perlinNoiseSeed = IntegerFieldWithLabel("Seed", -1, false)
private val perlinNoiseMinHeight = FloatFieldWithLabel("Min height", -1, true)
private val perlinNoiseMaxHeight = FloatFieldWithLabel("Max height", -1, true)
private val history: CommandHistory = Mundus.inject()
private val projectManager: ProjectManager = Mundus.inject()
init {
root.align(Align.left)
root.add(VisLabel("Load Heightmap")).pad(5f).left().row()
root.add(hmInput).left().expandX().fillX().row()
root.add(loadHeightMapBtn).padLeft(5f).left().row()
root.add(VisLabel("Perlin Noise")).pad(5f).padTop(10f).left().row()
root.add(perlinNoiseSeed).pad(5f).left().fillX().expandX().row()
root.add(perlinNoiseMinHeight).pad(5f).left().fillX().expandX().row()
root.add(perlinNoiseMaxHeight).pad(5f).left().fillX().expandX().row()
root.add(perlinNoiseBtn).pad(5f).left().row()
setupListeners()
}
private fun setupListeners() {
loadHeightMapBtn.addListener(object : ClickListener() {
override fun clicked(event: InputEvent?, x: Float, y: Float) {
val hm = hmInput.file
if (hm != null && hm.exists() && isImage(hm)) {
loadHeightMap(hm)
projectManager.current().assetManager.addDirtyAsset(parent.component.terrain)
} else {
Dialogs.showErrorDialog(UI, "Please select a heightmap image")
}
}
})
perlinNoiseBtn.addListener(object : ClickListener() {
override fun clicked(event: InputEvent?, x: Float, y: Float) {
val seed = perlinNoiseSeed.int
val min = perlinNoiseMinHeight.float
val max = perlinNoiseMaxHeight.float
generatePerlinNoise(seed, min, max)
projectManager.current().assetManager.addDirtyAsset(parent.component.terrain)
}
})
}
private fun loadHeightMap(heightMap: FileHandle) {
val terrain = parent.component.terrain.terrain
val command = TerrainHeightCommand(terrain)
command.setHeightDataBefore(terrain.heightData)
val originalMap = Pixmap(heightMap)
// scale pixmap if it doesn't fit the terrainAsset
if (originalMap.width != terrain.vertexResolution || originalMap.height != terrain.vertexResolution) {
val scaledPixmap = Pixmap(terrain.vertexResolution, terrain.vertexResolution,
originalMap.format)
scaledPixmap.drawPixmap(originalMap, 0, 0, originalMap.width, originalMap.height, 0, 0,
scaledPixmap.width, scaledPixmap.height)
originalMap.dispose()
Terraformer.heightMap(terrain).maxHeight(terrain.terrainWidth * 0.17f).map(scaledPixmap).terraform()
scaledPixmap.dispose()
} else {
Terraformer.heightMap(terrain).maxHeight(terrain.terrainWidth * 0.17f).map(originalMap).terraform()
originalMap.dispose()
}
command.setHeightDataAfter(terrain.heightData)
history.add(command)
}
private fun generatePerlinNoise(seed: Int, min: Float, max: Float) {
val terrain = parent.component.terrain.terrain
val command = TerrainHeightCommand(terrain)
command.setHeightDataBefore(terrain.heightData)
Terraformer.perlin(terrain).minHeight(min).maxHeight(max).seed(seed.toLong()).terraform()
command.setHeightDataAfter(terrain.heightData)
history.add(command)
}
override fun getTabTitle(): String {
return "Gen"
}
override fun getContentTable(): Table {
return root
}
}
| apache-2.0 | 864ac61cc0cd7f7b800d4fe36e330c18 | 39.715278 | 112 | 0.692137 | 4.248551 | false | false | false | false |
zdary/intellij-community | plugins/package-search/src/com/jetbrains/packagesearch/intellij/plugin/ui/toolwindow/panels/management/packages/HeaderPanel.kt | 1 | 4700 | package com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.panels.management.packages
import com.intellij.openapi.util.SystemInfo
import com.intellij.ui.HyperlinkLabel
import com.intellij.ui.RelativeFont
import com.intellij.util.ui.AsyncProcessIcon
import com.intellij.util.ui.components.BorderLayoutPanel
import com.jetbrains.packagesearch.intellij.plugin.PackageSearchBundle
import com.jetbrains.packagesearch.intellij.plugin.ui.PackageSearchUI
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.operations.PackageSearchOperation
import com.jetbrains.packagesearch.intellij.plugin.ui.updateAndRepaint
import com.jetbrains.packagesearch.intellij.plugin.ui.util.ScaledPixels
import com.jetbrains.packagesearch.intellij.plugin.ui.util.emptyBorder
import com.jetbrains.packagesearch.intellij.plugin.ui.util.scaled
import com.jetbrains.packagesearch.intellij.plugin.ui.util.scaledEmptyBorder
import com.jetbrains.packagesearch.intellij.plugin.ui.util.scrollbarWidth
import java.awt.BorderLayout
import java.awt.FlowLayout
import javax.swing.JLabel
@Suppress("MagicNumber") // Thanks Swing
internal class HeaderPanel(
onUpdateAllLinkClicked: (List<PackageSearchOperation<*>>) -> Unit
) : BorderLayoutPanel() {
private val titleLabel = JLabel().apply {
border = scaledEmptyBorder(right = 20)
font = RelativeFont.BOLD.derive(font)
}
private val countLabel = JLabel().apply {
foreground = PackageSearchUI.GRAY_COLOR
border = scaledEmptyBorder(right = 8)
}
private val progressAnimation = AsyncProcessIcon("pkgs-header-progress").apply {
isVisible = false
suspend()
}
private val updateAllLink = HyperlinkLabel(
PackageSearchBundle.message("packagesearch.ui.toolwindow.actions.upgradeAll.text")
).apply {
isVisible = false
border = scaledEmptyBorder(top = 4)
insets.top = 3.scaled()
}
private var updateAllOperations: List<PackageSearchOperation<*>> = emptyList()
init {
PackageSearchUI.setHeight(this, PackageSearchUI.SmallHeaderHeight)
border = emptyBorder(top = 5.scaled(), left = 5.scaled(), right = 1.scaled() + scrollbarWidth())
background = PackageSearchUI.SectionHeaderBackgroundColor
add(
PackageSearchUI.flowPanel(PackageSearchUI.SectionHeaderBackgroundColor) {
layout = FlowLayout(FlowLayout.LEFT, 6.scaled(), 0)
add(titleLabel)
add(countLabel)
add(progressAnimation)
},
BorderLayout.WEST
)
add(
PackageSearchUI.flowPanel(PackageSearchUI.SectionHeaderBackgroundColor) {
layout = FlowLayout(FlowLayout.RIGHT, 6.scaled(), 0)
add(updateAllLink)
},
BorderLayout.EAST
)
updateAllLink.addHyperlinkListener { onUpdateAllLinkClicked(updateAllOperations) }
}
fun showBusyIndicator(showIndicator: Boolean) {
if (showIndicator) {
progressAnimation.isVisible = true
progressAnimation.resume()
} else {
progressAnimation.isVisible = false
progressAnimation.suspend()
}
}
fun display(title: String, rowsCount: Int?, availableUpdatesCount: Int, updateOperations: List<PackageSearchOperation<*>>) {
titleLabel.text = title
if (rowsCount != null) {
countLabel.isVisible = true
countLabel.text = rowsCount.toString()
} else {
countLabel.isVisible = false
}
updateAllOperations = updateOperations
if (availableUpdatesCount > 0) {
updateAllLink.setHyperlinkText(
PackageSearchBundle.message(
"packagesearch.ui.toolwindow.actions.upgradeAll.text.withCount",
availableUpdatesCount
)
)
updateAllLink.isVisible = true
} else {
updateAllLink.isVisible = false
}
}
fun adjustForScrollbar(scrollbarVisible: Boolean, scrollbarOpaque: Boolean) {
// Non-opaque scrollbars for JTable are supported on Mac only (as of IJ 2020.3):
// See JBScrollPane.Layout#isAlwaysOpaque
val isAlwaysOpaque = !SystemInfo.isMac /* && ScrollSettings.isNotSupportedYet(view), == true for JTable */
val includeScrollbar = scrollbarVisible && (isAlwaysOpaque || scrollbarOpaque)
@ScaledPixels val rightBorder = if (includeScrollbar) scrollbarWidth() else 1.scaled()
border = emptyBorder(top = 5.scaled(), left = 5.scaled(), right = rightBorder)
updateAndRepaint()
}
}
| apache-2.0 | 0c12310cd068b716c2310505e13a5e13 | 37.52459 | 128 | 0.683191 | 5.075594 | false | false | false | false |
siosio/intellij-community | platform/core-ui/src/ui/ScalingDeferredSquareImageIcon.kt | 1 | 1507 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.ui
import com.intellij.ui.scale.ScaleContext
import com.intellij.ui.scale.ScaleType
import com.intellij.util.IconUtil
import com.intellij.util.ui.ImageUtil
import java.awt.Component
import java.awt.Graphics
import java.awt.Image
import javax.swing.Icon
class ScalingDeferredSquareImageIcon<K : Any>(size: Int, defaultIcon: Icon,
private val key: K,
imageLoader: (K) -> Image?) : Icon {
private val baseIcon = IconUtil.resizeSquared(defaultIcon, size)
private val scaledIconCache = ScaleContext.Cache { scaleCtx ->
IconDeferrer.getInstance().defer(baseIcon, key) {
try {
val image = imageLoader(it)
val hidpiImage = ImageUtil.ensureHiDPI(image, scaleCtx)
val scaledSize = scaleCtx.apply(size.toDouble(), ScaleType.USR_SCALE).toInt()
val scaledImage = ImageUtil.scaleImage(hidpiImage, scaledSize, scaledSize)
IconUtil.createImageIcon(scaledImage)
}
catch (e: Exception) {
baseIcon
}
}
}
override fun getIconHeight() = baseIcon.iconHeight
override fun getIconWidth() = baseIcon.iconWidth
override fun paintIcon(c: Component, g: Graphics, x: Int, y: Int) {
scaledIconCache.getOrProvide(ScaleContext.create(c))?.paintIcon(c, g, x, y)
}
} | apache-2.0 | 02753bc9d6f795a1c0a13e57fb4dc944 | 37.666667 | 158 | 0.684141 | 4.233146 | false | false | false | false |
feelfreelinux/WykopMobilny | app/src/main/kotlin/io/github/feelfreelinux/wykopmobilny/ui/modules/profile/links/comments/ProfileLinkCommentsFragment.kt | 1 | 1159 | package io.github.feelfreelinux.wykopmobilny.ui.modules.profile.links.comments
import android.os.Bundle
import io.github.feelfreelinux.wykopmobilny.base.BaseLinkCommentFragment
import io.github.feelfreelinux.wykopmobilny.ui.modules.profile.ProfileActivity
import javax.inject.Inject
class ProfileLinkCommentsFragment : BaseLinkCommentFragment(), ProfileLinkCommentsView {
@Inject lateinit var presenter: ProfileLinksFragmentPresenter
override var loadDataListener: (Boolean) -> Unit = { presenter.loadData(it) }
private val username by lazy { (activity as ProfileActivity).username }
companion object {
fun newInstance() = ProfileLinkCommentsFragment()
}
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
presenter.subscribe(this)
presenter.username = username
linkCommentsAdapter.linkCommentActionListener = presenter
linkCommentsAdapter.loadNewDataListener = { loadDataListener(false) }
presenter.loadData(true)
}
override fun onDestroy() {
presenter.unsubscribe()
super.onDestroy()
}
} | mit | 9fea7483d321eb6876465a94844ef586 | 35.25 | 88 | 0.75755 | 5.174107 | false | false | false | false |
siosio/intellij-community | plugins/package-search/src/com/jetbrains/packagesearch/intellij/plugin/ui/toolwindow/panels/management/packagedetails/PackageDetailsInfoPanel.kt | 1 | 13111 | package com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.panels.management.packagedetails
import com.jetbrains.packagesearch.api.v2.ApiStandardPackage
import com.jetbrains.packagesearch.intellij.plugin.PackageSearchBundle
import com.jetbrains.packagesearch.intellij.plugin.fus.FUSGroupIds
import com.jetbrains.packagesearch.intellij.plugin.fus.PackageSearchEventsLogger
import com.jetbrains.packagesearch.intellij.plugin.ui.PackageSearchUI
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.KnownRepositories
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.PackageModel
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.PackageVersion
import com.jetbrains.packagesearch.intellij.plugin.ui.updateAndRepaint
import com.jetbrains.packagesearch.intellij.plugin.ui.util.Displayable
import com.jetbrains.packagesearch.intellij.plugin.ui.util.ScaledPixels
import com.jetbrains.packagesearch.intellij.plugin.ui.util.emptyBorder
import com.jetbrains.packagesearch.intellij.plugin.ui.util.noInsets
import com.jetbrains.packagesearch.intellij.plugin.ui.util.scaled
import com.jetbrains.packagesearch.intellij.plugin.ui.util.scaledAsString
import com.jetbrains.packagesearch.intellij.plugin.ui.util.skipInvisibleComponents
import com.jetbrains.packagesearch.intellij.plugin.ui.util.withHtmlStyling
import com.jetbrains.packagesearch.intellij.plugin.util.AppUI
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import net.miginfocom.layout.AC
import net.miginfocom.layout.CC
import net.miginfocom.layout.LC
import net.miginfocom.swing.MigLayout
import org.apache.commons.lang3.StringUtils
import java.awt.Component
import java.awt.Dimension
import javax.swing.JComponent
import javax.swing.JPanel
@Suppress("MagicNumber") // Swing dimension constants
internal class PackageDetailsInfoPanel : JPanel(), Displayable<PackageDetailsInfoPanel.ViewModel> {
@ScaledPixels private val maxRowHeight = 180.scaled()
private val noDataLabel = PackageSearchUI.createLabel {
foreground = PackageSearchUI.GRAY_COLOR
text = PackageSearchBundle.message("packagesearch.ui.toolwindow.packages.details.noData")
.withHtmlStyling(wordWrap = true)
}.withMaxHeight(maxRowHeight)
private val descriptionLabel = PackageSearchUI.createLabel()
private val repositoriesLabel = PackageSearchUI.createLabel()
.withMaxHeight(maxRowHeight)
private val gitHubPanel = GitHubInfoPanel()
.withMaxHeight(maxRowHeight)
private val licensesLinkLabel = PackageSearchUI.createLabelWithLink()
.withMaxHeight(maxRowHeight)
private val projectWebsiteLinkLabel = PackageSearchUI.createLabelWithLink()
private val documentationLinkLabel = PackageSearchUI.createLabelWithLink()
private val readmeLinkLabel = PackageSearchUI.createLabelWithLink()
private val kotlinPlatformsPanel = PackageKotlinPlatformsPanel()
private val usagesPanel = PackageUsagesPanel()
private val authorsLabel = PackageSearchUI.createLabel()
init {
layout = MigLayout(
LC().fillX()
.noInsets()
.skipInvisibleComponents()
.gridGap("0", 8.scaledAsString()),
AC().grow(), // One column only
AC().fill().gap() // All rows are filling all available width
.fill().gap()
.fill().gap()
.fill().gap()
.fill().gap()
.fill().gap()
.fill().gap()
.fill().gap()
)
background = PackageSearchUI.UsualBackgroundColor
alignmentX = Component.LEFT_ALIGNMENT
@ScaledPixels val horizontalBorder = 12.scaled()
border = emptyBorder(left = horizontalBorder, bottom = 20.scaled(), right = horizontalBorder)
fun CC.compensateForHighlightableComponentMarginLeft() = pad(0, (-2).scaled(), 0, 0)
add(noDataLabel, CC().wrap())
add(repositoriesLabel, CC().wrap())
add(descriptionLabel, CC().wrap())
add(gitHubPanel, CC().wrap())
add(licensesLinkLabel, CC().compensateForHighlightableComponentMarginLeft().wrap())
add(projectWebsiteLinkLabel, CC().compensateForHighlightableComponentMarginLeft().wrap())
add(documentationLinkLabel, CC().compensateForHighlightableComponentMarginLeft().wrap())
add(readmeLinkLabel, CC().compensateForHighlightableComponentMarginLeft().wrap())
add(kotlinPlatformsPanel, CC().wrap())
add(usagesPanel, CC().wrap())
add(authorsLabel, CC().wrap())
}
internal data class ViewModel(
val packageModel: PackageModel,
val selectedVersion: PackageVersion,
val allKnownRepositories: KnownRepositories.All
)
override suspend fun display(viewModel: ViewModel) = withContext(Dispatchers.AppUI) {
clearPanelContents()
if (viewModel.packageModel.remoteInfo == null) {
return@withContext
}
noDataLabel.isVisible = false
displayDescriptionIfAny(viewModel.packageModel.remoteInfo)
val selectedVersionInfo = viewModel.packageModel.remoteInfo
.versions.find { it.version == viewModel.selectedVersion.versionName }
displayRepositoriesIfAny(selectedVersionInfo, viewModel.allKnownRepositories)
displayAuthorsIfAny(viewModel.packageModel.remoteInfo.authors)
val linkExtractor = LinkExtractor(viewModel.packageModel.remoteInfo)
displayGitHubInfoIfAny(linkExtractor.scm())
displayLicensesIfAny(linkExtractor.licenses())
displayProjectWebsiteIfAny(linkExtractor.projectWebsite())
displayDocumentationIfAny(linkExtractor.documentation())
displayReadmeIfAny(linkExtractor.readme())
displayKotlinPlatformsIfAny(viewModel.packageModel.remoteInfo)
displayUsagesIfAny(viewModel.packageModel)
updateAndRepaint()
(parent as JComponent).updateAndRepaint()
}
private fun clearPanelContents() {
noDataLabel.isVisible = true
descriptionLabel.isVisible = false
repositoriesLabel.isVisible = false
authorsLabel.isVisible = false
gitHubPanel.isVisible = false
licensesLinkLabel.isVisible = false
projectWebsiteLinkLabel.isVisible = false
documentationLinkLabel.isVisible = false
readmeLinkLabel.isVisible = false
kotlinPlatformsPanel.isVisible = false
usagesPanel.isVisible = false
kotlinPlatformsPanel.clear()
usagesPanel.clear()
updateAndRepaint()
}
private fun displayDescriptionIfAny(remoteInfo: ApiStandardPackage) {
@Suppress("HardCodedStringLiteral") // Comes from the API, it's @NlsSafe
val description = remoteInfo.description
if (description.isNullOrBlank() || description == remoteInfo.name) {
descriptionLabel.isVisible = false
return
}
descriptionLabel.isVisible = true
descriptionLabel.text = description.withHtmlStyling(wordWrap = true)
}
private fun displayRepositoriesIfAny(
selectedVersionInfo: ApiStandardPackage.ApiStandardVersion?,
allKnownRepositories: KnownRepositories.All
) {
if (selectedVersionInfo == null) {
repositoriesLabel.isVisible = false
return
}
val repositoryNames = selectedVersionInfo.repositoryIds
.mapNotNull { repoId -> allKnownRepositories.findById(repoId)?.displayName }
.filterNot { it.isBlank() }
val repositoryNamesToDisplay = repositoryNames.joinToString()
repositoriesLabel.text = if (repositoryNames.size == 1) {
PackageSearchBundle.message("packagesearch.ui.toolwindow.packages.details.info.repository", repositoryNamesToDisplay)
} else {
PackageSearchBundle.message("packagesearch.ui.toolwindow.packages.details.info.repositories", repositoryNamesToDisplay)
}.withHtmlStyling(wordWrap = true)
repositoriesLabel.isVisible = true
}
private fun displayAuthorsIfAny(authors: List<ApiStandardPackage.ApiAuthor>?) {
if (authors.isNullOrEmpty()) {
authorsLabel.isVisible = false
return
}
val authorNames = authors.filterNot { it.name.isNullOrBlank() }
.map { StringUtils.normalizeSpace(it.name) }
val authorsString = if (authorNames.size == 1) {
PackageSearchBundle.message("packagesearch.ui.toolwindow.packages.details.info.author", authorNames.joinToString())
} else {
PackageSearchBundle.message("packagesearch.ui.toolwindow.packages.details.info.authors", authorNames.joinToString())
}
authorsLabel.text = authorsString.withHtmlStyling(wordWrap = true)
authorsLabel.isVisible = true
}
private fun displayGitHubInfoIfAny(scmInfoLink: InfoLink.ScmRepository?) {
if (scmInfoLink !is InfoLink.ScmRepository.GitHub || !scmInfoLink.hasBrowsableUrl()) {
gitHubPanel.isVisible = false
return
}
gitHubPanel.isVisible = true
gitHubPanel.text = scmInfoLink.displayNameCapitalized
gitHubPanel.url = scmInfoLink.url
gitHubPanel.stars = scmInfoLink.stars
}
private fun displayLicensesIfAny(licenseInfoLink: List<InfoLink.License>) {
// TODO move this to a separate component, handle multiple licenses
val mainLicense = licenseInfoLink.firstOrNull()
if (mainLicense == null || !mainLicense.hasBrowsableUrl()) {
licensesLinkLabel.isVisible = false
return
}
licensesLinkLabel.isVisible = true
licensesLinkLabel.url = mainLicense.url
licensesLinkLabel.setDisplayText(
if (mainLicense.licenseName != null) {
PackageSearchBundle.message("packagesearch.ui.toolwindow.packages.details.info.license", mainLicense.licenseName)
} else {
mainLicense.displayNameCapitalized
}
)
licensesLinkLabel.urlClickedListener = {
PackageSearchEventsLogger.logDetailsLinkClick(FUSGroupIds.DetailsLinkTypes.License, mainLicense.url)
}
}
private fun displayProjectWebsiteIfAny(projectWebsiteLink: InfoLink.ProjectWebsite?) {
if (projectWebsiteLink == null || !projectWebsiteLink.hasBrowsableUrl()) {
projectWebsiteLinkLabel.isVisible = false
return
}
projectWebsiteLinkLabel.isVisible = true
projectWebsiteLinkLabel.url = projectWebsiteLink.url
projectWebsiteLinkLabel.setDisplayText(projectWebsiteLink.displayNameCapitalized)
projectWebsiteLinkLabel.urlClickedListener = {
PackageSearchEventsLogger.logDetailsLinkClick(FUSGroupIds.DetailsLinkTypes.ProjectWebsite, projectWebsiteLink.url)
}
}
private fun displayDocumentationIfAny(documentationLink: InfoLink.Documentation?) {
if (documentationLink == null || !documentationLink.hasBrowsableUrl()) {
documentationLinkLabel.isVisible = false
return
}
documentationLinkLabel.isVisible = true
documentationLinkLabel.url = documentationLink.url
documentationLinkLabel.setDisplayText(documentationLink.displayNameCapitalized)
documentationLinkLabel.urlClickedListener = {
PackageSearchEventsLogger.logDetailsLinkClick(FUSGroupIds.DetailsLinkTypes.Documentation, documentationLink.url)
}
}
private fun displayReadmeIfAny(readmeLink: InfoLink.Readme?) {
if (readmeLink == null || !readmeLink.hasBrowsableUrl()) {
readmeLinkLabel.isVisible = false
return
}
readmeLinkLabel.isVisible = true
readmeLinkLabel.url = readmeLink.url
readmeLinkLabel.setDisplayText(readmeLink.displayNameCapitalized)
readmeLinkLabel.urlClickedListener = {
PackageSearchEventsLogger.logDetailsLinkClick(FUSGroupIds.DetailsLinkTypes.Readme, readmeLink.url)
}
}
private fun displayKotlinPlatformsIfAny(packageDetails: ApiStandardPackage?) {
val isKotlinMultiplatform = packageDetails?.mpp != null
if (isKotlinMultiplatform && packageDetails?.platforms?.isNotEmpty() == true) {
kotlinPlatformsPanel.display(packageDetails.platforms ?: emptyList())
kotlinPlatformsPanel.isVisible = true
} else {
kotlinPlatformsPanel.clear()
kotlinPlatformsPanel.isVisible = false
}
}
private fun displayUsagesIfAny(packageModel: PackageModel) {
if (packageModel is PackageModel.Installed) {
usagesPanel.display(packageModel)
usagesPanel.isVisible = true
} else {
usagesPanel.clear()
usagesPanel.isVisible = false
}
}
private fun <T : JComponent> T.withMaxHeight(@ScaledPixels maxHeight: Int): T {
maximumSize = Dimension(Int.MAX_VALUE, maxHeight)
return this
}
}
| apache-2.0 | 8bafcfb537c4406e1cfff655d8c1cdf8 | 40.622222 | 131 | 0.708413 | 5.600598 | false | false | false | false |
siosio/intellij-community | plugins/kotlin/jvm/src/org/jetbrains/kotlin/idea/configuration/KotlinJsModuleConfigurator.kt | 1 | 3944 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.configuration
import com.intellij.openapi.module.Module
import com.intellij.openapi.project.Project
import com.intellij.openapi.projectRoots.Sdk
import com.intellij.openapi.roots.LibraryOrderEntry
import com.intellij.openapi.roots.ModuleRootManager
import com.intellij.openapi.roots.impl.libraries.LibraryEx
import com.intellij.openapi.roots.libraries.DummyLibraryProperties
import com.intellij.openapi.roots.libraries.Library
import com.intellij.openapi.roots.libraries.LibraryType
import org.jetbrains.kotlin.idea.KotlinJvmBundle
import org.jetbrains.kotlin.idea.framework.JSLibraryKind
import org.jetbrains.kotlin.idea.framework.JSLibraryStdDescription
import org.jetbrains.kotlin.idea.framework.JSLibraryType
import org.jetbrains.kotlin.idea.framework.JsLibraryStdDetectionUtil
import org.jetbrains.kotlin.idea.util.application.runWriteAction
import org.jetbrains.kotlin.idea.versions.LibraryJarDescriptor
import org.jetbrains.kotlin.js.JavaScript
import org.jetbrains.kotlin.platform.TargetPlatform
import org.jetbrains.kotlin.platform.js.JsPlatforms
open class KotlinJsModuleConfigurator : KotlinWithLibraryConfigurator() {
override val name: String
get() = NAME
override val targetPlatform: TargetPlatform
get() = JsPlatforms.defaultJsPlatform
@Suppress("DEPRECATION_ERROR")
override fun getTargetPlatform() = JsPlatforms.CompatJsPlatform
override val presentableText: String
get() = KotlinJvmBundle.message("language.name.javascript")
override fun isConfigured(module: Module) = hasKotlinJsRuntimeInScope(module)
override val libraryName: String
get() = JSLibraryStdDescription.LIBRARY_NAME
override val dialogTitle: String
get() = JSLibraryStdDescription.DIALOG_TITLE
override val libraryCaption: String
get() = JSLibraryStdDescription.LIBRARY_CAPTION
override val messageForOverrideDialog: String
get() = JSLibraryStdDescription.JAVA_SCRIPT_LIBRARY_CREATION
override fun getLibraryJarDescriptors(sdk: Sdk?): List<LibraryJarDescriptor> =
listOf(
LibraryJarDescriptor.JS_STDLIB_JAR,
LibraryJarDescriptor.JS_STDLIB_SRC_JAR
)
override val libraryMatcher: (Library, Project) -> Boolean = { library, project ->
JsLibraryStdDetectionUtil.hasJsStdlibJar(library, project)
}
override val libraryType: LibraryType<DummyLibraryProperties>?
get() = JSLibraryType.getInstance()
companion object {
const val NAME = JavaScript.LOWER_NAME
}
/**
* Migrate pre-1.1.3 projects which didn't have explicitly specified kind for JS libraries.
*/
override fun findAndFixBrokenKotlinLibrary(module: Module, collector: NotificationMessageCollector): Library? {
val allLibraries = mutableListOf<LibraryEx>()
var brokenStdlib: Library? = null
for (orderEntry in ModuleRootManager.getInstance(module).orderEntries) {
val library = (orderEntry as? LibraryOrderEntry)?.library as? LibraryEx ?: continue
allLibraries.add(library)
if (JsLibraryStdDetectionUtil.hasJsStdlibJar(library, module.project, ignoreKind = true) && library.kind == null) {
brokenStdlib = library
}
}
if (brokenStdlib != null) {
runWriteAction {
for (library in allLibraries.filter { it.kind == null }) {
library.modifiableModel.apply {
kind = JSLibraryKind
commit()
}
}
}
collector.addMessage(KotlinJvmBundle.message("updated.javascript.libraries.in.module.0", module.name))
}
return brokenStdlib
}
}
| apache-2.0 | d87684713da96598d7edfa7a8856f2e0 | 40.083333 | 158 | 0.722617 | 5.049936 | false | false | false | false |
AleksanderBrzozowski/ticket-booking | src/main/kotlin/com/maly/domain/room/SeatSpecification.kt | 1 | 1202 | package com.maly.domain.room
import com.maly.domain.event.Event
import com.maly.domain.order.Ticket
import org.springframework.data.jpa.domain.Specification
/**
* @author Aleksander Brzozowski
*/
class SeatSpecification private constructor(){
companion object {
fun forFree(eventId: Long): Specification<Seat> {
return Specification { root, query, cb ->
val seatId = root.get<Long>("id")
val sq = query.subquery(Long::class.java)
val ticket = sq.from(Ticket::class.java)
val seat = ticket.get<Seat>("seat")
val seatPredicate = cb.equal(seat.get<Long>("id"), seatId)
val event = ticket.get<Event>("event")
val eventPredicate = cb.equal(event.get<Long>("id"), eventId)
sq.where(cb.and(eventPredicate, seatPredicate))
cb.equal(sq.select(cb.count(ticket)), 0)
}
}
fun forRoom(roomId: Long): Specification<Seat> {
return Specification { root, _, cb ->
val room = root.get<Room>("room")
cb.equal(room.get<Long>("id"), roomId)
}
}
}
} | mit | ff9aa1e1fc143b9938d8ec220831b4a2 | 29.846154 | 77 | 0.566556 | 4.144828 | false | false | false | false |