repo_name
stringlengths 7
81
| path
stringlengths 6
242
| copies
stringclasses 53
values | size
stringlengths 2
6
| content
stringlengths 73
737k
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 5.44
99.8
| line_max
int64 15
977
| alpha_frac
float64 0.3
0.91
| ratio
float64 2
9.93
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
CineCor/CinecorAndroid | app/src/main/java/com/cinecor/android/cinemas/movies/ui/MoviesAdapter.kt | 1 | 2012 | package com.cinecor.android.cinemas.movies.ui
import android.support.v7.util.DiffUtil
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import com.bumptech.glide.Glide
import com.cinecor.android.R
import com.cinecor.android.data.model.Movie
import com.cinecor.android.utils.MovieDiffCallback
import kotlinx.android.synthetic.main.item_movie.view.*
import java.util.*
class MoviesAdapter(val listener: OnMovieClickListener) : RecyclerView.Adapter<MoviesAdapter.ViewHolder>() {
private var movies: List<Movie> = ArrayList()
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val view = LayoutInflater.from(parent.context).inflate(R.layout.item_movie, parent, false)
val viewHolder = ViewHolder(view)
view.setOnClickListener { listener.onMovieClicked(movies[viewHolder.adapterPosition], view.backdrop) }
return viewHolder
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
holder.bind(movies[position])
}
override fun getItemCount(): Int {
return movies.size
}
fun updateMovies(movies: List<Movie>) {
DiffUtil.calculateDiff(MovieDiffCallback(this.movies, movies)).dispatchUpdatesTo(this)
this.movies = movies
}
class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
fun bind(movie: Movie) {
with(movie) {
val images = getBackdropImages()
itemView.title.text = title
itemView.hours.text = getFormattedHours()
Glide.with(itemView)
.load(images?.first)
.thumbnail(Glide.with(itemView).load(images?.second))
.into(itemView.backdrop)
}
}
}
interface OnMovieClickListener {
fun onMovieClicked(movie: Movie, image: ImageView)
}
}
| gpl-3.0 | 8511326b616b218e761e30041189514a | 33.101695 | 110 | 0.682903 | 4.491071 | false | false | false | false |
songzhw/AndroidArchitecture | deprecated/MVI/MVI101/MVI_Client/app/src/main/java/ca/six/mvi/utils/http/HttpEngine.kt | 1 | 827 | package ca.six.mvi.utils.http
import io.reactivex.BackpressureStrategy
import io.reactivex.Flowable
import io.reactivex.FlowableOnSubscribe
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.Response
class HttpEngine {
fun get(url: String): Flowable<Response> {
val ret = Flowable.create(FlowableOnSubscribe<Response> { emitter ->
val client = OkHttpClient()
val request = Request.Builder()
.url(url)
.build()
val response = client.newCall(request).execute()
emitter.onNext(response)
emitter.onComplete()
}, BackpressureStrategy.BUFFER)
return ret
}
}
internal interface HttpCode {
companion object {
val OK = 2000
val ERROR_NO_CONNECTION = 1001
}
} | apache-2.0 | 7afd3ae5f76fa09bf326d8a0b1c51419 | 23.352941 | 76 | 0.638452 | 4.672316 | false | false | false | false |
arturbosch/detekt | detekt-tooling/src/main/kotlin/io/github/detekt/tooling/internal/EmptyContainer.kt | 1 | 957 | package io.github.detekt.tooling.internal
import io.gitlab.arturbosch.detekt.api.Detektion
import io.gitlab.arturbosch.detekt.api.Finding
import io.gitlab.arturbosch.detekt.api.Notification
import io.gitlab.arturbosch.detekt.api.ProjectMetric
import io.gitlab.arturbosch.detekt.api.RuleSetId
import org.jetbrains.kotlin.com.intellij.openapi.util.Key
object EmptyContainer : Detektion {
override val findings: Map<RuleSetId, List<Finding>> = emptyMap()
override val notifications: Collection<Notification> = emptyList()
override val metrics: Collection<ProjectMetric> = emptyList()
override fun <V> getData(key: Key<V>): V? = throw UnsupportedOperationException()
override fun <V> addData(key: Key<V>, value: V) = throw UnsupportedOperationException()
override fun add(notification: Notification) = throw UnsupportedOperationException()
override fun add(projectMetric: ProjectMetric) = throw UnsupportedOperationException()
}
| apache-2.0 | 284637506615d68c23172bfcdf0c7228 | 46.85 | 91 | 0.791014 | 4.430556 | false | false | false | false |
vhromada/Catalog-REST | src/main/kotlin/cz/vhromada/catalog/rest/controller/MusicController.kt | 1 | 5560 | package cz.vhromada.catalog.rest.controller
import cz.vhromada.catalog.entity.Music
import cz.vhromada.catalog.facade.MusicFacade
import cz.vhromada.common.web.controller.AbstractController
import org.springframework.http.HttpStatus
import org.springframework.web.bind.annotation.DeleteMapping
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.PathVariable
import org.springframework.web.bind.annotation.PostMapping
import org.springframework.web.bind.annotation.PutMapping
import org.springframework.web.bind.annotation.RequestBody
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.ResponseStatus
import org.springframework.web.bind.annotation.RestController
/**
* A class represents controller for music.
*
* @author Vladimir Hromada
*/
@RestController("musicController")
@RequestMapping("/catalog/music")
class MusicController(private val musicFacade: MusicFacade) : AbstractController() {
/**
* Returns list of music.
*
* @return list of music
*/
@GetMapping
fun getMusic(): List<Music> {
return processResult(musicFacade.getAll())!!
}
/**
* Creates new data.
*/
@PostMapping("/new")
@ResponseStatus(HttpStatus.NO_CONTENT)
fun newData() {
processResult(musicFacade.newData())
}
/**
* Returns music with ID or null if there isn't such music.
*
* @param id ID
* @return music with ID or null if there isn't such music
*/
@GetMapping("/{id}")
fun getMusic(@PathVariable("id") id: Int): Music {
return processResult(musicFacade.get(id))!!
}
/**
* Adds music. Sets new ID and position.
* <br></br>
* Validation errors:
*
* * ID isn't null
* * Position isn't null
* * Name is null
* * Name is empty string
* * URL to english Wikipedia page about music is null
* * URL to czech Wikipedia page about music is null
* * Count of media isn't positive number
* * Other data is null
* * Note is null
*
* @param music music
*/
@PutMapping("/add")
@ResponseStatus(HttpStatus.CREATED)
fun add(@RequestBody music: Music) {
processResult(musicFacade.add(music))
}
/**
* Updates music.
* <br></br>
* Validation errors:
*
* * ID is null
* * Position is null
* * Name is null
* * Name is empty string
* * URL to english Wikipedia page about music is null
* * URL to czech Wikipedia page about music is null
* * Count of media isn't positive number
* * Other data is null
* * Note is null
* * Music doesn't exist in data storage
*
* @param music new value of music
*/
@PostMapping("/update")
fun update(@RequestBody music: Music) {
processResult(musicFacade.update(music))
}
/**
* Removes music.
* <br></br>
* Validation errors:
*
* * Music doesn't exist in data storage
*
* @param id ID
*/
@DeleteMapping("/remove/{id}")
@ResponseStatus(HttpStatus.NO_CONTENT)
fun remove(@PathVariable("id") id: Int) {
val music = Music(id = id, name = null, wikiEn = null, wikiCz = null, mediaCount = null, note = null, position = null)
processResult(musicFacade.remove(music))
}
/**
* Duplicates music.
* <br></br>
* Validation errors:
*
* * ID is null
* * Music doesn't exist in data storage
*
* @param music music
*/
@PostMapping("/duplicate")
@ResponseStatus(HttpStatus.CREATED)
fun duplicate(@RequestBody music: Music) {
processResult(musicFacade.duplicate(music))
}
/**
* Moves music in list one position up.
* <br></br>
* Validation errors:
*
* * ID is null
* * Music can't be moved up
* * Music doesn't exist in data storage
*
* @param music music
*/
@PostMapping("/moveUp")
@ResponseStatus(HttpStatus.NO_CONTENT)
fun moveUp(@RequestBody music: Music) {
processResult(musicFacade.moveUp(music))
}
/**
* Moves music in list one position down.
* <br></br>
* Validation errors:
*
* * ID is null
* * Music can't be moved down
* * Music doesn't exist in data storage
*
* @param music music
*/
@PostMapping("/moveDown")
@ResponseStatus(HttpStatus.NO_CONTENT)
fun moveDown(@RequestBody music: Music) {
processResult(musicFacade.moveDown(music))
}
/**
* Updates positions.
*/
@PostMapping("/updatePositions")
@ResponseStatus(HttpStatus.NO_CONTENT)
fun updatePositions() {
processResult(musicFacade.updatePositions())
}
/**
* Returns total count of media.
*
* @return total count of media
*/
@GetMapping("/totalMedia")
fun getTotalMediaCount(): Int {
return processResult(musicFacade.getTotalMediaCount())!!
}
/**
* Returns total length of all music.
*
* @return total length of all music
*/
@GetMapping("/totalLength")
fun getTotalLength(): Int {
return processResult(musicFacade.getTotalLength())!!.length
}
/**
* Returns count of songs from all music.
*
* @return count of songs from all music
*/
@GetMapping("/songsCount")
fun geSongsCount(): Int {
return processResult(musicFacade.getSongsCount())!!
}
}
| mit | cbda6aaf7f7f382ecb85bd9a1a001fda | 25.859903 | 126 | 0.622482 | 4.31677 | false | false | false | false |
arturbosch/detekt | detekt-cli/src/test/kotlin/io/gitlab/arturbosch/detekt/cli/ReportPathSpec.kt | 1 | 3807 | package io.gitlab.arturbosch.detekt.cli
import org.assertj.core.api.Assertions.assertThat
import org.assertj.core.api.Assertions.assertThatIllegalArgumentException
import org.assertj.core.api.Assertions.assertThatIllegalStateException
import org.jetbrains.kotlin.com.intellij.openapi.util.SystemInfo
import org.spekframework.spek2.Spek
import org.spekframework.spek2.style.specification.describe
import java.nio.file.Paths
class ReportPathSpec : Spek({
describe("report paths") {
if (SystemInfo.isWindows) {
context("a Windows path") {
it("parses a valid absolute path correctly") {
val reportPath = ReportPath.from("test:C:\\tmp\\valid\\report")
assertThat(reportPath.path).isEqualTo(Paths.get("C:\\tmp\\valid\\report"))
}
it("parses a valid relative path correctly") {
val reportPath = ReportPath.from("test:valid\\report")
assertThat(reportPath.path).isEqualTo(Paths.get("valid\\report"))
}
it("fails when the path is empty") {
assertThatIllegalArgumentException()
.isThrownBy { ReportPath.from("test:") }
}
it("fails when the path is malformed") {
assertThatIllegalArgumentException()
.isThrownBy { ReportPath.from("test:a*a") }
}
}
} else {
context("a POSIX path") {
it("parses a valid absolute path correctly") {
val reportPath = ReportPath.from("test:/tmp/valid/report")
assertThat(reportPath.path).isEqualTo(Paths.get("/tmp/valid/report"))
}
it("parses a valid relative path correctly") {
val reportPath = ReportPath.from("test:valid/report")
assertThat(reportPath.path).isEqualTo(Paths.get("valid/report"))
}
it("fails when the path is empty") {
assertThatIllegalArgumentException()
.isThrownBy { ReportPath.from("test:") }
}
it("fails when the path is malformed") {
assertThatIllegalArgumentException()
.isThrownBy { ReportPath.from("test:a${0.toChar()}a") }
}
}
}
}
describe("`kind` processing") {
it("parses and maps the txt kind correctly") {
val reportPath = ReportPath.from("txt:/tmp/valid/report")
assertThat(reportPath.kind).isEqualTo("txt")
}
it("parses and maps the xml kind correctly") {
val reportPath = ReportPath.from("xml:/tmp/valid/report")
assertThat(reportPath.kind).isEqualTo("xml")
}
it("parses and maps the html kind correctly") {
val reportPath = ReportPath.from("html:/tmp/valid/report")
assertThat(reportPath.kind).isEqualTo("html")
}
it("parses and maps the txt kind correctly") {
val reportPath = ReportPath.from("txt:/tmp/valid/report")
assertThat(reportPath.kind).isEqualTo("txt")
}
it("parses a non-default kind correctly") {
val reportPath = ReportPath.from("test:/tmp/valid/report")
assertThat(reportPath.kind).isEqualTo("test")
}
it("fails when the kind is empty") {
assertThatIllegalArgumentException()
.isThrownBy { ReportPath.from(":/tmp/anything") }
}
it("fails when part size is illegal") {
assertThatIllegalStateException()
.isThrownBy { ReportPath.from("") }
}
}
})
| apache-2.0 | e313127676474cb5a2108e9537ff0c60 | 34.915094 | 94 | 0.562648 | 5.20082 | false | true | false | false |
nextcloud/android | app/src/main/java/com/owncloud/android/utils/FileExportUtils.kt | 1 | 5952 | /*
*
* Nextcloud Android client application
*
* @author Tobias Kaminsky
* Copyright (C) 2022 Tobias Kaminsky
* Copyright (C) 2022 Nextcloud GmbH
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.owncloud.android.utils
import android.annotation.SuppressLint
import android.content.ContentResolver
import android.content.ContentValues
import android.os.Build
import android.os.Environment
import android.provider.MediaStore
import androidx.annotation.RequiresApi
import com.owncloud.android.datamodel.OCFile
import com.owncloud.android.lib.common.utils.Log_OC
import java.io.File
import java.io.FileInputStream
import java.io.FileNotFoundException
import java.io.FileOutputStream
import java.io.IOException
import java.io.InputStream
class FileExportUtils {
@Throws(IllegalStateException::class)
fun exportFile(
fileName: String,
mimeType: String,
contentResolver: ContentResolver,
ocFile: OCFile?,
file: File?
) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
exportFileAndroid10AndAbove(
fileName,
mimeType,
contentResolver,
ocFile,
file
)
} else {
exportFilesBelowAndroid10(
fileName,
contentResolver,
ocFile,
file
)
}
}
@SuppressLint("Recycle") // handled inside copy method
@RequiresApi(Build.VERSION_CODES.Q)
private fun exportFileAndroid10AndAbove(
fileName: String,
mimeType: String,
contentResolver: ContentResolver,
ocFile: OCFile?,
file: File?
) {
val cv = ContentValues().apply {
put(MediaStore.MediaColumns.DISPLAY_NAME, fileName)
put(MediaStore.MediaColumns.MIME_TYPE, mimeType)
put(MediaStore.MediaColumns.RELATIVE_PATH, Environment.DIRECTORY_DOWNLOADS)
}
var uri = contentResolver.insert(MediaStore.Downloads.EXTERNAL_CONTENT_URI, cv)
if (uri == null) {
var count = INITIAL_RENAME_COUNT
do {
val name = generateNewName(fileName, count)
cv.put(MediaStore.MediaColumns.DISPLAY_NAME, name)
uri = contentResolver.insert(MediaStore.Downloads.EXTERNAL_CONTENT_URI, cv)
count++
} while (uri == null)
}
copy(
ocFile,
file,
contentResolver,
FileOutputStream(contentResolver.openFileDescriptor(uri, "w")?.fileDescriptor)
)
}
private fun exportFilesBelowAndroid10(
fileName: String,
contentResolver: ContentResolver,
ocFile: OCFile?,
file: File?
) {
try {
var target = File(
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS),
fileName
)
if (target.exists()) {
var count = INITIAL_RENAME_COUNT
do {
val name = generateNewName(fileName, count)
target = File(
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS),
name
)
count++
} while (target.exists())
}
copy(
ocFile,
file,
contentResolver,
FileOutputStream(target)
)
} catch (e: FileNotFoundException) {
Log_OC.e(this, "File not found", e)
} catch (e: IOException) {
Log_OC.e(this, "Cannot write file", e)
}
}
@Throws(IllegalStateException::class)
private fun copy(ocFile: OCFile?, file: File?, contentResolver: ContentResolver, outputStream: FileOutputStream) {
outputStream.use { fos ->
try {
val inputStream = when {
ocFile != null -> contentResolver.openInputStream(ocFile.storageUri)
file != null -> FileInputStream(file)
else -> error("ocFile and file both may not be null")
}!!
inputStream.use { fis ->
copyStream(fis, fos)
}
} catch (e: IOException) {
Log_OC.e(this, "Cannot write file", e)
}
}
}
private fun copyStream(inputStream: InputStream, outputStream: FileOutputStream) {
val buffer = ByteArray(COPY_BUFFER_SIZE)
var len: Int
while (inputStream.read(buffer).also { len = it } != -1) {
outputStream.write(buffer, 0, len)
}
}
private fun generateNewName(name: String, count: Int): String {
val extPos = name.lastIndexOf('.')
val suffix = " ($count)"
return if (extPos >= 0) {
val extension = name.substring(extPos + 1)
val nameWithoutExtension = name.substring(0, extPos)
"$nameWithoutExtension$suffix.$extension"
} else {
name + suffix
}
}
companion object {
private const val INITIAL_RENAME_COUNT = 2
private const val COPY_BUFFER_SIZE = 1024
}
}
| gpl-2.0 | 2a1183040bbd8138aa95d3cfff980bb5 | 30.828877 | 118 | 0.585517 | 5.014322 | false | false | false | false |
Kerr1Gan/ShareBox | share/src/main/java/com/flybd/sharebox/util/file/FileOpenIntentUtil.kt | 1 | 6715 | package com.flybd.sharebox.util.file
import android.content.Intent
import android.net.Uri
import java.io.File
/**
* Created by KerriGan on 2017/6/13.
*/
object FileOpenIntentUtil {
fun openFile(filePath: String): Intent? {
val file = File(filePath)
if (!file.exists()) return null
/* 取得扩展名 */
val end = file.name.substring(file.name.lastIndexOf(".") + 1, file.name.length).toLowerCase()
/* 依扩展名的类型决定MimeType */
if (end == "m4a" || end == "mp3" || end == "mid" ||
end == "xmf" || end == "ogg" || end == "wav") {
return getAudioFileIntent(filePath)
} else if (end == "3gp" || end == "mp4") {
return getAudioFileIntent(filePath)
} else if (end == "jpg" || end == "gif" || end == "png" ||
end == "jpeg" || end == "bmp") {
return getImageFileIntent(filePath)
} else if (end == "apk") {
return getApkFileIntent(filePath)
} else if (end == "ppt") {
return getPptFileIntent(filePath)
} else if (end == "xls") {
return getExcelFileIntent(filePath)
} else if (end == "doc") {
return getWordFileIntent(filePath)
} else if (end == "pdf") {
return getPdfFileIntent(filePath)
} else if (end == "chm") {
return getChmFileIntent(filePath)
} else if (end == "txt") {
return getTextFileIntent(filePath, false)
} else {
return getAllIntent(filePath)
}
}
//Android获取一个用于打开所有文件的intent
fun getAllIntent(param: String): Intent {
val intent = Intent()
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
intent.addCategory("android.intent.category.DEFAULT")
intent.action = Intent.ACTION_VIEW
val uri = Uri.fromFile(File(param))
intent.setData(uri)
// intent.setDataAndType(uri, "*/*")
return intent
}
//Android获取一个用于打开APK文件的intent
fun getApkFileIntent(param: String): Intent {
val intent = Intent()
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
intent.action = Intent.ACTION_VIEW
val uri = Uri.fromFile(File(param))
intent.setDataAndType(uri, "application/vnd.android.package-archive")
return intent
}
//Android获取一个用于打开VIDEO文件的intent
fun getVideoFileIntent(param: String): Intent {
val intent = Intent("android.intent.action.VIEW")
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
intent.putExtra("oneshot", 0)
intent.putExtra("configchange", 0)
val uri = Uri.fromFile(File(param))
intent.setDataAndType(uri, "video/*")
return intent
}
//Android获取一个用于打开AUDIO文件的intent
fun getAudioFileIntent(param: String): Intent {
val intent = Intent("android.intent.action.VIEW")
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
intent.putExtra("oneshot", 0)
intent.putExtra("configchange", 0)
val uri = Uri.fromFile(File(param))
intent.setDataAndType(uri, "audio/*")
return intent
}
//Android获取一个用于打开Html文件的intent
fun getHtmlFileIntent(param: String): Intent {
val uri = Uri.parse(param).buildUpon().encodedAuthority("com.android.htmlfileprovider").scheme("content").encodedPath(param).build()
val intent = Intent("android.intent.action.VIEW")
intent.setDataAndType(uri, "text/html")
return intent
}
//Android获取一个用于打开图片文件的intent
fun getImageFileIntent(param: String): Intent {
val intent = Intent("android.intent.action.VIEW")
intent.addCategory("android.intent.category.DEFAULT")
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
val uri = Uri.fromFile(File(param))
intent.setDataAndType(uri, "image/*")
return intent
}
//Android获取一个用于打开PPT文件的intent
fun getPptFileIntent(param: String): Intent {
val intent = Intent("android.intent.action.VIEW")
intent.addCategory("android.intent.category.DEFAULT")
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
val uri = Uri.fromFile(File(param))
intent.setDataAndType(uri, "application/vnd.ms-powerpoint")
return intent
}
//Android获取一个用于打开Excel文件的intent
fun getExcelFileIntent(param: String): Intent {
val intent = Intent("android.intent.action.VIEW")
intent.addCategory("android.intent.category.DEFAULT")
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
val uri = Uri.fromFile(File(param))
intent.setDataAndType(uri, "application/vnd.ms-excel")
return intent
}
//Android获取一个用于打开Word文件的intent
fun getWordFileIntent(param: String): Intent {
val intent = Intent("android.intent.action.VIEW")
intent.addCategory("android.intent.category.DEFAULT")
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
val uri = Uri.fromFile(File(param))
intent.setDataAndType(uri, "application/msword")
return intent
}
//Android获取一个用于打开CHM文件的intent
fun getChmFileIntent(param: String): Intent {
val intent = Intent("android.intent.action.VIEW")
intent.addCategory("android.intent.category.DEFAULT")
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
val uri = Uri.fromFile(File(param))
intent.setDataAndType(uri, "application/x-chm")
return intent
}
//Android获取一个用于打开文本文件的intent
fun getTextFileIntent(param: String, paramBoolean: Boolean): Intent {
val intent = Intent("android.intent.action.VIEW")
intent.addCategory("android.intent.category.DEFAULT")
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
if (paramBoolean) {
val uri1 = Uri.parse(param)
intent.setDataAndType(uri1, "text/plain")
} else {
val uri2 = Uri.fromFile(File(param))
intent.setDataAndType(uri2, "text/plain")
}
return intent
}
//Android获取一个用于打开PDF文件的intent
fun getPdfFileIntent(param: String): Intent {
val intent = Intent("android.intent.action.VIEW")
intent.addCategory("android.intent.category.DEFAULT")
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
val uri = Uri.fromFile(File(param))
intent.setDataAndType(uri, "application/pdf")
return intent
}
}
| apache-2.0 | 054e0825256e3614288b145000f24398 | 34.032787 | 140 | 0.628139 | 4.22054 | false | false | false | false |
goodwinnk/intellij-community | plugins/copyright/src/com/intellij/copyright/CopyrightManager.kt | 1 | 10841 | // 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 com.intellij.copyright
import com.intellij.configurationStore.*
import com.intellij.openapi.Disposable
import com.intellij.openapi.application.AppUIExecutor
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.ModalityState
import com.intellij.openapi.components.PersistentStateComponent
import com.intellij.openapi.components.State
import com.intellij.openapi.components.Storage
import com.intellij.openapi.components.service
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.editor.EditorFactory
import com.intellij.openapi.editor.event.DocumentEvent
import com.intellij.openapi.editor.event.DocumentListener
import com.intellij.openapi.fileEditor.FileDocumentManager
import com.intellij.openapi.options.SchemeManagerFactory
import com.intellij.openapi.project.Project
import com.intellij.openapi.roots.ProjectRootManager
import com.intellij.openapi.startup.StartupActivity
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.util.InvalidDataException
import com.intellij.openapi.util.WriteExternalException
import com.intellij.openapi.util.text.StringUtil
import com.intellij.packageDependencies.DependencyValidationManager
import com.intellij.project.isDirectoryBased
import com.intellij.psi.PsiFile
import com.intellij.psi.PsiManager
import com.intellij.util.attribute
import com.intellij.util.element
import com.maddyhome.idea.copyright.CopyrightProfile
import com.maddyhome.idea.copyright.actions.UpdateCopyrightProcessor
import com.maddyhome.idea.copyright.options.LanguageOptions
import com.maddyhome.idea.copyright.options.Options
import com.maddyhome.idea.copyright.util.FileTypeUtil
import com.maddyhome.idea.copyright.util.NewFileTracker
import org.jdom.Element
import org.jetbrains.annotations.TestOnly
import java.util.*
import java.util.function.Function
private const val DEFAULT = "default"
private const val MODULE_TO_COPYRIGHT = "module2copyright"
private const val COPYRIGHT = "copyright"
private const val ELEMENT = "element"
private const val MODULE = "module"
private val LOG = Logger.getInstance(CopyrightManager::class.java)
@State(name = "CopyrightManager", storages = [(Storage(value = "copyright/profiles_settings.xml", exclusive = true))])
class CopyrightManager @JvmOverloads constructor(private val project: Project, schemeManagerFactory: SchemeManagerFactory, isSupportIprProjects: Boolean = true) : PersistentStateComponent<Element> {
companion object {
@JvmStatic
fun getInstance(project: Project): CopyrightManager = project.service<CopyrightManager>()
}
private var defaultCopyrightName: String? = null
var defaultCopyright: CopyrightProfile?
get() = defaultCopyrightName?.let { schemeManager.findSchemeByName(it)?.scheme }
set(value) {
defaultCopyrightName = value?.name
}
val scopeToCopyright: LinkedHashMap<String, String> = LinkedHashMap<String, String>()
val options: Options = Options()
private val schemeWriter = { scheme: CopyrightProfile ->
val element = scheme.writeScheme()
if (project.isDirectoryBased) wrapScheme(element) else element
}
private val schemeManagerIprProvider = if (project.isDirectoryBased || !isSupportIprProjects) null else SchemeManagerIprProvider("copyright")
private val schemeManager = schemeManagerFactory.create("copyright", object : LazySchemeProcessor<SchemeWrapper<CopyrightProfile>, SchemeWrapper<CopyrightProfile>>("myName") {
override fun createScheme(dataHolder: SchemeDataHolder<SchemeWrapper<CopyrightProfile>>,
name: String,
attributeProvider: Function<in String, String?>,
isBundled: Boolean): SchemeWrapper<CopyrightProfile> {
return CopyrightLazySchemeWrapper(name, dataHolder, schemeWriter)
}
override fun isSchemeFile(name: CharSequence) = !StringUtil.equals(name, "profiles_settings.xml")
override fun getSchemeKey(attributeProvider: Function<String, String?>, fileNameWithoutExtension: String): String {
val schemeKey = super.getSchemeKey(attributeProvider, fileNameWithoutExtension)
if (schemeKey != null) {
return schemeKey
}
LOG.warn("Name is not specified for scheme $fileNameWithoutExtension, file name will be used instead")
return fileNameWithoutExtension
}
}, schemeNameToFileName = OLD_NAME_CONVERTER, streamProvider = schemeManagerIprProvider)
init {
val app = ApplicationManager.getApplication()
if (project.isDirectoryBased || !app.isUnitTestMode) {
schemeManager.loadSchemes()
}
}
@TestOnly
fun loadSchemes() {
LOG.assertTrue(ApplicationManager.getApplication().isUnitTestMode)
schemeManager.loadSchemes()
}
fun mapCopyright(scopeName: String, copyrightProfileName: String) {
scopeToCopyright.put(scopeName, copyrightProfileName)
}
fun unmapCopyright(scopeName: String) {
scopeToCopyright.remove(scopeName)
}
fun hasAnyCopyrights(): Boolean {
return defaultCopyrightName != null || !scopeToCopyright.isEmpty()
}
override fun getState(): Element? {
val result = Element("settings")
try {
schemeManagerIprProvider?.writeState(result)
if (!scopeToCopyright.isEmpty()) {
val map = Element(MODULE_TO_COPYRIGHT)
for ((scopeName, profileName) in scopeToCopyright) {
map.element(ELEMENT)
.attribute(MODULE, scopeName)
.attribute(COPYRIGHT, profileName)
}
result.addContent(map)
}
options.writeExternal(result)
}
catch (e: WriteExternalException) {
LOG.error(e)
return null
}
defaultCopyrightName?.let {
result.setAttribute(DEFAULT, it)
}
return wrapState(result, project)
}
override fun loadState(state: Element) {
val data = unwrapState(state, project, schemeManagerIprProvider, schemeManager) ?: return
data.getChild(MODULE_TO_COPYRIGHT)?.let {
for (element in it.getChildren(ELEMENT)) {
scopeToCopyright.put(element.getAttributeValue(MODULE), element.getAttributeValue(COPYRIGHT))
}
}
try {
defaultCopyrightName = data.getAttributeValue(DEFAULT)
options.readExternal(data)
}
catch (e: InvalidDataException) {
LOG.error(e)
}
}
private fun addCopyright(profile: CopyrightProfile) {
schemeManager.addScheme(InitializedSchemeWrapper(profile, schemeWriter))
}
fun getCopyrights(): Collection<CopyrightProfile> = schemeManager.allSchemes.map { it.scheme }
fun clearMappings() {
scopeToCopyright.clear()
}
fun removeCopyright(copyrightProfile: CopyrightProfile) {
schemeManager.removeScheme(copyrightProfile.name)
val it = scopeToCopyright.keys.iterator()
while (it.hasNext()) {
if (scopeToCopyright.get(it.next()) == copyrightProfile.name) {
it.remove()
}
}
}
fun replaceCopyright(name: String, profile: CopyrightProfile) {
val existingScheme = schemeManager.findSchemeByName(name)
if (existingScheme == null) {
addCopyright(profile)
}
else {
existingScheme.scheme.copyFrom(profile)
}
}
fun getCopyrightOptions(file: PsiFile): CopyrightProfile? {
val virtualFile = file.virtualFile
if (virtualFile == null || options.getOptions(virtualFile.fileType.name).getFileTypeOverride() == LanguageOptions.NO_COPYRIGHT) {
return null
}
val validationManager = DependencyValidationManager.getInstance(project)
for (scopeName in scopeToCopyright.keys) {
val packageSet = validationManager.getScope(scopeName)?.value ?: continue
if (packageSet.contains(file, validationManager)) {
scopeToCopyright.get(scopeName)?.let { schemeManager.findSchemeByName(it) }?.let { return it.scheme }
}
}
return defaultCopyright
}
}
private class CopyrightManagerPostStartupActivity : StartupActivity {
val newFileTracker = NewFileTracker()
override fun runActivity(project: Project) {
Disposer.register(project, Disposable { newFileTracker.clear() })
EditorFactory.getInstance().eventMulticaster.addDocumentListener(object : DocumentListener {
override fun documentChanged(e: DocumentEvent) {
val virtualFile = FileDocumentManager.getInstance().getFile(e.document) ?: return
val module = ProjectRootManager.getInstance(project).fileIndex.getModuleForFile(virtualFile) ?: return
if (!newFileTracker.poll(virtualFile) ||
!FileTypeUtil.getInstance().isSupportedFile(virtualFile) ||
PsiManager.getInstance(project).findFile(virtualFile) == null) {
return
}
AppUIExecutor.onUiThread(ModalityState.NON_MODAL).later().withDocumentsCommitted(project).submit {
if (!virtualFile.isValid) {
return@submit
}
val file = PsiManager.getInstance(project).findFile(virtualFile)
if (file != null && file.isWritable) {
CopyrightManager.getInstance(project).getCopyrightOptions(file)?.let {
UpdateCopyrightProcessor(project, module, file).run()
}
}
}
}
}, project)
}
}
private fun wrapScheme(element: Element): Element {
val wrapper = Element("component")
.attribute("name", "CopyrightManager")
wrapper.addContent(element)
return wrapper
}
private class CopyrightLazySchemeWrapper(name: String,
dataHolder: SchemeDataHolder<SchemeWrapper<CopyrightProfile>>,
writer: (scheme: CopyrightProfile) -> Element,
private val subStateTagName: String = "copyright") : LazySchemeWrapper<CopyrightProfile>(name, dataHolder, writer) {
override val lazyScheme = lazy {
val scheme = CopyrightProfile()
@Suppress("NAME_SHADOWING")
val dataHolder = this.dataHolder.getAndSet(null)
var element = dataHolder.read()
if (element.name != subStateTagName) {
element = element.getChild(subStateTagName)
}
element.deserializeInto(scheme)
// use effective name instead of probably missed from the serialized
// https://youtrack.jetbrains.com/v2/issue/IDEA-186546
scheme.profileName = name
@Suppress("DEPRECATION")
val allowReplaceKeyword = scheme.allowReplaceKeyword
if (allowReplaceKeyword != null && scheme.allowReplaceRegexp == null) {
scheme.allowReplaceRegexp = StringUtil.escapeToRegexp(allowReplaceKeyword)
@Suppress("DEPRECATION")
scheme.allowReplaceKeyword = null
}
scheme.resetModificationCount()
dataHolder.updateDigest(writer(scheme))
scheme
}
} | apache-2.0 | 6372142877ee6f33fe44b654b6887c19 | 37.042105 | 198 | 0.730652 | 5.009704 | false | false | false | false |
BOINC/boinc | android/BOINC/app/src/main/java/edu/berkeley/boinc/utils/BOINCDefs.kt | 4 | 3825 | /*
* This file is part of BOINC.
* http://boinc.berkeley.edu
* Copyright (C) 2020 University of California
*
* BOINC is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation,
* either version 3 of the License, or (at your option) any later version.
*
* BOINC is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with BOINC. If not, see <http://www.gnu.org/licenses/>.
*/
/*
* This tries to be the same as lib/common_defs.h
*/
@file:JvmName("BOINCDefs")
package edu.berkeley.boinc.utils
// run modes for CPU, GPU, network,
// controlled by Activity menu and snooze button
//
const val RUN_MODE_ALWAYS = 1
const val RUN_MODE_AUTO = 2
const val RUN_MODE_NEVER = 3
const val RUN_MODE_RESTORE = 4
// restore permanent mode - used only in set_X_mode() GUI RPC
// bitmap defs for task_suspend_reason, network_suspend_reason
// Note: doesn't need to be a bitmap, but keep for compatibility
//
const val SUSPEND_NOT_SUSPENDED = 0
const val SUSPEND_REASON_BATTERIES = 1
const val SUSPEND_REASON_USER_ACTIVE = 2
const val SUSPEND_REASON_USER_REQ = 4
const val SUSPEND_REASON_TIME_OF_DAY = 8
const val SUSPEND_REASON_BENCHMARKS = 16
const val SUSPEND_REASON_DISK_SIZE = 32
const val SUSPEND_REASON_CPU_THROTTLE = 64
const val SUSPEND_REASON_NO_RECENT_INPUT = 128
const val SUSPEND_REASON_INITIAL_DELAY = 256
const val SUSPEND_REASON_EXCLUSIVE_APP_RUNNING = 512
const val SUSPEND_REASON_CPU_USAGE = 1024
const val SUSPEND_REASON_NETWORK_QUOTA_EXCEEDED = 2048
const val SUSPEND_REASON_OS = 4096
const val SUSPEND_REASON_WIFI_STATE = 4097
const val SUSPEND_REASON_BATTERY_CHARGING = 4098
const val SUSPEND_REASON_BATTERY_OVERHEATED = 4099
// Values of RESULT::state
// THESE MUST BE IN NUMERICAL ORDER
// (because of the > comparison in RESULT::computing_done())
//
const val RESULT_NEW = 0
// New result
const val RESULT_FILES_DOWNLOADING = 1
// Input files for result (WU, app version) are being downloaded
const val RESULT_FILES_DOWNLOADED = 2
// Files are downloaded, result can be (or is being) computed
const val RESULT_COMPUTE_ERROR = 3
// computation failed; no file upload
const val RESULT_FILES_UPLOADING = 4
// Output files for result are being uploaded
const val RESULT_FILES_UPLOADED = 5
// Files are uploaded, notify scheduling server at some point
const val RESULT_ABORTED = 6
// result was aborted
const val RESULT_UPLOAD_FAILED = 7
// some output file permanent failure
// values of ACTIVE_TASK::task_state
//
const val PROCESS_UNINITIALIZED = 0
// process doesn't exist yet
const val PROCESS_EXECUTING = 1
// process is running, as far as we know
const val PROCESS_SUSPENDED = 9
// we've sent it a "suspend" message
const val PROCESS_ABORT_PENDING = 5
// process exceeded limits; send "abort" message, waiting to exit
const val PROCESS_QUIT_PENDING = 8
// we've sent it a "quit" message, waiting to exit
// custom value, representing booleans of edu.berkeley.boinc.rpc.Result
const val RESULT_SUSPENDED_VIA_GUI = 100
// process goes back to PROCESS_UNINITIALIZED after suspending
const val RESULT_PROJECT_SUSPENDED = 101
const val RESULT_READY_TO_REPORT = 102
const val PROCESS_ABORTED = 6
// aborted process has exited
// reasons for making a scheduler RPC:
//
const val RPC_REASON_USER_REQ = 1
const val RPC_REASON_RESULTS_DUE = 2
const val RPC_REASON_NEED_WORK = 3
const val RPC_REASON_TRICKLE_UP = 4
const val RPC_REASON_ACCT_MGR_REQ = 5
const val RPC_REASON_INIT = 6
const val RPC_REASON_PROJECT_REQ = 7
| lgpl-3.0 | e9d277371fce4fc9db4a9ac17d2c4dcd | 31.142857 | 75 | 0.751373 | 3.667306 | false | false | false | false |
d9n/intellij-rust | src/main/kotlin/org/rust/lang/core/psi/ext/RsTypeAlias.kt | 1 | 1637 | package org.rust.lang.core.psi.ext
import com.intellij.lang.ASTNode
import com.intellij.psi.PsiElement
import com.intellij.psi.stubs.IStubElementType
import org.rust.ide.icons.RsIcons
import org.rust.lang.core.psi.RsElementTypes.DEFAULT
import org.rust.lang.core.psi.RsImplItem
import org.rust.lang.core.psi.RsTraitItem
import org.rust.lang.core.psi.RsTypeAlias
import org.rust.lang.core.psi.RustPsiImplUtil
import org.rust.lang.core.stubs.RsTypeAliasStub
import javax.swing.Icon
enum class RsTypeAliasRole {
// Bump stub version if reorder fields
FREE,
TRAIT_ASSOC_TYPE,
IMPL_ASSOC_TYPE
}
val RsTypeAlias.role: RsTypeAliasRole get() {
val stub = stub
if (stub != null) return stub.role
return when (parent) {
is RsItemsOwner -> RsTypeAliasRole.FREE
is RsTraitItem -> RsTypeAliasRole.TRAIT_ASSOC_TYPE
is RsImplItem -> RsTypeAliasRole.IMPL_ASSOC_TYPE
else -> error("Unexpected parent of type alias: $parent")
}
}
val RsTypeAlias.default: PsiElement?
get() = node.findChildByType(DEFAULT)?.psi
abstract class RsTypeAliasImplMixin : RsStubbedNamedElementImpl<RsTypeAliasStub>, RsTypeAlias {
constructor(node: ASTNode) : super(node)
constructor(stub: RsTypeAliasStub, nodeType: IStubElementType<*, *>) : super(stub, nodeType)
override fun getIcon(flags: Int): Icon? = iconWithVisibility(flags, RsIcons.TYPE)
override val isPublic: Boolean get() = RustPsiImplUtil.isPublic(this, stub)
override val isAbstract: Boolean get() = typeReference == null
override val crateRelativePath: String? get() = RustPsiImplUtil.crateRelativePath(this)
}
| mit | 7f4c95d85e027a3c307b534edf2cd6b1 | 31.74 | 96 | 0.749542 | 4.0925 | false | false | false | false |
DemonWav/IntelliJBukkitSupport | src/main/kotlin/translations/sorting/template.kt | 1 | 2668 | /*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2021 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev.translations.sorting
import com.intellij.openapi.application.PathManager
import com.intellij.openapi.project.Project
import com.intellij.project.stateStore
import java.io.File
sealed class TemplateElement
data class Comment(val text: String) : TemplateElement()
data class Key(val matcher: Regex) : TemplateElement()
object EmptyLine : TemplateElement()
data class Template(val elements: List<TemplateElement>) {
companion object {
fun parse(s: String?): Template =
Template(
if (!s.isNullOrEmpty()) {
s.split('\n').map {
when {
it.isEmpty() -> EmptyLine
it.startsWith('#') -> Comment(it.substring(1).trim())
else -> Key(parseKey(it.trim()))
}
}
} else {
listOf()
}
)
private val keyRegex = Regex("([?!]?[+*]?)([^+*!?]*)([?!]?[+*]?)")
private fun parseKey(s: String) =
keyRegex.findAll(s).map {
parseQuantifier(it.groupValues[1]) +
Regex.escape(it.groupValues[2]) +
parseQuantifier(it.groupValues[3])
}.joinToString("", "^", "$").toRegex()
private fun parseQuantifier(q: String?) =
when (q) {
"!" -> "([^.])"
"!+" -> "([^.]+)"
"!*" -> "([^.]*)"
"?" -> "(.)"
"?+" -> "(..+)"
"+", "?*" -> "(.+)"
"*" -> "(.*?)"
else -> ""
}
}
}
object TemplateManager {
private const val FILE_NAME = "minecraft_localization_template.lang"
private fun globalFile(): File = File(PathManager.getConfigPath(), FILE_NAME)
private fun projectFile(project: Project): File? =
project.stateStore.directoryStorePath?.resolve(FILE_NAME)?.toFile()
fun getGlobalTemplateText() = if (globalFile().exists()) globalFile().readText() else ""
fun getProjectTemplateText(project: Project): String? =
projectFile(project)?.let { if (it.exists()) it.readText() else getGlobalTemplateText() }
fun getProjectTemplate(project: Project) = Template.parse(getProjectTemplateText(project))
fun writeGlobalTemplate(text: String) = globalFile().writeText(text)
fun writeProjectTemplate(project: Project, text: String) = projectFile(project)?.writeText(text)
}
| mit | a454b51643581e5ff9a4c401665bb6a3 | 29.666667 | 100 | 0.536357 | 4.592083 | false | false | false | false |
oboehm/jfachwert | src/main/kotlin/de/jfachwert/bank/Waehrung.kt | 1 | 10945 | /*
* Copyright (c) 2018-2020 by Oliver Boehm
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express orimplied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* (c)reated 04.08.18 by oliver ([email protected])
*/
package de.jfachwert.bank
import com.fasterxml.jackson.databind.annotation.JsonSerialize
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer
import de.jfachwert.KFachwert
import de.jfachwert.KSimpleValidator
import de.jfachwert.pruefung.NullValidator
import de.jfachwert.pruefung.exception.InvalidValueException
import de.jfachwert.pruefung.exception.LocalizedUnknownCurrencyException
import java.util.*
import java.util.logging.Level
import java.util.logging.Logger
import javax.money.CurrencyContext
import javax.money.CurrencyUnit
import javax.money.UnknownCurrencyException
/**
* Die Klasse Waehrung wurde fuer die Implementierung fuer [Geldbetrag]
* eingefuehrt und implementiert die [CurrencyUnit]. Diese ist
* Bestandteil der Money-API.
*
* @author oliver ([email protected])
* @since 1.0
*/
@JsonSerialize(using = ToStringSerializer::class)
open class Waehrung protected constructor(code: Currency, validator: KSimpleValidator<Currency>) : KFachwert, Comparable<CurrencyUnit>, CurrencyUnit {
companion object {
private val LOG = Logger.getLogger(Waehrung::class.java.name)
private val CACHE: MutableMap<String, Waehrung> = WeakHashMap()
private val VALIDATOR: KSimpleValidator<String> = Validator()
/** Default-Waehrung, die durch die Landeseinstellung (Locale) vorgegeben wird. */
@JvmField
val DEFAULT_CURRENCY = defaultCurrency
/** Default-Waehrung, die durch die Landeseinstellung (Locale) vorgegeben wird. */
@JvmField
val DEFAULT = Waehrung(DEFAULT_CURRENCY)
/** Die Euro-Waehrung als Konstante. */
@JvmField
val EUR = of("EUR")
/** Null-Konstante fuer Initialiserung. */
@JvmField
val NULL = Waehrung("XXX")
/**
* Gibt die entsprechende Currency als Waehrung zurueck. Da die Anzahl der
* Waehrungen ueberschaubar ist, werden sie in einem dauerhaften Cache
* vorgehalten.
*
* @param currency Currency
* @return Waehrung
*/
@JvmStatic
fun of(currency: Currency): Waehrung {
val key = currency.currencyCode
return CACHE.computeIfAbsent(key) { t: String? -> Waehrung(currency) }
}
/**
* Gibt die entsprechende Currency als Waehrung zurueck.
*
* @param currencyUnit CurrencyUnit
* @return Waehrung
*/
@JvmStatic
fun of(currencyUnit: CurrencyUnit): Waehrung {
return if (currencyUnit is Waehrung) {
currencyUnit
} else {
of(currencyUnit.currencyCode)
}
}
/**
* Gibt die entsprechende Currency als Waehrung zurueck.
*
* @param currency Waehrung, z.B. "EUR"
* @return Waehrung
*/
@JvmStatic
fun of(currency: String): Waehrung {
return of(toCurrency(currency))
}
/**
* Ermittelt aus dem uebergebenen String die entsprechende
* [Currency].
*
* @param name z.B. "EUR" oder auch ein einzelnes Symbol
* @return die entsprechende Waehrung
*/
@JvmStatic
fun toCurrency(name: String): Currency {
return try {
Currency.getInstance(name)
} catch (iae: IllegalArgumentException) {
if (name.length <= 3) {
for (c in Currency.getAvailableCurrencies()) {
if (matchesCurrency(name, c)) {
return c
}
}
toFallbackCurrency(name, iae)
} else {
try {
toCurrency(name.substring(0, 3))
} catch (ex: LocalizedUnknownCurrencyException) {
throw LocalizedUnknownCurrencyException(name, ex)
}
}
}
}
private fun matchesCurrency(name: String, c: Currency): Boolean {
return name.equals(c.currencyCode, ignoreCase = true) || name.equals(c.symbol, ignoreCase = true)
}
private fun toFallbackCurrency(name: String, iae: IllegalArgumentException): Currency {
return if (name == "\u20ac") {
Currency.getInstance("EUR")
} else {
throw LocalizedUnknownCurrencyException(name, iae)
}
}
/**
* Validiert den uebergebenen Waehrungscode.
*
* @param code Waehrungscode als String
* @return Waehrungscode zur Weiterverarbeitung
*/
@JvmStatic
fun validate(code: String): String {
return VALIDATOR.validate(code)
}
/**
* Lieft das Waehrungssymbol der uebergebenen Waehrungseinheit.
*
* @param cu Waehrungseinheit
* @return z.B. das Euro-Zeichen
*/
@JvmStatic
fun getSymbol(cu: CurrencyUnit): String {
return try {
of(cu).symbol
} catch (ex: IllegalArgumentException) {
LOG.log(Level.WARNING, "Cannot get symbol for '$cu':", ex)
cu.currencyCode
}
}
/**
* Ermittelt die Waehrung. Urspruenglich wurde die Default-Currency ueber
* <pre>
* Currency.getInstance(Locale.getDefault())
* </pre>
* ermittelt. Dies fuehrte aber auf der Sun zu Problemen, da dort
* die Currency fuer die Default-Locale folgende Exception hervorrief:
* <pre>
* java.lang.IllegalArgumentException
* at java.util.Currency.getInstance(Currency.java:384)
* at de.jfachwert.bank.Geldbetrag.<clinit>
* ...
* </pre>
*
* @return normalerweise die deutsche Currency
*/
private val defaultCurrency: Currency
get() {
val locales = arrayOf(Locale.getDefault(), Locale.GERMANY, Locale.GERMAN)
for (loc in locales) {
try {
return Currency.getInstance(loc)
} catch (iae: IllegalArgumentException) {
LOG.log(Level.INFO,
"No currency for locale '$loc' available on this machine - will try next one.", iae)
}
}
return Currency.getAvailableCurrencies().iterator().next()
}
init {
CACHE[DEFAULT_CURRENCY.currencyCode] = DEFAULT
}
}
/**
* Liefert die Waehrung als Currency zurueck.
*
* @return Waehrung als Currency
*/
val code: Currency
/**
* Darueber kann eine Waehrung angelegt werden.
*
* @param code z.B. "EUR"
*/
constructor(code: String) : this(toCurrency(code)) {}
/**
* Darueber kann eine Waehrung angelegt werden.
*
* @param code Waehrung
*/
constructor(code: Currency) : this(code, NullValidator<Currency>()) {}
/**
* Liefert die Currency zurueck.
*
* @return die Currency aus java.util.
*/
val currency: Currency
get() = code
/**
* Liefert den Waehrungscode.
*
* @return z.B. "EUR"
*/
override fun getCurrencyCode(): String {
return code.currencyCode
}
/**
* Liefert den numerischen Waehrungscode.
*
* @return z.B. 978 fuer EUro
*/
override fun getNumericCode(): Int {
return code.numericCode
}
/**
* Liefert die Anzahl der Nachkommastellen einer Waehrung.
*
* @return meist 2, manchmal 0
*/
override fun getDefaultFractionDigits(): Int {
return code.defaultFractionDigits
}
override fun getContext(): CurrencyContext {
throw UnsupportedOperationException("not yet implemented")
}
/**
* Liefert das Waehrungssymbol.
*
* @return z.B. "$"
*/
val symbol: String
get() = code.symbol
/**
* Zum Vergleich wird der Waehrungscode herangezogen und alphabetisch
* verglichen.
*
* @param other die andere Waerhung
* @return eine negative Zahl wenn die ander Waehrung alphabetisch
* danach kommt.
*/
override fun compareTo(other: CurrencyUnit): Int {
return currencyCode.compareTo(other.currencyCode)
}
/**
* Zwei Waehrungen sind nur dann gleich, wenn sie vom gleichen Typ sind .
*
* @param other zu vergleichender Waehrung
* @return true bei Gleichheit
* @see java.lang.Object.equals
*/
override fun equals(other: Any?): Boolean {
if (other !is Waehrung) {
return false
}
return code == other.code
}
/* (non-Javadoc)
* @see java.lang.Object#hashCode()
*/
override fun hashCode(): Int {
return code.hashCode()
}
/**
* Als toString-Implementierung wird der Waehrungscode ausgegeben.
*
* @return z.B. "EUR"
*/
override fun toString(): String {
return currencyCode
}
init {
this.code = validator.verify(code)
}
/**
* Dieser Validator ist fuer die Ueberpruefung von Waehrungen vorgesehen.
*
* @since 3.0
*/
class Validator : KSimpleValidator<String> {
/**
* Wenn der uebergebene Waehrungsstring gueltig ist, wird er
* unveraendert zurueckgegeben, damit er anschliessend von der
* aufrufenden Methode weiterverarbeitet werden kann. Ist der Wert
* nicht gueltig, wird eine [javax.validation.ValidationException]
* geworfen.
*
* @param value Waehrungs-String, der validiert wird
* @return Wert selber, wenn er gueltig ist
*/
override fun validate(value: String): String {
try {
toCurrency(value)
} catch (ex: IllegalArgumentException) {
throw InvalidValueException(value, "currency")
} catch (ex: UnknownCurrencyException) {
throw InvalidValueException(value, "currency")
}
return value
}
}
} | apache-2.0 | 04ecfc6bbfe8415dc43ce5d0652b1d62 | 29.833803 | 150 | 0.58392 | 4.558517 | false | false | false | false |
cashapp/sqldelight | sqldelight-compiler/src/main/kotlin/app/cash/sqldelight/core/lang/util/InsertStmtUtil.kt | 1 | 729 | package app.cash.sqldelight.core.lang.util
import com.alecstrong.sql.psi.core.psi.LazyQuery
import com.alecstrong.sql.psi.core.psi.NamedElement
import com.alecstrong.sql.psi.core.psi.SqlInsertStmt
/**
* The list of columns that values are being provided for.
*/
internal val SqlInsertStmt.columns: List<NamedElement>
get() {
val columns = table.query.columns
.map { (it.element as NamedElement) }
if (columnNameList.isEmpty()) return columns
val columnMap = linkedMapOf(*columns.map { it.name to it }.toTypedArray())
return columnNameList.mapNotNull { columnMap[it.name] }
}
internal val SqlInsertStmt.table: LazyQuery
get() = tablesAvailable(this).first { it.tableName.name == tableName.name }
| apache-2.0 | e1ee406b3643c22a116c115941a542ac | 33.714286 | 78 | 0.744856 | 3.796875 | false | false | false | false |
wikimedia/apps-android-wikipedia | app/src/main/java/org/wikipedia/views/SwipeableItemTouchHelperCallback.kt | 1 | 6182 | package org.wikipedia.views
import android.content.Context
import android.graphics.Bitmap
import android.graphics.Canvas
import android.graphics.Paint
import android.graphics.Typeface
import androidx.annotation.ColorRes
import androidx.annotation.DrawableRes
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.ItemTouchHelper
import androidx.recyclerview.widget.RecyclerView
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout
import org.wikipedia.R
import org.wikipedia.util.DimenUtil
import org.wikipedia.util.DimenUtil.densityScalar
import org.wikipedia.util.ResourceUtil.bitmapFromVectorDrawable
import org.wikipedia.util.ResourceUtil.getThemedColor
class SwipeableItemTouchHelperCallback @JvmOverloads constructor(
context: Context,
@ColorRes swipeColor: Int = R.color.red50,
@DrawableRes swipeIcon: Int = R.drawable.ic_delete_white_24dp,
@ColorRes val swipeIconTint: Int? = null,
private val swipeIconAndTextFromTag: Boolean = false,
val refreshLayout: SwipeRefreshLayout? = null
) : ItemTouchHelper.Callback() {
interface Callback {
fun onSwipe()
fun isSwipeable(): Boolean
}
private var swipeIconBitmap: Bitmap
private val swipeBackgroundPaint = Paint()
private val swipeIconPaint = Paint()
private val itemBackgroundPaint = Paint()
private val valueTextPaint = Paint().apply {
color = ContextCompat.getColor(context, swipeIconTint ?: android.R.color.white)
textSize = DimenUtil.dpToPx(12f)
textAlign = Paint.Align.CENTER
typeface = Typeface.create("sans-serif-medium", Typeface.NORMAL)
}
var swipeableEnabled = false
init {
swipeBackgroundPaint.style = Paint.Style.FILL
swipeBackgroundPaint.color = ContextCompat.getColor(context, swipeColor)
itemBackgroundPaint.style = Paint.Style.FILL
itemBackgroundPaint.color = getThemedColor(context, android.R.attr.windowBackground)
swipeIconBitmap = bitmapFromVectorDrawable(context, swipeIcon, swipeIconTint)
}
override fun isLongPressDragEnabled(): Boolean {
return false
}
override fun isItemViewSwipeEnabled(): Boolean {
return swipeableEnabled
}
override fun getMovementFlags(recyclerView: RecyclerView, holder: RecyclerView.ViewHolder): Int {
val dragFlags = 0 // ItemTouchHelper.UP | ItemTouchHelper.DOWN;
val swipeFlags = if (holder is Callback && holder.isSwipeable()) ItemTouchHelper.START or ItemTouchHelper.END else 0
return makeMovementFlags(dragFlags, swipeFlags)
}
override fun onMove(recyclerView: RecyclerView, source: RecyclerView.ViewHolder, target: RecyclerView.ViewHolder): Boolean {
return source.itemViewType == target.itemViewType
}
override fun onSwiped(viewHolder: RecyclerView.ViewHolder, i: Int) {
if (viewHolder is Callback) {
viewHolder.onSwipe()
}
}
override fun onSelectedChanged(viewHolder: RecyclerView.ViewHolder?, actionState: Int) {
super.onSelectedChanged(viewHolder, actionState)
refreshLayout?.isEnabled = actionState != ItemTouchHelper.ACTION_STATE_SWIPE
}
override fun onChildDraw(canvas: Canvas, recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder,
dx: Float, dy: Float, actionState: Int, isCurrentlyActive: Boolean) {
if (actionState == ItemTouchHelper.ACTION_STATE_SWIPE) {
// Text and icon sources from itemView tag.
var swipeText = ""
if (swipeIconAndTextFromTag &&
viewHolder.itemView.getTag(R.string.tag_icon_key) != null &&
viewHolder.itemView.getTag(R.string.tag_text_key) != null) {
swipeText = viewHolder.itemView.getTag(R.string.tag_text_key).toString()
swipeIconBitmap = bitmapFromVectorDrawable(recyclerView.context, viewHolder.itemView.getTag(R.string.tag_icon_key) as Int, swipeIconTint)
}
canvas.drawRect(0f, viewHolder.itemView.top.toFloat(), viewHolder.itemView.width.toFloat(), (viewHolder.itemView.top + viewHolder.itemView.height).toFloat(), swipeBackgroundPaint)
val iconPositionY = (viewHolder.itemView.top + (viewHolder.itemView.height / 2 - (if (swipeIconAndTextFromTag) (swipeIconBitmap.height / SWIPE_ICON_POSITION_SCALE).toInt() else swipeIconBitmap.height / 2))).toFloat()
val iconTextPositionY = viewHolder.itemView.top + (viewHolder.itemView.height / 2 + swipeIconBitmap.height) - SWIPE_ICON_PADDING_DP + SWIPE_TEXT_PADDING_DP
if (dx >= 0) {
canvas.drawBitmap(swipeIconBitmap, SWIPE_ICON_PADDING_DP * SWIPE_ICON_POSITION_SCALE * densityScalar, iconPositionY, swipeIconPaint)
if (swipeIconAndTextFromTag) {
canvas.drawText(swipeText, swipeIconBitmap.width + SWIPE_ICON_PADDING_DP * SWIPE_TEXT_POSITION_SCALE,
iconTextPositionY, valueTextPaint)
}
} else {
canvas.drawBitmap(swipeIconBitmap, viewHolder.itemView.right - swipeIconBitmap.width - SWIPE_ICON_PADDING_DP * SWIPE_ICON_POSITION_SCALE * densityScalar, iconPositionY, swipeIconPaint)
if (swipeIconAndTextFromTag) {
canvas.drawText(swipeText, viewHolder.itemView.right - swipeIconBitmap.width - SWIPE_ICON_PADDING_DP * SWIPE_TEXT_POSITION_SCALE,
iconTextPositionY, valueTextPaint)
}
}
canvas.drawRect(dx, viewHolder.itemView.top.toFloat(), viewHolder.itemView.width + dx, (viewHolder.itemView.top + viewHolder.itemView.height).toFloat(), itemBackgroundPaint)
viewHolder.itemView.translationX = dx
} else {
super.onChildDraw(canvas, recyclerView, viewHolder, dx, dy, actionState, isCurrentlyActive)
}
}
companion object {
private const val SWIPE_ICON_PADDING_DP = 16f
private const val SWIPE_TEXT_PADDING_DP = 2f
private const val SWIPE_ICON_POSITION_SCALE = 1.4f
private const val SWIPE_TEXT_POSITION_SCALE = 2f
}
}
| apache-2.0 | 1918a9717a5c8d85873506a84caf8a59 | 48.854839 | 228 | 0.702038 | 4.879242 | false | false | false | false |
stripe/stripe-android | camera-core/src/main/java/com/stripe/android/camera/framework/util/Layout.kt | 1 | 16841 | package com.stripe.android.camera.framework.util
import android.graphics.Rect
import android.graphics.RectF
import android.util.Size
import android.util.SizeF
import android.view.View
import androidx.annotation.CheckResult
import androidx.annotation.RestrictTo
import kotlin.math.max
import kotlin.math.min
import kotlin.math.roundToInt
/**
* Determine the maximum size of rectangle with a given aspect ratio (X/Y) that can fit inside the
* specified area.
*
* For example, if the aspect ratio is 1/2 and the area is 2x2, the resulting rectangle would be
* size 1x2 and look like this:
* ```
* ________
* | | | |
* | | | |
* | | | |
* |_|____|_|
* ```
*/
@CheckResult
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
fun maxAspectRatioInSize(area: Size, aspectRatio: Float): Size {
var width = area.width
var height = (width / aspectRatio).roundToInt()
return if (height <= area.height) {
Size(area.width, height)
} else {
height = area.height
width = (height * aspectRatio).roundToInt()
Size(min(width, area.width), height)
}
}
/**
* Determine the minimum size of rectangle with a given aspect ratio (X/Y) that a specified area
* can fit inside.
*
* For example, if the aspect ratio is 1/2 and the area is 1x1, the resulting rectangle would be
* size 1x2 and look like this:
* ```
* ____
* |____|
* | |
* |____|
* |____|
* ```
*/
@CheckResult
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
fun minAspectRatioSurroundingSize(area: Size, aspectRatio: Float): Size {
var width = area.width
var height = (width / aspectRatio).roundToInt()
return if (height >= area.height) {
Size(area.width, height)
} else {
height = area.height
width = (height * aspectRatio).roundToInt()
Size(max(width, area.width), height)
}
}
/**
* Given a size and an aspect ratio, resize the area to fit that aspect ratio. If the desired aspect
* ratio is smaller than the one of the provided size, the size will be cropped to match. If the
* desired aspect ratio is larger than the that of the provided size, then the size will be expanded
* to match.
*/
@CheckResult
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
fun adjustSizeToAspectRatio(area: Size, aspectRatio: Float): Size = if (aspectRatio < 1) {
Size(area.width, (area.width / aspectRatio).roundToInt())
} else {
Size((area.height * aspectRatio).roundToInt(), area.height)
}
/**
* Scale up a [Size] so that it fills a [containingSize] while maintaining its original aspect
* ratio.
*
* If using this to project a preview image onto a full camera image, This makes a few assumptions:
* 1. the preview image [Size] and full image [containingSize] are centered relative to each other
* 2. the preview image and the full image have the same orientation
* 3. the preview image and the full image share either a horizontal or vertical field of view
* 4. the non-shared field of view must be smaller on the preview image than the full image
*
* Note that the [Size] and the [containingSize] are allowed to have completely independent
* resolutions.
*/
@CheckResult
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
fun Size.scaleAndCenterWithin(containingSize: Size): Rect {
val aspectRatio = width.toFloat() / height
// Since the preview image may be at a different resolution than the full image, scale the
// preview image to be circumscribed by the fullImage.
val scaledSize = maxAspectRatioInSize(containingSize, aspectRatio)
val left = (containingSize.width - scaledSize.width) / 2
val top = (containingSize.height - scaledSize.height) / 2
return Rect(
left,
top,
left + scaledSize.width,
top + scaledSize.height
)
}
@CheckResult
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
fun Size.scaleAndCenterWithin(containingRect: Rect): Rect =
this.scaleAndCenterWithin(containingRect.size()).move(containingRect.left, containingRect.top)
/**
* Calculate the position of the [Size] surrounding the [surroundedSize]. This makes a few
* assumptions:
* 1. the [Size] and the [surroundedSize] are centered relative to each other.
* 2. the [Size] and the [surroundedSize] have the same orientation
* 3. the [surroundedSize] and the [Size] share either a horizontal or vertical field of view
* 4. the non-shared field of view must be smaller on the [surroundedSize] than the [Size]
*
* If using this to project a full camera image onto a preview image, This makes a few assumptions:
* 1. the preview image [surroundedSize] and full image [Size] are centered relative to each other
* 2. the preview image and the full image have the same orientation
* 3. the preview image and the full image share either a horizontal or vertical field of view
* 4. the non-shared field of view must be smaller on the preview image than the full image
*
* Note that the [Size] and the [surroundedSize] are allowed to have completely independent
* resolutions.
*/
@CheckResult
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
fun Size.scaleAndCenterSurrounding(surroundedSize: Size): Rect {
val aspectRatio = width.toFloat() / height
val scaledSize = minAspectRatioSurroundingSize(surroundedSize, aspectRatio)
val left = (surroundedSize.width - scaledSize.width) / 2
val top = (surroundedSize.height - scaledSize.height) / 2
return Rect(
left,
top,
left + scaledSize.width,
top + scaledSize.height
)
}
/**
* Scale a size based on percentage scale values, and keep track of its position.
*/
@CheckResult
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
fun Size.scaleCentered(x: Float, y: Float): Rect {
val newSize = this.scale(x, y)
val left = (this.width - newSize.width) / 2
val top = (this.height - newSize.height) / 2
return Rect(
left,
top,
left + newSize.width,
top + newSize.height
)
}
/**
* Calculate the new size based on percentage scale values.
*/
@CheckResult
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
fun SizeF.scale(x: Float, y: Float) = SizeF(this.width * x, this.height * y)
/**
* Calculate the new size based on a percentage scale.
*/
@CheckResult
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
fun SizeF.scale(scale: Float) = this.scale(scale, scale)
/**
* Calculate the new size based on percentage scale values.
*/
@CheckResult
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
fun Size.scale(x: Float, y: Float): Size =
Size((this.width * x).roundToInt(), (this.height * y).roundToInt())
/**
* Calculate the new size based on a percentage scale.
*/
@CheckResult
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
fun Size.scale(scale: Float) = this.scale(scale, scale)
/**
* Center a size on a given rectangle. The size may be larger or smaller than the rect.
*/
@CheckResult
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
fun Size.centerOn(rect: Rect) = Rect(
/* left */
rect.centerX() - this.width / 2,
/* top */
rect.centerY() - this.height / 2,
/* right */
rect.centerX() + this.width / 2,
/* bottom */
rect.centerY() + this.height / 2
)
/**
* Scale a [Rect] to have a size equivalent to the [scaledSize]. This will also scale the position
* of the [Rect].
*
* For example, scaling a Rect(1, 2, 3, 4) by Size(5, 6) will result in a Rect(5, 12, 15, 24)
*/
@CheckResult
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
fun RectF.scaled(scaledSize: Size) = RectF(
this.left * scaledSize.width,
this.top * scaledSize.height,
this.right * scaledSize.width,
this.bottom * scaledSize.height
)
/**
* Scale a [Rect] to have a size equivalent to the [scaledSize]. This will maintain the center
* position of the [Rect].
*
* For example, scaling a Rect(5, 6, 7, 8) by Size(2, 0.5) will result
*/
@CheckResult
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
fun RectF.centerScaled(scaleX: Float, scaleY: Float) = RectF(
this.centerX() - this.width() * scaleX / 2,
this.centerY() - this.height() * scaleY / 2,
this.centerX() + this.width() * scaleX / 2,
this.centerY() + this.height() * scaleY / 2
)
@CheckResult
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
fun Rect.centerScaled(scaleX: Float, scaleY: Float) = Rect(
this.centerX() - (this.width() * scaleX / 2).toInt(),
this.centerY() - (this.height() * scaleY / 2).toInt(),
this.centerX() + (this.width() * scaleX / 2).toInt(),
this.centerY() + (this.height() * scaleY / 2).toInt()
)
/**
* Converts a size to rectangle with the top left corner at 0,0
*/
@CheckResult
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
fun Size.toRect() = Rect(0, 0, this.width, this.height)
@CheckResult
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
fun Size.toRectF() = RectF(0F, 0F, this.width.toFloat(), this.height.toFloat())
/**
* Transpose a size's width and height.
*/
@CheckResult
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
fun Size.transpose() = Size(this.height, this.width)
/**
* Return a rect that is the intersection of two other rects
*/
@CheckResult
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
fun Rect.intersectionWith(rect: Rect): Rect {
require(this.intersect(rect)) {
"Given rects do not intersect $this <> $rect"
}
return Rect(
max(this.left, rect.left),
max(this.top, rect.top),
min(this.right, rect.right),
min(this.bottom, rect.bottom)
)
}
/**
* Move relative to its current position
*/
@CheckResult
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
fun Rect.move(relativeX: Int, relativeY: Int) = Rect(
this.left + relativeX,
this.top + relativeY,
this.right + relativeX,
this.bottom + relativeY
)
/**
* Move relative to its current position
*/
@CheckResult
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
fun RectF.move(relativeX: Float, relativeY: Float) = RectF(
this.left + relativeX,
this.top + relativeY,
this.right + relativeX,
this.bottom + relativeY
)
@CheckResult
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
fun Size.toSizeF() = SizeF(width.toFloat(), height.toFloat())
@CheckResult
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
fun SizeF.toSize() = Size(width.roundToInt(), height.roundToInt())
@CheckResult
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
fun Rect.toRectF() =
RectF(left.toFloat(), top.toFloat(), right.toFloat(), bottom.toFloat())
@CheckResult
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
fun RectF.toRect() =
Rect(left.roundToInt(), top.roundToInt(), right.roundToInt(), bottom.roundToInt())
/**
* Takes a relation between a region of interest and a size and projects the region of interest
* to that new location
*/
@CheckResult
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
fun SizeF.projectRegionOfInterest(toSize: SizeF, regionOfInterest: RectF): RectF {
require(this.width > 0 && this.height > 0) {
"Cannot project from container with non-positive dimensions"
}
return RectF(
regionOfInterest.left * toSize.width / this.width,
regionOfInterest.top * toSize.height / this.height,
regionOfInterest.right * toSize.width / this.width,
regionOfInterest.bottom * toSize.height / this.height
)
}
/**
* Takes a relation between a region of interest and a size and projects the region of interest
* to that new location
*/
@CheckResult
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
fun Size.projectRegionOfInterest(toSize: Size, regionOfInterest: Rect) =
this.toSizeF().projectRegionOfInterest(toSize.toSizeF(), regionOfInterest.toRectF()).toRect()
@CheckResult
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
fun RectF.projectRegionOfInterest(toSize: SizeF, regionOfInterest: RectF) =
this.size().projectRegionOfInterest(toSize, regionOfInterest.move(-this.left, -this.top))
@CheckResult
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
fun Rect.projectRegionOfInterest(toSize: Size, regionOfInterest: Rect) =
this.size().projectRegionOfInterest(toSize, regionOfInterest.move(-this.left, -this.top))
/**
* Project a region of interest from one [Rect] to another. For example, given the rect and region
* of interest:
* _______
* | |
* | _ |
* | |_| |
* | |
* |_______|
*
* When projected to the following region:
* ___________
* | |
* | |
* |___________|
*
* The position and size of the region of interest are scaled to the new rect.
*/
@CheckResult
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
fun RectF.projectRegionOfInterest(toRect: RectF, regionOfInterest: RectF) =
this.projectRegionOfInterest(toRect.size(), regionOfInterest).move(toRect.left, toRect.top)
/**
* Project a region of interest from one [Rect] to another. For example, given the rect and region
* of interest:
* _______
* | |
* | _ |
* | |_| |
* | |
* |_______|
*
* When projected to the following region:
* ___________
* | |
* | |
* |___________|
*
* The position and size of the region of interest are scaled to the new rect.
*/
@CheckResult
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
fun Rect.projectRegionOfInterest(toRect: Rect, regionOfInterest: Rect) =
this.projectRegionOfInterest(toRect.size(), regionOfInterest).move(toRect.left, toRect.top)
/**
* This method allows relocating and resizing a portion of a [Size]. It returns the required
* translations required to achieve this relocation. This is useful for zooming in on sections of
* an image.
*
* For example, given a size 5x5 and an original region (2, 2, 3, 3):
*
* _______
* | |
* | _ |
* | |_| |
* | |
* |_______|
*
* If the [newRegion] is (1, 1, 4, 4) and the [newSize] is 6x6, the result will look like this:
*
* ________
* | ___ |
* | | | |
* | | | |
* | |___| |
* | |
* |________|
*
* Nine individual translations will be returned for the affected regions. The returned [Rect]s
* will look like this:
*
* ________
* |_|___|__|
* | | | |
* | | | |
* |_|___|__|
* | | | |
* |_|___|__|
*/
@CheckResult
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
fun Size.resizeRegion(
originalRegion: Rect,
newRegion: Rect,
newSize: Size
): Map<Rect, Rect> = mapOf(
Rect(
0,
0,
originalRegion.left,
originalRegion.top
) to Rect(
0,
0,
newRegion.left,
newRegion.top
),
Rect(
originalRegion.left,
0,
originalRegion.right,
originalRegion.top
) to Rect(
newRegion.left,
0,
newRegion.right,
newRegion.top
),
Rect(
originalRegion.right,
0,
this.width,
originalRegion.top
) to Rect(
newRegion.right,
0,
newSize.width,
newRegion.top
),
Rect(
0,
originalRegion.top,
originalRegion.left,
originalRegion.bottom
) to Rect(
0,
newRegion.top,
newRegion.left,
newRegion.bottom
),
Rect(
originalRegion.left,
originalRegion.top,
originalRegion.right,
originalRegion.bottom
) to Rect(
newRegion.left,
newRegion.top,
newRegion.right,
newRegion.bottom
),
Rect(
originalRegion.right,
originalRegion.top,
this.width,
originalRegion.bottom
) to Rect(
newRegion.right,
newRegion.top,
newSize.width,
newRegion.bottom
),
Rect(
0,
originalRegion.bottom,
originalRegion.left,
this.height
) to Rect(
0,
newRegion.bottom,
newRegion.left,
newSize.height
),
Rect(
originalRegion.left,
originalRegion.bottom,
originalRegion.right,
this.height
) to Rect(
newRegion.left,
newRegion.bottom,
newRegion.right,
newSize.height
),
Rect(
originalRegion.right,
originalRegion.bottom,
this.width,
this.height
) to Rect(
newRegion.right,
newRegion.bottom,
newSize.width,
newSize.height
)
)
/**
* Determine the size of a [Rect].
*/
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
fun Rect.size() = Size(width(), height())
/**
* Determine the size of a [RectF].
*/
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
fun RectF.size() = SizeF(width(), height())
/**
* Determine the aspect ratio of a [Size].
*/
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
fun Size.aspectRatio() = width.toFloat() / height.toFloat()
/**
* Determine the aspect ratio of a [SizeF].
*/
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
fun SizeF.aspectRatio() = width / height
/**
* Determine the size of a [View].
*/
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
fun View.size() = Size(width, height)
| mit | 5a9e4ae41738645b14266d753fd1cc6e | 27.59253 | 100 | 0.658571 | 3.811906 | false | false | false | false |
willmadison/Axiomatic | src/main/kotlin/com/willmadison/store/Cart.kt | 1 | 463 | package com.willmadison.store
import java.util.*
data class Cart(val items: Set<CartItem> = emptySet(), val promotions: Set<String> = emptySet(), val id: String = UUID.randomUUID().toString())
fun exampleCart() = Cart(items = setOf(
CartItem("dummyUpc", "dummySku", 5.0, 10.0),
CartItem("dummyUpc1", "dummySku1", 7.0, 6.0),
CartItem("dummyUpc2", "dummySku2", 3.0, 5.0)
), promotions = setOf("promotion1", "promotion2")) | mit | be8ec8cf1d3ef75bdf0b05f0a71bc56b | 41.181818 | 143 | 0.637149 | 3.355072 | false | false | false | false |
stripe/stripe-android | payments-core/src/test/java/com/stripe/android/model/TokenFixtures.kt | 1 | 2354 | package com.stripe.android.model
import com.stripe.android.model.parsers.TokenJsonParser
import org.json.JSONObject
internal object TokenFixtures {
private val PARSER = TokenJsonParser()
val CARD_TOKEN_JSON = JSONObject(
"""
{
"id": "tok_189fi32eZvKYlo2Ct0KZvU5Y",
"object": "token",
"card": {
"id": "card_189fi32eZvKYlo2CHK8NPRME",
"object": "card",
"address_city": null,
"address_country": null,
"address_line1": null,
"address_line1_check": null,
"address_line2": null,
"address_state": null,
"address_zip": null,
"address_zip_check": null,
"brand": "Visa",
"country": "US",
"cvc_check": null,
"dynamic_last4": null,
"exp_month": 8,
"exp_year": 2017,
"funding": "credit",
"last4": "4242",
"metadata": {},
"name": null,
"tokenization_method": null
},
"client_ip": null,
"created": 1462905355,
"livemode": false,
"type": "card",
"used": false
}
""".trimIndent()
)
val CARD_TOKEN = requireNotNull(PARSER.parse(CARD_TOKEN_JSON))
val BANK_TOKEN_JSON = JSONObject(
"""
{
"id": "btok_9xJAbronBnS9bH",
"object": "token",
"bank_account": {
"id": "ba_19d8Fh2eZvKYlo2C9qw8RwpV",
"object": "bank_account",
"account_holder_name": "Jane Austen",
"account_holder_type": "individual",
"bank_name": "STRIPE TEST BANK",
"country": "US",
"currency": "usd",
"fingerprint": "1JWtPxqbdX5Gamtc",
"last4": "6789",
"routing_number": "110000000",
"status": "new"
},
"client_ip": null,
"created": 1484765567,
"livemode": false,
"type": "bank_account",
"used": false
}
""".trimIndent()
)
val BANK_TOKEN = requireNotNull(PARSER.parse(BANK_TOKEN_JSON))
}
| mit | f0947e0d5c65a19ecf350b9a6b642e55 | 29.973684 | 66 | 0.446049 | 4.108202 | false | false | false | false |
JoachimR/Bible2net | app/src/main/java/de/reiss/bible2net/theword/note/list/NoteListViewModel.kt | 1 | 1267 | package de.reiss.bible2net.theword.note.list
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import de.reiss.bible2net.theword.architecture.AsyncLoad
import de.reiss.bible2net.theword.architecture.AsyncLoadStatus.LOADING
open class NoteListViewModel(private val repository: NoteListRepository) : ViewModel() {
private val notesLiveData: MutableLiveData<AsyncLoad<FilteredNotes>> = MutableLiveData()
init {
notesLiveData.value = AsyncLoad.success(FilteredNotes())
}
open fun notesLiveData() = notesLiveData
open fun loadNotes() {
repository.getAllNotes(notesLiveData())
}
open fun applyNewFilter(query: String) {
repository.applyNewFilter(query, notesLiveData())
}
fun notes() = notesLiveData().value?.data ?: FilteredNotes(emptyList(), emptyList(), "")
fun isLoadingNotes() = notesLiveData().value?.loadStatus == LOADING
class Factory(private val repository: NoteListRepository) :
ViewModelProvider.NewInstanceFactory() {
override fun <T : ViewModel> create(modelClass: Class<T>): T {
@Suppress("UNCHECKED_CAST")
return NoteListViewModel(repository) as T
}
}
}
| gpl-3.0 | 214db6b36d0256698fad80e0de5774a8 | 30.675 | 92 | 0.722968 | 4.854406 | false | false | false | false |
exponent/exponent | android/versioned-abis/expoview-abi42_0_0/src/main/java/abi42_0_0/expo/modules/av/progress/ProgressLooper.kt | 2 | 1633 | package abi42_0_0.expo.modules.av.progress
typealias TimeMachineTick = () -> Unit
interface TimeMachine {
fun scheduleAt(intervalMillis: Long, callback: TimeMachineTick)
val time: Long
}
typealias PlayerProgressListener = () -> Unit
class ProgressLooper(private val timeMachine: TimeMachine) {
private var interval = 0L
private var nextExpectedTick = -1L
private var waiting = false
private var shouldLoop: Boolean
get() = interval > 0 && nextExpectedTick >= 0 && !waiting
set(value) {
if (!value) {
interval = 0L
nextExpectedTick = -1L
waiting = false
}
}
private var listener: PlayerProgressListener? = null
fun setListener(listener: PlayerProgressListener) {
this.listener = listener
}
fun loop(interval: Long, listener: PlayerProgressListener) {
this.listener = listener
this.interval = interval
scheduleNextTick()
}
fun stopLooping() {
this.shouldLoop = false
this.listener = null
}
fun isLooping(): Boolean {
return this.interval > 0
}
private fun scheduleNextTick() {
if (nextExpectedTick == -1L) {
nextExpectedTick = timeMachine.time
}
if (shouldLoop) {
nextExpectedTick += calculateNextInterval()
waiting = true
timeMachine.scheduleAt(nextExpectedTick - timeMachine.time) {
waiting = false
listener?.invoke()
scheduleNextTick()
}
}
}
private fun calculateNextInterval() =
if (nextExpectedTick > timeMachine.time) {
interval
} else {
(((timeMachine.time - nextExpectedTick) / interval) + 1) * interval
}
}
| bsd-3-clause | 1f692a657f371c5d9eb7b965f33e3db5 | 22.328571 | 73 | 0.659522 | 4.461749 | false | false | false | false |
HabitRPG/habitrpg-android | Habitica/src/main/java/com/habitrpg/android/habitica/ui/fragments/social/party/PartyInviteFragment.kt | 2 | 2431 | package com.habitrpg.android.habitica.ui.fragments.social.party
import android.os.Bundle
import android.text.InputType
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.EditText
import com.habitrpg.android.habitica.R
import com.habitrpg.android.habitica.components.UserComponent
import com.habitrpg.android.habitica.databinding.FragmentPartyInviteBinding
import com.habitrpg.android.habitica.helpers.AppConfigManager
import com.habitrpg.android.habitica.ui.fragments.BaseFragment
import javax.inject.Inject
class PartyInviteFragment : BaseFragment<FragmentPartyInviteBinding>() {
@Inject
lateinit var configManager: AppConfigManager
override var binding: FragmentPartyInviteBinding? = null
override fun createBinding(inflater: LayoutInflater, container: ViewGroup?): FragmentPartyInviteBinding {
return FragmentPartyInviteBinding.inflate(inflater, container, false)
}
var isEmailInvite: Boolean = false
val values: Array<String>
get() {
val values = ArrayList<String>()
for (i in 0 until (binding?.invitationWrapper?.childCount ?: 0)) {
val valueEditText = binding?.invitationWrapper?.getChildAt(i) as? EditText
if (valueEditText?.text?.toString()?.isNotEmpty() == true) {
values.add(valueEditText.text.toString())
}
}
return values.toTypedArray()
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
if (isEmailInvite) {
binding?.inviteDescription?.text = getString(R.string.invite_email_description)
} else {
binding?.inviteDescription?.text = getString(R.string.invite_username_description)
}
addInviteField()
binding?.addInviteButton?.setOnClickListener { addInviteField() }
}
override fun injectFragment(component: UserComponent) {
component.inject(this)
}
private fun addInviteField() {
val editText = EditText(context)
if (isEmailInvite) {
editText.setHint(R.string.email)
editText.inputType = InputType.TYPE_TEXT_VARIATION_EMAIL_ADDRESS
} else {
editText.setHint(R.string.username)
}
binding?.invitationWrapper?.addView(editText)
}
}
| gpl-3.0 | 716eb064eae30b05c9a385b5f3e2b9d5 | 33.728571 | 109 | 0.695187 | 4.90121 | false | false | false | false |
SimpleMobileTools/Simple-Commons | commons/src/main/kotlin/com/simplemobiletools/commons/activities/BaseSimpleActivity.kt | 1 | 43943 | package com.simplemobiletools.commons.activities
import android.annotation.SuppressLint
import android.app.Activity
import android.app.ActivityManager
import android.app.RecoverableSecurityException
import android.app.role.RoleManager
import android.content.ActivityNotFoundException
import android.content.Context
import android.content.Intent
import android.graphics.BitmapFactory
import android.graphics.Color
import android.graphics.PorterDuff
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.provider.DocumentsContract
import android.provider.MediaStore
import android.provider.Settings
import android.telecom.TelecomManager
import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.view.WindowManager
import android.widget.EditText
import android.widget.ImageView
import android.widget.Toast
import androidx.annotation.RequiresApi
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.core.util.Pair
import com.google.android.material.appbar.MaterialToolbar
import com.simplemobiletools.commons.R
import com.simplemobiletools.commons.asynctasks.CopyMoveTask
import com.simplemobiletools.commons.dialogs.*
import com.simplemobiletools.commons.dialogs.WritePermissionDialog.Mode
import com.simplemobiletools.commons.extensions.*
import com.simplemobiletools.commons.helpers.*
import com.simplemobiletools.commons.interfaces.CopyMoveListener
import com.simplemobiletools.commons.models.FAQItem
import com.simplemobiletools.commons.models.FileDirItem
import java.io.File
import java.io.OutputStream
import java.util.regex.Pattern
abstract class BaseSimpleActivity : AppCompatActivity() {
var copyMoveCallback: ((destinationPath: String) -> Unit)? = null
var actionOnPermission: ((granted: Boolean) -> Unit)? = null
var isAskingPermissions = false
var useDynamicTheme = true
var showTransparentTop = false
var showTransparentNavigation = false
var checkedDocumentPath = ""
var configItemsToExport = LinkedHashMap<String, Any>()
private val GENERIC_PERM_HANDLER = 100
private val DELETE_FILE_SDK_30_HANDLER = 300
private val RECOVERABLE_SECURITY_HANDLER = 301
private val UPDATE_FILE_SDK_30_HANDLER = 302
private val MANAGE_MEDIA_RC = 303
companion object {
var funAfterSAFPermission: ((success: Boolean) -> Unit)? = null
var funAfterSdk30Action: ((success: Boolean) -> Unit)? = null
var funAfterUpdate30File: ((success: Boolean) -> Unit)? = null
var funRecoverableSecurity: ((success: Boolean) -> Unit)? = null
var funAfterManageMediaPermission: (() -> Unit)? = null
}
abstract fun getAppIconIDs(): ArrayList<Int>
abstract fun getAppLauncherName(): String
override fun onCreate(savedInstanceState: Bundle?) {
if (useDynamicTheme) {
setTheme(getThemeId(showTransparentTop = showTransparentTop))
}
super.onCreate(savedInstanceState)
if (!packageName.startsWith("com.simplemobiletools.", true)) {
if ((0..50).random() == 10 || baseConfig.appRunCount % 100 == 0) {
val label = "You are using a fake version of the app. For your own safety download the original one from www.simplemobiletools.com. Thanks"
ConfirmationDialog(this, label, positive = R.string.ok, negative = 0) {
launchViewIntent("https://play.google.com/store/apps/dev?id=9070296388022589266")
}
}
}
}
@SuppressLint("NewApi")
override fun onResume() {
super.onResume()
if (useDynamicTheme) {
setTheme(getThemeId(showTransparentTop = showTransparentTop))
val backgroundColor = if (baseConfig.isUsingSystemTheme) {
resources.getColor(R.color.you_background_color, theme)
} else {
baseConfig.backgroundColor
}
updateBackgroundColor(backgroundColor)
}
if (showTransparentTop) {
window.statusBarColor = Color.TRANSPARENT
} else {
val color = if (baseConfig.isUsingSystemTheme) {
resources.getColor(R.color.you_status_bar_color)
} else {
getProperStatusBarColor()
}
updateActionbarColor(color)
}
updateRecentsAppIcon()
updateNavigationBarColor()
}
override fun onDestroy() {
super.onDestroy()
funAfterSAFPermission = null
actionOnPermission = null
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
android.R.id.home -> {
hideKeyboard()
finish()
}
else -> return super.onOptionsItemSelected(item)
}
return true
}
override fun attachBaseContext(newBase: Context) {
if (newBase.baseConfig.useEnglish && !isTiramisuPlus()) {
super.attachBaseContext(MyContextWrapper(newBase).wrap(newBase, "en"))
} else {
super.attachBaseContext(newBase)
}
}
fun updateBackgroundColor(color: Int = baseConfig.backgroundColor) {
window.decorView.setBackgroundColor(color)
}
fun updateStatusbarColor(color: Int) {
window.statusBarColor = color
if (isMarshmallowPlus()) {
if (color.getContrastColor() == 0xFF333333.toInt()) {
window.decorView.systemUiVisibility = window.decorView.systemUiVisibility.addBit(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR)
} else {
window.decorView.systemUiVisibility = window.decorView.systemUiVisibility.removeBit(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR)
}
}
}
fun updateActionbarColor(color: Int = getProperStatusBarColor()) {
updateStatusbarColor(color)
setTaskDescription(ActivityManager.TaskDescription(null, null, color))
}
fun updateNavigationBarColor(color: Int = baseConfig.navigationBarColor, isColorPreview: Boolean = false) {
if (showTransparentNavigation) {
return
}
if (baseConfig.isUsingSystemTheme && !isColorPreview) {
val navBarColor = getBottomNavigationBackgroundColor()
window.navigationBarColor = navBarColor
if (navBarColor.getContrastColor() == 0xFF333333.toInt()) {
window.decorView.systemUiVisibility = window.decorView.systemUiVisibility.addBit(View.SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR)
} else {
window.decorView.systemUiVisibility = window.decorView.systemUiVisibility.removeBit(View.SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR)
}
} else if (baseConfig.navigationBarColor != INVALID_NAVIGATION_BAR_COLOR) {
try {
val colorToUse = if (color == -2) -1 else color
window.navigationBarColor = colorToUse
if (isOreoPlus()) {
if (colorToUse.getContrastColor() == 0xFF333333.toInt()) {
window.decorView.systemUiVisibility = window.decorView.systemUiVisibility.addBit(View.SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR)
} else {
window.decorView.systemUiVisibility = window.decorView.systemUiVisibility.removeBit(View.SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR)
}
}
} catch (ignored: Exception) {
}
}
}
fun updateRecentsAppIcon() {
if (baseConfig.isUsingModifiedAppIcon) {
val appIconIDs = getAppIconIDs()
val currentAppIconColorIndex = getCurrentAppIconColorIndex()
if (appIconIDs.size - 1 < currentAppIconColorIndex) {
return
}
val recentsIcon = BitmapFactory.decodeResource(resources, appIconIDs[currentAppIconColorIndex])
val title = getAppLauncherName()
val color = baseConfig.primaryColor
val description = ActivityManager.TaskDescription(title, recentsIcon, color)
setTaskDescription(description)
}
}
fun updateMenuItemColors(menu: Menu?, useCrossAsBack: Boolean = false, baseColor: Int = getProperStatusBarColor(), forceWhiteIcons: Boolean = false) {
if (menu == null) {
return
}
var color = baseColor.getContrastColor()
if (forceWhiteIcons) {
color = Color.WHITE
}
for (i in 0 until menu.size()) {
try {
menu.getItem(i)?.icon?.setTint(color)
} catch (ignored: Exception) {
}
}
}
fun setupToolbar(
toolbar: MaterialToolbar,
toolbarNavigationIcon: NavigationIcon = NavigationIcon.None,
statusBarColor: Int = getProperStatusBarColor(),
searchMenuItem: MenuItem? = null
) {
val contrastColor = statusBarColor.getContrastColor()
toolbar.setBackgroundColor(statusBarColor)
toolbar.setTitleTextColor(contrastColor)
toolbar.overflowIcon = resources.getColoredDrawableWithColor(R.drawable.ic_three_dots_vector, contrastColor)
if (toolbarNavigationIcon != NavigationIcon.None) {
val drawableId = if (toolbarNavigationIcon == NavigationIcon.Cross) R.drawable.ic_cross_vector else R.drawable.ic_arrow_left_vector
toolbar.navigationIcon = resources.getColoredDrawableWithColor(drawableId, contrastColor)
}
updateMenuItemColors(toolbar.menu, toolbarNavigationIcon == NavigationIcon.Cross, statusBarColor)
toolbar.setNavigationOnClickListener {
hideKeyboard()
finish()
}
// this icon is used at closing search
toolbar.collapseIcon = resources.getColoredDrawableWithColor(R.drawable.ic_arrow_left_vector, contrastColor)
searchMenuItem?.actionView?.findViewById<ImageView>(androidx.appcompat.R.id.search_close_btn)?.apply {
applyColorFilter(contrastColor)
}
searchMenuItem?.actionView?.findViewById<EditText>(androidx.appcompat.R.id.search_src_text)?.apply {
setTextColor(contrastColor)
setHintTextColor(contrastColor.adjustAlpha(MEDIUM_ALPHA))
hint = "${getString(R.string.search)}…"
if (isQPlus()) {
textCursorDrawable = null
}
}
// search underline
searchMenuItem?.actionView?.findViewById<View>(androidx.appcompat.R.id.search_plate)?.apply {
background.setColorFilter(contrastColor, PorterDuff.Mode.MULTIPLY)
}
}
private fun getCurrentAppIconColorIndex(): Int {
val appIconColor = baseConfig.appIconColor
getAppIconColors().forEachIndexed { index, color ->
if (color == appIconColor) {
return index
}
}
return 0
}
fun setTranslucentNavigation() {
window.setFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION, WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION)
}
override fun onActivityResult(requestCode: Int, resultCode: Int, resultData: Intent?) {
super.onActivityResult(requestCode, resultCode, resultData)
val partition = try {
checkedDocumentPath.substring(9, 18)
} catch (e: Exception) {
""
}
val sdOtgPattern = Pattern.compile(SD_OTG_SHORT)
if (requestCode == CREATE_DOCUMENT_SDK_30) {
if (resultCode == Activity.RESULT_OK && resultData != null && resultData.data != null) {
val treeUri = resultData.data
val checkedUri = buildDocumentUriSdk30(checkedDocumentPath)
if (treeUri != checkedUri) {
toast(getString(R.string.wrong_folder_selected, checkedDocumentPath))
return
}
val takeFlags = Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_GRANT_WRITE_URI_PERMISSION
applicationContext.contentResolver.takePersistableUriPermission(treeUri, takeFlags)
val funAfter = funAfterSdk30Action
funAfterSdk30Action = null
funAfter?.invoke(true)
} else {
funAfterSdk30Action?.invoke(false)
}
} else if (requestCode == OPEN_DOCUMENT_TREE_FOR_SDK_30) {
if (resultCode == Activity.RESULT_OK && resultData != null && resultData.data != null) {
val treeUri = resultData.data
val checkedUri = createFirstParentTreeUri(checkedDocumentPath)
if (treeUri != checkedUri) {
val level = getFirstParentLevel(checkedDocumentPath)
val firstParentPath = checkedDocumentPath.getFirstParentPath(this, level)
toast(getString(R.string.wrong_folder_selected, humanizePath(firstParentPath)))
return
}
val takeFlags = Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_GRANT_WRITE_URI_PERMISSION
applicationContext.contentResolver.takePersistableUriPermission(treeUri, takeFlags)
val funAfter = funAfterSdk30Action
funAfterSdk30Action = null
funAfter?.invoke(true)
} else {
funAfterSdk30Action?.invoke(false)
}
} else if (requestCode == OPEN_DOCUMENT_TREE_FOR_ANDROID_DATA_OR_OBB) {
if (resultCode == Activity.RESULT_OK && resultData != null && resultData.data != null) {
if (isProperAndroidRoot(checkedDocumentPath, resultData.data!!)) {
if (resultData.dataString == baseConfig.OTGTreeUri || resultData.dataString == baseConfig.sdTreeUri) {
val pathToSelect = createAndroidDataOrObbPath(checkedDocumentPath)
toast(getString(R.string.wrong_folder_selected, pathToSelect))
return
}
val treeUri = resultData.data
storeAndroidTreeUri(checkedDocumentPath, treeUri.toString())
val takeFlags = Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_GRANT_WRITE_URI_PERMISSION
applicationContext.contentResolver.takePersistableUriPermission(treeUri!!, takeFlags)
funAfterSAFPermission?.invoke(true)
funAfterSAFPermission = null
} else {
toast(getString(R.string.wrong_folder_selected, createAndroidDataOrObbPath(checkedDocumentPath)))
Intent(Intent.ACTION_OPEN_DOCUMENT_TREE).apply {
if (isRPlus()) {
putExtra(DocumentsContract.EXTRA_INITIAL_URI, createAndroidDataOrObbUri(checkedDocumentPath))
}
try {
startActivityForResult(this, requestCode)
} catch (e: Exception) {
showErrorToast(e)
}
}
}
} else {
funAfterSAFPermission?.invoke(false)
}
} else if (requestCode == OPEN_DOCUMENT_TREE_SD) {
if (resultCode == Activity.RESULT_OK && resultData != null && resultData.data != null) {
val isProperPartition = partition.isEmpty() || !sdOtgPattern.matcher(partition).matches() || (sdOtgPattern.matcher(partition)
.matches() && resultData.dataString!!.contains(partition))
if (isProperSDRootFolder(resultData.data!!) && isProperPartition) {
if (resultData.dataString == baseConfig.OTGTreeUri) {
toast(R.string.sd_card_usb_same)
return
}
saveTreeUri(resultData)
funAfterSAFPermission?.invoke(true)
funAfterSAFPermission = null
} else {
toast(R.string.wrong_root_selected)
val intent = Intent(Intent.ACTION_OPEN_DOCUMENT_TREE)
try {
startActivityForResult(intent, requestCode)
} catch (e: Exception) {
showErrorToast(e)
}
}
} else {
funAfterSAFPermission?.invoke(false)
}
} else if (requestCode == OPEN_DOCUMENT_TREE_OTG) {
if (resultCode == Activity.RESULT_OK && resultData != null && resultData.data != null) {
val isProperPartition = partition.isEmpty() || !sdOtgPattern.matcher(partition).matches() || (sdOtgPattern.matcher(partition)
.matches() && resultData.dataString!!.contains(partition))
if (isProperOTGRootFolder(resultData.data!!) && isProperPartition) {
if (resultData.dataString == baseConfig.sdTreeUri) {
funAfterSAFPermission?.invoke(false)
toast(R.string.sd_card_usb_same)
return
}
baseConfig.OTGTreeUri = resultData.dataString!!
baseConfig.OTGPartition = baseConfig.OTGTreeUri.removeSuffix("%3A").substringAfterLast('/').trimEnd('/')
updateOTGPathFromPartition()
val takeFlags = Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_GRANT_WRITE_URI_PERMISSION
applicationContext.contentResolver.takePersistableUriPermission(resultData.data!!, takeFlags)
funAfterSAFPermission?.invoke(true)
funAfterSAFPermission = null
} else {
toast(R.string.wrong_root_selected_usb)
val intent = Intent(Intent.ACTION_OPEN_DOCUMENT_TREE)
try {
startActivityForResult(intent, requestCode)
} catch (e: Exception) {
showErrorToast(e)
}
}
} else {
funAfterSAFPermission?.invoke(false)
}
} else if (requestCode == SELECT_EXPORT_SETTINGS_FILE_INTENT && resultCode == Activity.RESULT_OK && resultData != null && resultData.data != null) {
val outputStream = contentResolver.openOutputStream(resultData.data!!)
exportSettingsTo(outputStream, configItemsToExport)
} else if (requestCode == DELETE_FILE_SDK_30_HANDLER) {
funAfterSdk30Action?.invoke(resultCode == Activity.RESULT_OK)
} else if (requestCode == RECOVERABLE_SECURITY_HANDLER) {
funRecoverableSecurity?.invoke(resultCode == Activity.RESULT_OK)
funRecoverableSecurity = null
} else if (requestCode == UPDATE_FILE_SDK_30_HANDLER) {
funAfterUpdate30File?.invoke(resultCode == Activity.RESULT_OK)
} else if (requestCode == MANAGE_MEDIA_RC) {
funAfterManageMediaPermission?.invoke()
}
}
private fun saveTreeUri(resultData: Intent) {
val treeUri = resultData.data
baseConfig.sdTreeUri = treeUri.toString()
val takeFlags = Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_GRANT_WRITE_URI_PERMISSION
applicationContext.contentResolver.takePersistableUriPermission(treeUri!!, takeFlags)
}
private fun isProperSDRootFolder(uri: Uri) = isExternalStorageDocument(uri) && isRootUri(uri) && !isInternalStorage(uri)
private fun isProperSDFolder(uri: Uri) = isExternalStorageDocument(uri) && !isInternalStorage(uri)
private fun isProperOTGRootFolder(uri: Uri) = isExternalStorageDocument(uri) && isRootUri(uri) && !isInternalStorage(uri)
private fun isProperOTGFolder(uri: Uri) = isExternalStorageDocument(uri) && !isInternalStorage(uri)
private fun isRootUri(uri: Uri) = uri.lastPathSegment?.endsWith(":") ?: false
private fun isInternalStorage(uri: Uri) = isExternalStorageDocument(uri) && DocumentsContract.getTreeDocumentId(uri).contains("primary")
private fun isAndroidDir(uri: Uri) = isExternalStorageDocument(uri) && DocumentsContract.getTreeDocumentId(uri).contains(":Android")
private fun isInternalStorageAndroidDir(uri: Uri) = isInternalStorage(uri) && isAndroidDir(uri)
private fun isOTGAndroidDir(uri: Uri) = isProperOTGFolder(uri) && isAndroidDir(uri)
private fun isSDAndroidDir(uri: Uri) = isProperSDFolder(uri) && isAndroidDir(uri)
private fun isExternalStorageDocument(uri: Uri) = EXTERNAL_STORAGE_PROVIDER_AUTHORITY == uri.authority
private fun isProperAndroidRoot(path: String, uri: Uri): Boolean {
return when {
isPathOnOTG(path) -> isOTGAndroidDir(uri)
isPathOnSD(path) -> isSDAndroidDir(uri)
else -> isInternalStorageAndroidDir(uri)
}
}
fun startAboutActivity(appNameId: Int, licenseMask: Long, versionName: String, faqItems: ArrayList<FAQItem>, showFAQBeforeMail: Boolean) {
hideKeyboard()
Intent(applicationContext, AboutActivity::class.java).apply {
putExtra(APP_ICON_IDS, getAppIconIDs())
putExtra(APP_LAUNCHER_NAME, getAppLauncherName())
putExtra(APP_NAME, getString(appNameId))
putExtra(APP_LICENSES, licenseMask)
putExtra(APP_VERSION_NAME, versionName)
putExtra(APP_FAQ, faqItems)
putExtra(SHOW_FAQ_BEFORE_MAIL, showFAQBeforeMail)
startActivity(this)
}
}
fun startCustomizationActivity() {
if (!packageName.contains("slootelibomelpmis".reversed(), true)) {
if (baseConfig.appRunCount > 100) {
val label = "You are using a fake version of the app. For your own safety download the original one from www.simplemobiletools.com. Thanks"
ConfirmationDialog(this, label, positive = R.string.ok, negative = 0) {
launchViewIntent("https://play.google.com/store/apps/dev?id=9070296388022589266")
}
return
}
}
Intent(applicationContext, CustomizationActivity::class.java).apply {
putExtra(APP_ICON_IDS, getAppIconIDs())
putExtra(APP_LAUNCHER_NAME, getAppLauncherName())
startActivity(this)
}
}
fun handleCustomizeColorsClick() {
if (isOrWasThankYouInstalled()) {
startCustomizationActivity()
} else {
FeatureLockedDialog(this) {}
}
}
@RequiresApi(Build.VERSION_CODES.O)
fun launchCustomizeNotificationsIntent() {
Intent(Settings.ACTION_APP_NOTIFICATION_SETTINGS).apply {
putExtra(Settings.EXTRA_APP_PACKAGE, packageName)
startActivity(this)
}
}
@RequiresApi(Build.VERSION_CODES.TIRAMISU)
fun launchChangeAppLanguageIntent() {
try {
Intent(Settings.ACTION_APP_LOCALE_SETTINGS).apply {
data = Uri.fromParts("package", packageName, null)
startActivity(this)
}
} catch (e: Exception) {
try {
Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS).apply {
data = Uri.fromParts("package", packageName, null)
startActivity(this)
}
} catch (e: Exception) {
showErrorToast(e)
}
}
}
// synchronous return value determines only if we are showing the SAF dialog, callback result tells if the SD or OTG permission has been granted
fun handleSAFDialog(path: String, callback: (success: Boolean) -> Unit): Boolean {
hideKeyboard()
return if (!packageName.startsWith("com.simplemobiletools")) {
callback(true)
false
} else if (isShowingSAFDialog(path) || isShowingOTGDialog(path)) {
funAfterSAFPermission = callback
true
} else {
callback(true)
false
}
}
fun handleSAFDialogSdk30(path: String, callback: (success: Boolean) -> Unit): Boolean {
hideKeyboard()
return if (!packageName.startsWith("com.simplemobiletools")) {
callback(true)
false
} else if (isShowingSAFDialogSdk30(path)) {
funAfterSdk30Action = callback
true
} else {
callback(true)
false
}
}
fun checkManageMediaOrHandleSAFDialogSdk30(path: String, callback: (success: Boolean) -> Unit): Boolean {
hideKeyboard()
return if (canManageMedia()) {
callback(true)
false
} else {
handleSAFDialogSdk30(path, callback)
}
}
fun handleSAFCreateDocumentDialogSdk30(path: String, callback: (success: Boolean) -> Unit): Boolean {
hideKeyboard()
return if (!packageName.startsWith("com.simplemobiletools")) {
callback(true)
false
} else if (isShowingSAFCreateDocumentDialogSdk30(path)) {
funAfterSdk30Action = callback
true
} else {
callback(true)
false
}
}
fun handleAndroidSAFDialog(path: String, callback: (success: Boolean) -> Unit): Boolean {
hideKeyboard()
return if (!packageName.startsWith("com.simplemobiletools")) {
callback(true)
false
} else if (isShowingAndroidSAFDialog(path)) {
funAfterSAFPermission = callback
true
} else {
callback(true)
false
}
}
fun handleOTGPermission(callback: (success: Boolean) -> Unit) {
hideKeyboard()
if (baseConfig.OTGTreeUri.isNotEmpty()) {
callback(true)
return
}
funAfterSAFPermission = callback
WritePermissionDialog(this, Mode.Otg) {
Intent(Intent.ACTION_OPEN_DOCUMENT_TREE).apply {
try {
startActivityForResult(this, OPEN_DOCUMENT_TREE_OTG)
return@apply
} catch (e: Exception) {
type = "*/*"
}
try {
startActivityForResult(this, OPEN_DOCUMENT_TREE_OTG)
} catch (e: ActivityNotFoundException) {
toast(R.string.system_service_disabled, Toast.LENGTH_LONG)
} catch (e: Exception) {
toast(R.string.unknown_error_occurred)
}
}
}
}
@SuppressLint("NewApi")
fun deleteSDK30Uris(uris: List<Uri>, callback: (success: Boolean) -> Unit) {
hideKeyboard()
if (isRPlus()) {
funAfterSdk30Action = callback
try {
val deleteRequest = MediaStore.createDeleteRequest(contentResolver, uris).intentSender
startIntentSenderForResult(deleteRequest, DELETE_FILE_SDK_30_HANDLER, null, 0, 0, 0)
} catch (e: Exception) {
showErrorToast(e)
}
} else {
callback(false)
}
}
@SuppressLint("NewApi")
fun updateSDK30Uris(uris: List<Uri>, callback: (success: Boolean) -> Unit) {
hideKeyboard()
if (isRPlus()) {
funAfterUpdate30File = callback
try {
val writeRequest = MediaStore.createWriteRequest(contentResolver, uris).intentSender
startIntentSenderForResult(writeRequest, UPDATE_FILE_SDK_30_HANDLER, null, 0, 0, 0)
} catch (e: Exception) {
showErrorToast(e)
}
} else {
callback(false)
}
}
@SuppressLint("NewApi")
fun handleRecoverableSecurityException(callback: (success: Boolean) -> Unit) {
try {
callback.invoke(true)
} catch (securityException: SecurityException) {
if (isQPlus()) {
funRecoverableSecurity = callback
val recoverableSecurityException = securityException as? RecoverableSecurityException ?: throw securityException
val intentSender = recoverableSecurityException.userAction.actionIntent.intentSender
startIntentSenderForResult(intentSender, RECOVERABLE_SECURITY_HANDLER, null, 0, 0, 0)
} else {
callback(false)
}
}
}
@RequiresApi(Build.VERSION_CODES.S)
fun launchMediaManagementIntent(callback: () -> Unit) {
Intent(Settings.ACTION_REQUEST_MANAGE_MEDIA).apply {
data = Uri.parse("package:$packageName")
try {
startActivityForResult(this, MANAGE_MEDIA_RC)
} catch (e: Exception) {
showErrorToast(e)
}
}
funAfterManageMediaPermission = callback
}
fun copyMoveFilesTo(
fileDirItems: ArrayList<FileDirItem>, source: String, destination: String, isCopyOperation: Boolean, copyPhotoVideoOnly: Boolean,
copyHidden: Boolean, callback: (destinationPath: String) -> Unit
) {
if (source == destination) {
toast(R.string.source_and_destination_same)
return
}
if (!getDoesFilePathExist(destination)) {
toast(R.string.invalid_destination)
return
}
handleSAFDialog(destination) {
if (!it) {
copyMoveListener.copyFailed()
return@handleSAFDialog
}
handleSAFDialogSdk30(destination) {
if (!it) {
copyMoveListener.copyFailed()
return@handleSAFDialogSdk30
}
copyMoveCallback = callback
var fileCountToCopy = fileDirItems.size
if (isCopyOperation) {
val recycleBinPath = fileDirItems.first().isRecycleBinPath(this)
if (canManageMedia() && !recycleBinPath) {
val fileUris = getFileUrisFromFileDirItems(fileDirItems)
updateSDK30Uris(fileUris) { sdk30UriSuccess ->
if (sdk30UriSuccess) {
startCopyMove(fileDirItems, destination, isCopyOperation, copyPhotoVideoOnly, copyHidden)
}
}
} else {
startCopyMove(fileDirItems, destination, isCopyOperation, copyPhotoVideoOnly, copyHidden)
}
} else {
if (isPathOnOTG(source) || isPathOnOTG(destination) || isPathOnSD(source) || isPathOnSD(destination) ||
isRestrictedSAFOnlyRoot(source) || isRestrictedSAFOnlyRoot(destination) ||
isAccessibleWithSAFSdk30(source) || isAccessibleWithSAFSdk30(destination) ||
fileDirItems.first().isDirectory
) {
handleSAFDialog(source) { safSuccess ->
if (safSuccess) {
val recycleBinPath = fileDirItems.first().isRecycleBinPath(this)
if (canManageMedia() && !recycleBinPath) {
val fileUris = getFileUrisFromFileDirItems(fileDirItems)
updateSDK30Uris(fileUris) { sdk30UriSuccess ->
if (sdk30UriSuccess) {
startCopyMove(fileDirItems, destination, isCopyOperation, copyPhotoVideoOnly, copyHidden)
}
}
} else {
startCopyMove(fileDirItems, destination, isCopyOperation, copyPhotoVideoOnly, copyHidden)
}
}
}
} else {
try {
checkConflicts(fileDirItems, destination, 0, LinkedHashMap()) {
toast(R.string.moving)
ensureBackgroundThread {
val updatedPaths = ArrayList<String>(fileDirItems.size)
val destinationFolder = File(destination)
for (oldFileDirItem in fileDirItems) {
var newFile = File(destinationFolder, oldFileDirItem.name)
if (newFile.exists()) {
when {
getConflictResolution(it, newFile.absolutePath) == CONFLICT_SKIP -> fileCountToCopy--
getConflictResolution(it, newFile.absolutePath) == CONFLICT_KEEP_BOTH -> newFile = getAlternativeFile(newFile)
else ->
// this file is guaranteed to be on the internal storage, so just delete it this way
newFile.delete()
}
}
if (!newFile.exists() && File(oldFileDirItem.path).renameTo(newFile)) {
if (!baseConfig.keepLastModified) {
newFile.setLastModified(System.currentTimeMillis())
}
updatedPaths.add(newFile.absolutePath)
deleteFromMediaStore(oldFileDirItem.path)
}
}
runOnUiThread {
if (updatedPaths.isEmpty()) {
copyMoveListener.copySucceeded(false, fileCountToCopy == 0, destination, false)
} else {
copyMoveListener.copySucceeded(false, fileCountToCopy <= updatedPaths.size, destination, updatedPaths.size == 1)
}
}
}
}
} catch (e: Exception) {
showErrorToast(e)
}
}
}
}
}
}
fun getAlternativeFile(file: File): File {
var fileIndex = 1
var newFile: File?
do {
val newName = String.format("%s(%d).%s", file.nameWithoutExtension, fileIndex, file.extension)
newFile = File(file.parent, newName)
fileIndex++
} while (getDoesFilePathExist(newFile!!.absolutePath))
return newFile
}
private fun startCopyMove(
files: ArrayList<FileDirItem>,
destinationPath: String,
isCopyOperation: Boolean,
copyPhotoVideoOnly: Boolean,
copyHidden: Boolean
) {
val availableSpace = destinationPath.getAvailableStorageB()
val sumToCopy = files.sumByLong { it.getProperSize(applicationContext, copyHidden) }
if (availableSpace == -1L || sumToCopy < availableSpace) {
checkConflicts(files, destinationPath, 0, LinkedHashMap()) {
toast(if (isCopyOperation) R.string.copying else R.string.moving)
val pair = Pair(files, destinationPath)
handleNotificationPermission { granted ->
if (granted) {
CopyMoveTask(this, isCopyOperation, copyPhotoVideoOnly, it, copyMoveListener, copyHidden).execute(pair)
} else {
toast(R.string.no_post_notifications_permissions)
}
}
}
} else {
val text = String.format(getString(R.string.no_space), sumToCopy.formatSize(), availableSpace.formatSize())
toast(text, Toast.LENGTH_LONG)
}
}
fun checkConflicts(
files: ArrayList<FileDirItem>, destinationPath: String, index: Int, conflictResolutions: LinkedHashMap<String, Int>,
callback: (resolutions: LinkedHashMap<String, Int>) -> Unit
) {
if (index == files.size) {
callback(conflictResolutions)
return
}
val file = files[index]
val newFileDirItem = FileDirItem("$destinationPath/${file.name}", file.name, file.isDirectory)
if (getDoesFilePathExist(newFileDirItem.path)) {
FileConflictDialog(this, newFileDirItem, files.size > 1) { resolution, applyForAll ->
if (applyForAll) {
conflictResolutions.clear()
conflictResolutions[""] = resolution
checkConflicts(files, destinationPath, files.size, conflictResolutions, callback)
} else {
conflictResolutions[newFileDirItem.path] = resolution
checkConflicts(files, destinationPath, index + 1, conflictResolutions, callback)
}
}
} else {
checkConflicts(files, destinationPath, index + 1, conflictResolutions, callback)
}
}
fun handlePermission(permissionId: Int, callback: (granted: Boolean) -> Unit) {
actionOnPermission = null
if (hasPermission(permissionId)) {
callback(true)
} else {
isAskingPermissions = true
actionOnPermission = callback
ActivityCompat.requestPermissions(this, arrayOf(getPermissionString(permissionId)), GENERIC_PERM_HANDLER)
}
}
fun handleNotificationPermission(callback: (granted: Boolean) -> Unit) {
if (!isTiramisuPlus()) {
callback(true)
} else {
handlePermission(PERMISSION_POST_NOTIFICATIONS) { granted ->
callback(granted)
}
}
}
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String>, grantResults: IntArray) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
isAskingPermissions = false
if (requestCode == GENERIC_PERM_HANDLER && grantResults.isNotEmpty()) {
actionOnPermission?.invoke(grantResults[0] == 0)
}
}
val copyMoveListener = object : CopyMoveListener {
override fun copySucceeded(copyOnly: Boolean, copiedAll: Boolean, destinationPath: String, wasCopyingOneFileOnly: Boolean) {
if (copyOnly) {
toast(
if (copiedAll) {
if (wasCopyingOneFileOnly) {
R.string.copying_success_one
} else {
R.string.copying_success
}
} else {
R.string.copying_success_partial
}
)
} else {
toast(
if (copiedAll) {
if (wasCopyingOneFileOnly) {
R.string.moving_success_one
} else {
R.string.moving_success
}
} else {
R.string.moving_success_partial
}
)
}
copyMoveCallback?.invoke(destinationPath)
copyMoveCallback = null
}
override fun copyFailed() {
toast(R.string.copy_move_failed)
copyMoveCallback = null
}
}
fun checkAppOnSDCard() {
if (!baseConfig.wasAppOnSDShown && isAppInstalledOnSDCard()) {
baseConfig.wasAppOnSDShown = true
ConfirmationDialog(this, "", R.string.app_on_sd_card, R.string.ok, 0) {}
}
}
fun exportSettings(configItems: LinkedHashMap<String, Any>) {
if (isQPlus()) {
configItemsToExport = configItems
ExportSettingsDialog(this, getExportSettingsFilename(), true) { path, filename ->
Intent(Intent.ACTION_CREATE_DOCUMENT).apply {
type = "text/plain"
putExtra(Intent.EXTRA_TITLE, filename)
addCategory(Intent.CATEGORY_OPENABLE)
try {
startActivityForResult(this, SELECT_EXPORT_SETTINGS_FILE_INTENT)
} catch (e: ActivityNotFoundException) {
toast(R.string.system_service_disabled, Toast.LENGTH_LONG)
} catch (e: Exception) {
showErrorToast(e)
}
}
}
} else {
handlePermission(PERMISSION_WRITE_STORAGE) {
if (it) {
ExportSettingsDialog(this, getExportSettingsFilename(), false) { path, filename ->
val file = File(path)
getFileOutputStream(file.toFileDirItem(this), true) {
exportSettingsTo(it, configItems)
}
}
}
}
}
}
private fun exportSettingsTo(outputStream: OutputStream?, configItems: LinkedHashMap<String, Any>) {
if (outputStream == null) {
toast(R.string.unknown_error_occurred)
return
}
ensureBackgroundThread {
outputStream.bufferedWriter().use { out ->
for ((key, value) in configItems) {
out.writeLn("$key=$value")
}
}
toast(R.string.settings_exported_successfully)
}
}
private fun getExportSettingsFilename(): String {
val appName = baseConfig.appId.removeSuffix(".debug").removeSuffix(".pro").removePrefix("com.simplemobiletools.")
return "$appName-settings_${getCurrentFormattedDateTime()}"
}
@SuppressLint("InlinedApi")
protected fun launchSetDefaultDialerIntent() {
if (isQPlus()) {
val roleManager = getSystemService(RoleManager::class.java)
if (roleManager!!.isRoleAvailable(RoleManager.ROLE_DIALER) && !roleManager.isRoleHeld(RoleManager.ROLE_DIALER)) {
val intent = roleManager.createRequestRoleIntent(RoleManager.ROLE_DIALER)
startActivityForResult(intent, REQUEST_CODE_SET_DEFAULT_DIALER)
}
} else {
Intent(TelecomManager.ACTION_CHANGE_DEFAULT_DIALER).putExtra(TelecomManager.EXTRA_CHANGE_DEFAULT_DIALER_PACKAGE_NAME, packageName).apply {
try {
startActivityForResult(this, REQUEST_CODE_SET_DEFAULT_DIALER)
} catch (e: ActivityNotFoundException) {
toast(R.string.no_app_found)
} catch (e: Exception) {
showErrorToast(e)
}
}
}
}
@RequiresApi(Build.VERSION_CODES.Q)
fun setDefaultCallerIdApp() {
val roleManager = getSystemService(RoleManager::class.java)
if (roleManager.isRoleAvailable(RoleManager.ROLE_CALL_SCREENING) && !roleManager.isRoleHeld(RoleManager.ROLE_CALL_SCREENING)) {
val intent = roleManager.createRequestRoleIntent(RoleManager.ROLE_CALL_SCREENING)
startActivityForResult(intent, REQUEST_CODE_SET_DEFAULT_CALLER_ID)
}
}
}
| gpl-3.0 | a9a33cae80728f79292610146afe79c7 | 41.661165 | 158 | 0.57732 | 5.472105 | false | false | false | false |
ligi/SurvivalManual | android/src/main/kotlin/org/ligi/survivalmanual/model/NavigationDefinitions.kt | 1 | 3551 | package org.ligi.survivalmanual.model
import androidx.annotation.DrawableRes
import androidx.annotation.StringRes
import org.ligi.survivalmanual.R
open class NavigationEntry(val url: String,
@StringRes val titleRes: Int,
@DrawableRes val iconRes: Int? = null,
val isAppendix: Boolean = false,
val isListed: Boolean = true)
class NavigationEntryWithId(val id: Int,
val entry: NavigationEntry)
val navigationEntryMap = arrayOf(
NavigationEntry("Introduction", R.string.introduction, R.drawable.ic_info_outline),
NavigationEntry("Psychology", R.string.psychology, R.drawable.ic_psychology),
NavigationEntry("Power", R.string.power, R.drawable.ic_power),
NavigationEntry("Planning", R.string.planning, R.drawable.ic_format_list_numbered),
NavigationEntry("Kits", R.string.kits, R.drawable.ic_business_center),
NavigationEntry("Apps", R.string.apps, R.drawable.ic_phone_android),
NavigationEntry("Medicine", R.string.basic_medicine, R.drawable.ic_healing),
NavigationEntry("Shelter", R.string.shelter, R.drawable.ic_store),
NavigationEntry("Water", R.string.water, R.drawable.ic_local_drink),
NavigationEntry("Fire", R.string.fire, R.drawable.ic_whatshot),
NavigationEntry("Food", R.string.food, R.drawable.ic_local_dining),
NavigationEntry("Plants", R.string.plants, R.drawable.ic_local_florist),
NavigationEntry("10", R.string.poisonous_plants, R.drawable.ic_face_dead),
NavigationEntry("Animals", R.string.animals, R.drawable.ic_pets),
NavigationEntry("Tools", R.string.tools, R.drawable.ic_gavel),
NavigationEntry("Desert", R.string.desert, R.drawable.ic_wb_sunny),
NavigationEntry("Tropical", R.string.tropical, R.drawable.ic_beach_access),
NavigationEntry("Cold", R.string.cold, R.drawable.ic_ac_unit),
NavigationEntry("Sea", R.string.sea, R.drawable.ic_directions_boat),
NavigationEntry("WaterCrossing", R.string.water_crossing, R.drawable.ic_rowing),
NavigationEntry("DirectionFinding", R.string.directionfinding, R.drawable.ic_explore),
NavigationEntry("ManMadeHazards", R.string.man_made_hazards, R.drawable.ic_attach_money),
NavigationEntry("Self-defense", R.string.self_defense, R.drawable.ic_security),
NavigationEntry("Signaling", R.string.signaling, R.drawable.ic_flag),
NavigationEntry("HostileAreas", R.string.hostile_areas, R.drawable.ic_flash_on),
NavigationEntry("Camouflage", R.string.camouflage, R.drawable.ic_palette),
NavigationEntry("People", R.string.people, R.drawable.ic_people),
NavigationEntry("Credits", R.string.credits, R.drawable.ic_star),
NavigationEntry("MultiTool", R.string.multitool, isAppendix = true),
NavigationEntry("DangerousArthropods", R.string.insects_and_arachnids, isAppendix = true),
NavigationEntry("FishAndMollusks", R.string.fish_and_mollusks, isAppendix = true),
NavigationEntry("RopesAndKnots", R.string.ropes_and_knots, isAppendix = true),
NavigationEntry("FAQ", R.string.faq, isAppendix = true),
NavigationEntry("TranslatorNotes", R.string.translator_notes, isListed = false)
).mapIndexed(::NavigationEntryWithId)
val titleResByURLMap = navigationEntryMap.associate { it.entry.url to it.entry.titleRes }
fun getTitleResByURL(url: String) = titleResByURLMap[url.split("#").first()]
| gpl-3.0 | 77483bbb9ca4a3d0adffdf57cc299607 | 59.186441 | 98 | 0.696142 | 3.902198 | false | false | false | false |
klazuka/intellij-elm | src/main/kotlin/org/elm/ide/refactoring/ElmRenamePsiFileProcessor.kt | 1 | 1616 | package org.elm.ide.refactoring
import com.intellij.openapi.util.io.FileUtil
import com.intellij.psi.PsiElement
import com.intellij.refactoring.rename.RenamePsiFileProcessor
import org.elm.lang.core.psi.ElmFile
import org.elm.lang.core.psi.elements.ElmModuleDeclaration
/**
* When renaming an Elm file, also rename any [ElmModuleDeclaration]s (which, transitively,
* will also rename all imports and qualified references).
*
* See https://intellij-support.jetbrains.com/hc/en-us/community/posts/206760415-Renaming-files-in-IDE
* and [ElmRenamePsiElementProcessor]
*/
class ElmRenamePsiFileProcessor : RenamePsiFileProcessor() {
override fun canProcessElement(element: PsiElement) =
element is ElmFile
override fun prepareRenaming(element: PsiElement, newName: String, allRenames: MutableMap<PsiElement, String>) {
val file = element as? ElmFile
?: return
val moduleDecl = file.getModuleDecl()
?: return
val newModuleName = FileUtil.getNameWithoutExtension(newName)
if (!isValidUpperIdentifier(newModuleName))
return
// When renaming the module, we must only replace the final part of the
// module name. Given a module `Foo.Bar` in file `src/Foo/Bar.elm`, if we want to
// rename `Bar.elm` to `Quux.elm`, the new module name will be `Foo.Quux`.
val moduleParts = moduleDecl.upperCaseQID.upperCaseIdentifierList.map { it.text }.toMutableList()
moduleParts[moduleParts.size - 1] = newModuleName
allRenames[moduleDecl] = moduleParts.joinToString(".")
}
} | mit | 80b41fc8128a53d69e84972d7c6f0a60 | 36.604651 | 116 | 0.714728 | 4.344086 | false | false | false | false |
EventFahrplan/EventFahrplan | app/src/main/java/nerd/tuxmobil/fahrplan/congress/notifications/NotificationHelper.kt | 1 | 5352 | package nerd.tuxmobil.fahrplan.congress.notifications
import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.Context
import android.content.ContextWrapper
import android.net.Uri
import android.os.Build
import androidx.core.app.NotificationCompat
import androidx.core.content.ContextCompat
import nerd.tuxmobil.fahrplan.congress.R
import nerd.tuxmobil.fahrplan.congress.extensions.getNotificationManager
internal class NotificationHelper(context: Context) : ContextWrapper(context) {
private val notificationManager: NotificationManager by lazy {
getNotificationManager()
}
init {
createChannels()
}
fun createChannels(){
createNotificationChannel(SESSION_ALARM_CHANNEL_ID, sessionAlarmChannelName, sessionAlarmChannelDescription)
createNotificationChannel(SCHEDULE_UPDATE_CHANNEL_ID, scheduleUpdateChannelName, scheduleUpdateChannelDescription)
}
fun getSessionAlarmNotificationBuilder(
contentIntent: PendingIntent,
contentTitle: String,
occurredAt: Long,
sound: Uri?,
deleteIntent: PendingIntent
): NotificationCompat.Builder =
getNotificationBuilder(SESSION_ALARM_CHANNEL_ID, contentIntent, sessionAlarmContentText, sound)
.setCategory(NotificationCompat.CATEGORY_REMINDER)
.setContentTitle(contentTitle)
.setDefaults(Notification.DEFAULT_LIGHTS or Notification.DEFAULT_VIBRATE)
.setWhen(occurredAt)
.setDeleteIntent(deleteIntent)
fun getScheduleUpdateNotificationBuilder(
contentIntent: PendingIntent,
contentText: String,
changesCount: Int,
sound: Uri?
): NotificationCompat.Builder =
getNotificationBuilder(SCHEDULE_UPDATE_CHANNEL_ID, contentIntent, contentText, sound)
.setCategory(NotificationCompat.CATEGORY_SERVICE)
.setContentTitle(sessionAlarmContentTitle)
.setDefaults(Notification.DEFAULT_LIGHTS)
.setSubText(getScheduleUpdateContentText(changesCount))
@JvmOverloads
fun notify(id: Int, builder: NotificationCompat.Builder, isInsistent: Boolean = false) {
val notification = builder.build()
if (isInsistent) {
notification.flags = notification.flags or Notification.FLAG_INSISTENT
}
notificationManager.notify(id, notification)
}
/**
* Cancels all existing schedule update notifications.
*/
fun cancelScheduleUpdateNotification() {
notificationManager.cancel(SCHEDULE_UPDATE_ID)
}
private fun createNotificationChannel(id: String, name: String, descriptionText: String) {
// TODO Replace with NotificationChannelCompat once it's complete. See https://issuetracker.google.com/issues/193814308
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
with(NotificationChannel(id, name, NotificationManager.IMPORTANCE_DEFAULT)) {
description = descriptionText
lightColor = color
lockscreenVisibility = Notification.VISIBILITY_PUBLIC
notificationManager.createNotificationChannel(this)
}
}
}
private fun getNotificationBuilder(
channelId: String,
contentIntent: PendingIntent,
contentText: String,
sound: Uri?) =
NotificationCompat.Builder(this, channelId)
.setAutoCancel(true)
.setColor(color)
.setContentIntent(contentIntent)
.setContentText(contentText)
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
.setSmallIcon(smallIcon)
.setSound(sound)
private val sessionAlarmChannelDescription: String
get() = getString(R.string.notifications_session_alarm_channel_description)
private val sessionAlarmChannelName: String
get() = getString(R.string.notifications_session_alarm_channel_name)
private val sessionAlarmContentTitle: String
get() = getString(R.string.notifications_session_alarm_content_title)
private val sessionAlarmContentText: String
get() = getString(R.string.notifications_session_alarm_content_text)
private val scheduleUpdateChannelDescription: String
get() = getString(R.string.notifications_schedule_update_channel_description)
private val scheduleUpdateChannelName: String
get() = getString(R.string.notifications_schedule_update_channel_name)
private fun getScheduleUpdateContentText(changesCount: Int): String =
resources.getQuantityString(R.plurals.notifications_schedule_changes, changesCount, changesCount)
private val color: Int
get() = ContextCompat.getColor(this, R.color.colorAccent)
private val smallIcon: Int
get() = R.drawable.ic_notification
companion object {
private const val SESSION_ALARM_CHANNEL_ID = "SESSION_ALARM_CHANNEL"
private const val SCHEDULE_UPDATE_CHANNEL_ID = "SCHEDULE_UPDATE_CHANNEL"
const val SCHEDULE_UPDATE_ID = 2
}
}
| apache-2.0 | d5aa4223a5f2b7f9f351d8bcf565ae83 | 39.545455 | 127 | 0.689275 | 5.56341 | false | false | false | false |
52inc/android-52Kit | library/src/main/java/com/ftinc/kit/util/IntentUtils.kt | 1 | 15476 | /*
* Copyright (c) 2017 52inc.
*
* 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.ftinc.kit.util
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Build
import android.provider.Contacts
import android.provider.MediaStore
import android.provider.Settings
import android.text.TextUtils
import java.io.File
import java.net.URL
/**
* @author Dmitriy Tarasov
*/
object IntentUtils {
/**
* Open app page at Google Play
*
* @param context Application context
* @param openInBrowser Should we try to open application page in web browser
* if Play Store app not found on device
*/
@JvmOverloads
fun openPlayStore(context: Context, openInBrowser: Boolean = true): Intent {
val appPackageName = context.packageName
val marketIntent = Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=$appPackageName"))
if (isIntentAvailable(context, marketIntent)) {
return marketIntent
}
return if (openInBrowser) {
openLink("https://play.google.com/store/apps/details?id=$appPackageName")
} else marketIntent
}
/**
* Send email message
*
* @param to Receiver email
* @param subject Message subject
* @param text Message body
* @see .sendEmail
*/
fun sendEmail(to: String, subject: String, text: String): Intent {
return sendEmail(arrayOf(to), subject, text)
}
/**
* @see .sendEmail
*/
fun sendEmail(to: Array<String>, subject: String, text: String): Intent {
val intent = Intent(Intent.ACTION_SEND)
intent.type = "message/rfc822"
intent.putExtra(Intent.EXTRA_EMAIL, to)
intent.putExtra(Intent.EXTRA_SUBJECT, subject)
intent.putExtra(Intent.EXTRA_TEXT, text)
return intent
}
/**
* Share text via thirdparty app like twitter, facebook, email, sms etc.
*
* @param subject Optional subject of the message
* @param text Text to share
*/
fun shareText(subject: String, text: String): Intent {
val intent = Intent()
intent.action = Intent.ACTION_SEND
if (!TextUtils.isEmpty(subject)) {
intent.putExtra(Intent.EXTRA_SUBJECT, subject)
}
intent.putExtra(Intent.EXTRA_TEXT, text)
intent.type = "text/plain"
return intent
}
/**
* Send SMS message using built-in app
*
* @param to Receiver phone number
* @param message Text to send
*/
fun sendSms(to: String, message: String): Intent {
val smsUri = Uri.parse("tel:$to")
val intent = Intent(Intent.ACTION_VIEW, smsUri)
intent.putExtra("address", to)
intent.putExtra("sms_body", message)
intent.type = "vnd.android-dir/mms-sms"
return intent
}
/**
* Opens the Street View application to the given location.
* The URI scheme is based on the syntax used for Street View panorama information in Google Maps URLs.
*
* @param latitude Latitude
* @param longitude Longitude
* @param yaw Panorama center-of-view in degrees clockwise from North.
* Note: The two commas after the yaw parameter are required.
* They are present for backwards-compatibility reasons.
* @param pitch Panorama center-of-view in degrees from -90 (look straight up) to 90 (look straight down.)
* @param zoom Panorama zoom. 1.0 = normal zoom, 2.0 = zoomed in 2x, 3.0 = zoomed in 4x, and so on.
* A zoom of 1.0 is 90 degree horizontal FOV for a nominal landscape mode 4 x 3 aspect ratio display Android
* phones in portrait mode will adjust the zoom so that the vertical FOV is approximately the same as the
* landscape vertical FOV. This means that the horizontal FOV of an Android phone in portrait mode is much
* narrower than in landscape mode. This is done to minimize the fisheye lens effect that would be present
* if a 90 degree horizontal FOV was used in portrait mode.
* @param mapZoom The map zoom of the map location associated with this panorama.
* This value is passed on to the Maps activity when the Street View "Go to Maps" menu item is chosen.
* It corresponds to the zoomLevel parameter in [.showLocation]
*/
fun showStreetView(latitude: Float,
longitude: Float,
yaw: Float?,
pitch: Int?,
zoom: Float?,
mapZoom: Int?): Intent {
val builder = StringBuilder("google.streetview:cbll=").append(latitude).append(",").append(longitude)
if (yaw != null || pitch != null || zoom != null) {
val cbpParam = String.format("%s,,%s,%s", yaw ?: "", pitch ?: "", zoom ?: "")
builder.append("&cbp=1,").append(cbpParam)
}
if (mapZoom != null) {
builder.append("&mz=").append(mapZoom)
}
val intent = Intent()
intent.action = Intent.ACTION_VIEW
intent.data = Uri.parse(builder.toString())
return intent
}
/**
* Opens the Maps application to the given location.
*
* @param latitude Latitude
* @param longitude Longitude
* @param zoomLevel A zoom level of 1 shows the whole Earth, centered at the given lat,lng.
* A zoom level of 2 shows a quarter of the Earth, and so on. The highest zoom level is 23.
* A larger zoom level will be clamped to 23.
* @see .findLocation
*/
fun showLocation(latitude: Float, longitude: Float, zoomLevel: Int?): Intent {
val intent = Intent()
intent.action = Intent.ACTION_VIEW
var data = String.format("geo:%s,%s", latitude, longitude)
if (zoomLevel != null) {
data = String.format("%s?z=%s", data, zoomLevel)
}
intent.data = Uri.parse(data)
return intent
}
/**
* Opens the Maps application to the given query.
*
* @param query Query string
* @see .showLocation
*/
fun findLocation(query: String): Intent {
val intent = Intent()
intent.action = Intent.ACTION_VIEW
val data = String.format("geo:0,0?q=%s", query)
intent.data = Uri.parse(data)
return intent
}
/**
* Open system settings location services screen for turning on/off GPS
*/
fun showLocationServices(): Intent {
val intent = Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS)
intent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY or Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET)
return intent
}
/**
* Open a browser window to the URL specified.
*
* @param url Target url
*/
fun openLink(url: String): Intent {
var url = url
// if protocol isn't defined use http by default
if (!TextUtils.isEmpty(url) && !url.contains("://")) {
url = "http://$url"
}
val intent = Intent()
intent.action = Intent.ACTION_VIEW
intent.data = Uri.parse(url)
return intent
}
/**
* @see .openLink
*/
fun openLink(url: URL): Intent {
return openLink(url.toString())
}
/**
* Open a video file in appropriate app
*
* @param file File to open
*/
fun openVideo(file: File): Intent {
return openVideo(Uri.fromFile(file))
}
/**
* @see .openVideo
*/
fun openVideo(file: String): Intent {
return openVideo(File(file))
}
/**
* @see .openVideo
*/
fun openVideo(uri: Uri): Intent {
return openMedia(uri, "video/*")
}
/**
* Open an audio file in appropriate app
*
* @param file File to open
*/
fun openAudio(file: File): Intent {
return openAudio(Uri.fromFile(file))
}
/**
* @see .openAudio
*/
fun openAudio(file: String): Intent {
return openAudio(File(file))
}
/**
* @see .openAudio
*/
fun openAudio(uri: Uri): Intent {
return openMedia(uri, "audio/*")
}
/**
* Open an image file in appropriate app
*
* @param file File to open
*/
fun openImage(file: String): Intent {
return openImage(File(file))
}
/**
* @see .openImage
*/
fun openImage(file: File): Intent {
return openImage(Uri.fromFile(file))
}
/**
* @see .openImage
*/
fun openImage(uri: Uri): Intent {
return openMedia(uri, "image/*")
}
/**
* Open a text file in appropriate app
*
* @param file File to open
*/
fun openText(file: String): Intent {
return openText(File(file))
}
/**
* @see .openText
*/
fun openText(file: File): Intent {
return openText(Uri.fromFile(file))
}
/**
* @see .openText
*/
fun openText(uri: Uri): Intent {
return openMedia(uri, "text/plain")
}
/**
* Pick file from sdcard with file manager. Chosen file can be obtained from Intent in onActivityResult.
* See code below for example:
*
* <pre>`
* protected void onActivityResult(int requestCode, int resultCode, Intent data) {
* Uri file = data.getData();
* }
`</pre> *
*/
fun pickFile(): Intent {
return pick("file/*")
}
/**
* Pick a type of file from the sdcard with the file manager.
* Chosen file can be obtained from Intent in onActivityResult.
* See code below for example:
*
* <pre>`
* protected void onActivityResult(int requestCode, int resultCode, Intent data) {
* Uri file = data.getData();
* }
`</pre> *
*
* @param mimeType the type of file to pick
* @return the intent to pick it
*/
fun pick(mimeType: String): Intent {
val intent = Intent(Intent.ACTION_GET_CONTENT)
intent.type = mimeType
return intent
}
/**
* Calls the entered phone number. Valid telephone numbers as defined in the IETF RFC 3966 are accepted.
* Valid examples include the following:
* tel:2125551212
* tel: (212) 555 1212
*
* Note: This requires your application to request the following permission in your manifest:
* `<uses-permission android:name="android.permission.CALL_PHONE"/>`
*
* @param phoneNumber Phone number
*/
fun callPhone(phoneNumber: String): Intent {
val intent = Intent()
intent.action = Intent.ACTION_CALL
intent.data = Uri.parse("tel:$phoneNumber")
return intent
}
/**
* Pick contact from phone book
*
* @param scope You can restrict selection by passing required content type.
*/
@JvmOverloads
fun pickContact(scope: String? = null): Intent {
val intent: Intent
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.ECLAIR) {
intent = Intent(Intent.ACTION_PICK, Contacts.People.CONTENT_URI)
} else {
intent = Intent(Intent.ACTION_PICK, Uri.parse("content://com.android.contacts/contacts"))
}
if (!TextUtils.isEmpty(scope)) {
intent.type = scope
}
return intent
}
/**
* Pick image from gallery
*/
fun pickImage(): Intent {
val intent = Intent(Intent.ACTION_PICK)
intent.type = "image/*"
return intent
}
/**
* Dials (but does not actually initiate the call) the number given.
* Telephone number normalization described for [.callPhone] applies to dial as well.
*
* @param phoneNumber Phone number
*/
fun dialPhone(phoneNumber: String): Intent {
val intent = Intent()
intent.action = Intent.ACTION_DIAL
intent.data = Uri.parse("tel:$phoneNumber")
return intent
}
/**
* Check that cropping application is available
*
* @param context Application context
* @return true if cropping app is available
* @see .cropImage
*/
fun isCropAvailable(context: Context): Boolean {
val intent = Intent("com.android.camera.action.CROP")
intent.type = "image/*"
return IntentUtils.isIntentAvailable(context, intent)
}
/**
* Crop image. Before using, cropImage requires especial check that differs from
* [.isIntentAvailable]
* see [.isCropAvailable] instead
*
* @param context Application context
* @param image Image that will be used for cropping. This image is not changed during the cropImage
* @param outputX Output image width
* @param outputY Output image height
* @param aspectX Crop frame aspect X
* @param aspectY Crop frame aspect Y
* @param scale Scale or not cropped image if output image and cropImage frame sizes differs
* @return Intent with `data`-extra in `onActivityResult` which contains result as a
* [android.graphics.Bitmap]. See demo app for details
*/
fun cropImage(context: Context, image: File, outputX: Int, outputY: Int, aspectX: Int, aspectY: Int, scale: Boolean): Intent {
val intent = Intent("com.android.camera.action.CROP")
intent.type = "image/*"
val list = context.packageManager.queryIntentActivities(intent, 0)
val res = list[0]
intent.putExtra("outputX", outputX)
intent.putExtra("outputY", outputY)
intent.putExtra("aspectX", aspectX)
intent.putExtra("aspectY", aspectY)
intent.putExtra("scale", scale)
intent.putExtra("return-data", true)
intent.data = Uri.fromFile(image)
intent.component = ComponentName(res.activityInfo.packageName, res.activityInfo.name)
return intent
}
/**
* Call standard camera application for capturing an image
*
* @param file Full path to captured file
*/
fun photoCapture(file: String): Intent {
val uri = Uri.fromFile(File(file))
val intent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
intent.putExtra(MediaStore.EXTRA_OUTPUT, uri)
return intent
}
/**
* Check that in the system exists application which can handle this intent
*
* @param context Application context
* @param intent Checked intent
* @return true if intent consumer exists, false otherwise
*/
fun isIntentAvailable(context: Context, intent: Intent): Boolean {
val packageManager = context.packageManager
val list = packageManager.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY)
return list.size > 0
}
private fun openMedia(uri: Uri, mimeType: String): Intent {
val intent = Intent(Intent.ACTION_VIEW)
intent.setDataAndType(uri, mimeType)
return intent
}
}
| apache-2.0 | a37f32ca0e7fc26c3cc6840f6441404d | 30.778234 | 130 | 0.615986 | 4.350857 | false | false | false | false |
esofthead/mycollab | mycollab-dao/src/main/java/org/mybatis/scripting/velocity/Equals.kt | 3 | 1117 | package org.mybatis.scripting.velocity
import org.apache.velocity.context.InternalContextAdapter
import org.apache.velocity.exception.MethodInvocationException
import org.apache.velocity.exception.ParseErrorException
import org.apache.velocity.exception.ResourceNotFoundException
import org.apache.velocity.runtime.directive.Directive
import org.apache.velocity.runtime.directive.DirectiveConstants
import org.apache.velocity.runtime.parser.node.Node
import java.io.IOException
import java.io.Writer
/**
* @author MyCollab Ltd
* @since 5.1.1
*/
class Equals : Directive() {
override fun getName(): String = "equals"
override fun getType(): Int = DirectiveConstants.LINE
@Throws(IOException::class, ResourceNotFoundException::class, ParseErrorException::class, MethodInvocationException::class)
override fun render(context: InternalContextAdapter, writer: Writer, node: Node): Boolean {
val value = node.jjtGetChild(0).value(context)
when {
value != null -> writer.write("='$value'")
else -> writer.write("IS NULL")
}
return true
}
}
| agpl-3.0 | a4412f3356c638d3f3f50273fe22746a | 33.90625 | 127 | 0.746643 | 4.346304 | false | false | false | false |
CruGlobal/android-gto-support | gto-support-util/src/main/java/org/ccci/gto/android/common/util/os/LocaleList.kt | 2 | 755 | @file:TargetApi(Build.VERSION_CODES.N)
package org.ccci.gto.android.common.util.os
import android.annotation.TargetApi
import android.os.Build
import android.os.LocaleList
import java.util.Locale
fun LocaleList.listIterator() = object : ListIterator<Locale> {
private val list = this@listIterator
private var i = 0
override fun hasNext() = i < list.size()
override fun next() = list[i++]
override fun hasPrevious() = i > 0
override fun previous() = list[--i]
override fun nextIndex() = i
override fun previousIndex() = i - 1
}
internal val LocaleList.locales
get() = object : Sequence<Locale> {
override fun iterator() = listIterator()
}
fun LocaleList.toTypedArray() = locales.toList().toTypedArray()
| mit | 51212b02253683d2c058591f676fc441 | 28.038462 | 63 | 0.700662 | 4.015957 | false | false | false | false |
esofthead/mycollab | mycollab-services/src/main/java/com/mycollab/module/user/domain/SimpleUser.kt | 3 | 2452 | /**
* Copyright © MyCollab
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http:></http:>//www.gnu.org/licenses/>.
*/
package com.mycollab.module.user.domain
import com.google.common.base.MoreObjects
import com.mycollab.core.arguments.NotBindable
import com.mycollab.core.utils.StringUtils
import com.mycollab.i18n.LocalizationHelper
import com.mycollab.security.PermissionMap
import java.util.*
/**
* @author MyCollab Ltd.
* @since 1.0
*/
class SimpleUser : User() {
var roleId: Int? = null
var roleName: String? = null
@NotBindable
var permissionMaps: PermissionMap? = null
@NotBindable
var isAccountOwner: Boolean? = null
@NotBindable
var locale: Locale? = null
get() {
return LocalizationHelper.getLocaleInstance(language)
}
var subDomain: String? = null
var accountId: Int? = null
var registerstatus: String? = null
var inviteUser: String? = null
var lastModuleVisit: String? = null
var inviteUserFullName: String? = null
var displayName: String? = null
get() {
val result = "$firstname $lastname"
if (StringUtils.isBlank(result)) {
val displayName = username
return StringUtils.extractNameFromEmail(displayName)
}
return result
}
var dateFormat: String? = null
get() = MoreObjects.firstNonNull(field, "MM/dd/yyyy")
var shortDateFormat: String? = null
get() = MoreObjects.firstNonNull(field, "MM/dd")
var longDateFormat: String? = null
get() = MoreObjects.firstNonNull(field, "E, dd MMM yyyy")
var showEmailPublicly: Boolean? = null
@NotBindable
var canSendEmail: Boolean? = null
enum class Field {
displayName, roleName, roleId;
fun equalTo(value: Any): Boolean = name == value
}
}
| agpl-3.0 | 16d3df6f0911d54b2a3386a58be9e5c8 | 30.025316 | 81 | 0.675235 | 4.322751 | false | false | false | false |
dhleong/ideavim | src/com/maddyhome/idea/vim/helper/UndoRedoHelper.kt | 1 | 1975 | /*
* IdeaVim - Vim emulator for IDEs based on the IntelliJ platform
* Copyright (C) 2003-2019 The IdeaVim authors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.maddyhome.idea.vim.helper
import com.intellij.openapi.actionSystem.DataContext
import com.intellij.openapi.actionSystem.PlatformDataKeys
import com.intellij.openapi.command.undo.UndoManager
import com.maddyhome.idea.vim.listener.SelectionVimListenerSuppressor
/**
* @author oleg
*/
object UndoRedoHelper {
fun undo(context: DataContext): Boolean {
val project = PlatformDataKeys.PROJECT.getData(context) ?: return false
val fileEditor = PlatformDataKeys.FILE_EDITOR.getData(context)
val undoManager = UndoManager.getInstance(project)
if (fileEditor != null && undoManager.isUndoAvailable(fileEditor)) {
SelectionVimListenerSuppressor.lock().use { undoManager.undo(fileEditor) }
return true
}
return false
}
fun redo(context: DataContext): Boolean {
val project = PlatformDataKeys.PROJECT.getData(context) ?: return false
val fileEditor = PlatformDataKeys.FILE_EDITOR.getData(context)
val undoManager = UndoManager.getInstance(project)
if (fileEditor != null && undoManager.isRedoAvailable(fileEditor)) {
SelectionVimListenerSuppressor.lock().use { undoManager.redo(fileEditor) }
return true
}
return false
}
}
| gpl-2.0 | 699a420d2c5ae90cf19a132ece5f12c0 | 37.72549 | 80 | 0.751392 | 4.561201 | false | false | false | false |
Lucas-Lu/KotlinWorld | KT11/src/main/java/net/println/kt11/Player.kt | 1 | 1991 | package net.println.kt11
import kotlin.properties.Delegates
/**
* Created by luliju on 2017/7/10.
*/
class Player {
private var state: State by Delegates.observable(State.IDLE, { prop, old, new ->
println("$old -> $new")
onPlayerStateChangedListener?.onStateChanged(old, new)
})
private fun sendCmd(cmd: PlayerCmd) {
when (cmd) {
is PlayerCmd.Play -> {
println("\nPlay ${cmd.url} from ${cmd.position}ms")
state = State.PLAYING
doPlay(cmd.url, cmd.position)
}
is PlayerCmd.Resume -> {
println("\nResume. ")
state = State.PLAYING
doResume()
}
is PlayerCmd.Pause -> {
println("\nPause. ")
state = State.PAUSED
doPause()
}
is PlayerCmd.Stop -> {
println("\nStop.")
state = State.IDLE
doStop()
}
is PlayerCmd.Seek -> {
println("\nSeek to ${cmd.position}ms, state: $state")
}
}
}
private fun doPlay(url: String, position: Long) {
TODO("Play function not yet implemented")
}
private fun doResume(){
//todo
}
private fun doPause() {
//todo
}
private fun doStop() {
//todo
}
//region api
interface OnPlayerStateChangedListener {
fun onStateChanged(oldState: State, new: State)
}
var onPlayerStateChangedListener: OnPlayerStateChangedListener? = null
fun play(url: String, position: Long = 0) {
sendCmd(PlayerCmd.Play(url, position))
}
fun resume() {
sendCmd(PlayerCmd.Resume)
}
fun pause() {
sendCmd(PlayerCmd.Pause)
}
fun stop() {
sendCmd(PlayerCmd.Stop)
}
fun seekTo(position: Long) {
sendCmd(PlayerCmd.Seek(position))
}
//endregion
}
| mit | f690c0f2ac6ae98c3d070a8e729210f3 | 22.702381 | 84 | 0.515319 | 4.494357 | false | false | false | false |
da1z/intellij-community | uast/uast-common/src/org/jetbrains/uast/evaluation/TreeBasedEvaluator.kt | 4 | 28106 | /*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.uast.evaluation
import com.intellij.openapi.progress.ProgressManager
import com.intellij.psi.JavaPsiFacade
import com.intellij.psi.PsiModifier
import com.intellij.psi.PsiType
import com.intellij.psi.PsiVariable
import org.jetbrains.uast.*
import org.jetbrains.uast.values.*
import org.jetbrains.uast.values.UNothingValue.JumpKind.BREAK
import org.jetbrains.uast.values.UNothingValue.JumpKind.CONTINUE
import org.jetbrains.uast.visitor.UastTypedVisitor
class TreeBasedEvaluator(
override val context: UastContext,
val extensions: List<UEvaluatorExtension>
) : UastTypedVisitor<UEvaluationState, UEvaluationInfo>, UEvaluator {
override fun getDependents(dependency: UDependency): Set<UValue> {
return resultCache.values.map { it.value }.filter { dependency in it.dependencies }.toSet()
}
private val inputStateCache = mutableMapOf<UExpression, UEvaluationState>()
private val resultCache = mutableMapOf<UExpression, UEvaluationInfo>()
override fun visitElement(node: UElement, data: UEvaluationState): UEvaluationInfo {
return UEvaluationInfo(UUndeterminedValue, data).apply {
if (node is UExpression) {
this storeResultFor node
}
}
}
override fun analyze(method: UMethod, state: UEvaluationState) {
method.uastBody?.accept(this, state)
}
override fun analyze(field: UField, state: UEvaluationState) {
field.uastInitializer?.accept(this, state)
}
internal fun getCached(expression: UExpression): UValue? {
return resultCache[expression]?.value
}
override fun evaluate(expression: UExpression, state: UEvaluationState?): UValue {
if (state == null) {
val result = resultCache[expression]
if (result != null) return result.value
}
val inputState = state ?: inputStateCache[expression] ?: expression.createEmptyState()
return expression.accept(this, inputState).value
}
// ----------------------- //
private infix fun UValue.to(state: UEvaluationState) = UEvaluationInfo(this, state)
private infix fun UEvaluationInfo.storeResultFor(expression: UExpression) = apply {
resultCache[expression] = this
}
override fun visitLiteralExpression(node: ULiteralExpression, data: UEvaluationState): UEvaluationInfo {
inputStateCache[node] = data
val value = node.value
return value.toConstant(node) to data storeResultFor node
}
override fun visitClassLiteralExpression(node: UClassLiteralExpression, data: UEvaluationState): UEvaluationInfo {
inputStateCache[node] = data
return (node.type?.let { value -> UClassConstant(value, node) } ?: UUndeterminedValue) to data storeResultFor node
}
override fun visitReturnExpression(node: UReturnExpression, data: UEvaluationState): UEvaluationInfo {
inputStateCache[node] = data
val argument = node.returnExpression
return UValue.UNREACHABLE to (argument?.accept(this, data)?.state ?: data) storeResultFor node
}
override fun visitBreakExpression(node: UBreakExpression, data: UEvaluationState): UEvaluationInfo {
inputStateCache[node] = data
return UNothingValue(node) to data storeResultFor node
}
override fun visitContinueExpression(node: UContinueExpression, data: UEvaluationState): UEvaluationInfo {
inputStateCache[node] = data
return UNothingValue(node) to data storeResultFor node
}
override fun visitThrowExpression(node: UThrowExpression, data: UEvaluationState): UEvaluationInfo {
inputStateCache[node] = data
return UValue.UNREACHABLE to data storeResultFor node
}
// ----------------------- //
override fun visitSimpleNameReferenceExpression(
node: USimpleNameReferenceExpression,
data: UEvaluationState
): UEvaluationInfo {
inputStateCache[node] = data
val resolvedElement = node.resolveToUElement()
return when (resolvedElement) {
is UEnumConstant -> UEnumEntryValueConstant(resolvedElement, node)
is UField -> if (resolvedElement.hasModifierProperty(PsiModifier.FINAL)) {
data[resolvedElement].ifUndetermined {
val helper = JavaPsiFacade.getInstance(resolvedElement.project).constantEvaluationHelper
val evaluated = helper.computeConstantExpression(resolvedElement.initializer)
evaluated?.toConstant() ?: UUndeterminedValue
}
}
else {
return super.visitSimpleNameReferenceExpression(node, data)
}
is UVariable -> data[resolvedElement].ifUndetermined {
node.evaluateViaExtensions { evaluateVariable(resolvedElement, data) }?.value ?: UUndeterminedValue
}
else -> return super.visitSimpleNameReferenceExpression(node, data)
} to data storeResultFor node
}
override fun visitReferenceExpression(
node: UReferenceExpression,
data: UEvaluationState
): UEvaluationInfo {
inputStateCache[node] = data
return UCallResultValue(node, emptyList()) to data storeResultFor node
}
// ----------------------- //
private fun UExpression.assign(
valueInfo: UEvaluationInfo,
operator: UastBinaryOperator.AssignOperator = UastBinaryOperator.ASSIGN
): UEvaluationInfo {
this.accept(this@TreeBasedEvaluator, valueInfo.state)
if (this is UResolvable) {
val resolvedElement = resolve()
if (resolvedElement is PsiVariable) {
val variable = context.getVariable(resolvedElement)
val currentValue = valueInfo.state[variable]
val result = when (operator) {
UastBinaryOperator.ASSIGN -> valueInfo.value
UastBinaryOperator.PLUS_ASSIGN -> currentValue + valueInfo.value
UastBinaryOperator.MINUS_ASSIGN -> currentValue - valueInfo.value
UastBinaryOperator.MULTIPLY_ASSIGN -> currentValue * valueInfo.value
UastBinaryOperator.DIVIDE_ASSIGN -> currentValue / valueInfo.value
UastBinaryOperator.REMAINDER_ASSIGN -> currentValue % valueInfo.value
UastBinaryOperator.AND_ASSIGN -> currentValue bitwiseAnd valueInfo.value
UastBinaryOperator.OR_ASSIGN -> currentValue bitwiseOr valueInfo.value
UastBinaryOperator.XOR_ASSIGN -> currentValue bitwiseXor valueInfo.value
UastBinaryOperator.SHIFT_LEFT_ASSIGN -> currentValue shl valueInfo.value
UastBinaryOperator.SHIFT_RIGHT_ASSIGN -> currentValue shr valueInfo.value
UastBinaryOperator.UNSIGNED_SHIFT_RIGHT_ASSIGN -> currentValue ushr valueInfo.value
else -> UUndeterminedValue
}
return result to valueInfo.state.assign(variable, result, this)
}
}
return UUndeterminedValue to valueInfo.state
}
private fun UExpression.assign(
operator: UastBinaryOperator.AssignOperator,
value: UExpression,
data: UEvaluationState
) = assign(value.accept(this@TreeBasedEvaluator, data), operator)
override fun visitPrefixExpression(node: UPrefixExpression, data: UEvaluationState): UEvaluationInfo {
inputStateCache[node] = data
val operandInfo = node.operand.accept(this, data)
val operandValue = operandInfo.value
if (!operandValue.reachable) return operandInfo storeResultFor node
return when (node.operator) {
UastPrefixOperator.UNARY_PLUS -> operandValue
UastPrefixOperator.UNARY_MINUS -> -operandValue
UastPrefixOperator.LOGICAL_NOT -> !operandValue
UastPrefixOperator.INC -> {
val resultValue = operandValue.inc()
val newState = node.operand.assign(resultValue to operandInfo.state).state
return resultValue to newState storeResultFor node
}
UastPrefixOperator.DEC -> {
val resultValue = operandValue.dec()
val newState = node.operand.assign(resultValue to operandInfo.state).state
return resultValue to newState storeResultFor node
}
else -> {
return node.evaluateViaExtensions { evaluatePrefix(node.operator, operandValue, operandInfo.state) }
?: UUndeterminedValue to operandInfo.state storeResultFor node
}
} to operandInfo.state storeResultFor node
}
inline fun UElement.evaluateViaExtensions(block: UEvaluatorExtension.() -> UEvaluationInfo): UEvaluationInfo? {
for (ext in extensions) {
val extResult = ext.block()
if (extResult.value != UUndeterminedValue) return extResult
}
languageExtension()?.block()?.let { if (it.value != UUndeterminedValue) return it }
return null
}
override fun visitPostfixExpression(node: UPostfixExpression, data: UEvaluationState): UEvaluationInfo {
inputStateCache[node] = data
val operandInfo = node.operand.accept(this, data)
val operandValue = operandInfo.value
if (!operandValue.reachable) return operandInfo storeResultFor node
return when (node.operator) {
UastPostfixOperator.INC -> {
operandValue to node.operand.assign(operandValue.inc() to operandInfo.state).state
}
UastPostfixOperator.DEC -> {
operandValue to node.operand.assign(operandValue.dec() to operandInfo.state).state
}
else -> {
return node.evaluateViaExtensions { evaluatePostfix(node.operator, operandValue, operandInfo.state) }
?: UUndeterminedValue to operandInfo.state storeResultFor node
}
} storeResultFor node
}
private fun UastBinaryOperator.evaluate(left: UValue, right: UValue): UValue? =
when (this) {
UastBinaryOperator.PLUS -> left + right
UastBinaryOperator.MINUS -> left - right
UastBinaryOperator.MULTIPLY -> left * right
UastBinaryOperator.DIV -> left / right
UastBinaryOperator.MOD -> left % right
UastBinaryOperator.EQUALS -> left valueEquals right
UastBinaryOperator.NOT_EQUALS -> left valueNotEquals right
UastBinaryOperator.IDENTITY_EQUALS -> left identityEquals right
UastBinaryOperator.IDENTITY_NOT_EQUALS -> left identityNotEquals right
UastBinaryOperator.GREATER -> left greater right
UastBinaryOperator.LESS -> left less right
UastBinaryOperator.GREATER_OR_EQUALS -> left greaterOrEquals right
UastBinaryOperator.LESS_OR_EQUALS -> left lessOrEquals right
UastBinaryOperator.LOGICAL_AND -> left and right
UastBinaryOperator.LOGICAL_OR -> left or right
UastBinaryOperator.BITWISE_AND -> left bitwiseAnd right
UastBinaryOperator.BITWISE_OR -> left bitwiseOr right
UastBinaryOperator.BITWISE_XOR -> left bitwiseXor right
UastBinaryOperator.SHIFT_LEFT -> left shl right
UastBinaryOperator.SHIFT_RIGHT -> left shr right
UastBinaryOperator.UNSIGNED_SHIFT_RIGHT -> left ushr right
else -> null
}
override fun visitBinaryExpression(node: UBinaryExpression, data: UEvaluationState): UEvaluationInfo {
inputStateCache[node] = data
val operator = node.operator
if (operator is UastBinaryOperator.AssignOperator) {
return node.leftOperand.assign(operator, node.rightOperand, data) storeResultFor node
}
val leftInfo = node.leftOperand.accept(this, data)
if (!leftInfo.reachable) {
return leftInfo storeResultFor node
}
val rightInfo = node.rightOperand.accept(this, leftInfo.state)
operator.evaluate(leftInfo.value, rightInfo.value)?.let {
return it to rightInfo.state storeResultFor node
}
return node.evaluateViaExtensions { evaluateBinary(node, leftInfo.value, rightInfo.value, rightInfo.state) }
?: UUndeterminedValue to rightInfo.state storeResultFor node
}
override fun visitPolyadicExpression(node: UPolyadicExpression, data: UEvaluationState): UEvaluationInfo {
inputStateCache[node] = data
val operator = node.operator
val infos = node.operands.map {
it.accept(this, data).apply {
if (!reachable) {
return this storeResultFor node
}
}
}
val lastInfo = infos.last()
val firstValue = infos.first().value
val restInfos = infos.drop(1)
return restInfos.fold(firstValue) { accumulator, info ->
operator.evaluate(accumulator, info.value) ?: return UUndeterminedValue to info.state storeResultFor node
} to lastInfo.state storeResultFor node
}
private fun evaluateTypeCast(operandInfo: UEvaluationInfo, type: PsiType): UEvaluationInfo {
val constant = operandInfo.value.toConstant() ?: return UUndeterminedValue to operandInfo.state
val resultConstant = when (type) {
PsiType.BOOLEAN -> {
constant as? UBooleanConstant
}
PsiType.CHAR -> when (constant) {
// Join the following three in UNumericConstant
// when https://youtrack.jetbrains.com/issue/KT-14868 is fixed
is UIntConstant -> UCharConstant(constant.value.toChar())
is ULongConstant -> UCharConstant(constant.value.toChar())
is UFloatConstant -> UCharConstant(constant.value.toChar())
is UCharConstant -> constant
else -> null
}
PsiType.LONG -> {
(constant as? UNumericConstant)?.value?.toLong()?.let { value -> ULongConstant(value) }
}
PsiType.BYTE, PsiType.SHORT, PsiType.INT -> {
(constant as? UNumericConstant)?.value?.toInt()?.let { UIntConstant(it, type) }
}
PsiType.FLOAT, PsiType.DOUBLE -> {
(constant as? UNumericConstant)?.value?.toDouble()?.let { UFloatConstant.create(it, type) }
}
else -> when (type.name) {
"java.lang.String" -> UStringConstant(constant.asString())
else -> null
}
} ?: return UUndeterminedValue to operandInfo.state
return when (operandInfo.value) {
resultConstant -> return operandInfo
is UConstant -> resultConstant
is UDependentValue -> UDependentValue.create(resultConstant, operandInfo.value.dependencies)
else -> UUndeterminedValue
} to operandInfo.state
}
private fun evaluateTypeCheck(operandInfo: UEvaluationInfo, type: PsiType): UEvaluationInfo {
val constant = operandInfo.value.toConstant() ?: return UUndeterminedValue to operandInfo.state
val valid = when (type) {
PsiType.BOOLEAN -> constant is UBooleanConstant
PsiType.LONG -> constant is ULongConstant
PsiType.BYTE, PsiType.SHORT, PsiType.INT, PsiType.CHAR -> constant is UIntConstant
PsiType.FLOAT, PsiType.DOUBLE -> constant is UFloatConstant
else -> when (type.name) {
"java.lang.String" -> constant is UStringConstant
else -> false
}
}
return UBooleanConstant.valueOf(valid) to operandInfo.state
}
override fun visitBinaryExpressionWithType(
node: UBinaryExpressionWithType, data: UEvaluationState
): UEvaluationInfo {
inputStateCache[node] = data
val operandInfo = node.operand.accept(this, data)
if (!operandInfo.reachable || operandInfo.value == UUndeterminedValue) {
return operandInfo storeResultFor node
}
return when (node.operationKind) {
UastBinaryExpressionWithTypeKind.TYPE_CAST -> evaluateTypeCast(operandInfo, node.type)
UastBinaryExpressionWithTypeKind.INSTANCE_CHECK -> evaluateTypeCheck(operandInfo, node.type)
else -> UUndeterminedValue to operandInfo.state
} storeResultFor node
}
override fun visitParenthesizedExpression(node: UParenthesizedExpression, data: UEvaluationState): UEvaluationInfo {
inputStateCache[node] = data
return node.expression.accept(this, data) storeResultFor node
}
override fun visitLabeledExpression(node: ULabeledExpression, data: UEvaluationState): UEvaluationInfo {
inputStateCache[node] = data
return node.expression.accept(this, data) storeResultFor node
}
override fun visitCallExpression(node: UCallExpression, data: UEvaluationState): UEvaluationInfo {
inputStateCache[node] = data
var currentInfo = UUndeterminedValue to data
currentInfo = node.receiver?.accept(this, currentInfo.state) ?: currentInfo
if (!currentInfo.reachable) return currentInfo storeResultFor node
val argumentValues = mutableListOf<UValue>()
for (valueArgument in node.valueArguments) {
currentInfo = valueArgument.accept(this, currentInfo.state)
if (!currentInfo.reachable) return currentInfo storeResultFor node
argumentValues.add(currentInfo.value)
}
return (node.evaluateViaExtensions {
node.resolve()?.let { method -> evaluateMethodCall(method, argumentValues, currentInfo.state) }
?: UUndeterminedValue to currentInfo.state
} ?: UCallResultValue(node, argumentValues) to currentInfo.state) storeResultFor node
}
override fun visitQualifiedReferenceExpression(
node: UQualifiedReferenceExpression,
data: UEvaluationState
): UEvaluationInfo {
inputStateCache[node] = data
var currentInfo = UUndeterminedValue to data
currentInfo = node.receiver.accept(this, currentInfo.state)
if (!currentInfo.reachable) return currentInfo storeResultFor node
val selectorInfo = node.selector.accept(this, currentInfo.state)
return when (node.accessType) {
UastQualifiedExpressionAccessType.SIMPLE -> {
selectorInfo
}
else -> {
return node.evaluateViaExtensions { evaluateQualified(node.accessType, currentInfo, selectorInfo) }
?: UUndeterminedValue to selectorInfo.state storeResultFor node
}
} storeResultFor node
}
override fun visitDeclarationsExpression(
node: UDeclarationsExpression,
data: UEvaluationState
): UEvaluationInfo {
inputStateCache[node] = data
var currentInfo = UUndeterminedValue to data
for (variable in node.declarations) {
currentInfo = variable.accept(this, currentInfo.state)
if (!currentInfo.reachable) return currentInfo storeResultFor node
}
return currentInfo storeResultFor node
}
override fun visitVariable(node: UVariable, data: UEvaluationState): UEvaluationInfo {
val initializer = node.uastInitializer
val initializerInfo = initializer?.accept(this, data) ?: UUndeterminedValue to data
if (!initializerInfo.reachable) return initializerInfo
return UUndeterminedValue to initializerInfo.state.assign(node, initializerInfo.value, node)
}
// ----------------------- //
override fun visitBlockExpression(node: UBlockExpression, data: UEvaluationState): UEvaluationInfo {
inputStateCache[node] = data
var currentInfo = UUndeterminedValue to data
for (expression in node.expressions) {
currentInfo = expression.accept(this, currentInfo.state)
if (!currentInfo.reachable) return currentInfo storeResultFor node
}
return currentInfo storeResultFor node
}
override fun visitIfExpression(node: UIfExpression, data: UEvaluationState): UEvaluationInfo {
inputStateCache[node] = data
val conditionInfo = node.condition.accept(this, data)
if (!conditionInfo.reachable) return conditionInfo storeResultFor node
val thenInfo = node.thenExpression?.accept(this, conditionInfo.state)
val elseInfo = node.elseExpression?.accept(this, conditionInfo.state)
val conditionValue = conditionInfo.value
val defaultInfo = UUndeterminedValue to conditionInfo.state
val constantConditionValue = conditionValue.toConstant()
return when (constantConditionValue) {
is UBooleanConstant -> {
if (constantConditionValue.value) thenInfo ?: defaultInfo
else elseInfo ?: defaultInfo
}
else -> when {
thenInfo == null -> elseInfo?.merge(defaultInfo) ?: defaultInfo
elseInfo == null -> thenInfo.merge(defaultInfo)
else -> thenInfo.merge(elseInfo)
}
} storeResultFor node
}
override fun visitSwitchExpression(node: USwitchExpression, data: UEvaluationState): UEvaluationInfo {
inputStateCache[node] = data
val subjectInfo = node.expression?.accept(this, data) ?: UUndeterminedValue to data
if (!subjectInfo.reachable) return subjectInfo storeResultFor node
var resultInfo: UEvaluationInfo? = null
var clauseInfo = subjectInfo
var fallThroughCondition: UValue = UBooleanConstant.False
fun List<UExpression>.evaluateAndFold(): UValue =
this.map {
clauseInfo = it.accept(this@TreeBasedEvaluator, clauseInfo.state)
(clauseInfo.value valueEquals subjectInfo.value).toConstant() as? UValueBase ?: UUndeterminedValue
}.fold(UBooleanConstant.False) { previous: UValue, next -> previous or next }
clausesLoop@ for (expression in node.body.expressions) {
val switchClauseWithBody = expression as USwitchClauseExpressionWithBody
val caseCondition = switchClauseWithBody.caseValues.evaluateAndFold().or(fallThroughCondition)
if (caseCondition != UBooleanConstant.False) {
for (bodyExpression in switchClauseWithBody.body.expressions) {
clauseInfo = bodyExpression.accept(this, clauseInfo.state)
if (!clauseInfo.reachable) break
}
val clauseValue = clauseInfo.value
if (clauseValue is UNothingValue && clauseValue.containingLoopOrSwitch == node) {
// break from switch
resultInfo = resultInfo?.merge(clauseInfo) ?: clauseInfo
if (caseCondition == UBooleanConstant.True) break@clausesLoop
clauseInfo = subjectInfo
fallThroughCondition = UBooleanConstant.False
}
// TODO: jump out
else {
fallThroughCondition = caseCondition
clauseInfo = clauseInfo.merge(subjectInfo)
}
}
}
resultInfo = resultInfo ?: subjectInfo
val resultValue = resultInfo.value
if (resultValue is UNothingValue && resultValue.containingLoopOrSwitch == node) {
resultInfo = resultInfo.copy(UUndeterminedValue)
}
return resultInfo storeResultFor node
}
private fun evaluateLoop(
loop: ULoopExpression,
inputState: UEvaluationState,
condition: UExpression? = null,
infinite: Boolean = false,
update: UExpression? = null
): UEvaluationInfo {
fun evaluateCondition(inputState: UEvaluationState): UEvaluationInfo =
condition?.accept(this, inputState)
?: (if (infinite) UBooleanConstant.True else UUndeterminedValue) to inputState
ProgressManager.checkCanceled()
var resultInfo = UUndeterminedValue to inputState
do {
val previousInfo = resultInfo
resultInfo = evaluateCondition(resultInfo.state)
val conditionConstant = resultInfo.value.toConstant()
if (conditionConstant == UBooleanConstant.False) {
return resultInfo.copy(UUndeterminedValue) storeResultFor loop
}
val bodyInfo = loop.body.accept(this, resultInfo.state)
val bodyValue = bodyInfo.value
if (bodyValue is UNothingValue) {
if (bodyValue.kind == BREAK && bodyValue.containingLoopOrSwitch == loop) {
return if (conditionConstant == UBooleanConstant.True) {
bodyInfo.copy(UUndeterminedValue)
}
else {
bodyInfo.copy(UUndeterminedValue).merge(previousInfo)
} storeResultFor loop
}
else if (bodyValue.kind == CONTINUE && bodyValue.containingLoopOrSwitch == loop) {
val updateInfo = update?.accept(this, bodyInfo.state) ?: bodyInfo
resultInfo = updateInfo.copy(UUndeterminedValue).merge(previousInfo)
}
else {
return if (conditionConstant == UBooleanConstant.True) {
bodyInfo
}
else {
resultInfo.copy(UUndeterminedValue)
} storeResultFor loop
}
}
else {
val updateInfo = update?.accept(this, bodyInfo.state) ?: bodyInfo
resultInfo = updateInfo.merge(previousInfo)
}
}
while (previousInfo != resultInfo)
return resultInfo.copy(UUndeterminedValue) storeResultFor loop
}
override fun visitForEachExpression(node: UForEachExpression, data: UEvaluationState): UEvaluationInfo {
inputStateCache[node] = data
val iterableInfo = node.iteratedValue.accept(this, data)
return evaluateLoop(node, iterableInfo.state)
}
override fun visitForExpression(node: UForExpression, data: UEvaluationState): UEvaluationInfo {
inputStateCache[node] = data
val initialState = node.declaration?.accept(this, data)?.state ?: data
return evaluateLoop(node, initialState, node.condition, node.condition == null, node.update)
}
override fun visitWhileExpression(node: UWhileExpression, data: UEvaluationState): UEvaluationInfo {
inputStateCache[node] = data
return evaluateLoop(node, data, node.condition)
}
override fun visitDoWhileExpression(node: UDoWhileExpression, data: UEvaluationState): UEvaluationInfo {
inputStateCache[node] = data
val bodyInfo = node.body.accept(this, data)
return evaluateLoop(node, bodyInfo.state, node.condition)
}
override fun visitTryExpression(node: UTryExpression, data: UEvaluationState): UEvaluationInfo {
inputStateCache[node] = data
val tryInfo = node.tryClause.accept(this, data)
val mergedTryInfo = tryInfo.merge(UUndeterminedValue to data)
val catchInfoList = node.catchClauses.map { it.accept(this, mergedTryInfo.state) }
val mergedTryCatchInfo = catchInfoList.fold(mergedTryInfo, UEvaluationInfo::merge)
val finallyInfo = node.finallyClause?.accept(this, mergedTryCatchInfo.state) ?: mergedTryCatchInfo
return finallyInfo storeResultFor node
}
// ----------------------- //
override fun visitObjectLiteralExpression(node: UObjectLiteralExpression, data: UEvaluationState): UEvaluationInfo {
inputStateCache[node] = data
val objectInfo = node.declaration.accept(this, data)
val resultState = data.merge(objectInfo.state)
return UUndeterminedValue to resultState storeResultFor node
}
override fun visitLambdaExpression(node: ULambdaExpression, data: UEvaluationState): UEvaluationInfo {
inputStateCache[node] = data
val lambdaInfo = node.body.accept(this, data)
val resultState = data.merge(lambdaInfo.state)
return UUndeterminedValue to resultState storeResultFor node
}
override fun visitClass(node: UClass, data: UEvaluationState): UEvaluationInfo {
// fields / initializers / nested classes?
var resultState = data
for (method in node.methods) {
resultState = resultState.merge(method.accept(this, resultState).state)
}
return UUndeterminedValue to resultState
}
override fun visitMethod(node: UMethod, data: UEvaluationState): UEvaluationInfo {
return UUndeterminedValue to (node.uastBody?.accept(this, data)?.state ?: data)
}
}
fun Any?.toConstant(node: ULiteralExpression? = null) = when (this) {
null -> UNullConstant
is Float -> UFloatConstant.create(this.toDouble(), UNumericType.FLOAT, node)
is Double -> UFloatConstant.create(this, UNumericType.DOUBLE, node)
is Long -> ULongConstant(this, node)
is Int -> UIntConstant(this, UNumericType.INT, node)
is Short -> UIntConstant(this.toInt(), UNumericType.SHORT, node)
is Byte -> UIntConstant(this.toInt(), UNumericType.BYTE, node)
is Char -> UCharConstant(this, node)
is Boolean -> UBooleanConstant.valueOf(this)
is String -> UStringConstant(this, node)
else -> UUndeterminedValue
}
| apache-2.0 | 431337c409e708d42c5ccbd5e5dd7d25 | 41.520424 | 120 | 0.707607 | 5.295026 | false | false | false | false |
Heiner1/AndroidAPS | automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/ComparatorConnect.kt | 1 | 2195 | package info.nightscout.androidaps.plugins.general.automation.elements
import android.view.Gravity
import android.view.View
import android.widget.AdapterView
import android.widget.ArrayAdapter
import android.widget.LinearLayout
import android.widget.Spinner
import androidx.annotation.StringRes
import info.nightscout.androidaps.automation.R
import info.nightscout.androidaps.interfaces.ResourceHelper
class ComparatorConnect(private val rh: ResourceHelper) : Element() {
enum class Compare {
ON_CONNECT, ON_DISCONNECT;
@get:StringRes val stringRes: Int
get() = when (this) {
ON_CONNECT -> R.string.onconnect
ON_DISCONNECT -> R.string.ondisconnect
}
companion object {
fun labels(rh: ResourceHelper): List<String> {
val list: MutableList<String> = ArrayList()
for (c in values()) list.add(rh.gs(c.stringRes))
return list
}
}
}
constructor(rh: ResourceHelper, value: Compare) : this(rh) {
this.value = value
}
var value = Compare.ON_CONNECT
override fun addToLayout(root: LinearLayout) {
root.addView(
Spinner(root.context).apply {
adapter = ArrayAdapter(root.context, R.layout.spinner_centered, Compare.labels(rh)).apply {
setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
}
layoutParams = LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT).apply {
setMargins(0, rh.dpToPx(4), 0, rh.dpToPx(4))
}
onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
value = Compare.values()[position]
}
override fun onNothingSelected(parent: AdapterView<*>?) {}
}
setSelection(value.ordinal)
gravity = Gravity.CENTER_HORIZONTAL
})
}
} | agpl-3.0 | 18eefded92b4219d72f228695ae15eba | 35 | 144 | 0.614579 | 5 | false | false | false | false |
ajalt/flexadapter | sample/src/main/kotlin/com/github/ajalt/flexadapter/sample/SampleActivity.kt | 1 | 5153 | package com.github.ajalt.flexadapter.sample
import android.os.Bundle
import android.support.annotation.ColorInt
import android.support.annotation.StringRes
import android.support.design.widget.Snackbar
import android.support.v7.app.AppCompatActivity
import android.support.v7.widget.CardView
import android.support.v7.widget.GridLayoutManager
import android.support.v7.widget.helper.ItemTouchHelper
import android.widget.TextView
import com.github.ajalt.flexadapter.CachingAdapterItem
import com.github.ajalt.flexadapter.CachingViewHolder
import com.github.ajalt.flexadapter.FlexAdapter
import kotlinx.android.synthetic.main.activity_sample.*
private const val COLUMNS = 3
private const val HORIZONTAL = ItemTouchHelper.LEFT or ItemTouchHelper.RIGHT
private const val VERTICAL = ItemTouchHelper.UP or ItemTouchHelper.DOWN
private const val ALL_DIRS = HORIZONTAL or VERTICAL
// You can have your data models inherit from FlexAdapterItem if you want to configure drag, swipe,
// or span per-item, or if you need more control over the ViewHolder creation.
/** A regular text item */
private class TextItem(
@StringRes var text: Int,
dragDirs: Int = 0
) : CachingAdapterItem(R.layout.item_text, dragDirs = dragDirs, span = COLUMNS) {
override fun CachingViewHolder.bindItemView(position: Int) {
view<TextView>(R.id.text_view).setText(text)
}
}
/** An image that spans all three columns */
private class WidePictureItem(
@ColorInt val color: Int = randomColor(),
dragDirs: Int = 0,
swipeDirs: Int = 0,
span: Int = COLUMNS
) : CachingAdapterItem(
R.layout.item_color_square_wide,
dragDirs = dragDirs,
swipeDirs = swipeDirs,
span = span
) {
override fun CachingViewHolder.bindItemView(position: Int) {
view<CardView>(R.id.card).setCardBackgroundColor(color)
}
}
// Or you can use any data model class (including primitives) if you use `FlexAdapter.register`.
data class HeaderItem(@StringRes var text: Int)
data class SquarePictureItem(@ColorInt val color: Int = randomColor())
object DIVIDER // It's fine to add the same item to the list more than once.
class SampleActivity : AppCompatActivity() {
// If you are only going to add a single type to the adapter, or if you have a common base type,
// you can use that as the type parameter instead of needing to cast from Any.
private val adapter = FlexAdapter<Any>()
private var extraImagesAdded = 0
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_sample)
recycler_view.adapter = adapter
recycler_view.layoutManager = GridLayoutManager(this, COLUMNS).apply {
spanSizeLookup = adapter.spanSizeLookup
}
with(adapter) {
register<HeaderItem>(R.layout.item_header, span = COLUMNS) {
view<TextView>(R.id.text_view).setText(it.text)
}
register<SquarePictureItem>(R.layout.item_color_square_large, dragDirs = ALL_DIRS) {
view<CardView>(R.id.card).setCardBackgroundColor(it.color)
}
register<DIVIDER>(R.layout.item_divider, span = COLUMNS)
}
val header1 = HeaderItem(R.string.title_drag_all)
val header2 = HeaderItem(R.string.title_swipe)
adapter.items.addAll(listOf(header1,
SquarePictureItem(),
SquarePictureItem(),
SquarePictureItem(),
SquarePictureItem(),
SquarePictureItem(),
SquarePictureItem(),
SquarePictureItem(),
SquarePictureItem(),
SquarePictureItem(),
WidePictureItem(span = 2, dragDirs = ALL_DIRS),
SquarePictureItem(),
DIVIDER,
HeaderItem(R.string.title_drag_vertical),
TextItem(R.string.list_drag_01),
TextItem(R.string.list_drag_02, dragDirs = VERTICAL),
TextItem(R.string.list_drag_03, dragDirs = VERTICAL),
TextItem(R.string.list_drag_04, dragDirs = VERTICAL),
TextItem(R.string.list_drag_05, dragDirs = VERTICAL),
TextItem(R.string.list_drag_06, dragDirs = VERTICAL),
DIVIDER,
header2,
WidePictureItem(swipeDirs = HORIZONTAL),
HeaderItem(R.string.title_no_swipe),
WidePictureItem()
))
// Change the header text when the large picture is swiped away
adapter.itemSwipedListener = {
header2.text = R.string.title_post_swipe
adapter.notifyItemObjectChanged(header2)
}
fab.setOnClickListener {
val item = SquarePictureItem()
adapter.items.add(adapter.items.indexOf(header1) + 1, item)
Snackbar.make(root_layout, R.string.snackbar_add_success, Snackbar.LENGTH_SHORT)
.setAction(R.string.action_undo) { adapter.items.remove(item); extraImagesAdded-- }
.show()
}
}
}
| apache-2.0 | 6ba454ffc14ad26b80cd1f8fb0a48e1a | 39.574803 | 103 | 0.657481 | 4.548102 | false | false | false | false |
bajdcc/jMiniLang | src/main/kotlin/com/bajdcc/LALR1/grammar/runtime/RuntimeFunc.kt | 1 | 2897 | package com.bajdcc.LALR1.grammar.runtime
/**
* 【运行时】调用函数基本单位
*
* @author bajdcc
*/
class RuntimeFunc {
/**
* 调用地址
*/
var address = -1
/**
* 名称
*/
var name: String? = null
/**
* 当前的代码页名
*/
var currentPc = 0
/**
* 当前的代码页名
*/
var currentPage = "extern"
/**
* 保存的返回指令地址
*/
var retPc = 0
/**
* 保存的返回代码页名
*/
var retPage = ""
/**
* 保存的异常跳转地址
*/
var tryJmp = -1
/**
* 参数
*/
private var params = mutableListOf<RuntimeObject>()
/**
* 临时变量
*/
private var tmp = mutableListOf<MutableMap<Int, RuntimeObject>>()
/**
* 函数闭包
*/
private var closure = mutableMapOf<Int, RuntimeObject>()
/**
* YIELD
*/
var yields = 0
private set
val simpleName: String
get() {
if (name == null)
return "extern"
val s = name!!.split("\\$".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()
return s[s.size - 1]
}
fun addYield() {
this.yields++
}
fun popYield() {
this.yields--
}
fun resetYield() {
this.yields = 0
}
init {
enterScope()
}
fun getParam(idx: Int): RuntimeObject {
return params[idx]
}
fun getParams(): List<RuntimeObject> {
return params
}
fun addParams(param: RuntimeObject) {
params.add(param)
}
fun getTmp(): List<Map<Int, RuntimeObject>> {
return tmp
}
fun addTmp(idx: Int, `val`: RuntimeObject) {
tmp[0].put(idx, `val`)
}
fun enterScope() {
tmp.add(0, mutableMapOf())
}
fun leaveScope() {
tmp.removeAt(0)
}
fun getClosure(): Map<Int, RuntimeObject> {
return closure
}
fun addClosure(idx: Int, `val`: RuntimeObject) {
closure[idx] = `val`
}
override fun toString(): String {
return System.lineSeparator() + "代码页:$currentPage,地址:$currentPc,名称:${name ?: "extern"},参数:$params,变量:$tmp,闭包:$closure"
}
fun copy(): RuntimeFunc {
val func = RuntimeFunc()
func.address = address
func.name = name
func.currentPc = currentPc
func.currentPage = currentPage
func.retPc = retPc
func.retPage = retPage
func.tryJmp = tryJmp
func.params = params.toMutableList()
func.tmp = tmp.map { it.entries.associate { it.key to it.value.clone() }.toMutableMap() }.toMutableList()
func.closure = closure.entries.associate { it.key to it.value.clone() }.toMutableMap()
func.yields = yields
return func
}
}
| mit | 3ecef263d4edf51fd95e54835cfac47c | 17.682759 | 126 | 0.51938 | 3.858974 | false | false | false | false |
square/retrofit | retrofit/src/main/java/retrofit2/KotlinExtensions.kt | 2 | 4057 | /*
* Copyright (C) 2018 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
@file:JvmName("KotlinExtensions")
package retrofit2
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.suspendCancellableCoroutine
import java.lang.reflect.ParameterizedType
import kotlin.coroutines.intrinsics.COROUTINE_SUSPENDED
import kotlin.coroutines.intrinsics.intercepted
import kotlin.coroutines.intrinsics.suspendCoroutineUninterceptedOrReturn
import kotlin.coroutines.resume
import kotlin.coroutines.resumeWithException
inline fun <reified T: Any> Retrofit.create(): T = create(T::class.java)
suspend fun <T : Any> Call<T>.await(): T {
return suspendCancellableCoroutine { continuation ->
continuation.invokeOnCancellation {
cancel()
}
enqueue(object : Callback<T> {
override fun onResponse(call: Call<T>, response: Response<T>) {
if (response.isSuccessful) {
val body = response.body()
if (body == null) {
val invocation = call.request().tag(Invocation::class.java)!!
val method = invocation.method()
val e = KotlinNullPointerException("Response from " +
method.declaringClass.name +
'.' +
method.name +
" was null but response body type was declared as non-null")
continuation.resumeWithException(e)
} else {
continuation.resume(body)
}
} else {
continuation.resumeWithException(HttpException(response))
}
}
override fun onFailure(call: Call<T>, t: Throwable) {
continuation.resumeWithException(t)
}
})
}
}
@JvmName("awaitNullable")
suspend fun <T : Any> Call<T?>.await(): T? {
return suspendCancellableCoroutine { continuation ->
continuation.invokeOnCancellation {
cancel()
}
enqueue(object : Callback<T?> {
override fun onResponse(call: Call<T?>, response: Response<T?>) {
if (response.isSuccessful) {
continuation.resume(response.body())
} else {
continuation.resumeWithException(HttpException(response))
}
}
override fun onFailure(call: Call<T?>, t: Throwable) {
continuation.resumeWithException(t)
}
})
}
}
@JvmName("awaitUnit")
suspend fun Call<Unit>.await() {
@Suppress("UNCHECKED_CAST")
(this as Call<Unit?>).await()
}
suspend fun <T> Call<T>.awaitResponse(): Response<T> {
return suspendCancellableCoroutine { continuation ->
continuation.invokeOnCancellation {
cancel()
}
enqueue(object : Callback<T> {
override fun onResponse(call: Call<T>, response: Response<T>) {
continuation.resume(response)
}
override fun onFailure(call: Call<T>, t: Throwable) {
continuation.resumeWithException(t)
}
})
}
}
/**
* Force the calling coroutine to suspend before throwing [this].
*
* This is needed when a checked exception is synchronously caught in a [java.lang.reflect.Proxy]
* invocation to avoid being wrapped in [java.lang.reflect.UndeclaredThrowableException].
*
* The implementation is derived from:
* https://github.com/Kotlin/kotlinx.coroutines/pull/1667#issuecomment-556106349
*/
internal suspend fun Exception.suspendAndThrow(): Nothing {
suspendCoroutineUninterceptedOrReturn<Nothing> { continuation ->
Dispatchers.Default.dispatch(continuation.context) {
continuation.intercepted().resumeWithException(this@suspendAndThrow)
}
COROUTINE_SUSPENDED
}
}
| apache-2.0 | 10f46d1ffb5dc6113667122e82621d14 | 31.198413 | 97 | 0.680552 | 4.553311 | false | false | false | false |
orbite-mobile/monastic-jerusalem-community | app/src/main/java/pl/orbitemobile/wspolnoty/activities/news/NewsView.kt | 1 | 4371 | /*
* Copyright (c) 2017. All Rights Reserved. Michal Jankowski orbitemobile.pl
*/
package pl.orbitemobile.wspolnoty.activities.news
import android.support.v7.widget.CardView
import android.support.v7.widget.GridLayoutManager
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.FrameLayout
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import com.squareup.picasso.Picasso
import pl.orbitemobile.mvp.bind
import pl.orbitemobile.wspolnoty.R
import pl.orbitemobile.wspolnoty.activities.mvp.DownloadViewUtil
import pl.orbitemobile.wspolnoty.data.dto.ArticleDTO
class NewsView : NewsContract.View(R.layout.news_view) {
override var viewContent: View? = null
var frameLayout: FrameLayout? = null
override var progressBar: View? = null
override var errorLayout: LinearLayout? = null
override var errorButton: TextView? = null
var recyclerView: RecyclerView? = null
var loadMoreNews: TextView? = null
private var adapter: NewsAdapter? = null
override fun View.bindViews(): View {
frameLayout = bind(R.id.news_frame_layout)
progressBar = bind(R.id.progress_bar)
errorLayout = bind(R.id.error_layout)
errorButton = bind(R.id.error_button)
recyclerView = bind(R.id.news_recycler_view)
loadMoreNews = bind(R.id.load_more_news)
viewContent = loadMoreNews
setRecyclerViewMatchScreenSize()
return this
}
override fun showErrorMessage() = DownloadViewUtil.showErrorMessage(this) { presenter!!.onRetryClick() }
override fun showLoadingScreen() = DownloadViewUtil.showLoadingScreen(this)
override fun showArticles(articleDTOs: Array<ArticleDTO>) {
DownloadViewUtil.showViewContent(this)
loadMoreNews!!.setOnClickListener { presenter!!.onShowMore() }
setRecyclerArticles(articleDTOs)
}
private fun setRecyclerArticles(articleDTOs: Array<ArticleDTO>) {
if (adapter == null) {
initNewAdapter(articleDTOs)
} else {
adapter?.addArticles(articleDTOs)
adapter?.notifyDataSetChanged()
}
}
private fun initNewAdapter(articleDTOs: Array<ArticleDTO>) {
val layoutManager = GridLayoutManager(context, 1)
recyclerView?.layoutManager = layoutManager
adapter = NewsAdapter(articleDTOs)
recyclerView?.adapter = adapter
}
private fun setRecyclerViewMatchScreenSize() {
val height = frameLayout?.layoutParams!!.height
val width = frameLayout?.layoutParams!!.width
recyclerView?.layoutParams = LinearLayout.LayoutParams(width, height)
}
private inner class NewsAdapter internal constructor(var mArticleDTOs: Array<ArticleDTO>) : RecyclerView.Adapter<NewsAdapter.ViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): NewsAdapter.ViewHolder {
val attachToRoot = false
val view = LayoutInflater.from(parent.context).inflate(R.layout.news_article_entry, parent, attachToRoot)
return ViewHolder(view)
}
override fun onBindViewHolder(holder: NewsAdapter.ViewHolder, position: Int) =
holder.setArticle(mArticleDTOs[position])
override fun getItemCount(): Int = mArticleDTOs.size
fun addArticles(articleDTOs: Array<ArticleDTO>) {
mArticleDTOs += articleDTOs
}
internal inner class ViewHolder(view: View) : RecyclerView.ViewHolder(view) {
private val mTitle: TextView = view.bind(R.id.news_title)
private val mDataCreated: TextView = view.bind(R.id.news_data_created)
private val mThumbnail: ImageView = view.bind(R.id.news_thumbnail)
private val newsElement: CardView = view.bind(R.id.news_element)
fun setArticle(article: ArticleDTO) {
mDataCreated.text = article.dataCreated
mTitle.text = article.title
Picasso.with(context)
.load(article.imgUrl)
.error(R.drawable.hours_top)
.into(mThumbnail)
newsElement.setOnClickListener { presenter!!.onArticleClick(article) }
}
}
}
}
| agpl-3.0 | fabf81fe0afd0828316d3ff174acae6e | 38.378378 | 144 | 0.689087 | 4.720302 | false | false | false | false |
Hexworks/zircon | zircon.jvm.examples/src/main/kotlin/org/hexworks/zircon/examples/extensions/SelectorExtensions.kt | 1 | 1739 | package org.hexworks.zircon.examples.extensions
import org.hexworks.cobalt.databinding.api.extension.toProperty
import org.hexworks.cobalt.databinding.api.property.Property
import org.hexworks.zircon.api.Fragments
import org.hexworks.zircon.api.builder.fragment.SelectorBuilder
import org.hexworks.zircon.api.component.ColorTheme
import org.hexworks.zircon.api.data.Size
import org.hexworks.zircon.api.fragment.Selector
import org.hexworks.zircon.api.resource.TilesetResource
import org.hexworks.zircon.internal.resource.BuiltInCP437TilesetResource
import org.hexworks.zircon.internal.resource.BuiltInTrueTypeFontResource
import org.hexworks.zircon.internal.resource.ColorThemeResource
private val THEMES = ColorThemeResource.values().map { it.getTheme() }.toProperty()
/**
* Creates a [SelectorBuilder] pre-configured for [ColorTheme]s.
*/
fun Fragments.colorThemeSelector() = SelectorBuilder.newBuilder<ColorTheme>()
.withValues(THEMES)
.withToStringMethod { it.name }
/**
* Creates a [SelectorBuilder] pre-configured for [TilesetResource]s.
*/
@JvmOverloads
fun Fragments.tilesetSelector(width: Int = 16, height: Int = width): SelectorBuilder<TilesetResource> {
val size = Size.create(width, height)
return SelectorBuilder.newBuilder<TilesetResource>()
.withValues(
BuiltInCP437TilesetResource.values()
.filter { it.size == size }.plus(BuiltInTrueTypeFontResource
.values()
.map { it.toTilesetResource(height) }
.filter { it.size == size })
.toProperty()
)
}
fun <T : Any> Selector<T>.updateFromSelection(property: Property<T>): Selector<T> = also {
property.updateFrom(selectedValue)
}
| apache-2.0 | 7e6b5ed1faae38618e7328bd7cb1d83b | 39.44186 | 103 | 0.740081 | 4.241463 | false | false | false | false |
wordpress-mobile/WordPress-Android | WordPress/src/main/java/org/wordpress/android/ui/media/ExoPlayerUtils.kt | 1 | 3297 | @file:Suppress("DEPRECATION")
package org.wordpress.android.ui.media
import android.content.Context
import android.net.Uri
import com.google.android.exoplayer2.C
import com.google.android.exoplayer2.C.ContentType
import com.google.android.exoplayer2.offline.FilteringManifestParser
import com.google.android.exoplayer2.source.ExtractorMediaSource
import com.google.android.exoplayer2.source.MediaSource
import com.google.android.exoplayer2.source.dash.DashMediaSource.Factory
import com.google.android.exoplayer2.source.dash.manifest.DashManifestParser
import com.google.android.exoplayer2.source.hls.HlsMediaSource
import com.google.android.exoplayer2.source.hls.playlist.DefaultHlsPlaylistParserFactory
import com.google.android.exoplayer2.source.smoothstreaming.SsMediaSource
import com.google.android.exoplayer2.source.smoothstreaming.manifest.SsManifestParser
import com.google.android.exoplayer2.upstream.DefaultDataSourceFactory
import com.google.android.exoplayer2.upstream.DefaultHttpDataSourceFactory
import com.google.android.exoplayer2.util.Util
import dagger.Reusable
import org.wordpress.android.WordPress
import org.wordpress.android.ui.utils.AuthenticationUtils
import javax.inject.Inject
@Reusable
@Suppress("DEPRECATION")
class ExoPlayerUtils @Inject constructor(
private val authenticationUtils: AuthenticationUtils,
private val appContext: Context
) {
private var httpDataSourceFactory: DefaultHttpDataSourceFactory? = null
fun buildHttpDataSourceFactory(url: String): DefaultHttpDataSourceFactory {
if (httpDataSourceFactory == null) {
httpDataSourceFactory = DefaultHttpDataSourceFactory(WordPress.getUserAgent())
}
httpDataSourceFactory?.defaultRequestProperties?.set(authenticationUtils.getAuthHeaders(url))
return httpDataSourceFactory as DefaultHttpDataSourceFactory
}
private fun buildDefaultDataSourceFactory(httpDataSourceFactory: DefaultHttpDataSourceFactory) =
DefaultDataSourceFactory(appContext, httpDataSourceFactory)
@Suppress("UseCheckOrError")
fun buildMediaSource(uri: Uri): MediaSource? {
val httpDataSourceFactory = buildHttpDataSourceFactory(uri.toString())
val defaultDataSourceFactory = buildDefaultDataSourceFactory(httpDataSourceFactory)
return when (@ContentType val type = Util.inferContentType(uri)) {
C.TYPE_DASH -> Factory(defaultDataSourceFactory)
.setManifestParser(FilteringManifestParser(DashManifestParser(), null))
.createMediaSource(uri)
C.TYPE_SS -> SsMediaSource.Factory(defaultDataSourceFactory)
.setManifestParser(FilteringManifestParser(SsManifestParser(), null))
.createMediaSource(uri)
C.TYPE_HLS -> HlsMediaSource.Factory(defaultDataSourceFactory)
.setPlaylistParserFactory(DefaultHlsPlaylistParserFactory())
.createMediaSource(uri)
C.TYPE_OTHER -> ExtractorMediaSource.Factory(defaultDataSourceFactory).createMediaSource(uri)
else -> {
throw IllegalStateException("$UNSUPPORTED_TYPE $type")
}
}
}
companion object {
private const val UNSUPPORTED_TYPE = "Unsupported type"
}
}
| gpl-2.0 | 3f17ff7827e88d31ad4e8f3deef590b0 | 46.782609 | 105 | 0.765848 | 5.2752 | false | false | false | false |
mdaniel/intellij-community | plugins/github/src/org/jetbrains/plugins/github/GithubShareAction.kt | 1 | 20060 | // 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
import com.intellij.CommonBundle
import com.intellij.icons.AllIcons
import com.intellij.ide.impl.isTrusted
import com.intellij.openapi.actionSystem.ActionUpdateThread
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.CommonDataKeys
import com.intellij.openapi.actionSystem.DataProvider
import com.intellij.openapi.application.invokeAndWaitIfNeeded
import com.intellij.openapi.components.service
import com.intellij.openapi.fileEditor.FileDocumentManager
import com.intellij.openapi.progress.ProcessCanceledException
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.progress.Task
import com.intellij.openapi.project.DumbAwareAction
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.DialogWrapper
import com.intellij.openapi.ui.Messages
import com.intellij.openapi.ui.Splitter
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.util.NlsSafe
import com.intellij.openapi.util.ThrowableComputable
import com.intellij.openapi.vcs.*
import com.intellij.openapi.vcs.changes.ChangeListManager
import com.intellij.openapi.vcs.changes.ui.SelectFilesDialog
import com.intellij.openapi.vcs.ui.CommitMessage
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.ui.components.BrowserLink
import com.intellij.ui.components.JBLabel
import com.intellij.util.containers.ContainerUtil
import com.intellij.util.containers.mapSmartSet
import com.intellij.util.ui.JBUI
import com.intellij.util.ui.UIUtil
import com.intellij.vcsUtil.VcsFileUtil
import git4idea.DialogManager
import git4idea.GitUtil
import git4idea.actions.GitInit
import git4idea.commands.Git
import git4idea.commands.GitCommand
import git4idea.commands.GitLineHandler
import git4idea.i18n.GitBundle
import git4idea.repo.GitRepository
import git4idea.util.GitFileUtils
import org.jetbrains.annotations.NonNls
import org.jetbrains.annotations.TestOnly
import org.jetbrains.plugins.github.api.GithubApiRequestExecutorManager
import org.jetbrains.plugins.github.api.GithubApiRequests
import org.jetbrains.plugins.github.api.data.request.Type
import org.jetbrains.plugins.github.api.util.GithubApiPagesLoader
import org.jetbrains.plugins.github.authentication.GithubAuthenticationManager
import org.jetbrains.plugins.github.authentication.accounts.GithubAccount
import org.jetbrains.plugins.github.authentication.accounts.GithubAccountInformationProvider
import org.jetbrains.plugins.github.i18n.GithubBundle
import org.jetbrains.plugins.github.ui.GithubShareDialog
import org.jetbrains.plugins.github.util.*
import java.awt.BorderLayout
import java.awt.Component
import java.awt.Container
import java.io.IOException
import javax.swing.BoxLayout
import javax.swing.JComponent
import javax.swing.JLabel
import javax.swing.JPanel
class GithubShareAction : DumbAwareAction(GithubBundle.messagePointer("share.action"),
GithubBundle.messagePointer("share.action.description"),
AllIcons.Vcs.Vendors.Github) {
override fun getActionUpdateThread(): ActionUpdateThread {
return ActionUpdateThread.BGT
}
override fun update(e: AnActionEvent) {
val project = e.getData(CommonDataKeys.PROJECT)
e.presentation.isEnabledAndVisible = project != null && !project.isDefault && project.isTrusted()
}
// get gitRepository
// check for existing git repo
// check available repos and privateRepo access (net)
// Show dialog (window)
// create GitHub repo (net)
// create local git repo (if not exist)
// add GitHub as a remote host
// make first commit
// push everything (net)
override fun actionPerformed(e: AnActionEvent) {
val project = e.getData(CommonDataKeys.PROJECT)
val file = e.getData(CommonDataKeys.VIRTUAL_FILE)
if (project == null || project.isDisposed) {
return
}
shareProjectOnGithub(project, file)
}
companion object {
private val LOG = GithubUtil.LOG
@JvmStatic
fun shareProjectOnGithub(project: Project, file: VirtualFile?) {
FileDocumentManager.getInstance().saveAllDocuments()
val gitRepository = GithubGitHelper.findGitRepository(project, file)
val possibleRemotes = gitRepository
?.let(project.service<GHProjectRepositoriesManager>()::findKnownRepositories)
?.map { it.gitRemoteUrlCoordinates.url }.orEmpty()
if (possibleRemotes.isNotEmpty()) {
val existingRemotesDialog = GithubExistingRemotesDialog(project, possibleRemotes)
DialogManager.show(existingRemotesDialog)
if (!existingRemotesDialog.isOK) {
return
}
}
val authManager = service<GithubAuthenticationManager>()
val progressManager = service<ProgressManager>()
val requestExecutorManager = service<GithubApiRequestExecutorManager>()
val accountInformationProvider = service<GithubAccountInformationProvider>()
val gitHelper = service<GithubGitHelper>()
val git = service<Git>()
val accountInformationLoader = object : (GithubAccount, Component) -> Pair<Boolean, Set<String>> {
private val loadedInfo = mutableMapOf<GithubAccount, Pair<Boolean, Set<String>>>()
@Throws(IOException::class)
override fun invoke(account: GithubAccount, parentComponent: Component) = loadedInfo.getOrPut(account) {
val requestExecutor = requestExecutorManager.getExecutor(account, parentComponent) ?: throw ProcessCanceledException()
progressManager.runProcessWithProgressSynchronously(ThrowableComputable<Pair<Boolean, Set<String>>, IOException> {
val user = requestExecutor.execute(progressManager.progressIndicator, GithubApiRequests.CurrentUser.get(account.server))
val names = GithubApiPagesLoader
.loadAll(requestExecutor, progressManager.progressIndicator,
GithubApiRequests.CurrentUser.Repos.pages(account.server, Type.OWNER))
.mapSmartSet { it.name }
user.canCreatePrivateRepo() to names
}, GithubBundle.message("share.process.loading.account.info", account), true, project)
}
}
val shareDialog = GithubShareDialog(project,
authManager.getAccounts(),
authManager.getDefaultAccount(project),
gitRepository?.remotes?.map { it.name }?.toSet() ?: emptySet(),
accountInformationLoader)
DialogManager.show(shareDialog)
if (!shareDialog.isOK) {
return
}
val name: String = shareDialog.getRepositoryName()
val isPrivate: Boolean = shareDialog.isPrivate()
val remoteName: String = shareDialog.getRemoteName()
val description: String = shareDialog.getDescription()
val account: GithubAccount = shareDialog.getAccount()!!
val requestExecutor = requestExecutorManager.getExecutor(account, project) ?: return
object : Task.Backgroundable(project, GithubBundle.message("share.process")) {
private lateinit var url: String
override fun run(indicator: ProgressIndicator) {
// create GitHub repo (network)
LOG.info("Creating GitHub repository")
indicator.text = GithubBundle.message("share.process.creating.repository")
url = requestExecutor
.execute(indicator, GithubApiRequests.CurrentUser.Repos.create(account.server, name, description, isPrivate)).htmlUrl
LOG.info("Successfully created GitHub repository")
val root = gitRepository?.root ?: project.baseDir
// creating empty git repo if git is not initialized
LOG.info("Binding local project with GitHub")
if (gitRepository == null) {
LOG.info("No git detected, creating empty git repo")
indicator.text = GithubBundle.message("share.process.creating.git.repository")
if (!createEmptyGitRepository(project, root)) {
return
}
}
val repositoryManager = GitUtil.getRepositoryManager(project)
val repository = repositoryManager.getRepositoryForRoot(root)
if (repository == null) {
GithubNotifications.showError(project,
GithubNotificationIdsHolder.SHARE_CANNOT_FIND_GIT_REPO,
GithubBundle.message("share.error.failed.to.create.repo"),
GithubBundle.message("cannot.find.git.repo"))
return
}
indicator.text = GithubBundle.message("share.process.retrieving.username")
val username = accountInformationProvider.getInformation(requestExecutor, indicator, account).login
val remoteUrl = gitHelper.getRemoteUrl(account.server, username, name)
//git remote add origin [email protected]:login/name.git
LOG.info("Adding GitHub as a remote host")
indicator.text = GithubBundle.message("share.process.adding.gh.as.remote.host")
git.addRemote(repository, remoteName, remoteUrl).throwOnError()
repository.update()
// create sample commit for binding project
if (!performFirstCommitIfRequired(project, root, repository, indicator, name, url)) {
return
}
//git push origin master
LOG.info("Pushing to github master")
indicator.text = GithubBundle.message("share.process.pushing.to.github.master")
if (!pushCurrentBranch(project, repository, remoteName, remoteUrl, name, url)) {
return
}
GithubNotifications.showInfoURL(project,
GithubNotificationIdsHolder.SHARE_PROJECT_SUCCESSFULLY_SHARED,
GithubBundle.message("share.process.successfully.shared"),
name,
url)
}
private fun createEmptyGitRepository(project: Project,
root: VirtualFile): Boolean {
val result = Git.getInstance().init(project, root)
if (!result.success()) {
VcsNotifier.getInstance(project).notifyError(GithubNotificationIdsHolder.GIT_REPO_INIT_REPO,
GitBundle.message("initializing.title"),
result.errorOutputAsHtmlString)
LOG.info("Failed to create empty git repo: " + result.errorOutputAsJoinedString)
return false
}
GitInit.refreshAndConfigureVcsMappings(project, root, root.path)
GitUtil.generateGitignoreFileIfNeeded(project, root)
return true
}
private fun performFirstCommitIfRequired(project: Project,
root: VirtualFile,
repository: GitRepository,
indicator: ProgressIndicator,
name: @NlsSafe String,
url: String): Boolean {
// check if there is no commits
if (!repository.isFresh) {
return true
}
LOG.info("Trying to commit")
try {
LOG.info("Adding files for commit")
indicator.text = GithubBundle.message("share.process.adding.files")
// ask for files to add
val trackedFiles = ChangeListManager.getInstance(project).affectedFiles
val untrackedFiles =
filterOutIgnored(project, repository.untrackedFilesHolder.retrieveUntrackedFilePaths().mapNotNull(FilePath::getVirtualFile))
trackedFiles.removeAll(untrackedFiles) // fix IDEA-119855
val allFiles = ArrayList<VirtualFile>()
allFiles.addAll(trackedFiles)
allFiles.addAll(untrackedFiles)
val dialog = invokeAndWaitIfNeeded(indicator.modalityState) {
GithubUntrackedFilesDialog(project, allFiles).apply {
if (!trackedFiles.isEmpty()) {
selectedFiles = trackedFiles
}
DialogManager.show(this)
}
}
val files2commit = dialog.selectedFiles
if (!dialog.isOK || files2commit.isEmpty()) {
GithubNotifications.showInfoURL(project,
GithubNotificationIdsHolder.SHARE_EMPTY_REPO_CREATED,
GithubBundle.message("share.process.empty.project.created"),
name, url)
return false
}
val files2add = ContainerUtil.intersection(untrackedFiles, files2commit)
val files2rm = ContainerUtil.subtract(trackedFiles, files2commit)
val modified = HashSet(trackedFiles)
modified.addAll(files2commit)
GitFileUtils.addFiles(project, root, files2add)
GitFileUtils.deleteFilesFromCache(project, root, files2rm)
// commit
LOG.info("Performing commit")
indicator.text = GithubBundle.message("share.process.performing.commit")
val handler = GitLineHandler(project, root, GitCommand.COMMIT)
handler.setStdoutSuppressed(false)
handler.addParameters("-m", dialog.commitMessage)
handler.endOptions()
Git.getInstance().runCommand(handler).throwOnError()
VcsFileUtil.markFilesDirty(project, modified)
}
catch (e: VcsException) {
LOG.warn(e)
GithubNotifications.showErrorURL(project, GithubNotificationIdsHolder.SHARE_PROJECT_INIT_COMMIT_FAILED,
GithubBundle.message("share.error.cannot.finish"),
GithubBundle.message("share.error.created.project"),
" '$name' ",
GithubBundle.message("share.error.init.commit.failed") + GithubUtil.getErrorTextFromException(
e),
url)
return false
}
LOG.info("Successfully created initial commit")
return true
}
private fun filterOutIgnored(project: Project, files: Collection<VirtualFile>): Collection<VirtualFile> {
val changeListManager = ChangeListManager.getInstance(project)
val vcsManager = ProjectLevelVcsManager.getInstance(project)
return ContainerUtil.filter(files) { file -> !changeListManager.isIgnoredFile(file) && !vcsManager.isIgnored(file) }
}
private fun pushCurrentBranch(project: Project,
repository: GitRepository,
remoteName: String,
remoteUrl: String,
name: String,
url: String): Boolean {
val currentBranch = repository.currentBranch
if (currentBranch == null) {
GithubNotifications.showErrorURL(project, GithubNotificationIdsHolder.SHARE_PROJECT_INIT_PUSH_FAILED,
GithubBundle.message("share.error.cannot.finish"),
GithubBundle.message("share.error.created.project"),
" '$name' ",
GithubBundle.message("share.error.push.no.current.branch"),
url)
return false
}
val result = git.push(repository, remoteName, remoteUrl, currentBranch.name, true)
if (!result.success()) {
GithubNotifications.showErrorURL(project, GithubNotificationIdsHolder.SHARE_PROJECT_INIT_PUSH_FAILED,
GithubBundle.message("share.error.cannot.finish"),
GithubBundle.message("share.error.created.project"),
" '$name' ",
GithubBundle.message("share.error.push.failed", result.errorOutputAsHtmlString),
url)
return false
}
return true
}
override fun onThrowable(error: Throwable) {
GithubNotifications.showError(project,
GithubNotificationIdsHolder.SHARE_CANNOT_CREATE_REPO,
GithubBundle.message("share.error.failed.to.create.repo"), error)
}
}.queue()
}
}
@TestOnly
class GithubExistingRemotesDialog(project: Project, private val remotes: List<String>) : DialogWrapper(project) {
init {
title = GithubBundle.message("share.error.project.is.on.github")
setOKButtonText(GithubBundle.message("share.anyway.button"))
init()
}
override fun createCenterPanel(): JComponent {
val mainText = JBLabel(if (remotes.size == 1) GithubBundle.message("share.action.remote.is.on.github")
else GithubBundle.message("share.action.remotes.are.on.github"))
val remotesPanel = JPanel().apply {
layout = BoxLayout(this, BoxLayout.Y_AXIS)
}
for (remote in remotes) {
remotesPanel.add(BrowserLink(remote, remote))
}
val messagesPanel = JBUI.Panels.simplePanel(UIUtil.DEFAULT_HGAP, UIUtil.DEFAULT_VGAP)
.addToTop(mainText)
.addToCenter(remotesPanel)
val iconContainer = Container().apply {
layout = BorderLayout()
add(JLabel(Messages.getQuestionIcon()), BorderLayout.NORTH)
}
return JBUI.Panels.simplePanel(UIUtil.DEFAULT_HGAP, UIUtil.DEFAULT_VGAP)
.addToCenter(messagesPanel)
.addToLeft(iconContainer)
.apply { border = JBUI.Borders.emptyBottom(UIUtil.LARGE_VGAP) }
}
}
@TestOnly
class GithubUntrackedFilesDialog(private val myProject: Project, untrackedFiles: List<VirtualFile>) :
SelectFilesDialog(myProject, untrackedFiles, null, null, true, false),
DataProvider {
private var myCommitMessagePanel: CommitMessage? = null
val commitMessage: String
get() = myCommitMessagePanel!!.comment
init {
title = GithubBundle.message("untracked.files.dialog.title")
setOKButtonText(CommonBundle.getAddButtonText())
setCancelButtonText(CommonBundle.getCancelButtonText())
init()
}
override fun createNorthPanel(): JComponent? {
return null
}
override fun createCenterPanel(): JComponent {
val tree = super.createCenterPanel()
val commitMessage = CommitMessage(myProject)
Disposer.register(disposable, commitMessage)
commitMessage.setCommitMessage("Initial commit")
myCommitMessagePanel = commitMessage
val splitter = Splitter(true)
splitter.setHonorComponentsMinimumSize(true)
splitter.firstComponent = tree
splitter.secondComponent = myCommitMessagePanel
splitter.proportion = 0.7f
return splitter
}
override fun getData(@NonNls dataId: String): Any? {
return if (VcsDataKeys.COMMIT_MESSAGE_CONTROL.`is`(dataId)) {
myCommitMessagePanel
}
else null
}
override fun getDimensionServiceKey(): String {
return "Github.UntrackedFilesDialog"
}
}
} | apache-2.0 | cfff616413238643627ad8239488d8b2 | 44.284424 | 139 | 0.639731 | 5.634831 | false | false | false | false |
ingokegel/intellij-community | platform/vcs-impl/src/com/intellij/vcs/commit/NonModalCommitPanel.kt | 1 | 8009 | // 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.vcs.commit
import com.intellij.openapi.Disposable
import com.intellij.openapi.actionSystem.*
import com.intellij.openapi.actionSystem.impl.ActionButton
import com.intellij.openapi.editor.colors.EditorColorsListener
import com.intellij.openapi.editor.colors.EditorColorsScheme
import com.intellij.openapi.editor.ex.EditorEx
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.ComponentContainer
import com.intellij.openapi.ui.popup.JBPopup
import com.intellij.openapi.ui.popup.JBPopupFactory
import com.intellij.openapi.ui.popup.JBPopupListener
import com.intellij.openapi.ui.popup.LightweightWindowEvent
import com.intellij.openapi.vcs.VcsBundle.message
import com.intellij.openapi.vcs.actions.ShowCommitOptionsAction
import com.intellij.openapi.vcs.changes.InclusionListener
import com.intellij.openapi.vcs.ui.CommitMessage
import com.intellij.openapi.wm.IdeFocusManager
import com.intellij.ui.JBColor
import com.intellij.ui.awt.RelativePoint
import com.intellij.ui.components.JBPanel
import com.intellij.ui.components.JBScrollPane
import com.intellij.ui.components.panels.VerticalLayout
import com.intellij.util.EventDispatcher
import com.intellij.util.IJSwingUtilities.updateComponentTreeUI
import com.intellij.util.ui.JBUI.Borders.empty
import com.intellij.util.ui.JBUI.Borders.emptyLeft
import com.intellij.util.ui.JBUI.Panels.simplePanel
import com.intellij.util.ui.JBUI.scale
import com.intellij.util.ui.UIUtil.getTreeBackground
import com.intellij.util.ui.UIUtil.uiTraverser
import com.intellij.util.ui.components.BorderLayoutPanel
import java.awt.Point
import javax.swing.BorderFactory
import javax.swing.JComponent
import javax.swing.JPanel
import javax.swing.LayoutFocusTraversalPolicy
import javax.swing.border.Border
import javax.swing.border.EmptyBorder
abstract class NonModalCommitPanel(
val project: Project,
val commitActionsPanel: CommitActionsPanel = CommitActionsPanel(),
val commitAuthorComponent: CommitAuthorComponent = CommitAuthorComponent(project)
) : BorderLayoutPanel(),
NonModalCommitWorkflowUi,
CommitActionsUi by commitActionsPanel,
CommitAuthorTracker by commitAuthorComponent,
ComponentContainer,
EditorColorsListener {
private val inclusionEventDispatcher = EventDispatcher.create(InclusionListener::class.java)
private val dataProviders = mutableListOf<DataProvider>()
private var needUpdateCommitOptionsUi = false
protected val centerPanel = simplePanel()
private val actions = ActionManager.getInstance().getAction("ChangesView.CommitToolbar") as ActionGroup
val toolbar = ActionManager.getInstance().createActionToolbar(COMMIT_TOOLBAR_PLACE, actions, true).apply {
targetComponent = this@NonModalCommitPanel
component.isOpaque = false
}
val commitMessage = CommitMessage(project, false, false, true, message("commit.message.placeholder")).apply {
editorField.addSettingsProvider {
it.setBorder(emptyLeft(6))
val jbScrollPane = it.scrollPane as? JBScrollPane
jbScrollPane?.statusComponent = createToolbarWithHistoryAction(editorField).component
}
}
private fun createToolbarWithHistoryAction(target: JComponent): ActionToolbar {
val actions = ActionManager.getInstance().getAction("Vcs.MessageActionGroup") as ActionGroup
val editorToolbar = ActionManager.getInstance().createActionToolbar(COMMIT_EDITOR_PLACE, actions, true).apply {
setReservePlaceAutoPopupIcon(false)
component.border = BorderFactory.createEmptyBorder()
component.isOpaque = false
targetComponent = target
}
return editorToolbar
}
override val commitMessageUi: CommitMessageUi get() = commitMessage
override fun getComponent(): JComponent = this
override fun getPreferredFocusableComponent(): JComponent = commitMessage.editorField
override fun getData(dataId: String) = getDataFromProviders(dataId) ?: commitMessage.getData(dataId)
fun getDataFromProviders(dataId: String): Any? {
for (dataProvider in dataProviders) {
return dataProvider.getData(dataId) ?: continue
}
return null
}
override fun addDataProvider(provider: DataProvider) {
dataProviders += provider
}
override fun addInclusionListener(listener: InclusionListener, parent: Disposable) =
inclusionEventDispatcher.addListener(listener, parent)
protected fun fireInclusionChanged() = inclusionEventDispatcher.multicaster.inclusionChanged()
override fun startBeforeCommitChecks() = Unit
override fun endBeforeCommitChecks(result: CommitChecksResult) = Unit
override fun dispose() = Unit
override fun globalSchemeChange(scheme: EditorColorsScheme?) {
needUpdateCommitOptionsUi = true
commitActionsPanel.border = getButtonPanelBorder()
}
protected fun buildLayout(bottomPanelBuilder: JPanel.() -> Unit) {
commitActionsPanel.apply {
border = getButtonPanelBorder()
background = getButtonPanelBackground()
setTargetComponent(this@NonModalCommitPanel)
}
centerPanel
.addToCenter(commitMessage)
.addToBottom(JBPanel<JBPanel<*>>(VerticalLayout(0)).apply {
background = getButtonPanelBackground()
bottomPanelBuilder()
})
addToCenter(centerPanel)
withPreferredHeight(85)
}
private fun getButtonPanelBorder(): Border {
return EmptyBorder(0, scale(3), (scale(6) - commitActionsPanel.getBottomInset()).coerceAtLeast(0), 0)
}
private fun getButtonPanelBackground(): JBColor? {
return JBColor.lazy { (commitMessage.editorField.editor as? EditorEx)?.backgroundColor ?: getTreeBackground() }
}
override fun showCommitOptions(options: CommitOptions, actionName: String, isFromToolbar: Boolean, dataContext: DataContext) {
val commitOptionsPanel = CommitOptionsPanel { actionName }.apply {
focusTraversalPolicy = LayoutFocusTraversalPolicy()
isFocusCycleRoot = true
setOptions(options)
border = empty(0, 10)
// to reflect LaF changes as commit options components are created once per commit
if (needUpdateCommitOptionsUi) {
needUpdateCommitOptionsUi = false
updateComponentTreeUI(this)
}
}
val focusComponent = IdeFocusManager.getInstance(project).getFocusTargetFor(commitOptionsPanel)
val commitOptionsPopup = JBPopupFactory.getInstance()
.createComponentPopupBuilder(commitOptionsPanel, focusComponent)
.setRequestFocus(true)
.addListener(object : JBPopupListener {
override fun beforeShown(event: LightweightWindowEvent) {
options.restoreState()
}
override fun onClosed(event: LightweightWindowEvent) {
options.saveState()
}
})
.createPopup()
showCommitOptions(commitOptionsPopup, isFromToolbar, dataContext)
}
protected open fun showCommitOptions(popup: JBPopup, isFromToolbar: Boolean, dataContext: DataContext) =
if (isFromToolbar) {
popup.showAbove(commitActionsPanel.getShowCommitOptionsButton() ?: commitActionsPanel)
}
else popup.showInBestPositionFor(dataContext)
companion object {
internal const val COMMIT_TOOLBAR_PLACE: String = "ChangesView.CommitToolbar"
internal const val COMMIT_EDITOR_PLACE: String = "ChangesView.Editor"
fun JBPopup.showAbove(component: JComponent) {
val northWest = RelativePoint(component, Point())
addListener(object : JBPopupListener {
override fun beforeShown(event: LightweightWindowEvent) {
val popup = event.asPopup()
val location = Point(popup.locationOnScreen).apply { y = northWest.screenPoint.y - popup.size.height }
popup.setLocation(location)
}
})
show(northWest)
}
}
}
private fun CommitActionsPanel.getShowCommitOptionsButton(): JComponent? =
uiTraverser(this)
.filter(ActionButton::class.java)
.find { it.action is ShowCommitOptionsAction }
| apache-2.0 | f0c42d2e73abbf7d0466b76fbe1f4159 | 37.504808 | 128 | 0.772131 | 4.990031 | false | false | false | false |
MER-GROUP/intellij-community | platform/script-debugger/debugger-ui/src/org/jetbrains/debugger/DebugProcessImpl.kt | 1 | 8729 | /*
* Copyright 2000-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.debugger
import com.intellij.execution.ExecutionResult
import com.intellij.execution.process.ProcessHandler
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.util.Url
import com.intellij.util.containers.ContainerUtil
import com.intellij.util.io.socketConnection.ConnectionStatus
import com.intellij.xdebugger.DefaultDebugProcessHandler
import com.intellij.xdebugger.XDebugProcess
import com.intellij.xdebugger.XDebugSession
import com.intellij.xdebugger.breakpoints.XBreakpoint
import com.intellij.xdebugger.breakpoints.XBreakpointHandler
import com.intellij.xdebugger.breakpoints.XLineBreakpoint
import com.intellij.xdebugger.breakpoints.XLineBreakpointType
import com.intellij.xdebugger.evaluation.XDebuggerEditorsProvider
import com.intellij.xdebugger.frame.XSuspendContext
import com.intellij.xdebugger.stepping.XSmartStepIntoHandler
import org.jetbrains.debugger.connection.VmConnection
import org.jetbrains.debugger.frame.SuspendContextImpl
import java.util.concurrent.ConcurrentMap
import java.util.concurrent.atomic.AtomicBoolean
abstract class DebugProcessImpl<C : VmConnection<*>>(session: XDebugSession,
val connection: C,
private val editorsProvider: XDebuggerEditorsProvider,
private val smartStepIntoHandler: XSmartStepIntoHandler<*>? = null,
protected val executionResult: ExecutionResult? = null) : XDebugProcess(session) {
protected val repeatStepInto: AtomicBoolean = AtomicBoolean()
@Volatile protected var lastStep: StepAction? = null
@Volatile protected var lastCallFrame: CallFrame? = null
@Volatile protected var isForceStep: Boolean = false
@Volatile protected var disableDoNotStepIntoLibraries: Boolean = false
protected val urlToFileCache: ConcurrentMap<Url, VirtualFile> = ContainerUtil.newConcurrentMap<Url, VirtualFile>()
var processBreakpointConditionsAtIdeSide: Boolean = false
private val _breakpointHandlers: Array<XBreakpointHandler<*>> by lazy(LazyThreadSafetyMode.NONE) { createBreakpointHandlers() }
init {
connection.stateChanged {
when (it.status) {
ConnectionStatus.DISCONNECTED, ConnectionStatus.DETACHED -> {
if (it.status == ConnectionStatus.DETACHED) {
if (realProcessHandler != null) {
// here must we must use effective process handler
processHandler.detachProcess()
}
}
getSession().stop()
}
ConnectionStatus.CONNECTION_FAILED -> {
getSession().reportError(it.message)
getSession().stop()
}
else -> {
getSession().rebuildViews()
}
}
}
}
protected final val realProcessHandler: ProcessHandler?
get() = executionResult?.processHandler
override final fun getSmartStepIntoHandler() = smartStepIntoHandler
override final fun getBreakpointHandlers() = when (connection.state.status) {
ConnectionStatus.DISCONNECTED, ConnectionStatus.DETACHED, ConnectionStatus.CONNECTION_FAILED -> XBreakpointHandler.EMPTY_ARRAY
else -> _breakpointHandlers
}
override final fun getEditorsProvider() = editorsProvider
val vm: Vm?
get() = connection.vm
protected abstract fun createBreakpointHandlers(): Array<XBreakpointHandler<*>>
private fun updateLastCallFrame() {
lastCallFrame = vm?.suspendContextManager?.context?.topFrame
}
override final fun checkCanPerformCommands() = vm != null
override final fun isValuesCustomSorted() = true
override final fun startStepOver() {
updateLastCallFrame()
continueVm(StepAction.OVER)
}
override final fun startForceStepInto() {
isForceStep = true
startStepInto()
}
override final fun startStepInto() {
updateLastCallFrame()
continueVm(StepAction.IN)
}
override final fun startStepOut() {
if (isVmStepOutCorrect()) {
lastCallFrame = null
}
else {
updateLastCallFrame()
}
continueVm(StepAction.OUT)
}
// some VM (firefox for example) doesn't implement step out correctly, so, we need to fix it
protected open fun isVmStepOutCorrect() = true
override final fun resume() {
continueVm(StepAction.CONTINUE)
}
/**
* You can override this method to avoid SuspendContextManager implementation, but it is not recommended.
*/
protected open fun continueVm(stepAction: StepAction) {
val suspendContextManager = vm!!.suspendContextManager
if (stepAction === StepAction.CONTINUE) {
if (suspendContextManager.context == null) {
// on resumed we ask session to resume, and session then call our "resume", but we have already resumed, so, we don't need to send "continue" message
return
}
lastStep = null
lastCallFrame = null
urlToFileCache.clear()
disableDoNotStepIntoLibraries = false
}
else {
lastStep = stepAction
}
suspendContextManager.continueVm(stepAction, 1)
}
protected fun setOverlay() {
vm!!.suspendContextManager.setOverlayMessage("Paused in debugger")
}
protected fun processBreakpoint(suspendContext: SuspendContext<*>, breakpoint: XBreakpoint<*>, xSuspendContext: SuspendContextImpl) {
val condition = breakpoint.conditionExpression?.expression
if (!processBreakpointConditionsAtIdeSide || condition == null) {
processBreakpointLogExpressionAndSuspend(breakpoint, xSuspendContext, suspendContext)
}
else {
xSuspendContext.evaluateExpression(condition)
.done(suspendContext) {
if ("false" == it) {
resume()
}
else {
processBreakpointLogExpressionAndSuspend(breakpoint, xSuspendContext, suspendContext)
}
}
.rejected(suspendContext) { processBreakpointLogExpressionAndSuspend(breakpoint, xSuspendContext, suspendContext) }
}
}
private fun processBreakpointLogExpressionAndSuspend(breakpoint: XBreakpoint<*>, xSuspendContext: SuspendContextImpl, suspendContext: SuspendContext<*>) {
val logExpression = breakpoint.logExpressionObject?.expression
if (logExpression == null) {
breakpointReached(breakpoint, null, xSuspendContext)
}
else {
xSuspendContext.evaluateExpression(logExpression)
.done(suspendContext) { breakpointReached(breakpoint, it, xSuspendContext) }
.rejected(suspendContext) { breakpointReached(breakpoint, "Failed to evaluate expression: $logExpression", xSuspendContext) }
}
}
private fun breakpointReached(breakpoint: XBreakpoint<*>, evaluatedLogExpression: String?, suspendContext: XSuspendContext) {
if (session.breakpointReached(breakpoint, evaluatedLogExpression, suspendContext)) {
setOverlay()
}
else {
resume()
}
}
override final fun startPausing() {
connection.vm.suspendContextManager.suspend().rejected(RejectErrorReporter(session, "Cannot pause"))
}
override final fun getCurrentStateMessage() = connection.state.message
override final fun getCurrentStateHyperlinkListener() = connection.state.messageLinkListener
override fun doGetProcessHandler() = executionResult?.processHandler ?: object : DefaultDebugProcessHandler() { override fun isSilentlyDestroyOnClose() = true }
fun saveResolvedFile(url: Url, file: VirtualFile) {
urlToFileCache.putIfAbsent(url, file)
}
open fun getLocationsForBreakpoint(breakpoint: XLineBreakpoint<*>): List<Location> = throw UnsupportedOperationException()
override fun isLibraryFrameFilterSupported() = true
}
class LineBreakpointHandler(breakpointTypeClass: Class<out XLineBreakpointType<*>>, private val manager: LineBreakpointManager) : XBreakpointHandler<XLineBreakpoint<*>>(breakpointTypeClass) {
override fun registerBreakpoint(breakpoint: XLineBreakpoint<*>) {
manager.setBreakpoint(breakpoint)
}
override fun unregisterBreakpoint(breakpoint: XLineBreakpoint<*>, temporary: Boolean) {
manager.removeBreakpoint(breakpoint, temporary)
}
} | apache-2.0 | 1eeabb50746ff436a4b251961375e64c | 37.122271 | 191 | 0.727804 | 5.287099 | false | false | false | false |
googlesamples/amapi | app/src/main/java/com/amapi/extensibility/demo/commands/CommandViewModel.kt | 1 | 4372 | /* Copyright 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.amapi.extensibility.demo.commands
import android.app.Application
import android.text.TextUtils
import android.util.Log
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.LiveData
import androidx.lifecycle.MediatorLiveData
import com.amapi.extensibility.demo.util.TAG
import com.google.android.managementapi.commands.LocalCommandClientFactory
import com.google.android.managementapi.commands.model.GetCommandRequest
import com.google.android.managementapi.commands.model.IssueCommandRequest
import com.google.android.managementapi.commands.model.IssueCommandRequest.ClearAppsData
import com.google.common.collect.ImmutableList
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.guava.await
import kotlinx.coroutines.launch
class CommandViewModel(application: Application) : AndroidViewModel(application) {
private val defaultScope = CoroutineScope(Dispatchers.Default)
private val commandResult: MediatorLiveData<String> =
MediatorLiveData<String>().apply {
addSource(InMemoryCommandRepository.getCommandLiveData()) { command ->
postValue(CommandUtils.parseCommandForPrettyPrint(command))
}
}
val commandResultLiveData: LiveData<String>
get() = commandResult
/**
* Issues a local command request to clear app data for [packageName].
*
* [commandResult] will be updated asynchronously of the response and in case of any error.
*/
fun issueClearAppDataCommand(packageName: String) {
if (TextUtils.isEmpty(packageName)) {
commandResult.postValue("Specify a package name")
return
}
defaultScope.launch {
try {
val command =
LocalCommandClientFactory.create(getApplication())
.issueCommand(
IssueCommandRequest.builder()
.setClearAppsData(
ClearAppsData.builder().setPackageNames(ImmutableList.of(packageName))
)
.build()
)
.await()
val parsedCommandString = CommandUtils.parseCommandForPrettyPrint(command)
Log.i(TAG, "Successfully issued command: $parsedCommandString")
commandResult.postValue(parsedCommandString)
} catch (exception: Exception) {
Log.e(TAG, "onFailure", exception)
val stringBuilder =
StringBuilder().apply {
append("Failed to execute command\n")
append(exception.message)
}
commandResult.postValue(stringBuilder.toString())
}
}
}
/**
* Issues a request to get the current status of previously issued local command with [commandId].
*
* [commandResult] will be updated asynchronously with the command status, or if the request
* failed.
*
* @param commandId
* - ID of the previously issued command
*/
fun getCommand(commandId: String) {
if (TextUtils.isEmpty(commandId)) {
commandResult.postValue("Command ID not specified")
return
}
defaultScope.launch {
try {
val command =
LocalCommandClientFactory.create(getApplication())
.getCommand(GetCommandRequest.builder().setCommandId(commandId).build())
.await()
val parsedCommandString = CommandUtils.parseCommandForPrettyPrint(command)
Log.i(TAG, "Successfully issued command: $parsedCommandString")
commandResult.postValue(parsedCommandString)
} catch (exception: Exception) {
Log.e(TAG, "Failed issuing command", exception)
val stringBuilder =
StringBuilder().apply {
append("Failed to get command\n")
append(exception.message)
}
commandResult.postValue(stringBuilder.toString())
}
}
}
}
| apache-2.0 | a28ab539c43f2e55a6f6d1949f76e42e | 36.050847 | 100 | 0.706084 | 4.923423 | false | false | false | false |
GunoH/intellij-community | platform/lang-impl/src/com/intellij/codeInsight/codeVision/ui/model/RichTextCodeVisionEntry.kt | 8 | 1796 | // 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.codeInsight.codeVision.ui.model
import com.intellij.codeInsight.codeVision.CodeVisionEntry
import com.intellij.codeInsight.codeVision.CodeVisionEntryExtraActionModel
import com.intellij.codeInsight.codeVision.codeVisionEntryMouseEventKey
import com.intellij.codeInsight.codeVision.ui.model.richText.RichText
import com.intellij.openapi.editor.Editor
import java.awt.event.MouseEvent
import javax.swing.Icon
open class RichTextCodeVisionEntry(providerId: String,
val text: RichText,
icon: Icon? = null,
longPresentation: String = "",
tooltip: String = "",
extraActions: List<CodeVisionEntryExtraActionModel> = emptyList())
: CodeVisionEntry(providerId, icon, longPresentation, tooltip, extraActions)
class ClickableRichTextCodeVisionEntry(providerId: String,
text: RichText,
val onClick: (MouseEvent?, Editor) -> Unit,
icon: Icon? = null,
longPresentation: String = "",
tooltip: String = "",
extraActions: List<CodeVisionEntryExtraActionModel> = emptyList()) : RichTextCodeVisionEntry(
providerId, text, icon, longPresentation, tooltip, extraActions), CodeVisionPredefinedActionEntry {
override fun onClick(editor: Editor) {
val mouseEvent = this.getUserData(codeVisionEntryMouseEventKey)
onClick.invoke(mouseEvent, editor)
}
} | apache-2.0 | 9d8686a2540d53c5ee2b1698c5e903db | 55.15625 | 132 | 0.624722 | 5.966777 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/ReplaceNegatedIsEmptyWithIsNotEmptyInspection.kt | 4 | 4701 | // 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.inspections
import com.intellij.codeInspection.LocalQuickFix
import com.intellij.codeInspection.ProblemDescriptor
import com.intellij.codeInspection.ProblemHighlightType
import com.intellij.codeInspection.ProblemsHolder
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiElementVisitor
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.base.psi.replaced
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.inspections.collections.isCalling
import org.jetbrains.kotlin.idea.intentions.callExpression
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.getLastParentOfTypeInRow
import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
import org.jetbrains.kotlin.idea.codeinsight.api.classic.inspections.AbstractKotlinInspection
class ReplaceNegatedIsEmptyWithIsNotEmptyInspection : AbstractKotlinInspection() {
override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean): PsiElementVisitor {
return qualifiedExpressionVisitor(fun(expression) {
if (expression.getWrappingPrefixExpressionIfAny()?.operationToken != KtTokens.EXCL) return
val calleeExpression = expression.callExpression?.calleeExpression ?: return
val from = calleeExpression.text
val to = expression.invertSelectorFunction()?.callExpression?.calleeExpression?.text ?: return
holder.registerProblem(
calleeExpression,
KotlinBundle.message("replace.negated.0.with.1", from, to),
ProblemHighlightType.GENERIC_ERROR_OR_WARNING,
ReplaceNegatedIsEmptyWithIsNotEmptyQuickFix(from, to)
)
})
}
companion object {
fun KtQualifiedExpression.invertSelectorFunction(bindingContext: BindingContext? = null): KtQualifiedExpression? {
val callExpression = callExpression ?: return null
val fromFunctionName = callExpression.calleeExpression?.text ?: return null
val (fromFunctionFqNames, toFunctionName) = functionNames[fromFunctionName] ?: return null
val context = bindingContext ?: analyze(BodyResolveMode.PARTIAL)
if (fromFunctionFqNames.none { callExpression.isCalling(it, context) }) return null
return KtPsiFactory(this).createExpressionByPattern(
"$0.$toFunctionName()",
receiverExpression,
reformat = false
) as? KtQualifiedExpression
}
}
}
class ReplaceNegatedIsEmptyWithIsNotEmptyQuickFix(private val from: String, private val to: String) : LocalQuickFix {
override fun getName() = KotlinBundle.message("replace.negated.0.with.1", from, to)
override fun getFamilyName() = name
override fun applyFix(project: Project, descriptor: ProblemDescriptor) {
val qualifiedExpression = descriptor.psiElement.getStrictParentOfType<KtQualifiedExpression>() ?: return
val prefixExpression = qualifiedExpression.getWrappingPrefixExpressionIfAny() ?: return
prefixExpression.replaced(
KtPsiFactory(qualifiedExpression).createExpressionByPattern(
"$0.$to()",
qualifiedExpression.receiverExpression
)
)
}
}
private fun PsiElement.getWrappingPrefixExpressionIfAny() =
(getLastParentOfTypeInRow<KtParenthesizedExpression>() ?: this).parent as? KtPrefixExpression
private val packages = listOf(
"java.util.ArrayList",
"java.util.HashMap",
"java.util.HashSet",
"java.util.LinkedHashMap",
"java.util.LinkedHashSet",
"kotlin.collections",
"kotlin.collections.List",
"kotlin.collections.Set",
"kotlin.collections.Map",
"kotlin.collections.MutableList",
"kotlin.collections.MutableSet",
"kotlin.collections.MutableMap",
"kotlin.text"
)
private val functionNames: Map<String, Pair<List<FqName>, String>> by lazy {
mapOf(
"isEmpty" to Pair(packages.map { FqName("$it.isEmpty") }, "isNotEmpty"),
"isNotEmpty" to Pair(packages.map { FqName("$it.isNotEmpty") }, "isEmpty"),
"isBlank" to Pair(listOf(FqName("kotlin.text.isBlank")), "isNotBlank"),
"isNotBlank" to Pair(listOf(FqName("kotlin.text.isNotBlank")), "isBlank"),
)
}
| apache-2.0 | a8cf174e07fa29720f4b196fa60f1a3c | 45.088235 | 122 | 0.730483 | 5.165934 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/frontend-independent/src/org/jetbrains/kotlin/idea/findUsages/handlers/KotlinFindUsagesHandler.kt | 1 | 5859 | // 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.findUsages.handlers
import com.intellij.find.findUsages.FindUsagesHandler
import com.intellij.find.findUsages.FindUsagesOptions
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.progress.ProgressManager
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiReference
import com.intellij.psi.impl.light.LightMemberReference
import com.intellij.psi.search.GlobalSearchScope
import com.intellij.psi.search.SearchScope
import com.intellij.usageView.UsageInfo
import com.intellij.util.CommonProcessors
import com.intellij.util.Processor
import org.jetbrains.kotlin.idea.base.util.runReadActionInSmartMode
import org.jetbrains.kotlin.idea.findUsages.KotlinFindUsagesHandlerFactory
import org.jetbrains.kotlin.idea.findUsages.KotlinReferencePreservingUsageInfo
import org.jetbrains.kotlin.idea.findUsages.KotlinReferenceUsageInfo
import com.intellij.openapi.application.runReadAction
import java.util.*
abstract class KotlinFindUsagesHandler<T : PsiElement>(
psiElement: T,
private val elementsToSearch: Collection<PsiElement>,
val factory: KotlinFindUsagesHandlerFactory
) : FindUsagesHandler(psiElement) {
@Suppress("UNCHECKED_CAST")
fun getElement(): T {
return psiElement as T
}
constructor(psiElement: T, factory: KotlinFindUsagesHandlerFactory) : this(psiElement, emptyList(), factory)
override fun getPrimaryElements(): Array<PsiElement> {
return if (elementsToSearch.isEmpty())
arrayOf(psiElement)
else
elementsToSearch.toTypedArray()
}
private fun searchTextOccurrences(
element: PsiElement,
processor: Processor<in UsageInfo>,
options: FindUsagesOptions
): Boolean {
if (!options.isSearchForTextOccurrences) return true
val scope = options.searchScope
if (scope is GlobalSearchScope) {
if (options.fastTrack == null) {
return processUsagesInText(element, processor, scope)
}
options.fastTrack.searchCustom {
processUsagesInText(element, processor, scope)
}
}
return true
}
override fun processElementUsages(
element: PsiElement,
processor: Processor<in UsageInfo>,
options: FindUsagesOptions
): Boolean {
return searchReferences(element, processor, options, forHighlight = false) && searchTextOccurrences(element, processor, options)
}
private fun searchReferences(
element: PsiElement,
processor: Processor<in UsageInfo>,
options: FindUsagesOptions,
forHighlight: Boolean
): Boolean {
val searcher = createSearcher(element, processor, options)
if (!runReadAction { project }.runReadActionInSmartMode { searcher.buildTaskList(forHighlight) }) return false
return searcher.executeTasks()
}
protected abstract fun createSearcher(
element: PsiElement,
processor: Processor<in UsageInfo>,
options: FindUsagesOptions
): Searcher
override fun findReferencesToHighlight(target: PsiElement, searchScope: SearchScope): Collection<PsiReference> {
val results = Collections.synchronizedList(arrayListOf<PsiReference>())
val options = findUsagesOptions.clone()
options.searchScope = searchScope
searchReferences(target, Processor { info ->
val reference = info.reference
if (reference != null) {
results.add(reference)
}
true
}, options, forHighlight = true)
return results
}
protected abstract class Searcher(
val element: PsiElement,
val processor: Processor<in UsageInfo>,
val options: FindUsagesOptions
) {
private val tasks = ArrayList<() -> Boolean>()
/**
* Adds a time-consuming operation to be executed outside read-action
*/
protected fun addTask(task: () -> Boolean) {
tasks.add(task)
}
/**
* Invoked outside read-action
*/
fun executeTasks(): Boolean {
return tasks.all { it() }
}
/**
* Invoked under read-action, should use [addTask] for all time-consuming operations
*/
abstract fun buildTaskList(forHighlight: Boolean): Boolean
}
companion object {
val LOG = Logger.getInstance(KotlinFindUsagesHandler::class.java)
internal fun processUsage(processor: Processor<in UsageInfo>, ref: PsiReference): Boolean =
processor.processIfNotNull {
when {
ref is LightMemberReference -> KotlinReferencePreservingUsageInfo(ref)
ref.element.isValid -> KotlinReferenceUsageInfo(ref)
else -> null
}
}
internal fun processUsage(
processor: Processor<in UsageInfo>,
element: PsiElement
): Boolean =
processor.processIfNotNull { if (element.isValid) UsageInfo(element) else null }
private fun Processor<in UsageInfo>.processIfNotNull(callback: () -> UsageInfo?): Boolean {
ProgressManager.checkCanceled()
val usageInfo = runReadAction(callback)
return if (usageInfo != null) process(usageInfo) else true
}
internal fun createReferenceProcessor(usageInfoProcessor: Processor<in UsageInfo>): Processor<PsiReference> {
val uniqueProcessor = CommonProcessors.UniqueProcessor(usageInfoProcessor)
return Processor { processUsage(uniqueProcessor, it) }
}
}
}
| apache-2.0 | e48ba91eb15996be9e95aca8feff91db | 35.61875 | 158 | 0.673835 | 5.440111 | false | false | false | false |
GunoH/intellij-community | plugins/yaml/src/org/jetbrains/yaml/formatter/YamlInjectedBlockFactory.kt | 2 | 9408 | // 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.
@file:JvmName("YamlInjectedBlockFactory")
package org.jetbrains.yaml.formatter
import com.intellij.formatting.*
import com.intellij.injected.editor.DocumentWindow
import com.intellij.lang.ASTNode
import com.intellij.lang.Language
import com.intellij.lang.injection.InjectedLanguageManager
import com.intellij.openapi.util.TextRange
import com.intellij.psi.PsiDocumentManager
import com.intellij.psi.PsiFile
import com.intellij.psi.PsiLanguageInjectionHost
import com.intellij.psi.codeStyle.CodeStyleSettings
import com.intellij.psi.formatter.common.DefaultInjectedLanguageBlockBuilder
import com.intellij.psi.templateLanguages.OuterLanguageElement
import com.intellij.util.SmartList
import com.intellij.util.asSafely
import com.intellij.util.text.TextRangeUtil
import com.intellij.util.text.escLBr
import org.jetbrains.yaml.YAMLFileType
import org.jetbrains.yaml.YAMLLanguage
internal fun substituteInjectedBlocks(settings: CodeStyleSettings,
rawSubBlocks: List<Block>,
injectionHost: ASTNode,
wrap: Wrap?,
alignment: Alignment?): List<Block> {
val injectedBlocks = SmartList<Block>().apply {
val outerBLocks = rawSubBlocks.filter { (it as? ASTBlock)?.node is OuterLanguageElement }
val fixedIndent = IndentImpl(Indent.Type.SPACES, false, settings.getIndentSize(YAMLFileType.YML), false, false)
YamlInjectedLanguageBlockBuilder(settings, outerBLocks).addInjectedBlocks(this, injectionHost, wrap, alignment, fixedIndent)
}
if (injectedBlocks.isEmpty()) return rawSubBlocks
injectedBlocks.addAll(0,
rawSubBlocks.filter(injectedBlocks.first().textRange.startOffset.let { start -> { it.textRange.endOffset <= start } }))
injectedBlocks.addAll(rawSubBlocks.filter(injectedBlocks.last().textRange.endOffset.let { end -> { it.textRange.startOffset >= end } }))
return injectedBlocks
}
private class YamlInjectedLanguageBlockBuilder(settings: CodeStyleSettings, val outerBlocks: List<Block>)
: DefaultInjectedLanguageBlockBuilder(settings) {
override fun supportsMultipleFragments(): Boolean = true
lateinit var injectionHost: ASTNode
lateinit var injectedFile: PsiFile
lateinit var injectionLanguage: Language
override fun addInjectedBlocks(result: MutableList<in Block>,
injectionHost: ASTNode,
wrap: Wrap?,
alignment: Alignment?,
indent: Indent?): Boolean {
this.injectionHost = injectionHost
return super.addInjectedBlocks(result, injectionHost, wrap, alignment, indent)
}
override fun addInjectedLanguageBlocks(result: MutableList<in Block>,
injectedFile: PsiFile,
indent: Indent?,
offset: Int,
injectedEditableRange: TextRange?,
shreds: List<PsiLanguageInjectionHost.Shred>) {
this.injectedFile = injectedFile
return super.addInjectedLanguageBlocks(result, injectedFile, indent, offset, injectedEditableRange, shreds)
}
override fun createBlockBeforeInjection(node: ASTNode, wrap: Wrap?, alignment: Alignment?, indent: Indent?, range: TextRange): Block? =
super.createBlockBeforeInjection(node, wrap, alignment, indent, removeIndentFromRange(range))
private fun removeIndentFromRange(range: TextRange): TextRange =
trimBlank(range, range.shiftLeft(injectionHost.startOffset).substring(injectionHost.text))
private fun injectedToHost(textRange: TextRange): TextRange =
InjectedLanguageManager.getInstance(injectedFile.project).injectedToHost(injectedFile, textRange)
private fun hostToInjected(textRange: TextRange): TextRange? {
val documentWindow = PsiDocumentManager.getInstance(injectedFile.project).getCachedDocument(injectedFile) as? DocumentWindow
?: return null
return TextRange(documentWindow.hostToInjected(textRange.startOffset), documentWindow.hostToInjected(textRange.endOffset))
}
override fun createInjectedBlock(node: ASTNode,
originalBlock: Block,
indent: Indent?,
offset: Int,
range: TextRange,
language: Language): Block {
this.injectionLanguage = language
val trimmedRange = trimBlank(range, range.substring(node.text))
return YamlInjectedLanguageBlockWrapper(originalBlock, injectedToHost(trimmedRange), trimmedRange, outerBlocks, indent, YAMLLanguage.INSTANCE)
}
private fun trimBlank(range: TextRange, substring: String): TextRange {
val preWS = substring.takeWhile { it.isWhitespace() }.count()
val postWS = substring.takeLastWhile { it.isWhitespace() }.count()
return if (preWS < range.length) range.run { TextRange(startOffset + preWS, endOffset - postWS) } else range
}
private inner class YamlInjectedLanguageBlockWrapper(val original: Block,
val rangeInHost: TextRange,
val myRange: TextRange,
outerBlocks: Collection<Block>,
private val indent: Indent?,
private val language: Language?) : BlockEx {
override fun toString(): String = "YamlInjectedLanguageBlockWrapper($original, $myRange," +
" rangeInRoot = $textRange '${textRange.substring(injectionHost.psi.containingFile.text).escLBr()}')"
override fun getTextRange(): TextRange {
val subBlocks = subBlocks
if (subBlocks.isEmpty()) return rangeInHost
return TextRange.create(
subBlocks.first().textRange.startOffset.coerceAtMost(rangeInHost.startOffset),
subBlocks.last().textRange.endOffset.coerceAtLeast(rangeInHost.endOffset))
}
private val myBlocks by lazy(LazyThreadSafetyMode.NONE) {
SmartList<Block>().also { result ->
val outerBlocksQueue = ArrayDeque(outerBlocks)
for (block in original.subBlocks) {
myRange.intersection(block.textRange)?.let { blockRange ->
val blockRangeInHost = injectedToHost(blockRange)
fun createInnerWrapper(blockRangeInHost: TextRange, blockRange: TextRange, outerNodes: Collection<Block>) =
YamlInjectedLanguageBlockWrapper(block,
blockRangeInHost,
blockRange,
outerNodes,
replaceAbsoluteIndent(block),
block.asSafely<BlockEx>()?.language ?: injectionLanguage)
result.addAll(outerBlocksQueue.popWhile { it.textRange.endOffset <= blockRangeInHost.startOffset })
if (block.subBlocks.isNotEmpty()) {
result.add(createInnerWrapper(
blockRangeInHost,
blockRange,
outerBlocksQueue.popWhile { blockRangeInHost.contains(it.textRange) }))
}
else {
val outer = outerBlocksQueue.popWhile { blockRangeInHost.contains(it.textRange) }
val remainingInjectedRanges = TextRangeUtil.excludeRanges(blockRangeInHost, outer.map { it.textRange })
val splitInjectedLeaves =
remainingInjectedRanges.map { part -> createInnerWrapper(part, hostToInjected(part) ?: blockRange, emptyList()) }
result.addAll((splitInjectedLeaves + outer).sortedBy { it.textRange.startOffset })
}
}
}
result.addAll(outerBlocksQueue)
}
}
private fun replaceAbsoluteIndent(block: Block): Indent? = block.indent.asSafely<IndentImpl>()?.takeIf { it.isAbsolute }
?.run { IndentImpl(type, false, spaces, isRelativeToDirectParent, isEnforceIndentToChildren) } ?:block.indent
override fun getSubBlocks(): List<Block> = myBlocks
override fun getWrap(): Wrap? = original.wrap
override fun getIndent(): Indent? = indent
override fun getAlignment(): Alignment? = original.alignment
override fun getSpacing(child1: Block?, child2: Block): Spacing? = original.getSpacing(child1?.unwrap(), child2.unwrap())
override fun getChildAttributes(newChildIndex: Int): ChildAttributes = original.getChildAttributes(newChildIndex)
override fun isIncomplete(): Boolean = original.isIncomplete
override fun isLeaf(): Boolean = original.isLeaf
override fun getLanguage(): Language? = language
}
private fun Block.unwrap() = this.asSafely<YamlInjectedLanguageBlockWrapper>()?.original ?: this
private fun <T> ArrayDeque<T>.popWhile(pred: (T) -> Boolean): List<T> {
if (this.isEmpty()) return emptyList()
val result = SmartList<T>()
while (this.isNotEmpty() && pred(this.first()))
result.add(this.removeFirst())
return result
}
} | apache-2.0 | b191ad110c472f3c30b0e31addc6cab1 | 50.415301 | 158 | 0.658588 | 5.379074 | false | false | false | false |
OnyxDevTools/onyx-database-parent | onyx-database-tests/src/main/kotlin/entities/EntityYo.kt | 1 | 719 | package entities
import com.onyx.buffer.BufferStreamable
import java.util.*
/**
* Created by timothy.osborn on 4/2/15.
*/
class EntityYo : BufferStreamable {
var id: String? = null
var longValue: Long? = null
var dateValue: Date? = null
var longStringValue: String? = null
var otherStringValue: String? = null
var mutableInteger: Int? = null
var mutableLong: Long? = null
var mutableBoolean: Boolean? = null
var mutableFloat: Float? = null
var mutableDouble: Double? = null
var immutableInteger: Int = 0
var immutableLong: Long = 0
var immutableBoolean: Boolean = false
var immutableFloat: Float = 0.toFloat()
var immutableDouble: Double = 0.toDouble()
}
| agpl-3.0 | 0c53377bfed842ffae9a98c07add2450 | 27.76 | 46 | 0.688456 | 3.907609 | false | false | false | false |
marius-m/wt4 | app/src/main/java/lt/markmerkk/widgets/help/ImgResourceLoader.kt | 1 | 1342 | package lt.markmerkk.widgets.help
import lt.markmerkk.repositories.ExternalResRepository
import lt.markmerkk.repositories.entities.ExternalRes
import org.slf4j.LoggerFactory
class ImgResourceLoader(
private val externalResRepository: ExternalResRepository
) {
private val imageFileMap: Map<ResourceSvg, ExternalRes>
init {
val externalResources = externalResRepository
.externalResources(rootPath = ROOT_PATH)
.toBlocking()
.value()
l.debug("Found ${externalResources.size} entries. [$externalResources]")
imageFileMap = ResourceSvg.values().map { res ->
l.debug("Matching '$res' to $externalResources")
val fileRes = externalResources.first { imageFile ->
imageFile.name == res.resFileName
}
res to fileRes
}.toMap()
}
fun imageResRaw(res: ResourceSvg): String {
val imageRes = imageFileMap.getValue(res)
return externalResRepository
.readExternalResourceAsString(imageRes)
.toBlocking().value()
}
companion object {
private const val ROOT_PATH: String = "svgs"
val l = LoggerFactory.getLogger(ImgResourceLoader::class.java)!!
}
}
enum class ResourceSvg(val resFileName: String) {
HELP("help_black_24dp.svg")
} | apache-2.0 | 9eedcf42c9d6d07fa4edfd38b33f04bf | 30.232558 | 80 | 0.660209 | 4.643599 | false | false | false | false |
CzBiX/v2ex-android | app/src/main/kotlin/com/czbix/v2ex/util/RxUtils.kt | 1 | 1044 | package com.czbix.v2ex.util
import io.reactivex.Single
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import io.reactivex.internal.observers.ConsumerSingleObserver
fun <T : Any> Single<T>.await(onSuccess: (T) -> Unit): Disposable {
return this.observeOn(AndroidSchedulers.mainThread()).subscribe(onSuccess)
}
fun <T> Single<T>.await(onSuccess: (T) -> Unit, onError: (Throwable) -> Unit): Disposable {
return this.observeOn(AndroidSchedulers.mainThread()).subscribe(onSuccess, onError)
}
fun MutableList<Disposable>.dispose() {
this.forEach { it.dispose() }
this.clear()
}
/**
* @see io.reactivex.exceptions.Exceptions.propagate
*/
fun <T> Single<T>.result(): T {
try {
return this.blockingGet()
} catch (e: RuntimeException) {
// unwarp RuntimeException for Exceptions.propagate
val cause = e.cause
when {
cause == null -> throw e
cause === e -> throw e
else -> throw cause
}
}
}
| apache-2.0 | ba3d0064adfb5fc12f79309461455d21 | 28 | 91 | 0.66954 | 4.030888 | false | false | false | false |
ktorio/ktor | ktor-server/ktor-server-core/jvmAndNix/src/io/ktor/server/util/Paths.kt | 1 | 3344 | /*
* 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.server.util
import io.ktor.util.*
/**
* Process path components such as `.` and `..`, replacing redundant path components including all leading.
* It also discards all reserved characters and component names that are reserved (such as `CON`, `NUL`).
*/
public fun List<String>.normalizePathComponents(): List<String> {
for (index in indices) {
val component = get(index)
if (component.shouldBeReplaced()) {
return filterComponentsImpl(index)
}
}
return this
}
private fun List<String>.filterComponentsImpl(startIndex: Int): List<String> {
val result = ArrayList<String>(size)
if (startIndex > 0) {
result.addAll(subList(0, startIndex))
}
result.processAndReplaceComponent(get(startIndex))
for (index in startIndex + 1 until size) {
val component = get(index)
if (component.shouldBeReplaced()) {
result.processAndReplaceComponent(component)
} else {
result.add(component)
}
}
return result
}
private fun MutableList<String>.processAndReplaceComponent(component: String) {
if (component.isEmpty() ||
component == "." || component == "~" || component.toUpperCasePreservingASCIIRules() in ReservedWords
) {
return
}
if (component == "..") {
if (isNotEmpty()) {
removeAt(lastIndex)
}
return
}
component.filter { it >= ' ' && it !in ReservedCharacters }
.trimEnd { it == ' ' || it == '.' }
.takeIf { it.isNotEmpty() }?.let { filtered ->
add(filtered)
}
}
private val FirstReservedLetters = charArrayOf('A', 'a', 'C', 'c', 'l', 'L', 'P', 'p', 'n', 'N').toASCIITable()
private val ReservedWords = setOf(
"CON", "PRN", "AUX", "NUL",
"COM1", "COM2", "COM3", "COM4", "COM5", "COM6", "COM7", "COM8", "COM9",
"LPT1", "LPT2", "LPT3", "LPT4", "LPT5", "LPT6", "LPT7", "LPT8", "LPT9"
)
private val ReservedCharacters = charArrayOf('\\', '/', ':', '*', '?', '\"', '<', '>', '|').toASCIITable()
@Suppress("LocalVariableName")
private fun String.shouldBeReplaced(): Boolean {
val length = length
if (length == 0) return true
val first = this[0]
if (first == '.' && (length == 1 || (length == 2 && this[1] == '.'))) {
// replace . and ..
return true
}
if (first == '~' && length == 1) {
return true
}
if (first in FirstReservedLetters &&
(this in ReservedWords || this.toUpperCasePreservingASCIIRules() in ReservedWords)
) {
return true
}
val last = this[length - 1]
if (last == ' ' || last == '.') {
// not allowed in Windows
return true
}
val ReservedCharacters = ReservedCharacters
if (any { it < ' ' || it in ReservedCharacters }) {
// control characters are not allowed on windows, \0 is not allowed on UNIX
return true
}
return false
}
private fun CharArray.toASCIITable(): BooleanArray = BooleanArray(0x100) { it.toChar() in this@toASCIITable }
private operator fun BooleanArray.contains(char: Char): Boolean {
val codepoint = char.code
return codepoint < size && this[codepoint]
}
| apache-2.0 | fda144d83f2ca25269479b3f9ca171f5 | 29.126126 | 119 | 0.595395 | 3.980952 | false | false | false | false |
jovr/imgui | core/src/main/kotlin/imgui/demo/showExampleApp/StyleEditor.kt | 2 | 20390 | package imgui.demo.showExampleApp
import gli_.hasnt
import glm_.c
import glm_.f
import glm_.i
import glm_.vec2.Vec2
import glm_.vec4.Vec4
import imgui.*
import imgui.ImGui.beginTabBar
import imgui.ImGui.beginTabItem
import imgui.ImGui.bulletText
import imgui.ImGui.button
import imgui.ImGui.checkbox
import imgui.ImGui.colorEditVec4
import imgui.ImGui.combo
import imgui.ImGui.cursorScreenPos
import imgui.ImGui.dragFloat
import imgui.ImGui.dummy
import imgui.ImGui.endTabBar
import imgui.ImGui.endTabItem
import imgui.ImGui.fontSize
import imgui.ImGui.image
import imgui.ImGui.io
import imgui.ImGui.isMouseHoveringRect
import imgui.ImGui.logFinish
import imgui.ImGui.logText
import imgui.ImGui.logToClipboard
import imgui.ImGui.logToTTY
import imgui.ImGui.popFont
import imgui.ImGui.popID
import imgui.ImGui.popItemWidth
import imgui.ImGui.pushFont
import imgui.ImGui.pushID
import imgui.ImGui.pushItemWidth
import imgui.ImGui.sameLine
import imgui.ImGui.separator
import imgui.ImGui.setNextWindowPos
import imgui.ImGui.setWindowFontScale
import imgui.ImGui.showFontSelector
import imgui.ImGui.sliderFloat
import imgui.ImGui.sliderVec2
import imgui.ImGui.style
import imgui.ImGui.text
import imgui.ImGui.textEx
import imgui.ImGui.treeNode
import imgui.ImGui.treePop
import imgui.ImGui.windowDrawList
import imgui.ImGui.windowWidth
import imgui.api.demoDebugInformations.Companion.helpMarker
import imgui.api.demoDebugInformations.ShowStyleSelector
import imgui.api.g
import imgui.classes.Style
import imgui.classes.TextFilter
import imgui.dsl.button
import imgui.dsl.child
import imgui.dsl.radioButton
import imgui.dsl.smallButton
import imgui.dsl.tooltip
import imgui.dsl.treeNode
import imgui.dsl.withID
import imgui.dsl.withItemWidth
import imgui.font.Font
import uno.kotlin.NUL
import kotlin.math.sqrt
import imgui.ColorEditFlag as Cef
import imgui.WindowFlag as Wf
object StyleEditor {
var init = true
var refSavedStyle: Style? = null
// Default Styles Selector
var styleIdx = 0
var border = false
var border1 = false
var popupBorder = false
var outputDest = 0
var outputOnlyModified = true
var alphaFlags: ColorEditFlags = 0
val filter = TextFilter()
var windowScale = 1f
operator fun invoke(ref_: Style? = null) {
// You can pass in a reference ImGuiStyle structure to compare to, revert to and save to
// (without a reference style pointer, we will use one compared locally as a reference)
// Default to using internal storage as reference
if (init && ref_ == null) refSavedStyle = Style(style)
init = false
var ref = ref_ ?: refSavedStyle
pushItemWidth(windowWidth * 0.55f)
if (ShowStyleSelector("Colors##Selector")) refSavedStyle = Style(style)
showFontSelector("Fonts##Selector")
// Simplified Settings (expose floating-pointer border sizes as boolean representing 0.0f or 1.0f)
if (sliderFloat("FrameRounding", style::frameRounding, 0f, 12f, "%.0f")) style.grabRounding =
style.frameRounding // Make GrabRounding always the same value as FrameRounding
run {
border = style.windowBorderSize > 0f
if (checkbox("WindowBorder", ::border)) style.windowBorderSize = border.f
}
sameLine()
run {
border = style.frameBorderSize > 0f
if (checkbox("FrameBorder", ::border)) style.frameBorderSize = border.f
}
sameLine()
run {
border = style.popupBorderSize > 0f
if (checkbox("PopupBorder", ::border)) style.popupBorderSize = border.f
}
// Save/Revert button
button("Save Ref") {
refSavedStyle = Style(style)
ref = style
}
sameLine()
if (button("Revert Ref")) g.style = ref!!
sameLine()
helpMarker(
"Save/Revert in local non-persistent storage. Default Colors definition are not affected. " + "Use \"Export\" below to save them somewhere.")
separator()
if (beginTabBar("##tabs", TabBarFlag.None.i)) {
if (beginTabItem("Sizes")) {
text("Main")
sliderVec2("WindowPadding", style.windowPadding, 0f, 20f, "%.0f")
sliderVec2("FramePadding", style.framePadding, 0f, 20f, "%.0f")
sliderVec2("CellPadding", style.cellPadding, 0f, 20f, "%.0f")
sliderVec2("ItemSpacing", style.itemSpacing, 0f, 20f, "%.0f")
sliderVec2("ItemInnerSpacing", style.itemInnerSpacing, 0f, 20f, "%.0f")
sliderVec2("TouchExtraPadding", style.touchExtraPadding, 0f, 10f, "%.0f")
sliderFloat("IndentSpacing", style::indentSpacing, 0f, 30f, "%.0f")
sliderFloat("ScrollbarSize", style::scrollbarSize, 1f, 20f, "%.0f")
sliderFloat("GrabMinSize", style::grabMinSize, 1f, 20f, "%.0f")
text("Borders")
sliderFloat("WindowBorderSize", style::windowBorderSize, 0f, 1f, "%.0f")
sliderFloat("ChildBorderSize", style::childBorderSize, 0f, 1f, "%.0f")
sliderFloat("PopupBorderSize", style::popupBorderSize, 0f, 1f, "%.0f")
sliderFloat("FrameBorderSize", style::frameBorderSize, 0f, 1f, "%.0f")
sliderFloat("TabBorderSize", style::tabBorderSize, 0f, 1f, "%.0f")
text("Rounding")
sliderFloat("WindowRounding", style::windowRounding, 0f, 12f, "%.0f")
sliderFloat("ChildRounding", style::childRounding, 0f, 12f, "%.0f")
sliderFloat("FrameRounding", style::frameRounding, 0f, 12f, "%.0f")
sliderFloat("PopupRounding", style::popupRounding, 0f, 16f, "%.0f")
sliderFloat("ScrollbarRounding", style::scrollbarRounding, 0f, 12f, "%.0f")
sliderFloat("GrabRounding", style::grabRounding, 0f, 12f, "%.0f")
sliderFloat("LogSliderDeadzone", style::logSliderDeadzone, 0f, 12f, "%.0f")
sliderFloat("TabRounding", style::tabRounding, 0f, 12f, "%.0f")
text("Alignment")
sliderVec2("WindowTitleAlign", style.windowTitleAlign, 0f, 1f, "%.2f")
run {
_i = style.windowMenuButtonPosition.i + 1
if (combo("WindowMenuButtonPosition", ::_i,
"None${NUL}Left${NUL}Right${NUL}")
) style.windowMenuButtonPosition = Dir.values().first { it.i == _i - 1 }
}
run {
_i = style.colorButtonPosition.i
combo("ColorButtonPosition", ::_i, "Left\u0000Right\u0000")
style.colorButtonPosition = Dir.values().first { it.i == _i }
}
sliderVec2("ButtonTextAlign", style.buttonTextAlign, 0f, 1f, "%.2f")
sameLine(); helpMarker("Alignment applies when a button is larger than its text content.")
sliderVec2("SelectableTextAlign", style.selectableTextAlign, 0f, 1f, "%.2f")
sameLine(); helpMarker("Alignment applies when a selectable is larger than its text content.")
text("Safe Area Padding")
sameLine(); helpMarker(
"Adjust if you cannot see the edges of your screen (e.g. on a TV where scaling has not been configured).")
sliderVec2("DisplaySafeAreaPadding", style.displaySafeAreaPadding, 0f, 30f, "%.0f")
endTabItem()
}
if (beginTabItem("Colors")) {
button("Export") {
if (outputDest == 0) logToClipboard()
else logToTTY()
logText("val colors = ImGui.style.colors\n")
for (i in Col.values()) {
val col = style.colors[i]
val name = i.name
if (!outputOnlyModified || col != ref!!.colors[i]) logText(
"colors[Col_$name]%s = Vec4(%.2f, %.2f, %.2f, %.2f)\n", " ".repeat(23 - name.length), col.x,
col.y, col.z, col.w)
}
logFinish()
}
sameLine()
withItemWidth(120f) { combo("##output_type", ::outputDest, "To Clipboard\u0000To TTY\u0000") }
sameLine()
checkbox("Only Modified Colors", ::outputOnlyModified)
text("Tip: Left-click on color square to open color picker,\nRight-click to open edit options menu.")
filter.draw("Filter colors", fontSize * 16)
radioButton("Opaque", alphaFlags == Cef.None.i) { alphaFlags = Cef.None.i }; sameLine()
radioButton("Alpha", alphaFlags == Cef.AlphaPreview.i) { alphaFlags = Cef.AlphaPreview.i }; sameLine()
radioButton("Both", alphaFlags == Cef.AlphaPreviewHalf.i) {
alphaFlags = Cef.AlphaPreviewHalf.i
}; sameLine()
helpMarker("""
In the color list:
Left-click on color square to open color picker,
Right-click to open edit options menu.""".trimIndent())
child("#colors", Vec2(), true,
Wf.AlwaysVerticalScrollbar or Wf.AlwaysHorizontalScrollbar or Wf._NavFlattened) {
withItemWidth(-160) {
for (i in 0 until Col.COUNT) {
val name = Col.values()[i].name
if (!filter.passFilter(name)) continue
withID(i) {
colorEditVec4("##color", style.colors[i], Cef.AlphaBar or alphaFlags)
if (style.colors[i] != ref!!.colors[i]) { // Tips: in a real user application, you may want to merge and use an icon font into the main font,
// so instead of "Save"/"Revert" you'd use icons!
// Read the FAQ and docs/FONTS.txt about using icon fonts. It's really easy and super convenient!
sameLine(0f, style.itemInnerSpacing.x)
if (button("Save")) ref!!.colors[i] = Vec4(style.colors[i])
sameLine(0f, style.itemInnerSpacing.x)
if (button("Revert")) style.colors[i] = Vec4(ref!!.colors[i])
}
sameLine(0f, style.itemInnerSpacing.x)
textEx(name)
}
}
}
}
endTabItem()
}
if (beginTabItem("Fonts")) {
val atlas = io.fonts
helpMarker("Read FAQ and docs/FONTS.txt for details on font loading.")
pushItemWidth(120)
for (font in atlas.fonts) {
pushID(font)
nodeFont(font)
popID()
}
treeNode("Atlas texture", "Atlas texture (${atlas.texSize.x}x${atlas.texSize.y} pixels)") {
val tintCol = Vec4(1f)
val borderCol = Vec4(1f, 1f, 1f, 0.5f)
image(atlas.texID, Vec2(atlas.texSize), Vec2(), Vec2(1), tintCol, borderCol)
}
// Post-baking font scaling. Note that this is NOT the nice way of scaling fonts, read below.
// (we enforce hard clamping manually as by default DragFloat/SliderFloat allows CTRL+Click text to get out of bounds).
val MIN_SCALE = 0.3f
val MAX_SCALE = 2f
helpMarker(
"Those are old settings provided for convenience.\n" + "However, the _correct_ way of scaling your UI is currently to reload your font at the designed size, " + "rebuild the font atlas, and call style.ScaleAllSizes() on a reference ImGuiStyle structure.\n" + "Using those settings here will give you poor quality results.")
if (dragFloat("window scale", ::windowScale, 0.005f, MIN_SCALE, MAX_SCALE, "%.2f",
SliderFlag.AlwaysClamp.i)
) // Scale only this window
setWindowFontScale(windowScale)
dragFloat("global scale", io::fontGlobalScale, 0.005f, MIN_SCALE, MAX_SCALE, "%.2f",
SliderFlag.AlwaysClamp.i) // Scale everything
popItemWidth()
endTabItem()
}
if (beginTabItem("Rendering")) {
checkbox("Anti-aliased lines", style::antiAliasedLines)
sameLine()
helpMarker(
"When disabling anti-aliasing lines, you'll probably want to disable borders in your style as well.")
checkbox("Anti-aliased lines use texture", style::antiAliasedLinesUseTex)
sameLine()
helpMarker(
"Faster lines using texture data. Require backend to render with bilinear filtering (not point/nearest filtering).")
checkbox("Anti-aliased fill", style::antiAliasedFill)
pushItemWidth(100)
dragFloat("Curve Tessellation Tolerance", style::curveTessellationTol, 0.02f, 0.1f, 10f, "%.2f")
if (style.curveTessellationTol < 10f) style.curveTessellationTol = 0.1f
// When editing the "Circle Segment Max Error" value, draw a preview of its effect on auto-tessellated circles.
dragFloat("Circle Segment Max Error", style::circleSegmentMaxError, 0.01f, 0.1f, 10f, "%.2f")
if (ImGui.isItemActive) {
setNextWindowPos(ImGui.cursorScreenPos)
tooltip {
val p = ImGui.cursorScreenPos
val drawList = ImGui.windowDrawList
val RAD_MIN = 10f
val RAD_MAX = 80f
var offX = 10f
for (n in 0..6) {
val rad = RAD_MIN + (RAD_MAX - RAD_MIN) * n.f / (7f - 1f)
drawList.addCircle(Vec2(p.x + offX + rad, p.y + RAD_MAX), rad, Col.Text.u32, 0)
offX += 10f + rad * 2f
}
ImGui.dummy(Vec2(offX, RAD_MAX * 2f))
}
}
ImGui.sameLine()
helpMarker(
"When drawing circle primitives with \"num_segments == 0\" tesselation will be calculated automatically.")
/* Not exposing zero here so user doesn't "lose" the UI (zero alpha clips all widgets).
But application code could have a toggle to switch between zero and non-zero. */
dragFloat("Global Alpha", style::alpha, 0.005f, 0.2f, 1f, "%.2f")
popItemWidth()
endTabItem()
}
endTabBar()
}
popItemWidth()
}
fun nodeFont(font: Font) {
val name = font.configData.getOrNull(0)?.name ?: ""
val fontDetailsOpened = treeNode(font,
"Font \\\"$name\\\"\\n%.2f px, %.2f px, ${font.glyphs.size} glyphs, ${font.configDataCount} file(s)",
font.fontSize)
sameLine(); smallButton("Set as default") { io.fontDefault = font }
if (fontDetailsOpened) {
pushFont(font)
text("The quick brown fox jumps over the lazy dog")
popFont()
dragFloat("Font scale", font::scale, 0.005f, 0.3f, 2f, "%.1f")
sameLine()
helpMarker("""
|Note than the default embedded font is NOT meant to be scaled.
|
|Font are currently rendered into bitmaps at a given size at the time of building the atlas. You may oversample them to get some flexibility with scaling. You can also render at multiple sizes and select which one to use at runtime.
|
|(Glimmer of hope: the atlas system should hopefully be rewritten in the future to make scaling more natural and automatic.)""".trimMargin())
text("Ascent: ${font.ascent}, Descent: ${font.descent}, Height: ${font.ascent - font.descent}")
text("Fallback character: '${font.fallbackChar}' (U+%04X)", font.fallbackChar)
text("Ellipsis character: '${font.ellipsisChar}' (U+%04X)", font.ellipsisChar)
val side = sqrt(font.metricsTotalSurface.f).i
text("Texture Area: about ${font.metricsTotalSurface} px ~${side}x$side px")
for (c in 0 until font.configDataCount) font.configData.getOrNull(c)?.let {
bulletText(
"Input $c: '${it.name}', Oversample: ${it.oversample}, PixelSnapH: ${it.pixelSnapH}, Offset: (%.1f,%.1f)",
it.glyphOffset.x, it.glyphOffset.y)
}
treeNode("Glyphs",
"Glyphs (${font.glyphs.size})") { // Display all glyphs of the fonts in separate pages of 256 characters
var base = 0
while (base <= UNICODE_CODEPOINT_MAX) {
// Skip ahead if a large bunch of glyphs are not present in the font (test in chunks of 4k)
// This is only a small optimization to reduce the number of iterations when IM_UNICODE_MAX_CODEPOINT
// is large // (if ImWchar==ImWchar32 we will do at least about 272 queries here)
if (base hasnt 4095 && font.isGlyphRangeUnused(base, base + 4095)) {
base += 4096 - 256
base += 256
continue
}
val count = (0 until 256).count { font.findGlyphNoFallback(base + it) != null }
val s = if (count > 1) "glyphs" else "glyph"
if (count > 0 && treeNode(Integer.valueOf(base), "U+%04X..U+%04X ($count $s)", base, base + 255)) {
val cellSize = font.fontSize * 1
val cellSpacing = style.itemSpacing.y
val basePos = Vec2(cursorScreenPos)
val drawList = windowDrawList
for (n in 0 until 256) {
val cellP1 = Vec2(basePos.x + (n % 16) * (cellSize + cellSpacing),
basePos.y + (n / 16) * (cellSize + cellSpacing))
val cellP2 = Vec2(cellP1.x + cellSize, cellP1.y + cellSize)
val glyph = font.findGlyphNoFallback((base + n).c)
drawList.addRect(cellP1, cellP2, COL32(255, 255, 255,
if (glyph != null) 100 else 50)) // We use ImFont::RenderChar as a shortcut because we don't have UTF-8 conversion functions
// available here and thus cannot easily generate a zero-terminated UTF-8 encoded string.
if (glyph != null) {
font.renderChar(drawList, cellSize, cellP1, Col.Text.u32, (base + n).c)
if (isMouseHoveringRect(cellP1, cellP2)) tooltip {
text("Codepoint: U+%04X", base + n)
separator()
if (DEBUG) text("Visible: ${glyph.visible}")
else text("Visible: ${glyph.visible.i}")
text("AdvanceX+1: %.1f", glyph.advanceX)
text("Pos: (%.2f,%.2f)->(%.2f,%.2f)", glyph.x0, glyph.y0, glyph.x1, glyph.y1)
text("UV: (%.3f,%.3f)->(%.3f,%.3f)", glyph.u0, glyph.v0, glyph.u1, glyph.v1)
}
}
}
dummy(Vec2((cellSize + cellSpacing) * 16, (cellSize + cellSpacing) * 16))
treePop()
}
base += 256
}
}
treePop()
}
}
} | mit | 86b0154ed871b9c26490f43213b2a217 | 49.100737 | 343 | 0.547278 | 4.559481 | false | false | false | false |
dbrant/apps-android-wikipedia | app/src/main/java/org/wikipedia/readinglist/MoveToReadingListDialog.kt | 1 | 3690 | package org.wikipedia.readinglist
import android.content.DialogInterface
import android.os.Bundle
import android.os.Parcelable
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.core.os.bundleOf
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers
import io.reactivex.rxjava3.core.Observable
import io.reactivex.rxjava3.schedulers.Schedulers
import org.wikipedia.Constants
import org.wikipedia.Constants.InvokeSource
import org.wikipedia.R
import org.wikipedia.analytics.ReadingListsFunnel
import org.wikipedia.page.PageTitle
import org.wikipedia.readinglist.database.ReadingList
import org.wikipedia.readinglist.database.ReadingListDbHelper
import org.wikipedia.util.log.L
import java.util.*
class MoveToReadingListDialog : AddToReadingListDialog() {
private var sourceReadingList: ReadingList? = null
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View {
val parentView = super.onCreateView(inflater, container, savedInstanceState)
parentView.findViewById<TextView>(R.id.dialog_title).setText(R.string.reading_list_move_to)
val sourceReadingListId = requireArguments().getLong(SOURCE_READING_LIST_ID)
sourceReadingList = ReadingListDbHelper.getListById(sourceReadingListId, false)
if (sourceReadingList == null) {
dismiss()
}
return parentView
}
override fun logClick(savedInstanceState: Bundle?) {
if (savedInstanceState == null) {
ReadingListsFunnel().logMoveClick(invokeSource)
}
}
override fun commitChanges(readingList: ReadingList, titles: List<PageTitle>) {
disposables.add(Observable.fromCallable { ReadingListDbHelper.movePagesToListAndDeleteSourcePages(sourceReadingList!!, readingList, titles) }
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe({ movedTitlesList ->
ReadingListsFunnel().logMoveToList(readingList, readingLists.size, invokeSource)
showViewListSnackBar(readingList, if (movedTitlesList.size == 1) getString(R.string.reading_list_article_moved_to_named, movedTitlesList[0], readingList.title) else getString(R.string.reading_list_articles_moved_to_named, movedTitlesList.size, readingList.title))
dismiss()
}) { obj -> L.w(obj) })
}
companion object {
private const val SOURCE_READING_LIST_ID = "sourceReadingListId"
@JvmStatic
fun newInstance(sourceReadingListId: Long,
title: PageTitle,
source: InvokeSource): MoveToReadingListDialog {
return newInstance(sourceReadingListId, listOf(title), source, true, null)
}
@JvmStatic
@JvmOverloads
fun newInstance(sourceReadingListId: Long,
titles: List<PageTitle>,
source: InvokeSource,
showDefaultList: Boolean = true,
listener: DialogInterface.OnDismissListener? = null): MoveToReadingListDialog {
return MoveToReadingListDialog().apply {
arguments = bundleOf(PAGE_TITLE_LIST to ArrayList<Parcelable>(titles),
Constants.INTENT_EXTRA_INVOKE_SOURCE to source,
SOURCE_READING_LIST_ID to sourceReadingListId,
SHOW_DEFAULT_LIST to showDefaultList)
dismissListener = listener
}
}
}
}
| apache-2.0 | 105d6fa8f4783a5733d59810eb872a4d | 44.555556 | 283 | 0.682927 | 5.182584 | false | false | false | false |
KinveyApps/Android-Starter | app/src/main/java/com/kinvey/bookshelf/ui/activity/BookActivity.kt | 1 | 13551 | package com.kinvey.bookshelf.ui.activity
import android.Manifest.permission
import android.app.Activity
import android.app.ProgressDialog
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.BitmapFactory
import android.net.Uri
import android.os.Bundle
import android.os.Environment
import android.provider.MediaStore.Images.ImageColumns
import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.view.View.OnClickListener
import android.widget.*
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import com.kinvey.android.Client
import com.kinvey.android.callback.AsyncDownloaderProgressListener
import com.kinvey.android.callback.AsyncUploaderProgressListener
import com.kinvey.android.callback.KinveyDeleteCallback
import com.kinvey.android.model.User
import com.kinvey.android.store.DataStore
import com.kinvey.bookshelf.App
import com.kinvey.bookshelf.Constants
import com.kinvey.bookshelf.R
import com.kinvey.bookshelf.entity.Author
import com.kinvey.bookshelf.entity.Book
import com.kinvey.java.core.KinveyClientCallback
import com.kinvey.java.core.MediaHttpDownloader
import com.kinvey.java.core.MediaHttpUploader
import com.kinvey.java.model.FileMetaData
import com.kinvey.java.store.StoreType
import kotlinx.android.synthetic.main.book.*
import timber.log.Timber
import java.io.File
import java.io.FileOutputStream
import java.io.IOException
import java.util.*
/**
* Created by Prots on 3/15/16.
*/
class BookActivity : AppCompatActivity(), OnClickListener {
private val SELECT_PHOTO = 2
private var client: Client<User>? = null
private var book = Book()
private var bookStore: DataStore<Book>? = null
private var imageMetaData: FileMetaData? = null
private var progressDialog: ProgressDialog? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.book)
setSupportActionBar(myToolbar)
client = (application as App).sharedClient
image?.isEnabled = false
save?.setOnClickListener(this)
uploadToInternetBtn?.setOnClickListener(this)
removeBtn?.setOnClickListener(this)
selectImageBtn?.setOnClickListener(this)
bookStore = DataStore.collection(Constants.COLLECTION_NAME, Book::class.java, StoreType.SYNC, client)
verifyStoragePermissions(this)
val storeTypes = ArrayList<StoreType>()
storeTypes.add(StoreType.SYNC)
storeTypes.add(StoreType.CACHE)
storeTypes.add(StoreType.NETWORK)
val spinnerArrayAdapter = ArrayAdapter(this, android.R.layout.simple_spinner_dropdown_item, storeTypes)
storyTypeSpinner?.adapter = spinnerArrayAdapter
storyTypeSpinner?.setSelection(1)
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
return if (book.containsKey(Constants.ID)) {
menuInflater.inflate(R.menu.menu_book, menu)
true
} else {
false
}
}
override fun onResume() {
super.onResume()
val id: String? = intent.getStringExtra(Constants.EXTRA_ID)
findBook(id)
}
override fun onStop() {
dismissProgress()
super.onStop()
}
override fun onClick(v: View) {
when (v.id) {
R.id.save -> save()
R.id.uploadToInternetBtn -> uploadFileToNetwork()
R.id.removeBtn -> try {
remove()
} catch (e: IOException) { Timber.e(e) }
R.id.selectImageBtn -> selectImage()
}
}
private fun save() {
if (name?.text.toString().trim { it <= ' ' }.isEmpty()) {
Toast.makeText(this, R.string.toast_empty_name, Toast.LENGTH_LONG).show()
} else {
showProgress(resources.getString(R.string.progress_save))
book.name = name?.text.toString()
book.author = Author("Tolstoy", null)
bookStore?.save(book,
object : KinveyClientCallback<Book> {
override fun onSuccess(result: Book?) {
dismissProgress()
Toast.makeText(application, resources.getString(R.string.toast_save_completed), Toast.LENGTH_LONG).show()
finish()
}
override fun onFailure(error: Throwable?) {
dismissProgress()
Toast.makeText(application, resources.getString(R.string.toast_save_failed), Toast.LENGTH_LONG).show()
}
})
}
}
private fun findBook(id: String?) {
if (id != null) {
showProgress(resources.getString(R.string.progress_find))
bookStore?.find(id, object : KinveyClientCallback<Book> {
override fun onSuccess(book: Book?) {
[email protected] = book!!
name?.setText([email protected])
invalidateOptionsMenu()
dismissProgress()
try {
checkImage([email protected])
} catch (e: IOException) { Timber.e(e) }
}
override fun onFailure(throwable: Throwable?) {
dismissProgress()
Toast.makeText(application, resources.getString(R.string.toast_find_failed), Toast.LENGTH_LONG).show()
}
})
}
}
@Throws(IOException::class)
private fun remove() {
if (imageMetaData != null) {
client?.getFileStore(storyTypeSpinner?.adapter?.getItem(storyTypeSpinner?.selectedItemPosition ?: -1) as StoreType)
?.remove(imageMetaData!!, object : KinveyDeleteCallback {
override fun onSuccess(integer: Int?) {
Toast.makeText(application, R.string.toast_successful, Toast.LENGTH_SHORT).show()
setImage(null)
}
override fun onFailure(throwable: Throwable?) {
Toast.makeText(application, R.string.toast_unsuccessful, Toast.LENGTH_SHORT).show()
}
})
}
}
private fun selectImage() {
val photoPickerIntent = Intent(Intent.ACTION_PICK)
photoPickerIntent.type = Constants.TYPE_IMAGE
startActivityForResult(photoPickerIntent, SELECT_PHOTO)
}
@Throws(IOException::class)
private fun checkImage(book: Book?) {
val imageId = book?.imageId ?: return
val dirFilePath = "${Environment.getDownloadCacheDirectory()}${Constants.IMAGE_DIRECTORY}"
val outputDirectory = File(dirFilePath)
if (!outputDirectory.exists()) { outputDirectory.mkdirs() }
val filePath = "${Environment.getExternalStorageDirectory()}${Constants.IMAGE_DIRECTORY}/$imageId${Constants.IMAGE_EXTENSION}"
val outputFile = File(filePath)
if (!outputFile.exists()) { outputFile.createNewFile() }
val fos = FileOutputStream(outputFile)
val fileMetaDataForDownload = FileMetaData()
fileMetaDataForDownload.id = imageId
client?.getFileStore(storyTypeSpinner?.adapter
?.getItem(storyTypeSpinner?.selectedItemPosition ?: -1) as StoreType)
?.download(fileMetaDataForDownload, fos,
object : AsyncDownloaderProgressListener<FileMetaData> {
override fun onSuccess(metaData: FileMetaData?) {
try {
fos.write(outputFile.absolutePath.toByteArray())
setImage(outputFile)
imageMetaData = metaData
Toast.makeText(application, R.string.toast_successful, Toast.LENGTH_SHORT).show()
} catch (e: IOException) { Timber.e(e) }
}
override fun onFailure(throwable: Throwable?) {
Toast.makeText(application, R.string.toast_unsuccessful, Toast.LENGTH_SHORT).show()
}
@Throws(IOException::class)
override fun progressChanged(mediaHttpDownloader: MediaHttpDownloader?) {
Timber.d("downloadFile: progressChanged")
}
override fun onCancelled() {
Toast.makeText(application, R.string.toast_download_canceled, Toast.LENGTH_SHORT).show()
}
override var isCancelled: Boolean = false
get() = false
})
}
private fun uploadFileToNetwork() {
showProgress(resources.getString(R.string.progress_upload))
val file = File(selectedImageEditText?.text.toString())
try {
client?.getFileStore(storyTypeSpinner?.adapter
?.getItem(storyTypeSpinner?.selectedItemPosition ?: -1) as StoreType)
?.upload(file, object : AsyncUploaderProgressListener<FileMetaData> {
override fun onSuccess(metaData: FileMetaData?) {
imageMetaData = metaData
dismissProgress()
Toast.makeText(application, R.string.toast_upload_completed, Toast.LENGTH_SHORT).show()
setImage(file)
book.imageId = imageMetaData?.id
}
override fun onFailure(throwable: Throwable?) {
dismissProgress()
Toast.makeText(application, R.string.toast_upload_failed, Toast.LENGTH_SHORT).show()
}
@Throws(IOException::class)
override fun progressChanged(mediaHttpUploader: MediaHttpUploader?) {
Timber.d("uploadFileToNetwork: progressChanged")
}
override fun onCancelled() {
dismissProgress()
Toast.makeText(application, R.string.toast_upload_canceled, Toast.LENGTH_SHORT).show()
}
override var isCancelled: Boolean = false
get() = false
})
} catch (e: IOException) { Timber.e(e) }
}
private fun deleteBook() {
showProgress(resources.getString(R.string.progress_delete))
bookStore?.delete(book[Constants.ID].toString(), object : KinveyDeleteCallback {
override fun onSuccess(integer: Int?) {
dismissProgress()
Toast.makeText(application, R.string.toast_delete_completed, Toast.LENGTH_SHORT).show()
finish()
}
override fun onFailure(throwable: Throwable?) {
dismissProgress()
Toast.makeText(application, R.string.toast_delete_failed, Toast.LENGTH_SHORT).show()
}
})
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
val id = item.itemId
if (id == R.id.action_delete) { deleteBook() }
return true
}
private fun setImage(file: File?) {
image?.setImageResource(0)
if (file != null && file.exists()) {
val myBitmap = BitmapFactory.decodeFile(file.absolutePath)
image?.setImageBitmap(myBitmap)
}
}
override fun onActivityResult(requestCode: Int, resultCode: Int, imageReturnedIntent: Intent?) {
super.onActivityResult(requestCode, resultCode, imageReturnedIntent)
when (requestCode) {
SELECT_PHOTO -> if (resultCode == Activity.RESULT_OK) {
val imageUri = imageReturnedIntent?.data ?: return
selectedImageEditText?.setText(getRealPathFromURI(imageUri))
}
}
}
private fun getRealPathFromURI(contentURI: Uri): String {
val result: String
val cursor = contentResolver.query(contentURI, null, null, null, null)
if (cursor == null) {
result = contentURI.path
} else {
cursor.moveToFirst()
val idx = cursor.getColumnIndex(ImageColumns.DATA)
result = cursor.getString(idx)
cursor.close()
}
return result
}
private fun showProgress(message: String) {
if (progressDialog == null) {
progressDialog = ProgressDialog(this)
}
progressDialog?.setMessage(message)
progressDialog?.show()
}
private fun dismissProgress() {
progressDialog?.dismiss()
}
companion object {
private const val REQUEST_EXTERNAL_STORAGE = 1
private val PERMISSIONS_STORAGE = arrayOf(
permission.READ_EXTERNAL_STORAGE,
permission.WRITE_EXTERNAL_STORAGE
)
/**
* Checks if the app has permission to write to device storage
*
* If the app does not has permission then the user will be prompted to grant permissions
*
* @param activity
*/
fun verifyStoragePermissions(activity: Activity) {
// Check if we have write permission
val permission = ActivityCompat.checkSelfPermission(activity, permission.WRITE_EXTERNAL_STORAGE)
if (permission != PackageManager.PERMISSION_GRANTED) {
// We don't have permission so prompt the user
ActivityCompat.requestPermissions(activity, PERMISSIONS_STORAGE, REQUEST_EXTERNAL_STORAGE)
}
}
}
} | apache-2.0 | 3ae5a155bffbfb032117792a0f4f4916 | 39.21365 | 134 | 0.620545 | 5.002215 | false | false | false | false |
nadraliev/DsrWeatherApp | app/src/main/java/soutvoid/com/DsrWeatherApp/ui/screen/newTrigger/widgets/timeDialog/ChooseTimeDialog.kt | 1 | 5083 | package soutvoid.com.DsrWeatherApp.ui.screen.newTrigger.widgets.timeDialog
import android.app.AlertDialog
import android.app.Dialog
import android.app.DialogFragment
import android.os.Bundle
import android.support.design.widget.TextInputLayout
import android.widget.ListView
import soutvoid.com.DsrWeatherApp.R
import soutvoid.com.DsrWeatherApp.domain.triggers.condition.Condition
import soutvoid.com.DsrWeatherApp.ui.screen.newTrigger.widgets.list.SelectableListItemAdapter
import soutvoid.com.DsrWeatherApp.ui.screen.newTrigger.widgets.timeDialog.data.NotificationTime
import soutvoid.com.DsrWeatherApp.ui.util.*
class ChooseTimeDialog(): DialogFragment() {
var timeChosenListener: ((NotificationTime?) -> Unit)? = null
private lateinit var quickOptions: List<NotificationTime>
private var inputField: TextInputLayout? = null
private var unitsAdapter: SelectableListItemAdapter? = null
private var customChosen = false
private val maxDays = 5
private val maxHours = 24
constructor(conditionChosenListener: ((NotificationTime?) -> Unit)?) : this() {
this.timeChosenListener = conditionChosenListener
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
initData()
}
override fun onResume() {
super.onResume()
(dialog as? AlertDialog)?.let {
it.getButton(Dialog.BUTTON_POSITIVE).setOnClickListener {
onOkPressed()
}
}
}
private fun initData() {
quickOptions = listOf(
NotificationTime(5, 0),
NotificationTime(2, 0),
NotificationTime(1, 0),
NotificationTime(10, 1),
NotificationTime(2, 1)
)
}
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
if (!customChosen) { //показать диалог с быстрыми опциями
val items = quickOptions
.map { "${it.getNiceString(activity)} ${activity.getString(R.string.before)}" }
.plusElementFront(activity.getString(R.string.no_time))
.plusElement(activity.getString(R.string.custom))
return DialogUtils.createSimpleListDialog(
activity,
items = items,
listener = { showSecondDialog(it) }
)
} else { //показать диалог с выбором фактора
return createSecondDialog()
}
}
private fun showSecondDialog(position: Int) {
if (position == 0) { //первая опция - без времени
timeChosenListener?.invoke(null)
dismiss()
} else if(position == quickOptions.size + 1) { //выбрана опция своего времени
customChosen = true
dismiss()
show(fragmentManager, "")
} else { //выбрана одна из быстрых опций
val index = position - 1
timeChosenListener?.invoke(quickOptions[index])
dismiss()
}
}
private fun createSecondDialog(): Dialog {
val builder = AlertDialog.Builder(activity)
val view = activity.layoutInflater.inflate(R.layout.time_custom_dialog, null)
builder.setView(view)
val list = view.findViewById<ListView>(R.id.time_custom_list)
unitsAdapter = SelectableListItemAdapter(activity,
NotificationTime.Unit.values().map { "${it.getNiceString(activity)} ${activity.getString(R.string.before)}" })
list.adapter = unitsAdapter
inputField = view.findViewById<TextInputLayout>(R.id.time_custom_input_field)
builder.setPositiveButton(R.string.ok) { _, _ -> }
return builder.create()
}
private fun onOkPressed() {
ifNotNull(inputField, unitsAdapter)
{ input, adapter ->
if (input.editText?.text == null || input.editText?.text.toString() == "")
input.error = activity.getString(R.string.enter_value)
else {
val value = input.editText?.text.toString().toInt()
val unit = NotificationTime.Unit.values()[adapter.selectedPosition]
if (value > maxDays && unit == NotificationTime.Unit.days)
input.error =
"${activity.getString(R.string.max)} $maxDays ${activity.resources.getQuantityString(R.plurals.days, maxDays)}"
else if (value > maxHours && unit == NotificationTime.Unit.hours)
input.error =
"${activity.getString(R.string.max)} $maxHours ${activity.resources.getQuantityString(R.plurals.hours, maxHours)}"
else {
val notificationTime = NotificationTime(value, adapter.selectedPosition)
timeChosenListener?.invoke(notificationTime)
dismiss()
}
}
}
}
} | apache-2.0 | 23159b37dc57102512a464ddbb5aeeb4 | 36.816794 | 142 | 0.619221 | 4.739713 | false | false | false | false |
securityfirst/Umbrella_android | app/src/main/java/org/secfirst/umbrella/feature/tour/view/TourUI.kt | 1 | 1829 | package org.secfirst.umbrella.feature.tour.view
import android.graphics.Color
import android.view.Gravity
import android.widget.LinearLayout
import com.stepstone.stepper.Step
import com.stepstone.stepper.VerificationError
import org.jetbrains.anko.*
import org.secfirst.umbrella.feature.base.view.BaseController
class TourUI(private val color: Int,
private val imageSource: Int,
private val textTourSource: Int,
private val visibilityImage: Int,
private val visibilityWebView: Int) : AnkoComponent<BaseController>, Step {
override fun createView(ui: AnkoContext<BaseController>) = ui.apply {
verticalLayout {
backgroundColorResource = color
verticalLayout {
imageView(imageSource).lparams(width = wrapContent, height = dip(400)) {
gravity = Gravity.CENTER
topMargin = dip(20)
}
visibility = visibilityImage
}
textView {
textResource = textTourSource
textSize = 24f
textColor = Color.WHITE
gravity = Gravity.CENTER
padding = dip(20)
}.lparams { gravity = Gravity.CENTER }
val params = LinearLayout.LayoutParams(wrapContent, wrapContent)
params.bottomMargin = dip(70)
params.leftMargin = dip(10)
params.rightMargin = dip(10)
webView {
loadUrl("file:///android_asset/terms.html")
visibility = visibilityWebView
bottomPadding = dip(20)
}.lparams(params)
}
}.view
override fun onSelected() {}
override fun verifyStep(): Nothing? = null
override fun onError(error: VerificationError) {}
} | gpl-3.0 | 344df5d4206f89dfa3071124d3725c9c | 31.678571 | 88 | 0.601968 | 5.31686 | false | false | false | false |
google/intellij-community | python/src/com/jetbrains/PySymbolFieldWithBrowseButton.kt | 3 | 8956 | // Copyright 2000-2017 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
import com.intellij.codeInsight.completion.CompletionResultSet
import com.intellij.codeInsight.lookup.LookupElement
import com.intellij.codeInsight.lookup.LookupElementBuilder
import com.intellij.ide.util.TreeChooser
import com.intellij.ide.util.gotoByName.GotoSymbolModel2
import com.intellij.navigation.NavigationItem
import com.intellij.openapi.project.DumbAware
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.ComponentWithBrowseButton
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.psi.PsiDirectory
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFileSystemItem
import com.intellij.psi.PsiNamedElement
import com.intellij.psi.search.GlobalSearchScope
import com.intellij.psi.util.QualifiedName
import com.intellij.ui.TextAccessor
import com.intellij.util.ProcessingContext
import com.intellij.util.Processor
import com.intellij.util.TextFieldCompletionProvider
import com.intellij.util.indexing.DumbModeAccessType
import com.intellij.util.indexing.FindSymbolParameters
import com.intellij.util.indexing.IdFilter
import com.intellij.util.textCompletion.TextFieldWithCompletion
import com.jetbrains.extensions.ContextAnchor
import com.jetbrains.extensions.QNameResolveContext
import com.jetbrains.extensions.getQName
import com.jetbrains.extensions.python.toPsi
import com.jetbrains.extensions.resolveToElement
import com.jetbrains.python.PyBundle
import com.jetbrains.python.PyGotoSymbolContributor
import com.jetbrains.python.PyNames
import com.jetbrains.python.PyTreeChooserDialog
import com.jetbrains.python.psi.PyFile
import com.jetbrains.python.psi.PyQualifiedNameOwner
import com.jetbrains.python.psi.PyTypedElement
import com.jetbrains.python.psi.PyUtil
import com.jetbrains.python.psi.stubs.PyClassNameIndex
import com.jetbrains.python.psi.stubs.PyFunctionNameIndex
import com.jetbrains.python.psi.types.PyModuleType
import com.jetbrains.python.psi.types.PyType
import com.jetbrains.python.psi.types.TypeEvalContext
/**
* Python module is file or package with init.py.
* Only source based packages are supported.
* [PySymbolFieldWithBrowseButton] use this function to get list of root names
*/
fun isPythonModule(element: PsiElement): Boolean = element is PyFile || (element as? PsiDirectory)?.let {
it.findFile(PyNames.INIT_DOT_PY) != null
} ?: false
/**
* Text field to enter python symbols and browse button (from [PyGotoSymbolContributor]).
* Supports auto-completion for symbol fully qualified names inside of textbox
* @param filter lambda to filter symbols
* @param startFromDirectory symbols resolved against module, but may additionally be resolved against this folder if provided like in [QNameResolveContext.folderToStart]
*
*/
class PySymbolFieldWithBrowseButton(contextAnchor: ContextAnchor,
filter: ((PsiElement) -> Boolean)? = null,
startFromDirectory: (() -> VirtualFile)? = null) : TextAccessor, ComponentWithBrowseButton<TextFieldWithCompletion>(
TextFieldWithCompletion(contextAnchor.project, PyNameCompletionProvider(contextAnchor, filter, startFromDirectory), "", true, true, true),
null) {
init {
addActionListener {
val dialog = PySymbolChooserDialog(contextAnchor.project, contextAnchor.scope, filter)
dialog.showDialog()
val element = dialog.selected
if (element is PyQualifiedNameOwner) {
childComponent.setText(element.qualifiedName)
}
if (element is PyFile) {
childComponent.setText(element.getQName()?.toString())
}
}
}
override fun setText(text: String?) {
childComponent.setText(text)
}
override fun getText(): String = childComponent.text
}
private fun PyType.getVariants(element: PsiElement): Array<LookupElement> =
this.getCompletionVariants("", element, ProcessingContext()).filterIsInstance(LookupElement::class.java).toTypedArray()
private class PyNameCompletionProvider(private val contextAnchor: ContextAnchor,
private val filter: ((PsiElement) -> Boolean)?,
private val startFromDirectory: (() -> VirtualFile)? = null) : TextFieldCompletionProvider(), DumbAware {
override fun addCompletionVariants(text: String, offset: Int, prefix: String, result: CompletionResultSet) {
val lookups: Array<LookupElement>
var name: QualifiedName? = null
if ('.' !in text) {
lookups = contextAnchor.getRoots()
.map { rootFolder -> rootFolder.children.map { it.toPsi(contextAnchor.project) } }
.flatten()
.filterNotNull()
.filter { isPythonModule(it) }
.map { LookupElementBuilder.create(it, it.virtualFile.nameWithoutExtension) }
.distinctBy { it.lookupString }
.toTypedArray()
}
else {
val evalContext = TypeEvalContext.userInitiated(contextAnchor.project, null)
name = QualifiedName.fromDottedString(text)
val resolveContext = QNameResolveContext(contextAnchor, evalContext = evalContext, allowInaccurateResult = false,
folderToStart = startFromDirectory?.invoke())
var element = name.resolveToElement(resolveContext, stopOnFirstFail = true)
if (element == null && name.componentCount > 1) {
name = name.removeLastComponent()
element = name.resolveToElement(resolveContext, stopOnFirstFail = true)
}
if (element == null) {
return
}
lookups = when (element) {
is PyFile -> PyModuleType(element).getVariants(element)
is PsiDirectory -> {
val init = PyUtil.turnDirIntoInit(element) as? PyFile ?: return
PyModuleType(init).getVariants(element) +
element.children.filterIsInstance(PsiFileSystemItem::class.java)
// For package we need all symbols in initpy and all filesystem children of this folder except initpy itself
.filterNot { it.name == PyNames.INIT_DOT_PY }
.map { LookupElementBuilder.create(it, it.virtualFile.nameWithoutExtension) }
}
is PyTypedElement -> {
evalContext.getType(element)?.getVariants(element) ?: return
}
else -> return
}
}
result.addAllElements(lookups
.filter { it.psiElement != null }
.filter { filter?.invoke(it.psiElement!!) ?: true }
.map { if (name != null) LookupElementBuilder.create("$name.${it.lookupString}") else it })
}
}
private class PySymbolChooserDialog(project: Project, scope: GlobalSearchScope, private val filter: ((PsiElement) -> Boolean)?)
: PyTreeChooserDialog<PsiNamedElement>(PyBundle.message("python.symbol.chooser.dialog.title"), PsiNamedElement::class.java,
project,
scope,
TreeChooser.Filter { filter?.invoke(it) ?: true }, null) {
override fun findElements(name: String, searchScope: GlobalSearchScope): Collection<PsiNamedElement> {
return PyClassNameIndex.find(name, project, searchScope) + PyFunctionNameIndex.find(name, project, searchScope)
}
override fun createChooseByNameModel() = GotoSymbolModel2(project, arrayOf(object : PyGotoSymbolContributor(), DumbAware {
override fun getNames(project: Project?, includeNonProjectItems: Boolean): Array<String> {
return DumbModeAccessType.RELIABLE_DATA_ONLY.ignoreDumbMode<Array<String>, RuntimeException> {
super.getNames(project, includeNonProjectItems)
}
}
override fun getItemsByName(name: String?,
pattern: String?,
project: Project?,
includeNonProjectItems: Boolean): Array<NavigationItem> {
return DumbModeAccessType.RELIABLE_DATA_ONLY.ignoreDumbMode<Array<NavigationItem>, RuntimeException> {
super.getItemsByName(name, pattern, project, includeNonProjectItems)
}
}
override fun processNames(processor: Processor<in String>, scope: GlobalSearchScope, filter: IdFilter?) {
DumbModeAccessType.RELIABLE_DATA_ONLY.ignoreDumbMode {
super.processNames(processor, scope, filter)
}
}
override fun processElementsWithName(name: String, processor: Processor<in NavigationItem>, parameters: FindSymbolParameters) {
DumbModeAccessType.RELIABLE_DATA_ONLY.ignoreDumbMode {
super.processElementsWithName(name, processor, parameters)
}
}
override fun getQualifiedName(item: NavigationItem): String? {
return DumbModeAccessType.RELIABLE_DATA_ONLY.ignoreDumbMode<String?, RuntimeException> {
super.getQualifiedName(item)
}
}
}))
}
| apache-2.0 | 2a80ecb3d23dd525f51555dc2a39f411 | 45.645833 | 170 | 0.715163 | 4.942605 | false | false | false | false |
RuneSuite/client | updater-mapper/src/main/java/org/runestar/client/updater/mapper/std/classes/AnimFrameset.kt | 1 | 1282 | package org.runestar.client.updater.mapper.std.classes
import org.objectweb.asm.Type.BOOLEAN_TYPE
import org.runestar.client.updater.mapper.IdentityMapper
import org.runestar.client.updater.mapper.DependsOn
import org.runestar.client.updater.mapper.MethodParameters
import org.runestar.client.updater.mapper.and
import org.runestar.client.updater.mapper.predicateOf
import org.runestar.client.updater.mapper.withDimensions
import org.runestar.client.updater.mapper.Class2
import org.runestar.client.updater.mapper.Field2
import org.runestar.client.updater.mapper.Method2
@DependsOn(DualNode::class, AnimFrame::class)
class AnimFrameset : IdentityMapper.Class() {
override val predicate = predicateOf<Class2> { it.superType == type<DualNode>() }
.and { it.instanceFields.size == 1 }
.and { it.instanceFields.any { it.type == type<AnimFrame>().withDimensions(1) } }
@DependsOn(AnimFrame::class)
class frames : IdentityMapper.InstanceField() {
override val predicate = predicateOf<Field2> { it.type == type<AnimFrame>().withDimensions(1) }
}
@MethodParameters("frame")
class hasAlphaTransform : IdentityMapper.InstanceMethod() {
override val predicate = predicateOf<Method2> { it.returnType == BOOLEAN_TYPE }
}
} | mit | b71a66e262d0e5095b9845c017c1abcd | 41.766667 | 103 | 0.75585 | 4.095847 | false | false | false | false |
JetBrains/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/SplitIfIntention.kt | 1 | 5219 | // 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.openapi.util.TextRange
import com.intellij.psi.util.PsiTreeUtil
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.codeinsight.api.classic.intentions.SelfTargetingIntention
import org.jetbrains.kotlin.idea.util.CommentSaver
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.PsiChildRange
import org.jetbrains.kotlin.psi.psiUtil.getNonStrictParentOfType
import org.jetbrains.kotlin.psi.psiUtil.lastBlockStatementOrThis
import org.jetbrains.kotlin.psi.psiUtil.startOffset
class SplitIfIntention : SelfTargetingIntention<KtExpression>(KtExpression::class.java, KotlinBundle.lazyMessage("split.if.into.two")) {
override fun isApplicableTo(element: KtExpression, caretOffset: Int): Boolean {
return when (element) {
is KtOperationReferenceExpression -> isOperatorValid(element)
is KtIfExpression -> getFirstValidOperator(element) != null && element.ifKeyword.textRange.containsOffset(caretOffset)
else -> false
}
}
override fun applyTo(element: KtExpression, editor: Editor?) {
val operator = when (element) {
is KtIfExpression -> getFirstValidOperator(element)!!
else -> element as KtOperationReferenceExpression
}
val ifExpression = operator.getNonStrictParentOfType<KtIfExpression>()
val commentSaver = CommentSaver(ifExpression!!)
val expression = operator.parent as KtBinaryExpression
val rightExpression = KtPsiUtil.safeDeparenthesize(getRight(expression, ifExpression.condition!!, commentSaver))
val leftExpression = KtPsiUtil.safeDeparenthesize(expression.left!!)
val thenBranch = ifExpression.then!!
val elseBranch = ifExpression.`else`
val psiFactory = KtPsiFactory(element.project)
val innerIf = psiFactory.createIf(rightExpression, thenBranch, elseBranch)
val newIf = when (operator.getReferencedNameElementType()) {
KtTokens.ANDAND -> psiFactory.createIf(leftExpression, psiFactory.createSingleStatementBlock(innerIf), elseBranch)
KtTokens.OROR -> {
val container = ifExpression.parent
// special case
if (container is KtBlockExpression && elseBranch == null && thenBranch.lastBlockStatementOrThis().isExitStatement()) {
val secondIf = container.addAfter(innerIf, ifExpression)
container.addAfter(psiFactory.createNewLine(), ifExpression)
val firstIf = ifExpression.replace(psiFactory.createIf(leftExpression, thenBranch))
commentSaver.restore(PsiChildRange(firstIf, secondIf))
return
} else {
psiFactory.createIf(leftExpression, thenBranch, innerIf)
}
}
else -> throw IllegalArgumentException()
}
val result = ifExpression.replace(newIf)
commentSaver.restore(result)
}
private fun getRight(element: KtBinaryExpression, condition: KtExpression, commentSaver: CommentSaver): KtExpression {
//gets the textOffset of the right side of the JetBinaryExpression in context to condition
val conditionRange = condition.textRange
val startOffset = element.right!!.startOffset - conditionRange.startOffset
val endOffset = conditionRange.length
val rightString = condition.text.substring(startOffset, endOffset)
val expression = KtPsiFactory(element.project).createExpression(rightString)
commentSaver.elementCreatedByText(expression, condition, TextRange(startOffset, endOffset))
return expression
}
private fun getFirstValidOperator(element: KtIfExpression): KtOperationReferenceExpression? {
val condition = element.condition ?: return null
return PsiTreeUtil.findChildrenOfType(condition, KtOperationReferenceExpression::class.java)
.firstOrNull { isOperatorValid(it) }
}
private fun isOperatorValid(element: KtOperationReferenceExpression): Boolean {
val operator = element.getReferencedNameElementType()
if (operator != KtTokens.ANDAND && operator != KtTokens.OROR) return false
var expression = element.parent as? KtBinaryExpression ?: return false
if (expression.right == null || expression.left == null) return false
while (true) {
expression = expression.parent as? KtBinaryExpression ?: break
if (expression.operationToken != operator) return false
}
val ifExpression = expression.parent.parent as? KtIfExpression ?: return false
if (ifExpression.condition == null) return false
if (!PsiTreeUtil.isAncestor(ifExpression.condition, element, false)) return false
if (ifExpression.then == null) return false
return true
}
}
| apache-2.0 | 4ee400d564cc95dab0fc9212abe8a214 | 45.185841 | 158 | 0.709331 | 5.581818 | false | false | false | false |
google/iosched | model/src/main/java/com/google/samples/apps/iosched/model/userdata/UserEvent.kt | 3 | 7847 | /*
* Copyright 2018 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.samples.apps.iosched.model.userdata
import com.google.samples.apps.iosched.model.SessionId
import com.google.samples.apps.iosched.model.reservations.ReservationRequest
import com.google.samples.apps.iosched.model.reservations.ReservationRequest.ReservationRequestEntityAction.CANCEL_REQUESTED
import com.google.samples.apps.iosched.model.reservations.ReservationRequest.ReservationRequestEntityAction.RESERVE_REQUESTED
import com.google.samples.apps.iosched.model.reservations.ReservationRequestResult
import com.google.samples.apps.iosched.model.reservations.ReservationRequestResult.ReservationRequestStatus.CANCEL_DENIED_CUTOFF
import com.google.samples.apps.iosched.model.reservations.ReservationRequestResult.ReservationRequestStatus.CANCEL_DENIED_UNKNOWN
import com.google.samples.apps.iosched.model.reservations.ReservationRequestResult.ReservationRequestStatus.CANCEL_SUCCEEDED
import com.google.samples.apps.iosched.model.reservations.ReservationRequestResult.ReservationRequestStatus.RESERVE_DENIED_CLASH
import com.google.samples.apps.iosched.model.reservations.ReservationRequestResult.ReservationRequestStatus.RESERVE_DENIED_CUTOFF
import com.google.samples.apps.iosched.model.reservations.ReservationRequestResult.ReservationRequestStatus.RESERVE_DENIED_UNKNOWN
import com.google.samples.apps.iosched.model.reservations.ReservationRequestResult.ReservationRequestStatus.RESERVE_SUCCEEDED
import com.google.samples.apps.iosched.model.reservations.ReservationRequestResult.ReservationRequestStatus.RESERVE_WAITLISTED
import com.google.samples.apps.iosched.model.reservations.ReservationRequestResult.ReservationRequestStatus.SWAP_DENIED_CLASH
import com.google.samples.apps.iosched.model.reservations.ReservationRequestResult.ReservationRequestStatus.SWAP_DENIED_CUTOFF
import com.google.samples.apps.iosched.model.reservations.ReservationRequestResult.ReservationRequestStatus.SWAP_DENIED_UNKNOWN
import com.google.samples.apps.iosched.model.reservations.ReservationRequestResult.ReservationRequestStatus.SWAP_SUCCEEDED
import com.google.samples.apps.iosched.model.reservations.ReservationRequestResult.ReservationRequestStatus.SWAP_WAITLISTED
/**
* Data for a user's personalized event stored in a Firestore document.
*/
data class UserEvent(
/**
* The unique ID for the event.
*/
val id: SessionId,
/** Tracks whether the user has starred the event. */
val isStarred: Boolean = false,
/** Tracks whether the user has provided feedback for the event. */
val isReviewed: Boolean = false,
/** Source of truth of the state of a reservation */
private val reservationStatus: ReservationStatus? = null,
/** Stores the result of a reservation request for the event. */
private val reservationRequestResult: ReservationRequestResult? = null,
/** Stores the user's latest reservation action */
private val reservationRequest: ReservationRequest? = null
) {
fun isStarredOrReserved(): Boolean {
return isStarred || isReserved() || isWaitlisted()
}
/**
* An request is pending if the result has a saved request with a different ID than the
* latest request made by the user.
*/
private fun isPending(): Boolean {
// Request but no result = pending
if (reservationRequest != null && reservationRequestResult == null) return true
// If request and result exist they need to have different IDs to be pending.
return reservationRequest != null &&
reservationRequest.requestId != reservationRequestResult?.requestId
}
fun isReserved(): Boolean {
return reservationStatus == ReservationStatus.RESERVED
}
fun isWaitlisted(): Boolean {
return reservationStatus == ReservationStatus.WAITLISTED
}
fun getReservationRequestResultId(): String? {
return reservationRequestResult?.requestId
}
fun isDifferentRequestResult(otherId: String?): Boolean {
return reservationRequestResult?.requestId != otherId
}
fun isReservedAndPendingCancel(): Boolean {
return isReserved() && isCancelPending()
}
fun isWaitlistedAndPendingCancel(): Boolean {
return isWaitlisted() && isCancelPending()
}
fun hasRequestResultError(): Boolean {
return requestResultError() != null
}
fun requestResultError(): ReservationRequestResult.ReservationRequestStatus? {
// The request result is garbage if there's a pending request
if (isPending()) return null
return when (reservationRequestResult?.requestResult) {
null -> null // If there's no request result, there's no error
RESERVE_SUCCEEDED -> null
RESERVE_WAITLISTED -> null
CANCEL_SUCCEEDED -> null
SWAP_SUCCEEDED -> null
SWAP_WAITLISTED -> null
else -> reservationRequestResult.requestResult
}
}
fun isRequestResultErrorReserveDeniedCutoff(): Boolean {
val e = requestResultError()
return e == RESERVE_DENIED_CUTOFF || e == SWAP_DENIED_CUTOFF
}
fun isRequestResultErrorReserveDeniedClash(): Boolean {
val e = requestResultError()
return e == RESERVE_DENIED_CLASH || e == SWAP_DENIED_CLASH
}
fun isRequestResultErrorReserveDeniedUnknown(): Boolean {
val e = requestResultError()
return e == RESERVE_DENIED_UNKNOWN || e == SWAP_DENIED_UNKNOWN
}
fun isRequestResultErrorCancelDeniedCutoff(): Boolean {
val e = requestResultError()
return e == CANCEL_DENIED_CUTOFF || e == SWAP_DENIED_CUTOFF
}
fun isRequestResultErrorCancelDeniedUnknown(): Boolean {
return requestResultError() == CANCEL_DENIED_UNKNOWN
}
fun isReservationPending(): Boolean {
return (reservationStatus == ReservationStatus.NONE || reservationStatus == null) &&
isPending() &&
reservationRequest?.action == RESERVE_REQUESTED
}
fun isCancelPending(): Boolean {
return reservationStatus != ReservationStatus.NONE &&
isPending() &&
reservationRequest?.action == CANCEL_REQUESTED
}
fun isLastRequestResultBySwap(): Boolean {
val r = reservationRequestResult?.requestResult ?: return false
return r == SWAP_SUCCEEDED || r == SWAP_WAITLISTED || r == SWAP_DENIED_CLASH ||
r == SWAP_DENIED_CUTOFF || r == SWAP_DENIED_UNKNOWN
}
fun isPreSessionNotificationRequired(): Boolean {
return isStarred || isReserved()
}
/**
* The source of truth for a reservation status.
*/
enum class ReservationStatus {
/** The reservation was granted */
RESERVED,
/** The reservation was granted but the user was placed on a waitlist. */
WAITLISTED,
/** The reservation request was denied because it was too close to the start of the
* event. */
NONE;
companion object {
fun getIfPresent(string: String): ReservationStatus? {
return try {
valueOf(string)
} catch (e: IllegalArgumentException) {
null
}
}
}
}
}
| apache-2.0 | e5b3dd1d59f11528acc24cd8663da5fe | 39.658031 | 130 | 0.714795 | 5.291301 | false | false | false | false |
JetBrains/intellij-community | plugins/github/src/org/jetbrains/plugins/github/pullrequest/ui/timeline/GHPRTimelineItemUIUtil.kt | 1 | 3633 | // 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.timeline
import com.intellij.collaboration.ui.codereview.timeline.StatusMessageComponentFactory
import com.intellij.collaboration.ui.codereview.timeline.StatusMessageType
import com.intellij.openapi.util.text.HtmlBuilder
import com.intellij.openapi.util.text.HtmlChunk
import com.intellij.ui.scale.JBUIScale
import com.intellij.util.text.JBDateFormat
import com.intellij.util.text.nullize
import com.intellij.util.ui.JBUI
import com.intellij.util.ui.UIUtil
import net.miginfocom.layout.CC
import net.miginfocom.layout.LC
import net.miginfocom.swing.MigLayout
import org.jetbrains.annotations.Nls
import org.jetbrains.plugins.github.api.data.GHActor
import org.jetbrains.plugins.github.ui.avatars.GHAvatarIconsProvider
import org.jetbrains.plugins.github.ui.util.GHUIUtil
import org.jetbrains.plugins.github.ui.util.HtmlEditorPane
import java.util.*
import javax.swing.JComponent
import javax.swing.JLabel
import javax.swing.JPanel
object GHPRTimelineItemUIUtil {
private const val MAIN_AVATAR_SIZE = 30
private const val AVATAR_CONTENT_GAP = 14
val maxTimelineItemTextWidth: Int
get() = GHUIUtil.getPRTimelineWidth()
val maxTimelineItemWidth: Int
get() = maxTimelineItemTextWidth + JBUIScale.scale(MAIN_AVATAR_SIZE) + JBUIScale.scale(AVATAR_CONTENT_GAP)
fun createItem(avatarIconsProvider: GHAvatarIconsProvider,
actor: GHActor,
date: Date?,
content: JComponent,
actionsPanel: JComponent? = null): JComponent {
return createItem(avatarIconsProvider, actor, date, content, maxTimelineItemTextWidth, actionsPanel)
}
fun createItem(avatarIconsProvider: GHAvatarIconsProvider,
actor: GHActor,
date: Date?,
content: JComponent,
maxContentWidth: Int = maxTimelineItemTextWidth,
actionsPanel: JComponent? = null): JComponent {
val icon = avatarIconsProvider.getIcon(actor.avatarUrl.nullize(), MAIN_AVATAR_SIZE)
val iconLabel = JLabel(icon).apply {
toolTipText = actor.login
}
val titleText = HtmlBuilder()
.appendLink(actor.url, actor.getPresentableName())
.append(HtmlChunk.nbsp())
.apply {
if (date != null) {
append(JBDateFormat.getFormatter().formatPrettyDateTime(date))
}
}.toString()
val titleTextPane = HtmlEditorPane(titleText).apply {
foreground = UIUtil.getContextHelpForeground()
}
return JPanel(null).apply {
isOpaque = false
border = JBUI.Borders.empty(10, 16)
layout = MigLayout(LC()
.fillX()
.gridGap("0", "0")
.insets("0", "0", "0", "0"))
add(iconLabel, CC().spanY(2).alignY("top")
.gapRight("${JBUIScale.scale(AVATAR_CONTENT_GAP)}"))
add(titleTextPane, CC().grow().push().gapRight("push")
.maxWidth("$maxTimelineItemTextWidth"))
if (actionsPanel != null) {
add(actionsPanel, CC().gapLeft("${JBUIScale.scale(10)}"))
}
add(content, CC().push().grow().spanX(2).newline()
.gapTop("${JBUIScale.scale(4)}")
.minWidth("0").maxWidth("$maxContentWidth"))
}
}
//language=HTML
fun createDescriptionComponent(text: @Nls String, type: StatusMessageType = StatusMessageType.INFO): JComponent {
val textPane = HtmlEditorPane(text)
return StatusMessageComponentFactory.create(textPane, type)
}
} | apache-2.0 | 2105c854199fe470dd27e8cdbbd40ff6 | 36.854167 | 120 | 0.69144 | 4.485185 | false | false | false | false |
allotria/intellij-community | platform/lang-impl/src/com/intellij/model/psi/impl/Psi2SymbolReference.kt | 2 | 1527 | // Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.model.psi.impl
import com.intellij.model.Symbol
import com.intellij.model.SymbolResolveResult
import com.intellij.model.psi.PsiSymbolReference
import com.intellij.model.psi.PsiSymbolService
import com.intellij.openapi.util.TextRange
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiPolyVariantReference
import com.intellij.psi.PsiReference
internal class Psi2SymbolReference(private val psiReference: PsiReference) : PsiSymbolReference {
override fun getElement(): PsiElement = psiReference.element
override fun getRangeInElement(): TextRange = psiReference.rangeInElement
override fun resolveReference(): Collection<SymbolResolveResult> {
if (psiReference is PsiPolyVariantReference) {
return psiReference.multiResolve(false).filter {
it.element != null
}.map(PsiSymbolService.getInstance()::asSymbolResolveResult)
}
else {
val resolved: PsiElement = psiReference.resolve() ?: return emptyList()
val symbol = PsiSymbolService.getInstance().asSymbol(resolved)
return listOf(SymbolResolveResult.fromSymbol(symbol))
}
}
override fun resolvesTo(target: Symbol): Boolean {
val psi = PsiSymbolService.getInstance().extractElementFromSymbol(target)
if (psi == null) {
return super.resolvesTo(target)
}
else {
return psiReference.isReferenceTo(psi)
}
}
}
| apache-2.0 | 8604eafc3c9607757e4470cafc73acc3 | 36.243902 | 140 | 0.762934 | 4.757009 | false | false | false | false |
deadpixelsociety/roto-ld34 | core/src/com/thedeadpixelsociety/ld34/TimeKeeper.kt | 1 | 416 | package com.thedeadpixelsociety.ld34
object TimeKeeper {
val DT = .01f
val MAX_DT = 16.666f
var frameTime = 0f
get
private set
var totalTime = 0f
get
private set
var deltaTime = 0f
get
set(value) {
field = value
frameTime += value
totalTime += value
}
fun reset() {
frameTime = 0f
}
}
| mit | ee4bc521c89ad7750727c379aa3ee0ef | 16.333333 | 36 | 0.497596 | 4.244898 | false | false | false | false |
allotria/intellij-community | java/java-features-trainer/src/com/intellij/java/ift/lesson/navigation/JavaOccurrencesLesson.kt | 3 | 3586 | // 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.java.ift.lesson.navigation
import com.intellij.find.SearchTextArea
import com.intellij.java.ift.JavaLessonsBundle
import com.intellij.usageView.UsageViewBundle
import training.dsl.LessonContext
import training.dsl.LessonUtil
import training.dsl.LessonUtil.restoreIfModifiedOrMoved
import training.dsl.parseLessonSample
import training.learn.course.KLesson
import training.learn.course.LessonType
class JavaOccurrencesLesson
: KLesson("java.occurrences.lesson", JavaLessonsBundle.message("java.find.occurrences.lesson.name")) {
override val lessonType = LessonType.SINGLE_EDITOR
val sample = parseLessonSample("""
class OccurrencesDemo {
final private String DATABASE = "MyDataBase";
DataEntry myPerson;
OccurrencesDemo(String name, int age, String <select>cellphone</select>) {
myPerson = new Person(name, age, "Cellphone: " + cellphone);
}
interface DataEntry {
String getCellphone();
String getName();
}
class Person implements DataEntry {
public Person(String name, int age, String cellphone) {
this.name = name;
this.age = age;
this.cellphone = cellphone;
}
private String name;
private int age;
private String cellphone;
public String getCellphone() {
return cellphone;
}
public String getName() {
return name;
}
}
}
""".trimIndent())
override val lessonContent: LessonContext.() -> Unit = {
prepareSample(sample)
task("Find") {
text(JavaLessonsBundle.message("java.find.occurrences.invoke.find", code("cellphone"), action(it)))
triggerByUiComponentAndHighlight(false, false) { _: SearchTextArea -> true }
restoreIfModifiedOrMoved()
test { actions(it) }
}
task("FindNext") {
trigger("com.intellij.find.editorHeaderActions.NextOccurrenceAction")
text(JavaLessonsBundle.message("java.find.occurrences.find.next", LessonUtil.rawEnter(), action(it)))
restoreByUi()
test {
ideFrame {
actionButton(UsageViewBundle.message("action.next.occurrence")).click()
}
}
}
task("FindPrevious") {
trigger("com.intellij.find.editorHeaderActions.PrevOccurrenceAction")
text(JavaLessonsBundle.message("java.find.occurrences.find.previous", action("FindPrevious")))
showWarning(JavaLessonsBundle.message("java.find.occurrences.search.closed.warning", action("Find"))) {
editor.headerComponent == null
}
test {
ideFrame {
actionButton(UsageViewBundle.message("action.previous.occurrence")).click()
}
}
}
task("EditorEscape") {
text(JavaLessonsBundle.message("java.find.occurrences.close.search.tool", action(it)))
stateCheck {
editor.headerComponent == null
}
test { invokeActionViaShortcut("ESCAPE") }
}
actionTask("FindNext") {
JavaLessonsBundle.message("java.find.occurrences.find.next.in.editor", action(it))
}
actionTask("FindPrevious") {
JavaLessonsBundle.message("java.find.occurrences.find.previous.in.editor", action(it))
}
text(JavaLessonsBundle.message("java.find.occurrences.note.about.cyclic", action("FindNext"), action("FindPrevious")))
}
} | apache-2.0 | 9f7d0836ad3116f946004b5515cccd8e | 33.161905 | 140 | 0.658673 | 4.794118 | false | false | false | false |
zpao/buck | src/com/facebook/buck/multitenant/service/Deltas.kt | 1 | 15865 | /*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* 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.facebook.buck.multitenant.service
import com.facebook.buck.core.model.UnconfiguredBuildTarget
import com.facebook.buck.core.path.ForwardRelativePath
import com.facebook.buck.multitenant.cache.AppendOnlyBidirectionalCache
import com.facebook.buck.multitenant.collect.Generation
/**
* Represents a collection of changes to apply to an [Index] to reflect [BuildPackageChanges] on top
* of a [Generation].
*/
internal data class Deltas(
val buildPackageDeltas: List<BuildPackageDelta>,
val ruleDeltas: List<RuleDelta>,
val rdepsDeltas: Map<BuildTargetId, MemorySharingIntSet?>,
val includesDeltas: IncludesMapChange
) {
fun isEmpty(): Boolean = buildPackageDeltas.isEmpty() && ruleDeltas.isEmpty() && rdepsDeltas.isEmpty() && includesDeltas.isEmpty()
}
/**
* Takes a repo state defined by a [Generation] and an [IndexGenerationData] and applies
* [BuildPackageChanges] to produce the [Deltas] that could be applied incrementally to the existing
* repo state to yield a new repo state that reflects the [BuildPackageChanges]. How the new repo
* state is realized is up to the caller.
* @see Index.createIndexForGenerationWithLocalChanges
* @see IndexAppender.addCommitData
*/
internal fun determineDeltas(
generation: Generation,
changes: BuildPackageChanges,
indexGenerationData: IndexGenerationData,
buildTargetCache: AppendOnlyBidirectionalCache<UnconfiguredBuildTarget>
): Deltas {
val internalChanges = toInternalChanges(changes, buildTargetCache)
// Perform lookupBuildPackages() before processing addedBuildPackages below because
// lookupBuildPackages() performs some sanity checks on addedBuildPackages.
val (modifiedPackageInfo, removedPackageInfo) = lookupBuildPackages(generation, internalChanges,
indexGenerationData, buildTargetCache)
val ruleDeltas = mutableListOf<RuleDelta>()
val rdepsUpdates = mutableListOf<Pair<BuildTargetId, SetDelta>>()
val buildPackageDeltas = mutableListOf<BuildPackageDelta>()
internalChanges.addedBuildPackages.forEach { added ->
val ruleNames = ArrayList<String>(added.rules.size)
added.rules.forEach { rule ->
val buildTarget = rule.targetNode.buildTarget
ruleNames.add(buildTarget.name)
ruleDeltas.add(RuleDelta.Added(rule))
val add = SetDelta.Add(buildTargetCache.get(buildTarget))
rule.deps.mapTo(rdepsUpdates) { dep -> Pair(dep, add) }
}
buildPackageDeltas.add(BuildPackageDelta.Updated(added.buildFileDirectory,
ruleNames.asSequence().toBuildRuleNames()))
}
val buildTargetsOfRemovedRules = mutableListOf<UnconfiguredBuildTarget>()
removedPackageInfo.forEach { (removed, oldRuleNames) ->
buildPackageDeltas.add(BuildPackageDelta.Removed(removed))
// Record the build targets of the removed rules. We must wait until we acquire the
// read lock on the rule map to get the deps so we can record the corresponding
// RuleDelta.Removed objects.
oldRuleNames.forEach { ruleName ->
val buildTarget = BuildTargets.createBuildTargetFromParts(removed, ruleName)
buildTargetsOfRemovedRules.add(buildTarget)
}
}
val buildTargetIdsOfRemovedRules = buildTargetsOfRemovedRules.map { buildTargetCache.get(it) }
val (modifiedRulesToProcess, removedRulesToProcess) = lookupBuildRules(
generation,
indexGenerationData,
modifiedPackageInfo,
buildTargetIdsOfRemovedRules,
buildTargetCache)
removedRulesToProcess.forEach { (buildTargetId, removedRule) ->
ruleDeltas.add(RuleDelta.Removed(removedRule))
val remove = SetDelta.Remove(buildTargetId)
removedRule.deps.mapTo(rdepsUpdates) { dep -> Pair(dep, remove) }
}
modifiedRulesToProcess.forEach { (internalBuildPackage, oldRuleNames, oldRules) ->
val newRules = internalBuildPackage.rules
// Compare oldRules and newRules to see whether the build package actually changed.
// Keep track of the individual rule changes so we need not recompute them later.
val ruleChanges = diffRules(oldRules, newRules)
if (ruleChanges.isNotEmpty()) {
// Note that oldRuleNames is a persistent collection, so we want to derive
// newRuleNames from oldRuleNames so they can share as much memory as possible.
var newRuleNames = oldRuleNames
ruleChanges.forEach { ruleChange ->
when (ruleChange) {
is RuleDelta.Added -> {
val buildTarget = ruleChange.rule.targetNode.buildTarget
newRuleNames = newRuleNames.add(buildTarget.name)
val add = SetDelta.Add(buildTargetCache.get(buildTarget))
ruleChange.rule.deps.mapTo(rdepsUpdates) { dep -> Pair(dep, add) }
}
is RuleDelta.Modified -> {
// Because the rule has been modified, newRuleNames will be
// unaffected, but the rule's deps may have changed.
val buildTargetId = buildTargetCache.get(ruleChange.oldRule.targetNode.buildTarget)
diffDeps(ruleChange.oldRule.deps, ruleChange.newRule.deps, rdepsUpdates, buildTargetId)
}
is RuleDelta.Removed -> {
val buildTarget = ruleChange.rule.targetNode.buildTarget
newRuleNames = newRuleNames.remove(buildTarget.name)
val remove = SetDelta.Remove(buildTargetCache.get(buildTarget))
ruleChange.rule.deps.mapTo(rdepsUpdates) { dep -> Pair(dep, remove) }
}
}
}
buildPackageDeltas.add(BuildPackageDelta.Updated(internalBuildPackage.buildFileDirectory, newRuleNames))
ruleDeltas.addAll(ruleChanges)
}
}
val includesMapChange = processIncludes(internalChanges, generation, indexGenerationData)
return Deltas(
buildPackageDeltas = buildPackageDeltas,
ruleDeltas = ruleDeltas,
rdepsDeltas = deriveDeltas(rdepsUpdates) { key ->
indexGenerationData.withRdepsMap { it.getVersion(key, generation) }
},
includesDeltas = includesMapChange
)
}
/**
* While holding the read lock for the `buildPackageMap`, extracts the data needed by
* [determineDeltas] and nothing more so the lock is held as briefly as possible.
*/
private fun lookupBuildPackages(
generation: Generation,
internalChanges: InternalChanges,
indexGenerationData: IndexGenerationData,
buildTargetCache: AppendOnlyBidirectionalCache<UnconfiguredBuildTarget>
): BuildPackagesLookup {
// We allocate the arrays before taking the lock to reduce the number of allocations made while
// holding the lock.
val modified = ArrayList<Pair<InternalBuildPackage, BuildRuleNames>>(internalChanges.modifiedBuildPackages.size)
val removed = ArrayList<Pair<ForwardRelativePath, BuildRuleNames>>(internalChanges.removedBuildPackages.size)
indexGenerationData.withBuildPackageMap { buildPackageMap ->
// As a sanity check, make sure there are no oldRules for any of the "added" packages.
internalChanges.addedBuildPackages.forEach { added ->
val oldRuleNames = buildPackageMap.getVersion(added.buildFileDirectory, generation)
require(oldRuleNames == null) {
"Build package to add already existed at ${added.buildFileDirectory} for generation $generation"
}
}
internalChanges.modifiedBuildPackages.mapTo(modified) { modified ->
val oldRuleNames = requireNotNull(
buildPackageMap.getVersion(modified.buildFileDirectory, generation)) {
"No version found for build file in ${modified.buildFileDirectory} for generation $generation"
}
Pair(modified, oldRuleNames)
}
internalChanges.removedBuildPackages.mapTo(removed) { removed ->
val oldRuleNames = requireNotNull(buildPackageMap.getVersion(removed, generation)) {
"Build package to remove did not exist at $removed for generation $generation"
}
Pair(removed, oldRuleNames)
}
}
val modifiedWithTargetIds = modified.map { (buildPackage, buildRuleNames) ->
val buildTargetIds = buildRuleNames.asSequence().map { name ->
val buildTarget = BuildTargets.createBuildTargetFromParts(buildPackage.buildFileDirectory, name)
requireNotNull(buildTargetCache.get(buildTarget))
}.toList()
ModifiedPackageByIds(
internalBuildPackage = buildPackage,
oldRuleNames = buildRuleNames,
oldBuildTargetIds = buildTargetIds)
}
return BuildPackagesLookup(
modifiedPackageInfo = modifiedWithTargetIds,
removedPackageInfo = removed)
}
private fun lookupBuildRules(
generation: Generation,
indexGenerationData: IndexGenerationData,
modified: List<ModifiedPackageByIds>,
buildTargetIdsOfRemovedRules: List<BuildTargetId>,
buildTargetCache: AppendOnlyBidirectionalCache<UnconfiguredBuildTarget>
): BuildRuleLookup {
// Pre-allocate arrays before taking the lock.
val modifiedRulesToProcess = ArrayList<ModifiedPackageByRules>(modified.size)
val removedRulesToProcess = ArrayList<Pair<BuildTargetId, InternalRawBuildRule>>(buildTargetIdsOfRemovedRules.size)
indexGenerationData.withRuleMap { ruleMap ->
modified.mapTo(modifiedRulesToProcess) { (internalBuildPackage, oldRuleNames, oldBuildTargetIds) ->
val oldRules = oldBuildTargetIds.map { oldBuildTargetId ->
requireNotNull(ruleMap.getVersion(oldBuildTargetId, generation)) {
"Missing deps for '${buildTargetCache.getByIndex(oldBuildTargetId)}' at generation $generation"
}
}
ModifiedPackageByRules(internalBuildPackage, oldRuleNames, oldRules)
}
buildTargetIdsOfRemovedRules.mapTo(removedRulesToProcess) { buildTargetId ->
val removedRule = requireNotNull(ruleMap.getVersion(buildTargetId, generation)) {
"No rule found for '${buildTargetCache.getByIndex(buildTargetId)}' at generation $generation"
}
Pair(buildTargetId, removedRule)
}
}
return BuildRuleLookup(modifiedRulesToProcess, removedRulesToProcess)
}
/** Diff the deps between old and new and add the updates directly to the specified list. */
private fun diffDeps(
old: BuildTargetSet,
new: BuildTargetSet,
rdepsUpdates: MutableList<Pair<BuildTargetId, SetDelta>>,
buildTargetId: BuildTargetId
) {
// We exploit the fact that the ids in a BuildTargetSet are sorted.
var oldIndex = 0
var newIndex = 0
while (oldIndex < old.size && newIndex < new.size) {
val oldBuildTargetId = old[oldIndex]
val newBuildTargetId = new[newIndex]
when {
oldBuildTargetId < newBuildTargetId -> {
// oldBuildTargetId does not exist in new.
rdepsUpdates.add(Pair(oldBuildTargetId, SetDelta.Remove(buildTargetId)))
++oldIndex
}
oldBuildTargetId > newBuildTargetId -> {
// newBuildTargetId does not exist in old.
rdepsUpdates.add(Pair(newBuildTargetId, SetDelta.Add(buildTargetId)))
++newIndex
}
else /* oldBuildTargetId == newBuildTargetId */ -> {
// The buildTargetId is present in old and new, so nothing to update.
++oldIndex
++newIndex
}
}
}
// If there is anything left in old, it must have been removed in new.
while (oldIndex < old.size) {
rdepsUpdates.add(Pair(old[oldIndex++], SetDelta.Remove(buildTargetId)))
}
// If there is anything left in new, it must have been added in new.
while (newIndex < new.size) {
rdepsUpdates.add(Pair(new[newIndex++], SetDelta.Add(buildTargetId)))
}
}
private fun toInternalChanges(
changes: BuildPackageChanges,
buildTargetCache: AppendOnlyBidirectionalCache<UnconfiguredBuildTarget>
): InternalChanges =
InternalChanges(
addedBuildPackages = changes.addedBuildPackages.asSequence().map {
toInternalBuildPackage(it, buildTargetCache)
}.toList(),
modifiedBuildPackages = changes.modifiedBuildPackages.asSequence().map {
toInternalBuildPackage(it, buildTargetCache)
}.toList(),
removedBuildPackages = changes.removedBuildPackages
)
private fun toInternalBuildPackage(
buildPackage: BuildPackage,
buildTargetCache: AppendOnlyBidirectionalCache<UnconfiguredBuildTarget>
): InternalBuildPackage =
InternalBuildPackage(
buildFileDirectory = buildPackage.buildFileDirectory,
rules = buildPackage.rules.asSequence().map {
toInternalRawBuildRule(it, buildTargetCache)
}.toSet(),
includes = buildPackage.includes
)
private fun toInternalRawBuildRule(
rawBuildRule: RawBuildRule,
buildTargetCache: AppendOnlyBidirectionalCache<UnconfiguredBuildTarget>
): InternalRawBuildRule =
InternalRawBuildRule(rawBuildRule.targetNode,
toBuildTargetSet(rawBuildRule.deps, buildTargetCache))
private fun toBuildTargetSet(
targets: Set<UnconfiguredBuildTarget>,
buildTargetCache: AppendOnlyBidirectionalCache<UnconfiguredBuildTarget>
): BuildTargetSet {
val ids = targets.map { buildTargetCache.get(it) }.toIntArray()
ids.sort()
return ids
}
/*
* We create a number of simple types for shuttling data between methods. These seem easier to
* comprehend than using [Pair] and [Triple] for everything.
*/
/**
* Data extracted from using [IndexGenerationData.withBuildPackageMap].
*/
private data class BuildPackagesLookup(
val modifiedPackageInfo: List<ModifiedPackageByIds>,
val removedPackageInfo: List<Pair<ForwardRelativePath, BuildRuleNames>>
)
/**
* Data extracted from using [IndexGenerationData.withRuleMap].
*/
private data class BuildRuleLookup(
val modifiedPackages: List<ModifiedPackageByRules>,
val removedPackages: List<Pair<BuildTargetId, InternalRawBuildRule>>
)
/**
* @property internalBuildPackage that has been modified
* @property oldRuleNames names of the build rules in the old version of the package
* @property oldBuildTargetIds build target ids corresponding to [oldRuleNames]
*/
private data class ModifiedPackageByIds(
val internalBuildPackage: InternalBuildPackage,
val oldRuleNames: BuildRuleNames,
val oldBuildTargetIds: List<BuildTargetId>
)
/**
* @property internalBuildPackage that has been modified
* @property oldRuleNames names of the build rules in the old version of the package
* @property oldRules rules corresponding to [oldRuleNames]
*/
private data class ModifiedPackageByRules(
val internalBuildPackage: InternalBuildPackage,
val oldRuleNames: BuildRuleNames,
val oldRules: List<InternalRawBuildRule>
)
| apache-2.0 | 83419f57937fe2a93457025e243ae778 | 43.192201 | 134 | 0.700536 | 5.453764 | false | false | false | false |
Kotlin/kotlinx.coroutines | kotlinx-coroutines-core/jvm/test/exceptions/StackTraceRecoveryCustomExceptionsTest.kt | 1 | 4386 | /*
* Copyright 2016-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
*/
package kotlinx.coroutines.exceptions
import kotlinx.coroutines.*
import kotlinx.coroutines.channels.*
import org.junit.Test
import kotlin.test.*
@Suppress("UNREACHABLE_CODE", "UNUSED", "UNUSED_PARAMETER")
class StackTraceRecoveryCustomExceptionsTest : TestBase() {
internal class NonCopyable(val customData: Int) : Throwable() {
// Bait
public constructor(cause: Throwable) : this(42)
}
internal class Copyable(val customData: Int) : Throwable(), CopyableThrowable<Copyable> {
// Bait
public constructor(cause: Throwable) : this(42)
override fun createCopy(): Copyable {
val copy = Copyable(customData)
copy.initCause(this)
return copy
}
}
@Test
fun testStackTraceNotRecovered() = runTest {
try {
withContext(wrapperDispatcher(coroutineContext)) {
throw NonCopyable(239)
}
expectUnreached()
} catch (e: NonCopyable) {
assertEquals(239, e.customData)
assertNull(e.cause)
}
}
@Test
fun testStackTraceRecovered() = runTest {
try {
withContext(wrapperDispatcher(coroutineContext)) {
throw Copyable(239)
}
expectUnreached()
} catch (e: Copyable) {
assertEquals(239, e.customData)
val cause = e.cause
assertTrue(cause is Copyable)
assertEquals(239, cause.customData)
}
}
internal class WithDefault(message: String = "default") : Exception(message)
@Test
fun testStackTraceRecoveredWithCustomMessage() = runTest {
try {
withContext(wrapperDispatcher(coroutineContext)) {
throw WithDefault("custom")
}
expectUnreached()
} catch (e: WithDefault) {
assertEquals("custom", e.message)
val cause = e.cause
assertTrue(cause is WithDefault)
assertEquals("custom", cause.message)
}
}
class WrongMessageException(token: String) : RuntimeException("Token $token")
@Test
fun testWrongMessageException() = runTest {
val result = runCatching {
coroutineScope<Unit> {
throw WrongMessageException("OK")
}
}
val ex = result.exceptionOrNull() ?: error("Expected to fail")
assertTrue(ex is WrongMessageException)
assertEquals("Token OK", ex.message)
}
@Test
fun testWrongMessageExceptionInChannel() = runTest {
val result = produce<Unit>(SupervisorJob() + Dispatchers.Unconfined) {
throw WrongMessageException("OK")
}
val ex = runCatching {
@Suppress("ControlFlowWithEmptyBody")
for (unit in result) {
// Iterator has a special code path
}
}.exceptionOrNull() ?: error("Expected to fail")
assertTrue(ex is WrongMessageException)
assertEquals("Token OK", ex.message)
}
class CopyableWithCustomMessage(
message: String?,
cause: Throwable? = null
) : RuntimeException(message, cause),
CopyableThrowable<CopyableWithCustomMessage> {
override fun createCopy(): CopyableWithCustomMessage {
return CopyableWithCustomMessage("Recovered: [$message]", cause)
}
}
@Test
fun testCustomCopyableMessage() = runTest {
val result = runCatching {
coroutineScope<Unit> {
throw CopyableWithCustomMessage("OK")
}
}
val ex = result.exceptionOrNull() ?: error("Expected to fail")
assertTrue(ex is CopyableWithCustomMessage)
assertEquals("Recovered: [OK]", ex.message)
}
@Test
fun testTryCopyThrows() = runTest {
class FailingException : Exception(), CopyableThrowable<FailingException> {
override fun createCopy(): FailingException? {
TODO("Not yet implemented")
}
}
val e = FailingException()
val result = runCatching {
coroutineScope<Unit> {
throw e
}
}
assertSame(e, result.exceptionOrNull())
}
}
| apache-2.0 | 4a109768011dd027f7e9a3f90ff7366b | 29.248276 | 102 | 0.590515 | 5.277978 | false | true | false | false |
leafclick/intellij-community | plugins/github/src/org/jetbrains/plugins/github/pullrequest/ui/timeline/GHPRTimelineItemComponentFactory.kt | 1 | 7104 | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.plugins.github.pullrequest.ui.timeline
import com.intellij.icons.AllIcons
import com.intellij.ide.BrowserUtil
import com.intellij.ui.components.labels.LinkLabel
import com.intellij.ui.components.labels.LinkListener
import com.intellij.ui.components.panels.HorizontalBox
import com.intellij.ui.components.panels.VerticalBox
import com.intellij.util.ui.JBDimension
import com.intellij.util.ui.JBUI
import com.intellij.util.ui.UI
import com.intellij.util.ui.UIUtil
import icons.GithubIcons
import net.miginfocom.layout.CC
import net.miginfocom.layout.LC
import net.miginfocom.swing.MigLayout
import org.intellij.lang.annotations.Language
import org.jetbrains.plugins.github.api.data.*
import org.jetbrains.plugins.github.api.data.pullrequest.GHPullRequestCommit
import org.jetbrains.plugins.github.api.data.pullrequest.GHPullRequestReview
import org.jetbrains.plugins.github.api.data.pullrequest.GHPullRequestReviewState.*
import org.jetbrains.plugins.github.api.data.pullrequest.timeline.GHPRTimelineEvent
import org.jetbrains.plugins.github.api.data.pullrequest.timeline.GHPRTimelineItem
import org.jetbrains.plugins.github.pullrequest.avatars.GHAvatarIconsProvider
import org.jetbrains.plugins.github.pullrequest.comment.ui.GHPRReviewThreadComponent
import org.jetbrains.plugins.github.pullrequest.data.service.GHPRReviewServiceAdapter
import org.jetbrains.plugins.github.ui.util.HtmlEditorPane
import org.jetbrains.plugins.github.util.GithubUIUtil
import java.util.*
import javax.swing.*
import kotlin.math.ceil
import kotlin.math.floor
class GHPRTimelineItemComponentFactory(private val reviewService: GHPRReviewServiceAdapter,
private val avatarIconsProvider: GHAvatarIconsProvider,
private val reviewsThreadsModelsProvider: GHPRReviewsThreadsModelsProvider,
private val reviewDiffComponentFactory: GHPRReviewThreadDiffComponentFactory,
private val eventComponentFactory: GHPRTimelineEventComponentFactory<GHPRTimelineEvent>,
private val currentUser: GHUser) {
fun createComponent(item: GHPRTimelineItem): Item {
try {
return when (item) {
is GHPullRequestCommit -> Item(AllIcons.Vcs.CommitNode, commitTitle(item.commit))
is GHIssueComment -> createComponent(item)
is GHPullRequestReview -> createComponent(item)
is GHPRTimelineEvent -> eventComponentFactory.createComponent(item)
else -> throw IllegalStateException("Unknown item type")
}
}
catch (e: Exception) {
return Item(AllIcons.General.Warning, HtmlEditorPane("Cannot display item - ${e.message}"))
}
}
private fun createComponent(model: GHIssueComment) =
Item(userAvatar(model.author),
actionTitle(model.author, "commented", model.createdAt),
HtmlEditorPane(model.bodyHtml))
private fun createComponent(review: GHPullRequestReview): Item {
val reviewThreadsModel = reviewsThreadsModelsProvider.getReviewThreadsModel(review.id)
val reviewPanel = VerticalBox().apply {
add(Box.createRigidArea(JBDimension(0, 4)))
if (review.bodyHTML.isNotEmpty()) {
add(HtmlEditorPane(review.bodyHTML).apply {
border = JBUI.Borders.emptyBottom(12)
})
}
add(GHPRReviewThreadsPanel(reviewThreadsModel) {
GHPRReviewThreadComponent.createWithDiff(it, reviewService, reviewDiffComponentFactory, avatarIconsProvider, currentUser)
})
}
val icon = when (review.state) {
APPROVED -> GithubIcons.ReviewAccepted
CHANGES_REQUESTED -> GithubIcons.ReviewRejected
COMMENTED -> GithubIcons.Review
DISMISSED -> GithubIcons.Review
PENDING -> GithubIcons.Review
}
val actionText = when (review.state) {
APPROVED -> "approved these changes"
CHANGES_REQUESTED -> "rejected these changes"
COMMENTED, DISMISSED, PENDING -> "reviewed"
}
return Item(icon, actionTitle(avatarIconsProvider, review.author, actionText, review.createdAt), reviewPanel)
}
private fun userAvatar(user: GHActor?): JLabel {
return userAvatar(avatarIconsProvider, user)
}
private fun userAvatar(user: GHGitActor?): JLabel {
return LinkLabel<Any>("", avatarIconsProvider.getIcon(user?.avatarUrl), LinkListener { _, _ ->
user?.url?.let { BrowserUtil.browse(it) }
})
}
private fun commitTitle(commit: GHCommit): JComponent {
//language=HTML
val text = """${commit.messageHeadlineHTML} <a href='${commit.url}'>${commit.abbreviatedOid}</a>"""
return HorizontalBox().apply {
add(userAvatar(commit.author))
add(Box.createRigidArea(JBDimension(8, 0)))
add(HtmlEditorPane(text))
}
}
class Item(val marker: JLabel, title: JComponent, content: JComponent? = null) : JPanel() {
constructor(markerIcon: Icon, title: JComponent, content: JComponent? = null)
: this(createMarkerLabel(markerIcon), title, content)
init {
isOpaque = false
layout = MigLayout(LC().gridGap("0", "0")
.insets("0", "0", "0", "0")
.fill()).apply {
columnConstraints = "[]${UI.scale(8)}[]"
}
add(marker, CC().pushY())
add(title, CC().growX().pushX())
if (content != null) add(content, CC().newline().skip().grow().push())
}
companion object {
private fun createMarkerLabel(markerIcon: Icon) =
JLabel(markerIcon).apply {
val verticalGap = if (markerIcon.iconHeight < 20) (20f - markerIcon.iconHeight) / 2 else 0f
val horizontalGap = if (markerIcon.iconWidth < 20) (20f - markerIcon.iconWidth) / 2 else 0f
border = JBUI.Borders.empty(floor(verticalGap).toInt(), floor(horizontalGap).toInt(),
ceil(verticalGap).toInt(), ceil(horizontalGap).toInt())
}
}
}
companion object {
fun userAvatar(avatarIconsProvider: GHAvatarIconsProvider, user: GHActor?): JLabel {
return LinkLabel<Any>("", avatarIconsProvider.getIcon(user?.avatarUrl), LinkListener { _, _ ->
user?.url?.let { BrowserUtil.browse(it) }
})
}
fun actionTitle(avatarIconsProvider: GHAvatarIconsProvider, actor: GHActor?, @Language("HTML") actionHTML: String, date: Date)
: JComponent {
return HorizontalBox().apply {
add(userAvatar(avatarIconsProvider, actor))
add(Box.createRigidArea(JBDimension(8, 0)))
add(actionTitle(actor, actionHTML, date))
}
}
fun actionTitle(actor: GHActor?, actionHTML: String, date: Date): JComponent {
//language=HTML
val text = """<a href='${actor?.url}'>${actor?.login ?: "unknown"}</a> $actionHTML ${GithubUIUtil.formatActionDate(date)}"""
return HtmlEditorPane(text).apply {
foreground = UIUtil.getContextHelpForeground()
}
}
}
}
| apache-2.0 | 95137af06cf78c93ccd8eee69eb3c49e | 40.54386 | 140 | 0.696368 | 4.717131 | false | false | false | false |
leafclick/intellij-community | java/java-impl/src/com/intellij/java/refactoring/suggested/JavaSuggestedRefactoringAvailability.kt | 1 | 4915 | // 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.java.refactoring.suggested
import com.intellij.psi.*
import com.intellij.refactoring.suggested.*
import com.intellij.refactoring.suggested.SuggestedRefactoringSupport.Parameter
import com.intellij.refactoring.suggested.SuggestedRefactoringSupport.Signature
class JavaSuggestedRefactoringAvailability(refactoringSupport: SuggestedRefactoringSupport) :
SuggestedRefactoringAvailability(refactoringSupport)
{
// we use resolve to filter out annotations that we don't want to spread over hierarchy
override fun refineSignaturesWithResolve(state: SuggestedRefactoringState): SuggestedRefactoringState {
val declaration = state.declaration as? PsiMethod ?: return state
val restoredDeclarationCopy = state.createRestoredDeclarationCopy(refactoringSupport) as PsiMethod
val psiFile = declaration.containingFile
val oldSignature = extractAnnotationsWithResolve(state.oldSignature, restoredDeclarationCopy, psiFile)
val newSignature = extractAnnotationsWithResolve(state.newSignature, declaration, psiFile)
return state.copy(oldSignature = oldSignature, newSignature = newSignature)
}
override fun detectAvailableRefactoring(state: SuggestedRefactoringState): SuggestedRefactoringData? {
val declaration = state.declaration
val oldSignature = state.oldSignature
val newSignature = state.newSignature
if (declaration !is PsiMethod) {
return SuggestedRenameData(declaration as PsiNamedElement, oldSignature.name)
}
val updateUsagesData = SuggestedChangeSignatureData.create(state, USAGES)
if (hasParameterAddedRemovedOrReordered(oldSignature, newSignature)) return updateUsagesData
val updateOverridesData = if (declaration.canHaveOverrides(oldSignature, newSignature))
updateUsagesData.copy(
nameOfStuffToUpdate = if (declaration.hasModifierProperty(PsiModifier.ABSTRACT)) IMPLEMENTATIONS else OVERRIDES
)
else
null
val (nameChanges, renameData) = nameChanges(oldSignature, newSignature, declaration, declaration.parameterList.parameters.asList())
val methodNameChanged = oldSignature.name != newSignature.name
if (hasTypeChanges(oldSignature, newSignature) || oldSignature.visibility != newSignature.visibility) {
return if (methodNameChanged || nameChanges > 0 && declaration.body != null) updateUsagesData else updateOverridesData
}
return when {
renameData != null -> renameData
nameChanges > 0 -> if (methodNameChanged || declaration.body != null) updateUsagesData else updateOverridesData
else -> null
}
}
private fun PsiMethod.canHaveOverrides(oldSignature: Signature, newSignature: Signature): Boolean {
if (isConstructor) return false
if (oldSignature.visibility == PsiModifier.PRIVATE || newSignature.visibility == PsiModifier.PRIVATE) return false
if (hasModifierProperty(PsiModifier.STATIC) || hasModifierProperty(PsiModifier.FINAL)) return false
if ((containingClass ?: return false).hasModifierProperty(PsiModifier.FINAL)) return false
return true
}
override fun hasTypeChanges(oldSignature: Signature, newSignature: Signature): Boolean {
return super.hasTypeChanges(oldSignature, newSignature)
|| oldSignature.annotations != newSignature.annotations
|| oldSignature.exceptionTypes != newSignature.exceptionTypes
}
override fun hasParameterTypeChanges(oldParam: Parameter, newParam: Parameter): Boolean {
return super.hasParameterTypeChanges(oldParam, newParam) || oldParam.annotations != newParam.annotations
}
// Annotations were extracted without use of resolve. We must extract them again using more precise method.
private fun extractAnnotationsWithResolve(signature: Signature, declaration: PsiMethod, psiFile: PsiFile): Signature {
val psiParameters = declaration.parameterList.parameters
require(signature.parameters.size == psiParameters.size)
return Signature.create(
signature.name,
signature.type,
signature.parameters.zip(psiParameters.asList()).map { (parameter, psiParameter) ->
val annotations = extractAnnotations(psiParameter.type, psiParameter, psiFile)
parameter.copy(additionalData = JavaParameterAdditionalData(annotations))
},
JavaSignatureAdditionalData(
signature.visibility,
extractAnnotations(declaration.returnType, declaration, psiFile),
signature.exceptionTypes
)
)!!
}
private fun extractAnnotations(type: PsiType?, owner: PsiModifierListOwner, psiFile: PsiFile): String {
if (type == null) return ""
return JavaSuggestedRefactoringSupport.extractAnnotationsToCopy(type, owner, psiFile)
.joinToString(separator = " ") { it.text } //TODO: strip comments and line breaks
}
} | apache-2.0 | a2110fd74f3c8397c8adbe799189abac | 48.656566 | 140 | 0.773347 | 5.516274 | false | false | false | false |
leafclick/intellij-community | platform/diff-impl/src/com/intellij/openapi/vcs/ex/DocumentTracker.kt | 1 | 29156 | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.openapi.vcs.ex
import com.intellij.diff.comparison.ComparisonUtil
import com.intellij.diff.comparison.iterables.DiffIterable
import com.intellij.diff.comparison.iterables.FairDiffIterable
import com.intellij.diff.comparison.trimStart
import com.intellij.diff.tools.util.text.LineOffsets
import com.intellij.diff.util.DiffUtil
import com.intellij.diff.util.Range
import com.intellij.diff.util.Side
import com.intellij.openapi.Disposable
import com.intellij.openapi.application.ApplicationListener
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.editor.Document
import com.intellij.openapi.editor.event.DocumentEvent
import com.intellij.openapi.editor.event.DocumentListener
import com.intellij.openapi.util.text.StringUtil
import com.intellij.openapi.vcs.ex.DocumentTracker.Block
import com.intellij.openapi.vcs.ex.DocumentTracker.Handler
import com.intellij.util.containers.PeekableIteratorWrapper
import org.jetbrains.annotations.CalledInAwt
import java.util.concurrent.locks.ReentrantLock
import kotlin.concurrent.withLock
import kotlin.math.max
class DocumentTracker : Disposable {
private val handler: Handler
// Any external calls (ex: Document modifications) must be avoided under lock,
// do avoid deadlock with ChangeListManager
internal val LOCK: Lock = Lock()
val document1: Document
val document2: Document
private val tracker: LineTracker
private val freezeHelper: FreezeHelper = FreezeHelper()
private var isDisposed: Boolean = false
constructor(document1: Document,
document2: Document,
handler: Handler) {
assert(document1 != document2)
this.document1 = document1
this.document2 = document2
this.handler = handler
val changes = when {
document1.immutableCharSequence === document2.immutableCharSequence -> emptyList()
else -> compareLines(document1.immutableCharSequence,
document2.immutableCharSequence,
document1.lineOffsets,
document2.lineOffsets).iterateChanges().toList()
}
tracker = LineTracker(this.handler, changes)
val application = ApplicationManager.getApplication()
application.addApplicationListener(MyApplicationListener(), this)
document1.addDocumentListener(MyDocumentListener(Side.LEFT), this)
document2.addDocumentListener(MyDocumentListener(Side.RIGHT), this)
}
@CalledInAwt
override fun dispose() {
ApplicationManager.getApplication().assertIsDispatchThread()
if (isDisposed) return
isDisposed = true
LOCK.write {
tracker.destroy()
}
}
val blocks: List<Block> get() = tracker.blocks
fun <T> readLock(task: () -> T): T = LOCK.read(task)
fun <T> writeLock(task: () -> T): T = LOCK.write(task)
val isLockHeldByCurrentThread: Boolean get() = LOCK.isHeldByCurrentThread
fun isFrozen(): Boolean {
LOCK.read {
return freezeHelper.isFrozen()
}
}
fun freeze(side: Side) {
LOCK.write {
freezeHelper.freeze(side)
}
}
@CalledInAwt
fun unfreeze(side: Side) {
LOCK.write {
freezeHelper.unfreeze(side)
}
}
@CalledInAwt
inline fun doFrozen(task: () -> Unit) {
doFrozen(Side.LEFT) {
doFrozen(Side.RIGHT) {
task()
}
}
}
@CalledInAwt
inline fun doFrozen(side: Side, task: () -> Unit) {
freeze(side)
try {
task()
}
finally {
unfreeze(side)
}
}
fun getContent(side: Side): CharSequence {
LOCK.read {
val frozenContent = freezeHelper.getFrozenContent(side)
if (frozenContent != null) return frozenContent
return side[document1, document2].immutableCharSequence
}
}
@CalledInAwt
fun refreshDirty(fastRefresh: Boolean, forceInFrozen: Boolean = false) {
if (isDisposed) return
if (!forceInFrozen && freezeHelper.isFrozen()) return
LOCK.write {
if (tracker.isDirty &&
blocks.isNotEmpty() &&
StringUtil.equals(document1.immutableCharSequence, document2.immutableCharSequence)) {
tracker.setRanges(emptyList(), false)
return
}
tracker.refreshDirty(document1.immutableCharSequence,
document2.immutableCharSequence,
document1.lineOffsets,
document2.lineOffsets,
fastRefresh)
}
}
private fun unfreeze(side: Side, oldText: CharSequence) {
assert(LOCK.isHeldByCurrentThread)
if (isDisposed) return
val newText = side[document1, document2]
val iterable = compareLines(oldText, newText.immutableCharSequence, oldText.lineOffsets, newText.lineOffsets)
if (iterable.changes().hasNext()) {
tracker.rangesChanged(side, iterable)
}
}
fun updateFrozenContentIfNeeded() {
// ensure blocks are up to date
updateFrozenContentIfNeeded(Side.LEFT)
updateFrozenContentIfNeeded(Side.RIGHT)
refreshDirty(fastRefresh = false, forceInFrozen = true)
}
private fun updateFrozenContentIfNeeded(side: Side) {
assert(LOCK.isHeldByCurrentThread)
if (!freezeHelper.isFrozen(side)) return
unfreeze(side, freezeHelper.getFrozenContent(side)!!)
freezeHelper.setFrozenContent(side, side[document1, document2].immutableCharSequence)
}
@CalledInAwt
fun partiallyApplyBlocks(side: Side, condition: (Block) -> Boolean, consumer: (Block, shift: Int) -> Unit) {
if (isDisposed) return
val otherSide = side.other()
val document = side[document1, document2]
val otherDocument = otherSide[document1, document2]
doFrozen(side) {
val appliedBlocks = LOCK.write {
updateFrozenContentIfNeeded()
tracker.partiallyApplyBlocks(side, condition)
}
// We use already filtered blocks here, because conditions might have been changed from other thread.
// The documents/blocks themselves did not change though.
var shift = 0
for (block in appliedBlocks) {
DiffUtil.applyModification(document, block.range.start(side) + shift, block.range.end(side) + shift,
otherDocument, block.range.start(otherSide), block.range.end(otherSide))
consumer(block, shift)
shift += getRangeDelta(block.range, side)
}
LOCK.write {
freezeHelper.setFrozenContent(side, document.immutableCharSequence)
}
}
}
fun getContentWithPartiallyAppliedBlocks(side: Side, condition: (Block) -> Boolean): String {
val otherSide = side.other()
val affectedBlocks = LOCK.write {
updateFrozenContentIfNeeded()
tracker.blocks.filter(condition)
}
val content = getContent(side)
val otherContent = getContent(otherSide)
val lineOffsets = content.lineOffsets
val otherLineOffsets = otherContent.lineOffsets
val ranges = affectedBlocks.map {
Range(it.range.start(side), it.range.end(side),
it.range.start(otherSide), it.range.end(otherSide))
}
return DiffUtil.applyModification(content, lineOffsets, otherContent, otherLineOffsets, ranges)
}
fun setFrozenState(content1: CharSequence, content2: CharSequence, lineRanges: List<Range>): Boolean {
assert(freezeHelper.isFrozen(Side.LEFT) && freezeHelper.isFrozen(Side.RIGHT))
if (isDisposed) return false
LOCK.write {
if (!ComparisonUtil.isValidRanges(content1, content2, content1.lineOffsets, content2.lineOffsets, lineRanges)) return false
freezeHelper.setFrozenContent(Side.LEFT, content1)
freezeHelper.setFrozenContent(Side.RIGHT, content2)
tracker.setRanges(lineRanges, true)
return true
}
}
@CalledInAwt
fun setFrozenState(lineRanges: List<Range>): Boolean {
if (isDisposed) return false
assert(freezeHelper.isFrozen(Side.LEFT) && freezeHelper.isFrozen(Side.RIGHT))
LOCK.write {
val content1 = getContent(Side.LEFT)
val content2 = getContent(Side.RIGHT)
if (!ComparisonUtil.isValidRanges(content1, content2, content1.lineOffsets, content2.lineOffsets, lineRanges)) return false
tracker.setRanges(lineRanges, true)
return true
}
}
private inner class MyApplicationListener : ApplicationListener {
override fun afterWriteActionFinished(action: Any) {
refreshDirty(fastRefresh = true)
}
}
private inner class MyDocumentListener(val side: Side) : DocumentListener {
private val document = side[document1, document2]
private var line1: Int = 0
private var line2: Int = 0
init {
if (document.isInBulkUpdate) freeze(side)
}
override fun beforeDocumentChange(e: DocumentEvent) {
if (isDisposed || freezeHelper.isFrozen(side)) return
line1 = document.getLineNumber(e.offset)
if (e.oldLength == 0) {
line2 = line1 + 1
}
else {
line2 = document.getLineNumber(e.offset + e.oldLength) + 1
}
}
override fun documentChanged(e: DocumentEvent) {
if (isDisposed || freezeHelper.isFrozen(side)) return
val newLine2: Int
if (e.newLength == 0) {
newLine2 = line1 + 1
}
else {
newLine2 = document.getLineNumber(e.offset + e.newLength) + 1
}
val (startLine, afterLength, beforeLength) = getAffectedRange(line1, line2, newLine2, e)
LOCK.write {
tracker.rangeChanged(side, startLine, beforeLength, afterLength)
}
}
override fun bulkUpdateStarting(document: Document) {
freeze(side)
}
override fun bulkUpdateFinished(document: Document) {
unfreeze(side)
}
private fun getAffectedRange(line1: Int, oldLine2: Int, newLine2: Int, e: DocumentEvent): Triple<Int, Int, Int> {
val afterLength = newLine2 - line1
val beforeLength = oldLine2 - line1
// Whole line insertion / deletion
if (e.oldLength == 0 && e.newLength != 0) {
if (StringUtil.endsWithChar(e.newFragment, '\n') && isNewlineBefore(e)) {
return Triple(line1, afterLength - 1, beforeLength - 1)
}
if (StringUtil.startsWithChar(e.newFragment, '\n') && isNewlineAfter(e)) {
return Triple(line1 + 1, afterLength - 1, beforeLength - 1)
}
}
if (e.oldLength != 0 && e.newLength == 0) {
if (StringUtil.endsWithChar(e.oldFragment, '\n') && isNewlineBefore(e)) {
return Triple(line1, afterLength - 1, beforeLength - 1)
}
if (StringUtil.startsWithChar(e.oldFragment, '\n') && isNewlineAfter(e)) {
return Triple(line1 + 1, afterLength - 1, beforeLength - 1)
}
}
return Triple(line1, afterLength, beforeLength)
}
private fun isNewlineBefore(e: DocumentEvent): Boolean {
if (e.offset == 0) return true
return e.document.immutableCharSequence[e.offset - 1] == '\n'
}
private fun isNewlineAfter(e: DocumentEvent): Boolean {
if (e.offset + e.newLength == e.document.immutableCharSequence.length) return true
return e.document.immutableCharSequence[e.offset + e.newLength] == '\n'
}
}
private inner class FreezeHelper {
private var data1: FreezeData? = null
private var data2: FreezeData? = null
fun isFrozen(side: Side) = getData(side) != null
fun isFrozen() = isFrozen(Side.LEFT) || isFrozen(Side.RIGHT)
fun freeze(side: Side) {
val wasFrozen = isFrozen()
var data = getData(side)
if (data == null) {
data = FreezeData(side[document1, document2])
setData(side, data)
data.counter++
if (wasFrozen) handler.onFreeze()
handler.onFreeze(side)
}
else {
data.counter++
}
}
fun unfreeze(side: Side) {
val data = getData(side)
if (data == null || data.counter == 0) {
LOG.error("DocumentTracker is not freezed: $side, ${data1?.counter ?: -1}, ${data2?.counter ?: -1}")
return
}
data.counter--
if (data.counter == 0) {
unfreeze(side, data.textBeforeFreeze)
setData(side, null)
refreshDirty(fastRefresh = false)
handler.onUnfreeze(side)
if (!isFrozen()) handler.onUnfreeze()
}
}
private fun getData(side: Side) = side[data1, data2]
private fun setData(side: Side, data: FreezeData?) {
if (side.isLeft) {
data1 = data
}
else {
data2 = data
}
}
fun getFrozenContent(side: Side): CharSequence? = getData(side)?.textBeforeFreeze
fun setFrozenContent(side: Side, newContent: CharSequence) {
setData(side, FreezeData(getData(side)!!, newContent))
}
}
private class FreezeData(val textBeforeFreeze: CharSequence, var counter: Int) {
constructor(document: Document) : this(document.immutableCharSequence, 0)
constructor(data: FreezeData, textBeforeFreeze: CharSequence) : this(textBeforeFreeze, data.counter)
}
internal inner class Lock {
private val myLock = ReentrantLock()
internal inline fun <T> read(task: () -> T): T {
return myLock.withLock(task)
}
internal inline fun <T> write(task: () -> T): T {
return myLock.withLock(task)
}
internal val isHeldByCurrentThread: Boolean
get() = myLock.isHeldByCurrentThread
}
interface Handler {
fun onRangeRefreshed(before: Block, after: List<Block>) {}
fun onRangesChanged(before: List<Block>, after: Block) {}
fun onRangeShifted(before: Block, after: Block) {}
fun onRangesMerged(range1: Block, range2: Block, merged: Block): Boolean = true
fun afterRangeChange() {}
fun afterBulkRangeChange() {}
fun onFreeze(side: Side) {}
fun onUnfreeze(side: Side) {}
fun onFreeze() {}
fun onUnfreeze() {}
}
class Block(val range: Range, internal val isDirty: Boolean, internal val isTooBig: Boolean) {
var data: Any? = null
}
companion object {
private val LOG = Logger.getInstance(DocumentTracker::class.java)
}
}
private class LineTracker(private val handler: Handler,
originalChanges: List<Range>) {
var blocks: List<Block> = originalChanges.map { Block(it, false, false) }
private set
var isDirty: Boolean = false
private set
fun setRanges(ranges: List<Range>, dirty: Boolean) {
blocks = ranges.map { Block(it, dirty, false) }
isDirty = dirty
handler.afterBulkRangeChange()
}
fun destroy() {
blocks = emptyList()
}
fun refreshDirty(text1: CharSequence,
text2: CharSequence,
lineOffsets1: LineOffsets,
lineOffsets2: LineOffsets,
fastRefresh: Boolean) {
if (!isDirty) return
val result = BlocksRefresher(handler, text1, text2, lineOffsets1, lineOffsets2).refresh(blocks, fastRefresh)
blocks = result.newBlocks
isDirty = false
handler.afterBulkRangeChange()
}
fun rangeChanged(side: Side, startLine: Int, beforeLength: Int, afterLength: Int) {
val data = RangeChangeHandler().run(blocks, side, startLine, beforeLength, afterLength)
handler.onRangesChanged(data.affectedBlocks, data.newAffectedBlock)
for (i in data.afterBlocks.indices) {
handler.onRangeShifted(data.afterBlocks[i], data.newAfterBlocks[i])
}
blocks = data.newBlocks
isDirty = true
handler.afterRangeChange()
}
fun rangesChanged(side: Side, iterable: DiffIterable) {
val newBlocks = BulkRangeChangeHandler(handler, blocks, side).run(iterable)
blocks = newBlocks
isDirty = true
handler.afterBulkRangeChange()
}
fun partiallyApplyBlocks(side: Side, condition: (Block) -> Boolean): List<Block> {
val newBlocks = mutableListOf<Block>()
val appliedBlocks = mutableListOf<Block>()
var shift = 0
for (block in blocks) {
if (condition(block)) {
appliedBlocks.add(block)
shift += getRangeDelta(block.range, side)
}
else {
val newBlock = block.shift(side, shift)
handler.onRangeShifted(block, newBlock)
newBlocks.add(newBlock)
}
}
blocks = newBlocks
handler.afterBulkRangeChange()
return appliedBlocks
}
}
private class RangeChangeHandler {
fun run(blocks: List<Block>,
side: Side,
startLine: Int,
beforeLength: Int,
afterLength: Int): Result {
val endLine = startLine + beforeLength
val rangeSizeDelta = afterLength - beforeLength
val (beforeBlocks, affectedBlocks, afterBlocks) = sortRanges(blocks, side, startLine, endLine)
val ourToOtherShift: Int = getOurToOtherShift(side, beforeBlocks)
val newAffectedBlock = getNewAffectedBlock(side, startLine, endLine, rangeSizeDelta, ourToOtherShift,
affectedBlocks)
val newAfterBlocks = afterBlocks.map { it.shift(side, rangeSizeDelta) }
val newBlocks = ArrayList<Block>(beforeBlocks.size + newAfterBlocks.size + 1)
newBlocks.addAll(beforeBlocks)
newBlocks.add(newAffectedBlock)
newBlocks.addAll(newAfterBlocks)
return Result(beforeBlocks, newBlocks,
affectedBlocks, afterBlocks,
newAffectedBlock, newAfterBlocks)
}
private fun sortRanges(blocks: List<Block>,
side: Side,
line1: Int,
line2: Int): Triple<List<Block>, List<Block>, List<Block>> {
val beforeChange = ArrayList<Block>()
val affected = ArrayList<Block>()
val afterChange = ArrayList<Block>()
for (block in blocks) {
if (block.range.end(side) < line1) {
beforeChange.add(block)
}
else if (block.range.start(side) > line2) {
afterChange.add(block)
}
else {
affected.add(block)
}
}
return Triple(beforeChange, affected, afterChange)
}
private fun getOurToOtherShift(side: Side, beforeBlocks: List<Block>): Int {
val lastBefore = beforeBlocks.lastOrNull()?.range
val otherShift: Int
if (lastBefore == null) {
otherShift = 0
}
else {
otherShift = lastBefore.end(side.other()) - lastBefore.end(side)
}
return otherShift
}
private fun getNewAffectedBlock(side: Side,
startLine: Int,
endLine: Int,
rangeSizeDelta: Int,
ourToOtherShift: Int,
affectedBlocks: List<Block>): Block {
val rangeStart: Int
val rangeEnd: Int
val rangeStartOther: Int
val rangeEndOther: Int
if (affectedBlocks.isEmpty()) {
rangeStart = startLine
rangeEnd = endLine + rangeSizeDelta
rangeStartOther = startLine + ourToOtherShift
rangeEndOther = endLine + ourToOtherShift
}
else {
val firstAffected = affectedBlocks.first().range
val lastAffected = affectedBlocks.last().range
val affectedStart = firstAffected.start(side)
val affectedStartOther = firstAffected.start(side.other())
val affectedEnd = lastAffected.end(side)
val affectedEndOther = lastAffected.end(side.other())
if (affectedStart <= startLine) {
rangeStart = affectedStart
rangeStartOther = affectedStartOther
}
else {
rangeStart = startLine
rangeStartOther = startLine + (affectedStartOther - affectedStart)
}
if (affectedEnd >= endLine) {
rangeEnd = affectedEnd + rangeSizeDelta
rangeEndOther = affectedEndOther
}
else {
rangeEnd = endLine + rangeSizeDelta
rangeEndOther = endLine + (affectedEndOther - affectedEnd)
}
}
val isTooBig = affectedBlocks.any { it.isTooBig }
val range = createRange(side, rangeStart, rangeEnd, rangeStartOther, rangeEndOther)
return Block(range, true, isTooBig)
}
data class Result(val beforeBlocks: List<Block>, val newBlocks: List<Block>,
val affectedBlocks: List<Block>, val afterBlocks: List<Block>,
val newAffectedBlock: Block, val newAfterBlocks: List<Block>)
}
/**
* We use line numbers in 3 documents:
* A: Line number in unchanged document
* B: Line number in changed document <before> the change
* C: Line number in changed document <after> the change
*
* Algorithm is similar to building ranges for a merge conflict,
* see [com.intellij.diff.comparison.ComparisonMergeUtil.FairMergeBuilder].
* ie: B is the "Base" and A/C are "Left"/"Right". Old blocks hold the differences "A -> B",
* changes from iterable hold the differences "B -> C". We want to construct new blocks with differences "A -> C.
*
* We iterate all differences in 'B' order, collecting interleaving groups of differences. Each group becomes a single newBlock.
* [blockShift]/[changeShift] indicate how 'B' line is mapped to the 'A'/'C' lines at the start of current group.
* [dirtyBlockShift]/[dirtyChangeShift] accumulate differences from the current group.
*
* block(otherSide -> side): A -> B
* newBlock(otherSide -> side): A -> C
* iterable: B -> C
* dirtyStart, dirtyEnd: B
* blockShift: delta B -> A
* changeShift: delta B -> C
*/
private class BulkRangeChangeHandler(private val handler: Handler,
private val blocks: List<Block>,
private val side: Side) {
private val newBlocks: MutableList<Block> = mutableListOf()
private var dirtyStart = -1
private var dirtyEnd = -1
private val dirtyBlocks: MutableList<Block> = mutableListOf()
private var dirtyBlocksModified = false
private var blockShift: Int = 0
private var changeShift: Int = 0
private var dirtyBlockShift: Int = 0
private var dirtyChangeShift: Int = 0
fun run(iterable: DiffIterable): List<Block> {
val it1 = PeekableIteratorWrapper(blocks.iterator())
val it2 = PeekableIteratorWrapper(iterable.changes())
while (it1.hasNext() || it2.hasNext()) {
if (!it2.hasNext()) {
handleBlock(it1.next())
continue
}
if (!it1.hasNext()) {
handleChange(it2.next())
continue
}
val block = it1.peek()
val range1 = block.range
val range2 = it2.peek()
if (range1.start(side) <= range2.start1) {
handleBlock(it1.next())
}
else {
handleChange(it2.next())
}
}
flush(Int.MAX_VALUE)
return newBlocks
}
private fun handleBlock(block: Block) {
val range = block.range
flush(range.start(side))
dirtyBlockShift += getRangeDelta(range, side)
markDirtyRange(range.start(side), range.end(side))
dirtyBlocks.add(block)
}
private fun handleChange(range: Range) {
flush(range.start1)
dirtyChangeShift += getRangeDelta(range, Side.LEFT)
markDirtyRange(range.start1, range.end1)
dirtyBlocksModified = true
}
private fun markDirtyRange(start: Int, end: Int) {
if (dirtyEnd == -1) {
dirtyStart = start
dirtyEnd = end
}
else {
dirtyEnd = max(dirtyEnd, end)
}
}
private fun flush(nextLine: Int) {
if (dirtyEnd != -1 && dirtyEnd < nextLine) {
if (dirtyBlocksModified) {
val isTooBig = dirtyBlocks.any { it.isTooBig }
val isDirty = true
val range = createRange(side,
dirtyStart + changeShift, dirtyEnd + changeShift + dirtyChangeShift,
dirtyStart + blockShift, dirtyEnd + blockShift + dirtyBlockShift)
val newBlock = Block(range, isDirty, isTooBig)
handler.onRangesChanged(dirtyBlocks, newBlock)
newBlocks.add(newBlock)
}
else {
assert(dirtyBlocks.size == 1)
if (changeShift != 0) {
for (oldBlock in dirtyBlocks) {
val newBlock = oldBlock.shift(side, changeShift)
handler.onRangeShifted(oldBlock, newBlock)
newBlocks.add(newBlock)
}
}
else {
newBlocks.addAll(dirtyBlocks)
}
}
dirtyStart = -1
dirtyEnd = -1
dirtyBlocks.clear()
dirtyBlocksModified = false
blockShift += dirtyBlockShift
changeShift += dirtyChangeShift
dirtyBlockShift = 0
dirtyChangeShift = 0
}
}
}
private class BlocksRefresher(val handler: Handler,
val text1: CharSequence,
val text2: CharSequence,
val lineOffsets1: LineOffsets,
val lineOffsets2: LineOffsets) {
fun refresh(blocks: List<Block>, fastRefresh: Boolean): Result {
val newBlocks = ArrayList<Block>()
processMergeableGroups(blocks) { group ->
if (group.any { it.isDirty }) {
processMergedBlocks(group) { mergedBlock ->
val freshBlocks = refreshBlock(mergedBlock, fastRefresh)
handler.onRangeRefreshed(mergedBlock, freshBlocks)
newBlocks.addAll(freshBlocks)
}
}
else {
newBlocks.addAll(group)
}
}
return Result(newBlocks)
}
private fun processMergeableGroups(blocks: List<Block>,
processGroup: (group: List<Block>) -> Unit) {
if (blocks.isEmpty()) return
var i = 0
var blockStart = 0
while (i < blocks.size - 1) {
if (!isWhitespaceOnlySeparated(blocks[i], blocks[i + 1])) {
processGroup(blocks.subList(blockStart, i + 1))
blockStart = i + 1
}
i += 1
}
processGroup(blocks.subList(blockStart, i + 1))
}
private fun isWhitespaceOnlySeparated(block1: Block, block2: Block): Boolean {
val range1 = DiffUtil.getLinesRange(lineOffsets1, block1.range.start1, block1.range.end1, false)
val range2 = DiffUtil.getLinesRange(lineOffsets1, block2.range.start1, block2.range.end1, false)
val start = range1.endOffset
val end = range2.startOffset
return trimStart(text1, start, end) == end
}
private fun processMergedBlocks(group: List<Block>,
processBlock: (merged: Block) -> Unit) {
assert(!group.isEmpty())
var merged: Block? = null
for (block in group) {
if (merged == null) {
merged = block
}
else {
val newMerged = mergeBlocks(merged, block)
if (newMerged != null) {
merged = newMerged
}
else {
processBlock(merged)
merged = block
}
}
}
processBlock(merged!!)
}
private fun mergeBlocks(block1: Block, block2: Block): Block? {
val isDirty = block1.isDirty || block2.isDirty
val isTooBig = block1.isTooBig || block2.isTooBig
val range = Range(block1.range.start1, block2.range.end1,
block1.range.start2, block2.range.end2)
val merged = Block(range, isDirty, isTooBig)
if (!handler.onRangesMerged(block1, block2, merged)) {
return null // merging vetoed
}
return merged
}
private fun refreshBlock(block: Block, fastRefresh: Boolean): List<Block> {
if (block.range.isEmpty) return emptyList()
val iterable: FairDiffIterable
val isTooBig: Boolean
if (block.isTooBig && fastRefresh) {
iterable = fastCompareLines(block.range, text1, text2, lineOffsets1, lineOffsets2)
isTooBig = true
}
else {
val realIterable = tryCompareLines(block.range, text1, text2, lineOffsets1, lineOffsets2)
if (realIterable != null) {
iterable = realIterable
isTooBig = false
}
else {
iterable = fastCompareLines(block.range, text1, text2, lineOffsets1, lineOffsets2)
isTooBig = true
}
}
return iterable.iterateChanges().map {
Block(shiftRange(it, block.range.start1, block.range.start2), false, isTooBig)
}
}
data class Result(val newBlocks: List<Block>)
}
private fun getRangeDelta(range: Range, side: Side): Int {
val otherSide = side.other()
val deleted = range.end(side) - range.start(side)
val inserted = range.end(otherSide) - range.start(otherSide)
return inserted - deleted
}
private fun Block.shift(side: Side, delta: Int) = Block(
shiftRange(this.range, side, delta), this.isDirty, this.isTooBig)
private fun shiftRange(range: Range, side: Side, shift: Int) = when {
side.isLeft -> shiftRange(range, shift, 0)
else -> shiftRange(range, 0, shift)
}
private fun shiftRange(range: Range, shift1: Int, shift2: Int) = Range(range.start1 + shift1,
range.end1 + shift1,
range.start2 + shift2,
range.end2 + shift2)
private fun createRange(side: Side, start: Int, end: Int, otherStart: Int, otherEnd: Int): Range = when {
side.isLeft -> Range(start, end, otherStart, otherEnd)
else -> Range(otherStart, otherEnd, start, end)
} | apache-2.0 | 7cfcbebea3e0841761815aa6f096280a | 29.756329 | 140 | 0.646797 | 4.40423 | false | false | false | false |
JuliusKunze/kotlin-native | backend.native/tests/external/codegen/box/properties/fieldInsideNested.kt | 5 | 194 | abstract class Your {
abstract val your: String
fun foo() = your
}
val my: String = "O"
get() = object: Your() {
override val your = field
}.foo() + "K"
fun box() = my | apache-2.0 | 5e667768f9e159d068155c3f54d4d792 | 15.25 | 33 | 0.541237 | 3.344828 | false | false | false | false |
smmribeiro/intellij-community | plugins/markdown/core/src/org/intellij/plugins/markdown/editor/tables/ui/MarkdownTableInlayProvider.kt | 1 | 3509 | // 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.intellij.plugins.markdown.editor.tables.ui
import com.intellij.codeInsight.hints.*
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.util.Key
import com.intellij.openapi.util.registry.Registry
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
import com.intellij.refactoring.suggested.startOffset
import com.intellij.util.DocumentUtil
import org.intellij.plugins.markdown.MarkdownBundle
import org.intellij.plugins.markdown.editor.tables.TableModificationUtils
import org.intellij.plugins.markdown.editor.tables.TableModificationUtils.hasCorrectBorders
import org.intellij.plugins.markdown.editor.tables.TableUtils
import org.intellij.plugins.markdown.editor.tables.ui.presentation.HorizontalBarPresentation
import org.intellij.plugins.markdown.editor.tables.ui.presentation.VerticalBarPresentation
import org.intellij.plugins.markdown.lang.MarkdownFileType
import org.intellij.plugins.markdown.lang.psi.impl.MarkdownTable
import org.intellij.plugins.markdown.lang.psi.impl.MarkdownTableRow
import org.intellij.plugins.markdown.lang.psi.impl.MarkdownTableSeparatorRow
import org.intellij.plugins.markdown.settings.MarkdownSettings
import javax.swing.JPanel
internal class MarkdownTableInlayProvider: InlayHintsProvider<NoSettings> {
override fun getCollectorFor(file: PsiFile, editor: Editor, settings: NoSettings, sink: InlayHintsSink): InlayHintsCollector? {
if (!Registry.`is`("markdown.tables.editing.support.enable") || !MarkdownSettings.getInstance(file.project).isEnhancedEditingEnabled) {
return null
}
if (file.fileType != MarkdownFileType.INSTANCE) {
return null
}
return Collector(editor)
}
private class Collector(editor: Editor): FactoryInlayHintsCollector(editor) {
override fun collect(element: PsiElement, editor: Editor, sink: InlayHintsSink): Boolean {
if (editor.getUserData(DISABLE_TABLE_INLAYS) == true) {
return true
}
if (element is MarkdownTableRow || element is MarkdownTableSeparatorRow) {
if (DocumentUtil.isAtLineStart(element.startOffset, editor.document) && TableUtils.findTable(element)?.hasCorrectBorders() == true) {
val presentation = VerticalBarPresentation.create(factory, editor, element)
sink.addInlineElement(element.startOffset, false, presentation, false)
}
} else if (element is MarkdownTable && element.hasCorrectBorders()) {
val presentation = HorizontalBarPresentation.create(factory, editor, element)
sink.addBlockElement(element.startOffset, false, true, -1, presentation)
}
return true
}
}
override fun createSettings() = NoSettings()
override val name: String
get() = MarkdownBundle.message("markdown.table.inlay.kind.name")
override val key: SettingsKey<NoSettings>
get() = settingsKey
override val previewText: String
get() = TableModificationUtils.buildEmptyTable(3, 3)
override fun createConfigurable(settings: NoSettings): ImmediateConfigurable {
return object: ImmediateConfigurable {
override fun createComponent(listener: ChangeListener) = JPanel()
}
}
companion object {
private val settingsKey = SettingsKey<NoSettings>("MarkdownTableInlayProviderSettingsKey")
val DISABLE_TABLE_INLAYS = Key<Boolean>("MarkdownDisableTableInlaysKey")
}
}
| apache-2.0 | e9edfd6625b020f36129e82609b409a7 | 45.171053 | 158 | 0.779709 | 4.641534 | false | false | false | false |
smmribeiro/intellij-community | platform/vcs-impl/src/com/intellij/util/ui/JButtonAction.kt | 2 | 2428 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.util.ui
import com.intellij.openapi.actionSystem.ActionToolbar
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.Presentation
import com.intellij.openapi.actionSystem.ex.ActionUtil
import com.intellij.openapi.actionSystem.ex.CustomComponentAction
import com.intellij.openapi.project.DumbAwareAction
import com.intellij.openapi.util.NlsActions.ActionDescription
import com.intellij.openapi.util.NlsActions.ActionText
import javax.swing.Icon
import javax.swing.JButton
import javax.swing.JComponent
abstract class JButtonAction(text: @ActionText String?, @ActionDescription description: String? = null, icon: Icon? = null)
: DumbAwareAction(text, description, icon), CustomComponentAction {
override fun createCustomComponent(presentation: Presentation, place: String): JComponent {
val button = createButton()
button.addActionListener {
performAction(button, place, presentation)
}
return button
}
protected fun performAction(component: JComponent, place: String, presentation: Presentation) {
val dataContext = ActionToolbar.getDataContextFor(component)
val event = AnActionEvent.createFromInputEvent(null, place, presentation, dataContext)
if (ActionUtil.lastUpdateAndCheckDumb(this, event, true)) {
ActionUtil.performActionDumbAwareWithCallbacks(this, event)
}
}
protected open fun createButton(): JButton = JButton().configureForToolbar()
protected fun JButton.configureForToolbar(): JButton =
apply {
isFocusable = false
font = JBUI.Fonts.toolbarFont()
putClientProperty("ActionToolbar.smallVariant", true)
}
override fun updateCustomComponent(component: JComponent, presentation: Presentation) {
if (component is JButton) {
updateButtonFromPresentation(component, presentation)
}
}
protected open fun updateButtonFromPresentation(button: JButton, presentation: Presentation) {
button.isEnabled = presentation.isEnabled
button.isVisible = presentation.isVisible
button.text = presentation.getText(true)
button.icon = presentation.icon
button.mnemonic = presentation.mnemonic
button.displayedMnemonicIndex = presentation.displayedMnemonicIndex
button.toolTipText = presentation.description
}
} | apache-2.0 | c25ab714008b7f15111719cb46ee4a48 | 38.819672 | 123 | 0.783773 | 5.058333 | false | false | false | false |
smmribeiro/intellij-community | plugins/settings-sync/src/com/intellij/settingsSync/SettingsSyncFiltering.kt | 1 | 3779 | package com.intellij.settingsSync
import com.intellij.configurationStore.getPerOsSettingsStorageFolderName
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.components.*
import com.intellij.openapi.editor.colors.impl.AppEditorFontOptions
import com.intellij.openapi.editor.colors.impl.EditorColorsManagerImpl
import com.intellij.openapi.keymap.impl.KEYMAPS_DIR_PATH
import com.intellij.openapi.util.text.StringUtil
import com.intellij.profile.codeInspection.InspectionProfileManager
import com.intellij.psi.impl.source.codeStyle.CodeStyleSchemesImpl
import com.intellij.serviceContainer.ComponentManagerImpl
import com.intellij.settingsSync.config.SettingsSyncUiGroup
internal fun isSyncEnabled(fileSpec: String, roamingType: RoamingType): Boolean {
if (roamingType == RoamingType.DISABLED) return false
val rawFileSpec = removeOsPrefix(fileSpec)
if (rawFileSpec == SettingsSyncSettings.FILE_SPEC) return true
val componentClasses = findComponentClasses(rawFileSpec)
val category = getSchemeCategory(rawFileSpec) ?: getCategory(componentClasses)
if (category != SettingsCategory.OTHER && SettingsSyncSettings.getInstance().isCategoryEnabled(category)) {
val subCategory = getSubCategory(componentClasses)
if (subCategory != null) {
return SettingsSyncSettings.getInstance().isSubcategoryEnabled(category, subCategory)
}
return true
}
return false
}
private fun removeOsPrefix(fileSpec: String): String {
val osPrefix = getPerOsSettingsStorageFolderName() + "/"
return if (fileSpec.startsWith(osPrefix)) StringUtil.trimStart(fileSpec, osPrefix) else fileSpec
}
private fun getCategory(componentClasses: List<Class<PersistentStateComponent<Any>>>): SettingsCategory {
when {
componentClasses.isEmpty() -> return SettingsCategory.OTHER
componentClasses.size == 1 -> return ComponentCategorizer.getCategory(componentClasses[0])
else -> {
componentClasses.forEach {
val category = ComponentCategorizer.getCategory(it)
if (category != SettingsCategory.OTHER) {
// Once found, ignore any other possibly conflicting definitions
return category
}
}
return SettingsCategory.OTHER
}
}
}
private fun getSchemeCategory(fileSpec: String): SettingsCategory? {
val separatorIndex = fileSpec.indexOf("/")
if (separatorIndex >= 0) {
when (fileSpec.substring(0, separatorIndex)) {
CodeStyleSchemesImpl.CODE_STYLES_DIR_PATH -> return SettingsCategory.CODE
EditorColorsManagerImpl.FILE_SPEC -> return SettingsCategory.UI
KEYMAPS_DIR_PATH -> return SettingsCategory.KEYMAP
InspectionProfileManager.INSPECTION_DIR -> return SettingsCategory.CODE
}
}
return null
}
private fun getSubCategory(componentClasses: List<Class<PersistentStateComponent<Any>>>): String? {
for (componentClass in componentClasses) {
if (AppEditorFontOptions::class.java.isAssignableFrom(componentClass)) {
return SettingsSyncUiGroup.EDITOR_FONT_ID
}
}
return null
}
private fun findComponentClasses(fileSpec: String): List<Class<PersistentStateComponent<Any>>> {
val componentManager = ApplicationManager.getApplication() as ComponentManagerImpl
val componentClasses = ArrayList<Class<PersistentStateComponent<Any>>>()
componentManager.processAllImplementationClasses { aClass, _ ->
if (PersistentStateComponent::class.java.isAssignableFrom(aClass)) {
val state = aClass.getAnnotation(State::class.java)
state?.storages?.forEach { storage ->
if (!storage.deprecated && storage.value == fileSpec) {
@Suppress("UNCHECKED_CAST")
componentClasses.add(aClass as Class<PersistentStateComponent<Any>>)
}
}
}
}
return componentClasses
} | apache-2.0 | 3df6221d17a88f70ebc088c5b5a124a5 | 41 | 109 | 0.767134 | 5.018592 | false | false | false | false |
anitawoodruff/habitica-android | Habitica/src/main/java/com/habitrpg/android/habitica/ui/viewHolders/tasks/TodoViewHolder.kt | 1 | 1485 | package com.habitrpg.android.habitica.ui.viewHolders.tasks
import android.view.View
import com.habitrpg.android.habitica.models.responses.TaskDirection
import com.habitrpg.android.habitica.models.tasks.ChecklistItem
import com.habitrpg.android.habitica.models.tasks.Task
import java.text.DateFormat
class TodoViewHolder(itemView: View, scoreTaskFunc: ((Task, TaskDirection) -> Unit), scoreChecklistItemFunc: ((Task, ChecklistItem) -> Unit), openTaskFunc: ((Task) -> Unit)) : ChecklistedViewHolder(itemView, scoreTaskFunc, scoreChecklistItemFunc, openTaskFunc) {
private val dateFormatter: DateFormat = android.text.format.DateFormat.getDateFormat(context)
override fun bind(newTask: Task, position: Int) {
this.task = newTask
if (newTask.completed) {
checklistIndicatorWrapper.setBackgroundColor(taskGray)
} else {
checklistIndicatorWrapper.setBackgroundColor(newTask.lightTaskColor)
}
super.bind(newTask, position)
}
override fun configureSpecialTaskTextView(task: Task) {
if (task.dueDate != null) {
this.specialTaskTextView?.text = dateFormatter.format(task.dueDate)
this.specialTaskTextView?.visibility = View.VISIBLE
} else {
this.specialTaskTextView?.visibility = View.INVISIBLE
}
}
override fun shouldDisplayAsActive(newTask: Task): Boolean {
return !newTask.completed
}
}
| gpl-3.0 | 7e8a68450ec5e6e2c9a47c044f62d46c | 38.135135 | 262 | 0.702357 | 4.611801 | false | false | false | false |
SkyTreasure/Kotlin-Firebase-Group-Chat | app/src/main/java/io/skytreasure/kotlingroupchat/chat/ui/adapter/OneOnOneListingAdapter.kt | 1 | 2239 | package io.skytreasure.kotlingroupchat.chat.ui.adapter
import android.content.Context
import android.content.Intent
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import io.skytreasure.kotlingroupchat.R
import io.skytreasure.kotlingroupchat.chat.ui.ChatMessagesActivity
import io.skytreasure.kotlingroupchat.chat.ui.ViewHolders.UserRowViewHolder
import io.skytreasure.kotlingroupchat.common.constants.AppConstants
import io.skytreasure.kotlingroupchat.common.constants.DataConstants
import io.skytreasure.kotlingroupchat.common.constants.NetworkConstants
import io.skytreasure.kotlingroupchat.common.util.loadRoundImage
/**
* Created by akash on 31/10/17.
*/
class OneOnOneListingAdapter(var context: Context) : RecyclerView.Adapter<UserRowViewHolder>() {
var holderMap: MutableMap<String, UserRowViewHolder> = mutableMapOf()
override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): UserRowViewHolder =
UserRowViewHolder(LayoutInflater.from(parent?.context).inflate(R.layout.item_user, parent, false))
override fun onBindViewHolder(holder: UserRowViewHolder, position: Int) {
val user = DataConstants.userList?.get(position)
holder.tvName.text = user?.name
holder.tvEmail.text = user?.email
loadRoundImage(holder.ivProfile, user?.image_url!!)
if (user.online != null && user.online!!) {
holder.viewOnlineStatus.visibility = View.VISIBLE
} else {
// holder.viewOnlineStatus.setBackgroundColor(R.color.greyish)
holder.viewOnlineStatus.visibility = View.GONE
}
holder.layout.setOnClickListener {
val intent = Intent(context, ChatMessagesActivity::class.java)
intent.putExtra(AppConstants.USER_ID, user.uid)
intent.putExtra(AppConstants.CHAT_TYPE, AppConstants.ONE_ON_ONE_CHAT)
intent.putExtra(AppConstants.POSITION, position)
context.startActivity(intent)
}
}
fun resetView(uid: String) {
holderMap.get(uid)?.ivSelected?.visibility = View.GONE
}
override fun getItemCount(): Int = DataConstants.userList?.size!!
} | mit | 736249e05eedcd4ec5b2cea0499ed423 | 39 | 110 | 0.740509 | 4.50503 | false | false | false | false |
benjamin-bader/thrifty | thrifty-integration-tests/src/test/kotlin/com/microsoft/thrifty/integration/conformance/server/KotlinServerConformanceTest.kt | 1 | 3263 | /*
* Thrifty
*
* Copyright (c) Microsoft Corporation
*
* All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the License);
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING
* WITHOUT LIMITATION ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE,
* FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABLITY OR NON-INFRINGEMENT.
*
* See the Apache Version 2.0 License for specific language governing permissions and limitations under the License.
*/
package com.microsoft.thrifty.integration.conformance.server
import com.microsoft.thrifty.testing.ServerProtocol
import com.microsoft.thrifty.testing.TestClient
import io.kotest.assertions.throwables.shouldThrow
import io.kotest.matchers.shouldBe
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.extension.RegisterExtension
import java.io.Closeable
import java.security.Permission
class BinaryServerConformanceTest : KotlinServerConformanceTest(ServerProtocol.BINARY)
class CompactServerConformanceTest : KotlinServerConformanceTest(ServerProtocol.COMPACT)
class JsonServerConformanceTest : KotlinServerConformanceTest(ServerProtocol.JSON)
/**
* A test of auto-generated service code for the standard ThriftTest
* service.
*
* Conformance is checked by roundtripping requests from a java client generated
* by the official Thrift generator to the server implementation generated by Thrifty.
* The test server has an implementation of ThriftTest methods with semantics as described in the
* .thrift file itself and in the Apache Thrift git repo
*/
abstract class KotlinServerConformanceTest(
private val serverProtocol: ServerProtocol
) {
protected class ExitException(val status: Int) : Exception()
private class NoExitSecurityManager : SecurityManager() {
override fun checkPermission(perm: Permission) {
// allow anything.
}
override fun checkPermission(perm: Permission, context: Any) {
// allow anything.
}
override fun checkExit(status: Int) {
throw ExitException(status)
}
}
class NoExit : Closeable {
init {
System.setSecurityManager(NoExitSecurityManager())
}
override fun close() {
System.setSecurityManager(null)
}
}
@JvmField
@RegisterExtension
val testServer = TestServer(serverProtocol)
@Test
fun testServer() {
val port = testServer.port()
val protocol = when (serverProtocol) {
ServerProtocol.BINARY -> "binary"
ServerProtocol.COMPACT -> "compact"
ServerProtocol.JSON -> "json"
}
val res = shouldThrow<ExitException> {
NoExit().use {
TestClient.main(arrayOf(
"--host=localhost",
"--port=$port",
"--transport=http",
"--protocol=$protocol"
))
}
}
res.status shouldBe 0
}
}
| apache-2.0 | c57cc5176431cd58b132fc1a0835e708 | 32.295918 | 116 | 0.680356 | 4.884731 | false | true | false | false |
siosio/intellij-community | plugins/kotlin/idea/tests/testData/codeInsight/renderingKDoc/functionRendering.kt | 4 | 1300 |
/**
* Hello darling
* @author DarkWing Duck
*/
fun testFun() {}
class outherClass {
/**
* Hello darling instance
* @author Morgana Macawber
*/
fun instanceFun() {
/**
* Hello darling local
* @author Launchpad McQuack
*/
fun localFun() {
if (true) {
/**
* Hello darling superLocal
* @author Reginald Bushroot
*/
fun superLocalFun() {
}
}
}
}
}
// RENDER: <div class='content'><p>Hello darling</p></div><table class='sections'><tr><td valign='top' class='section'><p>Author:</td><td valign='top'>DarkWing Duck</td></table>
// RENDER: <div class='content'><p>Hello darling instance</p></div><table class='sections'><tr><td valign='top' class='section'><p>Author:</td><td valign='top'>Morgana Macawber</td></table>
// RENDER: <div class='content'><p>Hello darling local</p></div><table class='sections'><tr><td valign='top' class='section'><p>Author:</td><td valign='top'>Launchpad McQuack</td></table>
// RENDER: <div class='content'><p>Hello darling superLocal</p></div><table class='sections'><tr><td valign='top' class='section'><p>Author:</td><td valign='top'>Reginald Bushroot</td></table> | apache-2.0 | 2172ff80234d11aa27f5d8025ed29dc6 | 35.138889 | 192 | 0.57 | 3.846154 | false | false | false | false |
siosio/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/SamConversionToAnonymousObjectIntention.kt | 1 | 7151 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.intentions
import com.intellij.codeInsight.intention.LowPriorityAction
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.util.TextRange
import org.jetbrains.kotlin.descriptors.ClassDescriptor
import org.jetbrains.kotlin.descriptors.FunctionDescriptor
import org.jetbrains.kotlin.descriptors.ValueParameterDescriptor
import org.jetbrains.kotlin.descriptors.impl.AnonymousFunctionDescriptor
import org.jetbrains.kotlin.diagnostics.Severity
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.caches.resolve.resolveToCall
import org.jetbrains.kotlin.idea.core.CollectingNameValidator
import org.jetbrains.kotlin.idea.core.KotlinNameSuggester
import org.jetbrains.kotlin.idea.core.replaced
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.load.java.sam.JavaSingleAbstractMethodUtils
import org.jetbrains.kotlin.psi.KtCallExpression
import org.jetbrains.kotlin.psi.KtFunctionLiteral
import org.jetbrains.kotlin.psi.KtLambdaExpression
import org.jetbrains.kotlin.psi.KtPsiFactory
import org.jetbrains.kotlin.psi.psiUtil.anyDescendantOfType
import org.jetbrains.kotlin.psi.psiUtil.getQualifiedExpressionForSelector
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.calls.callUtil.getType
import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameSafe
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
import org.jetbrains.kotlin.resolve.sam.getSingleAbstractMethodOrNull
import org.jetbrains.kotlin.types.typeUtil.isSubtypeOf
class SamConversionToAnonymousObjectIntention : SelfTargetingRangeIntention<KtCallExpression>(
KtCallExpression::class.java, KotlinBundle.lazyMessage("convert.to.anonymous.object")
), LowPriorityAction {
override fun applicabilityRange(element: KtCallExpression): TextRange? {
val callee = element.calleeExpression ?: return null
val lambda = getLambdaExpression(element) ?: return null
val functionLiteral = lambda.functionLiteral
val bindingContext = functionLiteral.analyze()
val sam = element.getSingleAbstractMethod(bindingContext) ?: return null
val samValueParameters = sam.valueParameters
val samValueParameterSize = samValueParameters.size
if (samValueParameterSize != functionLiteral.functionDescriptor(bindingContext)?.valueParameters?.size) return null
val samName = sam.name.asString()
if (functionLiteral.anyDescendantOfType<KtCallExpression> { call ->
if (call.calleeExpression?.text != samName) return@anyDescendantOfType false
val valueArguments = call.valueArguments
if (valueArguments.size != samValueParameterSize) return@anyDescendantOfType false
val context = call.analyze(BodyResolveMode.PARTIAL)
valueArguments.zip(samValueParameters).all { (arg, param) ->
arg.getArgumentExpression()?.getType(context)?.isSubtypeOf(param.type) == true
}
}) return null
if (bindingContext.diagnostics.forElement(functionLiteral).any { it.severity == Severity.ERROR }) return null
return callee.textRange
}
override fun applyTo(element: KtCallExpression, editor: Editor?) {
val lambda = getLambdaExpression(element) ?: return
val context = element.analyze(BodyResolveMode.PARTIAL)
val lambdaFunctionDescriptor = lambda.functionLiteral.functionDescriptor(context) ?: return
val samDescriptor = element.getSingleAbstractMethod(context) ?: return
convertToAnonymousObject(element, samDescriptor, lambda, lambdaFunctionDescriptor)
}
private fun KtCallExpression.getSingleAbstractMethod(context: BindingContext): FunctionDescriptor? {
val type = getType(context) ?: return null
if (!JavaSingleAbstractMethodUtils.isSamType(type)) return null
val classDescriptor = type.constructor.declarationDescriptor as? ClassDescriptor ?: return null
return getSingleAbstractMethodOrNull(classDescriptor)
}
private fun KtFunctionLiteral.functionDescriptor(context: BindingContext): AnonymousFunctionDescriptor? =
context[BindingContext.FUNCTION, this] as? AnonymousFunctionDescriptor
companion object {
fun convertToAnonymousObject(
call: KtCallExpression,
samDescriptor: FunctionDescriptor,
lambda: KtLambdaExpression,
lambdaFunctionDescriptor: AnonymousFunctionDescriptor? = null
) {
val parentOfCall = call.getQualifiedExpressionForSelector()
val interfaceName = if (parentOfCall != null) {
parentOfCall.resolveToCall()?.resultingDescriptor?.fqNameSafe?.asString()
} else {
call.calleeExpression?.text
} ?: return
val typeArguments = call.typeArguments.mapNotNull { it.typeReference }
val typeArgumentsText = if (typeArguments.isEmpty()) {
""
} else {
typeArguments.joinToString(prefix = "<", postfix = ">", separator = ", ") { it.text }
}
val functionDescriptor = lambdaFunctionDescriptor ?: samDescriptor
val functionName = samDescriptor.name.asString()
val samParameters = samDescriptor.valueParameters
val nameValidator = CollectingNameValidator(lambdaFunctionDescriptor?.valueParameters?.map { it.name.asString() }.orEmpty())
val functionParameterName: (ValueParameterDescriptor, Int) -> String = { parameter, index ->
val name = parameter.name
if (name.isSpecial) {
KotlinNameSuggester.suggestNameByName((samParameters.getOrNull(index)?.name ?: name).asString(), nameValidator)
} else {
name.asString()
}
}
val classDescriptor = functionDescriptor.containingDeclaration as? ClassDescriptor
val typeParameters = classDescriptor?.declaredTypeParameters?.map { it.name.asString() }?.zip(typeArguments)?.toMap().orEmpty()
LambdaToAnonymousFunctionIntention.convertLambdaToFunction(
lambda,
functionDescriptor,
functionName,
functionParameterName,
typeParameters
) {
it.addModifier(KtTokens.OVERRIDE_KEYWORD)
(parentOfCall ?: call).replaced(
KtPsiFactory(it).createExpression("object : $interfaceName$typeArgumentsText { ${it.text} }")
)
}
}
fun getLambdaExpression(element: KtCallExpression): KtLambdaExpression? =
element.lambdaArguments.firstOrNull()?.getLambdaExpression()
?: element.valueArguments.firstOrNull()?.getArgumentExpression() as? KtLambdaExpression
}
} | apache-2.0 | 3c144ed383798daac74a873dc20a4154 | 51.588235 | 158 | 0.715844 | 5.743775 | false | false | false | false |
siosio/intellij-community | plugins/kotlin/compiler-plugins/parcelize/tests/testData/checker/properties.kt | 2 | 1745 | // WITH_RUNTIME
package test
import kotlinx.parcelize.*
import android.os.Parcelable
@Parcelize
class A(val firstName: String) : Parcelable {
val <warning descr="[PROPERTY_WONT_BE_SERIALIZED] Property would not be serialized into a 'Parcel'. Add '@IgnoredOnParcel' annotation to remove the warning">secondName</warning>: String = ""
val <warning descr="[PROPERTY_WONT_BE_SERIALIZED] Property would not be serialized into a 'Parcel'. Add '@IgnoredOnParcel' annotation to remove the warning">delegated</warning> by lazy { "" }
lateinit var <warning descr="[PROPERTY_WONT_BE_SERIALIZED] Property would not be serialized into a 'Parcel'. Add '@IgnoredOnParcel' annotation to remove the warning">lateinit</warning>: String
val customGetter: String
get() = ""
var customSetter: String
get() = ""
set(<warning descr="[UNUSED_PARAMETER] Parameter 'v' is never used">v</warning>) {}
}
@Parcelize
@Suppress("WRONG_ANNOTATION_TARGET_WITH_USE_SITE_TARGET")
class B(<warning descr="[INAPPLICABLE_IGNORED_ON_PARCEL_CONSTRUCTOR_PROPERTY] '@IgnoredOnParcel' is inapplicable to properties declared in the primary constructor">@IgnoredOnParcel</warning> val firstName: String) : Parcelable {
@IgnoredOnParcel
var a: String = ""
@field:IgnoredOnParcel
var <warning descr="[PROPERTY_WONT_BE_SERIALIZED] Property would not be serialized into a 'Parcel'. Add '@IgnoredOnParcel' annotation to remove the warning">b</warning>: String = ""
@get:IgnoredOnParcel
var c: String = ""
@set:IgnoredOnParcel
var <warning descr="[PROPERTY_WONT_BE_SERIALIZED] Property would not be serialized into a 'Parcel'. Add '@IgnoredOnParcel' annotation to remove the warning">d</warning>: String = ""
} | apache-2.0 | 4a0b454422885da99d181e810f025d9f | 46.189189 | 228 | 0.729513 | 4.451531 | false | false | false | false |
spotify/heroic | heroic-component/src/main/java/com/spotify/heroic/metric/WriteMetric.kt | 1 | 2189 | /*
* Copyright (c) 2019 Spotify AB.
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package com.spotify.heroic.metric
import com.spotify.heroic.cluster.ClusterShard
import com.spotify.heroic.common.RequestTimer
import com.spotify.heroic.common.Series
import eu.toolchain.async.Collector
import eu.toolchain.async.Transform
data class WriteMetric(
val errors: List<RequestError> = listOf(),
val times: List<Long> = listOf()
) {
constructor(time: Long): this(times = listOf(time))
constructor(error: RequestError): this(errors = listOf(error))
companion object {
@JvmStatic fun shardError(c: ClusterShard): Transform<Throwable, WriteMetric> {
return Transform { e: Throwable ->
WriteMetric(listOf(ShardError.fromThrowable(c, e)))
}
}
@JvmStatic fun reduce(): Collector<WriteMetric, WriteMetric> {
return Collector { results: Collection<WriteMetric> ->
val errors = mutableListOf<RequestError>()
val times = mutableListOf<Long>()
results.forEach {
errors.addAll(it.errors)
times.addAll(it.times)
}
WriteMetric(errors.toList(), times.toList())
}
}
@JvmStatic fun timer() = RequestTimer(::WriteMetric)
}
data class Request(val series: Series, val data: MetricCollection)
} | apache-2.0 | 44b4e2e911158948ee5510ad9aad7896 | 34.322581 | 87 | 0.67291 | 4.494867 | false | false | false | false |
google/iosched | mobile/src/test/java/com/google/samples/apps/iosched/ui/MainActivityViewModelTest.kt | 1 | 4573 | /*
* Copyright 2019 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.samples.apps.iosched.ui
import android.content.Context
import androidx.arch.core.executor.testing.InstantTaskExecutorRule
import com.google.firebase.functions.FirebaseFunctions
import com.google.gson.GsonBuilder
import com.google.samples.apps.iosched.model.TestDataRepository
import com.google.samples.apps.iosched.shared.data.ar.DefaultArDebugFlagEndpoint
import com.google.samples.apps.iosched.shared.data.session.DefaultSessionRepository
import com.google.samples.apps.iosched.shared.data.userevent.DefaultSessionAndUserEventRepository
import com.google.samples.apps.iosched.shared.domain.ar.LoadArDebugFlagUseCase
import com.google.samples.apps.iosched.shared.domain.sessions.LoadPinnedSessionsJsonUseCase
import com.google.samples.apps.iosched.test.data.MainCoroutineRule
import com.google.samples.apps.iosched.test.util.fakes.FakeSignInViewModelDelegate
import com.google.samples.apps.iosched.test.util.fakes.FakeThemedActivityDelegate
import com.google.samples.apps.iosched.ui.schedule.TestUserEventDataSource
import com.google.samples.apps.iosched.ui.signin.SignInViewModelDelegate
import com.google.samples.apps.iosched.ui.theme.ThemedActivityDelegate
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.test.runTest
import org.junit.Assert.assertEquals
import org.junit.Rule
import org.junit.Test
import org.mockito.Mockito.mock
class MainActivityViewModelTest {
// Executes tasks in the Architecture Components in the same thread
@get:Rule
var instantTaskExecutorRule = InstantTaskExecutorRule()
// Overrides Dispatchers.Main used in Coroutines
@get:Rule
var coroutineRule = MainCoroutineRule()
private fun createMainActivityViewModel(
signInViewModelDelegate: SignInViewModelDelegate = FakeSignInViewModelDelegate(),
themedActivityDelegate: ThemedActivityDelegate = FakeThemedActivityDelegate()
): MainActivityViewModel {
return MainActivityViewModel(
signInViewModelDelegate = signInViewModelDelegate,
themedActivityDelegate = themedActivityDelegate,
loadPinnedSessionsUseCase = LoadPinnedSessionsJsonUseCase(
DefaultSessionAndUserEventRepository(
TestUserEventDataSource(), DefaultSessionRepository(TestDataRepository)
),
GsonBuilder().create(),
coroutineRule.testDispatcher
),
loadArDebugFlagUseCase = LoadArDebugFlagUseCase(
DefaultArDebugFlagEndpoint(
mock(FirebaseFunctions::class.java)
),
coroutineRule.testDispatcher
),
context = mock(Context::class.java)
)
}
@Test
fun notLoggedIn_profileClicked_showsSignInDialog() = runTest {
// Given a ViewModel with a signed out user
val signInViewModelDelegate = FakeSignInViewModelDelegate().apply {
injectIsSignedIn = false
}
val viewModel =
createMainActivityViewModel(signInViewModelDelegate = signInViewModelDelegate)
// When profile is clicked
viewModel.onProfileClicked()
// Then the sign in dialog should be shown
val signInEvent = viewModel.navigationActions.first()
assertEquals(signInEvent, MainNavigationAction.OpenSignIn)
}
@Test
fun loggedIn_profileClicked_showsSignOutDialog() = runTest {
// Given a ViewModel with a signed in user
val signInViewModelDelegate = FakeSignInViewModelDelegate().apply {
injectIsSignedIn = true
}
val viewModel =
createMainActivityViewModel(signInViewModelDelegate = signInViewModelDelegate)
// When profile is clicked
viewModel.onProfileClicked()
// Then the sign out dialog should be shown
val signOutEvent = viewModel.navigationActions.first()
assertEquals(signOutEvent, MainNavigationAction.OpenSignOut)
}
}
| apache-2.0 | c450f29a158a9d31fa4807b287b8c1ab | 40.954128 | 97 | 0.740214 | 5.373678 | false | true | false | false |
androidx/androidx | paging/integration-tests/testapp/src/main/java/androidx/paging/integration/testapp/v3/Item.kt | 3 | 1202 | /*
* 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.paging.integration.testapp.v3
import androidx.recyclerview.widget.DiffUtil
data class Item(val id: Int, val text: String, val bgColor: Int) {
companion object {
val DIFF_CALLBACK: DiffUtil.ItemCallback<Item> = object : DiffUtil.ItemCallback<Item>() {
override fun areContentsTheSame(oldItem: Item, newItem: Item): Boolean {
return oldItem == newItem
}
override fun areItemsTheSame(oldItem: Item, newItem: Item): Boolean {
return oldItem.id == newItem.id
}
}
}
} | apache-2.0 | 5e15aae720a6636076fc65ed4be861f2 | 35.454545 | 97 | 0.686356 | 4.485075 | false | false | false | false |
sjcl/LogicSummonerCode | src/旅立ちの街_フンケ/生け贄/夜との契約/sjcl/Main.kt | 1 | 1601 | /**
* Main.javaのKotlinバージョン。もっと良い書き方あるかも?
* 移植してから気がついた。Kotlinサポートされてないやん...
*/
package 旅立ちの街_フンケ.生け贄.夜との契約.sjcl
import java.util.Scanner
fun main(args: Array<String>) {
val sc = Scanner(System.`in`)
val size = sc.nextLine().toInt()
val magic = Array(size, { IntArray(size) })
for (w in 0..size - 1) {
val line = sc.nextLine().split(" ")
for (i in 0..size - 1)
magic[w][i] = line[i].toInt()
}
var total = 0
var validTotal = false
val zeroPos = arrayListOf<Pos>()
for (w in 0..size - 1) {
var zero = false
for (i in 0..size - 1) {
if (magic[w][i] == 0) {
zero = true
zeroPos.add(Pos(w, i))
}
if (!validTotal)
total += magic[w][i]
}
if (!zero)
validTotal = true
if (!validTotal)
total = 0
}
for ((x, y) in zeroPos) {
var lineTotal = 0
var zeroCount = 0
for (w in 0..size - 1) {
if (magic[w][y] == 0)
zeroCount++
lineTotal += magic[w][y]
}
if (zeroCount >= 2) {
lineTotal = 0
(0..size - 1).forEach { i -> lineTotal += magic[x][i] }
}
magic[x][y] = total - lineTotal
}
val op = buildString {
for (w in 0..size - 1)
appendln(magic[w].joinToString(" "))
}
println(op)
}
data class Pos(val x: Int, val y: Int)
| apache-2.0 | 52163d643477170fc888459f9eab5c26 | 25.052632 | 67 | 0.468013 | 3.179872 | false | false | false | false |
DSteve595/Put.io | app/src/main/java/com/stevenschoen/putionew/tv/TvPlayerActivity.kt | 1 | 4241 | package com.stevenschoen.putionew.tv
import android.net.Uri
import android.os.Bundle
import android.view.KeyEvent
import android.view.View
import android.view.WindowManager
import android.widget.TextView
import androidx.fragment.app.FragmentActivity
import com.google.android.exoplayer2.ExoPlayerFactory
import com.google.android.exoplayer2.SimpleExoPlayer
import com.google.android.exoplayer2.source.ExtractorMediaSource
import com.google.android.exoplayer2.trackselection.AdaptiveTrackSelection
import com.google.android.exoplayer2.trackselection.DefaultTrackSelector
import com.google.android.exoplayer2.ui.PlayerView
import com.google.android.exoplayer2.upstream.DefaultBandwidthMeter
import com.google.android.exoplayer2.upstream.DefaultDataSourceFactory
import com.google.android.exoplayer2.util.Util
import com.stevenschoen.putionew.R
import com.stevenschoen.putionew.model.files.PutioFile
import com.stevenschoen.putionew.putioApp
import org.apache.commons.io.FilenameUtils
class TvPlayerActivity : FragmentActivity() {
companion object {
const val EXTRA_VIDEO = "video"
const val EXTRA_USE_MP4 = "use_mp4"
}
private val video by lazy { intent.getParcelableExtra<PutioFile>(EXTRA_VIDEO)!! }
private val useMp4 by lazy { intent.getBooleanExtra(EXTRA_USE_MP4, false) }
private lateinit var player: SimpleExoPlayer
private lateinit var playerView: PlayerView
private var rewindView: View? = null
private var ffwdView: View? = null
private var controlsVisible = true
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.tv_player)
window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
val bandwidthMeter = DefaultBandwidthMeter()
val videoTrackSelectionFactory = AdaptiveTrackSelection.Factory(bandwidthMeter)
val trackSelector = DefaultTrackSelector(videoTrackSelectionFactory)
player = ExoPlayerFactory.newSimpleInstance(this, trackSelector)
playerView = findViewById(R.id.tv_player_exoplayer)
playerView.player = player
val dataSourceFactory = DefaultDataSourceFactory(
this,
Util.getUserAgent(this, "Put.io-for-Android"), bandwidthMeter
)
val url = video.getStreamUrl(putioApp.putioUtils!!, useMp4)
val videoSource = ExtractorMediaSource.Factory(dataSourceFactory::createDataSource).createMediaSource(Uri.parse(url))
player.playWhenReady = true
player.prepare(videoSource)
playerView.post {
val titleView = findViewById<TextView>(R.id.tv_player_title)
titleView.text = FilenameUtils.removeExtension(video.name)
rewindView = findViewById(R.id.exo_rew)
ffwdView = findViewById(R.id.exo_ffwd)
}
playerView.setControllerVisibilityListener { visibility ->
controlsVisible = visibility == View.VISIBLE
}
}
override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
return when (keyCode) {
KeyEvent.KEYCODE_DPAD_UP, KeyEvent.KEYCODE_DPAD_DOWN,
KeyEvent.KEYCODE_DPAD_LEFT, KeyEvent.KEYCODE_DPAD_RIGHT -> {
if (!controlsVisible) {
playerView.showController()
true
} else {
super.onKeyDown(keyCode, event)
}
}
else -> super.onKeyDown(keyCode, event)
}
}
override fun onKeyUp(keyCode: Int, event: KeyEvent): Boolean {
return when (keyCode) {
KeyEvent.KEYCODE_MEDIA_PLAY -> {
player.playWhenReady = true
true
}
KeyEvent.KEYCODE_MEDIA_PAUSE -> {
player.playWhenReady = false
true
}
KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE -> {
player.playWhenReady = !player.playWhenReady
true
}
KeyEvent.KEYCODE_MEDIA_REWIND -> {
playerView.showController()
rewindView?.callOnClick()
true
}
KeyEvent.KEYCODE_MEDIA_FAST_FORWARD -> {
playerView.showController()
ffwdView?.callOnClick()
true
}
else -> super.onKeyUp(keyCode, event)
}
}
override fun onBackPressed() {
if (controlsVisible) {
playerView.hideController()
} else {
super.onBackPressed()
}
}
override fun onDestroy() {
super.onDestroy()
player.release()
}
}
| mit | b555c088687543a80bbc29fa9811f569 | 30.649254 | 121 | 0.723414 | 4.408524 | false | false | false | false |
androidx/androidx | room/room-runtime/src/main/java/androidx/room/AutoClosingRoomOpenHelper.kt | 3 | 20973 | /*
* Copyright (C) 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.room
import android.content.ContentResolver
import android.content.ContentValues
import android.database.Cursor
import android.database.SQLException
import android.database.sqlite.SQLiteTransactionListener
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.os.CancellationSignal
import android.util.Pair
import androidx.annotation.RequiresApi
import androidx.sqlite.db.SupportSQLiteCompat
import androidx.sqlite.db.SupportSQLiteDatabase
import androidx.sqlite.db.SupportSQLiteOpenHelper
import androidx.sqlite.db.SupportSQLiteQuery
import androidx.sqlite.db.SupportSQLiteStatement
import java.io.IOException
import java.util.Locale
/**
* A SupportSQLiteOpenHelper that has auto close enabled for database connections.
*/
internal class AutoClosingRoomOpenHelper(
override val delegate: SupportSQLiteOpenHelper,
@JvmField
internal val autoCloser: AutoCloser
) : SupportSQLiteOpenHelper by delegate, DelegatingOpenHelper {
private val autoClosingDb: AutoClosingSupportSQLiteDatabase
init {
autoCloser.init(delegate)
autoClosingDb = AutoClosingSupportSQLiteDatabase(
autoCloser
)
}
@get:RequiresApi(api = Build.VERSION_CODES.N)
override val writableDatabase: SupportSQLiteDatabase
get() {
autoClosingDb.pokeOpen()
return autoClosingDb
}
@get:RequiresApi(api = Build.VERSION_CODES.N)
override val readableDatabase: SupportSQLiteDatabase
get() {
// Note we don't differentiate between writable db and readable db
// We try to open the db so the open callbacks run
autoClosingDb.pokeOpen()
return autoClosingDb
}
override fun close() {
autoClosingDb.close()
}
/**
* SupportSQLiteDatabase that also keeps refcounts and autocloses the database
*/
internal class AutoClosingSupportSQLiteDatabase(
private val autoCloser: AutoCloser
) : SupportSQLiteDatabase {
fun pokeOpen() {
autoCloser.executeRefCountingFunction<Any?> { null }
}
override fun compileStatement(sql: String): SupportSQLiteStatement {
return AutoClosingSupportSqliteStatement(sql, autoCloser)
}
override fun beginTransaction() {
// We assume that after every successful beginTransaction() call there *must* be a
// endTransaction() call.
val db = autoCloser.incrementCountAndEnsureDbIsOpen()
try {
db.beginTransaction()
} catch (t: Throwable) {
// Note: we only want to decrement the ref count if the beginTransaction call
// fails since there won't be a corresponding endTransaction call.
autoCloser.decrementCountAndScheduleClose()
throw t
}
}
override fun beginTransactionNonExclusive() {
// We assume that after every successful beginTransaction() call there *must* be a
// endTransaction() call.
val db = autoCloser.incrementCountAndEnsureDbIsOpen()
try {
db.beginTransactionNonExclusive()
} catch (t: Throwable) {
// Note: we only want to decrement the ref count if the beginTransaction call
// fails since there won't be a corresponding endTransaction call.
autoCloser.decrementCountAndScheduleClose()
throw t
}
}
override fun beginTransactionWithListener(transactionListener: SQLiteTransactionListener) {
// We assume that after every successful beginTransaction() call there *must* be a
// endTransaction() call.
val db = autoCloser.incrementCountAndEnsureDbIsOpen()
try {
db.beginTransactionWithListener(transactionListener)
} catch (t: Throwable) {
// Note: we only want to decrement the ref count if the beginTransaction call
// fails since there won't be a corresponding endTransaction call.
autoCloser.decrementCountAndScheduleClose()
throw t
}
}
override fun beginTransactionWithListenerNonExclusive(
transactionListener: SQLiteTransactionListener
) {
// We assume that after every successful beginTransaction() call there *will* always
// be a corresponding endTransaction() call. Without a corresponding
// endTransactionCall we will never close the db.
val db = autoCloser.incrementCountAndEnsureDbIsOpen()
try {
db.beginTransactionWithListenerNonExclusive(transactionListener)
} catch (t: Throwable) {
// Note: we only want to decrement the ref count if the beginTransaction call
// fails since there won't be a corresponding endTransaction call.
autoCloser.decrementCountAndScheduleClose()
throw t
}
}
override fun endTransaction() {
checkNotNull(autoCloser.delegateDatabase) {
"End transaction called but delegateDb is null"
}
try {
autoCloser.delegateDatabase!!.endTransaction()
} finally {
autoCloser.decrementCountAndScheduleClose()
}
}
override fun setTransactionSuccessful() {
autoCloser.delegateDatabase?.setTransactionSuccessful() ?: error(
"setTransactionSuccessful called but delegateDb is null"
)
}
override fun inTransaction(): Boolean {
return if (autoCloser.delegateDatabase == null) {
false
} else {
autoCloser.executeRefCountingFunction(SupportSQLiteDatabase::inTransaction)
}
}
override val isDbLockedByCurrentThread: Boolean
get() = if (autoCloser.delegateDatabase == null) {
false
} else {
autoCloser.executeRefCountingFunction(
SupportSQLiteDatabase::isDbLockedByCurrentThread
)
}
override fun yieldIfContendedSafely(): Boolean {
return autoCloser.executeRefCountingFunction(
SupportSQLiteDatabase::yieldIfContendedSafely
)
}
override fun yieldIfContendedSafely(sleepAfterYieldDelayMillis: Long): Boolean {
return autoCloser.executeRefCountingFunction(
SupportSQLiteDatabase::yieldIfContendedSafely
)
}
override var version: Int
get() = autoCloser.executeRefCountingFunction(
SupportSQLiteDatabase::version
)
set(version) {
autoCloser.executeRefCountingFunction<Any?> { db: SupportSQLiteDatabase ->
db.version = version
null
}
}
override val maximumSize: Long
get() = autoCloser.executeRefCountingFunction(
SupportSQLiteDatabase::maximumSize
)
override fun setMaximumSize(numBytes: Long): Long {
return autoCloser.executeRefCountingFunction {
db: SupportSQLiteDatabase -> db.setMaximumSize(numBytes)
}
}
override var pageSize: Long
get() = autoCloser.executeRefCountingFunction(SupportSQLiteDatabase::pageSize)
set(numBytes) {
autoCloser.executeRefCountingFunction<Any?> { db: SupportSQLiteDatabase ->
db.pageSize = numBytes
null
}
}
override fun query(query: String): Cursor {
val result = try {
autoCloser.incrementCountAndEnsureDbIsOpen().query(query)
} catch (throwable: Throwable) {
autoCloser.decrementCountAndScheduleClose()
throw throwable
}
return KeepAliveCursor(result, autoCloser)
}
override fun query(query: String, bindArgs: Array<out Any?>): Cursor {
val result = try {
autoCloser.incrementCountAndEnsureDbIsOpen().query(query, bindArgs)
} catch (throwable: Throwable) {
autoCloser.decrementCountAndScheduleClose()
throw throwable
}
return KeepAliveCursor(result, autoCloser)
}
override fun query(query: SupportSQLiteQuery): Cursor {
val result = try {
autoCloser.incrementCountAndEnsureDbIsOpen().query(query)
} catch (throwable: Throwable) {
autoCloser.decrementCountAndScheduleClose()
throw throwable
}
return KeepAliveCursor(result, autoCloser)
}
@RequiresApi(api = Build.VERSION_CODES.N)
override fun query(
query: SupportSQLiteQuery,
cancellationSignal: CancellationSignal?
): Cursor {
val result = try {
autoCloser.incrementCountAndEnsureDbIsOpen().query(query, cancellationSignal)
} catch (throwable: Throwable) {
autoCloser.decrementCountAndScheduleClose()
throw throwable
}
return KeepAliveCursor(result, autoCloser)
}
@Throws(SQLException::class)
override fun insert(table: String, conflictAlgorithm: Int, values: ContentValues): Long {
return autoCloser.executeRefCountingFunction { db: SupportSQLiteDatabase ->
db.insert(
table, conflictAlgorithm,
values
)
}
}
override fun delete(table: String, whereClause: String?, whereArgs: Array<out Any?>?): Int {
return autoCloser.executeRefCountingFunction { db: SupportSQLiteDatabase ->
db.delete(
table,
whereClause,
whereArgs
)
}
}
override fun update(
table: String,
conflictAlgorithm: Int,
values: ContentValues,
whereClause: String?,
whereArgs: Array<out Any?>?
): Int {
return autoCloser.executeRefCountingFunction { db: SupportSQLiteDatabase ->
db.update(
table, conflictAlgorithm,
values, whereClause, whereArgs
)
}
}
@Throws(SQLException::class)
override fun execSQL(sql: String) {
autoCloser.executeRefCountingFunction<Any?> { db: SupportSQLiteDatabase ->
db.execSQL(sql)
null
}
}
@Throws(SQLException::class)
override fun execSQL(sql: String, bindArgs: Array<out Any?>) {
autoCloser.executeRefCountingFunction<Any?> { db: SupportSQLiteDatabase ->
db.execSQL(sql, bindArgs)
null
}
}
override val isReadOnly: Boolean
get() = autoCloser.executeRefCountingFunction { obj: SupportSQLiteDatabase ->
obj.isReadOnly
}
override val isOpen: Boolean
get() {
// Get the db without incrementing the reference cause we don't want to open
// the db for an isOpen call.
val localDelegate = autoCloser.delegateDatabase ?: return false
return localDelegate.isOpen
}
override fun needUpgrade(newVersion: Int): Boolean {
return autoCloser.executeRefCountingFunction { db: SupportSQLiteDatabase ->
db.needUpgrade(
newVersion
)
}
}
override val path: String?
get() = autoCloser.executeRefCountingFunction { obj: SupportSQLiteDatabase ->
obj.path
}
override fun setLocale(locale: Locale) {
autoCloser.executeRefCountingFunction<Any?> { db: SupportSQLiteDatabase ->
db.setLocale(locale)
null
}
}
override fun setMaxSqlCacheSize(cacheSize: Int) {
autoCloser.executeRefCountingFunction<Any?> { db: SupportSQLiteDatabase ->
db.setMaxSqlCacheSize(cacheSize)
null
}
}
@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
override fun setForeignKeyConstraintsEnabled(enabled: Boolean) {
autoCloser.executeRefCountingFunction<Any?> { db: SupportSQLiteDatabase ->
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
db.setForeignKeyConstraintsEnabled(enabled)
}
null
}
}
override fun enableWriteAheadLogging(): Boolean {
throw UnsupportedOperationException(
"Enable/disable write ahead logging on the " +
"OpenHelper instead of on the database directly."
)
}
override fun disableWriteAheadLogging() {
throw UnsupportedOperationException(
"Enable/disable write ahead logging on the " +
"OpenHelper instead of on the database directly."
)
}
@get:RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
override val isWriteAheadLoggingEnabled: Boolean
get() = autoCloser.executeRefCountingFunction { db: SupportSQLiteDatabase ->
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
return@executeRefCountingFunction db.isWriteAheadLoggingEnabled
}
false
}
override val attachedDbs: List<Pair<String, String>>?
get() = autoCloser.executeRefCountingFunction {
obj: SupportSQLiteDatabase -> obj.attachedDbs
}
override val isDatabaseIntegrityOk: Boolean
get() = autoCloser.executeRefCountingFunction {
obj: SupportSQLiteDatabase -> obj.isDatabaseIntegrityOk
}
@Throws(IOException::class)
override fun close() {
autoCloser.closeDatabaseIfOpen()
}
}
/**
* We need to keep the db alive until the cursor is closed, so we can't decrement our
* reference count until the cursor is closed. The underlying database will not close until
* this cursor is closed.
*/
private class KeepAliveCursor(
private val delegate: Cursor,
private val autoCloser: AutoCloser
) : Cursor by delegate {
// close is the only important/changed method here:
override fun close() {
delegate.close()
autoCloser.decrementCountAndScheduleClose()
}
@RequiresApi(api = Build.VERSION_CODES.Q)
override fun setNotificationUris(
cr: ContentResolver,
uris: List<Uri>
) {
SupportSQLiteCompat.Api29Impl.setNotificationUris(delegate, cr, uris)
}
@RequiresApi(api = Build.VERSION_CODES.KITKAT)
override fun getNotificationUri(): Uri {
return SupportSQLiteCompat.Api19Impl.getNotificationUri(delegate)
}
@RequiresApi(api = Build.VERSION_CODES.Q)
override fun getNotificationUris(): List<Uri> {
return SupportSQLiteCompat.Api29Impl.getNotificationUris(delegate)
}
@RequiresApi(api = Build.VERSION_CODES.M)
override fun setExtras(extras: Bundle) {
SupportSQLiteCompat.Api23Impl.setExtras(delegate, extras)
}
}
/**
* We can't close our db if the SupportSqliteStatement is open.
*
* Each of these that are created need to be registered with RefCounter.
*
* On auto-close, RefCounter needs to close each of these before closing the db that these
* were constructed from.
*
* Each of the methods here need to get
*/
// TODO(rohitsat) cache the prepared statement... I'm not sure what the performance implications
// are for the way it's done here, but caching the prepared statement would definitely be more
// complicated since we need to invalidate any of the PreparedStatements that were created
// with this db
private class AutoClosingSupportSqliteStatement(
private val sql: String,
private val autoCloser: AutoCloser
) : SupportSQLiteStatement {
private val binds = ArrayList<Any?>()
private fun <T> executeSqliteStatementWithRefCount(
block: (SupportSQLiteStatement) -> T
): T {
return autoCloser.executeRefCountingFunction { db: SupportSQLiteDatabase ->
val statement: SupportSQLiteStatement = db.compileStatement(sql)
doBinds(statement)
block(statement)
}
}
private fun doBinds(supportSQLiteStatement: SupportSQLiteStatement) {
// Replay the binds
binds.forEachIndexed { i, _ ->
val bindIndex = i + 1 // Bind indices are 1 based so we start at 1 not 0
when (val bind = binds[i]) {
null -> {
supportSQLiteStatement.bindNull(bindIndex)
}
is Long -> {
supportSQLiteStatement.bindLong(bindIndex, bind)
}
is Double -> {
supportSQLiteStatement.bindDouble(bindIndex, bind)
}
is String -> {
supportSQLiteStatement.bindString(bindIndex, bind)
}
is ByteArray -> {
supportSQLiteStatement.bindBlob(bindIndex, bind)
}
}
}
}
private fun saveBinds(bindIndex: Int, value: Any?) {
val index = bindIndex - 1
if (index >= binds.size) {
// Add null entries to the list until we have the desired # of indices
for (i in binds.size..index) {
binds.add(null)
}
}
binds[index] = value
}
@Throws(IOException::class)
override fun close() {
// Nothing to do here since we re-compile the statement each time.
}
override fun execute() {
executeSqliteStatementWithRefCount<Any?> { statement: SupportSQLiteStatement ->
statement.execute()
null
}
}
override fun executeUpdateDelete(): Int {
return executeSqliteStatementWithRefCount { obj: SupportSQLiteStatement ->
obj.executeUpdateDelete() }
}
override fun executeInsert(): Long {
return executeSqliteStatementWithRefCount { obj: SupportSQLiteStatement ->
obj.executeInsert()
}
}
override fun simpleQueryForLong(): Long {
return executeSqliteStatementWithRefCount { obj: SupportSQLiteStatement ->
obj.simpleQueryForLong()
}
}
override fun simpleQueryForString(): String? {
return executeSqliteStatementWithRefCount { obj: SupportSQLiteStatement ->
obj.simpleQueryForString()
}
}
override fun bindNull(index: Int) {
saveBinds(index, null)
}
override fun bindLong(index: Int, value: Long) {
saveBinds(index, value)
}
override fun bindDouble(index: Int, value: Double) {
saveBinds(index, value)
}
override fun bindString(index: Int, value: String) {
saveBinds(index, value)
}
override fun bindBlob(index: Int, value: ByteArray) {
saveBinds(index, value)
}
override fun clearBindings() {
binds.clear()
}
}
} | apache-2.0 | 50f0e2309c1893baf1ccbe4645b300cf | 35.796491 | 100 | 0.589901 | 6.03019 | false | false | false | false |
scenerygraphics/SciView | src/main/kotlin/sc/iview/commands/edit/add/AddBox.kt | 1 | 2887 | /*-
* #%L
* Scenery-backed 3D visualization package for ImageJ.
* %%
* Copyright (C) 2016 - 2021 SciView developers.
* %%
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
* #L%
*/
package sc.iview.commands.edit.add
import org.joml.Vector3f
import org.scijava.command.Command
import org.scijava.display.DisplayService
import org.scijava.plugin.Menu
import org.scijava.plugin.Parameter
import org.scijava.plugin.Plugin
import org.scijava.util.ColorRGB
import sc.iview.SciView
import sc.iview.commands.MenuWeights.EDIT
import sc.iview.commands.MenuWeights.EDIT_ADD
import sc.iview.commands.MenuWeights.EDIT_ADD_BOX
/**
* Command to add a box to the scene
*
* @author Kyle Harrington
*/
@Plugin(
type = Command::class,
menuRoot = "SciView",
menu = [Menu(label = "Edit", weight = EDIT), Menu(label = "Add", weight = EDIT_ADD), Menu(
label = "Box...",
weight = EDIT_ADD_BOX
)]
)
class AddBox : Command {
@Parameter
private lateinit var displayService: DisplayService
@Parameter
private lateinit var sciView: SciView
// FIXME
// @Parameter
// private String position = "0; 0; 0";
@Parameter
private var size = 1.0f
@Parameter
private lateinit var color: ColorRGB
@Parameter
private var inside = false
override fun run() {
//final Vector3 pos = ClearGLVector3.parse( position );
val pos = Vector3f(0f, 0f, 0f)
val vSize = Vector3f(size, size, size)
if( !this::color.isInitialized ) {
color = SciView.DEFAULT_COLOR
}
sciView.addBox(pos, vSize, color, inside)
}
} | bsd-2-clause | d612747dfb7cd8ec795615bc0afd8a03 | 32.581395 | 94 | 0.712158 | 4.089235 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/RemoveSingleLambdaParameterFix.kt | 2 | 2366 | // 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.quickfix
import com.intellij.codeInsight.intention.IntentionAction
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import org.jetbrains.kotlin.diagnostics.Diagnostic
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.codeinsight.api.classic.quickfixes.KotlinQuickFixAction
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.getQualifiedExpressionForReceiver
import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType
class RemoveSingleLambdaParameterFix(element: KtParameter) : KotlinQuickFixAction<KtParameter>(element) {
override fun getFamilyName() = KotlinBundle.message("remove.single.lambda.parameter.declaration")
override fun getText() = familyName
override fun invoke(project: Project, editor: Editor?, file: KtFile) {
val element = element ?: return
val parameterList = element.parent as? KtParameterList ?: return
val ownerFunction = parameterList.ownerFunction ?: return
val arrow = ownerFunction.node.findChildByType(KtTokens.ARROW) ?: return
parameterList.delete()
ownerFunction.node.removeChild(arrow)
}
companion object : KotlinSingleIntentionActionFactory() {
override fun createAction(diagnostic: Diagnostic): IntentionAction? {
val parameter = diagnostic.psiElement as? KtParameter ?: return null
val parameterList = parameter.parent as? KtParameterList ?: return null
if (parameterList.parameters.size != 1) return null
val lambda = parameterList.parent.parent as? KtLambdaExpression ?: return null
val lambdaParent = lambda.parent
if (lambdaParent is KtWhenEntry || lambdaParent is KtContainerNodeForControlStructureBody) return null
if (lambda.getQualifiedExpressionForReceiver() != null) return null
val property = lambda.getStrictParentOfType<KtProperty>()
if (property != null && property.typeReference == null) return null
return RemoveSingleLambdaParameterFix(parameter)
}
}
} | apache-2.0 | a4798403b0ace00a7e7fcd4e9f73d2b5 | 46.34 | 158 | 0.749366 | 5.269488 | false | false | false | false |
tginsberg/advent-2016-kotlin | src/main/kotlin/com/ginsberg/advent2016/Day24.kt | 1 | 2917 | /*
* Copyright (c) 2016 by Todd Ginsberg
*/
package com.ginsberg.advent2016
import com.ginsberg.advent2016.utils.asDigit
import java.util.ArrayDeque
/**
* Advent of Code - Day 24: December 24, 2016
*
* From http://adventofcode.com/2016/day/24
*
*/
class Day24(val input: List<String>) {
val board: List<List<Spot>> = parseInput()
val numberedSpots: Map<Int, Spot> = findNumberedSpots(board)
val distances: Map<Pair<Int, Int>, Int> = mapAllDistances(numberedSpots)
private fun mapAllDistances(numberedSpots: Map<Int, Spot>): Map<Pair<Int, Int>, Int> {
val oneWay = numberedSpots.flatMap { l ->
numberedSpots.filter { l.key < it.key }.map { r -> Pair(l.key, r.key) to search(l.value, r.value) }
}.toMap()
return oneWay.plus(oneWay.map { Pair(it.key.second, it.key.first) to it.value })
}
fun solvePart1(): Int =
findMinPath(numberedSpots.keys)
fun solvePart2(): Int =
findMinPath(numberedSpots.keys, true)
fun search(from: Spot, to: Spot): Int {
val visited = mutableMapOf(from to 0)
val queue = ArrayDeque<Spot>().apply { add(from) }
while (queue.isNotEmpty()) {
val current = queue.poll()
val dist = visited[current]!!
if (current == to) {
return dist
}
val neighbors = listOf(
board[current.x][current.y - 1],
board[current.x][current.y + 1],
board[current.x - 1][current.y],
board[current.x + 1][current.y])
.filter { it.isValid() && !it.isWall() }
.filterNot { it in visited }
visited.putAll(neighbors.map { it to dist + 1 })
queue.addAll(neighbors)
}
return 0
}
private fun parseInput(): List<List<Spot>> =
(0..input.size - 1).map { x ->
(0..input[x].length - 1).map { y ->
Spot(x, y, input[x][y])
}
}
private fun findNumberedSpots(board: List<List<Spot>>): Map<Int, Spot> =
board.flatMap { it.filter { it.getGoalNumber() != null } }.associateBy { it.getGoalNumber()!! }
private fun findMinPath(all: Set<Int>, loopBack: Boolean = false): Int {
fun inner(unvisited: Set<Int>, at: Int = 0, acc: Int = 0): Int =
if (unvisited.isEmpty()) acc + (if (loopBack) distances[Pair(at, 0)]!! else 0)
else all.filter { it in unvisited }.map { it -> inner(unvisited.minus(it), it, acc + distances[Pair(at, it)]!!) }.min()!!
return inner(all.minus(0), 0, 0)
}
data class Spot(val x: Int, val y: Int, val contains: Char) {
fun isValid(): Boolean = x >= 0 && y >= 0
fun isWall(): Boolean = contains == '#'
fun getGoalNumber(): Int? = try {
contains.asDigit()
} catch(e: Exception) {
null
}
}
}
| mit | 775e460827670508b2fa92bd9f9b5e64 | 33.72619 | 133 | 0.555708 | 3.683081 | false | false | false | false |
DuckDeck/AndroidDemo | app/src/main/java/stan/androiddemo/store/ContentProvider/ContentProviderActivity.kt | 1 | 3449 | package stan.androiddemo.store.ContentProvider
import android.content.pm.PackageManager
import android.database.Cursor
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.provider.ContactsContract
import android.support.v4.app.ActivityCompat
import android.support.v4.content.ContextCompat
import android.widget.ArrayAdapter
import android.widget.Toast
import kotlinx.android.synthetic.main.activity_content_provider.*
import stan.androiddemo.R
class ContentProviderActivity : AppCompatActivity() {
lateinit var adapter: ArrayAdapter<String>
var arrContactList = ArrayList<String>()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_content_provider)
adapter = ArrayAdapter(this,android.R.layout.simple_list_item_1,arrContactList)
list_view_contact.adapter = adapter
if (ContextCompat.checkSelfPermission(this,android.Manifest.permission.READ_CONTACTS) != PackageManager.PERMISSION_GRANTED){
ActivityCompat.requestPermissions(this,arrayOf(android.Manifest.permission.READ_CONTACTS),1)
}
else{
readContacts()
}
}
fun readContacts(){
var cursor: Cursor? = null
var phoneCursor:Cursor?
try {
cursor = contentResolver.query(ContactsContract.Contacts.CONTENT_URI,null,null,null,null)
if (cursor != null){
while (cursor.moveToNext()){
val sb = StringBuilder()
val contactId = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID))
val name = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME))
// val number = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER))
// arrContactList.add(name + "\n" + number)
//真不知道你这电话号码读取API是怎么设计的
//书上是错的,读取电话号要新建一个cursor
phoneCursor = contentResolver.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,ContactsContract.CommonDataKinds.Phone.CONTACT_ID + "=" + contactId,null,null)
while(phoneCursor.moveToNext()){
val num = phoneCursor.getString(phoneCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER))
sb.append("Phone=").append(num)
}
phoneCursor.close()
arrContactList.add(name + "\n" + sb.toString())
}
adapter.notifyDataSetChanged()
}
}
catch (e:Exception){
e.printStackTrace()
}
finally {
if (cursor!=null){
cursor.close()
}
}
}
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
when(requestCode){
1->
if (grantResults.isNotEmpty() &&grantResults[0]== PackageManager.PERMISSION_GRANTED){
readContacts()
}
else {
Toast.makeText(this,"You denied the perssion",Toast.LENGTH_LONG).show()
}
}
}
}
| mit | ecd82184f9b8b0009fe37c13d2ca74b9 | 41.2625 | 132 | 0.624076 | 5.008889 | false | false | false | false |
sksamuel/ktest | kotest-framework/kotest-framework-api/src/commonMain/kotlin/io/kotest/core/config/Defaults.kt | 1 | 1355 | package io.kotest.core.config
import io.kotest.core.spec.IsolationMode
import io.kotest.core.spec.SpecExecutionOrder
import io.kotest.core.test.AssertionMode
import io.kotest.core.test.DuplicateTestNameMode
import io.kotest.core.test.TestCaseConfig
import io.kotest.core.test.TestCaseOrder
import io.kotest.core.test.TestNameCase
object Defaults {
val assertionMode: AssertionMode = AssertionMode.None
val testCaseConfig: TestCaseConfig = TestCaseConfig()
val testCaseOrder: TestCaseOrder = TestCaseOrder.Sequential
val isolationMode: IsolationMode = IsolationMode.SingleInstance
val duplicateTestNameMode: DuplicateTestNameMode = DuplicateTestNameMode.Warn
const val failOnEmptyTestSuite = false
const val specFailureFilePath: String = "./.kotest/spec_failures"
const val parallelism: Int = 1
const val defaultTimeoutInMillis: Long = 600 * 1000L
const val defaultInvocationTimeoutInMillis: Long = 600 * 1000L
const val failOnIgnoredTests: Boolean = false
val defaultIncludeTestScopeAffixes: Boolean? = null
const val writeSpecFailureFile = false
const val globalAssertSoftly = false
val defaultTestNameCase: TestNameCase = TestNameCase.AsIs
val specExecutionOrder = SpecExecutionOrder.Lexicographic
const val concurrentTests = Configuration.Sequential
const val dispatcherAffinity = true
}
| mit | 1e024935ce04196635d572a466dffee4 | 34.657895 | 80 | 0.805166 | 4.891697 | false | true | false | false |
piotrwalkusz1/LEBRB | lanlearn/src/main/kotlin/com/piotrwalkusz/lebrb/lanlearn/lemmatizers/LanguageToolLemmatizer.kt | 1 | 1535 | package com.piotrwalkusz.lebrb.lanlearn.lemmatizers
import com.piotrwalkusz.lebrb.lanlearn.Language
import org.languagetool.tagging.Tagger
import org.languagetool.tagging.de.GermanTagger
import org.languagetool.tagging.en.EnglishTagger
import java.io.Reader
class LanguageToolLemmatizer(language: Language) : Lemmatizer {
private val tagger: Tagger = when (language) {
Language.GERMAN -> GermanTagger()
Language.ENGLISH -> EnglishTagger()
else -> throw IllegalArgumentException("LanguageToolLemmatizer does not support the $language language")
}
override fun lemmatize(source: Reader, dictionary: Set<String>): Map<String, Int> {
val words = splitTextToWords(source)
val wordsFrequency = mutableMapOf<String, Int>()
for (word in words) {
val lemma = lemmatizeWord(word).find { dictionary.contains(it) }
if (lemma != null) {
wordsFrequency.merge(lemma, 1, Int::plus)
continue
}
val lowerCaseWord = word.toLowerCase()
if (dictionary.contains(lowerCaseWord)) {
wordsFrequency.merge(lowerCaseWord, 1, Int::plus)
}
}
return wordsFrequency
}
private fun splitTextToWords(source: Reader): List<String> {
return source.readText().split(Regex("\\P{L}"))
}
private fun lemmatizeWord(word: String): List<String> {
return tagger.tag(listOf(word))[0].mapNotNull { it.lemma?.toLowerCase() }.distinct()
}
} | mit | 1a9de82eadba614d5f82191e12749bd1 | 31.680851 | 112 | 0.656678 | 4.217033 | false | false | false | false |
d9n/trypp.support | src/main/code/trypp/support/math/MathUtils.kt | 1 | 1181 | package trypp.support.math
/**
* Return log₂ of value, rounded up to an integer ceiling.
*
* e.g. `log2(1) -> 0`, `log2(4) -> 2`, `log2(5) -> 3`, `log2(8) -> 3`
*/
fun log2(value: Int): Int {
if (value < 0) {
throw IllegalArgumentException("Log2 must take a value >= 1. Got: $value")
}
var valueCopy = value
var log2 = 0
while (valueCopy > 1) {
valueCopy = valueCopy shr 1
log2++
}
if (!isPowerOfTwo(value)) {
log2++ // Round up to the power of two ceiling. For example, 4 -> 4, 5 -> 8, 8 -> 8, 9 -> 16, etc.
}
return log2
}
fun isPowerOfTwo(value: Int): Boolean {
// See http://stackoverflow.com/a/19383296/1299302
return value and value - 1 == 0
}
fun clamp(value: Int, min: Int, max: Int): Int {
if (min > max) {
throw IllegalArgumentException("Called clamp with min > max (min: $min, max: $max")
}
return Math.max(min, Math.min(max, value))
}
fun clamp(value: Float, min: Float, max: Float): Float {
if (min > max) {
throw IllegalArgumentException("Called clamp with min > max (min: $min, max: $max")
}
return Math.max(min, Math.min(max, value))
}
| mit | c95eebf9d52d784249c129fcbb5e161f | 25.795455 | 106 | 0.582697 | 3.152406 | false | false | false | false |
savoirfairelinux/ring-client-android | ring-android/app/src/main/java/cx/ring/client/ConversationSelectionActivity.kt | 1 | 3865 | /*
* Copyright (C) 2004-2021 Savoir-faire Linux Inc.
*
* Author: Adrien Béraud <[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 cx.ring.client
import android.content.Intent
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import cx.ring.R
import cx.ring.adapters.SmartListAdapter
import cx.ring.application.JamiApplication
import cx.ring.utils.ConversationPath
import cx.ring.viewholders.SmartListViewHolder.SmartListListeners
import dagger.hilt.android.AndroidEntryPoint
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers
import io.reactivex.rxjava3.disposables.CompositeDisposable
import net.jami.services.ConversationFacade
import net.jami.model.Conference
import net.jami.model.Conversation
import net.jami.services.CallService
import net.jami.services.NotificationService
import javax.inject.Inject
import javax.inject.Singleton
@AndroidEntryPoint
class ConversationSelectionActivity : AppCompatActivity() {
private val mDisposable = CompositeDisposable()
@Inject
@Singleton lateinit
var mConversationFacade: ConversationFacade
@Inject
@Singleton lateinit
var mCallService: CallService
var adapter: SmartListAdapter? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.frag_selectconv)
val list = findViewById<RecyclerView>(R.id.conversationList)
list.layoutManager = LinearLayoutManager(this)
list.adapter = SmartListAdapter(null, object : SmartListListeners {
override fun onItemClick(item: Conversation) {
setResult(RESULT_OK, Intent().apply {
data = ConversationPath.toUri(item.accountId, item.uri)
})
finish()
}
override fun onItemLongClick(item: Conversation) {}
}, mConversationFacade, mDisposable)
.apply { adapter = this }
JamiApplication.instance?.startDaemon()
}
public override fun onStart() {
super.onStart()
val conference: Conference? = intent?.getStringExtra(NotificationService.KEY_CALL_ID)?.let { confId -> mCallService.getConference(confId) }
mDisposable.add(mConversationFacade
.getConversationSmartlist()
.map { vm: List<Conversation> ->
if (conference == null) return@map vm
return@map vm.filter { v ->
val contact = v.contact ?: return@filter true
for (call in conference.participants) {
if (call.contact === contact) {
return@filter false
}
}
return@filter true
}
}
.observeOn(AndroidSchedulers.mainThread())
.subscribe { list -> adapter?.update(list) })
}
public override fun onStop() {
super.onStop()
mDisposable.clear()
}
public override fun onDestroy() {
super.onDestroy()
adapter = null
}
}
| gpl-3.0 | eb2f01301f797fe8e203c0bcf9c3b399 | 35.8 | 147 | 0.679089 | 4.82397 | false | false | false | false |
RocketChat/Rocket.Chat.Android | app/src/main/java/chat/rocket/android/infrastructure/LocalRepository.kt | 2 | 1319 | package chat.rocket.android.infrastructure
import chat.rocket.common.model.User
interface LocalRepository {
fun save(key: String, value: String?)
fun save(key: String, value: Boolean)
fun save(key: String, value: Int)
fun save(key: String, value: Long)
fun save(key: String, value: Float)
fun get(key: String, defValue: String? = null): String?
fun getBoolean(key: String, defValue: Boolean = false): Boolean
fun getFloat(key: String, defValue: Float = -1f): Float
fun getInt(key: String, defValue: Int = -1): Int
fun getLong(key: String, defValue: Long = -1L): Long
fun clear(key: String)
fun clearAllFromServer(server: String)
fun getCurrentUser(url: String): User?
fun saveCurrentUser(url: String, user: User)
fun saveLastChatroomsRefresh(url: String, timestamp: Long)
fun getLastChatroomsRefresh(url: String): Long
companion object {
const val TOKEN_KEY = "token_"
const val SETTINGS_KEY = "settings_"
const val PERMISSIONS_KEY = "permissions_"
const val USER_KEY = "user_"
const val DRAFT_KEY = "draft"
const val CURRENT_USERNAME_KEY = "username_"
const val LAST_CHATROOMS_REFRESH = "_chatrooms_refresh"
}
}
fun LocalRepository.username() = get(LocalRepository.CURRENT_USERNAME_KEY) | mit | 7ca91807a1b241edaa184924a7d82c69 | 37.823529 | 74 | 0.682335 | 3.902367 | false | false | false | false |
Esri/arcgis-runtime-samples-android | kotlin/raster-function-service/src/main/java/com/esri/arcgisruntime/sample/rasterfunctionservice/MainActivity.kt | 1 | 4042 | /*
* Copyright 2020 Esri
*
* 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.esri.arcgisruntime.sample.rasterfunctionservice
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import com.esri.arcgisruntime.ArcGISRuntimeEnvironment
import com.esri.arcgisruntime.layers.RasterLayer
import com.esri.arcgisruntime.loadable.LoadStatus
import com.esri.arcgisruntime.mapping.ArcGISMap
import com.esri.arcgisruntime.mapping.BasemapStyle
import com.esri.arcgisruntime.mapping.view.MapView
import com.esri.arcgisruntime.raster.ImageServiceRaster
import com.esri.arcgisruntime.raster.Raster
import com.esri.arcgisruntime.raster.RasterFunction
import com.esri.arcgisruntime.sample.rasterfunctionservice.databinding.ActivityMainBinding
class MainActivity : AppCompatActivity() {
private val activityMainBinding by lazy {
ActivityMainBinding.inflate(layoutInflater)
}
private val mapView: MapView by lazy {
activityMainBinding.mapView
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(activityMainBinding.root)
// authentication with an API key or named user is required to access basemaps and other
// location services
ArcGISRuntimeEnvironment.setApiKey(BuildConfig.API_KEY)
// create a Dark Gray Vector BaseMap
val map = ArcGISMap(BasemapStyle.ARCGIS_DARK_GRAY)
// set the map to be displayed in this view
mapView.map = map
// create image service raster as raster layer
val imageServiceRaster = ImageServiceRaster(
resources.getString(R.string.image_service_raster_url)
)
val imageRasterLayer = RasterLayer(imageServiceRaster)
map.operationalLayers.add(imageRasterLayer)
// zoom to the extent of the raster service
imageRasterLayer.addDoneLoadingListener {
if (imageRasterLayer.loadStatus == LoadStatus.LOADED) {
// zoom to extent of raster
val centerPnt = imageServiceRaster.serviceInfo.fullExtent.center
mapView.setViewpointCenterAsync(centerPnt, 55000000.0)
// update raster with simplified hillshade
applyRasterFunction(imageServiceRaster)
}
}
}
/**
* Apply a raster function on the given Raster
*
* @param raster Input raster to apply function
*/
private fun applyRasterFunction(raster: Raster) {
// create raster function from json string
val rasterFunction =
RasterFunction.fromJson(resources.getString(R.string.hillshade_simplified))
// get parameter name value pairs used by hillshade
val rasterFunctionArguments = rasterFunction.arguments
// get list of raster names associated with raster function
val rasterName = rasterFunctionArguments.rasterNames
// set raster to the raster name
rasterFunctionArguments.setRaster(rasterName[0], raster)
// create raster as raster layer
val raster = Raster(rasterFunction)
val hillshadeLayer = RasterLayer(raster)
// add hillshade raster
mapView.map.operationalLayers.add(hillshadeLayer)
}
override fun onPause() {
super.onPause()
mapView.pause()
}
override fun onResume() {
super.onResume()
mapView.resume()
}
override fun onDestroy() {
super.onDestroy()
mapView.dispose()
}
}
| apache-2.0 | f777f278b4c52bf8b16eb0f67c9ac856 | 36.082569 | 96 | 0.707076 | 4.97171 | false | false | false | false |
soeminnminn/EngMyanDictionary | app/src/main/java/com/s16/engmyan/utils/UIManager.kt | 1 | 1887 | package com.s16.engmyan.utils
import android.content.Context
import android.content.Intent
import androidx.appcompat.app.AppCompatDelegate
import androidx.core.content.pm.ShortcutInfoCompat
import androidx.core.content.pm.ShortcutManagerCompat
import androidx.core.graphics.drawable.IconCompat
import com.s16.engmyan.Constants
import com.s16.engmyan.R
import com.s16.engmyan.activity.DetailsActivity
import com.s16.engmyan.data.FavoriteItem
object UIManager {
fun setTheme(selectedOption: String?) {
val mode = when(selectedOption) {
Constants.PREFS_THEMES_LIGHT -> AppCompatDelegate.MODE_NIGHT_NO
Constants.PREFS_THEMES_DARK -> AppCompatDelegate.MODE_NIGHT_YES
Constants.PREFS_THEMES_BATTERY -> AppCompatDelegate.MODE_NIGHT_AUTO_BATTERY
else -> AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM
}
AppCompatDelegate.setDefaultNightMode(mode)
}
fun createShortcuts(context: Context, list: List<FavoriteItem>) {
ShortcutManagerCompat.removeAllDynamicShortcuts(context)
val shortcuts : MutableList<ShortcutInfoCompat> = mutableListOf()
for(fav in list) {
val shortcutIntent = Intent(context.applicationContext, DetailsActivity::class.java)
shortcutIntent.action = Intent.ACTION_VIEW
shortcutIntent.putExtra(Constants.ARG_PARAM_ID, fav.refId)
val shortcut = ShortcutInfoCompat.Builder(context, "${fav.refId})")
.setShortLabel("${fav.word}")
.setLongLabel(context.getString(R.string.title_shortcut, "${fav.word}"))
.setIcon(IconCompat.createWithResource(context, R.drawable.ic_shortcut_definition))
.setIntent(shortcutIntent)
.build()
shortcuts.add(shortcut)
}
ShortcutManagerCompat.addDynamicShortcuts(context, shortcuts)
}
} | gpl-2.0 | f4d1f7b940ae6c3c3bd71fb29bdb3532 | 41.909091 | 99 | 0.707472 | 4.777215 | false | false | false | false |
UweTrottmann/SeriesGuide | app/src/main/java/com/battlelancer/seriesguide/traktapi/BaseOAuthActivity.kt | 1 | 7455 | package com.battlelancer.seriesguide.traktapi
import android.annotation.SuppressLint
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.view.LayoutInflater
import android.view.MenuItem
import android.view.View
import android.webkit.CookieManager
import android.webkit.WebView
import android.webkit.WebViewClient
import android.widget.Button
import android.widget.FrameLayout
import android.widget.TextView
import com.battlelancer.seriesguide.R
import com.battlelancer.seriesguide.ui.BaseActivity
import com.battlelancer.seriesguide.util.Errors.Companion.logAndReportNoBend
import com.battlelancer.seriesguide.util.Utils
import timber.log.Timber
/**
* Base class to create an OAuth 2.0 authorization flow using the browser, offering fallback to an
* embedded [android.webkit.WebView].
*/
abstract class BaseOAuthActivity : BaseActivity() {
private var webview: WebView? = null
private lateinit var buttonContainer: View
private lateinit var progressBar: View
private lateinit var textViewMessage: TextView
public override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_oauth)
setupActionBar()
bindViews()
if (handleAuthIntent(intent)) {
return
}
val isRetry = intent.getBooleanExtra(EXTRA_KEY_IS_RETRY, false)
if (isRetry) {
setMessage(authErrorMessage)
}
if (savedInstanceState == null && !isRetry) {
// try to launch external browser with OAuth page
launchBrowser()
}
}
override fun setupActionBar() {
super.setupActionBar()
supportActionBar?.setDisplayHomeAsUpEnabled(true)
}
private fun bindViews() {
buttonContainer = findViewById(R.id.containerOauthButtons)
progressBar = findViewById(R.id.progressBarOauth)
textViewMessage = buttonContainer.findViewById(R.id.textViewOauthMessage)
// set up buttons (can be used if browser launch fails or user comes back without code)
findViewById<Button>(R.id.buttonOauthBrowser).setOnClickListener { launchBrowser() }
findViewById<Button>(R.id.buttonOauthWebView).setOnClickListener { activateWebView() }
activateFallbackButtons()
setMessage(null)
}
private fun launchBrowser() {
val authorizationUrl = authorizationUrl
if (authorizationUrl != null) {
Utils.launchWebsite(this, authorizationUrl)
}
}
override fun onNewIntent(intent: Intent) {
super.onNewIntent(intent)
handleAuthIntent(intent)
}
private fun handleAuthIntent(intent: Intent): Boolean {
// handle auth callback from external browser
val callbackUri = intent.data
if (callbackUri == null || OAUTH_URI_SCHEME != callbackUri.scheme) {
return false
}
fetchTokensAndFinish(
callbackUri.getQueryParameter("code"),
callbackUri.getQueryParameter("state")
)
return true
}
protected fun activateFallbackButtons() {
buttonContainer.visibility = View.VISIBLE
webview?.visibility = View.GONE
}
@SuppressLint("SetJavaScriptEnabled")
protected fun activateWebView() {
buttonContainer.visibility = View.GONE
// Inflate the WebView on demand.
val webview = findViewById(R.id.webView)
?: try {
val container = findViewById<FrameLayout>(R.id.frameLayoutOauth)
LayoutInflater.from(container.context)
.inflate(R.layout.view_webview, container, true)
findViewById<WebView>(R.id.webView)
} catch (e: Exception) {
// There are various crashes where inflating fails due to a
// "Failed to load WebView provider: No WebView installed" exception.
// The most reasonable explanation is that the WebView is getting updated right
// when we want to inflate it.
// So just finish the activity and make the user open it again.
logAndReportNoBend("Inflate WebView", e)
finish()
return
}
this.webview = webview
webview.also {
it.visibility = View.VISIBLE
it.webViewClient = webViewClient
it.settings.javaScriptEnabled = true
}
// Clear all previous sign-in state.
val cookieManager = CookieManager.getInstance()
cookieManager.removeAllCookies(null)
webview.clearCache(true)
// Load the authorization page.
Timber.d("Initiating authorization request...")
val authUrl = authorizationUrl
if (authUrl != null) {
webview.loadUrl(authUrl)
}
}
protected fun setMessage(message: CharSequence?) {
setMessage(message, false)
}
protected fun setMessage(message: CharSequence?, progressVisible: Boolean) {
if (message == null) {
textViewMessage.visibility = View.GONE
} else {
textViewMessage.visibility = View.VISIBLE
textViewMessage.text = message
}
progressBar.visibility = if (progressVisible) View.VISIBLE else View.GONE
}
protected var webViewClient: WebViewClient = object : WebViewClient() {
override fun onReceivedError(
view: WebView, errorCode: Int, description: String,
failingUrl: String
) {
Timber.e("WebView error: %s %s", errorCode, description)
activateFallbackButtons()
setMessage("$authErrorMessage\n\n($errorCode $description)")
}
override fun shouldOverrideUrlLoading(view: WebView, url: String?): Boolean {
if (url != null && url.startsWith(OAUTH_CALLBACK_URL_CUSTOM)) {
val uri = Uri.parse(url)
fetchTokensAndFinish(uri.getQueryParameter("code"), uri.getQueryParameter("state"))
return true
}
return false
}
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
return when (item.itemId) {
android.R.id.home -> {
onBackPressedDispatcher.onBackPressed()
true
}
else -> super.onOptionsItemSelected(item)
}
}
/**
* Return the url of the OAuth authorization page.
*/
protected abstract val authorizationUrl: String?
/**
* Return an error message displayed if authorization fails at any point.
*/
protected abstract val authErrorMessage: String
/**
* Called with the OAuth auth code and state retrieved from the [authorizationUrl]
* once the user has authorized us. If state was sent, ensure it matches. Then retrieve the
* OAuth tokens with the auth code.
*/
protected abstract fun fetchTokensAndFinish(authCode: String?, state: String?)
companion object {
/** Pass with true to not auto launch the external browser, display default error message. */
const val EXTRA_KEY_IS_RETRY = "isRetry"
/** Needs to match with the scheme registered in the manifest. */
private const val OAUTH_URI_SCHEME = "sgoauth"
const val OAUTH_CALLBACK_URL_CUSTOM = "$OAUTH_URI_SCHEME://callback"
}
} | apache-2.0 | f1ad0999adfa6b9a1a53e660bc4cef68 | 34.004695 | 101 | 0.647351 | 5.198745 | false | false | false | false |
UweTrottmann/SeriesGuide | app/src/main/java/com/battlelancer/seriesguide/movies/details/MovieDetailsFragment.kt | 1 | 33111 | package com.battlelancer.seriesguide.movies.details
import android.content.Context
import android.graphics.Color
import android.graphics.drawable.BitmapDrawable
import android.graphics.drawable.ColorDrawable
import android.os.Bundle
import android.view.LayoutInflater
import android.view.Menu
import android.view.MenuInflater
import android.view.MenuItem
import android.view.View
import android.view.ViewGroup
import android.widget.PopupMenu
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.widget.TooltipCompat
import androidx.collection.SparseArrayCompat
import androidx.core.content.ContextCompat
import androidx.core.graphics.ColorUtils
import androidx.core.view.MenuProvider
import androidx.core.view.isGone
import androidx.core.widget.NestedScrollView
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.lifecycleScope
import androidx.loader.app.LoaderManager
import androidx.loader.content.Loader
import androidx.palette.graphics.Palette
import com.battlelancer.seriesguide.R
import com.battlelancer.seriesguide.backend.settings.HexagonSettings
import com.battlelancer.seriesguide.comments.TraktCommentsActivity
import com.battlelancer.seriesguide.databinding.FragmentMovieBinding
import com.battlelancer.seriesguide.extensions.ActionsHelper
import com.battlelancer.seriesguide.extensions.ExtensionManager
import com.battlelancer.seriesguide.extensions.MovieActionsContract
import com.battlelancer.seriesguide.movies.MovieLoader
import com.battlelancer.seriesguide.movies.MovieLocalizationDialogFragment
import com.battlelancer.seriesguide.movies.MoviesSettings
import com.battlelancer.seriesguide.movies.tools.MovieTools
import com.battlelancer.seriesguide.people.PeopleListHelper
import com.battlelancer.seriesguide.settings.TmdbSettings
import com.battlelancer.seriesguide.streaming.StreamingSearch
import com.battlelancer.seriesguide.tmdbapi.TmdbTools
import com.battlelancer.seriesguide.traktapi.MovieCheckInDialogFragment
import com.battlelancer.seriesguide.traktapi.RateDialogFragment
import com.battlelancer.seriesguide.traktapi.TraktCredentials
import com.battlelancer.seriesguide.traktapi.TraktTools
import com.battlelancer.seriesguide.ui.BaseMessageActivity
import com.battlelancer.seriesguide.ui.FullscreenImageActivity
import com.battlelancer.seriesguide.util.LanguageTools
import com.battlelancer.seriesguide.util.Metacritic
import com.battlelancer.seriesguide.util.ServiceUtils
import com.battlelancer.seriesguide.util.ShareUtils
import com.battlelancer.seriesguide.util.TextTools
import com.battlelancer.seriesguide.util.TimeTools
import com.battlelancer.seriesguide.util.Utils
import com.battlelancer.seriesguide.util.ViewTools
import com.battlelancer.seriesguide.util.copyTextToClipboardOnLongClick
import com.squareup.picasso.Callback
import com.squareup.picasso.Picasso
import com.uwetrottmann.androidutils.AndroidUtils
import com.uwetrottmann.tmdb2.entities.Credits
import com.uwetrottmann.tmdb2.entities.Videos
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import timber.log.Timber
/**
* Displays details about one movie including plot, ratings, trailers and a poster.
*/
class MovieDetailsFragment : Fragment(), MovieActionsContract {
private var _binding: FragmentMovieBinding? = null
private val binding get() = _binding!!
private var tmdbId: Int = 0
private var movieDetails: MovieDetails? =
MovieDetails()
private var movieTitle: String? = null
private var trailer: Videos.Video? = null
private val model: MovieDetailsModel by viewModels {
MovieDetailsModelFactory(tmdbId, requireActivity().application)
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
_binding = FragmentMovieBinding.inflate(inflater, container, false)
val view = binding.root
binding.progressBar.isGone = true
binding.textViewMovieGenresLabel.isGone = true
binding.labelMovieLastUpdated.isGone = true
// trailer button
binding.buttonMovieTrailer.setOnClickListener {
trailer?.let { ServiceUtils.openYoutube(it.key, activity) }
}
binding.buttonMovieTrailer.isGone = true
binding.buttonMovieTrailer.isEnabled = false
// important action buttons
binding.containerMovieButtons.root.isGone = true
binding.containerMovieButtons.buttonMovieCheckIn.setOnClickListener { onButtonCheckInClick() }
StreamingSearch.initButtons(
binding.containerMovieButtons.buttonMovieStreamingSearch,
binding.containerMovieButtons.buttonMovieStreamingSearchInfo,
parentFragmentManager
)
binding.containerRatings.root.isGone = true
TooltipCompat.setTooltipText(
binding.containerMovieButtons.buttonMovieCheckIn,
binding.containerMovieButtons.buttonMovieCheckIn.contentDescription
)
// language button
binding.buttonMovieLanguage.isGone = true
TooltipCompat.setTooltipText(
binding.buttonMovieLanguage,
binding.buttonMovieLanguage.context.getString(R.string.pref_language)
)
binding.buttonMovieLanguage.setOnClickListener {
MovieLocalizationDialogFragment.show(parentFragmentManager)
}
// comments button
binding.buttonMovieComments.isGone = true
// cast and crew
setCastVisibility(false)
setCrewVisibility(false)
// set up long-press to copy text to clipboard (d-pad friendly vs text selection)
binding.textViewMovieTitle.copyTextToClipboardOnLongClick()
binding.textViewMovieDate.copyTextToClipboardOnLongClick()
binding.textViewMovieDescription.copyTextToClipboardOnLongClick()
binding.textViewMovieGenres.copyTextToClipboardOnLongClick()
return view
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
tmdbId = requireArguments().getInt(ARG_TMDB_ID)
if (tmdbId <= 0) {
parentFragmentManager.popBackStack()
return
}
setupViews()
val args = Bundle()
args.putInt(ARG_TMDB_ID, tmdbId)
LoaderManager.getInstance(this).apply {
initLoader(MovieDetailsActivity.LOADER_ID_MOVIE, args, movieLoaderCallbacks)
initLoader(
MovieDetailsActivity.LOADER_ID_MOVIE_TRAILERS, args, trailerLoaderCallbacks
)
}
model.credits.observe(viewLifecycleOwner) {
populateMovieCreditsViews(it)
}
model.watchProvider.observe(viewLifecycleOwner) { watchInfo ->
StreamingSearch.configureButton(
binding.containerMovieButtons.buttonMovieStreamingSearch,
watchInfo
)
}
requireActivity().addMenuProvider(
optionsMenuProvider,
viewLifecycleOwner,
Lifecycle.State.RESUMED
)
}
private fun setupViews() {
// avoid overlap with status + action bar (adjust top margin)
// warning: pre-M status bar not always translucent (e.g. Nexus 10)
// (using fitsSystemWindows would not work correctly with multiple views)
val config = (activity as MovieDetailsActivity).systemBarTintManager.config
val pixelInsetTop = if (AndroidUtils.isMarshmallowOrHigher) {
config.statusBarHeight // full screen, status bar transparent
} else {
config.getPixelInsetTop(false) // status bar translucent
}
// action bar height is pre-set as top margin, add to it
val decorationHeightPx = pixelInsetTop + binding.contentContainerMovie.paddingTop
binding.contentContainerMovie.setPadding(0, decorationHeightPx, 0, 0)
// dual pane layout?
binding.contentContainerMovieRight?.setPadding(0, decorationHeightPx, 0, 0)
// show toolbar title and background when scrolling
val defaultPaddingPx = resources.getDimensionPixelSize(R.dimen.default_padding)
val scrollChangeListener = ToolbarScrollChangeListener(defaultPaddingPx, decorationHeightPx)
binding.contentContainerMovie.setOnScrollChangeListener(scrollChangeListener)
binding.contentContainerMovieRight?.setOnScrollChangeListener(scrollChangeListener)
}
override fun onStart() {
super.onStart()
val event = EventBus.getDefault()
.getStickyEvent(BaseMessageActivity.ServiceActiveEvent::class.java)
setMovieButtonsEnabled(event == null)
EventBus.getDefault().register(this)
}
override fun onResume() {
super.onResume()
// refresh actions when returning, enabled extensions or their actions might have changed
loadMovieActionsDelayed()
}
override fun onStop() {
super.onStop()
EventBus.getDefault().unregister(this)
}
override fun onDestroyView() {
super.onDestroyView()
// Always cancel the request here, this is safe to call even if the image has been loaded.
// This ensures that the anonymous callback we have does not prevent the fragment from
// being garbage collected. It also prevents our callback from getting invoked even after the
// fragment is destroyed.
Picasso.get().cancelRequest(binding.imageViewMoviePoster)
_binding = null
}
private val optionsMenuProvider = object : MenuProvider {
override fun onCreateMenu(menu: Menu, menuInflater: MenuInflater) {
movieDetails?.let {
menuInflater.inflate(R.menu.movie_details_menu, menu)
// enable/disable actions
val hasTitle = !it.tmdbMovie()?.title.isNullOrEmpty()
menu.findItem(R.id.menu_movie_share).apply {
isEnabled = hasTitle
isVisible = hasTitle
}
menu.findItem(R.id.menu_open_metacritic).apply {
isEnabled = hasTitle
isVisible = hasTitle
}
val isEnableImdb = !it.tmdbMovie()?.imdb_id.isNullOrEmpty()
menu.findItem(R.id.menu_open_imdb).apply {
isEnabled = isEnableImdb
isVisible = isEnableImdb
}
}
}
override fun onMenuItemSelected(menuItem: MenuItem): Boolean {
return when (menuItem.itemId) {
R.id.menu_movie_share -> {
movieDetails?.tmdbMovie()
?.title
?.let { ShareUtils.shareMovie(activity, tmdbId, it) }
true
}
R.id.menu_open_imdb -> {
movieDetails?.tmdbMovie()
?.let { ServiceUtils.openImdb(it.imdb_id, activity) }
true
}
R.id.menu_open_metacritic -> {
// Metacritic only has English titles, so using the original title is the best bet.
val titleOrNull = movieDetails?.tmdbMovie()
?.let { it.original_title ?: it.title }
titleOrNull?.let { Metacritic.searchForMovie(requireContext(), it) }
true
}
R.id.menu_open_tmdb -> {
TmdbTools.openTmdbMovie(activity, tmdbId)
true
}
R.id.menu_open_trakt -> {
Utils.launchWebsite(activity, TraktTools.buildMovieUrl(tmdbId))
true
}
else -> false
}
}
}
private fun populateMovieViews() {
val movieDetails = this.movieDetails ?: return
/*
Get everything from TMDb. Also get additional rating from trakt.
*/
val tmdbMovie = movieDetails.tmdbMovie() ?: return
val traktRatings = movieDetails.traktRatings()
val inCollection = movieDetails.isInCollection
val inWatchlist = movieDetails.isInWatchlist
val isWatched = movieDetails.isWatched
val plays = movieDetails.plays
val rating = movieDetails.userRating
movieTitle = tmdbMovie.title
binding.textViewMovieTitle.text = tmdbMovie.title
requireActivity().title = tmdbMovie.title
binding.textViewMovieDescription.text = TextTools.textWithTmdbSource(
binding.textViewMovieDescription.context,
tmdbMovie.overview
)
// release date and runtime: "July 17, 2009 | 95 min"
val releaseAndRuntime = StringBuilder()
tmdbMovie.release_date?.let {
releaseAndRuntime.append(TimeTools.formatToLocalDate(context, it))
releaseAndRuntime.append(" | ")
}
tmdbMovie.runtime?.let {
releaseAndRuntime.append(getString(R.string.runtime_minutes, it.toString()))
}
binding.textViewMovieDate.text = releaseAndRuntime.toString()
// show trailer button (but trailer is loaded separately, just for animation)
binding.buttonMovieTrailer.isGone = false
// hide check-in if not connected to trakt or hexagon is enabled
val isConnectedToTrakt = TraktCredentials.get(requireContext()).hasCredentials()
val hideCheckIn = !isConnectedToTrakt || HexagonSettings.isEnabled(requireContext())
binding.containerMovieButtons.buttonMovieCheckIn.isGone = hideCheckIn
// watched button
binding.containerMovieButtons.buttonMovieWatched.also {
it.text = TextTools.getWatchedButtonText(requireContext(), isWatched, plays)
TooltipCompat.setTooltipText(
it, it.context.getString(
if (isWatched) R.string.action_unwatched else R.string.action_watched
)
)
if (isWatched) {
ViewTools.setVectorDrawableTop(it, R.drawable.ic_watched_24dp)
} else {
ViewTools.setVectorDrawableTop(it, R.drawable.ic_watch_black_24dp)
}
it.setOnClickListener { view ->
if (isWatched) {
PopupMenu(view.context, view)
.apply {
inflate(R.menu.watched_popup_menu)
setOnMenuItemClickListener(
WatchedPopupMenuListener(
requireContext(),
tmdbId,
plays,
inWatchlist
)
)
}
.show()
} else {
MovieTools.watchedMovie(context, tmdbId, plays, inWatchlist)
}
}
}
// collected button
binding.containerMovieButtons.buttonMovieCollected.also {
if (inCollection) {
ViewTools.setVectorDrawableTop(it, R.drawable.ic_collected_24dp)
} else {
ViewTools.setVectorDrawableTop(it, R.drawable.ic_collect_black_24dp)
}
it.setText(
if (inCollection) R.string.state_in_collection else R.string.action_collection_add
)
TooltipCompat.setTooltipText(
it,
it.context.getString(
if (inCollection) R.string.action_collection_remove else R.string.action_collection_add
)
)
it.setOnClickListener {
if (inCollection) {
MovieTools.removeFromCollection(context, tmdbId)
} else {
MovieTools.addToCollection(context, tmdbId)
}
}
}
// watchlist button
binding.containerMovieButtons.buttonMovieWatchlisted.also {
if (inWatchlist) {
ViewTools.setVectorDrawableTop(it, R.drawable.ic_list_added_24dp)
} else {
ViewTools.setVectorDrawableTop(it, R.drawable.ic_list_add_white_24dp)
}
it.setText(
if (inWatchlist) R.string.state_on_watchlist else R.string.watchlist_add
)
TooltipCompat.setTooltipText(
it, it.context.getString(
if (inWatchlist) R.string.watchlist_remove else R.string.watchlist_add
)
)
it.setOnClickListener {
if (inWatchlist) {
MovieTools.removeFromWatchlist(context, tmdbId)
} else {
MovieTools.addToWatchlist(context, tmdbId)
}
}
}
// show button bar
binding.containerMovieButtons.root.isGone = false
// language button
binding.buttonMovieLanguage.also {
it.text = LanguageTools.getMovieLanguageStringFor(
requireContext(),
null,
MoviesSettings.getMoviesLanguage(requireContext())
)
it.isGone = false
}
// ratings
binding.containerRatings.textViewRatingsTmdbValue.text = TraktTools.buildRatingString(
tmdbMovie.vote_average
)
binding.containerRatings.textViewRatingsTmdbVotes.text =
TraktTools.buildRatingVotesString(activity, tmdbMovie.vote_count)
traktRatings?.let {
binding.containerRatings.textViewRatingsTraktVotes.text =
TraktTools.buildRatingVotesString(activity, it.votes)
binding.containerRatings.textViewRatingsTraktValue.text = TraktTools.buildRatingString(
it.rating
)
}
// if movie is not in database, can't handle user ratings
if (!inCollection && !inWatchlist && !isWatched) {
binding.containerRatings.textViewRatingsTraktUserLabel.isGone = true
binding.containerRatings.textViewRatingsTraktUser.isGone = true
binding.containerRatings.root.isClickable = false
binding.containerRatings.root.isLongClickable = false // cheat sheet
} else {
binding.containerRatings.textViewRatingsTraktUserLabel.isGone = false
binding.containerRatings.textViewRatingsTraktUser.isGone = false
binding.containerRatings.textViewRatingsTraktUser.text =
TraktTools.buildUserRatingString(
activity,
rating
)
binding.containerRatings.root.setOnClickListener { rateMovie() }
TooltipCompat.setTooltipText(
binding.containerRatings.root,
binding.containerRatings.root.context.getString(R.string.action_rate)
)
}
binding.containerRatings.root.isGone = false
// genres
binding.textViewMovieGenresLabel.isGone = false
ViewTools.setValueOrPlaceholder(
binding.textViewMovieGenres, TmdbTools.buildGenresString(tmdbMovie.genres)
)
// When this movie was last updated by this app
binding.labelMovieLastUpdated.isGone = false
binding.textMovieLastUpdated.text =
TextTools.timeInMillisToDateAndTime(requireContext(), movieDetails.lastUpdatedMillis)
// trakt comments link
binding.buttonMovieComments.setOnClickListener { v ->
val i = TraktCommentsActivity.intentMovie(requireContext(), movieTitle, tmdbId)
Utils.startActivityWithAnimation(activity, i, v)
}
binding.buttonMovieComments.isGone = false
// load poster, cache on external storage
if (tmdbMovie.poster_path.isNullOrEmpty()) {
binding.frameLayoutMoviePoster.isClickable = false
binding.frameLayoutMoviePoster.isFocusable = false
} else {
val smallImageUrl = (TmdbSettings.getImageBaseUrl(activity)
+ TmdbSettings.POSTER_SIZE_SPEC_W342 + tmdbMovie.poster_path)
ServiceUtils.loadWithPicasso(activity, smallImageUrl)
.into(binding.imageViewMoviePoster, object : Callback.EmptyCallback() {
override fun onSuccess() {
viewLifecycleOwner.lifecycleScope.launch {
val bitmap =
(binding.imageViewMoviePoster.drawable as BitmapDrawable).bitmap
val color = withContext(Dispatchers.Default) {
val palette = try {
Palette.from(bitmap).generate()
} catch (e: Exception) {
Timber.e(e, "Failed to generate palette.")
null
}
palette
?.getVibrantColor(Color.WHITE)
?.let { ColorUtils.setAlphaComponent(it, 50) }
}
color?.let { binding.rootLayoutMovie.setBackgroundColor(it) }
}
}
})
// click listener for high resolution poster
binding.frameLayoutMoviePoster.also {
it.isFocusable = true
it.setOnClickListener { view ->
val largeImageUrl =
TmdbSettings.getImageOriginalUrl(activity, tmdbMovie.poster_path)
val intent = FullscreenImageActivity.intent(
requireActivity(),
smallImageUrl,
largeImageUrl
)
Utils.startActivityWithAnimation(activity, intent, view)
}
}
}
}
/**
* Menu click listener to watch again (supporters only) or set unwatched.
*/
private class WatchedPopupMenuListener(
val context: Context,
val movieTmdbId: Int,
val plays: Int,
val inWatchlist: Boolean
) : PopupMenu.OnMenuItemClickListener {
override fun onMenuItemClick(item: MenuItem): Boolean {
when (item.itemId) {
R.id.watched_popup_menu_watch_again -> if (Utils.hasAccessToX(context)) {
MovieTools.watchedMovie(context, movieTmdbId, plays, inWatchlist)
} else {
Utils.advertiseSubscription(context)
}
R.id.watched_popup_menu_set_not_watched -> MovieTools.unwatchedMovie(
context,
movieTmdbId
)
}
return true
}
}
private fun populateMovieCreditsViews(credits: Credits?) {
if (credits == null) {
setCastVisibility(false)
setCrewVisibility(false)
return
}
// cast members
if (credits.cast?.size != 0
&& PeopleListHelper.populateMovieCast(
activity,
binding.moviePeople.containerCast,
credits
)) {
setCastVisibility(true)
} else {
setCastVisibility(false)
}
// crew members
if (credits.crew?.size != 0
&& PeopleListHelper.populateMovieCrew(
activity,
binding.moviePeople.containerCrew,
credits
)) {
setCrewVisibility(true)
} else {
setCrewVisibility(false)
}
}
private fun onButtonCheckInClick() {
movieTitle?.let {
if (it.isEmpty()) {
return
}
MovieCheckInDialogFragment.show(parentFragmentManager, tmdbId, it)
}
}
@Subscribe(threadMode = ThreadMode.MAIN)
override fun onEventMainThread(event: ExtensionManager.MovieActionReceivedEvent) {
if (event.movieTmdbId != tmdbId) {
return
}
loadMovieActionsDelayed()
}
@Subscribe(threadMode = ThreadMode.MAIN)
fun onEvent(event: MovieTools.MovieChangedEvent) {
if (event.movieTmdbId != tmdbId) {
return
}
// re-query to update movie details
restartMovieLoader()
}
@Subscribe(threadMode = ThreadMode.MAIN)
fun onEventEpisodeTask(@Suppress("UNUSED_PARAMETER") event: BaseMessageActivity.ServiceActiveEvent) {
setMovieButtonsEnabled(false)
}
@Subscribe(threadMode = ThreadMode.MAIN)
fun onEventEpisodeTask(@Suppress("UNUSED_PARAMETER") event: BaseMessageActivity.ServiceCompletedEvent) {
setMovieButtonsEnabled(true)
}
private fun setMovieButtonsEnabled(enabled: Boolean) {
binding.containerMovieButtons.apply {
buttonMovieCheckIn.isEnabled = enabled
buttonMovieWatched.isEnabled = enabled
buttonMovieCollected.isEnabled = enabled
buttonMovieWatchlisted.isEnabled = enabled
}
}
@Subscribe(threadMode = ThreadMode.MAIN)
fun handleLanguageEvent(@Suppress("UNUSED_PARAMETER") event: MovieLocalizationDialogFragment.LocalizationChangedEvent) {
// reload movie details and trailers (but not cast/crew info which is not language dependent)
restartMovieLoader()
val args = Bundle().apply {
putInt(ARG_TMDB_ID, tmdbId)
}
LoaderManager.getInstance(this).restartLoader(
MovieDetailsActivity.LOADER_ID_MOVIE_TRAILERS, args, trailerLoaderCallbacks
)
}
override fun loadMovieActions() {
var actions = ExtensionManager.get(context)
.getLatestMovieActions(context, tmdbId)
// no actions available yet, request extensions to publish them
if (actions == null || actions.size == 0) {
actions = ArrayList()
movieDetails?.tmdbMovie()?.let {
val movie = com.battlelancer.seriesguide.api.Movie.Builder()
.tmdbId(tmdbId)
.imdbId(it.imdb_id)
.title(it.title)
.releaseDate(it.release_date)
.build()
ExtensionManager.get(context).requestMovieActions(context, movie)
}
}
Timber.d("loadMovieActions: received %s actions for %s", actions.size, tmdbId)
requireActivity().run {
ActionsHelper.populateActions(
layoutInflater, theme, binding.containerMovieActions, actions
)
}
}
private var loadActionsJob: Job? = null
override fun loadMovieActionsDelayed() {
// Simple de-bounce: cancel any waiting job.
loadActionsJob?.cancel()
loadActionsJob = lifecycleScope.launch {
delay(MovieActionsContract.ACTION_LOADER_DELAY_MILLIS.toLong())
loadMovieActions()
}
}
private fun rateMovie() {
RateDialogFragment.newInstanceMovie(tmdbId).safeShow(context, parentFragmentManager)
}
private fun setCrewVisibility(visible: Boolean) {
binding.moviePeople.labelCrew.isGone = !visible
binding.moviePeople.containerCrew.isGone = !visible
}
private fun setCastVisibility(visible: Boolean) {
binding.moviePeople.labelCast.isGone = !visible
binding.moviePeople.containerCast.isGone = !visible
}
private fun restartMovieLoader() {
val args = Bundle()
args.putInt(ARG_TMDB_ID, tmdbId)
LoaderManager.getInstance(this)
.restartLoader(MovieDetailsActivity.LOADER_ID_MOVIE, args, movieLoaderCallbacks)
}
private val movieLoaderCallbacks = object : LoaderManager.LoaderCallbacks<MovieDetails> {
override fun onCreateLoader(loaderId: Int, args: Bundle?): Loader<MovieDetails> {
binding.progressBar.isGone = false
return MovieLoader(requireContext(), args!!.getInt(ARG_TMDB_ID))
}
override fun onLoadFinished(movieLoader: Loader<MovieDetails>, movieDetails: MovieDetails) {
if (!isAdded) {
return
}
[email protected] = movieDetails
binding.progressBar.isGone = true
// we need at least values from database or tmdb
if (movieDetails.tmdbMovie() != null) {
populateMovieViews()
loadMovieActions()
activity!!.invalidateOptionsMenu()
} else {
// if there is no local data and loading from network failed
binding.textViewMovieDescription.text =
if (AndroidUtils.isNetworkConnected(requireContext())) {
getString(R.string.api_error_generic, getString(R.string.tmdb))
} else {
getString(R.string.offline)
}
}
}
override fun onLoaderReset(movieLoader: Loader<MovieDetails>) {
// nothing to do
}
}
private val trailerLoaderCallbacks = object : LoaderManager.LoaderCallbacks<Videos.Video> {
override fun onCreateLoader(loaderId: Int, args: Bundle?): Loader<Videos.Video> {
return MovieTrailersLoader(
context,
args!!.getInt(ARG_TMDB_ID)
)
}
override fun onLoadFinished(
trailersLoader: Loader<Videos.Video>,
trailer: Videos.Video?
) {
if (!isAdded) {
return
}
if (trailer != null) {
[email protected] = trailer
binding.buttonMovieTrailer.isEnabled = true
}
}
override fun onLoaderReset(trailersLoader: Loader<Videos.Video>) {
// do nothing
}
}
private inner class ToolbarScrollChangeListener(
private val overlayThresholdPx: Int,
private val titleThresholdPx: Int
) : NestedScrollView.OnScrollChangeListener {
// we have determined by science that a capacity of 2 is good in our case :)
private val showOverlayMap: SparseArrayCompat<Boolean> = SparseArrayCompat(2)
private var showOverlay: Boolean = false
private var showTitle: Boolean = false
override fun onScrollChange(
v: NestedScrollView, scrollX: Int, scrollY: Int, oldScrollX: Int, oldScrollY: Int
) {
val actionBar = (activity as AppCompatActivity?)?.supportActionBar ?: return
val viewId = v.id
var shouldShowOverlayTemp = scrollY > overlayThresholdPx
showOverlayMap.put(viewId, shouldShowOverlayTemp)
for (i in 0 until showOverlayMap.size()) {
shouldShowOverlayTemp = shouldShowOverlayTemp or showOverlayMap.valueAt(i)
}
val shouldShowOverlay = shouldShowOverlayTemp
if (!showOverlay && shouldShowOverlay) {
val primaryColor = ContextCompat.getColor(
v.context,
Utils.resolveAttributeToResourceId(
v.context.theme, R.attr.sgColorStatusBarOverlay
)
)
actionBar.setBackgroundDrawable(ColorDrawable(primaryColor))
} else if (showOverlay && !shouldShowOverlay) {
actionBar.setBackgroundDrawable(null)
}
showOverlay = shouldShowOverlay
// only main container should show/hide title
if (viewId == R.id.contentContainerMovie) {
val shouldShowTitle = scrollY > titleThresholdPx
if (!showTitle && shouldShowTitle) {
movieDetails?.tmdbMovie()?.let {
actionBar.title = it.title
actionBar.setDisplayShowTitleEnabled(true)
}
} else if (showTitle && !shouldShowTitle) {
actionBar.setDisplayShowTitleEnabled(false)
}
showTitle = shouldShowTitle
}
}
}
companion object {
const val ARG_TMDB_ID = "tmdbid"
@JvmStatic
fun newInstance(tmdbId: Int): MovieDetailsFragment {
return MovieDetailsFragment().apply {
arguments = Bundle().apply {
putInt(ARG_TMDB_ID, tmdbId)
}
}
}
}
}
| apache-2.0 | d45f76d3e622b7f646602f7c680823af | 38.464839 | 124 | 0.61762 | 5.63208 | false | false | false | false |
premnirmal/StockTicker | app/src/main/kotlin/com/github/premnirmal/ticker/portfolio/drag_drop/SimpleItemTouchHelperCallback.kt | 1 | 3123 | package com.github.premnirmal.ticker.portfolio.drag_drop
import android.graphics.Canvas
import androidx.recyclerview.widget.ItemTouchHelper
/**
* Created by premnirmal on 2/29/16.
*/
internal class SimpleItemTouchHelperCallback(private val adapter: ItemTouchHelperAdapter) :
ItemTouchHelper.Callback() {
companion object {
const val ALPHA_FULL: Float = 1.0f
}
override fun isLongPressDragEnabled(): Boolean = true
override fun isItemViewSwipeEnabled(): Boolean = true
override fun getMovementFlags(
recyclerView: androidx.recyclerview.widget.RecyclerView,
viewHolder: androidx.recyclerview.widget.RecyclerView.ViewHolder
): Int {
return if (recyclerView.layoutManager is androidx.recyclerview.widget.GridLayoutManager) {
val dragFlags: Int =
ItemTouchHelper.UP or (ItemTouchHelper.DOWN) or (ItemTouchHelper.LEFT) or (ItemTouchHelper.RIGHT)
val swipeFlags = 0
makeMovementFlags(dragFlags, swipeFlags)
} else {
val dragFlags: Int = ItemTouchHelper.UP or (ItemTouchHelper.DOWN)
val swipeFlags: Int = ItemTouchHelper.START or (ItemTouchHelper.END)
makeMovementFlags(dragFlags, swipeFlags)
}
}
override fun onMove(
recyclerView: androidx.recyclerview.widget.RecyclerView,
source: androidx.recyclerview.widget.RecyclerView.ViewHolder,
target: androidx.recyclerview.widget.RecyclerView.ViewHolder
): Boolean {
adapter.onItemMove(source.adapterPosition, target.adapterPosition)
return true
}
override fun onSwiped(
viewHolder: androidx.recyclerview.widget.RecyclerView.ViewHolder,
i: Int
) {
}
override fun onChildDraw(
c: Canvas,
recyclerView: androidx.recyclerview.widget.RecyclerView,
viewHolder: androidx.recyclerview.widget.RecyclerView.ViewHolder,
dX: Float,
dY: Float,
actionState: Int,
isCurrentlyActive: Boolean
) {
if (actionState == ItemTouchHelper.ACTION_STATE_SWIPE) {
val alpha: Float = ALPHA_FULL - Math.abs(dX) / viewHolder.itemView.width
viewHolder.itemView.alpha = alpha
viewHolder.itemView.translationX = dX
} else {
super.onChildDraw(c, recyclerView, viewHolder, dX, dY, actionState, isCurrentlyActive)
}
}
override fun onSelectedChanged(
viewHolder: androidx.recyclerview.widget.RecyclerView.ViewHolder?,
actionState: Int
) {
if (actionState != ItemTouchHelper.ACTION_STATE_IDLE) {
if (viewHolder is ItemTouchHelperViewHolder) {
val itemViewHolder = viewHolder as ItemTouchHelperViewHolder
itemViewHolder.onItemSelected()
}
}
super.onSelectedChanged(viewHolder, actionState)
}
override fun clearView(
recyclerView: androidx.recyclerview.widget.RecyclerView,
viewHolder: androidx.recyclerview.widget.RecyclerView.ViewHolder
) {
super.clearView(recyclerView, viewHolder)
viewHolder.itemView.alpha = ALPHA_FULL
if (viewHolder is ItemTouchHelperViewHolder) {
val itemViewHolder = viewHolder as ItemTouchHelperViewHolder
itemViewHolder.onItemClear()
}
adapter.onItemDismiss(viewHolder.adapterPosition)
}
} | gpl-3.0 | 8bf4a050e4b89c7e7f3d6000bc10e9bf | 31.884211 | 105 | 0.740314 | 4.9968 | false | false | false | false |
commons-app/apps-android-commons | app/src/test/kotlin/fr/free/nrw/commons/quiz/QuizResultActivityUnitTest.kt | 6 | 2218 | package fr.free.nrw.commons.quiz
import android.content.Intent
import android.graphics.Bitmap
import fr.free.nrw.commons.TestCommonsApplication
import org.junit.Assert
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.Mock
import org.mockito.Mockito
import org.mockito.MockitoAnnotations
import org.powermock.api.mockito.PowerMockito
import org.robolectric.Robolectric
import org.robolectric.RobolectricTestRunner
import org.robolectric.annotation.Config
import org.robolectric.fakes.RoboMenu
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [21], application = TestCommonsApplication::class)
class QuizResultActivityUnitTest {
private lateinit var activity: QuizResultActivity
private lateinit var quizResultActivity: QuizResultActivity
private lateinit var menu: RoboMenu
@Mock
private lateinit var bitmap: Bitmap
@Before
fun setUp() {
MockitoAnnotations.initMocks(this)
val intent = Intent().putExtra("QuizResult", 0)
activity = Robolectric.buildActivity(QuizResultActivity::class.java, intent).get()
quizResultActivity = PowerMockito.mock(QuizResultActivity::class.java)
}
@Test
@Throws(Exception::class)
fun checkActivityNotNull() {
Assert.assertNotNull(activity)
}
@Test
@Throws(Exception::class)
fun testOnCreateCaseDefault() {
activity.onCreate(null)
}
@Test
@Throws(Exception::class)
fun testOnCreate() {
Mockito.`when`(quizResultActivity.intent).thenReturn(null)
activity.onCreate(null)
}
@Test
@Throws(Exception::class)
fun testLaunchContributionActivity() {
activity.launchContributionActivity()
}
@Test
@Throws(Exception::class)
fun tesOnBackPressed() {
activity.onBackPressed()
}
@Test
@Throws(Exception::class)
fun tesOnCreateOptionsMenu() {
menu = RoboMenu()
activity.onCreateOptionsMenu(menu)
}
@Test
@Throws(Exception::class)
fun tesShowAlert() {
activity.showAlert(bitmap)
}
@Test
@Throws(Exception::class)
fun tesShareScreen() {
activity.shareScreen(bitmap)
}
} | apache-2.0 | 7fdad11cec8149c786ff8ffde7548c87 | 24.215909 | 90 | 0.711001 | 4.462777 | false | true | false | false |
tbroyer/gradle-errorprone-plugin | src/test/kotlin/net/ltgt/gradle/errorprone/ManualConfigurationIntegrationTest.kt | 1 | 3475 | package net.ltgt.gradle.errorprone
import com.google.common.truth.Truth.assertThat
import org.gradle.testkit.runner.TaskOutcome
import org.junit.jupiter.api.Test
class ManualConfigurationIntegrationTest : AbstractPluginIntegrationTest() {
@Test
fun `in non-java project with applied plugin`() {
// given
buildFile.appendText(
"""
plugins {
id("${ErrorPronePlugin.PLUGIN_ID}")
`jvm-ecosystem`
}
repositories {
mavenCentral()
}
dependencies {
errorprone("com.google.errorprone:error_prone_core:$errorproneVersion")
}
val compileJava by tasks.creating(JavaCompile::class) {
source("src/main/java")
classpath = files()
destinationDir = file("${'$'}buildDir/classes")
sourceCompatibility = "8"
targetCompatibility = "8"
options.annotationProcessorPath = configurations["errorprone"]
options.errorprone {
isEnabled.set(true)
disableAllChecks.set(true)
error("ArrayEquals")
}
}
""".trimIndent()
)
testProjectDir.writeFailureSource()
// when
val result = testProjectDir.buildWithArgsAndFail("--info", "compileJava")
// then
assertThat(result.task(":compileJava")?.outcome).isEqualTo(TaskOutcome.FAILED)
assertThat(result.output).contains(FAILURE_SOURCE_COMPILATION_ERROR)
}
@Test
fun `in java project`() {
// This is similar to what the me.champeau.gradle.jmh plugin does
// given
buildFile.appendText(
"""
plugins {
java
id("${ErrorPronePlugin.PLUGIN_ID}")
}
repositories {
mavenCentral()
}
dependencies {
errorprone("com.google.errorprone:error_prone_core:$errorproneVersion")
}
val customCompileJava by tasks.creating(JavaCompile::class) {
source("src/main/java")
classpath = files()
destinationDir = file("${'$'}buildDir/classes/custom")
options.annotationProcessorPath = configurations["errorprone"]
options.errorprone {
disableAllChecks.set(true)
error("ArrayEquals")
}
}
""".trimIndent()
)
testProjectDir.writeFailureSource()
// Error Prone is disabled by default, so compilation should succeed.
// when
val result = testProjectDir.buildWithArgs("customCompileJava")
// then
assertThat(result.task(":customCompileJava")?.outcome).isEqualTo(TaskOutcome.SUCCESS)
// Now enable Error Prone and check that compilation fails.
// given
buildFile.appendText(
"""
customCompileJava.options.errorprone.isEnabled.set(true)
""".trimIndent()
)
// when
val result2 = testProjectDir.buildWithArgsAndFail("customCompileJava")
// then
assertThat(result2.task(":customCompileJava")?.outcome).isEqualTo(TaskOutcome.FAILED)
assertThat(result2.output).contains(FAILURE_SOURCE_COMPILATION_ERROR)
}
}
| apache-2.0 | db6ebe1f6ad535e7c6e283b4d7c63b00 | 30.306306 | 93 | 0.557122 | 5.56 | false | true | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.