repo_name
stringlengths 7
79
| path
stringlengths 8
206
| copies
stringclasses 36
values | size
stringlengths 2
6
| content
stringlengths 55
523k
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 7.18
99.5
| line_max
int64 16
979
| alpha_frac
float64 0.3
0.87
| ratio
float64 2.01
8.07
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
permissions-dispatcher/PermissionsDispatcher | ktx/src/main/java/permissions/dispatcher/ktx/PermissionRequestType.kt | 1 | 1971 | package permissions.dispatcher.ktx
import android.content.Context
import android.os.Build
import android.provider.Settings
import androidx.annotation.RequiresApi
import permissions.dispatcher.PermissionUtils.hasSelfPermissions
internal sealed class PermissionRequestType {
object Normal : PermissionRequestType() {
override fun checkPermissions(context: Context, permissions: Array<out String>): Boolean =
hasSelfPermissions(context, *permissions)
override fun fragment(permissions: Array<out String>): PermissionRequestFragment =
PermissionRequestFragment.NormalRequestPermissionFragment.newInstance(
permissions
)
}
object SystemAlertWindow : PermissionRequestType() {
override fun checkPermissions(context: Context, permissions: Array<out String>): Boolean =
Build.VERSION.SDK_INT < Build.VERSION_CODES.M || Settings.canDrawOverlays(context)
@RequiresApi(Build.VERSION_CODES.M)
override fun fragment(permissions: Array<out String>): PermissionRequestFragment =
PermissionRequestFragment.SpecialRequestPermissionFragment.newInstance(
Settings.ACTION_MANAGE_OVERLAY_PERMISSION
)
}
object WriteSettings : PermissionRequestType() {
override fun checkPermissions(context: Context, permissions: Array<out String>): Boolean =
Build.VERSION.SDK_INT < Build.VERSION_CODES.M || Settings.System.canWrite(context)
@RequiresApi(Build.VERSION_CODES.M)
override fun fragment(permissions: Array<out String>): PermissionRequestFragment =
PermissionRequestFragment.SpecialRequestPermissionFragment.newInstance(
Settings.ACTION_MANAGE_WRITE_SETTINGS
)
}
abstract fun checkPermissions(context: Context, permissions: Array<out String>): Boolean
abstract fun fragment(permissions: Array<out String>): PermissionRequestFragment
}
| apache-2.0 | 1fdfd5edbb5df93be91af4fde8871263 | 42.8 | 98 | 0.728564 | 5.521008 | false | false | false | false |
ffc-nectec/FFC | ffc/src/main/kotlin/ffc/app/util/messaging/FirebaseMessaging.kt | 1 | 2774 | /*
* Copyright (c) 2019 NECTEC
* National Electronics and Computer Technology Center, Thailand
*
* 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 ffc.app.util.messaging
import android.app.Application
import android.content.SharedPreferences
import ffc.api.FfcCentral
import ffc.app.auth.auth
import org.jetbrains.anko.defaultSharedPreferences
import retrofit2.dsl.enqueue
import timber.log.Timber
internal class FirebaseMessaging(val application: Application) : Messaging {
private val service by lazy { FfcCentral().service<MessingingTokenService>() }
private val preferences by lazy { application.defaultSharedPreferences }
private val org by lazy { auth(application).org }
override fun subscribe(token: String?) {
try {
val newToken = if (token == null) preferences.tempToken else token
require(newToken != null)
if (preferences.lastToken != null) {
unsubscribe()
}
check(org != null)
service.updateToken(org!!.id, mapOf("firebaseToken" to newToken!!)).enqueue {
always { Timber.d("Register token $token") }
onSuccess { preferences.lastToken = token }
}
} catch (ex: IllegalStateException) {
preferences.tempToken = token
} catch (ex: IllegalArgumentException) {
preferences.tempToken = token
}
}
override fun unsubscribe() {
try {
val preferences = application.defaultSharedPreferences
val token = preferences.lastToken
check(org != null)
check(token != null)
service.removeToken(org!!.id, token!!).enqueue {
if (preferences.lastToken == token) //lastToken may change before this call
preferences.lastToken = null
}
} catch (ex: IllegalStateException) {
//Do nothing
}
}
}
private var SharedPreferences.lastToken: String?
set(value) = edit().putString("lastToken", value).apply()
get() = getString("lastToken", null)
private var SharedPreferences.tempToken: String?
set(value) = edit().putString("tempToken", value).apply()
get() = getString("tempToken", null)
| apache-2.0 | 11e0dd1d4c659adad15b42542b522b65 | 34.564103 | 91 | 0.656453 | 4.677909 | false | false | false | false |
Ribesg/anko | dsl/test/org/jetbrains/android/anko/uniformity/uniformityUtils.kt | 2 | 1408 | package org.jetbrains.android.anko.uniformity
import java.io.File
import java.util.regex.Pattern
private fun String.replaceDoubledSpaces(): String {
var ret = this
while (true) {
val new = ret.replace(" ", " ")
if (new == ret) return new
ret = new
}
}
fun getAllDeclarations(
file: File,
receiver: String,
declarationType: String,
ignoreAnnotation: String? = null
): List<Pair<String, String>> {
val argsIncluded = declarationType == "fun"
val args = if (argsIncluded) "\\((.*?)\\)" else ""
val postfix = if (argsIncluded) "[ \n\r\t]*?[\\{\\=]" else ""
val pattern = Pattern.compile("$declarationType $receiver.([A-Za-z0-9_]+)$args( *?\\: *?.+?)?$postfix", Pattern.DOTALL)
val text = file.readText()
val matcher = pattern.matcher(text)
val functions = arrayListOf<Pair<String, String>>()
while (matcher.find()) {
if (ignoreAnnotation != null) {
val annotStart = matcher.start() - ignoreAnnotation.length - 1
if (text.substring(annotStart, annotStart + ignoreAnnotation.length) == ignoreAnnotation) continue
}
val arguments = if (!argsIncluded) "" else matcher.group(2)
.replace('\n', ' ').replace('\r', ' ').replace('\t', ' ').replaceDoubledSpaces().trim()
functions.add(matcher.group(1) to arguments)
}
return functions
} | apache-2.0 | dfcfe55982cbf84492a6336d616fbd8c | 34.225 | 123 | 0.605824 | 3.846995 | false | false | false | false |
niranjan94/show-java | app/src/main/kotlin/com/njlabs/showjava/activities/BaseActivity.kt | 1 | 9824 | /*
* Show Java - A java/apk decompiler for android
* Copyright (c) 2018 Niranjan Rajendran
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.njlabs.showjava.activities
import android.Manifest
import android.content.Context
import android.content.Intent
import android.content.pm.ActivityInfo
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Bundle
import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.widget.Toolbar
import com.google.ads.consent.ConsentInformation
import com.google.ads.consent.ConsentStatus
import com.google.ads.mediation.admob.AdMobAdapter
import com.google.android.gms.ads.AdListener
import com.google.android.gms.ads.AdRequest
import com.google.android.gms.ads.AdView
import com.google.firebase.analytics.FirebaseAnalytics
import com.njlabs.showjava.Constants
import com.njlabs.showjava.MainApplication
import com.njlabs.showjava.R
import com.njlabs.showjava.activities.about.AboutActivity
import com.njlabs.showjava.activities.purchase.PurchaseActivity
import com.njlabs.showjava.activities.settings.SettingsActivity
import com.njlabs.showjava.utils.secure.SecureUtils
import com.njlabs.showjava.utils.UserPreferences
import com.njlabs.showjava.utils.ktx.checkDataConnection
import io.reactivex.disposables.CompositeDisposable
import pub.devrel.easypermissions.AppSettingsDialog
import pub.devrel.easypermissions.EasyPermissions
abstract class BaseActivity : AppCompatActivity(), EasyPermissions.PermissionCallbacks {
protected lateinit var toolbar: Toolbar
protected lateinit var context: AppCompatActivity
protected lateinit var userPreferences: UserPreferences
protected lateinit var secureUtils: SecureUtils
protected lateinit var mainApplication: MainApplication
lateinit var firebaseAnalytics: FirebaseAnalytics
protected val disposables = CompositeDisposable()
protected var inEea = false
abstract fun init(savedInstanceState: Bundle?)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
context = this
inEea = ConsentInformation.getInstance(this).isRequestLocationInEeaOrUnknown
firebaseAnalytics = FirebaseAnalytics.getInstance(this)
mainApplication = application as MainApplication
firebaseAnalytics.setUserProperty("instance_id", mainApplication.instanceId)
userPreferences = UserPreferences(getSharedPreferences(UserPreferences.NAME, Context.MODE_PRIVATE))
secureUtils = SecureUtils.getInstance(applicationContext)
if (userPreferences.customFont) {
context.theme.applyStyle(R.style.LatoFontStyle, true)
}
if (!EasyPermissions.hasPermissions(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
EasyPermissions.requestPermissions(
this,
getString(R.string.storagePermissionRationale),
Constants.STORAGE_PERMISSION_REQUEST,
Manifest.permission.WRITE_EXTERNAL_STORAGE
)
init(savedInstanceState)
} else {
init(savedInstanceState)
postPermissionsGrant()
}
}
fun setupLayout(layoutRef: Int) {
setContentView(layoutRef)
setupToolbar(null)
setupGoogleAds()
}
fun setupLayout(layoutRef: Int, title: String) {
setContentView(layoutRef)
setupToolbar(title)
setupGoogleAds()
}
fun setupLayoutNoActionBar(layoutRef: Int) {
setContentView(layoutRef)
}
fun setSubtitle(subtitle: String?) {
// Workaround for a weird bug caused by Calligraphy
// https://github.com/chrisjenx/Calligraphy/issues/280#issuecomment-256444828
toolbar.post {
toolbar.subtitle = subtitle
}
}
private fun setupToolbar(title: String?) {
toolbar = findViewById<View>(R.id.toolbar) as Toolbar
setSupportActionBar(toolbar)
if (title != null) {
supportActionBar?.title = title
} else {
if (isPro()) {
val activityInfo: ActivityInfo
try {
activityInfo = packageManager.getActivityInfo(
componentName,
PackageManager.GET_META_DATA
)
val currentTitle = activityInfo.loadLabel(packageManager).toString()
if (currentTitle.trim() == getString(R.string.appName)) {
supportActionBar?.title = "${getString(R.string.appName)} Pro"
}
} catch (ignored: PackageManager.NameNotFoundException) {
}
}
}
supportActionBar?.setDisplayHomeAsUpEnabled(true)
supportActionBar?.setDisplayShowHomeEnabled(true)
}
private fun setupGoogleAds() {
findViewById<AdView>(R.id.adView)?.let {it ->
it.visibility = View.GONE
if (!isPro()) {
val extras = Bundle()
val consentStatus = ConsentStatus.values()[userPreferences.consentStatus]
if (consentStatus == ConsentStatus.NON_PERSONALIZED) {
extras.putString("npa", "1")
}
val adRequest = AdRequest.Builder()
.addNetworkExtrasBundle(AdMobAdapter::class.java, extras)
.addTestDevice(AdRequest.DEVICE_ID_EMULATOR)
.addTestDevice(getString(R.string.adUnitId))
.build()
it.adListener = object : AdListener() {
override fun onAdFailedToLoad(errorCode: Int) {
super.onAdFailedToLoad(errorCode)
it.visibility = View.GONE
}
override fun onAdLoaded() {
super.onAdLoaded()
it.visibility = View.VISIBLE
}
}
it.loadAd(adRequest)
if (!checkDataConnection(context)) {
it.visibility = View.GONE
}
}
}
}
fun isPro(): Boolean {
return secureUtils.hasPurchasedPro()
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
menuInflater.inflate(R.menu.menu_main, menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
android.R.id.home -> {
finish()
return true
}
R.id.about_option -> {
startActivity(Intent(baseContext, AboutActivity::class.java))
return true
}
R.id.bug_report_option -> {
val uri = Uri.parse("https://github.com/niranjan94/show-java/issues")
startActivity(Intent(Intent.ACTION_VIEW, uri))
overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out)
return true
}
R.id.settings_option -> {
startActivity(Intent(baseContext, SettingsActivity::class.java))
return true
}
R.id.get_pro_option -> {
startActivity(Intent(baseContext, PurchaseActivity::class.java))
return true
}
}
return super.onOptionsItemSelected(item)
}
open fun postPermissionsGrant() {}
override fun onPermissionsGranted(requestCode: Int, perms: MutableList<String>) {
postPermissionsGrant()
}
override fun onRequestPermissionsResult(
requestCode: Int,
permissions: Array<String>,
grantResults: IntArray
) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this)
}
override fun onPermissionsDenied(requestCode: Int, perms: List<String>) {
if (perms.isNotEmpty() || EasyPermissions.somePermissionPermanentlyDenied(this, perms)) {
AppSettingsDialog.Builder(this)
.build()
.show()
}
}
fun hasValidPermissions(): Boolean {
return EasyPermissions.hasPermissions(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
}
public override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode == AppSettingsDialog.DEFAULT_SETTINGS_REQ_CODE) {
if (!EasyPermissions.hasPermissions(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
Toast.makeText(
this,
R.string.storagePermissionRationale,
Toast.LENGTH_LONG
).show()
finish()
} else {
postPermissionsGrant()
}
}
}
override fun onDestroy() {
super.onDestroy()
disposables.clear()
}
}
| gpl-3.0 | b8e07819310fba09b1c37615435e0ac2 | 35.385185 | 107 | 0.639251 | 5.165089 | false | false | false | false |
vanita5/twittnuker | twittnuker/src/main/kotlin/de/vanita5/twittnuker/loader/statuses/ParcelableStatusesLoader.kt | 1 | 2385 | /*
* Twittnuker - Twitter client for Android
*
* Copyright (C) 2013-2017 vanita5 <[email protected]>
*
* This program incorporates a modified version of Twidere.
* Copyright (C) 2012-2017 Mariotaku Lee <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package de.vanita5.twittnuker.loader.statuses
import android.content.Context
import android.support.v4.content.FixedAsyncTaskLoader
import android.text.TextUtils
import de.vanita5.twittnuker.Constants
import de.vanita5.twittnuker.loader.iface.IExtendedLoader
import de.vanita5.twittnuker.model.ParcelableStatus
import de.vanita5.twittnuker.util.collection.NoDuplicatesArrayList
abstract class ParcelableStatusesLoader(
context: Context,
adapterData: List<ParcelableStatus>?,
protected val tabPosition: Int,
override var fromUser: Boolean
) : FixedAsyncTaskLoader<List<ParcelableStatus>>(context), IExtendedLoader {
protected val data = NoDuplicatesArrayList<ParcelableStatus>()
protected val isFirstLoad: Boolean = adapterData == null
init {
if (adapterData != null) {
data.addAll(adapterData)
}
}
protected fun containsStatus(statusId: String): Boolean {
return data.any { TextUtils.equals(it.id, statusId) }
}
protected fun deleteStatus(statuses: MutableList<ParcelableStatus>?, statusId: String): Boolean {
if (statuses == null || statuses.isEmpty()) return false
var result = false
for (i in statuses.indices.reversed()) {
if (TextUtils.equals(statuses[i].id, statusId)) {
statuses.removeAt(i)
result = true
}
}
return result
}
override fun onStartLoading() {
forceLoad()
}
} | gpl-3.0 | ba12bd18db310ad5ecddc1e54398eee4 | 32.605634 | 101 | 0.704822 | 4.457944 | false | false | false | false |
DarrenAtherton49/android-kotlin-base | app/src/main/kotlin/com/atherton/sample/presentation/base/BaseFragment.kt | 1 | 5096 | package com.atherton.sample.presentation.base
import android.os.Bundle
import android.os.Parcelable
import android.view.LayoutInflater
import android.view.MenuItem
import android.view.View
import android.view.ViewGroup
import androidx.annotation.CallSuper
import androidx.appcompat.widget.Toolbar
import androidx.fragment.app.Fragment
import androidx.navigation.ui.setupWithNavController
import com.atherton.sample.presentation.main.MainActivity
import com.atherton.sample.presentation.main.MainModule
import com.atherton.sample.presentation.main.MainViewEffect
import com.atherton.sample.presentation.main.MainViewModel
import com.atherton.sample.presentation.navigation.Navigator
import com.atherton.sample.presentation.util.extension.observeLiveData
import com.atherton.sample.presentation.util.toolbar.ToolbarOptions
import com.ww.roxie.BaseAction
import com.ww.roxie.BaseState
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.rxkotlin.plusAssign
abstract class BaseFragment<Action : BaseAction,
State,
ViewEffect : BaseViewEffect,
ViewModel : AppViewModel<Action, State, ViewEffect>>
: Fragment()
where State : BaseState,
State : Parcelable {
protected abstract val layoutResId: Int
protected abstract val stateBundleKey: String
protected abstract val viewModel: ViewModel
protected abstract val sharedViewModel: MainViewModel
protected val navigator: Navigator by lazy { mainActivity.navigator }
protected abstract val toolbarOptions: ToolbarOptions?
private var toolbar: Toolbar? = null
private val mainActivity: MainActivity by lazy { activity as MainActivity }
private val disposables: CompositeDisposable = CompositeDisposable()
override fun onCreate(savedInstanceState: Bundle?) {
// support process death by re-supplying last state to ViewModel
val lastState: State? = savedInstanceState?.getParcelable(stateBundleKey)
initInjection(lastState)
super.onCreate(savedInstanceState)
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
return inflater.inflate(layoutResId, container, false)
}
@CallSuper
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
viewModel.observableState.observeLiveData(viewLifecycleOwner) { state ->
state?.let { renderState(state) }
}
setupToolbar(toolbarOptions)
}
override fun onResume() {
super.onResume()
disposables += viewModel.viewEffects()
.observeOn(AndroidSchedulers.mainThread())
.subscribe {
processViewEffects(it)
}
disposables += sharedViewModel.viewEffects()
.observeOn(AndroidSchedulers.mainThread())
.subscribe {
processSharedViewEffects(it)
}
}
override fun onPause() {
super.onPause()
disposables.clear()
}
// support process death by saving last ViewModel state in bundle
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
outState.putParcelable(stateBundleKey, viewModel.observableState.value)
}
protected abstract fun initInjection(initialState: State?)
protected abstract fun renderState(state: State)
protected abstract fun processSharedViewEffects(viewEffect: MainViewEffect)
protected abstract fun processViewEffects(viewEffect: ViewEffect)
protected val mainModule: MainModule by lazy { MainModule(null) }
private fun setupToolbar(toolbarOptions: ToolbarOptions?) {
toolbarOptions?.let {
if (it.toolbarResId != null) {
toolbar = it.toolbarResId.let { id ->
view?.findViewById(id)
}
toolbar?.let { toolbar ->
toolbar.setupWithNavController(mainActivity.navController, mainActivity.appBarConfiguration)
toolbarOptions.titleResId?.let { titleResId ->
toolbar.title = getString(titleResId)
}
toolbarOptions.menuResId?.let { menuResId ->
toolbar.inflateMenu(menuResId)
}
val menu = toolbar.menu
for (i in 0 until menu.size()) {
menu.getItem(i).setOnMenuItemClickListener { menuItem -> onMenuItemClicked(menuItem) }
}
}
}
}
}
fun editMenuItem(menuItemId: Int, editBlock: MenuItem.() -> Unit) {
val menu = toolbar?.menu ?: throw IllegalStateException("Toolbar has not been set so cannot edit")
val menuItem = menu.findItem(menuItemId) ?: throw IllegalArgumentException("Could not find menu item")
menuItem.editBlock()
}
abstract fun onMenuItemClicked(menuItem: MenuItem): Boolean
}
| mit | 021f6f3e6cfd48fe4ca760c2ecce8925 | 35.4 | 115 | 0.692308 | 5.341719 | false | false | false | false |
slartus/4pdaClient-plus | forum/forum-impl/src/main/java/org/softeg/slartus/forpdaplus/forum/impl/ui/ForumViewModel.kt | 1 | 8642 | package org.softeg.slartus.forpdaplus.forum.impl.ui
import android.os.Bundle
import android.widget.Toast
import androidx.annotation.StringRes
import androidx.lifecycle.SavedStateHandle
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.CoroutineExceptionHandler
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.launch
import org.softeg.slartus.forpdaplus.core.AppActions
import org.softeg.slartus.forpdaplus.core.ForumPreferences
import org.softeg.slartus.forpdaplus.core.entities.SearchSettings
import org.softeg.slartus.forpdaplus.core.repositories.UserInfoRepository
import org.softeg.slartus.forpdaplus.core_lib.ui.adapter.Item
import org.softeg.slartus.forpdaplus.forum.impl.R
import org.softeg.slartus.forpdaplus.forum.impl.ui.fingerprints.CrumbItem
import org.softeg.slartus.forpdaplus.forum.impl.ui.fingerprints.ForumDataItem
import org.softeg.slartus.forpdaplus.forum.impl.ui.fingerprints.TopicsItemItem
import ru.softeg.slartus.forum.api.ForumRepository
import javax.inject.Inject
@HiltViewModel
class ForumViewModel @Inject constructor(
private val state: SavedStateHandle,
private val userInfoRepository: UserInfoRepository,
private val forumRepository: ForumRepository,
private val forumPreferences: ForumPreferences,
private val appActions: AppActions
) : ViewModel() {
val showImages: Boolean = forumPreferences.showImages
private val errorHandler = CoroutineExceptionHandler { _, ex ->
_events.value = Event.Error(ex)
}
private val _events = MutableStateFlow<Event>(Event.Empty)
val events: StateFlow<Event> = _events.asStateFlow()
private val _uiState = MutableStateFlow<UiState>(UiState.Initialize)
val uiState: StateFlow<UiState> = _uiState.asStateFlow()
private val _loading = MutableStateFlow(true)
val loading: StateFlow<Boolean> = _loading.asStateFlow()
private var items = emptyList<ForumItemModel>()
private var crumbs = emptyList<ForumItemModel>()
private var userLogined = false
var forumId: String? = state.get(ForumFragment.FORUM_ID_KEY)
set(value) {
field = value
state[ForumFragment.FORUM_ID_KEY] = value
}
init {
reload()
viewModelScope.launch {
launch(errorHandler) {
forumRepository.forum
.distinctUntilChanged()
.collect { rawItems ->
items = rawItems.map {
ForumItemModel(
id = it.id,
title = it.title,
description = it.description,
isHasTopics = it.isHasTopics,
isHasForums = it.isHasForums,
iconUrl = it.iconUrl,
parentId = it.parentId
)
}
refreshDataState(false)
}
}
launch(errorHandler) {
userInfoRepository.userInfo
.distinctUntilChanged()
.collect {
userLogined = it.logined
}
}
}
}
fun setArguments(arguments: Bundle?) {
forumId = this.forumId ?: arguments?.getString(ForumFragment.FORUM_ID_KEY, null)
?: forumPreferences.startForumId
refreshDataState(false)
}
fun reload() {
viewModelScope.launch(errorHandler) {
_loading.value = true
try {
forumRepository.load()
} finally {
_loading.value = false
}
}
}
fun onMarkAsReadClick() {
if (!userLogined) {
_events.value = Event.ShowToast(R.string.need_login)
} else {
_events.value = Event.MarkAsReadConfirmDialog
}
}
fun onMarkAsReadConfirmClick() {
_events.value = Event.ShowToast(R.string.request_sent)
getCurrentForum()?.let { f ->
markForumRead(f.id ?: "-1")
}
}
fun onSetForumStartingClick() {
getCurrentForum()?.let { f ->
setStartForum(f.id)
}
}
fun onCrumbClick(forumId: String?) {
val forum = items.firstOrNull { it.id == forumId }
if (forum?.isHasForums == true || forumId == null)
refreshDataState(forumId)
else if (forum != null)
appActions.showForumTopicsList(forum.id, forum.title)
}
fun onCrumbLongClick(forumId: String?) {
_events.value = Event.ShowUrlMenu(forumRepository.getForumUrl(forumId))
}
fun onForumClick(forumId: String?) {
val forum = items.firstOrNull { it.id == forumId } ?: return
if (forum.isHasForums) {
refreshDataState(forum.id)
} else {
appActions.showForumTopicsList(forum.id, forum.title)
}
}
fun onForumLongClick(forumId: String?) {
_events.value = Event.ShowUrlMenu(forumRepository.getForumUrl(forumId))
}
private fun refreshDataState(forumId: String?) {
this.forumId = forumId
refreshDataState(true)
}
private fun refreshDataState(scrollToTop: Boolean) {
crumbs = buildCrumbs(items)
val currentItems = items.filter { it.parentId == forumId }
.map {
ForumDataItem(
it.id,
it.title,
it.description,
it.iconUrl,
it.isHasForums
)
}
val currentForum = getCurrentForum()
val topicsList =
if (currentForum?.isHasTopics == true) listOf(TopicsItemItem(currentForum.id))
else emptyList()
val items = currentItems + topicsList
val crumbItems = crumbs.map { CrumbItem(it.id, it.title) }
_uiState.value = UiState.Items(crumbItems, items, scrollToTop)
}
private fun buildCrumbs(items: List<ForumItemModel>): List<ForumItemModel> {
if (items.isEmpty()) return emptyList()
val crumbs = ArrayList<ForumItemModel>()
var f = forumId
while (true) {
if (f == null) {
crumbs.add(0, ForumItemModel(null, "4PDA"))
break
} else {
val parent = items.firstOrNull { it.id == f }
f = if (parent == null) {
crumbs.add(0, ForumItemModel(f, parent?.title ?: "Not Found"))
null
} else {
crumbs.add(0, parent)
parent.parentId
}
}
}
return crumbs
}
fun onBack(): Boolean {
if (crumbs.size > 1) {
refreshDataState(crumbs.dropLast(1).last().id)
return true
}
return false
}
private fun getCurrentForum(): ForumItemModel? = items.firstOrNull { it.id == forumId }
private fun markForumRead(forumId: String) {
viewModelScope.launch(errorHandler) {
forumRepository.markAsRead(forumId)
_events.value = Event.ShowToast(R.string.forum_setted_read)
}
}
fun getSearchSettings(): SearchSettings {
val forumIds = forumId?.let { setOf(it) } ?: emptySet()
return SearchSettings(
sourceType = SearchSettings.SourceType.All,
forumIds = forumIds
)
}
private fun setStartForum(id: String?) {
forumPreferences.startForumId = id
_events.value = Event.ShowToast(R.string.forum_setted_to_start)
}
fun onEventReceived() {
_events.value = Event.Empty
}
fun onTopicsClick(id: String?) {
val forum = items.firstOrNull { it.id == id } ?: return
appActions.showForumTopicsList(forum.id, forum.title)
}
sealed class UiState {
object Initialize : UiState()
data class Items(val crumbs: List<Item>, val items: List<Item>, val scrollToTop: Boolean) :
UiState()
}
sealed class Event {
object Empty : Event()
data class Error(val exception: Throwable) : Event()
data class ShowToast(
@StringRes val resId: Int,// maybe need use enum for clear model
val duration: Int = Toast.LENGTH_SHORT
) : Event()
object MarkAsReadConfirmDialog : Event()
data class ShowUrlMenu(val url: String) : Event()
}
}
| apache-2.0 | d83b786ecaafaff917475529eb792d41 | 32.366795 | 99 | 0.589794 | 4.671351 | false | false | false | false |
Xenoage/Zong | utils-kotlin/src/com/xenoage/utils/sequences/FilterWithPreviousSequence.kt | 1 | 1442 | package com.xenoage.utils.sequences
/**
* A sequence that returns the values from the underlying [sequence] that match
* the specified [predicate]. It is identical to the [FilteringSequence] from the
* standard library but also provides the previous filtered value at each item.
*/
class FilterWithPreviousSequence<T>(
private val sequence: Sequence<T>,
private val predicate: (current: T, previous: T?) -> Boolean
) : Sequence<T> {
override fun iterator(): Iterator<T> = object : Iterator<T> {
val iterator = sequence.iterator()
var nextState: Int = -1 // -1 for unknown, 0 for done, 1 for continue
var previousFilteredItem: T? = null //at the beginning, no item was filtered yet
private fun calcNext() {
while (iterator.hasNext()) {
val item = iterator.next()
if (predicate(item, previousFilteredItem)) {
previousFilteredItem = item
nextState = 1
return
}
}
nextState = 0
}
override fun next(): T {
if (nextState == -1)
calcNext()
if (nextState == 0)
throw NoSuchElementException()
val result = previousFilteredItem!!
nextState = -1
return result
}
override fun hasNext(): Boolean {
if (nextState == -1)
calcNext()
return nextState == 1
}
}
}
/** See [FilterWithPreviousSequence]. */
fun <T> Sequence<T>.filterWithPrevious(
predicate: (current: T, previous: T?) -> Boolean): Sequence<T> =
FilterWithPreviousSequence(this, predicate) | agpl-3.0 | e6d0c0d9486cc944d6a39a0bcb05c561 | 26.75 | 82 | 0.680305 | 3.706941 | false | false | false | false |
AndroidX/androidx | glance/glance-wear-tiles/integration-tests/demos/src/main/java/androidx/glance/wear/tiles/demos/TilePreviewActivity.kt | 3 | 2921 | /*
* 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.glance.wear.tiles.demos
import android.content.ComponentName
import android.content.Context
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.FrameLayout
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentActivity
import androidx.wear.tiles.manager.TileUiClient
import androidx.viewpager2.widget.ViewPager2
import androidx.viewpager2.adapter.FragmentStateAdapter
private const val NUM_PAGES = 4
private val TILE_PROVIDERS_NAME = arrayOf(
HelloTileService::class.java,
CalendarTileService::class.java,
CountTileService::class.java,
CurvedLayoutTileService::class.java
)
class TilePageFragment(
private val activityContext: Context,
private val position: Int
) : Fragment() {
lateinit var tileUiClient: TileUiClient
override fun onCreateView(
inflator: LayoutInflater,
container: ViewGroup?,
savedInstanceBundle: Bundle?
): View = inflator.inflate(R.layout.fragment_page, container, false)
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val rootLayout = requireView().findViewById<FrameLayout>(R.id.tile_container)
tileUiClient = TileUiClient(
context = activityContext,
component = ComponentName(activityContext, TILE_PROVIDERS_NAME[position]),
parentView = rootLayout
)
tileUiClient.connect()
}
override fun onDestroy() {
super.onDestroy()
tileUiClient.close()
}
}
class TilePreviewActivity : FragmentActivity() {
private lateinit var viewPager: ViewPager2
override fun onCreate(savedInstanceBundle: Bundle?) {
super.onCreate(savedInstanceBundle)
setContentView(R.layout.activity_main)
viewPager = findViewById(R.id.carousel)
val pagerAdapter = TilePagerAdaptor(this)
viewPager.adapter = pagerAdapter
}
private inner class TilePagerAdaptor(
private val fa: FragmentActivity
) : FragmentStateAdapter(fa) {
override fun getItemCount(): Int = NUM_PAGES
override fun createFragment(position: Int): Fragment = TilePageFragment(fa, position)
}
} | apache-2.0 | a8fdc7ea5ffb0e392695bf1aef364b03 | 31.831461 | 93 | 0.731599 | 4.688604 | false | false | false | false |
AndroidX/androidx | wear/compose/compose-material/samples/src/main/java/androidx/wear/compose/material/samples/StepperSample.kt | 3 | 1879 | /*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.wear.compose.material.samples
import androidx.annotation.Sampled
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.wear.compose.material.Icon
import androidx.wear.compose.material.Stepper
import androidx.wear.compose.material.StepperDefaults
import androidx.wear.compose.material.Text
@Sampled
@Composable
fun StepperSample() {
var value by remember { mutableStateOf(2f) }
Stepper(
value = value,
onValueChange = { value = it },
valueRange = 1f..4f,
increaseIcon = { Icon(StepperDefaults.Increase, "Increase") },
decreaseIcon = { Icon(StepperDefaults.Decrease, "Decrease") },
steps = 7
) { Text("Value: $value") }
}
@Sampled
@Composable
fun StepperWithIntegerSample() {
var value by remember { mutableStateOf(2) }
Stepper(
value = value,
onValueChange = { value = it },
increaseIcon = { Icon(StepperDefaults.Increase, "Increase") },
decreaseIcon = { Icon(StepperDefaults.Decrease, "Decrease") },
valueProgression = 1..10
) { Text("Value: $value") }
}
| apache-2.0 | c7fbc6350b18a5858b724048a70e2964 | 33.163636 | 75 | 0.718999 | 4.203579 | false | false | false | false |
Undin/intellij-rust | src/main/kotlin/org/rust/lang/core/psi/RsPsiFactory.kt | 2 | 27206 | /*
* 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
import com.intellij.openapi.project.Project
import com.intellij.psi.*
import com.intellij.util.LocalTimeCounter
import org.rust.ide.presentation.getStubOnlyText
import org.rust.ide.presentation.renderInsertionSafe
import org.rust.ide.utils.checkMatch.Pattern
import org.rust.lang.RsFileType
import org.rust.lang.RsLanguage
import org.rust.lang.core.macros.MacroExpansionContext
import org.rust.lang.core.macros.prepareExpandedTextForParsing
import org.rust.lang.core.parser.RustParserUtil.PathParsingMode
import org.rust.lang.core.parser.RustParserUtil.PathParsingMode.*
import org.rust.lang.core.psi.ext.*
import org.rust.lang.core.types.Substitution
import org.rust.lang.core.types.infer.substitute
import org.rust.lang.core.types.ty.Mutability
import org.rust.lang.core.types.ty.Mutability.IMMUTABLE
import org.rust.lang.core.types.ty.Mutability.MUTABLE
import org.rust.lang.core.types.ty.Ty
import org.rust.lang.core.types.type
class RsPsiFactory(
private val project: Project,
private val markGenerated: Boolean = true,
private val eventSystemEnabled: Boolean = false
) {
fun createFile(text: CharSequence): RsFile = createPsiFile(text) as RsFile
/**
* Returns [PsiPlainTextFile] if [text] is too large.
* Otherwise returns [RsFile].
*/
fun createPsiFile(text: CharSequence): PsiFile =
PsiFileFactory.getInstance(project)
.createFileFromText(
"DUMMY.rs",
RsFileType,
text,
/*modificationStamp =*/ LocalTimeCounter.currentTime(), // default value
/*eventSystemEnabled =*/ eventSystemEnabled, // `false` by default
/*markAsCopy =*/ markGenerated // `true` by default
)
fun createMacroBody(text: String): RsMacroBody? = createFromText(
"macro_rules! m $text"
)
fun createMacroCall(
context: MacroExpansionContext,
braces: MacroBraces,
macroName: String,
vararg arguments: String
): RsMacroCall = createMacroCall(context, braces, macroName, arguments.joinToString(", "))
fun createMacroCall(
context: MacroExpansionContext,
braces: MacroBraces,
macroName: String,
argument: String
): RsMacroCall {
val appendSemicolon = (context == MacroExpansionContext.ITEM || context == MacroExpansionContext.STMT) &&
braces.needsSemicolon
val semicolon = if (appendSemicolon) ";" else ""
return createFromText(context.prepareExpandedTextForParsing("$macroName!${braces.wrap(argument)}$semicolon"))
?: error("Failed to create macro call")
}
fun createSelf(mutable: Boolean = false): RsSelfParameter {
return createFromText<RsFunction>("fn main(${if (mutable) "mut " else ""}self){}")?.selfParameter
?: error("Failed to create self element")
}
fun createSelfReference(mutable: Boolean = false): RsSelfParameter {
return createFromText<RsFunction>("fn main(&${if (mutable) "mut " else ""}self){}")?.selfParameter
?: error("Failed to create self element")
}
fun createIdentifier(text: String): PsiElement =
createFromText<RsModDeclItem>("mod ${text.escapeIdentifierIfNeeded()};")?.identifier
?: error("Failed to create identifier: `$text`")
fun createQuoteIdentifier(text: String): PsiElement =
createFromText<RsLifetimeParameter>("fn foo<$text>(_: &$text u8) {}")?.quoteIdentifier
?: error("Failed to create quote identifier: `$text`")
fun createMetavarIdentifier(text: String): PsiElement =
createFromText<RsMetaVarIdentifier>("macro m { ($ $text) => () }")
?: error("Failed to create metavar identifier: `$text`")
fun createExpression(text: String): RsExpr =
tryCreateExpression(text)
?: error("Failed to create expression from text: `$text`")
fun tryCreateExpression(text: CharSequence): RsExpr? =
createFromText("fn main() { let _ = $text; }")
fun tryCreateExprStmtWithSemicolon(text: CharSequence): RsExprStmt? =
createFromText<RsExprStmt>("fn main() { $text; }")?.takeIf { it.textLength == text.length + 1 }
fun tryCreateExprStmtWithoutSemicolon(text: CharSequence): RsExprStmt? =
createFromText<RsExprStmt>("fn main() { $text }")?.takeIf { it.textLength == text.length }
fun createTryExpression(expr: RsExpr): RsTryExpr {
val newElement = createExpressionOfType<RsTryExpr>("a?")
newElement.expr.replace(expr)
return newElement
}
fun createIfExpression(condition: RsExpr, thenBranch: RsExpr): RsIfExpr {
val result = createExpressionOfType<RsIfExpr>("if ${condition.text} { () }")
val block = result.block!!
if (thenBranch is RsBlockExpr) {
block.replace(thenBranch.block)
} else {
block.syntaxTailStmt!!.expr.replace(thenBranch)
}
return result
}
fun createIfElseExpression(condition: RsExpr, thenBlock: RsBlock, elseBlock: RsBlock): RsIfExpr {
val resultIfExpr = createExpressionOfType<RsIfExpr>("if ${condition.text} { () } else { () }")
resultIfExpr.block!!.replace(thenBlock)
resultIfExpr.elseBranch!!.block!!.replace(elseBlock)
return resultIfExpr
}
fun createBlockExpr(body: CharSequence): RsBlockExpr =
createExpressionOfType("{ $body }")
fun createUnsafeBlockExprOrStmt(body: PsiElement): RsElement = when (body) {
is RsExpr -> createExpressionOfType<RsBlockExpr>("unsafe { ${body.text} }")
is RsStmt -> createFromText<RsExprStmt>("fn f() { unsafe { ${body.text} } }")!!
else -> error("Unsupported element type: $body")
}
fun createRetExpr(expr: String): RsRetExpr =
createExpressionOfType("return $expr")
fun tryCreatePath(text: String, ns: PathParsingMode = TYPE): RsPath? {
val path = when (ns) {
TYPE -> createFromText("fn foo(t: $text) {}")
VALUE -> createFromText<RsPathExpr>("fn main() { $text; }")?.path
NO_TYPE_ARGS -> error("$NO_TYPE_ARGS mode is not supported; use $TYPE")
} ?: return null
if (path.text != text) return null
return path
}
fun createStructLiteral(name: String): RsStructLiteral =
createExpressionOfType("$name { }")
fun createStructLiteral(name: String, fields: String): RsStructLiteral =
createExpressionOfType("$name $fields")
fun createStructLiteralField(name: String, value: String): RsStructLiteralField {
return createExpressionOfType<RsStructLiteral>("S { $name: $value }")
.structLiteralBody
.structLiteralFieldList[0]
}
fun createStructLiteralField(name: String, value: RsExpr? = null): RsStructLiteralField {
val structLiteralField = createExpressionOfType<RsStructLiteral>("S { $name: () }")
.structLiteralBody
.structLiteralFieldList[0]
if (value != null) structLiteralField.expr?.replace(value)
return structLiteralField
}
fun createStructNamedField(text: String): RsNamedFieldDecl =
createFromText("struct S { $text }") ?: error("Failed to create block fields")
data class BlockField(val name: String, val type: Ty, val addPub: Boolean)
data class TupleField(val type: Ty, val addPub: Boolean)
fun createBlockFields(fields: List<BlockField>): RsBlockFields {
val fieldsText = fields.joinToString(separator = ",\n") {
val typeText = it.type.renderInsertionSafe(includeLifetimeArguments = true)
"${"pub".iff(it.addPub)}${it.name}: $typeText"
}
return createFromText("struct S { $fieldsText }") ?: error("Failed to create block fields")
}
fun createTupleFields(fields: List<TupleField>): RsTupleFields {
val fieldsText = fields.joinToString(separator = ", ") {
val typeText = it.type.renderInsertionSafe(includeLifetimeArguments = true)
"${"pub".iff(it.addPub)}$typeText"
}
return createFromText("struct S($fieldsText)") ?: error("Failed to create tuple fields")
}
@Suppress("unused")
fun createEnum(text: String): RsEnumItem =
createFromText(text)
?: error("Failed to create enum from text: `$text`")
fun createStruct(text: String): RsStructItem =
tryCreateStruct(text)
?: error("Failed to create struct from text: `$text`")
fun tryCreateStruct(text: String): RsStructItem? = createFromText(text)
fun createStatement(text: String): RsStmt =
createFromText("fn main() { $text 92; }")
?: error("Failed to create statement from text: `$text`")
fun createLetDeclaration(name: String, expr: RsExpr?, mutable: Boolean = false, type: RsTypeReference? = null): RsLetDecl =
createStatement("let ${"mut".iff(mutable)}$name${if (type != null) ": ${type.text}" else ""} ${if (expr != null) "= ${expr.text}" else ""};") as RsLetDecl
fun createType(text: CharSequence): RsTypeReference =
tryCreateType(text)
?: error("Failed to create type from text: `$text`")
fun tryCreateType(text: CharSequence): RsTypeReference? =
createFromText("fn main() { let a : $text; }")
fun createMethodParam(text: String): PsiElement {
val fnItem: RsFunction = createTraitMethodMember("fn foo($text);")
return fnItem.selfParameter ?: fnItem.valueParameters.firstOrNull()
?: error("Failed to create method param from text: `$text`")
}
fun createReferenceType(innerTypeText: String, mutable: Boolean): RsRefLikeType =
createType("&${if (mutable) "mut " else ""}$innerTypeText").skipParens() as RsRefLikeType
fun createModDeclItem(modName: String): RsModDeclItem =
tryCreateModDeclItem(modName) ?: error("Failed to create mod decl with name: `$modName`")
fun tryCreateModDeclItem(modName: String): RsModDeclItem? =
createFromText("mod ${modName.escapeIdentifierIfNeeded()};")
fun createUseItem(text: String, visibility: String = "", alias: String? = null): RsUseItem {
val aliasText = if (!alias.isNullOrEmpty()) " as $alias" else ""
return createFromText("$visibility use $text$aliasText;")
?: error("Failed to create use item from text: `$text`")
}
fun createUseSpeck(text: String): RsUseSpeck =
createFromText("use $text;")
?: error("Failed to create use speck from text: `$text`")
fun createExternCrateItem(crateName: String): RsExternCrateItem =
createFromText("extern crate $crateName;")
?: error("Failed to create extern crate item from text: `$crateName`")
fun createModItem(modName: String, modText: String): RsModItem {
val text = """
mod $modName {
$modText
}"""
return createFromText(text) ?: error("Failed to create mod item with name: `$modName` from text: `$modText`")
}
fun createTraitMethodMember(text: String): RsFunction {
return createFromText("trait Foo { $text }") ?: error("Failed to create a method member from text: `$text`")
}
fun createMembers(text: String): RsMembers {
return createFromText("impl T for S {$text}") ?: error("Failed to create members from text: `$text`")
}
fun tryCreateImplItem(text: String): RsImplItem? = createFromText(text)
fun tryCreateTraitItem(text: String): RsTraitItem? = createFromText(text)
fun createInherentImplItem(
name: String,
typeParameterList: RsTypeParameterList? = null,
whereClause: RsWhereClause? = null
): RsImplItem = createImplTemplate(name, typeParameterList, whereClause)
fun createTraitImplItem(
type: String,
trait: String,
typeParameterList: RsTypeParameterList? = null,
whereClause: RsWhereClause? = null
): RsImplItem = createImplTemplate("$trait for $type", typeParameterList, whereClause)
private fun createImplTemplate(
text: String,
typeParameterList: RsTypeParameterList?,
whereClause: RsWhereClause?
): RsImplItem {
val whereText = whereClause?.text ?: ""
val typeParameterListText = typeParameterList?.text ?: ""
val typeArgumentListText = typeParameterList
?.getGenericParameters()
?.mapNotNull {
if (it is RsLifetimeParameter) {
it.quoteIdentifier.text
} else {
it.name
}
}?.joinToString(", ", "<", ">")
.orEmpty()
return createFromText("impl $typeParameterListText $text $typeArgumentListText $whereText { }")
?: error("Failed to create an trait impl with text: `$text`")
}
fun createWhereClause(
lifetimeBounds: List<RsLifetimeParameter>,
typeBounds: List<RsTypeParameter>
): RsWhereClause {
val lifetimeConstraints = lifetimeBounds
.filter { it.lifetimeParamBounds != null }
.mapNotNull { it.text }
val typeConstraints = typeBounds
.filter { it.typeParamBounds != null }
.map {
//ignore default type parameter
it.text.take(it.eq?.startOffsetInParent ?: it.textLength)
}
val whereClauseConstraints = (lifetimeConstraints + typeConstraints).joinToString(", ")
val text = "where $whereClauseConstraints"
return createFromText("fn main() $text {}")
?: error("Failed to create a where clause from text: `$text`")
}
fun createTypeParameterList(
params: Iterable<String>
): RsTypeParameterList {
val text = params.joinToString(prefix = "<", separator = ", ", postfix = ">")
return createFromText<RsFunction>("fn foo$text() {}")?.typeParameterList
?: error("Failed to create type from text: `$text`")
}
fun createTypeParameterList(
params: String
): RsTypeParameterList {
return createFromText<RsFunction>("fn foo<$params>() {}")?.typeParameterList
?: error("Failed to create type parameters from text: `<$params`>")
}
fun createTypeArgumentList(
params: Iterable<String>
): RsTypeArgumentList {
val text = params.joinToString(prefix = "<", separator = ", ", postfix = ">")
return createFromText("type T = a$text") ?: error("Failed to create type argument from text: `$text`")
}
fun createTypeParamBounds(bounds: String): RsTypeParamBounds =
createFromText<RsTraitItem>("trait T : $bounds {}")?.childOfType()
?: error("Failed to create type bounds from text: `$bounds`")
fun createPolybound(bound: String): RsPolybound =
createTypeParamBounds(bound).polyboundList.single()
fun createOuterAttr(text: String): RsOuterAttr =
createFromText("#[$text] struct Dummy;")
?: error("Failed to create an outer attribute from text: `$text`")
fun createInnerAttr(text: String): RsInnerAttr =
createFromText("#![$text]")
?: error("Failed to create an inner attribute from text: `$text`")
fun createMatchBody(patterns: List<Pattern>, ctx: RsElement? = null): RsMatchBody {
val arms = patterns.joinToString("\n") { "${it.text(ctx)} => {}" }
return createExpressionOfType<RsMatchExpr>("match x { $arms }").matchBody
?: error("Failed to create match body from patterns: `$arms`")
}
fun createConstant(name: String, expr: RsExpr): RsConstant =
createFromText("const $name: ${expr.type.renderInsertionSafe(includeLifetimeArguments = true)} = ${expr.text};")
?: error("Failed to create constant $name from ${expr.text} ")
private inline fun <reified T : RsElement> createFromText(code: CharSequence): T? =
createFile(code).descendantOfTypeStrict()
fun createPub(): RsVis =
createFromText("pub fn f() {}")
?: error("Failed to create `pub` element")
fun createPubCrateRestricted(): RsVis =
createFromText("pub(crate) fn f() {}")
?: error("Failed to create `pub(crate)` element")
fun createBlockComment(text: String): PsiComment =
PsiParserFacade.getInstance(project).createBlockCommentFromText(RsLanguage, text)
fun createLineComment(text: String): PsiComment =
PsiParserFacade.getInstance(project).createLineCommentFromText(RsFileType, text)
fun createComma(): PsiElement =
createFromText<RsValueParameter>("fn f(_ : (), )")!!.nextSibling
fun createSemicolon(): PsiElement =
createFromText<RsConstant>("const C: () = ();")!!.semicolon!!
fun createColon(): PsiElement =
createFromText<RsConstant>("const C: () = ();")!!.colon!!
fun createColonColon(): PsiElement =
tryCreatePath("::x")!!.coloncolon!!
fun createEq(): PsiElement =
createFromText<RsConstant>("const C: () = ();")!!.eq!!
fun createPlus(): PsiElement =
(createFromText<RsConstant>("const C = 1 + 1;")!!.expr as RsBinaryExpr).binaryOp.plus!!
fun createIn(): PsiElement =
createFromText<RsConstant>("pub(in self) const C: () = ();")?.vis?.visRestriction?.`in`
?: error("Failed to create `in` element")
fun createNewline(): PsiElement = createWhitespace("\n")
fun createWhitespace(ws: String): PsiElement =
PsiParserFacade.getInstance(project).createWhiteSpaceFromText(ws)
fun createUnsafeKeyword(): PsiElement =
createFromText<RsFunction>("unsafe fn foo(){}")?.unsafe
?: error("Failed to create unsafe element")
fun createAsyncKeyword(): PsiElement =
createFromText<RsFunction>("async fn foo(){}")?.node?.findChildByType(RsElementTypes.ASYNC)?.psi
?: error("Failed to create async element")
fun createFunction(text: String): RsFunction =
tryCreateFunction(text) ?: error("Failed to create function element: $text")
fun tryCreateFunction(text: String): RsFunction? = createFromText(text)
fun createLambda(text: String): RsLambdaExpr =
tryCreateLambda(text) ?: error("Failed to create lambda element: $text")
private fun tryCreateLambda(text: String): RsLambdaExpr? = createFromText("fn main() { let _ = $text }")
fun createRetType(ty: String): RsRetType =
createFromText("fn foo() -> $ty {}")
?: error("Failed to create function return type: $ty")
fun createImpl(name: String, functions: List<RsFunction>): RsImplItem =
createFromText("impl $name {\n${functions.joinToString(separator = "\n", transform = { it.text })}\n}")
?: error("Failed to create RsImplItem element")
fun createSimpleValueParameterList(name: String, type: RsTypeReference): RsValueParameterList {
return createFromText<RsFunction>("fn main($name: ${type.text}){}")
?.valueParameterList
?: error("Failed to create parameter element")
}
fun createValueParameter(
name: String,
type: RsTypeReference,
mutable: Boolean = false,
reference: Boolean = true,
lifetime: RsLifetime? = null
): RsValueParameter {
return tryCreateValueParameter(name, type, mutable, reference, lifetime)
?: error("Failed to create parameter element")
}
fun tryCreateValueParameter(
name: String,
type: RsTypeReference,
mutable: Boolean = false,
reference: Boolean = true,
lifetime: RsLifetime? = null
): RsValueParameter? {
val referenceText = if (reference) "&" else ""
val lifetimeText = if (lifetime != null) "${lifetime.text} " else ""
val mutText = if (mutable) "mut " else ""
return createFromText<RsFunction>("fn main($name: $referenceText$lifetimeText$mutText${type.text}){}")
?.valueParameterList?.valueParameterList?.getOrNull(0)
}
fun createPatFieldFull(name: String, value: String): RsPatFieldFull =
createFromText("fn f(A{$name: $value}: ()) {}")
?: error("Failed to create full field pattern")
fun createPatBinding(name: String, mutable: Boolean = false, ref: Boolean = false): RsPatBinding =
(createStatement("let ${"ref ".iff(ref)}${"mut ".iff(mutable)}$name = 10;") as RsLetDecl).pat
?.firstChild as RsPatBinding?
?: error("Failed to create pat element")
fun createPatField(name: String): RsPatField =
createFromText("""
struct Foo { bar: i32 }
fn baz(foo: Foo) {
let Foo { $name } = foo;
}
""") ?: error("Failed to create pat field")
fun createPatStruct(name: String, pats: List<RsPatField>, patRest: RsPatRest?): RsPatStruct {
val pad = if (pats.isEmpty()) "" else " "
val items = pats.map { it.text } + listOfNotNull(patRest?.text)
val body = items
.joinToString(separator = ", ", prefix = " {$pad", postfix = "$pad}")
return createFromText("fn f($name$body: $name) {}") ?: error("Failed to create pat struct")
}
fun createPatStruct(struct: RsStructItem, name: String? = null): RsPatStruct {
val structName = name ?: struct.name ?: error("Failed to create pat struct")
val pad = if (struct.namedFields.isEmpty()) "" else " "
val body = struct.namedFields
.joinToString(separator = ", ", prefix = " {$pad", postfix = "$pad}") { it.name ?: "_" }
return createFromText("fn f($structName$body: $structName) {}") ?: error("Failed to create pat struct")
}
fun createPatTupleStruct(struct: RsStructItem, name: String? = null): RsPatTupleStruct {
val structName = name ?: struct.name ?: error("Failed to create pat tuple struct")
val body = struct.positionalFields
.joinToString(separator = ", ", prefix = "(", postfix = ")") { "_${it.name}" }
return createFromText("fn f($structName$body: $structName) {}") ?: error("Failed to create pat tuple struct")
}
fun createPatTupleStruct(name: String, pats: List<RsPat>): RsPatTupleStruct {
val patsText = pats.joinToString(", ", prefix = "(", postfix = ")") { it.text }
return createFromText("fn f($name${patsText}: $name) {}") ?: error("Failed to create pat tuple struct")
}
fun createPatTuple(fieldNum: Int): RsPatTup {
val tuple = (0 until fieldNum).joinToString(separator = ", ", prefix = "(", postfix = ")") { "_$it" }
return createFromText("fn f() { let $tuple = x; }") ?: error("Failed to create pat tuple")
}
fun createPatRest(): RsPatRest {
return createFromText("fn f(S {..}: S) {}") ?: error("Failed to create pat rest")
}
fun createCastExpr(expr: RsExpr, typeText: String): RsCastExpr = when (expr) {
is RsBinaryExpr -> createExpressionOfType("(${expr.text}) as $typeText")
else -> createExpressionOfType("${expr.text} as $typeText")
}
fun createFunctionCall(functionName: String, arguments: Iterable<RsExpr>): RsCallExpr =
createExpressionOfType("$functionName(${arguments.joinToString { it.text }})")
fun createFunctionCall(functionName: String, arguments: String): RsCallExpr =
createExpressionOfType("$functionName(${arguments})")
fun createAssocFunctionCall(typeText: String, methodNameText: String, arguments: Iterable<RsExpr>): RsCallExpr {
val isCorrectTypePath = tryCreatePath(typeText) != null
val typePath = if (isCorrectTypePath) typeText else "<$typeText>"
return createExpressionOfType("$typePath::$methodNameText(${arguments.joinToString { it.text }})")
}
fun createNoArgsMethodCall(expr: RsExpr, methodNameText: String): RsDotExpr = when (expr) {
is RsBinaryExpr, is RsUnaryExpr, is RsCastExpr -> createExpressionOfType("(${expr.text}).$methodNameText()")
else -> createExpressionOfType("${expr.text}.$methodNameText()")
}
fun tryCreateMethodCall(receiver: RsExpr, methodNameText: String, arguments: List<RsExpr>): RsDotExpr? =
tryCreateExpressionOfType("${receiver.text}.$methodNameText(${arguments.joinToString(", ") { it.text }})")
fun tryCreateValueArgumentList(arguments: List<RsExpr>): RsValueArgumentList? =
createFromText("fn bar() { foo(${arguments.joinToString(", ") { it.text }}); }")
fun createDerefExpr(expr: RsExpr, nOfDerefs: Int = 1): RsExpr =
if (nOfDerefs > 0)
when (expr) {
is RsBinaryExpr, is RsCastExpr -> createExpressionOfType("${"*".repeat(nOfDerefs)}(${expr.text})")
else -> createExpressionOfType("${"*".repeat(nOfDerefs)}${expr.text}")
}
else expr
fun createRefExpr(expr: RsExpr, muts: List<Mutability> = listOf(IMMUTABLE)): RsExpr =
if (!muts.none())
when (expr) {
is RsBinaryExpr, is RsCastExpr -> createExpressionOfType("${mutsToRefs(muts)}(${expr.text})")
else -> createExpressionOfType("${mutsToRefs(muts)}${expr.text}")
}
else expr
fun createVisRestriction(pathText: String): RsVisRestriction {
val inPrefix = when (pathText) {
"crate", "super", "self" -> ""
else -> "in "
}
return createFromText<RsFunction>("pub($inPrefix$pathText) fn foo() {}")?.vis?.visRestriction
?: error("Failed to create vis restriction element")
}
fun tryCreateVis(text: String): RsVis? = createFromText("$text fn foo() {}")
fun createVis(text: String): RsVis = tryCreateVis(text) ?: error("Failed to create vis")
private inline fun <reified E : RsExpr> createExpressionOfType(text: String): E =
createExpression(text) as? E
?: error("Failed to create ${E::class.simpleName} from `$text`")
private inline fun <reified E : RsExpr> tryCreateExpressionOfType(text: String): E? = createExpression(text) as? E
fun createDynTraitType(pathText: String): RsTraitType =
createFromText("type T = &dyn $pathText;}")
?: error("Failed to create trait type")
fun createPat(patText: String): RsPat = tryCreatePat(patText) ?: error("Failed to create pat element")
fun tryCreatePat(patText: String): RsPat? = (createStatement("let $patText;") as RsLetDecl).pat
fun createAssocTypeBinding(name: String, type: String): RsAssocTypeBinding =
createFromText("type T = &dyn Trait<$name=$type>;")
?: error("Failed to created assoc type binding")
}
private fun String.iff(cond: Boolean) = if (cond) "$this " else " "
fun RsTypeReference.substAndGetText(subst: Substitution): String =
getStubOnlyText(subst)
fun Ty.substAndGetText(subst: Substitution): String =
substitute(subst).renderInsertionSafe(includeLifetimeArguments = true)
private fun mutsToRefs(mutability: List<Mutability>): String =
mutability.joinToString("", "", "") {
when (it) {
IMMUTABLE -> "&"
MUTABLE -> "&mut "
}
}
| mit | 5ef4020bfb4b344b3f7105fd6b2eb327 | 42.5296 | 162 | 0.6446 | 4.563234 | false | false | false | false |
Undin/intellij-rust | src/test/kotlin/org/rust/cargo/project/CargoProjectOpenProcessorTest.kt | 3 | 1655 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.cargo.project
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.projectImport.ProjectOpenProcessor
import com.intellij.testFramework.LightPlatformTestCase
import org.rust.RsTestBase
import org.rust.fileTree
class CargoProjectOpenProcessorTest : RsTestBase() {
fun `test open project via Cargo toml file`() {
val testDir = fileTree {
dir("crate") {
toml("Cargo.toml", "")
dir("src") {
rust("lib.rs", "")
}
}
}.create(project, LightPlatformTestCase.getSourceRoot())
val crateDir = testDir.file("crate/Cargo.toml")
checkFileCanBeOpenedAsProject(crateDir)
}
fun `test open project via directory with Cargo toml file`() {
val testDir = fileTree {
dir("crate") {
toml("Cargo.toml", "")
dir("src") {
rust("lib.rs", "")
}
}
}.create(project, LightPlatformTestCase.getSourceRoot())
val crateDir = testDir.file("crate")
checkFileCanBeOpenedAsProject(crateDir)
}
private fun checkFileCanBeOpenedAsProject(file: VirtualFile) {
val processor = ProjectOpenProcessor.EXTENSION_POINT_NAME.extensionList.find { it is CargoProjectOpenProcessor }
?: error("CargoProjectOpenProcessor is not registered in plugin.xml")
check(processor.canOpenProject(file)) {
"Cargo project cannot be opened via `$file`"
}
}
}
| mit | 7d1ebb4eee51ea720424e36152ef6d14 | 31.45098 | 120 | 0.615106 | 4.839181 | false | true | false | false |
google/dokka | core/src/main/kotlin/Model/PackageDocs.kt | 2 | 5657 | package org.jetbrains.dokka
import com.google.inject.Inject
import com.google.inject.Singleton
import com.intellij.ide.highlighter.JavaFileType
import com.intellij.psi.PsiClass
import com.intellij.psi.PsiFileFactory
import com.intellij.psi.util.PsiTreeUtil
import com.intellij.util.LocalTimeCounter
import org.intellij.markdown.MarkdownElementTypes
import org.intellij.markdown.MarkdownTokenTypes
import org.intellij.markdown.parser.LinkMap
import org.jetbrains.kotlin.cli.jvm.compiler.KotlinCoreEnvironment
import org.jetbrains.kotlin.descriptors.PackageFragmentDescriptor
import java.io.File
@Singleton
class PackageDocs
@Inject constructor(val linkResolver: DeclarationLinkResolver?,
val logger: DokkaLogger,
val environment: KotlinCoreEnvironment,
val refGraph: NodeReferenceGraph,
val elementSignatureProvider: ElementSignatureProvider)
{
val moduleContent: MutableContent = MutableContent()
private val _packageContent: MutableMap<String, MutableContent> = hashMapOf()
val packageContent: Map<String, Content>
get() = _packageContent
fun parse(fileName: String, linkResolveContext: List<PackageFragmentDescriptor>) {
val file = File(fileName)
if (file.exists()) {
val text = file.readText()
val tree = parseMarkdown(text)
val linkMap = LinkMap.buildLinkMap(tree.node, text)
var targetContent: MutableContent = moduleContent
tree.children.forEach {
if (it.type == MarkdownElementTypes.ATX_1) {
val headingText = it.child(MarkdownTokenTypes.ATX_CONTENT)?.text
if (headingText != null) {
targetContent = findTargetContent(headingText.trimStart())
}
} else {
buildContentTo(it, targetContent, LinkResolver(linkMap, { resolveContentLink(fileName, it, linkResolveContext) }))
}
}
} else {
logger.warn("Include file $file was not found.")
}
}
private fun parseHtmlAsJavadoc(text: String, packageName: String, file: File) {
val javadocText = text
.replace("*/", "*/")
.removeSurrounding("<html>", "</html>", true).trim()
.removeSurrounding("<body>", "</body>", true)
.lineSequence()
.map { "* $it" }
.joinToString (separator = "\n", prefix = "/**\n", postfix = "\n*/")
parseJavadoc(javadocText, packageName, file)
}
private fun CharSequence.removeSurrounding(prefix: CharSequence, suffix: CharSequence, ignoringCase: Boolean = false): CharSequence {
if ((length >= prefix.length + suffix.length) && startsWith(prefix, ignoringCase) && endsWith(suffix, ignoringCase)) {
return subSequence(prefix.length, length - suffix.length)
}
return subSequence(0, length)
}
private fun parseJavadoc(text: String, packageName: String, file: File) {
val psiFileFactory = PsiFileFactory.getInstance(environment.project)
val psiFile = psiFileFactory.createFileFromText(
file.nameWithoutExtension + ".java",
JavaFileType.INSTANCE,
"package $packageName; $text\npublic class C {}",
LocalTimeCounter.currentTime(),
false,
true
)
val psiClass = PsiTreeUtil.getChildOfType(psiFile, PsiClass::class.java)!!
val parser = JavadocParser(refGraph, logger, elementSignatureProvider, linkResolver?.externalDocumentationLinkResolver!!)
findOrCreatePackageContent(packageName).apply {
val content = parser.parseDocumentation(psiClass).content
children.addAll(content.children)
content.sections.forEach {
addSection(it.tag, it.subjectName).children.addAll(it.children)
}
}
}
fun parseJava(fileName: String, packageName: String) {
val file = File(fileName)
if (file.exists()) {
val text = file.readText()
val trimmedText = text.trim()
if (trimmedText.startsWith("/**")) {
parseJavadoc(text, packageName, file)
} else if (trimmedText.toLowerCase().startsWith("<html>")) {
parseHtmlAsJavadoc(trimmedText, packageName, file)
}
}
}
private fun findTargetContent(heading: String): MutableContent {
if (heading.startsWith("Module") || heading.startsWith("module")) {
return moduleContent
}
if (heading.startsWith("Package") || heading.startsWith("package")) {
return findOrCreatePackageContent(heading.substring("package".length).trim())
}
return findOrCreatePackageContent(heading)
}
private fun findOrCreatePackageContent(packageName: String) =
_packageContent.getOrPut(packageName) { -> MutableContent() }
private fun resolveContentLink(fileName: String, href: String, linkResolveContext: List<PackageFragmentDescriptor>): ContentBlock {
if (linkResolver != null) {
linkResolveContext
.asSequence()
.map { p -> linkResolver.tryResolveContentLink(p, href) }
.filterNotNull()
.firstOrNull()
?.let { return it }
}
logger.warn("Unresolved link to `$href` in include ($fileName)")
return ContentExternalLink("#")
}
} | apache-2.0 | 2ffd3e51f89a1cf1ac49e969597bad0b | 40.911111 | 137 | 0.620824 | 5.119457 | false | false | false | false |
androidx/androidx | compose/material/material/src/commonMain/kotlin/androidx/compose/material/TextField.kt | 3 | 38405 | /*
* Copyright 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.compose.material
import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.background
import androidx.compose.foundation.interaction.Interaction
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.calculateEndPadding
import androidx.compose.foundation.layout.calculateStartPadding
import androidx.compose.foundation.layout.defaultMinSize
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.shape.ZeroCornerSize
import androidx.compose.foundation.text.BasicTextField
import androidx.compose.foundation.text.KeyboardActions
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material.TextFieldDefaults.indicatorLine
import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.drawWithContent
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.Shape
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.takeOrElse
import androidx.compose.ui.layout.AlignmentLine
import androidx.compose.ui.layout.IntrinsicMeasurable
import androidx.compose.ui.layout.IntrinsicMeasureScope
import androidx.compose.ui.layout.LastBaseline
import androidx.compose.ui.layout.Layout
import androidx.compose.ui.layout.Measurable
import androidx.compose.ui.layout.MeasurePolicy
import androidx.compose.ui.layout.MeasureResult
import androidx.compose.ui.layout.MeasureScope
import androidx.compose.ui.layout.Placeable
import androidx.compose.ui.layout.layoutId
import androidx.compose.ui.platform.LocalLayoutDirection
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.text.input.TextFieldValue
import androidx.compose.ui.text.input.VisualTransformation
import androidx.compose.ui.unit.Constraints
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.coerceAtLeast
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.offset
import kotlin.math.max
import kotlin.math.roundToInt
/**
* <a href="https://material.io/components/text-fields#filled-text-field" class="external" target="_blank">Material Design filled text field</a>.
*
* Filled text fields have more visual emphasis than outlined text fields, making them stand out
* when surrounded by other content and components.
*
* 
*
* If you are looking for an outlined version, see [OutlinedTextField].
*
* A simple single line text field looks like:
*
* @sample androidx.compose.material.samples.SimpleTextFieldSample
*
* You may provide a placeholder:
*
* @sample androidx.compose.material.samples.TextFieldWithPlaceholder
*
* You can also provide leading and trailing icons:
*
* @sample androidx.compose.material.samples.TextFieldWithIcons
*
* To handle the error input state, use [isError] parameter:
*
* @sample androidx.compose.material.samples.TextFieldWithErrorState
*
* Additionally, you may provide additional message at the bottom:
*
* @sample androidx.compose.material.samples.TextFieldWithHelperMessage
*
* Password text field example:
*
* @sample androidx.compose.material.samples.PasswordTextField
*
* Hiding a software keyboard on IME action performed:
*
* @sample androidx.compose.material.samples.TextFieldWithHideKeyboardOnImeAction
*
* If apart from input text change you also want to observe the cursor location, selection range,
* or IME composition use the TextField overload with the [TextFieldValue] parameter instead.
*
* @param value the input text to be shown in the text field
* @param onValueChange the callback that is triggered when the input service updates the text. An
* updated text comes as a parameter of the callback
* @param modifier a [Modifier] for this text field
* @param enabled controls the enabled state of the [TextField]. When `false`, the text field will
* be neither editable nor focusable, the input of the text field will not be selectable,
* visually text field will appear in the disabled UI state
* @param readOnly controls the editable state of the [TextField]. When `true`, the text
* field can not be modified, however, a user can focus it and copy text from it. Read-only text
* fields are usually used to display pre-filled forms that user can not edit
* @param textStyle the style to be applied to the input text. The default [textStyle] uses the
* [LocalTextStyle] defined by the theme
* @param label the optional label to be displayed inside the text field container. The default
* text style for internal [Text] is [Typography.caption] when the text field is in focus and
* [Typography.subtitle1] when the text field is not in focus
* @param placeholder the optional placeholder to be displayed when the text field is in focus and
* the input text is empty. The default text style for internal [Text] is [Typography.subtitle1]
* @param leadingIcon the optional leading icon to be displayed at the beginning of the text field
* container
* @param trailingIcon the optional trailing icon to be displayed at the end of the text field
* container
* @param isError indicates if the text field's current value is in error. If set to true, the
* label, bottom indicator and trailing icon by default will be displayed in error color
* @param visualTransformation transforms the visual representation of the input [value]
* For example, you can use
* [PasswordVisualTransformation][androidx.compose.ui.text.input.PasswordVisualTransformation] to
* create a password text field. By default no visual transformation is applied
* @param keyboardOptions software keyboard options that contains configuration such as
* [KeyboardType] and [ImeAction].
* @param keyboardActions when the input service emits an IME action, the corresponding callback
* is called. Note that this IME action may be different from what you specified in
* [KeyboardOptions.imeAction].
* @param singleLine when set to true, this text field becomes a single horizontally scrolling
* text field instead of wrapping onto multiple lines. The keyboard will be informed to not show
* the return key as the [ImeAction]. Note that [maxLines] parameter will be ignored as the
* maxLines attribute will be automatically set to 1.
* @param maxLines the maximum height in terms of maximum number of visible lines. It is required
* that 1 <= [minLines] <= [maxLines]. This parameter is ignored when [singleLine] is true.
* @param minLines the minimum height in terms of minimum number of visible lines. It is required
* that 1 <= [minLines] <= [maxLines]. This parameter is ignored when [singleLine] is true.
* @param interactionSource the [MutableInteractionSource] representing the stream of
* [Interaction]s for this TextField. You can create and pass in your own remembered
* [MutableInteractionSource] if you want to observe [Interaction]s and customize the
* appearance / behavior of this TextField in different [Interaction]s.
* @param shape the shape of the text field's container
* @param colors [TextFieldColors] that will be used to resolve color of the text, content
* (including label, placeholder, leading and trailing icons, indicator line) and background for
* this text field in different states. See [TextFieldDefaults.textFieldColors]
*/
@Composable
fun TextField(
value: String,
onValueChange: (String) -> Unit,
modifier: Modifier = Modifier,
enabled: Boolean = true,
readOnly: Boolean = false,
textStyle: TextStyle = LocalTextStyle.current,
label: @Composable (() -> Unit)? = null,
placeholder: @Composable (() -> Unit)? = null,
leadingIcon: @Composable (() -> Unit)? = null,
trailingIcon: @Composable (() -> Unit)? = null,
isError: Boolean = false,
visualTransformation: VisualTransformation = VisualTransformation.None,
keyboardOptions: KeyboardOptions = KeyboardOptions.Default,
keyboardActions: KeyboardActions = KeyboardActions(),
singleLine: Boolean = false,
maxLines: Int = if (singleLine) 1 else Int.MAX_VALUE,
minLines: Int = 1,
interactionSource: MutableInteractionSource = remember { MutableInteractionSource() },
shape: Shape =
MaterialTheme.shapes.small.copy(bottomEnd = ZeroCornerSize, bottomStart = ZeroCornerSize),
colors: TextFieldColors = TextFieldDefaults.textFieldColors()
) {
// If color is not provided via the text style, use content color as a default
val textColor = textStyle.color.takeOrElse {
colors.textColor(enabled).value
}
val mergedTextStyle = textStyle.merge(TextStyle(color = textColor))
@OptIn(ExperimentalMaterialApi::class)
BasicTextField(
value = value,
modifier = modifier
.background(colors.backgroundColor(enabled).value, shape)
.indicatorLine(enabled, isError, interactionSource, colors)
.defaultMinSize(
minWidth = TextFieldDefaults.MinWidth,
minHeight = TextFieldDefaults.MinHeight
),
onValueChange = onValueChange,
enabled = enabled,
readOnly = readOnly,
textStyle = mergedTextStyle,
cursorBrush = SolidColor(colors.cursorColor(isError).value),
visualTransformation = visualTransformation,
keyboardOptions = keyboardOptions,
keyboardActions = keyboardActions,
interactionSource = interactionSource,
singleLine = singleLine,
maxLines = maxLines,
minLines = minLines,
decorationBox = @Composable { innerTextField ->
// places leading icon, text field with label and placeholder, trailing icon
TextFieldDefaults.TextFieldDecorationBox(
value = value,
visualTransformation = visualTransformation,
innerTextField = innerTextField,
placeholder = placeholder,
label = label,
leadingIcon = leadingIcon,
trailingIcon = trailingIcon,
singleLine = singleLine,
enabled = enabled,
isError = isError,
interactionSource = interactionSource,
colors = colors
)
}
)
}
@Deprecated(
"Maintained for binary compatibility. Use version with minLines instead",
level = DeprecationLevel.HIDDEN
)
@Composable
fun TextField(
value: String,
onValueChange: (String) -> Unit,
modifier: Modifier = Modifier,
enabled: Boolean = true,
readOnly: Boolean = false,
textStyle: TextStyle = LocalTextStyle.current,
label: @Composable (() -> Unit)? = null,
placeholder: @Composable (() -> Unit)? = null,
leadingIcon: @Composable (() -> Unit)? = null,
trailingIcon: @Composable (() -> Unit)? = null,
isError: Boolean = false,
visualTransformation: VisualTransformation = VisualTransformation.None,
keyboardOptions: KeyboardOptions = KeyboardOptions.Default,
keyboardActions: KeyboardActions = KeyboardActions(),
singleLine: Boolean = false,
maxLines: Int = Int.MAX_VALUE,
interactionSource: MutableInteractionSource = remember { MutableInteractionSource() },
shape: Shape =
MaterialTheme.shapes.small.copy(bottomEnd = ZeroCornerSize, bottomStart = ZeroCornerSize),
colors: TextFieldColors = TextFieldDefaults.textFieldColors()
) {
TextField(
value,
onValueChange,
modifier,
enabled,
readOnly,
textStyle,
label,
placeholder,
leadingIcon,
trailingIcon,
isError,
visualTransformation,
keyboardOptions,
keyboardActions,
singleLine,
maxLines,
1,
interactionSource,
shape,
colors
)
}
/**
* <a href="https://material.io/components/text-fields#filled-text-field" class="external" target="_blank">Material Design filled text field</a>.
*
* Filled text fields have more visual emphasis than outlined text fields, making them stand out
* when surrounded by other content and components.
*
* 
*
* If you are looking for an outlined version, see [OutlinedTextField].
*
* See example usage:
* @sample androidx.compose.material.samples.TextFieldSample
*
* This overload provides access to the input text, cursor position, selection range and
* IME composition. If you only want to observe an input text change, use the TextField
* overload with the [String] parameter instead.
*
* @param value the input [TextFieldValue] to be shown in the text field
* @param onValueChange the callback that is triggered when the input service updates values in
* [TextFieldValue]. An updated [TextFieldValue] comes as a parameter of the callback
* @param modifier a [Modifier] for this text field
* @param enabled controls the enabled state of the [TextField]. When `false`, the text field will
* be neither editable nor focusable, the input of the text field will not be selectable,
* visually text field will appear in the disabled UI state
* @param readOnly controls the editable state of the [TextField]. When `true`, the text
* field can not be modified, however, a user can focus it and copy text from it. Read-only text
* fields are usually used to display pre-filled forms that user can not edit
* @param textStyle the style to be applied to the input text. The default [textStyle] uses the
* [LocalTextStyle] defined by the theme
* @param label the optional label to be displayed inside the text field container. The default
* text style for internal [Text] is [Typography.caption] when the text field is in focus and
* [Typography.subtitle1] when the text field is not in focus
* @param placeholder the optional placeholder to be displayed when the text field is in focus and
* the input text is empty. The default text style for internal [Text] is [Typography.subtitle1]
* @param leadingIcon the optional leading icon to be displayed at the beginning of the text field
* container
* @param trailingIcon the optional trailing icon to be displayed at the end of the text field
* container
* @param isError indicates if the text field's current value is in error state. If set to
* true, the label, bottom indicator and trailing icon by default will be displayed in error color
* @param visualTransformation transforms the visual representation of the input [value].
* For example, you can use
* [PasswordVisualTransformation][androidx.compose.ui.text.input.PasswordVisualTransformation] to
* create a password text field. By default no visual transformation is applied
* @param keyboardOptions software keyboard options that contains configuration such as
* [KeyboardType] and [ImeAction].
* @param keyboardActions when the input service emits an IME action, the corresponding callback
* is called. Note that this IME action may be different from what you specified in
* [KeyboardOptions.imeAction].
* @param singleLine when set to true, this text field becomes a single horizontally scrolling
* text field instead of wrapping onto multiple lines. The keyboard will be informed to not show
* the return key as the [ImeAction]. Note that [maxLines] parameter will be ignored as the
* maxLines attribute will be automatically set to 1.
* @param maxLines the maximum height in terms of maximum number of visible lines. It is required
* that 1 <= [minLines] <= [maxLines]. This parameter is ignored when [singleLine] is true.
* @param minLines the minimum height in terms of minimum number of visible lines. It is required
* that 1 <= [minLines] <= [maxLines]. This parameter is ignored when [singleLine] is true.
* @param interactionSource the [MutableInteractionSource] representing the stream of
* [Interaction]s for this TextField. You can create and pass in your own remembered
* [MutableInteractionSource] if you want to observe [Interaction]s and customize the
* appearance / behavior of this TextField in different [Interaction]s.
* @param shape the shape of the text field's container
* @param colors [TextFieldColors] that will be used to resolve color of the text, content
* (including label, placeholder, leading and trailing icons, indicator line) and background for
* this text field in different states. See [TextFieldDefaults.textFieldColors]
*/
@Composable
fun TextField(
value: TextFieldValue,
onValueChange: (TextFieldValue) -> Unit,
modifier: Modifier = Modifier,
enabled: Boolean = true,
readOnly: Boolean = false,
textStyle: TextStyle = LocalTextStyle.current,
label: @Composable (() -> Unit)? = null,
placeholder: @Composable (() -> Unit)? = null,
leadingIcon: @Composable (() -> Unit)? = null,
trailingIcon: @Composable (() -> Unit)? = null,
isError: Boolean = false,
visualTransformation: VisualTransformation = VisualTransformation.None,
keyboardOptions: KeyboardOptions = KeyboardOptions.Default,
keyboardActions: KeyboardActions = KeyboardActions(),
singleLine: Boolean = false,
maxLines: Int = if (singleLine) 1 else Int.MAX_VALUE,
minLines: Int = 1,
interactionSource: MutableInteractionSource = remember { MutableInteractionSource() },
shape: Shape = TextFieldDefaults.TextFieldShape,
colors: TextFieldColors = TextFieldDefaults.textFieldColors()
) {
// If color is not provided via the text style, use content color as a default
val textColor = textStyle.color.takeOrElse {
colors.textColor(enabled).value
}
val mergedTextStyle = textStyle.merge(TextStyle(color = textColor))
@OptIn(ExperimentalMaterialApi::class)
BasicTextField(
value = value,
modifier = modifier
.background(colors.backgroundColor(enabled).value, shape)
.indicatorLine(enabled, isError, interactionSource, colors)
.defaultMinSize(
minWidth = TextFieldDefaults.MinWidth,
minHeight = TextFieldDefaults.MinHeight
),
onValueChange = onValueChange,
enabled = enabled,
readOnly = readOnly,
textStyle = mergedTextStyle,
cursorBrush = SolidColor(colors.cursorColor(isError).value),
visualTransformation = visualTransformation,
keyboardOptions = keyboardOptions,
keyboardActions = keyboardActions,
interactionSource = interactionSource,
singleLine = singleLine,
maxLines = maxLines,
minLines = minLines,
decorationBox = @Composable { innerTextField ->
// places leading icon, text field with label and placeholder, trailing icon
TextFieldDefaults.TextFieldDecorationBox(
value = value.text,
visualTransformation = visualTransformation,
innerTextField = innerTextField,
placeholder = placeholder,
label = label,
leadingIcon = leadingIcon,
trailingIcon = trailingIcon,
singleLine = singleLine,
enabled = enabled,
isError = isError,
interactionSource = interactionSource,
colors = colors
)
}
)
}
@Deprecated(
"Maintained for binary compatibility. Use version with minLines instead",
level = DeprecationLevel.HIDDEN
)
@Composable
fun TextField(
value: TextFieldValue,
onValueChange: (TextFieldValue) -> Unit,
modifier: Modifier = Modifier,
enabled: Boolean = true,
readOnly: Boolean = false,
textStyle: TextStyle = LocalTextStyle.current,
label: @Composable (() -> Unit)? = null,
placeholder: @Composable (() -> Unit)? = null,
leadingIcon: @Composable (() -> Unit)? = null,
trailingIcon: @Composable (() -> Unit)? = null,
isError: Boolean = false,
visualTransformation: VisualTransformation = VisualTransformation.None,
keyboardOptions: KeyboardOptions = KeyboardOptions.Default,
keyboardActions: KeyboardActions = KeyboardActions(),
singleLine: Boolean = false,
maxLines: Int = Int.MAX_VALUE,
interactionSource: MutableInteractionSource = remember { MutableInteractionSource() },
shape: Shape = TextFieldDefaults.TextFieldShape,
colors: TextFieldColors = TextFieldDefaults.textFieldColors()
) {
TextField(
value,
onValueChange,
modifier,
enabled,
readOnly,
textStyle,
label,
placeholder,
leadingIcon,
trailingIcon,
isError,
visualTransformation,
keyboardOptions,
keyboardActions,
singleLine,
maxLines,
1,
interactionSource,
shape,
colors
)
}
/**
* Composable responsible for measuring and laying out leading and trailing icons, label,
* placeholder and the input field.
*/
@Composable
internal fun TextFieldLayout(
modifier: Modifier,
textField: @Composable () -> Unit,
label: @Composable (() -> Unit)?,
placeholder: @Composable ((Modifier) -> Unit)?,
leading: @Composable (() -> Unit)?,
trailing: @Composable (() -> Unit)?,
singleLine: Boolean,
animationProgress: Float,
paddingValues: PaddingValues
) {
val measurePolicy = remember(singleLine, animationProgress, paddingValues) {
TextFieldMeasurePolicy(singleLine, animationProgress, paddingValues)
}
val layoutDirection = LocalLayoutDirection.current
Layout(
modifier = modifier,
content = {
if (leading != null) {
Box(
modifier = Modifier.layoutId(LeadingId).then(IconDefaultSizeModifier),
contentAlignment = Alignment.Center
) {
leading()
}
}
if (trailing != null) {
Box(
modifier = Modifier.layoutId(TrailingId).then(IconDefaultSizeModifier),
contentAlignment = Alignment.Center
) {
trailing()
}
}
val startTextFieldPadding = paddingValues.calculateStartPadding(layoutDirection)
val endTextFieldPadding = paddingValues.calculateEndPadding(layoutDirection)
val padding = Modifier.padding(
start = if (leading != null) {
(startTextFieldPadding - HorizontalIconPadding).coerceAtLeast(
0.dp
)
} else {
startTextFieldPadding
},
end = if (trailing != null) {
(endTextFieldPadding - HorizontalIconPadding).coerceAtLeast(0.dp)
} else {
endTextFieldPadding
}
)
if (placeholder != null) {
placeholder(Modifier.layoutId(PlaceholderId).then(padding))
}
if (label != null) {
Box(Modifier.layoutId(LabelId).then(padding)) { label() }
}
Box(
modifier = Modifier.layoutId(TextFieldId).then(padding),
propagateMinConstraints = true,
) {
textField()
}
},
measurePolicy = measurePolicy
)
}
private class TextFieldMeasurePolicy(
private val singleLine: Boolean,
private val animationProgress: Float,
private val paddingValues: PaddingValues
) : MeasurePolicy {
override fun MeasureScope.measure(
measurables: List<Measurable>,
constraints: Constraints
): MeasureResult {
val topPaddingValue = paddingValues.calculateTopPadding().roundToPx()
val bottomPaddingValue = paddingValues.calculateBottomPadding().roundToPx()
// padding between label and input text
val topPadding = TextFieldTopPadding.roundToPx()
var occupiedSpaceHorizontally = 0
// measure leading icon
val looseConstraints = constraints.copy(minWidth = 0, minHeight = 0)
val leadingPlaceable =
measurables.find { it.layoutId == LeadingId }?.measure(looseConstraints)
occupiedSpaceHorizontally += widthOrZero(
leadingPlaceable
)
// measure trailing icon
val trailingPlaceable = measurables.find { it.layoutId == TrailingId }
?.measure(looseConstraints.offset(horizontal = -occupiedSpaceHorizontally))
occupiedSpaceHorizontally += widthOrZero(
trailingPlaceable
)
// measure label
val labelConstraints = looseConstraints
.offset(
vertical = -bottomPaddingValue,
horizontal = -occupiedSpaceHorizontally
)
val labelPlaceable =
measurables.find { it.layoutId == LabelId }?.measure(labelConstraints)
val lastBaseline = labelPlaceable?.get(LastBaseline)?.let {
if (it != AlignmentLine.Unspecified) it else labelPlaceable.height
} ?: 0
val effectiveLabelBaseline = max(lastBaseline, topPaddingValue)
// measure input field
// input field is laid out differently depending on whether the label is present or not
val verticalConstraintOffset = if (labelPlaceable != null) {
-bottomPaddingValue - topPadding - effectiveLabelBaseline
} else {
-topPaddingValue - bottomPaddingValue
}
val textFieldConstraints = constraints
.copy(minHeight = 0)
.offset(
vertical = verticalConstraintOffset,
horizontal = -occupiedSpaceHorizontally
)
val textFieldPlaceable = measurables
.first { it.layoutId == TextFieldId }
.measure(textFieldConstraints)
// measure placeholder
val placeholderConstraints = textFieldConstraints.copy(minWidth = 0)
val placeholderPlaceable = measurables
.find { it.layoutId == PlaceholderId }
?.measure(placeholderConstraints)
val width = calculateWidth(
widthOrZero(leadingPlaceable),
widthOrZero(trailingPlaceable),
textFieldPlaceable.width,
widthOrZero(labelPlaceable),
widthOrZero(placeholderPlaceable),
constraints
)
val height = calculateHeight(
textFieldPlaceable.height,
labelPlaceable != null,
effectiveLabelBaseline,
heightOrZero(leadingPlaceable),
heightOrZero(trailingPlaceable),
heightOrZero(placeholderPlaceable),
constraints,
density,
paddingValues
)
return layout(width, height) {
if (labelPlaceable != null) {
// label's final position is always relative to the baseline
val labelEndPosition = (topPaddingValue - lastBaseline).coerceAtLeast(0)
placeWithLabel(
width,
height,
textFieldPlaceable,
labelPlaceable,
placeholderPlaceable,
leadingPlaceable,
trailingPlaceable,
singleLine,
labelEndPosition,
effectiveLabelBaseline + topPadding,
animationProgress,
density
)
} else {
placeWithoutLabel(
width,
height,
textFieldPlaceable,
placeholderPlaceable,
leadingPlaceable,
trailingPlaceable,
singleLine,
density,
paddingValues
)
}
}
}
override fun IntrinsicMeasureScope.maxIntrinsicHeight(
measurables: List<IntrinsicMeasurable>,
width: Int
): Int {
return intrinsicHeight(measurables, width) { intrinsicMeasurable, w ->
intrinsicMeasurable.maxIntrinsicHeight(w)
}
}
override fun IntrinsicMeasureScope.minIntrinsicHeight(
measurables: List<IntrinsicMeasurable>,
width: Int
): Int {
return intrinsicHeight(measurables, width) { intrinsicMeasurable, w ->
intrinsicMeasurable.minIntrinsicHeight(w)
}
}
override fun IntrinsicMeasureScope.maxIntrinsicWidth(
measurables: List<IntrinsicMeasurable>,
height: Int
): Int {
return intrinsicWidth(measurables, height) { intrinsicMeasurable, h ->
intrinsicMeasurable.maxIntrinsicWidth(h)
}
}
override fun IntrinsicMeasureScope.minIntrinsicWidth(
measurables: List<IntrinsicMeasurable>,
height: Int
): Int {
return intrinsicWidth(measurables, height) { intrinsicMeasurable, h ->
intrinsicMeasurable.minIntrinsicWidth(h)
}
}
private fun intrinsicWidth(
measurables: List<IntrinsicMeasurable>,
height: Int,
intrinsicMeasurer: (IntrinsicMeasurable, Int) -> Int
): Int {
val textFieldWidth =
intrinsicMeasurer(measurables.first { it.layoutId == TextFieldId }, height)
val labelWidth = measurables.find { it.layoutId == LabelId }?.let {
intrinsicMeasurer(it, height)
} ?: 0
val trailingWidth = measurables.find { it.layoutId == TrailingId }?.let {
intrinsicMeasurer(it, height)
} ?: 0
val leadingWidth = measurables.find { it.layoutId == LeadingId }?.let {
intrinsicMeasurer(it, height)
} ?: 0
val placeholderWidth = measurables.find { it.layoutId == PlaceholderId }?.let {
intrinsicMeasurer(it, height)
} ?: 0
return calculateWidth(
leadingWidth = leadingWidth,
trailingWidth = trailingWidth,
textFieldWidth = textFieldWidth,
labelWidth = labelWidth,
placeholderWidth = placeholderWidth,
constraints = ZeroConstraints
)
}
private fun IntrinsicMeasureScope.intrinsicHeight(
measurables: List<IntrinsicMeasurable>,
width: Int,
intrinsicMeasurer: (IntrinsicMeasurable, Int) -> Int
): Int {
val textFieldHeight =
intrinsicMeasurer(measurables.first { it.layoutId == TextFieldId }, width)
val labelHeight = measurables.find { it.layoutId == LabelId }?.let {
intrinsicMeasurer(it, width)
} ?: 0
val trailingHeight = measurables.find { it.layoutId == TrailingId }?.let {
intrinsicMeasurer(it, width)
} ?: 0
val leadingHeight = measurables.find { it.layoutId == LeadingId }?.let {
intrinsicMeasurer(it, width)
} ?: 0
val placeholderHeight = measurables.find { it.layoutId == PlaceholderId }?.let {
intrinsicMeasurer(it, width)
} ?: 0
return calculateHeight(
textFieldHeight = textFieldHeight,
hasLabel = labelHeight > 0,
labelBaseline = labelHeight,
leadingHeight = leadingHeight,
trailingHeight = trailingHeight,
placeholderHeight = placeholderHeight,
constraints = ZeroConstraints,
density = density,
paddingValues = paddingValues
)
}
}
private fun calculateWidth(
leadingWidth: Int,
trailingWidth: Int,
textFieldWidth: Int,
labelWidth: Int,
placeholderWidth: Int,
constraints: Constraints
): Int {
val middleSection = maxOf(
textFieldWidth,
labelWidth,
placeholderWidth
)
val wrappedWidth = leadingWidth + middleSection + trailingWidth
return max(wrappedWidth, constraints.minWidth)
}
private fun calculateHeight(
textFieldHeight: Int,
hasLabel: Boolean,
labelBaseline: Int,
leadingHeight: Int,
trailingHeight: Int,
placeholderHeight: Int,
constraints: Constraints,
density: Float,
paddingValues: PaddingValues
): Int {
val paddingToLabel = TextFieldTopPadding.value * density
val topPaddingValue = paddingValues.calculateTopPadding().value * density
val bottomPaddingValue = paddingValues.calculateBottomPadding().value * density
val inputFieldHeight = max(textFieldHeight, placeholderHeight)
val middleSectionHeight = if (hasLabel) {
labelBaseline + paddingToLabel + inputFieldHeight + bottomPaddingValue
} else {
topPaddingValue + inputFieldHeight + bottomPaddingValue
}
return maxOf(
middleSectionHeight.roundToInt(),
max(leadingHeight, trailingHeight),
constraints.minHeight
)
}
/**
* Places the provided text field, placeholder and label with respect to the baseline offsets in
* [TextField] when there is a label. When there is no label, [placeWithoutLabel] is used.
*/
private fun Placeable.PlacementScope.placeWithLabel(
width: Int,
height: Int,
textfieldPlaceable: Placeable,
labelPlaceable: Placeable?,
placeholderPlaceable: Placeable?,
leadingPlaceable: Placeable?,
trailingPlaceable: Placeable?,
singleLine: Boolean,
labelEndPosition: Int,
textPosition: Int,
animationProgress: Float,
density: Float
) {
leadingPlaceable?.placeRelative(
0,
Alignment.CenterVertically.align(leadingPlaceable.height, height)
)
trailingPlaceable?.placeRelative(
width - trailingPlaceable.width,
Alignment.CenterVertically.align(trailingPlaceable.height, height)
)
labelPlaceable?.let {
// if it's a single line, the label's start position is in the center of the
// container. When it's a multiline text field, the label's start position is at the
// top with padding
val startPosition = if (singleLine) {
Alignment.CenterVertically.align(it.height, height)
} else {
// even though the padding is defined by developer, it only affects text field when animation progress == 1,
// which is when text field is focused or non-empty input text. The start position of the label is always 16.dp.
(TextFieldPadding.value * density).roundToInt()
}
val distance = startPosition - labelEndPosition
val positionY = startPosition - (distance * animationProgress).roundToInt()
it.placeRelative(widthOrZero(leadingPlaceable), positionY)
}
textfieldPlaceable.placeRelative(widthOrZero(leadingPlaceable), textPosition)
placeholderPlaceable?.placeRelative(widthOrZero(leadingPlaceable), textPosition)
}
/**
* Places the provided text field and placeholder in [TextField] when there is no label. When
* there is a label, [placeWithLabel] is used
*/
private fun Placeable.PlacementScope.placeWithoutLabel(
width: Int,
height: Int,
textPlaceable: Placeable,
placeholderPlaceable: Placeable?,
leadingPlaceable: Placeable?,
trailingPlaceable: Placeable?,
singleLine: Boolean,
density: Float,
paddingValues: PaddingValues
) {
val topPadding = (paddingValues.calculateTopPadding().value * density).roundToInt()
leadingPlaceable?.placeRelative(
0,
Alignment.CenterVertically.align(leadingPlaceable.height, height)
)
trailingPlaceable?.placeRelative(
width - trailingPlaceable.width,
Alignment.CenterVertically.align(trailingPlaceable.height, height)
)
// Single line text field without label places its input center vertically. Multiline text
// field without label places its input at the top with padding
val textVerticalPosition = if (singleLine) {
Alignment.CenterVertically.align(textPlaceable.height, height)
} else {
topPadding
}
textPlaceable.placeRelative(
widthOrZero(leadingPlaceable),
textVerticalPosition
)
// placeholder is placed similar to the text input above
placeholderPlaceable?.let {
val placeholderVerticalPosition = if (singleLine) {
Alignment.CenterVertically.align(placeholderPlaceable.height, height)
} else {
topPadding
}
it.placeRelative(
widthOrZero(leadingPlaceable),
placeholderVerticalPosition
)
}
}
/**
* A draw modifier that draws a bottom indicator line in [TextField]
*/
internal fun Modifier.drawIndicatorLine(indicatorBorder: BorderStroke): Modifier {
val strokeWidthDp = indicatorBorder.width
return drawWithContent {
drawContent()
if (strokeWidthDp == Dp.Hairline) return@drawWithContent
val strokeWidth = strokeWidthDp.value * density
val y = size.height - strokeWidth / 2
drawLine(
indicatorBorder.brush,
Offset(0f, y),
Offset(size.width, y),
strokeWidth
)
}
}
/** Padding from the label's baseline to the top */
internal val FirstBaselineOffset = 20.dp
/** Padding from input field to the bottom */
internal val TextFieldBottomPadding = 10.dp
/** Padding from label's baseline (or FirstBaselineOffset) to the input field */
/*@VisibleForTesting*/
internal val TextFieldTopPadding = 4.dp | apache-2.0 | da3500c00956efbe93fca2741fa19146 | 40.341227 | 145 | 0.682854 | 5.123399 | false | false | false | false |
androidx/androidx | compose/compiler/compiler-daemon/integration-tests/src/test/kotlin/androidx/compose/compiler/daemon/CompilerTest.kt | 3 | 3653 | /*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.compose.compiler.daemon
import org.jetbrains.kotlin.cli.common.ExitCode
import org.junit.Assert.assertEquals
import org.junit.Assert.assertTrue
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.Parameterized
import java.io.File
import java.nio.file.Files
@RunWith(Parameterized::class)
class CompilerTest(
@Suppress("UNUSED_PARAMETER") name: String,
private val daemonCompiler: DaemonCompiler
) {
companion object {
@JvmStatic
@Parameterized.Parameters(name = "{0}")
fun data(): Array<Array<Any>> = arrayOf(
arrayOf(BasicDaemonCompiler::class.java.name, BasicDaemonCompiler),
arrayOf(IncrementalDaemonCompiler::class.java.name, IncrementalDaemonCompiler)
)
}
@Test
fun `files are compiled successfully`() {
val sourceDir = Files.createTempDirectory("source")
val inputFile = File(sourceDir.toFile(), "Input.kt").apply {
writeText(
"""
fun main() {
}
""".trimIndent()
)
}
val inputFile2 = File(sourceDir.toFile(), "Input2.kt").apply {
writeText(
"""
fun main2() {
}
""".trimIndent()
)
}
run {
val outputDir = Files.createTempDirectory("output")
assertEquals(
ExitCode.OK, daemonCompiler.compile(
arrayOf(
"-d", outputDir.toAbsolutePath().toString(),
inputFile.absolutePath
), DaemonCompilerSettings(null)
)
)
assertTrue(File(outputDir.toFile(), "InputKt.class").exists())
}
// Verify multiple input files
run {
val outputDir = Files.createTempDirectory("output")
assertEquals(
ExitCode.OK, daemonCompiler.compile(
arrayOf(
"-d", outputDir.toAbsolutePath().toString(),
inputFile.absolutePath, inputFile2.absolutePath
), DaemonCompilerSettings(null)
)
)
assertTrue(File(outputDir.toFile(), "InputKt.class").exists())
assertTrue(File(outputDir.toFile(), "Input2Kt.class").exists())
}
}
@Test
fun `compilation fails with syntax errors`() {
val sourceDir = Files.createTempDirectory("source").toFile()
val outputDir = Files.createTempDirectory("output")
val inputFile = File(sourceDir, "Input.kt")
inputFile.writeText(
"""
Invalid code
""".trimIndent()
)
assertEquals(
ExitCode.COMPILATION_ERROR, daemonCompiler.compile(
arrayOf(
"-d", outputDir.toAbsolutePath().toString(),
inputFile.absolutePath
), DaemonCompilerSettings(null)
)
)
}
} | apache-2.0 | 7bf02e33df2dec8395de9d19f64ced59 | 31.918919 | 90 | 0.582809 | 5.080668 | false | false | false | false |
nrizzio/Signal-Android | app/src/main/java/org/thoughtcrime/securesms/gcm/FcmFetchManager.kt | 1 | 4036 | package org.thoughtcrime.securesms.gcm
import android.content.Context
import android.content.Intent
import android.os.Build
import androidx.core.content.ContextCompat
import org.signal.core.util.concurrent.SignalExecutors
import org.signal.core.util.logging.Log
import org.thoughtcrime.securesms.dependencies.ApplicationDependencies
import org.thoughtcrime.securesms.jobs.PushNotificationReceiveJob
import org.thoughtcrime.securesms.messages.RestStrategy
import org.thoughtcrime.securesms.util.concurrent.SerialMonoLifoExecutor
/**
* Our goals with FCM processing are as follows:
* (1) Ensure some service is active for the duration of the fetch and processing stages.
* (2) Do not make unnecessary network requests.
*
* To fulfill goal 1, this class will not stop the services until there is no more running
* requests.
*
* To fulfill goal 2, this class will not enqueue a fetch if there are already 2 active fetches
* (or rather, 1 active and 1 waiting, since we use a single thread executor).
*
* Unfortunately we can't do this all in [FcmReceiveService] because it won't let us process
* the next FCM message until [FcmReceiveService.onMessageReceived] returns,
* but as soon as that method returns, it could also destroy the service. By not letting us control
* when the service is destroyed, we can't accomplish both goals within that service.
*/
object FcmFetchManager {
private val TAG = Log.tag(FcmFetchManager::class.java)
private val EXECUTOR = SerialMonoLifoExecutor(SignalExecutors.UNBOUNDED)
@Volatile
private var activeCount = 0
@Volatile
private var startedForeground = false
/**
* @return True if a service was successfully started, otherwise false.
*/
@JvmStatic
fun enqueue(context: Context, foreground: Boolean): Boolean {
synchronized(this) {
try {
if (foreground) {
Log.i(TAG, "Starting in the foreground.")
ContextCompat.startForegroundService(context, Intent(context, FcmFetchForegroundService::class.java))
startedForeground = true
} else {
Log.i(TAG, "Starting in the background.")
context.startService(Intent(context, FcmFetchBackgroundService::class.java))
}
val performedReplace = EXECUTOR.enqueue { fetch(context) }
if (performedReplace) {
Log.i(TAG, "Already have one running and one enqueued. Ignoring.")
} else {
activeCount++
Log.i(TAG, "Incrementing active count to $activeCount")
}
} catch (e: Exception) {
Log.w(TAG, "Failed to start service!", e)
return false
}
}
return true
}
private fun fetch(context: Context) {
retrieveMessages(context)
synchronized(this) {
activeCount--
if (activeCount <= 0) {
Log.i(TAG, "No more active. Stopping.")
context.stopService(Intent(context, FcmFetchBackgroundService::class.java))
if (startedForeground) {
try {
context.startService(FcmFetchForegroundService.buildStopIntent(context))
} catch (e: IllegalStateException) {
Log.w(TAG, "Failed to stop the foreground notification!", e)
}
startedForeground = false
}
}
}
}
@JvmStatic
fun retrieveMessages(context: Context) {
val success = ApplicationDependencies.getBackgroundMessageRetriever().retrieveMessages(context, RestStrategy(), RestStrategy())
if (success) {
Log.i(TAG, "Successfully retrieved messages.")
} else {
if (Build.VERSION.SDK_INT >= 26) {
Log.w(TAG, "[API ${Build.VERSION.SDK_INT}] Failed to retrieve messages. Scheduling on the system JobScheduler (API " + Build.VERSION.SDK_INT + ").")
FcmJobService.schedule(context)
} else {
Log.w(TAG, "[API ${Build.VERSION.SDK_INT}] Failed to retrieve messages. Scheduling on JobManager (API " + Build.VERSION.SDK_INT + ").")
ApplicationDependencies.getJobManager().add(PushNotificationReceiveJob())
}
}
}
}
| gpl-3.0 | 616d473cf6124416bfb4c2ff92e97897 | 34.403509 | 156 | 0.694252 | 4.372698 | false | false | false | false |
androidx/androidx | compose/ui/ui/integration-tests/ui-demos/src/main/java/androidx/compose/ui/demos/focus/ScrollableRowFocusDemo.kt | 3 | 2400 | /*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.compose.ui.demos.focus
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.focusable
import androidx.compose.foundation.horizontalScroll
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.rememberScrollState
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.focus.onFocusChanged
import androidx.compose.ui.graphics.Color.Companion.Black
import androidx.compose.ui.graphics.Color.Companion.Red
import androidx.compose.ui.graphics.Color.Companion.White
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
@Composable
fun ScrollableRowFocusDemo() {
Column {
Text("Use the dpad or arrow keys to move focus")
Row(Modifier.horizontalScroll(rememberScrollState())) {
repeat(20) {
FocusableBox(it.toString())
}
}
}
}
@Composable
private fun FocusableBox(text: String, modifier: Modifier = Modifier) {
var color by remember { mutableStateOf(White) }
Text(
text = text,
fontSize = 50.sp,
textAlign = TextAlign.Center,
modifier = modifier
.size(100.dp)
.border(2.dp, Black)
.onFocusChanged { color = if (it.isFocused) Red else White }
.background(color)
.focusable()
)
}
| apache-2.0 | df396ec40bc1695485bef96de76961b1 | 34.294118 | 75 | 0.742083 | 4.33213 | false | false | false | false |
androidx/androidx | compose/ui/ui-text/src/androidMain/kotlin/androidx/compose/ui/text/font/AndroidPreloadedFont.kt | 3 | 7523 | /*
* 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.text.font
import android.content.Context
import android.content.res.AssetManager
import android.graphics.Typeface
import android.graphics.fonts.FontVariationAxis
import android.os.Build
import android.os.ParcelFileDescriptor
import androidx.annotation.DoNotInline
import androidx.annotation.RequiresApi
import androidx.compose.ui.text.ExperimentalTextApi
import androidx.compose.ui.unit.Density
import androidx.compose.ui.util.fastMap
import java.io.File
@OptIn(ExperimentalTextApi::class)
internal sealed class AndroidPreloadedFont @OptIn(ExperimentalTextApi::class) constructor(
final override val weight: FontWeight,
final override val style: FontStyle,
variationSettings: FontVariation.Settings
) : AndroidFont(
FontLoadingStrategy.Blocking,
AndroidPreloadedFontTypefaceLoader,
variationSettings
) {
abstract val cacheKey: String?
internal abstract fun doLoad(context: Context?): Typeface?
private var didInitWithContext: Boolean = false
// subclasses MUST initialize this by calling doLoad(null) - after overriding doLoad as final
internal var typeface: Typeface? = null
internal fun loadCached(context: Context): Typeface? {
if (!didInitWithContext && typeface == null) {
typeface = doLoad(context)
}
didInitWithContext = true
return typeface
}
}
private object AndroidPreloadedFontTypefaceLoader : AndroidFont.TypefaceLoader {
override fun loadBlocking(context: Context, font: AndroidFont): Typeface? =
(font as? AndroidPreloadedFont)?.loadCached(context)
override suspend fun awaitLoad(context: Context, font: AndroidFont): Nothing {
throw UnsupportedOperationException("All preloaded fonts are blocking.")
}
}
@OptIn(ExperimentalTextApi::class) /* FontVariation.Settings */
internal class AndroidAssetFont constructor(
val assetManager: AssetManager,
val path: String,
weight: FontWeight = FontWeight.Normal,
style: FontStyle = FontStyle.Normal,
variationSettings: FontVariation.Settings
) : AndroidPreloadedFont(weight, style, variationSettings) {
override fun doLoad(context: Context?): Typeface? {
return if (Build.VERSION.SDK_INT >= 26) {
TypefaceBuilderCompat.createFromAssets(assetManager, path, context, variationSettings)
} else {
Typeface.createFromAsset(assetManager, path)
}
}
init {
typeface = doLoad(null)
}
override val cacheKey: String = "asset:$path"
override fun toString(): String {
return "Font(assetManager, path=$path, weight=$weight, style=$style)"
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is AndroidAssetFont) return false
if (path != other.path) return false
if (variationSettings != other.variationSettings) return false
return true
}
override fun hashCode(): Int {
var result = path.hashCode()
result = 31 * result + variationSettings.hashCode()
return result
}
}
@OptIn(ExperimentalTextApi::class)
internal class AndroidFileFont constructor(
val file: File,
weight: FontWeight = FontWeight.Normal,
style: FontStyle = FontStyle.Normal,
variationSettings: FontVariation.Settings
) : AndroidPreloadedFont(weight, style, variationSettings) {
override fun doLoad(context: Context?): Typeface? {
return if (Build.VERSION.SDK_INT >= 26) {
TypefaceBuilderCompat.createFromFile(file, context, variationSettings)
} else {
Typeface.createFromFile(file)
}
}
init {
typeface = doLoad(null)
}
override val cacheKey: String? = null
override fun toString(): String {
return "Font(file=$file, weight=$weight, style=$style)"
}
}
@RequiresApi(26)
@OptIn(ExperimentalTextApi::class)
internal class AndroidFileDescriptorFont constructor(
val fileDescriptor: ParcelFileDescriptor,
weight: FontWeight = FontWeight.Normal,
style: FontStyle = FontStyle.Normal,
variationSettings: FontVariation.Settings
) : AndroidPreloadedFont(weight, style, variationSettings) {
override fun doLoad(context: Context?): Typeface? {
return if (Build.VERSION.SDK_INT >= 26) {
TypefaceBuilderCompat.createFromFileDescriptor(
fileDescriptor,
context,
variationSettings
)
} else {
throw IllegalArgumentException("Cannot create font from file descriptor for SDK < 26")
}
}
init {
typeface = doLoad(null)
}
override val cacheKey: String? = null
override fun toString(): String {
return "Font(fileDescriptor=$fileDescriptor, weight=$weight, style=$style)"
}
}
@RequiresApi(api = 26)
private object TypefaceBuilderCompat {
@ExperimentalTextApi
@DoNotInline
fun createFromAssets(
assetManager: AssetManager,
path: String,
context: Context?,
variationSettings: FontVariation.Settings
): Typeface? {
if (context == null) {
return null
}
return Typeface.Builder(assetManager, path)
.setFontVariationSettings(variationSettings.toVariationSettings(context))
.build()
}
@ExperimentalTextApi
@DoNotInline
fun createFromFile(
file: File,
context: Context?,
variationSettings: FontVariation.Settings
): Typeface? {
if (context == null) {
return null
}
return Typeface.Builder(file)
.setFontVariationSettings(variationSettings.toVariationSettings(context))
.build()
}
@ExperimentalTextApi
@DoNotInline
fun createFromFileDescriptor(
fileDescriptor: ParcelFileDescriptor,
context: Context?,
variationSettings: FontVariation.Settings,
): Typeface? {
if (context == null) {
return null
}
return Typeface.Builder(fileDescriptor.fileDescriptor)
.setFontVariationSettings(variationSettings.toVariationSettings(context))
.build()
}
@RequiresApi(Build.VERSION_CODES.O)
@ExperimentalTextApi
private fun FontVariation.Settings.toVariationSettings(
context: Context?
): Array<FontVariationAxis> {
val density = if (context != null) {
Density(context)
} else if (!needsDensity) {
// we don't need density, so make a fake one and be on with it
Density(1f, 1f)
} else {
// cannot reach
throw IllegalStateException("Required density, but not provided")
}
return settings.fastMap { setting ->
FontVariationAxis(setting.axisName, setting.toVariationValue(density))
}.toTypedArray()
}
}
| apache-2.0 | f08f9d13079d9ace4f570fef70ab6505 | 31.149573 | 98 | 0.678054 | 4.800893 | false | false | false | false |
androidx/androidx | compose/ui/ui/src/androidMain/kotlin/androidx/compose/ui/input/pointer/PointerInteropUtils.android.kt | 3 | 2567 | /*
* Copyright 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.compose.ui.input.pointer
import android.os.SystemClock
import android.view.InputDevice
import android.view.MotionEvent
import android.view.MotionEvent.ACTION_CANCEL
import androidx.compose.ui.geometry.Offset
/**
* Converts to a [MotionEvent] and runs [block] with it.
*
* @param offset The offset to be applied to the resulting [MotionEvent].
* @param block The block to be executed with the resulting [MotionEvent].
*/
internal fun PointerEvent.toMotionEventScope(
offset: Offset,
block: (MotionEvent) -> Unit
) {
toMotionEventScope(offset, block, false)
}
/**
* Converts to an [MotionEvent.ACTION_CANCEL] [MotionEvent] and runs [block] with it.
*
* @param offset The offset to be applied to the resulting [MotionEvent].
* @param block The block to be executed with the resulting [MotionEvent].
*/
internal fun PointerEvent.toCancelMotionEventScope(
offset: Offset,
block: (MotionEvent) -> Unit
) {
toMotionEventScope(offset, block, true)
}
internal fun emptyCancelMotionEventScope(
nowMillis: Long = SystemClock.uptimeMillis(),
block: (MotionEvent) -> Unit
) {
// Does what ViewGroup does when it needs to send a minimal ACTION_CANCEL event.
val motionEvent =
MotionEvent.obtain(nowMillis, nowMillis, ACTION_CANCEL, 0.0f, 0.0f, 0)
motionEvent.source = InputDevice.SOURCE_UNKNOWN
block(motionEvent)
motionEvent.recycle()
}
private fun PointerEvent.toMotionEventScope(
offset: Offset,
block: (MotionEvent) -> Unit,
cancel: Boolean
) {
val motionEvent = motionEvent
requireNotNull(motionEvent) {
"The PointerEvent receiver cannot have a null MotionEvent."
}
motionEvent.apply {
val oldAction = action
if (cancel) {
action = ACTION_CANCEL
}
offsetLocation(-offset.x, -offset.y)
block(this)
offsetLocation(offset.x, offset.y)
action = oldAction
}
} | apache-2.0 | 373b517c7e034f438631b8976e9ae8d8 | 28.517241 | 85 | 0.710557 | 4.278333 | false | false | false | false |
InfiniteSoul/ProxerAndroid | src/main/kotlin/me/proxer/app/chat/prv/conference/ConferenceAdapter.kt | 1 | 8409 | package me.proxer.app.chat.prv.conference
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.RelativeLayout
import android.widget.TextView
import androidx.core.view.isGone
import androidx.core.view.isVisible
import androidx.core.view.updateLayoutParams
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions
import com.google.android.material.chip.Chip
import com.jakewharton.rxbinding3.view.clicks
import com.mikepenz.iconics.IconicsDrawable
import com.mikepenz.iconics.typeface.IIcon
import com.mikepenz.iconics.typeface.library.community.material.CommunityMaterial
import com.mikepenz.iconics.utils.paddingDp
import com.mikepenz.iconics.utils.sizeDp
import com.mikepenz.iconics.utils.sizePx
import com.uber.autodispose.autoDisposable
import io.reactivex.subjects.PublishSubject
import kotterknife.bindView
import me.proxer.app.GlideRequests
import me.proxer.app.R
import me.proxer.app.base.AutoDisposeViewHolder
import me.proxer.app.base.BaseAdapter
import me.proxer.app.chat.prv.ConferenceWithMessage
import me.proxer.app.chat.prv.conference.ConferenceAdapter.ViewHolder
import me.proxer.app.util.data.StorageHelper
import me.proxer.app.util.extension.colorAttr
import me.proxer.app.util.extension.dip
import me.proxer.app.util.extension.distanceInWordsToNow
import me.proxer.app.util.extension.iconColor
import me.proxer.app.util.extension.logErrors
import me.proxer.app.util.extension.mapAdapterPosition
import me.proxer.app.util.extension.sp
import me.proxer.app.util.extension.toAppString
import me.proxer.app.util.extension.toLocalDateTime
import me.proxer.library.util.ProxerUrls
/**
* @author Ruben Gees
*/
class ConferenceAdapter(private val storageHelper: StorageHelper) : BaseAdapter<ConferenceWithMessage, ViewHolder>() {
var glide: GlideRequests? = null
val clickSubject: PublishSubject<ConferenceWithMessage> = PublishSubject.create()
init {
setHasStableIds(true)
}
override fun getItemId(position: Int): Long = data[position].conference.id
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
return ViewHolder(LayoutInflater.from(parent.context).inflate(R.layout.item_conference, parent, false))
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) = holder.bind(data[position])
override fun onViewRecycled(holder: ViewHolder) {
glide?.clear(holder.image)
}
override fun onDetachedFromRecyclerView(recyclerView: RecyclerView) {
glide = null
}
override fun areItemsTheSame(old: ConferenceWithMessage, new: ConferenceWithMessage): Boolean {
return old.conference.id == new.conference.id
}
inner class ViewHolder(itemView: View) : AutoDisposeViewHolder(itemView) {
internal val container: ViewGroup by bindView(R.id.container)
internal val image: ImageView by bindView(R.id.image)
internal val topic: TextView by bindView(R.id.topic)
internal val time: TextView by bindView(R.id.time)
internal val previewTextContainer: ViewGroup by bindView(R.id.previewTextContainer)
internal val previewText: TextView by bindView(R.id.previewText)
internal val newMessages: Chip by bindView(R.id.newMessages)
fun bind(item: ConferenceWithMessage) {
container.clicks()
.mapAdapterPosition({ adapterPosition }) { data[it] }
.autoDisposable(this)
.subscribe(clickSubject)
bindTopic(item)
bindTime(item)
bindPreviewText(item)
bindNewMessages(item)
bindImage(item)
}
private fun bindTopic(item: ConferenceWithMessage) {
topic.text = item.conference.topic
if (item.message != null) {
topic.updateLayoutParams<RelativeLayout.LayoutParams> {
bottomMargin = 0
addRule(RelativeLayout.CENTER_VERTICAL, 0)
}
} else {
topic.updateLayoutParams<RelativeLayout.LayoutParams> {
bottomMargin = previewTextContainer.context.dip(8)
addRule(RelativeLayout.CENTER_VERTICAL)
}
}
}
private fun bindTime(item: ConferenceWithMessage) {
time.text = item.conference.date.toLocalDateTime().distanceInWordsToNow(time.context)
}
private fun bindPreviewText(item: ConferenceWithMessage) {
if (item.message != null) {
val messageFromUser = item.message.userId == storageHelper.user?.id
val trimmedFirstMessageText = item.message.messageText
.replace("\r\n", " ")
.replace("\n", " ")
.trim()
val processedFirstMessageText = if (item.conference.isGroup && !messageFromUser) {
"${item.message.username}: $trimmedFirstMessageText"
} else {
trimmedFirstMessageText
}
val icon = when (messageFromUser) {
true -> when (item.message.messageId < 0) {
true -> CommunityMaterial.Icon3.cmd_clock_outline
false -> CommunityMaterial.Icon3.cmd_check
}
false -> null
}
val iconicsIcon = if (icon == null) null else generateMessageStatusDrawable(previewText.context, icon)
previewText.text = item.message.messageAction.toAppString(
previewText.context, item.message.username, processedFirstMessageText
)
previewText.setCompoundDrawables(iconicsIcon, null, null, null)
} else {
previewText.text = null
previewText.setCompoundDrawables(null, null, null, null)
}
if (item.conference.localIsRead) {
previewTextContainer.updateLayoutParams<RelativeLayout.LayoutParams> {
topMargin = previewTextContainer.context.dip(8)
bottomMargin = previewTextContainer.context.dip(8)
addRule(RelativeLayout.ALIGN_TOP, 0)
addRule(RelativeLayout.ALIGN_BOTTOM, 0)
addRule(RelativeLayout.BELOW, R.id.topic)
}
} else {
previewTextContainer.updateLayoutParams<RelativeLayout.LayoutParams> {
topMargin = 0
bottomMargin = 0
addRule(RelativeLayout.ALIGN_TOP, R.id.newMessages)
addRule(RelativeLayout.ALIGN_BOTTOM, R.id.newMessages)
addRule(RelativeLayout.BELOW, 0)
}
}
}
private fun bindNewMessages(item: ConferenceWithMessage) {
if (item.conference.localIsRead) {
newMessages.isGone = true
} else {
newMessages.isVisible = true
newMessages.text = item.conference.unreadMessageAmount.toString()
}
}
private fun bindImage(item: ConferenceWithMessage) {
if (item.conference.image.isBlank()) {
val icon = IconicsDrawable(image.context)
.sizeDp(96)
.paddingDp(16)
.colorAttr(image.context, R.attr.colorSecondary)
if (item.conference.isGroup) {
icon.icon(CommunityMaterial.Icon4.cmd_account_multiple)
} else {
icon.icon(CommunityMaterial.Icon4.cmd_account)
}
image.setImageDrawable(icon)
} else {
glide?.load(ProxerUrls.userImage(item.conference.image).toString())
?.transition(DrawableTransitionOptions.withCrossFade())
?.circleCrop()
?.logErrors()
?.into(image)
}
}
private fun generateMessageStatusDrawable(context: Context, icon: IIcon) = IconicsDrawable(context)
.icon(icon)
.iconColor(context)
.sizePx(context.sp(14))
}
}
| gpl-3.0 | 3aafa8a6d9f3c624ef5beb12064bb047 | 38.294393 | 118 | 0.638245 | 5.00238 | false | false | false | false |
inorichi/tachiyomi-extensions | src/en/earlymanga/src/eu/kanade/tachiyomi/extension/en/earlymanga/EarlyManga.kt | 1 | 6856 | package eu.kanade.tachiyomi.extension.en.earlymanga
import android.util.Base64
import eu.kanade.tachiyomi.network.GET
import eu.kanade.tachiyomi.source.model.FilterList
import eu.kanade.tachiyomi.source.model.Page
import eu.kanade.tachiyomi.source.model.SChapter
import eu.kanade.tachiyomi.source.model.SManga
import eu.kanade.tachiyomi.source.online.ParsedHttpSource
import eu.kanade.tachiyomi.util.asJsoup
import okhttp3.Headers
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.Response
import org.jsoup.nodes.Document
import org.jsoup.nodes.Element
import java.text.SimpleDateFormat
import java.util.Locale
import kotlin.math.absoluteValue
import kotlin.random.Random
class EarlyManga : ParsedHttpSource() {
override val name = "EarlyManga"
override val baseUrl = "https://earlymanga.org"
override val lang = "en"
override val supportsLatest = true
override val client: OkHttpClient = network.cloudflareClient
protected open val userAgentRandomizer1 = "${Random.nextInt(9).absoluteValue}"
protected open val userAgentRandomizer2 = "${Random.nextInt(10,99).absoluteValue}"
protected open val userAgentRandomizer3 = "${Random.nextInt(100,999).absoluteValue}"
override fun headersBuilder(): Headers.Builder = Headers.Builder()
.add(
"User-Agent",
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) " +
"Chrome/8$userAgentRandomizer1.0.4$userAgentRandomizer3.1$userAgentRandomizer2 Safari/537.36"
)
.add("Referer", baseUrl)
// popular
override fun popularMangaRequest(page: Int) = GET("$baseUrl/hot-manga?page=$page", headers)
override fun popularMangaSelector() = "div.content-homepage-item"
override fun popularMangaFromElement(element: Element): SManga {
val manga = SManga.create()
manga.url = element.select("a").attr("abs:href").substringAfter(baseUrl)
manga.title = element.select(".colum-content a.homepage-item-title").text()
manga.thumbnail_url = element.select("a img").attr("abs:src")
return manga
}
override fun popularMangaNextPageSelector() = "li.paging:not(.disabled)"
// latest
override fun latestUpdatesRequest(page: Int) = GET("$baseUrl/?page=$page", headers)
override fun latestUpdatesSelector() = ".container > .main-content .content-homepage-item"
override fun latestUpdatesFromElement(element: Element) = popularMangaFromElement(element)
override fun latestUpdatesNextPageSelector() = ".load-data-btn"
// search
override fun searchMangaRequest(page: Int, query: String, filters: FilterList): Request {
return GET("$baseUrl/search?search=$query", headers)
}
override fun searchMangaSelector() = "div.manga-entry"
override fun searchMangaFromElement(element: Element): SManga {
val manga = SManga.create()
manga.url = element.select("a").attr("abs:href").substringAfter(baseUrl)
manga.title = element.select("div:has(.flag)+a").attr("title")
manga.thumbnail_url = element.select("a img").attr("abs:src")
return manga
}
override fun searchMangaNextPageSelector(): String? = null
// manga details
override fun mangaDetailsParse(document: Document) = SManga.create().apply {
thumbnail_url = document.select(".manga-page-img").attr("abs:src")
title = document.select("title").text()
author = document.select(".author-link a").text()
artist = document.select(".artist-link a").text()
status = parseStatus(document.select(".pub_stutus").text())
description = document.select(".desc:not([class*=none])").text().replace("_", "")
genre = document.select(".manga-info-card a.badge-secondary").joinToString { it.text() }
}
private fun parseStatus(status: String?) = when {
status == null -> SManga.UNKNOWN
status.contains("ongoing", true) -> SManga.ONGOING
status.contains("completed", true) -> SManga.COMPLETED
else -> SManga.UNKNOWN
}
// chapters
override fun chapterListRequest(manga: SManga) = chapterListRequest(manga.url, 1)
private fun chapterListRequest(mangaUrl: String, page: Int): Request {
return GET("$baseUrl$mangaUrl?page=$page", headers)
}
override fun chapterListParse(response: Response): List<SChapter> {
var document = response.asJsoup()
val chapters = mutableListOf<SChapter>()
var nextPage = 2
document.select(chapterListSelector()).map { chapters.add(chapterFromElement(it)) }
while (document.select(paginationNextPageSelector).isNotEmpty()) {
val currentPage = document.select(".nav-link.active").attr("href")
document = client.newCall(chapterListRequest(currentPage, nextPage)).execute().asJsoup()
document.select(chapterListSelector()).map { chapters.add(chapterFromElement(it)) }
nextPage++
}
return chapters
}
private val paginationNextPageSelector = popularMangaNextPageSelector()
override fun chapterListSelector() = ".chapter-container > .row:not(:first-child,.d-none)"
override fun chapterFromElement(element: Element) = SChapter.create().apply {
val selectorEncoded1 = "TG1OdmJDro" + "wQWdJQ2NvbEFro" + "wnSUNBZ0lDQWdJQ0FrownSUNj" + "b2xBZ0lDQWdJQ0rowFnSUNBZ0xuSnZkeWN" +
"vbEFnSUNBZ0rowlDQWdJRDRjb2xnSUNBZ0xt" + "TnZiQzFzWnkwMUlDQWrowdJRDRnSU" + "NBZ1lUcHViM1FvT21acGNu" + "TjBMV05rowvYVd4a0tTd2dJY29s" +
"Q0FnSUM1amIyd2dJQ0Fn" + "SUNBdWNtOTNJQ0FnSWNvbENB" + "Z0lDQWdMbU52row" + "YkMxc1p5MDFJQ0FnY2" +
"9sSUNBZ0lDQWdJR0ZiYUhKbFppb" + "zlZMmhoY0hSbGNpMWRXY2ro" + "w9sMmh5WldZcVBWd3ZZMmhoY0hSbGN" + "sMDZhR0Z6S2NvbEdScG" + "Rpaz0="
val selectorEncoded2 = String(Base64.decode(selectorEncoded1.replace("row", ""), Base64.DEFAULT))
val selectorDecoded = String(Base64.decode(selectorEncoded2.replace("col", ""), Base64.DEFAULT))
setUrlWithoutDomain(element.select(selectorDecoded).attr("href"))
name = "Chapter " + url.substringAfter("chapter-")
date_upload = parseChapterDate(element.select(".ml-1").attr("title"))
}
private fun parseChapterDate(date: String): Long {
return try {
SimpleDateFormat("yyyy-MM-dd hh:mm:ss", Locale.US).parse(date)?.time ?: 0
} catch (_: Exception) {
0L
}
}
// pages
override fun pageListParse(document: Document): List<Page> {
return document.select(
"img[src*=manga],img[src*=chapter],div>div>img[src]"
).mapIndexed { i, element ->
Page(i, "", element.attr("abs:src"))
}
}
override fun imageUrlParse(document: Document): String = throw UnsupportedOperationException("Not Used")
}
| apache-2.0 | 87155a7ece2eb98c7338f2287d566641 | 41.583851 | 145 | 0.690053 | 3.931193 | false | false | false | false |
raxden/square | sample/src/main/java/com/raxdenstudios/square/sample/commons/FragmentBottomSheetActivity.kt | 2 | 4796 | package com.raxdenstudios.square.sample.commons
import android.graphics.Color
import android.os.Bundle
import android.support.design.widget.BottomSheetBehavior
import android.support.v7.app.AppCompatActivity
import android.support.v7.widget.Toolbar
import android.view.Menu
import android.view.MenuItem
import android.view.View
import com.raxdenstudios.square.interceptor.Interceptor
import com.raxdenstudios.square.interceptor.commons.autoinflatelayout.AutoInflateLayoutInterceptor
import com.raxdenstudios.square.interceptor.commons.autoinflatelayout.HasAutoInflateLayoutInterceptor
import com.raxdenstudios.square.interceptor.commons.fragmentbottomsheet.FragmentBottomSheetInterceptor
import com.raxdenstudios.square.interceptor.commons.fragmentbottomsheet.HasFragmentBottomSheetInterceptor
import com.raxdenstudios.square.interceptor.commons.injectfragment.HasInjectFragmentInterceptor
import com.raxdenstudios.square.interceptor.commons.injectfragment.InjectFragmentInterceptor
import com.raxdenstudios.square.interceptor.commons.toolbar.HasToolbarInterceptor
import com.raxdenstudios.square.interceptor.commons.toolbar.ToolbarInterceptor
import kotlinx.android.synthetic.main.fragment_bottom_sheet_activity.*
class FragmentBottomSheetActivity : AppCompatActivity(),
HasAutoInflateLayoutInterceptor,
HasToolbarInterceptor,
HasInjectFragmentInterceptor<InjectedFragment>,
HasFragmentBottomSheetInterceptor<View, InjectedFragment> {
private var mAutoInflateLayoutInterceptor: AutoInflateLayoutInterceptor? = null
private var mToolbarInterceptor: ToolbarInterceptor? = null
private var mInjectFragmentInterceptor: InjectFragmentInterceptor? = null
private var mBottomSheetInterceptor: FragmentBottomSheetInterceptor? = null
var mContentView: View? = null
var mToolbarView: Toolbar? = null
var mBottomSheetBehavior: BottomSheetBehavior<View>? = null
var mInjectedFragment: InjectedFragment? = null
var mInjectedBottomFragment: InjectedFragment? = null
override fun onCreateOptionsMenu(menu: Menu?): Boolean {
return super.onCreateOptionsMenu(menu?.apply {
add(0, 1001, 0, "hide")
add(0, 1002, 0, "show")
add(0, 1003, 0, "expand")
add(0, 1004, 0, "collapse")
})
}
override fun onOptionsItemSelected(item: MenuItem?): Boolean {
when (item?.itemId) {
1001 -> mBottomSheetInterceptor?.hide()
1002 -> mBottomSheetInterceptor?.show()
1003 -> mBottomSheetInterceptor?.expand()
1004 -> mBottomSheetInterceptor?.collapse()
}
return super.onOptionsItemSelected(item)
}
// ======== HasInflateLayoutInterceptor ====================================================
override fun onContentViewCreated(view: View) {
mContentView = view
}
// ======== HasToolbarInterceptor ==============================================================
override fun onCreateToolbarView(): Toolbar = toolbar_view
override fun onToolbarViewCreated(toolbar: Toolbar) {
mToolbarView = toolbar
}
// ======== HasInjectFragmentInterceptor =======================================================
override fun onLoadFragmentContainer(): View = container_view
override fun onCreateFragment(): InjectedFragment = InjectedFragment.newInstance(Bundle().apply { putString("title", "Fragment 1") })
override fun onFragmentLoaded(fragment: InjectedFragment) {
mInjectedFragment = fragment
}
// ======== HasFragmentBottomSheetInterceptor ==================================================
override fun onCreateBottomSheetView(): View = bottom_sheet_view
override fun onBottomSheetBehaviourCreated(bottomSheetView: BottomSheetBehavior<View>) {
mBottomSheetBehavior = bottomSheetView
}
override fun onLoadBottomSheetFragmentContainer(): View = bottom_sheet_view
override fun onCreateBottomSheetFragment(): InjectedFragment = InjectedFragment.newInstance(Bundle().apply {
putString("title", "Bottom Sheet Fragment")
putInt("backgroundColor", Color.parseColor("#ff0000"))
})
override fun onBottomSheetFragmentLoaded(fragment: InjectedFragment) {
mInjectedBottomFragment = fragment
}
// =============================================================================================
override fun onInterceptorCreated(interceptor: Interceptor) {
mAutoInflateLayoutInterceptor = interceptor as? AutoInflateLayoutInterceptor
mToolbarInterceptor = interceptor as? ToolbarInterceptor
mInjectFragmentInterceptor = interceptor as? InjectFragmentInterceptor
mBottomSheetInterceptor = interceptor as? FragmentBottomSheetInterceptor
}
} | apache-2.0 | 187232c51cfd240f78a633c2f77fb606 | 43.009174 | 137 | 0.708924 | 5.635723 | false | false | false | false |
JavaEden/Orchid | plugins/OrchidTaxonomies/src/main/kotlin/com/eden/orchid/taxonomies/pages/TaxonomyArchivePage.kt | 2 | 1157 | package com.eden.orchid.taxonomies.pages
import com.eden.orchid.api.options.annotations.Archetype
import com.eden.orchid.api.options.annotations.Description
import com.eden.orchid.api.options.archetypes.ConfigArchetype
import com.eden.orchid.api.render.RenderService
import com.eden.orchid.api.resources.resource.OrchidResource
import com.eden.orchid.api.theme.pages.OrchidPage
import com.eden.orchid.taxonomies.TaxonomiesGenerator
import com.eden.orchid.taxonomies.models.TaxonomiesModel
import com.eden.orchid.taxonomies.models.Taxonomy
@Archetype(value = ConfigArchetype::class, key = "${TaxonomiesGenerator.GENERATOR_KEY}.taxonomyArchivePages")
@Description(value = "A paginated page for all the Terms in a Taxonomy.", name = "Taxonomy")
open class TaxonomyArchivePage(
resource: OrchidResource,
val model: TaxonomiesModel,
val taxonomy: Taxonomy,
val index: Int
) : OrchidPage(resource, RenderService.RenderMode.TEMPLATE, "taxonomyArchive", taxonomy.title) {
override val itemIds: List<String> = listOf(taxonomy.key)
override fun getTemplates(): List<String> {
return listOf("${this.key}-${taxonomy.key}")
}
}
| lgpl-3.0 | c315d0285d0137ab34c311e684c01ea1 | 38.896552 | 109 | 0.785653 | 4.00346 | false | true | false | false |
felipebz/sonar-plsql | zpa-core/src/main/kotlin/org/sonar/plsqlopen/checks/IssueLocation.kt | 1 | 3370 | /**
* Z PL/SQL Analyzer
* Copyright (C) 2015-2022 Felipe Zorzo
* mailto:felipe AT felipezorzo DOT com DOT br
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.plsqlopen.checks
import com.felipebz.flr.api.AstNode
import com.felipebz.flr.api.Token
import org.sonar.plsqlopen.TokenLocation
abstract class IssueLocation private constructor(private val message: String) {
fun message() = message
abstract fun startLine(): Int
abstract fun startLineOffset(): Int
abstract fun endLine(): Int
abstract fun endLineOffset(): Int
private class PreciseIssueLocation : IssueLocation {
private val firstToken: Token
private val lastTokenLocation: TokenLocation
constructor(node: AstNode, message: String) : super(message) {
this.firstToken = node.token
this.lastTokenLocation = TokenLocation.from(node.lastToken)
}
constructor(startNode: AstNode, endNode: AstNode, message: String) : super(message) {
this.firstToken = startNode.token
this.lastTokenLocation = TokenLocation.from(endNode.lastToken)
}
override fun startLine() = firstToken.line
override fun startLineOffset() = firstToken.column
override fun endLine() = lastTokenLocation.endLine()
override fun endLineOffset() = lastTokenLocation.endColumn()
}
private class LineLevelIssueLocation(message: String, private val lineNumber: Int) : IssueLocation(message) {
override fun startLine() = lineNumber
override fun startLineOffset() = UNDEFINED_OFFSET
override fun endLine() = lineNumber
override fun endLineOffset() = UNDEFINED_OFFSET
}
private class FileLevelIssueLocation(message: String) : IssueLocation(message) {
override fun startLine() = UNDEFINED_LINE
override fun startLineOffset() = UNDEFINED_OFFSET
override fun endLine() = UNDEFINED_LINE
override fun endLineOffset() = UNDEFINED_OFFSET
}
companion object {
const val UNDEFINED_OFFSET = -1
const val UNDEFINED_LINE = 0
fun atFileLevel(message: String): IssueLocation =
FileLevelIssueLocation(message)
fun atLineLevel(message: String, lineNumber: Int): IssueLocation =
LineLevelIssueLocation(message, lineNumber)
fun preciseLocation(startNode: AstNode, endNode: AstNode, message: String): IssueLocation =
PreciseIssueLocation(startNode, endNode, message)
fun preciseLocation(startNode: AstNode, message: String): IssueLocation =
PreciseIssueLocation(startNode, message)
}
}
| lgpl-3.0 | 3918b5c0fc65d889a5a7a4e8c801a5a7 | 31.095238 | 113 | 0.702967 | 4.821173 | false | false | false | false |
westnordost/StreetComplete | app/src/main/java/de/westnordost/streetcomplete/quests/bike_parking_type/AddBikeParkingType.kt | 1 | 1026 | package de.westnordost.streetcomplete.quests.bike_parking_type
import de.westnordost.streetcomplete.R
import de.westnordost.streetcomplete.data.osm.osmquest.OsmFilterQuestType
import de.westnordost.streetcomplete.data.osm.changes.StringMapChangesBuilder
class AddBikeParkingType : OsmFilterQuestType<BikeParkingType>() {
override val elementFilter = """
nodes, ways with
amenity = bicycle_parking
and access !~ private|no
and !bicycle_parking
"""
override val commitMessage = "Add bicycle parking type"
override val wikiLink = "Key:bicycle_parking"
override val icon = R.drawable.ic_quest_bicycle_parking
override val isDeleteElementEnabled = true
override fun getTitle(tags: Map<String, String>) = R.string.quest_bicycle_parking_type_title
override fun createForm() = AddBikeParkingTypeForm()
override fun applyAnswerTo(answer: BikeParkingType, changes: StringMapChangesBuilder) {
changes.add("bicycle_parking", answer.osmValue)
}
}
| gpl-3.0 | 37475a98b0e955691564102633e8e252 | 37 | 96 | 0.746589 | 4.519824 | false | false | false | false |
westnordost/StreetComplete | app/src/main/java/de/westnordost/streetcomplete/quests/tactile_paving/AddTactilePavingBusStop.kt | 1 | 1970 | package de.westnordost.streetcomplete.quests.tactile_paving
import de.westnordost.streetcomplete.R
import de.westnordost.streetcomplete.data.meta.updateWithCheckDate
import de.westnordost.streetcomplete.data.osm.osmquest.OsmFilterQuestType
import de.westnordost.streetcomplete.data.osm.changes.StringMapChangesBuilder
import de.westnordost.streetcomplete.data.quest.NoCountriesExcept
import de.westnordost.streetcomplete.ktx.toYesNo
class AddTactilePavingBusStop : OsmFilterQuestType<Boolean>() {
override val elementFilter = """
nodes, ways with
(
(public_transport = platform and (bus = yes or trolleybus = yes or tram = yes))
or
(highway = bus_stop and public_transport != stop_position)
)
and physically_present != no and naptan:BusStopType != HAR
and (
!tactile_paving
or tactile_paving = no and tactile_paving older today -4 years
or tactile_paving older today -8 years
)
"""
override val commitMessage = "Add tactile pavings on bus stops"
override val wikiLink = "Key:tactile_paving"
override val icon = R.drawable.ic_quest_blind_bus
override val enabledInCountries = COUNTRIES_WHERE_TACTILE_PAVING_IS_COMMON
override fun getTitle(tags: Map<String, String>): Int {
val hasName = tags.containsKey("name")
val isTram = tags["tram"] == "yes"
return when {
isTram && hasName -> R.string.quest_tactilePaving_title_name_tram
isTram -> R.string.quest_tactilePaving_title_tram
hasName -> R.string.quest_tactilePaving_title_name_bus
else -> R.string.quest_tactilePaving_title_bus
}
}
override fun createForm() = TactilePavingForm()
override fun applyAnswerTo(answer: Boolean, changes: StringMapChangesBuilder) {
changes.updateWithCheckDate("tactile_paving", answer.toYesNo())
}
}
| gpl-3.0 | 8a913e06a062aae1f1822408de196473 | 40.914894 | 89 | 0.678173 | 4.41704 | false | false | false | false |
ilya-g/kotlinx.collections.experimental | kotlinx-collections-experimental/src/main/kotlin/kotlinx.collections.experimental/grouping/reducers.kt | 1 | 4135 | package kotlinx.collections.experimental.grouping
import java.util.*
import kotlin.jvm.internal.Ref.IntRef
typealias StepFunction<R, T> = (R, T) -> R
interface RReducer<R, A, in T> : StepFunction<A, T> {
override fun invoke(acc: A, item: T): A
fun initial(item: T): A
fun final(result: A): R
}
interface Reducer<R, in T> : RReducer<R, R, T> {
override fun final(result: R): R = result
}
/*
interface Transducer<B, C> {
fun <R, A> transform(r: RReducer<R, A, B>): RReducer<R, A, C>
}
public fun <A, B> map(f: (B) -> A): Transducer<A, B> = object : Transducer<A, B> {
override fun <R, Acc> transform(r: RReducer<R, Acc, A>) = object : RReducer<R, Acc, B> {
override fun initial(item: B): Acc = r.initial(f(item))
override fun invoke(acc: Acc, item: B): Acc = r(acc, f(item))
override fun final(result: Acc): R = r.final(result)
}
}*/
//typealias TransducerTA<R, A, B, C> = (RReducer<R, A, B>) -> RReducer<R, A, C>
//public fun <A, B, R, Acc> mapTA(f: (B) -> A): TransducerTA<R, Acc, A, B> = object : TransducerTA<R, Acc, A, B> {
//
//}
object Sum {
object Ints : Reducer<Int, Int> {
override fun invoke(acc: Int, item: Int): Int = acc + item
override fun initial(item: Int): Int = item
}
object Longs : Reducer<Long, Long> {
override fun invoke(acc: Long, item: Long): Long = acc + item
override fun initial(item: Long): Long = item
}
inline fun <T> by(crossinline selector: (T) -> Int) = object : Reducer<Int, T> {
override fun invoke(acc: Int, item: T): Int = acc + selector(item)
override fun initial(item: T): Int = selector(item)
}
inline fun <T> byLong(crossinline selector: (T) -> Long) = object : Reducer<Long, T> {
override fun invoke(acc: Long, item: T): Long = acc + selector(item)
override fun initial(item: T): Long = selector(item)
}
}
object RefSum {
inline fun <T> by(crossinline selector: (T) -> Int) = object : RReducer<Int, IntRef, T> {
override fun invoke(acc: IntRef, item: T): IntRef = acc.apply { element += selector(item) }
override fun initial(item: T): IntRef = IntRef().apply { element = selector(item) }
override fun final(result: IntRef): Int = result.element
}
}
object Count : Reducer<Int, Any?> {
override fun initial(item: Any?): Int = 1
override fun invoke(acc: Int, item: Any?) = acc + 1
}
object CountWithRef : RReducer<Int, IntRef, Any?> {
override fun invoke(acc: IntRef, item: Any?): IntRef = acc.apply { this.element += 1 }
override fun initial(item: Any?) = IntRef()
override fun final(result: IntRef) = result.element
}
object StringJoin {
fun <T> with(delimiter: String) = object : RReducer<String, StringBuilder, T> {
override fun initial(item: T): StringBuilder = StringBuilder(item.toString())
override fun invoke(acc: StringBuilder, item: T): StringBuilder = acc.append(delimiter).append(item.toString())
override fun final(result: StringBuilder): String = result.toString()
}
fun <T> with(delimiter: String, prefix: String, suffix: String) = object : RReducer<String, StringBuilder, T> {
override fun initial(item: T): StringBuilder = StringBuilder().append(prefix).append(item.toString())
override fun invoke(acc: StringBuilder, item: T): StringBuilder = acc.append(delimiter).append(item.toString())
override fun final(result: StringBuilder): String = result.append(suffix).toString()
}
}
public fun <T, R, A> Iterable<T>.reduce(reducer: RReducer<R, A, T>): R {
val it = iterator()
if (!it.hasNext())
throw NoSuchElementException("Empty collection can't be reduced")
var accumulator = reducer.initial(it.next())
for (e in it) {
accumulator = reducer(accumulator, e)
}
return reducer.final(accumulator)
}
fun main(args: Array<String>) {
val items = listOf(1, 2, 2, 9, 15, 21)
println(items.reduce(Count))
println(items.reduce(Sum.Ints))
println(items.map { it.toLong() }.reduce(Sum.Longs))
println(items.reduce(StringJoin.with("=")))
} | apache-2.0 | 74e2250d838b5d553a1be93302991a29 | 34.350427 | 119 | 0.634341 | 3.370008 | false | false | false | false |
StepicOrg/stepic-android | app/src/main/java/org/stepik/android/domain/lesson/interactor/LessonContentInteractor.kt | 2 | 3622 | package org.stepik.android.domain.lesson.interactor
import io.reactivex.Single
import io.reactivex.rxkotlin.Singles.zip
import io.reactivex.rxkotlin.toObservable
import org.stepic.droid.persistence.content.StepContentResolver
import org.stepic.droid.persistence.model.StepPersistentWrapper
import org.stepik.android.domain.assignment.repository.AssignmentRepository
import org.stepik.android.domain.lesson.model.StepItem
import org.stepik.android.domain.progress.mapper.getProgresses
import org.stepik.android.domain.progress.repository.ProgressRepository
import org.stepik.android.domain.review_session.model.ReviewSessionData
import org.stepik.android.domain.review_session.repository.ReviewSessionRepository
import org.stepik.android.domain.step.repository.StepRepository
import org.stepik.android.model.Assignment
import org.stepik.android.model.Lesson
import org.stepik.android.model.Progress
import org.stepik.android.model.Unit
import javax.inject.Inject
class LessonContentInteractor
@Inject
constructor(
private val assignmentRepository: AssignmentRepository,
private val stepRepository: StepRepository,
private val progressRepository: ProgressRepository,
private val stepContentResolver: StepContentResolver,
private val reviewSessionRepository: ReviewSessionRepository
) {
fun getStepItems(unit: Unit?, lesson: Lesson): Single<List<StepItem>> =
zip(
getAssignments(unit),
getSteps(*lesson.steps)
)
.flatMap { (assignments, steps) ->
getStepItems(assignments, steps, lesson.actions?.editLesson == null)
}
private fun getStepItems(assignments: List<Assignment>, steps: List<StepPersistentWrapper>, mustLoadReviewSessions: Boolean): Single<List<StepItem>> {
val progressIds = assignments.getProgresses() + steps.getProgresses()
val reviewSessionsSingle = if (mustLoadReviewSessions) {
reviewSessionRepository.getReviewSessions(steps.mapNotNull { it.step.session })
} else {
Single.just(emptyList())
}
return zip(
progressRepository.getProgresses(progressIds),
reviewSessionsSingle
) { progresses, reviewSessions ->
packStepItems(assignments, steps, progresses, reviewSessions)
}
}
private fun getSteps(vararg stepIds: Long): Single<List<StepPersistentWrapper>> =
stepRepository
.getSteps(*stepIds)
.flatMapObservable { it.toObservable() }
.flatMapSingle(stepContentResolver::resolvePersistentContent)
.toList()
private fun getAssignments(unit: Unit?): Single<List<Assignment>> =
assignmentRepository
.getAssignments(*unit?.assignments ?: emptyList())
private fun packStepItems(assignments: List<Assignment>, steps: List<StepPersistentWrapper>, progresses: List<Progress>, reviewSessions: List<ReviewSessionData>): List<StepItem> =
steps
.map { stepWrapper ->
val assignment = assignments
.find { it.step == stepWrapper.step.id }
val reviewSession = reviewSessions
.find { it.id == stepWrapper.step.session }
StepItem(
stepWrapper = stepWrapper,
stepProgress = progresses.find { it.id == stepWrapper.progress },
assignment = assignment,
assignmentProgress = progresses.find { it.id == assignment?.progress },
reviewSession = reviewSession?.session
)
}
} | apache-2.0 | 2d118ce6f4975b6fdf732b1f44171d94 | 42.130952 | 183 | 0.696024 | 4.982118 | false | false | false | false |
InsertKoinIO/koin | examples/androidx-samples/src/main/java/org/koin/sample/androidx/mvvm/MVVMActivity.kt | 1 | 2588 | package org.koin.sample.androidx.mvvm
import android.os.Bundle
import kotlinx.android.synthetic.main.mvvm_activity.*
import org.koin.android.ext.android.getKoin
import org.koin.androidx.fragment.android.replace
import org.koin.androidx.fragment.android.setupKoinFragmentFactory
import org.koin.androidx.scope.ScopeActivity
import org.koin.androidx.viewmodel.ext.android.viewModel
import org.koin.core.parameter.parametersOf
import org.koin.core.qualifier.named
import org.koin.sample.android.R
import org.koin.sample.androidx.components.ID
import org.koin.sample.androidx.components.mvvm.ExtSimpleViewModel
import org.koin.sample.androidx.components.mvvm.SavedStateBundleViewModel
import org.koin.sample.androidx.components.mvvm.SavedStateViewModel
import org.koin.sample.androidx.components.mvvm.SimpleViewModel
import org.koin.sample.androidx.components.scope.Session
import org.koin.sample.androidx.scope.ScopedActivityA
import org.koin.sample.androidx.utils.navigateTo
class MVVMActivity : ScopeActivity(contentLayoutId = R.layout.mvvm_activity) {
val simpleViewModel: SimpleViewModel by viewModel { parametersOf(ID) }
val vm1: SimpleViewModel by viewModel(named("vm1")) { parametersOf("vm1") }
val scopeVm: ExtSimpleViewModel by viewModel()
val extScopeVm: ExtSimpleViewModel by viewModel(named("ext"))
// val savedVm: SavedStateViewModel by stateViewModel { parametersOf("vm1") }
val savedVm: SavedStateViewModel by viewModel { parametersOf("vm1") }
// val state = Bundle().apply { putString("id", "vm1") }
// val stateVM: SavedStateBundleViewModel by stateViewModel(state = { state })
val stateVM: SavedStateBundleViewModel by viewModel()
override fun onCreate(savedInstanceState: Bundle?) {
// should set `lifecycleScope` here because we're
// using MVVMActivity with scope in mvvmModule (AppModule)
setupKoinFragmentFactory(scope)
super.onCreate(savedInstanceState)
checkNotNull(vm1)
checkNotNull(simpleViewModel)
title = "Android MVVM"
supportFragmentManager.beginTransaction()
.replace<MVVMFragment>(R.id.mvvm_frame)
.commit()
getKoin().setProperty("session_id", scope.get<Session>().id)
mvvm_button.setOnClickListener {
navigateTo<ScopedActivityA>(isRoot = true)
}
assert(scopeVm.session.id == extScopeVm.session.id)
assert(stateVM.result == "vm1")
}
override fun onStop() {
super.onStop()
println("simpleViewModel:${simpleViewModel.service}")
}
} | apache-2.0 | 03ff8f36e7cf2e7700556194981b6986 | 37.073529 | 84 | 0.743431 | 4.180937 | false | false | false | false |
dhleong/ideavim | src/com/maddyhome/idea/vim/action/motion/text/MotionWordLeftAction.kt | 1 | 2810 | /*
* IdeaVim - Vim emulator for IDEs based on the IntelliJ platform
* Copyright (C) 2003-2019 The IdeaVim authors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.maddyhome.idea.vim.action.motion.text
import com.intellij.openapi.actionSystem.DataContext
import com.intellij.openapi.editor.Caret
import com.intellij.openapi.editor.Editor
import com.maddyhome.idea.vim.VimPlugin
import com.maddyhome.idea.vim.action.MotionEditorAction
import com.maddyhome.idea.vim.command.Argument
import com.maddyhome.idea.vim.command.CommandFlags
import com.maddyhome.idea.vim.command.MappingMode
import com.maddyhome.idea.vim.handler.MotionActionHandler
import java.awt.event.KeyEvent
import java.util.*
import javax.swing.KeyStroke
class MotionWordLeftAction : MotionEditorAction() {
override val mappingModes: Set<MappingMode> = MappingMode.NVO
override val keyStrokesSet: Set<List<KeyStroke>> = parseKeysSet("b")
override val flags: EnumSet<CommandFlags> = EnumSet.of(CommandFlags.FLAG_MOT_EXCLUSIVE)
override fun makeActionHandler(): MotionActionHandler = MotionWordLeftActionHandler
}
class MotionWordLeftInsertAction : MotionEditorAction() {
override val mappingModes: Set<MappingMode> = MappingMode.I
override val keyStrokesSet: Set<List<KeyStroke>> = setOf(
listOf(KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, KeyEvent.CTRL_MASK)),
listOf(KeyStroke.getKeyStroke(KeyEvent.VK_KP_LEFT, KeyEvent.CTRL_MASK)),
listOf(KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, KeyEvent.SHIFT_MASK)),
listOf(KeyStroke.getKeyStroke(KeyEvent.VK_KP_LEFT, KeyEvent.SHIFT_MASK))
)
override val flags: EnumSet<CommandFlags> = EnumSet.of(CommandFlags.FLAG_SAVE_STROKE)
override fun makeActionHandler(): MotionActionHandler = MotionWordLeftActionHandler
}
private object MotionWordLeftActionHandler : MotionActionHandler.ForEachCaret() {
override fun getOffset(editor: Editor,
caret: Caret,
context: DataContext,
count: Int,
rawCount: Int,
argument: Argument?): Int {
return VimPlugin.getMotion().findOffsetOfNextWord(editor, caret.offset, -count, false)
}
}
| gpl-2.0 | 3296107b5446230e9a41ba6a07367bb6 | 39.724638 | 90 | 0.751601 | 4.383775 | false | false | false | false |
CarlosEsco/tachiyomi | app/src/main/java/eu/kanade/presentation/util/Constants.kt | 1 | 341 | package eu.kanade.presentation.util
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.ui.unit.dp
private val horizontal = 16.dp
private val vertical = 8.dp
val horizontalPadding = horizontal
val verticalPadding = vertical
val topPaddingValues = PaddingValues(top = vertical)
const val ReadItemAlpha = .38f
| apache-2.0 | 60d50f8547380f1ee9b32fffba58b13f | 23.357143 | 55 | 0.815249 | 4.158537 | false | false | false | false |
Heiner1/AndroidAPS | database/src/main/java/info/nightscout/androidaps/database/embedments/InterfaceIDs.kt | 1 | 1365 | package info.nightscout.androidaps.database.embedments
data class InterfaceIDs(
var nightscoutSystemId: String? = null,
var nightscoutId: String? = null,
var pumpType: PumpType? = null, // if == USER pumpSerial & pumpId can be null
var pumpSerial: String? = null,
var temporaryId: Long? = null, // temporary id for pump synchronization, when pump id is not available
var pumpId: Long? = null,
var startId: Long? = null,
var endId: Long? = null
) {
enum class PumpType {
GENERIC_AAPS,
CELLNOVO,
ACCU_CHEK_COMBO,
ACCU_CHEK_SPIRIT,
ACCU_CHEK_INSIGHT,
ACCU_CHEK_INSIGHT_BLUETOOTH,
ACCU_CHEK_SOLO,
ANIMAS_VIBE,
ANIMAS_PING,
DANA_R,
DANA_R_KOREAN,
DANA_RV2,
DANA_I,
DANA_RS,
DANA_RS_KOREAN,
OMNIPOD_EROS,
OMNIPOD_DASH,
MEDTRONIC_512_517,
MEDTRONIC_515_715,
MEDTRONIC_522_722,
MEDTRONIC_523_723_REVEL,
MEDTRONIC_554_754_VEO,
MEDTRONIC_640G,
TANDEM_T_SLIM,
TANDEM_T_FLEX,
TANDEM_T_SLIM_G4,
TANDEM_T_SLIM_X2,
YPSOPUMP,
MDI,
DIACONN_G8,
USER,
CACHE;
companion object {
fun fromString(name: String?) = values().firstOrNull { it.name == name }
}
}
} | agpl-3.0 | 49a8e2ae190351441855edc46cfafbf4 | 24.773585 | 106 | 0.5663 | 3.189252 | false | false | false | false |
MaTriXy/material-dialogs | files/src/main/java/com/afollestad/materialdialogs/files/DialogFileChooserExt.kt | 2 | 5783 | /**
* 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.
*/
@file:Suppress("unused")
package com.afollestad.materialdialogs.files
import android.annotation.SuppressLint
import android.content.Context
import android.text.InputFilter
import android.widget.EditText
import android.widget.TextView
import androidx.annotation.CheckResult
import androidx.annotation.StringRes
import androidx.recyclerview.widget.LinearLayoutManager
import com.afollestad.materialdialogs.MaterialDialog
import com.afollestad.materialdialogs.WhichButton.POSITIVE
import com.afollestad.materialdialogs.actions.setActionButtonEnabled
import com.afollestad.materialdialogs.customview.customView
import com.afollestad.materialdialogs.customview.getCustomView
import com.afollestad.materialdialogs.files.util.getExternalFilesDir
import com.afollestad.materialdialogs.files.util.hasReadStoragePermission
import com.afollestad.materialdialogs.files.util.hasWriteStoragePermission
import com.afollestad.materialdialogs.input.getInputField
import com.afollestad.materialdialogs.input.input
import com.afollestad.materialdialogs.internal.list.DialogRecyclerView
import com.afollestad.materialdialogs.utils.MDUtil.maybeSetTextColor
import java.io.File
typealias FileFilter = ((File) -> Boolean)?
typealias FileCallback = ((dialog: MaterialDialog, file: File) -> Unit)?
/** Gets the selected file for the current file chooser dialog. */
@CheckResult
fun MaterialDialog.selectedFile(): File? {
val customView = getCustomView()
val list: DialogRecyclerView = customView.findViewById(R.id.list)
return (list.adapter as? FileChooserAdapter)?.selectedFile
}
/**
* Shows a dialog that lets the user select a local file.
*
* @param initialDirectory The directory that is listed initially, defaults to external storage.
* @param filter A filter to apply when listing files, defaults to only show non-hidden files.
* @param waitForPositiveButton When true, the callback isn't invoked until the user selects a
* file and taps on the positive action button. Defaults to true if the dialog has buttons.
* @param emptyTextRes A string resource displayed on the empty view shown when a directory is
* empty. Defaults to "This folder's empty!".
* @param selection A callback invoked when a file is selected.
*/
@SuppressLint("CheckResult")
fun MaterialDialog.fileChooser(
context: Context,
initialDirectory: File? = context.getExternalFilesDir(),
filter: FileFilter = null,
waitForPositiveButton: Boolean = true,
emptyTextRes: Int = R.string.files_default_empty_text,
allowFolderCreation: Boolean = false,
@StringRes folderCreationLabel: Int? = null,
selection: FileCallback = null
): MaterialDialog {
var actualFilter: FileFilter = filter
if (allowFolderCreation) {
check(hasWriteStoragePermission()) {
"You must have the WRITE_EXTERNAL_STORAGE permission first."
}
if (filter == null) {
actualFilter = { !it.isHidden && it.canWrite() }
}
} else {
check(hasReadStoragePermission()) {
"You must have the READ_EXTERNAL_STORAGE permission first."
}
if (filter == null) {
actualFilter = { !it.isHidden && it.canRead() }
}
}
check(initialDirectory != null) {
"The initial directory is null."
}
customView(R.layout.md_file_chooser_base, noVerticalPadding = true)
setActionButtonEnabled(POSITIVE, false)
val customView = getCustomView()
val list: DialogRecyclerView = customView.findViewById(R.id.list)
val emptyText: TextView = customView.findViewById(R.id.empty_text)
emptyText.setText(emptyTextRes)
emptyText.maybeSetTextColor(windowContext, R.attr.md_color_content)
list.attach(this)
list.layoutManager = LinearLayoutManager(windowContext)
val adapter = FileChooserAdapter(
dialog = this,
initialFolder = initialDirectory,
waitForPositiveButton = waitForPositiveButton,
emptyView = emptyText,
onlyFolders = false,
filter = actualFilter,
allowFolderCreation = allowFolderCreation,
folderCreationLabel = folderCreationLabel,
callback = selection
)
list.adapter = adapter
if (waitForPositiveButton && selection != null) {
setActionButtonEnabled(POSITIVE, false)
positiveButton {
val selectedFile = adapter.selectedFile
if (selectedFile != null) {
selection.invoke(this, selectedFile)
}
}
}
return this
}
internal fun MaterialDialog.showNewFolderCreator(
parent: File,
@StringRes folderCreationLabel: Int?,
onCreation: () -> Unit
) {
val dialog = MaterialDialog(windowContext).show {
title(folderCreationLabel ?: R.string.files_new_folder)
input(hintRes = R.string.files_new_folder_hint) { _, input ->
File(parent, input.toString().trim()).mkdir()
onCreation()
}
}
dialog.getInputField()
.blockReservedCharacters()
}
private fun EditText.blockReservedCharacters() {
filters += InputFilter { source, _, _, _, _, _ ->
if (source.isEmpty()) {
return@InputFilter null
}
val last = source[source.length - 1]
val reservedChars = "?:\"*|/\\<>"
if (reservedChars.indexOf(last) > -1) {
source.subSequence(0, source.length - 1)
} else {
null
}
}
}
| apache-2.0 | b37985328b165231bd5b6bb882a06a74 | 34.478528 | 96 | 0.743386 | 4.465637 | false | false | false | false |
slesar/Layers | app/src/main/java/com/psliusar/layers/sample/screen/listener/ListenerLayer.kt | 1 | 1690 | package com.psliusar.layers.sample.screen.listener
import android.app.Activity
import android.content.Intent
import android.graphics.Bitmap
import android.os.Bundle
import android.provider.MediaStore
import android.view.View
import android.widget.ImageView
import com.psliusar.layers.Layer
import com.psliusar.layers.LayersActivity
import com.psliusar.layers.callbacks.BaseActivityEventListener
import com.psliusar.layers.sample.R
private const val CAMERA_IMAGE = 1001
class ListenerLayer : Layer(R.layout.screen_listener) {
private val imageListener = object : BaseActivityEventListener() {
override fun onActivityResult(requestCode: Int, resultCode: Int, intent: Intent?): Boolean {
if (requestCode == CAMERA_IMAGE) {
if (resultCode == Activity.RESULT_OK) {
val image = intent?.extras?.get("data") as Bitmap?
getView<ImageView>(R.id.listener_image).setImageBitmap(image)
}
return true
}
return false
}
}
override fun onBindView(savedState: Bundle?, view: View) {
super.onBindView(savedState, view)
getView<View>(R.id.listener_take_photo).setOnClickListener {
val intent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
if (intent.resolveActivity(activity.packageManager) != null) {
activity.startActivityForResult(intent, CAMERA_IMAGE)
}
}
(activity as LayersActivity).addEventListener(imageListener)
}
override fun onDestroyView() {
super.onDestroyView()
(activity as LayersActivity).removeEventListener(imageListener)
}
}
| apache-2.0 | d02f7f16ba8592fd60661f4af2a0d57a | 34.208333 | 100 | 0.678698 | 4.543011 | false | false | false | false |
Maccimo/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/inline/JavaToKotlinInlineHandler.kt | 1 | 10841 | // 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.inline
import com.intellij.lang.java.JavaLanguage
import com.intellij.lang.jvm.JvmModifier
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.progress.Task
import com.intellij.openapi.util.Key
import com.intellij.psi.*
import com.intellij.usageView.UsageInfo
import com.intellij.util.containers.MultiMap
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.KotlinLanguage
import org.jetbrains.kotlin.idea.base.utils.fqname.getKotlinFqName
import org.jetbrains.kotlin.idea.caches.resolve.resolveToCall
import org.jetbrains.kotlin.idea.codeInliner.UsageReplacementStrategy
import org.jetbrains.kotlin.idea.codeInliner.unwrapSpecialUsageOrNull
import org.jetbrains.kotlin.idea.base.psi.replaced
import org.jetbrains.kotlin.idea.inspections.findExistingEditor
import org.jetbrains.kotlin.idea.j2k.IdeaJavaToKotlinServices
import org.jetbrains.kotlin.idea.refactoring.inline.J2KInlineCache.Companion.findOrCreateUsageReplacementStrategy
import org.jetbrains.kotlin.idea.refactoring.inline.J2KInlineCache.Companion.findUsageReplacementStrategy
import org.jetbrains.kotlin.idea.util.application.runReadAction
import org.jetbrains.kotlin.idea.base.util.module
import org.jetbrains.kotlin.j2k.ConverterSettings
import org.jetbrains.kotlin.j2k.J2kConverterExtension
import org.jetbrains.kotlin.j2k.JKMultipleFilesPostProcessingTarget
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.nj2k.NewJavaToKotlinConverter
import org.jetbrains.kotlin.nj2k.NewJavaToKotlinConverter.Companion.addImports
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.getAssignmentByLHS
import org.jetbrains.kotlin.psi.psiUtil.getQualifiedElementSelector
import org.jetbrains.kotlin.psi.psiUtil.getQualifiedExpressionForSelectorOrThis
import org.jetbrains.kotlin.resolve.calls.tower.isSynthesized
class JavaToKotlinInlineHandler : AbstractCrossLanguageInlineHandler() {
override fun prepareReference(reference: PsiReference, referenced: PsiElement): MultiMap<PsiElement, String> {
val referenceElement = reference.element
if (referenceElement.language == KotlinLanguage.INSTANCE) {
KotlinInlineRefactoringFUSCollector.log(elementFrom = referenced, languageTo = KotlinLanguage.INSTANCE, isCrossLanguage = true)
}
val javaMemberToInline = referenced.javaMemberToInline ?: return super.prepareReference(reference, referenced)
validate(javaMemberToInline, referenceElement)?.let { error ->
return createMultiMapWithSingleConflict(referenceElement, error)
}
try {
val strategy = findOrCreateUsageReplacementStrategy(javaMemberToInline, referenceElement)
if (strategy == null) KotlinBundle.message("failed.to.create.a.wrapper.for.inlining.to.kotlin") else null
} catch (e: IllegalStateException) {
LOG.error(e)
e.message
}?.let { error ->
return createMultiMapWithSingleConflict(referenceElement, error)
}
return MultiMap.empty()
}
override fun performInline(usage: UsageInfo, referenced: PsiElement) {
val unwrappedUsage = unwrapUsage(usage) ?: kotlin.run {
LOG.error("Kotlin usage in $usage not found (element ${usage.element}")
return
}
val unwrappedElement = unwrapElement(unwrappedUsage, referenced)
val replacementStrategy = referenced.findUsageReplacementStrategy(withValidation = false) ?: kotlin.run {
LOG.error("Can't find strategy for ${unwrappedElement::class} (${unwrappedElement.getKotlinFqName()}) => ${unwrappedElement.text}")
return
}
replacementStrategy.createReplacer(unwrappedElement)?.invoke()
}
companion object {
private val LOG = Logger.getInstance(JavaToKotlinInlineHandler::class.java)
}
}
private val PsiElement.javaMemberToInline: PsiMember?
get() = if (language == JavaLanguage.INSTANCE && (this is PsiMethod || this is PsiField)) this as PsiMember else null
private fun validate(referenced: PsiMember, reference: PsiElement): String? = when {
referenced is PsiField && !referenced.hasInitializer() -> KotlinBundle.message("a.field.without.an.initializer.is.not.yet.supported")
referenced is PsiMethod && referenced.isConstructor -> KotlinBundle.message("a.constructor.call.is.not.yet.supported")
else -> findCallableConflictForUsage(reference)
}
private fun NewJavaToKotlinConverter.convertToKotlinNamedDeclaration(
referenced: PsiMember,
context: PsiElement,
): KtNamedDeclaration {
var fakeFile: KtFile? = null
object : Task.Modal(project, KotlinBundle.message("action.j2k.name"), false) {
override fun run(indicator: ProgressIndicator) {
val converterExtension = J2kConverterExtension.extension(useNewJ2k = true)
val postProcessor = converterExtension.createPostProcessor(formatCode = true)
val processor = converterExtension.createWithProgressProcessor(
progress = indicator,
files = listOf(referenced.containingFile as PsiJavaFile),
phasesCount = phasesCount + postProcessor.phasesCount,
)
val (j2kResults, _, j2kContext) = runReadAction {
elementsToKotlin(
inputElements = listOf(referenced),
processor = processor,
bodyFilter = { it == referenced }
)
}
val factory = KtPsiFactory(project)
val className = runReadAction { referenced.containingClass?.qualifiedName }
val j2kResult = j2kResults.first() ?: error("Can't convert to Kotlin ${referenced.text}")
val file = runReadAction {
factory.createAnalyzableFile(
fileName = "dummy.kt",
text = "class DuMmY_42_ : $className {\n${j2kResult.text}\n}",
contextToAnalyzeIn = context,
).also {
it.addImports(j2kResult.importsToAdd)
}
}
postProcessor.doAdditionalProcessing(
target = JKMultipleFilesPostProcessingTarget(files = listOf(file)),
converterContext = j2kContext,
onPhaseChanged = { i, s -> processor.updateState(null, phasesCount + i, s) },
)
fakeFile = file
}
}.queue()
val fakeClass = fakeFile?.declarations?.singleOrNull() as? KtClass ?: error("Can't find dummy class in ${fakeFile?.text}")
return fakeClass.declarations.singleOrNull() as? KtNamedDeclaration ?: error("Can't find fake declaration in ${fakeFile?.text}")
}
private fun unwrapUsage(usage: UsageInfo): KtReferenceExpression? {
val ktReferenceExpression = usage.element as? KtReferenceExpression ?: return null
return unwrapSpecialUsageOrNull(ktReferenceExpression) ?: ktReferenceExpression
}
private fun unwrapElement(unwrappedUsage: KtReferenceExpression, referenced: PsiElement): KtReferenceExpression {
if (referenced !is PsiMember) return unwrappedUsage
val name = referenced.name ?: return unwrappedUsage
if (unwrappedUsage.textMatches(name)) return unwrappedUsage
val qualifiedElementOrReference = unwrappedUsage.getQualifiedExpressionForSelectorOrThis()
val assignment = qualifiedElementOrReference.getAssignmentByLHS()?.takeIf { it.operationToken == KtTokens.EQ } ?: return unwrappedUsage
val argument = assignment.right ?: return unwrappedUsage
if (unwrappedUsage.resolveToCall()?.resultingDescriptor?.isSynthesized != true) return unwrappedUsage
val psiFactory = KtPsiFactory(unwrappedUsage)
val callExpression = psiFactory.createExpressionByPattern("$name($0)", argument) as? KtCallExpression ?: return unwrappedUsage
val resultExpression = assignment.replaced(unwrappedUsage.replaced(callExpression).getQualifiedExpressionForSelectorOrThis())
return resultExpression.getQualifiedElementSelector() as KtReferenceExpression
}
class J2KInlineCache(private val strategy: UsageReplacementStrategy, private val originalText: String) {
/**
* @return [strategy] without validation if [elementToValidation] is null
*/
private fun getStrategy(elementToValidation: PsiElement?): UsageReplacementStrategy? = strategy.takeIf {
elementToValidation?.textMatches(originalText) != false
}
companion object {
private val JAVA_TO_KOTLIN_INLINE_CACHE_KEY = Key<J2KInlineCache>("JAVA_TO_KOTLIN_INLINE_CACHE")
fun PsiElement.findUsageReplacementStrategy(withValidation: Boolean): UsageReplacementStrategy? =
getUserData(JAVA_TO_KOTLIN_INLINE_CACHE_KEY)?.getStrategy(this.takeIf { withValidation })
fun PsiElement.setUsageReplacementStrategy(strategy: UsageReplacementStrategy): Unit =
putUserData(JAVA_TO_KOTLIN_INLINE_CACHE_KEY, J2KInlineCache(strategy, text))
internal fun findOrCreateUsageReplacementStrategy(javaMember: PsiMember, context: PsiElement): UsageReplacementStrategy? {
javaMember.findUsageReplacementStrategy(withValidation = true)?.let { return it }
val converter = NewJavaToKotlinConverter(
javaMember.project,
javaMember.module,
ConverterSettings.defaultSettings,
IdeaJavaToKotlinServices
)
val declaration = converter.convertToKotlinNamedDeclaration(
referenced = javaMember,
context = context,
)
return createUsageReplacementStrategyForNamedDeclaration(
declaration,
javaMember.findExistingEditor(),
fallbackToSuperCall = javaMember.containingClass?.hasModifier(JvmModifier.FINAL) == true,
)?.also { javaMember.setUsageReplacementStrategy(it) }
}
}
}
private fun createUsageReplacementStrategyForNamedDeclaration(
namedDeclaration: KtNamedDeclaration,
editor: Editor?,
fallbackToSuperCall: Boolean,
): UsageReplacementStrategy? = when (namedDeclaration) {
is KtNamedFunction -> createUsageReplacementStrategyForFunction(
function = namedDeclaration,
editor = editor,
fallbackToSuperCall = fallbackToSuperCall,
)
is KtProperty -> createReplacementStrategyForProperty(
property = namedDeclaration,
editor = editor,
project = namedDeclaration.project,
fallbackToSuperCall = fallbackToSuperCall,
)
else -> null
}
| apache-2.0 | 7b50daaf50c833538254a35f9022ca82 | 46.969027 | 143 | 0.724841 | 5.169766 | false | false | false | false |
Mogikan/mobileLabs | Services/app/src/main/java/com/astu/vk/services/MathStartCommand.kt | 1 | 3094 | package com.astu.vk.services
import android.app.IntentService
import android.app.Service
import android.content.Context
import android.content.Intent
import android.os.IBinder
class MathStartCommand : Service() {
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
if (intent != null) {
val action = intent.action
if (ACTION_SUM == action) {
val param1 = intent.getIntExtra(EXTRA_OPERAND1,0)
val param2 = intent.getIntExtra(EXTRA_OPERAND2,0);
handleActionSum(param1, param2)
} else if (ACTION_MUL == action) {
val param1 = intent.getIntExtra(EXTRA_OPERAND1,0)
val param2 = intent.getIntExtra(EXTRA_OPERAND2,0);
handleActionMul(param1, param2)
}
}
return Service.START_NOT_STICKY
}
private fun handleActionSum(operand1: Int, operand2: Int) {
var resultIntent:Intent = Intent(RESULT_NOTIFICATION)
resultIntent.putExtra(RESULT_EXTRA,operand1+operand2)
sendBroadcast(resultIntent)
}
private fun handleActionMul(operand1: Int, operand2: Int) {
var resultIntent:Intent = Intent(RESULT_NOTIFICATION)
resultIntent.putExtra(RESULT_EXTRA,operand1*operand2)
sendBroadcast(resultIntent)
}
override fun onBind(p0: Intent?): IBinder {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
public fun Sum(operand1:Int,operand2:Int):Int{
return operand1+operand2
}
public fun Mul(operand1:Int,operand2:Int):Int{
return operand1*operand2
}
companion object {
public val RESULT_NOTIFICATION = "mathNonBoundedNotification"
public val RESULT_EXTRA = "mathNonBounderResultExtra"
private val ACTION_SUM = "com.astu.vk.services.action.SUM"
private val ACTION_MUL = "com.astu.vk.services.action.MUL"
private val EXTRA_OPERAND1 = "com.astu.vk.services.extra.OPERAND1"
private val EXTRA_OPERAND2 = "com.astu.vk.services.extra.OPERAND2"
fun startActionSum(context: Context, operand1: Int, operand2: Int) {
val intent = Intent(context, MathStartCommand::class.java)
intent.action =ACTION_SUM
intent.putExtra(EXTRA_OPERAND1, operand1)
intent.putExtra(EXTRA_OPERAND2, operand2)
context.startService(intent)
}
/**
* Starts this service to perform action Baz with the given parameters. If
* the service is already performing a task this action will be queued.
* @see IntentService
*/
// TODO: Customize helper method
fun startActionMul(context: Context, operand1: Int, operand2: Int) {
val intent = Intent(context, MathStartCommand::class.java)
intent.action = ACTION_MUL
intent.putExtra(EXTRA_OPERAND1, operand1)
intent.putExtra(EXTRA_OPERAND2, operand2)
context.startService(intent)
}
}
}
| gpl-3.0 | a144dfa85a920ad6fd6985ab8874fc7b | 36.277108 | 107 | 0.646412 | 4.158602 | false | false | false | false |
Tiofx/semester_6 | TRPSV/src/main/kotlin/task2/graph/bellmanFord/plainBellmanFord.kt | 1 | 1739 | package task2.graph.bellmanFord
import task2.graph.INFINITE
import task2.graph.InputGraph
import task2.graph.PlainAdjacency
import task2.graph.PlainAdjacencyList
import task2.graph.Util.AdjacencyMatrixUtil.toPlainAdjacencyList
import task2.graph.Util.PlainAdjacencyListUtil.edgeNumber
import task2.graph.Util.PlainAdjacencyListUtil.get
inline fun bellmanFord(graph: InputGraph) = with(graph) {
bellmanFord(
adjacencyMatrix.toPlainAdjacencyList(),
sourceVertex,
vertexNumber)
}
fun bellmanFord(plainAdjacencyList: PlainAdjacencyList,
sourceVertex: Int,
vertexNumber: Int): IntArray =
IntArray(vertexNumber, { INFINITE })
.apply { this[sourceVertex] = 0 }
.apply { while (plainAdjacencyList.relaxAll(this)); }
//TODO:Need optimization
fun PlainAdjacencyList.relaxAll(distance: IntArray, from: Int = 0, to: Int = edgeNumber - 1) =
(from..to)
.map { relax(it, distance) }
.onEach { if (it) return@relaxAll true }
.let { false }
fun PlainAdjacencyList.relax(index: Int, distance: IntArray): Boolean {
val lastValue = distance[get(index, PlainAdjacency.DESTINATION)]
if (distance[get(index, PlainAdjacency.SOURCE)] < INFINITE) {
distance[get(index, PlainAdjacency.DESTINATION)] =
minOf(distance[get(index, PlainAdjacency.DESTINATION)].toLong(),
distance[get(index, PlainAdjacency.SOURCE)].toLong()
+ get(index, PlainAdjacency.WEIGHT))
.toInt()
}
val isRelaxed = lastValue != distance[get(index, PlainAdjacency.DESTINATION)]
return isRelaxed
}
| gpl-3.0 | 3840fedab08a2bda3bf10de99656dfdb | 35.229167 | 94 | 0.655549 | 4.130641 | false | false | false | false |
ismail-s/JTime | JTime-android/src/main/kotlin/com/ismail_s/jtime/android/fragment/NearbyTimesFragment.kt | 1 | 3947 | package com.ismail_s.jtime.android.fragment
import android.location.Location
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import com.ismail_s.jtime.android.CalendarFormatter.formatCalendarAsTime
import com.ismail_s.jtime.android.R
import com.ismail_s.jtime.android.RestClient
import com.ismail_s.jtime.android.pojo.SalaahType
import kotlinx.android.synthetic.main.fragment_nearby_times.*
import nl.komponents.kovenant.ui.failUi
import nl.komponents.kovenant.ui.successUi
import org.jetbrains.anko.AnkoContext
import org.jetbrains.anko.debug
import org.jetbrains.anko.find
import org.jetbrains.anko.support.v4.act
import org.jetbrains.anko.support.v4.ctx
import org.jetbrains.anko.support.v4.toast
import org.jetbrains.anko.support.v4.withArguments
import org.jetbrains.anko.tableRow
import org.jetbrains.anko.textView
/**
* Displays nearby salaah times for today, for a given salaah type.
*/
class NearbyTimesFragment : BaseFragment() {
lateinit var salaahType: SalaahType
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View? {
val rootView = inflater.inflate(R.layout.fragment_nearby_times, container, false)
salaahType = arguments.getSerializable(SALAAH_TYPE) as SalaahType
val salaahNameLabel = rootView.find<TextView>(R.id.label_salaah_name)
salaahNameLabel.text = getString(R.string.nearby_times_title_text, salaahType.toString(ctx))
mainAct.location successUi {
getTimesAndDisplayInUi(it)
} failUi {
debug("Failed to get current location")
toast(getString(R.string.get_location_for_nearby_masjids_failure_toast))
}
return rootView
}
override fun onLocationChanged(loc: Location) = getTimesAndDisplayInUi(loc)
private fun getTimesAndDisplayInUi(loc: Location) {
val table = salaah_times_table
cancelPromiseOnFragmentDestroy {
RestClient(act).getTimesForNearbyMasjids(loc.latitude, loc.longitude, salaahType = salaahType)
.successUi s@ {
table.removeAllViews()
val tSize = 18f
if (it.isEmpty()) {
table.addView(with(AnkoContext.create(act, table)) {
tableRow {
textView(getString(R.string.no_salaah_times_nearby_masjids_toast)) {
textSize = tSize
}
}
})
return@s
}
it.sortedBy { it.datetime.timeInMillis }.forEach {
table.addView(with(AnkoContext.create(act, table)) {
tableRow {
textView(it.masjidName) {
textSize = tSize
}
textView(formatCalendarAsTime(it.datetime)) {
textSize = tSize
}
}
})
}
} failUi {
ifAttachedToAct {
debug("Failed to get nearby times from masjid")
toast(getString(R.string.get_masjid_times_failure_toast, it.message))
}
}
}
}
companion object {
private val SALAAH_TYPE = "salaahType"
fun newInstance(salaahType: SalaahType): NearbyTimesFragment =
NearbyTimesFragment().withArguments(SALAAH_TYPE to salaahType)
}
}
| gpl-2.0 | 9bc94685b56152f179107953b3521cc2 | 40.989362 | 106 | 0.572587 | 4.62178 | false | false | false | false |
JetBrains/ideavim | vim-engine/src/main/kotlin/com/maddyhome/idea/vim/action/motion/updown/MotionDownActions.kt | 1 | 2188 | /*
* Copyright 2003-2022 The IdeaVim authors
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE.txt file or at
* https://opensource.org/licenses/MIT.
*/
package com.maddyhome.idea.vim.action.motion.updown
import com.maddyhome.idea.vim.api.ExecutionContext
import com.maddyhome.idea.vim.api.VimCaret
import com.maddyhome.idea.vim.api.VimEditor
import com.maddyhome.idea.vim.api.injector
import com.maddyhome.idea.vim.command.Argument
import com.maddyhome.idea.vim.command.MotionType
import com.maddyhome.idea.vim.command.OperatorArguments
import com.maddyhome.idea.vim.handler.Motion
import com.maddyhome.idea.vim.handler.MotionActionHandler
import com.maddyhome.idea.vim.handler.toMotion
open class MotionDownAction : MotionActionHandler.ForEachCaret() {
override val motionType: MotionType = MotionType.LINE_WISE
override fun getOffset(
editor: VimEditor,
caret: VimCaret,
context: ExecutionContext,
argument: Argument?,
operatorArguments: OperatorArguments,
): Motion {
return injector.motion.getVerticalMotionOffset(editor, caret, operatorArguments.count1)
}
}
class MotionDownCtrlNAction : MotionDownAction() {
override fun getOffset(
editor: VimEditor,
caret: VimCaret,
context: ExecutionContext,
argument: Argument?,
operatorArguments: OperatorArguments,
): Motion {
val activeLookup = injector.lookupManager.getActiveLookup(editor)
return if (activeLookup != null) {
val primaryCaret = editor.primaryCaret()
if (caret == primaryCaret) {
activeLookup.down(primaryCaret, context)
}
caret.offset.point.toMotion()
} else {
super.getOffset(editor, caret, context, argument, operatorArguments)
}
}
}
class MotionDownNotLineWiseAction : MotionActionHandler.ForEachCaret() {
override val motionType: MotionType = MotionType.EXCLUSIVE
override fun getOffset(
editor: VimEditor,
caret: VimCaret,
context: ExecutionContext,
argument: Argument?,
operatorArguments: OperatorArguments,
): Motion {
return injector.motion.getVerticalMotionOffset(editor, caret, operatorArguments.count1)
}
}
| mit | a0d3fc42ab6e66b3725152b52ba77dd1 | 30.710145 | 91 | 0.755484 | 4.290196 | false | false | false | false |
pyamsoft/pydroid | ui/src/main/java/com/pyamsoft/pydroid/ui/internal/datapolicy/dialog/DataPolicyDisclosureScreen.kt | 1 | 7865 | /*
* Copyright 2022 Peter Kenji Yamanaka
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.pyamsoft.pydroid.ui.internal.datapolicy.dialog
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.padding
import androidx.compose.material.Button
import androidx.compose.material.ContentAlpha
import androidx.compose.material.MaterialTheme
import androidx.compose.material.SnackbarDuration
import androidx.compose.material.SnackbarHost
import androidx.compose.material.SnackbarHostState
import androidx.compose.material.Text
import androidx.compose.material.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import coil.ImageLoader
import com.pyamsoft.pydroid.theme.keylines
import com.pyamsoft.pydroid.ui.R
import com.pyamsoft.pydroid.ui.internal.app.AppHeaderDialog
import com.pyamsoft.pydroid.ui.internal.app.dialogItem
import com.pyamsoft.pydroid.ui.internal.test.createNewTestImageLoader
private val MAX_HEIGHT_PORTRAIT = 360.dp
@Composable
internal fun DataPolicyDisclosureScreen(
modifier: Modifier = Modifier,
state: DataPolicyDialogViewState,
imageLoader: ImageLoader,
onPrivacyPolicyClicked: () -> Unit,
onTermsOfServiceClicked: () -> Unit,
onNavigationErrorDismissed: () -> Unit,
onAccept: () -> Unit,
onReject: () -> Unit,
) {
val snackbarHostState = remember { SnackbarHostState() }
val name = state.name
AppHeaderDialog(
modifier = modifier.fillMaxWidth(),
icon = state.icon,
name = name,
imageLoader = imageLoader,
) {
dialogItem(
modifier = Modifier.fillMaxWidth(),
) {
Disclosure(
modifier = Modifier.fillMaxWidth().heightIn(max = MAX_HEIGHT_PORTRAIT),
name = name,
)
}
dialogItem(
modifier = Modifier.fillMaxWidth(),
) {
Links(
modifier = Modifier.fillMaxWidth(),
onPrivacyPolicyClicked = onPrivacyPolicyClicked,
onTermsOfServiceClicked = onTermsOfServiceClicked,
)
}
dialogItem(
modifier = Modifier.fillMaxWidth(),
) {
Actions(
modifier = Modifier.fillMaxWidth(),
onAccept = onAccept,
onReject = onReject,
)
}
item {
NavigationError(
modifier = Modifier.fillMaxWidth(),
snackbarHostState = snackbarHostState,
error = state.navigationError,
onSnackbarDismissed = onNavigationErrorDismissed,
)
}
}
}
@Composable
private fun Links(
modifier: Modifier = Modifier,
onPrivacyPolicyClicked: () -> Unit,
onTermsOfServiceClicked: () -> Unit,
) {
Column(
modifier = modifier.padding(vertical = MaterialTheme.keylines.baseline),
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Center,
) {
Text(
modifier = Modifier.clickable { onTermsOfServiceClicked() },
text = "View our Terms and Conditions",
style =
MaterialTheme.typography.caption.copy(
color = MaterialTheme.colors.primary,
),
)
Text(
modifier =
Modifier.clickable { onPrivacyPolicyClicked() }
.padding(top = MaterialTheme.keylines.baseline),
text = "View our Privacy Policy",
style =
MaterialTheme.typography.caption.copy(
color = MaterialTheme.colors.primary,
),
)
}
}
@Composable
private fun Disclosure(
modifier: Modifier = Modifier,
name: String,
) {
val typography = MaterialTheme.typography
val colors = MaterialTheme.colors
val alpha = ContentAlpha.medium
val disclosureStyle =
remember(
typography,
colors,
alpha,
) {
typography.body2.copy(
color =
colors.onSurface.copy(
alpha = alpha,
),
)
}
Column(
modifier = modifier.padding(MaterialTheme.keylines.content),
) {
Text(
text = "$name is open source software.",
style = MaterialTheme.typography.body1,
)
Text(
modifier = Modifier.padding(top = MaterialTheme.keylines.content),
text =
"""
Because it is distributed on the Google Play Store, the developer is provided
by default with certain analytics related to your usage of the application called Vitals.
You can opt out of these analytics from your device's system settings."""
.trimIndent()
.replace("\n", " "),
style = disclosureStyle,
)
Text(
modifier = Modifier.padding(top = MaterialTheme.keylines.content),
text =
"""
Aside from these Google Play Store Vitals, your application data is never knowingly
collected, shared, transported, or shown to any other party, including the developer.
"""
.trimIndent()
.replace("\n", " "),
style = disclosureStyle,
)
}
}
@Composable
private fun Actions(
modifier: Modifier = Modifier,
onAccept: () -> Unit,
onReject: () -> Unit,
) {
Column(
modifier =
modifier
.padding(horizontal = MaterialTheme.keylines.content)
.padding(top = MaterialTheme.keylines.content),
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Center,
) {
Button(
onClick = onAccept,
) {
Text(
text = stringResource(R.string.dpd_accept),
)
}
TextButton(
modifier = Modifier.padding(top = MaterialTheme.keylines.baseline),
onClick = onReject,
) {
Text(
text = stringResource(R.string.dpd_reject),
fontSize = 12.sp,
)
}
}
}
@Composable
private fun NavigationError(
modifier: Modifier = Modifier,
snackbarHostState: SnackbarHostState,
error: Throwable?,
onSnackbarDismissed: () -> Unit,
) {
SnackbarHost(
modifier = modifier,
hostState = snackbarHostState,
)
if (error != null) {
LaunchedEffect(error) {
snackbarHostState.showSnackbar(
message = error.message ?: "An unexpected error occurred",
duration = SnackbarDuration.Long,
)
onSnackbarDismissed()
}
}
}
@Preview
@Composable
private fun PreviewDataPolicyDisclosureScreen() {
DataPolicyDisclosureScreen(
state =
MutableDataPolicyDialogViewState().apply {
icon = 0
name = "TEST"
navigationError = null
},
imageLoader = createNewTestImageLoader(),
onPrivacyPolicyClicked = {},
onTermsOfServiceClicked = {},
onNavigationErrorDismissed = {},
onAccept = {},
onReject = {},
)
}
| apache-2.0 | 563bbc705728d5a0a9760db75c404174 | 27.809524 | 99 | 0.65569 | 4.73225 | false | false | false | false |
wordpress-mobile/WordPress-Android | WordPress/src/main/java/org/wordpress/android/viewmodel/SingleEventObservable.kt | 1 | 1494 | package org.wordpress.android.viewmodel
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.LiveData
import androidx.lifecycle.Observer
/**
* A lifecycle-aware observable that sends only new updates after subscription, used for events like
* navigation and SnackBar messages.
*
*
* This avoids a common problem with events: on configuration change (like rotation) an update
* can be emitted if the observer is active.
*
*
* Note that only one observer can be subscribed.
*/
class SingleEventObservable<T>(private val sourceLiveData: LiveData<T>) {
var lastEvent: T? = null
private set
@Suppress("UseCheckOrError")
fun observe(owner: LifecycleOwner, observer: Observer<T>) {
if (sourceLiveData.hasObservers()) {
throw IllegalStateException("SingleEventObservable can be observed only by a single observer.")
}
sourceLiveData.observe(owner, Observer {
if (it !== lastEvent) {
lastEvent = it
observer.onChanged(it)
}
})
}
@Suppress("UseCheckOrError")
fun observeForever(observer: Observer<T>) {
if (sourceLiveData.hasObservers()) {
throw IllegalStateException("SingleEventObservable can be observed only by a single observer.")
}
sourceLiveData.observeForever {
if (it !== lastEvent) {
lastEvent = it
observer.onChanged(it)
}
}
}
}
| gpl-2.0 | 46f4de80d4800b9bee359c3771b94f46 | 30.787234 | 107 | 0.649264 | 4.963455 | false | false | false | false |
micolous/metrodroid | src/jvmCommonMain/kotlin/au/id/micolous/metrodroid/util/StationTableReader.kt | 1 | 7073 | /*
* StationTableReader.kt
* Reader for Metrodroid Station Table (MdST) files.
*
* Copyright 2018 Michael Farrell <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package au.id.micolous.metrodroid.util
import au.id.micolous.metrodroid.multi.Log
import au.id.micolous.metrodroid.proto.Stations
import au.id.micolous.metrodroid.transit.TransitName
import au.id.micolous.metrodroid.transit.Trip
import au.id.micolous.metrodroid.util.StationTableReaderImpl.InvalidHeaderException
import org.jetbrains.annotations.NonNls
import java.io.IOException
import java.io.InputStream
import java.util.*
expect fun openMdstFile(dbName: String): InputStream?
internal actual fun StationTableReaderGetSTR(name: String): StationTableReader? =
StationTableReaderImpl.getSTR(name)
/**
* Metrodroid Station Table (MdST) file reader.
*
* For more information about the file format, see extras/mdst/README.md in the Metrodroid source
* repository.
*/
class StationTableReaderImpl
/**
* Initialises a "connection" to a Metrodroid Station Table kept in the `assets/` directory.
* @param dbName MdST filename
* @throws IOException On read errors
* @throws InvalidHeaderException If the file is not a MdST file.
*/
private constructor(dbName: String) : StationTableReader {
private val mStationDb: Stations.StationDb
private val mStationIndex: Stations.StationIndex? by lazy {
try {
// Reset back to the start of the station list.
mTable.reset()
// Skip over the station list
mTable.skip(mStationsLength.toLong())
// Read out the index
Stations.StationIndex.parseDelimitedFrom(mTable)
} catch (e: IOException) {
Log.e(TAG, "error reading index", e)
null
}
}
private val mTable: InputStream = openMdstFile(dbName)!!
private val mStationsLength: Int
override val notice: String?
get() = mStationDb.licenseNotice.ifEmpty { null }
class InvalidHeaderException : Exception()
init {
// Read the Magic, and validate it.
val header = ByteArray(4)
if (mTable.read(header) != 4) {
throw InvalidHeaderException()
}
if (!Arrays.equals(header, MAGIC)) {
throw InvalidHeaderException()
}
// Check the version
val version = readInt(mTable)
if (version != VERSION) {
throw InvalidHeaderException()
}
mStationsLength = readInt(mTable)
// Read out the header
mStationDb = Stations.StationDb.parseDelimitedFrom(mTable)
// Mark where the start of the station list is.
// AssetInputStream allows unlimited seeking, no need to specify a readlimit.
mTable.mark(0)
}
/**
* Gets a Station object, according to the MdST Protobuf definition.
* @param id Stop ID
* @return Station object, or null if it could not be found.
* @throws IOException on read errors
*/
@Throws(IOException::class)
private fun getProtoStationById(id: Int): Stations.Station? {
val offset: Int
try {
offset = mStationIndex?.getStationMapOrThrow(id) ?: return null
} catch (e: IllegalArgumentException) {
Log.d(TAG, "Unknown station $id")
return null
}
mTable.reset()
mTable.skip(offset.toLong())
return Stations.Station.parseDelimitedFrom(mTable)
}
override fun getOperatorDefaultMode(oper: Int): Trip.Mode? {
val po = mStationDb.getOperatorsOrDefault(oper, null) ?: return null
return if (po.defaultTransport == Stations.TransportType.UNKNOWN) null else Trip.Mode.valueOf(po.defaultTransport.toString())
}
override fun getOperatorName(oper: Int): TransitName? {
val po = mStationDb.getOperatorsOrDefault(oper, null) ?: return null
return makeTransitName(po.name ?: return null)
}
override fun getLineName(id: Int): TransitName? {
val pl = mStationDb.getLinesOrDefault(id, null) ?: return null
return makeTransitName(pl.name)
}
override fun getLineMode(id: Int): Trip.Mode? {
val pl = mStationDb.getLinesOrDefault(id, null) ?: return null
return if (pl.transport == Stations.TransportType.UNKNOWN) null else Trip.Mode.valueOf(pl.transport.toString())
}
/**
* Gets a Metrodroid-native Station object for a given stop ID.
* @param id Stop ID.
* @return Station object, or null if it could not be found.
* @throws IOException on read errors
*/
override fun getStationById(id: Int, humanReadableID: String): ProtoStation? {
val ps = getProtoStationById(id) ?: return null
return ProtoStation(name = makeTransitName(ps.name), latitude = ps.latitude, longitude = ps.longitude,
lineIdList = ps.lineIdList, operatorId = ps.operatorId)
}
private fun makeTransitName(name: Stations.Names) =
TransitName(englishFull = name.english,
englishShort = name.englishShort,
localFull = name.local,
localShort = name.localShort,
localLanguagesList = mStationDb.localLanguagesList,
ttsHintLanguage = mStationDb.ttsHintLanguage)
companion object {
private val MAGIC = byteArrayOf(0x4d, 0x64, 0x53, 0x54)
private const val VERSION = 1
private const val TAG = "StationTableReader"
private fun readInt(input: InputStream): Int {
val b = ByteArray(4)
input.read(b)
// TODO: avoid copying? Probably not worth it
return b.toImmutable().byteArrayToInt()
}
private val mSTRs: MutableMap<String, StationTableReader> = HashMap()
internal fun getSTR(@NonNls name: String?): StationTableReader? {
if (name == null) {
return null
}
synchronized(mSTRs) {
if (mSTRs.containsKey(name))
return mSTRs[name]
}
try {
val str = StationTableReaderImpl(name)
synchronized(mSTRs) {
mSTRs.put(name, str)
}
return str
} catch (e: Exception) {
Log.w(TAG, "Couldn't open DB $name", e)
return null
}
}
}
}
| gpl-3.0 | 5b7947ae14959fd9c58a60f9c620f60f | 34.542714 | 133 | 0.643433 | 4.307552 | false | false | false | false |
darkoverlordofdata/entitas-kotlin | entitas/src/main/java/com/darkoverlordofdata/entitas/Pool.kt | 1 | 6986 | package com.darkoverlordofdata.entitas
import java.util.*
/**
*
* A pool manages the lifecycle of entities and groups.
* You can create and destroy entities and get groups of entities.
* The preferred way is to use the generated methods from the code generator to create a Pool, e.g. var pool = Pools.pool;
*
* @param totalComponents number of components
* @param startCreationIndex entity index counter
* @param componentName component index to name function
*/
class Pool(totalComponents:Int, startCreationIndex:Int=0, componentName:((p:Int) -> String)={it.toString()}) {
val totalComponents = totalComponents
val startCreationIndex = startCreationIndex
val componentName = componentName
val count:Int get() = _entities.size
val reusableEntitiesCount:Int get() = _reusableEntities.size
val retainedEntitiesCount:Int get() = _retainedEntities.size
val onEntityCreated = Event<PoolEntityChangedArgs>()
val onEntityWillBeDestroyed = Event<PoolEntityChangedArgs>()
val onEntityDestroyed = Event<PoolEntityChangedArgs>()
val onGroupCreated = Event<PoolGroupChangedArgs>()
private var _creationIndex:Int = startCreationIndex
private val _entities: HashSet<Entity> = hashSetOf()
private val _groups: HashMap<IMatcher, Group> = hashMapOf()
private val _groupsForIndex: Array<MutableList<Group>?> = Array(totalComponents,{i -> null})
private val _reusableEntities: MutableList<Entity> = mutableListOf()
private val _retainedEntities: HashSet<Entity> = hashSetOf()
private val _entitiesCache: MutableList<Entity> = mutableListOf()
private lateinit var onEntityReleasedCache : (e: EntityReleasedArgs) -> Unit
/**
* EventHandler onEntityReleased
*/
val onEntityReleased = {e: EntityReleasedArgs ->
if (e.entity.isEnabled)
throw EntityIsNotDestroyedException("Cannot release entity.")
e.entity.onEntityReleased -= onEntityReleasedCache
_retainedEntities.remove(e.entity)
val ignore = _reusableEntities.add(e.entity)
}
/**
* EventHandler updateGroupsComponentAddedOrRemoved
*/
val updateGroupsComponentAddedOrRemoved = {e: EntityChangedArgs ->
if (_groupsForIndex[e.index] != null) {
for (i in 0.._groupsForIndex[e.index]!!.size-1) {
val group = _groupsForIndex[e.index]!![i]
if (e.component != null)
group.handleEntity(e.entity, e.index, e.component)
}
}
}
/**
* EventHandler updateGroupsComponentReplaced
*/
val updateGroupsComponentReplaced = {e: ComponentReplacedArgs ->
if (_groupsForIndex[e.index] != null) {
for (i in 0.._groupsForIndex[e.index]!!.size-1) {
val group = _groupsForIndex[e.index]!![i]
group.updateEntity(e.entity, e.index, e.previous, e.replacement)
}
}
}
init {
onEntityReleasedCache = onEntityReleased
_instance = this
}
/**
*
* Creates a new entity or gets a reusable entity from the internal ObjectPool for entities.
*/
fun createEntity(name: String): Entity {
val entity = if (_reusableEntities.size > 0) _reusableEntities.removeAt(_reusableEntities.size-1) else Entity(totalComponents)
entity.initialize(name, _creationIndex++)
// entity.isEnabled = true
// entity.name = name
// entity._creationIndex = _creationIndex++
entity.retain()
entity.onComponentAdded += updateGroupsComponentAddedOrRemoved
entity.onComponentRemoved += updateGroupsComponentAddedOrRemoved
entity.onComponentReplaced += updateGroupsComponentReplaced
entity.onEntityReleased += onEntityReleased
_entities.add(entity)
_entitiesCache.clear()
onEntityCreated(PoolEntityChangedArgs(this, entity))
return entity
}
/**
*
* Destroys the entity, removes all its components and pushes it back to the internal ObjectPool for entities.
*/
fun destroyEntity(entity: Entity?) {
if (entity == null) return
if (entity !in _entities) {
throw PoolDoesNotContainEntityException(entity, "Could not destroy entity!")
}
_entities.remove(entity)
_entitiesCache.clear()
onEntityWillBeDestroyed(PoolEntityChangedArgs(this, entity))
entity.destroy()
onEntityDestroyed(PoolEntityChangedArgs(this, entity))
if (entity.refCount == 1) {
entity.onEntityReleased -= onEntityReleased
_reusableEntities.add(entity)
} else {
_retainedEntities.add(entity)
}
}
/**
*
* Destroys all entities in the pool.
*/
fun destroyAllEntities() {
val entities = getEntities()
for (i in 0..entities.size)
destroyEntity(entities[i])
}
/**
*
* Determines whether the pool has the specified entity.
*/
fun hasEntity(entity: Entity): Boolean {
return entity in _entities
}
private fun getEntities(): MutableList<Entity> {
if (_entitiesCache.size == 0) {
for (entity in _entities)
_entitiesCache.add(entity)
}
return _entitiesCache
}
fun getEntities(matcher: IMatcher): Array<Entity>? {
return getGroup(matcher).entities
// return getGroup(matcher)!!.getEntities()
}
fun createSystem(system: ISystem): ISystem {
setPool(system, this)
if (system is IReactiveSystem) {
return ReactiveSystem(this, system)
}
if (system is IMultiReactiveSystem) {
return ReactiveSystem(this, system)
}
return system
}
/**
*
* Returns a group for the specified matcher.
* Calling pool.GetGroup(matcher) with the same matcher will always return the same instance of the group.
*/
fun getGroup(matcher: IMatcher): Group {
var group = _groups[matcher]
if (group != null) {
return group
} else {
val group = Group(matcher)
val entities = getEntities()
for (i in 0..entities.size-1) {
group.handleEntitySilently(entities[i])
}
_groups[matcher] = group
for (index in matcher.indices) {
if (_groupsForIndex[index] == null) {
_groupsForIndex[index] = mutableListOf()
}
_groupsForIndex[index]!!.add(group)
}
onGroupCreated(PoolGroupChangedArgs(this, group))
return group
}
}
companion object static {
private var _instance: Pool? = null
val instance : Pool? get() = _instance
fun setPool(system: ISystem, pool: Pool) {
if (system is ISetPool) {
system.setPool(pool)
}
}
}
} | mit | 1026d71fb81088a72c3f8e64671cd3a9 | 33.25 | 134 | 0.625251 | 4.58399 | false | false | false | false |
JavaEden/Orchid-Core | plugins/OrchidChangelog/src/main/kotlin/com/eden/orchid/changelog/adapter/ChangelogFileAdapter.kt | 2 | 3911 | package com.eden.orchid.changelog.adapter
import com.caseyjbrooks.clog.Clog
import com.eden.orchid.api.OrchidContext
import com.eden.orchid.api.options.annotations.Archetype
import com.eden.orchid.api.options.annotations.Description
import com.eden.orchid.api.options.annotations.IntDefault
import com.eden.orchid.api.options.annotations.Option
import com.eden.orchid.api.options.annotations.StringDefault
import com.eden.orchid.api.options.archetypes.ConfigArchetype
import com.eden.orchid.api.resources.resource.StringResource
import com.eden.orchid.api.resources.resourcesource.FlexibleResourceSource
import com.eden.orchid.api.resources.resourcesource.LocalResourceSource
import com.eden.orchid.api.resources.resourcesource.flexible
import com.eden.orchid.api.theme.pages.OrchidReference
import com.eden.orchid.changelog.ChangelogGenerator
import com.eden.orchid.changelog.model.ChangelogVersion
import com.eden.orchid.utilities.OrchidUtils
import com.eden.orchid.utilities.SuppressedWarnings
@Archetype(value = ConfigArchetype::class, key = ChangelogGenerator.GENERATOR_KEY)
class ChangelogFileAdapter : ChangelogAdapter {
@Option
@StringDefault("CHANGELOG")
@Description("The name of the changelog file.")
lateinit var filename: String
@Option
@Description("The base directory to start searching for the changelog file.")
lateinit var baseDir: String
@Option
@StringDefault("{major}.{minor}.{patch}")
@Description("The format your changelog versions follow.")
lateinit var format: String
@Option
@StringDefault("^#{1,2}\\s*?(.*?)\\s*?(?:[-/](.*?))?\$")
@Description("The format your changelog version follow.")
lateinit var versionRegex: String
@Option
@IntDefault(1)
var versionRegexGroup: Int = 1
@Option
@IntDefault(2)
var releaseDateRegexGroup: Int = 2
override fun getType() = "file"
@Suppress(SuppressedWarnings.DEPRECATION)
override fun loadChangelogEntries(context: OrchidContext): List<ChangelogVersion> {
val flexibleResourceSource: FlexibleResourceSource = context
.getFlexibleResourceSource(LocalResourceSource, null)
val readme = flexibleResourceSource.locateResourceEntry(context, filename)
?: flexibleResourceSource.findClosestFile(context, filename, baseDir)
if (readme == null) {
Clog.w("Changelog file not found")
return emptyList()
}
val regex = versionRegex.toRegex(RegexOption.MULTILINE)
var currentVersion: String? = null
var currentVersionReleaseDate: String? = null
var previousIndex = 0
val content = readme.content
val changelogVersions = mutableListOf<ChangelogVersion>()
regex.findAll(content).forEach {
if (currentVersion != null) {
changelogVersions += ChangelogVersion(
context,
format,
currentVersion!!.trim(),
currentVersionReleaseDate?.trim(),
StringResource(
OrchidReference(context, "${currentVersion}.${readme.reference.extension}"),
content.substring(previousIndex, it.range.first)
)
)
}
currentVersion = it.groupValues[versionRegexGroup]
currentVersionReleaseDate = it.groupValues[releaseDateRegexGroup]
previousIndex = it.range.last + 1
}
changelogVersions += ChangelogVersion(
context,
format,
currentVersion!!.trim(),
currentVersionReleaseDate?.trim(),
StringResource(
OrchidReference(context, "${currentVersion}.${readme.reference.extension}"),
content.substring(previousIndex)
)
)
return changelogVersions
}
}
| mit | 67d74282464ed96fbde07d1d31d997f4 | 35.551402 | 100 | 0.678855 | 5.112418 | false | false | false | false |
iPoli/iPoli-android | app/src/main/java/io/ipoli/android/common/ShareAppDialogController.kt | 1 | 8428 | package io.ipoli.android.common
import android.annotation.SuppressLint
import android.app.Activity.RESULT_OK
import android.content.Context
import android.content.Intent
import android.content.pm.ResolveInfo
import android.graphics.drawable.Drawable
import android.net.Uri
import android.os.Bundle
import android.support.v4.content.ContextCompat
import android.support.v7.app.AlertDialog
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ArrayAdapter
import com.facebook.share.model.ShareLinkContent
import com.facebook.share.widget.MessageDialog
import com.facebook.share.widget.ShareDialog
import com.google.android.gms.appinvite.AppInviteInvitation
import io.ipoli.android.Constants
import io.ipoli.android.Constants.Companion.FACEBOOK_PACKAGE
import io.ipoli.android.Constants.Companion.TWITTER_PACKAGE
import io.ipoli.android.MyPoliApp
import io.ipoli.android.R
import io.ipoli.android.common.di.UIModule
import io.ipoli.android.common.view.BaseDialogController
import io.ipoli.android.common.view.showLongToast
import io.ipoli.android.common.view.stringRes
import kotlinx.android.synthetic.main.item_share.view.*
import kotlinx.android.synthetic.main.view_dialog_header.view.*
import space.traversal.kapsule.Injects
import space.traversal.kapsule.inject
import space.traversal.kapsule.required
/**
* Created by Polina Zhelyazkova <[email protected]>
* on 3/26/18.
*/
class ShareAppDialogController(args: Bundle? = null) : BaseDialogController(args),
Injects<UIModule> {
private val eventLogger by required { eventLogger }
companion object {
const val SHARE_APP_REQUEST_CODE = 876
}
private var dialogTitle: String = ""
private var message: String = ""
constructor(dialogTitle: String, message: String) : this() {
this.dialogTitle = dialogTitle
this.message = message
}
@SuppressLint("InflateParams")
override fun onCreateContentView(inflater: LayoutInflater, savedViewState: Bundle?): View {
inject(MyPoliApp.uiModule(MyPoliApp.instance))
registerForActivityResult(SHARE_APP_REQUEST_CODE)
activity?.let {
eventLogger.logCurrentScreen(it, "ShareApp")
}
return inflater.inflate(R.layout.dialog_share_app, null)
}
override fun onHeaderViewCreated(headerView: View?) {
headerView!!.dialogHeaderTitle.text = dialogTitle
val v = ViewUtils.dpToPx(8f, headerView.context).toInt()
headerView.dialogHeaderIcon.setPadding(v, v, v, v)
headerView.dialogHeaderIcon.setImageResource(R.drawable.ic_person_add_white_24dp)
}
override fun onCreateDialog(
dialogBuilder: AlertDialog.Builder,
contentView: View,
savedViewState: Bundle?
): AlertDialog {
val inviteIntent = Intent(Intent.ACTION_SEND)
inviteIntent.type = "text/plain"
inviteIntent.putExtra(Intent.EXTRA_TEXT, "")
val adapter =
ShareDialogAdapter(
contentView.context,
filterInviteProviders(contentView.context, inviteIntent)
)
dialogBuilder.setAdapter(adapter) { _, item ->
val sa = adapter.getItem(item)
val packageName = sa.packageName
when {
packageName == null -> {
eventLogger.logEvent("share_app", mapOf("provider" to "Firebase"))
onInviteWithFirebase(message)
}
isFacebook(packageName) -> {
eventLogger.logEvent("share_app", mapOf("provider" to "Facebook"))
onInviteWithFacebook()
}
else -> {
var text = message
if (isTwitter(packageName)) {
text += " via " + Constants.TWITTER_USERNAME
}
eventLogger.logEvent("share_app", mapOf("provider" to sa.name))
inviteIntent.putExtra(Intent.EXTRA_TEXT, text)
inviteIntent.`package` = packageName
activity!!.startActivity(inviteIntent)
}
}
}
return dialogBuilder.create()
}
private fun onInviteWithFirebase(message: String) {
val intent = AppInviteInvitation.IntentBuilder(stringRes(R.string.invite_title))
.setMessage(message)
.setCustomImage(Uri.parse(Constants.INVITE_IMAGE_URL))
.setCallToActionText(stringRes(R.string.invite_call_to_action))
.build()
activity!!.startActivityForResult(intent, SHARE_APP_REQUEST_CODE)
}
private fun onInviteWithFacebook() {
val linkContent = ShareLinkContent.Builder()
.setContentUrl(Uri.parse("https://play.google.com/store/apps/details?id=io.ipoli.android"))
.build()
when {
MessageDialog.canShow(ShareLinkContent::class.java) ->
MessageDialog.show(
activity!!,
linkContent
)
ShareDialog.canShow(ShareLinkContent::class.java) ->
ShareDialog.show(
activity!!,
linkContent
)
else -> showLongToast(R.string.invite_request_update_facebook)
}
}
private fun filterInviteProviders(context: Context, inviteIntent: Intent): List<ShareApp> {
val shareApps = mutableListOf<ShareApp>()
val apps = context.packageManager.queryIntentActivities(inviteIntent, 0)
var twitter: ResolveInfo? = null
for (info in apps) {
val packageName = info.activityInfo.packageName
val name = info.loadLabel(context.packageManager).toString()
if (isTwitter(packageName)) {
if (name == "Tweet") {
twitter = info
}
continue
}
if (isFacebook(packageName)) {
continue
}
shareApps.add(ShareApp(packageName, name, info.loadIcon(context.packageManager)))
}
if (twitter != null) {
shareApps.add(
0,
ShareApp(
twitter.activityInfo.packageName,
"Twitter",
twitter.loadIcon(context.packageManager)
)
)
}
shareApps.add(
0,
ShareApp(
Constants.FACEBOOK_PACKAGE,
"Facebook",
ContextCompat.getDrawable(context, R.drawable.ic_facebook_blue_40dp)!!
)
)
shareApps.add(
0,
ShareApp(
null,
"Email or SMS",
ContextCompat.getDrawable(context, R.drawable.ic_email_red_40dp)!!
)
)
return shareApps
}
private fun isFacebook(packageName: String) = packageName.startsWith(FACEBOOK_PACKAGE)
private fun isTwitter(packageName: String) = packageName.startsWith(TWITTER_PACKAGE)
data class ShareApp(val packageName: String?, val name: String, val icon: Drawable)
inner class ShareDialogAdapter(context: Context, apps: List<ShareApp>) :
ArrayAdapter<ShareApp>(context, R.layout.item_share, apps) {
override fun getView(position: Int, convertView: View?, parent: ViewGroup): View {
var view = convertView
val app = getItem(position)
if (view == null) {
view =
LayoutInflater.from(context).inflate(R.layout.item_share, parent, false)
}
view!!.appName.text = app.name
view.appIcon.setImageDrawable(app.icon)
return view
}
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode == SHARE_APP_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
val inviteIds = AppInviteInvitation.getInvitationIds(resultCode, data!!)
eventLogger.logEvent(
"firebase_invite_sent",
mapOf("count" to inviteIds.size)
)
} else {
eventLogger.logEvent("firebase_invite_canceled")
}
}
}
} | gpl-3.0 | 65d6c910b57e2dd6c8af7a3c5f90155c | 34.716102 | 103 | 0.612126 | 4.783201 | false | false | false | false |
GunoH/intellij-community | plugins/settings-sync/git/src/com/intellij/settingsSync/git/SettingsSyncHistoryAction.kt | 4 | 1803 | package com.intellij.settingsSync.git
import com.intellij.openapi.actionSystem.ActionUpdateThread
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.project.DumbAwareAction
import com.intellij.openapi.ui.Messages
import com.intellij.openapi.vfs.VfsUtil
import com.intellij.openapi.wm.ToolWindowManager
import com.intellij.settingsSync.SettingsSyncBundle
import com.intellij.settingsSync.SettingsSyncMain
import com.intellij.settingsSync.isSettingsSyncEnabledByKey
import git4idea.GitVcs
import git4idea.log.showExternalGitLogInToolwindow
import java.util.function.Supplier
class SettingsSyncHistoryAction : DumbAwareAction() {
override fun actionPerformed(e: AnActionEvent) {
val project = e.project!!
val settingsSyncStorage = SettingsSyncMain.getInstance().controls.settingsSyncStorage
val virtualFile = VfsUtil.findFile(settingsSyncStorage, true)
if (virtualFile == null) {
Messages.showErrorDialog(SettingsSyncBundle.message("history.error.message"), SettingsSyncBundle.message("history.dialog.title"))
return
}
val toolWindowId = "SettingsSync"
val toolWindowManager = ToolWindowManager.getInstance(project)
val toolWindow = toolWindowManager.getToolWindow(toolWindowId) ?: toolWindowManager.registerToolWindow(toolWindowId) {
stripeTitle = Supplier { SettingsSyncBundle.message("title.settings.sync") }
}
showExternalGitLogInToolwindow(project, toolWindow, GitVcs.getInstance(project), listOf(virtualFile),
SettingsSyncBundle.message("history.tab.name"), "")
}
override fun getActionUpdateThread() = ActionUpdateThread.BGT
override fun update(e: AnActionEvent) {
e.presentation.isEnabledAndVisible = e.project != null && isSettingsSyncEnabledByKey()
}
} | apache-2.0 | 4bd583d3b2dab61ce251c27c98c49cd3 | 44.1 | 135 | 0.791459 | 5.136752 | false | false | false | false |
GunoH/intellij-community | plugins/groovy/src/org/jetbrains/plugins/groovy/config/wizard/GroovyNewProjectWizard.kt | 8 | 2132 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.plugins.groovy.config.wizard
import com.intellij.ide.JavaUiBundle
import com.intellij.ide.projectWizard.NewProjectWizardCollector.BuildSystem.logBuildSystemChanged
import com.intellij.ide.projectWizard.NewProjectWizardCollector.BuildSystem.logBuildSystemFinished
import com.intellij.ide.projectWizard.NewProjectWizardConstants.Language.GROOVY
import com.intellij.ide.wizard.*
import com.intellij.openapi.observable.properties.GraphProperty
import com.intellij.openapi.project.Project
import com.intellij.openapi.roots.ui.distribution.DistributionInfo
import com.intellij.ui.dsl.builder.Row
import com.intellij.ui.dsl.builder.SegmentedButton
class GroovyNewProjectWizard : LanguageNewProjectWizard {
override val name = GROOVY
override val ordinal = 200
override fun createStep(parent: NewProjectWizardLanguageStep) = Step(parent)
class Step(parent: NewProjectWizardLanguageStep) :
AbstractNewProjectWizardMultiStep<Step, BuildSystemGroovyNewProjectWizard>(parent, BuildSystemGroovyNewProjectWizard.EP_NAME),
LanguageNewProjectWizardData by parent,
BuildSystemGroovyNewProjectWizardData {
override val self: Step = this
override val label: String = JavaUiBundle.message("label.project.wizard.new.project.build.system")
override val buildSystemProperty: GraphProperty<String> by ::stepProperty
override var buildSystem: String by ::step
override val groovySdkProperty = propertyGraph.property<DistributionInfo?>(null)
override var groovySdk: DistributionInfo? by groovySdkProperty
override fun createAndSetupSwitcher(builder: Row): SegmentedButton<String> {
return super.createAndSetupSwitcher(builder)
.whenItemSelectedFromUi { logBuildSystemChanged() }
}
override fun setupProject(project: Project) {
super.setupProject(project)
logBuildSystemFinished()
logGroovySdkFinished(groovySdk)
}
init {
data.putUserData(BuildSystemGroovyNewProjectWizardData.KEY, this)
}
}
}
| apache-2.0 | cdce4e9bfe75f3aa0336a0765a87b269 | 38.481481 | 130 | 0.803471 | 4.901149 | false | false | false | false |
TonnyL/Mango | app/src/main/java/io/github/tonnyl/mango/util/Constants.kt | 1 | 2253 | /*
* Copyright (c) 2017 Lizhaotailang
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package io.github.tonnyl.mango.util
/**
* Created by lizhaotailang on 2017/6/27.
*
* Some constant strings but not included in [io.github.tonnyl.mango.retrofit.ApiConstants].
*/
class Constants {
companion object {
// If the user has logged in.
@JvmField
val IS_USER_LOGGED_IN = "IS_USER_LOGGED_IN"
// The access token string.
@JvmField
val ACCESS_TOKEN = "ACCESS_TOKEN"
// The intent actions of app shortcuts
@JvmField
val INTENT_ACTION_POPULAR = "INTENT_ACTION_POPULAR"
@JvmField
val INTENT_ACTION_FOLLOWING = "INTENT_ACTION_FOLLOWING"
@JvmField
val INTENT_ACTION_RECENT = "INTENT_ACTION_RECENT"
@JvmField
val INTENT_ACTION_DEBUTS = "INTENT_ACTION_DEBUTS"
// The ids of app shortcuts
@JvmField
val SHORTCUT_ID_FOLLOWING = "SHORTCUT_ID_FOLLOWING"
@JvmField
val SHORTCUT_ID_POPULAR = "SHORTCUT_ID_POPULAR"
@JvmField
val SHORTCUT_ID_RECENT = "SHORTCUT_ID_RECENT"
@JvmField
val SHORTCUT_ID_DEBUTS = "SHORTCUT_ID_DEBUTS"
}
} | mit | 8d3f0b33332aa7f168e3e2be0227f6cc | 33.676923 | 92 | 0.690191 | 4.250943 | false | false | false | false |
AsamK/TextSecure | app/src/main/java/org/thoughtcrime/securesms/conversation/colors/ui/ChatColorSelectionViewModel.kt | 2 | 2377 | package org.thoughtcrime.securesms.conversation.colors.ui
import androidx.fragment.app.FragmentActivity
import androidx.lifecycle.LiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import org.thoughtcrime.securesms.conversation.colors.ChatColors
import org.thoughtcrime.securesms.recipients.RecipientId
import org.thoughtcrime.securesms.util.SingleLiveEvent
import org.thoughtcrime.securesms.util.livedata.Store
class ChatColorSelectionViewModel(private val repository: ChatColorSelectionRepository) : ViewModel() {
private val store = Store<ChatColorSelectionState>(ChatColorSelectionState())
private val chatColors = ChatColorsOptionsLiveData()
private val internalEvents = SingleLiveEvent<Event>()
val state: LiveData<ChatColorSelectionState> = store.stateLiveData
val events: LiveData<Event> = internalEvents
init {
store.update(chatColors) { colors, state -> state.copy(chatColorOptions = colors) }
}
fun refresh() {
repository.getWallpaper { wallpaper ->
store.update { it.copy(wallpaper = wallpaper) }
}
repository.getChatColors { chatColors ->
store.update { it.copy(chatColors = chatColors) }
}
}
fun save(chatColors: ChatColors) {
repository.save(chatColors, this::refresh)
}
fun duplicate(chatColors: ChatColors) {
repository.duplicate(chatColors)
}
fun startDeletion(chatColors: ChatColors) {
repository.getUsageCount(chatColors.id) {
internalEvents.postValue(Event.ConfirmDeletion(it, chatColors))
}
}
fun deleteNow(chatColors: ChatColors) {
repository.delete(chatColors, this::refresh)
}
class Factory(private val repository: ChatColorSelectionRepository) : ViewModelProvider.Factory {
override fun <T : ViewModel> create(modelClass: Class<T>): T = requireNotNull(modelClass.cast(ChatColorSelectionViewModel(repository)))
}
companion object {
fun getOrCreate(activity: FragmentActivity, recipientId: RecipientId?): ChatColorSelectionViewModel {
val repository = ChatColorSelectionRepository.create(activity, recipientId)
val viewModelFactory = Factory(repository)
return ViewModelProvider(activity, viewModelFactory).get(ChatColorSelectionViewModel::class.java)
}
}
sealed class Event {
class ConfirmDeletion(val usageCount: Int, val chatColors: ChatColors) : Event()
}
}
| gpl-3.0 | 0e3d9800ace60096459b02821fad9404 | 33.449275 | 139 | 0.770299 | 4.633528 | false | false | false | false |
pdvrieze/kotlinsql | sql/src/main/kotlin/io/github/pdvrieze/kotlinsql/ddl/Database.kt | 1 | 4037 | /*
* Copyright (c) 2021.
*
* This file is part of kotlinsql.
*
* This file is licenced to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You should have received a copy of the license with the source distribution.
* Alternatively, 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.github.pdvrieze.kotlinsql.ddl
import java.lang.reflect.*
import kotlin.NoSuchElementException
import kotlin.collections.ArrayList
import kotlin.reflect.KProperty
/**
* This is an abstract class that contains a set of database tables.
*
* @property _version The version of the database schema. This can in the future be used for updating
* @property _tables The actual tables defined in the database
*/
@Suppress("unused")
abstract class Database constructor(@Suppress("MemberVisibilityCanBePrivate") val _version: Int) {
@Suppress("PropertyName")
val _tables: List<Table> by lazy {
val result = ArrayList<Table>()
result.addAll(tablesFromObjects(this.javaClass))
tablesFromProperties(this)
.filter { table -> !result.any { table._name == it._name } }
.forEach { result.add(it) }
result
}
/**
* Delegate function to be used to reference tables. Note that this requires the name of the property to match the name
* of the table.
*/
@Suppress("NOTHING_TO_INLINE")
protected inline fun <T : ImmutableTable> ref(table: T) = TableDelegate(table)
/**
* Delegate function to be used to reference tables. This delegate allows for renaming, by removing the need for checking.
*/
@Suppress("NOTHING_TO_INLINE")
protected inline fun <T : ImmutableTable> rename(table: T) = TableDelegate(table, false)
/**
* Helper class that implements the actual delegation of table access.
*/
protected class TableDelegate<out T : ImmutableTable>(
private val table: T,
private var needsCheck: Boolean = true,
) {
operator fun getValue(thisRef: Database, property: KProperty<*>): T {
if (needsCheck) {
if (table._name != property.name) throw IllegalArgumentException(
"The table names do not match (${table._name}, ${property.name})")
needsCheck = false
}
return table
}
}
operator fun get(key: String): Table {
return _tables.find { it._name == key } ?: throw NoSuchElementException("There is no table with the key $key")
}
operator fun get(key: TableRef) = get(key._name)
companion object {
private val Field.isStatic: Boolean inline get() = Modifier.isStatic(modifiers)
private fun tablesFromObjects(container: Class<out Database>): List<Table> {
return container.classes.asSequence()
.mapNotNull { member -> member.fields.firstOrNull { field -> field.isStatic && field.name == "INSTANCE" } }
.mapNotNull { field -> field.get(null) }
.map { it as Table }
.toList()
}
private fun tablesFromProperties(db: Database): List<Table> {
fun isTable(method: Method): Boolean {
return method.parameterCount == 0 &&
method.name.startsWith("get") &&
Table::class.java.isAssignableFrom(method.returnType)
}
return db.javaClass.declaredMethods.asSequence()
.filter(::isTable)
.map { method -> (method.invoke(db)) as Table }
.toList()
}
}
}
| apache-2.0 | 603971164b89f32502580ec1f2b92946 | 34.412281 | 126 | 0.637602 | 4.535955 | false | false | false | false |
pdvrieze/kotlinsql | util/src/main/kotlin/io/github/pdvrieze/jdbc/recorder/actions/ResultSetClose.kt | 1 | 1528 | /*
* Copyright (c) 2021.
*
* This file is part of kotlinsql.
*
* This file is licenced to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You should have received a copy of the license with the source distribution.
* Alternatively, 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.github.pdvrieze.jdbc.recorder.actions
import io.github.pdvrieze.jdbc.recorder.AbstractRecordingStatement
import io.github.pdvrieze.jdbc.recorder.escape
object ResultSetClose : Action {
override fun toString(): String = "ResultSetClose"
}
object ConnectionClose: Action {
override fun toString(): String = "Connection.close()"
}
class StatementClose(val query: String?): Action {
override fun toString(): String = "Statement(${query?.escape() ?: ""}).close()"
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is StatementClose) return false
if (query != other.query) return false
return true
}
override fun hashCode(): Int {
return query?.hashCode() ?: 0
}
}
| apache-2.0 | 6e73869fffa5464b4574f37f2658f798 | 30.183673 | 98 | 0.704188 | 4.186301 | false | false | false | false |
Philip-Trettner/GlmKt | GlmKt/src/glm/vec/String/MutableStringVec2.kt | 1 | 14446 | package glm
data class MutableStringVec2(var x: String, var y: String) {
// Initializes each element by evaluating init from 0 until 1
constructor(init: (Int) -> String) : this(init(0), init(1))
operator fun get(idx: Int): String = when (idx) {
0 -> x
1 -> y
else -> throw IndexOutOfBoundsException("index $idx is out of bounds")
}
operator fun set(idx: Int, value: String) = when (idx) {
0 -> x = value
1 -> y = value
else -> throw IndexOutOfBoundsException("index $idx is out of bounds")
}
// Operators
inline fun map(func: (String) -> String): MutableStringVec2 = MutableStringVec2(func(x), func(y))
fun toList(): List<String> = listOf(x, y)
// Predefined vector constants
companion object Constants {
val zero: MutableStringVec2 get() = MutableStringVec2("", "")
}
// Conversions to Float
inline fun toVec(conv: (String) -> Float): Vec2 = Vec2(conv(x), conv(y))
inline fun toVec2(conv: (String) -> Float): Vec2 = Vec2(conv(x), conv(y))
inline fun toVec3(z: Float = 0f, conv: (String) -> Float): Vec3 = Vec3(conv(x), conv(y), z)
inline fun toVec4(z: Float = 0f, w: Float = 0f, conv: (String) -> Float): Vec4 = Vec4(conv(x), conv(y), z, w)
// Conversions to Float
inline fun toMutableVec(conv: (String) -> Float): MutableVec2 = MutableVec2(conv(x), conv(y))
inline fun toMutableVec2(conv: (String) -> Float): MutableVec2 = MutableVec2(conv(x), conv(y))
inline fun toMutableVec3(z: Float = 0f, conv: (String) -> Float): MutableVec3 = MutableVec3(conv(x), conv(y), z)
inline fun toMutableVec4(z: Float = 0f, w: Float = 0f, conv: (String) -> Float): MutableVec4 = MutableVec4(conv(x), conv(y), z, w)
// Conversions to Double
inline fun toDoubleVec(conv: (String) -> Double): DoubleVec2 = DoubleVec2(conv(x), conv(y))
inline fun toDoubleVec2(conv: (String) -> Double): DoubleVec2 = DoubleVec2(conv(x), conv(y))
inline fun toDoubleVec3(z: Double = 0.0, conv: (String) -> Double): DoubleVec3 = DoubleVec3(conv(x), conv(y), z)
inline fun toDoubleVec4(z: Double = 0.0, w: Double = 0.0, conv: (String) -> Double): DoubleVec4 = DoubleVec4(conv(x), conv(y), z, w)
// Conversions to Double
inline fun toMutableDoubleVec(conv: (String) -> Double): MutableDoubleVec2 = MutableDoubleVec2(conv(x), conv(y))
inline fun toMutableDoubleVec2(conv: (String) -> Double): MutableDoubleVec2 = MutableDoubleVec2(conv(x), conv(y))
inline fun toMutableDoubleVec3(z: Double = 0.0, conv: (String) -> Double): MutableDoubleVec3 = MutableDoubleVec3(conv(x), conv(y), z)
inline fun toMutableDoubleVec4(z: Double = 0.0, w: Double = 0.0, conv: (String) -> Double): MutableDoubleVec4 = MutableDoubleVec4(conv(x), conv(y), z, w)
// Conversions to Int
inline fun toIntVec(conv: (String) -> Int): IntVec2 = IntVec2(conv(x), conv(y))
inline fun toIntVec2(conv: (String) -> Int): IntVec2 = IntVec2(conv(x), conv(y))
inline fun toIntVec3(z: Int = 0, conv: (String) -> Int): IntVec3 = IntVec3(conv(x), conv(y), z)
inline fun toIntVec4(z: Int = 0, w: Int = 0, conv: (String) -> Int): IntVec4 = IntVec4(conv(x), conv(y), z, w)
// Conversions to Int
inline fun toMutableIntVec(conv: (String) -> Int): MutableIntVec2 = MutableIntVec2(conv(x), conv(y))
inline fun toMutableIntVec2(conv: (String) -> Int): MutableIntVec2 = MutableIntVec2(conv(x), conv(y))
inline fun toMutableIntVec3(z: Int = 0, conv: (String) -> Int): MutableIntVec3 = MutableIntVec3(conv(x), conv(y), z)
inline fun toMutableIntVec4(z: Int = 0, w: Int = 0, conv: (String) -> Int): MutableIntVec4 = MutableIntVec4(conv(x), conv(y), z, w)
// Conversions to Long
inline fun toLongVec(conv: (String) -> Long): LongVec2 = LongVec2(conv(x), conv(y))
inline fun toLongVec2(conv: (String) -> Long): LongVec2 = LongVec2(conv(x), conv(y))
inline fun toLongVec3(z: Long = 0L, conv: (String) -> Long): LongVec3 = LongVec3(conv(x), conv(y), z)
inline fun toLongVec4(z: Long = 0L, w: Long = 0L, conv: (String) -> Long): LongVec4 = LongVec4(conv(x), conv(y), z, w)
// Conversions to Long
inline fun toMutableLongVec(conv: (String) -> Long): MutableLongVec2 = MutableLongVec2(conv(x), conv(y))
inline fun toMutableLongVec2(conv: (String) -> Long): MutableLongVec2 = MutableLongVec2(conv(x), conv(y))
inline fun toMutableLongVec3(z: Long = 0L, conv: (String) -> Long): MutableLongVec3 = MutableLongVec3(conv(x), conv(y), z)
inline fun toMutableLongVec4(z: Long = 0L, w: Long = 0L, conv: (String) -> Long): MutableLongVec4 = MutableLongVec4(conv(x), conv(y), z, w)
// Conversions to Short
inline fun toShortVec(conv: (String) -> Short): ShortVec2 = ShortVec2(conv(x), conv(y))
inline fun toShortVec2(conv: (String) -> Short): ShortVec2 = ShortVec2(conv(x), conv(y))
inline fun toShortVec3(z: Short = 0.toShort(), conv: (String) -> Short): ShortVec3 = ShortVec3(conv(x), conv(y), z)
inline fun toShortVec4(z: Short = 0.toShort(), w: Short = 0.toShort(), conv: (String) -> Short): ShortVec4 = ShortVec4(conv(x), conv(y), z, w)
// Conversions to Short
inline fun toMutableShortVec(conv: (String) -> Short): MutableShortVec2 = MutableShortVec2(conv(x), conv(y))
inline fun toMutableShortVec2(conv: (String) -> Short): MutableShortVec2 = MutableShortVec2(conv(x), conv(y))
inline fun toMutableShortVec3(z: Short = 0.toShort(), conv: (String) -> Short): MutableShortVec3 = MutableShortVec3(conv(x), conv(y), z)
inline fun toMutableShortVec4(z: Short = 0.toShort(), w: Short = 0.toShort(), conv: (String) -> Short): MutableShortVec4 = MutableShortVec4(conv(x), conv(y), z, w)
// Conversions to Byte
inline fun toByteVec(conv: (String) -> Byte): ByteVec2 = ByteVec2(conv(x), conv(y))
inline fun toByteVec2(conv: (String) -> Byte): ByteVec2 = ByteVec2(conv(x), conv(y))
inline fun toByteVec3(z: Byte = 0.toByte(), conv: (String) -> Byte): ByteVec3 = ByteVec3(conv(x), conv(y), z)
inline fun toByteVec4(z: Byte = 0.toByte(), w: Byte = 0.toByte(), conv: (String) -> Byte): ByteVec4 = ByteVec4(conv(x), conv(y), z, w)
// Conversions to Byte
inline fun toMutableByteVec(conv: (String) -> Byte): MutableByteVec2 = MutableByteVec2(conv(x), conv(y))
inline fun toMutableByteVec2(conv: (String) -> Byte): MutableByteVec2 = MutableByteVec2(conv(x), conv(y))
inline fun toMutableByteVec3(z: Byte = 0.toByte(), conv: (String) -> Byte): MutableByteVec3 = MutableByteVec3(conv(x), conv(y), z)
inline fun toMutableByteVec4(z: Byte = 0.toByte(), w: Byte = 0.toByte(), conv: (String) -> Byte): MutableByteVec4 = MutableByteVec4(conv(x), conv(y), z, w)
// Conversions to Char
inline fun toCharVec(conv: (String) -> Char): CharVec2 = CharVec2(conv(x), conv(y))
inline fun toCharVec2(conv: (String) -> Char): CharVec2 = CharVec2(conv(x), conv(y))
inline fun toCharVec3(z: Char, conv: (String) -> Char): CharVec3 = CharVec3(conv(x), conv(y), z)
inline fun toCharVec4(z: Char, w: Char, conv: (String) -> Char): CharVec4 = CharVec4(conv(x), conv(y), z, w)
// Conversions to Char
inline fun toMutableCharVec(conv: (String) -> Char): MutableCharVec2 = MutableCharVec2(conv(x), conv(y))
inline fun toMutableCharVec2(conv: (String) -> Char): MutableCharVec2 = MutableCharVec2(conv(x), conv(y))
inline fun toMutableCharVec3(z: Char, conv: (String) -> Char): MutableCharVec3 = MutableCharVec3(conv(x), conv(y), z)
inline fun toMutableCharVec4(z: Char, w: Char, conv: (String) -> Char): MutableCharVec4 = MutableCharVec4(conv(x), conv(y), z, w)
// Conversions to Boolean
fun toBoolVec(): BoolVec2 = BoolVec2(x != "", y != "")
inline fun toBoolVec(conv: (String) -> Boolean): BoolVec2 = BoolVec2(conv(x), conv(y))
fun toBoolVec2(): BoolVec2 = BoolVec2(x != "", y != "")
inline fun toBoolVec2(conv: (String) -> Boolean): BoolVec2 = BoolVec2(conv(x), conv(y))
fun toBoolVec3(z: Boolean = false): BoolVec3 = BoolVec3(x != "", y != "", z)
inline fun toBoolVec3(z: Boolean = false, conv: (String) -> Boolean): BoolVec3 = BoolVec3(conv(x), conv(y), z)
fun toBoolVec4(z: Boolean = false, w: Boolean = false): BoolVec4 = BoolVec4(x != "", y != "", z, w)
inline fun toBoolVec4(z: Boolean = false, w: Boolean = false, conv: (String) -> Boolean): BoolVec4 = BoolVec4(conv(x), conv(y), z, w)
// Conversions to Boolean
fun toMutableBoolVec(): MutableBoolVec2 = MutableBoolVec2(x != "", y != "")
inline fun toMutableBoolVec(conv: (String) -> Boolean): MutableBoolVec2 = MutableBoolVec2(conv(x), conv(y))
fun toMutableBoolVec2(): MutableBoolVec2 = MutableBoolVec2(x != "", y != "")
inline fun toMutableBoolVec2(conv: (String) -> Boolean): MutableBoolVec2 = MutableBoolVec2(conv(x), conv(y))
fun toMutableBoolVec3(z: Boolean = false): MutableBoolVec3 = MutableBoolVec3(x != "", y != "", z)
inline fun toMutableBoolVec3(z: Boolean = false, conv: (String) -> Boolean): MutableBoolVec3 = MutableBoolVec3(conv(x), conv(y), z)
fun toMutableBoolVec4(z: Boolean = false, w: Boolean = false): MutableBoolVec4 = MutableBoolVec4(x != "", y != "", z, w)
inline fun toMutableBoolVec4(z: Boolean = false, w: Boolean = false, conv: (String) -> Boolean): MutableBoolVec4 = MutableBoolVec4(conv(x), conv(y), z, w)
// Conversions to String
fun toStringVec(): StringVec2 = StringVec2(x, y)
inline fun toStringVec(conv: (String) -> String): StringVec2 = StringVec2(conv(x), conv(y))
fun toStringVec2(): StringVec2 = StringVec2(x, y)
inline fun toStringVec2(conv: (String) -> String): StringVec2 = StringVec2(conv(x), conv(y))
fun toStringVec3(z: String = ""): StringVec3 = StringVec3(x, y, z)
inline fun toStringVec3(z: String = "", conv: (String) -> String): StringVec3 = StringVec3(conv(x), conv(y), z)
fun toStringVec4(z: String = "", w: String = ""): StringVec4 = StringVec4(x, y, z, w)
inline fun toStringVec4(z: String = "", w: String = "", conv: (String) -> String): StringVec4 = StringVec4(conv(x), conv(y), z, w)
// Conversions to String
fun toMutableStringVec(): MutableStringVec2 = MutableStringVec2(x, y)
inline fun toMutableStringVec(conv: (String) -> String): MutableStringVec2 = MutableStringVec2(conv(x), conv(y))
fun toMutableStringVec2(): MutableStringVec2 = MutableStringVec2(x, y)
inline fun toMutableStringVec2(conv: (String) -> String): MutableStringVec2 = MutableStringVec2(conv(x), conv(y))
fun toMutableStringVec3(z: String = ""): MutableStringVec3 = MutableStringVec3(x, y, z)
inline fun toMutableStringVec3(z: String = "", conv: (String) -> String): MutableStringVec3 = MutableStringVec3(conv(x), conv(y), z)
fun toMutableStringVec4(z: String = "", w: String = ""): MutableStringVec4 = MutableStringVec4(x, y, z, w)
inline fun toMutableStringVec4(z: String = "", w: String = "", conv: (String) -> String): MutableStringVec4 = MutableStringVec4(conv(x), conv(y), z, w)
// Conversions to T2
inline fun <T2> toTVec(conv: (String) -> T2): TVec2<T2> = TVec2<T2>(conv(x), conv(y))
inline fun <T2> toTVec2(conv: (String) -> T2): TVec2<T2> = TVec2<T2>(conv(x), conv(y))
inline fun <T2> toTVec3(z: T2, conv: (String) -> T2): TVec3<T2> = TVec3<T2>(conv(x), conv(y), z)
inline fun <T2> toTVec4(z: T2, w: T2, conv: (String) -> T2): TVec4<T2> = TVec4<T2>(conv(x), conv(y), z, w)
// Conversions to T2
inline fun <T2> toMutableTVec(conv: (String) -> T2): MutableTVec2<T2> = MutableTVec2<T2>(conv(x), conv(y))
inline fun <T2> toMutableTVec2(conv: (String) -> T2): MutableTVec2<T2> = MutableTVec2<T2>(conv(x), conv(y))
inline fun <T2> toMutableTVec3(z: T2, conv: (String) -> T2): MutableTVec3<T2> = MutableTVec3<T2>(conv(x), conv(y), z)
inline fun <T2> toMutableTVec4(z: T2, w: T2, conv: (String) -> T2): MutableTVec4<T2> = MutableTVec4<T2>(conv(x), conv(y), z, w)
// Allows for swizzling, e.g. v.swizzle.xzx
inner class Swizzle {
val xx: MutableStringVec2 get() = MutableStringVec2(x, x)
var xy: MutableStringVec2
get() = MutableStringVec2(x, y)
set(value) {
x = value.x
y = value.y
}
var yx: MutableStringVec2
get() = MutableStringVec2(y, x)
set(value) {
y = value.x
x = value.y
}
val yy: MutableStringVec2 get() = MutableStringVec2(y, y)
val xxx: MutableStringVec3 get() = MutableStringVec3(x, x, x)
val xxy: MutableStringVec3 get() = MutableStringVec3(x, x, y)
val xyx: MutableStringVec3 get() = MutableStringVec3(x, y, x)
val xyy: MutableStringVec3 get() = MutableStringVec3(x, y, y)
val yxx: MutableStringVec3 get() = MutableStringVec3(y, x, x)
val yxy: MutableStringVec3 get() = MutableStringVec3(y, x, y)
val yyx: MutableStringVec3 get() = MutableStringVec3(y, y, x)
val yyy: MutableStringVec3 get() = MutableStringVec3(y, y, y)
val xxxx: MutableStringVec4 get() = MutableStringVec4(x, x, x, x)
val xxxy: MutableStringVec4 get() = MutableStringVec4(x, x, x, y)
val xxyx: MutableStringVec4 get() = MutableStringVec4(x, x, y, x)
val xxyy: MutableStringVec4 get() = MutableStringVec4(x, x, y, y)
val xyxx: MutableStringVec4 get() = MutableStringVec4(x, y, x, x)
val xyxy: MutableStringVec4 get() = MutableStringVec4(x, y, x, y)
val xyyx: MutableStringVec4 get() = MutableStringVec4(x, y, y, x)
val xyyy: MutableStringVec4 get() = MutableStringVec4(x, y, y, y)
val yxxx: MutableStringVec4 get() = MutableStringVec4(y, x, x, x)
val yxxy: MutableStringVec4 get() = MutableStringVec4(y, x, x, y)
val yxyx: MutableStringVec4 get() = MutableStringVec4(y, x, y, x)
val yxyy: MutableStringVec4 get() = MutableStringVec4(y, x, y, y)
val yyxx: MutableStringVec4 get() = MutableStringVec4(y, y, x, x)
val yyxy: MutableStringVec4 get() = MutableStringVec4(y, y, x, y)
val yyyx: MutableStringVec4 get() = MutableStringVec4(y, y, y, x)
val yyyy: MutableStringVec4 get() = MutableStringVec4(y, y, y, y)
}
val swizzle: Swizzle get() = Swizzle()
}
fun mutableVecOf(x: String, y: String): MutableStringVec2 = MutableStringVec2(x, y)
| mit | 75a8cd1809004a0179637a5854081dfc | 67.464455 | 167 | 0.647446 | 3.519123 | false | false | false | false |
airbnb/lottie-android | sample/src/main/kotlin/com/airbnb/lottie/samples/views/LottiefilesTabBar.kt | 1 | 1509 | package com.airbnb.lottie.samples.views
import android.content.Context
import android.util.AttributeSet
import android.widget.LinearLayout
import com.airbnb.epoxy.ModelProp
import com.airbnb.epoxy.ModelView
import com.airbnb.lottie.samples.LottiefilesMode
import com.airbnb.lottie.samples.databinding.LottiefilesTabBarBinding
import com.airbnb.lottie.samples.utils.viewBinding
@ModelView(autoLayout = ModelView.Size.MATCH_WIDTH_WRAP_HEIGHT)
class LottiefilesTabBar @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
defStyleAttr: Int = 0
) : LinearLayout(context, attrs, defStyleAttr) {
private val binding: LottiefilesTabBarBinding by viewBinding()
@ModelProp
fun setMode(mode: LottiefilesMode) {
binding.popularView.isActivated = mode == LottiefilesMode.Popular
binding.recentView.isActivated = mode == LottiefilesMode.Recent
binding.searchView.isActivated = mode == LottiefilesMode.Search
}
@ModelProp(options = [ModelProp.Option.DoNotHash])
fun setPopularClickListener(listener: OnClickListener) {
binding.popularView.setOnClickListener(listener)
}
@ModelProp(options = [ModelProp.Option.DoNotHash])
fun setRecentClickListener(listener: OnClickListener) {
binding.recentView.setOnClickListener(listener)
}
@ModelProp(options = [ModelProp.Option.DoNotHash])
fun setSearchClickListener(listener: OnClickListener) {
binding.searchView.setOnClickListener(listener)
}
} | apache-2.0 | ed01be4a33c15d318d1dde5b78539487 | 35.829268 | 73 | 0.769384 | 4.504478 | false | false | false | false |
Doctoror/ParticleConstellationsLiveWallpaper | app/src/main/java/com/doctoror/particleswallpaper/userprefs/particlecolor/ColorPreferenceNoPreview.kt | 1 | 1430 | /*
* Copyright (C) 2017 Yaroslav Mytkalyk
*
* 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.doctoror.particleswallpaper.userprefs.particlecolor
import android.content.Context
import android.util.AttributeSet
import android.view.View
import android.view.ViewGroup
import com.rarepebble.colorpicker.ColorPreference
/**
* Created by Yaroslav Mytkalyk on 29.05.17.
*
* [ColorPreference] that does not show preview view
*/
open class ColorPreferenceNoPreview @JvmOverloads constructor
(context: Context, attrs: AttributeSet? = null, defStyle: Int = 0) :
ColorPreference(context, attrs) {
override fun onBindView(view: View?) {
super.onBindView(view)
if (view != null) {
val widgetFrameView = view.findViewById<ViewGroup>(android.R.id.widget_frame)
widgetFrameView.visibility = View.GONE
widgetFrameView.removeAllViews()
}
}
}
| apache-2.0 | 41e5b0307048039f31dc95ef6bad98c0 | 33.878049 | 89 | 0.727273 | 4.255952 | false | false | false | false |
code-disaster/lwjgl3 | modules/lwjgl/lz4/src/templates/kotlin/lz4/LZ4Types.kt | 3 | 5074 | /*
* Copyright LWJGL. All rights reserved.
* License terms: https://www.lwjgl.org/license
*/
package lz4
import org.lwjgl.generator.*
val LZ4_i8 = typedef(int8_t, "LZ4_i8")
val LZ4_byte = typedef(uint8_t, "LZ4_byte")
val LZ4_u16 = typedef(uint16_t, "LZ4_u16")
val LZ4_u32 = typedef(uint32_t, "LZ4_u32")
val LZ4_stream_t = "LZ4_stream_t".opaque
val LZ4_streamDecode_t = "LZ4_streamDecode_t".opaque
// lz4frame.h
val LZ4F_errorCode_t = typedef(size_t, "LZ4F_errorCode_t")
val LZ4F_blockSizeID_t = "LZ4F_blockSizeID_t".enumType
val LZ4F_blockMode_t = "LZ4F_blockMode_t".enumType
val LZ4F_contentChecksum_t = "LZ4F_contentChecksum_t".enumType
val LZ4F_frameType_t = "LZ4F_frameType_t".enumType
val LZ4F_blockChecksum_t = "LZ4F_blockChecksum_t".enumType
val LZ4F_cctx = "LZ4F_cctx".opaque
val LZ4F_dctx = "LZ4F_dctx".opaque
val LZ4F_frameInfo_t = struct(Module.LZ4, "LZ4FFrameInfo", nativeName = "LZ4F_frameInfo_t") {
documentation =
"""
Makes it possible to set or read frame parameters.
Structure must be first init to 0, using {@code memset()}, setting all parameters to default. It's then possible to update selectively some parameter.
"""
LZ4F_blockSizeID_t("blockSizeID", "{@code 0 == default}").links("max\\d+\\w+")
LZ4F_blockMode_t("blockMode", "{@code 0 == default}").links("block\\w+")
LZ4F_contentChecksum_t("contentChecksumFlag", "1: frame terminated with 32-bit checksum of decompressed data; 0: disabled (default) ")
LZ4F_frameType_t("frameType", "read-only field").links("#frame #skippableFrame")
unsigned_long_long("contentSize", "size of uncompressed content ; {@code 0 == unknown}")
unsigned("dictID", "dictionary ID, sent by compressor to help decoder select correct dictionary; 0 == no {@code dictID} provided")
LZ4F_blockChecksum_t("blockChecksumFlag", "1: each block followed by a checksum of block's compressed data; 0: disabled (default)")
}
val LZ4F_preferences_t = struct(Module.LZ4, "LZ4FPreferences", nativeName = "LZ4F_preferences_t") {
documentation =
"""
Makes it possible to supply advanced compression instructions to streaming interface. Structure must be first init to 0, using {@code memset()},
setting all parameters to default. All reserved fields must be set to zero.
"""
LZ4F_frameInfo_t("frameInfo", "")
int(
"compressionLevel",
"0: default (fast mode); values > #CLEVEL_MAX count as #CLEVEL_MAX; values > 0 trigger \"fast acceleration\""
)
unsignedb("autoFlush", "1: always flush, reduces usage of internal buffers")
unsignedb("favorDecSpeed", "1: parser favors decompression speed vs compression ratio. Only works for high compression modes (≥ #CLEVEL_OPT_MIN). Since version 1.8.2.")
unsigned("reserved", "must be zero for forward compatibility")[3]
}
val LZ4F_compressOptions_t = struct(Module.LZ4, "LZ4FCompressOptions", nativeName = "LZ4F_compressOptions_t") {
unsigned(
"stableSrc",
"{@code 1 == src} content will remain present on future calls to {@code LZ4F_compress()}; skip copying {@code src} content within {@code tmp} buffer"
)
unsigned("reserved", "")[3]
}
val LZ4F_decompressOptions_t = struct(Module.LZ4, "LZ4FDecompressOptions", nativeName = "LZ4F_decompressOptions_t") {
unsigned(
"stableDst",
"""
pledges that last 64KB decompressed data will remain available unmodified between invocations.
This optimization skips storage operations in tmp buffers.
"""
)
unsigned(
"skipChecksums",
"""
disable checksum calculation and verification, even when one is present in frame, to save CPU time.
Setting this option to 1 once disables all checksums for the rest of the frame.
"""
)
unsigned("reserved1", "must be set to zero for forward compatibility")
unsigned("reserved0", "idem")
}
val LZ4F_AllocFunction = Module.LZ4.callback {
void.p(
"LZ4FAllocFunction",
"",
opaque_p("opaqueState", ""),
size_t("size", ""),
nativeType = "LZ4F_AllocFunction"
)
}
val LZ4F_CallocFunction = Module.LZ4.callback {
void.p(
"LZ4FCallocFunction",
"",
opaque_p("opaqueState", ""),
size_t("size", ""),
nativeType = "LZ4F_CallocFunction"
)
}
val LZ4F_FreeFunction = Module.LZ4.callback {
void.p(
"LZ4FFreeFunction",
"",
opaque_p("opaqueState", ""),
void.p("address", ""),
nativeType = "LZ4F_FreeFunction"
)
}
val LZ4F_CustomMem = struct(Module.LZ4, "LZ4FCustomMem", nativeName = "LZ4F_CustomMem") {
LZ4F_AllocFunction("customAlloc", "")
nullable..LZ4F_CallocFunction("customCalloc", "optional; when not defined, uses {@code customAlloc} + {@code memset}")
LZ4F_FreeFunction("customFree", "")
opaque_p("opaqueState", "");
}
// lz4frame_static.h
val LZ4F_errorCodes = "LZ4F_errorCodes".enumType
val LZ4F_CDict = "LZ4F_CDict".opaque
// lz4hc.h
val LZ4_streamHC_t = "LZ4_streamHC_t".opaque | bsd-3-clause | c4a5ae0fd47d4c87b28d0e7ab0fe7be0 | 34.739437 | 175 | 0.67028 | 3.387183 | false | false | false | false |
kobakei/MaterialFabSpeedDial | library/src/main/java/io/github/kobakei/materialfabspeeddial/FabSpeedDialMenu.kt | 1 | 4772 | package io.github.kobakei.materialfabspeeddial
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import androidx.annotation.StringRes
import androidx.recyclerview.widget.SortedList
import android.view.KeyEvent
import android.view.Menu
import android.view.MenuItem
import android.view.SubMenu
/**
* Menu class of FAB speed dial.
* This class implements [Menu] interface but some methods are marked as deprecated and not implemented.
*
* Created by keisuke on 2017/06/13.
*/
class FabSpeedDialMenu(private val context: Context) : Menu {
private val menuItems = SortedList(MenuItem::class.java, object : SortedList.Callback<MenuItem>() {
override fun compare(o1: MenuItem, o2: MenuItem): Int = o1.order - o2.order
override fun onChanged(position: Int, count: Int) {
}
override fun areContentsTheSame(oldItem: MenuItem, newItem: MenuItem): Boolean = false
override fun areItemsTheSame(item1: MenuItem, item2: MenuItem): Boolean = false
override fun onInserted(position: Int, count: Int) {
}
override fun onRemoved(position: Int, count: Int) {
}
override fun onMoved(fromPosition: Int, toPosition: Int) {
}
})
override fun add(title: CharSequence): MenuItem {
val itemId = menuItems.size() + 1
return add(0, itemId, itemId, title)
}
override fun add(@StringRes titleRes: Int): MenuItem {
val itemId = menuItems.size() + 1
return add(0, itemId, itemId, titleRes)
}
override fun add(groupId: Int, itemId: Int, order: Int, title: CharSequence): MenuItem {
val menuItem = FabSpeedDialMenuItem(context, itemId, groupId, order)
menuItem.title = title
menuItems.add(menuItem)
return menuItem
}
override fun add(groupId: Int, itemId: Int, order: Int, @StringRes titleRes: Int): MenuItem {
val menuItem = FabSpeedDialMenuItem(context, itemId, groupId, order)
menuItem.setTitle(titleRes)
menuItems.add(menuItem)
return menuItem
}
@Deprecated("")
override fun addSubMenu(title: CharSequence): SubMenu {
throw RuntimeException("Not implemented")
}
@Deprecated("")
override fun addSubMenu(@StringRes titleRes: Int): SubMenu {
throw RuntimeException("Not implemented")
}
@Deprecated("")
override fun addSubMenu(groupId: Int, itemId: Int, order: Int, title: CharSequence): SubMenu {
throw RuntimeException("Not implemented")
}
@Deprecated("")
override fun addSubMenu(groupId: Int, itemId: Int, order: Int, @StringRes titleRes: Int): SubMenu {
throw RuntimeException("Not implemented")
}
@Deprecated("")
override fun addIntentOptions(groupId: Int, itemId: Int, order: Int, caller: ComponentName, specifics: Array<Intent>, intent: Intent, flags: Int, outSpecificItems: Array<MenuItem>): Int {
throw RuntimeException("Not implemented")
}
@Deprecated("")
override fun removeItem(id: Int) {
throw RuntimeException("Not implemented")
}
@Deprecated("")
override fun removeGroup(groupId: Int) {
throw RuntimeException("Not implemented")
}
@Deprecated("")
override fun clear() {
throw RuntimeException("Not implemented")
}
@Deprecated("")
override fun setGroupCheckable(group: Int, checkable: Boolean, exclusive: Boolean) {
throw RuntimeException("Not implemented")
}
@Deprecated("")
override fun setGroupVisible(group: Int, visible: Boolean) {
throw RuntimeException("Not implemented")
}
@Deprecated("")
override fun setGroupEnabled(group: Int, enabled: Boolean) {
throw RuntimeException("Not implemented")
}
@Deprecated("")
override fun hasVisibleItems(): Boolean {
throw RuntimeException("Not implemented")
}
@Deprecated("")
override fun findItem(id: Int): MenuItem {
throw RuntimeException("Not implemented")
}
override fun size(): Int = menuItems.size()
override fun getItem(index: Int): MenuItem = menuItems.get(index)
override fun close() {
throw RuntimeException("Not implemented")
}
override fun performShortcut(keyCode: Int, event: KeyEvent, flags: Int): Boolean {
throw RuntimeException("Not implemented")
}
override fun isShortcutKey(keyCode: Int, event: KeyEvent): Boolean {
throw RuntimeException("Not implemented")
}
override fun performIdentifierAction(id: Int, flags: Int): Boolean {
throw RuntimeException("Not implemented")
}
override fun setQwertyMode(isQwerty: Boolean) {
throw RuntimeException("Not implemented")
}
}
| apache-2.0 | 36cf4a9cae9d1cfb1cd9f6bdd122c967 | 29.394904 | 191 | 0.672674 | 4.628516 | false | false | false | false |
mdanielwork/intellij-community | platform/vcs-log/graph/src/com/intellij/vcs/log/graph/impl/facade/ReachableNodes.kt | 1 | 2829 | /*
* Copyright 2000-2014 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.vcs.log.graph.impl.facade
import com.intellij.util.Consumer
import com.intellij.vcs.log.graph.api.LinearGraph
import com.intellij.vcs.log.graph.api.LiteLinearGraph
import com.intellij.vcs.log.graph.utils.*
import com.intellij.vcs.log.graph.utils.impl.BitSetFlags
import java.util.*
class ReachableNodes(private val graph: LiteLinearGraph) {
private val flags: Flags = BitSetFlags(graph.nodesCount())
fun getContainingBranches(nodeIndex: Int, branchNodeIndexes: Collection<Int>): Set<Int> {
val result = HashSet<Int>()
walk(listOf(nodeIndex), false) { node: Int ->
if (branchNodeIndexes.contains(node)) result.add(node)
true
}
return result
}
fun walkDown(headIds: Collection<Int>, consumer: Consumer<Int>) {
walk(headIds, true) { node: Int ->
consumer.consume(node)
true
}
}
fun walk(startNodes: Collection<Int>, goDown: Boolean, consumer: (Int) -> Boolean) {
synchronized(flags) {
flags.setAll(false)
for (start in startNodes) {
if (start < 0) continue
if (flags.get(start)) continue
flags.set(start, true)
if (!consumer(start)) return
walk(start) nextNode@{ currentNode ->
for (downNode in graph.getNodes(currentNode, if (goDown) LiteLinearGraph.NodeFilter.DOWN else LiteLinearGraph.NodeFilter.UP)) {
if (!flags.get(downNode)) {
flags.set(downNode, true)
if (!consumer(downNode)) return@nextNode Dfs.NextNode.EXIT
return@nextNode downNode
}
}
Dfs.NextNode.NODE_NOT_FOUND
}
}
}
}
companion object {
@JvmStatic
fun getReachableNodes(graph: LinearGraph, headNodeIndexes: Set<Int>?): UnsignedBitSet {
if (headNodeIndexes == null) {
val nodesVisibility = UnsignedBitSet()
nodesVisibility.set(0, graph.nodesCount() - 1, true)
return nodesVisibility
}
val result = UnsignedBitSet()
val reachableNodes = ReachableNodes(LinearGraphUtils.asLiteLinearGraph(graph))
reachableNodes.walk(headNodeIndexes, true) { node: Int ->
result.set(node, true)
true
}
return result
}
}
}
| apache-2.0 | fca160e1616fca8a441bea6ddfdb99a7 | 30.433333 | 137 | 0.671262 | 4.001414 | false | false | false | false |
iSoron/uhabits | uhabits-core/src/jvmTest/java/org/isoron/uhabits/core/commands/DeleteHabitsCommandTest.kt | 1 | 2139 | /*
* Copyright (C) 2016-2021 Álinson Santos Xavier <[email protected]>
*
* This file is part of Loop Habit Tracker.
*
* Loop Habit Tracker 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.
*
* Loop Habit Tracker is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.isoron.uhabits.core.commands
import org.hamcrest.CoreMatchers.equalTo
import org.hamcrest.MatcherAssert.assertThat
import org.isoron.uhabits.core.BaseUnitTest
import org.isoron.uhabits.core.models.Habit
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.junit.rules.ExpectedException
import java.util.LinkedList
class DeleteHabitsCommandTest : BaseUnitTest() {
private lateinit var command: DeleteHabitsCommand
private lateinit var selected: LinkedList<Habit>
@get:Rule
var thrown = ExpectedException.none()!!
@Before
@Throws(Exception::class)
override fun setUp() {
super.setUp()
selected = LinkedList()
// Habits that should be deleted
for (i in 0..2) {
val habit = fixtures.createShortHabit()
habitList.add(habit)
selected.add(habit)
}
// Extra habit that should not be deleted
val extraHabit = fixtures.createShortHabit()
extraHabit.name = "extra"
habitList.add(extraHabit)
command = DeleteHabitsCommand(habitList, selected)
}
@Test
fun testExecute() {
assertThat(habitList.size(), equalTo(4))
command.run()
assertThat(habitList.size(), equalTo(1))
assertThat(habitList.getByPosition(0).name, equalTo("extra"))
}
}
| gpl-3.0 | b53cd9174839fc08ba9aa3eb9821a735 | 31.892308 | 78 | 0.702526 | 4.327935 | false | true | false | false |
stanfy/helium | codegen/objc/objc-entities/src/main/kotlin/com/stanfy/helium/handler/codegen/objectivec/entity/filetree/ObjCPropertyDefinition.kt | 1 | 2413 | package com.stanfy.helium.handler.codegen.objectivec.entity.filetree;
import com.stanfy.helium.handler.codegen.objectivec.entity.classtree.ObjCType
import com.stanfy.helium.model.Field;
enum class AccessModifier {
COPY,
RETAIN,
ASSIGN,
STRONG,
WEAK
}
enum class AtomicModifier {
ATOMIC,
NONATOMIC,
}
/**
* Created by ptaykalo on 8/19/14.
* Wrapper for ObjC property
*/
class ObjCPropertyDefinition : ObjCSourcePart {
constructor(name: String, type: ObjCType) :
this(name, type, AccessModifier.STRONG, AtomicModifier.NONATOMIC) {
}
constructor(name: String, type: ObjCType, accessModifier: AccessModifier) :
this(name, type, accessModifier, AtomicModifier.NONATOMIC) {
}
constructor(name: String, type: ObjCType, accessModifier: AccessModifier, atomicModifier: AtomicModifier) {
this.name = name;
this.type = type;
this.accessModifier = accessModifier;
this.atomicModifier = atomicModifier;
}
/**
* Property name
*/
val name: String
/**
* Property result type (this is the type, which will be simply translated to the output)
* so, in case of ObjC - it should be NSString, and NSArray... etc
*/
val type: ObjCType
/**
* Access modifier for property AccessModifier.STRONG - for default value
*/
private val accessModifier:AccessModifier
/**
* By default we'll create non-atomic modifier
*/
val atomicModifier:AtomicModifier
/**
* Additional comment
*/
var comment: String? = null
//TODO : Remove it from here?
/**
* the Helium filed, from which this property was generated
*/
var correspondingField: Field? = null
/**
* Returns true, if this property is sequence,
* And property type is ono corresponds to the actual items type
*/
var isSequence: Boolean = false;
/**
* Holds information for item type, that will be presented in this property.
* Property type can be "NSArray / NSSet" etc
* This property will hold type of actual items, those are in this property
*/
var sequenceType: ObjCType? = null;
override fun asString(): String {
var propertyDeclaration = "@property(" + atomicModifier.toString().toLowerCase() + ", " + accessModifier.toString().toLowerCase() + ") " + type + " " + name + ";";
if (comment != null) {
propertyDeclaration = "// " + comment + "\n" + propertyDeclaration;
}
return propertyDeclaration;
}
}
| apache-2.0 | 4f72163f722934d6aabc6c71b0760941 | 24.4 | 167 | 0.689184 | 4.110733 | false | false | false | false |
ngthtung2805/dalatlaptop | app/src/main/java/com/tungnui/dalatlaptop/ux/adapters/ProductImagesPagerAdapter.kt | 1 | 1392 | package com.tungnui.dalatlaptop.ux.adapters
import android.content.Context
import android.support.v4.view.PagerAdapter
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.RelativeLayout
import com.tungnui.dalatlaptop.models.Image
import com.tungnui.dalatlaptop.R
import com.tungnui.dalatlaptop.views.TouchImageView
import com.tungnui.dalatlaptop.utils.loadImg
class ProductImagesPagerAdapter(private val context: Context, private val images: List<Image>) : PagerAdapter() {
override fun getCount(): Int {
return this.images.size
}
override fun isViewFromObject(view: View, `object`: Any): Boolean {
return view === `object`
}
override fun instantiateItem(container: ViewGroup, position: Int): Any {
val imgDisplay: TouchImageView
val inflater = context.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater
val viewLayout = inflater.inflate(R.layout.layout_fullscreen_image, container, false)
imgDisplay = viewLayout.findViewById<View>(R.id.fullscreen_image) as TouchImageView
imgDisplay.loadImg(images[position].src)
container.addView(viewLayout)
return viewLayout
}
override fun destroyItem(container: ViewGroup, position: Int, `object`: Any) {
container.removeView(`object` as RelativeLayout)
}
} | mit | dfe62a3e2f3ead3dca7759449a854b7a | 35.657895 | 113 | 0.750718 | 4.447284 | false | false | false | false |
dahlstrom-g/intellij-community | plugins/kotlin/idea/tests/testData/refactoring/move/kotlin/moveTopLevelDeclarations/misc/mutualDependency/before/pack/test.kt | 13 | 157 | package pack
class <caret>A {
val a = A()
val b = B()
val c = C()
}
class <caret>B {
val a = A()
val b = B()
val c = C()
}
class C | apache-2.0 | cfe49e7aa9be417295f4ee14c8a5647d | 9.533333 | 16 | 0.43949 | 2.532258 | false | false | false | false |
intellij-solidity/intellij-solidity | src/main/kotlin/me/serce/solidity/ide/inspections/fixes/ImportFileAction.kt | 1 | 5376 | package me.serce.solidity.ide.inspections.fixes
import com.intellij.codeInsight.hint.QuestionAction
import com.intellij.ide.util.DefaultPsiElementCellRenderer
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.command.CommandProcessor
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.popup.PopupStep
import com.intellij.openapi.ui.popup.util.BaseListPopupStep
import com.intellij.openapi.util.RecursionManager
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.psi.PsiDocumentManager
import com.intellij.psi.PsiFile
import com.intellij.ui.popup.list.ListPopupImpl
import com.intellij.ui.popup.list.PopupListElementRenderer
import me.serce.solidity.nullIfError
import me.serce.solidity.lang.psi.SolImportDirective
import me.serce.solidity.lang.psi.SolPragmaDirective
import me.serce.solidity.lang.psi.SolPsiFactory
import java.awt.BorderLayout
import java.io.File
import java.nio.file.Paths
import javax.swing.Icon
import javax.swing.JPanel
import javax.swing.ListCellRenderer
class ImportFileAction(
val editor: Editor,
private val file: PsiFile,
private val suggestions: Set<PsiFile>
) : QuestionAction {
val project: Project
get() = file.project
override fun execute(): Boolean {
PsiDocumentManager.getInstance(project).commitAllDocuments()
if (suggestions.size == 1) {
addImport(project, file, suggestions.first())
} else {
chooseFileToImport()
}
return true
}
private fun chooseFileToImport() {
val step = object : BaseListPopupStep<PsiFile>("File to import", suggestions.toMutableList()) {
override fun isAutoSelectionEnabled(): Boolean {
return false
}
override fun isSpeedSearchEnabled(): Boolean {
return true
}
override fun onChosen(selectedValue: PsiFile?, finalChoice: Boolean): PopupStep<*>? {
if (selectedValue == null) {
return PopupStep.FINAL_CHOICE
}
return doFinalStep {
PsiDocumentManager.getInstance(project).commitAllDocuments()
addImport(project, file, selectedValue)
}
}
override fun hasSubstep(selectedValue: PsiFile?): Boolean {
return true
}
override fun getTextFor(value: PsiFile): String {
return value.name
}
override fun getIconFor(aValue: PsiFile): Icon? {
return aValue.getIcon(0)
}
}
val popup = object : ListPopupImpl(project, step) {
override fun getListElementRenderer(): ListCellRenderer<PsiFile> {
@Suppress("UNCHECKED_CAST")
val baseRenderer = super.getListElementRenderer() as PopupListElementRenderer<PsiFile>
val psiRenderer = DefaultPsiElementCellRenderer()
return ListCellRenderer { list, value, index, isSelected, cellHasFocus ->
val panel = JPanel(BorderLayout())
baseRenderer.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus)
panel.add(baseRenderer.nextStepLabel, BorderLayout.EAST)
panel.add(psiRenderer.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus))
panel
}
}
}
popup.showInBestPositionFor(editor)
}
companion object {
fun isImportedAlready(file: PsiFile, to: PsiFile): Boolean {
return if (file == to) {
true
} else {
RecursionManager.doPreventingRecursion(file, true) {
file.children
.filterIsInstance<SolImportDirective>()
.mapNotNull { nullIfError { it.importPath?.reference?.resolve()?.containingFile } }
.any {
isImportedAlready(it, to)
}
} ?: false
}
}
fun addImport(project: Project, file: PsiFile, to: PsiFile) {
CommandProcessor.getInstance().runUndoTransparentAction {
ApplicationManager.getApplication().runWriteAction {
val after = file.children.filterIsInstance<SolImportDirective>().lastOrNull()
?: file.children.filterIsInstance<SolPragmaDirective>().firstOrNull()
val factory = SolPsiFactory(project)
file.addAfter(factory.createImportDirective(buildImportPath(file.virtualFile, to.virtualFile)), after)
file.addAfter(factory.createNewLine(project), after)
}
}
}
fun buildImportPath(source: VirtualFile, destination: VirtualFile): String {
return Paths.get(source.path).parent.relativize(Paths.get(destination.path)).toString().let {
val separator = File.separator
when {
it.contains("node_modules$separator") -> {
val idx = it.indexOf("node_modules$separator")
it.substring(idx + "node_modules$separator".length)
}
it.contains("lib$separator") -> {
val idx = it.indexOf("lib$separator")
it.substring(idx + "lib$separator".length)
}
it.contains("installed_contracts$separator") -> {
val idx = it.indexOf("installed_contracts$separator")
it.substring(idx + "installed_contracts$separator".length)
.replaceFirst("${separator}contracts${separator}", separator)
}
!it.startsWith(".") -> ".$separator$it"
else -> it
}
}
}
}
}
| mit | e48205ce414c0bbb58e8992f6e1625be | 34.602649 | 112 | 0.677269 | 4.830189 | false | false | false | false |
dkandalov/katas | kotlin/src/katas/kotlin/graph/Traversal4.kt | 1 | 4127 | package katas.kotlin.graph
import katas.kotlin.graph.Graph.Node
import nonstdlib.join
import datsok.shouldEqual
import org.junit.Test
import java.util.*
import kotlin.collections.LinkedHashSet
class Traversal4 {
@Test fun `depth-first traversal`() {
"[a]".toGraph().let {
it.dft("a") shouldEqual "a"
it.dft("x") shouldEqual ""
}
"[a-b]".toGraph().let {
it.dft("a") shouldEqual "a-b"
it.dft("b") shouldEqual "b-a"
it.dft("x") shouldEqual ""
}
"[a-b, b-c]".toGraph().let {
it.dft("a") shouldEqual "a-b-c"
it.dft("b") shouldEqual "b-a-c"
it.dft("c") shouldEqual "c-b-a"
it.dft("x") shouldEqual ""
}
// a──b1──c
// └──b2──┘
"[a-b1, a-b2, b1-c, b2-c]".toGraph().let {
it.dft("a") shouldEqual "a-b1-c-b2"
it.dft("b1") shouldEqual "b1-a-b2-c"
it.dft("b2") shouldEqual "b2-a-b1-c"
it.dft("c") shouldEqual "c-b1-a-b2"
}
}
@Test fun `breadth-first traversal`() {
"[a]".toGraph().let {
it.bft("a") shouldEqual "a"
it.bft("x") shouldEqual ""
}
"[a-b]".toGraph().let {
it.bft("a") shouldEqual "a-b"
it.bft("b") shouldEqual "b-a"
it.bft("x") shouldEqual ""
}
"[a-b, b-c]".toGraph().let {
it.bft("a") shouldEqual "a-b-c"
it.bft("b") shouldEqual "b-a-c"
it.bft("c") shouldEqual "c-b-a"
it.bft("x") shouldEqual ""
}
// a──b1──c
// └──b2──┘
"[a-b1, a-b2, b1-c, b2-c]".toGraph().let {
it.bft("a") shouldEqual "a-b1-b2-c"
it.bft("b1") shouldEqual "b1-a-c-b2"
it.bft("b2") shouldEqual "b2-a-c-b1"
it.bft("c") shouldEqual "c-b1-b2-a"
}
}
private data class Result<T>(val path: LinkedHashSet<T>) {
operator fun plus(value: T) = Result(LinkedHashSet(path + value))
fun contains(value: T) = path.contains(value)
companion object {
fun <T> empty(): Result<T> = Result(LinkedHashSet())
}
}
private interface Container<T> {
fun add(value: T)
fun add(values: Collection<T>)
fun remove(): T
fun isNotEmpty(): Boolean
companion object {
fun <T> queue() = object: Container<T> {
val list = LinkedList<T>()
override fun add(value: T) = list.addFirst(value)
override fun add(values: Collection<T>) { list.addAll(values) }
override fun remove() = list.removeFirst()
override fun isNotEmpty() = list.isNotEmpty()
}
fun <T> stack() = object: Container<T> {
val list = LinkedList<T>()
override fun add(value: T) = list.addLast(value)
override fun add(values: Collection<T>) { list.addAll(values.reversed()) }
override fun remove() = list.removeLast()
override fun isNotEmpty() = list.isNotEmpty()
}
}
}
private fun <Value, Label> Graph<Value, Label>.bft(value: Value, separator: String = "-"): String {
val node = nodes[value] ?: return ""
return node.traverse(Container.queue()).path.join(separator)
}
private fun <Value, Label> Graph<Value, Label>.dft(value: Value, separator: String = "-"): String {
val node = nodes[value] ?: return ""
return node.traverse(Container.stack()).path.join(separator)
}
private fun <Value, Label> Node<Value, Label>.traverse(container: Container<Node<Value, Label>>): Result<Value> {
var result = Result.empty<Value>()
container.add(this)
while (container.isNotEmpty()) {
val node = container.remove()
if (!result.contains(node.value)) {
result += node.value
container.add(node.neighbors())
}
}
return result
}
} | unlicense | 24835f1e9929d769ebecbf617d4d199e | 33.066667 | 117 | 0.512112 | 3.550825 | false | false | false | false |
martijn-heil/wac-core | src/main/kotlin/tk/martijn_heil/wac_core/craft/vessel/sail/Count.kt | 1 | 5766 | /*
* wac-core
* Copyright (C) 2016 Martijn Heil
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package tk.martijn_heil.wac_core.craft.vessel.sail
import org.bukkit.Location
import org.bukkit.Material
import org.bukkit.block.Block
import org.bukkit.block.Sign
import org.bukkit.event.EventHandler
import org.bukkit.event.EventPriority
import org.bukkit.event.HandlerList
import org.bukkit.event.Listener
import org.bukkit.event.player.PlayerInteractEvent
import org.bukkit.plugin.Plugin
import tk.martijn_heil.wac_core.craft.RowingDirection
import tk.martijn_heil.wac_core.craft.vessel.SimpleRudder
import java.util.*
import java.util.logging.Logger
class Count private constructor(plugin: Plugin, logger: Logger, blocks: Collection<Block>, rotationPoint: Location, sails: Collection<SimpleSail>, rudder: SimpleRudder, rowingSign: Sign, rowingDirectionSign: Sign) : SimpleSailingVessel(plugin, logger, blocks, rotationPoint, sails, rudder, rowingSign, rowingDirectionSign) {
override var normalMaxSpeed: Int = 7000
override var updateInterval: Int = 80
private val listener2 = object : Listener {
@EventHandler(ignoreCancelled = true, priority = EventPriority.HIGHEST)
fun onPlayerInteract(e: PlayerInteractEvent) {
if(e.clickedBlock == null) return
val state = e.clickedBlock.state
if (state is Sign && state.lines[0] == "[Craft]" && containsBlock(e.clickedBlock)) {
e.isCancelled = true
}
}
}
override fun init() {
super.init()
plugin.server.pluginManager.registerEvents(listener2, plugin)
}
override fun close() {
super.close()
HandlerList.unregisterAll(listener2)
}
companion object {
fun detect(plugin: Plugin, logger: Logger, detectionLoc: Location): SimpleSailingVessel {
val sails: MutableCollection<SimpleSail> = ArrayList()
try {
val maxSize = 10000
val allowedBlocks: Collection<Material> = Material.values().filter { it != Material.AIR && it != Material.WATER && it != Material.STATIONARY_WATER && it != Material.LAVA && it != Material.STATIONARY_LAVA }
val blocks: Collection<Block>
// Detect vessel
try {
logger.info("Detecting count at " + detectionLoc.x + "x " + detectionLoc.y + "y " + detectionLoc.z + "z")
blocks = tk.martijn_heil.wac_core.craft.util.detect(detectionLoc, allowedBlocks, maxSize)
} catch(e: Exception) {
logger.info("Failed to detect sailing vessel: " + (e.message ?: "unknown error"))
throw IllegalStateException(e.message)
}
val signs = blocks.map { it.state }.filter { it is Sign }.map { it as Sign }
val rotationPointSign = signs.find { it.lines[0] == "[RotationPoint]" }
if (rotationPointSign == null) {
logger.warning("Could not detect rotation point")
throw IllegalStateException("Could not detect rotation point.")
}
val rotationPoint = rotationPointSign.location
// Detect rudder
val rudderSign = signs.find { it.lines[0] == "[Rudder]" } ?: throw IllegalStateException("No rudder found.")
logger.info("Found rudder sign at " + rudderSign.x + " " + rudderSign.y + " " + rudderSign.z)
val rudder = SimpleRudder(rudderSign)
val rowingSign = signs.find { it.lines[0] == "[Rowing]" } ?: throw IllegalStateException("No rowing sign found.")
rowingSign.setLine(1, "false")
rowingSign.update(true, false)
logger.info("Found rowing sign at " + rowingSign.x + " " + rowingSign.y + " " + rudderSign.z)
val rowingDirectionSign = signs.find { it.lines[0] == "[RowingDirection]" } ?: throw IllegalStateException("No rowing direction sign found.")
if(rowingDirectionSign.lines[1] == "") rowingDirectionSign.setLine(1, RowingDirection.FORWARD.toString().toLowerCase())
logger.info("Found RowingDirection sign at " + rowingDirectionSign.x + " " + rowingDirectionSign.y + " " + rowingDirectionSign.z)
// Detect sails
signs.filter { it.lines[0] == "[Sail]" }.forEach {
logger.fine("Found sail sign at " + it.x + " " + it.y + " " + it.z)
sails.add(SimpleSail(plugin, it))
}
if (sails.isEmpty()) throw IllegalStateException("No sails found.")
val count = Count(plugin, logger, blocks, rotationPoint, sails, rudder, rowingSign, rowingDirectionSign)
count.init()
return count
} catch(t: Throwable) {
sails.forEach { it.isHoisted = true; it.close() }
throw t
}
}
}
} | gpl-3.0 | eb7b4d528f10062f776172df52763a33 | 47.724138 | 324 | 0.609261 | 4.536585 | false | false | false | false |
gituser9/InvoiceManagement | app/src/main/java/com/user/invoicemanagement/model/dto/ProductFactory.kt | 1 | 828 | package com.user.invoicemanagement.model.dto
import com.raizlabs.android.dbflow.annotation.Column
import com.raizlabs.android.dbflow.annotation.OneToMany
import com.raizlabs.android.dbflow.annotation.PrimaryKey
import com.raizlabs.android.dbflow.annotation.Table
import com.raizlabs.android.dbflow.kotlinextensions.from
import com.raizlabs.android.dbflow.kotlinextensions.oneToMany
import com.raizlabs.android.dbflow.kotlinextensions.select
import com.raizlabs.android.dbflow.kotlinextensions.where
@Table(database = DbflowDatabase::class)
class ProductFactory {
@PrimaryKey(autoincrement = true)
var id: Long = 0
@Column
var name: String = ""
@get:OneToMany(methods = arrayOf(OneToMany.Method.ALL))
var products by oneToMany { select from Product::class where (Product_Table.factoryId.eq(id)) }
} | mit | c1e712b074e4e9a1fe540aff96d8ca76 | 32.16 | 99 | 0.799517 | 4.078818 | false | false | false | false |
georocket/georocket | src/main/kotlin/io/georocket/storage/ChunkMeta.kt | 1 | 3816 | package io.georocket.storage
import com.fasterxml.jackson.annotation.JsonTypeInfo
import com.fasterxml.jackson.databind.DatabindContext
import com.fasterxml.jackson.databind.JavaType
import com.fasterxml.jackson.databind.annotation.JsonTypeIdResolver
import com.fasterxml.jackson.databind.jsontype.impl.TypeIdResolverBase
import io.georocket.util.MimeTypeUtils.belongsTo
import io.georocket.util.XMLStartElement
import io.vertx.core.json.JsonObject
@JsonTypeInfo(
use = JsonTypeInfo.Id.CUSTOM,
include = JsonTypeInfo.As.PROPERTY,
property = "mimeType",
visible = true,
)
@JsonTypeIdResolver(ChunkMetaResolver::class)
sealed class ChunkMeta {
abstract val mimeType: String
fun toJsonObject(): JsonObject {
return JsonObject.mapFrom(this)
}
companion object {
fun fromJsonObject(json: JsonObject): ChunkMeta {
return json.mapTo(ChunkMeta::class.java)
}
}
}
sealed class JsonChunkMeta : ChunkMeta() {
/**
* The name of the field whose value is equal to this chunk or, if
* the field is an array, whose value contains this chunk (may be
* `null` if the chunk does not have a parent)
*/
abstract val parentName: String?
}
sealed class XmlChunkMeta : ChunkMeta() {
/**
* the chunk's parents (i.e. the XML start elements the
* chunk is wrapped in)
*/
abstract val parents: List<XMLStartElement>
}
data class GenericChunkMeta(
override val mimeType: String,
) : ChunkMeta()
data class GenericJsonChunkMeta constructor(
override val parentName: String?,
override val mimeType: String = MIME_TYPE,
) : JsonChunkMeta() {
companion object {
const val MIME_TYPE = "application/json"
}
init {
if (!belongsTo(mimeType, "application", "json")) {
throw IllegalArgumentException("Mime type must belong to application/json")
}
}
}
data class GeoJsonChunkMeta(
/**
* The type of the GeoJSON object represented by the chunk
*/
val type: String,
override val parentName: String?,
override val mimeType: String = MIME_TYPE,
) : JsonChunkMeta() {
companion object {
const val MIME_TYPE = "application/geo+json"
}
constructor(type: String, baseMeta: JsonChunkMeta) : this(type, baseMeta.parentName, MIME_TYPE)
init {
if (!belongsTo(mimeType, "application", "geo+json")) {
throw IllegalArgumentException("Mime type must belong to application/geo+json")
}
}
}
data class GenericXmlChunkMeta(
override val parents: List<XMLStartElement>,
override val mimeType: String = MIME_TYPE
) : XmlChunkMeta() {
companion object {
const val MIME_TYPE = "application/xml"
}
init {
if (!belongsTo(mimeType, "application", "xml")) {
throw IllegalArgumentException("Mime type must belong to application/xml")
}
}
}
class ChunkMetaResolver : TypeIdResolverBase() {
var base: JavaType? = null
override fun init(baseType: JavaType?) {
base = baseType
}
override fun idFromValue(value: Any?): String = (value as ChunkMeta).mimeType
override fun typeFromId(context: DatabindContext?, id: String?): JavaType {
if (id == null) {
throw NullPointerException()
}
if (belongsTo(id, "application", "geo+json")) {
return context!!.constructSpecializedType(base, GeoJsonChunkMeta::class.java)
}
if (belongsTo(id, "application", "json")) {
return context!!.constructSpecializedType(base, GenericJsonChunkMeta::class.java)
}
if (belongsTo(id, "application", "xml")) {
return context!!.constructSpecializedType(base, GenericXmlChunkMeta::class.java)
}
return context!!.constructSpecializedType(base, GenericChunkMeta::class.java)
}
override fun idFromValueAndType(value: Any?, suggestedType: Class<*>?): String = idFromValue(value)
override fun getMechanism(): JsonTypeInfo.Id = JsonTypeInfo.Id.CUSTOM
}
| apache-2.0 | ff7d78b465cd1bc54a8b4195d9db6c16 | 27.058824 | 101 | 0.716981 | 4.112069 | false | false | false | false |
google/intellij-community | plugins/kotlin/refactorings/rename.k2/src/org/jetbrains/kotlin/idea/refactoring/rename/KotlinNamedDeclarationRenameUsage.kt | 1 | 2450 | // 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.rename
import com.intellij.model.Pointer
import com.intellij.navigation.TargetPresentation
import com.intellij.openapi.util.TextRange
import com.intellij.psi.PsiFile
import com.intellij.refactoring.rename.api.ModifiableRenameUsage
import com.intellij.refactoring.rename.api.PsiModifiableRenameUsage
import com.intellij.refactoring.rename.api.RenameTarget
import com.intellij.refactoring.suggested.createSmartPointer
import org.jetbrains.kotlin.idea.util.application.withPsiAttachment
import org.jetbrains.kotlin.psi.KtNamedDeclaration
import org.jetbrains.kotlin.utils.KotlinExceptionWithAttachments
internal class KotlinNamedDeclarationRenameUsage private constructor(
val element: KtNamedDeclaration
) : PsiModifiableRenameUsage, RenameTarget {
override fun createPointer(): Pointer<KotlinNamedDeclarationRenameUsage> {
return Pointer.delegatingPointer(element.createSmartPointer(), KotlinNamedDeclarationRenameUsage::create)
}
override val targetName: String
get() = element.name ?: reportMissingName()
override val presentation: TargetPresentation
get() = TargetPresentation.builder(targetName).presentation()
override val file: PsiFile
get() = element.containingFile
override val range: TextRange
get() = element.nameIdentifier?.textRange ?: reportMissingName()
override val declaration: Boolean
get() = true
override val fileUpdater: ModifiableRenameUsage.FileUpdater
get() = kotlinFileRangeUpdater()
private fun reportMissingName(): Nothing {
throw KotlinExceptionWithAttachments("Rename cannot work on declaration without name")
.withPsiAttachment("declaration", element)
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as KotlinNamedDeclarationRenameUsage
if (element != other.element) return false
return true
}
override fun hashCode(): Int {
return element.hashCode()
}
companion object {
fun create(element: KtNamedDeclaration): KotlinNamedDeclarationRenameUsage? =
if (element.nameIdentifier != null) KotlinNamedDeclarationRenameUsage(element) else null
}
}
| apache-2.0 | b95649255061bf74280ffd85c49ba87a | 36.121212 | 120 | 0.755102 | 5.326087 | false | false | false | false |
StepicOrg/stepik-android | app/src/main/java/org/stepic/droid/ui/dialogs/VideoQualityDialog.kt | 2 | 2500 | package org.stepic.droid.ui.dialogs
import android.app.Dialog
import android.os.Bundle
import com.google.android.material.dialog.MaterialAlertDialogBuilder
import org.stepic.droid.R
import org.stepic.droid.analytic.Analytic
import org.stepic.droid.base.App
import org.stepic.droid.preferences.UserPreferences
import ru.nobird.android.view.base.ui.extension.argument
import java.util.concurrent.ThreadPoolExecutor
import javax.inject.Inject
class VideoQualityDialog : VideoQualityDialogBase() {
companion object {
const val TAG = "VideoQualityDialog"
fun newInstance(forPlaying: Boolean) =
VideoQualityDialog().also {
it.forPlaying = forPlaying
}
}
@Inject
lateinit var userPreferences: UserPreferences
@Inject
lateinit var analytic: Analytic
@Inject
lateinit var threadPoolExecutor: ThreadPoolExecutor
private var forPlaying by argument<Boolean>()
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
init()
val qualityValue = if (forPlaying) {
userPreferences.qualityVideoForPlaying
} else {
userPreferences.qualityVideo
}
val chosenOptionPosition = qualityToPositionMap[qualityValue]!!
val builder = MaterialAlertDialogBuilder(requireContext())
builder
.setTitle(
if (forPlaying) {
R.string.video_quality_playing
} else {
R.string.video_quality
}
)
.setSingleChoiceItems(resources.getStringArray(R.array.video_quality), chosenOptionPosition) { dialog, which ->
val qualityString = positionToQualityMap[which]
analytic.reportEventWithIdName(Analytic.Preferences.VIDEO_QUALITY, which.toString(), qualityString)
threadPoolExecutor.execute {
if (forPlaying) {
userPreferences.saveVideoQualityForPlaying(qualityString)
} else {
userPreferences.storeQualityVideo(qualityString)
}
}
dialog.dismiss()
}
.setNegativeButton(R.string.cancel) { _, _ ->
analytic.reportEvent(Analytic.Interaction.CANCEL_VIDEO_QUALITY)
}
return builder.create()
}
override fun injectDependencies() {
App.component().inject(this)
}
}
| apache-2.0 | 8813e22dfd05004353b61298232c0dbb | 31.051282 | 123 | 0.63 | 5.353319 | false | false | false | false |
vvv1559/intellij-community | platform/script-debugger/backend/src/debugger/sourcemap/SourceMapDecoder.kt | 2 | 11540 | /*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.debugger.sourcemap
import com.google.gson.stream.JsonToken
import com.intellij.openapi.util.registry.Registry
import com.intellij.openapi.util.text.StringUtil
import com.intellij.openapi.util.text.StringUtilRt
import com.intellij.util.PathUtil
import com.intellij.util.SmartList
import com.intellij.util.UriUtil
import com.intellij.util.containers.isNullOrEmpty
import org.jetbrains.debugger.sourcemap.Base64VLQ.CharIterator
import org.jetbrains.io.JsonReaderEx
import java.io.IOException
import java.util.*
import kotlin.properties.Delegates.notNull
private val MAPPING_COMPARATOR_BY_SOURCE_POSITION = Comparator<MappingEntry> { o1, o2 ->
if (o1.sourceLine == o2.sourceLine) {
o1.sourceColumn - o2.sourceColumn
}
else {
o1.sourceLine - o2.sourceLine
}
}
val MAPPING_COMPARATOR_BY_GENERATED_POSITION: Comparator<MappingEntry> = Comparator { o1, o2 ->
if (o1.generatedLine == o2.generatedLine) {
o1.generatedColumn - o2.generatedColumn
}
else {
o1.generatedLine - o2.generatedLine
}
}
internal const val UNMAPPED = -1
// https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit?hl=en_US
fun decodeSourceMap(`in`: CharSequence, sourceResolverFactory: (sourceUrls: List<String>, sourceContents: List<String>?) -> SourceResolver): SourceMap? {
if (`in`.isEmpty()) {
throw IOException("source map contents cannot be empty")
}
val reader = JsonReaderEx(`in`)
reader.isLenient = true
return parseMap(reader, 0, 0, ArrayList(), sourceResolverFactory)
}
private fun parseMap(reader: JsonReaderEx,
line: Int,
column: Int,
mappings: MutableList<MappingEntry>,
sourceResolverFactory: (sourceUrls: List<String>, sourceContents: List<String>?) -> SourceResolver): SourceMap? {
reader.beginObject()
var sourceRoot: String? = null
var sourcesReader: JsonReaderEx? = null
var names: List<String>? = null
var encodedMappings: String? = null
var file: String? = null
var version = -1
var sourcesContent: MutableList<String>? = null
while (reader.hasNext()) {
when (reader.nextName()) {
"sections" -> throw IOException("sections is not supported yet")
"version" -> {
version = reader.nextInt()
}
"sourceRoot" -> {
sourceRoot = readSourcePath(reader)
if (sourceRoot != null && sourceRoot != "/") {
sourceRoot = UriUtil.trimTrailingSlashes(sourceRoot)
}
}
"sources" -> {
sourcesReader = reader.subReader()
reader.skipValue()
}
"names" -> {
reader.beginArray()
if (reader.hasNext()) {
names = ArrayList()
do {
if (reader.peek() == JsonToken.BEGIN_OBJECT) {
// polymer map
reader.skipValue()
names.add("POLYMER UNKNOWN NAME")
}
else {
names.add(reader.nextString(true))
}
}
while (reader.hasNext())
}
else {
names = emptyList()
}
reader.endArray()
}
"mappings" -> {
encodedMappings = reader.nextString()
}
"file" -> {
file = reader.nextString()
}
"sourcesContent" -> {
reader.beginArray()
if (reader.peek() != JsonToken.END_ARRAY) {
sourcesContent = SmartList<String>()
do {
if (reader.peek() == JsonToken.STRING) {
sourcesContent.add(StringUtilRt.convertLineSeparators(reader.nextString()))
}
else {
reader.skipValue()
}
}
while (reader.hasNext())
}
reader.endArray()
}
else -> {
// skip file or extensions
reader.skipValue()
}
}
}
reader.close()
// check it before other checks, probably it is not a sourcemap file
if (encodedMappings.isNullOrEmpty()) {
// empty map
return null
}
if (Registry.`is`("js.debugger.fix.jspm.source.maps", false) && encodedMappings!!.startsWith(";") && file != null && file.endsWith(".ts!transpiled")) {
encodedMappings = encodedMappings.substring(1)
}
if (version != 3) {
throw IOException("Unsupported sourcemap version: $version")
}
if (sourcesReader == null) {
throw IOException("sources is not specified")
}
val sources = readSources(sourcesReader, sourceRoot)
if (sources.isEmpty()) {
// empty map, meteor can report such ugly maps
return null
}
val reverseMappingsBySourceUrl = arrayOfNulls<MutableList<MappingEntry>?>(sources.size)
readMappings(encodedMappings!!, line, column, mappings, reverseMappingsBySourceUrl, names)
val sourceToEntries = Array<MappingList?>(reverseMappingsBySourceUrl.size) {
val entries = reverseMappingsBySourceUrl[it]
if (entries == null) {
null
}
else {
entries.sortWith(MAPPING_COMPARATOR_BY_SOURCE_POSITION)
SourceMappingList(entries)
}
}
return OneLevelSourceMap(file, GeneratedMappingList(mappings), sourceToEntries, sourceResolverFactory(sources, sourcesContent), !names.isNullOrEmpty())
}
private fun readSourcePath(reader: JsonReaderEx) = PathUtil.toSystemIndependentName(StringUtil.nullize(reader.nextString().trim { it <= ' ' }))
private fun readMappings(value: String,
initialLine: Int,
initialColumn: Int,
mappings: MutableList<MappingEntry>,
reverseMappingsBySourceUrl: Array<MutableList<MappingEntry>?>,
names: List<String>?) {
if (value.isEmpty()) {
return
}
var line = initialLine
var column = initialColumn
val charIterator = CharSequenceIterator(value)
var sourceIndex = 0
var reverseMappings: MutableList<MappingEntry> = getMapping(reverseMappingsBySourceUrl, sourceIndex)
var sourceLine = 0
var sourceColumn = 0
var nameIndex = 0
var prevEntry: MutableEntry? = null
fun addEntry(entry: MutableEntry) {
if (prevEntry != null) {
prevEntry!!.nextGenerated = entry
}
prevEntry = entry
mappings.add(entry)
}
while (charIterator.hasNext()) {
if (charIterator.peek() == ',') {
charIterator.next()
}
else {
while (charIterator.peek() == ';') {
line++
column = 0
charIterator.next()
if (!charIterator.hasNext()) {
return
}
}
}
column += Base64VLQ.decode(charIterator)
if (isSeparator(charIterator)) {
addEntry(UnmappedEntry(line, column))
continue
}
val sourceIndexDelta = Base64VLQ.decode(charIterator)
if (sourceIndexDelta != 0) {
sourceIndex += sourceIndexDelta
reverseMappings = getMapping(reverseMappingsBySourceUrl, sourceIndex)
}
sourceLine += Base64VLQ.decode(charIterator)
sourceColumn += Base64VLQ.decode(charIterator)
val entry: MutableEntry
if (isSeparator(charIterator)) {
entry = UnnamedEntry(line, column, sourceIndex, sourceLine, sourceColumn)
}
else {
nameIndex += Base64VLQ.decode(charIterator)
assert(names != null)
entry = NamedEntry(names!![nameIndex], line, column, sourceIndex, sourceLine, sourceColumn)
}
reverseMappings.add(entry)
addEntry(entry)
}
}
private fun readSources(reader: JsonReaderEx, sourceRoot: String?): List<String> {
reader.beginArray()
val sources: List<String>
if (reader.peek() == JsonToken.END_ARRAY) {
sources = emptyList()
}
else {
sources = SmartList<String>()
do {
var sourceUrl = readSourcePath(reader)
if (!sourceRoot.isNullOrEmpty()) {
if (sourceRoot == "/") {
sourceUrl = "/$sourceUrl"
}
else {
sourceUrl = "$sourceRoot/$sourceUrl"
}
}
sources.add(sourceUrl)
}
while (reader.hasNext())
}
reader.endArray()
return sources
}
private fun getMapping(reverseMappingsBySourceUrl: Array<MutableList<MappingEntry>?>, sourceIndex: Int): MutableList<MappingEntry> {
var reverseMappings = reverseMappingsBySourceUrl.get(sourceIndex)
if (reverseMappings == null) {
reverseMappings = ArrayList()
reverseMappingsBySourceUrl.set(sourceIndex, reverseMappings)
}
return reverseMappings
}
private fun isSeparator(charIterator: CharSequenceIterator): Boolean {
if (!charIterator.hasNext()) {
return true
}
val current = charIterator.peek()
return current == ',' || current == ';'
}
interface MutableEntry : MappingEntry {
override var nextGenerated: MappingEntry
}
/**
* Not mapped to a section in the original source.
*/
private data class UnmappedEntry(override val generatedLine: Int, override val generatedColumn: Int) : MappingEntry, MutableEntry {
override val sourceLine = UNMAPPED
override val sourceColumn = UNMAPPED
override var nextGenerated: MappingEntry by notNull()
}
/**
* Mapped to a section in the original source.
*/
private data class UnnamedEntry(override val generatedLine: Int,
override val generatedColumn: Int,
override val source: Int,
override val sourceLine: Int,
override val sourceColumn: Int) : MappingEntry, MutableEntry {
override var nextGenerated: MappingEntry by notNull()
}
/**
* Mapped to a section in the original source, and is associated with a name.
*/
private data class NamedEntry(override val name: String,
override val generatedLine: Int,
override val generatedColumn: Int,
override val source: Int,
override val sourceLine: Int,
override val sourceColumn: Int) : MappingEntry, MutableEntry {
override var nextGenerated: MappingEntry by notNull()
}
// java CharacterIterator is ugly, next() impl, so, we reinvent
private class CharSequenceIterator(private val content: CharSequence) : CharIterator {
private val length = content.length
private var current = 0
override fun next() = content.get(current++)
internal fun peek() = content.get(current)
override fun hasNext() = current < length
}
private class SourceMappingList(mappings: List<MappingEntry>) : MappingList(mappings) {
override fun getLine(mapping: MappingEntry) = mapping.sourceLine
override fun getColumn(mapping: MappingEntry) = mapping.sourceColumn
override val comparator = MAPPING_COMPARATOR_BY_SOURCE_POSITION
}
private class GeneratedMappingList(mappings: List<MappingEntry>) : MappingList(mappings) {
override fun getLine(mapping: MappingEntry) = mapping.generatedLine
override fun getColumn(mapping: MappingEntry) = mapping.generatedColumn
override val comparator = MAPPING_COMPARATOR_BY_GENERATED_POSITION
}
| apache-2.0 | 77d3c10ed8bbcace6b6987d4cfa32af1 | 30.616438 | 153 | 0.656066 | 4.428243 | false | false | false | false |
StepicOrg/stepik-android | app/src/main/java/org/stepik/android/view/latex/ui/widget/LatexView.kt | 1 | 5413 | package org.stepik.android.view.latex.ui.widget
import android.content.Context
import android.text.method.LinkMovementMethod
import android.util.AttributeSet
import android.util.TypedValue
import android.view.View
import android.view.ViewGroup
import android.webkit.WebViewClient
import android.widget.FrameLayout
import android.widget.TextView
import androidx.annotation.IdRes
import androidx.core.content.res.ResourcesCompat
import androidx.core.view.ViewCompat
import androidx.core.view.isVisible
import org.stepic.droid.R
import org.stepic.droid.base.App
import org.stepic.droid.core.ScreenManager
import org.stepik.android.domain.latex.mapper.LatexTextMapper
import org.stepik.android.domain.latex.model.LatexData
import org.stepik.android.view.base.ui.extension.ExternalLinkWebViewClient
import org.stepik.android.view.latex.mapper.LatexWebViewMapper
import org.stepik.android.view.latex.model.TextAttributes
import ru.nobird.android.view.base.ui.extension.inflate
import javax.inject.Inject
class LatexView
@JvmOverloads
constructor(context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0) : FrameLayout(context, attrs, defStyleAttr) {
companion object {
private fun TextView.setAttributes(textAttributes: TextAttributes) {
setTextSize(TypedValue.COMPLEX_UNIT_SP, textAttributes.textSize)
setTextColor(textAttributes.textColor)
highlightColor = textAttributes.textColorHighlight
setTextIsSelectable(textAttributes.textIsSelectable)
typeface = ResourcesCompat.getFont(context, textAttributes.fontResId)
}
}
@Inject
internal lateinit var latexTextMapper: LatexTextMapper
@Inject
internal lateinit var latexWebViewMapper: LatexWebViewMapper
@Inject
internal lateinit var screenManager: ScreenManager
@IdRes
private val textViewId: Int
@IdRes
private val webViewId: Int
lateinit var textView: TextView
private set
lateinit var webView: LatexWebView
private set
var attributes = TextAttributes.fromAttributeSet(context, attrs)
set(value) {
field = value
textView.setAttributes(value)
webView.attributes = value
}
var latexData: LatexData? = null
set(value) {
textView.isVisible = value is LatexData.Text
webView.isVisible = value is LatexData.Web
if (field == value) return
field = value
if (value == null) return
when (value) {
is LatexData.Text ->
textView.text = value.text
is LatexData.Web -> {
webView.text = latexWebViewMapper.mapLatexData(value, webView.attributes)
// TODO Switch to WebViewAssetLoader
/**
* Allow WebView to open file://
*/
webView.settings.allowFileAccess = true
/**
* Kotlin Playground downloads a file with Kotlin versions which generates a mistake, if allowUniversalAccessFromFileURLs is false
*/
webView.settings.allowUniversalAccessFromFileURLs = value.settings.allowUniversalAccessFromFileURLs
}
}
}
var webViewClient: WebViewClient? = null
set(value) {
field = value
if (ViewCompat.isAttachedToWindow(this)) {
webView.webViewClient = requireNotNull(webViewClient)
}
}
init {
App.component().inject(this)
val array = context.obtainStyledAttributes(attrs, R.styleable.LatexView)
try {
val textId = array.getResourceId(R.styleable.LatexView_textViewId, 0)
if (textId == 0) {
textViewId = R.id.latex_textview
inflate(R.layout.layout_latex_textview, attachToRoot = true)
} else {
textViewId = textId
}
val webId = array.getResourceId(R.styleable.LatexView_webViewId, 0)
if (webId == 0) {
webViewId = R.id.latex_webview
inflate(R.layout.layout_latex_webview, attachToRoot = true)
} else {
webViewId = webId
}
} finally {
array.recycle()
}
}
override fun addView(child: View?, index: Int, params: ViewGroup.LayoutParams?) {
when (child?.id) {
textViewId -> {
textView = child as TextView
textView.setAttributes(attributes)
textView.movementMethod = LinkMovementMethod.getInstance()
}
webViewId -> {
webView = child as LatexWebView
webView.attributes = attributes
}
}
super.addView(child, index, params)
}
override fun onAttachedToWindow() {
super.onAttachedToWindow()
webView.onImageClickListener = { screenManager.openImage(context, it) }
webView.webViewClient = webViewClient ?: ExternalLinkWebViewClient(context)
}
override fun onDetachedFromWindow() {
webView.onImageClickListener = null
super.onDetachedFromWindow()
}
fun setText(text: String?) {
latexData = text?.let(latexTextMapper::mapToLatexText)
}
} | apache-2.0 | cc6b992c8f5a3bc673e7d5fea2f748af | 32.419753 | 150 | 0.636616 | 5.025998 | false | false | false | false |
allotria/intellij-community | plugins/gradle/testSources/org/jetbrains/plugins/gradle/importing/GradleSettingScriptBuilder.kt | 4 | 657 | // 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.gradle.importing
import java.util.*
class GradleSettingScriptBuilder(projectName: String) {
private val builder = StringJoiner("\n")
.add("rootProject.name = '$projectName'")
.add("")
fun generate() = builder.toString()
fun withModule(name: String) = apply {
builder.add("include '$name'")
}
fun withFlat(name: String) = apply {
builder.add("includeFlat '$name'")
}
fun withBuild(name: String) = apply {
builder.add("includeBuild '$name'")
}
} | apache-2.0 | 37bdc64439efb9806e33c9cf3d0feb43 | 25.32 | 140 | 0.687976 | 3.842105 | false | false | false | false |
allotria/intellij-community | plugins/git4idea/src/git4idea/ui/branch/dashboard/BranchesDashboardUtil.kt | 1 | 4197 | // Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package git4idea.ui.branch.dashboard
import com.intellij.openapi.components.service
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.project.Project
import com.intellij.vcs.log.impl.VcsProjectLog
import com.intellij.vcs.log.util.exclusiveCommits
import com.intellij.vcs.log.util.findBranch
import com.intellij.vcs.log.visible.filters.VcsLogFilterObject
import git4idea.branch.GitBranchType
import git4idea.repo.GitRepository
import git4idea.repo.GitRepositoryManager
import git4idea.ui.branch.GitBranchManager
import gnu.trove.TIntHashSet
internal object BranchesDashboardUtil {
fun getLocalBranches(project: Project): Set<BranchInfo> {
val localMap = mutableMapOf<String, MutableSet<GitRepository>>()
for (repo in GitRepositoryManager.getInstance(project).repositories) {
for (branch in repo.branches.localBranches) {
localMap.computeIfAbsent(branch.name) { hashSetOf() }.add(repo)
}
val currentBranch = repo.currentBranch
if (currentBranch != null) {
localMap.computeIfAbsent(currentBranch.name) { hashSetOf() }.add(repo)
}
}
val gitBranchManager = project.service<GitBranchManager>()
val local = localMap.map { (branchName, repos) ->
BranchInfo(branchName, true, repos.any { it.currentBranch?.name == branchName },
repos.any { gitBranchManager.isFavorite(GitBranchType.LOCAL, it, branchName) },
repos.toList())
}.toHashSet()
return local
}
fun getRemoteBranches(project: Project): Set<BranchInfo> {
val remoteMap = mutableMapOf<String, MutableList<GitRepository>>()
for (repo in GitRepositoryManager.getInstance(project).repositories) {
for (remoteBranch in repo.branches.remoteBranches) {
remoteMap.computeIfAbsent(remoteBranch.name) { mutableListOf() }.add(repo)
}
}
val gitBranchManager = project.service<GitBranchManager>()
return remoteMap.map { (branchName, repos) ->
BranchInfo(branchName, false, false,
repos.any { gitBranchManager.isFavorite(GitBranchType.REMOTE, it, branchName) },
repos)
}.toHashSet()
}
fun checkIsMyBranchesSynchronously(log: VcsProjectLog,
branchesToCheck: Collection<BranchInfo>,
indicator: ProgressIndicator): Set<BranchInfo> {
val myCommits = findMyCommits(log)
if (myCommits.isNullOrEmpty()) return emptySet()
indicator.isIndeterminate = false
val myBranches = hashSetOf<BranchInfo>()
for ((step, branch) in branchesToCheck.withIndex()) {
indicator.fraction = step.toDouble() / branchesToCheck.size
for (repo in branch.repositories) {
indicator.checkCanceled()
if (isMyBranch(log, branch.branchName, repo, myCommits)) {
myBranches.add(branch)
}
}
}
return myBranches
}
private fun findMyCommits(log: VcsProjectLog): Set<Int> {
val filterByMe = VcsLogFilterObject.fromUserNames(listOf(VcsLogFilterObject.ME), log.dataManager!!)
return log.dataManager!!.index.dataGetter!!.filter(listOf(filterByMe))
}
private fun isMyBranch(log: VcsProjectLog,
branchName: String,
repo: GitRepository,
myCommits: Set<Int>): Boolean {
// branch is "my" if all its exclusive commits are made by me
val exclusiveCommits = findExclusiveCommits(log, branchName, repo) ?: return false
if (exclusiveCommits.isEmpty) return false
for (commit in exclusiveCommits) {
if (!myCommits.contains(commit)) {
return false
}
}
return true
}
private fun findExclusiveCommits(log: VcsProjectLog, branchName: String, repo: GitRepository): TIntHashSet? {
val dataPack = log.dataManager!!.dataPack
val ref = dataPack.findBranch(branchName, repo.root) ?: return null
if (!ref.type.isBranch) return null
return dataPack.exclusiveCommits(ref, dataPack.refsModel, log.dataManager!!.storage)
}
}
| apache-2.0 | 34709eda855b2b9d2e9005f423f19c79 | 38.224299 | 140 | 0.696212 | 4.652993 | false | false | false | false |
DmytroTroynikov/aemtools | common/src/main/kotlin/com/aemtools/common/util/PsiUtil.kt | 1 | 2255 | package com.aemtools.common.util
import com.intellij.lang.Language
import com.intellij.lang.StdLanguages
import com.intellij.openapi.application.runReadAction
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
import com.intellij.psi.PsiReference
import com.intellij.psi.SmartPointerManager
import com.intellij.psi.SmartPsiElementPointer
import com.intellij.psi.util.PsiUtilCore
import com.intellij.psi.xml.XmlFile
import com.intellij.refactoring.rename.RenamePsiElementProcessor
/**
* Psi utility & extension methods
* @author Dmytro_Troynikov
*/
/**
* Get [PsiFile] for specified [Language].
*
* @param language the language
*
* @receiver [PsiFile]
* @return the [PsiFile] for given [Language], *null* in case if no file was found
*/
fun PsiFile.getPsi(language: Language): PsiFile? = viewProvider.getPsi(language)
/**
* Get [PsiFile] for [StdLanguages.HTML] language.
*
* @receiver [PsiFile]
* @return psi file for html language, *null* if no such file available
*/
fun PsiFile.getHtmlFile(): PsiFile? = getPsi(StdLanguages.HTML)
/**
* Get [XmlFile] from current [PsiFile].
*
* @receiver [PsiFile]
* @return psi file for [StdLanguages.XML] language, *null* if no such file available
*/
fun PsiFile.getXmlFile(): XmlFile? = getPsi(StdLanguages.XML) as? XmlFile
/**
* Get [VirtualFile] instance that contain current [PsiElement].
*
* @receiver [PsiElement]
* @see [PsiUtilCore.getVirtualFile]
*
* @return instance of virtual file
*/
fun PsiElement.virtualFile(): VirtualFile? =
PsiUtilCore.getVirtualFile(this)
/**
* Find incoming references (usages) for current element.
*
* @receiver [PsiElement]
*
* @return list of incoming references
*/
fun PsiElement.incomingReferences(): List<PsiReference> = runReadAction {
RenamePsiElementProcessor.forElement(this).findReferences(this)
.toList()
}
/**
* Convert current [PsiElement] into [SmartPsiElementPointer].
*
* @receiver [PsiElement] based item
* @return [SmartPsiElementPointer] pointing to current [PsiElement]
*/
inline fun <reified T : PsiElement> T.toSmartPointer(): SmartPsiElementPointer<T>
= SmartPointerManager.getInstance(project)
.createSmartPsiElementPointer(this)
| gpl-3.0 | 2935361f6d1b369906cf44c1e7b56835 | 27.910256 | 85 | 0.75255 | 4.033989 | false | false | false | false |
android/wear-os-samples | WearTilesKotlin/app/src/main/java/com/example/wear/tiles/tools/WearPreviewDevices.kt | 1 | 1991 | /*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.wear.tiles.tools
import androidx.compose.ui.tooling.preview.Devices
import androidx.compose.ui.tooling.preview.Preview
@Preview(
device = Devices.WEAR_OS_LARGE_ROUND,
showSystemUi = true,
backgroundColor = 0xff000000,
showBackground = true,
group = "Devices - Large Round"
)
@Preview(
device = Devices.WEAR_OS_SMALL_ROUND,
showSystemUi = true,
backgroundColor = 0xff000000,
showBackground = true,
group = "Devices - Small Round"
)
@Preview(
device = Devices.WEAR_OS_SQUARE,
showSystemUi = true,
backgroundColor = 0xff000000,
showBackground = true,
group = "Devices - Square"
)
public annotation class WearPreviewDevices
@Preview(
device = Devices.WEAR_OS_SMALL_ROUND,
showSystemUi = true,
backgroundColor = 0xff000000,
showBackground = true,
group = "Devices - Small Round"
)
public annotation class WearSmallRoundDevicePreview
@Preview(
device = Devices.WEAR_OS_LARGE_ROUND,
showSystemUi = true,
backgroundColor = 0xff000000,
showBackground = true,
group = "Devices - Large Round"
)
public annotation class WearLargeRoundDevicePreview
@Preview(
device = Devices.WEAR_OS_SQUARE,
showSystemUi = true,
backgroundColor = 0xff000000,
showBackground = true,
group = "Devices - Square"
)
public annotation class WearSquareDevicePreview
| apache-2.0 | 87bfed17ed7b4d37c9a3ceaf117aafb7 | 27.855072 | 75 | 0.723757 | 3.98998 | false | false | false | false |
romannurik/muzei | muzei-api/src/main/java/com/google/android/apps/muzei/api/provider/ProviderContract.kt | 1 | 11676 | /*
* Copyright 2018 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.muzei.api.provider
import android.content.ComponentName
import android.content.ContentProviderOperation
import android.content.ContentResolver
import android.content.ContentUris
import android.content.Context
import android.content.OperationApplicationException
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Build
import android.os.RemoteException
import android.provider.BaseColumns
import androidx.annotation.RequiresApi
import java.util.ArrayList
/**
* Contract between Muzei and Muzei Art Providers, containing the definitions for all supported
* URIs and columns as well as helper methods to make it easier to work with the provided data.
*/
public object ProviderContract {
/**
* Retrieve the content URI for the given [MuzeiArtProvider], allowing you to build
* custom queries, inserts, updates, and deletes using a [ContentResolver].
*
* This **does not** check for the validity of the MuzeiArtProvider. You can
* use [PackageManager.resolveContentProvider] passing in the
* authority if you need to confirm the authority is valid.
*
* @param authority The [MuzeiArtProvider] you need a content URI for
* @return The content URI for the [MuzeiArtProvider]
* @see MuzeiArtProvider.contentUri
*/
@JvmStatic
public fun getContentUri(authority: String): Uri {
return Uri.Builder()
.scheme(ContentResolver.SCHEME_CONTENT)
.authority(authority)
.build()
}
/**
* Creates a new [ProviderClient] for accessing the given [MuzeiArtProvider]
* from anywhere in your application.
*
* @param context Context used to construct the ProviderClient.
* @param provider The [MuzeiArtProvider] you need a ProviderClient for.
* @return a [ProviderClient] suitable for accessing the [MuzeiArtProvider].
*/
@JvmStatic
@RequiresApi(Build.VERSION_CODES.KITKAT)
public fun getProviderClient(
context: Context,
provider: Class<out MuzeiArtProvider>
): ProviderClient {
val componentName = ComponentName(context, provider)
val pm = context.packageManager
val authority: String
try {
@Suppress("DEPRECATION")
val info = pm.getProviderInfo(componentName, 0)
authority = info.authority
} catch (e: PackageManager.NameNotFoundException) {
throw IllegalArgumentException(
"Invalid MuzeiArtProvider: $componentName, is your provider disabled?", e)
}
return getProviderClient(context, authority)
}
/**
* Creates a new [ProviderClient] for accessing the given [MuzeiArtProvider]
* from anywhere in your application.
*
* @param context Context used to construct the ProviderClient.
* @param Provider The subclass of [MuzeiArtProvider] you need a ProviderClient for.
* @return a [ProviderClient] suitable for accessing the [MuzeiArtProvider].
*/
@RequiresApi(Build.VERSION_CODES.KITKAT)
public inline fun <reified Provider : MuzeiArtProvider> getProviderClient(
context: Context): ProviderClient {
return getProviderClient(context, Provider::class.java)
}
/**
* Creates a new [ProviderClient] for accessing the given [MuzeiArtProvider]
* from anywhere in your application.
*
* @param context Context used to construct the ProviderClient.
* @param authority The [MuzeiArtProvider] you need a ProviderClient for.
* @return a [ProviderClient] suitable for accessing the [MuzeiArtProvider].
*/
@JvmStatic
@RequiresApi(Build.VERSION_CODES.KITKAT)
public fun getProviderClient(
context: Context,
authority: String): ProviderClient {
val contentUri = Uri.Builder()
.scheme(ContentResolver.SCHEME_CONTENT)
.authority(authority)
.build()
return object : ProviderClient {
override val contentUri: Uri
get() = contentUri
override val lastAddedArtwork: com.google.android.apps.muzei.api.provider.Artwork?
get() = context.contentResolver.query(
contentUri,
null, null, null,
"${BaseColumns._ID} DESC")?.use { data ->
return if (data.moveToFirst())
com.google.android.apps.muzei.api.provider.Artwork.fromCursor(data)
else
null
}
override fun addArtwork(
artwork: com.google.android.apps.muzei.api.provider.Artwork
): Uri? {
val contentResolver = context.contentResolver
return contentResolver.insert(contentUri, artwork.toContentValues())
}
override fun addArtwork(
artwork: Iterable<com.google.android.apps.muzei.api.provider.Artwork>
): List<Uri> {
val contentResolver = context.contentResolver
val operations = ArrayList<ContentProviderOperation>()
for (art in artwork) {
operations.add(ContentProviderOperation.newInsert(contentUri)
.withValues(art.toContentValues())
.build())
}
return try {
val results = contentResolver.applyBatch(authority, operations)
results.mapNotNull { result -> result.uri }
} catch (ignored: OperationApplicationException) {
emptyList()
} catch (ignored: RemoteException) {
emptyList()
}
}
override fun setArtwork(
artwork: com.google.android.apps.muzei.api.provider.Artwork
): Uri? {
val contentResolver = context.contentResolver
val operations = ArrayList<ContentProviderOperation>()
operations.add(ContentProviderOperation.newInsert(contentUri)
.withValues(artwork.toContentValues())
.build())
operations.add(ContentProviderOperation.newDelete(contentUri)
.withSelection("${BaseColumns._ID} != ?", arrayOfNulls(1))
.withSelectionBackReference(0, 0)
.build())
return try {
val results = contentResolver.applyBatch(
authority, operations)
results[0].uri
} catch (e: Exception) {
null
}
}
override fun setArtwork(
artwork: Iterable<com.google.android.apps.muzei.api.provider.Artwork>
): List<Uri> {
val contentResolver = context.contentResolver
val operations = ArrayList<ContentProviderOperation>()
for (art in artwork) {
operations.add(ContentProviderOperation.newInsert(contentUri)
.withValues(art.toContentValues())
.build())
}
val artworkCount = operations.size
val resultUris = ArrayList<Uri>(artworkCount)
// Delete any artwork that was not inserted/update in the above operations
val currentTime = System.currentTimeMillis()
operations.add(ContentProviderOperation.newDelete(contentUri)
.withSelection("${Artwork.DATE_MODIFIED} < ?",
arrayOf(currentTime.toString()))
.build())
try {
val results = contentResolver.applyBatch(authority, operations)
resultUris.addAll(results.take(artworkCount).mapNotNull { result -> result.uri })
} catch (ignored: OperationApplicationException) {
} catch (ignored: RemoteException) {
}
return resultUris
}
}
}
/**
* Constants and helper methods for working with the
* [Artwork][com.google.android.apps.muzei.api.provider.Artwork] associated
* with a [MuzeiArtProvider].
*/
public object Artwork {
/**
* The unique ID of the Artwork, suitable for use with [ContentUris.withAppendedId].
*/
@Suppress("unused", "ObjectPropertyName")
public const val _ID: String = BaseColumns._ID
/**
* The token that uniquely defines the artwork. Any inserts using the same non-null token
* will be considered updates to the existing artwork. Therefore there will always be at
* most one artwork with the same non-null token.
*
* This field **cannot** be changed after the artwork is inserted.
*
* Type: TEXT
*/
public const val TOKEN: String = "token"
/**
* The user-visible title of the artwork
*
* Type: TEXT
*/
public const val TITLE: String = "title"
/**
* The artwork's byline (such as author and date). This is generally used as a secondary
* source of information after the [TITLE].
*
* Type: TEXT
*/
public const val BYLINE: String = "byline"
/**
* The attribution info for the artwork
*
* Type: TEXT
*/
public const val ATTRIBUTION: String = "attribution"
/**
* The persistent URI of the artwork
*
* Type: TEXT (Uri)
*/
public const val PERSISTENT_URI: String = "persistent_uri"
/**
* The web URI of the artwork
*
* Type: TEXT (Uri)
*/
public const val WEB_URI: String = "web_uri"
/**
* The provider specific metadata about the artwork
*
* Type: TEXT
*/
public const val METADATA: String = "metadata"
/**
* Path to the file on disk.
*
* Note that apps may not have filesystem permissions to directly access
* this path. Instead of trying to open this path directly, apps should use
* [ContentResolver.openFileDescriptor][android.content.ContentResolver.openFileDescriptor]
* to gain access.
*
* Type: TEXT
*/
public const val DATA: String = "_data"
/**
* The time the file was added to the provider.
*
* Type: LONG (in milliseconds)
*/
public const val DATE_ADDED: String = "date_added"
/**
* The time the file was last modified.
*
* Type: LONG (in milliseconds)
*/
public const val DATE_MODIFIED: String = "date_modified"
}
} | apache-2.0 | 5f0e85a2838a5d0c32437c0f8b1edaee | 38.853242 | 101 | 0.59087 | 5.410565 | false | false | false | false |
code-helix/slatekit | src/lib/kotlin/slatekit-apis/src/main/kotlin/slatekit/apis/tools/code/TypeInfo.kt | 1 | 5886 | package slatekit.apis.tools.code
import slatekit.context.Context
import slatekit.requests.Request
import slatekit.meta.KTypes
import kotlin.reflect.KClass
import kotlin.reflect.KType
/** Represents type information for the purspose of code generation.
* @param isBasicType : whether this is a number, boolean, String
* @param isCollection : whether this is a list or map
* @param targetType : The target type name used as a parameter input: e.g. "int", "double"
* @param targetTypeName : The target type name used as a return type. For parsing/generic purposes,
* this is the corresponding object type for a type. e.g. Integer for int.
* e.g. "Integer", "Double"
* @param containerType : For collections, the Kotlin class representing the container type. e.g. "List::class", "Map::class"
* @param dataType : The Kotlin class representing the data type.
* @param conversionType : The Kotlin
*/
data class TypeInfo(
val isBasicType: Boolean,
val isCollection: Boolean,
val targetTypes: List<KClass<*>>,
val containerType: KClass<*>? = null,
val targetTypeNameBuilder:((KClass<*>) -> String)? = null
) {
/**
* First type e.g. For most cases
*/
val targetType:KClass<*> = targetTypes.first()
/**
* Converts the target Type name to actual type name
*/
val converter:(KClass<*>) -> String = { cls -> targetTypeNameBuilder?.let { it(cls) } ?: cls.simpleName!! }
/**
* For basic types:
* 1. Basic types: String, Int, Boolean
* 2. Containers : List<String>, Map<String, String>
* 3. Objects : User
*
*/
val targetTypeName: String = converter.invoke(targetType)
/**
* Generates comma delimited lists of the types e.g. String, Int
* Used for List, Map to create type signature as List<String> or Map<String, Int>
*/
val parameterizedNames:String = targetTypes.joinToString { ttype -> converter.invoke(ttype) }
fun returnType():String {
return when {
isList() -> "List<$parameterizedNames>"
isMap() -> "Map<$parameterizedNames>"
isPair() -> "Pair<$parameterizedNames>"
else -> parameterizedNames
}
}
/**
* Generates comma delimited lists of the types e.g. String, Int
* Used for List, Map to create type signature as List<String> or Map<String, Int>
*/
fun parameterizedTypes(suffix:String):String = targetTypes.joinToString { converter.invoke(it) + suffix }
fun isList(): Boolean = containerType == List::class
fun isMap(): Boolean = containerType == Map::class
fun isObject(): Boolean = !isBasicType && !isCollection
fun isPair(): Boolean = isObject() && targetType.simpleName?.startsWith("Pair") ?: false
fun isApplicableForCodeGen(): Boolean {
return !this.isBasicType &&
!this.isCollection &&
this.targetType != Request::class &&
this.targetType != Any::class &&
this.targetType != Context::class
}
fun converterTypeName(): String {
return when {
isList() -> List::class.simpleName!!
isMap() -> Map::class.simpleName!!
isPair() -> Pair::class.simpleName!!
else -> "Single"
}
}
companion object {
val basicTypes:Map<KType, TypeInfo> = mapOf(
// Basic types
KTypes.KStringType to TypeInfo(true, false, listOf(KTypes.KStringClass ), null),
KTypes.KBoolType to TypeInfo(true, false, listOf(KTypes.KBoolClass ), null),
KTypes.KShortType to TypeInfo(true, false, listOf(KTypes.KShortClass ), null),
KTypes.KIntType to TypeInfo(true, false, listOf(KTypes.KIntClass ), null),
KTypes.KLongType to TypeInfo(true, false, listOf(KTypes.KLongClass ), null),
KTypes.KFloatType to TypeInfo(true, false, listOf(KTypes.KFloatClass ), null),
KTypes.KDoubleType to TypeInfo(true, false, listOf(KTypes.KDoubleClass ), null),
KTypes.KDateTimeType to TypeInfo(true, false, listOf(KTypes.KDateTimeClass ), null),
KTypes.KLocalDateType to TypeInfo(true, false, listOf(KTypes.KLocalDateClass ), null),
KTypes.KLocalTimeType to TypeInfo(true, false, listOf(KTypes.KLocalTimeClass ), null),
KTypes.KLocalDateTimeType to TypeInfo(true, false, listOf(KTypes.KLocalDateTimeClass), null),
KTypes.KZonedDateTimeType to TypeInfo(true, false, listOf(KTypes.KZonedDateTimeClass), null),
KTypes.KDocType to TypeInfo(true, false, listOf(KTypes.KDocClass ), null),
KTypes.KVarsType to TypeInfo(true, false, listOf(KTypes.KVarsClass ), null),
KTypes.KSmartValueType to TypeInfo(true, false, listOf(KTypes.KSmartValueClass ), null),
KTypes.KUPIDType to TypeInfo(true, false, listOf(KTypes.KUPIDClass ), null),
KTypes.KUUIDType to TypeInfo(true, false, listOf(KTypes.KUUIDClass ), null),
KTypes.KContentType to TypeInfo(true, false, listOf(KTypes.KContentClass ), null),
KTypes.KDecStringType to TypeInfo(true, false, listOf(KTypes.KDecStringClass ), null),
KTypes.KDecIntType to TypeInfo(true, false, listOf(KTypes.KDecIntClass ), null),
KTypes.KDecLongType to TypeInfo(true, false, listOf(KTypes.KDecLongClass ), null),
KTypes.KDecDoubleType to TypeInfo(true, false, listOf(KTypes.KDecDoubleClass ), null),
KTypes.KAnyType to TypeInfo(false,false, listOf(KTypes.KAnyClass ), null)
)
}
}
| apache-2.0 | 01a3c694ad328f1b8c282e37eb834bcb | 46.088 | 125 | 0.620116 | 4.302632 | false | false | false | false |
code-helix/slatekit | src/lib/kotlin/slatekit/src/main/kotlin/slatekit/docs/DocConstants.kt | 1 | 404 | package slatekit.docs
object DocConstants {
val header = "doc:header"
val import_required = "doc:import_required"
val import_optional = "doc:import_optional"
val import_examples = "doc:import_examples"
val depends = "doc:depends"
val setup = "doc:setup"
val examples = "doc:examples"
val notes = "doc:notes"
val output = "doc:output"
} | apache-2.0 | edf9c9e4ad7e3388b778938aceaef750 | 30.153846 | 47 | 0.616337 | 3.607143 | false | false | false | false |
JuliusKunze/kotlin-native | backend.native/tests/external/codegen/box/javaInterop/generics/allWildcardsOnClass.kt | 2 | 1093 | // TODO: muted automatically, investigate should it be ran for JS or not
// IGNORE_BACKEND: JS, NATIVE
// WITH_RUNTIME
// FILE: JavaClass.java
public class JavaClass {
public static class C extends B {
public OutPair<String, Integer> foo() {
return super.foo();
}
public In<Object> bar() {
return super.bar();
}
}
public static String test() {
A a = new C();
if (!a.foo().getX().equals("OK")) return "fail 1";
if (!a.foo().getY().equals(123)) return "fail 2";
if (!a.bar().make("123").equals("123")) return "fail 3";
return "OK";
}
}
// FILE: main.kt
class OutPair<out X, out Y>(val x: X, val y: Y)
class In<in Z> {
fun make(x: Z): String = x.toString()
}
@JvmSuppressWildcards(suppress = false)
interface A {
fun foo(): OutPair<CharSequence, Number>
fun bar(): In<String>
}
abstract class B : A {
override fun foo(): OutPair<String, Int> = OutPair("OK", 123)
override fun bar(): In<Any> = In()
}
fun box(): String {
return JavaClass.test();
}
| apache-2.0 | 9358d97f8a3f8d13a39bddd6440824a2 | 20.431373 | 72 | 0.570906 | 3.469841 | false | false | false | false |
JuliusKunze/kotlin-native | backend.native/tests/external/stdlib/collections/MapTest/countBy.kt | 2 | 312 | import kotlin.test.*
fun box() {
val map = mapOf(Pair("b", 3), Pair("c", 2), Pair("a", 2))
assertEquals(3, map.count())
val filteredByKey = map.count { it.key == "b" }
assertEquals(1, filteredByKey)
val filteredByValue = map.count { it.value == 2 }
assertEquals(2, filteredByValue)
}
| apache-2.0 | b06ba8d605512aeb895b5d87dec45e76 | 23 | 61 | 0.608974 | 3.284211 | false | true | false | false |
peervalhoegen/SudoQ | sudoq-app/sudoqmodel/src/main/kotlin/de/sudoq/model/solverGenerator/solver/helper/LeftoverNoteHelper.kt | 1 | 2128 | package de.sudoq.model.solverGenerator.solver.helper
import de.sudoq.model.solverGenerator.solution.LeftoverNoteDerivation
import de.sudoq.model.solverGenerator.solver.SolverSudoku
import de.sudoq.model.solvingAssistant.HintTypes
import de.sudoq.model.sudoku.CandidateSet
import de.sudoq.model.sudoku.Constraint
/**
* @param complexity desired complexity for the final sudoku. Must be `>= 0`.
*/
open class LeftoverNoteHelper(sudoku: SolverSudoku, complexity: Int) :
SolveHelper(sudoku, complexity) {
override fun update(buildDerivation: Boolean): Boolean {
var foundOne = false
for (c in sudoku.sudokuType!!) if (c.hasUniqueBehavior() && hasLeftoverNotes(c)) {
foundOne = true
val leftover = getLeftoverNote(c)
deleteNote(c, leftover)
if (buildDerivation) {
derivation = LeftoverNoteDerivation(c, leftover)
}
break
}
return foundOne
}
protected fun hasLeftoverNotes(c: Constraint): Boolean {
val filled = CandidateSet()
val notes = CandidateSet()
for (p in c) {
if (sudoku.getCell(p)!!.isNotSolved)
notes.or(sudoku.getCurrentCandidates(p)) //collect all notes
else
filled.set(sudoku.getCell(p)!!.currentValue) //collect all entered solution
}
return filled.hasCommonElement(notes)
}
private fun getLeftoverNote(c: Constraint): Int {
val filled = CandidateSet()
val notes = CandidateSet()
for (p in c) {
if (sudoku.getCell(p)!!.isNotSolved)
notes.or(sudoku.getCurrentCandidates(p))
else
filled.set(sudoku.getCell(p)!!.currentValue)
}
filled.and(notes)
return filled.nextSetBit(0)
}
private fun deleteNote(c: Constraint, note: Int) {
for (p in c)
if (sudoku.getCell(p)!!.isNotSolved && sudoku.getCell(p)!!.isNoteSet(note))
sudoku.getCurrentCandidates(p).clear(note)
}
init {
hintType = HintTypes.LeftoverNote
}
} | gpl-3.0 | b4d29c5e8061eee1262d556c71cc7a6b | 32.793651 | 91 | 0.62453 | 4.247505 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/j2k/new/tests/testData/newJ2k/detectProperties/GetterSetterUsagesShadowing.kt | 9 | 755 | class A {
var foo: String? = null
fun g1(foo: String): Boolean {
return this.foo == foo
}
fun g2(foo: String): Boolean {
return this.foo == foo
}
fun g3(foo: String, other: A): Boolean {
return other.foo == foo
}
fun g4(foo: String?): Boolean {
return this.foo.equals(foo, ignoreCase = true)
}
fun g5(foo: String?): Boolean {
return this.foo.equals(foo, ignoreCase = true)
}
fun g6(foo: String?, other: A): Boolean {
return other.foo.equals(foo, ignoreCase = true)
}
fun s1(foo: String?) {
this.foo = foo
}
fun s2(foo: String?) {
this.foo = foo
}
fun s3() {
val foo = ""
this.foo = foo
}
}
| apache-2.0 | be04a4cf6cbe92350b56718240469550 | 17.875 | 55 | 0.512583 | 3.463303 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/loopToCallChain/UseWithIndexIntention.kt | 4 | 2174 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.intentions.loopToCallChain
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.util.TextRange
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.inspections.IntentionBasedInspection
import org.jetbrains.kotlin.idea.intentions.SelfTargetingRangeIntention
import org.jetbrains.kotlin.psi.KtBlockExpression
import org.jetbrains.kotlin.psi.KtForExpression
import org.jetbrains.kotlin.psi.KtPsiFactory
import org.jetbrains.kotlin.psi.createExpressionByPattern
@Suppress("DEPRECATION")
class UseWithIndexInspection : IntentionBasedInspection<KtForExpression>(UseWithIndexIntention::class)
class UseWithIndexIntention : SelfTargetingRangeIntention<KtForExpression>(
KtForExpression::class.java,
KotlinBundle.lazyMessage("use.withindex.instead.of.manual.index.increment")
) {
override fun applicabilityRange(element: KtForExpression): TextRange? =
if (matchIndexToIntroduce(element, reformat = false) != null) element.forKeyword.textRange else null
override fun applyTo(element: KtForExpression, editor: Editor?) {
val (indexVariable, initializationStatement, incrementExpression) = matchIndexToIntroduce(element, reformat = true)!!
val factory = KtPsiFactory(element)
val loopRange = element.loopRange!!
val loopParameter = element.loopParameter!!
val newLoopRange = factory.createExpressionByPattern("$0.withIndex()", loopRange)
loopRange.replace(newLoopRange)
val multiParameter = (factory.createExpressionByPattern(
"for(($0, $1) in x){}",
indexVariable.nameAsSafeName,
loopParameter.text
) as KtForExpression).loopParameter!!
loopParameter.replace(multiParameter)
initializationStatement.delete()
if (incrementExpression.parent is KtBlockExpression) {
incrementExpression.delete()
} else {
removePlusPlus(incrementExpression, true)
}
}
} | apache-2.0 | 3cbdb3a15510f415d82e9f880fe2b2f6 | 43.387755 | 158 | 0.75713 | 5.032407 | false | false | false | false |
smmribeiro/intellij-community | platform/configuration-store-impl/src/ComponentInfo.kt | 12 | 3351 | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.configurationStore
import com.intellij.openapi.components.*
import com.intellij.openapi.util.ModificationTracker
import com.intellij.util.ThreeState
import java.util.concurrent.TimeUnit
internal fun createComponentInfo(component: Any, stateSpec: State?, serviceDescriptor: ServiceDescriptor?): ComponentInfo {
val result = when (component) {
is PersistentStateComponentWithModificationTracker<*> -> ComponentWithStateModificationTrackerInfo(component, stateSpec, serviceDescriptor?.configurationSchemaKey)
is ModificationTracker -> ComponentWithModificationTrackerInfo(component, stateSpec, serviceDescriptor?.configurationSchemaKey)
else -> ComponentInfoImpl(component, stateSpec)
}
if (stateSpec != null && stateSpec.storages.isNotEmpty() && stateSpec.storages.all { it.deprecated || isUseSaveThreshold(it) }) {
result.lastSaved = TimeUnit.MILLISECONDS.toSeconds(System.currentTimeMillis()).toInt()
}
return result
}
private fun isUseSaveThreshold(storage: Storage): Boolean {
return storage.useSaveThreshold != ThreeState.NO && getEffectiveRoamingType(storage.roamingType, storage.path) === RoamingType.DISABLED
}
abstract class ComponentInfo {
open val configurationSchemaKey: String?
get() = null
abstract val component: Any
abstract val stateSpec: State?
abstract val lastModificationCount: Long
abstract val currentModificationCount: Long
abstract val isModificationTrackingSupported: Boolean
var lastSaved: Int = -1
var affectedPropertyNames: List<String> = emptyList()
open fun updateModificationCount(newCount: Long) {
}
}
internal class ComponentInfoImpl(override val component: Any, override val stateSpec: State?) : ComponentInfo() {
override val isModificationTrackingSupported = false
override val lastModificationCount: Long
get() = -1
override val currentModificationCount: Long
get() = -1
}
private abstract class ModificationTrackerAwareComponentInfo : ComponentInfo() {
final override val isModificationTrackingSupported = true
abstract override var lastModificationCount: Long
final override fun updateModificationCount(newCount: Long) {
lastModificationCount = newCount
}
}
private class ComponentWithStateModificationTrackerInfo(override val component: PersistentStateComponentWithModificationTracker<*>,
override val stateSpec: State?,
override val configurationSchemaKey: String?) : ModificationTrackerAwareComponentInfo() {
override val currentModificationCount: Long
get() = component.stateModificationCount
override var lastModificationCount = currentModificationCount
}
private class ComponentWithModificationTrackerInfo(override val component: ModificationTracker,
override val stateSpec: State?,
override val configurationSchemaKey: String?) : ModificationTrackerAwareComponentInfo() {
override val currentModificationCount: Long
get() = component.modificationCount
override var lastModificationCount = currentModificationCount
} | apache-2.0 | abc78a537aeb657dcbd82893d74761c2 | 39.878049 | 167 | 0.752313 | 5.708688 | false | true | false | false |
smmribeiro/intellij-community | platform/platform-impl/src/com/intellij/openapi/progress/impl/PlatformTaskSupport.kt | 1 | 3997 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.openapi.progress.impl
import com.intellij.openapi.application.EDT
import com.intellij.openapi.progress.*
import com.intellij.openapi.progress.util.AbstractProgressIndicatorExBase
import com.intellij.openapi.progress.util.ProgressIndicatorBase
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.NlsContexts.ProgressTitle
import com.intellij.openapi.wm.ex.IdeFrameEx
import com.intellij.openapi.wm.ex.ProgressIndicatorEx
import com.intellij.openapi.wm.ex.StatusBarEx
import com.intellij.openapi.wm.ex.WindowManagerEx
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.collect
internal class PlatformTaskSupport : TaskSupport {
override fun taskCancellationNonCancellableInternal(): TaskCancellation = NonCancellableTaskCancellation
override fun taskCancellationCancellableInternal(): TaskCancellation.Cancellable = defaultCancellable
override suspend fun <T> withBackgroundProgressIndicatorInternal(
project: Project,
title: @ProgressTitle String,
cancellation: TaskCancellation,
action: suspend CoroutineScope.() -> T
): T = coroutineScope {
val sink = FlowProgressSink()
val showIndicatorJob = showIndicator(project, taskInfo(title, cancellation), sink.stateFlow)
try {
withContext(sink.asContextElement(), action)
}
finally {
showIndicatorJob.cancel()
}
}
}
private fun CoroutineScope.showIndicator(
project: Project,
taskInfo: TaskInfo,
stateFlow: Flow<ProgressState>,
): Job {
return launch(Dispatchers.IO) {
delay(300L) // see com.intellij.find.actions.ShowUsagesAction.ourPopupDelayTimeout
val indicator = coroutineCancellingIndicator([email protected]) // cancel the parent job from UI
indicator.start()
try {
val indicatorAdded = withContext(Dispatchers.EDT) {
showIndicatorInUI(project, taskInfo, indicator)
}
if (indicatorAdded) {
indicator.updateFromSink(stateFlow)
}
}
finally {
indicator.stop()
indicator.finish(taskInfo)
}
}
}
/**
* @return an indicator which cancels the given [job] when it's cancelled
*/
private fun coroutineCancellingIndicator(job: Job): ProgressIndicatorEx {
val indicator = ProgressIndicatorBase()
indicator.addStateDelegate(object : AbstractProgressIndicatorExBase() {
override fun cancel() {
job.cancel()
super.cancel()
}
})
return indicator
}
/**
* Asynchronously updates the indicator [text][ProgressIndicator.setText],
* [text2][ProgressIndicator.setText2], and [fraction][ProgressIndicator.setFraction] from the [stateFlow].
*/
private suspend fun ProgressIndicatorEx.updateFromSink(stateFlow: Flow<ProgressState>): Nothing {
stateFlow.collect { state: ProgressState ->
text = state.text
text2 = state.details
if (state.fraction >= 0.0) {
// first fraction update makes the indicator determinate
isIndeterminate = false
}
fraction = state.fraction
}
error("collect call must be cancelled")
}
private fun showIndicatorInUI(project: Project, taskInfo: TaskInfo, indicator: ProgressIndicatorEx): Boolean {
val frameEx: IdeFrameEx = WindowManagerEx.getInstanceEx().findFrameHelper(project) ?: return false
val statusBar = frameEx.statusBar as? StatusBarEx ?: return false
statusBar.addProgress(indicator, taskInfo)
return true
}
private fun taskInfo(title: @ProgressTitle String, cancellation: TaskCancellation): TaskInfo = object : TaskInfo {
override fun getTitle(): String = title
override fun isCancellable(): Boolean = cancellation is CancellableTaskCancellation
override fun getCancelText(): String? = (cancellation as? CancellableTaskCancellation)?.buttonText
override fun getCancelTooltipText(): String? = (cancellation as? CancellableTaskCancellation)?.tooltipText
}
| apache-2.0 | 2d8edad83c3fb0a3b0893abcf79b25e1 | 36.009259 | 122 | 0.762322 | 4.568 | false | false | false | false |
google/intellij-community | platform/workspaceModel/storage/gen/com/intellij/workspaceModel/storage/bridgeEntities/api/ArtifactsOrderEntityImpl.kt | 1 | 7441 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.workspaceModel.storage.bridgeEntities.api
import com.intellij.workspaceModel.storage.*
import com.intellij.workspaceModel.storage.EntityInformation
import com.intellij.workspaceModel.storage.EntitySource
import com.intellij.workspaceModel.storage.EntityStorage
import com.intellij.workspaceModel.storage.GeneratedCodeApiVersion
import com.intellij.workspaceModel.storage.GeneratedCodeImplVersion
import com.intellij.workspaceModel.storage.ModifiableWorkspaceEntity
import com.intellij.workspaceModel.storage.MutableEntityStorage
import com.intellij.workspaceModel.storage.WorkspaceEntity
import com.intellij.workspaceModel.storage.impl.ConnectionId
import com.intellij.workspaceModel.storage.impl.ModifiableWorkspaceEntityBase
import com.intellij.workspaceModel.storage.impl.UsedClassesCollector
import com.intellij.workspaceModel.storage.impl.WorkspaceEntityBase
import com.intellij.workspaceModel.storage.impl.WorkspaceEntityData
import com.intellij.workspaceModel.storage.impl.containers.MutableWorkspaceList
import com.intellij.workspaceModel.storage.impl.containers.toMutableWorkspaceList
import org.jetbrains.deft.ObjBuilder
import org.jetbrains.deft.Type
import org.jetbrains.deft.annotations.Child
@GeneratedCodeApiVersion(1)
@GeneratedCodeImplVersion(1)
open class ArtifactsOrderEntityImpl(val dataSource: ArtifactsOrderEntityData) : ArtifactsOrderEntity, WorkspaceEntityBase() {
companion object {
val connections = listOf<ConnectionId>(
)
}
override val orderOfArtifacts: List<String>
get() = dataSource.orderOfArtifacts
override fun connectionIdList(): List<ConnectionId> {
return connections
}
class Builder(val result: ArtifactsOrderEntityData?) : ModifiableWorkspaceEntityBase<ArtifactsOrderEntity>(), ArtifactsOrderEntity.Builder {
constructor() : this(ArtifactsOrderEntityData())
override fun applyToBuilder(builder: MutableEntityStorage) {
if (this.diff != null) {
if (existsInBuilder(builder)) {
this.diff = builder
return
}
else {
error("Entity ArtifactsOrderEntity is already created in a different builder")
}
}
this.diff = builder
this.snapshot = builder
addToBuilder()
this.id = getEntityData().createEntityId()
// Process linked entities that are connected without a builder
processLinkedEntities(builder)
checkInitialization() // TODO uncomment and check failed tests
}
fun checkInitialization() {
val _diff = diff
if (!getEntityData().isEntitySourceInitialized()) {
error("Field WorkspaceEntity#entitySource should be initialized")
}
if (!getEntityData().isOrderOfArtifactsInitialized()) {
error("Field ArtifactsOrderEntity#orderOfArtifacts should be initialized")
}
}
override fun connectionIdList(): List<ConnectionId> {
return connections
}
// Relabeling code, move information from dataSource to this builder
override fun relabel(dataSource: WorkspaceEntity, parents: Set<WorkspaceEntity>?) {
dataSource as ArtifactsOrderEntity
this.entitySource = dataSource.entitySource
this.orderOfArtifacts = dataSource.orderOfArtifacts.toMutableList()
if (parents != null) {
}
}
override var entitySource: EntitySource
get() = getEntityData().entitySource
set(value) {
checkModificationAllowed()
getEntityData().entitySource = value
changedProperty.add("entitySource")
}
private val orderOfArtifactsUpdater: (value: List<String>) -> Unit = { value ->
changedProperty.add("orderOfArtifacts")
}
override var orderOfArtifacts: MutableList<String>
get() {
val collection_orderOfArtifacts = getEntityData().orderOfArtifacts
if (collection_orderOfArtifacts !is MutableWorkspaceList) return collection_orderOfArtifacts
collection_orderOfArtifacts.setModificationUpdateAction(orderOfArtifactsUpdater)
return collection_orderOfArtifacts
}
set(value) {
checkModificationAllowed()
getEntityData().orderOfArtifacts = value
orderOfArtifactsUpdater.invoke(value)
}
override fun getEntityData(): ArtifactsOrderEntityData = result ?: super.getEntityData() as ArtifactsOrderEntityData
override fun getEntityClass(): Class<ArtifactsOrderEntity> = ArtifactsOrderEntity::class.java
}
}
class ArtifactsOrderEntityData : WorkspaceEntityData<ArtifactsOrderEntity>() {
lateinit var orderOfArtifacts: MutableList<String>
fun isOrderOfArtifactsInitialized(): Boolean = ::orderOfArtifacts.isInitialized
override fun wrapAsModifiable(diff: MutableEntityStorage): ModifiableWorkspaceEntity<ArtifactsOrderEntity> {
val modifiable = ArtifactsOrderEntityImpl.Builder(null)
modifiable.allowModifications {
modifiable.diff = diff
modifiable.snapshot = diff
modifiable.id = createEntityId()
modifiable.entitySource = this.entitySource
}
modifiable.changedProperty.clear()
return modifiable
}
override fun createEntity(snapshot: EntityStorage): ArtifactsOrderEntity {
return getCached(snapshot) {
val entity = ArtifactsOrderEntityImpl(this)
entity.entitySource = entitySource
entity.snapshot = snapshot
entity.id = createEntityId()
entity
}
}
override fun clone(): ArtifactsOrderEntityData {
val clonedEntity = super.clone()
clonedEntity as ArtifactsOrderEntityData
clonedEntity.orderOfArtifacts = clonedEntity.orderOfArtifacts.toMutableWorkspaceList()
return clonedEntity
}
override fun getEntityInterface(): Class<out WorkspaceEntity> {
return ArtifactsOrderEntity::class.java
}
override fun serialize(ser: EntityInformation.Serializer) {
}
override fun deserialize(de: EntityInformation.Deserializer) {
}
override fun createDetachedEntity(parents: List<WorkspaceEntity>): WorkspaceEntity {
return ArtifactsOrderEntity(orderOfArtifacts, entitySource) {
}
}
override fun getRequiredParents(): List<Class<out WorkspaceEntity>> {
val res = mutableListOf<Class<out WorkspaceEntity>>()
return res
}
override fun equals(other: Any?): Boolean {
if (other == null) return false
if (this::class != other::class) return false
other as ArtifactsOrderEntityData
if (this.entitySource != other.entitySource) return false
if (this.orderOfArtifacts != other.orderOfArtifacts) return false
return true
}
override fun equalsIgnoringEntitySource(other: Any?): Boolean {
if (other == null) return false
if (this::class != other::class) return false
other as ArtifactsOrderEntityData
if (this.orderOfArtifacts != other.orderOfArtifacts) return false
return true
}
override fun hashCode(): Int {
var result = entitySource.hashCode()
result = 31 * result + orderOfArtifacts.hashCode()
return result
}
override fun hashCodeIgnoringEntitySource(): Int {
var result = javaClass.hashCode()
result = 31 * result + orderOfArtifacts.hashCode()
return result
}
override fun collectClassUsagesData(collector: UsedClassesCollector) {
this.orderOfArtifacts?.let { collector.add(it::class.java) }
collector.sameForAllEntities = false
}
}
| apache-2.0 | 25ff3afbad2d7051018ee1bb25ebabd4 | 33.934272 | 142 | 0.748555 | 5.67582 | false | false | false | false |
cout970/Modeler | src/main/kotlin/com/cout970/reactive/dsl/Event.kt | 1 | 3701 | @file:Suppress("UNCHECKED_CAST")
package com.cout970.reactive.dsl
import com.cout970.reactive.core.Listener
import com.cout970.reactive.core.RBuilder
import org.liquidengine.legui.component.Component
import org.liquidengine.legui.event.*
fun RBuilder.onClick(func: (MouseClickEvent<Component>) -> Unit) {
listeners.add(Listener(MouseClickEvent::class.java as Class<MouseClickEvent<Component>>) {
if (it.isClick()) func(it)
})
}
fun RBuilder.onPress(func: (MouseClickEvent<Component>) -> Unit) {
listeners.add(Listener(MouseClickEvent::class.java as Class<MouseClickEvent<Component>>) {
if (it.isPress()) func(it)
})
}
fun RBuilder.onRelease(func: (MouseClickEvent<Component>) -> Unit) {
listeners.add(Listener(MouseClickEvent::class.java as Class<MouseClickEvent<Component>>) {
if (it.isRelease()) func(it)
})
}
fun RBuilder.onCharTyped(func: (CharEvent<Component>) -> Unit) {
listeners.add(Listener(CharEvent::class.java as Class<CharEvent<Component>>, func))
}
fun RBuilder.onCursorEnter(func: (CursorEnterEvent<Component>) -> Unit) {
listeners.add(Listener(CursorEnterEvent::class.java as Class<CursorEnterEvent<Component>>, func))
}
fun RBuilder.onFocus(func: (FocusEvent<Component>) -> Unit) {
listeners.add(Listener(FocusEvent::class.java as Class<FocusEvent<Component>>, func))
}
fun RBuilder.onKey(func: (KeyEvent<Component>) -> Unit) {
listeners.add(Listener(KeyEvent::class.java as Class<KeyEvent<Component>>, func))
}
fun RBuilder.onDrag(func: (MouseDragEvent<Component>) -> Unit) {
listeners.add(Listener(MouseDragEvent::class.java as Class<MouseDragEvent<Component>>, func))
}
fun RBuilder.onScroll(func: (ScrollEvent<Component>) -> Unit) {
listeners.add(Listener(ScrollEvent::class.java as Class<ScrollEvent<Component>>, func))
}
fun Component.onClick(func: (MouseClickEvent<Component>) -> Unit) {
listenerMap.addListener(MouseClickEvent::class.java as Class<MouseClickEvent<Component>>) {
if (it.isClick()) func(it)
}
}
fun Component.onPress(func: (MouseClickEvent<Component>) -> Unit) {
listenerMap.addListener(MouseClickEvent::class.java as Class<MouseClickEvent<Component>>) {
if (it.isPress()) func(it)
}
}
fun Component.onRelease(func: (MouseClickEvent<Component>) -> Unit) {
listenerMap.addListener(MouseClickEvent::class.java as Class<MouseClickEvent<Component>>) {
if (it.isRelease()) func(it)
}
}
fun Component.onCharTyped(func: (CharEvent<Component>) -> Unit) {
listenerMap.addListener(CharEvent::class.java as Class<CharEvent<Component>>, func)
}
fun Component.onCursorEnter(func: (CursorEnterEvent<Component>) -> Unit) {
listenerMap.addListener(CursorEnterEvent::class.java as Class<CursorEnterEvent<Component>>, func)
}
fun Component.onFocus(func: (FocusEvent<Component>) -> Unit) {
listenerMap.addListener(FocusEvent::class.java as Class<FocusEvent<Component>>, func)
}
fun Component.onKey(func: (KeyEvent<Component>) -> Unit) {
listenerMap.addListener(KeyEvent::class.java as Class<KeyEvent<Component>>, func)
}
fun Component.onDrag(func: (MouseDragEvent<Component>) -> Unit) {
listenerMap.addListener(MouseDragEvent::class.java as Class<MouseDragEvent<Component>>, func)
}
fun Component.onScroll(func: (ScrollEvent<Component>) -> Unit) {
listenerMap.addListener(ScrollEvent::class.java as Class<ScrollEvent<Component>>, func)
}
inline fun MouseClickEvent<*>.isClick() = action == MouseClickEvent.MouseClickAction.CLICK
inline fun MouseClickEvent<*>.isPress() = action == MouseClickEvent.MouseClickAction.PRESS
inline fun MouseClickEvent<*>.isRelease() = action == MouseClickEvent.MouseClickAction.RELEASE | gpl-3.0 | 7abbbd8b4b3e04d0f32fb709838a96a1 | 37.164948 | 101 | 0.740881 | 3.847193 | false | false | false | false |
mdaniel/intellij-community | platform/vcs-impl/src/com/intellij/vcs/commit/SingleChangeListCommitter.kt | 5 | 4578 | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.vcs.commit
import com.intellij.openapi.application.ApplicationManager.getApplication
import com.intellij.openapi.application.ModalityState
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.Messages.getQuestionIcon
import com.intellij.openapi.vcs.VcsBundle.message
import com.intellij.openapi.vcs.VcsConfiguration
import com.intellij.openapi.vcs.VcsShowConfirmationOption
import com.intellij.openapi.vcs.changes.*
import com.intellij.openapi.vcs.changes.actions.MoveChangesToAnotherListAction
import com.intellij.openapi.vcs.changes.ui.ChangelistMoveOfferDialog
import com.intellij.util.concurrency.annotations.RequiresEdt
import com.intellij.util.ui.ConfirmationDialog.requestForConfirmation
import org.jetbrains.annotations.Nls
class ChangeListCommitState(val changeList: LocalChangeList, val changes: List<Change>, val commitMessage: String) {
internal fun copy(commitMessage: String): ChangeListCommitState =
if (this.commitMessage == commitMessage) this else ChangeListCommitState(changeList, changes, commitMessage)
}
open class SingleChangeListCommitter(
project: Project,
private val commitState: ChangeListCommitState,
commitContext: CommitContext,
localHistoryActionName: @Nls String,
private val isDefaultChangeListFullyIncluded: Boolean
) : LocalChangesCommitter(project, commitState.changes, commitState.commitMessage, commitContext, localHistoryActionName) {
private val changeList get() = commitState.changeList
override fun onFailure() {
getApplication().invokeLater(Runnable {
val failedCommitState = ChangeListCommitState(changeList, failedToCommitChanges, commitMessage)
moveToFailedList(project, failedCommitState, message("commit.dialog.failed.commit.template", changeList.name))
}, ModalityState.defaultModalityState(), project.disposed)
}
override fun afterRefreshChanges() {
if (isSuccess) {
updateChangeListAfterRefresh()
}
super.afterRefreshChanges()
}
private fun updateChangeListAfterRefresh() {
val changeListManager = ChangeListManagerImpl.getInstanceImpl(project)
val listName = changeList.name
val localList = changeListManager.findChangeList(listName) ?: return
changeListManager.editChangeListData(listName, null)
if (!localList.isDefault) {
changeListManager.scheduleAutomaticEmptyChangeListDeletion(localList)
}
else {
val changes = localList.changes
if (configuration.OFFER_MOVE_TO_ANOTHER_CHANGELIST_ON_PARTIAL_COMMIT && !changes.isEmpty() && isDefaultChangeListFullyIncluded) {
val dialog = ChangelistMoveOfferDialog(configuration)
if (dialog.showAndGet()) {
MoveChangesToAnotherListAction.askAndMove(project, changes, emptyList())
}
}
}
}
companion object {
@JvmStatic
@RequiresEdt
fun moveToFailedList(project: Project, commitState: ChangeListCommitState, newChangeListName: String) {
// No need to move since we'll get exactly the same changelist.
val failedChanges = commitState.changes
if (failedChanges.containsAll(commitState.changeList.changes)) return
val configuration = VcsConfiguration.getInstance(project)
if (configuration.MOVE_TO_FAILED_COMMIT_CHANGELIST != VcsShowConfirmationOption.Value.DO_ACTION_SILENTLY) {
val option = object : VcsShowConfirmationOption {
override fun getValue(): VcsShowConfirmationOption.Value = configuration.MOVE_TO_FAILED_COMMIT_CHANGELIST
override fun setValue(value: VcsShowConfirmationOption.Value) {
configuration.MOVE_TO_FAILED_COMMIT_CHANGELIST = value
}
override fun isPersistent(): Boolean = true
}
val result = requestForConfirmation(option, project, message("commit.failed.confirm.prompt"),
message("commit.failed.confirm.title"), getQuestionIcon())
if (!result) return
}
val changeListManager = ChangeListManager.getInstance(project)
var index = 1
var failedListName = newChangeListName
while (changeListManager.findChangeList(failedListName) != null) {
index++
failedListName = "$newChangeListName ($index)"
}
val failedList = changeListManager.addChangeList(failedListName, commitState.commitMessage)
changeListManager.moveChangesTo(failedList, *failedChanges.toTypedArray())
}
}
} | apache-2.0 | 06d1fa015edfb8ad13b30f257584c32f | 42.609524 | 140 | 0.757973 | 5.12654 | false | true | false | false |
idea4bsd/idea4bsd | platform/testFramework/src/com/intellij/testFramework/TemporaryDirectory.kt | 10 | 3284 | /*
* 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.testFramework
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.util.io.FileUtilRt
import com.intellij.openapi.vfs.LocalFileSystem
import com.intellij.openapi.vfs.VfsUtil
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.openapi.vfs.refreshVfs
import com.intellij.util.SmartList
import com.intellij.util.io.createDirectories
import com.intellij.util.io.delete
import com.intellij.util.io.exists
import com.intellij.util.io.systemIndependentPath
import com.intellij.util.lang.CompoundRuntimeException
import org.junit.rules.ExternalResource
import org.junit.runner.Description
import org.junit.runners.model.Statement
import java.io.IOException
import java.nio.file.Path
import java.nio.file.Paths
import kotlin.properties.Delegates
class TemporaryDirectory : ExternalResource() {
private val paths = SmartList<Path>()
private var sanitizedName: String by Delegates.notNull()
override fun apply(base: Statement, description: Description): Statement {
sanitizedName = FileUtil.sanitizeFileName(description.methodName, false)
return super.apply(base, description)
}
override fun after() {
val errors = SmartList<Throwable>()
for (path in paths) {
try {
path.delete()
}
catch (e: Throwable) {
errors.add(e)
}
}
CompoundRuntimeException.throwIfNotEmpty(errors)
paths.clear()
}
fun newPath(directoryName: String? = null, refreshVfs: Boolean = false): Path {
val path = generatePath(directoryName)
if (refreshVfs) {
path.refreshVfs()
}
return path
}
private fun generatePath(suffix: String?): Path {
var fileName = sanitizedName
if (suffix != null) {
fileName += "_$suffix"
}
val path = generateTemporaryPath(fileName)
paths.add(path)
return path
}
fun newVirtualDirectory(directoryName: String? = null): VirtualFile {
val path = generatePath(directoryName)
path.createDirectories()
val virtualFile = LocalFileSystem.getInstance().refreshAndFindFileByPath(path.systemIndependentPath)
VfsUtil.markDirtyAndRefresh(false, true, true, virtualFile)
return virtualFile!!
}
}
fun generateTemporaryPath(fileName: String?): Path {
val tempDirectory = Paths.get(FileUtilRt.getTempDirectory())
var path = tempDirectory.resolve(fileName)
var i = 0
while (path.exists() && i < 9) {
path = tempDirectory.resolve("${fileName}_$i")
i++
}
if (path.exists()) {
throw IOException("Cannot generate unique random path")
}
return path
}
fun VirtualFile.writeChild(relativePath: String, data: String) = VfsTestUtil.createFile(this, relativePath, data) | apache-2.0 | 45721f80aa99c00daed4b0a88c816a0f | 30.285714 | 113 | 0.738124 | 4.326746 | false | false | false | false |
Zhouzhouzhou/AndroidDemo | app/src/main/java/com/zhou/android/ui/FocusDrawView.kt | 1 | 2444 | package com.zhou.android.ui
import android.animation.Animator
import android.animation.AnimatorSet
import android.animation.ObjectAnimator
import android.animation.ValueAnimator
import android.content.Context
import android.graphics.Bitmap
import android.util.AttributeSet
import android.view.View
import android.view.animation.LinearInterpolator
import android.widget.RelativeLayout
import com.zhou.android.R
import kotlinx.android.synthetic.main.layout_focus_draw.view.*
/**
* Created by mxz on 2019/9/3.
*/
class FocusDrawView : RelativeLayout {
constructor(context: Context) : this(context, null)
constructor(context: Context, attrs: AttributeSet?) : this(context, attrs, 0)
constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr)
private val animator: AnimatorSet
private val rotation: ObjectAnimator
init {
inflate(context, R.layout.layout_focus_draw, this)
rotation = ObjectAnimator.ofFloat(focus, "rotation", 0f, 360f).apply {
duration = 2200
repeatCount = ValueAnimator.INFINITE
interpolator = LinearInterpolator()
}
animator = AnimatorSet().apply {
addListener(object : Animator.AnimatorListener {
override fun onAnimationRepeat(animation: Animator?) {
}
override fun onAnimationEnd(animation: Animator?) {
circleView.innerRadius = 500f
rotation.start()
}
override fun onAnimationCancel(animation: Animator?) {
}
override fun onAnimationStart(animation: Animator?) {
focus.visibility = View.VISIBLE
}
})
duration = 1200
interpolator = LinearInterpolator()
}
animator.play(ObjectAnimator.ofFloat(focus, "scaleX", 0.2f, 1f))
.with(ObjectAnimator.ofFloat(focus, "scaleY", 0.2f, 1f))
.with(ObjectAnimator.ofFloat(focus, "rotation", 0f, 360f))
animator.start()
}
override fun detachAllViewsFromParent() {
if (animator.isRunning) {
animator.cancel()
}
if (rotation.isRunning) {
rotation.cancel()
}
super.detachAllViewsFromParent()
}
fun setBitmap(bitmap: Bitmap) {
circleView.drawBitmap(bitmap)
}
} | mit | 0f4f70b723742d50223ba0f3d31d97e1 | 31.6 | 112 | 0.635843 | 4.907631 | false | false | false | false |
JetBrains/kotlin-native | Interop/Runtime/src/native/kotlin/kotlinx/cinterop/NativeTypes.kt | 3 | 9672 | /*
* Copyright 2010-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 kotlinx.cinterop
import kotlin.native.internal.getNativeNullPtr
import kotlin.native.internal.reinterpret
import kotlin.native.internal.Intrinsic
import kotlin.native.internal.VolatileLambda
import kotlin.native.internal.TypedIntrinsic
import kotlin.native.internal.IntrinsicType
typealias NativePtr = kotlin.native.internal.NativePtr
internal typealias NonNullNativePtr = kotlin.native.internal.NonNullNativePtr
@Suppress("NOTHING_TO_INLINE")
internal inline fun NativePtr.toNonNull() = this.reinterpret<NativePtr, NonNullNativePtr>()
inline val nativeNullPtr: NativePtr
get() = getNativeNullPtr()
@Deprecated("Use sizeOf<T>() or alignOf<T>() instead.")
@Suppress("DEPRECATION")
fun <T : CVariable> typeOf(): CVariable.Type = throw Error("typeOf() is called with erased argument")
/**
* Performs type cast of the native pointer to given interop type, including null values.
*
* @param T must not be abstract
*/
@TypedIntrinsic(IntrinsicType.IDENTITY)
external fun <T : NativePointed> interpretNullablePointed(ptr: NativePtr): T?
/**
* Performs type cast of the [CPointer] from the given raw pointer.
*/
@TypedIntrinsic(IntrinsicType.IDENTITY)
external fun <T : CPointed> interpretCPointer(rawValue: NativePtr): CPointer<T>?
@TypedIntrinsic(IntrinsicType.IDENTITY)
external fun NativePointed.getRawPointer(): NativePtr
@TypedIntrinsic(IntrinsicType.IDENTITY)
external fun CPointer<*>.getRawValue(): NativePtr
internal fun CPointer<*>.cPointerToString() = "CPointer(raw=$rawValue)"
@Suppress("FINAL_UPPER_BOUND")
public class Vector128VarOf<T : Vector128>(rawPtr: NativePtr) : CVariable(rawPtr) {
@Deprecated("Use sizeOf<T>() or alignOf<T>() instead.")
@Suppress("DEPRECATION")
companion object : Type(size = 16, align = 16)
}
public typealias Vector128Var = Vector128VarOf<Vector128>
@Suppress("FINAL_UPPER_BOUND", "UNCHECKED_CAST")
public var <T : Vector128> Vector128VarOf<T>.value: T
get() = nativeMemUtils.getVector(this) as T
set(value) = nativeMemUtils.putVector(this, value)
/**
* Returns a pointer to C function which calls given Kotlin *static* function.
*
* @param function must be *static*, i.e. an (unbound) reference to a Kotlin function or
* a closure which doesn't capture any variable
*/
@TypedIntrinsic(IntrinsicType.INTEROP_STATIC_C_FUNCTION) external fun <R> staticCFunction(@VolatileLambda function: () -> R): CPointer<CFunction<() -> R>>
@TypedIntrinsic(IntrinsicType.INTEROP_STATIC_C_FUNCTION) external fun <P1, R> staticCFunction(@VolatileLambda function: (P1) -> R): CPointer<CFunction<(P1) -> R>>
@TypedIntrinsic(IntrinsicType.INTEROP_STATIC_C_FUNCTION) external fun <P1, P2, R> staticCFunction(@VolatileLambda function: (P1, P2) -> R): CPointer<CFunction<(P1, P2) -> R>>
@TypedIntrinsic(IntrinsicType.INTEROP_STATIC_C_FUNCTION) external fun <P1, P2, P3, R> staticCFunction(@VolatileLambda function: (P1, P2, P3) -> R): CPointer<CFunction<(P1, P2, P3) -> R>>
@TypedIntrinsic(IntrinsicType.INTEROP_STATIC_C_FUNCTION) external fun <P1, P2, P3, P4, R> staticCFunction(@VolatileLambda function: (P1, P2, P3, P4) -> R): CPointer<CFunction<(P1, P2, P3, P4) -> R>>
@TypedIntrinsic(IntrinsicType.INTEROP_STATIC_C_FUNCTION) external fun <P1, P2, P3, P4, P5, R> staticCFunction(@VolatileLambda function: (P1, P2, P3, P4, P5) -> R): CPointer<CFunction<(P1, P2, P3, P4, P5) -> R>>
@TypedIntrinsic(IntrinsicType.INTEROP_STATIC_C_FUNCTION) external fun <P1, P2, P3, P4, P5, P6, R> staticCFunction(@VolatileLambda function: (P1, P2, P3, P4, P5, P6) -> R): CPointer<CFunction<(P1, P2, P3, P4, P5, P6) -> R>>
@TypedIntrinsic(IntrinsicType.INTEROP_STATIC_C_FUNCTION) external fun <P1, P2, P3, P4, P5, P6, P7, R> staticCFunction(@VolatileLambda function: (P1, P2, P3, P4, P5, P6, P7) -> R): CPointer<CFunction<(P1, P2, P3, P4, P5, P6, P7) -> R>>
@TypedIntrinsic(IntrinsicType.INTEROP_STATIC_C_FUNCTION) external fun <P1, P2, P3, P4, P5, P6, P7, P8, R> staticCFunction(@VolatileLambda function: (P1, P2, P3, P4, P5, P6, P7, P8) -> R): CPointer<CFunction<(P1, P2, P3, P4, P5, P6, P7, P8) -> R>>
@TypedIntrinsic(IntrinsicType.INTEROP_STATIC_C_FUNCTION) external fun <P1, P2, P3, P4, P5, P6, P7, P8, P9, R> staticCFunction(@VolatileLambda function: (P1, P2, P3, P4, P5, P6, P7, P8, P9) -> R): CPointer<CFunction<(P1, P2, P3, P4, P5, P6, P7, P8, P9) -> R>>
@TypedIntrinsic(IntrinsicType.INTEROP_STATIC_C_FUNCTION) external fun <P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, R> staticCFunction(@VolatileLambda function: (P1, P2, P3, P4, P5, P6, P7, P8, P9, P10) -> R): CPointer<CFunction<(P1, P2, P3, P4, P5, P6, P7, P8, P9, P10) -> R>>
@TypedIntrinsic(IntrinsicType.INTEROP_STATIC_C_FUNCTION) external fun <P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, R> staticCFunction(@VolatileLambda function: (P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11) -> R): CPointer<CFunction<(P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11) -> R>>
@TypedIntrinsic(IntrinsicType.INTEROP_STATIC_C_FUNCTION) external fun <P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, R> staticCFunction(@VolatileLambda function: (P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12) -> R): CPointer<CFunction<(P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12) -> R>>
@TypedIntrinsic(IntrinsicType.INTEROP_STATIC_C_FUNCTION) external fun <P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, R> staticCFunction(@VolatileLambda function: (P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13) -> R): CPointer<CFunction<(P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13) -> R>>
@TypedIntrinsic(IntrinsicType.INTEROP_STATIC_C_FUNCTION) external fun <P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, R> staticCFunction(@VolatileLambda function: (P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14) -> R): CPointer<CFunction<(P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14) -> R>>
@TypedIntrinsic(IntrinsicType.INTEROP_STATIC_C_FUNCTION) external fun <P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15, R> staticCFunction(@VolatileLambda function: (P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15) -> R): CPointer<CFunction<(P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15) -> R>>
@TypedIntrinsic(IntrinsicType.INTEROP_STATIC_C_FUNCTION) external fun <P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15, P16, R> staticCFunction(@VolatileLambda function: (P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15, P16) -> R): CPointer<CFunction<(P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15, P16) -> R>>
@TypedIntrinsic(IntrinsicType.INTEROP_STATIC_C_FUNCTION) external fun <P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15, P16, P17, R> staticCFunction(@VolatileLambda function: (P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15, P16, P17) -> R): CPointer<CFunction<(P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15, P16, P17) -> R>>
@TypedIntrinsic(IntrinsicType.INTEROP_STATIC_C_FUNCTION) external fun <P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15, P16, P17, P18, R> staticCFunction(@VolatileLambda function: (P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15, P16, P17, P18) -> R): CPointer<CFunction<(P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15, P16, P17, P18) -> R>>
@TypedIntrinsic(IntrinsicType.INTEROP_STATIC_C_FUNCTION) external fun <P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15, P16, P17, P18, P19, R> staticCFunction(@VolatileLambda function: (P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15, P16, P17, P18, P19) -> R): CPointer<CFunction<(P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15, P16, P17, P18, P19) -> R>>
@TypedIntrinsic(IntrinsicType.INTEROP_STATIC_C_FUNCTION) external fun <P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15, P16, P17, P18, P19, P20, R> staticCFunction(@VolatileLambda function: (P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15, P16, P17, P18, P19, P20) -> R): CPointer<CFunction<(P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15, P16, P17, P18, P19, P20) -> R>>
@TypedIntrinsic(IntrinsicType.INTEROP_STATIC_C_FUNCTION) external fun <P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15, P16, P17, P18, P19, P20, P21, R> staticCFunction(@VolatileLambda function: (P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15, P16, P17, P18, P19, P20, P21) -> R): CPointer<CFunction<(P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15, P16, P17, P18, P19, P20, P21) -> R>>
@TypedIntrinsic(IntrinsicType.INTEROP_STATIC_C_FUNCTION) external fun <P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15, P16, P17, P18, P19, P20, P21, P22, R> staticCFunction(@VolatileLambda function: (P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15, P16, P17, P18, P19, P20, P21, P22) -> R): CPointer<CFunction<(P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15, P16, P17, P18, P19, P20, P21, P22) -> R>>
| apache-2.0 | 79bda65bf1679ede654da6f8f6a527db | 76.376 | 453 | 0.688792 | 2.492784 | false | false | false | false |
vovagrechka/fucking-everything | pieces/pieces-100/src/main/java/pieces100/p100-compose.kt | 1 | 1108 | package pieces100
import alraune.*
import alraune.Al.*
import vgrechka.*
fun drawPlayTicker(domid: String = nextJSIdentifier(), location: Rightness, hidden: Boolean): Renderable {
val animationName by nextJsIdentDel()
return rawHtml("""
<style>
#$domid {
${hidden.thenElseEmpty {"display: none;"}}
width: 29px;
height: 34px;
float: ${location.cssString()};
animation-name: $animationName;
animation-duration: 500ms;
animation-iteration-count: infinite;
}
@keyframes $animationName {0% {opacity: 1;} 100% {opacity: 0;}}
</style>
<svg id="$domid" width="29" height="34" viewBox="0 0 29 34" xmlns="http://www.w3.org/2000/svg">
<circle cx="3" cy="17.5" r="2" fill="#546e7a"/>
<circle cx="11" cy="17.5" r="3" fill="#546e7a"/>
<polygon points="17,8 28,17.5, 17,26" fill="#546e7a" stroke="#546e7a" stroke-linecap="round" stroke-linejoin="round" stroke-width="2"/>
</svg>
""")
}
| apache-2.0 | 55ab32161f8afdb08be8357398601c1b | 30.657143 | 147 | 0.548736 | 3.620915 | false | false | false | false |
jwren/intellij-community | plugins/groovy/src/org/jetbrains/plugins/groovy/dgm/GroovyMacroRegistryServiceImpl.kt | 1 | 5246 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.plugins.groovy.dgm
import com.intellij.ProjectTopics
import com.intellij.lang.properties.psi.PropertiesFile
import com.intellij.openapi.module.Module
import com.intellij.openapi.module.ModuleManager
import com.intellij.openapi.module.ModuleUtilCore
import com.intellij.openapi.project.DumbService
import com.intellij.openapi.project.Project
import com.intellij.psi.JavaPsiFacade
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiMethod
import com.intellij.psi.search.FileTypeIndex
import com.intellij.psi.search.GlobalSearchScope
import com.intellij.psi.util.PsiUtilBase
import com.intellij.util.castSafelyTo
import com.intellij.util.lazyPub
import org.jetbrains.plugins.groovy.lang.psi.api.auxiliary.GrListOrMap
import org.jetbrains.plugins.groovy.lang.psi.api.statements.blocks.GrClosableBlock
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrMethodCall
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrReferenceExpression
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrTuple
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.path.GrMethodCallExpression
import org.jetbrains.plugins.groovy.lang.psi.util.GroovyCommonClassNames
import org.jetbrains.plugins.groovy.transformations.macro.GroovyMacroModuleListener
import org.jetbrains.plugins.groovy.transformations.macro.GroovyMacroRegistryService
class GroovyMacroRegistryServiceImpl(val project: Project) : GroovyMacroRegistryService {
@Volatile
private var availableModules: Lazy<Map<Module, MacroRegistry>> = getInitializer()
init {
val connection = project.messageBus.connect()
connection.subscribe(ProjectTopics.PROJECT_ROOTS, GroovyMacroModuleListener())
}
override fun resolveAsMacro(call: GrMethodCall): PsiMethod? {
val module = ModuleUtilCore.findModuleForPsiElement(call) ?: return null
val invokedName = call.invokedExpression.castSafelyTo<GrReferenceExpression>()?.referenceName ?: return null
val candidates = availableModules.value[module]?.filter { it.name == invokedName } ?: return null
return candidates.find { it.canBeAppliedTo(call) }
}
override fun getAllMacros(context: PsiElement): List<PsiMethod> {
val module = ModuleUtilCore.findModuleForPsiElement(context) ?: return emptyList()
return availableModules.value[module]?.toList() ?: emptyList()
}
override fun refreshModule(module: Module) {
availableModules = getInitializer()
}
private fun collectModuleRegistry(): Map<Module, MacroRegistry> {
val modules = mutableMapOf<Module, MacroRegistry>()
DumbService.getInstance(project).runWithAlternativeResolveEnabled<Throwable> {
for (module in ModuleManager.getInstance(project).modules) {
val registry = computeModuleRegistry(module)
if (registry.isNotEmpty()) {
modules[module] = registry
}
}
}
return modules
}
fun getInitializer(): Lazy<Map<Module, MacroRegistry>> {
return lazyPub { collectModuleRegistry() }
}
}
private fun computeModuleRegistry(module : Module) : MacroRegistry {
val scope = GlobalSearchScope.moduleWithDependenciesAndLibrariesScope(module)
val extensionFiles = FileTypeIndex.getFiles(DGMFileType, scope)
val macroRegistry = mutableSetOf<PsiMethod>()
for (extensionVirtualFile in extensionFiles) {
val psi = PsiUtilBase.getPsiFile(module.project, extensionVirtualFile)
val inst = psi.castSafelyTo<PropertiesFile>()?.findPropertyByKey("extensionClasses")
val extensionClassName = inst?.value ?: continue
val extensionClass = JavaPsiFacade.getInstance(module.project).findClass(extensionClassName, scope) ?: continue
val macroMethods = extensionClass.methods.filter {
it.hasAnnotation(GroovyCommonClassNames.ORG_CODEHAUS_GROOVY_MACRO_RUNTIME_MACRO) &&
it.parameterList.parameters[0].typeElement != null &&
it.parameterList.parameters[0].type.equalsToText("org.codehaus.groovy.macro.runtime.MacroContext")
}
macroRegistry.addAll(macroMethods)
}
return macroRegistry
}
private fun PsiMethod.canBeAppliedTo(call: GrMethodCall): Boolean {
val methodParameters = parameterList.parameters.drop(1)
for ((argument, parameter) in (call.expressionArguments + call.closureArguments).zip(methodParameters)) {
val type = parameter.typeElement?.type ?: return false
when {
type.equalsToText("org.codehaus.groovy.ast.expr.ClosureExpression") && argument !is GrClosableBlock -> return false
type.equalsToText("org.codehaus.groovy.ast.expr.ListExpression") && argument.castSafelyTo<GrListOrMap>()?.isMap != false -> return false
type.equalsToText("org.codehaus.groovy.ast.expr.MapExpression") && argument.castSafelyTo<GrListOrMap>()?.isMap != true -> return false
type.equalsToText("org.codehaus.groovy.ast.expr.TupleExpression") && argument !is GrTuple -> return false
type.equalsToText("org.codehaus.groovy.ast.expr.MethodCallExpression") && argument !is GrMethodCallExpression -> return false
}
}
return true
}
private typealias MacroRegistry = Set<PsiMethod> | apache-2.0 | 93000147f0906adde09409ea41f9ecf9 | 47.583333 | 142 | 0.784026 | 4.593695 | false | false | false | false |
akosyakov/intellij-community | platform/script-debugger/protocol/protocol-model-generator/src/Generator.kt | 5 | 10426 | package org.jetbrains.protocolModelGenerator
import gnu.trove.THashMap
import org.jetbrains.jsonProtocol.*
import org.jetbrains.protocolReader.FileUpdater
import org.jetbrains.protocolReader.TextOutput
import java.nio.file.FileSystems
import java.util.ArrayList
import java.util.Collections
import java.util.HashMap
import java.util.HashSet
/**
* Read metamodel and generates set of files with Java classes/interfaces for the protocol.
*/
class Generator(outputDir: String, rootPackage: String, requestClassName: String) {
val jsonProtocolParserClassNames = ArrayList<String>()
val parserRootInterfaceItems = ArrayList<ParserRootInterfaceItem>()
val typeMap = TypeMap()
val nestedTypeMap = THashMap<NamePath, StandaloneType>()
private val fileSet: FileSet
val naming: Naming
init {
fileSet = FileSet(FileSystems.getDefault().getPath(outputDir))
naming = Naming(rootPackage, requestClassName)
}
public class Naming(val inputPackage: String, val requestClassName: String) {
public val params: ClassNameScheme
public val additionalParam: ClassNameScheme
public val outputTypedef: ClassNameScheme
public val commandResult: ClassNameScheme.Input
public val eventData: ClassNameScheme.Input
public val inputValue: ClassNameScheme
public val inputEnum: ClassNameScheme
public val inputTypedef: ClassNameScheme
public val commonTypedef: ClassNameScheme
init {
params = ClassNameScheme.Output("", inputPackage)
additionalParam = ClassNameScheme.Output("", inputPackage)
outputTypedef = ClassNameScheme.Output("Typedef", inputPackage)
commonTypedef = ClassNameScheme.Common("Typedef", inputPackage)
commandResult = ClassNameScheme.Input("Result", inputPackage)
eventData = ClassNameScheme.Input("EventData", inputPackage)
inputValue = ClassNameScheme.Input("Value", inputPackage)
inputEnum = ClassNameScheme.Input("", inputPackage)
inputTypedef = ClassNameScheme.Input("Typedef", inputPackage)
}
}
fun go(metamodel: ProtocolMetaModel.Root) {
initializeKnownTypes()
val domainList = metamodel.domains()
val domainGeneratorMap = HashMap<String, DomainGenerator>()
for (domain in domainList) {
if (isDomainSkipped(domain)) {
System.out.println("Domain skipped: " + domain.domain())
continue
}
val domainGenerator = DomainGenerator(this, domain)
domainGeneratorMap.put(domain.domain(), domainGenerator)
domainGenerator.registerTypes()
}
for (domain in domainList) {
if (!isDomainSkipped(domain)) {
System.out.println("Domain generated: " + domain.domain())
}
}
typeMap.domainGeneratorMap = domainGeneratorMap
for (domainGenerator in domainGeneratorMap.values()) {
domainGenerator.generateCommandsAndEvents()
}
typeMap.generateRequestedTypes()
generateParserInterfaceList()
generateParserRoot(parserRootInterfaceItems)
fileSet.deleteOtherFiles()
}
fun resolveType(typedObject: ItemDescriptor, scope: ResolveAndGenerateScope): TypeDescriptor {
val optional = typedObject is ItemDescriptor.Named && (typedObject : ItemDescriptor.Named).optional()
return switchByType(typedObject, object : TypeVisitor<TypeDescriptor> {
override fun visitRef(refName: String): TypeDescriptor {
return TypeDescriptor(resolveRefType(scope.getDomainName(), refName, scope.getTypeDirection()), optional)
}
override fun visitBoolean(): TypeDescriptor {
return TypeDescriptor(BoxableType.BOOLEAN, optional)
}
override fun visitEnum(enumConstants: List<String>): TypeDescriptor {
assert(scope is MemberScope)
return TypeDescriptor((scope as MemberScope).generateEnum(typedObject.description(), enumConstants), optional)
}
override fun visitString(): TypeDescriptor {
return TypeDescriptor(BoxableType.STRING, optional)
}
override fun visitInteger(): TypeDescriptor {
return TypeDescriptor(BoxableType.INT, optional)
}
override fun visitNumber(): TypeDescriptor {
return TypeDescriptor(BoxableType.NUMBER, optional)
}
override fun visitMap(): TypeDescriptor {
return TypeDescriptor(BoxableType.MAP, optional)
}
override fun visitArray(items: ProtocolMetaModel.ArrayItemType): TypeDescriptor {
val type = scope.resolveType<ProtocolMetaModel.ArrayItemType>(items).type
return TypeDescriptor(ListType(type), optional, false, type == BoxableType.ANY_STRING)
}
override fun visitObject(properties: List<ProtocolMetaModel.ObjectProperty>?): TypeDescriptor {
return TypeDescriptor(scope.generateNestedObject(typedObject.description(), properties), optional)
}
override fun visitUnknown(): TypeDescriptor {
return TypeDescriptor(BoxableType.STRING, optional, false, true)
}
})
}
private fun generateParserInterfaceList() {
val fileUpdater = startJavaFile(naming.inputPackage, PARSER_INTERFACE_LIST_CLASS_NAME + ".java")
// Write classes in stable order.
Collections.sort<String>(jsonProtocolParserClassNames)
val out = fileUpdater.out
out.append("public class ").append(PARSER_INTERFACE_LIST_CLASS_NAME).openBlock()
out.append("public static final Class<?>[] LIST =").openBlock()
for (name in jsonProtocolParserClassNames) {
out.append(name).append(".class,").newLine()
}
out.closeBlock()
out.semi()
out.closeBlock()
fileUpdater.update()
}
private fun generateParserRoot(parserRootInterfaceItems: List<ParserRootInterfaceItem>) {
val fileUpdater = startJavaFile(naming.inputPackage, READER_INTERFACE_NAME + ".java")
// Write classes in stable order.
Collections.sort<ParserRootInterfaceItem>(parserRootInterfaceItems)
val out = fileUpdater.out
out.append("public abstract class ").append(READER_INTERFACE_NAME).space().append("implements org.jetbrains.jsonProtocol.ResponseResultReader").openBlock()
for (item in parserRootInterfaceItems) {
item.writeCode(out)
}
out.newLine().newLine().append("@Override").newLine().append("public Object readResult(String methodName, org.jetbrains.io.JsonReaderEx reader)")
out.openBlock()
var isNotFirst = false
for (item in parserRootInterfaceItems) {
if (isNotFirst) {
out.append("else ")
}
else {
isNotFirst = true
}
out.append("if (methodName.equals(\"")
if (!item.domain.isEmpty()) {
out.append(item.domain).append('.')
}
out.append(item.name).append('"').append(")) return ")
item.appendReadMethodName(out)
out.append("(reader)").semi().newLine()
}
out.append("else return null").semi()
out.closeBlock()
out.closeBlock()
fileUpdater.update()
}
/**
* Resolve absolute (DOMAIN.TYPE) or relative (TYPE) type name
*/
private fun resolveRefType(scopeDomainName: String, refName: String, direction: TypeData.Direction): BoxableType {
val pos = refName.indexOf('.')
val domainName: String
val shortName: String
if (pos == -1) {
domainName = scopeDomainName
shortName = refName
}
else {
domainName = refName.substring(0, pos)
shortName = refName.substring(pos + 1)
}
return typeMap.resolve(domainName, shortName, direction)!!
}
fun startJavaFile(nameScheme: ClassNameScheme, domain: ProtocolMetaModel.Domain, baseName: String): FileUpdater {
return startJavaFile(nameScheme.getPackageNameVirtual(domain.domain()), nameScheme.getShortName(baseName) + ".java")
}
public fun startJavaFile(packageName: String, filename: String): FileUpdater {
val fileUpdater = fileSet.createFileUpdater(packageName.replace('.', '/') + '/' + filename)
fileUpdater.out.append("// Generated source").newLine().append("package ").append(packageName).semi().newLine().newLine()
return fileUpdater
}
}
private val PARSER_INTERFACE_LIST_CLASS_NAME = "GeneratedReaderInterfaceList"
val READER_INTERFACE_NAME = "ProtocolResponseReader"
private fun isDomainSkipped(domain: ProtocolMetaModel.Domain): Boolean {
if (domain.domain() == "CSS" || domain.domain() == "Inspector") {
return false
}
// todo DOMDebugger
return domain.hidden() || domain.domain() == "DOMDebugger" || domain.domain() == "Timeline" || domain.domain() == "Input"
}
fun generateMethodNameSubstitute(originalName: String, out: TextOutput): String {
if (!BAD_METHOD_NAMES.contains(originalName)) {
return originalName
}
out.append("@org.jetbrains.jsonProtocol.JsonField(name = \"").append(originalName).append("\")").newLine()
return "get" + Character.toUpperCase(originalName.charAt(0)) + originalName.substring(1)
}
fun capitalizeFirstChar(s: String): String {
if (!s.isEmpty() && Character.isLowerCase(s.charAt(0))) {
return Character.toUpperCase(s.charAt(0)) + s.substring(1)
}
return s
}
fun <R> switchByType(typedObject: ItemDescriptor, visitor: TypeVisitor<R>): R {
val refName = if (typedObject is ItemDescriptor.Referenceable) (typedObject : ItemDescriptor.Referenceable).ref() else null
if (refName != null) {
return visitor.visitRef(refName)
}
val typeName = typedObject.type()
when (typeName) {
BOOLEAN_TYPE -> return visitor.visitBoolean()
STRING_TYPE -> {
if (typedObject.getEnum() != null) {
return visitor.visitEnum(typedObject.getEnum()!!)
}
return visitor.visitString()
}
INTEGER_TYPE, "int" -> return visitor.visitInteger()
NUMBER_TYPE -> return visitor.visitNumber()
ARRAY_TYPE -> return visitor.visitArray(typedObject.items())
OBJECT_TYPE -> {
if (typedObject !is ItemDescriptor.Type) {
return visitor.visitObject(null)
}
val properties = (typedObject : ItemDescriptor.Type).properties()
if (properties == null || properties.isEmpty()) {
return visitor.visitMap()
}
else {
return visitor.visitObject(properties)
}
}
ANY_TYPE -> return visitor.visitUnknown()
UNKNOWN_TYPE -> return visitor.visitUnknown()
}
throw RuntimeException("Unrecognized type " + typeName)
}
private fun initializeKnownTypes() {
// Code example:
// typeMap.getTypeData("Page", "Cookie").getInput().setJavaTypeName("Object");
}
private val BAD_METHOD_NAMES = HashSet(listOf("this")) | apache-2.0 | bb6f27e2585f5350fa7c3f29391d1248 | 35.33101 | 159 | 0.709476 | 4.572807 | false | false | false | false |
josecefe/Rueda | src/es/um/josecefe/rueda/modelo/AsignacionDiaSimple.kt | 1 | 1282 | /*
* Copyright (c) 2016-2017. Jose Ceferino Ortega Carretero
*
* This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
* You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package es.um.josecefe.rueda.modelo
/**
* @author josecefe
*/
data class AsignacionDiaSimple(
override val conductores: Set<Participante> = emptySet(),
override val coste: Int = 0
) : Comparable<AsignacionDiaSimple>, AsignacionDia {
override val peIda: Map<Participante, Lugar>
get() = conductores.associateWith { it.puntosEncuentro[0] }
override val peVuelta: Map<Participante, Lugar>
get() = peIda
override fun compareTo(other: AsignacionDiaSimple) = (conductores.size * 1000 + coste).compareTo(other.conductores.size * 1000 + other.coste)
} | gpl-3.0 | d96f1817fa6efa8498c429eb3d6b8d93 | 48.346154 | 242 | 0.74025 | 3.95679 | false | false | false | false |
jwren/intellij-community | plugins/maven/src/main/java/org/jetbrains/idea/maven/externalSystemIntegration/output/quickfixes/SourceOptionQuickFix.kt | 2 | 11664 | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.idea.maven.externalSystemIntegration.output.quickfixes
import com.google.common.primitives.Bytes
import com.intellij.build.events.BuildEvent
import com.intellij.build.events.MessageEvent
import com.intellij.build.events.impl.BuildIssueEventImpl
import com.intellij.build.issue.BuildIssue
import com.intellij.build.issue.BuildIssueQuickFix
import com.intellij.compiler.progress.BuildIssueContributor
import com.intellij.notification.Notification
import com.intellij.notification.NotificationType
import com.intellij.openapi.Disposable
import com.intellij.openapi.actionSystem.DataContext
import com.intellij.openapi.fileEditor.OpenFileDescriptor
import com.intellij.openapi.module.ModuleManager
import com.intellij.openapi.project.Project
import com.intellij.openapi.projectRoots.JavaSdk
import com.intellij.openapi.projectRoots.JavaSdkVersion
import com.intellij.openapi.projectRoots.ProjectJdkTable
import com.intellij.openapi.projectRoots.Sdk
import com.intellij.openapi.roots.ModuleRootManager
import com.intellij.openapi.vfs.VfsUtil
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.openapi.vfs.jrt.JrtFileSystem
import com.intellij.pom.Navigatable
import com.intellij.pom.java.LanguageLevel
import org.jetbrains.idea.maven.externalSystemIntegration.output.LogMessageType
import org.jetbrains.idea.maven.externalSystemIntegration.output.MavenLogEntryReader
import org.jetbrains.idea.maven.externalSystemIntegration.output.MavenLogEntryReader.MavenLogEntry
import org.jetbrains.idea.maven.externalSystemIntegration.output.MavenLoggedEventParser
import org.jetbrains.idea.maven.externalSystemIntegration.output.MavenParsingContext
import org.jetbrains.idea.maven.model.MavenId
import org.jetbrains.idea.maven.project.MavenProject
import org.jetbrains.idea.maven.project.MavenProjectBundle.message
import org.jetbrains.idea.maven.project.MavenProjectsManager
import org.jetbrains.idea.maven.utils.MavenLog
import org.jetbrains.idea.maven.utils.MavenUtil
import java.nio.charset.StandardCharsets
import java.util.*
import java.util.concurrent.CompletableFuture
import java.util.function.Consumer
class SourceOptionQuickFix : MavenLoggedEventParser {
override fun supportsType(type: LogMessageType?): Boolean {
return type == LogMessageType.ERROR
}
override fun checkLogLine(parentId: Any,
parsingContext: MavenParsingContext,
logLine: MavenLogEntry,
logEntryReader: MavenLogEntryReader,
messageConsumer: Consumer<in BuildEvent?>): Boolean {
if (logLine.line.startsWith("Source option 5 is no longer supported.")
|| logLine.line.startsWith("Source option 1.5 is no longer supported.")) {
val targetLine = logEntryReader.readLine()
if (targetLine != null && !targetLine.line.startsWith("Target option 1.5 is no longer supported.")) {
logEntryReader.pushBack()
}
val lastErrorProject = parsingContext.startedProjects.last() + ":"
val failedProject = parsingContext.projectsInReactor.find { it.startsWith(lastErrorProject) } ?: return false
val mavenProject = MavenProjectsManager.getInstance(parsingContext.ideaProject).findProject(MavenId(failedProject)) ?: return false
val moduleJdk = MavenUtil.getModuleJdk(MavenProjectsManager.getInstance(parsingContext.ideaProject), mavenProject) ?: return false
messageConsumer.accept(
BuildIssueEventImpl(parentId,
SourceLevelBuildIssue(logLine.line, logLine.line, mavenProject, moduleJdk),
MessageEvent.Kind.ERROR));
return true
}
return false
}
}
class SourceLevelBuildIssue(private val message: String,
override val title: String,
private val mavenProject: MavenProject,
private val moduleJdk: Sdk) : BuildIssue {
override val quickFixes: List<UpdateSourceLevelQuickFix> = Collections.singletonList(UpdateSourceLevelQuickFix(mavenProject))
override val description = createDescription()
private fun createDescription() = "$message\n<br/>" + quickFixes.map {
message("maven.source.level.not.supported.update",
LanguageLevel.parse(moduleJdk.versionString)?.toJavaVersion(),
it.id, it.mavenProject.displayName)
}.joinToString("\n<br/>")
override fun getNavigatable(project: Project): Navigatable? {
return mavenProject.file.let { OpenFileDescriptor(project, it) }
}
}
typealias MessagePredicate = (String) -> Boolean
/**
* @deprecated use {@link JpsLanguageLevelQuickFix.kt
*/
class JpsReleaseVersionQuickFix : BuildIssueContributor {
override fun createBuildIssue(project: Project,
moduleNames: Collection<String>,
title: String,
message: String,
kind: MessageEvent.Kind,
virtualFile: VirtualFile?,
navigatable: Navigatable?): BuildIssue? {
val manager = MavenProjectsManager.getInstance(project);
if (!manager.isMavenizedProject) return null
if (moduleNames.size != 1) {
return null
}
val moduleName = moduleNames.firstOrNull() ?: return null
val predicates = CacheForCompilerErrorMessages.getPredicatesToCheck(project, moduleName)
val failedId = extractFailedMavenId(project, moduleName) ?: return null;
val mavenProject = manager.findProject(failedId) ?: return null
val moduleJdk = MavenUtil.getModuleJdk(manager, mavenProject) ?: return null
if (predicates.any { it(message) }) return SourceLevelBuildIssue(title, message, mavenProject, moduleJdk)
return null
}
fun extractFailedMavenId(project: Project, moduleName: String): MavenId? {
val module = ModuleManager.getInstance(project).findModuleByName(moduleName) ?: return null
return MavenProjectsManager.getInstance(project).findProject(module)?.mavenId ?: return null
}
}
class UpdateSourceLevelQuickFix(val mavenProject: MavenProject) : BuildIssueQuickFix {
override val id = ID + mavenProject.mavenId.displayString
override fun runQuickFix(project: Project, dataContext: DataContext): CompletableFuture<*> {
val languageLevelQuickFix = LanguageLevelQuickFixFactory.getInstance(project, mavenProject)
return ProcessQuickFix.perform(languageLevelQuickFix, project, mavenProject)
}
companion object {
val ID = "maven_quickfix_source_level_"
}
}
object CacheForCompilerErrorMessages {
private val key = "compiler.err.unsupported.release.version".encodeToByteArray()
private val delimiter = ByteArray(2)
init {
delimiter[0] = 1 // SOH
delimiter[1] = 0 // NUL byte
}
private val DEFAULT_CHECK = listOf<MessagePredicate>(
{ it.contains("source release") && it.contains("requires target release") },
{ it.contains("invalid target release") },
{ it.contains("release version") && it.contains("not supported") }, //en
{
it.contains("\u30EA\u30EA\u30FC\u30B9\u30FB\u30D0\u30FC\u30B8\u30E7\u30F3")
&& it.contains("\u306F\u30B5\u30DD\u30FC\u30C8\u3055\u308C\u3066\u3044\u307E\u305B\u3093")
}, //ja
{ it.contains("\u4E0D\u652F\u6301\u53D1\u884C\u7248\u672C") } //zh_CN
)
private val map = WeakHashMap<String, List<MessagePredicate>>()
@JvmStatic
fun connectToJdkListener(myProject: Project, disposable: Disposable) {
myProject.messageBus.connect(disposable).subscribe(ProjectJdkTable.JDK_TABLE_TOPIC, object : ProjectJdkTable.Listener {
override fun jdkAdded(jdk: Sdk) {
synchronized(map) { map.remove(jdk.name) }
}
override fun jdkRemoved(jdk: Sdk) {
synchronized(map) { map.remove(jdk.name) }
}
override fun jdkNameChanged(jdk: Sdk, previousName: String) {
synchronized(map) {
val list = map[previousName]
if (list != null) {
map[jdk.name] = list
}
}
}
})
}
fun getPredicatesToCheck(project: Project, moduleName: String): List<MessagePredicate> {
val module = ModuleManager.getInstance(project).findModuleByName(moduleName) ?: return DEFAULT_CHECK;
val sdk = ModuleRootManager.getInstance(module).sdk ?: return DEFAULT_CHECK;
return synchronized(map) { map.getOrPut(sdk.name) { readFrom(sdk) } }
}
private fun readFrom(sdk: Sdk): List<MessagePredicate> {
val version = JavaSdk.getInstance().getVersion(sdk);
if (version == null || !version.isAtLeast(JavaSdkVersion.JDK_1_9)) {
return DEFAULT_CHECK;
}
try {
val jrtLocalFile = sdk.homeDirectory?.let { JrtFileSystem.getInstance().getRootByLocal(it) } ?: return DEFAULT_CHECK
val list =
jrtLocalFile.findFileByRelativePath("jdk.compiler/com/sun/tools/javac/resources")
?.children
?.filter { it.name.startsWith("compiler") && it.name.endsWith(".class") }
?.mapNotNull { readFromBinaryFile(it) }
?.toList()
if (list.isNullOrEmpty()) return DEFAULT_CHECK else return list
}
catch (e: Throwable) {
MavenLog.LOG.warn(e);
return DEFAULT_CHECK;
}
}
private fun readFromBinaryFile(file: VirtualFile?): MessagePredicate? {
if (file == null) return null
try {
val allBytes = VfsUtil.loadBytes(file)
val indexKey = Bytes.indexOf(allBytes, key)
if (indexKey == -1) return null
val startFrom = indexKey + key.size + 3;
val endIndex = allBytes.findNextSOH(startFrom)
if (endIndex == -1 || startFrom == endIndex) return null
val message = String(allBytes, startFrom, endIndex - startFrom, StandardCharsets.UTF_8)
return toMessagePredicate(message);
}
catch (e: Throwable) {
MavenLog.LOG.warn(e);
return null
}
}
private fun toMessagePredicate(message: String): MessagePredicate? {
val first = message.substringBefore("{0}")
val second = message.substringAfter("{0}")
return { it.contains(first) && it.contains(second) }
}
private fun ByteArray.findNextSOH(startFrom: Int): Int {
if (startFrom == -1) return -1
var i = startFrom
while (i < this.size - 1) {
if (this[i] == delimiter[0] && this[i + 1] == delimiter[1]) {
return i;
}
i++
}
return -1
}
}
object ProcessQuickFix {
fun perform(languageLevelQuickFix: LanguageLevelQuickFix?, project: Project, mavenProject: MavenProject): CompletableFuture<*> {
if (languageLevelQuickFix == null) {
Notification(MavenUtil.MAVEN_NOTIFICATION_GROUP, "",
message("maven.quickfix.cannot.update.source.level.module.not.found", mavenProject.displayName),
NotificationType.INFORMATION).notify(project)
return CompletableFuture.completedFuture(null)
}
val moduleJdk = MavenUtil.getModuleJdk(MavenProjectsManager.getInstance(project), languageLevelQuickFix.mavenProject)
if (moduleJdk == null) {
Notification(MavenUtil.MAVEN_NOTIFICATION_GROUP, "",
message("maven.quickfix.cannot.update.source.level.module.not.found",
languageLevelQuickFix.mavenProject.displayName),
NotificationType.INFORMATION).notify(project)
return CompletableFuture.completedFuture(null)
}
languageLevelQuickFix.perform(LanguageLevel.parse(moduleJdk.versionString)!!)
return CompletableFuture.completedFuture(null)
}
}
| apache-2.0 | a195ff961a625394641640d501316cfc | 41.108303 | 140 | 0.71082 | 4.542056 | false | false | false | false |
jwren/intellij-community | plugins/kotlin/idea/tests/testData/inspections/coroutines/directUseOfResultType/test.kt | 9 | 1793 | package kotlin
// NO (constructor)
class Result<T>(val value: T?) {
fun getOrThrow(): T = value ?: throw AssertionError("")
}
// YES
fun getSuccess() = success()
// YES
fun getSuccessExplicit(): Result<Int> = Result(456)
// NO (not catching 'correct' available)
fun correctCatching() = Result(true)
// NO (not Result)
fun correct() = true
// YES
fun incorrectCatching() = Result(3.14)
// YES
fun strangeCatching() = runCatching { false }
// NO (not Result)
fun strange() = 1
class Container {
// YES
fun classGetSuccess() = Result("123")
// YES
fun classGetSuccessExplicit(): Result<Int> = Result(456)
// NO (not catching 'classCorrect' available)
fun classCorrectCatching() = Result(true)
// NO (not Result)
fun classCorrect() = true
// YES
fun classIncorrectCatching() = Result(3.14)
}
fun test() {
// YES
fun localGetSuccess() = Result("123")
// NO (no name)
val anonymous = fun() = Result(45)
// NO (no name)
val lambda = { Result(true) }
// NO yet (we do not report local *catching functions)
fun localCatching() = Result(2.72)
}
// NO (stdlib)
fun success() = Result(true)
// NO (stdlib)
fun failure() = Result(false)
// NO (stdlib)
fun <T> runCatching(block: () -> T) = Result(block())
// NO (stdlib)
fun <T> Result<T>.id() = this
class ClassWithExtension() {
// NO (not Result)
fun calc() = 12345
// NO (not Result)
fun calcComplex(arg1: Int, arg2: Double): Double = arg1 + arg2
// YES (different parameters)
fun calcComplexCatching() = Result(0.0)
}
// NO (extension to calc)
fun ClassWithExtension.calcCatching() = Result(calc())
// NO (not Result)
fun Container.extensionAct() = 42
// YES (different extension receiver)
fun ClassWithExtension.extensionActCatching() = Result(42) | apache-2.0 | 43d9c6ebcbe7c366a0960eee70b0c548 | 25.776119 | 66 | 0.646403 | 3.454721 | false | false | false | false |
nrizzio/Signal-Android | app/src/main/java/org/thoughtcrime/securesms/mediasend/v2/text/TextFontButton.kt | 2 | 1057 | package org.thoughtcrime.securesms.mediasend.v2.text
import android.content.Context
import android.util.AttributeSet
import androidx.appcompat.widget.AppCompatImageView
import org.thoughtcrime.securesms.fonts.TextFont
import org.thoughtcrime.securesms.util.next
typealias OnTextFontChanged = (TextFont) -> Unit
/**
* Allows the user to cycle between fonts for a story text post
*/
class TextFontButton @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null
) : AppCompatImageView(context, attrs) {
private var textFont: TextFont = TextFont.REGULAR
var onTextFontChanged: OnTextFontChanged? = null
init {
setImageResource(textFont.icon)
super.setOnClickListener {
setTextFont(textFont.next())
}
}
override fun setOnClickListener(l: OnClickListener?) {
throw UnsupportedOperationException()
}
fun setTextFont(textFont: TextFont) {
if (textFont != this.textFont) {
this.textFont = textFont
setImageResource(textFont.icon)
onTextFontChanged?.invoke(textFont)
}
}
}
| gpl-3.0 | 2d023d9531d281dc806bfebe14fc9101 | 24.780488 | 63 | 0.751183 | 4.296748 | false | false | false | false |
androidx/androidx | camera/camera-camera2-pipe/src/main/java/androidx/camera/camera2/pipe/compat/Camera2CameraDevices.kt | 3 | 1894 | /*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.camera.camera2.pipe.compat
import androidx.annotation.RequiresApi
import androidx.camera.camera2.pipe.CameraDevices
import androidx.camera.camera2.pipe.CameraId
import androidx.camera.camera2.pipe.CameraMetadata
import javax.inject.Inject
import javax.inject.Singleton
import kotlinx.coroutines.runBlocking
/**
* Provides utilities for querying cameras and accessing metadata about those cameras.
*/
@RequiresApi(21) // TODO(b/200306659): Remove and replace with annotation on package-info.java
@Singleton
internal class Camera2CameraDevices @Inject constructor(
private val deviceCache: Camera2DeviceCache,
private val metadataCache: Camera2MetadataCache
) : CameraDevices {
@Deprecated(
message = "findAll may block the calling thread and is deprecated.",
replaceWith = ReplaceWith("ids"),
level = DeprecationLevel.WARNING
)
override fun findAll(): List<CameraId> = runBlocking { deviceCache.getCameras() }
override suspend fun ids(): List<CameraId> = deviceCache.getCameras()
override suspend fun getMetadata(camera: CameraId): CameraMetadata =
metadataCache.getMetadata(camera)
override fun awaitMetadata(camera: CameraId): CameraMetadata =
metadataCache.awaitMetadata(camera)
} | apache-2.0 | 38c232fab626c8568479ce8729a860bb | 37.673469 | 94 | 0.76188 | 4.5311 | false | false | false | false |
siosio/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/editor/KotlinLiteralCopyPasteProcessor.kt | 1 | 12088 | // 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.editor
import com.intellij.codeInsight.editorActions.CopyPastePreProcessor
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.editor.RawText
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.TextRange
import com.intellij.openapi.util.text.LineTokenizer
import com.intellij.openapi.util.text.StringUtil
import com.intellij.psi.PsiDocumentManager
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
import org.jetbrains.annotations.TestOnly
import org.jetbrains.kotlin.idea.editor.fixers.range
import org.jetbrains.kotlin.idea.intentions.callExpression
import org.jetbrains.kotlin.lexer.KotlinLexer
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.KtEscapeStringTemplateEntry
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.psi.KtStringTemplateExpression
import org.jetbrains.kotlin.psi.psiUtil.*
private val PsiElement.templateContentRange: TextRange?
get() = this.getParentOfType<KtStringTemplateExpression>(false)?.let {
it.textRange.cutOut(it.getContentRange())
}
private fun PsiFile.getTemplateIfAtLiteral(offset: Int, at: PsiElement? = findElementAt(offset)): KtStringTemplateExpression? {
if (at == null) return null
return when (at.node?.elementType) {
KtTokens.REGULAR_STRING_PART, KtTokens.ESCAPE_SEQUENCE, KtTokens.LONG_TEMPLATE_ENTRY_START, KtTokens.SHORT_TEMPLATE_ENTRY_START -> at.parent
.parent as? KtStringTemplateExpression
KtTokens.CLOSING_QUOTE -> if (offset == at.startOffset) at.parent as? KtStringTemplateExpression else null
else -> null
}
}
//Copied from StringLiteralCopyPasteProcessor to avoid erroneous inheritance
private fun deduceBlockSelectionWidth(startOffsets: IntArray, endOffsets: IntArray, text: String): Int {
val fragmentCount = startOffsets.size
assert(fragmentCount > 0)
var totalLength = fragmentCount - 1 // number of line breaks inserted between fragments
for (i in 0 until fragmentCount) {
totalLength += endOffsets[i] - startOffsets[i]
}
return if (totalLength < text.length && (text.length + 1) % fragmentCount == 0) {
(text.length + 1) / fragmentCount - 1
} else {
-1
}
}
class KotlinLiteralCopyPasteProcessor : CopyPastePreProcessor {
override fun preprocessOnCopy(file: PsiFile, startOffsets: IntArray, endOffsets: IntArray, text: String): String? {
if (file !is KtFile) {
return null
}
val buffer = StringBuilder()
var changed = false
val fileText = file.text
val deducedBlockSelectionWidth = deduceBlockSelectionWidth(startOffsets, endOffsets, text)
for (i in startOffsets.indices) {
if (i > 0) {
buffer.append('\n') // LF is added for block selection
}
val fileRange = TextRange(startOffsets[i], endOffsets[i])
var givenTextOffset = fileRange.startOffset
while (givenTextOffset < fileRange.endOffset) {
val element: PsiElement? = file.findElementAt(givenTextOffset)
if (element == null) {
buffer.append(fileText.substring(givenTextOffset, fileRange.endOffset - 1))
break
}
val elTp = element.node.elementType
if (elTp == KtTokens.ESCAPE_SEQUENCE && fileRange.contains(element.range) &&
element.templateContentRange?.contains(fileRange) == true
) {
val tpEntry = element.parent as KtEscapeStringTemplateEntry
changed = true
buffer.append(tpEntry.unescapedValue)
givenTextOffset = element.endOffset
} else if (elTp == KtTokens.SHORT_TEMPLATE_ENTRY_START || elTp == KtTokens.LONG_TEMPLATE_ENTRY_START) {
//Process inner templates without escaping
val tpEntry = element.parent
val inter = fileRange.intersection(tpEntry.range)!!
buffer.append(fileText.substring(inter.startOffset, inter.endOffset))
givenTextOffset = inter.endOffset
} else {
val inter = fileRange.intersection(element.range)!!
buffer.append(fileText.substring(inter.startOffset, inter.endOffset))
givenTextOffset = inter.endOffset
}
}
val blockSelectionPadding = deducedBlockSelectionWidth - fileRange.length
for (j in 0 until blockSelectionPadding) {
buffer.append(' ')
}
}
return if (changed) buffer.toString() else null
}
override fun preprocessOnPaste(project: Project, file: PsiFile, editor: Editor, text: String, rawText: RawText?): String {
if (file !is KtFile) {
return text
}
PsiDocumentManager.getInstance(project).commitDocument(editor.document)
val selectionModel = editor.selectionModel
val begin = file.findElementAt(selectionModel.selectionStart) ?: return text
val beginTp = file.getTemplateIfAtLiteral(selectionModel.selectionStart, begin) ?: return text
val endTp = file.getTemplateIfAtLiteral(selectionModel.selectionEnd) ?: return text
if (beginTp.isSingleQuoted() != endTp.isSingleQuoted()) {
return text
}
val templateTokenSequence = TemplateTokenSequence(text)
return if (beginTp.isSingleQuoted()) {
val res = StringBuilder()
val lineBreak = "\\n\"+\n \""
var endsInLineBreak = false
templateTokenSequence.forEach {
when (it) {
is LiteralChunk -> StringUtil.escapeStringCharacters(it.text.length, it.text, "\$\"", res)
is EntryChunk -> res.append(it.text)
is NewLineChunk -> res.append(lineBreak)
}
endsInLineBreak = it is NewLineChunk
}
return if (endsInLineBreak) {
res.removeSuffix(lineBreak).toString() + "\\n"
} else {
res.toString()
}
} else {
fun TemplateChunk?.indent() = when (this) {
is LiteralChunk -> this.text
is EntryChunk -> this.text
else -> ""
}.takeWhile { it.isWhitespace() }
val indent =
if (beginTp.firstChild?.text == "\"\"\"" &&
beginTp.getQualifiedExpressionForReceiver()?.callExpression?.calleeExpression?.text == "trimIndent" &&
templateTokenSequence.firstOrNull()?.indent() == templateTokenSequence.lastOrNull()?.indent()
) {
begin.parent?.prevSibling?.takeIf { it.text != "\n" && it.text != "\"\"\"" }?.text
} else {
null
} ?: ""
val tripleQuoteRe = Regex("[\"]{3,}")
templateTokenSequence.mapIndexed { index, chunk ->
when (chunk) {
is LiteralChunk -> {
val replaced = chunk.text.replace("\$", "\${'$'}").let { escapedDollar ->
tripleQuoteRe.replace(escapedDollar) { "\"\"" + "\${'\"'}".repeat(it.value.count() - 2) }
}
if (index == 0) replaced else indent + replaced
}
is EntryChunk -> if (index == 0) chunk.text else indent + chunk.text
is NewLineChunk -> "\n"
}
}.joinToString(separator = "")
}
}
}
private sealed class TemplateChunk
private data class LiteralChunk(val text: String) : TemplateChunk()
private data class EntryChunk(val text: String) : TemplateChunk()
private object NewLineChunk : TemplateChunk()
private class TemplateTokenSequence(private val inputString: String) : Sequence<TemplateChunk> {
private fun String.guessIsTemplateEntryStart(): Boolean = if (this.startsWith("\${")) {
true
} else if (this.length > 1 && this[0] == '$') {
val guessedIdentifier = substring(1)
val tokenType = KotlinLexer().apply { start(guessedIdentifier) }.tokenType
tokenType == KtTokens.IDENTIFIER || tokenType == KtTokens.THIS_KEYWORD
} else {
false
}
private fun findTemplateEntryEnd(input: String, from: Int): Int {
val wrapped = '"' + input.substring(from) + '"'
val lexer = KotlinLexer().apply { start(wrapped) }.apply { advance() }
when (lexer.tokenType) {
KtTokens.SHORT_TEMPLATE_ENTRY_START -> {
lexer.advance()
val tokenType = lexer.tokenType
return if (tokenType == KtTokens.IDENTIFIER || tokenType == KtTokens.THIS_KEYWORD) {
from + lexer.tokenEnd - 1
} else {
-1
}
}
KtTokens.LONG_TEMPLATE_ENTRY_START -> {
var depth = 0
while (lexer.tokenType != null) {
if (lexer.tokenType == KtTokens.LONG_TEMPLATE_ENTRY_START) {
depth++
} else if (lexer.tokenType == KtTokens.LONG_TEMPLATE_ENTRY_END) {
depth--
if (depth == 0) {
return from + lexer.currentPosition.offset
}
}
lexer.advance()
}
return -1
}
else -> return -1
}
}
private suspend fun SequenceScope<TemplateChunk>.yieldLiteral(chunk: String) {
val splitLines = LineTokenizer.tokenize(chunk, false, false)
for (i in splitLines.indices) {
if (i != 0) {
yield(NewLineChunk)
}
splitLines[i].takeIf { it.isNotEmpty() }?.let { yield(LiteralChunk(it)) }
}
}
private fun iterTemplateChunks(): Iterator<TemplateChunk> {
if (inputString.isEmpty()) {
return emptySequence<TemplateChunk>().iterator()
}
return iterator {
var from = 0
var to = 0
while (to < inputString.length) {
val c = inputString[to]
if (c == '\\') {
to += 1.toInt()
if (to < inputString.length) to += 1.toInt()
continue
} else if (c == '$') {
if (inputString.substring(to).guessIsTemplateEntryStart()) {
if (from < to) yieldLiteral(inputString.substring(from until to))
from = to
to = findTemplateEntryEnd(inputString, from)
if (to != -1) {
yield(EntryChunk(inputString.substring(from until to)))
} else {
to = inputString.length
yieldLiteral(inputString.substring(from until to))
}
from = to
continue
}
}
to++
}
if (from < to) {
yieldLiteral(inputString.substring(from until to))
}
}
}
override fun iterator(): Iterator<TemplateChunk> = iterTemplateChunks()
}
@TestOnly
fun createTemplateSequenceTokenString(input: String): String {
return TemplateTokenSequence(input).map {
when (it) {
is LiteralChunk -> "LITERAL_CHUNK(${it.text})"
is EntryChunk -> "ENTRY_CHUNK(${it.text})"
is NewLineChunk -> "NEW_LINE()"
}
}.joinToString(separator = "")
}
| apache-2.0 | 370bfdf7e3d1fdb5516f38a0515b1f6a | 41.865248 | 158 | 0.572386 | 4.937908 | false | false | false | false |
siosio/intellij-community | plugins/kotlin/idea/tests/testData/editor/quickDoc/AtConstantWithUnderscore.kt | 4 | 448 | class C {
/** Use [SOME_REFERENCED_VAL] to do something */
fun fo<caret>o() {
}
companion object {
val SOME_REFERENCED_VAL = 1
}
}
//INFO: <div class='definition'><pre><a href="psi_element://C"><code>C</code></a><br>public final fun <b>foo</b>(): Unit</pre></div><div class='content'><p>Use <a href="psi_element://SOME_REFERENCED_VAL">SOME_REFERENCED_VAL</a> to do something</p></div><table class='sections'></table>
| apache-2.0 | e7cd58bb38244dbf906110c804216b03 | 36.333333 | 285 | 0.618304 | 3.223022 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.