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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
ccomeaux/boardgamegeek4android | app/src/main/java/com/boardgamegeek/entities/ArticleEntity.kt | 1 | 416 | package com.boardgamegeek.entities
import android.os.Parcelable
import com.boardgamegeek.provider.BggContract
import kotlinx.parcelize.Parcelize
@Parcelize
data class ArticleEntity(
val id: Int = BggContract.INVALID_ID,
val username: String = "",
val link: String = "",
val postTicks: Long = 0,
val editTicks: Long = 0,
val body: String = "",
val numberOfEdits: Int = 0
) : Parcelable
| gpl-3.0 | d02467b81ea00be97a0ffe0cea92fc3e | 23.470588 | 45 | 0.706731 | 4 | false | false | false | false |
songzhw/Hello-kotlin | AdvancedJ/src/main/kotlin/kotlinx/serial/GsonLimitDemo.kt | 1 | 789 | //package kotlinx.serial
//
//import com.google.gson.Gson
//import kotlinx.serialization.Optional
//import kotlinx.serialization.Serializable
//import kotlinx.serialization.json.JSON
//
//@Serializable
//class Data(val a: Int, @Optional val b: String = "42") {
// @Optional private val c: Long = 9L
//
//// @delegate:Transient val d by lazy { b.length }
//
// override fun toString(): String {
// return "Data(a=$a, b='$b', c=$c)"
// }
//}
//
//fun main(args: Array<String>) {
// val jsonString = """{"a":22}"""
//
// val obj1 = JSON.parse<Data>(jsonString)
// println("szw ktex = $obj1") //=> Data(a=22, b='42', c=9)
//
// val obj2 = Gson().fromJson<Data>(jsonString, Data::class.java)
// println("szw gson = $obj2") //=> Data(a=22, b='null', c=0)
//}
| apache-2.0 | 546a1a9d649893793d047f7e37ee07f6 | 28.222222 | 68 | 0.599493 | 3.022989 | false | false | false | false |
adityaDave2017/my-vocab | app/src/main/java/com/android/vocab/provider/VocabHelper.kt | 1 | 1328 | package com.android.vocab.provider
import android.content.ContentValues
import android.content.Context
import android.content.res.AssetManager
import android.database.sqlite.SQLiteDatabase
import android.database.sqlite.SQLiteOpenHelper
import android.util.Log
import com.android.vocab.provider.VocabHelper.constants.DB_NAME
import com.android.vocab.provider.VocabHelper.constants.DB_VERSION
class VocabHelper(val baseContext: Context) : SQLiteOpenHelper(baseContext, DB_NAME, null, DB_VERSION) {
val LOG_TAG: String = VocabHelper::class.simpleName!!
object constants {
const val SQL_FILE_NAME: String = "vocab.sql"
const val DB_NAME: String = "vocab.sqlite"
const val DB_VERSION: Int = 1
}
override fun onCreate(sqLiteDatabase: SQLiteDatabase?) {
val assetManager: AssetManager = baseContext.assets
var queries: String = ""
assetManager.open(constants.SQL_FILE_NAME).reader().use {
reader -> queries = reader.readText()
}
queries.split(";").forEach({ query ->
if (!query.trim().isEmpty()) {
sqLiteDatabase?.execSQL(query + ";")
}
})
}
override fun onUpgrade(sqLiteDatabase: SQLiteDatabase?, oldVersion: Int, newVersion: Int) {
onCreate(sqLiteDatabase)
}
}
| mit | c9a245fdb8edaf2f833faee426d35366 | 29.883721 | 104 | 0.684488 | 4.41196 | false | false | false | false |
lifedemons/photoviewer | app/src/test/java/com/photoviewer/domain/usecases/GetPhotoDetailsTest.kt | 1 | 1648 | @file:Suppress("IllegalIdentifier")
package com.photoviewer.domain.usecases
import com.nhaarman.mockito_kotlin.mock
import com.nhaarman.mockito_kotlin.whenever
import com.photoviewer.data.entity.PhotoEntity
import com.photoviewer.data.repository.PhotoEntityDataSource
import com.photoviewer.domain.Photo
import org.junit.Before
import org.junit.Test
import org.mockito.Matchers.anyInt
import rx.Observable
import rx.Scheduler
import rx.observers.TestSubscriber
import kotlin.test.assertEquals
class GetPhotoDetailsTest {
private val mPhotoEntityDataSource: PhotoEntityDataSource = mock()
private val mScheduler: Scheduler = mock()
private lateinit var mGetPhotoDetails: GetPhotoDetails
private lateinit var mTestSubscriber: TestSubscriber<Photo>
companion object {
private val FAKE_PHOTO_ID = 123
}
@Before fun setUp() {
mTestSubscriber = TestSubscriber.create()
mGetPhotoDetails = GetPhotoDetails(mScheduler, mScheduler, mPhotoEntityDataSource)
}
@Test fun `should get particular photo`() {
val photoEntity = createPhotoEntity()
assumeDataSourceHasRequestedPhoto(photoEntity)
mGetPhotoDetails.setPhotoId(FAKE_PHOTO_ID)
mGetPhotoDetails.call().subscribe(mTestSubscriber)
assertEquals(FAKE_PHOTO_ID, mTestSubscriber.onNextEvents[0].id)
}
private fun createPhotoEntity() = PhotoEntity().apply {
id = FAKE_PHOTO_ID
}
private fun assumeDataSourceHasRequestedPhoto(photoEntity: PhotoEntity) {
whenever(mPhotoEntityDataSource.photo(anyInt())).thenReturn(
Observable.just(photoEntity))
}
}
| apache-2.0 | 84bb2158bff74bc8fdf652bc02c58166 | 29.518519 | 90 | 0.751214 | 4.539945 | false | true | false | false |
SimonVT/cathode | cathode-sync/src/main/java/net/simonvt/cathode/actions/people/SyncPersonMovieCredits.kt | 1 | 6702 | /*
* Copyright (C) 2016 Simon Vig Therkildsen
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.simonvt.cathode.actions.people
import android.content.ContentProviderOperation
import android.content.Context
import net.simonvt.cathode.actions.CallAction
import net.simonvt.cathode.actions.people.SyncPersonMovieCredits.Params
import net.simonvt.cathode.api.entity.Credit
import net.simonvt.cathode.api.entity.Credits
import net.simonvt.cathode.api.enumeration.Department
import net.simonvt.cathode.api.enumeration.Extended
import net.simonvt.cathode.api.service.PeopleService
import net.simonvt.cathode.common.database.getLong
import net.simonvt.cathode.provider.DatabaseContract.MovieCastColumns
import net.simonvt.cathode.provider.DatabaseContract.MovieCrewColumns
import net.simonvt.cathode.provider.DatabaseSchematic.Tables
import net.simonvt.cathode.provider.ProviderSchematic.MovieCast
import net.simonvt.cathode.provider.ProviderSchematic.MovieCrew
import net.simonvt.cathode.provider.batch
import net.simonvt.cathode.provider.helper.MovieDatabaseHelper
import net.simonvt.cathode.provider.helper.PersonDatabaseHelper
import net.simonvt.cathode.provider.query
import retrofit2.Call
import java.util.ArrayList
import javax.inject.Inject
class SyncPersonMovieCredits @Inject constructor(
private val context: Context,
private val movieHelper: MovieDatabaseHelper,
private val personHelper: PersonDatabaseHelper,
private val peopleService: PeopleService
) : CallAction<Params, Credits>() {
override fun key(params: Params): String = "SyncPersonMovieCredits&traktId=${params.traktId}"
override fun getCall(params: Params): Call<Credits> =
peopleService.movies(params.traktId, Extended.FULL)
override suspend fun handleResponse(params: Params, response: Credits) {
val ops = arrayListOf<ContentProviderOperation>()
val personId = personHelper.getId(params.traktId)
val oldCastCursor = context.contentResolver.query(
MovieCast.withPerson(personId),
arrayOf(Tables.MOVIE_CAST + "." + MovieCastColumns.ID, MovieCastColumns.MOVIE_ID)
)
val oldCast = mutableListOf<Long>()
val movieToCastIdMap = mutableMapOf<Long, Long>()
while (oldCastCursor.moveToNext()) {
val id = oldCastCursor.getLong(MovieCastColumns.ID)
val movieId = oldCastCursor.getLong(MovieCastColumns.MOVIE_ID)
oldCast.add(movieId)
movieToCastIdMap[movieId] = id
}
oldCastCursor.close()
val cast = response.cast
if (cast != null) {
for (credit in cast) {
val movieId = movieHelper.partialUpdate(credit.movie!!)
if (oldCast.remove(movieId)) {
val castId = movieToCastIdMap[movieId]!!
val op = ContentProviderOperation.newUpdate(MovieCast.withId(castId))
.withValue(MovieCastColumns.MOVIE_ID, movieId)
.withValue(MovieCastColumns.PERSON_ID, personId)
.withValue(MovieCastColumns.CHARACTER, credit.character)
.build()
ops.add(op)
} else {
val op = ContentProviderOperation.newInsert(MovieCast.MOVIE_CAST)
.withValue(MovieCastColumns.MOVIE_ID, movieId)
.withValue(MovieCastColumns.PERSON_ID, personId)
.withValue(MovieCastColumns.CHARACTER, credit.character)
.build()
ops.add(op)
}
}
}
for (movieId in oldCast) {
val castId = movieToCastIdMap[movieId]!!
val op = ContentProviderOperation.newDelete(MovieCast.withId(castId)).build()
ops.add(op)
}
val crew = response.crew
if (crew != null) {
insertCrew(ops, personId, Department.PRODUCTION, crew.production)
insertCrew(ops, personId, Department.ART, crew.art)
insertCrew(ops, personId, Department.CREW, crew.crew)
insertCrew(ops, personId, Department.COSTUME_AND_MAKEUP, crew.costume_and_make_up)
insertCrew(ops, personId, Department.DIRECTING, crew.directing)
insertCrew(ops, personId, Department.WRITING, crew.writing)
insertCrew(ops, personId, Department.SOUND, crew.sound)
insertCrew(ops, personId, Department.CAMERA, crew.camera)
}
context.contentResolver.batch(ops)
}
private fun insertCrew(
ops: ArrayList<ContentProviderOperation>,
personId: Long,
department: Department,
crew: List<Credit>?
) {
val oldCrewCursor = context.contentResolver.query(
MovieCrew.withPerson(personId),
arrayOf(Tables.MOVIE_CREW + "." + MovieCrewColumns.ID, MovieCrewColumns.MOVIE_ID),
MovieCrewColumns.CATEGORY + "=?",
arrayOf(department.toString())
)
val oldCrew = mutableListOf<Long>()
val movieToCrewIdMap = mutableMapOf<Long, Long>()
while (oldCrewCursor.moveToNext()) {
val id = oldCrewCursor.getLong(MovieCrewColumns.ID)
val movieId = oldCrewCursor.getLong(MovieCrewColumns.MOVIE_ID)
oldCrew.add(movieId)
movieToCrewIdMap[movieId] = id
}
oldCrewCursor.close()
if (crew != null) {
for (credit in crew) {
val movieId = movieHelper.partialUpdate(credit.movie!!)
if (oldCrew.remove(movieId)) {
val crewId = movieToCrewIdMap.get(movieId)!!
val op = ContentProviderOperation.newUpdate(MovieCrew.withId(crewId))
.withValue(MovieCrewColumns.MOVIE_ID, movieId)
.withValue(MovieCrewColumns.PERSON_ID, personId)
.withValue(MovieCrewColumns.CATEGORY, department.toString())
.withValue(MovieCrewColumns.JOB, credit.job)
.build()
ops.add(op)
} else {
val op = ContentProviderOperation.newInsert(MovieCrew.MOVIE_CREW)
.withValue(MovieCrewColumns.MOVIE_ID, movieId)
.withValue(MovieCrewColumns.PERSON_ID, personId)
.withValue(MovieCrewColumns.CATEGORY, department.toString())
.withValue(MovieCrewColumns.JOB, credit.job)
.build()
ops.add(op)
}
}
}
for (movieId in oldCrew) {
val crewId = movieToCrewIdMap[movieId]!!
val op = ContentProviderOperation.newDelete(MovieCrew.withId(crewId)).build()
ops.add(op)
}
}
data class Params(val traktId: Long)
}
| apache-2.0 | a147bbdded0a101f4c19b06931989ae9 | 37.739884 | 95 | 0.712922 | 4.193992 | false | false | false | false |
cempo/SimpleTodoList | app/src/main/java/com/makeevapps/simpletodolist/viewmodel/EditTaskViewModel.kt | 1 | 4853 | package com.makeevapps.simpletodolist.viewmodel
import android.arch.lifecycle.MutableLiveData
import android.arch.lifecycle.ViewModel
import android.os.Bundle
import com.makeevapps.simpletodolist.App
import com.makeevapps.simpletodolist.Keys
import com.makeevapps.simpletodolist.Keys.KEY_DUE_DATE_IN_MILLIS
import com.makeevapps.simpletodolist.Keys.KEY_TASK_ID
import com.makeevapps.simpletodolist.R
import com.makeevapps.simpletodolist.datasource.db.table.Task
import com.makeevapps.simpletodolist.datasource.preferences.PreferenceManager
import com.makeevapps.simpletodolist.enums.TaskPriority
import com.makeevapps.simpletodolist.repository.TaskRepository
import com.makeevapps.simpletodolist.utils.DateUtils
import com.makeevapps.simpletodolist.utils.extension.asString
import com.makeevapps.simpletodolist.utils.extension.endDayDate
import com.orhanobut.logger.Logger
import io.reactivex.disposables.CompositeDisposable
import java.util.*
import javax.inject.Inject
class EditTaskViewModel : ViewModel() {
@Inject
lateinit var preferenceManager: PreferenceManager
@Inject
lateinit var taskRepository: TaskRepository
private val taskResponse = MutableLiveData<Task>()
private val subTaskResponse = MutableLiveData<List<Task>>()
private val compositeDisposable = CompositeDisposable()
var oldTask: Task = Task("")
var newTask: Task = oldTask
private val is24HoursFormat: Boolean
init {
App.component.inject(this)
is24HoursFormat = preferenceManager.is24HourFormat()
}
/**
* Init logic
* */
fun initStartDate(extras: Bundle) {
val longDate = extras.getLong(KEY_DUE_DATE_IN_MILLIS)
val dueDate = if (longDate > 0) Date(longDate).endDayDate() else null
newTask.dueDate = dueDate
newTask.allDay = true
}
fun initTask(extras: Bundle) {
val taskId = extras.getString(KEY_TASK_ID)
if (!taskId.isNullOrEmpty()) {
compositeDisposable.add(taskRepository.getTaskByIdOnce(taskId!!).subscribe(
{ result ->
oldTask = result
newTask = result
taskResponse.value = result
loadSubTasks(newTask.id)
}
))
} else {
taskResponse.value = newTask
loadSubTasks(newTask.id)
}
}
/**
* Data logic
* */
fun updateDueDate(extras: Bundle) {
val dueDateTimestamp = extras.getLong(KEY_DUE_DATE_IN_MILLIS)
val allDay = extras.getBoolean(Keys.KEY_ALL_DAY, true)
newTask.dueDate = if (dueDateTimestamp > 0) Date(dueDateTimestamp) else null
newTask.allDay = allDay
taskResponse.value = newTask
}
fun getDueDateText(): String? = newTask.dueDate?.asString(DateUtils.SHORT_DATE_FORMAT2)
fun getDueTimeText(): String? = newTask.dueDate?.let {
if (is24HoursFormat) {
it.asString(DateUtils.TIME_24H_FORMAT)
} else {
it.asString(DateUtils.TIME_12H_FORMAT)
}
}
fun removeDate() {
newTask.dueDate = null
newTask.allDay = true
taskResponse.value = newTask
}
fun updatePriority(priority: TaskPriority) {
newTask.priority = priority
taskResponse.value = newTask
}
fun updateTitle(title: String) {
newTask.title = title
}
fun updateDescription(description: String) {
newTask.description = description
}
private fun loadSubTasks(taskId: String) {
compositeDisposable.add(taskRepository.getSubTasks(taskId).subscribe(
{ result ->
subTaskResponse.value = result
}
))
}
fun insertOrUpdateTask(onSuccess: () -> Unit, onError: (message: Int) -> Unit) {
if (newTask.title.isEmpty()) {
onError(R.string.error_title_empty)
} else {
taskRepository.insertOrUpdateTask(newTask).subscribe {
Logger.e(newTask.toString())
onSuccess()
}
}
}
fun deleteTask(onSuccess: () -> Unit) {
compositeDisposable.add(taskRepository.deleteTask(newTask).subscribe({ onSuccess() }))
}
fun insertOrUpdateSubTask(subTask: Task?) {
if (subTask != null) {
compositeDisposable.add(taskRepository.insertOrUpdateTask(subTask).subscribe())
}
}
fun deleteSubTask(subTask: Task?) {
if (subTask != null) {
compositeDisposable.add(taskRepository.deleteTask(subTask).subscribe())
}
}
fun getTaskResponse(): MutableLiveData<Task> = taskResponse
fun getSubTaskResponse(): MutableLiveData<List<Task>> = subTaskResponse
override fun onCleared() {
compositeDisposable.clear()
}
} | mit | d0cbe4c80c8414c01808f03134f102c9 | 29.528302 | 94 | 0.653822 | 4.730019 | false | false | false | false |
AlbRoehm/habitica-android | Habitica/src/main/java/com/habitrpg/android/habitica/ui/activities/PrefsActivity.kt | 1 | 2774 | package com.habitrpg.android.habitica.ui.activities
import android.os.Bundle
import android.support.v7.preference.PreferenceFragmentCompat
import android.support.v7.preference.PreferenceScreen
import android.support.v7.widget.Toolbar
import com.habitrpg.android.habitica.R
import com.habitrpg.android.habitica.components.AppComponent
import com.habitrpg.android.habitica.ui.fragments.preferences.PreferencesFragment
import com.habitrpg.android.habitica.ui.fragments.preferences.PushNotificationsPreferencesFragment
import butterknife.BindView
import com.habitrpg.android.habitica.ui.fragments.preferences.APIPreferenceFragment
import com.habitrpg.android.habitica.ui.fragments.preferences.AuthenticationPreferenceFragment
import com.habitrpg.android.habitica.ui.fragments.preferences.ProfilePreferencesFragment
import kotlinx.android.synthetic.main.activity_prefs.*
class PrefsActivity : BaseActivity(), PreferenceFragmentCompat.OnPreferenceStartScreenCallback {
override fun getLayoutResId(): Int = R.layout.activity_prefs
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setupToolbar(toolbar)
supportFragmentManager.beginTransaction()
.add(R.id.fragment_container, PreferencesFragment())
.commit()
}
override fun injectActivity(component: AppComponent) {
component.inject(this)
}
override fun onSupportNavigateUp(): Boolean {
if (supportFragmentManager.backStackEntryCount > 0) {
onBackPressed()
return true
}
return super.onSupportNavigateUp()
}
override fun onPreferenceStartScreen(preferenceFragment: PreferenceFragmentCompat,
preferenceScreen: PreferenceScreen): Boolean {
val fragment = createNextPage(preferenceScreen)
if (fragment != null) {
val arguments = Bundle()
arguments.putString(PreferenceFragmentCompat.ARG_PREFERENCE_ROOT, preferenceScreen.key)
fragment.arguments = arguments
supportFragmentManager.beginTransaction()
.replace(R.id.fragment_container, fragment)
.addToBackStack(null)
.commit()
return true
}
return false
}
private fun createNextPage(preferenceScreen: PreferenceScreen): PreferenceFragmentCompat? =
when (preferenceScreen.key) {
"profile" -> ProfilePreferencesFragment()
"authentication" -> AuthenticationPreferenceFragment()
"api" -> APIPreferenceFragment()
"pushNotifications" -> PushNotificationsPreferencesFragment()
else -> null
}
}
| gpl-3.0 | 76f532815993c4af259119a1108af740 | 38.628571 | 99 | 0.704758 | 5.743271 | false | false | false | false |
FHannes/intellij-community | java/java-tests/testSrc/com/intellij/codeInspection/Java9UnusedServiceImplementationsTest.kt | 2 | 4528 | /*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.codeInspection
import com.intellij.analysis.AnalysisScope
import com.intellij.openapi.application.ex.PathManagerEx
import com.intellij.openapi.module.ModuleManager
import com.intellij.openapi.roots.ModuleRootModificationUtil
import com.intellij.openapi.util.io.FileUtil
import com.intellij.testFramework.InspectionTestCase
import com.intellij.testFramework.InspectionTestUtil
import com.intellij.testFramework.createGlobalContextForTool
import com.intellij.testFramework.fixtures.LightJava9ModulesCodeInsightFixtureTestCase
import com.intellij.testFramework.fixtures.MultiModuleJava9ProjectDescriptor.ModuleDescriptor
import com.intellij.testFramework.fixtures.MultiModuleJava9ProjectDescriptor.ModuleDescriptor.*
import org.intellij.lang.annotations.Language
/**
* @author Pavel.Dolgov
*/
class Java9UnusedServiceImplementationsTest : LightJava9ModulesCodeInsightFixtureTestCase() {
override fun getTestDataPath() = PathManagerEx.getTestDataPath() + "/inspection/unusedServiceImplementations/"
override fun setUp() {
super.setUp()
moduleInfo("module MAIN { requires API; }", MAIN)
addFile("my/api/MyService.java", "package my.api; public interface MyService { void foo(); }", M2)
}
fun testImplementation() = doTest()
fun testConstructor() = doTest()
fun testProvider() = doTest()
fun testVarargConstructor() = doTest()
fun testUnusedImplementation() = doTest(false)
fun testUnusedConstructor() = doTest(false)
fun testUnusedProvider() = doTest(false)
fun testUnusedVarargConstructor() = doTest(false)
fun testExternalImplementation() = doTest(sameModule = false)
fun testExternalConstructor() = doTest(sameModule = false)
fun testExternalProvider() = doTest(sameModule = false)
fun testUnusedExternalImplementation() = doTest(false, sameModule = false)
fun testUnusedExternalConstructor() = doTest(false, sameModule = false)
fun testUnusedExternalProvider() = doTest(false, sameModule = false)
private fun doTest(withUsage: Boolean = true, sameModule: Boolean = true) {
@Language("JAVA")
val usageText = """
import my.api.MyService;
public class MyApp {
public static void main(String[] args) {
for (MyService service : ServiceLoader.load(MyService.class)) {
service.foo();
}
}
}"""
if (withUsage) addFile("my/app/MyApp.java", usageText, MAIN)
if (sameModule) {
moduleInfo("module API { exports my.api; provides my.api.MyService with my.impl.MyServiceImpl; }", M2)
}
else {
val moduleManager = ModuleManager.getInstance(project)
val m2 = moduleManager.findModuleByName(M2.moduleName)!!
val m4 = moduleManager.findModuleByName(M4.moduleName)!!
ModuleRootModificationUtil.addDependency(m4, m2)
moduleInfo("module API { exports my.api; }", M2)
moduleInfo("module EXT { requires API; provides my.api.MyService with my.ext.MyServiceExt; }", M4)
}
val testPath = testDataPath + "/" + getTestName(true)
val sourceFile = FileUtil.findFirstThatExist("$testPath/MyService${if (sameModule) "Impl" else "Ext"}.java")
assertNotNull("Test data: $testPath", sourceFile)
val implText = String(FileUtil.loadFileText(sourceFile!!))
if (sameModule)
addFile("my/impl/MyServiceImpl.java", implText, M2)
else
addFile("my/ext/MyServiceExt.java", implText, M4)
val toolWrapper = InspectionTestCase.getUnusedDeclarationWrapper()
val scope = AnalysisScope(project)
val globalContext = createGlobalContextForTool(scope, project, listOf(toolWrapper))
InspectionTestUtil.runTool(toolWrapper, scope, globalContext)
InspectionTestUtil.compareToolResults(globalContext, toolWrapper, true, testPath)
}
private fun moduleInfo(@Language("JAVA") moduleInfoText: String, descriptor: ModuleDescriptor) {
addFile("module-info.java", moduleInfoText, descriptor)
}
} | apache-2.0 | 3f83b5257af38447dc8fb1b3f7d72648 | 37.381356 | 112 | 0.746466 | 4.478734 | false | true | false | false |
GeoffreyMetais/vlc-android | application/vlc-android/src/org/videolan/vlc/gui/DiffUtilAdapter.kt | 1 | 2336 | package org.videolan.vlc.gui
import androidx.annotation.MainThread
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.RecyclerView
import kotlinx.coroutines.*
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.channels.actor
@ObsoleteCoroutinesApi
@ExperimentalCoroutinesApi
abstract class DiffUtilAdapter<D, VH : RecyclerView.ViewHolder> : RecyclerView.Adapter<VH>(), CoroutineScope {
override val coroutineContext = Dispatchers.Main.immediate + SupervisorJob()
var dataset: List<D> = listOf()
private set
private val diffCallback by lazy(LazyThreadSafetyMode.NONE) { createCB() }
private val updateActor = actor<List<D>>(capacity = Channel.CONFLATED) {
for (list in channel) internalUpdate(list)
}
protected open fun onUpdateFinished() {}
@MainThread
fun update (list: List<D>) {
updateActor.offer(list)
}
@MainThread
private suspend fun internalUpdate(list: List<D>) {
val (finalList, result) = withContext(Dispatchers.Default) {
val finalList = prepareList(list)
val result = DiffUtil.calculateDiff(diffCallback.apply { update(dataset, finalList) }, detectMoves())
Pair(finalList, result)
}
dataset = finalList
result.dispatchUpdatesTo(this@DiffUtilAdapter)
onUpdateFinished()
}
protected open fun prepareList(list: List<D>) : List<D> = list.toList()
@MainThread
fun isEmpty() = dataset.isEmpty()
open fun getItem(position: Int) = dataset[position]
override fun getItemCount() = dataset.size
protected open fun detectMoves() = false
protected open fun createCB() = DiffCallback<D>()
open class DiffCallback<D> : DiffUtil.Callback() {
lateinit var oldList: List<D>
lateinit var newList: List<D>
fun update(oldList: List<D>, newList: List<D>) {
this.oldList = oldList
this.newList = newList
}
override fun getOldListSize() = oldList.size
override fun getNewListSize() = newList.size
override fun areContentsTheSame(oldItemPosition : Int, newItemPosition : Int) = true
override fun areItemsTheSame(oldItemPosition : Int, newItemPosition : Int) = oldList[oldItemPosition] == newList[newItemPosition]
}
} | gpl-2.0 | edc2082acfb92c027004fe7592867c2e | 32.385714 | 137 | 0.694349 | 4.709677 | false | false | false | false |
schaal/ocreader | app/src/main/java/email/schaal/ocreader/Preferences.kt | 1 | 4566 | /*
* Copyright (C) 2015 Daniel Schaal <[email protected]>
*
* This file is part of OCReader.
*
* OCReader 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.
*
* OCReader 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 OCReader. If not, see <http://www.gnu.org/licenses/>.
*
*/
package email.schaal.ocreader
import android.content.SharedPreferences
import androidx.appcompat.app.AppCompatDelegate
import androidx.appcompat.app.AppCompatDelegate.NightMode
import email.schaal.ocreader.database.model.AllUnreadFolder
import email.schaal.ocreader.database.model.Item
import io.realm.Sort
/**
* Manage Preference values to store in SharedPreferences and retrieve those values.
*/
enum class Preferences constructor(val key: String, private val defaultValue: Any? = null, val changeAction: ChangeAction = ChangeAction.NOTHING) {
/** User preferences */
SHOW_ONLY_UNREAD("show_only_unread", false),
USERNAME("username"),
PASSWORD("password"),
APPTOKEN("apptoken"),
URL("url"),
ORDER("order", Sort.ASCENDING.name, ChangeAction.UPDATE),
SORT_FIELD("sort_field", Item::id.name, ChangeAction.UPDATE),
DARK_THEME("dark_theme", "system", ChangeAction.RECREATE),
ARTICLE_FONT("article_font", "system"),
BREADCRUMBS("breadcrumbs"),
/** System preferences */
SYS_NEEDS_UPDATE_AFTER_SYNC("needs_update_after_sync", false),
SYS_DETECTED_API_LEVEL("detected_api_level");
/**
* What to do after the preference changes
*/
enum class ChangeAction {
NOTHING, // do nothing
RECREATE, // recreate activity
UPDATE // update item recyclerview
}
fun getString(preferences: SharedPreferences): String? {
return preferences.getString(key, defaultValue as String?)
}
fun getBoolean(preferences: SharedPreferences): Boolean {
return preferences.getBoolean(key, (defaultValue as Boolean?) ?: false)
}
fun getBreadCrumbs(preferences: SharedPreferences): List<Pair<Long?, Boolean>> {
return (preferences.getString(key, defaultValue as String?)?.split(";") ?: listOf("${AllUnreadFolder.ID},false")).map {
it.split(",").let { pair ->
pair[0].toLong() to pair[1].toBoolean()
}
}
}
fun getLong(preferences: SharedPreferences): Long {
return preferences.getLong(key, (defaultValue as Long?) ?: 0L)
}
fun getOrder(preferences: SharedPreferences): Sort {
try {
return preferences.getString(key, defaultValue as String?)?.let { Sort.valueOf(it) } ?: Sort.ASCENDING
} catch (e: ClassCastException) {
preferences.edit().remove(key).apply()
}
return Sort.ASCENDING
}
companion object {
@NightMode
fun getNightMode(preferences: SharedPreferences): Int {
return try {
when(preferences.getString(DARK_THEME.key, "system")) {
"always" -> AppCompatDelegate.MODE_NIGHT_YES
"never" -> AppCompatDelegate.MODE_NIGHT_NO
else -> AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM
}
} catch(e: ClassCastException) {
preferences.edit()
.remove(DARK_THEME.key)
.putString(DARK_THEME.key, "system")
.apply()
AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM
}
}
fun hasCredentials(preferences: SharedPreferences): Boolean {
return USERNAME.getString(preferences) != null && SYS_DETECTED_API_LEVEL.getString(preferences) != null
}
fun getPreference(key: String): Preferences? {
for (preference in values()) {
if (preference.key == key) return preference
}
return null
}
}
}
fun SharedPreferences.Editor.putBreadCrumbs(breadcrumbs: List<Pair<Long?, Boolean>>): SharedPreferences.Editor {
putString(Preferences.BREADCRUMBS.key, breadcrumbs.joinToString(";") {
"${it.first},${it.second}"
})
return this
} | gpl-3.0 | 80666f9a933702e10a54147100cc4b2a | 36.130081 | 147 | 0.646518 | 4.570571 | false | false | false | false |
GeoffreyMetais/vlc-android | application/vlc-android/src/org/videolan/vlc/gui/SecondaryActivity.kt | 1 | 7861 | /*
* *************************************************************************
* SecondaryActivity.java
* **************************************************************************
* Copyright © 2015 VLC authors and VideoLAN
* Author: Geoffrey Métais
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
* ***************************************************************************
*/
package org.videolan.vlc.gui
import android.content.Intent
import android.content.res.Configuration
import android.os.Build
import android.os.Bundle
import android.os.Parcelable
import android.view.MenuItem
import android.view.View
import androidx.coordinatorlayout.widget.CoordinatorLayout
import androidx.fragment.app.Fragment
import com.google.android.material.appbar.AppBarLayout
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.ObsoleteCoroutinesApi
import org.videolan.medialibrary.interfaces.Medialibrary
import org.videolan.medialibrary.interfaces.media.MediaWrapper
import org.videolan.resources.AndroidDevices
import org.videolan.resources.KEY_FOLDER
import org.videolan.resources.KEY_GROUP
import org.videolan.resources.util.applyOverscanMargin
import org.videolan.tools.RESULT_RESCAN
import org.videolan.tools.RESULT_RESTART
import org.videolan.tools.isValidUrl
import org.videolan.tools.removeFileProtocole
import org.videolan.vlc.R
import org.videolan.vlc.gui.audio.AudioAlbumsSongsFragment
import org.videolan.vlc.gui.audio.AudioBrowserFragment
import org.videolan.vlc.gui.browser.FileBrowserFragment
import org.videolan.vlc.gui.browser.KEY_MEDIA
import org.videolan.vlc.gui.browser.NetworkBrowserFragment
import org.videolan.vlc.gui.browser.StorageBrowserFragment
import org.videolan.vlc.gui.helpers.UiTools
import org.videolan.vlc.gui.network.MRLPanelFragment
import org.videolan.vlc.gui.video.VideoGridFragment
import org.videolan.vlc.reloadLibrary
import org.videolan.vlc.util.isSchemeNetwork
import org.videolan.vlc.util.validateLocation
@ExperimentalCoroutinesApi
@ObsoleteCoroutinesApi
class SecondaryActivity : ContentActivity() {
private var fragment: Fragment? = null
override val displayTitle = true
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.secondary)
initAudioPlayerContainerActivity()
val fph = findViewById<View>(R.id.fragment_placeholder)
val params = fph.layoutParams as CoordinatorLayout.LayoutParams
if (AndroidDevices.isTv) {
applyOverscanMargin(this)
params.topMargin = resources.getDimensionPixelSize(UiTools.getResourceFromAttribute(this, R.attr.actionBarSize))
} else
params.behavior = AppBarLayout.ScrollingViewBehavior()
fph.requestLayout()
supportActionBar!!.setDisplayHomeAsUpEnabled(true)
if (supportFragmentManager.findFragmentById(R.id.fragment_placeholder) == null) {
val fragmentId = intent.getStringExtra(KEY_FRAGMENT)
fetchSecondaryFragment(fragmentId)
if (fragment == null) {
finish()
return
}
supportFragmentManager.beginTransaction()
.add(R.id.fragment_placeholder, fragment!!)
.commit()
}
}
//Workaround to avoid a crash with webviews. See https://stackoverflow.com/a/60854445/2732052 and https://stackoverflow.com/a/58131421/2732052
override fun applyOverrideConfiguration(overrideConfiguration: Configuration?) {
if (Build.VERSION.SDK_INT in 21..25 && (resources.configuration.uiMode == applicationContext.resources.configuration.uiMode)) {
return
}
super.applyOverrideConfiguration(overrideConfiguration)
}
override fun forceLoadVideoFragment() {
val fragmentId = intent.getStringExtra(KEY_FRAGMENT)
fetchSecondaryFragment(fragmentId)
if (fragment == null) {
finish()
return
}
supportFragmentManager.beginTransaction()
.replace(R.id.fragment_placeholder, fragment!!)
.commit()
}
override fun onResume() {
overridePendingTransition(0, 0)
super.onResume()
}
override fun onPause() {
if (isFinishing)
overridePendingTransition(0, 0)
super.onPause()
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode == ACTIVITY_RESULT_SECONDARY) {
if (resultCode == RESULT_RESCAN) this.reloadLibrary()
}
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
// Handle item selection
when (item.itemId) {
R.id.ml_menu_refresh -> {
val ml = Medialibrary.getInstance()
if (!ml.isWorking) reloadLibrary()
return true
}
}
return super.onOptionsItemSelected(item)
}
private fun fetchSecondaryFragment(id: String) {
when (id) {
ALBUMS_SONGS -> {
fragment = AudioAlbumsSongsFragment().apply {
val args = Bundle(1)
args.putParcelable(AudioBrowserFragment.TAG_ITEM, intent.getParcelableExtra<Parcelable>(AudioBrowserFragment.TAG_ITEM))
arguments = args
}
}
ABOUT -> fragment = AboutFragment()
STREAMS -> fragment = MRLPanelFragment()
HISTORY -> fragment = HistoryFragment()
VIDEO_GROUP_LIST -> {
fragment = VideoGridFragment().apply {
arguments = Bundle(2).apply {
putParcelable(KEY_FOLDER, intent.getParcelableExtra<Parcelable>(KEY_FOLDER))
putParcelable(KEY_GROUP, intent.getParcelableExtra<Parcelable>(KEY_GROUP))
}
}
}
STORAGE_BROWSER -> {
fragment = StorageBrowserFragment()
setResult(RESULT_RESTART)
}
FILE_BROWSER -> {
val media = intent.getParcelableExtra(KEY_MEDIA) as MediaWrapper
fragment = if(media.uri.scheme.isSchemeNetwork()) NetworkBrowserFragment()
else FileBrowserFragment()
fragment?.apply {
arguments = Bundle(2).apply {
putParcelable(KEY_MEDIA, media)
}
}
}
else -> throw IllegalArgumentException("Wrong fragment id.")
}
}
companion object {
const val TAG = "VLC/SecondaryActivity"
const val ACTIVITY_RESULT_SECONDARY = 3
const val KEY_FRAGMENT = "fragment"
const val ALBUMS_SONGS = "albumsSongs"
const val ABOUT = "about"
const val STREAMS = "streams"
const val HISTORY = "history"
const val VIDEO_GROUP_LIST = "videoGroupList"
const val STORAGE_BROWSER = "storage_browser"
const val FILE_BROWSER = "file_browser"
}
}
| gpl-2.0 | bec5cbf357ff4cb06af277c945778162 | 37.905941 | 146 | 0.646265 | 4.96149 | false | false | false | false |
QuickBlox/quickblox-android-sdk | sample-chat-kotlin/app/src/main/java/com/quickblox/sample/chat/kotlin/ui/activity/AppInfoActivity.kt | 1 | 3307 | package com.quickblox.sample.chat.kotlin.ui.activity
import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.os.Bundle
import android.text.Spannable
import android.text.SpannableString
import android.text.style.ForegroundColorSpan
import android.view.View
import android.widget.TextView
import com.quickblox.auth.session.QBSettings
import com.quickblox.sample.chat.kotlin.BuildConfig
import com.quickblox.sample.chat.kotlin.R
class AppInfoActivity : BaseActivity() {
private lateinit var appVersionTextView: TextView
private lateinit var sdkVersionTextView: TextView
private lateinit var appIDTextView: TextView
private lateinit var authKeyTextView: TextView
private lateinit var authSecretTextView: TextView
private lateinit var accountKeyTextView: TextView
private lateinit var apiDomainTextView: TextView
private lateinit var chatDomainTextView: TextView
private lateinit var appQAVersionTextView: TextView
companion object {
fun start(context: Context) = context.startActivity(Intent(context, AppInfoActivity::class.java))
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_appinfo)
initUI()
fillUI()
}
private fun initUI() {
appVersionTextView = findViewById(R.id.tv_app_version)
sdkVersionTextView = findViewById(R.id.tv_sdk_version)
appIDTextView = findViewById(R.id.tv_app_id)
authKeyTextView = findViewById(R.id.tv_auth_key)
authSecretTextView = findViewById(R.id.tv_auth_secret)
accountKeyTextView = findViewById(R.id.tv_account_key)
apiDomainTextView = findViewById(R.id.tv_api_domain)
chatDomainTextView = findViewById(R.id.tv_chat_domain)
appQAVersionTextView = findViewById(R.id.tv_qa_version)
}
private fun fillUI() {
supportActionBar?.setDisplayHomeAsUpEnabled(true)
supportActionBar?.title = getString(R.string.appinfo_title)
appVersionTextView.text = BuildConfig.VERSION_NAME
sdkVersionTextView.text = com.quickblox.BuildConfig.VERSION_NAME
appIDTextView.text = QBSettings.getInstance().applicationId
authKeyTextView.text = QBSettings.getInstance().authorizationKey
authSecretTextView.text = QBSettings.getInstance().authorizationSecret
accountKeyTextView.text = QBSettings.getInstance().accountKey
apiDomainTextView.text = QBSettings.getInstance().serverApiDomain
chatDomainTextView.text = QBSettings.getInstance().chatEndpoint
if (BuildConfig.IS_QA) {
val appVersion = BuildConfig.VERSION_NAME
val versionQACode = BuildConfig.VERSION_QA_CODE.toString()
val qaVersion = "$appVersion.$versionQACode"
val spannable = SpannableString(qaVersion)
spannable.setSpan(ForegroundColorSpan(Color.RED), appVersion.length + 1,
qaVersion.length, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
appQAVersionTextView.setText(spannable, TextView.BufferType.SPANNABLE)
appQAVersionTextView.visibility = View.VISIBLE
findViewById<View>(R.id.text_qa_version_title).visibility = View.VISIBLE
}
}
} | bsd-3-clause | 3bb8cf780e58b1ab3770f2242542d87e | 42.526316 | 105 | 0.736317 | 4.751437 | false | true | false | false |
rsiebert/TVHClient | app/src/main/java/org/tvheadend/tvhclient/ui/features/information/ChangeLogFragment.kt | 1 | 11866 | package org.tvheadend.tvhclient.ui.features.information
import android.content.Context
import android.graphics.Color
import android.os.Build
import android.os.Bundle
import android.view.*
import android.webkit.WebView
import android.widget.ProgressBar
import androidx.core.view.forEach
import androidx.fragment.app.Fragment
import androidx.preference.PreferenceManager
import kotlinx.coroutines.*
import org.tvheadend.tvhclient.BuildConfig
import org.tvheadend.tvhclient.R
import org.tvheadend.tvhclient.ui.common.interfaces.HideNavigationDrawerInterface
import org.tvheadend.tvhclient.ui.common.interfaces.BackPressedInterface
import org.tvheadend.tvhclient.ui.common.interfaces.LayoutControlInterface
import org.tvheadend.tvhclient.ui.common.interfaces.ToolbarInterface
import org.tvheadend.tvhclient.util.extensions.gone
import org.tvheadend.tvhclient.util.extensions.visible
import org.tvheadend.tvhclient.util.getThemeId
import timber.log.Timber
import java.io.BufferedReader
import java.io.InputStream
import java.io.InputStreamReader
class ChangeLogFragment : Fragment(), BackPressedInterface, HideNavigationDrawerInterface {
private val job = Job()
private val scope = CoroutineScope(Dispatchers.IO + job)
private var showFullChangeLog = false
private var versionName: String = ""
private var webView: WebView? = null
private var loadingView: ProgressBar? = null
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
val view = if (Build.VERSION.SDK_INT in 21..25) {
inflater.inflate(R.layout.webview_fragment_for_lollipop, container, false)
} else {
inflater.inflate(R.layout.webview_fragment, container, false)
}
webView = view.findViewById(R.id.webview)
loadingView = view.findViewById(R.id.loading_view)
return view
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
if (activity is ToolbarInterface) {
(activity as ToolbarInterface).setTitle(getString(R.string.pref_changelog))
}
if (activity is LayoutControlInterface) {
(activity as LayoutControlInterface).forceSingleScreenLayout()
}
showFullChangeLog = arguments?.getBoolean("showFullChangelog", true) ?: true
versionName = arguments?.getString("versionNameForChangelog", BuildConfig.VERSION_NAME) ?: BuildConfig.VERSION_NAME
setHasOptionsMenu(true)
// Make the background transparent to remove flickering. This avoids
// seeing the default theme background color before the stylesheets are loaded.
webView?.setBackgroundColor(Color.argb(0, 0, 0, 0))
Timber.d("Showing changelog, show full changelog: $showFullChangeLog")
activity?.let {
scope.launch { loadChangeLogContents(it, versionName, showFullChangeLog) }
}
}
override fun onDestroy() {
super.onDestroy()
job.cancel()
}
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
outState.putBoolean("showFullChangelog", showFullChangeLog)
outState.putString("versionNameForChangelog", versionName)
}
private suspend fun loadChangeLogContents(context: Context, versionName: String, showFullChangeLog: Boolean) {
Timber.d("Loading data in background via suspend function")
val deferredLoader = scope.async {
Timber.d("Invoking ChangeLogLoader")
return@async ChangeLogLoader(context, versionName).getChangeLogFromFile(showFullChangeLog)
}
// Switch the context to the main thread to call the following method
withContext(Dispatchers.Main) {
Timber.d("Waiting until contents have been loaded")
val contents = deferredLoader.await()
Timber.d("Contents have been loaded")
onFileContentsLoaded(contents)
}
}
override fun onPrepareOptionsMenu(menu: Menu) {
menu.forEach { it.isVisible = false }
menu.findItem(R.id.menu_show_full_changelog)?.isVisible = !showFullChangeLog
}
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
super.onCreateOptionsMenu(menu, inflater)
inflater.inflate(R.menu.changelog_options_menu, menu)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
android.R.id.home -> {
onBackPressed()
return true
}
R.id.menu_show_full_changelog -> {
scope.launch { loadChangeLogContents(requireContext(), versionName, true) }
return true
}
}
return super.onOptionsItemSelected(item)
}
override fun onBackPressed() {
// Save the information that the changelog was shown
val sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context)
val editor = sharedPreferences.edit()
editor.putString("versionNameForChangelog", BuildConfig.VERSION_NAME)
editor.apply()
activity?.supportFragmentManager?.popBackStack()
}
private fun onFileContentsLoaded(fileContent: String) {
Timber.d("Changelog data was loaded, file contents is not empty ${fileContent.isNotEmpty()}, fragment is added $isAdded and is visible $isVisible")
if (fileContent.isNotEmpty() && isAdded) {
Timber.d("Changelog data is available, showing contents in webview")
webView?.loadDataWithBaseURL("file:///android_asset/", fileContent, "text/html", "utf-8", null)
webView?.visible()
loadingView?.gone()
}
}
internal class ChangeLogLoader(context: Context, private val lastAppVersion: String) {
private var inputStream: InputStream
private var isLightTheme: Boolean = false
private var listMode = ListMode.NONE
private var stringBuffer = StringBuffer()
// modes for HTML-Lists (bullet, numbered)
private enum class ListMode {
NONE, ORDERED, UNORDERED
}
init {
Timber.d("Creating input stream from changelog file")
inputStream = context.resources.openRawResource(R.raw.changelog)
isLightTheme = getThemeId(context) == R.style.CustomTheme_Light
}
fun getChangeLogFromFile(loadFullChangelog: Boolean): String {
Timber.d("Loading full changelog $loadFullChangelog")
// Add the style sheet depending on the used theme
stringBuffer = StringBuffer()
stringBuffer.append("<html><head>")
if (isLightTheme) {
stringBuffer.append("<link href=\"html/styles_light.css\" type=\"text/css\" rel=\"stylesheet\"/>")
} else {
stringBuffer.append("<link href=\"html/styles_dark.css\" type=\"text/css\" rel=\"stylesheet\"/>")
}
stringBuffer.append("</head><body>")
val bufferedReader = BufferedReader(InputStreamReader(inputStream))
// ignore further version sections if set to true
var advanceToEOVS = false
// Loop through the contents for the file line by line
while (true) {
var line = bufferedReader.readLine() ?: break
// Remove any spaces before or after the line
line = line.trim()
// Get the first character which indicates the type of content on each line
val marker: Char = if (line.isNotEmpty()) line[0] else '0'
if (marker == '$') {
// begin of a version section
closeList()
val version = line.substring(1).trim()
// stop output?
if (!loadFullChangelog) {
if (lastAppVersion == version) {
advanceToEOVS = true
} else if (version == "END_OF_CHANGE_LOG") {
advanceToEOVS = false
}
}
} else if (!advanceToEOVS) {
when (marker) {
'%' -> {
// line contains version title
closeList()
stringBuffer.append("<div class=\"title\">")
stringBuffer.append(line.substring(1))
stringBuffer.append("</div>\n")
}
'_' -> {
// line contains version title
closeList()
stringBuffer.append("<div class=\"subtitle\">")
stringBuffer.append(line.substring(1))
stringBuffer.append("</div>\n")
}
'!' -> {
// line contains free text
closeList()
stringBuffer.append("<div class=\"content\">")
stringBuffer.append(line.substring(1))
stringBuffer.append("</div>\n")
}
'#' -> {
// line contains numbered list item
openList(ListMode.ORDERED)
stringBuffer.append("<li class=\"list_content\">")
stringBuffer.append(line.substring(1))
stringBuffer.append("</li>\n")
}
'*' -> {
// line contains bullet list item
openList(ListMode.UNORDERED)
stringBuffer.append("<li class=\"list_content\">")
stringBuffer.append(line.substring(1))
stringBuffer.append("</li>\n")
}
else -> {
// no special character: just use line as is
closeList()
stringBuffer.append(line)
stringBuffer.append("\n")
}
}
}
}
closeList()
bufferedReader.close()
stringBuffer.append("</body></html>")
Timber.d("Done reading changelog file")
return stringBuffer.toString()
}
private fun openList(listMode: ListMode) {
if (this.listMode != listMode) {
closeList()
if (listMode == ListMode.ORDERED) {
stringBuffer.append("<ol>\n")
} else if (listMode == ListMode.UNORDERED) {
stringBuffer.append("<ul>\n")
}
this.listMode = listMode
}
}
private fun closeList() {
if (listMode == ListMode.ORDERED) {
stringBuffer.append("</ol>\n")
} else if (listMode == ListMode.UNORDERED) {
stringBuffer.append("</ul>\n")
}
listMode = ListMode.NONE
}
}
companion object {
fun newInstance(versionName: String = BuildConfig.VERSION_NAME, showFullChangelog: Boolean = true): ChangeLogFragment {
val f = ChangeLogFragment()
val args = Bundle()
args.putBoolean("showFullChangelog", showFullChangelog)
args.putString("versionNameForChangelog", versionName)
f.arguments = args
return f
}
}
}
| gpl-3.0 | 0e6bc92ab4e5645763a6257814807536 | 40.635088 | 155 | 0.576774 | 5.374094 | false | false | false | false |
nemerosa/ontrack | ontrack-extension-indicators/src/main/java/net/nemerosa/ontrack/extension/indicators/ui/graphql/GQLRootQueryConfigurableIndicators.kt | 1 | 1656 | package net.nemerosa.ontrack.extension.indicators.ui.graphql
import graphql.Scalars.GraphQLString
import graphql.schema.GraphQLFieldDefinition
import net.nemerosa.ontrack.extension.indicators.computing.ConfigurableIndicatorService
import net.nemerosa.ontrack.graphql.schema.GQLRootQuery
import net.nemerosa.ontrack.graphql.support.listType
import org.springframework.stereotype.Component
@Component
class GQLRootQueryConfigurableIndicators(
private val gqlConfigurableIndicatorTypeState: GQLTypeConfigurableIndicatorTypeState,
private val configurableIndicatorService: ConfigurableIndicatorService,
): GQLRootQuery {
override fun getFieldDefinition(): GraphQLFieldDefinition = GraphQLFieldDefinition.newFieldDefinition()
.name("configurableIndicators")
.description("List of configurable indicators")
.argument {
it.name("category")
.description("Filter the indicators on their category ID")
.type(GraphQLString)
}
.argument {
it.name("type")
.description("Filter the indicators on their type ID")
.type(GraphQLString)
}
.type(listType(gqlConfigurableIndicatorTypeState.typeRef))
.dataFetcher { env ->
val category: String? = env.getArgument("category")
val type: String? = env.getArgument("type")
configurableIndicatorService.getConfigurableIndicatorStates().filter {
category == null || it.type.category.id == category
}.filter {
type == null || it.type.id == type
}
}
.build()
} | mit | 70d298cad40780f59d51bf2f3d7eacbd | 40.425 | 107 | 0.687198 | 5.394137 | false | true | false | false |
bailuk/AAT | aat-gtk/src/main/kotlin/ch/bailu/aat_gtk/view/map/control/Bar.kt | 1 | 1943 | package ch.bailu.aat_gtk.view.map.control
import ch.bailu.aat_gtk.config.Layout
import ch.bailu.aat_gtk.config.Strings
import ch.bailu.aat_gtk.lib.extensions.margin
import ch.bailu.aat_gtk.lib.extensions.setIcon
import ch.bailu.aat_lib.map.edge.EdgeViewInterface
import ch.bailu.aat_lib.map.edge.Position
import ch.bailu.gtk.GTK
import ch.bailu.gtk.gtk.*
open class Bar(private val pos: Position): EdgeViewInterface {
companion object {
private fun createBox(pos: Position): Box {
when (pos) {
Position.TOP ->
return Box(Orientation.HORIZONTAL, 0).apply {
halign = Align.CENTER
valign = Align.START
}
Position.BOTTOM ->
return Box(Orientation.HORIZONTAL, 0).apply {
halign = Align.CENTER
valign = Align.END
}
Position.LEFT ->
return Box(Orientation.VERTICAL, 0).apply {
valign = Align.CENTER
halign = Align.START
}
Position.RIGHT ->
return Box(Orientation.VERTICAL, 0).apply {
valign = Align.CENTER
halign = Align.END
}
}
}
}
val box = createBox(pos).apply {
visible = GTK.FALSE
addCssClass(Strings.mapControl)
}
fun add(image: String): Button {
val button = Button()
add(button)
button.setIcon(image)
return button
}
fun add(widget: Widget) {
widget.margin(Layout.margin)
box.append(widget)
}
override fun hide() {
box.visible = GTK.FALSE
}
override fun pos(): Position {
return pos
}
override fun show() {
box.visible = GTK.TRUE
}
}
| gpl-3.0 | fe368fe84da67d9a44486b46693a1dfa | 27.573529 | 65 | 0.518785 | 4.518605 | false | false | false | false |
nickbutcher/plaid | core/src/main/java/io/plaidapp/core/designernews/data/api/DesignerNewsSearchConverter.kt | 1 | 2493 | /*
* Copyright 2018 Google LLC.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.plaidapp.core.designernews.data.api
import java.lang.reflect.Type
import java.util.regex.Pattern
import okhttp3.ResponseBody
import org.jsoup.Jsoup
import org.jsoup.nodes.Element
import retrofit2.Converter
import retrofit2.Retrofit
private val PATTERN_STORY_ID = Pattern.compile("https:\\/\\/www\\.designernews\\.co\\/stories\\/([0-9]*)")
/**
* Designer News API doesn't have a search endpoint, so we have to scrape the HTML ourselves.
*
* This extracts the IDs from the HTML and returns them as a list. We can use these IDs with the API to get the rest of
* the information that we need.
*/
object DesignerNewsSearchConverter : Converter<ResponseBody, List<String>> {
/** Factory for creating converter. We only care about decoding responses. */
class Factory : Converter.Factory() {
override fun responseBodyConverter(
type: Type?,
annotations: Array<Annotation>?,
retrofit: Retrofit?
): Converter<ResponseBody, *>? {
return if (annotations != null && annotations.any { it is DesignerNewsSearch }) {
DesignerNewsSearchConverter
} else {
null
}
}
}
override fun convert(body: ResponseBody): List<String> {
val searchResults = Jsoup.parse(body.string(), DesignerNewsService.ENDPOINT)
.select("li.search-page-result > a")
return searchResults.mapNotNull { parseSearchResult(it) }
}
private fun parseSearchResult(searchResult: Element): String? {
if (searchResult.select(".search-result-content-type").text() != "story") {
return null
}
val idMatcher = PATTERN_STORY_ID.matcher(searchResult.attr("href"))
return if (idMatcher.find() && idMatcher.groupCount() == 1) {
idMatcher.group(1)
} else {
null
}
}
}
| apache-2.0 | d87d901cc88444abe803100f7bb8e5b9 | 34.112676 | 119 | 0.665864 | 4.373684 | false | false | false | false |
equeim/tremotesf-android | gradle-plugin/src/main/kotlin/org/equeim/tremotesf/gradle/utils/CMake.kt | 1 | 2607 | package org.equeim.tremotesf.gradle.utils
import org.gradle.api.Project
import org.gradle.api.invocation.Gradle
import org.gradle.api.logging.Logger
import java.io.File
private const val CMAKE = "cmake"
internal enum class CMakeMode {
Build,
Install
}
internal fun executeCMake(
mode: CMakeMode,
printBuildLogOnError: Boolean,
cmakeBinaryDir: File?,
buildDir: File,
logger: Logger,
gradle: Gradle
): ExecResult =
executeCMakeImpl(
when (mode) {
CMakeMode.Build -> listOf(
"--build",
buildDir.toString(),
"--parallel",
gradle.startParameter.maxWorkerCount.toString(),
"--verbose"
)
CMakeMode.Install -> listOf("--install", buildDir.toString(), "--verbose")
},
cmakeBinaryDir,
logger,
when (mode) {
CMakeMode.Build -> ExecOutputMode.RedirectOutputToFile(buildDir.resolve(BUILD_LOG_FILE), printBuildLogOnError)
CMakeMode.Install -> ExecOutputMode.RedirectOutputToFile(buildDir.resolve(INSTALL_LOG_FILE), printBuildLogOnError)
}
)
internal fun printCMakeInfo(cmakeBinaryDir: File?, logger: Logger) {
val info = getCMakeInfoOrNull(cmakeBinaryDir, logger) ?: return
logger.lifecycle("Using CMake {} from {}", info.version, info.executablePath)
}
data class CMakeInfo(val executablePath: String, val version: String)
fun getCMakeInfoOrNull(
cmakeBinaryDir: File?,
logger: Logger
): CMakeInfo? {
val execResult = runCatching {
executeCMakeImpl(listOf("--version"), cmakeBinaryDir, logger, ExecOutputMode.CaptureOutput)
}.getOrNull() ?: return null
val executablePath = execResult.executablePath ?: run {
logger.error("CMake executable path is unknown")
return null
}
val output = execResult.outputString()
val version = runCatching {
output
.lineSequence()
.first()
.trim()
.split(Regex("\\s"))
.last()
}.getOrElse {
logger.error("Failed to parse output of `cmake --version`", it)
logger.error("Output:")
System.err.println(output)
return null
}
return CMakeInfo(executablePath, version)
}
private fun executeCMakeImpl(
args: List<String>,
cmakeBinaryDir: File?,
logger: Logger,
outputMode: ExecOutputMode,
): ExecResult = executeCommand(listOf(cmakeBinaryDir?.resolve(CMAKE)?.toString() ?: CMAKE) + args, logger, outputMode = outputMode) {
cmakeBinaryDir?.let { prependPath(it) }
}
| gpl-3.0 | 8fb76cf510456b3ac3098260fe9af91f | 30.035714 | 133 | 0.643652 | 4.232143 | false | false | false | false |
inlacou/VolleyControllerLibrary | volleycontroller/src/main/java/com/libraries/inlacou/volleycontroller/CustomHurlStack.kt | 1 | 9748 | package com.libraries.inlacou.volleycontroller
import android.util.Log
import com.android.volley.AuthFailureError
import com.android.volley.Header
import com.android.volley.Request
import com.android.volley.toolbox.BaseHttpStack
import com.android.volley.toolbox.HttpResponse
import timber.log.Timber
import java.io.DataOutputStream
import java.io.FilterInputStream
import java.io.IOException
import java.io.InputStream
import java.net.HttpURLConnection
import java.net.URL
import java.util.*
import javax.net.ssl.HttpsURLConnection
import javax.net.ssl.SSLSocketFactory
/*
* Copyright (C) 2011 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.
*/ /** A [BaseHttpStack] based on [HttpURLConnection]. */
class CustomHurlStack
/**
* @param mUrlRewriter Rewriter to use for request URLs
* @param mSslSocketFactory SSL factory to use for HTTPS connections
*/
private constructor(private val mUrlRewriter: UrlRewriter?, private val mSslSocketFactory: SSLSocketFactory? = /* sslSocketFactory = */null) : BaseHttpStack() {
/** An interface for transforming URLs before use. */
interface UrlRewriter {
/**
* Returns a URL to use instead of the provided one, or null to indicate this URL should not
* be used at all.
*/
fun rewriteUrl(originalUrl: String?): String?
}
constructor() : this( /* urlRewriter = */null) {}
@Throws(IOException::class, AuthFailureError::class)
override fun executeRequest(request: Request<*>, additionalHeaders: Map<String, String>): HttpResponse {
var url = request.url
val map = HashMap<String, String>()
map.putAll(request.headers)
map.putAll(additionalHeaders)
if (mUrlRewriter != null) {
val rewritten = mUrlRewriter.rewriteUrl(url)
?: throw IOException("URL blocked by rewriter: $url")
url = rewritten
}
val parsedUrl = URL(url)
val connection = openConnection(parsedUrl, request)
var keepConnectionOpen = false
return try {
for (headerName in map.keys) {
connection.addRequestProperty(headerName, map[headerName])
}
setConnectionParametersForRequest(connection, request)
// Initialize HttpResponse with data from the HttpURLConnection.
val responseCode = connection.responseCode
if (responseCode == -1) {
// -1 is returned by getResponseCode() if the response code could not be retrieved.
// Signal to the caller that something was wrong with the connection.
throw IOException("Could not retrieve response code from HttpUrlConnection.")
}
if (!hasResponseBody(request.method, responseCode)) {
return HttpResponse(responseCode, convertHeaders(connection.headerFields))
}
// Need to keep the connection open until the stream is consumed by the caller. Wrap the
// stream such that close() will disconnect the connection.
keepConnectionOpen = true
HttpResponse(
responseCode,
convertHeaders(connection.headerFields),
connection.contentLength,
UrlConnectionInputStream(connection))
} finally {
if (!keepConnectionOpen) {
connection.disconnect()
}
}
}
/**
* Wrapper for a [HttpURLConnection]'s InputStream which disconnects the connection on
* stream close.
*/
internal class UrlConnectionInputStream(private val mConnection: HttpURLConnection) : FilterInputStream(inputStreamFromConnection(mConnection)) {
@Throws(IOException::class)
override fun close() {
super.close()
mConnection.disconnect()
}
}
/** Create an [HttpURLConnection] for the specified `url`. */
@Throws(IOException::class)
private fun createConnection(url: URL): HttpURLConnection {
val connection = url.openConnection() as HttpURLConnection
// Workaround for the M release HttpURLConnection not observing the
// HttpURLConnection.setFollowRedirects() property.
// https://code.google.com/p/android/issues/detail?id=194495
connection.instanceFollowRedirects = HttpURLConnection.getFollowRedirects()
return connection
}
/**
* Opens an [HttpURLConnection] with parameters.
*
* @param url
* @return an open connection
* @throws IOException
*/
@Throws(IOException::class)
private fun openConnection(url: URL, request: Request<*>): HttpURLConnection {
val connection = createConnection(url)
val timeoutMs = request.timeoutMs
connection.connectTimeout = timeoutMs
connection.readTimeout = timeoutMs
connection.useCaches = false
connection.doInput = true
// use caller-provided custom SslSocketFactory, if any, for HTTPS
if ("https" == url.protocol && mSslSocketFactory != null) {
(connection as HttpsURLConnection).sslSocketFactory = mSslSocketFactory
}
return connection
}
companion object {
private const val HTTP_CONTINUE = 100
private fun convertHeaders(responseHeaders: Map<String?, List<String>>): List<Header> {
val headerList: MutableList<Header> = ArrayList(responseHeaders.size)
for ((key, value1) in responseHeaders) {
// HttpUrlConnection includes the status line as a header with a null key; omit it here
// since it's not really a header and the rest of Volley assumes non-null keys.
if (key != null) {
for (value in value1) {
headerList.add(Header(key, value))
}
}
}
return headerList
}
/**
* Checks if a response message contains a body.
*
* @see [RFC 7230 section 3.3](https://tools.ietf.org/html/rfc7230.section-3.3)
*
* @param requestMethod request method
* @param responseCode response status code
* @return whether the response has a body
*/
private fun hasResponseBody(requestMethod: Int, responseCode: Int): Boolean {
return (requestMethod != Request.Method.HEAD && !(HTTP_CONTINUE <= responseCode && responseCode < HttpURLConnection.HTTP_OK)
&& responseCode != HttpURLConnection.HTTP_NO_CONTENT && responseCode != HttpURLConnection.HTTP_NOT_MODIFIED)
}
/**
* Initializes an [InputStream] from the given [HttpURLConnection].
*
* @param connection
* @return an HttpEntity populated with data from `connection`.
*/
private fun inputStreamFromConnection(connection: HttpURLConnection): InputStream {
return try {
connection.inputStream
} catch (ioe: IOException) {
connection.errorStream
}
}
@Throws(IOException::class, AuthFailureError::class)
private fun setConnectionParametersForRequest(connection: HttpURLConnection, request: Request<*>) {
if(VolleyController.log) Timber.d("setConnectionParametersForRequest: ${request.method}")
when (request.method) {
Request.Method.DEPRECATED_GET_OR_POST -> {
// This is the deprecated way that needs to be handled for backwards compatibility.
// If the request's post body is null, then the assumption is that the request is
// GET. Otherwise, it is assumed that the request is a POST.
val postBody = request.postBody
if (postBody != null) {
if(VolleyController.log) Timber.w("postBody!=null so setting request method to POST")
connection.requestMethod = "POST"
addBody(connection, request, postBody)
}
if(VolleyController.log) Timber.d("setRequestMethod DEPRECATED_GET_OR_POST")
}
Request.Method.GET -> {
// Not necessary to set the request method because connection defaults to GET but
// being explicit here.
connection.requestMethod = "GET"
if(VolleyController.log) Timber.d("setRequestMethod GET")
//Adding a body makes it a POST for google or PokeApi
//addBodyIfExists(connection, request)
}
Request.Method.DELETE -> {
connection.requestMethod = "DELETE"
if(VolleyController.log) Timber.d("setRequestMethod DELETE")
addBodyIfExists(connection, request)
}
Request.Method.POST -> {
connection.requestMethod = "POST"
if(VolleyController.log) Timber.d("setRequestMethod POST")
addBodyIfExists(connection, request)
}
Request.Method.PUT -> {
connection.requestMethod = "PUT"
if(VolleyController.log) Timber.d("setRequestMethod PUT")
addBodyIfExists(connection, request)
}
Request.Method.HEAD -> connection.requestMethod = "HEAD"
Request.Method.OPTIONS -> connection.requestMethod = "OPTIONS"
Request.Method.TRACE -> connection.requestMethod = "TRACE"
Request.Method.PATCH -> {
connection.requestMethod = "PATCH"
addBodyIfExists(connection, request)
}
else -> throw IllegalStateException("Unknown method type.")
}
}
@Throws(IOException::class, AuthFailureError::class)
private fun addBodyIfExists(connection: HttpURLConnection, request: Request<*>) {
val body = request.body ?: byteArrayOf()
if (body != null ) {
if(VolleyController.log) Timber.d("addBodyIfExists | ${body.map { it }}")
addBody(connection, request, body)
}
}
@Throws(IOException::class)
private fun addBody(connection: HttpURLConnection, request: Request<*>, body: ByteArray) {
// Prepare output. There is no need to set Content-Length explicitly,
// since this is handled by HttpURLConnection using the size of the prepared
// output stream.
connection.doOutput = true
connection.addRequestProperty("Content-Type", request.bodyContentType)
val out = DataOutputStream(connection.outputStream)
out.write(body)
out.close()
}
}
} | gpl-3.0 | 5780c311d289ee350704d9429ee367f1 | 36.496154 | 161 | 0.726713 | 4.088926 | false | false | false | false |
adgvcxz/ViewModel | viewmodel/src/main/kotlin/com/adgvcxz/ViewModelBuilder.kt | 1 | 1542 | package com.adgvcxz
import io.reactivex.rxjava3.core.Observable
import io.reactivex.rxjava3.disposables.Disposable
import io.reactivex.rxjava3.functions.Consumer
/**
* zhaowei
* Created by zhaowei on 2018/5/3.
*/
class ViewModelBuilder<M> {
private val items = arrayListOf<ViewModelItem<M, Any, Any>>()
fun build(viewModel: IViewModel<M>): List<Disposable> {
return items.map { item ->
viewModel.model.map { item.value.invoke(it) }
.distinctUntilChanged()
.compose { item.filter?.invoke(it) ?: it }
.flatMap {
val value = item.map?.invoke(it) ?: it
if (value == null) Observable.empty() else Observable.just(value)
}.subscribe { item.behavior.accept(it) }
}
}
@Suppress("UNCHECKED_CAST")
fun <S> addItem(init: ViewModelItem<M, S, S>.() -> Unit) {
val item = ViewModelItem<M, S, S>()
item.init()
items.add(item as ViewModelItem<M, Any, Any>)
}
}
class ViewModelItem<M, S, R> {
lateinit var value: (M.() -> S)
lateinit var behavior: (Consumer<in R>)
var filter: (Observable<S>.() -> Observable<S>)? = null
var map: (S.() -> R)? = null
fun behavior(init: (R) -> Unit) {
behavior = Consumer { init.invoke(it) }
}
fun value (init: M.() -> S) {
value = init
}
fun map(init: S.() -> R) {
map = init
}
fun filter(init: Observable<S>.() -> Observable<S>) {
filter = init
}
}
| apache-2.0 | 9327bca92f20486c41338be2b0973658 | 25.135593 | 85 | 0.559663 | 3.697842 | false | false | false | false |
bozaro/git-as-svn | src/main/kotlin/svnserver/ext/web/token/EncryptionFactoryAes.kt | 1 | 1277 | /*
* This file is part of git-as-svn. It is subject to the license terms
* in the LICENSE file found in the top-level directory of this distribution
* and at http://www.gnu.org/licenses/gpl-2.0.html. No part of git-as-svn,
* including this file, may be copied, modified, propagated, or distributed
* except according to the terms contained in the LICENSE file.
*/
package svnserver.ext.web.token
import org.jose4j.jwe.ContentEncryptionAlgorithmIdentifiers
import org.jose4j.jwe.JsonWebEncryption
import org.jose4j.jwe.KeyManagementAlgorithmIdentifiers
import org.jose4j.keys.AesKey
import java.security.Key
/**
* WJT token with AES encryption.
*
* @author Artem V. Navrotskiy <[email protected]>
*/
class EncryptionFactoryAes(secret: String) : EncryptionFactory {
private val key: Key
init {
key = AesKey(TokenHelper.secretToBytes(secret, KEY_SIZE))
}
override fun create(): JsonWebEncryption {
val jwe = JsonWebEncryption()
jwe.algorithmHeaderValue = KeyManagementAlgorithmIdentifiers.A128KW
jwe.encryptionMethodHeaderParameter = ContentEncryptionAlgorithmIdentifiers.AES_128_CBC_HMAC_SHA_256
jwe.key = key
return jwe
}
companion object {
var KEY_SIZE = 0x10
}
}
| gpl-2.0 | 924b00701fb3d5363774a3fccb4e68d0 | 31.74359 | 108 | 0.733751 | 3.789318 | false | false | false | false |
edvin/tornadofx | src/main/java/tornadofx/Workspace.kt | 1 | 17335 | package tornadofx
import javafx.beans.property.ObjectProperty
import javafx.beans.property.SimpleBooleanProperty
import javafx.beans.property.SimpleIntegerProperty
import javafx.beans.property.SimpleObjectProperty
import javafx.collections.FXCollections
import javafx.geometry.Pos
import javafx.geometry.Side
import javafx.scene.Node
import javafx.scene.Parent
import javafx.scene.control.Button
import javafx.scene.control.TabPane
import javafx.scene.control.ToolBar
import javafx.scene.input.KeyCode
import javafx.scene.input.KeyCodeCombination
import javafx.scene.input.KeyCombination
import javafx.scene.layout.BorderPane
import javafx.scene.layout.HBox
import javafx.scene.layout.StackPane
import tornadofx.Workspace.NavigationMode.Stack
import kotlin.reflect.KClass
import kotlin.reflect.full.isSubclassOf
class HeadingContainer : HBox() {
init {
addClass("heading-container")
}
}
class WorkspaceArea : BorderPane() {
internal var dynamicComponentMode: Boolean = false
internal val dynamicComponents = FXCollections.observableArrayList<Node>()
var header: ToolBar by singleAssign()
init {
addClass("workspace")
}
}
open class Workspace(title: String = "Workspace", navigationMode: NavigationMode = Stack) : View(title) {
var refreshButton: Button by singleAssign()
var saveButton: Button by singleAssign()
var createButton: Button by singleAssign()
var deleteButton: Button by singleAssign()
var backButton: Button by singleAssign()
var forwardButton: Button by singleAssign()
enum class NavigationMode { Stack, Tabs }
val navigationModeProperty: ObjectProperty<NavigationMode> = SimpleObjectProperty(navigationMode)
var navigationMode by navigationModeProperty
val viewStack = FXCollections.observableArrayList<UIComponent>()
val maxViewStackDepthProperty = SimpleIntegerProperty(DefaultViewStackDepth)
var maxViewStackDepth by maxViewStackDepthProperty
val headingContainer = HeadingContainer()
val tabContainer = TabPane().addClass("editor-container")
val stackContainer = StackPane().addClass("editor-container")
val contentContainerProperty = SimpleObjectProperty<Parent>(stackContainer)
var contentContainer by contentContainerProperty
val showHeadingLabelProperty = SimpleBooleanProperty(true)
var showHeadingLabel by showHeadingLabelProperty
val dockedComponentProperty: ObjectProperty<UIComponent> = SimpleObjectProperty()
val dockedComponent: UIComponent? get() = dockedComponentProperty.value
private val viewPos = integerBinding(viewStack, dockedComponentProperty) { viewStack.indexOf(dockedComponent) }
val leftDrawer: Drawer
get() = (root.left as? Drawer) ?: Drawer(Side.LEFT, false, false).also {
root.left = it
it.toFront()
}
val rightDrawer: Drawer
get() = (root.right as? Drawer) ?: Drawer(Side.RIGHT, false, false).also {
root.right = it
it.toFront()
}
val bottomDrawer: Drawer
get() = (root.bottom as? Drawer) ?: Drawer(Side.BOTTOM, false, false).also {
root.bottom = it
it.toFront()
}
companion object {
val activeWorkspaces = FXCollections.observableArrayList<Workspace>()
val DefaultViewStackDepth = 10
fun closeAll() {
activeWorkspaces.forEach(Workspace::close)
}
var defaultSavable = true
var defaultDeletable = true
var defaultRefreshable = true
var defaultCloseable = true
var defaultComplete = true
var defaultCreatable = true
init {
importStylesheet("/tornadofx/workspace.css")
}
}
fun disableNavigation() {
viewStack.clear()
maxViewStackDepth = 0
}
private fun registerWorkspaceAccelerators() {
accelerators[KeyCodeCombination(KeyCode.S, KeyCombination.SHORTCUT_DOWN)] = {
if (!saveButton.isDisable) onSave()
}
accelerators[KeyCodeCombination(KeyCode.N, KeyCombination.SHORTCUT_DOWN)] = {
if (!createButton.isDisable) onCreate()
}
accelerators[KeyCodeCombination(KeyCode.R, KeyCombination.SHORTCUT_DOWN)] = {
if (!refreshButton.isDisable) onRefresh()
}
accelerators[KeyCombination.valueOf("F5")] = {
if (!refreshButton.isDisable) onRefresh()
}
}
override fun onDock() {
activeWorkspaces += this
}
override fun onUndock() {
activeWorkspaces -= this
}
override val root = WorkspaceArea().apply {
top {
vbox {
header = toolbar {
addClass("header")
// Force the container to retain pos center even when it's resized (hack to make ToolBar behave)
skinProperty().onChange {
(lookup(".container") as? HBox)?.apply {
alignment = Pos.CENTER_LEFT
alignmentProperty().onChange {
if (it != Pos.CENTER_LEFT) alignment = Pos.CENTER_LEFT
}
}
}
button {
addClass("icon-only")
backButton = this
graphic = label { addClass("icon", "back") }
action {
if (dockedComponent?.onNavigateBack() ?: true) {
navigateBack()
}
}
disableProperty().bind(booleanBinding(viewPos, viewStack) { value < 1 })
}
button {
addClass("icon-only")
forwardButton = this
graphic = label { addClass("icon", "forward") }
action {
if (dockedComponent?.onNavigateForward() ?: true) {
navigateForward()
}
}
disableProperty().bind(booleanBinding(viewPos, viewStack) { value == viewStack.size - 1 })
}
button {
addClass("icon-only")
refreshButton = this
isDisable = true
graphic = label {
addClass("icon", "refresh")
}
action {
onRefresh()
}
}
button {
addClass("icon-only")
saveButton = this
isDisable = true
graphic = label { addClass("icon", "save") }
action {
onSave()
}
}
button {
addClass("icon-only")
createButton = this
isDisable = true
graphic = label { addClass("icon", "create") }
action {
onCreate()
}
}
button {
addClass("icon-only")
deleteButton = this
isDisable = true
graphic = label { addClass("icon", "delete") }
action {
onDelete()
}
}
add(headingContainer)
spacer()
}
}
}
}
val header: ToolBar get() = root.header
fun navigateForward(): Boolean {
if (!forwardButton.isDisabled) {
dock(viewStack[viewPos.get() + 1], false)
return true
}
return false
}
fun navigateBack(): Boolean {
if (!backButton.isDisabled) {
dock(viewStack[viewPos.get() - 1], false)
return true
}
return false
}
init {
// @Suppress("LeakingThis")
// if (!scope.hasActiveWorkspace) scope.workspaceInstance = this
navigationModeProperty.addListener { _, ov, nv -> navigationModeChanged(ov, nv) }
tabContainer.tabs.onChange { change ->
while (change.next()) {
if (change.wasRemoved()) {
change.removed.forEach {
if (it == dockedComponent) {
titleProperty.unbind()
refreshButton.disableProperty().unbind()
saveButton.disableProperty().unbind()
createButton.disableProperty().unbind()
deleteButton.disableProperty().unbind()
}
}
}
if (change.wasAdded()) {
change.addedSubList.forEach {
it.content.properties["tornadofx.tab"] = it
}
}
}
}
tabContainer.selectionModel.selectedItemProperty().addListener { observableValue, ov, nv ->
val newCmp = nv?.content?.uiComponent<UIComponent>()
val oldCmp = ov?.content?.uiComponent<UIComponent>()
if (newCmp != null && newCmp != dockedComponent) {
setAsCurrentlyDocked(newCmp)
}
if (oldCmp != newCmp) oldCmp?.callOnUndock()
if (newCmp == null) {
headingContainer.children.clear()
clearDynamicComponents()
dockedComponentProperty.value = null
}
}
dockedComponentProperty.onChange { child ->
if (child != null) {
inDynamicComponentMode {
if (contentContainer == stackContainer) {
tabContainer.tabs.clear()
stackContainer.clear()
stackContainer += child
} else {
stackContainer.clear()
var tab = tabContainer.tabs.find { it.content == child.root }
if (tab == null) {
tabContainer += child
tab = tabContainer.tabs.last()
} else {
child.callOnDock()
}
tabContainer.selectionModel.select(tab)
}
}
}
}
navigationModeChanged(null, navigationMode)
registerWorkspaceAccelerators()
}
private fun navigationModeChanged(oldMode: NavigationMode?, newMode: NavigationMode?) {
if (oldMode == null || oldMode != newMode) {
contentContainer = if (navigationMode == Stack) stackContainer else tabContainer
root.center = contentContainer
if (contentContainer == stackContainer && tabContainer.tabs.isNotEmpty()) {
tabContainer.tabs.clear()
}
dockedComponent?.also {
dockedComponentProperty.value = null
dock(it, true)
}
}
if (newMode == Stack) {
if (backButton !in root.header.items) {
root.header.items.add(0, backButton)
root.header.items.add(1, forwardButton)
}
} else {
root.header.items -= backButton
root.header.items -= forwardButton
}
}
override fun onSave() {
dockedComponentProperty.value
?.takeIf { it.effectiveSavable.value }
?.onSave()
}
override fun onDelete() {
dockedComponentProperty.value
?.takeIf { it.effectiveDeletable.value }
?.onDelete()
}
override fun onCreate() {
dockedComponentProperty.value
?.takeIf { it.effectiveCreatable.value }
?.onCreate()
}
override fun onRefresh() {
dockedComponentProperty.value
?.takeIf { it.effectiveRefreshable.value }
?.onRefresh()
}
inline fun <reified T : UIComponent> dock(scope: Scope = [email protected], params: Map<*, Any?>? = null) = dock(find<T>(scope, params))
inline fun <reified T : UIComponent> dock(scope: Scope = [email protected], vararg params: Pair<*, Any?>) { dock<T>(scope, params.toMap()) }
fun dock(child: UIComponent, forward: Boolean = true) {
if (child == dockedComponent) return
// Remove everything after viewpos if moving forward
if (forward) while (viewPos.get() < viewStack.size -1) viewStack.removeAt(viewPos.get() + 1)
val addToStack = contentContainer == stackContainer && maxViewStackDepth > 0 && child !in viewStack
if (addToStack) viewStack += child
setAsCurrentlyDocked(child)
// Ensure max stack size
while (viewStack.size >= maxViewStackDepth && viewStack.isNotEmpty())
viewStack.removeAt(0)
}
private fun setAsCurrentlyDocked(child: UIComponent) {
titleProperty.bind(child.titleProperty)
rebindWorkspaceButtons(child)
headingContainer.children.clear()
headingContainer.label(child.headingProperty) {
graphicProperty().bind(child.iconProperty)
removeWhen(!showHeadingLabelProperty)
}
clearDynamicComponents()
dockedComponentProperty.value = child
if (currentWindow?.isShowing != true && currentWindow?.aboutToBeShown != true)
FX.log.warning("UIComponent $child docked in invisible workspace $workspace")
}
fun rebindWorkspaceButtons(child: UIComponent) {
refreshButton.disableProperty().cleanBind(!child.effectiveRefreshable)
saveButton.disableProperty().cleanBind(!child.effectiveSavable)
createButton.disableProperty().cleanBind(!child.effectiveCreatable)
deleteButton.disableProperty().cleanBind(!child.effectiveDeletable)
}
private fun clearDynamicComponents() {
root.dynamicComponents.forEach(Node::removeFromParent)
root.dynamicComponents.clear()
}
fun inDynamicComponentMode(function: () -> Unit) {
root.dynamicComponentMode = true
try {
function()
} finally {
root.dynamicComponentMode = false
}
}
/**
* Create a new scope and associate it with this Workspace and optionally add one
* or more ScopedInstance instances into the scope. The op block operates on the workspace and is passed the new scope. The following example
* creates a new scope, injects a Customer Model into it and docks the CustomerEditor
* into the Workspace:
*
* <pre>
* workspace.withNewScope(CustomerModel(customer)) { newScope ->
* dock<CustomerEditor>(newScope)
* }
* </pre>
*/
fun withNewScope(vararg setInScope: ScopedInstance, op: Workspace.(Scope) -> Unit) = op(this, Scope(this, *setInScope))
/**
* Create a new scope and associate it with this Workspace and dock the given UIComponent type into
* the scope, passing the given parameters on to the UIComponent and optionally injecting the given Injectables into the new scope.
*/
inline fun <reified T : UIComponent> dockInNewScope(params: Map<*, Any?>, vararg setInScope: ScopedInstance) {
withNewScope(*setInScope) { newScope ->
dock<T>(newScope, params)
}
}
/**
* Create a new scope and associate it with this Workspace and dock the given UIComponent type into
* the scope, optionally injecting the given Injectables into the new scope.
*/
inline fun <reified T : UIComponent> dockInNewScope(vararg setInScope: ScopedInstance) {
withNewScope(*setInScope) { newScope ->
dock<T>(newScope)
}
}
/**
* Create a new scope and associate it with this Workspace and dock the given UIComponent type into
* the scope and optionally injecting the given Injectables into the new scope.
*/
fun <T : UIComponent> dockInNewScope(uiComponent: T, vararg setInScope: ScopedInstance) {
withNewScope(*setInScope) {
dock(uiComponent)
}
}
/**
* Will automatically dock the given [UIComponent] if the [ListMenuItem] is selected.
*/
inline fun <reified T : UIComponent> ListMenuItem.dockOnSelect() {
whenSelected { dock<T>() }
}
}
open class WorkspaceApp(val initiallyDockedView: KClass<out UIComponent>, vararg stylesheet: KClass<out Stylesheet>) : App(Workspace::class, *stylesheet) {
init {
if (initiallyDockedView.isSubclassOf(Workspace::class))
log.warning("WorkspaceApp called with a Workspace as parameter! Change to App($initiallyDockedView::class) instead.")
}
override fun onBeforeShow(view: UIComponent) {
workspace.dock(find(initiallyDockedView))
}
}
| apache-2.0 | e3dddee74e9bd858308d44aae533b2b6 | 35.804671 | 155 | 0.565676 | 5.322383 | false | false | false | false |
mctoyama/PixelClient | src/main/kotlin/org/pixelndice/table/pixelclient/connection/lobby/client/StateRunning33ShowTurnOrder.kt | 1 | 850 | package org.pixelndice.table.pixelclient.connection.lobby.client
import org.apache.logging.log4j.LogManager
import org.pixelndice.table.pixelclient.ApplicationBus
import org.pixelndice.table.pixelprotocol.Protobuf
private val logger = LogManager.getLogger(StateRunning33ShowTurnOrder::class.java)
class StateRunning33ShowTurnOrder: State {
override fun process(ctx: Context) {
val packet = ctx.channel.packet
if( packet != null ){
if( packet.payloadCase == Protobuf.Packet.PayloadCase.SHOWTURNORDER){
ApplicationBus.post(ApplicationBus.ReceiveShowTurnOrderProtocol())
ctx.state = StateRunning()
logger.debug("Received:\n$packet")
}else {
logger.error("Expecting ShowTurnOrder, instead received: $packet")
}
}
}
} | bsd-2-clause | 9949a40f9eb4cd3d73ecd535af1a8bd3 | 33.04 | 82 | 0.684706 | 4.619565 | false | false | false | false |
vanita5/twittnuker | twittnuker/src/main/kotlin/de/vanita5/twittnuker/view/NameView.kt | 1 | 5334 | /*
* 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.view
import android.content.Context
import android.content.res.Resources
import android.support.v4.text.BidiFormatter
import android.text.SpannableStringBuilder
import android.text.Spanned
import android.text.TextUtils
import android.text.style.AbsoluteSizeSpan
import android.text.style.ForegroundColorSpan
import android.text.style.StyleSpan
import android.util.AttributeSet
import android.util.TypedValue
import de.vanita5.twittnuker.R
class NameView(context: Context, attrs: AttributeSet? = null) : FixedTextView(context, attrs) {
var nameFirst: Boolean = false
var twoLine: Boolean = false
set(value) {
field = value
if (value) {
maxLines = 2
} else {
maxLines = 1
}
}
var name: String? = null
var screenName: String? = null
private val primaryTextStyle: StyleSpan
private val secondaryTextStyle: StyleSpan
private var primaryTextColor: ForegroundColorSpan? = null
private var secondaryTextColor: ForegroundColorSpan? = null
private var primaryTextSize: AbsoluteSizeSpan? = null
private var secondaryTextSize: AbsoluteSizeSpan? = null
init {
ellipsize = TextUtils.TruncateAt.END
val a = context.obtainStyledAttributes(attrs, R.styleable.NameView, 0, 0)
setPrimaryTextColor(a.getColor(R.styleable.NameView_nv_primaryTextColor, 0))
setSecondaryTextColor(a.getColor(R.styleable.NameView_nv_secondaryTextColor, 0))
twoLine = a.getBoolean(R.styleable.NameView_nv_twoLine, false)
primaryTextStyle = StyleSpan(a.getInt(R.styleable.NameView_nv_primaryTextStyle, 0))
secondaryTextStyle = StyleSpan(a.getInt(R.styleable.NameView_nv_secondaryTextStyle, 0))
a.recycle()
nameFirst = true
if (isInEditMode && text.isNullOrEmpty()) {
name = "Name"
screenName = "@screenname"
updateText()
}
}
override fun onTextContextMenuItem(id: Int): Boolean {
try {
return super.onTextContextMenuItem(id)
} catch (e: AbstractMethodError) {
// http://crashes.to/s/69acd0ea0de
return true
}
}
fun setPrimaryTextColor(color: Int) {
primaryTextColor = ForegroundColorSpan(color)
}
fun setSecondaryTextColor(color: Int) {
secondaryTextColor = ForegroundColorSpan(color)
}
fun updateText(formatter: BidiFormatter? = null) {
val sb = SpannableStringBuilder()
val primaryText = if (nameFirst) name else screenName
val secondaryText = if (nameFirst) screenName else name
if (primaryText != null) {
val start = sb.length
if (formatter != null && !isInEditMode) {
sb.append(formatter.unicodeWrap(primaryText))
} else {
sb.append(primaryText)
}
val end = sb.length
sb.setSpan(primaryTextColor, start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
sb.setSpan(primaryTextStyle, start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
sb.setSpan(primaryTextSize, start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
}
sb.append(if (twoLine) '\n' else ' ')
if (secondaryText != null) {
val start = sb.length
if (formatter != null && !isInEditMode) {
sb.append(formatter.unicodeWrap(secondaryText))
} else {
sb.append(secondaryText)
}
val end = sb.length
sb.setSpan(secondaryTextColor, start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
sb.setSpan(secondaryTextStyle, start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
sb.setSpan(secondaryTextSize, start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
}
setText(sb, BufferType.SPANNABLE)
}
fun setPrimaryTextSize(textSize: Float) {
primaryTextSize = AbsoluteSizeSpan(calculateTextSize(TypedValue.COMPLEX_UNIT_SP, textSize).toInt())
}
fun setSecondaryTextSize(textSize: Float) {
secondaryTextSize = AbsoluteSizeSpan(calculateTextSize(TypedValue.COMPLEX_UNIT_SP, textSize).toInt())
}
private fun calculateTextSize(unit: Int, size: Float): Float {
val r = context.resources ?: Resources.getSystem()
return TypedValue.applyDimension(unit, size, r.displayMetrics)
}
} | gpl-3.0 | e26cad2ce29dc34d890c621a50422a8d | 37.107143 | 109 | 0.667979 | 4.441299 | false | false | false | false |
vanita5/twittnuker | twittnuker/src/main/kotlin/de/vanita5/twittnuker/fragment/AbsContentListViewFragment.kt | 1 | 8468 | /*
* 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.fragment
import android.content.Context
import android.graphics.Rect
import android.graphics.drawable.Drawable
import android.os.Bundle
import android.support.v4.widget.SwipeRefreshLayout.OnRefreshListener
import android.view.*
import android.widget.AbsListView
import android.widget.ListAdapter
import kotlinx.android.synthetic.main.fragment_content_listview.*
import kotlinx.android.synthetic.main.layout_content_fragment_common.*
import de.vanita5.twittnuker.R
import de.vanita5.twittnuker.activity.iface.IControlBarActivity
import de.vanita5.twittnuker.activity.iface.IControlBarActivity.ControlBarOffsetListener
import de.vanita5.twittnuker.adapter.iface.ILoadMoreSupportAdapter
import de.vanita5.twittnuker.fragment.iface.RefreshScrollTopInterface
import de.vanita5.twittnuker.util.ContentScrollHandler.ContentListSupport
import de.vanita5.twittnuker.util.ListViewScrollHandler
import de.vanita5.twittnuker.util.ThemeUtils
import de.vanita5.twittnuker.util.TwidereColorUtils
abstract class AbsContentListViewFragment<A : ListAdapter> : BaseFragment(),
OnRefreshListener, RefreshScrollTopInterface, ControlBarOffsetListener, ContentListSupport<A>,
AbsListView.OnScrollListener {
private lateinit var scrollHandler: ListViewScrollHandler<A>
// Data fields
private val systemWindowsInsets = Rect()
protected open val overrideDivider: Drawable?
get() = ThemeUtils.getDrawableFromThemeAttribute(context, android.R.attr.listDivider)
protected val isProgressShowing: Boolean
get() = progressContainer.visibility == View.VISIBLE
override lateinit var adapter: A
override fun onControlBarOffsetChanged(activity: IControlBarActivity, offset: Float) {
updateRefreshProgressOffset()
}
override fun onRefresh() {
triggerRefresh()
}
override fun setUserVisibleHint(isVisibleToUser: Boolean) {
super.setUserVisibleHint(isVisibleToUser)
updateRefreshProgressOffset()
}
override fun scrollToStart(): Boolean {
listView.setSelectionFromTop(0, 0)
setControlVisible(true)
return true
}
override fun setControlVisible(visible: Boolean) {
val activity = activity
if (activity is IControlBarActivity) {
activity.setControlBarVisibleAnimate(visible)
}
}
override var refreshing: Boolean
get() = false
set(refreshing) {
val currentRefreshing = swipeLayout.isRefreshing
if (!currentRefreshing) {
updateRefreshProgressOffset()
}
if (refreshing == currentRefreshing) return
swipeLayout.isRefreshing = refreshing
}
override fun onLoadMoreContents(@ILoadMoreSupportAdapter.IndicatorPosition position: Long) {
setRefreshEnabled(false)
}
override fun onAttach(context: Context) {
super.onAttach(context)
if (context is IControlBarActivity) {
context.registerControlBarOffsetListener(this)
}
}
override fun onDetach() {
val activity = activity
if (activity is IControlBarActivity) {
activity.unregisterControlBarOffsetListener(this)
}
super.onDetach()
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
return inflater.inflate(R.layout.fragment_content_listview, container, false)
}
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
val backgroundColor = ThemeUtils.getColorBackground(context)
val colorRes = TwidereColorUtils.getContrastYIQ(backgroundColor,
R.color.bg_refresh_progress_color_light, R.color.bg_refresh_progress_color_dark)
swipeLayout.setOnRefreshListener(this)
swipeLayout.setProgressBackgroundColorSchemeResource(colorRes)
adapter = onCreateAdapter(context)
listView.setOnTouchListener { _, event ->
if (event.actionMasked == MotionEvent.ACTION_DOWN) {
updateRefreshProgressOffset()
}
false
}
listView.adapter = adapter
listView.clipToPadding = false
overrideDivider?.let { listView.divider = it }
scrollHandler = ListViewScrollHandler(this, ListViewScrollHandler.ListViewCallback(listView)).apply {
this.touchSlop = ViewConfiguration.get(context).scaledTouchSlop
this.onScrollListener = this@AbsContentListViewFragment
}
}
override fun onStart() {
super.onStart()
listView.setOnScrollListener(scrollHandler)
}
override fun onStop() {
listView.setOnScrollListener(scrollHandler)
super.onStop()
}
override fun onApplySystemWindowInsets(insets: Rect) {
listView.setPadding(insets.left, insets.top, insets.right, insets.bottom)
errorContainer.setPadding(insets.left, insets.top, insets.right, insets.bottom)
progressContainer.setPadding(insets.left, insets.top, insets.right, insets.bottom)
systemWindowsInsets.set(insets)
updateRefreshProgressOffset()
}
fun setRefreshEnabled(enabled: Boolean) {
swipeLayout.isEnabled = enabled
}
override fun triggerRefresh(): Boolean {
return false
}
protected abstract fun onCreateAdapter(context: Context): A
protected fun showContent() {
errorContainer.visibility = View.GONE
progressContainer.visibility = View.GONE
swipeLayout.visibility = View.VISIBLE
}
protected fun showProgress() {
errorContainer.visibility = View.GONE
progressContainer.visibility = View.VISIBLE
swipeLayout.visibility = View.GONE
}
protected fun showError(icon: Int, text: CharSequence) {
errorContainer.visibility = View.VISIBLE
progressContainer.visibility = View.GONE
swipeLayout.visibility = View.GONE
errorIcon.setImageResource(icon)
errorText.text = text
}
protected fun showEmpty(icon: Int, text: CharSequence) {
errorContainer.visibility = View.VISIBLE
progressContainer.visibility = View.GONE
swipeLayout.visibility = View.VISIBLE
errorIcon.setImageResource(icon)
errorText.text = text
}
protected fun updateRefreshProgressOffset() {
val activity = activity
if (activity !is IControlBarActivity || systemWindowsInsets.top == 0 || swipeLayout == null
|| refreshing) {
return
}
val density = resources.displayMetrics.density
val progressCircleDiameter = swipeLayout.progressCircleDiameter
val controlBarOffsetPixels = Math.round(activity.controlBarHeight * (1 - activity.controlBarOffset))
val swipeStart = systemWindowsInsets.top - controlBarOffsetPixels - progressCircleDiameter
// 64: SwipeRefreshLayout.DEFAULT_CIRCLE_TARGET
val swipeDistance = Math.round(64 * density)
swipeLayout.setProgressViewOffset(false, swipeStart, swipeStart + swipeDistance)
}
override val reachingStart: Boolean
get() = listView.firstVisiblePosition <= 0
override val reachingEnd: Boolean
get() = listView.lastVisiblePosition >= listView.count - 1
override fun onScrollStateChanged(view: AbsListView, scrollState: Int) {
}
override fun onScroll(view: AbsListView, firstVisibleItem: Int, visibleItemCount: Int, totalItemCount: Int) {
}
} | gpl-3.0 | f1b2b7b4417e7dea39ae04093f322b59 | 35.982533 | 116 | 0.712919 | 4.914684 | false | false | false | false |
slartus/4pdaClient-plus | forpdaapi/src/main/java/org/softeg/slartus/forpdaapi/qms/QmsApi.kt | 1 | 16016 | package org.softeg.slartus.forpdaapi.qms
import androidx.core.util.Pair
import org.softeg.slartus.forpdaapi.IHttpClient
import org.softeg.slartus.forpdaapi.ProgressState
import org.softeg.slartus.forpdaapi.post.EditAttach
import org.softeg.slartus.forpdacommon.*
import org.softeg.slartus.forpdacommon.UrlExtensions.getFileNameFromUrl
import org.softeg.slartus.hosthelper.HostHelper
import ru.slartus.http.CountingFileRequestBody
import ru.slartus.http.FileForm
import ru.slartus.http.Http
import java.io.IOException
import java.io.UnsupportedEncodingException
import java.util.*
import java.util.regex.Matcher
import java.util.regex.Pattern
/**
* Created by slartus on 02.03.14.
*/
object QmsApi {
val qmsSubscribers: ArrayList<QmsUser>
get() {
val pageBody =
Http.instance.performGet("https://${HostHelper.host}/forum/index.php?&act=qms-xhr&action=userlist").responseBody
return parseQmsUsers(pageBody)
}
@Throws(Throwable::class)
fun getChatPage(httpClient: IHttpClient, mid: String, themeId: String): String {
val additionalHeaders = HashMap<String, String>()
additionalHeaders["xhr"] = "body"
return httpClient.performPost(
"https://${HostHelper.host}/forum/index.php?act=qms&mid=$mid&t=$themeId",
additionalHeaders
).responseBody
}
@Throws(Exception::class)
private fun checkChatError(pageBody: String) {
val m = Pattern.compile("<div class=\"error\">([\\s\\S]*?)</div>").matcher(pageBody)
if (m.find()) {
throw Exception(m.group(1).fromHtml().toString())
}
}
@Throws(Throwable::class)
fun getChat(httpClient: IHttpClient, mid: String, themeId: String, daysCount: Int?): QmsPage {
val pageBody = getChatPage(httpClient, mid, themeId)
checkChatError(pageBody)
val qmsPage = QmsPage()
val m =
Pattern.compile("<[^>]*?\"navbar-title\"[^>]*?>[\\s\\S]*?<a[^>]*?showuser=(\\d+)[^>]*?>(.*?)<\\/a>:<\\/b>\\s*([\\s\\S]*?)\\s*<\\/span>")
.matcher(pageBody)
if (m.find()) {
qmsPage.userId = m.group(1)
qmsPage.userNick = m.group(2).fromHtml()
qmsPage.title = m.group(3).fromHtml()
}
qmsPage.body = matchChatBody(pageBody, daysCount)
return qmsPage
}
private fun matchChatBody(pageBod: String, daysCount: Int?): String {
var pageBody = pageBod
var chatInfo = ""
var m =
Pattern.compile("<span class=\"nav-text\"[\\s\\S]*?<a href=\"[^\"]*showuser[^>]*>([^>]*?)</a>:</b>([^<]*)")
.matcher(pageBody)
if (m.find())
chatInfo = "<span id=\"chatInfo\" style=\"display:none;\">" + m.group(1)
.trim { it <= ' ' } + "|:|" + m.group(2).trim { it <= ' ' } + "</span>"
if (daysCount != null) {
val datesMatcher =
Pattern.compile("(<div class=\"date\">[\\s\\S]*?(?=(?:<div class=\"date\">|<div class=\"form-thread)))")
.matcher(pageBody)
var days = emptyArray<String>()
while (datesMatcher.find()) {
val dayBody = datesMatcher.group(1)
days = days.plus(dayBody)
}
if (days.isNotEmpty() || daysCount == 0) {
if (days.size > daysCount) {
chatInfo += "<div class=\"panel\"><div class=\"navi\"><a id=\"chat_more_button\" class=\"button page\" ${
HtmlOutUtils.getHtmlout(
"loadMore"
)
} >Загрузить ещё (${daysCount}/${days.size}дн.)</a></div></div>"
}
return chatInfo + "<div id=\"thread_form\"><div id=\"thread-inside-top\"></div>" + days.takeLast(
daysCount
).joinToString(separator = "\n") + "</div>"
}
}
m =
Pattern.compile("<div id=\"thread-inside-top\"><\\/div>([\\s\\S]*)<div id=\"thread-inside-bottom\">")
.matcher(pageBody)
if (m.find())
return chatInfo + "<div id=\"thread_form\"><div id=\"thread-inside-top\"></div>" + m.group(
1
) + "</div>"
m = Pattern.compile("<div class=\"list_item\" t_id=([\\s\\S]*?)</form>").matcher(pageBody)
if (m.find())
return chatInfo + "<div id=\"thread_form\"><div class=\"list_item\" t_id=" + m.group(1) + "</div>"
// ни одного сообщения
m = Pattern.compile("</form>\\s*<div class=\"form\">").matcher(pageBody)
if (m.find())
return "<div id=\"thread_form\"></div>"
m =
Pattern.compile("<script>try\\{setTimeout \\( function\\(\\)\\{ updateScrollbar \\( \\$\\(\"#thread_container>.scrollbar_wrapper\"\\), \"bottom\" \\); \\}, 1 \\);\\}catch\\(e\\)\\{\\}</script>\\s*</div>")
.matcher(pageBody)
if (m.find())
return "<div id=\"thread_form\"></div>"
else
pageBody += ""
return pageBody
}
@Throws(Throwable::class)
fun sendMessage(
httpClient: IHttpClient, mid: String, tid: String, message: String, encoding: String,
attachs: ArrayList<EditAttach>, daysCount: Int?
): QmsPage {
val additionalHeaders = HashMap<String, String>()
additionalHeaders["action"] = "send-message"
additionalHeaders["mid"] = mid
additionalHeaders["t"] = tid
additionalHeaders["message"] = message
if (attachs.any())
additionalHeaders["attaches"] = attachs.joinToString { it.id }
val response = httpClient.performPost(
"https://${HostHelper.host}/forum/index.php?act=qms-xhr",
additionalHeaders, encoding
)
parseError(response.responseBody)
return getChat(httpClient, mid, tid, daysCount)
}
@Throws(IOException::class)
fun createThread(
httpClient: IHttpClient, userID: String, userNick: String, title: String, message: String,
outParams: MutableMap<String, String>, encoding: String
): String {
val additionalHeaders = HashMap<String, String>()
additionalHeaders["action"] = "create-thread"
additionalHeaders["username"] = userNick
additionalHeaders["title"] = title
additionalHeaders["message"] = message
val pageBody = httpClient.performPost(
"https://${HostHelper.host}/forum/index.php?act=qms&mid=$userID&xhr=body&do=1",
additionalHeaders,
encoding
)
var m =
Pattern.compile("<input\\s*type=\"hidden\"\\s*name=\"mid\"\\s*value=\"(\\d+)\"\\s*/>")
.matcher(pageBody.responseBody)
if (m.find())
outParams["mid"] = m.group(1)
m = Pattern.compile("<input\\s*type=\"hidden\"\\s*name=\"t\"\\s*value=\"(\\d+)\"\\s*/>")
.matcher(pageBody.responseBody)
if (m.find())
outParams["t"] = m.group(1)
// m = Pattern.compile("<strong>(.*?):\\s*</strong></a>\\s*(.*?)\\s*?</span>").matcher(pageBody);
//if (m.find()) {
outParams["user"] = userNick
outParams["title"] = title
//}
parseError(pageBody.responseBody)
return matchChatBody(pageBody.responseBody, 0)
}
private fun parseError(pageBody: String) {
val errorRegexes = listOf(
"<div class=\"form-error\">(.*?)</div>",
"<div class=\"list-group-item msgbox error\">([\\s\\S]*?)</div>"
)
errorRegexes.forEach { r ->
val m = Pattern.compile(r)
.matcher(pageBody)
if (m.find())
throw NotReportException(m.group(1)?.fromHtml()?.toString()?.trim())
}
}
@Throws(IOException::class)
fun deleteDialogs(httpClient: IHttpClient, mid: String, ids: List<String>) {
val additionalHeaders = HashMap<String, String>()
additionalHeaders["action"] = "delete-threads"
additionalHeaders["title"] = ""
additionalHeaders["message"] = ""
for (id in ids) {
additionalHeaders["thread-id[$id]"] = id
}
httpClient.performPost(
"https://${HostHelper.host}/forum/index.php?act=qms&xhr=body&do=1&mid=$mid",
additionalHeaders
)
}
@Throws(IOException::class)
fun deleteMessages(
httpClient: IHttpClient, mid: String, threadId: String, ids: List<String>,
encoding: String, daysCount: Int?
): String {
val additionalHeaders = HashMap<String, String>()
additionalHeaders["act"] = "qms"
additionalHeaders["mid"] = mid
additionalHeaders["t"] = threadId
additionalHeaders["xhr"] = "body"
additionalHeaders["do"] = "1"
additionalHeaders["action"] = "delete-messages"
additionalHeaders["forward-messages-username"] = ""
additionalHeaders["forward-thread-username"] = ""
additionalHeaders["message"] = ""
for (id in ids) {
additionalHeaders["message-id[$id]"] = id
}
return matchChatBody(
httpClient.performPost(
"https://${HostHelper.host}/forum/index.php?act=qms&mid$mid&t=$threadId&xhr=body&do=1",
additionalHeaders, encoding
).responseBody, daysCount
)
}
private fun parseQmsUsers(pageBody: String?): ArrayList<QmsUser> {
val res = ArrayList<QmsUser>()
val m = Pattern.compile(
"<a class=\"list-group-item[^>]*=(\\d*)\">[^<]*<div class=\"bage\">([^<]*)[\\s\\S]*?src=\"([^\"]*)\" title=\"([^\"]*)\"",
Pattern.CASE_INSENSITIVE
).matcher(pageBody!!)
var count: String
var qmsUser: QmsUser
while (m.find()) {
qmsUser = QmsUser()
qmsUser.setId(m.group(1))
var avatar = m.group(3)
if (avatar.substring(0, 2) == "//") {
avatar = "https:$avatar"
}
qmsUser.setAvatarUrl()
qmsUser.nick = m.group(4).fromHtml().toString().trim { it <= ' ' }
count = m.group(2).trim { it <= ' ' }
if (count != "")
qmsUser.newMessagesCount = count.replace("(", "").replace(")", "")
res.add(qmsUser)
}
return res
}
@Throws(Throwable::class)
fun getQmsUserThemes(
mid: String,
outUsers: ArrayList<QmsUser>, parseNick: Boolean?
): QmsUserThemes {
val res = QmsUserThemes()
val pageBody =
Http.instance.performGet("https://${HostHelper.host}/forum/index.php?act=qms&mid=$mid").responseBody
val newCountPattern = Pattern.compile("([\\s\\S]*?)\\((\\d+)\\s*\\/\\s*(\\d+)\\)\\s*$")
val countPattern = Pattern.compile("([\\s\\S]*?)\\((\\d+)\\)\\s*$")
val strongPattern = Pattern.compile("<strong>([\\s\\S]*?)</strong>")
var matcher =
Pattern.compile("<div class=\"list-group\">([\\s\\S]*)<form [^>]*>([\\s\\S]*?)<\\/form>")
.matcher(pageBody)
if (matcher.find()) {
outUsers.addAll(parseQmsUsers(matcher.group(1)))
matcher =
Pattern.compile("<a class=\"list-group-item[^>]*-(\\d*)\">[\\s\\S]*?<div[^>]*>([\\s\\S]*?)<\\/div>([\\s\\S]*?)<\\/a>")
.matcher(matcher.group(2))
var item: QmsUserTheme
var m: Matcher
var info: String
while (matcher.find()) {
item = QmsUserTheme()
item.Id = matcher.group(1)
item.Date = matcher.group(2)
info = matcher.group(3)
m = strongPattern.matcher(info)
if (m.find()) {
m = newCountPattern.matcher(m.group(1))
if (m.find()) {
item.Title = m.group(1).trim { it <= ' ' }
item.Count = m.group(2)
item.NewCount = m.group(3)
} else
item.Title = m.group(2).trim { it <= ' ' }
} else {
m = countPattern.matcher(info)
if (m.find()) {
item.Title = m.group(1).trim { it <= ' ' }
item.Count = m.group(2).trim { it <= ' ' }
} else
item.Title = info.trim { it <= ' ' }
}
res.add(item)
}
if (parseNick!!) {
matcher =
Pattern.compile("<div class=\"nav\">[\\s\\S]*?showuser[^>]*>([\\s\\S]*?)<\\/a>[\\s\\S]*?<\\/div>")
.matcher(pageBody)
if (matcher.find()) {
res.Nick = matcher.group(1)
}
}
}
return res
}
fun getNewQmsCount(pageBody: String): Int {
val qms20Pattern = PatternExtensions.compile("id=\"events-count\"[^>]*>[^\\d]*?(\\d+)<")
val m = qms20Pattern.matcher(pageBody)
return if (m.find()) {
Integer.parseInt(m.group(1))
} else 0
}
@Throws(IOException::class)
fun getNewQmsCount(client: IHttpClient): Int {
val body = client.performGet("https://${HostHelper.host}/forum/index.php?showforum=200")
return getNewQmsCount(body.responseBody)
}
private fun fromCharCode(vararg codePoints: Int): String {
val builder = StringBuilder(codePoints.size)
for (codePoint in codePoints) {
builder.append(Character.toChars(codePoint))
}
return builder.toString()
}
fun attachFile(
pathToFile: String,
progress: ProgressState,
code: String = "check"
): EditAttach {
var nameValue = "file"
try {
nameValue = getFileNameFromUrl(pathToFile)
} catch (e: UnsupportedEncodingException) {
e.printStackTrace()
}
val finalNameValue = nameValue
val params = ArrayList<Pair<String, String>>()
params.add(Pair("name", nameValue))
params.add(Pair("code", code))
params.add(Pair("relType", "MSG"))
params.add(Pair("index", "1"))
val (_, _, responseBody) = Http.instance.uploadFile("https://${HostHelper.host}/forum/index.php?act=attach",
nameValue,
pathToFile,
FileForm.FileUpload,
params
) { num ->
progress.update(
finalNameValue,
num
)
}
val body = ("" + responseBody).replace("(^\\x03|\\x03$)".toRegex(), "")
val parts =
body.split(fromCharCode(2).toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()
val k = parts[0].toInt()
if (k == 0) {
Thread.sleep(1000)
return attachFile(pathToFile, progress, "upload")
}
val error = when (k) {
-1 -> " no access on server."
-2 -> " too big."
-3 -> " has invalid mime type"
-4 -> " is banned on server."
else -> null
}
if (error != null)
throw NotReportException(error)
val id = parts[0]
val name = parts[1]
val ext = parts[2]
// val url = parts[3]
// val length = parts[4]
// val md5 = parts[5]
return EditAttach(id, "$name.$ext")
}
fun deleteAttach(attachId: String): Boolean {
val params = ArrayList<Pair<String, String>>()
params.add(Pair("code", "remove"))
params.add(Pair("relType", "MSG"))
params.add(Pair("relId", "0"))
params.add(Pair("index", "1"))
params.add(Pair("id", attachId))
Http.instance.performPost("https://${HostHelper.host}/forum/index.php?act=attach", params)
return true
}
}
| apache-2.0 | d61e35ac8dbf4fed2ef3992e92ccabfa | 36.879147 | 216 | 0.524241 | 4.032543 | false | false | false | false |
stripe/stripe-android | link/src/main/java/com/stripe/android/link/ui/inline/LinkInlineSignedIn.kt | 1 | 3790 | package com.stripe.android.link.ui.inline
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.text.ClickableText
import androidx.compose.material.Divider
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.semantics.testTag
import androidx.compose.ui.text.AnnotatedString
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.unit.dp
import androidx.lifecycle.viewmodel.compose.viewModel
import com.stripe.android.link.LinkPaymentLauncher
import com.stripe.android.link.R
import com.stripe.android.link.theme.linkShapes
import com.stripe.android.ui.core.PaymentsTheme
import com.stripe.android.ui.core.getBorderStroke
import com.stripe.android.ui.core.paymentsColors
@Composable
fun LinkInlineSignedIn(
linkPaymentLauncher: LinkPaymentLauncher,
onLogout: () -> Unit,
modifier: Modifier = Modifier
) {
linkPaymentLauncher.component?.let { component ->
val viewModel: InlineSignupViewModel = viewModel(
factory = InlineSignupViewModel.Factory(component.injector)
)
val accountEmail = viewModel.accountEmail.collectAsState(initial = "")
PaymentsTheme {
Box(
modifier = modifier
.border(
border = MaterialTheme.getBorderStroke(isSelected = false),
shape = MaterialTheme.linkShapes.small
)
.background(
color = MaterialTheme.paymentsColors.component,
shape = MaterialTheme.linkShapes.small
)
.semantics {
testTag = "SignedInBox"
}
) {
Column(
modifier = Modifier
.fillMaxWidth()
.padding(16.dp)
) {
Text(
text = stringResource(id = R.string.this_card_will_be_saved),
modifier = Modifier.padding(bottom = 16.dp)
)
Divider(
color = MaterialTheme.paymentsColors.componentBorder.copy(alpha = 0.1f),
modifier = Modifier.padding(bottom = 16.dp)
)
Row(
horizontalArrangement = Arrangement.SpaceBetween,
modifier = Modifier.fillMaxWidth()
) {
Text(
text = accountEmail.value ?: "",
color = MaterialTheme.paymentsColors.subtitle
)
ClickableText(
text = AnnotatedString(text = stringResource(id = R.string.logout)),
style = TextStyle.Default.copy(color = MaterialTheme.colors.primary),
onClick = {
viewModel.logout()
onLogout()
}
)
}
}
}
}
}
}
| mit | 731e2affc3220e111b4ca431bc013ff7 | 39.319149 | 97 | 0.582058 | 5.532847 | false | false | false | false |
AndroidX/androidx | compose/ui/ui-text/src/androidAndroidTest/kotlin/androidx/compose/ui/text/matchers/TypefaceResultSubject.kt | 3 | 2802 | /*
* Copyright 2019 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.compose.ui.text.matchers
import android.graphics.Typeface
import androidx.compose.ui.text.font.TypefaceResult
import androidx.compose.ui.text.font.TypefaceResult.Async
import androidx.compose.ui.text.font.TypefaceResult.Immutable
import com.google.common.truth.FailureMetadata
import com.google.common.truth.Subject
import com.google.common.truth.Subject.Factory
internal class TypefaceResultSubject private constructor(
failureMetadata: FailureMetadata?,
private val subject: TypefaceResult?
) : Subject(failureMetadata, subject) {
companion object {
internal val SUBJECT_FACTORY: Factory<TypefaceResultSubject?, TypefaceResult?> =
Factory { failureMetadata, subject -> TypefaceResultSubject(failureMetadata, subject) }
}
fun isImmutableTypefaceOf(expectedInstance: Typeface) {
check("isNotNull())").that(subject).isNotNull()
check("is TypefaceResult.Immutable").that(subject)
.isInstanceOf(Immutable::class.java)
check(".value == $expectedInstance").that(subject?.value)
.isSameInstanceAs(expectedInstance)
}
fun isImmutableTypeface() {
check("isNotNull())").that(subject).isNotNull()
check("is TypefaceResult.Immutable").that(subject)
.isInstanceOf(Immutable::class.java)
}
fun currentAsyncTypefaceValue(expectedInstance: Typeface) {
check("isNotNull())").that(subject).isNotNull()
check("is TypefaceResult.Async").that(subject)
.isInstanceOf(Async::class.java)
check("$subject === $expectedInstance")
.that(subject?.value)
.isSameInstanceAs(expectedInstance)
}
fun isAsyncTypeface() {
check("isNotNull())").that(subject).isNotNull()
check("is TypefaceResult.Async").that(subject)
.isInstanceOf(Async::class.java)
}
override fun actualCustomStringRepresentation(): String = when (subject) {
null -> "null TypefaceResult"
is Immutable ->
"TypefaceResult.Immutable(value=${subject.value})"
is Async ->
"TypefaceResult.Immutable(currentState=${subject.current.value})"
}
} | apache-2.0 | d83609f1ffeef271782440a8d0fc4722 | 37.39726 | 99 | 0.702355 | 4.533981 | false | false | false | false |
noud02/Akatsuki | src/main/kotlin/moe/kyubey/akatsuki/commands/Script.kt | 1 | 8450 | /*
* Copyright (c) 2017-2019 Yui
*
* 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 moe.kyubey.akatsuki.commands
import me.aurieh.ares.exposed.async.asyncTransaction
import moe.kyubey.akatsuki.Akatsuki
import moe.kyubey.akatsuki.annotations.*
import moe.kyubey.akatsuki.annotations.Alias
import moe.kyubey.akatsuki.db.schema.Scripts
import moe.kyubey.akatsuki.entities.Command
import moe.kyubey.akatsuki.entities.Context
import moe.kyubey.akatsuki.utils.I18n
import moe.kyubey.akatsuki.utils.LuaSandbox
import net.dv8tion.jda.core.Permission
import org.jetbrains.exposed.sql.*
@Perm(Permission.MANAGE_SERVER)
@Argument("script", "string")
class TestCommand : Command() {
override val desc = "Test lua scripts"
override val guildOnly = true
override fun run(ctx: Context) {
val script = ctx.rawArgs.joinToString(" ")
LuaSandbox.eval(script, ctx.rawArgs, ctx)
}
}
@Perm(Permission.MANAGE_SERVER)
@Arguments(
Argument("name", "string"),
Argument("script", "string")
)
@Flag("owner", 'o', "Make the custom command server owner only.")
class AddCommand : Command() {
override val desc = "Add custom scripts."
override val guildOnly = true
override fun run(ctx: Context) {
val content = ctx.rawArgs.slice(1 until ctx.rawArgs.size).joinToString(" ")
val name = ctx.args["name"] as String
asyncTransaction(Akatsuki.pool) {
val scriptsMatch = Scripts.select { Scripts.guildId.eq(ctx.guild!!.idLong).and(Scripts.scriptName.eq(name)) }
if (!scriptsMatch.empty()) {
return@asyncTransaction ctx.send(
I18n.parse(
ctx.lang.getString("script_exists"),
mapOf("username" to ctx.author.name)
)
)
}
Scripts.insert {
it[script] = content
it[scriptName] = name
it[ownerId] = ctx.author.idLong
it[ownerOnly] = ctx.flags.argMap.containsKey("owner") || ctx.flags.argMap.containsKey("o")
it[guildId] = ctx.guild!!.idLong
}
ctx.send(
I18n.parse(
ctx.lang.getString("added_script"),
mapOf("name" to name)
)
)
}.execute()
}
}
@Perms(
Perm(Permission.ADMINISTRATOR, true),
Perm(Permission.MANAGE_SERVER)
)
@Argument("name", "string")
class RemoveCommand : Command() {
override val guildOnly = true
override val desc = "Remove custom scripts."
override fun run(ctx: Context) {
val name = ctx.args["name"] as String
val hasPerm = ctx.perms["ADMINISTRATOR"] as Boolean
asyncTransaction(Akatsuki.pool) {
val match = Scripts.select { Scripts.guildId.eq(ctx.guild!!.idLong).and(Scripts.scriptName.eq(name)) }.firstOrNull()
?: return@asyncTransaction ctx.send(
I18n.parse(
ctx.lang.getString("script_not_found"),
mapOf("username" to ctx.author.name)
)
)
if (!hasPerm && match[Scripts.ownerId] != ctx.author.idLong) {
return@asyncTransaction ctx.send(
I18n.parse(
ctx.lang.getString("cant_delete_script"),
mapOf("username" to ctx.author.name)
)
)
}
Scripts.deleteWhere {
Scripts.scriptName.eq(name).and(Scripts.guildId.eq(ctx.guild!!.idLong))
}
ctx.send(
I18n.parse(
ctx.lang.getString("deleted_script"),
mapOf("name" to name)
)
)
}.execute()
}
}
@Perms(
Perm(Permission.MANAGE_SERVER),
Perm(Permission.ADMINISTRATOR, true)
)
@Arguments(
Argument("name", "string"),
Argument("script", "string")
)
class EditCommand : Command() {
override val desc = "Edit custom scripts."
override val guildOnly = true
override fun run(ctx: Context) {
val name = ctx.args["name"] as String
val hasPerm = ctx.perms["ADMINISTRATOR"] as Boolean
asyncTransaction(Akatsuki.pool) {
val match = Scripts.select { Scripts.guildId.eq(ctx.guild!!.idLong).and(Scripts.scriptName.eq(name)) }.firstOrNull()
?: return@asyncTransaction ctx.send(
I18n.parse(
ctx.lang.getString("script_not_found"),
mapOf("username" to ctx.author.name)
)
)
if (!hasPerm && match[Scripts.ownerId] != ctx.author.idLong) {
return@asyncTransaction ctx.send(
I18n.parse(
ctx.lang.getString("cant_edit_script"),
mapOf("username" to ctx.author.name)
)
)
}
Scripts.update({
Scripts.scriptName.eq(name).and(Scripts.guildId.eq(ctx.guild!!.idLong))
}) {
it[script] = ctx.args["script"] as String
}
ctx.send(
I18n.parse(
ctx.lang.getString("edited_script"),
mapOf("name" to name)
)
)
}.execute()
}
}
@Load
@Arguments(
Argument("command", "string"),
Argument("arguments", "string", true)
)
@Alias("cmd", "customcommand", "c", "s")
@Perm(Permission.ADMINISTRATOR, true)
class Script : Command() {
override val desc = "Execute custom scripts. (https://github.com/Kyuubey/Akatsuki/blob/master/SCRIPT_DOCS.md)"
override val guildOnly = true
init {
addSubcommand(TestCommand(), "test")
addSubcommand(AddCommand(), "add")
addSubcommand(RemoveCommand(), "remove")
addSubcommand(EditCommand(), "edit")
}
override fun run(ctx: Context) {
val cmd = ctx.args["command"] as String
val hasPerm = ctx.perms["ADMINISTRATOR"] as Boolean
asyncTransaction(Akatsuki.pool) {
val command = Scripts.select { Scripts.guildId.eq(ctx.guild!!.idLong).and(Scripts.scriptName.eq(cmd)) }.firstOrNull()
?: return@asyncTransaction ctx.send(
I18n.parse(
ctx.lang.getString("script_not_found"),
mapOf("username" to ctx.author.name)
)
)
if (command[Scripts.ownerOnly] && !hasPerm) {
return@asyncTransaction ctx.send(
I18n.parse(
ctx.lang.getString("script_owner_only"),
mapOf("username" to ctx.author.name)
)
)
}
LuaSandbox.eval(command[Scripts.script], ctx.rawArgs.slice(1 until ctx.rawArgs.size), ctx)
}.execute()
}
}
| mit | 64f846204785fb5e4f044209dc2ed4bf | 34.957447 | 129 | 0.550059 | 4.560173 | false | false | false | false |
Guardiola31337/uiagesturegen | uiagesturegen/src/androidTest/kotlin/com/pguardiola/uiagesturegen/PinchOutTest.kt | 1 | 3033 | /*
* Copyright (C) 2017 Pablo Guardiola Sánchez.
*
* 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.pguardiola.uiagesturegen
import android.content.Intent
import android.content.pm.PackageManager
import android.support.test.InstrumentationRegistry
import android.support.test.uiautomator.*
import org.hamcrest.CoreMatchers
import org.hamcrest.CoreMatchers.notNullValue
import org.junit.Assert.assertThat
import org.junit.Assert.assertTrue
import org.junit.Before
import org.junit.Test
class PinchOutTest {
companion object {
private val BASIC_SAMPLE_PACKAGE = "com.pguardiola.uiagesturegen"
private val LAUNCH_TIMEOUT = 5000
}
lateinit private var device: UiDevice
@Before fun startMainActivityFromHomeScreen() {
// Initialize UiDevice instance
device = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation())
// Start from the home screen
device.pressHome()
// Wait for launcher
val launcherPackage = obtainLauncherPackageName()
assertThat(launcherPackage, CoreMatchers.notNullValue())
device.wait(Until.hasObject(By.pkg(launcherPackage).depth(0)), LAUNCH_TIMEOUT.toLong())
// Launch the blueprint app
val context = InstrumentationRegistry.getContext()
val intent = context.packageManager.getLaunchIntentForPackage(BASIC_SAMPLE_PACKAGE)
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK) // Clear out any previous instances
context.startActivity(intent)
// Wait for the app to appear
device.wait(Until.hasObject(By.pkg(BASIC_SAMPLE_PACKAGE).depth(0)), LAUNCH_TIMEOUT.toLong())
}
@Test fun checksPreconditions() {
assertThat(device, notNullValue())
try {
val mapViewSelector = UiSelector().description("map view container")
val mapView = device.findObject(mapViewSelector)
assertTrue(mapView.pinchOut(100, 50))
} catch (e: UiObjectNotFoundException) {
e.printStackTrace()
}
}
private fun obtainLauncherPackageName(): String {
// Create launcher Intent
val intent = Intent(Intent.ACTION_MAIN)
intent.addCategory(Intent.CATEGORY_HOME)
// Use PackageManager to get the launcher package name
val pm = InstrumentationRegistry.getContext().packageManager
val resolveInfo = pm.resolveActivity(intent, PackageManager.MATCH_DEFAULT_ONLY)
return resolveInfo.activityInfo.packageName
}
}
| apache-2.0 | 5a11d31b58c22d3f1ba6ef45f3a46d91 | 35.095238 | 100 | 0.716029 | 4.715397 | false | true | false | false |
holisticon/ranked | backend/command/src/main/kotlin/team/PlayerCreatingSaga.kt | 1 | 2305 | @file:Suppress("PackageDirectoryMismatch", "unused")
package de.holisticon.ranked.command.team
import de.holisticon.ranked.command.api.CheckPlayer
import de.holisticon.ranked.command.api.CreatePlayer
import de.holisticon.ranked.command.rest.CommandApi
import de.holisticon.ranked.extension.send
import de.holisticon.ranked.model.UserName
import de.holisticon.ranked.model.event.PlayerCreated
import de.holisticon.ranked.model.event.PlayerExists
import de.holisticon.ranked.model.event.TeamCreated
import org.axonframework.commandhandling.gateway.CommandGateway
import org.axonframework.eventhandling.saga.SagaEventHandler
import org.axonframework.eventhandling.saga.SagaLifecycle
import org.axonframework.eventhandling.saga.SagaLifecycle.associateWith
import org.axonframework.eventhandling.saga.SagaLifecycle.end
import org.axonframework.eventhandling.saga.StartSaga
import org.axonframework.spring.stereotype.Saga
import org.springframework.beans.factory.annotation.Autowired
@Saga
class PlayerCreatingSaga() {
@Autowired
@Transient
lateinit var commandGateway: CommandGateway
private val missingPlayer: MutableSet<UserName> = mutableSetOf()
@StartSaga
@SagaEventHandler(associationProperty = "id")
fun on(e: TeamCreated) {
arrayOf(e.team.player1, e.team.player2).forEach {
// remember it
missingPlayer.add(it)
associateWith("userName", it.value)
commandGateway.send(
command = CheckPlayer(it),
success = { _, _: Any -> CommandApi.logger.debug { "Player $it exists." } },
failure = { _, _: Throwable ->
// player don't exist
// create it
commandGateway.send(
CreatePlayer(userName = it, displayName = it.value, imageUrl = ""),
success = { _, _: Any -> CommandApi.logger.debug { "Player $it will be created." } },
failure = { _, cause: Throwable -> throw cause }
)
}
)
}
}
@SagaEventHandler(associationProperty = "userName")
fun on(e: PlayerExists) {
missingPlayer.remove(e.userName)
if (missingPlayer.isEmpty()) {
end()
}
}
@SagaEventHandler(associationProperty = "userName")
fun on(e: PlayerCreated) {
missingPlayer.remove(e.userName)
if (missingPlayer.isEmpty()) {
end()
}
}
}
| bsd-3-clause | 4cb8dc8939991bedd9d7562f15b18eb5 | 29.733333 | 97 | 0.715835 | 4.101423 | false | false | false | false |
androidx/androidx | compose/animation/animation/src/commonMain/kotlin/androidx/compose/animation/SplineBasedDecay.kt | 3 | 4555 | /*
* 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.animation
import androidx.compose.animation.core.DecayAnimationSpec
import androidx.compose.animation.core.generateDecayAnimationSpec
import androidx.compose.ui.unit.Density
import kotlin.math.abs
import kotlin.math.ln
private const val Inflection = 0.35f // Tension lines cross at (Inflection, 1)
private const val StartTension = 0.5f
private const val EndTension = 1.0f
private const val P1 = StartTension * Inflection
private const val P2 = 1.0f - EndTension * (1.0f - Inflection)
private fun computeSplineInfo(
splinePositions: FloatArray,
splineTimes: FloatArray,
nbSamples: Int
) {
var xMin = 0.0f
var yMin = 0.0f
for (i in 0 until nbSamples) {
val alpha = i.toFloat() / nbSamples
var xMax = 1.0f
var x: Float
var tx: Float
var coef: Float
while (true) {
x = xMin + (xMax - xMin) / 2.0f
coef = 3.0f * x * (1.0f - x)
tx = coef * ((1.0f - x) * P1 + x * P2) + x * x * x
if (abs(tx - alpha) < 1E-5) break
if (tx > alpha) xMax = x else xMin = x
}
splinePositions[i] = coef * ((1.0f - x) * StartTension + x) + x * x * x
var yMax = 1.0f
var y: Float
var dy: Float
while (true) {
y = yMin + (yMax - yMin) / 2.0f
coef = 3.0f * y * (1.0f - y)
dy = coef * ((1.0f - y) * StartTension + y) + y * y * y
if (abs(dy - alpha) < 1E-5) break
if (dy > alpha) yMax = y else yMin = y
}
splineTimes[i] = coef * ((1.0f - y) * P1 + y * P2) + y * y * y
}
splineTimes[nbSamples] = 1.0f
splinePositions[nbSamples] = splineTimes[nbSamples]
}
/**
* The native Android fling scroll spline and the ability to sample it.
*
* Ported from `android.widget.Scroller`.
*/
internal object AndroidFlingSpline {
private const val NbSamples = 100
private val SplinePositions = FloatArray(NbSamples + 1)
private val SplineTimes = FloatArray(NbSamples + 1)
init {
// TODO This function used to be directly implemented in this init block, but it causes a
// crash in the IR compiler.
computeSplineInfo(SplinePositions, SplineTimes, NbSamples)
}
/**
* Compute an instantaneous fling position along the scroller spline.
*
* @param time progress through the fling animation from 0-1
*/
fun flingPosition(time: Float): FlingResult {
val index = (NbSamples * time).toInt()
var distanceCoef = 1f
var velocityCoef = 0f
if (index < NbSamples) {
val tInf = index.toFloat() / NbSamples
val tSup = (index + 1).toFloat() / NbSamples
val dInf = SplinePositions[index]
val dSup = SplinePositions[index + 1]
velocityCoef = (dSup - dInf) / (tSup - tInf)
distanceCoef = dInf + (time - tInf) * velocityCoef
}
return FlingResult(
distanceCoefficient = distanceCoef,
velocityCoefficient = velocityCoef
)
}
/**
* The rate of deceleration along the spline motion given [velocity] and [friction].
*/
fun deceleration(velocity: Float, friction: Float): Double =
ln(Inflection * abs(velocity) / friction.toDouble())
/**
* Result coefficients of a scroll computation
*/
// TODO: pack this into an inline class
data class FlingResult(
/**
* Linear distance traveled from 0-1, from source (0) to destination (1)
*/
val distanceCoefficient: Float,
/**
* Instantaneous velocity coefficient at this point in the fling expressed in
* total distance per unit time
*/
val velocityCoefficient: Float
)
}
fun <T> splineBasedDecay(density: Density): DecayAnimationSpec<T> =
SplineBasedFloatDecayAnimationSpec(density).generateDecayAnimationSpec()
| apache-2.0 | c9e47c1df5b7c692b3f83aafaf16911a | 33.770992 | 97 | 0.621515 | 3.795833 | false | false | false | false |
minecraft-dev/MinecraftDev | src/main/kotlin/platform/bungeecord/BungeeCordModuleType.kt | 1 | 1543 | /*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2022 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev.platform.bungeecord
import com.demonwav.mcdev.asset.PlatformAssets
import com.demonwav.mcdev.facet.MinecraftFacet
import com.demonwav.mcdev.platform.AbstractModuleType
import com.demonwav.mcdev.platform.PlatformType
import com.demonwav.mcdev.platform.bungeecord.generation.BungeeCordEventGenerationPanel
import com.demonwav.mcdev.platform.bungeecord.util.BungeeCordConstants
import com.demonwav.mcdev.util.CommonColors
import com.intellij.psi.PsiClass
object BungeeCordModuleType : AbstractModuleType<BungeeCordModule<BungeeCordModuleType>>("net.md-5", "bungeecord-api") {
private const val ID = "BUNGEECORD_MODULE_TYPE"
val IGNORED_ANNOTATIONS = listOf(BungeeCordConstants.HANDLER_ANNOTATION)
val LISTENER_ANNOTATIONS = listOf(BungeeCordConstants.HANDLER_ANNOTATION)
init {
CommonColors.applyStandardColors(colorMap, BungeeCordConstants.CHAT_COLOR_CLASS)
}
override val platformType = PlatformType.BUNGEECORD
override val icon = PlatformAssets.BUNGEECORD_ICON
override val id = ID
override val ignoredAnnotations = IGNORED_ANNOTATIONS
override val listenerAnnotations = LISTENER_ANNOTATIONS
override val isEventGenAvailable = true
override fun generateModule(facet: MinecraftFacet) = BungeeCordModule(facet, this)
override fun getEventGenerationPanel(chosenClass: PsiClass) = BungeeCordEventGenerationPanel(chosenClass)
}
| mit | 9eba3ae14b03200a86adaea9c5892484 | 35.738095 | 120 | 0.801037 | 4.60597 | false | false | false | false |
minecraft-dev/MinecraftDev | src/main/kotlin/platform/forge/inspections/sideonly/MethodCallSideOnlyInspection.kt | 1 | 10184 | /*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2022 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev.platform.forge.inspections.sideonly
import com.demonwav.mcdev.platform.forge.util.ForgeConstants
import com.demonwav.mcdev.util.findContainingClass
import com.intellij.psi.PsiAnnotation
import com.intellij.psi.PsiField
import com.intellij.psi.PsiMethod
import com.intellij.psi.PsiMethodCallExpression
import com.intellij.psi.PsiReferenceExpression
import com.siyeh.ig.BaseInspection
import com.siyeh.ig.BaseInspectionVisitor
import com.siyeh.ig.InspectionGadgetsFix
import org.jetbrains.annotations.Nls
class MethodCallSideOnlyInspection : BaseInspection() {
@Nls
override fun getDisplayName() =
"Invalid usage of a @SideOnly method call"
override fun buildErrorString(vararg infos: Any): String {
val error = infos[0] as Error
return error.getErrorString(*SideOnlyUtil.getSubArray(infos))
}
override fun getStaticDescription() =
"Methods which are declared with a @SideOnly annotation can only be " +
"used in matching @SideOnly classes and methods."
override fun buildFix(vararg infos: Any): InspectionGadgetsFix? {
val annotation = infos[3] as PsiAnnotation
return if (annotation.isWritable) {
RemoveAnnotationInspectionGadgetsFix(annotation, "Remove @SideOnly annotation from method declaration")
} else {
null
}
}
override fun buildVisitor(): BaseInspectionVisitor {
return object : BaseInspectionVisitor() {
override fun visitMethodCallExpression(expression: PsiMethodCallExpression) {
if (!SideOnlyUtil.beginningCheck(expression)) {
return
}
val referenceExpression = expression.methodExpression
val qualifierExpression = referenceExpression.qualifierExpression
// If this field is a @SidedProxy field, don't check. This is because people often are naughty and use the server impl as
// the base class for their @SidedProxy class, and client extends it. this messes up our checks, so we will just assume the
// right class is loaded for @SidedProxy's
run skip@{
if (qualifierExpression is PsiReferenceExpression) {
val resolve = qualifierExpression.resolve() as? PsiField ?: return@skip
val resolveFieldModifierList = resolve.modifierList ?: return@skip
if (resolveFieldModifierList.findAnnotation(ForgeConstants.SIDED_PROXY_ANNOTATION) == null) {
return@skip
}
return
}
}
val declaration = referenceExpression.resolve() as? PsiMethod ?: return
var (elementAnnotation, elementSide) = SideOnlyUtil.checkMethod(declaration)
// Check the class(es) the element is declared in
val declarationContainingClass = declaration.containingClass ?: return
val declarationClassHierarchySides = SideOnlyUtil.checkClassHierarchy(declarationContainingClass)
val (declarationClassAnnotation, declarationClassSide) =
SideOnlyUtil.getFirstSide(declarationClassHierarchySides)
// The element inherits the @SideOnly from it's parent class if it doesn't explicitly set it itself
var inherited = false
if (declarationClassAnnotation != null &&
declarationClassSide !== Side.NONE && (elementSide === Side.INVALID || elementSide === Side.NONE)
) {
inherited = true
elementSide = declarationClassSide
}
if (elementAnnotation == null || elementSide === Side.INVALID || elementSide === Side.NONE) {
return
}
// Check the class(es) the element is in
val containingClass = expression.findContainingClass() ?: return
val (classAnnotation, classSide) = SideOnlyUtil.getSideForClass(containingClass)
var classAnnotated = false
if (classAnnotation != null && classSide !== Side.NONE && classSide !== Side.INVALID) {
if (classSide !== elementSide) {
if (inherited) {
registerError(
referenceExpression.element,
Error.ANNOTATED_CLASS_METHOD_IN_CROSS_ANNOTATED_CLASS_METHOD,
elementAnnotation.renderSide(elementSide),
classAnnotation.renderSide(classSide),
declaration.getAnnotation(elementAnnotation.annotationName)
)
} else {
registerError(
referenceExpression.element,
Error.ANNOTATED_METHOD_IN_CROSS_ANNOTATED_CLASS_METHOD,
elementAnnotation.renderSide(elementSide),
classAnnotation.renderSide(classSide),
declaration.getAnnotation(elementAnnotation.annotationName)
)
}
}
classAnnotated = true
}
// Check the method the element is in
val (methodAnnotation, methodSide) = SideOnlyUtil.checkElementInMethod(expression)
// Put error on for method
if (methodAnnotation != null && elementSide !== methodSide && methodSide !== Side.INVALID) {
if (methodSide === Side.NONE) {
// If the class is properly annotated the method doesn't need to also be annotated
if (!classAnnotated) {
if (inherited) {
registerError(
referenceExpression.element,
Error.ANNOTATED_CLASS_METHOD_IN_UNANNOTATED_METHOD,
elementAnnotation.renderSide(elementSide),
null,
declaration.getAnnotation(elementAnnotation.annotationName)
)
} else {
registerError(
referenceExpression.element,
Error.ANNOTATED_METHOD_IN_UNANNOTATED_METHOD,
elementAnnotation.renderSide(elementSide),
null,
declaration.getAnnotation(elementAnnotation.annotationName)
)
}
}
} else {
if (inherited) {
registerError(
referenceExpression.element,
Error.ANNOTATED_CLASS_METHOD_IN_CROSS_ANNOTATED_METHOD,
elementAnnotation.renderSide(elementSide),
methodAnnotation.renderSide(methodSide),
declaration.getAnnotation(elementAnnotation.annotationName)
)
} else {
registerError(
referenceExpression.element,
Error.ANNOTATED_METHOD_IN_CROSS_ANNOTATED_METHOD,
elementAnnotation.renderSide(elementSide),
methodAnnotation.renderSide(methodSide),
declaration.getAnnotation(elementAnnotation.annotationName)
)
}
}
}
}
}
}
enum class Error {
ANNOTATED_METHOD_IN_UNANNOTATED_METHOD {
override fun getErrorString(vararg infos: Any): String {
return "Method annotated with " + infos[0] + " cannot be referenced in an un-annotated method."
}
},
ANNOTATED_CLASS_METHOD_IN_UNANNOTATED_METHOD {
override fun getErrorString(vararg infos: Any): String {
return "Method declared in a class annotated with " + infos[0] +
" cannot be referenced in an un-annotated method."
}
},
ANNOTATED_METHOD_IN_CROSS_ANNOTATED_METHOD {
override fun getErrorString(vararg infos: Any): String {
return "Method annotated with " + infos[0] +
" cannot be referenced in a method annotated with " + infos[1] + "."
}
},
ANNOTATED_CLASS_METHOD_IN_CROSS_ANNOTATED_METHOD {
override fun getErrorString(vararg infos: Any): String {
return "Method declared in a class annotated with " + infos[0] +
" cannot be referenced in a method annotated with " + infos[1] + "."
}
},
ANNOTATED_METHOD_IN_CROSS_ANNOTATED_CLASS_METHOD {
override fun getErrorString(vararg infos: Any): String {
return "Method annotated with " + infos[0] +
" cannot be referenced in a class annotated with " + infos[1] + "."
}
},
ANNOTATED_CLASS_METHOD_IN_CROSS_ANNOTATED_CLASS_METHOD {
override fun getErrorString(vararg infos: Any): String {
return "Method declared in a class annotated with " + infos[0] +
" cannot be referenced in a class annotated with " + infos[1] + "."
}
};
abstract fun getErrorString(vararg infos: Any): String
}
}
| mit | 6351206ad7fd30c35812df5439498acf | 45.081448 | 139 | 0.538786 | 6.217338 | false | false | false | false |
google/android-auto-companion-android | communication/src/com/google/android/libraries/car/communication/messagingsync/MessagingSyncManager.kt | 1 | 3102 | // Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.android.libraries.car.communication.messagingsync
import android.content.Context
import com.google.android.libraries.car.trustagent.FeatureManager
import com.google.android.libraries.car.trustagent.api.PublicApi
import java.util.UUID
/**
* Handles turning on messaging sync features, including turning on messaging sync
* and enable specific messaging apps
*/
@PublicApi
class MessagingSyncManager constructor(
private val context: Context,
private val timeProvider: TimeProvider = SystemTimeProvider()
) : FeatureManager() {
/** A map of car ids to messaging notification handlers. */
private val messagingHandlers = mutableMapOf<UUID, MessagingNotificationHandler>()
private val sharedHandlerState = NotificationHandlerSharedState()
private val messagingUtils = MessagingUtils(context)
override val featureId: UUID = FEATURE_ID
/**
* Assigns the car to all known handlers
*/
override fun onCarConnected(carId: UUID) {
// reuse the existing messaging handler before creating a new one
messagingHandlers.getOrPut(carId, { createMessagingHandler(carId) }).onCarConnected()
}
override fun onCarDisconnected(carId: UUID) {
messagingHandlers.remove(carId)?.onCarDisconnected()
}
override fun onMessageReceived(message: ByteArray, carId: UUID) {
messagingHandlers[carId]?.onMessageReceived(message)
}
override fun onMessageSent(messageId: Int, carId: UUID) {}
override fun onCarDisassociated(carId: UUID) {}
override fun onAllCarsDisassociated() {
// No-op
}
fun isMessagingSyncEnabled(carId: String): Boolean =
messagingUtils.isMessagingSyncEnabled(carId)
fun isNotificationAccessEnabled() =
messagingUtils.isNotificationAccessEnabled()
/**
* Handles the user flow to request user permissions and turn on messaging sync.
*/
fun enableMessagingSync(carId: String, onSuccess: () -> Unit, onFailure: (() -> Unit)?) =
messagingUtils.enableMessagingSync(carId, onSuccess, onFailure)
/**
* Turns off messaging sync feature.
*/
fun disableMessagingSync(carId: String) =
messagingUtils.disableMessagingSync(carId)
private fun createMessagingHandler(carId: UUID) = MessagingNotificationHandler(
context,
carId,
::sendMessage,
messagingUtils,
timeProvider,
sharedHandlerState
)
companion object {
// Recipient ID used by feature Third Party Messaging aka Snapback
private val FEATURE_ID = UUID.fromString("b2337f58-18ff-4f92-a0cf-4df63ab2c889")
}
}
| apache-2.0 | da22ed1aa12dd70c2d396667a90b618e | 32.717391 | 91 | 0.753063 | 4.502177 | false | false | false | false |
TUWien/DocScan | app/src/main/java/at/ac/tuwien/caa/docscan/logic/ExifHelper.kt | 1 | 9571 | package at.ac.tuwien.caa.docscan.logic
import androidx.exifinterface.media.ExifInterface
import at.ac.tuwien.caa.docscan.camera.ImageExifMetaData
import at.ac.tuwien.caa.docscan.db.model.error.IOErrorCode
import at.ac.tuwien.caa.docscan.db.model.exif.Rotation
import at.ac.tuwien.caa.docscan.db.model.exif.Rotation.Companion.getRotationByExif
import timber.log.Timber
import java.io.File
fun applyExifData(file: File, exifMetaData: ImageExifMetaData) {
try {
val exif = ExifInterface(file)
exif.setAttribute(
ExifInterface.TAG_ORIENTATION,
exifMetaData.exifOrientation.toString()
)
exif.setAttribute(ExifInterface.TAG_SOFTWARE, exifMetaData.exifSoftware)
exifMetaData.exifArtist?.let {
exif.setAttribute(ExifInterface.TAG_ARTIST, it)
}
exifMetaData.exifCopyRight?.let {
exif.setAttribute(ExifInterface.TAG_COPYRIGHT, it)
}
exifMetaData.location?.let {
exif.setAttribute(ExifInterface.TAG_GPS_LATITUDE, it.gpsLat)
exif.setAttribute(ExifInterface.TAG_GPS_LATITUDE_REF, it.gpsLatRef)
exif.setAttribute(ExifInterface.TAG_GPS_LONGITUDE, it.gpsLon)
exif.setAttribute(ExifInterface.TAG_GPS_LONGITUDE_REF, it.gpsLonRef)
}
exifMetaData.resolution?.let {
exif.setAttribute(ExifInterface.TAG_X_RESOLUTION, it.x)
exif.setAttribute(ExifInterface.TAG_Y_RESOLUTION, it.y)
}
exif.saveAttributes()
} catch (exception: Exception) {
Timber.e(exception, "Apply exif data has failed!")
}
}
fun getExifInterface(file: File): ExifInterface? {
return try {
ExifInterface(file)
} catch (e: Exception) {
Timber.e(e, "Unable to open exif interface!")
null
}
}
fun applyRotation(file: File, rotation: Rotation) {
try {
val exif = ExifInterface(file)
exif.setAttribute(
ExifInterface.TAG_ORIENTATION,
rotation.exifOrientation.toString()
)
exif.saveAttributes()
} catch (exception: Exception) {
Timber.e(exception, "Couldn't save exif attributes!")
}
}
fun applyRotationResource(file: File, rotation: Rotation): Resource<Unit> {
return try {
val exif = ExifInterface(file)
exif.setAttribute(ExifInterface.TAG_ORIENTATION, rotation.exifOrientation.toString())
exif.saveAttributes()
Success(Unit)
} catch (exception: Exception) {
Timber.e(exception, "Unable to apply exif orientation!")
IOErrorCode.APPLY_EXIF_ROTATION_ERROR.asFailure(exception)
}
}
fun getRotation(file: File): Rotation {
return try {
val exif = ExifInterface(file)
getRotationByExif(
exif.getAttributeInt(
ExifInterface.TAG_ORIENTATION,
ExifInterface.ORIENTATION_NORMAL
)
)
} catch (exception: Exception) {
Timber.e(exception, "Couldn't read orientation exif attribute!")
Rotation.ORIENTATION_NORMAL
}
}
fun removeRotation(file: File) {
try {
val exif = ExifInterface(file)
exif.setAttribute(
ExifInterface.TAG_ORIENTATION,
null
)
exif.saveAttributes()
} catch (exception: Exception) {
Timber.e(exception, "Couldn't remove exif rotation!")
}
}
/**
* Copies all existing exif information and resets the orientation to normal.
*/
fun saveExifAfterCrop(exif: ExifInterface, targetFile: File) {
try {
val newExif = ExifInterface(targetFile)
for (i in attributes.indices) {
val value = exif.getAttribute(attributes[i])
if (value != null) newExif.setAttribute(attributes[i], value)
}
newExif.resetOrientation()
newExif.saveAttributes()
} catch (e: Exception) {
Timber.e(e, "Couldn't save exif attributes!")
}
}
/**
* Represents all exif attributes which are preserved when files are copied.
*/
private val attributes = arrayOf(
// ExifInterface.TAG_ORIENTATION,
ExifInterface.TAG_ARTIST,
ExifInterface.TAG_BITS_PER_SAMPLE,
ExifInterface.TAG_BRIGHTNESS_VALUE,
ExifInterface.TAG_CFA_PATTERN,
ExifInterface.TAG_COLOR_SPACE,
ExifInterface.TAG_COMPONENTS_CONFIGURATION,
ExifInterface.TAG_COMPRESSED_BITS_PER_PIXEL,
ExifInterface.TAG_COMPRESSION,
ExifInterface.TAG_CONTRAST,
ExifInterface.TAG_COPYRIGHT,
ExifInterface.TAG_CUSTOM_RENDERED,
ExifInterface.TAG_DATETIME,
ExifInterface.TAG_DATETIME_DIGITIZED,
ExifInterface.TAG_DATETIME_ORIGINAL,
ExifInterface.TAG_DEFAULT_CROP_SIZE,
ExifInterface.TAG_DEVICE_SETTING_DESCRIPTION,
ExifInterface.TAG_DIGITAL_ZOOM_RATIO,
ExifInterface.TAG_DNG_VERSION,
ExifInterface.TAG_EXIF_VERSION,
ExifInterface.TAG_EXPOSURE_BIAS_VALUE,
ExifInterface.TAG_EXPOSURE_INDEX,
ExifInterface.TAG_EXPOSURE_MODE,
ExifInterface.TAG_EXPOSURE_PROGRAM,
ExifInterface.TAG_EXPOSURE_TIME,
ExifInterface.TAG_FILE_SOURCE,
ExifInterface.TAG_FLASH,
ExifInterface.TAG_FLASHPIX_VERSION,
ExifInterface.TAG_FLASH_ENERGY,
ExifInterface.TAG_FOCAL_LENGTH,
ExifInterface.TAG_FOCAL_LENGTH_IN_35MM_FILM,
ExifInterface.TAG_FOCAL_PLANE_RESOLUTION_UNIT,
ExifInterface.TAG_FOCAL_PLANE_X_RESOLUTION,
ExifInterface.TAG_FOCAL_PLANE_Y_RESOLUTION,
ExifInterface.TAG_F_NUMBER,
ExifInterface.TAG_GAIN_CONTROL,
ExifInterface.TAG_GPS_ALTITUDE,
ExifInterface.TAG_GPS_ALTITUDE_REF,
ExifInterface.TAG_GPS_AREA_INFORMATION,
ExifInterface.TAG_GPS_DATESTAMP,
ExifInterface.TAG_GPS_DEST_BEARING,
ExifInterface.TAG_GPS_DEST_BEARING_REF,
ExifInterface.TAG_GPS_DEST_DISTANCE,
ExifInterface.TAG_GPS_DEST_DISTANCE_REF,
ExifInterface.TAG_GPS_DEST_LATITUDE,
ExifInterface.TAG_GPS_DEST_LATITUDE_REF,
ExifInterface.TAG_GPS_DEST_LONGITUDE,
ExifInterface.TAG_GPS_DEST_LONGITUDE_REF,
ExifInterface.TAG_GPS_DIFFERENTIAL,
ExifInterface.TAG_GPS_DOP,
ExifInterface.TAG_GPS_IMG_DIRECTION,
ExifInterface.TAG_GPS_IMG_DIRECTION_REF,
ExifInterface.TAG_GPS_LATITUDE,
ExifInterface.TAG_GPS_LATITUDE_REF,
ExifInterface.TAG_GPS_LONGITUDE,
ExifInterface.TAG_GPS_LONGITUDE_REF,
ExifInterface.TAG_GPS_MAP_DATUM,
ExifInterface.TAG_GPS_MEASURE_MODE,
ExifInterface.TAG_GPS_PROCESSING_METHOD,
ExifInterface.TAG_GPS_SATELLITES,
ExifInterface.TAG_GPS_SPEED,
ExifInterface.TAG_GPS_SPEED_REF,
ExifInterface.TAG_GPS_STATUS,
ExifInterface.TAG_GPS_TIMESTAMP,
ExifInterface.TAG_GPS_TRACK,
ExifInterface.TAG_GPS_TRACK_REF,
ExifInterface.TAG_GPS_VERSION_ID,
ExifInterface.TAG_IMAGE_DESCRIPTION, // ExifInterface.TAG_IMAGE_LENGTH,
ExifInterface.TAG_IMAGE_UNIQUE_ID, // ExifInterface.TAG_IMAGE_WIDTH,
ExifInterface.TAG_INTEROPERABILITY_INDEX,
ExifInterface.TAG_PHOTOGRAPHIC_SENSITIVITY,
ExifInterface.TAG_JPEG_INTERCHANGE_FORMAT,
ExifInterface.TAG_JPEG_INTERCHANGE_FORMAT_LENGTH,
ExifInterface.TAG_LIGHT_SOURCE,
ExifInterface.TAG_MAKE,
ExifInterface.TAG_MAKER_NOTE,
ExifInterface.TAG_MAX_APERTURE_VALUE,
ExifInterface.TAG_METERING_MODE,
ExifInterface.TAG_MODEL,
ExifInterface.TAG_NEW_SUBFILE_TYPE,
ExifInterface.TAG_OECF,
ExifInterface.TAG_ORF_ASPECT_FRAME,
ExifInterface.TAG_ORF_PREVIEW_IMAGE_LENGTH,
ExifInterface.TAG_ORF_PREVIEW_IMAGE_START,
ExifInterface.TAG_ORF_THUMBNAIL_IMAGE, // ExifInterface.TAG_ORIENTATION,
ExifInterface.TAG_PHOTOMETRIC_INTERPRETATION, // ExifInterface.TAG_PIXEL_X_DIMENSION,
// ExifInterface.TAG_PIXEL_Y_DIMENSION,
ExifInterface.TAG_PLANAR_CONFIGURATION,
ExifInterface.TAG_PRIMARY_CHROMATICITIES,
ExifInterface.TAG_REFERENCE_BLACK_WHITE,
ExifInterface.TAG_RELATED_SOUND_FILE,
ExifInterface.TAG_RESOLUTION_UNIT, // ExifInterface.TAG_ROWS_PER_STRIP,
ExifInterface.TAG_RW2_ISO,
ExifInterface.TAG_RW2_JPG_FROM_RAW,
ExifInterface.TAG_RW2_SENSOR_BOTTOM_BORDER,
ExifInterface.TAG_RW2_SENSOR_LEFT_BORDER,
ExifInterface.TAG_RW2_SENSOR_RIGHT_BORDER,
ExifInterface.TAG_RW2_SENSOR_TOP_BORDER,
ExifInterface.TAG_SAMPLES_PER_PIXEL,
ExifInterface.TAG_SATURATION,
ExifInterface.TAG_SCENE_CAPTURE_TYPE,
ExifInterface.TAG_SCENE_TYPE,
ExifInterface.TAG_SENSING_METHOD,
ExifInterface.TAG_SHARPNESS,
ExifInterface.TAG_SHUTTER_SPEED_VALUE,
ExifInterface.TAG_SOFTWARE,
ExifInterface.TAG_SPATIAL_FREQUENCY_RESPONSE,
ExifInterface.TAG_SPECTRAL_SENSITIVITY, // ExifInterface.TAG_STRIP_BYTE_COUNTS,
// ExifInterface.TAG_STRIP_OFFSETS,
ExifInterface.TAG_SUBFILE_TYPE,
ExifInterface.TAG_SUBJECT_AREA,
ExifInterface.TAG_SUBJECT_DISTANCE,
ExifInterface.TAG_SUBJECT_DISTANCE_RANGE,
ExifInterface.TAG_SUBJECT_LOCATION,
ExifInterface.TAG_SUBSEC_TIME,
ExifInterface.TAG_SUBSEC_TIME_DIGITIZED,
ExifInterface.TAG_SUBSEC_TIME_ORIGINAL,
ExifInterface.TAG_THUMBNAIL_IMAGE_LENGTH,
ExifInterface.TAG_THUMBNAIL_IMAGE_WIDTH,
ExifInterface.TAG_TRANSFER_FUNCTION,
ExifInterface.TAG_USER_COMMENT,
ExifInterface.TAG_WHITE_BALANCE,
ExifInterface.TAG_WHITE_POINT, // ExifInterface.TAG_X_RESOLUTION,
ExifInterface.TAG_Y_CB_CR_COEFFICIENTS,
ExifInterface.TAG_Y_CB_CR_POSITIONING,
ExifInterface.TAG_Y_CB_CR_SUB_SAMPLING
)
| lgpl-3.0 | df58eb930e9a52f1b7c037a3adffef6a | 37.284 | 113 | 0.697942 | 4.028199 | false | false | false | false |
MarcelBlanck/AoC2016 | src/test/kotlin/day1/StreetGridWalkerSpec.kt | 1 | 4974 | /*
* MIT License
*
* Copyright (c) 2017 Marcel Blanck
*
* 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 day1
import com.winterbe.expekt.should
import org.jetbrains.spek.api.Spek
import org.jetbrains.spek.api.dsl.given
import org.jetbrains.spek.api.dsl.it
import org.jetbrains.spek.api.dsl.on
import org.junit.platform.runner.JUnitPlatform
import org.junit.runner.RunWith
@RunWith(JUnitPlatform::class)
class StreetGridWalkerSpec : Spek({
given("a StreetGridWalker") {
val streetGridWalker = StreetGridWalker()
on("malformed directions input for getDistanceToLastDirection") {
val walkingDirections = listOf("R2", "L4", "Error!?", "L2")
it("should throw ObjectStreamException") {
try {
streetGridWalker.getDistanceToLastDirection(walkingDirections)
} catch (ex : Exception) {
assert(ex is IllegalArgumentException)
}
}
}
on("malformed directions input for getDistanceToFirstIntersection") {
val walkingDirections = listOf("R2", "L4", "Error!?", "L2")
it("should throw ObjectStreamException") {
try {
streetGridWalker.getDistanceToLastDirection(walkingDirections)
} catch (ex : Exception) {
assert(ex is IllegalArgumentException)
}
}
}
on("empty directions input for getDistanceToLastDirection") {
val walkingDirections : List<String> = emptyList()
it("should walk to an overall distance of 0") {
streetGridWalker.getDistanceToLastDirection(walkingDirections).should.be.equal(0)
}
}
on("R1 input for getDistanceToLastDirection") {
val walkingDirections = listOf("R1")
it("should walk to an overall distance of 1") {
streetGridWalker.getDistanceToLastDirection(walkingDirections).should.be.equal(1)
}
}
on("L1 input for getDistanceToLastDirection") {
val walkingDirections = listOf("L1")
it("should walk to an overall distance of 1") {
streetGridWalker.getDistanceToLastDirection(walkingDirections).should.be.equal(1)
}
}
on("R2, L3 input for getDistanceToLastDirection") {
val walkingDirections = listOf("R2", "L3")
it("should walk to an overall distance of 5") {
streetGridWalker.getDistanceToLastDirection(walkingDirections).should.be.equal(5)
}
}
on("R2, R2, R2 input for getDistanceToLastDirection") {
val walkingDirections = listOf("R2", "R2", "R2")
it("should walk to an overall distance of 2") {
streetGridWalker.getDistanceToLastDirection(walkingDirections).should.be.equal(2)
}
}
on("R5, L5, R5, R3 input for getDistanceToLastDirection") {
val walkingDirections = listOf("R5", "L5", "R5", "R3")
it("should walk to an overall distance of 12") {
streetGridWalker.getDistanceToLastDirection(walkingDirections).should.be.equal(12)
}
}
on("R5, '', L5 input for getDistanceToLastDirection") {
val walkingDirections = listOf("R5", "", "L5")
it("should walk to an overall distance of 10") {
streetGridWalker.getDistanceToLastDirection(walkingDirections).should.be.equal(10)
}
}
on("R4, L4, L4, L8 input for getDistanceToFirstIntersection") {
val walkingDirections = listOf("R4", "L4", "L4", "L4")
it("should report distance to first location visited twice is 0 (intersection at origin)") {
streetGridWalker.getDistanceToFirstIntersection(walkingDirections).should.be.equal(0)
}
}
}
}) | mit | b5ea19e022116bbabf481c7952e51629 | 41.887931 | 104 | 0.639526 | 4.575897 | false | false | false | false |
bogerchan/National-Geography | app/src/main/java/me/boger/geographic/biz/detailpage/DetailPageFragment.kt | 1 | 13783 | package me.boger.geographic.biz.detailpage
import android.animation.Animator
import android.animation.AnimatorListenerAdapter
import android.animation.ValueAnimator
import android.content.ContentResolver
import android.content.Intent
import android.os.Bundle
import android.support.design.widget.Snackbar
import android.support.v4.view.ViewPager
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.ViewTreeObserver
import android.view.animation.LinearInterpolator
import android.view.animation.OvershootInterpolator
import android.widget.Toast
import me.boger.geographic.R
import me.boger.geographic.biz.common.ContentType
import me.boger.geographic.core.AppConfiguration
import me.boger.geographic.core.NGFragment
import me.boger.geographic.core.NGUtil
import me.boger.geographic.view.SealedIconFont
import me.boger.geographic.view.SealedTextView
import java.io.Serializable
import java.util.*
/**
* Created by BogerChan on 2017/6/30.
*/
class DetailPageFragment : NGFragment(), IDetailPageUI {
companion object {
val TAG = "DetailPageFragment"
val KEY_FRAGMENT_DETAIL_PAGE_INTERNAL_DATA = "key_fragment_detail_page_internal_data"
}
private val mPresenter: IDetailPagePresenter by lazy { DetailPagePresenterImpl() }
private val llcIntroAndMenu by lazy {
view!!.findViewById(R.id.llc_fragment_ng_detail_intro_and_menu)
}
private val llcMenuShare by lazy {
view!!.findViewById(R.id.llc_fragment_ng_detail_menu_share)
}
private val llcMenuSave by lazy {
view!!.findViewById(R.id.llc_fragment_ng_detail_menu_save)
}
private val llcMenuFav by lazy {
view!!.findViewById(R.id.llc_fragment_ng_detail_menu_fav)
}
private val llcMenu by lazy {
view!!.findViewById(R.id.llc_fragment_ng_detail_menu)
}
private val llcLoading by lazy {
view!!.findViewById(R.id.llc_fragment_ng_detail_loading)
}
private val tvTitle by lazy {
view!!.findViewById(R.id.tv_fragment_ng_detail_title) as SealedTextView
}
private val tvPageIdx by lazy {
view!!.findViewById(R.id.tv_fragment_ng_detail_page_idx) as SealedTextView
}
private val tvBody by lazy {
view!!.findViewById(R.id.tv_fragment_ng_detail_body) as SealedTextView
}
private val vpContent by lazy {
view!!.findViewById(R.id.vp_fragment_ng_detail) as ViewPager
}
private val tvMenuButton by lazy {
view!!.findViewById(R.id.icon_fragment_ng_detail_menu) as SealedIconFont
}
private val tvMenuFavIcon by lazy {
view!!.findViewById(R.id.icon_fragment_ng_detail_menu_fav) as SealedIconFont
}
private val vMenuDivider by lazy {
view!!.findViewById(R.id.v_fragment_ng_detail_divider_menu)
}
private val ablTitleBar by lazy {
activity!!.findViewById(R.id.abl_activity_main_ng_title)
}
private val mMenuDividerList by lazy {
arrayOf(
view!!.findViewById(R.id.v_fragment_ng_detail_divider_1),
view!!.findViewById(R.id.v_fragment_ng_detail_divider_2),
view!!.findViewById(R.id.v_fragment_ng_detail_divider_3)
)
}
private var mPendingMenuAnimator: Animator? = null
private var mPendingOverlayAnimator: Animator? = null
private class InternalData(var id: String? = null,
var offlineData: DetailPageData? = null) : Serializable
private lateinit var mInternalData: InternalData
override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View {
return inflater!!.inflate(R.layout.fragment_ng_detail, container, false)
}
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
restoreDataIfNeed(savedInstanceState)
mPresenter.restoreDataIfNeed(savedInstanceState)
initView()
mPresenter.init(this)
}
override fun onDestroyView() {
super.onDestroyView()
mPresenter.destroy()
}
override fun onDestroy() {
super.onDestroy()
setOverlayMenuShown(true)
}
private fun restoreDataIfNeed(savedInstanceState: Bundle?) {
if (savedInstanceState == null
|| !savedInstanceState.containsKey(KEY_FRAGMENT_DETAIL_PAGE_INTERNAL_DATA)) {
return
}
mInternalData = savedInstanceState.getSerializable(KEY_FRAGMENT_DETAIL_PAGE_INTERNAL_DATA) as InternalData
}
override fun onSaveInstanceState(outState: Bundle?) {
super.onSaveInstanceState(outState)
mPresenter.onSaveInstanceState(outState)
if (outState == null) {
return
}
outState.putSerializable(KEY_FRAGMENT_DETAIL_PAGE_INTERNAL_DATA, mInternalData)
}
fun initData(id: String?, offlineData: DetailPageData?) {
mInternalData = InternalData(id, offlineData)
}
fun initView() {
val adapter = DetailPageAdapter()
adapter.setOnItemClickListener(object : DetailPageAdapter.OnItemClickListener {
private var show: Boolean = true
override fun onItemClick(v: View, position: Int) {
show = !show
setOverlayMenuShown(show)
}
})
vpContent.adapter = adapter
vpContent.pageMargin = AppConfiguration.dp2px(10).toInt()
vpContent.addOnPageChangeListener(object : ViewPager.SimpleOnPageChangeListener() {
override fun onPageSelected(position: Int) {
updateContent(adapter.data, position)
}
})
llcIntroAndMenu.viewTreeObserver
.addOnGlobalLayoutListener(object : ViewTreeObserver.OnGlobalLayoutListener {
override fun onGlobalLayout() {
setBottomMenuExpanded(false)
llcIntroAndMenu.viewTreeObserver.removeOnGlobalLayoutListener(this)
}
})
tvMenuButton.setOnClickListener(object : View.OnClickListener {
private var expand: Boolean = false
override fun onClick(p0: View?) {
expand = !expand
setBottomMenuExpanded(expand)
}
})
llcMenuShare.setOnClickListener {
mPresenter.shareDetailPageImage(
(vpContent.adapter as DetailPageAdapter).data[vpContent.currentItem].url)
}
llcMenuSave.setOnClickListener {
mPresenter.saveDetailPageImage(
(vpContent.adapter as DetailPageAdapter).data[vpContent.currentItem].url)
}
llcMenuFav.setOnClickListener {
mPresenter.setDetailPageItemFavoriteState(
(vpContent.adapter as DetailPageAdapter).data[vpContent.currentItem])
}
}
override var contentType = ContentType.UNSET
get() {
return field
}
set(value) {
when (value) {
ContentType.LOADING -> {
llcLoading.visibility = View.VISIBLE
llcIntroAndMenu.visibility = View.INVISIBLE
vpContent.visibility = View.INVISIBLE
tvMenuButton.visibility = View.INVISIBLE
}
ContentType.CONTENT -> {
llcLoading.visibility = View.INVISIBLE
llcIntroAndMenu.visibility = View.VISIBLE
vpContent.visibility = View.VISIBLE
tvMenuButton.visibility = View.VISIBLE
}
ContentType.ERROR -> {
Snackbar.make(view, R.string.tip_load_error, Snackbar.LENGTH_SHORT).show()
fragmentManager.beginTransaction().remove(this).commit()
}
else -> {
}
}
field = value
}
override fun refreshData(data: List<DetailPagePictureData>) {
if (data.isEmpty()) {
return
}
val adapter = vpContent.adapter as DetailPageAdapter
adapter.data = data
adapter.notifyDataSetChanged()
vpContent.currentItem = 0
updateContent(data, 0)
}
private fun updateContent(dataList: List<DetailPagePictureData>, idx: Int) {
val data = dataList[idx]
val localeData = data.locale()
tvTitle.text = localeData.title
tvPageIdx.text = String.format(Locale.US, "%2d/%2d", idx + 1, dataList.size)
tvBody.text = String.format(Locale.US, getResourceString(R.string.template_detail_text_body), localeData.content, localeData.author)
setFavoriteButtonState(data.favorite)
}
private fun setOverlayMenuShown(show: Boolean) {
mPendingOverlayAnimator?.cancel()
// val titleBar = mMainUIController.getTitleBar()
val range = if (show) arrayOf(ablTitleBar.alpha, 1f) else arrayOf(ablTitleBar.alpha, 0f)
val ani = ValueAnimator.ofFloat(*range.toFloatArray())
ani.duration = 300
ani.interpolator = LinearInterpolator()
ani.addUpdateListener {
val value = it.animatedValue as Float
ablTitleBar.alpha = value
if (isVisible) {
llcIntroAndMenu.alpha = value
tvMenuButton.alpha = value
}
}
ani.addListener(object : AnimatorListenerAdapter() {
override fun onAnimationStart(animation: Animator?) {
mPendingOverlayAnimator = ani
if (show) {
ablTitleBar.visibility = View.VISIBLE
if (isVisible) {
llcIntroAndMenu.visibility = View.VISIBLE
tvMenuButton.visibility = View.VISIBLE
}
}
}
override fun onAnimationEnd(animation: Animator?) {
mPendingOverlayAnimator = null
if (!show) {
ablTitleBar.visibility = View.INVISIBLE
if (isVisible) {
llcIntroAndMenu.visibility = View.INVISIBLE
tvMenuButton.visibility = View.INVISIBLE
}
}
}
})
ani.start()
}
private fun setBottomMenuExpanded(expand: Boolean) {
mPendingMenuAnimator?.cancel()
val iconText = if (expand) "\ue649" else "\ue6e5"
val range = if (expand) arrayOf(llcIntroAndMenu.translationY, 0f) else
arrayOf(llcIntroAndMenu.translationY, (llcIntroAndMenu.height - vMenuDivider.top).toFloat())
val ani = ValueAnimator.ofFloat(*range.toFloatArray())
ani.duration = 500
ani.interpolator = OvershootInterpolator()
ani.addUpdateListener {
val value = it.animatedValue as Float
llcIntroAndMenu.translationY = value
val fraction = it.animatedFraction
tvMenuButton.rotation = fraction
if (fraction > .5f) {
tvMenuButton.alpha = (fraction - 0.5f) * 2
if (iconText != tvMenuButton.text) {
tvMenuButton.text = iconText
}
} else {
tvMenuButton.alpha = 1 - fraction * 2
}
}
ani.addListener(object : AnimatorListenerAdapter() {
override fun onAnimationStart(animation: Animator?) {
mPendingMenuAnimator = ani
if (!isVisible) {
return
}
if (expand) {
llcMenuShare.visibility = View.VISIBLE
llcMenuSave.visibility = View.VISIBLE
llcMenuFav.visibility = View.VISIBLE
mMenuDividerList.forEach {
it.visibility = View.VISIBLE
}
tvBody.maxLines = Int.MAX_VALUE
} else {
tvBody.maxLines = 4
}
}
override fun onAnimationEnd(animation: Animator?) {
mPendingMenuAnimator = null
if (!isVisible) {
return
}
if (!expand) {
llcMenuShare.visibility = View.INVISIBLE
llcMenuSave.visibility = View.INVISIBLE
llcMenuFav.visibility = View.INVISIBLE
mMenuDividerList.forEach {
it.visibility = View.INVISIBLE
}
}
}
})
ani.start()
}
override fun showTipMessage(msg: String) {
if (NGUtil.isUIThread()) {
Toast.makeText(activity, msg, Toast.LENGTH_SHORT).show()
} else {
activity.runOnUiThread {
Toast.makeText(activity, msg, Toast.LENGTH_SHORT).show()
}
}
}
override fun showTipMessage(msgId: Int) {
Toast.makeText(activity, activity.getString(msgId), Toast.LENGTH_SHORT).show()
}
override fun getResourceString(id: Int): String = activity.getString(id)
override fun getContentResolver(): ContentResolver = activity.contentResolver
override fun sendBroadcast(intent: Intent) {
activity.sendBroadcast(intent)
}
override fun setFavoriteButtonState(favorite: Boolean) {
tvMenuFavIcon.text = if (favorite) "\ue677" else "\ue603"
}
override fun hasOfflineData(): Boolean = mInternalData.offlineData != null
override fun getOfflineData(): DetailPageData = mInternalData.offlineData!!
override fun getDetailPageDataId(): String = mInternalData.id!!
} | apache-2.0 | 0792ad0360e813b8676a8f604f7c71d8 | 34.525773 | 140 | 0.609229 | 4.814181 | false | false | false | false |
TCA-Team/TumCampusApp | app/src/main/java/de/tum/in/tumcampusapp/component/ui/studyroom/model/StudyRoomGroup.kt | 1 | 735 | package de.tum.`in`.tumcampusapp.component.ui.studyroom.model
import androidx.room.Entity
import androidx.room.Ignore
import androidx.room.PrimaryKey
import com.google.gson.annotations.SerializedName
/**
* Representation of a study room group
*/
@Entity(tableName = "study_room_groups")
data class StudyRoomGroup(
@PrimaryKey
@SerializedName("id")
var id: Int = -1,
@SerializedName("name")
var name: String = "",
@SerializedName("details")
var details: String = "",
@Ignore
@SerializedName("rooms")
var rooms: List<StudyRoom> = emptyList()
) : Comparable<StudyRoomGroup> {
override fun toString() = name
override fun compareTo(other: StudyRoomGroup) = name.compareTo(other.name)
}
| gpl-3.0 | 6173a1956b036244b5d2b701cbad532d | 25.25 | 78 | 0.708844 | 4.016393 | false | false | false | false |
kohesive/klutter | core/src/main/kotlin/uy/klutter/core/collections/Immutable.kt | 2 | 8160 | package uy.klutter.core.collections
import java.io.Serializable
import java.util.*
// based off of the answer from @miensol in this Stackoverflow answer http://stackoverflow.com/a/37936456/3679676
interface ReadOnly
/**
* Wraps an Iterator with a lightweight delegating class that prevents casting back to mutable type
*/
class ReadOnlyIterator <T> (private val delegate: Iterator<T>) : Iterator<T> by delegate, ReadOnly, Serializable {
companion object {
@JvmField val serialVersionUID = 1L
}
override fun toString(): String {
return "ReadOnly: ${super.toString()}"
}
override fun equals(other: Any?): Boolean {
return delegate.equals(other)
}
override fun hashCode(): Int {
return delegate.hashCode()
}
}
/**
* Wraps a Collection with a lightweight delegating class that prevents casting back to mutable type
*/
class ReadOnlyCollection <T> (private val delegate: Collection<T>) : Collection<T> by delegate, ReadOnly, Serializable {
companion object {
@JvmField val serialVersionUID = 1L
}
override fun iterator(): Iterator<T> {
return delegate.iterator().asReadOnly()
}
override fun toString(): String {
return "ReadOnly: ${super.toString()}"
}
override fun equals(other: Any?): Boolean {
return delegate.equals(other)
}
override fun hashCode(): Int {
return delegate.hashCode()
}
}
/**
* Wraps a ListIterator with a lightweight delegating class that prevents casting back to mutable type
*/
class ReadOnlyListIterator <T> (private val delegate: ListIterator<T>): ListIterator<T> by delegate, ReadOnly, Serializable {
companion object {
@JvmField val serialVersionUID = 1L
}
override fun toString(): String {
return "ReadOnly: ${super.toString()}"
}
override fun equals(other: Any?): Boolean {
return delegate.equals(other)
}
override fun hashCode(): Int {
return delegate.hashCode()
}
}
/**
* Wraps a List with a lightweight delegating class that prevents casting back to mutable type
*/
open class ReadOnlyList <T>(protected val delegate: List<T>) : List<T> by delegate, ReadOnly, Serializable {
companion object {
@JvmField val serialVersionUID = 1L
}
override fun iterator(): Iterator<T> {
return delegate.iterator().asReadOnly()
}
override fun listIterator(): ListIterator<T> {
return delegate.listIterator().asReadOnly()
}
override fun listIterator(index: Int): ListIterator<T> {
return delegate.listIterator(index).asReadOnly()
}
override fun subList(fromIndex: Int, toIndex: Int): List<T> {
return delegate.subList(fromIndex, toIndex).asReadOnly()
}
override fun toString(): String {
return "ReadOnly: ${super.toString()}"
}
override fun equals(other: Any?): Boolean {
return delegate.equals(other)
}
override fun hashCode(): Int {
return delegate.hashCode()
}
}
/**
* Wraps a List that is also RandomAccess with a delegating class that prevents casting back to mutable type
*/
class ReadOnlyRandomAccessList <T> (delegate: List<T>): ReadOnlyList<T>(delegate), List<T>, ReadOnly, RandomAccess, Serializable {
companion object {
@JvmField val serialVersionUID = 1L
}
override fun toString(): String {
return "ReadOnly: ${super.toString()}"
}
override fun equals(other: Any?): Boolean {
return delegate.equals(other)
}
override fun hashCode(): Int {
return delegate.hashCode()
}
}
/**
* Wraps a Set with a lightweight delegating class that prevents casting back to mutable type
*/
class ReadOnlySet <T>(private val delegate: Set<T>) : Set<T> by delegate, ReadOnly, Serializable {
companion object {
@JvmField val serialVersionUID = 1L
}
override fun iterator(): Iterator<T> {
return delegate.iterator().asReadOnly()
}
override fun toString(): String {
return "ReadOnly: ${super.toString()}"
}
override fun equals(other: Any?): Boolean {
return delegate.equals(other)
}
override fun hashCode(): Int {
return delegate.hashCode()
}
}
/**
* Wraps a Map with a lightweight delegating class that prevents casting back to mutable type
*/
class ReadOnlyMap <K : Any, V>(private val delegate: Map<K, V>) : Map<K, V> by delegate, ReadOnly, Serializable {
companion object {
@JvmField val serialVersionUID = 1L
}
override val keys: Set<K>
get() = delegate.keys.asReadOnly()
override val values: Collection<V>
get() = delegate.values.asReadOnly()
override val entries: kotlin.collections.Set<kotlin.collections.Map.Entry<K, V>>
get() = delegate.entries.asReadOnly()
override fun toString(): String {
return "ReadOnly: ${super.toString()}"
}
override fun equals(other: Any?): Boolean {
return delegate.equals(other)
}
override fun hashCode(): Int {
return delegate.hashCode()
}
}
/**
* Wraps the Iterator with a lightweight delegating class that prevents casting back to mutable type
*/
fun <T> Iterator<T>.asReadOnly(): Iterator<T> = this.whenNotAlreadyReadOnly { ReadOnlyIterator(it) }
/**
* Wraps the ListIterator with a lightweight delegating class that prevents casting back to mutable type
*/
fun <T> ListIterator<T>.asReadOnly(): ListIterator<T> = this.whenNotAlreadyReadOnly { ReadOnlyListIterator(it) }
/**
* Wraps the Collection with a lightweight delegating class that prevents casting back to mutable type
*/
fun <T> Collection<T>.asReadOnly(): Collection<T> = this.whenNotAlreadyReadOnly { ReadOnlyCollection(it) }
/**
* Wraps the List with a lightweight delegating class that prevents casting back to mutable type,
* specializing for the case of the RandomAccess marker interface being retained if it was there originally
*/
fun <T> List<T>.asReadOnly(): List<T> {
return this.whenNotAlreadyReadOnly {
when (it) {
is RandomAccess -> ReadOnlyRandomAccessList(it)
else -> ReadOnlyList(it)
}
}
}
/**
* Copies the List and then wraps with a lightweight delegating class that prevents casting back to mutable type,
* specializing for the case of the RandomAccess marker interface being retained if it was there originally
*/
@Suppress("UNCHECKED_CAST")
fun <T> List<T>.toImmutable(): List<T> {
val copy = when (this) {
is RandomAccess -> ArrayList<T>(this)
else -> this.toList()
}
return when (copy) {
is RandomAccess -> ReadOnlyRandomAccessList(copy)
else -> ReadOnlyList(copy)
}
}
/**
* Wraps the List as a Collection with a lightweight delegating class that prevents casting back to mutable type
*/
fun <T> List<T>.asReadOnlyCollection(): Collection<T> = this.whenNotAlreadyReadOnly { ReadOnlyCollection(it) }
/**
* Wraps the Set with a lightweight delegating class that prevents casting back to mutable type
*/
fun <T> Set<T>.asReadOnly(): Set<T> = this.whenNotAlreadyReadOnly { ReadOnlySet(it) }
/**
* Copies the Set and then wraps with a lightweight delegating class that prevents casting back to mutable type
*/
fun <T> Set<T>.toImmutable(): Set<T> = ReadOnlySet(this.toSet())
/**
* Wraps the Set as a Collection with a lightweight delegating class that prevents casting back to mutable type
*/
fun <T> Set<T>.asReadOnlyCollection(): Collection<T> = this.whenNotAlreadyReadOnly { ReadOnlyCollection(it) }
/**
* Wraps the Map with a lightweight delegating class that prevents casting back to mutable type
*/
fun <K : Any, V> Map<K, V>.asReadOnly(): Map<K, V> = this.whenNotAlreadyReadOnly { ReadOnlyMap(it) }
/**
* Copies the Map and then wraps with a lightweight delegating class that prevents casting back to mutable type
*/
fun <K : Any, V> Map<K, V>.toImmutable(): Map<K, V> = ReadOnlyMap(this.asSequence().map { it.key to it.value }.toMap())
private inline fun <T: R, R: Any> T.whenNotAlreadyReadOnly(makeReadOnly: (T)->R): R = if (this is ReadOnly) this else makeReadOnly(this) | mit | 8b8e45afe3bdddff30af292974a787f2 | 29.912879 | 136 | 0.680025 | 4.247788 | false | false | false | false |
westnordost/StreetComplete | app/src/main/java/de/westnordost/streetcomplete/quests/max_speed/AddMaxSpeedForm.kt | 1 | 11736 | package de.westnordost.streetcomplete.quests.max_speed
import android.os.Bundle
import android.view.View
import android.view.inputmethod.EditorInfo
import android.view.inputmethod.InputMethodManager
import android.widget.ArrayAdapter
import android.widget.EditText
import android.widget.ImageView
import android.widget.Spinner
import androidx.annotation.IdRes
import androidx.appcompat.app.AlertDialog
import androidx.core.content.getSystemService
import androidx.core.view.children
import androidx.core.view.isGone
import de.westnordost.streetcomplete.R
import de.westnordost.streetcomplete.ktx.numberOrNull
import de.westnordost.streetcomplete.quests.AbstractQuestFormAnswerFragment
import de.westnordost.streetcomplete.quests.OtherAnswer
import de.westnordost.streetcomplete.quests.max_speed.SpeedMeasurementUnit.KILOMETERS_PER_HOUR
import de.westnordost.streetcomplete.quests.max_speed.SpeedMeasurementUnit.MILES_PER_HOUR
import de.westnordost.streetcomplete.quests.max_speed.SpeedType.*
import de.westnordost.streetcomplete.util.TextChangedWatcher
import kotlinx.android.synthetic.main.quest_maxspeed.*
class AddMaxSpeedForm : AbstractQuestFormAnswerFragment<MaxSpeedAnswer>() {
override val contentLayoutResId = R.layout.quest_maxspeed
override val otherAnswers: List<OtherAnswer> get() {
val result = mutableListOf<OtherAnswer>()
if (countryInfo.isAdvisorySpeedLimitKnown) {
result.add(OtherAnswer(R.string.quest_maxspeed_answer_advisory_speed_limit) { switchToAdvisorySpeedLimit() })
}
return result
}
private var speedInput: EditText? = null
private var speedUnitSelect: Spinner? = null
private var speedType: SpeedType? = null
private val speedUnits get() = countryInfo.speedUnits.map { it.toSpeedMeasurementUnit() }
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val highwayTag = osmElement!!.tags["highway"]!!
val couldBeSlowZone = countryInfo.isSlowZoneKnown && POSSIBLY_SLOWZONE_ROADS.contains(highwayTag)
zone.isGone = !couldBeSlowZone
val couldBeLivingStreet = countryInfo.isLivingStreetKnown && MAYBE_LIVING_STREET.contains(highwayTag)
living_street.isGone = !couldBeLivingStreet
speedTypeSelect.setOnCheckedChangeListener { _, checkedId -> setSpeedType(getSpeedType(checkedId)) }
}
override fun onClickOk() {
if (speedType == NO_SIGN) {
val couldBeSlowZone = countryInfo.isSlowZoneKnown
&& POSSIBLY_SLOWZONE_ROADS.contains(osmElement!!.tags["highway"])
if (couldBeSlowZone)
confirmNoSignSlowZone { determineImplicitMaxspeedType() }
else
confirmNoSign { determineImplicitMaxspeedType() }
} else if (speedType == LIVING_STREET) {
applyAnswer(IsLivingStreet)
} else {
if (userSelectedUnusualSpeed())
confirmUnusualInput { applySpeedLimitFormAnswer() }
else
applySpeedLimitFormAnswer()
}
}
override fun isFormComplete() =
speedType == NO_SIGN || speedType == LIVING_STREET || getSpeedFromInput() != null
/* ---------------------------------------- With sign --------------------------------------- */
private fun setSpeedType(speedType: SpeedType?) {
this.speedType = speedType
rightSideContainer.removeAllViews()
speedType?.layoutResId?.let { layoutInflater.inflate(it, rightSideContainer, true) }
// this is necessary because the inflated image view uses the activity context rather than
// the fragment / layout inflater context' resources to access it's drawable
val img = rightSideContainer.findViewById<ImageView>(R.id.livingStreetImage)
img?.setImageDrawable(resources.getDrawable(R.drawable.ic_living_street))
speedInput = rightSideContainer.findViewById(R.id.maxSpeedInput)
speedInput?.addTextChangedListener(TextChangedWatcher { checkIsFormComplete() })
speedUnitSelect = rightSideContainer.findViewById(R.id.speedUnitSelect)
speedUnitSelect?.isGone = speedUnits.size == 1
speedUnitSelect?.adapter = ArrayAdapter(requireContext(), R.layout.spinner_item_centered, speedUnits)
speedUnitSelect?.setSelection(0)
if (speedType == ZONE && LAST_INPUT_SLOW_ZONE != null) {
speedInput?.setText(LAST_INPUT_SLOW_ZONE.toString())
} else {
speedInput?.requestFocus()
speedInput?.let { showKeyboard(it) }
}
checkIsFormComplete()
}
private fun getSpeedType(@IdRes checkedId: Int) = when (checkedId) {
R.id.sign -> SIGN
R.id.zone -> ZONE
R.id.living_street -> LIVING_STREET
R.id.no_sign -> NO_SIGN
else -> null
}
private val SpeedType.layoutResId get() = when (this) {
SIGN -> R.layout.quest_maxspeed_sign
ZONE -> R.layout.quest_maxspeed_zone_sign
LIVING_STREET -> R.layout.quest_maxspeed_living_street_sign
ADVISORY -> R.layout.quest_maxspeed_advisory
else -> null
}
private fun userSelectedUnusualSpeed(): Boolean {
val speed = getSpeedFromInput() ?: return false
val kmh = speed.toKmh()
return kmh > 140 || kmh > 20 && speed.toValue() % 5 != 0
}
private fun switchToAdvisorySpeedLimit() {
speedTypeSelect.clearCheck()
for (child in speedTypeSelect.children) {
child.isEnabled = false
}
setSpeedType(ADVISORY)
}
private fun showKeyboard(focus: View) {
val imm = activity?.getSystemService<InputMethodManager>()
imm?.showSoftInput(focus, InputMethodManager.SHOW_IMPLICIT)
}
private fun confirmUnusualInput(onConfirmed: () -> Unit) {
activity?.let { AlertDialog.Builder(it)
.setTitle(R.string.quest_generic_confirmation_title)
.setMessage(R.string.quest_maxspeed_unusualInput_confirmation_description)
.setPositiveButton(R.string.quest_generic_confirmation_yes) { _, _ -> onConfirmed() }
.setNegativeButton(R.string.quest_generic_confirmation_no, null)
.show()
}
}
private fun applySpeedLimitFormAnswer() {
val speed = getSpeedFromInput()!!
when (speedType) {
ADVISORY -> applyAnswer(AdvisorySpeedSign(speed))
ZONE -> {
val zoneX = speed.toValue()
LAST_INPUT_SLOW_ZONE = zoneX
applyAnswer(MaxSpeedZone(speed, countryInfo.countryCode, "zone$zoneX"))
}
SIGN -> applyAnswer(MaxSpeedSign(speed))
else -> throw IllegalStateException()
}
}
private fun getSpeedFromInput(): SpeedMeasure? {
val value = speedInput?.numberOrNull?.toInt() ?: return null
val unit = speedUnitSelect?.selectedItem as SpeedMeasurementUnit? ?: speedUnits.first()
return when(unit) {
KILOMETERS_PER_HOUR -> Kmh(value)
MILES_PER_HOUR -> Mph(value)
}
}
/* ----------------------------------------- No sign ---------------------------------------- */
private fun confirmNoSign(onConfirmed: () -> Unit) {
activity?.let {
AlertDialog.Builder(it)
.setTitle(R.string.quest_maxspeed_answer_noSign_confirmation_title)
.setMessage(R.string.quest_maxspeed_answer_noSign_confirmation)
.setPositiveButton(R.string.quest_maxspeed_answer_noSign_confirmation_positive) { _, _ -> onConfirmed() }
.setNegativeButton(R.string.quest_generic_confirmation_no, null)
.show()
}
}
private fun confirmNoSignSlowZone(onConfirmed: () -> Unit) {
activity?.let {
val view = layoutInflater.inflate(R.layout.quest_maxspeed_no_sign_no_slow_zone_confirmation, null, false)
val input = view.findViewById<EditText>(R.id.maxSpeedInput)
input.setText("××")
input.inputType = EditorInfo.TYPE_NULL
AlertDialog.Builder(it)
.setTitle(R.string.quest_maxspeed_answer_noSign_confirmation_title)
.setView(view)
.setPositiveButton(R.string.quest_maxspeed_answer_noSign_confirmation_positive) { _, _ -> onConfirmed() }
.setNegativeButton(R.string.quest_generic_confirmation_no, null)
.show()
}
}
private fun determineImplicitMaxspeedType() {
val highwayTag = osmElement!!.tags["highway"]!!
if (ROADS_WITH_DEFINITE_SPEED_LIMIT.contains(highwayTag)) {
applyNoSignAnswer(highwayTag)
} else {
if (countryInfo.countryCode == "GB") {
determineLit(
onYes = { applyNoSignAnswer("nsl_restricted") },
onNo = {
askIsDualCarriageway(
onYes = { applyNoSignAnswer("nsl_dual") },
onNo = { applyNoSignAnswer("nsl_single") })
}
)
} else {
askUrbanOrRural(
onUrban = { applyNoSignAnswer("urban") },
onRural = { applyNoSignAnswer("rural") })
}
}
}
private fun askUrbanOrRural(onUrban: () -> Unit, onRural: () -> Unit) {
activity?.let {
AlertDialog.Builder(it)
.setTitle(R.string.quest_maxspeed_answer_noSign_info_urbanOrRural)
.setMessage(R.string.quest_maxspeed_answer_noSign_urbanOrRural_description)
.setPositiveButton(R.string.quest_maxspeed_answer_noSign_urbanOk) { _, _ -> onUrban() }
.setNegativeButton(R.string.quest_maxspeed_answer_noSign_ruralOk) { _, _ -> onRural() }
.show()
}
}
private fun determineLit(onYes: () -> Unit, onNo: () -> Unit) {
val lit = osmElement!!.tags["lit"]
when (lit) {
"yes" -> onYes()
"no" -> onNo()
else -> askLit(onYes, onNo)
}
}
private fun askLit(onYes: () -> Unit, onNo: () -> Unit) {
activity?.let {
AlertDialog.Builder(it)
.setMessage(R.string.quest_way_lit_road_title)
.setPositiveButton(R.string.quest_generic_hasFeature_yes) { _, _ -> onYes() }
.setNegativeButton(R.string.quest_generic_hasFeature_no) { _, _ -> onNo() }
.show()
}
}
private fun askIsDualCarriageway(onYes: () -> Unit, onNo: () -> Unit) {
activity?.let {
AlertDialog.Builder(it)
.setMessage(R.string.quest_maxspeed_answer_noSign_singleOrDualCarriageway_description)
.setPositiveButton(R.string.quest_generic_hasFeature_yes) { _, _ -> onYes() }
.setNegativeButton(R.string.quest_generic_hasFeature_no) { _, _ -> onNo() }
.show()
}
}
private fun applyNoSignAnswer(roadType: String) {
applyAnswer(ImplicitMaxSpeed(countryInfo.countryCode, roadType))
}
companion object {
private val POSSIBLY_SLOWZONE_ROADS = listOf("residential", "unclassified", "tertiary" /*#1133*/)
private val MAYBE_LIVING_STREET = listOf("residential", "unclassified")
private val ROADS_WITH_DEFINITE_SPEED_LIMIT = listOf("trunk", "motorway", "living_street")
private var LAST_INPUT_SLOW_ZONE: Int? = null
}
}
private enum class SpeedType {
SIGN, ZONE, LIVING_STREET, ADVISORY, NO_SIGN
}
| gpl-3.0 | 93c5164ac04e9d3c6e95ab8b38c7834f | 39.885017 | 121 | 0.621612 | 4.383265 | false | false | false | false |
HabitRPG/habitica-android | Habitica/src/main/java/com/habitrpg/android/habitica/ui/views/CurrencyView.kt | 1 | 6286 | package com.habitrpg.android.habitica.ui.views
import android.animation.ValueAnimator
import android.content.Context
import android.graphics.Bitmap
import android.graphics.drawable.BitmapDrawable
import android.util.AttributeSet
import android.util.TypedValue
import android.view.Gravity
import android.view.View
import android.view.ViewGroup
import androidx.core.animation.doOnEnd
import androidx.core.animation.doOnStart
import androidx.core.content.ContextCompat
import androidx.core.view.updateLayoutParams
import com.habitrpg.common.habitica.R
import com.habitrpg.common.habitica.extensions.isUsingNightModeResources
import com.habitrpg.common.habitica.helpers.NumberAbbreviator
class CurrencyView : androidx.appcompat.widget.AppCompatTextView {
var hideWhenEmpty: Boolean = false
var lightBackground: Boolean = false
set(value) {
field = value
configureCurrency()
}
var currency: String? = null
set(currency) {
field = currency
setCurrencyContentDescriptionFromCurrency(currency)
configureCurrency()
updateVisibility()
}
private var currencyContentDescription: String? = null
constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) {
val attributes = context.theme?.obtainStyledAttributes(
attrs,
R.styleable.CurrencyView,
0, 0
)
val fallBackLight = !context.isUsingNightModeResources()
lightBackground = try {
attributes?.getBoolean(R.styleable.CurrencyView_hasLightBackground, fallBackLight) ?: fallBackLight
} catch (_: ArrayIndexOutOfBoundsException) {
!context.isUsingNightModeResources()
}
currency = attributes?.getString(R.styleable.CurrencyView_currency)
visibility = GONE
setSingleLine()
}
constructor(context: Context, currency: String, lightbackground: Boolean) : super(context) {
this.lightBackground = lightbackground
this.currency = currency
setCurrencyContentDescriptionFromCurrency(currency)
visibility = GONE
setSingleLine()
}
private fun setCurrencyContentDescriptionFromCurrency(currency: String?) {
when (currency) {
"gold" -> this.currencyContentDescription = context.getString(R.string.gold_plural)
"gems" -> this.currencyContentDescription = context.getString(R.string.gems)
"hourglasses" -> this.currencyContentDescription = context.getString(R.string.mystic_hourglasses)
else -> this.currencyContentDescription = ""
}
}
private fun configureCurrency() {
if ("gold" == currency) {
icon = HabiticaIconsHelper.imageOfGold()
if (lightBackground) {
setTextColor(ContextCompat.getColor(context, R.color.yellow_1))
} else {
setTextColor(ContextCompat.getColor(context, R.color.yellow_100))
}
} else if ("gems" == currency) {
icon = HabiticaIconsHelper.imageOfGem()
if (lightBackground) {
setTextColor(ContextCompat.getColor(context, R.color.green_10))
} else {
setTextColor(ContextCompat.getColor(context, R.color.green_50))
}
} else if ("hourglasses" == currency) {
icon = HabiticaIconsHelper.imageOfHourglass()
if (lightBackground) {
setTextColor(ContextCompat.getColor(context, R.color.brand_300))
} else {
setTextColor(ContextCompat.getColor(context, R.color.brand_500))
}
}
hideWhenEmpty = "hourglasses" == currency
}
private var drawable: BitmapDrawable? = null
var icon: Bitmap? = null
set(value) {
field = value
if (value != null) {
drawable = BitmapDrawable(resources, value)
this.setCompoundDrawablesWithIntrinsicBounds(
drawable,
null, null, null
)
val padding = TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_DIP,
6f, context.resources.displayMetrics
).toInt()
compoundDrawablePadding = padding
this.gravity = Gravity.CENTER_VERTICAL
}
}
var minForAbbrevation = 0
var decimals = 2
var animationDuration = 500L
var animationDelay = 0L
private fun update(value: Double) {
text = NumberAbbreviator.abbreviate(context, value, decimals, minForAbbrevation = minForAbbrevation)
}
private fun endUpdate() {
contentDescription = "$text $currencyContentDescription"
updateVisibility()
updateLayoutParams {
width = ViewGroup.LayoutParams.WRAP_CONTENT
}
}
var value = 0.0
set(value) {
if (text.isEmpty() || animationDuration == 0L) {
update(value)
endUpdate()
} else {
val animator = ValueAnimator.ofFloat(field.toFloat(), value.toFloat())
animator.duration = animationDuration
animator.startDelay = animationDelay
animator.doOnStart {
layoutParams.width = width
}
animator.addUpdateListener {
update((it.animatedValue as Float).toDouble())
}
animator.doOnEnd {
endUpdate()
}
animator.start()
}
field = value
}
var isLocked = false
set(value) {
field = value
if (isLocked) {
this.setTextColor(ContextCompat.getColor(context, R.color.text_quad))
drawable?.alpha = 127
} else {
drawable?.alpha = 255
}
this.setCompoundDrawablesWithIntrinsicBounds(drawable, null, null, null)
}
private fun updateVisibility() {
visibility = if (hideWhenEmpty) {
if ("0" == text) View.GONE else View.VISIBLE
} else {
View.VISIBLE
}
}
}
| gpl-3.0 | 12d881546cf817a2a30d4993c81614f3 | 34.92 | 111 | 0.603404 | 5.264657 | false | false | false | false |
rhdunn/xquery-intellij-plugin | src/lang-xslt/main/uk/co/reecedunn/intellij/plugin/xslt/optree/DefaultFunctionXPathNamespace.kt | 1 | 1982 | /*
* Copyright (C) 2017-2021 Reece H. Dunn
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package uk.co.reecedunn.intellij.plugin.xslt.optree
import com.intellij.psi.PsiElement
import uk.co.reecedunn.intellij.plugin.xdm.module.path.XdmModuleType
import uk.co.reecedunn.intellij.plugin.xdm.types.XdmNode
import uk.co.reecedunn.intellij.plugin.xdm.types.XdmUriContext
import uk.co.reecedunn.intellij.plugin.xdm.types.XsAnyUriValue
import uk.co.reecedunn.intellij.plugin.xdm.types.XsNCNameValue
import uk.co.reecedunn.intellij.plugin.xdm.types.impl.psi.XsAnyUri
import uk.co.reecedunn.intellij.plugin.xpm.optree.namespace.XdmNamespaceType
import uk.co.reecedunn.intellij.plugin.xpm.optree.namespace.XpmNamespaceDeclaration
internal object DefaultFunctionXPathNamespace : XpmNamespaceDeclaration {
private const val FN_NAMESPACE_URI = "http://www.w3.org/2005/xpath-functions"
override val namespacePrefix: XsNCNameValue? = null
override val namespaceUri: XsAnyUriValue =
XsAnyUri(FN_NAMESPACE_URI, XdmUriContext.Namespace, XdmModuleType.MODULE, null as PsiElement?)
override val parentNode: XdmNode? = null
@Suppress("Reformat") // Kotlin formatter bug: https://youtrack.jetbrains.com/issue/KT-22518
override fun accepts(namespaceType: XdmNamespaceType): Boolean {
return (
namespaceType === XdmNamespaceType.DefaultFunctionDecl ||
namespaceType === XdmNamespaceType.DefaultFunctionRef
)
}
}
| apache-2.0 | ff35a8515f61df26c621aa99883700da | 43.044444 | 102 | 0.769425 | 4.044898 | false | false | false | false |
StepicOrg/stepic-android | app/src/main/java/org/stepik/android/view/step/ui/fragment/StepFragment.kt | 1 | 20836 | package org.stepik.android.view.step.ui.fragment
import android.os.Bundle
import android.text.method.LinkMovementMethod
import android.text.style.ClickableSpan
import android.view.Menu
import android.view.MenuInflater
import android.view.MenuItem
import android.view.View
import android.view.ViewGroup
import android.widget.LinearLayout
import androidx.appcompat.widget.LinearLayoutCompat
import androidx.core.text.buildSpannedString
import androidx.core.text.inSpans
import androidx.core.view.isGone
import androidx.core.view.isVisible
import androidx.core.view.updateLayoutParams
import androidx.fragment.app.DialogFragment
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.lifecycle.ViewModelProvider
import com.google.android.material.snackbar.Snackbar
import com.google.firebase.remoteconfig.FirebaseRemoteConfig
import kotlinx.android.synthetic.main.fragment_step.*
import kotlinx.android.synthetic.main.view_step_disabled.view.*
import kotlinx.android.synthetic.main.view_step_quiz_error.*
import org.stepic.droid.R
import org.stepic.droid.analytic.AmplitudeAnalytic
import org.stepic.droid.analytic.Analytic
import org.stepic.droid.base.App
import org.stepic.droid.configuration.EndpointResolver
import org.stepic.droid.core.ScreenManager
import org.stepic.droid.persistence.model.StepPersistentWrapper
import org.stepic.droid.ui.dialogs.LoadingProgressDialogFragment
import org.stepic.droid.ui.dialogs.StepShareDialogFragment
import org.stepic.droid.util.ProgressHelper
import org.stepic.droid.util.StringUtil
import org.stepic.droid.util.commitNow
import org.stepic.droid.util.copyTextToClipboard
import org.stepik.android.domain.course.analytic.CourseViewSource
import org.stepik.android.domain.lesson.model.LessonData
import org.stepik.android.domain.review_instruction.model.ReviewInstructionData
import org.stepik.android.domain.step.analytic.reportStepEvent
import org.stepik.android.domain.step.model.StepNavigationDirection
import org.stepik.android.model.Step
import org.stepik.android.presentation.step.StepPresenter
import org.stepik.android.presentation.step.StepView
import org.stepik.android.view.course.routing.CourseScreenTab
import org.stepik.android.view.course_complete.ui.dialog.CourseCompleteBottomSheetDialogFragment
import org.stepik.android.view.in_app_web_view.ui.dialog.InAppWebViewDialogFragment
import org.stepik.android.view.injection.step.StepComponent
import org.stepik.android.view.lesson.ui.dialog.LessonDemoCompleteBottomSheetDialogFragment
import org.stepik.android.view.lesson.ui.dialog.SectionUnavailableDialogFragment
import org.stepik.android.view.lesson.ui.interfaces.Moveable
import org.stepik.android.view.lesson.ui.interfaces.Playable
import org.stepik.android.view.lesson.ui.mapper.LessonTitleMapper
import org.stepik.android.view.step.model.StepNavigationAction
import org.stepik.android.view.step.ui.delegate.StepDiscussionsDelegate
import org.stepik.android.view.step.ui.delegate.StepNavigationDelegate
import org.stepik.android.view.step.ui.delegate.StepSolutionStatsDelegate
import org.stepik.android.view.step.ui.interfaces.StepMenuNavigator
import org.stepik.android.view.step_content.ui.factory.StepContentFragmentFactory
import org.stepik.android.view.step_quiz.ui.factory.StepQuizFragmentFactory
import org.stepik.android.view.submission.ui.dialog.SubmissionsDialogFragment
import ru.nobird.android.view.base.ui.extension.argument
import ru.nobird.android.view.base.ui.extension.showIfNotExists
import ru.nobird.android.view.base.ui.extension.snackbar
import javax.inject.Inject
class StepFragment : Fragment(R.layout.fragment_step), StepView,
Moveable,
Playable,
StepMenuNavigator,
SectionUnavailableDialogFragment.Callback,
CourseCompleteBottomSheetDialogFragment.Callback {
companion object {
private const val STEP_CONTENT_FRAGMENT_TAG = "step_content"
private const val STEP_QUIZ_FRAGMENT_TAG = "step_quiz"
fun newInstance(stepWrapper: StepPersistentWrapper, lessonData: LessonData): Fragment =
StepFragment()
.apply {
this.stepWrapper = stepWrapper
this.lessonData = lessonData
}
}
@Inject
internal lateinit var analytic: Analytic
@Inject
internal lateinit var screenManager: ScreenManager
@Inject
internal lateinit var stepContentFragmentFactory: StepContentFragmentFactory
@Inject
internal lateinit var stepQuizFragmentFactory: StepQuizFragmentFactory
@Inject
internal lateinit var viewModelFactory: ViewModelProvider.Factory
@Inject
internal lateinit var remoteConfig: FirebaseRemoteConfig
@Inject
internal lateinit var lessonTitleMapper: LessonTitleMapper
@Inject
internal lateinit var endpointResolver: EndpointResolver
private var stepWrapper: StepPersistentWrapper by argument()
private var lessonData: LessonData by argument()
private lateinit var stepComponent: StepComponent
private val stepPresenter: StepPresenter by viewModels { viewModelFactory }
private lateinit var stepSolutionStatsDelegate: StepSolutionStatsDelegate
private lateinit var stepNavigationDelegate: StepNavigationDelegate
private lateinit var stepDiscussionsDelegate: StepDiscussionsDelegate
private val progressDialogFragment: DialogFragment =
LoadingProgressDialogFragment.newInstance()
override fun onCreate(savedInstanceState: Bundle?) {
injectComponent()
super.onCreate(savedInstanceState)
setHasOptionsMenu(true)
stepPresenter.onLessonData(stepWrapper, lessonData)
}
private fun injectComponent() {
stepComponent = App
.componentManager()
.stepParentComponent(stepWrapper, lessonData)
stepComponent.inject(this)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
stepSolutionStatsDelegate = StepSolutionStatsDelegate(
stepSolutionStats,
stepWrapper.step,
stepWrapper.isStepCanHaveQuiz
)
stepNavigationDelegate = StepNavigationDelegate(stepNavigation) { stepPresenter.onStepDirectionClicked(it) }
stepDiscussionsDelegate = StepDiscussionsDelegate(view) { discussionThread ->
analytic.reportAmplitudeEvent(
AmplitudeAnalytic.Discussions.SCREEN_OPENED,
mapOf(AmplitudeAnalytic.Discussions.Params.SOURCE to AmplitudeAnalytic.Discussions.Values.DEFAULT)
)
screenManager
.openComments(
activity,
discussionThread,
stepWrapper.step,
null,
discussionThread.discussionsCount == 0,
lessonData.lesson.isTeacher
)
}
stepContentNext.isVisible = isStepContentNextVisible(stepWrapper, lessonData)
stepContentNext.setOnClickListener { move() }
stepStatusTryAgain.setOnClickListener { stepPresenter.fetchStepUpdate(stepWrapper.step.id) }
initDisabledStep()
initDisabledStepTeacher()
initStepContentFragment()
}
private fun initDisabledStep() {
val lessonTitle =
lessonTitleMapper.mapToLessonTitle(requireContext(), lessonData)
val stepTitle =
getString(R.string.step_disabled_student_pattern, lessonTitle, stepWrapper.step.position)
val stepLinkSpan = object : ClickableSpan() {
override fun onClick(widget: View) {
val stepUri = StringUtil
.getUriForStep(endpointResolver.getBaseUrl(), lessonData.lesson, lessonData.unit, stepWrapper.step)
requireContext()
.copyTextToClipboard(textToCopy = stepUri, toastMessage = getString(R.string.link_copied_title))
}
}
val placeholderMessage = stepDisabled.placeholderMessage
placeholderMessage.text =
buildSpannedString {
append(getString(R.string.step_disabled_student_description_part_1))
inSpans(stepLinkSpan) {
append(stepTitle)
}
append(getString(R.string.step_disabled_student_description_part_2))
}
placeholderMessage.movementMethod = LinkMovementMethod.getInstance()
}
private fun initDisabledStepTeacher() {
val tariffTitle = getString(R.string.step_disabled_teacher_tariff_title)
val tariffLinkSpan = object : ClickableSpan() {
override fun onClick(widget: View) {
val tariffInfoUrl = getString(R.string.step_disabled_teacher_tariff_url)
InAppWebViewDialogFragment
.newInstance(tariffTitle, tariffInfoUrl, isProvideAuth = false)
.showIfNotExists(childFragmentManager, InAppWebViewDialogFragment.TAG)
}
}
val isInCourse = lessonData.section != null && lessonData.unit != null
val planDescription1 = if (stepWrapper.step.needsPlan != null) {
if (isInCourse) {
getString(R.string.step_disabled_teacher_plan_description_with_course)
} else {
getString(R.string.step_disabled_teacher_plan_description_without_course)
}
} else {
if (isInCourse) {
getString(R.string.step_disabled_teacher_plan_none_description_with_course)
} else {
getString(R.string.step_disabled_teacher_plan_none_description_without_course)
}
}
val planDescription2 = when (stepWrapper.step.needsPlan) {
Step.PLAN_PRO -> {
if (isInCourse) {
getText(R.string.step_disabled_teacher_plan_pro_with_course)
} else {
getText(R.string.step_disabled_teacher_plan_pro_without_course)
}
}
Step.PLAN_ENTERPRISE -> {
if (isInCourse) {
getText(R.string.step_disabled_teacher_enterprise_with_course)
} else {
getText(R.string.step_disabled_teacher_plan_enterprise_without_course)
}
}
else ->
""
}
val placeholderMessage = stepDisabledTeacher.placeholderMessage
placeholderMessage.text =
buildSpannedString {
append(planDescription1)
append(planDescription2)
append(getString(R.string.step_disabled_teacher_tariff_description))
inSpans(tariffLinkSpan) {
append(tariffTitle)
}
append(getString(R.string.full_stop))
}
placeholderMessage.movementMethod = LinkMovementMethod.getInstance()
}
private fun initStepContentFragment() {
stepContentContainer.layoutParams = (stepContentContainer.layoutParams as LinearLayoutCompat.LayoutParams)
.apply {
if (stepWrapper.isStepCanHaveQuiz) {
height = LinearLayout.LayoutParams.WRAP_CONTENT
weight = 0f
} else {
height = 0
weight = 1f
}
}
if (childFragmentManager.findFragmentByTag(STEP_CONTENT_FRAGMENT_TAG) == null) {
val stepContentFragment =
stepContentFragmentFactory.createStepContentFragment(stepWrapper)
childFragmentManager
.beginTransaction()
.add(R.id.stepContentContainer, stepContentFragment, STEP_CONTENT_FRAGMENT_TAG)
.commitNow()
}
}
private fun setStepQuizFragment(isNeedReload: Boolean) {
val isStepHasQuiz = stepWrapper.isStepCanHaveQuiz
stepContentSeparator.isVisible = isStepHasQuiz
stepQuizContainer.isVisible = isStepHasQuiz
stepQuizError.isVisible = false
if (isStepHasQuiz) {
val isQuizFragmentEmpty = childFragmentManager.findFragmentByTag(STEP_QUIZ_FRAGMENT_TAG) == null
if (isQuizFragmentEmpty || isNeedReload) {
val quizFragment = stepQuizFragmentFactory.createStepQuizFragment(stepWrapper, lessonData)
childFragmentManager.commitNow {
if (isQuizFragmentEmpty) {
add(R.id.stepQuizContainer, quizFragment, STEP_QUIZ_FRAGMENT_TAG)
} else {
replace(R.id.stepQuizContainer, quizFragment, STEP_QUIZ_FRAGMENT_TAG)
}
}
}
}
}
override fun onStart() {
super.onStart()
stepPresenter.attachView(this)
}
override fun onStop() {
stepPresenter.detachView(this)
super.onStop()
}
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
inflater.inflate(R.menu.step_menu, menu)
menu.findItem(R.id.menu_item_submissions)
?.isVisible = stepWrapper.isStepCanHaveQuiz
super.onCreateOptionsMenu(menu, inflater)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean =
when (item.itemId) {
R.id.menu_item_share -> {
showShareDialog()
true
}
R.id.menu_item_submissions -> {
showSubmissions()
true
}
else ->
super.onOptionsItemSelected(item)
}
override fun showSubmissions() {
val instructionId = stepWrapper.step.instruction
if (instructionId != null) {
stepPresenter.onFetchReviewInstruction(instructionId)
} else {
showSubmissionsDialog(reviewInstructionData = null)
}
}
override fun showShareDialog() {
val supportFragmentManager = activity
?.supportFragmentManager
?: return
StepShareDialogFragment
.newInstance(stepWrapper.step, lessonData.lesson, lessonData.unit)
.showIfNotExists(supportFragmentManager, StepShareDialogFragment.TAG)
}
private fun showSubmissionsDialog(reviewInstructionData: ReviewInstructionData?) {
val supportFragmentManager = activity
?.supportFragmentManager
?: return
SubmissionsDialogFragment
.newInstance(stepWrapper.step, isTeacher = lessonData.lesson.isTeacher, reviewInstructionData = reviewInstructionData)
.showIfNotExists(supportFragmentManager, SubmissionsDialogFragment.TAG)
analytic
.reportStepEvent(AmplitudeAnalytic.Steps.STEP_SOLUTIONS_OPENED, stepWrapper.step)
}
override fun setState(state: StepView.State) {
if (state is StepView.State.Loaded) {
val isNeedReloadQuiz = stepWrapper.step.block != state.stepWrapper.step.block ||
stepWrapper.step.isEnabled != state.stepWrapper.step.isEnabled
val isStepDisabled = state.stepWrapper.step.isEnabled == false
val isStepUnavailable = isStepDisabled && !lessonData.lesson.isTeacher
stepContentContainer.isGone = isStepUnavailable
stepContentSeparator.isGone = isStepUnavailable
stepQuizError.isGone = isStepUnavailable
stepQuizContainer.isGone = isStepUnavailable
stepFooter.isGone = isStepUnavailable
stepDisabled.isVisible = isStepUnavailable
stepDisabledTeacher.isVisible = isStepDisabled && lessonData.lesson.isTeacher
stepContentNext.isVisible = isStepContentNextVisible(state.stepWrapper, lessonData)
stepWrapper = state.stepWrapper
if (!isStepDisabled || lessonData.lesson.isTeacher) {
stepDiscussionsDelegate.setDiscussionThreads(state.discussionThreads)
when (stepWrapper.step.status) {
Step.Status.READY ->
setStepQuizFragment(isNeedReloadQuiz)
Step.Status.PREPARING,
Step.Status.ERROR -> {
stepContentSeparator.isVisible = true
stepQuizContainer.isVisible = false
stepQuizError.isVisible = true
}
}
}
}
}
private fun isStepContentNextVisible(stepWrapper: StepPersistentWrapper, lessonData: LessonData): Boolean {
val isStepDisabled = stepWrapper.step.isEnabled == false
val isStepNotLast = stepWrapper.step.position < lessonData.lesson.steps.size
return ((isStepDisabled && !lessonData.lesson.isTeacher) || !stepWrapper.isStepCanHaveQuiz) && isStepNotLast
}
override fun setBlockingLoading(isLoading: Boolean) {
if (isLoading) {
ProgressHelper.activate(progressDialogFragment, activity?.supportFragmentManager, LoadingProgressDialogFragment.TAG)
} else {
ProgressHelper.dismiss(activity?.supportFragmentManager, LoadingProgressDialogFragment.TAG)
}
}
override fun setNavigation(directions: Set<StepNavigationDirection>) {
stepNavigationDelegate.setState(directions)
val actionBottomMargin = if (stepNavigation.visibility == View.VISIBLE) {
0
} else {
resources.getDimensionPixelSize(R.dimen.step_quiz_container_bottom_margin)
}
stepQuizContainer.updateLayoutParams<ViewGroup.MarginLayoutParams> {
bottomMargin = actionBottomMargin
}
stepContentNext.updateLayoutParams<ViewGroup.MarginLayoutParams> {
bottomMargin = actionBottomMargin
}
}
override fun handleNavigationAction(stepNavigationAction: StepNavigationAction) {
when (stepNavigationAction) {
is StepNavigationAction.ShowLesson -> {
val unit = stepNavigationAction.lessonData.unit ?: return
val section = stepNavigationAction.lessonData.section ?: return
activity?.finish()
screenManager.showSteps(
activity,
unit,
stepNavigationAction.lessonData.lesson,
section,
stepNavigationAction.direction == StepNavigationDirection.PREV,
stepNavigationAction.isAutoplayEnabled
)
}
is StepNavigationAction.ShowLessonDemoComplete ->
LessonDemoCompleteBottomSheetDialogFragment
.newInstance(stepNavigationAction.course)
.showIfNotExists(childFragmentManager, LessonDemoCompleteBottomSheetDialogFragment.TAG)
is StepNavigationAction.ShowSectionUnavailable ->
SectionUnavailableDialogFragment
.newInstance(stepNavigationAction.sectionUnavailableAction)
.showIfNotExists(childFragmentManager, SectionUnavailableDialogFragment.TAG)
is StepNavigationAction.ShowCourseComplete ->
CourseCompleteBottomSheetDialogFragment
.newInstance(stepNavigationAction.course)
.showIfNotExists(childFragmentManager, CourseCompleteBottomSheetDialogFragment.TAG)
is StepNavigationAction.Unknown ->
view?.snackbar(messageRes = R.string.step_navigation_action_unknown, length = Snackbar.LENGTH_LONG)
}
}
override fun showQuizReloadMessage() {
view?.snackbar(messageRes = R.string.step_quiz_reload_message, length = Snackbar.LENGTH_LONG)
}
override fun openShowSubmissionsWithReview(reviewInstructionData: ReviewInstructionData) {
showSubmissionsDialog(reviewInstructionData = reviewInstructionData)
}
override fun move(isAutoplayEnabled: Boolean, stepNavigationDirection: StepNavigationDirection): Boolean {
if ((activity as? Moveable)?.move(isAutoplayEnabled, stepNavigationDirection) != true) {
stepPresenter.onStepDirectionClicked(stepNavigationDirection, isAutoplayEnabled)
}
return true
}
override fun play(): Boolean =
(childFragmentManager.findFragmentByTag(STEP_CONTENT_FRAGMENT_TAG) as? Playable)
?.play()
?: false
override fun onSyllabusAction(courseViewSource: CourseViewSource) {
val course = lessonData.course ?: return
screenManager.showCourseFromNavigationDialog(requireContext(), course.id, courseViewSource, CourseScreenTab.SYLLABUS, false)
}
override fun showErrorMessage() {
view?.snackbar(messageRes = R.string.step_navigation_action_unknown, length = Snackbar.LENGTH_LONG)
}
} | apache-2.0 | 7b41a8007212e0d57e780e90113b49ec | 40.179842 | 132 | 0.677913 | 5.197306 | false | false | false | false |
jiaminglu/kotlin-native | Interop/Runtime/src/native/kotlin/kotlinx/cinterop/NativeMem.kt | 1 | 3449 | package kotlinx.cinterop
import konan.internal.Intrinsic
inline val pointerSize: Int
get() = getPointerSize()
@Intrinsic external fun getPointerSize(): Int
// TODO: do not use singleton because it leads to init-check on any access.
object nativeMemUtils {
@Intrinsic external fun getByte(mem: NativePointed): Byte
@Intrinsic external fun putByte(mem: NativePointed, value: Byte)
@Intrinsic external fun getShort(mem: NativePointed): Short
@Intrinsic external fun putShort(mem: NativePointed, value: Short)
@Intrinsic external fun getInt(mem: NativePointed): Int
@Intrinsic external fun putInt(mem: NativePointed, value: Int)
@Intrinsic external fun getLong(mem: NativePointed): Long
@Intrinsic external fun putLong(mem: NativePointed, value: Long)
@Intrinsic external fun getFloat(mem: NativePointed): Float
@Intrinsic external fun putFloat(mem: NativePointed, value: Float)
@Intrinsic external fun getDouble(mem: NativePointed): Double
@Intrinsic external fun putDouble(mem: NativePointed, value: Double)
@Intrinsic external fun getNativePtr(mem: NativePointed): NativePtr
@Intrinsic external fun putNativePtr(mem: NativePointed, value: NativePtr)
// TODO: optimize
fun getByteArray(source: NativePointed, dest: ByteArray, length: Int) {
val sourceArray = source.reinterpret<ByteVar>().ptr
var index = 0
while (index < length) {
dest[index] = sourceArray[index]
++index
}
}
// TODO: optimize
fun putByteArray(source: ByteArray, dest: NativePointed, length: Int) {
val destArray = dest.reinterpret<ByteVar>().ptr
var index = 0
while (index < length) {
destArray[index] = source[index]
++index
}
}
// TODO: optimize
fun getCharArray(source: NativePointed, dest: CharArray, length: Int) {
val sourceArray = source.reinterpret<ShortVar>().ptr
var index = 0
while (index < length) {
dest[index] = sourceArray[index].toChar()
++index
}
}
// TODO: optimize
fun putCharArray(source: CharArray, dest: NativePointed, length: Int) {
val destArray = dest.reinterpret<ShortVar>().ptr
var index = 0
while (index < length) {
destArray[index] = source[index].toShort()
++index
}
}
// TODO: optimize
fun zeroMemory(dest: NativePointed, length: Int): Unit {
val destArray = dest.reinterpret<ByteVar>().ptr
var index = 0
while (index < length) {
destArray[index] = 0
++index
}
}
private class NativeAllocated(rawPtr: NativePtr) : NativePointed(rawPtr)
fun alloc(size: Long, align: Int): NativePointed {
val ptr = malloc(size, align)
if (ptr == nativeNullPtr) {
throw OutOfMemoryError("unable to allocate native memory")
}
return interpretPointed<NativeAllocated>(ptr)
}
fun free(mem: NativePtr) {
cfree(mem)
}
}
@SymbolName("Kotlin_interop_malloc")
private external fun malloc(size: Long, align: Int): NativePtr
@SymbolName("Kotlin_interop_free")
private external fun cfree(ptr: NativePtr)
@Intrinsic external fun readBits(ptr: NativePtr, offset: Long, size: Int, signed: Boolean): Long
@Intrinsic external fun writeBits(ptr: NativePtr, offset: Long, size: Int, value: Long) | apache-2.0 | 4ad13c0e53582053ac1e05014cbd9c68 | 31.857143 | 96 | 0.656132 | 4.479221 | false | false | false | false |
StepicOrg/stepic-android | app/src/main/java/org/stepic/droid/features/stories/ui/delegate/StoriesActivityDelegate.kt | 1 | 3163 | package org.stepic.droid.features.stories.ui.delegate
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.children
import androidx.viewpager.widget.ViewPager
import kotlinx.android.synthetic.main.activity_stories.*
import org.stepic.droid.R
import org.stepic.droid.analytic.AmplitudeAnalytic
import org.stepic.droid.analytic.Analytic
import org.stepik.android.domain.story.model.StoryReaction
import ru.nobird.android.core.model.safeCast
import ru.nobird.android.stories.model.Story
import ru.nobird.android.stories.ui.adapter.StoriesPagerAdapter
import ru.nobird.android.stories.ui.custom.DismissableLayout
import ru.nobird.android.stories.ui.custom.StoryView
import ru.nobird.android.stories.ui.delegate.StoriesActivityDelegateBase
import ru.nobird.android.stories.ui.delegate.StoryPartViewDelegate
class StoriesActivityDelegate(
activity: AppCompatActivity,
private val analytic: Analytic,
storyReactionListener: (storyId: Long, storyPosition: Int, storyReaction: StoryReaction) -> Unit
) : StoriesActivityDelegateBase(activity) {
private val storyReactions = mutableMapOf<Long, StoryReaction>()
private val storyPartDelegate =
PlainTextWithButtonStoryPartDelegate(analytic, activity, storyReactions, storyReactionListener)
public override val dismissableLayout: DismissableLayout =
activity.content
public override val storiesViewPager: ViewPager =
activity.storiesPager
override val arguments: Bundle =
activity.intent.extras ?: Bundle.EMPTY
override val storyPartDelegates: List<StoryPartViewDelegate> =
listOf(storyPartDelegate, FeedbackStoryPartDelegate(analytic, activity, dismissableLayout))
override fun onComplete() {
super.onComplete()
val story = getCurrentStory() ?: return
analytic.reportAmplitudeEvent(AmplitudeAnalytic.Stories.STORY_CLOSED, mapOf(
AmplitudeAnalytic.Stories.Values.STORY_ID to story.id,
AmplitudeAnalytic.Stories.Values.CLOSE_TYPE to AmplitudeAnalytic.Stories.Values.CloseTypes.AUTO
))
}
fun getCurrentStory(): Story? =
storiesViewPager.adapter
.safeCast<StoriesPagerAdapter>()
?.stories
?.getOrNull(storiesViewPager.currentItem)
fun setStoryVotes(votes: Map<Long, StoryReaction>) {
val diff = votes - storyReactions // only this way as reactions can't be removed
storyReactions.clear()
storyReactions += votes
val adapter = storiesViewPager.adapter
.safeCast<StoriesPagerAdapter>() ?: return
diff.forEach { (storyId, _) ->
val position = adapter.stories
.indexOfFirst { it.id == storyId }
val story = adapter.stories
.getOrNull(position)
val storyPartPager = storiesViewPager
.findViewWithTag<StoryView>(position)
?.findViewById<ViewPager>(R.id.storyViewPager)
storyPartPager?.children?.forEach { view ->
storyPartDelegate.setUpReactions(story, view, position)
}
}
}
} | apache-2.0 | 3e274c358fad67a848d39db563dc5c80 | 37.120482 | 107 | 0.723048 | 4.785174 | false | false | false | false |
savvasdalkitsis/gameframe | workspace/src/main/java/com/savvasdalkitsis/gameframe/feature/workspace/element/palette/view/PaletteView.kt | 1 | 3373 | /**
* Copyright 2017 Savvas Dalkitsis
* 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.
*
* 'Game Frame' is a registered trademark of LEDSEQ
*/
package com.savvasdalkitsis.gameframe.feature.workspace.element.palette.view
import android.content.Context
import android.support.v7.widget.GridLayout
import android.util.AttributeSet
import com.savvasdalkitsis.gameframe.feature.workspace.element.palette.model.Palette
import com.savvasdalkitsis.gameframe.feature.workspace.element.swatch.view.SwatchSelectedListener
import com.savvasdalkitsis.gameframe.feature.workspace.element.swatch.view.SwatchView
class PaletteView : GridLayout {
private lateinit var swatches: Array<SwatchView?>
private var swatchSelectedListener: SwatchSelectedListener? = null
private var thumbnailMode: Boolean = false
constructor(context: Context) : super(context)
constructor(context: Context, attrs: AttributeSet) : super(context, attrs)
constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int) : super(context, attrs, defStyleAttr)
override fun onFinishInflate() {
super.onFinishInflate()
val childCount = childCount
if (childCount != SWATCH_COUNT) {
throw IllegalStateException("Wrong number of swatches in PaletteView. Expecting ${SWATCH_COUNT} found $childCount")
}
swatches = arrayOfNulls(SWATCH_COUNT)
for (i in 0 until SWATCH_COUNT) {
swatches[i] = getChildAt(i) as SwatchView
}
}
override fun onAttachedToWindow() {
super.onAttachedToWindow()
if (!thumbnailMode) {
post { this.selectFirstSwatch() }
}
}
fun setThumbnailMode() {
thumbnailMode = true
for (swatch in swatches) {
swatch?.let { with(it) {
setOnClickListener(null)
setOnLongClickListener(null)
isClickable = false
isLongClickable = false
} }
}
}
fun bind(palette: Palette) {
val colors = palette.colors
for (i in 0 until SWATCH_COUNT) {
swatches[i]?.bind(colors[i], i)
}
}
fun deselectAllSwatches() {
for (swatch in swatches) {
swatch?.isSelected = false
}
}
fun setOnSwatchSelectedListener(swatchSelectedListener: SwatchSelectedListener) {
this.swatchSelectedListener = swatchSelectedListener
}
fun notifyListenerOfSwatchSelected(swatchView: SwatchView) {
swatchSelectedListener?.onSwatchSelected(swatchView)
}
fun notifyListenerOfSwatchLongClicked(swatchView: SwatchView) {
swatchSelectedListener?.onSwatchLongPressed(swatchView)
}
private fun selectFirstSwatch() {
swatches[0]?.performClick()
}
companion object {
private const val SWATCH_COUNT = 16
}
}
| apache-2.0 | 2bb045465d786fa46ba85b7b61f58cc2 | 31.747573 | 127 | 0.686333 | 4.558108 | false | false | false | false |
CarlosEsco/tachiyomi | app/src/main/java/eu/kanade/tachiyomi/ui/reader/loader/RarPageLoader.kt | 1 | 2530 | package eu.kanade.tachiyomi.ui.reader.loader
import com.github.junrar.Archive
import com.github.junrar.rarfile.FileHeader
import eu.kanade.tachiyomi.source.model.Page
import eu.kanade.tachiyomi.ui.reader.model.ReaderPage
import eu.kanade.tachiyomi.util.lang.compareToCaseInsensitiveNaturalOrder
import eu.kanade.tachiyomi.util.system.ImageUtil
import rx.Observable
import java.io.File
import java.io.InputStream
import java.io.PipedInputStream
import java.io.PipedOutputStream
import java.util.concurrent.Executors
/**
* Loader used to load a chapter from a .rar or .cbr file.
*/
class RarPageLoader(file: File) : PageLoader() {
/**
* The rar archive to load pages from.
*/
private val archive = Archive(file)
/**
* Pool for copying compressed files to an input stream.
*/
private val pool = Executors.newFixedThreadPool(1)
/**
* Recycles this loader and the open archive.
*/
override fun recycle() {
super.recycle()
archive.close()
pool.shutdown()
}
/**
* Returns an observable containing the pages found on this rar archive ordered with a natural
* comparator.
*/
override fun getPages(): Observable<List<ReaderPage>> {
return archive.fileHeaders.asSequence()
.filter { !it.isDirectory && ImageUtil.isImage(it.fileName) { archive.getInputStream(it) } }
.sortedWith { f1, f2 -> f1.fileName.compareToCaseInsensitiveNaturalOrder(f2.fileName) }
.mapIndexed { i, header ->
ReaderPage(i).apply {
stream = { getStream(header) }
status = Page.READY
}
}
.let { Observable.just(it.toList()) }
}
/**
* Returns an observable that emits a ready state unless the loader was recycled.
*/
override fun getPage(page: ReaderPage): Observable<Int> {
return Observable.just(
if (isRecycled) {
Page.ERROR
} else {
Page.READY
},
)
}
/**
* Returns an input stream for the given [header].
*/
private fun getStream(header: FileHeader): InputStream {
val pipeIn = PipedInputStream()
val pipeOut = PipedOutputStream(pipeIn)
pool.execute {
try {
pipeOut.use {
archive.extractFile(header, it)
}
} catch (e: Exception) {
}
}
return pipeIn
}
}
| apache-2.0 | da0787f2094694580e4e96433d656f08 | 28.418605 | 104 | 0.604743 | 4.485816 | false | false | false | false |
santoslucas/guarda-filme-android | app/src/main/java/com/guardafilme/data/GFMoviesRepository.kt | 1 | 1368 | package com.guardafilme.data
import com.guardafilme.Utils
import com.guardafilme.model.Movie
import info.movito.themoviedbapi.TmdbApi
import info.movito.themoviedbapi.model.MovieDb
import org.jetbrains.anko.doAsync
import org.jetbrains.anko.uiThread
import javax.inject.Inject
/**
* Created by lucassantos on 20/11/17.
*/
class GFMoviesRepository @Inject constructor(): MoviesRepository {
override fun searchMovies(apiKey: String, query: String, onMoviesLoaded: (movies: List<Movie>) -> Unit) {
doAsync {
val searchResult = TmdbApi(apiKey).search.searchMovie(query, 0, "pt-BR", true, 0)
uiThread {
onMoviesLoaded(convertTmdbMoviesToInternal(searchResult.results))
}
}
}
private fun tmdbMovieToInternalMovie(tmdbMovie: MovieDb): Movie {
val movie = Movie()
movie.id = tmdbMovie.id
movie.title = tmdbMovie.title
movie.originalTitle = tmdbMovie.originalTitle
movie.year = Utils.getYearFromMovieReleaseDate(tmdbMovie.releaseDate)
movie.poster = tmdbMovie.posterPath ?: ""
movie.backdrop = tmdbMovie.backdropPath ?: ""
return movie
}
private fun convertTmdbMoviesToInternal(tmdbMoviesList: List<MovieDb>): List<Movie> {
return tmdbMoviesList.map { tmdbMovie -> tmdbMovieToInternalMovie(tmdbMovie) }
}
} | gpl-3.0 | 4393f838c69e43a97f0f791e6d225499 | 34.102564 | 109 | 0.701023 | 4.183486 | false | false | false | false |
geeteshk/Hyper | app/src/main/java/io/geeteshk/hyper/ui/adapter/IntroAdapter.kt | 1 | 1755 | /*
* Copyright 2016 Geetesh Kalakoti <[email protected]>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.geeteshk.hyper.ui.adapter
import android.content.Context
import android.os.Bundle
import androidx.fragment.app.FragmentManager
import androidx.fragment.app.FragmentStatePagerAdapter
import io.geeteshk.hyper.R
import io.geeteshk.hyper.ui.fragment.IntroFragment
class IntroAdapter(context: Context, fm: FragmentManager) : FragmentStatePagerAdapter(fm) {
private val bgColors: IntArray = context.resources.getIntArray(R.array.bg_screens)
private val images = intArrayOf(R.drawable.ic_intro_logo_n, R.drawable.ic_intro_editor, R.drawable.ic_intro_git, R.drawable.ic_intro_done)
private val titles: Array<String> = context.resources.getStringArray(R.array.slide_titles)
private val desc: Array<String> = context.resources.getStringArray(R.array.slide_desc)
override fun getItem(position: Int) = IntroFragment.newInstance(Bundle().apply {
putInt("position", position)
putInt("bg", bgColors[position])
putInt("image", images[position])
putString("title", titles[position])
putString("desc", desc[position])
})
override fun getCount(): Int = images.size
}
| apache-2.0 | 2407ee2871fe193e53d9aff8128ad138 | 40.785714 | 142 | 0.747009 | 4.006849 | false | false | false | false |
k9mail/k-9 | app/storage/src/test/java/com/fsck/k9/storage/messages/KeyValueHelpers.kt | 2 | 2103 | package com.fsck.k9.storage.messages
import android.content.ContentValues
import android.database.sqlite.SQLiteDatabase
import com.fsck.k9.helper.getLongOrNull
import com.fsck.k9.helper.getStringOrNull
import com.fsck.k9.helper.map
fun SQLiteDatabase.createExtraValue(
name: String = "irrelevant",
text: String? = null,
number: Long? = null
): Long {
val values = ContentValues().apply {
put("name", name)
put("value_text", text)
put("value_integer", number)
}
return insert("account_extra_values", null, values)
}
fun SQLiteDatabase.readExtraValues(): List<ExtraValueEntry> {
val cursor = rawQuery("SELECT * FROM account_extra_values", null)
return cursor.use {
cursor.map {
ExtraValueEntry(
name = cursor.getStringOrNull("name"),
text = cursor.getStringOrNull("value_text"),
number = cursor.getLongOrNull("value_integer")
)
}
}
}
data class ExtraValueEntry(
val name: String?,
val text: String?,
val number: Long?
)
fun SQLiteDatabase.createFolderExtraValue(
folderId: Long,
name: String = "irrelevant",
text: String? = null,
number: Long? = null
): Long {
val values = ContentValues().apply {
put("folder_id", folderId)
put("name", name)
put("value_text", text)
put("value_integer", number)
}
return insert("folder_extra_values", null, values)
}
fun SQLiteDatabase.readFolderExtraValues(): List<FolderExtraValueEntry> {
val cursor = rawQuery("SELECT * FROM folder_extra_values", null)
return cursor.use {
cursor.map {
FolderExtraValueEntry(
folderId = cursor.getLongOrNull("folder_id"),
name = cursor.getStringOrNull("name"),
text = cursor.getStringOrNull("value_text"),
number = cursor.getLongOrNull("value_integer")
)
}
}
}
data class FolderExtraValueEntry(
val folderId: Long?,
val name: String?,
val text: String?,
val number: Long?
)
| apache-2.0 | 504f12dce76e3a47c435a904a73f4815 | 26.311688 | 73 | 0.623871 | 4.131631 | false | false | false | false |
Maccimo/intellij-community | platform/workspaceModel/storage/src/com/intellij/workspaceModel/storage/impl/EntitiesBarrel.kt | 3 | 5346 | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.workspaceModel.storage.impl
import com.intellij.openapi.diagnostic.thisLogger
import com.intellij.workspaceModel.storage.*
internal open class ImmutableEntitiesBarrel internal constructor(
override val entityFamilies: List<ImmutableEntityFamily<out WorkspaceEntity>?>
) : EntitiesBarrel() {
constructor(): this(emptyList())
companion object {
val EMPTY = ImmutableEntitiesBarrel(emptyList())
}
}
internal class MutableEntitiesBarrel private constructor(
override var entityFamilies: MutableList<EntityFamily<out WorkspaceEntity>?>
) : EntitiesBarrel() {
fun remove(id: Int, clazz: Int) {
val entityFamily = getMutableEntityFamily(clazz)
entityFamily.remove(id)
}
fun getEntityDataForModification(id: EntityId): WorkspaceEntityData<*> {
return getMutableEntityFamily(id.clazz).getEntityDataForModification(id.arrayId)
}
@Suppress("UNCHECKED_CAST")
fun <T : WorkspaceEntity> add(newEntity: WorkspaceEntityData<T>, clazz: Int) {
(getMutableEntityFamily(clazz) as MutableEntityFamily<T>).add(newEntity)
}
fun book(clazz: Int): EntityId {
val arrayId = getMutableEntityFamily(clazz).book()
return createEntityId(arrayId, clazz)
}
@Suppress("UNCHECKED_CAST")
fun <T : WorkspaceEntity> cloneAndAdd(newEntity: WorkspaceEntityData<T>, clazz: Int): WorkspaceEntityData<T> {
val cloned = newEntity.clone()
(getMutableEntityFamily(clazz) as MutableEntityFamily<T>).add(cloned)
return cloned
}
@Suppress("UNCHECKED_CAST")
fun <T : WorkspaceEntity> cloneAndAddAt(newEntity: WorkspaceEntityData<T>, entityId: EntityId): WorkspaceEntityData<T> {
val cloned = newEntity.clone()
cloned.id = entityId.arrayId
(getMutableEntityFamily(entityId.clazz) as MutableEntityFamily<T>).insertAtId(cloned)
return cloned
}
@Suppress("UNCHECKED_CAST")
fun <T : WorkspaceEntity> replaceById(newEntity: WorkspaceEntityData<T>, clazz: Int) {
val family = getMutableEntityFamily(clazz) as MutableEntityFamily<T>
if (!family.exists(newEntity.id)) {
thisLogger().error("Nothing to replace. Class: $clazz, new entity: $newEntity")
return
}
family.replaceById(newEntity)
}
fun toImmutable(): ImmutableEntitiesBarrel {
val friezedEntities = entityFamilies.map { family ->
when (family) {
is MutableEntityFamily<*> -> if (!family.isEmpty()) family.toImmutable() else null
is ImmutableEntityFamily<*> -> family
else -> null
}
}
return ImmutableEntitiesBarrel(friezedEntities)
}
private fun getMutableEntityFamily(unmodifiableEntityId: Int): MutableEntityFamily<*> {
fillEmptyFamilies(unmodifiableEntityId)
val entityFamily = entityFamilies[unmodifiableEntityId] ?: run {
GeneratedCodeCompatibilityChecker.checkCode(unmodifiableEntityId.findWorkspaceEntity())
val emptyEntityFamily = MutableEntityFamily.createEmptyMutable<WorkspaceEntity>()
entityFamilies[unmodifiableEntityId] = emptyEntityFamily
emptyEntityFamily
}
return when (entityFamily) {
is MutableEntityFamily<*> -> entityFamily
is ImmutableEntityFamily<*> -> {
val newMutable = entityFamily.toMutable()
entityFamilies[unmodifiableEntityId] = newMutable
newMutable
}
}
}
internal fun fillEmptyFamilies(unmodifiableEntityId: Int) {
while (entityFamilies.size <= unmodifiableEntityId) entityFamilies.add(null)
}
companion object {
fun from(original: ImmutableEntitiesBarrel): MutableEntitiesBarrel = MutableEntitiesBarrel(ArrayList(original.entityFamilies))
fun create() = MutableEntitiesBarrel(ArrayList())
}
}
internal sealed class EntitiesBarrel {
internal abstract val entityFamilies: List<EntityFamily<out WorkspaceEntity>?>
open operator fun get(clazz: Int): EntityFamily<out WorkspaceEntity>? = entityFamilies.getOrNull(clazz)
fun size() = entityFamilies.size
fun assertConsistency(abstractEntityStorage: AbstractEntityStorage) {
val persistentIds = HashSet<PersistentEntityId<*>>()
entityFamilies.forEachIndexed { i, family ->
if (family == null) return@forEachIndexed
val clazz = i.findEntityClass<WorkspaceEntity>()
val hasPersistentId = WorkspaceEntityWithPersistentId::class.java.isAssignableFrom(clazz)
family.assertConsistency { entityData ->
// Assert correctness of the class
val immutableClass = entityData.getEntityInterface()
assert(clazz == immutableClass) {
"""EntityFamily contains entity data of wrong type:
| - EntityFamily class: $clazz
| - entityData class: $immutableClass
""".trimMargin()
}
// Assert unique of persistent id
if (hasPersistentId) {
val persistentId = entityData.persistentId()
assert(persistentId != null) { "Persistent id expected for $clazz" }
assert(persistentId !in persistentIds) { "Duplicated persistent ids: $persistentId" }
persistentIds.add(persistentId!!)
}
if (entityData is WithAssertableConsistency) {
entityData.assertConsistency(abstractEntityStorage)
}
}
}
}
}
| apache-2.0 | 9e1867c0be79d905c48af8b3133e8211 | 37.185714 | 140 | 0.720539 | 4.833635 | false | false | false | false |
Maccimo/intellij-community | platform/workspaceModel/codegen/src/com/intellij/workspaceModel/codegen/writer/imports.kt | 3 | 3869 | package com.intellij.workspaceModel.codegen.utils
import com.intellij.workspaceModel.storage.EntityStorage
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 org.jetbrains.deft.Obj
import kotlin.reflect.*
import kotlin.reflect.jvm.javaMethod
val fqnEscape = "#uC03o#"
fun fqn(function: KProperty1<KClass<*>, Collection<Any>>): String = function.fqn
fun fqn1(function: KFunction3<EntityStorage, ConnectionId, WorkspaceEntity, WorkspaceEntity?>): String = function.fqn
fun fqn2(function: KFunction3<EntityStorage, ConnectionId, WorkspaceEntity, Sequence<Any>>): String = function.fqn
fun fqn3(function: KFunction4<EntityStorage, ConnectionId, WorkspaceEntity, WorkspaceEntity?, Unit>): String = function.fqn
fun fqn4(function: KFunction4<EntityStorage, ConnectionId, WorkspaceEntity, List<WorkspaceEntity>, Unit>): String = function.fqn
fun fqn5(function: KFunction4<EntityStorage, ConnectionId, WorkspaceEntity, Sequence<WorkspaceEntity>, Unit>): String = function.fqn
fun fqn6(function: KFunction2<ModifiableWorkspaceEntityBase<*>, MutableEntityStorage, Unit>): String = function.fqn
private val KProperty<*>.fqn: String
get() {
val declaringClass = this.getter.javaMethod?.declaringClass ?: return ""
return fqn(declaringClass.packageName, this.name)
}
private val KFunction<*>.fqn: String
get() {
val declaringClass = this.javaMethod?.declaringClass ?: return ""
return fqn(declaringClass.packageName, this.name)
}
fun wsFqn(name: String): String {
val packageName = when (name) {
"VirtualFileUrl" -> "com.intellij.workspaceModel.storage.url"
"EntitySource", "referrersx", "referrersy"-> "com.intellij.workspaceModel.storage"
else -> null
}
return fqn(packageName, name)
}
/**
* Temporary string for adding to imports
*/
fun fqn(packageName: String?, name: String): String {
if (packageName == null) return name
return "$fqnEscape$packageName@@$name#$name"
}
val KClass<*>.fqn: String
get() = java.fqn
val Class<*>.fqn: String
get() {
val name = name
val packageName = name.substringBeforeLast(".")
val className = name.substringAfterLast(".")
.replace('$', '.')
if (className.contains(".")) {
val outerClassName = className.substringBefore(".")
val innerClassPath = className.substringAfter(".")
return fqn(packageName, outerClassName) + "." + innerClassPath
}
else {
return fqn(packageName, className)
}
}
class Imports(val scopeFqn: String?) {
val set = mutableSetOf<String>()
fun findAndRemoveFqns(str: String): String {
val res = StringBuilder()
var p = 0
while (true) {
var s = str.indexOf(fqnEscape, p)
if (s == -1) break
res.append(str, p, s)
s += fqnEscape.length
val e = str.indexOf('#', s)
check(e != -1)
val fqn = str.substring(s, e)
val (packageName, name) = fqn.split("@@")
add(packageName, name)
p = e + 1
}
res.append(str, p, str.length)
return res.toString()
}
fun add(packageName: String, name: String) {
if (packageName != scopeFqn) {
set.add("$packageName.$name")
}
}
}
fun fileContents(packageName: String?, code: String, additionalImports: Set<String>? = null): String {
val imports = Imports(packageName)
additionalImports?.let { imports.set.addAll(it) }
val code1 = imports.findAndRemoveFqns(code)
return buildString {
if (packageName != null) {
append("package $packageName\n")
}
if (imports.set.isNotEmpty()) {
append("\n")
imports.set.sorted().joinTo(this, "\n") { "import $it" }
append("\n")
}
append("\n")
append(code1)
}
} | apache-2.0 | e9e742fa5c93f41735b2834aa6c266c3 | 30.983471 | 132 | 0.696562 | 4.120341 | false | false | false | false |
Maccimo/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/RedundantLetInspection.kt | 1 | 11902 | // 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.inspections
import com.intellij.codeInspection.ProblemHighlightType
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiElement
import org.jetbrains.kotlin.descriptors.CallableMemberDescriptor
import org.jetbrains.kotlin.descriptors.impl.ValueParameterDescriptorImpl
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.base.psi.replaced
import org.jetbrains.kotlin.idea.core.util.isMultiLine
import org.jetbrains.kotlin.idea.intentions.*
import org.jetbrains.kotlin.idea.util.textRangeIn
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.*
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.bindingContextUtil.getReferenceTargets
import org.jetbrains.kotlin.resolve.calls.util.getResolvedCall
import org.jetbrains.kotlin.resolve.calls.model.VariableAsFunctionResolvedCall
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
import org.jetbrains.kotlin.types.isNullable
abstract class RedundantLetInspection : AbstractApplicabilityBasedInspection<KtCallExpression>(
KtCallExpression::class.java
) {
override fun inspectionText(element: KtCallExpression) = KotlinBundle.message("redundant.let.call.could.be.removed")
final override fun inspectionHighlightRangeInElement(element: KtCallExpression) = element.calleeExpression?.textRangeIn(element)
final override val defaultFixText get() = KotlinBundle.message("remove.let.call")
final override fun isApplicable(element: KtCallExpression): Boolean {
if (!element.isLetMethodCall()) return false
val lambdaExpression = element.lambdaArguments.firstOrNull()?.getLambdaExpression() ?: return false
val parameterName = lambdaExpression.getParameterName() ?: return false
return isApplicable(
element,
lambdaExpression.bodyExpression?.children?.singleOrNull() ?: return false,
lambdaExpression,
parameterName
)
}
protected abstract fun isApplicable(
element: KtCallExpression,
bodyExpression: PsiElement,
lambdaExpression: KtLambdaExpression,
parameterName: String
): Boolean
final override fun applyTo(element: KtCallExpression, project: Project, editor: Editor?) {
val lambdaExpression = element.lambdaArguments.firstOrNull()?.getLambdaExpression() ?: return
when (val bodyExpression = lambdaExpression.bodyExpression?.children?.singleOrNull() ?: return) {
is KtDotQualifiedExpression -> bodyExpression.applyTo(element)
is KtBinaryExpression -> bodyExpression.applyTo(element)
is KtCallExpression -> bodyExpression.applyTo(element, lambdaExpression.functionLiteral, editor)
is KtSimpleNameExpression -> deleteCall(element)
}
}
}
class SimpleRedundantLetInspection : RedundantLetInspection() {
override fun isApplicable(
element: KtCallExpression,
bodyExpression: PsiElement,
lambdaExpression: KtLambdaExpression,
parameterName: String
): Boolean = when (bodyExpression) {
is KtDotQualifiedExpression -> bodyExpression.isApplicable(parameterName)
is KtSimpleNameExpression -> bodyExpression.text == parameterName
else -> false
}
}
class ComplexRedundantLetInspection : RedundantLetInspection() {
override fun isApplicable(
element: KtCallExpression,
bodyExpression: PsiElement,
lambdaExpression: KtLambdaExpression,
parameterName: String
): Boolean = when (bodyExpression) {
is KtBinaryExpression ->
element.parent !is KtSafeQualifiedExpression && bodyExpression.isApplicable(parameterName)
is KtCallExpression ->
if (element.parent is KtSafeQualifiedExpression) {
false
} else {
val references = lambdaExpression.functionLiteral.valueParameterReferences(bodyExpression)
val destructuringDeclaration = lambdaExpression.functionLiteral.valueParameters.firstOrNull()?.destructuringDeclaration
references.isEmpty() || (references.singleOrNull()?.takeIf { expression ->
expression.parents.takeWhile { it != lambdaExpression.functionLiteral }.find { it is KtFunction } == null
} != null && destructuringDeclaration == null)
}
else ->
false
}
override fun inspectionHighlightType(element: KtCallExpression): ProblemHighlightType = if (isSingleLine(element))
ProblemHighlightType.GENERIC_ERROR_OR_WARNING
else
ProblemHighlightType.INFORMATION
}
private fun KtBinaryExpression.applyTo(element: KtCallExpression) {
val left = left ?: return
val factory = KtPsiFactory(element.project)
when (val parent = element.parent) {
is KtQualifiedExpression -> {
val receiver = parent.receiverExpression
val newLeft = when (left) {
is KtDotQualifiedExpression -> left.replaceFirstReceiver(factory, receiver, parent is KtSafeQualifiedExpression)
else -> receiver
}
val newExpression = factory.createExpressionByPattern("$0 $1 $2", newLeft, operationReference, right!!)
parent.replace(newExpression)
}
else -> {
val newLeft = when (left) {
is KtDotQualifiedExpression -> left.deleteFirstReceiver()
else -> factory.createThisExpression()
}
val newExpression = factory.createExpressionByPattern("$0 $1 $2", newLeft, operationReference, right!!)
element.replace(newExpression)
}
}
}
private fun KtDotQualifiedExpression.applyTo(element: KtCallExpression) {
when (val parent = element.parent) {
is KtQualifiedExpression -> {
val factory = KtPsiFactory(element.project)
val receiver = parent.receiverExpression
parent.replace(replaceFirstReceiver(factory, receiver, parent is KtSafeQualifiedExpression))
}
else -> {
element.replace(deleteFirstReceiver())
}
}
}
private fun deleteCall(element: KtCallExpression) {
val parent = element.parent as? KtQualifiedExpression
if (parent != null) {
val replacement = parent.selectorExpression?.takeIf { it != element } ?: parent.receiverExpression
parent.replace(replacement)
} else {
element.delete()
}
}
private fun KtCallExpression.applyTo(element: KtCallExpression, functionLiteral: KtFunctionLiteral, editor: Editor?) {
val parent = element.parent as? KtQualifiedExpression
val reference = functionLiteral.valueParameterReferences(this).firstOrNull()
val replaced = if (parent != null) {
reference?.replace(parent.receiverExpression)
parent.replaced(this)
} else {
reference?.replace(KtPsiFactory(this).createThisExpression())
element.replaced(this)
}
editor?.caretModel?.moveToOffset(replaced.startOffset)
}
private fun KtBinaryExpression.isApplicable(parameterName: String, isTopLevel: Boolean = true): Boolean {
val left = left ?: return false
if (isTopLevel) {
when (left) {
is KtNameReferenceExpression -> if (left.text != parameterName) return false
is KtDotQualifiedExpression -> if (!left.isApplicable(parameterName)) return false
else -> return false
}
} else {
if (!left.isApplicable(parameterName)) return false
}
val right = right ?: return false
return right.isApplicable(parameterName)
}
private fun KtExpression.isApplicable(parameterName: String): Boolean = when (this) {
is KtNameReferenceExpression -> text != parameterName
is KtDotQualifiedExpression -> !hasLambdaExpression() && !nameUsed(parameterName)
is KtBinaryExpression -> isApplicable(parameterName, isTopLevel = false)
is KtCallExpression -> isApplicable(parameterName)
is KtConstantExpression -> true
else -> false
}
private fun KtCallExpression.isApplicable(parameterName: String): Boolean = valueArguments.all {
val argumentExpression = it.getArgumentExpression() ?: return@all false
argumentExpression.isApplicable(parameterName)
}
private fun KtDotQualifiedExpression.isApplicable(parameterName: String): Boolean {
val context by lazy { analyze(BodyResolveMode.PARTIAL) }
return !hasLambdaExpression() && getLeftMostReceiverExpression().let { receiver ->
receiver is KtNameReferenceExpression &&
receiver.getReferencedName() == parameterName &&
!nameUsed(parameterName, except = receiver)
} && callExpression?.getResolvedCall(context) !is VariableAsFunctionResolvedCall && !hasNullableReceiverExtensionCall(context)
}
private fun KtDotQualifiedExpression.hasNullableReceiverExtensionCall(context: BindingContext): Boolean {
val descriptor = selectorExpression?.getResolvedCall(context)?.resultingDescriptor as? CallableMemberDescriptor ?: return false
if (descriptor.extensionReceiverParameter?.type?.isNullable() == true) return true
return (KtPsiUtil.deparenthesize(receiverExpression) as? KtDotQualifiedExpression)?.hasNullableReceiverExtensionCall(context) == true
}
private fun KtDotQualifiedExpression.hasLambdaExpression() = selectorExpression?.anyDescendantOfType<KtLambdaExpression>() ?: false
private fun KtCallExpression.isLetMethodCall() = calleeExpression?.text == "let" && isMethodCall("kotlin.let")
private fun KtLambdaExpression.getParameterName(): String? {
val parameters = valueParameters
if (parameters.size > 1) return null
return if (parameters.size == 1) parameters[0].text else "it"
}
private fun KtExpression.nameUsed(name: String, except: KtNameReferenceExpression? = null): Boolean =
anyDescendantOfType<KtNameReferenceExpression> { it != except && it.getReferencedName() == name }
private fun KtFunctionLiteral.valueParameterReferences(callExpression: KtCallExpression): List<KtNameReferenceExpression> {
val context = analyze(BodyResolveMode.PARTIAL)
val parameterDescriptor = context[BindingContext.FUNCTION, this]?.valueParameters?.singleOrNull() ?: return emptyList()
val variableDescriptorByName = if (parameterDescriptor is ValueParameterDescriptorImpl.WithDestructuringDeclaration)
parameterDescriptor.destructuringVariables.associateBy { it.name }
else
mapOf(parameterDescriptor.name to parameterDescriptor)
val callee = (callExpression.calleeExpression as? KtNameReferenceExpression)?.let {
val descriptor = variableDescriptorByName[it.getReferencedNameAsName()]
if (descriptor != null && it.getReferenceTargets(context).singleOrNull() == descriptor) listOf(it) else null
} ?: emptyList()
return callee + callExpression.valueArguments.flatMap { arg ->
arg.collectDescendantsOfType<KtNameReferenceExpression>().filter {
val descriptor = variableDescriptorByName[it.getReferencedNameAsName()]
descriptor != null && it.getResolvedCall(context)?.resultingDescriptor == descriptor
}
}
}
private fun isSingleLine(element: KtCallExpression): Boolean {
val qualifiedExpression = element.getQualifiedExpressionForSelector() ?: return true
var receiver = qualifiedExpression.receiverExpression
if (receiver.isMultiLine()) return false
var count = 1
while (true) {
if (count > 2) return false
receiver = (receiver as? KtQualifiedExpression)?.receiverExpression ?: break
count++
}
return true
}
| apache-2.0 | 173943c1f35bdf141cb6987ff4f34fb0 | 45.311284 | 158 | 0.726012 | 5.664921 | false | false | false | false |
Hexworks/zircon | zircon.core/src/commonMain/kotlin/org/hexworks/zircon/internal/shape/DefaultShape.kt | 1 | 1553 | package org.hexworks.zircon.internal.shape
import org.hexworks.zircon.api.builder.graphics.TileGraphicsBuilder
import org.hexworks.zircon.api.data.Position
import org.hexworks.zircon.api.data.Size
import org.hexworks.zircon.api.data.Tile
import org.hexworks.zircon.api.graphics.TileGraphics
import org.hexworks.zircon.api.resource.TilesetResource
import org.hexworks.zircon.api.shape.Shape
import kotlin.math.max
class DefaultShape(override val positions: Set<Position> = setOf()) : Shape, Collection<Position> by positions {
override fun toTileGraphics(tile: Tile, tileset: TilesetResource): TileGraphics {
val offsetPositions = offsetToDefaultPosition()
var maxCol = Int.MIN_VALUE
var maxRow = Int.MIN_VALUE
offsetPositions.forEach { (col, row) ->
maxCol = max(maxCol, col)
maxRow = max(maxRow, row)
}
val result = TileGraphicsBuilder.newBuilder()
.withSize(Size.create(maxCol + 1, maxRow + 1))
.withTileset(tileset)
.build()
offsetPositions.forEach {
result.draw(tile, it)
}
return result
}
override fun offsetToDefaultPosition(): Shape {
require(positions.isNotEmpty()) {
"You can't transform a Shape with zero points!"
}
val offset = Position.create(
x = positions.minByOrNull { it.x }!!.x,
y = positions.minByOrNull { it.y }!!.y
)
return DefaultShape(positions.map { it - offset }
.toSet())
}
}
| apache-2.0 | 22153267bd74ee74eeecd971f3f36668 | 35.116279 | 112 | 0.651642 | 4.220109 | false | false | false | false |
DuncanCasteleyn/DiscordModBot | src/main/kotlin/be/duncanc/discordmodbot/data/entities/ReportChannel.kt | 1 | 1519 | /*
* Copyright 2018 Duncan Casteleyn
*
* 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 be.duncanc.discordmodbot.data.entities
import javax.persistence.Column
import javax.persistence.Entity
import javax.persistence.Id
import javax.persistence.Table
import javax.validation.constraints.NotNull
@Entity
@Table(name = "report_channels")
data class ReportChannel
constructor(
@Id
@Column(updatable = false)
val guildId: Long,
@Column(nullable = false)
@field:NotNull
val textChannelId: Long
) {
override fun equals(other: Any?): Boolean {
if (this === other) {
return true
}
if (other == null || javaClass != other.javaClass) {
return false
}
val that = other as ReportChannel
return guildId == that.guildId
}
override fun hashCode(): Int = guildId.hashCode()
override fun toString(): String {
return "ReportChannel(guildId=$guildId, textChannelId=$textChannelId)"
}
}
| apache-2.0 | 9fe96d70f91f1368289ba6743e9c6309 | 26.125 | 78 | 0.691244 | 4.29096 | false | false | false | false |
wordpress-mobile/WordPress-Android | WordPress/src/main/java/org/wordpress/android/ui/jetpackoverlay/JetpackFeatureOverlayContentBuilder.kt | 1 | 7127 | package org.wordpress.android.ui.jetpackoverlay
import org.wordpress.android.R
import org.wordpress.android.ui.jetpackoverlay.JetpackFeatureRemovalOverlayUtil.JetpackFeatureOverlayScreenType
import org.wordpress.android.ui.jetpackoverlay.JetpackFeatureRemovalPhase.PhaseFour
import org.wordpress.android.ui.jetpackoverlay.JetpackFeatureRemovalPhase.PhaseNewUsers
import org.wordpress.android.ui.jetpackoverlay.JetpackFeatureRemovalPhase.PhaseOne
import org.wordpress.android.ui.jetpackoverlay.JetpackFeatureRemovalPhase.PhaseThree
import org.wordpress.android.ui.jetpackoverlay.JetpackFeatureRemovalPhase.PhaseTwo
import javax.inject.Inject
class JetpackFeatureOverlayContentBuilder @Inject constructor() {
fun build(params: JetpackFeatureOverlayContentBuilderParams): JetpackFeatureOverlayUIState {
return when (params.currentPhase) {
is PhaseOne -> getStateForPhaseOne(params, params.feature!!)
PhaseTwo -> TODO()
PhaseThree -> TODO()
PhaseFour -> TODO()
PhaseNewUsers -> TODO()
}
}
private fun getStateForPhaseOne(
params: JetpackFeatureOverlayContentBuilderParams,
feature: JetpackFeatureOverlayScreenType
): JetpackFeatureOverlayUIState {
val componentVisibility = JetpackFeatureOverlayComponentVisibility.PhaseOne()
val content = when (feature) {
JetpackFeatureOverlayScreenType.STATS -> getStateForPhaseOneStats(params.isRtl)
JetpackFeatureOverlayScreenType.NOTIFICATIONS -> getStateForPhaseOneNotifications(params.isRtl)
JetpackFeatureOverlayScreenType.READER -> getStateForPhaseOneReader(params.isRtl)
}
return JetpackFeatureOverlayUIState(componentVisibility, content)
}
private fun getStateForPhaseOneStats(rtl: Boolean): JetpackFeatureOverlayContent {
return JetpackFeatureOverlayContent(
illustration = if (rtl) R.raw.jp_stats_rtl else R.raw.jp_stats_left,
title = R.string.wp_jetpack_feature_removal_overlay_phase_one_title_stats,
caption = R.string.wp_jetpack_feature_removal_overlay_phase_one_description_stats,
primaryButtonText = R.string.wp_jetpack_feature_removal_overlay_switch_to_new_jetpack_app,
secondaryButtonText = R.string.wp_jetpack_continue_to_stats
)
}
private fun getStateForPhaseOneReader(rtl: Boolean): JetpackFeatureOverlayContent {
return JetpackFeatureOverlayContent(
illustration = if (rtl) R.raw.jp_reader_rtl else R.raw.jp_reader_left,
title = R.string.wp_jetpack_feature_removal_overlay_phase_one_title_reader,
caption = R.string.wp_jetpack_feature_removal_overlay_phase_one_description_reader,
primaryButtonText = R.string.wp_jetpack_feature_removal_overlay_switch_to_new_jetpack_app,
secondaryButtonText = R.string.wp_jetpack_continue_to_reader
)
}
private fun getStateForPhaseOneNotifications(rtl: Boolean): JetpackFeatureOverlayContent {
return JetpackFeatureOverlayContent(
illustration = if (rtl) R.raw.jp_notifications_rtl else R.raw.jp_notifications_left,
title = R.string.wp_jetpack_feature_removal_overlay_phase_one_title_notifications,
caption = R.string.wp_jetpack_feature_removal_overlay_phase_one_description_notifications,
primaryButtonText = R.string.wp_jetpack_feature_removal_overlay_switch_to_new_jetpack_app,
secondaryButtonText = R.string.wp_jetpack_continue_to_notifications
)
}
fun buildSiteCreationOverlayState(
siteCreationPhase: JetpackFeatureRemovalSiteCreationPhase,
isRtl: Boolean
): JetpackFeatureOverlayUIState {
return when (siteCreationPhase) {
JetpackFeatureRemovalSiteCreationPhase.PHASE_ONE -> getStateForSiteCreationPhaseOne(isRtl)
JetpackFeatureRemovalSiteCreationPhase.PHASE_TWO -> getStateForSiteCreationPhaseTwo(isRtl)
}
}
private fun getStateForSiteCreationPhaseOne(isRtl: Boolean): JetpackFeatureOverlayUIState {
val componentVisibility = JetpackFeatureOverlayComponentVisibility
.SiteCreationPhase.PhaseOne()
val content = getContentForSiteCreationPhaseOne(isRtl)
return JetpackFeatureOverlayUIState(componentVisibility, content)
}
private fun getContentForSiteCreationPhaseOne(rtl: Boolean): JetpackFeatureOverlayContent {
return JetpackFeatureOverlayContent(
illustration = if (rtl) R.raw.wp2jp_rtl else R.raw.wp2jp_left,
title = R.string.wp_jetpack_feature_removal_site_creation_overlay_title,
caption = R.string.wp_jetpack_feature_removal_site_creation_overlay_phase_one_description,
primaryButtonText = R.string.wp_jetpack_feature_removal_overlay_switch_to_new_jetpack_app,
secondaryButtonText = R.string.wp_jetpack_continue_without_jetpack
)
}
private fun getStateForSiteCreationPhaseTwo(rtl: Boolean): JetpackFeatureOverlayUIState {
val componentVisibility = JetpackFeatureOverlayComponentVisibility
.SiteCreationPhase.PhaseTwo()
val content = getContentForSiteCreationPhaseTwo(rtl)
return JetpackFeatureOverlayUIState(componentVisibility, content)
}
private fun getContentForSiteCreationPhaseTwo(rtl: Boolean): JetpackFeatureOverlayContent {
return JetpackFeatureOverlayContent(
illustration = if (rtl) R.raw.wp2jp_rtl else R.raw.wp2jp_left,
title = R.string.wp_jetpack_feature_removal_site_creation_overlay_title,
caption = R.string.wp_jetpack_feature_removal_site_creation_overlay_phase_two_description,
primaryButtonText = R.string.wp_jetpack_feature_removal_overlay_switch_to_new_jetpack_app,
)
}
fun buildDeepLinkOverlayState(isRtl: Boolean): JetpackFeatureOverlayUIState { return getStateForDeepLink(isRtl) }
private fun getStateForDeepLink(isRtl: Boolean): JetpackFeatureOverlayUIState {
val componentVisibility = JetpackFeatureOverlayComponentVisibility
.DeepLinkPhase.All()
val content = getContentForDeepLink(isRtl)
return JetpackFeatureOverlayUIState(componentVisibility, content)
}
private fun getContentForDeepLink(rtl: Boolean): JetpackFeatureOverlayContent {
return JetpackFeatureOverlayContent(
illustration = if (rtl) R.raw.wp2jp_rtl else R.raw.wp2jp_left,
title = R.string.wp_jetpack_deep_link_overlay_title,
caption = R.string.wp_jetpack_deep_link_overlay_description,
primaryButtonText = R.string.wp_jetpack_deep_link_open_in_jetpack,
secondaryButtonText = R.string.wp_jetpack_continue_without_jetpack
)
}
}
data class JetpackFeatureOverlayContentBuilderParams(
val currentPhase: JetpackFeatureRemovalPhase,
val isRtl: Boolean = true,
val feature: JetpackFeatureOverlayScreenType?
)
| gpl-2.0 | 08c97e66ff1936f84807aee62b082924 | 52.186567 | 117 | 0.724007 | 4.56859 | false | false | false | false |
wordpress-mobile/WordPress-Android | WordPress/src/main/java/org/wordpress/android/ui/photopicker/ThumbnailViewUtils.kt | 1 | 5931 | package org.wordpress.android.ui.photopicker
import android.view.View
import android.widget.ImageView
import android.widget.TextView
import org.wordpress.android.R.anim
import org.wordpress.android.R.drawable
import org.wordpress.android.R.string
import org.wordpress.android.util.AccessibilityUtils
import org.wordpress.android.util.AniUtils
import org.wordpress.android.util.AniUtils.Duration.SHORT
import org.wordpress.android.util.PhotoPickerUtils
import org.wordpress.android.util.ViewUtils
import org.wordpress.android.util.image.ImageManager
import org.wordpress.android.util.extensions.redirectContextClickToLongPressListener
import java.util.Locale
@Deprecated("This class is being refactored, if you implement any change, please also update " +
"{@link org.wordpress.android.ui.mediapicker.ThumbnailViewUtils}")
class ThumbnailViewUtils(val imageManager: ImageManager) {
@Suppress("DEPRECATION", "LongParameterList")
fun setupListeners(
imgThumbnail: ImageView,
isVideo: Boolean,
isSelected: Boolean,
toggleAction: PhotoPickerUiItem.ToggleAction,
clickAction: PhotoPickerUiItem.ClickAction,
animateSelection: Boolean
) {
addImageSelectedToAccessibilityFocusedEvent(imgThumbnail, isSelected)
imgThumbnail.setOnClickListener {
toggleAction.toggle()
PhotoPickerUtils.announceSelectedMediaForAccessibility(
imgThumbnail,
isVideo,
!isSelected
)
}
imgThumbnail.setOnLongClickListener {
clickAction.click()
true
}
imgThumbnail.redirectContextClickToLongPressListener()
displaySelection(animateSelection, isSelected, imgThumbnail)
}
private fun addImageSelectedToAccessibilityFocusedEvent(
imageView: ImageView,
isSelected: Boolean
) {
AccessibilityUtils.addPopulateAccessibilityEventFocusedListener(
imageView
) {
val imageSelectedText = imageView.context
.getString(string.photo_picker_image_selected)
if (isSelected) {
if (!imageView.contentDescription.toString().contains(imageSelectedText)) {
imageView.contentDescription = ("${imageView.contentDescription} $imageSelectedText")
}
} else {
imageView.contentDescription = imageView.contentDescription
.toString().replace(
imageSelectedText,
""
)
}
}
}
private fun displaySelection(animate: Boolean, isSelected: Boolean, imageView: ImageView) {
if (animate) {
if (isSelected) {
AniUtils.scale(
imageView,
SCALE_NORMAL,
SCALE_SELECTED,
ANI_DURATION
)
} else {
AniUtils.scale(
imageView,
SCALE_SELECTED,
SCALE_NORMAL,
ANI_DURATION
)
}
} else {
val scale = if (isSelected) SCALE_SELECTED else SCALE_NORMAL
if (imageView.scaleX != scale) {
imageView.scaleX = scale
imageView.scaleY = scale
}
}
}
fun displayTextSelectionCount(
animate: Boolean,
showOrderCounter: Boolean,
isSelected: Boolean,
txtSelectionCount: TextView
) {
if (animate) {
when {
showOrderCounter -> {
AniUtils.startAnimation(
txtSelectionCount,
anim.pop
)
}
isSelected -> {
AniUtils.fadeIn(
txtSelectionCount,
ANI_DURATION
)
}
else -> {
AniUtils.fadeOut(
txtSelectionCount,
ANI_DURATION
)
}
}
} else {
txtSelectionCount.visibility = if (showOrderCounter || isSelected) View.VISIBLE else View.GONE
}
}
fun updateSelectionCountForPosition(
txtSelectionCount: TextView,
selectedOrder: Int?
) {
if (selectedOrder != null) {
txtSelectionCount.text = String.format(Locale.getDefault(), "%d", selectedOrder)
} else {
txtSelectionCount.text = null
}
}
fun setupTextSelectionCount(
txtSelectionCount: TextView,
isSelected: Boolean,
selectedOrder: Int?,
showOrderCounter: Boolean,
animateSelection: Boolean
) {
ViewUtils.addCircularShadowOutline(
txtSelectionCount
)
txtSelectionCount.isSelected = isSelected
updateSelectionCountForPosition(txtSelectionCount, selectedOrder)
if (!showOrderCounter) {
txtSelectionCount.setBackgroundResource(drawable.photo_picker_circle_pressed)
}
displayTextSelectionCount(
animateSelection,
showOrderCounter,
isSelected,
txtSelectionCount
)
}
@Suppress("DEPRECATION")
fun setupVideoOverlay(videoOverlay: ImageView, clickAction: PhotoPickerUiItem.ClickAction) {
videoOverlay.visibility = View.VISIBLE
videoOverlay.setOnClickListener { clickAction.click() }
}
companion object {
private const val SCALE_NORMAL = 1.0f
private const val SCALE_SELECTED = .8f
private val ANI_DURATION = SHORT
}
}
| gpl-2.0 | 80dce1973cba802b0e82e030f0474ab3 | 33.283237 | 106 | 0.571067 | 5.574248 | false | false | false | false |
RadiationX/ForPDA | app/src/main/java/forpdateam/ru/forpda/ui/fragments/notes/NotesFragment.kt | 1 | 5983 | package forpdateam.ru.forpda.ui.fragments.notes
import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.widget.Toast
import moxy.presenter.InjectPresenter
import moxy.presenter.ProvidePresenter
import forpdateam.ru.forpda.App
import forpdateam.ru.forpda.R
import forpdateam.ru.forpda.common.FilePickHelper
import forpdateam.ru.forpda.entity.app.CloseableInfo
import forpdateam.ru.forpda.entity.app.notes.NoteItem
import forpdateam.ru.forpda.presentation.notes.NotesPresenter
import forpdateam.ru.forpda.presentation.notes.NotesView
import forpdateam.ru.forpda.ui.fragments.RecyclerFragment
import forpdateam.ru.forpda.ui.fragments.TabFragment
import forpdateam.ru.forpda.ui.fragments.devdb.brand.DevicesFragment
import forpdateam.ru.forpda.ui.fragments.notes.adapters.NotesAdapter
import forpdateam.ru.forpda.ui.views.ContentController
import forpdateam.ru.forpda.ui.views.DynamicDialogMenu
import forpdateam.ru.forpda.ui.views.FunnyContent
import forpdateam.ru.forpda.ui.views.adapters.BaseAdapter
/**
* Created by radiationx on 06.09.17.
*/
class NotesFragment : RecyclerFragment(), NotesView, BaseAdapter.OnItemClickListener<NoteItem> {
private lateinit var adapter: NotesAdapter
private val dialogMenu = DynamicDialogMenu<NotesFragment, NoteItem>()
@InjectPresenter
lateinit var presenter: NotesPresenter
@ProvidePresenter
fun providePresenter(): NotesPresenter = NotesPresenter(
App.get().Di().notesRepository,
App.get().Di().closeableInfoHolder,
App.get().Di().router,
App.get().Di().linkHandler,
App.get().Di().errorHandler
)
init {
configuration.defaultTitle = App.get().getString(R.string.fragment_title_notes)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
setCardsBackground()
setScrollFlagsEnterAlways()
adapter = NotesAdapter(this, presenter::onInfoClick)
recyclerView.adapter = adapter
recyclerView.layoutManager = androidx.recyclerview.widget.LinearLayoutManager(context)
refreshLayout.setOnRefreshListener { presenter.loadNotes() }
recyclerView.addItemDecoration(DevicesFragment.SpacingItemDecoration(App.px8, false))
dialogMenu.apply {
addItem(getString(R.string.copy_link)) { _, data ->
presenter.copyLink(data)
}
addItem(getString(R.string.edit)) { _, data ->
presenter.editNote(data)
}
addItem(getString(R.string.delete)) { _, data ->
presenter.deleteNote(data.id)
}
}
}
override fun addBaseToolbarMenu(menu: Menu) {
super.addBaseToolbarMenu(menu)
menu
.add(R.string.add)
.setIcon(App.getVecDrawable(context, R.drawable.ic_toolbar_add))
.setOnMenuItemClickListener {
presenter.addNote()
true
}
.setShowAsActionFlags(MenuItem.SHOW_AS_ACTION_ALWAYS)
menu
.add(R.string.import_s)
.setOnMenuItemClickListener {
App.get().checkStoragePermission({
startActivityForResult(FilePickHelper.pickFile(false), TabFragment.REQUEST_PICK_FILE)
}, App.getActivity())
true
}
menu
.add(R.string.export_s)
.setOnMenuItemClickListener {
App.get().checkStoragePermission({ presenter.exportNotes() }, App.getActivity())
true
}
}
override fun showNotes(items: List<NoteItem>, info: List<CloseableInfo>) {
if (items.isEmpty()) {
if (!contentController.contains(ContentController.TAG_NO_DATA)) {
val funnyContent = FunnyContent(context)
.setImage(R.drawable.ic_bookmark)
.setTitle(R.string.funny_notes_nodata_title)
contentController.addContent(funnyContent, ContentController.TAG_NO_DATA)
}
contentController.showContent(ContentController.TAG_NO_DATA)
} else {
contentController.hideContent(ContentController.TAG_NO_DATA)
}
adapter.bindItems(items, info)
}
override fun showNotesEditPopup(item: NoteItem) {
NotesAddPopup(context, item)
}
override fun showNotesAddPopup() {
NotesAddPopup(context, null)
}
override fun onImportNotes() {
Toast.makeText(context, "Заметки успешно импортированы", Toast.LENGTH_SHORT).show()
}
override fun onExportNotes(path: String) {
Toast.makeText(context, "Заметки успешно экспортированы в $path", Toast.LENGTH_SHORT).show()
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (resultCode == Activity.RESULT_OK) {
if (data == null) {
//Display an error
return
}
if (requestCode == TabFragment.REQUEST_PICK_FILE) {
val files = FilePickHelper.onActivityResult(context, data)
val file = files[0]
presenter.importNotes(file)
} else if (requestCode == TabFragment.REQUEST_SAVE_FILE) {
}
}
}
override fun onItemClick(item: NoteItem) {
presenter.onItemClick(item)
}
override fun onItemLongClick(item: NoteItem): Boolean {
dialogMenu.apply {
disallowAll()
allowAll()
show(context, this@NotesFragment, item)
}
return true
}
}
| gpl-3.0 | 47206d2f4a63e3840940daba32f2c1a0 | 35.361963 | 109 | 0.64299 | 4.566256 | false | false | false | false |
ingokegel/intellij-community | plugins/kotlin/code-insight/impl-base/src/org/jetbrains/kotlin/idea/structureView/KotlinStructureViewModel.kt | 1 | 3788 | // 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.structureView
import com.intellij.ide.structureView.StructureViewModel
import com.intellij.ide.structureView.StructureViewModelBase
import com.intellij.ide.structureView.StructureViewTreeElement
import com.intellij.ide.structureView.impl.java.VisibilitySorter
import com.intellij.ide.util.treeView.smartTree.*
import com.intellij.openapi.editor.Editor
import com.intellij.psi.NavigatablePsiElement
import com.intellij.psi.PsiElement
import com.intellij.util.PlatformIcons
import org.jetbrains.kotlin.idea.KotlinCodeInsightBundle
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.containingClassOrObject
import org.jetbrains.kotlin.psi.psiUtil.isPropertyParameter
open class KotlinStructureViewModel(ktFile: KtFile, editor: Editor?, rootElement : StructureViewTreeElement) :
StructureViewModelBase(ktFile, editor, rootElement),
StructureViewModel.ElementInfoProvider {
init {
withSorters(KotlinVisibilitySorter, Sorter.ALPHA_SORTER)
}
override fun isSuitable(element: PsiElement?): Boolean = element is KtDeclaration &&
element !is KtPropertyAccessor &&
element !is KtFunctionLiteral &&
!(element is KtProperty && element.parent !is KtFile && element.containingClassOrObject !is KtNamedDeclaration) &&
!(element is KtFunction && element.parent !is KtFile && element.containingClassOrObject !is KtNamedDeclaration)
override fun getFilters() = FILTERS
override fun isAlwaysShowsPlus(element: StructureViewTreeElement): Boolean {
val value = element.value
return (value is KtClassOrObject && value !is KtEnumEntry) || value is KtFile
}
override fun isAlwaysLeaf(element: StructureViewTreeElement): Boolean {
// Local declarations can in any other declaration
return false
}
companion object {
private val FILTERS = arrayOf(PropertiesFilter, PublicElementsFilter)
}
}
object KotlinVisibilitySorter : VisibilitySorter() {
override fun getComparator() = Comparator<Any> { a1, a2 -> a1.accessLevel() - a2.accessLevel() }
private fun Any.accessLevel() = (this as? AbstractKotlinStructureViewElement)?.accessLevel ?: Int.MAX_VALUE
override fun getName() = ID
const val ID = "KOTLIN_VISIBILITY_SORTER"
}
object PublicElementsFilter : Filter {
override fun isVisible(treeNode: TreeElement): Boolean {
return (treeNode as? AbstractKotlinStructureViewElement)?.isPublic ?: true
}
override fun getPresentation(): ActionPresentation {
return ActionPresentationData(KotlinCodeInsightBundle.message("show.non.public"), null, PlatformIcons.PRIVATE_ICON)
}
override fun getName() = ID
override fun isReverted() = true
const val ID = "KOTLIN_SHOW_NON_PUBLIC"
}
object PropertiesFilter : Filter {
override fun isVisible(treeNode: TreeElement): Boolean {
val element = (treeNode as? AbstractKotlinStructureViewElement)?.element
val isProperty = element is KtProperty && element.isMember || element is KtParameter && element.isPropertyParameter()
return !isProperty
}
override fun getPresentation(): ActionPresentation {
return ActionPresentationData(KotlinCodeInsightBundle.message("show.properties"), null, PlatformIcons.PROPERTY_ICON)
}
override fun getName() = ID
override fun isReverted() = true
const val ID = "KOTLIN_SHOW_PROPERTIES"
}
/**
* Required until 2 implementations would be merged
*/
interface AbstractKotlinStructureViewElement {
val accessLevel : Int?
val isPublic : Boolean
val element : NavigatablePsiElement
} | apache-2.0 | 03ff6f3a96aa9a823b268264bfc8f45e | 36.514851 | 126 | 0.748416 | 5.030544 | false | false | false | false |
ingokegel/intellij-community | plugins/kotlin/uast/uast-kotlin-base/src/org/jetbrains/uast/kotlin/declarations/KotlinScriptUClass.kt | 8 | 2610 | /*
* Copyright 2010-2021 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.uast.kotlin
import com.intellij.psi.*
import org.jetbrains.annotations.ApiStatus
import org.jetbrains.kotlin.asJava.classes.KtLightClassForScript
import org.jetbrains.kotlin.asJava.elements.KtLightMethod
import org.jetbrains.kotlin.psi.KtClassOrObject
import org.jetbrains.kotlin.psi.KtScript
import org.jetbrains.kotlin.psi.KtScriptInitializer
import org.jetbrains.uast.*
@ApiStatus.Internal
class KotlinScriptUClass(
psi: KtLightClassForScript,
givenParent: UElement?
) : AbstractKotlinUClass(givenParent), PsiClass by psi {
override fun getContainingFile(): PsiFile = unwrapFakeFileForLightClass(psi.containingFile)
override fun getNameIdentifier(): PsiIdentifier = UastLightIdentifier(psi, psi.kotlinOrigin)
override val uastAnchor: UIdentifier by lz { KotlinUIdentifier(nameIdentifier, sourcePsi?.nameIdentifier, this) }
override val javaPsi: PsiClass = psi
override val sourcePsi: KtClassOrObject? = psi.kotlinOrigin
override val psi = unwrap<UClass, KtLightClassForScript>(psi)
override fun getSuperClass(): UClass? = super.getSuperClass()
override fun getFields(): Array<UField> = super.getFields()
override fun getInitializers(): Array<UClassInitializer> = super.getInitializers()
override fun getInnerClasses(): Array<UClass> =
psi.innerClasses.mapNotNull { getLanguagePlugin().convertOpt<UClass>(it, this) }.toTypedArray()
override fun getMethods(): Array<UMethod> = psi.methods.map(this::createUMethod).toTypedArray()
private fun createUMethod(method: PsiMethod): UMethod {
return if (method.isConstructor) {
KotlinScriptConstructorUMethod(psi.script, method as KtLightMethod, this)
}
else {
languagePlugin?.convertOpt(method, this) ?: reportConvertFailure(method)
}
}
override fun getOriginalElement(): PsiElement? = psi.originalElement
@ApiStatus.Internal
class KotlinScriptConstructorUMethod(
script: KtScript,
override val psi: KtLightMethod,
givenParent: UElement?
) : KotlinUMethod(psi, psi.kotlinOrigin, givenParent) {
override val uastBody: UExpression? by lz {
val initializers = script.declarations.filterIsInstance<KtScriptInitializer>()
KotlinLazyUBlockExpression.create(initializers, this)
}
override val javaPsi = psi
}
}
| apache-2.0 | 7e4f45caeac62bf84fad64716bbf6a78 | 37.955224 | 117 | 0.742146 | 4.952562 | false | false | false | false |
kelsos/mbrc | app/src/main/kotlin/com/kelsos/mbrc/ui/help_feedback/HelpFragment.kt | 1 | 1598 | package com.kelsos.mbrc.ui.help_feedback
import android.content.pm.PackageManager
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.webkit.WebView
import android.webkit.WebViewClient
import androidx.fragment.app.Fragment
import com.kelsos.mbrc.R
import com.kelsos.mbrc.utilities.RemoteUtils.getVersion
import timber.log.Timber
class HelpFragment : Fragment() {
lateinit var helpView: WebView
override fun onStart() {
super.onStart()
val url: String
url = try {
String.format(
"https://mbrc.kelsos.net/help?version=%s",
requireContext().getVersion()
)
} catch (e: PackageManager.NameNotFoundException) {
Timber.v(e, "Failed to get version")
"https://mbrc.kelsos.net/help"
}
helpView.loadUrl(url)
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
val view = inflater.inflate(R.layout.fragment_help, container, false)
helpView = view.findViewById(R.id.help_webview)
helpView.webViewClient = RemoteWebViewClient()
return view
}
private class RemoteWebViewClient : WebViewClient() {
@Suppress("OverridingDeprecatedMember")
override fun shouldOverrideUrlLoading(view: WebView, url: String): Boolean {
view.loadUrl(url)
return false
}
}
companion object {
fun newInstance(): HelpFragment {
return HelpFragment()
}
}
}// Required empty public constructor
| gpl-3.0 | 0d80e3626b6002d97db89cab4980b089 | 24.774194 | 80 | 0.714018 | 4.318919 | false | false | false | false |
mdaniel/intellij-community | platform/workspaceModel/codegen/src/com/intellij/workspaceModel/codegen/writer/fields/implWsEntityFiledCode.kt | 1 | 6852 | package com.intellij.workspaceModel.codegen.fields
import com.intellij.workspaceModel.storage.EntityStorage
import com.intellij.workspaceModel.storage.impl.*
import com.intellij.workspaceModel.codegen.*
import com.intellij.workspaceModel.codegen.fields.javaType
import com.intellij.workspaceModel.codegen.getRefType
import com.intellij.workspaceModel.codegen.isRefType
import com.intellij.workspaceModel.codegen.refsFields
import com.intellij.workspaceModel.codegen.deft.model.KtObjModule
import com.intellij.workspaceModel.codegen.utils.fqn1
import com.intellij.workspaceModel.codegen.utils.fqn2
import com.intellij.workspaceModel.codegen.deft.*
import com.intellij.workspaceModel.codegen.deft.Field
import com.intellij.workspaceModel.codegen.deft.MemberOrExtField
val Field<*, *>.implWsEntityFieldCode: String
get() = buildString {
if (hasSetter) {
if (isOverride && name !in listOf("name", "entitySource")) {
append(implWsBlockingCodeOverride)
}
else append(implWsBlockingCode)
} else {
append("override var $javaName: ${type.javaType} = super<${owner.javaFullName}>.$javaName\n")
}
}
private val Field<*, *>.implWsBlockingCode: String
get() = implWsBlockCode(type, name, "")
internal fun Field<*, *>.implWsBlockCode(fieldType: ValueType<*>, name: String, optionalSuffix: String = ""): String {
return when (fieldType) {
TInt -> "override var $javaName: ${fieldType.javaType} = 0"
TBoolean -> "override var $javaName: ${fieldType.javaType} = false"
TString -> """
@JvmField var $implFieldName: String? = null
override val $javaName: ${fieldType.javaType}${optionalSuffix}
get() = $implFieldName${if (optionalSuffix.isBlank()) "!!" else ""}
""".trimIndent()
is TRef -> {
val notNullAssertion = if (optionalSuffix.isBlank()) "!!" else ""
"""
override val $name: ${fieldType.javaType}$optionalSuffix
get() = snapshot.${refsConnectionMethodCode()}$notNullAssertion
""".trimIndent()
}
is TList<*> -> {
if (fieldType.isRefType()) {
val connectionName = name.uppercase() + "_CONNECTION_ID"
val notNullAssertion = if (optionalSuffix.isBlank()) "!!" else ""
if ((fieldType.elementType as TRef<*>).targetObjType.abstract) {
"""
override val $name: ${fieldType.javaType}$optionalSuffix
get() = snapshot.${fqn2(EntityStorage::extractOneToAbstractManyChildren)}<${fieldType.elementType.javaType}>($connectionName, this)$notNullAssertion.toList()
""".trimIndent()
}
else {
"""
override val $name: ${fieldType.javaType}$optionalSuffix
get() = snapshot.${fqn2(EntityStorage::extractOneToManyChildren)}<${fieldType.elementType.javaType}>($connectionName, this)$notNullAssertion.toList()
""".trimIndent()
}
}
else {
val notNullAssertion = if (optionalSuffix.isBlank()) "!!" else ""
"""
@JvmField var $implFieldName: ${fieldType.javaType}? = null
override val $javaName: ${fieldType.javaType}$optionalSuffix
get() = $implFieldName$notNullAssertion
""".trimIndent()
}
}
is TSet<*> -> {
if (fieldType.isRefType()) {
error("Set of references is not supported")
}
else {
val notNullAssertion = if (optionalSuffix.isBlank()) "!!" else ""
"""
@JvmField var $implFieldName: ${fieldType.javaType}? = null
override val $javaName: ${fieldType.javaType}$optionalSuffix
get() = $implFieldName$notNullAssertion
""".trimIndent()
}
}
is TMap<*, *> -> """
@JvmField var $implFieldName: ${fieldType.javaType}? = null
override val $javaName: ${fieldType.javaType}$optionalSuffix
get() = $implFieldName${if (optionalSuffix.isBlank()) "!!" else ""}
""".trimIndent()
is TOptional<*> -> when (fieldType.type) {
TInt, TBoolean -> "override var $javaName: ${fieldType.javaType} = null"
else -> implWsBlockCode(fieldType.type, name, "?")
}
is TBlob<*> -> """
@JvmField var $implFieldName: ${fieldType.javaSimpleName}? = null
override val $javaName: ${fieldType.javaSimpleName}$optionalSuffix
get() = $implFieldName${if (optionalSuffix.isBlank()) "!!" else ""}
""".trimIndent()
else -> error("Unsupported field type: $this")
}
}
internal val Field<*, *>.implWsBlockingCodeOverride: String
get() {
val originalField = owner.structure.refsFields.first { it.type.javaType == type.javaType }
val connectionName = originalField.name.uppercase() + "_CONNECTION_ID"
var valueType = referencedField.type
val notNullAssertion = if (valueType is TOptional<*>) "" else "!!"
if (valueType is TOptional<*>) {
valueType = valueType.type as ValueType<Any?>
}
val getterName = when (valueType) {
is TList<*> -> if (owner.abstract)
fqn1(EntityStorage::extractOneToAbstractManyParent)
else
fqn1(EntityStorage::extractOneToManyParent)
is TRef<*> -> if (owner.abstract)
fqn1(EntityStorage::extractOneToAbstractOneParent)
else
fqn1(EntityStorage::extractOneToOneParent)
else -> error("Unsupported reference type")
}
return """
override val $javaName: ${type.javaType}
get() = snapshot.$getterName($connectionName, this)$notNullAssertion
""".trimIndent()
}
internal val MemberOrExtField<*, *>.referencedField: MemberOrExtField<*, *>
get() {
val ref = type.getRefType()
val declaredReferenceFromChild =
ref.targetObjType.structure.refsFields.filter { it.type.getRefType().targetObjType == owner && it != this } +
((ref.targetObjType.module as? KtObjModule)?.extFields?.filter { it.type.getRefType().targetObjType == owner && it.owner == ref.targetObjType && it != this }
?: emptyList())
if (declaredReferenceFromChild.isEmpty()) {
error("Reference should be declared at both entities. It exist at ${owner.name}#$name but absent at ${ref.targetObjType.name}")
}
if (declaredReferenceFromChild.size > 1) {
error(
"More then one reference to ${owner.name} declared at ${declaredReferenceFromChild[0].owner}#${declaredReferenceFromChild[0].name}," +
"${declaredReferenceFromChild[1].owner}#${declaredReferenceFromChild[1].name}")
}
return declaredReferenceFromChild[0]
}
| apache-2.0 | d741a4f12a595943167fc498fb8b2207 | 43.206452 | 177 | 0.623468 | 4.699588 | false | false | false | false |
micolous/metrodroid | src/commonMain/kotlin/au/id/micolous/metrodroid/transit/ravkav/RavKavSubscription.kt | 1 | 3305 | /*
* RavKavSubscription.kt
*
* Copyright 2018 Google
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package au.id.micolous.metrodroid.transit.ravkav
import au.id.micolous.metrodroid.multi.Parcelize
import au.id.micolous.metrodroid.transit.TransitBalance
import au.id.micolous.metrodroid.transit.TransitCurrency
import au.id.micolous.metrodroid.transit.en1545.*
import au.id.micolous.metrodroid.util.ImmutableByteArray
@Parcelize
class RavKavSubscription (override val parsed: En1545Parsed,
private val counter: Int?): En1545Subscription() {
override val balance: TransitBalance?
get() = if (ctrUse != 3 || counter == null) null else TransitCurrency.ILS(counter)
override val remainingTripCount: Int?
get() = if (ctrUse == 2 || counter == null) counter else null
private val ctrUse: Int
get() {
val tariffType = parsed.getIntOrZero(En1545Subscription.CONTRACT_TARIFF)
return tariffType shr 6 and 0x7
}
override val lookup: En1545Lookup
get() = RavKavLookup
constructor(data: ImmutableByteArray, ctr: Int?) : this(En1545Parser.parse(data, SUB_FIELDS), ctr)
companion object {
private val SUB_FIELDS = En1545Container(
En1545FixedInteger("Version", 3),
En1545FixedInteger.date(En1545Subscription.CONTRACT_START),
En1545FixedInteger(En1545Subscription.CONTRACT_PROVIDER, 8),
En1545FixedInteger(En1545Subscription.CONTRACT_TARIFF, 11),
En1545FixedInteger.date(En1545Subscription.CONTRACT_SALE),
En1545FixedInteger(En1545Subscription.CONTRACT_SALE_DEVICE, 12),
En1545FixedInteger("ContractSaleNumber", 10),
En1545FixedInteger(En1545Subscription.CONTRACT_INTERCHANGE, 1),
En1545Bitmap(
En1545FixedInteger(En1545Subscription.CONTRACT_UNKNOWN_A, 5),
En1545FixedInteger(En1545Subscription.CONTRACT_RESTRICT_CODE, 5),
En1545FixedInteger("ContractRestrictDuration", 6),
En1545FixedInteger.date(En1545Subscription.CONTRACT_END),
En1545FixedInteger(En1545Subscription.CONTRACT_DURATION, 8),
En1545FixedInteger(En1545Subscription.CONTRACT_UNKNOWN_B, 32),
En1545FixedInteger(En1545Subscription.CONTRACT_UNKNOWN_C, 6),
En1545FixedInteger(En1545Subscription.CONTRACT_UNKNOWN_D, 32),
En1545FixedInteger(En1545Subscription.CONTRACT_UNKNOWN_E, 32)
)
// TODO: parse locations?
)
}
}
| gpl-3.0 | 6c62dcf309692f1af6011899b855e4c4 | 44.273973 | 102 | 0.67292 | 4.41255 | false | false | false | false |
madisp/agp-tweeter | src/main/java/pink/madis/agptweeter/store/stores.kt | 1 | 2708 | package pink.madis.agptweeter.store
import java.io.IOException
import java.nio.file.Files
import java.nio.file.Path
import com.amazonaws.services.dynamodbv2.document.Item
import com.amazonaws.services.dynamodbv2.document.Table
import com.amazonaws.services.dynamodbv2.document.spec.GetItemSpec
import com.squareup.moshi.Moshi
import pink.madis.agptweeter.StoredVersions
import kotlin.text.Charsets.UTF_8
/**
* High level abstraction of a simple key-value store.
*/
interface Store {
/**
* reads an item from the store. Key has to be latin1 A-Za-z0-9-_
*/
@Throws(IOException::class) fun read(key: String): String?
/**
* writes an item into the store. Key has to be latin1 A-Za-z0-9-_
*/
@Throws(IOException::class) fun write(key: String, value: String)
}
/**
* A dumb key-value store that keeps everything in memory. Useful for testing.
*/
class MemStore: Store {
private val mem = HashMap<String, String>()
override fun read(key: String): String? = mem[key]
override fun write(key: String, value: String) {
mem[key] = value
}
}
/**
* A dumb key-value store that maps to files in a folder.
*/
class FileStore(private val basePath: Path): Store {
override fun read(key: String): String? {
val f = basePath.resolve(key)
return if (Files.exists(f)) Files.readAllBytes(f).toString(UTF_8) else null
}
override fun write(key: String, value: String) {
val f = basePath.resolve(key)
Files.createDirectories(f.parent)
Files.write(f, value.toByteArray(UTF_8))
}
override fun toString() = "local_files ($basePath)"
}
const val DYNAMO_PRIMARY_KEY = "coords"
const val DYNAMO_ATTRIBUTE_NAME = "versions"
/**
* A store backed by AWS DynamoDB
*/
class DynamoStore(private val db: Table): Store {
override fun read(key: String): String? {
val spec = GetItemSpec().withPrimaryKey(DYNAMO_PRIMARY_KEY, key).withConsistentRead(true)
val item: Item? = db.getItem(spec)
return item?.getString(DYNAMO_ATTRIBUTE_NAME)
}
override fun write(key: String, value: String) {
db.putItem(Item().withPrimaryKey(DYNAMO_PRIMARY_KEY, key).withString(DYNAMO_ATTRIBUTE_NAME, value))
}
override fun toString() = "dynamo (table ${db.tableName})"
}
/**
* A specific class that stores versions
*/
class VersionsStore(backingStore: Store, moshi: Moshi) {
private val store by lazy { migrate(backingStore, moshi) }
private val adapter = moshi.adapter(StoredVersions::class.java)
fun versions(key: String): StoredVersions {
return store.read(key)?.let { adapter.fromJson(it) } ?: StoredVersions(emptySet(), emptyList())
}
fun store(key: String, versions: StoredVersions) {
store.write(key, adapter.toJson(versions))
}
} | mit | 16c08f27d203442bfe6be6243d12d6d0 | 28.129032 | 103 | 0.712703 | 3.46735 | false | false | false | false |
GunoH/intellij-community | plugins/github/src/org/jetbrains/plugins/github/pullrequest/ui/toolwindow/GHPRToolWindowTabComponentControllerImpl.kt | 2 | 7185 | // 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.github.pullrequest.ui.toolwindow
import git4idea.remote.hosting.knownRepositories
import com.intellij.collaboration.ui.CollaborationToolsUIUtil
import com.intellij.ide.DataManager
import com.intellij.openapi.Disposable
import com.intellij.openapi.actionSystem.ActionManager
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.ClearableLazyValue
import com.intellij.openapi.util.Disposer
import com.intellij.ui.CollectionListModel
import com.intellij.ui.components.panels.Wrapper
import com.intellij.util.IJSwingUtilities
import com.intellij.util.ui.UIUtil
import org.jetbrains.annotations.Nls
import org.jetbrains.plugins.github.api.data.pullrequest.GHPullRequestShort
import org.jetbrains.plugins.github.i18n.GithubBundle
import org.jetbrains.plugins.github.pullrequest.action.GHPRActionKeys
import org.jetbrains.plugins.github.pullrequest.config.GithubPullRequestsProjectUISettings
import org.jetbrains.plugins.github.pullrequest.data.GHListLoader
import org.jetbrains.plugins.github.pullrequest.data.GHPRDataContext
import org.jetbrains.plugins.github.pullrequest.data.GHPRIdentifier
import org.jetbrains.plugins.github.pullrequest.ui.toolwindow.create.GHPRCreateComponentHolder
import org.jetbrains.plugins.github.ui.util.GHUIUtil
import org.jetbrains.plugins.github.util.GHGitRepositoryMapping
import org.jetbrains.plugins.github.util.GHHostedRepositoriesManager
import javax.swing.JComponent
internal class GHPRToolWindowTabComponentControllerImpl(
private val project: Project,
private val repositoryManager: GHHostedRepositoriesManager,
private val projectSettings: GithubPullRequestsProjectUISettings,
private val dataContext: GHPRDataContext,
private val wrapper: Wrapper,
private val parentDisposable: Disposable,
initialView: GHPRToolWindowViewType,
private val onTitleChange: (@Nls String) -> Unit
) : GHPRToolWindowTabComponentController {
private val listComponent by lazy { createListPanel() }
private val createComponentHolder = ClearableLazyValue.create {
GHPRCreateComponentHolder(ActionManager.getInstance(), project, projectSettings, repositoryManager, dataContext, this,
parentDisposable)
}
override lateinit var currentView: GHPRToolWindowViewType
private var currentDisposable: Disposable? = null
private var currentPullRequest: GHPRIdentifier? = null
init {
when (initialView) {
GHPRToolWindowViewType.NEW -> createPullRequest(false)
else -> viewList(false)
}
DataManager.registerDataProvider(wrapper) { dataId ->
when {
GHPRActionKeys.PULL_REQUESTS_TAB_CONTROLLER.`is`(dataId) -> this
else -> null
}
}
}
override fun createPullRequest(requestFocus: Boolean) {
val allRepos = repositoryManager.knownRepositories.map(GHGitRepositoryMapping::repository)
onTitleChange(GithubBundle.message("tab.title.pull.requests.new",
GHUIUtil.getRepositoryDisplayName(allRepos,
dataContext.repositoryDataService.repositoryCoordinates)))
currentDisposable?.let { Disposer.dispose(it) }
currentPullRequest = null
currentView = GHPRToolWindowViewType.NEW
wrapper.setContent(createComponentHolder.value.component)
IJSwingUtilities.updateComponentTreeUI(wrapper)
if (requestFocus) {
CollaborationToolsUIUtil.focusPanel(wrapper.targetComponent)
}
}
override fun resetNewPullRequestView() {
createComponentHolder.value.resetModel()
}
override fun viewList(requestFocus: Boolean) {
val allRepos = repositoryManager.knownRepositories.map(GHGitRepositoryMapping::repository)
onTitleChange(GithubBundle.message("tab.title.pull.requests.at",
GHUIUtil.getRepositoryDisplayName(allRepos,
dataContext.repositoryDataService.repositoryCoordinates)))
currentDisposable?.let { Disposer.dispose(it) }
currentPullRequest = null
currentView = GHPRToolWindowViewType.LIST
wrapper.setContent(listComponent)
IJSwingUtilities.updateComponentTreeUI(wrapper)
if (requestFocus) {
CollaborationToolsUIUtil.focusPanel(wrapper.targetComponent)
}
}
override fun refreshList() {
dataContext.listLoader.reset()
dataContext.repositoryDataService.resetData()
}
override fun viewPullRequest(id: GHPRIdentifier, requestFocus: Boolean, onShown: ((GHPRViewComponentController?) -> Unit)?) {
onTitleChange(GithubBundle.message("pull.request.num", id.number))
if (currentPullRequest != id) {
currentDisposable?.let { Disposer.dispose(it) }
currentDisposable = Disposer.newDisposable("Pull request component disposable").also {
Disposer.register(parentDisposable, it)
}
currentPullRequest = id
currentView = GHPRToolWindowViewType.DETAILS
val pullRequestComponent = GHPRViewComponentFactory(ActionManager.getInstance(), project, dataContext, this, id,
currentDisposable!!)
.create()
wrapper.setContent(pullRequestComponent)
wrapper.repaint()
}
if (onShown != null) onShown(UIUtil.getClientProperty(wrapper.targetComponent, GHPRViewComponentController.KEY))
if (requestFocus) {
CollaborationToolsUIUtil.focusPanel(wrapper.targetComponent)
}
}
override fun openPullRequestTimeline(id: GHPRIdentifier, requestFocus: Boolean) =
dataContext.filesManager.createAndOpenTimelineFile(id, requestFocus)
override fun openPullRequestDiff(id: GHPRIdentifier, requestFocus: Boolean) =
dataContext.filesManager.createAndOpenDiffFile(id, requestFocus)
private fun createListPanel(): JComponent {
val listLoader = dataContext.listLoader
val listModel = CollectionListModel(listLoader.loadedData)
listLoader.addDataListener(parentDisposable, object : GHListLoader.ListDataListener {
override fun onDataAdded(startIdx: Int) {
val loadedData = listLoader.loadedData
listModel.add(loadedData.subList(startIdx, loadedData.size))
}
override fun onDataUpdated(idx: Int) = listModel.setElementAt(listLoader.loadedData[idx], idx)
override fun onDataRemoved(data: Any) {
(data as? GHPullRequestShort)?.let { listModel.remove(it) }
}
override fun onAllDataRemoved() = listModel.removeAll()
})
val list = GHPRListComponentFactory(listModel).create(dataContext.avatarIconsProvider)
return GHPRListPanelFactory(project,
dataContext.repositoryDataService,
dataContext.securityService,
dataContext.listLoader,
dataContext.listUpdatesChecker,
dataContext.securityService.account,
parentDisposable)
.create(list, dataContext.avatarIconsProvider)
}
} | apache-2.0 | ac2a94e2611bd2ee0a477101e86f4ac8 | 44.194969 | 131 | 0.736674 | 5.229258 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/move/moveDeclarations/ui/KotlinSelectNestedClassRefactoringDialog.kt | 5 | 5056 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.idea.refactoring.move.moveDeclarations.ui
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.DialogWrapper
import com.intellij.psi.PsiDirectory
import com.intellij.psi.PsiElement
import com.intellij.refactoring.RefactoringBundle
import com.intellij.refactoring.util.RadioUpDownListener
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.psi.KtClass
import org.jetbrains.kotlin.psi.KtClassOrObject
import org.jetbrains.kotlin.psi.KtEnumEntry
import org.jetbrains.kotlin.psi.psiUtil.containingClassOrObject
import java.awt.BorderLayout
import javax.swing.*
internal class KotlinSelectNestedClassRefactoringDialog private constructor(
project: Project,
private val nestedClass: KtClassOrObject,
private val targetContainer: PsiElement?
) : DialogWrapper(project, true) {
private val moveToUpperLevelButton = JRadioButton()
private val moveMembersButton = JRadioButton()
init {
title = RefactoringBundle.message("select.refactoring.title")
init()
}
override fun createNorthPanel() = JLabel(RefactoringBundle.message("what.would.you.like.to.do"))
override fun getPreferredFocusedComponent() = moveToUpperLevelButton
override fun getDimensionServiceKey(): String {
return "#org.jetbrains.kotlin.idea.refactoring.move.moveTopLevelDeclarations.ui.KotlinSelectInnerOrMembersRefactoringDialog"
}
override fun createCenterPanel(): JComponent {
moveToUpperLevelButton.text = KotlinBundle.message("button.text.move.nested.class.0.to.upper.level", nestedClass.name.toString())
moveToUpperLevelButton.isSelected = true
moveMembersButton.text = KotlinBundle.message("button.text.move.nested.class.0.to.another.class", nestedClass.name.toString())
ButtonGroup().apply {
add(moveToUpperLevelButton)
add(moveMembersButton)
}
RadioUpDownListener(moveToUpperLevelButton, moveMembersButton)
return JPanel(BorderLayout()).apply {
val box = Box.createVerticalBox().apply {
add(Box.createVerticalStrut(5))
add(moveToUpperLevelButton)
add(moveMembersButton)
}
add(box, BorderLayout.CENTER)
}
}
fun getNextDialog(): DialogWrapper? {
return when {
moveToUpperLevelButton.isSelected -> MoveKotlinNestedClassesToUpperLevelDialog(nestedClass, targetContainer)
moveMembersButton.isSelected -> MoveKotlinNestedClassesDialog(nestedClass, targetContainer)
else -> null
}
}
companion object {
private fun MoveKotlinNestedClassesToUpperLevelDialog(
nestedClass: KtClassOrObject,
targetContainer: PsiElement?
): MoveKotlinNestedClassesToUpperLevelDialog? {
val outerClass = nestedClass.containingClassOrObject ?: return null
val newTarget = targetContainer
?: outerClass.containingClassOrObject
?: outerClass.containingFile.let { it.containingDirectory ?: it }
return MoveKotlinNestedClassesToUpperLevelDialog(nestedClass.project, nestedClass, newTarget)
}
private fun MoveKotlinNestedClassesDialog(
nestedClass: KtClassOrObject,
targetContainer: PsiElement?
): MoveKotlinNestedClassesDialog {
return MoveKotlinNestedClassesDialog(
nestedClass.project,
listOf(nestedClass),
nestedClass.containingClassOrObject!!,
targetContainer as? KtClassOrObject ?: nestedClass.containingClassOrObject!!,
targetContainer as? PsiDirectory,
null
)
}
fun chooseNestedClassRefactoring(nestedClass: KtClassOrObject, targetContainer: PsiElement?) {
val project = nestedClass.project
val dialog = when {
targetContainer.isUpperLevelFor(nestedClass) -> MoveKotlinNestedClassesToUpperLevelDialog(nestedClass, targetContainer)
nestedClass is KtEnumEntry -> return
else -> {
val selectionDialog =
KotlinSelectNestedClassRefactoringDialog(
project,
nestedClass,
targetContainer
)
selectionDialog.show()
if (selectionDialog.exitCode != OK_EXIT_CODE) return
selectionDialog.getNextDialog() ?: return
}
}
dialog?.show()
}
private fun PsiElement?.isUpperLevelFor(nestedClass: KtClassOrObject) =
this != null && this !is KtClassOrObject && this !is PsiDirectory ||
nestedClass is KtClass && nestedClass.isInner()
}
} | apache-2.0 | 4db25db7c967955fcee7c53d618bdded | 40.793388 | 137 | 0.670293 | 6.196078 | false | false | false | false |
AsamK/TextSecure | app/src/main/java/org/thoughtcrime/securesms/notifications/v2/NotificationStateV2.kt | 1 | 3498 | package org.thoughtcrime.securesms.notifications.v2
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import org.thoughtcrime.securesms.notifications.DeleteNotificationReceiver
import org.thoughtcrime.securesms.notifications.MarkReadReceiver
import org.thoughtcrime.securesms.notifications.NotificationIds
import org.thoughtcrime.securesms.recipients.Recipient
/**
* Hold all state for notifications for all conversations.
*/
data class NotificationStateV2(val conversations: List<NotificationConversation>, val muteFilteredMessages: List<FilteredMessage>, val profileFilteredMessages: List<FilteredMessage>) {
val threadCount: Int = conversations.size
val isEmpty: Boolean = conversations.isEmpty()
val messageCount: Int by lazy {
conversations.fold(0) { messageCount, conversation ->
messageCount + conversation.messageCount
}
}
val notificationItems: List<NotificationItemV2> by lazy {
conversations.map { it.notificationItems }
.flatten()
.sorted()
}
val notificationIds: Set<Int> by lazy {
conversations.map { it.notificationId }
.toSet()
}
val mostRecentNotification: NotificationItemV2?
get() = notificationItems.lastOrNull()
val mostRecentSender: Recipient?
get() = mostRecentNotification?.individualRecipient
fun getNonVisibleConversation(visibleThread: ConversationId?): List<NotificationConversation> {
return conversations.filterNot { it.thread == visibleThread }
}
fun getConversation(conversationId: ConversationId): NotificationConversation? {
return conversations.firstOrNull { it.thread == conversationId }
}
fun getDeleteIntent(context: Context): PendingIntent? {
val ids = LongArray(messageCount)
val mms = BooleanArray(ids.size)
val threads: MutableList<ConversationId> = mutableListOf()
conversations.forEach { conversation ->
threads += conversation.thread
conversation.notificationItems.forEachIndexed { index, notificationItem ->
ids[index] = notificationItem.id
mms[index] = notificationItem.isMms
}
}
val intent = Intent(context, DeleteNotificationReceiver::class.java)
.setAction(DeleteNotificationReceiver.DELETE_NOTIFICATION_ACTION)
.putExtra(DeleteNotificationReceiver.EXTRA_IDS, ids)
.putExtra(DeleteNotificationReceiver.EXTRA_MMS, mms)
.putParcelableArrayListExtra(DeleteNotificationReceiver.EXTRA_THREADS, ArrayList(threads))
.makeUniqueToPreventMerging()
return PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT)
}
fun getMarkAsReadIntent(context: Context): PendingIntent? {
val intent = Intent(context, MarkReadReceiver::class.java).setAction(MarkReadReceiver.CLEAR_ACTION)
.putParcelableArrayListExtra(MarkReadReceiver.THREADS_EXTRA, ArrayList(conversations.map { it.thread }))
.putExtra(MarkReadReceiver.NOTIFICATION_ID_EXTRA, NotificationIds.MESSAGE_SUMMARY)
.makeUniqueToPreventMerging()
return PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT)
}
fun getThreadsWithMostRecentNotificationFromSelf(): Set<ConversationId> {
return conversations.filter { it.mostRecentNotification.individualRecipient.isSelf }
.map { it.thread }
.toSet()
}
data class FilteredMessage(val id: Long, val isMms: Boolean)
companion object {
val EMPTY = NotificationStateV2(emptyList(), emptyList(), emptyList())
}
}
| gpl-3.0 | 216b2f4f25d9056a9e4385562e05d4b8 | 36.612903 | 184 | 0.765294 | 4.906031 | false | false | false | false |
milosmns/Timecrypt | Android/app/src/main/java/co/timecrypt/android/activities/CreateMessageActivity.kt | 1 | 8231 | package co.timecrypt.android.activities
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.support.v4.view.ViewPager
import android.support.v7.app.AppCompatActivity
import android.text.Editable
import android.util.Log
import android.view.View
import android.view.inputmethod.InputMethodManager
import android.widget.ImageView
import android.widget.Toast
import co.timecrypt.android.R
import co.timecrypt.android.helpers.OnMessageChangedListener
import co.timecrypt.android.helpers.PageChangeListenerAdapter
import co.timecrypt.android.helpers.TextWatcherAdapter
import co.timecrypt.android.pages.SwipeAdapter
import co.timecrypt.android.v2.api.TimecryptController
import co.timecrypt.android.v2.api.TimecryptMessage
import kotlinx.android.synthetic.main.activity_create_message.*
/**
* An activity that handles creation of new Timecrypt messages.
*/
class CreateMessageActivity : AppCompatActivity(), View.OnClickListener, OnMessageChangedListener {
@Suppress("PrivatePropertyName")
private val TAG = CreateMessageActivity::class.simpleName!!
private companion object {
const val KEY_MESSAGE = "TIMECRYPT_MESSAGE"
}
private var message: TimecryptMessage = TimecryptMessage("")
private var swipeAdapter: SwipeAdapter? = null
private var lastSelected: Int = 0
private var tabs: List<ImageView> = emptyList()
private var titles: List<Int> = emptyList()
private var controller: TimecryptController? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_create_message)
// initialize tab view collections
tabs = listOf(tabText, tabViews, tabDestructDate, tabDelivery)
titles = listOf(R.string.title_edit_hint, R.string.title_views, R.string.title_destruct_date, R.string.title_delivery)
// set up the controller instance and prepare the message
controller = TimecryptController(TimecryptController.Companion.DEFAULT_API_URL)
message = createMessage(intent)
// set up the swipe pager
swipeAdapter = SwipeAdapter(this, message, supportFragmentManager)
viewPager.adapter = swipeAdapter
viewPager.addOnPageChangeListener(pageChangeListener)
viewPager.offscreenPageLimit = tabs.size - 1
viewPager.swipeEnabled = false
// set up tab click listeners
tabs.forEachIndexed { i, view ->
view.setOnClickListener {
viewPager.setCurrentItem(i, true)
}
}
// all is done, prepare the initial state of UI
titleEdit.addTextChangedListener(titleChangeListener)
listOf(titleLogo, buttonCreate, buttonCancel).forEach { it.setOnClickListener(this) }
switchTabSelection(0)
}
override fun onNewIntent(intent: Intent?) {
super.onNewIntent(intent)
message = createMessage(intent)
swipeAdapter?.message = message
}
private fun createMessage(intent: Intent?): TimecryptMessage {
if (Intent.ACTION_SEND == intent?.action && intent.type?.startsWith("text/", true) == true) {
// this was a share action from outside
return TimecryptMessage(intent.getStringExtra(Intent.EXTRA_TEXT) ?: "")
}
// regular startup, just load a new empty message
return TimecryptMessage("")
}
override fun onSaveInstanceState(outState: Bundle?) {
outState?.putParcelable(KEY_MESSAGE, message)
super.onSaveInstanceState(outState)
}
override fun onRestoreInstanceState(savedInstanceState: Bundle?) {
super.onRestoreInstanceState(savedInstanceState)
val readMessage = savedInstanceState?.getParcelable<TimecryptMessage>(KEY_MESSAGE)
Log.i(TAG, "Restoring [$readMessage] from instance state")
message = readMessage ?: createMessage(intent)
swipeAdapter?.message = message
}
private val pageChangeListener = object : PageChangeListenerAdapter() {
override fun onPageScrollStateChanged(state: Int) {
if (state == ViewPager.SCROLL_STATE_IDLE) {
if (viewPager.currentItem != lastSelected) {
// update title and hide keyboard
if (viewPager.currentItem == 0) {
titleEdit.isEnabled = true
titleEdit.setText(message.title)
titleEdit.addTextChangedListener(titleChangeListener)
} else {
currentFocus?.let {
val inputManager = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
inputManager.hideSoftInputFromWindow(it.windowToken, 0)
}
titleEdit.removeTextChangedListener(titleChangeListener)
titleEdit.isEnabled = false
titleEdit.setText(titles[viewPager.currentItem])
}
// update tab selection
switchTabSelection(viewPager.currentItem)
}
}
}
}
private val titleChangeListener = object : TextWatcherAdapter() {
override fun afterTextChanged(text: Editable) {
message.title = text.toString()
}
}
override fun onClick(view: View) {
when (view.id) {
buttonCreate.id -> {
progressOverlay.visibility = View.VISIBLE
controller?.create(this, message, createOperationListener)
}
buttonCancel.id -> stopCreating()
titleLogo.id -> startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(TimecryptController.Companion.TIMECRYPT_URL)))
}
}
/**
* Used to listen for changes from the [TimecryptController.create] operation.
*/
private val createOperationListener = object : TimecryptController.CreateCompletedListener {
override fun onCreateCompleted(id: String) {
progressOverlay.visibility = View.GONE
// send info to the link viewer activity
val messageInfo = Bundle(3)
val fullUrl = String.format(TimecryptController.Companion.DEFAULT_MESSAGE_URL, id)
messageInfo.putString(LinkDisplayActivity.KEY_URL, fullUrl)
messageInfo.putString(LinkDisplayActivity.KEY_DATE, message.destructDate!!.toString())
messageInfo.putInt(LinkDisplayActivity.KEY_VIEWS, message.views)
val intent = Intent(this@CreateMessageActivity, LinkDisplayActivity::class.java)
intent.putExtras(messageInfo)
startActivity(intent)
finish()
}
override fun onCreateFailed(message: String) {
Log.e(TAG, message)
Toast.makeText(this@CreateMessageActivity, R.string.message_not_created, Toast.LENGTH_LONG).show()
progressOverlay.visibility = View.GONE
}
}
/**
* Switches selection highlight for tabs on top.
*/
private fun switchTabSelection(current: Int) {
tabs[lastSelected].setBackgroundResource(R.drawable.icon_background)
tabs[current].setBackgroundResource(R.drawable.icon_background_active)
tabs[lastSelected].isSelected = false
tabs[current].isSelected = true
lastSelected = current
}
override fun onTextInvalidated(empty: Boolean) {
titleEdit.visibility = if (empty) View.GONE else View.VISIBLE
buttonCreate.visibility = if (empty) View.GONE else View.VISIBLE
tabsContainer.visibility = if (empty) View.GONE else View.VISIBLE
viewPager.swipeEnabled = !empty
}
override fun onStop() {
super.onStop()
stopCreating()
}
private fun stopCreating() {
controller?.stopAll()
progressOverlay.visibility = View.GONE
}
override fun onDestroy() {
super.onDestroy()
controller = null
titleEdit.removeTextChangedListener(titleChangeListener)
viewPager.removeOnPageChangeListener(pageChangeListener)
swipeAdapter?.cleanup()
}
}
| apache-2.0 | 61fa508a7b1b0355390700d77f9402cd | 38.572115 | 126 | 0.667477 | 5.157268 | false | false | false | false |
himikof/intellij-rust | src/main/kotlin/org/rust/lang/core/resolve/ref/RsPathReferenceImpl.kt | 1 | 3197 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.lang.core.resolve.ref
import com.intellij.psi.PsiElement
import org.rust.lang.core.psi.RsPath
import org.rust.lang.core.psi.RsTraitItem
import org.rust.lang.core.psi.ext.RsCompositeElement
import org.rust.lang.core.psi.ext.RsGenericDeclaration
import org.rust.lang.core.psi.ext.typeParameters
import org.rust.lang.core.resolve.ImplLookup
import org.rust.lang.core.resolve.collectCompletionVariants
import org.rust.lang.core.resolve.collectResolveVariants
import org.rust.lang.core.resolve.processPathResolveVariants
import org.rust.lang.core.types.BoundElement
import org.rust.lang.core.types.ty.*
import org.rust.lang.core.types.type
class RsPathReferenceImpl(
element: RsPath
) : RsReferenceBase<RsPath>(element),
RsReference {
override val RsPath.referenceAnchor: PsiElement get() = referenceNameElement
override fun resolveInner(): List<BoundElement<RsCompositeElement>> {
val lookup = ImplLookup.relativeTo(element)
val result = collectResolveVariants(element.referenceName) {
processPathResolveVariants(lookup, element, false, it)
}
val typeArguments: List<Ty>? = run {
val inAngles = element.typeArgumentList
val fnSugar = element.valueParameterList
when {
inAngles != null -> inAngles.typeReferenceList.map { it.type }
fnSugar != null -> listOf(
TyTuple(fnSugar.valueParameterList.map { it.typeReference?.type ?: TyUnknown })
)
else -> null
}
}
val outputArg = element.retType?.typeReference?.type
return result.map { boundElement ->
val (element, subst) = boundElement.downcast<RsGenericDeclaration>() ?: return@map boundElement
val assocTypes = run {
if (element is RsTraitItem) {
val aliases = element.associatedTypesTransitively
.mapNotNull { it.type as? TyTypeParameter }
.associateBy { it }
val outputParam = lookup.fnOutputParam
return@run aliases + if (outputArg != null && outputParam != null) {
mapOf(outputParam to outputArg)
} else {
emptySubstitution
}
}
emptySubstitution
}
val parameters = element.typeParameters.map { TyTypeParameter.named(it) }
BoundElement(element,
subst
+ (if (typeArguments != null) parameters.zip(typeArguments).toMap() else parameters.associateBy { it })
+ assocTypes
)
}
}
override fun getVariants(): Array<out Any> =
collectCompletionVariants { processPathResolveVariants(ImplLookup.relativeTo(element), element, true, it) }
override fun isReferenceTo(element: PsiElement): Boolean {
val target = resolve()
return element.manager.areElementsEquivalent(target, element)
}
}
| mit | 35124b7b564f89c99fd43925810b2b54 | 36.174419 | 123 | 0.631217 | 4.903374 | false | false | false | false |
ktorio/ktor | ktor-client/ktor-client-plugins/ktor-client-logging/common/src/io/ktor/client/plugins/logging/LoggedContent.kt | 1 | 983 | /*
* Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license.
*/
package io.ktor.client.plugins.logging
import io.ktor.http.*
import io.ktor.http.content.*
import io.ktor.util.*
import io.ktor.utils.io.*
internal class LoggedContent(
private val originalContent: OutgoingContent,
private val channel: ByteReadChannel
) : OutgoingContent.ReadChannelContent() {
override val contentType: ContentType? = originalContent.contentType
override val contentLength: Long? = originalContent.contentLength
override val status: HttpStatusCode? = originalContent.status
override val headers: Headers = originalContent.headers
override fun <T : Any> getProperty(key: AttributeKey<T>): T? = originalContent.getProperty(key)
override fun <T : Any> setProperty(key: AttributeKey<T>, value: T?) =
originalContent.setProperty(key, value)
override fun readFrom(): ByteReadChannel = channel
}
| apache-2.0 | f2a5cb6612c4adefb1bdda748d9d16ec | 34.107143 | 118 | 0.752798 | 4.349558 | false | false | false | false |
Apolline-Lille/apolline-android | app/src/main/java/science/apolline/utils/CustomMarkerView.kt | 1 | 1677 | package science.apolline.utils
import android.content.Context
import com.github.mikephil.charting.components.MarkerView
import com.github.mikephil.charting.data.Entry
import com.github.mikephil.charting.highlight.Highlight
import com.github.mikephil.charting.utils.MPPointF
import kotlinx.android.synthetic.main.graph_custom_marker.view.*
import java.text.DateFormat
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale
class CustomMarkerView(context: Context, layoutResource: Int, private val referenceTimestamp: Long // minimum timestamp in your data set
) : MarkerView(context, layoutResource) {
private val mDataFormat: DateFormat
private val mDate: Date
private var mOffset: MPPointF? = null
init {
this.mDataFormat = SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.ENGLISH)
this.mDate = Date()
}
// callbacks everytime the MarkerView is redrawn, can be used to update the
// content (user-interface)
override fun refreshContent(e: Entry?, highlight: Highlight?) {
val currentTimestamp = e!!.x.toInt() + referenceTimestamp
tvContent.text = String.format("%s at %s", e.y, getTimedate(currentTimestamp))
super.refreshContent(e, highlight)
}
override fun getOffset(): MPPointF {
if (mOffset == null)
mOffset = MPPointF((-(width / 2)).toFloat(), (-height).toFloat())
return mOffset as MPPointF
}
private fun getTimedate(timestamp: Long): String {
try {
mDate.time = timestamp * 1000
return mDataFormat.format(mDate)
} catch (ex: Exception) {
return "xx"
}
}
} | gpl-3.0 | 06ef3de9813b517112ccbc741d6bd21f | 31.901961 | 137 | 0.694097 | 4.15099 | false | false | false | false |
dbrant/apps-android-wikipedia | app/src/main/java/org/wikipedia/search/SearchActivity.kt | 1 | 1719 | package org.wikipedia.search
import android.content.Context
import android.content.Intent
import org.wikipedia.Constants
import org.wikipedia.Constants.InvokeSource
import org.wikipedia.WikipediaApp
import org.wikipedia.activity.SingleFragmentActivity
import org.wikipedia.analytics.IntentFunnel
import org.wikipedia.util.log.L
import java.lang.RuntimeException
class SearchActivity : SingleFragmentActivity<SearchFragment>() {
public override fun createFragment(): SearchFragment {
var source = intent.getSerializableExtra(Constants.INTENT_EXTRA_INVOKE_SOURCE) as InvokeSource?
if (source == null) {
when {
Intent.ACTION_SEND == intent.action -> { source = InvokeSource.INTENT_SHARE }
Intent.ACTION_PROCESS_TEXT == intent.action -> { source = InvokeSource.INTENT_PROCESS_TEXT }
else -> {
source = InvokeSource.INTENT_UNKNOWN
L.logRemoteErrorIfProd(RuntimeException("Unknown intent when launching SearchActivity: " + intent.action.orEmpty()))
}
}
}
return SearchFragment.newInstance(source, intent.getStringExtra(QUERY_EXTRA))
}
companion object {
const val QUERY_EXTRA = "query"
@JvmStatic
fun newIntent(context: Context, source: InvokeSource, query: String?): Intent {
if (source == InvokeSource.WIDGET) {
IntentFunnel(WikipediaApp.getInstance()).logSearchWidgetTap()
}
return Intent(context, SearchActivity::class.java)
.putExtra(Constants.INTENT_EXTRA_INVOKE_SOURCE, source)
.putExtra(QUERY_EXTRA, query)
}
}
}
| apache-2.0 | 329f3c53b30cffb3beb53a87913cf54b | 39.928571 | 136 | 0.661431 | 5.055882 | false | false | false | false |
dahlstrom-g/intellij-community | platform/vcs-log/impl/src/com/intellij/vcs/log/impl/VcsLogToolWindowTabsWatcher.kt | 9 | 6704 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.vcs.log.impl
import com.intellij.openapi.Disposable
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.wm.ToolWindow
import com.intellij.openapi.wm.ToolWindowManager
import com.intellij.openapi.wm.ToolWindowManager.Companion.getInstance
import com.intellij.openapi.wm.ex.ToolWindowManagerListener
import com.intellij.ui.content.Content
import com.intellij.ui.content.ContentManagerEvent
import com.intellij.ui.content.ContentManagerListener
import com.intellij.ui.content.TabbedContent
import com.intellij.vcs.log.impl.PostponableLogRefresher.VcsLogWindow
import com.intellij.vcs.log.impl.VcsLogToolWindowTabsWatcher.VcsLogToolWindowTab
import com.intellij.vcs.log.ui.VcsLogUiEx
import org.jetbrains.annotations.NonNls
import java.beans.PropertyChangeEvent
import java.beans.PropertyChangeListener
import java.util.*
internal class VcsLogToolWindowTabsWatcher(private val project: Project,
private val toolWindowId: String,
parentDisposable: Disposable) : VcsLogTabsWatcherExtension<VcsLogToolWindowTab> {
private val mainDisposable = Disposer.newDisposable()
private val toolwindowListenerDisposable = Disposer.newDisposable()
private var tabSelectedCallback: (String) -> Unit = {}
private val toolWindow: ToolWindow?
get() = getInstance(project).getToolWindow(toolWindowId)
init {
val connection = project.messageBus.connect(mainDisposable)
connection.subscribe(ToolWindowManagerListener.TOPIC, MyToolWindowManagerListener())
installContentListeners()
Disposer.register(parentDisposable, mainDisposable)
Disposer.register(parentDisposable, toolwindowListenerDisposable)
}
override fun setTabSelectedCallback(callback: (String) -> Unit) {
tabSelectedCallback = callback
}
override fun createLogTab(ui: VcsLogUiEx, isClosedOnDispose: Boolean): VcsLogToolWindowTab {
return VcsLogToolWindowTab(ui, isClosedOnDispose)
}
override fun isOwnerOf(tab: VcsLogWindow): Boolean {
return tab is VcsLogToolWindowTab
}
override fun closeTabs(tabs: List<VcsLogWindow>) {
toolWindow?.let { window ->
val tabIds = tabs.filterIsInstance(VcsLogToolWindowTab::class.java).filter { it.isClosedOnDispose }.map { it.id }
for (tabId in tabIds) {
val closed = VcsLogContentUtil.closeLogTab(window.contentManager, tabId)
LOG.assertTrue(closed, """
Could not find content component for tab ${tabId}
Existing content: ${Arrays.toString(window.contentManager.contents)}
Tabs to close: $tabIds
""".trimIndent())
}
}
}
private fun installContentListeners() {
ApplicationManager.getApplication().assertIsDispatchThread()
toolWindow?.let { window ->
addContentManagerListener(window, object : VcsLogTabsListener(project, window, mainDisposable) {
override fun selectionChanged(tabId: String) {
tabSelectedCallback(tabId)
}
}, toolwindowListenerDisposable)
}
}
private fun removeContentListeners() {
Disposer.dispose(toolwindowListenerDisposable)
}
inner class VcsLogToolWindowTab(ui: VcsLogUiEx, val isClosedOnDispose: Boolean) : VcsLogWindow(ui) {
override fun isVisible(): Boolean {
val selectedTab = getSelectedToolWindowTabId(toolWindow)
return id == selectedTab
}
override fun toString(): @NonNls String {
return "VcsLogToolWindowTab '$id'"
}
}
private inner class MyToolWindowManagerListener : ToolWindowManagerListener {
override fun toolWindowsRegistered(ids: List<String>, toolWindowManager: ToolWindowManager) {
if (ids.contains(toolWindowId)) {
installContentListeners()
}
}
override fun toolWindowUnregistered(id: String, toolWindow: ToolWindow) {
if (id == toolWindowId) {
removeContentListeners()
}
}
}
private abstract class VcsLogTabsListener(project: Project, private val window: ToolWindow, disposable: Disposable) :
ToolWindowManagerListener, PropertyChangeListener, ContentManagerListener {
init {
project.messageBus.connect(disposable).subscribe(ToolWindowManagerListener.TOPIC, this)
Disposer.register(disposable) {
val contentManager = window.contentManagerIfCreated ?: return@register
for (content in contentManager.contents) {
(content as? TabbedContent)?.removePropertyChangeListener(this)
}
}
}
protected abstract fun selectionChanged(tabId: String)
private fun selectionChanged() {
getSelectedToolWindowTabId(window)?.let { selectionChanged(it) }
}
override fun selectionChanged(event: ContentManagerEvent) {
if (ContentManagerEvent.ContentOperation.add == event.operation) {
val tabId = VcsLogContentUtil.getId(event.content)
tabId?.let { selectionChanged(it) }
}
}
override fun contentAdded(event: ContentManagerEvent) {
val content = event.content
(content as? TabbedContent)?.addPropertyChangeListener(this)
}
override fun contentRemoved(event: ContentManagerEvent) {
val content = event.content
(content as? TabbedContent)?.removePropertyChangeListener(this)
}
override fun toolWindowShown(toolWindow: ToolWindow) {
if (window === toolWindow) selectionChanged()
}
override fun propertyChange(evt: PropertyChangeEvent) {
if (evt.propertyName == Content.PROP_COMPONENT) {
selectionChanged()
}
}
}
companion object {
private val LOG = Logger.getInstance(VcsLogToolWindowTabsWatcher::class.java)
private fun getSelectedToolWindowTabId(toolWindow: ToolWindow?): String? {
if (toolWindow == null || !toolWindow.isVisible) {
return null
}
val content = toolWindow.contentManager.selectedContent ?: return null
return VcsLogContentUtil.getId(content)
}
private fun addContentManagerListener(window: ToolWindow,
listener: ContentManagerListener,
disposable: Disposable) {
window.addContentManagerListener(listener)
Disposer.register(disposable) {
if (!window.isDisposed) {
window.contentManagerIfCreated?.removeContentManagerListener(listener)
}
}
}
}
} | apache-2.0 | 01af04b85ff9818ddf6c203304fd13dc | 36.668539 | 158 | 0.722703 | 5.113654 | false | false | false | false |
tomekby/miscellaneous | kotlin-game/android/app/src/main/java/pl/vot/tomekby/mathGame/domain/auth/DummyAuth.kt | 1 | 780 | package pl.vot.tomekby.mathGame.domain.auth
import org.jetbrains.anko.doAsync
import org.jetbrains.anko.uiThread
import pl.vot.tomekby.mathGame.EmptyCallback
/**
* Auth based on hardcoded data
*/
class DummyAuth : Auth {
companion object {
// Auth data
private const val validLogin = "wsb"
private const val validPassword = "wsb"
}
override fun login(username: String, password: String, onSuccess: EmptyCallback, onFailure: EmptyCallback) {
doAsync {
if (username == validLogin && password == validPassword) {
saveAuthData(username, password)
uiThread { onSuccess() }
} else {
uiThread { onFailure() }
}
}
}
} | mit | b05a1537f9596bdfe8500598c0afe64d | 26.962963 | 112 | 0.591026 | 4.40678 | false | false | false | false |
hkokocin/androidKit | library/src/main/java/com/github/hkokocin/androidkit/content/ResourcesKit.kt | 1 | 701 | package com.github.hkokocin.androidkit.content
import android.annotation.SuppressLint
import android.content.res.Resources
import com.github.hkokocin.androidkit.AndroidKit
@Suppress("DEPRECATION")
fun Resources.getColorInt(resourcesId: Int, theme: Resources.Theme? = null) =
AndroidKit.instance.getColorInt(this, resourcesId, theme)
interface ResourcesKit {
val sdkVersion: Int
@SuppressLint("NewApi")
@Suppress("DEPRECATION")
fun getColorInt(resources: Resources, resourcesId: Int, theme: Resources.Theme? = null) =
if (sdkVersion >= 23)
resources.getColor(resourcesId, theme)
else
resources.getColor(resourcesId)
} | mit | fd7b23fbfa2f12d3be57783014fe0e75 | 30.909091 | 93 | 0.714693 | 4.408805 | false | false | false | false |
dahlstrom-g/intellij-community | plugins/kotlin/core/tests/test/org/jetbrains/kotlin/IdeKotlinVersionTest.kt | 1 | 7721 | // 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
import org.jetbrains.kotlin.config.ApiVersion
import org.jetbrains.kotlin.config.LanguageVersion
import org.jetbrains.kotlin.idea.compiler.configuration.IdeKotlinVersion
import org.junit.Test
import kotlin.test.*
class IdeKotlinVersionTest {
@Test
fun testReleaseVersion() {
fun test(version: String, withBuildNumber: Boolean) = with (IdeKotlinVersion.get(version)) {
assertEquals(version, rawVersion)
assertEquals(KotlinVersion(1, 5, 10), kotlinVersion)
assertEquals(IdeKotlinVersion.Kind.Release, kind)
assertEquals(LanguageVersion.KOTLIN_1_5, languageVersion)
assertEquals(ApiVersion.KOTLIN_1_5, apiVersion)
assertEquals("1.5.10", baseVersion)
assertEquals("1.5.10", artifactVersion)
assertTrue(isRelease)
assertFalse(isPreRelease)
assertFalse(isDev)
assertFalse(isSnapshot)
if (withBuildNumber) assertNotNull(buildNumber) else assertNull(buildNumber)
}
test("1.5.10", withBuildNumber = false)
test("1.5.10-235", withBuildNumber = true)
test("1.5.10-release", withBuildNumber = false)
test("1.5.10-release-123", withBuildNumber = true)
test("1.5.10-Release-1", withBuildNumber = true)
}
@Test
fun testReleaseCandidateVersion() {
fun test(version: String, withBuildNumber: Boolean = false) = with (IdeKotlinVersion.get(version)) {
assertEquals(version, rawVersion)
assertEquals(KotlinVersion(1, 6, 0), kotlinVersion)
assertEquals(IdeKotlinVersion.Kind.ReleaseCandidate(1), kind)
assertEquals(LanguageVersion.KOTLIN_1_6, languageVersion)
assertEquals(ApiVersion.KOTLIN_1_6, apiVersion)
assertEquals("1.6.0", baseVersion)
assertEquals("1.6.0-RC", artifactVersion)
assertFalse(isRelease)
assertTrue(isPreRelease)
assertFalse(isDev)
assertFalse(isSnapshot)
if (withBuildNumber) assertNotNull(buildNumber) else assertNull(buildNumber)
}
test("1.6.0-RC")
test("1.6.0-RC-release")
test("1.6.0-RC-release-123", withBuildNumber = true)
}
@Test
fun testReleaseCandidate2Version() {
fun test(version: String) = with (IdeKotlinVersion.get(version)) {
assertEquals(version, rawVersion)
assertEquals(KotlinVersion(1, 6, 20), kotlinVersion)
assertEquals(IdeKotlinVersion.Kind.ReleaseCandidate(2), kind)
assertEquals(LanguageVersion.KOTLIN_1_6, languageVersion)
assertEquals(ApiVersion.KOTLIN_1_6, apiVersion)
assertEquals("1.6.20", baseVersion)
assertEquals("1.6.20-RC2", artifactVersion)
assertFalse(isRelease)
assertTrue(isPreRelease)
assertFalse(isDev)
assertFalse(isSnapshot)
}
test("1.6.20-RC2")
test("1.6.20-RC2-release")
test("1.6.20-RC2-release-123")
}
@Test
fun testMilestoneVersion() {
fun test(version: String, milestone: Int) = with (IdeKotlinVersion.get(version)) {
assertEquals(version, rawVersion)
assertEquals(KotlinVersion(1, 5, 30), kotlinVersion)
assertEquals(IdeKotlinVersion.Kind.Milestone(milestone), kind)
assertEquals(LanguageVersion.KOTLIN_1_5, languageVersion)
assertEquals(ApiVersion.KOTLIN_1_5, apiVersion)
assertEquals("1.5.30", baseVersion)
assertEquals("1.5.30-M${milestone}", artifactVersion)
assertFalse(isRelease)
assertTrue(isPreRelease)
assertFalse(isDev)
assertFalse(isSnapshot)
}
test("1.5.30-M1", milestone = 1)
test("1.5.30-M2-release", milestone = 2)
test("1.5.30-M2-release-123", milestone = 2)
test("1.5.30-M15-release-123", milestone = 15)
}
@Test
fun testEapVersion() {
fun test(version: String, eapNumber: Int) = with (IdeKotlinVersion.get(version)) {
assertEquals(version, rawVersion)
assertEquals(KotlinVersion(1, 5, 30), kotlinVersion)
assertEquals(IdeKotlinVersion.Kind.Eap(eapNumber), kind)
assertEquals(LanguageVersion.KOTLIN_1_5, languageVersion)
assertEquals(ApiVersion.KOTLIN_1_5, apiVersion)
assertEquals("1.5.30", baseVersion)
assertEquals("1.5.30-eap${if (eapNumber == 1) "" else eapNumber.toString()}", artifactVersion)
assertFalse(isRelease)
assertTrue(isPreRelease)
assertFalse(isDev)
assertFalse(isSnapshot)
}
test("1.5.30-eap", eapNumber = 1)
test("1.5.30-eap2-release", eapNumber = 2)
test("1.5.30-eap2-release-123", eapNumber = 2)
test("1.5.30-eap15-release-123", eapNumber = 15)
}
@Test
fun testBetaVersion() {
fun test(version: String, beta: Int) = with (IdeKotlinVersion.get(version)) {
assertEquals(version, rawVersion)
assertEquals(KotlinVersion(1, 5, 0), kotlinVersion)
assertEquals(IdeKotlinVersion.Kind.Beta(beta), kind)
assertEquals(LanguageVersion.KOTLIN_1_5, languageVersion)
assertEquals(ApiVersion.KOTLIN_1_5, apiVersion)
assertEquals("1.5.0", baseVersion)
assertEquals(if (beta == 1) "1.5.0-Beta" else "1.5.0-Beta$beta", artifactVersion)
assertFalse(isRelease)
assertTrue(isPreRelease)
assertFalse(isDev)
assertFalse(isSnapshot)
}
test("1.5.0-Beta", beta = 1)
test("1.5.0-Beta2-release", beta = 2)
test("1.5.0-BETA5-123", beta = 5)
test("1.5.0-beta15-release-123", beta = 15)
}
@Test
fun testDevVersion() {
fun test(version: String, artifactBuildSuffix: String) = with (IdeKotlinVersion.get(version)) {
assertEquals(version, rawVersion)
assertEquals(KotlinVersion(1, 6, 10), kotlinVersion)
assertEquals(IdeKotlinVersion.Kind.Dev, kind)
assertEquals(LanguageVersion.KOTLIN_1_6, languageVersion)
assertEquals(ApiVersion.KOTLIN_1_6, apiVersion)
assertEquals("1.6.10", baseVersion)
assertEquals("1.6.10-dev${artifactBuildSuffix}", artifactVersion)
assertFalse(isRelease)
assertTrue(isPreRelease)
assertTrue(isDev)
assertFalse(isSnapshot)
}
test("1.6.10-dev", artifactBuildSuffix = "")
test("1.6.10-dev-12", artifactBuildSuffix = "-12")
}
@Test
fun testSnapshotVersion() {
fun test(version: String, artifactBuildSuffix: String) = with (IdeKotlinVersion.get(version)) {
assertEquals(version, rawVersion)
assertEquals(KotlinVersion(1, 0, 0), kotlinVersion)
assertEquals(IdeKotlinVersion.Kind.Snapshot, kind)
assertEquals(LanguageVersion.KOTLIN_1_0, languageVersion)
assertEquals(ApiVersion.KOTLIN_1_0, apiVersion)
assertEquals("1.0.0", baseVersion)
assertEquals("1.0.0-SNAPSHOT${artifactBuildSuffix}", artifactVersion)
assertFalse(isRelease)
assertTrue(isPreRelease)
assertFalse(isDev)
assertTrue(isSnapshot)
}
test("1.0.0-snapshot", artifactBuildSuffix = "")
test("1.0.0-SNAPSHOT", artifactBuildSuffix = "")
test("1.0.0-SNAPSHOT-20", artifactBuildSuffix = "-20")
}
} | apache-2.0 | a4bcb7cae2e0078e14043e2b0fd79872 | 40.967391 | 120 | 0.626732 | 4.344963 | false | true | false | false |
mcdimus/mate-wp | src/main/kotlin/ee/mcdimus/matewp/service/OpSysServiceFactory.kt | 1 | 688 | package ee.mcdimus.matewp.service
/**
* @author Dmitri Maksimov
*/
object OpSysServiceFactory {
private enum class OS {
LINUX, WINDOWS
}
fun get() = when (detectOS()) {
OS.LINUX -> LinuxMateService()
OS.WINDOWS -> WindowsService()
}
private fun detectOS() = when (val osName = System.getProperty("os.name")) {
"Windows 7" -> OS.WINDOWS
"Linux" -> OS.LINUX
else -> makeGuess(osName)
}
private fun makeGuess(osName: String) = when {
osName.contains("windows", ignoreCase = true) -> OS.WINDOWS
osName.contains("linux", ignoreCase = true) -> OS.LINUX
else -> throw IllegalStateException("unsupported operating system: $osName")
}
}
| mit | e7e214140958b138289e3cd5e340dea6 | 22.724138 | 80 | 0.655523 | 3.822222 | false | false | false | false |
SirWellington/alchemy-arguments | src/test/java/tech/sirwellington/alchemy/arguments/assertions/StringAssertionsTest.kt | 1 | 17125 | /*
* Copyright © 2019. Sir Wellington.
* 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 tech.sirwellington.alchemy.arguments.assertions
import org.hamcrest.Matchers.notNullValue
import org.junit.Assert.assertThat
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import tech.sirwellington.alchemy.arguments.Arguments.checkThat
import tech.sirwellington.alchemy.arguments.failedAssertion
import tech.sirwellington.alchemy.arguments.illegalArgument
import tech.sirwellington.alchemy.arguments.nullPointer
import tech.sirwellington.alchemy.generator.AlchemyGenerator
import tech.sirwellington.alchemy.generator.NumberGenerators
import tech.sirwellington.alchemy.generator.NumberGenerators.Companion.doubles
import tech.sirwellington.alchemy.generator.NumberGenerators.Companion.integers
import tech.sirwellington.alchemy.generator.NumberGenerators.Companion.longs
import tech.sirwellington.alchemy.generator.NumberGenerators.Companion.negativeIntegers
import tech.sirwellington.alchemy.generator.NumberGenerators.Companion.positiveIntegers
import tech.sirwellington.alchemy.generator.NumberGenerators.Companion.smallPositiveIntegers
import tech.sirwellington.alchemy.generator.StringGenerators
import tech.sirwellington.alchemy.generator.StringGenerators.Companion.alphabeticStrings
import tech.sirwellington.alchemy.generator.StringGenerators.Companion.alphanumericStrings
import tech.sirwellington.alchemy.generator.StringGenerators.Companion.strings
import tech.sirwellington.alchemy.generator.StringGenerators.Companion.stringsFromFixedList
import tech.sirwellington.alchemy.generator.one
import tech.sirwellington.alchemy.test.junit.ThrowableAssertion.assertThrows
import tech.sirwellington.alchemy.test.junit.runners.AlchemyTestRunner
import tech.sirwellington.alchemy.test.junit.runners.Repeat
import java.lang.String.format
import java.util.regex.Pattern
/**
* @author SirWellington
*/
@Repeat(5000)
@RunWith(AlchemyTestRunner::class)
class StringAssertionsTest
{
@Before
fun setUp()
{
}
@Test
fun testEmptyString()
{
val instance = emptyString()
val badArguments = alphabeticStrings()
val goodArguments = stringsFromFixedList("", "")
Tests.runTests(instance, badArguments, goodArguments)
}
@Test
fun testStringWithLengthGreaterThan()
{
val minAccepted = one(integers(2, 10100))
val instance = stringWithLengthGreaterThan(minAccepted)
var badArguments = AlchemyGenerator<String> {
val length = one(integers(1, minAccepted))
one(alphabeticStrings(length))
}
val goodArguments = AlchemyGenerator<String> {
val length = minAccepted + one(smallPositiveIntegers())
one(alphabeticStrings(length))
}
Tests.runTests(instance, badArguments, goodArguments)
badArguments = strings(minAccepted)
Tests.runTests(instance, badArguments, goodArguments)
}
@Test
fun testStringWithLengthGreaterThanEdgeCases()
{
assertThrows { stringWithLengthGreaterThan(Integer.MAX_VALUE) }
.illegalArgument()
val badArgument = one(integers(Integer.MIN_VALUE, 1))
assertThrows { stringWithLengthGreaterThan(badArgument) }
.illegalArgument()
}
@Test
fun testStringWithLengthLessThan()
{
val upperBound = one(integers(2, 1000))
val instance = stringWithLengthLessThan(upperBound)
val badArguments = AlchemyGenerator {
val length = one(integers(upperBound + 1, upperBound * 2))
one(strings(length))
}
val goodArguments = AlchemyGenerator {
val length = one(integers(1, upperBound))
one(strings(length))
}
Tests.runTests(instance, badArguments, goodArguments)
}
@Test
fun testStringWithLengthLessThanEdgeCases()
{
val badArgument = one(integers(Integer.MIN_VALUE, 1))
assertThrows { stringWithLengthLessThan(badArgument) }
.illegalArgument()
}
@Test
fun testStringThatMatches()
{
val letter = one(alphabeticStrings()).substring(0, 1)
val pattern = Pattern.compile(".*$letter.*")
val instance = stringThatMatches(pattern)
val badArguments = AlchemyGenerator { alphabeticStrings().get().replace(letter.toRegex(), "") }
val goodArguments = AlchemyGenerator { alphabeticStrings().get() + letter }
Tests.runTests(instance, badArguments, goodArguments)
}
@Test
fun testStringThatMatchesEdgeCases()
{
assertThrows { stringThatMatches(null!!) }.nullPointer()
}
@Test
@Throws(Exception::class)
fun testNonEmptyString()
{
val instance = nonEmptyString()
assertThat(instance, notNullValue())
val arg = one(alphabeticStrings())
instance.check(arg)
assertThrows { instance.check("") }.failedAssertion()
assertThrows { instance.check(null) }.failedAssertion()
}
@Test
@Throws(Exception::class)
fun testStringWithLength()
{
assertThrows { stringWithLength(one(NumberGenerators.negativeIntegers())) }
.illegalArgument()
val expectedLength = one(integers(5, 25))
val instance = stringWithLength(expectedLength)
assertThat(instance, notNullValue())
Tests.checkForNullCase(instance)
val arg = one(alphabeticStrings(expectedLength))
instance.check(arg)
val tooShort = one(alphabeticStrings(expectedLength - 1))
assertThrows { instance.check(tooShort) }.failedAssertion()
val tooLong = one(strings(expectedLength + 1))
assertThrows { instance.check(tooLong) }.failedAssertion()
}
@Test
@Throws(Exception::class)
fun testStringWithLengthEdgeCases()
{
val badArgument = one(negativeIntegers())
assertThrows { stringWithLength(badArgument) }
.illegalArgument()
}
@Test
@Throws(Exception::class)
fun testStringWithLengthGreaterThanOrEqualToWithBadArgs()
{
val negativeNumber = one(negativeIntegers())
assertThrows { stringWithLengthGreaterThanOrEqualTo(negativeNumber) }
.illegalArgument()
}
@Test
@Throws(Exception::class)
fun testStringWithLengthGreaterThanOrEqualTo()
{
val expectedSize = one(integers(10, 100))
val instance = stringWithLengthGreaterThanOrEqualTo(expectedSize)
assertThat(instance, notNullValue())
Tests.checkForNullCase(instance)
val goodString = one(strings(expectedSize))
instance.check(goodString)
val amountToAdd = one(integers(1, 5))
val anotherGoodString = one(strings(expectedSize + amountToAdd))
instance.check(anotherGoodString)
val amountToSubtract = one(integers(1, 5))
val badString = one(strings(expectedSize - amountToSubtract))
assertThrows { instance.check(badString) }.failedAssertion()
}
@Test
@Throws(Exception::class)
fun testStringWithLengthLessThanOrEqualToWithBadArgs()
{
val negativeNumber = one(negativeIntegers())
assertThrows { stringWithLengthLessThanOrEqualTo(negativeNumber) }
.illegalArgument()
}
@Test
@Throws(Exception::class)
fun testStringWithLengthLessThanOrEqualTo()
{
val expectedSize = one(integers(5, 100))
val instance = stringWithLengthLessThanOrEqualTo(expectedSize)
assertThat(instance, notNullValue())
Tests.checkForNullCase(instance)
val goodStrings = strings(expectedSize)
val amountToAdd = one(integers(5, 10))
val badStrings = strings(expectedSize + amountToAdd)
Tests.runTests(instance, badStrings, goodStrings)
}
@Test
@Throws(Exception::class)
fun testStringWithNoWhitespace()
{
val instance = stringWithNoWhitespace()
assertThat(instance, notNullValue())
Tests.checkForNullCase(instance)
val goodStrings = alphabeticStrings()
val badStrings = AlchemyGenerator {
one(goodStrings) + one(stringsFromFixedList(" ", "\n", "\t")) + one(goodStrings)
}
Tests.runTests(instance, badStrings, goodStrings)
}
@Test
@Throws(Exception::class)
fun testStringWithLengthBetween()
{
val minimumLength = one(integers(10, 100))
val maximumLength = one(integers(minimumLength + 1, 1000))
val instance = stringWithLengthBetween(minimumLength, maximumLength)
assertThat(instance, notNullValue())
Tests.checkForNullCase(instance)
val tooShort = AlchemyGenerator {
//Sad cases
val stringTooShortLength = minimumLength - one(integers(1, 9))
val stringTooShort = one(strings(stringTooShortLength))
stringTooShort
}
val tooLong = AlchemyGenerator {
val stringTooLongLength = maximumLength + one(smallPositiveIntegers())
val stringTooLong = one(strings(stringTooLongLength))
stringTooLong
}
var goodStrings = AlchemyGenerator {
val length = one(integers(minimumLength, maximumLength))
one(strings(length))
}
Tests.runTests(instance, tooLong, goodStrings)
goodStrings = strings(minimumLength)
Tests.runTests(instance, tooShort, goodStrings)
}
@Test
@Throws(Exception::class)
fun testStringWithLengthBetweenEdgeCases()
{
val minimumLength = one(integers(10, 100))
val maximumLength = one(integers(minimumLength, 1000))
assertThrows { stringWithLengthBetween(maximumLength, minimumLength) }
.illegalArgument()
assertThrows { stringWithLengthBetween(-minimumLength, maximumLength) }
.illegalArgument()
}
@Test
fun testStringBeginningWith()
{
val string = one(strings(20))
val prefix = one(strings(4))
val instance = stringBeginningWith(prefix)
//Happy Cases
instance.check(prefix + string)
instance.check(prefix)
//Sad Cases
assertThrows { instance.check(null) }.failedAssertion()
assertThrows { instance.check(string) }.failedAssertion()
}
@Test
fun testStringBeginningWithEdgeCases()
{
assertThrows { stringBeginningWith(null!!) }.nullPointer()
assertThrows { stringBeginningWith("") }.illegalArgument()
}
@Test
fun testStringContaining()
{
val longString = one(strings(1000))
val substring = longString.substring(0, 100)
// Happy Case
stringContaining(substring)
.check(longString)
//Sad Cases
assertThrows { stringContaining("") }
.illegalArgument()
assertThrows { stringContaining(null!!) }.nullPointer()
val notSubstring = substring + one(StringGenerators.uuids())
assertThrows {
stringContaining(notSubstring).check(longString)
}.failedAssertion()
}
@Test
fun testAllUpperCaseString()
{
val allUpperCase = one(alphabeticStrings(50)).toUpperCase()
val oneLowerCaseCharacter = lowerCasedRandomCharacter(allUpperCase)
val instance = allUpperCaseString()
assertThat(instance, notNullValue())
instance.check(allUpperCase)
assertThrows { instance.check(oneLowerCaseCharacter) }.failedAssertion()
}
private fun lowerCasedRandomCharacter(string: String): String
{
val index = one(integers(0, string.length))
val character = string[index]
val builder = StringBuilder(string)
builder.replace(index, index + 1, character.toString().toLowerCase())
return builder.toString()
}
@Test
fun testAllLowerCaseString()
{
val allLowerCase = one(alphabeticStrings(50)).toLowerCase()
val oneUpperCaseCharacter = upperCaseRandomCharacter(allLowerCase)
val instance = allLowerCaseString()
assertThat(instance, notNullValue())
instance.check(allLowerCase)
assertThrows { instance.check(oneUpperCaseCharacter) }
.failedAssertion()
}
private fun upperCaseRandomCharacter(string: String): String
{
val index = one(integers(0, string.length))
val character = string[index]
val builder = StringBuilder(string)
builder.replace(index, index + 1, character.toString().toUpperCase())
return builder.toString()
}
@Test
fun testStringEndingWith()
{
//Edge Cases
assertThrows { stringEndingWith(null!!) }.nullPointer()
assertThrows { stringEndingWith("") }.illegalArgument()
//Happy Cases
val string = one(strings())
val suffix = randomSuffixFrom(string)
val instance = stringEndingWith(suffix)
assertThat(instance, notNullValue())
instance.check(string)
val anotherRandomString = one(strings())
assertThrows { instance.check(anotherRandomString) }.failedAssertion()
}
private fun randomSuffixFrom(string: String): String
{
val suffixStartIndex = one(integers(0, string.length / 2))
return string.substring(suffixStartIndex)
}
@Test
fun testAlphabeticString()
{
val instance = tech.sirwellington.alchemy.arguments.assertions.alphabeticString()
checkThat(instance, notNullValue())
val alphabetic = one(alphabeticStrings())
instance.check(alphabetic)
assertThrows { instance.check("") }.failedAssertion()
val alphanumeric = format("%s-%d", alphabetic, one(positiveIntegers()))
assertThrows { instance.check(alphanumeric) }.failedAssertion()
}
@Test
fun testAlphanumericString()
{
val instance = alphanumericString()
checkThat(instance, notNullValue())
val alphanumeric = one(StringGenerators.alphanumericStrings())
instance.check(alphanumeric)
val specialCharacters = alphanumeric + one(strings()) + "-!%$"
assertThrows { instance.check(specialCharacters) }.failedAssertion()
assertThrows { instance.check("") }
.failedAssertion()
}
@Test
fun testStringRepresentingInteger()
{
val instance = stringRepresentingInteger()
checkThat(instance, notNullValue())
val integer = one(longs(Long.MIN_VALUE, Long.MAX_VALUE))
val integerString = integer.toString()
instance.check(integerString)
//Edge cases
val floatingPoint = one(doubles(-Double.MAX_VALUE, Double.MAX_VALUE))
val floatingPointString = floatingPoint.toString()
assertThrows { instance.check(floatingPointString) }.failedAssertion()
val text = one(strings())
assertThrows { instance.check(text) }.failedAssertion()
}
@Test
fun testValidUUID()
{
val assertion = validUUID()
assertThat(assertion, notNullValue())
val uuid = one(StringGenerators.uuids)
assertion.check(uuid)
val nonUUID = one(alphabeticStrings(10))
assertThrows { assertion.check(nonUUID) }.failedAssertion()
}
@Test
fun testIntegerStringWithGoodString()
{
val value = one(integers(Integer.MIN_VALUE, Integer.MAX_VALUE))
val string = value.toString()
val assertion = integerString()
assertThat(assertion, notNullValue())
assertion.check(string)
}
@Test
fun testIntegerStringWithBadString()
{
val assertion = integerString()
val alphabetic = one(alphabeticStrings())
assertThrows { assertion.check(alphabetic) }.failedAssertion()
val value = one(doubles(-Double.MAX_VALUE, Double.MAX_VALUE))
val decimalString = value.toString()
assertThrows { assertion.check(decimalString) }.failedAssertion()
}
@Test
fun testDecimalString()
{
val assertion = decimalString()
assertThat(assertion, notNullValue())
val value = one(doubles(-Double.MAX_VALUE, Double.MAX_VALUE))
assertion.check(value.toString())
}
@Test
fun testDecimalStringWithBadString()
{
val assertion = decimalString()
assertThat(assertion, notNullValue())
val value = one(alphanumericStrings())
assertThrows { assertion.check(value) }.failedAssertion()
}
}
| apache-2.0 | 4034200b0d110785cf5b40dea467c337 | 29.688172 | 103 | 0.672506 | 4.845501 | false | true | false | false |
JuliaSoboleva/SmartReceiptsLibrary | app/src/main/java/co/smartreceipts/android/identity/widget/account/subscriptions/SubscriptionsListAdapter.kt | 2 | 1923 | package co.smartreceipts.android.identity.widget.account.subscriptions
import androidx.recyclerview.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import co.smartreceipts.android.R
import co.smartreceipts.android.date.DateFormatter
import co.smartreceipts.android.purchases.subscriptions.RemoteSubscription
import kotlinx.android.synthetic.main.item_subscription.view.*
import java.util.*
class SubscriptionsListAdapter(private val dateFormatter: DateFormatter) :
RecyclerView.Adapter<SubscriptionsListAdapter.SubscriptionViewHolder>() {
private var subscriptions = emptyList<RemoteSubscription>()
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): SubscriptionViewHolder {
val inflatedView = LayoutInflater.from(parent.context).inflate(R.layout.item_subscription, parent, false)
return SubscriptionViewHolder(inflatedView)
}
override fun getItemCount(): Int {
return subscriptions.size
}
override fun onBindViewHolder(holder: SubscriptionViewHolder, position: Int) {
val item = subscriptions[position]
holder.subscriptionName.text = item.inAppPurchase.name
val formattedDate = dateFormatter.getFormattedDate(item.expirationDate, TimeZone.getDefault())
holder.subscriptionExpirationDate.text = holder.itemView.context.getString(R.string.subscription_expiration, formattedDate)
}
fun setSubscriptions(subscriptions: List<RemoteSubscription>) {
this.subscriptions = subscriptions
notifyDataSetChanged()
}
class SubscriptionViewHolder internal constructor(itemView: View) : RecyclerView.ViewHolder(itemView) {
internal val subscriptionName: TextView = itemView.subscription_info
internal val subscriptionExpirationDate: TextView = itemView.subscription_expiration
}
} | agpl-3.0 | f0485bf80d0bd6815bd16d3545afeba5 | 38.265306 | 131 | 0.785231 | 5.297521 | false | false | false | false |
elpassion/mainframer-intellij-plugin | src/main/kotlin/com/elpassion/mainframerplugin/common/ui/InsertMacroActionListener.kt | 1 | 1079 | package com.elpassion.mainframerplugin.common.ui
import com.intellij.ide.macro.MacrosDialog
import com.intellij.openapi.project.Project
import com.intellij.openapi.wm.IdeFocusManager
import java.awt.event.ActionEvent
import java.awt.event.ActionListener
import javax.swing.JTextField
import javax.swing.text.BadLocationException
class InsertMacroActionListener(private val myTextField: JTextField,
private val project: Project) : ActionListener {
override fun actionPerformed(e: ActionEvent) {
val dialog = MacrosDialog(project)
if (dialog.showAndGet() && dialog.selectedMacro != null) {
val macro = dialog.selectedMacro.name
val position = myTextField.caretPosition
try {
myTextField.document.insertString(position, "$$macro$", null)
myTextField.caretPosition = position + macro.length + 2
} catch (ignored: BadLocationException) {
}
}
IdeFocusManager.findInstance().requestFocus(myTextField, true)
}
} | apache-2.0 | fda5aaf767458603b4438fe8a00be2d2 | 37.571429 | 88 | 0.684893 | 4.949541 | false | false | false | false |
paplorinc/intellij-community | plugins/gradle/java/src/service/resolve/GradleNonCodeMembersContributor.kt | 1 | 9257 | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.plugins.gradle.service.resolve
import com.intellij.openapi.externalSystem.util.ExternalSystemApiUtil
import com.intellij.openapi.module.ModuleManager
import com.intellij.openapi.roots.ProjectFileIndex
import com.intellij.openapi.util.Ref
import com.intellij.psi.*
import com.intellij.psi.scope.PsiScopeProcessor
import com.intellij.psi.util.InheritanceUtil
import com.intellij.psi.util.PsiTreeUtil
import groovy.lang.Closure
import org.jetbrains.plugins.gradle.service.resolve.GradleCommonClassNames.GRADLE_API_NAMED_DOMAIN_OBJECT_CONTAINER
import org.jetbrains.plugins.gradle.service.resolve.GradleCommonClassNames.GRADLE_API_PROJECT
import org.jetbrains.plugins.gradle.service.resolve.GradleExtensionsContributor.Companion.getDocumentation
import org.jetbrains.plugins.gradle.settings.GradleExtensionsSettings
import org.jetbrains.plugins.gradle.settings.GradleExtensionsSettings.GradleExtensionsData
import org.jetbrains.plugins.groovy.dsl.holders.NonCodeMembersHolder
import org.jetbrains.plugins.groovy.lang.psi.api.statements.blocks.GrClosableBlock
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrApplicationStatement
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.path.GrMethodCallExpression
import org.jetbrains.plugins.groovy.lang.psi.impl.statements.expressions.TypesUtil
import org.jetbrains.plugins.groovy.lang.psi.impl.synthetic.GrLightField
import org.jetbrains.plugins.groovy.lang.psi.impl.synthetic.GrLightMethodBuilder
import org.jetbrains.plugins.groovy.lang.psi.impl.synthetic.GrLightVariable
import org.jetbrains.plugins.groovy.lang.psi.util.GroovyCommonClassNames.GROOVY_LANG_CLOSURE
import org.jetbrains.plugins.groovy.lang.resolve.NonCodeMembersContributor
import org.jetbrains.plugins.groovy.lang.resolve.ResolveUtil
import org.jetbrains.plugins.groovy.lang.resolve.delegatesTo.DELEGATES_TO_KEY
import org.jetbrains.plugins.groovy.lang.resolve.delegatesTo.DELEGATES_TO_STRATEGY_KEY
import org.jetbrains.plugins.groovy.lang.resolve.delegatesTo.getDelegatesToInfo
import org.jetbrains.plugins.groovy.lang.resolve.shouldProcessProperties
/**
* @author Vladislav.Soroka
*/
class GradleNonCodeMembersContributor : NonCodeMembersContributor() {
override fun processDynamicElements(qualifierType: PsiType,
aClass: PsiClass?,
processor: PsiScopeProcessor,
place: PsiElement,
state: ResolveState) {
if (aClass == null) return
val containingFile = place.containingFile
if (!containingFile.isGradleScript() || containingFile?.originalFile?.virtualFile == aClass.containingFile?.originalFile?.virtualFile) return
if (qualifierType.equalsToText(GRADLE_API_PROJECT)) {
val propCandidate = place.references.singleOrNull()?.canonicalText ?: return
val extensionsData: GradleExtensionsData?
val methodCall = place.children.singleOrNull()
if (methodCall is GrMethodCallExpression) {
val projectPath = methodCall.argumentList.expressionArguments.singleOrNull()?.reference?.canonicalText ?: return
if (projectPath == ":") {
val file = containingFile?.originalFile?.virtualFile ?: return
val module = ProjectFileIndex.SERVICE.getInstance(place.project).getModuleForFile(file)
val rootProjectPath = ExternalSystemApiUtil.getExternalRootProjectPath(module)
extensionsData = GradleExtensionsSettings.getInstance(place.project).getExtensionsFor(rootProjectPath, rootProjectPath) ?: return
}
else {
val module = ModuleManager.getInstance(place.project).findModuleByName(projectPath.trimStart(':')) ?: return
extensionsData = GradleExtensionsSettings.getInstance(place.project).getExtensionsFor(module) ?: return
}
}
else if (methodCall is GrReferenceExpression) {
if (place.children[0].text == "rootProject") {
val file = containingFile?.originalFile?.virtualFile ?: return
val module = ProjectFileIndex.SERVICE.getInstance(place.project).getModuleForFile(file)
val rootProjectPath = ExternalSystemApiUtil.getExternalRootProjectPath(module)
extensionsData = GradleExtensionsSettings.getInstance(place.project).getExtensionsFor(rootProjectPath, rootProjectPath) ?: return
}
else return
}
else return
if (!processor.shouldProcessProperties()) {
return
}
val processVariable: (GradleExtensionsSettings.TypeAware) -> Boolean = {
val docRef = Ref.create<String>()
val variable = object : GrLightVariable(place.manager, propCandidate, it.typeFqn, place) {
override fun getNavigationElement(): PsiElement {
val navigationElement = super.getNavigationElement()
navigationElement.putUserData(NonCodeMembersHolder.DOCUMENTATION, docRef.get())
return navigationElement
}
}
val doc = getDocumentation(it, variable)
docRef.set(doc)
place.putUserData(NonCodeMembersHolder.DOCUMENTATION, doc)
processor.execute(variable, state)
}
extensionsData.tasks.firstOrNull { it.name == propCandidate }?.let(processVariable)
extensionsData.findProperty(propCandidate)?.let(processVariable)
}
else {
if (aClass.qualifiedName !in GradleConventionsContributor.conventions) {
processDeclarations(aClass, processor, state, place)
}
val propCandidate = place.references.singleOrNull()?.canonicalText ?: return
val domainObjectType = (qualifierType.superTypes.firstOrNull { it is PsiClassType } as? PsiClassType)?.parameters?.singleOrNull()
?: return
if (!InheritanceUtil.isInheritor(qualifierType, GRADLE_API_NAMED_DOMAIN_OBJECT_CONTAINER)) return
val classHint = processor.getHint(com.intellij.psi.scope.ElementClassHint.KEY)
val shouldProcessMethods = ResolveUtil.shouldProcessMethods(classHint)
val shouldProcessProperties = ResolveUtil.shouldProcessProperties(classHint)
if (GradleResolverUtil.canBeMethodOf(propCandidate, aClass)) return
val domainObjectFqn = TypesUtil.getQualifiedName(domainObjectType) ?: return
val javaPsiFacade = JavaPsiFacade.getInstance(place.project)
val domainObjectPsiClass = javaPsiFacade.findClass(domainObjectFqn, place.resolveScope) ?: return
if (GradleResolverUtil.canBeMethodOf(propCandidate, domainObjectPsiClass)) return
if (GradleResolverUtil.canBeMethodOf("get" + propCandidate.capitalize(), domainObjectPsiClass)) return
if (GradleResolverUtil.canBeMethodOf("set" + propCandidate.capitalize(), domainObjectPsiClass)) return
val closure = PsiTreeUtil.getParentOfType(place, GrClosableBlock::class.java)
val typeToDelegate = closure?.let { getDelegatesToInfo(it)?.typeToDelegate }
if (typeToDelegate != null) {
val fqNameToDelegate = TypesUtil.getQualifiedName(typeToDelegate) ?: return
val classToDelegate = javaPsiFacade.findClass(fqNameToDelegate, place.resolveScope) ?: return
if (classToDelegate !== aClass) {
val parent = place.parent
if (parent is GrMethodCall) {
if (canBeMethodOf(propCandidate, parent, typeToDelegate)) return
}
}
}
if (!shouldProcessMethods && shouldProcessProperties && place is GrReferenceExpression && place.parent !is GrApplicationStatement) {
val variable = GrLightField(propCandidate, domainObjectFqn, place)
place.putUserData(RESOLVED_CODE, true)
if (!processor.execute(variable, state)) return
}
if (shouldProcessMethods && place is GrReferenceExpression) {
val call = PsiTreeUtil.getParentOfType(place, GrMethodCall::class.java) ?: return
val args = call.argumentList
var argsCount = GradleResolverUtil.getGrMethodArumentsCount(args)
argsCount += call.closureArguments.size
argsCount++ // Configuration name is delivered as an argument.
// at runtime, see org.gradle.internal.metaobject.ConfigureDelegate.invokeMethod
val wrappedBase = GrLightMethodBuilder(place.manager, propCandidate).apply {
returnType = domainObjectType
containingClass = aClass
val closureParam = addAndGetOptionalParameter("configuration", GROOVY_LANG_CLOSURE)
closureParam.putUserData(DELEGATES_TO_KEY, domainObjectFqn)
closureParam.putUserData(DELEGATES_TO_STRATEGY_KEY, Closure.DELEGATE_FIRST)
val method = aClass.findMethodsByName("create", true).firstOrNull { it.parameterList.parametersCount == argsCount }
if (method != null) navigationElement = method
}
place.putUserData(RESOLVED_CODE, true)
if (!processor.execute(wrappedBase, state)) return
}
}
}
}
| apache-2.0 | 9a750cdfc7dbbca8fa48577b2678da23 | 56.85625 | 145 | 0.744734 | 5.07511 | false | false | false | false |
apoi/quickbeer-next | app/src/main/java/quickbeer/android/navigation/NavigationExtensions.kt | 2 | 9903 | /*
* Copyright 2019, The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package quickbeer.android.navigation
import android.content.Intent
import android.util.SparseArray
import androidx.core.util.forEach
import androidx.core.util.set
import androidx.fragment.app.FragmentManager
import androidx.navigation.NavController
import androidx.navigation.fragment.NavHostFragment
import com.google.android.material.bottomnavigation.BottomNavigationView
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import quickbeer.android.R
import quickbeer.android.ui.base.Resetable
/**
* Manages the various graphs needed for a [BottomNavigationView].
*
* This sample is a workaround until the Navigation Component supports multiple back stacks.
*/
@Suppress("LongMethod")
fun BottomNavigationView.setupWithNavController(
navGraphIds: List<Int>,
fragmentManager: FragmentManager,
containerId: Int,
intent: Intent
): StateFlow<NavController> {
// Map of tags
val graphIdToTagMap = SparseArray<String>()
// Result. Mutable live data with the selected controlled
val selectedNavController: MutableStateFlow<NavController>
var firstFragmentGraphId = 0
var initialNavController: NavController? = null
// First create a NavHostFragment for each NavGraph ID
navGraphIds.forEachIndexed { index, navGraphId ->
val fragmentTag = getFragmentTag(index)
// Find or create the Navigation host fragment
val navHostFragment = obtainNavHostFragment(
fragmentManager,
fragmentTag,
navGraphId,
containerId
)
// Obtain its id
val graphId = navHostFragment.navController.graph.id
if (index == 0) {
firstFragmentGraphId = graphId
}
// Save to the map
graphIdToTagMap[graphId] = fragmentTag
// Attach or detach nav host fragment depending on whether it's the selected item.
if (this.selectedItemId == graphId) {
// Update flow with the selected graph
initialNavController = navHostFragment.navController
attachNavHostFragment(fragmentManager, navHostFragment, index == 0)
} else {
detachNavHostFragment(fragmentManager, navHostFragment)
}
}
selectedNavController = initialNavController
?.let(::MutableStateFlow)
?: error("Can't find initial NavController")
// Now connect selecting an item with swapping Fragments
var selectedItemTag = graphIdToTagMap[this.selectedItemId]
val firstFragmentTag = graphIdToTagMap[firstFragmentGraphId]
var isOnFirstFragment = selectedItemTag == firstFragmentTag
// When a navigation item is selected
setOnNavigationItemSelectedListener { item ->
// Don't do anything if the state is state has already been saved.
if (fragmentManager.isStateSaved) {
false
} else {
val newlySelectedItemTag = graphIdToTagMap[item.itemId]
if (selectedItemTag != newlySelectedItemTag) {
// Pop everything above the first fragment (the "fixed start destination")
fragmentManager.popBackStack(
firstFragmentTag,
FragmentManager.POP_BACK_STACK_INCLUSIVE
)
val selectedFragment = fragmentManager.findFragmentByTag(newlySelectedItemTag)
as NavHostFragment
// Exclude the first fragment tag because it's always in the back stack.
if (firstFragmentTag != newlySelectedItemTag) {
// Commit a transaction that cleans the back stack and adds the first fragment
// to it, creating the fixed started destination.
fragmentManager.beginTransaction()
.setCustomAnimations(
R.anim.nav_default_enter_anim,
R.anim.nav_default_exit_anim,
R.anim.nav_default_pop_enter_anim,
R.anim.nav_default_pop_exit_anim
)
.attach(selectedFragment)
.setPrimaryNavigationFragment(selectedFragment)
.apply {
// Detach all other Fragments
graphIdToTagMap.forEach { _, fragmentTagIter ->
if (fragmentTagIter != newlySelectedItemTag) {
detach(fragmentManager.findFragmentByTag(firstFragmentTag)!!)
}
}
}
.addToBackStack(firstFragmentTag)
.setReorderingAllowed(true)
.commit()
}
selectedItemTag = newlySelectedItemTag
isOnFirstFragment = selectedItemTag == firstFragmentTag
selectedNavController.value = selectedFragment.navController
true
} else {
false
}
}
}
// Optional: on item reselected, pop back stack to the destination of the graph
setupItemReselected(graphIdToTagMap, fragmentManager)
// Handle deep link
setupDeepLinks(navGraphIds, fragmentManager, containerId, intent)
// Finally, ensure that we update our BottomNavigationView when the back stack changes
fragmentManager.addOnBackStackChangedListener {
if (!isOnFirstFragment && !fragmentManager.isOnBackStack(firstFragmentTag)) {
this.selectedItemId = firstFragmentGraphId
}
// Reset the graph if the currentDestination is not valid (happens when the back
// stack is popped after using the back button).
selectedNavController.value?.let { controller ->
if (controller.currentDestination == null) {
controller.navigate(controller.graph.id)
}
}
}
return selectedNavController
}
private fun BottomNavigationView.setupDeepLinks(
navGraphIds: List<Int>,
fragmentManager: FragmentManager,
containerId: Int,
intent: Intent
) {
navGraphIds.forEachIndexed { index, navGraphId ->
val fragmentTag = getFragmentTag(index)
// Find or create the Navigation host fragment
val navHostFragment = obtainNavHostFragment(
fragmentManager,
fragmentTag,
navGraphId,
containerId
)
// Handle Intent
if (navHostFragment.navController.handleDeepLink(intent) &&
selectedItemId != navHostFragment.navController.graph.id
) {
this.selectedItemId = navHostFragment.navController.graph.id
}
}
}
private fun BottomNavigationView.setupItemReselected(
graphIdToTagMap: SparseArray<String>,
fragmentManager: FragmentManager
) {
setOnNavigationItemReselectedListener { item ->
val newlySelectedItemTag = graphIdToTagMap[item.itemId]
val selectedFragment = fragmentManager.findFragmentByTag(newlySelectedItemTag)
as NavHostFragment
val navController = selectedFragment.navController
if (navController.graph.startDestination != navController.currentDestination?.id) {
// Pop the back stack to the start destination of the current navController graph
navController.popBackStack(navController.graph.startDestination, false)
} else {
// Already at the start destination, reset the fragment
val currentFragment = selectedFragment.childFragmentManager.fragments.lastOrNull()
(currentFragment as? Resetable)?.onReset()
}
}
}
private fun detachNavHostFragment(
fragmentManager: FragmentManager,
navHostFragment: NavHostFragment
) {
fragmentManager.beginTransaction()
.detach(navHostFragment)
.commitNow()
}
private fun attachNavHostFragment(
fragmentManager: FragmentManager,
navHostFragment: NavHostFragment,
isPrimaryNavFragment: Boolean
) {
fragmentManager.beginTransaction()
.attach(navHostFragment)
.apply {
if (isPrimaryNavFragment) {
setPrimaryNavigationFragment(navHostFragment)
}
}
.commitNow()
}
private fun obtainNavHostFragment(
fragmentManager: FragmentManager,
fragmentTag: String,
navGraphId: Int,
containerId: Int
): NavHostFragment {
// If the Nav Host fragment exists, return it
val existingFragment = fragmentManager.findFragmentByTag(fragmentTag) as NavHostFragment?
existingFragment?.let { return it }
// Otherwise, create it and return it.
val navHostFragment = NavHostFragment.create(navGraphId)
fragmentManager.beginTransaction()
.add(containerId, navHostFragment, fragmentTag)
.commitNow()
return navHostFragment
}
private fun FragmentManager.isOnBackStack(backStackName: String): Boolean {
val backStackCount = backStackEntryCount
for (index in 0 until backStackCount) {
if (getBackStackEntryAt(index).name == backStackName) {
return true
}
}
return false
}
private fun getFragmentTag(index: Int) = "bottomNavigation#$index"
| gpl-3.0 | 98a5dce2b101aaee9d284479dd15f7c5 | 36.369811 | 98 | 0.656468 | 5.576014 | false | false | false | false |
google/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/ConvertConcatenationToBuildStringIntention.kt | 2 | 4560 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.intentions
import com.intellij.openapi.editor.Editor
import com.intellij.psi.PsiComment
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiWhiteSpace
import com.intellij.psi.util.elementType
import com.intellij.psi.util.nextLeafs
import com.intellij.psi.util.siblings
import org.jetbrains.kotlin.builtins.KotlinBuiltIns
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.core.ShortenReferences
import org.jetbrains.kotlin.idea.base.psi.replaced
import org.jetbrains.kotlin.idea.caches.resolve.safeAnalyzeNonSourceRootCode
import org.jetbrains.kotlin.idea.codeinsight.api.classic.intentions.SelfTargetingIntention
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.parents
import org.jetbrains.kotlin.resolve.calls.util.getType
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
class ConvertConcatenationToBuildStringIntention : SelfTargetingIntention<KtBinaryExpression>(
KtBinaryExpression::class.java,
KotlinBundle.lazyMessage("convert.concatenation.to.build.string")
) {
override fun isApplicableTo(element: KtBinaryExpression, caretOffset: Int): Boolean {
return element.isConcatenation() && !element.parent.isConcatenation() && !element.mustBeConstant()
}
override fun applyTo(element: KtBinaryExpression, editor: Editor?) {
val buildStringCall = KtPsiFactory(element).buildExpression {
appendFixedText("kotlin.text.buildString {\n")
element.allExpressions().forEach { expression ->
appendFixedText("append(")
if (expression is KtStringTemplateExpression) {
val singleEntry = expression.entries.singleOrNull()
if (singleEntry is KtStringTemplateEntryWithExpression) {
appendExpression(singleEntry.expression)
} else {
appendNonFormattedText(expression.text)
}
} else {
appendExpression(expression)
}
appendFixedText(")")
val tailComments = expression.tailComments()
if (tailComments.isNotEmpty()) {
appendFixedText(" ")
tailComments.forEach { appendNonFormattedText(it.text) }
}
appendFixedText("\n")
}
appendFixedText("}")
}
element.deleteTailComments()
val replaced = element.replaced(buildStringCall)
ShortenReferences.DEFAULT.process(replaced)
}
private fun PsiElement.isConcatenation(): Boolean {
if (this !is KtBinaryExpression) return false
if (operationToken != KtTokens.PLUS) return false
val type = getType(safeAnalyzeNonSourceRootCode(BodyResolveMode.PARTIAL)) ?: return false
return KotlinBuiltIns.isString(type)
}
private fun KtBinaryExpression.allExpressions(): List<KtExpression> {
val expressions = mutableListOf<KtExpression>()
fun collect(expression: KtExpression?) {
when (expression) {
is KtBinaryExpression -> {
collect(expression.left)
collect(expression.right)
}
is KtExpression ->
expressions.add(expression)
}
}
collect(this)
return expressions
}
private fun KtExpression.tailComments(): List<PsiElement> {
val tailElements = this.nextLeafs
.takeWhile { it is PsiWhiteSpace || it is PsiComment || it.elementType == KtTokens.PLUS }
.dropWhile { it !is PsiComment }
return if (tailElements.any { it is PsiComment }) {
tailElements.toList().dropLastWhile { it is PsiWhiteSpace }
} else {
emptyList()
}
}
private fun KtExpression.deleteTailComments() {
siblings(withSelf = false)
.takeWhile { !it.isWhiteSpaceWithLineBreak() }
.filter { it is PsiComment }
.forEach { it.delete() }
}
private fun PsiElement.isWhiteSpaceWithLineBreak() = this is PsiWhiteSpace && this.textContains('\n')
}
internal fun KtExpression.mustBeConstant(): Boolean = this.parents.any { it is KtAnnotationEntry }
| apache-2.0 | d6d3b21eddaf7187774c775a643522ae | 41.222222 | 158 | 0.662281 | 5.320887 | false | false | false | false |
JetBrains/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/AbstractImportFix.kt | 1 | 42985 | // 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.quickfix
import com.intellij.codeInsight.ImportFilter
import com.intellij.codeInsight.daemon.DaemonCodeAnalyzerSettings
import com.intellij.codeInsight.hint.HintManager
import com.intellij.codeInsight.intention.HighPriorityAction
import com.intellij.codeInsight.intention.IntentionAction
import com.intellij.codeInspection.HintAction
import com.intellij.codeInspection.util.IntentionName
import com.intellij.openapi.Disposable
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.command.CommandProcessor
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Disposer
import com.intellij.packageDependencies.DependencyValidationManager
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiErrorElement
import com.intellij.psi.PsiFile
import com.intellij.psi.PsiModifier
import com.intellij.psi.util.PsiModificationTracker
import com.intellij.psi.util.elementType
import com.intellij.util.Processors
import org.jetbrains.annotations.TestOnly
import org.jetbrains.kotlin.KtNodeTypes
import org.jetbrains.kotlin.descriptors.*
import org.jetbrains.kotlin.diagnostics.Diagnostic
import org.jetbrains.kotlin.diagnostics.DiagnosticFactory
import org.jetbrains.kotlin.diagnostics.Errors
import org.jetbrains.kotlin.diagnostics.Severity
import org.jetbrains.kotlin.idea.actions.*
import org.jetbrains.kotlin.idea.actions.createGroupedImportsAction
import org.jetbrains.kotlin.idea.actions.createSingleImportAction
import org.jetbrains.kotlin.idea.actions.createSingleImportActionForConstructor
import org.jetbrains.kotlin.idea.base.facet.platform.platform
import org.jetbrains.kotlin.idea.base.projectStructure.languageVersionSettings
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.base.utils.fqname.isImported
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.caches.resolve.analyzeInContext
import org.jetbrains.kotlin.idea.caches.resolve.getResolutionFacade
import org.jetbrains.kotlin.idea.caches.resolve.util.getResolveScope
import org.jetbrains.kotlin.idea.codeInsight.DescriptorToSourceUtilsIde
import org.jetbrains.kotlin.idea.codeInsight.KotlinAutoImportsFilter
import org.jetbrains.kotlin.idea.codeinsight.api.classic.quickfixes.KotlinQuickFixAction
import org.jetbrains.kotlin.idea.codeinsight.api.classic.quickfixes.UnresolvedReferenceQuickFixFactory
import org.jetbrains.kotlin.idea.core.KotlinIndicesHelper
import org.jetbrains.kotlin.idea.core.isVisible
import org.jetbrains.kotlin.idea.imports.canBeReferencedViaImport
import org.jetbrains.kotlin.idea.imports.importableFqName
import org.jetbrains.kotlin.idea.intentions.getCallableDescriptor
import org.jetbrains.kotlin.idea.intentions.singleLambdaArgumentExpression
import org.jetbrains.kotlin.idea.references.mainReference
import org.jetbrains.kotlin.idea.util.*
import org.jetbrains.kotlin.incremental.components.NoLookupLocation
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.name.parentOrNull
import org.jetbrains.kotlin.platform.jvm.isJvm
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.KtPsiUtil.isSelectorInQualified
import org.jetbrains.kotlin.psi.psiUtil.*
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.DescriptorUtils
import org.jetbrains.kotlin.resolve.ImportPath
import org.jetbrains.kotlin.resolve.bindingContextUtil.getDataFlowInfoBefore
import org.jetbrains.kotlin.resolve.calls.context.ContextDependency
import org.jetbrains.kotlin.resolve.calls.inference.model.TypeVariableTypeConstructor
import org.jetbrains.kotlin.resolve.calls.util.getParentCall
import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameSafe
import org.jetbrains.kotlin.resolve.descriptorUtil.isExtension
import org.jetbrains.kotlin.resolve.descriptorUtil.isExtensionProperty
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
import org.jetbrains.kotlin.resolve.scopes.ExplicitImportsScope
import org.jetbrains.kotlin.resolve.scopes.utils.addImportingScope
import org.jetbrains.kotlin.resolve.scopes.utils.collectFunctions
import org.jetbrains.kotlin.types.KotlinType
import org.jetbrains.kotlin.types.typeUtil.isSubtypeOf
import org.jetbrains.kotlin.util.OperatorNameConventions
import org.jetbrains.kotlin.utils.KotlinExceptionWithAttachments
import org.jetbrains.kotlin.utils.addToStdlib.safeAs
import java.util.TreeSet
/**
* Check possibility and perform fix for unresolved references.
*/
internal abstract class ImportFixBase<T : KtExpression> protected constructor(
expression: T,
factory: Factory
) : KotlinQuickFixAction<T>(expression), HintAction, HighPriorityAction {
private val project = expression.project
private val modificationCountOnCreate = PsiModificationTracker.getInstance(project).modificationCount
protected lateinit var suggestions: Collection<FqName>
@IntentionName
private lateinit var text: String
internal fun computeSuggestions() {
val suggestionDescriptors = collectSuggestionDescriptors()
suggestions = collectSuggestions(suggestionDescriptors)
text = calculateText(suggestionDescriptors)
}
internal fun suggestions() = suggestions
protected open val supportedErrors = factory.supportedErrors.toSet()
protected abstract val importNames: Collection<Name>
protected abstract fun getCallTypeAndReceiver(): CallTypeAndReceiver<*, *>?
protected open fun getReceiverTypeFromDiagnostic(): KotlinType? = null
override fun showHint(editor: Editor): Boolean {
val element = element?.takeIf(PsiElement::isValid) ?: return false
if (isOutdated()) return false
if (ApplicationManager.getApplication().isHeadlessEnvironment ||
!DaemonCodeAnalyzerSettings.getInstance().isImportHintEnabled ||
HintManager.getInstance().hasShownHintsThatWillHideByOtherHint(true)) return false
if (suggestions.isEmpty()) return false
return createAction(project, editor, element).showHint()
}
@IntentionName
private fun calculateText(suggestionDescriptors: Collection<DeclarationDescriptor>): String {
val descriptors =
suggestionDescriptors.mapTo(hashSetOf()) { it.original }
val ktFile = element?.containingKtFile ?: return KotlinBundle.message("fix.import")
val languageVersionSettings = ktFile.languageVersionSettings
val prioritizer = Prioritizer(ktFile)
val kindNameGroupedByKind = descriptors.mapNotNull { descriptor ->
val kind = when {
descriptor.isExtensionProperty -> ImportKind.EXTENSION_PROPERTY
descriptor is PropertyDescriptor -> ImportKind.PROPERTY
descriptor is ClassConstructorDescriptor -> ImportKind.CLASS
descriptor is FunctionDescriptor && descriptor.isExtension -> ImportKind.EXTENSION_FUNCTION
descriptor is FunctionDescriptor -> ImportKind.FUNCTION
DescriptorUtils.isObject(descriptor) -> ImportKind.OBJECT
descriptor is ClassDescriptor -> ImportKind.CLASS
else -> null
} ?: return@mapNotNull null
val name = buildString {
descriptor.safeAs<CallableDescriptor>()?.let { callableDescriptor ->
val extensionReceiverParameter = callableDescriptor.extensionReceiverParameter
if (extensionReceiverParameter != null) {
extensionReceiverParameter.type.constructor.declarationDescriptor.safeAs<ClassDescriptor>()?.name?.let {
append(it.asString())
}
} else {
callableDescriptor.containingDeclaration.safeAs<ClassDescriptor>()?.name?.let {
append(it.asString())
}
}
}
descriptor.name.takeUnless { it.isSpecial }?.let {
if (this.isNotEmpty()) append('.')
append(it.asString())
}
}
ImportName(kind, name, prioritizer.priority(descriptor, languageVersionSettings))
}.groupBy(keySelector = { it.kind }) { it }
return if (kindNameGroupedByKind.size == 1) {
val (kind, names) = kindNameGroupedByKind.entries.first()
val sortedNames = TreeSet<ImportName>(compareBy({ it.priority }, { it.kind }, { it.name }))
sortedNames.addAll(names)
val firstName = sortedNames.first().name
val singlePackage = suggestions.groupBy { it.parentOrNull() ?: FqName.ROOT }.size == 1
if (singlePackage) {
val size = sortedNames.size
if (size == 2) {
KotlinBundle.message("fix.import.kind.0.name.1.and.name.2", kind.toText(size), firstName, sortedNames.last().name)
} else {
KotlinBundle.message("fix.import.kind.0.name.1.2", kind.toText(size), firstName, size - 1)
}
} else if (kind.groupedByPackage) {
KotlinBundle.message("fix.import.kind.0.name.1.2", kind.toText(1), firstName, 0)
} else {
val groupBy = sortedNames.map { it.name }.toSortedSet().groupBy { it.substringBefore('.') }
val value = groupBy.entries.first().value
val first = value.first()
val multiple = if (value.size == 1) 0 else 1
when {
groupBy.size != 1 -> KotlinBundle.message("fix.import.kind.0.name.1.2", kind.toText(1), first.substringAfter('.'), multiple)
value.size == 2 -> KotlinBundle.message("fix.import.kind.0.name.1.and.name.2", kind.toText(value.size), first, value.last())
else -> KotlinBundle.message("fix.import.kind.0.name.1.2", kind.toText(1), first, multiple)
}
}
} else {
KotlinBundle.message("fix.import")
}
}
private class ImportName(val kind: ImportKind, val name: String, val priority: ComparablePriority)
private enum class ImportKind(private val key: String, val groupedByPackage: Boolean = false) {
CLASS("text.class.0", true),
PROPERTY("text.property.0"),
OBJECT("text.object.0", true),
FUNCTION("text.function.0"),
EXTENSION_PROPERTY("text.extension.property.0"),
EXTENSION_FUNCTION("text.extension.function.0");
fun toText(number: Int) = KotlinBundle.message(key, if (number == 1) 1 else 2)
}
override fun getText(): String = text
override fun getFamilyName() = KotlinBundle.message("fix.import")
override fun isAvailable(project: Project, editor: Editor?, file: KtFile): Boolean {
return element != null && suggestions.isNotEmpty()
}
override fun invoke(project: Project, editor: Editor?, file: KtFile) {
val element = element ?: return
CommandProcessor.getInstance().runUndoTransparentAction {
createAction(project, editor!!, element).execute()
}
}
override fun startInWriteAction() = false
private fun isOutdated() = modificationCountOnCreate != PsiModificationTracker.getInstance(project).modificationCount
open fun createAction(project: Project, editor: Editor, element: KtExpression): KotlinAddImportAction {
return createSingleImportAction(project, editor, element, suggestions)
}
private fun createActionWithAutoImportsFilter(project: Project, editor: Editor, element: KtExpression): KotlinAddImportAction {
val filteredSuggestions =
KotlinAutoImportsFilter.filterSuggestionsIfApplicable(element.containingKtFile, suggestions)
return createSingleImportAction(project, editor, element, filteredSuggestions)
}
private fun collectSuggestionDescriptors(): Collection<DeclarationDescriptor> {
element?.takeIf(PsiElement::isValid)?.takeIf { it.containingFile is KtFile } ?: return emptyList()
val callTypeAndReceiver = getCallTypeAndReceiver() ?: return emptyList()
if (callTypeAndReceiver is CallTypeAndReceiver.UNKNOWN) return emptyList()
return importNames.flatMap { collectSuggestionsForName(it, callTypeAndReceiver) }
}
private fun collectSuggestions(suggestionDescriptors: Collection<DeclarationDescriptor>): Collection<FqName> =
suggestionDescriptors
.asSequence()
.map { it.fqNameSafe }
.distinct()
.toList()
private fun collectSuggestionsForName(name: Name, callTypeAndReceiver: CallTypeAndReceiver<*, *>): Collection<DeclarationDescriptor> {
val element = element ?: return emptyList()
val nameStr = name.asString()
if (nameStr.isEmpty()) return emptyList()
val file = element.containingKtFile
val bindingContext = element.analyze(BodyResolveMode.PARTIAL_WITH_DIAGNOSTICS)
if (!checkErrorStillPresent(bindingContext)) return emptyList()
val searchScope = getResolveScope(file)
val resolutionFacade = file.getResolutionFacade()
fun isVisible(descriptor: DeclarationDescriptor): Boolean = descriptor.safeAs<DeclarationDescriptorWithVisibility>()
?.isVisible(element, callTypeAndReceiver.receiver as? KtExpression, bindingContext, resolutionFacade) ?: true
val indicesHelper = KotlinIndicesHelper(resolutionFacade, searchScope, ::isVisible, file = file)
var result = fillCandidates(nameStr, callTypeAndReceiver, bindingContext, indicesHelper)
// for CallType.DEFAULT do not include functions if there is no parenthesis
if (callTypeAndReceiver is CallTypeAndReceiver.DEFAULT) {
val isCall = element.parent is KtCallExpression
if (!isCall) {
result = result.filter { it !is FunctionDescriptor }
}
}
result = result.filter { ImportFilter.shouldImport(file, it.fqNameSafe.asString()) }
return if (result.size > 1)
reduceCandidatesBasedOnDependencyRuleViolation(result, file)
else
result
}
private fun checkErrorStillPresent(bindingContext: BindingContext): Boolean {
val errors = supportedErrors
val elementsToCheckDiagnostics = elementsToCheckDiagnostics()
for (psiElement in elementsToCheckDiagnostics) {
if (bindingContext.diagnostics.forElement(psiElement).any { it.factory in errors }) return true
}
return false
}
protected open fun elementsToCheckDiagnostics(): Collection<PsiElement> = listOfNotNull(element)
abstract fun fillCandidates(
name: String,
callTypeAndReceiver: CallTypeAndReceiver<*, *>,
bindingContext: BindingContext,
indicesHelper: KotlinIndicesHelper
): List<DeclarationDescriptor>
private fun reduceCandidatesBasedOnDependencyRuleViolation(
candidates: Collection<DeclarationDescriptor>, file: PsiFile
): Collection<DeclarationDescriptor> {
val project = file.project
val validationManager = DependencyValidationManager.getInstance(project)
return candidates.filter {
val targetFile = DescriptorToSourceUtilsIde.getAnyDeclaration(project, it)?.containingFile ?: return@filter true
validationManager.getViolatorDependencyRules(file, targetFile).isEmpty()
}
}
abstract class Factory : KotlinSingleIntentionActionFactory() {
val supportedErrors: Collection<DiagnosticFactory<*>> by lazy { QuickFixes.getInstance().getDiagnostics(this) }
override fun isApplicableForCodeFragment() = true
abstract fun createImportAction(diagnostic: Diagnostic): ImportFixBase<*>?
override fun areActionsAvailable(diagnostic: Diagnostic): Boolean {
val element = diagnostic.psiElement
return element is KtExpression && element.references.isNotEmpty()
}
open fun createImportActionsForAllProblems(sameTypeDiagnostics: Collection<Diagnostic>): List<ImportFixBase<*>> = emptyList()
final override fun createAction(diagnostic: Diagnostic): IntentionAction? {
return try {
createImportAction(diagnostic)?.also { it.computeSuggestions() }
} catch (ex: KotlinExceptionWithAttachments) {
// Sometimes fails with
// <production sources for module light_idea_test_case> is a module[ModuleDescriptorImpl@508c55a2] is not contained in resolver...
// TODO: remove try-catch when the problem is fixed
if (AbstractImportFixInfo.IGNORE_MODULE_ERROR &&
ex.message?.contains("<production sources for module light_idea_test_case>") == true
) null
else throw ex
}
}
override fun doCreateActionsForAllProblems(sameTypeDiagnostics: Collection<Diagnostic>): List<IntentionAction> =
createImportActionsForAllProblems(sameTypeDiagnostics).onEach { it.computeSuggestions() }
}
abstract class FactoryWithUnresolvedReferenceQuickFix: Factory(), UnresolvedReferenceQuickFixFactory
}
internal abstract class OrdinaryImportFixBase<T : KtExpression>(expression: T, factory: Factory) : ImportFixBase<T>(expression, factory) {
override fun fillCandidates(
name: String,
callTypeAndReceiver: CallTypeAndReceiver<*, *>,
bindingContext: BindingContext,
indicesHelper: KotlinIndicesHelper
): List<DeclarationDescriptor> {
val expression = element ?: return emptyList()
val result = ArrayList<DeclarationDescriptor>()
if (expression is KtSimpleNameExpression) {
if (!expression.isImportDirectiveExpression() && !isSelectorInQualified(expression)) {
ProgressManager.checkCanceled()
val filterByCallType = callTypeAndReceiver.toFilter()
indicesHelper.getClassesByName(expression, name).filterTo(result, filterByCallType)
indicesHelper.processTopLevelTypeAliases({ it == name }, {
if (filterByCallType(it)) {
result.add(it)
}
})
indicesHelper.getTopLevelCallablesByName(name).filterTo(result, filterByCallType)
}
if (callTypeAndReceiver.callType == CallType.OPERATOR) {
val type = expression.getCallableDescriptor()?.returnType ?: getReceiverTypeFromDiagnostic()
if (type != null) {
result.addAll(indicesHelper.getCallableTopLevelExtensions(callTypeAndReceiver, listOf(type), { it == name }))
}
}
}
ProgressManager.checkCanceled()
result.addAll(
indicesHelper.getCallableTopLevelExtensions(
callTypeAndReceiver,
expression,
bindingContext,
findReceiverForDelegate(expression, callTypeAndReceiver.callType)
) { it == name }
)
val ktFile = element?.containingKtFile ?: return emptyList()
val importedFqNamesAsAlias = getImportedFqNamesAsAlias(ktFile)
val (defaultImports, excludedImports) = ImportInsertHelperImpl.computeDefaultAndExcludedImports(ktFile)
return result.filter {
val descriptor = it.takeUnless { expression.parent is KtCallExpression && it.isSealed() } ?: return@filter false
val importableFqName = descriptor.importableFqName ?: return@filter true
val importPath = ImportPath(importableFqName, isAllUnder = false)
!importPath.isImported(defaultImports, excludedImports) || importableFqName in importedFqNamesAsAlias
}
}
private fun findReceiverForDelegate(expression: KtExpression, callType: CallType<*>): KotlinType? {
if (callType != CallType.DELEGATE) return null
val receiverTypeFromDiagnostic = getReceiverTypeFromDiagnostic()
if (receiverTypeFromDiagnostic?.constructor is TypeVariableTypeConstructor) {
if (receiverTypeFromDiagnostic == expression.getCallableDescriptor()?.returnType) {
// the issue is that the whole lambda expression cannot be resolved,
// but it's possible to analyze the last expression independently and try guessing the receiver
return tryFindReceiverFromLambda(expression)
}
}
return receiverTypeFromDiagnostic
}
private fun tryFindReceiverFromLambda(expression: KtExpression): KotlinType? {
if (expression !is KtCallExpression) return null
val lambdaExpression = expression.singleLambdaArgumentExpression() ?: return null
val lastStatement = KtPsiUtil.getLastStatementInABlock(lambdaExpression.bodyExpression) ?: return null
val bindingContext = lastStatement.analyze(bodyResolveMode = BodyResolveMode.PARTIAL)
return bindingContext.getType(lastStatement)
}
private fun getImportedFqNamesAsAlias(ktFile: KtFile) =
ktFile.importDirectives
.filter { it.alias != null }
.mapNotNull { it.importedFqName }
}
// This is required to be abstract to reduce bunch file size
internal abstract class AbstractImportFix(expression: KtSimpleNameExpression, factory: Factory) :
OrdinaryImportFixBase<KtSimpleNameExpression>(expression, factory) {
override fun getCallTypeAndReceiver() = element?.let { CallTypeAndReceiver.detect(it) }
private fun importNamesForMembers(): Collection<Name> {
val element = element ?: return emptyList()
if (element.getIdentifier() != null) {
val name = element.getReferencedName()
if (Name.isValidIdentifier(name)) {
return listOf(Name.identifier(name))
}
}
return emptyList()
}
override val importNames: Collection<Name> =
((element?.mainReference?.resolvesByNames ?: emptyList()) + importNamesForMembers()).distinct()
private fun collectMemberCandidates(
name: String,
callTypeAndReceiver: CallTypeAndReceiver<*, *>,
bindingContext: BindingContext,
indicesHelper: KotlinIndicesHelper
): List<DeclarationDescriptor> {
val element = element ?: return emptyList()
if (element.isImportDirectiveExpression()) return emptyList()
val result = ArrayList<DeclarationDescriptor>()
val filterByCallType = callTypeAndReceiver.toFilter()
indicesHelper.getKotlinEnumsByName(name).filterTo(result, filterByCallType)
ProgressManager.checkCanceled()
val actualReceivers = getReceiversForExpression(element, callTypeAndReceiver, bindingContext)
if (isSelectorInQualified(element) && actualReceivers.explicitReceivers.isEmpty()) {
// If the element is qualified, and at the same time we haven't found any explicit
// receiver, it means that the qualifier is not a value (for example, it might be a type name).
// In this case we do not want to propose any importing fix, since it is impossible
// to import a function which can be syntactically called on a non-value qualifier -
// such function (for example, a static function) should be successfully resolved
// without any import
return emptyList()
}
val checkDispatchReceiver = when (callTypeAndReceiver) {
is CallTypeAndReceiver.OPERATOR, is CallTypeAndReceiver.INFIX -> true
else -> false
}
val processor = { descriptor: CallableDescriptor ->
ProgressManager.checkCanceled()
if (descriptor.canBeReferencedViaImport() && filterByCallType(descriptor)) {
if (descriptor.extensionReceiverParameter != null) {
result.addAll(
descriptor.substituteExtensionIfCallable(
actualReceivers.explicitReceivers.ifEmpty { actualReceivers.allReceivers },
callTypeAndReceiver.callType
)
)
} else if (descriptor.isValidByReceiversFor(actualReceivers, checkDispatchReceiver)) {
result.add(descriptor)
}
}
}
indicesHelper.processKotlinCallablesByName(
name,
filter = { declaration -> (declaration.parent as? KtClassBody)?.parent is KtObjectDeclaration },
processor = processor
)
indicesHelper.processAllCallablesInSubclassObjects(
name,
callTypeAndReceiver, element, bindingContext,
processor = processor
)
if (element.containingKtFile.platform.isJvm()) {
indicesHelper.processJvmCallablesByName(
name,
filter = { it.hasModifierProperty(PsiModifier.STATIC) },
processor = processor
)
}
return result
}
/**
* Currently at most one explicit receiver can be used in expression, but it can change in the future,
* so we use `Collection` to represent explicit receivers.
*/
private class Receivers(val explicitReceivers: Collection<KotlinType>, val allReceivers: Collection<KotlinType>)
private fun getReceiversForExpression(
element: KtSimpleNameExpression,
callTypeAndReceiver: CallTypeAndReceiver<*, *>,
bindingContext: BindingContext
): Receivers {
val resolutionFacade = element.getResolutionFacade()
val actualReceiverTypes = callTypeAndReceiver
.receiverTypesWithIndex(
bindingContext, element,
resolutionFacade.moduleDescriptor, resolutionFacade,
stableSmartCastsOnly = false,
withImplicitReceiversWhenExplicitPresent = true
).orEmpty()
val explicitReceiverType = actualReceiverTypes.filterNot { it.implicit }
return Receivers(
explicitReceiverType.map { it.type },
actualReceiverTypes.map { it.type }
)
}
/**
* This method accepts only callables with no extension receiver because it ignores generics
* and does not perform any substitution.
*
* @return true iff [this] descriptor can be called given [actualReceivers] present in scope AND
* passed [Receivers.explicitReceivers] are satisfied if present.
*/
private fun CallableDescriptor.isValidByReceiversFor(actualReceivers: Receivers, checkDispatchReceiver: Boolean): Boolean {
require(extensionReceiverParameter == null) { "This method works only on non-extension callables, got $this" }
val dispatcherReceiver = dispatchReceiverParameter.takeIf { checkDispatchReceiver }
return if (dispatcherReceiver == null) {
actualReceivers.explicitReceivers.isEmpty()
} else {
val typesToCheck = with(actualReceivers) { explicitReceivers.ifEmpty { allReceivers } }
typesToCheck.any { it.isSubtypeOf(dispatcherReceiver.type) }
}
}
override fun fillCandidates(
name: String,
callTypeAndReceiver: CallTypeAndReceiver<*, *>,
bindingContext: BindingContext,
indicesHelper: KotlinIndicesHelper
): List<DeclarationDescriptor> =
super.fillCandidates(name, callTypeAndReceiver, bindingContext, indicesHelper) + collectMemberCandidates(
name,
callTypeAndReceiver,
bindingContext,
indicesHelper
)
}
internal class ImportConstructorReferenceFix(expression: KtSimpleNameExpression) :
ImportFixBase<KtSimpleNameExpression>(expression, MyFactory) {
override fun getCallTypeAndReceiver() = element?.let {
CallTypeAndReceiver.detect(it) as? CallTypeAndReceiver.CALLABLE_REFERENCE
}
override fun fillCandidates(
name: String,
callTypeAndReceiver: CallTypeAndReceiver<*, *>,
bindingContext: BindingContext,
indicesHelper: KotlinIndicesHelper
): List<DeclarationDescriptor> {
val expression = element ?: return emptyList()
val filterByCallType = callTypeAndReceiver.toFilter()
// TODO Type-aliases
return indicesHelper.getClassesByName(expression, name)
.asSequence()
.map { it.constructors }.flatten()
.filter { it.importableFqName != null }
.filter(filterByCallType)
.toList()
}
override fun createAction(project: Project, editor: Editor, element: KtExpression): KotlinAddImportAction {
return createSingleImportActionForConstructor(project, editor, element, suggestions)
}
override val importNames = element?.mainReference?.resolvesByNames ?: emptyList()
companion object MyFactory : FactoryWithUnresolvedReferenceQuickFix() {
override fun createImportAction(diagnostic: Diagnostic) =
diagnostic.psiElement.safeAs<KtSimpleNameExpression>()?.let(::ImportConstructorReferenceFix)
}
}
internal class InvokeImportFix(
expression: KtExpression, val diagnostic: Diagnostic
) : OrdinaryImportFixBase<KtExpression>(expression, MyFactory) {
override val importNames = listOf(OperatorNameConventions.INVOKE)
override fun getCallTypeAndReceiver() = element?.let { CallTypeAndReceiver.OPERATOR(it) }
override fun getReceiverTypeFromDiagnostic(): KotlinType = Errors.FUNCTION_EXPECTED.cast(diagnostic).b
companion object MyFactory : FactoryWithUnresolvedReferenceQuickFix() {
override fun createImportAction(diagnostic: Diagnostic) =
diagnostic.psiElement.safeAs<KtExpression>()?.let {
InvokeImportFix(it, diagnostic)
}
}
}
internal class IteratorImportFix(expression: KtExpression) : OrdinaryImportFixBase<KtExpression>(expression, MyFactory) {
override val importNames = listOf(OperatorNameConventions.ITERATOR)
override fun getCallTypeAndReceiver() = element?.let { CallTypeAndReceiver.OPERATOR(it) }
companion object MyFactory : Factory() {
override fun createImportAction(diagnostic: Diagnostic): IteratorImportFix? =
diagnostic.psiElement.safeAs<KtExpression>()?.let(::IteratorImportFix)
}
}
internal open class ArrayAccessorImportFix(
element: KtArrayAccessExpression,
override val importNames: Collection<Name>
) : OrdinaryImportFixBase<KtArrayAccessExpression>(element, MyFactory) {
override fun getCallTypeAndReceiver() = element?.let { CallTypeAndReceiver.OPERATOR(it.arrayExpression!!) }
companion object MyFactory : FactoryWithUnresolvedReferenceQuickFix() {
private fun importName(diagnostic: Diagnostic): Name {
return when (diagnostic.factory) {
Errors.NO_GET_METHOD -> OperatorNameConventions.GET
Errors.NO_SET_METHOD -> OperatorNameConventions.SET
else -> throw IllegalStateException("Shouldn't be called for other diagnostics")
}
}
override fun createImportAction(diagnostic: Diagnostic): ArrayAccessorImportFix? {
val factory = diagnostic.factory
assert(factory == Errors.NO_GET_METHOD || factory == Errors.NO_SET_METHOD)
val element = diagnostic.psiElement
if (element is KtArrayAccessExpression && element.arrayExpression != null) {
return ArrayAccessorImportFix(element, listOf(importName(diagnostic)))
}
return null
}
}
}
internal class DelegateAccessorsImportFix(
element: KtExpression,
override val importNames: Collection<Name>,
private val solveSeveralProblems: Boolean,
private val diagnostic: Diagnostic,
) : OrdinaryImportFixBase<KtExpression>(element, MyFactory) {
override fun getCallTypeAndReceiver() = CallTypeAndReceiver.DELEGATE(element)
override fun createAction(project: Project, editor: Editor, element: KtExpression): KotlinAddImportAction {
if (solveSeveralProblems) {
return createGroupedImportsAction(
project, editor, element,
KotlinBundle.message("fix.import.kind.delegate.accessors"),
suggestions
)
}
return super.createAction(project, editor, element)
}
override fun getReceiverTypeFromDiagnostic(): KotlinType? =
if (diagnostic.factory === Errors.DELEGATE_SPECIAL_FUNCTION_MISSING) Errors.DELEGATE_SPECIAL_FUNCTION_MISSING.cast(diagnostic).b else null
companion object MyFactory : FactoryWithUnresolvedReferenceQuickFix() {
private fun importNames(diagnostics: Collection<Diagnostic>): Collection<Name> {
return diagnostics.map {
val missingMethodSignature =
if (it.factory === Errors.DELEGATE_SPECIAL_FUNCTION_MISSING) {
Errors.DELEGATE_SPECIAL_FUNCTION_MISSING.cast(it).a
} else {
Errors.DELEGATE_SPECIAL_FUNCTION_NONE_APPLICABLE.cast(it).a
}
if (missingMethodSignature.startsWith(OperatorNameConventions.GET_VALUE.identifier))
OperatorNameConventions.GET_VALUE
else
OperatorNameConventions.SET_VALUE
}.plus(OperatorNameConventions.PROVIDE_DELEGATE).distinct()
}
override fun createImportAction(diagnostic: Diagnostic): DelegateAccessorsImportFix? {
val expression = diagnostic.psiElement as? KtExpression ?: return null
val importNames = importNames(listOf(diagnostic))
return DelegateAccessorsImportFix(expression, importNames, false, diagnostic)
}
override fun createImportActionsForAllProblems(sameTypeDiagnostics: Collection<Diagnostic>): List<DelegateAccessorsImportFix> {
val diagnostic = sameTypeDiagnostics.first()
val element = diagnostic.psiElement
val expression = element as? KtExpression ?: return emptyList()
val names = importNames(sameTypeDiagnostics)
return listOf(DelegateAccessorsImportFix(expression, names, true, diagnostic))
}
}
}
internal class ComponentsImportFix(
element: KtExpression,
override val importNames: Collection<Name>,
private val solveSeveralProblems: Boolean
) : OrdinaryImportFixBase<KtExpression>(element, MyFactory) {
override fun getCallTypeAndReceiver() = element?.let { CallTypeAndReceiver.OPERATOR(it) }
override fun createAction(project: Project, editor: Editor, element: KtExpression): KotlinAddImportAction {
if (solveSeveralProblems) {
return createGroupedImportsAction(
project, editor, element,
KotlinBundle.message("fix.import.kind.component.functions"),
suggestions
)
}
return super.createAction(project, editor, element)
}
companion object MyFactory : FactoryWithUnresolvedReferenceQuickFix() {
private fun importNames(diagnostics: Collection<Diagnostic>) =
diagnostics.map { Name.identifier(Errors.COMPONENT_FUNCTION_MISSING.cast(it).a.identifier) }
override fun createImportAction(diagnostic: Diagnostic) =
(diagnostic.psiElement as? KtExpression)?.let {
ComponentsImportFix(it, importNames(listOf(diagnostic)), false)
}
override fun createImportActionsForAllProblems(sameTypeDiagnostics: Collection<Diagnostic>): List<ComponentsImportFix> {
val element = sameTypeDiagnostics.first().psiElement
val names = importNames(sameTypeDiagnostics)
val solveSeveralProblems = sameTypeDiagnostics.size > 1
val expression = element as? KtExpression ?: return emptyList()
return listOf(ComponentsImportFix(expression, names, solveSeveralProblems))
}
}
}
internal open class ImportForMismatchingArgumentsFix(
expression: KtSimpleNameExpression, factory: Factory
) : ImportFixBase<KtSimpleNameExpression>(expression, factory) {
override fun getCallTypeAndReceiver() = element?.let { CallTypeAndReceiver.detect(it) }
override val importNames = element?.mainReference?.resolvesByNames ?: emptyList()
override fun elementsToCheckDiagnostics(): Collection<PsiElement> {
val element = element ?: return emptyList()
return when (val parent = element.parent) {
is KtCallExpression -> parent.valueArguments +
parent.valueArguments.mapNotNull { it.getArgumentExpression() } +
parent.valueArguments.mapNotNull { it.getArgumentName()?.referenceExpression } +
listOfNotNull(parent.valueArgumentList, parent.referenceExpression(), parent.typeArgumentList)
is KtBinaryExpression -> listOf(element)
else -> emptyList()
}
}
override fun fillCandidates(
name: String,
callTypeAndReceiver: CallTypeAndReceiver<*, *>,
bindingContext: BindingContext,
indicesHelper: KotlinIndicesHelper
): List<DeclarationDescriptor> {
val element = element ?: return emptyList()
if (!Name.isValidIdentifier(name)) return emptyList()
val identifier = Name.identifier(name)
val call = element.getParentCall(bindingContext) ?: return emptyList()
val callElement = call.callElement as? KtExpression ?: return emptyList()
if (callElement.anyDescendantOfType<PsiErrorElement>()) return emptyList() // incomplete call
val elementToAnalyze = callElement.getQualifiedExpressionForSelectorOrThis()
val file = element.containingKtFile
val resolutionFacade = file.getResolutionFacade()
val resolutionScope = elementToAnalyze.getResolutionScope(bindingContext, resolutionFacade)
val imported = resolutionScope.collectFunctions(identifier, NoLookupLocation.FROM_IDE)
fun filterFunction(descriptor: FunctionDescriptor): Boolean {
if (!callTypeAndReceiver.callType.descriptorKindFilter.accepts(descriptor)) return false
val original = descriptor.original
if (original in imported) return false // already imported
// check that this function matches all arguments
val resolutionScopeWithAddedImport = resolutionScope.addImportingScope(ExplicitImportsScope(listOf(original)))
val dataFlowInfo = bindingContext.getDataFlowInfoBefore(elementToAnalyze)
val newBindingContext = elementToAnalyze.analyzeInContext(
resolutionScopeWithAddedImport,
dataFlowInfo = dataFlowInfo,
contextDependency = ContextDependency.DEPENDENT // to not check complete inference
)
return newBindingContext.diagnostics.none { it.severity == Severity.ERROR }
}
val result = ArrayList<FunctionDescriptor>()
fun processDescriptor(descriptor: CallableDescriptor) {
if (descriptor is FunctionDescriptor && filterFunction(descriptor)) {
result.add(descriptor)
}
}
indicesHelper
.getCallableTopLevelExtensions(callTypeAndReceiver, element, bindingContext, receiverTypeFromDiagnostic = null) { it == name }
.forEach(::processDescriptor)
if (!isSelectorInQualified(element)) {
indicesHelper
.getTopLevelCallablesByName(name)
.forEach(::processDescriptor)
}
return result
}
companion object MyFactory : AbstractImportForMismatchingArgumentsFixFactory()
}
internal abstract class AbstractImportForMismatchingArgumentsFixFactory : ImportFixBase.Factory() {
override fun createImportAction(diagnostic: Diagnostic): ImportForMismatchingArgumentsFix? {
val element = diagnostic.psiElement
val nameExpression = element.takeIf { it.elementType == KtNodeTypes.OPERATION_REFERENCE }.safeAs<KtSimpleNameExpression>()
?: element.getStrictParentOfType<KtCallExpression>()?.calleeExpression?.safeAs<KtNameReferenceExpression>()
?: return null
return ImportForMismatchingArgumentsFix(nameExpression, this)
}
}
internal object ImportForMismatchingArgumentsFixFactoryWithUnresolvedReferenceQuickFix : AbstractImportForMismatchingArgumentsFixFactory(),
UnresolvedReferenceQuickFixFactory
internal object ImportForMissingOperatorFactory : ImportFixBase.Factory() {
override fun createImportAction(diagnostic: Diagnostic): ImportFixBase<*>? {
val element = diagnostic.psiElement as? KtExpression ?: return null
val operatorDescriptor = Errors.OPERATOR_MODIFIER_REQUIRED.cast(diagnostic).a
when (val name = operatorDescriptor.name) {
OperatorNameConventions.GET, OperatorNameConventions.SET -> {
if (element is KtArrayAccessExpression) {
return object : ArrayAccessorImportFix(element, listOf(name)) {
override val supportedErrors = setOf(Errors.OPERATOR_MODIFIER_REQUIRED)
}
}
}
}
return null
}
}
private fun KotlinIndicesHelper.getClassesByName(expressionForPlatform: KtExpression, name: String): Collection<ClassDescriptor> =
if (expressionForPlatform.containingKtFile.platform.isJvm()) {
getJvmClassesByName(name)
} else {
val result = mutableListOf<ClassDescriptor>()
val processor = Processors.cancelableCollectProcessor(result)
// Enum entries should be contributed with members import fix
processKotlinClasses(
nameFilter = { it == name },
// Enum entries should be contributed with members import fix
psiFilter = { ktDeclaration -> ktDeclaration !is KtEnumEntry },
kindFilter = { kind -> kind != ClassKind.ENUM_ENTRY },
processor = processor::process
)
result
}
private fun CallTypeAndReceiver<*, *>.toFilter() = { descriptor: DeclarationDescriptor ->
callType.descriptorKindFilter.accepts(descriptor)
}
object AbstractImportFixInfo {
@Volatile
internal var IGNORE_MODULE_ERROR = false
@TestOnly
fun ignoreModuleError(disposable: Disposable) {
IGNORE_MODULE_ERROR = true
Disposer.register(disposable) { IGNORE_MODULE_ERROR = false }
}
} | apache-2.0 | 2ffdd587110c2e48ff7c1ee9c6a61ba4 | 44.536017 | 146 | 0.693312 | 5.601381 | false | false | false | false |
allotria/intellij-community | plugins/editorconfig/src/org/editorconfig/language/filetype/EditorConfigFileType.kt | 5 | 965 | // Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.editorconfig.language.filetype
import com.intellij.icons.AllIcons
import com.intellij.openapi.fileTypes.LanguageFileType
import com.intellij.openapi.vfs.CharsetToolkit
import com.intellij.openapi.vfs.VirtualFile
import org.editorconfig.language.EditorConfigLanguage
import org.editorconfig.language.messages.EditorConfigBundle
import javax.swing.Icon
object EditorConfigFileType : LanguageFileType(EditorConfigLanguage) {
override fun getName() = EditorConfigFileConstants.FILETYPE_NAME
override fun getDescription() = EditorConfigBundle.get("file.type.description")
override fun getDefaultExtension() = EditorConfigFileConstants.FILE_EXTENSION
override fun getIcon(): Icon? = AllIcons.Nodes.Editorconfig
override fun getCharset(file: VirtualFile, content: ByteArray): String = CharsetToolkit.UTF8
}
| apache-2.0 | 63446435212387cc239e23bb04c6128c | 52.611111 | 140 | 0.830052 | 4.707317 | false | true | false | false |
Skatteetaten/boober | src/main/kotlin/no/skatteetaten/aurora/boober/model/openshift/AuroreAzureApp.kt | 1 | 1425 | package no.skatteetaten.aurora.boober.model.openshift
import com.fasterxml.jackson.annotation.JsonIgnore
import com.fasterxml.jackson.annotation.JsonIgnoreProperties
import com.fasterxml.jackson.annotation.JsonInclude
import com.fasterxml.jackson.annotation.JsonPropertyOrder
import io.fabric8.kubernetes.api.model.HasMetadata
import io.fabric8.kubernetes.api.model.ObjectMeta
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonPropertyOrder(value = ["apiVersion", "kind", "metadata", "spec"])
data class AuroraAzureApp(
val spec: AzureAppSpec,
@JsonIgnore
var _metadata: ObjectMeta?,
@JsonIgnore
val _kind: String = "AuroraAzureApp",
@JsonIgnore
var _apiVersion: String = "skatteetaten.no/v1"
) : HasMetadata {
override fun getMetadata(): ObjectMeta {
return _metadata ?: ObjectMeta()
}
override fun getKind(): String {
return _kind
}
override fun getApiVersion(): String {
return _apiVersion
}
override fun setMetadata(metadata: ObjectMeta?) {
_metadata = metadata
}
override fun setApiVersion(version: String?) {
_apiVersion = apiVersion
}
}
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonInclude(JsonInclude.Include.NON_NULL)
data class AzureAppSpec(
val azureAppFqdn: String,
val appName: String,
val groups: List<String>,
val noProxy: Boolean
)
| apache-2.0 | 94e579c50edb3298def33ef733be8a17 | 27.5 | 70 | 0.726316 | 4.318182 | false | false | false | false |
Kotlin/kotlinx.coroutines | benchmarks/src/jmh/kotlin/benchmarks/scheduler/actors/CycledActorsBenchmark.kt | 1 | 4683 | /*
* Copyright 2016-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
*/
package benchmarks.scheduler.actors
import benchmarks.*
import benchmarks.akka.*
import benchmarks.scheduler.actors.PingPongActorBenchmark.*
import kotlinx.coroutines.*
import kotlinx.coroutines.channels.*
import org.openjdk.jmh.annotations.*
import java.util.concurrent.*
/*
* Cores count actors chained into single cycle pass message and process it using its private state.
*
* Benchmark (actorStateSize) (dispatcher) Mode Cnt Score Error Units
* CycledActorsBenchmark.cycledActors 1 fjp avgt 14 22.751 ± 1.351 ms/op
* CycledActorsBenchmark.cycledActors 1 ftp_1 avgt 14 4.535 ± 0.076 ms/op
* CycledActorsBenchmark.cycledActors 1 experimental avgt 14 6.728 ± 0.048 ms/op
*
* CycledActorsBenchmark.cycledActors 1024 fjp avgt 14 43.725 ± 14.393 ms/op
* CycledActorsBenchmark.cycledActors 1024 ftp_1 avgt 14 13.827 ± 1.554 ms/op
* CycledActorsBenchmark.cycledActors 1024 experimental avgt 14 23.823 ± 1.643 ms/op
*
* CycledActorsBenchmark.cycledActors 262144 fjp avgt 14 1885.708 ± 532.634 ms/op
* CycledActorsBenchmark.cycledActors 262144 ftp_1 avgt 14 1394.997 ± 101.938 ms/op
* CycledActorsBenchmark.cycledActors 262144 experimental avgt 14 1804.146 ± 57.275 ms/op
*/
@Warmup(iterations = 5, time = 1, timeUnit = TimeUnit.SECONDS)
@Measurement(iterations = 5, time = 1, timeUnit = TimeUnit.SECONDS)
@Fork(value = 1)
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.MILLISECONDS)
@State(Scope.Benchmark)
open class CycledActorsBenchmark : ParametrizedDispatcherBase() {
companion object {
val NO_CHANNEL = Channel<Letter>(0)
}
@Param("fjp", "ftp_1", "scheduler")
override var dispatcher: String = "fjp"
@Param("1", "1024")
var actorStateSize = 1
@Benchmark
fun cycledActors() = runBlocking {
val stopChannel = Channel<Unit>(CORES_COUNT)
runCycle(stopChannel)
repeat(CORES_COUNT) {
stopChannel.receive()
}
}
private suspend fun runCycle(stopChannel: Channel<Unit>) {
val trailingActor = lastActor(stopChannel)
var previous = trailingActor
for (i in 1 until CORES_COUNT) {
previous = createActor(previous, stopChannel)
}
trailingActor.send(Letter(Start(), previous))
}
private fun lastActor(stopChannel: Channel<Unit>) = actor<Letter>(capacity = 1024) {
var nextChannel: SendChannel<Letter>? = null
val state = LongArray(actorStateSize) { ThreadLocalRandom.current().nextLong(1024) }
for (letter in channel) with(letter) {
when (message) {
is Start -> {
nextChannel = sender
sender.send(Letter(Ball(ThreadLocalRandom.current().nextInt(1, 100)), NO_CHANNEL))
}
is Ball -> {
nextChannel!!.send(Letter(Ball(transmogrify(message.count, state)), NO_CHANNEL))
}
is Stop -> {
stopChannel.send(Unit)
return@actor
}
else -> error("Can't happen")
}
}
}
private fun createActor(nextActor: SendChannel<Letter>, stopChannel: Channel<Unit>) = actor<Letter>(capacity = 1024) {
var received = 0
val state = LongArray(actorStateSize) { ThreadLocalRandom.current().nextLong(1024) }
for (letter in channel) with(letter) {
when (message) {
is Ball -> {
if (++received > 1_000) {
nextActor.send(Letter(Stop(), NO_CHANNEL))
stopChannel.send(Unit)
return@actor
} else {
nextActor.send(Letter(Ball(transmogrify(message.count, state)), NO_CHANNEL))
}
}
is Stop -> {
nextActor.send(Letter(Stop(), NO_CHANNEL))
stopChannel.send(Unit)
}
else -> error("Can't happen")
}
}
}
private fun transmogrify(value: Int, coefficients: LongArray): Int {
var result = 0L
for (coefficient in coefficients) {
result += coefficient * value
}
return result.toInt()
}
}
| apache-2.0 | 146571f5c5d1f60adc7a4b34113180d8 | 37 | 122 | 0.573599 | 4.162066 | false | false | false | false |
intellij-purescript/intellij-purescript | lexer/src/main/kotlin/org/purescript/parser/PSTokens.kt | 1 | 4044 | package org.purescript.parser
import com.intellij.psi.tree.TokenSet
import org.purescript.psi.PSElementType
@JvmField val LAYOUT_START = PSElementType("layout start")
@JvmField val LAYOUT_SEP = PSElementType("layout separator")
@JvmField val LAYOUT_END = PSElementType("layout end")
@JvmField val MLCOMMENT = PSElementType("block comment")
@JvmField val SLCOMMENT = PSElementType("line comment")
@JvmField val DOC_COMMENT = PSElementType("doc comment")
@JvmField val DATA = PSElementType("data")
@JvmField val NEWTYPE = PSElementType("newtype")
@JvmField val TYPE = PSElementType("type")
@JvmField val FOREIGN = PSElementType("foreign")
@JvmField val IMPORT = PSElementType("import")
@JvmField val INFIXL = PSElementType("infixl")
@JvmField val INFIXR = PSElementType("infixr")
@JvmField val INFIX = PSElementType("infix")
@JvmField val CLASS = PSElementType("class")
@JvmField val KIND = PSElementType("kind")
@JvmField val INSTANCE = PSElementType("instance")
@JvmField val DERIVE = PSElementType("derive")
@JvmField val MODULE = PSElementType("module")
@JvmField val CASE = PSElementType("case")
@JvmField val OF = PSElementType("of")
@JvmField val IF = PSElementType("if")
@JvmField val THEN = PSElementType("then")
@JvmField val ELSE = PSElementType("else")
@JvmField val DO = PSElementType("do")
@JvmField val ADO = PSElementType("ado")
@JvmField val LET = PSElementType("let")
@JvmField val TRUE = PSElementType("true")
@JvmField val FALSE = PSElementType("false")
@JvmField val IN = PSElementType("in")
@JvmField val WHERE = PSElementType("where")
@JvmField val FORALL = PSElementType("forall") // contextual keyword
// TODO kings - I think qualified on import is gone now and can be removed
@JvmField val QUALIFIED = PSElementType("qualified") // contextual keyword
@JvmField val HIDING = PSElementType("hiding") // contextual keyword
@JvmField val AS = PSElementType("as") // contextual keyword
@JvmField val DARROW = PSElementType("=>")
@JvmField val LDARROW = PSElementType("<=")
@JvmField val ARROW = PSElementType("->")
@JvmField val LARROW = PSElementType("<-")
@JvmField val EQ = PSElementType("=")
@JvmField val DOT = PSElementType(".")
@JvmField val DDOT = PSElementType("..") // contextual keyword
@JvmField val SEMI = PSElementType(";")
@JvmField val DCOLON = PSElementType("::")
@JvmField val TICK = PSElementType("`")
@JvmField val PIPE = PSElementType("|")
@JvmField val COMMA = PSElementType(",")
@JvmField val LPAREN = PSElementType("(")
@JvmField val RPAREN = PSElementType(")")
@JvmField val LBRACK = PSElementType("[")
@JvmField val RBRACK = PSElementType("]")
@JvmField val LCURLY = PSElementType("{")
@JvmField val RCURLY = PSElementType("}")
@JvmField val START = PSElementType("*")
@JvmField val BANG = PSElementType("!")
@JvmField val BACKSLASH = PSElementType("\\")
@JvmField val OPERATOR = PSElementType("operator")
@JvmField val MODULE_PREFIX = PSElementType("module prefix")
@JvmField val PROPER_NAME = PSElementType("proper name")
@JvmField val IDENT = PSElementType("identifier")
@JvmField val STRING_ESCAPED = PSElementType("string escaping")
@JvmField val STRING_GAP = PSElementType("string escaping")
@JvmField val STRING_ERROR = PSElementType("string escaping error")
@JvmField val STRING = PSElementType("string")
@JvmField val CHAR = PSElementType("char")
@JvmField val NATURAL = PSElementType("natural")
@JvmField val FLOAT = PSElementType("float")
@JvmField val OPTIMISTIC = PSElementType("~>")
@JvmField val kKeywords = TokenSet.create(
DATA,
NEWTYPE,
TYPE,
FOREIGN,
IMPORT,
INFIXL,
INFIXR,
INFIX,
CLASS,
DERIVE,
INSTANCE,
MODULE,
CASE,
OF,
IF,
THEN,
ELSE,
DO,
ADO,
LET,
TRUE,
FALSE,
IN,
WHERE,
FORALL,
QUALIFIED,
HIDING,
AS,
START,
BANG
)
@JvmField val kStrings = TokenSet.create(STRING)
@JvmField val kOperators = TokenSet.create(
DARROW,
LARROW,
LDARROW,
ARROW,
EQ,
DOT,
OPTIMISTIC,
OPERATOR
)
@JvmField val EOF = PSElementType("<<eof>>") | bsd-3-clause | 25b5ed89ef6b0146d576fc4171a68b9b | 32.991597 | 74 | 0.719832 | 4.023881 | false | false | false | false |
bitsydarel/DBWeather | app/src/main/java/com/dbeginc/dbweather/utils/preferences/ApplicationPreferences.kt | 1 | 4041 | /*
* Copyright (C) 2017 Darel Bitsy
* 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.dbeginc.dbweather.utils.preferences
import android.content.SharedPreferences
import com.dbeginc.dbweather.utils.utility.*
import com.dbeginc.dbweathernews.newspapers.NewsPapersViewModel
/**
* Created by darel on 12.11.17.
*
* Application Preferences Manage all configuration
* For the application layer
*/
class ApplicationPreferences(private val sharedPreferences: SharedPreferences) {
fun getDefaultLatitude(): Double = sharedPreferences.getDouble(CURRENT_LATITUDE)
fun getDefaultLongitude(): Double = sharedPreferences.getDouble(CURRENT_LONGITUDE)
fun getDefaultCity(): String = sharedPreferences.getString(CURRENT_CITY, "")
fun getDefaultCountryCode(): String = sharedPreferences.getString(CURRENT_COUNTRY_CODE, "")
fun getCustomLatitude(): Double = sharedPreferences.getDouble(CUSTOM_LATITUDE)
fun getCustomLongitude(): Double = sharedPreferences.getDouble(CUSTOM_LONGITUDE)
fun getCustomCity(): String = sharedPreferences.getString(CUSTOM_CITY, "")
fun getCustomCountryCode(): String = sharedPreferences.getString(CUSTOM_COUNTRY_CODE, "")
fun updateDefaultCoordinates(city: String, countryCode: String, latitude: Double, longitude: Double) {
sharedPreferences.edit()
.putString(CURRENT_CITY, city)
.putString(CURRENT_COUNTRY_CODE, countryCode)
.putDouble(CURRENT_LATITUDE, latitude)
.putDouble(CURRENT_LONGITUDE, longitude)
.apply()
}
fun updateCustomCoordinates(city: String, countryCode: String, latitude: Double, longitude: Double) {
sharedPreferences.edit()
.putString(CUSTOM_CITY, city)
.putString(CUSTOM_COUNTRY_CODE, countryCode)
.putDouble(CUSTOM_LATITUDE, latitude)
.putDouble(CUSTOM_LONGITUDE, longitude)
.apply()
}
fun changeGpsPermissionStatus(isOn: Boolean) = sharedPreferences.edit().putBoolean(IS_GPS_PERMISSION_GRANTED, isOn).apply()
fun isGpsPermissionOn(): Boolean = sharedPreferences.getBoolean(IS_GPS_PERMISSION_GRANTED, false)
fun updateCurrentLocationType(isDefault: Boolean) = sharedPreferences.edit().putBoolean(IS_GPS_LOCATION, isDefault).apply()
fun isCurrentLocationDefault(): Boolean = sharedPreferences.getBoolean(IS_GPS_LOCATION, false)
fun changeDefaultLocationStatus(isFromGps: Boolean) = sharedPreferences.edit().putBoolean(IS_GPS_LOCATION, isFromGps).apply()
fun isFirstLaunchOfApplication(): Boolean = sharedPreferences.getBoolean(FIRST_RUN, true)
fun changeFirstLaunchStatus() = sharedPreferences.edit().putBoolean(FIRST_RUN, false).apply()
fun getNewsPaperPreferredOrder(): Int = sharedPreferences.getInt(SOURCE_SORTING_PREFERENCES, NewsPapersViewModel.SORT_BY_NAME)
fun getYoutubeLivesPreferredOrder(): Int = sharedPreferences.getInt(YOUTUBE_LIVES_SORTING_PREFERENCES, NewsPapersViewModel.SORT_BY_NAME)
fun isNewsTranslationOn(): Boolean = sharedPreferences.getBoolean(NEWS_TRANSLATION_STATUS, false)
fun isWeatherNotificationOn(): Boolean = sharedPreferences.getBoolean(WEATHER_NOTIFICATION_STATUS, false)
fun changeNewsTranslationStatus(enabled: Boolean) = sharedPreferences.edit().putBoolean(NEWS_TRANSLATION_STATUS, enabled).apply()
fun changeWeatherNotificationStatus(enabled: Boolean) = sharedPreferences.edit().putBoolean(WEATHER_NOTIFICATION_STATUS, enabled).apply()
} | gpl-3.0 | 368d154e0bce70de6de1311a2c27fe2d | 43.911111 | 141 | 0.74635 | 4.720794 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/core/src/org/jetbrains/kotlin/idea/core/overrideImplement/OverrideImplementMembersHandler.kt | 1 | 7980 | // 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.core.overrideImplement
import com.intellij.codeInsight.FileModificationService
import com.intellij.codeInsight.hint.HintManager
import com.intellij.ide.util.MemberChooser
import com.intellij.lang.LanguageCodeInsightActionHandler
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.DialogWrapper
import com.intellij.openapi.util.NlsContexts
import com.intellij.psi.PsiDocumentManager
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
import com.intellij.psi.util.PsiTreeUtil
import org.jetbrains.kotlin.descriptors.CallableMemberDescriptor
import org.jetbrains.kotlin.descriptors.ClassDescriptor
import org.jetbrains.kotlin.idea.caches.resolve.resolveToDescriptorIfAny
import org.jetbrains.kotlin.idea.core.insertMembersAfter
import org.jetbrains.kotlin.idea.search.usagesSearch.descriptor
import org.jetbrains.kotlin.idea.util.application.isUnitTestMode
import org.jetbrains.kotlin.psi.KtClassOrObject
import org.jetbrains.kotlin.psi.KtDeclaration
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.psi.KtParameter
import org.jetbrains.kotlin.psi.psiUtil.getNonStrictParentOfType
import org.jetbrains.kotlin.psi.psiUtil.prevSiblingOfSameType
import org.jetbrains.kotlin.psi.psiUtil.startOffset
import org.jetbrains.kotlin.resolve.DescriptorUtils
import org.jetbrains.kotlin.resolve.source.getPsi
import org.jetbrains.kotlin.util.findCallableMemberBySignature
import org.jetbrains.kotlin.utils.addToStdlib.firstNotNullResult
abstract class OverrideImplementMembersHandler : LanguageCodeInsightActionHandler {
fun collectMembersToGenerate(classOrObject: KtClassOrObject): Collection<OverrideMemberChooserObject> {
val descriptor = classOrObject.resolveToDescriptorIfAny() ?: return emptySet()
return collectMembersToGenerate(descriptor, classOrObject.project)
}
protected abstract fun collectMembersToGenerate(descriptor: ClassDescriptor, project: Project): Collection<OverrideMemberChooserObject>
private fun showOverrideImplementChooser(
project: Project,
members: Array<OverrideMemberChooserObject>
): MemberChooser<OverrideMemberChooserObject>? {
val chooser = MemberChooser(members, true, true, project)
chooser.title = getChooserTitle()
chooser.show()
if (chooser.exitCode != DialogWrapper.OK_EXIT_CODE) return null
return chooser
}
@NlsContexts.DialogTitle
protected abstract fun getChooserTitle(): String
protected open fun isValidForClass(classOrObject: KtClassOrObject) = true
override fun isValidFor(editor: Editor, file: PsiFile): Boolean {
if (file !is KtFile) return false
val elementAtCaret = file.findElementAt(editor.caretModel.offset)
val classOrObject = elementAtCaret?.getNonStrictParentOfType<KtClassOrObject>()
return classOrObject != null && isValidForClass(classOrObject)
}
@NlsContexts.HintText
protected abstract fun getNoMembersFoundHint(): String
fun invoke(project: Project, editor: Editor, file: PsiFile, implementAll: Boolean) {
val elementAtCaret = file.findElementAt(editor.caretModel.offset)
val classOrObject = elementAtCaret?.getNonStrictParentOfType<KtClassOrObject>() ?: return
if (!FileModificationService.getInstance().prepareFileForWrite(file)) return
val members = collectMembersToGenerate(classOrObject)
if (members.isEmpty() && !implementAll) {
HintManager.getInstance().showErrorHint(editor, getNoMembersFoundHint())
return
}
val copyDoc: Boolean
val selectedElements: Collection<OverrideMemberChooserObject>
if (implementAll) {
selectedElements = members
copyDoc = false
} else {
val chooser = showOverrideImplementChooser(project, members.toTypedArray()) ?: return
selectedElements = chooser.selectedElements ?: return
copyDoc = chooser.isCopyJavadoc
}
if (selectedElements.isEmpty()) return
PsiDocumentManager.getInstance(project).commitAllDocuments()
generateMembers(editor, classOrObject, selectedElements, copyDoc)
}
override fun invoke(project: Project, editor: Editor, file: PsiFile) {
invoke(project, editor, file, implementAll = isUnitTestMode())
}
override fun startInWriteAction(): Boolean = false
companion object {
fun generateMembers(
editor: Editor?,
classOrObject: KtClassOrObject,
selectedElements: Collection<OverrideMemberChooserObject>,
copyDoc: Boolean
) {
val selectedMemberDescriptors = selectedElements.associate { it.generateMember(classOrObject, copyDoc) to it.descriptor }
val classBody = classOrObject.body
if (classBody == null) {
insertMembersAfter(editor, classOrObject, selectedMemberDescriptors.keys)
return
}
val offset = editor?.caretModel?.offset ?: classBody.startOffset
val offsetCursorElement = PsiTreeUtil.findFirstParent(classBody.containingFile.findElementAt(offset)) {
it.parent == classBody
}
if (offsetCursorElement != null && offsetCursorElement != classBody.rBrace) {
insertMembersAfter(editor, classOrObject, selectedMemberDescriptors.keys)
return
}
val classLeftBrace = classBody.lBrace
val allSuperMemberDescriptors = selectedMemberDescriptors.values
.mapNotNull { it.containingDeclaration as? ClassDescriptor }
.associateWith {
DescriptorUtils.getAllDescriptors(it.unsubstitutedMemberScope).filterIsInstance<CallableMemberDescriptor>()
}
val implementedElements = mutableMapOf<CallableMemberDescriptor, KtDeclaration>()
fun ClassDescriptor.findElement(memberDescriptor: CallableMemberDescriptor): KtDeclaration? {
return implementedElements[memberDescriptor]
?: (findCallableMemberBySignature(memberDescriptor)?.source?.getPsi() as? KtDeclaration)
?.takeIf { it != classOrObject && it !is KtParameter }
?.also { implementedElements[memberDescriptor] = it }
}
fun getAnchor(selectedElement: KtDeclaration): PsiElement? {
val lastElement = classOrObject.declarations.lastOrNull()
val selectedMemberDescriptor = selectedMemberDescriptors[selectedElement] ?: return lastElement
val superMemberDescriptors = allSuperMemberDescriptors[selectedMemberDescriptor.containingDeclaration] ?: return lastElement
val index = superMemberDescriptors.indexOf(selectedMemberDescriptor.original)
if (index == -1) return lastElement
val classDescriptor = classOrObject.descriptor as? ClassDescriptor ?: return lastElement
val upperElement = ((index - 1) downTo 0).firstNotNullResult {
classDescriptor.findElement(superMemberDescriptors[it])
}
if (upperElement != null) return upperElement
val lowerElement = ((index + 1) until superMemberDescriptors.size).firstNotNullResult {
classDescriptor.findElement(superMemberDescriptors[it])
}
if (lowerElement != null) return lowerElement.prevSiblingOfSameType() ?: classLeftBrace
return lastElement
}
insertMembersAfter(editor, classOrObject, selectedMemberDescriptors.keys) { getAnchor(it) }
}
}
}
| apache-2.0 | d0b82efa3b462847d7baf15dc2dd0a04 | 46.5 | 158 | 0.715038 | 5.778421 | false | false | false | false |
smmribeiro/intellij-community | plugins/git4idea/src/git4idea/branch/GitCompareUtil.kt | 10 | 3514 | // 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 git4idea.branch
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.vcs.log.data.index.IndexDataGetter
import com.intellij.vcs.log.impl.HashImpl
import com.intellij.vcs.log.util.IntCollectionUtil
import com.intellij.vcs.log.util.VcsLogUtil
import it.unimi.dsi.fastutil.ints.IntOpenHashSet
import it.unimi.dsi.fastutil.ints.IntSet
import java.util.regex.Pattern
fun IndexDataGetter.match(root: VirtualFile,
sourceBranchCommits: IntSet,
targetBranchCommits: IntSet,
reliable: Boolean = true): IntSet {
val timeToSourceCommit = IntCollectionUtil.groupByAsIntSet(sourceBranchCommits) { getAuthorTime(it) }
val authorToSourceCommit = IntCollectionUtil.groupByAsIntSet(sourceBranchCommits) { getAuthor(it) }
val result = IntOpenHashSet()
for (targetCommit in targetBranchCommits) {
val time = getAuthorTime(targetCommit)
val author = getAuthor(targetCommit)
val commitsForAuthor = authorToSourceCommit[author] ?: IntOpenHashSet()
val sourceCandidates = IntCollectionUtil.intersect(timeToSourceCommit[time] ?: IntOpenHashSet(), commitsForAuthor) ?: continue
if (!sourceCandidates.isEmpty()) {
result.addAll(selectSourceCommits(targetCommit, root, sourceCandidates, commitsForAuthor, reliable))
}
}
return result
}
private const val suffixStart = "cherry picked from commit" //NON-NLS
private val suffixPattern = Pattern.compile("$suffixStart.*\\)")
private fun IndexDataGetter.selectSourceCommits(targetCommit: Int,
root: VirtualFile,
sourceCandidates: IntSet,
sourceCandidatesExtended: IntSet,
reliable: Boolean): IntSet {
val targetMessage = getFullMessage(targetCommit) ?: return IntSet.of()
val result = IntOpenHashSet()
val matcher = suffixPattern.matcher(targetMessage)
while (matcher.find()) {
val match = targetMessage.subSequence(matcher.start(), matcher.end())
val hashesString = match.subSequence(suffixStart.length, match.length - 1) // -1 for the last ")"
val hashesCandidates = hashesString.split(",", " ", ";")
for (h in hashesCandidates) {
if (VcsLogUtil.HASH_REGEX.matcher(h).matches()) {
val hash = HashImpl.build(h)
val index = logStorage.getCommitIndex(hash, root)
if (sourceCandidatesExtended.contains(index)) {
result.add(index)
}
}
}
if (IntCollectionUtil.intersects(sourceCandidates, result)) return result // target time should match one of sources time
}
if (!reliable) {
val inexactMatches = mutableSetOf<Int>()
val exactMatches = mutableSetOf<Int>()
for (sourceCandidate in sourceCandidates) {
val sourceMessage = getFullMessage(sourceCandidate) ?: return IntSet.of()
if (targetMessage.contains(sourceMessage)) {
if (targetMessage.length == sourceMessage.length) {
exactMatches.add(sourceCandidate)
}
else {
inexactMatches.add(sourceCandidate)
}
}
}
val match = (if (exactMatches.isNotEmpty()) exactMatches else inexactMatches).singleOrNull()
if (match != null) {
return IntSet.of(match)
}
}
return IntSet.of()
} | apache-2.0 | e779502818f4a8733627cf60d9d27f34 | 40.845238 | 140 | 0.675299 | 4.581486 | false | false | false | false |
smmribeiro/intellij-community | python/src/com/jetbrains/python/ui/ManualPathEntryDialog.kt | 2 | 1905 | // Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.jetbrains.python.ui
import com.intellij.execution.Platform
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.DialogWrapper
import com.intellij.ui.layout.*
import com.jetbrains.python.PyBundle
import javax.swing.JComponent
/**
* The dialog that allows to specify the path to a file or directory manually.
*
* Performs validation that the path that is being added is an absolute path on
* the specified [platform].
*/
class ManualPathEntryDialog(project: Project?, private val platform: Platform) : DialogWrapper(project) {
var path: String = ""
private set
init {
title = PyBundle.message("enter.path.dialog.title")
init()
}
override fun createCenterPanel(): JComponent =
panel {
row(label = PyBundle.message("path.label")) {
textField(prop = ::path).withValidationOnApply { textField ->
val text = textField.text
when {
text.isBlank() -> error(PyBundle.message("path.must.not.be.empty.error.message"))
!isAbsolutePath(text, platform) -> error(PyBundle.message("path.must.be.absolute.error.message"))
text.endsWith(" ") -> warning(PyBundle.message("path.ends.with.whitespace.warning.message"))
else -> null
}
}.focused()
}
}
companion object {
fun isAbsolutePath(path: String, platform: Platform): Boolean = when (platform) {
Platform.UNIX -> path.startsWith("/")
Platform.WINDOWS -> isAbsoluteWindowsPath(path)
}
private fun isAbsoluteWindowsPath(path: String): Boolean =
path.length > 2 && path[1] == ':' && isDriveLetter(path[0]) && path[2] in setOf('\\', '/')
private fun isDriveLetter(c: Char): Boolean = c in 'a'..'z' || c in 'A'..'Z'
}
} | apache-2.0 | c2b85fb98798267988ee17e9ca94a0d7 | 35.653846 | 140 | 0.671916 | 4.087983 | false | false | false | false |
Virtlink/aesi | aesi-intellij/src/main/kotlin/com/virtlink/editorservices/intellij/structureoutline/AesiStructureViewModel.kt | 1 | 4929 | package com.virtlink.editorservices.intellij.structureoutline
import com.google.inject.Inject
import com.google.inject.assistedinject.Assisted
import com.intellij.ide.structureView.StructureViewTreeElement
import com.intellij.ide.structureView.TextEditorBasedStructureViewModel
import com.intellij.ide.structureView.impl.common.PsiTreeElementBase
import com.intellij.openapi.editor.Editor
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
import com.intellij.psi.util.PsiTreeUtil
import com.intellij.util.PlatformIcons
import com.virtlink.editorservices.NullCancellationToken
import com.virtlink.editorservices.intellij.psi.AesiPsiElement
import com.virtlink.editorservices.intellij.resources.IntellijResourceManager
import com.virtlink.editorservices.structureoutline.*
import javax.swing.Icon
class AesiStructureViewModel @Inject constructor(
@Assisted editor: Editor?,
@Assisted psiFile: PsiFile,
private val structureOutlineService: IStructureOutlineService,
private val resourceManager: IntellijResourceManager)
: TextEditorBasedStructureViewModel(editor, psiFile) {
// : StructureViewModelBase(psiFile, editor, null), StructureViewModel.ElementInfoProvider {
interface IFactory {
fun create(editor: Editor?, psiFile: PsiFile): AesiStructureViewModel
}
override fun getRoot(): StructureViewTreeElement {
return RootElement(this.psiFile, this)
}
private inline fun <reified T: PsiElement> findElementAt(offset: Int): T? {
return PsiTreeUtil.getParentOfType(this.psiFile.findElementAt(offset), T::class.java)
}
private fun getRootNodes(): List<IStructureOutlineElement> {
val documentUri = this.resourceManager.getUri(this.psiFile)
return this.structureOutlineService.getRoots(documentUri, NullCancellationToken)?.elements ?: emptyList()
}
private fun getChildNodes(node: IStructureOutlineElement): List<IStructureOutlineElement> {
val documentUri = this.resourceManager.getUri(this.psiFile)
return this.structureOutlineService.getChildren(documentUri, node, NullCancellationToken)?.elements ?: emptyList()
}
private fun createTreeElements(symbols: Collection<IStructureOutlineElement>): MutableCollection<StructureViewTreeElement> {
return symbols.map { this.createTreeElement(it) }.toMutableList()
}
private fun createTreeElement(node: IStructureOutlineElement): StructureViewTreeElement {
val offset = node.nameSpan?.startOffset
val element = (if (offset != null) findElementAt<AesiPsiElement>(offset.toInt()) else null) ?: this.psiFile
return PapljTreeElement(element, node, this)
}
class RootElement<T : PsiElement>(
element: T,
val model: AesiStructureViewModel)
: PsiTreeElementBase<T>(element) {
override fun getIcon(open: Boolean): Icon? = null
override fun getPresentableText(): String? {
return "root"
}
override fun getChildrenBase(): MutableCollection<StructureViewTreeElement> {
return this.model.createTreeElements(this.model.getRootNodes())
}
}
class PapljTreeElement<T : PsiElement>(
element: T,
val node: IStructureOutlineElement,
val model: AesiStructureViewModel)
: PsiTreeElementBase<T>(element) {
override fun getIcon(open: Boolean): Icon? {
return when {
"meta.file" in node.scopes -> PlatformIcons.FILE_ICON
"meta.module" in node.scopes -> PlatformIcons.OPENED_MODULE_GROUP_ICON
"meta.namespace" in node.scopes -> PlatformIcons.PACKAGE_ICON
"meta.package" in node.scopes -> PlatformIcons.PACKAGE_ICON
"meta.class" in node.scopes -> PlatformIcons.CLASS_ICON
"meta.interface" in node.scopes -> PlatformIcons.INTERFACE_ICON
"meta.enum" in node.scopes -> PlatformIcons.ENUM_ICON
"meta.property" in node.scopes -> PlatformIcons.PROPERTY_ICON
"meta.field" in node.scopes -> PlatformIcons.FIELD_ICON
"meta.function" in node.scopes -> PlatformIcons.FUNCTION_ICON
"meta.method" in node.scopes -> PlatformIcons.METHOD_ICON
"meta.constructor" in node.scopes -> PlatformIcons.METHOD_ICON
"meta.variable" in node.scopes -> PlatformIcons.VARIABLE_ICON
"meta.constant" in node.scopes -> PlatformIcons.VARIABLE_READ_ACCESS
else -> PlatformIcons.VARIABLE_READ_ACCESS
}
}
override fun getPresentableText(): String? {
return node.label // ?: "root"
}
override fun getChildrenBase(): MutableCollection<StructureViewTreeElement> {
return this.model.createTreeElements(this.model.getChildNodes(this.node))
}
}
} | apache-2.0 | 7d34ad127fd5a8be2df7ba01b3348fcd | 43.414414 | 128 | 0.702779 | 5.039877 | false | false | false | false |
mdaniel/intellij-community | platform/diff-impl/src/com/intellij/diff/tools/combined/CombinedDiffBlocks.kt | 2 | 6902 | // 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.diff.tools.combined
import com.intellij.diff.FrameDiffTool
import com.intellij.openapi.Disposable
import com.intellij.openapi.actionSystem.*
import com.intellij.openapi.actionSystem.ex.CustomComponentAction
import com.intellij.openapi.extensions.ExtensionPointName
import com.intellij.openapi.fileTypes.FileTypeRegistry
import com.intellij.openapi.project.DumbAwareAction
import com.intellij.openapi.ui.VerticalFlowLayout
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.vcs.FilePath
import com.intellij.openapi.vcs.FileStatus
import com.intellij.ui.IdeBorderFactory
import com.intellij.ui.SideBorder
import com.intellij.ui.SimpleColoredComponent
import com.intellij.ui.SimpleTextAttributes
import com.intellij.ui.components.CheckBox
import com.intellij.ui.components.panels.OpaquePanel
import com.intellij.ui.components.panels.Wrapper
import com.intellij.util.FontUtil
import com.intellij.util.ui.JBEmptyBorder
import com.intellij.util.ui.JBUI
import com.intellij.util.ui.UIUtil
import com.intellij.util.ui.components.BorderLayoutPanel
import java.awt.FlowLayout
import javax.swing.JComponent
import javax.swing.JPanel
interface CombinedBlockId
interface CombinedDiffBlock<ID: CombinedBlockId> : Disposable {
val id: ID
val header: JComponent
val body: JComponent
val component: JComponent
fun updateBlockContent(newContent: CombinedDiffBlockContent) {}
}
interface CombinedDiffGlobalBlockHeaderProvider {
val globalHeader: JComponent
}
class CombinedDiffBlockContent(val viewer: FrameDiffTool.DiffViewer, val blockId: CombinedBlockId)
interface CombinedDiffBlockFactory<ID: CombinedBlockId> {
companion object {
private val EP_COMBINED_DIFF_BLOCK_FACTORY =
ExtensionPointName<CombinedDiffBlockFactory<*>>("com.intellij.diff.tools.combined.diffBlockFactory")
@Suppress("UNCHECKED_CAST")
fun <ID: CombinedBlockId> findApplicable(content: CombinedDiffBlockContent): CombinedDiffBlockFactory<ID>? {
return EP_COMBINED_DIFF_BLOCK_FACTORY.findFirstSafe { it.isApplicable(content) } as? CombinedDiffBlockFactory<ID>
}
}
fun isApplicable(content: CombinedDiffBlockContent): Boolean
fun createBlock(content: CombinedDiffBlockContent, withBorder: Boolean): CombinedDiffBlock<ID>
}
class CombinedSimpleDiffBlockFactory : CombinedDiffBlockFactory<CombinedPathBlockId> {
override fun isApplicable(content: CombinedDiffBlockContent) = true //default factory
override fun createBlock(content: CombinedDiffBlockContent, withBorder: Boolean): CombinedDiffBlock<CombinedPathBlockId> =
with(content.blockId as CombinedPathBlockId) { CombinedSimpleDiffBlock(this, content.viewer.component, withBorder) }
}
private class CombinedSimpleDiffHeader(blockId: CombinedPathBlockId, withBorder: Boolean, withPathOnly: Boolean) : BorderLayoutPanel() {
init {
if (withBorder) {
border = IdeBorderFactory.createBorder(SideBorder.TOP)
}
addToCenter(if (withPathOnly) buildPathComponent(blockId) else buildToolbar(blockId).component)
}
private fun buildPathComponent(blockId: CombinedPathBlockId): JComponent {
background = UIUtil.getListBackground()
return OpaquePanel(FlowLayout(FlowLayout.LEFT, JBUI.scale(3), 0))
.apply {
border = JBEmptyBorder(UIUtil.PANEL_SMALL_INSETS)
add(createTextComponent(blockId.path))
}
}
private fun buildToolbar(blockId: CombinedPathBlockId): ActionToolbar {
val path = blockId.path
val toolbarGroup = DefaultActionGroup()
toolbarGroup.add(CombinedOpenInEditorAction(path))
toolbarGroup.addSeparator()
toolbarGroup.add(SelectableFilePathLabel(path))
val toolbar = ActionManager.getInstance().createActionToolbar("CombinedDiffBlockHeaderToolbar", toolbarGroup, true)
toolbar.targetComponent = this
toolbar.layoutPolicy = ActionToolbar.NOWRAP_LAYOUT_POLICY
toolbar.component.background = UIUtil.getListBackground()
toolbar.component.border = JBEmptyBorder(UIUtil.PANEL_SMALL_INSETS)
toolbarGroup.add(CombinedPrevNextFileAction(blockId, toolbar.component, false))
toolbarGroup.add(CombinedPrevNextFileAction(blockId, toolbar.component, true))
return toolbar
}
private class SelectableFilePathLabel(private val path: FilePath) : DumbAwareAction(), CustomComponentAction {
private val checkBox = CheckBox("").apply { background = UIUtil.getListBackground() }
var selected: Boolean
get() = checkBox.isSelected
set(value) { checkBox.isSelected = value }
fun setSelectable(selectable: Boolean) {
checkBox.isVisible = selectable
}
init {
selected = false
setSelectable(false)
}
override fun actionPerformed(e: AnActionEvent) {}
override fun createCustomComponent(presentation: Presentation, place: String): JComponent {
val textComponent = createTextComponent(path)
val component = OpaquePanel(FlowLayout(FlowLayout.LEFT, JBUI.scale(3), 0))
.apply {
add(checkBox)
add(textComponent)
}
return component
}
}
companion object {
private fun createTextComponent(path: FilePath): JComponent {
return SimpleColoredComponent().append(path.name)
.apply {
val parentPath = path.parentPath?.let(FilePath::getPresentableUrl)?.let(FileUtil::getLocationRelativeToUserHome)
if (parentPath != null) {
append(FontUtil.spaceAndThinSpace() + parentPath, SimpleTextAttributes.GRAYED_ATTRIBUTES)
}
icon = FileTypeRegistry.getInstance().getFileTypeByFileName(path.name).icon
}
}
}
}
data class CombinedPathBlockId(val path: FilePath, val fileStatus: FileStatus, val tag: Any? = null) : CombinedBlockId
private class CombinedSimpleDiffBlock(override val id: CombinedPathBlockId, initialContent: JComponent, notFirstBlock: Boolean) :
JPanel(VerticalFlowLayout(VerticalFlowLayout.TOP, 0, 0, true, true)),
CombinedDiffBlock<CombinedPathBlockId>, CombinedDiffGlobalBlockHeaderProvider {
private val pathOnlyHeader = CombinedSimpleDiffHeader(id, notFirstBlock, true)
private val headerWithToolbar = CombinedSimpleDiffHeader(id, notFirstBlock, false)
override val header = Wrapper(pathOnlyHeader)
override val globalHeader = if (notFirstBlock) CombinedSimpleDiffHeader(id, false, false) else headerWithToolbar
override val body = Wrapper(initialContent)
init {
if (notFirstBlock) {
add(header)
}
add(body)
}
override fun updateBlockContent(newContent: CombinedDiffBlockContent) {
val viewer = newContent.viewer
body.setContent(viewer.component)
header.setContent(if (viewer is CombinedLazyDiffViewer) pathOnlyHeader else headerWithToolbar)
}
override val component = this
override fun dispose() {}
}
| apache-2.0 | e79c5f6c8c84e80a517f5425f8760c7e | 37.558659 | 136 | 0.774413 | 4.576923 | false | false | false | false |
JetBrains/kotlin-native | backend.native/tests/runtime/basic/cleaner_basic.kt | 1 | 5396 | /*
* Copyright 2010-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.
*/
@file:OptIn(ExperimentalStdlibApi::class)
package runtime.basic.cleaner_basic
import kotlin.test.*
import kotlin.native.internal.*
import kotlin.native.concurrent.*
import kotlin.native.ref.WeakReference
class AtomicBoolean(initialValue: Boolean) {
private val impl = AtomicInt(if (initialValue) 1 else 0)
init {
freeze()
}
public var value: Boolean
get() = impl.value != 0
set(new) { impl.value = if (new) 1 else 0 }
}
class FunBox(private val impl: () -> Unit) {
fun call() {
impl()
}
}
@Test
fun testCleanerLambda() {
val called = AtomicBoolean(false);
var funBoxWeak: WeakReference<FunBox>? = null
var cleanerWeak: WeakReference<Cleaner>? = null
{
val cleaner = {
val funBox = FunBox { called.value = true }.freeze()
funBoxWeak = WeakReference(funBox)
createCleaner(funBox) { it.call() }
}()
GC.collect() // Make sure local funBox reference is gone
cleanerWeak = WeakReference(cleaner)
assertFalse(called.value)
}()
GC.collect()
performGCOnCleanerWorker()
assertNull(cleanerWeak!!.value)
assertTrue(called.value)
assertNull(funBoxWeak!!.value)
}
@Test
fun testCleanerAnonymousFunction() {
val called = AtomicBoolean(false);
var funBoxWeak: WeakReference<FunBox>? = null
var cleanerWeak: WeakReference<Cleaner>? = null
{
val cleaner = {
val funBox = FunBox { called.value = true }.freeze()
funBoxWeak = WeakReference(funBox)
createCleaner(funBox, fun (it: FunBox) { it.call() })
}()
GC.collect() // Make sure local funBox reference is gone
cleanerWeak = WeakReference(cleaner)
assertFalse(called.value)
}()
GC.collect()
performGCOnCleanerWorker()
assertNull(cleanerWeak!!.value)
assertTrue(called.value)
assertNull(funBoxWeak!!.value)
}
@Test
fun testCleanerFunctionReference() {
val called = AtomicBoolean(false);
var funBoxWeak: WeakReference<FunBox>? = null
var cleanerWeak: WeakReference<Cleaner>? = null
{
val cleaner = {
val funBox = FunBox { called.value = true }.freeze()
funBoxWeak = WeakReference(funBox)
createCleaner(funBox, FunBox::call)
}()
GC.collect() // Make sure local funBox reference is gone
cleanerWeak = WeakReference(cleaner)
assertFalse(called.value)
}()
GC.collect()
performGCOnCleanerWorker()
assertNull(cleanerWeak!!.value)
assertTrue(called.value)
assertNull(funBoxWeak!!.value)
}
@Test
fun testCleanerFailWithNonShareableArgument() {
val funBox = FunBox {}
assertFailsWith<IllegalArgumentException> {
createCleaner(funBox) {}
}
}
@Test
fun testCleanerCleansWithoutGC() {
val called = AtomicBoolean(false);
var funBoxWeak: WeakReference<FunBox>? = null
var cleanerWeak: WeakReference<Cleaner>? = null
{
val cleaner = {
val funBox = FunBox { called.value = true }.freeze()
funBoxWeak = WeakReference(funBox)
createCleaner(funBox) { it.call() }
}()
GC.collect() // Make sure local funBox reference is gone
cleaner.freeze()
cleanerWeak = WeakReference(cleaner)
assertFalse(called.value)
}()
GC.collect()
assertNull(cleanerWeak!!.value)
waitCleanerWorker()
assertTrue(called.value)
// If this fails, GC has somehow ran on the cleaners worker.
assertNotNull(funBoxWeak!!.value)
}
val globalInt = AtomicInt(0)
@Test
fun testCleanerWithInt() {
var cleanerWeak: WeakReference<Cleaner>? = null
{
val cleaner = createCleaner(42) {
globalInt.value = it
}.freeze()
cleanerWeak = WeakReference(cleaner)
assertEquals(0, globalInt.value)
}()
GC.collect()
performGCOnCleanerWorker()
assertNull(cleanerWeak!!.value)
assertEquals(42, globalInt.value)
}
val globalPtr = AtomicNativePtr(NativePtr.NULL)
@Test
fun testCleanerWithNativePtr() {
var cleanerWeak: WeakReference<Cleaner>? = null
{
val cleaner = createCleaner(NativePtr.NULL + 42L) {
globalPtr.value = it
}
cleanerWeak = WeakReference(cleaner)
assertEquals(NativePtr.NULL, globalPtr.value)
}()
GC.collect()
performGCOnCleanerWorker()
assertNull(cleanerWeak!!.value)
assertEquals(NativePtr.NULL + 42L, globalPtr.value)
}
@Test
fun testCleanerWithException() {
val called = AtomicBoolean(false);
var funBoxWeak: WeakReference<FunBox>? = null
var cleanerWeak: WeakReference<Cleaner>? = null
{
val funBox = FunBox { called.value = true }.freeze()
funBoxWeak = WeakReference(funBox)
val cleaner = createCleaner(funBox) {
it.call()
error("Cleaner block failed")
}
cleanerWeak = WeakReference(cleaner)
}()
GC.collect()
performGCOnCleanerWorker()
assertNull(cleanerWeak!!.value)
// Cleaners block started executing.
assertTrue(called.value)
// Even though the block failed, the captured funBox is freed.
assertNull(funBoxWeak!!.value)
}
| apache-2.0 | 6648bee9c4c2ef34302e4a9dd0888fdd | 25.45098 | 101 | 0.643254 | 4.134866 | false | true | false | false |
jwren/intellij-community | plugins/kotlin/jvm-debugger/test/test/org/jetbrains/kotlin/idea/debugger/test/util/BreakpointCreator.kt | 1 | 10741 | // 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.debugger.test.util
import org.jetbrains.kotlin.idea.test.InTextDirectivesUtils.findLinesWithPrefixesRemoved
import com.intellij.debugger.DebuggerInvocationUtil
import com.intellij.openapi.application.ModalityState
import com.intellij.psi.PsiDocumentManager
import com.intellij.psi.PsiManager
import com.intellij.psi.search.FilenameIndex
import com.intellij.xdebugger.XDebuggerManager
import org.jetbrains.kotlin.idea.util.application.runReadAction
import com.intellij.debugger.engine.evaluation.CodeFragmentKind
import com.intellij.debugger.engine.evaluation.TextWithImportsImpl
import com.intellij.debugger.ui.breakpoints.Breakpoint
import com.intellij.debugger.ui.breakpoints.BreakpointManager
import com.intellij.debugger.ui.breakpoints.LineBreakpoint
import com.intellij.openapi.application.runWriteAction
import com.intellij.openapi.project.Project
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.psi.PsiFile
import com.intellij.xdebugger.XDebuggerUtil
import com.intellij.xdebugger.breakpoints.XBreakpointManager
import com.intellij.xdebugger.breakpoints.XBreakpointProperties
import com.intellij.xdebugger.breakpoints.XBreakpointType
import com.intellij.xdebugger.breakpoints.XLineBreakpointType
import org.jetbrains.java.debugger.breakpoints.properties.JavaBreakpointProperties
import org.jetbrains.java.debugger.breakpoints.properties.JavaLineBreakpointProperties
import org.jetbrains.kotlin.idea.debugger.breakpoints.*
import org.jetbrains.kotlin.idea.debugger.test.preference.DebuggerPreferenceKeys
import org.jetbrains.kotlin.idea.debugger.test.preference.DebuggerPreferences
import javax.swing.SwingUtilities
internal class BreakpointCreator(
private val project: Project,
private val logger: (String) -> Unit,
private val preferences: DebuggerPreferences
) {
fun createBreakpoints(file: PsiFile) {
val document = runReadAction { PsiDocumentManager.getInstance(project).getDocument(file) } ?: return
val breakpointManager = XDebuggerManager.getInstance(project).breakpointManager
val kotlinFieldBreakpointType = findBreakpointType(KotlinFieldBreakpointType::class.java)
val virtualFile = file.virtualFile
val runnable = {
var offset = -1
while (true) {
val fileText = document.text
offset = fileText.indexOf("point!", offset + 1)
if (offset == -1) break
val commentLine = document.getLineNumber(offset)
val lineIndex = commentLine + 1
val comment = fileText
.substring(document.getLineStartOffset(commentLine), document.getLineEndOffset(commentLine))
.trim()
when {
@Suppress("SpellCheckingInspection") comment.startsWith("//FieldWatchpoint!") -> {
val javaBreakpoint = createBreakpointOfType(
breakpointManager,
kotlinFieldBreakpointType,
lineIndex,
virtualFile
)
(javaBreakpoint as? KotlinFieldBreakpoint)?.apply {
@Suppress("SpellCheckingInspection")
val fieldName = comment.substringAfter("//FieldWatchpoint! (").substringBefore(")")
setFieldName(fieldName)
setWatchAccess(preferences[DebuggerPreferenceKeys.WATCH_FIELD_ACCESS])
setWatchModification(preferences[DebuggerPreferenceKeys.WATCH_FIELD_MODIFICATION])
setWatchInitialization(preferences[DebuggerPreferenceKeys.WATCH_FIELD_INITIALISATION])
BreakpointManager.addBreakpoint(javaBreakpoint)
logger("KotlinFieldBreakpoint created at ${file.virtualFile.name}:${lineIndex + 1}")
}
}
comment.startsWith("//Breakpoint!") -> {
val ordinal = getPropertyFromComment(comment, "lambdaOrdinal")?.toInt()
val condition = getPropertyFromComment(comment, "condition")
createLineBreakpoint(breakpointManager, file, lineIndex, ordinal, condition)
}
comment.startsWith("//FunctionBreakpoint!") -> {
createFunctionBreakpoint(breakpointManager, file, lineIndex, false)
}
else -> throw AssertionError("Cannot create breakpoint at line ${lineIndex + 1}")
}
}
}
if (!SwingUtilities.isEventDispatchThread()) {
DebuggerInvocationUtil.invokeAndWait(project, runnable, ModalityState.defaultModalityState())
} else {
runnable.invoke()
}
}
fun createAdditionalBreakpoints(fileContents: String) {
val breakpoints = findLinesWithPrefixesRemoved(fileContents, "// ADDITIONAL_BREAKPOINT: ")
for (breakpoint in breakpoints) {
val chunks = breakpoint.split('/').map { it.trim() }
val fileName = chunks.getOrNull(0) ?: continue
val lineMarker = chunks.getOrNull(1) ?: continue
val kind = chunks.getOrElse(2) { "line" }
val ordinal = chunks.getOrNull(3)?.toInt()
val breakpointManager = XDebuggerManager.getInstance(project).breakpointManager
when (kind) {
"line" -> createBreakpoint(fileName, lineMarker) { psiFile, lineNumber ->
createLineBreakpoint(breakpointManager, psiFile, lineNumber + 1, ordinal, null)
}
"fun" -> createBreakpoint(fileName, lineMarker) { psiFile, lineNumber ->
createFunctionBreakpoint(breakpointManager, psiFile, lineNumber, true)
}
else -> error("Unknown breakpoint kind: $kind")
}
}
}
private fun getPropertyFromComment(comment: String, propertyName: String): String? {
if (comment.contains("$propertyName = ")) {
val result = comment.substringAfter("$propertyName = ")
if (result.contains(", ")) {
return result.substringBefore(", ")
}
if (result.contains(")")) {
return result.substringBefore(")")
}
return result
}
return null
}
private fun createBreakpoint(fileName: String, lineMarker: String, action: (PsiFile, Int) -> Unit) {
val sourceFiles = runReadAction {
FilenameIndex.getAllFilesByExt(project, "kt")
.filter { it.name == fileName && it.contentsToByteArray().toString(Charsets.UTF_8).contains(lineMarker) }
}
val sourceFile = sourceFiles.singleOrNull()
?: error("Single source file should be found: name = $fileName, sourceFiles = $sourceFiles")
val runnable = Runnable {
val psiSourceFile = PsiManager.getInstance(project).findFile(sourceFile)
?: error("Psi file not found for $sourceFile")
val document = PsiDocumentManager.getInstance(project).getDocument(psiSourceFile)!!
val index = psiSourceFile.text!!.indexOf(lineMarker)
val lineNumber = document.getLineNumber(index)
action(psiSourceFile, lineNumber)
}
DebuggerInvocationUtil.invokeAndWait(project, runnable, ModalityState.defaultModalityState())
}
private fun createFunctionBreakpoint(breakpointManager: XBreakpointManager, file: PsiFile, lineIndex: Int, fromLibrary: Boolean) {
val breakpointType = findBreakpointType(KotlinFunctionBreakpointType::class.java)
val breakpoint = createBreakpointOfType(breakpointManager, breakpointType, lineIndex, file.virtualFile)
if (breakpoint is KotlinFunctionBreakpoint) {
val lineNumberSuffix = if (fromLibrary) "" else ":${lineIndex + 1}"
logger("FunctionBreakpoint created at ${file.virtualFile.name}$lineNumberSuffix")
}
}
private fun createLineBreakpoint(
breakpointManager: XBreakpointManager,
file: PsiFile,
lineIndex: Int,
lambdaOrdinal: Int?,
condition: String?
) {
val kotlinLineBreakpointType = findBreakpointType(KotlinLineBreakpointType::class.java)
val javaBreakpoint = createBreakpointOfType(
breakpointManager,
kotlinLineBreakpointType,
lineIndex,
file.virtualFile
)
if (javaBreakpoint is LineBreakpoint<*>) {
val properties = javaBreakpoint.xBreakpoint.properties as? JavaLineBreakpointProperties ?: return
var suffix = ""
if (lambdaOrdinal != null) {
if (lambdaOrdinal != -1) {
properties.lambdaOrdinal = lambdaOrdinal - 1
} else {
properties.lambdaOrdinal = lambdaOrdinal
}
suffix += " lambdaOrdinal = $lambdaOrdinal"
}
if (condition != null) {
javaBreakpoint.setCondition(TextWithImportsImpl(CodeFragmentKind.EXPRESSION, condition))
suffix += " condition = $condition"
}
BreakpointManager.addBreakpoint(javaBreakpoint)
logger("LineBreakpoint created at ${file.virtualFile.name}:${lineIndex + 1}$suffix")
}
}
private fun createBreakpointOfType(
breakpointManager: XBreakpointManager,
breakpointType: XLineBreakpointType<XBreakpointProperties<*>>,
lineIndex: Int,
virtualFile: VirtualFile
): Breakpoint<out JavaBreakpointProperties<*>>? {
if (!breakpointType.canPutAt(virtualFile, lineIndex, project)) return null
val xBreakpoint = runWriteAction {
breakpointManager.addLineBreakpoint(
breakpointType,
virtualFile.url,
lineIndex,
breakpointType.createBreakpointProperties(virtualFile, lineIndex)
)
}
return BreakpointManager.getJavaBreakpoint(xBreakpoint)
}
@Suppress("UNCHECKED_CAST")
private inline fun <reified T : XBreakpointType<*, *>> findBreakpointType(javaClass: Class<T>): XLineBreakpointType<XBreakpointProperties<*>> {
return XDebuggerUtil.getInstance().findBreakpointType(javaClass) as XLineBreakpointType<XBreakpointProperties<*>>
}
}
| apache-2.0 | 589e7a90cf527d824e6af4757b36cf11 | 46.109649 | 158 | 0.647612 | 5.71026 | false | false | false | false |
androidx/androidx | compose/animation/animation/integration-tests/animation-demos/src/main/java/androidx/compose/animation/demos/visualinspection/SlideInContentVariedSizes.kt | 3 | 8252 | /*
* 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.animation.demos.visualinspection
import androidx.compose.animation.AnimatedContent
import androidx.compose.animation.AnimatedContentScope.SlideDirection.Companion.Down
import androidx.compose.animation.AnimatedContentScope.SlideDirection.Companion.Left
import androidx.compose.animation.AnimatedContentScope.SlideDirection.Companion.Right
import androidx.compose.animation.AnimatedContentScope.SlideDirection.Companion.Up
import androidx.compose.animation.ExperimentalAnimationApi
import androidx.compose.animation.SizeTransform
import androidx.compose.animation.with
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.material.Button
import androidx.compose.material.Checkbox
import androidx.compose.material.DropdownMenu
import androidx.compose.material.DropdownMenuItem
import androidx.compose.material.Icon
import androidx.compose.material.Text
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ArrowBack
import androidx.compose.material.icons.filled.ArrowForward
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import kotlin.math.max
import kotlin.math.min
@Preview
@OptIn(ExperimentalAnimationApi::class)
@Composable
fun SlideInContentVariedSizes() {
Column {
var contentAlignment by remember { mutableStateOf(Alignment.TopStart) }
var clip by remember { mutableStateOf(true) }
var horizontal by remember { mutableStateOf(true) }
AlignmentMenu(contentAlignment, { contentAlignment = it })
Row(Modifier.clickable { clip = !clip }.padding(20.dp)) {
Checkbox(clip, { clip = it })
Text("Clip")
}
Row(Modifier.clickable { horizontal = !horizontal }.padding(20.dp)) {
Checkbox(horizontal, { horizontal = it })
Text("Slide horizontally")
}
var contentState by remember { mutableStateOf(PaneState.Pane1) }
Box(Modifier.fillMaxSize()) {
AnimatedContent(
contentState,
modifier = Modifier.padding(top = 120.dp, start = 100.dp)
.border(3.dp, Color(0xff79e9de)),
contentAlignment = contentAlignment,
transitionSpec = {
if (targetState < initialState) {
if (horizontal) {
slideIntoContainer(towards = Right) with slideOutOfContainer(
towards = Right
)
} else {
slideIntoContainer(towards = Down) with slideOutOfContainer(
towards = Down
)
}
} else {
if (horizontal) {
slideIntoContainer(towards = Left).with(
slideOutOfContainer(towards = Left)
)
} else {
slideIntoContainer(towards = Up).with(
slideOutOfContainer(towards = Up)
)
}
}.using(SizeTransform(clip = clip)).apply {
targetContentZIndex = when (targetState) {
PaneState.Pane1 -> 1f
PaneState.Pane2 -> 2f
PaneState.Pane3 -> 3f
}
}
}
) {
when (it) {
PaneState.Pane1 -> Pane1()
PaneState.Pane2 -> Pane2()
PaneState.Pane3 -> Pane3()
}
}
Row(
Modifier.matchParentSize(),
horizontalArrangement = Arrangement.SpaceBetween
) {
Icon(
Icons.Default.ArrowBack, contentDescription = null,
Modifier.clickable {
contentState = PaneState.values()[max(0, contentState.ordinal - 1)]
}.padding(top = 300.dp, bottom = 300.dp, end = 60.dp)
)
Icon(
Icons.Default.ArrowForward, contentDescription = null,
Modifier.clickable {
contentState = PaneState.values()[min(2, contentState.ordinal + 1)]
}.padding(top = 300.dp, bottom = 300.dp, start = 60.dp)
)
}
}
}
}
@Composable
fun AlignmentMenu(contentAlignment: Alignment, onAlignmentChanged: (alignment: Alignment) -> Unit) {
var expanded by remember { mutableStateOf(false) }
Box {
Button(onClick = { expanded = true }) {
Text("Current alignment: $contentAlignment")
}
DropdownMenu(
expanded = expanded,
onDismissRequest = { expanded = false }
) {
DropdownMenuItem(onClick = { onAlignmentChanged(Alignment.TopStart) }) {
Text("TopStart")
}
DropdownMenuItem(onClick = { onAlignmentChanged(Alignment.TopEnd) }) {
Text("TopEnd")
}
DropdownMenuItem(onClick = { onAlignmentChanged(Alignment.BottomStart) }) {
Text("BottomStart")
}
DropdownMenuItem(onClick = { onAlignmentChanged(Alignment.BottomEnd) }) {
Text("BottomEnd")
}
DropdownMenuItem(onClick = { onAlignmentChanged(Alignment.Center) }) {
Text("Center")
}
DropdownMenuItem(onClick = { onAlignmentChanged(Alignment.TopCenter) }) {
Text("TopCenter")
}
DropdownMenuItem(onClick = { onAlignmentChanged(Alignment.BottomCenter) }) {
Text("BottomCenter")
}
DropdownMenuItem(onClick = { onAlignmentChanged(Alignment.CenterStart) }) {
Text("CenterStart")
}
DropdownMenuItem(onClick = { onAlignmentChanged(Alignment.CenterEnd) }) {
Text("CenterEnd")
}
}
}
}
@Composable
fun Pane1() {
Column(Modifier.background(Color(0xFFe3ffd9)).padding(10.dp)) {
for (id in 1..4) {
Text("Range from ${(id - 1) * 10} to ${id * 10 - 1}:", fontSize = 20.sp)
}
}
}
@Composable
fun Pane3() {
Column(Modifier.background(Color(0xFFffe9d6)).padding(10.dp)) {
for (id in 1..10) {
Text("Line #$id ", fontSize = 20.sp)
}
}
}
@Composable
fun Pane2() {
Column(Modifier.background(Color(0xFFfffbd0)).padding(10.dp)) {
Text("Yes", fontSize = 20.sp)
Text("No", fontSize = 20.sp)
}
}
private enum class PaneState {
Pane1, Pane2, Pane3
}
| apache-2.0 | ba1ec0a65d6878fcfdf9e0456b9f731e | 37.924528 | 100 | 0.597189 | 4.891523 | false | false | false | false |
GunoH/intellij-community | plugins/git4idea/src/git4idea/actions/GitUseSharedLogAction.kt | 5 | 3006 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package git4idea.actions
import com.intellij.openapi.actionSystem.ActionUpdateThread
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.CommonDataKeys
import com.intellij.openapi.fileChooser.FileChooser
import com.intellij.openapi.fileChooser.FileChooserDescriptorFactory
import com.intellij.openapi.project.DumbAwareAction
import com.intellij.vcs.log.impl.VcsProjectLog
import git4idea.i18n.GitBundle
import git4idea.log.GitLogIndexDataUtils
internal class GitUseSharedLogAction : DumbAwareAction(GitBundle.messagePointer("vcs.log.use.log.index.data")) {
override fun getActionUpdateThread(): ActionUpdateThread {
return ActionUpdateThread.BGT
}
override fun update(e: AnActionEvent) {
val project = e.project ?: disable(e) ?: return
val vcsProjectLog = VcsProjectLog.getInstance(project) ?: disable(e) ?: return
val data = vcsProjectLog.dataManager
val isDataPackFull = data?.dataPack?.isFull ?: false
val indexingFinished = GitLogIndexDataUtils.indexingFinished(data)
if (isDataPackFull && indexingFinished) {
disable<Unit>(e)
return
}
e.presentation.isEnabledAndVisible = true
}
override fun actionPerformed(e: AnActionEvent) {
val project = e.getData(CommonDataKeys.PROJECT) ?: return
val fileChooserDescriptor = FileChooserDescriptorFactory.createSingleFileDescriptor()
val virtualFile = FileChooser.chooseFile(fileChooserDescriptor, project, null)
if (virtualFile == null) return
GitLogIndexDataUtils.extractLogDataFromArchive(project, virtualFile)
}
}
internal class GitDumpLogIndexDataAction : DumbAwareAction(GitBundle.messagePointer("vcs.log.create.archive.with.log.index.data")) {
override fun getActionUpdateThread(): ActionUpdateThread {
return ActionUpdateThread.BGT
}
override fun update(e: AnActionEvent) {
val project = e.project ?: disable(e) ?: return
val vcsProjectLog = VcsProjectLog.getInstance(project)
val data = vcsProjectLog.dataManager
val isDataPackFull = data?.dataPack?.isFull ?: false
val indexingFinished = GitLogIndexDataUtils.indexingFinished(data)
if (isDataPackFull && indexingFinished) {
e.presentation.isEnabledAndVisible = true
return
}
disable<Unit>(e) ?: return
}
override fun actionPerformed(e: AnActionEvent) {
val project = e.getData(CommonDataKeys.PROJECT) ?: return
val fileChooserDescriptor = FileChooserDescriptorFactory.createSingleFolderDescriptor()
val virtualFile = FileChooser.chooseFile(fileChooserDescriptor, project, null)
if (virtualFile == null) return
val outputArchiveDir = virtualFile.toNioPath()
GitLogIndexDataUtils.createArchiveWithLogData(project, outputArchiveDir)
}
}
private inline fun <reified T> disable(e: AnActionEvent): T? {
e.presentation.isEnabledAndVisible = false
return null
} | apache-2.0 | 553ba5355f70eb9d196026e37d56967e | 36.5875 | 132 | 0.774118 | 4.794258 | false | false | false | false |
TonnyL/Mango | app/src/main/java/io/github/tonnyl/mango/ui/user/following/FollowingPresenter.kt | 1 | 4660 | /*
* 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.ui.user.following
import io.github.tonnyl.mango.data.Followee
import io.github.tonnyl.mango.data.repository.UserRepository
import io.github.tonnyl.mango.util.PageLinks
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.schedulers.Schedulers
/**
* Created by lizhaotailang on 2017/7/29.
*
* Listens to user action from the ui [io.github.tonnyl.mango.ui.user.following.FollowingFragment],
* retrieves the data and update the ui as required.
*/
class FollowingPresenter(view: FollowingContract.View, userId: Long) : FollowingContract.Presenter {
private val mView = view
private val mUserId = userId
private val mCompositeDisposable: CompositeDisposable
private var mNextPageUrl: String? = null
private var mCachedFollowees = arrayListOf<Followee>()
companion object {
const val EXTRA_USER_ID = "EXTRA_USER_ID"
const val EXTRA_FOLLOWING_TITLE = "EXTRA_FOLLOWING_TITLE"
}
init {
mView.setPresenter(this)
mCompositeDisposable = CompositeDisposable()
}
override fun subscribe() {
loadFollowing()
}
override fun unsubscribe() {
mCompositeDisposable.clear()
}
override fun loadFollowing() {
mView.setLoadingIndicator(true)
val disposable = UserRepository.listFolloweeOfUser(mUserId)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe({ response ->
mView.setLoadingIndicator(false)
mNextPageUrl = PageLinks(response).next
response.body()?.let {
mView.setEmptyViewVisibility(it.isEmpty())
if (it.isNotEmpty()) {
if (mCachedFollowees.isNotEmpty()) {
val size = mCachedFollowees.size
mCachedFollowees.clear()
mView.notifyDataAllRemoved(size)
mCachedFollowees.addAll(it)
mView.notifyDataAdded(0, mCachedFollowees.size)
} else {
mCachedFollowees.addAll(it)
mView.showFollowings(mCachedFollowees)
}
}
}
}, {
mView.setEmptyViewVisibility(true)
mView.setLoadingIndicator(false)
it.printStackTrace()
})
mCompositeDisposable.add(disposable)
}
override fun loadMoreFollowing() {
mNextPageUrl?.let {
val disposable = UserRepository.listFolloweesOfNextPage(it)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe({ response ->
mNextPageUrl = PageLinks(response).next
response.body()?.let {
val size = mCachedFollowees.size
mCachedFollowees.addAll(it)
mView.notifyDataAdded(size, it.size)
}
}, {
mView.showNetworkError()
it.printStackTrace()
})
mCompositeDisposable.add(disposable)
}
}
} | mit | 7ee667470b37cca1da1961e5d55207d6 | 38.168067 | 100 | 0.604077 | 5.271493 | false | false | false | false |
BijoySingh/Quick-Note-Android | base/src/main/java/com/maubis/scarlet/base/core/note/NoteBuilder.kt | 1 | 3790 | package com.maubis.scarlet.base.core.note
import com.github.bijoysingh.starter.util.RandomHelper
import com.github.bijoysingh.starter.util.TextUtils
import com.google.gson.Gson
import com.maubis.scarlet.base.core.format.Format
import com.maubis.scarlet.base.core.format.FormatBuilder
import com.maubis.scarlet.base.core.format.FormatType
import com.maubis.scarlet.base.database.room.note.Note
import java.util.*
fun generateUUID() = UUID.randomUUID().toString()
class NoteBuilder {
/**
* Generate blank note with default configuration
*/
fun emptyNote(): Note {
val note = Note()
note.uuid = generateUUID()
note.state = NoteState.DEFAULT.name
note.timestamp = Calendar.getInstance().timeInMillis
note.updateTimestamp = note.timestamp
note.color = -0xff8695
note.folder = ""
note.description = FormatBuilder().getDescription(emptyList())
return note
}
/**
* Generate blank note with color
*/
fun emptyNote(color: Int): Note {
val note = emptyNote()
note.color = color
return note
}
/**
* Generate blank note from basic title and description
*/
fun gen(title: String, description: String): Note {
val note = emptyNote()
val formats = ArrayList<Format>()
if (!TextUtils.isNullOrEmpty(title)) {
formats.add(Format(FormatType.HEADING, title))
}
formats.add(Format(FormatType.TEXT, description))
note.description = FormatBuilder().getDescription(formats)
return note
}
/**
* Generate blank note from basic title and description
*/
fun gen(title: String, formatSource: List<Format>): Note {
val note = emptyNote()
val formats = ArrayList<Format>()
if (!TextUtils.isNullOrEmpty(title)) {
formats.add(Format(FormatType.HEADING, title))
}
formats.addAll(formatSource)
note.description = FormatBuilder().getDescription(formats)
return note
}
fun genFromKeep(content: String): List<Format> {
val randomDelimiter = "-+-" + RandomHelper.getRandom() + "-+-"
var delimitered = content.replace("(^|\n)\\s*\\[\\s\\]\\s*".toRegex(), randomDelimiter + "[ ]")
delimitered = delimitered.replace("(^|\n)\\s*\\[x\\]\\s*".toRegex(), randomDelimiter + "[x]")
val items = delimitered.split(randomDelimiter)
val formats = ArrayList<Format>()
for (item in items) {
when {
item.startsWith("[ ]") -> formats.add(Format(FormatType.CHECKLIST_UNCHECKED, item.removePrefix("[ ]")))
item.startsWith("[x]") -> formats.add(Format(FormatType.CHECKLIST_CHECKED, item.removePrefix("[x]")))
!item.isBlank() -> formats.add(Format(FormatType.TEXT, item))
}
}
return formats
}
fun copy(noteContainer: INoteContainer): Note {
val note = emptyNote()
note.uuid = noteContainer.uuid()
note.description = noteContainer.description()
note.timestamp = noteContainer.timestamp()
note.updateTimestamp = Math.max(note.updateTimestamp, note.timestamp)
note.color = noteContainer.color()
note.state = noteContainer.state()
note.locked = noteContainer.locked()
note.pinned = noteContainer.pinned()
note.tags = noteContainer.tags()
note.meta = Gson().toJson(noteContainer.meta())
note.folder = noteContainer.folder()
return note
}
fun copy(reference: Note): Note {
val note = emptyNote()
note.uid = reference.uid
note.uuid = reference.uuid
note.state = reference.state
note.description = reference.description
note.timestamp = reference.timestamp
note.updateTimestamp = reference.updateTimestamp
note.color = reference.color
note.tags = reference.tags
note.pinned = reference.pinned
note.locked = reference.locked
note.meta = reference.meta
note.folder = reference.folder
return note
}
} | gpl-3.0 | 5fcacf5097c2bac31f1fbde4fa36b460 | 31.681034 | 111 | 0.68628 | 4.014831 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.