repo_name
stringlengths 7
79
| path
stringlengths 8
206
| copies
stringclasses 36
values | size
stringlengths 2
6
| content
stringlengths 55
523k
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 7.18
99.5
| line_max
int64 16
979
| alpha_frac
float64 0.3
0.87
| ratio
float64 2.01
8.07
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
vhromada/Catalog
|
web/src/main/kotlin/com/github/vhromada/catalog/web/converter/ConverterUtils.kt
|
1
|
5130
|
package com.github.vhromada.catalog.web.converter
import com.github.vhromada.catalog.web.connector.entity.Game
import com.github.vhromada.catalog.web.connector.entity.Genre
import com.github.vhromada.catalog.web.connector.entity.Medium
import com.github.vhromada.catalog.web.connector.entity.Program
import com.github.vhromada.catalog.web.connector.entity.Season
/**
* A class represents utility class for converters.
*
* @author Vladimir Hromada
*/
object ConverterUtils {
/**
* Converts strings.
*
* @param strings strings
* @return converted strings
*/
@JvmStatic
fun convertStrings(strings: List<String>): String {
if (strings.isEmpty()) {
return ""
}
val result = StringBuilder()
for (string in strings) {
result.append(string)
result.append(", ")
}
return result.substring(0, result.length - 2)
}
/**
* Converts movie's media.
*
* @param media media
* @return converted movie's media
*/
@JvmStatic
fun convertMedia(media: List<Medium>): String {
return convertStrings(strings = media.map { it.formattedLength })
}
/**
* Converts game's additional data.
*
* @param game game
* @return converted game's additional data
*/
@JvmStatic
fun convertGameAdditionalData(game: Game): String {
val result = StringBuilder()
if (game.crack) {
result.append("Crack")
}
addToResult(result = result, value = game.serialKey, data = "serial key")
addToResult(result = result, value = game.patch, data = "patch")
addToResult(result = result, value = game.trainer, data = "trainer")
addToResult(result = result, value = game.trainerData, data = "data for trainer")
addToResult(result = result, value = game.editor, data = "editor")
addToResult(result = result, value = game.saves, data = "saves")
if (!game.otherData.isNullOrBlank()) {
if (result.isNotEmpty()) {
result.append(", ")
}
result.append(game.otherData)
}
return result.toString()
}
/**
* Converts content of game's additional data.
*
* @param game game
* @return converted content of game's additional data
*/
@JvmStatic
fun convertGameAdditionalDataContent(game: Game): Boolean {
return convertGameAdditionalData(game = game).isNotEmpty()
}
/**
* Converts season's years.
*
* @param season season
* @return converted season's years
*/
@JvmStatic
fun convertSeasonYears(season: Season): String {
return if (season.startYear == season.endYear) season.startYear.toString() else "${season.startYear} - ${season.endYear}"
}
/**
* Converts program's additional data.
*
* @param program program
* @return converted program's additional data
*/
@JvmStatic
fun convertProgramAdditionalData(program: Program): String {
val result = StringBuilder()
if (program.crack) {
result.append("Crack")
}
addToResult(result = result, value = program.serialKey, "serial key")
if (!program.otherData.isNullOrBlank()) {
if (result.isNotEmpty()) {
result.append(", ")
}
result.append(program.otherData)
}
return result.toString()
}
/**
* Converts content of program's additional data.
*
* @param program program
* @return converted content of program's additional data
*/
@JvmStatic
fun convertProgramAdditionalDataContent(program: Program): Boolean {
return convertProgramAdditionalData(program = program).isNotEmpty()
}
/**
* Converts genres.
*
* @param genres genres
* @return converted genres
*/
@JvmStatic
fun convertGenres(genres: List<Genre>): String {
return convertStrings(strings = genres.map { it.name })
}
/**
* Converts IMDB code.
*
* @param imdbCode imdb code
* @return converted IMDB code
*/
@JvmStatic
fun convertImdbCode(imdbCode: Int): String {
return imdbCode.toString().padStart(7, '0')
}
/**
* Converts page.
*
* @param currentPage current page
* @param totalPages count of pages
* @return converted page
*/
@JvmStatic
fun convertPage(currentPage: Int, totalPages: Int): String {
return "$currentPage / $totalPages"
}
/**
* Adds data to result.
*
* @param result result
* @param value value
* @param data data
*/
private fun addToResult(result: StringBuilder, value: Boolean, data: String) {
if (value) {
if (result.isEmpty()) {
result.append(data.substring(0, 1).uppercase())
result.append(data.substring(1))
} else {
result.append(", ")
result.append(data)
}
}
}
}
|
mit
|
539fb731bc55e7e85fc57cba5e9926de
| 26.72973 | 129 | 0.592982 | 4.507909 | false | false | false | false |
prt2121/kotlin-ios
|
webview/ios/src/main/kotlin/com/prat/webview/MyViewController.kt
|
1
|
2862
|
package com.prat.webview
import org.robovm.apple.foundation.NSError
import org.robovm.apple.foundation.NSRange
import org.robovm.apple.foundation.NSURL
import org.robovm.apple.foundation.NSURLRequest
import org.robovm.apple.uikit.*
import org.robovm.objc.annotation.CustomClass
import org.robovm.objc.annotation.IBOutlet
@CustomClass("MyViewController")
class MyViewController : UIViewController(), UIWebViewDelegate, UITextFieldDelegate {
@IBOutlet
private val webView: UIWebView? = null
@IBOutlet
private val addressTextField: UITextField? = null
override fun viewDidLoad() {
super.viewDidLoad()
configureWebView()
loadAddressURL()
}
override fun viewWillDisappear(animated: Boolean) {
super.viewWillDisappear(animated)
UIApplication.getSharedApplication().isNetworkActivityIndicatorVisible = false
}
private fun loadAddressURL() {
val requestURL = NSURL(addressTextField!!.text)
val request = NSURLRequest(requestURL)
webView!!.loadRequest(request)
}
private fun configureWebView() {
webView!!.backgroundColor = UIColor.white()
webView.isScalesPageToFit = true
webView.dataDetectorTypes = UIDataDetectorTypes.All
}
override fun shouldStartLoad(webView: UIWebView, request: NSURLRequest, navigationType: UIWebViewNavigationType): Boolean {
return true
}
override fun didStartLoad(webView: UIWebView) {
UIApplication.getSharedApplication().isNetworkActivityIndicatorVisible = true
}
override fun didFinishLoad(webView: UIWebView) {
UIApplication.getSharedApplication().isNetworkActivityIndicatorVisible = false
}
override fun didFailLoad(webView: UIWebView, error: NSError) {
// Report the error inside the web view.
val errorMessage = "An error occurred:"
val errorFormatString = "<!doctype html><html><body><div style=\"width: 100%%; text-align: center; font-size: 36pt;\">%s%s</div></body></html>"
val errorHTML = errorFormatString.format(errorMessage, error.localizedDescription)
webView.loadHTML(errorHTML, null)
UIApplication.getSharedApplication().isNetworkActivityIndicatorVisible = false
}
// This helps dismiss the keyboard when the "Done" button is clicked.
override fun shouldReturn(textField: UITextField): Boolean {
textField.resignFirstResponder()
loadAddressURL()
return true
}
override fun shouldBeginEditing(textField: UITextField): Boolean {
return true
}
override fun didBeginEditing(textField: UITextField) {
}
override fun shouldEndEditing(textField: UITextField): Boolean {
return true
}
override fun didEndEditing(textField: UITextField) {
}
override fun shouldChangeCharacters(textField: UITextField, range: NSRange, string: String): Boolean {
return true
}
override fun shouldClear(textField: UITextField): Boolean {
return true
}
}
|
apache-2.0
|
03387b759875e6523cfa933487a713a7
| 28.505155 | 147 | 0.756813 | 4.464899 | false | false | false | false |
customerly/Customerly-Android-SDK
|
customerly-android-sdk/src/main/java/io/customerly/entity/ping/ClyPingResponse.kt
|
1
|
9848
|
package io.customerly.entity.ping
/*
* Copyright (C) 2017 Customerly
*
* 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 android.content.SharedPreferences
import android.graphics.Color
import io.customerly.Customerly
import io.customerly.entity.*
import io.customerly.entity.chat.ClyMessage
import io.customerly.entity.chat.parseMessage
import io.customerly.sxdependencies.annotations.SXColorInt
import io.customerly.utils.COLORINT_BLUE_MALIBU
import io.customerly.utils.ggkext.*
import org.json.JSONException
import org.json.JSONObject
/**
* Created by Gianni on 29/04/18.
* Project: Customerly-KAndroid-SDK
*/
internal fun JSONObject.parsePing(): ClyPingResponse {
return try {
val minVersion = this.optTyped(name = "min-version-android", fallback = "0.0.0")
val activeAdmins = this.optArray<JSONObject, ClyAdmin>(name = "active_admins", map = { it.parseAdmin() })
val lastSurveys = this.optArray<JSONObject, ClySurvey>(name = "last_surveys", map = { it.parseSurvey() })
val lastMessages = this.optArray<JSONObject, ClyMessage>(name = "last_messages", map = { it.nullOnException { json -> json.parseMessage() } })
this.optTyped<JSONObject>(name = "user")?.optTyped<JSONObject>(name = "data")?.also { userData ->
userData.optTyped<String>(name = "email")?.also { contactEmail ->
Customerly.currentUser.updateUser(
isUser = userData.optTyped<Int>(name = "is_user") == 1,
contactEmail = contactEmail,
userId = userData.optTyped<String>(name = "user_id")?.takeIf { it.isNotBlank() },
contactName = userData.optTyped<String>(name = "name")?.takeIf { it.isNotBlank() })
}
}
this.optTyped<JSONObject>(name = "app_config")?.let { appConfig ->
@SXColorInt val widgetColor: Int = Customerly.widgetColorHardcoded ?: appConfig.optTyped<String>(name = "widget_color")?.takeIf { it.isNotEmpty() }?.let {
when {
it.firstOrNull() != '#' -> "#$it"
else -> it
}
}?.let {
try {
Color.parseColor(it)
} catch (exception: IllegalArgumentException) {
clySendError(errorCode = ERROR_CODE__HTTP_RESPONSE_ERROR, description = "ClyPingResponse:data.apps.app_config.widget_color is an invalid argb color: '$it'", throwable = exception)
null
}
} ?: COLORINT_BLUE_MALIBU
val formsDetails: ArrayList<ClyFormDetails>?
if(Customerly.iamLead() && appConfig.optTyped(name = "user_profiling_form_enabled", fallback = 0) == 1) {
val appStates:JSONObject? = this.optTyped<JSONObject>("app_states")
val userDataAttributes = this.optTyped<JSONObject>("user")?.parseUserDataAttributes()
formsDetails = this.optArray<JSONObject, ClyProfilingForm>(name = "user_profiling_forms", map = { it.parseProfilingForm() })
?.apply { this.sortBy { it.id } }
?.asSequence()
?.mapNotNull { form ->
if(userDataAttributes?.needFormProfiling(form) != false) {
appStates?.optJSONObject(form.appStateName)?.parseAppState()
} else {
null
}
}?.toList()?.toArrayList()
} else {
formsDetails = null
}
ClyPingResponse(
minVersion = minVersion,
widgetColor = widgetColor,
widgetBackgroundUrl = appConfig.optTyped(name = "widget_background_url"),
privacyUrl = appConfig.optTyped(name = "widget_privacy_url"),
brandedWidget = appConfig.optTyped(name = "branded_widget", fallback = 0L) == 1L,
welcomeMessageUsers = appConfig.optTyped(name = "welcome_message_users"),
welcomeMessageVisitors = appConfig.optTyped(name = "welcome_message_visitors"),
formsDetails = formsDetails,
nextOfficeHours = appConfig.optJSONObject("office_hour_next")?.parseNextOfficeHours(),
replyTime = appConfig.optTyped(name = "reply_time", fallback = 0).toClyReplyTime,
activeAdmins = activeAdmins,
lastSurveys = lastSurveys,
lastMessages = lastMessages,
allowAnonymousChat = appConfig.optTyped(name = "allow_anonymous_chat", fallback = 0) == 1)
} ?: ClyPingResponse(
minVersion = minVersion,
activeAdmins = activeAdmins,
lastSurveys = lastSurveys,
lastMessages = lastMessages)
} catch (wrongJson: JSONException) {
ClyPingResponse()
}
}
private const val PREFS_KEY_MIN_VERSION = "CUSTOMERLY_LASTPING_MIN_VERSION"
private const val PREFS_KEY_WIDGET_COLOR = "CUSTOMERLY_LASTPING_WIDGET_COLOR"
private const val PREFS_KEY_BACKGROUND_THEME_URL = "CUSTOMERLY_LASTPING_BACKGROUND_THEME_URL"
private const val PREFS_KEY_PRIVACY_URL = "CUSTOMERLY_LASTPING_PRIVACY_URL"
private const val PREFS_KEY_BRANDED_WIDGET = "CUSTOMERLY_LASTPING_POWERED_BY"
private const val PREFS_KEY_WELCOME_USERS = "CUSTOMERLY_LASTPING_WELCOME_USERS"
private const val PREFS_KEY_WELCOME_VISITORS = "CUSTOMERLY_LASTPING_WELCOME_VISITORS"
private const val PREFS_KEY_ALLOW_ANONYMOUS_CHAT = "CUSTOMERLY_LASTPING_ALLOW_ANONYMOUS_CHAT"
internal fun SharedPreferences.lastPingRestore() : ClyPingResponse {
return ClyPingResponse(
minVersion = this.safeString(PREFS_KEY_MIN_VERSION, "0.0.0"),
widgetColor = this.safeInt(PREFS_KEY_WIDGET_COLOR, Customerly.widgetColorFallback),
widgetBackgroundUrl = this.safeString(PREFS_KEY_BACKGROUND_THEME_URL),
privacyUrl = this.safeString(PREFS_KEY_PRIVACY_URL),
brandedWidget = this.safeBoolean(PREFS_KEY_BRANDED_WIDGET, true),
welcomeMessageUsers = this.safeString(PREFS_KEY_WELCOME_USERS),
welcomeMessageVisitors = this.safeString(PREFS_KEY_WELCOME_VISITORS),
allowAnonymousChat = this.safeBoolean(PREFS_KEY_ALLOW_ANONYMOUS_CHAT, false))
}
private fun SharedPreferences?.lastPingStore(lastPing: ClyPingResponse) {
this?.edit()
?.putString(PREFS_KEY_MIN_VERSION, lastPing.minVersion)
?.putInt(PREFS_KEY_WIDGET_COLOR, lastPing.widgetColor)
?.putString(PREFS_KEY_BACKGROUND_THEME_URL, lastPing.widgetBackgroundUrl)
?.putString(PREFS_KEY_PRIVACY_URL, lastPing.privacyUrl)
?.putBoolean(PREFS_KEY_BRANDED_WIDGET, lastPing.brandedWidget)
?.putString(PREFS_KEY_WELCOME_USERS, lastPing.welcomeMessageUsers)
?.putString(PREFS_KEY_WELCOME_VISITORS, lastPing.welcomeMessageVisitors)
?.putBoolean(PREFS_KEY_ALLOW_ANONYMOUS_CHAT, lastPing.allowAnonymousChat)
?.apply()
}
internal class ClyPingResponse(
internal val minVersion: String = "0.0.0",
@SXColorInt internal val widgetColor: Int = Customerly.widgetColorFallback,
internal val widgetBackgroundUrl: String? = null,
internal val privacyUrl: String? = null,
internal val brandedWidget: Boolean = true,
internal val welcomeMessageUsers: String? = null,
internal val welcomeMessageVisitors:String? = null,
internal val activeAdmins: Array<ClyAdmin>? = null,
internal val lastSurveys: Array<ClySurvey>? = null,
internal val lastMessages: Array<ClyMessage>? = null,
private val formsDetails: ArrayList<ClyFormDetails>? = null,
internal val nextOfficeHours: ClyNextOfficeHours? = null,
internal val replyTime: ClyReplyTime? = null,
internal val allowAnonymousChat: Boolean = false) {
init {
Customerly.preferences?.lastPingStore(lastPing = this)
}
internal val nextFormDetails: ClyFormDetails? get() = this.formsDetails?.firstOrNull()
internal fun setFormAnswered(form: ClyFormDetails) {
this.formsDetails?.remove(form)
}
internal fun tryShowSurvey(): Boolean {
return if(Customerly.isSurveyEnabled) {
val survey = this.lastSurveys?.firstOrNull { !it.isRejectedOrConcluded }
if(survey != null) {
survey.postDisplay()
true
} else {
Customerly.log(message = "No Survey to display")
false
}
} else {
false
}
}
internal fun tryShowLastMessage(): Boolean {
return if(Customerly.isSupportEnabled) {
val lastMessage = this.lastMessages?.firstOrNull { !it.discarded }
if(lastMessage != null) {
lastMessage.postDisplay()
true
} else {
Customerly.log(message = "No Last Messages to display")
false
}
} else {
false
}
}
}
|
apache-2.0
|
cd2897362c7009759a5f84a4c5a02fc0
| 47.757426 | 203 | 0.617892 | 4.511223 | false | true | false | false |
android/wear-os-samples
|
ComposeAdvanced/app/src/main/java/com/example/android/wearable/composeadvanced/presentation/ui/progressindicator/ProgressIndicators.kt
|
1
|
3926
|
/*
* 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.example.android.wearable.composeadvanced.presentation.ui.progressindicator
import androidx.compose.animation.core.LinearEasing
import androidx.compose.animation.core.animateFloat
import androidx.compose.animation.core.infiniteRepeatable
import androidx.compose.animation.core.rememberInfiniteTransition
import androidx.compose.animation.core.tween
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.wrapContentWidth
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.focus.FocusRequester
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.wear.compose.material.CircularProgressIndicator
import androidx.wear.compose.material.CompactChip
import androidx.wear.compose.material.ScalingLazyColumn
import androidx.wear.compose.material.ScalingLazyListAnchorType
import androidx.wear.compose.material.ScalingLazyListState
import androidx.wear.compose.material.Text
import com.example.android.wearable.composeadvanced.presentation.MenuItem
import com.google.android.horologist.compose.navscaffold.scrollableColumn
@Composable
fun ProgressIndicatorsScreen(
scalingLazyListState: ScalingLazyListState,
focusRequester: FocusRequester,
menuItems: List<MenuItem>,
modifier: Modifier = Modifier
) {
ScalingLazyColumn(
modifier = modifier
.scrollableColumn(focusRequester, scalingLazyListState)
.fillMaxWidth(),
state = scalingLazyListState,
anchorType = ScalingLazyListAnchorType.ItemStart
) {
for (menuItem in menuItems) {
item {
CompactChip(
onClick = menuItem.clickHander,
label = {
Text(
menuItem.name,
maxLines = 1,
overflow = TextOverflow.Ellipsis
)
},
modifier = Modifier.wrapContentWidth()
)
}
}
}
}
@Composable
fun IndeterminateProgressIndicator(
modifier: Modifier = Modifier
) {
Box(modifier = modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
CircularProgressIndicator()
}
}
@Composable
fun FullScreenProgressIndicator(
modifier: Modifier = Modifier
) {
val transition = rememberInfiniteTransition()
val currentRotation by transition.animateFloat(
0f,
1f,
infiniteRepeatable(
animation = tween(
durationMillis = 5000,
easing = LinearEasing,
delayMillis = 1000
)
)
)
Box(modifier = modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
CircularProgressIndicator(
startAngle = 315f,
endAngle = 225f,
progress = currentRotation,
modifier = Modifier
.fillMaxSize()
.padding(all = 1.dp)
)
}
}
|
apache-2.0
|
3f9c4d5dc384c77c6d82e81ea15338fb
| 34.053571 | 86 | 0.693581 | 5.098701 | false | false | false | false |
allotria/intellij-community
|
plugins/java-decompiler/plugin/src/org/jetbrains/java/decompiler/IdeaDecompiler.kt
|
2
|
9416
|
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.java.decompiler
import com.intellij.application.options.CodeStyle
import com.intellij.execution.filters.LineNumbersMapping
import com.intellij.ide.highlighter.JavaClassFileType
import com.intellij.ide.highlighter.JavaFileType
import com.intellij.ide.plugins.DynamicPlugins
import com.intellij.ide.plugins.IdeaPluginDescriptorImpl
import com.intellij.ide.plugins.PluginDescriptorLoader
import com.intellij.ide.plugins.PluginManagerCore
import com.intellij.ide.util.PropertiesComponent
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.extensions.PluginId
import com.intellij.openapi.fileEditor.FileEditorManager
import com.intellij.openapi.fileEditor.FileEditorManagerListener
import com.intellij.openapi.progress.ProcessCanceledException
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.ui.DialogWrapper
import com.intellij.openapi.util.Key
import com.intellij.openapi.util.UserDataHolder
import com.intellij.openapi.util.registry.Registry
import com.intellij.openapi.util.text.StringUtil
import com.intellij.openapi.util.text.Strings
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.psi.compiled.ClassFileDecompilers
import com.intellij.psi.impl.compiled.ClsFileImpl
import com.intellij.ui.components.LegalNoticeDialog
import com.intellij.util.FileContentUtilCore
import org.jetbrains.java.decompiler.main.decompiler.BaseDecompiler
import org.jetbrains.java.decompiler.main.extern.IBytecodeProvider
import org.jetbrains.java.decompiler.main.extern.IFernflowerPreferences
import org.jetbrains.java.decompiler.main.extern.IResultSaver
import java.io.File
import java.io.IOException
import java.util.concurrent.Callable
import java.util.concurrent.Future
import java.util.jar.Manifest
class IdeaDecompiler : ClassFileDecompilers.Light() {
companion object {
const val BANNER: String = "//\n// Source code recreated from a .class file by IntelliJ IDEA\n// (powered by FernFlower decompiler)\n//\n\n"
private const val LEGAL_NOTICE_KEY = "decompiler.legal.notice.accepted"
private const val POSTPONE_EXIT_CODE = DialogWrapper.CANCEL_EXIT_CODE
private const val DECLINE_EXIT_CODE = DialogWrapper.NEXT_USER_EXIT_CODE
private val TASK_KEY: Key<Future<CharSequence>> = Key.create("java.decompiler.optimistic.task")
private fun getOptions(): Map<String, Any> {
val options = CodeStyle.getDefaultSettings().getIndentOptions(JavaFileType.INSTANCE)
val indent = StringUtil.repeat(" ", options.INDENT_SIZE)
return mapOf(
IFernflowerPreferences.HIDE_DEFAULT_CONSTRUCTOR to "0",
IFernflowerPreferences.DECOMPILE_GENERIC_SIGNATURES to "1",
IFernflowerPreferences.REMOVE_SYNTHETIC to "1",
IFernflowerPreferences.REMOVE_BRIDGE to "1",
IFernflowerPreferences.LITERALS_AS_IS to "1",
IFernflowerPreferences.NEW_LINE_SEPARATOR to "1",
IFernflowerPreferences.BANNER to BANNER,
IFernflowerPreferences.MAX_PROCESSING_METHOD to 60,
IFernflowerPreferences.INDENT_STRING to indent,
IFernflowerPreferences.IGNORE_INVALID_BYTECODE to "1",
IFernflowerPreferences.VERIFY_ANONYMOUS_CLASSES to "1",
IFernflowerPreferences.UNIT_TEST_MODE to if (ApplicationManager.getApplication().isUnitTestMode) "1" else "0")
}
private fun canWork(): Boolean =
ApplicationManager.getApplication().isUnitTestMode || PropertiesComponent.getInstance().isValueSet(LEGAL_NOTICE_KEY)
}
class LegalBurden : FileEditorManagerListener.Before {
private var myShowNotice = !canWork()
override fun beforeFileOpened(source: FileEditorManager, file: VirtualFile) {
if (myShowNotice && file.fileType === JavaClassFileType.INSTANCE) {
val decompiler = ClassFileDecompilers.getInstance().find(file, ClassFileDecompilers.Light::class.java)
if (decompiler is IdeaDecompiler) {
TASK_KEY.set(file, ApplicationManager.getApplication().executeOnPooledThread(Callable { decompiler.decompile(file) }))
val title = IdeaDecompilerBundle.message("legal.notice.title", StringUtil.last(file.path, 40, true))
val message = IdeaDecompilerBundle.message("legal.notice.text")
val result = LegalNoticeDialog.build(title, message)
.withCancelText(IdeaDecompilerBundle.message("legal.notice.action.postpone"))
.withCustomAction(IdeaDecompilerBundle.message("legal.notice.action.reject"), DECLINE_EXIT_CODE)
.show()
when (result) {
DialogWrapper.OK_EXIT_CODE -> {
myShowNotice = false
PropertiesComponent.getInstance().setValue(LEGAL_NOTICE_KEY, true)
ApplicationManager.getApplication().invokeLater { FileContentUtilCore.reparseFiles(file) }
}
DECLINE_EXIT_CODE -> {
myShowNotice = false
TASK_KEY.set(file, null)
val id = PluginId.getId("org.jetbrains.java.decompiler")
PluginManagerCore.disablePlugin(id)
val plugin = PluginManagerCore.getPlugin(id)
if (plugin is IdeaPluginDescriptorImpl) {
val descriptor = PluginDescriptorLoader.loadFullDescriptor(plugin)
if (DynamicPlugins.allowLoadUnloadWithoutRestart(descriptor)) {
val task = DynamicPlugins.getPluginUnloadingTask(descriptor, DynamicPlugins.UnloadPluginOptions(disable = true, save = false))
ApplicationManager.getApplication().invokeLater(task)
}
}
}
POSTPONE_EXIT_CODE -> {
TASK_KEY.set(file, null)
}
}
}
}
}
}
private val myLogger = lazy { IdeaLogger() }
private val myOptions = lazy { getOptions() }
override fun accepts(file: VirtualFile): Boolean = true
override fun getText(file: VirtualFile): CharSequence =
if (canWork()) TASK_KEY.pop(file)?.get() ?: decompile(file)
else ClsFileImpl.decompile(file)
private fun decompile(file: VirtualFile): CharSequence {
val indicator = ProgressManager.getInstance().progressIndicator
if (indicator != null) {
indicator.text = IdeaDecompilerBundle.message("decompiling.progress", file.name)
}
try {
val mask = "${file.nameWithoutExtension}$"
val files = listOf(file) + file.parent.children.filter { it.name.startsWith(mask) && it.fileType === JavaClassFileType.INSTANCE }
val options = HashMap(myOptions.value)
if (Registry.`is`("decompiler.use.line.mapping")) {
options[IFernflowerPreferences.BYTECODE_SOURCE_MAPPING] = "1"
}
if (Registry.`is`("decompiler.dump.original.lines")) {
options[IFernflowerPreferences.DUMP_ORIGINAL_LINES] = "1"
}
val provider = MyBytecodeProvider(files)
val saver = MyResultSaver()
val decompiler = BaseDecompiler(provider, saver, options, myLogger.value)
files.forEach { decompiler.addSource(File(it.path)) }
decompiler.decompileContext()
val mapping = saver.myMapping
if (mapping != null) {
file.putUserData(LineNumbersMapping.LINE_NUMBERS_MAPPING_KEY, LineNumbersMapping.ArrayBasedMapping(mapping))
}
return saver.myResult
}
catch (e: ProcessCanceledException) {
throw e
}
catch (e: Exception) {
when {
e is IdeaLogger.InternalException && e.cause is IOException -> {
Logger.getInstance(IdeaDecompiler::class.java).warn(file.url, e)
return Strings.EMPTY_CHAR_SEQUENCE
}
ApplicationManager.getApplication().isUnitTestMode -> throw AssertionError(file.url, e)
else -> throw CannotDecompileException(file.url, e)
}
}
}
private class MyBytecodeProvider(files: List<VirtualFile>) : IBytecodeProvider {
private val pathMap = files.associateBy { File(it.path).absolutePath }
override fun getBytecode(externalPath: String, internalPath: String?): ByteArray =
pathMap[externalPath]?.contentsToByteArray(false) ?: throw AssertionError(externalPath + " not in " + pathMap.keys)
}
private class MyResultSaver : IResultSaver {
var myResult = ""
var myMapping: IntArray? = null
override fun saveClassFile(path: String, qualifiedName: String, entryName: String, content: String, mapping: IntArray?) {
if (myResult.isEmpty()) {
myResult = content
myMapping = mapping
}
}
override fun saveFolder(path: String) { }
override fun copyFile(source: String, path: String, entryName: String) { }
override fun createArchive(path: String, archiveName: String, manifest: Manifest) { }
override fun saveDirEntry(path: String, archiveName: String, entryName: String) { }
override fun copyEntry(source: String, path: String, archiveName: String, entry: String) { }
override fun saveClassEntry(path: String, archiveName: String, qualifiedName: String, entryName: String, content: String) { }
override fun closeArchive(path: String, archiveName: String) { }
}
private fun <T> Key<T>.pop(holder: UserDataHolder): T? {
val value = get(holder)
if (value != null) set(holder, null)
return value
}
}
|
apache-2.0
|
0f9a56f29b0acc8b5d9ce3653d1a43e5
| 42.795349 | 144 | 0.719732 | 4.568656 | false | false | false | false |
spring-projects/spring-framework
|
spring-webflux/src/main/kotlin/org/springframework/web/reactive/function/server/CoRouterFunctionDsl.kt
|
1
|
25138
|
/*
* Copyright 2002-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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 org.springframework.web.reactive.function.server
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.reactive.awaitSingle
import kotlinx.coroutines.reactor.mono
import org.springframework.core.io.Resource
import org.springframework.http.HttpMethod
import org.springframework.http.HttpStatusCode
import org.springframework.http.MediaType
import org.springframework.web.reactive.function.server.RouterFunctions.nest
import java.net.URI
/**
* Allow to create easily a WebFlux.fn [RouterFunction] with a [Coroutines router Kotlin DSL][CoRouterFunctionDsl].
*
* Example:
*
* ```
* @Configuration
* class RouterConfiguration {
*
* @Bean
* fun mainRouter(userHandler: UserHandler) = coRouter {
* accept(TEXT_HTML).nest {
* (GET("/user/") or GET("/users/")).invoke(userHandler::findAllView)
* GET("/users/{login}", userHandler::findViewById)
* }
* accept(APPLICATION_JSON).nest {
* (GET("/api/user/") or GET("/api/users/")).invoke(userHandler::findAll)
* POST("/api/users/", userHandler::create)
* }
* }
*
* }
* ```
*
* @author Sebastien Deleuze
* @see router
* @since 5.2
*/
fun coRouter(routes: (CoRouterFunctionDsl.() -> Unit)) =
CoRouterFunctionDsl(routes).build()
/**
* Provide a WebFlux.fn [RouterFunction] Coroutines Kotlin DSL created by [`coRouter { }`][coRouter] in order to be able to write idiomatic Kotlin code.
*
* @author Sebastien Deleuze
* @since 5.2
*/
class CoRouterFunctionDsl internal constructor (private val init: (CoRouterFunctionDsl.() -> Unit)) {
@PublishedApi
internal val builder = RouterFunctions.route()
/**
* Return a composed request predicate that tests against both this predicate AND
* the [other] predicate (String processed as a path predicate). When evaluating the
* composed predicate, if this predicate is `false`, then the [other] predicate is not
* evaluated.
* @see RequestPredicate.and
* @see RequestPredicates.path
*/
infix fun RequestPredicate.and(other: String): RequestPredicate = this.and(path(other))
/**
* Return a composed request predicate that tests against both this predicate OR
* the [other] predicate (String processed as a path predicate). When evaluating the
* composed predicate, if this predicate is `true`, then the [other] predicate is not
* evaluated.
* @see RequestPredicate.or
* @see RequestPredicates.path
*/
infix fun RequestPredicate.or(other: String): RequestPredicate = this.or(path(other))
/**
* Return a composed request predicate that tests against both this predicate (String
* processed as a path predicate) AND the [other] predicate. When evaluating the
* composed predicate, if this predicate is `false`, then the [other] predicate is not
* evaluated.
* @see RequestPredicate.and
* @see RequestPredicates.path
*/
infix fun String.and(other: RequestPredicate): RequestPredicate = path(this).and(other)
/**
* Return a composed request predicate that tests against both this predicate (String
* processed as a path predicate) OR the [other] predicate. When evaluating the
* composed predicate, if this predicate is `true`, then the [other] predicate is not
* evaluated.
* @see RequestPredicate.or
* @see RequestPredicates.path
*/
infix fun String.or(other: RequestPredicate): RequestPredicate = path(this).or(other)
/**
* Return a composed request predicate that tests against both this predicate AND
* the [other] predicate. When evaluating the composed predicate, if this
* predicate is `false`, then the [other] predicate is not evaluated.
* @see RequestPredicate.and
*/
infix fun RequestPredicate.and(other: RequestPredicate): RequestPredicate = this.and(other)
/**
* Return a composed request predicate that tests against both this predicate OR
* the [other] predicate. When evaluating the composed predicate, if this
* predicate is `true`, then the [other] predicate is not evaluated.
* @see RequestPredicate.or
*/
infix fun RequestPredicate.or(other: RequestPredicate): RequestPredicate = this.or(other)
/**
* Return a predicate that represents the logical negation of this predicate.
*/
operator fun RequestPredicate.not(): RequestPredicate = this.negate()
/**
* Route to the given router function if the given request predicate applies. This
* method can be used to create *nested routes*, where a group of routes share a
* common path (prefix), header, or other request predicate.
* @see RouterFunctions.nest
*/
fun RequestPredicate.nest(r: (CoRouterFunctionDsl.() -> Unit)) {
builder.add(nest(this, CoRouterFunctionDsl(r).build()))
}
/**
* Route to the given router function if the given request predicate (String
* processed as a path predicate) applies. This method can be used to create
* *nested routes*, where a group of routes share a common path
* (prefix), header, or other request predicate.
* @see RouterFunctions.nest
* @see RequestPredicates.path
*/
fun String.nest(r: (CoRouterFunctionDsl.() -> Unit)) = path(this).nest(r)
/**
* Adds a route to the given handler function that handles all HTTP `GET` requests
* that match the given pattern.
* @param pattern the pattern to match to
*/
fun GET(pattern: String, f: suspend (ServerRequest) -> ServerResponse) {
builder.GET(pattern, asHandlerFunction(f))
}
/**
* Adds a route to the given handler function that handles all HTTP `GET` requests
* that match the given pattern.
* @param pattern the pattern to match to
* @param predicate additional predicate to match
* @since 5.2
*/
fun GET(pattern: String, predicate: RequestPredicate, f: suspend (ServerRequest) -> ServerResponse) {
builder.GET(pattern, predicate, asHandlerFunction(f))
}
/**
* Return a [RequestPredicate] that matches if request's HTTP method is `GET`
* and the given `pattern` matches against the request path.
* @see RequestPredicates.GET
*/
fun GET(pattern: String): RequestPredicate = RequestPredicates.GET(pattern)
/**
* Adds a route to the given handler function that handles all HTTP `HEAD` requests
* that match the given pattern.
* @param pattern the pattern to match to
*/
fun HEAD(pattern: String, f: suspend (ServerRequest) -> ServerResponse) {
builder.HEAD(pattern, asHandlerFunction(f))
}
/**
* Adds a route to the given handler function that handles all HTTP `HEAD` requests
* that match the given pattern.
* @param pattern the pattern to match to
* @param predicate additional predicate to match
* @since 5.2
*/
fun HEAD(pattern: String, predicate: RequestPredicate, f: suspend (ServerRequest) -> ServerResponse) {
builder.HEAD(pattern, predicate, asHandlerFunction(f))
}
/**
* Return a [RequestPredicate] that matches if request's HTTP method is `HEAD`
* and the given `pattern` matches against the request path.
* @see RequestPredicates.HEAD
*/
fun HEAD(pattern: String): RequestPredicate = RequestPredicates.HEAD(pattern)
/**
* Adds a route to the given handler function that handles all HTTP `POST` requests
* that match the given pattern.
* @param pattern the pattern to match to
*/
fun POST(pattern: String, f: suspend (ServerRequest) -> ServerResponse) {
builder.POST(pattern, asHandlerFunction(f))
}
/**
* Adds a route to the given handler function that handles all HTTP `POST` requests
* that match the given pattern.
* @param pattern the pattern to match to
* @param predicate additional predicate to match
* @since 5.2
*/
fun POST(pattern: String, predicate: RequestPredicate, f: suspend (ServerRequest) -> ServerResponse) {
builder.POST(pattern, predicate, asHandlerFunction(f))
}
/**
* Return a [RequestPredicate] that matches if request's HTTP method is `POST`
* and the given `pattern` matches against the request path.
* @see RequestPredicates.POST
*/
fun POST(pattern: String): RequestPredicate = RequestPredicates.POST(pattern)
/**
* Adds a route to the given handler function that handles all HTTP `PUT` requests
* that match the given pattern.
* @param pattern the pattern to match to
*/
fun PUT(pattern: String, f: suspend (ServerRequest) -> ServerResponse) {
builder.PUT(pattern, asHandlerFunction(f))
}
/**
* Adds a route to the given handler function that handles all HTTP `PUT` requests
* that match the given pattern.
* @param pattern the pattern to match to
* @param predicate additional predicate to match
* @since 5.2
*/
fun PUT(pattern: String, predicate: RequestPredicate, f: suspend (ServerRequest) -> ServerResponse) {
builder.PUT(pattern, predicate, asHandlerFunction(f))
}
/**
* Return a [RequestPredicate] that matches if request's HTTP method is `PUT`
* and the given `pattern` matches against the request path.
* @see RequestPredicates.PUT
*/
fun PUT(pattern: String): RequestPredicate = RequestPredicates.PUT(pattern)
/**
* Adds a route to the given handler function that handles all HTTP `PATCH` requests
* that match the given pattern.
* @param pattern the pattern to match to
*/
fun PATCH(pattern: String, f: suspend (ServerRequest) -> ServerResponse) {
builder.PATCH(pattern, asHandlerFunction(f))
}
/**
* Adds a route to the given handler function that handles all HTTP `PATCH` requests
* that match the given pattern.
* @param pattern the pattern to match to
* @param predicate additional predicate to match
* @since 5.2
*/
fun PATCH(pattern: String, predicate: RequestPredicate, f: suspend (ServerRequest) -> ServerResponse) {
builder.PATCH(pattern, predicate, asHandlerFunction(f))
}
/**
* Return a [RequestPredicate] that matches if request's HTTP method is `PATCH`
* and the given `pattern` matches against the request path.
* @param pattern the path pattern to match against
* @return a predicate that matches if the request method is `PATCH` and if the given pattern
* matches against the request path
*/
fun PATCH(pattern: String): RequestPredicate = RequestPredicates.PATCH(pattern)
/**
* Adds a route to the given handler function that handles all HTTP `DELETE` requests
* that match the given pattern.
* @param pattern the pattern to match to
*/
fun DELETE(pattern: String, f: suspend (ServerRequest) -> ServerResponse) {
builder.DELETE(pattern, asHandlerFunction(f))
}
/**
* Adds a route to the given handler function that handles all HTTP `DELETE` requests
* that match the given pattern.
* @param pattern the pattern to match to
* @param predicate additional predicate to match
* @since 5.2
*/
fun DELETE(pattern: String, predicate: RequestPredicate, f: suspend (ServerRequest) -> ServerResponse) {
builder.DELETE(pattern, predicate, asHandlerFunction(f))
}
/**
* Return a [RequestPredicate] that matches if request's HTTP method is `DELETE`
* and the given `pattern` matches against the request path.
* @param pattern the path pattern to match against
* @return a predicate that matches if the request method is `DELETE` and if the given pattern
* matches against the request path
*/
fun DELETE(pattern: String): RequestPredicate = RequestPredicates.DELETE(pattern)
/**
* Adds a route to the given handler function that handles all HTTP `OPTIONS` requests
* that match the given pattern.
* @param pattern the pattern to match to
*/
fun OPTIONS(pattern: String, f: suspend (ServerRequest) -> ServerResponse) {
builder.OPTIONS(pattern, asHandlerFunction(f))
}
/**
* Adds a route to the given handler function that handles all HTTP `OPTIONS` requests
* that match the given pattern.
* @param pattern the pattern to match to
* @param predicate additional predicate to match
* @since 5.2
*/
fun OPTIONS(pattern: String, predicate: RequestPredicate, f: suspend (ServerRequest) -> ServerResponse) {
builder.OPTIONS(pattern, predicate, asHandlerFunction(f))
}
/**
* Return a [RequestPredicate] that matches if request's HTTP method is `OPTIONS`
* and the given `pattern` matches against the request path.
* @param pattern the path pattern to match against
* @return a predicate that matches if the request method is `OPTIONS` and if the given pattern
* matches against the request path
*/
fun OPTIONS(pattern: String): RequestPredicate = RequestPredicates.OPTIONS(pattern)
/**
* Route to the given handler function if the given accept predicate applies.
* @see RouterFunctions.route
*/
fun accept(mediaType: MediaType, f: suspend (ServerRequest) -> ServerResponse) {
builder.add(RouterFunctions.route(RequestPredicates.accept(mediaType), asHandlerFunction(f)))
}
/**
* Return a [RequestPredicate] that tests if the request's
* [accept][ServerRequest.Headers.accept] } header is
* [compatible][MediaType.isCompatibleWith] with any of the given media types.
* @param mediaType the media types to match the request's accept header against
* @return a predicate that tests the request's accept header against the given media types
*/
fun accept(vararg mediaType: MediaType): RequestPredicate = RequestPredicates.accept(*mediaType)
/**
* Route to the given handler function if the given contentType predicate applies.
* @see RouterFunctions.route
*/
fun contentType(mediaType: MediaType, f: suspend (ServerRequest) -> ServerResponse) {
builder.add(RouterFunctions.route(RequestPredicates.contentType(mediaType), asHandlerFunction(f)))
}
/**
* Return a [RequestPredicate] that tests if the request's
* [content type][ServerRequest.Headers.contentType] is
* [included][MediaType.includes] by any of the given media types.
* @param mediaTypes the media types to match the request's content type against
* @return a predicate that tests the request's content type against the given media types
*/
fun contentType(vararg mediaTypes: MediaType): RequestPredicate = RequestPredicates.contentType(*mediaTypes)
/**
* Route to the given handler function if the given headers predicate applies.
* @see RouterFunctions.route
*/
fun headers(headersPredicate: (ServerRequest.Headers) -> Boolean, f: suspend (ServerRequest) -> ServerResponse) {
builder.add(RouterFunctions.route(RequestPredicates.headers(headersPredicate), asHandlerFunction(f)))
}
/**
* Return a [RequestPredicate] that tests the request's headers against the given headers predicate.
* @param headersPredicate a predicate that tests against the request headers
* @return a predicate that tests against the given header predicate
*/
fun headers(headersPredicate: (ServerRequest.Headers) -> Boolean): RequestPredicate =
RequestPredicates.headers(headersPredicate)
/**
* Route to the given handler function if the given method predicate applies.
* @see RouterFunctions.route
*/
fun method(httpMethod: HttpMethod, f: suspend (ServerRequest) -> ServerResponse) {
builder.add(RouterFunctions.route(RequestPredicates.method(httpMethod), asHandlerFunction(f)))
}
/**
* Return a [RequestPredicate] that tests against the given HTTP method.
* @param httpMethod the HTTP method to match to
* @return a predicate that tests against the given HTTP method
*/
fun method(httpMethod: HttpMethod): RequestPredicate = RequestPredicates.method(httpMethod)
/**
* Route to the given handler function if the given path predicate applies.
* @see RouterFunctions.route
*/
fun path(pattern: String, f: suspend (ServerRequest) -> ServerResponse) {
builder.add(RouterFunctions.route(RequestPredicates.path(pattern), asHandlerFunction(f)))
}
/**
* Return a [RequestPredicate] that tests the request path against the given path pattern.
* @see RequestPredicates.path
*/
fun path(pattern: String): RequestPredicate = RequestPredicates.path(pattern)
/**
* Route to the given handler function if the given pathExtension predicate applies.
* @see RouterFunctions.route
*/
fun pathExtension(extension: String, f: suspend (ServerRequest) -> ServerResponse) {
builder.add(RouterFunctions.route(RequestPredicates.pathExtension(extension), asHandlerFunction(f)))
}
/**
* Return a [RequestPredicate] that matches if the request's path has the given extension.
* @param extension the path extension to match against, ignoring case
* @return a predicate that matches if the request's path has the given file extension
*/
fun pathExtension(extension: String): RequestPredicate = RequestPredicates.pathExtension(extension)
/**
* Route to the given handler function if the given pathExtension predicate applies.
* @see RouterFunctions.route
*/
fun pathExtension(predicate: (String) -> Boolean, f: suspend (ServerRequest) -> ServerResponse) {
builder.add(RouterFunctions.route(RequestPredicates.pathExtension(predicate), asHandlerFunction(f)))
}
/**
* Return a [RequestPredicate] that matches if the request's path matches the given
* predicate.
* @see RequestPredicates.pathExtension
*/
fun pathExtension(predicate: (String) -> Boolean): RequestPredicate =
RequestPredicates.pathExtension(predicate)
/**
* Route to the given handler function if the given queryParam predicate applies.
* @see RouterFunctions.route
*/
fun queryParam(name: String, predicate: (String) -> Boolean, f: suspend (ServerRequest) -> ServerResponse) {
builder.add(RouterFunctions.route(RequestPredicates.queryParam(name, predicate), asHandlerFunction(f)))
}
/**
* Return a [RequestPredicate] that tests the request's query parameter of the given name
* against the given predicate.
* @param name the name of the query parameter to test against
* @param predicate the predicate to test against the query parameter value
* @return a predicate that matches the given predicate against the query parameter of the given name
* @see ServerRequest#queryParam
*/
fun queryParam(name: String, predicate: (String) -> Boolean): RequestPredicate =
RequestPredicates.queryParam(name, predicate)
/**
* Route to the given handler function if the given request predicate applies.
* @see RouterFunctions.route
*/
operator fun RequestPredicate.invoke(f: suspend (ServerRequest) -> ServerResponse) {
builder.add(RouterFunctions.route(this, asHandlerFunction(f)))
}
/**
* Route to the given handler function if the given predicate (String
* processed as a path predicate) applies.
* @see RouterFunctions.route
*/
operator fun String.invoke(f: suspend (ServerRequest) -> ServerResponse) {
builder.add(RouterFunctions.route(RequestPredicates.path(this), asHandlerFunction(f)))
}
/**
* Route requests that match the given pattern to resources relative to the given root location.
* @see RouterFunctions.resources
*/
fun resources(path: String, location: Resource) {
builder.resources(path, location)
}
/**
* Route to resources using the provided lookup function. If the lookup function provides a
* [Resource] for the given request, it will be it will be exposed using a
* [HandlerFunction] that handles GET, HEAD, and OPTIONS requests.
*/
fun resources(lookupFunction: suspend (ServerRequest) -> Resource?) {
builder.resources {
mono(Dispatchers.Unconfined) {
lookupFunction.invoke(it)
}
}
}
/**
* Merge externally defined router functions into this one.
* @param routerFunction the router function to be added
* @since 5.2
*/
fun add(routerFunction: RouterFunction<ServerResponse>) {
builder.add(routerFunction)
}
/**
* Filters all routes created by this router with the given filter function. Filter
* functions are typically used to address cross-cutting concerns, such as logging,
* security, etc.
* @param filterFunction the function to filter all routes built by this router
* @since 5.2
*/
fun filter(filterFunction: suspend (ServerRequest, suspend (ServerRequest) -> ServerResponse) -> ServerResponse) {
builder.filter { serverRequest, handlerFunction ->
mono(Dispatchers.Unconfined) {
filterFunction(serverRequest) { handlerRequest ->
handlerFunction.handle(handlerRequest).awaitSingle()
}
}
}
}
/**
* Filter the request object for all routes created by this builder with the given request
* processing function. Filters are typically used to address cross-cutting concerns, such
* as logging, security, etc.
* @param requestProcessor a function that transforms the request
* @since 5.2
*/
fun before(requestProcessor: (ServerRequest) -> ServerRequest) {
builder.before(requestProcessor)
}
/**
* Filter the response object for all routes created by this builder with the given response
* processing function. Filters are typically used to address cross-cutting concerns, such
* as logging, security, etc.
* @param responseProcessor a function that transforms the response
* @since 5.2
*/
fun after(responseProcessor: (ServerRequest, ServerResponse) -> ServerResponse) {
builder.after(responseProcessor)
}
/**
* Filters all exceptions that match the predicate by applying the given response provider
* function.
* @param predicate the type of exception to filter
* @param responseProvider a function that creates a response
* @since 5.2
*/
fun onError(predicate: (Throwable) -> Boolean, responseProvider: suspend (Throwable, ServerRequest) -> ServerResponse) {
builder.onError(predicate) { throwable, request ->
mono(Dispatchers.Unconfined) { responseProvider.invoke(throwable, request) }
}
}
/**
* Filters all exceptions that match the predicate by applying the given response provider
* function.
* @param E the type of exception to filter
* @param responseProvider a function that creates a response
* @since 5.2
*/
inline fun <reified E : Throwable> onError(noinline responseProvider: suspend (Throwable, ServerRequest) -> ServerResponse) {
builder.onError({it is E}) { throwable, request ->
mono(Dispatchers.Unconfined) { responseProvider.invoke(throwable, request) }
}
}
/**
* Add an attribute with the given name and value to the last route built with this builder.
* @param name the attribute name
* @param value the attribute value
- * @since 6.0
*/
fun withAttribute(name: String, value: Any) {
builder.withAttribute(name, value)
}
/**
* Manipulate the attributes of the last route built with the given consumer.
*
* The map provided to the consumer is "live", so that the consumer can be used
* to [overwrite][MutableMap.put] existing attributes,
* [remove][MutableMap.remove] attributes, or use any of the other
* [MutableMap] methods.
* @param attributesConsumer a function that consumes the attributes map
* @since 6.0
*/
fun withAttributes(attributesConsumer: (MutableMap<String, Any>) -> Unit) {
builder.withAttributes(attributesConsumer)
}
/**
* Return a composed routing function created from all the registered routes.
*/
internal fun build(): RouterFunction<ServerResponse> {
init()
return builder.build()
}
private fun asHandlerFunction(init: suspend (ServerRequest) -> ServerResponse) = HandlerFunction {
mono(Dispatchers.Unconfined) {
init(it)
}
}
/**
* @see ServerResponse.from
*/
fun from(other: ServerResponse) =
ServerResponse.from(other)
/**
* @see ServerResponse.created
*/
fun created(location: URI) =
ServerResponse.created(location)
/**
* @see ServerResponse.ok
*/
fun ok() = ServerResponse.ok()
/**
* @see ServerResponse.noContent
*/
fun noContent() = ServerResponse.noContent()
/**
* @see ServerResponse.accepted
*/
fun accepted() = ServerResponse.accepted()
/**
* @see ServerResponse.permanentRedirect
*/
fun permanentRedirect(location: URI) = ServerResponse.permanentRedirect(location)
/**
* @see ServerResponse.temporaryRedirect
*/
fun temporaryRedirect(location: URI) = ServerResponse.temporaryRedirect(location)
/**
* @see ServerResponse.seeOther
*/
fun seeOther(location: URI) = ServerResponse.seeOther(location)
/**
* @see ServerResponse.badRequest
*/
fun badRequest() = ServerResponse.badRequest()
/**
* @see ServerResponse.notFound
*/
fun notFound() = ServerResponse.notFound()
/**
* @see ServerResponse.unprocessableEntity
*/
fun unprocessableEntity() = ServerResponse.unprocessableEntity()
/**
* @see ServerResponse.status
*/
fun status(status: HttpStatusCode) = ServerResponse.status(status)
/**
* @see ServerResponse.status
*/
fun status(status: Int) = ServerResponse.status(status)
}
/**
* Equivalent to [RouterFunction.and].
*/
operator fun <T: ServerResponse> RouterFunction<T>.plus(other: RouterFunction<T>) =
this.and(other)
|
apache-2.0
|
28b315ca7ff6b62b791b1d2e11d38857
| 34.911429 | 152 | 0.734506 | 4.19456 | false | false | false | false |
JuliusKunze/kotlin-native
|
backend.native/tests/external/codegen/box/increment/assignPlusOnSmartCast.kt
|
3
|
164
|
public fun box() : String {
var i : Int?
i = 10
// assignPlus on a smart cast should work
i += 1
return if (11 == i) "OK" else "fail i = $i"
}
|
apache-2.0
|
c99012fd9e4c9d2c97242377bd583e0f
| 19.5 | 47 | 0.518293 | 3.09434 | false | false | false | false |
smmribeiro/intellij-community
|
jvm/jvm-analysis-impl/src/com/intellij/codeInspection/UnstableApiUsageInspection.kt
|
9
|
13249
|
// 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.codeInspection
import com.intellij.analysis.JvmAnalysisBundle
import com.intellij.codeInsight.AnnotationUtil
import com.intellij.codeInsight.StaticAnalysisAnnotationManager
import com.intellij.codeInspection.AnnotatedApiUsageUtil.findAnnotatedContainingDeclaration
import com.intellij.codeInspection.AnnotatedApiUsageUtil.findAnnotatedTypeUsedInDeclarationSignature
import com.intellij.codeInspection.apiUsage.ApiUsageProcessor
import com.intellij.codeInspection.apiUsage.ApiUsageUastVisitor
import com.intellij.codeInspection.deprecation.DeprecationInspection
import com.intellij.codeInspection.ui.MultipleCheckboxOptionsPanel
import com.intellij.codeInspection.util.InspectionMessage
import com.intellij.codeInspection.util.SpecialAnnotationsUtil
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.roots.ProjectFileIndex
import com.intellij.psi.*
import com.intellij.psi.util.PsiUtilCore
import com.intellij.util.ArrayUtilRt
import com.siyeh.ig.ui.ExternalizableStringSet
import org.jetbrains.annotations.ApiStatus
import org.jetbrains.uast.*
import javax.swing.JPanel
class UnstableApiUsageInspection : LocalInspectionTool() {
companion object {
private val SCHEDULED_FOR_REMOVAL_ANNOTATION_NAME: String = ApiStatus.ScheduledForRemoval::class.java.canonicalName
private val knownAnnotationMessageProviders = mapOf(SCHEDULED_FOR_REMOVAL_ANNOTATION_NAME to ScheduledForRemovalMessageProvider())
}
@JvmField
val unstableApiAnnotations: List<String> =
ExternalizableStringSet(*ArrayUtilRt.toStringArray(StaticAnalysisAnnotationManager.getInstance().knownUnstableApiAnnotations))
@JvmField
var myIgnoreInsideImports: Boolean = true
@JvmField
var myIgnoreApiDeclaredInThisProject: Boolean = true
override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean): PsiElementVisitor {
val annotations = unstableApiAnnotations.toList()
return if (annotations.any { AnnotatedApiUsageUtil.canAnnotationBeUsedInFile(it, holder.file) }) {
ApiUsageUastVisitor.createPsiElementVisitor(
UnstableApiUsageProcessor(
holder,
myIgnoreInsideImports,
myIgnoreApiDeclaredInThisProject,
annotations,
knownAnnotationMessageProviders
)
)
} else {
PsiElementVisitor.EMPTY_VISITOR
}
}
override fun createOptionsPanel(): JPanel {
val panel = MultipleCheckboxOptionsPanel(this)
panel.addCheckbox(JvmAnalysisBundle.message("jvm.inspections.unstable.api.usage.ignore.inside.imports"), "myIgnoreInsideImports")
panel.addCheckbox(JvmAnalysisBundle.message("jvm.inspections.unstable.api.usage.ignore.declared.inside.this.project"), "myIgnoreApiDeclaredInThisProject")
//TODO in add annotation window "Include non-project items" should be enabled by default
val annotationsListControl = SpecialAnnotationsUtil.createSpecialAnnotationsListControl(
unstableApiAnnotations, JvmAnalysisBundle.message("jvm.inspections.unstable.api.usage.annotations.list")
)
panel.add(annotationsListControl, "growx, wrap")
return panel
}
}
private class UnstableApiUsageProcessor(
private val problemsHolder: ProblemsHolder,
private val ignoreInsideImports: Boolean,
private val ignoreApiDeclaredInThisProject: Boolean,
private val unstableApiAnnotations: List<String>,
private val knownAnnotationMessageProviders: Map<String, UnstableApiUsageMessageProvider>
) : ApiUsageProcessor {
private companion object {
fun isLibraryElement(element: PsiElement): Boolean {
if (ApplicationManager.getApplication().isUnitTestMode) {
return true
}
val containingVirtualFile = PsiUtilCore.getVirtualFile(element)
return containingVirtualFile != null && ProjectFileIndex.getInstance(element.project).isInLibraryClasses(containingVirtualFile)
}
}
override fun processImportReference(sourceNode: UElement, target: PsiModifierListOwner) {
if (!ignoreInsideImports) {
checkUnstableApiUsage(target, sourceNode, false)
}
}
override fun processReference(sourceNode: UElement, target: PsiModifierListOwner, qualifier: UExpression?) {
checkUnstableApiUsage(target, sourceNode, false)
}
override fun processConstructorInvocation(
sourceNode: UElement,
instantiatedClass: PsiClass,
constructor: PsiMethod?,
subclassDeclaration: UClass?
) {
if (constructor != null) {
checkUnstableApiUsage(constructor, sourceNode, false)
}
}
override fun processMethodOverriding(method: UMethod, overriddenMethod: PsiMethod) {
checkUnstableApiUsage(overriddenMethod, method, true)
}
private fun getMessageProvider(psiAnnotation: PsiAnnotation): UnstableApiUsageMessageProvider? {
val annotationName = psiAnnotation.qualifiedName ?: return null
return knownAnnotationMessageProviders[annotationName] ?: DefaultUnstableApiUsageMessageProvider
}
private fun getElementToHighlight(sourceNode: UElement): PsiElement? =
(sourceNode as? UDeclaration)?.uastAnchor.sourcePsiElement ?: sourceNode.sourcePsi
private fun checkUnstableApiUsage(target: PsiModifierListOwner, sourceNode: UElement, isMethodOverriding: Boolean) {
if (ignoreApiDeclaredInThisProject && !isLibraryElement(target)) {
return
}
if (checkTargetIsUnstableItself(target, sourceNode, isMethodOverriding)) {
return
}
checkTargetReferencesUnstableTypeInSignature(target, sourceNode, isMethodOverriding)
}
private fun checkTargetIsUnstableItself(target: PsiModifierListOwner, sourceNode: UElement, isMethodOverriding: Boolean): Boolean {
val annotatedContainingDeclaration = findAnnotatedContainingDeclaration(target, unstableApiAnnotations, true)
if (annotatedContainingDeclaration != null) {
val messageProvider = getMessageProvider(annotatedContainingDeclaration.psiAnnotation) ?: return false
val message = if (isMethodOverriding) {
messageProvider.buildMessageUnstableMethodOverridden(annotatedContainingDeclaration)
}
else {
messageProvider.buildMessage(annotatedContainingDeclaration)
}
val elementToHighlight = getElementToHighlight(sourceNode) ?: return false
problemsHolder.registerProblem(elementToHighlight, message, messageProvider.problemHighlightType)
return true
}
return false
}
private fun checkTargetReferencesUnstableTypeInSignature(target: PsiModifierListOwner, sourceNode: UElement, isMethodOverriding: Boolean) {
if (!isMethodOverriding && !arePsiElementsFromTheSameFile(sourceNode.sourcePsi, target.containingFile)) {
val declaration = target.toUElement(UDeclaration::class.java)
if (declaration !is UClass && declaration !is UMethod && declaration !is UField) {
return
}
val unstableTypeUsedInSignature = findAnnotatedTypeUsedInDeclarationSignature(declaration, unstableApiAnnotations)
if (unstableTypeUsedInSignature != null) {
val messageProvider = getMessageProvider(unstableTypeUsedInSignature.psiAnnotation) ?: return
val message = messageProvider.buildMessageUnstableTypeIsUsedInSignatureOfReferencedApi(target, unstableTypeUsedInSignature)
val elementToHighlight = getElementToHighlight(sourceNode) ?: return
problemsHolder.registerProblem(elementToHighlight, message, messageProvider.problemHighlightType)
}
}
}
private fun arePsiElementsFromTheSameFile(one: PsiElement?, two: PsiElement?): Boolean {
//For Kotlin: naive comparison of PSI containingFile-s does not work because one of the PSI elements might be light PSI element
// coming from a light PSI file, and another element would be physical PSI file, and they are not "equals()".
return one?.containingFile?.virtualFile == two?.containingFile?.virtualFile
}
}
private interface UnstableApiUsageMessageProvider {
val problemHighlightType: ProblemHighlightType
@InspectionMessage
fun buildMessage(annotatedContainingDeclaration: AnnotatedContainingDeclaration): String
@InspectionMessage
fun buildMessageUnstableMethodOverridden(annotatedContainingDeclaration: AnnotatedContainingDeclaration): String
@InspectionMessage
fun buildMessageUnstableTypeIsUsedInSignatureOfReferencedApi(
referencedApi: PsiModifierListOwner,
annotatedTypeUsedInSignature: AnnotatedContainingDeclaration
): String
}
private object DefaultUnstableApiUsageMessageProvider : UnstableApiUsageMessageProvider {
override val problemHighlightType
get() = ProblemHighlightType.GENERIC_ERROR_OR_WARNING
override fun buildMessageUnstableMethodOverridden(annotatedContainingDeclaration: AnnotatedContainingDeclaration): String =
with(annotatedContainingDeclaration) {
if (isOwnAnnotation) {
JvmAnalysisBundle.message("jvm.inspections.unstable.api.usage.overridden.method.is.marked.unstable.itself", targetName, presentableAnnotationName)
}
else {
JvmAnalysisBundle.message(
"jvm.inspections.unstable.api.usage.overridden.method.is.declared.in.unstable.api",
targetName,
containingDeclarationType,
containingDeclarationName,
presentableAnnotationName
)
}
}
override fun buildMessage(annotatedContainingDeclaration: AnnotatedContainingDeclaration): String =
with(annotatedContainingDeclaration) {
if (isOwnAnnotation) {
JvmAnalysisBundle.message("jvm.inspections.unstable.api.usage.api.is.marked.unstable.itself", targetName, presentableAnnotationName)
}
else {
JvmAnalysisBundle.message(
"jvm.inspections.unstable.api.usage.api.is.declared.in.unstable.api",
targetName,
containingDeclarationType,
containingDeclarationName,
presentableAnnotationName
)
}
}
override fun buildMessageUnstableTypeIsUsedInSignatureOfReferencedApi(
referencedApi: PsiModifierListOwner,
annotatedTypeUsedInSignature: AnnotatedContainingDeclaration
): String = JvmAnalysisBundle.message(
"jvm.inspections.unstable.api.usage.unstable.type.is.used.in.signature.of.referenced.api",
DeprecationInspection.getPresentableName(referencedApi),
annotatedTypeUsedInSignature.targetType,
annotatedTypeUsedInSignature.targetName,
annotatedTypeUsedInSignature.presentableAnnotationName
)
}
private class ScheduledForRemovalMessageProvider : UnstableApiUsageMessageProvider {
override val problemHighlightType
get() = ProblemHighlightType.GENERIC_ERROR
override fun buildMessageUnstableMethodOverridden(annotatedContainingDeclaration: AnnotatedContainingDeclaration): String {
val versionMessage = getVersionMessage(annotatedContainingDeclaration)
return with(annotatedContainingDeclaration) {
if (isOwnAnnotation) {
JvmAnalysisBundle.message(
"jvm.inspections.scheduled.for.removal.method.overridden.marked.itself",
targetName,
versionMessage
)
}
else {
JvmAnalysisBundle.message(
"jvm.inspections.scheduled.for.removal.method.overridden.declared.in.marked.api",
targetName,
containingDeclarationType,
containingDeclarationName,
versionMessage
)
}
}
}
override fun buildMessage(annotatedContainingDeclaration: AnnotatedContainingDeclaration): String {
val versionMessage = getVersionMessage(annotatedContainingDeclaration)
return with(annotatedContainingDeclaration) {
if (!isOwnAnnotation) {
JvmAnalysisBundle.message(
"jvm.inspections.scheduled.for.removal.api.is.declared.in.marked.api",
targetName,
containingDeclarationType,
containingDeclarationName,
versionMessage
)
}
else {
JvmAnalysisBundle.message(
"jvm.inspections.scheduled.for.removal.api.is.marked.itself", targetName, versionMessage
)
}
}
}
override fun buildMessageUnstableTypeIsUsedInSignatureOfReferencedApi(
referencedApi: PsiModifierListOwner,
annotatedTypeUsedInSignature: AnnotatedContainingDeclaration
): String {
val versionMessage = getVersionMessage(annotatedTypeUsedInSignature)
return JvmAnalysisBundle.message(
"jvm.inspections.scheduled.for.removal.scheduled.for.removal.type.is.used.in.signature.of.referenced.api",
DeprecationInspection.getPresentableName(referencedApi),
annotatedTypeUsedInSignature.targetType,
annotatedTypeUsedInSignature.targetName,
versionMessage
)
}
private fun getVersionMessage(annotatedContainingDeclaration: AnnotatedContainingDeclaration): String {
val versionValue = AnnotationUtil.getDeclaredStringAttributeValue(annotatedContainingDeclaration.psiAnnotation, "inVersion")
return if (versionValue.isNullOrEmpty()) {
JvmAnalysisBundle.message("jvm.inspections.scheduled.for.removal.future.version")
}
else {
JvmAnalysisBundle.message("jvm.inspections.scheduled.for.removal.predefined.version", versionValue)
}
}
}
|
apache-2.0
|
b8fb584f64cdbf32cd4651d68900a85f
| 40.93038 | 158 | 0.777115 | 5.450021 | false | false | false | false |
smmribeiro/intellij-community
|
platform/lang-impl/src/com/intellij/ide/navigationToolbar/StructureAwareNavBarModelExtension.kt
|
2
|
5984
|
// 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.ide.navigationToolbar
import com.intellij.ide.structureView.StructureViewModel
import com.intellij.ide.structureView.StructureViewTreeElement
import com.intellij.ide.structureView.TreeBasedStructureViewBuilder
import com.intellij.ide.structureView.impl.common.PsiTreeElementBase
import com.intellij.ide.ui.UISettings
import com.intellij.ide.util.treeView.smartTree.NodeProvider
import com.intellij.ide.util.treeView.smartTree.TreeElement
import com.intellij.lang.Language
import com.intellij.lang.LanguageStructureViewBuilder
import com.intellij.openapi.actionSystem.CommonDataKeys
import com.intellij.openapi.actionSystem.DataContext
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.IndexNotReadyException
import com.intellij.openapi.util.Key
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
import com.intellij.reference.SoftReference
import com.intellij.util.Processor
import org.jetbrains.annotations.NotNull
import org.jetbrains.annotations.Nullable
abstract class StructureAwareNavBarModelExtension : AbstractNavBarModelExtension() {
protected abstract val language: Language
private var currentFile: SoftReference<PsiFile>? = null
private var currentFileStructure: SoftReference<StructureViewModel>? = null
private var currentFileModCount = -1L
override fun getLeafElement(dataContext: DataContext): PsiElement? {
if (UISettings.instance.showMembersInNavigationBar) {
val psiFile = CommonDataKeys.PSI_FILE.getData(dataContext)
val editor = CommonDataKeys.EDITOR.getData(dataContext)
if (psiFile == null || !psiFile.isValid || editor == null) return null
val psiElement = psiFile.findElementAt(editor.caretModel.offset)
if (isAcceptableLanguage(psiElement)) {
try {
buildStructureViewModel(psiFile, editor)?.let { model ->
return (model.currentEditorElement as? PsiElement)?.originalElement
}
}
catch (ignored: IndexNotReadyException) {
}
}
}
return null
}
protected open fun isAcceptableLanguage(psiElement: @Nullable PsiElement?) = psiElement?.language == language
override fun processChildren(`object`: Any,
rootElement: Any?,
processor: Processor<Any>): Boolean {
if (UISettings.instance.showMembersInNavigationBar) {
(`object` as? PsiElement)?.let { psiElement ->
if (isAcceptableLanguage(psiElement)) {
buildStructureViewModel(psiElement.containingFile)?.let { model ->
return processStructureViewChildren(model.root, `object`, processor)
}
}
}
}
return super.processChildren(`object`, rootElement, processor)
}
override fun getParent(psiElement: PsiElement?): PsiElement? {
if (isAcceptableLanguage(psiElement)) {
val file = psiElement?.containingFile ?: return null
val model = buildStructureViewModel(file)
if (model != null) {
val parentInModel = findParentInModel(model.root, psiElement)
if (acceptParentFromModel(parentInModel)) {
return parentInModel
}
}
}
return super.getParent(psiElement)
}
protected open fun acceptParentFromModel(psiElement: PsiElement?): Boolean {
return true
}
protected open fun findParentInModel(root: StructureViewTreeElement, psiElement: PsiElement): PsiElement? {
for (child in childrenFromNodeAndProviders(root)) {
if ((child as StructureViewTreeElement).value == psiElement) {
return root.value as? PsiElement
}
findParentInModel(child, psiElement)?.let { return it }
}
return null
}
protected fun buildStructureViewModel(file: PsiFile, editor: Editor? = null): StructureViewModel? {
if (currentFile?.get() == file && currentFileModCount == file.modificationStamp) {
if (editor == null) {
currentFileStructure?.get()?.let { return it }
}
else {
val editorStructure = editor.getUserData(MODEL)
editorStructure?.get()?.let { return it }
}
}
val model = createModel(file, editor)
if (model != null) {
currentFile = SoftReference(file)
currentFileStructure = SoftReference(model)
currentFileModCount = file.modificationStamp
editor?.putUserData(MODEL, currentFileStructure)
}
return model
}
protected open fun createModel(file: PsiFile, editor: Editor?): @NotNull StructureViewModel? {
val builder = LanguageStructureViewBuilder.INSTANCE.getStructureViewBuilder(file)
return (builder as? TreeBasedStructureViewBuilder)?.createStructureViewModel(editor)
}
private fun processStructureViewChildren(parent: StructureViewTreeElement,
`object`: Any,
processor: Processor<Any>): Boolean {
if (parent.value == `object`) {
return childrenFromNodeAndProviders(parent)
.filterIsInstance<StructureViewTreeElement>()
.all { processor.process(it.value) }
}
return childrenFromNodeAndProviders(parent)
.filterIsInstance<StructureViewTreeElement>()
.all { processStructureViewChildren(it, `object`, processor) }
}
protected open fun childrenFromNodeAndProviders(parent: StructureViewTreeElement): List<TreeElement> {
val children = if (parent is PsiTreeElementBase<*>) parent.childrenWithoutCustomRegions else parent.children.toList()
return children + applicableNodeProviders.flatMap { it.provideNodes(parent) }
}
override fun normalizeChildren() = false
protected open val applicableNodeProviders: List<NodeProvider<*>> = emptyList()
companion object {
val MODEL: Key<SoftReference<StructureViewModel>?> = Key.create("editor.structure.model")
}
}
|
apache-2.0
|
ec19bf7e29d3ed98fd49893b40471426
| 39.439189 | 158 | 0.720254 | 5.007531 | false | false | false | false |
ianhanniballake/muzei
|
example-unsplash/src/main/java/com/example/muzei/unsplash/UnsplashRedirectActivity.kt
|
2
|
4169
|
/*
* Copyright 2020 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.muzei.unsplash
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.util.Log
import android.widget.Toast
import androidx.activity.ComponentActivity
import androidx.activity.result.contract.ActivityResultContracts.StartActivityForResult
import com.google.android.apps.muzei.api.MuzeiContract
/**
* This activity's sole purpose is to redirect users to Muzei, which is where they should
* activate Muzei and then select the Unsplash source.
*
* You'll note the usage of the `enable_launcher` boolean resource value to only enable
* this on API 29+ devices as it is on API 29+ that a launcher icon becomes mandatory for
* every app.
*/
class UnsplashRedirectActivity : ComponentActivity() {
companion object {
private const val TAG = "UnsplashRedirect"
private const val MUZEI_PACKAGE_NAME = "net.nurik.roman.muzei"
private const val PLAY_STORE_LINK = "https://play.google.com/store/apps/details?id=$MUZEI_PACKAGE_NAME"
}
private val requestLauncher = registerForActivityResult(StartActivityForResult()) {
// It doesn't matter what the result is, the important part is that the
// user hit the back button to return to this activity. Since this activity
// has no UI of its own, we can simply finish the activity.
finish()
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
// First check whether Unsplash is already selected
val launchIntent = packageManager.getLaunchIntentForPackage(MUZEI_PACKAGE_NAME)
if (MuzeiContract.Sources.isProviderSelected(this, BuildConfig.UNSPLASH_AUTHORITY)
&& launchIntent != null) {
// Already selected so just open Muzei
requestLauncher.launch(launchIntent)
return
}
// Build the list of Intents plus the Toast message that should be displayed
// to users when we successfully launch one of the Intents
val intents = listOf(
MuzeiContract.Sources.createChooseProviderIntent(BuildConfig.UNSPLASH_AUTHORITY)
to R.string.toast_enable_unsplash,
launchIntent
to R.string.toast_enable_unsplash_source,
Intent(Intent.ACTION_VIEW).setData(Uri.parse(PLAY_STORE_LINK))
to R.string.toast_muzei_missing_error)
// Go through each Intent/message pair, trying each in turn
val success = intents.fold(false) { success, (intent, toastMessage) ->
if (success) {
// If one launch has succeeded, we don't need to
// try any further Intents
return@fold success
}
if (intent == null) {
// A null Intent means there's nothing to attempt to launch
return@fold false
}
try {
requestLauncher.launch(intent)
// Only if the launch succeeds do we show the Toast and trigger success
Toast.makeText(this, toastMessage, Toast.LENGTH_LONG).show()
true
} catch (e: Exception) {
Log.v(TAG, "Intent $intent failed", e)
false
}
}
if (!success) {
// Only if all Intents failed do we show a 'everything failed' Toast
Toast.makeText(this, R.string.toast_play_store_missing_error, Toast.LENGTH_LONG).show()
finish()
}
}
}
|
apache-2.0
|
1986ba18878c0c108d038447ec5f076d
| 42.427083 | 111 | 0.653634 | 4.732123 | false | false | false | false |
android/compose-samples
|
Jetchat/app/src/main/java/com/example/compose/jetchat/UiExtras.kt
|
1
|
1331
|
/*
* Copyright 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.compose.jetchat
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
@Composable
fun FunctionalityNotAvailablePopup(onDismiss: () -> Unit) {
AlertDialog(
onDismissRequest = onDismiss,
text = {
Text(
text = "Functionality not available \uD83D\uDE48",
style = MaterialTheme.typography.bodyMedium
)
},
confirmButton = {
TextButton(onClick = onDismiss) {
Text(text = "CLOSE")
}
}
)
}
|
apache-2.0
|
99311b4a210befc860b04a07f0be5067
| 31.463415 | 75 | 0.68595 | 4.558219 | false | false | false | false |
fabmax/kool
|
kool-physics/src/jsMain/kotlin/de/fabmax/kool/physics/joints/DistanceJoint.kt
|
1
|
1585
|
package de.fabmax.kool.physics.joints
import de.fabmax.kool.math.Mat4f
import de.fabmax.kool.physics.MemoryStack
import de.fabmax.kool.physics.Physics
import de.fabmax.kool.physics.RigidActor
import de.fabmax.kool.physics.toPxTransform
import physx.*
actual class DistanceJoint actual constructor(
actual val bodyA: RigidActor,
actual val bodyB: RigidActor,
posA: Mat4f,
posB: Mat4f
) : Joint() {
actual val frameA = Mat4f().set(posA)
actual val frameB = Mat4f().set(posB)
override val pxJoint: PxDistanceJoint
init {
Physics.checkIsLoaded()
MemoryStack.stackPush().use { mem ->
val frmA = frameA.toPxTransform(mem.createPxTransform())
val frmB = frameB.toPxTransform(mem.createPxTransform())
pxJoint = Physics.Px.DistanceJointCreate(Physics.physics, bodyA.pxRigidActor, frmA, bodyB.pxRigidActor, frmB)
}
}
actual fun setMaxDistance(maxDistance: Float) {
pxJoint.maxDistance = maxDistance
pxJoint.setDistanceJointFlag(PxDistanceJointFlagEnum.eMAX_DISTANCE_ENABLED, maxDistance >= 0f)
}
actual fun setMinDistance(minDistance: Float) {
pxJoint.minDistance = minDistance
pxJoint.setDistanceJointFlag(PxDistanceJointFlagEnum.eMIN_DISTANCE_ENABLED, minDistance >= 0f)
}
actual fun removeMaxDistance() {
pxJoint.setDistanceJointFlag(PxDistanceJointFlagEnum.eMAX_DISTANCE_ENABLED, false)
}
actual fun removeMinDistance() {
pxJoint.setDistanceJointFlag(PxDistanceJointFlagEnum.eMIN_DISTANCE_ENABLED, false)
}
}
|
apache-2.0
|
3bfdabc098718b9f41c5bcb6deb45498
| 33.478261 | 121 | 0.721136 | 3.923267 | false | false | false | false |
viartemev/requestmapper
|
src/main/kotlin/com/viartemev/requestmapper/model/PopupPath.kt
|
1
|
852
|
package com.viartemev.requestmapper.model
/**
* format: METHOD PATH PARAMS(if presents)
* example: GET /account/activate params=some
*/
class PopupPath(popupItem: String) : Comparable<PopupPath> {
private val path = popupItem.split(' ')[1]
private val method = popupItem.split(' ')[0]
fun toPath() = Path(path)
companion object : Comparator<PopupPath> {
private val comparator: java.util.Comparator<PopupPath> = Comparator { o1: PopupPath, o2: PopupPath -> o1.method.compareTo(o2.method) }
.thenComparing { o1: PopupPath, o2: PopupPath -> o1.path.length.compareTo(o2.path.length) }
override fun compare(o1: PopupPath?, o2: PopupPath?): Int {
return comparator.compare(o1, o2)
}
}
override fun compareTo(other: PopupPath): Int {
return compare(this, other)
}
}
|
mit
|
ac4578e7d2f53f224daa401e2e9cfc4f
| 33.08 | 143 | 0.661972 | 3.55 | false | false | false | false |
jotomo/AndroidAPS
|
danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_Basal_Get_Profile_Basal_Rate.kt
|
1
|
1596
|
package info.nightscout.androidaps.danars.comm
import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.logging.LTag
import info.nightscout.androidaps.dana.DanaPump
import info.nightscout.androidaps.danars.encryption.BleEncryption
import java.util.*
import javax.inject.Inject
open class DanaRS_Packet_Basal_Get_Profile_Basal_Rate(
injector: HasAndroidInjector,
private val profileNumber: Int = 0
) : DanaRS_Packet(injector) {
@Inject lateinit var danaPump: DanaPump
init {
opCode = BleEncryption.DANAR_PACKET__OPCODE_BASAL__GET_PROFILE_BASAL_RATE
aapsLogger.debug(LTag.PUMPCOMM, "Requesting basal rates for profile $profileNumber")
}
override fun getRequestParams(): ByteArray {
val request = ByteArray(1)
request[0] = (profileNumber and 0xff).toByte()
return request
}
override fun handleMessage(data: ByteArray) {
var dataIndex = DATA_START
var dataSize = 2
danaPump.pumpProfiles = Array(4) { Array(48) { 0.0 } }
var i = 0
val size = 24
while (i < size) {
danaPump.pumpProfiles!![profileNumber][i] = byteArrayToInt(getBytes(data, dataIndex, dataSize)) / 100.0
dataIndex += dataSize
dataSize = 2
i++
}
for (index in 0..23)
aapsLogger.debug(LTag.PUMPCOMM, "Basal " + String.format(Locale.ENGLISH, "%02d", index) + "h: " + danaPump.pumpProfiles!![profileNumber][index])
}
override fun getFriendlyName(): String {
return "BASAL__GET_PROFILE_BASAL_RATE"
}
}
|
agpl-3.0
|
28fd587c1217555427311be0b80d2cd7
| 32.978723 | 156 | 0.664787 | 4.244681 | false | false | false | false |
fabmax/kool
|
kool-core/src/commonMain/kotlin/de/fabmax/kool/InputManager.kt
|
1
|
31316
|
package de.fabmax.kool
import de.fabmax.kool.util.*
import kotlin.math.abs
abstract class InputManager internal constructor() {
private val queuedKeyEvents: MutableList<KeyEvent> = mutableListOf()
val keyEvents: MutableList<KeyEvent> = mutableListOf()
private var currentKeyMods = 0
private var currentKeyRepeated = 0
private val keyHandlers = mutableMapOf<KeyCode, MutableList<KeyEventListener>>()
abstract var cursorMode: CursorMode
abstract var cursorShape: CursorShape
val pointerState = PointerState()
val isShiftDown: Boolean get() = (currentKeyMods and KEY_MOD_SHIFT) != 0
val isCtrlDown: Boolean get() = (currentKeyMods and KEY_MOD_CTRL) != 0
val isAltDown: Boolean get() = (currentKeyMods and KEY_MOD_ALT) != 0
val isSuperDown: Boolean get() = (currentKeyMods and KEY_MOD_SUPER) != 0
fun registerKeyListener(keyCode: KeyCode, name: String, filter: (KeyEvent) -> Boolean = { true }, callback: (KeyEvent) -> Unit): KeyEventListener {
val keyStr = keyCode.toString()
val listeners = keyHandlers.getOrPut(keyCode) { mutableListOf() }
if (listeners.isNotEmpty()) {
logW { "Multiple bindings for key $keyStr: ${listeners.map { it.name }}" }
}
val handler = KeyEventListener(keyCode, name, filter, callback)
listeners += handler
logD { "Registered key handler: \"$name\" [keyCode=$keyStr]" }
return handler
}
fun removeKeyListener(listener: KeyEventListener) {
val listeners = keyHandlers[listener.keyCode] ?: return
listeners -= listener
}
fun getKeyCodeForChar(char: Char) = char.uppercaseChar().code
internal fun onNewFrame(ctx: KoolContext) {
pointerState.onNewFrame(ctx)
keyEvents.clear()
keyEvents.addAll(queuedKeyEvents)
queuedKeyEvents.clear()
for (i in keyEvents.indices) {
val evt = keyEvents[i]
if (evt.keyCode.code != 0) {
keyHandlers[evt.keyCode]?.let { listeners ->
for (j in listeners.indices) {
if (listeners[j].filter(evt)) {
listeners[j](evt)
}
}
}
}
if (evt.localKeyCode.code != 0) {
keyHandlers[evt.localKeyCode]?.let { listeners ->
for (j in listeners.indices) {
if (listeners[j].filter(evt)) {
listeners[j](evt)
}
}
}
}
}
InputStack.handleInput(this, ctx)
}
fun keyEvent(ev: KeyEvent) {
currentKeyMods = ev.modifiers
currentKeyRepeated = ev.event and KEY_EV_REPEATED
queuedKeyEvents.add(ev)
}
fun charTyped(typedChar: Char) {
val ev = KeyEvent(LocalKeyCode(typedChar.code), KEY_EV_CHAR_TYPED or currentKeyRepeated, currentKeyMods)
ev.typedChar = typedChar
queuedKeyEvents.add(ev)
}
//
// mouse and touch handler functions to be called by platform code
//
fun handleTouchStart(pointerId: Int, x: Double, y: Double) = pointerState.handleTouchStart(pointerId, x, y)
fun handleTouchEnd(pointerId: Int) = pointerState.handleTouchEnd(pointerId)
fun handleTouchCancel(pointerId: Int) = pointerState.handleTouchCancel(pointerId)
fun handleTouchMove(pointerId: Int, x: Double, y: Double) = pointerState.handleTouchMove(pointerId, x, y)
fun handleMouseMove(x: Double, y: Double) = pointerState.handleMouseMove(x, y)
fun handleMouseButtonState(button: Int, down: Boolean) = pointerState.handleMouseButtonEvent(button, down)
fun handleMouseScroll(xTicks: Double, yTicks: Double) = pointerState.handleMouseScroll(xTicks, yTicks)
fun handleMouseExit() = pointerState.handleMouseExit()
open class Pointer {
var id = 0
internal set
var x = 0.0
internal set
var y = 0.0
internal set
var deltaX = 0.0
internal set
var deltaY = 0.0
internal set
var dragDeltaX = 0.0
internal set
var dragDeltaY = 0.0
internal set
var deltaScrollY = 0.0
internal set
var deltaScrollX = 0.0
internal set
val deltaScroll: Double
get() = deltaScrollY
var buttonMask = 0
internal set(value) {
buttonEventMask = buttonEventMask or (field xor value)
field = value
if (buttonEventMask and value != 0) {
updateButtonDownTimes()
}
}
var buttonEventMask = 0
internal set
var isValid = false
internal set
protected val buttonClickTimes = DoubleArray(5)
protected val buttonClickFrames = IntArray(5)
protected val buttonDownTimes = DoubleArray(5)
protected val buttonDownFrames = IntArray(5)
internal var consumptionMask = 0
internal var dragMovement = 0.0
val isAnyButtonDown: Boolean get() = buttonMask != 0
val isLeftButtonDown: Boolean get() = (buttonMask and LEFT_BUTTON_MASK) != 0
val isRightButtonDown: Boolean get() = (buttonMask and RIGHT_BUTTON_MASK) != 0
val isMiddleButtonDown: Boolean get() = (buttonMask and MIDDLE_BUTTON_MASK) != 0
val isBackButtonDown: Boolean get() = (buttonMask and BACK_BUTTON_MASK) != 0
val isForwardButtonDown: Boolean get() = (buttonMask and FORWARD_BUTTON_MASK) != 0
val isAnyButtonEvent: Boolean get() = buttonEventMask != 0
val isLeftButtonEvent: Boolean get() = (buttonEventMask and LEFT_BUTTON_MASK) != 0
val isRightButtonEvent: Boolean get() = (buttonEventMask and RIGHT_BUTTON_MASK) != 0
val isMiddleButtonEvent: Boolean get() = (buttonEventMask and MIDDLE_BUTTON_MASK) != 0
val isBackButtonEvent: Boolean get() = (buttonEventMask and BACK_BUTTON_MASK) != 0
val isForwardButtonEvent: Boolean get() = (buttonEventMask and FORWARD_BUTTON_MASK) != 0
val isLeftButtonPressed: Boolean get() = isLeftButtonEvent && isLeftButtonDown
val isRightButtonPressed: Boolean get() = isRightButtonEvent && isRightButtonDown
val isMiddleButtonPressed: Boolean get() = isMiddleButtonEvent && isMiddleButtonDown
val isBackButtonPressed: Boolean get() = isBackButtonEvent && isBackButtonDown
val isForwardButtonPressed: Boolean get() = isForwardButtonEvent && isForwardButtonDown
val isLeftButtonReleased: Boolean get() = isLeftButtonEvent && !isLeftButtonDown
val isRightButtonReleased: Boolean get() = isRightButtonEvent && !isRightButtonDown
val isMiddleButtonReleased: Boolean get() = isMiddleButtonEvent && !isMiddleButtonDown
val isBackButtonReleased: Boolean get() = isBackButtonEvent && !isBackButtonDown
val isForwardButtonReleased: Boolean get() = isForwardButtonEvent && !isForwardButtonDown
var isLeftButtonClicked = false
internal set
var isRightButtonClicked = false
internal set
var isMiddleButtonClicked = false
internal set
var isBackButtonClicked = false
internal set
var isForwardButtonClicked = false
internal set
var leftButtonRepeatedClickCount = 0
internal set
var rightButtonRepeatedClickCount = 0
internal set
var middleButtonRepeatedClickCount = 0
internal set
var backButtonRepeatedClickCount = 0
internal set
var forwardButtonRepeatedClickCount = 0
internal set
val isDrag: Boolean get() = isAnyButtonDown && (dragDeltaX != 0.0 || dragDeltaY != 0.0)
fun consume(mask: Int = CONSUMED_ALL) {
consumptionMask = consumptionMask or mask
}
fun isConsumed(mask: Int = CONSUMED_ALL) = (consumptionMask and mask) != 0
/**
* Usually, if a pointer is outside the viewport, it is not valid. However, they can be
* outside a viewport and valid, if there is more than one viewport (e.g. split viewport
* demo).
*/
fun isInViewport(viewport: Viewport, ctx: KoolContext): Boolean {
// y-axis of viewport is inverted to window coordinates
val ptrY = ctx.windowHeight - y
return (isValid) && viewport.isInViewport(x.toFloat(), ptrY.toFloat())
}
private fun updateButtonDownTimes() {
val downEvents = buttonEventMask and buttonMask
for (i in buttonDownTimes.indices) {
if (downEvents and (1 shl i) != 0) {
buttonDownTimes[i] = Time.precisionTime
buttonDownFrames[i] = Time.frameCount
}
}
}
}
internal class BufferedPointerInput : Pointer() {
private var updateState = UpdateState.INVALID
private var processedState = UpdateState.INVALID
private val buttonEventQueue = List<MutableList<Boolean>>(8) { mutableListOf() }
private var gotPointerEvents = false
var lastUpdate = 0.0
fun enqueueButtonEvent(button: Int, down: Boolean) {
if (button !in buttonEventQueue.indices) {
logW { "Discarding pointer button event for out of bounds button: $button" }
return
}
buttonEventQueue[button] += down
gotPointerEvents = true
}
fun processPointerEvents() {
clearClickStates()
while (gotPointerEvents) {
gotPointerEvents = false
// clear click states before every button event iteration so that we can count repeated click events
clearClickStates()
// process enqueued button events, update button mask after each iteration, so that we get click events
// even if a button was pressed and released again within a single frame
var updateMask = buttonMask
buttonEventQueue.forEachIndexed { button, events ->
if (events.isNotEmpty()) {
val event = events.removeAt(0)
updateMask = if (event) {
updateMask or (1 shl button)
} else {
updateMask and (1 shl button).inv()
}
if (events.isNotEmpty()) {
// there are button events left in the queue, continue processing them after all buttons
// are handled for this iteration
gotPointerEvents = true
}
}
}
buttonMask = updateMask
// reset drag tracker if left / mid / right button has been pressed
if (isLeftButtonPressed || isRightButtonPressed || isMiddleButtonPressed) {
dragDeltaX = 0.0
dragDeltaY = 0.0
dragMovement = 0.0
}
updateClickStates()
}
}
fun startPointer(pointerId: Int, x: Double, y: Double) {
movePointer(x, y)
id = pointerId
deltaX = 0.0
deltaY = 0.0
dragDeltaX = 0.0
dragDeltaY = 0.0
dragMovement = 0.0
deltaScrollX = 0.0
deltaScrollY = 0.0
updateState = UpdateState.STARTED
isValid = true
}
fun movePointer(x: Double, y: Double) {
val wasDrag = dragMovement != 0.0
if (isAnyButtonDown) {
dragDeltaX += x - this.x
dragDeltaY += y - this.y
dragMovement += abs(x - this.x) + abs(y - this.y)
}
deltaX += x - this.x
deltaY += y - this.y
// Do not update the position if a drag has just started - this way drag start events are guaranteed
// to have the same position as the previous hover event. Otherwise, the drag event might not be received
// by the correct receiver if the first movement is too large and / or the hover / drag target is very
// small (e.g. resizing of a window border)
if (!isDrag || isDrag == wasDrag) {
this.x = x
this.y = y
}
lastUpdate = Time.precisionTime
}
fun endPointer() {
updateState = when (processedState) {
UpdateState.ACTIVE -> UpdateState.ENDED
UpdateState.STARTED -> UpdateState.ENDED_BEFORE_ACTIVE
else -> UpdateState.ENDED_BEFORE_STARTED
}
}
fun cancelPointer() {
buttonMask = 0
buttonEventMask = 0
deltaX = 0.0
deltaY = 0.0
deltaScrollX = 0.0
deltaScrollY = 0.0
dragDeltaX = 0.0
dragDeltaY = 0.0
dragMovement = 0.0
updateState = UpdateState.INVALID
isValid = false
}
fun update(target: Pointer, t: Double) {
if (updateState != UpdateState.INVALID && t - lastUpdate > 200) {
logW { "Pointer $id timed out!" }
cancelPointer()
}
processPointerEvents()
target.id = id
target.deltaX = deltaX
target.deltaY = deltaY
target.dragDeltaX = dragDeltaX
target.dragDeltaY = dragDeltaY
target.dragMovement = dragMovement
target.deltaScrollX = deltaScrollX
target.deltaScrollY = deltaScrollY
target.x = x
target.y = y
target.isValid = true
target.consumptionMask = 0
target.buttonEventMask = 0
target.isLeftButtonClicked = isLeftButtonClicked
target.isRightButtonClicked = isRightButtonClicked
target.isMiddleButtonClicked = isMiddleButtonClicked
target.isBackButtonClicked = isBackButtonClicked
target.isForwardButtonClicked = isForwardButtonClicked
target.leftButtonRepeatedClickCount = leftButtonRepeatedClickCount
target.rightButtonRepeatedClickCount = rightButtonRepeatedClickCount
target.middleButtonRepeatedClickCount = middleButtonRepeatedClickCount
target.backButtonRepeatedClickCount = backButtonRepeatedClickCount
target.forwardButtonRepeatedClickCount = forwardButtonRepeatedClickCount
when (updateState) {
UpdateState.STARTED -> target.buttonMask = 0
UpdateState.ENDED_BEFORE_STARTED -> target.buttonMask = 0
UpdateState.ACTIVE -> target.buttonMask = buttonMask
UpdateState.ENDED_BEFORE_ACTIVE -> target.buttonMask = buttonMask
UpdateState.ENDED -> target.buttonMask = 0
UpdateState.INVALID -> {
isValid = false
target.isValid = false
}
}
deltaX = 0.0
deltaY = 0.0
deltaScrollX = 0.0
deltaScrollY = 0.0
buttonEventMask = 0
processedState = updateState
updateState = updateState.next()
}
private fun clearClickStates() {
isLeftButtonClicked = false
isRightButtonClicked = false
isMiddleButtonClicked = false
isBackButtonClicked = false
isForwardButtonClicked = false
}
private fun updateClickStates() {
isLeftButtonClicked = isClick(isLeftButtonReleased, 0, dragMovement)
isRightButtonClicked = isClick(isRightButtonReleased, 1, dragMovement)
isMiddleButtonClicked = isClick(isMiddleButtonReleased, 2, dragMovement)
isBackButtonClicked = isClick(isBackButtonReleased, 3, dragMovement)
isForwardButtonClicked = isClick(isForwardButtonReleased, 4, dragMovement)
leftButtonRepeatedClickCount = updateRepeatedClickCount(isLeftButtonClicked, 0, leftButtonRepeatedClickCount)
rightButtonRepeatedClickCount = updateRepeatedClickCount(isRightButtonClicked, 0, rightButtonRepeatedClickCount)
middleButtonRepeatedClickCount = updateRepeatedClickCount(isMiddleButtonClicked, 0, middleButtonRepeatedClickCount)
backButtonRepeatedClickCount = updateRepeatedClickCount(isBackButtonClicked, 0, backButtonRepeatedClickCount)
forwardButtonRepeatedClickCount = updateRepeatedClickCount(isForwardButtonClicked, 0, forwardButtonRepeatedClickCount)
if (isLeftButtonClicked) {
buttonClickTimes[0] = Time.precisionTime
buttonClickFrames[0] = Time.frameCount
}
if (isRightButtonClicked) {
buttonClickTimes[1] = Time.precisionTime
buttonClickFrames[1] = Time.frameCount
}
if (isMiddleButtonClicked) {
buttonClickTimes[2] = Time.precisionTime
buttonClickFrames[2] = Time.frameCount
}
if (isBackButtonClicked) {
buttonClickTimes[3] = Time.precisionTime
buttonClickFrames[3] = Time.frameCount
}
if (isForwardButtonClicked) {
buttonClickTimes[4] = Time.precisionTime
buttonClickFrames[4] = Time.frameCount
}
}
private fun isClick(isReleased: Boolean, buttonI: Int, dragMovement: Double): Boolean {
val pressedTime = buttonDownTimes[buttonI]
val pressedFrame = buttonDownFrames[buttonI]
return isReleased && dragMovement < MAX_CLICK_MOVE_PX
&& (Time.precisionTime - pressedTime < MAX_CLICK_TIME_SECS || Time.frameCount - pressedFrame == 1)
}
private fun updateRepeatedClickCount(isClick: Boolean, buttonI: Int, currentClickCount: Int): Int {
val dt = Time.precisionTime - buttonClickTimes[buttonI]
val dFrm = Time.frameCount - buttonClickFrames[buttonI]
return if (!isClick && dt > DOUBLE_CLICK_INTERVAL_SECS && dFrm > 2) {
0
} else if (isClick) {
currentClickCount + 1
} else {
currentClickCount
}
}
/**
* State machine for handling pointer state, needed for correct mouse button emulation for touch events.
*/
enum class UpdateState {
STARTED {
override fun next(): UpdateState = ACTIVE
},
ACTIVE {
override fun next(): UpdateState = ACTIVE
},
ENDED_BEFORE_STARTED {
override fun next(): UpdateState = ENDED_BEFORE_ACTIVE
},
ENDED_BEFORE_ACTIVE {
override fun next(): UpdateState = ENDED
},
ENDED {
override fun next(): UpdateState = INVALID
},
INVALID {
override fun next(): UpdateState = INVALID
};
abstract fun next(): UpdateState
}
}
class KeyEventListener(val keyCode: KeyCode, val name: String, val filter: (KeyEvent) -> Boolean = { true }, val callback: (KeyEvent) -> Unit) {
operator fun invoke(evt: KeyEvent) = callback.invoke(evt)
}
class KeyEvent(keyCode: KeyCode, localKeyCode: KeyCode, event: Int, modifiers: Int) {
/**
* Key code for US keyboard layout
*/
var keyCode = keyCode
internal set
/**
* Key code for local keyboard layout
*/
var localKeyCode = localKeyCode
internal set
var modifiers = modifiers
internal set
var event = event
internal set
var typedChar: Char = 0.toChar()
internal set
constructor(keyCode: KeyCode, event: Int, modifiers: Int) : this(keyCode, keyCode, event, modifiers)
val isPressed: Boolean get() = (event and KEY_EV_DOWN) != 0
val isRepeated: Boolean get() = (event and KEY_EV_REPEATED) != 0
val isReleased: Boolean get() = (event and KEY_EV_UP) != 0
val isCharTyped: Boolean get() = (event and KEY_EV_CHAR_TYPED) != 0
val isShiftDown: Boolean get() = (modifiers and KEY_MOD_SHIFT) != 0
val isCtrlDown: Boolean get() = (modifiers and KEY_MOD_CTRL) != 0
val isAltDown: Boolean get() = (modifiers and KEY_MOD_ALT) != 0
val isSuperDown: Boolean get() = (modifiers and KEY_MOD_SUPER) != 0
}
class PointerState {
val pointers = Array(MAX_POINTERS) { Pointer() }
private var lastPtrInput = 0.0
private val inputPointers = Array(MAX_POINTERS) { BufferedPointerInput() }
private val compatGestureEvaluator = TouchGestureEvaluator()
var isEvaluatingCompatGestures = true
/**
* The primary pointer. For mouse-input that's the mouse cursor, for touch-input it's the first finger
* that touched the screen. Keep in mind that the returned [Pointer] might be invalid (i.e. [Pointer.isValid] is
* false) if the cursor exited the GL surface or if no finger touches the screen.
*/
val primaryPointer = pointers[0]
fun getActivePointers(result: MutableList<Pointer>, consumedMask: Int = CONSUMED_ALL) {
result.clear()
// pointers.filter { it.isValid }.forEach { result.add(it) }
for (i in pointers.indices) {
if (pointers[i].isValid && !pointers[i].isConsumed(consumedMask)) {
result.add(pointers[i])
}
}
}
internal fun onNewFrame(ctx: KoolContext) {
for (i in pointers.indices) {
inputPointers[i].update(pointers[i], lastPtrInput)
}
if (isEvaluatingCompatGestures) {
compatGestureEvaluator.evaluate(this, ctx)
when (compatGestureEvaluator.currentGesture.type) {
TouchGestureEvaluator.PINCH -> {
// set primary pointer deltaScroll for compatibility with mouse input
primaryPointer.consumptionMask = 0
primaryPointer.deltaScrollY = compatGestureEvaluator.currentGesture.dPinchAmount / 20.0
primaryPointer.x = compatGestureEvaluator.currentGesture.centerCurrent.x
primaryPointer.y = compatGestureEvaluator.currentGesture.centerCurrent.y
primaryPointer.deltaX = compatGestureEvaluator.currentGesture.dCenter.x
primaryPointer.deltaY = compatGestureEvaluator.currentGesture.dCenter.y
}
TouchGestureEvaluator.TWO_FINGER_DRAG -> {
// set primary pointer right button down for compatibility with mouse input
primaryPointer.consumptionMask = 0
primaryPointer.x = compatGestureEvaluator.currentGesture.centerCurrent.x
primaryPointer.y = compatGestureEvaluator.currentGesture.centerCurrent.y
primaryPointer.deltaX = compatGestureEvaluator.currentGesture.dCenter.x
primaryPointer.deltaY = compatGestureEvaluator.currentGesture.dCenter.y
if (primaryPointer.buttonMask == LEFT_BUTTON_MASK) {
primaryPointer.buttonMask = RIGHT_BUTTON_MASK
if (compatGestureEvaluator.currentGesture.numUpdates > 1){
primaryPointer.buttonEventMask = 0
}
}
}
}
}
}
private fun getFreeInputPointer(): BufferedPointerInput? {
for (i in inputPointers.indices) {
if (!inputPointers[i].isValid) {
return inputPointers[i]
}
}
return null
}
private fun findInputPointer(pointerId: Int): BufferedPointerInput? {
for (i in inputPointers.indices) {
if (inputPointers[i].isValid && inputPointers[i].id == pointerId) {
return inputPointers[i]
}
}
return null
}
internal fun handleTouchStart(pointerId: Int, x: Double, y: Double) {
lastPtrInput = Time.precisionTime
val inPtr = getFreeInputPointer() ?: return
inPtr.startPointer(pointerId, x, y)
inPtr.buttonMask = 1
}
internal fun handleTouchEnd(pointerId: Int) {
findInputPointer(pointerId)?.endPointer()
}
internal fun handleTouchCancel(pointerId: Int) {
findInputPointer(pointerId)?.cancelPointer()
}
internal fun handleTouchMove(pointerId: Int, x: Double, y: Double) {
lastPtrInput = Time.precisionTime
findInputPointer(pointerId)?.movePointer(x, y)
}
//
// mouse handler functions to be called by platform code
//
internal fun handleMouseMove(x: Double, y: Double) {
lastPtrInput = Time.precisionTime
val mousePtr = findInputPointer(MOUSE_POINTER_ID)
if (mousePtr == null) {
val startPtr = getFreeInputPointer() ?: return
startPtr.startPointer(MOUSE_POINTER_ID, x, y)
} else {
mousePtr.movePointer(x, y)
}
}
internal fun handleMouseButtonEvent(button: Int, down: Boolean) {
val ptr = findInputPointer(MOUSE_POINTER_ID) ?: return
ptr.enqueueButtonEvent(button, down)
}
internal fun handleMouseScroll(xTicks: Double, yTicks: Double) {
val ptr = findInputPointer(MOUSE_POINTER_ID) ?: return
ptr.deltaScrollX += xTicks
ptr.deltaScrollY += yTicks
}
internal fun handleMouseExit() {
findInputPointer(MOUSE_POINTER_ID)?.cancelPointer()
}
}
enum class CursorMode {
NORMAL,
LOCKED
}
enum class CursorShape {
DEFAULT,
TEXT,
CROSSHAIR,
HAND,
H_RESIZE,
V_RESIZE
}
companion object {
const val MAX_CLICK_MOVE_PX = 15.0
const val MAX_CLICK_TIME_SECS = 0.25
const val DOUBLE_CLICK_INTERVAL_SECS = 0.35
const val LEFT_BUTTON = 0
const val LEFT_BUTTON_MASK = 1
const val RIGHT_BUTTON = 1
const val RIGHT_BUTTON_MASK = 2
const val MIDDLE_BUTTON = 2
const val MIDDLE_BUTTON_MASK = 4
const val BACK_BUTTON = 3
const val BACK_BUTTON_MASK = 8
const val FORWARD_BUTTON = 4
const val FORWARD_BUTTON_MASK = 16
const val MAX_POINTERS = 10
const val MOUSE_POINTER_ID = -1000000
const val CONSUMED_ALL = -1 // 0xffffffff
const val CONSUMED_LEFT_BUTTON = LEFT_BUTTON_MASK
const val CONSUMED_RIGHT_BUTTON = RIGHT_BUTTON_MASK
const val CONSUMED_MIDDLE_BUTTON = MIDDLE_BUTTON_MASK
const val CONSUMED_BACK_BUTTON = BACK_BUTTON_MASK
const val CONSUMED_FORWARD_BUTTON = FORWARD_BUTTON_MASK
const val CONSUMED_SCROLL_X = 32
const val CONSUMED_SCROLL_Y = 64
const val CONSUMED_X = 128
const val CONSUMED_Y = 256
const val KEY_EV_UP = 1
const val KEY_EV_DOWN = 2
const val KEY_EV_REPEATED = 4
const val KEY_EV_CHAR_TYPED = 8
const val KEY_MOD_SHIFT = 1
const val KEY_MOD_CTRL = 2
const val KEY_MOD_ALT = 4
const val KEY_MOD_SUPER = 8
val KEY_CTRL_LEFT = UniversalKeyCode(-1, "CTRL_LEFT")
val KEY_CTRL_RIGHT = UniversalKeyCode(-2, "CTRL_RIGHT")
val KEY_SHIFT_LEFT = UniversalKeyCode(-3, "SHIFT_LEFT")
val KEY_SHIFT_RIGHT = UniversalKeyCode(-4, "SHIFT_RIGHT")
val KEY_ALT_LEFT = UniversalKeyCode(-5, "ALT_LEFT")
val KEY_ALT_RIGHT = UniversalKeyCode(-6, "ALT_RIGHT")
val KEY_SUPER_LEFT = UniversalKeyCode(-7, "SUPER_LEFT")
val KEY_SUPER_RIGHT = UniversalKeyCode(-8, "SUPER_RIGHT")
val KEY_ESC = UniversalKeyCode(-9, "ESC")
val KEY_MENU = UniversalKeyCode(-10, "MENU")
val KEY_ENTER = UniversalKeyCode(-11, "ENTER")
val KEY_NP_ENTER = UniversalKeyCode(-12, "NP_ENTER")
val KEY_NP_DIV = UniversalKeyCode(-13, "NP_DIV")
val KEY_NP_MUL = UniversalKeyCode(-14, "NP_MUL")
val KEY_NP_PLUS = UniversalKeyCode(-15, "NP_PLUS")
val KEY_NP_MINUS = UniversalKeyCode(-16, "NP_MINUS")
val KEY_BACKSPACE = UniversalKeyCode(-17, "BACKSPACE")
val KEY_TAB = UniversalKeyCode(-18, "TAB")
val KEY_DEL = UniversalKeyCode(-19, "DEL")
val KEY_INSERT = UniversalKeyCode(-20, "INSERT")
val KEY_HOME = UniversalKeyCode(-21, "HOME")
val KEY_END = UniversalKeyCode(-22, "END")
val KEY_PAGE_UP = UniversalKeyCode(-23, "PAGE_UP")
val KEY_PAGE_DOWN = UniversalKeyCode(-24, "PAGE_DOWN")
val KEY_CURSOR_LEFT = UniversalKeyCode(-25, "CURSOR_LEFT")
val KEY_CURSOR_RIGHT = UniversalKeyCode(-26, "CURSOR_RIGHT")
val KEY_CURSOR_UP = UniversalKeyCode(-27, "CURSOR_UP")
val KEY_CURSOR_DOWN = UniversalKeyCode(-28, "CURSOR_DOWN")
val KEY_F1 = UniversalKeyCode(-29, "F1")
val KEY_F2 = UniversalKeyCode(-30, "F2")
val KEY_F3 = UniversalKeyCode(-31, "F3")
val KEY_F4 = UniversalKeyCode(-32, "F4")
val KEY_F5 = UniversalKeyCode(-33, "F5")
val KEY_F6 = UniversalKeyCode(-34, "F6")
val KEY_F7 = UniversalKeyCode(-35, "F7")
val KEY_F8 = UniversalKeyCode(-36, "F8")
val KEY_F9 = UniversalKeyCode(-37, "F9")
val KEY_F10 = UniversalKeyCode(-38, "F10")
val KEY_F11 = UniversalKeyCode(-39, "F11")
val KEY_F12 = UniversalKeyCode(-40, "F12")
}
}
sealed class KeyCode(val code: Int, val isLocal: Boolean, name: String?) {
val name = name ?: if (code in 32..126) "${code.toChar()}" else "$code"
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is KeyCode) return false
return code == other.code && isLocal == other.isLocal
}
override fun hashCode(): Int = code * if (isLocal) -1 else 1
}
class UniversalKeyCode(code: Int, name: String? = null) : KeyCode(code, false, name) {
constructor(codeChar: Char) : this(codeChar.uppercaseChar().code)
override fun toString() = "{universal:$name}"
}
class LocalKeyCode(code: Int, name: String? = null) : KeyCode(code, true, name) {
constructor(codeChar: Char) : this(codeChar.uppercaseChar().code)
override fun toString() = "{local:$name}"
}
|
apache-2.0
|
65f940eb22d77b528c8a2e11f83baaa7
| 39.148718 | 151 | 0.588645 | 4.754935 | false | false | false | false |
mdaniel/intellij-community
|
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/ReplaceWithOrdinaryAssignmentIntention.kt
|
1
|
2210
|
// 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.intentions
import com.intellij.codeInsight.intention.LowPriorityAction
import com.intellij.openapi.editor.Editor
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.caches.resolve.resolveToCall
import org.jetbrains.kotlin.idea.codeinsight.api.classic.intentions.SelfTargetingIntention
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
import org.jetbrains.kotlin.util.OperatorNameConventions
import org.jetbrains.kotlin.utils.addToStdlib.safeAs
class ReplaceWithOrdinaryAssignmentIntention : SelfTargetingIntention<KtBinaryExpression>(
KtBinaryExpression::class.java,
KotlinBundle.lazyMessage("replace.with.ordinary.assignment")
), LowPriorityAction {
override fun isApplicableTo(element: KtBinaryExpression, caretOffset: Int): Boolean {
val operationReference = element.operationReference
if (!operationReference.textRange.containsOffset(caretOffset)) return false
if (element.operationToken !in KtTokens.AUGMENTED_ASSIGNMENTS) return false
val left = element.left ?: return false
if (left.safeAs<KtQualifiedExpression>()?.receiverExpression is KtQualifiedExpression) return false
if (element.right == null) return false
val resultingDescriptor = operationReference.resolveToCall(BodyResolveMode.PARTIAL)?.resultingDescriptor ?: return false
return resultingDescriptor.name !in OperatorNameConventions.ASSIGNMENT_OPERATIONS
}
override fun applyTo(element: KtBinaryExpression, editor: Editor?) {
val left = element.left!!
val right = element.right!!
val factory = KtPsiFactory(element)
val assignOpText = element.operationReference.text
assert(assignOpText.endsWith("="))
val operationText = assignOpText.substring(0, assignOpText.length - 1)
element.replace(factory.createExpressionByPattern("$0 = $0 $operationText $1", left, right))
}
}
|
apache-2.0
|
06698251501b39c3a29cfe20dde0f24d
| 50.395349 | 158 | 0.777376 | 5.011338 | false | false | false | false |
hsson/card-balance-app
|
app/src/main/java/se/creotec/chscardbalance2/controller/FoodDishRecyclerViewAdapter.kt
|
1
|
2051
|
// Copyright (c) 2017 Alexander Håkansson
//
// This software is released under the MIT License.
// https://opensource.org/licenses/MIT
package se.creotec.chscardbalance2.controller
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import se.creotec.chscardbalance2.R
import se.creotec.chscardbalance2.controller.FoodDishFragment.OnListFragmentInteractionListener
import se.creotec.chscardbalance2.model.Dish
import se.creotec.chscardbalance2.util.Util
class FoodDishRecyclerViewAdapter(private val dishes: List<Dish>, private val listener: OnListFragmentInteractionListener?) : RecyclerView.Adapter<FoodDishRecyclerViewAdapter.ViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val view = LayoutInflater.from(parent.context)
.inflate(R.layout.fragment_dish, parent, false)
return ViewHolder(view)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val dish: Dish = dishes[position]
holder.dish = dish
holder.dishTitle.text = Util.capitalizeAllWords(dish.title)
holder.dishDesc.text = Util.capitalizeAllWords(dish.description)
holder.dishContainer.setOnLongClickListener(View.OnLongClickListener {
listener?.let {
it.onListFragmentInteraction(dish)
return@OnLongClickListener true
}
false
})
}
override fun getItemCount(): Int {
return dishes.size
}
inner class ViewHolder(val dishContainer: View) : RecyclerView.ViewHolder(dishContainer) {
val dishTitle: TextView = dishContainer.findViewById(R.id.dish_title) as TextView
val dishDesc: TextView = dishContainer.findViewById(R.id.dish_desc) as TextView
var dish: Dish? = null
override fun toString(): String {
return super.toString() + " '" + dish?.toString() + "'"
}
}
}
|
mit
|
77b635953e5a59fbb500618772cc20ee
| 37.679245 | 190 | 0.714634 | 4.288703 | false | false | false | false |
siosio/intellij-community
|
platform/collaboration-tools/src/com/intellij/collaboration/ui/codereview/diff/EditorComponentInlaysManager.kt
|
1
|
5086
|
// 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.collaboration.ui.codereview.diff
import com.intellij.openapi.Disposable
import com.intellij.openapi.editor.ex.EditorEx
import com.intellij.openapi.editor.ex.util.EditorUtil
import com.intellij.openapi.editor.impl.EditorEmbeddedComponentManager
import com.intellij.openapi.editor.impl.EditorImpl
import com.intellij.openapi.editor.impl.view.FontLayoutService
import com.intellij.openapi.util.Disposer
import com.intellij.ui.components.JBScrollPane
import com.intellij.util.concurrency.annotations.RequiresEdt
import com.intellij.util.ui.JBUI
import com.intellij.util.ui.components.BorderLayoutPanel
import java.awt.Dimension
import java.awt.Font
import java.awt.event.ComponentAdapter
import java.awt.event.ComponentEvent
import javax.swing.JComponent
import kotlin.math.ceil
import kotlin.math.max
import kotlin.math.min
class EditorComponentInlaysManager(val editor: EditorImpl) : Disposable {
private val managedInlays = mutableMapOf<ComponentWrapper, Disposable>()
private val editorWidthWatcher = EditorTextWidthWatcher()
init {
editor.scrollPane.viewport.addComponentListener(editorWidthWatcher)
Disposer.register(this, Disposable {
editor.scrollPane.viewport.removeComponentListener(editorWidthWatcher)
})
EditorUtil.disposeWithEditor(editor, this)
}
@RequiresEdt
fun insertAfter(lineIndex: Int, component: JComponent): Disposable? {
if (Disposer.isDisposed(this)) return null
val wrappedComponent = ComponentWrapper(component)
val offset = editor.document.getLineEndOffset(lineIndex)
return EditorEmbeddedComponentManager.getInstance()
.addComponent(editor, wrappedComponent,
EditorEmbeddedComponentManager.Properties(EditorEmbeddedComponentManager.ResizePolicy.none(),
null,
true,
false,
0,
offset))?.also {
managedInlays[wrappedComponent] = it
Disposer.register(it, Disposable { managedInlays.remove(wrappedComponent) })
}
}
private inner class ComponentWrapper(private val component: JComponent) : BorderLayoutPanel() {
init {
isOpaque = false
border = JBUI.Borders.empty()
addToCenter(component)
component.addComponentListener(object : ComponentAdapter() {
override fun componentResized(e: ComponentEvent) = dispatchEvent(ComponentEvent(component, ComponentEvent.COMPONENT_RESIZED))
})
}
override fun getPreferredSize(): Dimension {
return Dimension(editorWidthWatcher.editorTextWidth, component.preferredSize.height)
}
}
override fun dispose() {
managedInlays.values.forEach(Disposer::dispose)
}
private inner class EditorTextWidthWatcher : ComponentAdapter() {
var editorTextWidth: Int = 0
private val maximumEditorTextWidth: Int
private val verticalScrollbarFlipped: Boolean
init {
val metrics = editor.getFontMetrics(Font.PLAIN)
val spaceWidth = FontLayoutService.getInstance().charWidth2D(metrics, ' '.toInt())
// -4 to create some space
maximumEditorTextWidth = ceil(spaceWidth * (editor.settings.getRightMargin(editor.project)) - 4).toInt()
val scrollbarFlip = editor.scrollPane.getClientProperty(JBScrollPane.Flip::class.java)
verticalScrollbarFlipped = scrollbarFlip == JBScrollPane.Flip.HORIZONTAL || scrollbarFlip == JBScrollPane.Flip.BOTH
}
override fun componentResized(e: ComponentEvent) = updateWidthForAllInlays()
override fun componentHidden(e: ComponentEvent) = updateWidthForAllInlays()
override fun componentShown(e: ComponentEvent) = updateWidthForAllInlays()
private fun updateWidthForAllInlays() {
val newWidth = calcWidth()
if (editorTextWidth == newWidth) return
editorTextWidth = newWidth
managedInlays.keys.forEach {
it.dispatchEvent(ComponentEvent(it, ComponentEvent.COMPONENT_RESIZED))
it.invalidate()
}
}
private fun calcWidth(): Int {
val visibleEditorTextWidth = editor.scrollPane.viewport.width - getVerticalScrollbarWidth() - getGutterTextGap()
return min(max(visibleEditorTextWidth, 0), max(maximumEditorTextWidth, MINIMAL_TEXT_WIDTH))
}
private fun getVerticalScrollbarWidth(): Int {
val width = editor.scrollPane.verticalScrollBar.width
return if (!verticalScrollbarFlipped) width * 2 else width
}
private fun getGutterTextGap(): Int {
return if (verticalScrollbarFlipped) {
val gutter = (editor as EditorEx).gutterComponentEx
gutter.width - gutter.whitespaceSeparatorOffset
}
else 0
}
}
companion object {
private const val MINIMAL_TEXT_WIDTH = 300
}
}
|
apache-2.0
|
bbd5a8f106291c742ad887e1773bc39b
| 37.24812 | 140 | 0.708022 | 5.000983 | false | false | false | false |
siosio/intellij-community
|
platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/ui/completion/JTextCompletionContributor.kt
|
1
|
2892
|
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.openapi.externalSystem.service.ui.completion
import org.jetbrains.annotations.ApiStatus
import javax.swing.text.BadLocationException
import javax.swing.text.JTextComponent
@ApiStatus.Experimental
abstract class JTextCompletionContributor(completionType: CompletionType) : AbstractTextCompletionContributor<JTextComponent>() {
override fun getTextToComplete(owner: JTextComponent): String {
val caretPosition = getCaretPosition(owner)
val wordRange = getWordRange(owner, caretPosition)
val textToCompleteRange = wordRange.first until caretPosition
return owner.text.substring(textToCompleteRange)
}
private fun getWordRange(owner: JTextComponent, offset: Int): IntRange {
var wordStartPosition = 0
for (word in owner.text.split(" ")) {
val wordEndPosition = wordStartPosition + word.length
if (offset in wordStartPosition..wordEndPosition) {
return wordStartPosition until wordEndPosition
}
wordStartPosition = wordEndPosition + 1
}
throw BadLocationException(owner.text, offset)
}
private fun getCaretPosition(owner: JTextComponent): Int {
return maxOf(0, minOf(owner.text.length, owner.caretPosition))
}
private fun insert(owner: JTextComponent, variant: TextCompletionInfo) {
val textToComplete = getTextToComplete(owner)
val textCompletionSuffix = variant.text.removePrefix(textToComplete)
val caretPosition = getCaretPosition(owner)
owner.document.insertString(caretPosition, textCompletionSuffix, null)
}
private fun replace(owner: JTextComponent, variant: TextCompletionInfo) {
val caretPosition = getCaretPosition(owner)
val wordRange = getWordRange(owner, caretPosition)
owner.document.remove(caretPosition, wordRange.last - caretPosition + 1)
val textToCompleteRange = wordRange.first until caretPosition
val textToComplete = owner.text.substring(textToCompleteRange)
val textCompletionSuffix = variant.text.removePrefix(textToComplete)
owner.document.insertString(caretPosition, textCompletionSuffix, null)
}
init {
whenVariantChosen { owner, variant ->
when (completionType) {
CompletionType.INSERT -> insert(owner, variant)
CompletionType.REPLACE -> replace(owner, variant)
}
}
}
enum class CompletionType { INSERT, REPLACE }
companion object {
fun create(
completionType: CompletionType = CompletionType.INSERT,
completionVariants: (String) -> List<TextCompletionInfo>
) = object : JTextCompletionContributor(completionType) {
override fun getCompletionVariants(owner: JTextComponent, textToComplete: String): List<TextCompletionInfo> {
return completionVariants(textToComplete)
}
}
}
}
|
apache-2.0
|
a69e1253cef9e0b257c7860bf4da8c82
| 39.746479 | 140 | 0.757953 | 4.803987 | false | false | false | false |
vovagrechka/fucking-everything
|
alraune/alraune/src/main/java/alraune/SpitTaskPage.kt
|
1
|
2685
|
package alraune
import pieces100.*
import vgrechka.*
// TODO:vgrechka Security
class SpitTaskPage : SpitPage {
companion object {
val path = "/task"
}
override fun spit() {Spit()}
inner class Spit {
val getParams = GetParams()
val task = dbSelectTaskOrBailOut(getParamOrBailOut(getParams.longId))
val css = AlCSS.tasks
init {
imf()
spitUsualPage_withNewContext1 {
composeMinimalMainContainer {
val title = t("TOTE", "Задача ${AlText.numString(task.id)}")
rctx0.htmlHeadTitle = title
!OoEntityTitleShit(
pagePath = SpitTaskPage.path,
title = title,
shitIntoHamburger = {},
impersonationPillsUsage = null)
.subTitle(task.data.composeRichTitle(task))
// oo(!object : OoUsualPaginatedShit<Task>(
// req = rctx.req,
// itemClass = Task::class, table = alraune.entity.Task.Meta.table,
// spitPage = SpitTaskPage::class,
// notDeleted = false,
// pizda = Pizda(
// composeBeforeItems = {rawHtml("<table>")},
// composeAfterItems = {rawHtml("</table>")})) {
//
// init {
// orderingFrom(getParams)
// }
//
// override fun composeItem(item: Task) = composeFreakingItem(item)
//
// override fun shitIntoWhere(q: AlQueryBuilder) {
// q.text("and ${alraune.entity.Task.Meta.status} =", Task.Status.Open)
// }
// })
}
}
}
// fun composeFreakingItem(item: Task) =
// tr().className(AlCSS.tasks.pizda1).with {
// fun fart(x: String) = oo(td().add(div().className(AlCSS.tasks.pizda2).add(x)))
// fart(AlText.taskId(item.id))
// fart(TimePile.kievTimeString(item.createdAt))
//
// val data = item.data
// val href = when (data) {
// is Task.ApproveOrder_CustomerDraft_V1 -> makeUrlPart(SpitOrderPage::class) {
// it.longId.set(data.order.id)
// }
// else -> wtf()
// }
// oo(td().style("width: 100%;")
// .add(composeTagaProgressy(href).add(item.title)))
// }
}
}
|
apache-2.0
|
d65d7bc4f6e461b7ba1338ae2fa199c8
| 35.712329 | 98 | 0.454647 | 4.272727 | false | false | false | false |
youdonghai/intellij-community
|
platform/projectModel-impl/src/com/intellij/project/project.kt
|
1
|
4293
|
/*
* Copyright 2000-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.project
import com.intellij.ide.highlighter.ProjectFileType
import com.intellij.openapi.application.runWriteAction
import com.intellij.openapi.components.StorageScheme
import com.intellij.openapi.components.impl.stores.IComponentStore
import com.intellij.openapi.components.impl.stores.IProjectStore
import com.intellij.openapi.components.stateStore
import com.intellij.openapi.module.ModifiableModuleModel
import com.intellij.openapi.module.Module
import com.intellij.openapi.module.ModuleManager
import com.intellij.openapi.project.Project
import com.intellij.openapi.roots.ModuleRootManager
import com.intellij.openapi.util.SystemInfo
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.util.io.basicAttributesIfExists
import com.intellij.util.io.exists
import java.nio.file.InvalidPathException
import java.nio.file.Paths
val Project.isDirectoryBased: Boolean
get() {
val store = stateStore
return store is IProjectStore && StorageScheme.DIRECTORY_BASED == store.storageScheme
}
val Project.stateStore: IProjectStore
get() {
return picoContainer.getComponentInstance(IComponentStore::class.java) as IProjectStore
}
fun getProjectStoreDirectory(file: VirtualFile): VirtualFile? {
return if (file.isDirectory) file.findChild(Project.DIRECTORY_STORE_FOLDER) else null
}
fun isValidProjectPath(path: String): Boolean {
val file = try {
Paths.get(path)
}
catch (e: InvalidPathException) {
return false
}
val attributes = file.basicAttributesIfExists() ?: return false
return if (attributes.isDirectory) file.resolve(Project.DIRECTORY_STORE_FOLDER).exists() else path.endsWith(ProjectFileType.DOT_DEFAULT_EXTENSION)
}
fun isProjectDirectoryExistsUsingIo(parent: VirtualFile): Boolean {
try {
return Paths.get(FileUtil.toSystemDependentName(parent.path), Project.DIRECTORY_STORE_FOLDER).exists()
}
catch (e: InvalidPathException) {
return false
}
}
fun isEqualToProjectFileStorePath(project: Project, filePath: String, storePath: String): Boolean {
if (!project.isDirectoryBased) {
return false
}
val store = project.stateStore as IProjectStore
return filePath.equals(store.stateStorageManager.expandMacros(storePath), !SystemInfo.isFileSystemCaseSensitive)
}
inline fun <T> Project.modifyModules(crossinline task: ModifiableModuleModel.() -> T): T {
val model = ModuleManager.getInstance(this).modifiableModel
val result = model.task()
runWriteAction {
model.commit()
}
return result
}
val Module.rootManager: ModuleRootManager
get() = ModuleRootManager.getInstance(this)
/**
* Tries to guess the "main project directory" of the project.
*
* There is no strict definition of what is a project directory, since a project can contain multiple modules located in different places,
* and the `.idea` directory can be located elsewhere (making the popular [Project.getBaseDir] method not applicable to get the "project
* directory"). This method should be preferred, although it can't provide perfect accuracy either.
*
* @throws IllegalStateException if called on the default project, since there is no sense in "project dir" in that case.
*/
fun Project.guessProjectDir() : VirtualFile {
if (isDefault) {
throw IllegalStateException("Not applicable for default project")
}
val modules = ModuleManager.getInstance(this).modules
val module = if (modules.size == 1) modules.first() else modules.find { it.name == this.name }
if (module != null) {
val roots = ModuleRootManager.getInstance(module).contentRoots
roots.firstOrNull()?.let {
return it
}
}
return this.baseDir!!
}
|
apache-2.0
|
a6bc93be4ef2fdbcb0da75e1afc38593
| 35.700855 | 148 | 0.772653 | 4.376147 | false | false | false | false |
androidx/androidx
|
work/work-lint/src/main/java/androidx/work/lint/IdleBatteryChargingConstraintsDetector.kt
|
3
|
5100
|
/*
* Copyright 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
@file:Suppress("UnstableApiUsage")
package androidx.work.lint
import com.android.tools.lint.detector.api.Category
import com.android.tools.lint.detector.api.ConstantEvaluator
import com.android.tools.lint.detector.api.Detector
import com.android.tools.lint.detector.api.Implementation
import com.android.tools.lint.detector.api.Issue
import com.android.tools.lint.detector.api.JavaContext
import com.android.tools.lint.detector.api.Scope
import com.android.tools.lint.detector.api.Severity
import com.android.tools.lint.detector.api.SourceCodeScanner
import com.intellij.psi.PsiMethod
import org.jetbrains.uast.UBlockExpression
import org.jetbrains.uast.UCallExpression
import org.jetbrains.uast.UQualifiedReferenceExpression
import org.jetbrains.uast.USimpleNameReferenceExpression
import org.jetbrains.uast.getParentOfType
import org.jetbrains.uast.toUElement
import org.jetbrains.uast.visitor.AbstractUastVisitor
import java.util.EnumSet
/**
* Warns when a developer uses both idle + battery charging constraints in WorkManager.
*/
class IdleBatteryChargingConstraintsDetector : Detector(), SourceCodeScanner {
companion object {
private const val DESCRIPTION = "Constraints may not be met for some devices"
val ISSUE = Issue.create(
id = "IdleBatteryChargingConstraints",
briefDescription = DESCRIPTION,
explanation = """
Some devices are never considered charging and idle at the same time.
Consider removing one of these constraints.
""",
androidSpecific = true,
category = Category.CORRECTNESS,
severity = Severity.WARNING,
implementation = Implementation(
IdleBatteryChargingConstraintsDetector::class.java,
EnumSet.of(Scope.JAVA_FILE)
)
)
}
override fun getApplicableMethodNames(): List<String> = listOf("setRequiresDeviceIdle")
override fun visitMethodCall(context: JavaContext, node: UCallExpression, method: PsiMethod) {
var reported = false
if (context.evaluator.isMemberInClass(
method,
"androidx.work.Constraints.Builder"
) && node.isArgumentTrue(context)
) {
val name = node.identifierName()
val sourcePsi = node.receiver?.sourcePsi
if (sourcePsi != null) {
// We need to walk both backwards to the nearest block expression and look for
// setRequiresCharging(true) on Constraints
val blockExpression = sourcePsi.toUElement()?.getParentOfType<UBlockExpression>()
val visitor = object : AbstractUastVisitor() {
override fun visitCallExpression(node: UCallExpression): Boolean {
val variableName = node.identifierName()
if (node.methodName == "setRequiresCharging" &&
node.isArgumentTrue(context) &&
// Same variable name
name == variableName &&
node.receiverType?.canonicalText == "androidx.work.Constraints.Builder"
) {
if (!reported) {
reported = true
context.report(ISSUE, context.getLocation(node), DESCRIPTION)
}
}
return true
}
}
// Note: We need to navigate the sourcePsi for call expressions.
// blockExpression.accept(...) will NOT do what you think it does.
blockExpression?.sourcePsi?.toUElement()?.accept(visitor)
}
}
}
fun UCallExpression.isArgumentTrue(context: JavaContext): Boolean {
if (valueArgumentCount > 0) {
val value = ConstantEvaluator.evaluate(context, valueArguments.first())
return value == true
}
return false
}
fun UCallExpression.identifierName(): String? {
var current = receiver
while (current != null && current !is USimpleNameReferenceExpression) {
current = (current as? UQualifiedReferenceExpression)?.receiver
}
if (current != null && current is USimpleNameReferenceExpression) {
return current.identifier
}
return null
}
}
|
apache-2.0
|
d287b230090dc481d40287c746315549
| 40.803279 | 99 | 0.636667 | 5.323591 | false | false | false | false |
androidx/androidx
|
viewpager2/integration-tests/testapp/src/androidTest/java/androidx/viewpager2/integration/testapp/test/TabLayoutTest.kt
|
4
|
2529
|
/*
* Copyright 2019 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.viewpager2.integration.testapp.test
import androidx.test.espresso.Espresso.onIdle
import androidx.test.espresso.action.ViewActions.click
import androidx.test.espresso.action.ViewActions.scrollTo
import androidx.test.espresso.assertion.ViewAssertions.matches
import androidx.test.espresso.matcher.ViewMatchers.isSelected
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.filters.LargeTest
import androidx.viewpager2.integration.testapp.CardViewTabLayoutActivity
import androidx.viewpager2.integration.testapp.R
import androidx.viewpager2.integration.testapp.cards.Card
import androidx.viewpager2.integration.testapp.cards.Card.Companion.find
import androidx.viewpager2.integration.testapp.test.util.onTab
import org.junit.Test
import org.junit.runner.RunWith
@LargeTest
@RunWith(AndroidJUnit4::class)
class TabLayoutTest : BaseTest<CardViewTabLayoutActivity>(CardViewTabLayoutActivity::class.java) {
private val nineOfHeartsTab = Card.DECK.find("9", "♥").toString()
private val tenOfHeartsTab = Card.DECK.find("10", "♥").toString()
private val nineOfHeartsPage = "9\n♥"
private val tenOfHeartsPage = "10\n♥"
override val layoutId get() = R.id.view_pager
@Test
fun testTabLayoutIntegration() {
// test if ViewPager2 follows TabLayout when clicking a tab
selectTab(tenOfHeartsTab)
verifySelectedTab(tenOfHeartsTab)
verifyCurrentPage(tenOfHeartsPage)
// test if TabLayout follows ViewPager2 when swiping to a page
swipeToPreviousPage()
verifySelectedTab(nineOfHeartsTab)
verifyCurrentPage(nineOfHeartsPage)
}
private fun selectTab(text: String) {
onTab(text).perform(scrollTo(), click())
idleWatcher.waitForIdle()
onIdle()
}
private fun verifySelectedTab(text: String) {
onTab(text).check(matches(isSelected()))
}
}
|
apache-2.0
|
e12d2d9a0d2be03cbbef3bcdc288a6f9
| 37.19697 | 98 | 0.758429 | 4.0859 | false | true | false | false |
GunoH/intellij-community
|
plugins/gradle/java/testSources/dsl/GradleHighlightingPerformanceTest.kt
|
2
|
4449
|
// 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.gradle.dsl
import com.intellij.openapi.editor.RangeMarker
import com.intellij.openapi.editor.ex.DocumentEx
import com.intellij.openapi.editor.ex.RangeMarkerEx
import com.intellij.openapi.externalSystem.util.runInEdtAndWait
import com.intellij.openapi.externalSystem.util.text
import com.intellij.psi.PsiDocumentManager
import com.intellij.testFramework.PlatformTestUtil
import com.intellij.util.asSafely
import org.gradle.util.GradleVersion
import org.jetbrains.plugins.gradle.testFramework.GradleCodeInsightTestCase
import org.jetbrains.plugins.gradle.testFramework.GradleTestFixtureBuilder
import org.jetbrains.plugins.gradle.testFramework.annotations.BaseGradleVersionSource
import org.jetbrains.plugins.groovy.lang.completion.GroovyCompletionUtil.disableSlowCompletionElements
import org.junit.jupiter.api.Assertions
import org.junit.jupiter.params.ParameterizedTest
class GradleHighlightingPerformanceTest : GradleCodeInsightTestCase() {
@ParameterizedTest
@BaseGradleVersionSource
fun testPerformance(gradleVersion: GradleVersion) {
test(gradleVersion, FIXTURE_BUILDER) {
val file = getFile("build.gradle")
val pos = file.text.indexOf("a.json")
runInEdtAndWait {
fixture.openFileInEditor(file)
fixture.editor.caretModel.moveToOffset(pos + 1)
fixture.checkHighlighting()
PlatformTestUtil.startPerformanceTest("GradleHighlightingPerformanceTest.testPerformance", 6000) {
fixture.psiManager.dropPsiCaches()
repeat(4) {
fixture.type('a')
PsiDocumentManager.getInstance(fixture.project).commitAllDocuments()
fixture.doHighlighting()
fixture.completeBasic()
}
}.assertTiming()
}
}
}
@ParameterizedTest
@BaseGradleVersionSource
fun testCompletionPerformance(gradleVersion: GradleVersion) {
test(gradleVersion, COMPLETION_FIXTURE) {
val file = getFile("build.gradle")
val pos = file.text.indexOf("dependencies {") + "dependencies {".length
runInEdtAndWait {
fixture.openFileInEditor(file)
fixture.editor.caretModel.moveToOffset(pos)
fixture.checkHighlighting()
fixture.type('i')
PsiDocumentManager.getInstance(project).commitAllDocuments()
val document = PsiDocumentManager.getInstance(project).getDocument(fixture.file)
disableSlowCompletionElements(fixture.testRootDisposable)
val repeatSize = 10
PlatformTestUtil.startPerformanceTest("GradleHighlightingPerformanceTest.testCompletion", 450 * repeatSize) {
fixture.psiManager.dropResolveCaches()
repeat(repeatSize) {
val lookupElements = fixture.completeBasic()
Assertions.assertTrue(lookupElements.any { it.lookupString == "implementation" })
}
}.setup {
val rangeMarkers = ArrayList<RangeMarker>()
document.asSafely<DocumentEx>()?.processRangeMarkers { rangeMarkers.add(it) }
rangeMarkers.forEach { marker -> document.asSafely<DocumentEx>()?.removeRangeMarker(marker as RangeMarkerEx) }
}.usesAllCPUCores().assertTiming()
}
}
}
companion object {
private val FIXTURE_BUILDER = GradleTestFixtureBuilder.buildFile("GradleHighlightingPerformanceTest") {
addBuildScriptRepository("mavenCentral()")
addBuildScriptClasspath("io.github.http-builder-ng:http-builder-ng-apache:1.0.3")
addImport("groovyx.net.http.HttpBuilder")
withTask("bitbucketJenkinsTest") {
call("doLast") {
property("bitbucket", call("HttpBuilder.configure") {
assign("request.uri", "https://127.0.0.1")
call("request.auth.basic", "", "")
})
call("bitbucket.post") {
assign("request.uri.path", "/rest/api/")
assign("request.contentType", "a.json")
}
}
}
}
private val COMPLETION_FIXTURE = GradleTestFixtureBuilder.buildFile("GradleCompletionPerformanceTest") {
withPrefix {
call("plugins") {
call("id", string("java"))
call("id", string("groovy"))
call("id", string("scala"))
}
}
addRepository("mavenCentral()")
withPostfix {
call("dependencies") {
}
}
}
}
}
|
apache-2.0
|
9e1b05d5f91bf70492cb46860e54c13b
| 39.081081 | 120 | 0.698809 | 4.965402 | false | true | false | false |
GunoH/intellij-community
|
platform/build-scripts/src/org/jetbrains/intellij/build/impl/BundledRuntimeImpl.kt
|
2
|
7814
|
// 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.intellij.build.impl
import com.intellij.diagnostic.telemetry.use
import com.intellij.openapi.util.SystemInfoRt
import com.intellij.openapi.util.io.NioFiles
import kotlinx.collections.immutable.persistentListOf
import org.apache.commons.compress.archivers.tar.TarArchiveInputStream
import org.jetbrains.intellij.build.*
import org.jetbrains.intellij.build.TraceManager.spanBuilder
import org.jetbrains.intellij.build.dependencies.BuildDependenciesDownloader
import org.jetbrains.intellij.build.dependencies.BuildDependenciesExtractOptions
import org.jetbrains.intellij.build.dependencies.DependenciesProperties
import java.nio.file.*
import java.nio.file.attribute.BasicFileAttributes
import java.nio.file.attribute.DosFileAttributeView
import java.nio.file.attribute.PosixFilePermission.*
import java.util.*
import java.util.zip.GZIPInputStream
class BundledRuntimeImpl(
private val options: BuildOptions,
private val paths: BuildPaths,
private val dependenciesProperties: DependenciesProperties,
private val error: (String) -> Unit,
private val info: (String) -> Unit) : BundledRuntime {
companion object {
fun getProductPrefix(context: BuildContext): String {
return context.options.bundledRuntimePrefix ?: context.productProperties.runtimeDistribution.artifactPrefix
}
}
private val build by lazy {
options.bundledRuntimeBuild ?: dependenciesProperties.property("runtimeBuild")
}
override suspend fun getHomeForCurrentOsAndArch(): Path {
var prefix = "jbr_jcef-"
val os = OsFamily.currentOs
val arch = JvmArchitecture.currentJvmArch
if (System.getProperty("intellij.build.jbr.setupSdk", "false").toBoolean()) {
// required as a runtime for debugger tests
prefix = "jbrsdk-"
}
else {
options.bundledRuntimePrefix?.let {
prefix = it
}
}
val path = extract(prefix, os, arch)
val home = if (os == OsFamily.MACOS) path.resolve("jbr/Contents/Home") else path.resolve("jbr")
val releaseFile = home.resolve("release")
check(Files.exists(releaseFile)) {
"Unable to find release file $releaseFile after extracting JBR at $path"
}
return home
}
// contract: returns a directory, where only one subdirectory is available: 'jbr', which contains specified JBR
override suspend fun extract(prefix: String, os: OsFamily, arch: JvmArchitecture): Path {
val targetDir = paths.communityHomeDir.resolve("build/download/${prefix}${build}-${os.jbrArchiveSuffix}-$arch")
val jbrDir = targetDir.resolve("jbr")
val archive = findArchive(prefix, os, arch)
BuildDependenciesDownloader.extractFile(
archive, jbrDir,
paths.communityHomeDirRoot,
BuildDependenciesExtractOptions.STRIP_ROOT,
)
fixPermissions(jbrDir, os == OsFamily.WINDOWS)
val releaseFile = if (os == OsFamily.MACOS) jbrDir.resolve("Contents/Home/release") else jbrDir.resolve("release")
check(Files.exists(releaseFile)) {
"Unable to find release file $releaseFile after extracting JBR at $archive"
}
return targetDir
}
override suspend fun extractTo(prefix: String, os: OsFamily, destinationDir: Path, arch: JvmArchitecture) {
doExtract(findArchive(prefix, os, arch), destinationDir, os)
}
private suspend fun findArchive(prefix: String, os: OsFamily, arch: JvmArchitecture): Path {
val archiveName = archiveName(prefix = prefix, arch = arch, os = os)
val url = "https://cache-redirector.jetbrains.com/intellij-jbr/$archiveName"
return downloadFileToCacheLocation(url = url, communityRoot = paths.communityHomeDirRoot)
}
/**
* Update this method together with:
* [com.intellij.remoteDev.downloader.CodeWithMeClientDownloader.downloadClientAndJdk]
* [UploadingAndSigning.getMissingJbrs]
* [org.jetbrains.intellij.build.dependencies.JdkDownloader.getUrl]
*/
override fun archiveName(prefix: String, arch: JvmArchitecture, os: OsFamily, forceVersionWithUnderscores: Boolean): String {
val split = build.split('b')
if (split.size != 2) {
throw IllegalArgumentException("$build doesn't match '<update>b<build_number>' format (e.g.: 17.0.2b387.1)")
}
val version = if (forceVersionWithUnderscores) split[0].replace(".", "_") else split[0]
val buildNumber = "b${split[1]}"
val archSuffix = getArchSuffix(arch)
return "${prefix}${version}-${os.jbrArchiveSuffix}-${archSuffix}-${runtimeBuildPrefix()}${buildNumber}.tar.gz"
}
private fun runtimeBuildPrefix(): String {
if (!options.runtimeDebug) {
return ""
}
if (!options.isTestBuild && !options.isInDevelopmentMode) {
error("Either test or development mode is required to use fastdebug runtime build")
}
info("Fastdebug runtime build is requested")
return "fastdebug-"
}
/**
* When changing this list of patterns, also change patch_bin_file in launcher.sh (for remote dev)
*/
override fun executableFilesPatterns(os: OsFamily): List<String> {
val pathPrefix = if (os == OsFamily.MACOS) "jbr/Contents/Home/" else "jbr/"
@Suppress("SpellCheckingInspection")
var executableFilesPatterns = persistentListOf(
pathPrefix + "bin/*",
pathPrefix + "lib/jexec",
pathPrefix + "lib/jspawnhelper",
pathPrefix + "lib/chrome-sandbox"
)
if (os == OsFamily.LINUX) {
executableFilesPatterns = executableFilesPatterns.add("jbr/lib/jcef_helper")
}
return executableFilesPatterns
}
}
private fun getArchSuffix(arch: JvmArchitecture): String {
return when (arch) {
JvmArchitecture.x64 -> "x64"
JvmArchitecture.aarch64 -> "aarch64"
}
}
private fun doExtract(archive: Path, destinationDir: Path, os: OsFamily) {
spanBuilder("extract JBR")
.setAttribute("archive", archive.toString())
.setAttribute("os", os.osName)
.setAttribute("destination", destinationDir.toString())
.use {
NioFiles.deleteRecursively(destinationDir)
unTar(archive, destinationDir)
fixPermissions(destinationDir, os == OsFamily.WINDOWS)
}
}
private fun unTar(archive: Path, destination: Path) {
// CompressorStreamFactory requires stream with mark support
val rootDir = createTarGzInputStream(archive).use {
it.nextTarEntry?.name
}
if (rootDir == null) {
throw IllegalStateException("Unable to detect root dir of $archive")
}
ArchiveUtils.unTar(archive, destination, if (rootDir.startsWith("jbr")) rootDir else null)
}
private fun createTarGzInputStream(archive: Path): TarArchiveInputStream {
return TarArchiveInputStream(GZIPInputStream(Files.newInputStream(archive), 64 * 1024))
}
private fun fixPermissions(destinationDir: Path, forWin: Boolean) {
val exeOrDir = EnumSet.of(OWNER_READ, OWNER_WRITE, OWNER_EXECUTE, GROUP_READ, GROUP_EXECUTE, OTHERS_READ, OTHERS_EXECUTE)
val regular = EnumSet.of(OWNER_READ, OWNER_WRITE, GROUP_READ, OTHERS_READ)
Files.walkFileTree(destinationDir, object : SimpleFileVisitor<Path>() {
@Override
override fun preVisitDirectory(dir: Path, attrs: BasicFileAttributes): FileVisitResult {
if (dir != destinationDir && SystemInfoRt.isUnix) {
Files.setPosixFilePermissions(dir, exeOrDir)
}
return FileVisitResult.CONTINUE
}
override fun visitFile(file: Path, attrs: BasicFileAttributes): FileVisitResult {
if (SystemInfoRt.isUnix) {
val noExec = forWin || OWNER_EXECUTE !in Files.getPosixFilePermissions(file)
Files.setPosixFilePermissions(file, if (noExec) regular else exeOrDir)
}
else {
Files.getFileAttributeView(file, DosFileAttributeView::class.java).setReadOnly(false)
}
return FileVisitResult.CONTINUE
}
})
}
|
apache-2.0
|
23c366ddd5b33fece9f9f12431e88738
| 38.271357 | 127 | 0.729076 | 4.34594 | false | false | false | false |
GunoH/intellij-community
|
plugins/kotlin/jvm/src/org/jetbrains/kotlin/idea/scratch/compile/KtScratchSourceFileProcessor.kt
|
4
|
5002
|
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.scratch.compile
import org.jetbrains.kotlin.diagnostics.rendering.Renderers
import org.jetbrains.kotlin.diagnostics.rendering.RenderingContext
import org.jetbrains.kotlin.idea.caches.resolve.resolveToDescriptorIfAny
import org.jetbrains.kotlin.idea.scratch.ScratchExpression
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.resolve.calls.util.isSingleUnderscore
class KtScratchSourceFileProcessor {
companion object {
const val GENERATED_OUTPUT_PREFIX = "##scratch##generated##"
const val LINES_INFO_MARKER = "end##"
const val END_OUTPUT_MARKER = "end##!@#%^&*"
const val OBJECT_NAME = "ScratchFileRunnerGenerated"
const val INSTANCE_NAME = "instanceScratchFileRunner"
const val PACKAGE_NAME = "org.jetbrains.kotlin.idea.scratch.generated"
const val GET_RES_FUN_NAME_PREFIX = "generated_get_instance_res"
}
fun process(expressions: List<ScratchExpression>): Result {
val sourceProcessor = KtSourceProcessor()
expressions.forEach {
sourceProcessor.process(it)
}
val codeResult =
"""
package $PACKAGE_NAME
${sourceProcessor.imports.joinToString("\n") { it.text }}
object $OBJECT_NAME {
class $OBJECT_NAME {
${sourceProcessor.classBuilder}
}
@JvmStatic fun main(args: Array<String>) {
val $INSTANCE_NAME = $OBJECT_NAME()
${sourceProcessor.objectBuilder}
println("$END_OUTPUT_MARKER")
}
}
"""
return Result.OK("$PACKAGE_NAME.$OBJECT_NAME", codeResult)
}
class KtSourceProcessor {
val classBuilder = StringBuilder()
val objectBuilder = StringBuilder()
val imports = arrayListOf<KtImportDirective>()
private var resCount = 0
fun process(expression: ScratchExpression) {
when (val psiElement = expression.element) {
is KtDestructuringDeclaration -> processDestructuringDeclaration(expression, psiElement)
is KtVariableDeclaration -> processDeclaration(expression, psiElement)
is KtFunction -> processDeclaration(expression, psiElement)
is KtClassOrObject -> processDeclaration(expression, psiElement)
is KtImportDirective -> imports.add(psiElement)
is KtExpression -> processExpression(expression, psiElement)
}
}
private fun processDeclaration(e: ScratchExpression, c: KtDeclaration) {
classBuilder.append(c.text).newLine()
val descriptor = c.resolveToDescriptorIfAny() ?: return
val context = RenderingContext.of(descriptor)
objectBuilder.println(Renderers.COMPACT.render(descriptor, context))
objectBuilder.appendLineInfo(e)
}
private fun processDestructuringDeclaration(e: ScratchExpression, c: KtDestructuringDeclaration) {
val entries = c.entries.mapNotNull { if (it.isSingleUnderscore) null else it.resolveToDescriptorIfAny() }
entries.forEach {
val context = RenderingContext.of(it)
val rendered = Renderers.COMPACT.render(it, context)
classBuilder.append(rendered).newLine()
objectBuilder.println(rendered)
}
objectBuilder.appendLineInfo(e)
classBuilder.append("init {").newLine()
classBuilder.append(c.text).newLine()
entries.forEach {
classBuilder.append("this.${it.name} = ${it.name}").newLine()
}
classBuilder.append("}").newLine()
}
private fun processExpression(e: ScratchExpression, expr: KtExpression) {
val resName = "$GET_RES_FUN_NAME_PREFIX$resCount"
classBuilder.append("fun $resName() = run { ${expr.text} }").newLine()
objectBuilder.printlnObj("$INSTANCE_NAME.$resName()")
objectBuilder.appendLineInfo(e)
resCount += 1
}
private fun StringBuilder.appendLineInfo(e: ScratchExpression) {
println("$LINES_INFO_MARKER${e.lineStart}|${e.lineEnd}")
}
private fun StringBuilder.println(str: String) = append("println(\"$GENERATED_OUTPUT_PREFIX$str\")").newLine()
private fun StringBuilder.printlnObj(str: String) = append("println(\"$GENERATED_OUTPUT_PREFIX\${$str}\")").newLine()
private fun StringBuilder.newLine() = append("\n")
}
sealed class Result {
class Error(val message: String) : Result()
class OK(val mainClassName: String, val code: String) : Result()
}
}
|
apache-2.0
|
785b569d527e7d568014e8932310de6d
| 40.691667 | 158 | 0.626549 | 5.21585 | false | false | false | false |
stinsonga/GeoQuake
|
geoquake/src/main/java/com/geo/geoquake/models/Earthquake.kt
|
1
|
1167
|
package com.geo.geoquake.models
/**
* Created by George Stinson on 2016-10-24.
*/
class Earthquake {
var place = ""
var url: String = ""
var mag: Double = 0.toDouble()
var latitude: Double = 0.toDouble()
var longitude: Double = 0.toDouble()
var time: Long = 0
var timeString = ""
var source: Int = 0
constructor() {}
constructor(latitude: Double, longitude: Double, mag: Double, place: String, time: Long, url: String) {
this.latitude = latitude
this.longitude = longitude
this.mag = mag
this.place = place
this.time = time
this.url = url
}
constructor(feature: Feature) {
this.latitude = feature.getLatitude()
this.longitude = feature.getLongitude()
this.mag = feature.getProperties().getMag()
this.place = feature.getProperties().getPlace()
this.time = feature.getProperties().getTime()
feature.getProperties().getUrl()?.let {
this.url = feature.getProperties().getUrl()
}
this.source = USA
}
companion object {
const val USA = 0
const val CANADA = 1
}
}
|
bsd-3-clause
|
08f76dd0a2f4ed3bc7ff1bc882392cf2
| 24.369565 | 107 | 0.592117 | 4.123675 | false | false | false | false |
LouisCAD/Splitties
|
modules/views-selectable-constraintlayout/src/androidMain/kotlin/splitties/views/selectable/constraintlayout/SelectableConstraintLayout.kt
|
1
|
2126
|
/*
* Copyright 2019 Louis Cognault Ayeva Derman. Use of this source code is governed by the Apache 2.0 license.
*/
package splitties.views.selectable.constraintlayout
import android.content.Context
import android.graphics.Canvas
import android.graphics.drawable.Drawable
import android.util.AttributeSet
import androidx.annotation.CallSuper
import androidx.annotation.RequiresApi
import androidx.constraintlayout.widget.ConstraintLayout
import splitties.resources.styledDrawable
/**
* [ConstraintLayout] with ripple effect / select foreground when touched.
*/
open class SelectableConstraintLayout @JvmOverloads constructor(
context: Context, attrs: AttributeSet?, defStyleAttr: Int = 0
) : ConstraintLayout(context, attrs, defStyleAttr) {
constructor(context: Context) : this(context, null)
var foregroundSelector: Drawable? = null
set(value) {
field?.callback = null
field = value
value?.callback = this
setWillNotDraw(value === null)
}
init {
foregroundSelector = styledDrawable(android.R.attr.selectableItemBackground)
}
@CallSuper
override fun drawableStateChanged() {
super.drawableStateChanged()
foregroundSelector?.state = drawableState
}
@CallSuper
override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
super.onSizeChanged(w, h, oldw, oldh)
foregroundSelector?.setBounds(0, 0, w, h)
}
@CallSuper
override fun onDraw(canvas: Canvas) {
super.onDraw(canvas)
foregroundSelector?.draw(canvas)
}
@CallSuper
override fun jumpDrawablesToCurrentState() {
super.jumpDrawablesToCurrentState()
foregroundSelector?.jumpToCurrentState()
}
@CallSuper
override fun verifyDrawable(who: Drawable): Boolean {
return who === foregroundSelector || super.verifyDrawable(who)
}
@RequiresApi(21)
@CallSuper
override fun dispatchDrawableHotspotChanged(x: Float, y: Float) {
super.dispatchDrawableHotspotChanged(x, y)
foregroundSelector?.setHotspot(x, y)
}
}
|
apache-2.0
|
3e4808d7d630f4b80b7d14aae51ee529
| 28.943662 | 109 | 0.701317 | 4.734967 | false | false | false | false |
smmribeiro/intellij-community
|
platform/projectModel-impl/src/com/intellij/workspaceModel/ide/impl/legacyBridge/module/roots/ModuleLibraryTableBridgeImpl.kt
|
2
|
3433
|
// 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.module.Module
import com.intellij.openapi.roots.ProjectModelExternalSource
import com.intellij.openapi.roots.impl.ModuleLibraryTableBase
import com.intellij.openapi.roots.impl.libraries.LibraryEx
import com.intellij.openapi.roots.libraries.Library
import com.intellij.openapi.roots.libraries.PersistentLibraryKind
import com.intellij.openapi.util.Disposer
import com.intellij.workspaceModel.ide.WorkspaceModel
import com.intellij.workspaceModel.ide.impl.legacyBridge.library.LibraryBridgeImpl
import com.intellij.workspaceModel.ide.impl.legacyBridge.library.ProjectLibraryTableBridgeImpl.Companion.libraryMap
import com.intellij.workspaceModel.ide.impl.legacyBridge.library.ProjectLibraryTableBridgeImpl.Companion.mutableLibraryMap
import com.intellij.workspaceModel.ide.legacyBridge.ModuleBridge
import com.intellij.workspaceModel.storage.WorkspaceEntityStorageDiffBuilder
import com.intellij.workspaceModel.storage.bridgeEntities.LibraryEntity
import org.jetbrains.annotations.ApiStatus
/**
* This class mwthods [registerModuleLibraryInstances], [addLibrary] should be marked as internal after [ModuleManagerComponentBridge]
* migration to the `intellij.platform.projectModel.impl` module
*/
@ApiStatus.Internal
class ModuleLibraryTableBridgeImpl(private val moduleBridge: ModuleBridge) : ModuleLibraryTableBase(), ModuleLibraryTableBridge {
init {
Disposer.register(moduleBridge, this)
}
fun registerModuleLibraryInstances(builder: WorkspaceEntityStorageDiffBuilder?) {
libraryEntities().forEach { addLibrary(it, builder) }
}
internal fun libraryEntities(): Sequence<LibraryEntity> {
return moduleBridge.entityStorage.current.referrers(moduleBridge.moduleEntityId, LibraryEntity::class.java)
}
override fun getLibraryIterator(): Iterator<Library> {
val storage = moduleBridge.entityStorage.current
return libraryEntities().mapNotNull { storage.libraryMap.getDataByEntity(it) }.iterator()
}
override fun createLibrary(name: String?,
type: PersistentLibraryKind<*>?,
externalSource: ProjectModelExternalSource?): Library {
error("Must not be called for read-only table")
}
override fun removeLibrary(library: Library) {
error("Must not be called for read-only table")
}
override fun isChanged(): Boolean {
return false
}
fun addLibrary(entity: LibraryEntity, storageBuilder: WorkspaceEntityStorageDiffBuilder?): LibraryBridgeImpl {
val library = LibraryBridgeImpl(
libraryTable = this,
project = module.project,
initialId = entity.persistentId(),
initialEntityStorage = moduleBridge.entityStorage,
targetBuilder = null
)
if (storageBuilder != null) {
storageBuilder.mutableLibraryMap.addMapping(entity, library)
}
else {
WorkspaceModel.getInstance(moduleBridge.project).updateProjectModelSilent {
it.mutableLibraryMap.addMapping(entity, library)
}
}
return library
}
override fun dispose() {
for (library in libraryIterator) {
if (!(library as LibraryEx).isDisposed) Disposer.dispose(library)
}
}
override val module: Module
get() = moduleBridge
}
|
apache-2.0
|
5596a439bd16ac0574478c62bdb0b0df
| 39.869048 | 140 | 0.775415 | 5.011679 | false | false | false | false |
smmribeiro/intellij-community
|
plugins/markdown/core/src/org/intellij/plugins/markdown/fileActions/importFrom/docx/MarkdownDocxFileDropHandler.kt
|
9
|
1961
|
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.intellij.plugins.markdown.fileActions.importFrom.docx
import com.intellij.ide.dnd.FileCopyPasteUtil
import com.intellij.ide.impl.DataManagerImpl
import com.intellij.openapi.editor.CustomFileDropHandler
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.openapi.vfs.VfsUtil
import org.intellij.plugins.markdown.MarkdownBundle
import org.intellij.plugins.markdown.fileActions.export.MarkdownDocxExportProvider
import org.intellij.plugins.markdown.fileActions.utils.MarkdownImportExportUtils
import java.awt.datatransfer.Transferable
import java.io.File
internal class MarkdownDocxFileDropHandler : CustomFileDropHandler() {
override fun canHandle(t: Transferable, editor: Editor?): Boolean {
val list = FileCopyPasteUtil.getFileList(t)?.takeIf { it.size != 1 } ?: return false
return isDocxFile(list.first())
}
override fun handleDrop(t: Transferable, editor: Editor?, project: Project): Boolean {
val list = FileCopyPasteUtil.getFileList(t)?.takeIf { it.size != 1 } ?: return false
val vFileToImport = VfsUtil.findFileByIoFile(list.first(), true)
val dataContext = DataManagerImpl().dataContext
return if (vFileToImport != null) {
val suggestedFilePath = MarkdownImportExportUtils.suggestFileNameToCreate(project, vFileToImport, dataContext)
val importTaskTitle = MarkdownBundle.message("markdown.import.docx.convert.task.title")
val importDialogTitle = MarkdownBundle.message("markdown.import.from.docx.dialog.title")
MarkdownImportDocxDialog(vFileToImport, importTaskTitle, importDialogTitle, project, suggestedFilePath).show()
true
}
else false
}
private fun isDocxFile(file: File): Boolean {
return file.extension == MarkdownDocxExportProvider.format.extension
}
}
|
apache-2.0
|
1a2dca0419ef0e4bf2248058ba978600
| 45.690476 | 140 | 0.787353 | 4.357778 | false | false | false | false |
DuckDeck/AndroidDemo
|
app/src/main/java/stan/androiddemo/project/petal/Widget/BoardEditDialogFragment.kt
|
1
|
6463
|
package stan.androiddemo.project.petal.Widget
import android.app.AlertDialog
import android.app.Dialog
import android.content.Context
import android.os.Bundle
import android.text.TextUtils
import android.view.LayoutInflater
import android.view.View
import android.widget.AdapterView
import android.widget.ArrayAdapter
import android.widget.EditText
import android.widget.Spinner
import stan.androiddemo.R
import stan.androiddemo.project.petal.Base.BaseDialogFragment
import stan.androiddemo.project.petal.Event.OnEditDialogInteractionListener
import stan.androiddemo.tool.Logger
/**
* Created by stanhu on 18/8/2017.
*/
class BoardEditDialogFragment: BaseDialogFragment() {
//UI
lateinit var mEditTextBoardName: EditText
lateinit var mEditTextBoardDescribe: EditText
lateinit var mSpinnerBoardTitle: Spinner
private var mContext: Context? = null
//外部传入的值
private var mStringBoardId: String? = null
private var mStringBoardName: String? = null
private var mStringDescribe: String? = null
private var mStringBoardType: String? = null
private var isChange = false//输入值是否有变化 默认false
internal var mListener: OnEditDialogInteractionListener? = null
override fun getTAGInfo(): String {
return this.toString()
}
override fun onAttach(context: Context?) {
super.onAttach(context)
mContext = context
}
companion object {
//bundle key
private val KEYBOARDID = "keyBoardId"
private val KEYBOARDNAME = "keyBoardName"
private val KEYDESCRIBE = "keyDescribe"
private val KEYBOARDTYPE = "keyBoardType"
fun create(boardId:String,name:String,describe:String,boardTitle:String):BoardEditDialogFragment{
val bundle = Bundle()
bundle.putString(KEYBOARDID, boardId)
bundle.putString(KEYBOARDNAME, name)
bundle.putString(KEYDESCRIBE, describe)
bundle.putString(KEYBOARDTYPE, boardTitle)
val fragment = BoardEditDialogFragment()
fragment.arguments = bundle
return fragment
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val args = arguments
if (args != null){
mStringBoardId = args.getString(KEYBOARDID)
mStringBoardName = args.getString(KEYBOARDNAME)
mStringBoardType = args.getString(KEYBOARDTYPE)
mStringDescribe = args.getString(KEYDESCRIBE)
}
}
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
val builder = AlertDialog.Builder(mContext)
builder.setTitle(resources.getString(R.string.dialog_title_edit))
val inflate = LayoutInflater.from(mContext)
val dialogView = inflate.inflate(R.layout.petal_dialog_board_edit,null)
initView(dialogView)
setData()
builder.setView(dialogView)
builder.setNegativeButton(resources.getString(R.string.dialog_negative),null)
builder.setNeutralButton(resources.getString(R.string.dialog_delete_positive)) { p0, p1 -> mListener?.onDialogNeutralClick(mStringBoardId!!,mStringBoardName!!) }
builder.setPositiveButton(R.string.dialog_edit_positive) { dialog, which ->
Logger.d()
//如果检测到值有变化才有回调
if (DataChange()) {
mListener?.onDialogPositiveClick(mStringBoardId!!,
mEditTextBoardName.text.toString(), mEditTextBoardDescribe.text.toString(), mStringBoardType!!)
}
}
return builder.create()
}
private fun DataChange(): Boolean {
//Spinner 控件会影响 所以先取内部变量
val isChange = this.isChange
if (isChange) {
return true
}
//临时变量
var input: String
input = mEditTextBoardName.text.toString().trim { it <= ' ' }//取名称输入框值
//判断 不为空 并且值有变化
if (!TextUtils.isEmpty(input) && input != mStringBoardName) {
return true
}
input = mEditTextBoardDescribe.text.toString().trim { it <= ' ' }//取描述输入框值
if (!TextUtils.isEmpty(input) && input != mStringDescribe) {
return true
}
return false
}
private fun initView(dialogView: View) {
mEditTextBoardName = dialogView.findViewById(R.id.edit_board_name)
mEditTextBoardDescribe = dialogView.findViewById(R.id.edit_board_describe)
mSpinnerBoardTitle = dialogView.findViewById(R.id.spinner_title)
}
private fun setData() {
//画板名称
if (!TextUtils.isEmpty(mStringBoardName)) {
mEditTextBoardName.setText(mStringBoardName)
} else {
mEditTextBoardName.setText(R.string.text_is_default)
}
//画板描述 可以为空
mEditTextBoardDescribe.setText(mStringDescribe)
//画板类型 定义在本地资源中
val titleList = resources.getStringArray(R.array.title_array_all)
val typeList = resources.getStringArray(R.array.type_array_all)
var selectPosition = 0//默认选中第一项
if (mStringBoardType != null) {
//遍历查找
var i = 0
val size = titleList.size
while (i < size) {
if (typeList[i] == mStringBoardType) {
selectPosition = i
}
i++
}
}
val adapter = ArrayAdapter(mContext, R.layout.support_simple_spinner_dropdown_item, titleList)
mSpinnerBoardTitle.adapter = adapter
mSpinnerBoardTitle.setSelection(selectPosition)
mSpinnerBoardTitle.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
override fun onItemSelected(parent: AdapterView<*>, view: View, position: Int, id: Long) {
Logger.d("position=" + position)
//选中监听事件 产生变化 赋值
val selected = typeList[position]
if (selected != mStringBoardType) {
mStringBoardType = typeList[position]
isChange = true//有选择 就表示数据发生变化
}
}
override fun onNothingSelected(parent: AdapterView<*>) {
}
}
}
}
|
mit
|
a8f8c1a87308241300123c44cf8f933c
| 32.535135 | 169 | 0.643237 | 4.557678 | false | false | false | false |
Waboodoo/HTTP-Shortcuts
|
HTTPShortcuts/app/src/main/kotlin/ch/rmy/android/http_shortcuts/activities/settings/documentation/DocumentationUrlManager.kt
|
1
|
1515
|
package ch.rmy.android.http_shortcuts.activities.settings.documentation
import android.net.Uri
import ch.rmy.android.framework.extensions.isWebUrl
object DocumentationUrlManager {
private const val DOCUMENTATION_HOST = "http-shortcuts.rmy.ch"
private val SUPPORTED_PATHS = setOf(
"categories",
"documentation",
"execution-flow",
"faq",
"import-export",
"introduction",
"privacy-policy",
"scripting",
"shortcuts",
"variables",
)
fun toInternalUrl(url: Uri): Uri? {
if (!canHandle(url)) {
return null
}
return url
.buildUpon()
.scheme("file")
.authority("")
.path("/android_asset/docs" + url.path.orEmpty() + ".html")
.build()
}
fun toExternal(url: Uri): Uri {
if (url.scheme == "file" && url.authority.isNullOrEmpty() && url.path?.startsWith("/android_asset/docs/") == true) {
return url
.buildUpon()
.scheme("https")
.authority(DOCUMENTATION_HOST)
.path("/" + url.path!!.removePrefix("/android_asset/docs/").removeSuffix(".md").removeSuffix(".html"))
.build()
}
return url
}
fun canHandle(url: Uri): Boolean {
if (!url.isWebUrl || url.host != DOCUMENTATION_HOST) {
return false
}
return url.path.orEmpty().trimStart('/') in SUPPORTED_PATHS
}
}
|
mit
|
f75f53e9639ed31b236fc7c6a7496c71
| 27.584906 | 124 | 0.542574 | 4.41691 | false | false | false | false |
prof18/RSS-Parser
|
rssparser/src/main/java/com/prof/rssparser/core/CoreXMLParser.kt
|
1
|
19063
|
/*
* Copyright 2016 Marco Gomiero
*
* 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.prof.rssparser.core
import com.prof.rssparser.Article
import com.prof.rssparser.Channel
import com.prof.rssparser.Image
import com.prof.rssparser.ItunesArticleData
import com.prof.rssparser.ItunesChannelData
import com.prof.rssparser.ItunesOwner
import com.prof.rssparser.utils.RSSKeyword
import com.prof.rssparser.utils.attributeValue
import com.prof.rssparser.utils.contains
import com.prof.rssparser.utils.nextTrimmedText
import org.xmlpull.v1.XmlPullParser
import org.xmlpull.v1.XmlPullParserFactory
import java.io.ByteArrayInputStream
import java.io.InputStreamReader
import java.io.Reader
import java.util.regex.Pattern
internal object CoreXMLParser {
fun parseXML(xml: String): Channel {
var articleBuilder = Article.Builder()
val channelImageBuilder = Image.Builder()
val channelBuilder = Channel.Builder()
val itunesChannelBuilder = ItunesChannelData.Builder()
var itunesArticleBuilder = ItunesArticleData.Builder()
var itunesOwnerBuilder = ItunesOwner.Builder()
// This image url is extracted from the content and the description of the rss item.
// It's a fallback just in case there aren't any images in the enclosure tag.
var imageUrlFromContent: String? = null
val factory = XmlPullParserFactory.newInstance()
factory.isNamespaceAware = false
val xmlPullParser = factory.newPullParser()
val reader: Reader = InputStreamReader(ByteArrayInputStream(xml.trim().toByteArray()))
xmlPullParser.setInput(reader)
// A flag just to be sure of the correct parsing
var insideItem = false
var insideChannel = false
var insideChannelImage = false
var insideItunesOwner = false
var eventType = xmlPullParser.eventType
// Start parsing the xml
loop@ while (eventType != XmlPullParser.END_DOCUMENT) {
// Start parsing the item
when {
eventType == XmlPullParser.START_TAG -> when {
// Entering conditions
xmlPullParser.contains(RSSKeyword.Channel.Channel) -> {
insideChannel = true
}
xmlPullParser.contains(RSSKeyword.Item.Item) -> {
insideItem = true
}
xmlPullParser.contains(RSSKeyword.Channel.Itunes.Owner) -> {
insideItunesOwner = true
}
//region Channel tags
xmlPullParser.contains(RSSKeyword.Channel.LastBuildDate) -> {
if (insideChannel) {
channelBuilder.lastBuildDate(xmlPullParser.nextTrimmedText())
}
}
xmlPullParser.contains(RSSKeyword.Channel.UpdatePeriod) -> {
if (insideChannel) {
channelBuilder.updatePeriod(xmlPullParser.nextTrimmedText())
}
}
xmlPullParser.contains(RSSKeyword.URL) -> {
if (insideChannelImage) {
channelImageBuilder.url(xmlPullParser.nextTrimmedText())
}
}
xmlPullParser.contains(RSSKeyword.Channel.Itunes.Category) -> {
if (insideChannel) {
val category = xmlPullParser.attributeValue(RSSKeyword.Channel.Itunes.Text)
itunesChannelBuilder.addCategory(category)
}
}
xmlPullParser.contains(RSSKeyword.Channel.Itunes.Type) -> {
if (insideChannel) {
itunesChannelBuilder.type(xmlPullParser.nextTrimmedText())
}
}
xmlPullParser.contains(RSSKeyword.Channel.Itunes.NewFeedUrl) -> {
if (insideChannel) {
itunesChannelBuilder.newsFeedUrl(xmlPullParser.nextTrimmedText())
}
}
//endregion
//region Item tags
xmlPullParser.contains(RSSKeyword.Item.Author) -> {
if (insideItem) {
articleBuilder.author(xmlPullParser.nextTrimmedText())
}
}
xmlPullParser.contains(RSSKeyword.Item.Category) -> {
if (insideItem) {
articleBuilder.addCategory(xmlPullParser.nextTrimmedText())
}
}
xmlPullParser.contains(RSSKeyword.Item.Thumbnail) -> {
if (insideItem) {
articleBuilder.image(xmlPullParser.attributeValue(RSSKeyword.URL))
}
}
xmlPullParser.contains(RSSKeyword.Item.MediaContent) -> {
if (insideItem) {
articleBuilder.image(xmlPullParser.attributeValue(RSSKeyword.URL))
}
}
xmlPullParser.contains(RSSKeyword.Item.Enclosure) -> {
if (insideItem) {
val type = xmlPullParser.attributeValue(RSSKeyword.Item.Type)
when {
type != null && type.contains("image") -> {
// If there are multiple elements, we take only the first
articleBuilder.imageIfNull(
xmlPullParser.attributeValue(
RSSKeyword.URL
)
)
}
type != null && type.contains("audio") -> {
// If there are multiple elements, we take only the first
articleBuilder.audioIfNull(
xmlPullParser.attributeValue(
RSSKeyword.URL
)
)
}
type != null && type.contains("video") -> {
// If there are multiple elements, we take only the first
articleBuilder.videoIfNull(
xmlPullParser.attributeValue(
RSSKeyword.URL
)
)
}
else -> {
articleBuilder.imageIfNull(
xmlPullParser.nextText().trim()
)
}
}
}
}
xmlPullParser.contains(RSSKeyword.Item.Source) -> {
if (insideItem) {
val sourceUrl = xmlPullParser.attributeValue(RSSKeyword.URL)
val sourceName = xmlPullParser.nextText()
articleBuilder.sourceName(sourceName)
articleBuilder.sourceUrl(sourceUrl)
}
}
xmlPullParser.contains(RSSKeyword.Item.Time) -> {
if (insideItem) {
articleBuilder.pubDate(xmlPullParser.nextTrimmedText())
}
}
xmlPullParser.contains(RSSKeyword.Item.GUID) -> {
if (insideItem) {
articleBuilder.guid(xmlPullParser.nextTrimmedText())
}
}
xmlPullParser.contains(RSSKeyword.Item.Content) -> {
if (insideItem) {
val content = xmlPullParser.nextTrimmedText()
articleBuilder.content(content)
imageUrlFromContent = getImageUrl(content)
}
}
xmlPullParser.contains(RSSKeyword.Item.PubDate) -> {
if (insideItem) {
val nextTokenType = xmlPullParser.next()
if (nextTokenType == XmlPullParser.TEXT) {
articleBuilder.pubDate(xmlPullParser.text.trim())
}
// Skip to be able to find date inside 'tag' tag
continue@loop
}
}
xmlPullParser.contains(RSSKeyword.Item.News.Image) -> {
if (insideItem) {
articleBuilder.image(xmlPullParser.nextTrimmedText())
}
}
xmlPullParser.contains(RSSKeyword.Item.Itunes.Episode) -> {
if (insideItem) {
itunesArticleBuilder.episode(xmlPullParser.nextTrimmedText())
}
}
xmlPullParser.contains(RSSKeyword.Item.Itunes.EpisodeType) -> {
if (insideItem) {
itunesArticleBuilder.episodeType(xmlPullParser.nextTrimmedText())
}
}
xmlPullParser.contains(RSSKeyword.Item.Itunes.Season) -> {
if (insideItem) {
itunesArticleBuilder.season(xmlPullParser.nextTrimmedText())
}
}
//endregion
//region Itunes Owner tags
xmlPullParser.contains(RSSKeyword.Channel.Itunes.OwnerName) -> {
if (insideItunesOwner) {
itunesOwnerBuilder.name(xmlPullParser.nextTrimmedText())
}
}
xmlPullParser.contains(RSSKeyword.Channel.Itunes.OwnerEmail) -> {
if (insideItunesOwner) {
itunesOwnerBuilder.email(xmlPullParser.nextTrimmedText())
}
}
//endregion
//region Mixed tags
xmlPullParser.contains(RSSKeyword.Image) -> when {
insideChannel && !insideItem -> insideChannelImage = true
insideItem -> articleBuilder.image(xmlPullParser.nextTrimmedText())
}
xmlPullParser.contains(RSSKeyword.Title) -> {
if (insideChannel) {
when {
insideChannelImage -> channelImageBuilder.title(xmlPullParser.nextTrimmedText())
insideItem -> articleBuilder.title(xmlPullParser.nextTrimmedText())
else -> channelBuilder.title(xmlPullParser.nextTrimmedText())
}
}
}
xmlPullParser.contains(RSSKeyword.Link) -> {
if (insideChannel) {
when {
insideChannelImage -> channelImageBuilder.link(xmlPullParser.nextTrimmedText())
insideItem -> articleBuilder.link(xmlPullParser.nextTrimmedText())
else -> channelBuilder.link(xmlPullParser.nextTrimmedText())
}
}
}
xmlPullParser.contains(RSSKeyword.Item.Description) -> {
if (insideChannel) {
when {
insideItem -> {
val description = xmlPullParser.nextTrimmedText()
articleBuilder.description(description)
imageUrlFromContent = getImageUrl(description)
}
insideChannelImage -> channelImageBuilder.description(xmlPullParser.nextTrimmedText())
else -> channelBuilder.description(xmlPullParser.nextTrimmedText())
}
}
}
xmlPullParser.contains(RSSKeyword.Itunes.Author) -> when {
insideItem -> itunesArticleBuilder.author(xmlPullParser.nextTrimmedText())
insideChannel -> itunesChannelBuilder.author(xmlPullParser.nextTrimmedText())
}
xmlPullParser.contains(RSSKeyword.Itunes.Duration) -> when {
insideItem -> itunesArticleBuilder.duration(xmlPullParser.nextTrimmedText())
insideChannel -> itunesChannelBuilder.duration(xmlPullParser.nextTrimmedText())
}
xmlPullParser.contains(RSSKeyword.Itunes.Keywords) -> {
val keywords = xmlPullParser.nextTrimmedText()
val keywordList = keywords?.split(",")?.mapNotNull {
it.ifEmpty {
null
}
} ?: emptyList()
if (keywordList.isNotEmpty()) {
when {
insideItem -> itunesArticleBuilder.keywords(keywordList)
insideChannel -> itunesChannelBuilder.keywords(keywordList)
}
}
}
xmlPullParser.contains(RSSKeyword.Itunes.Image) -> when {
insideItem -> itunesArticleBuilder.image(
xmlPullParser.attributeValue(
RSSKeyword.HREF
)
)
insideChannel -> itunesChannelBuilder.image(
xmlPullParser.attributeValue(
RSSKeyword.HREF
)
)
}
xmlPullParser.contains(RSSKeyword.Itunes.Explicit) -> when {
insideItem -> itunesArticleBuilder.explicit(xmlPullParser.nextTrimmedText())
insideChannel -> itunesChannelBuilder.explicit(xmlPullParser.nextTrimmedText())
}
xmlPullParser.contains(RSSKeyword.Itunes.Subtitle) -> when {
insideItem -> itunesArticleBuilder.subtitle(xmlPullParser.nextTrimmedText())
insideChannel -> itunesChannelBuilder.subtitle(xmlPullParser.nextTrimmedText())
}
xmlPullParser.contains(RSSKeyword.Itunes.Summary) -> when {
insideItem -> itunesArticleBuilder.summary(xmlPullParser.nextTrimmedText())
insideChannel -> itunesChannelBuilder.summary(xmlPullParser.nextTrimmedText())
}
//endregion
}
// Exit conditions
eventType == XmlPullParser.END_TAG && xmlPullParser.contains(RSSKeyword.Item.Item) -> {
// The item is correctly parsed
insideItem = false
// Set data
articleBuilder.imageIfNull(imageUrlFromContent)
articleBuilder.itunesArticleData(itunesArticleBuilder.build())
channelBuilder.addArticle(articleBuilder.build())
// Reset temp data
imageUrlFromContent = null
articleBuilder = Article.Builder()
itunesArticleBuilder = ItunesArticleData.Builder()
}
eventType == XmlPullParser.END_TAG && xmlPullParser.contains(RSSKeyword.Channel.Channel) -> {
// The channel is correctly parsed
insideChannel = false
}
eventType == XmlPullParser.END_TAG && xmlPullParser.contains(RSSKeyword.Image) -> {
// The channel image is correctly parsed
insideChannelImage = false
}
eventType == XmlPullParser.END_TAG && xmlPullParser.contains(RSSKeyword.Channel.Itunes.Owner) -> {
// The itunes owner is correctly parsed
itunesChannelBuilder.owner(itunesOwnerBuilder.build())
itunesOwnerBuilder = ItunesOwner.Builder()
insideItunesOwner = false
}
}
eventType = xmlPullParser.next()
}
val channelImage = channelImageBuilder.build()
if (channelImage.isNotEmpty()) {
channelBuilder.image(channelImage)
}
channelBuilder.itunesChannelData(itunesChannelBuilder.build())
return channelBuilder.build()
}
/**
* Finds the first img tag and get the src as featured image
*
* @param input The content in which to search for the tag
* @return The url, if there is one
*/
private fun getImageUrl(input: String?): String? {
var url: String? = null
val patternImg = Pattern.compile("(<img .*?>)")
val matcherImg = patternImg.matcher(input ?: "")
if (matcherImg.find()) {
val imgTag = matcherImg.group(1)
val patternLink = Pattern.compile("src\\s*=\\s*([\"'])(.+?)([\"'])")
val matcherLink = patternLink.matcher(imgTag ?: "")
if (matcherLink.find()) {
url = matcherLink.group(2)?.trim()
}
}
return url
}
}
|
apache-2.0
|
53fb2468f41af59ace9d96006af242c0
| 47.754476 | 118 | 0.482086 | 6.000315 | false | false | false | false |
vector-im/vector-android
|
vector/src/main/java/im/vector/ui/list/GenericRecyclerViewItem.kt
|
2
|
1443
|
/*
* Copyright 2019 New Vector Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package im.vector.ui.list
import androidx.annotation.DrawableRes
/**
* A generic list item.
* Displays an item with a title, and optional description.
* Can display an accessory on the right, that can be an image or an indeterminate progress.
* If provided with an action, will display a button at the bottom of the list item.
*/
class GenericRecyclerViewItem(val title: String,
var description: String? = null,
val style: STYLE = STYLE.NORMAL_TEXT) {
enum class STYLE {
BIG_TEXT,
NORMAL_TEXT
}
@DrawableRes
var endIconResourceId: Int = -1
var hasIndeterminateProcess = false
var buttonAction: Action? = null
var itemClickAction: Action? = null
class Action(var title: String) {
var perform: Runnable? = null
}
}
|
apache-2.0
|
e820756a4cc79811dab850e79866f430
| 29.723404 | 92 | 0.683299 | 4.333333 | false | false | false | false |
aosp-mirror/platform_frameworks_support
|
jetifier/jetifier/processor/src/test/kotlin/com/android/tools/build/jetifier/processor/transform/pom/PomDocumentTest.kt
|
1
|
13743
|
/*
* Copyright 2017 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.tools.build.jetifier.processor.transform.pom
import com.android.tools.build.jetifier.core.config.Config
import com.android.tools.build.jetifier.core.pom.DependencyVersions
import com.android.tools.build.jetifier.core.pom.PomDependency
import com.android.tools.build.jetifier.core.pom.PomRewriteRule
import com.android.tools.build.jetifier.processor.archive.ArchiveFile
import com.android.tools.build.jetifier.processor.transform.TransformationContext
import com.google.common.truth.Truth
import org.junit.Test
import java.nio.charset.StandardCharsets
import java.nio.file.Paths
class PomDocumentTest {
@Test fun pom_noRules_noChange() {
testRewriteToTheSame(
givenAndExpectedXml =
" <dependencies>\n" +
" <dependency>\n" +
" <groupId>supportGroup</groupId>\n" +
" <artifactId>supportArtifact</artifactId>\n" +
" <version>4.0</version>\n" +
" <type>jar</type>\n" +
" <scope>test</scope>\n" +
" <optional>true</optional>\n" +
" </dependency>\n" +
" </dependencies>",
rules = emptySet()
)
}
@Test fun pom_oneRule_shouldApply() {
testRewrite(
givenXml =
" <dependencies>\n" +
" <dependency>\n" +
" <groupId>supportGroup</groupId>\n" +
" <artifactId>supportArtifact</artifactId>\n" +
" <version>4.0</version>\n" +
" </dependency>\n" +
" <dependency>\n" +
" <systemPath>test/test</systemPath>\n" +
" </dependency>\n" +
" </dependencies>",
expectedXml =
" <dependencies>\n" +
" <dependency>\n" +
" <groupId>testGroup</groupId>\n" +
" <artifactId>testArtifact</artifactId>\n" +
" <version>1.0</version>\n" +
" </dependency>\n" +
" <dependency>\n" +
" <systemPath>test/test</systemPath>\n" +
" </dependency>\n" +
" </dependencies>",
rules = setOf(
PomRewriteRule(
PomDependency(
groupId = "supportGroup", artifactId = "supportArtifact",
version = "4.0"),
PomDependency(
groupId = "testGroup", artifactId = "testArtifact",
version = "1.0")
)
)
)
}
@Test fun pom_oneRule_withVersionSubstitution_shouldApply() {
testRewrite(
givenXml =
" <dependencies>\n" +
" <dependency>\n" +
" <groupId>supportGroup</groupId>\n" +
" <artifactId>supportArtifact</artifactId>\n" +
" <version>4.0</version>\n" +
" </dependency>\n" +
" </dependencies>",
expectedXml =
" <dependencies>\n" +
" <dependency>\n" +
" <groupId>testGroup</groupId>\n" +
" <artifactId>testArtifact</artifactId>\n" +
" <version>1.0.0-test</version>\n" +
" </dependency>\n" +
" </dependencies>",
rules = setOf(
PomRewriteRule(
PomDependency(
groupId = "supportGroup", artifactId = "supportArtifact",
version = "4.0"),
PomDependency(
groupId = "testGroup", artifactId = "testArtifact",
version = "{newSlVersion}")
)
),
versions = DependencyVersions(mapOf("newSlVersion" to "1.0.0-test"))
)
}
@Test fun pom_oneRule_notApplicable() {
testRewriteToTheSame(
givenAndExpectedXml =
" <dependencies>\n" +
" <dependency>\n" +
" <groupId>supportGroup</groupId>\n" +
" <artifactId>supportArtifact</artifactId>\n" +
" <version>4.0</version>\n" +
" </dependency>\n" +
" </dependencies>",
rules = setOf(
PomRewriteRule(
PomDependency(
groupId = "supportGroup", artifactId = "supportArtifact2",
version = "4.0"),
PomDependency(
groupId = "testGroup", artifactId = "testArtifact",
version = "1.0")
)
)
)
}
@Test fun pom_oneRule_appliedForEachType() {
testRewrite(
givenXml =
" <dependencies>\n" +
" <dependency>\n" +
" <groupId>supportGroup</groupId>\n" +
" <artifactId>supportArtifact</artifactId>\n" +
" <version>4.0</version>\n" +
" <type>test</type>\n" +
" </dependency>\n" +
" <dependency>\n" +
" <groupId>supportGroup</groupId>\n" +
" <artifactId>supportArtifact</artifactId>\n" +
" <version>4.0</version>\n" +
" <type>compile</type>\n" +
" </dependency>\n" +
" </dependencies>",
expectedXml =
" <dependencies>\n" +
" <dependency>\n" +
" <groupId>testGroup</groupId>\n" +
" <artifactId>testArtifact</artifactId>\n" +
" <version>1.0</version>\n" +
" <type>test</type>\n" +
" </dependency>\n" +
" <dependency>\n" +
" <groupId>testGroup</groupId>\n" +
" <artifactId>testArtifact</artifactId>\n" +
" <version>1.0</version>\n" +
" <type>compile</type>\n" +
" </dependency>\n" +
" </dependencies>",
rules = setOf(
PomRewriteRule(
PomDependency(
groupId = "supportGroup", artifactId = "supportArtifact",
version = "4.0"),
PomDependency(
groupId = "testGroup", artifactId = "testArtifact",
version = "1.0")
)
)
)
}
@Test fun pom_oneRule_hasToKeepExtraAttributesAndRewrite() {
testRewrite(
givenXml =
" <dependencies>\n" +
" <dependency>\n" +
" <groupId>supportGroup</groupId>\n" +
" <artifactId>supportArtifact</artifactId>\n" +
" <version>4.0</version>\n" +
" <classifier>hey</classifier>\n" +
" <type>jar</type>\n" +
" <scope>runtime</scope>\n" +
" <systemPath>somePath</systemPath>\n" +
" <optional>true</optional>\n" +
" </dependency>\n" +
" </dependencies>",
expectedXml =
" <dependencies>\n" +
" <dependency>\n" +
" <groupId>testGroup</groupId>\n" +
" <artifactId>testArtifact</artifactId>\n" +
" <version>1.0</version>\n" +
" <classifier>hey</classifier>\n" +
" <type>jar</type>\n" +
" <scope>runtime</scope>\n" +
" <systemPath>somePath</systemPath>\n" +
" <optional>true</optional>\n" +
" </dependency>\n" +
" </dependencies>",
rules = setOf(
PomRewriteRule(
PomDependency(
groupId = "supportGroup", artifactId = "supportArtifact",
version = "4.0"),
PomDependency(
groupId = "testGroup", artifactId = "testArtifact",
version = "1.0")
)
)
)
}
@Test fun pom_usingEmptyProperties_shouldNotCrash() {
val document = loadDocument(
" <properties/>\n" +
" <dependencies>\n" +
" <dependency>\n" +
" <groupId>supportGroup</groupId>\n" +
" <artifactId>\${groupId.version.property}</artifactId>\n" +
" <version>\${groupId.version.property}</version>\n" +
" </dependency>\n" +
" </dependencies>"
)
Truth.assertThat(document.dependencies).hasSize(1)
}
@Test fun pom_usingProperties_shouldResolve() {
val document = loadDocument(
" <properties>\n" +
" <groupId.version.property>1.0.0</groupId.version.property>\n" +
" <groupId.artifactId.property>supportArtifact</groupId.artifactId.property>\n" +
" </properties>\n" +
" <dependencies>\n" +
" <dependency>\n" +
" <groupId>supportGroup</groupId>\n" +
" <artifactId>\${groupId.artifactId.property}</artifactId>\n" +
" <version>\${groupId.version.property}</version>\n" +
" </dependency>\n" +
" </dependencies>"
)
Truth.assertThat(document.dependencies).hasSize(1)
val dependency = document.dependencies.first()
Truth.assertThat(dependency.version).isEqualTo("1.0.0")
Truth.assertThat(dependency.artifactId).isEqualTo("supportArtifact")
}
private fun testRewriteToTheSame(givenAndExpectedXml: String, rules: Set<PomRewriteRule>) {
testRewrite(givenAndExpectedXml, givenAndExpectedXml, rules)
}
private fun testRewrite(
givenXml: String,
expectedXml: String,
rules: Set<PomRewriteRule>,
versions: DependencyVersions = DependencyVersions.EMPTY
) {
val given =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
"<project xmlns=\"http://maven.apache.org/POM/4.0.0\" " +
"xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" " +
"xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 " +
"http://maven.apache.org/xsd/maven-4.0.0.xsd\">\n" +
" <!-- Some comment -->\n" +
" <groupId>test.group</groupId>\n" +
" <artifactId>test.artifact.id</artifactId>\n" +
" <version>1.0</version>\n" +
" $givenXml\n" +
"</project>\n"
var expected =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
"<project xmlns=\"http://maven.apache.org/POM/4.0.0\" " +
"xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" " +
"xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 " +
"http://maven.apache.org/xsd/maven-4.0.0.xsd\">\n" +
" <!-- Some comment -->\n" +
" <groupId>test.group</groupId>\n" +
" <artifactId>test.artifact.id</artifactId>\n" +
" <version>1.0</version>\n" +
" $expectedXml\n" +
"</project>\n"
val file = ArchiveFile(Paths.get("pom.xml"), given.toByteArray())
val pomDocument = PomDocument.loadFrom(file)
val config = Config.fromOptional(
restrictToPackagePrefixes = emptySet(),
pomRewriteRules = rules)
val context = TransformationContext(config, versions = versions)
pomDocument.applyRules(context)
pomDocument.saveBackToFileIfNeeded()
var strResult = file.data.toString(StandardCharsets.UTF_8)
// Remove spaces in front of '<' and the back of '>'
expected = expected.replace(">[ ]+".toRegex(), ">")
expected = expected.replace("[ ]+<".toRegex(), "<")
strResult = strResult.replace(">[ ]+".toRegex(), ">")
strResult = strResult.replace("[ ]+<".toRegex(), "<")
// Replace newline characters to match the ones we are using in the expected string
strResult = strResult.replace("\\r\\n".toRegex(), "\n")
Truth.assertThat(strResult).isEqualTo(expected)
}
private fun loadDocument(givenXml: String): PomDocument {
val given =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
"<project xmlns=\"http://maven.apache.org/POM/4.0.0\" " +
"xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" " +
"xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 " +
"http://maven.apache.org/xsd/maven-4.0.0.xsd\">\n" +
" <!-- Some comment -->\n" +
" <groupId>test.group</groupId>\n" +
" <artifactId>test.artifact.id</artifactId>\n" +
" <version>1.0</version>\n" +
" $givenXml\n" +
"</project>\n"
val file = ArchiveFile(Paths.get("pom.xml"), given.toByteArray())
val pomDocument = PomDocument.loadFrom(file)
return pomDocument
}
}
|
apache-2.0
|
81e71c67c0e1191e492f96a9aea4e058
| 39.184211 | 96 | 0.495962 | 4.164545 | false | true | false | false |
chiken88/passnotes
|
app/src/main/kotlin/com/ivanovsky/passnotes/data/crypto/entity/SecretData.kt
|
1
|
880
|
package com.ivanovsky.passnotes.data.crypto.entity
data class SecretData(
val initVector: String,
val encryptedText: String
) {
override fun toString(): String {
return "$initVector$INIT_VECTOR_SEPARATOR$encryptedText"
}
companion object {
private const val INIT_VECTOR_SEPARATOR = "|"
fun parse(data: String): SecretData? {
var result: SecretData? = null
if (data.isNotEmpty()) {
val separatorIdx = data.indexOf(INIT_VECTOR_SEPARATOR)
if (separatorIdx > 0 && separatorIdx + 1 <= data.length) {
val initVector = data.substring(0, separatorIdx)
val cipherText = data.substring(separatorIdx + 1)
result = SecretData(initVector, cipherText)
}
}
return result
}
}
}
|
gpl-2.0
|
fbd62f6f7cd2a9bd7cbc8f7ce95e2dbc
| 27.419355 | 74 | 0.570455 | 4.656085 | false | false | false | false |
orgzly/orgzly-android
|
app/src/main/java/com/orgzly/android/db/dao/BookLinkDao.kt
|
1
|
859
|
package com.orgzly.android.db.dao
import androidx.room.*
import com.orgzly.android.db.entity.BookLink
@Dao
abstract class BookLinkDao : BaseDao<BookLink> {
@Query("SELECT * FROM book_links WHERE book_id = :bookId")
abstract fun getByBookId(bookId: Long): BookLink?
@Insert(onConflict = OnConflictStrategy.REPLACE)
abstract fun replace(bookLink: BookLink): Long
@Query("DELETE FROM book_links WHERE book_id = :bookId")
abstract fun deleteByBookId(bookId: Long)
@Query("DELETE FROM book_links WHERE repo_id = :repoId")
abstract fun deleteByRepoId(repoId: Long)
@Transaction
open fun upsert(bookId: Long, repoId: Long) {
val link = getByBookId(bookId)
if (link == null) {
insert(BookLink(bookId, repoId))
} else {
update(link.copy(repoId = repoId))
}
}
}
|
gpl-3.0
|
904883feddec3555954baf91eacb6a0f
| 27.633333 | 62 | 0.665891 | 3.869369 | false | false | false | false |
orgzly/orgzly-android
|
app/src/main/java/com/orgzly/android/reminders/RemindersScheduler.kt
|
1
|
6512
|
package com.orgzly.android.reminders
import android.app.AlarmManager
import android.app.Application
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.os.SystemClock
import android.util.Log
import androidx.annotation.RequiresApi
import com.orgzly.android.AppIntent
import com.orgzly.android.data.logs.AppLogsRepository
import com.orgzly.android.prefs.AppPreferences
import com.orgzly.android.ui.util.ActivityUtils
import com.orgzly.android.ui.util.getAlarmManager
import com.orgzly.android.util.LogMajorEvents
import org.joda.time.DateTime
import javax.inject.Inject
class RemindersScheduler @Inject constructor(val context: Application, val logs: AppLogsRepository) {
companion object {
fun notifyDataSetChanged(context: Context) {
context.sendBroadcast(dataSetChangedIntent(context))
}
private fun dataSetChangedIntent(context: Context): Intent {
return Intent(context, RemindersBroadcastReceiver::class.java).apply {
action = AppIntent.ACTION_REMINDER_DATA_CHANGED
}
}
}
fun scheduleReminder(inMs: Long, hasTime: Boolean) {
val intent = reminderTriggeredIntent()
schedule(intent, inMs, hasTime, "reminder")
}
fun scheduleSnoozeEnd(noteId: Long, noteTimeType: Int, timestamp: Long, hasTime: Boolean) {
val (inMs, newRunTime) = snoozeEndInMs(timestamp) ?: return
val intent = snoozeEndedIntent(noteId, noteTimeType, newRunTime)
schedule(intent, inMs, hasTime, "snooze")
}
fun cancelAll() {
context.getAlarmManager().cancel(reminderTriggeredIntent())
if (LogMajorEvents.isEnabled()) {
logs.log(LogMajorEvents.REMINDERS, "Canceled all reminders")
}
}
private fun reminderTriggeredIntent(): PendingIntent {
return Intent(context, RemindersBroadcastReceiver::class.java).let { intent ->
intent.action = AppIntent.ACTION_REMINDER_TRIGGERED
PendingIntent.getBroadcast(context, 0, intent, ActivityUtils.immutable(0))
}
}
private fun snoozeEndedIntent(noteId: Long, noteTimeType: Int, timestamp: Long): PendingIntent {
return Intent(context, RemindersBroadcastReceiver::class.java).let { intent ->
intent.action = AppIntent.ACTION_REMINDER_SNOOZE_ENDED
intent.data = Uri.parse("custom://$noteId")
intent.putExtra(AppIntent.EXTRA_NOTE_ID, noteId)
intent.putExtra(AppIntent.EXTRA_NOTE_TIME_TYPE, noteTimeType)
intent.putExtra(AppIntent.EXTRA_SNOOZE_TIMESTAMP, timestamp)
PendingIntent.getBroadcast(context, 0, intent, ActivityUtils.immutable(0))
}
}
private fun schedule(intent: PendingIntent, inMs: Long, hasTime: Boolean, origin: String) {
val alarmManager = context.getAlarmManager()
// TODO: Add preferences to control *how* to schedule the alarms
if (hasTime) {
if (AppPreferences.remindersUseAlarmClockForTodReminders(context)) {
scheduleAlarmClock(alarmManager, intent, inMs, origin)
} else {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
scheduleExactAndAllowWhileIdle(alarmManager, intent, inMs, origin)
} else {
scheduleExact(alarmManager, intent, inMs, origin)
}
}
} else {
// Does not trigger while dozing
scheduleExact(alarmManager, intent, inMs, origin)
}
// Intent received, notifications not displayed by default
// Note: Neither setAndAllowWhileIdle() nor setExactAndAllowWhileIdle() can fire
// alarms more than once per 9 minutes, per app.
// scheduleExactAndAllowWhileIdle(context, intent, inMs)
}
private fun scheduleAlarmClock(alarmManager: AlarmManager, intent: PendingIntent, inMs: Long, origin: String) {
val info = AlarmManager.AlarmClockInfo(System.currentTimeMillis() + inMs, null)
alarmManager.setAlarmClock(info, intent)
logScheduled("setAlarmClock", origin, inMs)
}
private fun scheduleExact(alarmManager: AlarmManager, intent: PendingIntent, inMs: Long, origin: String) {
alarmManager.setExact(
AlarmManager.ELAPSED_REALTIME_WAKEUP,
SystemClock.elapsedRealtime() + inMs,
intent)
logScheduled("setExact", origin, inMs)
}
@RequiresApi(Build.VERSION_CODES.M)
private fun scheduleExactAndAllowWhileIdle(alarmManager: AlarmManager, intent: PendingIntent, inMs: Long, origin: String) {
alarmManager.setExactAndAllowWhileIdle(
AlarmManager.ELAPSED_REALTIME_WAKEUP,
SystemClock.elapsedRealtime() + inMs,
intent)
logScheduled("setExactAndAllowWhileIdle", origin, inMs)
}
private fun logScheduled(method: String, origin: String, inMs: Long) {
if (LogMajorEvents.isEnabled()) {
val now = System.currentTimeMillis()
logs.log(
LogMajorEvents.REMINDERS,
"Scheduled ($origin) using $method in $inMs ms (~ ${DateTime(now + inMs)}) on ${Build.DEVICE} (API ${Build.VERSION.SDK_INT})"
)
}
}
private fun snoozeEndInMs(timestamp: Long): Pair<Long, Long>? {
val snoozeTime = AppPreferences.remindersSnoozeTime(context) * 60 * 1000L
val snoozeRelativeTo = AppPreferences.remindersSnoozeRelativeTo(context)
when (snoozeRelativeTo) {
"button" -> {
// Fixed time after button is pressed
return Pair(snoozeTime, timestamp)
}
"alarm" -> {
var t = timestamp + snoozeTime
var inMs = t - System.currentTimeMillis()
// keep adding snooze times until positive: handle the case where
// someone lets the alarm go off for more that one snoozeTime interval
while (inMs <= 0) {
inMs += snoozeTime
t += snoozeTime
}
return Pair(inMs, t)
}
else -> {
// should never happen
Log.e(TAG, "unhandled snoozeRelativeTo $snoozeRelativeTo")
return null
}
}
}
private val TAG: String = RemindersScheduler::class.java.name
}
|
gpl-3.0
|
999a8e1d7a0ed4b937c34631506aa453
| 38.23494 | 141 | 0.647881 | 4.678161 | false | false | false | false |
Authman2/Orbs-2
|
Orbs2/src/main/java/world/Camera.kt
|
1
|
1257
|
package world
import entities.Entity
import javafx.geometry.Rectangle2D
import je.visual.Vector2D
import main_package.Orbs2
class Camera(x: Float, y: Float) {
/********************
* *
* VARIABLES *
* *
*********************/
public var position: Vector2D = Vector2D(x,y)
public var collisionBox: Rectangle2D = Rectangle2D(position.X.toDouble(), position.Y.toDouble(),
Orbs2.WIDTH.toDouble(), Orbs2.HEIGHT.toDouble())
/********************
* *
* GETTERS *
* *
*********************/
/** Returns whether or not the camera is touching a certain entity. This means that the entity
is within the camera view. */
public fun touching(ent: Entity): Boolean {
if( collisionBox.intersects( ent.renderBox ) ) {
return true;
}
return false;
}
/********************
* *
* ABSTRACT *
* *
*********************/
fun initialize() {
}
fun update(ent: Entity) {
position.X = ent.position.X*ent.size - Orbs2.WIDTH/2
position.Y = ent.position.Y*ent.size - Orbs2.HEIGHT/2
this.collisionBox = Rectangle2D(position.X.toDouble(),
position.Y.toDouble(),
Orbs2.WIDTH.toDouble(),
Orbs2.HEIGHT.toDouble())
}
fun draw() {
}
}
|
gpl-3.0
|
24d12d495995bd31f4f5755cf03bf7ae
| 18.65625 | 97 | 0.559268 | 3.206633 | false | false | false | false |
proxer/ProxerLibAndroid
|
library/src/main/kotlin/me/proxer/library/entity/user/UserHistoryEntry.kt
|
2
|
1036
|
package me.proxer.library.entity.user
import com.squareup.moshi.Json
import com.squareup.moshi.JsonClass
import me.proxer.library.entity.ProxerIdItem
import me.proxer.library.enums.Category
import me.proxer.library.enums.MediaLanguage
import me.proxer.library.enums.Medium
/**
* Entity representing a single entry in the history list.
*
* @property entryId The id of the associated [me.proxer.library.entity.info.Entry].
* @property name The name.
* @property language The language.
* @property medium The medium.
* @property category The category.
* @property episode The episode.
*
* @author Ruben Gees
*/
@JsonClass(generateAdapter = true)
data class UserHistoryEntry(
@Json(name = "id") override val id: String,
@Json(name = "eid") val entryId: String,
@Json(name = "name") val name: String,
@Json(name = "language") val language: MediaLanguage,
@Json(name = "medium") val medium: Medium,
@Json(name = "kat") val category: Category,
@Json(name = "episode") val episode: Int
) : ProxerIdItem
|
gpl-3.0
|
44edd530019db79a6d65ee72db06dd23
| 32.419355 | 84 | 0.726834 | 3.660777 | false | false | false | false |
tmarsteel/kotlin-prolog
|
core/src/main/kotlin/com/github/prologdb/runtime/exceptions.kt
|
1
|
4914
|
@file:JvmName("PrologExceptionUtils")
package com.github.prologdb.runtime
import com.github.prologdb.runtime.exception.PrologStackTraceElement
import com.github.prologdb.runtime.module.Module
import com.github.prologdb.runtime.term.Term
import com.github.prologdb.runtime.term.Variable
import com.github.prologdb.runtime.term.prologTypeName
import java.util.concurrent.atomic.AtomicReference
/**
* An exception related to, but not limited to, parsing and interpreting prolog programs.
*/
abstract class PrologException(message: String, override val cause: Throwable? = null) : RuntimeException(message) {
private val _prologStackTrace = mutableListOf<PrologStackTraceElement>()
fun addPrologStackFrame(frameInfo: PrologStackTraceElement) {
_prologStackTrace.add(frameInfo)
}
val prologStackTrace: List<PrologStackTraceElement> = _prologStackTrace
}
open class PrologInternalError(message: String, cause: Throwable? = null) : PrologException(message, cause)
open class PredicateNotDynamicException(val indicator: FullyQualifiedClauseIndicator, cause: Throwable? = null) : PrologException("Predicate $indicator is not dynamic", cause)
open class PrologPermissionError(message: String, cause: Throwable? = null) : PrologException(message, cause)
open class PrologUnsupportedOperationException(message: String, cause: Throwable? = null) : PrologException(message, cause)
open class TermNotAssertableException(message: String) : PrologUnsupportedOperationException(message)
open class InsufficientInstantiationException(val variable: Variable, message: String = "$variable is not sufficiently instantiated") : PrologException(message)
open class CircularTermException(message: String) : PrologInternalError(message)
open class PredicateNotDefinedException(
val indicator: ClauseIndicator,
val inContextOfModule: Module,
message: String? = null
) : PrologException(
message ?: "Predicate $indicator not defined in context of module ${inContextOfModule.declaration.moduleName}"
)
open class PredicateNotExportedException(val fqi: FullyQualifiedClauseIndicator, inContextOfModule: Module) : PredicateNotDefinedException(
fqi.indicator,
inContextOfModule,
"Predicate ${fqi.indicator} is not exported by module ${fqi.moduleName}"
)
open class PrologInvocationContractViolationException(private val initialIndicator: ClauseIndicator?, message: String, cause: Throwable? = null) : PrologException(message, cause) {
constructor(message: String, cause: Throwable? = null) : this(null, message, cause)
private val actualIndicator = AtomicReference<ClauseIndicator>(initialIndicator)
val indicator: ClauseIndicator?
get() = actualIndicator.get()
fun fillIndicator(indicator: ClauseIndicator) {
if (!actualIndicator.compareAndSet(null, indicator)) {
throw IllegalStateException("The indicator can only be set once.")
}
}
}
open class ArgumentError(
predicate: ClauseIndicator?,
val argumentIndex: Int,
message: String,
cause: Throwable? = null
) : PrologInvocationContractViolationException(predicate, StringBuilder().also { msg ->
msg.append("Argument ")
msg.append(argumentIndex + 1)
if (predicate != null) {
msg.append(" to ")
msg.append(predicate.toString())
}
msg.append(' ')
msg.append(message)
}.toString(), cause) {
constructor(argumentIndex: Int, message: String, cause: Throwable? = null) : this(null, argumentIndex, message, cause)
}
class ArgumentTypeError(
predicate: ClauseIndicator?,
argumentIndex: Int,
val actual: Term,
vararg val expectedTypes: Class<out Term>
) : ArgumentError(predicate, argumentIndex, StringBuilder().also { msg ->
if (actual is Variable) {
msg.append(" not sufficiently instantiated (expected ")
msg.append(expectedTypes.expectedPhrase)
msg.append(")")
} else {
msg.append(" must be ")
msg.append(expectedTypes.expectedPhrase)
msg.append(", got ")
msg.append(actual.prologTypeName)
}
}.toString()) {
constructor(argumentIndex: Int, actual: Term, vararg expectedTypes: Class<out Term>) : this(
null,
argumentIndex,
actual,
*expectedTypes
)
private companion object {
val Class<out Term>.expectedPhrase: String
get() = if (Variable::class.java.isAssignableFrom(this)) "unbound" else "a $prologTypeName"
val Array<out Class<out Term>>.expectedPhrase: String
get() = when (this.size) {
0, 1 -> single().expectedPhrase
else -> {
val most = take(size - 1).joinToString(
transform = { it.expectedPhrase },
separator = ", "
)
"$most or ${last().expectedPhrase}"
}
}
}
}
|
mit
|
5d00ca9130e0e7b3a3dd40f5f2754dc3
| 38.629032 | 180 | 0.707774 | 4.653409 | false | false | false | false |
davinkevin/Podcast-Server
|
backend/src/main/kotlin/com/github/davinkevin/podcastserver/update/updaters/youtube/YoutubeByXmlUpdater.kt
|
1
|
5044
|
package com.github.davinkevin.podcastserver.update.updaters.youtube
import com.github.davinkevin.podcastserver.update.updaters.ItemFromUpdate
import com.github.davinkevin.podcastserver.update.updaters.PodcastToUpdate
import com.github.davinkevin.podcastserver.update.updaters.Updater
import org.jdom2.Element
import org.jdom2.Namespace
import org.jdom2.input.SAXBuilder
import org.jsoup.Jsoup
import org.springframework.core.io.ByteArrayResource
import org.springframework.util.DigestUtils
import org.springframework.web.reactive.function.client.WebClient
import org.springframework.web.reactive.function.client.bodyToMono
import reactor.core.publisher.Flux
import reactor.core.publisher.Mono
import reactor.kotlin.core.publisher.toFlux
import reactor.kotlin.core.publisher.toMono
import java.net.URI
import java.time.ZonedDateTime
import java.time.format.DateTimeFormatter
/**
* Created by kevin on 15/03/2020
*/
class YoutubeByXmlUpdater(
private val wc: WebClient
): Updater {
override fun findItems(podcast: PodcastToUpdate): Flux<ItemFromUpdate> {
return fetchXml(podcast.url)
.flatMapMany { text ->
val xml = SAXBuilder().build(text.inputStream)
val dn = xml.rootElement.namespace
xml
.rootElement
.getChildren("entry", dn)
.toFlux()
.map { toItem(it, dn) }
}
}
private fun toItem(e: Element, dn: Namespace): ItemFromUpdate {
val mediaGroup = e.getChild("group", MEDIA_NAMESPACE)
val idVideo = mediaGroup.getChild("content", MEDIA_NAMESPACE)
.getAttributeValue("url")
.substringAfterLast("/")
.substringBefore("?")
val thumbnail = mediaGroup.getChild("thumbnail", MEDIA_NAMESPACE)
return ItemFromUpdate(
title = e.getChildText("title", dn),
description = mediaGroup.getChildText("description", MEDIA_NAMESPACE),
//2013-12-20T22:30:01.000Z
pubDate = ZonedDateTime.parse(e.getChildText("published", dn), DateTimeFormatter.ISO_DATE_TIME),
url = URI("https://www.youtube.com/watch?v=$idVideo"),
cover = ItemFromUpdate.Cover(
url = URI(thumbnail.getAttributeValue("url")),
width = thumbnail.getAttributeValue("width").toInt(),
height = thumbnail.getAttributeValue("height").toInt()
),
mimeType = "video/webm"
)
}
override fun signatureOf(url: URI): Mono<String> {
return fetchXml(url)
.flatMapIterable { text ->
val xml = SAXBuilder().build(text.inputStream)
val dn = xml.rootElement.namespace
xml
.rootElement
.getChildren("entry", dn)
.map { it.getChildText("id", dn) }
}
.sort()
.reduce { t, u -> "$t, $u" }
.map { DigestUtils.md5DigestAsHex(it.toByteArray()) }
.switchIfEmpty("".toMono())
}
private fun fetchXml(url: URI): Mono<ByteArrayResource> {
return queryParamsOf(url)
.flatMap { (key, value) -> wc
.get()
.uri { it
.path("/feeds/videos.xml")
.queryParam(key, value)
.build()
}
.retrieve()
.bodyToMono<ByteArrayResource>()
}
}
private fun queryParamsOf(url: URI): Mono<Pair<String, String>> {
val stringUrl = url.toASCIIString()
if (isPlaylist(url)) {
val playlistId = stringUrl.substringAfter("list=")
return ("playlist_id" to playlistId).toMono()
}
val path = stringUrl.substringAfterLast("https://www.youtube.com")
return wc
.get()
.uri(path)
.retrieve()
.bodyToMono<String>()
.map { Jsoup.parse(it, "https://www.youtube.com") }
.flatMap { Mono.justOrEmpty(it.select("meta[itemprop=channelId]").firstOrNull()) }
.map { "channel_id" to it.attr("content") }
}
override fun type() = type
override fun compatibility(url: String): Int = youtubeCompatibility(url)
companion object {
private const val PLAYLIST_RSS_BASE = "https://www.youtube.com/feeds/videos.xml?playlist_id=%s"
private const val CHANNEL_RSS_BASE = "https://www.youtube.com/feeds/videos.xml?channel_id=%s"
private const val URL_PAGE_BASE = "https://www.youtube.com/watch?v=%s"
private val MEDIA_NAMESPACE = Namespace.getNamespace("media", "http://search.yahoo.com/mrss/")
}
}
|
apache-2.0
|
736b1878acdea19d6b29e3905d48cd1e
| 39.031746 | 112 | 0.568795 | 4.714019 | false | false | false | false |
ratedali/EEESE-android
|
app/src/main/java/edu/uofk/eeese/eeese/about/AboutActivity.kt
|
1
|
5341
|
/*
* Copyright 2017 Ali Salah Alddin
*
* 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 edu.uofk.eeese.eeese.about
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.support.design.widget.NavigationView
import android.support.v4.widget.DrawerLayout
import android.support.v7.app.AppCompatActivity
import android.view.MenuItem
import android.view.View
import com.github.florent37.picassopalette.PicassoPalette
import com.squareup.picasso.Picasso
import edu.uofk.eeese.eeese.EEESEapp
import edu.uofk.eeese.eeese.R
import edu.uofk.eeese.eeese.data.sync.SyncManager
import edu.uofk.eeese.eeese.util.ActivityUtils
import edu.uofk.eeese.eeese.util.ViewUtils
import kotlinx.android.synthetic.main.activity_home.*
import kotlinx.android.synthetic.main.project_gallery_card.*
import javax.inject.Inject
class AboutActivity : AppCompatActivity(), AboutContract.View {
companion object {
private val TAG = AboutActivity::class.java.name
private val PROJECT_GALLERY_URL = "http://eeese.uofk.edu#project"
}
@Inject lateinit var aboutPresenter: AboutContract.Presenter
@Inject lateinit var syncManager: SyncManager
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
(application as EEESEapp)
.appComponent
.aboutComponent(AboutModule(this))
.inject(this)
syncManager.setupSync()
ActivityUtils.setEnterTransition(this, R.transition.home_enter)
ActivityUtils.setSharedElementEnterTransition(this, R.transition.shared_toolbar)
ActivityUtils.setSharedElementExitTransition(this, R.transition.shared_toolbar)
setContentView(R.layout.activity_home)
setSupportActionBar(toolbar)
val actionBar = supportActionBar
if (actionBar != null) {
actionBar.setHomeAsUpIndicator(R.drawable.ic_menu)
actionBar.setDisplayHomeAsUpEnabled(true)
actionBar.setTitle(R.string.app_name)
}
setupDrawer(nav_view, drawer_layout)
aboutPresenter.loadGalleryImage()
}
override fun onResume() {
super.onResume()
aboutPresenter.subscribe()
}
override fun onPause() {
super.onPause()
aboutPresenter.unsubscribe()
}
override fun setPresenter(presenter: AboutContract.Presenter) {
aboutPresenter = presenter
}
override fun openGallery() {
val intent = Intent(Intent.ACTION_VIEW, Uri.parse(PROJECT_GALLERY_URL))
startActivity(intent)
}
override fun showGalleryImage(imageUri: Uri) {
Picasso.with(this)
.load(imageUri)
.into(gallery_image,
PicassoPalette.with(imageUri.toString(), gallery_image)
.use(PicassoPalette.Profile.VIBRANT)
.intoBackground(gallery_card)
.intoTextColor(gallery_title,
PicassoPalette.Swatch.TITLE_TEXT_COLOR)
.intoTextColor(gallery_body,
PicassoPalette.Swatch.BODY_TEXT_COLOR))
}
private fun setupDrawer(navView: NavigationView,
drawer: DrawerLayout) {
navView.setCheckedItem(R.id.nav_about)
navView.setNavigationItemSelectedListener {
it.isChecked = true
drawer.closeDrawers()
val targetActivity = ActivityUtils.getTargetActivity(it)
if (targetActivity != null && targetActivity != this::class.java) {
val intent = Intent(this, targetActivity)
ActivityUtils.startActivityWithTransition(this, intent,
android.util.Pair<View, String>(appbar,
getString(R.string.transitionname_toolbar)))
}
true
}
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
android.R.id.home -> ViewUtils.openDrawer(drawer_layout)
else -> return super.onOptionsItemSelected(item)
}
return true
}
fun galleryCardClicked(view: View) {
aboutPresenter.galleryCardClicked()
}
}
|
mit
|
f4eb7c44524c2d0cd3a06db9bf7acfc7
| 39.157895 | 463 | 0.67478 | 4.855455 | false | false | false | false |
joseph-roque/BowlingCompanion
|
app/src/main/java/ca/josephroque/bowlingcompanion/database/Saviour.kt
|
1
|
8019
|
package ca.josephroque.bowlingcompanion.database
import android.content.ContentValues
import android.content.Context
import android.database.sqlite.SQLiteDatabase
import android.util.Log
import ca.josephroque.bowlingcompanion.App
import ca.josephroque.bowlingcompanion.common.Android
import ca.josephroque.bowlingcompanion.database.Contract.FrameEntry
import ca.josephroque.bowlingcompanion.database.Contract.GameEntry
import ca.josephroque.bowlingcompanion.database.Contract.MatchPlayEntry
import ca.josephroque.bowlingcompanion.games.Frame
import ca.josephroque.bowlingcompanion.games.Game
import ca.josephroque.bowlingcompanion.games.lane.toInt
import ca.josephroque.bowlingcompanion.matchplay.MatchPlay
import kotlinx.coroutines.experimental.async
import kotlinx.coroutines.experimental.delay
import kotlinx.coroutines.experimental.CommonPool
import kotlinx.coroutines.experimental.CoroutineStart
import kotlinx.coroutines.experimental.Deferred
import kotlinx.coroutines.experimental.Job
import kotlinx.coroutines.experimental.launch
import java.lang.ref.WeakReference
import java.util.LinkedList
import java.util.Queue
import java.util.concurrent.atomic.AtomicBoolean
/**
* Copyright (C) 2018 Joseph Roque
*
* Managing saving to the database synchronously and waiting for tasks to finish saving before
* loading happens.
*/
class Saviour private constructor() {
companion object {
@Suppress("unused")
private const val TAG = "Saviour"
val instance: Saviour by lazy { Holder.INSTANCE }
}
private object Holder { val INSTANCE = Saviour() }
private var saviourIsRunning = AtomicBoolean(false)
private val saveQueue: Queue<Job> = LinkedList()
init {
launchSaviourProcessor()
}
// MARK: Saviour
fun wait(): Deferred<Unit> {
return async(CommonPool) {
launchSaviourProcessor()
while (saveQueue.isNotEmpty()) {
delay(50)
}
}
}
fun saveFrame(weakContext: WeakReference<Context>, score: Int, frame: Frame) {
val job = launch(context = Android, start = CoroutineStart.LAZY) {
val strongContext = weakContext.get() ?: return@launch
val database = DatabaseHelper.getInstance(strongContext).writableDatabase
database.beginTransaction()
try {
// Save the score
val values = ContentValues()
values.put(GameEntry.COLUMN_SCORE, score)
database.update(GameEntry.TABLE_NAME,
values,
"${GameEntry._ID}=?",
arrayOf(frame.gameId.toString()))
// Save the frame
writeFrameToDatabase(database, frame)
database.setTransactionSuccessful()
} catch (ex: Exception) {
Log.e(TAG, "Fatal error. Game could not save.")
throw ex
} finally {
database.endTransaction()
}
}
saveQueue.offer(job)
launchSaviourProcessor()
}
fun saveMatchPlay(weakContext: WeakReference<Context>, matchPlay: MatchPlay) {
val job = launch(context = Android, start = CoroutineStart.LAZY) {
val strongContext = weakContext.get() ?: return@launch
val database = DatabaseHelper.getInstance(strongContext).writableDatabase
database.beginTransaction()
try {
writeMatchPlayToDatabase(database, matchPlay)
database.setTransactionSuccessful()
} catch (ex: Exception) {
Log.e(TAG, "Fatal error. Game could not save.")
throw ex
} finally {
database.endTransaction()
}
}
saveQueue.offer(job)
launchSaviourProcessor()
}
fun saveGame(weakContext: WeakReference<Context>, game: Game) {
val job = launch(context = Android, start = CoroutineStart.LAZY) {
val strongContext = weakContext.get() ?: return@launch
val database = DatabaseHelper.getInstance(strongContext).writableDatabase
database.beginTransaction()
try {
val values = ContentValues().apply {
put(GameEntry.COLUMN_SCORE, game.score)
put(GameEntry.COLUMN_IS_LOCKED, game.isLocked)
put(GameEntry.COLUMN_IS_MANUAL, game.isManual)
}
database.update(GameEntry.TABLE_NAME,
values,
"${GameEntry._ID}=?",
arrayOf(game.id.toString()))
for (frame in game.frames) {
writeFrameToDatabase(database, frame)
}
writeMatchPlayToDatabase(database, game.matchPlay)
database.setTransactionSuccessful()
} catch (ex: Exception) {
Log.e(TAG, "Fatal error. Game could not save.")
throw ex
} finally {
database.endTransaction()
}
}
saveQueue.offer(job)
launchSaviourProcessor()
}
// MARK: Private functions
private fun launchSaviourProcessor() {
if (saviourIsRunning.get()) {
return
}
saviourIsRunning.set(true)
launch(CommonPool) {
while (App.isRunning.get() || saveQueue.isNotEmpty()) {
val saveRoutine = saveQueue.poll()
if (!saveRoutine.isCompleted && !saveRoutine.isCancelled) {
saveRoutine.join()
} else {
Log.e(TAG, "Saviour thread already processed - $saveRoutine")
}
}
saviourIsRunning.set(false)
}
}
private fun writeFrameToDatabase(database: SQLiteDatabase, frame: Frame) {
val values = ContentValues().apply {
for (i in 0 until Frame.NUMBER_OF_BALLS) {
put(FrameEntry.COLUMN_PIN_STATE[i], frame.pinState[i].toInt())
}
put(FrameEntry.COLUMN_IS_ACCESSED, if (frame.isAccessed) 1 else 0)
put(FrameEntry.COLUMN_FOULS, frame.dbFouls)
}
database.update(FrameEntry.TABLE_NAME,
values,
"${FrameEntry._ID}=?",
arrayOf(frame.id.toString()))
}
private fun writeMatchPlayToDatabase(database: SQLiteDatabase, matchPlay: MatchPlay) {
// Save the match play result to the game
var values = ContentValues()
values.put(GameEntry.COLUMN_MATCH_PLAY, matchPlay.result.ordinal)
database.update(GameEntry.TABLE_NAME,
values,
"${GameEntry._ID}=?",
arrayOf(matchPlay.gameId.toString()))
// Save the match play details
values = ContentValues().apply {
put(MatchPlayEntry.COLUMN_GAME_ID, matchPlay.gameId)
put(MatchPlayEntry.COLUMN_OPPONENT_NAME, matchPlay.opponentName)
put(MatchPlayEntry.COLUMN_OPPONENT_SCORE, matchPlay.opponentScore)
}
/*
* Due to the way this method was originally implemented, when match play results were updated,
* often the wrong row in the table was altered. This bug prevented users from saving match play
* results under certain circumstances. This has been fixed, but the old data cannot be safely
* removed all at once, without potentially deleting some of the user's real data. As a fix, when
* a user now saves match play results, any old results for *only that game* are deleted, and the
* new results are inserted, as seen below.
*/
database.delete(MatchPlayEntry.TABLE_NAME,
"${MatchPlayEntry.COLUMN_GAME_ID}=?",
arrayOf(matchPlay.gameId.toString()))
database.insert(MatchPlayEntry.TABLE_NAME,
null,
values)
}
}
|
mit
|
256d520fe9a9ac1b8a4e781c19e62746
| 35.953917 | 105 | 0.612421 | 4.94085 | false | false | false | false |
tarsjoris/Sudoku
|
src/com/tjoris/sudoku/Field.kt
|
1
|
1144
|
package com.tjoris.sudoku
open class Field(private val length: Int, private val conversion : Conversion) {
protected val cells = Array(length * length) { Cell() }
constructor(field : Field) : this(field.length, field.conversion){
this.cells.forEachIndexed { i, cell ->
cell.value = field.cells[i].value
}
}
fun print() {
val size = Math.sqrt(this.length.toDouble()).toInt()
printSeparator(size)
this.cells.forEachIndexed { i, cell ->
if (i % size == 0) {
print('|')
}
if (i > 0 && i % this.length == 0) {
println()
if (i % (size * this.length) == 0) {
printSeparator(size)
}
print('|')
}
print(this.conversion.serialize(cell))
}
println('|')
printSeparator(size)
}
private fun printSeparator(size: Int) {
for (i in 0 until size) {
print('+')
for (j in 0 until size) {
print('-')
}
}
println('+')
}
}
|
gpl-3.0
|
9c284d1dd6752114d3fb154144704169
| 26.902439 | 80 | 0.465909 | 4.383142 | false | false | false | false |
AsynkronIT/protoactor-kotlin
|
proto-router/src/main/kotlin/actor/proto/router/RoundRobinRouterState.kt
|
1
|
715
|
package actor.proto.router
import actor.proto.PID
import actor.proto.send
import java.util.concurrent.atomic.AtomicInteger
internal class RoundRobinRouterState : RouterState() {
private var currentIndex: AtomicInteger = AtomicInteger(0)
private lateinit var routees: Set<PID>
private lateinit var values: Array<PID>
override fun getRoutees(): Set<PID> {
return routees
}
override fun setRoutees(routees: Set<PID>) {
this.routees = routees
values = routees.toTypedArray()
}
override fun routeMessage(message: Any) {
val v = values
val i = currentIndex.getAndIncrement() % v.count()
val pid = v[i]
send(pid,message)
}
}
|
apache-2.0
|
5e3d45a31f682f5dde61c1dc897ab16f
| 25.481481 | 62 | 0.672727 | 4.039548 | false | false | false | false |
nickthecoder/tickle
|
tickle-editor/src/main/kotlin/uk/co/nickthecoder/tickle/editor/tabs/EditorPreferencesTab.kt
|
1
|
2764
|
/*
Tickle
Copyright (C) 2017 Nick Robinson
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 uk.co.nickthecoder.tickle.editor.tabs
import uk.co.nickthecoder.paratask.AbstractTask
import uk.co.nickthecoder.paratask.TaskDescription
import uk.co.nickthecoder.paratask.parameters.*
import uk.co.nickthecoder.tickle.EditorPreferences
import uk.co.nickthecoder.tickle.editor.util.ClassLister
import uk.co.nickthecoder.tickle.resources.Resources
class EditorPreferencesTab
: EditTaskTab(
EditorPreferencesTask(Resources.instance.preferences),
dataName = "Editor Preferences",
data = Resources.instance.preferences,
graphicName = "preferences.png") {
}
class EditorPreferencesTask(val editorPreferences: EditorPreferences) : AbstractTask() {
val treeThumbnailSizeP = IntParameter("treeThumbnailSize", value = editorPreferences.treeThumnailSize)
val costumePickerSizeP = IntParameter("costumePickerThumbnailSize", value = editorPreferences.costumePickerThumbnailSize)
val packageInfoP = InformationParameter("packageInfo", information = "The top level packages used by your game. This is used to scan the code for Producer, Director and Role classes.")
val packagesP = MultipleParameter("packages", label = "Packages", value = editorPreferences.packages.toMutableList()) {
StringParameter("package")
}
val packagesGroupP = SimpleGroupParameter("packagesGroup", label = "Packages")
.addParameters(packageInfoP, packagesP)
val outputFormatP = ChoiceParameter<EditorPreferences.JsonFormat>("outputFormat", value = editorPreferences.outputFormat)
.enumChoices(true)
override val taskD = TaskDescription("editGameInfo")
.addParameters(treeThumbnailSizeP, costumePickerSizeP, packagesGroupP, outputFormatP)
override fun run() {
ClassLister.packages(packagesP.value)
with(editorPreferences) {
packages.clear()
packages.addAll(packagesP.value)
treeThumnailSize = treeThumbnailSizeP.value!!
costumePickerThumbnailSize = costumePickerSizeP.value!!
outputFormat = outputFormatP.value!!
}
}
}
|
gpl-3.0
|
aff77faeec75bdc59910b988892523ad
| 39.057971 | 188 | 0.75398 | 4.661046 | false | false | false | false |
ajalt/clikt
|
clikt/src/jvmMain/kotlin/com/github/ajalt/clikt/output/EditorJVM.kt
|
1
|
2749
|
package com.github.ajalt.clikt.output
import com.github.ajalt.clikt.core.CliktError
import java.io.IOException
import java.util.concurrent.TimeUnit
internal actual fun createEditor(
editorPath: String?,
env: Map<String, String>,
requireSave: Boolean,
extension: String,
): Editor = JvmEditor(editorPath, env, requireSave, extension)
private class JvmEditor(
private val editorPath: String?,
private val env: Map<String, String>,
private val requireSave: Boolean,
private val extension: String,
) : Editor {
private fun getEditorPath(): String {
return editorPath ?: inferEditorPath { editor ->
try {
val process = ProcessBuilder(getWhichCommand(), editor).start()
process.waitFor(100, TimeUnit.MILLISECONDS) && process.exitValue() == 0
} catch (err: Exception) {
when (err) {
is IOException, is SecurityException, is InterruptedException,
is IllegalThreadStateException,
-> false
else -> throw CliktError("Error staring editor", err)
}
}
}
}
private fun getEditorCommand(): Array<String> {
return getEditorPath().trim().split(" ").toTypedArray()
}
private fun editFileWithEditor(editorCmd: Array<String>, filename: String) {
try {
val process = ProcessBuilder(*editorCmd, filename).apply {
environment() += env
inheritIO()
}.start()
val exitCode = process.waitFor()
if (exitCode != 0) throw CliktError("${editorCmd[0]}: Editing failed!")
} catch (err: Exception) {
when (err) {
is CliktError -> throw err
else -> throw CliktError("Error staring editor", err)
}
}
}
override fun editFile(filename: String) {
editFileWithEditor(getEditorCommand(), filename)
}
@Suppress("DEPRECATION") // The replacement is experimental
override fun edit(text: String): String? {
val editorCmd = getEditorCommand()
val textToEdit = normalizeEditorText(editorCmd[0], text)
val file = createTempFile(suffix = extension)
try {
file.writeText(textToEdit)
val ts = file.lastModified()
editFileWithEditor(editorCmd, file.canonicalPath)
if (requireSave && file.lastModified() == ts) {
return null
}
return file.readText().replace("\r\n", "\n")
} catch (err: Exception) {
throw CliktError("Error staring editor", err)
} finally {
file.delete()
}
}
}
|
apache-2.0
|
c5f5dd5c826a21cbb00f3a67c0f0181a
| 32.52439 | 87 | 0.580575 | 4.882771 | false | false | false | false |
xfmax/BasePedo
|
app/src/main/java/com/base/basepedo/service/StepInAcceleration.kt
|
1
|
9301
|
package com.base.basepedo.service
import android.content.Context
import android.hardware.Sensor
import android.hardware.SensorEvent
import android.hardware.SensorManager
import android.util.Log
import com.base.basepedo.base.StepMode
import com.base.basepedo.callback.StepCallBack
import com.base.basepedo.utils.CountDownTimer
import java.util.*
/**
* Created by base on 2016/8/17.
*/
class StepInAcceleration(context: Context?, stepCallBack: StepCallBack?) : StepMode(context!!, stepCallBack!!) {
private val TAG = "StepInAcceleration"
//存放三轴数据
val valueNum = 5
//用于存放计算阈值的波峰波谷差值
var tempValue = FloatArray(valueNum)
var tempCount = 0
//是否上升的标志位
var isDirectionUp = false
//持续上升次数
var continueUpCount = 0
//上一点的持续上升的次数,为了记录波峰的上升次数
var continueUpFormerCount = 0
//上一点的状态,上升还是下降
var lastStatus = false
//波峰值
var peakOfWave = 0f
//波谷值
var valleyOfWave = 0f
//此次波峰的时间
var timeOfThisPeak: Long = 0
//上次波峰的时间
var timeOfLastPeak: Long = 0
//当前的时间
var timeOfNow: Long = 0
//当前传感器的值
var gravityNew = 0f
//上次传感器的值
var gravityOld = 0f
//动态阈值需要动态的数据,这个值用于这些动态数据的阈值
val initialValue = 1.7.toFloat()
//初始阈值
var ThreadValue = 2.0.toFloat()
//初始范围
var minValue = 11f
var maxValue = 19.6f
/**
* 0-准备计时 1-计时中 2-正常计步中
*/
private var CountTimeState = 0
private var lastStep = -1
private var timer: Timer? = null
// 倒计时3.5秒,3.5秒内不会显示计步,用于屏蔽细微波动
private val duration: Long = 3500
private var time: TimeCount? = null
override fun registerSensor() {
addBasePedoListener()
}
private fun addBasePedoListener() {
// 获得传感器的类型,这里获得的类型是加速度传感器
// 此方法用来注册,只有注册过才会生效,参数:SensorEventListener的实例,Sensor的实例,更新速率
val sensor = sensorManager
?.getDefaultSensor(Sensor.TYPE_ACCELEROMETER)
// sensorManager.unregisterListener(stepDetector);
isAvailable = sensorManager!!.registerListener(this, sensor,
SensorManager.SENSOR_DELAY_UI)
if (isAvailable) {
Log.v(TAG, "加速度传感器可以使用")
} else {
Log.v(TAG, "加速度传感器无法使用")
}
}
override fun onAccuracyChanged(arg0: Sensor, arg1: Int) {}
override fun onSensorChanged(event: SensorEvent) {
val sensor = event.sensor
synchronized(this) {
if (sensor.type == Sensor.TYPE_ACCELEROMETER) {
calc_step(event)
}
}
}
@Synchronized
private fun calc_step(event: SensorEvent) {
average = Math.sqrt(Math.pow(event.values[0].toDouble(), 2.0)
+ Math.pow(event.values[1].toDouble(), 2.0) + Math.pow(event.values[2].toDouble(), 2.0)).toFloat()
detectorNewStep(average)
}
/*
* 检测步子,并开始计步
* 1.传入sersor中的数据
* 2.如果检测到了波峰,并且符合时间差以及阈值的条件,则判定为1步
* 3.符合时间差条件,波峰波谷差值大于initialValue,则将该差值纳入阈值的计算中
* */
fun detectorNewStep(values: Float) {
if (gravityOld == 0f) {
gravityOld = values
} else {
if (DetectorPeak(values, gravityOld)) {
timeOfLastPeak = timeOfThisPeak
timeOfNow = System.currentTimeMillis()
if (timeOfNow - timeOfLastPeak >= 200 && peakOfWave - valleyOfWave >= ThreadValue && timeOfNow - timeOfLastPeak <= 2000) {
timeOfThisPeak = timeOfNow
//更新界面的处理,不涉及到算法
preStep()
}
if (timeOfNow - timeOfLastPeak >= 200
&& peakOfWave - valleyOfWave >= initialValue) {
timeOfThisPeak = timeOfNow
ThreadValue = Peak_Valley_Thread(peakOfWave - valleyOfWave)
}
}
}
gravityOld = values
}
private fun preStep() {
if (CountTimeState == 0) {
// 开启计时器
time = TimeCount(duration, 700)
time!!.start()
CountTimeState = 1
Log.v(TAG, "开启计时器")
} else if (CountTimeState == 1) {
TEMP_STEP++
Log.v(TAG, "计步中 TEMP_STEP:$TEMP_STEP")
} else if (CountTimeState == 2) {
CURRENT_SETP++
if (stepCallBack != null) {
stepCallBack.Step(CURRENT_SETP)
}
}
}
/*
* 检测波峰
* 以下四个条件判断为波峰:
* 1.目前点为下降的趋势:isDirectionUp为false
* 2.之前的点为上升的趋势:lastStatus为true
* 3.到波峰为止,持续上升大于等于2次
* 4.波峰值大于1.2g,小于2g
* 记录波谷值
* 1.观察波形图,可以发现在出现步子的地方,波谷的下一个就是波峰,有比较明显的特征以及差值
* 2.所以要记录每次的波谷值,为了和下次的波峰做对比
* */
fun DetectorPeak(newValue: Float, oldValue: Float): Boolean {
lastStatus = isDirectionUp
if (newValue >= oldValue) {
isDirectionUp = true
continueUpCount++
} else {
continueUpFormerCount = continueUpCount
continueUpCount = 0
isDirectionUp = false
}
// Log.v(TAG, "oldValue:" + oldValue);
return if (!isDirectionUp && lastStatus
&& continueUpFormerCount >= 2 && oldValue >= minValue && oldValue < maxValue) {
peakOfWave = oldValue
true
} else if (!lastStatus && isDirectionUp) {
valleyOfWave = oldValue
false
} else {
false
}
}
/*
* 阈值的计算
* 1.通过波峰波谷的差值计算阈值
* 2.记录4个值,存入tempValue[]数组中
* 3.在将数组传入函数averageValue中计算阈值
* */
fun Peak_Valley_Thread(value: Float): Float {
var tempThread = ThreadValue
if (tempCount < valueNum) {
tempValue[tempCount] = value
tempCount++
} else {
tempThread = averageValue(tempValue, valueNum)
for (i in 1 until valueNum) {
tempValue[i - 1] = tempValue[i]
}
tempValue[valueNum - 1] = value
}
return tempThread
}
/*
* 梯度化阈值
* 1.计算数组的均值
* 2.通过均值将阈值梯度化在一个范围里
* */
fun averageValue(value: FloatArray, n: Int): Float {
var ave = 0f
for (i in 0 until n) {
ave += value[i]
}
ave = ave / valueNum
ave = if (ave >= 8) {
// Log.v(TAG, "超过8");
4.3.toFloat()
} else if (ave >= 7 && ave < 8) {
// Log.v(TAG, "7-8");
3.3.toFloat()
} else if (ave >= 4 && ave < 7) {
// Log.v(TAG, "4-7");
2.3.toFloat()
} else if (ave >= 3 && ave < 4) {
// Log.v(TAG, "3-4");
2.0.toFloat()
} else {
// Log.v(TAG, "else");
1.7.toFloat()
}
return ave
}
internal inner class TimeCount(millisInFuture: Long, countDownInterval: Long) : CountDownTimer(millisInFuture, countDownInterval) {
override fun onFinish() {
// 如果计时器正常结束,则开始计步
time!!.cancel()
CURRENT_SETP += TEMP_STEP
lastStep = -1
Log.v(TAG, "计时正常结束")
timer = Timer(true)
val task: TimerTask = object : TimerTask() {
override fun run() {
if (lastStep == CURRENT_SETP) {
timer!!.cancel()
CountTimeState = 0
lastStep = -1
TEMP_STEP = 0
Log.v(TAG, "停止计步:$CURRENT_SETP")
} else {
lastStep = CURRENT_SETP
}
}
}
timer!!.schedule(task, 0, 2000)
CountTimeState = 2
}
override fun onTick(millisUntilFinished: Long) {
if (lastStep == TEMP_STEP) {
Log.v(TAG, "onTick 计时停止:$TEMP_STEP")
time!!.cancel()
CountTimeState = 0
lastStep = -1
TEMP_STEP = 0
} else {
lastStep = TEMP_STEP
}
}
}
companion object {
var TEMP_STEP = 0
//用x、y、z轴三个维度算出的平均值
var average = 0f
}
}
|
apache-2.0
|
e047e5d1c1faac44dfaa5c430613aec4
| 26.824742 | 138 | 0.528961 | 3.403531 | false | false | false | false |
etesync/android
|
app/src/main/java/com/etesync/syncadapter/HttpClient.kt
|
1
|
10260
|
/*
* Copyright © 2013 – 2015 Ricki Hirner (bitfire web engineering).
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Public License v3.0
* which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/gpl.html
*/
package com.etesync.syncadapter
import android.content.Context
import android.os.Build
import android.security.KeyChain
import at.bitfire.cert4android.CustomCertManager
import com.etesync.syncadapter.log.Logger
import com.etesync.syncadapter.model.ServiceDB
import com.etesync.syncadapter.model.Settings
import okhttp3.*
import okhttp3.internal.tls.OkHostnameVerifier
import okhttp3.logging.HttpLoggingInterceptor
import java.io.File
import java.io.IOException
import java.net.InetSocketAddress
import java.net.Proxy
import java.net.Socket
import java.security.KeyStore
import java.security.Principal
import java.util.*
import java.util.concurrent.TimeUnit
import java.util.logging.Level
import javax.net.ssl.*
class HttpClient private constructor(
val okHttpClient: OkHttpClient,
private val certManager: CustomCertManager?
): AutoCloseable {
companion object {
/** max. size of disk cache (10 MB) */
const val DISK_CACHE_MAX_SIZE: Long = 10*1024*1024
/** [OkHttpClient] singleton to build all clients from */
val sharedClient: OkHttpClient = OkHttpClient.Builder()
// set timeouts
.connectTimeout(15, TimeUnit.SECONDS)
.writeTimeout(30, TimeUnit.SECONDS)
.readTimeout(120, TimeUnit.SECONDS)
// don't allow redirects by default, because it would break PROPFIND handling
.followRedirects(false)
// add User-Agent to every request
.addNetworkInterceptor(UserAgentInterceptor)
.build()
}
override fun close() {
okHttpClient.cache?.close()
certManager?.close()
}
class Builder(
val context: Context? = null,
accountSettings: AccountSettings? = null,
val logger: java.util.logging.Logger = Logger.log
) {
private var certManager: CustomCertManager? = null
private var certificateAlias: String? = null
private val orig = sharedClient.newBuilder()
init {
// add network logging, if requested
if (logger.isLoggable(Level.FINEST)) {
val loggingInterceptor = HttpLoggingInterceptor(object: HttpLoggingInterceptor.Logger {
override fun log(message: String) {
logger.finest(message)
}
})
loggingInterceptor.level = HttpLoggingInterceptor.Level.BODY
orig.addInterceptor(loggingInterceptor)
}
context?.let {
val dbHelper = ServiceDB.OpenHelper(context)
val settings = Settings(dbHelper.readableDatabase)
try {
if (settings.getBoolean(App.OVERRIDE_PROXY, false)) {
val address = InetSocketAddress(
settings.getString(App.OVERRIDE_PROXY_HOST, App.OVERRIDE_PROXY_HOST_DEFAULT),
settings.getInt(App.OVERRIDE_PROXY_PORT, App.OVERRIDE_PROXY_PORT_DEFAULT)
)
val proxy = Proxy(Proxy.Type.HTTP, address)
orig.proxy(proxy)
Logger.log.log(Level.INFO, "Using proxy", proxy)
}
} catch (e: Exception) {
Logger.log.log(Level.SEVERE, "Can't set proxy, ignoring", e)
} finally {
// dbHelper.close()
}
//if (BuildConfig.customCerts)
customCertManager(CustomCertManager(context, true,
!(settings.getBoolean(App.DISTRUST_SYSTEM_CERTIFICATES,false)), true))
dbHelper.close()
}
// use account settings for authentication
accountSettings?.let {
addAuthentication(accountSettings.uri!!.host, accountSettings.authToken)
}
}
constructor(context: Context?, host: String?, authToken: String): this(context) {
addAuthentication(host, authToken)
}
fun withDiskCache(): Builder {
val context = context ?: throw IllegalArgumentException("Context is required to find the cache directory")
for (dir in arrayOf(context.externalCacheDir, context.cacheDir).filterNotNull()) {
if (dir.exists() && dir.canWrite()) {
val cacheDir = File(dir, "HttpClient")
cacheDir.mkdir()
Logger.log.fine("Using disk cache: $cacheDir")
orig.cache(Cache(cacheDir, DISK_CACHE_MAX_SIZE))
break
}
}
return this
}
fun followRedirects(follow: Boolean): Builder {
orig.followRedirects(follow)
return this
}
fun customCertManager(manager: CustomCertManager) {
certManager = manager
}
fun setForeground(foreground: Boolean): Builder {
certManager?.appInForeground = foreground
return this
}
private fun addAuthentication(host: String?, token: String): Builder {
val authHandler = TokenAuthenticator(host, token)
orig.addNetworkInterceptor(authHandler)
return this
}
private class TokenAuthenticator internal constructor(internal val host: String?, internal val token: String?) : Interceptor {
@Throws(IOException::class)
override fun intercept(chain: Interceptor.Chain): Response {
var request = chain.request()
/* Only add to the host we want. */
if (host == null || request.url.host == host) {
if (token != null && request.header(HEADER_AUTHORIZATION) == null) {
request = request.newBuilder()
.header(HEADER_AUTHORIZATION, "Token $token")
.build()
}
}
return chain.proceed(request)
}
companion object {
protected val HEADER_AUTHORIZATION = "Authorization"
}
}
fun build(): HttpClient {
val trustManager = certManager ?: {
val factory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm())
factory.init(null as KeyStore?)
factory.trustManagers.first() as X509TrustManager
}()
val hostnameVerifier = certManager?.hostnameVerifier(OkHostnameVerifier)
?: OkHostnameVerifier
var keyManager: KeyManager? = null
certificateAlias?.let { alias ->
try {
val context = requireNotNull(context)
// get provider certificate and private key
val certs = KeyChain.getCertificateChain(context, alias) ?: return@let
val key = KeyChain.getPrivateKey(context, alias) ?: return@let
logger.fine("Using provider certificate $alias for authentication (chain length: ${certs.size})")
// create Android KeyStore (performs key operations without revealing secret data to DAVx5)
val keyStore = KeyStore.getInstance("AndroidKeyStore")
keyStore.load(null)
// create KeyManager
keyManager = object: X509ExtendedKeyManager() {
override fun getServerAliases(p0: String?, p1: Array<out Principal>?): Array<String>? = null
override fun chooseServerAlias(p0: String?, p1: Array<out Principal>?, p2: Socket?) = null
override fun getClientAliases(p0: String?, p1: Array<out Principal>?) =
arrayOf(alias)
override fun chooseClientAlias(p0: Array<out String>?, p1: Array<out Principal>?, p2: Socket?) =
alias
override fun getCertificateChain(forAlias: String?) =
certs.takeIf { forAlias == alias }
override fun getPrivateKey(forAlias: String?) =
key.takeIf { forAlias == alias }
}
// HTTP/2 doesn't support client certificates (yet)
// see https://tools.ietf.org/html/draft-ietf-httpbis-http2-secondary-certs-04
orig.protocols(listOf(Protocol.HTTP_1_1))
} catch (e: Exception) {
logger.log(Level.SEVERE, "Couldn't set up provider certificate authentication", e)
}
}
val sslContext = SSLContext.getInstance("TLS")
sslContext.init(
if (keyManager != null) arrayOf(keyManager) else null,
arrayOf(trustManager),
null)
orig.sslSocketFactory(sslContext.socketFactory, trustManager)
orig.hostnameVerifier(hostnameVerifier)
return HttpClient(orig.build(), certManager)
}
}
private object UserAgentInterceptor : Interceptor {
private val userAgent = "${App.appName}/${BuildConfig.VERSION_NAME} (okhttp3) Android/${Build.VERSION.RELEASE}"
@Throws(IOException::class)
override fun intercept(chain: Interceptor.Chain): Response {
val locale = Locale.getDefault()
val request = chain.request().newBuilder()
.header("User-Agent", userAgent)
.header("Accept-Language", locale.language + "-" + locale.country + ", " + locale.language + ";q=0.7, *;q=0.5")
.build()
return chain.proceed(request)
}
}
}
|
gpl-3.0
|
8ae4c2879063fc4ada3c5442d3b77fb5
| 38.602317 | 134 | 0.56966 | 5.295302 | false | false | false | false |
proxer/ProxerAndroid
|
src/main/kotlin/me/proxer/app/profile/info/ProfileInfoFragment.kt
|
1
|
6415
|
package me.proxer.app.profile.info
import android.os.Bundle
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.core.os.bundleOf
import androidx.core.view.isGone
import androidx.core.view.isVisible
import com.gojuno.koptional.rxjava2.filterSome
import com.gojuno.koptional.toOptional
import com.uber.autodispose.android.lifecycle.scope
import com.uber.autodispose.autoDisposable
import kotterknife.bindView
import me.proxer.app.R
import me.proxer.app.base.BaseContentFragment
import me.proxer.app.forum.TopicActivity
import me.proxer.app.profile.ProfileActivity
import me.proxer.app.profile.ProfileViewModel
import me.proxer.app.profile.ProfileViewModel.UserInfoWrapper
import me.proxer.app.util.extension.distanceInWordsToNow
import me.proxer.app.util.extension.linkClicks
import me.proxer.app.util.extension.linkify
import me.proxer.app.util.extension.toPrefixedUrlOrNull
import org.koin.androidx.viewmodel.ext.android.sharedViewModel
import org.koin.core.parameter.parametersOf
/**
* @author Ruben Gees
*/
class ProfileInfoFragment : BaseContentFragment<UserInfoWrapper>(R.layout.fragment_profile) {
companion object {
private const val RANK_FORUM_ID = "207664"
private const val RANK_FORUM_CATEGORY_ID = "79"
private const val RANK_FORUM_TOPIC = "Rangpunkte und Ränge"
private const val DATE_FORMAT = "%.1f"
private val rankRegex = Regex(".+", RegexOption.DOT_MATCHES_ALL)
fun newInstance() = ProfileInfoFragment().apply {
arguments = bundleOf()
}
}
override val hostingActivity: ProfileActivity
get() = activity as ProfileActivity
override val viewModel by sharedViewModel<ProfileViewModel> {
parametersOf(userId, username)
}
private val userId: String?
get() = hostingActivity.userId
private val username: String?
get() = hostingActivity.username
private val animePointsRow: TextView by bindView(R.id.animePointsRow)
private val mangaPointsRow: TextView by bindView(R.id.mangaPointsRow)
private val uploadPointsRow: TextView by bindView(R.id.uploadPointsRow)
private val forumPointsRow: TextView by bindView(R.id.forumPointsRow)
private val infoPointsRow: TextView by bindView(R.id.infoPointsRow)
private val miscellaneousPointsRow: TextView by bindView(R.id.miscellaneousPointsRow)
private val totalPointsRow: TextView by bindView(R.id.totalPointsRow)
private val rank: TextView by bindView(R.id.rank)
private val statusContainer: ViewGroup by bindView(R.id.statusContainer)
private val statusText: TextView by bindView(R.id.statusText)
private val watchedEpisodesContainer: ViewGroup by bindView(R.id.watchedEpisodesContainer)
private val episodesRow: TextView by bindView(R.id.episodesRow)
private val minutesRow: TextView by bindView(R.id.minutesRow)
private val hoursRow: TextView by bindView(R.id.hoursRow)
private val daysRow: TextView by bindView(R.id.daysRow)
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
statusText.linkClicks()
.map { it.toPrefixedUrlOrNull().toOptional() }
.filterSome()
.autoDisposable(viewLifecycleOwner.scope())
.subscribe { showPage(it) }
rank.linkClicks()
.autoDisposable(viewLifecycleOwner.scope())
.subscribe {
TopicActivity.navigateTo(requireActivity(), RANK_FORUM_ID, RANK_FORUM_CATEGORY_ID, RANK_FORUM_TOPIC)
}
}
override fun showData(data: UserInfoWrapper) {
super.showData(data)
val (userInfo, watchedEpisodes) = data
val totalPoints = userInfo.animePoints + userInfo.mangaPoints + userInfo.uploadPoints +
userInfo.forumPoints + userInfo.infoPoints + userInfo.miscPoints
animePointsRow.text = userInfo.animePoints.toString()
mangaPointsRow.text = userInfo.mangaPoints.toString()
uploadPointsRow.text = userInfo.uploadPoints.toString()
forumPointsRow.text = userInfo.forumPoints.toString()
infoPointsRow.text = userInfo.infoPoints.toString()
miscellaneousPointsRow.text = userInfo.miscPoints.toString()
totalPointsRow.text = totalPoints.toString()
rank.text = rankToString(totalPoints).linkify(web = false, mentions = false, custom = arrayOf(rankRegex))
if (userInfo.status.isBlank()) {
statusContainer.isGone = true
} else {
val rawText = userInfo.status + " - " + userInfo.lastStatusChange.distanceInWordsToNow(requireContext())
statusText.text = rawText.linkify(mentions = false)
}
if (watchedEpisodes != null) {
val minutes = watchedEpisodes * 20
val hours = minutes / 60f
val days = hours / 24f
watchedEpisodesContainer.isVisible = true
episodesRow.text = watchedEpisodes.toString()
minutesRow.text = minutes.toString()
hoursRow.text = DATE_FORMAT.format(hours)
daysRow.text = DATE_FORMAT.format(days)
} else {
watchedEpisodesContainer.isVisible = false
}
}
private fun rankToString(points: Int) = requireContext().getString(
when {
points < 10 -> R.string.rank_10
points < 100 -> R.string.rank_100
points < 200 -> R.string.rank_200
points < 500 -> R.string.rank_500
points < 700 -> R.string.rank_700
points < 1_000 -> R.string.rank_1000
points < 1_500 -> R.string.rank_1500
points < 2_000 -> R.string.rank_2000
points < 3_000 -> R.string.rank_3000
points < 4_000 -> R.string.rank_4000
points < 6_000 -> R.string.rank_6000
points < 8_000 -> R.string.rank_8000
points < 10_000 -> R.string.rank_10000
points < 11_000 -> R.string.rank_11000
points < 12_000 -> R.string.rank_12000
points < 14_000 -> R.string.rank_14000
points < 16_000 -> R.string.rank_16000
points < 18_000 -> R.string.rank_18000
points < 20_000 -> R.string.rank_20000
points > 20_000 -> R.string.rank_kami_sama
else -> error("Illegal rank: $points")
}
)
}
|
gpl-3.0
|
f88c11ed5be6a40954d66deb1f858a11
| 39.594937 | 116 | 0.68101 | 4.244871 | false | false | false | false |
eugeis/ee
|
ee-lang/src/main/kotlin/ee/lang/gen/java/LangJavaUtils.kt
|
1
|
1226
|
package ee.lang.gen.java
import ee.lang.ExternalType
import ee.lang.StructureUnit
import ee.lang.Type
object j : StructureUnit({ namespace("java").name("Java") }) {
object util : StructureUnit() {
val Date = Type()
object concurrent : StructureUnit() {
val TimeUnit = Type()
}
}
object net : StructureUnit() {
val URL = Type()
}
object nio : StructureUnit() {
object file : StructureUnit() {
val Path = Type()
val Paths = Type()
}
}
}
object junit : StructureUnit({ namespace("org.junit.jupiter.api").name("JUnit5") }) {
val Test = ExternalType()
object Assertions : StructureUnit() {
val assertEquals = ExternalType()
}
}
object jackson : StructureUnit({ namespace("com.fasterxml.jackson") }) {
object json : StructureUnit({ namespace("com.fasterxml.jackson.annotation") }) {
object JsonProperty : ExternalType()
object JsonValue : ExternalType()
}
object xml : StructureUnit({ namespace("com.fasterxml.jackson.dataformat.xml.annotation") }) {
object JacksonXmlProperty : ExternalType()
object JacksonXmlElementWrapper : ExternalType()
}
}
|
apache-2.0
|
556440cf714275afa0f1229b3697c774
| 25.106383 | 98 | 0.622349 | 4.362989 | false | false | false | false |
KarlNosworthy/dagger_two_example
|
app/src/main/java/com/karlnosworthy/examples/daggerv2/reporting/ActivityEntryReporter.kt
|
1
|
902
|
package com.karlnosworthy.examples.daggerv2.reporting
import android.app.Activity
class ActivityEntryReporter {
private var activityEntryStats: MutableMap<String, Int>
init {
activityEntryStats = mutableMapOf()
}
fun reportActivityEntry(activity: Activity) {
var activityEntryCount = 0
val activityName = getActivityName(activity)
if (activityEntryStats.containsKey(activityName)) {
activityEntryCount = activityEntryStats[activityName] ?: 0
}
activityEntryCount += 1
activityEntryStats[activityName] = activityEntryCount
}
fun getEntryCount(activity: Activity): Int {
val activityName = getActivityName(activity)
return activityEntryStats[activityName] ?: 0
}
private fun getActivityName(activity: Activity): String {
return activity::class.java.simpleName
}
}
|
apache-2.0
|
595c818aa622ed024e72f60b26527c67
| 24.055556 | 70 | 0.694013 | 4.983425 | false | false | false | false |
ragnraok/MovieCamera
|
app/src/main/java/com/ragnarok/moviecamera/ui/ImageListAdapter.kt
|
1
|
2906
|
package com.ragnarok.moviecamera.ui
import android.support.v7.widget.CardView
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.MotionEvent
import android.view.View
import android.view.ViewGroup
import android.view.animation.OvershootInterpolator
import android.widget.ImageView
import com.ragnarok.moviecamera.R
/**
* Created by ragnarok on 15/6/20.
*/
class ImageListAdapter(var context: MainUI): RecyclerView.Adapter<RecyclerView.ViewHolder>() {
val TAG: String = "MovieCamera.ImageListAdapter"
var itemCounts = 0
var lastAnimatedPosition = -1
override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): RecyclerView.ViewHolder? {
var view = LayoutInflater.from(context).inflate(R.layout.image_item_layout, parent, false)
val result = ImageListViewHolder(view)
return result
}
override fun onBindViewHolder(holder: RecyclerView.ViewHolder?, position: Int) {
holder?.getItemViewType()
startItemInitAnim(holder?.itemView, position)
}
private fun startItemInitAnim(view: View?, position: Int) {
if (position> lastAnimatedPosition) {
lastAnimatedPosition = position
view?.setScaleX(0.5f)
view?.setScaleY(0.5f)
if (view != null) {
view.animate().scaleX(1.0f).scaleY(1.0f).setInterpolator(OvershootInterpolator()).setDuration(200)
}
}
}
override fun getItemCount(): Int {
return itemCounts;
}
public fun updateItems() {
itemCounts = 10
notifyDataSetChanged()
}
class ImageListViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView), View.OnTouchListener, View.OnClickListener {
var cardView: CardView? = null
var imageView: ImageView? = null
var clickLocationX = -1
var clickLocationY = -1
init {
cardView = itemView.findViewById(R.id.image_cardview) as CardView
imageView = itemView.findViewById(R.id.image) as ImageView
cardView?.setOnTouchListener(this)
cardView?.setOnClickListener(this)
}
override fun onTouch(v: View?, event: MotionEvent): Boolean {
if (v?.getId() == R.id.image_cardview && event.getAction() == MotionEvent.ACTION_UP) {
clickLocationX = event.getX().toInt()
clickLocationY = event.getY().toInt()
}
return false;
}
override fun onClick(v: View) {
if (v.getId() == R.id.image_cardview) {
if (clickLocationX >=0 && clickLocationY >= 0) {
clickLocationX = -1
clickLocationY = -1
}
}
}
}
}
|
mit
|
160b64bb7e4c0672e036932b39cbb54b
| 30.258065 | 127 | 0.608052 | 4.612698 | false | false | false | false |
danrien/projectBlue
|
projectBlueWater/src/main/java/com/lasthopesoftware/bluewater/settings/repository/ApplicationSettings.kt
|
2
|
338
|
package com.lasthopesoftware.bluewater.settings.repository
import androidx.annotation.Keep
@Keep
data class ApplicationSettings(
var isSyncOnWifiOnly: Boolean = false,
var isSyncOnPowerOnly: Boolean = false,
var isVolumeLevelingEnabled: Boolean = false,
var playbackEngineTypeName: String? = null,
var chosenLibraryId: Int = -1,
)
|
lgpl-3.0
|
14a9132cecb61befceff5954a853d3c7
| 27.166667 | 58 | 0.801775 | 3.930233 | false | false | false | false |
ruuvi/Android_RuuvitagScanner
|
app/src/main/java/com/ruuvi/station/settings/domain/AppSettingsInteractor.kt
|
1
|
4041
|
package com.ruuvi.station.settings.domain
import com.google.gson.JsonObject
import com.koushikdutta.async.future.FutureCallback
import com.koushikdutta.ion.Response
import com.ruuvi.station.app.locale.LocaleType
import com.ruuvi.station.app.preferences.PreferencesRepository
import com.ruuvi.station.gateway.GatewaySender
import com.ruuvi.station.units.domain.UnitsConverter
import com.ruuvi.station.units.model.HumidityUnit
import com.ruuvi.station.units.model.PressureUnit
import com.ruuvi.station.units.model.TemperatureUnit
import com.ruuvi.station.util.BackgroundScanModes
class AppSettingsInteractor(
private val preferencesRepository: PreferencesRepository,
private val gatewaySender: GatewaySender,
private val unitsConverter: UnitsConverter
) {
fun getTemperatureUnit(): TemperatureUnit =
preferencesRepository.getTemperatureUnit()
fun setTemperatureUnit(unit: TemperatureUnit) =
preferencesRepository.setTemperatureUnit(unit)
fun getHumidityUnit(): HumidityUnit =
preferencesRepository.getHumidityUnit()
fun setHumidityUnit(unit: HumidityUnit) =
preferencesRepository.setHumidityUnit(unit)
fun getGatewayUrl(): String =
preferencesRepository.getGatewayUrl()
fun setGatewayUrl(gatewayUrl: String) {
preferencesRepository.setGatewayUrl(gatewayUrl)
}
fun getDeviceId(): String =
preferencesRepository.getDeviceId()
fun setDeviceId(deviceId: String) {
preferencesRepository.setDeviceId(deviceId)
}
fun isServiceWakeLock(): Boolean =
preferencesRepository.isServiceWakelock()
fun setIsServiceWakeLock(isLocked: Boolean) =
preferencesRepository.setIsServiceWakeLock(isLocked)
fun saveUrlAndDeviceId(url: String, deviceId: String) =
preferencesRepository.saveUrlAndDeviceId(url, deviceId)
fun getBackgroundScanMode(): BackgroundScanModes =
preferencesRepository.getBackgroundScanMode()
fun setBackgroundScanMode(mode: BackgroundScanModes) =
preferencesRepository.setBackgroundScanMode(mode)
fun isDashboardEnabled(): Boolean =
preferencesRepository.isDashboardEnabled()
fun setIsDashboardEnabled(isEnabled: Boolean) =
preferencesRepository.setIsDashboardEnabled(isEnabled)
fun getBackgroundScanInterval(): Int =
preferencesRepository.getBackgroundScanInterval()
fun setBackgroundScanInterval(interval: Int) =
preferencesRepository.setBackgroundScanInterval(interval)
fun isShowAllGraphPoint(): Boolean =
preferencesRepository.isShowAllGraphPoint()
fun setIsShowAllGraphPoint(isShow: Boolean) =
preferencesRepository.setIsShowAllGraphPoint(isShow)
fun graphDrawDots(): Boolean =
preferencesRepository.graphDrawDots()
fun setGraphDrawDots(isDrawDots: Boolean) =
preferencesRepository.setGraphDrawDots(isDrawDots)
fun getGraphPointInterval(): Int =
preferencesRepository.getGraphPointInterval()
fun setGraphPointInterval(newInterval: Int) =
preferencesRepository.setGraphPointInterval(newInterval)
fun getGraphViewPeriod(): Int =
preferencesRepository.getGraphViewPeriodDays()
fun setGraphViewPeriod(newPeriod: Int) =
preferencesRepository.setGraphViewPeriodDays(newPeriod)
fun testGateway(
gatewayUrl: String,
deviceId: String,
callback: FutureCallback<Response<JsonObject>>
) = gatewaySender.test(gatewayUrl, deviceId, callback)
fun getAllPressureUnits(): Array<PressureUnit> = unitsConverter.getAllPressureUnits()
fun getPressureUnit(): PressureUnit = unitsConverter.getPressureUnit()
fun setPressureUnit(unit: PressureUnit) {
preferencesRepository.setPressureUnit(unit)
}
fun getAllTemperatureUnits(): Array<TemperatureUnit> = unitsConverter.getAllTemperatureUnits()
fun getAllHumidityUnits(): Array<HumidityUnit> = unitsConverter.getAllHumidityUnits()
fun getAllLocales(): Array<LocaleType> = LocaleType.values()
}
|
mit
|
2e94eca6f089f8c031969d8ad55f7d2c
| 33.547009 | 98 | 0.766147 | 4.782249 | false | false | false | false |
ngageoint/mage-android
|
mage/src/main/java/mil/nga/giat/mage/observation/attachment/AttachmentViewScreen.kt
|
1
|
7283
|
package mil.nga.giat.mage.observation.attachment
import android.net.Uri
import android.widget.MediaController
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.*
import androidx.compose.material.*
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ArrowBack
import androidx.compose.material.icons.filled.Share
import androidx.compose.material.icons.filled.VisibilityOff
import androidx.compose.runtime.*
import androidx.compose.runtime.livedata.observeAsState
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.toArgb
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.compose.ui.viewinterop.AndroidView
import androidx.swiperefreshlayout.widget.CircularProgressDrawable
import com.google.accompanist.glide.rememberGlidePainter
import com.google.android.exoplayer2.ExoPlayer
import com.google.android.exoplayer2.MediaItem
import com.google.android.exoplayer2.source.ProgressiveMediaSource
import com.google.android.exoplayer2.ui.PlayerView
import com.google.android.exoplayer2.ui.StyledPlayerView
import com.google.android.exoplayer2.upstream.DataSource
import com.google.android.exoplayer2.upstream.DefaultDataSource
import com.google.android.exoplayer2.upstream.DefaultDataSourceFactory
import com.google.android.exoplayer2.util.Util
import mil.nga.giat.mage.ui.theme.MageTheme
import mil.nga.giat.mage.ui.theme.topAppBarBackground
@Composable
fun AttachmentViewScreen(
viewModel: AttachmentViewModel,
onShare: () -> Unit,
onClose: () -> Unit,
onOpen: () -> Unit,
onCancelDownload: () -> Unit
) {
val attachmentState by viewModel.attachmentUri.observeAsState()
val downloadProgress by viewModel.downloadProgress.observeAsState()
MageTheme {
Scaffold(
topBar = {
TopBar(
onShare = onShare,
onClose = onClose
)
},
content = {
attachmentState?.let { AttachmentContent(it, onOpen) }
}
)
DownloadDialog(downloadProgress) {
onCancelDownload()
}
}
}
@Composable
private fun DownloadDialog(
progress: Float?,
onCancel: () -> Unit
) {
if (progress != null) {
AlertDialog(
onDismissRequest = {
onCancel()
},
title = {
Text(
text = "Downloading Attachment",
style = MaterialTheme.typography.h6,
)
},
text = {
Column(Modifier.padding(horizontal = 16.dp)) {
LinearProgressIndicator(
progress = progress
)
}
},
buttons = {
Row(
horizontalArrangement = Arrangement.End,
modifier = Modifier
.fillMaxWidth()
.padding(end = 16.dp)
) {
TextButton(
onClick = { onCancel() }
) {
Text("Cancel")
}
}
}
)
}
}
@Composable
private fun TopBar(
onShare: () -> Unit,
onClose: () -> Unit
) {
TopAppBar(
backgroundColor = MaterialTheme.colors.topAppBarBackground,
contentColor = Color.White,
title = { Text("Observation Attachment") },
navigationIcon = {
IconButton(onClick = { onClose.invoke() }) {
Icon(Icons.Default.ArrowBack, "Cancel Edit")
}
},
actions = {
IconButton(
onClick = onShare,
) {
Icon(
imageVector = Icons.Default.Share,
contentDescription = "Share Attachment",
tint = Color.White
)
}
}
)
}
@Composable
private fun AttachmentContent(
state: AttachmentState,
onOpen: () -> Unit
) {
when (state) {
is AttachmentState.ImageState -> AttachmentImageContent(state)
is AttachmentState.MediaState -> AttachmentMediaContent(state)
is AttachmentState.OtherState -> AttachmentOtherContent(state, onOpen)
}
}
@Composable
private fun AttachmentImageContent(state: AttachmentState.ImageState) {
val progress = CircularProgressDrawable(LocalContext.current)
progress.strokeWidth = 10f
progress.centerRadius = 80f
progress.setColorSchemeColors(MaterialTheme.colors.primary.toArgb())
progress.setTint(MaterialTheme.colors.primary.toArgb())
progress.start()
Box(
Modifier
.fillMaxWidth()
.background(Color(0x19000000))
) {
Image(
painter = rememberGlidePainter(
state.model,
fadeIn = true,
requestBuilder = {
placeholder(progress)
}
),
contentDescription = "Image",
Modifier.fillMaxSize()
)
}
}
@Composable
private fun AttachmentMediaContent(
state: AttachmentState.MediaState,
) {
Column(
Modifier.fillMaxSize(),
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Center
) {
val context = LocalContext.current
val exoPlayer = remember(context) {
ExoPlayer.Builder(context).build().apply {
setMediaItem(MediaItem.fromUri(state.uri))
prepare()
}
}
AndroidView(factory = { context ->
StyledPlayerView(context).apply {
setShowBuffering(StyledPlayerView.SHOW_BUFFERING_ALWAYS)
player = exoPlayer
}
})
}
}
@Composable
private fun AttachmentOtherContent(
state: AttachmentState.OtherState,
onOpen: () -> Unit
) {
Column(
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally,
modifier = Modifier
.fillMaxSize()
.padding(16.dp)
) {
CompositionLocalProvider(LocalContentAlpha provides ContentAlpha.medium) {
Icon(
imageVector = Icons.Default.VisibilityOff,
contentDescription = "Media Icon",
tint = MaterialTheme.colors.primary.copy(LocalContentAlpha.current),
modifier = Modifier
.height(164.dp)
.width(164.dp)
.padding(bottom = 16.dp)
)
}
CompositionLocalProvider(LocalContentAlpha provides ContentAlpha.medium) {
Text(
text = "Preview Not Available",
textAlign = TextAlign.Center,
style = MaterialTheme.typography.h5,
modifier = Modifier.padding(bottom = 8.dp),
)
Text(
text = "You may be able to view this content in another application",
textAlign = TextAlign.Center,
style = MaterialTheme.typography.subtitle2,
modifier = Modifier.padding(bottom = 32.dp)
)
}
OutlinedButton(
modifier = Modifier
.fillMaxWidth()
.padding(16.dp),
onClick = {
onOpen.invoke()
}
) {
Text(text = "OPEN WITH")
}
}
}
|
apache-2.0
|
55a7b2faca9e1ce72a1f50d2696aeb3f
| 27.453125 | 81 | 0.625566 | 4.855333 | false | false | false | false |
Shopify/mobile-buy-sdk-android
|
MobileBuy/buy3/src/test/java/com/shopify/buy3/GraphClientTest.kt
|
1
|
10844
|
/*
* The MIT License (MIT)
*
* Copyright (c) 2015 Shopify Inc.
*
* 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.shopify.buy3
import android.content.Context
import android.os.Handler
import com.google.common.truth.Truth.assertThat
import com.nhaarman.mockito_kotlin.any
import com.nhaarman.mockito_kotlin.doAnswer
import com.nhaarman.mockito_kotlin.doReturn
import com.nhaarman.mockito_kotlin.mock
import com.nhaarman.mockito_kotlin.whenever
import okhttp3.OkHttpClient
import okhttp3.mockwebserver.MockResponse
import okhttp3.mockwebserver.MockWebServer
import org.intellij.lang.annotations.Language
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.Mock
import org.mockito.junit.MockitoJUnitRunner
import java.net.SocketTimeoutException
import java.util.concurrent.TimeUnit
import java.util.concurrent.atomic.AtomicBoolean
import java.util.concurrent.atomic.AtomicReference
private const val PACKAGE_NAME = "com.shopify.buy3.test"
@RunWith(MockitoJUnitRunner::class)
class GraphClientTest {
private val server = MockWebServer()
@Mock lateinit var mockContext: Context
private lateinit var graphClient: GraphClient
@Before fun setUp() {
doReturn(PACKAGE_NAME).whenever(mockContext).getPackageName()
val okHttpClient = OkHttpClient.Builder()
.connectTimeout(1, TimeUnit.SECONDS)
.readTimeout(1, TimeUnit.SECONDS)
.build()
graphClient = GraphClient.build(context = mockContext, shopDomain = "shopDomain", accessToken = "accessToken", configure = {
httpClient = okHttpClient
endpointUrl = server.url("/")
})
}
@Test fun httpRequestHeaders() {
server.enqueueShopNameResponse()
val result = graphClient.fetchShopName()
assertThat(result).isInstanceOf(GraphCallResult.Success::class.java)
with(server.takeRequest()) {
assertThat(headers["Accept"]).isEqualTo("application/json")
assertThat(headers["User-Agent"]).isEqualTo("Mobile Buy SDK Android/${BuildConfig.BUY_SDK_VERSION}/$PACKAGE_NAME")
assertThat(headers["X-SDK-Version"]).isEqualTo(BuildConfig.BUY_SDK_VERSION)
assertThat(headers["X-SDK-Variant"]).isEqualTo("android")
assertThat(headers["X-Shopify-Storefront-Access-Token"]).isEqualTo("accessToken")
assertThat(this.body.readUtf8()).isEqualTo("query {shop{id,name}}")
}
}
@Test fun graphResponse() {
server.enqueueShopNameResponse()
val result = graphClient.fetchShopName()
assertThat(result).isInstanceOf(GraphCallResult.Success::class.java)
with(result as GraphCallResult.Success) {
assertThat(response.data!!.shop.name).isEqualTo("MyShop")
assertThat(response.errors).isEmpty()
assertThat(response.hasErrors).isFalse()
}
}
@Test fun graphResponseWithLocale() {
server.enqueueShopNameResponse()
val okHttpClient = OkHttpClient.Builder()
.connectTimeout(1, TimeUnit.SECONDS)
.readTimeout(1, TimeUnit.SECONDS)
.build()
graphClient = GraphClient.build(context = mockContext, shopDomain = "shopDomain", accessToken = "accessToken", configure = {
httpClient = okHttpClient
endpointUrl = server.url("/")
}, locale = "fr")
val result = graphClient.fetchShopName()
assertThat(result).isInstanceOf(GraphCallResult.Success::class.java)
with(result as GraphCallResult.Success) {
assertThat(response.data!!.shop.name).isEqualTo("MyShop")
assertThat(response.errors).isEmpty()
assertThat(response.hasErrors).isFalse()
}
}
@Test fun graphResponseErrors() {
server.enqueueGraphErrorResponse()
val result = graphClient.fetchShopName()
assertThat(result).isInstanceOf(GraphCallResult.Success::class.java)
with(result as GraphCallResult.Success) {
assertThat(response.data).isNull()
assertThat(response.errors).isNotEmpty()
assertThat(response.hasErrors).isTrue()
assertThat(response.formattedErrorMessage).isEqualTo("Field 'names' doesn't exist on type 'Shop'")
}
}
@Test fun httpResponseError() {
server.enqueue(MockResponse().setResponseCode(401).setBody("Unauthorized request!"))
val result = graphClient.fetchShopName()
assertThat(result).isInstanceOf(GraphCallResult.Failure::class.java)
with(result as GraphCallResult.Failure) {
assertThat(error).isInstanceOf(GraphError.HttpError::class.java)
with(error as GraphError.HttpError) {
assertThat(statusCode).isEqualTo(401)
assertThat(message).isEqualTo("HTTP(401) Client Error")
}
}
}
@Test fun networkError() {
val result = graphClient.fetchShopName()
assertThat(result).isInstanceOf(GraphCallResult.Failure::class.java)
with(result as GraphCallResult.Failure) {
assertThat(error).isInstanceOf(GraphError.NetworkError::class.java)
with(error as GraphError.NetworkError) {
assertThat(cause).isInstanceOf(SocketTimeoutException::class.java)
}
}
}
@Test fun parseError() {
server.enqueue(MockResponse().setBody("Noise"))
val result = graphClient.fetchShopName()
assertThat(result).isInstanceOf(GraphCallResult.Failure::class.java)
with(result as GraphCallResult.Failure) {
assertThat(error).isInstanceOf(GraphError.ParseError::class.java)
with(error as GraphError.ParseError) {
assertThat(message).isEqualTo("Failed to parse GraphQL http response")
}
}
}
@Test fun canceledErrorBeforeExecute() {
val call = graphClient.queryGraph(Storefront.query { root -> root.shop { it.name() } })
call.cancel()
val result = AtomicReference<GraphCallResult<Storefront.QueryRoot>>()
val latch = NamedCountDownLatch("canceledErrorBeforeExecute", 1)
call.enqueue {
result.set(it)
latch.countDown()
}
latch.awaitOrThrowWithTimeout(2, TimeUnit.SECONDS)
assertThat(result.get()).isInstanceOf(GraphCallResult.Failure::class.java)
with(result.get() as GraphCallResult.Failure) {
assertThat(error).isInstanceOf(GraphError.CallCanceledError::class.java)
}
}
@Test fun canceledErrorDuringExecute() {
server.enqueueShopNameResponse(TimeUnit.SECONDS.toMillis(3))
val result = AtomicReference<GraphCallResult<Storefront.QueryRoot>>()
val latch = NamedCountDownLatch("canceledErrorDuringExecute", 1)
val call = graphClient.queryGraph(Storefront.query { root -> root.shop { it.name() } }).enqueue {
result.set(it)
latch.countDown()
}
latch.await(1, TimeUnit.SECONDS)
call.cancel()
latch.awaitOrThrowWithTimeout(1, TimeUnit.SECONDS)
assertThat(result.get()).isInstanceOf(GraphCallResult.Failure::class.java)
with(result.get() as GraphCallResult.Failure) {
assertThat(error).isInstanceOf(GraphError.CallCanceledError::class.java)
}
}
@Test fun callbackHandler() {
val deliveredInHandler = AtomicBoolean()
val handler = mock<Handler> {
on { post(any()) } doAnswer { invocation ->
deliveredInHandler.set(true)
invocation.getArgument<Runnable>(0).run()
true
}
}
server.enqueueShopNameResponse()
val result = graphClient.fetchShopName(handler)
assertThat(result).isInstanceOf(GraphCallResult.Success::class.java)
with(result as GraphCallResult.Success) {
assertThat(response.data!!.shop.name).isEqualTo("MyShop")
assertThat(response.errors).isEmpty()
assertThat(response.hasErrors).isFalse()
}
assertThat(deliveredInHandler.get()).isTrue()
}
}
private fun GraphClient.fetchShopName(handler: Handler? = null): GraphCallResult<Storefront.QueryRoot> {
val result = AtomicReference<GraphCallResult<Storefront.QueryRoot>>()
val latch = NamedCountDownLatch("getGraphCallResult", 1)
queryGraph(Storefront.query { root -> root.shop { it.name() } }).enqueue(handler) {
result.set(it)
latch.countDown()
}
latch.awaitOrThrowWithTimeout(2, TimeUnit.SECONDS)
return result.get()!!
}
private fun MockWebServer.enqueueShopNameResponse(delayMs: Long = 0) {
@Language("json") val response = """
{
"data": {
"shop" : {
"name" : "MyShop"
}
}
}
""".trimIndent()
enqueue(
MockResponse()
.setResponseCode(200)
.setBody(response)
.let { if (delayMs > 0) it.setBodyDelay(delayMs, TimeUnit.MILLISECONDS) else it }
)
}
private fun MockWebServer.enqueueGraphErrorResponse() {
@Language("json") val response = """
{
"errors": [
{
"message" : "Field 'names' doesn't exist on type 'Shop'",
"locations": [
{
"line" : 1,
"column": 7
}
],
"fields": [
"query", "shop", "names"
]
}
]
}
""".trimIndent()
enqueue(MockResponse().setResponseCode(200).setBody(response))
}
|
mit
|
14338dfa1446c3d37e30e33ee6dabe38
| 37.183099 | 132 | 0.646717 | 4.672124 | false | false | false | false |
robinverduijn/gradle
|
subprojects/instant-execution/src/main/kotlin/org/gradle/instantexecution/serialization/Contexts.kt
|
1
|
8556
|
/*
* Copyright 2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gradle.instantexecution.serialization
import org.gradle.api.internal.initialization.ClassLoaderScope
import org.gradle.api.internal.project.ProjectInternal
import org.gradle.api.logging.Logger
import org.gradle.initialization.ClassLoaderScopeRegistry
import org.gradle.instantexecution.ClassLoaderScopeSpec
import org.gradle.instantexecution.serialization.beans.BeanConstructors
import org.gradle.instantexecution.serialization.beans.BeanPropertyReader
import org.gradle.instantexecution.serialization.beans.BeanPropertyWriter
import org.gradle.instantexecution.serialization.beans.BeanStateReader
import org.gradle.instantexecution.serialization.beans.BeanStateWriter
import org.gradle.internal.serialize.Decoder
import org.gradle.internal.serialize.Encoder
internal
class DefaultWriteContext(
codec: Codec<Any?>,
private
val encoder: Encoder,
private
val scopeLookup: ScopeLookup,
override val logger: Logger,
private
val problemHandler: (PropertyProblem) -> Unit
) : AbstractIsolateContext<WriteIsolate>(codec), WriteContext, Encoder by encoder {
override val sharedIdentities = WriteIdentities()
private
val beanPropertyWriters = hashMapOf<Class<*>, BeanStateWriter>()
private
val classes = WriteIdentities()
private
val scopes = WriteIdentities()
override fun beanStateWriterFor(beanType: Class<*>): BeanStateWriter =
beanPropertyWriters.computeIfAbsent(beanType, ::BeanPropertyWriter)
override val isolate: WriteIsolate
get() = getIsolate()
override suspend fun write(value: Any?) {
getCodec().run {
encode(value)
}
}
override fun writeClass(type: Class<*>) {
val id = classes.getId(type)
if (id != null) {
writeSmallInt(id)
} else {
val scope = scopeLookup.scopeFor(type.classLoader)
val newId = classes.putInstance(type)
writeSmallInt(newId)
writeString(type.name)
if (scope == null) {
writeBoolean(false)
} else {
writeBoolean(true)
writeScope(scope.first)
writeBoolean(scope.second.local)
}
}
}
private
fun writeScope(scope: ClassLoaderScopeSpec) {
val id = scopes.getId(scope)
if (id != null) {
writeSmallInt(id)
} else {
val newId = scopes.putInstance(scope)
writeSmallInt(newId)
if (scope.parent != null) {
writeBoolean(true)
writeScope(scope.parent)
writeString(scope.name)
writeClassPath(scope.localClassPath)
writeClassPath(scope.exportClassPath)
} else {
writeBoolean(false)
}
}
}
// TODO: consider interning strings
override fun writeString(string: CharSequence) =
encoder.writeString(string)
override fun newIsolate(owner: IsolateOwner): WriteIsolate =
DefaultWriteIsolate(owner)
override fun onProblem(problem: PropertyProblem) {
problemHandler(problem)
}
}
interface EncodingProvider<T> {
suspend fun WriteContext.encode(value: T)
}
@Suppress("experimental_feature_warning")
inline class ClassLoaderRole(val local: Boolean)
internal
interface ScopeLookup {
fun scopeFor(classLoader: ClassLoader?): Pair<ClassLoaderScopeSpec, ClassLoaderRole>?
}
internal
class DefaultReadContext(
codec: Codec<Any?>,
private
val decoder: Decoder,
private
val constructors: BeanConstructors,
override val logger: Logger
) : AbstractIsolateContext<ReadIsolate>(codec), ReadContext, Decoder by decoder {
override val sharedIdentities = ReadIdentities()
private
val beanStateReaders = hashMapOf<Class<*>, BeanStateReader>()
private
val classes = ReadIdentities()
private
val scopes = ReadIdentities()
private
lateinit var projectProvider: ProjectProvider
override lateinit var classLoader: ClassLoader
internal
fun initClassLoader(classLoader: ClassLoader) {
this.classLoader = classLoader
}
internal
fun initProjectProvider(projectProvider: ProjectProvider) {
this.projectProvider = projectProvider
}
override var immediateMode: Boolean = false
override suspend fun read(): Any? = getCodec().run {
decode()
}
override val isolate: ReadIsolate
get() = getIsolate()
override fun beanStateReaderFor(beanType: Class<*>): BeanStateReader =
beanStateReaders.computeIfAbsent(beanType) { type -> BeanPropertyReader(type, constructors) }
override fun readClass(): Class<*> {
val id = readSmallInt()
val type = classes.getInstance(id)
if (type != null) {
return type as Class<*>
}
val name = readString()
val classLoader = if (readBoolean()) {
val scope = readScope()
if (readBoolean()) {
scope.localClassLoader
} else {
scope.exportClassLoader
}
} else {
this.classLoader
}
val newType = Class.forName(name, false, classLoader)
classes.putInstance(id, newType)
return newType
}
private
fun readScope(): ClassLoaderScope {
val id = readSmallInt()
val scope = scopes.getInstance(id)
if (scope != null) {
return scope as ClassLoaderScope
}
val newScope = if (readBoolean()) {
val parent = readScope()
val name = readString()
val localClassPath = readClassPath()
val exportClassPath = readClassPath()
parent
.createChild(name)
.local(localClassPath)
.export(exportClassPath)
.lock()
} else {
isolate.owner.service(ClassLoaderScopeRegistry::class.java).coreAndPluginsScope
}
Workarounds.maybeSetDefaultStaticStateIn(newScope)
scopes.putInstance(id, newScope)
return newScope
}
override fun getProject(path: String): ProjectInternal =
projectProvider(path)
override fun newIsolate(owner: IsolateOwner): ReadIsolate =
DefaultReadIsolate(owner)
override fun onProblem(problem: PropertyProblem) {
// ignore problems
}
}
interface DecodingProvider<T> {
suspend fun ReadContext.decode(): T?
}
internal
typealias ProjectProvider = (String) -> ProjectInternal
internal
abstract class AbstractIsolateContext<T>(codec: Codec<Any?>) : MutableIsolateContext {
private
var currentIsolate: T? = null
private
var currentCodec = codec
var trace: PropertyTrace = PropertyTrace.Unknown
protected
abstract fun newIsolate(owner: IsolateOwner): T
protected
fun getIsolate(): T = currentIsolate.let { isolate ->
require(isolate != null) {
"`isolate` is only available during Task serialization."
}
isolate
}
protected
fun getCodec() = currentCodec
private
val contexts = ArrayList<Pair<T?, Codec<Any?>>>()
override fun push(owner: IsolateOwner, codec: Codec<Any?>) {
contexts.add(0, Pair(currentIsolate, currentCodec))
currentIsolate = newIsolate(owner)
currentCodec = codec
}
override fun pop() {
val previousValues = contexts.removeAt(0)
currentIsolate = previousValues.first
currentCodec = previousValues.second
}
}
internal
class DefaultWriteIsolate(override val owner: IsolateOwner) : WriteIsolate {
override val identities: WriteIdentities = WriteIdentities()
}
internal
class DefaultReadIsolate(override val owner: IsolateOwner) : ReadIsolate {
override val identities: ReadIdentities = ReadIdentities()
}
|
apache-2.0
|
c6513dc6c990f1c77f91f8518ac50d69
| 26.423077 | 101 | 0.660472 | 4.817568 | false | false | false | false |
jilees/Fuel
|
fuel/src/main/kotlin/com/github/kittinunf/fuel/util/Delegates.kt
|
1
|
794
|
package com.github.kittinunf.fuel.util
import kotlin.properties.ReadWriteProperty
import kotlin.reflect.KProperty
fun <T> readWriteLazy(initializer: () -> T): ReadWriteProperty<Any?, T> = ReadWriteLazyVal(initializer)
private class ReadWriteLazyVal<T>(private val initializer: () -> T) : ReadWriteProperty<Any?, T> {
private var value: Any? = null
operator override fun getValue(thisRef: Any?, property: KProperty<*>): T {
if (value == null) {
value = (initializer()) ?: throw IllegalStateException("Initializer block of property ${property.name} return null")
}
@Suppress("UNCHECKED_CAST")
return value as T
}
operator override fun setValue(thisRef: Any?, property: KProperty<*>, value: T) {
this.value = value
}
}
|
mit
|
47645e15ac7d2d7d8d41a5eca94a006a
| 32.125 | 128 | 0.675063 | 4.362637 | false | false | false | false |
Ph1b/MaterialAudiobookPlayer
|
data/src/main/kotlin/de/ph1b/audiobook/data/repo/internals/BookStorage.kt
|
1
|
2741
|
package de.ph1b.audiobook.data.repo.internals
import de.ph1b.audiobook.data.Book
import de.ph1b.audiobook.data.BookContent
import de.ph1b.audiobook.data.repo.internals.dao.BookMetaDataDao
import de.ph1b.audiobook.data.repo.internals.dao.BookSettingsDao
import de.ph1b.audiobook.data.repo.internals.dao.ChapterDao
import timber.log.Timber
import java.util.UUID
import javax.inject.Inject
import javax.inject.Singleton
/**
* Provides access to the persistent storage for bookmarks.
*/
@Singleton
class BookStorage
@Inject constructor(
private val chapterDao: ChapterDao,
private val metaDataDao: BookMetaDataDao,
private val bookSettingsDao: BookSettingsDao,
private val appDb: AppDb
) {
suspend fun books(): List<Book> {
return appDb.transaction {
bookSettingsDao.all()
.mapNotNull { bookSettings ->
val bookId = bookSettings.id
val metaData = metaDataDao.byId(bookId)
val chapters = chapterDao.byBookId(bookId)
if (chapters.isEmpty()) {
Timber.e("No chapters found for metaData=$metaData, bookSettings=$bookSettings")
metaDataDao.delete(metaData)
bookSettingsDao.delete(bookSettings)
null
} else {
val bookSettingsFileInChapters = chapters.any { chapter ->
chapter.file == bookSettings.currentFile
}
val correctedBookSettings = if (bookSettingsFileInChapters) {
bookSettings
} else {
Timber.e("bookSettings=$bookSettings currentFile is not in $chapters. metaData=$metaData")
bookSettings.copy(currentFile = chapters[0].file)
}
Book(
id = bookId,
content = BookContent(
id = bookId,
chapters = chapters,
settings = correctedBookSettings
),
metaData = metaData
)
}
}
}
}
suspend fun setBookActive(bookId: UUID, active: Boolean) {
bookSettingsDao.setActive(bookId, active = active)
}
suspend fun addOrUpdate(book: Book) {
appDb.transaction {
metaDataDao.insert(book.metaData)
bookSettingsDao.insert(book.content.settings)
// delete old chapters and replace them with new ones
chapterDao.deleteByBookId(book.id)
chapterDao.insert(book.content.chapters)
}
}
suspend fun updateBookName(id: UUID, name: String) {
metaDataDao.updateBookName(id, name)
}
suspend fun updateLastPlayedAt(id: UUID, lastPlayedAt: Long) {
bookSettingsDao.updateLastPlayedAt(id, lastPlayedAt)
}
suspend fun updateBookContent(content: BookContent) {
bookSettingsDao.insert(content.settings)
}
}
|
lgpl-3.0
|
4d01706ebf624f32a08996c7c8a1c707
| 30.505747 | 104 | 0.661437 | 4.296238 | false | false | false | false |
toastkidjp/Jitte
|
todo/src/main/java/jp/toastkid/todo/view/list/TaskListFragment.kt
|
1
|
4793
|
/*
* Copyright (c) 2019 toastkidjp.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompany this distribution.
* The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html.
*/
package jp.toastkid.todo.view.list
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.fragment.app.Fragment
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.paging.Pager
import androidx.paging.PagingConfig
import jp.toastkid.lib.AppBarViewModel
import jp.toastkid.todo.R
import jp.toastkid.todo.data.TodoTaskDatabase
import jp.toastkid.todo.databinding.AppBarTaskListBinding
import jp.toastkid.todo.databinding.FragmentTaskListBinding
import jp.toastkid.todo.view.addition.TaskAdditionDialogFragmentUseCase
import jp.toastkid.todo.view.addition.TaskAdditionDialogFragmentViewModel
import jp.toastkid.todo.view.item.menu.ItemMenuPopup
import jp.toastkid.todo.view.item.menu.ItemMenuPopupActionUseCase
import jp.toastkid.todo.view.list.initial.InitialTaskPreparation
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
/**
* @author toastkidjp
*/
class TaskListFragment : Fragment() {
private lateinit var binding: FragmentTaskListBinding
private lateinit var appBarBinding: AppBarTaskListBinding
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
binding = DataBindingUtil.inflate(inflater, LAYOUT_ID, container, false)
appBarBinding =
DataBindingUtil.inflate(inflater, APP_BAR_LAYOUT_ID, container, false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val repository = TodoTaskDatabase.find(view.context).repository()
var popup: ItemMenuPopup? = null
val viewModel = ViewModelProvider(this).get(TaskListFragmentViewModel::class.java)
viewModel
.showMenu
.observe(viewLifecycleOwner, Observer { event ->
event.getContentIfNotHandled()?.let {
popup?.show(it.first, it.second)
}
})
val adapter = Adapter(viewModel)
val refresh = { adapter.refresh() }
val taskAdditionDialogFragmentUseCase =
TaskAdditionDialogFragmentUseCase(
this,
ViewModelProvider(this).get(TaskAdditionDialogFragmentViewModel::class.java)
) {
CoroutineScope(Dispatchers.Main).launch {
withContext(Dispatchers.IO) {
repository.insert(it)
}
refresh()
}
}
popup = ItemMenuPopup(
view.context,
ItemMenuPopupActionUseCase(
{ taskAdditionDialogFragmentUseCase.invoke(it) },
{
CoroutineScope(Dispatchers.Main).launch {
withContext(Dispatchers.IO) {
repository.delete(it)
}
refresh()
}
}
)
)
binding.results.adapter = adapter
CoroutineScope(Dispatchers.IO).launch {
if (repository.count() == 0) {
InitialTaskPreparation(repository).invoke()
}
Pager(
PagingConfig(pageSize = 10, enablePlaceholders = true),
pagingSourceFactory = { repository.allTasks() }
)
.flow
.collectLatest {
adapter.submitData(it)
}
}
appBarBinding.add.setOnClickListener {
taskAdditionDialogFragmentUseCase.invoke()
}
activity?.let {
ViewModelProvider(it).get(AppBarViewModel::class.java).replace(appBarBinding.root)
}
}
companion object {
@LayoutRes
private val LAYOUT_ID = R.layout.fragment_task_list
@LayoutRes
private val APP_BAR_LAYOUT_ID = R.layout.app_bar_task_list
}
}
|
epl-1.0
|
f360548c7f4b6c8020aec0b990aa1b52
| 33.489209 | 100 | 0.619028 | 5.43424 | false | false | false | false |
7hens/KDroid
|
core/src/main/java/cn/thens/kdroid/core/vadapter/VPagerAdapter.kt
|
1
|
2067
|
package cn.thens.kdroid.core.vadapter
import androidx.annotation.LayoutRes
import androidx.viewpager.widget.PagerAdapter
import android.util.SparseArray
import android.view.View
import android.view.ViewGroup
import java.lang.ref.WeakReference
/**
* The Adapter for [ViewPager][android.support.v4.view.PagerAdapter].
*/
abstract class VPagerAdapter<D>(private val boundless: Boolean = false) : PagerAdapter(), VBaseAdapter<D>, MutableList<D> by ArrayList<D>() {
override val holderList = SparseArray<WeakReference<VAdapter.Holder<D>>>()
override fun notifyChanged() {
notifyDataSetChanged()
}
override fun getCount(): Int {
return if (boundless && size > 1) Integer.MAX_VALUE else size
}
val startIndex: Int get () = (count / 2).let { it - it % size }
override fun isViewFromObject(view: View, o: Any): Boolean {
return view === o
}
private fun getSmartSize(size: Int): Int {
val limit = 4
var result = size
while (result < limit) {
result += size
}
return result
}
override fun instantiateItem(container: ViewGroup, position: Int): Any {
val realPos = position % getSmartSize(size)
val holder = getHolder(container, realPos)
val itemView = holder.view
(itemView.parent as? ViewGroup)?.removeView(itemView)
container.addView(itemView)
bindHolder(holder, realPos % size)
return itemView
}
override fun destroyItem(container: ViewGroup, position: Int, `object`: Any) {
removeHolder(position % getSmartSize(size))
}
companion object {
fun <D> create(@LayoutRes layoutRes: Int, boundless: Boolean = false, bind: View.(data: D, position: Int) -> Unit): VPagerAdapter<D> {
return object : VPagerAdapter<D>(boundless) {
override fun createHolder(viewGroup: ViewGroup, viewType: Int): VAdapter.Holder<D> {
return viewGroup.inflate(layoutRes).toHolder(bind)
}
}
}
}
}
|
apache-2.0
|
7c7d23dadbd17fdd6b184d72524261bb
| 31.809524 | 142 | 0.644896 | 4.351579 | false | false | false | false |
SUPERCILEX/Robot-Scouter
|
buildSrc/src/main/kotlin/Projects.kt
|
1
|
528
|
import com.supercilex.robotscouter.build.internal.isCi
import com.supercilex.robotscouter.build.internal.isRelease
import org.gradle.api.Project
val Project.buildTags: List<String>
get() = listOf(
if (isCi) "CI" else "Local",
if (isRelease) "Release" else "Debug",
if (isReleaseBuild) "ProdBuild" else "DevBuild"
)
val Project.isReleaseBuild: Boolean get() = hasProperty("relBuild") || isCi
internal fun Project.child(name: String): Project = subprojects.first { it.name == name }
|
gpl-3.0
|
18317026d709498874147549aae27335
| 36.714286 | 89 | 0.69697 | 3.771429 | false | false | false | false |
google/ksp
|
test-utils/src/main/kotlin/com/google/devtools/ksp/processor/RecordJavaGetAllMembersProcessor.kt
|
1
|
1972
|
/*
* Copyright 2020 Google LLC
* Copyright 2010-2020 JetBrains s.r.o. and Kotlin Programming Language 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.google.devtools.ksp.processor
import com.google.devtools.ksp.processing.Resolver
import com.google.devtools.ksp.processing.impl.ResolverImpl
import com.google.devtools.ksp.symbol.*
class RecordJavaGetAllMembersProcessor : AbstractTestProcessor() {
val results = mutableListOf<String>()
override fun toResult(): List<String> {
val finalResult = mutableListOf(results[0])
finalResult.addAll(results.subList(1, results.size).sorted())
return finalResult
}
override fun process(resolver: Resolver): List<KSAnnotated> {
resolver.getAllFiles().forEach {
if (it.fileName == "A.kt") {
val c = it.declarations.single {
it is KSClassDeclaration && it.simpleName.asString() == "A"
} as KSClassDeclaration
c.getAllFunctions()
c.getAllProperties()
}
}
if (resolver is ResolverImpl) {
val m = resolver.incrementalContext.dumpLookupRecords().toSortedMap()
m.toSortedMap().forEach { symbol, files ->
files.filter { it.endsWith(".java") }.sorted().forEach {
results.add("$symbol: $it")
}
}
}
return emptyList()
}
}
|
apache-2.0
|
30ae67ce513a82356b3df2a6c3a2bf5a
| 35.518519 | 85 | 0.649594 | 4.554273 | false | false | false | false |
rumboalla/apkupdater
|
app/src/main/java/com/apkupdater/repository/fdroid/FdroidRepository.kt
|
1
|
5740
|
package com.apkupdater.repository.fdroid
import android.content.Context
import android.os.Build
import android.util.Log
import com.apkupdater.R
import com.apkupdater.model.fdroid.FdroidApp
import com.apkupdater.model.fdroid.FdroidData
import com.apkupdater.model.fdroid.FdroidPackage
import com.apkupdater.model.ui.AppInstalled
import com.apkupdater.model.ui.AppSearch
import com.apkupdater.model.ui.AppUpdate
import com.apkupdater.util.app.AppPrefs
import com.apkupdater.util.app.InstallUtil
import com.apkupdater.util.ioScope
import com.apkupdater.util.orZero
import com.github.kittinunf.fuel.Fuel
import com.google.gson.Gson
import com.google.gson.stream.JsonReader
import com.kryptoprefs.invoke
import kotlinx.coroutines.async
import org.koin.core.KoinComponent
import org.koin.core.inject
import java.io.File
import java.io.InputStreamReader
import java.util.jar.JarFile
class FdroidRepository: KoinComponent {
private val prefs: AppPrefs by inject()
private val installer: InstallUtil by inject()
private val context: Context by inject()
private val file = File(context.cacheDir, "fdroid")
private val baseUrl = "https://f-droid.org/repo/"
private val index = "index-v1.jar"
private var lastCheck = 0L
private var data: FdroidData? = null
private val arch: List<String> by lazy {
if (Build.VERSION.SDK_INT >= 21) {
Build.SUPPORTED_ABIS.toList()
} else {
listOfNotNull(Build.CPU_ABI, Build.CPU_ABI2)
}
}
@Suppress("BlockingMethodInNonBlockingContext")
fun getDataAsync() = ioScope.async {
runCatching {
if (data == null || System.currentTimeMillis() - lastCheck > 3600000) {
// Head request so we get only the headers
var last = ""
try {
last = Fuel.head("$baseUrl$index").response().second.headers["Last-Modified"].first()
} catch (e: Exception) {
}
lastCheck = System.currentTimeMillis()
// Check if last changed
var refresh = false
if (last != prefs.lastFdroid() || data == null) {
// Download new file
installer.downloadAsync(context, "$baseUrl$index", file)
prefs.lastFdroid(last)
refresh = true
}
// Read the json from inside jar
if (data == null || refresh) {
val jar = JarFile(file)
val stream = jar.getInputStream(jar.getEntry("index-v1.json"))
data = Gson().fromJson<FdroidData>(JsonReader(InputStreamReader(stream, "UTF-8")), FdroidData::class.java)
}
}
data
}.fold(
onSuccess = { it },
onFailure = {
Log.e("FdroidRepository", "getDataAsync", it)
null
}
)
}
fun updateAsync(apps: Sequence<AppInstalled>) = ioScope.async {
runCatching {
if (getDataAsync().await() == null) throw NullPointerException("updateAsync: data is null")
apps.mapNotNull { app -> if (prefs.settings.excludeExperimental && isExperimental(data?.apps?.find { it.packageName == app.packageName }?: FdroidApp())) null else app }
.mapNotNull { app -> if (prefs.settings.excludeMinApi && data?.packages?.get(app.packageName)?.first()?.minSdkVersion.orZero() > Build.VERSION.SDK_INT) null else app }
.mapNotNull { app -> if (prefs.settings.excludeArch && isIncompatibleArch(data?.packages?.get(app.packageName)?.first())) null else app }
.mapNotNull { app -> data?.packages?.get(app.packageName)?.first()?.let { pack -> if (pack.versionCode > app.versionCode) AppUpdate.from(app, pack) else null }
}.sortedBy { it.name }.toList()
}.onFailure { Result.failure<List<AppUpdate>>(it) }.onSuccess { Result.success(it) }
}
fun searchAsync(text: String) = ioScope.async {
runCatching {
getDataAsync().await()?.apps.orEmpty()
.asSequence()
.filter { app -> app.description.contains(text, true) || app.packageName.contains(text, true) }
.mapNotNull { app -> if (prefs.settings.excludeExperimental && isExperimental(app)) null else app }
.mapNotNull { app -> if (prefs.settings.excludeMinApi && data?.packages?.get(app.packageName)?.first()?.minSdkVersion.orZero() > Build.VERSION.SDK_INT) null else app }
.mapNotNull { app -> if (prefs.settings.excludeArch && isIncompatibleArch(data?.packages?.get(app.packageName)?.first())) null else app }
.sortedByDescending { app -> app.lastUpdated }
.take(10)
.map { app -> AppSearch.from(app) }
.toList()
}.fold(onSuccess = { Result.success(it) }, onFailure = { Result.failure(it) })
}
private fun isIncompatibleArch(pack: FdroidPackage?): Boolean {
pack?.let { return !(it.nativecode.isEmpty() || it.nativecode.intersect(arch).isNotEmpty()) }
return false
}
private fun isExperimental(app: FdroidApp): Boolean {
if (app.suggestedVersionName.contains("-alpha", true) || app.suggestedVersionName.contains("-beta", true)
|| app.packageName.endsWith(".alpha") || app.packageName.endsWith(".beta")
|| app.name.contains("(alpha)", true) || app.name.contains("(beta)", true)) return true
return false
}
private fun AppUpdate.Companion.from(app: AppInstalled, pack: FdroidPackage) =
AppUpdate(
app.name,
app.packageName,
pack.versionName,
pack.versionCode,
app.version,
app.versionCode,
"$baseUrl${pack.apkName}",
R.drawable.fdroid_logo
)
private fun AppSearch.Companion.from(app: FdroidApp) =
AppSearch(
app.name,
"$baseUrl${app.packageName}_${app.suggestedVersionCode}.apk",
"${baseUrl}icons-640/${app.icon}",
app.packageName,
R.drawable.fdroid_logo
)
}
|
gpl-3.0
|
479ab8413d4de2f0d3da621b01d28922
| 37.530201 | 171 | 0.662718 | 3.811421 | false | false | false | false |
alygin/intellij-rust
|
src/test/kotlin/org/rust/cargo/util/CargoCommandCompletionProviderTest.kt
|
1
|
3772
|
/*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.cargo.util
import com.intellij.codeInsight.completion.PlainPrefixMatcher
import org.rust.cargo.project.workspace.CargoWorkspace
import org.rust.cargo.toolchain.impl.CleanCargoMetadata
import org.rust.lang.RsTestBase
class CargoCommandCompletionProviderTest : RsTestBase() {
fun `test split context prefix`() {
val provider = CargoCommandCompletionProvider(null)
fun doCheck(text: String, ctx: String, prefix: String) {
val (actualCtx, actualPrefix) = provider.splitContextPrefix(text)
check(actualCtx == ctx && actualPrefix == prefix) {
"\nExpected\n\n$ctx, $prefix\nActual:\n$actualCtx, $actualPrefix"
}
}
doCheck("build", "", "build")
doCheck("b", "", "b")
doCheck("build ", "build", "")
}
fun `test complete empty`() = checkCompletion(
"",
listOf("run", "test", "check", "build", "update", "bench", "doc", "publish", "clean", "search", "install")
)
fun `test complete command name`() = checkCompletion(
"b",
listOf("build", "bench")
)
fun `test no completion for unknown command`() = checkCompletion(
"frob ",
listOf()
)
fun `test complete run args`() = checkCompletion(
"run ",
listOf("--release", "--jobs", "--features", "--all-features", "--no-default-features", "--triple", "--verbose", "--quite", "--bin", "--example", "--package")
)
fun `test dont suggest a flag twice`() = checkCompletion(
"run --release --rel",
listOf()
)
fun `test dont suggest after double dash`() = checkCompletion(
"run -- --rel",
listOf()
)
fun `test suggest package argument`() = checkCompletion(
"test --package ",
listOf("foo", "quux")
)
fun `test suggest bin argument`() = checkCompletion(
"run --bin ",
listOf("bar", "baz")
)
private fun checkCompletion(
text: String,
expectedCompletions: List<String>
) {
val provider = CargoCommandCompletionProvider(TEST_WORKSPACE)
val (ctx, prefix) = provider.splitContextPrefix(text)
val matcher = PlainPrefixMatcher(prefix)
val actual = provider.complete(ctx).filter { matcher.isStartMatch(it) }.map { it.lookupString }
check(actual == expectedCompletions) {
"\nExpected:\n$expectedCompletions\n\nActual:\n$actual"
}
}
private val TEST_WORKSPACE = run {
fun target(name: String, kind: CargoWorkspace.TargetKind): CleanCargoMetadata.Target = CleanCargoMetadata.Target(
url = "/tmp/lib/rs",
name = name,
kind = kind
)
fun pkg(
name: String,
isWorkspaceMember: Boolean,
targets: List<CleanCargoMetadata.Target>
): CleanCargoMetadata.Package = CleanCargoMetadata.Package(
name = name,
id = "pkg-id",
url = "/tmp",
version = "1.0.0",
targets = targets,
source = null,
manifestPath = "/tmp/Cargo.toml",
isWorkspaceMember = isWorkspaceMember
)
val pkgs = listOf(
pkg("foo", true, listOf(
target("foo", CargoWorkspace.TargetKind.LIB),
target("bar", CargoWorkspace.TargetKind.BIN),
target("baz", CargoWorkspace.TargetKind.BIN)
)),
pkg("quux", false, listOf(target("quux", CargoWorkspace.TargetKind.LIB)))
)
CargoWorkspace.deserialize(null, CleanCargoMetadata(pkgs, dependencies = emptyList()))
}
}
|
mit
|
fffb855f84297a6027d77ec2fd5851c9
| 31.517241 | 165 | 0.583245 | 4.42723 | false | true | false | false |
wuseal/JsonToKotlinClass
|
src/main/kotlin/wu/seal/jsontokotlin/utils/ClassImportDeclarationWriter.kt
|
1
|
1713
|
package wu.seal.jsontokotlin.utils
import com.intellij.openapi.editor.Document
import com.intellij.openapi.project.Project
import wu.seal.jsontokotlin.interceptor.InterceptorManager
import kotlin.math.max
/**
* to be a helper to insert Import class declare code
* Created by Seal.Wu on 2017/9/18.
*/
object ClassImportDeclarationWriter : IClassImportDeclarationWriter {
override fun insertImportClassCode(project: Project?, editFile: Document) {
val text = editFile.text
val interceptedImportClassDeclaration = ClassImportDeclaration.applyImportClassDeclarationInterceptors(
InterceptorManager.getEnabledImportClassDeclarationInterceptors()
)
interceptedImportClassDeclaration.split("\n").forEach { importClassLineString ->
if (importClassLineString !in text) {
val packageIndex = try {
"^[\\s]*package\\s.+\n$".toRegex(RegexOption.MULTILINE).find(text)!!.range.last
} catch (e: Exception) {
-1
}
val lastImportKeywordIndex = try {
"^[\\s]*import\\s.+\n$".toRegex(RegexOption.MULTILINE).findAll(text).last().range.last
} catch (e: Exception) {
-1
}
val index = max(lastImportKeywordIndex, packageIndex)
val insertIndex =
if (index == -1) 0 else editFile.getLineEndOffset(editFile.getLineNumber(index))
executeCouldRollBackAction(project) {
editFile.insertString(insertIndex, "\n" + importClassLineString + "\n")
}
}
}
}
}
|
gpl-3.0
|
ddf2b185cf5b10c0036ce055de5ff891
| 31.320755 | 111 | 0.608873 | 4.936599 | false | false | false | false |
rahulsom/grooves
|
grooves-example-springboot-kotlin/src/main/kotlin/grooves/boot/kotlin/domain/PatientAccount.kt
|
1
|
2217
|
package grooves.boot.kotlin.domain
import com.fasterxml.jackson.annotation.JsonFormat
import com.fasterxml.jackson.annotation.JsonIgnore
import com.github.rahulsom.grooves.api.snapshots.Snapshot
import grooves.boot.kotlin.repositories.PatientRepository
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.beans.factory.annotation.Configurable
import reactor.core.publisher.Flux.empty
import reactor.core.publisher.Mono
import reactor.core.publisher.Mono.just
import java.math.BigDecimal
import java.util.Date
// tag::documented[]
@Configurable
class PatientAccount : Snapshot<Patient, String, String, PatientEvent> { // <1>
override var id: String? = null
override var lastEventPosition: Long = 0 // <2>
@JsonFormat(pattern = "yyyy-MM-dd'T'HH:mm:ss.SSSZ")
override var lastEventTimestamp: Date? = null // <3>
val deprecatesIds: MutableList<String> = mutableListOf()
private var deprecator: Patient? = null
var aggregateId: String? = null
var name: String? = null
var balance: BigDecimal = BigDecimal.ZERO
var moneyMade: BigDecimal = BigDecimal.ZERO
fun getDeprecatedBy() = deprecator
@JsonIgnore
override fun getAggregateObservable() = // <4>
aggregateId?.let { patientRepository!!.findAllById(just(it)) } ?: empty()
override fun setAggregate(aggregate: Patient) {
this.aggregateId = aggregate.id
}
@JsonIgnore
@Autowired
var patientRepository: PatientRepository? = null
@JsonIgnore
override fun getDeprecatedByObservable() = // <5>
deprecator?.let { just(it) } ?: Mono.empty()
override fun setDeprecatedBy(deprecatingAggregate: Patient) {
deprecator = deprecatingAggregate
}
@JsonIgnore
override fun getDeprecatesObservable() = // <6>
if (deprecatesIds.size > 0)
patientRepository!!.findAllById(deprecatesIds)
else
empty()
// end::documented[]
override fun toString(): String {
return "PatientAccount(id=$id, aggregate=$aggregateId, " +
"lastEventPosition=$lastEventPosition, lastEventTimestamp=$lastEventTimestamp)"
}
// tag::documented[]
}
// end::documented[]
|
apache-2.0
|
e5dc2d94ae6206e775f1ec549d11c91a
| 31.617647 | 91 | 0.712675 | 4.105556 | false | false | false | false |
importre/popular
|
app/src/main/kotlin/io/github/importre/popular/BaseActivity.kt
|
1
|
2672
|
package io.github.importre.popular
import android.app.Activity
import android.content.Context
import android.os.Bundle
import android.support.annotation.AttrRes
import android.support.annotation.IdRes
import android.support.v4.widget.DrawerLayout
import android.support.v7.app.ActionBarActivity
import android.support.v7.widget.Toolbar
import android.util.TypedValue
import android.view.MenuItem
import android.view.ViewManager
import de.hdodenhof.circleimageview.CircleImageView
import kotlinx.android.anko.__dslAddView
import kotlin.properties.Delegates
abstract class BaseActivity : ActionBarActivity() {
protected val primaryColor: Int by Delegates.lazy {
getAttrColor(R.attr.colorPrimary)
}
protected val primaryDarkColor: Int by Delegates.lazy {
getAttrColor(R.attr.colorPrimaryDark)
}
protected val toolbarSize: Int by Delegates.lazy {
getAttrDimen(R.attr.actionBarSize)
}
protected val insetStart: Int by Delegates.lazy {
getAttrDimen(R.attr.actionBarInsetStart)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
}
fun ViewManager.toolbar(init: Toolbar.() -> Unit = {}) =
__dslAddView({ Toolbar(it) }, init, this)
fun ViewManager.circleImageView(init: CircleImageView.() -> Unit = {}) =
__dslAddView({ CircleImageView(it) }, init, this)
fun Activity.drawerLayout(init: DrawerLayout.() -> Unit = {}) =
__dslAddView({ DrawerLayout(it) }, init, this)
fun Activity.getAttrColor(AttrRes attr: Int): Int {
val outValue = TypedValue()
getTheme().resolveAttribute(attr, outValue, true)
return getResources().getColor(outValue.resourceId)
}
fun Activity.getAttrDimen(AttrRes attr: Int): Int {
val outValue = TypedValue()
getTheme().resolveAttribute(attr, outValue, true)
return getResources().getDimension(outValue.resourceId).toInt()
}
fun Activity.getAttrResId(AttrRes attr: Int): Int {
val outValue = TypedValue()
getTheme().resolveAttribute(attr, outValue, true)
return outValue.resourceId
}
fun Context.getDimen(IdRes id: Int): Int {
return getResources().getDimension(id).toInt()
}
fun Activity.getDimen(IdRes id: Int): Int {
return getResources().getDimension(id).toInt()
}
override fun onOptionsItemSelected(item: MenuItem?): Boolean {
when (item!!.getItemId()) {
android.R.id.home -> {
onBackPressed()
return true
}
}
return super.onOptionsItemSelected(item)
}
}
|
mit
|
5d7e85cc2091e14d9daae22de65ccc88
| 30.435294 | 76 | 0.68226 | 4.453333 | false | false | false | false |
ZsemberiDaniel/EgerBusz
|
app/src/main/java/com/zsemberidaniel/egerbuszuj/misc/TodayType.kt
|
1
|
6352
|
package com.zsemberidaniel.egerbuszuj.misc
import android.content.Context
import android.os.AsyncTask
import android.util.Log
import org.joda.time.DateTime
import org.joda.time.DateTimeConstants
import org.joda.time.LocalDate
import java.io.BufferedReader
import java.io.IOException
import java.io.InputStreamReader
import java.util.ArrayList
import java.util.Calendar
/**
* Created by zsemberi.daniel on 2017. 05. 08..
*/
class TodayType {
companion object {
/**
* The file:
* year
* // After this do the special munkaszuneti napok come
* month day
* ...
* // After this do the tanszuneti napok come
* month day
* ...
* // After this do the special days on which we have to work come
* month day
* ...
* // After this do the summer break come
* month day // from
* month day // till
*/
private val CALENDAR_FILE_PATH = "calendar.txt"
var ISKOLAI_MUNKANAP = 0
var TANSZUNETI_MUNKANAP = 1
var SZABADNAP = 2
var MUNKASZUNETI_NAP = 3
private lateinit var munkaszunetiNapok: ArrayList<DateTime>
private lateinit var tanszunetiNapok: ArrayList<DateTime>
private lateinit var specialisMunkanap: ArrayList<DateTime>
private lateinit var summerBreak: Array<DateTime>
/**
* Initializes the special days. Needs to be called at the start of the app every time.
* @param context The current context
*/
fun init(context: Context) {
var reader: BufferedReader
try {
reader = BufferedReader(InputStreamReader(context.assets.open(CALENDAR_FILE_PATH)))
val year = Integer.valueOf(reader.readLine())!!
// Casting the value to int because Android Studio 2.3 gives error that year should be Calendar.Sunday or something...
if (year != Calendar.getInstance().get(Calendar.YEAR)) {
// TODO not current year -> fetch from server
}
munkaszunetiNapok = ArrayList<DateTime>()
tanszunetiNapok = ArrayList<DateTime>()
specialisMunkanap = ArrayList<DateTime>()
summerBreak = Array(2, { DateTime() })
var words: Array<String>
var at: Int = 0
val splitRegex = " ".toRegex()
BufferedReader(reader).use { reader ->
reader.lineSequence().forEach {
if (it == "")
at++
else when (at) {
// munkaszuneti nap
0 -> {
words = it.split(splitRegex).dropLastWhile({ it.isEmpty() }).toTypedArray()
munkaszunetiNapok.add(DateTime(year, Integer.valueOf(words[0])!!, Integer.valueOf(words[1])!!, 0, 0))
}
// tanszuneti nao
1 -> {
words = it.split(splitRegex).dropLastWhile({ it.isEmpty() }).toTypedArray()
tanszunetiNapok.add(DateTime(year, Integer.valueOf(words[0])!!, Integer.valueOf(words[1])!!, 0, 0))
}
// specialis munkanap
2 -> {
words = it.split(splitRegex).dropLastWhile({ it.isEmpty() }).toTypedArray()
specialisMunkanap.add(DateTime(year, Integer.valueOf(words[0])!!, Integer.valueOf(words[1])!!, 0, 0))
}
// nyari szunet
3, 4 -> {
words = it.split(splitRegex).dropLastWhile({ it.isEmpty() }).toTypedArray()
summerBreak[at - 3] = DateTime(year, Integer.valueOf(words[0])!!, Integer.valueOf(words[1])!!, 0, 0)
at++
}
}
}
}
} catch (exception: IOException) {
// TODO file not found fetch it from the server maybe
}
}
/**
* Based on today's date return what type of day it is
* @return It's based on the ints in this class (ISKOLAI_MUNKANAP, TANSZUNETI_MUNKANAP ...)
*/
val todayType: Int
get() {
val today = DateTime.now()
return getDayType(today)
}
/**
* The day type of the given date
* @return It's based on the ints in this class (ISKOLAI_MUNKANAP, TANSZUNETI_MUNKANAP ...)
*/
fun getDayType(date: DateTime): Int {
// first let's go through the days on which we work but we normally wouldn't have to
specialisMunkanap
.filter { it.withTimeAtStartOfDay() == date.withTimeAtStartOfDay() }
.forEach { return ISKOLAI_MUNKANAP }
// Then we need to get rid of all the munkaszuneti nap-s and the szabadnap-s becaus
// munkaszuneti nap-s and szabadnap-s override tanszuneti nap-s
// This comes first because if something is a tanszuneti nap it doesn't mean that it's a munkaszunet
munkaszunetiNapok
.filter { it.withTimeAtStartOfDay() == date.withTimeAtStartOfDay() }
.forEach { return MUNKASZUNETI_NAP }
// The day is saturday -> SZABADNAP
if (date.dayOfWeek == DateTimeConstants.SATURDAY) {
return SZABADNAP
} else if (date.dayOfWeek == DateTimeConstants.SUNDAY) {
return MUNKASZUNETI_NAP
}
// At this point there are no munkaszuneti nap-s
tanszunetiNapok
.filter { it.withTimeAtStartOfDay() == date.withTimeAtStartOfDay() }
.forEach { return TANSZUNETI_MUNKANAP }
// Now comes the summer break
if (date.isBefore(summerBreak[1]) && date.isAfter(summerBreak[0]))
return TANSZUNETI_MUNKANAP
return ISKOLAI_MUNKANAP
}
}
}
|
apache-2.0
|
5f3f3189648c50b0a3b98e761d92e803
| 37.97546 | 134 | 0.5233 | 4.441958 | false | false | false | false |
alashow/music-android
|
modules/core-ui-downloader/src/main/java/tm/alashow/datmusic/ui/downloader/DownloaderHost.kt
|
1
|
4636
|
/*
* Copyright (C) 2021, Alashov Berkeli
* All rights reserved.
*/
package tm.alashow.datmusic.ui.downloader
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.material.AlertDialog
import androidx.compose.material.LocalAbsoluteElevation
import androidx.compose.material.SnackbarHostState
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.runtime.staticCompositionLocalOf
import androidx.compose.ui.ExperimentalComposeUiApi
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import androidx.compose.ui.window.DialogProperties
import androidx.hilt.navigation.compose.hiltViewModel
import kotlinx.coroutines.launch
import timber.log.Timber
import tm.alashow.base.util.asString
import tm.alashow.common.compose.LocalScaffoldState
import tm.alashow.common.compose.collectEvent
import tm.alashow.datmusic.downloader.Downloader
import tm.alashow.datmusic.downloader.DownloaderEvent
import tm.alashow.ui.components.TextRoundedButton
import tm.alashow.ui.theme.AppTheme
val LocalDownloader = staticCompositionLocalOf<Downloader> {
error("LocalDownloader not provided")
}
@Composable
fun DownloaderHost(
viewModel: DownloaderViewModel = hiltViewModel(),
snackbarHostState: SnackbarHostState = LocalScaffoldState.current.snackbarHostState,
content: @Composable () -> Unit
) {
val context = LocalContext.current
val coroutine = rememberCoroutineScope()
var downloadsLocationDialogShown by remember { mutableStateOf(false) }
collectEvent(viewModel.downloader.downloaderEvents) { event ->
when (event) {
DownloaderEvent.ChooseDownloadsLocation -> {
downloadsLocationDialogShown = true
}
is DownloaderEvent.DownloaderMessage -> {
val message = event.message.asString(context)
coroutine.launch { snackbarHostState.showSnackbar(message) }
}
else -> Unit
}
}
CompositionLocalProvider(LocalDownloader provides viewModel.downloader) {
DownloadsLocationDialog(dialogShown = downloadsLocationDialogShown, onDismiss = { downloadsLocationDialogShown = false })
content()
}
}
@OptIn(ExperimentalComposeUiApi::class)
@Composable
private fun DownloadsLocationDialog(
dialogShown: Boolean,
downloader: Downloader = LocalDownloader.current,
onDismiss: () -> Unit,
) {
val coroutine = rememberCoroutineScope()
val documentTreeLauncher = rememberLauncherForActivityResult(contract = WriteableOpenDocumentTree()) {
coroutine.launch {
try {
downloader.setDownloadsLocation(it)
} catch (e: Exception) {
Timber.e(e)
}
}
}
if (dialogShown) {
// [ColorPalettePreference.Black] theme needs at least 1.dp dialog surfaces
CompositionLocalProvider(LocalAbsoluteElevation provides 1.dp) {
AlertDialog(
properties = DialogProperties(usePlatformDefaultWidth = true),
onDismissRequest = { onDismiss() },
title = { Text(stringResource(R.string.downloader_downloadsLocationSelect_title)) },
text = { Text(stringResource(R.string.downloader_downloadsLocationSelect_text)) },
buttons = {
Row(
horizontalArrangement = Arrangement.End,
modifier = Modifier
.fillMaxWidth()
.padding(AppTheme.specs.padding)
) {
TextRoundedButton(
onClick = {
onDismiss()
documentTreeLauncher.launch(null)
},
text = stringResource(R.string.downloader_downloadsLocationSelect_next)
)
}
},
)
}
}
}
|
apache-2.0
|
753ce052e4852f239283b63972dcbb27
| 37.957983 | 129 | 0.687015 | 5.298286 | false | false | false | false |
JetBrains/anko
|
anko/library/generator/src/org/jetbrains/android/anko/generator/layoutParamsUtils.kt
|
2
|
2851
|
/*
* 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.
*/
package org.jetbrains.android.anko.generator
import org.jetbrains.android.anko.annotations.ExternalAnnotation
import org.jetbrains.android.anko.isPublic
import org.jetbrains.android.anko.parameterRawTypes
import org.jetbrains.android.anko.returnType
import org.jetbrains.android.anko.utils.fqName
import org.jetbrains.android.anko.utils.getConstructors
import org.jetbrains.android.anko.utils.unique
import org.objectweb.asm.tree.ClassNode
//return a pair<viewGroup, layoutParams> or null if the viewGroup doesn't contain custom LayoutParams
fun GenerationState.extractLayoutParams(viewGroup: ClassNode): LayoutElement? {
fun findActualLayoutParamsClass(viewGroup: ClassNode): ClassNode? {
fun findForParent() = findActualLayoutParamsClass(classTree.findNode(viewGroup)!!.parent!!.data)
val generateMethod = viewGroup.methods.firstOrNull { method ->
method.name == "generateLayoutParams"
&& method.parameterRawTypes.unique?.internalName == "android/util/AttributeSet"
} ?: return findForParent()
val returnTypeClass = classTree.findNode(generateMethod.returnType.internalName)!!.data
if (!returnTypeClass.fqName.startsWith(viewGroup.fqName)) return findForParent()
return if (returnTypeClass.isLayoutParams) returnTypeClass else findForParent()
}
val lpInnerClassName = viewGroup.innerClasses?.firstOrNull { it.name.contains("LayoutParams") }
val lpInnerClass = lpInnerClassName?.let { classTree.findNode(it.name)!!.data }
val externalAnnotations = annotationManager.findExternalAnnotations(viewGroup.fqName)
val hasGenerateLayoutAnnotation = ExternalAnnotation.GenerateLayout in externalAnnotations
val hasGenerateViewAnnotation = ExternalAnnotation.GenerateView in externalAnnotations
if (hasGenerateViewAnnotation || (lpInnerClass == null && !hasGenerateLayoutAnnotation)) return null
val layoutParams = lpInnerClass?.takeIf { it.name.startsWith(viewGroup.name) }
?: findActualLayoutParamsClass(viewGroup)?.takeIf { it.name != "android/view/ViewGroup\$LayoutParams" }
return layoutParams?.let { classNode ->
LayoutElement(viewGroup, classNode, classNode.getConstructors().filter { it.isPublic })
}
}
|
apache-2.0
|
1f2ad3650130ca4d1583f63f6b96b386
| 49.035088 | 115 | 0.766047 | 4.720199 | false | false | false | false |
ccomeaux/boardgamegeek4android
|
app/src/main/java/com/boardgamegeek/ui/dialog/PlayTimeFilterDialog.kt
|
1
|
1886
|
package com.boardgamegeek.ui.dialog
import android.content.Context
import com.boardgamegeek.R
import com.boardgamegeek.extensions.andMore
import com.boardgamegeek.extensions.asTime
import com.boardgamegeek.filterer.CollectionFilterer
import com.boardgamegeek.filterer.PlayTimeFilterer
import kotlin.math.roundToInt
class PlayTimeFilterDialog : SliderFilterDialog() {
override fun getType(context: Context) = PlayTimeFilterer(context).type
override val titleResId = R.string.menu_play_time
override val descriptionResId = R.string.filter_description_include_missing_play_time
override val supportsSlider = false
override val valueFrom = PlayTimeFilterer.lowerBound.toFloat()
override val valueTo = PlayTimeFilterer.upperBound.toFloat()
override val stepSize = 5f
override fun initValues(filter: CollectionFilterer?): InitialValues {
val f = filter as? PlayTimeFilterer
return InitialValues(
(f?.min ?: PlayTimeFilterer.lowerBound).toFloat(),
(f?.max ?: PlayTimeFilterer.upperBound).toFloat(),
f?.includeUndefined ?: false,
)
}
override fun createFilterer(context: Context): CollectionFilterer {
return PlayTimeFilterer(context).apply {
min = low.roundToInt()
max = high.roundToInt()
includeUndefined = checkboxIsChecked
}
}
override fun describeRange(context: Context): String {
return (createFilterer(context) as? PlayTimeFilterer)?.describeRange(" - ")?.ifEmpty { context.getString(R.string.all) } ?: context.getString(
R.string.all
)
}
override fun formatSliderLabel(context: Context, value: Float): String {
return when (val time = value.roundToInt()) {
PlayTimeFilterer.upperBound -> time.asTime().andMore()
else -> time.asTime()
}
}
}
|
gpl-3.0
|
0602d274ac85d001f4067a155cc9991c
| 37.489796 | 150 | 0.696713 | 4.611247 | false | false | false | false |
ccomeaux/boardgamegeek4android
|
app/src/main/java/com/boardgamegeek/ui/viewmodel/GameCollectionItemViewModel.kt
|
1
|
8372
|
package com.boardgamegeek.ui.viewmodel
import android.app.Application
import androidx.lifecycle.*
import androidx.palette.graphics.Palette
import com.boardgamegeek.entities.CollectionItemEntity
import com.boardgamegeek.entities.RefreshableResource
import com.boardgamegeek.extensions.getHeaderSwatch
import com.boardgamegeek.extensions.isOlderThan
import com.boardgamegeek.provider.BggContract
import com.boardgamegeek.provider.BggContract.Collection
import com.boardgamegeek.repository.GameCollectionRepository
import com.boardgamegeek.util.RemoteConfig
import kotlinx.coroutines.launch
import java.util.concurrent.TimeUnit
import java.util.concurrent.atomic.AtomicBoolean
class GameCollectionItemViewModel(application: Application) : AndroidViewModel(application) {
private val gameCollectionRepository = GameCollectionRepository(getApplication())
private val areItemsRefreshing = AtomicBoolean()
private val isImageRefreshing = AtomicBoolean()
private val forceRefresh = AtomicBoolean()
private val refreshMinutes = RemoteConfig.getInt(RemoteConfig.KEY_REFRESH_GAME_COLLECTION_MINUTES)
private val _collectionId = MutableLiveData<Int>()
val collectionId: LiveData<Int>
get() = _collectionId
private val _isEditMode = MutableLiveData<Boolean>()
val isEditMode: LiveData<Boolean>
get() = _isEditMode
private val _isEdited = MutableLiveData<Boolean>()
val isEdited: LiveData<Boolean>
get() = _isEdited
init {
_isEditMode.value = false
_isEdited.value = false
}
fun setId(id: Int) {
if (_collectionId.value != id) _collectionId.value = id
}
fun toggleEditMode() {
if (item.value?.data != null)
_isEditMode.value?.let { _isEditMode.value = !it }
}
val item: LiveData<RefreshableResource<CollectionItemEntity>> = _collectionId.switchMap { id ->
liveData {
try {
latestValue?.data?.let { emit(RefreshableResource.refreshing(it)) }
val item = gameCollectionRepository.loadCollectionItem(id)
emit(RefreshableResource.success(item))
val refreshedItem = if (areItemsRefreshing.compareAndSet(false, true)) {
item?.let {
val canRefresh = it.gameId != BggContract.INVALID_ID
val shouldRefresh = it.syncTimestamp.isOlderThan(refreshMinutes, TimeUnit.HOURS)
if (canRefresh && (shouldRefresh || forceRefresh.compareAndSet(true, false))) {
emit(RefreshableResource.refreshing(it))
gameCollectionRepository.refreshCollectionItem(it.gameId, id)
val loadedItem = gameCollectionRepository.loadCollectionItem(id)
emit(RefreshableResource.success(loadedItem))
loadedItem
} else item
}
} else item
if (isImageRefreshing.compareAndSet(false, true)) {
refreshedItem?.let {
gameCollectionRepository.refreshHeroImage(it)
emit(RefreshableResource.success(gameCollectionRepository.loadCollectionItem(id)))
}
}
} catch (e: Exception) {
emit(RefreshableResource.error(e, application))
} finally {
areItemsRefreshing.set(false)
isImageRefreshing.set(false)
}
}
}
val acquiredFrom = liveData {
emit(gameCollectionRepository.loadAcquiredFrom())
}
val inventoryLocation = liveData {
emit(gameCollectionRepository.loadInventoryLocation())
}
private val _swatch = MutableLiveData<Palette.Swatch>()
val swatch: LiveData<Palette.Swatch>
get() = _swatch
fun refresh() {
_collectionId.value?.let { _collectionId.value = it }
}
fun updateGameColors(palette: Palette?) {
palette?.let { _swatch.value = it.getHeaderSwatch() }
}
fun updatePrivateInfo(
priceCurrency: String?,
pricePaid: Double?,
currentValueCurrency: String?,
currentValue: Double?,
quantity: Int?,
acquisitionDate: Long?,
acquiredFrom: String?,
inventoryLocation: String?
) {
val itemModified = item.value?.data?.let {
priceCurrency != it.pricePaidCurrency ||
pricePaid != it.pricePaid ||
currentValueCurrency != it.currentValueCurrency ||
currentValue != it.currentValue ||
quantity != it.quantity ||
acquisitionDate != it.acquisitionDate ||
acquiredFrom != it.acquiredFrom ||
inventoryLocation != it.inventoryLocation
} ?: false
if (itemModified) {
setEdited(true)
viewModelScope.launch {
gameCollectionRepository.updatePrivateInfo(
item.value?.data?.internalId ?: BggContract.INVALID_ID.toLong(),
priceCurrency,
pricePaid,
currentValueCurrency,
currentValue,
quantity,
acquisitionDate,
acquiredFrom,
inventoryLocation
)
refresh()
}
}
}
fun updateStatuses(statuses: List<String>, wishlistPriority: Int) {
val itemModified = item.value?.data?.let {
statuses.contains(Collection.Columns.STATUS_OWN) != it.own ||
statuses.contains(Collection.Columns.STATUS_OWN) != it.own ||
statuses.contains(Collection.Columns.STATUS_PREVIOUSLY_OWNED) != it.previouslyOwned ||
statuses.contains(Collection.Columns.STATUS_PREORDERED) != it.preOrdered ||
statuses.contains(Collection.Columns.STATUS_FOR_TRADE) != it.forTrade ||
statuses.contains(Collection.Columns.STATUS_WANT) != it.wantInTrade ||
statuses.contains(Collection.Columns.STATUS_WANT_TO_BUY) != it.wantToBuy ||
statuses.contains(Collection.Columns.STATUS_WANT_TO_PLAY) != it.wantToPlay ||
statuses.contains(Collection.Columns.STATUS_WISHLIST) != it.wishList
} ?: false
if (itemModified) {
setEdited(true)
viewModelScope.launch {
val internalId = item.value?.data?.internalId ?: BggContract.INVALID_ID.toLong()
gameCollectionRepository.updateStatuses(internalId, statuses, wishlistPriority)
refresh()
}
}
}
fun updateRating(rating: Double) {
val currentRating = item.value?.data?.rating ?: 0.0
if (rating != currentRating) {
setEdited(true)
viewModelScope.launch {
val internalId = item.value?.data?.internalId ?: BggContract.INVALID_ID.toLong()
gameCollectionRepository.updateRating(internalId, rating)
refresh()
}
}
}
fun updateText(text: String, textColumn: String, timestampColumn: String, originalText: String? = null) {
if (text != originalText) {
setEdited(true)
viewModelScope.launch {
val internalId = item.value?.data?.internalId ?: BggContract.INVALID_ID.toLong()
gameCollectionRepository.updateText(internalId, text, textColumn, timestampColumn)
refresh()
}
}
}
fun delete() {
setEdited(false)
viewModelScope.launch {
gameCollectionRepository.markAsDeleted(item.value?.data?.internalId ?: BggContract.INVALID_ID.toLong())
refresh()
}
}
fun reset() {
setEdited(false)
viewModelScope.launch {
val internalId = item.value?.data?.internalId ?: BggContract.INVALID_ID.toLong()
gameCollectionRepository.resetTimestamps(internalId)
forceRefresh.set(true)
refresh()
}
}
private fun setEdited(edited: Boolean) {
if (_isEdited.value != edited) _isEdited.value = edited
}
}
|
gpl-3.0
|
1f2bcf03b19f85828883c5a52cb6aa43
| 39.057416 | 115 | 0.602962 | 5.2 | false | false | false | false |
simo-andreev/Colourizmus
|
app/src/main/java/bg/o/sim/colourizmus/view/ColourCreationActivity.kt
|
1
|
5966
|
package bg.o.sim.colourizmus.view
import android.Manifest.permission.CAMERA
import android.content.Intent
import android.content.pm.PackageManager.PERMISSION_GRANTED
import android.graphics.Bitmap
import android.net.Uri
import android.os.Bundle
import android.provider.MediaStore
import android.view.Menu
import android.view.MenuItem
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts.GetContent
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.core.content.FileProvider
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentPagerAdapter
import androidx.lifecycle.Observer
import bg.o.sim.colourizmus.R
import bg.o.sim.colourizmus.databinding.ActivityMainBinding
import bg.o.sim.colourizmus.model.CustomColour
import bg.o.sim.colourizmus.model.LIVE_COLOUR
import bg.o.sim.colourizmus.model.LiveColour
import bg.o.sim.colourizmus.utils.*
class ColourCreationActivity : AppCompatActivity() {
private var mImageUri: Uri? = null
private lateinit var binding: ActivityMainBinding
private lateinit var getContent: ActivityResultLauncher<String>
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
getContent = registerForActivityResult(GetContent()) { uri: Uri? ->
if (uri == null) {
toastLong("No Image selected")
return@registerForActivityResult;
}
startActivity(Intent(this, ColourDetailsActivity::class.java).apply {
putExtra(EXTRA_PICTURE_URI, uri)
})
}
this.setSupportActionBar(binding.allahuAppbar.allahuAppbar)
binding.mainFabHexadecInput.setOnClickListener {
MainScreenHexInput().show(fragmentManager, "HexadecInputDialog")
}
binding.mainFabReleaseDaKamrakken.setOnClickListener {
if (this.havePermission(CAMERA))
takePhoto()
else
ActivityCompat.requestPermissions(this, arrayOf(CAMERA), REQUEST_PERMISSION_IMAGE_CAPTURE)
}
binding.mainFabPlunderYerGallery.setOnClickListener {
if (this.havePermission(CAMERA))
openGallery()
else
ActivityCompat.requestPermissions(this, arrayOf(CAMERA), REQUEST_PERMISSION_IMAGE_CAPTURE)
}
binding.mainFabSaveColour.setOnClickListener {
SaveColourDialogue().show(fragmentManager, SaveColourDialogue.TAG)
}
binding.colourCreationPager.adapter = object : FragmentPagerAdapter(supportFragmentManager) {
override fun getItem(position: Int): Fragment = when (position) {
0 -> SeekerFragment.newInstance()
1 -> PickerFragment.newInstance()
else -> throw IllegalArgumentException()
}
override fun getCount() = 2
override fun getPageTitle(position: Int): CharSequence = when (position) {
0 -> getString(R.string.coarse)
1 -> getString(R.string.precise)
else -> getString(R.string.FUCK)
}
}
LIVE_COLOUR.observe(this, Observer<Int> {
binding.colourCreationPager.setBackgroundColor(it!!)
binding.colourCreationHexadecPreview.text = "#${Integer.toHexString(it)}"
binding.colourCreationHexadecPreview.setTextColor(getComplimentaryColour(CustomColour(it, "")).value)
})
}
private fun openGallery() {
getContent.launch("image/*")
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
R.id.action_settings -> startActivity(Intent(this, ColourListActivity::class.java))
}
return true
}
override fun onCreateOptionsMenu(menu: Menu?): Boolean {
menuInflater.inflate(R.menu.dashboard, menu)
return true
}
private fun takePhoto() {
val cameraIntent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
if (cameraIntent.resolveActivity(packageManager) != null) {
val authority = getString(R.string.file_provider_auth)
mImageUri = FileProvider.getUriForFile(this, authority, getImageFile())
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, mImageUri)
startActivityForResult(cameraIntent, REQUEST_IMAGE_CAPTURE)
} else {
this.toastLong("You have no camera dummy (^.^)")
}
}
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
when (requestCode) {
REQUEST_PERMISSION_IMAGE_CAPTURE ->
if (PERMISSION_GRANTED in grantResults) takePhoto()
else this.toastLong("Y U NO GIB PRMISHNZ? :@")
// other cases can go here at a later point
}
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
when (requestCode) {
REQUEST_IMAGE_CAPTURE -> if (resultCode == RESULT_OK) {
val showPicResult = Intent(this, ColourDetailsActivity::class.java)
showPicResult.putExtra(EXTRA_PICTURE_URI, mImageUri)
showPicResult.putExtra(EXTRA_PICTURE_THUMB, data!!.extras!!["data"] as Bitmap)
startActivity(showPicResult)
}
// other cases can go here at a later point
}
}
}
class MainScreenHexInput : HexadecInputDialog() {
override fun onSave(dialogue: HexadecInputDialog, colour: LiveColour) {
LIVE_COLOUR.set(colour)
dialogue.dismiss()
}
}
|
apache-2.0
|
fd576ca48d7bc937a2cb64f00da4164b
| 36.765823 | 119 | 0.671472 | 4.862266 | false | false | false | false |
ratabb/Hishoot2i
|
app/src/main/java/core/impl/BadgeBuilderImpl.kt
|
1
|
2939
|
package core.impl
import android.content.Context
import android.graphics.Bitmap
import android.graphics.Paint
import android.graphics.PorterDuff
import android.graphics.PorterDuffXfermode
import android.graphics.Rect
import android.graphics.RectF
import android.os.Build
import android.text.TextPaint
import androidx.core.graphics.applyCanvas
import common.ext.dp2px
import common.ext.graphics.createBitmap
import common.ext.graphics.drawBitmapSafely
import common.ext.graphics.halfAlpha
import common.ext.graphics.sizes
import common.ext.textSize
import core.BadgeBuilder
import dagger.hilt.android.qualifiers.ApplicationContext
import entity.BadgePosition
import entity.Sizes
import java.util.Locale
import javax.inject.Inject
import kotlin.math.roundToInt
class BadgeBuilderImpl @Inject constructor(
@ApplicationContext context: Context
) : BadgeBuilder {
private val rectF: RectF = RectF()
private val padding by lazy { context.dp2px(16F) }
private val cornerRadius by lazy { context.dp2px(8F) }
private val textPaint: TextPaint = TextPaint().apply {
flags = (Paint.ANTI_ALIAS_FLAG or Paint.SUBPIXEL_TEXT_FLAG or Paint.LINEAR_TEXT_FLAG)
if (Build.VERSION.SDK_INT >= 21) isElegantTextHeight = true //
isFakeBoldText = true
xfermode = PorterDuffXfermode(PorterDuff.Mode.CLEAR)
}
private val backgroundPaint: Paint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
style = Paint.Style.FILL
}
private val textSizes: (Float) -> Float = { value -> context.textSize(value) }
//
private val badgeBitmapPadding by lazy { context.dp2px(10F).roundToInt() }
override suspend fun Bitmap.drawBadge(
isEnable: Boolean,
position: BadgePosition,
config: BadgeBuilder.Config
) = applyCanvas {
if (!isEnable) return@applyCanvas
val badgeBitmap = buildWith(config)
val (left, top) = position.getValue(sizes, badgeBitmap.sizes, badgeBitmapPadding)
applyCanvas { drawBitmapSafely(badgeBitmap, left, top) }
}
private fun buildWith(config: BadgeBuilder.Config): Bitmap {
val textUpperCase = config.text.toUpperCase(Locale.ROOT)
val localBound = Rect()
textPaint.apply {
typeface = config.typeFace
textSize = textSizes(config.size)
getTextBounds(textUpperCase, 0, textUpperCase.length, localBound)
}
val sizes = Sizes(
textPaint.measureText(textUpperCase).toInt(),
localBound.height()
) + (padding * 2 + 0.5F).toInt()
backgroundPaint.color = config.color.halfAlpha
rectF.apply {
right = sizes.x.toFloat()
bottom = sizes.y.toFloat()
}
return sizes.createBitmap().applyCanvas {
drawRoundRect(rectF, cornerRadius, cornerRadius, backgroundPaint)
drawText(textUpperCase, padding, height - padding, textPaint)
}
}
}
|
apache-2.0
|
db3573a4cf4614b7e4808d9ea5389483
| 35.7375 | 93 | 0.7033 | 4.322059 | false | true | false | false |
MehdiK/Humanizer.jvm
|
src/main/kotlin/org/humanizer/jvm/Inflector.kt
|
1
|
9806
|
package org.humanizer.jvm
import java.util.regex.Pattern
import org.humanizer.jvm.exceptions.NoRuleFoundException
fun String.camelize(): String {
var previousWasUnderscore = false
var t = ""
this.decapitalize().forEach {
if (it.toString().equals("_")) previousWasUnderscore = true
if (Character.isLetterOrDigit(it) && previousWasUnderscore) {
previousWasUnderscore = false
t = "${t}${it.toString().toUpperCase()}"
} else {
t = "${t}${it}"
}
}
return t.replace("_", "")
}
fun String.pascalize(): String {
var previousWasUnderscore = false
var t = ""
this.capitalize().forEach {
if (it.toString().equals("_")) previousWasUnderscore = true
if (Character.isLetterOrDigit(it) && previousWasUnderscore) {
previousWasUnderscore = false
t = "${t}${it.toString().toUpperCase()}"
} else {
t = "${t}${it}"
}
}
return t.replace("_", "")
}
fun String.underscore(): String {
var previousWasCapital = false
var t = ""
this.decapitalize().forEach {
if (Character.isUpperCase(it)) previousWasCapital = true
if (Character.isLetterOrDigit(it) && previousWasCapital) {
previousWasCapital = false
t = "${t}_${it.toString().toLowerCase()}"
} else {
t = "${t}${it}"
}
}
return t.replace(" ", "_")
}
fun String.titleize(): String {
var previousWasWhitespace = false
var t = ""
this.replace("-", " ").replace("_", " ").capitalize()
.forEach {
if (Character.isWhitespace(it) || !Character.isLetterOrDigit(it)) previousWasWhitespace = true
if (Character.isLetterOrDigit(it) && previousWasWhitespace) {
previousWasWhitespace = false
t = "${t}${it.toString().toUpperCase()}"
} else {
t = "${t}${it}"
}
}
return t
}
fun String.dasherize(): String {
return this.replace("_", "-")
}
fun String.hyphenate(): String {
return this.replace("_", "-")
}
/*
The pluralize and singularize methods are based on the code found in the following places.
https://github.com/atteo/evo-inflector/blob/master/src/main/java/org/atteo/evo/inflector/English.java
http://www.java2s.com/Tutorial/Java/0040__Data-Type/Transformswordstosingularpluralhumanizedhumanreadableunderscorecamelcaseorordinalform.htm
https://github.com/rails/rails/blob/26698fb91d88dca0f860adcb80528d8d3f0f6285/activesupport/lib/active_support/inflector/inflections.rb
*/
fun String.pluralize(plurality: Plurality = Plurality.Singular): String {
if(plurality== Plurality.Plural) return this
if(plurality == Plurality.Singular)
return this.pluralizer()
if (this.singularizer() != this && this.singularizer() + "s" != this && this.singularizer().pluralizer() == this && this.pluralizer() != this)
return this
return this.pluralizer()
}
fun String.singularize(plurality: Plurality = Plurality.Plural): String {
if(plurality== Plurality.Singular) return this
if(plurality == Plurality.Plural) return this.singularizer()
if (this.pluralizer() != this && this+"s" != this.pluralizer() && this.pluralizer().singularize() == this && this.singularizer() != this)
return this;
return this.singularize()
}
private fun String.pluralizer() : String{
if (unCountable().contains(this)) return this
val rule = pluralizeRules().last { Pattern.compile(it.component1(), Pattern.CASE_INSENSITIVE).matcher(this).find() }
var found = Pattern.compile(rule.component1(), Pattern.CASE_INSENSITIVE).matcher(this).replaceAll(rule.component2())
val endswith = exceptions().firstOrNull { this.endsWith(it.component1()) }
if (endswith != null) found = this.replace(endswith.component1(), endswith.component2())
val excep = exceptions().firstOrNull() { this.equals(it.component1()) }
if (excep != null) found = excep.component2()
return found
}
private fun String.singularizer() : String {
if (unCountable().contains(this)) return this
val excep = exceptions().firstOrNull() { this.equals(it.component2()) }
if (excep != null) return excep.component1()
val endswith = exceptions().firstOrNull { this.endsWith(it.component2()) }
if (endswith != null) return this.replace(endswith.component2(), endswith.component1())
try{
if(singularizeRules().count { Pattern.compile(it.component1(), Pattern.CASE_INSENSITIVE).matcher(this).find() } == 0 ) return this
val rule = singularizeRules().last { Pattern.compile(it.component1(), Pattern.CASE_INSENSITIVE).matcher(this).find() }
return Pattern.compile(rule.component1(), Pattern.CASE_INSENSITIVE).matcher(this).replaceAll(rule.component2())}
catch(ex : IllegalArgumentException) {
NoRuleFoundException("singularize")
}
return this
}
fun unCountable(): List<String> {
return listOf("equipment", "information", "rice", "money",
"species", "series", "fish", "sheep", "aircraft", "bison", "flounder", "pliers", "bream",
"gallows", "proceedings", "breeches", "graffiti", "rabies",
"britches", "headquarters", "salmon", "carp", "herpes",
"scissors", "chassis", "high-jinks", "sea-bass", "clippers",
"homework", "cod", "innings", "shears",
"contretemps", "jackanapes", "corps", "mackerel",
"swine", "debris", "measles", "trout", "diabetes", "mews",
"tuna", "djinn", "mumps", "whiting", "eland", "news",
"wildebeest", "elk", "pincers", "sugar")
}
fun exceptions(): List<Pair<String, String>> {
return listOf("person" to "people",
"man" to "men",
"goose" to "geese",
"child" to "children",
"sex" to "sexes",
"move" to "moves",
"stadium" to "stadiums",
"deer" to "deer",
"codex" to "codices",
"murex" to "murices",
"silex" to "silices",
"radix" to "radices",
"helix" to "helices",
"alumna" to "alumnae",
"alga" to "algae",
"vertebra" to "vertebrae",
"persona" to "personae",
"stamen" to "stamina",
"foramen" to "foramina",
"lumen" to "lumina",
"afreet" to "afreeti",
"afrit" to "afriti",
"efreet" to "efreeti",
"cherub" to "cherubim",
"goy" to "goyim",
"human" to "humans",
"lumen" to "lumina",
"seraph" to "seraphim",
"Alabaman" to "Alabamans",
"Bahaman" to "Bahamans",
"Burman" to "Burmans",
"German" to "Germans",
"Hiroshiman" to "Hiroshimans",
"Liman" to "Limans",
"Nakayaman" to "Nakayamans",
"Oklahoman" to "Oklahomans",
"Panaman" to "Panamans",
"Selman" to "Selmans",
"Sonaman" to "Sonamans",
"Tacoman" to "Tacomans",
"Yakiman" to "Yakimans",
"Yokohaman" to "Yokohamans",
"Yuman" to "Yumans","criterion" to "criteria",
"perihelion" to "perihelia",
"aphelion" to "aphelia",
"phenomenon" to "phenomena",
"prolegomenon" to "prolegomena",
"noumenon" to "noumena",
"organon" to "organa",
"asyndeton" to "asyndeta",
"hyperbaton" to "hyperbata")
}
fun pluralizeRules(): List<Pair<String, String>> {
return listOf(
"$" to "s",
"s$"to "s",
"(ax|test)is$" to "$1es",
"us$" to "i",
"(octop|vir)us$" to "$1i",
"(octop|vir)i$" to "$1i",
"(alias|status)$" to "$1es",
"(bu)s$" to "$1ses",
"(buffal|tomat)o$" to "$1oes",
"([ti])um$" to "$1a",
"([ti])a$" to "$1a",
"sis$" to "ses",
"(,:([^f])fe|([lr])f)$" to "$1$2ves",
"(hive)$" to "$1s",
"([^aeiouy]|qu)y$" to "$1ies",
"(x|ch|ss|sh)$" to "$1es",
"(matr|vert|ind)ix|ex$" to "$1ices",
"([m|l])ouse$" to "$1ice",
"([m|l])ice$" to "$1ice",
"^(ox)$" to "$1en",
"(quiz)$" to "$1zes",
"f$" to "ves",
"fe$" to "ves",
"um$" to "a",
"on$" to "a")
}
fun singularizeRules(): List<Pair<String, String>> {
return listOf(
"s$" to "",
"(s|si|u)s$" to "$1s",
"(n)ews$" to "$1ews",
"([ti])a$" to "$1um",
"((a)naly|(b)a|(d)iagno|(p)arenthe|(p)rogno|(s)ynop|(t)he)ses$" to "$1$2sis",
"(^analy)ses$" to "$1sis",
"(^analy)sis$" to "$1sis",
"([^f])ves$" to "$1fe",
"(hive)s$" to "$1",
"(tive)s$" to "$1",
"([lr])ves$" to "$1f",
"([^aeiouy]|qu)ies$" to "$1y",
"(s)eries$" to "$1eries",
"(m)ovies$" to "$1ovie",
"(x|ch|ss|sh)es$" to "$1",
"([m|l])ice$" to "$1ouse",
"(bus)es$" to "$1",
"(o)es$" to "$1",
"(shoe)s$" to "$1",
"(cris|ax|test)is$" to "$1is",
"(cris|ax|test)es$" to "$1is",
"(octop|vir)i$" to "$1us",
"(octop|vir)us$" to "$1us",
"(alias|status)es$" to "$1",
"(alias|status)$" to "$1",
"^(ox)en" to "$1",
"(vert|ind)ices$" to "$1ex",
"(matr)ices$" to "$1ix",
"(quiz)zes$" to "$1",
"a$" to "um",
"i$" to "us",
"ae$" to "a")
}
enum class Plurality {
Singular
Plural
CouldBeEither
}
|
apache-2.0
|
0b6ab0805fe401473524e89cb026f79e
| 35.188192 | 146 | 0.533245 | 3.509664 | false | false | false | false |
crunchersaspire/worshipsongs-android
|
app/src/main/java/org/worshipsongs/domain/DragDrop.kt
|
2
|
2004
|
package org.worshipsongs.domain
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import org.apache.commons.lang3.StringUtils
import org.apache.commons.lang3.builder.EqualsBuilder
import org.apache.commons.lang3.builder.HashCodeBuilder
import java.util.ArrayList
/**
* Author : Madasamy
* Version : 3.x.x
*/
open class DragDrop
{
//TODO: Rename this as orderId (Ref: Favourite.kt). (Please note that this will have an impact in existing favourites)
var id: Long = 0
var title: String? = null
var isChecked: Boolean = false
constructor()
{
}
constructor(orderId: Long, title: String, checked: Boolean)
{
this.id = orderId
this.title = title
this.isChecked = checked
}
override fun toString(): String
{
return "DragDrop{" + "orderId=" + id + ", title='" + title + '\''.toString() + ", checked=" + isChecked + '}'.toString()
}
override fun equals(`object`: Any?): Boolean
{
if (`object` is DragDrop)
{
val otherObject = `object` as DragDrop?
val builder = EqualsBuilder()
builder.append(title, otherObject!!.title)
return builder.isEquals
}
return false
}
override fun hashCode(): Int
{
val hashCodeBuilder = HashCodeBuilder()
hashCodeBuilder.append(title)
return hashCodeBuilder.hashCode()
}
companion object
{
fun toJson(items: List<DragDrop>): String
{
val gson = Gson()
return gson.toJson(items)
}
fun toArrays(jsonString: String): ArrayList<DragDrop>
{
if (StringUtils.isNotBlank(jsonString))
{
val gson = Gson()
val type = object : TypeToken<ArrayList<DragDrop>>()
{
}.type
return gson.fromJson(jsonString, type)
}
return ArrayList()
}
}
}
|
gpl-3.0
|
bc3f899a56b280f7a05d65fc4f0fe06f
| 23.144578 | 128 | 0.578343 | 4.493274 | false | false | false | false |
FHannes/intellij-community
|
platform/testFramework/src/com/intellij/mock/MockRunManager.kt
|
11
|
4264
|
/*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.mock
import com.intellij.execution.BeforeRunTask
import com.intellij.execution.RunManagerConfig
import com.intellij.execution.RunManagerEx
import com.intellij.execution.RunnerAndConfigurationSettings
import com.intellij.execution.configurations.ConfigurationFactory
import com.intellij.execution.configurations.ConfigurationType
import com.intellij.execution.configurations.RunConfiguration
import com.intellij.execution.configurations.RunProfile
import com.intellij.openapi.util.Key
import javax.swing.Icon
/**
* @author gregsh
*/
class MockRunManager : RunManagerEx() {
override fun getConfigurationType(typeName: String) = TODO("not implemented")
override fun addConfiguration(settings: RunnerAndConfigurationSettings, isShared: Boolean) {
}
override fun hasSettings(settings: RunnerAndConfigurationSettings) = false
override fun getConfigurationsList(type: ConfigurationType) = emptyList<RunConfiguration>()
override fun makeStable(settings: RunnerAndConfigurationSettings) {}
override val configurationFactories: Array<ConfigurationType>
get() = emptyArray()
override val configurationFactoriesWithoutUnknown: List<ConfigurationType>
get() = emptyList()
override val allConfigurationsList: List<RunConfiguration>
get() = emptyList()
override val allSettings: List<RunnerAndConfigurationSettings>
get() = emptyList()
override val tempConfigurationsList: List<RunnerAndConfigurationSettings>
get() = emptyList()
override var selectedConfiguration: RunnerAndConfigurationSettings?
get() = null
set(value) {}
override fun createConfiguration(runConfiguration: RunConfiguration, factory: ConfigurationFactory): RunnerAndConfigurationSettings {
throw UnsupportedOperationException()
}
override fun getConfigurationTemplate(factory: ConfigurationFactory): RunnerAndConfigurationSettings {
throw UnsupportedOperationException()
}
override fun getConfigurationSettingsList(type: ConfigurationType): List<RunnerAndConfigurationSettings> {
return emptyList()
}
override fun getStructure(type: ConfigurationType): Map<String, List<RunnerAndConfigurationSettings>> {
return emptyMap()
}
override fun setTemporaryConfiguration(tempConfiguration: RunnerAndConfigurationSettings?) {}
override fun getConfig(): RunManagerConfig {
throw UnsupportedOperationException()
}
override fun createConfiguration(name: String, factory: ConfigurationFactory): RunnerAndConfigurationSettings {
throw UnsupportedOperationException()
}
override fun addConfiguration(settings: RunnerAndConfigurationSettings) {
}
override fun getBeforeRunTasks(configuration: RunConfiguration): List<BeforeRunTask<*>> {
return emptyList()
}
override fun <T : BeforeRunTask<*>> getBeforeRunTasks(taskProviderID: Key<T>): List<T> {
return emptyList()
}
override fun <T : BeforeRunTask<*>> getBeforeRunTasks(settings: RunConfiguration, taskProviderID: Key<T>): List<T> {
return emptyList()
}
override fun setBeforeRunTasks(runConfiguration: RunConfiguration, tasks: List<BeforeRunTask<*>>, addEnabledTemplateTasksIfAbsent: Boolean) {}
override fun findConfigurationByName(name: String?): RunnerAndConfigurationSettings? {
return null
}
override fun getConfigurationIcon(settings: RunnerAndConfigurationSettings): Icon? {
return null
}
override fun getConfigurationIcon(settings: RunnerAndConfigurationSettings, withLiveIndicator: Boolean): Icon? {
return null
}
override fun removeConfiguration(settings: RunnerAndConfigurationSettings?) {}
override fun refreshUsagesList(profile: RunProfile) {}
}
|
apache-2.0
|
974031aa136b399ed204be35367761d7
| 34.239669 | 144 | 0.787523 | 5.487773 | false | true | false | false |
danrien/projectBlueWater
|
projectBlueWater/src/test/java/com/lasthopesoftware/bluewater/shared/android/audiofocus/GivenAnAudioFocusRequest/AndItIsImmediatelyRejected/WhenRequestingFocus.kt
|
2
|
1545
|
package com.lasthopesoftware.bluewater.shared.android.audiofocus.GivenAnAudioFocusRequest.AndItIsImmediatelyRejected
import android.media.AudioManager
import androidx.media.AudioFocusRequestCompat
import androidx.media.AudioManagerCompat
import com.lasthopesoftware.AndroidContext
import com.lasthopesoftware.bluewater.shared.android.audiofocus.AudioFocusManagement
import com.lasthopesoftware.bluewater.shared.android.audiofocus.UnableToGrantAudioFocusException
import com.lasthopesoftware.bluewater.shared.promises.extensions.toFuture
import org.assertj.core.api.Assertions.assertThat
import org.junit.Test
import org.mockito.Mockito.*
import java.util.concurrent.ExecutionException
class WhenRequestingFocus : AndroidContext() {
companion object {
private lateinit var unableToGrantException: UnableToGrantAudioFocusException
}
override fun before() {
val audioManager = mock(AudioManager::class.java)
`when`(audioManager.requestAudioFocus(any()))
.thenReturn(AudioManager.AUDIOFOCUS_REQUEST_FAILED)
val request = AudioFocusRequestCompat.Builder(AudioManagerCompat.AUDIOFOCUS_GAIN)
.setOnAudioFocusChangeListener { }
.build()
val audioFocusManagement = AudioFocusManagement(audioManager)
try {
audioFocusManagement.promiseAudioFocus(request).toFuture().get()!!
} catch (e: ExecutionException) {
val cause = e.cause
if (cause is UnableToGrantAudioFocusException)
unableToGrantException = cause
}
}
@Test
fun thenAudioFocusIsNotGranted() {
assertThat(unableToGrantException).isNotNull
}
}
|
lgpl-3.0
|
44549dae2f9dd7ee08e633ac62586cc5
| 34.113636 | 116 | 0.82589 | 4.414286 | false | false | false | false |
TeamAmaze/AmazeFileManager
|
app/src/main/java/com/amaze/filemanager/asynchronous/asynctasks/ftp/hostcert/FtpsGetHostCertificateTaskCallable.kt
|
1
|
2553
|
/*
* Copyright (C) 2014-2022 Arpit Khurana <[email protected]>, Vishal Nehra <[email protected]>,
* Emmanuel Messulam<[email protected]>, Raymond Lai <airwave209gt at gmail.com> and Contributors.
*
* This file is part of Amaze File Manager.
*
* Amaze File Manager 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 com.amaze.filemanager.asynchronous.asynctasks.ftp.hostcert
import androidx.annotation.WorkerThread
import com.amaze.filemanager.filesystem.ftp.NetCopyClientConnectionPool
import com.amaze.filemanager.filesystem.ftp.NetCopyClientConnectionPool.CONNECT_TIMEOUT
import com.amaze.filemanager.filesystem.ftp.NetCopyClientConnectionPool.FTPS_URI_PREFIX
import com.amaze.filemanager.utils.X509CertificateUtil
import org.apache.commons.net.ftp.FTPSClient
import org.json.JSONObject
import java.util.concurrent.Callable
import java.util.concurrent.CountDownLatch
import javax.net.ssl.HostnameVerifier
open class FtpsGetHostCertificateTaskCallable(
private val hostname: String,
private val port: Int
) : Callable<JSONObject> {
@WorkerThread
override fun call(): JSONObject? {
val latch = CountDownLatch(1)
var result: JSONObject? = null
val ftpClient = createFTPClient()
ftpClient.connectTimeout = CONNECT_TIMEOUT
ftpClient.controlEncoding = Charsets.UTF_8.name()
ftpClient.hostnameVerifier = HostnameVerifier { _, session ->
if (session.peerCertificateChain.isNotEmpty()) {
val certinfo = X509CertificateUtil.parse(session.peerCertificateChain[0])
result = JSONObject(certinfo)
}
latch.countDown()
true
}
ftpClient.connect(hostname, port)
latch.await()
ftpClient.disconnect()
return result
}
protected open fun createFTPClient(): FTPSClient =
NetCopyClientConnectionPool.ftpClientFactory.create(FTPS_URI_PREFIX) as FTPSClient
}
|
gpl-3.0
|
952918e5fbf6ed71e0c4bc0320cdaa11
| 40.177419 | 107 | 0.737564 | 4.42461 | false | false | false | false |
QuickBlox/quickblox-android-sdk
|
sample-chat-kotlin/app/src/main/java/com/quickblox/sample/chat/kotlin/ui/activity/ChatActivity.kt
|
1
|
46765
|
package com.quickblox.sample.chat.kotlin.ui.activity
import android.app.Activity
import android.app.DownloadManager
import android.content.Context
import android.content.DialogInterface
import android.content.Intent
import android.net.Uri
import android.os.*
import android.text.Editable
import android.text.TextUtils
import android.text.TextWatcher
import android.util.Log
import android.view.Gravity
import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.widget.*
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.widget.PopupMenu
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.google.android.material.snackbar.Snackbar
import com.quickblox.chat.QBChatService
import com.quickblox.chat.QBMessageStatusesManager
import com.quickblox.chat.QBSystemMessagesManager
import com.quickblox.chat.exception.QBChatException
import com.quickblox.chat.listeners.QBChatDialogTypingListener
import com.quickblox.chat.listeners.QBMessageStatusListener
import com.quickblox.chat.listeners.QBSystemMessageListener
import com.quickblox.chat.model.QBAttachment
import com.quickblox.chat.model.QBChatDialog
import com.quickblox.chat.model.QBChatMessage
import com.quickblox.chat.model.QBDialogType
import com.quickblox.content.model.QBFile
import com.quickblox.core.QBEntityCallback
import com.quickblox.core.exception.QBResponseException
import com.quickblox.sample.chat.kotlin.R
import com.quickblox.sample.chat.kotlin.managers.DialogsManager
import com.quickblox.sample.chat.kotlin.ui.adapter.*
import com.quickblox.sample.chat.kotlin.ui.adapter.listeners.AttachClickListener
import com.quickblox.sample.chat.kotlin.ui.adapter.listeners.MessageLongClickListener
import com.quickblox.sample.chat.kotlin.ui.views.AttachmentPreviewAdapterView
import com.quickblox.sample.chat.kotlin.utils.SharedPrefsHelper
import com.quickblox.sample.chat.kotlin.utils.SystemPermissionHelper
import com.quickblox.sample.chat.kotlin.utils.chat.CHAT_HISTORY_ITEMS_PER_PAGE
import com.quickblox.sample.chat.kotlin.utils.chat.ChatHelper
import com.quickblox.sample.chat.kotlin.utils.imagepick.OnImagePickedListener
import com.quickblox.sample.chat.kotlin.utils.imagepick.pickAnImage
import com.quickblox.sample.chat.kotlin.utils.qb.*
import com.quickblox.sample.chat.kotlin.utils.shortToast
import com.quickblox.sample.chat.kotlin.utils.showSnackbar
import com.quickblox.users.QBUsers
import com.quickblox.users.model.QBUser
import com.timehop.stickyheadersrecyclerview.StickyRecyclerHeadersDecoration
import org.jivesoftware.smack.ConnectionListener
import org.jivesoftware.smack.SmackException
import org.jivesoftware.smack.XMPPException
import org.jivesoftware.smackx.muc.DiscussionHistory
import java.io.File
import java.util.*
import kotlin.collections.ArrayList
const val REQUEST_CODE_SELECT_PEOPLE = 752
private const val REQUEST_CODE_ATTACHMENT = 721
private const val PERMISSIONS_FOR_SAVE_FILE_IMAGE_REQUEST = 1010
const val PROPERTY_FORWARD_USER_NAME = "origin_sender_name"
const val EXTRA_DIALOG_ID = "dialogId"
const val EXTRA_IS_NEW_DIALOG = "isNewDialog"
const val IS_IN_BACKGROUND = "is_in_background"
const val ORDER_RULE = "order"
const val ORDER_VALUE_UPDATED_AT = "desc string updated_at"
const val TYPING_STATUS_DELAY = 2000L
const val TYPING_STATUS_INACTIVITY_DELAY = 10000L
private const val SEND_TYPING_STATUS_DELAY: Long = 3000L
const val MAX_ATTACHMENTS_COUNT = 1
const val MAX_MESSAGE_SYMBOLS_LENGTH = 1000
class ChatActivity : BaseActivity(), OnImagePickedListener, QBMessageStatusListener, DialogsManager.ManagingDialogsCallbacks {
private val TAG = ChatActivity::class.java.simpleName
private lateinit var progressBar: ProgressBar
private lateinit var messageEditText: EditText
private lateinit var attachmentBtnChat: ImageView
private lateinit var typingStatus: TextView
private var currentUser = QBUser()
private lateinit var attachmentPreviewContainerLayout: LinearLayout
private lateinit var chatMessagesRecyclerView: RecyclerView
private lateinit var sendMessageContainer: RelativeLayout
private lateinit var chatAdapter: ChatAdapter
private lateinit var attachmentPreviewAdapter: AttachmentPreviewAdapter
private lateinit var chatConnectionListener: ConnectionListener
private lateinit var imageAttachClickListener: ImageAttachClickListener
private lateinit var videoAttachClickListener: VideoAttachClickListener
private lateinit var fileAttachClickListener: FileAttachClickListener
private lateinit var messageLongClickListener: MessageLongClickListenerImpl
private var qbMessageStatusesManager: QBMessageStatusesManager? = null
private var chatMessageListener: ChatMessageListener = ChatMessageListener()
private var dialogsManager: DialogsManager = DialogsManager()
private var systemMessagesListener: SystemMessagesListener = SystemMessagesListener()
private var systemMessagesManager: QBSystemMessagesManager? = null
private lateinit var messagesList: MutableList<QBChatMessage>
private lateinit var qbChatDialog: QBChatDialog
private var unShownMessages: ArrayList<QBChatMessage>? = null
private var skipPagination = 0
private var checkAdapterInit: Boolean = false
companion object {
fun startForResult(activity: Activity, code: Int, dialogId: QBChatDialog) {
val intent = Intent(activity, ChatActivity::class.java)
intent.putExtra(EXTRA_DIALOG_ID, dialogId)
activity.startActivityForResult(intent, code)
}
fun startForResult(activity: Activity, code: Int, dialogId: QBChatDialog, isNewDialog: Boolean) {
val intent = Intent(activity, ChatActivity::class.java)
intent.putExtra(EXTRA_DIALOG_ID, dialogId)
intent.putExtra(EXTRA_IS_NEW_DIALOG, isNewDialog)
activity.startActivityForResult(intent, code)
}
}
public override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_chat)
SharedPrefsHelper.delete(IS_IN_BACKGROUND)
Log.v(TAG, "onCreate ChatActivity on Thread ID = " + Thread.currentThread().id)
if (!ChatHelper.isLogged()) {
reloginToChat()
}
qbChatDialog = intent.getSerializableExtra(EXTRA_DIALOG_ID) as QBChatDialog
if (ChatHelper.getCurrentUser() != null) {
currentUser = ChatHelper.getCurrentUser()!!
} else {
Log.e(TAG, "Finishing " + TAG + ". Current user is null")
finish()
}
Log.v(TAG, "Deserialized dialog = $qbChatDialog")
try {
qbChatDialog.initForChat(QBChatService.getInstance())
} catch (e: IllegalStateException) {
Log.d(TAG, "initForChat error. Error message is : " + e.toString())
Log.e(TAG, "Finishing " + TAG + ". Unable to init chat")
finish()
}
qbChatDialog.addMessageListener(chatMessageListener)
qbChatDialog.addIsTypingListener(TypingStatusListener())
initViews()
initMessagesRecyclerView()
initChatConnectionListener()
initChat()
}
override fun onSaveInstanceState(outState: Bundle, outPersistentState: PersistableBundle) {
outState.putString(EXTRA_DIALOG_ID, qbChatDialog.dialogId)
super.onSaveInstanceState(outState, outPersistentState)
}
override fun onRestoreInstanceState(savedInstanceState: Bundle) {
super.onRestoreInstanceState(savedInstanceState)
try {
val dialogId = savedInstanceState.getString(EXTRA_DIALOG_ID)!!
qbChatDialog = QbDialogHolder.getChatDialogById(dialogId)!!
} catch (e: Exception) {
Log.d(TAG, e.toString())
}
}
override fun onResumeFinished() {
if (ChatHelper.isLogged()) {
if (!::qbChatDialog.isInitialized) {
qbChatDialog = intent.getSerializableExtra(EXTRA_DIALOG_ID) as QBChatDialog
}
returnToChat()
} else {
reloginToChat()
}
}
private fun reloginToChat() {
showProgressDialog(R.string.dlg_login)
ChatHelper.loginToChat(SharedPrefsHelper.getQbUser()!!, object : QBEntityCallback<Void> {
override fun onSuccess(aVoid: Void?, bundle: Bundle?) {
returnToChat()
hideProgressDialog()
}
override fun onError(e: QBResponseException?) {
hideProgressDialog()
showErrorSnackbar(R.string.reconnect_failed, e, View.OnClickListener { reloginToChat() })
}
})
}
private fun returnToChat() {
qbChatDialog.initForChat(QBChatService.getInstance())
if (!qbChatDialog.isJoined) {
ChatHelper.join(qbChatDialog, object : QBEntityCallback<Void> {
override fun onSuccess(result: Void?, b: Bundle?) {
// Loading unread messages received in background
if (SharedPrefsHelper.get(IS_IN_BACKGROUND, false)) {
progressBar.visibility = View.VISIBLE
skipPagination = 0
checkAdapterInit = false
loadChatHistory()
}
sendMessageContainer.visibility = View.VISIBLE
returnListeners()
}
override fun onError(e: QBResponseException) {
Log.e(TAG, "Join Dialog Exception: " + e.toString())
showErrorSnackbar(R.string.error_joining_chat, e) {
returnToChat()
}
}
})
}
}
private fun returnListeners() {
if (qbChatDialog.isTypingListeners.isEmpty()) {
qbChatDialog.addIsTypingListener(TypingStatusListener())
}
dialogsManager.addManagingDialogsCallbackListener(this)
try {
systemMessagesManager = QBChatService.getInstance().systemMessagesManager
systemMessagesManager?.addSystemMessageListener(systemMessagesListener)
qbMessageStatusesManager = QBChatService.getInstance().messageStatusesManager
qbMessageStatusesManager?.addMessageStatusListener(this)
} catch (e: Exception) {
e.toString()?.let { Log.d(TAG, it) }
showErrorSnackbar(R.string.error_getting_chat_service, e, View.OnClickListener { returnListeners() })
}
chatAdapter.setAttachImageClickListener(imageAttachClickListener)
chatAdapter.setAttachVideoClickListener(videoAttachClickListener)
chatAdapter.setAttachFileClickListener(fileAttachClickListener)
chatAdapter.setMessageLongClickListener(messageLongClickListener)
ChatHelper.addConnectionListener(chatConnectionListener)
}
override fun onPause() {
super.onPause()
chatAdapter.removeClickListeners()
ChatHelper.removeConnectionListener(chatConnectionListener)
qbMessageStatusesManager?.removeMessageStatusListener(this)
SharedPrefsHelper.save(IS_IN_BACKGROUND, true)
}
override fun onDestroy() {
super.onDestroy()
systemMessagesManager?.removeSystemMessageListener(systemMessagesListener)
qbChatDialog.removeMessageListrener(chatMessageListener)
dialogsManager.removeManagingDialogsCallbackListener(this)
SharedPrefsHelper.delete(IS_IN_BACKGROUND)
}
override fun onBackPressed() {
qbChatDialog.removeMessageListrener(chatMessageListener)
sendDialogId()
super.onBackPressed()
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
menuInflater.inflate(R.menu.menu_activity_chat, menu)
val menuItemInfo = menu.findItem(R.id.menu_chat_action_info)
val menuItemLeave = menu.findItem(R.id.menu_chat_action_leave)
val menuItemDelete = menu.findItem(R.id.menu_chat_action_delete)
when (qbChatDialog.type) {
QBDialogType.GROUP -> {
menuItemDelete.isVisible = false
}
QBDialogType.PRIVATE -> {
menuItemInfo.isVisible = false
menuItemLeave.isVisible = false
}
QBDialogType.PUBLIC_GROUP -> {
menuItemInfo.isVisible = false
menuItemLeave.isVisible = false
menuItemDelete.isVisible = false
}
else -> {
}
}
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
R.id.menu_chat_action_info -> {
updateDialog()
return true
}
R.id.menu_chat_action_leave -> {
openAlertDialogLeaveGroupChat()
return true
}
R.id.menu_chat_action_delete -> {
openAlertDialogDeletePrivateChat()
return true
}
android.R.id.home -> {
onBackPressed()
return true
}
else -> return super.onOptionsItemSelected(item)
}
}
private fun openAlertDialogLeaveGroupChat() {
val alertDialogBuilder = AlertDialog.Builder(this@ChatActivity, R.style.AlertDialogStyle)
alertDialogBuilder.setTitle(getString(R.string.dlg_leave_group_dialog))
alertDialogBuilder.setMessage(getString(R.string.dlg_leave_group_question))
alertDialogBuilder.setCancelable(false)
alertDialogBuilder.setPositiveButton(getString(R.string.dlg_leave)) { dialog, which -> leaveGroupChat() }
alertDialogBuilder.setNegativeButton(getString(R.string.dlg_cancel)) { dialog, which -> }
alertDialogBuilder.create()
alertDialogBuilder.show()
}
private fun openAlertDialogDeletePrivateChat() {
val alertDialogBuilder = AlertDialog.Builder(this@ChatActivity, R.style.AlertDialogStyle)
alertDialogBuilder.setTitle(getString(R.string.dlg_delete_private_dialog))
alertDialogBuilder.setMessage(getString(R.string.dlg_delete_private_question))
alertDialogBuilder.setCancelable(false)
alertDialogBuilder.setPositiveButton(getString(R.string.dlg_delete)) { dialog, which -> deleteChat() }
alertDialogBuilder.setNegativeButton(getString(R.string.dlg_cancel)) { dialog, which -> }
alertDialogBuilder.create()
alertDialogBuilder.show()
}
private fun showPopupMenu(isIncomingMessageClicked: Boolean, view: View, chatMessage: QBChatMessage) {
val popupMenu = PopupMenu(this@ChatActivity, view)
popupMenu.menuInflater.inflate(R.menu.menu_message_longclick, popupMenu.menu)
popupMenu.gravity = Gravity.RIGHT
if (isIncomingMessageClicked || (qbChatDialog.type != QBDialogType.GROUP)) {
popupMenu.menu.removeItem(R.id.menu_message_delivered_to)
popupMenu.menu.removeItem(R.id.menu_message_viewed_by)
popupMenu.gravity = Gravity.LEFT
}
popupMenu.setOnMenuItemClickListener {
when (it.itemId) {
R.id.menu_message_forward -> {
startForwardingMessage(chatMessage)
}
R.id.menu_message_delivered_to -> {
showDeliveredToScreen(chatMessage)
}
R.id.menu_message_viewed_by -> {
Log.d(TAG, "Viewed by")
showViewedByScreen(chatMessage)
}
}
true
}
popupMenu.show()
}
private fun showFilePopup(itemViewType: Int?, attachment: QBAttachment?, view: View) {
val popupMenu = PopupMenu(this@ChatActivity, view)
popupMenu.menuInflater.inflate(R.menu.menu_file_popup, popupMenu.menu)
if (itemViewType == TYPE_TEXT_RIGHT || itemViewType == TYPE_ATTACH_RIGHT) {
popupMenu.gravity = Gravity.RIGHT
} else if (itemViewType == TYPE_TEXT_LEFT || itemViewType == TYPE_ATTACH_LEFT) {
popupMenu.gravity = Gravity.LEFT
}
popupMenu.setOnMenuItemClickListener {
when (it.itemId) {
R.id.menu_file_save -> {
saveFileToStorage(attachment)
}
}
true
}
popupMenu.show()
}
private fun saveFileToStorage(attachment: QBAttachment?) {
val file = File(application.filesDir, attachment?.name)
val url = QBFile.getPrivateUrlForUID(attachment?.id)
val request = DownloadManager.Request(Uri.parse(url))
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, file.name)
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED)
request.allowScanningByMediaScanner()
val manager = getSystemService(Context.DOWNLOAD_SERVICE) as DownloadManager
manager.enqueue(request)
}
private fun startForwardingMessage(message: QBChatMessage) {
ForwardToActivity.start(this, message)
}
private fun showDeliveredToScreen(message: QBChatMessage) {
MessageInfoActivity.start(this, message, MESSAGE_INFO_DELIVERED_TO)
}
private fun showViewedByScreen(message: QBChatMessage) {
MessageInfoActivity.start(this, message, MESSAGE_INFO_READ_BY)
}
private fun updateDialog() {
showProgressDialog(R.string.dlg_updating)
Log.d(TAG, "Starting Dialog Update")
ChatHelper.getDialogById(qbChatDialog.dialogId, object : QBEntityCallback<QBChatDialog> {
override fun onSuccess(updatedChatDialog: QBChatDialog, bundle: Bundle) {
Log.d(TAG, "Update Dialog Successful: " + updatedChatDialog.dialogId)
qbChatDialog = updatedChatDialog
hideProgressDialog()
ChatInfoActivity.start(this@ChatActivity, qbChatDialog)
}
override fun onError(e: QBResponseException) {
Log.d(TAG, "Dialog Loading Error: " + e.toString())
hideProgressDialog()
showErrorSnackbar(R.string.select_users_get_dialog_error, e, null)
}
})
}
private fun sendDialogId() {
val intent = Intent().putExtra(EXTRA_DIALOG_ID, qbChatDialog.dialogId)
setResult(Activity.RESULT_OK, intent)
}
private fun leaveGroupChat() {
showProgressDialog(R.string.dlg_loading)
dialogsManager.sendMessageLeftUser(qbChatDialog)
systemMessagesManager?.let {
dialogsManager.sendSystemMessageLeftUser(it, qbChatDialog)
}
try {
// Its a hack to give the Chat Server more time to process the message and deliver them
Thread.sleep(300)
} catch (e: InterruptedException) {
e.printStackTrace()
}
Log.d(TAG, "Leaving Dialog")
ChatHelper.exitFromDialog(qbChatDialog, object : QBEntityCallback<QBChatDialog> {
override fun onSuccess(qbDialog: QBChatDialog, bundle: Bundle?) {
Log.d(TAG, "Leaving Dialog Successful: " + qbDialog.dialogId)
hideProgressDialog()
QbDialogHolder.deleteDialog(qbDialog)
finish()
}
override fun onError(e: QBResponseException) {
Log.d(TAG, "Leaving Dialog Error: " + e.toString())
hideProgressDialog()
showErrorSnackbar(R.string.error_leave_chat, e, View.OnClickListener { leaveGroupChat() })
}
})
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
Log.d(TAG, "onActivityResult with resultCode: $resultCode requestCode: $requestCode")
if (resultCode == Activity.RESULT_OK) {
if (requestCode == REQUEST_CODE_SELECT_PEOPLE && data != null) {
progressBar.visibility = View.VISIBLE
val selectedUsers = data.getSerializableExtra(EXTRA_QB_USERS) as ArrayList<QBUser>
val existingOccupants = qbChatDialog.occupants
val newUserIds = ArrayList<Int>()
for (user in selectedUsers) {
if (!existingOccupants.contains(user.id)) {
newUserIds.add(user.id)
}
}
ChatHelper.getDialogById(qbChatDialog.dialogId, object : QBEntityCallback<QBChatDialog> {
override fun onSuccess(qbChatDialog: QBChatDialog, p1: Bundle?) {
progressBar.visibility = View.GONE
dialogsManager.sendMessageAddedUsers(qbChatDialog, newUserIds)
systemMessagesManager?.let {
dialogsManager.sendSystemMessageAddedUser(it, qbChatDialog, newUserIds)
}
qbChatDialog.let {
[email protected] = it
}
updateDialog(selectedUsers)
}
override fun onError(e: QBResponseException?) {
progressBar.visibility = View.GONE
showErrorSnackbar(R.string.update_dialog_error, e, null)
}
})
}
}
}
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
if (requestCode == PERMISSIONS_FOR_SAVE_FILE_IMAGE_REQUEST && grantResults.size > 0 && grantResults[0] != -1) {
openImagePicker()
}
}
override fun onImagePicked(requestCode: Int, file: File) {
when (requestCode) {
REQUEST_CODE_ATTACHMENT -> {
attachmentPreviewAdapter.add(file)
}
}
}
override fun onImagePickError(requestCode: Int, e: Exception) {
showErrorSnackbar(0, e, null)
val rootView = window.decorView.findViewById<View>(android.R.id.content)
showSnackbar(rootView, 0, e, R.string.dlg_hide, object : View.OnClickListener {
override fun onClick(v: View?) {
Snackbar.SnackbarLayout.GONE
}
})
}
override fun onImagePickClosed(ignored: Int) {
}
fun onSendChatClick(view: View) {
try {
qbChatDialog.sendStopTypingNotification()
} catch (e: XMPPException) {
Log.d(TAG, e.toString())
} catch (e: SmackException.NotConnectedException) {
Log.d(TAG, e.toString())
}
val totalAttachmentsCount = attachmentPreviewAdapter.count
val uploadedAttachments = attachmentPreviewAdapter.uploadedAttachments
if (uploadedAttachments.isNotEmpty()) {
if (uploadedAttachments.size == totalAttachmentsCount) {
for (attachment in uploadedAttachments) {
sendChatMessage(null, attachment)
}
} else {
shortToast(R.string.chat_wait_for_attachments_to_upload)
}
}
var text = messageEditText.text.toString().trim { it <= ' ' }
if (!TextUtils.isEmpty(text)) {
if (text.length > MAX_MESSAGE_SYMBOLS_LENGTH) {
text = text.substring(0, MAX_MESSAGE_SYMBOLS_LENGTH)
}
sendChatMessage(text, null)
}
}
fun showMessage(message: QBChatMessage) {
if (isAdapterConnected()) {
chatAdapter.addMessage(message)
scrollMessageListDown()
} else {
delayShowMessage(message)
}
}
private fun isAdapterConnected(): Boolean {
return checkAdapterInit
}
private fun delayShowMessage(message: QBChatMessage) {
if (unShownMessages == null) {
unShownMessages = ArrayList()
}
unShownMessages!!.add(message)
}
private fun initViews() {
supportActionBar?.title = ""
supportActionBar?.setDisplayHomeAsUpEnabled(true)
typingStatus = findViewById(R.id.tv_typing_status)
messageEditText = findViewById(R.id.et_chat_message)
messageEditText.addTextChangedListener(TextInputWatcher())
progressBar = findViewById(R.id.progress_chat)
attachmentPreviewContainerLayout = findViewById(R.id.ll_attachment_preview_container)
sendMessageContainer = findViewById(R.id.rl_chat_send_container)
attachmentBtnChat = findViewById(R.id.iv_chat_attachment)
attachmentBtnChat.setOnClickListener {
if (attachmentPreviewAdapter.count >= MAX_ATTACHMENTS_COUNT) {
shortToast(R.string.error_attachment_count)
} else {
openImagePicker()
}
}
attachmentPreviewAdapter = AttachmentPreviewAdapter(this, object : AttachmentPreviewAdapter.AttachmentCountChangedListener {
override fun onAttachmentCountChanged(count: Int) {
val visiblePreview = when (count) {
0 -> View.GONE
else -> View.VISIBLE
}
attachmentPreviewContainerLayout.visibility = visiblePreview
}
}, object : AttachmentPreviewAdapter.AttachmentUploadErrorListener {
override fun onAttachmentUploadError(e: QBResponseException) {
showErrorSnackbar(0, e, View.OnClickListener { v ->
pickAnImage(this@ChatActivity, REQUEST_CODE_ATTACHMENT)
})
}
})
val previewAdapterView = findViewById<AttachmentPreviewAdapterView>(R.id.adapter_attachment_preview)
previewAdapterView.setAdapter(attachmentPreviewAdapter)
}
private fun openImagePicker() {
val permissionHelper = SystemPermissionHelper(this)
if (permissionHelper.isSaveImagePermissionGranted()) {
pickAnImage(this, REQUEST_CODE_ATTACHMENT)
} else {
permissionHelper.requestPermissionsForSaveFileImage()
}
}
private fun initMessagesRecyclerView() {
chatMessagesRecyclerView = findViewById(R.id.rv_chat_messages)
val layoutManager = LinearLayoutManager(this)
layoutManager.stackFromEnd = true
chatMessagesRecyclerView.layoutManager = layoutManager
messagesList = ArrayList()
chatAdapter = ChatAdapter(this, qbChatDialog, messagesList)
chatAdapter.setPaginationHistoryListener(PaginationListener())
chatMessagesRecyclerView.addItemDecoration(StickyRecyclerHeadersDecoration(chatAdapter))
chatMessagesRecyclerView.adapter = chatAdapter
imageAttachClickListener = ImageAttachClickListener()
videoAttachClickListener = VideoAttachClickListener()
fileAttachClickListener = FileAttachClickListener()
messageLongClickListener = MessageLongClickListenerImpl()
}
private fun sendChatMessage(text: String?, attachment: QBAttachment?) {
if (ChatHelper.isLogged()) {
val chatMessage = QBChatMessage()
attachment?.let {
chatMessage.addAttachment(it)
} ?: run {
chatMessage.body = text
}
chatMessage.setSaveToHistory(true)
chatMessage.dateSent = System.currentTimeMillis() / 1000
chatMessage.isMarkable = true
if (qbChatDialog.type != QBDialogType.PRIVATE && !qbChatDialog.isJoined) {
qbChatDialog.join(DiscussionHistory())
shortToast(R.string.chat_still_joining)
return
}
try {
Log.d(TAG, "Sending Message with ID: " + chatMessage.id)
qbChatDialog.sendMessage(chatMessage)
if (qbChatDialog.type == QBDialogType.PRIVATE) {
showMessage(chatMessage)
}
attachment?.let {
attachmentPreviewAdapter.remove(it)
} ?: run {
messageEditText.setText("")
}
} catch (e: SmackException.NotConnectedException) {
Log.w(TAG, e)
shortToast(R.string.chat_error_send_message)
}
} else {
showProgressDialog(R.string.dlg_login)
Log.d(TAG, "Relogin to Chat")
ChatHelper.loginToChat(currentUser,
object : QBEntityCallback<Void> {
override fun onSuccess(p0: Void?, p1: Bundle?) {
Log.d(TAG, "Relogin Successful")
sendChatMessage(text, attachment)
hideProgressDialog()
}
override fun onError(e: QBResponseException) {
Log.d(TAG, "Relogin Error: " + e.toString())
hideProgressDialog()
shortToast(R.string.chat_send_message_error)
}
})
}
}
private fun initChat() {
when (qbChatDialog.type) {
QBDialogType.GROUP,
QBDialogType.PUBLIC_GROUP -> joinGroupChat()
QBDialogType.PRIVATE -> {
loadDialogUsers()
sendMessageContainer.visibility = View.VISIBLE
}
else -> {
shortToast(String.format("%s %s", getString(R.string.chat_unsupported_type), qbChatDialog.type.name))
finish()
}
}
}
private fun joinGroupChat() {
progressBar.visibility = View.VISIBLE
ChatHelper.join(qbChatDialog, object : QBEntityCallback<Void> {
override fun onSuccess(result: Void?, b: Bundle?) {
Log.d(TAG, "Joined to Dialog Successful")
notifyUsersAboutCreatingDialog()
hideProgressDialog()
sendMessageContainer.visibility = View.VISIBLE
loadDialogUsers()
}
override fun onError(e: QBResponseException) {
Log.d(TAG, "Joining Dialog Error: " + e.toString())
/*progressBar.visibility = View.GONE
showErrorSnackbar(R.string.connection_error, e, null)*/
}
})
}
private fun notifyUsersAboutCreatingDialog() {
if (intent.getBooleanExtra(EXTRA_IS_NEW_DIALOG, false)) {
dialogsManager.sendMessageCreatedDialog(qbChatDialog)
intent.removeExtra(EXTRA_IS_NEW_DIALOG)
}
}
private fun updateDialog(selectedUsers: ArrayList<QBUser>) {
ChatHelper.updateDialogUsers(qbChatDialog, selectedUsers, object : QBEntityCallback<QBChatDialog> {
override fun onSuccess(dialog: QBChatDialog, args: Bundle?) {
qbChatDialog = dialog
loadDialogUsers()
}
override fun onError(e: QBResponseException) {
showErrorSnackbar(R.string.chat_info_add_people_error, e, View.OnClickListener { updateDialog(selectedUsers) })
}
})
}
private fun loadDialogUsers() {
ChatHelper.getUsersFromDialog(qbChatDialog, object : QBEntityCallback<ArrayList<QBUser>> {
override fun onSuccess(users: ArrayList<QBUser>, bundle: Bundle?) {
setChatNameToActionBar()
loadChatHistory()
}
override fun onError(e: QBResponseException) {
showErrorSnackbar(R.string.chat_load_users_error, e, View.OnClickListener { loadDialogUsers() })
}
})
}
private fun setChatNameToActionBar() {
val chatName = getDialogName(qbChatDialog)
supportActionBar?.title = chatName
supportActionBar?.setDisplayHomeAsUpEnabled(true)
supportActionBar?.setHomeButtonEnabled(true)
}
private fun loadChatHistory() {
ChatHelper.loadChatHistory(qbChatDialog, skipPagination, object : QBEntityCallback<ArrayList<QBChatMessage>> {
override fun onSuccess(messages: ArrayList<QBChatMessage>, args: Bundle?) {
// The newest messages should be in the end of list,
// so we need to reverse list to show messages in the right order
messages.reverse()
if (checkAdapterInit) {
chatAdapter.addMessages(messages)
} else {
checkAdapterInit = true
chatAdapter.setMessages(messages)
addDelayedMessagesToAdapter()
}
if (skipPagination == 0) {
scrollMessageListDown()
}
skipPagination += CHAT_HISTORY_ITEMS_PER_PAGE
progressBar.visibility = View.GONE
}
override fun onError(e: QBResponseException) {
progressBar.visibility = View.GONE
showErrorSnackbar(R.string.connection_error, e, null)
}
})
}
private fun addDelayedMessagesToAdapter() {
unShownMessages?.let {
if (it.isNotEmpty()) {
val chatList = chatAdapter.getMessages()
for (message in it) {
if (!chatList.contains(message)) {
chatAdapter.addMessage(message)
}
}
}
}
}
private fun scrollMessageListDown() {
chatMessagesRecyclerView.scrollToPosition(messagesList.size - 1)
}
private fun deleteChat() {
ChatHelper.deleteDialog(qbChatDialog, object : QBEntityCallback<Void> {
override fun onSuccess(aVoid: Void?, bundle: Bundle?) {
QbDialogHolder.deleteDialog(qbChatDialog)
setResult(Activity.RESULT_OK)
finish()
}
override fun onError(e: QBResponseException) {
showErrorSnackbar(R.string.dialogs_deletion_error, e, View.OnClickListener { deleteChat() })
}
})
}
private fun initChatConnectionListener() {
val rootView: View = findViewById(R.id.rv_chat_messages)
chatConnectionListener = object : VerboseQbChatConnectionListener(rootView) {
override fun reconnectionSuccessful() {
super.reconnectionSuccessful()
skipPagination = 0
if (qbChatDialog.type == QBDialogType.GROUP || qbChatDialog.type == QBDialogType.PUBLIC_GROUP) {
checkAdapterInit = false
// Join active room if we're in Group Chat
runOnUiThread {
joinGroupChat()
}
}
}
}
}
override fun processMessageDelivered(messageID: String, dialogID: String, userID: Int?) {
if (qbChatDialog.dialogId == dialogID && userID != null) {
chatAdapter.updateStatusDelivered(messageID, userID)
}
}
override fun processMessageRead(messageID: String, dialogID: String, userID: Int?) {
if (qbChatDialog.dialogId == dialogID && userID != null) {
chatAdapter.updateStatusRead(messageID, userID)
}
}
override fun onDialogCreated(chatDialog: QBChatDialog) {
}
override fun onDialogUpdated(chatDialog: String) {
}
override fun onNewDialogLoaded(chatDialog: QBChatDialog) {
}
private inner class ChatMessageListener : QbChatDialogMessageListenerImpl() {
override fun processMessage(s: String, qbChatMessage: QBChatMessage, integer: Int?) {
Log.d(TAG, "Processing Received Message: " + qbChatMessage.body)
showMessage(qbChatMessage)
}
}
private inner class SystemMessagesListener : QBSystemMessageListener {
override fun processMessage(qbChatMessage: QBChatMessage) {
Log.d(TAG, "System Message Received: " + qbChatMessage.id)
dialogsManager.onSystemMessageReceived(qbChatMessage)
}
override fun processError(e: QBChatException?, qbChatMessage: QBChatMessage?) {
Log.d(TAG, "System Messages Error: " + e?.message + "With MessageID: " + qbChatMessage?.id)
}
}
private inner class ImageAttachClickListener : AttachClickListener {
override fun onAttachmentClicked(itemViewType: Int?, view: View, attachment: QBAttachment) {
val url = QBFile.getPrivateUrlForUID(attachment.id)
AttachmentImageActivity.start(this@ChatActivity, url)
}
}
private inner class VideoAttachClickListener : AttachClickListener {
override fun onAttachmentClicked(itemViewType: Int?, view: View, attachment: QBAttachment) {
val url = QBFile.getPrivateUrlForUID(attachment.id)
AttachmentVideoActivity.start(this@ChatActivity, attachment.name, url)
}
}
private inner class FileAttachClickListener : AttachClickListener {
override fun onAttachmentClicked(itemViewType: Int?, view: View, attachment: QBAttachment) {
showFilePopup(itemViewType, attachment, view)
}
}
private inner class MessageLongClickListenerImpl : MessageLongClickListener {
override fun onMessageLongClicked(itemViewType: Int?, view: View, chatMessage: QBChatMessage?) {
val vibrator = getSystemService(Context.VIBRATOR_SERVICE) as Vibrator
vibrator.vibrate(80)
if (chatMessage != null) {
if (itemViewType == TYPE_TEXT_RIGHT || itemViewType == TYPE_ATTACH_RIGHT) {
Log.d(TAG, "Outgoing message LongClicked")
showPopupMenu(false, view, chatMessage)
} else if (itemViewType == TYPE_TEXT_LEFT || itemViewType == TYPE_ATTACH_LEFT) {
Log.d(TAG, "Incoming message LongClicked")
showPopupMenu(true, view, chatMessage)
}
}
}
}
private inner class PaginationListener : PaginationHistoryListener {
override fun downloadMore() {
Log.w(TAG, "Download More")
loadChatHistory()
}
}
private inner class TypingStatusListener : QBChatDialogTypingListener {
private var currentTypingUserNames = ArrayList<String>()
private val usersTimerMap = HashMap<Int, Timer>()
override fun processUserIsTyping(dialogID: String?, userID: Int?) {
val currentUserID = currentUser.id
if (dialogID != null && dialogID == qbChatDialog.dialogId && userID != null && userID != currentUserID) {
Log.d(TAG, "User $userID is typing")
updateTypingInactivityTimer(dialogID, userID)
val user = QbUsersHolder.getUserById(userID)
if (user != null && user.fullName != null) {
Log.d(TAG, "User $userID is in UsersHolder")
addUserToTypingList(user)
} else {
Log.d(TAG, "User $userID not in UsersHolder")
QBUsers.getUser(userID).performAsync(object : QBEntityCallback<QBUser> {
override fun onSuccess(qbUser: QBUser?, bundle: Bundle?) {
qbUser?.let {
Log.d(TAG, "User " + qbUser.id + " Loaded from Server")
QbUsersHolder.putUser(qbUser)
addUserToTypingList(qbUser)
}
}
override fun onError(e: QBResponseException?) {
Log.d(TAG, "Loading User Error: " + e?.message)
}
})
}
}
}
private fun addUserToTypingList(user: QBUser) {
val userName = if (TextUtils.isEmpty(user.fullName)) user.login else user.fullName
if (!TextUtils.isEmpty(userName) && !currentTypingUserNames.contains(userName) && usersTimerMap.containsKey(user.id)) {
currentTypingUserNames.add(userName)
}
typingStatus.text = makeStringFromNames()
typingStatus.visibility = View.VISIBLE
}
override fun processUserStopTyping(dialogID: String?, userID: Int?) {
val currentUserID = currentUser.id
if (dialogID != null && dialogID == qbChatDialog.dialogId && userID != null && userID != currentUserID) {
Log.d(TAG, "User $userID stopped typing")
stopInactivityTimer(userID)
val user = QbUsersHolder.getUserById(userID)
if (user != null ) {
removeUserFromTypingList(user)
}
}
}
private fun removeUserFromTypingList(user: QBUser) {
val userName = user.fullName
userName?.let {
if (currentTypingUserNames.contains(userName)) {
currentTypingUserNames.remove(userName)
}
}
typingStatus.text = makeStringFromNames()
if (makeStringFromNames().isEmpty()) {
typingStatus.visibility = View.GONE
}
}
private fun updateTypingInactivityTimer(dialogID: String, userID: Int) {
stopInactivityTimer(userID)
val timer = Timer()
timer.schedule(object : TimerTask() {
override fun run() {
Log.d("Typing Status", "User with ID $userID Did not refresh typing status. Processing stop typing")
runOnUiThread {
processUserStopTyping(dialogID, userID)
}
}
}, TYPING_STATUS_INACTIVITY_DELAY)
usersTimerMap.put(userID, timer)
}
private fun stopInactivityTimer(userID: Int?) {
if (usersTimerMap.get(userID) != null) {
try {
usersTimerMap.get(userID)!!.cancel()
} catch (ignored: NullPointerException) {
} finally {
usersTimerMap.remove(userID)
}
}
}
private fun makeStringFromNames(): String {
var result = ""
val usersCount = currentTypingUserNames.size
if (usersCount == 1) {
val firstUser = currentTypingUserNames.get(0)
if (firstUser.length <= 20) {
result = firstUser + " " + getString(R.string.typing_postfix_singular)
} else {
result = firstUser.subSequence(0, 19).toString() +
getString(R.string.typing_ellipsis) +
" " + getString(R.string.typing_postfix_singular)
}
} else if (usersCount == 2) {
var firstUser = currentTypingUserNames.get(0)
var secondUser = currentTypingUserNames.get(1)
if ((firstUser + secondUser).length > 20) {
if (firstUser.length >= 10) {
firstUser = firstUser.subSequence(0, 9).toString() + getString(R.string.typing_ellipsis)
}
if (secondUser.length >= 10) {
secondUser = secondUser.subSequence(0, 9).toString() + getString(R.string.typing_ellipsis)
}
}
result = firstUser + " and " + secondUser + " " + getString(R.string.typing_postfix_plural)
} else if (usersCount > 2) {
var firstUser = currentTypingUserNames.get(0)
var secondUser = currentTypingUserNames.get(1)
val thirdUser = currentTypingUserNames.get(2)
if ((firstUser + secondUser + thirdUser).length <= 20) {
result = firstUser + ", " + secondUser + " and " + thirdUser + " " + getString(R.string.typing_postfix_plural)
} else if ((firstUser + secondUser).length <= 20) {
result = firstUser + ", " + secondUser + " and " + (currentTypingUserNames.size - 2).toString() + " more " + getString(R.string.typing_postfix_plural)
} else {
if (firstUser.length >= 10) {
firstUser = firstUser.subSequence(0, 9).toString() + getString(R.string.typing_ellipsis)
}
if (secondUser.length >= 10) {
secondUser = secondUser.subSequence(0, 9).toString() + getString(R.string.typing_ellipsis)
}
result = firstUser + ", " + secondUser +
" and " + (currentTypingUserNames.size - 2).toString() + " more " + getString(R.string.typing_postfix_plural)
}
}
return result
}
}
private inner class TextInputWatcher : TextWatcher {
private var timer = Timer()
private var lastSendTime: Long = 0L
override fun beforeTextChanged(charSequence: CharSequence?, start: Int, count: Int, after: Int) {
}
override fun onTextChanged(charSequence: CharSequence?, start: Int, before: Int, count: Int) {
if (SystemClock.uptimeMillis() - lastSendTime > SEND_TYPING_STATUS_DELAY) {
lastSendTime = SystemClock.uptimeMillis()
try {
qbChatDialog.sendIsTypingNotification()
} catch (e: XMPPException) {
Log.d(TAG, e.toString())
} catch (e: SmackException.NotConnectedException) {
Log.d(TAG, e.toString())
}
}
}
override fun afterTextChanged(s: Editable?) {
timer.cancel()
timer = Timer()
timer.schedule(object : TimerTask() {
override fun run() {
try {
qbChatDialog.sendStopTypingNotification()
} catch (e: XMPPException) {
Log.d(TAG, e.toString())
} catch (e: SmackException.NotConnectedException) {
Log.d(TAG, e.toString())
}
}
}, TYPING_STATUS_DELAY)
}
}
}
|
bsd-3-clause
|
080967c5237bb2028e192471e6e4c03c
| 39.950963 | 170 | 0.614648 | 5.078736 | false | false | false | false |
tasks/tasks
|
app/src/main/java/org/tasks/data/GoogleTaskListDao.kt
|
1
|
3225
|
package org.tasks.data
import androidx.lifecycle.LiveData
import androidx.room.*
import com.todoroo.astrid.api.FilterListItem.NO_ORDER
import org.tasks.filters.GoogleTaskFilters
import org.tasks.time.DateTimeUtils.currentTimeMillis
@Dao
interface GoogleTaskListDao {
@Query("SELECT * FROM google_task_accounts WHERE gta_id = :id")
fun watchAccount(id: Long): LiveData<GoogleTaskAccount>
@Query("SELECT COUNT(*) FROM google_task_accounts")
suspend fun accountCount(): Int
@Query("SELECT * FROM google_task_accounts")
suspend fun getAccounts(): List<GoogleTaskAccount>
@Query("SELECT * FROM google_task_accounts")
fun watchAccounts(): LiveData<List<GoogleTaskAccount>>
@Query("SELECT * FROM google_task_accounts WHERE gta_account = :account COLLATE NOCASE LIMIT 1")
suspend fun getAccount(account: String): GoogleTaskAccount?
@Query("SELECT * FROM google_task_lists WHERE gtl_id = :id")
suspend fun getById(id: Long): GoogleTaskList?
@Query("SELECT * FROM google_task_lists WHERE gtl_account = :account ORDER BY gtl_title ASC")
suspend fun getLists(account: String): List<GoogleTaskList>
@Query("SELECT * FROM google_task_lists WHERE gtl_remote_id = :remoteId LIMIT 1")
suspend fun getByRemoteId(remoteId: String): GoogleTaskList?
@Query("SELECT * FROM google_task_lists WHERE gtl_remote_id IN (:remoteIds)")
suspend fun getByRemoteId(remoteIds: List<String>): List<GoogleTaskList>
@Query("SELECT * FROM google_task_lists")
fun subscribeToLists(): LiveData<List<GoogleTaskList>>
@Query("SELECT * FROM google_task_lists WHERE gtl_remote_id = :remoteId AND IFNULL(gtl_account, '') = ''")
suspend fun findExistingList(remoteId: String): GoogleTaskList?
@Query("SELECT * FROM google_task_lists")
suspend fun getAllLists(): List<GoogleTaskList>
@Query("UPDATE google_task_lists SET gtl_last_sync = 0 WHERE gtl_account = :account")
suspend fun resetLastSync(account: String)
@Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun insertOrReplace(googleTaskList: GoogleTaskList): Long
@Insert
suspend fun insert(googleTaskList: GoogleTaskList): Long
@Insert
suspend fun insert(googleTaskAccount: GoogleTaskAccount)
@Update
suspend fun update(account: GoogleTaskAccount)
@Update
suspend fun update(list: GoogleTaskList)
@Query("SELECT google_task_lists.*, COUNT(tasks._id) AS count"
+ " FROM google_task_lists "
+ " LEFT JOIN google_tasks ON google_tasks.gt_list_id = google_task_lists.gtl_remote_id"
+ " LEFT JOIN tasks ON google_tasks.gt_task = tasks._id AND tasks.deleted = 0 AND tasks.completed = 0 AND tasks.hideUntil < :now AND gt_deleted = 0"
+ " WHERE google_task_lists.gtl_account = :account"
+ " GROUP BY google_task_lists.gtl_remote_id")
suspend fun getGoogleTaskFilters(account: String, now: Long = currentTimeMillis()): List<GoogleTaskFilters>
@Query("UPDATE google_task_lists SET gtl_remote_order = $NO_ORDER")
suspend fun resetOrders()
@Query("UPDATE google_task_lists SET gtl_remote_order = :order WHERE gtl_id = :id")
suspend fun setOrder(id: Long, order: Int)
}
|
gpl-3.0
|
2e53ccb5fd9130507ad63a0a7ed29223
| 40.358974 | 160 | 0.715349 | 3.909091 | false | false | false | false |
FranPregernik/radarsimulator
|
designer/src/main/kotlin/hr/franp/rsim/MovingTargetSelectorView.kt
|
1
|
2646
|
package hr.franp.rsim
import hr.franp.rsim.models.*
import javafx.scene.control.*
import org.controlsfx.glyphfont.*
import org.controlsfx.glyphfont.FontAwesome.Glyph.*
import tornadofx.*
class MovingTargetSelectorView : View() {
private val designerController: DesignerController by inject()
private val simulatorController: SimulatorController by inject()
private var fontAwesome = GlyphFontRegistry.font("FontAwesome")
private var targetSelector by singleAssign<ComboBox<MovingTarget>>()
override val root = toolbar {
label("Target") {
tooltip("Select target to edit")
setOnMouseClicked {
targetSelector.selectionModel.clearSelection()
designerController.selectedMovingTargetProperty.set(null)
}
}
targetSelector = combobox<MovingTarget> {
designerController.scenarioProperty.addListener { _, _, _ ->
itemsProperty().bind(designerController.scenario.movingTargetsProperty())
}
itemsProperty().bind(designerController.scenario.movingTargetsProperty())
// Update the target inside the view model on selection change
valueProperty().bindBidirectional(designerController.selectedMovingTargetProperty)
}
button("", fontAwesome.create(FontAwesome.Glyph.PLUS)) {
tooltip("Adds a new target")
disableProperty().bind(
designerController.calculatingHitsProperty.or(
simulatorController.simulationRunningProperty
)
)
setOnAction {
val newMovingTarget = MovingTarget().apply {
name = "T${designerController.scenario.movingTargets.size + 1}"
}
designerController.scenario.movingTargets.add(newMovingTarget)
targetSelector.selectionModel.select(newMovingTarget)
}
}
button("", fontAwesome.create(TRASH)) {
tooltip("Removes the currently selected target")
disableProperty().bind(
designerController.calculatingHitsProperty
.or(simulatorController.simulationRunningProperty)
.or(designerController.selectedMovingTargetProperty.isNull)
)
setOnAction {
designerController.scenario.movingTargets.remove(designerController.selectedMovingTarget)
targetSelector.selectionModel.clearSelection()
designerController.selectedMovingTargetProperty.set(null)
}
}
}
}
|
apache-2.0
|
e92b3c98e46fe15fab97ab965f1f4cdf
| 36.267606 | 105 | 0.641345 | 5.54717 | false | false | false | false |
ibaton/3House
|
mobile/src/main/java/treehou/se/habit/ui/bindings/BindingsFragment.kt
|
1
|
5323
|
package treehou.se.habit.ui.bindings
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.support.v7.widget.DefaultItemAnimator
import android.support.v7.widget.GridLayoutManager
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.crashlytics.android.Crashlytics
import com.google.gson.reflect.TypeToken
import com.trello.rxlifecycle2.components.support.RxFragment
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import io.realm.Realm
import kotlinx.android.synthetic.main.fragment_bindings_list.*
import se.treehou.ng.ohcommunicator.connector.models.OHBinding
import se.treehou.ng.ohcommunicator.util.GsonHelper
import treehou.se.habit.R
import treehou.se.habit.connector.models.Binding
import treehou.se.habit.core.db.model.ServerDB
import treehou.se.habit.ui.adapter.BindingAdapter
import treehou.se.habit.util.ConnectionFactory
import treehou.se.habit.util.Constants
import treehou.se.habit.util.Util
import treehou.se.habit.util.logging.Logger
import java.util.*
import javax.inject.Inject
class BindingsFragment : RxFragment() {
@Inject lateinit var connectionFactory: ConnectionFactory
@Inject lateinit var logger: Logger
private var bindingAdapter: BindingAdapter? = null
private var server: ServerDB? = null
private var container: ViewGroup? = null
private var bindings: List<OHBinding> = ArrayList()
private var realm: Realm? = null
override fun onCreate(savedInstanceState: Bundle?) {
Util.getApplicationComponent(this).inject(this)
Crashlytics.setString(Constants.FIREABASE_DEBUG_KEY_FRAGMENT, javaClass.name)
realm = Realm.getDefaultInstance()
if (arguments != null) {
if (arguments!!.containsKey(ARG_SERVER)) {
val serverId = arguments!!.getLong(ARG_SERVER)
server = Realm.getDefaultInstance().where(ServerDB::class.java).equalTo("id", serverId).findFirst()
}
}
if (savedInstanceState != null) {
if (savedInstanceState.containsKey(STATE_BINDINGS)) {
bindings = GsonHelper.createGsonBuilder().fromJson(savedInstanceState.getString(STATE_BINDINGS), object : TypeToken<List<Binding>>() {
}.type)
}
}
super.onCreate(savedInstanceState)
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View? {
val rootView = inflater.inflate(R.layout.fragment_bindings_list, container, false)
this.container = container
val actionBar = (activity as AppCompatActivity).supportActionBar
actionBar?.setTitle(R.string.bindings)
setHasOptionsMenu(true)
return rootView
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
bindingAdapter = BindingAdapter()
val listener = object : BindingAdapter.ItemClickListener {
override fun onClick(binding: OHBinding) {
openBinding(binding)
}
}
bindingAdapter!!.setItemClickListener(listener)
val gridLayoutManager = GridLayoutManager(activity, 1)
lstBinding.layoutManager = gridLayoutManager
lstBinding.itemAnimator = DefaultItemAnimator()
lstBinding.adapter = bindingAdapter
bindingAdapter!!.setBindings(bindings)
}
/**
* Open up binding page.
* @param binding the binding to show.
*/
private fun openBinding(binding: OHBinding) {
val fragment = BindingFragment.newInstance(binding)
activity!!.supportFragmentManager.beginTransaction()
.replace(this.container!!.id, fragment)
.addToBackStack(null)
.commit()
}
override fun onResume() {
super.onResume()
val serverHandler = connectionFactory.createServerHandler(server!!.toGeneric(), activity)
serverHandler.requestBindingsRx()
.compose(bindToLifecycle())
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe({ bindings ->
Log.d(TAG, "onUpdate " + bindings)
bindingAdapter!!.setBindings(bindings)
}, { logger.e(TAG, "request bindings failed", it) })
}
override fun onDestroy() {
super.onDestroy()
realm!!.close()
}
override fun onSaveInstanceState(outState: Bundle) {
outState.putString(STATE_BINDINGS, GsonHelper.createGsonBuilder().toJson(bindings))
super.onSaveInstanceState(outState)
}
companion object {
private val TAG = BindingsFragment::class.java.simpleName
private val ARG_SERVER = "ARG_SERVER"
private val STATE_BINDINGS = "STATE_BINDINGS"
fun newInstance(serverId: Long): BindingsFragment {
val fragment = BindingsFragment()
val args = Bundle()
args.putLong(ARG_SERVER, serverId)
fragment.arguments = args
return fragment
}
}
}// Required empty public constructor
|
epl-1.0
|
3f54b0ea9c66865b11266e73752f7178
| 33.564935 | 150 | 0.680068 | 4.942433 | false | false | false | false |
ibaton/3House
|
mobile/src/main/java/treehou/se/habit/ui/widget/WidgetColorpickerFactory.kt
|
1
|
5371
|
package treehou.se.habit.ui.widget
import android.annotation.SuppressLint
import android.content.Intent
import android.graphics.Color
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageButton
import android.widget.Toast
import se.treehou.ng.ohcommunicator.connector.models.OHItem
import se.treehou.ng.ohcommunicator.connector.models.OHLinkedPage
import se.treehou.ng.ohcommunicator.connector.models.OHServer
import se.treehou.ng.ohcommunicator.connector.models.OHWidget
import se.treehou.ng.ohcommunicator.services.IServerHandler
import se.treehou.ng.ohcommunicator.util.GsonHelper
import treehou.se.habit.R
import treehou.se.habit.connector.Constants
import treehou.se.habit.ui.adapter.WidgetAdapter
import treehou.se.habit.ui.colorpicker.ColorpickerActivity
import treehou.se.habit.util.logging.Logger
import javax.inject.Inject
class WidgetColorpickerFactory @Inject constructor() : WidgetFactory {
@Inject lateinit var logger: Logger
@Inject lateinit var server: OHServer
@Inject lateinit var page: OHLinkedPage
@Inject lateinit var serverHandler: IServerHandler
override fun createViewHolder(parent: ViewGroup): WidgetAdapter.WidgetViewHolder {
val view = LayoutInflater.from(parent.context).inflate(R.layout.widget_color_picker, parent, false)
return ColorPickerWidgetViewHolder(view)
}
inner class ColorPickerWidgetViewHolder(view: View) : WidgetBaseHolder(view, server, page) {
val incrementButton: ImageButton = view.findViewById(R.id.incrementButton)
val decrementButton: ImageButton = view.findViewById(R.id.decrementButton)
init {
setupOpenColorPickerListener()
}
override fun bind(itemWidget: WidgetAdapter.WidgetItem) {
super.bind(itemWidget)
setupIncrementDecrementButtons()
}
private fun getColor(): Int {
return if (widget.item != null && widget.item.state != null) {
val sHSV = widget.item.state.split(",".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()
if (sHSV.size == 3) {
val hSV = floatArrayOf(java.lang.Float.valueOf(sHSV[0])!!, java.lang.Float.valueOf(sHSV[1])!!, java.lang.Float.valueOf(sHSV[2])!!)
Color.HSVToColor(hSV)
} else{
Color.TRANSPARENT
}
} else {
Color.TRANSPARENT
}
}
private fun setupOpenColorPickerListener(){
val context = itemView.context
itemView.setOnClickListener({
val color = getColor()
if (widget.item != null) {
val intent = Intent(context, ColorpickerActivity::class.java)
val gson = GsonHelper.createGsonBuilder()
intent.putExtra(ColorpickerActivity.EXTRA_SERVER, server.id)
intent.putExtra(ColorpickerActivity.EXTRA_WIDGET, gson.toJson(widget))
intent.putExtra(ColorpickerActivity.EXTRA_COLOR, color)
context.startActivity(intent)
} else {
Toast.makeText(context, context.getString(R.string.item_missing), Toast.LENGTH_SHORT).show()
Log.d(TAG, "WidgetFactory doesn't contain item")
}
})
}
@SuppressLint("ClickableViewAccessibility")
private fun setupIncrementDecrementButtons(){
val item: OHItem? = widget.item;
if(item != null){
incrementButton.setOnTouchListener(HoldListener(
object : HoldListener.OnTickListener {
override fun onTick(tick: Int) {
if (tick > 0) {
serverHandler.sendCommand(item.name, Constants.COMMAND_INCREMENT)
}
}
}
, object : HoldListener.OnReleaseListener {
override fun onRelease(tick: Int) {
if (tick <= 0) {
serverHandler.sendCommand(item.name, Constants.COMMAND_ON)
}
}
}))
decrementButton.setOnTouchListener(HoldListener(
object : HoldListener.OnTickListener {
override fun onTick(tick: Int) {
if (tick > 0) {
serverHandler.sendCommand(item.name, Constants.COMMAND_DECREMENT)
}
}
}
, object : HoldListener.OnReleaseListener {
override fun onRelease(tick: Int) {
if (tick <= 0) {
serverHandler.sendCommand(item.name, Constants.COMMAND_OFF)
}
}
}))
} else {
incrementButton.setOnTouchListener(null)
decrementButton.setOnTouchListener(null)
}
}
}
companion object {
const val TAG = "WidgetSwitchFactory"
}
}
|
epl-1.0
|
b5f0a119677e7d8cfe9cf3be2ef572aa
| 40.96875 | 150 | 0.579408 | 5.199419 | false | false | false | false |
oboehm/jfachwert
|
src/main/kotlin/de/jfachwert/post/Postfach.kt
|
1
|
11028
|
/*
* Copyright (c) 2017-2020 by Oliver Boehm
*
* 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.
*
* (c)reated 21.02.2017 by oboehm ([email protected])
*/
package de.jfachwert.post
import com.fasterxml.jackson.annotation.JsonCreator
import com.fasterxml.jackson.databind.annotation.JsonSerialize
import de.jfachwert.KFachwert
import de.jfachwert.pruefung.exception.InvalidValueException
import de.jfachwert.pruefung.exception.LocalizedIllegalArgumentException
import de.jfachwert.util.ToFachwertSerializer
import org.apache.commons.lang3.RegExUtils
import org.apache.commons.lang3.StringUtils
import java.math.BigInteger
import java.util.*
import javax.validation.ValidationException
/**
* Ein Postfach besteht aus einer Nummer ohne fuehrende Nullen und einer
* Postleitzahl mit Ortsangabe. Die Nummer selbst ist optional, wenn die
* durch die Postleitzahl bereits das Postfach abgebildet wird.
*
*
* Im Englischen wird das Postfach oft als POB (Post Office Box) bezeichnet.
*
*
* @author oboehm
* @since 0.2 (19.06.2017)
*/
@JsonSerialize(using = ToFachwertSerializer::class)
open class Postfach : KFachwert {
private val nummer: BigInteger?
/**
* Liefert den Ort.
*
* @return Ort
*/
val ort: Ort
/**
* Zerlegt den uebergebenen String in seine Einzelteile und validiert sie.
* Folgende Heuristiken werden fuer die Zerlegung herangezogen:
*
* * Format ist "Postfach, Ort" oder nur "Ort" (mit PLZ)
* * Postfach ist vom Ort durch Komma oder Zeilenvorschub getrennt
*
* @param postfach z.B. "Postfach 98765, 12345 Entenhausen"
*/
constructor(postfach: String) : this(split(postfach)) {}
private constructor(postfach: Array<String>) : this(postfach[0], postfach[1]) {}
/**
* Erzeugt ein Postfach ohne Postfachnummer. D.h. die PLZ des Ortes
* adressiert bereits das Postfach.
*
* @param ort gueltiger Ort mit PLZ
*/
constructor(ort: Ort) {
this.ort = ort
nummer = null
validate(ort)
}
/**
* Erzeugt ein Postfach mit Postfachnummer. Wenn die uebergebene Nummer
* leer ist, wird ein Postfach ohne Postfachnummer erzeugt.
*
* @param nummer z.B. "12 34 56"
* @param ort Ort mit Postleitzahl
*/
constructor(nummer: String, ort: String) : this(toNumber(nummer), Ort(ort)) {}
/**
* Erzeugt ein neues Postfach.
*
* @param map mit den einzelnen Elementen fuer "plz", "ortsname" und
* "nummer".
*/
@JsonCreator
constructor(map: Map<String, String>) : this(toNumber(map["nummer"]!!), Ort(PLZ.of(map["plz"]!!), map["ortsname"]!!)) {
}
/**
* Erzeugt ein Postfach.
*
* @param nummer positive Zahl ohne fuehrende Null
* @param ort gueltiger Ort mit PLZ
*/
constructor(nummer: Long, ort: Ort) : this(BigInteger.valueOf(nummer), ort) {}
/**
* Erzeugt ein Postfach.
*
* @param nummer positive Zahl ohne fuehrende Null
* @param ort gueltiger Ort mit PLZ
*/
constructor(nummer: BigInteger, ort: Ort) {
this.nummer = nummer
this.ort = ort
verify(nummer, ort)
}
/**
* Erzeugt ein Postfach.
*
* @param nummer positive Zahl oder leer
* @param ort Ort
*/
constructor(nummer: Optional<BigInteger>, ort: Ort) {
this.nummer = nummer.orElse(null)
this.ort = ort
if (this.nummer == null) {
verify(ort)
} else {
verify(nummer.get(), ort)
}
}
/**
* Liefert die Postfach-Nummer als normale Zahl. Da die Nummer optional
* sein kann, wird sie als [Optional] zurueckgeliefert.
*
* @return z.B. 815
*/
fun getNummer(): Optional<BigInteger> {
return if (nummer == null) {
Optional.empty()
} else {
Optional.of(nummer)
}
}
/**
* Liefert die Postfach-Nummer als formattierte Zahl. Dies macht natuerlich
* nur Sinn, wenn diese Nummer gesetzt ist. Daher wird eine
* [IllegalStateException] geworfen, wenn dies nicht der Fall ist.
*
* @return z.B. "8 15"
*/
val nummerFormatted: String
get() {
check(getNummer().isPresent) { "no number present" }
val hundert = BigInteger.valueOf(100)
val formatted = StringBuilder()
var i = getNummer().get()
while (i.compareTo(BigInteger.ONE) > 0) {
formatted.insert(0, " " + i.remainder(hundert))
i = i.divide(hundert)
}
return formatted.toString().trim { it <= ' ' }
}
/**
* Liefert die Postleitzahl. Ohne gueltige Postleitzahl kann kein Postfach
* angelegt werden, weswegen hier immer eine PLZ zurueckgegeben wird.
*
* @return z.B. 09876
*/
val pLZ: PLZ
get() = ort.pLZ.get()
/**
* Liefert den Ortsnamen.
*
* @return Ortsname
*/
val ortsname: String
get() = ort.name
/**
* Zwei Postfaecher sind gleich, wenn sie die gleiche Attribute haben.
*
* @param other das andere Postfach
* @return true bei Gleichheit
*/
override fun equals(other: Any?): Boolean {
if (other !is Postfach) {
return false
}
return nummer == other.nummer && ort.equals(other.ort)
}
/**
* Da die PLZ meistens bereits ein Postfach adressiert, nehmen dies als
* Basis fuer die Hashcode-Implementierung.
*
* @return hashCode
*/
override fun hashCode(): Int {
return ort.hashCode()
}
/**
* Hierueber wird das Postfach einzeilig ausgegeben.
*
* @return z.B. "Postfach 8 15, 09876 Nirwana"
*/
override fun toString(): String {
return if (getNummer().isPresent) {
"Postfach " + nummerFormatted + ", " + ort
} else {
ort.toString()
}
}
/**
* Liefert die einzelnen Attribute eines Postfaches als Map.
*
* @return Attribute als Map
*/
override fun toMap(): Map<String, Any> {
val map: MutableMap<String, Any> = HashMap()
map["plz"] = pLZ
map["ortsname"] = ortsname
if (nummer != null) {
map["nummer"] = nummer
}
return map
}
companion object {
/** Null-Konstante fuer Initialisierungen. */
@JvmField
val NULL = Postfach(Ort.NULL)
/**
* Zerlegt den uebergebenen String in seine Einzelteile und validiert sie.
* Folgende Heuristiken werden fuer die Zerlegung herangezogen:
*
* * Format ist "Postfach, Ort" oder nur "Ort" (mit PLZ)
* * Postfach ist vom Ort durch Komma oder Zeilenvorschub getrennt
*
* @param postfach z.B. "Postfach 98765, 12345 Entenhausen"
* @return Postfach
*/
@JvmStatic
fun of(postfach: String): Postfach {
return Postfach(postfach)
}
/**
* Erzeugt ein Postfach.
*
* @param nummer positive Zahl ohne fuehrende Null
* @param ort gueltiger Ort mit PLZ
* @return Postfach
*/
@JvmStatic
fun of(nummer: Long, ort: Ort): Postfach {
return Postfach(nummer, ort)
}
/**
* Erzeugt ein Postfach.
*
* @param nummer positive Zahl ohne fuehrende Null
* @param ort gueltiger Ort mit PLZ
* @return Postfach
*/
@JvmStatic
fun of(nummer: BigInteger, ort: Ort): Postfach {
return Postfach(nummer, ort)
}
/**
* Zerlegt das uebergebene Postfach in seine Einzelteile und validiert sie.
* Folgende Heuristiken werden fuer die Zerlegung herangezogen:
*
* * Format ist "Postfach, Ort" oder nur "Ort" (mit PLZ)
* * Postfach ist vom Ort durch Komma oder Zeilenvorschub getrennt
*
* @param postfach z.B. "Postfach 98765, 12345 Entenhausen"
*/
@JvmStatic
fun validate(postfach: String) {
val lines = split(postfach)
toNumber(lines[0])
val ort = Ort(lines[1])
if (!ort.pLZ.isPresent) {
throw InvalidValueException(postfach, "postal_code")
}
}
private fun split(postfach: String): Array<String> {
val lines = StringUtils.trimToEmpty(postfach).split("[,\\n$]".toRegex()).toTypedArray()
var splitted = arrayOf("", lines[0])
if (lines.size == 2) {
splitted = lines
} else if (lines.size > 2) {
throw InvalidValueException(postfach, "post_office_box")
}
return splitted
}
private fun toNumber(number: String): Optional<BigInteger> {
if (StringUtils.isBlank(number)) {
return Optional.empty()
}
val unformatted = RegExUtils.replaceAll(number, "Postfach|\\s+", "")
return try {
Optional.of(BigInteger(unformatted))
} catch (nfe: NumberFormatException) {
throw InvalidValueException(number, "number", nfe)
}
}
/**
* Validiert das uebergebene Postfach auf moegliche Fehler.
*
* @param nummer Postfach-Nummer (muss positiv sein)
* @param ort Ort mit PLZ
*/
fun validate(nummer: BigInteger, ort: Ort) {
if (nummer.compareTo(BigInteger.ONE) < 0) {
throw InvalidValueException(nummer, "number")
}
validate(ort)
}
private fun verify(nummer: BigInteger, ort: Ort) {
try {
validate(nummer, ort)
} catch (ex: ValidationException) {
throw LocalizedIllegalArgumentException(ex)
}
}
/**
* Ueberprueft, ob der uebergebene Ort tatsaechlich ein PLZ enthaelt.
*
* @param ort Ort mit PLZ
*/
fun validate(ort: Ort) {
if (!ort.pLZ.isPresent) {
throw InvalidValueException(ort, "postal_code")
}
}
private fun verify(ort: Ort) {
try {
validate(ort)
} catch (ex: ValidationException) {
throw LocalizedIllegalArgumentException(ex)
}
}
}
}
|
apache-2.0
|
0d9a99a745619f911bb30538492bd228
| 28.970109 | 123 | 0.579888 | 3.656499 | false | false | false | false |
StoneMain/Shortranks
|
ShortranksBukkit/src/main/kotlin/eu/mikroskeem/shortranks/bukkit/Shortranks.kt
|
1
|
8102
|
/*
* This file is part of project Shortranks, licensed under the MIT License (MIT).
*
* Copyright (c) 2017-2019 Mark Vainomaa <[email protected]>
* Copyright (c) Contributors
*
* 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 eu.mikroskeem.shortranks.bukkit
import co.aikar.commands.BukkitCommandManager
import eu.mikroskeem.shortranks.api.CollisionRule
import eu.mikroskeem.shortranks.api.HookManager
import eu.mikroskeem.shortranks.api.NameTagVisibility
import eu.mikroskeem.shortranks.api.ScoreboardManager
import eu.mikroskeem.shortranks.api.ShortranksAPI
import eu.mikroskeem.shortranks.api.ShortranksPlugin
import eu.mikroskeem.shortranks.api.ShortranksPlugin.Info
import eu.mikroskeem.shortranks.api.player.ShortranksPlayer
import eu.mikroskeem.shortranks.bukkit.common.HookManagerImpl
import eu.mikroskeem.shortranks.bukkit.hooks.LibsDisguisesHook
import eu.mikroskeem.shortranks.common.hooks.LuckPermsHook
import eu.mikroskeem.shortranks.bukkit.hooks.PlaceholderAPIHook
import eu.mikroskeem.shortranks.bukkit.packets.ScoreboardPacketListener
import eu.mikroskeem.shortranks.bukkit.player.ShortranksPlayerBukkit
import eu.mikroskeem.shortranks.bukkit.scoreboard.ScoreboardManagerImpl
import eu.mikroskeem.shortranks.common.commands.MainCommand
import eu.mikroskeem.shortranks.common.shortranksPluginInstance
import org.bukkit.Server
import org.bukkit.entity.Player
import org.bukkit.event.EventHandler
import org.bukkit.event.EventPriority
import org.bukkit.event.Listener
import org.bukkit.event.player.PlayerJoinEvent
import org.bukkit.event.player.PlayerQuitEvent
import org.bukkit.plugin.ServicePriority
import org.bukkit.plugin.java.JavaPlugin
import org.slf4j.Logger
import java.util.HashMap
import java.util.UUID
/**
* The mighty Shortranks plugin!
*
* @author Mark Vainomaa
*/
class Shortranks : JavaPlugin(), Listener, ShortranksAPI, ShortranksPlugin<Server, Player> {
private val pluginInfo by lazy { ShortranksBukkitInfo(this) }
internal lateinit var sbManager: ScoreboardManagerImpl
internal lateinit var hookManager: HookManagerImpl
internal lateinit var cmdManager: BukkitCommandManager
internal lateinit var packetListener: ScoreboardPacketListener
internal var debug = false
internal var defaultCollisionRule = CollisionRule.PUSH_OTHER_TEAMS
internal var defaultNameTagVisibility = NameTagVisibility.ALWAYS
override fun onEnable() {
// Set up plugin configuration
saveDefaultConfig()
config.options().copyDefaults(true)
saveConfig()
loadSettings()
// Set up scoreboard manager
sbManager = ScoreboardManagerImpl(this)
// Set up hook manager
hookManager = HookManagerImpl(this)
// TODO: pls no bully
shortranksPluginInstance = this
// Set up built in hooks
config.getStringList("enabled-built-in-hooks").run {
// Set up LuckPerms hook
if(server.pluginManager.isPluginEnabled("LuckPerms") && contains("LuckPerms hook"))
hookManager.registerHook(LuckPermsHook(this@Shortranks))
// Set up LibsDisguises hook
if(server.pluginManager.isPluginEnabled("LibsDisguises") && contains("LibsDisguises hook"))
hookManager.registerHook(LibsDisguisesHook(this@Shortranks))
// Set up PlaceholderAPI hook
if(server.pluginManager.isPluginEnabled("PlaceholderAPI") && contains("PlaceholderAPI hook"))
hookManager.registerHook(PlaceholderAPIHook(this@Shortranks))
}
// Set up packet listener
packetListener = ScoreboardPacketListener(this).also { it.register() }
// Listen for events
server.pluginManager.registerEvents(this, this)
// Set up commands
cmdManager = BukkitCommandManager(this)
cmdManager.commandCompletions.registerAsyncCompletion("hooks") {
hookManager.registeredHooks.map { it.name }
}
cmdManager.registerCommand(MainCommand(this))
// Register to service manager
server.servicesManager.register(ShortranksAPI::class.java, this, this, ServicePriority.Normal)
}
override fun onDisable() {
// Unhook all hooks
hookManager.unregisterAllHooks()
// Remove teams
HashMap(sbManager.teamsMap).forEach { p, _ ->
sbManager.removePlayer(p)
}
// Unregister packet listener
packetListener.unregister()
}
override fun reloadConfig() {
super.reloadConfig()
loadSettings()
}
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
fun on(event: PlayerJoinEvent) {
if(debug) logger.info("Player ${event.player} joined the game")
sbManager.getTeam(event.player)
}
@EventHandler(priority = EventPriority.HIGHEST)
fun on(event: PlayerQuitEvent) {
if(debug) logger.info("Player ${event.player} left the game")
sbManager.removePlayer(event.player)
}
// Methods to implement ShortranksAPI interface
override fun getScoreboardManager(): ScoreboardManager = sbManager
override fun getHookManager(): HookManager = hookManager
// Methods to implement ShortranksPlugin interface
override fun getApi(): ShortranksAPI = this
override fun findOnlinePlayer(uniqueId: UUID): ShortranksPlayer<Player>? =server.getPlayer(uniqueId)?.run {
ShortranksPlayerBukkit(this)
}
override fun reloadConfiguration() = reloadConfig()
override fun isBehindBungeeCord(): Boolean = server.spigot().spigotConfig.getBoolean("settings.bungeecord", false)
override fun isInDebugMode(): Boolean = debug
override fun getPluginLogger(): Logger = slF4JLogger
override fun getInfo(): Info = pluginInfo
private fun loadSettings() {
debug = config.getBoolean("debug", false)
defaultCollisionRule = CollisionRule.valueOf(config.getString("default-collision-rule", "PUSH_OTHER_TEAMS")!!)
defaultNameTagVisibility = NameTagVisibility.valueOf(config.getString("default-nametag-visibility", "ALWAYS")!!)
try {
val paperConfigClass = Class.forName("com.destroystokyo.paper.PaperConfig")
if(!server.spigot().paperConfig.getBoolean("settings.enable-player-collisions", true)
&& defaultCollisionRule != CollisionRule.NEVER) {
logger.warning("** Paper's `settings.enable-player-collisions` is false.")
logger.warning("That does not work with Shortranks, as this plugin uses own scoreboard manager.")
logger.warning("If you'd like to achieve same thing, set 'default-collision-rule' in Shortranks " +
"config.yml to 'NEVER'")
server.spigot().paperConfig.set("settings.enable-player-collisions", true)
paperConfigClass.getField("enablePlayerCollisions").set(null, true)
}
} catch(e: ClassNotFoundException) {
//logger.severe("Use Paper or go home.")
}
}
}
|
mit
|
d1f4bfcaa650ea7dfb09113c92bcf0c3
| 42.101064 | 120 | 0.725006 | 4.595576 | false | true | false | false |
mix-it/mixit
|
src/main/kotlin/mixit/util/Extensions.kt
|
1
|
6672
|
package mixit.util
import mixit.model.Language
import org.springframework.http.MediaType.APPLICATION_JSON
import org.springframework.http.MediaType.APPLICATION_XML
import org.springframework.http.MediaType.TEXT_HTML
import org.springframework.web.reactive.function.server.ServerRequest
import org.springframework.web.reactive.function.server.ServerResponse
import org.springframework.web.reactive.function.server.ServerResponse.permanentRedirect
import org.springframework.web.reactive.function.server.ServerResponse.seeOther
import java.net.URI
import java.net.URLEncoder
import java.nio.charset.Charset
import java.security.MessageDigest
import java.text.Normalizer
import java.time.LocalDateTime
import java.time.ZoneOffset
import java.time.ZonedDateTime
import java.time.format.DateTimeFormatter
import java.time.format.DateTimeFormatterBuilder
import java.time.temporal.ChronoField
import java.util.Base64
import java.util.Locale
import java.util.stream.Collectors
import java.util.stream.IntStream
import javax.crypto.Cipher
import javax.crypto.spec.IvParameterSpec
import javax.crypto.spec.SecretKeySpec
// -------------------------
// Spring WebFlux extensions
// -------------------------
fun ServerRequest.language() =
Language.findByTag(
if (this.headers().asHttpHeaders().contentLanguage != null) this.headers().asHttpHeaders().contentLanguage!!.language
else this.headers().asHttpHeaders().acceptLanguageAsLocales.first().language
)
fun ServerRequest.locale(): Locale =
this.headers().asHttpHeaders().contentLanguage ?: Locale.ENGLISH
fun ServerResponse.BodyBuilder.json() = contentType(APPLICATION_JSON)
fun ServerResponse.BodyBuilder.xml() = contentType(APPLICATION_XML)
fun ServerResponse.BodyBuilder.html() = contentType(TEXT_HTML)
fun permanentRedirect(uri: String) = permanentRedirect(URI(uri)).build()
fun seeOther(uri: String) = seeOther(URI(uri)).build()
// --------------------
// Date/Time extensions
// --------------------
fun LocalDateTime.formatDate(language: Language): String =
if (language == Language.ENGLISH) this.format(englishDateFormatter) else this.format(frenchDateFormatter)
fun LocalDateTime.formatTalkDate(language: Language): String =
if (language == Language.ENGLISH) this.format(englishTalkDateFormatter) else this.format(frenchTalkDateFormatter)
fun LocalDateTime.formatTalkTime(language: Language): String =
if (language == Language.ENGLISH) this.format(englishTalkTimeFormatter) else this.format(frenchTalkTimeFormatter)
fun LocalDateTime.toRFC3339(): String = ZonedDateTime.of(this, ZoneOffset.UTC).format(rfc3339Formatter)
private val daysLookup: Map<Long, String> =
IntStream.rangeClosed(1, 31).boxed().collect(Collectors.toMap(Int::toLong, ::getOrdinal))
private val frenchDateFormatter = DateTimeFormatter.ofPattern("d MMMM yyyy", Locale.FRENCH)
private val englishDateFormatter = DateTimeFormatterBuilder()
.appendPattern("MMMM")
.appendLiteral(" ")
.appendText(ChronoField.DAY_OF_MONTH, daysLookup)
.appendLiteral(" ")
.appendPattern("yyyy")
.toFormatter(Locale.ENGLISH)
private val frenchTalkDateFormatter = DateTimeFormatter.ofPattern("EEEE d MMMM", Locale.FRENCH)
private val frenchTalkTimeFormatter = DateTimeFormatter.ofPattern("HH'h'mm", Locale.FRENCH)
private val englishTalkDateFormatter = DateTimeFormatterBuilder()
.appendPattern("EEEE")
.appendLiteral(" ")
.appendPattern("MMMM")
.appendLiteral(" ")
.appendText(ChronoField.DAY_OF_MONTH, daysLookup)
.toFormatter(Locale.ENGLISH)
private val englishTalkTimeFormatter = DateTimeFormatter.ofPattern("HH:mm", Locale.ENGLISH)
private val rfc3339Formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ssXXX")
private fun getOrdinal(n: Int) =
when {
n in 11..13 -> "${n}th"
n % 10 == 1 -> "${n}st"
n % 10 == 2 -> "${n}nd"
n % 10 == 3 -> "${n}rd"
else -> "${n}th"
}
// ----------------
// Other extensions
// ----------------
fun String.markFoundOccurrences(searchTerms: List<String>? = emptyList()) = if (searchTerms == null || searchTerms.isEmpty()) this else {
var str = this
searchTerms.forEach { str = str.replace(it, "<span class=\"mxt-text--found\">$it</span>", true) }
str
}
fun String.stripAccents() = Normalizer
.normalize(this, Normalizer.Form.NFD)
.replace("\\p{InCombiningDiacriticalMarks}+".toRegex(), "")
fun String.toSlug() = lowercase()
.stripAccents()
.replace("\n", " ")
.replace("[^a-z\\d\\s]".toRegex(), " ")
.split(" ")
.joinToString("-")
.replace("-+".toRegex(), "-") // Avoid multiple consecutive "--"
fun String.camelCase() = this
.trim()
.lowercase()
.replaceFirstChar { if (it.isLowerCase()) it.titlecase(Locale.getDefault()) else it.toString() }
fun String.toUrlPath() = URLEncoder.encode(this, "UTF-8").replace("+", "%20")
fun String.encodeToMd5(): String? = if (isNullOrEmpty()) null else hex(MessageDigest.getInstance("MD5").digest(toByteArray(Charset.forName("CP1252"))))
fun String.encodeToBase64(): String? = if (isNullOrEmpty()) null else Base64.getEncoder().encodeToString(toByteArray())
fun String.decodeFromBase64(): String? = if (isNullOrEmpty()) null else String(Base64.getDecoder().decode(toByteArray()))
fun String.encrypt(key: String, initVector: String): String? {
try {
val encrypted = cipher(key, initVector, Cipher.ENCRYPT_MODE).doFinal(toByteArray())
return Base64.getEncoder().encodeToString(encrypted)
} catch (ex: Exception) {
ex.printStackTrace()
}
return null
}
fun String.decrypt(key: String, initVector: String): String? {
try {
val encrypted = Base64.getDecoder().decode(toByteArray())
return String(cipher(key, initVector, Cipher.DECRYPT_MODE).doFinal(encrypted))
} catch (ex: Exception) {
ex.printStackTrace()
}
return null
}
private fun cipher(key: String, initVector: String, mode: Int): Cipher {
val iv = IvParameterSpec(initVector.toByteArray(charset("UTF-8")))
val skeySpec = SecretKeySpec(key.toByteArray(charset("UTF-8")), "AES")
val cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING")
cipher.init(mode, skeySpec, iv)
return cipher
}
private fun hex(digested: ByteArray): String {
val sb = StringBuffer()
for (i in digested.indices) {
val v = Integer.toHexString(((digested[i].toInt() and 0xFF) or 0x100))
sb.append(v.substring(1, 3))
}
return sb.toString()
}
fun <T> Iterable<T>.shuffle(): Iterable<T> =
toMutableList().apply { this.shuffle() }
fun localePrefix(locale: Locale) = if (locale.language == "en") "/en" else ""
|
apache-2.0
|
e758e87e5350fb1b5a572bd9bb266a70
| 35.659341 | 151 | 0.713579 | 4.01444 | false | false | false | false |
RuntimeModels/chazm
|
chazm-model/src/main/kotlin/runtimemodels/chazm/model/relation/ContainsEvent.kt
|
2
|
1804
|
package runtimemodels.chazm.model.relation
import runtimemodels.chazm.api.entity.Characteristic
import runtimemodels.chazm.api.entity.CharacteristicId
import runtimemodels.chazm.api.entity.Role
import runtimemodels.chazm.api.entity.RoleId
import runtimemodels.chazm.api.id.UniqueId
import runtimemodels.chazm.api.relation.Contains
import runtimemodels.chazm.model.event.AbstractEvent
import runtimemodels.chazm.model.event.EventType
import runtimemodels.chazm.model.message.M
import java.util.*
import javax.inject.Inject
/**
* The [ContainsEvent] class indicates that there is an update about a [Contains] relation.
*
* @author Christopher Zhong
* @since 7.0.0
*/
open class ContainsEvent @Inject internal constructor(
category: EventType,
contains: Contains
) : AbstractEvent(category) {
/**
* Returns a [UniqueId] that represents a [Role].
*
* @return a [UniqueId].
*/
val roleId: RoleId = contains.role.id
/**
* Returns a [UniqueId] that represents a [Characteristic].
*
* @return a [UniqueId].
*/
val characteristicId: CharacteristicId = contains.characteristic.id
/**
* Returns a `double` value.
*
* @return a `double` value
*/
val value: Double = contains.value
override fun equals(other: Any?): Boolean {
if (other is ContainsEvent) {
return super.equals(other) && roleId == other.roleId && characteristicId == other.characteristicId
}
return false
}
override fun hashCode(): Int = Objects.hash(category, roleId, characteristicId)
override fun toString(): String = M.EVENT_WITH_2_IDS_AND_VALUE[super.toString(), roleId, characteristicId, value]
companion object {
private const val serialVersionUID = 87203168183879944L
}
}
|
apache-2.0
|
b30f7c2aa4e82bd0dee08282ceadbc11
| 29.576271 | 117 | 0.705654 | 4.214953 | false | false | false | false |
freundTech/OneSlotServer
|
src/main/kotlin/com/freundtech/minecraft/oneslotserver/handler/event/PlayerListener.kt
|
1
|
2933
|
package com.freundtech.minecraft.oneslotserver.handler.event
import com.freundtech.minecraft.oneslotserver.OneSlotServer
import com.freundtech.minecraft.oneslotserver.extension.*
import com.freundtech.minecraft.oneslotserver.util.*
import org.bukkit.event.EventHandler
import org.bukkit.event.Listener
import org.bukkit.event.player.*
import org.bukkit.event.player.PlayerLoginEvent.Result
class PlayerListener(private val plugin: OneSlotServer) : Listener {
@EventHandler
fun onPlayerLogin(event: PlayerLoginEvent) {
val now = currentTime()
val playerInfo = event.player.oneSlotServer
val activePlayer = plugin.activePlayer
event.player.oneSlotServer.join()
if (!playerInfo.hasTimeRemaining()) {
val waitLeft = plugin.waitTime - (now - playerInfo.firstJoin)
if (!event.player.hasPermission(PERMISSION_SPECTATE)) {
event.disallow(Result.KICK_OTHER,
"You have no time left on this server. Please wait ${waitLeft.format()}.")
}
} else if (activePlayer != null) {
val waitLeft = activePlayer.oneSlotServer.timeLeft
if (!event.player.hasPermission(PERMISSION_SPECTATE)) {
event.disallow(Result.KICK_FULL,
"A person is already playing. Please wait ${waitLeft.format()}.")
}
}
else if (event.result == Result.ALLOWED) {
plugin.activePlayer = event.player
event.player.loadFromSharedData()
}
}
@EventHandler
fun onPlayerJoin(event: PlayerJoinEvent) {
event.joinMessage = ""
if (plugin.activePlayer?.uniqueId == event.player.uniqueId) {
event.player.isSleepingIgnored = false
if (!event.player.hasPermission(PERMISSION_SEE_SPECTATORS)) {
plugin.server.onlinePlayers.filter {
event.player.uniqueId != it.uniqueId
}.forEach {
event.player.hidePlayer(plugin, it)
}
}
event.player.apply {
sendMessage(arrayOf(
"Welcome to the one slot server.",
"You have ${oneSlotServer.timeLeft.format()} left to play."
))
}
} else if (event.player.hasPermission(PERMISSION_SPECTATE)) {
event.player.setSpectator()
if (plugin.activePlayer?.hasPermission(PERMISSION_SEE_SPECTATORS) == false) {
plugin.activePlayer?.hidePlayer(plugin, event.player)
}
}
}
@EventHandler
fun onPlayerQuit(event: PlayerQuitEvent) {
event.quitMessage = ""
if (plugin.activePlayer?.uniqueId == event.player.uniqueId) {
event.player.saveToSharedData()
plugin.activePlayer = null
}
event.player.oneSlotServer.save()
}
}
|
mit
|
5ec45de2bc25d25b024595a41011fda2
| 34.768293 | 98 | 0.608251 | 4.53323 | false | false | false | false |
shlusiak/Freebloks-Android
|
themes/src/main/java/de/saschahlusiak/freebloks/theme/ThemeManager.kt
|
1
|
3233
|
package de.saschahlusiak.freebloks.theme
import android.content.Context
import android.util.Log
/**
* Manages available [Theme] definitions. Get the singleton instance using [.get].
*
* @see [getTheme]
*/
class ThemeManager private constructor(context: Context) {
private val tag = ThemeManager::class.java.simpleName
val backgroundThemes: List<Theme>
val boardThemes: List<Theme>
init {
backgroundThemes = loadBackgroundThemes(context)
boardThemes = loadBoardThemes(context)
}
/**
* Discovers and initialises all background themes
* @param context Context
*/
private fun loadBackgroundThemes(context: Context): List<Theme> {
val themes: MutableList<Theme> = mutableListOf(
ColorThemes.Black,
ColorThemes.Blue
)
if (BuildConfig.DEBUG) {
themes.add(ColorThemes.Green)
themes.add(ColorThemes.White)
}
themes.addAll(AssetThemes().getAllThemes(context))
return themes
}
/**
* Discovers and initialises all board themes
* @param context Context
*/
private fun loadBoardThemes(context: Context): List<Theme> {
return BoardThemes().getAllThemes(context).toList()
}
/**
* For a given package name (a [ThemeProvider] return all themes. On error, an empty collection is returned.
*
* @param context Context
* @param className fully qualified class name of theme provider to use
*/
private fun loadThemesFromPackage(context: Context, className: String): Collection<Theme> {
try {
val c = Class.forName(className)
val provider = c.newInstance()
provider as? ThemeProvider ?: throw IllegalArgumentException("ThemeProvider expected, ${provider.javaClass.name} found")
val themesFromProvider = provider.getAllThemes(context)
Log.i(tag, "Got " + themesFromProvider.size + " themes from " + className)
return themesFromProvider
} catch (e: ClassNotFoundException) {
e.printStackTrace()
} catch (e: IllegalAccessException) {
e.printStackTrace()
} catch (e: InstantiationException) {
e.printStackTrace()
}
return ArrayList()
}
/**
* Get a specified Theme by name, or the default theme if not found.
*
* @param name name, as retrieved via [Theme.name]
* @param defaultTheme fall back theme, if not found
* @return Theme instance
*/
fun getTheme(name: String?, defaultTheme: Theme): Theme {
return (backgroundThemes + boardThemes).firstOrNull { it.name == name } ?: defaultTheme
}
companion object {
private var singleton: ThemeManager? = null
/**
* Return the singleton instance of the [ThemeManager]
*
* @param context Context
* @return the singleton instance
*/
fun get(context: Context): ThemeManager {
return singleton ?: ThemeManager(context).also { singleton = it }
}
/**
* Release all resources
*/
fun release() {
singleton = null
}
}
}
|
gpl-2.0
|
169eac681b4dfecd381be1faad6c5f27
| 28.935185 | 132 | 0.619239 | 4.832586 | false | false | false | false |
openstreetview/android
|
app/src/main/java/com/telenav/osv/data/collector/obddata/service/OBDService.kt
|
1
|
2028
|
package com.telenav.osv.data.collector.obddata.service
import android.app.Service
import android.content.Intent
import android.os.*
import androidx.annotation.Nullable
import com.telenav.osv.data.collector.obddata.manager.OBDSensorManager
import timber.log.Timber
/**
* Created by raduh on 9/8/2016.
*/
class OBDService : Service() {
/**
* The thread on which service runs (different from main thread)
*/
private var thread: HandlerThread? = null
private var mServiceHandler: ServiceHandler? = null
private val obdBinder: IBinder = ObdServiceBinder()
@Nullable
override fun onBind(intent: Intent): IBinder {
return obdBinder
}
override fun onCreate() {
// Start up the thread running the service. Note that we create a
// separate thread because the service normally runs in the process's
// main thread, which we don't want to block. We also make it
// background priority so CPU-intensive work will not disrupt our UI.
thread = HandlerThread("ServiceStartArguments", Process.THREAD_PRIORITY_BACKGROUND)
thread!!.start()
val mServiceLooper = thread!!.looper
mServiceHandler = ServiceHandler(mServiceLooper)
}
override fun onDestroy() {
super.onDestroy()
thread!!.quit()
thread!!.interrupt()
Timber.tag(TAG).d("OVI: thread destroy called")
}
fun startSendingCommands() {
val msg = mServiceHandler!!.obtainMessage()
mServiceHandler!!.sendMessage(msg)
}
private inner class ServiceHandler internal constructor(looper: Looper?) : Handler(looper) {
override fun handleMessage(msg: Message) {
OBDSensorManager.instance.getAbstractClientDataTransmission()?.startSendingSensorCommands()
}
}
inner class ObdServiceBinder : Binder() {
val obdService: OBDService
get() = this@OBDService
}
companion object {
private val TAG = OBDService::class.java.simpleName
}
}
|
lgpl-3.0
|
00c17a6da81a2c10a60170031489b994
| 31.206349 | 103 | 0.678501 | 4.61959 | false | false | false | false |
vanita5/twittnuker
|
twittnuker/src/main/kotlin/de/vanita5/twittnuker/util/api/TwidereExceptionFactory.kt
|
1
|
2427
|
/*
* Twittnuker - Twitter client for Android
*
* Copyright (C) 2013-2017 vanita5 <[email protected]>
*
* This program incorporates a modified version of Twidere.
* Copyright (C) 2012-2017 Mariotaku Lee <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package de.vanita5.twittnuker.util.api
import com.fasterxml.jackson.core.JsonParseException
import de.vanita5.microblog.library.MicroBlogException
import org.mariotaku.restfu.ExceptionFactory
import org.mariotaku.restfu.RestConverter
import org.mariotaku.restfu.http.HttpRequest
import org.mariotaku.restfu.http.HttpResponse
import java.io.IOException
/**
* Create `MicroBlogException`
*/
object TwidereExceptionFactory : ExceptionFactory<MicroBlogException> {
override fun newException(cause: Throwable?, request: HttpRequest?, response: HttpResponse?): MicroBlogException {
val te = if (cause != null) {
MicroBlogException(cause)
} else if (response != null) {
parseTwitterException(response)
} else {
MicroBlogException()
}
te.httpRequest = request
te.httpResponse = response
return te
}
fun parseTwitterException(resp: HttpResponse): MicroBlogException {
try {
val converter = TwitterConverterFactory.forResponse(MicroBlogException::class.java)
return converter.convert(resp) as MicroBlogException
} catch (e: JsonParseException) {
return MicroBlogException("Malformed JSON Data", e)
} catch (e: IOException) {
return MicroBlogException("IOException while throwing exception", e)
} catch (e: RestConverter.ConvertException) {
return MicroBlogException(e)
} catch (e: MicroBlogException) {
return e
}
}
}
|
gpl-3.0
|
ed095f20147808a505aec3a491f75f7b
| 35.238806 | 118 | 0.704986 | 4.649425 | false | false | false | false |
slartus/4pdaClient-plus
|
qms/qms-impl/src/main/java/org/softeg/slartus/forpdaplus/qms/impl/screens/threads/fingerprints/QmsThreadSelectableFingerprint.kt
|
1
|
3425
|
package org.softeg.slartus.forpdaplus.qms.impl.screens.threads.fingerprints
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.annotation.DrawableRes
import androidx.core.view.isVisible
import androidx.recyclerview.widget.DiffUtil
import org.softeg.slartus.forpdaplus.core_lib.ui.adapter.BaseViewHolder
import org.softeg.slartus.forpdaplus.core_lib.ui.adapter.Item
import org.softeg.slartus.forpdaplus.core_lib.ui.adapter.ItemFingerprint
import org.softeg.slartus.forpdaplus.qms.impl.R
import org.softeg.slartus.forpdaplus.qms.impl.databinding.LayoutQmsThreadSelectableItemBinding
class QmsThreadSelectableFingerprint(
@DrawableRes
private val accentBackground: Int,
private val onClickListener: (view: View?, item: QmsThreadSelectableItem) -> Unit
) :
ItemFingerprint<LayoutQmsThreadSelectableItemBinding, QmsThreadSelectableItem> {
private val diffUtil = object : DiffUtil.ItemCallback<QmsThreadSelectableItem>() {
override fun areItemsTheSame(
oldItem: QmsThreadSelectableItem,
newItem: QmsThreadSelectableItem
) = oldItem.id == newItem.id
override fun areContentsTheSame(
oldItem: QmsThreadSelectableItem,
newItem: QmsThreadSelectableItem
) = oldItem == newItem
}
override fun getLayoutId() = R.layout.layout_qms_thread_selectable_item
override fun isRelativeItem(item: Item) = item is QmsThreadSelectableItem
override fun getViewHolder(
layoutInflater: LayoutInflater,
parent: ViewGroup
): BaseViewHolder<LayoutQmsThreadSelectableItemBinding, QmsThreadSelectableItem> {
val binding = LayoutQmsThreadSelectableItemBinding.inflate(layoutInflater, parent, false)
return QmsThreadSelectableViewHolder(
binding = binding,
accentBackground = accentBackground,
onClickListener = onClickListener
)
}
override fun getDiffUtil() = diffUtil
}
class QmsThreadSelectableViewHolder(
binding: LayoutQmsThreadSelectableItemBinding,
@DrawableRes
accentBackground: Int,
private val onClickListener: (view: View?, item: QmsThreadSelectableItem) -> Unit
) :
BaseViewHolder<LayoutQmsThreadSelectableItemBinding, QmsThreadSelectableItem>(binding) {
private val totalTextFormat =
itemView.context.getString(org.softeg.slartus.forpdaplus.core_res.R.string.qms_thread_total)
init {
itemView.setOnClickListener { v ->
onClickListener(v, item)
}
binding.newMessagesCountTextView.setBackgroundResource(accentBackground)
}
override fun onBind(item: QmsThreadSelectableItem) {
super.onBind(item)
with(binding) {
titleTextView.text = item.title
messagesCountTextView.text = totalTextFormat.format(item.messagesCount)
newMessagesCountTextView.text = item.newMessagesCount.toString()
newMessagesCountTextView.isVisible = item.newMessagesCount > 0
selectedCheckBox.isChecked = item.selected
dateTextView.text = item.lastMessageDate
}
}
}
data class QmsThreadSelectableItem(
override val id: String,
override val title: String,
override val messagesCount: Int,
override val newMessagesCount: Int,
override val lastMessageDate: String?,
val selected: Boolean = false
) : ThreadItem
|
apache-2.0
|
ac79d06329d3132bbc80df0852836eb8
| 37.066667 | 100 | 0.738102 | 4.803647 | false | false | false | false |
AndroidX/androidx
|
room/room-compiler-processing/src/main/java/androidx/room/compiler/processing/javac/JavacRawType.kt
|
3
|
1879
|
/*
* Copyright 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.room.compiler.processing.javac
import androidx.room.compiler.codegen.XTypeName
import androidx.room.compiler.processing.XNullability
import androidx.room.compiler.processing.XRawType
import androidx.room.compiler.processing.safeTypeName
internal class JavacRawType(
env: JavacProcessingEnv,
original: JavacType
) : XRawType {
private val erased = env.typeUtils.erasure(original.typeMirror)
private val typeUtils = env.delegate.typeUtils
override val typeName by lazy {
xTypeName.java
}
private val xTypeName: XTypeName by lazy {
XTypeName(
erased.safeTypeName(),
XTypeName.UNAVAILABLE_KTYPE_NAME,
original.maybeNullability ?: XNullability.UNKNOWN
)
}
override fun asTypeName() = xTypeName
override fun isAssignableFrom(other: XRawType): Boolean {
return other is JavacRawType && typeUtils.isAssignable(other.erased, erased)
}
override fun equals(other: Any?): Boolean {
return this === other || xTypeName == (other as? XRawType)?.asTypeName()
}
override fun hashCode(): Int {
return xTypeName.hashCode()
}
override fun toString(): String {
return xTypeName.java.toString()
}
}
|
apache-2.0
|
e03a88acd0f98452a7f434a112d18fb5
| 30.333333 | 84 | 0.708888 | 4.674129 | false | false | false | false |
AndroidX/androidx
|
glance/glance/src/androidMain/kotlin/androidx/glance/layout/SizeModifiers.kt
|
3
|
3928
|
/*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.glance.layout
import androidx.annotation.DimenRes
import androidx.annotation.RestrictTo
import androidx.compose.ui.unit.Dp
import androidx.glance.GlanceModifier
import androidx.glance.unit.Dimension
/**
* Modifier to represent the width of an element.
*
* @suppress
*/
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
class WidthModifier(val width: Dimension) : GlanceModifier.Element
/** Sets the absolute width of an element, in [Dp]. */
fun GlanceModifier.width(width: Dp): GlanceModifier =
this.then(WidthModifier(Dimension.Dp(width)))
/** Set the width of a view from the value of a resource. */
fun GlanceModifier.width(@DimenRes width: Int): GlanceModifier =
this.then(WidthModifier(Dimension.Resource(width)))
/** Specifies that the width of the element should wrap its contents. */
fun GlanceModifier.wrapContentWidth(): GlanceModifier =
this.then(WidthModifier(Dimension.Wrap))
/**
* Specifies that the width of the element should expand to the size of its parent. Note that if
* multiple elements within a linear container (e.g. Row or Column) have their width as
* [fillMaxWidth], then they will all share the remaining space.
*/
fun GlanceModifier.fillMaxWidth(): GlanceModifier = this.then(WidthModifier(Dimension.Fill))
/**
* Modifier to represent the height of an element.
*
* @suppress
*/
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
class HeightModifier(val height: Dimension) : GlanceModifier.Element
/** Sets the absolute height of an element, in [Dp]. */
fun GlanceModifier.height(height: Dp): GlanceModifier =
this.then(HeightModifier(Dimension.Dp(height)))
/** Set the height of the view from a resource. */
fun GlanceModifier.height(@DimenRes height: Int): GlanceModifier =
this.then(HeightModifier(Dimension.Resource(height)))
/** Specifies that the height of the element should wrap its contents. */
fun GlanceModifier.wrapContentHeight(): GlanceModifier =
this.then(HeightModifier(Dimension.Wrap))
/**
* Specifies that the height of the element should expand to the size of its parent. Note that if
* multiple elements within a linear container (e.g. Row or Column) have their height as
* expandHeight, then they will all share the remaining space.
*/
fun GlanceModifier.fillMaxHeight(): GlanceModifier =
this.then(HeightModifier(Dimension.Fill))
/** Sets both the width and height of an element, in [Dp]. */
fun GlanceModifier.size(size: Dp): GlanceModifier = this.width(size).height(size)
/** Sets both width and height of an element from a resource. */
fun GlanceModifier.size(@DimenRes size: Int): GlanceModifier = this.width(size).height(size)
/** Sets both the width and height of an element, in [Dp]. */
fun GlanceModifier.size(width: Dp, height: Dp): GlanceModifier =
this.width(width).height(height)
/** Sets both the width and height of an element from resources. */
fun GlanceModifier.size(@DimenRes width: Int, @DimenRes height: Int): GlanceModifier =
this.width(width).height(height)
/** Wrap both the width and height's content. */
fun GlanceModifier.wrapContentSize(): GlanceModifier =
this.wrapContentHeight().wrapContentWidth()
/** Set both the width and height to the maximum available space. */
fun GlanceModifier.fillMaxSize(): GlanceModifier = this.fillMaxWidth().fillMaxHeight()
|
apache-2.0
|
f026d34a1ef68591c5892c3be47c5045
| 38.686869 | 97 | 0.754073 | 4.269565 | false | false | false | false |
joaoevangelista/Convertx
|
app/src/main/kotlin/io/github/joaoevangelista/convertx/op/Units.kt
|
1
|
7038
|
package io.github.joaoevangelista.convertx.op
import android.support.annotation.StringRes
import android.util.Pair
import io.github.joaoevangelista.convertx.R
import io.github.joaoevangelista.convertx.op.ConversionTypes.AREA
import io.github.joaoevangelista.convertx.op.ConversionTypes.FORCES
import io.github.joaoevangelista.convertx.op.ConversionTypes.LENGTH
import io.github.joaoevangelista.convertx.op.ConversionTypes.MASS
import io.github.joaoevangelista.convertx.op.ConversionTypes.TEMPERATURE
import io.github.joaoevangelista.convertx.op.ConversionTypes.VOLUME
import io.github.joaoevangelista.convertx.op.ConversionTypes.values
import java.util.Arrays
/**
* Provides common accessor to the translatable name of a unit
*/
interface NamedUnit {
@StringRes fun t(): Int
override fun toString(): String
fun valueOf(string: String): Any
}
enum class ConversionTypes(@StringRes val title: Int) {
LENGTH(R.string.conversion_measure_unit), TEMPERATURE(R.string.conversion_temperature), AREA(
R.string.conversion_area),
VOLUME(R.string.conversion_volume), FORCES(R.string.conversion_force), MASS(
R.string.conversion_mass)
}
enum class Lengths(val unit: String) : NamedUnit {
METERS("m") {
override fun valueOf(string: String): Any = Lengths.valueOf(string)
override fun t(): Int = R.string.unit_length_meters
},
KILOMETERS("km") {
override fun valueOf(string: String): Any = Lengths.valueOf(string)
override fun t(): Int = R.string.unit_length_kilometers
},
CENTIMETERS("cm") {
override fun valueOf(string: String): Any = Lengths.valueOf(string)
override fun t(): Int = R.string.unit_length_centimeters
},
MILLIMETERS("mm") {
override fun valueOf(string: String): Any = Lengths.valueOf(string)
override fun t(): Int = R.string.unit_length_millimeters
},
MILES("mi") {
override fun valueOf(string: String): Any = Lengths.valueOf(string)
override fun t(): Int = R.string.unit_length_miles
},
FOOT("ft") {
override fun valueOf(string: String): Any = Lengths.valueOf(string)
override fun t(): Int = R.string.unit_length_foot
},
YARD("yd") {
override fun valueOf(string: String): Any = Lengths.valueOf(string)
override fun t(): Int = R.string.unit_length_yard
},
INCH("in") {
override fun valueOf(string: String): Any = Lengths.valueOf(string)
override fun t(): Int = R.string.unit_length_inch
},
NAUTICAL_MILES("nmi") {
override fun valueOf(string: String): Any = Lengths.valueOf(string)
override fun t(): Int = R.string.unit_length_nautica_miles
},
ANGSTROM("Å") {
override fun valueOf(string: String): Any = Lengths.valueOf(string)
override fun t(): Int = R.string.unit_length_angstrom
},
ASTRONOMICAL_UNIT("ua") {
override fun valueOf(string: String): Any = Lengths.valueOf(string)
override fun t(): Int = R.string.unit_length_astronomical_unit
},
LIGHT_YEAR("ly") {
override fun valueOf(string: String): Any = Lengths.valueOf(string)
override fun t(): Int = R.string.unit_length_light_year
},
PARSEC("pc") {
override fun valueOf(string: String): Any = Lengths.valueOf(string)
override fun t(): Int = R.string.unit_length_parsec
},
POINT("pt") {
override fun valueOf(string: String): Any = Lengths.valueOf(string)
override fun t(): Int = R.string.unit_length_point
},
PIXEL("pixel") {
override fun valueOf(string: String): Any = Lengths.valueOf(string)
override fun t(): Int = R.string.unit_length_pixel
}
}
enum class Temperatures(val unit: String) : NamedUnit {
CELSIUS("°C") {
override fun valueOf(string: String): Any = Temperatures.valueOf(string)
override fun t(): Int = R.string.unit_temperature_celsius
},
FAHRENHEIT("°F") {
override fun valueOf(string: String): Any = Temperatures.valueOf(string)
override fun t(): Int = R.string.unit_temperature_fahrenheit
},
KELVIN("K") {
override fun valueOf(string: String): Any = Temperatures.valueOf(string)
override fun t(): Int = R.string.unit_temperature_kelvin
}
}
enum class Areas(val unit: String) : NamedUnit {
SQUARE_METRE("m²") {
override fun valueOf(string: String): Any = Areas.valueOf(string)
override fun t(): Int = R.string.unit_area_square_metre
},
ARE("a") {
override fun valueOf(string: String): Any = Areas.valueOf(string)
override fun t(): Int = R.string.unit_area_are
},
HECTARE("ha") {
override fun valueOf(string: String): Any = Areas.valueOf(string)
override fun t(): Int = R.string.unit_area_hectare
}
}
enum class Volumes(val unit: String) : NamedUnit {
CUBIC_METRE("m³") {
override fun valueOf(string: String): Any = Volumes.valueOf(string)
override fun t(): Int = R.string.unit_volume_cubic_metre
},
LITER("L") {
override fun valueOf(string: String): Any = Volumes.valueOf(string)
override fun t(): Int = R.string.unit_volume_liter
},
CUBIC_INCH("in³") {
override fun valueOf(string: String): Any = Volumes.valueOf(string)
override fun t(): Int = R.string.unit_volume_cubic_inch
}
}
enum class Forces(val unit: String) : NamedUnit {
DYNE("dyn") {
override fun valueOf(string: String): Any = Forces.valueOf(string)
override fun t(): Int = R.string.unit_force_dyne
},
KILOGRAM_FORCE("kgf") {
override fun valueOf(string: String): Any = Forces.valueOf(string)
override fun t(): Int = R.string.unit_force_kilogram_force
},
POUND_FORCE("lbf") {
override fun valueOf(string: String): Any = Forces.valueOf(string)
override fun t(): Int = R.string.unit_force_pound_force
},
NEWTON("N") {
override fun valueOf(string: String): Any = Forces.valueOf(string)
override fun t(): Int = R.string.unit_force_newton
}
}
enum class Mass(val unit: String) : NamedUnit {
GRAMS("g") {
override fun valueOf(string: String): Any = Mass.valueOf(string)
override fun t(): Int = R.string.unit_mass_grams
},
KILOGRAM("kg") {
override fun valueOf(string: String): Any = Mass.valueOf(string)
override fun t(): Int = R.string.unit_mass_kilogram
},
TON("t") {
override fun valueOf(string: String): Any = Mass.valueOf(string)
override fun t(): Int = R.string.unit_mass_ton
}
}
val areas = Areas.values()
val lengths = Lengths.values()
val temperatures = Temperatures.values()
val volumes = Volumes.values()
val conversions = values()
val forces = Forces.values()
val mass = Mass.values()
val units = Arrays.asList(*areas, *lengths, *temperatures, *volumes, *forces, *mass)
val typesMap = arrayListOf(
Pair<ConversionTypes, Array<out NamedUnit>>(LENGTH, lengths),
Pair<ConversionTypes, Array<out NamedUnit>>(AREA, areas),
Pair<ConversionTypes, Array<out NamedUnit>>(VOLUME, volumes),
Pair<ConversionTypes, Array<out NamedUnit>>(TEMPERATURE, temperatures),
Pair<ConversionTypes, Array<out NamedUnit>>(FORCES, forces),
Pair<ConversionTypes, Array<out NamedUnit>>(MASS, mass)
)
fun findUnit(name: String): NamedUnit {
return units.find { it.toString() == name } as NamedUnit
}
|
apache-2.0
|
b1d5305dde45f7903c0481ffdd2448eb
| 35.625 | 95 | 0.700228 | 3.379145 | false | false | false | false |
JoachimR/Bible2net
|
app/src/main/java/de/reiss/bible2net/theword/note/list/NoteListRepository.kt
|
1
|
3747
|
package de.reiss.bible2net.theword.note.list
import androidx.lifecycle.MutableLiveData
import de.reiss.bible2net.theword.architecture.AsyncLoad
import de.reiss.bible2net.theword.database.NoteItemDao
import de.reiss.bible2net.theword.database.converter.Converter
import de.reiss.bible2net.theword.model.Note
import de.reiss.bible2net.theword.model.TheWordContent
import java.util.Locale
import java.util.concurrent.Executor
import javax.inject.Inject
open class NoteListRepository @Inject constructor(
private val executor: Executor,
private val noteItemDao: NoteItemDao
) {
open fun getAllNotes(result: MutableLiveData<AsyncLoad<FilteredNotes>>) {
val oldData = result.value?.data ?: return
result.postValue(AsyncLoad.loading(oldData))
executor.execute {
val query = oldData.query
val allItems = noteItemDao.all()
.mapNotNull {
Converter.noteItemToNote(it)
}
if (query.isEmpty()) {
result.postValue(
AsyncLoad.success(
FilteredNotes(
allItems = allItems,
filteredItems = allItems,
query = query
)
)
)
} else {
val filteredItems = filter(query, allItems)
result.postValue(
AsyncLoad.success(
FilteredNotes(
allItems = allItems,
filteredItems = filteredItems,
query = query
)
)
)
}
}
}
open fun applyNewFilter(query: String, result: MutableLiveData<AsyncLoad<FilteredNotes>>) {
val unfiltered = result.value?.data ?: return
if (query.isEmpty()) {
result.postValue(
AsyncLoad.success(
FilteredNotes(
allItems = unfiltered.allItems,
filteredItems = unfiltered.allItems,
query = query
)
)
)
return
}
result.postValue(AsyncLoad.loading(unfiltered))
executor.execute {
val filteredItems = filter(query, unfiltered.allItems)
result.postValue(
AsyncLoad.success(
FilteredNotes(
allItems = unfiltered.allItems,
filteredItems = filteredItems,
query = query
)
)
)
}
}
private fun filter(query: String, noteList: List<Note>) =
query.lowerCase().let { match ->
noteList.filter {
it.noteText.lowerCase().contains(match) || it.theWordContent.contains(match)
}
}
private fun TheWordContent.contains(match: String) =
this.chapter1.lowerCase().contains(match) ||
this.verse1.lowerCase().contains(match) ||
this.intro1.lowerCase().contains(match) ||
this.text1.lowerCase().contains(match) ||
this.ref1.lowerCase().contains(match) ||
this.book2.lowerCase().contains(match) ||
this.chapter2.lowerCase().contains(match) ||
this.verse2.lowerCase().contains(match) ||
this.intro2.lowerCase().contains(match) ||
this.text2.lowerCase().contains(match) ||
this.ref2.lowerCase().contains(match)
private fun String.lowerCase() = this.toLowerCase(Locale.getDefault())
}
|
gpl-3.0
|
cd5c2235589ae35b5b6d10499caa0969
| 34.018692 | 95 | 0.531625 | 5.307365 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.