repo_name
stringlengths 7
81
| path
stringlengths 6
242
| copies
stringclasses 55
values | size
stringlengths 2
6
| content
stringlengths 55
737k
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 5.44
99.8
| line_max
int64 15
979
| alpha_frac
float64 0.3
0.91
| ratio
float64 2
9.93
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
dexbleeker/hamersapp | hamersapp/src/main/java/nl/ecci/hamers/fcm/MessagingService.kt | 1 | 6786 | package nl.ecci.hamers.fcm
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.media.RingtoneManager
import androidx.core.app.NotificationCompat
import android.util.Log
import com.bumptech.glide.Glide
import com.google.firebase.messaging.FirebaseMessagingService
import com.google.firebase.messaging.RemoteMessage
import com.google.gson.Gson
import com.google.gson.GsonBuilder
import nl.ecci.hamers.R
import nl.ecci.hamers.data.Loader
import nl.ecci.hamers.models.*
import nl.ecci.hamers.ui.activities.MainActivity
import nl.ecci.hamers.ui.activities.SingleBeerActivity
import nl.ecci.hamers.ui.activities.SingleEventActivity
import nl.ecci.hamers.ui.activities.SingleMeetingActivity
import nl.ecci.hamers.utils.DataUtils
import nl.ecci.hamers.utils.DataUtils.getGravatarURL
class MessagingService : FirebaseMessagingService() {
var intent: Intent? = null
private var pendingIntent : PendingIntent? = null
var gson: Gson = GsonBuilder().setDateFormat(MainActivity.dbDF.toPattern()).create()
/**
* Called when message is received.
*/
override fun onMessageReceived(remoteMessage: RemoteMessage?) {
intent = Intent(this, MainActivity::class.java)
intent?.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
// Check if message contains a notification payload.
if (remoteMessage?.notification != null) {
// TODO
Log.d(TAG, "FCM Notification Body: " + remoteMessage.notification!!.body!!)
}
// Check if message contains a data payload.
if (remoteMessage?.data?.isNotEmpty() as Boolean) {
Log.d(TAG, "FCM data payload: " + remoteMessage.data)
when (remoteMessage.data["type"]) {
"Quote" -> quotePush(remoteMessage.data["object"])
"Event" -> eventPush(remoteMessage.data["object"])
"Beer" -> beerPush(remoteMessage.data["object"])
"Review" -> reviewPush(remoteMessage.data["object"])
"News" -> newsPush(remoteMessage.data["object"])
"Meeting" -> meetingPush(remoteMessage.data["object"])
"Sticker" -> stickerPush(remoteMessage.data["object"])
}
}
}
private fun quotePush(quoteString: String?) {
val quote = gson.fromJson(quoteString, Quote::class.java)
sendNotification(quote.text, applicationContext.getString(R.string.change_quote_new), quote.userID)
}
private fun eventPush(eventString: String?) {
Loader.getData(this, Loader.EVENTURL, -1, null, null)
val event = gson.fromJson(eventString, Event::class.java)
var title = event.title
if (event.location.isNotBlank()) {
title += "(@" + event.location + ")"
}
intent = Intent(this, SingleEventActivity::class.java)
intent?.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
intent?.putExtra(Event.EVENT, event.id)
pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_ONE_SHOT)
sendNotification(title, applicationContext.getString(R.string.change_event_new), event.userID)
}
private fun beerPush(beerString: String?) {
Loader.getData(this, Loader.BEERURL, -1, null, null)
val beer = gson.fromJson(beerString, Beer::class.java)
intent = Intent(this, SingleBeerActivity::class.java)
intent?.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
intent?.putExtra(Beer.BEER, beer.id)
pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_ONE_SHOT)
sendNotification(beer.name, applicationContext.getString(R.string.change_beer_new), -1)
}
private fun reviewPush(reviewString: String?) {
Loader.getData(this, Loader.REVIEWURL, -1, null, null)
val review = gson.fromJson(reviewString, Review::class.java)
intent = Intent(this, SingleBeerActivity::class.java)
intent?.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
intent?.putExtra(Beer.BEER, review.beerID)
pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_ONE_SHOT)
sendNotification(review.description, applicationContext.getString(R.string.change_review_new), review.userID)
}
private fun newsPush(newsString: String?) {
val news = gson.fromJson(newsString, News::class.java)
sendNotification(news.title, applicationContext.getString(R.string.change_news_new), -1)
}
private fun meetingPush(meetingString: String?) {
Loader.getData(this, Loader.MEETINGURL, -1, null, null)
val meeting = gson.fromJson(meetingString, Meeting::class.java)
intent = Intent(this, SingleMeetingActivity::class.java)
intent?.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
intent?.putExtra(Meeting.MEETING, meeting.id)
pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_ONE_SHOT)
sendNotification(meeting.subject, applicationContext.getString(R.string.change_meeting_new), meeting.userID)
}
private fun stickerPush(stickerString: String?) {
val sticker = gson.fromJson(stickerString, Sticker::class.java)
sendNotification(applicationContext.getString(R.string.change_sticker_new), sticker.notes, sticker.userID)
}
/**
* Create and show a simple notification containing the received FCM message.
*/
private fun sendNotification(title: String, summary: String, userId: Int) {
val user = DataUtils.getUser(applicationContext, userId)
val icon = Glide.with(this).asBitmap().load(getGravatarURL(user.email)).submit(300, 300).get()
val defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)
val notificationBuilder = NotificationCompat.Builder(this, "")
.setSmallIcon(R.drawable.launcher_icon)
.setLargeIcon(icon)
.setContentTitle(title)
.setAutoCancel(true)
.setSound(defaultSoundUri)
val style = NotificationCompat.BigTextStyle()
style.setBigContentTitle(title)
style.bigText(summary)
style.setSummaryText(summary)
notificationBuilder.setStyle(style)
if (pendingIntent == null) {
pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_ONE_SHOT)
}
notificationBuilder.setContentIntent(pendingIntent)
val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
notificationManager.notify(0, notificationBuilder.build())
}
companion object {
const val TAG = "MessagingService"
}
}
| gpl-3.0 | 4b4a5a83d5b4d2888077f41c74ce3e89 | 40.888889 | 117 | 0.691424 | 4.435294 | false | false | false | false |
Aidanvii7/Toolbox | delegates-observable-rxjava/src/test/java/com/aidanvii/toolbox/delegates/observable/rxjava/RxSkipDecoratorTest.kt | 1 | 1279 | package com.aidanvii.toolbox.delegates.observable.rxjava
import com.aidanvii.toolbox.assignedButNeverAccessed
import com.aidanvii.toolbox.delegates.observable.doOnNext
import com.aidanvii.toolbox.delegates.observable.observable
import com.aidanvii.toolbox.delegates.observable.skip
import com.aidanvii.toolbox.unusedValue
import com.aidanvii.toolbox.unusedVariable
import com.nhaarman.mockito_kotlin.inOrder
import org.amshove.kluent.mock
import org.junit.Test
@Suppress(assignedButNeverAccessed, unusedValue, unusedVariable)
class RxSkipDecoratorTest {
val mockDoOnNext = mock<(propertyEvent: Int) -> Unit>()
@Test
fun `only propagates values downstream after skipCount has been met`() {
val skipCount = 5
val givenValues = intArrayOf(1, 2, 3, 4, 5, 6, 7)
val expectedValues = givenValues.takeLast(givenValues.size - skipCount)
var property by observable(0)
.toRx()
.skip(skipCount)
.doOnNext { mockDoOnNext(it) }
for (givenValue in givenValues) {
property = givenValue
}
inOrder(mockDoOnNext).apply {
for (expectedValue in expectedValues) {
verify(mockDoOnNext).invoke(expectedValue)
}
}
}
} | apache-2.0 | 173bdbacc03af84245cd020be2df2037 | 32.684211 | 79 | 0.694292 | 4.306397 | false | true | false | false |
JTechMe/JumpGo | app/src/main/java/com/jtechme/jumpgo/search/suggestions/BaseSuggestionsModel.kt | 1 | 4687 | package com.jtechme.jumpgo.search.suggestions
import com.jtechme.jumpgo.database.HistoryItem
import com.jtechme.jumpgo.utils.FileUtils
import com.jtechme.jumpgo.utils.Utils
import android.app.Application
import android.text.TextUtils
import android.util.Log
import okhttp3.*
import java.io.File
import java.io.IOException
import java.io.InputStream
import java.io.UnsupportedEncodingException
import java.net.URL
import java.net.URLEncoder
import java.util.*
import java.util.concurrent.TimeUnit
/**
* The base search suggestions API. Provides common
* fetching and caching functionality for each potential
* suggestions provider.
*/
abstract class BaseSuggestionsModel internal constructor(application: Application, private val encoding: String) {
private val httpClient: OkHttpClient
private val cacheControl = CacheControl.Builder().maxStale(1, TimeUnit.DAYS).build()
/**
* Create a URL for the given query in the given language.
* @param query the query that was made.
* *
* @param language the locale of the user.
* *
* @return should return a URL that can be fetched using a GET.
*/
protected abstract fun createQueryUrl(query: String, language: String): String
/**
* Parse the results of an input stream into a list of [HistoryItem].
* @param inputStream the raw input to parse.
* *
* @param results the list to populate.
* *
* @throws Exception throw an exception if anything goes wrong.
*/
@Throws(Exception::class)
protected abstract fun parseResults(inputStream: InputStream, results: MutableList<HistoryItem>)
init {
val suggestionsCache = File(application.cacheDir, "suggestion_responses")
httpClient = OkHttpClient.Builder()
.cache(Cache(suggestionsCache, FileUtils.megabytesToBytes(1)))
.addNetworkInterceptor(REWRITE_CACHE_CONTROL_INTERCEPTOR)
.build()
}
/**
* Retrieves the results for a query.
* @param rawQuery the raw query to retrieve the results for.
* *
* @return a list of history items for the query.
*/
fun fetchResults(rawQuery: String): List<HistoryItem> {
val filter = ArrayList<HistoryItem>(5)
val query: String
try {
query = URLEncoder.encode(rawQuery, encoding)
} catch (e: UnsupportedEncodingException) {
Log.e(TAG, "Unable to encode the URL", e)
return filter
}
val inputStream = downloadSuggestionsForQuery(query, language) ?: return filter
try {
parseResults(inputStream, filter)
} catch (e: Exception) {
Log.e(TAG, "Unable to parse results", e)
} finally {
Utils.close(inputStream)
}
return filter
}
/**
* This method downloads the search suggestions for the specific query.
* NOTE: This is a blocking operation, do not fetchResults on the UI thread.
* @param query the query to get suggestions for
* *
* @return the cache file containing the suggestions
*/
private fun downloadSuggestionsForQuery(query: String, language: String): InputStream? {
val queryUrl = createQueryUrl(query, language)
try {
val url = URL(queryUrl)
// OkHttp automatically gzips requests
val suggestionsRequest = Request.Builder().url(url)
.addHeader("Accept-Charset", encoding)
.cacheControl(cacheControl)
.build()
val suggestionsResponse = httpClient.newCall(suggestionsRequest).execute()
val responseBody = suggestionsResponse.body()
return responseBody?.byteStream()
} catch (exception: IOException) {
Log.e(TAG, "Problem getting search suggestions", exception)
}
return null
}
companion object {
private val TAG = "BaseSuggestionsModel"
internal val MAX_RESULTS = 5
private val INTERVAL_DAY = TimeUnit.DAYS.toSeconds(1)
private val DEFAULT_LANGUAGE = "en"
private val language by lazy {
var lang = Locale.getDefault().language
if (TextUtils.isEmpty(lang)) {
lang = DEFAULT_LANGUAGE
}
lang
}
private val REWRITE_CACHE_CONTROL_INTERCEPTOR = Interceptor { chain ->
val originalResponse = chain.proceed(chain.request())
originalResponse.newBuilder()
.header("cache-control", "max-age=$INTERVAL_DAY, max-stale=$INTERVAL_DAY")
.build()
}
}
}
| mpl-2.0 | dfcf77fe47a319770ff8b212395fdce6 | 30.456376 | 114 | 0.640068 | 4.817061 | false | false | false | false |
JetBrains/anko | anko/library/static/commons/src/main/java/Async.kt | 2 | 7002 | /*
* Copyright 2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
@file:Suppress("unused")
package org.jetbrains.anko
import android.app.Activity
import android.app.Fragment
import android.content.Context
import android.os.Handler
import android.os.Looper
import java.lang.ref.WeakReference
import java.util.concurrent.ExecutorService
import java.util.concurrent.Executors
import java.util.concurrent.Future
/**
* Execute [f] on the application UI thread.
*/
fun Context.runOnUiThread(f: Context.() -> Unit) {
if (Looper.getMainLooper() === Looper.myLooper()) f() else ContextHelper.handler.post { f() }
}
/**
* Execute [f] on the application UI thread.
*/
@Deprecated(message = "Use support library fragments instead. Framework fragments were deprecated in API 28.")
inline fun Fragment.runOnUiThread(crossinline f: () -> Unit) {
activity?.runOnUiThread { f() }
}
class AnkoAsyncContext<T>(val weakRef: WeakReference<T>)
/**
* Execute [f] on the application UI thread.
* If the [doAsync] receiver still exists (was not collected by GC),
* [f] gets it as a parameter ([f] gets null if the receiver does not exist anymore).
*/
fun <T> AnkoAsyncContext<T>.onComplete(f: (T?) -> Unit) {
val ref = weakRef.get()
if (Looper.getMainLooper() === Looper.myLooper()) {
f(ref)
} else {
ContextHelper.handler.post { f(ref) }
}
}
/**
* Execute [f] on the application UI thread.
* [doAsync] receiver will be passed to [f].
* If the receiver does not exist anymore (it was collected by GC), [f] will not be executed.
*/
fun <T> AnkoAsyncContext<T>.uiThread(f: (T) -> Unit): Boolean {
val ref = weakRef.get() ?: return false
if (Looper.getMainLooper() === Looper.myLooper()) {
f(ref)
} else {
ContextHelper.handler.post { f(ref) }
}
return true
}
/**
* Execute [f] on the application UI thread if the underlying [Activity] still exists and is not finished.
* The receiver [Activity] will be passed to [f].
* If it is not exist anymore or if it was finished, [f] will not be called.
*/
fun <T: Activity> AnkoAsyncContext<T>.activityUiThread(f: (T) -> Unit): Boolean {
val activity = weakRef.get() ?: return false
if (activity.isFinishing) return false
activity.runOnUiThread { f(activity) }
return true
}
fun <T: Activity> AnkoAsyncContext<T>.activityUiThreadWithContext(f: Context.(T) -> Unit): Boolean {
val activity = weakRef.get() ?: return false
if (activity.isFinishing) return false
activity.runOnUiThread { activity.f(activity) }
return true
}
@JvmName("activityContextUiThread")
fun <T: Activity> AnkoAsyncContext<AnkoContext<T>>.activityUiThread(f: (T) -> Unit): Boolean {
val activity = weakRef.get()?.owner ?: return false
if (activity.isFinishing) return false
activity.runOnUiThread { f(activity) }
return true
}
@JvmName("activityContextUiThreadWithContext")
fun <T: Activity> AnkoAsyncContext<AnkoContext<T>>.activityUiThreadWithContext(f: Context.(T) -> Unit): Boolean {
val activity = weakRef.get()?.owner ?: return false
if (activity.isFinishing) return false
activity.runOnUiThread { activity.f(activity) }
return true
}
@Deprecated(message = "Use support library fragments instead. Framework fragments were deprecated in API 28.")
fun <T: Fragment> AnkoAsyncContext<T>.fragmentUiThread(f: (T) -> Unit): Boolean {
val fragment = weakRef.get() ?: return false
if (fragment.isDetached) return false
val activity = fragment.activity ?: return false
activity.runOnUiThread { f(fragment) }
return true
}
@Deprecated(message = "Use support library fragments instead. Framework fragments were deprecated in API 28.")
fun <T: Fragment> AnkoAsyncContext<T>.fragmentUiThreadWithContext(f: Context.(T) -> Unit): Boolean {
val fragment = weakRef.get() ?: return false
if (fragment.isDetached) return false
val activity = fragment.activity ?: return false
activity.runOnUiThread { activity.f(fragment) }
return true
}
private val crashLogger = { throwable : Throwable -> throwable.printStackTrace() }
/**
* Execute [task] asynchronously.
*
* @param exceptionHandler optional exception handler.
* If defined, any exceptions thrown inside [task] will be passed to it. If not, exceptions will be ignored.
* @param task the code to execute asynchronously.
*/
fun <T> T.doAsync(
exceptionHandler: ((Throwable) -> Unit)? = crashLogger,
task: AnkoAsyncContext<T>.() -> Unit
): Future<Unit> {
val context = AnkoAsyncContext(WeakReference(this))
return BackgroundExecutor.submit {
return@submit try {
context.task()
} catch (thr: Throwable) {
val result = exceptionHandler?.invoke(thr)
if (result != null) {
result
} else {
Unit
}
}
}
}
fun <T> T.doAsync(
exceptionHandler: ((Throwable) -> Unit)? = crashLogger,
executorService: ExecutorService,
task: AnkoAsyncContext<T>.() -> Unit
): Future<Unit> {
val context = AnkoAsyncContext(WeakReference(this))
return executorService.submit<Unit> {
try {
context.task()
} catch (thr: Throwable) {
exceptionHandler?.invoke(thr)
}
}
}
fun <T, R> T.doAsyncResult(
exceptionHandler: ((Throwable) -> Unit)? = crashLogger,
task: AnkoAsyncContext<T>.() -> R
): Future<R> {
val context = AnkoAsyncContext(WeakReference(this))
return BackgroundExecutor.submit {
try {
context.task()
} catch (thr: Throwable) {
exceptionHandler?.invoke(thr)
throw thr
}
}
}
fun <T, R> T.doAsyncResult(
exceptionHandler: ((Throwable) -> Unit)? = crashLogger,
executorService: ExecutorService,
task: AnkoAsyncContext<T>.() -> R
): Future<R> {
val context = AnkoAsyncContext(WeakReference(this))
return executorService.submit<R> {
try {
context.task()
} catch (thr: Throwable) {
exceptionHandler?.invoke(thr)
throw thr
}
}
}
internal object BackgroundExecutor {
var executor: ExecutorService =
Executors.newScheduledThreadPool(2 * Runtime.getRuntime().availableProcessors())
fun <T> submit(task: () -> T): Future<T> = executor.submit(task)
}
private object ContextHelper {
val handler = Handler(Looper.getMainLooper())
}
| apache-2.0 | cea6d5e87f785c505357262029a46ed3 | 32.184834 | 113 | 0.669809 | 4.205405 | false | false | false | false |
pdvrieze/ProcessManager | ProcessEngine/core/src/jvmMain/kotlin/nl/adaptivity/process/engine/processModel/ExecutableDefineType.kt | 1 | 4640 | /*
* Copyright (c) 2018.
*
* This file is part of ProcessManager.
*
* ProcessManager is free software: you can redistribute it and/or modify it under the terms of version 3 of the
* GNU Lesser General Public License as published by the Free Software Foundation.
*
* ProcessManager 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 Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License along with ProcessManager. If not,
* see <http://www.gnu.org/licenses/>.
*/
package nl.adaptivity.process.engine.processModel
import net.devrieze.util.Handle
import net.devrieze.util.security.SecureObject
import nl.adaptivity.process.engine.*
import nl.adaptivity.process.processModel.*
import nl.adaptivity.util.DomUtil
import nl.adaptivity.xmlutil.SimpleNamespaceContext
import nl.adaptivity.xmlutil.XmlException
import nl.adaptivity.xmlutil.XmlUtilInternal
import nl.adaptivity.xmlutil.siblingsToFragment
import nl.adaptivity.xmlutil.util.CompactFragment
import nl.adaptivity.xmlutil.util.ICompactFragment
import nl.adaptivity.xmlutil.util.XMLFragmentStreamReader
import org.w3c.dom.NodeList
import java.io.CharArrayReader
import java.sql.SQLException
import javax.xml.xpath.XPathConstants
actual fun IXmlDefineType.applyData(nodeInstanceSource: IProcessInstance, context: ActivityInstanceContext): ProcessData {
// TODO, make this not need engineData
val nodeInstance = nodeInstanceSource.getChildNodeInstance(context.handle)
return applyDataImpl(nodeInstanceSource, refNode?.let { nodeInstance.resolvePredecessor(nodeInstanceSource, it)}, context.processContext.handle)
}
@Throws(SQLException::class)
actual fun IXmlDefineType.applyFromProcessInstance(processInstance: ProcessInstance.Builder): ProcessData {
val predecessor: IProcessNodeInstance? = refNode?.let { refNode -> processInstance
.allChildNodeInstances { it.node.id == refNode }
.lastOrNull()
}
return applyDataImpl(processInstance, predecessor?.build(processInstance), processInstance.handle)
}
@OptIn(XmlUtilInternal::class)
private fun IXmlDefineType.applyDataImpl(nodeInstanceSource: IProcessInstance, predecessor: IProcessNodeInstance?, hProcessInstance: Handle<SecureObject<ProcessInstance>>): ProcessData {
val processData: ProcessData
val predRefName = predecessor?.node?.effectiveRefName(refName)
if (predecessor != null && predRefName != null) {
val origpair = predecessor.getResult(predRefName)
if (origpair == null) {
// TODO on missing data do something else than an empty value
processData = ProcessData.missingData(name)
} else {
val xPath = when (this) {
is XPathHolder -> xPath
else -> null
}
processData = when (xPath) {
null -> ProcessData(name, origpair.content)
else -> ProcessData(
name,
DomUtil.nodeListToFragment(
xPath.evaluate(origpair.contentFragment, XPathConstants.NODESET) as NodeList
)
)
}
}
} else if (predecessor==null && !refName.isNullOrEmpty()) { // Reference to container
return nodeInstanceSource.inputs.single { it.name == refName }.let { ProcessData(name, it.content) }
} else {
processData = ProcessData(name, CompactFragment(""))
}
val content = content
if (content != null && content.isNotEmpty()) {
try {
val transformer = PETransformer.create(SimpleNamespaceContext.from(originalNSContext), processData)
val fragmentReader =
when (this) {
is ICompactFragment -> XMLFragmentStreamReader.from(this)
else -> XMLFragmentStreamReader.from(CharArrayReader(content), originalNSContext)
}
val reader = transformer.createFilter(fragmentReader)
if (reader.hasNext()) reader.next() // Initialise the reader
val transformed = reader.siblingsToFragment()
return ProcessData(name, transformed)
} catch (e: XmlException) {
throw RuntimeException(e)
}
} else {
return processData
}
}
private fun ProcessNode.effectiveRefName(refName: String?): String? = when {
! refName.isNullOrEmpty() -> refName
else -> results.singleOrNull()?.getName()
}
| lgpl-3.0 | 55145ec2ea83a227f39a32a4ab2c4e77 | 41.181818 | 186 | 0.69569 | 5.005394 | false | false | false | false |
wordpress-mobile/WordPress-Stores-Android | plugins/woocommerce/src/main/kotlin/org/wordpress/android/fluxc/network/rest/wpcom/wc/leaderboards/LeaderboardProductItem.kt | 1 | 6730 | package org.wordpress.android.fluxc.network.rest.wpcom.wc.leaderboards
import android.annotation.TargetApi
import android.os.Build
import android.text.Html
import android.text.SpannableStringBuilder
import android.text.style.URLSpan
import org.wordpress.android.fluxc.network.rest.wpcom.wc.leaderboards.LeaderboardsApiResponse.LeaderboardItemRow
import org.wordpress.android.fluxc.network.rest.wpcom.wc.leaderboards.LeaderboardsApiResponse.Type.PRODUCTS
/**
* The API response from the V4 Leaderboards endpoint returns the Top Performers Products list as an array of arrays,
* each inner array represents a Top Performer Product itself, so in the end it's an array of Top Performers items.
*
* Each Top Performer item is an array containing three objects with the following properties: display and value.
*
* Single Top Performer item response example:
[
{
"display": "<a href='https:\/\/mystagingwebsite.com\/wp-admin\/admin.php?page=wc-admin&path=\/analytics\/products&filter=single_product&products=14'>Beanie<\/a>",
"value": "Beanie"
},
{
"display": "2.000",
"value": 2000
},
{
"display": "<span class=\"woocommerce-Price-amount amount\"><span class=\"woocommerce-Price-currencySymbol\">R$<\/span>36.000,00<\/span>",
"value": 36000
}
]
This class represents one Single Top Performer item response as a Product type one
*/
@Suppress("MaxLineLength")
class LeaderboardProductItem(
private val itemRows: Array<LeaderboardItemRow>? = null
) {
val quantity
get() = itemRows
?.second()
?.value
val total
get() = itemRows
?.third()
?.value
/**
* This property will operate and transform a HTML tag in order to retrieve the currency symbol out of it.
*
* Example:
* HTML tag -> <span class=\"woocommerce-Price-amount amount\"><span class=\"woocommerce-Price-currencySymbol\">R$<\/span>36.000,00<\/span>
*
* split from ">" delimiter
* Output: string list containing
* <span class=\"woocommerce-Price-amount amount\"
* <span class=\"woocommerce-Price-currencySymbol\"
* R$<\/span
* 36.000,00<\/span
*
* first who contains "&#"
* Output: R$<\/span>
*
* split from ";" delimiter
* Output: string list containing
* R
* $
* <\/span>
*
* filter what contains "&#"
* Output: string list containing
* R
* $
*
* reduce string list
* Output: R$
*
* fromHtmlWithSafeApiCall
* Output: R$
*/
@Suppress("MaxLineLength") val currency by lazy {
priceAmountHtmlTag
?.split(">")
?.firstOrNull { it.contains("&#") }
?.split(";")
?.filter { it.contains("&#") }
?.reduce { total, new -> "$total$new" }
?.run { fromHtmlWithSafeApiCall(this) }
?: plainTextCurrency
}
/**
* This property will serve as a fallback for cases where the currency is represented in plain text instead of
* HTML currency code.
*
* It will extract the raw content between tags and leave only the currency information
*
* Example:
*
* HTML tag -> <span class=\"woocommerce-Price-amount amount\"><span class=\"woocommerce-Price-currencySymbol\">DKK<\/span>36.000,00<\/span>
*
* parse HTML tag to string
* Output: DKK36.000,00
*
* regex filter with replace
* Output: DKK
*/
@Suppress("MaxLineLength") private val plainTextCurrency by lazy {
fromHtmlWithSafeApiCall(priceAmountHtmlTag)
.toString()
.replace(Regex("[0-9.,]"), "")
}
/**
* This property will operate and transform a URL string in order to retrieve the product id parameter out of it.
*
* Example:
* URL string -> https:\/\/mystagingwebsite.com\/wp-admin\/admin.php?page=wc-admin&path=\/analytics\/products&filter=single_product&products=14
*
* split from "&" delimiter
* Output: string list containing
* https:\/\/mystagingwebsite.com\/wp-admin\/admin.php?page=wc-admin
* filter=single_product
* products=14
*
* first who contains "products="
* Output: products=14
*
* split from "=" delimiter
* Output: string list containing
* products
* 14
*
* extract last string from the list
* Output: 14 as String
*
* try to convert to long
* Output: 14 as Long
*/
@Suppress("MaxLineLength") val productId by lazy {
link
?.split("&")
?.firstOrNull { it.contains("${PRODUCTS.value}=", true) }
?.split("=")
?.last()
?.toLongOrNull()
}
/**
* This property will operate and transform a HTML tag in order to retrieve the inner URL out of the <a href/> tag
* using the [SpannableStringBuilder] implementation in order to parse it
*/
private val link by lazy {
fromHtmlWithSafeApiCall(itemHtmlTag)
.run { this as? SpannableStringBuilder }
?.spansAsList()
?.firstOrNull()
?.url
}
private val itemHtmlTag by lazy {
itemRows
?.first()
?.display
}
private val priceAmountHtmlTag by lazy {
itemRows
?.third()
?.display
}
private fun SpannableStringBuilder.spansAsList() =
getSpans(0, length, URLSpan::class.java)
.toList()
@TargetApi(Build.VERSION_CODES.N)
private fun fromHtmlWithSafeApiCall(source: String?) = source
?.takeIf { Build.VERSION.SDK_INT >= Build.VERSION_CODES.N }?.let {
Html.fromHtml(source, Html.FROM_HTML_MODE_LEGACY)
} ?: Html.fromHtml(source)
/**
* Returns the second object of the Top Performer Item Array if exists
*/
private fun Array<LeaderboardItemRow>.second() =
takeIf { isNotEmpty() && size > 1 }
?.let { this[1] }
/**
* Returns the third object of the Top Performer Item Array if exists
*/
private fun Array<LeaderboardItemRow>.third() =
takeIf { isNotEmpty() && size > 2 }
?.let { this[2] }
}
| gpl-2.0 | 5b3c796a7a611be2ebf1e318fd81132f | 33.162437 | 170 | 0.568648 | 4.528937 | false | false | false | false |
wordpress-mobile/WordPress-Stores-Android | example/src/main/java/org/wordpress/android/fluxc/example/ui/products/WooProductFiltersFragment.kt | 2 | 7490 | package org.wordpress.android.fluxc.example.ui.products
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import dagger.android.support.AndroidSupportInjection
import kotlinx.android.synthetic.main.fragment_woo_product_filters.*
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import org.wordpress.android.fluxc.Dispatcher
import org.wordpress.android.fluxc.action.WCProductAction.FETCH_PRODUCTS
import org.wordpress.android.fluxc.example.R.layout
import org.wordpress.android.fluxc.example.prependToLog
import org.wordpress.android.fluxc.example.ui.ListSelectorDialog
import org.wordpress.android.fluxc.example.ui.ListSelectorDialog.Companion.ARG_LIST_SELECTED_ITEM
import org.wordpress.android.fluxc.example.ui.ListSelectorDialog.Companion.LIST_SELECTOR_REQUEST_CODE
import org.wordpress.android.fluxc.generated.WCProductActionBuilder
import org.wordpress.android.fluxc.network.rest.wpcom.wc.product.CoreProductStatus
import org.wordpress.android.fluxc.network.rest.wpcom.wc.product.CoreProductStockStatus
import org.wordpress.android.fluxc.network.rest.wpcom.wc.product.CoreProductType
import org.wordpress.android.fluxc.store.WCProductStore
import org.wordpress.android.fluxc.store.WCProductStore.FetchProductsPayload
import org.wordpress.android.fluxc.store.WCProductStore.OnProductChanged
import org.wordpress.android.fluxc.store.WCProductStore.ProductFilterOption
import org.wordpress.android.fluxc.store.WCProductStore.ProductFilterOption.CATEGORY
import org.wordpress.android.fluxc.store.WCProductStore.ProductFilterOption.STATUS
import org.wordpress.android.fluxc.store.WCProductStore.ProductFilterOption.STOCK_STATUS
import org.wordpress.android.fluxc.store.WCProductStore.ProductFilterOption.TYPE
import org.wordpress.android.fluxc.store.WooCommerceStore
import java.io.Serializable
import javax.inject.Inject
class WooProductFiltersFragment : Fragment() {
@Inject internal lateinit var dispatcher: Dispatcher
@Inject internal lateinit var wooCommerceStore: WooCommerceStore
@Inject internal lateinit var wcProductStore: WCProductStore
private var selectedSiteId: Int = -1
private var filterOptions: MutableMap<ProductFilterOption, String>? = null
companion object {
const val ARG_SELECTED_SITE_ID = "ARG_SELECTED_SITE_ID"
const val ARG_SELECTED_FILTER_OPTIONS = "ARG_SELECTED_FILTER_OPTIONS"
const val LIST_RESULT_CODE_STOCK_STATUS = 101
const val LIST_RESULT_CODE_PRODUCT_TYPE = 102
const val LIST_RESULT_CODE_PRODUCT_STATUS = 103
@JvmStatic
fun newInstance(selectedSitePosition: Int): WooProductFiltersFragment {
return WooProductFiltersFragment().apply {
this.selectedSiteId = selectedSitePosition
}
}
}
override fun onAttach(context: Context) {
AndroidSupportInjection.inject(this)
super.onAttach(context)
}
override fun onStart() {
super.onStart()
dispatcher.register(this)
}
override fun onStop() {
super.onStop()
dispatcher.unregister(this)
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? =
inflater.inflate(layout.fragment_woo_product_filters, container, false)
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
savedInstanceState?.let { bundle -> selectedSiteId = bundle.getInt(ARG_SELECTED_SITE_ID) }
filterOptions = savedInstanceState?.getSerializable(ARG_SELECTED_FILTER_OPTIONS)
as? MutableMap<ProductFilterOption, String> ?: mutableMapOf()
filter_stock_status.setOnClickListener {
showListSelectorDialog(
CoreProductStockStatus.values().map { it.value }.toList(),
LIST_RESULT_CODE_STOCK_STATUS, filterOptions?.get(STOCK_STATUS)
)
}
filter_by_status.setOnClickListener {
showListSelectorDialog(
CoreProductStatus.values().map { it.value }.toList(),
LIST_RESULT_CODE_PRODUCT_STATUS, filterOptions?.get(STATUS)
)
}
filter_by_type.setOnClickListener {
showListSelectorDialog(
CoreProductType.values().map { it.value }.toList(),
LIST_RESULT_CODE_PRODUCT_TYPE, filterOptions?.get(TYPE)
)
}
filter_by_category.setOnClickListener {
getWCSite()?.let { site ->
val randomCategory = wcProductStore.getProductCategoriesForSite(site).random()
filterOptions?.clear()
filterOptions?.put(CATEGORY, randomCategory.remoteCategoryId.toString())
prependToLog("Selected category: ${randomCategory.name} id: ${randomCategory.remoteCategoryId}")
}
}
filter_products.setOnClickListener {
getWCSite()?.let { site ->
val payload = FetchProductsPayload(site, filterOptions = filterOptions)
dispatcher.dispatch(WCProductActionBuilder.newFetchProductsAction(payload))
} ?: prependToLog("No valid siteId defined...doing nothing")
}
}
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
outState.putInt(ARG_SELECTED_SITE_ID, selectedSiteId)
outState.putSerializable(ARG_SELECTED_FILTER_OPTIONS, filterOptions as? Serializable)
}
private fun getWCSite() = wooCommerceStore.getWooCommerceSites().getOrNull(selectedSiteId)
private fun showListSelectorDialog(listItems: List<String>, resultCode: Int, selectedItem: String? = null) {
fragmentManager?.let { fm ->
val dialog = ListSelectorDialog.newInstance(
this, listItems, resultCode, selectedItem
)
dialog.show(fm, "ListSelectorDialog")
}
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode == LIST_SELECTOR_REQUEST_CODE) {
val selectedItem = data?.getStringExtra(ARG_LIST_SELECTED_ITEM)
when (resultCode) {
LIST_RESULT_CODE_PRODUCT_TYPE -> {
selectedItem?.let { filterOptions?.put(TYPE, it) }
}
LIST_RESULT_CODE_STOCK_STATUS -> {
selectedItem?.let { filterOptions?.put(STOCK_STATUS, it) }
}
LIST_RESULT_CODE_PRODUCT_STATUS -> {
selectedItem?.let { filterOptions?.put(STATUS, it) }
}
}
}
}
@Suppress("unused")
@Subscribe(threadMode = ThreadMode.MAIN)
fun onProductChanged(event: OnProductChanged) {
if (event.isError) {
prependToLog("Error from " + event.causeOfChange + " - error: " + event.error.type)
return
}
if (event.causeOfChange == FETCH_PRODUCTS) {
prependToLog("Fetched ${event.rowsAffected} products")
filterOptions?.let {
if (it.containsKey(CATEGORY)) {
prependToLog("From category ID " + it[CATEGORY])
}
}
}
}
}
| gpl-2.0 | df38c5d7d1f72cedfc445d75bd8ca416 | 42.045977 | 116 | 0.686382 | 4.889034 | false | false | false | false |
KDatabases/Kuery | src/main/kotlin/com/sxtanna/database/task/builder/base/TargetedStatement.kt | 1 | 2914 | package com.sxtanna.database.task.builder.base
import com.sxtanna.database.struct.obj.Target
import com.sxtanna.database.struct.obj.Target.Position
import com.sxtanna.database.struct.obj.Target.Position.*
import com.sxtanna.database.type.base.SqlObject
abstract class TargetedStatement<T : SqlObject, W : TargetedStatement<T, W>> : BuilderStatement() {
val where = mutableListOf<Target>()
@JvmOverloads
fun like(column : String, value : Any, option : Position, not : Boolean = false) = impl().apply { where.add(Target.like(column, value, option, not)) }
@JvmOverloads
fun startsWith(column : String, value : Any, not : Boolean = false) = like(column, value, START, not)
@JvmSynthetic
@JvmName("inStartsWith")
infix fun String.startsWith(value : Any) = startsWith(this, value, false)
@JvmSynthetic
infix fun String.startsNotWith(value : Any) = startsWith(this, value, true)
@JvmOverloads
fun contains(column : String, value : Any, not : Boolean = false) = like(column, value, CONTAINS, not)
@JvmSynthetic
@JvmName("inContains")
infix fun String.contains(value : Any) = contains(this, value, false)
@JvmSynthetic
infix fun String.containsNot(value : Any) = contains(this, value, true)
@JvmOverloads
fun endsWith(column : String, value : Any, not : Boolean = false) = like(column, value, END, not)
@JvmSynthetic
@JvmName("inEndsWith")
infix fun String.endsWith(value : Any) = endsWith(this, value, false)
@JvmSynthetic
infix fun String.endsNotWith(value : Any) = endsWith(this, value, true)
@JvmOverloads
fun equals(column : String, value : Any, not : Boolean = false) = impl().apply { where.add(Target.equals(column, value, not)) }
@JvmSynthetic
@JvmName("inEquals")
infix fun String.equals(value : Any) = equals(this, value, false)
@JvmSynthetic
infix fun String.equalsNot(value : Any) = equals(this, value, true)
@JvmOverloads
fun between(column : String, first : Any, second : Any, not : Boolean = false) = impl().apply { where.add(Target.between(column, first, second, not)) }
@JvmSynthetic
infix fun String.between(data : Pair<Any, Any>) = between(this, data.first, data.second, false)
@JvmSynthetic
infix fun String.notBetween(data : Pair<Any, Any>) = between(this, data.first, data.second, true)
fun lesser(column : String, value : Any, orEqual : Boolean) = impl().apply { where.add(Target.lesser(column, value, orEqual)) }
@JvmSynthetic
infix fun String.lesser(value : Any) = lesser(this, value, false)
@JvmSynthetic
infix fun String.lesserOrEqual(value : Any) = lesser(this, value, true)
fun greater(column : String, value : Any, orEqual : Boolean) = impl().apply { where.add(Target.greater(column, value, orEqual)) }
@JvmSynthetic
infix fun String.greater(value : Any) = greater(this, value, false)
@JvmSynthetic
infix fun String.greaterOrEqual(value : Any) = greater(this, value, true)
abstract protected fun impl() : W
} | apache-2.0 | 4abaed18a1e67b86cee97946a8c593e5 | 31.032967 | 152 | 0.724091 | 3.408187 | false | false | false | false |
LanternPowered/LanternServer | src/main/kotlin/org/lanternpowered/api/item/enchantment/Enchantment.kt | 1 | 1367 | /*
* Lantern
*
* Copyright (c) LanternPowered <https://www.lanternpowered.org>
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* This work is licensed under the terms of the MIT License (MIT). For
* a copy, see 'LICENSE.txt' or <https://opensource.org/licenses/MIT>.
*/
@file:Suppress("FunctionName", "NOTHING_TO_INLINE")
package org.lanternpowered.api.item.enchantment
import java.util.function.Supplier
typealias Enchantment = org.spongepowered.api.item.enchantment.Enchantment
/**
* Constructs a new [Enchantment] with the given [EnchantmentType] and level. If no
* level is specified, then will the minimum one be used instead.
*
* @param type The enchantment type
* @param level The level of the enchantment
* @return The constructed enchantment
*/
inline fun enchantmentOf(type: Supplier<out EnchantmentType>, level: Int = type.get().minimumLevel): Enchantment = Enchantment.of(type, level)
/**
* Constructs a new [Enchantment] with the given [EnchantmentType] and level. If no
* level is specified, then will the minimum one be used instead.
*
* @param type The enchantment type
* @param level The level of the enchantment
* @return The constructed enchantment
*/
inline fun enchantmentOf(type: EnchantmentType, level: Int = type.minimumLevel): Enchantment = Enchantment.of(type, level)
| mit | 357147d3538fd13bcb328ef6daee76e6 | 35.945946 | 142 | 0.749086 | 4.020588 | false | false | false | false |
simo-andreev/Colourizmus | app/src/main/java/bg/o/sim/colourizmus/model/CustomColour.kt | 1 | 1341 | package bg.o.sim.colourizmus.model
import androidx.room.ColumnInfo
import androidx.room.Entity
import androidx.room.Index
import androidx.room.PrimaryKey
import androidx.annotation.ColorInt
import java.io.Serializable
const val TABLE: String = "colour"
const val COLUMN_PK: String = "value"
const val COLUMN_NAME: String = "name"
const val COLUMN_IS_FAVOURITE: String = "is_favourite"
/**
* The [CustomColour] represents a single, named, colour that
* can be marked as favourite and is persisted in on-disk database.
*/
@Entity(tableName = TABLE, indices = [(Index(value = [COLUMN_NAME], unique = true))])
class CustomColour(@ColorInt value: Int, name: String) : Serializable {
@PrimaryKey(autoGenerate = false)
@ColumnInfo(name = COLUMN_PK)
@ColorInt val value: Int = value
@ColumnInfo(name = COLUMN_NAME)
var name: String = name
@ColumnInfo(name = COLUMN_IS_FAVOURITE)
var isFavourite: Boolean = false
// TODO: 16/02/18 - include name in hash? Yes? No?
override fun hashCode(): Int = value
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (this.javaClass != other?.javaClass) return false
other as CustomColour
if (value != other.value) return false
if (name != other.name) return false
return true
}
}
| apache-2.0 | 446e425239c73176a8df46c6e0e9bf4a | 28.152174 | 85 | 0.691275 | 3.955752 | false | false | false | false |
SimonVT/cathode | cathode/src/main/java/net/simonvt/cathode/ui/search/SearchFragment.kt | 1 | 6010 | /*
* Copyright (C) 2016 Simon Vig Therkildsen
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.simonvt.cathode.ui.search
import android.content.Context
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProviders
import androidx.recyclerview.widget.RecyclerView.ViewHolder
import butterknife.BindView
import net.simonvt.cathode.R
import net.simonvt.cathode.common.ui.fragment.ToolbarGridFragment
import net.simonvt.cathode.common.widget.ErrorView
import net.simonvt.cathode.common.widget.SearchView
import net.simonvt.cathode.search.SearchHandler.SearchResult
import net.simonvt.cathode.settings.Settings
import net.simonvt.cathode.sync.scheduler.SearchTaskScheduler
import net.simonvt.cathode.ui.CathodeViewModelFactory
import net.simonvt.cathode.ui.LibraryType
import net.simonvt.cathode.ui.NavigationListener
import javax.inject.Inject
class SearchFragment @Inject constructor(
private val viewModelFactory: CathodeViewModelFactory,
private val searchScheduler: SearchTaskScheduler
) : ToolbarGridFragment<ViewHolder>(), SearchAdapter.OnResultClickListener {
@BindView(R.id.errorView)
@JvmField
var errorView: ErrorView? = null
private lateinit var viewModel: SearchViewModel
private var searchView: SearchView? = null
private var requestFocus: Boolean = false
private var sortBy: SortBy? = null
private val adapter = SearchAdapter(this)
private var displayErrorView: Boolean = false
private var resetScrollPosition: Boolean = false
private lateinit var navigationListener: NavigationListener
enum class SortBy(val key: String) {
TITLE("title"), RATING("rating"), RELEVANCE("relevance");
override fun toString(): String {
return key
}
companion object {
fun fromValue(value: String): SortBy? {
return values().firstOrNull { it.key == value }
}
}
}
override fun onAttach(context: Context) {
super.onAttach(context)
navigationListener = requireActivity() as NavigationListener
}
override fun onCreate(inState: Bundle?) {
super.onCreate(inState)
sortBy = SortBy.fromValue(
Settings.get(requireContext()).getString(Settings.Sort.SEARCH, SortBy.TITLE.key)!!
)
setAdapter(adapter)
setEmptyText(R.string.search_empty)
if (inState == null) {
requestFocus = true
}
viewModel = ViewModelProviders.of(this, viewModelFactory).get(SearchViewModel::class.java)
viewModel.recents.observe(
this,
Observer { recentQueries -> adapter.setRecentQueries(recentQueries) })
viewModel.liveResults.observe(this, resultsObserver)
}
private val resultsObserver = Observer<SearchResult> { (success, results) ->
adapter.setSearching(false)
displayErrorView = !success
updateErrorView()
if (success) {
adapter.setResults(results)
resetScrollPosition = true
updateScrollPosition()
if (view != null) {
updateScrollPosition()
}
} else {
adapter.setResults(null)
}
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
inState: Bundle?
): View? {
return inflater.inflate(R.layout.search_fragment, container, false)
}
override fun onViewCreated(view: View, inState: Bundle?) {
super.onViewCreated(view, inState)
searchView = LayoutInflater.from(toolbar!!.context)
.inflate(R.layout.search_view, toolbar, false) as SearchView
toolbar!!.addView(searchView)
searchView!!.setListener(object : SearchView.SearchViewListener {
override fun onTextChanged(newText: String) {
queryChanged(newText)
}
override fun onSubmit(query: String) {
query(query)
searchView!!.clearFocus()
}
})
updateErrorView()
if (requestFocus) {
requestFocus = false
searchView!!.onActionViewExpanded()
}
}
override fun onDestroyView() {
searchView = null
super.onDestroyView()
}
override fun onViewStateRestored(inState: Bundle?) {
super.onViewStateRestored(inState)
updateScrollPosition()
}
private fun updateScrollPosition() {
if (view != null && resetScrollPosition) {
resetScrollPosition = false
recyclerView.scrollToPosition(0)
}
}
private fun updateErrorView() {
if (displayErrorView) {
errorView!!.show()
} else {
errorView!!.hide()
}
}
private fun queryChanged(query: String) {
viewModel.search(query)
}
private fun query(query: String) {
if (!query.isBlank()) {
adapter.setSearching(true)
searchScheduler.insertRecentQuery(query)
}
viewModel.search(query)
}
override fun onShowClicked(showId: Long, title: String?, overview: String?) {
navigationListener.onDisplayShow(showId, title, overview, LibraryType.WATCHED)
if (title != null) {
searchScheduler.insertRecentQuery(title)
}
}
override fun onMovieClicked(movieId: Long, title: String?, overview: String?) {
navigationListener.onDisplayMovie(movieId, title, overview)
if (title != null) {
searchScheduler.insertRecentQuery(title)
}
}
override fun onQueryClicked(query: String) {
searchView?.clearFocus()
searchView?.query = query
adapter.setSearching(true)
query(query)
}
companion object {
const val TAG = "net.simonvt.cathode.ui.search.SearchFragment"
}
}
| apache-2.0 | 11024c673130188224ef7a462e34bf8f | 27.215962 | 94 | 0.718968 | 4.518797 | false | false | false | false |
ykrank/S1-Next | app/src/main/java/me/ykrank/s1next/widget/download/ProgressManager.kt | 1 | 1810 | package me.ykrank.s1next.widget.download
import com.liulishuo.okdownload.DownloadTask
import com.liulishuo.okdownload.core.cause.EndCause
import com.liulishuo.okdownload.core.listener.assist.Listener1Assist
import java.util.*
object ProgressManager {
private val mListeners = WeakHashMap<String, MutableList<ProgressListener>>()
fun addListener(url: String, listener: ProgressListener) {
var progressListeners: MutableList<ProgressListener>?
synchronized(ProgressManager::class.java) {
progressListeners = mListeners[url]
if (progressListeners == null) {
progressListeners = LinkedList()
mListeners[url] = progressListeners
}
}
progressListeners?.add(listener)
}
fun notifyProgress(task: DownloadTask, currentOffset: Long, totalLength: Long) {
val progressListeners = mListeners[task.url]
if (progressListeners != null) {
val array = progressListeners.toTypedArray()
for (i in array.indices) {
array[i].onProgress(task, currentOffset, totalLength)
}
}
}
fun notifyTaskEnd(task: DownloadTask, cause: EndCause, realCause: java.lang.Exception?, model: Listener1Assist.Listener1Model) {
val progressListeners = mListeners[task.url]
if (progressListeners != null) {
val array = progressListeners.toTypedArray()
for (i in array.indices) {
array[i].taskEnd(task, cause, realCause, model)
}
}
}
}
interface ProgressListener {
fun onProgress(task: DownloadTask, currentOffset: Long, totalLength: Long)
fun taskEnd(task: DownloadTask, cause: EndCause, realCause: java.lang.Exception?, model: Listener1Assist.Listener1Model)
} | apache-2.0 | 141f374739bd655b0accd6a7f80b4015 | 36.729167 | 132 | 0.670166 | 4.677003 | false | false | false | false |
Mauin/detekt | detekt-core/src/test/kotlin/io/gitlab/arturbosch/detekt/core/TestPatternTest.kt | 1 | 1244 | package io.gitlab.arturbosch.detekt.core
import io.gitlab.arturbosch.detekt.api.SplitPattern
import io.gitlab.arturbosch.detekt.test.yamlConfig
import org.assertj.core.api.Assertions
import org.jetbrains.spek.api.Spek
import org.jetbrains.spek.api.dsl.given
import org.jetbrains.spek.api.dsl.it
import java.nio.file.Path
import java.nio.file.Paths
/**
* @author Artur Bosch
*/
class TestPatternTest : Spek({
given("a bunch of paths") {
val pathContent = """
a/b/c/test/abcTest.kt,
a/b/c/test/adeTest.kt,
a/b/c/test/afgTest.kt,
a/b/c/d/ab.kt,
a/b/c/d/bb.kt,
a/b/c/d/cb.kt
"""
val paths = SplitPattern(pathContent).mapAll { Paths.get(it) }
fun splitSources(pattern: TestPattern, paths: List<Path>): Pair<List<Path>, List<Path>> =
paths.partition { pattern.matches(it.toString()) }
fun preparePattern() = createTestPattern(yamlConfig("patterns/test-pattern.yml"))
it("should split the given paths to main and test sources") {
val pattern = preparePattern()
val (testSources, mainSources) = splitSources(pattern, paths)
Assertions.assertThat(testSources).allMatch { it.toString().endsWith("Test.kt") }
Assertions.assertThat(mainSources).allMatch { it.toString().endsWith("b.kt") }
}
}
})
| apache-2.0 | 33f74bc030db8fdbd4b298fdf0812758 | 28.619048 | 91 | 0.719453 | 3.041565 | false | true | false | false |
PaulWoitaschek/Voice | bookOverview/src/main/kotlin/voice/bookOverview/views/ExplanationTooltip.kt | 1 | 3229 | package voice.bookOverview.views
import androidx.compose.foundation.layout.ColumnScope
import androidx.compose.foundation.layout.widthIn
import androidx.compose.foundation.shape.GenericShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Path
import androidx.compose.ui.graphics.PathOperation
import androidx.compose.ui.graphics.addOutline
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.unit.Density
import androidx.compose.ui.unit.IntOffset
import androidx.compose.ui.unit.IntRect
import androidx.compose.ui.unit.IntSize
import androidx.compose.ui.unit.LayoutDirection
import androidx.compose.ui.unit.dp
import androidx.compose.ui.window.Popup
import androidx.compose.ui.window.PopupPositionProvider
@Composable
internal fun ExplanationTooltip(content: @Composable ColumnScope.() -> Unit) {
var triangleCenterX: Float? by remember { mutableStateOf(null) }
val popupPositionProvider = ExplanationTooltipPopupPositionProvider(LocalDensity.current) {
triangleCenterX = it.toFloat()
}
Popup(popupPositionProvider = popupPositionProvider) {
Card(
modifier = Modifier.widthIn(max = 240.dp),
elevation = CardDefaults.cardElevation(defaultElevation = 4.dp),
shape = explanationTooltipShape(triangleCenterX, LocalDensity.current),
) {
content()
}
}
}
private class ExplanationTooltipPopupPositionProvider(
private val density: Density,
private val onTriangleCenterX: (Int) -> Unit,
) : PopupPositionProvider {
override fun calculatePosition(
anchorBounds: IntRect,
windowSize: IntSize,
layoutDirection: LayoutDirection,
popupContentSize: IntSize,
): IntOffset {
val rightMargin = with(density) { 16.dp.toPx() }
var offset = IntOffset(anchorBounds.center.x - popupContentSize.width / 2, anchorBounds.bottom)
if ((offset.x + popupContentSize.width + rightMargin) > windowSize.width) {
offset -= IntOffset(rightMargin.toInt() + (offset.x + popupContentSize.width - windowSize.width), 0)
}
onTriangleCenterX(anchorBounds.center.x - offset.x)
return offset
}
}
private fun explanationTooltipShape(triangleCenterX: Float?, density: Density): GenericShape {
val triangleSize = with(density) {
28.dp.toPx()
}
return GenericShape { size, layoutDirection ->
addOutline(
RoundedCornerShape(12.0.dp)
.createOutline(size, layoutDirection, density),
)
if (triangleCenterX != null) {
val trianglePath = Path().apply {
moveTo(
x = triangleCenterX - triangleSize / 2F,
y = 0F,
)
lineTo(
x = triangleCenterX,
y = -triangleSize / 2F,
)
lineTo(
x = triangleCenterX + triangleSize / 2F,
y = 0F,
)
close()
}
op(this, trianglePath, PathOperation.Union)
}
}
}
| gpl-3.0 | 1d660e00f4184499aff02ed1e08eab69 | 32.989474 | 106 | 0.73738 | 4.381275 | false | false | false | false |
TWiStErRob/TWiStErRob | KotlinAdvent2018/week2/src/main/kotlin/net/twisterrob/challenges/adventOfKotlin2018/week2/global/CoffeeShop.kt | 1 | 1035 | package net.twisterrob.challenges.adventOfKotlin2018.week2.global
import net.twisterrob.challenges.adventOfKotlin2018.week2.Twinject
import net.twisterrob.challenges.adventOfKotlin2018.week2.reflect.register
import net.twisterrob.challenges.adventOfKotlin2018.week2.reflect.registerContract
val inject = (Twinject()) {
// reflective creation (same type)
register<CoffeeMaker>()
// reflective creation (super type)
registerContract<Pump, Thermosiphon>()
// custom creation
register<Heater> { EletrictHeater() }
}
fun main(args: Array<String>) {
val maker: CoffeeMaker = inject()
maker.brew()
}
interface Pump {
fun pump()
}
interface Heater {
fun heat()
}
class Thermosiphon(
private val heater: Heater = inject()
) : Pump {
override fun pump() {
heater.heat()
println("=> => pumping => =>")
}
}
class CoffeeMaker {
private val pump: Pump by inject
fun brew() {
pump.pump()
println(" [_]P coffee! [_]P")
}
}
class EletrictHeater : Heater {
override fun heat() {
println("~ ~ ~ heating ~ ~ ~")
}
}
| unlicense | 58d6d47c8d13b92e67c733b16b15517c | 18.528302 | 82 | 0.711111 | 3.204334 | false | false | false | false |
FHannes/intellij-community | platform/credential-store/src/linuxSecretLibrary.kt | 6 | 5824 | package com.intellij.credentialStore
import com.intellij.util.io.jna.DisposableMemory
import com.sun.jna.Library
import com.sun.jna.Native
import com.sun.jna.Pointer
import com.sun.jna.Structure
private val LIBRARY by lazy { Native.loadLibrary("secret-1", SecretLibrary::class.java) as SecretLibrary }
private const val SECRET_SCHEMA_NONE = 0
private const val SECRET_SCHEMA_ATTRIBUTE_STRING = 0
// explicitly create pointer to be explicitly dispose it to avoid sensitive data in the memory
internal fun stringPointer(data: ByteArray, clearInput: Boolean = false): DisposableMemory {
val pointer = DisposableMemory(data.size + 1L)
pointer.write(0, data, 0, data.size)
pointer.setByte(data.size.toLong(), 0.toByte())
if (clearInput) {
data.fill(0)
}
return pointer
}
// we use default collection, it seems no way to use custom
internal class SecretCredentialStore(schemeName: String) : CredentialStore {
private val serviceAttributeNamePointer by lazy { stringPointer("service".toByteArray()) }
private val accountAttributeNamePointer by lazy { stringPointer("account".toByteArray()) }
private val scheme by lazy {
LIBRARY.secret_schema_new(schemeName, SECRET_SCHEMA_NONE,
serviceAttributeNamePointer, SECRET_SCHEMA_ATTRIBUTE_STRING,
accountAttributeNamePointer, SECRET_SCHEMA_ATTRIBUTE_STRING,
null)
}
override fun get(attributes: CredentialAttributes): Credentials? {
checkError("secret_password_lookup_sync") { errorRef ->
val serviceNamePointer = stringPointer(attributes.serviceName.toByteArray())
if (attributes.userName == null) {
LIBRARY.secret_password_lookup_sync(scheme, null, errorRef, serviceAttributeNamePointer, serviceNamePointer, null)?.let {
// Secret Service doesn't allow to get attributes, so, we store joined data
return splitData(it)
}
}
else {
LIBRARY.secret_password_lookup_sync(scheme, null, errorRef,
serviceAttributeNamePointer, serviceNamePointer,
accountAttributeNamePointer, stringPointer(attributes.userName!!.toByteArray()),
null)?.let {
return splitData(it)
}
}
}
return null
}
override fun set(attributes: CredentialAttributes, credentials: Credentials?) {
val serviceNamePointer = stringPointer(attributes.serviceName.toByteArray())
val accountName = attributes.userName ?: credentials?.userName
if (credentials.isEmpty()) {
checkError("secret_password_store_sync") { errorRef ->
if (accountName == null) {
LIBRARY.secret_password_clear_sync(scheme, null, errorRef,
serviceAttributeNamePointer, serviceNamePointer,
null)
}
else {
LIBRARY.secret_password_clear_sync(scheme, null, errorRef,
serviceAttributeNamePointer, serviceNamePointer,
accountAttributeNamePointer, stringPointer(accountName.toByteArray()),
null)
}
}
return
}
val passwordPointer = stringPointer(credentials!!.serialize(!attributes.isPasswordMemoryOnly), true)
checkError("secret_password_store_sync") { errorRef ->
try {
if (accountName == null) {
LIBRARY.secret_password_store_sync(scheme, null, serviceNamePointer, passwordPointer, null, errorRef,
serviceAttributeNamePointer, serviceNamePointer,
null)
}
else {
LIBRARY.secret_password_store_sync(scheme, null, serviceNamePointer, passwordPointer, null, errorRef,
serviceAttributeNamePointer, serviceNamePointer,
accountAttributeNamePointer, stringPointer(accountName.toByteArray()),
null)
}
}
finally {
passwordPointer.dispose()
}
}
}
}
private inline fun <T> checkError(method: String, task: (errorRef: Array<GErrorStruct?>) -> T): T {
val errorRef = arrayOf<GErrorStruct?>(null)
val result = task(errorRef)
val error = errorRef.get(0)
if (error != null && error.code !== 0) {
if (error.code == 32584 || error.code == 32618 || error.code == 32606 || error.code == 32642) {
LOG.warn("gnome-keyring not installed or kde doesn't support Secret Service API. $method error code ${error.code}, error message ${error.message}")
}
else {
LOG.error("$method error code ${error.code}, error message ${error.message}")
}
}
return result
}
// we use sync API to simplify - client will use postponed write
private interface SecretLibrary : Library {
fun secret_schema_new(name: String, flags: Int, vararg attributes: Any?): Pointer
fun secret_password_store_sync(scheme: Pointer, collection: Pointer?, label: Pointer, password: Pointer, cancellable: Pointer?, error: Array<GErrorStruct?>, vararg attributes: Pointer?)
fun secret_password_lookup_sync(scheme: Pointer, cancellable: Pointer?, error: Array<GErrorStruct?>, vararg attributes: Pointer?): String?
fun secret_password_clear_sync(scheme: Pointer, cancellable: Pointer?, error: Array<GErrorStruct?>, vararg attributes: Pointer?)
}
@Suppress("unused")
internal class GErrorStruct : Structure() {
@JvmField
var domain = 0
@JvmField
var code = 0
@JvmField
var message: String? = null
override fun getFieldOrder() = listOf("domain", "code", "message")
} | apache-2.0 | 12a34000769b6e251f886eb492635bb0 | 41.518248 | 187 | 0.638049 | 5.149425 | false | false | false | false |
B515/Schedule | app/src/main/kotlin/xyz/b515/schedule/api/ZfRetrofit.kt | 1 | 1892 | package xyz.b515.schedule.api
import okhttp3.*
import retrofit2.Retrofit
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory
import retrofit2.converter.scalars.ScalarsConverterFactory
import java.util.*
import java.util.concurrent.TimeUnit
object ZfRetrofit {
private val server = "http://gdjwgl.bjut.edu.cn"
private val headers = Headers.Builder()
.add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3014.0 Safari/537.36")
.add("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8")
.add("Accept-Encoding", "gzip, deflate, sdch")
.add("Accept-Language", "zh-CN,en-US;q=0.8")
.build()
private val httpClient = OkHttpClient.Builder()
.connectTimeout(10, TimeUnit.SECONDS)
.readTimeout(10, TimeUnit.SECONDS)
.addInterceptor { chain -> chain.proceed(chain.request().newBuilder().headers(headers).build()) }
.cookieJar(object : CookieJar {
private val cookieStore = HashMap<String, List<Cookie>>()
override fun saveFromResponse(url: HttpUrl, cookies: List<Cookie>) {
cookieStore.put(url.host(), cookies)
}
override fun loadForRequest(url: HttpUrl): List<Cookie> {
val cookies = cookieStore[url.host()]
return cookies ?: ArrayList()
}
})
.build()
val zfService: ZfService by lazy {
Retrofit.Builder()
.baseUrl(server)
.client(httpClient)
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.addConverterFactory(ScalarsConverterFactory.create())
.build()
.create(ZfService::class.java)
}
}
| apache-2.0 | 76e5a72549539efb5162ee9a3b0e1e05 | 42 | 147 | 0.604123 | 4.3 | false | false | false | false |
ansman/okhttp | okhttp/src/main/kotlin/okhttp3/internal/ws/WebSocketReader.kt | 6 | 9947 | /*
* Copyright (C) 2014 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package okhttp3.internal.ws
import java.io.Closeable
import java.io.IOException
import java.net.ProtocolException
import java.util.concurrent.TimeUnit
import okhttp3.internal.and
import okhttp3.internal.toHexString
import okhttp3.internal.ws.WebSocketProtocol.B0_FLAG_FIN
import okhttp3.internal.ws.WebSocketProtocol.B0_FLAG_RSV1
import okhttp3.internal.ws.WebSocketProtocol.B0_FLAG_RSV2
import okhttp3.internal.ws.WebSocketProtocol.B0_FLAG_RSV3
import okhttp3.internal.ws.WebSocketProtocol.B0_MASK_OPCODE
import okhttp3.internal.ws.WebSocketProtocol.B1_FLAG_MASK
import okhttp3.internal.ws.WebSocketProtocol.B1_MASK_LENGTH
import okhttp3.internal.ws.WebSocketProtocol.CLOSE_NO_STATUS_CODE
import okhttp3.internal.ws.WebSocketProtocol.OPCODE_BINARY
import okhttp3.internal.ws.WebSocketProtocol.OPCODE_CONTINUATION
import okhttp3.internal.ws.WebSocketProtocol.OPCODE_CONTROL_CLOSE
import okhttp3.internal.ws.WebSocketProtocol.OPCODE_CONTROL_PING
import okhttp3.internal.ws.WebSocketProtocol.OPCODE_CONTROL_PONG
import okhttp3.internal.ws.WebSocketProtocol.OPCODE_FLAG_CONTROL
import okhttp3.internal.ws.WebSocketProtocol.OPCODE_TEXT
import okhttp3.internal.ws.WebSocketProtocol.PAYLOAD_BYTE_MAX
import okhttp3.internal.ws.WebSocketProtocol.PAYLOAD_LONG
import okhttp3.internal.ws.WebSocketProtocol.PAYLOAD_SHORT
import okhttp3.internal.ws.WebSocketProtocol.toggleMask
import okio.Buffer
import okio.BufferedSource
import okio.ByteString
/**
* An [RFC 6455][rfc_6455]-compatible WebSocket frame reader.
*
* This class is not thread safe.
*
* [rfc_6455]: http://tools.ietf.org/html/rfc6455
*/
class WebSocketReader(
private val isClient: Boolean,
val source: BufferedSource,
private val frameCallback: FrameCallback,
private val perMessageDeflate: Boolean,
private val noContextTakeover: Boolean
) : Closeable {
private var closed = false
// Stateful data about the current frame.
private var opcode = 0
private var frameLength = 0L
private var isFinalFrame = false
private var isControlFrame = false
private var readingCompressedMessage = false
private val controlFrameBuffer = Buffer()
private val messageFrameBuffer = Buffer()
/** Lazily initialized on first use. */
private var messageInflater: MessageInflater? = null
// Masks are only a concern for server writers.
private val maskKey: ByteArray? = if (isClient) null else ByteArray(4)
private val maskCursor: Buffer.UnsafeCursor? = if (isClient) null else Buffer.UnsafeCursor()
interface FrameCallback {
@Throws(IOException::class)
fun onReadMessage(text: String)
@Throws(IOException::class)
fun onReadMessage(bytes: ByteString)
fun onReadPing(payload: ByteString)
fun onReadPong(payload: ByteString)
fun onReadClose(code: Int, reason: String)
}
/**
* Process the next protocol frame.
*
* * If it is a control frame this will result in a single call to [FrameCallback].
* * If it is a message frame this will result in a single call to [FrameCallback.onReadMessage].
* If the message spans multiple frames, each interleaved control frame will result in a
* corresponding call to [FrameCallback].
*/
@Throws(IOException::class)
fun processNextFrame() {
readHeader()
if (isControlFrame) {
readControlFrame()
} else {
readMessageFrame()
}
}
@Throws(IOException::class, ProtocolException::class)
private fun readHeader() {
if (closed) throw IOException("closed")
// Disable the timeout to read the first byte of a new frame.
val b0: Int
val timeoutBefore = source.timeout().timeoutNanos()
source.timeout().clearTimeout()
try {
b0 = source.readByte() and 0xff
} finally {
source.timeout().timeout(timeoutBefore, TimeUnit.NANOSECONDS)
}
opcode = b0 and B0_MASK_OPCODE
isFinalFrame = b0 and B0_FLAG_FIN != 0
isControlFrame = b0 and OPCODE_FLAG_CONTROL != 0
// Control frames must be final frames (cannot contain continuations).
if (isControlFrame && !isFinalFrame) {
throw ProtocolException("Control frames must be final.")
}
val reservedFlag1 = b0 and B0_FLAG_RSV1 != 0
when (opcode) {
OPCODE_TEXT, OPCODE_BINARY -> {
readingCompressedMessage = if (reservedFlag1) {
if (!perMessageDeflate) throw ProtocolException("Unexpected rsv1 flag")
true
} else {
false
}
}
else -> {
if (reservedFlag1) throw ProtocolException("Unexpected rsv1 flag")
}
}
val reservedFlag2 = b0 and B0_FLAG_RSV2 != 0
if (reservedFlag2) throw ProtocolException("Unexpected rsv2 flag")
val reservedFlag3 = b0 and B0_FLAG_RSV3 != 0
if (reservedFlag3) throw ProtocolException("Unexpected rsv3 flag")
val b1 = source.readByte() and 0xff
val isMasked = b1 and B1_FLAG_MASK != 0
if (isMasked == isClient) {
// Masked payloads must be read on the server. Unmasked payloads must be read on the client.
throw ProtocolException(if (isClient) {
"Server-sent frames must not be masked."
} else {
"Client-sent frames must be masked."
})
}
// Get frame length, optionally reading from follow-up bytes if indicated by special values.
frameLength = (b1 and B1_MASK_LENGTH).toLong()
if (frameLength == PAYLOAD_SHORT.toLong()) {
frameLength = (source.readShort() and 0xffff).toLong() // Value is unsigned.
} else if (frameLength == PAYLOAD_LONG.toLong()) {
frameLength = source.readLong()
if (frameLength < 0L) {
throw ProtocolException(
"Frame length 0x${frameLength.toHexString()} > 0x7FFFFFFFFFFFFFFF")
}
}
if (isControlFrame && frameLength > PAYLOAD_BYTE_MAX) {
throw ProtocolException("Control frame must be less than ${PAYLOAD_BYTE_MAX}B.")
}
if (isMasked) {
// Read the masking key as bytes so that they can be used directly for unmasking.
source.readFully(maskKey!!)
}
}
@Throws(IOException::class)
private fun readControlFrame() {
if (frameLength > 0L) {
source.readFully(controlFrameBuffer, frameLength)
if (!isClient) {
controlFrameBuffer.readAndWriteUnsafe(maskCursor!!)
maskCursor.seek(0)
toggleMask(maskCursor, maskKey!!)
maskCursor.close()
}
}
when (opcode) {
OPCODE_CONTROL_PING -> {
frameCallback.onReadPing(controlFrameBuffer.readByteString())
}
OPCODE_CONTROL_PONG -> {
frameCallback.onReadPong(controlFrameBuffer.readByteString())
}
OPCODE_CONTROL_CLOSE -> {
var code = CLOSE_NO_STATUS_CODE
var reason = ""
val bufferSize = controlFrameBuffer.size
if (bufferSize == 1L) {
throw ProtocolException("Malformed close payload length of 1.")
} else if (bufferSize != 0L) {
code = controlFrameBuffer.readShort().toInt()
reason = controlFrameBuffer.readUtf8()
val codeExceptionMessage = WebSocketProtocol.closeCodeExceptionMessage(code)
if (codeExceptionMessage != null) throw ProtocolException(codeExceptionMessage)
}
frameCallback.onReadClose(code, reason)
closed = true
}
else -> {
throw ProtocolException("Unknown control opcode: " + opcode.toHexString())
}
}
}
@Throws(IOException::class)
private fun readMessageFrame() {
val opcode = this.opcode
if (opcode != OPCODE_TEXT && opcode != OPCODE_BINARY) {
throw ProtocolException("Unknown opcode: ${opcode.toHexString()}")
}
readMessage()
if (readingCompressedMessage) {
val messageInflater = this.messageInflater
?: MessageInflater(noContextTakeover).also { this.messageInflater = it }
messageInflater.inflate(messageFrameBuffer)
}
if (opcode == OPCODE_TEXT) {
frameCallback.onReadMessage(messageFrameBuffer.readUtf8())
} else {
frameCallback.onReadMessage(messageFrameBuffer.readByteString())
}
}
/** Read headers and process any control frames until we reach a non-control frame. */
@Throws(IOException::class)
private fun readUntilNonControlFrame() {
while (!closed) {
readHeader()
if (!isControlFrame) {
break
}
readControlFrame()
}
}
/**
* Reads a message body into across one or more frames. Control frames that occur between
* fragments will be processed. If the message payload is masked this will unmask as it's being
* processed.
*/
@Throws(IOException::class)
private fun readMessage() {
while (true) {
if (closed) throw IOException("closed")
if (frameLength > 0L) {
source.readFully(messageFrameBuffer, frameLength)
if (!isClient) {
messageFrameBuffer.readAndWriteUnsafe(maskCursor!!)
maskCursor.seek(messageFrameBuffer.size - frameLength)
toggleMask(maskCursor, maskKey!!)
maskCursor.close()
}
}
if (isFinalFrame) break // We are exhausted and have no continuations.
readUntilNonControlFrame()
if (opcode != OPCODE_CONTINUATION) {
throw ProtocolException("Expected continuation opcode. Got: ${opcode.toHexString()}")
}
}
}
@Throws(IOException::class)
override fun close() {
messageInflater?.close()
}
}
| apache-2.0 | 1beb344dca4bc3a831de37bd4c92c39d | 32.491582 | 100 | 0.695788 | 4.349366 | false | false | false | false |
didi/DoraemonKit | Android/dokit/src/main/java/com/didichuxing/doraemonkit/kit/network/utils/OkHttpResponse.kt | 1 | 1221 | @file:RestrictTo(RestrictTo.Scope.LIBRARY)
package com.didichuxing.doraemonkit.kit.network.utils
import androidx.annotation.RestrictTo
import com.didichuxing.doraemonkit.okhttp_api.OkHttpWrap
import okhttp3.Response
import okio.Buffer
import okio.GzipSource
import java.nio.charset.Charset
internal fun Response.encoding() =
this.header("content-encoding") ?: this.header("Content-Encoding")
internal fun Response.charset(): Charset {
this.encoding()
?.takeIf { Charset.isSupported(it) }
?.also {
return Charset.forName(it)
}
return OkHttpWrap.toResponseBody(this)?.contentType()?.charset() ?: Charset.defaultCharset()
}
internal fun Response.bodyContent(): String = OkHttpWrap.toResponseBody(this)
?.let { body ->
val source = body.source()
.apply {
request(Long.MAX_VALUE)
}
var buffer = source.buffer
val encoding = encoding()
if ("gzip".equals(encoding, true)) {
GzipSource(buffer.clone()).use { gzippedBody ->
buffer = Buffer().also { it.writeAll(gzippedBody) }
}
}
buffer
}
?.clone()
?.readString(charset())
?: ""
| apache-2.0 | 36b1abe0308838a2eb0d1dc868b016af | 28.780488 | 96 | 0.635545 | 4.329787 | false | false | false | false |
SpineEventEngine/core-java | buildSrc/src/main/kotlin/io/spine/internal/gradle/github/pages/Update.kt | 2 | 5187 | /*
* Copyright 2022, TeamDev. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Redistribution and use in source and/or binary forms, with or without
* modification, must retain the above copyright notice and the following
* disclaimer.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package io.spine.internal.gradle.github.pages
import java.io.File
import java.nio.file.Path
import org.gradle.api.Project
import org.gradle.api.Task
import org.gradle.api.file.ConfigurableFileCollection
import org.gradle.api.file.FileCollection
import org.gradle.api.logging.Logger
import io.spine.internal.gradle.git.Repository
/**
* Performs the update of GitHub pages.
*/
fun Task.updateGhPages(project: Project) {
val plugin = project.plugins.getPlugin(UpdateGitHubPages::class.java)
with(plugin) {
SshKey(rootFolder).register()
}
val repository = Repository.forPublishingDocumentation()
val updateJavadoc = with(plugin) {
UpdateJavadoc(project, javadocOutputFolder, repository, logger)
}
val updateDokka = with(plugin) {
UpdateDokka(project, dokkaOutputFolder, repository, logger)
}
repository.use {
updateJavadoc.run()
updateDokka.run()
repository.push()
}
}
private abstract class UpdateDocumentation(
private val project: Project,
private val docsSourceFolder: Path,
private val repository: Repository,
private val logger: Logger
) {
/**
* The folder under the repository's root(`/`) for storing documentation.
*
* The value should not contain any leading or trailing file separators.
*
* The absolute path to the project's documentation is made by appending its
* name to the end, making `/docsDestinationFolder/project.name`.
*/
protected abstract val docsDestinationFolder: String
/**
* The name of the tool used to generate the documentation to update.
*
* This name will appear in logs as part of a message.
*/
protected abstract val toolName: String
private val mostRecentFolder by lazy {
File("${repository.location}/${docsDestinationFolder}/${project.name}")
}
fun run() {
val module = project.name
logger.debug("Update of the $toolName documentation for module `$module` started.")
val documentation = replaceMostRecentDocs()
copyIntoVersionDir(documentation)
val version = project.version
val updateMessage = "Update $toolName documentation for module `$module` as for " +
"version $version"
repository.commitAllChanges(updateMessage)
logger.debug("Update of the $toolName documentation for `$module` successfully finished.")
}
private fun replaceMostRecentDocs(): ConfigurableFileCollection {
val generatedDocs = project.files(docsSourceFolder)
logger.debug("Replacing the most recent $toolName documentation in ${mostRecentFolder}.")
copyDocs(generatedDocs, mostRecentFolder)
return generatedDocs
}
private fun copyDocs(source: FileCollection, destination: File) {
destination.mkdir()
project.copy {
from(source)
into(destination)
}
}
private fun copyIntoVersionDir(generatedDocs: ConfigurableFileCollection) {
val versionedDocDir = File("$mostRecentFolder/v/${project.version}")
logger.debug("Storing the new version of $toolName documentation in `${versionedDocDir}.")
copyDocs(generatedDocs, versionedDocDir)
}
}
private class UpdateJavadoc(
project: Project,
docsSourceFolder: Path,
repository: Repository,
logger: Logger
) : UpdateDocumentation(project, docsSourceFolder, repository, logger) {
override val docsDestinationFolder: String
get() = "reference"
override val toolName: String
get() = "Javadoc"
}
private class UpdateDokka(
project: Project,
docsSourceFolder: Path,
repository: Repository,
logger: Logger
) : UpdateDocumentation(project, docsSourceFolder, repository, logger) {
override val docsDestinationFolder: String
get() = "dokka-reference"
override val toolName: String
get() = "Dokka"
}
| apache-2.0 | 794598e2c2840fe7d5b65b1337994cc9 | 32.038217 | 98 | 0.707152 | 4.689873 | false | false | false | false |
gpolitis/jitsi-videobridge | jvb/src/main/kotlin/org/jitsi/videobridge/cc/allocation/VideoConstraints.kt | 1 | 1242 | /*
* Copyright @ 2020 - present 8x8, 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 org.jitsi.videobridge.cc.allocation
import com.fasterxml.jackson.annotation.JsonIgnoreProperties
import org.json.simple.JSONObject
@JsonIgnoreProperties(ignoreUnknown = true)
data class VideoConstraints(
val maxHeight: Int,
val maxFrameRate: Double = -1.0
) {
override fun toString(): String = JSONObject().apply {
this["maxHeight"] = maxHeight
this["maxFrameRate"] = maxFrameRate
}.toJSONString()
companion object {
val NOTHING = VideoConstraints(0)
}
}
fun Map<String, VideoConstraints>.prettyPrint(): String =
entries.joinToString { "${it.key}->${it.value.maxHeight}" }
| apache-2.0 | 38496c9fc37a4d00c0aeb10426e49443 | 32.567568 | 75 | 0.719002 | 4.238908 | false | false | false | false |
gpolitis/jitsi-videobridge | jvb/src/test/kotlin/org/jitsi/videobridge/message/BridgeChannelMessageTest.kt | 1 | 15332 | /*
* Copyright @ 2020-Present 8x8, 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 org.jitsi.videobridge.message
import com.fasterxml.jackson.core.JsonProcessingException
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.databind.exc.InvalidTypeIdException
import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper
import com.fasterxml.jackson.module.kotlin.readValue
import io.kotest.assertions.throwables.shouldThrow
import io.kotest.core.spec.style.ShouldSpec
import io.kotest.matchers.collections.shouldContainExactly
import io.kotest.matchers.nulls.shouldNotBeNull
import io.kotest.matchers.shouldBe
import io.kotest.matchers.string.shouldNotInclude
import io.kotest.matchers.types.shouldBeInstanceOf
import org.jitsi.videobridge.cc.allocation.VideoConstraints
import org.jitsi.videobridge.message.BridgeChannelMessage.Companion.parse
import org.jitsi.videobridge.util.VideoType
import org.json.simple.JSONArray
import org.json.simple.JSONObject
import org.json.simple.parser.JSONParser
@Suppress("BlockingMethodInNonBlockingContext")
class BridgeChannelMessageTest : ShouldSpec() {
init {
context("serializing") {
should("encode the type as colibriClass") {
// Any message will do, this one is just simple
val message = ClientHelloMessage()
val parsed = JSONParser().parse(message.toJson())
parsed.shouldBeInstanceOf<JSONObject>()
val parsedColibriClass = parsed["colibriClass"]
parsedColibriClass.shouldBeInstanceOf<String>()
parsedColibriClass shouldBe message.type
}
}
context("parsing and serializing a SelectedEndpointsChangedEvent message") {
val parsed = parse(SELECTED_ENDPOINTS_MESSAGE)
should("parse to the correct type") {
parsed.shouldBeInstanceOf<SelectedEndpointsMessage>()
}
should("parse the list of endpoints correctly") {
parsed as SelectedEndpointsMessage
parsed.selectedEndpoints shouldBe listOf("abcdabcd", "12341234")
}
should("serialize and de-serialize correctly") {
val selectedEndpoints = listOf("abcdabcd", "12341234")
val serialized = SelectedEndpointsMessage(selectedEndpoints).toJson()
val parsed2 = parse(serialized)
parsed2.shouldBeInstanceOf<SelectedEndpointsMessage>()
parsed2.selectedEndpoints shouldBe selectedEndpoints
}
}
context("parsing an invalid message") {
shouldThrow<JsonProcessingException> {
parse("{invalid json")
}
shouldThrow<JsonProcessingException> {
parse("")
}
shouldThrow<InvalidTypeIdException> {
parse("{}")
}
shouldThrow<InvalidTypeIdException> {
parse("""{"colibriClass": "invalid-colibri-class" }""")
}
context("when some of the message-specific fields are missing/invalid") {
shouldThrow<JsonProcessingException> {
parse("""{"colibriClass": "SelectedEndpointsChangedEvent" }""")
}
shouldThrow<JsonProcessingException> {
parse("""{"colibriClass": "SelectedEndpointsChangedEvent", "selectedEndpoints": 5 }""")
}
}
}
context("serializing and parsing EndpointMessage") {
val endpointsMessage = EndpointMessage("to_value")
endpointsMessage.otherFields["other_field1"] = "other_value1"
endpointsMessage.put("other_field2", 97)
val json = endpointsMessage.toJson()
// Make sure we don't mistakenly serialize the "broadcast" flag.
json shouldNotInclude "broadcast"
// Make sure we don't mistakenly serialize the "type".
json shouldNotInclude """
"type":
""".trimIndent()
val parsed = parse(json)
parsed.shouldBeInstanceOf<EndpointMessage>()
parsed.from shouldBe null
parsed.to shouldBe "to_value"
parsed.otherFields["other_field1"] shouldBe "other_value1"
parsed.otherFields["other_field2"] shouldBe 97
endpointsMessage.from = "new"
(parse(endpointsMessage.toJson()) as EndpointMessage).from shouldBe "new"
context("parsing") {
val parsed2 = parse(ENDPOINT_MESSAGE)
parsed2 as EndpointMessage
parsed2.from shouldBe null
parsed2.to shouldBe "to_value"
parsed2.otherFields["other_field1"] shouldBe "other_value1"
parsed2.otherFields["other_field2"] shouldBe 97
}
}
context("serializing and parsing DominantSpeakerMessage") {
val previousSpeakers = listOf("p1", "p2")
val original = DominantSpeakerMessage("d", previousSpeakers)
val parsed = parse(original.toJson())
parsed.shouldBeInstanceOf<DominantSpeakerMessage>()
parsed.dominantSpeakerEndpoint shouldBe "d"
parsed.previousSpeakers shouldBe listOf("p1", "p2")
}
context("serializing and parsing ServerHello") {
context("without a version") {
val parsed = parse(ServerHelloMessage().toJson())
parsed.shouldBeInstanceOf<ServerHelloMessage>()
parsed.version shouldBe null
}
context("with a version") {
val message = ServerHelloMessage("v")
val parsed = parse(message.toJson())
parsed.shouldBeInstanceOf<ServerHelloMessage>()
parsed.version shouldBe "v"
}
}
context("serializing and parsing ClientHello") {
val parsed = parse(ClientHelloMessage().toJson())
parsed.shouldBeInstanceOf<ClientHelloMessage>()
}
context("serializing and parsing EndpointConnectionStatusMessage") {
val parsed = parse(EndpointConnectionStatusMessage("abcdabcd", true).toJson())
parsed.shouldBeInstanceOf<EndpointConnectionStatusMessage>()
parsed.endpoint shouldBe "abcdabcd"
parsed.active shouldBe "true"
}
context("serializing and parsing ForwardedEndpointsMessage") {
val forwardedEndpoints = setOf("a", "b", "c")
val message = ForwardedEndpointsMessage(forwardedEndpoints)
val parsed = parse(message.toJson())
parsed.shouldBeInstanceOf<ForwardedEndpointsMessage>()
parsed.forwardedEndpoints shouldContainExactly forwardedEndpoints
// Make sure the forwardedEndpoints field is serialized as lastNEndpoints as the client (presumably) expects
val parsedJson = JSONParser().parse(message.toJson())
parsedJson.shouldBeInstanceOf<JSONObject>()
val parsedForwardedEndpoints = parsedJson["lastNEndpoints"]
parsedForwardedEndpoints.shouldBeInstanceOf<JSONArray>()
parsedForwardedEndpoints.toList() shouldContainExactly forwardedEndpoints
}
context("serializing and parsing VideoConstraints") {
val videoConstraints: VideoConstraints = jacksonObjectMapper().readValue(VIDEO_CONSTRAINTS)
videoConstraints.maxHeight shouldBe 1080
videoConstraints.maxFrameRate shouldBe 15.0
}
context("and SenderVideoConstraintsMessage") {
val senderVideoConstraintsMessage = SenderVideoConstraintsMessage(1080)
val parsed = parse(senderVideoConstraintsMessage.toJson())
parsed.shouldBeInstanceOf<SenderVideoConstraintsMessage>()
parsed.videoConstraints.idealHeight shouldBe 1080
}
context("serializing and parsing AddReceiver") {
val message = AddReceiverMessage("bridge1", "abcdabcd", VideoConstraints(360))
val parsed = parse(message.toJson())
parsed.shouldBeInstanceOf<AddReceiverMessage>()
parsed.bridgeId shouldBe "bridge1"
parsed.endpointId shouldBe "abcdabcd"
parsed.videoConstraints shouldBe VideoConstraints(360)
}
context("serializing and parsing RemoveReceiver") {
val message = RemoveReceiverMessage("bridge1", "abcdabcd")
val parsed = parse(message.toJson())
parsed.shouldBeInstanceOf<RemoveReceiverMessage>()
parsed.bridgeId shouldBe "bridge1"
parsed.endpointId shouldBe "abcdabcd"
}
context("serializing and parsing VideoType") {
val videoTypeMessage = VideoTypeMessage(VideoType.DESKTOP)
videoTypeMessage.videoType shouldBe VideoType.DESKTOP
parse(videoTypeMessage.toJson()).apply {
shouldBeInstanceOf<VideoTypeMessage>()
videoType shouldBe VideoType.DESKTOP
}
listOf("none", "NONE", "None", "nOnE").forEach {
val jsonString = """
{
"colibriClass" : "VideoTypeMessage",
"videoType" : "$it"
}
"""
parse(jsonString).apply {
shouldBeInstanceOf<VideoTypeMessage>()
videoType shouldBe VideoType.NONE
}
}
val jsonString = """
{
"colibriClass" : "VideoTypeMessage",
"videoType" : "desktop_high_fps"
}
"""
parse(jsonString).apply {
shouldBeInstanceOf<VideoTypeMessage>()
videoType shouldBe VideoType.DESKTOP_HIGH_FPS
}
}
context("Parsing ReceiverVideoConstraints") {
context("With all fields present") {
val parsed = parse(RECEIVER_VIDEO_CONSTRAINTS)
parsed.shouldBeInstanceOf<ReceiverVideoConstraintsMessage>()
parsed.lastN shouldBe 3
parsed.onStageEndpoints shouldBe listOf("onstage1", "onstage2")
parsed.selectedEndpoints shouldBe listOf("selected1", "selected2")
parsed.defaultConstraints shouldBe VideoConstraints(0)
val constraints = parsed.constraints
constraints.shouldNotBeNull()
constraints.size shouldBe 3
constraints["epOnStage"] shouldBe VideoConstraints(720)
constraints["epThumbnail1"] shouldBe VideoConstraints(180)
constraints["epThumbnail2"] shouldBe VideoConstraints(180, 30.0)
}
context("With fields missing") {
val parsed = parse(RECEIVER_VIDEO_CONSTRAINTS_EMPTY)
parsed.shouldBeInstanceOf<ReceiverVideoConstraintsMessage>()
parsed.lastN shouldBe null
parsed.onStageEndpoints shouldBe null
parsed.selectedEndpoints shouldBe null
parsed.defaultConstraints shouldBe null
parsed.constraints shouldBe null
}
}
xcontext("Serializing performance") {
val times = 1_000_000
val objectMapper = ObjectMapper()
fun toJsonJackson(m: DominantSpeakerMessage): String = objectMapper.writeValueAsString(m)
fun toJsonJsonSimple(m: DominantSpeakerMessage) = JSONObject().apply {
this["dominantSpeakerEndpoint"] = m.dominantSpeakerEndpoint
}.toJSONString()
fun toJsonStringConcat(m: DominantSpeakerMessage) =
"{\"colibriClass\":\"DominantSpeakerEndpointChangeEvent\",\"dominantSpeakerEndpoint\":\"" +
m.dominantSpeakerEndpoint + "\"}"
fun toJsonStringTemplate(m: DominantSpeakerMessage) =
"{\"colibriClass\":\"${DominantSpeakerMessage.TYPE}\"," +
"\"dominantSpeakerEndpoint\":\"${m.dominantSpeakerEndpoint}\"}"
fun toJsonRawStringTemplate(m: DominantSpeakerMessage) = """
{"colibriClass":"${DominantSpeakerMessage.TYPE}",
"dominantSpeakerEndpoint":"${m.dominantSpeakerEndpoint}"}
"""
fun runTest(f: (DominantSpeakerMessage) -> String): Long {
val start = System.currentTimeMillis()
for (i in 0..times) {
f(DominantSpeakerMessage(i.toString()))
}
val end = System.currentTimeMillis()
return end - start
}
System.err.println("Times=$times")
System.err.println("Jackson: ${runTest { toJsonJackson(it) }}")
System.err.println("Json-simple: ${runTest { toJsonJsonSimple(it) }}")
System.err.println("String concat: ${runTest { toJsonStringConcat(it) }}")
System.err.println("String template: ${runTest { toJsonStringTemplate(it) }}")
System.err.println("Raw string template: ${runTest { toJsonRawStringTemplate(it) }}")
System.err.println("Raw string template (trim): ${runTest { toJsonRawStringTemplate(it).trimMargin() }}")
}
}
companion object {
const val SELECTED_ENDPOINTS_MESSAGE = """
{
"colibriClass": "SelectedEndpointsChangedEvent",
"selectedEndpoints": [ "abcdabcd", "12341234" ]
}
"""
const val ENDPOINT_MESSAGE = """
{
"colibriClass": "EndpointMessage",
"to": "to_value",
"other_field1": "other_value1",
"other_field2": 97
}
"""
const val VIDEO_CONSTRAINTS = """
{
"maxHeight": 1080,
"maxFrameRate": 15.0
}
"""
const val RECEIVER_VIDEO_CONSTRAINTS_EMPTY = """
{
"colibriClass": "ReceiverVideoConstraints"
}
"""
const val RECEIVER_VIDEO_CONSTRAINTS = """
{
"colibriClass": "ReceiverVideoConstraints",
"lastN": 3,
"selectedEndpoints": [ "selected1", "selected2" ],
"onStageEndpoints": [ "onstage1", "onstage2" ],
"defaultConstraints": { "maxHeight": 0 },
"constraints": {
"epOnStage": { "maxHeight": 720 },
"epThumbnail1": { "maxHeight": 180 },
"epThumbnail2": { "maxHeight": 180, "maxFrameRate": 30 }
}
}
"""
}
}
| apache-2.0 | fd04754ceb1ec0bba0f8b9bbbeec6bcd | 40.663043 | 120 | 0.601618 | 5.796597 | false | false | false | false |
rcgroot/open-gpstracker-ng | studio/features/src/main/java/nl/sogeti/android/gpstracker/ng/features/tracklist/TrackListActivity.kt | 1 | 2879 | /*------------------------------------------------------------------------------
** Ident: Sogeti Smart Mobile Solutions
** Author: rene
** Copyright: (c) 2016 Sogeti Nederland B.V. All Rights Reserved.
**------------------------------------------------------------------------------
** Sogeti Nederland B.V. | No part of this file may be reproduced
** Distributed Software Engineering | or transmitted in any form or by any
** Lange Dreef 17 | means, electronic or mechanical, for the
** 4131 NJ Vianen | purpose, without the express written
** The Netherlands | permission of the copyright holder.
*------------------------------------------------------------------------------
*
* This file is part of OpenGPSTracker.
*
* OpenGPSTracker 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.
*
* OpenGPSTracker 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 OpenGPSTracker. If not, see <http://www.gnu.org/licenses/>.
*
*/
package nl.sogeti.android.gpstracker.ng.features.tracklist
import android.app.SearchManager
import android.content.Context
import android.content.Intent
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.widget.Toolbar
import nl.sogeti.android.gpstracker.ng.features.FeatureConfiguration
import nl.sogeti.android.gpstracker.ng.features.model.TrackSearch
import nl.sogeti.android.opengpstrack.ng.features.R
import javax.inject.Inject
class TrackListActivity : AppCompatActivity() {
@Inject
lateinit var trackSearch: TrackSearch
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_tracklist)
val toolbar = findViewById<Toolbar>(R.id.toolbar)
setSupportActionBar(toolbar)
supportActionBar?.setDisplayHomeAsUpEnabled(true)
FeatureConfiguration.featureComponent.inject(this)
}
override fun onNewIntent(intent: Intent?) {
super.onNewIntent(intent)
if (intent?.action == Intent.ACTION_SEARCH) {
trackSearch.query.value = intent.getStringExtra(SearchManager.QUERY)
}
}
companion object {
fun start(context: Context) {
val intent = Intent(context, TrackListActivity::class.java)
context.startActivity(intent)
}
}
}
| gpl-3.0 | 231c3c862477e600f959dd6bbe316110 | 40.128571 | 81 | 0.651268 | 4.871404 | false | false | false | false |
nemerosa/ontrack | ontrack-extension-plugin/src/main/kotlin/net/nemerosa/ontrack/extension/plugin/OntrackExtension.kt | 1 | 2347 | package net.nemerosa.ontrack.extension.plugin
import org.gradle.api.GradleException
import org.gradle.api.Project
import org.gradle.kotlin.dsl.apply
import org.gradle.kotlin.dsl.dependencies
import org.gradle.kotlin.dsl.extra
import org.gradle.kotlin.dsl.withType
import org.jetbrains.kotlin.gradle.tasks.KotlinCompile
/**
* Prefix for Ontrack extensions module names
*/
const val PREFIX = "ontrack-extension-"
/**
* Configuration of the Ontrack extension.
*
* @property project Linked project
*/
open class OntrackExtension(
private val project: Project
) {
/**
* ID of the extension (required)
*/
private var id: String? = null
/**
* DSL access
*/
fun id(value: String) {
id = value
}
/**
* Applies Kotlin dependencies
*/
fun kotlin() {
val kotlinVersion = project.extra["kotlinVersion"] as String
println("[ontrack] Applying Kotlin v${kotlinVersion} to ${project.name} plugin")
project.apply(plugin = "kotlin")
project.apply(plugin = "kotlin-spring")
project.tasks.withType<KotlinCompile> {
kotlinOptions {
jvmTarget = "11"
freeCompilerArgs = listOf("-Xjsr305=strict")
}
}
project.dependencies {
"compileOnly"("org.jetbrains.kotlin:kotlin-stdlib-jdk8:${kotlinVersion}")
"compileOnly"("org.jetbrains.kotlin:kotlin-reflect:${kotlinVersion}")
}
}
/**
* Dynamic computation of the ID if not specified
*/
fun id(): String {
return id ?: if (project.name.startsWith(PREFIX)) {
project.name.removePrefix(PREFIX)
} else {
throw GradleException("""
Project ${project.path} must declare the Ontrack extension id or have a name like `ontrack-extension-<id>`.
Use:
ontrack {
id "your-extension-id"
}
""".trimIndent())
}
}
/**
* Registers an ontrack core extension
*/
fun uses(extension: String) {
val version = project.extra["ontrackVersion"] as String
project.dependencies {
"compile"("net.nemerosa.ontrack:ontrack-extension-${extension}:${version}")
}
}
}
| mit | 084afd5a95209b7016164a95777a3ae9 | 26.290698 | 123 | 0.589263 | 4.666004 | false | false | false | false |
wiltonlazary/kotlin-native | samples/html5Canvas/src/html5CanvasMain/kotlin/main.kt | 3 | 1302 | /*
* Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the license/LICENSE.txt file.
*/
package sample.html5canvas
import kotlinx.interop.wasm.dom.*
import kotlinx.wasm.jsinterop.*
fun main() {
val canvas = document.getElementById("myCanvas").asCanvas
val ctx = canvas.getContext("2d")
val rect = canvas.getBoundingClientRect()
val rectLeft = rect.left
val rectTop = rect.top
var mouseX: Int = 0
var mouseY: Int = 0
var draw: Boolean = false
document.setter("onmousemove") { arguments: ArrayList<JsValue> ->
val event = MouseEvent(arguments[0])
mouseX = event.getInt("clientX") - rectLeft
mouseY = event.getInt("clientY") - rectTop
if (mouseX < 0) mouseX = 0
if (mouseX > 639) mouseX = 639
if (mouseY < 0) mouseY = 0
if (mouseY > 479) mouseY = 479
}
document.setter("onmousedown") {
draw = true
}
document.setter("onmouseup") {
draw = false
}
setInterval(10) {
if (draw) {
ctx.strokeStyle = "#222222"
ctx.lineTo(mouseX, mouseY)
ctx.stroke()
} else {
ctx.moveTo(mouseX, mouseY)
ctx.stroke()
}
}
}
| apache-2.0 | 380e34703f54375316ac3b0e33b74d7b | 23.566038 | 101 | 0.59063 | 3.852071 | false | false | false | false |
samtstern/quickstart-android | auth/app/src/main/java/com/google/firebase/quickstart/auth/kotlin/FacebookLoginActivity.kt | 1 | 5492 | package com.google.firebase.quickstart.auth.kotlin
import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.view.View
import android.widget.Toast
import com.facebook.AccessToken
import com.facebook.CallbackManager
import com.facebook.FacebookCallback
import com.facebook.FacebookException
import com.facebook.login.LoginManager
import com.facebook.login.LoginResult
import com.google.firebase.auth.FacebookAuthProvider
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.auth.FirebaseUser
import com.google.firebase.auth.ktx.auth
import com.google.firebase.ktx.Firebase
import com.google.firebase.quickstart.auth.R
import com.google.firebase.quickstart.auth.databinding.ActivityFacebookBinding
/**
* Demonstrate Firebase Authentication using a Facebook access token.
*/
class FacebookLoginActivity : BaseActivity(), View.OnClickListener {
// [START declare_auth]
private lateinit var auth: FirebaseAuth
// [END declare_auth]
private lateinit var binding: ActivityFacebookBinding
private lateinit var callbackManager: CallbackManager
public override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityFacebookBinding.inflate(layoutInflater)
setContentView(binding.root)
setProgressBar(binding.progressBar)
binding.buttonFacebookSignout.setOnClickListener(this)
// [START initialize_auth]
// Initialize Firebase Auth
auth = Firebase.auth
// [END initialize_auth]
// [START initialize_fblogin]
// Initialize Facebook Login button
callbackManager = CallbackManager.Factory.create()
binding.buttonFacebookLogin.setReadPermissions("email", "public_profile")
binding.buttonFacebookLogin.registerCallback(callbackManager, object : FacebookCallback<LoginResult> {
override fun onSuccess(loginResult: LoginResult) {
Log.d(TAG, "facebook:onSuccess:$loginResult")
handleFacebookAccessToken(loginResult.accessToken)
}
override fun onCancel() {
Log.d(TAG, "facebook:onCancel")
// [START_EXCLUDE]
updateUI(null)
// [END_EXCLUDE]
}
override fun onError(error: FacebookException) {
Log.d(TAG, "facebook:onError", error)
// [START_EXCLUDE]
updateUI(null)
// [END_EXCLUDE]
}
})
// [END initialize_fblogin]
}
// [START on_start_check_user]
public override fun onStart() {
super.onStart()
// Check if user is signed in (non-null) and update UI accordingly.
val currentUser = auth.currentUser
updateUI(currentUser)
}
// [END on_start_check_user]
// [START on_activity_result]
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
// Pass the activity result back to the Facebook SDK
callbackManager.onActivityResult(requestCode, resultCode, data)
}
// [END on_activity_result]
// [START auth_with_facebook]
private fun handleFacebookAccessToken(token: AccessToken) {
Log.d(TAG, "handleFacebookAccessToken:$token")
// [START_EXCLUDE silent]
showProgressBar()
// [END_EXCLUDE]
val credential = FacebookAuthProvider.getCredential(token.token)
auth.signInWithCredential(credential)
.addOnCompleteListener(this) { task ->
if (task.isSuccessful) {
// Sign in success, update UI with the signed-in user's information
Log.d(TAG, "signInWithCredential:success")
val user = auth.currentUser
updateUI(user)
} else {
// If sign in fails, display a message to the user.
Log.w(TAG, "signInWithCredential:failure", task.exception)
Toast.makeText(baseContext, "Authentication failed.",
Toast.LENGTH_SHORT).show()
updateUI(null)
}
// [START_EXCLUDE]
hideProgressBar()
// [END_EXCLUDE]
}
}
// [END auth_with_facebook]
fun signOut() {
auth.signOut()
LoginManager.getInstance().logOut()
updateUI(null)
}
private fun updateUI(user: FirebaseUser?) {
hideProgressBar()
if (user != null) {
binding.status.text = getString(R.string.facebook_status_fmt, user.displayName)
binding.detail.text = getString(R.string.firebase_status_fmt, user.uid)
binding.buttonFacebookLogin.visibility = View.GONE
binding.buttonFacebookSignout.visibility = View.VISIBLE
} else {
binding.status.setText(R.string.signed_out)
binding.detail.text = null
binding.buttonFacebookLogin.visibility = View.VISIBLE
binding.buttonFacebookSignout.visibility = View.GONE
}
}
override fun onClick(v: View) {
if (v.id == R.id.buttonFacebookSignout) {
signOut()
}
}
companion object {
private const val TAG = "FacebookLogin"
}
}
| apache-2.0 | aa85ceb7c2bdaa67d6788a3793a46023 | 34.205128 | 110 | 0.628369 | 5.071099 | false | false | false | false |
bozaro/git-as-svn | src/main/kotlin/svnserver/repository/git/path/matcher/path/FileMaskMatcher.kt | 1 | 1509 | /*
* This file is part of git-as-svn. It is subject to the license terms
* in the LICENSE file found in the top-level directory of this distribution
* and at http://www.gnu.org/licenses/gpl-2.0.html. No part of git-as-svn,
* including this file, may be copied, modified, propagated, or distributed
* except according to the terms contained in the LICENSE file.
*/
package svnserver.repository.git.path.matcher.path
import svnserver.repository.git.path.NameMatcher
import svnserver.repository.git.path.PathMatcher
/**
* Complex full-feature pattern matcher.
*
* @author Artem V. Navrotskiy <[email protected]>
*/
class FileMaskMatcher constructor(private val matcher: NameMatcher) : PathMatcher {
override fun createChild(name: String, isDir: Boolean): PathMatcher? {
if (matcher.isMatch(name, isDir)) {
return AlwaysMatcher.INSTANCE
}
if (!isDir) {
return null
}
return this
}
override val isMatch: Boolean
get() {
return false
}
override val svnMaskGlobal: String?
get() {
return matcher.svnMask
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other == null || javaClass != other.javaClass) return false
val that: FileMaskMatcher = other as FileMaskMatcher
return (matcher == that.matcher)
}
override fun hashCode(): Int {
return matcher.hashCode()
}
}
| gpl-2.0 | 091798b5d2be86c38ae3da3909aa8350 | 30.4375 | 83 | 0.655401 | 4.286932 | false | false | false | false |
soywiz/korge | @old/korge-ui/src/commonMain/kotlin/com/soywiz/korge/ui/korui/KorgeLightComponents.kt | 1 | 2047 | package com.soywiz.korge.ui.korui
import com.soywiz.korge.input.*
import com.soywiz.korge.view.*
import com.soywiz.korio.lang.*
import com.soywiz.korev.*
import com.soywiz.korge.ui.*
import com.soywiz.korui.light.*
import kotlin.reflect.*
//class KorgeLightComponentsFactory : LightComponentsFactory() {
// //override fun create(): LightComponents = KorgeLightComponents()
// override fun create(): LightComponents = TODO()
//}
class KorgeLightComponents(val uiFactory: UIFactory) : LightComponents() {
val views = uiFactory.views
override fun create(type: LightType, config: Any?): LightComponentInfo {
val handle = when (type) {
LightType.BUTTON -> uiFactory.button()
LightType.CONTAINER -> FixedSizeContainer()
LightType.FRAME -> FixedSizeContainer()
LightType.LABEL -> uiFactory.label("")
else -> FixedSizeContainer()
}
return LightComponentInfo(handle)
}
override fun setBounds(c: Any, x: Int, y: Int, width: Int, height: Int) {
val view = c as View
view.x = x.toDouble()
view.y = y.toDouble()
view.width = width.toDouble()
view.height = height.toDouble()
}
override fun <T> setProperty(c: Any, key: LightProperty<T>, value: T) {
val view = c as View
when (key) {
LightProperty.TEXT -> {
(view as? IText)?.text = value as String
}
}
}
override fun <T : Event> registerEventKind(c: Any, clazz: KClass<T>, ed: EventDispatcher): Closeable {
val view = c as View
val mouseEvent = MouseEvent()
when (clazz) {
MouseEvent::class -> {
return listOf(
view.mouse.onClick {
ed.dispatch(mouseEvent.apply {
this.type = MouseEvent.Type.CLICK
this.button = MouseButton.LEFT
this.x = 0
this.y = 0
})
}
).closeable()
}
}
return super.registerEventKind(c, clazz, ed)
}
override fun openURL(url: String) {
//browser.browse(URL(url))
}
override fun setParent(c: Any, parent: Any?) {
val view = c as View
val parentView = parent as? Container?
parentView?.addChild(view)
}
override fun repaint(c: Any) {
}
}
| apache-2.0 | 32b51bb1cc66cb98bb974165d90fd90c | 24.5875 | 103 | 0.675623 | 3.312298 | false | false | false | false |
fufik/vsu_schedule | src/main/java/com/fufik/vsuschedule/RecyclerAdapter.kt | 1 | 1524 | package com.fufik.vsuschedule
import android.support.v7.widget.CardView
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import java.util.ArrayList
class RecyclerAdapter(private val mParas: ArrayList<Para>) : RecyclerView.Adapter<RecyclerAdapter.ViewHolder>() {
class ViewHolder(v:View):RecyclerView.ViewHolder(v) {
val mCard:CardView = v.findViewById(R.id.cv)
var mBeginTime:TextView = v.findViewById(R.id.item_begin_time)
var mEndTime:TextView = v.findViewById(R.id.item_end_time)
var mParaName:TextView = v.findViewById(R.id.item_para_name)
var mParaRoom:TextView = v.findViewById(R.id.item_para_room)
var mParaTeacher:TextView = v.findViewById(R.id.item_para_teacher)
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerAdapter.ViewHolder {
val v = LayoutInflater.from(parent.context).inflate(R.layout.recycler_item, parent, false)
return ViewHolder(v)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
holder.mBeginTime.text = mParas[position].beginTime
holder.mEndTime.text = mParas[position].endTime
holder.mParaName.text = mParas[position].name
holder.mParaRoom.text = mParas[position].room
holder.mParaTeacher.text = mParas[position].teacher
}
override fun getItemCount(): Int {
return mParas.size
}
}
| gpl-3.0 | d27cfa6280f9d871fd74600278742748 | 38.076923 | 113 | 0.728346 | 3.948187 | false | false | false | false |
ArdentDiscord/ArdentKotlin | src/main/kotlin/web/WebUtils.kt | 1 | 2469 | package web
import com.google.gson.JsonSyntaxException
import events.Command
import loginRedirect
import main.config
import main.jdas
import org.jsoup.Jsoup
import utils.functionality.gson
import utils.functionality.log
val dapi = "https://discordapp.com/api"
data class Token(val access_token: String, val token_type: String, val expires_in: Int, val refresh_token: String, val scope: String)
data class IdentificationObject(val username: String, val verified: Boolean, val mfa_enabled: Boolean, val id: String, val avatar: String, val discriminator: String)
enum class Scope(val route: String) {
CONNECTIONS("/users/@me/connections"),
EMAIL("/users/@me"),
IDENTIFY("/users/@me"),
GUILDS("/users/@me/guilds"),
BOT_INFORMATION("/oauth2/applications/@me");
override fun toString(): String {
return route
}
}
fun identityObject(access_token: String): IdentificationObject? {
val obj = gson.fromJson(retrieveObject(access_token, Scope.IDENTIFY), IdentificationObject::class.java)
return if (obj.id == null) null /* This is possible due to issues with the kotlin compiler */
else obj
}
fun retrieveObject(access_token: String, scope: Scope): String {
return Jsoup.connect("$dapi$scope").ignoreContentType(true).ignoreHttpErrors(true)
.header("authorization", "Bearer $access_token")
.header("cache-control", "no-cache")
.get()
.text()
}
fun retrieveToken(code: String): Token? {
val response = Jsoup.connect("$dapi/oauth2/token").ignoreContentType(true).ignoreHttpErrors(true)
.header("content-type", "application/x-www-form-urlencoded")
.header("authorization", "Bearer $code")
.header("cache-control", "no-cache")
.data("client_id", jdas[0].selfUser.id)
.data("client_secret", config.getValue("client_secret"))
.data("grant_type", "authorization_code")
.data("redirect_uri", loginRedirect)
.data("code", code)
.post()
return try {
val data = gson.fromJson(response.text(), Token::class.java)
if (data.access_token == null) null // this is a possibility due to issues with the kotlin compiler
else data /* verified non null object */
} catch (e: JsonSyntaxException) {
e.printStackTrace()
null
}
}
data class CommandWrapper(val category: String, val description: String, val commands: List<Command>) | apache-2.0 | c193db6a5b3d928d6b9483ddf07a5a5d | 37.59375 | 165 | 0.673147 | 3.988691 | false | false | false | false |
vondear/RxTools | RxKit/src/main/java/com/tamsiree/rxkit/RxProcessTool.kt | 1 | 6003 | package com.tamsiree.rxkit
import android.app.ActivityManager
import android.app.ActivityManager.RunningAppProcessInfo
import android.app.AppOpsManager
import android.app.usage.UsageStats
import android.app.usage.UsageStatsManager
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Build
import android.provider.Settings
import com.tamsiree.rxkit.RxDataTool.Companion.isNullString
import java.util.*
/**
* @author tamsiree
* @date 2016/12/21
*/
object RxProcessTool {
/**
* 获取前台线程包名
*
* 当不是查看当前App,且SDK大于21时,
* 需添加权限 `<uses-permission android:name="android.permission.PACKAGE_USAGE_STATS"/>`
*
* @return 前台应用包名
*/
@JvmStatic
fun getForegroundProcessName(context: Context): String? {
val manager = context.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
val infos = manager.runningAppProcesses
if (infos != null && infos.size != 0) {
for (info in infos) {
if (info.importance == RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
return info.processName
}
}
}
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP) {
val packageManager = context.packageManager
val intent = Intent(Settings.ACTION_USAGE_ACCESS_SETTINGS)
val list = packageManager.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY)
println(list)
if (list.size > 0) { // 有"有权查看使用权限的应用"选项
try {
val info = packageManager.getApplicationInfo(context.packageName, 0)
val aom = context.getSystemService(Context.APP_OPS_SERVICE) as AppOpsManager
if (aom.checkOpNoThrow(AppOpsManager.OPSTR_GET_USAGE_STATS, info.uid, info.packageName) != AppOpsManager.MODE_ALLOWED) {
context.startActivity(intent)
}
if (aom.checkOpNoThrow(AppOpsManager.OPSTR_GET_USAGE_STATS, info.uid, info.packageName) != AppOpsManager.MODE_ALLOWED) {
TLog.d("getForegroundApp", "没有打开\"有权查看使用权限的应用\"选项")
return null
}
val usageStatsManager = context.getSystemService(Context.USAGE_STATS_SERVICE) as UsageStatsManager
val endTime = System.currentTimeMillis()
val beginTime = endTime - 86400000 * 7
val usageStatses = usageStatsManager.queryUsageStats(UsageStatsManager.INTERVAL_BEST, beginTime, endTime)
if (usageStatses == null || usageStatses.isEmpty()) return null
var recentStats: UsageStats? = null
for (usageStats in usageStatses) {
if (recentStats == null || usageStats.lastTimeUsed > recentStats.lastTimeUsed) {
recentStats = usageStats
}
}
return recentStats?.packageName
} catch (e: PackageManager.NameNotFoundException) {
e.printStackTrace()
}
} else {
TLog.d("getForegroundApp", "无\"有权查看使用权限的应用\"选项")
}
}
return null
}
/**
* 获取后台服务进程
*
* 需添加权限 `<uses-permission android:name="android.permission.KILL_BACKGROUND_PROCESSES"/>`
*
* @return 后台服务进程
*/
@JvmStatic
fun getAllBackgroundProcesses(context: Context): MutableCollection<String> {
val am = context.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
val infos = am.runningAppProcesses
val set: MutableCollection<String> = HashSet()
for (info in infos) {
Collections.addAll(set, *info.pkgList)
}
return set
}
/**
* 杀死后台服务进程
*
* 需添加权限 `<uses-permission android:name="android.permission.KILL_BACKGROUND_PROCESSES"/>`
*
* @return 被暂时杀死的服务集合
*/
@JvmStatic
fun killAllBackgroundProcesses(context: Context): Set<String> {
val am = context.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
var infos = am.runningAppProcesses
val set: MutableSet<String> = HashSet()
for (info in infos) {
for (pkg in info.pkgList) {
am.killBackgroundProcesses(pkg)
set.add(pkg)
}
}
infos = am.runningAppProcesses
for (info in infos) {
for (pkg in info.pkgList) {
set.remove(pkg)
}
}
return set
}
/**
* 杀死后台服务进程
*
* 需添加权限 `<uses-permission android:name="android.permission.KILL_BACKGROUND_PROCESSES"/>`
*
* @param packageName 包名
* @return `true`: 杀死成功<br></br>`false`: 杀死失败
*/
@JvmStatic
fun killBackgroundProcesses(context: Context, packageName: String?): Boolean {
if (isNullString(packageName)) return false
val am = context.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
var infos = am.runningAppProcesses
if (infos == null || infos.size == 0) return true
for (info in infos) {
if (Arrays.asList(*info.pkgList).contains(packageName)) {
am.killBackgroundProcesses(packageName)
}
}
infos = am.runningAppProcesses
if (infos == null || infos.size == 0) return true
for (info in infos) {
if (Arrays.asList(*info.pkgList).contains(packageName)) {
return false
}
}
return true
}
} | apache-2.0 | a1cb2570508c42ed60da961ba86a4f7b | 36.880795 | 140 | 0.593635 | 4.765833 | false | false | false | false |
iceboundrock/android-playground | app/src/main/kotlin/li/ruoshi/playground/DemoAdapter.kt | 1 | 1827 | package li.ruoshi.playground
import android.content.Context
import android.support.v7.widget.RecyclerView
import android.util.Log
import android.view.ViewGroup
import android.widget.TextView
import java.util.*
/**
* Created by ruoshili on 7/13/2016.
*/
private const val TAG = "DemoAdapter"
class DemoAdapter() : RecyclerView.Adapter<DemoViewHolder>() {
private val items: MutableList<Int> = ArrayList()
override fun onBindViewHolder(holder: DemoViewHolder?, position: Int) {
if(holder == null) {
return
}
if(position < 0 || position >= items.size) {
return
}
Log.v(TAG, "onBindViewHolder pos: $position, value: ${items[position]}, holder id: ${holder.id}")
holder.update(items[position])
}
override fun onFailedToRecycleView(holder: DemoViewHolder?): Boolean {
Log.e(TAG, "onFailedToRecycleView")
return super.onFailedToRecycleView(holder)
}
override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): DemoViewHolder {
val textView = TextView(parent!!.context!!)
val holder = DemoViewHolder(textView)
Log.v(TAG, "onCreateViewHolder, holder id: ${holder.id}")
return holder
}
override fun getItemCount(): Int {
return items.size
}
fun addItem(i : Int) {
items.add(i)
notifyItemInserted(items.size - 1)
}
fun removeItem(pos : Int) {
if(pos < 0 || pos >= items.size) {
return
}
items.removeAt(pos)
notifyItemRemoved(pos)
}
fun removeOddItems() {
while (true) {
val pos = items.indexOfFirst { it % 2 == 1 }
if(pos < 0) {
break
} else {
removeItem(pos)
}
}
}
} | apache-2.0 | f7ad24de03f418eb6543fab30a5b361f | 23.373333 | 105 | 0.594417 | 4.339667 | false | false | false | false |
vondear/RxTools | RxUI/src/main/java/com/tamsiree/rxui/view/loadingview/animation/interpolator/PathInterpolatorDonut.kt | 1 | 2811 | package com.tamsiree.rxui.view.loadingview.animation.interpolator
import android.graphics.Path
import android.graphics.PathMeasure
import android.view.animation.Interpolator
/**
* @author tamsiree
* A path interpolator implementation compatible with API 4+.
*/
internal class PathInterpolatorDonut(path: Path?) : Interpolator {
private val mX: FloatArray
private val mY: FloatArray
constructor(controlX: Float, controlY: Float) : this(createQuad(controlX, controlY))
constructor(controlX1: Float, controlY1: Float,
controlX2: Float, controlY2: Float) : this(createCubic(controlX1, controlY1, controlX2, controlY2))
override fun getInterpolation(t: Float): Float {
if (t <= 0.0f) {
return 0.0f
} else if (t >= 1.0f) {
return 1.0f
}
// Do a binary search for the correct x to interpolate between.
var startIndex = 0
var endIndex = mX.size - 1
while (endIndex - startIndex > 1) {
val midIndex = (startIndex + endIndex) / 2
if (t < mX[midIndex]) {
endIndex = midIndex
} else {
startIndex = midIndex
}
}
val xRange = mX[endIndex] - mX[startIndex]
if (xRange == 0f) {
return mY[startIndex]
}
val tInRange = t - mX[startIndex]
val fraction = tInRange / xRange
val startY = mY[startIndex]
val endY = mY[endIndex]
return startY + fraction * (endY - startY)
}
companion object {
/**
* Governs the accuracy of the approximation of the [Path].
*/
private const val PRECISION = 0.002f
private fun createQuad(controlX: Float, controlY: Float): Path {
val path = Path()
path.moveTo(0.0f, 0.0f)
path.quadTo(controlX, controlY, 1.0f, 1.0f)
return path
}
private fun createCubic(controlX1: Float, controlY1: Float,
controlX2: Float, controlY2: Float): Path {
val path = Path()
path.moveTo(0.0f, 0.0f)
path.cubicTo(controlX1, controlY1, controlX2, controlY2, 1.0f, 1.0f)
return path
}
}
init {
val pathMeasure = PathMeasure(path, false /* forceClosed */)
val pathLength = pathMeasure.length
val numPoints = (pathLength / PRECISION).toInt() + 1
mX = FloatArray(numPoints)
mY = FloatArray(numPoints)
val position = FloatArray(2)
for (i in 0 until numPoints) {
val distance = i * pathLength / (numPoints - 1)
pathMeasure.getPosTan(distance, position, null /* tangent */)
mX[i] = position[0]
mY[i] = position[1]
}
}
} | apache-2.0 | 11d545e949948eab19823f739aa49c34 | 32.879518 | 115 | 0.574884 | 4.239819 | false | false | false | false |
vondear/RxTools | RxUI/src/main/java/com/tamsiree/rxui/view/roundprogressbar/RxTextRoundProgress.kt | 1 | 10943 | package com.tamsiree.rxui.view.roundprogressbar
import android.content.Context
import android.graphics.Color
import android.os.Parcel
import android.os.Parcelable
import android.util.AttributeSet
import android.util.TypedValue
import android.view.ViewTreeObserver.OnGlobalLayoutListener
import android.widget.LinearLayout
import android.widget.RelativeLayout
import android.widget.TextView
import com.tamsiree.rxkit.RxImageTool.dp2px
import com.tamsiree.rxui.R
import com.tamsiree.rxui.view.roundprogressbar.common.RxBaseRoundProgress
/**
* @author tamsiree
*/
class RxTextRoundProgress : RxBaseRoundProgress, OnGlobalLayoutListener {
private var tvProgress: TextView? = null
private var colorTextProgress = 0
private var textProgressSize = 0
private var textProgressMargin = 0
private var textProgress: String? = null
constructor(context: Context, attrs: AttributeSet?) : super(context, attrs)
constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr)
override fun initLayout(): Int {
return R.layout.layout_text_round_corner_progress_bar
}
override fun initStyleable(context: Context, attrs: AttributeSet?) {
val typedArray = context.obtainStyledAttributes(attrs, R.styleable.RxTextRoundProgress)
colorTextProgress = typedArray.getColor(R.styleable.RxTextRoundProgress_rcTextProgressColor, Color.WHITE)
textProgressSize = typedArray.getDimension(R.styleable.RxTextRoundProgress_rcTextProgressSize, dp2px(context, DEFAULT_TEXT_SIZE.toFloat()).toFloat()).toInt()
textProgressMargin = typedArray.getDimension(R.styleable.RxTextRoundProgress_rcTextProgressMargin, dp2px(context, DEFAULT_TEXT_MARGIN.toFloat()).toFloat()).toInt()
textProgress = typedArray.getString(R.styleable.RxTextRoundProgress_rcTextProgress)
typedArray.recycle()
}
override fun initView() {
tvProgress = findViewById(R.id.tv_progress)
tvProgress?.viewTreeObserver?.addOnGlobalLayoutListener(this)
}
override fun drawProgress(layoutProgress: LinearLayout?, max: Float, progress: Float, totalWidth: Float,
radius: Int, padding: Int, colorProgress: Int, isReverse: Boolean) {
val backgroundDrawable = createGradientDrawable(colorProgress)
val newRadius = radius - padding / 2
backgroundDrawable.cornerRadii = floatArrayOf(newRadius.toFloat(), newRadius.toFloat(), newRadius.toFloat(), newRadius.toFloat(), newRadius.toFloat(), newRadius.toFloat(), newRadius.toFloat(), newRadius.toFloat())
layoutProgress?.background = backgroundDrawable
val ratio = max / progress
val progressWidth = ((totalWidth - padding * 2) / ratio).toInt()
val progressParams = layoutProgress?.layoutParams
progressParams?.width = progressWidth
layoutProgress?.layoutParams = progressParams
}
override fun onViewDraw() {
drawTextProgress()
drawTextProgressSize()
drawTextProgressMargin()
drawTextProgressPosition()
drawTextProgressColor()
}
private fun drawTextProgress() {
tvProgress!!.text = textProgress
}
private fun drawTextProgressColor() {
tvProgress!!.setTextColor(colorTextProgress)
}
private fun drawTextProgressSize() {
tvProgress!!.setTextSize(TypedValue.COMPLEX_UNIT_PX, textProgressSize.toFloat())
}
private fun drawTextProgressMargin() {
val params = tvProgress!!.layoutParams as MarginLayoutParams
params.setMargins(textProgressMargin, 0, textProgressMargin, 0)
tvProgress!!.layoutParams = params
}
private fun drawTextProgressPosition() {
// tvProgress.setVisibility(View.INVISIBLE);
// tvProgress.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
// @SuppressWarnings("deprecation")
// @Override
// public void onGlobalLayout() {
// if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN)
// tvProgress.getViewTreeObserver().removeOnGlobalLayoutListener(this);
// else
// tvProgress.getViewTreeObserver().removeGlobalOnLayoutListener(this);
// setTextProgressAlign();
// }
// });
clearTextProgressAlign()
// TODO Temporary
val textProgressWidth = tvProgress!!.measuredWidth + getTextProgressMargin() * 2
val ratio = getMax() / getProgress()
val progressWidth = ((layoutWidth - getPadding() * 2) / ratio).toInt()
if (textProgressWidth + textProgressMargin < progressWidth) {
alignTextProgressInsideProgress()
} else {
alignTextProgressOutsideProgress()
}
}
// private void setTextProgressAlign() {
// tvProgress.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
// @SuppressWarnings("deprecation")
// @Override
// public void onGlobalLayout() {
// if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN)
// tvProgress.getViewTreeObserver().removeOnGlobalLayoutListener(this);
// else
// tvProgress.getViewTreeObserver().removeGlobalOnLayoutListener(this);
// tvProgress.setVisibility(View.VISIBLE);
// }
// });
// int textProgressWidth = tvProgress.getMeasuredWidth() + (getTextProgressMargin() * 2);
// float ratio = getMax() / getProgress();
// int progressWidth = (int) ((getLayoutWidth() - (getPadding() * 2)) / ratio);
// if (textProgressWidth + textProgressMargin < progressWidth) {
// alignTextProgressInsideProgress();
// } else {
// alignTextProgressOutsideProgress();
// }
// }
private fun clearTextProgressAlign() {
val params = tvProgress!!.layoutParams as RelativeLayout.LayoutParams
params.addRule(RelativeLayout.ALIGN_LEFT, 0)
params.addRule(RelativeLayout.ALIGN_RIGHT, 0)
params.addRule(RelativeLayout.LEFT_OF, 0)
params.addRule(RelativeLayout.RIGHT_OF, 0)
params.removeRule(RelativeLayout.START_OF)
params.removeRule(RelativeLayout.END_OF)
params.removeRule(RelativeLayout.ALIGN_START)
params.removeRule(RelativeLayout.ALIGN_END)
tvProgress!!.layoutParams = params
}
private fun alignTextProgressInsideProgress() {
val params = tvProgress!!.layoutParams as RelativeLayout.LayoutParams
if (getReverse()) {
params.addRule(RelativeLayout.ALIGN_LEFT, R.id.layout_progress)
params.addRule(RelativeLayout.ALIGN_START, R.id.layout_progress)
} else {
params.addRule(RelativeLayout.ALIGN_RIGHT, R.id.layout_progress)
params.addRule(RelativeLayout.ALIGN_END, R.id.layout_progress)
}
tvProgress!!.layoutParams = params
}
private fun alignTextProgressOutsideProgress() {
val params = tvProgress!!.layoutParams as RelativeLayout.LayoutParams
if (getReverse()) {
params.addRule(RelativeLayout.LEFT_OF, R.id.layout_progress)
params.addRule(RelativeLayout.START_OF, R.id.layout_progress)
} else {
params.addRule(RelativeLayout.RIGHT_OF, R.id.layout_progress)
params.addRule(RelativeLayout.END_OF, R.id.layout_progress)
}
tvProgress!!.layoutParams = params
}
var progressText: String?
get() = textProgress
set(text) {
textProgress = text
drawTextProgress()
drawTextProgressPosition()
}
override fun setProgress(progress: Float) {
super.setProgress(progress)
drawTextProgressPosition()
}
var textProgressColor: Int
get() = colorTextProgress
set(color) {
colorTextProgress = color
drawTextProgressColor()
}
fun getTextProgressSize(): Int {
return textProgressSize
}
fun setTextProgressSize(size: Int) {
textProgressSize = size
drawTextProgressSize()
drawTextProgressPosition()
}
fun getTextProgressMargin(): Int {
return textProgressMargin
}
fun setTextProgressMargin(margin: Int) {
textProgressMargin = margin
drawTextProgressMargin()
drawTextProgressPosition()
}
override fun onGlobalLayout() {
tvProgress!!.viewTreeObserver.removeOnGlobalLayoutListener(this)
drawTextProgressPosition()
}
override fun onSaveInstanceState(): Parcelable? {
val superState = super.onSaveInstanceState()
val ss = SavedState(superState)
ss.colorTextProgress = colorTextProgress
ss.textProgressSize = textProgressSize
ss.textProgressMargin = textProgressMargin
ss.textProgress = textProgress
return ss
}
override fun onRestoreInstanceState(state: Parcelable) {
if (state !is SavedState) {
super.onRestoreInstanceState(state)
return
}
val ss = state
super.onRestoreInstanceState(ss.superState)
colorTextProgress = ss.colorTextProgress
textProgressSize = ss.textProgressSize
textProgressMargin = ss.textProgressMargin
textProgress = ss.textProgress
}
private class SavedState : BaseSavedState {
var colorTextProgress = 0
var textProgressSize = 0
var textProgressMargin = 0
var textProgress: String? = null
internal constructor(superState: Parcelable?) : super(superState)
private constructor(`in`: Parcel) : super(`in`) {
colorTextProgress = `in`.readInt()
textProgressSize = `in`.readInt()
textProgressMargin = `in`.readInt()
textProgress = `in`.readString()
}
override fun writeToParcel(out: Parcel, flags: Int) {
super.writeToParcel(out, flags)
out.writeInt(colorTextProgress)
out.writeInt(textProgressSize)
out.writeInt(textProgressMargin)
out.writeString(textProgress)
}
companion object {
val CREATOR: Parcelable.Creator<SavedState> = object : Parcelable.Creator<SavedState> {
override fun createFromParcel(`in`: Parcel): SavedState? {
return SavedState(`in`)
}
override fun newArray(size: Int): Array<SavedState?> {
return arrayOfNulls(size)
}
}
}
}
companion object {
protected const val DEFAULT_TEXT_SIZE = 16
protected const val DEFAULT_TEXT_MARGIN = 10
}
} | apache-2.0 | bd369e77d457b01f0fddc39eae101df1 | 38.509025 | 221 | 0.656676 | 5.42001 | false | false | false | false |
AndroidX/androidx | compose/ui/ui/samples/src/main/java/androidx/compose/ui/samples/NestedScrollInteropSamples.kt | 3 | 6336 | /*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.compose.ui.samples
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import androidx.annotation.Sampled
import androidx.compose.foundation.background
import androidx.compose.foundation.gestures.Orientation
import androidx.compose.foundation.gestures.rememberScrollableState
import androidx.compose.foundation.gestures.scrollable
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.offset
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.material.Text
import androidx.compose.material.TopAppBar
import androidx.compose.runtime.Composable
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.input.nestedscroll.NestedScrollConnection
import androidx.compose.ui.input.nestedscroll.NestedScrollSource
import androidx.compose.ui.input.nestedscroll.nestedScroll
import androidx.compose.ui.platform.ComposeView
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.platform.rememberNestedScrollInteropConnection
import androidx.compose.ui.unit.IntOffset
import androidx.compose.ui.unit.dp
import androidx.compose.ui.viewinterop.AndroidView
import androidx.core.view.ViewCompat
import kotlin.math.roundToInt
@Sampled
@Composable
fun ComposeInCooperatingViewNestedScrollInteropSample() {
val nestedSrollInterop = rememberNestedScrollInteropConnection()
// Add the nested scroll connection to your top level @Composable element
// using the nestedScroll modifier.
LazyColumn(modifier = Modifier.nestedScroll(nestedSrollInterop)) {
items(20) { item ->
Box(
modifier = Modifier
.padding(16.dp)
.height(56.dp)
.fillMaxWidth()
.background(Color.Gray),
contentAlignment = Alignment.Center
) {
Text(item.toString())
}
}
}
}
@Sampled
@Composable
fun ViewInComposeNestedScrollInteropSample() {
Box(
Modifier
.fillMaxSize()
.scrollable(rememberScrollableState {
// view world deltas should be reflected in compose world
// components that participate in nested scrolling
it
}, Orientation.Vertical)
) {
AndroidView(
{ context ->
LayoutInflater.from(context)
.inflate(android.R.layout.activity_list_item, null)
.apply {
// Nested Scroll Interop will be Enabled when
// nested scroll is enabled for the root view
ViewCompat.setNestedScrollingEnabled(this, true)
}
}
)
}
}
private val ToolbarHeight = 48.dp
@Composable
fun CollapsingToolbarComposeViewComposeNestedScrollInteropSample() {
val toolbarHeightPx = with(LocalDensity.current) { ToolbarHeight.roundToPx().toFloat() }
val toolbarOffsetHeightPx = remember { mutableStateOf(0f) }
val nestedScrollConnection = remember {
object : NestedScrollConnection {
override fun onPreScroll(available: Offset, source: NestedScrollSource): Offset {
val delta = available.y
val newOffset = toolbarOffsetHeightPx.value + delta
toolbarOffsetHeightPx.value = newOffset.coerceIn(-toolbarHeightPx, 0f)
return Offset.Zero
}
}
}
// Compose Scrollable
Box(
Modifier
.fillMaxSize()
.nestedScroll(nestedScrollConnection)
) {
TopAppBar(
modifier = Modifier
.height(ToolbarHeight)
.offset { IntOffset(x = 0, y = toolbarOffsetHeightPx.value.roundToInt()) },
title = { Text("toolbar offset is ${toolbarOffsetHeightPx.value}") }
)
// Android View
AndroidView(
factory = { context -> AndroidViewWithCompose(context) },
modifier = Modifier.fillMaxWidth()
)
}
}
private fun AndroidViewWithCompose(context: Context): View {
return LayoutInflater.from(context)
.inflate(R.layout.three_fold_nested_scroll_interop, null).apply {
with(findViewById<ComposeView>(R.id.compose_view)) {
// Compose
setContent { LazyColumnWithNestedScrollInteropEnabled() }
}
}.also {
ViewCompat.setNestedScrollingEnabled(it, true)
}
}
@Composable
private fun LazyColumnWithNestedScrollInteropEnabled() {
LazyColumn(
modifier = Modifier.nestedScroll(
rememberNestedScrollInteropConnection()
),
contentPadding = PaddingValues(top = ToolbarHeight)
) {
item {
Text("This is a Lazy Column")
}
items(40) { item ->
Box(
modifier = Modifier
.padding(16.dp)
.height(56.dp)
.fillMaxWidth()
.background(Color.Gray),
contentAlignment = Alignment.Center
) {
Text(item.toString())
}
}
}
}
| apache-2.0 | 48b3b74637835f7ece6a9336341e9a87 | 34.595506 | 93 | 0.663668 | 5.085072 | false | false | false | false |
Undin/intellij-rust | src/main/kotlin/org/rust/lang/core/psi/ext/RsTypeArgumentList.kt | 2 | 1421 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.lang.core.psi.ext
import org.rust.lang.core.psi.*
fun RsTypeArgumentList.getGenericArguments(
includeLifetimes: Boolean = true,
includeTypes: Boolean = true,
includeConsts: Boolean = true,
includeAssocBindings: Boolean = true
): List<RsElement> {
val typeArguments = typeArguments
return stubChildrenOfType<RsElement>().filter {
when {
it is RsLifetime -> includeLifetimes
it is RsTypeReference && it in typeArguments -> includeTypes
it is RsExpr || it is RsTypeReference -> includeConsts
it is RsAssocTypeBinding -> includeAssocBindings
else -> false
}
}
}
val RsTypeArgumentList.lifetimeArguments: List<RsLifetime> get() = lifetimeList
val RsTypeArgumentList.typeArguments: List<RsTypeReference>
get() = typeReferenceList.filter { ref ->
val type = ref as? RsPathType
val element = type?.path?.reference?.resolve()
element !is RsConstant && element !is RsFunction && element !is RsConstParameter
}
val RsTypeArgumentList.constArguments: List<RsElement>
get() {
val typeArguments = typeArguments
return stubChildrenOfType<RsElement>().filter {
it is RsExpr || it is RsTypeReference && it !in typeArguments
}
}
| mit | 67b73c077b3878d883aadea1aa5d8731 | 32.046512 | 88 | 0.675581 | 4.816949 | false | false | false | false |
HabitRPG/habitrpg-android | Habitica/src/main/java/com/habitrpg/android/habitica/ui/viewmodels/GroupViewModel.kt | 1 | 11804 | package com.habitrpg.android.habitica.ui.viewmodels
import android.os.Bundle
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import com.habitrpg.android.habitica.components.UserComponent
import com.habitrpg.android.habitica.data.ChallengeRepository
import com.habitrpg.android.habitica.data.SocialRepository
import com.habitrpg.android.habitica.extensions.Optional
import com.habitrpg.android.habitica.extensions.asOptional
import com.habitrpg.android.habitica.extensions.filterOptionalDoOnEmpty
import com.habitrpg.android.habitica.helpers.MainNavigationController
import com.habitrpg.android.habitica.helpers.NotificationsManager
import com.habitrpg.android.habitica.helpers.RxErrorHandler
import com.habitrpg.android.habitica.models.members.Member
import com.habitrpg.android.habitica.models.notifications.NewChatMessageData
import com.habitrpg.android.habitica.models.social.Challenge
import com.habitrpg.android.habitica.models.social.ChatMessage
import com.habitrpg.android.habitica.models.social.Group
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers
import io.reactivex.rxjava3.core.BackpressureStrategy
import io.reactivex.rxjava3.core.Flowable
import io.reactivex.rxjava3.subjects.BehaviorSubject
import retrofit2.HttpException
import java.util.concurrent.TimeUnit
import javax.inject.Inject
enum class GroupViewType(internal val order: String) {
PARTY("party"),
GUILD("guild"),
TAVERN("tavern")
}
open class GroupViewModel(initializeComponent: Boolean) : BaseViewModel(initializeComponent) {
constructor() : this(true)
@Inject
lateinit var challengeRepository: ChallengeRepository
@Inject
lateinit var socialRepository: SocialRepository
@Inject
lateinit var notificationsManager: NotificationsManager
var groupViewType: GroupViewType? = null
private val group: MutableLiveData<Group?> by lazy {
MutableLiveData<Group?>()
}
private val leader: MutableLiveData<Member?> by lazy {
MutableLiveData<Member?>()
}
private val isMemberData: MutableLiveData<Boolean?> by lazy {
MutableLiveData<Boolean?>()
}
private val _chatMessages: MutableLiveData<List<ChatMessage>> by lazy {
MutableLiveData<List<ChatMessage>>(listOf())
}
val chatmessages: LiveData<List<ChatMessage>> by lazy {
_chatMessages
}
protected val groupIDSubject = BehaviorSubject.create<Optional<String>>()
val groupIDFlowable: Flowable<Optional<String>> = groupIDSubject.toFlowable(BackpressureStrategy.BUFFER)
var gotNewMessages: Boolean = false
init {
loadGroupFromLocal()
loadLeaderFromLocal()
loadMembershipFromLocal()
}
override fun inject(component: UserComponent) {
component.inject(this)
}
override fun onCleared() {
socialRepository.close()
super.onCleared()
}
fun setGroupID(groupID: String) {
if (groupID == groupIDSubject.value?.value) return
groupIDSubject.onNext(groupID.asOptional())
disposable.add(
notificationsManager.getNotifications().firstElement().map {
it.filter { notification ->
val data = notification.data as? NewChatMessageData
data?.group?.id == groupID
}
}
.filter { it.isNotEmpty() }
.flatMapPublisher { userRepository.readNotification(it.first().id) }
.subscribe(
{
},
RxErrorHandler.handleEmptyError()
)
)
}
val groupID: String?
get() = groupIDSubject.value?.value
val isMember: Boolean
get() = isMemberData.value ?: false
val leaderID: String?
get() = group.value?.leaderID
val isLeader: Boolean
get() = user.value?.id == leaderID
val isPublicGuild: Boolean
get() = group.value?.privacy == "public"
fun getGroupData(): LiveData<Group?> = group
fun getLeaderData(): LiveData<Member?> = leader
fun getIsMemberData(): LiveData<Boolean?> = isMemberData
private fun loadGroupFromLocal() {
disposable.add(
groupIDFlowable
.filterOptionalDoOnEmpty { group.value = null }
.flatMap { socialRepository.getGroup(it) }
.map { socialRepository.getUnmanagedCopy(it) }
.observeOn(AndroidSchedulers.mainThread())
.subscribe({ group.value = it }, RxErrorHandler.handleEmptyError())
)
}
private fun loadLeaderFromLocal() {
disposable.add(
groupIDFlowable
.filterOptionalDoOnEmpty { leader.value = null }
.flatMap { socialRepository.getGroup(it) }
.distinctUntilChanged { group1, group2 -> group1.id == group2.id }
.flatMap { socialRepository.getMember(it.leaderID) }
.observeOn(AndroidSchedulers.mainThread())
.subscribe({ leader.value = it }, RxErrorHandler.handleEmptyError())
)
}
private fun loadMembershipFromLocal() {
disposable.add(
groupIDFlowable
.filterOptionalDoOnEmpty { isMemberData.value = null }
.flatMap { socialRepository.getGroupMemberships() }
.observeOn(AndroidSchedulers.mainThread())
.subscribe(
{
isMemberData.value = it.firstOrNull { membership -> membership.groupID == groupID } != null
},
RxErrorHandler.handleEmptyError()
)
)
}
fun retrieveGroup(function: (() -> Unit)?) {
if (groupID?.isNotEmpty() == true) {
disposable.add(
socialRepository.retrieveGroup(groupID ?: "")
.filter { groupViewType == GroupViewType.PARTY }
.flatMap { group1 ->
socialRepository.retrieveGroupMembers(group1.id, true)
}
.doOnComplete { function?.invoke() }
.subscribe({ }, {
if (it is HttpException && it.code() == 404) {
MainNavigationController.navigateBack()
}
RxErrorHandler.reportError(it)
})
)
}
}
fun inviteToGroup(inviteData: HashMap<String, Any>) {
disposable.add(
socialRepository.inviteToGroup(group.value?.id ?: "", inviteData)
.subscribe({ }, RxErrorHandler.handleEmptyError())
)
}
fun updateOrCreateGroup(bundle: Bundle?) {
if (group.value == null) {
socialRepository.createGroup(
bundle?.getString("name"),
bundle?.getString("description"),
bundle?.getString("leader"),
bundle?.getString("groupType"),
bundle?.getString("privacy"),
bundle?.getBoolean("leaderCreateChallenge")
)
} else {
disposable.add(
socialRepository.updateGroup(
group.value, bundle?.getString("name"),
bundle?.getString("description"),
bundle?.getString("leader"),
bundle?.getBoolean("leaderCreateChallenge")
)
.subscribe({ }, RxErrorHandler.handleEmptyError())
)
}
}
fun leaveGroup(groupChallenges: List<Challenge>, keepChallenges: Boolean = true, function: (() -> Unit)? = null) {
if (!keepChallenges) {
for (challenge in groupChallenges) {
challengeRepository.leaveChallenge(challenge, "remove-all").subscribe({}, RxErrorHandler.handleEmptyError())
}
}
disposable.add(
socialRepository.leaveGroup(this.group.value?.id ?: "", keepChallenges)
.flatMap { userRepository.retrieveUser(withTasks = false, forced = true) }
.subscribe(
{
function?.invoke()
},
RxErrorHandler.handleEmptyError()
)
)
}
fun joinGroup(id: String? = null, function: (() -> Unit)? = null) {
disposable.add(
socialRepository.joinGroup(id ?: groupID).subscribe(
{
function?.invoke()
},
RxErrorHandler.handleEmptyError()
)
)
}
fun rejectGroupInvite(id: String? = null) {
groupID?.let {
disposable.add(socialRepository.rejectGroupInvite(id ?: it).subscribe({ }, RxErrorHandler.handleEmptyError()))
}
}
fun markMessagesSeen() {
groupIDSubject.value?.value?.let {
if (groupViewType != GroupViewType.TAVERN && it.isNotEmpty() && gotNewMessages) {
socialRepository.markMessagesSeen(it)
}
}
}
fun likeMessage(message: ChatMessage) {
val index = _chatMessages.value?.indexOf(message)
if (index == null || index < 0) return
disposable.add(
socialRepository.likeMessage(message).subscribe(
{
val list = _chatMessages.value?.toMutableList()
list?.set(index, it)
_chatMessages.postValue(list)
}, RxErrorHandler.handleEmptyError()
)
)
}
fun deleteMessage(chatMessage: ChatMessage) {
val oldIndex = _chatMessages.value?.indexOf(chatMessage) ?: return
val list = _chatMessages.value?.toMutableList()
list?.remove(chatMessage)
_chatMessages.postValue(list)
disposable.add(
socialRepository.deleteMessage(chatMessage).subscribe({
}, {
list?.add(oldIndex, chatMessage)
_chatMessages.postValue(list)
RxErrorHandler.reportError(it)
})
)
}
fun postGroupChat(chatText: String, onComplete: () -> Unit, onError: () -> Unit) {
groupIDSubject.value?.value?.let { groupID ->
socialRepository.postGroupChat(groupID, chatText).subscribe(
{
val list = _chatMessages.value?.toMutableList()
list?.add(0, it.message)
_chatMessages.postValue(list)
onComplete()
},
{ error ->
RxErrorHandler.reportError(error)
onError()
}
)
}
}
fun retrieveGroupChat(onComplete: () -> Unit) {
val groupID = groupIDSubject.value?.value
if (groupID.isNullOrEmpty()) {
onComplete()
return
}
disposable.add(
socialRepository.retrieveGroupChat(groupID)
.delay(500, TimeUnit.MILLISECONDS)
.observeOn(AndroidSchedulers.mainThread())
.subscribe(
{
_chatMessages.postValue(it)
onComplete()
},
RxErrorHandler.handleEmptyError()
)
)
}
fun updateGroup(bundle: Bundle?) {
disposable.add(
socialRepository.updateGroup(
group.value,
bundle?.getString("name"),
bundle?.getString("description"),
bundle?.getString("leader"),
bundle?.getBoolean("leaderOnlyChallenges")
)
.subscribe({}, RxErrorHandler.handleEmptyError())
)
}
}
| gpl-3.0 | 83c737d5e7a01ba4723750f1214d8e66 | 34.987805 | 124 | 0.579973 | 5.581087 | false | false | false | false |
androidx/androidx | compose/material3/material3/src/androidAndroidTest/kotlin/androidx/compose/material3/DismissibleNavigationDrawerTest.kt | 3 | 21774 | /*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.compose.material3
import androidx.compose.animation.core.TweenSpec
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.WindowInsets
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material3.tokens.NavigationDrawerTokens
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.input.canScroll
import androidx.compose.ui.input.consumeScrollContainerInfo
import androidx.compose.ui.platform.LocalLayoutDirection
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.semantics.SemanticsActions
import androidx.compose.ui.semantics.SemanticsProperties
import androidx.compose.ui.test.SemanticsMatcher
import androidx.compose.ui.test.assert
import androidx.compose.ui.test.assertLeftPositionInRootIsEqualTo
import androidx.compose.ui.test.assertTopPositionInRootIsEqualTo
import androidx.compose.ui.test.assertWidthIsEqualTo
import androidx.compose.ui.test.click
import androidx.compose.ui.test.junit4.createComposeRule
import androidx.compose.ui.test.onNodeWithTag
import androidx.compose.ui.test.onParent
import androidx.compose.ui.test.performClick
import androidx.compose.ui.test.performSemanticsAction
import androidx.compose.ui.test.performTouchInput
import androidx.compose.ui.test.swipeLeft
import androidx.compose.ui.test.swipeRight
import androidx.compose.ui.unit.LayoutDirection
import androidx.compose.ui.unit.dp
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.filters.LargeTest
import androidx.test.filters.MediumTest
import androidx.test.filters.SmallTest
import com.google.common.truth.Truth.assertThat
import kotlinx.coroutines.runBlocking
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
@MediumTest
@RunWith(AndroidJUnit4::class)
@OptIn(ExperimentalMaterial3Api::class)
class DismissibleNavigationDrawerTest {
@get:Rule
val rule = createComposeRule()
val NavigationDrawerWidth = NavigationDrawerTokens.ContainerWidth
@Test
fun dismissibleNavigationDrawer_testOffset_whenOpen() {
rule.setMaterialContent(lightColorScheme()) {
val drawerState = rememberDrawerState(DrawerValue.Open)
DismissibleNavigationDrawer(
drawerState = drawerState,
drawerContent = {
DismissibleDrawerSheet {
Box(
Modifier
.fillMaxSize()
.testTag("content")
)
}
},
content = {}
)
}
rule.onNodeWithTag("content")
.assertLeftPositionInRootIsEqualTo(0.dp)
}
@Test
fun dismissibleNavigationDrawer_sheet_respectsContentPadding() {
rule.setMaterialContent(lightColorScheme()) {
val drawerState = rememberDrawerState(DrawerValue.Open)
DismissibleNavigationDrawer(
drawerState = drawerState,
drawerContent = {
DismissibleDrawerSheet(windowInsets = WindowInsets(7.dp, 7.dp, 7.dp, 7.dp)) {
Box(
Modifier
.fillMaxSize()
.testTag("content")
)
}
},
content = {}
)
}
rule.onNodeWithTag("content")
.assertLeftPositionInRootIsEqualTo(7.dp)
.assertTopPositionInRootIsEqualTo(7.dp)
}
@Test
fun dismissibleNavigationDrawer_testOffset_whenClosed() {
rule.setMaterialContent(lightColorScheme()) {
val drawerState = rememberDrawerState(DrawerValue.Closed)
DismissibleNavigationDrawer(
drawerState = drawerState,
drawerContent = {
DismissibleDrawerSheet {
Box(
Modifier
.fillMaxSize()
.testTag("content")
)
}
},
content = {}
)
}
rule.onNodeWithTag("content")
.assertLeftPositionInRootIsEqualTo(-NavigationDrawerWidth)
}
@Test
fun dismissibleNavigationDrawer_testWidth_whenOpen() {
rule.setMaterialContent(lightColorScheme()) {
val drawerState = rememberDrawerState(DrawerValue.Open)
DismissibleNavigationDrawer(
drawerState = drawerState,
drawerContent = {
DismissibleDrawerSheet {
Box(
Modifier
.fillMaxSize()
.testTag("content")
)
}
},
content = {}
)
}
rule.onNodeWithTag("content")
.assertWidthIsEqualTo(NavigationDrawerWidth)
}
@Test
@SmallTest
fun dismissibleNavigationDrawer_hasPaneTitle() {
lateinit var navigationMenu: String
rule.setMaterialContent(lightColorScheme()) {
DismissibleNavigationDrawer(
drawerState = rememberDrawerState(DrawerValue.Open),
drawerContent = {
DismissibleDrawerSheet(Modifier.testTag("navigationDrawerTag")) {
Box(
Modifier
.fillMaxSize()
)
}
},
content = {}
)
navigationMenu = getString(Strings.NavigationMenu)
}
rule.onNodeWithTag("navigationDrawerTag", useUnmergedTree = true)
.onParent()
.assert(SemanticsMatcher.expectValue(SemanticsProperties.PaneTitle, navigationMenu))
}
@Test
@LargeTest
fun dismissibleNavigationDrawer_openAndClose(): Unit = runBlocking(AutoTestFrameClock()) {
lateinit var drawerState: DrawerState
rule.setMaterialContent(lightColorScheme()) {
drawerState = rememberDrawerState(DrawerValue.Closed)
DismissibleNavigationDrawer(
drawerState = drawerState,
drawerContent = {
DismissibleDrawerSheet {
Box(
Modifier
.fillMaxSize()
.testTag(DrawerTestTag)
)
}
},
content = {}
)
}
// Drawer should start in closed state
rule.onNodeWithTag(DrawerTestTag).assertLeftPositionInRootIsEqualTo(-NavigationDrawerWidth)
// When the drawer state is set to Opened
drawerState.open()
// Then the drawer should be opened
rule.onNodeWithTag(DrawerTestTag).assertLeftPositionInRootIsEqualTo(0.dp)
// When the drawer state is set to Closed
drawerState.close()
// Then the drawer should be closed
rule.onNodeWithTag(DrawerTestTag).assertLeftPositionInRootIsEqualTo(-NavigationDrawerWidth)
}
@Test
@LargeTest
fun dismissibleNavigationDrawer_animateTo(): Unit = runBlocking(AutoTestFrameClock()) {
lateinit var drawerState: DrawerState
rule.setMaterialContent(lightColorScheme()) {
drawerState = rememberDrawerState(DrawerValue.Closed)
DismissibleNavigationDrawer(
drawerState = drawerState,
drawerContent = {
DismissibleDrawerSheet {
Box(
Modifier
.fillMaxSize()
.testTag(DrawerTestTag)
)
}
},
content = {}
)
}
// Drawer should start in closed state
rule.onNodeWithTag(DrawerTestTag).assertLeftPositionInRootIsEqualTo(-NavigationDrawerWidth)
// When the drawer state is set to Opened
drawerState.animateTo(DrawerValue.Open, TweenSpec())
// Then the drawer should be opened
rule.onNodeWithTag(DrawerTestTag).assertLeftPositionInRootIsEqualTo(0.dp)
// When the drawer state is set to Closed
drawerState.animateTo(DrawerValue.Closed, TweenSpec())
// Then the drawer should be closed
rule.onNodeWithTag(DrawerTestTag).assertLeftPositionInRootIsEqualTo(-NavigationDrawerWidth)
}
@Test
@LargeTest
fun dismissibleNavigationDrawer_snapTo(): Unit = runBlocking(AutoTestFrameClock()) {
lateinit var drawerState: DrawerState
rule.setMaterialContent(lightColorScheme()) {
drawerState = rememberDrawerState(DrawerValue.Closed)
DismissibleNavigationDrawer(
drawerState = drawerState,
drawerContent = {
DismissibleDrawerSheet {
Box(
Modifier
.fillMaxSize()
.testTag(DrawerTestTag)
)
}
},
content = {}
)
}
// Drawer should start in closed state
rule.onNodeWithTag(DrawerTestTag).assertLeftPositionInRootIsEqualTo(-NavigationDrawerWidth)
// When the drawer state is set to Opened
drawerState.snapTo(DrawerValue.Open)
// Then the drawer should be opened
rule.onNodeWithTag(DrawerTestTag).assertLeftPositionInRootIsEqualTo(0.dp)
// When the drawer state is set to Closed
drawerState.snapTo(DrawerValue.Closed)
// Then the drawer should be closed
rule.onNodeWithTag(DrawerTestTag).assertLeftPositionInRootIsEqualTo(-NavigationDrawerWidth)
}
@Test
@LargeTest
fun dismissibleNavigationDrawer_currentValue(): Unit = runBlocking(AutoTestFrameClock()) {
lateinit var drawerState: DrawerState
rule.setMaterialContent(lightColorScheme()) {
drawerState = rememberDrawerState(DrawerValue.Closed)
DismissibleNavigationDrawer(
drawerState = drawerState,
drawerContent = {
DismissibleDrawerSheet {
Box(
Modifier
.fillMaxSize()
.testTag(DrawerTestTag)
)
}
},
content = {}
)
}
// Drawer should start in closed state
assertThat(drawerState.currentValue).isEqualTo(DrawerValue.Closed)
// When the drawer state is set to Opened
drawerState.snapTo(DrawerValue.Open)
// Then the drawer should be opened
assertThat(drawerState.currentValue).isEqualTo(DrawerValue.Open)
// When the drawer state is set to Closed
drawerState.snapTo(DrawerValue.Closed)
// Then the drawer should be closed
assertThat(drawerState.currentValue).isEqualTo(DrawerValue.Closed)
}
@Test
@LargeTest
fun dismissibleNavigationDrawer_drawerContent_doesntPropagateClicksWhenOpen(): Unit =
runBlocking(
AutoTestFrameClock()
) {
var bodyClicks = 0
lateinit var drawerState: DrawerState
rule.setMaterialContent(lightColorScheme()) {
drawerState = rememberDrawerState(DrawerValue.Closed)
DismissibleNavigationDrawer(
drawerState = drawerState,
drawerContent = {
DismissibleDrawerSheet {
Box(
Modifier
.fillMaxSize()
.testTag(DrawerTestTag)
)
}
},
content = {
Box(
Modifier
.fillMaxSize()
.clickable { bodyClicks += 1 })
}
)
}
// Click in the middle of the drawer
rule.onNodeWithTag(DrawerTestTag).performClick()
rule.runOnIdle {
assertThat(bodyClicks).isEqualTo(1)
}
drawerState.open()
// Click on the left-center pixel of the drawer
rule.onNodeWithTag(DrawerTestTag).performTouchInput {
click(centerLeft)
}
rule.runOnIdle {
assertThat(bodyClicks).isEqualTo(1)
}
}
@Test
@LargeTest
fun dismissibleNavigationDrawer_openBySwipe() {
lateinit var drawerState: DrawerState
rule.setMaterialContent(lightColorScheme()) {
drawerState = rememberDrawerState(DrawerValue.Closed)
Box(Modifier.testTag(DrawerTestTag)) {
DismissibleNavigationDrawer(
drawerState = drawerState,
drawerContent = {
DismissibleDrawerSheet {
Box(
Modifier
.fillMaxSize()
.background(color = Color.Magenta)
)
}
},
content = {
Box(
Modifier
.fillMaxSize()
.background(color = Color.Red)
)
}
)
}
}
rule.onNodeWithTag(DrawerTestTag)
.performTouchInput { swipeRight() }
rule.runOnIdle {
assertThat(drawerState.currentValue).isEqualTo(DrawerValue.Open)
}
rule.onNodeWithTag(DrawerTestTag)
.performTouchInput { swipeLeft() }
rule.runOnIdle {
assertThat(drawerState.currentValue).isEqualTo(DrawerValue.Closed)
}
}
@Test
@LargeTest
fun dismissibleNavigationDrawer_confirmStateChangeRespect() {
lateinit var drawerState: DrawerState
rule.setMaterialContent(lightColorScheme()) {
drawerState = rememberDrawerState(
DrawerValue.Open,
confirmStateChange = {
it != DrawerValue.Closed
}
)
Box(Modifier.testTag(DrawerTestTag)) {
DismissibleNavigationDrawer(
drawerState = drawerState,
drawerContent = {
DismissibleDrawerSheet(Modifier.testTag("content")) {
Box(
Modifier
.fillMaxSize()
.background(color = Color.Magenta)
)
}
},
content = {
Box(
Modifier
.fillMaxSize()
.background(color = Color.Red)
)
}
)
}
}
rule.onNodeWithTag(DrawerTestTag)
.performTouchInput { swipeLeft() }
// still open
rule.runOnIdle {
assertThat(drawerState.currentValue).isEqualTo(DrawerValue.Open)
}
rule.onNodeWithTag("content", useUnmergedTree = true)
.onParent()
.performSemanticsAction(SemanticsActions.Dismiss)
rule.runOnIdle {
assertThat(drawerState.currentValue).isEqualTo(DrawerValue.Open)
}
}
@Test
@LargeTest
fun dismissibleNavigationDrawer_openBySwipe_rtl() {
lateinit var drawerState: DrawerState
rule.setMaterialContent(lightColorScheme()) {
drawerState = rememberDrawerState(DrawerValue.Closed)
// emulate click on the screen
CompositionLocalProvider(LocalLayoutDirection provides LayoutDirection.Rtl) {
Box(Modifier.testTag(DrawerTestTag)) {
DismissibleNavigationDrawer(
drawerState = drawerState,
drawerContent = {
DismissibleDrawerSheet {
Box(
Modifier
.fillMaxSize()
.background(color = Color.Magenta)
)
}
},
content = {
Box(
Modifier
.fillMaxSize()
.background(color = Color.Red)
)
}
)
}
}
}
rule.onNodeWithTag(DrawerTestTag)
.performTouchInput { swipeLeft() }
rule.runOnIdle {
assertThat(drawerState.currentValue).isEqualTo(DrawerValue.Open)
}
rule.onNodeWithTag(DrawerTestTag)
.performTouchInput { swipeRight() }
rule.runOnIdle {
assertThat(drawerState.currentValue).isEqualTo(DrawerValue.Closed)
}
}
@Test
@LargeTest
fun dismissibleNavigationDrawer_noDismissActionWhenClosed_hasDissmissActionWhenOpen(): Unit =
runBlocking(
AutoTestFrameClock()
) {
lateinit var drawerState: DrawerState
rule.setMaterialContent(lightColorScheme()) {
drawerState = rememberDrawerState(DrawerValue.Closed)
DismissibleNavigationDrawer(
drawerState = drawerState,
drawerContent = {
DismissibleDrawerSheet(Modifier.testTag(DrawerTestTag)) {
Box(
Modifier
.fillMaxSize()
)
}
},
content = {}
)
}
// Drawer should start in closed state and have no dismiss action
rule.onNodeWithTag(DrawerTestTag, useUnmergedTree = true)
.onParent()
.assert(SemanticsMatcher.keyNotDefined(SemanticsActions.Dismiss))
// When the drawer state is set to Opened
drawerState.open()
// Then the drawer should be opened and have dismiss action
rule.onNodeWithTag(DrawerTestTag, useUnmergedTree = true)
.onParent()
.assert(SemanticsMatcher.keyIsDefined(SemanticsActions.Dismiss))
// When the drawer state is set to Closed using dismiss action
rule.onNodeWithTag(DrawerTestTag, useUnmergedTree = true)
.onParent()
.performSemanticsAction(SemanticsActions.Dismiss)
// Then the drawer should be closed and have no dismiss action
rule.onNodeWithTag(DrawerTestTag, useUnmergedTree = true)
.onParent()
.assert(SemanticsMatcher.keyNotDefined(SemanticsActions.Dismiss))
}
@Test
fun dismissibleNavigationDrawer_providesScrollableContainerInfo_enabled() {
var actualValue = { false }
rule.setMaterialContent(lightColorScheme()) {
DismissibleNavigationDrawer(
gesturesEnabled = true,
drawerContent = {},
content = {
Box(Modifier.consumeScrollContainerInfo {
actualValue = { it!!.canScroll() }
})
}
)
}
assertThat(actualValue()).isTrue()
}
@Test
fun dismissibleNavigationDrawer_providesScrollableContainerInfo_disabled() {
var actualValue = { false }
rule.setMaterialContent(lightColorScheme()) {
DismissibleNavigationDrawer(
gesturesEnabled = false,
drawerContent = {},
content = {
Box(Modifier.consumeScrollContainerInfo {
actualValue = { it!!.canScroll() }
})
}
)
}
assertThat(actualValue()).isFalse()
}
}
private val DrawerTestTag = "drawer" | apache-2.0 | 7b56568bd98551dbe99304451d464346 | 35.111111 | 99 | 0.542298 | 6.821429 | false | true | false | false |
Soya93/Extract-Refactoring | platform/diff-impl/tests/com/intellij/diff/merge/MergeTestBase.kt | 4 | 14642 | /*
* 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.diff.merge
import com.intellij.diff.DiffContentFactoryImpl
import com.intellij.diff.DiffTestCase
import com.intellij.diff.contents.DocumentContent
import com.intellij.diff.merge.MergeTestBase.SidesState.*
import com.intellij.diff.merge.TextMergeViewer
import com.intellij.diff.merge.TextMergeViewer.MyThreesideViewer
import com.intellij.diff.util.DiffUtil
import com.intellij.diff.util.Side
import com.intellij.diff.util.TextDiffType
import com.intellij.diff.util.ThreeSide
import com.intellij.openapi.actionSystem.ActionPlaces
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.command.CommandProcessor
import com.intellij.openapi.command.undo.UndoManager
import com.intellij.openapi.editor.Document
import com.intellij.openapi.editor.ex.EditorEx
import com.intellij.openapi.fileEditor.impl.text.TextEditorProvider
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Couple
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.util.text.StringUtil
import com.intellij.testFramework.fixtures.IdeaProjectTestFixture
import com.intellij.testFramework.fixtures.IdeaTestFixtureFactory
import com.intellij.util.ui.UIUtil
abstract class MergeTestBase : DiffTestCase() {
private var projectFixture: IdeaProjectTestFixture? = null
private var project: Project? = null
override fun setUp() {
super.setUp()
projectFixture = IdeaTestFixtureFactory.getFixtureFactory().createFixtureBuilder(getTestName(true)).fixture
projectFixture!!.setUp()
project = projectFixture!!.project
}
override fun tearDown() {
projectFixture?.tearDown()
project = null
super.tearDown()
}
fun test1(left: String, base: String, right: String, f: TestBuilder.() -> Unit) {
test(left, base, right, 1, f)
}
fun test2(left: String, base: String, right: String, f: TestBuilder.() -> Unit) {
test(left, base, right, 2, f)
}
fun testN(left: String, base: String, right: String, f: TestBuilder.() -> Unit) {
test(left, base, right, -1, f)
}
fun test(left: String, base: String, right: String, changesCount: Int, f: TestBuilder.() -> Unit) {
val contentFactory = DiffContentFactoryImpl()
val leftContent: DocumentContent = contentFactory.create(parseSource(left))
val baseContent: DocumentContent = contentFactory.create(parseSource(base))
val rightContent: DocumentContent = contentFactory.create(parseSource(right))
val outputContent: DocumentContent = contentFactory.create(parseSource(""))
outputContent.document.setReadOnly(false)
val context = MockMergeContext(project)
val request = MockMergeRequest(leftContent, baseContent, rightContent, outputContent)
val viewer = TextMergeTool.INSTANCE.createComponent(context, request) as TextMergeViewer
try {
val toolbar = viewer.init()
UIUtil.dispatchAllInvocationEvents()
val builder = TestBuilder(viewer, toolbar.toolbarActions ?: emptyList())
builder.assertChangesCount(changesCount)
builder.f()
} finally {
Disposer.dispose(viewer)
}
}
inner class TestBuilder(val mergeViewer: TextMergeViewer, private val actions: List<AnAction>) {
val viewer: MyThreesideViewer = mergeViewer.viewer
val changes: List<TextMergeChange> = viewer.allChanges
val editor: EditorEx = viewer.editor
val document: Document = editor.document
private val textEditor = TextEditorProvider.getInstance().getTextEditor(editor);
private val undoManager = UndoManager.getInstance(project!!)
fun change(num: Int): TextMergeChange {
if (changes.size < num) throw Exception("changes: ${changes.size}, index: $num")
return changes[num]
}
fun activeChanges(): List<TextMergeChange> = viewer.changes
//
// Actions
//
fun runActionByTitle(name: String): Boolean {
val action = actions.filter { name.equals(it.templatePresentation.text) }
assertTrue(action.size == 1, action.toString())
return runAction(action[0])
}
private fun runAction(action: AnAction): Boolean {
val actionEvent = AnActionEvent.createFromAnAction(action, null, ActionPlaces.MAIN_MENU, editor.dataContext)
action.update(actionEvent)
val success = actionEvent.presentation.isEnabledAndVisible
if (success) action.actionPerformed(actionEvent)
return success
}
//
// Modification
//
fun command(affected: TextMergeChange, f: () -> Unit): Unit {
command(listOf(affected), f)
}
fun command(affected: List<TextMergeChange>? = null, f: () -> Unit): Unit {
viewer.executeMergeCommand(null, affected, f)
UIUtil.dispatchAllInvocationEvents()
}
fun write(f: () -> Unit): Unit {
ApplicationManager.getApplication().runWriteAction({ CommandProcessor.getInstance().executeCommand(project, f, null, null) })
UIUtil.dispatchAllInvocationEvents()
}
fun Int.ignore(side: Side, modifier: Boolean = false) {
val change = change(this)
command(change) { viewer.ignoreChange(change, side, modifier) }
}
fun Int.apply(side: Side, modifier: Boolean = false) {
val change = change(this)
command(change) { viewer.replaceChange(change, side, modifier) }
}
//
// Text modification
//
fun insertText(offset: Int, newContent: CharSequence) {
replaceText(offset, offset, newContent)
}
fun deleteText(startOffset: Int, endOffset: Int) {
replaceText(startOffset, endOffset, "")
}
fun replaceText(startOffset: Int, endOffset: Int, newContent: CharSequence) {
write { document.replaceString(startOffset, endOffset, parseSource(newContent)) }
}
fun insertText(offset: LineCol, newContent: CharSequence) {
replaceText(offset.toOffset(), offset.toOffset(), newContent)
}
fun deleteText(startOffset: LineCol, endOffset: LineCol) {
replaceText(startOffset.toOffset(), endOffset.toOffset(), "")
}
fun replaceText(startOffset: LineCol, endOffset: LineCol, newContent: CharSequence) {
write { replaceText(startOffset.toOffset(), endOffset.toOffset(), newContent) }
}
fun replaceText(oldContent: CharSequence, newContent: CharSequence) {
write {
val range = findRange(parseSource(oldContent))
replaceText(range.first, range.second, newContent)
}
}
fun deleteText(oldContent: CharSequence) {
write {
val range = findRange(parseSource(oldContent))
replaceText(range.first, range.second, "")
}
}
fun insertTextBefore(oldContent: CharSequence, newContent: CharSequence) {
write { insertText(findRange(parseSource(oldContent)).first, newContent) }
}
fun insertTextAfter(oldContent: CharSequence, newContent: CharSequence) {
write { insertText(findRange(parseSource(oldContent)).second, newContent) }
}
private fun findRange(oldContent: CharSequence): Couple<Int> {
val text = document.charsSequence
val index1 = StringUtil.indexOf(text, oldContent)
assertTrue(index1 >= 0, "content - '\n$oldContent\n'\ntext - '\n$text'")
val index2 = StringUtil.indexOf(text, oldContent, index1 + 1)
assertTrue(index2 == -1, "content - '\n$oldContent\n'\ntext - '\n$text'")
return Couple(index1, index1 + oldContent.length)
}
//
// Undo
//
fun undo(count: Int = 1) {
if (count == -1) {
while (undoManager.isUndoAvailable(textEditor)) {
undoManager.undo(textEditor)
}
}
else {
for (i in 1..count) {
assertTrue(undoManager.isUndoAvailable(textEditor))
undoManager.undo(textEditor)
}
}
}
fun redo(count: Int = 1) {
if (count == -1) {
while (undoManager.isRedoAvailable(textEditor)) {
undoManager.redo(textEditor)
}
}
else {
for (i in 1..count) {
assertTrue(undoManager.isRedoAvailable(textEditor))
undoManager.redo(textEditor)
}
}
}
fun checkUndo(count: Int = -1, f: TestBuilder.() -> Unit) {
val initialState = ViewerState.recordState(viewer)
f()
UIUtil.dispatchAllInvocationEvents()
val afterState = ViewerState.recordState(viewer)
undo(count)
UIUtil.dispatchAllInvocationEvents()
val undoState = ViewerState.recordState(viewer)
redo(count)
UIUtil.dispatchAllInvocationEvents()
val redoState = ViewerState.recordState(viewer)
assertEquals(initialState, undoState)
assertEquals(afterState, redoState)
}
//
// Checks
//
fun assertChangesCount(expected: Int) {
if (expected == -1) return
val actual = activeChanges().size
assertEquals(expected, actual)
}
fun Int.assertType(type: TextDiffType, changeType: SidesState) {
assertType(type)
assertType(changeType)
}
fun Int.assertType(type: TextDiffType) {
val change = change(this)
assertEquals(change.diffType, type)
}
fun Int.assertType(changeType: SidesState) {
assertTrue(changeType != NONE)
val change = change(this)
val actual = change.type
val isLeftChange = changeType != RIGHT
val isRightChange = changeType != LEFT
assertEquals(Pair(isLeftChange, isRightChange), Pair(actual.isLeftChange, actual.isRightChange))
}
fun Int.assertResolved(type: SidesState) {
val change = change(this)
val isLeftResolved = type == LEFT || type == BOTH
val isRightResolved = type == RIGHT || type == BOTH
assertEquals(Pair(isLeftResolved, isRightResolved), Pair(change.isResolved(Side.LEFT), change.isResolved(Side.RIGHT)))
}
fun Int.assertRange(start: Int, end: Int) {
val change = change(this)
assertEquals(Pair(start, end), Pair(change.startLine, change.endLine))
}
fun Int.assertContent(expected: String, start: Int, end: Int) {
assertContent(expected)
assertRange(start, end)
}
fun Int.assertContent(expected: String) {
val change = change(this)
val document = editor.document
val actual = DiffUtil.getLinesContent(document, change.startLine, change.endLine)
assertEquals(parseSource(expected), actual)
}
fun assertContent(expected: String) {
val actual = viewer.editor.document.charsSequence
assertEquals(parseSource(expected), actual)
}
//
// Helpers
//
operator fun Int.not(): LineColHelper = LineColHelper(this)
operator fun LineColHelper.minus(col: Int): LineCol = LineCol(this.line, col)
inner class LineColHelper(val line: Int) {
}
inner class LineCol(val line: Int, val col: Int) {
fun toOffset(): Int = editor.document.getLineStartOffset(line) + col
}
}
private class MockMergeContext(private val myProject: Project?) : MergeContext() {
override fun getProject(): Project? = myProject
override fun isFocused(): Boolean = false
override fun requestFocus() {
}
override fun finishMerge(result: MergeResult) {
}
}
private class MockMergeRequest(val left: DocumentContent,
val base: DocumentContent,
val right: DocumentContent,
val output: DocumentContent) : TextMergeRequest() {
override fun getTitle(): String? = null
override fun applyResult(result: MergeResult) {
}
override fun getContents(): List<DocumentContent> = listOf(left, base, right)
override fun getOutputContent(): DocumentContent = output
override fun getContentTitles(): List<String?> = listOf(null, null, null)
}
enum class SidesState {
LEFT, RIGHT, BOTH, NONE
}
private data class ViewerState private constructor(private val content: CharSequence,
private val changes: List<ViewerState.ChangeState>) {
companion object {
fun recordState(viewer: MyThreesideViewer): ViewerState {
val content = viewer.editor.document.immutableCharSequence
val changes = viewer.allChanges.map { recordChangeState(viewer, it) }
return ViewerState(content, changes)
}
private fun recordChangeState(viewer: MyThreesideViewer, change: TextMergeChange): ChangeState {
val document = viewer.editor.document;
val content = DiffUtil.getLinesContent(document, change.startLine, change.endLine)
val resolved = if (change.isResolved) BOTH else if (change.isResolved(Side.LEFT)) LEFT else if (change.isResolved(Side.RIGHT)) RIGHT else NONE
val starts = Trio.from { change.getStartLine(it) }
val ends = Trio.from { change.getStartLine(it) }
return ChangeState(content, starts, ends, resolved)
}
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is ViewerState) return false
if (!StringUtil.equals(content, other.content)) return false
if (!changes.equals(other.changes)) return false
return true
}
override fun hashCode(): Int = StringUtil.hashCode(content)
private data class ChangeState(private val content: CharSequence,
private val starts: Trio<Int>,
private val ends: Trio<Int>,
private val resolved: SidesState) {
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is ChangeState) return false
if (!StringUtil.equals(content, other.content)) return false
if (!starts.equals(other.starts)) return false
if (!ends.equals(other.ends)) return false
if (!resolved.equals(other.resolved)) return false
return true
}
override fun hashCode(): Int = StringUtil.hashCode(content)
}
}
}
| apache-2.0 | 37996d36d5abbabc26c0d18369b210f0 | 33.370892 | 150 | 0.68283 | 4.660089 | false | true | false | false |
wordpress-mobile/AztecEditor-Android | aztec/src/test/kotlin/org/wordpress/aztec/CodeTest.kt | 1 | 17840 | //package org.wordpress.aztec
//
//import android.app.Activity
//import android.text.TextUtils
//import org.junit.Assert
//import org.junit.Before
//import org.junit.Test
//import org.junit.runner.RunWith
//import org.robolectric.Robolectric
//import org.robolectric.RobolectricTestRunner
//import org.robolectric.annotation.Config
//import java.util.*
//
///**
// * Testing code behaviour.
// */
//@RunWith(RobolectricTestRunner::class)
//@Config(constants = BuildConfig::class)
//class CodeTest {
//
// val formattingType = AztecTextFormat.FORMAT_CODE
// val codeTag = "code"
// lateinit var editText: AztecText
//
// /**
// * Initialize variables.
// */
// @Before
// fun init() {
// val activity = Robolectric.buildActivity(Activity::class.java).create().visible().get()
// editText = AztecText(activity)
// activity.setContentView(editText)
// }
//
// fun setStyles(editText: AztecText) {
// val styles = ArrayList<ITextFormat>()
// styles.add(formattingType)
// editText.setSelectedStyles(styles)
// }
//
// @Test
// @Throws(Exception::class)
// fun styleSingleItem() {
// editText.append("println(\"hello world\");")
// setStyles(editText)
// Assert.assertEquals("<$codeTag>println(\"hello world\");</$codeTag>", editText.toHtml())
// }
//
// @Test
// @Throws(Exception::class)
// fun styleMultipleSelectedItems() {
// junit.framework.Assert.assertTrue(TextUtils.isEmpty(editText.text))
// editText.append("first item")
// editText.append("\n")
// editText.append("second item")
// editText.append("\n")
// editText.append("third item")
// editText.setSelection(0, editText.length())
// setStyles(editText)
// Assert.assertEquals("<$codeTag>first item<br>second item<br>third item</$codeTag>", editText.toHtml())
// }
//
// @Test
// @Throws(Exception::class)
// fun stylePartiallySelectedMultipleItems() {
// junit.framework.Assert.assertTrue(TextUtils.isEmpty(editText.text))
// editText.append("first item")
// editText.append("\n")
// editText.append("second item")
// editText.append("\n")
// editText.append("third item")
// editText.setSelection(4, 15) // we partially selected first and second item
// setStyles(editText)
// Assert.assertEquals("<$codeTag>first item<br>second item</$codeTag>third item", editText.toHtml())
// }
//
// @Test
// @Throws(Exception::class)
// fun styleSurroundedItem() {
// junit.framework.Assert.assertTrue(TextUtils.isEmpty(editText.text))
// editText.append("first item")
// editText.append("\n")
// editText.append("second item")
// editText.append("\n")
// editText.append("third item")
// editText.setSelection(14)
// setStyles(editText)
// Assert.assertEquals("first item<$codeTag>second item</$codeTag>third item", editText.toHtml())
// }
//
// // enable styling on empty line and enter text
// @Test
// @Throws(Exception::class)
// fun emptyCode() {
// editText.toggleFormatting(formattingType)
// Assert.assertEquals("<$codeTag></$codeTag>", editText.toHtml())
// }
//
// @Test
// @Throws(Exception::class)
// fun styleSingleEnteredItem() {
// setStyles(editText)
// editText.append("first item")
// Assert.assertEquals("<$codeTag>first item</$codeTag>", editText.toHtml())
// }
//
// @Test
// @Throws(Exception::class)
// fun styleMultipleEnteredItems() {
// setStyles(editText)
// editText.append("first item")
// editText.append("\n")
// editText.append("second item")
// Assert.assertEquals("<$codeTag>first item<br>second item</$codeTag>", editText.toHtml())
// }
//
// @Test
// @Throws(Exception::class)
// fun closingPopulatedCode1() {
// val styles = ArrayList<ITextFormat>()
// styles.add(AztecTextFormat.FORMAT_STRIKETHROUGH)
// editText.setSelectedStyles(styles)
// editText.append("first item")
// Assert.assertEquals("<s>first item</s>", editText.toHtml().toString())
// }
//
// @Test
// @Throws(Exception::class)
// fun closingPopulatedCode() {
// val styles = ArrayList<ITextFormat>()
// styles.add(formattingType)
// editText.setSelectedStyles(styles)
// editText.append("first item")
// editText.append("\n")
// editText.append("\n")
// editText.append("not in the code")
// Assert.assertEquals("<$codeTag>first item</$codeTag>not in the code", editText.toHtml().toString())
// }
//
// @Test
// @Throws(Exception::class)
// fun closingEmptyCode() {
// setStyles(editText)
// editText.append("\n")
// Assert.assertEquals("", editText.toHtml().toString())
// }
//
// @Test
// @Throws(Exception::class)
// fun extendingCodeBySplittingItems() {
// setStyles(editText)
// editText.append("firstitem")
// editText.text.insert(5, "\n")
// Assert.assertEquals("<$codeTag>first<br>item</$codeTag>", editText.toHtml().toString())
// }
//
// @Test
// @Throws(Exception::class)
// fun codeSplitWithToolbar() {
// editText.fromHtml("<$codeTag>first item<br>second item<br>third item</$codeTag>")
// editText.setSelection(14)
// setStyles(editText)
// Assert.assertEquals("<$codeTag>first item</$codeTag>second item<$codeTag>third item</$codeTag>", editText.toHtml())
// }
//
// @Test
// @Throws(Exception::class)
// fun removeCodeStyling() {
// editText.fromHtml("<$codeTag>first item</$codeTag>")
// editText.setSelection(1)
// setStyles(editText)
// Assert.assertEquals("first item", editText.toHtml())
// }
//
// @Test
// @Throws(Exception::class)
// fun removeCodeStylingForPartialSelection() {
// editText.fromHtml("<$codeTag>first item</$codeTag>")
// editText.setSelection(2, 4)
// setStyles(editText)
// Assert.assertEquals("first item", editText.toHtml())
// }
//
// @Test
// @Throws(Exception::class)
// fun removeCodeStylingForMultilinePartialSelection() {
// setStyles(editText)
// editText.append("first item")
// editText.append("\n")
// editText.append("second item")
// val firstMark = editText.length() - 4
// editText.append("\n")
// editText.append("third item")
// editText.append("\n")
// val secondMark = editText.length() - 4
// editText.append("fourth item")
// editText.append("\n")
// editText.append("\n")
// editText.append("not in code")
// editText.setSelection(firstMark, secondMark)
// editText.setSelectedStyles(ArrayList());
// Assert.assertEquals("<$codeTag>first item</$codeTag>second item<br>third item<$codeTag>fourth item</$codeTag>not in code", editText.toHtml())
// }
//
// @Test
// @Throws(Exception::class)
// fun emptyCodeSurroundedBytItems() {
// setStyles(editText)
// editText.append("first item")
// editText.append("\n")
// val firstMark = editText.length()
// editText.append("second item")
// editText.append("\n")
// val secondMart = editText.length()
// editText.append("third item")
// editText.text.delete(firstMark - 1, secondMart - 2)
// Assert.assertEquals("<$codeTag>first item<br><br>third item</$codeTag>", editText.toHtml())
// }
//
// @Test
// @Throws(Exception::class)
// fun trailingEmptyLine() {
// setStyles(editText)
// editText.append("first item")
// editText.append("\n")
// editText.append("second item")
// editText.append("\n")
// editText.append("third item")
// val mark = editText.length()
// editText.append("\n")
// Assert.assertEquals("<$codeTag>first item<br>second item<br>third item</$codeTag>", editText.toHtml())
//
// editText.append("\n")
// Assert.assertEquals("<$codeTag>first item<br>second item<br>third item</$codeTag>", editText.toHtml())
//
// editText.append("not in code")
// editText.setSelection(mark)
// editText.text.insert(mark, "\n")
// Assert.assertEquals("<$codeTag>first item<br>second item<br>third item</$codeTag><br>not in code", editText.toHtml())
// }
//
// @Test
// @Throws(Exception::class)
// fun openCodeByAddingNewline() {
// editText.fromHtml("<$codeTag>first item<br>second item</$codeTag>not in code")
// val mark = editText.text.indexOf("second item") + "second item".length
// editText.text.insert(mark, "\n")
// editText.text.insert(mark + 1, "third item")
// Assert.assertEquals("<$codeTag>first item<br>second item<br>third item</$codeTag>not in code", editText.toHtml())
// }
//
// @Test
// @Throws(Exception::class)
// fun openCodeByAppendingTextToTheEnd() {
// editText.fromHtml("<$codeTag>first item<br>second item</$codeTag>not in code")
// editText.setSelection(editText.length())
// editText.text.insert(editText.text.indexOf("\nnot in code"), " (appended)")
// Assert.assertEquals("<$codeTag>first item<br>second item (appended)</$codeTag>not in code", editText.toHtml())
// }
//
// @Test
// @Throws(Exception::class)
// fun openCodeByMovingOutsideTextInsideIt() {
// editText.fromHtml("<$codeTag>first item<br>second item</$codeTag>")
// editText.append("not in code")
//
// editText.text.delete(editText.text.indexOf("not in code"), editText.text.indexOf("not in code"))
// Assert.assertEquals("<$codeTag>first item<br>second itemnot in code</$codeTag>", editText.toHtml())
// }
//
// @Test
// @Throws(Exception::class)
// fun codeRemainsClosedWhenLastCharacterIsDeleted() {
// editText.fromHtml("<$codeTag>first item<br>second item</$codeTag>not in code")
// editText.setSelection(editText.length())
//
// val mark = editText.text.indexOf("second item") + "second item".length;
//
// // delete last character from "second item"
// editText.text.delete(mark - 1, mark)
// Assert.assertEquals("<$codeTag>first item<br>second ite</$codeTag>not in code", editText.toHtml())
// }
//
// @Test
// @Throws(Exception::class)
// fun openingAndReopeningOfCode() {
// editText.fromHtml("<$codeTag>first item<br>second item</$codeTag>")
// editText.setSelection(editText.length())
//
// editText.append("\n")
// editText.append("third item")
// Assert.assertEquals("<$codeTag>first item<br>second item<br>third item</$codeTag>", editText.toHtml())
// editText.append("\n")
// editText.append("\n")
// val mark = editText.length() - 1
// editText.append("not in the code")
// Assert.assertEquals("<$codeTag>first item<br>second item<br>third item</$codeTag>not in the code", editText.toHtml())
// editText.append("\n")
// editText.append("foo")
// Assert.assertEquals("<$codeTag>first item<br>second item<br>third item</$codeTag>not in the code<br>foo", editText.toHtml())
//
// // reopen code
// editText.text.delete(mark, mark + 1)
// Assert.assertEquals("<$codeTag>first item<br>second item<br>third itemnot in the code</$codeTag>foo", editText.toHtml())
// }
//
// @Test
// @Throws(Exception::class)
// fun closeCode() {
// editText.fromHtml("<$codeTag>first item</$codeTag>")
// editText.setSelection(editText.length())
//
// Assert.assertEquals("first item", editText.text.toString())
// editText.append("\n")
// Assert.assertEquals("first item\n\u200B", editText.text.toString())
//
// editText.text.delete(editText.length() - 1, editText.length())
// Assert.assertEquals("first item\n", editText.text.toString())
//
// editText.append("not in the code")
// Assert.assertEquals("<$codeTag>first item</$codeTag>not in the code", editText.toHtml())
// }
//
// @Test
// @Throws(Exception::class)
// fun handlecodeReopeningAfterLastElementDeletion() {
// editText.fromHtml("<$codeTag>first item<br>second item<br>third item</$codeTag>")
// editText.setSelection(editText.length())
// editText.text.delete(editText.text.indexOf("third item", 0), editText.length())
// editText.append("not in the code")
// Assert.assertEquals("<$codeTag>first item<br>second item</$codeTag>not in the code", editText.toHtml())
//
// editText.text.insert(editText.text.indexOf("not in the code") - 1, " addition")
// Assert.assertEquals("<$codeTag>first item<br>second item addition</$codeTag>not in the code", editText.toHtml())
//
// editText.text.insert(editText.text.indexOf("not in the code") - 1, "\n")
// editText.text.insert(editText.text.indexOf("not in the code") - 1, "third item")
// Assert.assertEquals("first item\nsecond item addition\nthird item\nnot in the code", editText.text.toString())
// Assert.assertEquals("<$codeTag>first item<br>second item addition<br>third item</$codeTag>not in the code", editText.toHtml())
// }
//
// @Test
// @Throws(Exception::class)
// fun additionToClosedCode() {
// setStyles(editText)
// editText.append("first item")
// editText.append("\n")
// editText.append("second item")
// val mark = editText.length()
// editText.append("\n")
// editText.append("\n")
// editText.append("not in the code")
// Assert.assertEquals("<$codeTag>first item<br>second item</$codeTag>not in the code", editText.toHtml().toString())
//
// editText.text.insert(mark, " (addition)")
// Assert.assertEquals("<$codeTag>first item<br>second item (addition)</$codeTag>not in the code", editText.toHtml().toString())
// }
//
// @Test
// @Throws(Exception::class)
// fun addItemToCodeFromBottom() {
// setStyles(editText)
// editText.append("first item")
// editText.append("\n")
// editText.append("second item")
// editText.append("\n")
// editText.append("\n")
// editText.append("third item")
// editText.setSelection(editText.length())
// setStyles(editText)
// Assert.assertEquals("<$codeTag>first item<br>second item<br>third item</$codeTag>", editText.toHtml())
// }
//
// @Test
// @Throws(Exception::class)
// fun addItemToCodeFromTop() {
// editText.append("first item")
// editText.append("\n")
// editText.append("second item")
// editText.setSelection(editText.length())
// editText.toggleFormatting(formattingType)
// editText.append("\n")
// editText.append("third item")
// editText.setSelection(0)
// editText.toggleFormatting(formattingType)
// Assert.assertEquals("<$codeTag>first item<br>second item<br>third item</$codeTag>", editText.toHtml())
// }
//
// @Test
// @Throws(Exception::class)
// fun addItemToCodeFromInside() {
// setStyles(editText)
// editText.append("first item")
// editText.append("\n")
// editText.append("\n")
// editText.append("second item")
// editText.append("\n")
// editText.append("third item")
// editText.setSelection(editText.length())
// editText.toggleFormatting(formattingType)
// Assert.assertEquals("<$codeTag>first item</$codeTag>second item<$codeTag>third item</$codeTag>", editText.toHtml())
//
// editText.setSelection(15)
// editText.toggleFormatting(formattingType)
// Assert.assertEquals("<$codeTag>first item<br>second item<br>third item</$codeTag>", editText.toHtml())
// }
//
// @Test
// @Throws(Exception::class)
// fun appendToCodeFromTopAtFirstLine() {
// setStyles(editText)
// editText.append("first item")
// editText.append("\n")
// editText.append("second item")
// editText.setSelection(0)
// editText.text.insert(0, "addition ")
// Assert.assertEquals("<$codeTag>addition first item<br>second item</$codeTag>", editText.toHtml())
// }
//
// @Test
// @Throws(Exception::class)
// fun appendToCodeFromTop() {
// editText.append("not in code")
// editText.append("\n")
// setStyles(editText)
// val mark = editText.length() - 1
// editText.append("first item")
// editText.append("\n")
// editText.append("second item")
// editText.setSelection(mark)
// editText.text.insert(mark, "addition ")
// Assert.assertEquals("not in code<$codeTag>addition first item<br>second item</$codeTag>", editText.toHtml())
// }
//
// @Test
// @Throws(Exception::class)
// fun deleteFirstItemWithKeyboard() {
// setStyles(editText)
// editText.append("first item")
// val firstMark = editText.length()
// editText.append("\n")
// editText.append("second item")
// val secondMark = editText.length()
// editText.append("\n")
// editText.append("third item")
// editText.setSelection(0)
// Assert.assertEquals("first item\nsecond item\nthird item", editText.text.toString())
//
// editText.text.delete(firstMark + 1, secondMark)
// Assert.assertEquals("first item\n\nthird item", editText.text.toString())
// Assert.assertEquals("<$codeTag>first item<br><br>third item</$codeTag>", editText.toHtml())
//
// editText.text.delete(0, firstMark)
// Assert.assertEquals("<$codeTag><br><br>third item</$codeTag>", editText.toHtml())
// }
//}
| mpl-2.0 | a23b11d5d397ee86d8548ad9fbc7d0b9 | 38.122807 | 151 | 0.615247 | 3.781263 | false | true | false | false |
inorichi/tachiyomi-extensions | multisrc/src/main/java/eu/kanade/tachiyomi/multisrc/eromuse/EroMuseGenerator.kt | 1 | 718 | package eu.kanade.tachiyomi.multisrc.eromuse
import generator.ThemeSourceData.SingleLang
import generator.ThemeSourceGenerator
class EroMuseGenerator : ThemeSourceGenerator {
override val themePkg = "eromuse"
override val themeClass = "EroMuse"
override val baseVersionCode: Int = 1
override val sources = listOf(
SingleLang("8Muses", "https://comics.8muses.com", "en", className = "EightMuses", isNsfw = true, overrideVersionCode = 1),
SingleLang("Erofus", "https://www.erofus.com", "en", isNsfw = true, overrideVersionCode = 1)
)
companion object {
@JvmStatic
fun main(args: Array<String>) {
EroMuseGenerator().createAll()
}
}
}
| apache-2.0 | 08d97a7fa8f269572d0a0b9913bf02d7 | 27.72 | 130 | 0.67688 | 3.966851 | false | false | false | false |
Hentioe/BloggerMini | app/src/main/kotlin/io/bluerain/tweets/data/models/TweetModel.kt | 1 | 1031 | package io.bluerain.tweets.data.models
import com.google.gson.annotations.SerializedName
import java.text.SimpleDateFormat
import java.util.*
/**
* Created by hentioe on 17-4-23.
* 数据层: Tweet 模型相关
*/
// 前台 Tweet 模型
data class TweetModel(
var id: Long = 0,
var content: String = "",
var color: String = "",
@SerializedName("create_at") var createAt: Date = Date(),
@SerializedName("update_at") var updateAt: Date = Date(),
@SerializedName("resource_status") var resourceStatus: Int = 0
)
private val dateFormat = SimpleDateFormat("yyyy.MM.dd", Locale.CHINA)
fun TweetModel.createFormatDate(): String = dateFormat.format(this.createAt)
fun TweetModel.statusToString(): String {
when (this.resourceStatus) {
0 -> return ""
1 -> return "(被隐藏的)"
}
return "(特殊状态)"
}
// Tweet Json 传输模型
data class TweetJsonModel(
val id: Long = 0,
var content: String = "",
var color: String = ""
) | gpl-3.0 | 29738564ecb91fe3d8e8bb13bbc20ce8 | 24.282051 | 76 | 0.641624 | 3.648148 | false | false | false | false |
PassionateWsj/YH-Android | app/src/main/java/com/intfocus/template/dashboard/kpi/KpiScrollerListener.kt | 1 | 1694 | package com.intfocus.template.dashboard.kpi
import android.content.Context
import android.support.v7.widget.RecyclerView
import android.view.View
import com.intfocus.template.ui.view.CustomLinearLayoutManager
import com.yonghui.homemetrics.utils.Utils
/**
* Created by CANC on 2017/7/28.
*/
class KpiScrollerListener(val context: Context,
val recyclerView: RecyclerView,
val titleTop: View) : RecyclerView.OnScrollListener() {
private val statusBarHeight: Int = Utils.getStatusBarHeight(context)
private val mLinearLayoutManager: CustomLinearLayoutManager = recyclerView.layoutManager as CustomLinearLayoutManager
/**
* firstVisibleItem:当前能看见的第一个列表项ID(从0开始)
* visibleItemCount:当前能看见的列表项个数(小半个也算) totalItemCount:列表项共数
*/
override fun onScrolled(view: RecyclerView?, dx: Int, dy: Int) {
val isSignificantDelta = Math.abs(dy) > 4
if (isSignificantDelta) {
if (dy > 0) {
} else {
}
}
val loc = IntArray(2)
val firstVisibleItem = mLinearLayoutManager.findFirstVisibleItemPosition()
if (firstVisibleItem == 0 && recyclerView.getChildAt(firstVisibleItem) != null) {
recyclerView.getChildAt(firstVisibleItem).getLocationOnScreen(loc)
if (loc[1] <= statusBarHeight) {
val alpha = Math.abs(loc[1] - statusBarHeight) * 1.0f / titleTop
.measuredHeight
titleTop.alpha = alpha
} else {
titleTop.alpha = 0f
}
}
}
}
| gpl-3.0 | d0d4ba2497ea4227d70ebf486bc61c73 | 33.956522 | 121 | 0.639925 | 4.581197 | false | false | false | false |
wax911/AniTrendApp | app/src/main/java/com/mxt/anitrend/base/custom/viewmodel/ViewModelBase.kt | 1 | 4260 | package com.mxt.anitrend.base.custom.viewmodel
import android.content.Context
import android.os.AsyncTask
import android.os.Bundle
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import com.mxt.anitrend.R
import com.mxt.anitrend.base.custom.async.RequestHandler
import com.mxt.anitrend.base.interfaces.event.ResponseCallback
import com.mxt.anitrend.base.interfaces.event.RetroCallback
import com.mxt.anitrend.util.KeyUtil
import com.mxt.anitrend.util.graphql.apiError
import kotlinx.coroutines.*
import retrofit2.Call
import retrofit2.Response
import kotlin.coroutines.CoroutineContext
/**
* Created by max on 2017/10/14.
* View model abstraction contains the generic data model
*/
class ViewModelBase<T>: ViewModel(), RetroCallback<T>, CoroutineScope {
private val job: Job = SupervisorJob()
val model by lazy {
MutableLiveData<T>()
}
var state: ResponseCallback? = null
private var mLoader: RequestHandler<T>? = null
private lateinit var emptyMessage: String
private lateinit var errorMessage: String
private lateinit var tokenMessage: String
val params = Bundle()
fun setContext(context: Context?) {
context?.apply {
emptyMessage = getString(R.string.layout_empty_response)
errorMessage = getString(R.string.text_error_request)
tokenMessage = getString(R.string.text_error_auth_token)
}
}
/**
* Template to make requests for various data types from api, the
* <br></br>
* @param request_type the type of request to execute
*/
fun requestData(@KeyUtil.RequestType request_type: Int, context: Context) {
mLoader = RequestHandler(params, this, request_type)
mLoader?.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, context)
}
/**
* This method will be called when this ViewModel is no longer used and will be destroyed.
*
*
* It is useful when ViewModel observes some data and you need to clear this subscription to
* prevent a leak of this ViewModel.
*/
override fun onCleared() {
cancel()
if (mLoader?.status != AsyncTask.Status.FINISHED)
mLoader?.cancel(true)
mLoader = null
state = null
super.onCleared()
}
/**
* Invoked for a received HTTP response.
*
*
* Note: An HTTP response may still indicate an application-level failure such as a 404 or 500.
* Call [Response.isSuccessful] to determine if the response indicates success.
*
* @param call the origination requesting object
* @param response the response from the network
*/
override fun onResponse(call: Call<T>, response: Response<T>) {
val container: T? = response.body()
if (response.isSuccessful && container != null)
model.setValue(container)
else {
val error = response.apiError()
// Hacky fix that I'm ashamed of
if (response.code() == 400 && error.contains("Invalid token"))
state?.showError(tokenMessage)
else if (response.code() == 401)
state?.showError(tokenMessage)
else
state?.showError(error)
}
}
/**
* Invoked when a network exception occurred talking to the server or when an unexpected
* exception occurred creating the request or processing the response.
*
* @param call the origination requesting object
* @param throwable contains information about the error
*/
override fun onFailure(call: Call<T>, throwable: Throwable) {
state?.showEmpty(throwable.message ?: errorMessage)
throwable.printStackTrace()
}
/**
* The context of this scope.
* Context is encapsulated by the scope and used for implementation of coroutine builders that are extensions on the scope.
* Accessing this property in general code is not recommended for any purposes except accessing the [Job] instance for advanced usages.
*
* By convention, should contain an instance of a [job][Job] to enforce structured concurrency.
*/
override val coroutineContext: CoroutineContext = Dispatchers.IO + job
}
| lgpl-3.0 | 94970bb5391e4f15b17a4e240de338a3 | 33.918033 | 139 | 0.675822 | 4.67618 | false | false | false | false |
wax911/AniTrendApp | app/src/main/java/com/mxt/anitrend/model/api/converter/AniGraphConverter.kt | 1 | 3981 | package com.mxt.anitrend.model.api.converter
import android.content.Context
import com.google.gson.ExclusionStrategy
import com.google.gson.FieldAttributes
import com.google.gson.GsonBuilder
import com.mxt.anitrend.model.api.converter.request.AniRequestConverter
import com.mxt.anitrend.model.api.converter.response.AniGraphResponseConverter
import io.github.wax911.library.converter.GraphConverter
import io.github.wax911.library.model.request.QueryContainerBuilder
import okhttp3.RequestBody
import okhttp3.ResponseBody
import retrofit2.Converter
import retrofit2.Retrofit
import java.lang.reflect.Type
class AniGraphConverter(
context: Context?
) : GraphConverter(context) {
/**
* Response body converter delegates logic processing to a child class that handles
* wrapping and deserialization of the json response data.
*
* @param parameterAnnotations All the annotation applied to request parameters
* @param methodAnnotations All the annotation applied to the requesting method
* @param retrofit The retrofit object representing the response
* @param type The type of the parameter of the request
*
* @see AniRequestConverter
*/
override fun requestBodyConverter(
type: Type?,
parameterAnnotations: Array<Annotation>,
methodAnnotations: Array<Annotation>,
retrofit: Retrofit?
): Converter<QueryContainerBuilder, RequestBody>? =
AniRequestConverter(
methodAnnotations = methodAnnotations,
graphProcessor = graphProcessor,
gson = gson
)
/**
* Response body converter delegates logic processing to a child class that handles
* wrapping and deserialization of the json response data.
* @see GraphResponseConverter
* <br></br>
*
*
* @param annotations All the annotation applied to the requesting Call method
* @see retrofit2.Call
*
* @param retrofit The retrofit object representing the response
* @param type The generic type declared on the Call method
*/
override fun responseBodyConverter(
type: Type?,
annotations: Array<Annotation>,
retrofit: Retrofit
): Converter<ResponseBody, *>? =
AniGraphResponseConverter<Any>(type, gson)
companion object {
/**
* Allows you to provide your own Gson configuration which will be used when serialize or
* deserialize response and request bodies.
*
* @param context any valid application context
*/
fun create(context: Context?) =
AniGraphConverter(context).apply {
gson = GsonBuilder()
.addSerializationExclusionStrategy(object : ExclusionStrategy {
/**
* @param clazz the class object that is under test
* @return true if the class should be ignored; otherwise false
*/
override fun shouldSkipClass(clazz: Class<*>?) = false
/**
* @param f the field object that is under test
* @return true if the field should be ignored; otherwise false
*/
override fun shouldSkipField(f: FieldAttributes?): Boolean {
return f?.name?.equals("operationName") ?: false
||
f?.name?.equals("extensions") ?: false
}
})
.enableComplexMapKeySerialization()
.setLenient()
.create()
}
}
} | lgpl-3.0 | 7b6af1fb7eb1e8e8f10d1a24fdcd3034 | 40.051546 | 97 | 0.583019 | 5.950673 | false | false | false | false |
rhdunn/xquery-intellij-plugin | src/lang-xquery/main/uk/co/reecedunn/intellij/plugin/xquery/lang/highlighter/XQuerySemanticHighlighter.kt | 1 | 5221 | /*
* Copyright (C) 2021 Reece H. Dunn
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package uk.co.reecedunn.intellij.plugin.xquery.lang.highlighter
import com.intellij.lang.annotation.AnnotationHolder
import com.intellij.lang.annotation.HighlightSeverity
import com.intellij.openapi.editor.colors.EditorColorsManager
import com.intellij.openapi.editor.colors.TextAttributesKey
import com.intellij.openapi.editor.markup.TextAttributes
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
import com.intellij.psi.util.elementType
import uk.co.reecedunn.intellij.plugin.xpath.model.getUsageType
import uk.co.reecedunn.intellij.plugin.xpm.context.XpmUsageType
import uk.co.reecedunn.intellij.plugin.xpm.lang.highlighter.XpmSemanticHighlighter
import uk.co.reecedunn.intellij.plugin.xquery.ast.plugin.PluginDirAttribute
import uk.co.reecedunn.intellij.plugin.xquery.ast.plugin.PluginDirNamespaceAttribute
import uk.co.reecedunn.intellij.plugin.xquery.ast.xquery.XQueryDirElemConstructor
import uk.co.reecedunn.intellij.plugin.xquery.ast.xquery.XQueryDirPIConstructor
import uk.co.reecedunn.intellij.plugin.xquery.ast.xquery.XQueryModule
object XQuerySemanticHighlighter : XpmSemanticHighlighter {
private fun getVariableHighlighting(element: PsiElement?): TextAttributesKey = when (element?.getUsageType()) {
XpmUsageType.Parameter -> XQuerySyntaxHighlighterColors.PARAMETER
else -> XQuerySyntaxHighlighterColors.VARIABLE
}
override fun accepts(file: PsiFile): Boolean = file is XQueryModule
override fun getHighlighting(element: PsiElement): TextAttributesKey = when (element.getUsageType()) {
XpmUsageType.Annotation -> XQuerySyntaxHighlighterColors.ANNOTATION
XpmUsageType.Attribute -> XQuerySyntaxHighlighterColors.ATTRIBUTE
XpmUsageType.DecimalFormat -> XQuerySyntaxHighlighterColors.DECIMAL_FORMAT
XpmUsageType.Element -> XQuerySyntaxHighlighterColors.ELEMENT
XpmUsageType.FunctionDecl -> XQuerySyntaxHighlighterColors.FUNCTION_DECL
XpmUsageType.FunctionRef -> XQuerySyntaxHighlighterColors.FUNCTION_CALL
XpmUsageType.MapKey -> XQuerySyntaxHighlighterColors.MAP_KEY
XpmUsageType.Namespace -> XQuerySyntaxHighlighterColors.NS_PREFIX
XpmUsageType.Option -> XQuerySyntaxHighlighterColors.OPTION
XpmUsageType.Parameter -> XQuerySyntaxHighlighterColors.PARAMETER
XpmUsageType.Pragma -> XQuerySyntaxHighlighterColors.PRAGMA
XpmUsageType.ProcessingInstruction -> XQuerySyntaxHighlighterColors.PROCESSING_INSTRUCTION
XpmUsageType.Type -> XQuerySyntaxHighlighterColors.TYPE
XpmUsageType.Variable -> getVariableHighlighting(element.reference?.resolve())
XpmUsageType.Unknown -> XQuerySyntaxHighlighterColors.IDENTIFIER
}
override fun getElementHighlighting(element: PsiElement): TextAttributesKey {
val ret = XQuerySyntaxHighlighter.getTokenHighlights(element.elementType!!)
return when {
ret.isEmpty() -> XQuerySyntaxHighlighterColors.IDENTIFIER
ret.size == 1 -> ret[0]
else -> ret[1]
}
}
override fun getQNamePrefixHighlighting(element: PsiElement): TextAttributesKey = when {
XpmSemanticHighlighter.isXmlnsPrefix(element) -> XQuerySyntaxHighlighterColors.ATTRIBUTE
else -> XQuerySyntaxHighlighterColors.NS_PREFIX
}
override fun highlight(element: PsiElement, holder: AnnotationHolder) {
highlight(element, XQuerySyntaxHighlighterColors.IDENTIFIER, holder)
}
override fun highlight(element: PsiElement, textAttributes: TextAttributesKey, holder: AnnotationHolder) {
holder.newSilentAnnotation(HighlightSeverity.INFORMATION).range(element)
.enforcedTextAttributes(TextAttributes.ERASE_MARKER)
.create()
if (supportsXmlTagHighlighting(element.parent.parent)) {
// Workaround IDEA-234709 -- XML_TAG is overriding the text colour of textAttributes.
if (!EditorColorsManager.getInstance().isDarkEditor) {
holder.newSilentAnnotation(HighlightSeverity.INFORMATION).range(element)
.textAttributes(XQuerySyntaxHighlighterColors.XML_TAG)
.create()
}
}
holder.newSilentAnnotation(HighlightSeverity.INFORMATION).range(element)
.textAttributes(textAttributes)
.create()
}
private fun supportsXmlTagHighlighting(node: PsiElement): Boolean = when (node) {
is PluginDirAttribute -> true
is PluginDirNamespaceAttribute -> true
is XQueryDirElemConstructor -> true
is XQueryDirPIConstructor -> true
else -> false
}
}
| apache-2.0 | 44c0f8c7c38eb1f53d10988db3ff120b | 48.72381 | 115 | 0.75656 | 5.410363 | false | false | false | false |
HabitRPG/habitica-android | Habitica/src/main/java/com/habitrpg/android/habitica/ui/views/tasks/form/HabitResetStreakButtons.kt | 1 | 3451 | package com.habitrpg.android.habitica.ui.views.tasks.form
import android.content.Context
import android.graphics.Typeface
import android.util.AttributeSet
import android.view.Gravity
import android.view.View
import android.view.accessibility.AccessibilityEvent
import android.widget.LinearLayout
import android.widget.TextView
import androidx.core.content.ContextCompat
import com.habitrpg.android.habitica.R
import com.habitrpg.common.habitica.extensions.dpToPx
import com.habitrpg.common.habitica.extensions.nameRes
import com.habitrpg.shared.habitica.models.tasks.HabitResetOption
class HabitResetStreakButtons @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
defStyleAttr: Int = 0
) : LinearLayout(context, attrs, defStyleAttr) {
var tintColor: Int = ContextCompat.getColor(context, R.color.brand_300)
var selectedResetOption: HabitResetOption = HabitResetOption.DAILY
set(value) {
field = value
removeAllViews()
addAllButtons()
selectedButton.sendAccessibilityEvent(
AccessibilityEvent.CONTENT_CHANGE_TYPE_CONTENT_DESCRIPTION
)
}
private lateinit var selectedButton: TextView
init {
addAllButtons()
}
private fun addAllButtons() {
val lastResetOption = HabitResetOption.values().last()
val margin = 16.dpToPx(context)
val height = 28.dpToPx(context)
for (resetOption in HabitResetOption.values()) {
val button = createButton(resetOption)
val layoutParams = LayoutParams(0, height)
layoutParams.weight = 1f
if (resetOption != lastResetOption) {
layoutParams.marginEnd = margin
}
button.textAlignment = View.TEXT_ALIGNMENT_GRAVITY
button.gravity = Gravity.CENTER
button.layoutParams = layoutParams
addView(button)
if (resetOption == selectedResetOption) {
selectedButton = button
}
}
}
private fun createButton(resetOption: HabitResetOption): TextView {
val isActive = selectedResetOption == resetOption
val button = TextView(context)
val buttonText = context.getString(resetOption.nameRes)
button.text = buttonText
button.contentDescription = toContentDescription(buttonText, isActive)
button.background = ContextCompat.getDrawable(context, R.drawable.layout_rounded_bg_content)
if (isActive) {
button.background.setTint(tintColor)
button.setTextColor(ContextCompat.getColor(context, R.color.white))
button.typeface = Typeface.create("sans-serif-medium", Typeface.NORMAL)
} else {
button.background.setTint(ContextCompat.getColor(context, R.color.taskform_gray))
button.setTextColor(ContextCompat.getColor(context, R.color.text_secondary))
button.typeface = Typeface.create("sans-serif", Typeface.NORMAL)
}
button.setOnClickListener {
selectedResetOption = resetOption
}
return button
}
private fun toContentDescription(buttonText: CharSequence, isActive: Boolean): String {
val statusString = if (isActive) {
context.getString(R.string.selected)
} else context.getString(R.string.not_selected)
return "$buttonText, $statusString"
}
}
| gpl-3.0 | 5ea0723d01a92dbcc3e1f3afb7ecc68d | 36.51087 | 100 | 0.680093 | 5.060117 | false | false | false | false |
TimLavers/IndoFlashKotlin | app/src/main/java/org/grandtestauto/indoflash/IndoFlash.kt | 1 | 6521 | package org.grandtestauto.indoflash
import android.app.Application
import android.content.Context
import android.util.Log
import org.grandtestauto.indoflash.spec.ApplicationSpec
import org.grandtestauto.indoflash.spec.ChapterSpec
import org.grandtestauto.indoflash.spec.WordListSpec
import org.grandtestauto.indoflash.word.Word
import org.grandtestauto.indoflash.word.WordList
import org.grandtestauto.indoflash.word.readFromStream
import java.io.BufferedReader
import java.io.InputStreamReader
import java.io.OutputStreamWriter
import javax.xml.parsers.DocumentBuilderFactory
const val FAVOURITES_FILE_NAME = "favourites"
const val LOG_ID = "IndoFlash:IndoFlash"
const val PREFERENCES_NAME = "IndoFlash"
const val INDONESIAN_TO_ENGLISH_PREFERENCES_KEY = "IndonesianToEnglish"
const val CHAPTER_PREFERENCES_KEY = "Chapter"
const val WORD_LIST_PREFERENCES_KEY = "WordList"
/**
* The main application. Holds the state such as the list of words
* currently being studied, whether or not to shuffle the list,
* and so on.
*
* @author Tim Lavers
*/
class IndoFlash : Application() {
lateinit private var wordListSpec: WordListSpec
lateinit private var wordList: WordList
lateinit private var currentChapter: ChapterSpec
lateinit private var applicationSpec: ApplicationSpec
private var showIndonesianFirst = false
private var showingFavourites = false
private var shuffle = false
override fun onCreate() {
super.onCreate()
parseSetupFileToApplicationSpec()
showIndonesianFirst = getSharedPreferences(PREFERENCES_NAME, Context.MODE_PRIVATE).getBoolean(INDONESIAN_TO_ENGLISH_PREFERENCES_KEY, false)
setInitialChapterAndWordList()
}
private fun setInitialChapterAndWordList() {
val storedChapter = getSetting(CHAPTER_PREFERENCES_KEY)
currentChapter = applicationSpec.chapterForName(storedChapter) ?: applicationSpec.chapterSpecs[0]
val storedWordList = getSetting(WORD_LIST_PREFERENCES_KEY)
wordListSpec = currentChapter.forName(storedWordList) ?: currentChapter.wordLists()[0]
setWordList(wordListSpec)
}
override fun onTerminate() {
super.onTerminate()
}
fun applicationSpec(): ApplicationSpec = applicationSpec
fun addRemoveFavourite(word: Word) {
//If translation is showing first, the word passed in here is the reverse of its stored version in the data files.
val wordToAddOrRemove = if (showIndonesianFirst()) word else Word(word.definition, word.word)
val words = readFromFavourites()
if (showingFavourites) {
words.remove(wordToAddOrRemove)
} else {
words.add(wordToAddOrRemove)
}
writeToFavourites(words)
}
fun clearFavourites() {
writeToFavourites(WordList(emptyList<Word>()))
}
internal fun storedFavourites(): WordList = readFromFavourites()
internal fun wordList(): WordList = wordList
fun toggleShowIndonesianFirst() {
showIndonesianFirst = !showIndonesianFirst
storeSetting(INDONESIAN_TO_ENGLISH_PREFERENCES_KEY, showIndonesianFirst)
}
private fun storeSetting(key: String, value: Boolean) {
getSharedPreferences(PREFERENCES_NAME, Context.MODE_PRIVATE).edit().putBoolean(key, value).apply()
}
private fun storeSetting(key: String, value: String) {
getSharedPreferences(PREFERENCES_NAME, Context.MODE_PRIVATE).edit().putString(key, value).apply()
}
private fun getSetting(key: String): String = getSharedPreferences(PREFERENCES_NAME, Context.MODE_PRIVATE).getString(key, "")
fun showIndonesianFirst(): Boolean = showIndonesianFirst
fun setWordList(wordListSpec: WordListSpec) {
this.wordListSpec = wordListSpec
val fileName = wordListSpec.fileName
if (fileName.equals(FAVOURITES_FILE_NAME, ignoreCase = true)) {
wordList = readFromFavourites()
showingFavourites = true
} else {
wordList = readWordList(fileName)
showingFavourites = false
}
storeSetting(WORD_LIST_PREFERENCES_KEY, wordListSpec.title)
}
fun setCurrentChapter(chapterSpec: ChapterSpec) {
this.currentChapter = chapterSpec
storeSetting(CHAPTER_PREFERENCES_KEY, chapterSpec.title)
}
fun currentChapter(): ChapterSpec = currentChapter
fun currentWordList(): WordListSpec = wordListSpec
fun chapterSpecs(): List<ChapterSpec> = applicationSpec.chapterSpecs
fun shuffle(): Boolean = shuffle
fun toggleShuffle() {
shuffle = !shuffle
}
fun showingFavourites(): Boolean = showingFavourites
private fun parseSetupFileToApplicationSpec() {
val inputStream = resources.openRawResource(R.raw.setup)
try {
val builder = DocumentBuilderFactory.newInstance().newDocumentBuilder()
val document = builder.parse(inputStream)
applicationSpec = ApplicationSpec(document)
} catch (e: Exception) {
handleError("Error reading setup file", e)
}
}
private fun readWordList(fileName: String): WordList {
val raw = R.raw::class.java
try {
val fileNameIntField = raw.getField(fileName)
val fileNameInt = fileNameIntField.getInt(null)
val inputStream = resources.openRawResource(fileNameInt)
val reader = BufferedReader(InputStreamReader(inputStream, "UTF-8"))
return readFromStream(reader)
} catch (e: Throwable) {
Log.e(LOG_ID, "Problem loading file", e)
return WordList(emptyList<Word>())
}
}
private fun readFromFavourites(): WordList {
try {
val fin = openFileInput(FAVOURITES_FILE_NAME)
val reader = InputStreamReader(fin, "UTF-8")
return readFromStream(reader)
} catch (e: Exception) {
Log.d(LOG_ID, "Problem when reading from favourites.", e)
return WordList(emptyList<Word>())
}
}
private fun writeToFavourites(toStore: WordList) {
try {
val fout = openFileOutput(FAVOURITES_FILE_NAME, Context.MODE_PRIVATE)
toStore.store(OutputStreamWriter(fout!!, "UTF-8"))
} catch (e: Exception) {
Log.d(LOG_ID, "Could not find file $FAVOURITES_FILE_NAME when writing to favourites.", e)
}
}
private fun handleError(msg: String, problem: Exception) {
Log.e(LOG_ID, msg, problem)
}
} | mit | 6a64102bbdd77ea6aa9a24284cc4b6e5 | 35.033149 | 147 | 0.692225 | 4.812546 | false | false | false | false |
GLodi/GitNav | app/src/main/java/giuliolodi/gitnav/ui/issuelist/IssueClosedPresenter.kt | 1 | 4409 | /*
* Copyright 2017 GLodi
*
* 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 giuliolodi.gitnav.ui.issuelist
import giuliolodi.gitnav.data.DataManager
import giuliolodi.gitnav.ui.base.BasePresenter
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.schedulers.Schedulers
import org.eclipse.egit.github.core.Issue
import timber.log.Timber
import javax.inject.Inject
/**
* Created by giulio on 02/09/2017.
*/
class IssueClosedPresenter<V: IssueClosedContract.View> : BasePresenter<V>, IssueClosedContract.Presenter<V> {
private val TAG = "IssueClosedPresenter"
private var mOwner: String? = null
private var mName: String? = null
private var PAGE_N: Int = 1
private var ITEMS_PER_PAGE: Int = 10
private var LOADING: Boolean = false
private var LOADING_LIST: Boolean = false
private var mHashMap: HashMap<String,String> = hashMapOf()
private var mIssueList: MutableList<Issue> = mutableListOf()
private var NO_SHOWING: Boolean = false
@Inject
constructor(mCompositeDisposable: CompositeDisposable, mDataManager: DataManager) : super(mCompositeDisposable, mDataManager)
override fun subscribe(isNetworkAvailable: Boolean, owner: String?, name: String?) {
mOwner = owner
mName = name
mHashMap.put("state", "closed")
if (!mIssueList.isEmpty()) getView().showClosedIssues(mIssueList)
else if (LOADING) getView().showLoading()
else if (NO_SHOWING) getView().showNoClosedIssues()
else {
if (isNetworkAvailable) {
getView().showLoading()
LOADING = true
loadClosedIssues()
}
else {
getView().showNoConnectionError()
getView().hideLoading()
LOADING = false
}
}
}
private fun loadClosedIssues() {
getCompositeDisposable().add(getDataManager().pageIssues(mOwner!!, mName!!, PAGE_N, ITEMS_PER_PAGE, mHashMap)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(
{ openIssueList ->
getView().hideLoading()
getView().hideListLoading()
mIssueList.addAll(openIssueList)
getView().showClosedIssues(openIssueList)
if (PAGE_N == 1 && openIssueList.isEmpty()) {
getView().showNoClosedIssues()
NO_SHOWING = true
}
PAGE_N += 1
LOADING = false
LOADING_LIST = false
},
{ throwable ->
throwable?.localizedMessage?.let { getView().showError(it) }
getView().hideLoading()
getView().hideListLoading()
Timber.e(throwable)
LOADING = false
LOADING_LIST = false
}
))
}
override fun onLastItemVisible(isNetworkAvailable: Boolean, dy: Int) {
if (LOADING_LIST)
return
if (isNetworkAvailable) {
LOADING_LIST = true
getView().showListLoading()
loadClosedIssues()
}
else if (dy > 0) {
getView().showNoConnectionError()
getView().hideLoading()
}
}
override fun onUserClick(username: String) {
getView().intentToUserActivity(username)
}
override fun onIssueClick(issueNumber: Int) {
getView().intentToIssueActivity(issueNumber)
}
} | apache-2.0 | fb47f87421b7690ac4db814cea33541c | 35.446281 | 129 | 0.580857 | 5.324879 | false | false | false | false |
StepicOrg/stepic-android | app/src/main/java/org/stepik/android/domain/course/analytic/batch/CourseCardSeenAnalyticBatchEvent.kt | 2 | 1305 | package org.stepik.android.domain.course.analytic.batch
import org.stepik.android.domain.base.analytic.AnalyticEvent
import org.stepik.android.domain.base.analytic.AnalyticSource
import org.stepik.android.domain.course.analytic.CourseViewSource
import java.util.EnumSet
class CourseCardSeenAnalyticBatchEvent(
courseId: Long,
source: CourseViewSource
) : AnalyticEvent {
companion object {
private const val DATA = "data"
private const val PARAM_COURSE = "course"
private const val PARAM_SOURCE = "source"
private const val PARAM_PLATFORM = "platform"
private const val PARAM_POSITION = "position"
private const val PARAM_DATA = "data"
private const val PLATFORM_VALUE = "android"
private const val POSITION_VALUE = 1
}
override val name: String =
"catalog-display"
override val params: Map<String, Any> =
mapOf(
DATA to mapOf(
PARAM_COURSE to courseId,
PARAM_SOURCE to source.name,
PARAM_PLATFORM to PLATFORM_VALUE,
PARAM_POSITION to POSITION_VALUE,
PARAM_DATA to source.params
)
)
override val sources: EnumSet<AnalyticSource> =
EnumSet.of(AnalyticSource.STEPIK_API)
} | apache-2.0 | 0988b190740fe32395f731628e64d8c8 | 30.853659 | 65 | 0.657471 | 4.611307 | false | false | false | false |
WangDaYeeeeee/GeometricWeather | app/src/main/java/wangdaye/com/geometricweather/main/fragments/HomeFragment.kt | 1 | 16136 | package wangdaye.com.geometricweather.main.fragments
import android.animation.Animator
import android.annotation.SuppressLint
import android.content.res.Configuration
import android.graphics.Color
import android.os.Bundle
import android.view.LayoutInflater
import android.view.MotionEvent
import android.view.View
import android.view.View.OnTouchListener
import android.view.ViewGroup
import androidx.coordinatorlayout.widget.CoordinatorLayout
import androidx.core.graphics.ColorUtils
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.RecyclerView
import wangdaye.com.geometricweather.R
import wangdaye.com.geometricweather.common.basic.GeoActivity
import wangdaye.com.geometricweather.common.basic.livedata.EqualtableLiveData
import wangdaye.com.geometricweather.common.basic.models.Location
import wangdaye.com.geometricweather.common.ui.widgets.SwipeSwitchLayout
import wangdaye.com.geometricweather.common.ui.widgets.SwipeSwitchLayout.OnSwitchListener
import wangdaye.com.geometricweather.databinding.FragmentHomeBinding
import wangdaye.com.geometricweather.main.MainActivityViewModel
import wangdaye.com.geometricweather.main.adapters.main.MainAdapter
import wangdaye.com.geometricweather.main.layouts.MainLayoutManager
import wangdaye.com.geometricweather.main.utils.MainModuleUtils
import wangdaye.com.geometricweather.main.utils.MainThemeColorProvider
import wangdaye.com.geometricweather.settings.SettingsManager
import wangdaye.com.geometricweather.theme.ThemeManager
import wangdaye.com.geometricweather.theme.resource.ResourcesProviderFactory
import wangdaye.com.geometricweather.theme.resource.providers.ResourceProvider
import wangdaye.com.geometricweather.theme.weatherView.WeatherView
import wangdaye.com.geometricweather.theme.weatherView.WeatherViewController
class HomeFragment : MainModuleFragment() {
private lateinit var binding: FragmentHomeBinding
private lateinit var viewModel: MainActivityViewModel
private lateinit var weatherView: WeatherView
private var adapter: MainAdapter? = null
private var scrollListener: OnScrollListener? = null
private var recyclerViewAnimator: Animator? = null
private var resourceProvider: ResourceProvider? = null
private val previewOffset = EqualtableLiveData(0)
private var callback: Callback? = null
interface Callback {
fun onManageIconClicked()
fun onSettingsIconClicked()
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
binding = FragmentHomeBinding.inflate(layoutInflater, container, false)
initModel()
// attach weather view.
weatherView = ThemeManager
.getInstance(requireContext())
.weatherThemeDelegate
.getWeatherView(requireContext())
(binding.switchLayout.parent as CoordinatorLayout).addView(
weatherView as View,
0,
CoordinatorLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT
)
)
initView()
setCallback(requireActivity() as Callback)
return binding.root
}
override fun onResume() {
super.onResume()
weatherView.setDrawable(!isHidden)
}
override fun onPause() {
super.onPause()
weatherView.setDrawable(false)
}
override fun onDestroyView() {
super.onDestroyView()
adapter = null
binding.recyclerView.clearOnScrollListeners()
scrollListener = null
}
override fun onHiddenChanged(hidden: Boolean) {
super.onHiddenChanged(hidden)
weatherView.setDrawable(!hidden)
}
override fun setSystemBarStyle() {
ThemeManager
.getInstance(requireContext())
.weatherThemeDelegate
.setSystemBarStyle(
requireContext(),
requireActivity().window,
statusShader = scrollListener?.topOverlap == true,
lightStatus = false,
navigationShader = true,
lightNavigation = false
)
}
override fun onConfigurationChanged(newConfig: Configuration) {
super.onConfigurationChanged(newConfig)
updateDayNightColors()
updateViews()
}
// init.
private fun initModel() {
viewModel = ViewModelProvider(requireActivity())[MainActivityViewModel::class.java]
}
@SuppressLint("ClickableViewAccessibility", "NonConstantResourceId", "NotifyDataSetChanged")
private fun initView() {
ensureResourceProvider()
weatherView.setGravitySensorEnabled(
SettingsManager.getInstance(requireContext()).isGravitySensorEnabled
)
binding.toolbar.setNavigationOnClickListener {
if (callback != null) {
callback!!.onManageIconClicked()
}
}
binding.toolbar.inflateMenu(R.menu.activity_main)
binding.toolbar.setOnMenuItemClickListener { menuItem ->
when (menuItem.itemId) {
R.id.action_manage -> if (callback != null) {
callback!!.onManageIconClicked()
}
R.id.action_settings -> if (callback != null) {
callback!!.onSettingsIconClicked()
}
}
true
}
binding.switchLayout.setOnSwitchListener(switchListener)
binding.switchLayout.reset()
binding.indicator.setSwitchView(binding.switchLayout)
binding.indicator.setCurrentIndicatorColor(Color.WHITE)
binding.indicator.setIndicatorColor(
ColorUtils.setAlphaComponent(Color.WHITE, (0.5 * 255).toInt())
)
binding.refreshLayout.setOnRefreshListener {
viewModel.updateWithUpdatingChecking(
triggeredByUser = true,
checkPermissions = true
)
}
val listAnimationEnabled = SettingsManager
.getInstance(requireContext())
.isListAnimationEnabled
val itemAnimationEnabled = SettingsManager
.getInstance(requireContext())
.isItemAnimationEnabled
adapter = MainAdapter(
(requireActivity() as GeoActivity),
binding.recyclerView,
weatherView,
null,
resourceProvider!!,
listAnimationEnabled,
itemAnimationEnabled
)
binding.recyclerView.adapter = adapter
binding.recyclerView.layoutManager = MainLayoutManager()
binding.recyclerView.addOnScrollListener(OnScrollListener().also { scrollListener = it })
binding.recyclerView.setOnTouchListener(indicatorStateListener)
viewModel.currentLocation.observe(viewLifecycleOwner) {
updateViews(it.location)
}
viewModel.loading.observe(viewLifecycleOwner) { setRefreshing(it) }
viewModel.indicator.observe(viewLifecycleOwner) {
binding.switchLayout.isEnabled = it.total > 1
if (binding.switchLayout.totalCount != it.total
|| binding.switchLayout.position != it.index) {
binding.switchLayout.setData(it.index, it.total)
binding.indicator.setSwitchView(binding.switchLayout)
}
binding.indicator.visibility = if (it.total > 1) View.VISIBLE else View.GONE
}
previewOffset.observe(viewLifecycleOwner) {
binding.root.post {
if (isFragmentViewCreated) {
updatePreviewSubviews()
}
}
}
}
private fun updateDayNightColors() {
binding.refreshLayout.setProgressBackgroundColorSchemeColor(
MainThemeColorProvider.getColor(
location = viewModel.currentLocation.value!!.location,
id = R.attr.colorSurface
)
)
}
// control.
@JvmOverloads
fun updateViews(location: Location = viewModel.currentLocation.value!!.location) {
ensureResourceProvider()
updateContentViews(location = location)
binding.root.post {
if (isFragmentViewCreated) {
updatePreviewSubviews()
}
}
}
@SuppressLint("ClickableViewAccessibility", "NotifyDataSetChanged")
private fun updateContentViews(location: Location) {
if (recyclerViewAnimator != null) {
recyclerViewAnimator!!.cancel()
recyclerViewAnimator = null
}
updateDayNightColors()
binding.switchLayout.reset()
if (location.weather == null) {
adapter!!.setNullWeather()
adapter!!.notifyDataSetChanged()
binding.recyclerView.setOnTouchListener { _, event ->
if (event.action == MotionEvent.ACTION_DOWN
&& !binding.refreshLayout.isRefreshing) {
viewModel.updateWithUpdatingChecking(
triggeredByUser = true,
checkPermissions = true
)
}
false
}
return
}
binding.recyclerView.setOnTouchListener(null)
val listAnimationEnabled = SettingsManager
.getInstance(requireContext())
.isListAnimationEnabled
val itemAnimationEnabled = SettingsManager
.getInstance(requireContext())
.isItemAnimationEnabled
adapter!!.update(
(requireActivity() as GeoActivity),
binding.recyclerView,
weatherView,
location,
resourceProvider!!,
listAnimationEnabled,
itemAnimationEnabled
)
adapter!!.notifyDataSetChanged()
scrollListener!!.postReset(binding.recyclerView)
if (!listAnimationEnabled) {
binding.recyclerView.alpha = 0f
recyclerViewAnimator = MainModuleUtils.getEnterAnimator(
binding.recyclerView,
0
)
recyclerViewAnimator!!.startDelay = 150
recyclerViewAnimator!!.start()
}
}
private fun ensureResourceProvider() {
val iconProvider = SettingsManager
.getInstance(requireContext())
.iconProvider
if (resourceProvider == null
|| resourceProvider!!.packageName != iconProvider) {
resourceProvider = ResourcesProviderFactory.getNewInstance()
}
}
private fun updatePreviewSubviews() {
val location = viewModel.getValidLocation(
previewOffset.value!!
)
val daylight = location.isDaylight
binding.toolbar.title = location.getCityName(requireContext())
WeatherViewController.setWeatherCode(
weatherView,
location.weather,
daylight,
resourceProvider!!
)
binding.refreshLayout.setColorSchemeColors(
ThemeManager
.getInstance(requireContext())
.weatherThemeDelegate
.getThemeColors(
requireContext(),
WeatherViewController.getWeatherKind(location.weather),
daylight
)[0]
)
}
private fun setRefreshing(b: Boolean) {
binding.refreshLayout.post {
if (isFragmentViewCreated) {
binding.refreshLayout.isRefreshing = b
}
}
}
// interface.
private fun setCallback(callback: Callback?) {
this.callback = callback
}
// on touch listener.
@SuppressLint("ClickableViewAccessibility")
private val indicatorStateListener = OnTouchListener { _, event ->
when (event.action) {
MotionEvent.ACTION_MOVE ->
binding.indicator.setDisplayState(true)
MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL ->
binding.indicator.setDisplayState(false)
}
false
}
// on swipe listener (swipe switch layout).
private val switchListener: OnSwitchListener = object : OnSwitchListener {
override fun onSwiped(swipeDirection: Int, progress: Float) {
binding.indicator.setDisplayState(progress != 0f)
if (progress >= 1) {
previewOffset.setValue(
if (swipeDirection == SwipeSwitchLayout.SWIPE_DIRECTION_LEFT) 1 else -1
)
} else {
previewOffset.setValue(0)
}
}
override fun onSwitched(swipeDirection: Int) {
binding.indicator.setDisplayState(false)
viewModel.offsetLocation(
if (swipeDirection == SwipeSwitchLayout.SWIPE_DIRECTION_LEFT) 1 else -1
)
previewOffset.setValue(0)
}
}
// on scroll changed listener.
private inner class OnScrollListener : RecyclerView.OnScrollListener() {
private var mTopChanged: Boolean? = null
var topOverlap = false
private var mFirstCardMarginTop = 0
private var mScrollY = 0
private var mLastAppBarTranslationY = 0f
fun postReset(recyclerView: RecyclerView) {
recyclerView.post {
if (!isFragmentViewCreated) {
return@post
}
mTopChanged = null
topOverlap = false
mFirstCardMarginTop = 0
mScrollY = 0
mLastAppBarTranslationY = 0f
onScrolled(recyclerView, 0, 0)
}
}
override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
mFirstCardMarginTop = if (recyclerView.childCount > 0) {
recyclerView.getChildAt(0).measuredHeight
} else {
-1
}
mScrollY = recyclerView.computeVerticalScrollOffset()
mLastAppBarTranslationY = binding.appBar.translationY
weatherView.onScroll(mScrollY)
if (adapter != null) {
adapter!!.onScroll()
}
// set translation y of toolbar.
if (adapter != null && mFirstCardMarginTop > 0) {
if (mFirstCardMarginTop >= binding.appBar.measuredHeight
+ adapter!!.currentTemperatureTextHeight) {
when {
mScrollY < (mFirstCardMarginTop
- binding.appBar.measuredHeight
- adapter!!.currentTemperatureTextHeight) -> {
binding.appBar.translationY = 0f
}
mScrollY > mFirstCardMarginTop - binding.appBar.y -> {
binding.appBar.translationY = -binding.appBar.measuredHeight.toFloat()
}
else -> {
binding.appBar.translationY = (
mFirstCardMarginTop
- adapter!!.currentTemperatureTextHeight
- mScrollY
- binding.appBar.measuredHeight
).toFloat()
}
}
} else {
binding.appBar.translationY = -mScrollY.toFloat()
}
}
// set system bar style.
if (mFirstCardMarginTop <= 0) {
mTopChanged = true
topOverlap = false
} else {
mTopChanged = (binding.appBar.translationY != 0f) != (mLastAppBarTranslationY != 0f)
topOverlap = binding.appBar.translationY != 0f
}
if (mTopChanged!!) {
checkToSetSystemBarStyle()
}
}
}
} | lgpl-3.0 | 1d391fd61538af39bc2f9e252fa99163 | 33.407249 | 100 | 0.603929 | 6.023143 | false | false | false | false |
walleth/walleth | app/src/main/java/org/walleth/util/InputDialog.kt | 1 | 1096 | package org.walleth.util
import android.view.ViewGroup.LayoutParams.MATCH_PARENT
import android.view.ViewGroup.LayoutParams.WRAP_CONTENT
import android.widget.EditText
import android.widget.FrameLayout
import android.widget.LinearLayout
import androidx.annotation.StringRes
import androidx.appcompat.app.AlertDialog
import org.walleth.base_activities.BaseSubActivity
fun BaseSubActivity.showInputAlert(@StringRes title: Int, action : (input: String) -> Unit) {
val editText = EditText(this)
val container = FrameLayout(this)
val params = LinearLayout.LayoutParams(MATCH_PARENT, WRAP_CONTENT)
params.setMargins(16.toDp(), 0, 16.toDp(), 0)
editText.layoutParams = params
editText.isSingleLine = true
container.addView(editText)
AlertDialog.Builder(this)
.setTitle(title)
.setView(container)
.setPositiveButton(android.R.string.ok) { dialog, _ ->
dialog.cancel()
action(editText.text.toString())
}
.setNegativeButton(android.R.string.cancel, null)
.show()
}
| gpl-3.0 | a5e06f09c760df585ea1e058ef86455b | 34.354839 | 94 | 0.706204 | 4.419355 | false | false | false | false |
k0kubun/githubranking | worker/src/main/kotlin/com/github/k0kubun/gitstar_ranking/db/UserQuery.kt | 1 | 4754 | package com.github.k0kubun.gitstar_ranking.db
import com.github.k0kubun.gitstar_ranking.client.UserResponse
import com.github.k0kubun.gitstar_ranking.core.StarsCursor
import com.github.k0kubun.gitstar_ranking.core.User
import java.sql.Timestamp
import org.jooq.DSLContext
import org.jooq.Record
import org.jooq.RecordMapper
import org.jooq.impl.DSL.field
import org.jooq.impl.DSL.now
import org.jooq.impl.DSL.table
class UserQuery(private val database: DSLContext) {
private val userColumns = listOf(
field("id"),
field("type"),
field("login"),
field("stargazers_count"),
field("updated_at", Timestamp::class.java),
)
private val userMapper = RecordMapper<Record, User> { record ->
User(
id = record.get("id", Long::class.java),
type = record.get("type", String::class.java),
login = record.get("login", String::class.java),
stargazersCount = record.get("stargazers_count", Long::class.java),
updatedAt = record.get("updated_at", Timestamp::class.java),
)
}
fun find(id: Long): User? {
return database
.select(userColumns)
.from("users")
.where(field("id").eq(id))
.fetchOne(userMapper)
}
fun findBy(login: String): User? {
return database
.select(userColumns)
.from("users")
.where(field("login").eq(login))
.fetchOne(userMapper)
}
fun create(user: UserResponse) {
database
.insertInto(table("users"))
.columns(
field("id"),
field("type"),
field("login"),
field("avatar_url"),
field("created_at"),
field("updated_at"),
)
.values(
user.id,
user.type,
user.login,
user.avatarUrl,
now(), // created_at
now(), // updated_at
)
.execute()
}
fun update(id: Long, login: String? = null, stargazersCount: Long? = null) {
database
.update(table("users"))
.set(field("updated_at"), now())
.run {
if (login != null) {
set(field("login"), login)
} else this
}
.run {
if (stargazersCount != null) {
set(field("stargazers_count"), stargazersCount)
} else this
}
.where(field("id").eq(id))
.execute()
}
fun destroy(id: Long) {
database
.delete(table("users"))
.where(field("id").eq(id))
.execute()
}
fun count(stargazersCount: Long? = null): Long {
return database
.selectCount()
.from("users")
.where(field("type").eq("User"))
.run {
if (stargazersCount != null) {
and("stargazers_count = ?", stargazersCount)
} else this
}
.fetchOne(0, Long::class.java)!!
}
fun max(column: String): Long? {
return database
.select(field(column))
.from("users")
.orderBy(field(column).desc())
.limit(1)
.fetchOne(column, Long::class.java)
}
fun findStargazersCount(stargazersCountLessThan: Long): Long? {
return database
.select(field("stargazers_count"))
.from("users")
.where(field("stargazers_count").lessThan(stargazersCountLessThan))
.orderBy(field("stargazers_count").desc())
.limit(1)
.fetchOne("stargazers_count", Long::class.java)
}
fun orderByIdAsc(stargazersCount: Long, idAfter: Long, limit: Int): List<User> {
return database
.select(userColumns)
.from("users")
.where(field("stargazers_count").eq(stargazersCount))
.and(field("id").greaterThan(idAfter))
.orderBy(field("id").asc())
.limit(limit)
.fetch(userMapper)
}
fun orderByStarsDesc(limit: Int, after: StarsCursor? = null): List<User> {
return database
.select(userColumns)
.from("users")
.where(field("type").eq("User"))
.run {
if (after != null) {
and("(stargazers_count, id) < (?, ?)", after.stars, after.id)
} else this
}
.orderBy(field("stargazers_count").desc(), field("id").desc())
.limit(limit)
.fetch(userMapper)
}
}
| mit | 6e59d8306f2f8a6105f3fb324ef35374 | 30.071895 | 84 | 0.50589 | 4.393715 | false | false | false | false |
CarlosEsco/tachiyomi | app/src/main/java/eu/kanade/presentation/more/settings/widget/TrackingPreferenceWidget.kt | 1 | 2877 | package eu.kanade.presentation.more.settings.widget
import androidx.annotation.ColorInt
import androidx.annotation.DrawableRes
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Check
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.unit.dp
import eu.kanade.presentation.more.settings.LocalPreferenceHighlighted
@Composable
fun TrackingPreferenceWidget(
modifier: Modifier = Modifier,
title: String,
@DrawableRes logoRes: Int,
@ColorInt logoColor: Int,
checked: Boolean,
onClick: (() -> Unit)? = null,
) {
val highlighted = LocalPreferenceHighlighted.current
Box(modifier = Modifier.highlightBackground(highlighted)) {
Row(
modifier = modifier
.clickable(enabled = onClick != null, onClick = { onClick?.invoke() })
.fillMaxWidth()
.padding(horizontal = PrefsHorizontalPadding, vertical = 8.dp),
verticalAlignment = Alignment.CenterVertically,
) {
Box(
modifier = Modifier
.size(48.dp)
.background(color = Color(logoColor), shape = RoundedCornerShape(8.dp))
.padding(4.dp),
contentAlignment = Alignment.Center,
) {
Image(
painter = painterResource(id = logoRes),
contentDescription = null,
)
}
Text(
text = title,
modifier = Modifier
.weight(1f)
.padding(horizontal = 16.dp),
maxLines = 1,
style = MaterialTheme.typography.titleLarge,
fontSize = TitleFontSize,
)
if (checked) {
Icon(
imageVector = Icons.Default.Check,
modifier = Modifier
.padding(4.dp)
.size(32.dp),
tint = Color(0xFF4CAF50),
contentDescription = null,
)
}
}
}
}
| apache-2.0 | 61208b91a8965e4189e8d15bc42c5332 | 35.884615 | 91 | 0.623566 | 5.038529 | false | false | false | false |
CarlosEsco/tachiyomi | app/src/main/java/eu/kanade/tachiyomi/data/notification/Notifications.kt | 1 | 8187 | package eu.kanade.tachiyomi.data.notification
import android.content.Context
import androidx.core.app.NotificationManagerCompat
import androidx.core.app.NotificationManagerCompat.IMPORTANCE_DEFAULT
import androidx.core.app.NotificationManagerCompat.IMPORTANCE_HIGH
import androidx.core.app.NotificationManagerCompat.IMPORTANCE_LOW
import eu.kanade.tachiyomi.R
import eu.kanade.tachiyomi.util.system.buildNotificationChannel
import eu.kanade.tachiyomi.util.system.buildNotificationChannelGroup
/**
* Class to manage the basic information of all the notifications used in the app.
*/
object Notifications {
/**
* Common notification channel and ids used anywhere.
*/
const val CHANNEL_COMMON = "common_channel"
const val ID_DOWNLOAD_IMAGE = 2
/**
* Notification channel and ids used by the library updater.
*/
private const val GROUP_LIBRARY = "group_library"
const val CHANNEL_LIBRARY_PROGRESS = "library_progress_channel"
const val ID_LIBRARY_PROGRESS = -101
const val ID_LIBRARY_SIZE_WARNING = -103
const val CHANNEL_LIBRARY_ERROR = "library_errors_channel"
const val ID_LIBRARY_ERROR = -102
const val CHANNEL_LIBRARY_SKIPPED = "library_skipped_channel"
const val ID_LIBRARY_SKIPPED = -104
/**
* Notification channel and ids used by the downloader.
*/
private const val GROUP_DOWNLOADER = "group_downloader"
const val CHANNEL_DOWNLOADER_PROGRESS = "downloader_progress_channel"
const val ID_DOWNLOAD_CHAPTER_PROGRESS = -201
const val CHANNEL_DOWNLOADER_COMPLETE = "downloader_complete_channel"
const val ID_DOWNLOAD_CHAPTER_COMPLETE = -203
const val CHANNEL_DOWNLOADER_ERROR = "downloader_error_channel"
const val ID_DOWNLOAD_CHAPTER_ERROR = -202
/**
* Notification channel and ids used by the library updater.
*/
const val CHANNEL_NEW_CHAPTERS = "new_chapters_channel"
const val ID_NEW_CHAPTERS = -301
const val GROUP_NEW_CHAPTERS = "eu.kanade.tachiyomi.NEW_CHAPTERS"
/**
* Notification channel and ids used by the backup/restore system.
*/
private const val GROUP_BACKUP_RESTORE = "group_backup_restore"
const val CHANNEL_BACKUP_RESTORE_PROGRESS = "backup_restore_progress_channel"
const val ID_BACKUP_PROGRESS = -501
const val ID_RESTORE_PROGRESS = -503
const val CHANNEL_BACKUP_RESTORE_COMPLETE = "backup_restore_complete_channel_v2"
const val ID_BACKUP_COMPLETE = -502
const val ID_RESTORE_COMPLETE = -504
/**
* Notification channel used for crash log file sharing.
*/
const val CHANNEL_CRASH_LOGS = "crash_logs_channel"
const val ID_CRASH_LOGS = -601
/**
* Notification channel used for Incognito Mode
*/
const val CHANNEL_INCOGNITO_MODE = "incognito_mode_channel"
const val ID_INCOGNITO_MODE = -701
/**
* Notification channel and ids used for app and extension updates.
*/
private const val GROUP_APK_UPDATES = "group_apk_updates"
const val CHANNEL_APP_UPDATE = "app_apk_update_channel"
const val ID_APP_UPDATER = 1
const val ID_APP_UPDATE_PROMPT = 2
const val CHANNEL_EXTENSIONS_UPDATE = "ext_apk_update_channel"
const val ID_UPDATES_TO_EXTS = -401
const val ID_EXTENSION_INSTALLER = -402
private val deprecatedChannels = listOf(
"downloader_channel",
"backup_restore_complete_channel",
"library_channel",
"library_progress_channel",
"updates_ext_channel",
)
/**
* Creates the notification channels introduced in Android Oreo.
* This won't do anything on Android versions that don't support notification channels.
*
* @param context The application context.
*/
fun createChannels(context: Context) {
val notificationService = NotificationManagerCompat.from(context)
// Delete old notification channels
deprecatedChannels.forEach(notificationService::deleteNotificationChannel)
notificationService.createNotificationChannelGroupsCompat(
listOf(
buildNotificationChannelGroup(GROUP_BACKUP_RESTORE) {
setName(context.getString(R.string.label_backup))
},
buildNotificationChannelGroup(GROUP_DOWNLOADER) {
setName(context.getString(R.string.download_notifier_downloader_title))
},
buildNotificationChannelGroup(GROUP_LIBRARY) {
setName(context.getString(R.string.label_library))
},
buildNotificationChannelGroup(GROUP_APK_UPDATES) {
setName(context.getString(R.string.label_recent_updates))
},
),
)
notificationService.createNotificationChannelsCompat(
listOf(
buildNotificationChannel(CHANNEL_COMMON, IMPORTANCE_LOW) {
setName(context.getString(R.string.channel_common))
},
buildNotificationChannel(CHANNEL_LIBRARY_PROGRESS, IMPORTANCE_LOW) {
setName(context.getString(R.string.channel_progress))
setGroup(GROUP_LIBRARY)
setShowBadge(false)
},
buildNotificationChannel(CHANNEL_LIBRARY_ERROR, IMPORTANCE_LOW) {
setName(context.getString(R.string.channel_errors))
setGroup(GROUP_LIBRARY)
setShowBadge(false)
},
buildNotificationChannel(CHANNEL_LIBRARY_SKIPPED, IMPORTANCE_LOW) {
setName(context.getString(R.string.channel_skipped))
setGroup(GROUP_LIBRARY)
setShowBadge(false)
},
buildNotificationChannel(CHANNEL_NEW_CHAPTERS, IMPORTANCE_DEFAULT) {
setName(context.getString(R.string.channel_new_chapters))
},
buildNotificationChannel(CHANNEL_DOWNLOADER_PROGRESS, IMPORTANCE_LOW) {
setName(context.getString(R.string.channel_progress))
setGroup(GROUP_DOWNLOADER)
setShowBadge(false)
},
buildNotificationChannel(CHANNEL_DOWNLOADER_COMPLETE, IMPORTANCE_LOW) {
setName(context.getString(R.string.channel_complete))
setGroup(GROUP_DOWNLOADER)
setShowBadge(false)
},
buildNotificationChannel(CHANNEL_DOWNLOADER_ERROR, IMPORTANCE_LOW) {
setName(context.getString(R.string.channel_errors))
setGroup(GROUP_DOWNLOADER)
setShowBadge(false)
},
buildNotificationChannel(CHANNEL_BACKUP_RESTORE_PROGRESS, IMPORTANCE_LOW) {
setName(context.getString(R.string.channel_progress))
setGroup(GROUP_BACKUP_RESTORE)
setShowBadge(false)
},
buildNotificationChannel(CHANNEL_BACKUP_RESTORE_COMPLETE, IMPORTANCE_HIGH) {
setName(context.getString(R.string.channel_complete))
setGroup(GROUP_BACKUP_RESTORE)
setShowBadge(false)
setSound(null, null)
},
buildNotificationChannel(CHANNEL_CRASH_LOGS, IMPORTANCE_HIGH) {
setName(context.getString(R.string.channel_crash_logs))
},
buildNotificationChannel(CHANNEL_INCOGNITO_MODE, IMPORTANCE_LOW) {
setName(context.getString(R.string.pref_incognito_mode))
},
buildNotificationChannel(CHANNEL_APP_UPDATE, IMPORTANCE_DEFAULT) {
setGroup(GROUP_APK_UPDATES)
setName(context.getString(R.string.channel_app_updates))
},
buildNotificationChannel(CHANNEL_EXTENSIONS_UPDATE, IMPORTANCE_DEFAULT) {
setGroup(GROUP_APK_UPDATES)
setName(context.getString(R.string.channel_ext_updates))
},
),
)
}
}
| apache-2.0 | 9f4be8b2fa4faea436e0640e4fbbcb08 | 42.089474 | 92 | 0.630512 | 5.02887 | false | false | false | false |
CarlosEsco/tachiyomi | app/src/main/java/eu/kanade/tachiyomi/data/updater/AppUpdateService.kt | 1 | 6939 | package eu.kanade.tachiyomi.data.updater
import android.app.PendingIntent
import android.app.Service
import android.content.Context
import android.content.Intent
import android.os.IBinder
import android.os.PowerManager
import androidx.core.content.ContextCompat
import eu.kanade.tachiyomi.BuildConfig
import eu.kanade.tachiyomi.R
import eu.kanade.tachiyomi.data.notification.Notifications
import eu.kanade.tachiyomi.network.GET
import eu.kanade.tachiyomi.network.NetworkHelper
import eu.kanade.tachiyomi.network.ProgressListener
import eu.kanade.tachiyomi.network.await
import eu.kanade.tachiyomi.network.newCachelessCallWithProgress
import eu.kanade.tachiyomi.util.lang.launchIO
import eu.kanade.tachiyomi.util.storage.getUriCompat
import eu.kanade.tachiyomi.util.storage.saveTo
import eu.kanade.tachiyomi.util.system.acquireWakeLock
import eu.kanade.tachiyomi.util.system.isServiceRunning
import eu.kanade.tachiyomi.util.system.logcat
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.Job
import logcat.LogPriority
import okhttp3.Call
import okhttp3.internal.http2.ErrorCode
import okhttp3.internal.http2.StreamResetException
import uy.kohesive.injekt.injectLazy
import java.io.File
class AppUpdateService : Service() {
private val network: NetworkHelper by injectLazy()
/**
* Wake lock that will be held until the service is destroyed.
*/
private lateinit var wakeLock: PowerManager.WakeLock
private lateinit var notifier: AppUpdateNotifier
private var runningJob: Job? = null
private var runningCall: Call? = null
override fun onCreate() {
super.onCreate()
notifier = AppUpdateNotifier(this)
wakeLock = acquireWakeLock(javaClass.name)
startForeground(Notifications.ID_APP_UPDATER, notifier.onDownloadStarted().build())
}
/**
* This method needs to be implemented, but it's not used/needed.
*/
override fun onBind(intent: Intent): IBinder? = null
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
if (intent == null) return START_NOT_STICKY
val url = intent.getStringExtra(EXTRA_DOWNLOAD_URL) ?: return START_NOT_STICKY
val title = intent.getStringExtra(EXTRA_DOWNLOAD_TITLE) ?: getString(R.string.app_name)
runningJob = launchIO {
downloadApk(title, url)
}
runningJob?.invokeOnCompletion { stopSelf(startId) }
return START_NOT_STICKY
}
override fun stopService(name: Intent?): Boolean {
destroyJob()
return super.stopService(name)
}
override fun onDestroy() {
destroyJob()
super.onDestroy()
}
private fun destroyJob() {
runningJob?.cancel()
runningCall?.cancel()
if (wakeLock.isHeld) {
wakeLock.release()
}
}
/**
* Called to start downloading apk of new update
*
* @param url url location of file
*/
private suspend fun downloadApk(title: String, url: String) {
// Show notification download starting.
notifier.onDownloadStarted(title)
val progressListener = object : ProgressListener {
// Progress of the download
var savedProgress = 0
// Keep track of the last notification sent to avoid posting too many.
var lastTick = 0L
override fun update(bytesRead: Long, contentLength: Long, done: Boolean) {
val progress = (100 * (bytesRead.toFloat() / contentLength)).toInt()
val currentTime = System.currentTimeMillis()
if (progress > savedProgress && currentTime - 200 > lastTick) {
savedProgress = progress
lastTick = currentTime
notifier.onProgressChange(progress)
}
}
}
try {
// Download the new update.
val call = network.client.newCachelessCallWithProgress(GET(url), progressListener)
runningCall = call
val response = call.await()
// File where the apk will be saved.
val apkFile = File(externalCacheDir, "update.apk")
if (response.isSuccessful) {
response.body.source().saveTo(apkFile)
} else {
response.close()
throw Exception("Unsuccessful response")
}
notifier.promptInstall(apkFile.getUriCompat(this))
} catch (e: Exception) {
logcat(LogPriority.ERROR, e)
if (e is CancellationException ||
(e is StreamResetException && e.errorCode == ErrorCode.CANCEL)
) {
notifier.cancel()
} else {
notifier.onDownloadError(url)
}
}
}
companion object {
internal const val EXTRA_DOWNLOAD_URL = "${BuildConfig.APPLICATION_ID}.UpdaterService.DOWNLOAD_URL"
internal const val EXTRA_DOWNLOAD_TITLE = "${BuildConfig.APPLICATION_ID}.UpdaterService.DOWNLOAD_TITLE"
/**
* Returns the status of the service.
*
* @param context the application context.
* @return true if the service is running, false otherwise.
*/
private fun isRunning(context: Context): Boolean =
context.isServiceRunning(AppUpdateService::class.java)
/**
* Downloads a new update and let the user install the new version from a notification.
*
* @param context the application context.
* @param url the url to the new update.
*/
fun start(context: Context, url: String, title: String? = context.getString(R.string.app_name)) {
if (!isRunning(context)) {
val intent = Intent(context, AppUpdateService::class.java).apply {
putExtra(EXTRA_DOWNLOAD_TITLE, title)
putExtra(EXTRA_DOWNLOAD_URL, url)
}
ContextCompat.startForegroundService(context, intent)
}
}
/**
* Stops the service.
*
* @param context the application context
*/
fun stop(context: Context) {
context.stopService(Intent(context, AppUpdateService::class.java))
}
/**
* Returns [PendingIntent] that starts a service which downloads the apk specified in url.
*
* @param url the url to the new update.
* @return [PendingIntent]
*/
internal fun downloadApkPendingService(context: Context, url: String): PendingIntent {
val intent = Intent(context, AppUpdateService::class.java).apply {
putExtra(EXTRA_DOWNLOAD_URL, url)
}
return PendingIntent.getService(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE)
}
}
}
| apache-2.0 | 7bb608b835a055aecc749ec3fa3e23b8 | 33.695 | 130 | 0.637124 | 4.921277 | false | false | false | false |
CarlosEsco/tachiyomi | app/src/main/java/eu/kanade/tachiyomi/data/download/DownloadPendingDeleter.kt | 1 | 5694 | package eu.kanade.tachiyomi.data.download
import android.content.Context
import androidx.core.content.edit
import eu.kanade.domain.manga.model.Manga
import eu.kanade.tachiyomi.data.database.models.Chapter
import kotlinx.serialization.Serializable
import kotlinx.serialization.decodeFromString
import kotlinx.serialization.encodeToString
import kotlinx.serialization.json.Json
import uy.kohesive.injekt.injectLazy
/**
* Class used to keep a list of chapters for future deletion.
*
* @param context the application context.
*/
class DownloadPendingDeleter(context: Context) {
private val json: Json by injectLazy()
/**
* Preferences used to store the list of chapters to delete.
*/
private val preferences = context.getSharedPreferences("chapters_to_delete", Context.MODE_PRIVATE)
/**
* Last added chapter, used to avoid decoding from the preference too often.
*/
private var lastAddedEntry: Entry? = null
/**
* Adds a list of chapters for future deletion.
*
* @param chapters the chapters to be deleted.
* @param manga the manga of the chapters.
*/
@Synchronized
fun addChapters(chapters: List<Chapter>, manga: Manga) {
val lastEntry = lastAddedEntry
val newEntry = if (lastEntry != null && lastEntry.manga.id == manga.id) {
// Append new chapters
val newChapters = lastEntry.chapters.addUniqueById(chapters)
// If no chapters were added, do nothing
if (newChapters.size == lastEntry.chapters.size) return
// Last entry matches the manga, reuse it to avoid decoding json from preferences
lastEntry.copy(chapters = newChapters)
} else {
val existingEntry = preferences.getString(manga.id.toString(), null)
if (existingEntry != null) {
// Existing entry found on preferences, decode json and add the new chapter
val savedEntry = json.decodeFromString<Entry>(existingEntry)
// Append new chapters
val newChapters = savedEntry.chapters.addUniqueById(chapters)
// If no chapters were added, do nothing
if (newChapters.size == savedEntry.chapters.size) return
savedEntry.copy(chapters = newChapters)
} else {
// No entry has been found yet, create a new one
Entry(chapters.map { it.toEntry() }, manga.toEntry())
}
}
// Save current state
val json = json.encodeToString(newEntry)
preferences.edit {
putString(newEntry.manga.id.toString(), json)
}
lastAddedEntry = newEntry
}
/**
* Returns the list of chapters to be deleted grouped by its manga.
*
* Note: the returned list of manga and chapters only contain basic information needed by the
* downloader, so don't use them for anything else.
*/
@Synchronized
fun getPendingChapters(): Map<Manga, List<Chapter>> {
val entries = decodeAll()
preferences.edit {
clear()
}
lastAddedEntry = null
return entries.associate { (chapters, manga) ->
manga.toModel() to chapters.map { it.toModel() }
}
}
/**
* Decodes all the chapters from preferences.
*/
private fun decodeAll(): List<Entry> {
return preferences.all.values.mapNotNull { rawEntry ->
try {
(rawEntry as? String)?.let { json.decodeFromString<Entry>(it) }
} catch (e: Exception) {
null
}
}
}
/**
* Returns a copy of chapter entries ensuring no duplicates by chapter id.
*/
private fun List<ChapterEntry>.addUniqueById(chapters: List<Chapter>): List<ChapterEntry> {
val newList = toMutableList()
for (chapter in chapters) {
if (none { it.id == chapter.id }) {
newList.add(chapter.toEntry())
}
}
return newList
}
/**
* Class used to save an entry of chapters with their manga into preferences.
*/
@Serializable
private data class Entry(
val chapters: List<ChapterEntry>,
val manga: MangaEntry,
)
/**
* Class used to save an entry for a chapter into preferences.
*/
@Serializable
private data class ChapterEntry(
val id: Long,
val url: String,
val name: String,
val scanlator: String? = null,
)
/**
* Class used to save an entry for a manga into preferences.
*/
@Serializable
private data class MangaEntry(
val id: Long,
val url: String,
val title: String,
val source: Long,
)
/**
* Returns a manga entry from a manga model.
*/
private fun Manga.toEntry(): MangaEntry {
return MangaEntry(id, url, title, source)
}
/**
* Returns a chapter entry from a chapter model.
*/
private fun Chapter.toEntry(): ChapterEntry {
return ChapterEntry(id!!, url, name, scanlator)
}
/**
* Returns a manga model from a manga entry.
*/
private fun MangaEntry.toModel(): Manga {
return Manga.create().copy(
url = url,
title = title,
source = source,
id = id,
)
}
/**
* Returns a chapter model from a chapter entry.
*/
private fun ChapterEntry.toModel(): Chapter {
return Chapter.create().also {
it.id = id
it.url = url
it.name = name
it.scanlator = scanlator
}
}
}
| apache-2.0 | 97305b751d4896076a7dd6163249851e | 28.811518 | 102 | 0.597295 | 4.748957 | false | false | false | false |
Heiner1/AndroidAPS | database/src/main/java/info/nightscout/androidaps/database/daos/TraceableDao.kt | 1 | 2239 | package info.nightscout.androidaps.database.daos
import androidx.room.Insert
import androidx.room.Update
import info.nightscout.androidaps.database.daos.workaround.TraceableDaoWorkaround
import info.nightscout.androidaps.database.interfaces.TraceableDBEntry
internal interface TraceableDao<T : TraceableDBEntry> : TraceableDaoWorkaround<T> {
fun findById(id: Long): T?
fun deleteAllEntries()
//fun getAllStartingFrom(id: Long): Single<List<T>>
@Insert
fun insert(entry: T): Long
@Update
fun update(entry: T)
}
/**
* Inserts a new entry
* @return The ID of the newly generated entry
*/
//@Transaction
internal fun <T : TraceableDBEntry> TraceableDao<T>.insertNewEntryImpl(entry: T): Long {
if (entry.id != 0L) throw IllegalArgumentException("ID must be 0.")
if (entry.version != 0) throw IllegalArgumentException("Version must be 0.")
if (entry.referenceId != null) throw IllegalArgumentException("Reference ID must be null.")
if (!entry.foreignKeysValid) throw IllegalArgumentException("One or more foreign keys are invalid (e.g. 0 value).")
val lastModified = System.currentTimeMillis()
entry.dateCreated = lastModified
val id = insert(entry)
entry.id = id
return id
}
/**
* Updates an existing entry
* @return The ID of the newly generated HISTORIC entry
*/
//@Transaction
internal fun <T : TraceableDBEntry> TraceableDao<T>.updateExistingEntryImpl(entry: T): Long {
if (entry.id == 0L) throw IllegalArgumentException("ID must not be 0.")
if (entry.referenceId != null) throw IllegalArgumentException("Reference ID must be null.")
if (!entry.foreignKeysValid) throw IllegalArgumentException("One or more foreign keys are invalid (e.g. 0 value).")
val lastModified = System.currentTimeMillis()
entry.dateCreated = lastModified
val current = findById(entry.id)
?: throw IllegalArgumentException("The entry with the specified ID does not exist.")
if (current.referenceId != null) throw IllegalArgumentException("The entry with the specified ID is historic and cannot be updated.")
entry.version = current.version + 1
update(entry)
current.referenceId = entry.id
current.id = 0
return insert(current)
} | agpl-3.0 | 1b87bb56216116506b0922c1073c800c | 36.966102 | 137 | 0.732023 | 4.424901 | false | false | false | false |
MaTriXy/material-dialogs | core/src/main/java/com/afollestad/materialdialogs/internal/main/DialogTitleLayout.kt | 2 | 5398 | /**
* Designed and developed by Aidan Follestad (@afollestad)
*
* 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.afollestad.materialdialogs.internal.main
import android.content.Context
import android.graphics.Canvas
import android.util.AttributeSet
import android.view.View.MeasureSpec.AT_MOST
import android.view.View.MeasureSpec.EXACTLY
import android.view.View.MeasureSpec.UNSPECIFIED
import android.view.View.MeasureSpec.getSize
import android.view.View.MeasureSpec.makeMeasureSpec
import android.widget.ImageView
import android.widget.TextView
import androidx.annotation.RestrictTo
import androidx.annotation.RestrictTo.Scope.LIBRARY_GROUP
import com.afollestad.materialdialogs.R
import com.afollestad.materialdialogs.utils.MDUtil.additionalPaddingForFont
import com.afollestad.materialdialogs.utils.MDUtil.dimenPx
import com.afollestad.materialdialogs.utils.isNotVisible
import com.afollestad.materialdialogs.utils.isRtl
import com.afollestad.materialdialogs.utils.isVisible
/**
* Manages the header frame of the dialog, including the optional icon and title.
*
* @author Aidan Follestad (afollestad)
*/
@RestrictTo(LIBRARY_GROUP)
class DialogTitleLayout(
context: Context,
attrs: AttributeSet? = null
) : BaseSubLayout(context, attrs) {
private val frameMarginVertical = dimenPx(R.dimen.md_dialog_frame_margin_vertical)
private val titleMarginBottom = dimenPx(R.dimen.md_dialog_title_layout_margin_bottom)
private val frameMarginHorizontal = dimenPx(R.dimen.md_dialog_frame_margin_horizontal)
private val iconMargin = dimenPx(R.dimen.md_icon_margin)
private val iconSize = dimenPx(R.dimen.md_icon_size)
internal lateinit var iconView: ImageView
internal lateinit var titleView: TextView
override fun onFinishInflate() {
super.onFinishInflate()
iconView = findViewById(R.id.md_icon_title)
titleView = findViewById(R.id.md_text_title)
}
fun shouldNotBeVisible() = iconView.isNotVisible() && titleView.isNotVisible()
override fun onMeasure(
widthMeasureSpec: Int,
heightMeasureSpec: Int
) {
if (shouldNotBeVisible()) {
setMeasuredDimension(0, 0)
return
}
val parentWidth = getSize(widthMeasureSpec)
var titleMaxWidth = parentWidth - (frameMarginHorizontal * 2)
if (iconView.isVisible()) {
iconView.measure(
makeMeasureSpec(iconSize, EXACTLY),
makeMeasureSpec(iconSize, EXACTLY)
)
titleMaxWidth -= (iconView.measuredWidth + iconMargin)
}
titleView.measure(
makeMeasureSpec(titleMaxWidth, AT_MOST),
makeMeasureSpec(0, UNSPECIFIED)
)
val iconViewHeight = if (iconView.isVisible()) iconView.measuredHeight else 0
val requiredHeight = iconViewHeight.coerceAtLeast(titleView.measuredHeight)
val actualHeight = requiredHeight + frameMarginVertical + titleMarginBottom
setMeasuredDimension(parentWidth, actualHeight)
}
override fun onLayout(
changed: Boolean,
left: Int,
top: Int,
right: Int,
bottom: Int
) {
if (shouldNotBeVisible()) return
val contentTop = frameMarginVertical
val contentBottom = measuredHeight - titleMarginBottom
val contentHeight = contentBottom - contentTop
val contentMidPoint = contentBottom - (contentHeight / 2)
val titleHalfHeight = titleView.measuredHeight / 2
val titleTop = contentMidPoint - titleHalfHeight
val titleBottom = contentMidPoint + titleHalfHeight +
titleView.additionalPaddingForFont()
var titleLeft: Int
var titleRight: Int
if (isRtl()) {
titleRight = measuredWidth - frameMarginHorizontal
titleLeft = titleRight - titleView.measuredWidth
} else {
titleLeft = frameMarginHorizontal
titleRight = titleLeft + titleView.measuredWidth
}
if (iconView.isVisible()) {
val iconHalfHeight = iconView.measuredHeight / 2
val iconTop = contentMidPoint - iconHalfHeight
val iconBottom = contentMidPoint + iconHalfHeight
val iconLeft: Int
val iconRight: Int
if (isRtl()) {
iconRight = titleRight
iconLeft = iconRight - iconView.measuredWidth
titleRight = iconLeft - iconMargin
titleLeft = titleRight - titleView.measuredWidth
} else {
iconLeft = titleLeft
iconRight = iconLeft + iconView.measuredWidth
titleLeft = iconRight + iconMargin
titleRight = titleLeft + titleView.measuredWidth
}
iconView.layout(iconLeft, iconTop, iconRight, iconBottom)
}
titleView.layout(titleLeft, titleTop, titleRight, titleBottom)
}
override fun onDraw(canvas: Canvas) {
super.onDraw(canvas)
if (drawDivider) {
canvas.drawLine(
0f,
measuredHeight.toFloat() - dividerHeight.toFloat(),
measuredWidth.toFloat(),
measuredHeight.toFloat(),
dividerPaint()
)
}
}
}
| apache-2.0 | 46a8c7567ce88565e63c4be4a2a808d7 | 31.715152 | 88 | 0.729715 | 4.760141 | false | false | false | false |
hurricup/intellij-community | plugins/settings-repository/testSrc/IcsCredentialTest.kt | 1 | 2505 | package org.jetbrains.settingsRepository
import com.intellij.credentialStore.Credentials
import com.intellij.testFramework.ApplicationRule
import org.assertj.core.api.Assertions.assertThat
import org.eclipse.jgit.storage.file.FileRepositoryBuilder
import org.eclipse.jgit.transport.CredentialItem
import org.eclipse.jgit.transport.URIish
import org.jetbrains.settingsRepository.git.JGitCredentialsProvider
import org.junit.ClassRule
import org.junit.Test
import java.io.File
internal class IcsCredentialTest {
companion object {
@JvmField
@ClassRule
val projectRule = ApplicationRule()
}
private fun createProvider(credentialsStore: IcsCredentialsStore): JGitCredentialsProvider {
return JGitCredentialsProvider(lazyOf(credentialsStore), FileRepositoryBuilder().setBare().setGitDir(File("/tmp/fake")).build())
}
private fun createStore() = IcsCredentialsStore()
@Test
fun explicitSpecifiedInURL() {
val credentialsStore = createStore()
val username = CredentialItem.Username()
val password = CredentialItem.Password()
val uri = URIish("https://develar:[email protected]/develar/settings-repository.git")
assertThat(createProvider(credentialsStore).get(uri, username, password)).isTrue()
assertThat(username.value).isEqualTo("develar")
assertThat(String(password.value!!)).isEqualTo("bike")
// ensure that credentials store was not used
assertThat(credentialsStore.get(uri.host, null, null)).isNull()
}
@Test
fun gitCredentialHelper() {
val credentialStore = createStore()
credentialStore.set("bitbucket.org", null, Credentials("develar", "bike"))
val username = CredentialItem.Username()
val password = CredentialItem.Password()
val uri = URIish("https://[email protected]/develar/test-ics.git")
assertThat(createProvider(credentialStore).get(uri, username, password)).isTrue()
assertThat(username.value).isEqualTo("develar")
assertThat(String(password.value!!)).isNotEmpty()
}
@Test
fun userByServiceName() {
val credentialStore = createStore()
credentialStore.set("bitbucket.org", null, Credentials("develar", "bike"))
val username = CredentialItem.Username()
val password = CredentialItem.Password()
val uri = URIish("https://bitbucket.org/develar/test-ics.git")
assertThat(createProvider(credentialStore).get(uri, username, password)).isTrue()
assertThat(username.value).isEqualTo("develar")
assertThat(String(password.value!!)).isNotEmpty()
}
}
| apache-2.0 | 9b0fda7f61be9717b76375940a3177ed | 37.538462 | 132 | 0.758483 | 4.664804 | false | true | false | false |
grpc/grpc-kotlin | examples/server/src/test/kotlin/io/grpc/examples/helloworld/HelloWorldServerTest.kt | 1 | 1316 | /*
* Copyright 2022 gRPC 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 io.grpc.examples.helloworld
import io.grpc.testing.GrpcServerRule
import kotlinx.coroutines.runBlocking
import org.junit.Rule
import kotlin.test.Test
import kotlin.test.assertEquals
class HelloWorldServerTest {
@get:Rule
val grpcServerRule: GrpcServerRule = GrpcServerRule().directExecutor()
@Test
fun sayHello() = runBlocking {
val service = HelloWorldServer.HelloWorldService()
grpcServerRule.serviceRegistry.addService(service)
val stub = GreeterGrpcKt.GreeterCoroutineStub(grpcServerRule.channel)
val testName = "test name"
val reply = stub.sayHello(helloRequest { name = testName })
assertEquals("Hello $testName", reply.message)
}
}
| apache-2.0 | 1eb9a6b0da9b2a60d1761d17ca63b8b7 | 30.333333 | 77 | 0.737842 | 4.401338 | false | true | false | false |
k9mail/k-9 | app/storage/src/main/java/com/fsck/k9/storage/migrations/MigrationTo82.kt | 2 | 982 | package com.fsck.k9.storage.migrations
import android.database.sqlite.SQLiteDatabase
/**
* Add 'new_message' column to 'messages' table.
*/
internal class MigrationTo82(private val db: SQLiteDatabase) {
fun addNewMessageColumn() {
db.execSQL("ALTER TABLE messages ADD new_message INTEGER DEFAULT 0")
db.execSQL("DROP INDEX IF EXISTS new_messages")
db.execSQL("CREATE INDEX IF NOT EXISTS new_messages ON messages(new_message)")
db.execSQL(
"CREATE TRIGGER new_message_reset " +
"AFTER UPDATE OF read ON messages " +
"FOR EACH ROW WHEN NEW.read = 1 AND NEW.new_message = 1 " +
"BEGIN " +
"UPDATE messages SET new_message = 0 WHERE ROWID = NEW.ROWID; " +
"END"
)
// Mark messages with existing notifications as "new"
db.execSQL("UPDATE messages SET new_message = 1 WHERE id in (SELECT message_id FROM notifications)")
}
}
| apache-2.0 | 0194c47047080011c9d5a4f0f9c31752 | 35.37037 | 108 | 0.624236 | 4.269565 | false | false | false | false |
Maccimo/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/move/moveDeclarations/ui/KotlinSelectNestedClassRefactoringDialog.kt | 2 | 5041 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.idea.refactoring.move.moveDeclarations.ui
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.DialogWrapper
import com.intellij.psi.PsiDirectory
import com.intellij.psi.PsiElement
import com.intellij.refactoring.RefactoringBundle
import com.intellij.refactoring.util.RadioUpDownListener
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.psi.KtClass
import org.jetbrains.kotlin.psi.KtClassOrObject
import org.jetbrains.kotlin.psi.KtEnumEntry
import org.jetbrains.kotlin.psi.psiUtil.containingClassOrObject
import java.awt.BorderLayout
import javax.swing.*
internal class KotlinSelectNestedClassRefactoringDialog private constructor(
project: Project,
private val nestedClass: KtClassOrObject,
private val targetContainer: PsiElement?
) : DialogWrapper(project, true) {
private val moveToUpperLevelButton = JRadioButton()
private val moveMembersButton = JRadioButton()
init {
title = RefactoringBundle.message("select.refactoring.title")
init()
}
override fun createNorthPanel() = JLabel(RefactoringBundle.message("what.would.you.like.to.do"))
override fun getPreferredFocusedComponent() = moveToUpperLevelButton
override fun getDimensionServiceKey(): String {
return "#org.jetbrains.kotlin.idea.refactoring.move.moveTopLevelDeclarations.ui.KotlinSelectInnerOrMembersRefactoringDialog"
}
override fun createCenterPanel(): JComponent {
moveToUpperLevelButton.text = KotlinBundle.message("button.text.move.nested.class.0.to.upper.level", nestedClass.name.toString())
moveToUpperLevelButton.isSelected = true
moveMembersButton.text = KotlinBundle.message("button.text.move.nested.class.0.to.another.class", nestedClass.name.toString())
ButtonGroup().apply {
add(moveToUpperLevelButton)
add(moveMembersButton)
}
RadioUpDownListener(moveToUpperLevelButton, moveMembersButton)
return JPanel(BorderLayout()).apply {
val box = Box.createVerticalBox().apply {
add(Box.createVerticalStrut(5))
add(moveToUpperLevelButton)
add(moveMembersButton)
}
add(box, BorderLayout.CENTER)
}
}
fun getNextDialog(): DialogWrapper? {
return when {
moveToUpperLevelButton.isSelected -> MoveKotlinNestedClassesToUpperLevelDialog(nestedClass, targetContainer)
moveMembersButton.isSelected -> MoveKotlinNestedClassesDialog(nestedClass, targetContainer)
else -> null
}
}
companion object {
private fun MoveKotlinNestedClassesToUpperLevelDialog(
nestedClass: KtClassOrObject,
targetContainer: PsiElement?
): MoveKotlinNestedClassesToUpperLevelDialog? {
val outerClass = nestedClass.containingClassOrObject ?: return null
val newTarget = targetContainer
?: outerClass.containingClassOrObject
?: outerClass.containingFile.let { it.containingDirectory ?: it }
return MoveKotlinNestedClassesToUpperLevelDialog(nestedClass.project, nestedClass, newTarget)
}
private fun MoveKotlinNestedClassesDialog(
nestedClass: KtClassOrObject,
targetContainer: PsiElement?
): MoveKotlinNestedClassesDialog {
return MoveKotlinNestedClassesDialog(
nestedClass.project,
listOf(nestedClass),
nestedClass.containingClassOrObject!!,
targetContainer as? KtClassOrObject ?: nestedClass.containingClassOrObject!!,
targetContainer as? PsiDirectory,
null
)
}
fun chooseNestedClassRefactoring(nestedClass: KtClassOrObject, targetContainer: PsiElement?) {
val project = nestedClass.project
val dialog = when {
targetContainer.isUpperLevelFor(nestedClass) -> MoveKotlinNestedClassesToUpperLevelDialog(nestedClass, targetContainer)
nestedClass is KtEnumEntry -> return
else -> {
val selectionDialog =
KotlinSelectNestedClassRefactoringDialog(
project,
nestedClass,
targetContainer
)
selectionDialog.show()
if (selectionDialog.exitCode != OK_EXIT_CODE) return
selectionDialog.getNextDialog() ?: return
}
}
dialog?.show()
}
private fun PsiElement?.isUpperLevelFor(nestedClass: KtClassOrObject) =
this != null && this !is KtClassOrObject && this !is PsiDirectory ||
nestedClass is KtClass && nestedClass.isInner()
}
} | apache-2.0 | c8d83951262f822ba12a09074a1f82f6 | 40.669421 | 137 | 0.669708 | 6.208128 | false | false | false | false |
Hexworks/zircon | zircon.core/src/commonMain/kotlin/org/hexworks/zircon/api/builder/fragment/TableColumnBuilder.kt | 1 | 1987 | package org.hexworks.zircon.api.builder.fragment
import org.hexworks.zircon.api.Beta
import org.hexworks.zircon.api.component.Component
import org.hexworks.zircon.api.data.Position
import org.hexworks.zircon.api.fragment.builder.FragmentBuilder
import org.hexworks.zircon.internal.dsl.ZirconDsl
import org.hexworks.zircon.internal.fragment.impl.TableColumn
import kotlin.jvm.JvmStatic
@ZirconDsl
@Beta
class TableColumnBuilder<T : Any, V : Any, C : Component> private constructor(
/**
* The name of this column. It will be used as table header.
*/
var name: String = "",
/**
* The width of this column. The component created by [cellRenderer]
* may not be wider than this.
*/
var width: Int = 0,
/**
* This function will be used to extract the column value out of the
* table model object
*/
var valueProvider: ((T) -> V)? = null,
/**
* This function will be used to create a component to display the
* cell.
*/
var cellRenderer: ((V) -> C)? = null
) : FragmentBuilder<TableColumn<T, V, C>, TableColumnBuilder<T, V, C>> {
override fun build(): TableColumn<T, V, C> {
require(width > 0) {
"The minimum column width is 1. $width was provided."
}
return TableColumn(
name = name,
width = width,
valueProvider = valueProvider ?: error("Value provider is missing"),
cellRenderer = cellRenderer ?: error("Cell renderer is missing")
)
}
companion object {
@JvmStatic
fun <T : Any, V : Any, C : Component> newBuilder() = TableColumnBuilder<T, V, C>()
}
override fun createCopy() = TableColumnBuilder(
name = name,
width = width,
valueProvider = valueProvider,
cellRenderer = cellRenderer
)
override fun withPosition(position: Position): TableColumnBuilder<T, V, C> {
error("Can't set the position of a table column")
}
}
| apache-2.0 | a631ee5eb790ab7a81424d092b52eeb2 | 30.539683 | 90 | 0.636638 | 4.282328 | false | false | false | false |
kittttttan/pe | kt/pe/src/main/kotlin/ktn/pe/Pe9.kt | 1 | 749 | package ktn.pe
class Pe9 : Pe {
private var limit = 1000
override val problemNumber: Int
get() = 9
fun pe9(limit: Int): Int {
val last = (limit shr 1) + 1
for (x in 1 until last) {
val x2 = x * x
for (y in x until last) {
val z = limit - x - y
if (x2 + y * y == z * z) {
return x * y * z
}
}
}
return 0
}
override fun setArgs(args: Array<String>) {
if (args.isNotEmpty()) {
limit = args[0].toInt()
}
}
override fun solve() {
System.out.println(PeUtils.format(this, pe9(limit)))
}
override fun run() {
solve()
}
}
| mit | dd03c9f31bfd028b738fca347999a3d2 | 18.710526 | 60 | 0.427236 | 3.782828 | false | false | false | false |
wordpress-mobile/WordPress-Android | WordPress/src/main/java/org/wordpress/android/ui/photopicker/MediaPickerConstants.kt | 1 | 685 | package org.wordpress.android.ui.photopicker
object MediaPickerConstants {
const val EXTRA_MEDIA_URIS = "media_uris"
const val EXTRA_MEDIA_QUEUED_URIS = "queued_media_uris"
const val EXTRA_MEDIA_ID = "media_id"
const val EXTRA_LAUNCH_WPSTORIES_CAMERA_REQUESTED = "launch_wpstories_camera_requested"
const val EXTRA_LAUNCH_WPSTORIES_MEDIA_PICKER_REQUESTED = "launch_wpstories_media_picker_requested"
const val EXTRA_SAVED_MEDIA_MODEL_LOCAL_IDS = "saved_media_model_local_ids"
// the enum name of the source will be returned as a string in EXTRA_MEDIA_SOURCE
const val EXTRA_MEDIA_SOURCE = "media_source"
const val LOCAL_POST_ID = "local_post_id"
}
| gpl-2.0 | 08a84c2d2b3d68372de7325a02fa9d50 | 47.928571 | 103 | 0.743066 | 3.530928 | false | false | false | false |
kelsos/mbrc | changelog/src/main/java/com/kelsos/mbrc/changelog/VersionAdapter.kt | 1 | 3109 | package com.kelsos.mbrc.changelog
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.core.text.HtmlCompat
import androidx.core.text.HtmlCompat.FROM_HTML_MODE_LEGACY
import androidx.core.text.HtmlCompat.TO_HTML_PARAGRAPH_LINES_CONSECUTIVE
import androidx.recyclerview.widget.RecyclerView
class VersionAdapter(private val changeLog: List<ChangeLogEntry>) :
RecyclerView.Adapter<RecyclerView.ViewHolder>() {
class VersionViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
private val version: TextView = itemView.findViewById(R.id.changelog_version__version)
private val release: TextView = itemView.findViewById(R.id.changelog_version__release)
fun bind(version: ChangeLogEntry.Version) {
this.version.text = version.version
this.release.text = version.release
}
companion object {
fun from(parent: ViewGroup): VersionViewHolder {
val inflater = LayoutInflater.from(parent.context)
val itemView = inflater.inflate(R.layout.changelog_dialog__header, parent, false)
return VersionViewHolder(itemView)
}
}
}
class EntryViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
private val text: TextView = itemView.findViewById(R.id.changelog_entry__text)
private val type: TextView = itemView.findViewById(R.id.changelog_entry__type)
fun bind(entry: ChangeLogEntry.Entry) {
val typeResId = when (entry.type) {
is EntryType.BUG -> R.string.entry__bug
is EntryType.FEATURE -> R.string.entry__feature
is EntryType.REMOVED -> R.string.entry__removed
}
type.setText(typeResId)
text.text = HtmlCompat.fromHtml(entry.text, FROM_HTML_MODE_LEGACY)
}
companion object {
fun from(parent: ViewGroup): EntryViewHolder {
val inflater = LayoutInflater.from(parent.context)
val itemView = inflater.inflate(R.layout.changelog_dialog__entry, parent, false)
return EntryViewHolder(itemView)
}
}
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
return when (viewType) {
ITEM_VIEW_TYPE_HEADER -> VersionViewHolder.from(parent)
ITEM_VIEW_TYPE_ITEM -> EntryViewHolder.from(parent)
else -> throw ClassCastException("Unknown viewType $viewType")
}
}
override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
val version = changeLog[position]
when (holder) {
is VersionViewHolder -> holder.bind(version as ChangeLogEntry.Version)
is EntryViewHolder -> holder.bind(version as ChangeLogEntry.Entry)
}
}
override fun getItemViewType(position: Int): Int {
return when (changeLog[position]) {
is ChangeLogEntry.Version -> ITEM_VIEW_TYPE_HEADER
is ChangeLogEntry.Entry -> ITEM_VIEW_TYPE_ITEM
}
}
override fun getItemCount(): Int {
return changeLog.size
}
companion object {
private const val ITEM_VIEW_TYPE_HEADER = 0
private const val ITEM_VIEW_TYPE_ITEM = 1
}
}
| gpl-3.0 | 75e4feafda829a850581340be88e63b1 | 34.329545 | 94 | 0.719524 | 4.354342 | false | false | false | false |
mdaniel/intellij-community | plugins/kotlin/gradle/gradle/src/org/jetbrains/kotlin/idea/gradle/configuration/klib/KlibManifestProvider.kt | 5 | 4334 | // 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.gradle.configuration.klib
import com.intellij.util.containers.orNull
import com.intellij.util.io.isFile
import org.jetbrains.kotlin.library.KLIB_MANIFEST_FILE_NAME
import java.io.IOException
import java.nio.file.Files
import java.nio.file.Path
import java.util.*
import java.util.zip.ZipEntry
import java.util.zip.ZipFile
internal fun interface KlibManifestProvider {
fun getManifest(libraryPath: Path): Properties?
companion object {
fun default(): KlibManifestProvider {
return CachedKlibManifestProvider(
cache = mutableMapOf(),
provider = CompositeKlibManifestProvider(
listOf(DirectoryKlibManifestProvider(), ZipKlibManifestProvider)
)
)
}
}
}
internal interface KlibManifestFileFinder {
fun getManifestFile(libraryPath: Path): Path?
}
internal class CompositeKlibManifestProvider(
private val providers: List<KlibManifestProvider>
) : KlibManifestProvider {
override fun getManifest(libraryPath: Path): Properties? {
return providers.asSequence()
.map { it.getManifest(libraryPath) }
.filterNotNull()
.firstOrNull()
}
}
internal class CachedKlibManifestProvider(
private val cache: MutableMap<Path, Properties> = mutableMapOf(),
private val provider: KlibManifestProvider
) : KlibManifestProvider {
override fun getManifest(libraryPath: Path): Properties? {
return cache.getOrPut(libraryPath) {
provider.getManifest(libraryPath) ?: return null
}
}
}
internal class DirectoryKlibManifestProvider(
private val manifestFileFinder: KlibManifestFileFinder = DefaultKlibManifestFileFinder,
) : KlibManifestProvider {
override fun getManifest(libraryPath: Path): Properties? {
val file = manifestFileFinder.getManifestFile(libraryPath) ?: return null
val properties = Properties()
try {
Files.newInputStream(file).use { properties.load(it) }
return properties
} catch (_: IOException) {
return null
}
}
}
internal object ZipKlibManifestProvider : KlibManifestProvider {
private val manifestEntryRegex = Regex("""(.+/manifest|manifest)""")
override fun getManifest(libraryPath: Path): Properties? {
if (!libraryPath.isFile()) return null
try {
val properties = Properties()
val zipFile = ZipFile(libraryPath.toFile())
zipFile.use {
val manifestEntry = zipFile.findManifestEntry() ?: return null
zipFile.getInputStream(manifestEntry).use { manifestStream ->
properties.load(manifestStream)
}
}
return properties
} catch (_: Exception) {
return null
}
}
private fun ZipFile.findManifestEntry(): ZipEntry? {
return this.stream().filter { entry -> entry.name.matches(manifestEntryRegex) }.findFirst().orNull()
}
}
private object DefaultKlibManifestFileFinder : KlibManifestFileFinder {
override fun getManifestFile(libraryPath: Path): Path? {
libraryPath.resolve(KLIB_MANIFEST_FILE_NAME).let { propertiesPath ->
// KLIB layout without components
if (Files.isRegularFile(propertiesPath)) return propertiesPath
}
if (!Files.isDirectory(libraryPath)) return null
// look up through all components and find all manifest files
val candidates = Files.newDirectoryStream(libraryPath).use { stream ->
stream.mapNotNull { componentPath ->
val candidate = componentPath.resolve(KLIB_MANIFEST_FILE_NAME)
if (Files.isRegularFile(candidate)) candidate else null
}
}
return when (candidates.size) {
0 -> null
1 -> candidates.single()
else -> {
// there are multiple components, let's take just the first one alphabetically
candidates.minByOrNull { it.getName(it.nameCount - 2).toString() }!!
}
}
}
}
| apache-2.0 | 4bca6d36d8267b3668cef4c34c7be033 | 33.951613 | 158 | 0.65413 | 5.227986 | false | false | false | false |
ingokegel/intellij-community | plugins/kotlin/performance-tests/test/org/jetbrains/kotlin/idea/perf/synthetic/PerformanceStressTest.kt | 1 | 13862 | // 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.perf.synthetic
import com.intellij.testFramework.UsefulTestCase
import com.intellij.usages.Usage
import org.jetbrains.kotlin.idea.testFramework.Parameter
import org.jetbrains.kotlin.idea.perf.profilers.ProfilerConfig
import org.jetbrains.kotlin.idea.perf.suite.DefaultProfile
import org.jetbrains.kotlin.idea.perf.suite.PerformanceSuite
import org.jetbrains.kotlin.idea.perf.suite.StatsScopeConfig
import org.jetbrains.kotlin.idea.perf.suite.suite
import org.jetbrains.kotlin.idea.perf.util.*
import org.jetbrains.kotlin.idea.perf.util.registerLoadingErrorsHeadlessNotifier
import org.jetbrains.kotlin.idea.test.JUnit3RunnerWithInners
import org.junit.runner.RunWith
@RunWith(JUnit3RunnerWithInners::class)
open class PerformanceStressTest : UsefulTestCase() {
protected open fun profileConfig(): ProfilerConfig = ProfilerConfig()
protected open fun outputConfig(): OutputConfig = OutputConfig()
protected open fun suiteWithConfig(suiteName: String, name: String? = null, block: PerformanceSuite.StatsScope.() -> Unit) {
suite(
suiteName,
config = StatsScopeConfig(name = name, outputConfig = outputConfig(), profilerConfig = profileConfig()),
block = block
)
}
override fun setUp() {
super.setUp()
testRootDisposable.registerLoadingErrorsHeadlessNotifier()
}
fun testFindUsages() = doFindUsagesTest(false)
fun testFindUsagesWithCompilerReferenceIndex() = doFindUsagesTest(true)
private fun doFindUsagesTest(withCompilerIndex: Boolean) {
// 1. Create 2 classes with the same name, but in a different packages
// 2. Create 50 packages with a class that uses 50 times one of class from p.1
// 3. Use one of the classes from p.1 in the only one class at p.2
// 4. Run find usages of class that has limited usages
//
// Find usages have to resolve each reference due to the fact they have same names
val numberOfFuns = 50
for (numberOfPackagesWithCandidates in arrayOf(30, 50, 100)) {
val name = "findUsages${numberOfFuns}_$numberOfPackagesWithCandidates" + if (withCompilerIndex) "_with_cri" else ""
suiteWithConfig(name) {
app {
warmUpProject()
project {
descriptor {
name(name)
module {
kotlinStandardLibrary()
for (index in 1..2) {
kotlinFile("DataClass") {
pkg("pkg$index")
topClass("DataClass") {
dataClass()
ctorParameter(Parameter("name", "String"))
ctorParameter(Parameter("value", "Int"))
}
}
}
for (pkgIndex in 1..numberOfPackagesWithCandidates) {
kotlinFile("SomeService") {
pkg("pkgX$pkgIndex")
// use pkg1 for `pkgX1.SomeService`, and pkg2 for all other `pkgX*.SomeService`
import("pkg${if (pkgIndex == 1) 1 else 2}.DataClass")
topClass("SomeService") {
for (index in 1..numberOfFuns) {
function("foo$index") {
returnType("DataClass")
param("data", "DataClass")
body("return DataClass(data.name, data.value + $index)")
}
}
}
}
}
}
}
profile(DefaultProfile)
if (withCompilerIndex) {
withCompiler()
rebuildProject()
}
fixture("pkg1/DataClass.kt").use { fixture ->
with(fixture.cursorConfig) { marker = "DataClass" }
with(config) {
warmup = 8
iterations = 15
}
measure<Set<Usage>>(fixture, "findUsages") {
before = {
fixture.moveCursor()
}
test = {
val findUsages = findUsages(fixture.cursorConfig)
// 1 from import
// + numberOfUsages as function argument
// + numberOfUsages as return type functions
// + numberOfUsages as new instance in a body of function
// in a SomeService
assertEquals(1 + 3 * numberOfFuns, findUsages.size)
findUsages
}
}
}
}
}
}
}
}
fun testBaseClassAndLotsOfSubClasses() {
// there is a base class with several open functions
// and lots of subclasses of it
// KTIJ-21027
suiteWithConfig("Base class and lots of subclasses project", "ktij-21027 project") {
app {
warmUpProject()
project {
descriptor {
name("ktij-21027")
val baseClassFunctionNames = (0..10).map { "foo$it" }
module {
kotlinStandardLibrary()
src("src/main/java/")
kotlinFile("BaseClass") {
pkg("pkg")
topClass("BaseClass") {
openClass()
for (fnName in baseClassFunctionNames) {
function(fnName) {
openFunction()
returnType("String")
body("TODO()")
}
}
}
}
for (classIndex in 0..5) {
val superClassName = "SomeClass$classIndex"
kotlinFile(superClassName) {
pkg("pkg")
topClass(superClassName) {
openClass()
superClass("BaseClass")
for (fnName in baseClassFunctionNames) {
function(fnName) {
overrideFunction()
returnType("String")
body("TODO()")
}
}
}
}
for (subclassIndex in 0..10) {
val subClassName = "SubClass${classIndex}0${subclassIndex}"
kotlinFile(subClassName) {
pkg("pkg")
topClass(subClassName) {
superClass(superClassName)
for (fnName in baseClassFunctionNames) {
function(fnName) {
overrideFunction()
returnType("String")
body("TODO()")
}
}
}
}
}
}
}
}
profile(DefaultProfile)
fixture("src/main/java/pkg/BaseClass.kt").use { fixture ->
with(config) {
warmup = 8
iterations = 15
}
measureHighlight(fixture)
}
}
}
}
}
fun testLotsOfOverloadedMethods() {
// KT-35135
val generatedTypes = mutableListOf(listOf<String>())
generateTypes(arrayOf("Int", "String", "Long", "List<Int>", "Array<Int>"), generatedTypes)
suiteWithConfig("Lots of overloaded method project", "kt-35135 project") {
app {
warmUpProject()
project {
descriptor {
name("kt-35135")
module {
kotlinStandardLibrary()
src("src/main/java/")
kotlinFile("OverloadX") {
pkg("pkg")
topClass("OverloadX") {
openClass()
for (types in generatedTypes) {
function("foo") {
openFunction()
returnType("String")
for ((index, type) in types.withIndex()) {
param("arg$index", type)
}
body("TODO()")
}
}
}
}
kotlinFile("SomeClass") {
pkg("pkg")
topClass("SomeClass") {
superClass("OverloadX")
body("ov")
}
}
}
}
profile(DefaultProfile)
fixture("src/main/java/pkg/SomeClass.kt").use { fixture ->
with(fixture.typingConfig) {
marker = "ov"
insertString = "override fun foo(): String = TODO()"
delayMs = 50
}
with(config) {
warmup = 8
iterations = 15
}
measureTypeAndHighlight(fixture, "type override fun foo()")
}
}
}
}
}
private tailrec fun generateTypes(types: Array<String>, results: MutableList<List<String>>, index: Int = 0, maxCount: Int = 3000) {
val newResults = mutableListOf<List<String>>()
for (list in results) {
if (list.size < index) continue
for (t in types) {
val newList = mutableListOf<String>()
newList.addAll(list)
newList.add(t)
newResults.add(newList.toList())
if (results.size + newResults.size >= maxCount) {
results.addAll(newResults)
return
}
}
}
results.addAll(newResults)
generateTypes(types, results, index + 1, maxCount)
}
fun testManyModulesExample() {
suiteWithConfig("10 modules", "10 modules") {
app {
warmUpProject()
project {
descriptor {
name("ten_modules")
for(index in 0 until 10) {
module("module$index") {
kotlinStandardLibrary()
for (libIndex in 0 until 10) {
library("log4j$libIndex", "log4j:log4j:1.2.17")
}
kotlinFile("SomeService$index") {
pkg("pkg")
topClass("SomeService$index") {
}
}
}
}
}
}
}
}
}
}
| apache-2.0 | a7a008136ba8cf70db147fc1c664c598 | 39.063584 | 158 | 0.370726 | 7.068842 | false | true | false | false |
android/play-billing-samples | ClassyTaxiAppKotlin/app/src/main/java/com/example/subscriptions/data/network/retrofit/authentication/RetrofitClient.kt | 1 | 2337 | /*
* Copyright 2021 Google LLC. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* 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.subscriptions.data.network.retrofit.authentication
import com.example.subscriptions.BuildConfig
import com.google.gson.GsonBuilder
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import okhttp3.logging.HttpLoggingInterceptor.Level
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import retrofit2.converter.scalars.ScalarsConverterFactory
import java.util.concurrent.TimeUnit
/**
* Creates Retrofit instances that [ServerFunctionImpl]
* uses to make authenticated HTTPS requests.
*
* @param <S>
*/
class RetrofitClient<S>(baseUrl: String, serviceClass: Class<S>) {
private val service: S
init {
val gson = GsonBuilder().create()
val loggingInterceptor = HttpLoggingInterceptor()
loggingInterceptor.level = if (BuildConfig.DEBUG) Level.BASIC else Level.NONE
val okHttpClient = OkHttpClient.Builder()
.connectTimeout(NETWORK_TIMEOUT_SECONDS, TimeUnit.SECONDS)
.readTimeout(NETWORK_TIMEOUT_SECONDS, TimeUnit.SECONDS)
.writeTimeout(NETWORK_TIMEOUT_SECONDS, TimeUnit.SECONDS)
.addInterceptor(loggingInterceptor)
.addInterceptor(UserIdTokenInterceptor())
.build()
val retrofit = Retrofit.Builder()
.baseUrl(baseUrl)
.client(okHttpClient)
.addConverterFactory(ScalarsConverterFactory.create())
.addConverterFactory(GsonConverterFactory.create(gson))
.build()
service = retrofit.create(serviceClass)
}
fun getService(): S {
return service
}
companion object {
private const val NETWORK_TIMEOUT_SECONDS: Long = 60
}
} | apache-2.0 | 0822f2ce8b987e54dcf91bdde96aac55 | 33.895522 | 85 | 0.71887 | 4.828512 | false | false | false | false |
squanchy-dev/squanchy-android | app/src/main/java/net/squanchy/eventdetails/EventDetailsActivity.kt | 1 | 4574 | package net.squanchy.eventdetails
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.Menu
import android.view.MenuItem
import androidx.appcompat.app.AppCompatActivity
import androidx.transition.TransitionManager
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.CompositeDisposable
import kotlinx.android.synthetic.main.activity_event_details.*
import net.squanchy.R
import net.squanchy.eventdetails.widget.EventDetailsRootLayout
import net.squanchy.navigation.Navigator
import net.squanchy.notification.scheduleNotificationWork
import net.squanchy.schedule.domain.view.Event
import net.squanchy.signin.SignInOrigin
import net.squanchy.speaker.domain.view.Speaker
import timber.log.Timber
class EventDetailsActivity : AppCompatActivity() {
private val subscriptions = CompositeDisposable()
private lateinit var service: EventDetailsService
private lateinit var navigator: Navigator
private lateinit var eventId: String
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_event_details)
setupToolbar()
with(eventDetailsComponent(this)) {
service = service()
navigator = navigator()
}
}
private fun setupToolbar() {
setSupportActionBar(toolbar)
supportActionBar!!.setDisplayShowTitleEnabled(false)
supportActionBar!!.setDisplayHomeAsUpEnabled(true)
}
override fun onStart() {
super.onStart()
eventId = intent.getStringExtra(EXTRA_EVENT_ID)
subscribeToEvent(eventId)
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
if (requestCode == REQUEST_CODE_SIGNIN) {
subscribeToEvent(eventId)
} else {
super.onActivityResult(requestCode, resultCode, data)
}
}
private fun subscribeToEvent(eventId: String) {
subscriptions.add(
service.event(eventId)
.observeOn(AndroidSchedulers.mainThread())
.subscribe(this@EventDetailsActivity::onDataReceived, Timber::e)
)
}
private fun onDataReceived(event: Event) {
TransitionManager.beginDelayedTransition(eventDetailsRoot)
eventDetailsRoot.updateWith(event, onEventDetailsClickListener(event))
}
private fun onEventDetailsClickListener(event: Event): EventDetailsRootLayout.OnEventDetailsClickListener =
object : EventDetailsRootLayout.OnEventDetailsClickListener {
override fun onSpeakerClicked(speaker: Speaker) {
navigator.toSpeakerDetails(speaker.id)
}
override fun onFavoriteClick() {
subscriptions.add(
service.toggleFavorite(event)
.subscribe(::onFavouriteStateChange, Timber::e)
)
}
}
private fun onFavouriteStateChange(result: EventDetailsService.FavoriteResult) {
if (result === EventDetailsService.FavoriteResult.MUST_AUTHENTICATE) {
requestSignIn()
} else {
triggerNotificationService()
}
}
private fun requestSignIn() {
navigator.toSignInForResult(REQUEST_CODE_SIGNIN, SignInOrigin.EVENT_DETAILS)
unsubscribeFromUpdates()
}
private fun triggerNotificationService() {
scheduleNotificationWork()
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
menuInflater.inflate(R.menu.event_details, menu)
return super.onCreateOptionsMenu(menu)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
return when (item.itemId) {
R.id.action_search -> {
navigator.toSearch(); true
}
android.R.id.home -> {
finish(); true
}
else -> super.onOptionsItemSelected(item)
}
}
override fun onStop() {
super.onStop()
unsubscribeFromUpdates()
}
private fun unsubscribeFromUpdates() {
subscriptions.clear()
}
companion object {
private val EXTRA_EVENT_ID = "${EventDetailsActivity::class.java.name}.event_id"
private const val REQUEST_CODE_SIGNIN = 1235
fun createIntent(context: Context, eventId: String) =
Intent(context, EventDetailsActivity::class.java).apply {
putExtra(EXTRA_EVENT_ID, eventId)
}
}
}
| apache-2.0 | 759e2c7c75a5aa1add9a3a1fd92bd1e3 | 30.115646 | 111 | 0.671622 | 5.185941 | false | false | false | false |
GunoH/intellij-community | platform/xdebugger-impl/src/com/intellij/xdebugger/impl/ui/attach/dialog/items/tree/AttachTreeNodes.kt | 2 | 9587 | package com.intellij.xdebugger.impl.ui.attach.dialog.items.tree
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.util.UserDataHolder
import com.intellij.ui.ColoredTreeCellRenderer
import com.intellij.ui.SimpleTextAttributes
import com.intellij.ui.render.RenderingUtil
import com.intellij.util.ui.JBUI
import com.intellij.xdebugger.XDebuggerBundle
import com.intellij.xdebugger.impl.ui.attach.dialog.AttachDialogProcessItem
import com.intellij.xdebugger.impl.ui.attach.dialog.AttachDialogState
import com.intellij.xdebugger.impl.ui.attach.dialog.items.AttachSelectionIgnoredNode
import com.intellij.xdebugger.impl.ui.attach.dialog.items.AttachToProcessElement
import com.intellij.xdebugger.impl.ui.attach.dialog.items.AttachToProcessElementsFilters
import com.intellij.xdebugger.impl.ui.attach.dialog.items.separators.AttachTreeGroupColumnRenderer
import com.intellij.xdebugger.impl.ui.attach.dialog.items.separators.AttachTreeGroupFirstColumnRenderer
import com.intellij.xdebugger.impl.ui.attach.dialog.items.separators.AttachTreeGroupLastColumnRenderer
import java.awt.Component
import javax.swing.JComponent
import javax.swing.JLabel
import javax.swing.JTree
import javax.swing.table.TableCellRenderer
internal abstract class AttachTreeNode(defaultIndentLevel: Int = 0): AttachToProcessElement {
private val children = mutableListOf<AttachTreeNode>()
private var parent: AttachTreeNode? = null
private var myIndentLevel: Int = defaultIndentLevel
private var myTree: AttachToProcessTree? = null
fun addChild(child: AttachTreeNode) {
children.add(child)
child.parent = this
child.updateIndentLevel(myIndentLevel + 1)
}
fun getChildNodes(): List<AttachTreeNode> = children
fun getParent(): AttachTreeNode? = parent
fun getIndentLevel(): Int = myIndentLevel
var tree: AttachToProcessTree
get() = myTree ?: throw IllegalStateException("Parent tree is not yet set")
set(value) {
myTree = value
for (child in children) {
child.tree = value
}
}
abstract fun getValueAtColumn(column: Int): Any
abstract fun getRenderer(column: Int): TableCellRenderer?
private fun updateIndentLevel(newIndentLevel: Int) {
myIndentLevel = newIndentLevel
for (child in children) {
child.updateIndentLevel(newIndentLevel + 1)
}
}
abstract fun getTreeCellRendererComponent(tree: JTree?,
value: AttachTreeNode,
selected: Boolean,
expanded: Boolean,
leaf: Boolean,
row: Int,
hasFocus: Boolean): Component
override fun getProcessItem(): AttachDialogProcessItem? = null
}
internal class AttachTreeRecentProcessNode(item: AttachDialogProcessItem,
dialogState: AttachDialogState,
dataHolder: UserDataHolder) : AttachTreeProcessNode(item,
dialogState,
dataHolder) {
override fun isRecentItem(): Boolean = true
}
internal open class AttachTreeProcessNode(val item: AttachDialogProcessItem,
val dialogState: AttachDialogState,
val dataHolder: UserDataHolder) : AttachTreeNode() {
companion object {
private val logger = Logger.getInstance(AttachTreeProcessNode::class.java)
}
private val renderer = object : ColoredTreeCellRenderer() {
override fun customizeCellRenderer(tree: JTree,
value: Any?,
selected: Boolean,
expanded: Boolean,
leaf: Boolean,
row: Int,
hasFocus: Boolean) {
val cell = ExecutableCell(this@AttachTreeProcessNode, dialogState)
val (text, tooltip) = cell.getPresentation(this, (cell.node.getIndentLevel() + 1) * JBUI.scale(18))
this.append(text, modifyAttributes(cell.getTextAttributes(), [email protected], row))
this.toolTipText = tooltip
}
private fun modifyAttributes(attributes: SimpleTextAttributes, tree: AttachToProcessTree, row: Int): SimpleTextAttributes {
//We should not trust the selected value as the TreeTableTree
// is inserted into table and usually has wrong selection information
val isTableRowSelected = tree.isRowSelected(row)
return if (!isTableRowSelected) attributes else SimpleTextAttributes(attributes.style, RenderingUtil.getSelectionForeground(tree))
}
}
open fun isRecentItem(): Boolean = false
override fun getValueAtColumn(column: Int): Any = when (column) {
0 -> this
1 -> PidCell(this, dialogState)
2 -> DebuggersCell(this, dialogState)
3 -> CommandLineCell(this, dialogState)
else -> {
logger.error("Unexpected column index: $column")
Any()
}
}
override fun getRenderer(column: Int): TableCellRenderer? = null
override fun getTreeCellRendererComponent(tree: JTree?,
value: AttachTreeNode,
selected: Boolean,
expanded: Boolean,
leaf: Boolean,
row: Int,
hasFocus: Boolean): Component {
return renderer.getTreeCellRendererComponent(tree, value, selected, expanded, leaf, row, hasFocus)
}
override fun visit(filters: AttachToProcessElementsFilters): Boolean {
return filters.accept(item)
}
override fun getProcessItem(): AttachDialogProcessItem = item
}
internal class AttachTreeRecentNode(recentItemNodes: List<AttachTreeRecentProcessNode>) : AttachTreeNode(), AttachSelectionIgnoredNode {
init {
for (recentItemNode in recentItemNodes) {
addChild(recentItemNode)
}
}
override fun getValueAtColumn(column: Int): Any {
return this
}
override fun getRenderer(column: Int): TableCellRenderer? = null
override fun getTreeCellRendererComponent(tree: JTree?,
value: AttachTreeNode,
selected: Boolean,
expanded: Boolean,
leaf: Boolean,
row: Int,
hasFocus: Boolean): JComponent {
return JLabel(XDebuggerBundle.message("xdebugger.attach.dialog.recently.attached.message"))
}
override fun visit(filters: AttachToProcessElementsFilters): Boolean {
return getChildNodes().any { filters.matches(it) }
}
}
internal class AttachTreeSeparatorNode(private val relatedNodes: List<AttachTreeRecentProcessNode>) : AttachTreeNode(), AttachSelectionIgnoredNode {
companion object {
private val logger = Logger.getInstance(AttachTreeSeparatorNode::class.java)
private val leftColumnRenderer = AttachTreeGroupFirstColumnRenderer()
private val middleColumnRenderer = AttachTreeGroupColumnRenderer()
private val rightColumnRenderer = AttachTreeGroupLastColumnRenderer()
}
override fun getValueAtColumn(column: Int): Any {
return this
}
override fun getRenderer(column: Int): TableCellRenderer? {
return when (column) {
0 -> leftColumnRenderer
1 -> middleColumnRenderer
2 -> middleColumnRenderer
3 -> rightColumnRenderer
else -> {
logger.error("Unexpected column index: $column")
null
}
}
}
override fun getTreeCellRendererComponent(tree: JTree?,
value: AttachTreeNode,
selected: Boolean,
expanded: Boolean,
leaf: Boolean,
row: Int,
hasFocus: Boolean): JComponent {
return leftColumnRenderer.getTreeCellRendererComponent(tree, value, selected, expanded, leaf, row, hasFocus)
}
override fun visit(filters: AttachToProcessElementsFilters): Boolean {
return relatedNodes.any { filters.matches(it) }
}
}
internal class AttachTreeRootNode(items: List<AttachTreeNode>) : AttachTreeNode(-1), AttachSelectionIgnoredNode {
init {
for (item in items) {
addChild(item)
}
}
override fun getValueAtColumn(column: Int): Any {
return this
}
override fun getRenderer(column: Int): TableCellRenderer? = null
override fun getTreeCellRendererComponent(tree: JTree?,
value: AttachTreeNode,
selected: Boolean,
expanded: Boolean,
leaf: Boolean,
row: Int,
hasFocus: Boolean): JComponent {
return JLabel()
}
override fun visit(filters: AttachToProcessElementsFilters): Boolean {
return true
}
} | apache-2.0 | fa3465edbfd370b830aae38e0bf1cfad | 38.95 | 148 | 0.610827 | 5.817354 | false | false | false | false |
google/fastboot-mobile | lib/src/main/java/com/google/android/fastbootmobile/FastbootDeviceManager.kt | 1 | 4965 | /*
* Copyright 2018 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.fastbootmobile
import android.hardware.usb.UsbDevice
import android.hardware.usb.UsbDeviceConnection
import android.hardware.usb.UsbInterface
import com.google.android.fastbootmobile.transport.UsbTransport
import java.lang.ref.WeakReference
typealias DeviceId = String
object FastbootDeviceManager {
private const val USB_CLASS = 0xff
private const val USB_SUBCLASS = 0x42
private const val USB_PROTOCOL = 0x03
private val connectedDevices = HashMap<DeviceId, FastbootDeviceContext>()
private val usbDeviceManager: UsbDeviceManager = UsbDeviceManager(
WeakReference(FastbootMobile.getApplicationContext()))
private val listeners = ArrayList<FastbootDeviceManagerListener>()
private val usbDeviceManagerListener = object : UsbDeviceManagerListener {
override fun filterDevice(device: UsbDevice): Boolean =
[email protected](device)
@Synchronized
override fun onUsbDeviceAttached(device: UsbDevice) {
listeners.forEach {
it.onFastbootDeviceAttached(device.serialNumber)
}
}
@Synchronized
override fun onUsbDeviceDetached(device: UsbDevice) {
if (connectedDevices.containsKey(device.serialNumber)) {
connectedDevices[device.serialNumber]?.close()
}
connectedDevices.remove(device.serialNumber)
listeners.forEach {
it.onFastbootDeviceDetached(device.serialNumber)
}
}
@Synchronized
override fun onUsbDeviceConnected(device: UsbDevice,
connection: UsbDeviceConnection) {
val deviceContext = FastbootDeviceContext(
UsbTransport(findFastbootInterface(device)!!, connection))
connectedDevices[device.serialNumber]?.close()
connectedDevices[device.serialNumber] = deviceContext
listeners.forEach {
it.onFastbootDeviceConnected(device.serialNumber, deviceContext)
}
}
}
private fun filterDevice(device: UsbDevice): Boolean {
if (device.deviceClass == USB_CLASS &&
device.deviceSubclass == USB_SUBCLASS &&
device.deviceProtocol == USB_PROTOCOL) {
return true
}
return findFastbootInterface(device) != null
}
@Synchronized
fun addFastbootDeviceManagerListener(
listener: FastbootDeviceManagerListener) {
listeners.add(listener)
if (listeners.size == 1)
usbDeviceManager.addUsbDeviceManagerListener(
usbDeviceManagerListener)
}
@Synchronized
fun removeFastbootDeviceManagerListener(
listener: FastbootDeviceManagerListener) {
listeners.remove(listener)
if (listeners.size == 0)
usbDeviceManager.removeUsbDeviceManagerListener(
usbDeviceManagerListener)
}
@Synchronized
fun connectToDevice(deviceId: DeviceId) {
val device = usbDeviceManager.getDevices().values
.filter(::filterDevice).firstOrNull { it.serialNumber == deviceId }
if (device != null)
usbDeviceManager.connectToDevice(device)
}
@Synchronized
fun getAttachedDeviceIds(): List<DeviceId> {
return usbDeviceManager.getDevices().values
.filter(::filterDevice).map { it.serialNumber }.toList()
}
@Synchronized
fun getConnectedDeviceIds(): List<DeviceId> {
return connectedDevices.keys.toList()
}
@Synchronized
fun getDeviceContext(
deviceId: DeviceId): Pair<DeviceId, FastbootDeviceContext>? {
return connectedDevices.entries.firstOrNull {
it.key == deviceId
}?.toPair()
}
private fun findFastbootInterface(device: UsbDevice): UsbInterface? {
for (i: Int in 0 until device.interfaceCount) {
val deviceInterface = device.getInterface(i)
if (deviceInterface.interfaceClass == USB_CLASS &&
deviceInterface.interfaceSubclass == USB_SUBCLASS &&
deviceInterface.interfaceProtocol == USB_PROTOCOL) {
return deviceInterface
}
}
return null
}
}
| apache-2.0 | 482006a429d8eb5602866f3b138b54fb | 33.964789 | 83 | 0.6572 | 5.373377 | false | false | false | false |
RayBa82/DVBViewerController | dvbViewerController/src/main/java/org/dvbviewer/controller/ui/base/BaseDialogFragment.kt | 1 | 3496 | /*
* Copyright © 2016 dvbviewer-controller 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 org.dvbviewer.controller.ui.base
import android.content.Context
import android.os.Bundle
import android.text.TextUtils
import android.widget.Toast
import androidx.appcompat.app.AppCompatDialogFragment
import org.dvbviewer.controller.R
import org.dvbviewer.controller.data.api.io.exception.AuthenticationException
import org.dvbviewer.controller.data.api.io.exception.DefaultHttpException
import org.xml.sax.SAXException
/**
* @author RayBa82 on 24.01.2016
*
* Base class for Fragments
*/
open class BaseDialogFragment : AppCompatDialogFragment() {
/**
* Generic method to catch an Exception.
* It shows a toast to inform the user.
* This method is safe to be called from non UI threads.
*
* @param e the Excetpion to catch
*/
protected fun catchException(e: Exception) {
if (e is AuthenticationException) {
showToast(context, getStringSafely(R.string.error_invalid_credentials))
} else if (e is DefaultHttpException) {
showToast(context, e.message)
} else if (e is SAXException) {
showToast(context, getStringSafely(R.string.error_parsing_xml))
} else {
showToast(context, getStringSafely(R.string.error_common) + "\n\n" + if (e.message != null) e.message else e.javaClass.name)
}
}
/**
* Possibility to show a Toastmessage from non UI threads.
*
* @param context the context to show the toast
* @param message the message to display
*/
/**
* Possibility to show a Toastmessage from non UI threads.
*
* @param context the context to show the toast
* @param message the message to display
*/
protected fun showToast(context: Context?, message: String?) {
if (context != null && !isDetached) {
val errorRunnable = Runnable {
if (!TextUtils.isEmpty(message)) {
Toast.makeText(context, message, Toast.LENGTH_LONG).show()
}
}
activity!!.runOnUiThread(errorRunnable)
}
}
/**
* Possibility for sublasses to provide a LayouRessource
* before constructor is called.
*
* @param resId the resource id
*
* @return the String for the resource id
*/
protected fun getStringSafely(resId: Int): String {
var result = ""
if (!isDetached && isVisible && isAdded) {
try {
result = getString(resId)
} catch (e: Exception) {
// Dirty Exception Handling, because this keeps and keeps crashing...
e.printStackTrace()
}
}
return result
}
fun logEvent(category: String, bundle: Bundle?){
val baseActivity = activity as BaseActivity?
baseActivity?.mFirebaseAnalytics?.logEvent(category, bundle)
}
} | apache-2.0 | 1dd57e80b849b6c5fe8b6b250200f5f5 | 31.672897 | 136 | 0.649785 | 4.509677 | false | false | false | false |
AntonovAlexander/activecore | kernelip/reordex/src/io_buffer_risc.kt | 1 | 13368 | /*
* io_buffer_risc.kt
*
* Created on: 24.12.2020
* Author: Alexander Antonov <[email protected]>
* License: See LICENSE file for details
*/
package reordex
import hwast.*
internal class io_buffer_risc(cyclix_gen : cyclix.Generic,
ExUnit_name : String,
ExUnit_num : Int,
name_prefix : String,
TRX_BUF_SIZE : Int,
MultiExu_CFG : Reordex_CFG,
exu_id_num: hw_imm,
iq_exu: Boolean,
CDB_index : Int,
cdb_num : Int,
busreq_mem_struct : hw_struct,
commit_cdb : hw_var
) : io_buffer_coproc(cyclix_gen, ExUnit_name, ExUnit_num, name_prefix, TRX_BUF_SIZE, MultiExu_CFG, exu_id_num, iq_exu, CDB_index, cdb_num, busreq_mem_struct, commit_cdb) {
var mem_req = AdduStageVar("mem_req", 0, 0, "0")
var mem_we = AdduStageVar("mem_we", 0, 0, "0")
var mem_addr = AdduStageVar("mem_addr", 31, 0, "0")
var mem_wdata = AdduStageVar("mem_wdata", 31, 0, "0")
var mem_be = AdduStageVar("mem_be", 3, 0, "0")
var mem_load_signext = AdduStageVar("mem_load_signext", 0, 0, "0")
var mem_ctrlflow_enb = AdduStageVar("mem_ctrlflow_enb", 0, 0, "0")
var mem_addr_generated = AdduStageVar("mem_addr_generated", 0, 0, "0")
var mem_addr_generate = cyclix_gen.ulocal("mem_addr_generate", 0, 0, "0")
var mem_addr_generate_trx = cyclix_gen.ulocal("mem_addr_generate_trx", GetWidthToContain(TRX_BUF_SIZE) -1, 0, "0")
val data_name_prefix = "genmcopipe_data_mem_"
var rd_struct = hw_struct("genpmodule_" + cyclix_gen.name + "_" + data_name_prefix + "genstruct_fifo_wdata")
var data_req_fifo = cyclix_gen.fifo_out((data_name_prefix + "req"), rd_struct)
var data_resp_fifo = cyclix_gen.ufifo_in((data_name_prefix + "resp"), 31, 0)
var mem_data_wdata = cyclix_gen.local("mem_data_wdata", data_req_fifo.vartype, "0")
var mem_data_rdata = cyclix_gen.local("mem_data_rdata", data_resp_fifo.vartype, "0")
var lsu_iq_done = cyclix_gen.ulocal("lsu_iq_done", 0, 0, "0")
var lsu_iq_num = cyclix_gen.ulocal("lsu_iq_num", GetWidthToContain(TRX_BUF.GetWidth()) -1, 0, "0")
var io_iq_cmd = TRX_BUF.GetFracRef(lsu_iq_num)
var exu_cdb_inst_enb = commit_cdb.GetFracRef("enb")
var exu_cdb_inst_data = commit_cdb.GetFracRef("data")
var exu_cdb_inst_trx_id = exu_cdb_inst_data.GetFracRef("trx_id")
var exu_cdb_inst_req = exu_cdb_inst_data.GetFracRef("rd0_req") // TODO: fix
var exu_cdb_inst_tag = exu_cdb_inst_data.GetFracRef("rd0_tag") // TODO: fix
var exu_cdb_inst_wdata = exu_cdb_inst_data.GetFracRef("rd0_wdata") // TODO: fix
var resp_buf = io_buffer_resp_risc(cyclix_gen, "LSU_resp", 4, MultiExu_CFG, data_resp_fifo.vartype.dimensions)
var search_active = cyclix_gen.ulocal("search_active", 0, 0, "1")
init {
rd_struct.addu("we", 0, 0, "0")
rd_struct.add("wdata", hw_type(busreq_mem_struct), "0")
}
override fun ProcessIO(io_cdb_buf : hw_var, io_cdb_rs1_wdata_buf : hw_var, rob_buf : rob) {
cyclix_gen.MSG_COMMENT("I/O IQ processing...")
preinit_ctrls()
init_locals()
resp_buf.preinit_ctrls()
var io_cdb_enb = io_cdb_buf.GetFracRef("enb")
var io_cdb_data = io_cdb_buf.GetFracRef("data")
var io_cdb_trx_id = io_cdb_data.GetFracRef("trx_id")
var io_cdb_req = io_cdb_data.GetFracRef("rd0_req")
var io_cdb_tag = io_cdb_data.GetFracRef("rd0_tag")
var io_cdb_wdata = io_cdb_data.GetFracRef("rd0_wdata")
cyclix_gen.assign(io_cdb_enb, 0)
cyclix_gen.assign(io_cdb_data, 0)
cyclix_gen.assign(mem_addr, src_rsrv[0].src_data)
cyclix_gen.assign(mem_wdata, src_rsrv[1].src_data)
cyclix_gen.MSG_COMMENT("Returning I/O to CDB...")
var resp_buf_head = resp_buf.TRX_BUF.GetFracRef(0)
var resp_buf_head_rdy = resp_buf_head.GetFracRef("rdy")
var resp_buf_head_trx_id = resp_buf_head.GetFracRef("trx_id")
var resp_buf_head_rd0_req = resp_buf_head.GetFracRef("rd0_req")
var resp_buf_head_rd0_tag = resp_buf_head.GetFracRef("rd0_tag")
var resp_buf_head_mem_be = resp_buf_head.GetFracRef("mem_be")
var resp_buf_head_mem_load_signext = resp_buf_head.GetFracRef("mem_load_signext")
var resp_buf_head_mem_data_rdata = resp_buf_head.GetFracRef("mem_data_rdata")
cyclix_gen.begif(resp_buf.TRX_BUF_COUNTER_NEMPTY)
run {
cyclix_gen.begif(resp_buf_head_rdy)
run {
cyclix_gen.assign(exu_cdb_inst_enb, 1)
cyclix_gen.assign(exu_cdb_inst_trx_id, resp_buf_head_trx_id)
cyclix_gen.assign(exu_cdb_inst_req, resp_buf_head_rd0_req)
cyclix_gen.assign(exu_cdb_inst_tag, resp_buf_head_rd0_tag)
cyclix_gen.assign(exu_cdb_inst_wdata, resp_buf_head_mem_data_rdata)
resp_buf.pop_trx()
}; cyclix_gen.endif()
}; cyclix_gen.endif()
cyclix_gen.MSG_COMMENT("Returning I/O to CDB: done")
cyclix_gen.MSG_COMMENT("Fetching I/O response...")
cyclix_gen.begif(cyclix_gen.fifo_rd_unblk(data_resp_fifo, mem_data_rdata))
run {
cyclix_gen.begif(cyclix_gen.eq2(resp_buf_head_mem_be, 0x1))
run {
cyclix_gen.begif(resp_buf_head_mem_load_signext)
run {
mem_data_rdata.assign(cyclix_gen.signext(mem_data_rdata[7, 0], 32))
}; cyclix_gen.endif()
cyclix_gen.begelse()
run {
mem_data_rdata.assign(cyclix_gen.zeroext(mem_data_rdata[7, 0], 32))
}; cyclix_gen.endif()
}; cyclix_gen.endif()
cyclix_gen.begif(cyclix_gen.eq2(resp_buf_head_mem_be, 0x3))
run {
cyclix_gen.begif(resp_buf_head_mem_load_signext)
run {
mem_data_rdata.assign(cyclix_gen.signext(mem_data_rdata[15, 0], 32))
}; cyclix_gen.endif()
cyclix_gen.begelse()
run {
mem_data_rdata.assign(cyclix_gen.zeroext(mem_data_rdata[15, 0], 32))
}; cyclix_gen.endif()
}; cyclix_gen.endif()
cyclix_gen.assign(resp_buf_head_mem_data_rdata, mem_data_rdata)
cyclix_gen.assign(resp_buf_head_rdy, 1)
}; cyclix_gen.endif()
cyclix_gen.MSG_COMMENT("Fetching I/O response: done")
cyclix_gen.MSG_COMMENT("Initiating I/O request...")
cyclix_gen.begif(cyclix_gen.band(ctrl_active, resp_buf.ctrl_rdy))
run {
cyclix_gen.begif(mem_addr_generated)
run {
cyclix_gen.begif(mem_ctrlflow_enb)
run {
// data is ready identification
cyclix_gen.assign(rdy, src_rsrv[0].src_rdy)
cyclix_gen.begif(mem_we)
run {
cyclix_gen.band_gen(rdy, rdy, src_rsrv[1].src_rdy)
}; cyclix_gen.endif()
cyclix_gen.begif(rdy)
run {
cyclix_gen.assign(mem_data_wdata.GetFracRef("we"), mem_we)
cyclix_gen.assign(mem_data_wdata.GetFracRef("wdata").GetFracRef("addr"), mem_addr)
cyclix_gen.assign(mem_data_wdata.GetFracRef("wdata").GetFracRef("be"), mem_be)
cyclix_gen.assign(mem_data_wdata.GetFracRef("wdata").GetFracRef("wdata"), mem_wdata)
cyclix_gen.begif(cyclix_gen.fifo_wr_unblk(data_req_fifo, mem_data_wdata))
run {
var resp_trx = resp_buf.GetPushTrx()
var resp_trx_rdy = resp_trx.GetFracRef("rdy")
var resp_trx_trx_id = resp_trx.GetFracRef("trx_id")
var resp_trx_rd0_req = resp_trx.GetFracRef("rd0_req")
var resp_trx_rd0_tag = resp_trx.GetFracRef("rd0_tag")
var resp_trx_mem_be = resp_trx.GetFracRef("mem_be")
var resp_trx_mem_load_signext = resp_trx.GetFracRef("mem_load_signext")
var resp_trx_mem_data_rdata = resp_trx.GetFracRef("mem_data_rdata")
cyclix_gen.assign(resp_trx_rdy, mem_we)
cyclix_gen.assign(resp_trx_trx_id, trx_id)
cyclix_gen.assign(resp_trx_rd0_req, !mem_we)
cyclix_gen.assign(resp_trx_rd0_tag, rd_ctrls[0].tag)
cyclix_gen.assign(resp_trx_mem_be, mem_be)
cyclix_gen.assign(resp_trx_mem_load_signext, mem_load_signext)
cyclix_gen.assign(resp_trx_mem_data_rdata, 0)
resp_buf.push_trx(resp_trx)
cyclix_gen.assign(pop, 1)
pop_trx()
}; cyclix_gen.endif()
}; cyclix_gen.endif()
}; cyclix_gen.endif()
}; cyclix_gen.endif()
}; cyclix_gen.endif()
cyclix_gen.MSG_COMMENT("Initiating I/O request: done")
cyclix_gen.MSG_COMMENT("Mem addr generating...")
for (trx_idx in TRX_BUF.vartype.dimensions.last().msb downTo 0) {
var entry_ptr = TRX_BUF.GetFracRef(trx_idx)
cyclix_gen.begif(cyclix_gen.band(entry_ptr.GetFracRef("enb"), entry_ptr.GetFracRef("src0_rdy"), !entry_ptr.GetFracRef("mem_addr_generated")))
run {
cyclix_gen.assign(mem_addr_generate, 1)
cyclix_gen.assign(mem_addr_generate_trx, trx_idx)
}; cyclix_gen.endif()
}
cyclix_gen.begif(mem_addr_generate)
run {
var entry_ptr = TRX_BUF.GetFracRef(mem_addr_generate_trx)
cyclix_gen.add_gen(entry_ptr.GetFracRef("src0_data"), entry_ptr.GetFracRef("src0_data"), entry_ptr.GetFracRef("immediate"))
cyclix_gen.assign(entry_ptr.GetFracRef("mem_addr_generated"), 1)
}; cyclix_gen.endif()
cyclix_gen.MSG_COMMENT("Mem addr generating: done")
cyclix_gen.COMMENT("Memory flow control consistency identification...")
var ROB_SEARCH_DEPTH = 4
for (rob_trx_idx in 0 until ROB_SEARCH_DEPTH) {
for (rob_trx_entry_idx in 0 until rob_buf.TRX_BUF_MULTIDIM) {
cyclix_gen.begif(search_active)
run {
var lsu_entry = TRX_BUF.GetFracRef(0)
var rob_entry = rob_buf.TRX_BUF.GetFracRef(rob_trx_idx).GetFracRef(rob_trx_entry_idx)
var break_val = (rob_entry.GetFracRef("cf_can_alter") as hw_param)
if (rob_trx_idx == 0) {
break_val = cyclix_gen.band(break_val, (rob_buf as rob_risc).entry_mask.GetFracRef(rob_trx_entry_idx))
}
cyclix_gen.begif(break_val)
run {
search_active.assign(0)
}; cyclix_gen.endif()
cyclix_gen.begelse()
run {
var active_trx_id = rob_entry.GetFracRef("trx_id")
cyclix_gen.begif(cyclix_gen.eq2(lsu_entry.GetFracRef("trx_id"), active_trx_id))
run {
cyclix_gen.assign(lsu_entry.GetFracRef("mem_ctrlflow_enb"), 1)
}; cyclix_gen.endif()
}; cyclix_gen.endif()
}; cyclix_gen.endif()
}
}
cyclix_gen.COMMENT("Memory flow control consistency identification: done")
cyclix_gen.MSG_COMMENT("I/O IQ processing: done")
}
}
internal class io_buffer_resp_risc (cyclix_gen : cyclix.Generic,
name_prefix : String,
TRX_BUF_SIZE : Int,
MultiExu_CFG : Reordex_CFG,
data_dim : hw_dim_static
): trx_buffer(cyclix_gen, name_prefix, TRX_BUF_SIZE, 0, MultiExu_CFG) {
var rdy = AdduStageVar("rdy", 0, 0, "0")
var trx_id = AddStageVar(hw_structvar("trx_id", DATA_TYPE.BV_UNSIGNED, GetWidthToContain(MultiExu_CFG.trx_inflight_num)-1, 0, "0"))
var rd0_req = AdduStageVar("rd0_req", 0, 0, "0")
var rd0_tag = AdduStageVar("rd0_tag", 31, 0, "0") // TODO: fix dims
var mem_be = AdduStageVar("mem_be", 3, 0, "0")
var mem_load_signext = AdduStageVar("mem_load_signext", 0, 0, "0")
var mem_data_rdata = AdduStageVar("mem_data_rdata", data_dim, "0")
} | apache-2.0 | 32d8c882bdc6d6d7c59da37ddcf0b19e | 46.974359 | 171 | 0.525509 | 3.605178 | false | false | false | false |
onnerby/musikcube | src/musikdroid/app/src/main/java/io/casey/musikcube/remote/ui/category/adapter/AllCategoriesAdapter.kt | 2 | 1882 | package io.casey.musikcube.remote.ui.category.adapter
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import io.casey.musikcube.remote.R
import io.casey.musikcube.remote.ui.category.constant.Category.toDisplayString
class AllCategoriesAdapter(private val listener: EventListener)
: RecyclerView.Adapter<AllCategoriesAdapter.Holder>()
{
private var categories: List<String> = listOf()
interface EventListener {
fun onItemClicked(category: String)
}
class Holder(itemView: View): RecyclerView.ViewHolder(itemView) {
private val title: TextView = itemView.findViewById(R.id.title)
init {
itemView.findViewById<View>(R.id.action).visibility = View.GONE
itemView.findViewById<View>(R.id.subtitle).visibility = View.GONE
}
internal fun bindView(category: String) {
title.text = toDisplayString(itemView.context, category)
itemView.tag = category
}
}
override fun onBindViewHolder(holder: Holder, position: Int) {
holder.bindView(categories[position])
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): Holder {
val inflater = LayoutInflater.from(parent.context)
val view = inflater.inflate(R.layout.simple_list_item, parent, false)
view.setOnClickListener { v -> listener.onItemClicked(v.tag as String) }
return Holder(view)
}
override fun getItemCount(): Int {
return categories.size
}
fun setModel(model: List<String>) {
this.categories = model.filter { !BLACKLIST.contains(it) }
this.notifyDataSetChanged()
}
companion object {
val BLACKLIST = setOf("channels", "encoder", "path_id", "totaltracks")
}
} | bsd-3-clause | 2f250f95ea1ec0681b97efdd78103db2 | 32.035088 | 80 | 0.695005 | 4.513189 | false | false | false | false |
syrop/GPS-Texter | texter/src/main/kotlin/pl/org/seva/texter/settings/PhoneNumberFragment.kt | 1 | 9287 | /*
* Copyright (C) 2017 Wiktor Nizio
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* If you like this program, consider donating bitcoin: bc1qncxh5xs6erq6w4qz3a7xl7f50agrgn3w58dsfp
*/
package pl.org.seva.texter.settings
import android.Manifest
import android.annotation.SuppressLint
import android.app.Dialog
import android.content.DialogInterface
import android.content.pm.PackageManager
import android.database.Cursor
import android.os.Bundle
import android.preference.PreferenceManager
import android.provider.ContactsContract
import androidx.fragment.app.DialogFragment
import androidx.loader.app.LoaderManager
import androidx.core.content.ContextCompat
import androidx.loader.content.CursorLoader
import androidx.loader.content.Loader
import androidx.cursoradapter.widget.SimpleCursorAdapter
import androidx.appcompat.app.AlertDialog
import android.view.LayoutInflater
import android.view.View
import android.widget.AdapterView
import android.widget.EditText
import android.widget.ListView
import android.widget.Toast
import java.util.ArrayList
import pl.org.seva.texter.R
import pl.org.seva.texter.main.Constants
class PhoneNumberFragment : DialogFragment(), LoaderManager.LoaderCallbacks<Cursor> {
private var toast: Toast? = null
private var contactsEnabled: Boolean = false
private lateinit var contactKey: String
private var contactName: String? = null
lateinit var adapter: SimpleCursorAdapter
private lateinit var number: EditText
@SuppressLint("InflateParams")
private fun phoneNumberDialogView(inflater: LayoutInflater) : View {
val v = inflater.inflate(R.layout.fragment_number, null)
number = v.findViewById(R.id.number)
val contacts: ListView = v.findViewById(R.id.contacts)
contactsEnabled = ContextCompat.checkSelfPermission(
requireActivity(),
Manifest.permission.READ_CONTACTS) == PackageManager.PERMISSION_GRANTED
if (!contactsEnabled) {
contacts.visibility = View.GONE
} else {
contacts.onItemClickListener = AdapterView.OnItemClickListener {
parent, _, position, _ -> this.onItemClick(parent, position) }
adapter = SimpleCursorAdapter(
activity,
R.layout.item_contact, null,
FROM_COLUMNS,
TO_IDS,
0)
contacts.adapter = adapter
}
return v
}
private val persistedString: String
get() = checkNotNull(PreferenceManager.getDefaultSharedPreferences(activity)
.getString(SettingsActivity.PHONE_NUMBER, Constants.DEFAULT_PHONE_NUMBER))
@SuppressLint("InflateParams")
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
val builder = AlertDialog.Builder(requireActivity())
// Get the layout inflater
val inflater = requireActivity().layoutInflater
// Inflate and set the layout for the dialog
// Pass null as the parent view because its going in the dialog layout
builder.setView(phoneNumberDialogView(inflater))
// Add action buttons
.setPositiveButton(android.R.string.ok) { dialog, _ -> onOkPressedInDialog(dialog) }
.setNegativeButton(android.R.string.cancel) { dialog, _ -> dialog.dismiss() }
setNumber(persistedString)
return builder.create()
}
private fun onOkPressedInDialog(d: DialogInterface) {
persistString(number.text.toString())
d.dismiss()
}
private fun persistString(`val`: String) = PreferenceManager.getDefaultSharedPreferences(activity).edit()
.putString(SettingsActivity.PHONE_NUMBER, `val`).apply()
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
if (contactsEnabled) {
loaderManager.initLoader(CONTACTS_QUERY_ID, null, this)
}
}
override fun toString() = number.text.toString()
override fun onCreateLoader(id: Int, args: Bundle?): Loader<Cursor> {
when (id) {
CONTACTS_QUERY_ID -> {
val contactsSelectionArgs = arrayOf("1")
return CursorLoader(
requireActivity(),
ContactsContract.Contacts.CONTENT_URI,
CONTACTS_PROJECTION,
CONTACTS_SELECTION,
contactsSelectionArgs,
CONTACTS_SORT)
}
DETAILS_QUERY_ID -> {
val detailsSelectionArgs = arrayOf(contactKey)
return CursorLoader(
requireActivity(),
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
DETAILS_PROJECTION,
DETAILS_SELECTION,
detailsSelectionArgs,
DETAILS_SORT)
}
else -> throw IllegalArgumentException()
}
}
override fun onLoadFinished(loader: Loader<Cursor>, data: Cursor) {
when (loader.id) {
CONTACTS_QUERY_ID -> adapter.swapCursor(data)
DETAILS_QUERY_ID -> {
val numbers = ArrayList<String>()
while (data.moveToNext()) {
val n = data.getString(DETAILS_NUMBER_INDEX)
if (!numbers.contains(n)) {
numbers.add(n)
}
}
data.close()
when {
numbers.size == 1 -> this.number.setText(numbers[0])
numbers.isEmpty() -> {
toast = Toast.makeText(
context,
R.string.no_number,
Toast.LENGTH_SHORT)
checkNotNull(toast).show()
}
else -> {
val items = numbers.toTypedArray()
AlertDialog.Builder(requireActivity()).setItems(items) { dialog, which ->
dialog.dismiss()
number.setText(numbers[which])
}.setTitle(contactName).setCancelable(true).setNegativeButton(
android.R.string.cancel)
{ dialog, _ -> dialog.dismiss() }.show()
}
}
}
}
}
override fun onLoaderReset(loader: Loader<Cursor>) {
when (loader.id) {
CONTACTS_QUERY_ID -> adapter.swapCursor(null)
DETAILS_QUERY_ID -> {
}
}
}
private fun onItemClick(parent: AdapterView<*>, position: Int) {
toast?.cancel()
val cursor = (parent.adapter as SimpleCursorAdapter).cursor
cursor.moveToPosition(position)
contactKey = cursor.getString(CONTACT_KEY_INDEX)
contactName = cursor.getString(CONTACT_NAME_INDEX)
loaderManager.restartLoader(DETAILS_QUERY_ID, null, this)
}
private fun setNumber(number: String?) = this.number.setText(number)
companion object {
private const val CONTACTS_QUERY_ID = 0
private const val DETAILS_QUERY_ID = 1
private val FROM_COLUMNS = arrayOf(ContactsContract.Contacts.DISPLAY_NAME_PRIMARY)
private val CONTACTS_PROJECTION = arrayOf( // SELECT
ContactsContract.Contacts._ID, ContactsContract.Contacts.LOOKUP_KEY, ContactsContract.Contacts.DISPLAY_NAME_PRIMARY, ContactsContract.Contacts.HAS_PHONE_NUMBER)
private const val CONTACTS_SELECTION = // FROM
ContactsContract.Contacts.HAS_PHONE_NUMBER + " = ?"
private const val CONTACTS_SORT = // ORDER_BY
ContactsContract.Contacts.DISPLAY_NAME_PRIMARY
private val DETAILS_PROJECTION = arrayOf( // SELECT
ContactsContract.CommonDataKinds.Phone._ID, ContactsContract.CommonDataKinds.Phone.NUMBER, ContactsContract.CommonDataKinds.Phone.TYPE, ContactsContract.CommonDataKinds.Phone.LABEL)
private const val DETAILS_SORT = // ORDER_BY
ContactsContract.CommonDataKinds.Phone._ID
private const val DETAILS_SELECTION = // WHERE
ContactsContract.Data.LOOKUP_KEY + " = ?"
// The column index for the LOOKUP_KEY column
private const val CONTACT_KEY_INDEX = 1
private const val CONTACT_NAME_INDEX = 2
private const val DETAILS_NUMBER_INDEX = 1
private val TO_IDS = intArrayOf(android.R.id.text1)
}
}
| gpl-3.0 | 5f8abbd5e047ce5e012f3f34759fe3d3 | 37.376033 | 197 | 0.62216 | 5.182478 | false | false | false | false |
mdanielwork/intellij-community | plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/impl/statements/expressions/GrReferenceExpressionReference.kt | 1 | 3762 | // Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.plugins.groovy.lang.psi.impl.statements.expressions
import com.intellij.psi.PsiElement
import org.jetbrains.plugins.groovy.lang.psi.GroovyElementTypes
import org.jetbrains.plugins.groovy.lang.psi.api.GroovyResolveResult
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrReferenceExpression
import org.jetbrains.plugins.groovy.lang.psi.impl.statements.expressions.GrSuperReferenceResolver.resolveSuperExpression
import org.jetbrains.plugins.groovy.lang.psi.impl.statements.expressions.GrThisReferenceResolver.resolveThisExpression
import org.jetbrains.plugins.groovy.lang.psi.util.PsiUtil
import org.jetbrains.plugins.groovy.lang.resolve.GrReferenceResolveRunner
import org.jetbrains.plugins.groovy.lang.resolve.GrResolverProcessor
import org.jetbrains.plugins.groovy.lang.resolve.api.Argument
import org.jetbrains.plugins.groovy.lang.resolve.api.GroovyCachingReference
import org.jetbrains.plugins.groovy.lang.resolve.processors.GroovyLValueProcessor
import org.jetbrains.plugins.groovy.lang.resolve.processors.GroovyRValueProcessor
import org.jetbrains.plugins.groovy.lang.resolve.processors.GroovyResolveKind
import org.jetbrains.plugins.groovy.lang.resolve.processors.GroovyResolveKind.*
import java.util.*
abstract class GrReferenceExpressionReference(ref: GrReferenceExpressionImpl) : GroovyCachingReference<GrReferenceExpressionImpl>(ref) {
override fun doResolve(incomplete: Boolean): Collection<GroovyResolveResult> {
val staticResults = element.staticReference.resolve(incomplete)
if (staticResults.isNotEmpty()) {
return staticResults
}
return doResolveNonStatic()
}
protected open fun doResolveNonStatic(): Collection<GroovyResolveResult> {
val expression = element
val name = expression.referenceName ?: return emptyList()
val kinds = expression.resolveKinds()
val processor = buildProcessor(name, expression, kinds)
GrReferenceResolveRunner(expression, processor).resolveReferenceExpression()
return processor.results
}
protected abstract fun buildProcessor(name: String, place: PsiElement, kinds: Set<GroovyResolveKind>): GrResolverProcessor<*>
}
class GrRValueExpressionReference(ref: GrReferenceExpressionImpl) : GrReferenceExpressionReference(ref) {
override fun doResolveNonStatic(): Collection<GroovyResolveResult> {
return element.handleSpecialCases()
?: super.doResolveNonStatic()
}
override fun buildProcessor(name: String, place: PsiElement, kinds: Set<GroovyResolveKind>): GrResolverProcessor<*> {
return GroovyRValueProcessor(name, place, kinds)
}
}
class GrLValueExpressionReference(ref: GrReferenceExpressionImpl, private val argument: Argument) : GrReferenceExpressionReference(ref) {
override fun buildProcessor(name: String, place: PsiElement, kinds: Set<GroovyResolveKind>): GrResolverProcessor<*> {
return GroovyLValueProcessor(name, place, kinds, listOf(argument))
}
}
private fun GrReferenceExpression.handleSpecialCases(): Collection<GroovyResolveResult>? {
when (referenceNameElement?.node?.elementType) {
GroovyElementTypes.KW_THIS -> return resolveThisExpression(this)
GroovyElementTypes.KW_SUPER -> return resolveSuperExpression(this)
GroovyElementTypes.KW_CLASS -> {
if (!PsiUtil.isCompileStatic(this) && qualifier?.type == null) {
return emptyList()
}
}
}
return null
}
private fun GrReferenceExpressionImpl.resolveKinds(): Set<GroovyResolveKind> {
return if (isQualified) {
EnumSet.of(FIELD, PROPERTY, VARIABLE)
}
else {
EnumSet.of(FIELD, PROPERTY, VARIABLE, BINDING)
}
}
| apache-2.0 | 5356c431559d488aaabc6493487d9bbb | 44.878049 | 140 | 0.799309 | 4.667494 | false | false | false | false |
dahlstrom-g/intellij-community | plugins/kotlin/jvm-debugger/core-fe10/src/org/jetbrains/kotlin/idea/debugger/stepping/smartStepInto/KotlinMethodFilter.kt | 2 | 5522 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.idea.debugger.stepping.smartStepInto
import com.intellij.debugger.PositionManager
import com.intellij.debugger.engine.DebugProcessImpl
import com.intellij.debugger.engine.NamedMethodFilter
import com.intellij.openapi.application.ReadAction
import com.intellij.util.Range
import com.sun.jdi.LocalVariable
import com.sun.jdi.Location
import org.jetbrains.kotlin.descriptors.CallableMemberDescriptor
import org.jetbrains.kotlin.descriptors.DeclarationDescriptor
import org.jetbrains.kotlin.idea.caches.resolve.resolveToDescriptorIfAny
import org.jetbrains.kotlin.idea.codeInsight.DescriptorToSourceUtilsIde
import org.jetbrains.kotlin.idea.debugger.DebuggerUtils.trimIfMangledInBytecode
import org.jetbrains.kotlin.idea.debugger.getInlineFunctionAndArgumentVariablesToBordersMap
import org.jetbrains.kotlin.idea.debugger.safeMethod
import org.jetbrains.kotlin.load.java.JvmAbi
import org.jetbrains.kotlin.psi.KtClass
import org.jetbrains.kotlin.psi.KtDeclaration
import org.jetbrains.kotlin.psi.KtProperty
import org.jetbrains.kotlin.psi.psiUtil.createSmartPointer
import org.jetbrains.kotlin.psi.psiUtil.getParentOfTypesAndPredicate
import org.jetbrains.kotlin.resolve.DescriptorUtils
open class KotlinMethodFilter(
declaration: KtDeclaration?,
private val lines: Range<Int>?,
private val methodInfo: CallableMemberInfo
) : NamedMethodFilter {
private val declarationPtr = declaration?.createSmartPointer()
override fun locationMatches(process: DebugProcessImpl, location: Location): Boolean {
if (!nameMatches(location)) {
return false
}
return ReadAction.nonBlocking<Boolean> {
declarationMatches(process, location)
}.executeSynchronously()
}
private fun declarationMatches(process: DebugProcessImpl, location: Location): Boolean {
val (currentDescriptor, currentDeclaration) = getMethodDescriptorAndDeclaration(process.positionManager, location)
if (currentDescriptor == null || currentDeclaration == null) {
return false
}
if (currentDescriptor !is CallableMemberDescriptor) return false
if (currentDescriptor.kind != CallableMemberDescriptor.Kind.DECLARATION) return false
if (methodInfo.isInvoke) {
// There can be only one 'invoke' target at the moment so consider position as expected.
// Descriptors can be not-equal, say when parameter has type `(T) -> T` and lambda is `Int.() -> Int`.
return true
}
// Element is lost. But we know that name matches, so stop.
val declaration = declarationPtr?.element ?: return true
val psiManager = currentDeclaration.manager
if (psiManager.areElementsEquivalent(currentDeclaration, declaration)) {
return true
}
return DescriptorUtils.getAllOverriddenDescriptors(currentDescriptor).any { baseOfCurrent ->
val currentBaseDeclaration = DescriptorToSourceUtilsIde.getAnyDeclaration(currentDeclaration.project, baseOfCurrent)
psiManager.areElementsEquivalent(declaration, currentBaseDeclaration)
}
}
override fun getCallingExpressionLines(): Range<Int>? =
lines
override fun getMethodName(): String =
methodInfo.name
private fun nameMatches(location: Location): Boolean {
val method = location.safeMethod() ?: return false
val targetMethodName = methodName
val isNameMangledInBytecode = methodInfo.isNameMangledInBytecode
val actualMethodName = method.name().trimIfMangledInBytecode(isNameMangledInBytecode)
return actualMethodName == targetMethodName ||
actualMethodName == "$targetMethodName${JvmAbi.DEFAULT_PARAMS_IMPL_SUFFIX}" ||
// A correct way here is to memorize the original location (where smart step into was started)
// and filter out ranges that contain that original location.
// Otherwise, nested inline with the same method name will not work correctly.
method.getInlineFunctionAndArgumentVariablesToBordersMap()
.filter { location in it.value }
.any { it.key.isInlinedFromFunction(targetMethodName, isNameMangledInBytecode) }
}
}
private fun getMethodDescriptorAndDeclaration(
positionManager: PositionManager,
location: Location
): Pair<DeclarationDescriptor?, KtDeclaration?> {
val actualMethodName = location.safeMethod()?.name() ?: return null to null
val elementAt = positionManager.getSourcePosition(location)?.elementAt
val declaration = elementAt?.getParentOfTypesAndPredicate(false, KtDeclaration::class.java) {
it !is KtProperty || !it.isLocal
}
return if (declaration is KtClass && actualMethodName == "<init>") {
declaration.resolveToDescriptorIfAny()?.unsubstitutedPrimaryConstructor to declaration
} else {
declaration?.resolveToDescriptorIfAny() to declaration
}
}
private fun LocalVariable.isInlinedFromFunction(methodName: String, isNameMangledInBytecode: Boolean): Boolean {
val variableName = name().trimIfMangledInBytecode(isNameMangledInBytecode)
return variableName.startsWith(JvmAbi.LOCAL_VARIABLE_NAME_PREFIX_INLINE_FUNCTION) &&
variableName.substringAfter(JvmAbi.LOCAL_VARIABLE_NAME_PREFIX_INLINE_FUNCTION) == methodName
}
| apache-2.0 | e33ffcf58171184851e0d7d65045d874 | 46.196581 | 128 | 0.745382 | 5.429695 | false | false | false | false |
dkandalov/katas | kotlin/src/katas/kotlin/shuntingYard/ShuntingYard2.kt | 1 | 1400 | package katas.kotlin.shuntingYard
import datsok.shouldEqual
import org.junit.Test
import java.util.LinkedList
class ShuntingYard2 {
@Test fun `convert infix expression into RPN`() {
listOf("1", "+", "2").toRPN() shouldEqual listOf("1", "2", "+")
listOf("1", "+", "2", "+", "3").toRPN() shouldEqual listOf("1", "2", "+", "3", "+")
listOf("1", "*", "2", "+", "3").toRPN() shouldEqual listOf("1", "2", "*", "3", "+")
listOf("1", "+", "2", "*", "3").toRPN() shouldEqual listOf("1", "2", "3", "*", "+")
}
private fun List<String>.toRPN(): List<String> {
val result = ArrayList<String>(size)
val stack = LinkedList<String>()
forEach { token ->
if (token.isOperator()) {
if (stack.isNotEmpty() && token.precedence() <= stack.first().precedence()) {
result.consume(stack)
}
stack.add(0, token)
} else {
result.add(token)
}
}
result.consume(stack)
return result
}
private val operators = mapOf(
"*" to 20,
"+" to 10
)
private fun String.isOperator() = operators.contains(this)
private fun String.precedence() = operators[this]!!
private fun <E> MutableList<E>.consume(list: MutableList<E>) = apply {
addAll(list)
list.clear()
}
}
| unlicense | 7958f1619f64b5b014b9e57aff10ca0a | 30.111111 | 93 | 0.513571 | 4.011461 | false | false | false | false |
dahlstrom-g/intellij-community | plugins/git4idea/src/git4idea/repo/GitModulesFileReader.kt | 13 | 1744 | /*
* 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 git4idea.repo
import com.intellij.openapi.diagnostic.logger
import org.ini4j.Ini
import java.io.File
import java.io.IOException
import java.util.regex.Pattern
class GitModulesFileReader {
private val LOG = logger<GitModulesFileReader>()
private val MODULE_SECTION = Pattern.compile("submodule \"(.*)\"", Pattern.CASE_INSENSITIVE)
fun read(file: File): Collection<GitSubmoduleInfo> {
if (!file.exists()) return listOf()
val ini: Ini
try {
ini = loadIniFile(file)
}
catch (e: IOException) {
return listOf()
}
val modules = mutableSetOf<GitSubmoduleInfo>()
for ((sectionName, section) in ini) {
val matcher = MODULE_SECTION.matcher(sectionName)
if (matcher.matches() && matcher.groupCount() == 1) {
val path = section["path"]
val url = section["url"]
if (path == null || url == null) {
LOG.warn("Partially defined submodule: $section")
}
else {
val module = GitSubmoduleInfo(path, url)
LOG.debug("Found submodule $module")
modules.add(module)
}
}
}
return modules
}
} | apache-2.0 | 69450aec6a9076ce6c0bc526ccea31eb | 29.614035 | 94 | 0.667431 | 4.037037 | false | false | false | false |
tateisu/SubwayTooter | app/src/main/java/jp/juggler/subwaytooter/table/UserRelation.kt | 1 | 16272 | package jp.juggler.subwaytooter.table
import android.content.ContentValues
import android.database.Cursor
import android.database.sqlite.SQLiteDatabase
import android.provider.BaseColumns
import jp.juggler.subwaytooter.api.TootParser
import jp.juggler.subwaytooter.api.entity.Acct
import jp.juggler.subwaytooter.api.entity.EntityId
import jp.juggler.subwaytooter.api.entity.TootAccount
import jp.juggler.subwaytooter.api.entity.TootRelationShip
import jp.juggler.subwaytooter.global.appDatabase
import jp.juggler.util.*
class UserRelation {
var following = false // 認証ユーザからのフォロー状態にある
var followed_by = false // 認証ユーザは被フォロー状態にある
var blocking = false // 認証ユーザからブロックした
var blocked_by = false // 認証ユーザからブロックされた(Misskeyのみ。Mastodonでは常にfalse)
var muting = false
var requested = false // 認証ユーザからのフォローは申請中である
var requested_by = false // 相手から認証ユーザへのフォローリクエスト申請中(Misskeyのみ。Mastodonでは常にfalse)
var following_reblogs = 0 // このユーザからのブーストをTLに表示する
var endorsed = false // ユーザをプロフィールで紹介する
var notifying = false // ユーザの投稿を通知する
var note: String? = null
// 認証ユーザからのフォロー状態
fun getFollowing(who: TootAccount?): Boolean {
return if (requested && !following && who != null && !who.locked) true else following
}
// 認証ユーザからのフォローリクエスト申請中状態
fun getRequested(who: TootAccount?): Boolean {
return if (requested && !following && who != null && !who.locked) false else requested
}
companion object : TableCompanion {
const val REBLOG_HIDE =
0 // don't show the boosts from target account will be shown on authorized user's home TL.
const val REBLOG_SHOW =
1 // show the boosts from target account will be shown on authorized user's home TL.
const val REBLOG_UNKNOWN = 2 // not following, or instance don't support hide reblog.
private val mMemoryCache = androidx.collection.LruCache<String, UserRelation>(2048)
private val log = LogCategory("UserRelationMisskey")
override val table = "user_relation_misskey"
val columnList: ColumnMeta.List = ColumnMeta.List(table, 30).apply {
createExtra = {
arrayOf(
"create unique index if not exists ${table}_id on $table($COL_DB_ID,$COL_WHO_ID)",
"create index if not exists ${table}_time on $table($COL_TIME_SAVE)",
)
}
deleteBeforeCreate = true
}
val COL_ID =
ColumnMeta(columnList, 0, BaseColumns._ID, "INTEGER PRIMARY KEY", primary = true)
private val COL_TIME_SAVE = ColumnMeta(columnList, 0, "time_save", "integer not null")
// SavedAccount のDB_ID。 疑似アカウント用のエントリは -2L
private val COL_DB_ID = ColumnMeta(columnList, 0, "db_id", "integer not null")
// ターゲットアカウントのID
val COL_WHO_ID = ColumnMeta(columnList, 0, "who_id", "text not null")
private val COL_FOLLOWING = ColumnMeta(columnList, 0, "following", "integer not null")
private val COL_FOLLOWED_BY = ColumnMeta(columnList, 0, "followed_by", "integer not null")
private val COL_BLOCKING = ColumnMeta(columnList, 0, "blocking", "integer not null")
private val COL_MUTING = ColumnMeta(columnList, 0, "muting", "integer not null")
private val COL_REQUESTED = ColumnMeta(columnList, 0, "requested", "integer not null")
private val COL_FOLLOWING_REBLOGS =
ColumnMeta(columnList, 0, "following_reblogs", "integer not null")
private val COL_ENDORSED = ColumnMeta(columnList, 32, "endorsed", "integer default 0")
private val COL_BLOCKED_BY = ColumnMeta(columnList, 34, "blocked_by", "integer default 0")
private val COL_REQUESTED_BY =
ColumnMeta(columnList, 35, "requested_by", "integer default 0")
private val COL_NOTE = ColumnMeta(columnList, 55, "note", "text default null")
private val COL_NOTIFYING = ColumnMeta(columnList, 58, "notifying", "integer default 0")
private const val DB_ID_PSEUDO = -2L
override fun onDBCreate(db: SQLiteDatabase) =
columnList.onDBCreate(db)
override fun onDBUpgrade(db: SQLiteDatabase, oldVersion: Int, newVersion: Int) =
columnList.onDBUpgrade(db, oldVersion, newVersion)
fun deleteOld(now: Long) {
try {
val expire = now - 86400000L * 365
appDatabase.delete(table, "$COL_TIME_SAVE<?", arrayOf(expire.toString()))
} catch (ex: Throwable) {
log.e(ex, "deleteOld failed.")
}
try {
// 旧型式のテーブルの古いデータの削除だけは時々回す
val table = "user_relation"
val COL_TIME_SAVE = "time_save"
val expire = now - 86400000L * 365
appDatabase.delete(table, "$COL_TIME_SAVE<?", arrayOf(expire.toString()))
} catch (_: Throwable) {
}
}
private fun key(dbId: Long, whoId: String) = "$dbId:$whoId"
private fun key(dbId: Long, whoId: EntityId) = key(dbId, whoId.toString())
private fun ContentValues.fromUserRelation(src: UserRelation) {
put(COL_FOLLOWING, src.following)
put(COL_FOLLOWED_BY, src.followed_by)
put(COL_BLOCKING, src.blocking)
put(COL_MUTING, src.muting)
put(COL_REQUESTED, src.requested)
put(COL_FOLLOWING_REBLOGS, src.following_reblogs)
put(COL_ENDORSED, src.endorsed)
put(COL_BLOCKED_BY, src.blocked_by)
put(COL_REQUESTED_BY, src.requested_by)
put(COL_NOTIFYING, src.notifying)
put(COL_NOTE, src.note) // may null
}
private fun ContentValues.fromTootRelationShip(src: TootRelationShip) {
put(COL_FOLLOWING, src.following)
put(COL_FOLLOWED_BY, src.followed_by)
put(COL_BLOCKING, src.blocking)
put(COL_MUTING, src.muting)
put(COL_REQUESTED, src.requested)
put(COL_FOLLOWING_REBLOGS, src.showing_reblogs)
put(COL_ENDORSED, src.endorsed)
put(COL_BLOCKED_BY, src.blocked_by)
put(COL_REQUESTED_BY, src.requested_by)
put(COL_NOTIFYING, src.notifying)
put(COL_NOTE, src.note) // may null
}
// マストドン用
fun save1Mastodon(now: Long, dbId: Long, src: TootRelationShip): UserRelation {
val id: String = src.id.toString()
try {
ContentValues().apply {
put(COL_TIME_SAVE, now)
put(COL_DB_ID, dbId)
put(COL_WHO_ID, id)
fromTootRelationShip(src)
}.let { appDatabase.replaceOrThrow(table, null, it) }
mMemoryCache.remove(key(dbId, id))
} catch (ex: Throwable) {
log.e(ex, "save failed.")
}
return load(dbId, id)
}
// マストドン用
fun saveListMastodon(now: Long, dbId: Long, srcList: Iterable<TootRelationShip>) {
val db = appDatabase
db.execSQL("BEGIN TRANSACTION")
val bOK = try {
val cv = ContentValues()
cv.put(COL_TIME_SAVE, now)
cv.put(COL_DB_ID, dbId)
for (src in srcList) {
val id = src.id.toString()
cv.put(COL_WHO_ID, id)
cv.fromTootRelationShip(src)
db.replaceOrThrow(table, null, cv)
}
true
} catch (ex: Throwable) {
log.trace(ex)
log.e(ex, "saveList failed.")
false
}
when {
!bOK -> db.execSQL("ROLLBACK TRANSACTION")
else -> {
db.execSQL("COMMIT TRANSACTION")
for (src in srcList) {
mMemoryCache.remove(key(dbId, src.id))
}
}
}
}
fun save1Misskey(now: Long, dbId: Long, whoId: String, src: UserRelation?) {
src ?: return
try {
ContentValues().apply {
put(COL_TIME_SAVE, now)
put(COL_DB_ID, dbId)
put(COL_WHO_ID, whoId)
fromUserRelation(src)
}.let { appDatabase.replaceOrThrow(table, null, it) }
mMemoryCache.remove(key(dbId, whoId))
} catch (ex: Throwable) {
log.e(ex, "save failed.")
}
}
fun saveListMisskey(
now: Long,
dbId: Long,
srcList: List<Map.Entry<EntityId, UserRelation>>,
start: Int,
end: Int,
) {
val db = appDatabase
db.execSQL("BEGIN TRANSACTION")
val bOK = try {
val cv = ContentValues()
cv.put(COL_TIME_SAVE, now)
cv.put(COL_DB_ID, dbId)
for (i in start until end) {
val entry = srcList[i]
val id = entry.key
val src = entry.value
cv.put(COL_WHO_ID, id.toString())
cv.fromUserRelation(src)
db.replaceOrThrow(table, null, cv)
}
true
} catch (ex: Throwable) {
log.trace(ex)
log.e(ex, "saveList failed.")
false
}
when {
!bOK -> db.execSQL("ROLLBACK TRANSACTION")
else -> {
db.execSQL("COMMIT TRANSACTION")
for (i in start until end) {
val entry = srcList[i]
val key = key(dbId, entry.key)
mMemoryCache.remove(key)
}
}
}
}
// Misskeyのリレーション取得APIから
fun saveListMisskeyRelationApi(now: Long, dbId: Long, list: ArrayList<TootRelationShip>) {
val db = appDatabase
db.execSQL("BEGIN TRANSACTION")
val bOK = try {
val cv = ContentValues()
cv.put(COL_TIME_SAVE, now)
cv.put(COL_DB_ID, dbId)
for (src in list) {
val id = src.id.toString()
cv.put(COL_WHO_ID, id)
cv.fromTootRelationShip(src)
db.replace(table, null, cv)
}
true
} catch (ex: Throwable) {
log.trace(ex)
log.e(ex, "saveListMisskeyRelationApi failed.")
false
}
when {
!bOK -> db.execSQL("ROLLBACK TRANSACTION")
else -> {
db.execSQL("COMMIT TRANSACTION")
for (src in list) {
mMemoryCache.remove(key(dbId, src.id))
}
}
}
}
private val loadWhere = "$COL_DB_ID=? and $COL_WHO_ID=?"
private val loadWhereArg = object : ThreadLocal<Array<String?>>() {
override fun initialValue(): Array<String?> = Array(2) { null }
}
fun load(dbId: Long, whoId: EntityId): UserRelation {
//
val key = key(dbId, whoId)
val cached: UserRelation? = mMemoryCache.get(key)
if (cached != null) return cached
val dst = load(dbId, whoId.toString())
mMemoryCache.put(key, dst)
return dst
}
fun load(dbId: Long, whoId: String): UserRelation {
try {
val where_arg = loadWhereArg.get() ?: arrayOfNulls<String?>(2)
where_arg[0] = dbId.toString()
where_arg[1] = whoId
appDatabase.query(table, null, loadWhere, where_arg, null, null, null)
.use { cursor ->
if (cursor.moveToNext()) {
val dst = UserRelation()
dst.following = cursor.getBoolean(COL_FOLLOWING)
dst.followed_by = cursor.getBoolean(COL_FOLLOWED_BY)
dst.blocking = cursor.getBoolean(COL_BLOCKING)
dst.muting = cursor.getBoolean(COL_MUTING)
dst.requested = cursor.getBoolean(COL_REQUESTED)
dst.following_reblogs = cursor.getInt(COL_FOLLOWING_REBLOGS)
dst.endorsed = cursor.getBoolean(COL_ENDORSED)
dst.blocked_by = cursor.getBoolean(COL_BLOCKED_BY)
dst.requested_by = cursor.getBoolean(COL_REQUESTED_BY)
dst.notifying = cursor.getBoolean(COL_NOTIFYING)
dst.note = cursor.getStringOrNull(COL_NOTE)
return dst
}
}
} catch (ex: Throwable) {
log.trace(ex)
log.e(ex, "load failed.")
}
return UserRelation()
}
// MisskeyはUserエンティティにユーザリレーションが含まれたり含まれなかったりする
fun fromAccount(parser: TootParser, src: JsonObject, id: EntityId) {
// アカウントのjsonがユーザリレーションを含まないなら何もしない
src["isFollowing"] ?: return
// プロフカラムで ユーザのプロフ(A)とアカウントTL(B)を順に取得すると
// (A)ではisBlockingに情報が入っているが、(B)では情報が入っていない
// 対策として(A)でリレーションを取得済みのユーザは(B)のタイミングではリレーションを読み捨てる
val map = parser.misskeyUserRelationMap
if (map.containsKey(id)) return
map[id] = UserRelation().apply {
following = src.optBoolean("isFollowing")
followed_by = src.optBoolean("isFollowed")
muting = src.optBoolean("isMuted")
blocking = src.optBoolean("isBlocking")
blocked_by = src.optBoolean("isBlocked")
endorsed = false
requested = src.optBoolean("hasPendingFollowRequestFromYou")
requested_by = src.optBoolean("hasPendingFollowRequestToYou")
}
}
fun loadPseudo(acct: Acct) = load(DB_ID_PSEUDO, acct.ascii)
fun createCursorPseudo(): Cursor =
appDatabase.query(
table,
arrayOf(COL_ID.name, COL_WHO_ID.name),
"$COL_DB_ID=$DB_ID_PSEUDO and ( $COL_MUTING=1 or $COL_BLOCKING=1 )",
null,
null,
null,
"$COL_WHO_ID asc"
)
fun deletePseudo(rowId: Long) {
try {
appDatabase.delete(table, "$COL_ID=$rowId", null)
} catch (ex: Throwable) {
log.trace(ex)
}
}
}
fun savePseudo(acct: String) =
save1Misskey(System.currentTimeMillis(), DB_ID_PSEUDO, acct, this)
}
| apache-2.0 | 4440d0ab566adbdd5e2a5b6dc07063c0 | 38.691293 | 102 | 0.518675 | 4.455938 | false | false | false | false |
paplorinc/intellij-community | platform/testGuiFramework/src/com/intellij/testGuiFramework/remote/server/JUnitServerImpl.kt | 7 | 6627 | /*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.testGuiFramework.remote.server
import com.intellij.testGuiFramework.remote.transport.MessageType
import com.intellij.testGuiFramework.remote.transport.TransportMessage
import org.apache.log4j.Logger
import java.io.InvalidClassException
import java.io.ObjectInputStream
import java.io.ObjectOutputStream
import java.net.ServerSocket
import java.net.Socket
import java.net.SocketException
import java.util.*
import java.util.concurrent.BlockingQueue
import java.util.concurrent.CountDownLatch
import java.util.concurrent.LinkedBlockingQueue
import java.util.concurrent.TimeUnit
/**
* @author Sergey Karashevich
*/
class JUnitServerImpl : JUnitServer {
private val SEND_THREAD = "JUnit Server Send Thread"
private val RECEIVE_THREAD = "JUnit Server Receive Thread"
private val postingMessages: BlockingQueue<TransportMessage> = LinkedBlockingQueue()
private val receivingMessages: BlockingQueue<TransportMessage> = LinkedBlockingQueue()
private val handlers: ArrayList<ServerHandler> = ArrayList()
private var failHandler: ((Throwable) -> Unit)? = null
private val LOG = Logger.getLogger("#com.intellij.testGuiFramework.remote.server.JUnitServerImpl")
private val serverSocket = ServerSocket(0)
private lateinit var serverSendThread: ServerSendThread
private lateinit var serverReceiveThread: ServerReceiveThread
private lateinit var connection: Socket
private var isStarted = false
private val IDE_STARTUP_TIMEOUT = 180000
private val port: Int
init {
port = serverSocket.localPort
serverSocket.soTimeout = IDE_STARTUP_TIMEOUT
}
override fun start() {
connection = serverSocket.accept()
LOG.info("Server accepted client on port: ${connection.port}")
serverSendThread = ServerSendThread()
serverSendThread.start()
serverReceiveThread = ServerReceiveThread()
serverReceiveThread.start()
isStarted = true
}
override fun isStarted(): Boolean = isStarted
override fun send(message: TransportMessage) {
postingMessages.put(message)
LOG.info("Add message to send pool: $message ")
}
override fun receive(): TransportMessage {
return receivingMessages.poll(IDE_STARTUP_TIMEOUT.toLong(), TimeUnit.MILLISECONDS)
?: throw SocketException("Client doesn't respond. Either the test has hanged or IDE crushed.")
}
override fun sendAndWaitAnswer(message: TransportMessage): Unit = sendAndWaitAnswerBase(message)
override fun sendAndWaitAnswer(message: TransportMessage, timeout: Long, timeUnit: TimeUnit): Unit = sendAndWaitAnswerBase(message, timeout, timeUnit)
private fun sendAndWaitAnswerBase(message: TransportMessage, timeout: Long = 0L, timeUnit: TimeUnit = TimeUnit.SECONDS) {
val countDownLatch = CountDownLatch(1)
val waitHandler = createCallbackServerHandler({ countDownLatch.countDown() }, message.id)
addHandler(waitHandler)
send(message)
if (timeout == 0L)
countDownLatch.await()
else
countDownLatch.await(timeout, timeUnit)
removeHandler(waitHandler)
}
override fun addHandler(serverHandler: ServerHandler) {
handlers.add(serverHandler)
}
override fun removeHandler(serverHandler: ServerHandler) {
handlers.remove(serverHandler)
}
override fun removeAllHandlers() {
handlers.clear()
}
override fun setFailHandler(failHandler: (Throwable) -> Unit) {
this.failHandler = failHandler
}
override fun isConnected(): Boolean {
return try {
connection.isConnected && !connection.isClosed
}
catch (lateInitException: UninitializedPropertyAccessException) {
false
}
}
override fun getPort(): Int = port
override fun stopServer() {
if (!isStarted) return
serverSendThread.interrupt()
LOG.info("Server Send Thread joined")
serverReceiveThread.interrupt()
LOG.info("Server Receive Thread joined")
connection.close()
isStarted = false
}
private fun createCallbackServerHandler(handler: (TransportMessage) -> Unit, id: Long)
= object : ServerHandler() {
override fun acceptObject(message: TransportMessage) = message.id == id
override fun handleObject(message: TransportMessage) {
handler(message)
}
}
private inner class ServerSendThread: Thread(SEND_THREAD) {
override fun run() {
LOG.info("Server Send Thread started")
ObjectOutputStream(connection.getOutputStream()).use { outputStream ->
try {
while (!connection.isClosed) {
val message = postingMessages.take()
LOG.info("Sending message: $message ")
outputStream.writeObject(message)
}
}
catch (e: Exception) {
when (e) {
is InterruptedException -> { /* ignore */ }
is InvalidClassException -> LOG.error("Probably client is down:", e)
else -> {
LOG.info(e)
failHandler?.invoke(e)
}
}
}
}
}
}
private inner class ServerReceiveThread: Thread(RECEIVE_THREAD) {
override fun run() {
LOG.info("Server Receive Thread started")
ObjectInputStream(connection.getInputStream()).use { inputStream ->
try {
while (!connection.isClosed) {
val obj = inputStream.readObject()
LOG.debug("Receiving message (DEBUG): $obj")
assert(obj is TransportMessage)
val message = obj as TransportMessage
if (message.type != MessageType.KEEP_ALIVE) LOG.info("Receiving message: $obj")
receivingMessages.put(message)
handlers.filter { it.acceptObject(message) }.forEach { it.handleObject(message) }
}
}
catch (e: Exception) {
when (e) {
is InterruptedException -> { /* ignore */ }
is InvalidClassException -> LOG.error("Probably serialization error:", e)
else -> {
LOG.info(e)
failHandler?.invoke(e)
}
}
}
}
}
}
} | apache-2.0 | 8a900cda7f3b3ddef0484cba935db8af | 31.811881 | 152 | 0.694432 | 4.771058 | false | false | false | false |
google/intellij-community | plugins/kotlin/jvm-debugger/evaluation/src/org/jetbrains/kotlin/idea/debugger/evaluate/variables/VariableFinder.kt | 1 | 21584 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.idea.debugger.evaluate.variables
import com.intellij.debugger.engine.JavaValue
import com.intellij.debugger.engine.evaluation.EvaluationContextImpl
import com.intellij.debugger.jdi.LocalVariableProxyImpl
import com.intellij.debugger.jdi.StackFrameProxyImpl
import com.sun.jdi.*
import org.jetbrains.kotlin.codegen.AsmUtil
import org.jetbrains.kotlin.codegen.AsmUtil.getCapturedFieldName
import org.jetbrains.kotlin.codegen.AsmUtil.getLabeledThisName
import org.jetbrains.kotlin.codegen.coroutines.CONTINUATION_VARIABLE_NAME
import org.jetbrains.kotlin.codegen.coroutines.SUSPEND_FUNCTION_COMPLETION_PARAMETER_NAME
import org.jetbrains.kotlin.codegen.inline.INLINE_FUN_VAR_SUFFIX
import org.jetbrains.kotlin.codegen.inline.INLINE_TRANSFORMATION_SUFFIX
import org.jetbrains.kotlin.idea.debugger.base.util.*
import org.jetbrains.kotlin.idea.debugger.base.util.evaluate.ExecutionContext
import org.jetbrains.kotlin.idea.debugger.core.stackFrame.InlineStackFrameProxyImpl
import org.jetbrains.kotlin.idea.debugger.coroutine.proxy.CoroutineStackFrameProxyImpl
import org.jetbrains.kotlin.idea.debugger.evaluate.compilation.CodeFragmentParameter
import org.jetbrains.kotlin.idea.debugger.evaluate.compilation.CodeFragmentParameter.Kind
import org.jetbrains.kotlin.idea.debugger.evaluate.compilation.DebugLabelPropertyDescriptorProvider
import org.jetbrains.kotlin.load.java.JvmAbi
import org.jetbrains.kotlin.utils.addToStdlib.safeAs
import kotlin.coroutines.Continuation
import com.sun.jdi.Type as JdiType
import org.jetbrains.org.objectweb.asm.Type as AsmType
class VariableFinder(val context: ExecutionContext) {
private val frameProxy = context.frameProxy
companion object {
private val USE_UNSAFE_FALLBACK: Boolean
get() = true
private fun getCapturedVariableNameRegex(capturedName: String): Regex {
val escapedName = Regex.escape(capturedName)
val escapedSuffix = Regex.escape(INLINE_TRANSFORMATION_SUFFIX)
return Regex("^$escapedName(?:$escapedSuffix)?$")
}
}
val evaluatorValueConverter = EvaluatorValueConverter(context)
val refWrappers: List<RefWrapper>
get() = mutableRefWrappers
private val mutableRefWrappers = mutableListOf<RefWrapper>()
class RefWrapper(val localVariableName: String, val wrapper: Value?)
sealed class VariableKind(val asmType: AsmType) {
abstract fun capturedNameMatches(name: String): Boolean
class Ordinary(val name: String, asmType: AsmType, val isDelegated: Boolean) : VariableKind(asmType) {
private val capturedNameRegex = getCapturedVariableNameRegex(getCapturedFieldName(this.name))
override fun capturedNameMatches(name: String) = capturedNameRegex.matches(name)
}
// TODO Support overloaded local functions
class LocalFunction(val name: String, asmType: AsmType) : VariableKind(asmType) {
@Suppress("ConvertToStringTemplate")
override fun capturedNameMatches(name: String) = name == "$" + name
}
class UnlabeledThis(asmType: AsmType) : VariableKind(asmType) {
override fun capturedNameMatches(name: String) =
(name == AsmUtil.CAPTURED_RECEIVER_FIELD || name.startsWith(getCapturedFieldName(AsmUtil.LABELED_THIS_FIELD)))
}
class OuterClassThis(asmType: AsmType) : VariableKind(asmType) {
override fun capturedNameMatches(name: String) = false
}
class FieldVar(val fieldName: String, asmType: AsmType) : VariableKind(asmType) {
// Captured 'field' are not supported yet
override fun capturedNameMatches(name: String) = false
}
class ExtensionThis(val label: String, asmType: AsmType) : VariableKind(asmType) {
val parameterName = getLabeledThisName(label, AsmUtil.LABELED_THIS_PARAMETER, AsmUtil.RECEIVER_PARAMETER_NAME)
val fieldName = getLabeledThisName(label, getCapturedFieldName(AsmUtil.LABELED_THIS_FIELD), AsmUtil.CAPTURED_RECEIVER_FIELD)
private val capturedNameRegex = getCapturedVariableNameRegex(fieldName)
override fun capturedNameMatches(name: String) = capturedNameRegex.matches(name)
}
}
class Result(val value: Value?)
private class NamedEntity(val name: String, val lazyType: Lazy<JdiType?>, val lazyValue: Lazy<Value?>) {
val type: JdiType?
get() = lazyType.value
val value: Value?
get() = lazyValue.value
companion object {
fun of(field: Field, owner: ObjectReference): NamedEntity {
val type = lazy(LazyThreadSafetyMode.PUBLICATION) { field.safeType() }
val value = lazy(LazyThreadSafetyMode.PUBLICATION) { owner.getValue(field) }
return NamedEntity(field.name(), type, value)
}
fun of(variable: LocalVariableProxyImpl, frameProxy: StackFrameProxyImpl): NamedEntity {
val type = lazy(LazyThreadSafetyMode.PUBLICATION) { variable.safeType() }
val value = lazy(LazyThreadSafetyMode.PUBLICATION) { frameProxy.getValue(variable) }
return NamedEntity(variable.name(), type, value)
}
fun of(variable: JavaValue, context: EvaluationContextImpl): NamedEntity {
val type = lazy(LazyThreadSafetyMode.PUBLICATION) { variable.descriptor.type }
val value = lazy(LazyThreadSafetyMode.PUBLICATION) { variable.descriptor.safeCalcValue(context) }
return NamedEntity(variable.name, type, value)
}
}
}
fun find(parameter: CodeFragmentParameter, asmType: AsmType): Result? {
return when (parameter.kind) {
Kind.ORDINARY -> findOrdinary(VariableKind.Ordinary(parameter.name, asmType, isDelegated = false))
Kind.DELEGATED -> findOrdinary(VariableKind.Ordinary(parameter.name, asmType, isDelegated = true))
Kind.FAKE_JAVA_OUTER_CLASS -> thisObject()?.let { Result(it) }
Kind.EXTENSION_RECEIVER -> findExtensionThis(VariableKind.ExtensionThis(parameter.name, asmType))
Kind.LOCAL_FUNCTION -> findLocalFunction(VariableKind.LocalFunction(parameter.name, asmType))
Kind.DISPATCH_RECEIVER -> findDispatchThis(VariableKind.OuterClassThis(asmType))
Kind.COROUTINE_CONTEXT -> findCoroutineContext()
Kind.FIELD_VAR -> findFieldVariable(VariableKind.FieldVar(parameter.name, asmType))
Kind.DEBUG_LABEL -> findDebugLabel(parameter.name)
}
}
private fun findOrdinary(kind: VariableKind.Ordinary): Result? {
val variables = frameProxy.safeVisibleVariables()
// Local variables – direct search
findLocalVariable(variables, kind, kind.name)?.let { return it }
// Recursive search in local receiver variables
findCapturedVariableInReceiver(variables, kind)?.let { return it }
// Recursive search in captured this
return findCapturedVariableInContainingThis(kind)
}
private fun findFieldVariable(kind: VariableKind.FieldVar): Result? {
val thisObject = thisObject()
if (thisObject != null) {
val field = thisObject.referenceType().fieldByName(kind.fieldName) ?: return null
return Result(thisObject.getValue(field))
} else {
val containingType = frameProxy.safeLocation()?.declaringType() ?: return null
val field = containingType.fieldByName(kind.fieldName) ?: return null
return Result(containingType.getValue(field))
}
}
private fun findLocalFunction(kind: VariableKind.LocalFunction): Result? {
val variables = frameProxy.safeVisibleVariables()
// Local variables – direct search, new convention
val newConventionName = AsmUtil.LOCAL_FUNCTION_VARIABLE_PREFIX + kind.name
findLocalVariable(variables, kind, newConventionName)?.let { return it }
// Local variables – direct search, old convention (before 1.3.30)
findLocalVariable(variables, kind, kind.name + "$")?.let { return it }
// Recursive search in local receiver variables
findCapturedVariableInReceiver(variables, kind)?.let { return it }
// Recursive search in captured this
return findCapturedVariableInContainingThis(kind)
}
private fun findCapturedVariableInContainingThis(kind: VariableKind): Result? {
if (frameProxy is CoroutineStackFrameProxyImpl && frameProxy.isCoroutineScopeAvailable()) {
findCapturedVariable(kind, frameProxy.thisObject())?.let { return it }
return findCapturedVariable(kind, frameProxy.continuation)
}
val containingThis = thisObject() ?: return null
return findCapturedVariable(kind, containingThis)
}
private fun findExtensionThis(kind: VariableKind.ExtensionThis): Result? {
val variables = frameProxy.safeVisibleVariables()
// Local variables – direct search
val namePredicate = fun(name: String) = name == kind.parameterName || name.startsWith(kind.parameterName + '$')
findLocalVariable(variables, kind, namePredicate)?.let { return it }
// Recursive search in local receiver variables
findCapturedVariableInReceiver(variables, kind)?.let { return it }
// Recursive search in captured this
findCapturedVariableInContainingThis(kind)?.let { return it }
if (USE_UNSAFE_FALLBACK) {
// Find an unlabeled this with the compatible type
findUnlabeledThis(VariableKind.UnlabeledThis(kind.asmType))?.let { return it }
}
return null
}
private fun findDispatchThis(kind: VariableKind.OuterClassThis): Result? {
findCapturedVariableInContainingThis(kind)?.let { return it }
if (isInsideDefaultImpls()) {
val variables = frameProxy.safeVisibleVariables()
findLocalVariable(variables, kind, AsmUtil.THIS_IN_DEFAULT_IMPLS)?.let { return it }
}
val variables = frameProxy.safeVisibleVariables()
val inlineDepth = getInlineDepth(variables)
if (inlineDepth > 0) {
variables.namedEntitySequence()
.filter { it.name.matches(INLINED_THIS_REGEX) && getInlineDepth(it.name) == inlineDepth && kind.typeMatches(it.type) }
.mapNotNull { it.unwrapAndCheck(kind) }
.firstOrNull()
?.let { return it }
}
if (USE_UNSAFE_FALLBACK) {
// Find an unlabeled this with the compatible type
findUnlabeledThis(VariableKind.UnlabeledThis(kind.asmType))?.let { return it }
}
return null
}
private fun findDebugLabel(name: String): Result? {
val markupMap = DebugLabelPropertyDescriptorProvider.getMarkupMap(context.debugProcess)
for ((value, markup) in markupMap) {
if (markup.text == name) {
return Result(value)
}
}
return null
}
private fun findUnlabeledThis(kind: VariableKind.UnlabeledThis): Result? {
val variables = frameProxy.safeVisibleVariables()
// Recursive search in local receiver variables
findCapturedVariableInReceiver(variables, kind)?.let { return it }
return findCapturedVariableInContainingThis(kind)
}
private fun findLocalVariable(variables: List<LocalVariableProxyImpl>, kind: VariableKind, name: String): Result? {
return findLocalVariable(variables, kind) { it == name }
}
private fun findLocalVariable(
variables: List<LocalVariableProxyImpl>,
kind: VariableKind,
namePredicate: (String) -> Boolean
): Result? {
val inlineDepth =
frameProxy.safeAs<InlineStackFrameProxyImpl>()?.inlineDepth
?: getInlineDepth(variables)
findLocalVariable(variables, kind, inlineDepth, namePredicate)?.let { return it }
// Try to find variables outside of inline functions as well
if (inlineDepth > 0 && USE_UNSAFE_FALLBACK) {
findLocalVariable(variables, kind, 0, namePredicate)?.let { return it }
}
return null
}
private fun findLocalVariable(
variables: List<LocalVariableProxyImpl>,
kind: VariableKind,
inlineDepth: Int,
namePredicate: (String) -> Boolean
): Result? {
val actualPredicate: (String) -> Boolean
if (inlineDepth > 0) {
actualPredicate = fun(name: String): Boolean {
var endIndex = name.length
var depth = 0
val suffixLen = INLINE_FUN_VAR_SUFFIX.length
while (endIndex >= suffixLen) {
if (name.substring(endIndex - suffixLen, endIndex) != INLINE_FUN_VAR_SUFFIX) {
break
}
depth++
endIndex -= suffixLen
}
return namePredicate(name.take(endIndex)) && getInlineDepth(name) == inlineDepth
}
} else {
actualPredicate = namePredicate
}
val namedEntities = variables.namedEntitySequence() + getCoroutineStackFrameNamedEntities()
for (item in namedEntities) {
if (!actualPredicate(item.name) || !kind.typeMatches(item.type)) {
continue
}
val rawValue = item.value
val result = evaluatorValueConverter.coerce(getUnwrapDelegate(kind, rawValue), kind.asmType) ?: continue
if (!rawValue.isRefType && result.value.isRefType) {
// Local variable was wrapped into a Ref instance
mutableRefWrappers += RefWrapper(item.name, result.value)
}
return result
}
return null
}
private fun getCoroutineStackFrameNamedEntities() =
if (frameProxy is CoroutineStackFrameProxyImpl) {
frameProxy.spilledVariables.namedEntitySequence(context.evaluationContext)
} else {
emptySequence()
}
private fun isInsideDefaultImpls(): Boolean {
val declaringType = frameProxy.safeLocation()?.declaringType() ?: return false
return declaringType.name().endsWith(JvmAbi.DEFAULT_IMPLS_SUFFIX)
}
private fun findCoroutineContext(): Result? {
val method = frameProxy.safeLocation()?.safeMethod() ?: return null
val result = findCoroutineContextForLambda(method) ?: findCoroutineContextForMethod(method) ?: return null
return Result(result)
}
private fun findCoroutineContextForLambda(method: Method): ObjectReference? {
if (method.name() != "invokeSuspend" || method.signature() != "(Ljava/lang/Object;)Ljava/lang/Object;" ||
frameProxy !is CoroutineStackFrameProxyImpl) {
return null
}
val continuation = frameProxy.continuation ?: return null
val continuationType = continuation.referenceType()
if (SUSPEND_LAMBDA_CLASSES.none { continuationType.isSubtype(it) }) {
return null
}
return findCoroutineContextForContinuation(continuation)
}
private fun findCoroutineContextForMethod(method: Method): ObjectReference? {
if (CONTINUATION_TYPE.descriptor + ")" !in method.signature()) {
return null
}
val continuationVariable = frameProxy.safeVisibleVariableByName(CONTINUATION_VARIABLE_NAME)
?: frameProxy.safeVisibleVariableByName(SUSPEND_FUNCTION_COMPLETION_PARAMETER_NAME)
?: return null
val continuation = frameProxy.getValue(continuationVariable) as? ObjectReference ?: return null
return findCoroutineContextForContinuation(continuation)
}
private fun findCoroutineContextForContinuation(continuation: ObjectReference): ObjectReference? {
val continuationType = (continuation.referenceType() as? ClassType)
?.allInterfaces()?.firstOrNull { it.name() == Continuation::class.java.name }
?: return null
val getContextMethod = continuationType
.methodsByName("getContext", "()Lkotlin/coroutines/CoroutineContext;").firstOrNull()
?: return null
return context.invokeMethod(continuation, getContextMethod, emptyList()) as? ObjectReference
}
private fun findCapturedVariableInReceiver(variables: List<LocalVariableProxyImpl>, kind: VariableKind): Result? {
fun isReceiverOrPassedThis(name: String) =
name.startsWith(AsmUtil.LABELED_THIS_PARAMETER)
|| name == AsmUtil.RECEIVER_PARAMETER_NAME
|| name == AsmUtil.THIS_IN_DEFAULT_IMPLS
|| INLINED_THIS_REGEX.matches(name)
// In the old backend captured variables are stored as fields of a generated lambda class.
// In the IR backend SAM lambdas are generated as functions, and captured variables are
// stored in the LVT table.
if (kind is VariableKind.ExtensionThis || kind is VariableKind.Ordinary) {
variables.namedEntitySequence()
.filter { kind.capturedNameMatches(it.name) && kind.typeMatches(it.type) }
.mapNotNull { it.unwrapAndCheck(kind) }
.firstOrNull()
?.let { return it }
}
return variables.namedEntitySequence()
.filter { isReceiverOrPassedThis(it.name) }
.mapNotNull { findCapturedVariable(kind, it.value) }
.firstOrNull()
}
private fun findCapturedVariable(kind: VariableKind, parentFactory: () -> Value?): Result? {
val parent = getUnwrapDelegate(kind, parentFactory())
return findCapturedVariable(kind, parent)
}
private fun findCapturedVariable(kind: VariableKind, parent: Value?): Result? {
val acceptsParentValue = kind is VariableKind.UnlabeledThis || kind is VariableKind.OuterClassThis
if (parent != null && acceptsParentValue && kind.typeMatches(parent.type())) {
return Result(parent)
}
val fields = (parent as? ObjectReference)?.referenceType()?.fields() ?: return null
if (kind !is VariableKind.OuterClassThis) {
// Captured variables - direct search
fields.namedEntitySequence(parent)
.filter { kind.capturedNameMatches(it.name) && kind.typeMatches(it.type) }
.mapNotNull { it.unwrapAndCheck(kind) }
.firstOrNull()
?.let { return it }
// Recursive search in captured receivers
fields.namedEntitySequence(parent)
.filter { isCapturedReceiverFieldName(it.name) }
.mapNotNull { findCapturedVariable(kind, it.value) }
.firstOrNull()
?.let { return it }
}
// Recursive search in outer and captured this
fields.namedEntitySequence(parent)
.filter { it.name == AsmUtil.THIS_IN_DEFAULT_IMPLS || it.name == AsmUtil.CAPTURED_THIS_FIELD }
.mapNotNull { findCapturedVariable(kind, it.value) }
.firstOrNull()
?.let { return it }
return null
}
private fun getUnwrapDelegate(kind: VariableKind, rawValue: Value?): Value? {
if (kind !is VariableKind.Ordinary || !kind.isDelegated) {
return rawValue
}
val delegateValue = rawValue as? ObjectReference ?: return rawValue
val getValueMethod = delegateValue.referenceType()
.methodsByName("getValue", "()Ljava/lang/Object;").firstOrNull()
?: return rawValue
return context.invokeMethod(delegateValue, getValueMethod, emptyList())
}
private fun isCapturedReceiverFieldName(name: String): Boolean {
return name.startsWith(getCapturedFieldName(AsmUtil.LABELED_THIS_FIELD))
|| name == AsmUtil.CAPTURED_RECEIVER_FIELD
}
private fun VariableKind.typeMatches(actualType: JdiType?): Boolean {
if (this is VariableKind.Ordinary && isDelegated) {
// We can't figure out the actual type of the value yet.
// No worries: it will be checked again (and more carefully) in `unwrapAndCheck()`.
return true
}
return evaluatorValueConverter.typeMatches(asmType, actualType)
}
private fun NamedEntity.unwrapAndCheck(kind: VariableKind): Result? {
return evaluatorValueConverter.coerce(getUnwrapDelegate(kind, value), kind.asmType)
}
private fun List<Field>.namedEntitySequence(owner: ObjectReference): Sequence<NamedEntity> {
return asSequence().map { NamedEntity.of(it, owner) }
}
private fun List<LocalVariableProxyImpl>.namedEntitySequence(): Sequence<NamedEntity> {
return asSequence().map { NamedEntity.of(it, frameProxy) }
}
private fun List<JavaValue>.namedEntitySequence(context: EvaluationContextImpl): Sequence<NamedEntity> {
return asSequence().map { NamedEntity.of(it, context) }
}
private fun thisObject(): ObjectReference? {
val thisObjectFromEvaluation = context.evaluationContext.computeThisObject() as? ObjectReference
if (thisObjectFromEvaluation != null) {
return thisObjectFromEvaluation
}
return frameProxy.thisObject()
}
}
| apache-2.0 | c190976003d8ef694ca22b423107f2c8 | 42.152 | 136 | 0.66713 | 5.398049 | false | false | false | false |
google/intellij-community | plugins/kotlin/jvm-debugger/evaluation/src/org/jetbrains/kotlin/idea/debugger/evaluate/KotlinCodeFragmentFactory.kt | 2 | 14118 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.idea.debugger.evaluate
import com.intellij.debugger.DebuggerManagerEx
import com.intellij.debugger.engine.DebugProcessImpl
import com.intellij.debugger.engine.JavaDebuggerEvaluator
import com.intellij.debugger.engine.evaluation.CodeFragmentFactory
import com.intellij.debugger.engine.evaluation.TextWithImports
import com.intellij.debugger.engine.events.DebuggerCommandImpl
import com.intellij.debugger.impl.DebuggerContextImpl
import com.intellij.ide.highlighter.JavaFileType
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Key
import com.intellij.psi.*
import com.intellij.psi.util.PsiTreeUtil
import com.intellij.psi.util.PsiTypesUtil
import com.intellij.util.IncorrectOperationException
import com.intellij.util.concurrency.Semaphore
import com.sun.jdi.AbsentInformationException
import com.sun.jdi.InvalidStackFrameException
import org.jetbrains.annotations.TestOnly
import org.jetbrains.kotlin.idea.KotlinFileType
import org.jetbrains.kotlin.idea.base.projectStructure.hasKotlinJvmRuntime
import org.jetbrains.kotlin.idea.core.syncNonBlockingReadAction
import org.jetbrains.kotlin.idea.core.util.CodeFragmentUtils
import org.jetbrains.kotlin.idea.debugger.base.util.evaluate.KotlinDebuggerEvaluator
import org.jetbrains.kotlin.idea.debugger.evaluate.compilation.DebugLabelPropertyDescriptorProvider
import org.jetbrains.kotlin.idea.debugger.core.getContextElement
import org.jetbrains.kotlin.idea.debugger.base.util.hopelessAware
import org.jetbrains.kotlin.idea.j2k.J2kPostProcessor
import org.jetbrains.kotlin.idea.j2k.convertToKotlin
import org.jetbrains.kotlin.idea.j2k.j2kText
import org.jetbrains.kotlin.idea.util.application.executeWriteCommand
import org.jetbrains.kotlin.idea.util.application.isUnitTestMode
import org.jetbrains.kotlin.idea.util.application.runReadAction
import org.jetbrains.kotlin.j2k.AfterConversionPass
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.quoteIfNeeded
import org.jetbrains.kotlin.types.KotlinType
import java.util.concurrent.atomic.AtomicReference
class KotlinCodeFragmentFactory : CodeFragmentFactory() {
override fun createCodeFragment(item: TextWithImports, context: PsiElement?, project: Project): JavaCodeFragment {
val contextElement = getContextElement(context)
val codeFragment = KtBlockCodeFragment(project, "fragment.kt", item.text, initImports(item.imports), contextElement)
supplyDebugInformation(item, codeFragment, context)
codeFragment.putCopyableUserData(CodeFragmentUtils.RUNTIME_TYPE_EVALUATOR) { expression: KtExpression ->
val debuggerContext = DebuggerManagerEx.getInstanceEx(project).context
val debuggerSession = debuggerContext.debuggerSession
if (debuggerSession == null || debuggerContext.suspendContext == null) {
null
} else {
val semaphore = Semaphore()
semaphore.down()
val nameRef = AtomicReference<KotlinType>()
val worker = object : KotlinRuntimeTypeEvaluator(
null, expression, debuggerContext, ProgressManager.getInstance().progressIndicator!!
) {
override fun typeCalculationFinished(type: KotlinType?) {
nameRef.set(type)
semaphore.up()
}
}
debuggerContext.debugProcess?.managerThread?.invoke(worker)
for (i in 0..50) {
ProgressManager.checkCanceled()
if (semaphore.waitFor(20)) break
}
nameRef.get()
}
}
if (contextElement != null && contextElement !is KtElement) {
codeFragment.putCopyableUserData(KtCodeFragment.FAKE_CONTEXT_FOR_JAVA_FILE) {
val emptyFile = createFakeFileWithJavaContextElement("", contextElement)
val debuggerContext = DebuggerManagerEx.getInstanceEx(project).context
val debuggerSession = debuggerContext.debuggerSession
if ((debuggerSession == null || debuggerContext.suspendContext == null) &&
!isUnitTestMode()
) {
LOG.warn("Couldn't create fake context element for java file, debugger isn't paused on breakpoint")
return@putCopyableUserData emptyFile
}
val frameInfo = getFrameInfo(contextElement, debuggerContext) ?: run {
val position = "${debuggerContext.sourcePosition?.file?.name}:${debuggerContext.sourcePosition?.line}"
LOG.warn("Couldn't get info about 'this' and local variables for $position")
return@putCopyableUserData emptyFile
}
val fakeFunctionText = buildString {
append("fun ")
val thisType = frameInfo.thisObject?.asProperty()?.typeReference?.typeElement?.unwrapNullableType()
if (thisType != null) {
append(thisType.text).append('.')
}
append(FAKE_JAVA_CONTEXT_FUNCTION_NAME).append("() {\n")
for (variable in frameInfo.variables) {
val text = variable.asProperty()?.text ?: continue
append(" ").append(text).append("\n")
}
// There should be at least one declaration inside the function (or 'fakeContext' below won't work).
append(" val _debug_context_val = 1\n")
append("}")
}
val fakeFile = createFakeFileWithJavaContextElement(fakeFunctionText, contextElement)
val fakeFunction = fakeFile.declarations.firstOrNull() as? KtFunction
val fakeContext = fakeFunction?.bodyBlockExpression?.statements?.lastOrNull()
return@putCopyableUserData fakeContext ?: emptyFile
}
}
return codeFragment
}
private fun KtTypeElement.unwrapNullableType(): KtTypeElement {
return if (this is KtNullableType) innerType ?: this else this
}
private fun supplyDebugInformation(item: TextWithImports, codeFragment: KtCodeFragment, context: PsiElement?) {
val project = codeFragment.project
val debugProcess = getDebugProcess(project, context) ?: return
DebugLabelPropertyDescriptorProvider(codeFragment, debugProcess).supplyDebugLabels()
val evaluationType = when (val evaluator = debugProcess.session.xDebugSession?.currentStackFrame?.evaluator) {
is KotlinDebuggerEvaluator -> evaluator.getType(item)
is JavaDebuggerEvaluator -> KotlinDebuggerEvaluator.EvaluationType.FROM_JAVA
else -> KotlinDebuggerEvaluator.EvaluationType.UNKNOWN
}
codeFragment.putUserData(EVALUATION_TYPE, evaluationType)
}
private fun getDebugProcess(project: Project, context: PsiElement?): DebugProcessImpl? {
return if (isUnitTestMode()) {
context?.getCopyableUserData(DEBUG_CONTEXT_FOR_TESTS)?.debugProcess
} else {
DebuggerManagerEx.getInstanceEx(project).context.debugProcess
}
}
private fun getFrameInfo(contextElement: PsiElement?, debuggerContext: DebuggerContextImpl): FrameInfo? {
val semaphore = Semaphore()
semaphore.down()
var frameInfo: FrameInfo? = null
val worker = object : DebuggerCommandImpl() {
override fun action() {
try {
val frameProxy = hopelessAware {
if (isUnitTestMode()) {
contextElement?.getCopyableUserData(DEBUG_CONTEXT_FOR_TESTS)?.frameProxy
} else {
debuggerContext.frameProxy
}
}
frameInfo = FrameInfo.from(debuggerContext.project, frameProxy)
} catch (ignored: AbsentInformationException) {
// Debug info unavailable
} catch (ignored: InvalidStackFrameException) {
// Thread is resumed, the frame we have is not valid anymore
} finally {
semaphore.up()
}
}
}
debuggerContext.debugProcess?.managerThread?.invoke(worker)
for (i in 0..50) {
if (semaphore.waitFor(20)) break
}
return frameInfo
}
private fun initImports(imports: String?): String? {
if (!imports.isNullOrEmpty()) {
return imports.split(KtCodeFragment.IMPORT_SEPARATOR)
.mapNotNull { fixImportIfNeeded(it) }
.joinToString(KtCodeFragment.IMPORT_SEPARATOR)
}
return null
}
private fun fixImportIfNeeded(import: String): String? {
// skip arrays
if (import.endsWith("[]")) {
return fixImportIfNeeded(import.removeSuffix("[]").trim())
}
// skip primitive types
if (PsiTypesUtil.boxIfPossible(import) != import) {
return null
}
return import
}
override fun createPresentationCodeFragment(item: TextWithImports, context: PsiElement?, project: Project): JavaCodeFragment {
val kotlinCodeFragment = createCodeFragment(item, context, project)
if (PsiTreeUtil.hasErrorElements(kotlinCodeFragment) && kotlinCodeFragment is KtCodeFragment) {
val javaExpression = try {
PsiElementFactory.getInstance(project).createExpressionFromText(item.text, context)
} catch (e: IncorrectOperationException) {
null
}
val importList = try {
kotlinCodeFragment.importsAsImportList()?.let {
(PsiFileFactory.getInstance(project).createFileFromText(
"dummy.java", JavaFileType.INSTANCE, it.text
) as? PsiJavaFile)?.importList
}
} catch (e: IncorrectOperationException) {
null
}
if (javaExpression != null && !PsiTreeUtil.hasErrorElements(javaExpression)) {
var convertedFragment: KtExpressionCodeFragment? = null
project.executeWriteCommand(KotlinDebuggerEvaluationBundle.message("j2k.expression")) {
try {
val (elementResults, _, conversionContext) = javaExpression.convertToKotlin() ?: return@executeWriteCommand
val newText = elementResults.singleOrNull()?.text
val newImports = importList?.j2kText()
if (newText != null) {
convertedFragment = KtExpressionCodeFragment(
project,
kotlinCodeFragment.name,
newText,
newImports,
kotlinCodeFragment.context
)
AfterConversionPass(project, J2kPostProcessor(formatCode = false))
.run(
convertedFragment!!,
conversionContext,
range = null,
onPhaseChanged = null
)
}
} catch (e: Throwable) {
// ignored because text can be invalid
LOG.error("Couldn't convert expression:\n`${javaExpression.text}`", e)
}
}
return convertedFragment ?: kotlinCodeFragment
}
}
return kotlinCodeFragment
}
override fun isContextAccepted(contextElement: PsiElement?): Boolean = runReadAction {
when {
// PsiCodeBlock -> DummyHolder -> originalElement
contextElement is PsiCodeBlock -> isContextAccepted(contextElement.context?.context)
contextElement == null -> false
contextElement.language == KotlinFileType.INSTANCE.language -> true
contextElement.language == JavaFileType.INSTANCE.language -> {
val project = contextElement.project
val scope = contextElement.resolveScope
syncNonBlockingReadAction(project) { scope.hasKotlinJvmRuntime(project) }
}
else -> false
}
}
override fun getFileType(): KotlinFileType = KotlinFileType.INSTANCE
override fun getEvaluatorBuilder() = KotlinEvaluatorBuilder
companion object {
private val LOG = Logger.getInstance(this::class.java)
@get:TestOnly
val DEBUG_CONTEXT_FOR_TESTS: Key<DebuggerContextImpl> = Key.create("DEBUG_CONTEXT_FOR_TESTS")
val EVALUATION_TYPE: Key<KotlinDebuggerEvaluator.EvaluationType> = Key.create("DEBUG_EVALUATION_TYPE")
const val FAKE_JAVA_CONTEXT_FUNCTION_NAME = "_java_locals_debug_fun_"
}
private fun createFakeFileWithJavaContextElement(funWithLocalVariables: String, javaContext: PsiElement): KtFile {
val javaFile = javaContext.containingFile as? PsiJavaFile
val sb = StringBuilder()
javaFile?.packageName?.takeUnless { it.isBlank() }?.let {
sb.append("package ").append(it.quoteIfNeeded()).append("\n")
}
javaFile?.importList?.let { sb.append(it.text).append("\n") }
sb.append(funWithLocalVariables)
return KtPsiFactory(javaContext.project).createAnalyzableFile("fakeFileForJavaContextInDebugger.kt", sb.toString(), javaContext)
}
}
| apache-2.0 | a3267d1da79bbf3b814bb2a4bcd35ec6 | 43.396226 | 136 | 0.62608 | 5.865393 | false | false | false | false |
JetBrains/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/ConvertLambdaLineIntention.kt | 1 | 3236 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.intentions
import com.intellij.openapi.editor.Editor
import com.intellij.psi.PsiComment
import org.jetbrains.kotlin.idea.base.psi.getLineNumber
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.codeinsight.api.classic.intentions.SelfTargetingIntention
import org.jetbrains.kotlin.idea.codeinsight.utils.isRedundantSemicolon
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.KtLambdaExpression
import org.jetbrains.kotlin.psi.KtPsiFactory
import org.jetbrains.kotlin.psi.psiUtil.allChildren
import org.jetbrains.kotlin.psi.psiUtil.getNextSiblingIgnoringWhitespace
import org.jetbrains.kotlin.psi.psiUtil.getPrevSiblingIgnoringWhitespace
sealed class ConvertLambdaLineIntention(private val toMultiLine: Boolean) : SelfTargetingIntention<KtLambdaExpression>(
KtLambdaExpression::class.java,
KotlinBundle.lazyMessage("intention.convert.lambda.line", 1.takeIf { toMultiLine } ?: 0),
) {
override fun isApplicableTo(element: KtLambdaExpression, caretOffset: Int): Boolean {
val functionLiteral = element.functionLiteral
val body = functionLiteral.bodyBlockExpression ?: return false
val startLine = functionLiteral.getLineNumber(start = true)
val endLine = functionLiteral.getLineNumber(start = false)
return if (toMultiLine) {
startLine == endLine
} else {
if (startLine == endLine) return false
val allChildren = body.allChildren
if (allChildren.any { it is PsiComment && it.node.elementType == KtTokens.EOL_COMMENT }) return false
val first = allChildren.first?.getNextSiblingIgnoringWhitespace(withItself = true) ?: return true
val last = allChildren.last?.getPrevSiblingIgnoringWhitespace(withItself = true)
first.getLineNumber(start = true) == last?.getLineNumber(start = false)
}
}
override fun applyTo(element: KtLambdaExpression, editor: Editor?) {
val functionLiteral = element.functionLiteral
val body = functionLiteral.bodyBlockExpression ?: return
val psiFactory = KtPsiFactory(element.project)
if (toMultiLine) {
body.allChildren.forEach {
if (it.node.elementType == KtTokens.SEMICOLON) {
body.addAfter(psiFactory.createNewLine(), it)
if (isRedundantSemicolon(it)) it.delete()
}
}
}
val bodyText = body.text
val startLineBreak = if (toMultiLine) "\n" else ""
val endLineBreak = if (toMultiLine && bodyText != "") "\n" else ""
element.replace(
psiFactory.createLambdaExpression(
functionLiteral.valueParameters.joinToString { it.text },
"$startLineBreak$bodyText$endLineBreak"
)
)
}
}
class ConvertLambdaToMultiLineIntention : ConvertLambdaLineIntention(toMultiLine = true)
class ConvertLambdaToSingleLineIntention : ConvertLambdaLineIntention(toMultiLine = false)
| apache-2.0 | e909f869cb40c3196db528d21849959a | 48.784615 | 158 | 0.714153 | 5.104101 | false | false | false | false |
vhromada/Catalog | web/src/main/kotlin/com/github/vhromada/catalog/web/mapper/impl/ProgramMapperImpl.kt | 1 | 1474 | package com.github.vhromada.catalog.web.mapper.impl
import com.github.vhromada.catalog.web.connector.entity.ChangeProgramRequest
import com.github.vhromada.catalog.web.connector.entity.Program
import com.github.vhromada.catalog.web.fo.ProgramFO
import com.github.vhromada.catalog.web.mapper.ProgramMapper
import org.springframework.stereotype.Component
/**
* A class represents implementation of mapper for programs.
*
* @author Vladimir Hromada
*/
@Component("programMapper")
class ProgramMapperImpl : ProgramMapper {
override fun map(source: Program): ProgramFO {
return ProgramFO(
uuid = source.uuid,
name = source.name,
wikiEn = source.wikiEn,
wikiCz = source.wikiCz,
mediaCount = source.mediaCount.toString(),
format = source.format,
crack = source.crack,
serialKey = source.serialKey,
otherData = source.otherData,
note = source.note
)
}
override fun mapRequest(source: ProgramFO): ChangeProgramRequest {
return ChangeProgramRequest(
name = source.name!!,
wikiEn = source.wikiEn,
wikiCz = source.wikiCz,
mediaCount = source.mediaCount!!.toInt(),
format = source.format!!,
crack = source.crack!!,
serialKey = source.serialKey!!,
otherData = source.otherData,
note = source.note
)
}
}
| mit | 8815bdb99fa6cf095312d06722b3e713 | 31.043478 | 76 | 0.635685 | 4.724359 | false | false | false | false |
StepicOrg/stepik-android | app/src/main/java/org/stepik/android/cache/assignment/structure/DbStructureAssignment.kt | 2 | 380 | package org.stepik.android.cache.assignment.structure
object DbStructureAssignment {
const val TABLE_NAME = "assignment"
object Columns {
const val ID = "id"
const val STEP = "step"
const val UNIT = "unit"
const val PROGRESS = "progress"
const val CREATE_DATE = "create_date"
const val UPDATE_DATE = "update_date"
}
} | apache-2.0 | 266711c92c163ea99b6c212dee32b25f | 24.4 | 53 | 0.626316 | 4.130435 | false | false | false | false |
StepicOrg/stepik-android | app/src/main/java/org/stepic/droid/code/data/AutocompleteDictionary.kt | 1 | 1931 | package org.stepic.droid.code.data
import ru.nobird.app.core.model.isNotOrdered
/**
* Class for fast search strings with common prefix
*/
class AutocompleteDictionary(
private val dict: Array<String>,
needSort: Boolean = true,
private val isCaseSensitive : Boolean = true
) {
companion object {
/**
* Returns next in chars string.
* e.g.: incrementString("aa") == "ab"
*/
fun incrementString(string: String): String {
val chars = string.toCharArray()
for (i in chars.size - 1 downTo 0) {
if (chars[i] + 1 < chars[i]) {
chars[i] = 0.toChar()
} else {
chars[i] = chars[i] + 1
break
}
}
return if (chars.isEmpty() || chars[0] == 0.toChar()) {
1.toChar() + String(chars)
} else {
String(chars)
}
}
/**
* Kotlin's binarySearch provides element position or position where element should be multiplied by -1.
* This method convert result in second case to positive position.
*/
private fun getBinarySearchPosition(pos: Int): Int =
if (pos < 0)
-(pos + 1)
else
pos
}
init {
if (needSort) {
dict.sort()
} else {
require(!dict.isNotOrdered()) { "Given array should be sorted" }
}
}
fun getAutocompleteForPrefix(prefix: String): List<String> {
val comparator = Comparator<String> { s1, s2 -> s1.compareTo(s2, ignoreCase = !isCaseSensitive) }
val start = dict.binarySearch(prefix, comparator).let(::getBinarySearchPosition)
val end = dict.binarySearch(incrementString(prefix), comparator).let(::getBinarySearchPosition)
return dict.slice(start until end)
}
} | apache-2.0 | 6d4e8bd7221c79485ae17170cf796b4e | 31.2 | 112 | 0.537545 | 4.43908 | false | false | false | false |
dmcg/konsent | src/test/java/com/oneeyedmen/konsent/BetterEnglishTests.kt | 1 | 1870 | package com.oneeyedmen.konsent
import com.natpryce.hamkrest.equalTo
import org.junit.runner.RunWith
@RunWith(Konsent::class)
class BetterEnglishTests : AcceptanceTest() {
val driver = DummyDriver()
val duncan = Actor.with("Duncan", "he", driver, recorder)
val alice = Actor.with("Alice", "she", driver, recorder)
@Scenario(1) fun `uses 'and' instead of repeating clause`() {
Given(duncan).doesAThing("Duncan's thing")
Given(alice).doesAThing("Alice's thing")
Then(alice).shouldSee(theLastThingHappened, equalTo("Alice's thing happened"))
Then(duncan).shouldSee(theLastThingHappened, equalTo("Alice's thing happened"))
}
@Scenario(2) fun `uses 'and' instead of repeating name and operation`() {
Given(duncan).doesAThing("Duncan's thing")
Then(duncan).shouldSee(theLastThingHappened, equalTo("Duncan's thing happened"))
Then(duncan).shouldSee(theLastThingHappened, equalTo("Alice's thing happened").not())
Then(alice).shouldSee(theLastThingHappened, equalTo("Duncan's thing happened"))
}
@Scenario(3) fun `uses 'he' instead of repeating name`() {
Then(duncan).doesAThing("Duncan's thing")
Then(duncan).shouldSee(theLastThingHappened, equalTo("Duncan's thing happened"))
}
@Scenario(4) fun `uses 'he' instead of repeating name with anonymous term`() {
duncan.he.doesAThing("Duncan's thing")
duncan.he.shouldSee(theLastThingHappened, equalTo("Duncan's thing happened"))
}
}
val theLastThingHappened = selector<DummyDriver, String?>("the last thing happened") {
driver.state
}
private fun Steps<DummyDriver>.doesAThing(s: String) = describedBy("""does a thing named "$s"""") {
driver.doThing(s)
}
class DummyDriver {
var state: String? = null
fun doThing(s: String) {
state = "$s happened"
}
}
| apache-2.0 | b5e896fbacd45dc3704580e5da6b6911 | 33.62963 | 99 | 0.683957 | 4.164811 | false | false | false | false |
allotria/intellij-community | platform/vcs-impl/src/com/intellij/openapi/vcs/changes/ui/BooleanCommitOption.kt | 3 | 2267 | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.openapi.vcs.changes.ui
import com.intellij.ide.ui.UISettings
import com.intellij.openapi.options.UnnamedConfigurable
import com.intellij.openapi.vcs.CheckinProjectPanel
import com.intellij.openapi.vcs.VcsBundle
import com.intellij.openapi.vcs.checkin.CheckinHandlerUtil.disableWhenDumb
import com.intellij.openapi.vcs.configurable.CommitOptionsConfigurable
import com.intellij.openapi.vcs.ui.RefreshableOnComponent
import com.intellij.ui.components.JBCheckBox
import com.intellij.vcs.commit.isNonModalCommit
import org.jetbrains.annotations.Nls
import java.util.function.Consumer
import javax.swing.JComponent
import kotlin.reflect.KMutableProperty0
open class BooleanCommitOption(
private val checkinPanel: CheckinProjectPanel,
@Nls text: String,
disableWhenDumb: Boolean,
private val getter: () -> Boolean,
private val setter: Consumer<Boolean>
) : RefreshableOnComponent,
UnnamedConfigurable {
constructor(panel: CheckinProjectPanel, @Nls text: String, disableWhenDumb: Boolean, property: KMutableProperty0<Boolean>) :
this(panel, text, disableWhenDumb, { property.get() }, Consumer { property.set(it) })
protected val checkBox = JBCheckBox(text).apply {
isFocusable = isInSettings || isInNonModalOptionsPopup || UISettings.shadowInstance.disableMnemonicsInControls
if (disableWhenDumb && !isInSettings) disableWhenDumb(checkinPanel.project, this,
VcsBundle.message("changes.impossible.until.indices.are.up.to.date"))
}
private val isInSettings get() = checkinPanel is CommitOptionsConfigurable.CheckinPanel
private val isInNonModalOptionsPopup get() = checkinPanel.isNonModalCommit
override fun refresh() {
}
override fun saveState() {
setter.accept(checkBox.isSelected)
}
override fun restoreState() {
checkBox.isSelected = getter()
}
override fun getComponent(): JComponent = checkBox
override fun createComponent() = component
override fun isModified() = checkBox.isSelected != getter()
override fun apply() = saveState()
override fun reset() = restoreState()
} | apache-2.0 | 97396262dfa114687bd0132617be94ce | 37.440678 | 140 | 0.770181 | 4.645492 | false | true | false | false |
allotria/intellij-community | plugins/git4idea/src/git4idea/rebase/log/GitLogCommitDetailsLoader.kt | 2 | 3492 | // 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 git4idea.rebase.log
import com.intellij.notification.NotificationType
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.project.Project
import com.intellij.openapi.vcs.VcsException
import com.intellij.openapi.vcs.VcsNotifier
import com.intellij.vcs.log.VcsCommitMetadata
import com.intellij.vcs.log.VcsShortCommitDetails
import com.intellij.vcs.log.data.VcsLogData
import com.intellij.vcs.log.impl.VcsCommitMetadataImpl
import com.intellij.vcs.log.util.VcsLogUtil
import git4idea.i18n.GitBundle
private val LOG = Logger.getInstance("Git.Rebase.Log.Action.CommitDetailsLoader")
internal fun getOrLoadDetails(project: Project, data: VcsLogData, commitList: List<VcsShortCommitDetails>): List<VcsCommitMetadata> {
val commitsToLoad = HashSet<VcsShortCommitDetails>(commitList)
val result = HashMap<VcsShortCommitDetails, VcsCommitMetadata>()
commitList.forEach { commit ->
val commitMetadata = (commit as? VcsCommitMetadata) ?: getCommitDataFromCache(data, commit)
if (commitMetadata != null) {
result[commit] = commitMetadata
}
else {
commitsToLoad.add(commit)
}
}
val loadedDetails = loadDetails(project, data, commitsToLoad)
result.putAll(loadedDetails)
return commitList.map {
result[it] ?: throw LoadCommitDetailsException()
}
}
private fun getCommitDataFromCache(data: VcsLogData, commit: VcsShortCommitDetails): VcsCommitMetadata? {
val commitIndex = data.getCommitIndex(commit.id, commit.root)
val commitData = data.commitDetailsGetter.getCommitDataIfAvailable(commitIndex)
if (commitData != null) {
return commitData
}
val message = data.index.dataGetter?.getFullMessage(commitIndex)
if (message != null) {
return VcsCommitMetadataImpl(commit.id, commit.parents, commit.commitTime, commit.root, commit.subject,
commit.author, message, commit.committer, commit.authorTime)
}
return null
}
private fun loadDetails(
project: Project,
data: VcsLogData,
commits: Collection<VcsShortCommitDetails>
): Map<VcsShortCommitDetails, VcsCommitMetadata> {
val result = HashMap<VcsShortCommitDetails, VcsCommitMetadata>()
ProgressManager.getInstance().runProcessWithProgressSynchronously(
{
try {
val commitList = commits.toList()
if (commitList.isEmpty()) {
return@runProcessWithProgressSynchronously
}
val root = commits.first().root
val commitListData = VcsLogUtil.getDetails(data.getLogProvider(root), root, commitList.map { it.id.asString() })
result.putAll(commitList.zip(commitListData))
}
catch (e: VcsException) {
val error = GitBundle.message("rebase.log.action.loading.commit.message.failed.message", commits.size)
LOG.warn(error, e)
val notification = VcsNotifier.STANDARD_NOTIFICATION.createNotification(
"",
error,
NotificationType.ERROR,
null,
"git.log.could.not.load.changes.of.commit"
)
VcsNotifier.getInstance(project).notify(notification)
}
},
GitBundle.message("rebase.log.action.progress.indicator.loading.commit.message.title", commits.size),
true,
project
)
return result
}
internal class LoadCommitDetailsException : Exception() | apache-2.0 | bdfa97a51dae77b30f5f0745923e3e23 | 37.811111 | 140 | 0.739691 | 4.505806 | false | false | false | false |
LivingDoc/livingdoc | livingdoc-tests/src/test/kotlin/org/livingdoc/example/CalculatorDocumentDisabledExecutableDocument.kt | 2 | 3412 | package org.livingdoc.example
import org.assertj.core.api.Assertions.assertThat
import org.livingdoc.api.disabled.Disabled
import org.livingdoc.api.documents.ExecutableDocument
import org.livingdoc.api.fixtures.decisiontables.BeforeRow
import org.livingdoc.api.fixtures.decisiontables.Check
import org.livingdoc.api.fixtures.decisiontables.DecisionTableFixture
import org.livingdoc.api.fixtures.decisiontables.Input
/**
* This [ExecutableDocument] demonstrates the [Disabled] annotation. It will not be run during the LivingDoc test execution. Instead its state will be recorded as `Disabled`
*
* @see Disabled
* @see ExecutableDocument
*/
@Disabled("Skip this document")
@ExecutableDocument("local://Calculator.html")
class CalculatorDocumentDisabledExecutableDocument {
/**
* This [DecisionTableFixture] demonstrates that the [Disabled] annotation from above works and you are able to disable the document even if it contains fixtures.
* Otherwise this would not be tested.
* @see DecisionTableFixture
*/
@DecisionTableFixture
class CalculatorDecisionTableFixture {
private lateinit var sut: Calculator
@Input("a")
private var valueA: Float = 0f
private var valueB: Float = 0f
@BeforeRow
fun beforeRow() {
sut = Calculator()
}
@Input("b")
fun setValueB(valueB: Float) {
this.valueB = valueB
}
@Check("a + b = ?")
fun checkSum(expectedValue: Float) {
val result = sut.sum(valueA, valueB)
assertThat(result).isEqualTo(expectedValue)
}
@Check("a - b = ?")
fun checkDiff(expectedValue: Float) {
val result = sut.diff(valueA, valueB)
assertThat(result).isEqualTo(expectedValue)
}
@Check("a * b = ?")
fun checkMultiply(expectedValue: Float) {
val result = sut.multiply(valueA, valueB)
assertThat(result).isEqualTo(expectedValue)
}
@Check("a / b = ?")
fun checkDivide(expectedValue: Float) {
val result = sut.divide(valueA, valueB)
assertThat(result).isEqualTo(expectedValue)
}
}
@DecisionTableFixture
class CalculatorDecisionTableFixture2 {
private lateinit var sut: Calculator
@Input("x")
private var valueA: Float = 0f
private var valueB: Float = 0f
@BeforeRow
fun beforeRow() {
sut = Calculator()
}
@Input("y")
fun setValueB(valueB: Float) {
this.valueB = valueB
}
@Check("a + b = ?")
fun checkSum(expectedValue: Float) {
val result = sut.sum(valueA, valueB)
assertThat(result).isEqualTo(expectedValue)
}
@Check("a - b = ?")
fun checkDiff(expectedValue: Float) {
val result = sut.diff(valueA, valueB)
assertThat(result).isEqualTo(expectedValue)
}
@Check("a * b = ?")
fun checkMultiply(expectedValue: Float) {
val result = sut.multiply(valueA, valueB)
assertThat(result).isEqualTo(expectedValue)
}
@Check("a / b = ?")
fun checkDivide(expectedValue: Float) {
val result = sut.divide(valueA, valueB)
assertThat(result).isEqualTo(expectedValue)
}
}
}
| apache-2.0 | 2b454dc4dddf9d7fba0d4b428cca1165 | 28.929825 | 173 | 0.618113 | 4.752089 | false | false | false | false |
leafclick/intellij-community | platform/workspaceModel-ide-tests/testSrc/com/intellij/workspace/jps/TestModuleComponent.kt | 1 | 670 | package com.intellij.workspace.jps
import com.intellij.openapi.components.PersistentStateComponent
import com.intellij.openapi.components.State
import com.intellij.openapi.module.Module
import com.intellij.openapi.module.ModuleComponent
@State(name = "XXX")
class TestModuleComponent: ModuleComponent, PersistentStateComponent<TestModuleComponent> {
var testString: String = ""
override fun getState(): TestModuleComponent? = this
override fun loadState(state: TestModuleComponent) {
testString = state.testString
}
companion object {
fun getInstance(module: Module): TestModuleComponent = module.getComponent(TestModuleComponent::class.java)
}
} | apache-2.0 | 08050eb8e4af0c0e0227afaca26828e0 | 32.55 | 111 | 0.802985 | 4.652778 | false | true | false | false |
zdary/intellij-community | plugins/editorconfig/src/org/editorconfig/language/structureview/EditorConfigStructureViewElement.kt | 7 | 1781 | // Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.editorconfig.language.structureview
import com.intellij.ide.projectView.PresentationData
import com.intellij.ide.structureView.StructureViewTreeElement
import com.intellij.ide.util.treeView.smartTree.SortableTreeElement
import com.intellij.ide.util.treeView.smartTree.TreeElement
import com.intellij.psi.NavigatablePsiElement
import com.intellij.psi.util.PsiTreeUtil
import org.editorconfig.language.psi.EditorConfigPsiFile
import org.editorconfig.language.psi.EditorConfigRootDeclaration
import org.editorconfig.language.psi.EditorConfigSection
class EditorConfigStructureViewElement(private val element: NavigatablePsiElement) : StructureViewTreeElement, SortableTreeElement {
override fun getValue() = element
override fun navigate(requestFocus: Boolean) = element.navigate(requestFocus)
override fun canNavigate() = element.canNavigate()
override fun canNavigateToSource() = element.canNavigateToSource()
override fun getAlphaSortKey() = element.name ?: ""
override fun getPresentation() = element.presentation ?: PresentationData()
override fun getChildren(): Array<out TreeElement> = when (element) {
is EditorConfigPsiFile -> {
val roots = PsiTreeUtil
.getChildrenOfTypeAsList(element, EditorConfigRootDeclaration::class.java)
.map(::EditorConfigStructureViewElement)
val sections = element.sections
.map(::EditorConfigStructureViewElement)
.toTypedArray()
(roots + sections).toTypedArray()
}
is EditorConfigSection -> element.optionList
.map(::EditorConfigStructureViewElement)
.toTypedArray()
else -> emptyArray()
}
}
| apache-2.0 | 0962c36f5d418dfa6d4668fa903590c4 | 42.439024 | 140 | 0.784391 | 5.162319 | false | true | false | false |
leafclick/intellij-community | platform/projectModel-impl/src/com/intellij/openapi/module/impl/UnloadedModuleDescriptionImpl.kt | 1 | 2993 | /*
* 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.openapi.module.impl
import com.intellij.openapi.Disposable
import com.intellij.openapi.application.PathManager
import com.intellij.openapi.module.UnloadedModuleDescription
import com.intellij.openapi.vfs.pointers.VirtualFilePointer
import com.intellij.openapi.vfs.pointers.VirtualFilePointerManager
import org.jetbrains.jps.model.module.JpsModule
import org.jetbrains.jps.model.module.JpsModuleDependency
import org.jetbrains.jps.model.serialization.JpsGlobalLoader
import org.jetbrains.jps.model.serialization.JpsProjectLoader
import java.nio.file.Paths
class UnloadedModuleDescriptionImpl(val modulePath: ModulePath,
private val dependencyModuleNames: List<String>,
private val contentRoots: List<VirtualFilePointer>) : UnloadedModuleDescription {
override fun getGroupPath(): List<String> = modulePath.group?.split(ModuleManagerImpl.MODULE_GROUP_SEPARATOR) ?: emptyList()
override fun getName(): String = modulePath.moduleName
override fun getContentRoots(): List<VirtualFilePointer> = contentRoots
override fun getDependencyModuleNames(): List<String> = dependencyModuleNames
override fun equals(other: Any?): Boolean = other is UnloadedModuleDescriptionImpl && name == other.name
override fun hashCode(): Int = name.hashCode()
companion object {
@JvmStatic
fun createFromPaths(paths: Collection<ModulePath>, parentDisposable: Disposable): List<UnloadedModuleDescriptionImpl> {
val pathVariables = JpsGlobalLoader.computeAllPathVariables(PathManager.getOptionsPath())
val modules = JpsProjectLoader.loadModules(paths.map { Paths.get(it.path) }, null, pathVariables)
val pathsByName = paths.associateBy { it.moduleName }
return modules.map { create(pathsByName[it.name]!!, it, parentDisposable) }
}
private fun create(path: ModulePath, module: JpsModule, parentDisposable: Disposable): UnloadedModuleDescriptionImpl {
val dependencyModuleNames = module.dependenciesList.dependencies
.filterIsInstance(JpsModuleDependency::class.java)
.map { it.moduleReference.moduleName }
val pointerManager = VirtualFilePointerManager.getInstance()
return UnloadedModuleDescriptionImpl(path, dependencyModuleNames, module.contentRootsList.urls.map {pointerManager.create(it, parentDisposable, null)})
}
}
}
| apache-2.0 | 20e926b69e614e5f054d9ee4c3b90c50 | 47.274194 | 157 | 0.767792 | 5.005017 | false | false | false | false |
JuliusKunze/kotlin-native | backend.native/tests/external/codegen/box/reflection/enclosing/lambdaInLocalClassSuperCall.kt | 2 | 860 | // TODO: muted automatically, investigate should it be ran for JS or not
// IGNORE_BACKEND: JS, NATIVE
// WITH_REFLECT
open class C(val a: Any)
fun box(): String {
class L : C({}) {
}
val l = L()
val javaClass = l.a.javaClass
val enclosingMethod = javaClass.getEnclosingConstructor()!!.getName()
if (enclosingMethod != "LambdaInLocalClassSuperCallKt\$box\$L") return "ctor: $enclosingMethod"
val enclosingClass = javaClass.getEnclosingClass()!!.getName()
if (enclosingClass != "LambdaInLocalClassSuperCallKt\$box\$L") return "enclosing class: $enclosingClass"
if (enclosingMethod != enclosingClass) return "$enclosingClass != $enclosingMethod"
val declaringClass = javaClass.getDeclaringClass()
if (declaringClass != null) return "anonymous function has a declaring class: $declaringClass"
return "OK"
}
| apache-2.0 | ce9fc9c6a5acd42e9bf1d66661bfff97 | 32.076923 | 108 | 0.70814 | 4.502618 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/idea/tests/testData/refactoring/inlineMultiFile/fromJavaToKotlin/inheritance/after/otherusage/main.kt | 12 | 6718 | package otheruse
import javapackage.one.JavaClassOne
import kotlinpackage.one.extensionSelf
fun a() {
val javaClassOne = JavaClassOne()
println(javaClassOne.onlySuperMethod())
println(javaClassOne.superClassMethod())
println(javaClassOne.superClassMethod())
JavaClassOne().extensionSelf().toJavaClassTwo().returnSelf().toJavaOne().otherMethod()
val d = JavaClassOne()
println(d.onlySuperMethod())
println(d.superClassMethod())
println(d.superClassMethod())
JavaClassOne().extensionSelf().toJavaClassTwo().returnSelf().toJavaOne().otherMethod()
d.let {
println(it.onlySuperMethod())
println(it.superClassMethod())
println(it.superClassMethod())
JavaClassOne().extensionSelf().toJavaClassTwo().returnSelf().toJavaOne().otherMethod()
}
d.also {
println(it.onlySuperMethod())
println(it.superClassMethod())
println(it.superClassMethod())
JavaClassOne().extensionSelf().toJavaClassTwo().returnSelf().toJavaOne().otherMethod()
}
with(d) {
println(onlySuperMethod())
println(superClassMethod())
println(superClassMethod())
JavaClassOne().extensionSelf().toJavaClassTwo().returnSelf().toJavaOne().otherMethod()
}
with(d) out@{
with(4) {
println([email protected]())
println([email protected]())
println([email protected]())
JavaClassOne().extensionSelf().toJavaClassTwo().returnSelf().toJavaOne().otherMethod()
}
}
}
fun a2() {
val d: JavaClassOne? = null
if (d != null) {
println(d.onlySuperMethod())
println(d.superClassMethod())
println(d.superClassMethod())
JavaClassOne().extensionSelf().toJavaClassTwo().returnSelf().toJavaOne().otherMethod()
}
d?.let {
println(it.onlySuperMethod())
println(it.superClassMethod())
println(it.superClassMethod())
JavaClassOne().extensionSelf().toJavaClassTwo().returnSelf().toJavaOne().otherMethod()
}
d?.also {
println(it.onlySuperMethod())
println(it.superClassMethod())
println(it.superClassMethod())
JavaClassOne().extensionSelf().toJavaClassTwo().returnSelf().toJavaOne().otherMethod()
}
with(d) {
this?.let {
println(it.onlySuperMethod())
println(it.superClassMethod())
println(it.superClassMethod())
JavaClassOne().extensionSelf().toJavaClassTwo().returnSelf().toJavaOne().otherMethod()
}
}
with(d) out@{
with(4) {
this@out?.let {
println(it.onlySuperMethod())
println(it.superClassMethod())
println(it.superClassMethod())
JavaClassOne().extensionSelf().toJavaClassTwo().returnSelf().toJavaOne().otherMethod()
}
}
}
}
fun a3() {
val d: JavaClassOne? = null
val a1 = d?.let {
println(it.onlySuperMethod())
println(it.superClassMethod())
println(it.superClassMethod())
JavaClassOne().extensionSelf().toJavaClassTwo().returnSelf().toJavaOne().otherMethod()
}
val a2 = d?.let {
println(it.onlySuperMethod())
println(it.superClassMethod())
println(it.superClassMethod())
JavaClassOne().extensionSelf().toJavaClassTwo().returnSelf().toJavaOne().otherMethod()
}
val a3 = d?.also {
println(it.onlySuperMethod())
println(it.superClassMethod())
println(it.superClassMethod())
JavaClassOne().extensionSelf().toJavaClassTwo().returnSelf().toJavaOne().otherMethod()
}
val a4 = with(d) {
this?.let {
println(it.onlySuperMethod())
println(it.superClassMethod())
println(it.superClassMethod())
JavaClassOne().extensionSelf().toJavaClassTwo().returnSelf().toJavaOne().otherMethod()
}
}
val a5 = with(d) out@{
with(4) {
this@out?.let {
println(it.onlySuperMethod())
println(it.superClassMethod())
println(it.superClassMethod())
JavaClassOne().extensionSelf().toJavaClassTwo().returnSelf().toJavaOne().otherMethod()
}
}
}
}
fun a4() {
val d: JavaClassOne? = null
d?.let {
println(it.onlySuperMethod())
println(it.superClassMethod())
println(it.superClassMethod())
JavaClassOne().extensionSelf().toJavaClassTwo().returnSelf().toJavaOne().otherMethod()
}?.dec()
val a2 = d?.let {
println(it.onlySuperMethod())
println(it.superClassMethod())
println(it.superClassMethod())
JavaClassOne().extensionSelf().toJavaClassTwo().returnSelf().toJavaOne().otherMethod()
}
a2?.toLong()
d?.also {
println(it.onlySuperMethod())
println(it.superClassMethod())
println(it.superClassMethod())
JavaClassOne().extensionSelf().toJavaClassTwo().returnSelf().toJavaOne().otherMethod()
}?.let {
println(it.onlySuperMethod())
println(it.superClassMethod())
println(it.superClassMethod())
JavaClassOne().extensionSelf().toJavaClassTwo().returnSelf().toJavaOne().otherMethod()
}?.and(4)
val a4 = with(d) {
this?.let {
println(it.onlySuperMethod())
println(it.superClassMethod())
println(it.superClassMethod())
JavaClassOne().extensionSelf().toJavaClassTwo().returnSelf().toJavaOne().otherMethod()
}
}
val a5 = with(d) out@{
with(4) {
this@out?.let {
println(it.onlySuperMethod())
println(it.superClassMethod())
println(it.superClassMethod())
JavaClassOne().extensionSelf().toJavaClassTwo().returnSelf().toJavaOne().otherMethod()
}
}
}
val a6 = a4?.let { out -> a5?.let { out + it } }
}
fun JavaClassOne.b(): Int? {
println(onlySuperMethod())
println(superClassMethod())
println(superClassMethod())
return JavaClassOne().extensionSelf().toJavaClassTwo().returnSelf().toJavaOne().otherMethod()
}
fun JavaClassOne.c(): Int {
println(this.onlySuperMethod())
println(this.superClassMethod())
println(this.superClassMethod())
return JavaClassOne().extensionSelf().toJavaClassTwo().returnSelf().toJavaOne().otherMethod()
}
fun d(d: JavaClassOne): Int? {
println(d.onlySuperMethod())
println(d.superClassMethod())
println(d.superClassMethod())
return JavaClassOne().extensionSelf().toJavaClassTwo().returnSelf().toJavaOne().otherMethod()
}
| apache-2.0 | b2a5405fabe60c8d462658862ad13161 | 31.454106 | 102 | 0.616255 | 5.281447 | false | false | false | false |
smmribeiro/intellij-community | plugins/devkit/devkit-core/src/module/DevKitModuleBuilder.kt | 1 | 8053 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.idea.devkit.module
import com.intellij.icons.AllIcons
import com.intellij.ide.fileTemplates.FileTemplateManager
import com.intellij.ide.plugins.PluginManager
import com.intellij.ide.starters.local.*
import com.intellij.ide.starters.local.gradle.GradleResourcesProvider
import com.intellij.ide.starters.local.wizard.StarterInitialStep
import com.intellij.ide.starters.shared.*
import com.intellij.ide.util.projectWizard.ModuleWizardStep
import com.intellij.ide.util.projectWizard.ProjectWizardUtil
import com.intellij.ide.util.projectWizard.WizardContext
import com.intellij.openapi.extensions.PluginId
import com.intellij.openapi.module.Module
import com.intellij.openapi.observable.properties.GraphProperty
import com.intellij.openapi.observable.properties.GraphPropertyImpl.Companion.graphProperty
import com.intellij.openapi.project.ProjectManager
import com.intellij.openapi.projectRoots.Sdk
import com.intellij.openapi.projectRoots.SdkTypeId
import com.intellij.openapi.roots.ui.configuration.ModulesProvider
import com.intellij.openapi.util.Condition
import com.intellij.openapi.util.Key
import com.intellij.openapi.util.NlsSafe
import com.intellij.openapi.util.text.Strings
import com.intellij.pom.java.LanguageLevel
import com.intellij.ui.HyperlinkLabel
import com.intellij.ui.layout.*
import com.intellij.util.lang.JavaVersion
import org.jetbrains.annotations.Nls
import org.jetbrains.idea.devkit.DevKitBundle
import org.jetbrains.idea.devkit.DevKitFileTemplatesFactory
import org.jetbrains.idea.devkit.projectRoots.IdeaJdk
import java.util.function.Supplier
import javax.swing.Icon
class DevKitModuleBuilder : StarterModuleBuilder() {
private val PLUGIN_TYPE_KEY: Key<PluginType> = Key.create("devkit.plugin.type")
override fun getBuilderId(): String = "idea-plugin"
override fun getPresentableName(): String = DevKitBundle.message("module.builder.title")
override fun getWeight(): Int = IJ_PLUGIN_WEIGHT
override fun getNodeIcon(): Icon = AllIcons.Nodes.Plugin
override fun getDescription(): String = DevKitBundle.message("module.description")
override fun getProjectTypes(): List<StarterProjectType> = emptyList()
override fun getTestFrameworks(): List<StarterTestRunner> = emptyList()
override fun getMinJavaVersion(): JavaVersion = LanguageLevel.JDK_11.toJavaVersion()
override fun getLanguages(): List<StarterLanguage> {
return listOf(
JAVA_STARTER_LANGUAGE,
KOTLIN_STARTER_LANGUAGE
)
}
override fun getStarterPack(): StarterPack {
return StarterPack("devkit", listOf(
Starter("devkit", "DevKit", getDependencyConfig("/starters/devkit.pom"), emptyList())
))
}
override fun createWizardSteps(context: WizardContext, modulesProvider: ModulesProvider): Array<ModuleWizardStep> {
return emptyArray()
}
override fun createOptionsStep(contextProvider: StarterContextProvider): StarterInitialStep {
return DevKitInitialStep(contextProvider)
}
override fun isSuitableSdkType(sdkType: SdkTypeId?): Boolean {
val pluginType = starterContext.getUserData(PLUGIN_TYPE_KEY) ?: PluginType.PLUGIN
if (pluginType == PluginType.PLUGIN) {
return super.isSuitableSdkType(sdkType)
}
return sdkType == IdeaJdk.getInstance()
}
override fun setupModule(module: Module) {
// manually set, we do not show the second page with libraries
starterContext.starter = starterContext.starterPack.starters.first()
starterContext.starterDependencyConfig = loadDependencyConfig()[starterContext.starter?.id]
super.setupModule(module)
}
override fun getAssets(starter: Starter): List<GeneratorAsset> {
val ftManager = FileTemplateManager.getInstance(ProjectManager.getInstance().defaultProject)
val assets = mutableListOf<GeneratorAsset>()
assets.add(GeneratorTemplateFile("build.gradle.kts", ftManager.getJ2eeTemplate(DevKitFileTemplatesFactory.BUILD_GRADLE_KTS)))
assets.add(GeneratorTemplateFile("settings.gradle.kts", ftManager.getJ2eeTemplate(DevKitFileTemplatesFactory.SETTINGS_GRADLE_KTS)))
assets.add(GeneratorTemplateFile("gradle/wrapper/gradle-wrapper.properties",
ftManager.getJ2eeTemplate(DevKitFileTemplatesFactory.GRADLE_WRAPPER_PROPERTIES)))
assets.addAll(GradleResourcesProvider().getGradlewResources())
val packagePath = getPackagePath(starterContext.group, starterContext.artifact)
if (starterContext.language == JAVA_STARTER_LANGUAGE) {
assets.add(GeneratorEmptyDirectory("src/main/java/${packagePath}"))
}
else if (starterContext.language == KOTLIN_STARTER_LANGUAGE) {
assets.add(GeneratorEmptyDirectory("src/main/kotlin/${packagePath}"))
}
assets.add(GeneratorTemplateFile("src/main/resources/META-INF/plugin.xml",
ftManager.getJ2eeTemplate(DevKitFileTemplatesFactory.PLUGIN_XML)))
assets.add(GeneratorResourceFile("src/main/resources/META-INF/pluginIcon.svg",
javaClass.getResource("/assets/devkit-pluginIcon.svg")!!))
assets.add(GeneratorResourceFile(".run/Run IDE with Plugin.run.xml",
javaClass.getResource("/assets/devkit-Run_IDE_with_Plugin.run.xml")!!))
return assets
}
override fun getGeneratorContextProperties(sdk: Sdk?, dependencyConfig: DependencyConfig): Map<String, String> {
return mapOf("pluginTitle" to Strings.capitalize(starterContext.artifact))
}
override fun getFilePathsToOpen(): List<String> {
return listOf(
"src/main/resources/META-INF/plugin.xml",
"build.gradle.kts"
)
}
private inner class DevKitInitialStep(contextProvider: StarterContextProvider) : StarterInitialStep(contextProvider) {
private val typeProperty: GraphProperty<PluginType> = propertyGraph.graphProperty { PluginType.PLUGIN }
override fun addFieldsBefore(layout: LayoutBuilder) {
layout.row(DevKitBundle.message("module.builder.type")) {
segmentedButton(listOf(PluginType.PLUGIN, PluginType.THEME), typeProperty) { it.messagePointer.get() }
}.largeGapAfter()
starterContext.putUserData(PLUGIN_TYPE_KEY, PluginType.PLUGIN)
typeProperty.afterChange { pluginType ->
starterContext.putUserData(PLUGIN_TYPE_KEY, pluginType)
languageRow.visible = pluginType == PluginType.PLUGIN
groupRow.visible = pluginType == PluginType.PLUGIN
artifactRow.visible = pluginType == PluginType.PLUGIN
// Theme / Plugin projects require different SDK type
sdkComboBox.selectedJdk = null
sdkComboBox.reloadModel()
ProjectWizardUtil.preselectJdkForNewModule(wizardContext.project, null, sdkComboBox, Condition(::isSuitableSdkType))
}
}
override fun addFieldsAfter(layout: LayoutBuilder) {
layout.row {
hyperLink(DevKitBundle.message("module.builder.how.to.link"),
"https://plugins.jetbrains.com/docs/intellij/intellij-platform.html")
}
layout.row {
hyperLink(DevKitBundle.message("module.builder.github.template.link"),
"https://github.com/JetBrains/intellij-platform-plugin-template")
}
if (PluginManager.isPluginInstalled(PluginId.findId("org.intellij.scala"))) {
layout.row {
hyperLink(DevKitBundle.message("module.builder.scala.github.template.link"),
"https://github.com/JetBrains/sbt-idea-plugin")
}
}
}
}
private fun Row.hyperLink(@Nls title: String, @NlsSafe url: String) {
val hyperlinkLabel = HyperlinkLabel(title)
hyperlinkLabel.setHyperlinkTarget(url)
hyperlinkLabel.toolTipText = url
this.component(hyperlinkLabel)
}
private enum class PluginType(
val messagePointer: Supplier<String>
) {
PLUGIN(DevKitBundle.messagePointer("module.builder.type.plugin")),
THEME(DevKitBundle.messagePointer("module.builder.type.theme"))
}
} | apache-2.0 | 987a4b7ff8a91a995150483e650332b3 | 42.301075 | 135 | 0.7509 | 4.753837 | false | false | false | false |
ssoudan/ktSpringTest | src/main/java/eu/ssoudan/ktSpringTest/management/ServiceHealthIndicator.kt | 1 | 1659 | package eu.ssoudan.ktSpringTest.management
import org.springframework.boot.actuate.health.Health
import org.springframework.boot.actuate.health.AbstractHealthIndicator
import org.springframework.stereotype.Service
import eu.ssoudan.ktSpringTest.management.HealthCheckedService.HealthStatus
import java.util.LinkedList
import eu.ssoudan.ktSpringTest.configuration.HelloConfiguration
import org.springframework.beans.factory.annotation.Autowired
/**
* Created by ssoudan on 12/6/14.
*
* Apache License, Version 2.0
*/
Service
class ServiceHealthIndicator [Autowired] (val services: List<HealthCheckedService>,
val configuration: HelloConfiguration) : AbstractHealthIndicator() {
fun updateStatus(status: HealthStatus, dependencies: List<HealthCheckedService.HealthInfo>): HealthStatus {
var updatedStatus = status;
dependencies.forEach { dep ->
dep.updateStatus()
if (dep.status == HealthStatus.DOWN) {
updatedStatus = HealthStatus.DOWN;
}
}
return updatedStatus
}
override fun doHealthCheck(p0: Health.Builder?) {
if (p0 != null) {
val dependencies = LinkedList<HealthCheckedService.HealthInfo>()
services.forEach { i -> dependencies.add(i.healthCheck()) }
val status = updateStatus(HealthStatus.UP, dependencies)
p0.withDetail("dependencies", dependencies)
p0.withDetail("serviceName", configuration.serviceName)
if (status == HealthStatus.UP)
p0.up()
else
p0.down()
}
}
} | apache-2.0 | e732bc732d5e36db60a6dadc98fcabd3 | 32.877551 | 111 | 0.670283 | 4.879412 | false | true | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.